There's a State in This Machine!

I came across this article from Massimiliano Pagani at https://www.embeddedrelated.com/ and found it very interesting.

He describes an "implicit state machine" which is what one may code quickly, and goes on to explain why that may not be the best way (scaling up, maintainability, etc).


Let's try a first attempt at coding the state machine:

void lightSwitcher()
{
  int lightOn = 0;
  while( true ) {
    gpioWrite( lightOn );
    if( justPressed() ) {
      lightOn ^= 1;
    }
  }
}

This is short and quick to write but somewhat obfuscates that this is a state machine. State, events, and transitions define a state machine, but we can see no explicit mention of any of them. This is an "implicit state machine", meaning that there is a state, but it is hidden in the conventional program state.

The full thing:

3 Likes

PS: Particle best practices for FSMs are here:

1 Like