Breadboard exercises/ B6EnglishРусский

Exercise B6 · basics · shift register

Shift register: serial in, parallel out

Press the D button during one blink of the clock and a lit LED appears on the left of the LED module; at every following blink it moves one LED to the right, until it falls off the end after eight. A 4015 holds the last eight bits you entered, one per clock period, and shows all of them at once.

1 chip4015, both 4-bit halves joined into 8 bits
9 + 18 wireson the board + jumper leads to the modules
8 bitsQ1 newest, Q8 oldest
~1 Hz clockfrom the 555 module, no clock circuit to build

1What it is and why it matters

What it does. A shift register is a chain of D flip-flops on one clock: at each rising edge, every flip-flop takes the value of the one before it, and the first takes the serial input. Bits enter one at a time and come out side by side: serial in, parallel out (SIPO). The 4015 has two 4-bit registers; connecting the last stage of the first (Q4A) to the input of the second (DATA B) makes one 8-bit register. The button gives the serial input D, the clock module the clock, another button the reset, and the LED module shows all eight stages. This is the fourth exercise of the Basics list in “An improved way of teaching school kids digital electronics”: “Demo 4015, a serial-to-parallel (SiPo – serial input / parallel output) shift register”; in lesson 1.3 of the Habr article half of the class enters bits with a button and watches the LEDs.

How it works. Hold D during a blink and Q1 becomes 1 at the edge. At the next edge Q1 passes its 1 to Q2 and takes the new value of D, and so on. What you see on the LEDs is the history of the button: Q1 is what D was one clock ago, Q8 what it was eight clocks ago.

Where it is used. Wherever bits travel one at a time: a serial port, SPI, USB and Ethernet receive bits on one wire and turn them into bytes with a shift register; a chip with few pins reads a long configuration word bit by bit. Shift registers also delay signals by a fixed number of clocks, make pseudo-random numbers (with a little XOR feedback), and become the Johnson counter inside the 4017 of exercise M11. The bit-serial adder project of the course uses a 4015 to collect the sum bits.

Why learn it.

2The key element: a chain of flip-flops

D flip-flop with reset

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

Each stage is one of these. Q takes the value of D at the rising edge; the reset clears it at once.

Four clock edges, the input 1, 0, 1, 1

After a reset all stages are 0. Each row is one rising edge: D comes in at Q1 and everything moves one place to the right.

edgeDQ1Q2Q3Q4Q5Q6Q7Q8
000000000
1110000000
2001000000
3110100000
4111010000

Why does a bit move only one place per edge, and not all the way through? Because all flip-flops sample their inputs at the same instant, the rising edge, and change only after it. Q2 takes the value Q1 had before the edge. In SystemVerilog the non-blocking assignment <= says exactly this.

Waveforms

clkrstDQ1Q2Q3Q4Q5Q6Q7Q8
From the simulation of tb.sv in Icarus Verilog. Dotted lines are the rising edges of the clock. Each bit of D appears on Q1 at the next edge and moves down one row per edge, Q1 to Q8. After 20 bits a reset clears all eight stages at once. · SVG · PNG

3Parts

PartIn this circuitQtyPriceSupplier
CD4015dual 4-bit shift register: both halves, joined into 8 bits1$0.35Elexp (elexp.com)
555 clock modulethe clock, set to about 1 Hz1$0.53aliexpress.us
Button modulesD and reset; two modules from the pack of five2$0.66 / packaliexpress.us
8-LED moduleshows all eight bits1$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
Male-male Dupont jumpers9 wires on the board (or pre-cut wires)9$1.30 / packaliexpress.us
Male-female Dupont jumpers18 leads to the modules18$1.30 / packaliexpress.us

Prices from the LSSK components sheet; all of these parts are in the Basics kit. The 4015 needs no tie-off wires: all its inputs are used.

Hold the button for a whole blink. The register samples D at the rising edge only. A press that starts after an edge and ends before the next one is never seen, as in exercise B4. Set the clock slow and hold D across a blink of the clock module's LED.

4The chip, pin by pin

The 4015 is CMOS 4000B series: it works 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; here every input is used, so there is nothing to tie off. The drawing shows the chip from above, the way it sits on the breadboard: notch on the left, pin 1 at the bottom left, pins numbered counter-clockwise. Blue arrows are inputs, orange arrows are outputs.

4015: dual 4-stage shift register

