An LFSR is a simple circuit that generates a sequence of bits that looks random. It is used to create patterns for testing or encryption.
0
0
Linear Feedback Shift Register (LFSR) in Verilog
Introduction
To generate pseudo-random numbers in hardware.
To create test patterns for checking digital circuits.
To scramble data for simple encryption.
To simulate noise or random signals in designs.
Syntax
Verilog
module lfsr(
input clk,
input reset,
output reg [3:0] q
);
wire feedback = q[3] ^ q[2];
always @(posedge clk or posedge reset) begin
if (reset)
q <= 4'b0001;
else
q <= {q[2:0], feedback};
end
endmoduleThe LFSR uses XOR of selected bits as feedback.
The register shifts bits on each clock cycle, adding the feedback bit at the end.
Examples
Example of feedback using bits 3 and 1 for a 4-bit LFSR.
Verilog
wire feedback = q[3] ^ q[1]; q <= {q[2:0], feedback};
Resetting the LFSR to a different initial value.
Verilog
if (reset) q <= 4'b1000; else q <= {q[2:0], feedback};
Sample Program
This program creates a 4-bit LFSR and a testbench that runs it. The output shows the LFSR state changing every clock cycle.
Verilog
module lfsr(
input clk,
input reset,
output reg [3:0] q
);
wire feedback = q[3] ^ q[2];
always @(posedge clk or posedge reset) begin
if (reset)
q <= 4'b0001;
else
q <= {q[2:0], feedback};
end
endmodule
// Testbench
module testbench();
reg clk = 0;
reg reset = 1;
wire [3:0] q;
lfsr uut(.clk(clk), .reset(reset), .q(q));
always #5 clk = ~clk; // Clock toggles every 5 time units
initial begin
$monitor($time, " q = %b", q);
#10 reset = 0; // Release reset after 10 time units
#100 $finish;
end
endmoduleOutputSuccess
Important Notes
Make sure the initial value (seed) is not zero; otherwise, the LFSR will stay at zero.
The choice of bits for feedback affects the length of the sequence before it repeats.
Summary
An LFSR generates a sequence of bits using shift and XOR feedback.
It is useful for pseudo-random number generation and testing hardware.
Reset sets the starting value, and feedback taps control the sequence.