Breadboard exercises/ M11aEnglishРусский

Exercise M11a · mini-project · finite state machine

Traffic light: Timofei's original circuit

Green for three seconds, yellow for one, red for three, and again. This is the traffic light as Timofei Nikiforov, a school student, built it: a 4017 decade counter that resets itself when it reaches state 7, and the four 2-input OR gates of a 4071. It is a finite state machine with seven states in a ring.

2 chips4017 counter, 4071 OR gates
18 + 3 wireson the board + jumper leads to the clock module
7 states3 green, 1 yellow, 3 red
~1 Hz clockfrom the 555 module, no clock circuit to build
Four variants of this exercise

1What it is and why it matters

What it does. A traffic light that changes once per clock period: three periods green, one yellow, three red, then green again. With the clock module set to 1 Hz that is 3 seconds of green, 1 of yellow and 3 of red, in the order of a real traffic light: yellow comes between green and red.

Timofei's circuit. Timofei Nikiforov worked this circuit out on his own and built it with his younger brother Nil. The Habr article (lesson 1.7) and “Teaching children electronics is due for a major redesign” (picture 15) describe a version with ten states, which is exercise M11b. Timofei describes his own circuit like this: 3 seconds of green, 1 of yellow and 3 of red; the counter resets at Q7; two 3-input OR gates drive the lights. A photo of his board shows how he built it: a 4017, a 4071 whose four 2-input OR gates make the two 3-input ones, a traffic-light module plugged straight into the breadboard and a 555 clock module. There is no reset button. This page builds that circuit. The photo does not show every wire, so which states go to which gate follows from the timing.

How it works. The 4017 has ten outputs, Q0 to Q9, and exactly one of them is high at any time: Q0 after a reset, Q1 after the first rising clock edge, and so on. Each output is one state of a state machine. Here Q7 is wired to RESET: as soon as the counter reaches state 7, Q7 goes high and clears the counter, so the state after S6 is S0, and the ring has seven states. OR gates turn the states into lights:

green = (Q0 OR Q1) OR Q2
yellow = Q3
red   = (Q4 OR Q5) OR Q6
RESET = Q7

A shorter ring through RESET. Wiring an output to RESET is a classic way to make a 4017 count to less than ten. It works because RESET is asynchronous: it does not wait for the clock. State 7 lasts only as long as the reset takes, about 0.3 µs at 5 V; the Texas Instruments datasheet gives 265 ns from RESET to the outputs as a typical value. No lamp can show such a pulse, and nothing else listens to Q7. The trick is safe on the 4017 because its decoder never glitches (section 2), so Q7 cannot pulse at a wrong moment.

Two gates make one. OR does not care how its inputs are grouped: (Q0 OR Q1) OR Q2 is the same as Q0 OR Q1 OR Q2. So two 2-input gates in a chain make a 3-input OR, and the four gates of one 4071 are exactly enough for green and red. The only cost is a second gate delay, about 0.1 µs, which a traffic light does not notice.

Where it is used. A machine whose states follow each other in a fixed ring, one step per clock, is the simplest kind of finite state machine (FSM). Chips are full of them: a controller that steps through the phases of a transfer (send the address, wait, take the data), the sequencer of a simple processor (fetch, decode, execute, write back), a display driver that lights one digit after another, a round-robin scheduler that gives every requester its turn, a timer that cuts a period into slots. In FPGAs such sequencers are often built exactly like the outputs of the 4017: one flip-flop per state, one of them set at a time (a one-hot code), and outputs that are ORs of states.

Why learn it.

2The key element: a counter with decoded outputs

S0S1S2S3S4S5S6rstS7S7: on the breadboard: Q7 → RESETfor about 0.3 µsevery clock edge:one step clockwise

Every rising edge of the clock moves the machine one step clockwise. The colour of each circle is the light it shows. The state changes only on the clock edge, and the light depends only on the state: this is a Moore machine.

The dashed S7 exists only on the breadboard: the 4017 steps into it at the clock edge and leaves it about 0.3 µs later through RESET. As a state machine, the circuit has seven states. The arrow marked rst is the reset of the SystemVerilog designs and of the simulation; the breadboard has no reset button.

Inside, the 4017 is not a binary counter. A binary counter needs four flip-flops for ten states, but its decoder sees several bits change at once (7 → 8 changes all four), and for a moment it may show a wrong state, a glitch. With a binary counter, a glitch on the output wired to RESET could clear the counter at the wrong moment.

Inside the 4017: a Johnson counter and a decoder

The 4017 uses five D flip-flops connected as a shift register, with the last bit fed back inverted into the first. Starting from 00000 the register fills with ones from the right and then with zeros, changing exactly one bit per clock. Two neighbouring bits identify each pattern, so one 2-input AND gate per state is enough, and the decoder cannot glitch. Here the ring stops after the seventh pattern:

StateJohnson register r4…r0Decoder: q = 1 whenQ6…Q0Carry outLight
S000000~r0 & ~r400000011green
S100001r0 & ~r100000101green
S200011r1 & ~r200001001green
S300111r2 & ~r300010001yellow
S401111r3 & ~r400100001red
S511111r0 & r401000000red
S611110~r0 & r110000000red
S711100~r1 & r2Q7 = 1 resets the 4017 at once

