Breadboard exercises/ B7EnglishРусский

Exercise B7 · basics · display

Seven-segment display and the 4511 decoder

First you light the segments of a display one by one with a wire from +5 V and find out which pin is which. Then a 4511 does it for you: four buttons give a code from 0 to 15, and the chip lights the segments that draw the digit, through seven resistors.

1 chip + 1 display4511 decoder, common-cathode digit
13 + 12 wireson the board + jumper leads to the buttons
7 resistors560 Ω, one per segment
16 codes0–9 shown, 10–15 blank

1What it is and why it matters

What it does. A seven-segment display draws a digit with seven bars, a to g, and has a decimal point. In step 1 you power each bar by hand and learn the pins. In step 2 the 4511 turns a 4-bit binary code, given by four buttons D, C, B and A with weights 8, 4, 2 and 1, into the seven signals that draw that digit. This is the fifth exercise of the Basics list in “An improved way of teaching school kids digital electronics”: “Explore a common-cathode single-digit seven-segment display and drive it with the 4511 chip”; lesson 1.2 of the Habr article describes both steps.

How it works. Each segment is an LED, and in a common-cathode display the cathodes, the − ends, of all of them are joined inside and come out on pins 3 and 8. With those pins at GND, a segment lights when its own pin gets +5 V through a resistor. The 4511 has one output per segment; its decoder knows which segments each digit needs: 1 is b and c, 8 is all seven.

Where it is used. Every clock, meter, scale and counter display works this way, and so do the digits on FPGA boards and on the Tiny Tapeout demo board. More generally, a decoder that turns a code into one signal per output is everywhere in chips: the instruction decoder of a processor turns the bits of an instruction into the control signals for each unit, and an address decoder turns an address into the select line of one memory chip.

Why learn it.

2The key element: a decoder

00000100012001030011401005010160110701118100091001101010111011121100131101141110151111
What the 4511 shows for each code. The chip draws 6 without the top segment and 9 without the bottom one, and leaves the display blank for codes 10–15. · SVG · PNG

The truth table of the 4511

One row per code: 1 means the segment is lit. This is the table seven_segment.sv describes and the testbench checks.

codeD C B Aabcdefg
00 0 0 011111100
10 0 0 101100001
20 0 1 011011012
30 0 1 111110013
40 1 0 001100114
50 1 0 110110115
60 1 1 000111116
70 1 1 111100007
81 0 0 011111118
91 0 0 111100119
101 0 1 00000000blank
111 0 1 10000000blank
121 1 0 00000000blank
131 1 0 10000000blank
141 1 1 00000000blank
151 1 1 10000000blank

The control inputs

Three more inputs of the 4511 change what the table says. In this exercise they are fixed: LT and BI at +5V, LE at GND, which is the third row below.

LTBILESegments
0anyanyall lit
10anyall off
110from the code at the inputs
111from the code held when LE rose

Waveforms

code0123456789101112131415abcdefg
From the simulation of tb.sv in Icarus Verilog. The testbench steps the code from 0 to 15, one per clock; each row shows when a segment is lit. From code 10 on, all segments are off. · SVG · PNG

3Parts

PartIn this circuitQtyPriceSupplier
CD4511BCD-to-7-segment latch, decoder and driver1$0.65Elexp (elexp.com)
7-segment display, common cathodeone digit, 0.56 inch, pins in two rows 0.6 inch apart1$0.90elexp.com
Resistor, 560 Ω, ½ Wone per segment; step 1 needs one more7$0.04elexp.com
Button modulesthe BCD code D C B A; four modules from the pack of five4$0.66 / packaliexpress.us
Breadboard, 830 points1$3.00amazon.com
Breadboard power module5 V on the rails1$1.00aliexpress.us
USB-to-DC cable, 9 Vpowers the module from a USB charger1$1.17aliexpress.us
Male-male Dupont jumpers13 wires on the board13$1.30 / packaliexpress.us
Male-female Dupont jumpers12 leads to the buttons12$1.30 / packaliexpress.us

Prices from the LSSK components sheet; all of these parts are in the Basics kit. The board wires are male-male Dupont jumpers from the Basics kit.

