So far, outputs depended only on the current inputs. To build counters, registers and processors, circuits must remember. The trick is feedback: an output wired back to an input.
The SR latch
Two NOR gates, each feeding its output into the other's input, form an SR latch. Setting S = 1 makes Q = 1; R = 1 makes Q = 0; with S = R = 0 the loop keeps whatever it had. S = R = 1 is not allowed: both outputs become 0, and when both inputs drop, the result is unpredictable.
def nor(a, b):
return 1 - (a | b)
q, q_bar = 0, 1 # the latch starts holding 0
for s, r in [(1, 0), (0, 0), (0, 1), (0, 0)]:
for _ in range(3): # let the feedback loop settle
q = nor(r, q_bar)
q_bar = nor(s, q)
print("S =", s, "R =", r, "-> Q =", q)From latch to flip-flop
A D latch has one data input D and an enable: while enable is 1, Q follows D; when it drops to 0, Q holds. That is useful but leaky: Q can change several times while enabled.
A flip-flop changes only at an instant: the rising edge of the clock, when it goes from 0 to 1. Between edges, its inputs may wobble; only their value at the edge counts. Every register in a processor is built from flip-flops, so the whole chip moves one step per clock tick.
| Flip-flop | At the clock edge | Use |
|---|---|---|
| D | Q becomes D | registers, storing a bit |
| T | T = 1: Q flips; T = 0: Q holds | counters |
| JK | 00 hold, 01 reset, 10 set, 11 toggle | general purpose |
| SR | 00 hold, 01 reset, 10 set, 11 not allowed | (replaced by JK) |
JK is the SR flip-flop with the forbidden case put to use: J = K = 1 toggles. Change the inputs and step through the clocks:
q = 0
for clock, (j, k) in enumerate([(1, 0), (0, 0), (1, 1), (1, 1), (0, 1)], start=1):
if j and k:
q = 1 - q # toggle
elif j:
q = 1 # set
elif k:
q = 0 # reset
print("clock", clock, ": J =", j, "K =", k, "-> Q =", q)Real flip-flops need their input to be steady for a moment before the edge (setup time) and after it (hold time); this sets a chip's top clock speed.
Common mistakes
- Thinking a flip-flop's output changes as soon as its input does: it waits for the clock edge.
- Giving an SR latch S = R = 1.
- Mixing up latches (level-triggered: transparent while enabled) and flip-flops (edge-triggered).
Quick check
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.