Skip to content

Instantly share code, notes, and snippets.

@NormalUniverse
Created June 25, 2016 21:13
Show Gist options
  • Save NormalUniverse/4b8f0ca16632f1430498cf0325907753 to your computer and use it in GitHub Desktop.
Save NormalUniverse/4b8f0ca16632f1430498cf0325907753 to your computer and use it in GitHub Desktop.
Arduino sketch that creates a "Swith" class that handles debouncing
//***************************************************************************************************
//Defeinition of "Switch" class
//Should I change the name to avoid conflict with "switch" logical structure?
//***************************************************************************************************
//The switch
class Switch
{
public:
//Constructor, pin defines IO pin and t_bounce defines debouncing time
Switch(int pin, long t_bounce);
//steps the Finite State Machine (FSM) of the switch forward one cycle
void FSM();
//returns state of switch FSM
int getState();
//returns the raw value of the IO pin
int getValue();
private:
//hardware related
int _pin;
//used in finite state machine
int _state;
int _value;
//necessary timing variables
long _t_0;
long _t_bounce;
long _t;
};
Switch::Switch(int pin, long t_bounce)
{
//read out the pin assignment
_pin = pin;
pinMode(_pin,INPUT_PULLUP);
//initialize the FSM
_state = 0;
_value = 1; //pullup resistor used, to value is high when no other connection
//initialize _t and _t_0, read out debounce time
_t = millis();
_t_0 = millis();
_t_bounce = t_bounce;
}
void Switch::FSM()
{
_value = digitalRead(_pin);
switch(_state) { //Finite State Machine, see diagram
case 0:
if (_value == 0) {
_state = 1;
}
break;
case 1:
_t_0 = millis();
_state = 2;
break;
case 2:
//record current time for comparison
_t = millis();
if (_value == 1) { //if the user releases button, go back to start
_state = 0;
}
if (_t > (_t_0 + _t_bounce)) { //if the debounce buffer expires, arm
_state = 3;
}
break;
case 3:
if (_value == 1) {
_state = 4;
}
break;
case 4:
_state = 0;
break;
}
}
int Switch::getState()
{
return _state;
}
int Switch::getValue()
{
return _value;
}
//***************************************************************************************************
//Main Arduino Sketch
//***************************************************************************************************
Switch button1(7,10);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop() {
button1.FSM();
Serial.print("button 1 state = ");
Serial.println(button1.getState());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment