Breadboard exercises/ BB6EnglishРусский

Exercise BB6 · building blocks · encoder

4532 priority encoder with a display

Press any of eight buttons, several at once if you like, and the display shows the number of the highest one. A 4532 priority encoder turns eight wires into a 3-bit number, and a 4511 draws it as a digit.

2 chips4532 encoder, 4511 display decoder
24 + 27 wireson the board + jumper leads to the modules
7 resistors560 Ω, one per segment
no clockthe digit follows the buttons at once

1What it is and why it matters

What it does. Buttons D0–D7 drive the eight inputs of a 4532. Its outputs Q2 Q1 Q0 give the number of the highest input that is 1: press D2 and D5 and the number is 5. A 4511 turns the number into the segments of the display, as in exercise B7. Two more outputs go to the LED module: GS (group select) is 1 when any input is 1, and EO (enable out) when none is.

How it works. The encoder is the opposite of a decoder (BB5): eight wires in, three bits out. When several inputs are 1 at once, the highest one wins: that is the priority. With no input at 1 the number is 0, the same as for D0 alone; GS tells the two cases apart.

Where it is used. An interrupt controller receives requests from many devices and tells the processor the number of the most urgent one; that is a priority encoder. A keyboard encoder gives the code of the pressed key; a floating-point unit finds the highest bit that is 1 to normalize a number (“count leading zeros”). Arbiters, which choose who gets a shared resource (exercise P4), are related: a fixed-priority arbiter is a priority encoder.

Why learn it.

2The key elements: priority, GS and EO

D7 … D0Highest input at 1Q2 Q1 Q0GSEO
000000000 (none)00001
00000001000010
00000110201010
00010000410010
10010001711110
01111111611010
10000000711110

EI, the enable input, is tied to +5V here. At 0 it switches the encoder off: all outputs go to 0. Two 4532s make a 16-input encoder by connecting EO of the higher chip to EI of the lower one: the lower chip is enabled only when the higher one has nothing to say.

Waveforms

D7…D000000001000000100000001100000100000001010000011000000111000010000000100100001010000010110000110000001101000011100000111100010000Q0112222333333334GSEO
From the simulation of tb.sv in Icarus Verilog: the first 16 of 512 steps. Q follows the highest input that is 1; GS is 1 whenever any input is. · SVG · PNG

3Parts

PartIn this circuitQtyPriceSupplier
CD45328-to-3 priority encoder1$0.60elexp.com
CD4511BCD-to-7-segment decoder for the display1$0.65Elexp (elexp.com)
Button modulesD0-D7; the first pack of five5$0.66 / packaliexpress.us
Button modules3 more from the second pack3$2.03 / packaliexpress.us
8-LED moduleshows GS and EO1$0.38aliexpress.us
7-segment display, common cathodeshows the number of the highest input pressed1$0.90elexp.com
Resistor, 560 Ω, ½ Wone per segment7$0.04elexp.com
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 wires24 wires on the board (or male-male Dupont jumpers)24$11.95 / packjameco.com
Male-female Dupont jumpers27 leads to the buttons and the LED module27$1.30 / packaliexpress.us

Prices from the LSSK components sheet; the 4532 is in the Comprehensive kit, and the 4511, the display and the resistors are the ones of exercise B7.

The display needs resistors. Unlike the LED module, a 7-segment display has no resistors inside: each segment gets its own 560 Ω resistor, as in exercise B7.

4The chips and the display, 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.

4532: 8-to-3 priority encoder

1D42D53D64D75EI6Q27Q18VSS9Q010D011D112D213D314GS15EO16VDD4532priority encoder
CD4532B. A 16-pin chip: VDD is pin 16 and VSS pin 8. · SVG · PNG

D0–D3 are on pins 10–13, D4–D7 on pins 1–4. EI is pin 5, the outputs Q2, Q1 and Q0 are pins 6, 7 and 9, GS pin 14 and EO pin 15. All inputs and outputs are active high. On the breadboard the 4532 sits turned around, notch on the right, so that its outputs face the 4511.