The display needs resistors; the LEDs of earlier exercises did not. The LED module and the 5 V LEDs have resistors built in, a display does not. Without a resistor a lit segment would draw far too much current. With 560 Ω a segment takes a few milliamps: bright enough, and safe for the 4511, whose outputs can give up to 25 mA. The ½ W resistors of the kit have thick leads that hold well in the breadboard.

4The chip and the display, pin by pin

The 4511 is CMOS 4000B series: it works from 3 to 18 V, here from the 5 V of the power module. Its inputs are CMOS: every one must be connected, here to the buttons or to the rails. Its seven outputs are stronger than ordinary CMOS outputs, made to drive display segments. The drawings show the parts from above, notch on the left, pin 1 at the bottom left, pins numbered counter-clockwise. Blue arrows are inputs, orange arrows are outputs.

4511: BCD-to-7-segment latch, decoder and driver

1B2C3LT4BI5LE6D7A8VSS9e10d11c12b13a14g15f16VDD4511BCD → 7 segments
CD4511B. The inputs are along the bottom, the seven segment outputs along the top. · SVG · PNG

Polarity. A, B, C and D are the code, A the lowest bit. The segment outputs are active high: 1 lights the segment. ~LT (lamp test) and ~BI (blanking) are active low: they act at 0, so here they are held at 1. LE (latch enable) is active high: at 0 the decoder follows the inputs.

On the breadboard the 4511 sits turned around, notch on the right, so that its outputs are on the bottom row, next to the bottom pins of the display, and its inputs face the buttons above the board.

PinNameDirectionFunctionIn this circuit
1BinputBCD input, bit 1 (weight 2)B
2CinputBCD input, bit 2 (weight 4)C
3LTinputlamp test: 0 lights all segments. Active low+5V
4BIinputblanking: 0 turns all segments off. Active low+5V
5LEinputlatch enable: 0 = follow the inputs, 1 = hold the codeGND
6DinputBCD input, bit 3 (weight 8)D
7AinputBCD input, bit 0 (weight 1)A
8VSSpowerground, 0 VGND
9eoutputsegment e (bottom left); 1 = lit; drives up to 25 mA through a resistore
10doutputsegment d (bottom); 1 = lit; drives up to 25 mA through a resistord
11coutputsegment c (bottom right); 1 = lit; drives up to 25 mA through a resistorc
12boutputsegment b (top right); 1 = lit; drives up to 25 mA through a resistorb
13aoutputsegment a (top); 1 = lit; drives up to 25 mA through a resistora
14goutputsegment g (middle); 1 = lit; drives up to 25 mA through a resistorg
15foutputsegment f (top left); 1 = lit; drives up to 25 mA through a resistorf
16VDDpowersupply, +5 V (3 to 18 V allowed)+5V

Common-cathode display

abcdefgDP1e2d3CC4c5DP6b7a8CC9f10gcommon cathode:pins 3 and 8 to GND
A single-digit common-cathode display seen from above, decimal point at the bottom right. Pins 1–5 along the bottom, 6–10 along the top; pins 3 and 8 are the common cathode. · SVG · PNG

This is the usual pinout of a single 0.56-inch digit with ten pins in two rows 0.6 inch apart. Displays differ, so check yours in step 1 before you build step 2: touch each pin with the probe wire and write down which bar lights.

PinNameSegment
1ebottom left
2dbottom
3CCcommon cathode, to GND
4cbottom right
5DPdecimal point
6btop right
7atop
8CCcommon cathode, joined to pin 3 inside
9ftop left
10gmiddle

5Schematic 1: decoder, resistors, display

Dweight 8Cweight 4Bweight 2Aweight 1DECODERBCD → 7 segmentslike the 4511: 10-15 blankthe displayabcdefg7 × 560 Ωabcdefgcommon cathodecode 5 = 0101: a, c, d, f and g lit
The circuit without the chip: four buttons give the code, a decoder computes the seven segments, and each segment gets its own resistor. This is what seven_segment.sv describes; the resistors and the display are outside the logic. · SVG · PNG

The decoder is combinational: sixteen rows of a truth table, no clock and no memory, the same kind of circuit as the gates of exercise B1, only bigger. Inside the 4511 it is a few dozen gates; in SystemVerilog it is a case statement.

