Breadboard exercises/ P5EnglishРусский

Exercise P5 · project · finite state machine

FSM that recognizes 0, 1: the Harris & Harris snail

A snail crawls along a paper tape of 0s and 1s and smiles when the last two digits it crossed are 0, then 1. Two flip-flops, an inverter and an AND gate make the snail's brain: a finite state machine, the circuit behind every code lock and every protocol decoder.

3 chips4013, 4081, 4069
25 + 13 wireson the board + jumper leads to the modules
3 statesin 2 flip-flops
~1 Hzone sample of the button per clock

1What it is and why it matters

What it does. At every rising edge of the clock the circuit takes one sample of button A: released is 0, pressed is 1. When the last two samples were 0 and then 1, LED 3, the output Y, lights for one clock period. LED 1 shows A and LED 2 the first state bit, S0.

How it works. The machine has three states: S0, nothing useful seen yet; S1, the last sample was 0; S2, the last two samples were 0, then 1. Harris & Harris write them in two bits and get two short equations for the next state:

Where it is used. Every circuit that has to react to a sequence is a state machine: a code lock, a serial receiver that waits for a start bit, a network chip that looks for the start of a packet, the controller of a processor that steps through the phases of an instruction. In SystemVerilog, state machines are among the most common pieces of code.

Why learn it.

2The key elements: states and transitions

The state table, with the state written as the bits S1 S0:

State = S1 S0ANext stateY = S1
S0 = 000S1 = 010
S0 = 001S0 = 000
S1 = 010S1 = 010
S1 = 011S2 = 100
S2 = 100S1 = 011
S2 = 101S0 = 001

The code 11 never occurs. After a reset the machine is in S0 = 00. Note that the input is sampled, not watched: pressing and releasing A between two ticks of the clock does nothing, and bounces of the button do not matter.

Waveforms

CLKRSTAS0S1 = Y
From the simulation of tb.sv in Icarus Verilog. S0 is 1 after every sample of A at 0; Y lights one clock period after every sample at 1 that follows a 0. The reset at the end erases a 0 that was seen just before it. · SVG · PNG

3Parts

PartIn this circuitQtyPriceSupplier
CD4013dual D flip-flop: the two state bits S0 and S11$0.35Elexp (elexp.com)
CD4081quad AND: S0 AND A (one of four used)1$0.55Elexp (elexp.com)
CD4069hex inverter: NOT A (one of six used)1$0.30Elexp (elexp.com)
Button modulesRESET and the input A; 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, S0 and S1 = Y on LEDs 1-31$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 wires25 wires on the board (or male-male Dupont jumpers)25$11.95 / packjameco.com
Male-female Dupont jumpers13 leads to the clock module, the buttons and the LED module13$1.30 / packaliexpress.us

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

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.

4013: dual D flip-flop

1Q12Q13CLK14R15D16S17VSS8S29D210R211CLK212Q213Q214VDD40132 × D flip-flop
CD4013B. · SVG · PNG

As in exercise B4. Flip-flop 1 holds S0: D1 (pin 5) gets NOT A, Q1 (pin 1) is S0. Flip-flop 2 holds S1: D2 (pin 9) gets S0 AND A, Q2 (pin 13) is S1 and the output Y. Both clocks (pins 3 and 11) come from the clock module, both resets (pins 4 and 10) from the RESET button; the set inputs (pins 6 and 8) are at GND.

PinNameDirectionFunctionIn this circuit
1Q1outputflip-flop 1 outputS0
2Q1outputflip-flop 1 output, invertednot connected
3CLOCK1inputflip-flop 1 stores D1 on the rising edge, 0 to 1CLK
4RESET1input1 sets Q1 = 0 at once, without the clock. Active highRST
5D1inputflip-flop 1 data inputA
6SET1input1 sets Q1 = 1 at once, without the clock. Active highGND
7VSSpowerground, 0 VGND
8SET2input1 sets Q2 = 1 at once. Active highGND
9D2inputflip-flop 2 data inputS0·A
10RESET2input1 sets Q2 = 0 at once. Active highRST
11CLOCK2inputflip-flop 2 stores D2 on the rising edgeCLK
12Q2outputflip-flop 2 output, invertednot connected
13Q2outputflip-flop 2 outputS1
14VDDpowersupply, +5 V (3 to 18 V allowed)+5V