PinNameDirectionFunctionIn this circuit
1D4inputinput 4D4
2D5inputinput 5D5
3D6inputinput 6D6
4D7inputinput 7, the highest priorityD7
5EIinputEI, enable in: 0 sets all outputs to 0+5V
6Q2outputnumber of the highest active input, bit 2Q2
7Q1outputbit 1 of that numberQ1
8VSSpowerground, 0 VGND
9Q0outputbit 0 of that numberQ0
10D0inputinput 0, the lowest priorityD0
11D1inputinput 1D1
12D2inputinput 2D2
13D3inputinput 3D3
14GSoutputGS: 1 when any input is 1 (and EI = 1)GS
15EOoutputEO: 1 when EI = 1 and no input is 1; enables the next encoderEO
16VDDpowersupply, +5 V (3 to 18 V allowed)+5V

4511: BCD-to-7-segment decoder

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

As in exercise B7: A, B, C and D are the code, here Q0, Q1, Q2 of the encoder and D tied to GND. ~LT (pin 3) and ~BI (pin 4) are held at +5V, LE (pin 5) at GND. The 4511 is turned around too, so that its outputs are on the bottom row next to the display.

PinNameDirectionFunctionIn this circuit
1BinputBCD input, bit 1 (weight 2)Q1
2CinputBCD input, bit 2 (weight 4)Q2
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)GND
7AinputBCD input, bit 0 (weight 1)Q0
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. Pins 1–5 along the bottom, 6–10 along the top; pins 3 and 8 are the common cathode. · SVG · PNG

The same display as in exercise B7; check its pins with a probe wire as described there before you build.

5Schematic 1: encoder and decoder

D7D6D5D4D3D2D1D04532D7D6D5D4D3D2D1D0EIQ2Q1Q0GSEOpriority encoder4511DCBALTBILEabcdefg7-segment decoderasegmentbsegmentcsegmentdsegmentesegmentfsegmentgsegmentGSLED 1EOLED 2
The circuit as two blocks. This is what priority_encoder.sv describes; the resistors and the display are outside the logic. · SVG · PNG

6Schematic 2: connections

12345678910111213141516D4D5D6D7EIQ2Q1Q0D0D1D2D3GSEO4532priority encoder12345678910111213141516BCLTBILEDAedcbagf4511BCD → 7 segmentse1d2CC3c4DP5b6a7CC8f9g10abcdefgD0D1D2D3D4D6D7Q0Q1Q2GSEOD7D6D5D4D3D2D1D0LED module: LEDs 1-2+5V
The same circuit with the chips, pin by pin, both turned around as on the breadboard. Each segment pin of the display has its resistor drawn on it. · SVG · PNG

A segment has two nets: a from the 4511 to its resistor, and a′ from the resistor to the display pin.

NetFromToWire
D7button D7, OUT4532 4 (D7)M-F
D6button D6, OUT4532 3 (D6)M-F
D5button D5, OUT4532 2 (D5)M-F
D4button D4, OUT4532 1 (D4)M-F
D3button D3, OUT4532 13 (D3)M-F, M-M
D2button D2, OUT4532 12 (D2)M-F, M-M
D1button D1, OUT4532 11 (D1)M-F, M-M
D0button D0, OUT4532 10 (D0)M-F, M-M
Q24532 6 (Q2)4511 2 (C)M-M
Q14532 7 (Q1)4511 1 (B)M-M
Q04532 9 (Q0)4511 7 (A)M-M
GS4532 14 (GS)LED module, LED 1M-F
EO4532 15 (EO)LED module, LED 2M-F
a4511 13 (a)RaM-M
b4511 12 (b)RbM-M (loose jumper)
c4511 11 (c)RcM-M
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+5V4532 16 (VDD), 4511 16 (VDD), 4532 5 (EI), 4511 4 (BI), 4511 3 (LT)
GNDGND4532 8 (VSS), 4511 8 (VSS), 4511 6 (D), 4511 5 (LE), 3 (CC)
not connected 5 (DP), 8 (CC)

7Schematic 3: the breadboard

