changed range conditions

Dependents:   theRobot3

Fork of HCSR04 by stephen smitherman

Revision:
2:3ebde19131af
Parent:
1:68ad9acbec81
Child:
3:89f21eb28e13
--- a/HCSR04.cpp	Mon Dec 02 23:14:26 2013 +0000
+++ b/HCSR04.cpp	Thu Dec 12 17:22:48 2013 +0000
@@ -7,6 +7,8 @@
 
 #include "mbed.h"
 #include "HCSR04.h"
+#include "stdio.h"
+
 
 #define SPEED_OF_SOUND      (343.2f)    // meters/sec
 
@@ -15,8 +17,6 @@
 #define SIGNAL_LOW      (0)
 
 #define TRIGGER_TIME    (10)            // microseconds
-
-
 // Name: HCSR04
 // Desc: HCSR04 constructor
 // Inputs: PinName - pin used for trigger signal
@@ -29,9 +29,11 @@
 measTimeStart_us(0),
 measTimeStop_us(0)
 {
+     
     echo.rise( this, &HCSR04::ISR_echoRising );
     echo.fall( this, &HCSR04::ISR_echoFalling );
     echoTimer.start();
+    
 }
 
 // Name: startMeas
@@ -42,9 +44,11 @@
 //
 void HCSR04::startMeas(void)
 {
-    trigger = SIGNAL_HIGH;
+    //printf("Start US\n\n");
     echoTimer.reset();
+    trigger = SIGNAL_HIGH;
     triggerTicker.attach_us(this, &HCSR04::triggerTicker_cb, TRIGGER_TIME);
+    
 }
  
 // Name: getMeas
@@ -53,18 +57,22 @@
 // Outputs: etHCSR04 - RANGE_MEAS_VALID or RANGE_MEAS_INVALID
 //
 etHCSR04_RANGE_STATUS HCSR04::getMeas(float &rRangeMeters)
-{
-    unsigned long dTime_us;
-    if ( !measTimeStart_us || !measTimeStop_us )
-    {
+{ 
+    
+    if ( status ==  RANGE_MEAS_VALID)
+    {   
+        dTime_us = measTimeStop_us - measTimeStart_us;
+        measTimeStart_us = 0;
+        measTimeStop_us = 0;
+    
+        rRangeMeters = (float)dTime_us * SPEED_OF_SOUND / 2000000.0 * MTRS_TO_INCH;
+        status = RANGE_MEAS_INVALID;
+        return RANGE_MEAS_VALID;
+    }else{  
+        
         return RANGE_MEAS_INVALID;
+        
     }
-    
-    dTime_us = measTimeStop_us - measTimeStart_us;
-    rRangeMeters = (float)dTime_us / 1000000. * SPEED_OF_SOUND / 2;
-    measTimeStart_us = 0;
-    measTimeStop_us = 0;
-    return ( RANGE_MEAS_VALID );
 }
 
 // Name: triggerTicker_cb
@@ -73,10 +81,9 @@
 // Outputs: none
 //
 void HCSR04::triggerTicker_cb(void)
-{
+{ 
     trigger = SIGNAL_LOW;
     triggerTicker.detach();
-    
 }
 
 
@@ -98,5 +105,6 @@
 void HCSR04::ISR_echoFalling(void)
 {
     measTimeStop_us = echoTimer.read_us();
+    status = RANGE_MEAS_VALID;
 }