4081: quad 2-input AND

1A2B3J4K5C6D7VSS8E9F10L11M12G13H14VDD4081
CD4081B. · SVG · PNG

Gate J, pins 1 and 2 to pin 3, makes S0 AND A. The inputs of the other three gates are tied to GND.

PinNameDirectionFunctionIn this circuit
1Ainputinput of the gate with its output on pin 3S0
2Binputinput of the gate with its output on pin 3A
3JoutputJ = A AND BS0·A
4KoutputK = C AND 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 AND Fnot connected
11MoutputM = G AND Hnot connected
12Ginputinput of the gate with its output on pin 11tied to +5V
13Hinputinput of the gate with its output on pin 11tied to +5V
14VDDpowersupply, +5 V (3 to 18 V allowed)+5V

4069: hex inverter

1A2G3B4H5C6I7VSS8J9D10K11E12L13F14VDD4069
CD4069UB. · SVG · PNG

One inverter, pins 5 → 6, makes NOT A. The inputs of the other five are tied to the rails.

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

5Schematic 1: the state machine

CLKRESETA4069DRQ40134081DRQ4013ALED 1S0LED 2S1 = YLED 3
The circuit as gates and flip-flops. This is what snail_fsm.sv describes. · SVG · PNG

6Schematic 2: connections between the chips

1234567891011121314Q1Q1CLK1R1D1S1S2D2R2CLK2Q2Q240132 × D flip-flop1234567891011121314408112345678910111213144069CLKRSTAAS0S0·AS1clockRESETALED module: LEDs 1-3+5V
The same circuit as chips, pin by pin. · SVG · PNG
NetFromToWire
CLK555 clock module, OUT4013 3 (CLK1), 4013 11 (CLK2)M-F, M-M
RSTbutton RESET, OUT4013 4 (R1), 4013 10 (R2)M-F, M-M
Abutton A, OUT4069 5 (C), 4081 2 (B), LED module, LED 1M-F, M-M
A4069 6 (I)4013 5 (D1)M-M
S04013 1 (Q1)4081 1 (A), LED module, LED 2M-F, M-M
S0·A4081 3 (J)4013 9 (D2)M-M
S14013 13 (Q2)LED module, LED 3M-F
+5V+5V4013 14 (VDD), 4081 14 (VDD), 4069 14 (VDD), 4081 13 (H), 4081 12 (G), 4081 9 (F), 4081 8 (E), 4069 3 (B), 4069 1 (A)
GNDGND4013 7 (VSS), 4081 7 (VSS), 4069 7 (VSS), 4013 8 (S2), 4013 6 (S1), 4081 5 (C), 4081 6 (D), 4069 9 (D), 4069 11 (E), 4069 13 (F)
not connected4013 2 (Q1), 4013 12 (Q2), 4081 4 (K), 4081 10 (L), 4081 11 (M), 4069 2 (G), 4069 4 (H), 4069 8 (J), 4069 10 (K), 4069 12 (L)

7Schematic 3: the breadboard

−+−+1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950abcdefghij5V5VPOWER MODULE · 5V9V USB-DC401340814069CLKRSTAAS0·A−OUT+555CLOCK 555~1 Hz+OUT−RESET+OUT−AG1A2S03S1456788-LED MODULELEDs 1-3 used
Every wire in its hole. Column numbers are printed along the top; rows a–e are above the gap, f–j below it. The clock module and the two buttons hang above the board, the LED module below it. · SVG · PNG
CLKRSTAAS0S0·AS1+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 4013 turned around, notch to the right, pin 1 in hole 18e; the 4081, notch to the left, pin 1 in hole 20f; the 4069 turned around, notch to the right, pin 1 in hole 34e. 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: the set inputs of the 4013, the inputs of the three unused AND gates and of the five unused inverters.
  5. The signal wires: the clock to both flip-flops, RESET to both resets, A to the inverter and to the AND gate, NOT A to D1, S0 to the AND gate, the AND output to D2. Tick each wire as you insert it.
  6. With the power off, the modules: the clock module, RESET and A 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 −) · 6 wires
