Breadboard exercises/ BB5EnglishРусский

Exercise BB5 · building blocks · decoder

4028 BCD-to-decimal decoder

Four buttons give a 4-bit code, and exactly one of ten LEDs lights: the one whose number is the code. The 4028 turns a binary number into one wire per value, the opposite of what the buttons do.

1 chip4028 BCD-to-decimal decoder
5 + 24 wireson the board + jumper leads to the modules
10 outputsQ0–Q9, at most one of them 1
no clockthe LEDs follow the buttons at once

1What it is and why it matters

What it does. Buttons D, C, B and A give a code from 0 to 15, D the highest bit with weight 8, A the lowest with weight 1. The 4028 has ten outputs, Q0–Q9, and for codes 0–9 exactly the output with the number of the code is 1. Codes 10–15 are not decimal digits, and for them all outputs are 0. Two LED modules show the outputs: Q0–Q7 on the first, Q8 and Q9 on the second.

How it works. Each output is an AND gate that recognises one code: Q5 is 1 when D = 0, C = 1, B = 0 and A = 1. Ten such gates, each looking at the four inputs, some of them inverted, make the decoder. Exactly one of them can match a code.

Where it is used. A memory chip decodes its address to select one row of cells; a processor decodes the operation code of an instruction to choose what the datapath does; a keyboard scanner and a display driver decode which row or digit is active. In this course the 4028 also comes back as the first half of a multiplexer: in M5 and M6 its outputs select which data input reaches the output.

Why learn it.

2The key elements: one output per code

CodeDCBAOutput at 1
00000Q0
10001Q1
20010Q2
30011Q3
40100Q4
50101Q5
60110Q6
70111Q7
81000Q8
91001Q9
101010none
111011none
121100none
131101none
141110none
151111none

The 4028 can also be used as a binary-to-octal decoder: with D tied to GND, Q0–Q7 decode C B A, and Q8, Q9 stay 0.

Waveforms

D C B A1234567891011121314150Q0Q1Q2Q3Q4Q5Q6Q7Q8Q9
From the simulation of tb.sv in Icarus Verilog: the code counting from 0 to 15. One output is 1 for codes 0–9, none for 10–15. · SVG · PNG

3Parts

PartIn this circuitQtyPriceSupplier
CD4028BCD-to-decimal decoder1$0.35Elexp (elexp.com)
Button modulesD, C, B and A; 4 from the pack of five4$0.66 / packaliexpress.us
8-LED moduleQ0-Q7 on the first, Q8 and Q9 on the second2$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 wires5 wires on the board (or male-male Dupont jumpers)5$11.95 / packjameco.com
Male-female Dupont jumpers24 leads to the buttons and the LED modules24$1.30 / packaliexpress.us

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

4028: BCD-to-decimal decoder

1Q42Q23Q04Q75Q96Q57Q68VSS9Q810A11D12C13B14Q115Q316VDD4028BCD → 1 of 10
CD4028B. A 16-pin chip: VDD is pin 16 and VSS pin 8. · SVG · PNG

The inputs are A on pin 10, B on 13, C on 12 and D on 11, all on the top row. The outputs are spread over both rows in an order that looks random: Q0 is pin 3, Q1 pin 14, Q2 pin 2, Q3 pin 15, Q4 pin 1, Q5 pin 6, Q6 pin 7, Q7 pin 4, Q8 pin 9 and Q9 pin 5. Read the table below with care.

Polarity. Inputs and outputs are active high: the selected output is 1, the others 0.

PinNameDirectionFunctionIn this circuit
1Q4output1 when the code D C B A is 4, 0 otherwiseQ4
2Q2output1 when the code D C B A is 2, 0 otherwiseQ2
3Q0output1 when the code D C B A is 0, 0 otherwiseQ0
4Q7output1 when the code D C B A is 7, 0 otherwiseQ7
5Q9output1 when the code D C B A is 9, 0 otherwiseQ9
6Q5output1 when the code D C B A is 5, 0 otherwiseQ5
7Q6output1 when the code D C B A is 6, 0 otherwiseQ6
8VSSpowerground, 0 VGND
9Q8output1 when the code D C B A is 8, 0 otherwiseQ8
10Ainputcode bit A (weight 1)A
11Dinputcode bit D (weight 8)D
12Cinputcode bit C (weight 4)C
13Binputcode bit B (weight 2)B
14Q1output1 when the code D C B A is 1, 0 otherwiseQ1
15Q3output1 when the code D C B A is 3, 0 otherwiseQ3
16VDDpowersupply, +5 V (3 to 18 V allowed)+5V

