changed range conditions
Fork of HCSR04 by
Diff: HCSR04.cpp
- Revision:
- 0:5461d44a187c
- Child:
- 1:68ad9acbec81
diff -r 000000000000 -r 5461d44a187c HCSR04.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/HCSR04.cpp Sun Nov 24 21:45:46 2013 +0000 @@ -0,0 +1,100 @@ +/* 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(); +} +