−+−+1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950abcdefghij5V5VPOWER MODULE · 5V9V USB-DC45324511abcdefgD2D3Q0Q1Q2+OUT−D7+OUT−D6+OUT−D5+OUT−D4+OUT−D3+OUT−D2+OUT−D1+OUT−D0G1GS2EO3456788-LED MODULELEDs 1-2 used
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 eight buttons hang above the board, the LED module below it. The wire for segment b is drawn as a loose jumper, because it has to cross over the display. · SVG · PNG
D7D6D5D4D3D2D1D0Q2Q1Q0GSEOabcdefga′b′c′d′e′f′g′+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 4532 turned around, notch to the right, pin 1 in hole 15e; the 4511 turned around, notch to the right, pin 1 in hole 27e. 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. Insert the display with pin 1 in hole 35h and pin 10 in 35d, decimal point at the bottom right.
  4. 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.
  5. The fixed inputs: EI of the 4532 (pin 5, column 11) to the top + rail; ~LT and ~BI of the 4511 (pins 3 and 4, columns 25 and 24) to the top + rail, LE and D (pins 5 and 6, columns 23 and 22) to the top − rail; the common cathode of the display (pin 3, column 37) to the bottom − rail.
  6. The seven resistors, as in the checklist: each from the column of a display pin to a free column four or five columns away.
  7. The signal wires: Q0, Q1 and Q2 from the 4532 to A, B and C of the 4511, the seven segment wires from the 4511 to the resistors, and four wires that bring D0–D3 from the bottom row to the top half, where the buttons land.
  8. With the power off, the buttons above the board, in the order D7 … D0, and the LED module below it.
  9. Turn the power on.

Wiring checklist

·

#NetFromTo
Power (red to +, black to −) · 4 wires
1+5V15j (4532 pin 16, VDD)bottom + rail, column 15
2GND8a (4532 pin 8, VSS)top − rail, column 8
3+5V27j (4511 pin 16, VDD)bottom + rail, column 27
4GND20a (4511 pin 8, VSS)top − rail, column 20
Fixed inputs: CMOS inputs must not float · 6 wires
5+5V11a (4532 pin 5, EI)top + rail, column 11
6GND22a (4511 pin 6, D)top − rail, column 22
7GND23a (4511 pin 5, LE)top − rail, column 23
8+5V24a (4511 pin 4, BI)top + rail, column 24
9+5V25a (4511 pin 3, LT)top + rail, column 25
10GND37j (display pin 3, CC)bottom − rail, column 37
Resistors, 560 Ω (not wires: put each resistor in these two holes) · 7 resistors
Rg560 Ω35b31b
Rf560 Ω36a32a
Ra560 Ω38c33c
Re560 Ω35j31j
Rd560 Ω36i32i
Rb560 Ω39a43a
Rc560 Ω38j42j
Signal wires · 14 wires
11a24g (4511 pin 13, a)33e (Ra)
12b (loose jumper)23h (4511 pin 12, b)43c (Rb)
13c22j (4511 pin 11, c)42i (Rc)
14d21g (4511 pin 10, d)32g (Rd)
15e20h (4511 pin 9, e)31h (Re)
16f26i (4511 pin 15, f)32d (Rf)
17g25i (4511 pin 14, g)31a (Rg)
18D09g (4532 pin 10, D0)6e
19D110g (4532 pin 11, D1)7e
20D211g (4532 pin 12, D2)17e
21D312g (4532 pin 13, D3)16e
22Q08h (4532 pin 9, Q0)21d (4511 pin 7, A)
23Q19c (4532 pin 7, Q1)27c (4511 pin 1, B)
24Q210b (4532 pin 6, Q2)26b (4511 pin 2, C)
Modules on male-female jumpers · 27 wires
25+5Vbutton D7, +top + rail, column 5
26D7button D7, OUT12a (4532 pin 4, D7)
27GNDbutton D7, −top − rail, column 5
28+5Vbutton D6, +top + rail, column 8
29D6button D6, OUT13a (4532 pin 3, D6)
30GNDbutton D6, −top − rail, column 10
31+5Vbutton D5, +top + rail, column 13
32D5button D5, OUT14a (4532 pin 2, D5)
33GNDbutton D5, −top − rail, column 15
34+5Vbutton D4, +top + rail, column 18
35D4button D4, OUT15a (4532 pin 1, D4)
36GNDbutton D4, −top − rail, column 19
37+5Vbutton D3, +top + rail, column 23
38D3button D3, OUT16a
39GNDbutton D3, −top − rail, column 25
40+5Vbutton D2, +top + rail, column 28
41D2button D2, OUT17a
42GNDbutton D2, −top − rail, column 30
43+5Vbutton D1, +top + rail, column 33
44D1button D1, OUT7a
45GNDbutton D1, −top − rail, column 35
46+5Vbutton D0, +top + rail, column 38
47D0button D0, OUT6a
48GNDbutton D0, −top − rail, column 40
49GNDLED module, Gbottom − rail, column 5
50GSLED module, LED 113j (4532 pin 14, GS)
51EOLED module, LED 214j (4532 pin 15, EO)

