A debouncing InterruptIn wrapper

ButtonIn.cpp

Committer:
evwijk
Date:
2012-02-07
Revision:
2:c353357a97e4
Parent:
1:e806603f0088

File content as of revision 2:c353357a97e4:

/*
ButtonIn is a debouncing InterruptIn class for mbed (http://mbed.org).

Copyright (C) 2012 Erik van Wijk (http://mbed.org/users/evwijk/)

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/    
    
#include "ButtonIn.h"

ButtonIn::ButtonIn(PinName buttonPin) :
    _button(buttonPin) {
        _buttonCanPress = true;
        _callback = NULL;
        _callbackInstance = NULL;
        _callbackMethod = NULL;
        timeout = 200;
        _button.rise(this, &ButtonIn::click);
}

void ButtonIn::attach(void (*method)(void)) {
    _callback = method;
}
    
template<class T>
void attach(T* instance, void (T::*method)(void)) {
    _callbackInstance = (ButtonInCallbackInstance *)instance;
    _callbackMethod = (void (ButtonInCallbackInstance::*)(void))method;
}

void ButtonIn::click() {
    if (_buttonCanPress) {
        _buttonCanPress = false;
        _buttonDownTimeout.attach_us(this, &ButtonIn::reset, timeout * 1000);
        call();
    }
}

void ButtonIn::call() {
    if (_callback != NULL)
        (*_callback)();
    else
        (_callbackInstance->*_callbackMethod)();        
}

void ButtonIn::reset() {
    _buttonCanPress = true;
}