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