Test it

If it does not work: if the digit is wrong only when certain buttons are pressed, check the leads of those buttons: D0–D3 and D4–D7 are on different rows. If the display shows nonsense, compare the segment wires with the checklist. If the display stays dark, check ~BI at +5V and the common cathode at GND.

8SystemVerilog: the generic design

priority_encoder.sv describes both blocks: a loop that scans the inputs from the lowest up, so that a higher input that is 1 overwrites a lower one, and a case with the digits of the 4511. It is synthesizable.

priority_encoder.svfile
// Exercise BB6: an 8-to-3 priority encoder, like the 4532, whose output is
// shown on a 7-segment display through a decoder, like the 4511.
//
// Generic version that matches schematic 1, not tied to any chip.
// Synthesizable.

module priority_encoder
(
    input  logic [7:0] d,        // d [7] has the highest priority

    output logic [2:0] q,        // The number of the highest input at 1
    output logic       gs,       // Group select: some input is 1
    output logic       eo,       // Enable out: no input is 1
    output logic [6:0] abcdefg   // Segments a-g: abcdefg [6] is a, the top one
);

    //------------------------------------------------------------------------
    // The encoder: scan from the lowest input up, so that a higher input that
    // is 1 overwrites a lower one.  The loop is unrolled by synthesis.

    always_comb
    begin
        q = 3'd0;

        for (int i = 0; i < 8; i ++)
            if (d [i])
                q = 3' (i);
    end

    assign gs =   | d;
    assign eo = ~| d;

    //------------------------------------------------------------------------
    // The decoder: the digits 0-7 as the 4511 draws them.  Its 6 has no top
    // segment.

    always_comb
        case (q)
        3'd0:    abcdefg = 7'b111_1110;
        3'd1:    abcdefg = 7'b011_0000;
        3'd2:    abcdefg = 7'b110_1101;
        3'd3:    abcdefg = 7'b111_1001;
        3'd4:    abcdefg = 7'b011_0011;
        3'd5:    abcdefg = 7'b101_1011;
        3'd6:    abcdefg = 7'b001_1111;
        default: abcdefg = 7'b111_0000;
        endcase

endmodule

9SystemVerilog models of the chips

One module per chip, with ports named as in the datasheet and the pin number of each port in a comment. The models leave out the power pins: in SystemVerilog a wire simply has the value 0 or 1.

cd4532.svfile
// CD4532B: 8-bit priority encoder.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (8)
// and VDD (16), are left out.  Synthesizable.
//
// With EI = 1, Q2 Q1 Q0 is the number of the highest input that is 1, and
// GS = 1; when no input is 1, Q = 0, GS = 0 and EO = 1, which enables the
// next, lower encoder of a cascade.  EI = 0 sets all outputs to 0.

module cd4532
(
    input  logic d4,  // Pin 1
    input  logic d5,  // Pin 2
    input  logic d6,  // Pin 3
    input  logic d7,  // Pin 4:  highest priority
    input  logic ei,  // Pin 5:  enable in
    output logic q2,  // Pin 6
    output logic q1,  // Pin 7
                      // Pin 8:  VSS
    output logic q0,  // Pin 9
    input  logic d0,  // Pin 10: lowest priority
    input  logic d1,  // Pin 11
    input  logic d2,  // Pin 12
    input  logic d3,  // Pin 13
    output logic gs,  // Pin 14: group select
    output logic eo   // Pin 15: enable out
                      // Pin 16: VDD
);

    wire [7:0] d = { d7, d6, d5, d4, d3, d2, d1, d0 };

    logic [2:0] q;

    always_comb
    begin
        q = 3'd0;

        for (int i = 0; i < 8; i ++)
            if (d [i])
                q = 3'(i);
    end

    assign { q2, q1, q0 } = ei ? q : 3'd0;
    assign gs = ei &   (| d);
    assign eo = ei & ~ (| d);

