Breadboard exercises/ BB1EnglishРусский

Exercise BB1 · building blocks · programmable gate

4048 multifunction 8-input gate

One chip, eight functions: three wires choose whether the 4048 is an 8-input AND, OR, NAND, NOR or one of four two-level combinations. Four buttons drive inputs A–D; the other inputs and the function are wires that you move between the rails.

1 chip4048 multifunction expandable gate
15 + 18 wireson the board + jumper leads to the modules
8 functionschosen by Ka, Kb and Kc
no clockthe output follows the inputs at once

1What it is and why it matters

What it does. The 4048 has eight inputs, A–H, in two groups of four, and one output, J. Three control inputs, Ka, Kb and Kc, choose what J computes: AND, OR, NAND or NOR of all eight inputs, or a two-level function such as (A or B or C or D) and (E or F or G or H). On this board buttons drive A–D, and E–H, Ka, Kb and Kc are wires to the rails. The LED module shows A–D and J. The wires start in the AND position: J lights only when all four buttons are pressed.

How it works. Inside, every input passes an XNOR gate with Ka, each group of four goes into a NAND gate, the two group results pass XNOR gates with Kb, then a NAND gate joins them and a last XNOR with Kc gives J. An XNOR with a control input is an inverter that you switch on or off: Ka, Kb and Kc decide where the circuit inverts, and by De Morgan's laws (exercise B2) that turns the same NAND gates into AND, OR, NAND or NOR.

Where it is used. The idea of a gate whose function is set by control bits is the heart of every FPGA: a lookup table is a small memory whose contents choose the function of its inputs. The 4048 is a fixed menu of eight functions; an FPGA lookup table with four inputs can make any of the 65 536 functions of four inputs. The idea of an output that can be switched off, Kd, is how many chips share one bus.

Why learn it.

2The key elements: the function table and the inside

The function table

Ka, Kb and Kc in the order of the datasheet. The last column says where to put the wires of E–H so that the 4048 works as a 4-input gate of the buttons.

KaKbKcFunctionJ isE–H for a 4-input gate of A–D
000NOR1 when all eight inputs are 0GND
001OR1 when any input is 1GND
010OR/AND(A or B or C or D) and (E or F or G or H)—
011OR/NANDnot ((A or … D) and (E or … H))—
100AND1 when all eight inputs are 1+5V
101NAND0 when all eight inputs are 1+5V
110AND/NORnot ((A and … D) or (E and … H))—
111AND/OR(A and B and C and D) or (E and F and G and H)—

Inside the 4048

ABCDEFGHKaKbKcJ
The logic diagram of the datasheet, redrawn: XNOR gates with Ka, two 4-input NAND gates, XNOR gates with Kb, a NAND gate and an XNOR gate with Kc. The EXPAND input and the output enable Kd are left out: here EXPAND is at GND and Kd at +5V. · SVG · PNG

An XNOR gate with one input at 1 passes the other input unchanged; with one input at 0 it inverts it. So Ka = 1 leaves the inputs as they are, and Ka = 0 inverts them before the NAND gates: an AND of inverted inputs is a NOR. Kb and Kc do the same one and two levels further on.

Waveforms

ABCDE-H11111110Kc..Ka001J
From the simulation of tb.sv in Icarus Verilog: the first 16 of its 4096 steps. Ka Kb Kc = 1 0 0, the AND function, and E–H at 1, as on the breadboard; J is 1 only when A–D are all 1. · SVG · PNG

3Parts

PartIn this circuitQtyPriceSupplier
CD4048multifunction expandable 8-input gate1$0.55ti.com
Button modulesA, B, C and D; 4 from the pack of five4$0.66 / packaliexpress.us
8-LED moduleshows A-D and the output J1$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 wires15 wires on the board (or male-male Dupont jumpers)15$11.95 / packjameco.com
Male-female Dupont jumpers18 leads to the buttons and the LED module18$1.30 / packaliexpress.us

Prices from the LSSK components sheet; the 4048 is in the Comprehensive kit.

4The chip, 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.

4048: multifunction expandable 8-input gate

1J2Kd3H4G5F6E7Kb8VSS9Kc10Ka11D12C13B14A15EXP16VDD40488-input gate, 8 functions
CD4048B. A 16-pin chip: VDD is pin 16 and VSS pin 8. · SVG · PNG

Inputs A–D are on pins 14–11 of the top row, E–H on pins 6–3 of the bottom row. Ka is pin 10, Kc pin 9, both on the top row; Kb is pin 7 on the bottom row. The output J is pin 1.

