// ------ Universal FSM Template ----------
enum State {
STATE_IDLE,
STATE_ACTION,
STATE_RESULT,
STATE_ERROR
};
State currentState = STATE_IDLE; // enum var and assigned val to it
unsigned long stateEntryTime = 0;
// -- This Switch Case is the one time action when entering the new state --
void enterState(State newState){
currentState = newState; // assigning the new state to the old var
stateEntryTime = millis(); // starting the timer (can be used to timeout from a screen going back)
switch(newState)
{
case STATE_IDLE:
// One time action when entering IDLE
break;
case STATE_ACTION:
// One time action when entering ACTION
break;
case STATE_RESULT:
// One time action when entering RESULT
break;
case STATE_ERROR:
// One time action when entering ERROR
break;
}
}
// -- This Switch case handles transistion logic and the running logic --
void fsmUpdate()
{
unsigned long now = millis();
switch (currentState)
{
case STATE_IDLE:
//check cond for transistion
// if(button pressed) -> enterState(STATE_ACTION);
break;
case STATE_ACTION:
// Monitor ongoing stuff
// if(timeout) -> enterState(STATE_RESULT)
// if(error) -> enterState(STATE_ERROR)
break;
case STATE_RESULT:
// stay here for some time or until reset
// if (now - stateEntryTime > 3000) -> enterState(IDLE)
break;
case STATE_ERROR:
// Recover or reset
// if (reset_cond) -> enterState(IDLE)
break;
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
enterState(STATE_IDLE); // starting here
}
void loop() {
fsmUpdate(); //always running
}