Breadboard exercises/ P6EnglishРусский

Exercise P6 · project · finite state machine

Your own FSM: a code lock

The teacher gives each student a short sequence of button presses, and the student designs a circuit that recognizes it: a state diagram, a state table, minimized equations, gates on a breadboard. This page goes through one example from start to finish: a lock that opens after 1, 0, 1.

4 chips40174, 4069, 4081, 4071
37 + 14 wireson the board + jumper leads to the modules
4 statesin 2 flip-flops, plus 1 for the button
~1 Hzone digit of the code per clock

1What it is and why it matters

What it does. The code is entered with one button, one digit per blink of the clock module: held is 1, released is 0. After 1, 0, 1 the lock opens, LED 4, and stays open until RESET. LED 1 shows the button as the circuit saw it at the last clock edge, LEDs 2 and 3 the state.

How it works. The first flip-flop of a 40174 samples the button, so the rest of the circuit works with a value A that stays put for a whole clock cycle. Two more flip-flops hold the state: the number of code digits matched so far, from 0 to 3, where 3 means open. Gates compute the next state from the state and A.

Where it is used. Code locks, remote controls, serial receivers that wait for a start pattern, network chips that look for the header of a packet: every circuit that reacts to a sequence is a state machine designed this way.

Why learn it.

2The key elements: from a sequence to equations

1. States. The state is how much of the code the last digits match. After 1, 1 the last digit can still be the start of the code, so the state is 1, not 0; after 1, 0, 0 nothing matches any more and the state is 0. In a lock, state 3 is open and keeps itself.

State = S1 S0SeenNext if A = 0Next if A = 1OPEN
0 = 00nothing yet0 = 001 = 010
1 = 0112 = 101 = 010
2 = 101, 00 = 003 = 110
3 = 111, 0, 1: open3 = 113 = 111

2. Encoding. Four states fit into two bits, S1 S0, with the state number in binary.

3. Equations. For each next-state bit, write a table with S1, S0 and A as inputs and minimize it with a Karnaugh map. The FSM kit does this for every code with a program; for 1, 0, 1 the result is:

4. Gates. Three AND gates (S1·S0 is used twice), two OR gates and one inverter for NOT A, plus one more inverter: the CLEAR input of the 40174 is active low, and the RESET button gives 1 when pressed.

Waveforms

CLKRSTBTNAS1 S0000100011011000100OPEN
From the simulation of tb.sv in Icarus Verilog. A follows the button one clock edge later, the state one edge after A. After the wrong code 0, 1, 1, 0 and a reset, the right code 1, 0, 1 opens the lock, and it stays open. · SVG · PNG

3Parts

PartIn this circuitQtyPriceSupplier
CD4069hex inverter: NOT A and NOT RESET (two of six used)1$0.30Elexp (elexp.com)
CD40174hex D flip-flop: the button and the two state bits (three of six used)1$0.58Elexp (elexp.com)
CD4081quad AND: S1·S0, S0·~A, S1·A (three of four used)1$0.55Elexp (elexp.com)
CD4071quad OR: the next S0 and S1 (two of four used)1$0.25Elexp (elexp.com)
Button modulesRESET and the code button; 2 from the pack of five2$0.66 / packaliexpress.us
555 clock modulethe clock, set to about 1 Hz1$0.53aliexpress.us
8-LED moduleA, S1, S0 and OPEN on LEDs 1-41$0.38aliexpress.us
Breadboard, 830 points1$3.00amazon.com
Breadboard power module5 V on the rails1$1.00aliexpress.us
USB-to-DC cable, 9 Vpowers the module from a USB charger1$1.17aliexpress.us
Pre-cut jumper wires37 wires on the board (or male-male Dupont jumpers)37$11.95 / packjameco.com
Male-female Dupont jumpers14 leads to the clock module, the buttons and the LED module14$1.30 / packaliexpress.us

Prices from the LSSK components sheet. The FSM kit holds enough gates for any code of up to 5 digits: 4073 and 4082 for 3- and 4-input ANDs, 4075 and 4072 for 3- and 4-input ORs, and 4011 and 4001.

4The chips, pin by pin

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

40174: hex D flip-flop

1CLR2Q13D14D25Q26D37Q38VSS9CLK10Q411D412Q513D514D615Q616VDD401746 × D flip-flop
CD40174B. · SVG · PNG

Six D flip-flops with one clock (pin 9) and one ~CLEAR (pin 1), active low. Here flip-flop 1 samples the button (D1 pin 3, Q1 pin 2 is A), flip-flop 2 holds S0 (D2 pin 4, Q2 pin 5) and flip-flop 3 holds S1 (D3 pin 6, Q3 pin 7). The inputs of the other three are at GND. A longer code needs more of them.

PinNameDirectionFunctionIn this circuit
1CLEARinput0 clears all six flip-flops at once, without the clock. Active lowRST
2Q1outputoutput of flip-flop 1A
3D1inputdata input of flip-flop 1BTN
4D2inputdata input of flip-flop 2S0'
5Q2outputoutput of flip-flop 2S0
6D3inputdata input of flip-flop 3S1'
7Q3outputoutput of flip-flop 3S1
8VSSpowerground, 0 VGND
9CLOCKinputall six flip-flops store D at the rising edgeCLK
10Q4outputoutput of flip-flop 4not connected
11D4inputdata input of flip-flop 4tied to +5V
12Q5outputoutput of flip-flop 5not connected
13D5inputdata input of flip-flop 5tied to +5V
14D6inputdata input of flip-flop 6tied to +5V
15Q6outputoutput of flip-flop 6not connected
16VDDpowersupply, +5 V (3 to 18 V allowed)+5V