Kd, pin 2, switches the output on (1) or off (0). Off means high impedance: the output is connected to nothing, as if the pin were cut, so that several 4048s can drive one wire in turn. Here Kd is tied to +5V.

EXPAND, pin 15, lets two 4048s make a 16-input gate: the J of one goes into EXPAND of the other. Here it is tied to GND, which means “no expansion”.

PinNameDirectionFunctionIn this circuit
1Joutputoutput J; 3-state: driven only while Kd = 1J
2KdinputKd: 1 = output on, 0 = output open (3-state)+5V
3Hinputinput HH (+5V)
4Ginputinput GG (+5V)
5Finputinput FF (+5V)
6Einputinput EE (+5V)
7KbinputKb: function select (Ka Kb Kc: 000 NOR, 001 OR, 010 OR/AND, 011 OR/NAND, 100 AND, 101 NAND, 110 AND/NOR, 111 AND/OR)Kb (GND)
8VSSpowerground, 0 VGND
9KcinputKc: function select, see KbKc (GND)
10KainputKa: function select, see KbKa (+5V)
11Dinputinput DD
12Cinputinput CC
13Binputinput BB
14Ainputinput AA
15EXPANDinputEXPAND: tie to GND when not used; 1 forces the inner NAND to 1GND
16VDDpowersupply, +5 V (3 to 18 V allowed)+5V

5Schematic 1: the gate as a block

ABCDEFGHKaKbKc4048ABCDEFGHKaKbKcKdEXPJ8-input multifunction gateALED 1BLED 2CLED 3DLED 4JLED 5
The circuit with the 4048 as one block. This is what multifunction_gate.sv describes. The open circles are the wires that you move between the rails. · SVG · PNG

6Schematic 2: connections

12345678910111213141516JKdHGFEKbKcKaDCBAEXP40488-input gate, 8 functionsABCDJABCDLED module: LEDs 1-5Ka→ +5VKc→ GNDH→ +5VG→ +5VF→ +5VE→ +5VKb→ GND+5V
The same circuit with the chip, pin by pin. The chip is drawn from above with the notch on the left. The boxes with an arrow are the wires you move, with the rail they start on. · SVG · PNG
NetFromToWire
Abutton A, OUT4048 14 (A), LED module, LED 1M-F, M-M
Bbutton B, OUT4048 13 (B), LED module, LED 2M-F, M-M
Cbutton C, OUT4048 12 (C), LED module, LED 3M-F, M-M
Dbutton D, OUT4048 11 (D), LED module, LED 4M-F, M-M
EE wire: +5V4048 6 (E)M-M
FF wire: +5V4048 5 (F)M-M
GG wire: +5V4048 4 (G)M-M
HH wire: +5V4048 3 (H)M-M
KaKa wire: +5V4048 10 (Ka)M-M
KbKb wire: GND4048 7 (Kb)M-M
KcKc wire: GND4048 9 (Kc)M-M
J4048 1 (J)LED module, LED 5M-F
+5V+5V4048 16 (VDD), 4048 2 (Kd)
GNDGND4048 8 (VSS), 4048 15 (EXP)

7Schematic 3: the breadboard

−+−+12345678910111213141516171819202122232425262728293031323334353637383940414243444546abcdefghij5V5VPOWER MODULE · 5V9V USB-DC4048EFGHKaKbKcBCD+OUT−A+OUT−B+OUT−C+OUT−DG1A2B3C4D5J6788-LED MODULELEDs 1-5 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 and the LED module below it, on male-female jumpers. The wires with a tag are the ones you move: E–H, Ka, Kb and Kc. · SVG · PNG
ABCDEFGHKaKbKcJ+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 4048 with pin 1 in hole 9f. Read the numbers on the chips: many look alike.
  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. Make sure no wire touches + and − at the same time.
  4. The fixed inputs: Kd (pin 2, column 10, bottom half) to the bottom + rail, EXPAND (pin 15, column 10, top half) to the top − rail.
  5. The wires you will move, in their starting positions: E, F, G and H (pins 6–3, columns 14–11, bottom half) to the bottom + rail; Ka (pin 10, column 15, top half) to the top + rail; Kb (pin 7, column 15, bottom half) to the bottom − rail; Kc (pin 9, column 16, top half) to the top − rail. Use a colour you will recognise.
  6. The four signal wires bring A–D from the top row down to the bottom half, where the leads of the LED module go.
  7. With the power off, the modules: the four buttons above the board, the LED module below. Connect the − of each button and G of the LED module first.
  8. Turn the power on.

