Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Projects and Practice

Project: Traffic Light Controller as a State Machine

Build a traffic light controller with a table-driven finite state machine, a pedestrian request button and a safety test, in C that runs on a PC and ports to a microcontroller.

Almost every embedded product is, at heart, a state machine: a washing machine, a microwave, a vending machine, a remote control, a communication protocol. The device is always in exactly one state, and events (a button, a timer expiry, a received byte) move it to another state while triggering actions. Writing the machine explicitly, instead of scattering flags through the code, makes behavior easy to read, easy to test and easy to prove safe.

In this project you will build a traffic light controller for a two-road crossing with a pedestrian button. The logic is plain C with no hardware access, so it runs on this page. Afterwards we map it onto a real board.

Requirements

  1. Two roads: north-south (NS) and east-west (EW). Each has a red, yellow and green lamp.
  2. The cycle is: NS green 10 s, NS yellow 3 s, all red 2 s, EW green 10 s, EW yellow 3 s, all red 2 s, repeat.
  3. A pedestrian button can be pressed at any time. The request is remembered, and at the next all-red phase the controller adds a 6 s "walk" phase (all vehicle lamps red) before continuing.
  4. Safety: the two roads must never both show green or yellow at the same time, and every green must pass through yellow and an all-red phase.

The design

stateDiagram-v2
    [*] --> NS_GREEN
    NS_GREEN --> NS_YELLOW: 10 s
    NS_YELLOW --> RED_A: 3 s
    RED_A --> EW_GREEN: 2 s, no request
    RED_A --> WALK: 2 s, request pending
    WALK --> EW_GREEN: 6 s
    EW_GREEN --> EW_YELLOW: 10 s
    EW_YELLOW --> RED_B: 3 s
    RED_B --> NS_GREEN: 2 s, no request
    RED_B --> WALK: 2 s, request pending
    WALK --> NS_GREEN: 6 s (resumes the other direction)

The WALK state is entered only from an all-red state and returns to whichever direction was due next.

The machine is table-driven: a constant array describes each state (its name, its duration and its lamp colors), and one small function decides the next state. That separates data (what each phase looks like) from logic (how to move on), so changing a timing is a one-line edit. The machine has a single entry point, fsm_tick, that you call once per second from a timer. This is a Moore machine: the outputs (lamps) depend only on the current state.

Two details are worth noticing. The pedestrian button only sets a flag (ped_req); the machine looks at the flag at a safe moment. This is the same "ISR sets a flag, the main loop acts" pattern from the interrupts lesson. And the resume field remembers which direction should follow the walk phase.

C The traffic light state machine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check the output against the requirements. The button pressed at 12 s (during NS yellow) is served at the next all-red phase; the second press at 14 s merges with the first (a flag, not a counter, which is correct here: one walk phase serves everyone waiting). The press at 60 s triggers a walk in the following all-red gap, after which the controller resumes with the direction that was due.

Testing the safety property

The requirement "never both green" is exactly the kind of property you want a test to prove. Because the machine is a pure function of its inputs, you can simulate thousands of random button presses and check the invariants after every tick. This is a tiny example of property-based testing; the idea carries over to any state machine.

C Random stress test of the safety invariants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Zero violations over a hundred thousand simulated seconds is not a formal proof, but a table-driven machine of this size can be fully verified by reading its seven rows, and the stress test guards against future edits that accidentally add a bad transition. Add a failing case on purpose (for example, make RED_A return NS_GREEN) and watch the test catch it.

Porting to a microcontroller

Only three things change on real hardware:

  1. Time base. Call fsm_tick from a 1 Hz timer interrupt, or from the main loop when a software timer fires, instead of a for loop.
  2. Inputs. The button sets ped_req from a debounced input, in an interrupt or the main loop (a volatile flag, since an ISR writes it).
  3. Outputs. Replace show() with GPIO writes: a function set_lamps(ns, ew) that turns the six LED pins on and off according to the phase's colors.
C
// Read-only sketch for a board: map the state's colors to six GPIO pins
static void set_lamps(char ns, char ew) {
    gpio_write(NS_RED,    ns == 'R');
    gpio_write(NS_YELLOW, ns == 'Y');
    gpio_write(NS_GREEN,  ns == 'G');
    gpio_write(EW_RED,    ew == 'R');
    gpio_write(EW_YELLOW, ew == 'Y');
    gpio_write(EW_GREEN,  ew == 'G');
}

A real controller adds a fail-safe: if the machine reaches an undefined state or the watchdog resets the chip, the outputs must fall back to a safe pattern (flashing red or flashing yellow), and a conflict monitor (often a separate hardware circuit) forces that pattern if it ever sees two greens.

Extensions to try

  • Night mode: after midnight, flash yellow on the minor road and keep the main road green.
  • A vehicle sensor on the minor road that triggers its green only on demand.
  • A longer green for the main road depending on the time of day, from a table.
  • A countdown display for pedestrians (what changes in the table and what in the code?).
  • Log every state change into a ring buffer and dump it over a serial port.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In the traffic light machine, why is the button handler just 'ped_req = 1'?

    Events set flags; the state machine acts on them only at safe transitions, so the lamps never change mid-phase.
  2. 2. What makes a table-driven state machine easy to change?

    Changing a duration or a color is a one-line edit in the table, with no logic changes.
  3. 3. Which of these is a Moore machine property?

    In a Moore machine outputs are a function of the state alone; in a Mealy machine they also depend on the current input.
  4. 4. Why include a fail-safe pattern such as flashing red?

    Safety-critical outputs must default to a safe state when software or hardware fails.

Summary

  • A state machine makes behavior explicit: states, events, transitions and outputs.
  • A table of phases plus one next_state function keeps data and logic apart and makes changes safe.
  • Pure logic with no hardware access can be simulated and stress-tested on a PC, including safety invariants.
  • Porting needs only a time base, input flags and output pins; real systems add fail-safe behavior.

Next: Project: A Sensor Data Logger