A replacement for InterruptIn that debounces the interrupt.
Dependents: D7A_Demo-Get-started CVtoOSCConverter EE3501keypad D7A_Localisation ... more
Fork of DebouncedInterrupt by
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) {} }
Diff: DebouncedInterrupt.cpp
- Revision:
- 23:cd4042093f85
- Parent:
- 22:9733f886810a
- Child:
- 24:4e095ebbcfad
--- a/DebouncedInterrupt.cpp Tue Feb 25 23:44:37 2014 +0000 +++ b/DebouncedInterrupt.cpp Thu Nov 19 15:37:39 2015 +0000 @@ -2,28 +2,32 @@ * DebouncedInterrupt.cpp **/ #include "DebouncedInterrupt.h" +#include "dbg.h" -Timeout timeout; DebouncedInterrupt::DebouncedInterrupt(PinName pin) { _in = new InterruptIn(pin); _din = new DigitalIn(pin); + _timeout = new Timeout; } DebouncedInterrupt::~DebouncedInterrupt() { delete _in; delete _din; + delete _timeout; } -void DebouncedInterrupt::attach(void (*fptr)(void), const gpio_irq_event trigger, const unsigned int& debounce_ms) +void DebouncedInterrupt::attach(void (*fptr)(void), const gpio_irq_event trigger, const uint32_t debounce_ms, bool immediate) { if(fptr) { _fAttach.attach(fptr); _last_bounce_count = _bounce_count = 0; _debounce_us = 1000*debounce_ms; _trigger = trigger; + _timeout_expired = true; + _immediate = immediate; switch(trigger) { @@ -44,7 +48,8 @@ void DebouncedInterrupt::reset() { - timeout.detach(); + _timeout->detach(); + _timeout_expired = true; } unsigned int DebouncedInterrupt::get_bounce() @@ -56,13 +61,26 @@ { _last_bounce_count = _bounce_count; _bounce_count = 0; - if(_din->read() == (_trigger==IRQ_RISE)) { - _fAttach.call(); + if (!_immediate) { + if (_din->read() == (_trigger==IRQ_RISE)) { + _fAttach.call(); + } } + _timeout_expired = true; } void DebouncedInterrupt::_onInterrupt() { _bounce_count++; - timeout.attach_us(this, &DebouncedInterrupt::_callback, _debounce_us); + + if (_immediate) { + if (_timeout_expired) { + _timeout_expired = false; + _fAttach.call(); + _timeout->attach_us(this, &DebouncedInterrupt::_callback, _debounce_us); + } + } + else { + _timeout->attach_us(this, &DebouncedInterrupt::_callback, _debounce_us); + } }