Breadboard exercises/ P7EnglishРусский

Exercise P7 · project · finite state machine

Bit-serial comparator: an FSM against the 4063

The 4063 of exercise BB3 compares two 4-bit numbers in one go. This circuit compares numbers of any length, one bit per clock, with two flip-flops and a handful of gates: time instead of wires, the trade every chip designer makes.

5 chips4069, 4077, 4081, 4071, 4013
48 + 12 wireson the board + jumper leads to the modules
any lengthone bit of A and B per clock
~1 Hzfrom the 555 clock module

1What it is and why it matters

What it does. Press RESET to start. Then, at every blink of the clock module, hold the buttons A and B for one bit of each number, lowest bit first: pressed is 1, released is 0. The traffic light always shows how the numbers entered so far compare: green for A > B, yellow for A = B, red for A < B.

How it works. Two flip-flops of a 4013 hold GT (A > B so far) and LT (A < B so far). A new bit weighs more than all the earlier bits together. So if the new bits differ, they decide; if they are the same, the old result stays:

GT and LT are never 1 together, so NOR (GT, LT) is the same as GT XNOR LT, and a spare gate of the 4077 makes EQ instead of a fifth gate chip.

Where it is used. Serial links send numbers one bit after another, and a circuit that works bit by bit needs no wide buses. Processors compare numbers by subtracting them in the ALU and looking at the flags; this machine does the same as a subtractor that keeps only the sign of the difference.

Why learn it.

2The key elements: the newest bit decides

A = 6 = 0110 and B = 10 = 1010, lowest bit first:

ClockBitABNumbers so farGTLTLight
1bit 0000 : 000yellow
2bit 1112 : 200yellow
3bit 2106 : 210green
4bit 3016 : 1001red

Waveforms

CLKRSTABGTEQLT
From the simulation of tb.sv in Icarus Verilog: the example above, then 5 against 3 after a reset. The light changes one clock edge after the bits that decide. · SVG · PNG

3Parts

PartIn this circuitQtyPriceSupplier
CD4077quad XNOR: A XNOR B, the bits are equal, and EQ = GT XNOR LT (two of four used)1$0.30Futurlec (futurlec.com)
CD4069hex inverter: NOT A and NOT B (two of six used)1$0.30Elexp (elexp.com)
CD4081quad AND: all four used1$0.55Elexp (elexp.com)
CD4071quad OR: two used, for the next GT and LT1$0.25Elexp (elexp.com)
CD4013dual D flip-flop: GT and LT1$0.35Elexp (elexp.com)
Button modulesRESET and the bits of A and B; 3 from the pack of five3$0.66 / packaliexpress.us
555 clock modulethe clock, set to about 1 Hz1$0.53aliexpress.us
Traffic-light LED module, 5 VA > B green, equal yellow, A < B red; plugged into the board; resistors built in1$0.40aliexpress.us
Breadboard, 830 points1$3.00amazon.com
Breadboard power module5 V on the rails1$1.00aliexpress.us
USB-to-DC cable, 9 Vpowers the module from a USB charger1$1.17aliexpress.us
Pre-cut jumper wires48 wires on the board (or male-male Dupont jumpers)48$11.95 / packjameco.com
Male-female Dupont jumpers12 leads to the clock module and the buttons12$1.30 / packaliexpress.us

Prices from the LSSK components sheet; these chips are in the FSM kit.

4The chips, pin by pin

The chips are CMOS 4000B series: they work from 3 to 18 V, here from the 5 V of the power module. Every input must be connected to something, because a CMOS input left open picks up noise and can switch at random. The drawings show each chip from above with the notch on the left, as in the datasheet: pin 1 at the bottom left, pins numbered counter-clockwise. Blue arrows are inputs, orange arrows are outputs.

4069: hex inverter

1A2G3B4H5C6I7VSS8J9D10K11E12L13F14VDD4069
CD4069UB. · SVG · PNG

Two inverters make NOT A and NOT B; the inputs of the other four are tied to the rails.

PinNameDirectionFunctionIn this circuit
1Ainputinput of the gate with its output on pin 2A
2GoutputG = NOT AA
3Binputinput of the gate with its output on pin 4tied to +5V
4HoutputH = NOT Bnot connected
5Cinputinput of the gate with its output on pin 6tied to +5V
6IoutputI = NOT Cnot connected
7VSSpowerground, 0 VGND
8JoutputJ = NOT DB
9Dinputinput of the gate with its output on pin 8B
10KoutputK = NOT Enot connected
11Einputinput of the gate with its output on pin 10tied to GND
12LoutputL = NOT Fnot connected
13Finputinput of the gate with its output on pin 12tied to GND
14VDDpowersupply, +5 V (3 to 18 V allowed)+5V

4077: quad 2-input XNOR

1A2B3J4K5C6D7VSS8E9F10L11M12G13H14VDD4077
CD4077B. · SVG · PNG

One gate makes X = A XNOR B, another EQ = GT XNOR LT. The inputs of the other two are tied to GND.

PinNameDirectionFunctionIn this circuit
1Ainputinput of the gate with its output on pin 3GT
2Binputinput of the gate with its output on pin 3LT
3JoutputJ = NOT (A XOR B)EQ
4KoutputK = NOT (C XOR D)not connected
5Cinputinput of the gate with its output on pin 4tied to GND
6Dinputinput of the gate with its output on pin 4tied to GND
7VSSpowerground, 0 VGND
8Einputinput of the gate with its output on pin 10tied to +5V
9Finputinput of the gate with its output on pin 10tied to +5V
10LoutputL = NOT (E XOR F)not connected
11MoutputM = NOT (G XOR H)X
12Ginputinput of the gate with its output on pin 11A
13Hinputinput of the gate with its output on pin 11B
14VDDpowersupply, +5 V (3 to 18 V allowed)+5V

4081: quad 2-input AND

1A2B3J4K5C6D7VSS8E9F10L11M12G13H14VDD4081
CD4081B. · SVG · PNG

All four gates: A·NOT B, NOT A·B, GT·X and LT·X.

PinNameDirectionFunctionIn this circuit
1Ainputinput of the gate with its output on pin 3A
2Binputinput of the gate with its output on pin 3B
3JoutputJ = A AND BA·B
4KoutputK = C AND DA·B
5Cinputinput of the gate with its output on pin 4A
6Dinputinput of the gate with its output on pin 4B
7VSSpowerground, 0 VGND
8Einputinput of the gate with its output on pin 10X
9Finputinput of the gate with its output on pin 10GT
10LoutputL = E AND FGT·X
11MoutputM = G AND HLT·X
12Ginputinput of the gate with its output on pin 11LT
13Hinputinput of the gate with its output on pin 11X
14VDDpowersupply, +5 V (3 to 18 V allowed)+5V

4071: quad 2-input OR

1A2B3J4K5C6D7VSS8E9F10L11M12G13H14VDD4071
CD4071B. · SVG · PNG

Two gates make GT' and LT'; the inputs of the other two are tied to GND.

