---
title: State machines
heading: Code that remembers where it is
eyebrow: A4 · Lesson 21 · State machines
xp: 40
---

::: hook
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?

- [ ] 2
- [x] 4
- [ ] 6
- [ ] 1

::: reveal
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.
:::
:::

::: nameit
## States, inputs and transitions

A state machine has:
- a set of **states**, one of which it's in at any moment, such as `RELEASED` and `PRESSED`;
- **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 from `RELEASED` to `PRESSED`).

## Writing one as a table

When states and inputs are few, a dictionary is the whole machine:

```python
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:

```python
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.
:::

::: 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.

::: solution
1. **Run the samples through the debouncer.** Summing its `True` returns counts the presses.

```python
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
```

2. **The press bounce.** Counting from 1, sample 2 is a single high that resets when a 0 follows, so nothing happens.
3. **The first press.** Samples 4, 5 and 6 are three highs in a row, and the state becomes 1 at the sixth sample.
4. **The release.** It bounces (0, 1, 0), and the state returns to 0 after the 0s at samples 11, 12 and 13.
5. **The second press.** The 1s from sample 16 on make it.
6. **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.
:::
:::

::: 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.

::: solution
1. **Parse with four states.** Hunt for the start byte, read the length, collect the data, then check the sum.

```python
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)]
```

2. **Hunt.** The leading 0x00 is ignored while hunting.
3. **The first frame.** It carries 0x41 0x42 ("AB") with checksum 0x41 ^ 0x42 = 0x03, which matches.
4. **The second frame.** It carries 0x55 ("U") with checksum 0x55, which matches too.
5. **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.
:::
:::

::: 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.

::: solution
1. **Put the timing in a table.** It holds each state's duration and successor.
2. **Count down each second.** Record the color, and when the time runs out move to the next state.

```python
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
```

3. **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.
4. **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
kind: python
given: n = 2 | 3 | 4; k = 1..5 int

## Write a class `Debouncer(n)` whose `step(x)` takes a 0 or 1 sample, changes the debounced state only after `n` = {n} 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 starter
import random
random.seed(k)
raw = []
for level in [0, 1, 0, 1, 0, 1, 0]:
    raw += [level, 1 - level, level, 1 - level] + [level] * random.randint(6, 12)

class Debouncer:
    def __init__(self, n):
        self.state = 0
    def step(self, x):
        rose = x == 1 and self.state == 0
        self.state = x
        return rose

d = Debouncer(n)
presses = sum(d.step(x) for x in raw)
print(presses)
```

```python solution
import random
random.seed(k)
raw = []
for level in [0, 1, 0, 1, 0, 1, 0]:
    raw += [level, 1 - level, level, 1 - level] + [level] * random.randint(6, 12)

class Debouncer:
    def __init__(self, n):
        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
        else:
            self.run = 0
        return False

d = Debouncer(n)
presses = sum(d.step(x) for x in raw)
print(presses)
```

```python tests
t = Debouncer(n)
assert [t.step(x) for x in [1] * (n - 1)] == [False] * (n - 1), f"Fewer than {n} highs in a row must not register."
assert t.step(1) is True, f"The {n}th high in a row should register a press."
t2 = Debouncer(n)
seq = ([1] * (n - 1) + [0]) * 5
assert not any(t2.step(x) for x in seq), "A run of highs broken by a low starts counting again."
assert presses == 3, f"The samples hold 3 real presses, but your debouncer found {presses}."
```

::: right
Right. A run of differing samples has to be unbroken, so any sample that agrees with the present state resets the counter. Each edge in the samples bounces before it settles, and the three presses still come out as three.
:::
:::

::: check
kind: python
given: k = 0..3 int

## 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 starter
streams = [[0x00, 0x7E, 0x02, 0x41, 0x42, 0x03, 0x7E, 0x01, 0x55, 0x55],
           [0x7E, 0x03, 0x01, 0x02, 0x03, 0x00, 0xFF, 0x7E, 0x02, 0x10, 0x20, 0x31],
           [0x7E, 0x00, 0x00, 0x11, 0x7E, 0x01, 0x7E, 0x7E],
           [0x12, 0x34, 0x7E, 0x02, 0xAA, 0x55, 0xFF, 0x7E, 0x01]]
stream = streams[k]

def frames(stream):
    return []

got = frames(stream)
print(got)
```

