1 sensor using RTOS Timer, another 2 over RTOS Semaphore
Dependents: Autonomous_quadcopter
Fork of HCSR04 by
hcsr04.cpp@2:8801a3da8693, 2017-12-01 (annotated)
- Committer:
- edy05
- Date:
- Fri Dec 01 11:10:54 2017 +0000
- Revision:
- 2:8801a3da8693
- Parent:
- 1:53657de3246f
- Child:
- 3:81512ca9a13c
updated;
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" |
edy05 | 1:53657de3246f | 3 | #include "rtos.h" |
antoniolinux | 0:86b2086be101 | 4 | /* |
antoniolinux | 0:86b2086be101 | 5 | *HCSR04.cpp |
antoniolinux | 0:86b2086be101 | 6 | */ |
edy05 | 1:53657de3246f | 7 | HCSR04::HCSR04(PinName t, PinName e) : trig(t), echo(e) { |
edy05 | 1:53657de3246f | 8 | thread = new Thread(threadWorker, this); |
edy05 | 1:53657de3246f | 9 | } |
edy05 | 1:53657de3246f | 10 | |
edy05 | 1:53657de3246f | 11 | void HCSR04::threadWorker(void const *p) |
edy05 | 1:53657de3246f | 12 | { |
edy05 | 1:53657de3246f | 13 | HCSR04* self = (HCSR04*)p; |
edy05 | 1:53657de3246f | 14 | |
edy05 | 1:53657de3246f | 15 | while(1){ |
antoniolinux | 0:86b2086be101 | 16 | |
edy05 | 1:53657de3246f | 17 | self->trig=0; // trigger low |
edy05 | 1:53657de3246f | 18 | wait_us(2); // wait |
edy05 | 1:53657de3246f | 19 | self->trig=1; // trigger high |
edy05 | 1:53657de3246f | 20 | wait_us(10); |
edy05 | 1:53657de3246f | 21 | self->trig=0; // trigger low |
edy05 | 1:53657de3246f | 22 | while(!self->echo); // start pulseIN |
edy05 | 1:53657de3246f | 23 | self->timer.reset(); //reset timer |
edy05 | 1:53657de3246f | 24 | self->timer.start(); |
edy05 | 1:53657de3246f | 25 | while(self->echo); |
edy05 | 1:53657de3246f | 26 | self->timer.stop(); |
edy05 | 1:53657de3246f | 27 | self->distan = self->timer.read_us() / 58; |
edy05 | 1:53657de3246f | 28 | |
edy05 | 2:8801a3da8693 | 29 | Thread::wait(2); |
edy05 | 1:53657de3246f | 30 | } |
edy05 | 1:53657de3246f | 31 | } |
edy05 | 1:53657de3246f | 32 | |
edy05 | 1:53657de3246f | 33 | uint16_t HCSR04::getDistan(){ |
edy05 | 1:53657de3246f | 34 | return distan; |
antoniolinux | 0:86b2086be101 | 35 | } |
antoniolinux | 0:86b2086be101 | 36 | |
antoniolinux | 0:86b2086be101 | 37 | //return distance in cm |
edy05 | 1:53657de3246f | 38 | uint16_t HCSR04::getDistance(){ |
edy05 | 1:53657de3246f | 39 | distance_cm = distan/58; |
edy05 | 1:53657de3246f | 40 | return distance_cm; |
antoniolinux | 0:86b2086be101 | 41 | |
antoniolinux | 0:86b2086be101 | 42 | } |