robot

Dependencies:   FastPWM3 mbed

PwmIn/PwmIn.cpp

Committer:
bwang
Date:
2017-05-04
Revision:
155:7c6005933d4c
Parent:
151:5bbb15351798
Child:
221:1e607c8d7d76

File content as of revision 155:7c6005933d4c:

#include "mbed.h"
#include "PwmIn.h"
#include "MathHelpers.h"

PwmIn::PwmIn(PinName pin, int usec_min, int usec_max)
{
    int_in = new InterruptIn(pin);
    dig_in = new DigitalIn(pin);
    int_in->rise(this, &PwmIn::handle_rise);
    int_in->fall(this, &PwmIn::handle_fall);
    this->usec_min = usec_min;
    this->usec_max = usec_max;
    
    usecs = usec_min;
    blocked = false;
    enabled = false;
    risen = false;
}


bool PwmIn::get_enabled()
{
    return enabled;
}

void PwmIn::handle_rise()
{
    if (!enabled) {
        enabled = true;
        usecs = usec_min;
    }
    risen = true;
    
    timer.stop();
    timer.reset();
    timer.start();
}

void PwmIn::handle_fall()
{
    if (!risen) return;
    risen = false;
    
    if (blocked) {
        blocked = false;;
        return;
    }
    
    usecs = timer.read_us();
    timer.stop();
    timer.reset();
    timer.start();
}

float PwmIn::get_throttle()
{
    if(timer.read_us() > 40000) {
        enabled = false;
        usecs = usec_min;
    }
    if(!enabled) return -1;
    return constrain(map((float)usecs, usec_min, usec_max, 0, 1), 0, 1);
}