Exercise B4 · basics · flip-flop
D flip-flop with an asynchronous reset
The clock module blinks once a second. Press the D button and Q follows it, but only at the next rising edge of the clock; press and release between two edges and Q never sees it. The reset button clears Q at once, without waiting. One chip, four LEDs, and the idea behind every register in every processor.
1What it is and why it matters
What it does. A D flip-flop stores one bit. At each rising edge of its clock, the moment the clock goes from 0 to 1, it copies its input D to its output Q, and then holds Q until the next rising edge, whatever D does in between. Its reset input clears Q to 0 at once. Here the clock comes from the 555 module at about 1 Hz, D and reset from two buttons, and the LED module shows CLK, D, Q and ~Q (NOT Q) side by side. This is the second exercise of the Basics list in “An improved way of teaching school kids digital electronics”: “Demo 4013, D-flip-flop (DFF) with asynchronous reset”. Lesson 1.3 of the Habr article runs the same demo with a slow clock, and picture 5 of “Teaching children electronics is due for a major redesign” shows it on a breadboard.
How it works. Watch the LEDs: Q changes only when the CLK LED lights up. Hold D down across an edge and Q becomes 1 at that edge. Tap D quickly while the CLK LED stays the same, and Q does not move. Press reset and Q goes dark immediately, even in the middle of a clock period.
Where it is used. Every register in a chip is a row of D flip-flops on one clock: the program counter and the registers of a processor, the pipeline stages between its steps, the state register of every state machine, the stages of a shift register (exercise B6) and of a counter (exercise B5). An FPGA has hundreds of thousands of them. The asynchronous reset puts all of them into a known state when the chip starts.
Why learn it.
- A flip-flop is the boundary between combinational logic, which follows its inputs at once, and sequential logic, which changes only at clock edges. Everything after this exercise is built on it.
- The rule “only the value at the rising edge counts” is how every synchronous design works, and how every testbench in this course samples signals.
- Seeing an asynchronous reset next to the clock shows the difference between “at once” and “at the next edge”, which matters in every SystemVerilog design you will write.
- In SystemVerilog the whole flip-flop is three lines:
always_ff @ (posedge clk or posedge rst)with anif.
2The key element: the D flip-flop
D flip-flop with reset
| rst | clk | D | Q after |
|---|---|---|---|
| 1 | any | any | 0, at once |
| 0 | ↑ | 0 | 0 |
| 0 | ↑ | 1 | 1 |
| 0 | no edge | any | keeps Q |
Q takes the value of D at the rising edge of the clock (↑) and keeps it until the next edge. R = 1 clears Q at once, without the clock. The triangle at the clock input marks an edge-triggered input.
NOT
| A | Y = NOT A |
|---|---|
| 0 | 1 |
| 1 | 0 |
The 4013 has a second output, ~Q, that is always the opposite of Q. In a drawing of the flip-flop alone it is one NOT gate after Q.
The 4013 with both of its asynchronous inputs
Each flip-flop of the 4013 has a SET input as well as RESET. SET = 1 makes Q = 1 at once. In this exercise SET is tied to GND, so only RESET is used. The function table from the datasheet:
| CLOCK | D | RESET | SET | Q | Q̅ |
|---|---|---|---|---|---|
| ↑ | 0 | 0 | 0 | 0 | 1 |
| ↑ | 1 | 0 | 0 | 1 | 0 |
| ↓ | any | 0 | 0 | Q | Q̅ |
| any | any | 1 | 0 | 0 | 1 |
| any | any | 0 | 1 | 1 | 0 |
| any | any | 1 | 1 | 1 | 1 |
The last row is a special case: with SET and RESET both 1, the 4013 sets both Q and ~Q to 1. A design should not rely on it.
Waveforms
tb.sv in Icarus Verilog. Dotted lines are the rising edges of
the clock. D is 1 at the second edge, so Q becomes 1 there. The short 0 of D between the second and third edges
and the short 1 between the fourth and fifth edges come and go without an edge: Q does not see them. At the end,
rst clears Q in the middle of a clock period. · SVG · PNG3Parts
| Part | In this circuit | Qty | Price | Supplier |
|---|---|---|---|---|
| CD4013 | dual D flip-flop: the first one is used | 1 | $0.35 | Elexp (elexp.com) |
| 555 clock module | the clock, set to about 1 Hz | 1 | $0.53 | aliexpress.us |
| Button modules | D and reset; two modules from the pack of five | 2 | $0.66 / pack | aliexpress.us |
| 8-LED module | shows CLK, D, Q and ~Q | 1 | $0.38 | aliexpress.us |
| Breadboard, 830 points | 1 | $3.00 | amazon.com | |
| Breadboard power module | 5 V on the rails | 1 | $1.00 | aliexpress.us |
| USB-to-DC cable, 9 V | powers the module from a USB charger | 1 | $1.17 | aliexpress.us |
| Male-male Dupont jumpers | 7 wires on the board (or pre-cut wires) | 7 | $1.30 / pack | aliexpress.us |
| Male-female Dupont jumpers | 14 leads to the modules | 14 | $1.30 / pack | aliexpress.us |
Prices from the LSSK components sheet; all of these parts are in the Basics kit. The clock module and the buttons are modules on male-female jumpers, so the board itself has only power and tie-off wires.
4The chip, pin by pin
The 4013 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. That is why SET of the first flip-flop and all four inputs of the unused second flip-flop are wired to GND. 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.
4013: dual D flip-flop with set and reset
Polarity. Each flip-flop stores D on the rising edge of its CLOCK. RESET and SET are active high and asynchronous: while RESET is 1, Q is 0, whatever the clock does. Both outputs are active high; ~Q is the inverted output.
Flip-flop 1 uses pins 1–6 along the bottom, flip-flop 2 pins 8–13 along the top. Only flip-flop 1 is used here.
| Pin | Name | Direction | Function | In this circuit |
|---|---|---|---|---|
| 1 | Q1 | output | flip-flop 1 output | Q |
| 2 | Q1 | output | flip-flop 1 output, inverted | Q |
| 3 | CLOCK1 | input | flip-flop 1 stores D1 on the rising edge, 0 to 1 | CLK |
| 4 | RESET1 | input | 1 sets Q1 = 0 at once, without the clock. Active high | RST |
| 5 | D1 | input | flip-flop 1 data input | D |
| 6 | SET1 | input | 1 sets Q1 = 1 at once, without the clock. Active high | GND |
| 7 | VSS | power | ground, 0 V | GND |
| 8 | SET2 | input | 1 sets Q2 = 1 at once. Active high | tied to GND |
| 9 | D2 | input | flip-flop 2 data input | tied to GND |
| 10 | RESET2 | input | 1 sets Q2 = 0 at once. Active high | tied to GND |
| 11 | CLOCK2 | input | flip-flop 2 stores D2 on the rising edge | tied to GND |
| 12 | Q2 | output | flip-flop 2 output, inverted | not connected |
| 13 | Q2 | output | flip-flop 2 output | not connected |
| 14 | VDD | power | supply, +5 V (3 to 18 V allowed) | +5V |
5Schematic 1: the flip-flop
d_flip_flop.sv describes. · SVG · PNGThe button D drives the D input, the clock module drives the clock input, the reset button drives R. CLK and D also go to LEDs 1 and 2, so that you can see the input values next to the output.
6Schematic 2: connections of the chip
Every connection of the circuit, net by net. d_flip_flop_chips.sv in section 10 is written from the
same list.
| Net | From | To | Wire |
|---|---|---|---|
| CLK | 555 clock module, OUT | 4013 3 (CLK1), LED module, LED 1 | M-F |
| RST | reset button, OUT | 4013 4 (R1) | M-F |
| D | button D, OUT | 4013 5 (D1), LED module, LED 2 | M-F |
| Q | 4013 1 (Q1) | LED module, LED 3 | M-F |
| Q | 4013 2 (Q1) | LED module, LED 4 | M-F |
| +5V | +5V | 4013 14 (VDD) | |
| GND | GND | 4013 7 (VSS), 4013 11 (CLK2), 4013 10 (R2), 4013 9 (D2), 4013 6 (S1), 4013 8 (S2) | |
| not connected | 4013 12 (Q2), 4013 13 (Q2) |
7Schematic 3: the breadboard
Build it step by step
- 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.
- Insert the 4013 across the gap, notch to the left, pin 1 in hole 18f.
- Power: a red wire from pin 14 to the top + rail, a black wire from pin 7 to the bottom − rail.
- The tie-offs: SET1 (pin 6) to the bottom − rail, and the four inputs of flip-flop 2 (pins 8–11) to the top − rail. The top − rail is the outer one: the wire crosses the + rail.
- With the power off, the modules below the board: reset button, clock module, LED module and button D. Connect their − pins and G of the LED module first.
- Turn the power on and set the clock module to about 1 Hz.
Wiring checklist
| # | Net | From | To | |
|---|---|---|---|---|
| Power (red to +, black to −) · 2 wires | ||||
| 1 | +5V | 18a (4013 pin 14, VDD) | top + rail, column 18 | |
| 2 | GND | 24j (4013 pin 7, VSS) | bottom − rail, column 24 | |
| Fixed inputs: CMOS inputs must not float · 5 wires | ||||
| 3 | GND | 21a (4013 pin 11, CLK2) | top − rail, column 21 | |
| 4 | GND | 22a (4013 pin 10, R2) | top − rail, column 22 | |
| 5 | GND | 23a (4013 pin 9, D2) | top − rail, column 23 | |
| 6 | GND | 23j (4013 pin 6, S1) | bottom − rail, column 23 | |
| 7 | GND | 24a (4013 pin 8, S2) | top − rail, column 24 | |
| Modules on male-female jumpers · 14 wires | ||||
| 8 | +5V | reset button, + | bottom + rail, column 7 | |
| 9 | RST | reset button, OUT | 21j (4013 pin 4, R1) | |
| 10 | GND | reset button, − | bottom − rail, column 9 | |
| 11 | GND | 555 clock module, − | bottom − rail, column 12 | |
| 12 | CLK | 555 clock module, OUT | 20j (4013 pin 3, CLK1) | |
| 13 | +5V | 555 clock module, + | bottom + rail, column 14 | |
| 14 | GND | LED module, G | bottom − rail, column 21 | |
| 15 | CLK | LED module, LED 1 | 20i (4013 pin 3, CLK1) | |
| 16 | D | LED module, LED 2 | 22j (4013 pin 5, D1) | |
| 17 | Q | LED module, LED 3 | 18j (4013 pin 1, Q1) | |
| 18 | Q | LED module, LED 4 | 19j (4013 pin 2, Q1) | |
| 19 | +5V | button D, + | bottom + rail, column 38 | |
| 20 | D | button D, OUT | 22i (4013 pin 5, D1) | |
| 21 | GND | button D, − | bottom − rail, column 40 | |
Test it
- LED 1 (CLK) blinks with the clock module. Without pressing anything, Q (LED 3) stays dark and ~Q (LED 4) lit.
- Hold D down until the next blink, then let go: Q lights at the blink and stays lit after you let go, until an edge comes while D is up.
- With Q dark, tap D quickly between two blinks: LED 2 flashes, Q stays dark.
- With Q lit, press reset: Q goes dark at once, without waiting for the clock.
If it does not work: if Q never changes, check the clock lead to pin 3 and that RESET (pin 4) is 0 when the button is up. If Q and ~Q are both lit, SET and RESET are both 1: SET (pin 6) must go to GND. If Q changes at random when you touch the board, an input is floating: look for a missing tie-off.
8SystemVerilog: the generic design
d_flip_flop.sv describes schematic 1. The always_ff block is the flip-flop: it runs at
every rising edge of clk and at every rising edge of rst, and the if gives the
reset priority. Because rst is in the sensitivity list, the reset does not wait for the clock: it is
asynchronous, like RESET of the 4013. The assign is the NOT gate.
// Exercise B4: a D flip-flop with an asynchronous reset. // // Generic version that matches schematic 1: one D flip-flop and a NOT gate // for the inverted output, not tied to any chip. Synthesizable. module d_flip_flop ( input logic clk, input logic rst, // 1 = Q goes to 0 at once, like RESET of the 4013 input logic d, output logic q, // D as it was at the last rising edge of clk output logic q_n // NOT Q ); always_ff @ (posedge clk or posedge rst) if (rst) q <= 1'b0; else q <= d; assign q_n = ~ q; endmodule
Remove or posedge rst and the reset becomes synchronous: it acts only at the next clock edge. The
testbench in section 11 notices the difference.
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.
// 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
Each flip-flop of the model has two asynchronous inputs. When SET and RESET are both 1, the model sets both outputs to 1, like the chip. What happens when both are released at the same moment is not defined for the chip, and the model does not try to say.
10SystemVerilog: the chip-level design
d_flip_flop_chips.sv connects the chip model exactly as schematic 2 and the breadboard connect the
chip, with the same ports as d_flip_flop.sv. The tied-off inputs go to gnd and the unused
outputs of flip-flop 2 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.
// Exercise B4, chip-level version: the chip and wires of schematic 2 and // of the breadboard. Same ports as d_flip_flop.sv. // // Generated by tools/bb_lib.py from the checked breadboard wire list; // change the layout in tools/bb_b4.py, not this file. Synthesizable. module d_flip_flop_chips ( input logic clk, input logic rst, input logic d, output logic q, output logic q_n ); // The power rails of the breadboard, for tied-off inputs wire gnd = 1'b0; // Outputs that go nowhere wire unused_u1_q2_n; wire unused_u1_q2; //------------------------------------------------------------------------ // U1: CD4013 dual D flip-flop with set and reset, pin 1 in column 18 cd4013 i_u1 ( .q1 ( q ), // Pin 1 -> Q .q1_n ( q_n ), // Pin 2 -> ~Q .clock1 ( clk ), // Pin 3 <- 555 clock module .reset1 ( rst ), // Pin 4 <- reset button .d1 ( d ), // Pin 5 <- button D .set1 ( gnd ), // Pin 6 <- GND .set2 ( gnd ), // Pin 8 <- GND, unused input .d2 ( gnd ), // Pin 9 <- GND, unused input .reset2 ( gnd ), // Pin 10 <- GND, unused input .clock2 ( gnd ), // Pin 11 <- GND, unused input .q2_n ( unused_u1_q2_n ), // Pin 12, unused output .q2 ( unused_u1_q2 ) // Pin 13, unused output ); endmodule
11Testbench and simulation scripts
tb.sv runs both designs side by side and compares them with a reference model. On the breadboard
you can press D at any moment, also between two clock edges. To do the same, the testbench has its own faster
clock, tick, and treats the clock of the flip-flop as one more input. Like the testbenches of
Basics-Graphics-Music, it changes clk, rst and d only right after rising edges
of tick and checks the outputs only at rising edges of tick; it never changes
d at the tick where clk rises. The stimulus is written as three timing charts, one
character per tick, so you can read it like the waveform. At the end it prints PASS or
FAIL.
tb.sv176 lines · show the codefile
// Testbench for exercise B4. // // Runs the generic design (d_flip_flop.sv) and the chip-level design // (d_flip_flop_chips.sv) side by side and compares both with a reference // model. Works with Icarus Verilog, Verilator (--binary) and Questa. // // On the breadboard you can press the D button at any moment, also in the // middle of a clock period. To do the same, the testbench has its own, // faster clock, tick, and treats the clock of the flip-flop as one more // input: like the testbenches of Basics-Graphics-Music it changes clk, rst // and d only right after rising edges of tick and checks the outputs only // at rising edges of tick. It never changes d at the tick where clk rises. // 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 tick; logic clk, rst, d; wire q, q_chips; wire q_n, q_n_chips; d_flip_flop i_generic ( .clk ( clk ), .rst ( rst ), .d ( d ), .q ( q ), .q_n ( q_n ) ); d_flip_flop_chips i_chips ( .clk ( clk ), .rst ( rst ), .d ( d ), .q ( q_chips ), .q_n ( q_n_chips ) ); //------------------------------------------------------------------------ // The testbench clock, period 10 ns. The flip-flop clock below has a // period of 8 ticks; on the breadboard it is about a second. initial begin tick = '0; forever # 5 tick = ~ tick; end //------------------------------------------------------------------------ // The stimulus as three timing charts, one character per tick. // Rising edges of clk at ticks 4, 12, 20, 28, 36 and 44. // // tick 0 4 8 12 16 20 24 28 32 36 40 44 // clk 0000111100001111000011110000111100001111000011110 // rst 0110000000000000000000000000000000000000000000100 // d 0000001111111100011111000000001111000011111111111 // // D is 1 at the edge at tick 12, so Q becomes 1. The short 0 at ticks // 14-16 and the short 1 at ticks 30-33 come and go between edges: Q does // not see them. The reset at tick 46 clears Q at once, without an edge. localparam n_ticks = 49; // The leftmost character is tick 0, the highest bit of each vector wire [n_ticks - 1:0] clk_wave = 49'b0000111100001111000011110000111100001111000011110; wire [n_ticks - 1:0] rst_wave = 49'b0110000000000000000000000000000000000000000000100; wire [n_ticks - 1:0] d_wave = 49'b0000001111111100011111000000001111000011111111111; //------------------------------------------------------------------------ // Reference model. Like RESET of the 4013, rst clears Q at once. logic q_expected; always @ (posedge clk or posedge rst) if (rst) q_expected <= 1'b0; else q_expected <= d; wire ok_generic = q === q_expected && q_n === ~ q_expected; wire ok_chips = q_chips === q_expected && q_n_chips === ~ q_expected; //------------------------------------------------------------------------ // Checking at every rising edge of tick, from the first reset on // Initial values are fine in a testbench, and the checker samples rst at // the tick 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 n_ticks_seen = 0; int n_checks = 0; int n_errors = 0; int n_ones = 0; // Ticks with Q = 1, to see that Q did change always @ (posedge tick) begin if (rst) was_reset <= 1'b1; if (~ done) n_ticks_seen <= n_ticks_seen + 1; if ((rst | was_reset) & ~ done) begin n_checks <= n_checks + 2; n_errors <= n_errors + (ok_generic ? 0 : 1) + (ok_chips ? 0 : 1); n_ones <= n_ones + (q_expected ? 1 : 0); end if (~ done) $display ("%4d %b %b %b %b %b %s %s", n_ticks_seen, clk, rst, d, q, q_n, ~ (rst | was_reset) ? "- " : ok_generic ? "ok " : "WRONG ", ~ (rst | was_reset) ? "- " : ok_chips ? "ok " : "WRONG"); end //------------------------------------------------------------------------ // Driving clk, rst and d from the timing charts initial begin $dumpfile ("tb.vcd"); `ifdef __ICARUS__ $dumpvars (0, tb); // Without a scope Icarus also tries to dump $unit `else $dumpvars; `endif $display ("tick clk rst d Q ~Q generic chips"); for (int i = 0; i < n_ticks; i ++) begin clk <= clk_wave [n_ticks - 1 - i]; rst <= rst_wave [n_ticks - 1 - i]; d <= d_wave [n_ticks - 1 - i]; @ (posedge tick); end // Stop checking one edge before $finish, so that every simulator // reports the same number of checks done <= '1; @ (posedge tick); $finish; end //------------------------------------------------------------------------ final begin if (n_errors == 0 && n_checks > 0 && n_ones == 18) $display ("PASS: %0d checks, no errors", n_checks); else $display ("FAIL: %0d errors in %0d checks, Q = 1 for %0d ticks", n_errors, n_checks, n_ones); 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 B4: 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 d_flip_flop.sv d_flip_flop_chips.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 B4: 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 d_flip_flop.sv d_flip_flop_chips.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 B4: 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 d_flip_flop.sv d_flip_flop_chips.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: one line per tick, with - before the first
reset, while Q is still unknown.
VCD info: dumpfile tb.vcd opened for output. tick clk rst d Q ~Q generic chips 0 0 0 0 x x - - 1 0 1 0 0 1 ok ok 2 0 1 0 0 1 ok ok 3 0 0 0 0 1 ok ok 4 1 0 0 0 1 ok ok 5 1 0 0 0 1 ok ok 6 1 0 1 0 1 ok ok 7 1 0 1 0 1 ok ok 8 0 0 1 0 1 ok ok 9 0 0 1 0 1 ok ok 10 0 0 1 0 1 ok ok 11 0 0 1 0 1 ok ok 12 1 0 1 1 0 ok ok 13 1 0 1 1 0 ok ok 14 1 0 0 1 0 ok ok 15 1 0 0 1 0 ok ok 16 0 0 0 1 0 ok ok 17 0 0 1 1 0 ok ok 18 0 0 1 1 0 ok ok 19 0 0 1 1 0 ok ok 20 1 0 1 1 0 ok ok 21 1 0 1 1 0 ok ok 22 1 0 0 1 0 ok ok 23 1 0 0 1 0 ok ok 24 0 0 0 1 0 ok ok 25 0 0 0 1 0 ok ok 26 0 0 0 1 0 ok ok 27 0 0 0 1 0 ok ok 28 1 0 0 0 1 ok ok 29 1 0 0 0 1 ok ok 30 1 0 1 0 1 ok ok 31 1 0 1 0 1 ok ok 32 0 0 1 0 1 ok ok 33 0 0 1 0 1 ok ok 34 0 0 0 0 1 ok ok 35 0 0 0 0 1 ok ok 36 1 0 0 0 1 ok ok 37 1 0 0 0 1 ok ok 38 1 0 1 0 1 ok ok 39 1 0 1 0 1 ok ok 40 0 0 1 0 1 ok ok 41 0 0 1 0 1 ok ok 42 0 0 1 0 1 ok ok 43 0 0 1 0 1 ok ok 44 1 0 1 1 0 ok ok 45 1 0 1 1 0 ok ok 46 1 1 1 0 1 ok ok 47 1 0 1 0 1 ok ok 48 0 0 1 0 1 ok ok tb.sv:163: $finish called at 495000 (1ps) PASS: 96 checks, no errors
To see that the testbench catches mistakes, break something and run it again: remove
or posedge rst in d_flip_flop.sv (a synchronous reset), or change posedge
clock1 to negedge clock1 in cd4013.sv. The script reports FAIL and the
trace shows the ticks 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.
- Copy a lab, for example
labs/1_basics/1_06_binary_counter, to a new directory. - Replace its
lab_top.svwithbgm_lab/lab_top.svfrom this exercise and addd_flip_flop.sv. - Run
./03_synthesize_for_fpga.bashand./04_configure_fpga.bash; the first run asks which board you have.
The flip-flop runs from 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 is the reset, and the LEDs
show the clock, D, Q and NOT Q.
bgm_lab/lab_top.sv100 lines · show the codefile
// Exercise B4 on an FPGA board with the Basics-Graphics-Music (BGM) labs: // https://github.com/yuri-panchul/basics-graphics-music // // Copy a lab, for example labs/1_basics/1_06_binary_counter, to a new // directory, replace its lab_top.sv with this file and add d_flip_flop.sv. // For the chip-level design add d_flip_flop_chips.sv and cd4013.sv instead, // and change the module name below. // // The flip-flop is clocked by 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 is the reset. The LEDs show what the LED module // shows on the breadboard: led [0] the clock, led [1] D, led [2] Q, // led [3] NOT Q. `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; //------------------------------------------------------------------------ wire d = key [0]; logic q, q_n; d_flip_flop i_d_flip_flop ( .clk ( slow_clk ), .rst ( rst ), .d ( d ), .q ( q ), .q_n ( q_n ) ); assign led = w_led' ({ q_n, q, d, slow_clk }); 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. BGM has a problem on the same subject, hackathon/problems/3_d_flip_flop,
which compares flip-flops with and without resets.
- Copy
hackathon/problems/3_d_flip_flop. - Replace its
hackathon_top.svwithbgm_hackathon/hackathon_top.svand addd_flip_flop.sv. - Run
./03_synthesize_for_fpga.bashand./04_configure_fpga.bash.
Any key is D. The LEDs and four lamps on the screen show the clock, D, Q and NOT Q.
bgm_hackathon/hackathon_top.sv81 lines · show the codefile
// Board configuration: tang_nano_9k_lcd_480_272_tm1638_hackathon // This module uses few parameterization and relaxed typing rules // Exercise B4 in the hackathon setup of Basics-Graphics-Music (BGM): // https://github.com/yuri-panchul/basics-graphics-music // // Copy hackathon/problems/3_d_flip_flop, replace its hackathon_top.sv with // this file and add d_flip_flop.sv. // // The flip-flop runs from slow_clock, one beat per second, like the // breadboard with the 555 module. Any key is D. The LEDs show the clock, // D, Q and NOT Q, and so does the screen, as four lamps. 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 ); //------------------------------------------------------------------------ wire d = | key; logic q, q_n; d_flip_flop i_d_flip_flop ( .clk ( slow_clock ), .rst ( reset ), .d ( d ), .q ( q ), .q_n ( q_n ) ); assign led = { 4'b0, q_n, q, d, slow_clock }; assign abcdefgh = '0; assign digit = '0; //------------------------------------------------------------------------ // Four square lamps on the 480 x 272 screen: clock and D in blue, // Q and NOT Q in green. Bright when 1, dim when 0. wire [3:0] lamp = { q_n, q, d, slow_clock }; always_comb begin red = 0; green = 0; blue = 0; for (int i = 0; i < 4; i ++) if (x >= 9' (88 + i * 80) & x < 9' (136 + i * 80) & y >= 112 & y < 160) begin if (i < 2) blue = lamp [i] ? 31 : 6; else green = lamp [i] ? 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 flip-flop, just as the 555 module clocks the 4013
on the breadboard. Switch 0 is D; the display shows Q as the digit 0 or 1, and the dot shows D.
tiny_tapeout/project.v51 lines · show the codefile
/* * Exercise B4 on Tiny Tapeout: a D flip-flop, with DIP switch 0 as D and * the 7-segment display of the demo board showing Q as the digit 0 or 1. * * Add d_flip_flop.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 flip-flop directly, like the 555 // module on the breadboard. The reset button of the board is rst_n. wire d = ui_in [0]; wire q, q_n; d_flip_flop i_d_flip_flop ( .clk ( clk ), .rst ( ~ rst_n ), .d ( d ), .q ( q ), .q_n ( q_n ) ); // 7-segment display: uo_out [0] is segment a, ..., uo_out [6] is g, // uo_out [7] is the dot. The digit shows Q: segments b and c make 1, // a-f make 0. The dot shows D, the switch. assign uo_out = { d, q ? 7'b000_0110 : 7'b011_1111 }; 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, q_n, 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>_d_flip_flop
source_files:
- "project.v"
- "d_flip_flop.sv"
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 and timing that nobody controls. 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.15Going further
Tasks for students
- Set instead of reset. Move the reset lead from RESET1 (pin 4) to SET1 (pin 6) and tie pin 4 to GND.
What does the button do now? Change
d_flip_flop.svto match. - A divider by two. Use flip-flop 2: connect its ~Q (pin 12) to its D (pin 9) and its clock to the clock module. Q2 changes at every rising edge: it blinks at half the rate of the clock.
- Two flip-flops in a row. Connect Q1 to D2 and both clocks together. A press of D reaches Q2 one clock later: this is the start of the shift register of exercise B6.
- An edge detector. With the two flip-flops in a row, Q1 AND NOT Q2 is 1 for exactly one clock period after D rises. Build it with a free gate from exercise B1 and show it on an LED.
- In SystemVerilog: write a version with a synchronous reset and a clock enable, like the flip-flops in
BGM's
3_d_flip_flopproblem, and change the testbench to check it.
Files of this exercise
- d_flip_flop.sv: the generic design (section 8)
- cd4013.sv: the chip model (section 9)
- d_flip_flop_chips.sv: the chip-level design (section 10)
- tb.sv and run_icarus.bash, run_verilator.bash, run_questa.bash, clean.bash (section 11)
- bgm_lab/lab_top.sv, bgm_hackathon/hackathon_top.sv, tiny_tapeout/project.v (sections 12–14)
- Drawings as SVG and PNG in images/: the three schematics, the pinout and the waveforms;
the Russian versions end in
_ru
Sources
The exercise is the second 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 demo with a 4013 and an assembled 555 module, and picture 5 of “Teaching children electronics is due for a major redesign” shows it on a breadboard. The 4013 is described in the Texas Instruments datasheet for the CD4013B.