Library for controlling ultrasonic ranging module HCSR04 Ported by hiawoood from arduino library orgininally created by ITead studio.
Revision 1:b30b99a74f6e, committed 2022-05-08
- Comitter:
- sas638
- Date:
- Sun May 08 20:09:39 2022 +0000
- Parent:
- 0:0bda99bb39a4
- Commit message:
- sensor;
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 0bda99bb39a4 -r b30b99a74f6e HCSR04.cpp --- a/HCSR04.cpp Tue Oct 18 14:32:12 2011 +0000 +++ b/HCSR04.cpp Sun May 08 20:09:39 2022 +0000 @@ -10,24 +10,24 @@ // //return echo duration in us (refer to digram above) -long HCSR04::echo_duration() { +int HCSR04::echo_duration() { timer.reset(); - trig = 0; - wait_us(2); - trig = 1; - wait_us(10); - trig = 0; - while(echo == 0); - timer.start(); - while(echo == 1); - timer.stop(); - return timer.read_us(); + trig = 0; //set trig low + wait_us(2); //wait 2 microseconds + trig = 1; //set trig high + wait_us(10); //wait 10 microseconds + trig = 0; // set trig low again + while(echo == 0); //while loop for starting timer when echo set to 0 + timer.start(); //start timer + while(echo == 1); //while loop for stopping timer when echo set to 1 + timer.stop(); // stop timer + return static_cast<int>(timer.read_us()); //return the timer } //return distance to nearest obstacle or returns -1 //if no obstacle within range //set sys to cm or inch accordingly -long HCSR04::distance(int sys){ +int HCSR04::distance(int sys){ duration = echo_duration(); if(duration > 30000) return -1;
diff -r 0bda99bb39a4 -r b30b99a74f6e HCSR04.h --- a/HCSR04.h Tue Oct 18 14:32:12 2011 +0000 +++ b/HCSR04.h Sun May 08 20:09:39 2022 +0000 @@ -26,14 +26,14 @@ class HCSR04 { public: HCSR04(PinName t, PinName e); - long echo_duration(); - long distance(int sys); + int echo_duration(); + int distance(int sys); private: DigitalOut trig; DigitalIn echo; Timer timer; - long duration,distacne_cm,distance_inc; + int duration,distacne_cm,distance_inc; }; #endif \ No newline at end of file