Breadboard exercises/ B5EnglishРусский

Exercise B5 · basics · counter

Up/down counter

A 4029 counts the blinks of the clock module and shows the count in binary on four LEDs: 0, 1, 2 … 9 and back to 0, or up to 15, or backwards. Two wires choose the mode, a button resets the count, and a fifth LED marks the last count before the counter wraps around.

1 chip4029 presettable up/down counter
11 + 12 wireson the board + jumper leads to the modules
4 modesup or down, 0–9 or 0–15
~1 Hz clockfrom the 555 module, no clock circuit to build

1What it is and why it matters

What it does. At every rising edge of the clock the 4029 adds 1 to its count, or subtracts 1. The count is a 4-bit number on outputs Q4, Q3, Q2 and Q1; the LED module shows it with the highest bit on the left, the way binary numbers are written. In decade mode the counter runs 0 to 9, in binary mode 0 to 15. The output ~CARRY OUT goes low at the last count, 9 or 15 when counting up and 0 when counting down, so LED 6 goes dark for one clock period just before the count wraps around. This is the third exercise of the Basics list in “An improved way of teaching school kids digital electronics”: “Demo 4029 counter”; lesson 1.3 of the Habr article gives it to half of the class next to the shift register of exercise B6.

How it works. Inside is a 4-bit register, four flip-flops like the one of exercise B4, and logic that computes the next count from the present one: +1 or −1, and back to 0 after the last count. The register takes the next count at each rising edge. The two mode inputs only change which next count that logic computes.

Where it is used. Counters are everywhere in chips: the program counter of a processor steps through the instructions, address counters walk through memories, the read and write pointers of a FIFO are counters, timers count clock periods, and the refresh of a multiplexed display counts through its digits. An up/down counter is the fill level of a FIFO: up on a write, down on a read.

Why learn it.

2The key element: a counter

4029 counter

4029CLKPEJ1…J4CIU/DB/DQ1Q2Q3Q4CO

CLK counts on the rising edge, PE = 1 loads J1–J4 at once, ~CI = 0 lets it count. U/D and B/D choose the mode; Q1–Q4 are the count, ~CO is 0 at the last count.

D flip-flop with reset

DQRDclkQrst
rstclkDQ after
1anyany0, at once
0↑00
0↑11
0no edgeanykeeps Q

The register of the counter is four of these, on one clock. The reset clears all four at once.

The four modes

U/DB/DCount~CO = 0 at
100, 1, 2 … 9, 09
110, 1, 2 … 15, 015
009, 8 … 1, 0, 90
0115, 14 … 1, 0, 150

In this exercise the mode inputs are not buttons but two wires you move between the + and − rails: a wire stays where you put it, and you can watch a mode for as long as you like. The UP wire starts at +5V (count up), the BIN wire at GND (decade).

Waveforms

clkrstupbinaryq0123456789012345678910111213141501Q4Q3Q2Q1CO
From the simulation of tb.sv in Icarus Verilog, part 1. Dotted lines are the rising edges of the clock. After the reset the counter counts up in decade mode, 0 to 9, wraps to 0, and ~CO is 0 at 9. Then the testbench switches to binary: the count goes on to 15 and wraps, and ~CO is 0 at 15. · SVG · PNG
clkrstupbinaryq0151413121110987654321098012345Q4Q3Q2Q1CO
Part 2: counting down, first in binary from 0 to 15, 14, … then in decade mode from 9 down through 0 to 9. Counting down, ~CO is 0 at 0. At the end a reset in the middle of a clock period sets 0 at once. · SVG · PNG

3Parts

PartIn this circuitQtyPriceSupplier
CD4029up/down counter, binary or decade1$0.80Elexp (elexp.com)
555 clock modulethe clock, set to about 1 Hz1$0.53aliexpress.us
Button modulereset; one module from the pack of five1$0.66 / packaliexpress.us
8-LED moduleshows Q4, Q3, Q2, Q1 and ~CARRY OUT1$0.38aliexpress.us
Breadboard, 830 points1$3.00amazon.com
Breadboard power module5 V on the rails1$1.00aliexpress.us
USB-to-DC cable, 9 Vpowers the module from a USB charger1$1.17aliexpress.us
Male-male Dupont jumpers11 wires on the board, two of them the mode wires11$1.30 / packaliexpress.us
Male-female Dupont jumpers12 leads to the modules12$1.30 / packaliexpress.us

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

Set the clock slow. At about 1 Hz you can read each number on the LEDs before the next one comes. Faster, Q1 blinks too quickly to follow, but Q4 still shows the counting.

4The chip, pin by pin

