Breadboard exercises/ M9EnglishРусский

Exercise M9 · mini-project · select gate

4019 bit-mask merge and the same from basic gates

One function built twice on one board: D = A·Ka + B·Kb for four bits, once in a 4019 and once from eight AND gates and four OR gates. The LED module shows both results side by side, and they always agree.

4 chips4019, two 4081, 4071
42 + 15 wireson the board + jumper leads to the modules
2 × 4 bitsD from the 4019, E from the gates
no clockthe outputs follow the inputs at once

1What it is and why it matters

What it does. Wires to the rails set two 4-bit words, A4…A1 and B4…B1. Buttons Ka and Kb choose what reaches the outputs: Ka lets A through, Kb lets B through, both together give A OR B, neither gives 0. The 4019 computes D1–D4 this way in one chip (exercise BB4d). Next to it, two 4081s and a 4071 compute the same thing as E1–E4: the first 4081 makes Ak·Ka, the second Bk·Kb, and the 4071 ORs each pair. Each data wire feeds both circuits. LEDs 1–4 show D, LEDs 5–8 show E.

How it works. AND with a control bit is a mask: Ka = 1 lets every bit of A through unchanged, Ka = 0 clears them all. OR merges the two masked words. With exactly one of Ka and Kb at 1 this is a 2:1 multiplexer of 4-bit words; with both at 1 it is a bitwise OR.

Where it is used. Masks and merges are everywhere: setting and clearing bits of a hardware register, mixing fields of an instruction, selecting a byte of a word. In a processor the result multiplexer of the ALU is often written exactly as an AND-OR of one-hot selects with the results.

Why learn it.

2The key elements: masks and merging

With the data wires as on the breadboard, A4…A1 = 0101 and B4…B1 = 0011:

KaKbD = ED4 … D1E4 … E1
00nothing00000000
01B00110011
10A01010101
11A OR B01110111

Waveforms

A4…A10101B4…B100110010KaKbD4…D100000011010101110000E4…E100000011010101110000
From the simulation of tb.sv in Icarus Verilog: the four combinations of Ka and Kb with the data as on the breadboard. D and E are always equal. · SVG · PNG

3Parts

PartIn this circuitQtyPriceSupplier
CD4019quad AND/OR select gate: D1-D41$0.40Elexp (elexp.com)
CD4081quad 2-input AND: A·Ka in one chip, B·Kb in the other2$0.55Elexp (elexp.com)
CD4071quad 2-input OR: E1-E41$0.25Elexp (elexp.com)
Button modulesKa and Kb; 2 from the pack of five2$0.66 / packaliexpress.us
8-LED moduleD1-D4 of the 4019 and E1-E4 of the gates1$0.38aliexpress.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 wires42 wires on the board (or male-male Dupont jumpers)42$11.95 / packjameco.com
Male-female Dupont jumpers15 leads to the buttons and the LED module15$1.30 / packaliexpress.us

Prices from the LSSK components sheet; these chips are in the Comprehensive 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.

4019: quad AND/OR select gate

1B42A33B34A25B26A17B18VSS9Ka10D111D212D313D414Kb15A416VDD40194 × AND/OR select
CD4019B. A 16-pin chip: VDD is pin 16 and VSS pin 8. · SVG · PNG

A1–A4 are pins 6, 4, 2 and 15, B1–B4 pins 7, 5, 3 and 1. Ka is pin 9, Kb pin 14, and D1–D4 are pins 10–13. Here the data pins of the 4019 are where the data wires go to the rails; short wires carry each bit on to the 4081s.

PinNameDirectionFunctionIn this circuit
1B4inputB4B4 (GND)
2A3inputA3A3 (+5V)
3B3inputB3B3 (GND)
4A2inputA2A2 (GND)
5B2inputB2B2 (+5V)
6A1inputA1A1 (+5V)
7B1inputB1B1 (+5V)
8VSSpowerground, 0 VGND
9KainputKa: 1 passes the A inputsKa
10D1outputD1 = A1·Ka + B1·KbD1
11D2outputD2 = A2·Ka + B2·KbD2
12D3outputD3 = A3·Ka + B3·KbD3
13D4outputD4 = A4·Ka + B4·KbD4
14KbinputKb: 1 passes the B inputsKb
15A4inputA4A4 (GND)
16VDDpowersupply, +5 V (3 to 18 V allowed)+5V

4081: quad 2-input AND

