view Button.h @ 1:284066a427c8

added flanks detection
author ark
date 2017-01-25 23:12 +0100
parents 968a3e3eb8ef
children b76b999b88c7
line wrap: on
line source

#ifndef Button_h
#define Button_h


/**
    utility class for debouncing a button based on pin state and time.

    notes time of state change. ignores further state changes for
    Button::BOUNCE_THRESHOLD miliseconds.

    (c) 2017 arkadiusz@wobblyhead.net
*/
class Button {
    public: 
        // stabilised button state
        bool isOn;
        // millis() time of last state change
        unsigned long lastChangeMs;
        // flag, true if state changed to pressed
        bool isPressed;
        // flag, true if state changed to off
        bool isReleased;

        /**
            create an uninitialised Button.
            setup() must be called after this to make it usable.
        */
        Button();

        /**
            setup button instance.
            assumes internal pullup.
            @param {byte} pin   button input pin
        */
        void setup(byte pin);

        /**
            setup button instance.
            @param {byte} pin   button input pin
            @param {bool} pu    if true, button uses internal pullup
        */
        void setup(byte pin, bool pu);

        /**
            check pin and update button state.
            calls millis() before calling update(ulong). if a recent millis()
            value is known, call update(ulong) directly to avoid the additional
            millis() call.
        */
        void update();

        /**
            check pin and update button state.
            @param {unsigned long} ms   current millis() value
        */
        void update(unsigned long ms);

        /** bounce threshold in miliseconds. state changes are ignored for that
         * long after a change.
         */
        const unsigned long BOUNCE_THRESHOLD = 100;

    private: 
        byte pin;
        bool isPullup;

        /**
            read pin state, translate to pressed state.
            @return {bool} true if buton is pressed
        */
        bool readState();

};

#endif