1 sensor using RTOS Timer, another 2 over RTOS Semaphore

Dependents:   Autonomous_quadcopter

Fork of HCSR04 by Antoniolinux B.

Committer:
edy05
Date:
Thu Oct 26 15:54:16 2017 +0000
Revision:
1:53657de3246f
Parent:
0:86b2086be101
Child:
2:8801a3da8693
hcsro4 runs in its own thread

Who changed what in which revision?

UserRevisionLine numberNew 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 1:53657de3246f 29 Thread::wait(50);
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 }