PinNameDirectionFunctionIn this circuit
1Ainputinput of the gate with its output on pin 3tied to GND
2Binputinput of the gate with its output on pin 3tied to GND
3JoutputJ = A OR Bnot connected
4KoutputK = C OR DGT'
5Cinputinput of the gate with its output on pin 4A·B
6Dinputinput of the gate with its output on pin 4GT·X
7VSSpowerground, 0 VGND
8Einputinput of the gate with its output on pin 10A·B
9Finputinput of the gate with its output on pin 10LT·X
10LoutputL = E OR FLT'
11MoutputM = G OR Hnot connected
12Ginputinput of the gate with its output on pin 11tied to +5V
13Hinputinput of the gate with its output on pin 11tied to +5V
14VDDpowersupply, +5 V (3 to 18 V allowed)+5V

4013: dual D flip-flop

1Q12Q13CLK14R15D16S17VSS8S29D210R211CLK212Q213Q214VDD40132 × D flip-flop
CD4013B. · SVG · PNG

As in exercise B4. Flip-flop 1 holds GT (D1 pin 5, Q1 pin 1), flip-flop 2 holds LT (D2 pin 9, Q2 pin 13). Both take the clock (pins 3 and 11) and RESET (pins 4 and 10); the set inputs (pins 6 and 8) are at GND.

PinNameDirectionFunctionIn this circuit
1Q1outputflip-flop 1 outputGT
2Q1outputflip-flop 1 output, invertednot connected
3CLOCK1inputflip-flop 1 stores D1 on the rising edge, 0 to 1CLK
4RESET1input1 sets Q1 = 0 at once, without the clock. Active highRST
5D1inputflip-flop 1 data inputGT'
6SET1input1 sets Q1 = 1 at once, without the clock. Active highGND
7VSSpowerground, 0 VGND
8SET2input1 sets Q2 = 1 at once. Active highGND
9D2inputflip-flop 2 data inputLT'
10RESET2input1 sets Q2 = 0 at once. Active highRST
11CLOCK2inputflip-flop 2 stores D2 on the rising edgeCLK
12Q2outputflip-flop 2 output, invertednot connected
13Q2outputflip-flop 2 outputLT
14VDDpowersupply, +5 V (3 to 18 V allowed)+5V

5Schematic 1: gates and two flip-flops

CLKRESETAB406940774069408140814081408140714071DRQ4013DRQ40134077GTgreenEQyellowLTred
The circuit as gates and flip-flops. This is what serial_compare.sv describes. The lines along the top and the bottom bring GT and LT back to the AND gates. · SVG · PNG

6Schematic 2: connections between the chips

123456789101112131440771234567891011121314406912345678910111213144081123456789101112131440711234567891011121314Q1Q1CLK1R1D1S1S2D2R2CLK2Q2Q240132 × D flip-flopGYRGNDCLKRSTABABXA·BA·BGT·XLT·XGT'LT'GTLTEQclockRESETAB+5V
The same circuit as chips, pin by pin. The traffic light is on the right. · SVG · PNG
NetFromToWire
CLK555 clock module, OUT4013 3 (CLK1), 4013 11 (CLK2)M-F, M-M
RSTbutton RESET, OUT4013 4 (R1), 4013 10 (R2)M-F, M-M
Abutton A, OUT4069 1 (A), 4077 12 (G), 4081 1 (A)M-F, M-M
Bbutton B, OUT4069 9 (D), 4077 13 (H), 4081 6 (D)M-F, M-M
A4069 2 (G)4081 5 (C)M-M
B4069 8 (J)4081 2 (B)M-M
X4077 11 (M)4081 8 (E), 4081 13 (H)M-M
A·B4081 3 (J)4071 5 (C)M-M
A·B4081 4 (K)4071 8 (E)M-M
GT·X4081 10 (L)4071 6 (D)M-M
LT·X4081 11 (M)4071 9 (F)M-M
GT'4071 4 (K)4013 5 (D1)M-M
LT'4071 10 (L)4013 9 (D2)M-M
GT4013 1 (Q1)4081 9 (F), 4077 1 (A), traffic light, GM-M
LT4013 13 (Q2)4081 12 (G), 4077 2 (B), traffic light, RM-M
EQ4077 3 (J)traffic light, YM-M
+5V+5V4077 14 (VDD), 4069 14 (VDD), 4081 14 (VDD), 4071 14 (VDD), 4013 14 (VDD), 4077 9 (F), 4077 8 (E), 4069 5 (C), 4069 3 (B), 4071 13 (H), 4071 12 (G)
GNDGND4077 7 (VSS), 4069 7 (VSS), 4081 7 (VSS), 4071 7 (VSS), 4013 7 (VSS), traffic light, GND, 4077 5 (C), 4077 6 (D), 4069 11 (E), 4069 13 (F), 4071 1 (A), 4071 2 (B), 4013 6 (S1), 4013 8 (S2)
not connected4077 4 (K), 4077 10 (L), 4069 4 (H), 4069 6 (I), 4069 10 (K), 4069 12 (L), 4071 3 (J), 4071 11 (M), 4013 2 (Q1), 4013 12 (Q2)

7Schematic 3: the breadboard

−+−+123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263abcdefghij5V5VPOWER MODULE · 5V9V USB-DC40774069408140714013GYRGNDTRAFFIC LIGHTCLKRSTAABBABXXA·BA·BGT·XLT·XGT'LT'GTGTGTLTLTLTEQ−OUT+555CLOCK 555~1 Hz+OUT−RESET+OUT−A+OUT−B
Every wire in its hole. Column numbers are printed along the top; rows a–e are above the gap, f–j below it. The clock module and the three buttons hang above the board; the traffic light is plugged into the board on the right. · SVG · PNG
CLKRSTABABXA·BA·BGT·XLT·XGT'LT'GTLTEQ+5VGND

Build it step by step

  1. Do the getting-started steps first: how the breadboard is connected inside, the power module with both jumpers on 5 V, how a chip sits across the gap.
  2. Insert the chips across the gap: the 4077, notch to the left, pin 1 in hole 19f; the 4069 turned around, notch to the right, pin 1 in hole 33e; the 4081 turned around, notch to the right, pin 1 in hole 42e; the 4071, notch to the left, pin 1 in hole 44f; the 4013, notch to the left, pin 1 in hole 52f. Read the numbers on the chips: many look alike. A chip turned around has pin 1 at the top right: it puts the pins this circuit needs next to its neighbours.
  3. Plug the traffic-light module into the board as the drawing shows, G on the left and GND on the right.
  4. Power: for each chip a red wire from its VDD pin (14, or 16 on a 16-pin chip) to the + rail and a black wire from its VSS pin (7 or 8) to the − rail, each to the rail on its own side of the gap. On a chip turned around VDD is on the bottom row and VSS on the top row. Make sure no wire touches + and − at the same time.
  5. The fixed inputs: the set inputs of the 4013, the inputs of the unused gates and the GND pin of the traffic light.
  6. The signal wires, following the checklist. There are many; tick each wire as you insert it.
  7. With the power off, the modules: the clock module, RESET, A and B above the board.
  8. Turn the power on and set the clock module to about one blink per second.

Wiring checklist

·