6Schematic 2: connections of the chip

12345678910111213141516BCLTBILEDAedcbagf4511BCD → 7 segmentse1d2CC3c4DP5b6a7CC8f9g10abcdefgABCDDCBA+5V
The same circuit as a chip and a display, pin by pin. The 4511 is drawn turned around, as it sits on the breadboard, notch on the right. Each segment pin of the display has its resistor drawn on it; the boxes at the top are the buttons. · SVG · PNG

Every connection of the circuit, net by net. A segment has two nets: a from the 4511 to its resistor, and a′ from the resistor to the display pin. seven_segment_chips.sv in section 10 is written from the same list.

NetFromToWire
Dbutton D, OUT4511 6 (D)M-F
Cbutton C, OUT4511 2 (C)M-F
Bbutton B, OUT4511 1 (B)M-F
Abutton A, OUT4511 7 (A)M-F
a4511 13 (a)RaM-M
b4511 12 (b)RbM-M
c4511 11 (c)RcM-M (loose jumper)
d4511 10 (d)RdM-M
e4511 9 (e)ReM-M
f4511 15 (f)RfM-M
g4511 14 (g)RgM-M
a′—Ra, 7 (a)
b′—Rb, 6 (b)
c′—Rc, 4 (c)
d′—Rd, 2 (d)
e′—Re, 1 (e)
f′—Rf, 9 (f)
g′—Rg, 10 (g)
+5V+5V4511 16 (VDD), 4511 4 (BI), 4511 3 (LT)
GNDGND4511 8 (VSS), 4511 5 (LE), 3 (CC)
not connected 5 (DP), 8 (CC)

7Schematic 3: the breadboard, in two steps

Step 1: explore the display

−+−+12345678910111213141516171819202122232425262728293031323334abcdefghij5V5VPOWER MODULE · 5V9V USB-DC+5V
The display alone, its pins in rows d and h. One resistor goes from the common cathode, pin 3, to a free column, and a black wire from there to the − rail. The red probe wire comes from the + rail; here it touches pin 7, and segment a lights. · SVG · PNG
  1. Insert the display across the gap with its pins in rows d and h, decimal point at the bottom right.
  2. Put a 560 Ω resistor from the column of pin 3 to a free column, and a black wire from that column to the bottom − rail.
  3. Plug one end of a red wire into the top + rail and touch the other end to the holes above and below the display, one pin column at a time. Write down which bar lights for which pin. Pins 3 and 8 light nothing.
  4. Touch two segment pins at once: both bars light, but dimmer, because they share the one resistor. That is why step 2 gives each segment its own.

Step 2: the 4511 drives the display

−+−+12345678910111213141516171819202122232425262728293031323334353637383940abcdefghij5V5VPOWER MODULE · 5V9V USB-DC4511abcdeg+OUT−D · 8+OUT−C · 4+OUT−B · 2+OUT−A · 1
Every wire and resistor in its hole. Column numbers are printed along the top; rows a–e are above the gap, f–j below it. The 4511 is turned around, notch on the right. The buttons hang above the board. Each segment has a resistor next to the display: five on the left, two on the right. The wire for segment c is drawn as a loose jumper, because it has to cross over the display. The board goes on to column 63 on the right. · SVG · PNG
DCBAabcdefga′b′c′d′e′f′g′+5VGND
  1. Do the getting-started steps first if you have not.
  2. Insert the 4511 across the gap with its notch on the right: pin 1 is then at the top right, in hole 15e, and pin 8 at the top left, in 8e. Insert the display with pin 1 in 23h and pin 10 in 23d.
  3. Power: VDD (pin 16, bottom right, column 15) to the bottom + rail, which is the outer one, and VSS (pin 8, top left, column 8) to the top − rail, also the outer one.
  4. The fixed inputs: ~LT and ~BI (pins 3 and 4) to the top + rail, LE (pin 5) to the top − rail, and the common cathode (pin 3 of the display) to the bottom − rail.
  5. The seven resistors, as in the checklist: each from a free column to the column of a display pin.
  6. The seven segment wires from the outputs of the 4511 to the free ends of the resistors.
  7. With the power off, the four buttons above the board. Connect their − pins first.
  8. Turn the power on.

