Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
hcsr04.h
00001 // Primary Author: David Glover 00002 // March, 2012 00003 // ECE 510 Embedded Systems, Roy Kravitz 00004 // 00005 // HCSR04 ultrasonic sensor class using interrupts and allowing multiple instances. 00006 // You can use the same trigger pin for multiple instances, the echo is recieved and 00007 // measurement calculated based on the echo input alone (when the echo signal goes high 00008 // the timer is started, when the echo signal goes low the timer value in microseconds 00009 // is saved as the length, and the timer is stopped and reset. Length calculation is done 00010 // when the length is requested (either inches or centimeters) using the appropriate 00011 // function. 00012 00013 #ifndef MBED_HCSR04_H 00014 #define MBED_HCSR04_H 00015 00016 //required to use mbed functions 00017 #include "mbed.h" 00018 00019 #define TRIGGER_DELAY 12 // length of trigger signal expected by HCSR04 sensor 00020 #define INCHES_DIVISOR 148 // 00021 #define CM_DIVISOR 58 00022 00023 class hcsr04 { 00024 00025 private: 00026 InterruptIn *_echo_int; // pin to receive echo signal 00027 DigitalOut trigger_out; // pin to send the trigger signal 00028 Timer timer; // timer to track length of pulse 00029 float value; // to store the last pulse length 00030 00031 public: 00032 bool measuring; // true while the echo signal is high (measurement in progress) 00033 hcsr04(PinName trigger, PinName echo) : trigger_out(trigger) { // _pass the names to the pin configuration 00034 // _trigger_out = new DigitalOut( trigger ); 00035 _echo_int = new InterruptIn( echo ); 00036 _echo_int->rise(this, &hcsr04::timer_start); 00037 _echo_int->fall(this, &hcsr04::calc_measurement); 00038 measuring = false; 00039 } 00040 00041 00042 void calc_measurement() { 00043 value = timer.read_us(); 00044 //value = timer.read_us() - timestart; 00045 timer.stop(); 00046 timer.reset(); 00047 measuring = false; 00048 } 00049 00050 void timer_start() { 00051 this->timer.start(); 00052 measuring = true; 00053 } 00054 00055 void trigger(void) { 00056 trigger_out.write(1); // start trigger signal 00057 wait_us(TRIGGER_DELAY); 00058 trigger_out.write(0); // end trigger signal 00059 } 00060 00061 float inches() { // return distance in inches. 00062 return value / INCHES_DIVISOR; 00063 } 00064 00065 float cm() { // return distance in centimeters. 00066 return value / CM_DIVISOR; 00067 } 00068 00069 }; 00070 00071 #endif
Generated on Thu Jul 14 2022 13:39:36 by
1.7.2