5Schematic 1: the decoder as a block

DCBA4028DCBAQ0Q1Q2Q3Q4Q5Q6Q7Q8Q9BCD-to-decimal decoderQ0module 1, LED 1Q1module 1, LED 2Q2module 1, LED 3Q3module 1, LED 4Q4module 1, LED 5Q5module 1, LED 6Q6module 1, LED 7Q7module 1, LED 8Q8module 2, LED 1Q9module 2, LED 2
The circuit with the 4028 as one block. This is what decoder.sv describes. · SVG · PNG

6Schematic 2: connections

12345678910111213141516Q4Q2Q0Q7Q9Q5Q6Q8ADCBQ1Q34028BCD → 1 of 10ABCDQ0Q1Q3Q5Q6Q8Q9DCBALED module: LEDs 1-8LED module: LEDs 1-2+5V
The same circuit with the chip, pin by pin. The buttons are above, the two LED modules below. · SVG · PNG
NetFromToWire
Dbutton D, OUT4028 11 (D)M-F
Cbutton C, OUT4028 12 (C)M-F
Bbutton B, OUT4028 13 (B)M-F
Abutton A, OUT4028 10 (A)M-F
Q04028 3 (Q0)LED module, LED 1M-F
Q14028 14 (Q1)LED module, LED 2M-F, M-M
Q24028 2 (Q2)LED module, LED 3M-F
Q34028 15 (Q3)LED module, LED 4M-F, M-M
Q44028 1 (Q4)LED module, LED 5M-F
Q54028 6 (Q5)LED module, LED 6M-F
Q64028 7 (Q6)LED module, LED 7M-F
Q74028 4 (Q7)LED module, LED 8M-F
Q84028 9 (Q8)LED module, LED 1M-F, M-M
Q94028 5 (Q9)LED module, LED 2M-F
+5V+5V4028 16 (VDD)
GNDGND4028 8 (VSS)

7Schematic 3: the breadboard

−+−+1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950abcdefghij5V5VPOWER MODULE · 5V9V USB-DC4028+OUT−D+OUT−C+OUT−B+OUT−AG1Q02Q13Q24Q35Q46Q57Q68Q78-LED MODULELEDs 1-8 usedG1Q82Q93456788-LED MODULELEDs 1-2 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 four buttons hang above the board, in the order D C B A, and the two LED modules below it. · SVG · PNG
DCBAQ0Q1Q2Q3Q4Q5Q6Q7Q8Q9+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 4028 with pin 1 in hole 12f. 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. Three signal wires cross the gap: Q1 (column 14) and Q3 (column 13) go down to columns 11 and 10, Q8 (column 19) to column 20 of the bottom half, where the LED modules land. The other outputs are on the bottom row already.
  5. With the power off, the modules: the buttons above the board, the LED modules below. Connect the − of each button and G of each LED module first.
  6. Turn the power on.

Wiring checklist

·

