// Very simple Finite State Machine
// Forum: https://forum.arduino.cc/t/using-finite-state-machine/1114323/
// Tutorial: https://majenko.co.uk/blog/our-blog-1/the-finite-state-machine-26
// This Wokwi project: https://wokwi.com/projects/361809673037018113
const int buttonPin = 2;
const int redLedPin = 12;
const int greenLedPin = 13;
int lastButtonValue = HIGH; // default HIGH is not pressed.
enum
{
IDLE,
RED,
GREEN,
} state;
void setup()
{
pinMode( buttonPin, INPUT_PULLUP);
pinMode( redLedPin, OUTPUT);
pinMode( greenLedPin, OUTPUT);
}
void loop()
{
// ------------------------------------------------------
// Gather all the information from buttons and sensors.
// ------------------------------------------------------
// The variable 'buttonPressed' is passed on to the Finite State Machine.
bool buttonPressed = false; // default: button not pressed
// Checking the event that the button has just been pressed
// can be done with the finite state machine.
// I decided to that with a variable.
int buttonValue = digitalRead( buttonPin);
if( buttonValue != lastButtonValue) // something changed ?
{
if( buttonValue == LOW) // pressed just now ?
buttonPressed = true;
lastButtonValue = buttonValue; // remember for the next time
}
// ------------------------------------------------------
// Process the information with a Finite State Machine
// ------------------------------------------------------
// Changing the leds can be done with a intermediate state,
// depending on how much needs to be done before going
// to a new state.
switch( state)
{
case IDLE:
if( buttonPressed)
{
digitalWrite( redLedPin, HIGH);
state = RED;
}
break;
case RED:
if( buttonPressed)
{
digitalWrite( redLedPin, LOW);
digitalWrite( greenLedPin, HIGH);
state = GREEN;
}
break;
case GREEN:
if( buttonPressed)
{
digitalWrite( redLedPin, HIGH);
digitalWrite( greenLedPin, LOW);
state = RED;
}
break;
}
delay(20); // slow down the sketch, also to avoid button bouncing
}