Breadboard exercises/ M12EnglishРусский

Exercise M12 · mini-project · counters

Binary counter against a Johnson counter on the 4063

One clock drives two 4-bit counters, a 4029 counting in binary and a Johnson counter made of a 4015 and a 4069. A 4063 compares their values at every moment, and a traffic light shows which one is ahead: a race between two ways of counting.

4 chips4029, 4015, 4069, 4063
45 + 15 wireson the board + jumper leads to the modules
16 and 8states of the two counters
~1 Hzfrom the 555 clock module

1What it is and why it matters

What it does. The 4029 counts up in binary, 0 to 15 and round again. Register A of the 4015 with an inverter of the 4069 is a 4-stage Johnson counter: 0000, 0001, 0011, 0111, 1111, 1110, 1100, 1000 and round again (exercise M10 has a 5-stage one). Both step on the same clock edge, and the reset button clears both. The 4063 reads the binary count as A and the Johnson code, taken as a binary number, as B. The traffic light shows green while A > B, yellow when A = B and red while A < B. The LED module shows the binary count on LEDs 1–4 and the Johnson code on 5–8.

How it works. After reset both are 0, and after the first clock both are 1: yellow. Then the Johnson code races ahead, because it fills with ones from the bottom (3, 7, 15) while the binary count only adds one: red. Then it empties from the bottom (14, 12, 8, 0) and at clock 8 falls behind for good: green until clock 15. The pattern of colours repeats every 16 clocks, the least common multiple of 16 and 8 states.

Where it is used. Comparing a counter with a value is how timers, PWM generators and watchdogs work. Here the “value” is itself a counter, which shows how two state machines in one clock domain can be watched by a third circuit.

Why learn it.

2The key elements: two codes, one comparison

The first 16 clock edges after reset:

ClockBinary=Johnson=Light
00000000000yellow
10001100011yellow
20010200113red
30011301117red
401004111115red
501015111014red
601106110012red
70111710008red
81000800000green
91001900011green
1010101000113green
1110111101117green
12110012111115red
13110113111014red
14111014110012green
1511111510008green

Waveforms

CLKRSTbinary01234567891011121314150Johnson01371514128013715141280A>BA=BA<B
From the simulation of tb.sv in Icarus Verilog: reset, then both counters and the three outputs of the comparator, numbers in decimal. · SVG · PNG

3Parts

