EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 17
State Machines in Firmware
A tidy way to organise behaviour over time.
A state machine has a list of states and rules for moving between them. A door lock might have Locked, Unlocked and Alarm states.
In code, use an enum for states and a switch inside the main loop. This avoids blocking delays, so the chip stays responsive to buttons and sensors.
Each pass of the loop checks inputs, decides whether to change state, and performs that state's action.
EXAMPLE
enum State { LOCKED, UNLOCKED };
enum State s = LOCKED;
for (;;) {
switch (s) {
case LOCKED: if (code_ok()) s = UNLOCKED; break;
case UNLOCKED: if (door_closed()) s = LOCKED; break;
}
}