1+5V18j (4013 pin 14, VDD)bottom + rail, column 18
2GND12a (4013 pin 7, VSS)top − rail, column 12
3+5V20a (4081 pin 14, VDD)top + rail, column 20
4GND26j (4081 pin 7, VSS)bottom − rail, column 26
5+5V34j (4069 pin 14, VDD)bottom + rail, column 34
6GND28a (4069 pin 7, VSS)top − rail, column 28
Fixed inputs: CMOS inputs must not float · 13 wires
7GND12j (4013 pin 8, S2)bottom − rail, column 12
8GND13a (4013 pin 6, S1)top − rail, column 13
9+5V21a (4081 pin 13, H)top + rail, column 21
10+5V22a (4081 pin 12, G)top + rail, column 22
11GND24j (4081 pin 5, C)bottom − rail, column 24
12+5V25a (4081 pin 9, F)top + rail, column 25
13GND25j (4081 pin 6, D)bottom − rail, column 25
14+5V26a (4081 pin 8, E)top + rail, column 26
15GND29j (4069 pin 9, D)bottom − rail, column 29
16GND31j (4069 pin 11, E)bottom − rail, column 31
17+5V32a (4069 pin 3, B)top + rail, column 32
18GND33j (4069 pin 13, F)bottom − rail, column 33
19+5V34a (4069 pin 1, A)top + rail, column 34
Signal wires · 6 wires
20CLK16c (4013 pin 3, CLK1)15g (4013 pin 11, CLK2)
21RST15b (4013 pin 4, R1)14h (4013 pin 10, R2)
22A30c (4069 pin 5, C)21g (4081 pin 2, B)
23A29d (4069 pin 6, I)14d (4013 pin 5, D1)
24S018c (4013 pin 1, Q1)20g (4081 pin 1, A)
25S0·A22g (4081 pin 3, J)13g (4013 pin 9, D2)
Modules on male-female jumpers · 13 wires
26GND555 clock module, −top − rail, column 11
27CLK555 clock module, OUT16a (4013 pin 3, CLK1)
28+5V555 clock module, +top + rail, column 14
29+5Vbutton RESET, +top + rail, column 18
30RSTbutton RESET, OUT15a (4013 pin 4, R1)
31GNDbutton RESET, −top − rail, column 20
32+5Vbutton A, +top + rail, column 24
33Abutton A, OUT30a (4069 pin 5, C)
34GNDbutton A, −top − rail, column 26
35GNDLED module, Gbottom − rail, column 17
36ALED module, LED 121j (4081 pin 2, B)
37S0LED module, LED 220j (4081 pin 1, A)
38S1LED module, LED 317j (4013 pin 13, Q2)

Test it

If it does not work: if LED 2 lights while A is pressed, the inverter is missing and A goes straight to D1. If Y never lights, check the wire from Q1 to the AND gate: with NOT A there instead of S0, the gate gets A AND NOT A, which is always 0. If nothing moves, check the clock wire to both pins 3 and 11.

8SystemVerilog: the generic design

snail_fsm.sv writes the two equations of the book into one always_ff block. In larger designs the states get names with an enum, as in the snail lab of Basics-Graphics-Music, and synthesis chooses the gates. It is synthesizable.

snail_fsm.svfile
// Exercise P5: a Moore finite state machine that recognizes the sequence
// 0, 1 on its input a, the "snail" of Harris & Harris, Digital Design and
// Computer Architecture.
//
// Generic version that matches schematic 1, not tied to any chip.  The
// two state bits are written with the equations of the book:
//
//     state [0]' = ~ a                 the last sample of a was 0
//     state [1]' = state [0] & a       the last two samples were 0, then 1
//
// so the three states are 00 (S0: nothing seen), 01 (S1: a 0 seen) and
// 10 (S2: 0, 1 seen).  The output y of the machine is state [1]: in a
// Moore machine the output depends only on the state.  rst clears both
// bits at once, without the clock.  Synthesizable.

