Breadboard exercises/ B1EnglishРусский

Exercise B1 · basics · logic gates

AND, OR, XOR and NOT gates

Two buttons, four chips and one row of LEDs. Press A, B, both or neither, and the LEDs show the result of an AND, an OR, an XOR and two NOT gates at once: each press is one row of the truth table.

4 chips4081 AND, 4071 OR, 4070 XOR, 4069 NOT
36 + 14 wireson the board + jumper leads to the modules
4 input rowsA and B: 00, 01, 10, 11
no clockthe outputs follow the buttons at once

1What it is and why it matters

What it does. Button A and button B each give a 0 or a 1: 0 while the button is up, 1 while it is pressed. Both signals go to one gate of each of four chips. The 8-LED module shows the two inputs on LEDs 1 and 2 and the five results on LEDs 3–7: A AND B, A OR B, A XOR B, NOT A and NOT B. This is the first exercise of the Basics list in “An improved way of teaching school kids digital electronics”: “Demo 4081 (AND), 4071 (OR), 4069 (NOT), 4070 (XOR)”; lesson 1.1 of the Habr article uses the same chips.

How it works. A gate computes one output from its inputs, and only from its present inputs: it has no memory and no clock. Its whole behaviour fits in a truth table with one row for each combination of the inputs; two inputs give four rows. The LEDs on this board show all five tables side by side.

Where it is used. Everywhere. Every digital chip, from a calculator to a graphics processor, is built from gates and flip-flops. An adder is XOR and AND gates (exercise B9); a multiplexer picks one of several inputs with AND and OR; a comparator checks two numbers bit by bit with XOR; the next-state logic of every state machine is gates. When a synthesis tool turns SystemVerilog into a circuit, it produces a network of gates like these, only millions of them.

Why learn it.

2The key elements: four kinds of gate

AND

ABY
ABY = A AND B
000
010
100
111

Y = 1 only when A and B are both 1. In SystemVerilog: a & b.

OR

ABY
ABY = A OR B
000
011
101
111

Y = 1 when A or B or both are 1. In SystemVerilog: a | b.

XOR, exclusive OR

ABY
ABY = A XOR B
000
011
101
110

Y = 1 when A and B are different. In SystemVerilog: a ^ b.

NOT, inverter

AY
AY = NOT A
01
10

Y is the opposite of A. The small circle means NOT. In SystemVerilog: ~ a.

All five results for each row

This is what LEDs 1–7 show, one row per combination of the buttons. The bar over a letter, as in A, is the usual way to write NOT A.

ABA&BA|BA^B~A~B
0000011
0101110
1001101
1111000

Two things to notice. XOR is OR without its last row: it is 0 when both inputs are 1. And NOT A AND NOT B is 1 only in the first row, where A OR B is 0: that is one of De Morgan's laws, ~ (a | b) == ~ a & ~ b, which exercise B2 builds with these chips.

Waveforms

ABA&BA|BA^BAB
From the simulation of tb.sv in Icarus Verilog. The testbench sets A and B right after a rising edge of its clock (dotted lines) and checks the outputs at the next edge. The outputs change together with the inputs: gates have no clock. · SVG · PNG

3Parts

PartIn this circuitQtyPriceSupplier
CD4081quad 2-input AND: A AND B (one gate used)1$0.55Elexp (elexp.com)
CD4071quad 2-input OR: A OR B (one gate used)1$0.25Elexp (elexp.com)
CD4070quad 2-input XOR: A XOR B (one gate used)1$0.45Elexp (elexp.com)
CD4069hex inverter: NOT A and NOT B (two of six used)1$0.30Elexp (elexp.com)
Button modulesA and B; two modules from the pack of five2$0.66 / packaliexpress.us
8-LED moduleshows A, B and the five results1$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
Male-male Dupont jumpers36 wires on the board (or pre-cut wires)36$1.30 / packaliexpress.us
Male-female Dupont jumpers14 leads to the buttons and the LED module14$1.30 / packaliexpress.us

Prices from the LSSK components sheet; all of these parts are in the Basics kit. The board wires are male-male Dupont jumpers from the Basics kit; pre-cut wires lie flatter and match the drawing better.

The LEDs need no resistors. The LED module and the 5 V LEDs of the kit have their current-limiting resistors built in, and the button modules have their pull-down resistors built in. The circuit has only the chips, the modules and wires.

