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