Pseudo random generator

Way 1 : 



module pseudo_random_generator (

  input clk,

  input rst,

  input seed_en,

  input [7:0] seed,

  output reg [7:0] rand_out

);


reg [7:0] state;


always @ (posedge clk) begin

  if (rst) begin

    state <= 8'hFF;

    rand_out <= 8'hFF;

  end

  else if (seed_en) begin

    state <= seed;

    rand_out <= seed;

  end

  else begin

    state <= {state[6:0], state[7] ^ state[5] ^ state[4] ^ state[3]};

    rand_out <= state;

  end

end


endmodule


Way 2 : 



module lfsr (

  input clk,

  input rst,

  input seed_en,

  input [7:0] seed,

  output [7:0] rand_out

);


reg [7:0] temp_q;


always @ (posedge clk) begin

  if (rst) begin

    temp_q <= 8'h00;

  end

  else if (seed_en) begin

    temp_q <= seed;

  end

  else begin

    temp_q <= {temp_q[6:0], temp_q[7] ^ temp_q[5] ^ temp_q[4] ^ temp_q[3]}; 

  end

end

assign rand_out = temp_q;


endmodule



Way 3 : 



module lfsr (

  input clk,

  input rst,

  input seed_en,

  input [7:0] seed,

  output [7:0] rand_out

);


  reg [7:0] temp_q;

  wire bit_gen;


always @ (posedge clk) begin

  if (rst) begin

    temp_q <= 8'h00;

  end

  else if (seed_en) begin

    temp_q <= seed;

  end

  else begin

    temp_q <= {temp_q[6:0], bit_gen};

  end

end

assign rand_out = temp_q;

  assign bit_gen = temp_q[7] ^ temp_q[5] ^ temp_q[4] ^ temp_q[3];


endmodule


Testbench for All : 


module lfsr_tb;


reg clk, rst, seed_en;

reg [7:0] seed;

wire [7:0] rand_out;


lfsr dut (

  .clk(clk),

  .rst(rst),

  .seed_en(seed_en),

  .seed(seed),

  .rand_out(rand_out)

);


initial begin

  clk = 0;

  forever #5 clk = ~clk;

end


initial begin

  rst = 1;

  seed_en = 0;

  seed = 8'h5A; // set seed to 01011010

  #10 rst = 0;

  #100 $finish;

end


initial begin

  seed_en <= 0;

  #10 seed_en <= 1;

  #10 seed_en <= 0;

end

  

  initial begin 

    $monitor ("seed = %b rand_out = %b",seed,rand_out);

    $dumpvars();

    $dumpfile("dump.vcd");

  end


endmodule


Post a Comment (0)
Previous Post Next Post