#NetFromTo
Power (red to +, black to −) · 11 wires
1+5V19a (4077 pin 14, VDD)top + rail, column 19
2GND25j (4077 pin 7, VSS)bottom − rail, column 25
3+5V33j (4069 pin 14, VDD)bottom + rail, column 33
4GND27a (4069 pin 7, VSS)top − rail, column 27
5+5V42j (4081 pin 14, VDD)bottom + rail, column 42
6GND36a (4081 pin 7, VSS)top − rail, column 36
7+5V44a (4071 pin 14, VDD)top + rail, column 44
8GND50j (4071 pin 7, VSS)bottom − rail, column 50
9+5V52a (4013 pin 14, VDD)top + rail, column 52
10GND58j (4013 pin 7, VSS)bottom − rail, column 58
11GND14j (traffic light, GND)bottom − rail, column 14
Fixed inputs: CMOS inputs must not float · 14 wires
12GND23j (4077 pin 5, C)bottom − rail, column 23
13+5V24a (4077 pin 9, F)top + rail, column 24
14GND24j (4077 pin 6, D)bottom − rail, column 24
15+5V25a (4077 pin 8, E)top + rail, column 25
16+5V29a (4069 pin 5, C)top + rail, column 29
17GND30j (4069 pin 11, E)bottom − rail, column 30
18+5V31a (4069 pin 3, B)top + rail, column 31
19GND32j (4069 pin 13, F)bottom − rail, column 32
20GND44j (4071 pin 1, A)bottom − rail, column 44
21+5V45a (4071 pin 13, H)top + rail, column 45
22GND45j (4071 pin 2, B)bottom − rail, column 45
23+5V46a (4071 pin 12, G)top + rail, column 46
24GND57j (4013 pin 6, S1)bottom − rail, column 57
25GND58a (4013 pin 8, S2)top − rail, column 58
Signal wires · 23 wires
26CLK54g (4013 pin 3, CLK1)55c (4013 pin 11, CLK2)
27RST55g (4013 pin 4, R1)56d (4013 pin 10, R2)
28A33c (4069 pin 1, A)42c (4081 pin 1, A)
29A33d (4069 pin 1, A)21c (4077 pin 12, G)
30B28g (4069 pin 9, D)20d (4077 pin 13, H)
31B20a (4077 pin 13, H)37b (4081 pin 6, D)
32A32d (4069 pin 2, G)38d (4081 pin 5, C)
33B27g (4069 pin 8, J)41b (4081 pin 2, B)
34X22b (4077 pin 11, M)36g (4081 pin 8, E)
35X36h (4081 pin 8, E)41h (4081 pin 13, H)
36A·B40a (4081 pin 3, J)48g (4071 pin 5, C)
37A·B39d (4081 pin 4, K)50d (4071 pin 8, E)
38GT·X38j (4081 pin 10, L)49j (4071 pin 6, D)
39LT·X39g (4081 pin 11, M)49c (4071 pin 9, F)
40GT'47h (4071 pin 4, K)56h (4013 pin 5, D1)
41LT'48b (4071 pin 10, L)57b (4013 pin 9, D2)
42GT52g (4013 pin 1, Q1)37g (4081 pin 9, F)
43GT37j (4081 pin 9, F)19j (4077 pin 1, A)
44GT19h (4077 pin 1, A)11h (traffic light, G)
45LT53a (4013 pin 13, Q2)40i (4081 pin 12, G)
46LT40j (4081 pin 12, G)20i (4077 pin 2, B)
47LT20g (4077 pin 2, B)13g (traffic light, R)
48EQ21g (4077 pin 3, J)12g (traffic light, Y)
Modules on male-female jumpers · 12 wires
49GND555 clock module, −top − rail, column 53
50CLK555 clock module, OUT55a (4013 pin 11, CLK2)
51+5V555 clock module, +top + rail, column 55
52+5Vbutton RESET, +top + rail, column 58
53RSTbutton RESET, OUT56a (4013 pin 10, R2)
54GNDbutton RESET, −top − rail, column 60
55+5Vbutton A, +top + rail, column 28
56Abutton A, OUT33a (4069 pin 1, A)
57GNDbutton A, −top − rail, column 31
58+5Vbutton B, +top + rail, column 34
59Bbutton B, OUT37a (4081 pin 6, D)
60GNDbutton B, −top − rail, column 35

Test it

If it does not work: if the light only follows the last pair of bits, the AND gates do not get GT and LT back from the flip-flops, or X stays at 0: check the XNOR gate. If green and red light together, X stays at 1 or an OR gate gets the wrong input. If green and red are swapped, A and B are swapped.

8SystemVerilog: the generic design

serial_compare.sv writes the equations into one always_ff block, and EQ as a NOR. It is synthesizable.

serial_compare.svfile
// Exercise P7: a bit-serial comparator.  It compares two numbers of any
// length that arrive one bit per clock, lowest bit first.
//
// Generic version that matches schematic 1, not tied to any chip.  gt says
// that the bits seen so far make A greater than B, lt that they make it
// less.  A new bit weighs more than all the earlier ones together: if the
// new bits of A and B differ, they decide; if they are equal, the earlier
// result stays.  eq is 1 while neither gt nor lt is.  rst starts a new
// comparison at once, without the clock.  Synthesizable.

module serial_compare
(
    input  logic clk,
    input  logic rst,
    input  logic a,    // one bit of A per clock, lowest first
    input  logic b,    // one bit of B per clock, lowest first
    output logic gt,   // A > B
    output logic lt,   // A < B
    output logic eq    // A = B
);

    wire same = a ~^ b;

    always_ff @ (posedge clk or posedge rst)
        if (rst)
        begin
            gt <= 1'b0;
            lt <= 1'b0;
        end
        else
        begin
            gt <= (a & ~ b) | (gt & same);
            lt <= (~ a & b) | (lt & same);
        end

    assign eq = ~ (gt | lt);

endmodule

9SystemVerilog models of the chips

One module per chip, with ports named as in the datasheet and the pin number of each port in a comment. The models leave out the power pins: in SystemVerilog a wire simply has the value 0 or 1.

cd4069.svfile
// CD4069UB: hex inverter (six NOT gates).
//
// Ports in pin order, named as in the datasheet: inputs A-F, outputs G-L.
// The power pins, VSS (7) and VDD (14), are left out.  Synthesizable.

module cd4069
(
    input  logic a,  // Pin 1
    output logic g,  // Pin 2:  g = ~ a
    input  logic b,  // Pin 3
    output logic h,  // Pin 4:  h = ~ b
    input  logic c,  // Pin 5
    output logic i,  // Pin 6:  i = ~ c
                     // Pin 7:  VSS
    output logic j,  // Pin 8:  j = ~ d
    input  logic d,  // Pin 9
    output logic k,  // Pin 10: k = ~ e
    input  logic e,  // Pin 11
    output logic l,  // Pin 12: l = ~ f
    input  logic f   // Pin 13
                     // Pin 14: VDD
);

    assign g = ~ a;
    assign h = ~ b;
    assign i = ~ c;
    assign j = ~ d;
    assign k = ~ e;
    assign l = ~ f;

endmodule
cd4077.svfile
// CD4077B: quad 2-input exclusive-NOR gate.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (7)
// and VDD (14), are left out.  Synthesizable.

module cd4077
(
    input  logic a,  // Pin 1
    input  logic b,  // Pin 2
    output logic j,  // Pin 3:  j = ~ (a ^ b)
    output logic k,  // Pin 4:  k = ~ (c ^ d)
    input  logic c,  // Pin 5
    input  logic d,  // Pin 6
                     // Pin 7:  VSS
    input  logic e,  // Pin 8
    input  logic f,  // Pin 9
    output logic l,  // Pin 10: l = ~ (e ^ f)
    output logic m,  // Pin 11: m = ~ (g ^ h)
    input  logic g,  // Pin 12
    input  logic h   // Pin 13
                     // Pin 14: VDD
);

    assign j = ~ (a ^ b);
    assign k = ~ (c ^ d);
    assign l = ~ (e ^ f);
    assign m = ~ (g ^ h);

