Skip to content
Programming Computational thinking
All classes Beginner About 12 min Premium

A traffic light is a state machine

Run a traffic light for a number of ticks. A loop moves it from red to green to yellow and back to red, using one variable for the state and % to go round again. Count each colour's turns and predict the light at any tick.

Core concept

A state machine is always in one of a few states and moves to the next state by a rule; a traffic light keeps its state in a variable and goes round red, green, yellow with (state + 1) % 3

Topic: Computational thinking

A traffic light is always showing one colour: it is in one state. When its time is up, it moves to the next state by a fixed rule: red, then green, then yellow, then red again. Machines like this are called state machines, and lifts, washing machines and games are built the same way. A program can keep the state in a variable: A named box that holds a value the program can read and change. All key words: 0 for red, 1 for green and 2 for yellow. On each tick an IF chooses what to show for the state, then the state moves on with state ← (state + 1) % 3. The % 3 is the remainder after dividing by 3, so after 2 the state goes back to 0 instead of 3.

Key words explained

What you will learn

  • Explain what a state is and how a state machine moves from one state to the next.
  • Use a variable to hold the state and IF to act on it.
  • Use % to make the states go round in a cycle.
  • Predict the state after a number of ticks.

Before you start

  • Know how a FOR loop repeats and how IF / ELSE chooses.

Materials

  • A notebook to write the colours

Equipment

  • None

Procedure

  1. Run the light for 6 ticks and count each colour.
  2. Step through 3 ticks and watch the state change.
  3. Run it for 12 ticks.
  4. Answer the practice challenges.
Premium experiment Create a free account