Home / Learn Chip Programming / Finite State Machines (FSM)
Finite State Machines (FSM)
A state machine is the way to design controllers: traffic lights, protocols, button handlers.
Theory in plain words
What it is
An FSM has a finite number of states, inputs and transitions. Moore machines output depends on the state; Mealy outputs also depend on the input.
Why we use it
Every embedded controller is an FSM. Writing it as a table makes the logic testable and prevents spaghetti code.
How it works
List the states, draw arrows for each input, assign outputs. In hardware the state is stored in flip-flops and next-state logic is combinational. In C the state is a variable and a switch statement.
Where it is used
- Traffic light, vending machine, elevator
- Protocol parsers (UART, I2C start/stop, USB enumeration)
- Button debounce and menu navigation
Sequence detector
Enter 1 0 1 1: the counter goes S1, S2, S3 and then the last 1 gives a hit. The overlapping input 1 0 1 1 0 1 1 gives two hits.
typedef enum { RED, RED_YELLOW, GREEN, YELLOW } state_t;
static state_t state = RED;
void traffic_tick(void) { // call this every second
static uint8_t t = 0;
t++;
switch (state) {
case RED: set_lights(1,0,0); if (t >= 10) { state = RED_YELLOW; t = 0; } break;
case RED_YELLOW: set_lights(1,1,0); if (t >= 2) { state = GREEN; t = 0; } break;
case GREEN: set_lights(0,0,1); if (t >= 10) { state = YELLOW; t = 0; } break;
case YELLOW: set_lights(0,1,0); if (t >= 3) { state = RED; t = 0; } break;
}
}| Machine | Output depends on | Property |
|---|---|---|
| Moore | state only | outputs change only at clock edges; more states |
| Mealy | state and input | fewer states, outputs can react in the same cycle |
Quick quiz
1. In a Moore machine the output depends on...
Mealy also uses the current input.
2. How is a state typically stored in C?
An enum and a switch statement is the standard pattern.