Hi, I have a problem. I keep failing with using debouncing to cycle a state machine.
In this example, I want to have one button to go up one state, and one button to go down one state, with debounce features. This should be obvious; I just don't understand enough yet.
When I press either of the two buttons, serial shows going through all the states to the max, or min value. Why does it skip through them, and not cycle each state individually? I don't understand what I've missed. Thank you.
#include <Bounce2.h>
#define BUTTON_PIN_1 2
#define BUTTON_PIN_2 3
#define LED_PIN 13
//global ints
int state = 0;
int old = 0;
Bounce debouncer1 = Bounce();
Bounce debouncer2 = Bounce();
void setup() {
Serial.begin(9600);
// Setup the first button with an internal pull-up :
pinMode(BUTTON_PIN_1,INPUT_PULLUP);
// After setting up the button, setup the Bounce instance :
debouncer1.attach(BUTTON_PIN_1);
debouncer1.interval(50); // interval in ms
// Setup the second button with an internal pull-up :
pinMode(BUTTON_PIN_2,INPUT_PULLUP);
// After setting up the button, setup the Bounce instance :
debouncer2.attach(BUTTON_PIN_2);
debouncer2.interval(50); // interval in ms
//Setup the LED :
pinMode(LED_PIN,OUTPUT);
}
void loop() {
// Update the Bounce instances :
debouncer1.update();
debouncer2.update();
// Get the updated value :
int value1 = debouncer1.read();
int value2 = debouncer2.read();
// Turn on the LED if either button is pressed :
if ( value1 == LOW ) {
digitalWrite(LED_PIN, HIGH );
state = old + 1;
}
else {
digitalWrite(LED_PIN, LOW );
}
if ( value2 == LOW ) {
digitalWrite(LED_PIN, HIGH );
state = old - 1;
}
else {
digitalWrite(LED_PIN, LOW );
}
switch (state) {
case 1:
Serial.println("one");
old = 1;
break;
case 2:
Serial.println("two");
old = 2;
break;
case 3:
Serial.println("three");
old = 3;
break;
case 4:
Serial.println("four");
old = 4;
break;
}}