(DA) Internet of Things and Smart Electronics- ELE3006M2122
/
18689004Coursework
Coursework
hcsr04.cpp@0:1f799c7cce2b, 2021-12-16 (annotated)
- Committer:
- sesa514652
- Date:
- Thu Dec 16 14:03:11 2021 +0000
- Revision:
- 0:1f799c7cce2b
Screen and US combined code
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
sesa514652 | 0:1f799c7cce2b | 1 | #include "hcsr04.h" |
sesa514652 | 0:1f799c7cce2b | 2 | #include "mbed.h" |
sesa514652 | 0:1f799c7cce2b | 3 | /* |
sesa514652 | 0:1f799c7cce2b | 4 | *HCSR04.cpp |
sesa514652 | 0:1f799c7cce2b | 5 | */ |
sesa514652 | 0:1f799c7cce2b | 6 | HCSR04::HCSR04(PinName t, PinName e) : trig(t), echo(e) {} |
sesa514652 | 0:1f799c7cce2b | 7 | long HCSR04::echo_duration() { |
sesa514652 | 0:1f799c7cce2b | 8 | |
sesa514652 | 0:1f799c7cce2b | 9 | timer.reset(); //reset timer |
sesa514652 | 0:1f799c7cce2b | 10 | trig=0; // trigger low |
sesa514652 | 0:1f799c7cce2b | 11 | wait_us(2); // wait |
sesa514652 | 0:1f799c7cce2b | 12 | trig=1; // trigger high |
sesa514652 | 0:1f799c7cce2b | 13 | wait_us(10); |
sesa514652 | 0:1f799c7cce2b | 14 | trig=0; // trigger low |
sesa514652 | 0:1f799c7cce2b | 15 | while(!echo); // start pulseIN |
sesa514652 | 0:1f799c7cce2b | 16 | timer.start(); |
sesa514652 | 0:1f799c7cce2b | 17 | while(echo); |
sesa514652 | 0:1f799c7cce2b | 18 | timer.stop(); |
sesa514652 | 0:1f799c7cce2b | 19 | return timer.read_us(); |
sesa514652 | 0:1f799c7cce2b | 20 | |
sesa514652 | 0:1f799c7cce2b | 21 | } |
sesa514652 | 0:1f799c7cce2b | 22 | |
sesa514652 | 0:1f799c7cce2b | 23 | //return distance in cm |
sesa514652 | 0:1f799c7cce2b | 24 | long HCSR04::distance(){ |
sesa514652 | 0:1f799c7cce2b | 25 | duration = echo_duration(); |
sesa514652 | 0:1f799c7cce2b | 26 | distance_cm = (duration/2)/29.1 ; |
sesa514652 | 0:1f799c7cce2b | 27 | return distance_cm; |
sesa514652 | 0:1f799c7cce2b | 28 | |
sesa514652 | 0:1f799c7cce2b | 29 | } |