Minh Nguyen / Pushbutton
Revision:
1:e47e80a32fb5
Parent:
0:4482075b8b95
Child:
2:6ade0fbab4e1
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Pushbutton.cpp	Sun Feb 28 03:26:11 2021 +0000
@@ -0,0 +1,75 @@
+//INCLUDES
+#include "Pushbutton.h"
+
+#define timer_read_s(x)     chrono::duration_cast<chrono::seconds>((x).elapsed_time()).count()
+
+DigitalIn Pushbutton::lastPressed(PIN_ACCEL_PANEL);
+
+//Constructor
+Pushbutton::Pushbutton(PinName bt) : button(bt),buttonInt(bt){
+    busy = 0;
+}
+Pushbutton::Pushbutton(PinName bt, int* state) : buttonInt(bt),button(bt){
+    busy = 0;
+    mode = state;
+    if(INPUT_LOGIC == 0)
+    {
+        buttonInt.fall(callback(this,&Pushbutton::updateMode));
+    }
+    else
+    {
+        buttonInt.rise(callback(this,&Pushbutton::updateMode));
+    }
+}
+
+//Methods
+//read()
+int Pushbutton::read(){
+    if(Pushbutton::lastPressed == INPUT_LOGIC && Pushbutton::lastPressed != button)
+        return 0;
+    else if(Pushbutton::lastPressed == INPUT_LOGIC && Pushbutton::lastPressed == button)
+        return 1;
+    
+    wait_us(DEBOUNCE_TIME);
+    
+    Pushbutton::lastPressed = (button == INPUT_LOGIC) ? button : Pushbutton::lastPressed;
+    busy == (button == INPUT_LOGIC) ? 1 : 0;
+    return (button == INPUT_LOGIC) ? 1 : 0;
+}
+
+//updateMode()
+void Pushbutton::updateMode()
+{   
+    Timer t;
+    t.start();
+    
+    wait_us(DEBOUNCE_TIME);
+    if(read()) //If received input
+    {
+        while((int)timer_read_s(t) <= TIME_WSETTING) //check if button is held to the threshold
+        {
+            if(buttonInt.read() != INPUT_LOGIC) //check if button is released
+            {
+                if(*mode == OP_NORMAL || *mode == OP_WIND)
+                {
+                    *mode = OP_MANUAL1;
+                    return;
+                }
+                else if(*mode == OP_MANUAL1)
+                {
+                    *mode = OP_MANUAL2;
+                    return;
+                }
+                else if(*mode == OP_MANUAL2 || *mode == OP_WSETTING)
+                {
+                    *mode = OP_NORMAL;
+                    return;
+                }
+                t.stop();
+                return;
+            }
+        }
+        *mode = OP_WSETTING;
+        return;
+    }
+}