Breadboard exercises/ BB4bEnglishРусский

Exercise BB4b · building blocks · multiplexer

Multiplexer 4052: two of four

Two multiplexers of four channels in one chip, with one select: buttons B and A choose the same channel number in both, so the 4052 switches a 2-bit word.

1 chip4052 dual 4-channel multiplexer
15 + 15 wireson the board + jumper leads to the modules
2 × 4 channelschosen by B A
no clockthe output follows the inputs at once
Four multiplexer chips

1What it is and why it matters

What it does. The 4052 has two groups of four channels, X0–X3 and Y0–Y3, with common pins X COM and Y COM. The select inputs B and A form a number from 0 to 3, and in both groups the switch of that channel closes. Here the channels are wires to the rails; the LED module shows B, A, INH, X COM and Y COM.

How it works. Inside are eight analog switches and a 1-of-4 decoder that closes one switch in each group. Two outputs that change together carry a 2-bit value: with more chips of this kind a whole data bus is switched between sources.

Where it is used. A multiplexer chooses which of several signals goes on: the register a processor reads, the source of a bus, the input of an ALU. In an FPGA every lookup table is a multiplexer whose data inputs are the bits of its configuration memory. The analog switches of the 4051–4053 also route audio and sensor signals to one converter.

Why learn it.

2The key elements: select, data, output

B AINHX COM ↔X COMY COM ↔Y COM
000X01Y00
010X10Y11
100X21Y21
110X31Y30
any1—z—z

Waveforms

X3…X01101Y3…Y0011001110100B A1230123012301230INHX COMY COM
From the simulation of tb.sv in Icarus Verilog: the first 16 steps, with the data wires as on the breadboard. With INH = 1 the output is z, drawn grey. · SVG · PNG

3Parts

PartIn this circuitQtyPriceSupplier
CD4052dual 4-channel analog multiplexer1$0.45Elexp (elexp.com)
Button modulesB, A, INH; 3 from the pack of five3$0.66 / packaliexpress.us
8-LED moduleshows the selects and the outputs1$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 jumpers15 leads to the buttons and the LED module15$1.30 / packaliexpress.us

Prices from the LSSK components sheet; the 4052 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.

4052: dual 4-channel analog multiplexer

1Y02Y23Y4Y35Y16INH7VEE8VSS9B10A11X312X013X14X115X216VDD40522 × 1 of 4 switch
CD4052B. A 16-pin chip: VDD is pin 16 and VSS pin 8. · SVG · PNG

X0–X3 are pins 12, 14, 15, 11, Y0–Y3 pins 1, 5, 2, 4; X COM is pin 13 and Y COM pin 3. The selects A and B are pins 10 and 9, INH pin 6, VEE pin 7 (to GND).

PinNameDirectionFunctionIn this circuit
1Y0in/outchannel Y0: joined to its common pin when B A = 0Y0 (GND)
2Y2in/outchannel Y2: joined to its common pin when B A = 2Y2 (+5V)
3Y COMin/outcommon in/out of the Y switchY COM
4Y3in/outchannel Y3: joined to its common pin when B A = 3Y3 (GND)
5Y1in/outchannel Y1: joined to its common pin when B A = 1Y1 (+5V)
6INHinputINH: 1 opens all switchesINH
7VEEpowernegative supply of the analog switches: GND here, for signals from 0 to 5 VGND
8VSSpowerground, 0 VGND
9Binputselect bit B (weight 2)B
10Ainputselect bit A (weight 1)A
11X3in/outchannel X3: joined to its common pin when B A = 3X3 (+5V)
12X0in/outchannel X0: joined to its common pin when B A = 0X0 (+5V)
13X COMin/outcommon in/out of the X switchX COM
14X1in/outchannel X1: joined to its common pin when B A = 1X1 (GND)
15X2in/outchannel X2: joined to its common pin when B A = 2X2 (+5V)
16VDDpowersupply, +5 V (3 to 18 V allowed)+5V

5Schematic 1: the multiplexer as a block

BAINHX0X1X2X3Y0Y1Y2Y34052BAINHX0X1X2X3Y0Y1Y2Y3VEEX COMY COMdual 4-channel multiplexerBLED 1ALED 2INHLED 3X COMLED 4Y COMLED 5
The circuit with the 4052 as one block. This is what mux_4_dual.sv describes. The open circles are the wires to the rails that set the data. · SVG · PNG