#NetFromTo
Power (red to +, black to −) · 2 wires
1+5V12a (4028 pin 16, VDD)top + rail, column 12
2GND19j (4028 pin 8, VSS)bottom − rail, column 19
Signal wires · 3 wires
3Q114d (4028 pin 14, Q1)11f
4Q313c (4028 pin 15, Q3)10f
5Q819d (4028 pin 9, Q8)20f
Modules on male-female jumpers · 24 wires
6+5Vbutton D, +top + rail, column 11
7Dbutton D, OUT17a (4028 pin 11, D)
8GNDbutton D, −top − rail, column 14
9+5Vbutton C, +top + rail, column 17
10Cbutton C, OUT16a (4028 pin 12, C)
11GNDbutton C, −top − rail, column 19
12+5Vbutton B, +top + rail, column 22
13Bbutton B, OUT15a (4028 pin 13, B)
14GNDbutton B, −top − rail, column 24
15+5Vbutton A, +top + rail, column 27
16Abutton A, OUT18a (4028 pin 10, A)
17GNDbutton A, −top − rail, column 29
18GNDLED module, Gbottom − rail, column 8
19Q0LED module, LED 114j (4028 pin 3, Q0)
20Q1LED module, LED 211j
21Q2LED module, LED 313j (4028 pin 2, Q2)
22Q3LED module, LED 410j
23Q4LED module, LED 512j (4028 pin 1, Q4)
24Q5LED module, LED 617j (4028 pin 6, Q5)
25Q6LED module, LED 718j (4028 pin 7, Q6)
26Q7LED module, LED 815j (4028 pin 4, Q7)
27GNDLED module, Gbottom − rail, column 24
28Q8LED module, LED 120j
29Q9LED module, LED 216j (4028 pin 5, Q9)

Test it

If it does not work: if the wrong LED lights for a code, compare the LED leads with the checklist: the outputs of the 4028 are in no simple order. If two LEDs light at once, two leads share a hole. If nothing lights, check the power wires.

8SystemVerilog: the generic design

decoder.sv describes the ten AND gates as ten comparisons of the code with a constant, made by a for loop with genvar. It is synthesizable.

decoder.svfile
// Exercise BB5: a BCD-to-decimal decoder, like the 4028.
//
// Generic version that matches schematic 1, not tied to any chip: output
// q [k] is 1 when the code is k.  For codes 10-15, which are not decimal
// digits, all outputs are 0.  Synthesizable.

module decoder
(
    input  logic [3:0] code,  // D C B A: code [3] is D, weight 8
    output logic [9:0] q
);

    for (genvar k = 0; k < 10; k ++)
    begin : output_k
        assign q [k] = code == 4' (k);
    end

endmodule

Another way to write it is assign q = 10'b1 << code;, a single 1 shifted left by the code. For codes 10–15 the 1 is shifted out of the ten bits and all outputs are 0, just as on the 4028.

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.

cd4028.svfile
// CD4028B: BCD-to-decimal decoder.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (8)
// and VDD (16), are left out.  Synthesizable.
//
// The output whose number is the code D C B A is 1, all others 0; codes
// 10-15 set every output to 0.  With D = 0 it is a 1-of-8 decoder.

module cd4028
(
    output logic q4,  // Pin 1
    output logic q2,  // Pin 2
    output logic q0,  // Pin 3
    output logic q7,  // Pin 4
    output logic q9,  // Pin 5
    output logic q5,  // Pin 6
    output logic q6,  // Pin 7
                      // Pin 8:  VSS
    output logic q8,  // Pin 9
    input  logic a,   // Pin 10: weight 1
    input  logic d,   // Pin 11: weight 8
    input  logic c,   // Pin 12: weight 4
    input  logic b,   // Pin 13: weight 2
    output logic q1,  // Pin 14
    output logic q3   // Pin 15
                      // Pin 16: VDD
);

    wire [3:0] code = { d, c, b, a };

    assign q0 = code == 4'd0;
    assign q1 = code == 4'd1;
    assign q2 = code == 4'd2;
    assign q3 = code == 4'd3;
    assign q4 = code == 4'd4;
    assign q5 = code == 4'd5;
    assign q6 = code == 4'd6;
    assign q7 = code == 4'd7;
    assign q8 = code == 4'd8;
    assign q9 = code == 4'd9;

endmodule

10SystemVerilog: the chip-level design

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

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

module decoder_chips
(
    input  logic [3:0] code,
    output logic [9:0] q
);



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

    // U1: CD4028 BCD-to-decimal decoder, pin 1 in column 12

    cd4028 i_u1
    (
        .q4 ( q [4]    ),  // Pin 1 -> Q4
        .q2 ( q [2]    ),  // Pin 2 -> Q2
        .q0 ( q [0]    ),  // Pin 3 -> Q0
        .q7 ( q [7]    ),  // Pin 4 -> Q7
        .q9 ( q [9]    ),  // Pin 5 -> Q9
        .q5 ( q [5]    ),  // Pin 6 -> Q5
        .q6 ( q [6]    ),  // Pin 7 -> Q6
        .q8 ( q [8]    ),  // Pin 9 -> Q8
        .a  ( code [0] ),  // Pin 10 <- button A
        .d  ( code [3] ),  // Pin 11 <- button D
        .c  ( code [2] ),  // Pin 12 <- button C
        .b  ( code [1] ),  // Pin 13 <- button B
        .q1 ( q [1]    ),  // Pin 14 -> Q1
        .q3 ( q [3]    )   // Pin 15 -> Q3
    );