1A2B3J4K5C6D7VSS8E9F10L11M12G13H14VDD4081
CD4081B. · SVG · PNG

One 4081 makes A1·Ka … A4·Ka, the other B1·Kb … B4·Kb: Ka goes to one input of every gate of the first chip, Kb of the second.

PinNameDirectionFunctionIn this circuit
1Ainputinput of the gate with its output on pin 3A1
2Binputinput of the gate with its output on pin 3Ka
3JoutputJ = A AND BA1&Ka
4KoutputK = C AND DA2&Ka
5Cinputinput of the gate with its output on pin 4A2
6Dinputinput of the gate with its output on pin 4Ka
7VSSpowerground, 0 VGND
8Einputinput of the gate with its output on pin 10Ka
9Finputinput of the gate with its output on pin 10A3
10LoutputL = E AND FA3&Ka
11MoutputM = G AND HA4&Ka
12Ginputinput of the gate with its output on pin 11A4
13Hinputinput of the gate with its output on pin 11Ka
14VDDpowersupply, +5 V (3 to 18 V allowed)+5V

4071: quad 2-input OR

1A2B3J4K5C6D7VSS8E9F10L11M12G13H14VDD4071
CD4071B. · SVG · PNG

Each gate ORs the A term and the B term of one bit: Ek = Ak·Ka + Bk·Kb.

PinNameDirectionFunctionIn this circuit
1Ainputinput of the gate with its output on pin 3A1&Ka
2Binputinput of the gate with its output on pin 3B1&Kb
3JoutputJ = A OR BE1
4KoutputK = C OR DE2
5Cinputinput of the gate with its output on pin 4A2&Ka
6Dinputinput of the gate with its output on pin 4B2&Kb
7VSSpowerground, 0 VGND
8Einputinput of the gate with its output on pin 10A3&Ka
9Finputinput of the gate with its output on pin 10B3&Kb
10LoutputL = E OR FE3
11MoutputM = G OR HE4
12Ginputinput of the gate with its output on pin 11A4&Ka
13Hinputinput of the gate with its output on pin 11B4&Kb
14VDDpowersupply, +5 V (3 to 18 V allowed)+5V

5Schematic 1: two circuits, one function

KaKbA1A2A3A4B1B2B3B44019KaKbA1A2A3A4B1B2B3B4D1D2D3D4AND/OR select408140814081408140814081408140814071407140714071D1LED 1D2LED 2D3LED 3D4LED 4E1LED 5E2LED 6E3LED 7E4LED 8
Both circuits as blocks and gates. This is what mask_merge.sv describes. The open circles are the data wires; each feeds the 4019 and one AND gate. · SVG · PNG

6Schematic 2: connections between the chips

12345678910111213141516B4A3B3A2B2A1B1KaD1D2D3D4KbA440194 × AND/OR select123456789101112131440811234567891011121314408112345678910111213144071KaKbA1B1D1A1&KaB1&KbE1A2B2D2A2&KaB2&KbE2A3B3D3A3&KaB3&KbE3A4B4D4A4&KaB4&KbE4button Kabutton KbLED module: LEDs 1-8B1→ +5VA1→ +5VB2→ +5VA2→ GNDB3→ GNDA3→ +5VB4→ GNDA4→ GND+5V
The same circuit as chips, pin by pin. The boxes with an arrow are the data wires, with the rail they start on. · SVG · PNG

Every connection, net by net. A data net has two pins: the 4019 pin with the wire to the rail, and the AND gate it also feeds.