Wiring checklist

·

#NetFromTo
Power (red to +, black to −) · 2 wires
1+5V9a (4048 pin 16, VDD)top + rail, column 9
2GND16j (4048 pin 8, VSS)bottom − rail, column 16
Fixed inputs: CMOS inputs must not float · 2 wires
10GND10a (4048 pin 15, EXP)top − rail, column 10
11+5V10j (4048 pin 2, Kd)bottom + rail, column 10
Mode wires: move them between + and − to change the mode · 7 wires
3E14j (4048 pin 6, E)bottom + rail, column 14
4F13j (4048 pin 5, F)bottom + rail, column 13
5G12j (4048 pin 4, G)bottom + rail, column 12
6H11j (4048 pin 3, H)bottom + rail, column 11
7Ka15a (4048 pin 10, Ka)top + rail, column 15
8Kb15j (4048 pin 7, Kb)bottom − rail, column 15
9Kc16a (4048 pin 9, Kc)top − rail, column 16
Signal wires · 4 wires
12A11d (4048 pin 14, A)8f
13B12d (4048 pin 13, B)17f
14C13c (4048 pin 12, C)18f
15D14b (4048 pin 11, D)19f
Modules on male-female jumpers · 18 wires
16+5Vbutton A, +top + rail, column 8
17Abutton A, OUT11a (4048 pin 14, A)
18GNDbutton A, −top − rail, column 9
19+5Vbutton B, +top + rail, column 13
20Bbutton B, OUT12a (4048 pin 13, B)
21GNDbutton B, −top − rail, column 15
22+5Vbutton C, +top + rail, column 18
23Cbutton C, OUT13a (4048 pin 12, C)
24GNDbutton C, −top − rail, column 20
25+5Vbutton D, +top + rail, column 23
26Dbutton D, OUT14a (4048 pin 11, D)
27GNDbutton D, −top − rail, column 25
28GNDLED module, Gbottom − rail, column 24
29ALED module, LED 18j
30BLED module, LED 217j
31CLED module, LED 318j
32DLED module, LED 419j
33JLED module, LED 59j (4048 pin 1, J)

Test it

If it does not work: check the three K wires against the table first: one wire on the wrong rail gives a different, perfectly working function. If J never changes, check Kd: at GND the output is switched off and the LED stays dark. If J is always lit in the AND position, an E–H wire is at −.

8SystemVerilog: the generic design

multifunction_gate.sv describes the function table directly: the OR and AND of each group, and a case on Ka, Kb and Kc that picks the function. It is synthesizable.

multifunction_gate.svfile
// Exercise BB1: the 4048 multifunction expandable 8-input gate.
//
// Generic version that matches the function table of the datasheet:
// Ka, Kb and Kc choose one of eight functions of the inputs A-H, which
// come in two groups of four.  Not tied to any chip.  Synthesizable.

module multifunction_gate
(
    input  logic       a,
    input  logic       b,
    input  logic       c,
    input  logic       d,
    input  logic [3:0] rest,  // E-H, rest [0] is E
    input  logic [2:0] k,     // k [0] is Ka, k [1] Kb, k [2] Kc

    output logic       j
);

    wire [3:0] group_1 = { d, c, b, a };
    wire [3:0] group_2 = rest;

    wire or_1  = | group_1;
    wire or_2  = | group_2;
    wire and_1 = & group_1;
    wire and_2 = & group_2;

    always_comb
        case ({ k [0], k [1], k [2] })   // Ka Kb Kc, as in the datasheet
        3'b000:  j = ~ (or_1 | or_2);    // NOR
        3'b001:  j =    or_1 | or_2;     // OR
        3'b010:  j =    or_1 & or_2;     // OR/AND
        3'b011:  j = ~ (or_1 & or_2);    // OR/NAND
        3'b100:  j =    and_1 & and_2;   // AND
        3'b101:  j = ~ (and_1 & and_2);  // NAND
        3'b110:  j = ~ (and_1 | and_2);  // AND/NOR
        default: j =    and_1 | and_2;   // AND/OR
        endcase

endmodule

The model of the chip in section 9 is written the other way, gate by gate from the datasheet's logic diagram. The testbench checks that both give the same J for every input: the table and the circuit are the same function.

9SystemVerilog model of the chip

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.