4069: hex inverter

1A2G3B4H5C6I7VSS8J9D10K11E12L13F14VDD4069
CD4069UB. · SVG · PNG

Two inverters: NOT RESET for ~CLEAR, and NOT A. The inputs of the other four are tied to the rails.

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

4081: quad 2-input AND

1A2B3J4K5C6D7VSS8E9F10L11M12G13H14VDD4081
CD4081B. · SVG · PNG

Three gates: S1·S0, which is OPEN and a term of S0', then S0·NOT A and S1·A for S1'.

PinNameDirectionFunctionIn this circuit
1Ainputinput of the gate with its output on pin 3tied to +5V
2Binputinput of the gate with its output on pin 3tied to +5V
3JoutputJ = A AND Bnot connected
4KoutputK = C AND DS0·A
5Cinputinput of the gate with its output on pin 4S0
6Dinputinput of the gate with its output on pin 4A
7VSSpowerground, 0 VGND
8Einputinput of the gate with its output on pin 10S1
9Finputinput of the gate with its output on pin 10S0
10LoutputL = E AND FOPEN
11MoutputM = G AND HS1·A
12Ginputinput of the gate with its output on pin 11S1
13Hinputinput of the gate with its output on pin 11A
14VDDpowersupply, +5 V (3 to 18 V allowed)+5V

4071: quad 2-input OR

1A2B3J4K5C6D7VSS8E9F10L11M12G13H14VDD4071
CD4071B. · SVG · PNG

Two gates: S0' = A OR S1·S0 and S1' = S0·NOT A OR S1·A. The inputs of the other two are tied to GND.

PinNameDirectionFunctionIn this circuit
1Ainputinput of the gate with its output on pin 3OPEN
2Binputinput of the gate with its output on pin 3A
3JoutputJ = A OR BS0'
4KoutputK = C OR Dnot connected
5Cinputinput of the gate with its output on pin 4tied to GND
6Dinputinput of the gate with its output on pin 4tied to GND
7VSSpowerground, 0 VGND
8Einputinput of the gate with its output on pin 10tied to +5V
9Finputinput of the gate with its output on pin 10tied to +5V
10LoutputL = E OR Fnot connected
11MoutputM = G OR HS1'
12Ginputinput of the gate with its output on pin 11S1·A
13Hinputinput of the gate with its output on pin 11S0·A
14VDDpowersupply, +5 V (3 to 18 V allowed)+5V

5Schematic 1: the code lock

CLKRESETCODE406940174D1D2D3CLKCLRQ1Q2Q33 of 6 flip-flops406940814081408140714071ALED 1S1LED 2S0LED 3OPENLED 4
The circuit as flip-flops and gates. This is what code_lock.sv describes. The lines along the top and the bottom bring the next state back to the flip-flops. · SVG · PNG

6Schematic 2: connections between the chips

1234567891011121314406912345678910111213141516CLRQ1D1D2Q2D3Q3CLKQ4D4Q5D5D6Q6401746 × D flip-flop1234567891011121314408112345678910111213144071CLKRSTBTNAAS0S1OPENS0·AS1·AS0'S1'resetcodeclockLED module: LEDs 1-4+5V
The same circuit as chips, pin by pin. · SVG · PNG
NetFromToWire
CLK555 clock module, OUT40174 9 (CLK)M-F
RSTreset button, OUT4069 1 (A)M-F, M-M
RST4069 2 (G)40174 1 (CLR)M-M
BTNcode button, OUT40174 3 (D1)M-F, M-M
A40174 2 (Q1)4069 3 (B), 4081 13 (H), 4071 2 (B), LED module, LED 1M-F, M-M
A4069 4 (H)4081 6 (D)M-M
S140174 7 (Q3)4081 8 (E), 4081 12 (G), LED module, LED 2M-F, M-M
S040174 5 (Q2)4081 9 (F), 4081 5 (C), LED module, LED 3M-F, M-M
OPEN4081 10 (L)4071 1 (A), LED module, LED 4M-F, M-M
S0·A4081 4 (K)4071 13 (H)M-M
S1·A4081 11 (M)4071 12 (G)M-M
S0'4071 3 (J)40174 4 (D2)M-M
S1'4071 11 (M)40174 6 (D3)M-M
+5V+5V4069 14 (VDD), 40174 16 (VDD), 4081 14 (VDD), 4071 14 (VDD), 4069 13 (F), 4069 11 (E), 4069 9 (D), 40174 14 (D6), 40174 13 (D5), 40174 11 (D4), 4081 2 (B), 4081 1 (A), 4071 9 (F), 4071 8 (E)
GNDGND4069 7 (VSS), 40174 8 (VSS), 4081 7 (VSS), 4071 7 (VSS), 4069 5 (C), 4071 5 (C), 4071 6 (D)
not connected4069 6 (I), 4069 8 (J), 4069 10 (K), 4069 12 (L), 40174 10 (Q4), 40174 12 (Q5), 40174 15 (Q6), 4081 3 (J), 4071 4 (K), 4071 10 (L)

7Schematic 3: the breadboard

