Skip to content
systemcoding.dev
Hardware

Write a Verilog Testbench With initial Blocks and $display

Write a Verilog testbench with initial blocks that drives inputs, prints with $display and $monitor, checks outputs with !== and ends with PASS or FAIL.

7 min read
Summarize in AI
Flat illustration of logic gates wired into a small circuit, with the KiCad, Haskell and SparkFun logos.

A testbench is a Verilog module whose only job is to exercise another module and tell you whether it behaved. It has no ports because nothing sits above it in the hierarchy: it creates the signals, drives them, watches the outputs and prints a verdict. This post builds a testbench for a two-input adder using only initial blocks, $display and $monitor, which is enough for the first dozen designs you write. It uses Icarus Verilog 12.0 syntax with the -g2012 flag, and everything shown also runs in Verilator's --binary mode. If you have not yet compiled and run a simulation, the Icarus and GTKWave walkthrough in this cluster is the right place to start.

The design under test

The adder is combinational: its output depends only on its current inputs, with no clock.

adder.vverilog
module adder (
    input  wire [3:0] a,
    input  wire [3:0] b,
    output wire [4:0] sum
);
    assign sum = a + b;
endmodule

sum is five bits wide so the largest result, 15 plus 15, equals 30 and fits. If you declared it four bits, the carry would be silently dropped, which is a bug a good testbench should catch.

An initial block is a script

The statements inside initial begin ... end run once, in order, starting at time zero. Unlike an always block, nothing loops. Delays written as #10 advance simulation time by ten time units, which is how a testbench says "wait ten nanoseconds, then do the next thing". These constructs exist only for simulation; a synthesis tool will refuse or ignore most of them. That is fine because the testbench is never built into hardware.

Inputs in a testbench are reg because an initial block assigns to them procedurally. Outputs of the design are wire because the design drives them.

The first testbench

adder_tb.vverilog
`timescale 1ns/1ps

module adder_tb;
    reg  [3:0] a;
    reg  [3:0] b;
    wire [4:0] sum;

    adder dut (.a(a), .b(b), .sum(sum));

    initial begin
        a = 4'd0;  b = 4'd0;  #10;
        $display("a=%0d b=%0d sum=%0d", a, b, sum);

        a = 4'd3;  b = 4'd4;  #10;
        $display("a=%0d b=%0d sum=%0d", a, b, sum);

        a = 4'd15; b = 4'd15; #10;
        $display("a=%0d b=%0d sum=%0d", a, b, sum);

        $finish;
    end
endmodule
Shell
iverilog -g2012 -o adder_sim adder.v adder_tb.v
vvp adder_sim
Text
a=0 b=0 sum=0
a=3 b=4 sum=7
a=15 b=15 sum=30

The #10 after each assignment is not decoration. Without a delay, $display would run in the same time step as the assignment, and the continuous assignment inside adder may not have updated yet, so you could print a stale sum. Waiting lets the design settle before you look.

Format specifiers

$display works like printf. The specifiers you will use constantly:

SpecifierPrints
%ddecimal, padded to the width of the signal
%0ddecimal with no padding
%bbinary
%hhexadecimal
%tsimulation time, formatted by $timeformat
%mthe hierarchical name of the module that printed

%d pads with spaces to fit the largest value the signal could hold, which makes columns line up but surprises people. If you print sum with %d you get 30 for a 5-bit signal but 7 with a leading space for the value 7. Use %0d when you want the plain number.

A related system task, $write, prints without the trailing newline. $strobe prints at the end of the current time step, after all assignments have settled, which solves the stale-value problem without a delay. For a combinational circuit with delays between steps, $display is enough.

Watching a signal with $monitor

$monitor registers a print statement that fires every time any listed value changes. You call it once and it keeps going for the rest of the run.

adder_mon_tb.vverilog
`timescale 1ns/1ps

module adder_mon_tb;
    reg  [3:0] a;
    reg  [3:0] b;
    wire [4:0] sum;

    adder dut (.a(a), .b(b), .sum(sum));

    initial begin
        $monitor("t=%0t a=%0d b=%0d sum=%0d", $time, a, b, sum);
        a = 4'd1; b = 4'd2; #10;
        a = 4'd7; #10;
        b = 4'd9; #10;
        $finish;
    end
endmodule
Text
t=0 a=1 b=2 sum=3
t=10000 a=7 b=2 sum=9
t=20000 a=7 b=9 sum=16

