Lesson 31: State machine
One state at a time
- Many machines are always in one state: a turnstile is LOCKED or UNLOCKED, a washing machine is filling, washing or spinning.
- An input (a coin, a push) can move the machine to another state. The same input can do different things in different states.
- A program like this is a state machine. In C++ it is a
switchwith onecasefor each state.
Words for this lesson
| Word | Meaning |
|---|---|
| state | what the machine is doing now |
| transition | a change from one state to another |
| turnstile | a gate that lets one person through at a time |
| switch / case | choose the code for the value of a variable |
The turnstile's table
| State | Input | Next state |
|---|---|---|
| LOCKED | coin | UNLOCKED |
| LOCKED | push | ALARM |
| UNLOCKED | push | LOCKED |
| UNLOCKED | coin | UNLOCKED |
| ALARM | 1 s passes | LOCKED |
- The outputs: going to UNLOCKED prints
UNLOCKED; going to ALARM printsALARMand starts the tone; leaving ALARM stops the tone. A coin when UNLOCKED has no output.
switch in C++
void setup() {
Serial.begin(9600);
int state = 1;
switch (state) {
case 0:
Serial.println("LOCKED");
break;
case 1:
Serial.println("UNLOCKED");
break;
}
}
void loop() {
}
stateis 1, so onlycase 1runs and the sketch printsUNLOCKED.breakends theswitch.
In the exam
A-Level Computer Science (9618) Paper 2 asks you to read and draw state-transition diagrams: each state is a circle, each arrow is a transition labelled input | output, and START points to the first state.
- 9618/21/M/J/22 Q2: a diagram with buttons X, Y and Z: count the states and inputs, and follow the arrows.
- 9618/21/O/N/23 Q7: a table like the one above (current state, input, output, next state): draw the diagram from it.
רמת קושי 4/5 · 280 מטבעות + בונוס קטן בהשלמה הראשונה היום
A turnstile at a station is LOCKED (red light) or UNLOCKED (green light). A coin (button on pin 2) unlocks it; a push (button on pin 3) when it is unlocked lets one person through and locks it again. Other inputs change nothing. The sketch has a switch with the LOCKED case. Add the UNLOCKED case.
לחץ על הרץ כדי לראות את התוצא כאן.
רמת קושי 5/5 · 400 מטבעות + בונוס קטן בהשלמה הראשונה היום
Add a third state, ALARM. A push while the turnstile is LOCKED starts the alarm: print ALARM, play a 1000 Hz tone on pin 8 and keep the time in alarmStart. In the ALARM state, after 1000 ms the alarm stops by itself (noTone) and the turnstile is LOCKED again. A timed change needs no input.
לחץ על הרץ כדי לראות את התוצא כאן.