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.

In shortA state machine is the way to design controllers: traffic lights, protocols, button handlers.

Theory in plain words

Traffic light FSMREDRED + YELLOWGREENYELLOWtimer
Traffic light FSM

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

Detect the bit pattern 1011 (Mealy FSM)Try it Yourself

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.

The same FSM style in C
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;
    }
}
MachineOutput depends onProperty
Moorestate onlyoutputs change only at clock edges; more states
Mealystate and inputfewer states, outputs can react in the same cycle
Tip:Draw the diagram first, then fill a transition table (current state x input -> next state, output). If the table is complete, the code and the Verilog are almost mechanical.

Quick quiz

1. In a Moore machine the output depends on...

2. How is a state typically stored in C?