Breadboard exercises/ BB7EnglishРусский

Exercise BB7 · building blocks · counter

4017 decade counter with decoded outputs

A 4017 counts the clock from 0 to 9 and lights one of ten outputs for each count: a single light runs along two LED modules, one step per second. Inside the chip is a Johnson counter, which exercise M10 builds from a shift register.

1 chip4017 decade counter
7 + 19 wireson the board + jumper leads to the modules
10 statesone output at 1 in each
~1 Hzfrom the 555 clock module

1What it is and why it matters

What it does. At every rising edge of the clock the 4017 moves to the next of its ten states, from 0 to 9 and then back to 0. In state k output Qk is 1 and all others are 0. CARRY OUT is 1 in states 0–4 and 0 in states 5–9. The reset button sets state 0 at once. The first LED module shows Q0–Q7, the second Q8, Q9 and CARRY OUT.

How it works. The chip does not count in binary. It holds a 5-bit Johnson counter: a shift register whose inverted last bit goes back into the first. Its code fills with ones from one end, then with zeros, and comes back after ten steps. Each state differs from its neighbours in one bit, so a 2-input AND gate per output is enough to decode it, and the outputs never glitch between states.

Where it is used. Sequencers: a washing machine program, a traffic light (exercise M11 is built on this chip), a chaser of lights, the ten digits of a counter display. In digital design the 4017 is a simple state machine: ten states in a ring, one step per clock, and one output per state, which is a one-hot code.

Why learn it.

2The key elements: the count and the Johnson code

CountJohnson register r4 … r0Output at 1CARRY OUT
000000Q01
100001Q11
200011Q21
300111Q31
401111Q41
511111Q50
611110Q60
711100Q70
811000Q80
910000Q90

CARRY OUT is simply NOT r4, the inverted last bit of the Johnson register. Each output looks at two neighbouring bits: Q0 is 1 when r4 = 0 and r0 = 0, Q1 when r0 = 1 and r1 = 0, and so on round the ring.

Waveforms

CLKRSTQ0Q1Q2Q3Q4Q5Q6Q7Q8Q9CO
From the simulation of tb.sv in Icarus Verilog: reset, then the running light. Each output is 1 for one clock period, and CARRY OUT for five. · SVG · PNG

3Parts

PartIn this circuitQtyPriceSupplier
CD4017decade counter with 10 decoded outputs1$0.40Elexp (elexp.com)
Button moduleRESET; one from the pack of five1$0.66 / packaliexpress.us
555 clock modulethe clock, set to about 1 Hz1$0.53aliexpress.us
8-LED moduleQ0-Q7 on the first, Q8, Q9 and CARRY OUT on the second2$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
Pre-cut jumper wires7 wires on the board (or male-male Dupont jumpers)7$11.95 / packjameco.com
Male-female Dupont jumpers19 leads to the clock module, the button and the LED modules19$1.30 / packaliexpress.us

Prices from the LSSK components sheet; the 4017 is in the Comprehensive kit.

4The chip, pin by pin

The chips are CMOS 4000B series: they work from 3 to 18 V, here from the 5 V of the power module. Every input must be connected to something, because a CMOS input left open picks up noise and can switch at random. The drawings show each chip from above with the notch on the left, as in the datasheet: pin 1 at the bottom left, pins numbered counter-clockwise. Blue arrows are inputs, orange arrows are outputs.

4017: decade counter with 10 decoded outputs

1Q52Q13Q04Q25Q66Q77Q38VSS9Q810Q411Q912CO13INH14CLK15RST16VDD4017decade counter
CD4017B. A 16-pin chip: VDD is pin 16 and VSS pin 8. The triangle at CLOCK marks an edge-triggered input. · SVG · PNG

The outputs are spread over both rows: Q0 pin 3, Q1 pin 2, Q2 pin 4, Q3 pin 7, Q4 pin 10, Q5 pin 1, Q6 pin 5, Q7 pin 6, Q8 pin 9, Q9 pin 11. CARRY OUT is pin 12, CLOCK INHIBIT 13, CLOCK 14 and RESET 15.

