Pulse measurement to know signal occupancy

Dependents:   PwmReaderTest

PwmReader.cpp

Committer:
abouillot
Date:
2017-01-25
Revision:
0:15aa9d3aeb2e
Child:
1:ebc39fb22351

File content as of revision 0:15aa9d3aeb2e:

/*!
 * PwmReader.cpp
 *
 * Read signal occupacy on a pin in a non blocking way using timer and interrupt
 *
 * Copyright (c) 2017 -  Alexandre Bouillot github.com/abouillot
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documnetation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to  whom the Software is
 * furished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS OR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
 
#include "PwmReader.h"


void PwmReader::pressedInt()
{
    _high += _timer.read_us() - _last_toggle;
    _last_toggle = _timer.read_us();
//    _timer.reset();
//    printf("p %ld ", _high);
//    sleep();
}

void PwmReader::releasedInt()
{
    _down += _timer.read_us() - _last_toggle;
    _last_toggle = _timer.read_us();
//    _timer.reset();
//    printf("r %ld", _down);
//    sleep();
}

void PwmReader::init()
{
    _pin.fall(callback(this, &PwmReader::pressedInt));
    _pin.rise(callback(this, &PwmReader::releasedInt));
}

void PwmReader::start()
{
    _high = 0;
    _down = 0;
    _start_state = _pin.read();
    _pin.enable_irq();
    _timer.start();
}

void PwmReader::stop()
{
    _pin.disable_irq();

    if (_high == 0 && _down == 0)
        if (_start_state == 0)
            _high = _timer.read_us();
        else if (_start_state == 1)
            _down = _timer.read_us();
    _timer.stop();
}