Breadboard exercises/ BB8EnglishРусский

Exercise BB8 · building block · FIFO

40105 FIFO: a queue of 4-bit words

Put numbers into a queue with one button and take them out with another, in the same order. The 40105 holds sixteen words; a 4013 turns every press of PUSH and POP into one clean edge. FIFOs like this one connect the stages of every GPU, network chip and processor pipeline.

2 chips40105 FIFO, 4013 flip-flops
15 + 27 wireson the board + jumper leads to the modules
16 × 4words × bits; 3 bits used
~1 Hzfrom the 555 clock module

1What it is and why it matters

What it does. Hold some of the data buttons D2, D1, D0 to make a number from 0 to 7, and press PUSH: the number goes to the end of the queue. Press POP: the number at the head of the queue goes away, and the next one takes its place. The LED module shows DOR (data-out ready: the queue is not empty) on LED 1 and the head of the queue on LEDs 2–4. LED 8 is DIR (data-in ready: there is room for another word); it goes dark after sixteen words.

How it works. The 40105 is a FIFO, first in, first out: it gives the words back in the order they came in. A rising edge on its SI input (shift in) loads the data inputs, and a falling edge on SO (shift out) drops the word at the head. A button bounces, so a button wired straight to SI would load several words per press. Here the buttons go through the two D flip-flops of a 4013, clocked by the 555 module, as in exercise B4: Q1 rises once per press of PUSH and drives SI; ~Q2 falls once per press of POP and drives SO.

Where it is used. A FIFO connects two parts of a circuit that do not work in step: one part produces data when it can, the other consumes them when it can, and the FIFO holds what is in between. A UART such as the 16550 has a FIFO for each direction, network chips keep packets in FIFOs, and a processor pipeline has them between its stages. When a FIFO fills up, its DIR flag tells the producer to wait: this is called backpressure.

Why learn it.

2The key elements: first in, first out

A sequence of presses and what the LEDs show after each one:

PressQueue, head firstDOR (LED 1)Q2 Q1 Q0 (LEDs 2-4)DIR (LED 8)
RESETempty0—1
PUSH 221010 = 21
PUSH 52, 51010 = 21
PUSH 72, 5, 71010 = 21
POP5, 71101 = 51
PUSH 35, 7, 31101 = 51
POP7, 31111 = 71
POP31011 = 31
POPempty0—1
POP (ignored)empty0—1

A press acts at the first rising edge of the clock that sees the button at 1, so hold a button until the clock module blinks. The data buttons are read at the same edge, so hold them together with PUSH. Holding PUSH longer does not load the word twice: the 40105 waits for SI to go back to 0 before it takes another word.

Waveforms

CLKRSTPUSHDATA0257030SIPOPSODORHEAD2573DIRwords012323210
From the simulation of tb.sv in Icarus Verilog: the presses of the table above. SI rises at the first clock edge after PUSH goes to 1, SO falls at the first edge after POP goes to 1. words is the number of words in the reference model of the testbench. · SVG · PNG

3Parts

PartIn this circuitQtyPriceSupplier
CD74HC40105FIFO of sixteen 4-bit words; 3 bits used1$1.74ti.com
CD4013dual D flip-flop: one clean edge per press of PUSH and POP1$0.35Elexp (elexp.com)
Button modulesRESET, PUSH, POP and the data bits D2, D1, D0; the first pack of five5$0.66 / packaliexpress.us
Button modules1 more from the second pack1$2.03 / packaliexpress.us
555 clock modulethe clock, set to about 1 Hz1$0.53aliexpress.us
8-LED moduleDOR and the head of the queue on LEDs 1-4, DIR on LED 81$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 wires15 wires on the board (or male-male Dupont jumpers)15$11.95 / packjameco.com
Male-female Dupont jumpers27 leads to the clock module, the buttons and the LED module27$1.30 / packaliexpress.us

Prices from the LSSK components sheet; the 40105 and the 4013 are in the FIFO kit and in the Comprehensive 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.

40105: FIFO of sixteen 4-bit words

1OE2DIR3SI4D05D16D27D38GND9MR10Q311Q212Q113Q014DOR15SO16VCC4010516 × 4 FIFO
CD74HC40105. A 16-pin chip of the 74HC family: its supply pins are called VCC (pin 16) and GND (pin 8). · SVG · PNG

Data go in on D0–D3 (pins 4–7) and come out on Q0–Q3 (pins 13–10). SI (pin 3) loads on its rising edge; SO (pin 15) drops the head on its falling edge, marked by the small circle. DIR (pin 2) and DOR (pin 14) are the flags. MR (pin 9), master reset, is active high: here it comes from the RESET button. OE (pin 1) at GND keeps the outputs on. D3 is at GND, so the words are 0 to 7, and Q3 is not used.

Inside. The chip is a chain of sixteen places. A new word moves along the chain on its own until it reaches the last free place, which takes up to about half a microsecond at 5 V. This is why DIR drops for a moment after every load, and why the datasheet asks for a reset pulse on MR after power-up.

