Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 37 ยท Projects and Practice

Project: Traffic Light State Machine

Build a pedestrian-crossing traffic light with Arduino: wiring, a non-blocking finite state machine driven by millis(), a debounced button, and a simulation to test the logic.

A traffic light looks simple: red, green, yellow, repeat. The pedestrian crossing makes it interesting, because a button press arrives at an unpredictable moment, and the light must react safely without breaking its timing rules. This project teaches the most useful structure in embedded programming: the finite state machine, written so the sketch never blocks on delay().

The real circuit and sketch need an Arduino, which this site cannot run. The Arduino code is real and read-only. The C program is a labelled stand-in: the same state machine driven by a fake clock and scripted button presses, so you can test the logic and see the timeline.

What you need

  • Arduino Uno (or similar)
  • Three LEDs for the cars: red, yellow, green, each with a 220 ohm resistor
  • Two LEDs for the pedestrians: red and green with resistors (optional)
  • A push button and jumper wires

Wiring: car red to pin 2, yellow to 3, green to 4; pedestrian red to 5, green to 6; the button between pin 7 and ground (using the internal pull-up, so pressed reads LOW). Every LED goes through its resistor to ground. Use the digital I/O skills from the earlier chapters: pinMode, digitalWrite, INPUT_PULLUP.

Design the states

A state machine has a set of states, one active at a time, and rules for moving between them. Draw it before coding:

stateDiagram-v2
  [*] --> CarsGreen
  CarsGreen --> CarsYellow: button pressed and 5 s passed
  CarsYellow --> CarsRed: 2 s
  CarsRed --> WalkGreen: 1 s
  WalkGreen --> WalkRed: 6 s
  WalkRed --> CarsGreen: 1 s

Cars get green by default; a button request starts the crossing sequence after a minimum green time.

Each state defines: which LEDs are on, how long the state lasts, and what comes next. Two safety rules fall out: cars must never be green while pedestrians are green, and there is always an "all red" gap between phases.

The sketch

C++
enum State { CARS_GREEN, CARS_YELLOW, CARS_RED, WALK_GREEN, WALK_RED };

const int CAR_RED = 2, CAR_YEL = 3, CAR_GRN = 4;
const int PED_RED = 5, PED_GRN = 6;
const int BUTTON = 7;

const unsigned long MIN_GREEN_MS = 5000;
const unsigned long YELLOW_MS = 2000;
const unsigned long ALL_RED_MS = 1000;
const unsigned long WALK_MS = 6000;

State state = CARS_GREEN;
unsigned long stateStart = 0;
bool walkRequested = false;

void setLights(bool cr, bool cy, bool cg, bool pr, bool pg) {
  digitalWrite(CAR_RED, cr);
  digitalWrite(CAR_YEL, cy);
  digitalWrite(CAR_GRN, cg);
  digitalWrite(PED_RED, pr);
  digitalWrite(PED_GRN, pg);
}

void enter(State next) {
  state = next;
  stateStart = millis();
  switch (state) {
    case CARS_GREEN:  setLights(0, 0, 1, 1, 0); break;
    case CARS_YELLOW: setLights(0, 1, 0, 1, 0); break;
    case CARS_RED:    setLights(1, 0, 0, 1, 0); break;
    case WALK_GREEN:  setLights(1, 0, 0, 0, 1); break;
    case WALK_RED:    setLights(1, 0, 0, 1, 0); break;
  }
}

void setup() {
  const int outputs[] = {CAR_RED, CAR_YEL, CAR_GRN, PED_RED, PED_GRN};
  for (int i = 0; i < 5; i++) {
    pinMode(outputs[i], OUTPUT);
  }
  pinMode(BUTTON, INPUT_PULLUP);
  enter(CARS_GREEN);
}

void loop() {
  unsigned long elapsed = millis() - stateStart;

  if (digitalRead(BUTTON) == LOW) {
    walkRequested = true;           // remember the request, whatever the state
  }

  switch (state) {
    case CARS_GREEN:
      if (walkRequested && elapsed >= MIN_GREEN_MS) enter(CARS_YELLOW);
      break;
    case CARS_YELLOW:
      if (elapsed >= YELLOW_MS) enter(CARS_RED);
      break;
    case CARS_RED:
      if (elapsed >= ALL_RED_MS) enter(WALK_GREEN);
      break;
    case WALK_GREEN:
      if (elapsed >= WALK_MS) {
        walkRequested = false;
        enter(WALK_RED);
      }
      break;
    case WALK_RED:
      if (elapsed >= ALL_RED_MS) enter(CARS_GREEN);
      break;
  }
}

How it works:

  • enum State gives states readable names instead of magic numbers.
  • enter() is the only place where a state starts: it records the time and sets the lights, so the lights always match the state.
  • loop() checks the elapsed time in the current state and decides whether to move on. There is no delay(), so the button is read hundreds of times per second. The request is remembered in walkRequested, so a press during the red or walk phase is not lost, and a press while the light is still in minimum green waits its turn.
  • The button is read without debouncing, because it only sets a flag; bounces cause no harm. If you counted presses you would need debouncing (see the practice problems).

Stand-in: simulate the timeline

The program below uses a fake clock that advances in 100 ms steps and a scripted button press, running the identical logic and printing each transition.

C Stand-in: traffic light state machine simulation (C)

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.

Notice that the press at 2000 ms is accepted immediately but the yellow phase waits until the minimum green of 5000 ms has passed. Change button_presses[0] to 7000 and the sequence starts at once.

Extensions

  1. Blinking walk signal: in the last two seconds of WALK_GREEN, blink the pedestrian green using (millis() / 250) % 2.
  2. Night mode: hold the cars on flashing yellow when a light sensor (see the analog chapter for reading analog inputs) says it is dark.
  3. Two roads: add a second set of lights and a state table for the cross phases.
  4. Table-driven design: store {lights, duration, next} in an array of structs and loop through it, so changing timings needs no new code.
  5. Add a buzzer that beeps during WALK_GREEN for blind pedestrians (use tone()).

Why state machines matter

The same structure runs elevators, washing machines, vending machines, game logic, communication protocols and robot behavior. When a sketch grows "if" statements that nobody can follow, step back, list the states and transitions, and rewrite it as a machine. It makes the behavior visible, testable (as the simulation shows) and safe: illegal combinations are impossible because lights are set in one place.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main reason this sketch avoids delay()?

    With non-blocking timing the loop runs continuously, so button presses are noticed at any moment.
  2. 2. Why is there an all-red phase between car traffic and pedestrians?

    A clearance gap is a safety margin: cars stop completely before the walk signal starts.
  3. 3. What does the variable walkRequested accomplish?

    A press can arrive at any time; the flag keeps it until the machine reaches a state that can handle it.
  4. 4. Where should the lights for a state be set in this design?

    Setting lights in enter() keeps outputs consistent with the state and prevents illegal combinations.

Summary

  • A finite state machine has named states, durations and transitions; enter() sets outputs and records the time.
  • Compare millis() - stateStart with each state's duration instead of calling delay().
  • Remember asynchronous events (a button press) with a flag.
  • Simulating the logic with a fake clock lets you test timing before wiring anything.

Next: Project: Data Logger