4The chips, pin by pin

All four 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, and it can also make the chip draw extra current. That is why every unused gate input here is wired to +5V or GND, and why there are more tie-off wires than signal wires. Outputs of unused gates stay open. The drawings show each chip from above, the way it sits on the breadboard: notch on the left, pin 1 at the bottom left, pins numbered counter-clockwise. Blue arrows are inputs, orange arrows are outputs.

4081: quad 2-input AND

1A2B3J4K5C6D7VSS8E9F10L11M12G13H14VDD4081
CD4081B. Four independent AND gates. · SVG · PNG

Pin 3 = pin 1 AND pin 2 makes A AND B. The 4081, 4071 and 4070 have the same pinout: gate J has inputs on pins 1 and 2 and its output on pin 3, gate K on pins 5, 6 and 4, gate L on 8, 9 and 10, gate M on 12, 13 and 11. Only the function inside differs.

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 Dnot 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 = E AND Fnot connected
11MoutputM = G AND 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

4071: quad 2-input OR

1A2B3J4K5C6D7VSS8E9F10L11M12G13H14VDD4071
CD4071B. Four independent OR gates. · SVG · PNG

Pin 3 = pin 1 OR pin 2 makes A OR B. The other three gates are not used; their six inputs go to the rails.

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 OR BA|B
4KoutputK = C OR Dnot 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 = E OR Fnot connected
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

4070: quad 2-input XOR

1A2B3J4K5C6D7VSS8E9F10L11M12G13H14VDD4070
CD4070B. Four independent exclusive-OR gates: the extra curve on the input side marks XOR. · SVG · PNG

Pin 3 = pin 1 XOR pin 2 makes A XOR B.

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 XOR BA^B
4KoutputK = C XOR Dnot 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 = E XOR Fnot connected
11MoutputM = G XOR 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

4069: hex inverter

1A2G3B4H5C6I7VSS8J9D10K11E12L13F14VDD4069
CD4069UB. Six inverters, each with its input and output on neighbouring pins. · SVG · PNG

Pin 2 = NOT pin 1 makes NOT A, pin 4 = NOT pin 3 makes NOT B. The 4069 has a different pinout from the other three: an inverter has only one input. The four unused inverters have their inputs on pins 5, 9, 11 and 13.

Polarity. On all four chips 1 means +5 V and 0 means 0 V, and an LED lights for 1. The buttons give 1 while pressed.

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 4B
4HoutputH = NOT BB
5Cinputinput of the gate with its output on pin 6tied to GND
6IoutputI = NOT Cnot connected
7VSSpowerground, 0 VGND
8JoutputJ = NOT Dnot connected
9Dinputinput of the gate with its output on pin 8tied to +5V
10KoutputK = NOT Enot connected
11Einputinput of the gate with its output on pin 10tied to +5V
12LoutputL = NOT Fnot connected
13Finputinput of the gate with its output on pin 12tied to +5V
14VDDpowersupply, +5 V (3 to 18 V allowed)+5V

5Schematic 1: the gates

ABALED 1BLED 2A&BLED 3A|BLED 4A^BLED 5ALED 6BLED 7
The circuit as gates, without chips. This is what basic_gates.sv describes. A dot means a connection; crossing lines without a dot are not connected. · SVG · PNG

Five gates read the same two signals. The A line feeds the AND, OR and XOR gates and one NOT gate; the B line feeds the same three gates and the other NOT gate. On the breadboard each line is one net: the button, a wire from chip to chip and a lead to the LED module.

6Schematic 2: connections between the chips

12345678910111213144081123456789101112131440711234567891011121314407012345678910111213144069ABA&BA|BA^BABbutton Abutton BLED module: LEDs 1-7+5V
The same circuit as chips, pin by pin. Each chip is drawn from above with the notch on the left; pin numbers are next to the pins. The gates in use are drawn in full, the unused ones faded, their inputs tied to +5V (T) or GND. The boxes at the bottom are the modules. · SVG · PNG

Every connection of the circuit, net by net. basic_gates_chips.sv in section 10 is written from the same list.

