Breadboard exercises/ M4EnglishРусский

Exercise M4 · mini-project · adder

8-bit adder from two cascaded 4008s

One 4008 adds two 4-bit numbers. Connect its carry out to the carry in of a second 4008, and the two add 8-bit numbers: the low chip adds bits 3–0, the high chip bits 7–4 and the carry that comes from below. This is how wide adders are built from narrow ones.

2 chips4008 × 2
16 + 33 wireson the board + jumper leads to the modules
8 + 8 bitsA from buttons, B from wires
no clockthe sum follows the inputs

1What it is and why it matters

What it does. Eight buttons A7–A0 give the number A, eight wires B7–B0 to the rails give the number B; they start at 00101101, the number 45. The LED module shows the 8-bit sum, S7 on LED 1 and S0 on LED 8, and a red LED shows the ninth bit, the carry out C8.

How it works. The low 4008 adds A3–A0 and B3–B0 with its carry in at GND. Its carry out C4 says that the low half overflowed, and it goes into the carry in of the high 4008, which adds A7–A4, B7–B4 and C4. The high carry out is the ninth bit of the sum.

Where it is used. Every wide adder is built from narrow pieces. Inside the 4008 the carry goes across the four bits at once (a parallel carry), but between the two chips it ripples: the high chip waits for the low one. In a processor, look-ahead carry circuits, like the 40182 for the 40181 of exercise BB10, cut this wait.

Why learn it.

2The key elements: the carry between the chips

ExampleABC4S7 … S0 (LEDs 1-8)C8 (red LED)A + B
100 + 4501100100001011011100100010145
200 + 4511001000001011011111101010245
15 + 10000111100000001100010000016
255 + 111111111000000011000000001256
128 + 12810000000100000000000000001256
85 + 17001010101101010100111111110255

C4 is 1 when the low halves add up to 16 or more: 15 + 1 makes 0000 in the low half and passes 1 to the high half. 255 + 1 overflows both: the sum is 0 and the red LED lights.

Waveforms

A2001525512885012345678910111213B4511281700A + B2451600255012345678910111213C4C8
From the simulation of tb.sv in Icarus Verilog: the six examples of the table, then the start of the run through all 65536 pairs. C4 is the wire between the two chips. · SVG · PNG

3Parts

PartIn this circuitQtyPriceSupplier
CD40084-bit full adders: bits 3-0 and bits 7-42$1.00leeselectronic.com
Button modulesA7-A0; the first pack of five5$0.66 / packaliexpress.us
Button modules3 more from the second pack3$2.03 / packaliexpress.us
8-LED modulethe sum S7-S01$0.38aliexpress.us
5 V LED, redthe carry out C8, plugged into the board1$0.45elexp.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 wires16 wires on the board (or male-male Dupont jumpers)16$11.95 / packjameco.com
Male-female Dupont jumpers33 leads to the buttons and the LED module33$1.30 / packaliexpress.us

Prices from the LSSK components sheet; the 4008 is in the Basics kit, and this exercise needs two of them.

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.

4008: 4-bit full adder

1A42B33A34B25A26B17A18VSS9CIN10S111S212S313S414COUT15B416VDD40084-bit adder
CD4008B. · SVG · PNG

As in exercise B8. A1–A4 are pins 7, 5, 3, 1; B1–B4 are pins 6, 4, 2, 15; CARRY IN is pin 9; S1–S4 are pins 10–13 and CARRY OUT pin 14. In the low chip CARRY IN is at GND and CARRY OUT goes to CARRY IN of the high chip.

PinNameDirectionFunctionIn this circuit
1A4inputnumber A, bit 3 (weight 8)A3
2B3inputnumber B, bit 2 (weight 4)B2 (+5V)
3A3inputnumber A, bit 2 (weight 4)A2
4B2inputnumber B, bit 1 (weight 2)B1 (GND)
5A2inputnumber A, bit 1 (weight 2)A1
6B1inputnumber B, bit 0 (weight 1)B0 (+5V)
7A1inputnumber A, bit 0 (weight 1)A0
8VSSpowerground, 0 VGND
9CINinputcarry in, added to A + BGND
10S1outputsum, bit 0 (weight 1)S0
11S2outputsum, bit 1 (weight 2)S1
12S3outputsum, bit 2 (weight 4)S2
13S4outputsum, bit 3 (weight 8)S3
14COUToutputcarry out, the fifth bit of the sum (weight 16)C4
15B4inputnumber B, bit 3 (weight 8)B3 (+5V)
16VDDpowersupply, +5 V (3 to 18 V allowed)+5V