The symbols

D flip-flop with reset

DQRDclkQrst
rstclkDQ after
1anyany0, at once
0↑00
0↑11
0no edgeanykeeps Q

Q takes the value of D at the rising edge of the clock (↑) and keeps it until the next edge. R = 1 clears Q at once, without the clock.

NOT

AY
AY
01
10

Feeds the inverted last bit back into the first flip-flop. A small circle on a gate input or output means NOT.

AND with an inverted input

ABY
ABY = A AND NOT B
000
010
101
110

One such gate per state in the decoder, for example q1 = r0 AND NOT r1, and three more that end the ring after state 6 in schematic 1.

OR, 2 inputs

ABY
ABY = A OR B
000
011
101
111

Y = 1 when any input is 1. Two of them in a chain make a 3-input OR: feed the output of the first into an input of the second.

4017 decade counter

4017CLKINHRSTQ0Q1Q2Q3Q4Q5Q6Q7Q8Q9CO

CLK counts on the rising edge, INH = 1 holds the count, RST = 1 sets the count to 0. One of Q0–Q9 is high; CO is high in states 0–4.

Waveforms

clkrstr4…r00000000001000110011101111111111111000000000010001100111011111111111110stateS0S1S2S3S4S5S6S0S1S2S3S4S5S6Q0Q1Q2Q3Q4Q5Q6greenyellowred
From the simulation of tb.sv in Icarus Verilog. Before reset the state is unknown (shaded). The testbench changes reset right after a rising clock edge; from then on every rising edge (dotted lines) shifts the Johnson register r and moves the state one step. Each output Q0–Q6 is high for exactly one clock period; green lasts three periods, yellow one, red three. After S6 the register goes back to 00000. · SVG · PNG

3Parts

PartIn this circuitQtyPriceSupplier
CD4017decade counter: the state register and the decoder1$0.40Elexp (elexp.com)
CD4071quad 2-input OR: two gates for green, two for red1$0.25Elexp (elexp.com)
555 clock modulethe clock, set to about 1 Hz1$0.53aliexpress.us
Traffic-light LED module, 5 Vplugged 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 wires18 wires on the board18$11.95 / packjameco.com
Male-female Dupont jumpers3 leads to the clock module3$1.30 / packaliexpress.us

Prices from the LSSK components sheet; this exercise is part of the Comprehensive kit. As on Timofei's board there is no reset button. After power-up the 4017 may start in any of its ten states; in S8 and S9 no lamp is lit, so the light may stay dark for a second or two before it starts with green. Exercise M11d adds a reset button.

Buy the 5 V traffic-light module. The same module is also sold in a 1 V version, and the two look alike; lesson 1.7 of the Habr article warns about this. The 5 V version is driven straight from the chip outputs, as here.

4The chips, pin by pin

Both 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. All outputs here are active high: 1 means +5 V and a lit lamp. The drawings show each chip from above with the notch on the left, as in the datasheet: pin 1 at the bottom left, pins numbered counter-clockwise. Blue arrows are inputs, orange arrows are outputs.

4017: decade counter with 10 decoded outputs

1Q52Q13Q04Q25Q66Q77Q38VSS9Q810Q411Q912CO13INH14CLK15RST16VDD4017decade counter
CD4017B. The triangle at CLOCK marks an edge-triggered input. · SVG · PNG

Polarity. The count advances on the rising edge of CLOCK while CLOCK INHIBIT is low. RESET is active high and asynchronous: while it is 1 the count is 0 and Q0 is high, whatever the clock does. CLOCK INHIBIT is active high: 1 holds the count.

Here RESET has one job: it ends the ring. Q7 (pin 6) is wired straight to it (pin 15), so after S6 the counter passes S7 for about 0.3 µs and starts again at S0. Q8, Q9 and CARRY OUT stay unconnected.

The 4017 also counts on a falling edge of CLOCK INHIBIT while CLOCK is high: CLOCK INHIBIT gates the clock. Here it is tied to GND, so only CLOCK matters.

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

4071: quad 2-input OR

1A2B3J4K5C6D7VSS8E9F10L11M12G13H14VDD4071
CD4071B. Four independent gates; here all four are used. · SVG · PNG

Four independent gates: pin 3 = pins 1 OR 2, pin 4 = pins 5 OR 6, pin 10 = pins 8 OR 9, pin 11 = pins 12 OR 13. Here they make two chains. For green, the gate with output pin 10 takes Q0 and Q1, and the gate with output pin 11 adds Q2. For red, the gate with output pin 4 takes Q4 and Q5, and the gate with output pin 3 adds Q6.

On the breadboard the 4071 sits turned around, notch to the right: then pins 8–13 are on the bottom row, next to Q0–Q2 of the 4017, and pin 1 is at the top right.

PinNameDirectionFunctionIn this circuit
1Ainputinput of the gate with its output on pin 3Q6
2Binputinput of the gate with its output on pin 3Q4|Q5
3JoutputJ = A OR BRED
4KoutputK = C OR DQ4|Q5
5Cinputinput of the gate with its output on pin 4Q4
6Dinputinput of the gate with its output on pin 4Q5
7VSSpowerground, 0 VGND
8Einputinput of the gate with its output on pin 10Q0
9Finputinput of the gate with its output on pin 10Q1
10LoutputL = E OR FQ0|Q1
11MoutputM = G OR HGREEN
12Ginputinput of the gate with its output on pin 11Q2
13Hinputinput of the gate with its output on pin 11Q0|Q1
14VDDpowersupply, +5 V (3 to 18 V allowed)+5V