Polarity. The count advances on the rising edge of CLOCK while CLOCK INHIBIT is 0; here CLOCK INHIBIT is tied to GND. RESET is active high and asynchronous: while it is 1 the count is 0.

PinNameDirectionFunctionIn this circuit
1Q5output1 in state 5, 0 otherwiseQ5
2Q1output1 in state 1, 0 otherwiseQ1
3Q0output1 in state 0, 0 otherwiseQ0
4Q2output1 in state 2, 0 otherwiseQ2
5Q6output1 in state 6, 0 otherwiseQ6
6Q7output1 in state 7, 0 otherwiseQ7
7Q3output1 in state 3, 0 otherwiseQ3
8VSSpowerground, 0 VGND
9Q8output1 in state 8, 0 otherwiseQ8
10Q4output1 in state 4, 0 otherwiseQ4
11Q9output1 in state 9, 0 otherwiseQ9
12CARRY OUToutput1 in states 0-4, 0 in states 5-9; rises when the count goes from 9 to 0, so it can clock the next 4017CO
13CLOCK INHIBITinput1 holds the count; 0 lets the counter count. Active highGND
14CLOCKinputthe count advances on the rising edge, 0 to 1CLK
15RESETinput1 sets the count to 0 at once (Q0 = 1), without waiting for the clock. Active highRST
16VDDpowersupply, +5 V (3 to 18 V allowed)+5V

5Schematic 1: the counter as a block

CLKRESET4017CLKINHRSTQ0Q1Q2Q3Q4Q5Q6Q7Q8Q9COdecade counterQ0module 1, LED 1Q1module 1, LED 2Q2module 1, LED 3Q3module 1, LED 4Q4module 1, LED 5Q5module 1, LED 6Q6module 1, LED 7Q7module 1, LED 8Q8module 2, LED 1Q9module 2, LED 2COmodule 2, LED 3
The circuit with the 4017 as one block. This is what decade_counter.sv describes. · SVG · PNG

6Schematic 2: connections

12345678910111213141516Q5Q1Q0Q2Q6Q7Q3Q8Q4Q9COINHCLKRST4017decade counterRSTCOQ0Q2Q3Q4Q5Q8Q9clockRESETLED module: LEDs 1-8LED module: LEDs 1-3+5V
The same circuit with the chip, pin by pin. The clock module and the reset button are above, the two LED modules below. · SVG · PNG
NetFromToWire
CLK555 clock module, OUT4017 14 (CLK)M-F
RSTbutton RESET, OUT4017 15 (RST)M-F
Q04017 3 (Q0)LED module, LED 1M-F
Q14017 2 (Q1)LED module, LED 2M-F
Q24017 4 (Q2)LED module, LED 3M-F
Q34017 7 (Q3)LED module, LED 4M-F
Q44017 10 (Q4)LED module, LED 5M-F, M-M
Q54017 1 (Q5)LED module, LED 6M-F
Q64017 5 (Q6)LED module, LED 7M-F
Q74017 6 (Q7)LED module, LED 8M-F
Q84017 9 (Q8)LED module, LED 1M-F, M-M
Q94017 11 (Q9)LED module, LED 2M-F, M-M
CO4017 12 (CO)LED module, LED 3M-F, M-M
+5V+5V4017 16 (VDD)
GNDGND4017 8 (VSS), 4017 13 (INH)

7Schematic 3: the breadboard

−+−+1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950abcdefghij5V5VPOWER MODULE · 5V9V USB-DC4017COQ9−OUT+555CLOCK 555~1 Hz+OUT−RESETG1Q02Q13Q24Q35Q46Q57Q68Q78-LED MODULELEDs 1-8 usedG1Q82Q93CO456788-LED MODULELEDs 1-3 used
Every wire in its hole. Column numbers are printed along the top; rows a–e are above the gap, f–j below it. The clock module and the reset button hang above the board, the two LED modules below it. · SVG · PNG
CLKRSTQ0Q1Q2Q3Q4Q5Q6Q7Q8Q9CO+5VGND