5Schematic 1: two adders in a cascade

A7A6A5A4A3A2A1A0B7B6B5B4B3B2B1B04008A4A3A2A1B4B3B2B1CINS4S3S2S1COUTbits 3-04008A4A3A2A1B4B3B2B1CINS4S3S2S1COUTbits 7-4S7LED 1S6LED 2S5LED 3S4LED 4S3LED 5S2LED 6S1LED 7S0LED 8C8red LED
The circuit as two blocks. This is what adder8.sv describes. · SVG · PNG

6Schematic 2: connections between the chips

12345678910111213141516A4B3A3B2A2B1A1CINS1S2S3S4COUTB440084-bit adder12345678910111213141516A4B3A3B2A2B1A1CINS1S2S3S4COUTB440084-bit adder+−C8, 5 V LEDA0A1A2A3A4A5A6A7S0S1S2S3S4S5S6S7C4C8A7A6A5A4A3A2A1A0LED module: LEDs 1-8B0→ +5VB1→ GNDB2→ +5VB4→ GNDB5→ +5VB6→ GNDB3→ +5VB7→ GND+5V
The same circuit as chips, pin by pin. The boxes marked “→ GND” or “→ +5V” are the B wires in their starting places. · SVG · PNG
NetFromToWire
A7button A7, OUT4008 1 (A4)M-F
A6button A6, OUT4008 3 (A3)M-F
A5button A5, OUT4008 5 (A2)M-F
A4button A4, OUT4008 7 (A1)M-F
A3button A3, OUT4008 1 (A4)M-F
A2button A2, OUT4008 3 (A3)M-F
A1button A1, OUT4008 5 (A2)M-F
A0button A0, OUT4008 7 (A1)M-F
B7B7 wire: GND4008 15 (B4)M-M
B6B6 wire: GND4008 2 (B3)M-M
B5B5 wire: +5V4008 4 (B2)M-M
B4B4 wire: GND4008 6 (B1)M-M
B3B3 wire: +5V4008 15 (B4)M-M
B2B2 wire: +5V4008 2 (B3)M-M
B1B1 wire: GND4008 4 (B2)M-M
B0B0 wire: +5V4008 6 (B1)M-M
C44008 14 (COUT)4008 9 (CIN)M-M
S74008 13 (S4)LED module, LED 1M-F
S64008 12 (S3)LED module, LED 2M-F
S54008 11 (S2)LED module, LED 3M-F
S44008 10 (S1)LED module, LED 4M-F
S34008 13 (S4)LED module, LED 5M-F
S24008 12 (S3)LED module, LED 6M-F
S14008 11 (S2)LED module, LED 7M-F
S04008 10 (S1)LED module, LED 8M-F
C84008 14 (COUT)5 V LED, + legM-M
+5V+5V4008 16 (VDD), 4008 16 (VDD)
GNDGND4008 8 (VSS), 4008 8 (VSS), 5 V LED, − leg, 4008 9 (CIN)

7Schematic 3: the breadboard

−+−+123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263abcdefghij5V5VPOWER MODULE · 5V9V USB-DC40084008+−C8, 5 V LEDB0B1B2B3B4B5B6B7C4C8+OUT−A7+OUT−A6+OUT−A5+OUT−A4+OUT−A3+OUT−A2+OUT−A1+OUT−A0G1S72S63S54S45S36S27S18S08-LED MODULELEDs 1-8 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 eight buttons hang above the board, the LED module below it; the red LED is plugged into the board. The dashed lines are the B wires to the rails. · SVG · PNG
A7A6A5A4A3A2A1A0B7B6B5B4B3B2B1B0C4S7S6S5S4S3S2S1S0C8+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 4008 turned around, notch to the right, pin 1 in hole 15e; the 4008 turned around, notch to the right, pin 1 in hole 25e. Read the numbers on the chips: many look alike. A chip turned around has pin 1 at the top right: it puts the pins this circuit needs next to its neighbours.
  3. Power: for each chip a red wire from its VDD pin (14, or 16 on a 16-pin chip) to the + rail and a black wire from its VSS pin (7 or 8) to the − rail, each to the rail on its own side of the gap. On a chip turned around VDD is on the bottom row and VSS on the top row. Make sure no wire touches + and − at the same time.
  4. The red 5 V LED: long leg into the hole shown, short leg to GND as in the checklist. It has its resistor inside.
  5. CARRY IN of the low 4008 to GND, and the cascade wire from CARRY OUT of the low 4008 to CARRY IN of the high one.
  6. The eight B wires to the rails, as in the checklist.
  7. With the power off, the modules: A7–A0 above the board, the LED module below it. Tick each wire as you insert it.
  8. Turn the power on.