6Schematic 2: connections

12345678910111213141516Y0Y2YY3Y1INHBAX3X0XX1X240522 × 1 of 4 switchBAINHX COMY COMBAINHLED module: LEDs 1-5Y1→ +5VY3→ GNDY2→ +5VY0→ GNDX3→ +5VX0→ +5VX1→ GNDX2→ +5V+5V
The same circuit with the chip, pin by pin. The boxes with an arrow are the data wires, with the rail they start on; the buttons are above, the LED module below. · SVG · PNG
NetFromToWire
Bbutton B, OUT4052 9 (B), LED module, LED 1M-F, M-M
Abutton A, OUT4052 10 (A), LED module, LED 2M-F, M-M
INHbutton INH, OUT4052 6 (INH), LED module, LED 3M-F, M-M
X0X0 wire: +5V4052 12 (X0)M-M
X1X1 wire: GND4052 14 (X1)M-M
X2X2 wire: +5V4052 15 (X2)M-M
X3X3 wire: +5V4052 11 (X3)M-M
Y0Y0 wire: GND4052 1 (Y0)M-M
Y1Y1 wire: +5V4052 5 (Y1)M-M
Y2Y2 wire: +5V4052 2 (Y2)M-M
Y3Y3 wire: GND4052 4 (Y3)M-M
X COM—4052 13 (X), LED module, LED 4M-F
Y COM—4052 3 (Y), LED module, LED 5M-F, M-M
+5V+5V4052 16 (VDD)
GNDGND4052 8 (VSS), 4052 7 (VEE)

7Schematic 3: the breadboard

−+−+1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950abcdefghij5V5VPOWER MODULE · 5V9V USB-DC4052X0X1X2X3Y0Y1Y2Y3INHY COM+OUT−B+OUT−A+OUT−INHG1B2A3INH4X COM5Y COM6788-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, the LED module below it. The wires with a tag are the data inputs: + is 1, − is 0. · SVG · PNG
BAINHX0X1X2X3Y0Y1Y2Y3X COMY COM+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 4052 turned around, notch to the right, pin 1 in hole 19e. 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. VEE, pin 7, to the bottom − rail: the switches pass logic levels between 0 and 5 V.
  5. The data wires, each from its pin to a rail, in the positions of the checklist.
  6. The signal wires of the checklist, which bring pins to the half of the board where the module leads land.
  7. With the power off, the buttons above the board and the LED module below it.
  8. Turn the power on.

Wiring checklist

·

#NetFromTo
Power (red to +, black to −) · 2 wires
1+5V19j (4052 pin 16, VDD)bottom + rail, column 19
2GND12a (4052 pin 8, VSS)top − rail, column 12
Fixed inputs: CMOS inputs must not float · 1 wire
11GND13a (4052 pin 7, VEE)top − rail, column 13
Mode wires: move them between + and − to change the mode · 8 wires
3X015j (4052 pin 12, X0)bottom + rail, column 15
4X117j (4052 pin 14, X1)bottom − rail, column 17
5X218j (4052 pin 15, X2)bottom + rail, column 18
6X314j (4052 pin 11, X3)bottom + rail, column 14
7Y019a (4052 pin 1, Y0)top − rail, column 19
8Y115a (4052 pin 5, Y1)top + rail, column 15
9Y218a (4052 pin 2, Y2)top + rail, column 18
10Y316a (4052 pin 4, Y3)top − rail, column 16
Signal wires · 4 wires
12B12g (4052 pin 9, B)11e
13A13g (4052 pin 10, A)10e
14INH14c (4052 pin 6, INH)20f
15Y COM17d (4052 pin 3, Y)21f
Modules on male-female jumpers · 15 wires
16+5Vbutton B, +top + rail, column 9
17Bbutton B, OUT11a
18GNDbutton B, −top − rail, column 11
19+5Vbutton A, +top + rail, column 14
20Abutton A, OUT10a
21GNDbutton A, −top − rail, column 15
22+5Vbutton INH, +top + rail, column 19
23INHbutton INH, OUT14a (4052 pin 6, INH)
24GNDbutton INH, −top − rail, column 21
25GNDLED module, Gbottom − rail, column 24
26BLED module, LED 112j (4052 pin 9, B)
27ALED module, LED 213j (4052 pin 10, A)
28INHLED module, LED 320j
29X COMLED module, LED 416j (4052 pin 13, X)
30Y COMLED module, LED 521j