NetFromToWire
Kabutton Ka, OUT4019 9 (Ka), 4081 2 (B), 4081 6 (D), 4081 8 (E), 4081 13 (H)M-F, M-M
Kbbutton Kb, OUT4019 14 (Kb), 4081 9 (F), 4081 12 (G), 4081 6 (D), 4081 2 (B)M-F, M-M
A1A1 wire: +5V4019 6 (A1), 4081 1 (A)M-M
A2A2 wire: GND4019 4 (A2), 4081 5 (C)M-M
A3A3 wire: +5V4019 2 (A3), 4081 9 (F)M-M
A4A4 wire: GND4019 15 (A4), 4081 12 (G)M-M
B1B1 wire: +5V4019 7 (B1), 4081 8 (E)M-M
B2B2 wire: +5V4019 5 (B2), 4081 13 (H)M-M
B3B3 wire: GND4019 3 (B3), 4081 5 (C)M-M
B4B4 wire: GND4019 1 (B4), 4081 1 (A)M-M
D14019 10 (D1)LED module, LED 1M-F
D24019 11 (D2)LED module, LED 2M-F
D34019 12 (D3)LED module, LED 3M-F
D44019 13 (D4)LED module, LED 4M-F
A1&Ka4081 3 (J)4071 1 (A)M-M
A2&Ka4081 4 (K)4071 5 (C)M-M
A3&Ka4081 10 (L)4071 8 (E)M-M
A4&Ka4081 11 (M)4071 12 (G)M-M
B1&Kb4081 10 (L)4071 2 (B)M-M
B2&Kb4081 11 (M)4071 6 (D)M-M
B3&Kb4081 4 (K)4071 9 (F)M-M (loose jumper)
B4&Kb4081 3 (J)4071 13 (H)M-M (loose jumper)
E14071 3 (J)LED module, LED 5M-F
E24071 4 (K)LED module, LED 6M-F
E34071 10 (L)LED module, LED 7M-F, M-M
E44071 11 (M)LED module, LED 8M-F, M-M
+5V+5V4019 16 (VDD), 4081 14 (VDD), 4081 14 (VDD), 4071 14 (VDD)
GNDGND4019 8 (VSS), 4081 7 (VSS), 4081 7 (VSS), 4071 7 (VSS)

7Schematic 3: the breadboard

−+−+123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263abcdefghij5V5VPOWER MODULE · 5V9V USB-DC4019408140814071A1B1A2B2A3B3A4B4KaKaKaKbKbA1B1A1&KaB1&KbA2B2A2&KaB2&KbA3B3A3&KaB3&KbE3A4B4A4&KaB4&KbE4+OUT−BUTTON Ka+OUT−BUTTON KbG1D12D23D34D45E16E27E38E48-LED MODULELEDs 1-8 used
Every wire in its hole. Column numbers are printed along the top; rows a–e are above the gap, f–j below it. The buttons hang above the board, the LED module below it. The wires with a tag are the data: + is 1, − is 0. Wires drawn as loose arcs could not be laid flat between the others. · SVG · PNG
KaKbA1A2A3A4B1B2B3B4D1D2D3D4A1&KaA2&KaA3&KaA4&KaB1&KbB2&KbB3&KbB4&KbE1E2E3E4+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 4081 turned around, notch to the right, pin 1 in hole 17e; the 4019 turned around, notch to the right, pin 1 in hole 26e; the 4081, notch to the left, pin 1 in hole 30f; the 4071, notch to the left, pin 1 in hole 38f. 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. 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.
  4. The data wires, each from its pin of the 4019 to a rail, in the positions of the checklist.
  5. The signal wires: each data bit from the 4019 to its AND gate, Ka and Kb to the four gates of their 4081, the AND outputs to the 4071. Tick each wire as you insert it: there are many.
  6. With the power off, the buttons above the board and the LED module below it.
  7. Turn the power on.

Wiring checklist

·

