Now working with floats instead of long ints
Fork of HCSR04 by
hcsr04.cpp@1:ca0ff158918c, 2015-11-03 (annotated)
- Committer:
- emiedema
- Date:
- Tue Nov 03 14:42:13 2015 +0000
- Revision:
- 1:ca0ff158918c
- Parent:
- 0:86b2086be101
Awesome!
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 | */ |
antoniolinux | 0:86b2086be101 | 6 | HCSR04::HCSR04(PinName t, PinName e) : trig(t), echo(e) {} |
emiedema | 1:ca0ff158918c | 7 | float 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 |
antoniolinux | 0:86b2086be101 | 15 | while(!echo); // start pulseIN |
antoniolinux | 0:86b2086be101 | 16 | timer.start(); |
antoniolinux | 0:86b2086be101 | 17 | while(echo); |
antoniolinux | 0:86b2086be101 | 18 | timer.stop(); |
antoniolinux | 0:86b2086be101 | 19 | return timer.read_us(); |
antoniolinux | 0:86b2086be101 | 20 | |
antoniolinux | 0:86b2086be101 | 21 | } |
antoniolinux | 0:86b2086be101 | 22 | |
antoniolinux | 0:86b2086be101 | 23 | //return distance in cm |
emiedema | 1:ca0ff158918c | 24 | float HCSR04::distance(){ |
antoniolinux | 0:86b2086be101 | 25 | duration = echo_duration(); |
antoniolinux | 0:86b2086be101 | 26 | distance_cm = (duration/2)/29.1 ; |
antoniolinux | 0:86b2086be101 | 27 | return distance_cm; |
antoniolinux | 0:86b2086be101 | 28 | |
antoniolinux | 0:86b2086be101 | 29 | } |