Build it step by step

  1. Do the getting-started steps first: how the breadboard is connected inside, the power module with both jumpers on 5 V, how a chip sits across the gap.
  2. Insert the chips across the gap, notch to the left: the 4017 with pin 1 in hole 10f. Read the numbers on the chips: many look alike.
  3. Power: for each chip a red wire from its VDD pin (14, or 16 on a 16-pin chip) to the + rail and a black wire from its VSS pin (7 or 8) to the − rail, each to the rail on its own side of the gap. Make sure no wire touches + and − at the same time.
  4. CLOCK INHIBIT, pin 13 (column 13, top half), to the top − rail.
  5. Four outputs are on the top row: Q9 (column 15), Q4 (column 16), Q8 (column 17) and CARRY OUT (column 14). Four wires bring them down to columns 18–21 of the bottom half, where the LED modules land.
  6. With the power off, the modules: the clock module and the reset button above the board, the LED modules below. Connect G of each LED module first.
  7. Turn the power on and set the clock module to about one blink per second.

Wiring checklist

·

#NetFromTo
Power (red to +, black to −) · 2 wires
1+5V10a (4017 pin 16, VDD)top + rail, column 10
2GND17j (4017 pin 8, VSS)bottom − rail, column 17
Fixed inputs: CMOS inputs must not float · 1 wire
3GND13a (4017 pin 13, INH)top − rail, column 13
Signal wires · 4 wires
4CO14a (4017 pin 12, CO)21f
5Q416d (4017 pin 10, Q4)18f
6Q817c (4017 pin 9, Q8)19f
7Q915b (4017 pin 11, Q9)20f
Modules on male-female jumpers · 19 wires
8GND555 clock module, −top − rail, column 11
9CLK555 clock module, OUT12a (4017 pin 14, CLK)
10+5V555 clock module, +top + rail, column 13
11+5Vbutton RESET, +top + rail, column 17
12RSTbutton RESET, OUT11a (4017 pin 15, RST)
13GNDbutton RESET, −top − rail, column 19
14GNDLED module, Gbottom − rail, column 7
15Q0LED module, LED 112j (4017 pin 3, Q0)
16Q1LED module, LED 211j (4017 pin 2, Q1)
17Q2LED module, LED 313j (4017 pin 4, Q2)
18Q3LED module, LED 416j (4017 pin 7, Q3)
19Q4LED module, LED 518j
20Q5LED module, LED 610j (4017 pin 1, Q5)
21Q6LED module, LED 714j (4017 pin 5, Q6)
22Q7LED module, LED 815j (4017 pin 6, Q7)
23GNDLED module, Gbottom − rail, column 22
24Q8LED module, LED 119j
25Q9LED module, LED 220j
26COLED module, LED 321j

Test it

If it does not work: if the light jumps in a strange order, compare the LED leads with the checklist: the outputs of the 4017 are in no simple order. If nothing moves, check pin 13 (must be at GND), pin 15 (GND when the button is up) and the clock lead to pin 14.

8SystemVerilog: the generic design

decade_counter.sv describes the counter the obvious way: a 4-bit binary count from 0 to 9 and a decoder. It is synthesizable. The chip-level design uses the Johnson counter of the 4017; the testbench shows that the two give the same outputs.

decade_counter.svfile
// Exercise BB7: a decade counter with ten decoded outputs, like the 4017.
//
// Generic version that matches schematic 1, not tied to any chip.  It counts
// clock edges from 0 to 9 in a 4-bit register and decodes the count, so
// that exactly one of the outputs q is 1.  The 4017 does the same with a
// 5-bit Johnson counter inside; section 2 of the page compares the two.
// rst sets the count to 0 at once, without the clock.  Synthesizable.