cd4048.svfile
// CD4048B: multifunction expandable 8-input gate.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (8)
// and VDD (16), are left out.
//
// The model follows the logic diagram of the TI datasheet: every input is
// inverted and XORed with Ka; each group of four goes into a NAND whose
// output is XORed with ~Kb; both groups and ~EXPAND go into a 3-input NAND,
// XORed with ~Kc.  Ka Kb Kc choose the function:
//
//   000 NOR   001 OR   010 OR/AND   011 OR/NAND
//   100 AND   101 NAND 110 AND/NOR  111 AND/OR
//
// Kd = 0 turns the output off (high impedance), so that several 4048s can
// share a bus.  Synthesizable while Kd is 1; in an FPGA, keep Kd at 1.

module cd4048
(
    output logic j,       // Pin 1:  output, 3-state
    input  logic kd,      // Pin 2:  1 = output on
    input  logic h,       // Pin 3
    input  logic g,       // Pin 4
    input  logic f,       // Pin 5
    input  logic e,       // Pin 6
    input  logic kb,      // Pin 7
                          // Pin 8:  VSS
    input  logic kc,      // Pin 9
    input  logic ka,      // Pin 10
    input  logic d,       // Pin 11
    input  logic c,       // Pin 12
    input  logic b,       // Pin 13
    input  logic a,       // Pin 14
    input  logic expand   // Pin 15: GND when not used
                          // Pin 16: VDD
);

    wire [7:0] in_x = ~ { h, g, f, e, d, c, b, a } ^ { 8 { ka } };

    wire group_1 = ~ (& in_x [3:0]) ^ ~ kb;  // A, B, C, D
    wire group_2 = ~ (& in_x [7:4]) ^ ~ kb;  // E, F, G, H

    wire inner = ~ (group_1 & group_2 & ~ expand);
    wire z     = inner ^ ~ kc;

    assign j = kd ? z : 1'bz;

endmodule

1'bz is the value of a wire that nobody drives. FPGAs have no high-impedance outputs inside, so keep Kd at 1 there.

10SystemVerilog: the chip-level design

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

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

module multifunction_gate_chips
(
    input  logic       a,
    input  logic       b,
    input  logic       c,
    input  logic       d,
    input  logic [3:0] rest,
    input  logic [2:0] k,
    output logic       j
);

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

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

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

    // U1: CD4048 multifunction expandable 8-input gate, pin 1 in column 9

    cd4048 i_u1
    (
        .j      ( j        ),  // Pin 1 -> J
        .kd     ( vdd      ),  // Pin 2 <- +5V
        .h      ( rest [3] ),  // Pin 3 <- H wire, at +5V on the breadboard
        .g      ( rest [2] ),  // Pin 4 <- G wire, at +5V on the breadboard
        .f      ( rest [1] ),  // Pin 5 <- F wire, at +5V on the breadboard
        .e      ( rest [0] ),  // Pin 6 <- E wire, at +5V on the breadboard
        .kb     ( k [1]    ),  // Pin 7 <- Kb wire, at GND on the breadboard
        .kc     ( k [2]    ),  // Pin 9 <- Kc wire, at GND on the breadboard
        .ka     ( k [0]    ),  // Pin 10 <- Ka wire, at +5V on the breadboard
        .d      ( d        ),  // Pin 11 <- button D
        .c      ( c        ),  // Pin 12 <- button C
        .b      ( b        ),  // Pin 13 <- button B
        .a      ( a        ),  // Pin 14 <- button A
        .expand ( gnd      )   // Pin 15 <- GND
    );

endmodule

11Testbench and simulation scripts

tb.sv runs both designs side by side and compares them with a reference model written a third way: it compares each group with all zeros and all ones. 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 J at the next one. It drives all 2048 combinations of A–D, E–H and Ka–Kc twice, counting up from the AND function and then in Gray code order, and prints the rows with E–H at 1 of the first pass, and any row with an error. The output below is shortened.

