Exercise M10 · mini-project · counter
Johnson counter from a 4015 and a 4069
A shift register whose last stage, inverted, goes back into the first: five flip-flops and one inverter make a ring of ten states. It is the counter inside the 4017 of exercise BB7, built here from a shift register you can watch.
1What it is and why it matters
What it does. The four stages of register A of a 4015 and the first stage of register B form a 5-stage shift register: at every rising clock edge each stage takes the value of the stage before it. The first stage takes NOT Q5, made by an inverter of a 4069. After a reset all stages are 0; then ones march in from Q1 until all five are 1, and then zeros march in until all are 0 again: ten states, then the ring repeats. LEDs 1–5 show Q1–Q5.
How it works. A shift register remembers the last five bits that went in. Feeding in the inverse of the oldest bit makes the register fill up and empty out by itself. A Johnson counter, or twisted-ring counter, of n flip-flops has 2n states, and each state differs from the next in exactly one bit.
Where it is used. The 4017 is a Johnson counter with ten decoding gates (BB7), and traffic lights and light chasers are built on it (M11). Because only one bit changes per step, decoding a Johnson counter needs one 2-input gate per state and never glitches. Johnson counters also make clocks with several phases, and the same structure, a shift register with feedback, is the base of pseudo-random generators and CRC checks.
Why learn it.
- It is the simplest state machine with real feedback: the next state is computed from the present state.
- It shows one counter in two forms: a single chip (BB7) and a register plus a gate (here).
- It shows that the code of a state is a choice: binary needs fewer flip-flops, Johnson needs simpler decoding.
2The key elements: the ring of codes
| State | Q5 … Q1 (LEDs 5 … 1) | 4017 output at 1 in the same state |
|---|---|---|
| 0 | 00000 | Q0 |
| 1 | 00001 | Q1 |
| 2 | 00011 | Q2 |
| 3 | 00111 | Q3 |
| 4 | 01111 | Q4 |
| 5 | 11111 | Q5 |
| 6 | 11110 | Q6 |
| 7 | 11100 | Q7 |
| 8 | 11000 | Q8 |
| 9 | 10000 | Q9 |
Compare the code with the 4017 of BB7: in each state exactly one 4017 output is 1, and it is decoded from two neighbouring bits of this code. CARRY OUT of the 4017 is NOT Q5.
Waveforms
tb.sv in Icarus Verilog: reset, then the ring. Each stage is 1 for
five clock periods and 0 for five, one period later than the stage before it. · SVG · PNG3Parts
| Part | In this circuit | Qty | Price | Supplier |
|---|---|---|---|---|
| CD4015 | dual 4-bit shift register: register A and the first stage of B make five stages | 1 | $0.35 | Elexp (elexp.com) |
| CD4069 | hex inverter: the feedback NOT (one of six used) | 1 | $0.30 | Elexp (elexp.com) |
| Button module | RESET; one from the pack of five | 1 | $0.66 / pack | aliexpress.us |
| 555 clock module | the clock, set to about 1 Hz | 1 | $0.53 | aliexpress.us |
| 8-LED module | shows the five stages | 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 |
| Pre-cut jumper wires | 15 wires on the board (or male-male Dupont jumpers) | 15 | $11.95 / pack | jameco.com |
| Male-female Dupont jumpers | 12 leads to the clock module, the button and the LED module | 12 | $1.30 / pack | aliexpress.us |
Prices from the LSSK components sheet; the 4015 and the 4069 are also in the Basics kit.
4The chips, 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.
4015: dual 4-stage shift register
Register A: DATA A pin 7, CLOCK A pin 9, RESET A pin 6, Q1A–Q4A pins 5, 4, 3 and 10. Register B: DATA B pin 15, CLOCK B pin 1, RESET B pin 14, Q1B–Q4B pins 13, 12, 11 and 2. Here Q4A goes to DATA B, both clocks come from the clock module and both resets from the button; Q2B–Q4B are not used.
Polarity. Both registers shift on the rising edge of their clock. RESET is active high and asynchronous: it clears the register at once.
| Pin | Name | Direction | Function | In this circuit |
|---|---|---|---|---|
| 1 | CLOCK B | input | register B shifts on the rising edge | CLK |
| 2 | Q4B | output | register B, stage 4 (the oldest bit) | not connected |
| 3 | Q3A | output | register A, stage 3 | Q3 |
| 4 | Q2A | output | register A, stage 2 | Q2 |
| 5 | Q1A | output | register A, stage 1 (the newest bit) | Q1 |
| 6 | RESET A | input | 1 clears register A at once, without the clock. Active high | RST |
| 7 | DATA A | input | register A, serial input | Q5 |
| 8 | VSS | power | ground, 0 V | GND |
| 9 | CLOCK A | input | register A shifts on the rising edge | CLK |
| 10 | Q4A | output | register A, stage 4 (the oldest bit) | Q4 |
| 11 | Q3B | output | register B, stage 3 | not connected |
| 12 | Q2B | output | register B, stage 2 | not connected |
| 13 | Q1B | output | register B, stage 1 | Q5 |
| 14 | RESET B | input | 1 clears register B at once. Active high | RST |
| 15 | DATA B | input | register B, serial input | Q4 |
| 16 | VDD | power | supply, +5 V (3 to 18 V allowed) | +5V |
4069: hex inverter
One inverter, pins 1 → 2, turns Q5 (Q1B) into the input of the first stage. The other five have their inputs tied to the rails.
| Pin | Name | Direction | Function | In this circuit |
|---|---|---|---|---|
| 1 | A | input | input of the gate with its output on pin 2 | Q5 |
| 2 | G | output | G = NOT A | Q5 |
| 3 | B | input | input of the gate with its output on pin 4 | tied to GND |
| 4 | H | output | H = NOT B | not connected |
| 5 | C | input | input of the gate with its output on pin 6 | tied to GND |
| 6 | I | output | I = NOT C | not connected |
| 7 | VSS | power | ground, 0 V | GND |
| 8 | J | output | J = NOT D | not connected |
| 9 | D | input | input of the gate with its output on pin 8 | tied to +5V |
| 10 | K | output | K = NOT E | not connected |
| 11 | E | input | input of the gate with its output on pin 10 | tied to +5V |
| 12 | L | output | L = NOT F | not connected |
| 13 | F | input | input of the gate with its output on pin 12 | tied to +5V |
| 14 | VDD | power | supply, +5 V (3 to 18 V allowed) | +5V |
5Schematic 1: flip-flops and the feedback
johnson_counter.sv describes. The line along the bottom is the feedback from Q5 to the inverter. · SVG · PNG6Schematic 2: connections between the chips
| Net | From | To | Wire |
|---|---|---|---|
| CLK | 555 clock module, OUT | 4015 9 (CLKA), 4015 1 (CLKB) | M-F, M-M |
| RST | button RESET, OUT | 4015 6 (RA), 4015 14 (RB) | M-F, M-M |
| Q1 | 4015 5 (Q1A) | LED module, LED 1 | M-F |
| Q2 | 4015 4 (Q2A) | LED module, LED 2 | M-F |
| Q3 | 4015 3 (Q3A) | LED module, LED 3 | M-F |
| Q4 | 4015 10 (Q4A) | 4015 15 (DB), LED module, LED 4 | M-F, M-M |
| Q5 | 4015 13 (Q1B) | 4069 1 (A), LED module, LED 5 | M-F, M-M |
| Q5 | 4069 2 (G) | 4015 7 (DA) | M-M |
| +5V | +5V | 4015 16 (VDD), 4069 14 (VDD), 4069 13 (F), 4069 11 (E), 4069 9 (D) | |
| GND | GND | 4015 8 (VSS), 4069 7 (VSS), 4069 3 (B), 4069 5 (C) | |
| not connected | 4015 2 (Q4B), 4015 11 (Q3B), 4015 12 (Q2B), 4069 4 (H), 4069 6 (I), 4069 8 (J), 4069 10 (K), 4069 12 (L) |
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 chips across the gap, notch to the left: the 4015 with pin 1 in hole 7f; the 4069 with pin 1 in hole 17f. Read the numbers on the chips: many look alike.
- 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. Make sure no wire touches + and − at the same time.
- The tie-offs of the five unused inverters.
- The signal wires: CLOCK A to CLOCK B, RESET A to RESET B, Q4A to DATA B (the cascade), Q1B to the inverter, and the inverter output back to DATA A (the feedback). Tick each wire as you insert it.
- With the power off, the modules: the clock module and the reset button above the board, the LED module below.
- Turn the power on and set the clock module to about one blink per second.
Wiring checklist
| # | Net | From | To | |
|---|---|---|---|---|
| Power (red to +, black to −) · 4 wires | ||||
| 1 | +5V | 7a (4015 pin 16, VDD) | top + rail, column 7 | |
| 2 | GND | 14j (4015 pin 8, VSS) | bottom − rail, column 14 | |
| 3 | +5V | 17a (4069 pin 14, VDD) | top + rail, column 17 | |
| 4 | GND | 23j (4069 pin 7, VSS) | bottom − rail, column 23 | |
| Fixed inputs: CMOS inputs must not float · 5 wires | ||||
| 5 | +5V | 18a (4069 pin 13, F) | top + rail, column 18 | |
| 6 | GND | 19j (4069 pin 3, B) | bottom − rail, column 19 | |
| 7 | +5V | 20a (4069 pin 11, E) | top + rail, column 20 | |
| 8 | GND | 21j (4069 pin 5, C) | bottom − rail, column 21 | |
| 9 | +5V | 22a (4069 pin 9, D) | top + rail, column 22 | |
| Signal wires · 6 wires | ||||
| 10 | CLK | 14c (4015 pin 9, CLKA) | 7g (4015 pin 1, CLKB) | |
| 11 | RST | 12g (4015 pin 6, RA) | 9d (4015 pin 14, RB) | |
| 12 | Q4 | 13a (4015 pin 10, Q4A) | 8a (4015 pin 15, DB) | |
| 13 | Q4 | 13d (4015 pin 10, Q4A) | 15f | |
| 14 | Q5 | 10b (4015 pin 13, Q1B) | 17g (4069 pin 1, A) | |
| 15 | Q5 | 18g (4069 pin 2, G) | 13g (4015 pin 7, DA) | |
| Modules on male-female jumpers · 12 wires | ||||
| 16 | GND | 555 clock module, − | top − rail, column 10 | |
| 17 | CLK | 555 clock module, OUT | 14a (4015 pin 9, CLKA) | |
| 18 | +5V | 555 clock module, + | top + rail, column 12 | |
| 19 | +5V | button RESET, + | top + rail, column 16 | |
| 20 | RST | button RESET, OUT | 9a (4015 pin 14, RB) | |
| 21 | GND | button RESET, − | top − rail, column 18 | |
| 22 | GND | LED module, G | bottom − rail, column 10 | |
| 23 | Q1 | LED module, LED 1 | 11j (4015 pin 5, Q1A) | |
| 24 | Q2 | LED module, LED 2 | 10j (4015 pin 4, Q2A) | |
| 25 | Q3 | LED module, LED 3 | 9j (4015 pin 3, Q3A) | |
| 26 | Q4 | LED module, LED 4 | 15j | |
| 27 | Q5 | LED module, LED 5 | 17j (4069 pin 1, A) | |
Test it
- Press RESET: all LEDs go dark.
- Release it: LED 1 lights, then LEDs 1–2, 1–3, 1–4, 1–5; then LED 1 goes dark, then 2, … until all are dark again. Ten steps.
- Count the states between two moments when all LEDs are dark.
If it does not work: if the LEDs fill up but never empty, the feedback misses its inverter. If only four stages move, the cascade wire from Q4A to DATA B is missing. If the pattern jumps, a wire of the five LEDs is in the wrong place, or the two clocks are not joined.
8SystemVerilog: the generic design
johnson_counter.sv describes schematic 1 in one line: the register shifts up, and the inverted top bit
comes in at the bottom. It is synthesizable.
// Exercise M10: a 5-stage Johnson counter. // // Generic version that matches schematic 1, not tied to any chip. Five // D flip-flops form a shift register; the inverted last stage goes back // into the first. From 00000 the register fills with ones from the bottom // and then with zeros: ten states, then it repeats. The 4017 of exercise // BB7 has the same counter inside. rst clears all stages at once, without // the clock. Synthesizable. module johnson_counter ( input logic clk, input logic rst, output logic [4:0] q // q [0] is stage 1, q [4] is stage 5 ); always_ff @ (posedge clk or posedge rst) if (rst) q <= '0; else q <= { q [3:0], ~ q [4] }; endmodule
9SystemVerilog models of the chips
One module per chip, with ports named as in the datasheet and the pin number of each port in a comment. The models leave out the power pins: in SystemVerilog a wire simply has the value 0 or 1.
// CD4015B: dual 4-stage shift register, serial input, parallel output. // // Ports in pin order, named as in the datasheet. The power pins, VSS (8) // and VDD (16), are left out. Synthesizable. // // Each register shifts on the rising edge of its clock: DATA goes into Q1, // Q1 into Q2, Q2 into Q3, Q3 into Q4. RESET is active high and // asynchronous: it clears all four stages at once, without the clock. // Connect Q4A to DATA B to make one 8-stage register. module cd4015 ( input logic clock_b, // Pin 1 output logic q4b, // Pin 2 output logic q3a, // Pin 3 output logic q2a, // Pin 4 output logic q1a, // Pin 5 input logic reset_a, // Pin 6: 1 = Q1A-Q4A go to 0 at once input logic data_a, // Pin 7 // Pin 8: VSS input logic clock_a, // Pin 9 output logic q4a, // Pin 10 output logic q3b, // Pin 11 output logic q2b, // Pin 12 output logic q1b, // Pin 13 input logic reset_b, // Pin 14: 1 = Q1B-Q4B go to 0 at once input logic data_b // Pin 15 // Pin 16: VDD ); logic [4:1] ra, rb; // ra [1] is Q1A, ra [4] is Q4A always_ff @ (posedge clock_a or posedge reset_a) if (reset_a) ra <= '0; else ra <= { ra [3:1], data_a }; always_ff @ (posedge clock_b or posedge reset_b) if (reset_b) rb <= '0; else rb <= { rb [3:1], data_b }; assign { q4a, q3a, q2a, q1a } = ra; assign { q4b, q3b, q2b, q1b } = rb; endmodule
// CD4069UB: hex inverter (six NOT gates). // // Ports in pin order, named as in the datasheet: inputs A-F, outputs G-L. // The power pins, VSS (7) and VDD (14), are left out. Synthesizable. module cd4069 ( input logic a, // Pin 1 output logic g, // Pin 2: g = ~ a input logic b, // Pin 3 output logic h, // Pin 4: h = ~ b input logic c, // Pin 5 output logic i, // Pin 6: i = ~ c // Pin 7: VSS output logic j, // Pin 8: j = ~ d input logic d, // Pin 9 output logic k, // Pin 10: k = ~ e input logic e, // Pin 11 output logic l, // Pin 12: l = ~ f input logic f // Pin 13 // Pin 14: VDD ); assign g = ~ a; assign h = ~ b; assign i = ~ c; assign j = ~ d; assign k = ~ e; assign l = ~ f; endmodule
10SystemVerilog: the chip-level design
johnson_counter_chips.sv connects the chip models exactly as schematic 2 and the breadboard connect
the chips, with the same ports as johnson_counter.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.
// Exercise M10, chip-level version: the chips and wires of schematic 2 and // of the breadboard. Same ports as johnson_counter.sv. // // Generated by tools/bb_lib.py from the checked breadboard wire list; // change the layout in tools/bb_m10.py, not this file. Synthesizable. module johnson_counter_chips ( input logic clk, input logic rst, output logic [4:0] q ); // Connections between the chips that are not ports wire fb; // The power rails of the breadboard, for tied-off inputs wire gnd = 1'b0; wire vdd = 1'b1; // Outputs that go nowhere wire unused_u1_q4b; wire unused_u1_q3b; wire unused_u1_q2b; wire unused_u2_h; wire unused_u2_i; wire unused_u2_j; wire unused_u2_k; wire unused_u2_l; //------------------------------------------------------------------------ // U1: CD4015 dual 4-stage shift register, serial in, parallel out, pin 1 in column 7 cd4015 i_u1 ( .clock_b ( clk ), // Pin 1 <- 555 clock module .q4b ( unused_u1_q4b ), // Pin 2, unused output .q3a ( q [2] ), // Pin 3 -> Q3 .q2a ( q [1] ), // Pin 4 -> Q2 .q1a ( q [0] ), // Pin 5 -> Q1 .reset_a ( rst ), // Pin 6 <- button RESET .data_a ( fb ), // Pin 7 <- U2 pin 2 (G) .clock_a ( clk ), // Pin 9 <- 555 clock module .q4a ( q [3] ), // Pin 10 -> Q4 .q3b ( unused_u1_q3b ), // Pin 11, unused output .q2b ( unused_u1_q2b ), // Pin 12, unused output .q1b ( q [4] ), // Pin 13 -> Q5 .reset_b ( rst ), // Pin 14 <- button RESET .data_b ( q [3] ) // Pin 15 <- U1 pin 10 (Q4A) ); //------------------------------------------------------------------------ // U2: CD4069 hex inverter (six NOT gates), pin 1 in column 17 cd4069 i_u2 ( .a ( q [4] ), // Pin 1 <- U1 pin 13 (Q1B) .g ( fb ), // Pin 2 -> ~Q5 .b ( gnd ), // Pin 3 <- GND, unused input .h ( unused_u2_h ), // Pin 4, unused output .c ( gnd ), // Pin 5 <- GND, unused input .i ( unused_u2_i ), // Pin 6, unused output .j ( unused_u2_j ), // Pin 8, unused output .d ( vdd ), // Pin 9 <- +5V, unused input .k ( unused_u2_k ), // Pin 10, unused output .e ( vdd ), // Pin 11 <- +5V, unused input .l ( unused_u2_l ), // Pin 12, unused output .f ( vdd ) // Pin 13 <- +5V, unused input ); 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 number of the state and its Johnson code. Like the testbenches of Basics-Graphics-Music, it drives and checks
signals only at rising clock edges. It runs more than twice round the ring, resets in the middle, and checks that reset
acts at once. The output below is shortened.
tb.sv190 lines · show the codefile
// Testbench for exercise M10. // // Runs the generic design (johnson_counter.sv) and the chip-level design // (johnson_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 runs through the ten states of // the ring more than twice, resets in the middle, and checks that reset acts // at once, without waiting for the clock, like RESET A and B of the 4015. // 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; wire [4:0] q, q_chips; johnson_counter i_generic ( .clk ( clk ), .rst ( rst ), .q ( q ) ); johnson_counter_chips i_chips ( .clk ( clk ), .rst ( rst ), .q ( q_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 number of the state, 0 to 9, and its Johnson // code: k ones from the bottom for k <= 5, then 10 - k ones from the top. // rst sets state 0 at once. int count; always @ (posedge clk or posedge rst) if (rst) count <= 0; else count <= (count + 1) % 10; function automatic logic [4:0] johnson_code (input int k); if (k <= 5) return 5' ((1 << k) - 1); else return 5' (5'b11111 << (k - 5)); endfunction wire [4:0] q_expected = johnson_code (count); wire ok_generic = q === q_expected; wire ok_chips = q_chips === q_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 [9:0] seen = '0; // Which counts were checked outside reset 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); if (~ rst) seen [count] <= 1'b1; $display ("%5d %b %b %0d %s %s", cycle + 1, rst, q, count, ok_generic ? "ok " : "WRONG ", ok_chips ? "ok" : "WRONG"); end end //------------------------------------------------------------------------ // Asynchronous reset: in the middle of a clock period, the outputs must // show count 0 at once. The stimulus sets rst right after an edge; one // time unit later the reset has acted. int n_async = 0; always @ (posedge rst) begin # 1; if (q !== 5'b0 || q_chips !== 5'b0) begin $display ("WRONG: reset did not act at once, q = %b, q_chips = %b", q, q_chips); n_errors <= n_errors + 1; end n_async <= n_async + 1; 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 rst Q5..Q1 state generic chips"); // Before reset the count is unknown, as after power-up rst <= 1'bx; repeat (2) @ (posedge clk); rst <= 1'b1; repeat (2) @ (posedge clk); rst <= 1'b0; repeat (23) @ (posedge clk); // More than twice round the ring of ten states // Reset in the middle of the count rst <= 1'b1; @ (posedge clk); rst <= 1'b0; repeat (12) @ (posedge clk); // 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 && seen == 10'h3ff && n_async >= 2) $display ("PASS: %0d checks, no errors", n_checks); else $display ("FAIL: %0d errors in %0d checks, counts seen %b, %0d resets", n_errors, n_checks, seen, n_async); 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 M10: 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 johnson_counter.sv johnson_counter_chips.sv cd4015.sv cd4069.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 M10: 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 johnson_counter.sv johnson_counter_chips.sv cd4015.sv cd4069.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 M10: 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 johnson_counter.sv johnson_counter_chips.sv cd4015.sv cd4069.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 Q5..Q1 state generic chips
1 1 00000 0 ok ok
2 1 00000 0 ok ok
3 0 00000 0 ok ok
4 0 00001 1 ok ok
5 0 00011 2 ok ok
6 0 00111 3 ok ok
7 0 01111 4 ok ok
8 0 11111 5 ok ok
9 0 11110 6 ok ok
10 0 11100 7 ok ok
11 0 11000 8 ok ok
12 0 10000 9 ok ok
13 0 00000 0 ok ok
14 0 00001 1 ok ok
15 0 00011 2 ok ok
16 0 00111 3 ok ok
17 0 01111 4 ok ok
18 0 11111 5 ok ok
19 0 11110 6 ok ok
20 0 11100 7 ok ok
21 0 11000 8 ok ok
22 0 10000 9 ok ok
23 0 00000 0 ok ok
24 0 00001 1 ok ok
…
tb.sv:176: $finish called at 405000 (1ps)
PASS: 76 checks, no errors
To see that the testbench catches mistakes, break something and run it again: feed q [4] instead of ~ q [4] into the register in johnson_counter.sv,
or connect DATA B to Q3A instead of Q4A in johnson_counter_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.
- Copy
labs/1_basics/1_07_shift_registerto a new directory. - Replace its
lab_top.svwithbgm_lab/lab_top.svfrom this exercise and addjohnson_counter.sv. The BGM scripts compile every.svfile of the directory excepttb.sv. - Run
./03_synthesize_for_fpga.bashand./04_configure_fpga.bash; the first run asks which board you have.
The design runs from slow_clk, which every BGM board makes at 1 Hz, so it steps once
a second like the breadboard with the 555 module. 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.
LEDs 4–0 show Q5–Q1. To run the chip-level design instead, add johnson_counter_chips.sv,
cd4015.sv and cd4069.sv and change the module name in the instance.
bgm_lab/lab_top.sv94 lines · show the codefile
// Exercise M10 on an FPGA board with the Basics-Graphics-Music (BGM) labs: // https://github.com/yuri-panchul/basics-graphics-music // // Copy labs/1_basics/1_07_shift_register to a new directory, replace its // lab_top.sv with this file and add johnson_counter.sv. For the chip-level // design add johnson_counter_chips.sv, cd4015.sv and cd4069.sv instead, and // change the module name below. // // The counter runs from slow_clk, 1 Hz on every BGM board, and rst is the // reset of the board. LEDs 4-0 show the five stages Q5-Q1. `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 abcdefgh = '0; assign digit = '0; assign red = '0; assign green = '0; assign blue = '0; assign sound = '0; assign uart_tx = '1; //------------------------------------------------------------------------ logic [4:0] q; johnson_counter i_johnson_counter ( .clk ( slow_clk ), .rst ( rst ), .q ( q ) ); assign led = w_led' (q); 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/5_shift_register. - Replace its
hackathon_top.svwithbgm_hackathon/hackathon_top.svand addjohnson_counter.sv. - Run
./03_synthesize_for_fpga.bashand./04_configure_fpga.bash.
The screen shows five lamps, stage 1 on the left: the ones fill up from the left and then empty out.
bgm_hackathon/hackathon_top.sv70 lines · show the codefile
// Board configuration: tang_nano_9k_lcd_480_272_tm1638_hackathon // This module uses few parameterization and relaxed typing rules // Exercise M10 in the hackathon setup of Basics-Graphics-Music (BGM): // https://github.com/yuri-panchul/basics-graphics-music // // Copy a directory such as hackathon/problems/5_shift_register, replace its // hackathon_top.sv with this file and add johnson_counter.sv. // // The counter runs from slow_clock. The LEDs show Q5-Q1, and the screen // five lamps, Q1 on the left, like the LED module on the breadboard. 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 [4:0] q; johnson_counter i_johnson_counter ( .clk ( slow_clock ), .rst ( reset ), .q ( q ) ); assign led = { 3'b0, q }; assign abcdefgh = '0; assign digit = '0; //------------------------------------------------------------------------ // Five square lamps on the 480 x 272 screen, 40 pixels wide, 64 apart, // stage 1 on the left. Bright green when 1, dim when 0. always_comb begin red = 0; green = 0; blue = 0; for (int i = 0; i < 5; i ++) if (x >= 9' (92 + i * 64) & x < 9' (132 + i * 64) & y >= 116 & y < 156) green = q [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
chips on the breadboard.
Segments a–e show the five stages: the lit part of the digit grows round it and then shrinks. The reset button of the demo board resets the counter.
tiny_tapeout/project.v47 lines · show the codefile
/* * Exercise M10 on Tiny Tapeout: a 5-stage Johnson counter. Segments a-e of * the 7-segment display of the demo board show the five stages. * * Add johnson_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 ); // The demo board makes the project clock; set it to 1 Hz. The reset // button of the board resets the counter. wire [4:0] q; johnson_counter i_johnson_counter ( .clk ( clk ), .rst ( ~ rst_n ), .q ( q ) ); // 7-segment display: uo_out [0] is segment a, ..., uo_out [6] is g, // uo_out [7] is the dot. Segments a-e show stages 1-5: the lit part // grows round the digit and then shrinks. assign uo_out = { 3'b0, q }; assign uio_out = 8'b0; assign uio_oe = 8'b0; // List all unused inputs to prevent warnings wire _unused = & { ena, ui_in, uio_in, 1'b0 }; endmodule
In info.yaml set the clock to 1 Hz, list the files and use the module name as the top module:
project:
clock_hz: 1 # 1 Hz from the demo board
top_module: "tt_um_example" # rename to tt_um_<your GitHub name>_johnson_counter
source_files:
- "project.v"
- "johnson_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, its edges come later than those of clk by a delay nobody
controls, and every signal between the two clocks crosses clock domains. 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 add a clock enable: a
pulse one clock long that lets the slow logic change only on the edges where it is 1.15Going further
Tasks for students
- Eight stages. Use all of register B: Q4B into the inverter instead of Q1B. How many states now?
- Decode one state. With one AND gate of a 4081 and the right two stages, light an extra LED only in state 3. Which stages, and is one of them inverted?
- Lost states. Five flip-flops have 32 combinations, the ring uses 10. What happens if the counter starts in one of the other 22, say 00101? (The 4017 has extra gates that bring it back into the ring.)
- Against binary. Exercise M12 compares a binary counter with a 4-stage Johnson counter on a 4063.
- In SystemVerilog: make the length a parameter, and compare the flip-flops and gates that synthesis makes for a Johnson counter and a binary counter with the same number of states.
Files of this exercise
- johnson_counter.sv: the generic design (section 8)
- cd4015.sv and cd4069.sv: chip models (section 9)
- johnson_counter_chips.sv: the chip-level design (section 10)
- tb.sv, 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 schematics, the pinouts and the waveforms; the Russian versions end in
_ru
Sources
The exercise is in the Mini-projects list of “An improved way of teaching school kids digital electronics” and in lesson 1.6 of the Habr article about the electronics course; the LSSK components sheet notes that the 4017 is a Johnson counter inside. The chips are described in the Texas Instruments datasheets for the CD4015B and CD4069UB.