NetFromToWire
Abutton A, OUT4081 1 (A), 4071 1 (A), 4070 1 (A), 4069 1 (A), LED module, LED 1M-F, M-M
Bbutton B, OUT4081 2 (B), 4071 2 (B), 4070 2 (B), 4069 3 (B), LED module, LED 2M-F, M-M
A&B4081 3 (J)LED module, LED 3M-F
A|B4071 3 (J)LED module, LED 4M-F
A^B4070 3 (J)LED module, LED 5M-F
A4069 2 (G)LED module, LED 6M-F
B4069 4 (H)LED module, LED 7M-F
+5V+5V4081 14 (VDD), 4071 14 (VDD), 4070 14 (VDD), 4069 14 (VDD), 4081 13 (H), 4081 12 (G), 4081 9 (F), 4081 8 (E), 4071 13 (H), 4071 12 (G), 4071 9 (F), 4071 8 (E), 4070 13 (H), 4070 12 (G), 4070 9 (F), 4070 8 (E), 4069 13 (F), 4069 11 (E), 4069 9 (D)
GNDGND4081 7 (VSS), 4071 7 (VSS), 4070 7 (VSS), 4069 7 (VSS), 4081 5 (C), 4081 6 (D), 4071 5 (C), 4071 6 (D), 4070 5 (C), 4070 6 (D), 4069 5 (C)
not connected4081 4 (K), 4081 10 (L), 4081 11 (M), 4071 4 (K), 4071 10 (L), 4071 11 (M), 4070 4 (K), 4070 10 (L), 4070 11 (M), 4069 6 (I), 4069 8 (J), 4069 10 (K), 4069 12 (L)

7Schematic 3: the breadboard

−+−+1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950abcdefghij5V5VPOWER MODULE · 5V9V USB-DC4081407140704069AAABBB+OUT−BUTTON A+OUT−BUTTON BG1A2B3A&B4A|B5A^B6A7B88-LED MODULELEDs 1-7 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 two buttons and the LED module hang below the board on male-female jumpers. The board goes on to column 63 on the right. · SVG · PNG
ABA&BA|BA^BAB+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, notch to the left: the 4081 with pin 1 in hole 10f, the 4071 in 19f, the 4070 in 28f, the 4069 in 37f. Read the numbers on the chips: the 4081, 4071 and 4070 look the same.
  3. Power: for each chip a red wire from pin 14 to the top + rail and a black wire from pin 7 to the bottom − rail.
  4. The tie-offs: every unused input to the nearest rail, top pins to +, bottom pins to −. It is the longest part of the job; tick each wire in the checklist.
  5. The six signal wires: line A from pin 1 of the 4081 through pin 1 of the 4071 and the 4070 to pin 1 of the 4069, line B from pin 2 to pin 2 to pin 2 to pin 3 of the 4069.
  6. With the power off, the modules: the buttons and the LED module below the board. Connect the − of each button and G of the LED module first.
  7. Turn the power on.

Wiring checklist

·