1CLKB2Q4B3Q3A4Q2A5Q1A6RA7DA8VSS9CLKA10Q4A11Q3B12Q2B13Q1B14RB15DB16VDD40152 × 4-bit shift register
CD4015B. The triangles at CLOCK A and CLOCK B mark edge-triggered inputs. · SVG · PNG

Polarity. Each register shifts on the rising edge of its CLOCK. RESET is active high and asynchronous: while it is 1, all four stages of that register are 0. All outputs are active high.

The pins of the two registers are mixed over both rows: register A has its outputs Q1A–Q3A at the bottom and Q4A at the top, register B the other way round. That is why the breadboard needs wires from the top row to the bottom half for the LED module.

PinNameDirectionFunctionIn this circuit
1CLOCK Binputregister B shifts on the rising edgeCLK
2Q4Boutputregister B, stage 4 (the oldest bit)Q8
3Q3Aoutputregister A, stage 3Q3
4Q2Aoutputregister A, stage 2Q2
5Q1Aoutputregister A, stage 1 (the newest bit)Q1
6RESET Ainput1 clears register A at once, without the clock. Active highRST
7DATA Ainputregister A, serial inputD
8VSSpowerground, 0 VGND
9CLOCK Ainputregister A shifts on the rising edgeCLK
10Q4Aoutputregister A, stage 4 (the oldest bit)Q4
11Q3Boutputregister B, stage 3Q7
12Q2Boutputregister B, stage 2Q6
13Q1Boutputregister B, stage 1Q5
14RESET Binput1 clears register B at once. Active highRST
15DATA Binputregister B, serial inputQ4
16VDDpowersupply, +5 V (3 to 18 V allowed)+5V

5Schematic 1: eight flip-flops

4015, REGISTER A4015, REGISTER BD~1 HzRDQRFF1Q1DQRFF2Q2DQRFF3Q3DQRFF4Q4DQRFF5Q5DQRFF6Q6DQRFF7Q7DQRFF8Q8clkrstd
The circuit without the chip: eight D flip-flops in a chain with a common clock and a common reset. The first four are register A of the 4015, the last four register B. This is what shift_register.sv describes. · SVG · PNG

The output of each flip-flop is the input of the next one and also drives an LED. The wire from FF4 to FF5 is the one wire on the breadboard that joins the two halves of the chip, from Q4A to DATA B.

6Schematic 2: connections of the chip

12345678910111213141516CLKBQ4BQ3AQ2AQ1ARADACLKAQ4AQ3BQ2BQ1BRBDB40152 × 4-bit shift registerRSTDQ2Q3Q4Q5Q6Q7Q8clockresetbutton DLEDs 1-8+5V
The same circuit as a chip, pin by pin. The chip is drawn from above with the notch on the left; pin numbers are next to the pins. The boxes are the modules. · SVG · PNG

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

NetFromToWire
CLK555 clock module, OUT4015 9 (CLKA), 4015 1 (CLKB)M-F, M-M
RSTreset button, OUT4015 6 (RA), 4015 14 (RB)M-F, M-M
Dbutton D, OUT4015 7 (DA)M-F
Q14015 5 (Q1A)LED module, LED 1M-F
Q24015 4 (Q2A)LED module, LED 2M-F
Q34015 3 (Q3A)LED module, LED 3M-F
Q44015 10 (Q4A)4015 15 (DB), LED module, LED 4M-F, M-M
Q54015 13 (Q1B)LED module, LED 5M-F, M-M
Q64015 12 (Q2B)LED module, LED 6M-F, M-M
Q74015 11 (Q3B)LED module, LED 7M-F, M-M
Q84015 2 (Q4B)LED module, LED 8M-F
+5V+5V4015 16 (VDD)
GNDGND4015 8 (VSS)

7Schematic 3: the breadboard

