← Breadboard exercisesРусский
BB-FSM-01C · CMOS → RTL → FPGA → ASIC

COUT: green 5 → yellow 1 → red 4

Three implementations of a cyclic traffic-light FSM. This lesson gives one complete build.

1. Purpose and prerequisites

A finite state machine stores the current step and chooses outputs from that state. This cyclic Moore FSM advances once per clock edge; the lamp is a decoded state output. Build it from CMOS, then compare generic RTL with a pin-connected chip model.

№VariantG / Y / RCMOS
1Timofei: green 3 → yellow 1 → red 33 / 1 / 34017 + 4075
2Yuri: green 4 → yellow 2 → red 44 / 2 / 44017 + 4072 + 4071
3COUT: green 5 → yellow 1 → red 45 / 1 / 44017 + 4072

This is a proposed COUT-based variant: green 5, yellow 1, red 4. No specific original COUT schematic was supplied. COUT directly drives green, Q5 directly drives yellow, and one four-input OR gate drives red from Q6…Q9. LED-loaded outputs do not feed logic inputs.

Prerequisites: breadboard contact strips, polarity, basic OR/NOT logic and a rising clock edge. Use the inventory’s regulated 5 V supply, assembled clock and qualified active-high button module. The three indicators must be the specified current-limited 5 V types. This is a teaching circuit, not a road-signal controller.

SystemVerilog style rules

2. Behavior, symbols and observations

After reset: S0, green on. Each rising clock edge advances one stable state. Green lasts 5 clocks, yellow 1, red 4, then green repeats. At 1 Hz these counts are seconds; at f Hz divide each count by f. A manual reset restarts green immediately and shortens the interrupted phase.

green = COUT
yellow = Q5
red = Q6 | Q7 | Q8 | Q9
RESET = rst

CD4017 COUT is high in Q0…Q4 and low in Q5…Q9. It is not a short pulse only at overflow. Q5 selects yellow in the first low interval. OR(Q6,Q7,Q8,Q9) selects red in the remaining four low intervals. The equivalent Boolean expression ~(COUT|Q5) is not used physically, because COUT and Q5 already drive LED loads. COUT changes both at Q4→Q5 and Q9→Q0.

State transition diagram
State transition diagram · SVG · PNG
State encoding diagram
State encoding diagram · SVG · PNG
Sstate[9:0]RYGNext ↑clk
S00000000001001S1
S10000000010001S2
S20000000100001S3
S30000001000001S4
S40000010000001S5
S50000100000010S6
S60001000000100S7
S70010000000100S8
S80100000000100S9
S91000000000100S0
Timing diagram
Timing diagram · SVG · PNG

Interactive model · settled states

Red0
Yellow0
Green0

3. Parts you need

PartQuantityLSSK rowPurpose
CD4017BE137CMOS logic
CD4072BE121CMOS logic
830-contact breadboard145Main board
5 V regulated power module156Supply all logic at 5 V
USB-to-9 V cable157Only to compatible regulator input
Active-high button module165Manual reset; built-in pull-down
Assembled 555 module154Clock, approximately 1 Hz
5 V current-limited LED · red146One lamp
5 V current-limited LED · green147One lamp
5 V current-limited LED · yellow148One lamp
M–M jumper1970Board connections including rail bridges
M–F lead1471Module/LED leads; adapt ends to actual connectors

CSV · 33 wires, including module leads and rail bridges; no reserve. Match connector ends to the actual modules. No parts from the abandoned October 14 observation-buffer design are included.

4. Chip functions, pins and polarity

Chip pinouts
Chip pinouts · SVG · PNG

Top view: notch up on the pin diagram; notch left on the horizontal breadboard drawing, pin 1 below the trench. CD4017: pin 16 = +5 V, 8 = GND, 14 = clock, 13 = inhibit tied low, 15 = active-high asynchronous reset. Reset selects Q0 and makes COUT high. All unused logic inputs are grounded; unused outputs and true NC pins stay open.

U1 · CD4017B

PinFunctionTypeNet
1Q5outputyellow
2Q1outputNC
3Q0outputNC
4Q2outputNC
5Q6outputstate[6]
6Q7outputstate[7]
7Q3outputNC
8VSSsupplyGND
9Q8outputstate[8]
10Q4outputNC
11Q9outputstate[9]
12CARRYoutputgreen
13INHIBITinputGND
14CLOCKinputclk
15RESETinputrst
16VDDsupply+5V

U2 · CD4072B

OR gate pin groups: 2/3/4/5 → 1; 9/10/11/12 → 13. Supply: 14 = +5 V, 7 = GND.

PinFunctionTypeNet
1Joutputred
2Ainputstate[6]
3Binputstate[7]
4Cinputstate[8]
5Dinputstate[9]
6NCNCNC
7VSSsupplyGND
8NCNCNC
9EinputGND
10FinputGND
11GinputGND
12HinputGND
13KoutputNC
14VDDsupply+5V

5. Schematic 1 · Generic logic

Generic logic
Generic logic · SVG · PNG

OR means “at least one input is high”. The state memory is in the counter. No extra clock periods are needed to decode the lamps.

6. Schematic 2 · Chip connections

Chip connections
Chip connections · SVG · PNG

Identical net labels denote connected wires. The pin tables include power, fixed levels and unused pins. LED anodes A connect to the named lamp outputs, cathodes K to GND. Module terminal labels denote functions, not a universal connector order.

U1.12 (COUT) → green LED; U1.1 (Q5) → yellow LED. U1.5/6/9/11 (Q6/Q7/Q8/Q9) → U2.2/3/4/5; U2.1 → red LED. U2.9/10/11/12 → GND; U2.13 is an unused output; U2.6/8 are NC. Q0…Q4 are unused.

Full pin/net database

7. Schematic 3 · Breadboard and assembly

Breadboard wiring
Breadboard wiring · SVG · PNG