−+−+123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263abcdefghij5V5VPOWER MODULE · 5V9V USB-DC40694017440814071RSTAAAAS0S1S1OPENS0·AS1·AS0'S1'+OUT−RESETbutton+OUT−CODEbutton−OUT+555CLOCK 555~1 HzG1A2S13S04OPEN56788-LED MODULELEDs 1-4 used
Every wire in its hole. Column numbers are printed along the top; rows a–e are above the gap, f–j below it. The clock module and the two buttons hang above the board, the LED module below it. · SVG · PNG
CLKRSTRSTBTNAAS1S0OPENS0·AS1·AS0'S1'+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 4069, notch to the left, pin 1 in hole 10f; the 40174, notch to the left, pin 1 in hole 21f; the 4081 turned around, notch to the right, pin 1 in hole 37e; the 4071, notch to the left, pin 1 in hole 39f. Read the numbers on the chips: many look alike. A chip turned around has pin 1 at the top right: it puts the pins this circuit needs next to its neighbours.
  3. Power: for each chip a red wire from its VDD pin (14, or 16 on a 16-pin chip) to the + rail and a black wire from its VSS pin (7 or 8) to the − rail, each to the rail on its own side of the gap. On a chip turned around VDD is on the bottom row and VSS on the top row. Make sure no wire touches + and − at the same time.
  4. The fixed inputs: D4–D6 of the 40174 and the inputs of the unused gates.
  5. The signal wires, following the checklist: the clock, RESET through the inverter to ~CLEAR, the button to D1, A and the state bits to the gates, the OR outputs back to D2 and D3. Tick each wire as you insert it.
  6. With the power off, the modules: the clock module, RESET and the code button above the board, the LED module below it.
  7. Turn the power on and set the clock module to about one blink per second.

Wiring checklist

·

#NetFromTo
Power (red to +, black to −) · 8 wires
1+5V10a (4069 pin 14, VDD)top + rail, column 10
2GND16j (4069 pin 7, VSS)bottom − rail, column 16
3+5V21a (40174 pin 16, VDD)top + rail, column 21
4GND28j (40174 pin 8, VSS)bottom − rail, column 28
5+5V37j (4081 pin 14, VDD)bottom + rail, column 37
6GND31a (4081 pin 7, VSS)top − rail, column 31
7+5V39a (4071 pin 14, VDD)top + rail, column 39
8GND45j (4071 pin 7, VSS)bottom − rail, column 45
Fixed inputs: CMOS inputs must not float · 13 wires
9+5V11a (4069 pin 13, F)top + rail, column 11
10+5V13a (4069 pin 11, E)top + rail, column 13
11GND14j (4069 pin 5, C)bottom − rail, column 14
12+5V15a (4069 pin 9, D)top + rail, column 15
13+5V23a (40174 pin 14, D6)top + rail, column 23
14+5V24a (40174 pin 13, D5)top + rail, column 24
15+5V26a (40174 pin 11, D4)top + rail, column 26
16+5V36a (4081 pin 2, B)top + rail, column 36
17+5V37a (4081 pin 1, A)top + rail, column 37
18GND43j (4071 pin 5, C)bottom − rail, column 43
19+5V44a (4071 pin 9, F)top + rail, column 44
20GND44j (4071 pin 6, D)bottom − rail, column 44
21+5V45a (4071 pin 8, E)top + rail, column 45
Signal wires · 16 wires
22RST10g (4069 pin 1, A)9e
23RST11g (4069 pin 2, G)21g (40174 pin 1, CLR)
24BTN23g (40174 pin 3, D1)20e
25A22h (40174 pin 2, Q1)12h (4069 pin 3, B)
26A22i (40174 pin 2, Q1)36i (4081 pin 13, H)
27A36g (4081 pin 13, H)40g (4071 pin 2, B)
28A13g (4069 pin 4, H)32b (4081 pin 6, D)
29S025h (40174 pin 5, Q2)32h (4081 pin 9, F)
30S032g (4081 pin 9, F)33d (4081 pin 5, C)
31S127g (40174 pin 7, Q3)31g (4081 pin 8, E)
32S131h (4081 pin 8, E)35g (4081 pin 12, G)
33OPEN33h (4081 pin 10, L)39h (4071 pin 1, A)
34S0·A34b (4081 pin 4, K)40b (4071 pin 13, H)
35S1·A34g (4081 pin 11, M)41d (4071 pin 12, G)
36S0'41j (4071 pin 3, J)24j (40174 pin 4, D2)
37S1'42c (4071 pin 11, M)26g (40174 pin 6, D3)
Modules on male-female jumpers · 14 wires
38+5Vreset button, +top + rail, column 8
39RSTreset button, OUT9a
40GNDreset button, −top − rail, column 10
41+5Vcode button, +top + rail, column 16
42BTNcode button, OUT20a
43GNDcode button, −top − rail, column 18
44GND555 clock module, −top − rail, column 25
45CLK555 clock module, OUT28a (40174 pin 9, CLK)
46+5V555 clock module, +top + rail, column 27
47GNDLED module, Gbottom − rail, column 24
48ALED module, LED 122j (40174 pin 2, Q1)
49S1LED module, LED 227j (40174 pin 7, Q3)
50S0LED module, LED 325j (40174 pin 5, Q2)
51OPENLED module, LED 433j (4081 pin 10, L)

Test it

If it does not work: if nothing ever changes, check NOT RESET to pin 1: while ~CLEAR is 0, the 40174 stays cleared. If the state jumps to 3 too early or never gets there, compare each gate input with the equations above. If LED 1 does not follow the button, check the wire to D1 and the clock to pin 9.

8SystemVerilog: the generic design

code_lock.sv writes the synchronizing flip-flop and the two equations into one always_ff block. In SystemVerilog a student would usually write the states with an enum and the transitions with a case, and let synthesis find the equations; doing it by hand once shows what synthesis does. It is synthesizable.

