Debounce a mechanical switch by periodic sampling.

Dependents:   RedButton WS_7_Seg_mit_LM1635 WS_7_Seg_mit_LM1635 Lichtschalter_M0 ... more

Revision:
0:2359961af424
Child:
2:7f2f00805d41
diff -r 000000000000 -r 2359961af424 Debouncer.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Debouncer.h	Mon May 18 12:57:27 2015 +0000
@@ -0,0 +1,49 @@
+/* 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;
+    bool now;
+    int _samples;
+    uint32_t previous;
+    void tick(void);
+
+public:
+    Debouncer(PinName pin, PinMode mode = PullUp);
+    Debouncer &samples(int 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);
+};