Friday, May 18, 2012

Pseudo Random Sequence Generator in Verilog


Pseudo Random Sequence is widely used in spread spectrum communication, to spread and de-spread the information sequence. The following diagram shows a PN sequence generator which has 3 memory elements, leads to processing gain 7 (2^3 - 1). According to the diagram, if the initial state is all zero, then the sequence will also be all zeros which is not usable.




Behavioural Model

module PNSeqGen(
    input clk, reset,
    output s3
    );
reg s1, s2, s3;
wire s0;
// MODULO 2 ADDITION
assign s0 = s1 ^ s3;
// STATE MACHINE
always @ (posedge clk or reset) begin
// INITIAL STATE SHOULDN'T BE 000 => 100
if(reset) begin
s1 <= 1;
s2 <= 0;
s3 <= 0;
end else begin
s1 <= s0;
s2 <= s1;
s3 <= s2;
end
end
endmodule

Test Bench

`timescale 1ns / 1ps
module Test_PNSeqGen;
// Inputs
reg clk;
reg reset;
// Outputs
wire s3;
// Instantiate the Unit Under Test (UUT)
PNSeqGen uut (
.clk(clk), 
.reset(reset), 
.s3(s3)
);
initial begin
// Initialize Inputs
clk = 0;
reset = 0;
// Wait 100 ns for global reset to finish
#100;
// Add stimulus here
#10 reset = 1;
#10 reset = 0;
#200 $finish;
end
always begin
#5 clk = ~clk;
end
// PRINT SEQUENCE
always @ (posedge clk) $write("%b",s3);      
endmodule

Output

001110100111010011101

Tuesday, May 8, 2012

4 Bit Priority Encoder in Verilog


Priority Encoder is an encoder circuit that includes a priority function. The operation is such that if two or more inputs are equal to 1 at the same time, the input having the highest priority will take precedence. 
Here, the priority decreases from right to left in the input. D[3] has the highest priority. V indicate the validity of the input (atleast one input should be 1) and the Y gives the output.(01 means 1, 10 means 2 like that...)


















Behavioural Model : 4 Bit Priority Encoder

module PriorityEncoder_4Bit(
    input [0:3] D,
    output [1:0] Y,
    output V
    );
reg [1:0] Y;
reg V;
always @(D)
begin
Y[1] <= D[2] | D[3];
Y[0] <= D[3] | D[1] & ~D[2];
V = D[0] | D[1] | D[2] | D[3];
end
endmodule

Test Bench : 4 Bit Priority Encoder

module PriorityEncoder_4Bit_Test;
// Inputs
reg [3:0] D;
// Outputs
wire [1:0] Y;
wire V;
// Instantiate the Unit Under Test (UUT)
PriorityEncoder_4Bit uut (
.D(D), 
.Y(Y), 
.V(V)
);
initial begin
// Initialize Inputs
D = 0;
// Wait 100 ns for global reset to finish
#100;        
// Add stimulus here
#10 D = 4'b0000;
#10 D = 4'b1000;
#10 D = 4'b0100;
#10 D = 4'b0010;
#10 D = 4'b0001;
#10 D = 4'b1010;
#10 D = 4'b1111;
end
initial begin
$monitor("time=",$time,, "D=%b : Y=%b V=%b",D,Y,V);
end      
endmodule

Simulation Results

time= 000, D=0000 : Y=00 V=0
time= 120, D=1000 : Y=00 V=1
time= 130, D=0100 : Y=01 V=1
time= 140, D=0010 : Y=10 V=1
time= 150, D=0001 : Y=11 V=1
time= 160, D=1010 : Y=10 V=1
time= 170, D=1111 : Y=11 V=1