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
// JK Flip-Flop with asynchronous active-low reset
module jk_ff (
 	input j, 			// Input J: when high with K low, sets Q to 1
 	input k,  			// Input K: when high with J low, resets Q to 0
 	input rstn, 		// Active-low async reset: immediately clears Q
 	input clk,  		// Clock: triggers state changes on rising edge
 	output reg q  		// Output Q: stored state value
);

 	// Sequential logic: sensitive to clock edge and reset edge
 	always @ (posedge clk or negedge rstn) begin
 		if (!rstn) begin
 			// Asynchronous reset: Q becomes 0 immediately when rstn goes low
 			// This happens independent of clock edge
 			q <= 0;
 		end else begin
			// JK flip-flop logic (evaluated only on rising clock edge):
			// j=0,k=0: hold current value (q unchanged)
			// j=0,k=1: reset Q to 0
			// j=1,k=0: set Q to 1
			// j=1,k=1: toggle Q
			// Boolean expression: Q_next = (J & ~Q) | (~K & Q)
			q <= (j & ~q) | (~k & q);
 		end
 	end
endmodule
testbench.v
module tb;
	// Declare testbench variables
	reg j, k, rstn, clk;
	wire q; 				// Output from DUT (must be wire)
	integer i;
	reg [2:0] dly;

	// Generate clock: 50% duty cycle, 20ns period (50 MHz)
	always #10 clk = ~clk;

	// Instantiate the JK flip-flop design under test
	jk_ff u0 (
		.j(j),
		.k(k),
		.clk(clk),
		.rstn(rstn),
		.q(q)
	);

	// Stimulus generation
	initial begin
		// Initialize all inputs to zero at time 0
		{j, k, rstn, clk} <= 0;

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

		// Apply random stimulus: 10 iterations
		for (i = 0; i < 10; i = i+1) begin
			dly = $random; // Random delay (0-7 ns)
			#(dly) j <= $random; // Random J input
			#(dly) k <= $random; // Random K input
		end

		// Let simulation run a bit longer, then finish
		#20 $finish;
	end

	// Monitor output changes
	initial begin
		$monitor("Time=%0t | rstn=%b j=%b k=%b q=%b",
		$time, rstn, j, k, q);
	end

	// Waveform dumping for analysis
	initial begin
		$dumpfile("jk_ff.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.