Computer science
State machines
Traffic light, turnstile, elevator: many machines remember a state and change it by fixed rules.
What you need first
A traffic light never shows just any colour. It is always in exactly one phase, and it only switches to the next one by fixed rules. A turnstile at the pool is either locked or unlocked, nothing in between. Computer science calls such machines state machines: they remember a state and only change it when a certain event occurs. This simple pattern sits inside traffic lights, elevators, washing machines, and countless programs.
States and transitions
Two ideas are enough to describe any state machine. The state is the situation the machine is currently in, for example green or locked. A transition is a rule for changing, and it can always be written as a sentence: when event X happens in state A, switch to state B. A whole machine is simply a list of such sentences. That is all a state diagram in words is.
The traffic light as a state machine
A traffic light in Germany has four states: red, then red and yellow together, then green, then yellow, and after that red again. Some countries have no red and yellow phase, but the pattern of states and transitions stays the same. The event that triggers each transition of the traffic light is simply an expired timer. In words: when the timer runs out in state red, switch to red and yellow. When the timer runs out in state green, switch to yellow. Four such sentences, and the cycle is fully described. Exactly this set of rules sits in the controller of every real traffic light.
The turnstile
The turnstile shows a second important idea: the same event can have a different effect depending on the state. It has two states, locked and unlocked, and two events, inserting a coin and pushing. A coin in the locked state unlocks the turnstile. Pushing in the unlocked state lets one person through and locks it again. Pushing in the locked state, however, does nothing, the turnstile stays shut. And a second coin in the unlocked state changes nothing either, the turnstile simply stays unlocked. So the machine does not react to the event alone, but to the combination of state and event.
Exercises
0 of 6 solvedTime to try it yourself. You can't break anything, every attempt counts.
What is the state of a state machine?
Which of these is a state of the traffic light?
What triggers a state machine's transition from one state to another?
A transition leads from one state to another as soon as a certain … occurs.
How many states does the traffic light cycle from the tutorial have?
The turnstile: match each combination of state and event to its result.