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
// 4-bit Left Shift Register
module lshift_4b_reg (
 input d, // Serial data input (enters at LSB)
 input clk, // Clock signal
 input rstn, // Synchronous active-low reset
 output reg [3:0] out // 4-bit parallel output
);

 // Sequential logic: shift operation on clock edge
 always @ (posedge clk) begin
 if (!rstn) begin
 // Reset: clear all bits
 out <= 0;
 end else begin
 // Left shift operation:
 // - out[3] gets out[2] (MSB shifts out, lost)
 // - out[2] gets out[1]
 // - out[1] gets out[0]
 // - out[0] gets d (new bit enters at LSB)
 // Concatenation syntax: {out[2:0], d}
 out <= {out[2:0], d};
 end
 end
endmodule
testbench.v
module tb;
 reg clk, rstn, d;
 wire [3:0] out;
 integer i;

 // Instantiate the 4-bit left shift register
 lshift_4b_reg u0 (
 .d(d),
 .clk(clk),
 .rstn(rstn),
 .out(out)
 );

 // Generate clock
 always #10 clk = ~clk;

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

 // Release reset
 #10 rstn <= 1;

 // Shift in 20 random bits, synchronized to clock edge
 for (i = 0; i < 20; i=i+1) begin
 @(posedge clk) d <= $random; // Apply new bit at clock edge
 end

 // Wait a bit and finish
 #10 $finish;
 end

 // Monitor shift register value
 initial begin
 $monitor("Time=%0t | d=%b out=%b", $time, d, out);
 end

 // Waveform dump
 initial begin
 $dumpfile("lshift_4b.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.