The traffic-light module

Three LEDs with their resistors on a small board with four pins, printed G, Y, R and GND: a 1 on G, Y or R lights that lamp. As on Timofei's board, the module is plugged straight into the breadboard, its pins in row f of four neighbouring columns, so it needs no jumper leads. Its body stands up over the top half of those columns, whose holes stay unused.

5Schematic 1: flip-flops and gates

STATE REGISTER: 5-BIT JOHNSON COUNTERNEXT STATEDECODER: 7 AND GATESOUTPUT LOGICDQRFF0rstDQRFF1rstDQRFF2rstDQRFF3rstDQRFF4rstq6q6q6in state 6 these three gates put 0 into r2-r4: the next state is S0the inverted last bit goes back to the firstclkr0r0r1r1r2r2r3r3r4r4q0q1q2q3q4q5q6greenyellowreddot: wires connectedbubble: inverted inputrstto R of every flip-flop
The whole circuit as flip-flops and gates, without chips. This is what traffic_light.sv describes. · SVG · PNG

Read it as a state machine:

Why not copy the RESET trick? On the breadboard the ring ends with an asynchronous reset that comes from the counter's own output. In a synchronous design, on an FPGA or in an ASIC, logic that resets its own flip-flops is avoided: the pulse is only as long as the delays make it, the timing tools cannot check it, and any glitch on the decoded output would clear the counter at the wrong moment. So the generic design takes the step from S6 to S0 at the clock edge. In state 6 the register holds 11110, and the shift would give 11100; the three AND gates clear r2–r4. The new r0 and r1 are 0 anyway, so they need no gate.

6Schematic 2: connections between the chips

12345678910111213141516Q5Q1Q0Q2Q6Q7Q3Q8Q4Q9COINHCLKRST4017decade counter12345678910111213144071GYRGNDQ7Q0Q1Q0|Q1Q2GREENQ3Q4Q5Q4|Q5REDclock+5V
The same circuit as chips, pin by pin, placed as on the breadboard: the 4017 with the notch on the left, the 4071 turned around, and the traffic-light module with its four pins. Pin numbers are next to the pins. Wires have the same colours as on the breadboard. The box at the top is the clock module. · SVG · PNG

Every connection of the circuit, net by net. traffic_light_chips.sv in section 10 is written from the same list.

NetFromToWire
CLK555 clock module, OUT4017 14 (CLK)M-F
Q74017 6 (Q7)4017 15 (RST)M-M
Q04017 3 (Q0)4071 8 (E)M-M
Q14017 2 (Q1)4071 9 (F)M-M
Q24017 4 (Q2)4071 12 (G)M-M
Q34017 7 (Q3)traffic light, YM-M
Q44017 10 (Q4)4071 5 (C)M-M
Q54017 1 (Q5)4071 6 (D)M-M
Q64017 5 (Q6)4071 1 (A)M-M
Q0|Q14071 10 (L)4071 13 (H)M-M
GREEN4071 11 (M)traffic light, GM-M
Q4|Q54071 4 (K)4071 2 (B)M-M
RED4071 3 (J)traffic light, RM-M
+5V+5V4017 16 (VDD), 4071 14 (VDD)
GNDGND4017 8 (VSS), 4071 7 (VSS), traffic light, GND, 4017 13 (INH)
not connected4017 9 (Q8), 4017 11 (Q9), 4017 12 (CO)

7Schematic 3: the breadboard

−+−+12345678910111213141516171819202122232425262728293031323334353637383940414243444546abcdefghij5V5VPOWER MODULE · 5V9V USB-DC40174071GYRGNDTRAFFIC LIGHTQ7Q0Q1Q2GREENQ3Q4Q5Q6RED−OUT+555CLOCK 555~1 Hz
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 hangs above the board on male-female jumpers; the traffic light is plugged into the board on the right. The board goes on to column 63 on the right. · SVG · PNG
CLKQ7Q0Q1Q2Q3Q4Q5Q6Q0|Q1GREENQ4|Q5RED+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: the 4017 with the notch to the left, pin 1 in hole 8f; then the 4071 turned around, notch to the right, so that pin 1 is in hole 23e at the top right of the chip. Check the numbers on the chips.
  3. Plug the traffic-light module into holes 27f to 30f, G in 27f and GND in 30f, lamps facing you.
  4. Power: a red wire from pin 16 of the 4017 to the top + rail and a black wire from its pin 8 to the bottom − rail. The turned 4071 has its power pins the other way round: a red wire from pin 14 (bottom, column 23) to the bottom + rail and a black wire from pin 7 (top, column 17) to the top − rail. Then a black wire from column 30, the GND pin of the traffic light, to the bottom − rail. Make sure no wire touches + and − at the same time.
  5. CLOCK INHIBIT, pin 13 of the 4017, to the top − rail.
  6. The twelve signal wires, in the order of the checklist below: Q7 to RESET, Q0–Q2 and Q4–Q6 to the OR gates, the two wires between the gates of each chain, and the wires to G, Y and R of the traffic light. Tick each wire as you insert it.
  7. The clock module, with the power off, above the board.
  8. Turn the power on and set the clock module to about 1 Hz with its potentiometer.

