Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

Priority Encoder: Testbench

Verilog Examples

Runnable example from the Verilog Priority Encoder tutorial (Testbench)

Open in IDE
design.v
module pr_en_4to2 (
  input      [3:0] req,     // Request inputs; req[3] has the highest priority
  output reg [1:0] idx,     // Index of the highest-priority active request
  output reg       valid    // 1 when any request is active
);

  always @(*) begin
    valid = 1'b1;                       // Assume a request is present
    if      (req[3]) idx = 2'd3;        // Checked first, so req[3] always wins
    else if (req[2]) idx = 2'd2;        // Reached only when req[3] is 0
    else if (req[1]) idx = 2'd1;        // Reached only when req[3:2] are 0
    else if (req[0]) idx = 2'd0;
    else begin                          // No request at all
      idx   = 2'd0;                     // Assign idx here too, or a latch is inferred
      valid = 1'b0;
    end
  end

endmodule
testbench.v
module tb_pr_en;

  reg  [3:0] req;            // Drives the design input
  wire [1:0] idx;            // Collects the design outputs
  wire       valid;

  reg  [1:0] exp_idx;        // Expected values from the reference model
  reg        exp_valid;
  integer    i, errors;

  // Device under test: the if-else-if version
  pr_en_4to2 dut (.req(req), .idx(idx), .valid(valid));

  initial begin
    errors = 0;

    // Apply all 16 input patterns, one every 5 time units
    for (i = 0; i < 16; i = i + 1) begin
      req = i;
      #5;

      // Reference model: written differently from the design on purpose
      exp_valid = |req;
      exp_idx   = req[3] ? 2'd3 :
                  req[2] ? 2'd2 :
                  req[1] ? 2'd1 : 2'd0;

      $display("[%0t] req=%b idx=%0d valid=%b", $time, req, idx, valid);

      // !== compares x and z as well, so an undriven output is caught
      if (idx !== exp_idx || valid !== exp_valid) begin
        $display("  ERROR: expected idx=%0d valid=%b", exp_idx, exp_valid);
        errors = errors + 1;
      end
    end

    if (errors == 0) $display("PASS: all 16 input patterns");
    else             $display("FAIL: %0d mismatches", errors);
    $finish;
  end

endmodule
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.