同步fifo的Verilog实现

时间:2021-01-04 05:26:12

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='d8,DEPTH=7'd64;//假设位宽为8,深度为64,只考虑深度为2的幂次方的情况 reg [WIDTH- : ] ram [DEPTH- : ];//开辟存储区
reg [ : ] count; reg rp,wp;//定义读写指针 always@(posedge clk) begin   if(rst) begin
    wp <= ;
    rp <= ;
    dout <= ;
    empty <= ;
    full <= ;
    count <= ;
  end
  else begin
    case({rd_en,wr_en}) begin
      '00:count <= count;
      
      'b01:begin
        if(~full) begin
          ram(wp) <= din;
          wp <= wp + ;
          count <= count + ;
        end
      end       'b10:begin
        if(~empty) begin
          dout <= ram(rp);
          rp <= rp + ;
          count <= count - ;
        end  
      end       'b11:begin
        if(empty) begin
          ram(wp) <= din;
          wp <= wp + ;
          count <= count + ;
        end
        else begin
          ram(wp) <= din;
          wp <= wp + ;
          dout <= ram(rp);
          rp <= rp + ;
          count <= count;
        end
      end
    end
  end
end assign full = (count == 'd63) ? 1 : 0;
assign empty = (count == ) ? : ;

实现方法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='d8,DEPTH=7'd64;//假设位宽为8,深度为64,只考虑深度为2的幂次方的情况 reg [WIDTH- : ] ram [DEPTH- : ];//开辟存储区
reg [DEPTH- : ] count;
wire [WIDTH- : ] 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):; //写指针wp
always@(posedge clk)begin
  if(rst)begin
    wp <= ;
  end
  else if(wr_en & ~full) begin
    wp <= wp + ;
  end
  else if(full && (wr_en & rd_en)) begin
    wp <= wp + ;
  end
end //读指针rp
always@(posedge clk) begin
  if(rst) begin
    rp <= ;
  end
  else if(rd_en & ~empty) begin
    rp <= rp + ;
  end
end //满标志full
always@(posedge clk) begin
  if(rst) begin
    full <= ;
  end
  else if((wr_en & ~rd_en) && (wp == rp - )) begin
    full <= ;
  end
  else if(full & rd_en) begin
    full <=
  end
end //空标志empty
always@(posedge clk) begin
  if(rst) begin
    empty <= ;
  end
  else if(wr_en & empty) begin
    empty <= ;
  end
  else if((rd_en & ~wr_en) && (rp == wp - )) begin
    empty <= ;
  end
end