Librería HCSR04 con algunas modificaciones
HCSR044.cpp@0:d4d01f7a6c68, 2014-12-04 (annotated)
- Committer:
- jaruiz
- Date:
- Thu Dec 04 06:28:23 2014 +0000
- Revision:
- 0:d4d01f7a6c68
Librer?a HCSR04 con algunas modificaciones
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
jaruiz | 0:d4d01f7a6c68 | 1 | #include "HCSR044.h" |
jaruiz | 0:d4d01f7a6c68 | 2 | #include "mbed.h" |
jaruiz | 0:d4d01f7a6c68 | 3 | |
jaruiz | 0:d4d01f7a6c68 | 4 | |
jaruiz | 0:d4d01f7a6c68 | 5 | HCSR044::HCSR044(PinName t, PinName e) : trig(t), echo(e) {} |
jaruiz | 0:d4d01f7a6c68 | 6 | |
jaruiz | 0:d4d01f7a6c68 | 7 | // Trigger Echo |
jaruiz | 0:d4d01f7a6c68 | 8 | // _______ _____________,,,,,,,,, |
jaruiz | 0:d4d01f7a6c68 | 9 | // ____| 10us |_________| 150us-25ms, or 38ms if no obstacle |
jaruiz | 0:d4d01f7a6c68 | 10 | // |
jaruiz | 0:d4d01f7a6c68 | 11 | |
jaruiz | 0:d4d01f7a6c68 | 12 | //return echo duration in us (refer to digram above) |
jaruiz | 0:d4d01f7a6c68 | 13 | long HCSR044::echo_duration() { |
jaruiz | 0:d4d01f7a6c68 | 14 | timer.reset(); |
jaruiz | 0:d4d01f7a6c68 | 15 | trig = 0; |
jaruiz | 0:d4d01f7a6c68 | 16 | wait_us(2); |
jaruiz | 0:d4d01f7a6c68 | 17 | trig = 1; |
jaruiz | 0:d4d01f7a6c68 | 18 | wait_us(10); |
jaruiz | 0:d4d01f7a6c68 | 19 | trig = 0; |
jaruiz | 0:d4d01f7a6c68 | 20 | while(echo == 0); |
jaruiz | 0:d4d01f7a6c68 | 21 | timer.start(); |
jaruiz | 0:d4d01f7a6c68 | 22 | while(echo == 1); |
jaruiz | 0:d4d01f7a6c68 | 23 | timer.stop(); |
jaruiz | 0:d4d01f7a6c68 | 24 | return timer.read_us(); |
jaruiz | 0:d4d01f7a6c68 | 25 | } |
jaruiz | 0:d4d01f7a6c68 | 26 | |
jaruiz | 0:d4d01f7a6c68 | 27 | //return distance to nearest obstacle or returns -1 |
jaruiz | 0:d4d01f7a6c68 | 28 | //if no obstacle within range |
jaruiz | 0:d4d01f7a6c68 | 29 | //set sys to cm or inch accordingly |
jaruiz | 0:d4d01f7a6c68 | 30 | long HCSR044::distance(int sys){ |
jaruiz | 0:d4d01f7a6c68 | 31 | duration = echo_duration(); |
jaruiz | 0:d4d01f7a6c68 | 32 | if(duration > 30000) |
jaruiz | 0:d4d01f7a6c68 | 33 | return -1; |
jaruiz | 0:d4d01f7a6c68 | 34 | distacne_cm = duration /29 / 2 ; |
jaruiz | 0:d4d01f7a6c68 | 35 | distance_inc = duration / 74 / 2; |
jaruiz | 0:d4d01f7a6c68 | 36 | if (sys) |
jaruiz | 0:d4d01f7a6c68 | 37 | return distacne_cm; |
jaruiz | 0:d4d01f7a6c68 | 38 | else |
jaruiz | 0:d4d01f7a6c68 | 39 | return distance_inc; |
jaruiz | 0:d4d01f7a6c68 | 40 | } |
jaruiz | 0:d4d01f7a6c68 | 41 |