```python solution
streams = [[0x00, 0x7E, 0x02, 0x41, 0x42, 0x03, 0x7E, 0x01, 0x55, 0x55],
           [0x7E, 0x03, 0x01, 0x02, 0x03, 0x00, 0xFF, 0x7E, 0x02, 0x10, 0x20, 0x31],
           [0x7E, 0x00, 0x00, 0x11, 0x7E, 0x01, 0x7E, 0x7E],
           [0x12, 0x34, 0x7E, 0x02, 0xAA, 0x55, 0xFF, 0x7E, 0x01]]
stream = streams[k]

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

got = frames(stream)
print(got)
```

```python tests
want = [[(b"AB", True), (b"U", True)],
        [(bytes([1, 2, 3]), True), (bytes([0x10, 0x20]), False)],
        [(b"", True), (bytes([0x7E]), True)],
        [(bytes([0xAA, 0x55]), True)]][k]
assert got == want, f"This stream should give {want}."
```

::: right
Right. A zero-length frame goes straight to the checksum, a 0x7E inside a frame is just data, and a frame cut off at the end of the stream is never reported. Each of those is one line in the state machine and a bug in code that tries to do without one.
:::
:::

::: check
kind: python
given: price = 35 | 50 | 65; k = 0..3 int

## A vending machine takes coins of 5, 10 and 25 cents. Its state is the credit so far. When the credit reaches `price` = {price} 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 starter
coin_lists = [[25, 10], [25, 25, 10, 5, 5], [10, 10, 10, 10, 25, 25, 5], [5] * 20]
coins = coin_lists[k]

def vend(coins, price):
    return sum(coins) // price, None

items, change = vend(coins, price)
print(items, change)
```

```python solution
coin_lists = [[25, 10], [25, 25, 10, 5, 5], [10, 10, 10, 10, 25, 25, 5], [5] * 20]
coins = coin_lists[k]

def vend(coins, price):
    credit, items, change = 0, 0, []
    for c in coins:
        credit += c
        if credit >= price:
            items += 1
            change.append(credit - price)
            credit = 0
    return items, change

items, change = vend(coins, price)
print(items, change)
```

```python tests
cr, it, ch = 0, 0, []
for c in coin_lists[k]:
    cr += c
    if cr >= price:
        it += 1; ch.append(cr - price); cr = 0
assert (items, change) == (it, ch), f"With these coins at {price} cents it dispenses {it} items and returns {ch}."
```

::: right
Right. The machine never holds more than one purchase's credit: the moment the price is reached it dispenses and resets. That's why it doesn't match `sum(coins) // price`, which assumes credit carries over.
:::
:::

::: check
kind: python
given: k = 1..6 int; pat = 0 | 1 | 2

## 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 starter
import random
random.seed(k)
bits = [random.randint(0, 1) for _ in range(60)]
pattern = [[1, 0, 1], [1, 1, 0, 1], [0, 0, 1, 0]][pat]

def count_matches(bits, pattern):
    count, state = 0, 0
    for b in bits:
        if b == pattern[state]:
            state += 1
            if state == len(pattern):
                count += 1
                state = 0
        else:
            state = 0
    return count

n = count_matches(bits, pattern)
print(n)
```

```python solution
import random
random.seed(k)
bits = [random.randint(0, 1) for _ in range(60)]
pattern = [[1, 0, 1], [1, 1, 0, 1], [0, 0, 1, 0]][pat]

def count_matches(bits, pattern):
    m = len(pattern)
    def nxt(state, b):
        seq = pattern[:state] + [b]
        for j in range(min(len(seq), m), 0, -1):
            if seq[-j:] == pattern[:j]:
                return j
        return 0
    count, state = 0, 0
    for b in bits:
        state = nxt(state, b)
        if state == m:
            count += 1
    return count