Wiring checklist

·

#NetFromTo
Power (red to +, black to −) · 5 wires
1+5V15j (4008 pin 16, VDD)bottom + rail, column 15
2GND8a (4008 pin 8, VSS)top − rail, column 8
3+5V25j (4008 pin 16, VDD)bottom + rail, column 25
4GND18a (4008 pin 8, VSS)top − rail, column 18
13GND29j (5 V LED, − leg)bottom − rail, column 29
Fixed inputs: CMOS inputs must not float · 1 wire
14GND8j (4008 pin 9, CIN)bottom − rail, column 8
Mode wires: move them between + and − to change the mode · 8 wires
5B010a (4008 pin 6, B1)top + rail, column 10
6B112a (4008 pin 4, B2)top − rail, column 12
7B214a (4008 pin 2, B3)top + rail, column 14
8B314j (4008 pin 15, B4)bottom + rail, column 14
9B420a (4008 pin 6, B1)top − rail, column 20
10B522a (4008 pin 4, B2)top + rail, column 22
11B624a (4008 pin 2, B3)top − rail, column 24
12B724j (4008 pin 15, B4)bottom − rail, column 24
Signal wires · 2 wires
15C413g (4008 pin 14, COUT)18g (4008 pin 9, CIN)
16C823g (4008 pin 14, COUT)28g (5 V LED, + leg)
Modules on male-female jumpers · 33 wires
17+5Vbutton A7, +top + rail, column 5
18A7button A7, OUT25a (4008 pin 1, A4)
19GNDbutton A7, −top − rail, column 7
20+5Vbutton A6, +top + rail, column 9
21A6button A6, OUT23a (4008 pin 3, A3)
22GNDbutton A6, −top − rail, column 11
23+5Vbutton A5, +top + rail, column 15
24A5button A5, OUT21a (4008 pin 5, A2)
25GNDbutton A5, −top − rail, column 17
26+5Vbutton A4, +top + rail, column 20
27A4button A4, OUT19a (4008 pin 7, A1)
28GNDbutton A4, −top − rail, column 22
29+5Vbutton A3, +top + rail, column 25
30A3button A3, OUT15a (4008 pin 1, A4)
31GNDbutton A3, −top − rail, column 27
32+5Vbutton A2, +top + rail, column 30
33A2button A2, OUT13a (4008 pin 3, A3)
34GNDbutton A2, −top − rail, column 32
35+5Vbutton A1, +top + rail, column 35
36A1button A1, OUT11a (4008 pin 5, A2)
37GNDbutton A1, −top − rail, column 37
38+5Vbutton A0, +top + rail, column 40
39A0button A0, OUT9a (4008 pin 7, A1)
40GNDbutton A0, −top − rail, column 42
41GNDLED module, Gbottom − rail, column 12
42S7LED module, LED 122j (4008 pin 13, S4)
43S6LED module, LED 221j (4008 pin 12, S3)
44S5LED module, LED 320j (4008 pin 11, S2)
45S4LED module, LED 419j (4008 pin 10, S1)
46S3LED module, LED 512j (4008 pin 13, S4)
47S2LED module, LED 611j (4008 pin 12, S3)
48S1LED module, LED 710j (4008 pin 11, S2)
49S0LED module, LED 89j (4008 pin 10, S1)

Test it