PinNameDirectionFunctionIn this circuit
1OEinputthree-state control: 0 turns Q0-Q3 on, 1 turns them offGND
2DIRoutputdata-in ready: 1 while there is room for a wordDIR
3SIinputa rising edge, 0 to 1, loads D0-D3 at the end of the queueSI
4D0inputdata input, bit 0D0
5D1inputdata input, bit 1D1
6D2inputdata input, bit 2D2
7D3inputdata input, bit 3GND
8GNDpowerground, 0 VGND
9MRinputmaster reset: 1 empties the queue at once, without SI or SO. Active highRST
10Q3outputthe word at the head of the queue, bit 3not connected
11Q2outputthe word at the head of the queue, bit 2Q2
12Q1outputthe word at the head of the queue, bit 1Q1
13Q0outputthe word at the head of the queue, bit 0Q0
14DORoutputdata-out ready: 1 while Q0-Q3 show a wordDOR
15SOinputa falling edge, 1 to 0, drops the word at the head; the next one moves upSO
16VCCpowersupply, +5 V (2 to 6 V allowed)+5V

4013: dual D flip-flop

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

As in exercise B4. Both flip-flops take their clock from the 555 module (pins 3 and 11) and their reset from the RESET button (pins 4 and 10). Flip-flop 1 samples PUSH (D1, pin 5), and its Q1 (pin 1) drives SI. Flip-flop 2 samples POP (D2, pin 9), and its inverted output ~Q2 (pin 12) drives SO: SO is 1 while POP is released and falls when the press is seen. The set inputs, pins 6 and 8, are at GND.

PinNameDirectionFunctionIn this circuit
1Q1outputflip-flop 1 outputSI
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 inputPUSH
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 inputPOP
10RESET2input1 sets Q2 = 0 at once. Active highRST
11CLOCK2inputflip-flop 2 stores D2 on the rising edgeCLK
12Q2outputflip-flop 2 output, invertedSO
13Q2outputflip-flop 2 outputnot connected
14VDDpowersupply, +5 V (3 to 18 V allowed)+5V

5Schematic 1: two flip-flops and a FIFO

CLKRESETPUSHPOPD2D1D0DRQ4013DRQ401340105SISOMRD2D1D0D3OEDORQ2Q1Q0DIRFIFO 16 × 4DORLED 1Q2LED 2Q1LED 3Q0LED 4DIRLED 8
The circuit as blocks. This is what fifo_demo.sv describes. The circle at SO marks the falling edge. · SVG · PNG

6Schematic 2: connections between the chips

12345678910111213141516OEDIRSID0D1D2D3MRQ3Q2Q1Q0DORSO4010516 × 4 FIFO1234567891011121314Q1Q1CLK1R1D1S1S2D2R2CLK2Q2Q240132 × D flip-flopCLKRSTPUSHPOPSISODORDIRD0D2D2D1D0PUSHPOPRESETclockLED module: LEDs 1, 2, 3, 4, 8+5V
The same circuit as chips, pin by pin. Both chips are turned around, notch on the right, as on the breadboard. · SVG · PNG
NetFromToWire
CLK555 clock module, OUT4013 3 (CLK1), 4013 11 (CLK2)M-F, M-M
RSTbutton RESET, OUT4013 4 (R1), 4013 10 (R2), 40105 9 (MR)M-F, M-M
PUSHbutton PUSH, OUT4013 5 (D1)M-F
POPbutton POP, OUT4013 9 (D2)M-F, M-M
SI4013 1 (Q1)40105 3 (SI)M-M
SO4013 12 (Q2)40105 15 (SO)M-M
D2button D2, OUT40105 6 (D2)M-F
D1button D1, OUT40105 5 (D1)M-F
D0button D0, OUT40105 4 (D0)M-F
DOR40105 14 (DOR)LED module, LED 1M-F
Q240105 11 (Q2)LED module, LED 2M-F
Q140105 12 (Q1)LED module, LED 3M-F
Q040105 13 (Q0)LED module, LED 4M-F
DIR40105 2 (DIR)LED module, LED 8M-F, M-M
+5V+5V40105 16 (VCC), 4013 14 (VDD)
GNDGND40105 8 (GND), 4013 7 (VSS), 40105 7 (D3), 40105 1 (OE), 4013 8 (S2), 4013 6 (S1)
not connected40105 10 (Q3), 4013 2 (Q1), 4013 13 (Q2)

7Schematic 3: the breadboard

−+−+123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263abcdefghij5V5VPOWER MODULE · 5V9V USB-DC401054013CLKRSTRSTSISO+OUT−D2+OUT−D1+OUT−D0+OUT−PUSH+OUT−POP+OUT−RESET−OUT+555CLOCK 555~1 HzG1DOR2Q23Q14Q05678DIR8-LED MODULELEDs 1, 2, 3, 4, 8 used
Every wire in its hole. Column numbers are printed along the top; rows a–e are above the gap, f–j below it. The six buttons and the clock module hang above the board, the LED module below it. · SVG · PNG
CLKRSTPUSHPOPSISOD2D1D0DORQ2Q1Q0DIR+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 40105 turned around, notch to the right, pin 1 in hole 14e; the 4013 turned around, notch to the right, pin 1 in hole 23e. 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 the 40105 these pins are called VCC and GND. 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: OE and D3 of the 40105 and the set inputs S1 and S2 of the 4013 to GND.
  5. The signal wires: the clock to both clock inputs of the 4013, RESET to R1, R2 and MR, Q1 to SI, ~Q2 to SO. Tick each wire as you insert it.
  6. With the power off, the modules: the three data buttons, PUSH, POP, RESET and the clock module above the board, the LED module below it.
  7. Turn the power on, set the clock module to about one blink per second, and press RESET once: the 40105 needs a reset after power-up.

