1 sensor using RTOS Timer, another 2 over RTOS Semaphore

Dependents:   Autonomous_quadcopter

Fork of HCSR04 by Antoniolinux B.

hcsr04.cpp

Committer:
edy05
Date:
2018-02-04
Revision:
5:02948ae78be7
Parent:
3:81512ca9a13c
Child:
6:7f98f258e8ef

File content as of revision 5:02948ae78be7:

#include "hcsr04.h"
#include "definitions.h"
#include "mbed.h"
#include "rtos.h"
/*
*HCSR04.cpp
*/
HCSR04::HCSR04(PinName t, PinName e) : trig(t), echo(e) {
    //thread = new Thread(threadWorker, this);
    threadUpdateTimer = new RtosTimer(threadWorker, osTimerPeriodic, this);
    int rate = (1.0 / FLIGHT_CONTROLLER_FREQUENCY) * 1000;
    threadUpdateTimer->start(rate);
}

void HCSR04::threadWorker(void const *p)
{
    HCSR04* self = (HCSR04*)p;
    
        self->trig=1;   //  trigger high
        wait_us(10);
        self->trig=0;  // trigger low
        // start pulseIN
        self->timer.reset();
        self->timer.start();
        while(!self->echo){
            if(self->timer.read_us() > 4500){
                //printf("moc1\n\r");
                break;
            }    
        }
        if(self->timer.read_us() < 4500){
            self->timer.stop();
            self->timer.reset();  //reset timer
            self->timer.start();
            while(self->echo){
                if(self->timer.read_us() > 4500){
                    //printf("moc2\n\r");
                    break;
                }
            }
            self->timer.stop();
            self->distan = self->timer.read_us() / 58;
        }
}

uint16_t HCSR04::getDistan(){
    return distan;    
}
 
//return distance in cm 
uint16_t HCSR04::getDistance(){
    distance_cm = distan/58;
    return distance_cm;

}