Test it

If it does not work: if the output shows the wrong channel, check the select leads: a swapped pair gives a different but consistent order. If one channel never shows, check its data wire. If an output stays dark, check INH (GND when the button is up) and VEE at GND.

8SystemVerilog: the generic design

mux_4_dual.sv describes schematic 1 in a few lines. It is synthesizable.

mux_4_dual.svfile
// Exercise BB4b: a dual 4-channel multiplexer, like the 4052.
//
// Generic version that matches schematic 1, not tied to any chip: two
// multiplexers with one select, X and Y.  With inh = 1 both outputs are not
// driven (high impedance), as the common pins of the 4052 float.
// Synthesizable; in an FPGA keep inh at 0.

module mux_4_dual
(
    input  logic [3:0] x_ch,   // x_ch [0] is X0
    input  logic [3:0] y_ch,   // y_ch [0] is Y0
    input  logic [1:0] sel,    // B A: sel [1] is B, weight 2
    input  logic       inh,    // 1 = all switches open

    output logic       x_com,
    output logic       y_com
);

    assign x_com = inh ? 1'bz : x_ch [sel];
    assign y_com = inh ? 1'bz : y_ch [sel];

endmodule

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.

cd4052.svfile
// CD4052B: dual 4-channel analog multiplexer/demultiplexer.
//
// Ports in pin order, named as in the datasheet.  The power pins, VEE (7),
// VSS (8) and VDD (16), are left out.
//
// Digital model of two analog switches with a common select B A: it passes
// the selected X and Y channels to X COM and Y COM.  INH = 1 opens all
// switches and both commons float.  Synthesizable while INH is 0.

module cd4052
(
    input  logic y0,     // Pin 1
    input  logic y2,     // Pin 2
    output logic y_com,  // Pin 3:  Y common in/out
    input  logic y3,     // Pin 4
    input  logic y1,     // Pin 5
    input  logic inh,    // Pin 6:  1 = all switches open
                         // Pin 7:  VEE
                         // Pin 8:  VSS
    input  logic b,      // Pin 9:  select, weight 2
    input  logic a,      // Pin 10: select, weight 1
    input  logic x3,     // Pin 11
    input  logic x0,     // Pin 12
    output logic x_com,  // Pin 13: X common in/out
    input  logic x1,     // Pin 14
    input  logic x2      // Pin 15
                         // Pin 16: VDD
);

    wire [1:0] sel = { b, a };
    wire [3:0] x   = { x3, x2, x1, x0 };
    wire [3:0] y   = { y3, y2, y1, y0 };

    assign x_com = inh ? 1'bz : x [sel];
    assign y_com = inh ? 1'bz : y [sel];

endmodule

The model passes logic levels from the channels to the common pins only. The real chip is a set of switches that conduct both ways; that cannot be written as a synthesizable logic model.

10SystemVerilog: the chip-level design

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

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

module mux_4_dual_chips
(
    input  logic [3:0] x_ch,
    input  logic [3:0] y_ch,
    input  logic [1:0] sel,
    input  logic       inh,
    output logic       x_com,
    output logic       y_com
);



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

    // U1: CD4052 dual 4-channel analog multiplexer, pin 1 in column 12

    cd4052 i_u1
    (
        .y0    ( y_ch [0] ),  // Pin 1 <- Y0 wire, at GND on the breadboard
        .y2    ( y_ch [2] ),  // Pin 2 <- Y2 wire, at +5V on the breadboard
        .y_com ( y_com    ),  // Pin 3 -> Y COM
        .y3    ( y_ch [3] ),  // Pin 4 <- Y3 wire, at GND on the breadboard
        .y1    ( y_ch [1] ),  // Pin 5 <- Y1 wire, at +5V on the breadboard
        .inh   ( inh      ),  // Pin 6 <- button INH
        .b     ( sel [1]  ),  // Pin 9 <- button B
        .a     ( sel [0]  ),  // Pin 10 <- button A
        .x3    ( x_ch [3] ),  // Pin 11 <- X3 wire, at +5V on the breadboard
        .x0    ( x_ch [0] ),  // Pin 12 <- X0 wire, at +5V on the breadboard
        .x_com ( x_com    ),  // Pin 13 -> X COM
        .x1    ( x_ch [1] ),  // Pin 14 <- X1 wire, at GND on the breadboard
        .x2    ( x_ch [2] )   // Pin 15 <- X2 wire, at +5V on the breadboard
    );