Wiring checklist

·

#NetFromTo
Power (red to +, black to −) · 2 wires
1+5V15j (4511 pin 16, VDD)bottom + rail, column 15
2GND8a (4511 pin 8, VSS)top − rail, column 8
Fixed inputs: CMOS inputs must not float · 4 wires
3GND11a (4511 pin 5, LE)top − rail, column 11
4+5V12a (4511 pin 4, BI)top + rail, column 12
5+5V13a (4511 pin 3, LT)top + rail, column 13
6GND25j (display pin 3, CC)bottom − rail, column 25
Resistors, 560 Ω (not wires: put each resistor in these two holes) · 7 resistors
Rg560 Ω23b19b
Rf560 Ω24a20a
Ra560 Ω26c21c
Re560 Ω23j19j
Rd560 Ω24i20i
Rb560 Ω27a31a
Rc560 Ω26j30j
Signal wires · 7 wires
7a12h (4511 pin 13, a)21d (Ra)
8b11j (4511 pin 12, b)31e (Rb)
9c (loose jumper)10h (4511 pin 11, c)30h (Rc)
10d9g (4511 pin 10, d)20f (Rd)
11e8g (4511 pin 9, e)19g (Re)
12f14i (4511 pin 15, f)20c (Rf)
13g13i (4511 pin 14, g)19c (Rg)
Modules on male-female jumpers · 12 wires
14+5Vbutton D, +top + rail, column 5
15Dbutton D, OUT10a (4511 pin 6, D)
16GNDbutton D, −top − rail, column 6
17+5Vbutton C, +top + rail, column 10
18Cbutton C, OUT14a (4511 pin 2, C)
19GNDbutton C, −top − rail, column 12
20+5Vbutton B, +top + rail, column 16
21Bbutton B, OUT15a (4511 pin 1, B)
22GNDbutton B, −top − rail, column 18
23+5Vbutton A, +top + rail, column 22
24Abutton A, OUT9a (4511 pin 7, A)
25GNDbutton A, −top − rail, column 24

Test it

If it does not work: if one bar never lights, follow its path from the 4511 output through the resistor to the display pin. If the digit is all segments at once, ~LT (pin 3) is at 0. If it is always dark, check ~BI (pin 4) at +5V and the common cathode at GND. Wrong digits usually mean two segment wires are swapped; compare with the table in section 2. If the 4511 gets warm, a segment output is shorted to GND: a resistor is missing.

8SystemVerilog: the generic design

seven_segment.sv describes the decoder of schematic 1 as a case statement: the truth table of section 2, row by row. It is synthesizable: synthesis turns the table into gates or lookup tables.

seven_segment.svfile
// Exercise B7: a BCD-to-7-segment decoder for a common-cathode display.
//
// Generic version that matches schematic 1: a decoder written as a table,
// not tied to any chip.  It draws the digits like the 4511: 6 without the
// top segment, 9 without the bottom one, and codes 10-15 blank the display.
// Synthesizable.

module seven_segment
(
    input  logic [3:0] bcd,      // The code: bcd [3] is D (weight 8), bcd [0] is A (weight 1)
    output logic [6:0] abcdefg   // 1 = segment lit: abcdefg [6] is a, abcdefg [0] is g
);

    //   --a--
    //  |     |
    //  f     b
    //  |     |
    //   --g--
    //  |     |
    //  e     c
    //  |     |
    //   --d--

    always_comb
        case (bcd)
        4'd0:    abcdefg = 7'b111_1110;
        4'd1:    abcdefg = 7'b011_0000;
        4'd2:    abcdefg = 7'b110_1101;
        4'd3:    abcdefg = 7'b111_1001;
        4'd4:    abcdefg = 7'b011_0011;
        4'd5:    abcdefg = 7'b101_1011;
        4'd6:    abcdefg = 7'b001_1111;
        4'd7:    abcdefg = 7'b111_0000;
        4'd8:    abcdefg = 7'b111_1111;
        4'd9:    abcdefg = 7'b111_0011;
        default: abcdefg = 7'b000_0000;
        endcase