endmodule

11Testbench and simulation scripts

tb.sv runs both designs side by side and compares them with a reference model that sets the bit with the number of the code, for codes up to 9. The circuit has no clock, but the testbench has one, like the testbenches of Basics-Graphics-Music: it sets the code right after a rising edge and checks the outputs at the next one. It tries all 16 codes twice, counting up and in Gray code order, and prints PASS only if both designs match every time.

tb.sv151 lines · show the codefile
// Testbench for exercise BB5.
//
// Runs the generic design (decoder.sv) and the chip-level design
// (decoder_chips.sv) side by side and compares both with
// a one at the position given by the code, for codes 0-9.  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 16 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] code;

    wire  [9:0] q, q_chips;

    decoder i_generic
    (
        .code ( code ),
        .q    ( q    )
    );

    decoder_chips i_chips
    (
        .code ( code    ),
        .q    ( q_chips )
    );

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

    initial
    begin
        clk = '0;

        forever
            # 5 clk = ~ clk;
    end

    //------------------------------------------------------------------------
    // Reference model: a one at the position given by the code, for codes 0-9.
    // Bits, from the left: q.

    function automatic logic [9:0] expected (input logic [3:0] in_code);
        logic [9:0] y;

        y = '0;

        if (in_code <= 4'd9)
            y [in_code] = 1'b1;

        return y;
    endfunction

    wire [9:0] out       = { q };
    wire [9:0] out_chips = { q_chips };
    wire [9:0] out_model = expected (code);

    //------------------------------------------------------------------------
    // 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 [15: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 | 16'b1 << { code };

            $display ("%5d  %b  %b %s  %s",
                cycle + 1, code, q,
                out       === out_model ? "ok     " : "WRONG  ",
                out_chips === out_model ? "ok   "   : "WRONG");
        end

    //------------------------------------------------------------------------
    // Driving the inputs: all combinations, counting up, 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  DCBA  Q9..Q0  generic  chips");

        checking <= '1;

        for (int i = 0; i < 16; i ++)
        begin
            { code } <= 4' (i);
            @ (posedge clk);
        end

        for (int i = 0; i < 16; i ++)
        begin
            { code } <= 4' (i ^ (i >> 1));
            @ (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), 16);
    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 BB5: 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 decoder.sv decoder_chips.sv cd4028.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 BB5: 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 decoder.sv decoder_chips.sv cd4028.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 BB5: 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 decoder.sv decoder_chips.sv cd4028.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  DCBA  Q9..Q0  generic  chips
    1  0000  0000000001 ok       ok   
    2  0001  0000000010 ok       ok   
    3  0010  0000000100 ok       ok   
    4  0011  0000001000 ok       ok   
    5  0100  0000010000 ok       ok   
    6  0101  0000100000 ok       ok   
    7  0110  0001000000 ok       ok   
    8  0111  0010000000 ok       ok   
    9  1000  0100000000 ok       ok   
   10  1001  1000000000 ok       ok   
   11  1010  0000000000 ok       ok   
   12  1011  0000000000 ok       ok   
   13  1100  0000000000 ok       ok   
   14  1101  0000000000 ok       ok   
   15  1110  0000000000 ok       ok   
   16  1111  0000000000 ok       ok   
   17  0000  0000000001 ok       ok   
   18  0001  0000000010 ok       ok   
   19  0011  0000001000 ok       ok   
   20  0010  0000000100 ok       ok   
   21  0110  0001000000 ok       ok   
   22  0111  0010000000 ok       ok   
   23  0101  0000100000 ok       ok   
   24  0100  0000010000 ok       ok   
   25  1100  0000000000 ok       ok   
   26  1101  0000000000 ok       ok   
   27  1111  0000000000 ok       ok   
   28  1110  0000000000 ok       ok   
   29  1010  0000000000 ok       ok   
   30  1011  0000000000 ok       ok   
   31  1001  1000000000 ok       ok   
   32  1000  0100000000 ok       ok   