The 4029 is CMOS 4000B series: it works 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. Here the four JAM inputs and ~CARRY IN go to GND. The drawing shows the chip from above, the way it sits on the breadboard: notch on the left, pin 1 at the bottom left, pins numbered counter-clockwise. Blue arrows are inputs, orange arrows are outputs.

4029: presettable up/down counter, binary or decade

1PE2Q43J44J15CI6Q17CO8VSS9B/D10U/D11Q212J213J314Q315CLK16VDD4029up/down counter
CD4029B. The triangle at CLOCK marks an edge-triggered input. JAM1–JAM4 are J1–J4. · SVG · PNG

Polarity. The count changes on the rising edge of CLOCK while ~CARRY IN is low. PRESET ENABLE is active high and asynchronous: while it is 1, the count equals the JAM inputs, whatever the clock does. ~CARRY IN and ~CARRY OUT are active low: 0 means “count” and “last count”. UP/DOWN = 1 counts up, BINARY/DECADE = 1 counts in binary.

The outputs are scattered over both rows: Q1 and Q4 at the bottom, Q2 and Q3 at the top. Q1 is the lowest bit, weight 1; Q4 the highest, weight 8.

PinNameDirectionFunctionIn this circuit
1PRESET ENABLEinput1 loads the JAM inputs at once, without the clock. Active highRST
2Q4outputcount, bit 3 (weight 8)Q4
3JAM4inputpreset value, bit 3GND
4JAM1inputpreset value, bit 0GND
5CARRY INinput0 lets the counter count, 1 holds it. Active lowGND
6Q1outputcount, bit 0 (weight 1)Q1
7CARRY OUToutput0 at the last count (9 or 15 up, 0 down) while ~CARRY IN is 0. Active lowCO
8VSSpowerground, 0 VGND
9BINARY/DECADEinput1 = binary, 0 to 15; 0 = decade, 0 to 9BIN (GND)
10UP/DOWNinput1 = count up, 0 = count downUP (+5V)
11Q2outputcount, bit 1 (weight 2)Q2
12JAM2inputpreset value, bit 1GND
13JAM3inputpreset value, bit 2GND
14Q3outputcount, bit 2 (weight 4)Q3
15CLOCKinputthe count changes on the rising edge, 0 to 1CLK
16VDDpowersupply, +5 V (3 to 18 V allowed)+5V

The datasheet does not say what the 4029 does in decade mode at counts 10–15, which it reaches when you switch from binary to decade at such a count. That makes a good experiment: see the tasks in section 15.

5Schematic 1: register and next-state logic

NEXT STATEup: q = last ? 0 : q + 1down: q = 0 ? last : q − 1last = binary ? 15 : 9DQR4 × D flip-flop444qLEDs 1-4CARRYup ? q == last : q == 04COLED 6upbinary~1 HzRclkrst
The counter without the chip, at the register-transfer level: a 4-bit register of four D flip-flops, the next-state logic and the carry logic. Thick lines are buses of four bits. This is what up_down_counter.sv describes. · SVG · PNG

Read it as a loop. The register holds the count q. The next-state block computes from q, up and binary what q should be after the next edge; the register takes it at that edge. The carry block compares q with the last count and drives ~CO low there. The reset clears the register at once.

The 4029 does the same with toggle flip-flops and a different gate network, which the datasheet shows. The generic design describes the behaviour, not that particular network; synthesis builds its own gates from it.

6Schematic 2: connections of the chip

12345678910111213141516PEQ4J4J1CIQ1COB/DU/DQ2J2J3Q3CLK4029up/down counterCLKRSTQ4Q3Q2Q1COclockresetLEDs 1-4, 6UP→ +5VBIN→ GND+5V
The same circuit as a chip, pin by pin. The chip is drawn from above with the notch on the left; pin numbers are next to the pins. The two boxes UP and BIN at the top are the mode wires; the other boxes are the modules. · SVG · PNG

Every connection of the circuit, net by net. up_down_counter_chips.sv in section 10 is written from the same list.

NetFromToWire
CLK555 clock module, OUT4029 15 (CLK)M-F
RSTreset button, OUT4029 1 (PE)M-F
UPUP wire: +5V4029 10 (U/D)M-M
BINBIN wire: GND4029 9 (B/D)M-M
Q44029 2 (Q4)LED module, LED 1M-F
Q34029 14 (Q3)LED module, LED 2M-F, M-M
Q24029 11 (Q2)LED module, LED 3M-F, M-M
Q14029 6 (Q1)LED module, LED 4M-F
CO4029 7 (CO)LED module, LED 6M-F
+5V+5V4029 16 (VDD)
GNDGND4029 8 (VSS), 4029 3 (J4), 4029 13 (J3), 4029 4 (J1), 4029 12 (J2), 4029 5 (CI)