endmodule

The default row covers codes 10–15 and keeps the logic combinational: without it, an always_comb block that does not assign abcdefg in every case would describe a latch.

9SystemVerilog model of the chip

One module with ports named as in the datasheet and the pin number of each port in a comment. The inputs A–D are called bcd_a–bcd_d and the outputs seg_a–seg_g, because SystemVerilog names are case-sensitive and a and A side by side would be confusing.

cd4511.svfile
// CD4511B: BCD-to-7-segment latch, decoder and driver.
//
// Ports in pin order, named as in the datasheet: BCD inputs A-D (A is the
// lowest bit), segment outputs a-g.  The power pins, VSS (8) and VDD (16),
// are left out.  Synthesizable; LATCH ENABLE makes a latch, which FPGA
// tools accept but warn about.
//
// The outputs drive a common-cathode display through resistors: 1 lights
// the segment.  Codes 10 to 15 blank the display.  The chip draws 6 without
// the top segment and 9 without the bottom one.
//
// LAMP TEST (active low) lights all segments; BLANKING (active low) turns
// them all off; LAMP TEST wins.  LATCH ENABLE: 0 = the decoder follows the
// inputs, 1 = it keeps the code it had when LATCH ENABLE rose.

module cd4511
(
    input  logic bcd_b,         // Pin 1
    input  logic bcd_c,         // Pin 2
    input  logic lamp_test_n,   // Pin 3:  0 = all segments on
    input  logic blank_n,       // Pin 4:  0 = all segments off
    input  logic latch_enable,  // Pin 5:  1 = hold the code
    input  logic bcd_d,         // Pin 6
    input  logic bcd_a,         // Pin 7
                                // Pin 8:  VSS
    output logic seg_e,         // Pin 9
    output logic seg_d,         // Pin 10
    output logic seg_c,         // Pin 11
    output logic seg_b,         // Pin 12
    output logic seg_a,         // Pin 13
    output logic seg_g,         // Pin 14
    output logic seg_f          // Pin 15
                                // Pin 16: VDD
);

    logic [3:0] code;

    // This is a latch, but Verilator 5 does not see it and warns
    // verilator lint_off NOLATCH

    always_latch
        if (~ latch_enable)
            code = { bcd_d, bcd_c, bcd_b, bcd_a };

    logic [6:0] abcdefg;

    always_comb
        if (~ lamp_test_n)
            abcdefg = 7'b111_1111;
        else if (~ blank_n)
            abcdefg = 7'b000_0000;
        else
            case (code)
            4'd0:    abcdefg = 7'b111_1110;
            4'd1:    abcdefg = 7'b011_0000;
            4'd2:    abcdefg = 7'b110_1101;
            4'd3:    abcdefg = 7'b111_1001;
            4'd4:    abcdefg = 7'b011_0011;
            4'd5:    abcdefg = 7'b101_1011;
            4'd6:    abcdefg = 7'b001_1111;  // No top segment
            4'd7:    abcdefg = 7'b111_0000;
            4'd8:    abcdefg = 7'b111_1111;
            4'd9:    abcdefg = 7'b111_0011;  // No bottom segment
            default: abcdefg = 7'b000_0000;  // 10-15: blank
            endcase

    assign { seg_a, seg_b, seg_c, seg_d, seg_e, seg_f, seg_g } = abcdefg;

endmodule

LATCH ENABLE makes a latch: while LE is 1 the decoder keeps the code it had when LE rose. The model describes it with always_latch; FPGA tools accept latches but warn about them, and here LE is tied to 0, so the latch is always open.

10SystemVerilog: the chip-level design

seven_segment_chips.sv connects the chip model exactly as schematic 2 and the breadboard connect the chip, with the same ports as seven_segment.sv. The display and its resistors are not in the design: its outputs are the outputs of the 4511. 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.

seven_segment_chips.svfile
// Exercise B7, chip-level version: the chip and wires of schematic 2 and
// of the breadboard.  Same ports as seven_segment.sv.  The display and its
// resistors are not in the design: its outputs are the outputs of the 4511.
//
// Generated by tools/bb_lib.py from the checked breadboard wire list;
// change the layout in tools/bb_b7.py, not this file.  Synthesizable.

