Added timeout functionality

Fork of HCSR04 by Antoniolinux B.

Files at this revision

API Documentation at this revision

Comitter:
EmbeddedSam
Date:
Mon Oct 24 12:59:41 2016 +0000
Parent:
0:86b2086be101
Commit message:
added timeout functionality

Changed in this revision

hcsr04.cpp Show annotated file Show diff for this revision Revisions of this file
hcsr04.h Show annotated file Show diff for this revision Revisions of this file
diff -r 86b2086be101 -r e01896ab28d7 hcsr04.cpp
--- a/hcsr04.cpp	Mon Apr 14 08:23:09 2014 +0000
+++ b/hcsr04.cpp	Mon Oct 24 12:59:41 2016 +0000
@@ -7,16 +7,55 @@
  long HCSR04::echo_duration() {
         
     timer.reset();  //reset timer
+    timeout_timer.reset();
+    
+    //Initiate Trigger
     trig=0;   // trigger low 
     wait_us(2); //  wait 
     trig=1;   //  trigger high
     wait_us(10);
     trig=0;  // trigger low
-         while(!echo); // start pulseIN
-      timer.start();
-     while(echo);
-      timer.stop();
-     return timer.read_us(); 
+    
+    timeout_timer.start();
+    
+    while(!echo){
+      //Wait for 5V/3.3V pulse to start
+      if(timeout_timer.read_ms()>=10){ //100 ms timeout
+          timedOut = true;
+          break;      
+          }
+      }
+      
+      //Pulse Started
+      if(timedOut == true){
+          //Error, pulse didn't start for some reason
+          timedOut = false;
+          return 999999;  //error pulse not started in time
+      }
+      else
+      {
+        timeout_timer.reset();
+        timer.start();
+        timeout_timer.start(); 
+        while(echo){
+            if(timeout_timer.read_ms()>=10){
+                timedOut = true;
+                break;
+            }        
+        }
+        if(timedOut == true){
+          timedOut = false;
+          return 999999;
+          }
+        else{
+          timer.stop();
+          return timer.read_us();     
+          }  
+      }
+      
+      
+      
+
  
 }
  
diff -r 86b2086be101 -r e01896ab28d7 hcsr04.h
--- a/hcsr04.h	Mon Apr 14 08:23:09 2014 +0000
+++ b/hcsr04.h	Mon Oct 24 12:59:41 2016 +0000
@@ -39,11 +39,13 @@
     HCSR04(PinName t, PinName e);
     long echo_duration();
     long distance();
+    bool timedOut;
  
     private:
         DigitalOut trig;
         DigitalIn echo;
         Timer timer;
+        Timer timeout_timer;
         long duration,distance_cm;
 };