Wiring checklist

·

#NetFromTo
Power (red to +, black to −) · 5 wires
1+5V8a (4017 pin 16, VDD)top + rail, column 8
2GND15j (4017 pin 8, VSS)bottom − rail, column 15
3+5V23j (4071 pin 14, VDD)bottom + rail, column 23
4GND17a (4071 pin 7, VSS)top − rail, column 17
5GND30j (traffic light, GND)bottom − rail, column 30
Fixed inputs: CMOS inputs must not float · 1 wire
6GND11a (4017 pin 13, INH)top − rail, column 11
Signal wires · 12 wires
7Q713g (4017 pin 6, Q7)9d (4017 pin 15, RST)
8Q010h (4017 pin 3, Q0)17h (4071 pin 8, E)
9Q19i (4017 pin 2, Q1)18i (4071 pin 9, F)
10Q0|Q119i (4071 pin 10, L)22i (4071 pin 13, H)
11Q211g (4017 pin 4, Q2)21g (4071 pin 12, G)
12GREEN20h (4071 pin 11, M)27h (traffic light, G)
13Q314g (4017 pin 7, Q3)28g (traffic light, Y)
14Q414d (4017 pin 10, Q4)19d (4071 pin 5, C)
15Q58g (4017 pin 1, Q5)18b (4071 pin 6, D)
16Q4|Q520b (4071 pin 4, K)22b (4071 pin 2, B)
17Q612j (4017 pin 5, Q6)23c (4071 pin 1, A)
18RED21d (4071 pin 3, J)29g (traffic light, R)
Modules on male-female jumpers · 3 wires
19GND555 clock module, −top − rail, column 8
20CLK555 clock module, OUT10a (4017 pin 14, CLK)
21+5V555 clock module, +top + rail, column 10

Test it

If it does not work: a lamp that never lights usually means a wire one hole off; a lamp that is always on, an input of its OR gates tied to +5V by mistake. If one state of green or red is dark, check the wire between the two gates of that chain. If the light stays green and does not move, RESET (pin 15) is held high: only the Q7 wire may go there. If all lamps go dark for three seconds after red, Q7 does not reach RESET, and the counter runs on through S7, S8 and S9. If the light stops, check pin 13 of the 4017 (must be GND). If the chips get warm, turn the power off at once and look for a short between + and −; with the turned 4071, check that its red wire goes from pin 14 to the + rail.

8SystemVerilog: the generic design

traffic_light.sv describes schematic 1: the Johnson register with its three AND gates is the always_ff block, the decoder is seven assign statements with AND, and the output logic is three more. It is synthesizable: an FPGA or an ASIC flow turns it into five flip-flops and a few gates. The output q shows the state, like the outputs Q0–Q6 of the 4017, so that the testbench and the boards can watch it.

traffic_light.svfile
// Exercise M11a: Timofei Nikiforov's traffic light, as he built it:
// 3 clock cycles green, 1 yellow, 3 red.  On the breadboard a 4017 decade
// counter steps through the states, Q7 resets it, and the four 2-input OR
// gates of a 4071 make two 3-input OR gates for the lights.
//
// Generic version that matches schematic 1: five D flip-flops and gates,
// not tied to any chip.  Synthesizable.

module traffic_light
(
    input  logic       clk,
    input  logic       rst,     // 1 = go to state 0 at once, like RESET of the 4017

    output logic [6:0] q,       // q [k] = 1 in state k, like outputs Q0-Q6 of the 4017
    output logic       red,
    output logic       yellow,
    output logic       green
);

    //------------------------------------------------------------------------
    // State register: the 5-bit Johnson counter of the 4017 (a twisted ring
    // counter).  Every clock it shifts left and feeds the inverted top bit
    // into bit 0, one bit changes per clock:
    //
    // state  0     1     2     3     4     5     6
    // r      00000 00001 00011 00111 01111 11111 11110
    //
    // The ring has seven states.  On the breadboard the 4017 goes on to
    // state 7, and its output Q7, wired to RESET, clears the counter at once.
    // Here the step from state 6 to state 0 happens at the clock edge, as it
    // should in a synchronous design: after 11110 the shift would give 11100,
    // so in state 6 three AND gates put 0 into r [2], r [3] and r [4].
    // The new r [1] and r [0] are 0 anyway, because r [0] = 0 and r [4] = 1.

    logic [4:0] r;

    always_ff @ (posedge clk or posedge rst)
        if (rst)
            r <= '0;
        else
            r <= { r [3] & ~ q [6],
                   r [2] & ~ q [6],
                   r [1] & ~ q [6],
                   r [0],
                   ~ r [4] };

    //------------------------------------------------------------------------
    // Decoder: seven 2-input AND gates.  Two neighbouring bits identify each state.

    assign q [0] = ~ r [4] & ~ r [0];
    assign q [1] =   r [0] & ~ r [1];
    assign q [2] =   r [1] & ~ r [2];
    assign q [3] =   r [2] & ~ r [3];
    assign q [4] =   r [3] & ~ r [4];
    assign q [5] =   r [4] &   r [0];
    assign q [6] = ~ r [0] &   r [1];

    //------------------------------------------------------------------------
    // Output logic: each 3-input OR is two 2-input OR gates, as on the 4071;
    // yellow needs no gate

    assign green  = (q [0] | q [1]) | q [2];  // 3 clock cycles
    assign yellow =  q [3];                   // 1 clock cycle
    assign red    = (q [4] | q [5]) | q [6];  // 3 clock cycles