code_lock.svfile
// Exercise P6: your own FSM.  The worked example is a code lock that opens
// after the button gives 1, 0, 1 at three clock edges in a row, and stays
// open until reset.
//
// Generic version that matches schematic 1, not tied to any chip.  The
// first flip-flop samples the button: a is the button at the last clock
// edge, so the state machine works with a value that stays put for a whole
// clock cycle.  The state is the number of code digits matched so far:
// 0 nothing, 1 "1", 2 "1, 0", 3 open.  The next-state equations are the
// minimized ones of the FSM kit:
//
//     state [0]' = a | state [1] & state [0]
//     state [1]' = state [0] & ~ a | state [1] & a
//     open       = state [1] & state [0]
//
// rst clears everything at once, without the clock.  Synthesizable.

module code_lock
(
    input  logic       clk,
    input  logic       rst,
    input  logic       btn,
    output logic       a,      // the button, sampled
    output logic [1:0] state,
    output logic       open
);

    always_ff @ (posedge clk or posedge rst)
        if (rst)
        begin
            a     <= 1'b0;
            state <= 2'd0;
        end
        else
        begin
            a         <= btn;
            state [0] <= a | state [1] & state [0];
            state [1] <= state [0] & ~ a | state [1] & a;
        end

    assign open = state [1] & state [0];

endmodule

9SystemVerilog models of the chips

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

cd40174.svfile
// CD40174B: hex D flip-flop with a common clock and a common clear.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (8)
// and VDD (16), are left out.  Synthesizable.
//
// All six flip-flops store their D input at the rising edge of CLOCK.
// CLEAR is active low and asynchronous: 0 sets all Q to 0 at once.

module cd40174
(
    input  logic clear_n,  // Pin 1:  0 = all Q to 0 at once
    output logic q1,       // Pin 2
    input  logic d1,       // Pin 3
    input  logic d2,       // Pin 4
    output logic q2,       // Pin 5
    input  logic d3,       // Pin 6
    output logic q3,       // Pin 7
                           // Pin 8:  VSS
    input  logic clock,    // Pin 9
    output logic q4,       // Pin 10
    input  logic d4,       // Pin 11
    output logic q5,       // Pin 12
    input  logic d5,       // Pin 13
    input  logic d6,       // Pin 14
    output logic q6        // Pin 15
                           // Pin 16: VDD
);

    logic [6:1] q;

    always_ff @ (posedge clock or negedge clear_n)
        if (~ clear_n)
            q <= '0;
        else
            q <= { d6, d5, d4, d3, d2, d1 };

    assign { q6, q5, q4, q3, q2, q1 } = q;

endmodule
cd4069.svfile
// CD4069UB: hex inverter (six NOT gates).
//
// Ports in pin order, named as in the datasheet: inputs A-F, outputs G-L.
// The power pins, VSS (7) and VDD (14), are left out.  Synthesizable.

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

    assign g = ~ a;
    assign h = ~ b;
    assign i = ~ c;
    assign j = ~ d;
    assign k = ~ e;
    assign l = ~ f;

endmodule
cd4081.svfile
// CD4081B: quad 2-input AND gate.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (7)
// and VDD (14), are left out.  Synthesizable.
//
// The 4081, 4071 and 4070 have the same pinout: only the function of the
// gates differs.