tb.sv191 lines · show the codefile
// Testbench for exercise BB1.
//
// Runs the generic design (multifunction_gate.sv) and the chip-level design
// (multifunction_gate_chips.sv) side by side and compares both with
// the function table of the 4048, written with comparisons.  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 2048 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       a;
    logic       b;
    logic       c;
    logic       d;
    logic [3:0] rest;
    logic [2:0] k;

    wire  j, j_chips;

    multifunction_gate i_generic
    (
        .a    ( a    ),
        .b    ( b    ),
        .c    ( c    ),
        .d    ( d    ),
        .rest ( rest ),
        .k    ( k    ),
        .j    ( j    )
    );

    multifunction_gate_chips i_chips
    (
        .a    ( a       ),
        .b    ( b       ),
        .c    ( c       ),
        .d    ( d       ),
        .rest ( rest    ),
        .k    ( k       ),
        .j    ( j_chips )
    );

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

    initial
    begin
        clk = '0;

        forever
            # 5 clk = ~ clk;
    end

    //------------------------------------------------------------------------
    // Reference model: the function table of the 4048, written with comparisons.
    // Bits, from the left: j.

    function automatic logic [0:0] expected
    (
        input logic       in_a,
        input logic       in_b,
        input logic       in_c,
        input logic       in_d,
        input logic [3:0] in_rest,
        input logic [2:0] in_k
    );
        // The two groups of four inputs, compared with all zeros and all ones

        logic [3:0] g1, g2;
        logic       y;

        g1 = { in_a, in_b, in_c, in_d };
        g2 = in_rest;

        case ({ in_k [0], in_k [1], in_k [2] })            // Ka Kb Kc, as in the datasheet
        3'b000:  y =    g1 == 4'h0 && g2 == 4'h0;          // NOR
        3'b001:  y = ! (g1 == 4'h0 && g2 == 4'h0);         // OR
        3'b010:  y =    g1 != 4'h0 && g2 != 4'h0;          // OR/AND
        3'b011:  y = ! (g1 != 4'h0 && g2 != 4'h0);         // OR/NAND
        3'b100:  y =    g1 == 4'hf && g2 == 4'hf;          // AND
        3'b101:  y = ! (g1 == 4'hf && g2 == 4'hf);         // NAND
        3'b110:  y = ! (g1 == 4'hf || g2 == 4'hf);         // AND/NOR
        3'b111:  y =    g1 == 4'hf || g2 == 4'hf;          // AND/OR
        default: y = 1'bx;
        endcase

        return y;
    endfunction

    wire [0:0] out       = { j };
    wire [0:0] out_chips = { j_chips };
    wire [0:0] out_model = expected (a, b, c, d, rest, k);

    //------------------------------------------------------------------------
    // 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 [2047: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 | 2048'b1 << { a, b, c, d, rest, k };

            // Print the first pass with E-H at 1, and every error

            if (rest == 4'hf & cycle < 2048 | out !== out_model | out_chips !== out_model)
                $display ("%5d  %b  %b  %b  %b  %b %b     %b  %s  %s",
                    cycle + 1, a, b, c, d, rest, k, j,
                    out       === out_model ? "ok     " : "WRONG  ",
                    out_chips === out_model ? "ok   "   : "WRONG");
        end

    //------------------------------------------------------------------------
    // Driving the inputs: all combinations, counting up from the AND function with
    // E-H at 1 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  A  B  C  D  E-H  Kc..Ka  J  generic  chips");

        checking <= '1;

        for (int i = 0; i < 2048; i ++)
        begin
            { k, rest, a, b, c, d } <= 11' (i) ^ 11'h1f0;
            @ (posedge clk);
        end

        for (int i = 0; i < 2048; i ++)
        begin
            { k, rest, a, b, c, d } <= 11' (i ^ (i >> 1)) ^ 11'h1f0;
            @ (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), 2048);
    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 BB1: 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 multifunction_gate.sv multifunction_gate_chips.sv cd4048.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 BB1: 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 multifunction_gate.sv multifunction_gate_chips.sv cd4048.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 BB1: 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 multifunction_gate.sv multifunction_gate_chips.sv cd4048.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  C  D  E-H  Kc..Ka  J  generic  chips
    1  0  0  0  0  1111 001     0  ok       ok   
    2  0  0  0  1  1111 001     0  ok       ok   
    3  0  0  1  0  1111 001     0  ok       ok   
    4  0  0  1  1  1111 001     0  ok       ok   
    5  0  1  0  0  1111 001     0  ok       ok   
    6  0  1  0  1  1111 001     0  ok       ok   
    7  0  1  1  0  1111 001     0  ok       ok   
    8  0  1  1  1  1111 001     0  ok       ok   
    9  1  0  0  0  1111 001     0  ok       ok   
   10  1  0  0  1  1111 001     0  ok       ok   
   11  1  0  1  0  1111 001     0  ok       ok   
   12  1  0  1  1  1111 001     0  ok       ok   
   13  1  1  0  0  1111 001     0  ok       ok   
   14  1  1  0  1  1111 001     0  ok       ok   
   15  1  1  1  0  1111 001     0  ok       ok   
   16  1  1  1  1  1111 001     1  ok       ok   
  257  0  0  0  0  1111 000     0  ok       ok   
  258  0  0  0  1  1111 000     0  ok       ok   
  259  0  0  1  0  1111 000     0  ok       ok   
  260  0  0  1  1  1111 000     0  ok       ok   
  …
