mbed device driver for HC-SR04 ultrasonic range finder

Dependents:   ROBot Ultrasonic Ksen Core1000_SmartFarm ... more

HCSR04.cpp

Committer:
rabad1
Date:
2013-11-24
Revision:
0:5461d44a187c

File content as of revision 0:5461d44a187c:

/* File: HCSR04.h
 * Author: Robert Abad  Copyright (c) 2013
 *
 * Desc: driver for HCSR04 Ultrasonic Range Finder.  See header file,
 *       HCSR04.h, for more details.
 */

#include "mbed.h"
#include "HCSR04.h"

#define SPEED_OF_SOUND      (343.2f)    // meters/sec

// HCSR04 TRIGGER pin
#define SIGNAL_HIGH     (1)
#define SIGNAL_LOW      (0)

#define TRIGGER_TIME    (10)            // microseconds


// Name: HCSR04
// Desc: HCSR04 constructor
// Inputs: PinName - pin used for trigger signal
//         PinName - pin used for echo signal
// Outputs: none
//
HCSR04::HCSR04( PinName pinTrigger, PinName pinEcho ) : 
trigger(pinTrigger),
echo(pinEcho),
measTimeStart_us(0),
measTimeStop_us(0)
{
    echo.rise( this, &HCSR04::ISR_echoRising );
    echo.fall( this, &HCSR04::ISR_echoFalling );
    echoTimer.start();
}

// Name: startMeas
// Desc: initiates range measurement driving the trigger signal HIGH then sets
//       a timer to keep trigger HIGH for the duration of TRIGGER_TIME
// Inputs: none
// Outputs: none
//
void HCSR04::startMeas(void)
{
    trigger = SIGNAL_HIGH;
    echoTimer.reset();
    triggerTicker.attach_us(this, &HCSR04::triggerTicker_cb, TRIGGER_TIME);
}
 
// Name: getMeas
// Desc: returns range measurement in meters
// Inputs: float & - reference to range measurement
// Outputs: etHCSR04 - RANGE_MEAS_VALID or RANGE_MEAS_INVALID
//
etHCSR04_RANGE_STATUS HCSR04::getMeas(float &rRangeMeters)
{
    unsigned long dTime_us;
    if ( !measTimeStart_us || !measTimeStop_us )
    {
        return RANGE_MEAS_INVALID;
    }
    
    dTime_us = measTimeStop_us - measTimeStart_us;
    rRangeMeters = (float)dTime_us / 1000000. * SPEED_OF_SOUND / 2;
    measTimeStart_us = 0;
    measTimeStop_us = 0;
    return ( RANGE_MEAS_VALID );
}

// Name: triggerTicker_cb
// Desc: Timer ticker callback function used to drive trigger signal LOW
// Inputs: none
// Outputs: none
//
void HCSR04::triggerTicker_cb(void)
{
    trigger = SIGNAL_LOW;
}


// Name: ISR_echoRising
// Desc: ISR for rising edge of HCSR04 ECHO signal
// Inputs: none
// Outputs: none
//
void HCSR04::ISR_echoRising(void)
{
    measTimeStart_us = echoTimer.read_us();
}

// Name: ISR_echoFalling
// Desc: ISR for falling edge of HCSR04 ECHO signal
// Inputs: none
// Outputs: none
//
void HCSR04::ISR_echoFalling(void)
{
    measTimeStop_us = echoTimer.read_us();
}