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

Introduction to Verilog: Testbench code

Verilog Examples

Runnable example from the Introduction to Verilog tutorial (Testbench code)

Open in IDE
design.v
// "dff" is the name of this module

module dff  ( input   d,            // Inputs to the design should start with "input"
                      rstn,
                      clk,
              output reg q);         // Outputs of the design should start with "output"

  always @ (posedge clk) begin      // This block is executed at the positive edge of clk 0->1
    if (!rstn)                      // At the posedge, if rstn is 0 then q should get 0
      q <= 0;
    else
      q <= d;                       // At the posedge, if rstn is 1 then q should get d
  end
endmodule                           // End of module
testbench.v
module tb;
  reg   tb_clk, tb_d, tb_rstn;
  wire  tb_q;

  dff   dff0 (.clk (tb_clk), .d (tb_d), .rstn (tb_rstn), .q (tb_q));

  always #5 tb_clk = ~tb_clk;       // Clock toggles every 5 units: rising edges at 5, 15, 25 ...

  initial begin
    // Print a line every time rstn, d or q changes
    $monitor ("T=%0t rstn=%b d=%b q=%b", $time, tb_rstn, tb_d, tb_q);

    tb_rstn = 1'b0;                 // Reset asserted
    tb_clk  = 1'b0;
    tb_d    = 1'b0;

    #12 tb_rstn = 1'b1;             // Release reset at T=12
    #10 tb_d    = 1'b1;             // T=22
    #10 tb_d    = 1'b0;             // T=32
    #10 tb_d    = 1'b1;             // T=42
    #20 $finish;                    // End the simulation at T=62
  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.