A4 · Lesson 21 · State machines
Code that remembers where it is
A push button doesn't close cleanly: for a few milliseconds its contacts bounce, and a program that counts every rising edge counts one press as five. A serial link delivers bytes one at a time, and the program has to know whether the next byte is a start marker, a length or data. A traffic light's next color depends on its present one. In each case the right response to an input depends on what has happened before, and the clean way to write that is a state machine: name the states, list how each input moves between them, and let the code follow the table.
Predict
A button is sampled every millisecond: 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0. How many times does it go from 0 to 1?
Four: at the second, fourth, tenth and sixteenth samples. But the person pressed it twice. The first press bounced (0, 1, 0, 1) before settling, and the release bounced too. Counting raw edges overcounts. A debouncing state machine that only changes its mind after three equal samples in a row reports two presses.
Name it
States, inputs and transitions
A state machine has:
- a set of states, one of which it's in at any moment, such as
RELEASEDandPRESSED; - inputs that arrive one at a time, such as a sample or a byte;
- transitions: for each state and input, the next state;
- outputs: what it does, either in each state (a Moore machine: the light is red while in
RED) or on each transition (a Mealy machine: count a press when moving fromRELEASEDtoPRESSED).
Writing one as a table
When states and inputs are few, a dictionary is the whole machine:
NEXT = {("RED", "tick"): "GREEN", ("GREEN", "tick"): "YELLOW", ("YELLOW", "tick"): "RED"}
state = "RED"
for event in ["tick", "tick", "tick", "tick"]:
state = NEXT[(state, event)]
print(state) # GREEN
A missing (state, input) pair raises KeyError, which is good while you're testing: it tells you about a case you forgot. Use NEXT.get((state, event), state) only when "ignore it and stay put" really is the rule.
Writing one as a class
When a state carries data, such as a counter or a buffer, wrap the state and its data in a class with a step(input) method:
class Debouncer:
def __init__(self, n=3):
self.n, self.state, self.run = n, 0, 0
def step(self, x):
if x != self.state:
self.run += 1
if self.run >= self.n:
self.state, self.run = x, 0
return self.state == 1 # True on a debounced press
else:
self.run = 0
return False
The run counter is part of the state: the machine is really "released, and has seen two highs in a row". Writing it this way keeps that detail out of the code that uses the debouncer.
Draw it first
A state diagram, circles for states and arrows labeled with inputs, catches missing cases before any code is written: every state needs an arrow for every input. The same machines run in firmware (C12), in logic (C7) and in protocol stacks.
Worked example
Debounce the samples 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0 with a machine that changes state after three equal samples in a row, and count presses.
Show the solution
- Run the samples through the debouncer. Summing its
Truereturns counts the presses.
raw = [0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0]
d = Debouncer(3)
presses = sum(d.step(x) for x in raw)
print(presses) # 2
- The press bounce. Counting from 1, sample 2 is a single high that resets when a 0 follows, so nothing happens.
- The first press. Samples 4, 5 and 6 are three highs in a row, and the state becomes 1 at the sixth sample.
- The release. It bounces (0, 1, 0), and the state returns to 0 after the 0s at samples 11, 12 and 13.
- The second press. The 1s from sample 16 on make it.
- The cost. A delay of three samples, 3 ms here, which no one notices.
Answer the debouncer counts 2 presses, at the price of a three-sample (3 ms) delay.
Worked example
A link sends frames as a start byte 0x7E, a length byte, that many data bytes, and an XOR checksum of the data. Pull the frames out of the stream 0x00, 0x7E, 0x02, 0x41, 0x42, 0x03, 0x7E, 0x01, 0x55, 0x55.
Show the solution
- Parse with four states. Hunt for the start byte, read the length, collect the data, then check the sum.
def frames(stream):
state, out = "HUNT", []
for b in stream:
if state == "HUNT":
if b == 0x7E:
state = "LEN"
elif state == "LEN":
n, buf = b, []
state = "DATA" if n > 0 else "SUM"
elif state == "DATA":
buf.append(b)
if len(buf) == n:
state = "SUM"
elif state == "SUM":
c = 0
for x in buf:
c ^= x
out.append((bytes(buf), c == b))
state = "HUNT"
return out
print(frames([0x00, 0x7E, 0x02, 0x41, 0x42, 0x03, 0x7E, 0x01, 0x55, 0x55]))
# [(b'AB', True), (b'U', True)]
- Hunt. The leading 0x00 is ignored while hunting.
- The first frame. It carries 0x41 0x42 ("AB") with checksum 0x41 ^ 0x42 = 0x03, which matches.
- The second frame. It carries 0x55 ("U") with checksum 0x55, which matches too.
- What the state does. Each byte's meaning depends entirely on the state, and the state is the only thing the parser needs to remember between bytes.
Answer two frames, "AB" (0x41 0x42) and "U" (0x55), both with good checksums.
Worked example
A traffic light stays green 5 s, yellow 2 s and red 4 s, starting green. Write it as a Moore machine and list its color each second for 12 s.
Show the solution
- Put the timing in a table. It holds each state's duration and successor.
- Count down each second. Record the color, and when the time runs out move to the next state.
PLAN = {"GREEN": (5, "YELLOW"), "YELLOW": (2, "RED"), "RED": (4, "GREEN")}
state, left, colors = "GREEN", 5, []
for t in range(12):
colors.append(state)
left -= 1
if left == 0:
state = PLAN[state][1]
left = PLAN[state][0]
print(colors)
# 5 × GREEN, 2 × YELLOW, 4 × RED, then GREEN again
- Change it easily. Since the table holds each state's duration and successor, changing the timing or adding a state is a one-line edit.
- Name the kind of machine. The output depends only on the state, which is what makes it a Moore machine.
Answer five seconds of green, two of yellow and four of red, then green again.
Check
Write a class Debouncer(n) whose step(x) takes a 0 or 1 sample, changes the debounced state only after n = 3 samples in a row that differ from it, and returns True exactly when the state changes from 0 to 1. Then set presses to the number of presses it finds in the starter's samples raw.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write frames(stream) for the framing in the second example (0x7E, a length, the data, then the XOR checksum of the data), returning a list of (data_bytes, ok) pairs. Set got = frames(stream) for the stream the starter picks.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
A vending machine takes coins of 5, 10 and 25 cents. Its state is the credit so far. When the credit reaches price = 50 cents it dispenses, returns the change, and goes back to zero credit. Write vend(coins, price) returning (items, change): how many items it dispensed, and the list of change amounts it returned, for the coins the starter picks.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write count_matches(bits, pattern) that counts every place a pattern of bits occurs in a stream, overlaps included (so 1, 0, 1, 0, 1 holds the pattern 1, 0, 1 twice), by stepping a state machine one bit at a time: the state is how many bits of the pattern currently match. Set n = count_matches(bits, pattern) for the starter's stream and pattern.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
A traffic light holds green for g = 5 s, yellow for y = 2 s and red for r = 6 s, starting green. Using a table of durations and successors, set colors to the list of its color ("GREEN", "YELLOW" or "RED") at each whole second from 0 to 59, and red_frac to the fraction of those seconds that are red.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
A state machine is stored as NEXT = {(state, input): next_state} and stepped with state = NEXT[(state, x)]. An input arrives that the table has no entry for in the present state. What happens?
Explain why
Why is a state machine easier to get right than a tangle of flags and if statements that does the same job?
A state machine forces you to name every situation the code can be in and to decide, for each one, what every input does. Written as a table or a diagram, a missing case is visible as a blank entry, and each transition can be tested on its own. Flags and nested ifs encode the same situations implicitly, as combinations of variables, so impossible combinations can sneak in and missing cases hide inside conditions nobody wrote down. The machine also makes the program's memory explicit: the state is the only thing carried from one input to the next.
Practice
Keep practicing
7 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.