endmodule
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

10SystemVerilog: the chip-level design

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

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

module priority_encoder_chips
(
    input  logic [7:0] d,
    output logic [2:0] q,
    output logic       gs,
    output logic       eo,
    output logic [6:0] abcdefg
);

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

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

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

    // U1: CD4532 8-bit priority encoder, pin 1 in column 8

    cd4532 i_u1
    (
        .d4 ( d [4] ),  // Pin 1 <- button D4
        .d5 ( d [5] ),  // Pin 2 <- button D5
        .d6 ( d [6] ),  // Pin 3 <- button D6
        .d7 ( d [7] ),  // Pin 4 <- button D7
        .ei ( vdd   ),  // Pin 5 <- +5V
        .q2 ( q [2] ),  // Pin 6 -> Q2
        .q1 ( q [1] ),  // Pin 7 -> Q1
        .q0 ( q [0] ),  // Pin 9 -> Q0
        .d0 ( d [0] ),  // Pin 10 <- button D0
        .d1 ( d [1] ),  // Pin 11 <- button D1
        .d2 ( d [2] ),  // Pin 12 <- button D2
        .d3 ( d [3] ),  // Pin 13 <- button D3
        .gs ( gs    ),  // Pin 14 -> GS
        .eo ( eo    )   // Pin 15 -> EO
    );

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

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

    cd4511 i_u2
    (
        .bcd_b        ( q [1]       ),  // Pin 1 <- U1 pin 7 (Q1)
        .bcd_c        ( q [2]       ),  // Pin 2 <- U1 pin 6 (Q2)
        .lamp_test_n  ( vdd         ),  // Pin 3 <- +5V
        .blank_n      ( vdd         ),  // Pin 4 <- +5V
        .latch_enable ( gnd         ),  // Pin 5 <- GND
        .bcd_d        ( gnd         ),  // Pin 6 <- GND
        .bcd_a        ( q [0]       ),  // Pin 7 <- U1 pin 9 (Q0)
        .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 the number, GS, EO and all seven segments 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 tries all 256 combinations of the buttons twice, counting up and in Gray code order. The output below is shortened.

tb.sv176 lines · show the codefile
// Testbench for exercise BB6.
//
// Runs the generic design (priority_encoder.sv) and the chip-level design
// (priority_encoder_chips.sv) side by side and compares both with
// the number of the highest input at 1 and the digit that the 4511 draws for it.  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 256 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 [7:0] d;

    wire  [2:0] q,       q_chips;
    wire        gs,      gs_chips;
    wire        eo,      eo_chips;
    wire  [6:0] abcdefg, abcdefg_chips;

    priority_encoder i_generic
    (
        .d       ( d       ),
        .q       ( q       ),
        .gs      ( gs      ),
        .eo      ( eo      ),
        .abcdefg ( abcdefg )
    );

    priority_encoder_chips i_chips
    (
        .d       ( d             ),
        .q       ( q_chips       ),
        .gs      ( gs_chips      ),
        .eo      ( eo_chips      ),
        .abcdefg ( abcdefg_chips )
    );

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

    initial
    begin
        clk = '0;

        forever
            # 5 clk = ~ clk;
    end

    //------------------------------------------------------------------------
    // Reference model: the number of the highest input at 1 and the digit that the 4511 draws for it.
    // Bits, from the left: q, gs, eo, abcdefg.

    function automatic logic [11:0] expected (input logic [7:0] in_d);
        logic [2:0] n;
        logic [6:0] segments;

        n = '0;

        for (int i = 0; i < 8; i ++)
            if (in_d [i])
                n = 3' (i);

        // Segments a ... g of the digits 0-7 as the 4511 draws them; a is the top
        // segment.  Its 6 has no top segment.

        case (n)
        3'd0:    segments = 7'b111_1110;
        3'd1:    segments = 7'b011_0000;
        3'd2:    segments = 7'b110_1101;
        3'd3:    segments = 7'b111_1001;
        3'd4:    segments = 7'b011_0011;
        3'd5:    segments = 7'b101_1011;
        3'd6:    segments = 7'b001_1111;
        default: segments = 7'b111_0000;
        endcase

        return { n, in_d != 8'b0, in_d == 8'b0, segments };
    endfunction

    wire [11:0] out       = { q, gs, eo, abcdefg };
    wire [11:0] out_chips = { q_chips, gs_chips, eo_chips, abcdefg_chips };
    wire [11:0] out_model = expected (d);

    //------------------------------------------------------------------------
    // 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 [255: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 | 256'b1 << { d };

            $display ("%5d  %b %b %b   %b   %b  %s  %s",
                cycle + 1, d, q, gs, eo, abcdefg,
                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  D7..D0  Q  GS  EO  abcdefg  generic  chips");

        checking <= '1;

        for (int i = 0; i < 256; i ++)
        begin
            { d } <= 8' (i);
            @ (posedge clk);
        end

        for (int i = 0; i < 256; i ++)
        begin
            { d } <= 8' (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), 256);
    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 BB6: 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 priority_encoder.sv priority_encoder_chips.sv cd4532.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 BB6: 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 priority_encoder.sv priority_encoder_chips.sv cd4532.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 BB6: 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 priority_encoder.sv priority_encoder_chips.sv cd4532.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.
cycle  D7..D0  Q  GS  EO  abcdefg  generic  chips
    1  00000000 000 0   1   1111110  ok       ok   
    2  00000001 000 1   0   1111110  ok       ok   
    3  00000010 001 1   0   0110000  ok       ok   
    4  00000011 001 1   0   0110000  ok       ok   
    5  00000100 010 1   0   1101101  ok       ok   
    6  00000101 010 1   0   1101101  ok       ok   
    7  00000110 010 1   0   1101101  ok       ok   
    8  00000111 010 1   0   1101101  ok       ok   
    9  00001000 011 1   0   1111001  ok       ok   
   10  00001001 011 1   0   1111001  ok       ok   
   11  00001010 011 1   0   1111001  ok       ok   
   12  00001011 011 1   0   1111001  ok       ok   
   13  00001100 011 1   0   1111001  ok       ok   
   14  00001101 011 1   0   1111001  ok       ok   
   15  00001110 011 1   0   1111001  ok       ok   
   16  00001111 011 1   0   1111001  ok       ok   
   17  00010000 100 1   0   0110011  ok       ok   
   18  00010001 100 1   0   0110011  ok       ok   
   19  00010010 100 1   0   0110011  ok       ok   
   20  00010011 100 1   0   0110011  ok       ok   
   21  00010100 100 1   0   0110011  ok       ok   
   22  00010101 100 1   0   0110011  ok       ok   
  …
tb.sv:162: $finish called at 5125000 (1ps)
PASS: 1024 checks, no errors

To see that the testbench catches mistakes, break something and run it again: scan the inputs from the highest down instead of from the lowest up in priority_encoder.sv, so that the lowest input wins, or connect Q0 and Q1 the other way round in priority_encoder_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_04_priority_encoder to a new directory.
  2. Replace its lab_top.sv with bgm_lab/lab_top.sv from this exercise and add priority_encoder.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.

Switches 7–0 are D7–D0; on a board without switches use keys. The rightmost digit shows the number, the LEDs show Q, GS and EO. To run the chip-level design instead, add priority_encoder_chips.sv, cd4532.sv and cd4511.sv and change the module name in the instance.

bgm_lab/lab_top.sv99 lines · show the codefile
// Exercise BB6 on an FPGA board with the Basics-Graphics-Music (BGM) labs:
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy labs/1_basics/1_04_priority_encoder to a new directory, replace
// its lab_top.sv with this file and add priority_encoder.sv.  For the
// chip-level design add priority_encoder_chips.sv, cd4532.sv and cd4511.sv
// instead, and change the module name below.
//
// Switches 7-0 are D7-D0 (on a board without switches use keys).  The
// rightmost digit shows the number of the highest switch that is on, the
// LEDs show Q in binary, GS and EO.

`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 [2:0] q;
    logic       gs, eo;
    logic [6:0] abcdefg;

    priority_encoder i_priority_encoder
    (
        .d       ( 8' (sw) ),
        .q       ( q       ),
        .gs      ( gs      ),
        .eo      ( eo      ),
        .abcdefg ( abcdefg )
    );

    assign led      = w_led' ({ eo, gs, q });
    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 priority_encoder.sv.
  3. Run ./03_synthesize_for_fpga.bash and ./04_configure_fpga.bash.

Keys 7–0 are D7–D0. The screen shows eight lamps, D0 on the left: blue for a pressed key and green for the one that wins. The rightmost digit shows the number.

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

// Exercise BB6 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 priority_encoder.sv.
//
// Keys 7-0 are D7-D0.  The rightmost digit shows the number of the highest
// key pressed, the LEDs show Q, GS and EO, and the screen eight lamps for
// the keys, D0 on the left, with the winning one in green.

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 [2:0] q;
    logic       gs, eo;
    logic [6:0] abcdefg;

    priority_encoder i_priority_encoder
    (
        .d       ( key     ),
        .q       ( q       ),
        .gs      ( gs      ),
        .eo      ( eo      ),
        .abcdefg ( abcdefg )
    );

    assign led      = { 3'b0, eo, gs, q };
    assign abcdefgh = { abcdefg, 1'b0 };
    assign digit    = 8'b0000_0001;

    //------------------------------------------------------------------------
    // Eight square lamps, D0 on the left: blue for a pressed key, green for
    // the one that wins, dim for the others.

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

        for (int i = 0; i < 8; i ++)
            if (x >= 9' (40 + i * 52) & x < 9' (80 + i * 52) & y >= 116 & y < 156)
            begin
                if (gs & q == 3' (i))
                    green = 63;
                else if (key [i])
                    blue  = 31;
                else
                    blue  = 6;
            end
    end

endmodule

14On a chip: Tiny Tapeout

Tiny Tapeout makes real chips from student designs. Each design is a module with the ports below; on the demo board ui_in comes from DIP switches and uo_out drives a 7-segment display.

This design has no clock and no state: project.v connects the DIP switches to its inputs and its outputs to the display. The project still gets a clock and a reset from the board; they stay unused.

Switches 7–0 are D7–D0. The display shows the digit drawn by the design, the dot is GS, and Q and EO go to the BIDIR Pmod.

tiny_tapeout/project.v52 lines · show the codefile
/*
 * Exercise BB6 on Tiny Tapeout: an 8-to-3 priority encoder like the 4532,
 * with the DIP switches as inputs and the 7-segment display of the demo
 * board showing the number of the highest switch that is on.
 *
 * Add priority_encoder.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 7-0 are D7-D0

    wire [2:0] q;
    wire       gs, eo;
    wire [6:0] abcdefg;

    priority_encoder i_priority_encoder (
        .d       ( ui_in   ),
        .q       ( q       ),
        .gs      ( gs      ),
        .eo      ( eo      ),
        .abcdefg ( abcdefg )
    );

    // uo_out [0] is segment a, ..., uo_out [6] is g; the dot, uo_out [7],
    // is GS.  Q and EO go to the BIDIR Pmod, for LEDs or a logic analyzer.

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

    assign uio_out = { 4'b0, eo, q };
    assign uio_oe  = 8'b0000_1111;

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

    wire _unused = & { ena, clk, rst_n, 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>_priority_encoder
  source_files:
    - "project.v"
    - "priority_encoder.sv"

15Going further

Tasks for students

Files of this exercise

Sources

The 4532 with a 4511 and a display is in the Building blocks list of “An improved way of teaching school kids digital electronics” and in lesson 1.6 of the Habr article about the electronics course. The chips are described in the Texas Instruments datasheets for the CD4532B and the CD4511B.