module cd4081
(
    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
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

code_lock_chips.sv connects the chip models exactly as schematic 2 and the breadboard connect the chips, with the same ports as code_lock.sv. Unused inputs are tied to vdd or gnd as on the breadboard, and unused outputs go to wires named unused_…. The file is generated from the breadboard wire list after a pin-level check of that list, so the code, the drawings and the checklist cannot disagree.

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

module code_lock_chips
(
    input  logic       clk,
    input  logic       rst,
    input  logic       btn,
    output logic       a,
    output logic [1:0] state,
    output logic       open
);

    // Connections between the chips that are not ports

    wire nrst;
    wire na;
    wire d0;
    wire d1;
    wire t2;
    wire t3;

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

    wire gnd = 1'b0;
    wire vdd = 1'b1;

    // Outputs that go nowhere

    wire unused_u2_i;
    wire unused_u2_j;
    wire unused_u2_k;
    wire unused_u2_l;
    wire unused_u1_q4;
    wire unused_u1_q5;
    wire unused_u1_q6;
    wire unused_u3_j;
    wire unused_u4_k;
    wire unused_u4_l;

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

    // U2: CD4069 hex inverter (six NOT gates), pin 1 in column 10

    cd4069 i_u2
    (
        .a ( rst         ),  // Pin 1 <- reset button
        .g ( nrst        ),  // Pin 2 -> ~RST
        .b ( a           ),  // Pin 3 <- U1 pin 2 (Q1)
        .h ( na          ),  // Pin 4 -> ~A
        .c ( gnd         ),  // Pin 5 <- GND, unused input
        .i ( unused_u2_i ),  // Pin 6, unused output
        .j ( unused_u2_j ),  // Pin 8, unused output
        .d ( vdd         ),  // Pin 9 <- +5V, unused input
        .k ( unused_u2_k ),  // Pin 10, unused output
        .e ( vdd         ),  // Pin 11 <- +5V, unused input
        .l ( unused_u2_l ),  // Pin 12, unused output
        .f ( vdd         )   // Pin 13 <- +5V, unused input
    );

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

    // U1: CD40174 hex D flip-flop with common clock and clear, pin 1 in column 21

    cd40174 i_u1
    (
        .clear_n ( nrst         ),  // Pin 1 <- U2 pin 2 (G)
        .q1      ( a            ),  // Pin 2 -> A
        .d1      ( btn          ),  // Pin 3 <- code button
        .d2      ( d0           ),  // Pin 4 <- U4 pin 3 (J)
        .q2      ( state [0]    ),  // Pin 5 -> S0
        .d3      ( d1           ),  // Pin 6 <- U4 pin 11 (M)
        .q3      ( state [1]    ),  // Pin 7 -> S1
        .clock   ( clk          ),  // Pin 9 <- 555 clock module
        .q4      ( unused_u1_q4 ),  // Pin 10, unused output
        .d4      ( vdd          ),  // Pin 11 <- +5V, unused input
        .q5      ( unused_u1_q5 ),  // Pin 12, unused output
        .d5      ( vdd          ),  // Pin 13 <- +5V, unused input
        .d6      ( vdd          ),  // Pin 14 <- +5V, unused input
        .q6      ( unused_u1_q6 )   // Pin 15, unused output
    );

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

    // U3: CD4081 quad 2-input AND, pin 1 in column 31

    cd4081 i_u3
    (
        .a ( vdd         ),  // Pin 1 <- +5V, unused input
        .b ( vdd         ),  // Pin 2 <- +5V, unused input
        .j ( unused_u3_j ),  // Pin 3, unused output
        .k ( t2          ),  // Pin 4 -> S0·~A
        .c ( state [0]   ),  // Pin 5 <- U1 pin 5 (Q2)
        .d ( na          ),  // Pin 6 <- U2 pin 4 (H)
        .e ( state [1]   ),  // Pin 8 <- U1 pin 7 (Q3)
        .f ( state [0]   ),  // Pin 9 <- U1 pin 5 (Q2)
        .l ( open        ),  // Pin 10 -> OPEN
        .m ( t3          ),  // Pin 11 -> S1·A
        .g ( state [1]   ),  // Pin 12 <- U1 pin 7 (Q3)
        .h ( a           )   // Pin 13 <- U1 pin 2 (Q1)
    );

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

    // U4: CD4071 quad 2-input OR, pin 1 in column 39

    cd4071 i_u4
    (
        .a ( open        ),  // Pin 1 <- U3 pin 10 (L)
        .b ( a           ),  // Pin 2 <- U1 pin 2 (Q1)
        .j ( d0          ),  // Pin 3 -> S0'
        .k ( unused_u4_k ),  // Pin 4, unused output
        .c ( gnd         ),  // Pin 5 <- GND, unused input
        .d ( gnd         ),  // Pin 6 <- GND, unused input
        .e ( vdd         ),  // Pin 8 <- +5V, unused input
        .f ( vdd         ),  // Pin 9 <- +5V, unused input
        .l ( unused_u4_l ),  // Pin 10, unused output
        .m ( d1          ),  // Pin 11 -> S1'
        .g ( t3          ),  // Pin 12 <- U3 pin 11 (M)
        .h ( t2          )   // Pin 13 <- U3 pin 4 (K)
    );

endmodule

11Testbench and simulation scripts

tb.sv runs both designs side by side and compares them with a reference model that knows nothing about states: it keeps the last samples of the button and notes when 1, 0, 1 has been among them. Like the testbenches of Basics-Graphics-Music, it drives and checks signals only at rising clock edges. It enters wrong codes, the right one, the code after extra digits, resets in between, and ends with 80 clocks of pseudo-random presses with a reset now and then. The output below is shortened.

tb.sv254 lines · show the codefile
// Testbench for exercise P6.
//
// Runs the generic design (code_lock.sv) and the chip-level design
// (code_lock_chips.sv) side by side and compares both with a reference
// model that keeps the samples of the button instead of states: the lock is
// open once the samples since reset contain 1, 0, 1.  Works with Icarus
// Verilog, Verilator (--binary) and Questa.
//
// Like the testbenches of Basics-Graphics-Music, it drives and samples
// signals only at rising clock edges.  It enters wrong codes, the right one,
// codes with extra digits before it, resets in between, makes pseudo-random
// presses, and checks that reset acts at once.

// Time units.  The design files have none: Yosys does not accept timeunit
// and timeprecision, and the Tiny Tapeout template sets `timescale 1ns / 1ps
// in its own testbench.  This line sets the same units here and for the
// design files compiled after it, so tb.sv comes first in the file list.

`timescale 1ns / 1ps

module tb;

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

    wire        a,     a_chips;
    wire  [1:0] state, state_chips;
    wire        open,  open_chips;

    code_lock i_generic
    (
        .clk   ( clk   ),
        .rst   ( rst   ),
        .btn   ( btn   ),
        .a     ( a     ),
        .state ( state ),
        .open  ( open  )
    );

    code_lock_chips i_chips
    (
        .clk   ( clk         ),
        .rst   ( rst         ),
        .btn   ( btn         ),
        .a     ( a_chips     ),
        .state ( state_chips ),
        .open  ( open_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 sampled button, the samples of it since reset
    // (the newest in bit 0) and whether 1, 0, 1 has been among them

    logic       a_model;
    logic [1:0] last_two;
    int         n_samples;
    logic       opened;

    always @ (posedge clk or posedge rst)
        if (rst)
        begin
            a_model   <= 1'b0;
            n_samples <= 0;
            opened    <= 1'b0;
        end
        else
        begin
            a_model   <= btn;
            last_two  <= { last_two [0], a_model };
            n_samples <= n_samples + 1;

            if (n_samples >= 2 && last_two == 2'b10 && a_model)
                opened <= 1'b1;
        end

    // The state: how much of 1, 0, 1 the last samples match

    wire [1:0] state_expected = opened                                 ? 2'd3
                              : n_samples >= 2 && last_two == 2'b10    ? 2'd2
                              : n_samples >= 1 && last_two [0] == 1'b1 ? 2'd1
                              :                                          2'd0;

    wire ok_generic = { a,       state,       open       } === { a_model, state_expected, opened };
    wire ok_chips   = { a_chips, state_chips, open_chips } === { a_model, state_expected, opened };

    //------------------------------------------------------------------------
    // Checking at every rising clock edge.  At the edge both designs and the
    // model still show the clock cycle that ends there, the same values that
    // a flip-flop would sample.

    // Initial values are fine in a testbench, and the checker samples rst at
    // the clock edge on purpose, although the designs reset asynchronously

    // verilator lint_off PROCASSINIT
    // verilator lint_off SYNCASYNCNET

    logic was_reset = 1'b0;
    logic done      = 1'b0;  // Set by the stimulus before $finish

    int cycle    = 0;
    int n_checks = 0;
    int n_errors = 0;
    int n_opened = 0;  // Times the lock opened

    logic opened_before = 1'b0;

    logic [3:0] states_seen = '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);
            states_seen <= states_seen | (4'b1 << state_expected);

            opened_before <= opened;

            if (opened & ~ opened_before)
                n_opened <= n_opened + 1;

            $display ("%5d  %b    %b    %b  %b%b      %b   %s  %s",
                cycle + 1, rst, btn, a, state [1], state [0], open,
                ok_generic ? "ok     " : "WRONG  ", ok_chips ? "ok" : "WRONG");
        end
    end

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

    int n_async = 0;

    always @ (posedge rst)
    begin
        # 1;

        if ({ a, state, open, a_chips, state_chips, open_chips } !== 8'b0)
        begin
            $display ("WRONG: reset did not act at once");
            n_errors <= n_errors + 1;
        end

        n_async <= n_async + 1;
    end

    //------------------------------------------------------------------------
    // Driving the inputs: one digit of the code per clock edge, as when the
    // button is held or released through one tick of the clock module

    // n digits of code, the first digit in bit n - 1

    task automatic enter (input logic [7:0] code, input int n);
        for (int i = n - 1; i >= 0; i --)
        begin
            btn <= code [i];
            @ (posedge clk);
        end

        btn <= 1'b0;
    endtask

    task automatic reset_lock;
        rst <= 1'b1;
        @ (posedge clk);
        rst <= 1'b0;
    endtask

    logic [31:0] seed = 32'd9;

    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  BTN  A  S1S0  OPEN  generic  chips");

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

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

        enter (8'b0110,    4);  // 0, 1, 1, 0: no 1, 0, 1 in it
        reset_lock;
        enter (8'b101,     3);  // the code: opens
        enter (8'b0000,    4);  // and the lock stays open
        reset_lock;
        enter (8'b1101,    4);  // the code after an extra 1: opens
        reset_lock;
        enter (8'b10001,   5);  // no 1, 0, 1 in it
        reset_lock;
        enter (8'b1001,    4);  // no 1, 0, 1 in it
        enter (8'b0110100, 7);  // 1, 0, 1 in the middle: opens
        reset_lock;

        // Pseudo-random presses, the same in every simulator, with a reset
        // now and then

        for (int i = 0; i < 80; i ++)
        begin
            seed = seed * 32'd1664525 + 32'd1013904223;

            if (seed [31:28] == 4'b0)
                reset_lock;
            else
            begin
                btn <= seed [27];
                @ (posedge clk);
            end
        end

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

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

        $finish;
    end

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

    final
    begin
        if (n_errors == 0 && states_seen == 4'b1111 && n_opened >= 2 && n_async >= 4)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, states seen %b, opened %0d times, %0d resets",
                      n_errors, n_checks, states_seen, n_opened, n_async);
    end

endmodule

Each script compiles the files, runs the simulation, writes a log and the waveform tb.vcd, and exits with an error unless the test passes. Run them from any directory: ./run_icarus.bash, ./run_verilator.bash or ./run_questa.bash; ./clean.bash removes what they make. The waveform opens in GTKWave or Surfer.

run_icarus.bash22 lines · show the codefile
#!/usr/bin/env bash

# Exercise P6: 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 code_lock.sv code_lock_chips.sv cd4069.sv cd40174.sv cd4081.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 P6: 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 code_lock.sv code_lock_chips.sv cd4069.sv cd40174.sv cd4081.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 P6: 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 code_lock.sv code_lock_chips.sv cd4069.sv cd40174.sv cd4081.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  BTN  A  S1S0  OPEN  generic  chips
    1  1    0    0  00      0   ok          ok
    2  0    0    0  00      0   ok          ok
    3  0    1    0  00      0   ok          ok
    4  0    1    1  00      0   ok          ok
    5  0    0    1  01      0   ok          ok
    6  1    0    0  00      0   ok          ok
    7  0    1    0  00      0   ok          ok
    8  0    0    1  00      0   ok          ok
    9  0    1    0  01      0   ok          ok
   10  0    0    1  10      0   ok          ok
   11  0    0    0  11      1   ok          ok
   12  0    0    0  11      1   ok          ok
   13  0    0    0  11      1   ok          ok
   14  1    0    0  00      0   ok          ok
   15  0    1    0  00      0   ok          ok
   16  0    1    1  00      0   ok          ok
   17  0    0    1  01      0   ok          ok
   18  0    1    0  01      0   ok          ok
   19  1    0    0  00      0   ok          ok
   20  0    1    0  00      0   ok          ok
   21  0    0    1  00      0   ok          ok
   22  0    0    0  01      0   ok          ok
   23  0    0    0  10      0   ok          ok
   24  0    1    0  00      0   ok          ok
   25  1    0    0  00      0   ok          ok
   26  0    1    0  00      0   ok          ok
   27  0    0    1  00      0   ok          ok
   28  0    0    0  01      0   ok          ok
  …
  116  0    0    1  00      0   ok          ok
  117  0    1    0  01      0   ok          ok
tb.sv:240: $finish called at 1195000 (1ps)
PASS: 234 checks, no errors

To see that the testbench catches mistakes, break something and run it again: replace state [1] & state [0] with state [0] in the equation of state [0] in code_lock.sv, or connect D2 of the 40174 to A instead of S0' in code_lock_chips.sv. The script reports FAIL and the trace shows the lines marked WRONG.

12On an FPGA board: lab_top in BGM

The Basics-Graphics-Music (BGM) repository runs the same labs on dozens of FPGA boards. Each lab has a lab_top module with the same ports on every board: clock, a 1 Hz slow_clk, reset, keys, LEDs, a 7-segment display.

  1. Copy labs/1_basics/1_10_snail_fsm to a new directory.
  2. Replace its lab_top.sv with bgm_lab/lab_top.sv from this exercise and add code_lock.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.

Key 0 is the code button: hold it or release it through a tick of slow_clk. LED 0 shows the sampled button, LEDs 2–1 the state and LED 3 OPEN. The rightmost digit shows the state, 0 to 3, and its dot lights while the lock is open. To run the chip-level design instead, add code_lock_chips.sv, cd40174.sv, cd4069.sv, cd4081.sv and cd4071.sv and change the module name in the instance.

bgm_lab/lab_top.sv111 lines · show the codefile
// Exercise P6 on an FPGA board with the Basics-Graphics-Music (BGM) labs:
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy labs/1_basics/1_10_snail_fsm to a new directory, replace its
// lab_top.sv with this file and add code_lock.sv.  For the chip-level
// design add code_lock_chips.sv and cd40174.sv, cd4069.sv, cd4081.sv,
// cd4071.sv instead, and change the module name below.
//
// The lock runs from slow_clk, 1 Hz on every BGM board, and rst is the
// reset of the board.  Key 0 is the code button: hold it or release it
// through a tick of slow_clk to enter 1, 0, 1.  LED 0 shows the sampled
// button, LEDs 2-1 the state, LED 3 OPEN.  The rightmost digit shows the
// state, 0 to 3, and its dot lights while the lock is open.

`include "config.svh"

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

               screen_width  = 640,
               screen_height = 480,

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

               w_x           = $clog2 ( screen_width  ),
               w_y           = $clog2 ( screen_height )
)
(
    input                        clk,
    input                        slow_clk,
    input                        rst,

    // Keys, switches, LEDs

    input        [w_key   - 1:0] key,
    input        [w_sw    - 1:0] sw,
    output logic [w_led   - 1:0] led,

    // A dynamic seven-segment display

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

    // Graphics

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

    output logic [w_red   - 1:0] red,
    output logic [w_green - 1:0] green,
    output logic [w_blue  - 1:0] blue,

    // Microphone, sound output and UART

    input        [         23:0] mic,
    output       [         15:0] sound,

    input                        uart_rx,
    output                       uart_tx,

    // General-purpose Input/Output

    inout        [w_gpio  - 1:0] gpio
);

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

       assign red        = '0;
       assign green      = '0;
       assign blue       = '0;
       assign sound      = '0;
       assign uart_tx    = '1;

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

    logic       a, open;
    logic [1:0] state;

    code_lock i_code_lock
    (
        .clk   ( slow_clk ),
        .rst   ( rst      ),
        .btn   ( key [0]  ),
        .a     ( a        ),
        .state ( state    ),
        .open  ( open     )
    );

    assign led = w_led' ({ open, state, a });

    // The number of the state: how many digits of the code are matched

    always_comb
        case (state)
        2'd0: abcdefgh = 8'b1111_1100;  // 0
        2'd1: abcdefgh = 8'b0110_0000;  // 1
        2'd2: abcdefgh = 8'b1101_1010;  // 2
        2'd3: abcdefgh = 8'b1111_0011;  // 3 and the dot: open
        endcase

    assign digit = w_digit' (1);

