Debounce a mechanical switch by periodic sampling.

Dependents:   RedButton WS_7_Seg_mit_LM1635 WS_7_Seg_mit_LM1635 Lichtschalter_M0 ... more

Debouncer.h

Committer:
huliyang
Date:
2015-05-18
Revision:
2:7f2f00805d41
Parent:
0:2359961af424

File content as of revision 2:7f2f00805d41:

/* Copyright (c) 2015 Liyang HU, MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation 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 furnished 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 FOR 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 <mbed.h>
#include <DigitalIn.h>
#include <Ticker.h>

class Debouncer : private Ticker
{
private:
    FunctionPointer fun_fall, fun_rise;
    DigitalIn in;
    uint32_t previous;
    uint8_t _samples;
    bool now;
    void tick(void);

public:
    Debouncer(PinName pin, PinMode mode = PullUp);
    Debouncer &samples(uint8_t n = 8);
    Debouncer &period(float seconds = 3.90625e-3);
    operator bool(void);

    Debouncer &attach_fall(void (*fun)(void) = NULL);
    Debouncer &attach_rise(void (*fun)(void) = NULL);
    template <typename T>
        Debouncer &attach_fall(T *obj, void (T::*fun)(void) = NULL);
    template <typename T>
        Debouncer &attach_rise(T *obj, void (T::*fun)(void) = NULL);
};