endmodule
cd4081.svfile
// CD4081B: quad 2-input AND gate.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (7)
// and VDD (14), are left out.  Synthesizable.
//
// The 4081, 4071 and 4070 have the same pinout: only the function of the
// gates differs.

module cd4081
(
    input  logic a,  // Pin 1
    input  logic b,  // Pin 2
    output logic j,  // Pin 3:  j = a & b
    output logic k,  // Pin 4:  k = c & d
    input  logic c,  // Pin 5
    input  logic d,  // Pin 6
                     // Pin 7:  VSS
    input  logic e,  // Pin 8
    input  logic f,  // Pin 9
    output logic l,  // Pin 10: l = e & f
    output logic m,  // Pin 11: m = g & h
    input  logic g,  // Pin 12
    input  logic h   // Pin 13
                     // Pin 14: VDD
);

    assign j = a & b;
    assign k = c & d;
    assign l = e & f;
    assign m = g & h;

endmodule
cd4071.svfile
// CD4071B: quad 2-input OR gate.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (7)
// and VDD (14), are left out.  Synthesizable.

module cd4071
(
    input  logic a,  // Pin 1
    input  logic b,  // Pin 2
    output logic j,  // Pin 3:  j = a | b
    output logic k,  // Pin 4:  k = c | d
    input  logic c,  // Pin 5
    input  logic d,  // Pin 6
                     // Pin 7:  VSS
    input  logic e,  // Pin 8
    input  logic f,  // Pin 9
    output logic l,  // Pin 10: l = e | f
    output logic m,  // Pin 11: m = g | h
    input  logic g,  // Pin 12
    input  logic h   // Pin 13
                     // Pin 14: VDD
);

    assign j = a | b;
    assign k = c | d;
    assign l = e | f;
    assign m = g | h;

endmodule
cd4013.svfile
// CD4013B: dual D flip-flop with set and reset.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (7)
// and VDD (14), are left out.  Synthesizable.
//
// Each flip-flop stores D at the rising edge of its clock.  SET and RESET
// are active high and asynchronous: they act at once, without the clock.
// With SET and RESET both high the chip sets both Q and ~Q high; the model
// does the same while they are both high.  Do not release them at the same
// moment: which of the two wins is not defined.

module cd4013
(
    output logic q1,      // Pin 1
    output logic q1_n,    // Pin 2:  ~Q1
    input  logic clock1,  // Pin 3
    input  logic reset1,  // Pin 4:  1 = Q1 goes to 0 at once
    input  logic d1,      // Pin 5
    input  logic set1,    // Pin 6:  1 = Q1 goes to 1 at once
                          // Pin 7:  VSS
    input  logic set2,    // Pin 8
    input  logic d2,      // Pin 9
    input  logic reset2,  // Pin 10
    input  logic clock2,  // Pin 11
    output logic q2_n,    // Pin 12: ~Q2
    output logic q2       // Pin 13
                          // Pin 14: VDD
);

    logic r1, r2;

    always_ff @ (posedge clock1 or posedge reset1 or posedge set1)
        if (reset1)
            r1 <= 1'b0;
        else if (set1)
            r1 <= 1'b1;
        else
            r1 <= d1;

    always_ff @ (posedge clock2 or posedge reset2 or posedge set2)
        if (reset2)
            r2 <= 1'b0;
        else if (set2)
            r2 <= 1'b1;
        else
            r2 <= d2;

    assign q1   =   r1 | (set1 & reset1);
    assign q1_n = ~ r1 | (set1 & reset1);
    assign q2   =   r2 | (set2 & reset2);
    assign q2_n = ~ r2 | (set2 & reset2);

endmodule

10SystemVerilog: the chip-level design

serial_compare_chips.sv connects the chip models exactly as schematic 2 and the breadboard connect the chips, with the same ports as serial_compare.sv. Unused inputs are tied to vdd or gnd as on the breadboard, and unused outputs go to wires named unused_…. The file is generated from the breadboard wire list after a pin-level check of that list, so the code, the drawings and the checklist cannot disagree.

serial_compare_chips.svfile
// Exercise P7, chip-level version: the chips and wires of schematic 2 and
// of the breadboard.  Same ports as serial_compare.sv.
//
// Generated by tools/bb_lib.py from the checked breadboard wire list;
// change the layout in tools/bb_p7.py, not this file.  Synthesizable.