tb.sv:137: $finish called at 325000 (1ps)
PASS: 64 checks, no errors

To see that the testbench catches mistakes, break something and run it again: change k < 10 to k < 9 in decoder.sv, or connect the outputs Q1 and Q2 the other way round in decoder_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_03_decoder to a new directory.
  2. Replace its lab_top.sv with bgm_lab/lab_top.sv from this exercise and add decoder.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 3–0 are D C B A. A board has eight LEDs, not ten, so LEDs 7–0 show Q7–Q0, and the rightmost digit of the display shows the number of the output that is 1, blank for codes 10–15. The digit is drawn by a small table in lab_top.sv, not by the decoder. To run the chip-level design instead, add decoder_chips.sv and cd4028.sv and change the module name in the instance.

bgm_lab/lab_top.sv116 lines · show the codefile
// Exercise BB5 on an FPGA board with the Basics-Graphics-Music (BGM) labs:
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy labs/1_basics/1_03_decoder to a new directory, replace its
// lab_top.sv with this file and add decoder.sv.  For the chip-level design
// add decoder_chips.sv and cd4028.sv instead, and change the module name
// below.
//
// Keys 3-0 are the code D C B A.  LEDs 7-0 show Q7-Q0, and the rightmost
// digit of the display shows the number of the output that is 1, so Q8 and
// Q9 are seen there too.  Codes 10-15 leave the digit blank.

