Library used to implement HCSR04 Ranging Module.

Dependents:   2Project3_Robot2_Final

Fork of HCSR04 by Awadh Al Shukaili

HCSR04.cpp

Committer:
Jakschwa
Date:
2016-05-02
Revision:
1:348fdd74f030
Parent:
0:0bda99bb39a4

File content as of revision 1:348fdd74f030:

#include "HCSR04.h"
#include "mbed.h"


HCSR04::HCSR04(PinName t, PinName e) : trig(t), echo(e) {}

//      Trigger          Echo
//      _______           _____________,,,,,,,,,
// ____|  10us |_________| 150us-25ms, or 38ms if no obstacle
// 

//return echo duration in us (refer to digram above)
long HCSR04::echo_duration() {
    timer.reset();
    trig = 0;
    wait_us(2);
    trig = 1;
    wait_us(10);
    trig = 0;
    while(echo == 0);
    timer.start();
    while(echo == 1);
    timer.stop();
    return timer.read_us();
}

//return distance to nearest obstacle or returns -1 
//if no obstacle within range
//set sys to cm or inch accordingly
long HCSR04::distance(void){
    duration = echo_duration();
    if(duration > 30000)
        return 1000;
    distacne_cm = duration /29 / 2 ;
    distance_inc = duration / 74 / 2;
    return distacne_cm;
}