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.
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
- Run the light for 6 ticks and count each colour.
- Step through 3 ticks and watch the state change.
- Run it for 12 ticks.
- Answer the practice challenges.