How to code a Finite State Machine

This page wants to show an easy procedure to overcome the pain of implementing in whatever language you want a Finite State Machine.

Simple example

Let's take a simple state machine:

The state machine can be always represented using a matrix form:

origin\destinationstate 0state 1
state 0--transition 1 = f01()
state 1transition 2 = f10()--

 

A state machine has always a set of inputs and outputs. These includes the variable that are used for checking the transitions and the variables changes in the various states.

the state machine function has to keep in memory always the last status.

!!! At the first FSM function call the last status is the default value (in the above scheme is state 0)

Since we defined the state machine in matrix form we can say that the last_status corresponds to the matrix row index.

For the sake of convenience the last_status can be integrated in the inputs.

Since we change the state we have inside the outputs also the new state:

A set of parameters could be also present:

Each state acts on the outputs. For example:

For each state we can define the function associated that is executed when we enter the state:

For associating the function to the state we can build an array of function references that matches the state "column" array:

Let's define the transition function. These function shall return always a bool in order to describe if the transition is activated or not. For example:

 

Now we have to associate each transition to the states. We do by following the matrix we defined before:

Now we can write the state machine main function:

 

To run the state machine :

 

Why should we bother to do all of this?

In the above example an if else would have been the best solution but when the problem scales up, a spaghetti code made of if and switch instruction is not desirable.

If we take for example this 10 state FSM, in which every state is connected to the others:

 

This FSM can be easily described with the state matric form:

And by using the same fsm_step and fsm_execute() , with appropriate inputs,outputs and parameters and all the function defined; the state machine is implemented without caring to handle branches.

Final considerations

This is a simplified implementation model of a FSM. But can be extended.

For example if we need timers in states an additional matrix that saves the current_time for each evaluated state is needed in order to compare the elapsed time from the state activation and the running time for comparisons.