এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
University Computer Science — Year 1 · স্নাতক প্রথম বর্ষ
28Sequential Circuits and Finite-State Machines
A traffic light changes every thirty seconds, and it knows which colour comes next. The circuits of Chapter 27 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, 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, the model behind every controller, whose most important example is the control unit 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 and the state machine, and its toy machine runs a fetch–decode–execute cycle; combinational circuits, Karnaugh maps, the ALU and propagation delay are in Chapter 27.
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 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, 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.
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
$ 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
Definition 28.2 (Latch, SR latch, D latch)
A latch is a circuit with two stable states that stores one bit. An SR latch has inputs (set) and (reset): makes its output 1, makes it 0, and keeps it. The input is forbidden. A D latch has a data input and an enable : while its output follows (it is transparent), and while it keeps the last value.
| next | ||
|---|---|---|
| 0 | 0 | (hold) |
| 1 | 0 | 1 (set) |
| 0 | 1 | 0 (reset) |
| 1 | 1 | forbidden |
With each NOR gate is an inverter, and two inverters in a loop are stable in two ways, and : that is the stored bit. forces , hence ; forces the opposite. With 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 puts two AND gates in front: and , so the forbidden input cannot happen. Its transparency is a problem, however. If the output of a latch feeds, through some logic, back to its own input, a change can run round the loop many times while the 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 to its output at each rising edge (a change from 0 to 1) of its clock input, and keeps the rest of the time.
Two D latches make one. The first, the master, is enabled while the clock is 0 and follows ; 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 had at that moment, and the slave opens and shows it; while the clock is 1, may change, but the master is closed.
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
$ 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
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, all driven by the same clock, and of combinational logic between them, with no loop that does not pass through a flip-flop.
In a synchronous circuit the state, the contents of the flip-flops, 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 load at the next edge. Every loop is cut by a flip-flop, so the logic between edges is combinational, and Chapter 27 applies to it.
Definition 28.5 (Setup time, hold time)
The setup time of a 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 finds a setup time of 2 units: a that falls one unit before the edge is missed, because the path from through the NOT gate into the master is one gate longer than the path of a rising . Its hold time is 0, and the clock-to-output delay 2 units. The figure below draws the run.
The clock period is bounded below. After an edge, the new state appears at the flip-flop outputs a clock-to-output delay later, crosses the combinational logic along its longest delay path (Definition 27.12), and must arrive a setup time before the next edge:
The hold time puts a bound on the shortest path: the new values must not reach the next flip-flops before their hold time has passed. A processor’s clock frequency is set by the slowest path between two of its registers.
28.3 Registers, counters and memory
Definition 28.6 (Register, shift register, counter)
A register is a row of flip-flops 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 at successive edges.
The enable is a multiplexer in front of each flip-flop, choosing between its own output and the new input: a register with enable is a synchronous circuit, its clock never stopped.
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]
$ 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
A shift 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 can be built two ways. In a synchronous counter every 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 only the first 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.
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
$ 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
A circuit that reads the ripple counter while it settles may see 2 or 0 between 3 and 4: a glitch. The synchronous counter has none, and settles in one flip-flop delay whatever its width, where the ripple counter needs .
A memory is many registers and a way to choose one. A -to- decoder (Definition 27.10) turns the address into one selected row; a write loads the row whose decoder output is 1; a read sends the selected row through a multiplexer 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.
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
$ 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
More than half of the gates are cells, and the share grows with the size: a memory of words of bits needs gates of cells against about for the decoder. Real memories make the cell as small as possible: six transistors in a static 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 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.
28.4 Finite-state machines
Every synchronous circuit is the same object seen from far: a state, kept in flip-flops; 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 , an output alphabet, and a transition function that gives, for each state and input symbol , the next state . 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 of the state; in a Mealy machine it is a function of the state and the input, attached to the transition. A state diagram draws the states as circles and each transition as an arrow labelled by its input (and, for a Mealy machine, its output, as ). A state encoding gives each state a distinct word of bits, to be stored in flip-flops.
For an input word a Mealy machine outputs and a Moore machine , where is the state after 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 there is an equivalent Mealy machine with the same states, and for every Mealy machine with state set and output alphabet there is an equivalent Moore machine with at most states.
Proof. Moore to Mealy: put on each transition the output of the state it enters, . Mealy to Moore: take the pairs as states, meaning “in , having just output ”, with and output . Both machines go through the same states , and the output read after step is in both; Exercise 28.10 writes the induction out. ∎
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()})
The example is a sequence detector: it reads bits and outputs 1 exactly when the last three were . Overlaps count: in it fires twice. Its Mealy states remember the longest end of the input that is a beginning of : nothing, , or .
$ 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]
From a state diagram to a circuit. Four steps make a machine into a synchronous circuit. Encode the states in bits, one 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); and connect the logic’s outputs to the flip-flops’ 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
says that the low state bit is just the last input, a one-bit shift register; needs one gate. A different encoding gives different equations, sometimes better ones; one-hot encoding, one flip-flop per state, spends flip-flops to make the logic trivial (Exercise 28.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 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, the ALU, the buses and multiplexers between them, and the connection to memory. The control unit is a finite-state machine that, at each clock cycle, sends the datapath the signals that choose which register transfer happens: which register is loaded, from which source, with which ALU operation.
The datapath of the toy machine has the four registers, the program counter PC, the stack pointer SP, the flags, and two instruction registers IR0 and IR1 for the two bytes of the current instruction; its ALU is that of Definition 27.11 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 is a Moore machine: each state names the 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.
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)
R is the 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.
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
$ 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
The control unit has 23 states, so five flip-flops 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 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 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 starts with . Its inputs take the values , , , , , each held long enough for the latch to settle. Give after each.
Solution
Solution of Exercise 28.1.
(set), (hold), (reset), (set), (hold).
Exercise 28.2 ★
The synchronous 3-bit counter of Listing 28.4 holds 5. Give its value after each of the next five clock edges, and which bits flip at each.
Solution
Solution of Exercise 28.2.
6, 7, 0, 1, 2. From 5 () bits 0 and 1 flip; from 6 bit 0; from 7 all three; from 0 bit 0; from 1 bits 0 and 1. Bit flips when all the bits below it are 1.
Exercise 28.3 ★
What does the Moore detector of Output 28.6 output on the input word ? Give the states it goes through.
Solution
Solution of Exercise 28.3.
The states are , then , , , , , , , , and the output word : the detector fires at the fourth and the sixth bit, the second overlapping the first.
Exercise 28.4 ★
A 4-bit shift register as in Listing 28.3 holds . The bits enter at four edges. Give its contents after each.
Solution
Solution of Exercise 28.4.
, , , : each bit enters on the left and the rightmost one leaves.
Exercise 28.5 ★★
A circuit compares the 3-bit ripple counter of Output 28.4 with 2, and sounds a bell when they are equal. The counter goes from 0 to 7 once. How many times does the bell sound, and when? Repair the design.
Solution
Solution of Exercise 28.5.
Twice. Once rightly, while the count is 2; once wrongly, between 3 and 4, where the counter shows 2 for time units (Output 28.4). Two repairs: use the synchronous counter, whose bits change together; or feed the comparator’s output into a 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.
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
$ python exo_incomplete.py
['cars go', 'cars slow', 'people cross', 'cars go', 'cars go']
KeyError: ('red', 1)
Solution
Solution of Exercise 28.6.
The pair ("red", 1) has no transition: the state diagram leaves out what happens when someone presses the button while people cross, and the first word never does that. A finite-state machine must have a transition 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 entries.
Exercise 28.7 ★★
Build the Mealy detector of , overlaps allowed, and test it on every word of up to 12 bits against the definition.
Solution
Solution of Exercise 28.7.
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 of Listing 28.10, built for , has the states , , , ; after it goes to , since the last 0 begins a new pattern. It agrees with the definition on all 8191 words.
Exercise 28.8 ★★
Design a synchronous counter modulo 6 on three D flip-flops: the next-state equations, simplified with the codes 6 and 7 as don’t-cares, and a check that it counts .
Solution
Solution of Exercise 28.8.
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 program finds , , : 9 gates. From 5 (): , , , back to 0; without the don’t-cares the equations are longer. The run prints .
Exercise 28.9 ★★
How many flip-flops does a machine with states need with a binary encoding? With one-hot encoding? For the control unit of Listing 28.7, compare, and say what one-hot encoding buys.
Solution
Solution of Exercise 28.9.
with a binary encoding, with one-hot. The control unit has 23 states: 5 flip-flops against 23. One-hot buys simple logic: the output signals are ORs of the states that order them, with no decoding of the state, and the next-state input of each flip-flop is an OR of the transitions entering its state. Hardware designers often pay the flip-flops for that speed.
Exercise 28.10 ★★★
Prove by induction on the length of the input word that the conversions of Proposition 28.10 give equivalent machines.
Solution
Solution of Exercise 28.10.
Mealy to Moore : let be the state of after and its -th output. Claim: is in after symbols (). For , . If it holds for , then . So the -th output of , the output of the state entered, is . Moore to Mealy : both machines go through the same states, by induction since they have the same ; the -th output of is , the -th output of . In both directions the output is not delayed: the Mealy output on the transition into and the Moore output of are read after the same symbol.
Exercise 28.11 ★★★
In a synchronous circuit the flip-flops have a clock-to-output delay of 50 ps, a setup time of 30 ps and a hold time of 10 ps; every gate takes 25 ps. Between two registers the longest path has 12 gates and the shortest 2. What is the highest clock frequency? Is the hold time respected? What if the shortest path had no gate?
Solution
Solution of Exercise 28.11.
ps, so at most GHz. The earliest change at a flip-flop input comes ps after the edge, well after the 10 ps hold time. With no gate it comes after 50 ps, still enough: the clock-to-output delay itself protects the hold time, unless the clock reaches the two flip-flops 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 (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
Solution of Exercise 28.12.
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 credit is 0, 1 or 2 (); with coins , the code 11 and the credit 3 are don’t-cares. The program finds , , , : 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 . The program builds its Mealy machine from the pattern, converts it to a Moore machine, finds for each pair of states a word that tells them apart, and turns both machines into circuits, checked on every word of up to 12 keys.
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)
$ 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
Part I — The Mealy machine.
- Draw the Mealy machine of the output: four states, eight transitions.
- Why is the next state of on key 1 the state , and not ?
- Which line of the listing finds that next state, and how?
- Run the machine by hand on . When does the lock open?
- Why is the machine complete: why does every state have a transition for both keys?
- The output is 1 on a transition. When, exactly, should the bolt move?
Part II — The Moore machine.
- Draw the Moore machine; which state is new?
- Why does the conversion give five states and not ?
- On the same word , compare the outputs of the two machines step by step.
- Why do the pairs involving need only the empty word?
- Explain why a word that tells two states apart proves that no equivalent machine can merge them.
- Conclude that four Mealy states and five Moore states are each the fewest possible.
Part III — Circuits.
- Give the binary encodings the program uses, in the order of the output.
- Check the Mealy equation on two transitions.
- Why may the Moore equations use the codes 5, 6 and 7 freely?
- Why is the Moore output , with no gate at all?
- Count the gates of each circuit from its equations, as the program does.
- Which circuit is faster from key to output, and why does the answer not depend only on gates?
Part IV — Checking.
- How many words of up to 12 keys are there?
- 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.
- 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?
- What would a wrong encoding (two states with the same code) do to the check?
- A real keypad has ten keys. How does the machine change, and how many words of up to 12 keys are there now?
- State the named result, Mealy saves a state, with the counts of states, flip-flops and gates.
Solution
Solution of Problem 28.1.
1. States . From : , . From : , . From : , . From : , . Every other output is 0.
2. After , the longest end of the input that begins the pattern is the last : a new attempt has begun. would forget it, and miss the lock opening on .
3. Line 22: it tries the ends of from the longest to the empty one, and keeps the first that is a prefix.
4. The outputs are : the lock opens after the fourth and the seventh keys, the second 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. and the new , the state entered by the opening transition.
8. Only reachable pairs are kept: only is ever entered with an output of 1.
9. Both print , as Proposition 28.10 says; the Moore machine shows each 1 as the output of the state .
10. is the only state with output 1, so its own output already differs from every other’s.
11. If two states differ on a word , two inputs leading to them (here the prefixes that name them) followed by give different outputs; a machine in the same state after both would give the same.
12. The printed words separate all Mealy pairs and all Moore pairs, so no two states can be merged: in a Moore machine, after the words and the futures are equal but the current outputs differ.
13. Mealy: , , , . Moore: , , , , .
14. From () on 1 to (): . From on 0 to : . 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 has , and the codes 5 to 7 are don’t-cares.
17. Mealy: NOT , NOT , ANDs , , , one OR: 6. Moore: NOTs of , and , 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, one clock edge later but free of the input’s glitches. Timing depends on the clock as much as on gates.
19. , 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 keys, equal next-state functions put them in the same state after , 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 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 (they begin no attempt); the states stay the same. There are words of up to 12 keys; 20 and 21 make a check of all states and keys enough.
24. Mealy saves a state: the lock needs 4 Mealy states and 5 Moore states, each number minimal by the distinguishing words; the circuits need 2 flip-flops and 6 gates against 3 flip-flops and 11 gates.
এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ
- Clock signal, clock period, synchronous circuit
- Datapath, control unit
- Finite-state machine
- Flip-flop, edge-triggered D flip-flop
- Latch, SR latch, D latch
- Memory cell
- Moore machine, Mealy machine, state diagram, state encoding
- Register, shift register, counter
- Sequential circuit
- Setup time, hold time