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.
Dependents: TextLCD_HelloWorld ES_4_P4
HCSR04.cpp
00001 #include "mbed.h" 00002 #include "HCSR04.h" 00003 00004 HCSR04::HCSR04(PinName echoPin, PinName triggerPin) : echo(echoPin), trigger(triggerPin) { 00005 init(); 00006 } 00007 00008 void HCSR04::init() { 00009 /** configure the rising edge to start the timer */ 00010 echo.rise(this, &HCSR04::startTimer); 00011 00012 /** configure the falling edge to stop the timer */ 00013 echo.fall(this, &HCSR04::stopTimer); 00014 00015 distance = -1; // initial distance 00016 minDistance = 2; 00017 maxDistance = 400; 00018 } 00019 00020 void HCSR04::startTimer() { 00021 timer.start(); // start the timer 00022 } 00023 00024 void HCSR04::stopTimer() { 00025 timer.stop(); // stop the timer 00026 } 00027 00028 void HCSR04::startMeasurement() { 00029 trigger = 1; 00030 wait_us(10); 00031 trigger = 0; 00032 wait_us(23660); // just enough time to measure 400 cm 00033 timer.stop(); // just in case echo fall did not occur 00034 distance = timer.read() * 1e6 / 58; 00035 if (distance < minDistance) 00036 distance = minDistance; 00037 if (distance > maxDistance) 00038 distance = maxDistance; 00039 timer.reset(); 00040 } 00041 00042 float HCSR04::getDistance_cm() { 00043 startMeasurement(); 00044 return distance; 00045 } 00046 00047 float HCSR04::getDistance_mm() { 00048 startMeasurement(); 00049 return distance * 10; 00050 } 00051 00052 void HCSR04::setRanges(float minRange, float maxRange) { 00053 if (minRange < maxRange) { 00054 if (minRange >= 2) 00055 minDistance = minRange; 00056 if (maxRange <= 400) 00057 maxDistance = maxRange; 00058 } 00059 } 00060 00061 float HCSR04::getMinRange() { 00062 return minDistance; 00063 } 00064 00065 float HCSR04::getMaxRange() { 00066 return maxDistance; 00067 }
Generated on Tue Jul 12 2022 17:30:46 by
1.7.2