module decade_counter
(
    input  logic       clk,
    input  logic       rst,

    output logic [9:0] q,          // q [k] is 1 at count k
    output logic       carry_out   // 1 for counts 0-4, 0 for counts 5-9
);

    logic [3:0] count;

    always_ff @ (posedge clk or posedge rst)
        if (rst)
            count <= 4'd0;
        else if (count == 4'd9)
            count <= 4'd0;
        else
            count <= count + 4'd1;

    assign q         = 10'b1 << count;
    assign carry_out = count < 4'd5;

endmodule

9SystemVerilog model of the chip

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

cd4017.svfile
// CD4017B: CMOS decade counter with 10 decoded outputs.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (8)
// and VDD (16), are left out.  Synthesizable.
//
// The chip counts on a rising edge of CLOCK while CLOCK INHIBIT is low, and
// also on a falling edge of CLOCK INHIBIT while CLOCK is high: CLOCK INHIBIT
// gates the clock.  The model does the same with an AND gate in the clock path.
// In an FPGA design keep clock_inhibit at 0; then the gate is just a wire.
//
// RESET is active high and asynchronous: while it is 1 the count is 0.
//
// Inside, the counter is a 5-stage Johnson counter with a decoder, the same
// circuit as traffic_light.sv.  The real chip also has extra gates that bring
// the counter into the ten-state sequence from any state after power-up;
// the model needs a reset instead.

module cd4017
(
    output logic q5,             // Pin 1
    output logic q1,             // Pin 2
    output logic q0,             // Pin 3
    output logic q2,             // Pin 4
    output logic q6,             // Pin 5
    output logic q7,             // Pin 6
    output logic q3,             // Pin 7
                                 // Pin 8:  VSS
    output logic q8,             // Pin 9
    output logic q4,             // Pin 10
    output logic q9,             // Pin 11
    output logic carry_out,      // Pin 12: 1 for counts 0-4, 0 for counts 5-9
    input  logic clock_inhibit,  // Pin 13: 1 = hold the count
    input  logic clock,          // Pin 14
    input  logic reset           // Pin 15: 1 = count 0 (Q0 = 1) at once
                                 // Pin 16: VDD
);

    wire gated_clock = clock & ~ clock_inhibit;

    logic [4:0] r;

    always_ff @ (posedge gated_clock or posedge reset)
        if (reset)
            r <= '0;
        else
            r <= { r [3:0], ~ r [4] };

    assign q0 = ~ r [4] & ~ r [0];
    assign q1 =   r [0] & ~ r [1];
    assign q2 =   r [1] & ~ r [2];
    assign q3 =   r [2] & ~ r [3];
    assign q4 =   r [3] & ~ r [4];
    assign q5 =   r [4] &   r [0];
    assign q6 = ~ r [0] &   r [1];
    assign q7 = ~ r [1] &   r [2];
    assign q8 = ~ r [2] &   r [3];
    assign q9 = ~ r [3] &   r [4];

    assign carry_out = ~ r [4];

endmodule

gated_clock: the real chip counts on the rising edge of CLOCK while CLOCK INHIBIT is low, and an AND gate in the clock path does exactly that. On an FPGA, clocks should not pass through gates, so keep clock_inhibit at 0; synthesis then removes the gate.

10SystemVerilog: the chip-level design

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

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

module decade_counter_chips
(
    input  logic       clk,
    input  logic       rst,
    output logic [9:0] q,
    output logic       carry_out
);

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

    wire gnd = 1'b0;

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

    // U1: CD4017 decade counter with 10 decoded outputs, pin 1 in column 10

    cd4017 i_u1
    (
        .q5            ( q [5]     ),  // Pin 1 -> Q5
        .q1            ( q [1]     ),  // Pin 2 -> Q1
        .q0            ( q [0]     ),  // Pin 3 -> Q0
        .q2            ( q [2]     ),  // Pin 4 -> Q2
        .q6            ( q [6]     ),  // Pin 5 -> Q6
        .q7            ( q [7]     ),  // Pin 6 -> Q7
        .q3            ( q [3]     ),  // Pin 7 -> Q3
        .q8            ( q [8]     ),  // Pin 9 -> Q8
        .q4            ( q [4]     ),  // Pin 10 -> Q4
        .q9            ( q [9]     ),  // Pin 11 -> Q9
        .carry_out     ( carry_out ),  // Pin 12 -> CO
        .clock_inhibit ( gnd       ),  // Pin 13 <- GND
        .clock         ( clk       ),  // Pin 14 <- 555 clock module
        .reset         ( rst       )   // Pin 15 <- button RESET
    );

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 modulo 10. Like the testbenches of Basics-Graphics-Music, it drives and checks signals only at rising clock edges. It goes more than twice round the ring, resets in the middle of the count, and checks that reset acts at once, without waiting for a clock edge. The output below is shortened.

tb.sv185 lines · show the codefile
// Testbench for exercise BB7.
//
// Runs the generic design (decade_counter.sv) and the chip-level design
// (decade_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 through the ten states
// more than twice, resets in the middle of the count, and checks that reset
// acts at once, without waiting for the clock, like RESET of the 4017.

// 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  [9:0] q,         q_chips;
    wire        carry_out, carry_out_chips;

    decade_counter i_generic
    (
        .clk       ( clk       ),
        .rst       ( rst       ),
        .q         ( q         ),
        .carry_out ( carry_out )
    );

    decade_counter_chips i_chips
    (
        .clk       ( clk             ),
        .rst       ( rst             ),
        .q         ( q_chips         ),
        .carry_out ( carry_out_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.  rst sets 0 at once.

    int count;

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

    wire [9:0] q_expected     = 10'b1 << count;
    wire       carry_expected = count < 5;

    wire ok_generic = q       === q_expected && carry_out       === carry_expected;
    wire ok_chips   = q_chips === q_expected && carry_out_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 [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  %b    %0d     %s  %s",
                cycle + 1, rst, q, carry_out, 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 !== 10'b1 || q_chips !== 10'b1)
        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  Q9...Q0     CO  count  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

        // 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 BB7: 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 decade_counter.sv decade_counter_chips.sv cd4017.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 BB7: 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 decade_counter.sv decade_counter_chips.sv cd4017.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 BB7: 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 decade_counter.sv decade_counter_chips.sv cd4017.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  Q9...Q0     CO  count  generic  chips
    1  1    0000000001  1    0     ok          ok
    2  1    0000000001  1    0     ok          ok
    3  0    0000000001  1    0     ok          ok
    4  0    0000000010  1    1     ok          ok
    5  0    0000000100  1    2     ok          ok
    6  0    0000001000  1    3     ok          ok
    7  0    0000010000  1    4     ok          ok
    8  0    0000100000  0    5     ok          ok
    9  0    0001000000  0    6     ok          ok
   10  0    0010000000  0    7     ok          ok
   11  0    0100000000  0    8     ok          ok
   12  0    1000000000  0    9     ok          ok
   13  0    0000000001  1    0     ok          ok
   14  0    0000000010  1    1     ok          ok
   15  0    0000000100  1    2     ok          ok
   16  0    0000001000  1    3     ok          ok
   17  0    0000010000  1    4     ok          ok
   18  0    0000100000  0    5     ok          ok
   19  0    0001000000  0    6     ok          ok
   20  0    0010000000  0    7     ok          ok
   21  0    0100000000  0    8     ok          ok
   22  0    1000000000  0    9     ok          ok
   23  0    0000000001  1    0     ok          ok
   24  0    0000000010  1    1     ok          ok
  …
tb.sv:171: $finish called at 405000 (1ps)
PASS: 76 checks, no errors

To see that the testbench catches mistakes, break something and run it again: change count == 4'd9 to count == 4'd8 in decade_counter.sv, or swap the outputs Q3 and Q4 in decade_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.

  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 decade_counter.sv. The BGM scripts compile every .sv file of the directory except tb.sv.
  3. Run ./03_synthesize_for_fpga.bash and ./04_configure_fpga.bash; the first run asks which board you have.

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 7–0 show Q7–Q0, and the rightmost digit shows the number of the output that is 1, with CARRY OUT on its dot. The digit is drawn by a small table in lab_top.sv. To run the chip-level design instead, add decade_counter_chips.sv and cd4017.sv and change the module name in the instance.

bgm_lab/lab_top.sv120 lines · show the codefile
// Exercise BB7 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 decade_counter.sv.  For the chip-level
// design add decade_counter_chips.sv and cd4017.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 7-0 show Q7-Q0, and the rightmost digit of the
// display shows the number of the output that is 1, so Q8 and Q9 are seen
// there too; its dot is CARRY OUT.

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

    decade_counter i_decade_counter
    (
        .clk       ( slow_clk  ),
        .rst       ( rst       ),
        .q         ( q         ),
        .carry_out ( carry_out )
    );

    assign led = w_led' (q);

    //------------------------------------------------------------------------
    // The digit whose output is 1, on a 7-segment display: a is the top
    // segment, g the middle one.  No output at 1: blank.

    logic [6:0] abcdefg;

    always_comb
        case (q)
        10'b00_0000_0001: abcdefg = 7'b111_1110;  // 0
        10'b00_0000_0010: abcdefg = 7'b011_0000;  // 1
        10'b00_0000_0100: abcdefg = 7'b110_1101;  // 2
        10'b00_0000_1000: abcdefg = 7'b111_1001;  // 3
        10'b00_0001_0000: abcdefg = 7'b011_0011;  // 4
        10'b00_0010_0000: abcdefg = 7'b101_1011;  // 5
        10'b00_0100_0000: abcdefg = 7'b101_1111;  // 6
        10'b00_1000_0000: abcdefg = 7'b111_0000;  // 7
        10'b01_0000_0000: abcdefg = 7'b111_1111;  // 8
        10'b10_0000_0000: abcdefg = 7'b111_1011;  // 9
        default:          abcdefg = 7'b000_0000;
        endcase

    assign abcdefgh = { abcdefg, carry_out };
    assign digit    = w_digit' (1);

endmodule

13On an FPGA board: hackathon_top in BGM

The hackathon setup of BGM uses a Tang Nano 9K with a 480×272 screen and a TM1638 board of keys, LEDs and digits. Its top module, hackathon_top, has simpler ports; the first line of the file names the board, so the scripts need no questions.

  1. Copy hackathon/problems/4_binary_counter.
  2. Replace its hackathon_top.sv with bgm_hackathon/hackathon_top.sv and add decade_counter.sv.
  3. Run ./03_synthesize_for_fpga.bash and ./04_configure_fpga.bash.

The screen shows ten lamps in a row with the running light and CARRY OUT in blue at the right end; the LEDs and the rightmost digit are as in lab_top.

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

// Exercise BB7 in the hackathon setup of Basics-Graphics-Music (BGM):
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy a directory such as hackathon/problems/4_binary_counter, replace its
// hackathon_top.sv with this file and add decade_counter.sv.
//
// The counter runs from slow_clock.  The LEDs show Q7-Q0, the rightmost
// digit the number of the output that is 1 with CARRY OUT on its dot, and
// the screen ten lamps, Q0 on the left, and CARRY OUT in blue on the right:
// like the two LED modules 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 [9:0] q;
    logic       carry_out;

    decade_counter i_decade_counter
    (
        .clk       ( slow_clock ),
        .rst       ( reset      ),
        .q         ( q          ),
        .carry_out ( carry_out  )
    );

    assign led = q [7:0];

    //------------------------------------------------------------------------
    // The digit whose output is 1, on a 7-segment display: a is the top
    // segment, g the middle one.  No output at 1: blank.

    logic [6:0] abcdefg;

    always_comb
        case (q)
        10'b00_0000_0001: abcdefg = 7'b111_1110;  // 0
        10'b00_0000_0010: abcdefg = 7'b011_0000;  // 1
        10'b00_0000_0100: abcdefg = 7'b110_1101;  // 2
        10'b00_0000_1000: abcdefg = 7'b111_1001;  // 3
        10'b00_0001_0000: abcdefg = 7'b011_0011;  // 4
        10'b00_0010_0000: abcdefg = 7'b101_1011;  // 5
        10'b00_0100_0000: abcdefg = 7'b101_1111;  // 6
        10'b00_1000_0000: abcdefg = 7'b111_0000;  // 7
        10'b01_0000_0000: abcdefg = 7'b111_1111;  // 8
        10'b10_0000_0000: abcdefg = 7'b111_1011;  // 9
        default:          abcdefg = 7'b000_0000;
        endcase

    assign abcdefgh = { abcdefg, carry_out };
    assign digit    = 8'b0000_0001;

    //------------------------------------------------------------------------
    // Ten square lamps on the 480 x 272 screen, 30 pixels wide, 40 apart,
    // Q0 on the left, and CARRY OUT in blue at the right end.  Bright when
    // 1, dim when 0.

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

        for (int i = 0; i < 10; i ++)
            if (x >= 9' (25 + i * 40) & x < 9' (55 + i * 40) & y >= 121 & y < 151)
                green = q [i] ? 63 : 12;

        if (x >= 425 & x < 455 & y >= 121 & y < 151)
            blue = carry_out ? 31 : 6;
    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.

The display shows the number of the output that is 1 as a digit, with CARRY OUT on the dot; the reset button of the demo board resets the counter.

tiny_tapeout/project.v70 lines · show the codefile
/*
 * Exercise BB7 on Tiny Tapeout: a decade counter like the 4017.  The
 * 7-segment display of the demo board shows the number of the output that
 * is 1, and its dot CARRY OUT.
 *
 * Add decade_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 [9:0] q;
    wire       carry_out;

    decade_counter i_decade_counter (
        .clk       ( clk       ),
        .rst       ( ~ rst_n   ),
        .q         ( q         ),
        .carry_out ( carry_out )
    );

    // The digit whose output is 1, on the 7-segment display: a is the top
    // segment, g the middle one.  No output at 1: blank.

    function [6:0] digit_of (input [9:0] one_hot);
        case (one_hot)
        10'b00_0000_0001: digit_of = 7'b111_1110;  // 0
        10'b00_0000_0010: digit_of = 7'b011_0000;  // 1
        10'b00_0000_0100: digit_of = 7'b110_1101;  // 2
        10'b00_0000_1000: digit_of = 7'b111_1001;  // 3
        10'b00_0001_0000: digit_of = 7'b011_0011;  // 4
        10'b00_0010_0000: digit_of = 7'b101_1011;  // 5
        10'b00_0100_0000: digit_of = 7'b101_1111;  // 6
        10'b00_1000_0000: digit_of = 7'b111_0000;  // 7
        10'b01_0000_0000: digit_of = 7'b111_1111;  // 8
        10'b10_0000_0000: digit_of = 7'b111_1011;  // 9
        default:          digit_of = 7'b000_0000;
        endcase
    endfunction

    wire [6:0] abcdefg = digit_of (q);

    // uo_out [0] is segment a, ..., uo_out [6] is g, uo_out [7] is the dot

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

    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>_decade_counter
  source_files:
    - "project.v"
    - "decade_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, 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

Files of this exercise

Sources

The 4017 is in the Building blocks list of “An improved way of teaching school kids digital electronics” and in lessons 1.6 and 1.7 of the Habr article about the electronics course. The chip is described in the Texas Instruments datasheet for the CD4017B.