David Glover
/
HCSR04_Class
Diff: HCSR04/hcsr04.h
- Revision:
- 0:90e8d27246ad
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/HCSR04/hcsr04.h Sun Mar 18 21:00:22 2012 +0000 @@ -0,0 +1,70 @@ +// HCSR04 ultrasonic sensor class using interrupts and allowing multiple instances. +// You can use the same trigger pin for multiple instances, the echo is recieved and +// measurement calculated based on the echo input alone (when the echo signal goes high +// the timer is started, when the echo signal is low the timer value in microseconds +// is saved as the length, and the timer is stopped and reset. Length calculation is done +// when the length is requested (either inches or centimeters) using the appropriate +// function. +// + +#ifndef MBED_HCSR04_H +#define MBED_HCSR04_H + +//required to use mbed functions +#include "mbed.h" + +#define TRIGGER_DELAY 12 // length of trigger signal expected by HCSR04 sensor +#define INCHES_DIVISOR 148 // +#define CM_DIVISOR 58 + +class hcsr04 { + +private: + InterruptIn *_echo_int; // pin to receive echo signal + DigitalOut trigger_out; // pin to send the trigger signal + Timer timer; // timer to track length of pulse + // int timestart; // beginning time of echo pulse + float value; // to store the last pulse length + +public: + bool measuring; // true while the echo signal is high (measurement in progress) + hcsr04(PinName trigger, PinName echo) : trigger_out(trigger) { // _pass the names to the pin configuration + // _trigger_out = new DigitalOut( trigger ); + _echo_int = new InterruptIn( echo ); + _echo_int->rise(this, &hcsr04::timer_start); + _echo_int->fall(this, &hcsr04::calc_measurement); + measuring = false; + } + + + +void calc_measurement() { + value = timer.read_us(); + //value = timer.read_us() - timestart; + timer.stop(); + timer.reset(); + measuring = false; +} + +void timer_start() { + this->timer.start(); + measuring = true; +} + +void trigger(void) { + trigger_out.write(1); // start trigger signal + wait_us(TRIGGER_DELAY); + trigger_out.write(0); // end trigger signal +} + +float inches() { + return value / INCHES_DIVISOR; +} + +float cm() { + return value /CM_DIVISOR; +} + +}; + +#endif \ No newline at end of file