module rand_gen
(
input clock,
input enable,
input reset,
output reg [7:0] rnd
);
localparam LFSR_LEN = 128;
reg [LFSR_LEN-1:0] random;
wire feedback = random[127] ^ random[125] ^ random[100] ^ random[98];
reg [2:0] bit_idx;
always @(posedge clock) begin
if (reset) begin
random <= {LFSR_LEN{4'b0101}};
bit_idx <= 0;
rnd <= 0;
end else if (enable) begin
random <= {random[LFSR_LEN-2:0], feedback};
rnd[bit_idx] <= feedback;
bit_idx <= bit_idx + 1;
end
end
endmodule
module rand_gen_tb;
reg clock;
reg reset;
reg enable;
wire [7:0] rnd;
integer fd;
rand_gen inst (
.clock(clock),
.enable(enable),
.reset(reset),
.rnd(rnd)
);
initial begin
clock = 0;
reset = 1;
enable = 0;
fd = $fopen("./sim_out/rand_gen.txt", "w");
# 10 reset = 0;
enable = 1;
# 10000000 $finish;
end
always begin
#1 clock <= ~clock;
end
always @(posedge clock) begin
if (enable) begin
$fwrite(fd, "%d\n", rnd);
end
end
endmodule
我们看到代码从两个方面保证随机:1,整个128BIT的移位链不断移入新的产生的随机位。2,同时在输出的位数中的轮流加入新的随机位。
上述代码输出的是8位,实际输出可以达到128位。修改位数需要注意bit_idx的位数要对应输出的位数。比如输出32位,bit_idx就要设置成5.