I think basically this is incredibly simple but i can't work out why it's not working as intended. I want it so that every time the sketch is uploaded or power is cycled it always starts with case STATE 0. However when i upload the sketch or cycle power LED1 does not turn on. Then when i press the button LED1 lights up and every subsequent button press causes it to cycle through the states as expected. So why won't it start with case STATE 0? I can only get it to do this if i hold the button whilst i upload or cycle power. Just can't get my head round it. Any help would be greatly appreciated!
#include <Bounce2.h>
// Define the states
enum State {
STATE_0,
STATE_1,
STATE_2,
STATE_3
};
Bounce D10 = Bounce(10, 50);
State currentState = STATE_1; // Initial state
bool switchPressed = false; // Flag to track switch state
void setup() {
// Ensure currentState starts with STATE_1
currentState = STATE_0;
Serial.begin(9600);
pinMode(10, INPUT_PULLUP);
pinMode(3, OUTPUT); // pin 3 (the LED) is an output;
pinMode(4, OUTPUT); // pin 4 led
pinMode(11, OUTPUT); // pin 11 led
pinMode(12, OUTPUT); // pin 12 led
}
void loop() {
// SWITCH STATE CASES
// Check for falling edge of the switch
if (digitalRead(10) == LOW && !switchPressed) {
// Flag the switch as pressed
switchPressed = true;
switch(currentState) {
case STATE_0:
digitalWrite(3, HIGH);
digitalWrite(4, LOW);
digitalWrite(11, LOW);
digitalWrite(12, LOW);
break;
case STATE_1:
digitalWrite(3, LOW);
digitalWrite(4, HIGH);
digitalWrite(11, LOW);
digitalWrite(12, LOW);
break;
case STATE_2:
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(11, HIGH);
digitalWrite(12, LOW);
break;
case STATE_3:
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(11, LOW);
digitalWrite(12, HIGH);
break;
}
// Increment the state
currentState = static_cast<State>((currentState + 1) % 4);
// Debugging output
Serial.println("Switch pressed. Current state: " + String(currentState));
}
// Check for rising edge of the switch
if (digitalRead(10) == HIGH && switchPressed) {
// Reset the switch state flag
switchPressed = false;
// Debugging output
Serial.println("Switch released. Current state: " + String(currentState));
}
}