#include "mbed.h"
#include "uSound.h"

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

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

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

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

void uSound::startMeasurement() {
    trigger = 1;
    wait_us(10);
    trigger = 0;
    wait_ms(25); // 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 uSound::getDistance_cm() {
    startMeasurement();
    return distance;
}

float uSound::getDistance_mm() {
    startMeasurement();
    return distance * 10;
}

void uSound::setRanges(float minRange, float maxRange) {
    if (minRange < maxRange) {
        if (minRange >= 2) 
            minDistance = minRange;
        if (maxRange <= 400)
            maxDistance = maxRange;
    }
}

float uSound::getMinRange() {
    return minDistance;
}

float uSound::getMaxRange() {
    return maxDistance;
}