module serial_compare_chips
(
    input  logic       clk,
    input  logic       rst,
    input  logic       a,
    input  logic       b,
    output logic       gt,
    output logic       lt,
    output logic       eq
);

    // Connections between the chips that are not ports

    wire x;
    wire na;
    wire nb;
    wire gi;
    wire li;
    wire gk;
    wire lk;
    wire dg;
    wire dl;

    // The power rails of the breadboard, for tied-off inputs

    wire gnd = 1'b0;
    wire vdd = 1'b1;

    // Outputs that go nowhere

    wire unused_u2_k;
    wire unused_u2_l;
    wire unused_u1_h;
    wire unused_u1_i;
    wire unused_u1_k;
    wire unused_u1_l;
    wire unused_u4_j;
    wire unused_u4_m;
    wire unused_u5_q1_n;
    wire unused_u5_q2_n;

    //------------------------------------------------------------------------

    // U2: CD4077 quad 2-input XNOR, pin 1 in column 19

    cd4077 i_u2
    (
        .a ( gt          ),  // Pin 1 <- U5 pin 1 (Q1)
        .b ( lt          ),  // Pin 2 <- U5 pin 13 (Q2)
        .j ( eq          ),  // Pin 3 -> EQ
        .k ( unused_u2_k ),  // Pin 4, unused output
        .c ( gnd         ),  // Pin 5 <- GND, unused input
        .d ( gnd         ),  // Pin 6 <- GND, unused input
        .e ( vdd         ),  // Pin 8 <- +5V, unused input
        .f ( vdd         ),  // Pin 9 <- +5V, unused input
        .l ( unused_u2_l ),  // Pin 10, unused output
        .m ( x           ),  // Pin 11 -> X
        .g ( a           ),  // Pin 12 <- button A
        .h ( b           )   // Pin 13 <- button B
    );

    //------------------------------------------------------------------------

    // U1: CD4069 hex inverter (six NOT gates), pin 1 in column 27

    cd4069 i_u1
    (
        .a ( a           ),  // Pin 1 <- button A
        .g ( na          ),  // Pin 2 -> ~A
        .b ( vdd         ),  // Pin 3 <- +5V, unused input
        .h ( unused_u1_h ),  // Pin 4, unused output
        .c ( vdd         ),  // Pin 5 <- +5V, unused input
        .i ( unused_u1_i ),  // Pin 6, unused output
        .j ( nb          ),  // Pin 8 -> ~B
        .d ( b           ),  // Pin 9 <- button B
        .k ( unused_u1_k ),  // Pin 10, unused output
        .e ( gnd         ),  // Pin 11 <- GND, unused input
        .l ( unused_u1_l ),  // Pin 12, unused output
        .f ( gnd         )   // Pin 13 <- GND, unused input
    );

    //------------------------------------------------------------------------

    // U3: CD4081 quad 2-input AND, pin 1 in column 36

    cd4081 i_u3
    (
        .a ( a  ),  // Pin 1 <- button A
        .b ( nb ),  // Pin 2 <- U1 pin 8 (J)
        .j ( gi ),  // Pin 3 -> A·~B
        .k ( li ),  // Pin 4 -> ~A·B
        .c ( na ),  // Pin 5 <- U1 pin 2 (G)
        .d ( b  ),  // Pin 6 <- button B
        .e ( x  ),  // Pin 8 <- U2 pin 11 (M)
        .f ( gt ),  // Pin 9 <- U5 pin 1 (Q1)
        .l ( gk ),  // Pin 10 -> GT·X
        .m ( lk ),  // Pin 11 -> LT·X
        .g ( lt ),  // Pin 12 <- U5 pin 13 (Q2)
        .h ( x  )   // Pin 13 <- U2 pin 11 (M)
    );

    //------------------------------------------------------------------------

    // U4: CD4071 quad 2-input OR, pin 1 in column 44

    cd4071 i_u4
    (
        .a ( gnd         ),  // Pin 1 <- GND, unused input
        .b ( gnd         ),  // Pin 2 <- GND, unused input
        .j ( unused_u4_j ),  // Pin 3, unused output
        .k ( dg          ),  // Pin 4 -> GT'
        .c ( gi          ),  // Pin 5 <- U3 pin 3 (J)
        .d ( gk          ),  // Pin 6 <- U3 pin 10 (L)
        .e ( li          ),  // Pin 8 <- U3 pin 4 (K)
        .f ( lk          ),  // Pin 9 <- U3 pin 11 (M)
        .l ( dl          ),  // Pin 10 -> LT'
        .m ( unused_u4_m ),  // Pin 11, unused output
        .g ( vdd         ),  // Pin 12 <- +5V, unused input
        .h ( vdd         )   // Pin 13 <- +5V, unused input
    );

    //------------------------------------------------------------------------

    // U5: CD4013 dual D flip-flop with set and reset, pin 1 in column 52

    cd4013 i_u5
    (
        .q1     ( gt             ),  // Pin 1 -> GT
        .q1_n   ( unused_u5_q1_n ),  // Pin 2, unused output
        .clock1 ( clk            ),  // Pin 3 <- 555 clock module
        .reset1 ( rst            ),  // Pin 4 <- button RESET
        .d1     ( dg             ),  // Pin 5 <- U4 pin 4 (K)
        .set1   ( gnd            ),  // Pin 6 <- GND
        .set2   ( gnd            ),  // Pin 8 <- GND
        .d2     ( dl             ),  // Pin 9 <- U4 pin 10 (L)
        .reset2 ( rst            ),  // Pin 10 <- button RESET
        .clock2 ( clk            ),  // Pin 11 <- 555 clock module
        .q2_n   ( unused_u5_q2_n ),  // Pin 12, unused output
        .q2     ( lt             )   // Pin 13 -> LT
    );

endmodule

11Testbench and simulation scripts

tb.sv runs both designs side by side and compares them with a reference model that collects the bits since reset into two numbers and compares the numbers. Like the testbenches of Basics-Graphics-Music, it drives and checks signals only at rising clock edges. Every comparison starts with a reset; there are seven chosen pairs and twelve pseudo-random ones, up to 16 bits long. The output below is shortened.

tb.sv241 lines · show the codefile
// Testbench for exercise P7.
//
// Runs the generic design (serial_compare.sv) and the chip-level design
// (serial_compare_chips.sv) side by side and compares both with a reference
// model that collects the bits since reset into two numbers and compares
// the numbers.  Works with Icarus Verilog, Verilator (--binary) and Questa.
//
// Like the testbenches of Basics-Graphics-Music, it drives and samples
// signals only at rising clock edges.  Every comparison starts with a reset
// and feeds two numbers lowest bit first, up to 16 bits long, beyond what
// one 4063 can compare.

// Time units.  The design files have none: Yosys does not accept timeunit
// and timeprecision, and the Tiny Tapeout template sets `timescale 1ns / 1ps
// in its own testbench.  This line sets the same units here and for the
// design files compiled after it, so tb.sv comes first in the file list.

