题解 | #同步FIFO#
同步FIFO
https://www.nowcoder.com/practice/3ece2bed6f044ceebd172a7bf5cfb416
`timescale 1ns/1ns /**********************************RAM************************************/ module dual_port_RAM #(parameter DEPTH = 16, parameter WIDTH = 8)( input wclk ,input wenc ,input [$clog2(DEPTH)-1:0] waddr //深度对2取对数,得到地址的位宽。 ,input [WIDTH-1:0] wdata //数据写入 ,input rclk ,input renc ,input [$clog2(DEPTH)-1:0] raddr //深度对2取对数,得到地址的位宽。 ,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 ); reg [$clog2(DEPTH):0] waddr, raddr; always@(posedge clk, negedge rst_n) begin if(~rst_n) begin rempty <= 0; wfull <= 0; end else begin rempty <= (waddr == raddr); wfull <= (waddr[$clog2(DEPTH)] != raddr[$clog2(DEPTH)]) && (waddr[$clog2(DEPTH)-1:0] == raddr[$clog2(DEPTH)-1:0]); end end always@(posedge clk, negedge rst_n) if(~rst_n) raddr <= 0; else if(rinc) raddr <= raddr + 1; always@(posedge clk, negedge rst_n) if(~rst_n) waddr <= 0; else if(winc) waddr <= waddr + 1; dual_port_RAM #( .DEPTH(DEPTH), .WIDTH(WIDTH)) fifo( .wclk(clk), .wenc(winc), .waddr(waddr[$clog2(DEPTH)-1:0]), .wdata(wdata), .rclk(clk), .renc(rinc), .raddr(raddr[$clog2(DEPTH)-1:0]), .rdata(rdata) ); endmodule
用“套圈”的思想判断空/满,因此读写地址要多取一位。