endmodule

The new value of r is a concatenation of five bits, from r4 down to r0: the lower bits move one place up, three of them through an AND with ~ q [6], and the inverted top bit comes in at the bottom. You will often see the same idea written as else if (q [6]) r <= '0;. In the seven states of the ring it does the same thing, but it also clears r0 and needs one more gate. The parentheses in (q [0] | q [1]) | q [2] show the two gates of the 4071; synthesis treats it as one 3-input OR.

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. Both models are synthesizable. The models leave out the power pins: in SystemVerilog a wire simply has the value 0 or 1.

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

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

    wire gated_clock = clock & ~ clock_inhibit;

    logic [4:0] r;

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

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

    assign carry_out = ~ r [4];

endmodule

The 4017 model has one detail you may not expect: gated_clock. The real chip counts on the rising edge of CLOCK while CLOCK INHIBIT is low, and also on the falling edge of CLOCK INHIBIT while CLOCK is high; an AND gate in the clock path does exactly that. On an FPGA, clocks should not pass through gates, so keep clock_inhibit at 0; synthesis then removes the gate. The real chip also recovers from any state at power-up; the model needs a reset.

cd4071.svfile
// CD4071B: quad 2-input OR gate.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (7)
// and VDD (14), are left out.  Synthesizable.

module cd4071
(
    input  logic a,  // Pin 1
    input  logic b,  // Pin 2
    output logic j,  // Pin 3:  j = a | b
    output logic k,  // Pin 4:  k = c | d
    input  logic c,  // Pin 5
    input  logic d,  // Pin 6
                     // Pin 7:  VSS
    input  logic e,  // Pin 8
    input  logic f,  // Pin 9
    output logic l,  // Pin 10: l = e | f
    output logic m,  // Pin 11: m = g | h
    input  logic g,  // Pin 12
    input  logic h   // Pin 13
                     // Pin 14: VDD
);

    assign j = a | b;
    assign k = c | d;
    assign l = e | f;
    assign m = g | h;

endmodule

10SystemVerilog: the chip-level design

traffic_light_chips.sv connects the chip models exactly as schematic 2 and the breadboard connect the chips, with the same ports as traffic_light.sv. CLOCK INHIBIT is tied to gnd as on the breadboard, and unused outputs go to wires named unused_…. Yellow is the same wire as q [3], hence the line assign yellow = q [3];. 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.

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

module traffic_light_chips
(
    input  logic       clk,
    input  logic       rst,
    output logic [6:0] q,
    output logic       red,
    output logic       yellow,
    output logic       green
);

    // Connections between the chips that are not ports

    wire q7;
    wire red45;
    wire green01;

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

    wire gnd = 1'b0;

    // Outputs that go nowhere

    wire unused_u1_q8;
    wire unused_u1_q9;
    wire unused_u1_carry_out;

    // Ports that are the same wire as another port

    assign yellow = q [3];

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

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

    cd4017 i_u1
    (
        .q5            ( q [5]               ),  // Pin 1 -> Q5
        .q1            ( q [1]               ),  // Pin 2 -> Q1
        .q0            ( q [0]               ),  // Pin 3 -> Q0
        .q2            ( q [2]               ),  // Pin 4 -> Q2
        .q6            ( q [6]               ),  // Pin 5 -> Q6
        .q7            ( q7                  ),  // Pin 6 -> Q7
        .q3            ( q [3]               ),  // Pin 7 -> Q3
        .q8            ( unused_u1_q8        ),  // Pin 9, unused output
        .q4            ( q [4]               ),  // Pin 10 -> Q4
        .q9            ( unused_u1_q9        ),  // Pin 11, unused output
        .carry_out     ( unused_u1_carry_out ),  // Pin 12, unused output
        .clock_inhibit ( gnd                 ),  // Pin 13 <- GND
        .clock         ( clk                 ),  // Pin 14 <- 555 clock module
        .reset         ( q7 | rst            )   // Pin 15 <- Q7, pin 6; | rst only here, as a power-on reset
    );

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

    // U2: CD4071 quad 2-input OR, pin 1 in column 17

    cd4071 i_u2
    (
        .a ( q [6]   ),  // Pin 1 <- U1 pin 5 (Q6)
        .b ( red45   ),  // Pin 2 <- U2 pin 4 (K)
        .j ( red     ),  // Pin 3 -> RED
        .k ( red45   ),  // Pin 4 -> Q4|Q5
        .c ( q [4]   ),  // Pin 5 <- U1 pin 10 (Q4)
        .d ( q [5]   ),  // Pin 6 <- U1 pin 1 (Q5)
        .e ( q [0]   ),  // Pin 8 <- U1 pin 3 (Q0)
        .f ( q [1]   ),  // Pin 9 <- U1 pin 2 (Q1)
        .l ( green01 ),  // Pin 10 -> Q0|Q1
        .m ( green   ),  // Pin 11 -> GREEN
        .g ( q [2]   ),  // Pin 12 <- U1 pin 4 (Q2)
        .h ( green01 )   // Pin 13 <- U2 pin 10 (L)
    );