B1.a…e at the same number form one contact strip; B1.f…j form another. TP/BP are positive rails, TG/BG ground rails. Bridge the illustrated rail splits at 25–26, then join upper/lower rails. Check the actual board with continuity mode if its rail arrangement differs. Crossings without dots are not junctions.

  1. With power disconnected, place each DIP across the trench, notch LEFT. Use the coordinates below; the chip leg occupies e or f, a jumper uses a different hole in the same strip.
  2. Wire GND, +5 V, rail bridges and tied inputs first. Set the regulator to 5 V before connecting logic; the 9 V input cable must not feed the logic rails directly.
  3. Add clock OUT and button OUT, then the signal wires and LED leads from jumpers.csv. Support external modules beside the board and follow their terminal markings.
  4. Inspect orientation, supplies and unused inputs. Power on, press and release reset. Green should light first. Adjust the ready-made clock to approximately 1 Hz and count a complete cycle.
ICPin 1Last pin
U1B1.f8B1.e8
U2B1.f26B1.e26

Complete wiring CSV · Connectivity checks

IDNetFromTo
W001+5VB1.TP25B1.TP26
W002GNDB1.TG25B1.TG26
W003+5VB1.BP25B1.BP26
W004GNDB1.BG25B1.BG26
W005+5VB1.TP1B1.BP1
W006GNDB1.TG1B1.BG1
W007yellowB1.j8L2.A
W008state[6]B1.j12B1.j27
W009state[7]B1.j13B1.j28
W010GNDB1.j15B1.BG2
W011GNDB1.a11B1.TG2
W012GNDB1.j32B1.BG3
W013GNDB1.a31B1.TG3
W014GNDB1.a30B1.TG4
W015GNDB1.a29B1.TG5
W016GNDB1.a28B1.TG6
W017GNDS1.GNDB1.BG4
W018GNDCLK.GNDB1.BG5
W019GNDPWR.GNDB1.BG6
W020GNDL1.KB1.BG7
W021GNDL2.KB1.BG8
W022GNDL3.KB1.BG9
W023state[8]B1.a15B1.j29
W024state[9]B1.a13B1.j30
W025greenB1.a12L3.A
W026clkB1.a10CLK.OUT
W027rstB1.a9S1.OUT
W028+5VB1.a8B1.TP2
W029+5VB1.a26B1.TP3
W030+5VS1.VCCB1.BP2
W031+5VCLK.VCCB1.BP3
W032+5VPWR.+5VB1.BP4
W033redB1.j26L1.A

8. Generic synthesizable SystemVerilog

The one-hot register stores the stable state. Reset explicitly initializes bit 0; uninitialized hardware is not assumed to start in S0. The output interface is identical for both descriptions. RTL has no timeunit, timeprecision or timescale; use four spaces and plain input/output net ports.

rtl/traffic_light.sv

Download source

// Synthesizable one-hot FSM: green, then yellow, then red.

module traffic_light
(
    input              clk,
    input              rst,

    output             red,
    output             yellow,
    output             green,
    output logic [9:0] state
);

    wire [9:0] next_state = { state [8:0], state [9] };

    always_ff @ (posedge clk or posedge rst)
        if (rst)
            state <= 10'b00_0000_0001;
        else
            state <= next_state;

    assign red    = | state [9:6];
    assign yellow = state [5];
    assign green  = | state [4:0];

endmodule

9. CMOS chip models

Models describe Boolean behavior and are synthesizable. Power pins, drive strength and propagation delays are omitted. CD4017 uses a modulo-10 count, decoded outputs and COUT = count < 5. Inhibit is tied low in these builds. The chip bench additionally checks inhibition and asynchronous reset.

models/cd4017b.sv

Download source

// Synthesizable, zero-delay functional model of a powered CD4017B.
// Physical supply pins: 16 = VDD, 8 = VSS; they are not HDL ports.
// Binary encoding abstracts the chip's five-stage Johnson counter.
// Reset is required. Illegal Johnson-state recovery and electrical effects
// (current, setup/hold, pulse width and propagation delay) are not modeled.

