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 // HCSR04 ultrasonic sensor class using interrupts and allowing multiple instances. 00002 // You can use the same trigger pin for multiple instances, the echo is recieved and 00003 // measurement calculated based on the echo input alone (when the echo signal goes high 00004 // the timer is started, when the echo signal is low the timer value in microseconds 00005 // is saved as the length, and the timer is stopped and reset. Length calculation is done 00006 // when the length is requested (either inches or centimeters) using the appropriate 00007 // function. 00008 // 00009 00010 #ifndef MBED_HCSR04_H 00011 #define MBED_HCSR04_H 00012 00013 //required to use mbed functions 00014 #include "mbed.h" 00015 00016 #define TRIGGER_DELAY 12 // length of trigger signal expected by HCSR04 sensor 00017 #define INCHES_DIVISOR 148 // 00018 #define CM_DIVISOR 58 00019 00020 class hcsr04 { 00021 00022 private: 00023 InterruptIn *_echo_int; // pin to receive echo signal 00024 DigitalOut trigger_out; // pin to send the trigger signal 00025 Timer timer; // timer to track length of pulse 00026 // int timestart; // beginning time of echo pulse 00027 float value; // to store the last pulse length 00028 00029 public: 00030 bool measuring; // true while the echo signal is high (measurement in progress) 00031 hcsr04(PinName trigger, PinName echo) : trigger_out(trigger) { // _pass the names to the pin configuration 00032 // _trigger_out = new DigitalOut( trigger ); 00033 _echo_int = new InterruptIn( echo ); 00034 _echo_int->rise(this, &hcsr04::timer_start); 00035 _echo_int->fall(this, &hcsr04::calc_measurement); 00036 measuring = false; 00037 } 00038 00039 00040 00041 void calc_measurement() { 00042 value = timer.read_us(); 00043 //value = timer.read_us() - timestart; 00044 timer.stop(); 00045 timer.reset(); 00046 measuring = false; 00047 } 00048 00049 void timer_start() { 00050 this->timer.start(); 00051 measuring = true; 00052 } 00053 00054 void trigger(void) { 00055 trigger_out.write(1); // start trigger signal 00056 wait_us(TRIGGER_DELAY); 00057 trigger_out.write(0); // end trigger signal 00058 } 00059 00060 float inches() { 00061 return value / INCHES_DIVISOR; 00062 } 00063 00064 float cm() { 00065 return value /CM_DIVISOR; 00066 } 00067 00068 }; 00069 00070 #endif
Generated on Fri Jul 22 2022 21:45:20 by
1.7.2