Added timeout functionality
Fork of HCSR04 by
hcsr04.cpp
- Committer:
- EmbeddedSam
- Date:
- 2016-10-24
- Revision:
- 1:e01896ab28d7
- Parent:
- 0:86b2086be101
File content as of revision 1:e01896ab28d7:
#include "hcsr04.h" #include "mbed.h" /* *HCSR04.cpp */ HCSR04::HCSR04(PinName t, PinName e) : trig(t), echo(e) {} 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 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(); } } } //return distance in cm long HCSR04::distance(){ duration = echo_duration(); distance_cm = (duration/2)/29.1 ; return distance_cm; }