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.
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.
- It is the simplest machine whose next state is computed from its present state: a register plus next-state logic, the structure of every synchronous design.
- Counting in binary on LEDs teaches binary numbers better than any table: watch which bit changes when.
- ~CARRY OUT is an active-low output: the LED is lit when nothing happens and goes dark at the event. Active-low signals are common, and they confuse everybody once.
- The 4029 resets through a parallel load: PRESET ENABLE loads the JAM inputs, which are tied to 0. Loading a value and resetting are the same operation.
2The key element: a counter
4029 counter
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
| rst | clk | D | Q after |
|---|---|---|---|
| 1 | any | any | 0, at once |
| 0 | ↑ | 0 | 0 |
| 0 | ↑ | 1 | 1 |
| 0 | no edge | any | keeps Q |
The register of the counter is four of these, on one clock. The reset clears all four at once.
The four modes
| U/D | B/D | Count | ~CO = 0 at |
|---|---|---|---|
| 1 | 0 | 0, 1, 2 … 9, 0 | 9 |
| 1 | 1 | 0, 1, 2 … 15, 0 | 15 |
| 0 | 0 | 9, 8 … 1, 0, 9 | 0 |
| 0 | 1 | 15, 14 … 1, 0, 15 | 0 |
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
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 · PNG3Parts
| Part | In this circuit | Qty | Price | Supplier |
|---|---|---|---|---|
| CD4029 | up/down counter, binary or decade | 1 | $0.80 | Elexp (elexp.com) |
| 555 clock module | the clock, set to about 1 Hz | 1 | $0.53 | aliexpress.us |
| Button module | reset; one module from the pack of five | 1 | $0.66 / pack | aliexpress.us |
| 8-LED module | shows Q4, Q3, Q2, Q1 and ~CARRY OUT | 1 | $0.38 | aliexpress.us |
| Breadboard, 830 points | 1 | $3.00 | amazon.com | |
| Breadboard power module | 5 V on the rails | 1 | $1.00 | aliexpress.us |
| USB-to-DC cable, 9 V | powers the module from a USB charger | 1 | $1.17 | aliexpress.us |
| Male-male Dupont jumpers | 11 wires on the board, two of them the mode wires | 11 | $1.30 / pack | aliexpress.us |
| Male-female Dupont jumpers | 12 leads to the modules | 12 | $1.30 / pack | aliexpress.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.
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
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.
| Pin | Name | Direction | Function | In this circuit |
|---|---|---|---|---|
| 1 | PRESET ENABLE | input | 1 loads the JAM inputs at once, without the clock. Active high | RST |
| 2 | Q4 | output | count, bit 3 (weight 8) | Q4 |
| 3 | JAM4 | input | preset value, bit 3 | GND |
| 4 | JAM1 | input | preset value, bit 0 | GND |
| 5 | CARRY IN | input | 0 lets the counter count, 1 holds it. Active low | GND |
| 6 | Q1 | output | count, bit 0 (weight 1) | Q1 |
| 7 | CARRY OUT | output | 0 at the last count (9 or 15 up, 0 down) while ~CARRY IN is 0. Active low | CO |
| 8 | VSS | power | ground, 0 V | GND |
| 9 | BINARY/DECADE | input | 1 = binary, 0 to 15; 0 = decade, 0 to 9 | BIN (GND) |
| 10 | UP/DOWN | input | 1 = count up, 0 = count down | UP (+5V) |
| 11 | Q2 | output | count, bit 1 (weight 2) | Q2 |
| 12 | JAM2 | input | preset value, bit 1 | GND |
| 13 | JAM3 | input | preset value, bit 2 | GND |
| 14 | Q3 | output | count, bit 2 (weight 4) | Q3 |
| 15 | CLOCK | input | the count changes on the rising edge, 0 to 1 | CLK |
| 16 | VDD | power | supply, +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
up_down_counter.sv describes. · SVG · PNGRead 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
Every connection of the circuit, net by net. up_down_counter_chips.sv in section 10 is written from
the same list.
| Net | From | To | Wire |
|---|---|---|---|
| CLK | 555 clock module, OUT | 4029 15 (CLK) | M-F |
| RST | reset button, OUT | 4029 1 (PE) | M-F |
| UP | UP wire: +5V | 4029 10 (U/D) | M-M |
| BIN | BIN wire: GND | 4029 9 (B/D) | M-M |
| Q4 | 4029 2 (Q4) | LED module, LED 1 | M-F |
| Q3 | 4029 14 (Q3) | LED module, LED 2 | M-F, M-M |
| Q2 | 4029 11 (Q2) | LED module, LED 3 | M-F, M-M |
| Q1 | 4029 6 (Q1) | LED module, LED 4 | M-F |
| CO | 4029 7 (CO) | LED module, LED 6 | M-F |
| +5V | +5V | 4029 16 (VDD) | |
| GND | GND | 4029 8 (VSS), 4029 3 (J4), 4029 13 (J3), 4029 4 (J1), 4029 12 (J2), 4029 5 (CI) |
7Schematic 3: the breadboard
Build it step by step
- 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.
- Insert the 4029 across the gap, notch to the left, pin 1 in hole 18f.
- Power: a red wire from pin 16 to the top + rail, a black wire from pin 8 to the bottom − rail.
- 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.
- The mode wires: UP/DOWN (pin 10) to the top + rail, BINARY/DECADE (pin 9) to the top − rail.
- The two wires that bring Q3 and Q2 down to the bottom half.
- With the power off, the modules: the clock module above the board, the reset button and the LED module below. Connect − and G first.
- Turn the power on and set the clock module to about 1 Hz.
Wiring checklist
| # | Net | From | To | |
|---|---|---|---|---|
| Power (red to +, black to −) · 2 wires | ||||
| 1 | +5V | 18a (4029 pin 16, VDD) | top + rail, column 18 | |
| 2 | GND | 25j (4029 pin 8, VSS) | bottom − rail, column 25 | |
| Fixed inputs: CMOS inputs must not float · 5 wires | ||||
| 5 | GND | 20j (4029 pin 3, J4) | bottom − rail, column 20 | |
| 6 | GND | 21a (4029 pin 13, J3) | top − rail, column 21 | |
| 7 | GND | 21j (4029 pin 4, J1) | bottom − rail, column 21 | |
| 8 | GND | 22a (4029 pin 12, J2) | top − rail, column 22 | |
| 9 | GND | 22j (4029 pin 5, CI) | bottom − rail, column 22 | |
| Mode wires: move them between + and − to change the mode · 2 wires | ||||
| 3 | UP | 24a (4029 pin 10, U/D) | top + rail, column 24 | |
| 4 | BIN | 25a (4029 pin 9, B/D) | top − rail, column 25 | |
| Signal wires · 2 wires | ||||
| 10 | Q3 | 20c (4029 pin 14, Q3) | 28f | |
| 11 | Q2 | 23d (4029 pin 11, Q2) | 29f | |
| Modules on male-female jumpers · 12 wires | ||||
| 12 | GND | 555 clock module, − | top − rail, column 13 | |
| 13 | CLK | 555 clock module, OUT | 19a (4029 pin 15, CLK) | |
| 14 | +5V | 555 clock module, + | top + rail, column 15 | |
| 15 | +5V | reset button, + | bottom + rail, column 11 | |
| 16 | RST | reset button, OUT | 18j (4029 pin 1, PE) | |
| 17 | GND | reset button, − | bottom − rail, column 13 | |
| 18 | GND | LED module, G | bottom − rail, column 23 | |
| 19 | Q4 | LED module, LED 1 | 19j (4029 pin 2, Q4) | |
| 20 | Q3 | LED module, LED 2 | 28j | |
| 21 | Q2 | LED module, LED 3 | 29j | |
| 22 | Q1 | LED module, LED 4 | 23j (4029 pin 6, Q1) | |
| 23 | CO | LED module, LED 6 | 24j (4029 pin 7, CO) | |
Test it
- Press reset: LEDs 1–4 go dark (0000). Release it: the LEDs count 0001, 0010, 0011 … 1001 and back to 0000.
- LED 6 (~CO) is lit all the time except at 9 (1001), when it goes dark for one blink.
- Move the BIN wire to the + rail: the counter now goes on to 1111 (15), and ~CO goes dark at 15.
- Move the UP wire to the − rail: the count goes down, and ~CO goes dark at 0.
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.
// 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.
// 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.
// 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.
- Copy
labs/1_basics/1_06_binary_counterto a new directory. - Replace its
lab_top.svwithbgm_lab/lab_top.svfrom this exercise and addup_down_counter.sv. - Run
./03_synthesize_for_fpga.bashand./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.
- Copy
hackathon/problems/4_binary_counter. - Replace its
hackathon_top.svwithbgm_hackathon/hackathon_top.svand addup_down_counter.sv. - Run
./03_synthesize_for_fpga.bashand./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"
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
- What the datasheet does not say. Switch to binary, wait for a count of 12 or more, and switch to decade. Write down what the real 4029 does, then compare with the model, which counts on up to 15. Is the model right?
- Preset. Move JAM1 and JAM4 from GND to +5V: now the reset button loads 9 instead of 0. What does the counter do counting down from 9? Change the testbench to match.
- Hold. Connect ~CARRY IN to a button instead of GND: while the button is pressed, the count stops.
- Two digits. Clock a second 4029 from the first one's ~CARRY OUT: it rises when the first counter goes from 9 to 0. Or chain them the way the datasheet shows, with one clock for both and ~CARRY OUT of the first to ~CARRY IN of the second. Either way you get a counter from 00 to 99.
- A display. With the 4511 and a display from exercise B7, show the count as a digit.
- In SystemVerilog: add a load input and a 4-bit value to load, like JAM and PRESET ENABLE, and test it.
Files of this exercise
- up_down_counter.sv: the generic design (section 8)
- cd4029.sv: the chip model (section 9)
- up_down_counter_chips.sv: the chip-level design (section 10)
- tb.sv and run_icarus.bash, run_verilator.bash, run_questa.bash, clean.bash (section 11)
- bgm_lab/lab_top.sv, bgm_hackathon/hackathon_top.sv, tiny_tapeout/project.v (sections 12–14)
- Drawings as SVG and PNG in images/: the three schematics, the pinout and the waveforms;
the Russian versions end in
_ru
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.