If it does not work: if the high half never gets the carry, as when 45 + 6 shows 00100011, check the cascade wire from pin 14 of the low chip to pin 9 of the high chip. If the sum is one too big, CARRY IN of the low chip is not at GND. If single bits are wrong, compare the A and B wires with the pins: A and B take turns on the 4008.

8SystemVerilog: the generic design

adder8.sv adds the two halves separately and passes the carry, to match the two chips. The one line { carry, sum } = a + b would give the same result, and synthesis would choose the adder. It is synthesizable.

adder8.svfile
// Exercise M4: an 8-bit adder made of two 4-bit adders, the carry out of
// the low one into the carry in of the high one, like two cascaded 4008s.
//
// Generic version that matches schematic 1, not tied to any chip.  carry is
// the ninth bit of the sum: 1 when a + b > 255.  Synthesizable.

module adder8
(
    input  logic [7:0] a,
    input  logic [7:0] b,
    output logic [7:0] sum,
    output logic       carry
);

    // The low adder adds bits 3-0 with no carry in; its carry out C4 goes
    // into the high adder, which adds bits 7-4

    wire [4:0] low  = 5' (a [3:0]) + 5' (b [3:0]);
    wire [4:0] high = 5' (a [7:4]) + 5' (b [7:4]) + 5' (low [4]);

    assign sum   = { high [3:0], low [3:0] };
    assign carry = high [4];

endmodule

9SystemVerilog model of the chip

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

cd4008.svfile
// CD4008B: 4-bit full adder with a fast carry output.
//
// Ports in pin order, named as in the datasheet: A1-A4 and B1-B4 are the
// two numbers (A1 and B1 the lowest bits), S1-S4 the sum.  The power pins,
// VSS (8) and VDD (16), are left out.  Synthesizable.
//
// Inside are four full adders.  The chip computes CARRY OUT with extra
// look-ahead logic, so it does not wait for the carry to ripple through all
// four stages; the result is the same.

