Saturday, 21 October 2017

State machienes













There are two common approaches for implementing an event based state machine.
  1. Using conditional statements
  2. 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.
A sample implementation for the state machine is shown below.
 

Table based approach
In this approach, the state machine is coded in a table with one dimension as states and the other as events. Each element in the table has the handler for the state/event combination. The table could be implemented in C using a two-dimensional array of function pointers.
An example implementation for the coffee vending machine is shown below.


No comments:

Post a Comment