module snail_fsm
(
    input  logic       clk,
    input  logic       rst,
    input  logic       a,
    output logic [1:0] state  // y = state [1]
);

    always_ff @ (posedge clk or posedge rst)
        if (rst)
            state <= '0;
        else
            state <= { state [0] & a, ~ a };

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.

cd4013.svfile
// CD4013B: dual D flip-flop with set and reset.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (7)
// and VDD (14), are left out.  Synthesizable.
//
// Each flip-flop stores D at the rising edge of its clock.  SET and RESET
// are active high and asynchronous: they act at once, without the clock.
// With SET and RESET both high the chip sets both Q and ~Q high; the model
// does the same while they are both high.  Do not release them at the same
// moment: which of the two wins is not defined.

module cd4013
(
    output logic q1,      // Pin 1
    output logic q1_n,    // Pin 2:  ~Q1
    input  logic clock1,  // Pin 3
    input  logic reset1,  // Pin 4:  1 = Q1 goes to 0 at once
    input  logic d1,      // Pin 5
    input  logic set1,    // Pin 6:  1 = Q1 goes to 1 at once
                          // Pin 7:  VSS
    input  logic set2,    // Pin 8
    input  logic d2,      // Pin 9
    input  logic reset2,  // Pin 10
    input  logic clock2,  // Pin 11
    output logic q2_n,    // Pin 12: ~Q2
    output logic q2       // Pin 13
                          // Pin 14: VDD
);

    logic r1, r2;

    always_ff @ (posedge clock1 or posedge reset1 or posedge set1)
        if (reset1)
            r1 <= 1'b0;
        else if (set1)
            r1 <= 1'b1;
        else
            r1 <= d1;

    always_ff @ (posedge clock2 or posedge reset2 or posedge set2)
        if (reset2)
            r2 <= 1'b0;
        else if (set2)
            r2 <= 1'b1;
        else
            r2 <= d2;

    assign q1   =   r1 | (set1 & reset1);
    assign q1_n = ~ r1 | (set1 & reset1);
    assign q2   =   r2 | (set2 & reset2);
    assign q2_n = ~ r2 | (set2 & reset2);

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

10SystemVerilog: the chip-level design

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

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

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

    // Connections between the chips that are not ports

    wire na;
    wire d1;

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

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

    // Outputs that go nowhere

    wire unused_u1_q1_n;
    wire unused_u1_q2_n;
    wire unused_u2_k;
    wire unused_u2_l;
    wire unused_u2_m;
    wire unused_u3_g;
    wire unused_u3_h;
    wire unused_u3_j;
    wire unused_u3_k;
    wire unused_u3_l;

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

    // U1: CD4013 dual D flip-flop with set and reset, pin 1 in column 12

    cd4013 i_u1
    (
        .q1     ( state [0]      ),  // Pin 1 -> S0
        .q1_n   ( unused_u1_q1_n ),  // Pin 2, unused output
        .clock1 ( clk            ),  // Pin 3 <- 555 clock module
        .reset1 ( rst            ),  // Pin 4 <- button RESET
        .d1     ( na             ),  // Pin 5 <- U3 pin 6 (I)
        .set1   ( gnd            ),  // Pin 6 <- GND
        .set2   ( gnd            ),  // Pin 8 <- GND
        .d2     ( d1             ),  // Pin 9 <- U2 pin 3 (J)
        .reset2 ( rst            ),  // Pin 10 <- button RESET
        .clock2 ( clk            ),  // Pin 11 <- 555 clock module
        .q2_n   ( unused_u1_q2_n ),  // Pin 12, unused output
        .q2     ( state [1]      )   // Pin 13 -> S1
    );

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

    // U2: CD4081 quad 2-input AND, pin 1 in column 20

    cd4081 i_u2
    (
        .a ( state [0]   ),  // Pin 1 <- U1 pin 1 (Q1)
        .b ( a           ),  // Pin 2 <- button A
        .j ( d1          ),  // Pin 3 -> S0·A
        .k ( unused_u2_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_u2_l ),  // Pin 10, unused output
        .m ( unused_u2_m ),  // Pin 11, unused output
        .g ( vdd         ),  // Pin 12 <- +5V, unused input
        .h ( vdd         )   // Pin 13 <- +5V, unused input
    );

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

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

    cd4069 i_u3
    (
        .a ( vdd         ),  // Pin 1 <- +5V, unused input
        .g ( unused_u3_g ),  // Pin 2, unused output
        .b ( vdd         ),  // Pin 3 <- +5V, unused input
        .h ( unused_u3_h ),  // Pin 4, unused output
        .c ( a           ),  // Pin 5 <- button A
        .i ( na          ),  // Pin 6 -> ~A
        .j ( unused_u3_j ),  // Pin 8, unused output
        .d ( gnd         ),  // Pin 9 <- GND, unused input
        .k ( unused_u3_k ),  // Pin 10, unused output
        .e ( gnd         ),  // Pin 11 <- GND, unused input
        .l ( unused_u3_l ),  // Pin 12, unused output
        .f ( gnd         )   // Pin 13 <- GND, unused input
    );

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 two samples of A since reset. Like the testbenches of Basics-Graphics-Music, it drives and checks signals only at rising clock edges. It feeds a sequence that holds every pair of bits, resets right after a 0, and ends with 60 pseudo-random bits. The output below is shortened.