module seven_segment_chips
(
    input  logic [3:0] bcd,
    output logic [6:0] abcdefg
);

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

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

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

    // U1: CD4511 BCD-to-7-segment latch, decoder and driver, pin 1 in column 8

    cd4511 i_u1
    (
        .bcd_b        ( bcd [1]     ),  // Pin 1 <- button B
        .bcd_c        ( bcd [2]     ),  // Pin 2 <- button C
        .lamp_test_n  ( vdd         ),  // Pin 3 <- +5V
        .blank_n      ( vdd         ),  // Pin 4 <- +5V
        .latch_enable ( gnd         ),  // Pin 5 <- GND
        .bcd_d        ( bcd [3]     ),  // Pin 6 <- button D
        .bcd_a        ( bcd [0]     ),  // Pin 7 <- button A
        .seg_e        ( abcdefg [2] ),  // Pin 9 -> e
        .seg_d        ( abcdefg [3] ),  // Pin 10 -> d
        .seg_c        ( abcdefg [4] ),  // Pin 11 -> c
        .seg_b        ( abcdefg [5] ),  // Pin 12 -> b
        .seg_a        ( abcdefg [6] ),  // Pin 13 -> a
        .seg_g        ( abcdefg [0] ),  // Pin 14 -> g
        .seg_f        ( abcdefg [1] )   // Pin 15 -> f
    );

endmodule

11Testbench and simulation scripts

tb.sv runs both designs side by side and compares them with the truth table of the 4511 copied from the datasheet, for all sixteen codes. The decoder 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 segments at the next rising edge. The trace shows the digit the segments draw.

tb.sv159 lines · show the codefile
// Testbench for exercise B7.
//
// Runs the generic design (seven_segment.sv) and the chip-level design
// (seven_segment_chips.sv) side by side and compares both with the truth
// table of the 4511 from the datasheet, for all sixteen codes.  Works with
// Icarus Verilog, Verilator (--binary) and Questa.
//
// The decoder 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 sets the code after one edge and checks the segments at the next.

// Time units.  The design files have none: Yosys does not accept timeunit
// and timeprecision, and the Tiny Tapeout template sets `timescale 1ns / 1ps
// in its own testbench.  This line sets the same units here and for the
// design files compiled after it, so tb.sv comes first in the file list.