`include "config.svh"

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

               screen_width  = 640,
               screen_height = 480,

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

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

    // Keys, switches, LEDs

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

    // A dynamic seven-segment display

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

    // Graphics

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

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

    // Microphone, sound output and UART

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

    input                        uart_rx,
    output                       uart_tx,

    // General-purpose Input/Output

    inout        [w_gpio  - 1:0] gpio
);

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

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

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

    logic [9:0] q;

    decoder i_decoder
    (
        .code ( 4' (key) ),
        .q    ( q        )
    );

    assign led = w_led' (q);

    //------------------------------------------------------------------------
    // The digit whose output is 1, on a 7-segment display: a is the top
    // segment, g the middle one.  No output at 1 (codes 10-15): blank.

    logic [6:0] abcdefg;

    always_comb
        case (q)
        10'b00_0000_0001: abcdefg = 7'b111_1110;  // 0
        10'b00_0000_0010: abcdefg = 7'b011_0000;  // 1
        10'b00_0000_0100: abcdefg = 7'b110_1101;  // 2
        10'b00_0000_1000: abcdefg = 7'b111_1001;  // 3
        10'b00_0001_0000: abcdefg = 7'b011_0011;  // 4
        10'b00_0010_0000: abcdefg = 7'b101_1011;  // 5
        10'b00_0100_0000: abcdefg = 7'b101_1111;  // 6
        10'b00_1000_0000: abcdefg = 7'b111_0000;  // 7
        10'b01_0000_0000: abcdefg = 7'b111_1111;  // 8
        10'b10_0000_0000: abcdefg = 7'b111_1011;  // 9
        default:          abcdefg = 7'b000_0000;
        endcase

    assign abcdefgh = { abcdefg, 1'b0 };
    assign digit    = w_digit' (1);

endmodule

13On an FPGA board: hackathon_top in BGM

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

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

Keys 3–0 are D C B A. The screen shows ten lamps, Q0 on the left, like the two LED modules; the LEDs show Q7–Q0 and the rightmost digit the number.

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

// Exercise BB5 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 decoder.sv.
//
// Keys 3-0 are the code D C B A.  The LEDs show Q7-Q0, the rightmost digit
// the number of the output that is 1, and the screen ten lamps, Q0 on the
// left: like the two LED modules on the breadboard.

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

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

    // A dynamic seven-segment display

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

    // LCD screen interface

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

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

    inout  logic [3:0] gpio
);

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

    logic [9:0] q;

    decoder i_decoder
    (
        .code ( key [3:0] ),
        .q    ( q         )
    );

    assign led = q [7:0];

    //------------------------------------------------------------------------
    // The digit whose output is 1, on a 7-segment display: a is the top
    // segment, g the middle one.  No output at 1 (codes 10-15): blank.

    logic [6:0] abcdefg;

    always_comb
        case (q)
        10'b00_0000_0001: abcdefg = 7'b111_1110;  // 0
        10'b00_0000_0010: abcdefg = 7'b011_0000;  // 1
        10'b00_0000_0100: abcdefg = 7'b110_1101;  // 2
        10'b00_0000_1000: abcdefg = 7'b111_1001;  // 3
        10'b00_0001_0000: abcdefg = 7'b011_0011;  // 4
        10'b00_0010_0000: abcdefg = 7'b101_1011;  // 5
        10'b00_0100_0000: abcdefg = 7'b101_1111;  // 6
        10'b00_1000_0000: abcdefg = 7'b111_0000;  // 7
        10'b01_0000_0000: abcdefg = 7'b111_1111;  // 8
        10'b10_0000_0000: abcdefg = 7'b111_1011;  // 9
        default:          abcdefg = 7'b000_0000;
        endcase

    assign abcdefgh = { abcdefg, 1'b0 };
    assign digit    = 8'b0000_0001;

    //------------------------------------------------------------------------
    // Ten square lamps on the 480 x 272 screen, 30 pixels wide, 44 apart,
    // Q0 on the left.  Bright green when 1, dim when 0.

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

        for (int i = 0; i < 10; i ++)
            if (x >= 9' (27 + i * 44) & x < 9' (57 + i * 44) & y >= 121 & y < 151)
                green = q [i] ? 63 : 12;
    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 3–0 are D C B A. Ten outputs do not fit on eight segments, so the display shows the number of the output that is 1 as a digit, blank for codes 10–15.

tiny_tapeout/project.v67 lines · show the codefile
/*
 * Exercise BB5 on Tiny Tapeout: a BCD-to-decimal decoder like the 4028, with
 * the DIP switches as the code and the 7-segment display of the demo board
 * showing the number of the output that is 1.
 *
 * Add decoder.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 3-0 are the code D C B A

    wire [9:0] q;

    decoder i_decoder (
        .code ( ui_in [3:0] ),
        .q    ( q           )
    );

    // The digit whose output is 1, on the 7-segment display: a is the top
    // segment, g the middle one.  No output at 1 (codes 10-15): blank.

    function [6:0] digit_of (input [9:0] one_hot);
        case (one_hot)
        10'b00_0000_0001: digit_of = 7'b111_1110;  // 0
        10'b00_0000_0010: digit_of = 7'b011_0000;  // 1
        10'b00_0000_0100: digit_of = 7'b110_1101;  // 2
        10'b00_0000_1000: digit_of = 7'b111_1001;  // 3
        10'b00_0001_0000: digit_of = 7'b011_0011;  // 4
        10'b00_0010_0000: digit_of = 7'b101_1011;  // 5
        10'b00_0100_0000: digit_of = 7'b101_1111;  // 6
        10'b00_1000_0000: digit_of = 7'b111_0000;  // 7
        10'b01_0000_0000: digit_of = 7'b111_1111;  // 8
        10'b10_0000_0000: digit_of = 7'b111_1011;  // 9
        default:          digit_of = 7'b000_0000;
        endcase
    endfunction

    wire [6:0] abcdefg = digit_of (q);

    // uo_out [0] is segment a, ..., uo_out [6] is g, uo_out [7] is the dot

    assign uo_out  = { 1'b0, abcdefg [0], abcdefg [1], abcdefg [2], abcdefg [3],
                             abcdefg [4], abcdefg [5], abcdefg [6] };

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

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

    wire _unused = & { ena, clk, rst_n, ui_in [7:4], 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>_decoder
  source_files:
    - "project.v"
    - "decoder.sv"

15Going further

Tasks for students

Files of this exercise

Sources

The 4028 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, where the decoder is later used to build multiplexers. The chip is described in the Texas Instruments datasheet for the CD4028B.