Library for Ultrasonic Range,
Fork of HCSR04 by
hcsr04.cpp@1:0b3bdb910fe7, 2016-06-21 (annotated)
- Committer:
- yruiewyrui3
- Date:
- Tue Jun 21 07:45:27 2016 +0000
- Revision:
- 1:0b3bdb910fe7
- Parent:
- 0:86b2086be101
.
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
antoniolinux | 0:86b2086be101 | 1 | #include "hcsr04.h" |
antoniolinux | 0:86b2086be101 | 2 | #include "mbed.h" |
antoniolinux | 0:86b2086be101 | 3 | /* |
antoniolinux | 0:86b2086be101 | 4 | *HCSR04.cpp |
antoniolinux | 0:86b2086be101 | 5 | */ |
yruiewyrui3 | 1:0b3bdb910fe7 | 6 | HCSR04::HCSR04(PinName t, PinName e, long to) : trig(t), echo(e), time_out(to){} |
antoniolinux | 0:86b2086be101 | 7 | long HCSR04::echo_duration() { |
antoniolinux | 0:86b2086be101 | 8 | |
antoniolinux | 0:86b2086be101 | 9 | timer.reset(); //reset timer |
antoniolinux | 0:86b2086be101 | 10 | trig=0; // trigger low |
antoniolinux | 0:86b2086be101 | 11 | wait_us(2); // wait |
antoniolinux | 0:86b2086be101 | 12 | trig=1; // trigger high |
antoniolinux | 0:86b2086be101 | 13 | wait_us(10); |
antoniolinux | 0:86b2086be101 | 14 | trig=0; // trigger low |
yruiewyrui3 | 1:0b3bdb910fe7 | 15 | while(!echo); // start pulseIN |
yruiewyrui3 | 1:0b3bdb910fe7 | 16 | timer.start(); |
yruiewyrui3 | 1:0b3bdb910fe7 | 17 | while(echo) |
yruiewyrui3 | 1:0b3bdb910fe7 | 18 | { |
yruiewyrui3 | 1:0b3bdb910fe7 | 19 | if(timer.read_us()>time_out) |
yruiewyrui3 | 1:0b3bdb910fe7 | 20 | break; |
yruiewyrui3 | 1:0b3bdb910fe7 | 21 | } |
yruiewyrui3 | 1:0b3bdb910fe7 | 22 | timer.stop(); |
yruiewyrui3 | 1:0b3bdb910fe7 | 23 | long czas=timer.read_us(); |
yruiewyrui3 | 1:0b3bdb910fe7 | 24 | if(czas<300) |
yruiewyrui3 | 1:0b3bdb910fe7 | 25 | return 0; |
yruiewyrui3 | 1:0b3bdb910fe7 | 26 | return timer.read_us(); |
antoniolinux | 0:86b2086be101 | 27 | |
antoniolinux | 0:86b2086be101 | 28 | } |
antoniolinux | 0:86b2086be101 | 29 | |
antoniolinux | 0:86b2086be101 | 30 | //return distance in cm |
antoniolinux | 0:86b2086be101 | 31 | long HCSR04::distance(){ |
antoniolinux | 0:86b2086be101 | 32 | duration = echo_duration(); |
yruiewyrui3 | 1:0b3bdb910fe7 | 33 | distance_cm = (duration/2.00)/29.10 ; |
antoniolinux | 0:86b2086be101 | 34 | return distance_cm; |
antoniolinux | 0:86b2086be101 | 35 | |
antoniolinux | 0:86b2086be101 | 36 | } |