A Verilog module for a 4-bit shift register with a testbench. The shift register will be a simple serial-in, serial-out design with a clock, reset, and data input.
module shift_register (
input wire clk, // Clock input
input wire reset, // Synchronous reset
input wire data_in, // Serial data input
output reg data_out, // Serial data output
output reg [3:0] reg_content // Current register content
);
// 4-bit shift register
reg [3:0] shift_reg;
always @(posedge clk) begin
if (reset) begin
shift_reg <= 4'b0000;
data_out <= 1'b0;
end
else begin
// Shift left and insert new data
shift_reg <= {shift_reg[2:0], data_in};
data_out <= shift_reg[3];
end
end
// Assign register content to output
always @(*) begin
reg_content = shift_reg;
end
endmodule
module shift_register_tb;
// Testbench signals
reg clk;
reg reset;
reg data_in;
wire data_out;
wire [3:0] reg_content;
// Instantiate the shift register
shift_register uut (
.clk(clk),
.reset(reset),
.data_in(data_in),
.data_out(data_out),
.reg_content(reg_content)
);
// Clock generation
initial begin
clk = 0;
forever #5 clk = ~clk; // 100MHz clock (10ns period)
end
// Test stimulus
initial begin
// Initialize signals
reset = 1;
data_in = 0;
#20;
// Release reset
reset = 0;
#10;
// Test case 1: Shift in 1011
data_in = 1; #10;
data_in = 0; #10;
data_in = 1; #10;
data_in = 1; #10;
// Test case 2: Shift in 0101
data_in = 0; #10;
data_in = 1; #10;
data_in = 0; #10;
data_in = 1; #10;
// Apply reset
reset = 1; #10;
reset = 0; #10;
// Test case 3: Shift in 1111
data_in = 1; #40;
// End simulation
#20;
$finish;
end
// Monitor outputs
initial begin
$monitor("Time=%0t reset=%b data_in=%b data_out=%b reg_content=%b",
$time, reset, data_in, data_out, reg_content);
end
endmodule
This implementation includes:
- A 4-bit shift register module (shift_register.v) that:
- Shifts data left on each positive clock edge
- Has synchronous reset
- Outputs both the serial data and the entire register content
- A testbench (shift_register_tb.v) that:
- Generates a 100MHz clock
- Tests various input sequences (1011, 0101, 1111)
- Includes reset testing
- Monitors and displays signal values
To simulate:
- Compile both files in a Verilog simulator (e.g., ModelSim, Vivado)
- Run the simulation
- The $monitor statement will display the state of signals at each time step
The testbench exercises the shift register by:
- Applying reset
- Shifting in different bit patterns
- Testing reset functionality
- Verifying serial output and register content
Your comments will be moderated before it appears here.