Friday, November 5, 2021

Linear Feedback Shift Register Verilog Code

Linear Feedback Shift Register is used to generate pseudo random numbers. It is used during DFT in VLSI and other applications like DSP. Let us see how to write a Verilog code to design it.

Example Design:

The Linear Feedback Shift Register as its name suggests, consists of a shift register with a linear feedback logic. Usually XOR gates are used.


The LFSR is initialized with certain initial values which generates a periodic sequence. The next state is always a linear function of its current state.
It is a self-starting logic and no inputs need to be fed to it except clock and reset.

LFSRs are used to implement a characteristic polynomial expression:

  • Degree of polynomial = number of FFs
  • Coefficient of xi = XOR feedback connection to FF i
From the above design, the characteristic polynomial is x4 + x3 + x + 1 (1 is always present).


Verilog Code:


module lfsr (clk,rst,pattern);

input clk,rst;
output [3:0] pattern;

reg q1, next_q1;
reg q2;
reg q3;
reg q4;

wire [3:0] pattern;
assign pattern = {q1,q2,q3,q4};

always@(posedge clk)
begin
 if(!rst) 
 begin
  q1 <= 1'b1;
  q2 <= 1'b1;
  q3 <= 1'b0;
  q4 <= 1'b0;
 end
 else
 begin
  q1 <= next_q1;
  q2 <= q1;
  q3 <= q2;
  q4 <= q3;
 end 
end

always@(*)
begin
 next_q1 = q1 ^ (q3 ^ q4);
end

endmodule


Testbench:


module lfsr_tb;

reg clk,rst;
wire [3:0] pattern;

lfsr dut (clk,rst,pattern);

always #5 clk = ~clk; 

initial begin
clk=1'b0; rst=1'b0;
#50 rst=1'b1;
end

endmodule


Simulation Waveform:



As seen in the waveform, as soon as reset is released, the LFSR starts a counting sequence which goes on until the reset is asserted again. Initial state of 1100 ('hC) was provided as per code.

LFSRs are useful to generate test patterns used for debugging purposes.
Different patterns can be generated based on the initial state of the Flip-Flops and by changing the position of the XOR gates.

No comments:

Post a Comment