A distance measurement class using ultrasonic sensor HC-SR04.

Dependents:   Esercitazione4_4 HC-SR04 Group10_slave Oled_Gus ... more

The purpose of this library is to encourage students to develope their own classes. Instructions how to follow the development of this library for ultrasonic distance measurement are given here.

Revision:
3:9a7899cf5e3a
Parent:
0:8871082486ac
Child:
4:aae70f15357f
--- a/HCSR04.cpp	Sat Dec 05 09:42:14 2015 +0000
+++ b/HCSR04.cpp	Sun Dec 06 15:13:54 2015 +0000
@@ -12,7 +12,9 @@
     /** configure the falling edge to stop the timer */
     echo.fall(this, &HCSR04::stopTimer);
     
-    distance = -1; // initial distance
+    distance = -1;      // initial distance
+    minDistance = 4;
+    maxDistance = 400;
 }
 
 void HCSR04::startTimer() {
@@ -24,19 +26,17 @@
 }
 
 void HCSR04::startMeasurement() {
-    /** Start the measurement by sending the 10us trigger pulse. */
     trigger = 1;
     wait_us(10);
     trigger = 0;
-    
-    /** Wait for the sensor to finish measurement (generate rise and fall interrupts).
-     *  Minimum wait time is determined by maximum measurement distance of 400 cm.
-     *  t_min = 400 * 58 = 23200 us = 23.2 ms */
-    wait_ms(25); 
-    
-    /** calculate the distance in cm */
+    wait_us(23660); // just enough time to measure 400 cm
+    timer.stop(); // just in case echo fall did not occur
     distance = timer.read() * 1e6 / 58;
-    timer.reset(); // reset the timer to 0 after storing the distance
+    if (distance < minDistance)
+        distance = minDistance;
+    if (distance > maxDistance)
+        distance = maxDistance;
+    timer.reset();
 }
 
 float HCSR04::getDistance_cm() {