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

Ripple Counter: Testbench

Verilog Examples

Runnable example from the Verilog Ripple Counter tutorial (Testbench)

Open in IDE
design.v
module dff (   input d,
               input clk,
               input rstn,
               output reg q,
               output qn);
   always @ (posedge clk or negedge rstn)
      if (!rstn)
         q <= 0;
      else
         q <= d;

   assign qn = ~q;    // Inverted output, used both for feedback and as the count
endmodule

module ripple ( input clk,
                input rstn,
                output [3:0] out);
   wire  q0;
   wire  qn0;
   wire  q1;
   wire  qn1;
   wire  q2;
   wire  qn2;
   wire  q3;
   wire  qn3;

   // Stage 0: clocked by the system clock, toggles on every rising edge
   dff   dff0 ( .d (qn0),
                .clk (clk),
                .rstn (rstn),
                .q (q0),
                .qn (qn0));

   // Stage 1: clocked by q0, toggles when q0 rises
   dff   dff1 ( .d (qn1),
                .clk (q0),
                .rstn (rstn),
                .q (q1),
                .qn (qn1));

   // Stage 2: clocked by q1
   dff   dff2 ( .d (qn2),
                .clk (q1),
                .rstn (rstn),
                .q (q2),
                .qn (qn2));

   // Stage 3: clocked by q2
   dff   dff3 ( .d (qn3),
                .clk (q2),
                .rstn (rstn),
                .q (q3),
                .qn (qn3));

   // The q outputs count down, so their inverses count up
   assign out = {qn3, qn2, qn1, qn0};

endmodule
testbench.v
module tb_ripple;
   reg clk;
   reg rstn;
   wire [3:0] out;

   ripple r0   (  .clk (clk),
                  .rstn (rstn),
                  .out (out));

   always #5 clk = ~clk;      // 10 ns period

   initial begin
      $monitor ("[%0t] rstn=%0b out=0x%0h", $time, rstn, out);

      rstn <= 0;              // Assert reset: out = 4'hF
      clk <= 0;

      repeat (4) @ (posedge clk);
      rstn <= 1;              // Release reset

      repeat (25) @ (posedge clk);   // Count through more than one full cycle
      $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.