#NetFromTo
Power (red to +, black to −) · 8 wires
1+5V10a (4081 pin 14, VDD)top + rail, column 10
2GND16j (4081 pin 7, VSS)bottom − rail, column 16
3+5V19a (4071 pin 14, VDD)top + rail, column 19
4GND25j (4071 pin 7, VSS)bottom − rail, column 25
5+5V28a (4070 pin 14, VDD)top + rail, column 28
6GND34j (4070 pin 7, VSS)bottom − rail, column 34
7+5V37a (4069 pin 14, VDD)top + rail, column 37
8GND43j (4069 pin 7, VSS)bottom − rail, column 43
Fixed inputs: CMOS inputs must not float · 22 wires
9+5V11a (4081 pin 13, H)top + rail, column 11
10+5V12a (4081 pin 12, G)top + rail, column 12
11GND14j (4081 pin 5, C)bottom − rail, column 14
12+5V15a (4081 pin 9, F)top + rail, column 15
13GND15j (4081 pin 6, D)bottom − rail, column 15
14+5V16a (4081 pin 8, E)top + rail, column 16
15+5V20a (4071 pin 13, H)top + rail, column 20
16+5V21a (4071 pin 12, G)top + rail, column 21
17GND23j (4071 pin 5, C)bottom − rail, column 23
18+5V24a (4071 pin 9, F)top + rail, column 24
19GND24j (4071 pin 6, D)bottom − rail, column 24
20+5V25a (4071 pin 8, E)top + rail, column 25
21+5V29a (4070 pin 13, H)top + rail, column 29
22+5V30a (4070 pin 12, G)top + rail, column 30
23GND32j (4070 pin 5, C)bottom − rail, column 32
24+5V33a (4070 pin 9, F)top + rail, column 33
25GND33j (4070 pin 6, D)bottom − rail, column 33
26+5V34a (4070 pin 8, E)top + rail, column 34
27+5V38a (4069 pin 13, F)top + rail, column 38
28+5V40a (4069 pin 11, E)top + rail, column 40
29GND41j (4069 pin 5, C)bottom − rail, column 41
30+5V42a (4069 pin 9, D)top + rail, column 42
Signal wires · 6 wires
31A10g (4081 pin 1, A)19g (4071 pin 1, A)
32A19h (4071 pin 1, A)28g (4070 pin 1, A)
33A28h (4070 pin 1, A)37g (4069 pin 1, A)
34B11g (4081 pin 2, B)20g (4071 pin 2, B)
35B20h (4071 pin 2, B)29g (4070 pin 2, B)
36B29h (4070 pin 2, B)39g (4069 pin 3, B)
Modules on male-female jumpers · 14 wires
37+5Vbutton A, +bottom + rail, column 6
38Abutton A, OUT10j (4081 pin 1, A)
39GNDbutton A, −bottom − rail, column 8
40+5Vbutton B, +bottom + rail, column 12
41Bbutton B, OUT11j (4081 pin 2, B)
42GNDbutton B, −bottom − rail, column 13
43GNDLED module, Gbottom − rail, column 27
44ALED module, LED 128j (4070 pin 1, A)
45BLED module, LED 229j (4070 pin 2, B)
46A&BLED module, LED 312j (4081 pin 3, J)
47A|BLED module, LED 421j (4071 pin 3, J)
48A^BLED module, LED 530j (4070 pin 3, J)
49ALED module, LED 638j (4069 pin 2, G)
50BLED module, LED 740j (4069 pin 4, H)

Test it

If it does not work: an LED that never lights usually means a lead in the wrong hole; an LED that is always on, an input of its gate tied to +5V by mistake. If several LEDs flicker when you touch the wires, an input is floating: look for a missing tie-off. If a chip gets warm, turn the power off at once: a chip inserted the wrong way round or a short between + and − are the usual causes.

8SystemVerilog: the generic design

basic_gates.sv describes schematic 1: five assign statements, one per gate. It is synthesizable: an FPGA tool turns it into a few lookup tables, an ASIC flow into five standard cells.

basic_gates.svfile
// Exercise B1: the basic gates AND, OR, XOR and NOT.
//
// Generic version that matches schematic 1: five gates, not tied to any
// chip.  Synthesizable.

module basic_gates
(
    input  logic a,
    input  logic b,

    output logic a_and_b,  // 1 when both inputs are 1
    output logic a_or_b,   // 1 when at least one input is 1
    output logic a_xor_b,  // 1 when the inputs differ
    output logic not_a,    // 1 when a is 0
    output logic not_b     // 1 when b is 0
);

    assign a_and_b = a & b;
    assign a_or_b  = a | b;
    assign a_xor_b = a ^ b;
    assign not_a   = ~ a;
    assign not_b   = ~ b;

endmodule

An assign is not a step of a program: it is a wire that always carries the value of its expression, like the output pin of a gate.

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. All four models are synthesizable. The models leave out the power pins: in SystemVerilog a wire simply has the value 0 or 1.

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
cd4070.svfile
// CD4070B: quad 2-input exclusive-OR (XOR) gate.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (7)
// and VDD (14), are left out.  Synthesizable.
//
// The 4070, 4071 and 4081 have the same pinout: only the function of the
// gates differs.