tb.sv:177: $finish called at 40965000 (1ps)
PASS: 8192 checks, no errors

To see that the testbench catches mistakes, break something and run it again: change or_1 & or_2 to or_1 | or_2 for OR/AND in multifunction_gate.sv, or connect Ka and Kb the other way round in multifunction_gate_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_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 multifunction_gate.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 FPGA board has fewer inputs than the 4048, so switch 7 sets all four inputs E–H at once. Switches 3–0 are A–D, switches 6–4 are Kc, Kb and Ka, and LED 0 is J. To run the chip-level design instead, add multifunction_gate_chips.sv and cd4048.sv and change the module name in the instance.

bgm_lab/lab_top.sv100 lines · show the codefile
// Exercise BB1 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 multifunction_gate.sv. For
// the chip-level design add multifunction_gate_chips.sv and cd4048.sv
// instead, and change the module name below.
//
// Switches: sw [0] a, sw [1] b, sw [2] c, sw [3] d, sw [6:4] k. The LEDs: led
// [0] j. A board with fewer LEDs shows the first ones.
//
// Input 7 sets all four inputs E-H at once.

`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 j;

    multifunction_gate i_multifunction_gate
    (
        .a    ( sw [0]           ),
        .b    ( sw [1]           ),
        .c    ( sw [2]           ),
        .d    ( sw [3]           ),
        .k    ( sw [6:4]         ),
        .rest ( { 4 { sw [7] } } ),
        .j    ( j                )
    );

    assign led = w_led' ({ j });

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 multifunction_gate.sv.
  3. Run ./03_synthesize_for_fpga.bash and ./04_configure_fpga.bash.

Keys 0–3 are A–D, keys 4–6 are Ka, Kb and Kc, and key 7 sets E–H. The screen shows eight lamps: A–D and Ka–Kc in blue, J in green.

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

// Exercise BB1 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 multifunction_gate.sv.
//
// Keys: key [0] a, key [1] b, key [2] c, key [3] d, key [6:4] k. The LEDs:
// led [0] j. The screen shows 8 lamps in a row: A, B, C, D, Ka, Kb, Kc, J;
// inputs in blue, outputs in green.
//
// Input 7 sets all four inputs E-H at once.
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];
    wire       c = key [2];
    wire       d = key [3];
    wire [2:0] k = key [6:4];

    logic j;

    multifunction_gate i_multifunction_gate
    (
        .a    ( a                 ),
        .b    ( b                 ),
        .c    ( c                 ),
        .d    ( d                 ),
        .k    ( k                 ),
        .rest ( { 4 { key [7] } } ),
        .j    ( j                 )
    );

    assign led      = { 7'b0, j };

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

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

    wire [7:0] lamp = { j, k, d, c, b, a };

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

        for (int i = 0; i < 8; i ++)
            if (x >= 9' (20 + i * 57) & x < 9' (60 + i * 57) & y >= 116 & y < 156)
            begin
                if (i < 7)
                    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–3 are A–D, switches 4–6 Ka, Kb and Kc, and switch 7 sets E–H; segment a of the display is J.

tiny_tapeout/project.v53 lines · show the codefile
/*
 * Exercise BB1 on Tiny Tapeout: the 4048 multifunction gate, with the DIP switches as
 * inputs and the 7-segment display of the demo board as lamps.
 *
 * Add multifunction_gate.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, switch 2 is c, switch 3 is d, switches
    // 6-4 are k
    // Input 7 sets all four inputs E-H at once.

    wire j;

    multifunction_gate i_multifunction_gate (
        .a    ( ui_in [0]           ),
        .b    ( ui_in [1]           ),
        .c    ( ui_in [2]           ),
        .d    ( ui_in [3]           ),
        .k    ( ui_in [6:4]         ),
        .rest ( { 4 { ui_in [7] } } ),
        .j    ( j                   )
    );

    // 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) j.

    assign uo_out  = { 7'b0, j };

    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], 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>_multifunction_gate
  source_files:
    - "project.v"
    - "multifunction_gate.sv"

15Going further

Tasks for students

Files of this exercise

Sources

The 4048 is in the Building blocks 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 function table and the logic diagram come from the Texas Instruments datasheet for the CD4048B.