A distance measurement class using ultrasonic sensor HC-SR04.

Dependents:   Esercitazione4_4 HC-SR04 Group10_slave Oled_Gus ... more

The purpose of this library is to encourage students to develope their own classes. Instructions how to follow the development of this library for ultrasonic distance measurement are given here.

HCSR04.cpp

Committer:
tbjazic
Date:
2015-12-06
Revision:
3:9a7899cf5e3a
Parent:
0:8871082486ac
Child:
4:aae70f15357f

File content as of revision 3:9a7899cf5e3a:

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

HCSR04::HCSR04(PinName echoPin, PinName triggerPin) : echo(echoPin), trigger(triggerPin) {
    init();
}

void HCSR04::init() {
    /** configure the rising edge to start the timer */
    echo.rise(this, &HCSR04::startTimer);
    
    /** configure the falling edge to stop the timer */
    echo.fall(this, &HCSR04::stopTimer);
    
    distance = -1;      // initial distance
    minDistance = 4;
    maxDistance = 400;
}

void HCSR04::startTimer() {
    timer.start(); // start the timer
}

void HCSR04::stopTimer() {
    timer.stop(); // stop the timer
}

void HCSR04::startMeasurement() {
    trigger = 1;
    wait_us(10);
    trigger = 0;
    wait_us(23660); // just enough time to measure 400 cm
    timer.stop(); // just in case echo fall did not occur
    distance = timer.read() * 1e6 / 58;
    if (distance < minDistance)
        distance = minDistance;
    if (distance > maxDistance)
        distance = maxDistance;
    timer.reset();
}

float HCSR04::getDistance_cm() {
    startMeasurement();
    return distance;
}