module cd4070
(
    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
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

10SystemVerilog: the chip-level design

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

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

module basic_gates_chips
(
    input  logic       a,
    input  logic       b,
    output logic       a_and_b,
    output logic       a_or_b,
    output logic       a_xor_b,
    output logic       not_a,
    output logic       not_b
);

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

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

    // Outputs that go nowhere

    wire unused_u1_k;
    wire unused_u1_l;
    wire unused_u1_m;
    wire unused_u2_k;
    wire unused_u2_l;
    wire unused_u2_m;
    wire unused_u3_k;
    wire unused_u3_l;
    wire unused_u3_m;
    wire unused_u4_i;
    wire unused_u4_j;
    wire unused_u4_k;
    wire unused_u4_l;

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

    // U1: CD4081 quad 2-input AND, pin 1 in column 10

    cd4081 i_u1
    (
        .a ( a           ),  // Pin 1 <- button A
        .b ( b           ),  // Pin 2 <- button B
        .j ( a_and_b     ),  // Pin 3 -> A&B
        .k ( unused_u1_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_u1_l ),  // Pin 10, unused output
        .m ( unused_u1_m ),  // Pin 11, unused output
        .g ( vdd         ),  // Pin 12 <- +5V, unused input
        .h ( vdd         )   // Pin 13 <- +5V, unused input
    );

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

    // U2: CD4071 quad 2-input OR, pin 1 in column 19

    cd4071 i_u2
    (
        .a ( a           ),  // Pin 1 <- button A
        .b ( b           ),  // Pin 2 <- button B
        .j ( a_or_b      ),  // Pin 3 -> A|B
        .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 ( unused_u2_m ),  // Pin 11, unused output
        .g ( vdd         ),  // Pin 12 <- +5V, unused input
        .h ( vdd         )   // Pin 13 <- +5V, unused input
    );

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

    // U3: CD4070 quad 2-input XOR, pin 1 in column 28

    cd4070 i_u3
    (
        .a ( a           ),  // Pin 1 <- button A
        .b ( b           ),  // Pin 2 <- button B
        .j ( a_xor_b     ),  // Pin 3 -> A^B
        .k ( unused_u3_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_u3_l ),  // Pin 10, unused output
        .m ( unused_u3_m ),  // Pin 11, unused output
        .g ( vdd         ),  // Pin 12 <- +5V, unused input
        .h ( vdd         )   // Pin 13 <- +5V, unused input
    );

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

    // U4: CD4069 hex inverter (six NOT gates), pin 1 in column 37

    cd4069 i_u4
    (
        .a ( a           ),  // Pin 1 <- button A
        .g ( not_a       ),  // Pin 2 -> ~A
        .b ( b           ),  // Pin 3 <- button B
        .h ( not_b       ),  // Pin 4 -> ~B
        .c ( gnd         ),  // Pin 5 <- GND, unused input
        .i ( unused_u4_i ),  // Pin 6, unused output
        .j ( unused_u4_j ),  // Pin 8, unused output
        .d ( vdd         ),  // Pin 9 <- +5V, unused input
        .k ( unused_u4_k ),  // Pin 10, unused output
        .e ( vdd         ),  // Pin 11 <- +5V, unused input
        .l ( unused_u4_l ),  // Pin 12, unused output
        .f ( vdd         )   // Pin 13 <- +5V, unused input
    );

endmodule

11Testbench and simulation scripts

tb.sv runs both designs side by side and compares them with the truth tables, written out row by row. The gates have no clock, but the testbench has one, like the testbenches of Basics-Graphics-Music: it sets A and B right after a rising edge and checks the outputs at the next rising edge. It goes through the four rows twice, in two different orders, and prints PASS only if both designs match every time and every row was seen.

tb.sv154 lines · show the codefile
// Testbench for exercise B1.
//
// Runs the generic design (basic_gates.sv) and the chip-level design
// (basic_gates_chips.sv) side by side and compares both with the truth
// tables of the gates.  Works with Icarus Verilog, Verilator (--binary)
// and Questa.
//
// The gates have 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 A and B after one edge and checks the outputs at the next.

// 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 a, b;

    wire  a_and_b, a_and_b_chips;
    wire  a_or_b,  a_or_b_chips;
    wire  a_xor_b, a_xor_b_chips;
    wire  not_a,   not_a_chips;
    wire  not_b,   not_b_chips;

    basic_gates i_generic
    (
        .a       ( a       ),
        .b       ( b       ),
        .a_and_b ( a_and_b ),
        .a_or_b  ( a_or_b  ),
        .a_xor_b ( a_xor_b ),
        .not_a   ( not_a   ),
        .not_b   ( not_b   )
    );

    basic_gates_chips i_chips
    (
        .a       ( a             ),
        .b       ( b             ),
        .a_and_b ( a_and_b_chips ),
        .a_or_b  ( a_or_b_chips  ),
        .a_xor_b ( a_xor_b_chips ),
        .not_a   ( not_a_chips   ),
        .not_b   ( not_b_chips   )
    );

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

    initial
    begin
        clk = '0;

        forever
            # 5 clk = ~ clk;
    end

    //------------------------------------------------------------------------
    // Reference model: the truth tables, written out row by row.
    // Bits: AND, OR, XOR, NOT A, NOT B.

    function automatic logic [4:0] expected (input logic in_a, input logic in_b);
        case ({ in_a, in_b })
        2'b00:   return 5'b000_11;
        2'b01:   return 5'b011_10;
        2'b10:   return 5'b011_01;
        2'b11:   return 5'b110_00;
        default: return 5'bxxx_xx;
        endcase
    endfunction

    wire [4:0] out       = { a_and_b,       a_or_b,       a_xor_b,       not_a,       not_b       };
    wire [4:0] out_chips = { a_and_b_chips, a_or_b_chips, a_xor_b_chips, not_a_chips, not_b_chips };

    //------------------------------------------------------------------------
    // Checking at every rising clock edge: A and B 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 [3:0] rows_seen = '0;  // Which rows of the truth table were checked

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

            $display ("%5d  %b %b   %b   %b   %b    %b    %b     %s  %s",
                cycle + 1, a, b, a_and_b, a_or_b, a_xor_b, not_a, not_b,
                out       === expected (a, b) ? "ok     " : "WRONG  ",
                out_chips === expected (a, b) ? "ok   "   : "WRONG");
        end

    //------------------------------------------------------------------------
    // Driving A and B: every row of the truth table, twice, in two orders

    wire [15:0] order = 16'b00_01_10_11_11_10_00_01;  // { A, B } for each step

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

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

        $display ("cycle  A B  AND  OR XOR NOT A NOT B  generic  chips");

        checking <= '1;

        for (int i = 0; i < 8; i ++)
        begin
            { a, b } <= order [15 - 2 * i -: 2];
            @ (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 == 4'b1111)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, truth table rows seen %b", n_errors, n_checks, rows_seen);
    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 B1: 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 basic_gates.sv basic_gates_chips.sv cd4081.sv cd4071.sv cd4070.sv cd4069.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 B1: 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 basic_gates.sv basic_gates_chips.sv cd4081.sv cd4071.sv cd4070.sv cd4069.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 B1: 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 basic_gates.sv basic_gates_chips.sv cd4081.sv cd4071.sv cd4070.sv cd4069.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  A B  AND  OR XOR NOT A NOT B  generic  chips
    1  0 0   0   0   0    1    1     ok       ok   
    2  0 1   0   1   1    1    0     ok       ok   
    3  1 0   0   1   1    0    1     ok       ok   
    4  1 1   1   1   0    0    0     ok       ok   
    5  1 1   1   1   0    0    0     ok       ok   
    6  1 0   0   1   1    0    1     ok       ok   
    7  0 0   0   0   0    1    1     ok       ok   
    8  0 1   0   1   1    1    0     ok       ok   
tb.sv:141: $finish called at 85000 (1ps)
PASS: 16 checks, no errors

To see that the testbench catches mistakes, break something and run it again: change a ^ b to a | b in basic_gates.sv, or swap the connections of two outputs in basic_gates_chips.sv. The script reports FAIL and the trace marks the rows 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, reset, keys, LEDs, a 7-segment display. The first BGM lab, 1_01_and_or_not_xor_de_morgan, is about the same gates.

  1. Copy labs/1_basics/1_01_and_or_not_xor_de_morgan to a new directory.
  2. Replace its lab_top.sv with bgm_lab/lab_top.sv from this exercise and add basic_gates.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.

Keys 0 and 1 are A and B; the LEDs show A AND B, A OR B, A XOR B, NOT A and NOT B. To run the chip-level design instead, add basic_gates_chips.sv and the four chip models and change the module name in the instance.

bgm_lab/lab_top.sv99 lines · show the codefile
// Exercise B1 on an FPGA board with the Basics-Graphics-Music (BGM) labs:
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy labs/1_basics/1_01_and_or_not_xor_de_morgan to a new directory,
// replace its lab_top.sv with this file and add basic_gates.sv.  For the
// chip-level design add basic_gates_chips.sv and cd4081.sv, cd4071.sv,
// cd4070.sv, cd4069.sv instead, and change the module name below.
//
// Keys 0 and 1 are the buttons A and B.  The LEDs show the results:
// led [0] A AND B, led [1] A OR B, led [2] A XOR B, led [3] NOT A,
// led [4] NOT B.  A board with fewer LEDs shows the first ones.

`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 a_and_b, a_or_b, a_xor_b, not_a, not_b;

    basic_gates i_basic_gates
    (
        .a       ( key [0] ),
        .b       ( key [1] ),
        .a_and_b ( a_and_b ),
        .a_or_b  ( a_or_b  ),
        .a_xor_b ( a_xor_b ),
        .not_a   ( not_a   ),
        .not_b   ( not_b   )
    );

    assign led = w_led' ({ not_b, not_a, a_xor_b, a_or_b, a_and_b });

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 a directory such as hackathon/problems/1_gates_and_muxes.
  2. Replace its hackathon_top.sv with bgm_hackathon/hackathon_top.sv and add basic_gates.sv.
  3. Run ./03_synthesize_for_fpga.bash and ./04_configure_fpga.bash.

Keys 0 and 1 are A and B. The screen shows seven square lamps in a row, A and B in blue and the five results in green, like the LED module on the breadboard.

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

// Exercise B1 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 basic_gates.sv.
//
// Keys 0 and 1 are A and B.  The LEDs show the results: led [0] A AND B,
// led [1] A OR B, led [2] A XOR B, led [3] NOT A, led [4] NOT B.
// The screen shows seven lamps in a row: A, B and the five results.

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 a = key [0];
    wire b = key [1];

    logic a_and_b, a_or_b, a_xor_b, not_a, not_b;

    basic_gates i_basic_gates
    (
        .a       ( a       ),
        .b       ( b       ),
        .a_and_b ( a_and_b ),
        .a_or_b  ( a_or_b  ),
        .a_xor_b ( a_xor_b ),
        .not_a   ( not_a   ),
        .not_b   ( not_b   )
    );

    assign led      = { 3'b0, not_b, not_a, a_xor_b, a_or_b, a_and_b };

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

    //------------------------------------------------------------------------
    // Seven square lamps on the 480 x 272 screen, 40 pixels wide, 24 apart:
    // A and B in blue, the results in green.  Bright when 1, dim when 0.

    wire [6:0] lamp = { not_b, not_a, a_xor_b, a_or_b, a_and_b, b, a };

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

        for (int i = 0; i < 7; i ++)
            if (x >= 9' (30 + i * 64) & x < 9' (70 + i * 64) & y >= 116 & y < 156)
            begin
                if (i < 2)
                    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.

Switches 0 and 1 are A and B. The display has no row of LEDs, so each result lights one segment: a (top) is A AND B, b (top right) A OR B, c (bottom right) A XOR B, d (bottom) NOT A, e (bottom left) NOT B. The gates need no clock: clk and rst_n are listed as unused.

tiny_tapeout/project.v52 lines · show the codefile
/*
 * Exercise B1 on Tiny Tapeout: the basic gates, with the DIP switches as
 * inputs and the 7-segment display of the demo board as five lamps.
 *
 * Add basic_gates.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 A, switch 1 is B

    wire a_and_b, a_or_b, a_xor_b, not_a, not_b;

    basic_gates i_basic_gates (
        .a       ( ui_in [0] ),
        .b       ( ui_in [1] ),
        .a_and_b ( a_and_b   ),
        .a_or_b  ( a_or_b    ),
        .a_xor_b ( a_xor_b   ),
        .not_a   ( not_a     ),
        .not_b   ( not_b     )
    );

    // 7-segment display: uo_out [0] is segment a, ..., uo_out [6] is g,
    // uo_out [7] is the dot.  Each result lights one segment:
    // a (top) A AND B, b (top right) A OR B, c (bottom right) A XOR B,
    // d (bottom) NOT A, e (bottom left) NOT B.

    assign uo_out  = { 3'b0, not_b, not_a, a_xor_b, a_or_b, a_and_b };

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

    // The gates need no clock or reset.
    // List all unused inputs to prevent warnings

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

endmodule

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

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

15Going further

Tasks for students

Files of this exercise

Sources

The exercise is the first of the Basics list in “An improved way of teaching school kids digital electronics using venerable small-scale integration ICs”; lesson 1.1 of the Habr article about the electronics course describes the class with these chips, 5 V LEDs and buttons with built-in pull-down resistors. The chips are described in the Texas Instruments datasheets for the CD4081B, CD4071B, CD4070B and CD4069UB.