7Schematic 3: the breadboard

−+−+1234567891011121314151617181920212223242526272829303132333435363738394041424344abcdefghij5V5VPOWER MODULE · 5V9V USB-DC4029UPBINQ3Q2−OUT+555CLOCK 555~1 Hz+OUT−RESETbuttonG1Q42Q33Q24Q156CO788-LED MODULEQ4 Q3 Q2 Q1 · ~CO
Every wire in its hole. Column numbers are printed along the top; rows a–e are above the gap, f–j below it. The clock module hangs above the board, the reset button and the LED module below it. The two mode wires, UP and BIN, go from pins 10 and 9 to the top rails. Q3 and Q2 are on the top row, so two wires bring them down to columns 28 and 29 for the LED module. The board goes on to column 63 on the right. · SVG · PNG
CLKRSTUPBINQ4Q3Q2Q1CO+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 4029 across the gap, notch to the left, pin 1 in hole 18f.
  3. Power: a red wire from pin 16 to the top + rail, a black wire from pin 8 to the bottom − rail.
  4. The fixed inputs: JAM4, JAM1 and ~CARRY IN (pins 3, 4, 5) to the bottom − rail, JAM3 and JAM2 (pins 13, 12) to the top − rail.
  5. The mode wires: UP/DOWN (pin 10) to the top + rail, BINARY/DECADE (pin 9) to the top − rail.
  6. The two wires that bring Q3 and Q2 down to the bottom half.
  7. With the power off, the modules: the clock module above the board, the reset button and the LED module below. Connect − and G first.
  8. Turn the power on and set the clock module to about 1 Hz.

Wiring checklist

·

#NetFromTo
Power (red to +, black to −) · 2 wires
1+5V18a (4029 pin 16, VDD)top + rail, column 18
2GND25j (4029 pin 8, VSS)bottom − rail, column 25
Fixed inputs: CMOS inputs must not float · 5 wires
5GND20j (4029 pin 3, J4)bottom − rail, column 20
6GND21a (4029 pin 13, J3)top − rail, column 21
7GND21j (4029 pin 4, J1)bottom − rail, column 21
8GND22a (4029 pin 12, J2)top − rail, column 22
9GND22j (4029 pin 5, CI)bottom − rail, column 22
Mode wires: move them between + and − to change the mode · 2 wires
3UP24a (4029 pin 10, U/D)top + rail, column 24
4BIN25a (4029 pin 9, B/D)top − rail, column 25
Signal wires · 2 wires
10Q320c (4029 pin 14, Q3)28f
11Q223d (4029 pin 11, Q2)29f
Modules on male-female jumpers · 12 wires
12GND555 clock module, −top − rail, column 13
13CLK555 clock module, OUT19a (4029 pin 15, CLK)
14+5V555 clock module, +top + rail, column 15
15+5Vreset button, +bottom + rail, column 11
16RSTreset button, OUT18j (4029 pin 1, PE)
17GNDreset button, −bottom − rail, column 13
18GNDLED module, Gbottom − rail, column 23
19Q4LED module, LED 119j (4029 pin 2, Q4)
20Q3LED module, LED 228j
21Q2LED module, LED 329j
22Q1LED module, LED 423j (4029 pin 6, Q1)
23COLED module, LED 624j (4029 pin 7, CO)

Test it

If it does not work: if the LEDs show 0000 and nothing happens, check the clock lead to pin 15, that PRESET ENABLE (pin 1) is 0 when the button is up, and that ~CARRY IN (pin 5) is at GND. If the count jumps or the LEDs show odd patterns, look for a JAM input that is not tied. Two LEDs swapped means the Q2 and Q3 wires are crossed.

8SystemVerilog: the generic design

up_down_counter.sv describes schematic 1. The always_ff block is the register and the next-state logic together: at each rising edge it stores the next count, and rst in the sensitivity list makes the reset asynchronous. The assign is the carry logic. It is synthesizable.

up_down_counter.svfile
// Exercise B5: a 4-bit up/down counter, binary (0-15) or decade (0-9).
//
// Generic version that matches schematic 1: a 4-bit register with an
// asynchronous reset, the next-state logic that adds or subtracts 1 and
// wraps around, and the logic for the carry output.  Not tied to any chip.
// Synthesizable.

