Ultrasonic Range Finder Sensors Library. May be used for SRF05 and all others sensors of the same kind (50ms period, 10us pulse)

Dependents:   FRC_2018 TestVMA 0hackton_08_06_18 lib_FRC_2019 ... more

VMA306.cpp

Committer:
haarkon
Date:
2018-06-05
Revision:
6:158dfeb5c24d
Parent:
3:4d9c742b860b

File content as of revision 6:158dfeb5c24d:

/* mbed VMA306 Ultrasonic Rangefiner Library
 */

#include "VMA306.h"

VMA306::VMA306(PinName trigG, PinName echoG, PinName trigB, PinName echoB, PinName trigD, PinName echoD)
    : _trig1(trigG), _echo1(echoG), _trig2(trigB), _echo2(echoB), _trig3(trigD), _echo3(echoD)
{

    // Attach interrupts
    _ticker.attach(callback(this, &VMA306::_startRanging), 0.05);

    _echo1.rise(callback(this, &VMA306::_rise1));
    _echo1.fall(callback(this, &VMA306::_fall1));
    _echo1.enable_irq();
    _echo2.rise(callback(this, &VMA306::_rise2));
    _echo2.fall(callback(this, &VMA306::_fall2));
    _echo2.enable_irq();
    _echo3.rise(callback(this, &VMA306::_rise3));
    _echo3.fall(callback(this, &VMA306::_fall3));
    _echo3.enable_irq();
    _timer.start();
}

void VMA306::_startRanging()
{
    static int step = 1;

    switch(step) {
        case 1:
            _trig1 = 1;
            wait_us(20);
            _trig1 = 0;
            step = 2;
            break;

        case 2:
            _trig2 = 1;
            wait_us(20);
            _trig2 = 0;
            step = 3;
            break;

        case 3:
            _trig3 = 1;
            wait_us(20);
            _trig3 = 0;
            step = 1;
            break;
    }
}

// Clear and start the timer at the begining of the echo pulse
void VMA306::_rise1(void)
{
    _startValue1 = _timer.read_us();
}

// Stop and read the timer at the end of the pulse
void VMA306::_fall1(void)
{
    _dist1 = (double)(_timer.read_us() - _startValue1)/58.0;
    _VMA306Flag1 = 1;
}

// Clear and start the timer at the begining of the echo pulse
void VMA306::_rise2(void)
{
    _startValue2 = _timer.read_us();
}

// Stop and read the timer at the end of the pulse
void VMA306::_fall2(void)
{
    _dist2 = (double)(_timer.read_us() - _startValue2)/58.0;
    _VMA306Flag2 = 1;
}

// Clear and start the timer at the begining of the echo pulse
void VMA306::_rise3(void)
{
    _startValue3 = _timer.read_us();
}

// Stop and read the timer at the end of the pulse
void VMA306::_fall3(void)
{
    _dist3 = (double)(_timer.read_us() - _startValue3)/58.0;
    _VMA306Flag3 = 1;
}

int VMA306::isUSGReady (void)
{
    return (_VMA306Flag1);
}

int VMA306::isUSBReady (void)
{
    return (_VMA306Flag2);
}

int VMA306::isUSDReady (void)
{
    return (_VMA306Flag3);
}

float VMA306::readUSG(void)
{
    _VMA306Flag1 = 0;
    return (_dist1);
}

float VMA306::readUSB(void)
{
    _VMA306Flag2 = 0;
    return (_dist2);
}

float VMA306::readUSD(void)
{
    _VMA306Flag3 = 0;
    return (_dist3);
}