Session 17: State machines
Learning outcomes
- Describe a behaviour as a state table
- Implement a timed state machine with a state variable and stateStart
- Explain why every state change must record stateStart
- Plan a state machine with a button event
Kit and components
- Uno, red, amber and green LEDs with 330 Ω resistors, push button, breadboard
Pre-reading about 20 min
Students read these on their phones before class. They are listed on the student Before class page.
Session plan
- 0:0010 minRecap
Quiz: millis()
- 0:1020 minDemo
From table to code
Draw the traffic light state table and turn each row into one branch. Remove stateStart = millis() and show the lights racing through the states.
- 0:3015 min
- 0:4530 minBuild
Traffic light: Code Along at the bench
One activity, not two: students write the traffic light in Code Along until it passes, then upload the same sketch to red, amber and green LEDs on the bench and add a Serial report of each state change. There is no separate build of the lesson's example 2.
- 1:1525 minCode Along
Catch-up and check
Time saved by building the traffic light once. Students finish any S16 timing exercises still open while you check each traffic light against its state table. Students who are up to date start the pedestrian crossing state table early.
- 1:4020 minPlan
Design a pedestrian crossing
In pairs, students write a state table for the lesson challenge's pedestrian button - the planning style Task A needs.
Checkpoint: ready to move on?
Students have a working traffic light driven by a state variable, and a written state table for the pedestrian version.
Extension for fast finishers
Code the pedestrian crossing from the state table.
Catch-up path
Code the two-state flasher first, then add the third state.
Homework and practice
Pre-reading for S18; finish the pedestrian crossing state table if it is not done.
Facilitator notes
- Students who can write a state table before coding will find Task A much easier.