module cd4008
(
    input  logic a4,         // Pin 1
    input  logic b3,         // Pin 2
    input  logic a3,         // Pin 3
    input  logic b2,         // Pin 4
    input  logic a2,         // Pin 5
    input  logic b1,         // Pin 6
    input  logic a1,         // Pin 7
                             // Pin 8:  VSS
    input  logic carry_in,   // Pin 9
    output logic s1,         // Pin 10
    output logic s2,         // Pin 11
    output logic s3,         // Pin 12
    output logic s4,         // Pin 13
    output logic carry_out,  // Pin 14
    input  logic b4          // Pin 15
                             // Pin 16: VDD
);

    assign { carry_out, s4, s3, s2, s1 } =   { 1'b0, a4, a3, a2, a1 }
                                           + { 1'b0, b4, b3, b2, b1 }
                                           + { 4'b0, carry_in };

endmodule

10SystemVerilog: the chip-level design

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

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

module adder8_chips
(
    input  logic [7:0] a,
    input  logic [7:0] b,
    output logic [7:0] sum,
    output logic       carry
);

    // Connections between the chips that are not ports

    wire c4;

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

    wire gnd = 1'b0;

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

    // U1: CD4008 4-bit full adder, pin 1 in column 8

    cd4008 i_u1
    (
        .a4        ( a [3]   ),  // Pin 1 <- button A3
        .b3        ( b [2]   ),  // Pin 2 <- B2 wire, at +5V on the breadboard
        .a3        ( a [2]   ),  // Pin 3 <- button A2
        .b2        ( b [1]   ),  // Pin 4 <- B1 wire, at GND on the breadboard
        .a2        ( a [1]   ),  // Pin 5 <- button A1
        .b1        ( b [0]   ),  // Pin 6 <- B0 wire, at +5V on the breadboard
        .a1        ( a [0]   ),  // Pin 7 <- button A0
        .carry_in  ( gnd     ),  // Pin 9 <- GND
        .s1        ( sum [0] ),  // Pin 10 -> S0
        .s2        ( sum [1] ),  // Pin 11 -> S1
        .s3        ( sum [2] ),  // Pin 12 -> S2
        .s4        ( sum [3] ),  // Pin 13 -> S3
        .carry_out ( c4      ),  // Pin 14 -> C4
        .b4        ( b [3]   )   // Pin 15 <- B3 wire, at +5V on the breadboard
    );

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

    // U2: CD4008 4-bit full adder, pin 1 in column 18

    cd4008 i_u2
    (
        .a4        ( a [7]   ),  // Pin 1 <- button A7
        .b3        ( b [6]   ),  // Pin 2 <- B6 wire, at GND on the breadboard
        .a3        ( a [6]   ),  // Pin 3 <- button A6
        .b2        ( b [5]   ),  // Pin 4 <- B5 wire, at +5V on the breadboard
        .a2        ( a [5]   ),  // Pin 5 <- button A5
        .b1        ( b [4]   ),  // Pin 6 <- B4 wire, at GND on the breadboard
        .a1        ( a [4]   ),  // Pin 7 <- button A4
        .carry_in  ( c4      ),  // Pin 9 <- U1 pin 14 (COUT)
        .s1        ( sum [4] ),  // Pin 10 -> S4
        .s2        ( sum [5] ),  // Pin 11 -> S5
        .s3        ( sum [6] ),  // Pin 12 -> S6
        .s4        ( sum [7] ),  // Pin 13 -> S7
        .carry_out ( carry   ),  // Pin 14 -> C8
        .b4        ( b [7]   )   // Pin 15 <- B7 wire, at GND on the breadboard
    );

endmodule

11Testbench and simulation scripts

tb.sv adds the examples of section 2 and then every pair of 8-bit numbers, 65536 in all, and compares both designs with integer addition. Like the testbenches of Basics-Graphics-Music, it changes the inputs and checks the outputs only at rising clock edges. It prints only the examples and any error, and dumps the waveforms only at the start, so that the files stay small.

tb.sv150 lines · show the codefile
// Testbench for exercise M4.
//
// Drives the generic design (adder8.sv) and the chip-level design
// (adder8_chips.sv) with the same inputs and compares both with integer
// addition.  Works with Icarus Verilog, Verilator (--binary) and Questa.
//
// Like the testbenches of Basics-Graphics-Music, it changes the inputs and
// checks the outputs only at rising clock edges.  It adds the examples of
// section 2 and then every pair of 8-bit numbers, 65536 in all; it prints
// only the examples and any error, and dumps the waveforms only at the
// start.

// 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] a, b;

    wire  [7:0] sum,   sum_chips;
    wire        carry, carry_chips;

    adder8 i_generic
    (
        .a     ( a     ),
        .b     ( b     ),
        .sum   ( sum   ),
        .carry ( carry )
    );

    adder8_chips i_chips
    (
        .a     ( a           ),
        .b     ( b           ),
        .sum   ( sum_chips   ),
        .carry ( carry_chips )
    );

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

    initial
    begin
        clk = '0;

        forever
            # 5 clk = ~ clk;
    end

    //------------------------------------------------------------------------
    // Reference model: integer addition, the ninth bit is the carry

    wire [8:0] expected = 9' (a) + 9' (b);

    wire ok_generic = { carry,       sum       } === expected;
    wire ok_chips   = { carry_chips, sum_chips } === expected;

    //------------------------------------------------------------------------
    // 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 printing = 1'b1;  // Cleared by the stimulus after the examples
    logic done     = 1'b0;  // Set by the stimulus before $finish

    int cycle    = 0;
    int n_checks = 0;
    int n_errors = 0;

    always @ (posedge clk)
        if (checking & ~ done)
        begin
            cycle    <= cycle + 1;
            n_checks <= n_checks + 2;
            n_errors <= n_errors + (ok_generic ? 0 : 1) + (ok_chips ? 0 : 1);

            if (printing | ~ ok_generic | ~ ok_chips)
                $display ("%5d  %3d + %3d  %b %b  %3d  %s  %s", cycle + 1, a, b, carry, sum, expected,
                    ok_generic ? "ok     " : "WRONG  ", ok_chips ? "ok" : "WRONG");
        end

    //------------------------------------------------------------------------
    // Driving the inputs

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

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

        $display ("cycle    A     B    C8 S7..S0    A+B  generic  chips");

        checking <= '1;

        // The examples of section 2

        { a, b } <= { 8'd100, 8'd45  };  @ (posedge clk);
        { a, b } <= { 8'd200, 8'd45  };  @ (posedge clk);
        { a, b } <= { 8'd15,  8'd1   };  @ (posedge clk);
        { a, b } <= { 8'd255, 8'd1   };  @ (posedge clk);
        { a, b } <= { 8'd128, 8'd128 };  @ (posedge clk);
        { a, b } <= { 8'd85,  8'd170 };  @ (posedge clk);

        // Every pair, counting up: the low nibbles change fastest, so the
        // carry between the two adders flips often

        printing <= '0;

        for (int i = 0; i < 65536; i ++)
        begin
            { b, a } <= 16' (i);
            @ (posedge clk);

            if (i == 14)
                $dumpoff;
        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 && n_checks == 2 * (6 + 65536))
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks", n_errors, n_checks);
    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 M4: 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 adder8.sv adder8_chips.sv cd4008.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 M4: 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 adder8.sv adder8_chips.sv cd4008.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 M4: 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 adder8.sv adder8_chips.sv cd4008.sv)

# When vsim is not in PATH, look for it where Quartus installs it

if ! command -v vsim > /dev/null
then
    for dir in "$HOME"/intelFPGA_lite/*/questa_fse/bin  \
               "$HOME"/altera_lite/*/questa_fse/bin     \
               /opt/intelFPGA_lite/*/questa_fse/bin     \
               /opt/altera_lite/*/questa_fse/bin
    do
        if [ -x "$dir/vsim" ]
        then
            PATH="$dir:$PATH"
            break
        fi
    done
fi

if ! command -v vsim > /dev/null
then
    printf '%s\n' "$0: vsim not found, install Questa or add it to PATH" >&2
    exit 1
fi

# The Starter Edition needs a free license file from the Intel
# licensing site; Quartus keeps it in ~/flexlm/license.dat

license="$HOME/flexlm/license.dat"

# ${SALT_LICENSE_SERVER-} is empty when the variable is not set,
# where a plain $SALT_LICENSE_SERVER would stop the script (set -u)
salt_license="${SALT_LICENSE_SERVER-}"

if [ -z "$salt_license" ] && [ -f "$license" ]
then
    export SALT_LICENSE_SERVER="$license"
fi

# Older Questa versions read LM_LICENSE_FILE; ${LM_LICENSE_FILE-}
# is empty when the variable is not set
lm_license="${LM_LICENSE_FILE-}"

if [ -z "$lm_license" ] && [ -f "$license" ]
then
    export LM_LICENSE_FILE="$license"
fi

rm -rf work
vlib work > /dev/null
vlog -sv -lint "${files[@]}"
vsim -c tb -do "run -all; quit -f" | tee questa.log

grep -q 'PASS' questa.log

Tested with Icarus Verilog 12.0 and 14.0 (development), Verilator 5.053 with -Wall and no warnings, and Questa Altera Starter FPGA Edition 2025.2 from Quartus Prime Lite 25.1. The code uses only what Icarus Verilog 13 supports. This is the output, from Icarus Verilog:

VCD info: dumpfile tb.vcd opened for output.
cycle    A     B    C8 S7..S0    A+B  generic  chips
    1  100 +  45  0 10010001  145  ok          ok
    2  200 +  45  0 11110101  245  ok          ok
    3   15 +   1  0 00010000   16  ok          ok
    4  255 +   1  1 00000000  256  ok          ok
    5  128 + 128  1 00000000  256  ok          ok
    6   85 + 170  0 11111111  255  ok          ok
tb.sv:137: $finish called at 655425000 (1ps)
PASS: 131084 checks, no errors

To see that the testbench catches mistakes, break something and run it again: replace 5' (low [4]) with 5'd0 in adder8.sv, or connect CARRY IN of the high 4008 to GND instead of C4 in adder8_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_06_binary_counter to a new directory.
  2. Replace its lab_top.sv with bgm_lab/lab_top.sv from this exercise and add adder8.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 A. B is fixed in the code, as the wires on the breadboard: change it to try other numbers. LEDs 7–0 show the sum, and the dot of the rightmost digit is the carry out. To run the chip-level design instead, add adder8_chips.sv and cd4008.sv and change the module name in the instance.

bgm_lab/lab_top.sv99 lines · show the codefile
// Exercise M4 on an FPGA board with the Basics-Graphics-Music (BGM) labs:
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy labs/1_basics/1_06_binary_counter to a new directory, replace its
// lab_top.sv with this file and add adder8.sv.  For the chip-level design
// add adder8_chips.sv and cd4008.sv instead, and change the module name
// below.
//
// Switches 7-0 are A.  B is fixed in the code, as the wires to the rails
// on the breadboard: change B below to try other numbers.  LEDs 7-0 show
// the sum, and the dot of the rightmost digit is the carry out C8.

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

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

    localparam [7:0] B = 8'd45;  // 0010 1101, as the wires on the breadboard

    logic [7:0] sum;
    logic       carry;

    adder8 i_adder8
    (
        .a     ( sw [7:0] ),
        .b     ( B        ),
        .sum   ( sum      ),
        .carry ( carry    )
    );

    assign led      = w_led' (sum);
    assign abcdefgh = { 7'b0, carry };
    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 adder8.sv.
  3. Run ./03_synthesize_for_fpga.bash and ./04_configure_fpga.bash.

Keys 7–0 are A, B is fixed in the code. The screen shows three rows of eight lamps: A, B and the sum, with the carry left of the sum.

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

// Exercise M4 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 adder8.sv.
//
// Keys 7-0 are A.  B is fixed in the code, as the wires to the rails on the
// breadboard.  The LEDs show the sum, the dot of the rightmost digit the
// carry.  The screen shows three rows of eight lamps, bit 7 on the left:
// A in blue, B in orange and the sum in green, with the carry left of it.

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

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

    localparam [7:0] B = 8'd45;  // 0010 1101, as the wires on the breadboard

    logic [7:0] sum;
    logic       carry;

    adder8 i_adder8
    (
        .a     ( key   ),
        .b     ( B     ),
        .sum   ( sum   ),
        .carry ( carry )
    );

    assign led      = sum;
    assign abcdefgh = { 7'b0, carry };
    assign digit    = 8'b0000_0001;

    //------------------------------------------------------------------------
    // Lamps 30 pixels wide, 44 apart, from x = 90: rows at y = 60 (A),
    // 120 (B) and 180 (the sum); the carry at x = 46 in the row of the sum

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

        for (int i = 0; i < 8; i ++)
            if (x >= 9' (90 + i * 44) & x < 9' (120 + i * 44))
            begin
                if (y >= 60 & y < 90)
                begin
                    green = key [7 - i] ? 40 : 8;
                    blue  = key [7 - i] ? 31 : 6;
                end

                if (y >= 120 & y < 150)
                begin
                    red   = B [7 - i] ? 31 : 6;
                    green = B [7 - i] ? 32 : 6;
                end

                if (y >= 180 & y < 210)
                    green = sum [7 - i] ? 63 : 12;
            end

        if (x >= 46 & x < 76 & y >= 180 & y < 210)
            green = carry ? 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.

DIP switches 0–7 are A and BIDIR pins 0–7 are B. The sum lights the segments of the display, bit k on segment k and bit 7 on the dot. All pins are taken, so the carry out has no pin.

tiny_tapeout/project.v48 lines · show the codefile
/*
 * Exercise M4 on Tiny Tapeout: an 8-bit adder made of two 4-bit adders.
 *
 * Add adder8.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
);

    // DIP switches 0-7 are A, BIDIR pins 0-7 are B.  The circuit has no
    // clock and no reset.

    wire [7:0] sum;
    wire       carry;

    adder8 i_adder8 (
        .a     ( ui_in  ),
        .b     ( uio_in ),
        .sum   ( sum    ),
        .carry ( carry  )
    );

    // The sum on the 7-segment display and the OUTPUT Pmod: bit k lights
    // segment k, bit 7 the dot.  All 24 pins are taken, so the carry out has
    // no pin: a + b > 255 shows as a small sum.

    assign uo_out  = sum;

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

    // List all unused inputs to prevent warnings

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

15Going further

Tasks for students

Files of this exercise

Sources

The exercise is in lesson 1.4 of the Habr article about the electronics course, where the second group builds a cascade of two 4008s to add 8-bit numbers. The chip is described in the Texas Instruments datasheet for the CD4008B.