Implementing finite state machines in embedded systems

A finite state machine is one of the most popular design patterns in embedded systems. Many applications from simple home appliances to complex communication systems implement event based state machines.

The finite state machine is made up of multiple states. At any point of time, the system is in one state and an event triggers certain actions in that state along with a possible change in state. The event could be due to an interrupt in the system, an RTOS signal, a timer expiry indication or an input or indication from another module in the system.

In this article, we will look into the different approaches for implementing state machines using C.

Figure 1 shows a sample state machine for a coffee vending machine. It has three states:

Idle,

Coin Inserted and

Option Selected.

The system waits on user inputs and signals from the coffee dispensing unit. Additional events like debug timer expiry signal could be added.

Figure 1 Sample state machine for a coffee vending machine (Source: The author)

There are two common approaches for implementing an event based state machine like the one above:

Using conditional statements

Using lookup table

Using conditional statements

This is a very simple approach. A switch-case statement or if-else statement is used to check each state. Within each state, another conditional statement is added to check the event triggered. A handler is then added for that state/event combination. Alternatively, we could swap the order and check the event first and then the state. If there is a state change involved, the handler returns the new state.