endmodule

11Testbench and simulation scripts

tb.sv runs both designs side by side and compares them with a reference model. 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 every combination of the data, the selects and INH twice, counting up from the data wires 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. It compares with ===, so z must match z. The output below is shortened.

tb.sv169 lines · show the codefile
// Testbench for exercise BB4b.
//
// Runs the generic design (mux_4_dual.sv) and the chip-level design
// (mux_4_dual_chips.sv) side by side and compares both with
// the channels with the number of the select, or z while INH = 1.  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 [3:0] x_ch;
    logic [3:0] y_ch;
    logic [1:0] sel;
    logic       inh;

    wire  x_com, x_com_chips;
    wire  y_com, y_com_chips;

    mux_4_dual i_generic
    (
        .x_ch  ( x_ch  ),
        .y_ch  ( y_ch  ),
        .sel   ( sel   ),
        .inh   ( inh   ),
        .x_com ( x_com ),
        .y_com ( y_com )
    );

    mux_4_dual_chips i_chips
    (
        .x_ch  ( x_ch        ),
        .y_ch  ( y_ch        ),
        .sel   ( sel         ),
        .inh   ( inh         ),
        .x_com ( x_com_chips ),
        .y_com ( y_com_chips )
    );

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

    initial
    begin
        clk = '0;

        forever
            # 5 clk = ~ clk;
    end

    //------------------------------------------------------------------------
    // Reference model: the channels with the number of the select, or z while INH = 1.
    // Bits, from the left: x_com, y_com.

    function automatic logic [1:0] expected
    (
        input logic [3:0] in_x_ch,
        input logic [3:0] in_y_ch,
        input logic [1:0] in_sel,
        input logic       in_inh
    );
        if (in_inh)
            return 2'bzz;

        return { in_x_ch [in_sel], in_y_ch [in_sel] };
    endfunction

    wire [1:0] out       = { x_com, y_com };
    wire [1:0] out_chips = { x_com_chips, y_com_chips };
    wire [1:0] out_model = expected (x_ch, y_ch, sel, inh);

    //------------------------------------------------------------------------
    // 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 << { x_ch, y_ch, sel, inh };

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

            if (x_ch == 4'b1101 & y_ch == 4'b0110 | out !== out_model | out_chips !== out_model)
                $display ("%5d  %b    %b    %b  %b    %b      %b      %s  %s",
                    cycle + 1, x_ch, y_ch, sel, inh, x_com, y_com,
                    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  X3..X0  Y3..Y0  BA  INH  X COM  Y COM  generic  chips");

        checking <= '1;

        for (int i = 0; i < 2048; i ++)
        begin
            { x_ch, y_ch, inh, sel } <= 11' (i) ^ 11'h6b0;
            @ (posedge clk);
        end

        for (int i = 0; i < 2048; i ++)
        begin
            { x_ch, y_ch, inh, sel } <= 11' (i ^ (i >> 1)) ^ 11'h6b0;
            @ (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 BB4b: 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 mux_4_dual.sv mux_4_dual_chips.sv cd4052.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 BB4b: 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 mux_4_dual.sv mux_4_dual_chips.sv cd4052.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 BB4b: 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 mux_4_dual.sv mux_4_dual_chips.sv cd4052.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  X3..X0  Y3..Y0  BA  INH  X COM  Y COM  generic  chips
    1  1101    0110    00  0    1      0      ok       ok   
    2  1101    0110    01  0    0      1      ok       ok   
    3  1101    0110    10  0    1      1      ok       ok   
    4  1101    0110    11  0    1      0      ok       ok   
    5  1101    0110    00  1    z      z      ok       ok   
    6  1101    0110    01  1    z      z      ok       ok   
    7  1101    0110    10  1    z      z      ok       ok   
    8  1101    0110    11  1    z      z      ok       ok   
 2049  1101    0110    00  0    1      0      ok       ok   
 2050  1101    0110    01  0    0      1      ok       ok   
 2051  1101    0110    11  0    1      0      ok       ok   
 2052  1101    0110    10  0    1      1      ok       ok   
 2053  1101    0110    10  1    z      z      ok       ok   
 2054  1101    0110    11  1    z      z      ok       ok   
 2055  1101    0110    01  1    z      z      ok       ok   
 2056  1101    0110    00  1    z      z      ok       ok   
tb.sv:155: $finish called at 40965000 (1ps)
PASS: 8192 checks, no errors

To see that the testbench catches mistakes, break something and run it again: change x_ch [sel] to y_ch [sel] in mux_4_dual.sv, or swap the select inputs A and B in mux_4_dual_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 mux_4_dual.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 breadboard has wires, so the data are fixed in lab_top.sv as the wires of the breadboard: change the constants to try others. The keys are B, A; INH is held at 0, because an FPGA has no high-impedance wires inside. To run the chip-level design instead, add mux_4_dual_chips.sv and cd4052.sv and change the module name in the instance.

bgm_lab/lab_top.sv102 lines · show the codefile
// Exercise BB4b 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 mux_4_dual.sv. For the chip-level design add
// mux_4_dual_chips.sv and cd4052.sv instead, and change the module name
// below.
//
// Keys: key [1:0] sel. The LEDs: led [0] x_com, led [1] y_com. A board with
// fewer LEDs shows the first ones.
//
// The channels are fixed at X3-X0 = 1101 and Y3-Y0 = 0110, as the wires on
// the breadboard. INH is held at 0: an FPGA has no high-impedance wires
// inside.

`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 x_com;
    logic y_com;

    mux_4_dual i_mux_4_dual
    (
        .sel   ( key [1:0] ),
        .x_ch  ( 4'b1101   ),
        .y_ch  ( 4'b0110   ),
        .inh   ( 1'b0      ),
        .x_com ( x_com     ),
        .y_com ( y_com     )
    );

    assign led = w_led' ({ y_com, x_com });

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

The keys are B, A, the data are fixed as in lab_top; the screen shows the inputs in blue and the outputs 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 BB4b 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 mux_4_dual.sv.
//
// Keys: key [1:0] sel. The LEDs: led [0] x_com, led [1] y_com. The screen
// shows 4 lamps in a row: A, B, X COM, Y COM; inputs in blue, outputs in
// green.
//
// The channels are fixed at X3-X0 = 1101 and Y3-Y0 = 0110, as the wires on
// the breadboard. INH is held at 0: an FPGA has no high-impedance wires
// inside.
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 [1:0] sel = key [1:0];

    logic x_com;
    logic y_com;

    mux_4_dual i_mux_4_dual
    (
        .sel   ( sel     ),
        .x_ch  ( 4'b1101 ),
        .y_ch  ( 4'b0110 ),
        .inh   ( 1'b0    ),
        .x_com ( x_com   ),
        .y_com ( y_com   )
    );

    assign led      = { 6'b0, y_com, x_com };

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

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

    wire [3:0] lamp = { y_com, x_com, sel };

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

        for (int i = 0; i < 4; i ++)
            if (x >= 9' (124 + i * 64) & x < 9' (164 + 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.

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.

The switches are B, A; the data are fixed in project.v, INH at 0. The segments of the display show the outputs.

tiny_tapeout/project.v54 lines · show the codefile
/*
 * Exercise BB4b on Tiny Tapeout: a dual 4-channel multiplexer, with the DIP switches as
 * inputs and the 7-segment display of the demo board as lamps.
 *
 * Add mux_4_dual.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
);

    // Switches 1-0 are sel
    // The channels are fixed at X3-X0 = 1101 and Y3-Y0 = 0110, as the wires
    // on the breadboard. INH is held at 0: an FPGA has no high-impedance
    // wires inside.

    wire x_com;
    wire y_com;

    mux_4_dual i_mux_4_dual (
        .sel   ( ui_in [1:0] ),
        .x_ch  ( 4'b1101     ),
        .y_ch  ( 4'b0110     ),
        .inh   ( 1'b0        ),
        .x_com ( x_com       ),
        .y_com ( y_com       )
    );

    // 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) x_com, b (top right) y_com.

    assign uo_out  = { 6'b0, y_com, x_com };

    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:2], 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>_mux_4_dual
  source_files:
    - "project.v"
    - "mux_4_dual.sv"

15Going further

Tasks for students

Files of this exercise

Sources

The multiplexers 4051, 4052, 4053 and 4019 are 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 4052 is described in the Texas Instruments datasheet for the CD4052B.