---
title: "Sequential Circuits and Finite-State Machines"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 28
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/28-sequential-circuits-and-finite-state-machines
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 28 — Sequential Circuits and Finite-State Machines

A traffic light changes every thirty seconds, and it knows which colour comes next. The circuits of [Chapter 27](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#ch-b1-combinational-circuits) cannot do that: their outputs depend only on their inputs of the moment, and two identical inputs give identical outputs, whatever happened before. A light, a [counter](#def-b1-sequential-circuits-register), a lock and a processor all need *memory*. This chapter builds memory from gates by letting them feed back on themselves, tames it with a clock, and arrives at the [finite-state machine](#def-b1-sequential-circuits-fsm), the model behind every controller, whose most important example is the [control unit](#def-b1-sequential-circuits-datapath) of a processor. The last section builds one for the toy machine and checks it, instruction by instruction, against the toy machine’s simulator.

**You already know.**

The second book met the [flip-flop](#def-b1-sequential-circuits-flip-flop) and the state machine, and its toy machine runs a fetch–decode–execute cycle; [combinational circuits](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#def-b1-combinational-circuits-combinational), [Karnaugh maps](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#def-b1-combinational-circuits-karnaugh), the ALU and [propagation delay](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#def-b1-combinational-circuits-delay) are in [Chapter 27](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#ch-b1-combinational-circuits).

## 28.1 Feedback and memory

**Definition 28.1 (Sequential circuit).**

A *sequential circuit* is a circuit whose outputs depend on the past inputs as well as the present ones. Its gates form a [graph](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) with cycles, or it contains elements that store bits.

The simplest has two NOR gates, each fed by the other. The simulator for such circuits cannot evaluate the gates in a [topological order](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-topo), since there is none; it moves time forward one gate delay at a time, every gate taking the values its inputs had one unit before.

```python
def sr_latch():
    n = Net("S", "R")
    n.gate("Q", "NOR", "R", "Qn")  # Qn is Q', the complement
    n.gate("Qn", "NOR", "S", "Q")
    return n
```

***Listing 28.1.** Two NOR gates feeding each other code/bachelor-1/28-sequential-circuits/listings/sr_latch.py*

```
$ python sr_latch.py
phase      S R   Q Q' after each time unit
set        1 0   00 10 10 10 10 10
hold       0 0   10 10 10 10 10 10
reset      0 1   00 01 01 01 01 01
hold       0 0   01 01 01 01 01 01
forbidden  1 1   00 00 00 00 00 00
release    0 0   11 00 11 00 11 00
```

***Output 28.1.** The [latch](#def-b1-sequential-circuits-latch) traced one gate delay at a time. After *set* and *reset* it holds its bit; released from $S = R = 1$ it oscillates.*

**Definition 28.2 (Latch, SR latch, D latch).**

A *latch* is a circuit with two stable [states](#def-b1-sequential-circuits-fsm) that stores one bit. An *SR latch* has inputs $S$ (set) and $R$ (reset): $S = 1$ makes its output $Q$ 1, $R = 1$ makes it 0, and $S = R = 0$ keeps it. The input $S = R = 1$ is forbidden. A *D latch* has a data input $D$ and an enable $E$: while $E = 1$ its output follows $D$ (it is *transparent*), and while $E = 0$ it keeps the last value.

| $S$ | $R$ | $Q$ next |
| --- | --- | --- |
| 0 | 0 | $Q$ (hold) |
| 1 | 0 | 1 (set) |
| 0 | 1 | 0 (reset) |
| 1 | 1 | forbidden |

![An SR latch: the output of each NOR gate is an input of the other. The loop is what remembers.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-sequential-circuits/fig-85fca5cfb800.svg)

*An [SR latch](#def-b1-sequential-circuits-latch): the output of each NOR gate is an input of the other. The loop is what remembers.*

With $S = R = 0$ each NOR gate is an inverter, and two inverters in a loop are stable in two ways, $Q = 1, Q' = 0$ and $Q = 0, Q' = 1$: that is the stored bit. $S = 1$ forces $Q' = 0$, hence $Q = 1$; $R = 1$ forces the opposite. With $S = R
= 1$ both outputs are 0, which is not a pair of complements; releasing both inputs at once lets the two gates race, and in a model with exactly equal delays they oscillate for ever. In real gates one wins, but nobody can say which: that is why the input is forbidden.

A [D latch](#def-b1-sequential-circuits-latch) puts two AND gates in front: $S = DE$ and $R = D'E$, so the forbidden input cannot happen. Its transparency is a problem, however. If the output of a [latch](#def-b1-sequential-circuits-latch) feeds, through some logic, back to its own input, a change can run round the loop many times while the [latch](#def-b1-sequential-circuits-latch) is enabled, and the result depends on how long the enable lasts. The cure is to let the stored value change only at an instant.

## 28.2 Flip-flops and the clock

**Definition 28.3 (Flip-flop, edge-triggered D flip-flop).**

A *flip-flop* stores one bit and changes it only at an edge of a control signal. An *edge-triggered D flip-flop* copies its input $D$ to its output $Q$ at each rising edge (a change from 0 to 1) of its clock input, and keeps $Q$ the rest of the time.

Two [D latches](#def-b1-sequential-circuits-latch) make one. The first, the *master*, is enabled while the clock is 0 and follows $D$; the second, the *slave*, is enabled while the clock is 1 and copies the master. At the rising edge the master closes, holding the value $D$ had at that moment, and the slave opens and shows it; while the clock is 1, $D$ may change, but the master is closed.

```python
def d_latch(n, name, d, enable):
    """S = D and E, R = D' and E, into an SR latch of two NOR gates."""
    n.gate(name + "d'", "NOT", d)
    n.gate(name + "s", "AND", d, enable)
    n.gate(name + "r", "AND", name + "d'", enable)
    n.gate(name + "Q", "NOR", name + "r", name + "Q'")
    n.gate(name + "Q'", "NOR", name + "s", name + "Q")
    return name + "Q"


def d_flipflop():
    n = Net("clk", "D")
    n.gate("clk'", "NOT", "clk")
    d_latch(n, "m", "D", "clk'")  # the master follows D while the clock is 0
    d_latch(n, "s", "mQ", "clk")  # the slave copies the master while it is 1
    return n
```

***Listing 28.2.** A master–slave D [flip-flop](#def-b1-sequential-circuits-flip-flop) from two [D latches](#def-b1-sequential-circuits-latch) code/bachelor-1/28-sequential-circuits/listings/d_flipflop.py*

```
$ python d_flipflop.py
clk __________----------__________----------__________----------__________----------
D   _____--------------------_____________________-------____------_________________
Q   ____________-------------------_____________________-------------------_________
D goes 0 -> 1 at edge + k, k = -4..4; stored: 1 1 1 1 1 0 0 0 0
D goes 1 -> 0 at edge + k, k = -4..4; stored: 0 0 0 1 1 1 1 1 1
setup time 2 units, hold time 0 units
clock edge to Q: 2 time units
```

***Output 28.2.** The [flip-flop](#def-b1-sequential-circuits-flip-flop) under a clock of period 20 time units: $Q$ changes only after rising edges. Then $D$ is changed at $k$ units from an edge, to find the window in which it must not move.*

**Definition 28.4 (Clock signal, clock period, synchronous circuit).**

A *clock signal* is a signal that alternates between 0 and 1 at a fixed rate; the time between two rising edges is the *clock period*, and its inverse the clock frequency. A *synchronous circuit* is made of [flip-flops](#def-b1-sequential-circuits-flip-flop), all driven by the same clock, and of combinational logic between them, with no loop that does not pass through a [flip-flop](#def-b1-sequential-circuits-flip-flop).

In a [synchronous circuit](#def-b1-sequential-circuits-clock) the state, the contents of the [flip-flops](#def-b1-sequential-circuits-flip-flop), changes only at the edges; between two edges the combinational logic computes, from the state and the inputs, the next state, which the [flip-flops](#def-b1-sequential-circuits-flip-flop) load at the next edge. Every loop is cut by a [flip-flop](#def-b1-sequential-circuits-flip-flop), so the logic between edges is combinational, and [Chapter 27](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#ch-b1-combinational-circuits) applies to it.

**Definition 28.5 (Setup time, hold time).**

The *setup time* of a [flip-flop](#def-b1-sequential-circuits-flip-flop) is how long before the clock edge its input must be stable; the *hold time*, how long after the edge it must stay stable. The *clock-to-output delay* is the time from the edge to the new output.

The measurement in [Output 28.2](#out-b1-sequential-circuits-dff) finds a [setup time](#def-b1-sequential-circuits-setup) of 2 units: a $D$ that falls one unit before the edge is missed, because the path from $D$ through the NOT gate into the master is one gate longer than the path of a rising $D$. Its [hold time](#def-b1-sequential-circuits-setup) is 0, and the clock-to-output delay 2 units. The figure below draws the run.

![The run of . Q takes the value D had at each rising edge, two time units later; the shaded windows are the setup times, in which D must not change.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-sequential-circuits/fig-77576e6ebced.svg)

*The run of [Output 28.2](#out-b1-sequential-circuits-dff). $Q$ takes the value $D$ had at each rising edge, two time units later; the shaded windows are the [setup times](#def-b1-sequential-circuits-setup), in which $D$ must not change.*

The [clock period](#def-b1-sequential-circuits-clock) is bounded below. After an edge, the new state appears at the [flip-flop](#def-b1-sequential-circuits-flip-flop) outputs a clock-to-output delay later, crosses the combinational logic along its [longest delay path](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#def-b1-combinational-circuits-delay) ([Definition 27.12](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#def-b1-combinational-circuits-delay)), and must arrive a [setup time](#def-b1-sequential-circuits-setup) before the next edge:

$$
T \geq t_{\text{clock-to-output}} + t_{\text{logic}} + t_{\text{setup}}.
$$

The [hold time](#def-b1-sequential-circuits-setup) puts a bound on the *shortest* path: the new values must not reach the next [flip-flops](#def-b1-sequential-circuits-flip-flop) before their [hold time](#def-b1-sequential-circuits-setup) has passed. A processor’s clock frequency is set by the slowest path between two of its [registers](#def-b1-sequential-circuits-register).

## 28.3 Registers, counters and memory

**Definition 28.6 (Register, shift register, counter).**

A *register* is a row of [flip-flops](#def-b1-sequential-circuits-flip-flop) on the same clock that store a word; with an *enable* input, each loads its input when enable is 1 and keeps its value otherwise. A *shift register* moves its bits one place at each edge, a new bit entering at one end. A *counter* is a register whose value goes through $0, 1, 2, \dots$ at successive edges.

The enable is a [multiplexer](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#def-b1-combinational-circuits-mux) in front of each [flip-flop](#def-b1-sequential-circuits-flip-flop), choosing between its own output and the new input: a [register](#def-b1-sequential-circuits-register) with enable is a [synchronous circuit](#def-b1-sequential-circuits-clock), its clock never stopped.

```python
def mux(s, x0, x1):
    return ((1 - s) & x0) | (s & x1)  # s' x0 + s x1


def register_next(q, d, enable):
    """Load d when enable is 1, keep q otherwise."""
    return [mux(enable, qi, di) for qi, di in zip(q, d)]


def shift_next(q, serial_in):
    """q[0] is the left bit; every bit moves one place right, serial_in enters left."""
    return [serial_in] + q[:-1]
```

***Listing 28.3.** A [register](#def-b1-sequential-circuits-register) with enable and a [shift register](#def-b1-sequential-circuits-register), one clock edge at a time code/bachelor-1/28-sequential-circuits/listings/shift.py*

```
$ python shift.py
register: D = 1011, enable 0 -> Q = 0000
register: D = 1011, enable 1 -> Q = 1011
register: D = 0110, enable 0 -> Q = 1011
register: D = 0110, enable 1 -> Q = 0110
shift register, edge 1: in 1 -> 1000
shift register, edge 2: in 1 -> 1100
shift register, edge 3: in 0 -> 0110
shift register, edge 4: in 1 -> 1011
shift register, edge 5: in 0 -> 0101
shift register, edge 6: in 0 -> 0010
```

***Output 28.3.** Loading only when enabled; four bits entering one by one, then moving on.*

A [shift register](#def-b1-sequential-circuits-register) turns a stream of bits into a word (after four edges the bits 1, 1, 0, 1 sit side by side) and back: that is how a serial line, such as a USB cable, carries bytes one bit at a time.

A [counter](#def-b1-sequential-circuits-register) can be built two ways. In a *synchronous [counter](#def-b1-sequential-circuits-register)* every [flip-flop](#def-b1-sequential-circuits-flip-flop) is on the clock, and gates compute the next value: bit 0 flips at every edge, bit 1 when bit 0 is 1, bit 2 when bits 0 and 1 are both 1. In a *ripple [counter](#def-b1-sequential-circuits-register)* only the first [flip-flop](#def-b1-sequential-circuits-flip-flop) sees the clock; each of the others flips when the one before it falls from 1 to 0. It needs no gates, but its bits change one after the other.

```python
def synchronous_next(q):
    """q = (q0, q1, q2), q0 the low bit: add 1 with gates."""
    q0, q1, q2 = q
    return (1 - q0, q1 ^ q0, q2 ^ (q1 & q0))


def synchronous(cycles, d=2):
    """The value seen at each time unit; the clock rises every 10 units."""
    q, seen = (0, 0, 0), []
    for t in range(10 * cycles):
        if t % 10 == d:  # every flip-flop changes d units after the shared edge
            q = synchronous_next(q)
        seen.append(q[0] + 2 * q[1] + 4 * q[2])
    return seen


def ripple(cycles, d=2, n=3):
    """Flip-flop i toggles d units after flip-flop i - 1 falls from 1 to 0."""
    q, seen, changes = [0] * n, [], {}  # changes: time -> the flip-flops to toggle
    for t in range(10 * cycles):
        if t % 10 == 0:
            changes.setdefault(t + d, []).append(0)
        for i in changes.pop(t, []):
            q[i] ^= 1
            if q[i] == 0 and i + 1 < n:  # it fell: the next one toggles d later
                changes.setdefault(t + d, []).append(i + 1)
        seen.append(sum(b << i for i, b in enumerate(q)))
    return seen
```

***Listing 28.4.** Two 3-bit [counters](#def-b1-sequential-circuits-register), watched at every time unit; each [flip-flop](#def-b1-sequential-circuits-flip-flop) takes $d$ units code/bachelor-1/28-sequential-circuits/listings/counter.py*

```
$ python counter.py
synchronous 0 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 6 | 6 7 | 7 0
            values that are neither the old count nor the new: 0
ripple      0 1 | 1 0 2 | 2 3 | 3 2 0 4 | 4 5 | 5 4 6 | 6 7 | 7 6 4 0
            values that are neither the old count nor the new: 6
ripple, 3 bits: settled 6 units after the edge; synchronous: 2
ripple, 4 bits: settled 8 units after the edge; synchronous: 2
```

***Output 28.4.** The values seen between two clock edges. The ripple [counter](#def-b1-sequential-circuits-register) passes through wrong values: from 3 to 4 it shows 2 and 0 on the way.*

A circuit that reads the ripple [counter](#def-b1-sequential-circuits-register) while it settles may see 2 or 0 between 3 and 4: a *glitch*. The synchronous [counter](#def-b1-sequential-circuits-register) has none, and settles in one [flip-flop](#def-b1-sequential-circuits-flip-flop) delay whatever its width, where the ripple [counter](#def-b1-sequential-circuits-register) needs $n$.

A memory is many [registers](#def-b1-sequential-circuits-register) and a way to choose one. A $k$-to-$2^k$ [decoder](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#def-b1-combinational-circuits-mux) ([Definition 27.10](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#def-b1-combinational-circuits-mux)) turns the address into one selected row; a write loads the row whose [decoder](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#def-b1-combinational-circuits-mux) output is 1; a read sends the selected row through a [multiplexer](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#def-b1-combinational-circuits-mux) to the output.

**Definition 28.7 (Memory cell).**

A *memory cell* is the circuit that stores one bit of a memory, with an input that selects it for writing and an output that the read logic selects.

```python
def decoder(k):
    """k address bits in, 2^k outputs, exactly one of them 1."""
    c = Circuit(*[f"a{i}" for i in range(k)])
    inv = [c.gate("NOT", f"a{i}") for i in range(k)]
    for row in range(2 ** k):
        lits = [f"a{i}" if row >> i & 1 else inv[i] for i in range(k)]
        c.outputs[row] = c.gate("AND", *lits)
    return c


def multiplexer(k):
    """2^k data inputs, k select inputs: a tree of 2-to-1 multiplexers."""
    c = Circuit(*[f"x{j}" for j in range(2 ** k)], *[f"a{i}" for i in range(k)])
    level = [f"x{j}" for j in range(2 ** k)]
    for i in range(k):
        s, s_inv = f"a{i}", c.gate("NOT", f"a{i}")
        level = [c.gate("OR", c.gate("AND", s_inv, x0), c.gate("AND", s, x1))
                 for x0, x1 in zip(level[::2], level[1::2])]
    c.outputs["out"] = level[0]
    return c
```

***Listing 28.5.** The [decoder](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#def-b1-combinational-circuits-mux) and the [multiplexer](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#def-b1-combinational-circuits-mux) of a 16-word memory code/bachelor-1/28-sequential-circuits/listings/ram.py*

```
$ python ram.py
write  9 at address  3
write  5 at address 12
write 14 at address  3
read: [3] = 14, [12] = 5, [7] = 0
gates: decoder 20, write enables 16, cells 320, read multiplexers 196; total 552
```

***Output 28.5.** A $16 \times 4$ memory: writes and reads, and its gates.*

More than half of the gates are cells, and the share grows with the size: a memory of $2^k$ words of $w$ bits needs $5
\cdot 2^k w$ gates of cells against about $2^k$ for the [decoder](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#def-b1-combinational-circuits-mux). Real memories make the cell as small as possible: six transistors in a static [memory cell](#def-b1-sequential-circuits-memory-cell), one transistor and a capacitor, refreshed every few hundredths of a second, in a dynamic one.

**History — Magnetic cores.**

Before memories were made of transistors, the main memory of computers was a plane of tiny rings of magnetic material, threaded on a grid of wires: each ring held one bit as the direction of its magnetisation, and the current in one row wire and one column wire together selected a single ring, a [decoder](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#def-b1-combinational-circuits-mux) made of physics. Jay Forrester described the three-dimensional arrangement in 1951, and core memory was the main memory of most computers until the 1970s.

![A plane of core memory holding 1024 bits: 32 rows and 32 columns of ferrite rings, each threaded by the wires of its row and its column. Photograph: Konstantin Lanzet, CC BY-SA 3.0.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-sequential-circuits/img-c6246107498b.jpg)

*A plane of core memory holding 1024 bits: 32 rows and 32 columns of ferrite rings, each threaded by the wires of its row and its column. Photograph: Konstantin Lanzet, CC BY-SA 3.0.*

## 28.4 Finite-state machines

Every [synchronous circuit](#def-b1-sequential-circuits-clock) is the same object seen from far: a state, kept in [flip-flops](#def-b1-sequential-circuits-flip-flop); an input at each clock cycle; a next state and an output computed from them. Mathematics names it.

**Definition 28.8 (Finite-state machine).**

A *finite-state machine* has a finite set of *states*, one of them initial, a finite input alphabet $\Sigma$, an output alphabet, and a *transition* function that gives, for each state $q$ and input symbol $a$, the next state $\delta(q, a)$. It reads one symbol per step and produces one output per step.

**Definition 28.9 (Moore machine, Mealy machine, state diagram, state encoding).**

In a *Moore machine* the output is a function $\lambda(q)$ of the state; in a *Mealy machine* it is a function $\lambda(q, a)$ of the state and the input, attached to the [transition](#def-b1-sequential-circuits-fsm). A *state diagram* draws the [states](#def-b1-sequential-circuits-fsm) as circles and each [transition](#def-b1-sequential-circuits-fsm) as an arrow labelled by its input (and, for a Mealy machine, its output, as $a/o$). A *state encoding* gives each state a distinct word of bits, to be stored in [flip-flops](#def-b1-sequential-circuits-flip-flop).

For an input word $a_1 \dots a_n$ a [Mealy machine](#def-b1-sequential-circuits-moore-mealy) outputs $\lambda(q_0, a_1) \dots \lambda(q_{n-1}, a_n)$ and a [Moore machine](#def-b1-sequential-circuits-moore-mealy) $\lambda(q_1) \dots \lambda(q_n)$, where $q_i$ is the state after $i$ symbols. Two machines are *equivalent* if they give the same output word for every input word. Both kinds compute the same things:

**Proposition 28.10 (Moore and Mealy are equivalent).**

For every [Moore machine](#def-b1-sequential-circuits-moore-mealy) there is an equivalent [Mealy machine](#def-b1-sequential-circuits-moore-mealy) with the same [states](#def-b1-sequential-circuits-fsm), and for every [Mealy machine](#def-b1-sequential-circuits-moore-mealy) with state set $Q$ and output alphabet $O$ there is an equivalent [Moore machine](#def-b1-sequential-circuits-moore-mealy) with at most $|Q| \cdot |O|$ [states](#def-b1-sequential-circuits-fsm).

**Proof.** Moore to Mealy: put on each [transition](#def-b1-sequential-circuits-fsm) the output of the state it enters, $\lambda'(q, a) = \lambda(\delta(q, a))$. Mealy to Moore: take the pairs $(q, o)$ as [states](#def-b1-sequential-circuits-fsm), meaning “in $q$, having just output $o$”, with $\delta'((q, o), a) = (\delta(q,
a), \lambda(q, a))$ and output $o$. Both machines go through the same [states](#def-b1-sequential-circuits-fsm) $q_i$, and the output read after step $i$ is $\lambda(q_{i-1}, a_i)$ in both; [Exercise 28.10](#exo-b1-sequential-circuits-10) writes the induction out. ∎

```python
def mealy_to_moore(m, alphabet):
    """A Moore state (q, o): in q, having just output o. Only the reachable ones."""
    first = (m.start, 0)
    states, todo, delta = {first}, [first], {}
    while todo:
        q, o = todo.pop()
        for a in alphabet:
            nxt = m.delta[q, a]
            delta[(q, o), a] = nxt
            if nxt not in states:
                states.add(nxt)
                todo.append(nxt)
    return Moore(first, delta, {s: s[1] for s in states})


def moore_to_mealy(m):
    """Output, on a transition, the output of the state it enters."""
    return Mealy(m.start, {(q, a): (r, m.out[r]) for (q, a), r in m.delta.items()})
```

***Listing 28.6.** The two conversions, keeping only the reachable pairs code/bachelor-1/28-sequential-circuits/listings/moore_mealy.py*

The example is a *sequence detector*: it reads bits and outputs 1 exactly when the last three were $1, 0, 1$. Overlaps count: in $10101$ it fires twice. Its Mealy [states](#def-b1-sequential-circuits-fsm) remember the longest end of the input that is a beginning of $101$: nothing, $1$, or $10$.

```
$ python moore_mealy.py
Moore ( -, 0) --0--> ( -, 0)
Moore ( -, 0) --1--> ( 1, 0)
Moore ( 1, 0) --0--> (10, 0)
Moore ( 1, 0) --1--> ( 1, 0)
Moore ( 1, 1) --0--> (10, 0)
Moore ( 1, 1) --1--> ( 1, 0)
Moore (10, 0) --0--> ( -, 0)
Moore (10, 0) --1--> ( 1, 1)
Mealy states: 3, Moore states: 4
Mealy and Moore agree on all 2047 words of length <= 10: True
and the Mealy machine made back from it: True
on 0110101101: [0, 0, 0, 0, 1, 0, 1, 0, 0, 1]
```

***Output 28.6.** The [Moore machine](#def-b1-sequential-circuits-moore-mealy) made from the Mealy detector of 101: the state $(1, 1)$ is new, the state $1$ entered with an output of 1. Both agree on every word of up to ten bits.*

![The detector of 101. Left, the Mealy machine: the 1 is output on the transition from 10 on input 1. Right, the Moore machine: the 1 is the output of the state 1/1, which splits the state 1 in two.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-sequential-circuits/fig-de3050537eb8.svg)

*The detector of 101. Left, the [Mealy machine](#def-b1-sequential-circuits-moore-mealy): the 1 is output on the [transition](#def-b1-sequential-circuits-fsm) from $10$ on input 1. Right, the [Moore machine](#def-b1-sequential-circuits-moore-mealy): the 1 is the output of the state $1/1$, which splits the state $1$ in two.*

**From a [state diagram](#def-b1-sequential-circuits-moore-mealy) to a circuit.** Four steps make a machine into a [synchronous circuit](#def-b1-sequential-circuits-clock). Encode the [states](#def-b1-sequential-circuits-fsm) in $\lceil \log_2 |Q| \rceil$ bits, one [flip-flop](#def-b1-sequential-circuits-flip-flop) per bit; write the truth tables of the next-state bits and of the output, as functions of the state bits and the input; simplify them ([Section 27.2](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#sec-b1-combinational-circuits-simplification)); and connect the logic’s outputs to the [flip-flops](#def-b1-sequential-circuits-flip-flop)’ inputs. Unused codes are don’t-cares.

```
$ python detector.py
A+ = Bx' + AB'x
B+ = x
z  = AB
gates: 6, flip-flops: 2
circuit = machine on all 8191 words of length <= 12: True
```

***Output 28.7.** The Moore detector with $(\varepsilon, 0) = 00$, $(1, 0) = 01$, $(10, 0) = 10$, $(1, 1) = 11$; $A$ is the high state bit, $B$ the low one, $x$ the input. The circuit is checked against the machine.*

$B^+ = x$ says that the low state bit is just the last input, a one-bit [shift register](#def-b1-sequential-circuits-register); $z = AB$ needs one gate. A different encoding gives different equations, sometimes better ones; *one-hot* encoding, one [flip-flop](#def-b1-sequential-circuits-flip-flop) per state, spends [flip-flops](#def-b1-sequential-circuits-flip-flop) to make the logic trivial ([Exercise 28.9](#exo-b1-sequential-circuits-9)).

## 28.5 The control of a small processor

The toy machine of the earlier books executes an instruction in one step of its simulator. Hardware cannot: reading the two bytes of the instruction, reading or writing memory, and changing [registers](#def-b1-sequential-circuits-register) take several clock cycles, and something must order them. A processor is two parts.

**Definition 28.11 (Datapath, control unit).**

The *datapath* of a processor is the part that holds and transforms data: [registers](#def-b1-sequential-circuits-register), the ALU, the buses and [multiplexers](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#def-b1-combinational-circuits-mux) between them, and the connection to memory. The *control unit* is a [finite-state machine](#def-b1-sequential-circuits-fsm) that, at each clock cycle, sends the datapath the signals that choose which [register](#def-b1-sequential-circuits-register) transfer happens: which [register](#def-b1-sequential-circuits-register) is loaded, from which source, with which ALU operation.

The [datapath](#def-b1-sequential-circuits-datapath) of the toy machine has the four [registers](#def-b1-sequential-circuits-register), the program [counter](#def-b1-sequential-circuits-register) `PC`, the stack [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) `SP`, the flags, and two instruction [registers](#def-b1-sequential-circuits-register) `IR0` and `IR1` for the two bytes of the current instruction; its ALU is that of [Definition 27.11](https://one-course.com/books/computer-science/3/en/chapter/27-boolean-algebra-and-combinational-circuits#def-b1-combinational-circuits-alu) on eight bits, which the program computes with integer arithmetic, except that, as in the toy machine, the flag C after a subtraction is the borrow. The [control unit](#def-b1-sequential-circuits-datapath) is a [Moore machine](#def-b1-sequential-circuits-moore-mealy): each state names the [register](#def-b1-sequential-circuits-register) transfers it orders. Its next state depends on the state, on the operation code in `IR0`, and, for a conditional jump, on the flags.

```python
CONTROL = {
    "FETCH0": ("IR0 <- M[PC]", "PC <- PC+1"),
    "FETCH1": ("IR1 <- M[PC]", "PC <- PC+1"),
    "DECODE": (),
    "LOADI": ("R <- IR1",), "LOAD": ("R <- M[IR1]",), "STORE": ("M[IR1] <- R",),
    "ALU_RR": ("R <- ALU(R, S)",), "ALU_RI": ("R <- ALU(R, IR1)",),
    "ALU_R": ("R <- ALU(R)",), "CMP": ("FLAGS <- ALU(R, S)",),
    "JUMP": ("PC <- IR1",), "IN": ("R <- IN",), "OUT": ("OUT <- R",),
    "LOADR": ("R <- M[S]",), "STORER": ("M[S] <- R",),
    "PUSH1": ("SP <- SP-1",), "PUSH2": ("M[SP] <- R",),
    "POP": ("R <- M[SP]", "SP <- SP+1"),
    "CALL1": ("SP <- SP-1",), "CALL2": ("M[SP] <- PC", "PC <- IR1"),
    "RET": ("PC <- M[SP]", "SP <- SP+1"),
    "HALT": ("PC <- PC-2",), "STOP": (),
}
GROUP = {"ADD": "ALU_RR", "SUB": "ALU_RR", "AND": "ALU_RR", "OR": "ALU_RR",
         "XOR": "ALU_RR", "ADDI": "ALU_RI", "NOT": "ALU_R", "SHL": "ALU_R",
         "SHR": "ALU_R", "JMP": "JUMP", "PUSH": "PUSH1", "CALL": "CALL1",
         "NOP": "FETCH0"}
TAKEN = {"JZ": ("Z", 1), "JNZ": ("Z", 0), "JN": ("N", 1), "JC": ("C", 1)}
AFTER = {"FETCH0": "FETCH1", "FETCH1": "DECODE", "PUSH1": "PUSH2", "CALL1": "CALL2",
         "HALT": "STOP", "STOP": "STOP"}


def next_state(state, op, flags):
    """The control unit's next state, from its state, the opcode and the flags."""
    if state != "DECODE":
        return AFTER.get(state, "FETCH0")
    if op in TAKEN:
        flag, value = TAKEN[op]
        return "JUMP" if flags[flag] == value else "FETCH0"
    return GROUP.get(op, op)
```

***Listing 28.7.** The [control unit](#def-b1-sequential-circuits-datapath) of the toy machine: the transfers each state orders, and the next-state function code/bachelor-1/28-sequential-circuits/listings/toy_control.py*

`R` is the [register](#def-b1-sequential-circuits-register) named in the first byte, `S` the one named in the second, and `M[...]` the memory. `FETCH0` and `FETCH1` read the two bytes of the instruction; `DECODE` chooses the execute state from the operation code; each execute state goes back to `FETCH0`. A jump not taken goes straight back too.

```python
def run(mem, inputs, trace=None, max_cycles=100_000):
    """Clock the control unit and the datapath; compare with the shared simulator after
    every instruction. Returns (instructions, cycles)."""
    d, ref, state = Datapath(mem, inputs), Machine(mem, inputs), "FETCH0"
    instructions = cycles = 0
    while state != "STOP" and cycles < max_cycles:
        for transfer in CONTROL[state]:
            d.do(transfer)
        if trace:
            trace(cycles, state, d)
        cycles += 1
        state = next_state(state, OPS[d.ir0 // 4][0], d.flags)
        if state in ("FETCH0", "STOP"):  # an instruction is over
            instructions += 1
            ref.step()
            assert d.snapshot() == (ref.pc, ref.sp, ref.reg, ref.flags, ref.mem,
                                    ref.outputs)
    return instructions, cycles
```

***Listing 28.8.** Clocking the two parts, and comparing the [datapath](#def-b1-sequential-circuits-datapath) with the simulator after every instruction code/bachelor-1/28-sequential-circuits/listings/toy_control.py*

```
$ python toy_control.py
abs_value         7 instructions   28 cycles, as the simulator after each one
call_square      19 instructions   77 cycles, as the simulator after each one
count_down       12 instructions   47 cycles, as the simulator after each one
divide           78 instructions  298 cycles, as the simulator after each one
gcd              26 instructions   98 cycles, as the simulator after each one
max2              6 instructions   24 cycles, as the simulator after each one
max3             12 instructions   47 cycles, as the simulator after each one
max_array        53 instructions  206 cycles, as the simulator after each one
multiply         41 instructions  162 cycles, as the simulator after each one
self_modify       5 instructions   20 cycles, as the simulator after each one
shift_multiply   35 instructions  135 cycles, as the simulator after each one
sum              17 instructions   67 cycles, as the simulator after each one
sum_array        35 instructions  139 cycles, as the simulator after each one
times_ten         9 instructions   36 cycles, as the simulator after each one
in all: 355 instructions, 1384 cycles, 3.90 cycles per instruction
```

***Output 28.8.** The programs of the earlier books, run by the [control unit](#def-b1-sequential-circuits-datapath) and its [datapath](#def-b1-sequential-circuits-datapath); after every instruction the [registers](#def-b1-sequential-circuits-register), flags, memory and outputs are those of the toy machine’s simulator.*

![The control unit of , some execute states left out: four states per instruction for most (two fetch states, decode, one execute state), three for a jump not taken, five for PUSH and CALL. The program counts 3.9 cycles per instruction on average.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-sequential-circuits/fig-7e000706b60a.svg)

*The [control unit](#def-b1-sequential-circuits-datapath) of [Listing 28.7](#lst-b1-sequential-circuits-control), some execute [states](#def-b1-sequential-circuits-fsm) left out: four [states](#def-b1-sequential-circuits-fsm) per instruction for most (two fetch [states](#def-b1-sequential-circuits-fsm), decode, one execute state), three for a jump not taken, five for PUSH and CALL. The program counts 3.9 cycles per instruction on average.*

The [control unit](#def-b1-sequential-circuits-datapath) has 23 [states](#def-b1-sequential-circuits-fsm), so five [flip-flops](#def-b1-sequential-circuits-flip-flop) encode it, and its next-state and output functions are combinational logic of the state, six bits of operation code and three flags, which [Section 28.4](#sec-28-4) turns into gates. Large instruction sets made those functions unmanageable; the answer, *microprogrammed control*, stores the control signals of each state as a word in a small read-only memory, the *microprogram*, addressed by the state, so that the [control unit](#def-b1-sequential-circuits-datapath) is itself a tiny computer reading a table. Many processors since have been built that way, and many have gone back to gates when speed mattered more than the size of the instruction set.

## 28.6 Exercises

**Exercise 28.1 ★.**

An [SR latch](#def-b1-sequential-circuits-latch) starts with $Q = 0$. Its inputs $(S, R)$ take the values $10$, $00$, $01$, $10$, $00$, each held long enough for the [latch](#def-b1-sequential-circuits-latch) to settle. Give $Q$ after each.

**Solution of Exercise 28.1.**

$Q = 1$ (set), $1$ (hold), $0$ (reset), $1$ (set), $1$ (hold).

**Exercise 28.2 ★.**

The synchronous 3-bit [counter](#def-b1-sequential-circuits-register) of [Listing 28.4](#lst-b1-sequential-circuits-counter) holds 5. Give its value after each of the next five clock edges, and which bits flip at each.

**Solution of Exercise 28.2.**

6, 7, 0, 1, 2. From 5 ($101$) bits 0 and 1 flip; from 6 bit 0; from 7 all three; from 0 bit 0; from 1 bits 0 and 1. Bit $i$ flips when all the bits below it are 1.

**Exercise 28.3 ★.**

What does the Moore detector of [Output 28.6](#out-b1-sequential-circuits-conversion) output on the input word $11010110$? Give the [states](#def-b1-sequential-circuits-fsm) it goes through.

**Solution of Exercise 28.3.**

The [states](#def-b1-sequential-circuits-fsm) are $\varepsilon/0$, then $1/0$, $1/0$, $10/0$, $1/1$, $10/0$, $1/1$, $1/0$, $10/0$, and the output word $00010100$: the detector fires at the fourth and the sixth bit, the second $101$ overlapping the first.

**Exercise 28.4 ★.**

A 4-bit [shift register](#def-b1-sequential-circuits-register) as in [Listing 28.3](#lst-b1-sequential-circuits-shift) holds $1010$. The bits $1, 1, 0, 0$ enter at four edges. Give its contents after each.

**Solution of Exercise 28.4.**

$1101$, $1110$, $0111$, $0011$: each bit enters on the left and the rightmost one leaves.

**Exercise 28.5 ★★.**

A circuit compares the 3-bit ripple [counter](#def-b1-sequential-circuits-register) of [Output 28.4](#out-b1-sequential-circuits-counter) with 2, and sounds a bell when they are equal. The [counter](#def-b1-sequential-circuits-register) goes from 0 to 7 once. How many times does the bell sound, and when? Repair the design.

**Solution of Exercise 28.5.**

Twice. Once rightly, while the count is 2; once wrongly, between 3 and 4, where the [counter](#def-b1-sequential-circuits-register) shows 2 for $d$ time units ([Output 28.4](#out-b1-sequential-circuits-counter)). Two repairs: use the synchronous [counter](#def-b1-sequential-circuits-register), whose bits change together; or feed the comparator’s output into a [flip-flop](#def-b1-sequential-circuits-flip-flop) on the same clock, so that the bell sees it only at the edges, after the value has settled.

**Exercise 28.6 ★★.**

This traffic light stops with an error on the second input word. Explain why, and complete the machine.

```python
DELTA = {("green", 0): "green", ("green", 1): "amber",
         ("amber", 0): "red", ("amber", 1): "red",
         ("red", 0): "green"}
SHOWS = {"green": "cars go", "amber": "cars slow", "red": "people cross"}


def run(word, state="green"):
    shown = []
    for button in word:
        state = DELTA[state, button]
        shown.append(SHOWS[state])
    return shown
```

***Listing 28.9.** A traffic light code/bachelor-1/28-sequential-circuits/listings/exo_incomplete.py*

```
$ python exo_incomplete.py
['cars go', 'cars slow', 'people cross', 'cars go', 'cars go']
KeyError: ('red', 1)
```

***Output 28.9.** The two runs.*

**Solution of Exercise 28.6.**

The pair `("red", 1)` has no [transition](#def-b1-sequential-circuits-fsm): the [state diagram](#def-b1-sequential-circuits-moore-mealy) leaves out what happens when someone presses the button while people cross, and the first word never does that. A [finite-state machine](#def-b1-sequential-circuits-fsm) must have a [transition](#def-b1-sequential-circuits-fsm) for every state and every input symbol. Add `("red", 1): "green"` (the press is ignored, the light goes on), or keep the light red one more period; either is a decision, and the test should check that the table has $3 \times 2$ entries.

**Exercise 28.7 ★★.**

Build the Mealy detector of $0110$, overlaps allowed, and test it on every word of up to 12 bits against the definition.

**Solution of Exercise 28.7.**

```python
def check(longest=12):
    m = detector([0, 1, 1, 0])
    for w in all_words((0, 1), longest):
        want = [int(w[i - 3:i + 1] == (0, 1, 1, 0)) if i >= 3 else 0
                for i in range(len(w))]
        if m.run(w) != want:
            return False
    return True
```

*The detector, checked against the definition code/bachelor-1/28-sequential-circuits/exercises/detect_0110.py*

The detector of [Listing 28.10](#lst-b1-sequential-circuits-lock), built for $0110$, has the [states](#def-b1-sequential-circuits-fsm) $e$, $0$, $01$, $011$; after $0110$ it goes to $0$, since the last 0 begins a new pattern. It agrees with the definition on all 8191 words.

**Exercise 28.8 ★★.**

Design a synchronous [counter](#def-b1-sequential-circuits-register) modulo 6 on three D [flip-flops](#def-b1-sequential-circuits-flip-flop): the next-state equations, simplified with the codes 6 and 7 as don’t-cares, and a check that it counts $0, 1, \dots, 5, 0, \dots$.

**Solution of Exercise 28.8.**

```python
def equations():
    """A+, B+, C+ as functions of (A, B, C)."""
    return [minimal_sop([q for q in range(6) if (q + 1) % 6 >> bit & 1], [6, 7], 3)
            for bit in (2, 1, 0)]
```

*The next-state equations code/bachelor-1/28-sequential-circuits/exercises/mod6.py*

The program finds $A^+ = BC + AC'$, $B^+ = BC' + A'B'C$, $C^+ = C'$: 9 gates. From 5 ($101$): $A^+ = 0 + 0 = 0$, $B^+ = 0 + 0 =
0$, $C^+ = 0$, back to 0; without the don’t-cares the equations are longer. The run prints $0, 1, \dots, 5, 0, \dots$.

**Exercise 28.9 ★★.**

How many [flip-flops](#def-b1-sequential-circuits-flip-flop) does a machine with $k$ [states](#def-b1-sequential-circuits-fsm) need with a binary encoding? With one-hot encoding? For the [control unit](#def-b1-sequential-circuits-datapath) of [Listing 28.7](#lst-b1-sequential-circuits-control), compare, and say what one-hot encoding buys.

**Solution of Exercise 28.9.**

$\lceil \log_2 k \rceil$ with a binary encoding, $k$ with one-hot. The [control unit](#def-b1-sequential-circuits-datapath) has 23 [states](#def-b1-sequential-circuits-fsm): 5 [flip-flops](#def-b1-sequential-circuits-flip-flop) against 23. One-hot buys simple logic: the output signals are ORs of the [states](#def-b1-sequential-circuits-fsm) that order them, with no decoding of the state, and the next-state input of each [flip-flop](#def-b1-sequential-circuits-flip-flop) is an OR of the [transitions](#def-b1-sequential-circuits-fsm) entering its state. Hardware designers often pay the [flip-flops](#def-b1-sequential-circuits-flip-flop) for that speed.

**Exercise 28.10 ★★★.**

Prove by induction on the length of the input word that the conversions of [Proposition 28.10](#prop-b1-sequential-circuits-conversion) give equivalent machines.

**Solution of Exercise 28.10.**

Mealy $M$ to Moore $M'$: let $q_i$ be the state of $M$ after $a_1 \dots a_i$ and $o_i = \lambda(q_{i-1}, a_i)$ its $i$-th output. Claim: $M'$ is in $(q_i, o_i)$ after $i$ symbols ($i \geq 1$). For $i = 1$, $\delta'((q_0, 0), a_1) = (\delta(q_0,
a_1), \lambda(q_0, a_1)) = (q_1, o_1)$. If it holds for $i$, then $\delta'((q_i, o_i), a_{i+1}) = (q_{i+1}, o_{i+1})$. So the $i$-th output of $M'$, the output of the state entered, is $o_i$. Moore $M$ to Mealy $M'$: both machines go through the same [states](#def-b1-sequential-circuits-fsm), by induction since they have the same $\delta$; the $i$-th output of $M'$ is $\lambda(\delta(q_{i-1}, a_i)) =
\lambda(q_i)$, the $i$-th output of $M$. In both directions the output is not delayed: the Mealy output on the [transition](#def-b1-sequential-circuits-fsm) into $q_i$ and the Moore output of $q_i$ are read after the same symbol.

**Exercise 28.11 ★★★.**

In a [synchronous circuit](#def-b1-sequential-circuits-clock) the [flip-flops](#def-b1-sequential-circuits-flip-flop) have a clock-to-output delay of 50 ps, a [setup time](#def-b1-sequential-circuits-setup) of 30 ps and a [hold time](#def-b1-sequential-circuits-setup) of 10 ps; every gate takes 25 ps. Between two [registers](#def-b1-sequential-circuits-register) the longest path has 12 gates and the shortest 2. What is the highest clock frequency? Is the [hold time](#def-b1-sequential-circuits-setup) respected? What if the [shortest path](https://one-course.com/books/computer-science/3/en/chapter/25-shortest-paths#def-b1-shortest-paths-shortest) had no gate?

**Solution of Exercise 28.11.**

$T \geq 50 + 12 \times 25 + 30 = 380$ ps, so at most $1 / 380\,\text{ps} \approx 2.63$ GHz. The earliest change at a [flip-flop](#def-b1-sequential-circuits-flip-flop) input comes $50 + 2 \times 25 = 100$ ps after the edge, well after the 10 ps [hold time](#def-b1-sequential-circuits-setup). With no gate it comes after 50 ps, still enough: the clock-to-output delay itself protects the [hold time](#def-b1-sequential-circuits-setup), unless the clock reaches the two [flip-flops](#def-b1-sequential-circuits-flip-flop) at different times.

**Exercise 28.12 ★★★.**

A vending machine sells an item for 3; at each clock cycle a coin of 1 or 2, or none, is inserted. Draw its [Mealy machine](#def-b1-sequential-circuits-moore-mealy) (outputs: give the item, give back 1), derive simplified next-state and output equations, and simulate the circuit against the machine on every sequence of up to eight coins.

**Solution of Exercise 28.12.**

```python
def machine(credit, coin):
    """The state diagram, as a function: (next credit, v, r)."""
    total = credit + coin
    return (0, 1, total - 3) if total >= 3 else (total, 0, 0)
```

*The [state diagram](#def-b1-sequential-circuits-moore-mealy), as a function code/bachelor-1/28-sequential-circuits/exercises/vending.py*

The credit is 0, 1 or 2 ($AB = 00, 01, 10$); with coins $c_1 c_0 = 00, 01, 10$, the code 11 and the credit 3 are don’t-cares. The program finds $A^+ = Bc_0 + A'B'c_1 + Ac_1'c_0'$, $B^+ = Bc_1'c_0' + A'B'c_0$, $v = Bc_1 + Ac_0 + Ac_1$, $r =
Ac_1$: 16 gates, and the circuit agrees with the machine on all 9841 sequences of up to eight coins.

## 28.7 Problem: A combination lock

**Problem 28.1.**

Weekend problem — A combination lock

A lock has two keys, 0 and 1, and opens when the last four keys pressed are $1, 0, 1, 1$. The program builds its [Mealy machine](#def-b1-sequential-circuits-moore-mealy) from the pattern, converts it to a [Moore machine](#def-b1-sequential-circuits-moore-mealy), finds for each pair of [states](#def-b1-sequential-circuits-fsm) a word that tells them apart, and turns both machines into circuits, checked on every word of up to 12 keys.

```python
def detector(pattern):
    """Mealy machine: the state is the longest prefix of the pattern that ends the
    keys pressed so far; output 1 when the whole pattern has just been pressed."""
    prefixes = [tuple(pattern[:i]) for i in range(len(pattern))]
    delta = {}
    for p in prefixes:
        for a in KEYS:
            w = p + (a,)
            done = int(w == tuple(pattern))
            nxt = next(w[i:] for i in range(len(w) + 1) if w[i:] in prefixes)
            delta[p, a] = (nxt, done)
    return Mealy((), delta)
```

***Listing 28.10.** The detector of any pattern: [states](#def-b1-sequential-circuits-fsm) are the prefixes of the pattern code/bachelor-1/28-sequential-circuits/listings/lock.py*

```
$ python lock.py
Mealy: 4 states: e, 1, 10, 101
  6 pairs of states, each with a word telling them apart:
    e~1 '011', e~10 '11', e~101 '1', 1~10 '11', 1~101 '1'
    10~101 '1'
  A+ = Bx' + AB'x
  B+ = x
  z  = ABx
  flip-flops 2, gates 6; circuit = machine on all words of up to 12 keys: True
Moore: 5 states: e/0, 1/0, 10/0, 101/0, 1/1
  10 pairs of states, each with a word telling them apart:
    e/0~1/0 '011', e/0~10/0 '11', e/0~101/0 '1', e/0~1/1 '', 1/0~10/0 '11'
    1/0~101/0 '1', 1/0~1/1 '', 10/0~101/0 '1', 10/0~1/1 '', 101/0~1/1 ''
  A+ = BCx
  B+ = Cx' + BC'x + Ax'
  C+ = C'x + B'x
  z  = A
  flip-flops 3, gates 11; circuit = machine on all words of up to 12 keys: True
```

***Output 28.10.** The two machines, the words that distinguish their [states](#def-b1-sequential-circuits-fsm) ($e$ is the empty prefix; in the [Moore machine](#def-b1-sequential-circuits-moore-mealy) $p/o$ is the prefix $p$ entered with output $o$), and their circuits.*

**Part I — The Mealy machine.**

1. Draw the [Mealy machine](#def-b1-sequential-circuits-moore-mealy) of the output: four [states](#def-b1-sequential-circuits-fsm) , eight [transitions](#def-b1-sequential-circuits-fsm) .
2. Why is the next state of $101$ on key 1 the state $1$ , and not $e$ ?
3. Which line of the listing finds that next state, and how?
4. Run the machine by hand on $1011011$ . When does the lock open?
5. Why is the machine *complete* : why does every state have a [transition](#def-b1-sequential-circuits-fsm) for both keys?
6. The output is 1 on a [transition](#def-b1-sequential-circuits-fsm) . When, exactly, should the bolt move?

**Part II — The Moore machine.**

7. Draw the [Moore machine](#def-b1-sequential-circuits-moore-mealy) ; which state is new?
8. Why does the conversion give five [states](#def-b1-sequential-circuits-fsm) and not $4 \times 2 = 8$ ?
9. On the same word $1011011$ , compare the outputs of the two machines step by step.
10. Why do the pairs involving $1/1$ need only the empty word?
11. Explain why a word that tells two [states](#def-b1-sequential-circuits-fsm) apart proves that no equivalent machine can merge them.
12. Conclude that four Mealy [states](#def-b1-sequential-circuits-fsm) and five Moore [states](#def-b1-sequential-circuits-fsm) are each the fewest possible.

**Part III — Circuits.**

13. Give the binary encodings the program uses, in the order of the output.
14. Check the Mealy equation $B^+ = x$ on two [transitions](#def-b1-sequential-circuits-fsm) .
15. Why may the Moore equations use the codes 5, 6 and 7 freely?
16. Why is the Moore output $z = A$ , with no gate at all?
17. Count the gates of each circuit from its equations, as the program does.
18. Which circuit is faster from key to output, and why does the answer not depend only on gates?

**Part IV — Checking.**

19. How many words of up to 12 keys are there?
20. Show that if a circuit and a machine have the same output and next state on every reachable state and key, they agree on every word, of any length.
21. Every state is reachable in at most four keys. Why do the words of up to 12 keys check every state and key, and more?
22. What would a wrong encoding (two [states](#def-b1-sequential-circuits-fsm) with the same code) do to the check?
23. A real keypad has ten keys. How does the machine change, and how many words of up to 12 keys are there now?
24. State the named result, *Mealy saves a state* , with the counts of [states](#def-b1-sequential-circuits-fsm) , [flip-flops](#def-b1-sequential-circuits-flip-flop) and gates.

**Solution of Problem 28.1.**

**1.** [States](#def-b1-sequential-circuits-fsm) $e, 1, 10, 101$. From $e$: $0 \to e$, $1 \to 1$. From $1$: $0 \to 10$, $1 \to 1$. From $10$: $0 \to e$, $1 \to 101$. From $101$: $0 \to 10$, $1/\mathbf{1} \to 1$. Every other output is 0.

**2.** After $1011$, the longest end of the input that begins the pattern is the last $1$: a new attempt has begun. $e$ would forget it, and miss the lock opening on $1011011$.

**3.** Line 22: it tries the ends of $w$ from the longest to the empty one, and keeps the first that is a prefix.

**4.** The outputs are $0001001$: the lock opens after the fourth and the seventh keys, the second $1011$ sharing a 1 with the first.

**5.** The double loop over prefixes and keys makes one entry per pair, and `next` always finds an end, the empty one at worst.

**6.** As the fourth key is pressed: the output is 1 during the clock cycle of that key, before the next edge.

**7.** $e/0, 1/0, 10/0, 101/0$ and the new $1/1$, the state $1$ entered by the opening [transition](#def-b1-sequential-circuits-fsm).

**8.** Only reachable pairs are kept: only $1$ is ever entered with an output of 1.

**9.** Both print $0001001$, as [Proposition 28.10](#prop-b1-sequential-circuits-conversion) says; the [Moore machine](#def-b1-sequential-circuits-moore-mealy) shows each 1 as the output of the state $1/1$.

**10.** $1/1$ is the only state with output 1, so its own output already differs from every other’s.

**11.** If two [states](#def-b1-sequential-circuits-fsm) differ on a word $w$, two inputs leading to them (here the prefixes that name them) followed by $w$ give different outputs; a machine in the same state after both would give the same.

**12.** The printed words separate all $\binom{4}{2} = 6$ Mealy pairs and all $\binom{5}{2} = 10$ Moore pairs, so no two [states](#def-b1-sequential-circuits-fsm) can be merged: in a [Moore machine](#def-b1-sequential-circuits-moore-mealy), after the words $1$ and $1011$ the futures are equal but the current outputs differ.

**13.** Mealy: $e = 00$, $1 = 01$, $10 = 10$, $101 = 11$. Moore: $e/0 = 000$, $1/0 = 001$, $10/0 = 010$, $101/0 = 011$, $1/1 = 100$.

**14.** From $10$ ($AB = 10$) on 1 to $101$ ($11$): $B^+ = 1$. From $101$ on 0 to $10$: $B^+ = 0$. The low bit records whether the last key was 1.

**15.** No state has them, so their rows never occur: don’t-cares.

**16.** Only $1/1$ has $A = 1$, and the codes 5 to 7 are don’t-cares.

**17.** Mealy: NOT $x$, NOT $B$, ANDs $Bx'$, $AB'x$, $ABx$, one OR: 6. Moore: NOTs of $B$, $C$ and $x$, six ANDs and two ORs: 11.

**18.** The Mealy output is one AND gate away from the key, within the same cycle; the Moore output comes from a [flip-flop](#def-b1-sequential-circuits-flip-flop), one clock edge later but free of the input’s glitches. Timing depends on the clock as much as on gates.

**19.** $2^{13} - 1 = 8191$, the empty word included.

**20.** By induction on the length: they start in the same state, and if they are in the same state after $i$ keys, equal next-state functions put them in the same state after $i + 1$, with the same output.

**21.** Every state followed by every key appears within the first five keys of some word, so the check covers every reachable (state, key) pair, and **20** extends it to every length.

**22.** Two [states](#def-b1-sequential-circuits-fsm) with one code would merge them, and some word in the check, such as the distinguishing word following the two prefixes, would show a difference.

**23.** Keys 2 to 9 send every state back to $e$ (they begin no attempt); the [states](#def-b1-sequential-circuits-fsm) stay the same. There are $(10^{13} - 1) / 9 \approx 1.1 \times 10^{12}$ words of up to 12 keys; **20** and **21** make a check of all [states](#def-b1-sequential-circuits-fsm) and keys enough.

**24.** *Mealy saves a state*: the lock needs 4 Mealy [states](#def-b1-sequential-circuits-fsm) and 5 Moore [states](#def-b1-sequential-circuits-fsm), each number minimal by the distinguishing words; the circuits need 2 [flip-flops](#def-b1-sequential-circuits-flip-flop) and 6 gates against 3 [flip-flops](#def-b1-sequential-circuits-flip-flop) and 11 gates.
