A replacement for InterruptIn that debounces the interrupt.

Dependents:   D7A_Demo-Get-started CVtoOSCConverter EE3501keypad D7A_1x_demo_sensors_v3 ... more

Fork of DebouncedInterrupt by Anil Kandangath

Example code:

#include "DebouncedInterrupt.h"

DebouncedInterrupt up_button(USER_BUTTON);

void onUp()
{
    // Do Something
}

int main()
{
    // Will immediatly call function and ignore other interrupts until timeout
    up_button.attach(&onUp, IRQ_FALL, 1000, true);

    // Will call function only if button has been held for the specified time
    //up_button.attach(&onUp, IRQ_FALL, 500, false);

    while(1) {}
}

DebouncedInterrupt.cpp

Committer:
Jeej
Date:
2017-04-27
Revision:
26:2df374d23986
Parent:
25:2163ebb21aef

File content as of revision 26:2df374d23986:

/**
* DebouncedInterrupt.cpp
**/
#include "DebouncedInterrupt.h"


DebouncedInterrupt::DebouncedInterrupt(PinName pin)
{
    _in = new InterruptIn(pin);
    _din = new DigitalIn(pin, PullUp);
    _timeout = new Timeout;
}

DebouncedInterrupt::~DebouncedInterrupt()
{
    delete _in;
    delete _din;
    delete _timeout;
}

void DebouncedInterrupt::attach(void (*fptr)(void), const gpio_irq_event trigger, const uint32_t debounce_ms, bool immediate)
{
    if(fptr) {
        _callback = callback(fptr);
        _last_bounce_count = _bounce_count = 0;
        _debounce_us = 1000*debounce_ms;
        _trigger = trigger;
        _timeout_expired = true;
        _immediate = immediate;
        
        switch(trigger)
        {
            case IRQ_RISE:
                _in->rise(callback(this, &DebouncedInterrupt::_onInterrupt));
                break;
            case IRQ_FALL:
                _in->fall(callback(this, &DebouncedInterrupt::_onInterrupt));
                break;
            case IRQ_NONE:
                reset(); // Unexpected. Clear callbacks.
                break;
        }
    } else {
        reset();
    }
}

void DebouncedInterrupt::reset()
{
    _timeout->detach();
    _timeout_expired = true;
}

unsigned int DebouncedInterrupt::get_bounce()
{
    return _last_bounce_count;
}

void DebouncedInterrupt::_onCallback()
{
    _last_bounce_count = _bounce_count;
    _bounce_count = 0;
    if (!_immediate) {
        if (_din->read() == (_trigger==IRQ_RISE)) {
            _callback.call();
        }
    }
    _timeout_expired = true;
}

void DebouncedInterrupt::_onInterrupt()
{
    _bounce_count++;

    if (_immediate) {
        if (_timeout_expired) {
            _timeout_expired = false;
            _callback.call();
            _timeout->attach_us(callback(this, &DebouncedInterrupt::_onCallback), _debounce_us);
        }
    }
    else {
        _timeout->attach_us(callback(this, &DebouncedInterrupt::_onCallback), _debounce_us);
    }
}