module up_down_counter
(
    input  logic       clk,
    input  logic       rst,          // 1 = count 0 at once, like PRESET ENABLE of the 4029 with JAM = 0
    input  logic       up,           // 1 = count up, 0 = count down
    input  logic       binary,       // 1 = count 0-15, 0 = count 0-9

    output logic [3:0] q,            // The count
    output logic       carry_out_n   // 0 at the last count: 9 or 15 up, 0 down
);

    wire [3:0] last = binary ? 4'd15 : 4'd9;

    //------------------------------------------------------------------------
    // Register and next-state logic

    always_ff @ (posedge clk or posedge rst)
        if (rst)
            q <= 4'd0;
        else if (up)
            q <= q == last ? 4'd0 : q + 4'd1;
        else
            q <= q == 4'd0 ? last : q - 4'd1;

    //------------------------------------------------------------------------
    // Carry: active low, like CARRY OUT of the 4029

    assign carry_out_n = ~ (up ? q == last : q == 4'd0);

endmodule

last is 9 or 15. The conditional operator c ? x : y is a multiplexer: in hardware all three branches are computed and the condition picks one.

9SystemVerilog model of the chip

One module with ports named as in the datasheet and the pin number of each port in a comment. It leaves out the power pins, because in SystemVerilog a wire simply has the value 0 or 1.

cd4029.svfile
// CD4029B: presettable up/down counter, binary or decade (BCD).
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (8)
// and VDD (16), are left out.
//
// The count advances on the rising edge of CLOCK while CARRY IN is low.
// UP/DOWN: 1 = count up, 0 = count down.  BINARY/DECADE: 1 = 0 to 15,
// 0 = 0 to 9.  PRESET ENABLE is active high and asynchronous: while it is
// 1 the count takes the value of the JAM inputs at once, without the clock.
// CARRY OUT is active low: it is 0 at the last count (15 or 9 up, 0 down)
// while CARRY IN is low.
//
// Synthesizable by tools that support an asynchronous load, such as Yosys.
// The model loads JAM when PRESET ENABLE rises; with the JAM inputs tied,
// as in the exercises, that is the same as the chip.  For an FPGA tie the
// JAM inputs to 0: then the load is an ordinary asynchronous reset.
//
// The datasheet does not say what the chip does in decade mode at counts
// 10 to 15, which it reaches when you switch from binary to decade.  The
// model counts up from them to 15 and then 0, and down as usual.

module cd4029
(
    input  logic preset_enable,  // Pin 1:  1 = count = JAM at once
    output logic q4,             // Pin 2
    input  logic jam4,           // Pin 3
    input  logic jam1,           // Pin 4
    input  logic carry_in_n,     // Pin 5:  0 = count, 1 = hold
    output logic q1,             // Pin 6
    output logic carry_out_n,    // Pin 7:  0 at the last count
                                 // Pin 8:  VSS
    input  logic binary_decade,  // Pin 9:  1 = binary, 0 = decade
    input  logic up_down,        // Pin 10: 1 = up, 0 = down
    output logic q2,             // Pin 11
    input  logic jam2,           // Pin 12
    input  logic jam3,           // Pin 13
    output logic q3,             // Pin 14
    input  logic clock           // Pin 15
                                 // Pin 16: VDD
);

    logic [3:0] count;

    wire  [3:0] jam  = { jam4, jam3, jam2, jam1 };
    wire  [3:0] last = binary_decade ? 4'd15 : 4'd9;

    always_ff @ (posedge clock or posedge preset_enable)
        if (preset_enable)
            count <= jam;
        else if (~ carry_in_n)
        begin
            if (up_down)
                count <= count == last  ? 4'd0 : count + 4'd1;
            else
                count <= count == 4'd0  ? last : count - 4'd1;
        end

    assign { q4, q3, q2, q1 } = count;

    assign carry_out_n = carry_in_n | (up_down ? count != last : count != 4'd0);

endmodule

The model loads JAM when PRESET ENABLE rises. That is an asynchronous load of a value that is not a constant, which Yosys can synthesize but many FPGA tools cannot; with the JAM inputs tied to 0, as here, it is an ordinary asynchronous reset. For counts 10–15 in decade mode the model does what the comment says, because the datasheet does not say what the chip does.

10SystemVerilog: the chip-level design

up_down_counter_chips.sv connects the chip model exactly as schematic 2 and the breadboard connect the chip, with the same ports as up_down_counter.sv. The tied inputs go to gnd; the two pins with mode wires go to the ports up and binary, because on the breadboard you move those wires. 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.

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

module up_down_counter_chips
(
    input  logic       clk,
    input  logic       rst,
    input  logic       up,
    input  logic       binary,
    output logic [3:0] q,
    output logic       carry_out_n
);

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

    wire gnd = 1'b0;

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

    // U1: CD4029 presettable up/down counter, binary or decade, pin 1 in column 18

    cd4029 i_u1
    (
        .preset_enable ( rst         ),  // Pin 1 <- reset button
        .q4            ( q [3]       ),  // Pin 2 -> Q4
        .jam4          ( gnd         ),  // Pin 3 <- GND
        .jam1          ( gnd         ),  // Pin 4 <- GND
        .carry_in_n    ( gnd         ),  // Pin 5 <- GND
        .q1            ( q [0]       ),  // Pin 6 -> Q1
        .carry_out_n   ( carry_out_n ),  // Pin 7 -> ~CO
        .binary_decade ( binary      ),  // Pin 9 <- BIN wire, at GND on the breadboard
        .up_down       ( up          ),  // Pin 10 <- UP wire, at +5V on the breadboard
        .q2            ( q [1]       ),  // Pin 11 -> Q2
        .jam2          ( gnd         ),  // Pin 12 <- GND
        .jam3          ( gnd         ),  // Pin 13 <- GND
        .q3            ( q [2]       ),  // Pin 14 -> Q3
        .clock         ( clk         )   // Pin 15 <- 555 clock module
    );

endmodule

11Testbench and simulation scripts

tb.sv runs both designs side by side from the same clock and reset and compares them with a reference model: the count as an integer, with the remainder of a division by 10 or 16. Like the testbenches of Basics-Graphics-Music, it drives and checks signals only at rising clock edges. It counts up and down in both modes, sees every wrap-around and every carry, and resets the counter in the middle of a count: both designs must go to 0 at once, not at the next clock edge. It switches to decade mode only at counts 0–9. At the end it prints PASS or FAIL.

tb.sv188 lines · show the codefile
// Testbench for exercise B5.
//
// Runs the generic design (up_down_counter.sv) and the chip-level design
// (up_down_counter_chips.sv) side by side and compares both with a reference
// model.  Works with Icarus Verilog, Verilator (--binary) and Questa.
//
// Like the testbenches of Basics-Graphics-Music, it drives and samples
// signals only at rising clock edges.  It counts up and down in both modes,
// sees every wrap-around, and resets the counter in the middle of a count.
// It switches to decade mode only at counts 0-9, because the datasheet does
// not say what the 4029 does in decade mode at counts 10-15.

// 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       rst;
    logic       up;
    logic       binary;

    wire  [3:0] q,           q_chips;
    wire        carry_out_n, carry_out_n_chips;

    up_down_counter i_generic
    (
        .clk         ( clk         ),
        .rst         ( rst         ),
        .up          ( up          ),
        .binary      ( binary      ),
        .q           ( q           ),
        .carry_out_n ( carry_out_n )
    );

    up_down_counter_chips i_chips
    (
        .clk         ( clk               ),
        .rst         ( rst               ),
        .up          ( up                ),
        .binary      ( binary            ),
        .q           ( q_chips           ),
        .carry_out_n ( carry_out_n_chips )
    );

    //------------------------------------------------------------------------
    // Clock with a period of 10 ns.
    // On the breadboard one period is about a second.

    initial
    begin
        clk = '0;

        forever
            # 5 clk = ~ clk;
    end

    //------------------------------------------------------------------------
    // Reference model: the count as an integer, with the remainder of the
    // division by the modulus.  rst sets 0 at once, without the clock.

    int count;

    wire [31:0] modulus = binary ? 32'd16 : 32'd10;

    always @ (posedge clk or posedge rst)
        if (rst)
            count <= 0;
        else if (up)
            count <= (count + 1) % modulus;
        else
            count <= (count + modulus - 1) % modulus;

    wire carry_expected = up ? count == modulus - 1 : count == 0;

    wire ok_generic = q       === 4' (count) && carry_out_n       === ~ carry_expected;
    wire ok_chips   = q_chips === 4' (count) && carry_out_n_chips === ~ carry_expected;

    //------------------------------------------------------------------------
    // Checking at every rising clock edge.  At the edge both designs and the
    // model still show the clock cycle that ends there, the same values that
    // a flip-flop would sample.

    // Initial values are fine in a testbench, and the checker samples rst at
    // the clock edge on purpose, although the designs reset asynchronously

    // verilator lint_off PROCASSINIT
    // verilator lint_off SYNCASYNCNET

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

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

    logic [3:0] carry_seen = '0;  // Carry seen in: decade up, binary up, decade down, binary down

    always @ (posedge clk)
    begin
        if (rst)
            was_reset <= 1'b1;

        if ((rst | was_reset) & ~ done)
        begin
            cycle    <= cycle + 1;
            n_checks <= n_checks + 2;
            n_errors <= n_errors + (ok_generic ? 0 : 1) + (ok_chips ? 0 : 1)
                                 + (count >= 0 && count < int' (modulus) ? 0 : 1);

            if (~ rst & carry_expected)
                carry_seen [{ ~ up, binary }] <= 1'b1;

            $display ("%5d  %b   %s %s   %2d   %b    %b   %s  %s",
                cycle + 1, rst, up ? "up  " : "down", binary ? "bin" : "dec", q, q, carry_out_n,
                ok_generic ? "ok     " : "WRONG  ", ok_chips ? "ok   " : "WRONG");
        end
    end

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

    task automatic run (input logic u, input logic bin, input int n);
        up     <= u;
        binary <= bin;
        repeat (n) @ (posedge clk);
    endtask

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

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

        $display ("cycle  rst  mode      q   bits  ~CO   generic  chips");

        // Before reset the count is unknown, as after power-up

        up     <= '1;
        binary <= '0;
        rst    <= 'x;
        repeat (3) @ (posedge clk);
        rst    <= '1;
        repeat (3) @ (posedge clk);
        rst    <= '0;

        run (1, 0, 13);  // Decade, up:   1 ... 9, 0, 1, 2, 3
        run (1, 1, 14);  // Binary, up:   4 ... 15, 0, 1
        run (0, 1,  8);  // Binary, down: 0, 15, 14, 13, 12, 11, 10, 9
        run (0, 0, 12);  // Decade, down: 8 ... 0, 9, 8, 7

        // Reset in the middle of the count.  Both designs must go to 0 at
        // once, not at the next clock edge, like PRESET ENABLE of the 4029.

        rst <= '1;
        repeat (2) @ (posedge clk);
        rst <= '0;

        run (1, 0, 4);

        // 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 && carry_seen == 4'b1111)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, carry seen %b", n_errors, n_checks, carry_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 B5: 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 up_down_counter.sv up_down_counter_chips.sv cd4029.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 B5: 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 up_down_counter.sv up_down_counter_chips.sv cd4029.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 B5: 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 up_down_counter.sv up_down_counter_chips.sv cd4029.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  rst  mode      q   bits  ~CO   generic  chips
    1  1   up   dec    0   0000    1   ok       ok   
    2  1   up   dec    0   0000    1   ok       ok   
    3  1   up   dec    0   0000    1   ok       ok   
    4  0   up   dec    0   0000    1   ok       ok   
    5  0   up   dec    1   0001    1   ok       ok   
    6  0   up   dec    2   0010    1   ok       ok   
    7  0   up   dec    3   0011    1   ok       ok   
    8  0   up   dec    4   0100    1   ok       ok   
    9  0   up   dec    5   0101    1   ok       ok   
   10  0   up   dec    6   0110    1   ok       ok   
   11  0   up   dec    7   0111    1   ok       ok   
   12  0   up   dec    8   1000    1   ok       ok   
   13  0   up   dec    9   1001    0   ok       ok   
   14  0   up   dec    0   0000    1   ok       ok   
   15  0   up   dec    1   0001    1   ok       ok   
   16  0   up   dec    2   0010    1   ok       ok   
   17  0   up   bin    3   0011    1   ok       ok   
   18  0   up   bin    4   0100    1   ok       ok   
   19  0   up   bin    5   0101    1   ok       ok   
   20  0   up   bin    6   0110    1   ok       ok   
   21  0   up   bin    7   0111    1   ok       ok   
   22  0   up   bin    8   1000    1   ok       ok   
   23  0   up   bin    9   1001    1   ok       ok   
   24  0   up   bin   10   1010    1   ok       ok   
   25  0   up   bin   11   1011    1   ok       ok   
   26  0   up   bin   12   1100    1   ok       ok   
   27  0   up   bin   13   1101    1   ok       ok   
   28  0   up   bin   14   1110    1   ok       ok   
   29  0   up   bin   15   1111    0   ok       ok   
   30  0   up   bin    0   0000    1   ok       ok   
   31  0   down bin    1   0001    1   ok       ok   
   32  0   down bin    0   0000    0   ok       ok   
   33  0   down bin   15   1111    1   ok       ok   
   34  0   down bin   14   1110    1   ok       ok   
   35  0   down bin   13   1101    1   ok       ok   
   36  0   down bin   12   1100    1   ok       ok   
   37  0   down bin   11   1011    1   ok       ok   
   38  0   down bin   10   1010    1   ok       ok   
   39  0   down dec    9   1001    1   ok       ok   
   40  0   down dec    8   1000    1   ok       ok   
   41  0   down dec    7   0111    1   ok       ok   
   42  0   down dec    6   0110    1   ok       ok   
   43  0   down dec    5   0101    1   ok       ok   
   44  0   down dec    4   0100    1   ok       ok   
   45  0   down dec    3   0011    1   ok       ok   
   46  0   down dec    2   0010    1   ok       ok   
   47  0   down dec    1   0001    1   ok       ok   
   48  0   down dec    0   0000    0   ok       ok   
   49  0   down dec    9   1001    1   ok       ok   
   50  0   down dec    8   1000    1   ok       ok   
   51  1   down dec    0   0000    0   ok       ok   
   52  1   down dec    0   0000    0   ok       ok   
   53  0   up   dec    0   0000    1   ok       ok   
   54  0   up   dec    1   0001    1   ok       ok   
   55  0   up   dec    2   0010    1   ok       ok   
   56  0   up   dec    3   0011    1   ok       ok   
tb.sv:175: $finish called at 595000 (1ps)
PASS: 112 checks, no errors

To see that the testbench catches mistakes, break something and run it again: change 4'd9 to 4'd8 in up_down_counter.sv, or remove or posedge rst there. The script reports FAIL and the trace shows the cycles 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 up_down_counter.sv.
  3. Run ./03_synthesize_for_fpga.bash and ./04_configure_fpga.bash; the first run asks which board you have.

The counter runs from slow_clk, which every BGM board makes at 1 Hz. BGM makes it in peripherals/slow_clk_gen.sv: a counter on the board clock toggles a flip-flop, and on AMD (Xilinx) and Intel (Altera) FPGAs a BUFG or global primitive puts that signal on the FPGA clock network, so it reaches all flip-flops like a real clock. The counter counts up; it counts down while key 0 is pressed, and in binary while key 1 is pressed. The LEDs show the count and ~CO, and the display shows the count in hexadecimal with BGM's seven_segment_display.

bgm_lab/lab_top.sv112 lines · show the codefile
// Exercise B5 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 up_down_counter.sv.  For the chip-level
// design add up_down_counter_chips.sv and cd4029.sv instead, and change the
// module name below.
//
// The counter runs from slow_clk, the 1 Hz clock that every BGM board
// wrapper makes, like the breadboard with the 555 module.  The reset button
// of the board resets the count.  It counts up, or down while key 0 is
// pressed; it counts 0-9, or 0-15 while key 1 is pressed.  LEDs 0-3 show
// the count, LED 4 shows ~CARRY OUT, and the display shows the count in
// hexadecimal with seven_segment_display from labs/common.

`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 [3:0] q;
    logic       carry_out_n;

    up_down_counter i_up_down_counter
    (
        .clk         ( slow_clk    ),
        .rst         ( rst         ),
        .up          ( ~ key [0]   ),
        .binary      ( key [1]     ),
        .q           ( q           ),
        .carry_out_n ( carry_out_n )
    );

    assign led = w_led' ({ carry_out_n, q });

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

    seven_segment_display # (w_digit) i_7segment
    (
        .clk      ( clk                   ),
        .rst      ( rst                   ),
        .number   ( (w_digit * 4)' (q)    ),
        .dots     ( w_digit' (0)          ),
        .abcdefgh ( abcdefgh              ),
        .digit    ( digit                 )
    );

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/4_binary_counter.
  2. Replace its hackathon_top.sv with bgm_hackathon/hackathon_top.sv and add up_down_counter.sv.
  3. Run ./03_synthesize_for_fpga.bash and ./04_configure_fpga.bash.

Keys 0 and 1 work as in lab_top. The rightmost digit shows the count, the LEDs the count and ~CO, and the screen four bars, one per bit, Q4 on the left.

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

// Exercise B5 in the hackathon setup of Basics-Graphics-Music (BGM):
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy hackathon/problems/4_binary_counter, replace its hackathon_top.sv
// with this file and add up_down_counter.sv.
//
// The counter runs from slow_clock, one beat per second, like the
// breadboard with the 555 module.  It counts up, or down while key 0 is
// pressed; it counts 0-9, or 0-15 while key 1 is pressed.  The LEDs show
// the count and ~CARRY OUT, the rightmost digit shows the count, and the
// screen shows four bars, one per bit, Q4 on the left.

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 [3:0] q;
    logic       carry_out_n;

    up_down_counter i_up_down_counter
    (
        .clk         ( slow_clock  ),
        .rst         ( reset       ),
        .up          ( ~ key [0]   ),
        .binary      ( key [1]     ),
        .q           ( q           ),
        .carry_out_n ( carry_out_n )
    );

    assign led = { 3'b0, carry_out_n, q };

    seven_segment_display # (.w_digit (8)) i_7segment
    (
        .clk      ( clock          ),
        .rst      ( reset          ),
        .number   ( 32' (q)        ),
        .dots     ( '0             ),
        .abcdefgh ( abcdefgh       ),
        .digit    ( digit          )
    );

    //------------------------------------------------------------------------
    // Four bars on the 480 x 272 screen, one per bit of the count: bright
    // green for 1, dim for 0.  Bit 3 is on the left, as on the LEDs.

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

        for (int i = 0; i < 4; i ++)
            if (x >= 9' (72 + i * 96) & x < 9' (144 + i * 96) & y >= 60 & y < 212)
                green = q [3 - i] ? 63 : 12;
    end

endmodule

14On a chip: Tiny Tapeout

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

The demo board makes the project clock itself and can set it anywhere from 1 Hz to 66.5 MHz (see Clock in the Tiny Tapeout docs). Set it to 1 Hz, and project.v connects clk straight to the counter, just as the 555 module clocks the 4029 on the breadboard. Switch 0 = count up, switch 1 = binary. The display shows the count as a hexadecimal digit, and the dot lights at the last count.

tiny_tapeout/project.v75 lines · show the codefile
/*
 * Exercise B5 on Tiny Tapeout: an up/down counter shown as a hexadecimal
 * digit on the 7-segment display of the demo board.
 *
 * Add up_down_counter.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
);

    // Set the project clock to 1 Hz (clock_hz: 1 in info.yaml): the demo
    // board makes it, and clk drives the counter directly, like the 555
    // module on the breadboard.  Switch 0 = count up, switch 1 = binary
    // (0-15) instead of decade (0-9).  The reset button of the board is rst_n.

    wire [3:0] q;
    wire       carry_out_n;

    up_down_counter i_up_down_counter (
        .clk         ( clk         ),
        .rst         ( ~ rst_n     ),
        .up          ( ui_in [0]   ),
        .binary      ( ui_in [1]   ),
        .q           ( q           ),
        .carry_out_n ( carry_out_n )
    );

    // 7-segment display: uo_out [0] is segment a, ..., uo_out [6] is g,
    // uo_out [7] is the dot.  The digit shows the count in hexadecimal, the
    // dot lights at the last count (CARRY OUT is active low).

    reg [6:0] gfedcba;

    always @(*)
        case (q)
        4'h0: gfedcba = 7'b011_1111;
        4'h1: gfedcba = 7'b000_0110;
        4'h2: gfedcba = 7'b101_1011;
        4'h3: gfedcba = 7'b100_1111;
        4'h4: gfedcba = 7'b110_0110;
        4'h5: gfedcba = 7'b110_1101;
        4'h6: gfedcba = 7'b111_1101;
        4'h7: gfedcba = 7'b000_0111;
        4'h8: gfedcba = 7'b111_1111;
        4'h9: gfedcba = 7'b110_1111;
        4'ha: gfedcba = 7'b111_0111;
        4'hb: gfedcba = 7'b111_1100;
        4'hc: gfedcba = 7'b011_1001;
        4'hd: gfedcba = 7'b101_1110;
        4'he: gfedcba = 7'b111_1001;
        4'hf: gfedcba = 7'b111_0001;
        endcase

    assign uo_out  = { ~ carry_out_n, gfedcba };

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

    // List all unused inputs to prevent warnings

    wire _unused = & { ena, ui_in [7:2], uio_in, 1'b0 };

endmodule

In info.yaml set the clock to 1 Hz, list both files and use the module name as the top module:

project:
  clock_hz:   1                 # the demo board makes a 1 Hz clock
  top_module: "tt_um_example"   # rename to tt_um_<your GitHub name>_up_down_counter
  source_files:
    - "project.v"
    - "up_down_counter.sv"
No clock divider on a chip. BGM makes slow_clk with a counter, but on AMD and Intel FPGAs it routes that signal onto the clock network with BUFG or global (section 12). In an ASIC a counter bit used as a clock is bad practice: it is a second clock with its own clock tree and timing that nobody controls. Here the board makes the 1 Hz clock, so no divider is needed. When a chip needs a slow tick from a fast clock, keep one clock and use a clock enable: a counter like this one, running on the fast clock, makes a one-clock pulse at its last count, and the slow logic changes only on the clock edges where that pulse is 1.

15Going further

Tasks for students

Files of this exercise

Sources

The exercise is the third of the Basics list in “An improved way of teaching school kids digital electronics using venerable small-scale integration ICs”; lesson 1.3 of the Habr article about the electronics course uses the 4029 with the assembled 555 module. The 4029 is described in the Texas Instruments datasheet for the CD4029B, including its logic diagram and the timing diagrams for both modes.