Module 6: Verilog for Testbench & Simulation · 6.2 Simulation-Only Constructs

$readmemh and $readmemb

Hardcoding hundreds of test vectors inside procedural initial blocks makes testbenches difficult to maintain. Separating stimulus data from testbench execution code improves modularity. The $readmemh and $readmemb system tasks load external text files into Verilog arrays in a single execution step.

File Format Specifications

Data files contain whitespace-separated values. Line comments (//) and blank lines are ignored:

// counter_vectors.hex
0a
ff
80
00

The @address directive jumps to specific array indices:

@0000
aa bb cc dd     // Loaded into array indices 0 through 3

@0010
11 22 33        // Loaded into indices 16 through 18; unmapped indices retain 'x'

Use $readmemh for hexadecimal notation. Use $readmemb for binary notation.

Loading Arrays

Declare an internal array and load data during initialization:

reg [7:0] test_vectors [0:255];

initial begin
    $readmemh("vectors.hex", test_vectors);
end

The simulator populates array entries sequentially from index 0 until data or array bounds end. Unpopulated entries retain uninitialized (x) states. You can also specify explicit start and stop address ranges:

$readmemh("data.hex", mem, 256, 511);    // Populates only mem[256] through mem[511]

Structuring Test Vector Records

You can organize vector data using two approaches:

  1. Packed wide words: Concatenate opcode, input operands, and expected results into a single wide register.
  2. Parallel arrays: Maintain distinct files and arrays for inputs and expected outputs:
reg [17:0] inputs   [0:99];    // Packed format: {op[1:0], a[7:0], b[7:0]}
reg [7:0]  expected [0:99];    // Expected golden output

initial begin
    $readmemh("alu_inputs.hex",   inputs);
    $readmemh("alu_expected.hex", expected);
end

Parallel arrays allow software reference generators (written in Python or C) to update expected values independently from input vectors.

Synthesizable Application: ROM and RAM Initialization

FPGA synthesis tools support $readmemh inside initial blocks to pre-load block RAMs and lookup tables:

module sine_lut (
    input  wire [7:0] addr,
    output reg  [7:0] data
);
    reg [7:0] rom [0:255];

    initial begin
        $readmemh("sine_table.hex", rom); // Synthesizes into initialized FPGA Block RAM
    end

    always @(*)
        data = rom[addr];
endmodule

The synthesis tool reads the text file during elaboration and embeds the constants directly into the FPGA bitstream.

Data-Driven ALU Testbench Example

The file alu_vectors.hex stores 32-bit records: operation code, operand a, operand b, and expected result:

// alu_vectors.hex: op(8b) a(8b) b(8b) expected(8b)
000A050F    // ADD: 10 + 5 = 15
00FF0100    // ADD: 255 + 1 = 0 (wrap)
00807FFF    // ADD: 128 + 127 = 255
010A0505    // SUB: 10 - 5 = 5
010001FF    // SUB: 0 - 1 = 255 (wrap)
02F00F00    // AND: 0xF0 & 0x0F = 0x00
03F00FFF    // OR:  0xF0 | 0x0F = 0xFF

The testbench parses and executes these external vectors:

`timescale 1ns / 1ps

module alu_8bit (
    input  wire [1:0] op,
    input  wire [7:0] a,
    input  wire [7:0] b,
    output reg  [7:0] result
);
    always @(*) begin
        case (op)
            2'b00:   result = a + b;
            2'b01:   result = a - b;
            2'b10:   result = a & b;
            2'b11:   result = a | b;
            default: result = 8'hxx;
        endcase
    end
endmodule

module tb_alu_readmem();

    reg  [1:0] op;
    reg  [7:0] a, b;
    wire [7:0] result;

    reg [31:0] vectors [0:255];

    integer error_count, test_count;
    integer log_mcd, log_and_console;
    integer i;

    alu_8bit dut (
        .op    (op),
        .a     (a),
        .b     (b),
        .result(result)
    );

    initial begin
        #50_000;
        $fatal(1, "TIMEOUT");
    end

    initial begin
        $dumpfile("tb_alu_readmem.vcd");
        $dumpvars(0, tb_alu_readmem);
        $timeformat(-9, 0, " ns", 8);

        log_mcd = $fopen("alu_results.log");
        if (log_mcd == 0)
            $fatal(1, "Cannot open alu_results.log");
        log_and_console = log_mcd | 32'h1;

        $readmemh("alu_vectors.hex", vectors);

        error_count = 0;
        test_count  = 0;

        for (i = 0; i < 256; i = i + 1) begin
            if (vectors[i] !== 32'hxxxxxxxx) begin      // Stop at uninitialized entries
                op = vectors[i][25:24];
                a  = vectors[i][23:16];
                b  = vectors[i][15:8];
                #10;

                test_count = test_count + 1;

                if (result !== vectors[i][7:0]) begin
                    $fdisplay(log_and_console, "%t  op=%0d a=%02h b=%02h expected=%02h got=%02h  FAIL",
                              $time, op, a, b, vectors[i][7:0], result);
                    error_count = error_count + 1;
                end else begin
                    $fdisplay(log_mcd, "%t  op=%0d a=%02h b=%02h expected=%02h got=%02h  pass",
                              $time, op, a, b, vectors[i][7:0], result);
                end
            end
        end

        if (error_count == 0)
            $fdisplay(log_and_console, "RESULT: PASSED, all %0d tests.", test_count);
        else
            $fdisplay(log_and_console, "RESULT: FAILED, %0d of %0d tests.", error_count, test_count);

        $fclose(log_mcd);
        $finish;
    end

endmodule

The condition vectors[i] !== 32'hxxxxxxxx detects uninitialized array positions, terminating execution when file vectors end.

The next article examines timing control constructs: delays, event triggers, and level-sensitive wait statements.

← Writing to Files #delay, @(event) and wait() →