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

Sequential Logic with always: Testbench

Verilog Examples

Runnable example from the Sequential Logic with always tutorial (Testbench)

Open in IDE
design.v
// Modulo-10 Counter: Counts from 0 to 9, then rolls over
module mod10_counter (
	input clk, // Clock input
	input rstn, // Synchronous active-low reset
	output reg [3:0] out // 4-bit output (0-9, needs 4 bits)
);

	// Sequential logic: triggered on rising clock edge only
	always @ (posedge clk) begin
		if (!rstn) begin
			// Synchronous reset: counter resets to 0 on next clock edge
			// (Unlike asynchronous reset, this waits for clock edge)
			out <= 0;
		end else begin
			// Counter logic
			if (out == 9) // Check if reached maximum count
				out <= 0; // Roll over to 0
			else
				out <= out + 1; // Increment counter
		end
	end
endmodule
testbench.v
module tb;
	reg clk, rstn;
	wire [3:0] out; // Counter output (wire, not reg)

	// Instantiate the modulo-10 counter
	mod10_counter u0 (
		.clk(clk),
		.rstn(rstn),
		.out(out)
	);

	// Generate clock: 20ns period
	always #10 clk = ~clk;

	// Stimulus
	initial begin
		// Initialize signals
		{clk, rstn} <= 0;

		// Release reset after 10ns
		#10 rstn <= 1;

		// Let counter run for multiple cycles to observe rollover
		#450 $finish;
	end

	// Display counter value at each change
	initial begin
		$monitor("Time=%0t | rstn=%b out=%0d", $time, rstn, out);
	end

	// Waveform dump
	initial begin
		$dumpfile("mod10_counter.vcd");
		$dumpvars(0, tb);
	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.