对其他网友的代码进行了改进纠正,使代码更加完整,并用vivado2020.1进行了仿真测试
源代码:
`timescale 1ns/1ps
module test (clk,rst,w_en,r_en,w_data,r_data,fifo_empty,fifo_full,w_ptr,r_ptr,cnt
);
parameter width =4 ;
parameter depth =8 ;
input clk,rst,w_en,r_en;
input [width-1:0]w_data;
output reg [width-1:0]r_data;
output fifo_empty,fifo_full;
output reg [6:0]w_ptr,r_ptr;
output reg [6:0]cnt;
reg [width-1:0]ram[depth-1:0];
always @(posedge clk or negedge rst) begin
if(!rst)begin
r_data<=0;
w_ptr<=0;
r_ptr<=0;
cnt<=0;
end
else begin
case({w_en,r_en})
2'b00:cnt<=cnt;
2'b01:begin//读
cnt<=(!fifo_empty)?cnt-1:cnt;
r_data<=(!fifo_empty)?ram[r_ptr]:r_data;
r_ptr<=(!fifo_empty)?((r_ptr==(depth-1))?0:r_ptr+1):r_ptr;
end
2'b10:begin//写
cnt<=(!fifo_full)?cnt+1:cnt;
ram[w_ptr]<=(!fifo_full)?w_data:ram[w_ptr];
w_ptr<=(!fifo_full)?((w_ptr==(depth-1))?0:w_ptr+1): w_ptr;
end
2'b11:begin
if(cnt==0)begin
r_data<=w_data;
end
else begin
r_data<=(!fifo_empty)?ram[r_ptr]:r_data;
r_ptr<=(!fifo_empty)?((r_ptr==(depth-1))?0:r_ptr+1):r_ptr;
ram[w_ptr]<=(!fifo_full)?w_data:ram[w_ptr];
w_ptr<=(!fifo_full)?((w_ptr==(depth-1))?0:w_ptr+1): w_ptr;
end
end
endcase
end
end
assign fifo_empty=(cnt==0);
assign fifo_full=(cnt==depth);
endmodule
测试代码:
`timescale 1ns / 1ps
module test_sim;
parameter width =4 ;
parameter depth =8 ;
reg clk,rst,w_en,r_en;
reg [width-1:0]w_data;
wire [width-1:0]r_data;
wire fifo_empty,fifo_full;
wire [6:0]cnt;
wire [6:0]w_ptr,r_ptr;
always #10 clk=~clk;
always @(posedge clk) begin
w_data<={$random%16};
end
initial begin
clk=0;
rst=1;
w_data=0;
{w_en,r_en}=2'b00;
#4 rst=0;
#10 rst=1;
#200 {w_en,r_en}=2'b10;
#200 {w_en,r_en}=2'b01;
#100 {w_en,r_en}=2'b11;
// #200 $stop;
end
test m1(
.clk(clk),
.rst(rst),
.w_en(w_en),
.r_en(r_en),
.w_data(w_data),
.r_data(r_data),
.fifo_empty(fifo_empty),
.fifo_full(fifo_full),
.w_ptr(w_ptr),
.r_ptr(r_ptr),
.cnt(cnt)
);
endmodule
vivado2020仿真结果