Two things in that output need explaining. $monitor prints at the end of a time step, after everything in that step has settled, and at most once per step. That is why the first line already shows sum=3: the inputs were assigned and the continuous assignment updated sum in the same step, and the monitor reports the settled result, never the intermediate one. The times print as 10000 and 20000 because %0t formats in the simulator's precision unit, and with a timescale of 1ns/1ps that unit is the picosecond, so 10 ns reads as 10000. Call $timeformat(-9, 0, " ns", 8); once at the top of the initial block to print nanoseconds instead.

Only one $monitor is active at a time. A second call replaces the first, so you cannot monitor two different groups of signals independently.

Checking, not just printing

A testbench that only prints needs a person to read it, and a person will skim a hundred lines and miss the wrong one. Make the testbench decide. Compare each result with the value you expect and print a verdict:

adder_check_tb.vverilog
`timescale 1ns/1ps

module adder_check_tb;
    reg  [3:0] a;
    reg  [3:0] b;
    wire [4:0] sum;
    integer    errors;

    adder dut (.a(a), .b(b), .sum(sum));

    task check(input [3:0] ta, input [3:0] tb, input [4:0] expected);
        begin
            a = ta;
            b = tb;
            #1;
            if (sum !== expected) begin
                $display("FAIL: %0d + %0d = %0d, expected %0d", ta, tb, sum, expected);
                errors = errors + 1;
            end
        end
    endtask

    initial begin
        errors = 0;
        check(4'd0,  4'd0,  5'd0);
        check(4'd3,  4'd4,  5'd7);
        check(4'd15, 4'd1,  5'd16);
        check(4'd15, 4'd15, 5'd30);

        if (errors == 0)
            $display("PASS: all checks");
        else
            $display("FAIL: %0d errors", errors);
        $finish;
    end
endmodule
Text
PASS: all checks

The operator !== is the case-inequality operator. It compares four-valued logic exactly, so an x or z in sum counts as a mismatch. The plain != returns x when either side contains an unknown, an if treats x as false, and the failure disappears. Use === and !== in testbench checks every time.

The task packages the apply-wait-compare pattern so each test is one line. Tasks may contain delays, which functions may not, so a task is the right construct here.

If you break the adder on purpose, for example by declaring sum as [3:0], the same testbench prints:

Text
FAIL: 15 + 1 = 0, expected 16
FAIL: 15 + 15 = 14, expected 30
FAIL: 2 errors

The truncated sum is exactly what a four-bit result would hold: 16 mod 16 is 0, and 30 mod 16 is 14.

Testing every input

A four-bit adder has only 256 input combinations, so you do not have to pick cases by hand. A loop can apply all of them and compare each result with the language's own + operator, computed in the testbench with enough width.

adder_all_tb.vverilog
`timescale 1ns/1ps

module adder_all_tb;
    reg  [3:0] a;
    reg  [3:0] b;
    wire [4:0] sum;
    integer    i;
    integer    j;
    integer    errors;

    adder dut (.a(a), .b(b), .sum(sum));

    initial begin
        errors = 0;
        for (i = 0; i < 16; i = i + 1) begin
            for (j = 0; j < 16; j = j + 1) begin
                a = i;
                b = j;
                #1;
                if (sum !== i + j) begin
                    $display("FAIL: %0d + %0d gave %0d", i, j, sum);
                    errors = errors + 1;
                end
            end
        end
        $display("%0d errors in 256 cases", errors);
        $finish;
    end
endmodule
Text
0 errors in 256 cases

The loop variables are 32-bit integer values, so i + j is computed at 32 bits and never wraps, which is what makes it a fair reference for the five-bit hardware sum. Exhaustive testing is the strongest check you can write, and it stops being practical only when the input space grows: a 32-bit adder has about 1.8e19 combinations, and there you switch to directed corner cases plus random stimulus.

Ending the simulation

$finish ends the run. If you forget it, an always-block clock keeps the event queue busy forever and the simulator never returns, so a testbench with a clock always needs a $finish. For a purely combinational testbench like these, the run ends on its own when events run out, but writing $finish explicitly is the habit to keep. $stop pauses and enters the simulator's interactive prompt in tools that have one, which is not what you want in a script.

A reusable skeleton

Most small testbenches repeat the same shape, so keep a template and fill in the design's name and checks. The skeleton has a timescale, signals for every port, one instance called dut, a clock if the design needs one, a task for the apply-wait-check cycle, an initial block that runs the cases and ends with one verdict line, and a watchdog so a hung simulation fails instead of waiting forever. Writing the verdict as a single PASS or FAIL line costs nothing and lets a script or a build rule read the outcome without parsing the log.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.