#NetFromTo
Power (red to +, black to −) · 8 wires
1+5V26j (4019 pin 16, VDD)bottom + rail, column 26
2GND19a (4019 pin 8, VSS)top − rail, column 19
3+5V30a (4081 pin 14, VDD)top + rail, column 30
4GND36j (4081 pin 7, VSS)bottom − rail, column 36
5+5V17j (4081 pin 14, VDD)bottom + rail, column 17
6GND11a (4081 pin 7, VSS)top − rail, column 11
7+5V38a (4071 pin 14, VDD)top + rail, column 38
8GND44j (4071 pin 7, VSS)bottom − rail, column 44
Mode wires: move them between + and − to change the mode · 8 wires
9A121a (4019 pin 6, A1)top + rail, column 21
10B120a (4019 pin 7, B1)top + rail, column 20
11A223a (4019 pin 4, A2)top − rail, column 23
12B222a (4019 pin 5, B2)top + rail, column 22
13A325a (4019 pin 2, A3)top + rail, column 25
14B324a (4019 pin 3, B3)top − rail, column 24
15A425j (4019 pin 15, A4)bottom − rail, column 25
16B426a (4019 pin 1, B4)top − rail, column 26
Signal wires · 26 wires
17Ka19g (4019 pin 9, Ka)31i (4081 pin 2, B)
18Ka31g (4081 pin 2, B)35g (4081 pin 6, D)
19Ka31h (4081 pin 2, B)31d (4081 pin 13, H)
20Ka31c (4081 pin 13, H)36d (4081 pin 8, E)
21Kb24g (4019 pin 14, Kb)15g (4081 pin 12, G)
22Kb15h (4081 pin 12, G)12g (4081 pin 9, F)
23Kb12h (4081 pin 9, F)12d (4081 pin 6, D)
24Kb12c (4081 pin 6, D)16d (4081 pin 2, B)
25A121b (4019 pin 6, A1)30h (4081 pin 1, A)
26B120b (4019 pin 7, B1)11g (4081 pin 8, E)
27A1&Ka32g (4081 pin 3, J)38g (4071 pin 1, A)
28B1&Kb13i (4081 pin 10, L)39i (4071 pin 2, B)
29A2 (loose jumper)23c (4019 pin 4, A2)34h (4081 pin 5, C)
30B222b (4019 pin 5, B2)16g (4081 pin 13, H)
31A2&Ka33h (4081 pin 4, K)42h (4071 pin 5, C)
32B2&Kb14j (4081 pin 11, M)43j (4071 pin 6, D)
33A325b (4019 pin 2, A3)35b (4081 pin 9, F)
34B324c (4019 pin 3, B3)13c (4081 pin 5, C)
35A3&Ka34a (4081 pin 10, L)44a (4071 pin 8, E)
36B3&Kb (loose jumper)14c (4081 pin 4, K)43c (4071 pin 9, F)
37E342b (4071 pin 10, L)37f
38A425g (4019 pin 15, A4)32c (4081 pin 12, G)
39B426d (4019 pin 1, B4)17d (4081 pin 1, A)
40A4&Ka33c (4081 pin 11, M)40c (4071 pin 12, G)
41B4&Kb (loose jumper)15c (4081 pin 3, J)39c (4071 pin 13, H)
42E441d (4071 pin 11, M)45f
Modules on male-female jumpers · 15 wires
43+5Vbutton Ka, +top + rail, column 29
44Kabutton Ka, OUT31a (4081 pin 13, H)
45GNDbutton Ka, −top − rail, column 32
46+5Vbutton Kb, +top + rail, column 15
47Kbbutton Kb, OUT16a (4081 pin 2, B)
48GNDbutton Kb, −top − rail, column 17
49GNDLED module, Gbottom − rail, column 27
50D1LED module, LED 120j (4019 pin 10, D1)
51D2LED module, LED 221j (4019 pin 11, D2)
52D3LED module, LED 322j (4019 pin 12, D3)
53D4LED module, LED 423j (4019 pin 13, D4)
54E1LED module, LED 540j (4071 pin 3, J)
55E2LED module, LED 641j (4071 pin 4, K)
56E3LED module, LED 737j
57E4LED module, LED 845j

Test it

If it does not work: if one bit of E differs from D, follow its two AND gates and its OR gate. If all of E is wrong for Ka, check the Ka wires to the first 4081. If an LED flickers, an input is floating.

8SystemVerilog: the generic design

mask_merge.sv describes both circuits: the 4019 as one line with replicated masks, and the gate version bit by bit in a for loop with genvar. It is synthesizable; synthesis makes the same gates of both.

mask_merge.svfile
// Exercise M9: a bit-mask merge, D = A AND Ka OR B AND Kb, built twice: as
// the 4019 does it (output d) and from separate AND and OR gates (output
// e).
//
// Generic version that matches schematic 1, not tied to any chip.  Both
// outputs are the same function, so they must always be equal; the
// testbench checks that.  Synthesizable.

module mask_merge
(
    input  logic [3:0] a,    // a [0] is A1
    input  logic [3:0] b,    // b [0] is B1
    input  logic       ka,
    input  logic       kb,

    output logic [3:0] d,    // As the 4019: four AND-OR select gates
    output logic [3:0] e     // From gates: eight AND and four OR
);

    // The 4019: each bit selects A, B, both or neither

    assign d = a & { 4 { ka } } | b & { 4 { kb } };

    // The same from basic gates, bit by bit

    for (genvar k = 0; k < 4; k ++)
    begin : bit_k
        wire a_term = a [k] & ka;  // A 4081 gate
        wire b_term = b [k] & kb;  // A gate of the other 4081

        assign e [k] = a_term | b_term;  // A 4071 gate
    end

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.

cd4019.svfile
// CD4019B: quad AND/OR select gate.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (8)
// and VDD (16), are left out.  Synthesizable.
//
// Each output is Dn = An & Ka | Bn & Kb: Ka passes the A word, Kb the B word,
// both pass A OR B, neither gives 0.