`timescale 1ns / 1ps

module tb;

    logic       clk;
    logic [3:0] bcd;

    wire  [6:0] abcdefg, abcdefg_chips;

    seven_segment i_generic
    (
        .bcd     ( bcd     ),
        .abcdefg ( abcdefg )
    );

    seven_segment_chips i_chips
    (
        .bcd     ( bcd           ),
        .abcdefg ( abcdefg_chips )
    );

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

    initial
    begin
        clk = '0;

        forever
            # 5 clk = ~ clk;
    end

    //------------------------------------------------------------------------
    // Reference model: the truth table of the CD4511B datasheet, segments
    // a b c d e f g, with LAMP TEST and BLANKING at 1 and LATCH ENABLE at 0

    function automatic logic [6:0] expected (input logic [3:0] code);
        case (code)
        4'd0:    return 7'b111_1110;
        4'd1:    return 7'b011_0000;
        4'd2:    return 7'b110_1101;
        4'd3:    return 7'b111_1001;
        4'd4:    return 7'b011_0011;
        4'd5:    return 7'b101_1011;
        4'd6:    return 7'b001_1111;
        4'd7:    return 7'b111_0000;
        4'd8:    return 7'b111_1111;
        4'd9:    return 7'b111_0011;
        default: return 7'b000_0000;
        endcase
    endfunction

    // The digit as text, from the segments, for the trace

    function automatic string shown (input logic [6:0] s);
        case (s)
        7'b111_1110: return "0";
        7'b011_0000: return "1";
        7'b110_1101: return "2";
        7'b111_1001: return "3";
        7'b011_0011: return "4";
        7'b101_1011: return "5";
        7'b001_1111: return "6";
        7'b111_0000: return "7";
        7'b111_1111: return "8";
        7'b111_0011: return "9";
        7'b000_0000: return " ";
        default:     return "?";
        endcase
    endfunction

    //------------------------------------------------------------------------
    // Checking at every rising clock edge: the code still holds the value
    // the stimulus set at the previous edge, and the segments have settled.

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

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

    int n_checks = 0;
    int n_errors = 0;

    logic [15:0] codes_seen = '0;

    always @ (posedge clk)
        if (checking & ~ done)
        begin
            n_checks   <= n_checks + 2;
            n_errors   <= n_errors + (abcdefg       === expected (bcd) ? 0 : 1)
                                   + (abcdefg_chips === expected (bcd) ? 0 : 1);
            codes_seen <= codes_seen | 16'b1 << bcd;

            $display ("%2d   %b    %b   %s     %s  %s",
                bcd, bcd, abcdefg, shown (abcdefg),
                abcdefg       === expected (bcd) ? "ok     " : "WRONG  ",
                abcdefg_chips === expected (bcd) ? "ok   "   : "WRONG");
        end

    //------------------------------------------------------------------------
    // Driving the code: 0 to 15, as with the four buttons D C B A

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

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

        $display ("code DCBA  abcdefg  digit  generic  chips");

        checking <= '1;

        for (int i = 0; i < 16; i ++)
        begin
            bcd <= 4' (i);
            @ (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 && codes_seen == 16'hffff)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, codes seen %b", n_errors, n_checks, codes_seen);
    end

endmodule

Each script compiles the files, runs the simulation, writes a log and the waveform tb.vcd, and exits with an error unless the test passes. Run them from any directory: ./run_icarus.bash, ./run_verilator.bash or ./run_questa.bash; ./clean.bash removes what they make. The waveform opens in GTKWave or Surfer.

run_icarus.bash22 lines · show the codefile
#!/usr/bin/env bash

# Exercise B7: 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 seven_segment.sv seven_segment_chips.sv cd4511.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 B7: 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 seven_segment.sv seven_segment_chips.sv cd4511.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 B7: 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 seven_segment.sv seven_segment_chips.sv cd4511.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.
code DCBA  abcdefg  digit  generic  chips
 0   0000    1111110   0     ok       ok   
 1   0001    0110000   1     ok       ok   
 2   0010    1101101   2     ok       ok   
 3   0011    1111001   3     ok       ok   
 4   0100    0110011   4     ok       ok   
 5   0101    1011011   5     ok       ok   
 6   0110    0011111   6     ok       ok   
 7   0111    1110000   7     ok       ok   
 8   1000    1111111   8     ok       ok   
 9   1001    1110011   9     ok       ok   
10   1010    0000000         ok       ok   
11   1011    0000000         ok       ok   
12   1100    0000000         ok       ok   
13   1101    0000000         ok       ok   
14   1110    0000000         ok       ok   
15   1111    0000000         ok       ok   
tb.sv:146: $finish called at 165000 (1ps)
PASS: 32 checks, no errors

To see that the testbench catches mistakes, break something and run it again: give 6 its top segment in seven_segment.sv (7'b101_1111), or swap two segment outputs in seven_segment_chips.sv. The script reports FAIL and the trace marks the codes WRONG.

12On an FPGA board: lab_top in BGM

The Basics-Graphics-Music (BGM) repository runs the same labs on dozens of FPGA boards. Each lab has a lab_top module with the same ports on every board: clock, reset, keys, LEDs, and a 7-segment display with the segments abcdefgh (h is the dot) and a digit select.

  1. Copy labs/1_basics/1_05_7seven_segment_letter to a new directory.
  2. Replace its lab_top.sv with bgm_lab/lab_top.sv from this exercise and add seven_segment.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. The rightmost digit shows the code the way the 4511 does, and the LEDs show the code. abcdefg has segment a in its top bit, like abcdefgh in BGM, so it connects without reordering.

bgm_lab/lab_top.sv96 lines · show the codefile
// Exercise B7 on an FPGA board with the Basics-Graphics-Music (BGM) labs:
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy labs/1_basics/1_05_7seven_segment_letter to a new directory,
// replace its lab_top.sv with this file and add seven_segment.sv.  For the
// chip-level design add seven_segment_chips.sv and cd4511.sv instead, and
// change the module name below.
//
// Keys 3-0 are the buttons D C B A: hold them to make a code from 0 to 15.
// The rightmost digit of the display shows it the way the 4511 does, and
// the LEDs show the code.  On a board with fewer than four keys the
// missing bits are 0.

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

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

    wire  [3:0] bcd = 4' (key);
    logic [6:0] abcdefg;

    seven_segment i_seven_segment
    (
        .bcd     ( bcd     ),
        .abcdefg ( abcdefg )
    );

    assign abcdefgh = { abcdefg, 1'b0 };  // The dot, h, stays off
    assign digit    = w_digit' (1);
    assign led      = w_led' (bcd);

endmodule

13On an FPGA board: hackathon_top in BGM

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

  1. Copy a directory such as hackathon/problems/1_gates_and_muxes.
  2. Replace its hackathon_top.sv with bgm_hackathon/hackathon_top.sv and add seven_segment.sv.
  3. Run ./03_synthesize_for_fpga.bash and ./04_configure_fpga.bash.

Keys 3–0 are D C B A. The rightmost digit shows the code, and the screen draws the same digit large: seven bars, red when lit and dim when not.

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

// Exercise B7 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 seven_segment.sv.
//
// Keys 3-0 are the buttons D C B A.  The rightmost digit shows the code the
// way the 4511 does, the LEDs show the code, and the screen draws the same
// digit large: each segment is a bar, red when lit and dim when not.

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  [3:0] bcd = key [3:0];
    logic [6:0] abcdefg;

    seven_segment i_seven_segment
    (
        .bcd     ( bcd     ),
        .abcdefg ( abcdefg )
    );

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

    //------------------------------------------------------------------------
    // A large digit on the 480 x 272 screen.  Segment bars are 20 pixels
    // thick: a, g and d across, f, b, e and c up and down.

    wire seg_a = x >= 210 & x < 270 & y >=  36 & y <  56;
    wire seg_g = x >= 210 & x < 270 & y >= 126 & y < 146;
    wire seg_d = x >= 210 & x < 270 & y >= 216 & y < 236;
    wire seg_f = x >= 190 & x < 210 & y >=  56 & y < 126;
    wire seg_b = x >= 270 & x < 290 & y >=  56 & y < 126;
    wire seg_e = x >= 190 & x < 210 & y >= 146 & y < 216;
    wire seg_c = x >= 270 & x < 290 & y >= 146 & y < 216;

    wire [6:0] here = { seg_a, seg_b, seg_c, seg_d, seg_e, seg_f, seg_g };

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

        if (| (here & abcdefg))
            red = 31;
        else if (| here)
        begin
            red   = 6;
            green = 4;
            blue  = 2;
        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, with segment a on uo_out [0].

Switches 3–0 give the code D C B A, and the display of the demo board shows the digit: the 4511 as logic on your own chip. The decoder needs no clock: clk and rst_n are listed as unused.

tiny_tapeout/project.v46 lines · show the codefile
/*
 * Exercise B7 on Tiny Tapeout: the 4511 decoder in logic.  DIP switches
 * 3-0 give the code D C B A, the 7-segment display of the demo board shows
 * the digit.
 *
 * Add seven_segment.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
);

    wire [6:0] abcdefg;

    seven_segment i_seven_segment (
        .bcd     ( ui_in [3:0] ),
        .abcdefg ( abcdefg     )
    );

    // 7-segment display: uo_out [0] is segment a, ..., uo_out [6] is g,
    // uo_out [7] is the dot, which stays off.  abcdefg has a at the top,
    // so the bits go in reverse order.

    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 both files and use the module name as the top module:

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

15Going further

Tasks for students

Files of this exercise

Sources

The exercise is the fifth of the Basics list in “An improved way of teaching school kids digital electronics using venerable small-scale integration ICs”. Lesson 1.2 of the Habr article about the electronics course describes exploring the display with one 560-ohm, ½-watt resistor on the common cathode and then driving it from a 4511 with a resistor per segment. The 4511 and its truth table are from the Texas Instruments datasheet for the CD4511B.