module cd4017b
(
    input   p14_clock,
    input   p13_inhibit,
    input   p15_reset,

    output  p3_q0,
    output  p2_q1,
    output  p4_q2,
    output  p7_q3,
    output  p10_q4,
    output  p1_q5,
    output  p5_q6,
    output  p6_q7,
    output  p9_q8,
    output  p11_q9,
    output  p12_carry
);

    // Falling INHIBIT while CLOCK is high is also a count event.
    // INHIBIT is tied low in this exercise, so synthesis removes the gate.
    // This models the chip; it is not a recommendation to gate FPGA clocks.

    wire effective_clock = p14_clock & ~ p13_inhibit;

    logic [3:0] count;

    always_ff @ (posedge effective_clock or posedge p15_reset)
        if (p15_reset)
            count <= '0;
        else if (count == 4'd9)
            count <= '0;
        else
            count <= count + 1'b1;

    assign p3_q0     = (count == 4'd0);
    assign p2_q1     = (count == 4'd1);
    assign p4_q2     = (count == 4'd2);
    assign p7_q3     = (count == 4'd3);
    assign p10_q4    = (count == 4'd4);
    assign p1_q5     = (count == 4'd5);
    assign p5_q6     = (count == 4'd6);
    assign p6_q7     = (count == 4'd7);
    assign p9_q8     = (count == 4'd8);
    assign p11_q9    = (count == 4'd9);
    assign p12_carry = (count <  4'd5);

endmodule
models/cd4072b.sv

Download source

// Synthesizable ideal gate model. Power pins and propagation delay omitted.

module cd4072b
(
    input              p2_a,
    input              p3_b,
    input              p4_c,
    input              p5_d,
    input              p9_e,
    input              p10_f,
    input              p11_g,
    input              p12_h,
    output             p1_j,
    output             p13_k
);

    assign p1_j  = p2_a | p3_b | p4_c | p5_d;
    assign p13_k = p9_e | p10_f | p11_g | p12_h;

endmodule

10. Pin-connected SystemVerilog

Named ports include physical pin numbers. state[9:0] observes all counter outputs in simulation; it does not require ten extra breadboard LEDs or wires. Compare outputs after combinational logic settles.

rtl/traffic_light_chips.sv

Download source

// Pin-connected model. state observes the counter outputs without adding hardware.

module traffic_light_chips
(
    input              clk,
    input              rst,

    output             red,
    output             yellow,
    output             green,
    output       [9:0] state
);

    logic cout;

    cd4017b u1
    (
        .p1_q5        (state [5]),
        .p2_q1        (state [1]),
        .p3_q0        (state [0]),
        .p4_q2        (state [2]),
        .p5_q6        (state [6]),
        .p6_q7        (state [7]),
        .p7_q3        (state [3]),
        .p9_q8        (state [8]),
        .p10_q4       (state [4]),
        .p11_q9       (state [9]),
        .p12_carry    (cout),
        .p13_inhibit  (1'b0),
        .p14_clock    (clk),
        .p15_reset    (rst)
    );

    cd4072b u2
    (
        .p1_j         (red),
        .p2_a         (state [6]),
        .p3_b         (state [7]),
        .p4_c         (state [8]),
        .p5_d         (state [9]),
        .p9_e         (1'b0),
        .p10_f        (1'b0),
        .p11_g        (1'b0),
        .p12_h        (1'b0),
        .p13_k        ()
    );

    assign green  = cout;
    assign yellow = state [5];

endmodule

11. Testbenches and simulator scripts

Run from this lesson’s directory. Three self-checking benches exercise every gate input combination, counter/carry behavior, twelve complete lamp cycles, reset from every stable state with clock high and low, and both core selections in all three wrappers. Bench files begin with `timescale 1ns / 1ps; RTL files have no time declarations. Watchdogs count clock cycles.

bash scripts/run_icarus.sh
bash scripts/run_verilator.sh
bash scripts/run_questa.sh
python3 scripts/check_synthesis.py

The scripts accept IVERILOG/VVP, VERILATOR and VLIB/VMAP/VLOG/VSIM overrides. Questa installation on this machine: /home/verilog/altera_lite/25.1std/questa_fse/bin. The license is under /home/verilog/flexlm. Tool results and limitations are recorded below; a successful compile is not a simulation pass.

CheckResult
icarus14PASS
synthesisPASS
verilatorPASS
questa_compilePASS
icarus12PASS
questa_runtimeSee log / limitation

Dated validation record and source hashes

Questa runtime is unavailable inside this agent’s sandbox: license host identification fails although the local installation and license are present. This does not imply that the user’s normal terminal cannot run Questa. Icarus 12 and 14 were used here; version 13 is not installed.

tb/tb_cmos.sv

Download source

// Simulation only. Chip pin truth tables and 4017 clock semantics.

`timescale 1ns / 1ps

module tb_cmos;

    localparam period         = 20;
    localparam timeout_cycles = 1000;

    logic clk     = 1'b0;
    logic inhibit = 1'b0;
    logic rst     = 1'b0;
    logic [7:0] a = '0;

    always # (period / 2) clk = ~ clk;

    logic [9:0] q;
    logic carry;

    int expected = 0;

    logic [1:0] y_cd4072b;

    cd4072b gates_cd4072b
    (
        .p2_a         (a [0]),
        .p3_b         (a [1]),
        .p4_c         (a [2]),
        .p5_d         (a [3]),
        .p1_j         (y_cd4072b [0]),
        .p9_e         (a [4]),
        .p10_f        (a [5]),
        .p11_g        (a [6]),
        .p12_h        (a [7]),
        .p13_k        (y_cd4072b [1])
    );

    cd4017b counter
    (
        .p14_clock    (clk),
        .p13_inhibit  (inhibit),
        .p15_reset    (rst),
        .p3_q0        (q [0]),
        .p2_q1        (q [1]),
        .p4_q2        (q [2]),
        .p7_q3        (q [3]),
        .p10_q4       (q [4]),
        .p1_q5        (q [5]),
        .p5_q6        (q [6]),
        .p6_q7        (q [7]),
        .p9_q8        (q [8]),
        .p11_q9       (q [9]),
        .p12_carry    (carry)
    );

    task check_counter;
        if (q !== (10'b1 << expected) || carry !== (expected < 5))
            $fatal (1, "4017 state/carry mismatch: expected=%0d q=%b carry=%b",
                expected, q, carry);
    endtask

    task tick;
        @ (posedge clk);
        expected = rst ? 0 : inhibit ? expected : (expected + 1) % 10;
        # 1;  // Counter register and decoded output settling.
        check_counter ();
    endtask

    initial
    begin
        @ (posedge clk);
        # 1;  // Assert reset after the clock event, without a stimulus/DUT race.
        rst      = 1'b1;
        expected = 0;
        # 1;  // Check asynchronous reset before the next clock edge.
        check_counter ();

        // Inputs are changed after sampling, safely before the next clock edge.
        for (int i = 0; i < 256; i ++)
        begin
            a = 8' (i);
            tick ();

            if (y_cd4072b !== { (| a [7:4]), (| a [3:0]) })
                $fatal (1, "Gate pin truth-table mismatch input=%h", a);
        end

        rst = 1'b0;

        repeat (30)
            tick ();

        inhibit = 1'b1;
        # 1;  // Raising inhibit while CLOCK is high must not count.
        check_counter ();

        repeat (4)
            tick ();

        // Necessary exception: falling INHIBIT with CLOCK low must not count.
        // Posedge-only stimulus cannot test this half of the chip's truth table.
        @ (negedge clk);
        inhibit = 1'b0;
        # 1;  // Settle the effective clock and output decode before checking.
        check_counter ();

        tick ();

        inhibit = 1'b1;
        # 1;  // Raising inhibit with CLOCK high must not count.
        check_counter ();

        inhibit  = 1'b0;
        expected = (expected + 1) % 10;
        # 1;  // Falling inhibit with CLOCK high IS a count event.
        check_counter ();

        rst      = 1'b1;
        expected = 0;
        # 1;  // Reset must act without waiting for the next clock edge.
        check_counter ();

        inhibit = 1'b1;
        tick ();
        inhibit = 1'b0;
        # 1;  // Reset also dominates the falling-INHIBIT count event.
        check_counter ();

        repeat (2)
            tick ();

        $display ("PASS CMOS: 256 gate input combinations; 30 count edges; carry, inhibit and asynchronous reset");
        $finish;
    end

    initial
    begin
        repeat (timeout_cycles) @ (posedge clk);
        $fatal (1, "Timeout after %0d clock cycles", timeout_cycles);
    end

endmodule
tb/tb_traffic_light.sv

Download source

// Simulation only. Portable procedural checks; no classes, DPI or UVM.

`timescale 1ns / 1ps

module tb_traffic_light;

    localparam period         = 20;
    localparam timeout_cycles = 500;

    logic clk = 1'b0;
    logic rst = 1'b0;

    always # (period / 2) clk = ~ clk;

    logic red_generic, yellow_generic, green_generic;
    logic red_chips, yellow_chips, green_chips;
    logic [9:0] state_generic, state_chips;

    int expected     = 0;
    int checks       = 0;
    int red_slots    = 0;
    int yellow_slots = 0;
    int green_slots  = 0;
    int visits [0:9];

    traffic_light generic_dut
    (
        .clk          (clk),
        .rst          (rst),
        .red          (red_generic),
        .yellow       (yellow_generic),
        .green        (green_generic),
        .state        (state_generic)
    );

    traffic_light_chips chip_dut
    (
        .clk          (clk),
        .rst          (rst),
        .red          (red_chips),
        .yellow       (yellow_chips),
        .green        (green_chips),
        .state        (state_chips)
    );

    task check_state;
        logic [9:0] wanted;
        logic [2:0] lamps;

        wanted = 10'b1 << expected;
        lamps  = expected < 5 ? 3'b001 : expected < 6 ? 3'b010 : 3'b100;

        if (   state_generic !== wanted
            || state_chips   !== wanted
            || { red_generic, yellow_generic, green_generic } !== lamps
            || { red_chips,   yellow_chips,   green_chips   } !== lamps)
        begin
            $fatal (1, "state=%0d generic=%b/%b chips=%b/%b",
                expected,
                state_generic, { red_generic, yellow_generic, green_generic },
                state_chips,   { red_chips,   yellow_chips,   green_chips   });
        end

        checks = checks + 1;
    endtask

    task tick;
        @ (posedge clk);
        expected = rst ? 0 : (expected + 1) % 10;
        # 1;  // Let register updates and lamp decoding settle before sampling.
        check_state ();
    endtask

    // Called between rising edges, after tick or the focused low-phase check.
    // Checking before the next clock edge distinguishes asynchronous reset.
    task reset_now;
        rst      = 1'b1;
        expected = 0;
        # 1;  // Asynchronous register update and combinational output settling.
        check_state ();
        rst = 1'b0;
    endtask

    initial
    begin
        $dumpfile ("traffic_light.vcd");
        $dumpvars (0, tb_traffic_light);

        for (int i = 0; i < 10; i ++)
            visits [i] = 0;

        @ (posedge clk);
        # 1;  // Place the initial reset after the clock event, without a race.
        reset_now ();

        for (int round = 0; round < 12; round ++)
            for (int i = 0; i < 10; i ++)
            begin
                visits [expected] = visits [expected] + 1;

                if (red_generic)
                    red_slots = red_slots + 1;

                if (yellow_generic)
                    yellow_slots = yellow_slots + 1;

                if (green_generic)
                    green_slots = green_slots + 1;

                tick ();
            end

        if (red_slots != 48 || yellow_slots != 12 || green_slots != 60)
            $fatal (1, "5/1/4 green/yellow/red duration mismatch");

        for (int i = 0; i < 10; i ++)
            if (visits [i] != 12)
                $fatal (1, "Missing state %0d", i);

        // Reset from every state while CLOCK is high, then while it is low.
        for (int low_phase = 0; low_phase < 2; low_phase ++)
            for (int i = 0; i < 10; i ++)
            begin
                tick ();
                reset_now ();

                repeat (i)
                    tick ();

                if (low_phase != 0)
                begin
                    // Necessary exception: exercise reset with CLOCK low and
                    // verify that a falling clock edge does not advance state.
                    @ (negedge clk);
                    # 1;  // Observe any erroneous falling-edge state update.
                    check_state ();
                end

                reset_now ();
            end

        rst      = 1'b1;
        expected = 0;

        repeat (3)
            tick ();  // Reset dominates the clock.

        rst = 1'b0;
        tick ();

        $display ("PASS traffic_light: %0d checks; 12 full cycles; green/yellow/red=60/12/48; reset and wrap",
            checks);
        $finish;
    end

    initial
    begin
        repeat (timeout_cycles) @ (posedge clk);
        $fatal (1, "Timeout after %0d clock cycles", timeout_cycles);
    end

endmodule
tb/tb_integrations.sv

Download source

// Simulation only. Both core versions in all three integration wrappers.

`timescale 1ns / 1ps

module tb_integrations;

    localparam period         = 20;
    localparam timeout_cycles = 200;

    logic clk = 1'b0;
    logic rst = 1'b0;
    logic ena = 1'b1;

    always # (period / 2) clk = ~ clk;

    logic [7:0] ui  = '0;
    logic [7:0] key = '0;

    logic [7:0] lab_led  [0:1];
    logic [7:0] hack_led [0:1];
    logic [7:0] tt_out   [0:1];
    logic [7:0] tt_io    [0:1];
    logic [7:0] tt_oe    [0:1];

    int n_bgm = 0;
    int n_tt  = 0;
    logic [7:0] seven [0:9];

    generate
        genvar k;

        for (k = 0; k < 2; k ++)
        begin : versions
            lab_top # (.CHIP_MODEL (k)) lab
            (
                .clk          (clk),
                .slow_clk     (clk),
                .rst          (rst),
                .key          (key [3:0]),
                .sw           (8'b0),
                .led          (lab_led [k]),
                .abcdefgh     (),
                .digit        (),
                .x            (10'b0),
                .y            (9'b0),
                .red          (),
                .green        (),
                .blue         (),
                .mic          (24'b0),
                .sound        (),
                .uart_rx      (1'b0),
                .uart_tx      (),
                .gpio         ()
            );

            hackathon_top # (.CHIP_MODEL (k)) hack
            (
                .clock        (clk),
                .slow_clock   (clk),
                .reset        (rst),
                .key          (key),
                .led          (hack_led [k]),
                .abcdefgh     (),
                .digit        (),
                .x            (9'b0),
                .y            (9'b0),
                .red          (),
                .green        (),
                .blue         (),
                .gpio         ()
            );

            tt_um_carry_traffic_light # (.USE_CHIP_MODEL (k)) tt
            (
                .ui_in        (ui),
                .uo_out       (tt_out [k]),
                .uio_in       (8'b0),
                .uio_out      (tt_io [k]),
                .uio_oe       (tt_oe [k]),
                .ena          (ena),
                .clk          (clk),
                .rst_n        (~ rst)
            );
        end
    endgenerate

    task check_all;
        logic [2:0] bgm_lamps;
        logic [2:0] tt_lamps;
        logic [7:0] segments;

        bgm_lamps = n_bgm < 5 ? 3'b100 : n_bgm < 6 ? 3'b010 : 3'b001;
        tt_lamps  = n_tt  < 5 ? 3'b100 : n_tt  < 6 ? 3'b010 : 3'b001;
        segments  = ui [0] ? seven [n_tt] : n_tt < 5 ? 8'h08 : n_tt < 6 ? 8'h40 : 8'h01;

        for (int j = 0; j < 2; j ++)
        begin
            if (   lab_led  [j] !== { 5'b0, bgm_lamps }
                || hack_led [j] !== { 5'b0, bgm_lamps })
                $fatal (1, "BGM output mismatch state=%0d model=%0d", n_bgm, j);

            if (   tt_out [j] !== (ena ? segments : 8'b0)
                || tt_io  [j] !== (ena ? { 5'b0, tt_lamps } : 8'b0)
                || tt_oe  [j] !== (ena ? 8'h07 : 8'b0))
                $fatal (1, "Tiny Tapeout output mismatch state=%0d model=%0d", n_tt, j);
        end
    endtask

    task tick;
        @ (posedge clk);
        n_bgm = rst || key [0] ? 0 : (n_bgm + 1) % 10;
        n_tt  = rst           ? 0 : (n_tt  + 1) % 10;
        # 1;  // Register updates and wrapper output decoding must settle.
        check_all ();
    endtask

    initial
    begin
        seven [0] = 8'h3f;
        seven [1] = 8'h06;
        seven [2] = 8'h5b;
        seven [3] = 8'h4f;
        seven [4] = 8'h66;
        seven [5] = 8'h6d;
        seven [6] = 8'h7d;
        seven [7] = 8'h07;
        seven [8] = 8'h7f;
        seven [9] = 8'h6f;

        @ (posedge clk);
        # 1;  // Drive reset after the clock event, without a stimulus/DUT race.
        rst   = 1'b1;
        n_bgm = 0;
        n_tt  = 0;
        # 1;  // Asynchronous reset must be observable before the next clock.
        check_all ();
        rst = 1'b0;

        // Each display mode sees all stable states; stimulus changes after sampling.
        for (int i = 0; i < 30; i ++)
        begin
            ui = 8' ((i / 10) % 2);
            tick ();
        end

        // ena blanks TT outputs but must not stop the internal state sequence.
        ena = 1'b0;

        repeat (3)
            tick ();

        ena = 1'b1;
        # 1;  // Combinational output-enable and display settling.
        check_all ();

        // Check the BGM reset button independently of the dedicated TT reset.
        key   = 8'd1;
        n_bgm = 0;
        # 1;  // Asynchronous button reset; TT must retain its own state.
        check_all ();

        repeat (2)
            tick ();

        key = '0;
        tick ();

        rst   = 1'b1;
        n_bgm = 0;
        n_tt  = 0;
        # 1;  // Asynchronous dedicated reset in all wrappers.
        check_all ();

        repeat (2)
            tick ();

        rst = 1'b0;
        tick ();

        $display ("PASS integrations: both implementations in BGM lab/hackathon and Tiny Tapeout; 30 steps, both display modes, 3 disabled cycles, independent button and dedicated resets");
        $finish;
    end

    initial
    begin
        repeat (timeout_cycles) @ (posedge clk);
        $fatal (1, "Timeout after %0d clock cycles", timeout_cycles);
    end

endmodule
scripts/run.sh

Download source

#!/usr/bin/env bash
set -euo pipefail
exercise_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)
simulator=${1:-icarus}
case "$simulator" in icarus|questa|verilator) ;; *) echo "Usage: $0 {icarus|questa|verilator}" >&2; exit 2;; esac
build_dir="$exercise_dir/build/$simulator"
mkdir -p "$build_dir"
cd "$build_dir"
core=("$exercise_dir"/rtl/*.sv "$exercise_dir"/models/*.sv)
wrappers=("$exercise_dir/integration/bgm_lab/lab_top.sv" "$exercise_dir/integration/bgm_hackathon/hackathon_top.sv" "$exercise_dir/integration/tinytapeout/project.v")
for top in ${TEST_TOP:-tb_cmos tb_traffic_light tb_integrations}; do
    case "$top" in tb_cmos|tb_traffic_light|tb_integrations) ;; *) echo "Unknown test: $top" >&2; exit 2;; esac
    sources=("${core[@]}" "$exercise_dir/tb/$top.sv")
    if [[ "$top" == tb_integrations ]]; then sources+=("${wrappers[@]}"); fi
    case "$simulator" in
        icarus)
            "${IVERILOG:-iverilog}" -g2012 -Wall -s "$top" -o "$top.vvp" "${sources[@]}" 2>&1 | tee "$top.compile.log"
            "${VVP:-vvp}" "$top.vvp" 2>&1 | tee "$top.log"
            ;;
        questa)
            [[ -f modelsim.ini ]] || "${VMAP:-vmap}" -c > /dev/null
            [[ -d work ]] || "${VLIB:-vlib}" work
            # The RTL has no time declarations; set a simulation-only default.
            "${VLOG:-vlog}" -sv -timescale 1ns/1ps -work work "${sources[@]}" 2>&1 | tee "$top.compile.log"
            # $fatal/onbreak returns failure; normal $finish exits successfully.
            "${VSIM:-vsim}" "${QUESTA_MODE:--batch}" -onfinish exit "work.$top" -do "onerror {quit -code 1}; onbreak {quit -code 1}; run -all; quit -code 0" 2>&1 | tee "$top.log"
            ;;
        verilator)
            "${VERILATOR:-verilator}" --binary --timing --trace --timescale 1ns/1ps --top-module "$top" --Mdir "obj_$top" \
                -Wno-PINCONNECTEMPTY -Wno-DECLFILENAME -j 2 "${sources[@]}" > "$top.compile.log" 2>&1 || { cat "$top.compile.log"; exit 1; }
            "./obj_$top/V$top" 2>&1 | tee "$top.log"
            ;;
    esac
    grep -q 'PASS ' "$top.log" || { echo "Missing PASS from $top" >&2; exit 1; }
done
scripts/run_icarus.sh

Download source

#!/usr/bin/env bash
set -euo pipefail
exec "$(dirname -- "${BASH_SOURCE[0]}")/run.sh" icarus
scripts/run_questa.sh

Download source

#!/usr/bin/env bash
set -euo pipefail

# Preserve explicit tool choices; otherwise find a local Quartus installation.
questa_bin=${QUESTA_BIN:-}
if [[ -z "$questa_bin" ]]; then
    if command -v "${VSIM:-vsim}" > /dev/null 2>&1; then
        questa_bin=$(dirname -- "$(command -v "${VSIM:-vsim}")")
    else
        for candidate in "$HOME"/altera_lite/*/questa_fse/bin \
                         "$HOME"/intelFPGA_lite/*/questa_fse/bin \
                         /opt/altera_lite/*/questa_fse/bin \
                         /opt/intelFPGA_lite/*/questa_fse/bin; do
            if [[ -x "$candidate/vsim" ]]; then
                questa_bin=$candidate
                break
            fi
        done
    fi
fi
if [[ -n "$questa_bin" ]]; then
    export VLIB=${VLIB:-$questa_bin/vlib}
    export VMAP=${VMAP:-$questa_bin/vmap}
    export VLOG=${VLOG:-$questa_bin/vlog}
    export VSIM=${VSIM:-$questa_bin/vsim}
fi

# Read the user's existing license; never copy it into the project or archive.
if [[ -z "${SALT_LICENSE_SERVER:-}" && -f "$HOME/flexlm/license.dat" ]]; then
    export SALT_LICENSE_SERVER="$HOME/flexlm/license.dat"
fi

exec "$(dirname -- "${BASH_SOURCE[0]}")/run.sh" questa
scripts/run_verilator.sh

Download source

#!/usr/bin/env bash
set -euo pipefail
exec "$(dirname -- "${BASH_SOURCE[0]}")/run.sh" verilator
scripts/check_synthesis.py

Download source

#!/usr/bin/env python3
"""Check both cores using the built-in Yosys reader, or optionally Slang."""
import argparse
import os
from pathlib import Path
import subprocess


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--frontend', choices=['verilog', 'slang'], default='verilog')
    args = parser.parse_args()
    exercise = Path(__file__).resolve().parents[1]
    build = exercise / 'build/synthesis'
    build.mkdir(parents=True, exist_ok=True)
    sources = sorted((exercise / 'rtl').glob('*.sv'))
    sources += sorted((exercise / 'models').glob('*.sv'))
    # Fixed relative source names also work when the exercise directory has spaces.
    filenames = ' '.join(p.relative_to(exercise).as_posix() for p in sources)
    yosys = os.environ.get('YOSYS', 'yosys')

    for top in ['traffic_light', 'traffic_light_chips']:
        read = (f'read_slang --top {top}' if args.frontend == 'slang'
                else 'read_verilog -sv')
        commands = (f'{read} {filenames}; '
                    f'synth -top {top} -flatten; check -assert; stat')
        log = build / f'{top}.log'
        with log.open('w') as output:
            plugin = ['-m', 'slang'] if args.frontend == 'slang' else []
            result = subprocess.run([yosys, '-Q'] + plugin + ['-p', commands],
                                    cwd=exercise, stdout=output, stderr=subprocess.STDOUT)
        if result.returncode:
            print(log.read_text())
            raise SystemExit(result.returncode)
        print(f'PASS synthesis: {top} (Yosys, {args.frontend} frontend); {log}')


if __name__ == '__main__':
    main()

12. BGM lab_top integration

CHIP_MODEL=0 chooses generic RTL; 1 chooses the chip-connected model. Supply a 1 Hz slow clock. Dedicated reset OR key[0] resets to green. led[2:0] = {green,yellow,red}; remaining LED bits are zero. The LCD is filled with the current lamp color; the seven-segment output is blank.

lab_top uses clk, slow_clk and rst, with the BGM lab interface. The fast clock is not the lesson’s state clock.

python3 scripts/stage_integration.py lab /tmp/traffic_light_carry_lab

Choose a new destination directory. Copy the staged source set into a new BGM exercise, replace its top wrapper, and add sources.f entries to the board project. Board-specific constraints and output polarity remain the platform’s responsibility. Compile only one variant’s source set at a time: the cores intentionally share module names.

integration/bgm_lab/lab_top.sv

Download source

// Full BGM lab interface. Requires w_key >= 1 and w_led >= 3.

module lab_top
# (
    parameter CHIP_MODEL    = 0,
    parameter clk_mhz       = 50,
    parameter w_key         = 4,
    parameter w_sw          = 8,
    parameter w_led         = 8,
    parameter w_digit       = 8,
    parameter w_gpio        = 100,

    parameter screen_width  = 640,
    parameter screen_height = 480,

    parameter w_red         = 4,
    parameter w_green       = 4,
    parameter w_blue        = 4,

    parameter w_x           = $clog2 (screen_width),
    parameter 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 [w_led   - 1:0] led,

    // A dynamic seven-segment display

    output [          7:0] abcdefgh,
    output [w_digit - 1:0] digit,

    // Graphics

    input  [w_x     - 1:0] x,
    input  [w_y     - 1:0] y,

    output [w_red   - 1:0] red,
    output [w_green - 1:0] green,
    output [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
);

    logic lamp_red, lamp_yellow, lamp_green;
    logic [9:0] state;

    wire exercise_reset = rst | key [0];

    generate
        if (CHIP_MODEL == 0)
        begin : generic_version
            traffic_light dut
            (
                .clk          (slow_clk),
                .rst          (exercise_reset),
                .red          (lamp_red),
                .yellow       (lamp_yellow),
                .green        (lamp_green),
                .state        (state)
            );
        end
        else
        begin : chip_version
            traffic_light_chips dut
            (
                .clk          (slow_clk),
                .rst          (exercise_reset),
                .red          (lamp_red),
                .yellow       (lamp_yellow),
                .green        (lamp_green),
                .state        (state)
            );
        end
    endgenerate

    // Infrastructure LEDs and graphics use active-high logical signals.

    assign led      = w_led' ({ 5'b0, lamp_green, lamp_yellow, lamp_red });
    assign red      = { w_red   { lamp_red   | lamp_yellow } };
    assign green    = { w_green { lamp_green | lamp_yellow } };
    assign blue     = '0;
    assign abcdefgh = '0;
    assign digit    = '0;
    assign sound    = '0;
    assign uart_tx  = 1'b1;
    assign gpio     = 'z;

    wire unused_inputs = & { 1'b0, clk, sw, key, x, y, mic, uart_rx, state };

endmodule

13. BGM hackathon_top integration

CHIP_MODEL=0 chooses generic RTL; 1 chooses the chip-connected model. Supply a 1 Hz slow clock. Dedicated reset OR key[0] resets to green. led[2:0] = {green,yellow,red}; remaining LED bits are zero. The LCD is filled with the current lamp color; the seven-segment output is blank.

The module name is hackathon_top (with h). This wrapper preserves the 480×272 example interface with x[8:0], y[8:0], clock, slow_clock and reset. If selecting an 800×480 BGM configuration, adapt x to [9:0] to match that configuration. gpio is high impedance.

python3 scripts/stage_integration.py hackathon /tmp/traffic_light_carry_hackathon

Choose a new destination directory. Copy the staged source set into a new BGM exercise, replace its top wrapper, and add sources.f entries to the board project. Board-specific constraints and output polarity remain the platform’s responsibility. Compile only one variant’s source set at a time: the cores intentionally share module names.

integration/bgm_hackathon/hackathon_top.sv

Download source

// The BGM module is spelled hackathon_top, with "h".

module hackathon_top
# (
    parameter CHIP_MODEL = 0
)
(
    input        clock,
    input        slow_clock,
    input        reset,

    input  [7:0] key,
    output [7:0] led,

    // A dynamic seven-segment display

    output [7:0] abcdefgh,
    output [7:0] digit,

    // LCD screen interface

    input  [8:0] x,
    input  [8:0] y,

    output [4:0] red,
    output [5:0] green,
    output [4:0] blue,

    inout  [3:0] gpio
);

    logic lamp_red, lamp_yellow, lamp_green;
    logic [9:0] state;

    wire exercise_reset = reset | key [0];

    generate
        if (CHIP_MODEL == 0)
        begin : generic_version
            traffic_light dut
            (
                .clk          (slow_clock),
                .rst          (exercise_reset),
                .red          (lamp_red),
                .yellow       (lamp_yellow),
                .green        (lamp_green),
                .state        (state)
            );
        end
        else
        begin : chip_version
            traffic_light_chips dut
            (
                .clk          (slow_clock),
                .rst          (exercise_reset),
                .red          (lamp_red),
                .yellow       (lamp_yellow),
                .green        (lamp_green),
                .state        (state)
            );
        end
    endgenerate

    assign led      = { 5'b0, lamp_green, lamp_yellow, lamp_red };
    assign red      = { 5 { lamp_red   | lamp_yellow } };
    assign green    = { 6 { lamp_green | lamp_yellow } };
    assign blue     = '0;
    assign abcdefgh = '0;
    assign digit    = '0;
    assign gpio     = 'z;

    wire unused_inputs = & { 1'b0, clock, key, x, y, state };

endmodule

14. Tiny Tapeout project.v integration

Top module: tt_um_carry_traffic_light. Compile project.v as SystemVerilog with all staged dependencies. Supply an external 1 Hz clk. rst_n is active low and is inverted internally. USE_CHIP_MODEL selects the implementation; the default is 0.

SignalMeaning
ui_in[0]0: red/yellow/green as top/middle/bottom bars; 1: stable state number
uo_out[7:0]{dp,g,f,e,d,c,b,a} · active high
uio_out[2:0]{green,yellow,red}
uio_oe00000111 when ena=1, otherwise 0
ena=0Output values and output enables become zero; state continues advancing

The state number is not seconds remaining. This wrapper implements the circuit inside the FPGA/ASIC platform; do not wire the 5 V breadboard outputs to those platform pins. Merge info_fragment.yaml with the Tiny Tapeout template metadata. The staged src/ list uses flat filenames.

python3 scripts/stage_integration.py tinytapeout /tmp/traffic_light_carry_tt
integration/tinytapeout/project.v

Download source

// Synthesizable Tiny Tapeout top; compile as SystemVerilog.
// Set the external project clock to 1 Hz.
// Set USE_CHIP_MODEL to 1 to synthesize the pin-connected version.

module tt_um_carry_traffic_light
# (
    parameter USE_CHIP_MODEL = 0
)
(
    input  [7:0] ui_in,
    output [7:0] uo_out,
    input  [7:0] uio_in,
    output [7:0] uio_out,
    output [7:0] uio_oe,
    input        ena,
    input        clk,
    input        rst_n
);

    logic red, yellow, green;
    logic [9:0] state;

    generate
        if (USE_CHIP_MODEL == 0)
        begin : generic_version
            traffic_light dut
            (
                .clk          (clk),
                .rst          (~ rst_n),
                .red          (red),
                .yellow       (yellow),
                .green        (green),
                .state        (state)
            );
        end
        else
        begin : chip_version
            traffic_light_chips dut
            (
                .clk          (clk),
                .rst          (~ rst_n),
                .red          (red),
                .yellow       (yellow),
                .green        (green),
                .state        (state)
            );
        end
    endgenerate

    // TT output order [7:0] = { dp, g, f, e, d, c, b, a }; active high.
    // DIP 0 = 0: top/middle/bottom bar represents red/yellow/green.
    // DIP 0 = 1: show state number 0..9, not seconds remaining.

    logic [7:0] decimal_segments;

    always_comb
    begin
        decimal_segments = '0;

        case (state)
        10'b00_0000_0001: decimal_segments = 8'h3f;
        10'b00_0000_0010: decimal_segments = 8'h06;
        10'b00_0000_0100: decimal_segments = 8'h5b;
        10'b00_0000_1000: decimal_segments = 8'h4f;
        10'b00_0001_0000: decimal_segments = 8'h66;
        10'b00_0010_0000: decimal_segments = 8'h6d;
        10'b00_0100_0000: decimal_segments = 8'h7d;
        10'b00_1000_0000: decimal_segments = 8'h07;
        10'b01_0000_0000: decimal_segments = 8'h7f;
        10'b10_0000_0000: decimal_segments = 8'h6f;
        default:          decimal_segments = '0;
        endcase
    end

    wire [7:0] bars = { 1'b0, yellow, 2'b00, green, 2'b00, red };

    assign uo_out  = ena ? (ui_in [0] ? decimal_segments : bars) : '0;
    assign uio_out = ena ? { 5'b0, green, yellow, red } : '0;
    assign uio_oe  = ena ? 8'b0000_0111 : '0;

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

endmodule
integration/tinytapeout/info_fragment.yaml

Download source

project:
  top_module: "tt_um_carry_traffic_light"
  clock_hz: 1
  source_files:
    - "project.v"
    - "traffic_light.sv"
    - "traffic_light_chips.sv"
    - "cd4017b.sv"
    - "cd4072b.sv"
# Flat names for the staged src/ directory; merge the template metadata.
scripts/stage_integration.py

Download source

#!/usr/bin/env python3
"""Stage one platform and all local HDL dependencies in a new directory."""
from pathlib import Path
import argparse,shutil
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('target',choices=['lab','hackathon','tinytapeout'])
p.add_argument('destination',type=Path)
a=p.parse_args();root=Path(__file__).resolve().parents[1]
if a.destination.exists():p.error('Destination already exists; choose a new directory.')
folder={'lab':'bgm_lab','hackathon':'bgm_hackathon','tinytapeout':'tinytapeout'}[a.target]
files=list((root/'rtl').glob('*.sv'))+list((root/'models').glob('*.sv'))
files+=list((root/'integration'/folder).glob('*.sv'))+list((root/'integration'/folder).glob('*.v'))
a.destination.mkdir(parents=True)
for f in files:shutil.copy2(f,a.destination/f.name)
(a.destination/'sources.f').write_text(''.join(f.name+'\n' for f in files))
if a.target=='tinytapeout':shutil.copy2(root/'integration/tinytapeout/info_fragment.yaml',a.destination/'info_fragment.yaml')
print('Staged',len(files),'HDL files in',a.destination)

15. Experiments, troubleshooting and sources

Predict the lamp after every edge before running the demo. Measure one full cycle. Change the clock frequency and explain which quantities change. Compare chip count, gate count and reset behavior across all three variants. Change the output decode while keeping the same state sequence, then update the expected-output table and testbench.

SymptomFirst check
No sequencePower, ground, clock OUT, inhibit=0, RESET not held high
Wrong duration/colorVariant, Q numbering from Q0, LED polarity and pin table
Reset does not restart greenActive-high button, pull-down, reset net and chip orientation

Validation covers ideal HDL behavior and static wiring connectivity. Physical assembly, LED loading/brightness, clock voltage levels and full FPGA place-and-route or ASIC signoff have not been performed. Check actual module variants and manufacturer timing requirements on the hardware.

Rebuild all three variants: python3 breadboard/tools/build_traffic.py --png. Each page also has a Markdown version.