FSM recipe
This page provides a step-by-step recipie for implementing any state machine in C language. In the next page, we show how to use this recipe to implement the passcode example.
1. Start by identifying
FSM input(s)
FSM output(s)
FSM states
If you are unsure, do not worry; you will figure it out as you continue to build.
2. Draw your FSM.
3. In C, create a skeleton for your FSM.
3.1. Define enum for the states. Declare a state with the initial state. This has to be static.
3.2. Declare booleans or enums for your outputs. Assign default values to these outputs.
3.3. Build an empty switch-case-statement:
3.3.1. All states should be present in the skeleton
3.3.2. Put a break after each case.
3.4. In the switch-case statement, for each state:
Implement each transition arc (edge) based on the input conditions. For each edge,
3.4.1.Assign all the outputs that are different from default values
3.4.2. Assign the next state
3.5. If needed, take actions based on the Boolean FSM outputs (e.g., call ToggleLED() if bool Should_Toggle is true.)
3.6. If you have written the FSM function such that one of the boolean outputs is the returned value of the function, make sure to return it!