Wiring checklist

·

#NetFromTo
Power (red to +, black to −) · 4 wires
1+5V14j (40105 pin 16, VCC)bottom + rail, column 14
2GND7a (40105 pin 8, GND)top − rail, column 7
3+5V23j (4013 pin 14, VDD)bottom + rail, column 23
4GND17a (4013 pin 7, VSS)top − rail, column 17
Fixed inputs: CMOS inputs must not float · 4 wires
5GND8a (40105 pin 7, D3)top − rail, column 8
6GND14a (40105 pin 1, OE)top − rail, column 14
7GND17j (4013 pin 8, S2)bottom − rail, column 17
8GND18a (4013 pin 6, S1)top − rail, column 18
Signal wires · 7 wires
9CLK21d (4013 pin 3, CLK1)20g (4013 pin 11, CLK2)
10RST20c (4013 pin 4, R1)19g (4013 pin 10, R2)
11RST19h (4013 pin 10, R2)7g (40105 pin 9, MR)
12POP18g (4013 pin 9, D2)16e
13SI23b (4013 pin 1, Q1)12b (40105 pin 3, SI)
14SO21h (4013 pin 12, Q2)13h (40105 pin 15, SO)
15DIR13d (40105 pin 2, DIR)15f
Modules on male-female jumpers · 27 wires
16+5Vbutton D2, +top + rail, column 5
17D2button D2, OUT9a (40105 pin 6, D2)
18GNDbutton D2, −top − rail, column 5
19+5Vbutton D1, +top + rail, column 10
20D1button D1, OUT10a (40105 pin 5, D1)
21GNDbutton D1, −top − rail, column 12
22+5Vbutton D0, +top + rail, column 17
23D0button D0, OUT11a (40105 pin 4, D0)
24GNDbutton D0, −top − rail, column 19
25+5Vbutton PUSH, +top + rail, column 24
26PUSHbutton PUSH, OUT19a (4013 pin 5, D1)
27GNDbutton PUSH, −top − rail, column 26
28+5Vbutton POP, +top + rail, column 31
29POPbutton POP, OUT16a
30GNDbutton POP, −top − rail, column 33
31+5Vbutton RESET, +top + rail, column 38
32RSTbutton RESET, OUT20a (4013 pin 4, R1)
33GNDbutton RESET, −top − rail, column 40
34GND555 clock module, −top − rail, column 45
35CLK555 clock module, OUT21a (4013 pin 3, CLK1)
36+5V555 clock module, +top + rail, column 47
37GNDLED module, Gbottom − rail, column 7
38DORLED module, LED 112j (40105 pin 14, DOR)
39Q2LED module, LED 29j (40105 pin 11, Q2)
40Q1LED module, LED 310j (40105 pin 12, Q1)
41Q0LED module, LED 411j (40105 pin 13, Q0)
42DIRLED module, LED 815j

Test it

If it does not work: if LED 1 never lights, check Q1 to SI and that MR is 0 while RESET is released. If a pop happens when you release POP rather than when you press it, SO is on Q2 (pin 13) instead of ~Q2 (pin 12). If the head shows the wrong number, check the order of the data buttons on D0–D2 and of LEDs 2–4 on Q2–Q0. If nothing happens at all, check the clock wire to both pins 3 and 11.

8SystemVerilog: the generic design

fifo_demo.sv keeps the words in an array of sixteen places with two counters, one for writing and one for reading. Each counter has one bit more than the address of a place: the counters are equal when the FIFO is empty and sixteen apart when it is full. This is how FIFOs are usually written in SystemVerilog; the 40105 inside is different, a chain through which the words ripple. The two flip-flops of the 4013 become push_q and pop_q. It is synthesizable and runs from one clock.

fifo_demo.svfile
// Exercise BB8: a FIFO of sixteen 3-bit words with a push and a pop button,
// like a 40105 with the two flip-flops of a 4013.
//
// Generic version that matches schematic 1, not tied to any chip.  Like the
// 4013, the design samples push and pop at the rising edge of clk, and it
// acts once per press: the first edge that sees push at 1 puts data at the
// end of the queue, the first edge that sees pop at 1 drops the word at the
// head.  head shows the oldest word while dor (data-out ready) is 1; dir
// (data-in ready) is 0 while all sixteen places are full.  A push into a
// full FIFO and a pop from an empty one are ignored.  rst empties the FIFO
// at once, without the clock.  Synthesizable.