endmodule

One connection differs from the breadboard: RESET of the 4017 gets q7 | rst. The breadboard has no reset button, but a simulation needs a known start, because the chip model, unlike the real 4017, does not find its way into the ring after power-up. So rst joins Q7 here, in SystemVerilog only.

Unlike the generic design, this one keeps the breadboard's trick: q7 goes straight back into the counter. In the simulation the models have no delays, so at the clock edge the counter steps into S7, Q7 rises, RESET rises and clears the counter, and Q7 falls again, all at the same simulation time: the pulse has zero width. The testbench checks the outputs at clock edges and sees S6 followed by S0, the same as from the generic design.

11Testbench and simulation scripts

tb.sv runs both designs side by side from the same clock and reset and compares them with a reference model: a state number from 0 to 6 and the colour that belongs to it. Like the testbenches of Basics-Graphics-Music, it drives and checks signals only at rising clock edges. At each edge it compares the values that the designs held during the clock cycle that ends there, the same values a flip-flop would sample. It also turns reset on in the middle of the ring: both designs must go to state 0 at once, not at the next clock edge, like RESET of the 4017. At the end it counts the clock periods of each colour after a reset and prints PASS or FAIL.

tb.sv207 lines · show the codefile
// Testbench for exercise M11a.
//
// Runs the generic design (traffic_light.sv) and the chip-level design
// (traffic_light_chips.sv) side by side and compares both with a reference
// model: a state number from 0 to 6 and the colour that belongs to it.
// 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.

// 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  [6:0] q,      q_chips;
    wire        red,    red_chips;
    wire        yellow, yellow_chips;
    wire        green,  green_chips;

    traffic_light i_generic
    (
        .clk    ( clk    ),
        .rst    ( rst    ),
        .q      ( q      ),
        .red    ( red    ),
        .yellow ( yellow ),
        .green  ( green  )
    );

    traffic_light_chips i_chips
    (
        .clk    ( clk          ),
        .rst    ( rst          ),
        .q      ( q_chips      ),
        .red    ( red_chips    ),
        .yellow ( yellow_chips ),
        .green  ( green_chips  )
    );

    //------------------------------------------------------------------------
    // Clock with a period of 10 ns.
    // On the breadboard one period is about a second.

    initial
    begin
        clk = '0;

        forever
            # 5 clk = ~ clk;
    end

    //------------------------------------------------------------------------
    // Reference model: the number of the state, from 0 to 6.
    // Like RESET of the 4017, rst sets state 0 at once, without the clock.

    logic [2:0] state;

    always @ (posedge clk or posedge rst)
        if (rst)
            state <= 3'd0;
        else if (state == 3'd6)
            state <= 3'd0;
        else
            state <= state + 3'd1;

    wire [6:0] q_expected      = 7'b1 << state;
    wire       green_expected  = state <= 3'd2;
    wire       yellow_expected = state == 3'd3;
    wire       red_expected    = state >= 3'd4;

    wire ok_generic =    q            === q_expected
                      && red          === red_expected
                      && yellow       === yellow_expected
                      && green        === green_expected;

    wire ok_chips   =    q_chips      === q_expected
                      && red_chips    === red_expected
                      && yellow_chips === yellow_expected
                      && green_chips  === green_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.

    function automatic string light_name (input logic r, input logic y, input logic g);
        case ({ r, y, g })
        3'b100:  return "red   ";
        3'b010:  return "yellow";
        3'b001:  return "green ";
        3'b000:  return "dark  ";
        default: return "mixed ";
        endcase
    endfunction

    // 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;

    // Clock cycles of each colour during the first full period after reset

    int n_period = 0;
    int n_red    = 0;
    int n_yellow = 0;
    int n_green  = 0;

    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);

            $display ("%5d  %b    %b  %s  %s  %s",
                cycle + 1, rst, q, light_name (red, yellow, green),
                ok_generic ? "ok     " : "WRONG  ", ok_chips ? "ok" : "WRONG");
        end

        if (was_reset & ~ rst & n_period < 7)
        begin
            n_period <= n_period + 1;
            n_red    <= n_red    + (red    ? 1 : 0);
            n_yellow <= n_yellow + (yellow ? 1 : 0);
            n_green  <= n_green  + (green  ? 1 : 0);
        end
    end

    //------------------------------------------------------------------------
    // Driving reset

    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  Q6..Q0   light   generic  chips");

        // Before reset the state is unknown, as after power-up

        rst <= 'x;
        repeat (3) @ (posedge clk);
        rst <= '1;
        repeat (3) @ (posedge clk);
        rst <= '0;

        repeat (24) @ (posedge clk);

        // Reset in the middle of the ring.  Both designs must go to state 0
        // at once, not at the next clock edge, like RESET of the 4017.
        // The breadboard has no reset button; in the chip-level design rst is
        // ORed with Q7 in SystemVerilog only, as a power-on reset.

        rst <= '1;
        repeat (2) @ (posedge clk);
        rst <= '0;

        repeat (12) @ (posedge clk);

        // Stop checking one clock edge before $finish, so that every
        // simulator reports the same number of checks

        done <= '1;
        @ (posedge clk);

        $finish;
    end

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

    final
    begin
        $display ("One period after reset: green %0d, yellow %0d, red %0d clock cycles",
            n_green, n_yellow, n_red);

        if (n_errors == 0 && n_green == 3 && n_yellow == 1 && n_red == 3)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks", n_errors, n_checks);
    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 M11a: 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 traffic_light.sv traffic_light_chips.sv cd4017.sv cd4071.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 M11a: 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 traffic_light.sv traffic_light_chips.sv cd4017.sv cd4071.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 M11a: 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 traffic_light.sv traffic_light_chips.sv cd4017.sv cd4071.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  Q6..Q0   light   generic  chips
    1  1    0000001  green   ok          ok
    2  1    0000001  green   ok          ok
    3  1    0000001  green   ok          ok
    4  0    0000001  green   ok          ok
    5  0    0000010  green   ok          ok
    6  0    0000100  green   ok          ok
    7  0    0001000  yellow  ok          ok
    8  0    0010000  red     ok          ok
    9  0    0100000  red     ok          ok
   10  0    1000000  red     ok          ok
   11  0    0000001  green   ok          ok
   12  0    0000010  green   ok          ok
   13  0    0000100  green   ok          ok
   14  0    0001000  yellow  ok          ok
   15  0    0010000  red     ok          ok
   16  0    0100000  red     ok          ok
   17  0    1000000  red     ok          ok
   18  0    0000001  green   ok          ok
   19  0    0000010  green   ok          ok
   20  0    0000100  green   ok          ok
   21  0    0001000  yellow  ok          ok
   22  0    0010000  red     ok          ok
   23  0    0100000  red     ok          ok
   24  0    1000000  red     ok          ok
   25  0    0000001  green   ok          ok
   26  0    0000010  green   ok          ok
   27  0    0000100  green   ok          ok
   28  1    0000001  green   ok          ok
   29  1    0000001  green   ok          ok
   30  0    0000001  green   ok          ok
   31  0    0000010  green   ok          ok
   32  0    0000100  green   ok          ok
   33  0    0001000  yellow  ok          ok
   34  0    0010000  red     ok          ok
   35  0    0100000  red     ok          ok
   36  0    1000000  red     ok          ok
   37  0    0000001  green   ok          ok
   38  0    0000010  green   ok          ok
   39  0    0000100  green   ok          ok
   40  0    0001000  yellow  ok          ok
   41  0    0010000  red     ok          ok