tb.sv217 lines · show the codefile
// Testbench for exercise P5.
//
// Runs the generic design (snail_fsm.sv) and the chip-level design
// (snail_fsm_chips.sv) side by side and compares both with a reference
// model that does not use states at all: it remembers the last two samples
// of a since reset.  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 feeds a sequence that holds every
// pair of bits, then pseudo-random bits, resets in the middle, and checks
// that reset acts at once.

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

`timescale 1ns / 1ps

module tb;

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

    wire  [1:0] state, state_chips;

    snail_fsm i_generic
    (
        .clk   ( clk   ),
        .rst   ( rst   ),
        .a     ( a     ),
        .state ( state )
    );

    snail_fsm_chips i_chips
    (
        .clk   ( clk         ),
        .rst   ( rst         ),
        .a     ( a           ),
        .state ( state_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 samples since reset and the last two

    int   n_samples;
    logic last, before_last;

    always @ (posedge clk or posedge rst)
        if (rst)
            n_samples <= 0;
        else
        begin
            n_samples   <= n_samples + 1;
            before_last <= last;
            last        <= a;
        end

    // S0: the last sample was 0.  S1 = Y: the last two were 0, then 1.

    wire [1:0] state_expected = { n_samples >= 2 && before_last == 1'b0 && last == 1'b1,
                                  n_samples >= 1 && last == 1'b0 };

    wire ok_generic = state       === state_expected;
    wire ok_chips   = state_chips === state_expected;

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

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

    // verilator lint_off PROCASSINIT
    // verilator lint_off SYNCASYNCNET

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

    int cycle    = 0;
    int n_checks = 0;
    int n_errors = 0;
    int n_found  = 0;  // Cycles with y = 1

    logic [2:0] states_seen = '0;  // S0, S1, S2

    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);
            n_found     <= n_found + (state_expected [1] ? 1 : 0);

            states_seen <= states_seen | (state_expected == 2'b00 ? 3'b001 :
                                          state_expected == 2'b01 ? 3'b010 :
                                          state_expected == 2'b10 ? 3'b100 : 3'b000);

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

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

    int n_async = 0;

    always @ (posedge rst)
    begin
        # 1;

        if ({ state, state_chips } !== 4'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 bit of the sequence per clock edge, as when
    // the button is held or released through one tick of the clock module

    // 1 1 0 0 1 0 1 1 1 0 1 0 0 0 1 1: every pair of bits, 0 1 found four times

    localparam logic [15:0] SEQUENCE = 16'b1100_1011_1010_0011;

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

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

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

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

        for (int i = 15; i >= 0; i --)
        begin
            a <= SEQUENCE [i];
            @ (posedge clk);
        end

        // Reset in the middle, right after a 0, so that the 0 is forgotten

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

        // Pseudo-random bits, the same in every simulator

        for (int i = 0; i < 60; i ++)
        begin
            seed = seed * 32'd1664525 + 32'd1013904223;
            a <= seed [31];
            @ (posedge clk);
        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 == 3'b111 && n_found >= 4 && n_async >= 2)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, states seen %b, 0 1 found %0d times, %0d resets",
                      n_errors, n_checks, states_seen, n_found, 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 P5: 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 snail_fsm.sv snail_fsm_chips.sv cd4013.sv cd4081.sv cd4069.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 P5: 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 snail_fsm.sv snail_fsm_chips.sv cd4013.sv cd4081.sv cd4069.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 P5: 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 snail_fsm.sv snail_fsm_chips.sv cd4013.sv cd4081.sv cd4069.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  A  S1S0  Y  generic  chips
    1  1    0  00    0  ok          ok
    2  1    0  00    0  ok          ok
    3  0    1  00    0  ok          ok
    4  0    1  00    0  ok          ok
    5  0    0  00    0  ok          ok
    6  0    0  01    0  ok          ok
    7  0    1  01    0  ok          ok
    8  0    0  10    1  ok          ok
    9  0    1  01    0  ok          ok
   10  0    1  10    1  ok          ok
   11  0    1  00    0  ok          ok
   12  0    0  00    0  ok          ok
   13  0    1  01    0  ok          ok
   14  0    0  10    1  ok          ok
   15  0    0  01    0  ok          ok
   16  0    0  01    0  ok          ok
   17  0    1  01    0  ok          ok
   18  0    1  10    1  ok          ok
   19  0    0  00    0  ok          ok
   20  1    1  00    0  ok          ok
   21  0    1  00    0  ok          ok
   22  0    0  00    0  ok          ok
   23  0    1  01    0  ok          ok
   24  0    0  10    1  ok          ok
   25  0    1  01    0  ok          ok
   26  0    1  10    1  ok          ok
   27  0    0  00    0  ok          ok
   28  0    0  01    0  ok          ok
  …
   80  0    1  01    0  ok          ok
   81  0    1  10    1  ok          ok
tb.sv:203: $finish called at 835000 (1ps)
PASS: 162 checks, no errors

To see that the testbench catches mistakes, break something and run it again: replace ~ a with a in snail_fsm.sv, or connect pin 1 of the 4081 to the inverter output instead of Q1 in snail_fsm_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 snail_fsm.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 A: hold it or release it through a tick of slow_clk. LED 0 shows A, LEDs 1 and 2 the state bits S0 and S1 = Y. The rightmost digit shows the number of the state, 0, 1 or 2, and its dot lights while Y is 1. The lab in Basics-Graphics-Music feeds the snail from a shift register and has a Mealy version beside the Moore one: compare them. To run the chip-level design instead, add snail_fsm_chips.sv, cd4013.sv, cd4081.sv and cd4069.sv and change the module name in the instance.

bgm_lab/lab_top.sv108 lines · show the codefile
// Exercise P5 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 snail_fsm.sv.  For the chip-level
// design add snail_fsm_chips.sv and cd4013.sv, cd4081.sv, cd4069.sv
// instead, and change the module name below.
//
// The FSM runs from slow_clk, 1 Hz on every BGM board, and rst is the
// reset of the board.  Key 0 is the input A: hold it or release it through
// a tick of slow_clk.  LED 0 shows A, LEDs 1 and 2 the state bits S0 and
// S1 = Y.  The rightmost digit shows the number of the state, 0, 1 or 2,
// and its dot lights while Y is 1.

`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 [1:0] state;

    snail_fsm i_snail_fsm
    (
        .clk   ( slow_clk ),
        .rst   ( rst      ),
        .a     ( key [0]  ),
        .state ( state    )
    );

    assign led = w_led' ({ state, key [0] });

    // The number of the state: 00 is S0, 01 is S1, 10 is S2

    always_comb
        case (state)
        2'b00:   abcdefgh = 8'b1111_1100;  // 0
        2'b01:   abcdefgh = 8'b0110_0000;  // 1
        2'b10:   abcdefgh = 8'b1101_1011;  // 2 and the dot: Y = 1
        default: abcdefgh = 8'b0000_0010;  // never reached: a dash
        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 snail_fsm.sv.
  3. Run ./03_synthesize_for_fpga.bash and ./04_configure_fpga.bash.

