Debounce and latch a button input

Dependencies:   mbed

Revision:
0:59aa41d04f51
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Debounce.cpp	Mon Jun 02 06:47:09 2014 +0000
@@ -0,0 +1,38 @@
+#include "mbed.h"
+
+Serial pc(USBTX, USBRX);
+DigitalIn btn(USER_BUTTON);
+DigitalOut led(LED1);
+Timer timer;
+Timer debounce;
+
+bool state = false;
+bool prevState = false;
+bool counting = false;
+
+int main() {
+    while(true) {
+        state = btn;
+        if(state != prevState) {
+            debounce.start();
+        }
+        if(debounce.read_ms() > 20) {
+            debounce.stop();
+            debounce.reset();
+            if(!state) {
+                if(!counting) {
+                    counting = true;
+                    led = true;
+                    timer.start();
+                } else {
+                    counting = false;
+                    led = false;
+                    timer.stop();
+                    pc.printf("%i ms\n", timer.read_ms());
+                    timer.reset();
+                }
+            }
+        }
+        prevState = state;
+    }
+}
\ No newline at end of file