Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 37 ยท Testbenches

Clocks, Resets, Memories and Files in Testbenches

Generate clocks and resets in a Verilog testbench, avoid races at clock edges, load test vectors with $readmem and $fopen, and dump waveforms with $dumpvars.

Sequential designs need a clock and, nearly always, a reset. Writing those two correctly is the foundation of every testbench for registers, counters and state machines. This lesson covers a clock generator, a reset sequence, how to drive inputs without racing the clock edge, how to load vectors from a file with $readmem, how to read and write files with $fopen and friends, and how to dump waveforms for a viewer such as GTKWave.

Verilog runs only in a simulator, which this site does not provide, so the Verilog is read-only. The C programs are labelled stand-ins that mimic a clock, a register that samples at the rising edge, and a vector file.

A clock generator

The usual 10-time-unit clock is two lines:

VERILOG
reg clk = 1'b0;
always #5 clk = ~clk;      // period = 10, 100 MHz at timescale 1ns

The always block waits 5 units, flips the clock, and repeats forever. Starting at 0 means the first rising edge is at t = 5. For a duty cycle other than 50% write the high and low phases separately:

VERILOG
always begin
  #3 clk = 1'b1;           // high for 3
  #7 clk = 1'b0;           // low for 7 (period 10, 30% duty)
end

A parameter keeps the period in one place:

VERILOG
parameter PERIOD = 10;
always #(PERIOD/2) clk = ~clk;

An endless clock means $finish is essential: the simulation never runs out of events by itself.

A reset sequence

Most designs have a synchronous or asynchronous reset. The testbench asserts it at the start, holds it for a few clocks, then releases it:

VERILOG
reg rst_n;
initial begin
  rst_n = 1'b0;                    // active low: asserted
  repeat (3) @(posedge clk);       // hold for 3 clock edges
  #1 rst_n = 1'b1;                 // release just after an edge
end

@(posedge clk) waits for a rising edge, and repeat (n) runs the following statement n times. Releasing a little after the edge keeps the change away from the sampling instant, the topic of the next section.

Avoiding races at the clock edge

A register samples its input at the rising edge. If the testbench changes the input at exactly the same simulation time, which value does the register see, the old or the new one? The language does not say: the order of two events scheduled at the same time is arbitrary, so a testbench that does this is racy and may behave differently in two simulators.

Safe styles:

  • Drive after the edge with a small delay: @(posedge clk); #1 data = 8'h5A;
  • Drive on the falling edge: @(negedge clk) data = 8'h5A;
  • Use non-blocking assignments in the testbench: @(posedge clk) data <= 8'h5A; The new value is applied after all blocking reads of this time step, so the DUT sees the old value at this edge and the new value at the next. This mirrors what real registers do.
  • SystemVerilog clocking blocks automate this (see interfaces and modports).

The first stand-in models the sampling problem. A register captures d at each rising edge; the testbench changes d in the same step, either before or after the capture, and the captured sequences differ. That is the race in numbers.

C Stand-in: input changing at the same moment as the clock edge

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The first line shows q lagging one cycle behind the stimulus (0, 1, 2, 3), as real hardware would; the second shows q equal to the stimulus (1, 2, 3, 4), which would be wrong if the DUT's flip-flop is supposed to delay by one cycle. Two simulators could legally produce either, so write the testbench so that only the first can happen.

Waveforms

For debugging, record every signal over time into a VCD (value change dump) file and open it in a viewer like GTKWave:

VERILOG
initial begin
  $dumpfile("adder4_tb.vcd");
  $dumpvars(0, adder4_tb);     // 0 = all levels below this module
end

Put the dump in a separate initial block. The call must happen before the interesting activity starts, so run it at time 0.

Loading memories and vectors

$readmemh and $readmemb load a text file (hexadecimal or binary words) into an array:

VERILOG
reg [15:0] vectors [0:255];     // 256 words of 16 bits
initial $readmemh("vectors.hex", vectors);

The file holds one value per whitespace-separated word, with // comments and optional @address markers to jump:

TEXT
// a b expected_sum
0304 0007
0909 0013
@10
0F01 0010

A vector-driven testbench loops over the array, splitting each word into inputs and expected output, then uses the check task from self-checking testbenches. The same $readmemh is also how you initialise a ROM or RAM in a design for simulation (and FPGA tools often accept it for synthesis).

File I/O with $fopen

For richer reading and writing use the C-like file routines:

VERILOG
integer fd, status;
reg [7:0] value;
initial begin
  fd = $fopen("input.txt", "r");
  if (fd == 0) begin
    $display("cannot open input.txt");
    $finish;
  end
  while (!$feof(fd)) begin
    status = $fscanf(fd, "%h\n", value);
    if (status == 1) $display("read %h", value);
  end
  $fclose(fd);
end

Writing is fd = $fopen("log.txt", "w"); $fdisplay(fd, "a=%0d", a);. Always check that $fopen returned a nonzero handle.

A second stand-in: a vector file in memory

The second program mimics the vector flow: a text block plays the role of vectors.hex, is parsed into an array like $readmemh, and each line is applied to a DUT and checked. It prints how many vectors passed.

C Stand-in: $readmemh-style vectors drive and check a DUT

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Vector 2 is 9 + 9 = 0x12, which is 18, so it passes. The file keeps data and test code separate: change the vectors without touching the testbench.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does always #5 clk = ~clk; generate when the timescale is 1 ns?

    The clock toggles every 5 ns, so one full cycle (high plus low) takes 10 ns.
  2. 2. Why can driving an input exactly at posedge clk with a blocking assignment be a problem?

    Both events occur at the same simulation time, and the language does not define their order. A race.
  3. 3. What does $readmemh("v.hex", mem) do?

    $readmemh fills an array from a text file of hexadecimal values. $readmemb does the same for binary.
  4. 4. Why start $dumpvars in an initial block at time 0?

    Signals changing before the dump starts are not recorded, so you would miss the reset sequence.

Summary

  • A clock is always #(PERIOD/2) clk = ~clk;; end the simulation with $finish.
  • Assert reset for a few clocks, release it just after an edge.
  • Avoid races: change inputs after the edge, on the falling edge, or with non-blocking assignments.
  • $dumpfile/$dumpvars write waveforms; $readmemh loads vectors and memory images; $fopen, $fscanf and $fdisplay read and write text files.

Next: Moore and Mealy State Machines