PartIn this circuitQtyPriceSupplier
CD4029up/down counter: counts up in binary1$0.80Elexp (elexp.com)
CD4015dual shift register: register A is the Johnson counter1$0.35Elexp (elexp.com)
CD4069hex inverter: the feedback of the Johnson counter1$0.30Elexp (elexp.com)
CD40634-bit comparator: binary against Johnson1$0.30Futurlec (futurlec.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 modulethe binary count on LEDs 1-4, the Johnson code on 5-81$0.38aliexpress.us
Traffic-light LED module, 5 Vbinary > Johnson green, equal yellow, less red; plugged into the board; resistors built in1$0.40aliexpress.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 wires45 wires on the board (or male-male Dupont jumpers)45$11.95 / packjameco.com
Male-female Dupont jumpers15 leads to the clock module, the button and the LED module15$1.30 / packaliexpress.us

Prices from the LSSK components sheet; these chips are in the Comprehensive kit.

Buy the 5 V traffic-light module. The same module is sold for 1 V and looks alike.

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.

4029: up/down binary/decade counter

1PE2Q43J44J15CI6Q17CO8VSS9B/D10U/D11Q212J213J314Q315CLK16VDD4029up/down counter
CD4029B. · SVG · PNG

As in exercise B5. Here BINARY/DECADE (pin 9) and UP/DOWN (pin 10) are at +5V: binary, up. ~CARRY IN (pin 5) is at GND, so the counter counts. PRESET ENABLE (pin 1) comes from the reset button: while it is 1, the counter loads the JAM inputs, all four at GND, so it shows 0. Q1–Q4 are pins 6, 11, 14 and 2.

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

4015: dual 4-stage shift register

1CLKB2Q4B3Q3A4Q2A5Q1A6RA7DA8VSS9CLKA10Q4A11Q3B12Q2B13Q1B14RB15DB16VDD40152 × 4-bit shift register
CD4015B. · SVG · PNG

Register A only: DATA A (pin 7) from the inverter, CLOCK A (pin 9) from the clock, RESET A (pin 6) from the button, Q1A–Q4A on pins 5, 4, 3 and 10. The inputs of register B are tied to the rails.

PinNameDirectionFunctionIn this circuit
1CLOCK Binputregister B shifts on the rising edgetied to GND
2Q4Boutputregister B, stage 4 (the oldest bit)not connected
3Q3Aoutputregister A, stage 3J3
4Q2Aoutputregister A, stage 2J2
5Q1Aoutputregister A, stage 1 (the newest bit)J1
6RESET Ainput1 clears register A at once, without the clock. Active highRST
7DATA Ainputregister A, serial inputJ4
8VSSpowerground, 0 VGND
9CLOCK Ainputregister A shifts on the rising edgeCLK
10Q4Aoutputregister A, stage 4 (the oldest bit)J4
11Q3Boutputregister B, stage 3not connected
12Q2Boutputregister B, stage 2not connected
13Q1Boutputregister B, stage 1not connected
14RESET Binput1 clears register B at once. Active hightied to +5V
15DATA Binputregister B, serial inputtied to +5V
16VDDpowersupply, +5 V (3 to 18 V allowed)+5V

4069: hex inverter

1A2G3B4H5C6I7VSS8J9D10K11E12L13F14VDD4069
CD4069UB. · SVG · PNG

One inverter turns Q4A into DATA A: the twist of the Johnson ring.

PinNameDirectionFunctionIn this circuit
1Ainputinput of the gate with its output on pin 2J4
2GoutputG = NOT AJ4
3Binputinput of the gate with its output on pin 4tied to GND
4HoutputH = NOT Bnot connected
5Cinputinput of the gate with its output on pin 6tied to GND
6IoutputI = NOT Cnot connected
7VSSpowerground, 0 VGND
8JoutputJ = NOT Dnot connected
9Dinputinput of the gate with its output on pin 8tied to +5V
10KoutputK = NOT Enot connected
11Einputinput of the gate with its output on pin 10tied to +5V
12LoutputL = NOT Fnot connected
13Finputinput of the gate with its output on pin 12tied to +5V
14VDDpowersupply, +5 V (3 to 18 V allowed)+5V

4063: 4-bit magnitude comparator

1B32<in3=in4>in5A>B6A=B7A<B8VSS9B010A011B112A113A214B215A316VDD40634-bit comparator
CD4063B. · SVG · PNG

As in exercise BB3: A0–A3 from the 4029, B0–B3 from the 4015, the cascade inputs set for a single chip, the outputs A>B, A=B, A<B to G, Y and R of the traffic light.

PinNameDirectionFunctionIn this circuit
1B3inputnumber B, bit 3 (weight 8)J4
2A<B INinputcascade input A<B: 0 for a single chipGND
3A=B INinputcascade input A=B: 1 for a single chip+5V
4A>B INinputcascade input A>B: 0 for a single chipGND
5A>B OUToutput1 when A > BA>B
6A=B OUToutput1 when A = B (and the cascade input A=B is 1)A=B
7A<B OUToutput1 when A < BA<B
8VSSpowerground, 0 VGND
9B0inputnumber B, bit 0 (weight 1)J1
10A0inputnumber A, bit 0 (weight 1)N1
11B1inputnumber B, bit 1 (weight 2)J2
12A1inputnumber A, bit 1 (weight 2)N2
13A2inputnumber A, bit 2 (weight 4)N3
14B2inputnumber B, bit 2 (weight 4)J3
15A3inputnumber A, bit 3 (weight 8)N4
16VDDpowersupply, +5 V (3 to 18 V allowed)+5V

5Schematic 1: two counters and a comparator

CLKRESET4029CLKPEU/DB/DCIJAMQ1Q2Q3Q4binary counter40694015 ADCLKRQ1Q2Q3Q4Johnson counter4063A0A1A2A3B0B1B2B3<IN=IN>INA>BA=BA<BcomparatorA>BgreenA=ByellowA<Bred
The circuit as blocks. This is what counter_race.sv describes. The line along the bottom is the feedback of the Johnson counter. · SVG · PNG

6Schematic 2: connections between the chips

12345678910111213141516PEQ4J4J1CIQ1COB/DU/DQ2J2J3Q3CLK4029up/down counter12345678910111213141516CLKBQ4BQ3AQ2AQ1ARADACLKAQ4AQ3BQ2BQ1BRBDB40152 × 4-bit shift register1234567891011121314406912345678910111213141516B3<in=in>inA>BA=BA<BB0A0B1A1A2B2A340634-bit comparatorGYRGNDCLKRSTJ4A>BA=BA<BN1J1N2J2N3J3N4J4clockRESETLED module: LEDs 1-8+5V
The same circuit as chips, pin by pin. The traffic light is on the right; the modules are above and below. · SVG · PNG
NetFromToWire
CLK555 clock module, OUT4029 15 (CLK), 4015 9 (CLKA)M-F, M-M
RSTbutton RESET, OUT4029 1 (PE), 4015 6 (RA)M-F, M-M
N14029 6 (Q1)4063 10 (A0), LED module, LED 4M-F, M-M
N24029 11 (Q2)4063 12 (A1), LED module, LED 3M-F, M-M
N34029 14 (Q3)4063 13 (A2), LED module, LED 2M-F, M-M
N44029 2 (Q4)4063 15 (A3), LED module, LED 1M-F, M-M (loose jumper)
J14015 5 (Q1A)4063 9 (B0), LED module, LED 8M-F, M-M
J24015 4 (Q2A)4063 11 (B1), LED module, LED 7M-F, M-M
J34015 3 (Q3A)4063 14 (B2), LED module, LED 6M-F, M-M (loose jumper)
J44015 10 (Q4A)4063 1 (B3), LED module, LED 5, 4069 1 (A)M-F, M-M
J44069 2 (G)4015 7 (DA)M-M
A>B4063 5 (A>B)traffic light, GM-M
A=B4063 6 (A=B)traffic light, YM-M
A<B4063 7 (A<B)traffic light, RM-M
+5V+5V4029 16 (VDD), 4015 16 (VDD), 4069 14 (VDD), 4063 16 (VDD), 4029 10 (U/D), 4029 9 (B/D), 4015 15 (DB), 4015 14 (RB), 4069 13 (F), 4069 11 (E), 4069 9 (D), 4063 3 (=in)
GNDGND4029 8 (VSS), 4015 8 (VSS), 4069 7 (VSS), 4063 8 (VSS), traffic light, GND, 4029 3 (J4), 4029 13 (J3), 4029 4 (J1), 4029 12 (J2), 4029 5 (CI), 4015 1 (CLKB), 4069 3 (B), 4069 5 (C), 4063 2 (<in), 4063 4 (>in)
not connected4029 7 (CO), 4015 2 (Q4B), 4015 11 (Q3B), 4015 12 (Q2B), 4015 13 (Q1B), 4069 4 (H), 4069 6 (I), 4069 8 (J), 4069 10 (K), 4069 12 (L)

7Schematic 3: the breadboard

−+−+123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263abcdefghij5V5VPOWER MODULE · 5V9V USB-DC4029401540694063GYRGNDTRAFFIC LIGHTCLKRSTJ4A>BA=BA<BN1J1N2J2N3N3J3N4J4−OUT+555CLOCK 555~1 Hz+OUT−RESETG1N42N33N24N15J46J37J28J18-LED MODULELEDs 1-8 used
Every wire in its hole. Column numbers are printed along the top; rows a–e are above the gap, f–j below it. The clock module and the reset button hang above the board, the LED module below it; the traffic light is plugged into the board on the right. Wires drawn as loose arcs could not be laid flat. · SVG · PNG
CLKRSTN1N2N3N4J1J2J3J4J4A>BA=BA<B+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 4029 with pin 1 in hole 6f; the 4015 with pin 1 in hole 16f; the 4069 with pin 1 in hole 26f; the 4063 with pin 1 in hole 35f. Read the numbers on the chips: many look alike.
  3. Plug the traffic-light module into holes 46f to 49f, G in 46f and GND in 49f.
  4. 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.
  5. The fixed inputs, as in the checklist: the JAM inputs and ~CARRY IN of the 4029 to GND, BINARY/DECADE and UP/DOWN to +5V; the inputs of register B and of the unused inverters to the rails; the cascade inputs of the 4063; the GND pin of the traffic light.
  6. The signal wires: the clock to both counters, the reset to PRESET ENABLE and RESET A, the feedback through the inverter, the eight bits to the comparator, the three outputs to the light. Tick each wire as you insert it.
  7. With the power off, the clock module and the reset button above the board, the LED module below.
  8. Turn the power on and set the clock module to about one blink per second.

Wiring checklist

·

#NetFromTo
Power (red to +, black to −) · 9 wires
1+5V6a (4029 pin 16, VDD)top + rail, column 6
2GND13j (4029 pin 8, VSS)bottom − rail, column 13
3+5V16a (4015 pin 16, VDD)top + rail, column 16
4GND23j (4015 pin 8, VSS)bottom − rail, column 23
5+5V26a (4069 pin 14, VDD)top + rail, column 26
6GND32j (4069 pin 7, VSS)bottom − rail, column 32
7+5V35a (4063 pin 16, VDD)top + rail, column 35
8GND42j (4063 pin 8, VSS)bottom − rail, column 42
9GND49j (traffic light, GND)bottom − rail, column 49
Fixed inputs: CMOS inputs must not float · 18 wires
10GND8j (4029 pin 3, J4)bottom − rail, column 8
11GND9a (4029 pin 13, J3)top − rail, column 9
12GND9j (4029 pin 4, J1)bottom − rail, column 9
13GND10a (4029 pin 12, J2)top − rail, column 10
14GND10j (4029 pin 5, CI)bottom − rail, column 10
15+5V12a (4029 pin 10, U/D)top + rail, column 12
16+5V13a (4029 pin 9, B/D)top + rail, column 13
17GND16j (4015 pin 1, CLKB)bottom − rail, column 16
18+5V17a (4015 pin 15, DB)top + rail, column 17
19+5V18a (4015 pin 14, RB)top + rail, column 18
20+5V27a (4069 pin 13, F)top + rail, column 27
21GND28j (4069 pin 3, B)bottom − rail, column 28
22+5V29a (4069 pin 11, E)top + rail, column 29
23GND30j (4069 pin 5, C)bottom − rail, column 30
24+5V31a (4069 pin 9, D)top + rail, column 31
25GND36j (4063 pin 2, <in)bottom − rail, column 36
26+5V37j (4063 pin 3, =in)bottom + rail, column 37
27GND38j (4063 pin 4, >in)bottom − rail, column 38
Signal wires · 18 wires
28CLK7b (4029 pin 15, CLK)23b (4015 pin 9, CLKA)
29RST6g (4029 pin 1, PE)21g (4015 pin 6, RA)
30RST21h (4015 pin 6, RA)24e
31J427h (4069 pin 2, G)22h (4015 pin 7, DA)
32A>B39g (4063 pin 5, A>B)46g (traffic light, G)
33A=B40g (4063 pin 6, A=B)47g (traffic light, Y)
34A<B41h (4063 pin 7, A<B)48h (traffic light, R)
35N111i (4029 pin 6, Q1)41c (4063 pin 10, A0)
36J120g (4015 pin 5, Q1A)42b (4063 pin 9, B0)
37N211c (4029 pin 11, Q2)14f
38N211a (4029 pin 11, Q2)39a (4063 pin 12, A1)
39J219i (4015 pin 4, Q2A)40d (4063 pin 11, B1)
40N38d (4029 pin 14, Q3)38d (4063 pin 13, A2)
41N338c (4063 pin 13, A2)34f
42J3 (loose jumper)18h (4015 pin 3, Q3A)37c (4063 pin 14, B2)
43N4 (loose jumper)7h (4029 pin 2, Q4)36c (4063 pin 15, A3)
44J422c (4015 pin 10, Q4A)26g (4069 pin 1, A)
45J426h (4069 pin 1, A)35g (4063 pin 1, B3)
Modules on male-female jumpers · 15 wires
46GND555 clock module, −top − rail, column 11
47CLK555 clock module, OUT7a (4029 pin 15, CLK)
48+5V555 clock module, +top + rail, column 14
49+5Vbutton RESET, +top + rail, column 15
50RSTbutton RESET, OUT24a
51GNDbutton RESET, −top − rail, column 19
52GNDLED module, Gbottom − rail, column 24
53N4LED module, LED 17j (4029 pin 2, Q4)
54N3LED module, LED 234j
55N2LED module, LED 314j
56N1LED module, LED 411j (4029 pin 6, Q1)
57J4LED module, LED 526j (4069 pin 1, A)
58J3LED module, LED 618j (4015 pin 3, Q3A)
59J2LED module, LED 719j (4015 pin 4, Q2A)
60J1LED module, LED 820j (4015 pin 5, Q1A)

Test it

If it does not work: check each counter on its own LEDs first: the binary count on LEDs 1–4 must go 0001, 0010, 0011…, the Johnson code on LEDs 5–8 0001, 0011, 0111… Then check the comparator wiring: A0–A3 and B0–B3 are mixed on its top row, pins 9–15.

8SystemVerilog: the generic design

counter_race.sv describes both counters in one always_ff block and the comparator in three assign statements. It is synthesizable.

counter_race.svfile
// Exercise M12: a binary counter and a Johnson counter, both 4 bits wide,
// run from one clock and compared, as in Maya Grigoryeva's project.
//
// Generic version that matches schematic 1, not tied to any chip.  The
// binary counter steps through 0 ... 15, the Johnson counter through its
// eight codes 0000, 0001, 0011, 0111, 1111, 1110, 1100, 1000.  A comparator
// says whether the binary value is greater than, equal to or less than the
// Johnson code read as a number.  rst clears both counters at once, without
// the clock.  Synthesizable.

module counter_race
(
    input  logic       clk,
    input  logic       rst,

    output logic [3:0] binary,
    output logic [3:0] johnson,

    output logic       a_gt_b,   // binary >  johnson
    output logic       a_eq_b,   // binary == johnson
    output logic       a_lt_b    // binary <  johnson
);

    always_ff @ (posedge clk or posedge rst)
        if (rst)
        begin
            binary  <= '0;
            johnson <= '0;
        end
        else
        begin
            binary  <= binary + 4'd1;
            johnson <= { johnson [2:0], ~ johnson [3] };
        end

    assign a_gt_b = binary >  johnson;
    assign a_eq_b = binary == johnson;
    assign a_lt_b = binary <  johnson;

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.

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

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

    logic [3:0] count;

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

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

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

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

endmodule
cd4015.svfile
// 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
cd4069.svfile
// 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
cd4063.svfile
// CD4063B: 4-bit magnitude comparator, pin-compatible with the 7485.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (8)
// and VDD (16), are left out.  Synthesizable.
//
// When the two words differ, A>B or A<B is 1.  When they are equal, the
// outputs copy the cascading inputs, which come from the next less
// significant comparator.  A single chip gets A<B = 0, A=B = 1, A>B = 0.

module cd4063
(
    input  logic b3,      // Pin 1
    input  logic lt_in,   // Pin 2:  cascading input A<B
    input  logic eq_in,   // Pin 3:  cascading input A=B
    input  logic gt_in,   // Pin 4:  cascading input A>B
    output logic gt_out,  // Pin 5:  A>B
    output logic eq_out,  // Pin 6:  A=B
    output logic lt_out,  // Pin 7:  A<B
                          // Pin 8:  VSS
    input  logic b0,      // Pin 9
    input  logic a0,      // Pin 10
    input  logic b1,      // Pin 11
    input  logic a1,      // Pin 12
    input  logic a2,      // Pin 13
    input  logic b2,      // Pin 14
    input  logic a3       // Pin 15
                          // Pin 16: VDD
);

    wire [3:0] a = { a3, a2, a1, a0 };
    wire [3:0] b = { b3, b2, b1, b0 };

    assign gt_out = a > b | a == b & gt_in;
    assign lt_out = a < b | a == b & lt_in;
    assign eq_out =         a == b & eq_in;

endmodule

10SystemVerilog: the chip-level design

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

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

module counter_race_chips
(
    input  logic       clk,
    input  logic       rst,
    output logic [3:0] binary,
    output logic [3:0] johnson,
    output logic       a_gt_b,
    output logic       a_eq_b,
    output logic       a_lt_b
);

    // 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_carry_out_n;
    wire unused_u2_q4b;
    wire unused_u2_q3b;
    wire unused_u2_q2b;
    wire unused_u2_q1b;
    wire unused_u3_h;
    wire unused_u3_i;
    wire unused_u3_j;
    wire unused_u3_k;
    wire unused_u3_l;

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

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

    cd4029 i_u1
    (
        .preset_enable ( rst                   ),  // Pin 1 <- button RESET
        .q4            ( binary [3]            ),  // Pin 2 -> N4
        .jam4          ( gnd                   ),  // Pin 3 <- GND
        .jam1          ( gnd                   ),  // Pin 4 <- GND
        .carry_in_n    ( gnd                   ),  // Pin 5 <- GND
        .q1            ( binary [0]            ),  // Pin 6 -> N1
        .carry_out_n   ( unused_u1_carry_out_n ),  // Pin 7, unused output
        .binary_decade ( vdd                   ),  // Pin 9 <- +5V
        .up_down       ( vdd                   ),  // Pin 10 <- +5V
        .q2            ( binary [1]            ),  // Pin 11 -> N2
        .jam2          ( gnd                   ),  // Pin 12 <- GND
        .jam3          ( gnd                   ),  // Pin 13 <- GND
        .q3            ( binary [2]            ),  // Pin 14 -> N3
        .clock         ( clk                   )   // Pin 15 <- 555 clock module
    );

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

    // U2: CD4015 dual 4-stage shift register, serial in, parallel out, pin 1 in column 16

    cd4015 i_u2
    (
        .clock_b ( gnd           ),  // Pin 1 <- GND, unused input
        .q4b     ( unused_u2_q4b ),  // Pin 2, unused output
        .q3a     ( johnson [2]   ),  // Pin 3 -> J3
        .q2a     ( johnson [1]   ),  // Pin 4 -> J2
        .q1a     ( johnson [0]   ),  // Pin 5 -> J1
        .reset_a ( rst           ),  // Pin 6 <- button RESET
        .data_a  ( fb            ),  // Pin 7 <- U3 pin 2 (G)
        .clock_a ( clk           ),  // Pin 9 <- 555 clock module
        .q4a     ( johnson [3]   ),  // Pin 10 -> J4
        .q3b     ( unused_u2_q3b ),  // Pin 11, unused output
        .q2b     ( unused_u2_q2b ),  // Pin 12, unused output
        .q1b     ( unused_u2_q1b ),  // Pin 13, unused output
        .reset_b ( vdd           ),  // Pin 14 <- +5V, unused input
        .data_b  ( vdd           )   // Pin 15 <- +5V, unused input
    );

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

    // U3: CD4069 hex inverter (six NOT gates), pin 1 in column 26

    cd4069 i_u3
    (
        .a ( johnson [3] ),  // Pin 1 <- U2 pin 10 (Q4A)
        .g ( fb          ),  // Pin 2 -> ~J4
        .b ( gnd         ),  // Pin 3 <- GND, unused input
        .h ( unused_u3_h ),  // Pin 4, unused output
        .c ( gnd         ),  // Pin 5 <- GND, unused input
        .i ( unused_u3_i ),  // Pin 6, unused output
        .j ( unused_u3_j ),  // Pin 8, unused output
        .d ( vdd         ),  // Pin 9 <- +5V, unused input
        .k ( unused_u3_k ),  // Pin 10, unused output
        .e ( vdd         ),  // Pin 11 <- +5V, unused input
        .l ( unused_u3_l ),  // Pin 12, unused output
        .f ( vdd         )   // Pin 13 <- +5V, unused input
    );

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

    // U4: CD4063 4-bit magnitude comparator, pin 1 in column 35

    cd4063 i_u4
    (
        .b3     ( johnson [3] ),  // Pin 1 <- U2 pin 10 (Q4A)
        .lt_in  ( gnd         ),  // Pin 2 <- GND
        .eq_in  ( vdd         ),  // Pin 3 <- +5V
        .gt_in  ( gnd         ),  // Pin 4 <- GND
        .gt_out ( a_gt_b      ),  // Pin 5 -> A>B
        .eq_out ( a_eq_b      ),  // Pin 6 -> A=B
        .lt_out ( a_lt_b      ),  // Pin 7 -> A<B
        .b0     ( johnson [0] ),  // Pin 9 <- U2 pin 5 (Q1A)
        .a0     ( binary [0]  ),  // Pin 10 <- U1 pin 6 (Q1)
        .b1     ( johnson [1] ),  // Pin 11 <- U2 pin 4 (Q2A)
        .a1     ( binary [1]  ),  // Pin 12 <- U1 pin 11 (Q2)
        .a2     ( binary [2]  ),  // Pin 13 <- U1 pin 14 (Q3)
        .b2     ( johnson [2] ),  // Pin 14 <- U2 pin 3 (Q3A)
        .a3     ( binary [3]  )   // Pin 15 <- U1 pin 2 (Q4)
    );

endmodule

11Testbench and simulation scripts

tb.sv runs both designs side by side from the same clock and reset and compares both counters and the three comparator outputs with a reference model: the number of clock edges since reset, shown modulo 16 in binary and modulo 8 in Johnson code. Like the testbenches of Basics-Graphics-Music, it drives and checks signals only at rising clock edges. It runs 40 clocks, resets in the middle and checks that reset acts at once. The output below is shortened.

tb.sv209 lines · show the codefile
// Testbench for exercise M12.
//
// Runs the generic design (counter_race.sv) and the chip-level design
// (counter_race_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 the two counters through
// 40 clock periods, more than twice the 16 states of the binary counter,
// resets them in the middle, and checks that reset acts at once.

// 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  [3:0] binary,  binary_chips;
    wire  [3:0] johnson, johnson_chips;
    wire        a_gt_b,  a_gt_b_chips;
    wire        a_eq_b,  a_eq_b_chips;
    wire        a_lt_b,  a_lt_b_chips;

    counter_race i_generic
    (
        .clk     ( clk     ),
        .rst     ( rst     ),
        .binary  ( binary  ),
        .johnson ( johnson ),
        .a_gt_b  ( a_gt_b  ),
        .a_eq_b  ( a_eq_b  ),
        .a_lt_b  ( a_lt_b  )
    );

    counter_race_chips i_chips
    (
        .clk     ( clk           ),
        .rst     ( rst           ),
        .binary  ( binary_chips  ),
        .johnson ( johnson_chips ),
        .a_gt_b  ( a_gt_b_chips  ),
        .a_eq_b  ( a_eq_b_chips  ),
        .a_lt_b  ( a_lt_b_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 clock edges since reset.  The binary
    // counter shows it modulo 16; the Johnson counter shows the code of
    // state t mod 8.  rst sets 0 at once.

    int t;

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

    function automatic logic [3:0] johnson_code (input int k);
        if (k <= 4)
            return 4' ((1 << k) - 1);
        else
            return 4' (4'b1111 << (k - 4));
    endfunction

    wire [3:0] binary_expected  = 4' (t);
    wire [3:0] johnson_expected = johnson_code (t % 8);

    wire [2:0] compare_expected = { binary_expected >  johnson_expected,
                                    binary_expected == johnson_expected,
                                    binary_expected <  johnson_expected };

    wire ok_generic =    binary        === binary_expected
                      && johnson       === johnson_expected
                      && { a_gt_b, a_eq_b, a_lt_b } === compare_expected;

    wire ok_chips   =    binary_chips  === binary_expected
                      && johnson_chips === johnson_expected
                      && { a_gt_b_chips, a_eq_b_chips, a_lt_b_chips } === compare_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 [2:0] lights_seen = '0;  // Which of A>B, A=B, A<B were seen

    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);
            lights_seen <= lights_seen | compare_expected;

            $display ("%5d  %b    %b %2d   %b %2d   %s   %s  %s",
                cycle + 1, rst, binary, binary, johnson, johnson,
                a_gt_b ? "A>B" : a_eq_b ? "A=B" : a_lt_b ? "A<B" : "---",
                ok_generic ? "ok     " : "WRONG  ", ok_chips ? "ok" : "WRONG");
        end
    end

    //------------------------------------------------------------------------
    // Asynchronous reset: right after rst rises, both counters must be 0.

    int n_async = 0;

    always @ (posedge rst)
    begin
        # 1;

        if ({ binary, johnson, binary_chips, johnson_chips } !== 16'b0)
        begin
            $display ("WRONG: reset did not act at once");
            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  binary    Johnson   light  generic  chips");

        // Before reset the counters are unknown, as after power-up

        rst <= 1'bx;
        repeat (2) @ (posedge clk);
        rst <= 1'b1;
        repeat (2) @ (posedge clk);
        rst <= 1'b0;

        repeat (40) @ (posedge clk);

        // Reset in the middle

        rst <= 1'b1;
        @ (posedge clk);
        rst <= 1'b0;

        repeat (10) @ (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 && lights_seen == 3'b111 && n_async >= 2)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, lights seen %b, %0d resets", n_errors, n_checks,
                      lights_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 M12: 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 counter_race.sv counter_race_chips.sv cd4029.sv cd4015.sv cd4069.sv cd4063.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 M12: 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 counter_race.sv counter_race_chips.sv cd4029.sv cd4015.sv cd4069.sv cd4063.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 M12: 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 counter_race.sv counter_race_chips.sv cd4029.sv cd4015.sv cd4069.sv cd4063.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  binary    Johnson   light  generic  chips
    1  1    0000  0   0000  0   A=B   ok          ok
    2  1    0000  0   0000  0   A=B   ok          ok
    3  0    0000  0   0000  0   A=B   ok          ok
    4  0    0001  1   0001  1   A=B   ok          ok
    5  0    0010  2   0011  3   A<B   ok          ok
    6  0    0011  3   0111  7   A<B   ok          ok
    7  0    0100  4   1111 15   A<B   ok          ok
    8  0    0101  5   1110 14   A<B   ok          ok
    9  0    0110  6   1100 12   A<B   ok          ok
   10  0    0111  7   1000  8   A<B   ok          ok
   11  0    1000  8   0000  0   A>B   ok          ok
   12  0    1001  9   0001  1   A>B   ok          ok
   13  0    1010 10   0011  3   A>B   ok          ok
   14  0    1011 11   0111  7   A>B   ok          ok
   15  0    1100 12   1111 15   A<B   ok          ok
   16  0    1101 13   1110 14   A<B   ok          ok
   17  0    1110 14   1100 12   A>B   ok          ok
   18  0    1111 15   1000  8   A>B   ok          ok
   19  0    0000  0   0000  0   A=B   ok          ok
   20  0    0001  1   0001  1   A=B   ok          ok
   21  0    0010  2   0011  3   A<B   ok          ok
   22  0    0011  3   0111  7   A<B   ok          ok
   23  0    0100  4   1111 15   A<B   ok          ok
   24  0    0101  5   1110 14   A<B   ok          ok
  …
tb.sv:195: $finish called at 555000 (1ps)
PASS: 106 checks, no errors

To see that the testbench catches mistakes, break something and run it again: feed johnson [3] instead of ~ johnson [3] back in counter_race.sv, or swap the comparator inputs A0 and B0 in counter_race_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 counter_race.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 3–0 show the binary count and LEDs 7–4 the Johnson code. The rightmost digit is a small traffic light: segment a (top) red, g (middle) yellow, d (bottom) green. To run the chip-level design instead, add counter_race_chips.sv and the four chip models and change the module name in the instance.

bgm_lab/lab_top.sv104 lines · show the codefile
// Exercise M12 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 counter_race.sv.  For the chip-level
// design add counter_race_chips.sv and cd4029.sv, cd4015.sv, cd4069.sv,
// cd4063.sv instead, and change the module name below.
//
// The counters run from slow_clk, 1 Hz on every BGM board, and rst is the
// reset of the board.  LEDs 3-0 show the binary count, LEDs 7-4 the Johnson
// code.  The rightmost digit is a small traffic light: segment a (top) is
// red for binary < Johnson, g (middle) yellow for equal, d (bottom) green
// for binary > Johnson.

`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] binary, johnson;
    logic       a_gt_b, a_eq_b, a_lt_b;

    counter_race i_counter_race
    (
        .clk     ( slow_clk ),
        .rst     ( rst      ),
        .binary  ( binary   ),
        .johnson ( johnson  ),
        .a_gt_b  ( a_gt_b   ),
        .a_eq_b  ( a_eq_b   ),
        .a_lt_b  ( a_lt_b   )
    );

    assign led = w_led' ({ johnson, binary });

    //                 a       b     c     d       e     f     g       h
    assign abcdefgh = { a_lt_b, 1'b0, 1'b0, a_gt_b, 1'b0, 1'b0, a_eq_b, 1'b0 };
    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 counter_race.sv.
  3. Run ./03_synthesize_for_fpga.bash and ./04_configure_fpga.bash.

The screen shows a traffic light of three lamps in a dark box; the LEDs and the rightmost digit are as in lab_top.

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

// Exercise M12 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 counter_race.sv.
//
// The counters run from slow_clock.  The LEDs show the binary count (3-0)
// and the Johnson code (7-4), the rightmost digit the traffic light as in
// lab_top, and the screen a traffic light of three square lamps.

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] binary, johnson;
    logic       a_gt_b, a_eq_b, a_lt_b;

    counter_race i_counter_race
    (
        .clk     ( slow_clock ),
        .rst     ( reset      ),
        .binary  ( binary     ),
        .johnson ( johnson    ),
        .a_gt_b  ( a_gt_b     ),
        .a_eq_b  ( a_eq_b     ),
        .a_lt_b  ( a_lt_b     )
    );

    assign led      = { johnson, binary };

    //                 a       b     c     d       e     f     g       h
    assign abcdefgh = { a_lt_b, 1'b0, 1'b0, a_gt_b, 1'b0, 1'b0, a_eq_b, 1'b0 };
    assign digit    = 8'b0000_0001;

    //------------------------------------------------------------------------
    // A traffic light on the screen: three square lamps in a dark box, red
    // on top, bright when on and dim when off

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

        if (x >= 210 & x < 270 & y >= 40 & y < 232)
        begin
            red   = 2;
            green = 4;
            blue  = 2;
        end

        if (x >= 220 & x < 260)
        begin
            if (y >= 50 & y < 90)
                red = a_lt_b ? 31 : 8;
            else if (y >= 116 & y < 156)
            begin
                red   = a_eq_b ? 31 : 8;
                green = a_eq_b ? 50 : 12;
            end
            else if (y >= 182 & y < 222)
                green = a_gt_b ? 63 : 14;
        end
    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 both counters, just as the 555 module clocks the chips on the breadboard.

Segments a, g and d of the display are the traffic light; the two counts go to the BIDIR Pmod. The reset button of the demo board resets both counters.

tiny_tapeout/project.v55 lines · show the codefile
/*
 * Exercise M12 on Tiny Tapeout: a binary counter against a Johnson counter.
 * The 7-segment display of the demo board is a small traffic light, and
 * the two counts go to the BIDIR Pmod.
 *
 * Add counter_race.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 both counters.

    wire [3:0] binary, johnson;
    wire       a_gt_b, a_eq_b, a_lt_b;

    counter_race i_counter_race (
        .clk     ( clk     ),
        .rst     ( ~ rst_n ),
        .binary  ( binary  ),
        .johnson ( johnson ),
        .a_gt_b  ( a_gt_b  ),
        .a_eq_b  ( a_eq_b  ),
        .a_lt_b  ( a_lt_b  )
    );

    // 7-segment display: uo_out [0] is segment a, ..., uo_out [6] is g.
    // Segment a (top) is red for binary < Johnson, g (middle) yellow for
    // equal, d (bottom) green for binary > Johnson.

    assign uo_out  = { 1'b0, a_eq_b, 2'b0, a_gt_b, 2'b0, a_lt_b };

    // Both counts on the BIDIR Pmod, for LEDs or a logic analyzer

    assign uio_out = { johnson, binary };
    assign uio_oe  = 8'hff;

    // 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>_counter_race
  source_files:
    - "project.v"
    - "counter_race.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

This is Maya Grigoryeva's project from lesson 1.6 of the Habr article about the electronics course. The chips are described in the Texas Instruments datasheets for the CD4029B, CD4015B, CD4069UB and CD4063B.