题解 | #同步FIFO#
同步FIFO
https://www.nowcoder.com/practice/e5e86054a0ce4355b9dfc08238f25f5f
`timescale 1ns/1ns /**********************************RAM************************************/ module dual_port_RAM #(parameter DEPTH = 16, parameter WIDTH = 8)( input wclk ,input wenc ,input [$clog2(DEPTH)-1:0] waddr ,input [WIDTH-1:0] wdata ,input rclk ,input renc ,input [$clog2(DEPTH)-1:0] raddr ,output reg [WIDTH-1:0] rdata ); reg [WIDTH-1:0] RAM_MEM [0:DEPTH-1]; always @(posedge wclk) begin if(wenc) RAM_MEM[waddr] <= wdata; end always @(posedge rclk) begin if(renc) rdata <= RAM_MEM[raddr]; end endmodule /**********************************SFIFO************************************/ module sfifo#( parameter WIDTH = 8, parameter DEPTH = 16 )( input clk , input rst_n , input winc , input rinc , input [WIDTH-1:0] wdata , output reg wfull , output reg rempty , output wire [WIDTH-1:0] rdata ); //首先定义waddr和raddr,比RAM的读写地址多一位,用于检测空满状态 reg [$clog2(DEPTH):0] waddr; reg [$clog2(DEPTH):0] raddr; //使用waddr和raddr检测读空和写满标志 always@(posedge clk or negedge rst_n) begin if(!rst_n) begin wfull <= 0; rempty <= 0; end else begin rempty <= (waddr == raddr) ? 1 : 0; wfull <= ((~waddr[$clog2(DEPTH)] == raddr[$clog2(DEPTH)]) && (waddr[$clog2(DEPTH)-1:0] == raddr[$clog2(DEPTH)-1:0])) ? 1 : 0; end end //根据winc和wfull信号使得waddr累加 always@(posedge clk or negedge rst_n) begin if(!rst_n) waddr <= 0; else if(winc & (~wfull)) waddr <= waddr + 1; else waddr <= waddr; end //根据rinc和rempty信号使得raddr累加 always@(posedge clk or negedge rst_n) begin if(!rst_n) raddr <= 0; else if(rinc & (~rempty)) raddr <= raddr + 1; else raddr <= raddr; end dual_port_RAM #( .WIDTH(WIDTH), .DEPTH(DEPTH) )d1( .wclk (clk), .wenc (winc&(~wfull)), //重点别搞错 .waddr (waddr[$clog2(DEPTH)-1:0]), .wdata (wdata), .rclk (clk), .renc (rinc&(~rempty)), //重点别搞错 .raddr (raddr[$clog2(DEPTH)-1:0]), .rdata (rdata) ); endmodule