State machine

Dependencies:   mbed Adafruit_GFX BioroboticsMotorControl MODSERIAL BioroboticsEMGFilter

Revision:
7:e7f808875bc4
Parent:
3:4b19b6cf6cc7
Child:
9:27d00b64076e
--- a/Button.h	Tue Oct 30 12:19:51 2018 +0000
+++ b/Button.h	Wed Oct 31 05:58:51 2018 +0000
@@ -2,17 +2,12 @@
 
 #include "mbed.h"
 
-// seconds that a button should be stable to be considered "pressed".
-// 50 ms.
-const float debounce_time = 0.05;
-
 class Button
 {
 private:
-    InterruptIn pin;
+    DigitalIn pin;
 
-    Timeout debounce_timeout;
-
+    volatile bool last_state;
     volatile bool pressed;
 
     volatile bool just_switched_to_pressed;
@@ -21,10 +16,34 @@
 public:
     Button(PinName pin_name):
         pin(pin_name) {
-        pin.rise(this, &Button::rise);
-        pin.fall(this, &Button::fall);
 
+        last_state = false;
         pressed = false;
+        
+        just_switched_to_pressed = false;
+        just_got_pressed = false;
+    }
+    
+    void poll_pin() {
+        // We need to poll the pins periodically.
+        // Normally one would use rise and fall interrupts, so this wouldn't be
+        // needed. But the buttons we use generate so much chatter that
+        // sometimes a rising or a falling edge doesn't get registered.
+        // With all the confusion that accompanies it.
+        
+        bool state = !pin;
+        
+        // Debounce the button by looking over two periods.
+        if (last_state && state) {
+            pressed = true;
+            just_switched_to_pressed = true;
+        }
+    
+        if (!state) {
+            pressed = false;
+        }
+        
+        last_state = state;
     }
 
     void update() {
@@ -45,20 +64,4 @@
     bool has_just_been_pressed() {
         return just_got_pressed;
     };
-private:
-    void rise() {
-        // Button is now potentially pressed, or is simply bouncing.
-        debounce_timeout.detach();
-        pressed = false;
-    }
-
-    void fall() {
-        // Button just got released, or bounced up again.
-        debounce_timeout.attach(this, &Button::debounce_callback, debounce_time);
-    }
-
-    void debounce_callback() {
-        pressed = true;
-        just_switched_to_pressed = true;
-    }
 };
\ No newline at end of file