module cd4019
(
    input  logic b4,  // Pin 1
    input  logic a3,  // Pin 2
    input  logic b3,  // Pin 3
    input  logic a2,  // Pin 4
    input  logic b2,  // Pin 5
    input  logic a1,  // Pin 6
    input  logic b1,  // Pin 7
                      // Pin 8:  VSS
    input  logic ka,  // Pin 9
    output logic d1,  // Pin 10
    output logic d2,  // Pin 11
    output logic d3,  // Pin 12
    output logic d4,  // Pin 13
    input  logic kb,  // Pin 14
    input  logic a4   // Pin 15
                      // Pin 16: VDD
);

    assign d1 = a1 & ka | b1 & kb;
    assign d2 = a2 & ka | b2 & kb;
    assign d3 = a3 & ka | b3 & kb;
    assign d4 = a4 & ka | b4 & kb;

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

10SystemVerilog: the chip-level design

mask_merge_chips.sv connects the chip models exactly as schematic 2 and the breadboard connect the chips, with the same ports as mask_merge.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.

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

module mask_merge_chips
(
    input  logic [3:0] a,
    input  logic [3:0] b,
    input  logic       ka,
    input  logic       kb,
    output logic [3:0] d,
    output logic [3:0] e
);

    // Connections between the chips that are not ports

    wire tb4;
    wire tb3;
    wire tb1;
    wire tb2;
    wire ta1;
    wire ta2;
    wire ta3;
    wire ta4;


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

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

    cd4081 i_u3
    (
        .a ( b [3] ),  // Pin 1 <- B4 wire, at GND on the breadboard
        .b ( kb    ),  // Pin 2 <- button Kb
        .j ( tb4   ),  // Pin 3 -> B4&Kb
        .k ( tb3   ),  // Pin 4 -> B3&Kb
        .c ( b [2] ),  // Pin 5 <- B3 wire, at GND on the breadboard
        .d ( kb    ),  // Pin 6 <- button Kb
        .e ( b [0] ),  // Pin 8 <- B1 wire, at +5V on the breadboard
        .f ( kb    ),  // Pin 9 <- button Kb
        .l ( tb1   ),  // Pin 10 -> B1&Kb
        .m ( tb2   ),  // Pin 11 -> B2&Kb
        .g ( kb    ),  // Pin 12 <- button Kb
        .h ( b [1] )   // Pin 13 <- B2 wire, at +5V on the breadboard
    );

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

    // U1: CD4019 quad AND/OR select gate, pin 1 in column 19

    cd4019 i_u1
    (
        .b4 ( b [3] ),  // Pin 1 <- B4 wire, at GND on the breadboard
        .a3 ( a [2] ),  // Pin 2 <- A3 wire, at +5V on the breadboard
        .b3 ( b [2] ),  // Pin 3 <- B3 wire, at GND on the breadboard
        .a2 ( a [1] ),  // Pin 4 <- A2 wire, at GND on the breadboard
        .b2 ( b [1] ),  // Pin 5 <- B2 wire, at +5V on the breadboard
        .a1 ( a [0] ),  // Pin 6 <- A1 wire, at +5V on the breadboard
        .b1 ( b [0] ),  // Pin 7 <- B1 wire, at +5V on the breadboard
        .ka ( ka    ),  // Pin 9 <- button Ka
        .d1 ( d [0] ),  // Pin 10 -> D1
        .d2 ( d [1] ),  // Pin 11 -> D2
        .d3 ( d [2] ),  // Pin 12 -> D3
        .d4 ( d [3] ),  // Pin 13 -> D4
        .kb ( kb    ),  // Pin 14 <- button Kb
        .a4 ( a [3] )   // Pin 15 <- A4 wire, at GND on the breadboard
    );

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

    // U2: CD4081 quad 2-input AND, pin 1 in column 30

    cd4081 i_u2
    (
        .a ( a [0] ),  // Pin 1 <- A1 wire, at +5V on the breadboard
        .b ( ka    ),  // Pin 2 <- button Ka
        .j ( ta1   ),  // Pin 3 -> A1&Ka
        .k ( ta2   ),  // Pin 4 -> A2&Ka
        .c ( a [1] ),  // Pin 5 <- A2 wire, at GND on the breadboard
        .d ( ka    ),  // Pin 6 <- button Ka
        .e ( ka    ),  // Pin 8 <- button Ka
        .f ( a [2] ),  // Pin 9 <- A3 wire, at +5V on the breadboard
        .l ( ta3   ),  // Pin 10 -> A3&Ka
        .m ( ta4   ),  // Pin 11 -> A4&Ka
        .g ( a [3] ),  // Pin 12 <- A4 wire, at GND on the breadboard
        .h ( ka    )   // Pin 13 <- button Ka
    );

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

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

    cd4071 i_u4
    (
        .a ( ta1   ),  // Pin 1 <- U2 pin 3 (J)
        .b ( tb1   ),  // Pin 2 <- U3 pin 10 (L)
        .j ( e [0] ),  // Pin 3 -> E1
        .k ( e [1] ),  // Pin 4 -> E2
        .c ( ta2   ),  // Pin 5 <- U2 pin 4 (K)
        .d ( tb2   ),  // Pin 6 <- U3 pin 11 (M)
        .e ( ta3   ),  // Pin 8 <- U2 pin 10 (L)
        .f ( tb3   ),  // Pin 9 <- U3 pin 4 (K)
        .l ( e [2] ),  // Pin 10 -> E3
        .m ( e [3] ),  // Pin 11 -> E4
        .g ( ta4   ),  // Pin 12 <- U2 pin 11 (M)
        .h ( tb4   )   // Pin 13 <- U3 pin 3 (J)
    );