Any key is A. The screen shows three lamps: A in blue, S0 in orange and S1 = Y in green. The LEDs and the rightmost digit are as in lab_top.

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

// Exercise P5 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 snail_fsm.sv.
//
// The FSM runs from slow_clock.  Any key is the input A: hold it or release
// it through a tick of slow_clock.  The LEDs and the rightmost digit are as
// in lab_top.  The screen shows three lamps: A in blue, S0 in orange and
// S1 = Y in green.

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 [1:0] state;

    wire a = | key;

    snail_fsm i_snail_fsm
    (
        .clk   ( slow_clock ),
        .rst   ( reset      ),
        .a     ( a          ),
        .state ( state      )
    );

    assign led = { 5'b0, state, a };

    always_comb
        case (state)
        2'b00:   abcdefgh = 8'b1111_1100;  // 0
        2'b01:   abcdefgh = 8'b0110_0000;  // 1
        2'b10:   abcdefgh = 8'b1101_1011;  // 2 and the dot: Y = 1
        default: abcdefgh = 8'b0000_0010;  // never reached: a dash
        endcase

    assign digit = 8'b0000_0001;

    //------------------------------------------------------------------------
    // Three square lamps on the 480 x 272 screen: A, S0, S1 = Y.
    // Bright for 1, dim for 0.

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

        if (y >= 106 & y < 166)
        begin
            if (x >= 90 & x < 150)
                blue  = a ? 31 : 6;

            if (x >= 210 & x < 270)
            begin
                red   = state [0] ? 31 : 6;
                green = state [0] ? 24 : 5;
            end

            if (x >= 330 & x < 390)
                green = state [1] ? 63 : 12;
        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 FSM, just as the 555 module clocks the chips on the breadboard.

DIP switch 0 is A: set it before a tick of the clock. The display shows the number of the state, and its dot is Y. The reset button of the demo board resets the FSM.

tiny_tapeout/project.v60 lines · show the codefile
/*
 * Exercise P5 on Tiny Tapeout: a Moore FSM that recognizes 0, 1 on its
 * input, the snail of Harris & Harris.  The 7-segment display of the demo
 * board shows the number of the state, and its dot is the output Y.
 *
 * Add snail_fsm.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 input A: set it before a tick of the clock.  The reset button
    // of the board resets the FSM.

    wire [1:0] state;

    snail_fsm i_snail_fsm (
        .clk   ( clk       ),
        .rst   ( ~ rst_n   ),
        .a     ( ui_in [0] ),
        .state ( state     )
    );

    // 7-segment display: uo_out [0] is segment a, ..., uo_out [6] is g,
    // uo_out [7] is the dot.  0, 1 or 2 for the states S0, S1, S2; the dot
    // is Y = S1.

    reg [6:0] gfedcba;

    always @(*)
        case (state)
        2'b00:   gfedcba = 7'b0111111;  // 0
        2'b01:   gfedcba = 7'b0000110;  // 1
        2'b10:   gfedcba = 7'b1011011;  // 2
        default: gfedcba = 7'b1000000;  // never reached: a dash
        endcase

    assign uo_out  = { state [1], gfedcba };

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

    // 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>_snail_fsm
  source_files:
    - "project.v"
    - "snail_fsm.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 of the Habr article about the electronics course, which refers to the note “FSM using 3 gens”. The snail and its equations are from D. M. Harris and S. L. Harris, Digital Design and Computer Architecture; the same machine is lab 1_10_snail_fsm of Basics-Graphics-Music. The chips are described in the Texas Instruments datasheets for the CD4013B, CD4081B and CD4069UB.