−+−+1234567891011121314151617181920212223242526272829303132333435363738394041424344abcdefghij5V5VPOWER MODULE · 5V9V USB-DC4015CLKRSTQ4Q4Q5Q6Q7−OUT+555CLOCK 555~1 Hz+OUT−RESETbutton+OUT−BUTTON DG1Q12Q23Q34Q45Q56Q67Q78Q88-LED MODULEQ1 … Q8
Every wire in its hole. Column numbers are printed along the top; rows a–e are above the gap, f–j below it. The clock module hangs above the board, the buttons and the LED module below it. The clock and the reset each need a wire across the gap, because CLOCK A and RESET B are on the top row and CLOCK B and RESET A on the bottom row. Four more wires bring Q4A, Q1B, Q2B and Q3B down for the LED module. The board goes on to column 63 on the right. · SVG · PNG
CLKRSTDQ1Q2Q3Q4Q5Q6Q7Q8+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 4015 across the gap, notch to the left, pin 1 in hole 18f.
  3. Power: a red wire from pin 16 to the top + rail, a black wire from pin 8 to the bottom − rail.
  4. The cascade wire from Q4A (pin 10) to DATA B (pin 15), then the clock wire from CLOCK A to CLOCK B and the reset wire from RESET A to RESET B.
  5. The four wires that bring Q4A, Q1B, Q2B and Q3B down to columns 15, 28, 29 and 30.
  6. With the power off, the modules: the clock module above the board, the reset button, button D and the LED module below. Connect − and G first.
  7. Turn the power on and set the clock module to about 1 Hz.

Wiring checklist

·

#NetFromTo
Power (red to +, black to −) · 2 wires
1+5V18a (4015 pin 16, VDD)top + rail, column 18
2GND25j (4015 pin 8, VSS)bottom − rail, column 25
Signal wires · 7 wires
3CLK25d (4015 pin 9, CLKA)18g (4015 pin 1, CLKB)
4RST23g (4015 pin 6, RA)20c (4015 pin 14, RB)
5Q424d (4015 pin 10, Q4A)19d (4015 pin 15, DB)
6Q419c (4015 pin 15, DB)15f
7Q521c (4015 pin 13, Q1B)28f
8Q622b (4015 pin 12, Q2B)29f
9Q723a (4015 pin 11, Q3B)30f
Modules on male-female jumpers · 18 wires
10GND555 clock module, −top − rail, column 25
11CLK555 clock module, OUT25a (4015 pin 9, CLKA)
12+5V555 clock module, +top + rail, column 27
13+5Vreset button, +bottom + rail, column 8
14RSTreset button, OUT23j (4015 pin 6, RA)
15GNDreset button, −bottom − rail, column 10
16+5Vbutton D, +bottom + rail, column 13
17Dbutton D, OUT24j (4015 pin 7, DA)
18GNDbutton D, −bottom − rail, column 15
19GNDLED module, Gbottom − rail, column 22
20Q1LED module, LED 122j (4015 pin 5, Q1A)
21Q2LED module, LED 221j (4015 pin 4, Q2A)
22Q3LED module, LED 320j (4015 pin 3, Q3A)
23Q4LED module, LED 415j
24Q5LED module, LED 528j
25Q6LED module, LED 629j
26Q7LED module, LED 730j
27Q8LED module, LED 819j (4015 pin 2, Q4B)

Test it

If it does not work: if the light stops at LED 4, the cascade wire from Q4A to DATA B is missing or in the wrong hole. If LEDs 5–8 never light but 1–4 work, check the clock wire to CLOCK B (pin 1) and RESET B (pin 14). If the order of the LEDs is mixed up, compare the LED leads with the checklist: the outputs of the 4015 are not in pin order.

8SystemVerilog: the generic design

shift_register.sv describes schematic 1. The concatenation { q [6:0], d } is the whole chain: bits 6 to 0 move up to 7 to 1, and d comes in at bit 0. With the non-blocking <=, all eight bits change together at the edge. It is synthesizable: eight flip-flops and no gates.

shift_register.svfile
// Exercise B6: an 8-bit shift register, serial input, parallel output.
//
// Generic version that matches schematic 1: eight D flip-flops in a chain,
// with a common clock and an asynchronous reset, not tied to any chip.
// Synthesizable.

module shift_register
(
    input  logic       clk,
    input  logic       rst,  // 1 = all bits go to 0 at once, like RESET A and B of the 4015
    input  logic       d,    // The serial input

    output logic [7:0] q     // q [0] is the newest bit, q [7] the oldest
);

    // Every clock the bits move one place up and d comes in at the bottom

    always_ff @ (posedge clk or posedge rst)
        if (rst)
            q <= '0;
        else
            q <= { q [6:0], d };

endmodule

9SystemVerilog model of the chip

One module with ports named as in the datasheet and the pin number of each port in a comment. The model is synthesizable; it leaves out the power pins, because in SystemVerilog a wire simply has the value 0 or 1.