module fifo_demo
(
    input  logic       clk,
    input  logic       rst,

    input  logic       push,
    input  logic       pop,
    input  logic [2:0] data,

    output logic [2:0] head,
    output logic       dor,    // data-out ready: the queue is not empty
    output logic       dir     // data-in ready: the queue is not full
);

    logic       push_q, pop_q;  // the buttons at the last clock edge

    // Write and read counters with one extra bit: equal when the queue is
    // empty, 16 apart when it is full

    logic [4:0] wr, rd;
    logic [2:0] word [0:15];

    wire do_push = push & ~ push_q & dir;
    wire do_pop  = pop  & ~ pop_q  & dor;

    always_ff @ (posedge clk or posedge rst)
        if (rst)
        begin
            push_q <= 1'b0;
            pop_q  <= 1'b0;
            wr     <= '0;
            rd     <= '0;
        end
        else
        begin
            push_q <= push;
            pop_q  <= pop;

            if (do_push)
                wr <= wr + 5'd1;

            if (do_pop)
                rd <= rd + 5'd1;
        end

    always_ff @ (posedge clk)
        if (do_push)
            word [wr [3:0]] <= data;

    assign dor  = wr != rd;
    assign dir  = wr != { ~ rd [4], rd [3:0] };
    assign head = word [rd [3: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.

The 40105 model leaves out the time a word takes to ripple through the chip, and two details of the datasheet: if SI rises while the FIFO is full, the chip loads the word as soon as a place frees, provided SI is still 1; and if SI is 1 at the end of a reset, the chip loads the data inputs. On the breadboard you can see the first one: hold PUSH on a full FIFO and press POP.

cd40105.svfile
// CD74HC40105: FIFO of sixteen 4-bit words.
//
// Ports in pin order, named as in the datasheet.  The power pins, GND (8)
// and VCC (16), are left out.
//
// A rising edge on SI (shift in) puts D0-D3 at the end of the queue while
// DIR (data-in ready) is 1; with all sixteen places full DIR is 0 and SI is
// ignored.  While DOR (data-out ready) is 1, Q0-Q3 show the word at the
// head of the queue; a falling edge on SO (shift out) drops it and the next
// word moves up.  With the queue empty DOR is 0 and SO is ignored.  MR
// (master reset) is active high and asynchronous: it empties the queue at
// once.  OE (three-state control) 1 turns Q0-Q3 off.
//
// The chip passes a word from place to place inside, so a word takes up to
// about half a microsecond at 5 V to reach the output, and DIR drops for a
// moment after every load.  The model leaves these delays out: a word is at
// the output right after the edge that loads it.  It also leaves out two
// details: if SI rises while the queue is full, the chip loads the word as
// soon as a place frees, if SI is still 1; and if SI is 1 at the end of MR,
// the chip loads D0-D3.  The model ignores both.
//
// Synthesizable, with SI and SO as two clocks.

module cd40105
(
    input  logic oe,   // Pin 1:  1 = Q0-Q3 off
    output logic dir,  // Pin 2:  1 = room for a word
    input  logic si,   // Pin 3:  rising edge = load
    input  logic d0,   // Pin 4
    input  logic d1,   // Pin 5
    input  logic d2,   // Pin 6
    input  logic d3,   // Pin 7
                       // Pin 8:  GND
    input  logic mr,   // Pin 9:  1 = empty the queue at once
    output logic q3,   // Pin 10
    output logic q2,   // Pin 11
    output logic q1,   // Pin 12
    output logic q0,   // Pin 13
    output logic dor,  // Pin 14: 1 = a word on Q0-Q3
    input  logic so    // Pin 15: falling edge = drop the head
                       // Pin 16: VCC
);

    logic [3:0] word [0:15];

    // Write and read counters with one extra bit: equal when the queue is
    // empty, 16 apart when it is full

    logic [4:0] wr, rd;

    always_ff @ (posedge si or posedge mr)
        if (mr)
            wr <= '0;
        else if (dir)
            wr <= wr + 5'd1;

    always_ff @ (posedge si)
        if (dir & ~ mr)
            word [wr [3:0]] <= { d3, d2, d1, d0 };

    always_ff @ (negedge so or posedge mr)
        if (mr)
            rd <= '0;
        else if (dor)
            rd <= rd + 5'd1;

    assign dor = wr != rd;
    assign dir = wr != { ~ rd [4], rd [3:0] };

    assign { q3, q2, q1, q0 } = oe ? 4'bz : word [rd [3:0]];

endmodule
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

10SystemVerilog: the chip-level design

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

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

module fifo_demo_chips
(
    input  logic       clk,
    input  logic       rst,
    input  logic       push,
    input  logic       pop,
    input  logic [2:0] data,
    output logic [2:0] head,
    output logic       dor,
    output logic       dir
);

    // Connections between the chips that are not ports

    wire si;
    wire so;

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

    wire gnd = 1'b0;

    // Outputs that go nowhere

    wire unused_u2_q3;
    wire unused_u1_q1_n;
    wire unused_u1_q2;

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

    // U2: CD74HC40105 FIFO of sixteen 4-bit words, pin 1 in column 7

    cd40105 i_u2
    (
        .oe  ( gnd          ),  // Pin 1 <- GND
        .dir ( dir          ),  // Pin 2 -> DIR
        .si  ( si           ),  // Pin 3 <- U1 pin 1 (Q1)
        .d0  ( data [0]     ),  // Pin 4 <- button D0
        .d1  ( data [1]     ),  // Pin 5 <- button D1
        .d2  ( data [2]     ),  // Pin 6 <- button D2
        .d3  ( gnd          ),  // Pin 7 <- GND
        .mr  ( rst          ),  // Pin 9 <- button RESET
        .q3  ( unused_u2_q3 ),  // Pin 10, unused output
        .q2  ( head [2]     ),  // Pin 11 -> Q2
        .q1  ( head [1]     ),  // Pin 12 -> Q1
        .q0  ( head [0]     ),  // Pin 13 -> Q0
        .dor ( dor          ),  // Pin 14 -> DOR
        .so  ( so           )   // Pin 15 <- U1 pin 12 (~Q2)
    );

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

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

    cd4013 i_u1
    (
        .q1     ( si             ),  // Pin 1 -> SI
        .q1_n   ( unused_u1_q1_n ),  // Pin 2, unused output
        .clock1 ( clk            ),  // Pin 3 <- 555 clock module
        .reset1 ( rst            ),  // Pin 4 <- button RESET
        .d1     ( push           ),  // Pin 5 <- button PUSH
        .set1   ( gnd            ),  // Pin 6 <- GND
        .set2   ( gnd            ),  // Pin 8 <- GND
        .d2     ( pop            ),  // Pin 9 <- button POP
        .reset2 ( rst            ),  // Pin 10 <- button RESET
        .clock2 ( clk            ),  // Pin 11 <- 555 clock module
        .q2_n   ( so             ),  // Pin 12 -> SO
        .q2     ( unused_u1_q2   )   // Pin 13, unused output
    );

endmodule

11Testbench and simulation scripts

tb.sv runs both designs side by side from the same clock and buttons and compares them with a reference model, a queue kept as an array with the head in place 0. Like the testbenches of Basics-Graphics-Music, it drives and checks signals only at rising clock edges. It plays the presses of section 2, fills the FIFO with eighteen pushes and empties it with seventeen pops, presses both buttons at once, makes 160 clocks of pseudo-random presses, resets in the middle and checks that reset acts at once. It changes the data only while PUSH is released, as you do on the breadboard: the 40105 reads the data at the very edge that loads them. The output below is shortened.

tb.sv305 lines · show the codefile
// Testbench for exercise BB8.
//
// Runs the generic design (fifo_demo.sv) and the chip-level design
// (fifo_demo_chips.sv) side by side and compares both with a reference
// model, a queue kept as an array with the head in place 0.  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 pushes and pops a few words,
// fills the FIFO beyond its sixteen places, empties it beyond the last
// word, presses both buttons at once, runs a stretch of pseudo-random
// presses, 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       push = 1'b0;
    logic       pop  = 1'b0;
    logic [2:0] data = '0;

    wire  [2:0] head, head_chips;
    wire        dor,  dor_chips;
    wire        dir,  dir_chips;

    fifo_demo i_generic
    (
        .clk  ( clk  ),
        .rst  ( rst  ),
        .push ( push ),
        .pop  ( pop  ),
        .data ( data ),
        .head ( head ),
        .dor  ( dor  ),
        .dir  ( dir  )
    );

    fifo_demo_chips i_chips
    (
        .clk  ( clk        ),
        .rst  ( rst        ),
        .push ( push       ),
        .pop  ( pop        ),
        .data ( data       ),
        .head ( head_chips ),
        .dor  ( dor_chips  ),
        .dir  ( dir_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.  A press is the first clock edge that sees the button
    // at 1.  A push into a full queue and a pop from an empty one do
    // nothing.  rst empties the queue at once.

    logic [2:0] model [0:15];  // model [0] is the head of the queue
    int         count;         // words in the queue
    logic       push_was, pop_was;

    wire pushed = push & ~ push_was;
    wire popped = pop  & ~ pop_was;

    wire model_push = pushed & count < 16;
    wire model_pop  = popped & count > 0;

    always @ (posedge clk or posedge rst)
        if (rst)
        begin
            count    <= 0;
            push_was <= 1'b0;
            pop_was  <= 1'b0;
        end
        else
        begin
            push_was <= push;
            pop_was  <= pop;

            if (model_pop)
                for (int k = 0; k < 15; k ++)
                    model [k] <= model [k + 1];

            // After the shift above, so that this write wins

            if (model_push)
                model [model_pop ? count - 1 : count] <= data;

            count <= count + (model_push ? 1 : 0) - (model_pop ? 1 : 0);
        end

    wire       dor_expected  = count > 0;
    wire       dir_expected  = count < 16;
    wire [2:0] head_expected = model [0];

    // The head is checked only while DOR is 1: an empty FIFO shows an old
    // word, or nothing at all after power-up

    wire ok_generic =    dor === dor_expected && dir === dir_expected
                      && (! dor_expected || head === head_expected);

    wire ok_chips   =    dor_chips === dor_expected && dir_chips === dir_expected
                      && (! dor_expected || head_chips === head_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;

    // What the run has seen: a full queue, a push into it, a pop from an
    // empty queue, and a push and a pop at the same edge

    logic seen_full = 1'b0, seen_push_full = 1'b0, seen_pop_empty = 1'b0, seen_both = 1'b0;

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

            seen_full      <= seen_full      | count == 16;
            seen_push_full <= seen_push_full | ~ rst & pushed & count == 16;
            seen_pop_empty <= seen_pop_empty | ~ rst & popped & count == 0;
            seen_both      <= seen_both      | ~ rst & model_push & model_pop;

            $display ("%5d  %b    %b     %b    %0d     %b    %b    %c     %2d    %s  %s",
                cycle + 1, rst, push, pop, data, dor, dir, dor ? 8'd48 + 8' (head) : 8'd45, count,
                ok_generic ? "ok     " : "WRONG  ", ok_chips ? "ok" : "WRONG");
        end
    end

    //------------------------------------------------------------------------
    // Asynchronous reset: right after rst rises, both FIFOs must be empty.

    int n_async = 0;

    always @ (posedge rst)
    begin
        # 1;

        if ({ dor, dir, dor_chips, dir_chips } !== 4'b0101)
        begin
            $display ("WRONG: reset did not act at once");
            n_errors <= n_errors + 1;
        end

        n_async <= n_async + 1;
    end

    //------------------------------------------------------------------------
    // Driving the inputs.
    //
    // As on the breadboard, the data bits change only while PUSH is
    // released.  The 40105 takes D0-D2 at the very edge that loads them, one
    // clock after PUSH is pressed, so data that changed at that edge would
    // make a race in the simulation, and a wrong word on the breadboard.

    // One press: hold the buttons for a number of clock edges, then release
    // them for one edge, so that the next press is a new one

    task automatic press (input logic push_on, input logic pop_on, input logic [2:0] value, input int edges);
        data <= value;
        push <= push_on;
        pop  <= pop_on;
        repeat (edges) @ (posedge clk);
        push <= 1'b0;
        pop  <= 1'b0;
        @ (posedge clk);
    endtask

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

    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  push  pop  data  DOR  DIR  head  words  generic  chips");

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

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

        // The example of section 2: push 2, 5, 7, pop, push 3, pop four
        // times, the last time from an empty queue.  Some presses are long.

        press (1, 0, 2, 1);
        press (1, 0, 5, 3);
        press (1, 0, 7, 2);
        press (0, 1, 0, 1);
        press (1, 0, 3, 1);
        repeat (4) press (0, 1, 0, 2);

        // Eighteen pushes: the last two find the FIFO full

        for (int k = 0; k < 18; k ++)
            press (1, 0, 3' (k), 1);

        // Both buttons at once: on a full FIFO only the pop works, with one
        // place free both work

        press (1, 1, 6, 1);
        press (1, 1, 5, 1);

        // Empty it, and two pops more

        repeat (17) press (0, 1, 0, 1);

        // Pseudo-random presses, the same in every simulator.  The data
        // change only while push is 0 at this edge.

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

            if (! push)
                data <= seed [26:24];

            push <= seed [29] & seed [28];
            pop  <= seed [31] & (seed [30] | seed [27]);

            @ (posedge clk);
        end

        push <= 1'b0;
        pop  <= 1'b0;
        @ (posedge clk);

        // Reset in the middle, with words in the queue

        press (1, 0, 1, 1);
        press (1, 0, 4, 1);
        rst <= 1'b1;
        @ (posedge clk);
        rst <= 1'b0;
        @ (posedge clk);

        press (1, 0, 6, 1);
        press (0, 1, 0, 1);
        press (0, 1, 0, 1);

        // 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 && seen_full && seen_push_full && seen_pop_empty && seen_both && n_async >= 2)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, seen full %b, push full %b, pop empty %b, both %b, %0d resets",
                      n_errors, n_checks, seen_full, seen_push_full, seen_pop_empty, seen_both, 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 BB8: 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 fifo_demo.sv fifo_demo_chips.sv cd40105.sv cd4013.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 BB8: 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 fifo_demo.sv fifo_demo_chips.sv cd40105.sv cd4013.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 BB8: 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 fifo_demo.sv fifo_demo_chips.sv cd40105.sv cd4013.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  push  pop  data  DOR  DIR  head  words  generic  chips
    1  1    0     0    0     0    1    -      0    ok          ok
    2  1    0     0    0     0    1    -      0    ok          ok
    3  0    1     0    2     0    1    -      0    ok          ok
    4  0    0     0    2     1    1    2      1    ok          ok
    5  0    1     0    5     1    1    2      1    ok          ok
    6  0    1     0    5     1    1    2      2    ok          ok
    7  0    1     0    5     1    1    2      2    ok          ok
    8  0    0     0    5     1    1    2      2    ok          ok
    9  0    1     0    7     1    1    2      2    ok          ok
   10  0    1     0    7     1    1    2      3    ok          ok
   11  0    0     0    7     1    1    2      3    ok          ok
   12  0    0     1    0     1    1    2      3    ok          ok
   13  0    0     0    0     1    1    5      2    ok          ok
   14  0    1     0    3     1    1    5      2    ok          ok
   15  0    0     0    3     1    1    5      3    ok          ok
   16  0    0     1    0     1    1    5      3    ok          ok
   17  0    0     1    0     1    1    7      2    ok          ok
   18  0    0     0    0     1    1    7      2    ok          ok
   19  0    0     1    0     1    1    7      2    ok          ok
   20  0    0     1    0     1    1    3      1    ok          ok
   21  0    0     0    0     1    1    3      1    ok          ok
   22  0    0     1    0     1    1    3      1    ok          ok
   23  0    0     1    0     0    1    -      0    ok          ok
   24  0    0     0    0     0    1    -      0    ok          ok
   25  0    0     1    0     0    1    -      0    ok          ok
   26  0    0     1    0     0    1    -      0    ok          ok
   27  0    0     0    0     0    1    -      0    ok          ok
   28  0    1     0    0     0    1    -      0    ok          ok
  …
  273  0    0     1    0     0    1    -      0    ok          ok
  274  0    0     0    0     0    1    -      0    ok          ok
tb.sv:291: $finish called at 2765000 (1ps)
PASS: 548 checks, no errors

To see that the testbench catches mistakes, break something and run it again: delete ~ push_q & in fifo_demo.sv, so that a long press pushes at every clock, or drive SO from Q2 instead of ~Q2 in fifo_demo_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_07_shift_register to a new directory.
  2. Replace its lab_top.sv with bgm_lab/lab_top.sv from this exercise and add fifo_demo.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.

Switches 2–0 are the data, key 0 is PUSH and key 1 is POP: hold the key until the next tick of slow_clk. LEDs 2–0 show the head of the queue, LED 3 DOR and LED 7 DIR. The rightmost digit shows the head as a number while the FIFO is not empty, and its dot lights while the FIFO is full. To run the chip-level design instead, add fifo_demo_chips.sv, cd4013.sv and cd40105.sv and change the module name in the instance. In that design SI and SO become clocks made by flip-flops; at 1 Hz that works, but in a real FPGA design every flip-flop takes the same clock, as in fifo_demo.sv.

bgm_lab/lab_top.sv124 lines · show the codefile
// Exercise BB8 on an FPGA board with the Basics-Graphics-Music (BGM) labs:
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy labs/1_basics/1_07_shift_register to a new directory, replace its
// lab_top.sv with this file and add fifo_demo.sv.  For the chip-level design
// add fifo_demo_chips.sv, cd4013.sv and cd40105.sv instead, and change the
// module name below.
//
// The FIFO runs from slow_clk, 1 Hz on every BGM board, and rst is the
// reset of the board.  Switches 2-0 are the data, key 0 is PUSH and key 1
// is POP: hold a key until the next tick of slow_clk.  LEDs 2-0 show the
// head of the queue, LED 3 DOR and LED 7 DIR.  The rightmost digit shows
// the head as a number while the FIFO is not empty; its dot lights while
// the FIFO is full.

`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 [2:0] head;
    logic       dor, dir;

    fifo_demo i_fifo_demo
    (
        .clk  ( slow_clk  ),
        .rst  ( rst       ),
        .push ( key [0]   ),
        .pop  ( key [1]   ),
        .data ( sw  [2:0] ),
        .head ( head      ),
        .dor  ( dor       ),
        .dir  ( dir       )
    );

    assign led = w_led' ({ dir, 3'b0, dor, head });

    // The head as a digit, dark while the FIFO is empty

    logic [6:0] abcdefg;

    always_comb
        if (~ dor)
            abcdefg = 7'b0000000;
        else
            case (head)
            3'd0: abcdefg = 7'b1111110;
            3'd1: abcdefg = 7'b0110000;
            3'd2: abcdefg = 7'b1101101;
            3'd3: abcdefg = 7'b1111001;
            3'd4: abcdefg = 7'b0110011;
            3'd5: abcdefg = 7'b1011011;
            3'd6: abcdefg = 7'b1011111;
            3'd7: abcdefg = 7'b1110000;
            endcase

    assign abcdefgh = { abcdefg, ~ dir };
    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/5_shift_register.
  2. Replace its hackathon_top.sv with bgm_hackathon/hackathon_top.sv and add fifo_demo.sv.
  3. Run ./03_synthesize_for_fpga.bash and ./04_configure_fpga.bash.

Keys 7–5 are the data, key 1 is PUSH and key 0 is POP: hold the data keys, then hold PUSH until the next tick of slow_clock. The screen shows five lamps: DOR, the three bits of the head and DIR. The LEDs and the rightmost digit are as in lab_top.

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

// Exercise BB8 in the hackathon setup of Basics-Graphics-Music (BGM):
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy a directory such as hackathon/problems/5_shift_register, replace its
// hackathon_top.sv with this file and add fifo_demo.sv.
//
// The FIFO runs from slow_clock.  Keys 7-5 are the data, key 1 is PUSH and
// key 0 is POP: hold the data keys, then hold PUSH until the next tick of
// slow_clock.  The LEDs and the rightmost digit are as in lab_top.  The
// screen shows five lamps: DOR, the three bits of the head and DIR.

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 [2:0] head;
    logic       dor, dir;

    fifo_demo i_fifo_demo
    (
        .clk  ( slow_clock ),
        .rst  ( reset      ),
        .push ( key [1]    ),
        .pop  ( key [0]    ),
        .data ( key [7:5]  ),
        .head ( head       ),
        .dor  ( dor        ),
        .dir  ( dir        )
    );

    assign led = { dir, 3'b0, dor, head };

    // The head as a digit, dark while the FIFO is empty

    logic [6:0] abcdefg;

    always_comb
        if (~ dor)
            abcdefg = 7'b0000000;
        else
            case (head)
            3'd0: abcdefg = 7'b1111110;
            3'd1: abcdefg = 7'b0110000;
            3'd2: abcdefg = 7'b1101101;
            3'd3: abcdefg = 7'b1111001;
            3'd4: abcdefg = 7'b0110011;
            3'd5: abcdefg = 7'b1011011;
            3'd6: abcdefg = 7'b1011111;
            3'd7: abcdefg = 7'b1110000;
            endcase

    assign abcdefgh = { abcdefg, ~ dir };
    assign digit    = 8'b0000_0001;

    //------------------------------------------------------------------------
    // Five square lamps on the 480 x 272 screen, left to right: DOR in
    // magenta, Q2, Q1, Q0 in cyan, DIR in orange.  Bright for 1, dim for 0;
    // the head is dark while the FIFO is empty.

    wire [4:0] lamp = { dir, head & { 3 { dor } }, dor };

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

        for (int i = 0; i < 5; i ++)
            if (x >= 9' (80 + i * 70) & x < 9' (130 + i * 70) & y >= 111 & y < 161)
            begin
                if (i == 0)
                begin
                    red   = lamp [0] ? 31 : 6;
                    blue  = lamp [0] ? 16 : 3;
                end
                else if (i < 4)
                begin
                    green = lamp [4 - i] ? 50 : 10;
                    blue  = lamp [4 - i] ? 31 : 6;
                end
                else
                begin
                    red   = lamp [4] ? 31 : 6;
                    green = lamp [4] ? 36 : 7;
                end
            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 FIFO, just as the 555 module clocks the chips on the breadboard.

DIP switches 0–2 are the data, switch 3 is PUSH and switch 4 is POP: turn the switch on, wait for a tick of the clock, and turn it off again. The display shows the head as a digit while the FIFO is not empty, and its dot lights while it is full. DIR, DOR and the head also go to the BIDIR Pmod. The reset button of the demo board empties the FIFO.

tiny_tapeout/project.v75 lines · show the codefile
/*
 * Exercise BB8 on Tiny Tapeout: a FIFO of sixteen 3-bit words with a push
 * and a pop input.  The 7-segment display of the demo board shows the head
 * of the queue, and DOR, DIR and the head go to the BIDIR Pmod.
 *
 * Add fifo_demo.sv to source_files in info.yaml next to project.v.
 * Rename the module to tt_um_<your GitHub name>_<project name> and use the
 * same name as top_module in info.yaml.
 */

`default_nettype none

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

    // The demo board makes the project clock; set it to 1 Hz.  The reset
    // button of the board empties the FIFO.  DIP switches 0-2 are the data,
    // switch 3 is PUSH and switch 4 is POP: turn the switch on, wait for a
    // tick of the clock, and turn it off again.

    wire [2:0] head;
    wire       dor, dir;

    fifo_demo i_fifo_demo (
        .clk  ( clk         ),
        .rst  ( ~ rst_n     ),
        .push ( ui_in [3]   ),
        .pop  ( ui_in [4]   ),
        .data ( ui_in [2:0] ),
        .head ( head        ),
        .dor  ( dor         ),
        .dir  ( dir         )
    );

    // 7-segment display: uo_out [0] is segment a, ..., uo_out [6] is g,
    // uo_out [7] is the dot.  The head as a digit, dark while the FIFO is
    // empty; the dot lights while the FIFO is full.

    reg [6:0] gfedcba;

    always @(*)
        if (~ dor)
            gfedcba = 7'b0000000;
        else
            case (head)
            3'd0: gfedcba = 7'b0111111;
            3'd1: gfedcba = 7'b0000110;
            3'd2: gfedcba = 7'b1011011;
            3'd3: gfedcba = 7'b1001111;
            3'd4: gfedcba = 7'b1100110;
            3'd5: gfedcba = 7'b1101101;
            3'd6: gfedcba = 7'b1111101;
            3'd7: gfedcba = 7'b0000111;
            endcase

    assign uo_out  = { ~ dir, gfedcba };

    // DIR, DOR and the head on the BIDIR Pmod, for LEDs or a logic analyzer

    assign uio_out = { dir, 3'b0, dor, head };
    assign uio_oe  = 8'hff;

    // List all unused inputs to prevent warnings

    wire _unused = & { ena, ui_in [7:5], 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>_fifo_demo
  source_files:
    - "project.v"
    - "fifo_demo.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 Building blocks list of “An improved way of teaching school kids digital electronics” and in lesson 1.5 of the Habr article about the electronics course. Pictures 9 and 10 of “Teaching children electronics is due for a major redesign” show the FIFO demo Maya Grigoryeva built with a 40105. The chips are described in the Texas Instruments datasheets for the CD74HC40105 and the CD4013B.