endmodule

13On an FPGA board: hackathon_top in BGM

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

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

Any key is the code button. The screen shows a big square, red while the lock is closed and green when it is open, with three small lamps above it: A, S1 and S0. The LEDs and the rightmost digit are as in lab_top.

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

// Exercise P6 in the hackathon setup of Basics-Graphics-Music (BGM):
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy a directory such as hackathon/problems/3_d_flip_flop, replace its
// hackathon_top.sv with this file and add code_lock.sv.
//
// The lock runs from slow_clock.  Any key is the code button: hold it or
// release it through a tick of slow_clock to enter 1, 0, 1.  The LEDs and
// the rightmost digit are as in lab_top.  The screen shows a lock: a red
// square while it is closed, a green one when it is open, with the three
// small lamps A, S1, S0 above it.

module hackathon_top
(
    input  logic       clock,
    input  logic       slow_clock,
    input  logic       reset,

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

    // A dynamic seven-segment display

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

    // LCD screen interface

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

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

    inout  logic [3:0] gpio
);

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

    logic       a, open;
    logic [1:0] state;

    code_lock i_code_lock
    (
        .clk   ( slow_clock ),
        .rst   ( reset      ),
        .btn   ( | key      ),
        .a     ( a          ),
        .state ( state      ),
        .open  ( open       )
    );

    assign led = { 4'b0, open, state, a };

    // The number of the state: how many digits of the code are matched

    always_comb
        case (state)
        2'd0: abcdefgh = 8'b1111_1100;  // 0
        2'd1: abcdefgh = 8'b0110_0000;  // 1
        2'd2: abcdefgh = 8'b1101_1010;  // 2
        2'd3: abcdefgh = 8'b1111_0011;  // 3 and the dot: open
        endcase

    assign digit = 8'b0000_0001;

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

    wire [2:0] lamp = { a, state [1], state [0] };

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

        for (int i = 0; i < 3; i ++)
            if (x >= 9' (170 + i * 50) & x < 9' (200 + i * 50) & y >= 40 & y < 70)
            begin
                green = lamp [2 - i] ? 40 : 8;
                blue  = lamp [2 - i] ? 31 : 6;
            end

        if (x >= 180 & x < 300 & y >= 100 & y < 220)
        begin
            if (open)
                green = 63;
            else
                red   = 31;
        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 lock, just as the 555 module clocks the chips on the breadboard.

DIP switch 0 is the code button: set it before a tick of the clock. The display shows the state, and its dot is OPEN. The sampled button and OPEN also go to BIDIR pins 0 and 1. The reset button of the demo board closes the lock.

tiny_tapeout/project.v64 lines · show the codefile
/*
 * Exercise P6 on Tiny Tapeout: a code lock, a state machine that opens
 * after the input gives 1, 0, 1 at three clock edges in a row.  The
 * 7-segment display of the demo board shows the state, and its dot is OPEN.
 *
 * Add code_lock.sv to source_files in info.yaml next to project.v.
 * Rename the module to tt_um_<your GitHub name>_<project name> and use the
 * same name as top_module in info.yaml.
 */

`default_nettype none

module tt_um_example (
    input  wire [7:0] ui_in,    // DIP switches, INPUT Pmod, RP2350 GPIO17-24
    output wire [7:0] uo_out,   // 7-segment display, OUTPUT Pmod, RP2350 GPIO33-40
    input  wire [7:0] uio_in,   // BIDIR Pmod, RP2350 GPIO25-32
    output wire [7:0] uio_out,  //   (same pins)
    output wire [7:0] uio_oe,   //   1 = your design drives the pin
    input  wire       ena,      // set by the on-chip project mux, not a board pin
    input  wire       clk,      // RP2350 GPIO16
    input  wire       rst_n     // RP2350 GPIO14
);

    // The demo board makes the project clock; set it to 1 Hz.  DIP switch 0
    // is the code button: set it before a tick of the clock.  The reset
    // button of the board closes the lock.

    wire       a, open;
    wire [1:0] state;

    code_lock i_code_lock (
        .clk   ( clk       ),
        .rst   ( ~ rst_n   ),
        .btn   ( ui_in [0] ),
        .a     ( a         ),
        .state ( state     ),
        .open  ( open      )
    );

    // 7-segment display: uo_out [0] is segment a, ..., uo_out [6] is g,
    // uo_out [7] is the dot.  The state, 0 to 3; the dot is OPEN.

    reg [6:0] gfedcba;

    always @(*)
        case (state)
        2'd0: gfedcba = 7'b0111111;  // 0
        2'd1: gfedcba = 7'b0000110;  // 1
        2'd2: gfedcba = 7'b1011011;  // 2
        2'd3: gfedcba = 7'b1001111;  // 3
        endcase

    assign uo_out  = { open, gfedcba };

    // The sampled input and OPEN on BIDIR pins 0-1

    assign uio_out = { 6'b0, open, a };
    assign uio_oe  = 8'b0000_0011;

    // List all unused inputs to prevent warnings

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

endmodule

In info.yaml set the clock to 1 Hz, list the files and use the module name as the top module:

project:
  clock_hz:   1                 # 1 Hz from the demo board
  top_module: "tt_um_example"   # rename to tt_um_<your GitHub name>_code_lock
  source_files:
    - "project.v"
    - "code_lock.sv"
No clock divider on a chip. BGM makes slow_clk with a counter, but on AMD and Intel FPGAs it routes that signal onto the clock network with BUFG or global (section 12). In an ASIC a counter bit used as a clock is bad practice: it is a second clock with its own clock tree, its edges come later than those of clk by a delay nobody controls, and every signal between the two clocks crosses clock domains. Here the board makes the 1 Hz clock, so no divider is needed. When a chip needs a slow tick from a fast clock, keep one clock and add a clock enable: a pulse one clock long that lets the slow logic change only on the edges where it is 1.

15Going further

Tasks for students

Files of this exercise

Sources

The exercise is in the Projects list of “An improved way of teaching school kids digital electronics” and in lesson 1.7, “Code lock”, of the Habr article about the electronics course, which suggests the 4076 or 40174 for more flip-flops. The equations were made by the task generator of the LSSK FSM kit, which solves every code of 2 to 6 digits to size the kit and print the task cards. The chips are described in the Texas Instruments datasheets for the CD40174B, CD4069UB, CD4081B and CD4071B.