cd4015.svfile
// CD4015B: dual 4-stage shift register, serial input, parallel output.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (8)
// and VDD (16), are left out.  Synthesizable.
//
// Each register shifts on the rising edge of its clock: DATA goes into Q1,
// Q1 into Q2, Q2 into Q3, Q3 into Q4.  RESET is active high and
// asynchronous: it clears all four stages at once, without the clock.
// Connect Q4A to DATA B to make one 8-stage register.

module cd4015
(
    input  logic clock_b,  // Pin 1
    output logic q4b,      // Pin 2
    output logic q3a,      // Pin 3
    output logic q2a,      // Pin 4
    output logic q1a,      // Pin 5
    input  logic reset_a,  // Pin 6:  1 = Q1A-Q4A go to 0 at once
    input  logic data_a,   // Pin 7
                           // Pin 8:  VSS
    input  logic clock_a,  // Pin 9
    output logic q4a,      // Pin 10
    output logic q3b,      // Pin 11
    output logic q2b,      // Pin 12
    output logic q1b,      // Pin 13
    input  logic reset_b,  // Pin 14: 1 = Q1B-Q4B go to 0 at once
    input  logic data_b    // Pin 15
                           // Pin 16: VDD
);

    logic [4:1] ra, rb;  // ra [1] is Q1A, ra [4] is Q4A

    always_ff @ (posedge clock_a or posedge reset_a)
        if (reset_a)
            ra <= '0;
        else
            ra <= { ra [3:1], data_a };

    always_ff @ (posedge clock_b or posedge reset_b)
        if (reset_b)
            rb <= '0;
        else
            rb <= { rb [3:1], data_b };

    assign { q4a, q3a, q2a, q1a } = ra;
    assign { q4b, q3b, q2b, q1b } = rb;

endmodule

10SystemVerilog: the chip-level design

shift_register_chips.sv connects the chip model exactly as schematic 2 and the breadboard connect the chip, with the same ports as shift_register.sv. Q4A drives both q [3] and DATA B, as on the breadboard. 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.

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

module shift_register_chips
(
    input  logic       clk,
    input  logic       rst,
    input  logic       d,
    output logic [7:0] q
);



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

    // U1: CD4015 dual 4-stage shift register, serial in, parallel out, pin 1 in column 18

    cd4015 i_u1
    (
        .clock_b ( clk   ),  // Pin 1 <- 555 clock module
        .q4b     ( q [7] ),  // Pin 2 -> Q8
        .q3a     ( q [2] ),  // Pin 3 -> Q3
        .q2a     ( q [1] ),  // Pin 4 -> Q2
        .q1a     ( q [0] ),  // Pin 5 -> Q1
        .reset_a ( rst   ),  // Pin 6 <- reset button
        .data_a  ( d     ),  // Pin 7 <- button D
        .clock_a ( clk   ),  // Pin 9 <- 555 clock module
        .q4a     ( q [3] ),  // Pin 10 -> Q4
        .q3b     ( q [6] ),  // Pin 11 -> Q7
        .q2b     ( q [5] ),  // Pin 12 -> Q6
        .q1b     ( q [4] ),  // Pin 13 -> Q5
        .reset_b ( rst   ),  // Pin 14 <- reset button
        .data_b  ( q [3] )   // Pin 15 <- U1 pin 10 (Q4A)
    );

endmodule

11Testbench and simulation scripts

tb.sv runs both designs side by side from the same clock and reset and compares them with a reference model: the last eight values of d, one per clock edge since the last reset. Like the testbenches of Basics-Graphics-Music, it drives and checks signals only at rising clock edges. It shifts in a 28-bit pattern, as if you pressed the button during some clock periods and not others, and resets the register after 20 bits: both designs must clear at once, not at the next edge. At the end it prints PASS or FAIL.

