FIFO是一种先进先出的数据缓存器,他与普通存储器相比:
优点:没有外部读写地址线,这样使用起来非常简单;
缺点:只能顺序写入数据,顺序的读出数据, 其数据地址由内部读写指针自动加1完成,不能像普通存储器那样可以由地址线决定读取或写入某个指定的地址。
根据FIFO工作的时钟域,可以将FIFO分为同步FIFO和异步FIFO。同步FIFO是指读时钟和写时钟为同一个时钟。在时钟沿来临时同时发生读写操作。异步FIFO是指读写时钟不一致,读写时钟是互相独立的。
FIFO设计的难点在于怎样判断FIFO的空/满状态。为了保证数据正确的写入或读出,而不发生溢出或读空的状态出现,必须保证FIFO在满的情况下不能进行写操作,在空的状态下不能进行读操作。
因此,怎样判断FIFO的满/空就成了FIFO设计的核心问题。
实现方法1:
module fifo( input clk, input rst, input din, input wr_en, input rd_en, output reg dout, output empty, output full ); parameter WIDTH=4'd8,DEPTH=7'd64;//假设位宽为8,深度为64,只考虑深度为2的幂次方的情况 reg [WIDTH-1 : 0] ram [DEPTH-1 : 0];//开辟存储区 reg [5 : 0] count; reg rp,wp;//定义读写指针 always@(posedge clk) begin if(rst) begin wp <= 0; rp <= 0; dout <= 0; empty <= 1; full <= 0; count <= 0; end else begin case({rd_en,wr_en}) begin 2'00:count <= count; 2'b01:begin if(~full) begin ram(wp) <= din; wp <= wp + 1; count <= count + 1; end end 2'b10:begin if(~empty) begin dout <= ram(rp); rp <= rp + 1; count <= count - 1; end end 2'b11:begin if(empty) begin ram(wp) <= din; wp <= wp + 1; count <= count + 1; end else begin ram(wp) <= din; wp <= wp + 1; dout <= ram(rp); rp <= rp + 1; count <= count; end end end end end assign full = (count == 6'd63) ? 1 : 0; assign empty = (count == 0) ? 1 : 0;
实现方法2:
module fifo( input clk, input rst, input din, input wr_en, input rd_en, output dout, output reg empty, output reg full ); parameter WIDTH=4'd8,DEPTH=7'd64;//假设位宽为8,深度为64,只考虑深度为2的幂次方的情况 reg [WIDTH-1 : 0] ram [DEPTH-1 : 0];//开辟存储区 reg [DEPTH-1 : 0] count; wire [WIDTH-1 : 0] dout,din;//读写数据 reg rp,wp;//定义读写指针 //写入数据din always@(posedge clk) begin if((wr_en & ~full) || (full & wr_en & rd_en)) begin ram(wp) <= din; end end //读出数据dout assign dout = (rd_en & ~empty)?ram(rp):0; //写指针wp always@(posedge clk)begin if(rst)begin wp <= 0; end else if(wr_en & ~full) begin wp <= wp + 1; end else if(full && (wr_en & rd_en)) begin wp <= wp + 1; end end //读指针rp always@(posedge clk) begin if(rst) begin rp <= 0; end else if(rd_en & ~empty) begin rp <= rp + 1; end end //满标志full always@(posedge clk) begin if(rst) begin full <= 0; end else if((wr_en & ~rd_en) && (wp == rp - 1)) begin full <= 1; end else if(full & rd_en) begin full <= 0 end end //空标志empty always@(posedge clk) begin if(rst) begin empty <= 1; end else if(wr_en & empty) begin empty <= 0; end else if((rd_en & ~wr_en) && (rp == wp - 1)) begin empty <= 1; end end