`timescale 1ns / 1ps

module tb;

    logic clk;
    logic rst;
    logic a = 1'b0;
    logic b = 1'b0;

    wire  gt, gt_chips;
    wire  lt, lt_chips;
    wire  eq, eq_chips;

    serial_compare i_generic
    (
        .clk ( clk ),
        .rst ( rst ),
        .a   ( a   ),
        .b   ( b   ),
        .gt  ( gt  ),
        .lt  ( lt  ),
        .eq  ( eq  )
    );

    serial_compare_chips i_chips
    (
        .clk ( clk      ),
        .rst ( rst      ),
        .a   ( a        ),
        .b   ( b        ),
        .gt  ( gt_chips ),
        .lt  ( lt_chips ),
        .eq  ( eq_chips )
    );

    //------------------------------------------------------------------------
    // Clock with a period of 10 ns.
    // On the breadboard one period is about a second.

    initial
    begin
        clk = '0;

        forever
            # 5 clk = ~ clk;
    end

    //------------------------------------------------------------------------
    // Reference model: the numbers made of the bits since reset

    logic [31:0] value_a, value_b;
    int          n_bits;

    always @ (posedge clk or posedge rst)
        if (rst)
        begin
            value_a <= '0;
            value_b <= '0;
            n_bits  <= 0;
        end
        else
        begin
            value_a <= value_a | (32' (a) << n_bits);
            value_b <= value_b | (32' (b) << n_bits);
            n_bits  <= n_bits + 1;
        end

    wire [2:0] expected = { value_a > value_b, value_a == value_b, value_a < value_b };

    wire ok_generic = { gt,       eq,       lt       } === expected;
    wire ok_chips   = { gt_chips, eq_chips, lt_chips } === expected;

    //------------------------------------------------------------------------
    // Checking at every rising clock edge.  At the edge both designs and the
    // model still show the clock cycle that ends there, the same values that
    // a flip-flop would sample.

    // Initial values are fine in a testbench, and the checker samples rst at
    // the clock edge on purpose, although the designs reset asynchronously

    // verilator lint_off PROCASSINIT
    // verilator lint_off SYNCASYNCNET

    logic was_reset = 1'b0;
    logic done      = 1'b0;  // Set by the stimulus before $finish

    int cycle    = 0;
    int n_checks = 0;
    int n_errors = 0;

    logic [2:0] results_seen = '0;  // GT, EQ, LT after more than 4 bits
    int         n_compared   = 0;

    always @ (posedge clk)
    begin
        if (rst)
            was_reset <= 1'b1;

        if ((rst | was_reset) & ~ done)
        begin
            cycle    <= cycle + 1;
            n_checks <= n_checks + 2;
            n_errors <= n_errors + (ok_generic ? 0 : 1) + (ok_chips ? 0 : 1);

            if (n_bits > 4)
                results_seen <= results_seen | expected;

            $display ("%5d  %b    %b  %b  %b   %b   %b   %5d %5d  %s  %s",
                cycle + 1, rst, a, b, gt, eq, lt, value_a, value_b,
                ok_generic ? "ok     " : "WRONG  ", ok_chips ? "ok" : "WRONG");
        end
    end

    //------------------------------------------------------------------------
    // Asynchronous reset: right after rst rises, both designs must say A = B.

    int n_async = 0;

    always @ (posedge rst)
    begin
        # 1;

        if ({ gt, eq, lt, gt_chips, eq_chips, lt_chips } !== 6'b010_010)
        begin
            $display ("WRONG: reset did not act at once");
            n_errors <= n_errors + 1;
        end

        n_async <= n_async + 1;
    end

    //------------------------------------------------------------------------
    // Driving the inputs

    // One comparison: reset, the bits lowest first, then one more pair of
    // zeros, which does not change the numbers, so that the last result
    // stays for a clock edge before the next reset

    task automatic compare (input logic [15:0] x, input logic [15:0] y, input int n);
        rst <= 1'b1;
        a   <= 1'b0;
        b   <= 1'b0;
        @ (posedge clk);
        rst <= 1'b0;

        for (int k = 0; k < n; k ++)
        begin
            a <= x [k];
            b <= y [k];
            @ (posedge clk);
        end

        a <= 1'b0;
        b <= 1'b0;
        @ (posedge clk);

        n_compared <= n_compared + 1;
    endtask

    logic [31:0] seed = 32'd11;

    initial
    begin
        $dumpfile ("tb.vcd");

        `ifdef __ICARUS__
            $dumpvars (0, tb);  // Without a scope Icarus also tries to dump $unit
        `else
            $dumpvars;
        `endif

        $display ("cycle  rst  A  B  GT  EQ  LT   A so far B so far  generic  chips");

        // Before reset the result is unknown, as after power-up

        rst <= 1'bx;
        repeat (2) @ (posedge clk);

        // The example of section 2, then numbers of growing length

        compare (    6,    10,  4);
        compare (    5,     3,  4);
        compare (    9,     9,  4);
        compare (  200,   201,  8);
        compare ( 1000,   999, 10);
        compare (12345, 12345, 16);
        compare (65535, 65534, 16);

        // Pseudo-random pairs, the same in every simulator; every third pair
        // is equal

        for (int i = 0; i < 12; i ++)
        begin
            logic [15:0] x, y;

            seed = seed * 32'd1664525 + 32'd1013904223;
            x    = seed [31:16];
            seed = seed * 32'd1664525 + 32'd1013904223;
            y    = i % 3 == 0 ? x : seed [31:16];

            compare (x, y, 1 + int' (seed [3:0]));
        end

        // Stop checking one clock edge before $finish, so that every
        // simulator reports the same number of checks

        done <= '1;
        @ (posedge clk);

        $finish;
    end

    //------------------------------------------------------------------------

    final
    begin
        if (n_errors == 0 && results_seen == 3'b111 && n_compared == 19 && n_async >= 19)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, results seen %b, %0d comparisons, %0d resets",
                      n_errors, n_checks, results_seen, n_compared, n_async);
    end

endmodule

Each script compiles the files, runs the simulation, writes a log and the waveform tb.vcd, and exits with an error unless the test passes. Run them from any directory: ./run_icarus.bash, ./run_verilator.bash or ./run_questa.bash; ./clean.bash removes what they make. The waveform opens in GTKWave or Surfer.

run_icarus.bash22 lines · show the codefile
#!/usr/bin/env bash

# Exercise P7: run the testbench with Icarus Verilog 12 or later.
# The output goes to icarus.log and the waveform to tb.vcd,
# for GTKWave or Surfer.

set -Eeuo pipefail

cd "$(dirname "$0")"

files=(tb.sv serial_compare.sv serial_compare_chips.sv cd4077.sv cd4069.sv cd4081.sv cd4071.sv cd4013.sv)

if ! command -v iverilog > /dev/null
then
    printf '%s\n' "$0: iverilog not found, install Icarus Verilog 12 or later" >&2
    exit 1
fi

iverilog -g2012 -o tb.vvp "${files[@]}"
vvp -n tb.vvp | tee icarus.log

grep -q '^PASS' icarus.log
run_verilator.bash29 lines · show the codefile
#!/usr/bin/env bash

# Exercise P7: run the testbench with Verilator 5.  --binary builds
# a simulator with the testbench's delays; it needs a C++20 compiler.
# The output goes to verilator.log and the waveform to tb.vcd.

set -Eeuo pipefail

cd "$(dirname "$0")"

files=(tb.sv serial_compare.sv serial_compare_chips.sv cd4077.sv cd4069.sv cd4081.sv cd4071.sv cd4013.sv)

# OSS CAD Suite unpacked in the home directory has Verilator too

if ! command -v verilator > /dev/null && [ -x "$HOME/oss-cad-suite/bin/verilator" ]
then
    PATH="$HOME/oss-cad-suite/bin:$PATH"
fi

if ! command -v verilator > /dev/null
then
    printf '%s\n' "$0: verilator not found, install Verilator 5" >&2
    exit 1
fi

verilator --binary -Wall --trace --top-module tb -o tb "${files[@]}"
obj_dir/tb | tee verilator.log

grep -q '^PASS' verilator.log
run_questa.bash64 lines · show the codefile
#!/usr/bin/env bash

# Exercise P7: run the testbench with Questa, for example the free
# Questa Starter Edition that comes with Quartus Prime Lite.
# The output goes to questa.log and the waveform to tb.vcd.

set -Eeuo pipefail

cd "$(dirname "$0")"

files=(tb.sv serial_compare.sv serial_compare_chips.sv cd4077.sv cd4069.sv cd4081.sv cd4071.sv cd4013.sv)

# When vsim is not in PATH, look for it where Quartus installs it

if ! command -v vsim > /dev/null
then
    for dir in "$HOME"/intelFPGA_lite/*/questa_fse/bin  \
               "$HOME"/altera_lite/*/questa_fse/bin     \
               /opt/intelFPGA_lite/*/questa_fse/bin     \
               /opt/altera_lite/*/questa_fse/bin
    do
        if [ -x "$dir/vsim" ]
        then
            PATH="$dir:$PATH"
            break
        fi
    done
fi

if ! command -v vsim > /dev/null
then
    printf '%s\n' "$0: vsim not found, install Questa or add it to PATH" >&2
    exit 1
fi

# The Starter Edition needs a free license file from the Intel
# licensing site; Quartus keeps it in ~/flexlm/license.dat

license="$HOME/flexlm/license.dat"

# ${SALT_LICENSE_SERVER-} is empty when the variable is not set,
# where a plain $SALT_LICENSE_SERVER would stop the script (set -u)
salt_license="${SALT_LICENSE_SERVER-}"

if [ -z "$salt_license" ] && [ -f "$license" ]
then
    export SALT_LICENSE_SERVER="$license"
fi

# Older Questa versions read LM_LICENSE_FILE; ${LM_LICENSE_FILE-}
# is empty when the variable is not set
lm_license="${LM_LICENSE_FILE-}"

if [ -z "$lm_license" ] && [ -f "$license" ]
then
    export LM_LICENSE_FILE="$license"
fi

rm -rf work
vlib work > /dev/null
vlog -sv -lint "${files[@]}"
vsim -c tb -do "run -all; quit -f" | tee questa.log

grep -q 'PASS' questa.log

Tested with Icarus Verilog 12.0 and 14.0 (development), Verilator 5.053 with -Wall and no warnings, and Questa Altera Starter FPGA Edition 2025.2 from Quartus Prime Lite 25.1. The code uses only what Icarus Verilog 13 supports. This is the output, from Icarus Verilog:

VCD info: dumpfile tb.vcd opened for output.
cycle  rst  A  B  GT  EQ  LT   A so far B so far  generic  chips
    1  1    0  0  0   1   0       0     0  ok          ok
    2  0    0  0  0   1   0       0     0  ok          ok
    3  0    1  1  0   1   0       0     0  ok          ok
    4  0    1  0  0   1   0       2     2  ok          ok
    5  0    0  1  1   0   0       6     2  ok          ok
    6  0    0  0  0   0   1       6    10  ok          ok
    7  1    0  0  0   1   0       0     0  ok          ok
    8  0    1  1  0   1   0       0     0  ok          ok
    9  0    0  1  0   1   0       1     1  ok          ok
   10  0    1  0  0   0   1       1     3  ok          ok
   11  0    0  0  1   0   0       5     3  ok          ok
   12  0    0  0  1   0   0       5     3  ok          ok
   13  1    0  0  0   1   0       0     0  ok          ok
   14  0    1  1  0   1   0       0     0  ok          ok
   15  0    0  0  0   1   0       1     1  ok          ok
   16  0    0  0  0   1   0       1     1  ok          ok
   17  0    1  1  0   1   0       1     1  ok          ok
   18  0    0  0  0   1   0       9     9  ok          ok
   19  1    0  0  0   1   0       0     0  ok          ok
   20  0    0  1  0   1   0       0     0  ok          ok
   21  0    0  0  0   0   1       0     1  ok          ok
   22  0    0  0  0   0   1       0     1  ok          ok
   23  0    1  1  0   0   1       0     1  ok          ok
   24  0    0  0  0   0   1       8     9  ok          ok
   25  0    0  0  0   0   1       8     9  ok          ok
   26  0    1  1  0   0   1       8     9  ok          ok
   27  0    1  1  0   0   1      72    73  ok          ok
   28  0    0  0  0   0   1     200   201  ok          ok
  …
  207  0    1  0  0   0   1       2     5  ok          ok
  208  0    0  0  1   0   0      10     5  ok          ok
tb.sv:227: $finish called at 2105000 (1ps)
PASS: 416 checks, no errors

To see that the testbench catches mistakes, break something and run it again: replace gt & same with gt in serial_compare.sv, or connect pin 5 of the 4013 to A·~B instead of GT' in serial_compare_chips.sv. The script reports FAIL and the trace shows the lines marked WRONG.

12On an FPGA board: lab_top in BGM

The Basics-Graphics-Music (BGM) repository runs the same labs on dozens of FPGA boards. Each lab has a lab_top module with the same ports on every board: clock, a 1 Hz slow_clk, reset, keys, LEDs, a 7-segment display.

  1. Copy labs/1_basics/1_10_snail_fsm to a new directory.
  2. Replace its lab_top.sv with bgm_lab/lab_top.sv from this exercise and add serial_compare.sv. The BGM scripts compile every .sv file of the directory except tb.sv.
  3. Run ./03_synthesize_for_fpga.bash and ./04_configure_fpga.bash; the first run asks which board you have.

The design runs from slow_clk, which every BGM board makes at 1 Hz, so it steps once a second like the breadboard with the 555 module. BGM makes it in peripherals/slow_clk_gen.sv: a counter on the board clock toggles a flip-flop, and on AMD (Xilinx) and Intel (Altera) FPGAs a BUFG or global primitive puts that signal on the FPGA clock network, so it reaches all flip-flops like a real clock.

The reset of the board starts a new comparison. Key 1 is the bit of A and key 0 the bit of B: hold them through a tick of slow_clk, lowest bits first. LEDs 2–0 show LT, EQ and GT. The rightmost digit is a small traffic light: segment a (top) red, g (middle) yellow, d (bottom) green. To run the chip-level design instead, add serial_compare_chips.sv and the five chip models and change the module name in the instance.

bgm_lab/lab_top.sv104 lines · show the codefile
// Exercise P7 on an FPGA board with the Basics-Graphics-Music (BGM) labs:
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy labs/1_basics/1_10_snail_fsm to a new directory, replace its
// lab_top.sv with this file and add serial_compare.sv.  For the chip-level
// design add serial_compare_chips.sv and cd4069.sv, cd4077.sv, cd4081.sv,
// cd4071.sv, cd4013.sv instead, and change the module name below.
//
// The comparator runs from slow_clk, 1 Hz on every BGM board; the reset of
// the board starts a new comparison.  Key 1 is the bit of A and key 0 the
// bit of B: hold them through a tick of slow_clk, lowest bits first.  LEDs
// 2-0 show LT, EQ and GT.  The rightmost digit is a small traffic light:
// segment a (top) red for A < B, g (middle) yellow for A = B, d (bottom)
// green for A > B.

`include "config.svh"

module lab_top
# (
    parameter  clk_mhz       = 50,
               w_key         = 4,
               w_sw          = 8,
               w_led         = 8,
               w_digit       = 8,
               w_gpio        = 100,

               screen_width  = 640,
               screen_height = 480,

               w_red         = 4,
               w_green       = 4,
               w_blue        = 4,

               w_x           = $clog2 ( screen_width  ),
               w_y           = $clog2 ( screen_height )
)
(
    input                        clk,
    input                        slow_clk,
    input                        rst,

    // Keys, switches, LEDs

    input        [w_key   - 1:0] key,
    input        [w_sw    - 1:0] sw,
    output logic [w_led   - 1:0] led,

    // A dynamic seven-segment display

    output logic [          7:0] abcdefgh,
    output logic [w_digit - 1:0] digit,

    // Graphics

    input        [w_x     - 1:0] x,
    input        [w_y     - 1:0] y,

    output logic [w_red   - 1:0] red,
    output logic [w_green - 1:0] green,
    output logic [w_blue  - 1:0] blue,

    // Microphone, sound output and UART

    input        [         23:0] mic,
    output       [         15:0] sound,

    input                        uart_rx,
    output                       uart_tx,

    // General-purpose Input/Output

    inout        [w_gpio  - 1:0] gpio
);

    //------------------------------------------------------------------------

       assign red        = '0;
       assign green      = '0;
       assign blue       = '0;
       assign sound      = '0;
       assign uart_tx    = '1;

    //------------------------------------------------------------------------

    logic gt, lt, eq;

    serial_compare i_serial_compare
    (
        .clk ( slow_clk ),
        .rst ( rst      ),
        .a   ( key [1]  ),
        .b   ( key [0]  ),
        .gt  ( gt       ),
        .lt  ( lt       ),
        .eq  ( eq       )
    );

    assign led = w_led' ({ lt, eq, gt });

    //                 a   b     c     d   e     f     g   h
    assign abcdefgh = { lt, 1'b0, 1'b0, gt, 1'b0, 1'b0, eq, 1'b0 };
    assign digit    = w_digit' (1);

endmodule

13On an FPGA board: hackathon_top in BGM

The hackathon setup of BGM uses a Tang Nano 9K with a 480×272 screen and a TM1638 board of keys, LEDs and digits. Its top module, hackathon_top, has simpler ports; the first line of the file names the board, so the scripts need no questions.

  1. Copy hackathon/problems/3_d_flip_flop.
  2. Replace its hackathon_top.sv with bgm_hackathon/hackathon_top.sv and add serial_compare.sv.
  3. Run ./03_synthesize_for_fpga.bash and ./04_configure_fpga.bash.

Key 1 is the bit of A and key 0 the bit of B. The screen shows a traffic light of three lamps; the LEDs and the rightmost digit are as in lab_top.

bgm_hackathon/hackathon_top.sv93 lines · show the codefile
// Board configuration: tang_nano_9k_lcd_480_272_tm1638_hackathon
// This module uses few parameterization and relaxed typing rules

// Exercise P7 in the hackathon setup of Basics-Graphics-Music (BGM):
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy a directory such as hackathon/problems/3_d_flip_flop, replace its
// hackathon_top.sv with this file and add serial_compare.sv.
//
// The comparator runs from slow_clock; reset starts a new comparison.
// Key 1 is the bit of A and key 0 the bit of B: hold them through a tick of
// slow_clock, lowest bits first.  The LEDs and the rightmost digit are as in
// lab_top, and the screen shows a traffic light of three square lamps.

module hackathon_top
(
    input  logic       clock,
    input  logic       slow_clock,
    input  logic       reset,

    input  logic [7:0] key,
    output logic [7:0] led,

    // A dynamic seven-segment display

    output logic [7:0] abcdefgh,
    output logic [7:0] digit,

    // LCD screen interface

    input  logic [8:0] x,
    input  logic [8:0] y,

    output logic [4:0] red,
    output logic [5:0] green,
    output logic [4:0] blue,

    inout  logic [3:0] gpio
);

    //------------------------------------------------------------------------

    logic gt, lt, eq;

    serial_compare i_serial_compare
    (
        .clk ( slow_clock ),
        .rst ( reset      ),
        .a   ( key [1]    ),
        .b   ( key [0]    ),
        .gt  ( gt         ),
        .lt  ( lt         ),
        .eq  ( eq         )
    );

    assign led      = { 5'b0, lt, eq, gt };

    //                 a   b     c     d   e     f     g   h
    assign abcdefgh = { lt, 1'b0, 1'b0, gt, 1'b0, 1'b0, eq, 1'b0 };
    assign digit    = 8'b0000_0001;

    //------------------------------------------------------------------------
    // A traffic light on the screen: three square lamps in a dark box, red
    // on top, bright when on and dim when off

    always_comb
    begin
        red   = 0;
        green = 0;
        blue  = 0;

        if (x >= 210 & x < 270 & y >= 40 & y < 232)
        begin
            red   = 2;
            green = 4;
            blue  = 2;
        end

        if (x >= 220 & x < 260)
        begin
            if (y >= 50 & y < 90)
                red = lt ? 31 : 8;
            else if (y >= 116 & y < 156)
            begin
                red   = eq ? 31 : 8;
                green = eq ? 50 : 12;
            end
            else if (y >= 182 & y < 222)
                green = gt ? 63 : 14;
        end
    end

endmodule

14On a chip: Tiny Tapeout

Tiny Tapeout makes real chips from student designs. Each design is a module with the ports below; on the demo board ui_in comes from DIP switches and uo_out drives a 7-segment display.

The demo board makes the project clock itself and can set it anywhere from 1 Hz to 66.5 MHz (see Clock in the Tiny Tapeout docs). Set it to 1 Hz, and project.v connects clk straight to the comparator, just as the 555 module clocks the chips on the breadboard.

DIP switch 0 is the bit of A and switch 1 the bit of B: set them before a tick of the clock, lowest bits first. Segments a, g and d of the display are the traffic light. The reset button of the demo board starts a new comparison.

tiny_tapeout/project.v54 lines · show the codefile
/*
 * Exercise P7 on Tiny Tapeout: a bit-serial comparator that compares two
 * numbers of any length, one bit per clock, lowest bit first.  The
 * 7-segment display of the demo board is a small traffic light.
 *
 * Add serial_compare.sv to source_files in info.yaml next to project.v.
 * Rename the module to tt_um_<your GitHub name>_<project name> and use the
 * same name as top_module in info.yaml.
 */

`default_nettype none

module tt_um_example (
    input  wire [7:0] ui_in,    // DIP switches, INPUT Pmod, RP2350 GPIO17-24
    output wire [7:0] uo_out,   // 7-segment display, OUTPUT Pmod, RP2350 GPIO33-40
    input  wire [7:0] uio_in,   // BIDIR Pmod, RP2350 GPIO25-32
    output wire [7:0] uio_out,  //   (same pins)
    output wire [7:0] uio_oe,   //   1 = your design drives the pin
    input  wire       ena,      // set by the on-chip project mux, not a board pin
    input  wire       clk,      // RP2350 GPIO16
    input  wire       rst_n     // RP2350 GPIO14
);

    // The demo board makes the project clock; set it to 1 Hz.  DIP switch 0
    // is the bit of A and switch 1 the bit of B: set them before a tick of
    // the clock, lowest bits first.  The reset button of the board starts a
    // new comparison.

    wire gt, lt, eq;

    serial_compare i_serial_compare (
        .clk ( clk       ),
        .rst ( ~ rst_n   ),
        .a   ( ui_in [0] ),
        .b   ( ui_in [1] ),
        .gt  ( gt        ),
        .lt  ( lt        ),
        .eq  ( eq        )
    );

    // 7-segment display: uo_out [0] is segment a, ..., uo_out [6] is g.
    // Segment a (top) is red for A < B, g (middle) yellow for A = B,
    // d (bottom) green for A > B.

    assign uo_out  = { 1'b0, eq, 2'b0, gt, 2'b0, lt };

    assign uio_out = 8'b0;
    assign uio_oe  = 8'b0;

    // List all unused inputs to prevent warnings

    wire _unused = & { ena, ui_in [7:2], uio_in, 1'b0 };

endmodule

In info.yaml set the clock to 1 Hz, list the files and use the module name as the top module:

project:
  clock_hz:   1                 # 1 Hz from the demo board
  top_module: "tt_um_example"   # rename to tt_um_<your GitHub name>_serial_compare
  source_files:
    - "project.v"
    - "serial_compare.sv"
No clock divider on a chip. BGM makes slow_clk with a counter, but on AMD and Intel FPGAs it routes that signal onto the clock network with BUFG or global (section 12). In an ASIC a counter bit used as a clock is bad practice: it is a second clock with its own clock tree, its edges come later than those of clk by a delay nobody controls, and every signal between the two clocks crosses clock domains. Here the board makes the 1 Hz clock, so no divider is needed. When a chip needs a slow tick from a fast clock, keep one clock and add a clock enable: a pulse one clock long that lets the slow logic change only on the edges where it is 1.

15Going further

Tasks for students

Files of this exercise

Sources

The exercise is in the Projects list of “An improved way of teaching school kids digital electronics” and in lesson 1.7 of the Habr article about the electronics course, which proposes the variants: lowest or highest bit first, cascaded 4063s, four bits per clock. The first plan of the LSSK list used a 4001 for EQ; this page uses a spare gate of the 4077 instead. The chips are described in the Texas Instruments datasheets for the CD4069UB, CD4077B, CD4081B, CD4071B and CD4013B.