endmodule

11Testbench and simulation scripts

tb.sv runs both designs side by side and compares both outputs, D and E, with a reference model: A where Ka is 1, ORed with B where Kb is 1. The circuit has no clock, but the testbench has one, like the testbenches of Basics-Graphics-Music: it sets the inputs right after a rising edge and checks the outputs at the next one. It drives all 1024 combinations twice, counting up from the data as on the breadboard and then in Gray code order, and prints the rows with the data as on the breadboard, and any row with an error. The output below is shortened.

tb.sv176 lines · show the codefile
// Testbench for exercise M9.
//
// Runs the generic design (mask_merge.sv) and the chip-level design
// (mask_merge_chips.sv) side by side and compares both with
// A where Ka is 1, ORed with B where Kb is 1, for both outputs.  Works with Icarus Verilog, Verilator (--binary)
// and Questa.
//
// The circuit has no clock, but like the testbenches of Basics-Graphics-Music
// this one drives and checks signals only at rising edges of its own clock:
// it changes the inputs after one edge and checks the outputs at the next.
// It tries all 1024 input combinations twice: counting up, and then in
// Gray code order, where one input changes at a time, as when a student
// presses or releases one button.

// 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 [3:0] a;
    logic [3:0] b;
    logic       ka;
    logic       kb;

    wire  [3:0] d, d_chips;
    wire  [3:0] e, e_chips;

    mask_merge i_generic
    (
        .a  ( a  ),
        .b  ( b  ),
        .ka ( ka ),
        .kb ( kb ),
        .d  ( d  ),
        .e  ( e  )
    );

    mask_merge_chips i_chips
    (
        .a  ( a       ),
        .b  ( b       ),
        .ka ( ka      ),
        .kb ( kb      ),
        .d  ( d_chips ),
        .e  ( e_chips )
    );

    //------------------------------------------------------------------------
    // Clock with a period of 10 ns

    initial
    begin
        clk = '0;

        forever
            # 5 clk = ~ clk;
    end

    //------------------------------------------------------------------------
    // Reference model: A where Ka is 1, ORed with B where Kb is 1, for both outputs.
    // Bits, from the left: d, e.

    function automatic logic [7:0] expected
    (
        input logic [3:0] in_a,
        input logic [3:0] in_b,
        input logic       in_ka,
        input logic       in_kb
    );
        logic [3:0] y;

        y = '0;

        if (in_ka)
            y = y | in_a;

        if (in_kb)
            y = y | in_b;

        return { y, y };
    endfunction

    wire [7:0] out       = { d, e };
    wire [7:0] out_chips = { d_chips, e_chips };
    wire [7:0] out_model = expected (a, b, ka, kb);

    //------------------------------------------------------------------------
    // Checking at every rising clock edge: the inputs still hold the values the
    // stimulus set at the previous edge, and the outputs have settled.

    // Initial values are fine in a testbench
    // verilator lint_off PROCASSINIT

    logic checking = 1'b0;  // Set by the stimulus after the first inputs
    logic done     = 1'b0;  // Set by the stimulus before $finish

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

    logic [1023:0] rows_seen = '0;  // Which input combinations were checked

    always @ (posedge clk)
        if (checking & ~ done)
        begin
            cycle     <= cycle + 1;
            n_checks  <= n_checks + 2;
            n_errors  <= n_errors + (out === out_model ? 0 : 1) + (out_chips === out_model ? 0 : 1);
            rows_seen <= rows_seen | 1024'b1 << { a, b, ka, kb };

            // Print the rows with the data wires as on the breadboard, and every error

            if (a == 4'b0101 & b == 4'b0011 | out !== out_model | out_chips !== out_model)
                $display ("%5d  %b    %b    %b   %b   %b    %b    %s  %s",
                    cycle + 1, a, b, ka, kb, d, e,
                    out       === out_model ? "ok     " : "WRONG  ",
                    out_chips === out_model ? "ok   "   : "WRONG");
        end

    //------------------------------------------------------------------------
    // Driving the inputs: all combinations, counting up from the data wires as on the
    // breadboard, then in Gray code order

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

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

        $display ("cycle  A4..A1  B4..B1  Ka  Kb  D4..D1  E4..E1  generic  chips");

        checking <= '1;

        for (int i = 0; i < 1024; i ++)
        begin
            { a, b, ka, kb } <= 10' (i) ^ 10'h14c;
            @ (posedge clk);
        end

        for (int i = 0; i < 1024; i ++)
        begin
            { a, b, ka, kb } <= 10' (i ^ (i >> 1)) ^ 10'h14c;
            @ (posedge clk);
        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 && & rows_seen)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, %0d of %0d input combinations seen",
                n_errors, n_checks, $countones (rows_seen), 1024);
    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 M9: 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 mask_merge.sv mask_merge_chips.sv cd4019.sv cd4081.sv cd4071.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 M9: 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 mask_merge.sv mask_merge_chips.sv cd4019.sv cd4081.sv cd4071.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 M9: 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 mask_merge.sv mask_merge_chips.sv cd4019.sv cd4081.sv cd4071.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  A4..A1  B4..B1  Ka  Kb  D4..D1  E4..E1  generic  chips
    1  0101    0011    0   0   0000    0000    ok       ok   
    2  0101    0011    0   1   0011    0011    ok       ok   
    3  0101    0011    1   0   0101    0101    ok       ok   
    4  0101    0011    1   1   0111    0111    ok       ok   
 1025  0101    0011    0   0   0000    0000    ok       ok   
 1026  0101    0011    0   1   0011    0011    ok       ok   
 1027  0101    0011    1   1   0111    0111    ok       ok   
 1028  0101    0011    1   0   0101    0101    ok       ok   
