#define STATE_0 0
#define STATE_1 1
#define STATE_2 2
int state = STATE_0;
int counter;
void stateMachine() {
switch(state) {
case STATE_0 :
//check whether a state transition should be made
if(counter > 20) {
//set state to transition to
state = STATE_1;
//do actions on changing state
Serial.println("Switching to state 1");
counter = 0;
}
break;
case STATE_1 :
if(counter > 30) {
state = STATE_2;
Serial.println("Switching to state 2");
counter = 0;
}
break;
case STATE_2 :
if(counter > 40) {
state = STATE_0;
Serial.println("Switching to state 0");
counter = 0;
}
break;
}
}
setup {
Serial.begin(115200);
}
loop {
stateMachine();
// do other stuff
counter++;
delay(100);
}
Note that several different state machines can be called from the main loop to manage different activities. The counter in the example is just a trivial method to show transitions. Normally one might be testing for other conditions. State transitions can also be triggered by other activities. E.g. a button press or a web server call may change state and trigger a sequence of activities through further state transitions.