tb.sv:191: $finish called at 445000 (1ps)
One period after reset: green 3, yellow 1, red 3 clock cycles
PASS: 82 checks, no errors

All three simulators handle the zero-time loop through RESET.

To see that the testbench catches mistakes, break something and run it again: in traffic_light_chips.sv write q [6] | rst instead of q7 | rst for pin 15 of the 4017, so that the ring ends one state early, or connect pin 12 of the 4071 to q [3] instead of q [2]; or change one decoder line in traffic_light.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 traffic_light.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.

The rightmost digit of the display is a small traffic light: segment a (top) is red, g (middle) yellow, d (bottom) green. The LEDs show the state as a running light. To run the chip-level design instead, add traffic_light_chips.sv and the two chip models and change the module name in the instance. For real use prefer the generic design: section 5 explains why a counter should not reset itself.

bgm_lab/lab_top.sv117 lines · show the codefile
// Exercise M11a on an FPGA board with the Basics-Graphics-Music (BGM) labs:
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy a lab directory, for example labs/1_basics/1_06_binary_counter,
// replace its lab_top.sv with this file and add traffic_light.sv.
// For the chip-level design add traffic_light_chips.sv, cd4017.sv and
// cd4071.sv instead, and change the module name below.
//
// The traffic light runs from slow_clk, the 1 Hz clock that every BGM board
// wrapper makes, so it changes state once a second, like the breadboard with
// the 555 module.  Reset is the reset button of the board.
// The 7-segment display shows the light: segment a red, g yellow, d green.
// The LEDs show the state as a running light.

