mbed device driver for HC-SR04 ultrasonic range finder
Dependents: TJPS UltraTest NavigationTest NavigationTest_ ... more
Fork of HCSR04 by
HCSR04.cpp
- Committer:
- srsmitherman
- Date:
- 2013-12-12
- Revision:
- 2:3ebde19131af
- Parent:
- 1:68ad9acbec81
File content as of revision 2:3ebde19131af:
/* 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" #include "stdio.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) { //printf("Start US\n\n"); echoTimer.reset(); trigger = SIGNAL_HIGH; 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) { if ( status == RANGE_MEAS_VALID) { dTime_us = measTimeStop_us - measTimeStart_us; measTimeStart_us = 0; measTimeStop_us = 0; rRangeMeters = (float)dTime_us * SPEED_OF_SOUND / 2000000.0 * MTRS_TO_INCH; status = RANGE_MEAS_INVALID; return RANGE_MEAS_VALID; }else{ return RANGE_MEAS_INVALID; } } // 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; triggerTicker.detach(); } // 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(); status = RANGE_MEAS_VALID; }