tb.sv:162: $finish called at 20485000 (1ps)
PASS: 4096 checks, no errors

To see that the testbench catches mistakes, break something and run it again: change a_term | b_term to a_term ^ b_term in mask_merge.sv, or swap Ka and Kb at the 4019 in mask_merge_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_02_mux to a new directory.
  2. Replace its lab_top.sv with bgm_lab/lab_top.sv from this exercise and add mask_merge.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.

Switches 0 and 1 are Ka and Kb, switches 5–2 are A4…A1, and B4…B1 is fixed in lab_top.sv as on the breadboard. LEDs 3–0 show D and LEDs 7–4 show E. To run the chip-level design instead, add mask_merge_chips.sv and the chip models and change the module name in the instance.

bgm_lab/lab_top.sv100 lines · show the codefile
// Exercise M9 on an FPGA board with the Basics-Graphics-Music (BGM) labs:
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy labs/1_basics/1_02_mux to a new directory, replace its lab_top.sv with
// this file and add mask_merge.sv. For the chip-level design add
// mask_merge_chips.sv and cd4019.sv, cd4081.sv, cd4071.sv instead, and change
// the module name below.
//
// Switches: sw [0] ka, sw [1] kb, sw [5:2] a. The LEDs: led [3:0] d, led
// [7:4] e. A board with fewer LEDs shows the first ones.
//
// B4-B1 is fixed at 0011, as the wires on the breadboard.