`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;

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

    // lab_top already has ports named red and green (the screen colours),
    // so the lights get other names here

    logic [6:0] q;
    logic       light_red, light_yellow, light_green;

    traffic_light i_traffic_light
    (
        .clk    ( slow_clk     ),
        .rst    ( rst          ),
        .q      ( q            ),
        .red    ( light_red    ),
        .yellow ( light_yellow ),
        .green  ( light_green  )
    );

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

    //   --a--
    //  |     |
    //  f     b
    //  |     |
    //   --g--
    //  |     |
    //  e     c
    //  |     |
    //   --d--  h

    assign abcdefgh = { light_red, 2'b0, light_green, 2'b0, light_yellow, 1'b0 };
    assign digit    = w_digit' (1);

    assign led      = w_led' (q);

endmodule

13On an FPGA board: hackathon_top in BGM

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

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

The screen shows a traffic light: three round lamps in a dark box, bright when on and dim when off. The rightmost digit shows the same three segments as in lab_top, and the eight LEDs show states 0–6. The screen colour ports are called red and green, so the lights are called light_red, light_yellow and light_green here.

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

// Exercise M11a 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 traffic_light.sv.
//
// The traffic light runs from slow_clock, one beat per second, like the
// breadboard with the 555 module.  The screen shows a traffic light,
// the 7-segment display shows it too (segment a red, g yellow, d green),
// and the eight LEDs show states 0-6 as a running light.

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
);

    //------------------------------------------------------------------------
    // The screen colours are called red and green already,
    // so the lights get other names

    logic [6:0] q;
    logic       light_red, light_yellow, light_green;

    traffic_light i_traffic_light
    (
        .clk    ( slow_clock   ),
        .rst    ( reset        ),
        .q      ( q            ),
        .red    ( light_red    ),
        .yellow ( light_yellow ),
        .green  ( light_green  )
    );

    assign led      = { 1'b0, q };

    assign abcdefgh = { light_red, 2'b0, light_green, 2'b0, light_yellow, 1'b0 };
    assign digit    = 8'b0000_0001;

    //------------------------------------------------------------------------
    // A traffic light on the 480 x 272 screen: three round lamps in a dark box.
    // dx is the distance from the middle of the screen, dy1-dy3 the distances
    // from the centres of the lamps, so a lamp is where dx * dx + dy * dy < 34 * 34.

    wire [8:0] dx  = x > 240 ? x - 240 : 240 - x;
    wire [8:0] dy1 = y > 56  ? y - 56  : 56  - y;
    wire [8:0] dy2 = y > 136 ? y - 136 : 136 - y;
    wire [8:0] dy3 = y > 216 ? y - 216 : 216 - y;

    wire lamp1 = dx * dx + dy1 * dy1 < 34 * 34;
    wire lamp2 = dx * dx + dy2 * dy2 < 34 * 34;
    wire lamp3 = dx * dx + dy3 * dy3 < 34 * 34;

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

        if (x >= 196 & x < 284 & y >= 12 & y < 260)
        begin
            red   = 3;
            green = 6;
            blue  = 3;
        end

        if (lamp1)
        begin
            red   = light_red ? 31 : 7;
            green = 0;
            blue  = 0;
        end

        if (lamp2)
        begin
            red   = light_yellow ? 31 : 7;
            green = light_yellow ? 50 : 11;
            blue  = 0;
        end

        if (lamp3)
        begin
            red   = 0;
            green = light_green ? 63 : 14;
            blue  = light_green ? 8  : 2;
        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 the traffic light, just as the 555 module clocks the chips on the breadboard.

The display shows the light on segments a, g and d. Use the generic design here: on a chip the synchronous step from S6 to S0 is the right way, not the loop through RESET.

tiny_tapeout/project.v54 lines · show the codefile
/*
 * Exercise M11a on Tiny Tapeout: Timofei's traffic light on the 7-segment
 * display of the demo board.
 *
 * Add traffic_light.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 light should change about once a second.  The demo board makes
    // clk itself and can set it anywhere from 1 Hz to 66.5 MHz, so set the
    // project clock to 1 Hz (clock_hz: 1 in info.yaml) and clk drives the
    // traffic light directly.  Do not make a slow clock from a counter in an
    // ASIC: keep one clock and use a clock enable when you need a slow tick.

    wire [6:0] q;
    wire       red, yellow, green;

    traffic_light i_traffic_light (
        .clk    ( clk      ),
        .rst    ( ~ rst_n  ),
        .q      ( q        ),
        .red    ( red      ),
        .yellow ( yellow   ),
        .green  ( green    )
    );

    // 7-segment display: uo_out [0] is segment a, ..., uo_out [6] is g,
    // uo_out [7] is the dot.  Segment a (top) is red, g (middle) yellow,
    // d (bottom) green.

    assign uo_out  = { 1'b0, yellow, 2'b0, green, 2'b0, red };

    assign uio_out = 8'b0;
    assign uio_oe  = 8'b0;

    // List all unused inputs to prevent warnings

    wire _unused = & { ena, ui_in, uio_in, q, 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>_traffic_light
  source_files:
    - "project.v"
    - "traffic_light.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

A shortcut that the chip hides

With the Johnson register visible, the decoder and the OR gates shrink to almost nothing: green is states 0–2, which is exactly ~ r [2]; yellow is r [2] & ~ r [3]; red is r [3]. Check them in the state table of section 2: in a ring of seven states, two bits are enough. The 4017 cannot do this because its Johnson bits stay inside the chip, but in an FPGA it is a free optimization, and synthesis tools find such things on their own.

The 555-and-4017 traffic light has been built for decades, mostly with diodes. A few versions to compare:

Files of this exercise

Sources

The timing, the reset at Q7 and the two 3-input OR gates come from Timofei Nikiforov's own description of his circuit; the chips, the plugged-in traffic light and the missing reset button come from a photo of his board. A ten-state version is described in the Habr article about the electronics course (lesson 1.7) and in “Teaching children electronics is due for a major redesign”, picture 15. The 4017 and 4071 and the RESET delay are described in the Texas Instruments datasheets for the CD4017B and CD4071B.