n = count_matches(bits, pattern)
print(n)
```

```python tests
want = sum(1 for i in range(len(bits) - len(pattern) + 1) if bits[i:i + len(pattern)] == pattern)
assert n == want, f"The pattern occurs {want} times, overlaps included. After a mismatch or a full match, the longest end of what you've seen that starts the pattern is the new state."
assert count_matches([1, 0, 1, 0, 1], [1, 0, 1]) == 2 and count_matches([1, 1, 0, 1], [1, 0, 1]) == 1, "1,0,1,0,1 holds 1,0,1 twice; 1,1,0,1 holds it once."
```

::: right
Right. Resetting to zero after a mismatch or a match loses the overlaps: in 1, 1, 0, 1 the second 1 starts a new match. The right next state is the longest tail of what you've seen that's also a start of the pattern, which is how hardware sequence detectors are designed in C7.
:::
:::

::: check
kind: python
given: g = 4 | 5 | 8; y = 2 | 3; r = 3 | 4 | 6

## A traffic light holds green for `g` = {g} s, yellow for `y` = {y} s and red for `r` = {r} 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 starter
colors = ["GREEN"] * 60
red_frac = 0
print(colors[:15], red_frac)
```

```python solution
PLAN = {"GREEN": (g, "YELLOW"), "YELLOW": (y, "RED"), "RED": (r, "GREEN")}
state, left, colors = "GREEN", g, []
for t in range(60):
    colors.append(state)
    left -= 1
    if left == 0:
        state = PLAN[state][1]
        left = PLAN[state][0]
red_frac = colors.count("RED") / 60
print(colors[:15], red_frac)
```

```python tests
cyc = ["GREEN"] * g + ["YELLOW"] * y + ["RED"] * r
want = [cyc[t % len(cyc)] for t in range(60)]
assert colors == want, f"Second by second the light should go {g} green, {y} yellow, {r} red, and repeat."
assert abs(red_frac - want.count("RED") / 60) < 1e-12, "red_frac is the fraction of the 60 seconds that are red."
```

::: right
Right. Each state carries its own timer, and the table says where it goes when the timer runs out. The output is a function of the state alone, a Moore machine.
:::
:::

::: check
kind: choice

## 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?

- [x] A `KeyError`, which points straight at the missing case
- [ ] The machine stays in its state
- [ ] The machine goes back to its first state
- [ ] `state` becomes `None`

::: right
Right. Looking up a missing key raises `KeyError`. During testing that's what you want: it names the state and input you forgot. If staying put really is the rule, say so with `NEXT.get((state, x), state)`.
:::

::: misses
- [2] Only if you ask for that with `.get((state, x), state)`. Square brackets raise an error.
- [3] Nothing in a dictionary lookup knows which state came first.
- [4] Square-bracket lookup raises an error; `.get` without a default would return `None`.
:::
:::

::: explain
## Why is a state machine easier to get right than a tangle of flags and `if` statements that does the same job?

::: model
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 `if`s 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

::: check
kind: python
given: n = 3 | 5 | 7

## A toggle switch flips a lamp each time it's pressed. Starting with the lamp off, set `lamp` to its state (`True` for on) after `n` = {n} presses, using a loop that steps the state.

```python starter
lamp = False
print(lamp)
```

```python solution
lamp = False
for _ in range(n):
    lamp = not lamp
print(lamp)
```

```python tests
assert lamp == (n % 2 == 1), f"After {n} presses the lamp is {'on' if n % 2 else 'off'}."
```
:::

::: check
kind: python
given: k = 0..2 int

## The table `NEXT` maps `(state, letter)` to the next state of a machine that accepts the word `"ON"`. Starting in `"S0"`, step it through the string `s` the starter picks and set `accepted` to whether it ends in `"DONE"`. Inputs not in the table send it back to `"S0"`.

```python starter
NEXT = {("S0", "O"): "S1", ("S1", "N"): "DONE"}
s = ["ON", "OFF", "OON"][k]
accepted = None
print(accepted)
```

```python solution
NEXT = {("S0", "O"): "S1", ("S1", "N"): "DONE"}
s = ["ON", "OFF", "OON"][k]
state = "S0"
for ch in s:
    state = NEXT.get((state, ch), "S0")
accepted = state == "DONE"
print(accepted)
```

```python tests
assert accepted == [True, False, False][k], "Step through each letter with NEXT.get((state, ch), 'S0') and check the final state."
```
:::
:::