`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 abcdefgh   = '0;
       assign digit      = '0;
       assign red        = '0;
       assign green      = '0;
       assign blue       = '0;
       assign sound      = '0;
       assign uart_tx    = '1;

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

    logic [3:0] d;
    logic [3:0] e;

    mask_merge i_mask_merge
    (
        .ka ( sw [0]   ),
        .kb ( sw [1]   ),
        .a  ( sw [5:2] ),
        .b  ( 4'b0011  ),
        .d  ( d        ),
        .e  ( e        )
    );

    assign led = w_led' ({ e, d });

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/1_gates_and_muxes.
  2. Replace its hackathon_top.sv with bgm_hackathon/hackathon_top.sv and add mask_merge.sv.
  3. Run ./03_synthesize_for_fpga.bash and ./04_configure_fpga.bash.

Keys 0 and 1 are Ka and Kb, keys 2–5 are A1–A4; B is fixed. The screen shows the inputs in blue and D and E in green.

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

// Exercise M9 in the hackathon setup of Basics-Graphics-Music (BGM):
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy a directory such as hackathon/problems/1_gates_and_muxes, replace its
// hackathon_top.sv with this file and add mask_merge.sv.
//
// Keys: key [0] ka, key [1] kb, key [5:2] a. The LEDs: led [3:0] d, led [7:4]
// e. The screen shows 14 lamps in a row: Ka, Kb, A1, A2, A3, A4, D1, D2, D3,
// D4, E1, E2, E3, E4; inputs in blue, outputs in green.
//
// B4-B1 is fixed at 0011, as the wires on the breadboard.
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
);

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

    wire       ka = key [0];
    wire       kb = key [1];
    wire [3:0] a = key [5:2];

    logic [3:0] d;
    logic [3:0] e;

    mask_merge i_mask_merge
    (
        .ka ( ka      ),
        .kb ( kb      ),
        .a  ( a       ),
        .b  ( 4'b0011 ),
        .d  ( d       ),
        .e  ( e       )
    );

    assign led      = { e, d };

    assign abcdefgh = '0;
    assign digit    = '0;

    //------------------------------------------------------------------------
    // 14 square lamps on the 480 x 272 screen, 20 pixels wide, 32 apart:
    // the inputs in blue, the outputs in green.  Bright when 1, dim when 0.

    wire [13:0] lamp = { e, d, a, kb, ka };

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

        for (int i = 0; i < 14; i ++)
            if (x >= 9' (22 + i * 32) & x < 9' (42 + i * 32) & y >= 126 & y < 146)
            begin
                if (i < 6)
                    blue  = lamp [i] ? 31 : 6;
                else
                    green = lamp [i] ? 63 : 12;
            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.

This design has no clock and no state: project.v connects the DIP switches to its inputs and its outputs to the display. The project still gets a clock and a reset from the board; they stay unused.

Switches 0 and 1 are Ka and Kb, switches 2–5 are A1–A4; B is fixed in project.v. The display has only eight segments, so it shows D on segments a–d and E on e–g and the dot.

tiny_tapeout/project.v54 lines · show the codefile
/*
 * Exercise M9 on Tiny Tapeout: the 4019 and the same function from gates, with the DIP switches as
 * inputs and the 7-segment display of the demo board as lamps.
 *
 * Add mask_merge.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
);

    // Switch 0 is ka, switch 1 is kb, switches 5-2 are a
    // B4-B1 is fixed at 0011, as the wires on the breadboard.

    wire [3:0] d;
    wire [3:0] e;

    mask_merge i_mask_merge (
        .ka ( ui_in [0]   ),
        .kb ( ui_in [1]   ),
        .a  ( ui_in [5:2] ),
        .b  ( 4'b0011     ),
        .d  ( d           ),
        .e  ( e           )
    );

    // 7-segment display: uo_out [0] is segment a, ..., uo_out [6] is g,
    // uo_out [7] is the dot.  Each output lights one segment:
    // a (top) d [0], b (top right) d [1], c (bottom right) d [2], d (bottom)
    // d [3], e (bottom left) e [0], f (top left) e [1], g (middle) e [2], h
    // (the dot) e [3].

    assign uo_out  = { e, d };

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

    // The circuit needs no clock or reset.
    // List all unused inputs to prevent warnings

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

endmodule

In info.yaml list the files and use the module name as the top module:

project:
  top_module: "tt_um_example"   # rename to tt_um_<your GitHub name>_mask_merge
  source_files:
    - "project.v"
    - "mask_merge.sv"

15Going further

Tasks for students

Files of this exercise

Sources

The exercise is in the Mini-projects list of “An improved way of teaching school kids digital electronics” and in lesson 1.6 of the Habr article about the electronics course. The chips are described in the Texas Instruments datasheets for the CD4019B, CD4081B and CD4071B.