Button class with auto repeat function.

Revision:
0:a39041955963
Child:
1:3385a1ea4a7d
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Button.h	Tue Feb 14 13:00:47 2017 +0000
@@ -0,0 +1,70 @@
+#ifndef BUTTON_H_INCLUDED
+#define BUTTON_H_INCLUDED
+
+#include "mbed.h"
+
+enum ButtonEvent
+{
+    BUTTON_DOWN = 0, BUTTON_UP, BUTTON_PRESS, BUTTON_LONG_PRESS
+};
+
+class Button
+{
+public:
+    Button(PinName pinName, PinMode pinMode, int activeState, void(*onButtonEvent)(ButtonEvent event, PinName pinName), float autoRepeatTime = 0, uint16_t longPressTime = 600, uint16_t shortPressTime = 30)
+    : _pinName(pinName)
+    , _in(pinName)
+    , _shortPressTime(shortPressTime)
+    , _longPressTime(longPressTime)
+    , _autoRepeatTime(autoRepeatTime)
+    , _activeState(activeState)
+    , _prevState(0)
+    , _fireUpDown(false)
+    , _onButtonEvent(onButtonEvent)
+    {
+        _in.mode(pinMode);
+        _in.rise(Callback<void()>(this, &Button::isrRise));
+        _in.fall(Callback<void()>(this, &Button::isrFall));
+    };
+    inline void setAutoRepeat(float autoRepeatTime)
+    {
+        _autoRepeatTime = autoRepeatTime;
+    };
+    inline float getAutoRepeat() const
+    {
+        return _autoRepeatTime;
+    }
+    inline int read()
+    {
+        return _in.read() == _activeState;
+    };
+    operator int()
+    {
+        return read();
+    };
+    void setFireUpDown(bool fire)
+    {
+        _fireUpDown = fire;
+    };
+private:
+    PinName _pinName;
+    InterruptIn _in;
+    Timer _timer;
+    Ticker _tickerAutoRepeat;
+    Timeout _autoRepeatStarter;
+    uint16_t _shortPressTime;
+    uint16_t _longPressTime;
+    float _autoRepeatTime;
+    int _activeState;
+    int _prevState;
+    bool _fireUpDown;
+    void(*_onButtonEvent)(ButtonEvent event, PinName pinName);
+    void isrFall(void);
+    void isrRise(void);
+    void onPress(void);
+    void onRelease(void);
+    void autoRepeat(void);
+    void startAutoRepeat(void);
+};
+
+#endif /* BUTTON_H_INCLUDED */