tb.sv182 lines · show the codefile
// Testbench for exercise B6.
//
// Runs the generic design (shift_register.sv) and the chip-level design
// (shift_register_chips.sv) side by side and compares both with a reference
// model.  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 shifts in a bit pattern, checks
// that every bit comes out of q [k] k + 1 clock edges after it went in, and
// resets the register in the middle of the run.

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

    wire  [7:0] q, q_chips;

    shift_register i_generic
    (
        .clk ( clk ),
        .rst ( rst ),
        .d   ( d   ),
        .q   ( q   )
    );

    shift_register_chips i_chips
    (
        .clk ( clk     ),
        .rst ( rst     ),
        .d   ( d       ),
        .q   ( q_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 last eight values of d, one per clock edge since
    // the last reset, the newest at the bottom.  q [k] must equal the bit
    // that came in k + 1 edges ago.

    logic [7:0] history;
    int          n_in;  // Bits shifted in since the last reset

    always @ (posedge clk or posedge rst)
        if (rst)
        begin
            history <= '0;
            n_in    <= 0;
        end
        else
        begin
            history <= { history [6:0], d };
            n_in    <= n_in + 1;
        end

    wire [7:0] q_expected = history [7:0];

    //------------------------------------------------------------------------
    // 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 max_in   = 0;        // The longest run without a reset

    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 + (q === q_expected ? 0 : 1) + (q_chips === q_expected ? 0 : 1);
            max_in   <= n_in > max_in ? n_in : max_in;

            $display ("%5d  %b   %b   %b   %s  %s",
                cycle + 1, rst, d, q,
                q       === q_expected ? "ok     " : "WRONG  ",
                q_chips === q_expected ? "ok   "   : "WRONG");
        end
    end

    //------------------------------------------------------------------------
    // Driving the inputs: a pattern of bits, one per clock, as if you pressed
    // the D button during some clock periods and not during others

    localparam n_bits = 28;

    wire [n_bits - 1:0] pattern = 28'b1011_0011_1000_0110_1111_0100_1101;  // From the left

    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  d   q [7:0]    generic  chips");

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

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

        for (int i = 0; i < n_bits; i ++)
        begin
            d <= pattern [n_bits - 1 - i];
            @ (posedge clk);

            // Reset in the middle of the run.  Both designs must clear at
            // once, not at the next clock edge, like RESET of the 4015.

            if (i == 19)
            begin
                rst <= '1;
                @ (posedge clk);
                rst <= '0;
            end
        end

        d <= '0;
        repeat (4) @ (posedge clk);

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

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

        $finish;
    end

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

    final
    begin
        if (n_errors == 0 && max_in >= 16)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, longest run %0d bits", n_errors, n_checks, max_in);
    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 B6: 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 shift_register.sv shift_register_chips.sv cd4015.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 B6: 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 shift_register.sv shift_register_chips.sv cd4015.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 B6: 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 shift_register.sv shift_register_chips.sv cd4015.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; q [7:0] is printed with Q8 on the left, so the bits move left in the trace:

VCD info: dumpfile tb.vcd opened for output.
cycle  rst  d   q [7:0]    generic  chips
    1  1   0   00000000   ok       ok   
    2  1   0   00000000   ok       ok   
    3  1   0   00000000   ok       ok   
    4  0   1   00000000   ok       ok   
    5  0   0   00000001   ok       ok   
    6  0   1   00000010   ok       ok   
    7  0   1   00000101   ok       ok   
    8  0   0   00001011   ok       ok   
    9  0   0   00010110   ok       ok   
   10  0   1   00101100   ok       ok   
   11  0   1   01011001   ok       ok   
   12  0   1   10110011   ok       ok   
   13  0   0   01100111   ok       ok   
   14  0   0   11001110   ok       ok   
   15  0   0   10011100   ok       ok   
   16  0   0   00111000   ok       ok   
   17  0   1   01110000   ok       ok   
   18  0   1   11100001   ok       ok   
   19  0   0   11000011   ok       ok   
   20  0   1   10000110   ok       ok   
   21  0   1   00001101   ok       ok   
   22  0   1   00011011   ok       ok   
   23  0   1   00110111   ok       ok   
   24  1   1   00000000   ok       ok   
   25  0   0   00000000   ok       ok   
   26  0   1   00000000   ok       ok   
   27  0   0   00000001   ok       ok   
   28  0   0   00000010   ok       ok   
   29  0   1   00000100   ok       ok   
   30  0   1   00001001   ok       ok   
   31  0   0   00010011   ok       ok   
   32  0   1   00100110   ok       ok   
   33  0   0   01001101   ok       ok   
   34  0   0   10011010   ok       ok   
   35  0   0   00110100   ok       ok   
   36  0   0   01101000   ok       ok   
tb.sv:169: $finish called at 395000 (1ps)
PASS: 72 checks, no errors

To see that the testbench catches mistakes, break something and run it again: in shift_register_chips.sv connect data_b to q [2] instead of q [3], or remove or posedge reset_b in cd4015.sv. The script reports FAIL and the trace shows the cycles 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. BGM has its own lab on the subject, 1_07_shift_register.

  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 shift_register.sv.
  3. Run ./03_synthesize_for_fpga.bash and ./04_configure_fpga.bash; the first run asks which board you have.

The register shifts on slow_clk, which every BGM board makes at 1 Hz. 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 D, the reset button of the board clears the register, and the LEDs show the eight bits.

bgm_lab/lab_top.sv97 lines · show the codefile
// Exercise B6 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 shift_register.sv.  For the chip-level
// design add shift_register_chips.sv and cd4015.sv instead, and change the
// module name below.
//
// The register shifts on slow_clk, the 1 Hz clock that every BGM board
// wrapper makes, like the breadboard with the 555 module.  Key 0 is D, the
// reset button of the board clears the register.  The LEDs show the eight
// bits; a board with fewer LEDs shows the first ones.

`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 abcdefgh   = '0;
       assign digit      = '0;
       assign red        = '0;
       assign green      = '0;
       assign blue       = '0;
       assign sound      = '0;
       assign uart_tx    = '1;

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

    logic [7:0] q;

    shift_register i_shift_register
    (
        .clk ( slow_clk ),
        .rst ( rst      ),
        .d   ( key [0]  ),
        .q   ( q        )
    );

    assign led = w_led' (q);

endmodule

13On an FPGA board: hackathon_top in BGM

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

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

Any key is D. The eight LEDs and a row of eight squares on the screen show the bits, Q1 on the left.

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

// Exercise B6 in the hackathon setup of Basics-Graphics-Music (BGM):
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy hackathon/problems/5_shift_register, replace its hackathon_top.sv
// with this file and add shift_register.sv.
//
// The register shifts on slow_clock, one beat per second, like the
// breadboard with the 555 module.  Any key is D.  The LEDs and a row of
// eight squares on the screen show the bits; Q1, the newest, is on the left.

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

    shift_register i_shift_register
    (
        .clk ( slow_clock ),
        .rst ( reset      ),
        .d   ( | key      ),
        .q   ( q          )
    );

    assign led      = q;

    assign abcdefgh = '0;
    assign digit    = '0;

    //------------------------------------------------------------------------
    // Eight squares on the 480 x 272 screen, bright orange for 1, dim for 0

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

        for (int i = 0; i < 8; i ++)
            if (x >= 9' (24 + i * 56) & x < 9' (64 + i * 56) & y >= 116 & y < 156)
            begin
                red   = q [i] ? 31 : 6;
                green = q [i] ? 40 : 8;
            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 register, just as the 555 module clocks the 4015 on the breadboard. Switch 0 is D. The eight bits light the seven segments and the dot, so a 1 runs around the digit: a, b, c, d, e, f, g, dot.

tiny_tapeout/project.v49 lines · show the codefile
/*
 * Exercise B6 on Tiny Tapeout: an 8-bit shift register.  Switch 0 is D;
 * the eight bits light the seven segments and the dot of the demo board.
 *
 * Add shift_register.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
);

    // Set the project clock to 1 Hz (clock_hz: 1 in info.yaml): the demo
    // board makes it, and clk drives the register directly, like the 555
    // module on the breadboard.  The reset button of the board is rst_n.

    wire [7:0] q;

    shift_register i_shift_register (
        .clk ( clk       ),
        .rst ( ~ rst_n   ),
        .d   ( ui_in [0] ),
        .q   ( q         )
    );

    // 7-segment display: uo_out [0] is segment a, ..., uo_out [6] is g,
    // uo_out [7] is the dot.  Bit k lights segment k: a 1 entered with
    // switch 0 runs a, b, c, d, e, f, g and the dot.

    assign uo_out  = q;

    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 both files and use the module name as the top module:

project:
  clock_hz:   1                 # the demo board makes a 1 Hz clock
  top_module: "tt_um_example"   # rename to tt_um_<your GitHub name>_shift_register
  source_files:
    - "project.v"
    - "shift_register.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. Here the board makes the 1 Hz clock, so no divider is needed; on a chip that needs a slow tick from a fast clock, keep one clock and add a clock enable.

15Going further

Tasks for students

Files of this exercise

Sources

The exercise is the fourth of the Basics list in “An improved way of teaching school kids digital electronics using venerable small-scale integration ICs”; lesson 1.3 of the Habr article about the electronics course describes the class with the 4015, a button and the LED module. The 4015 is described in the Texas Instruments datasheet for the CD4015B.