FIFO一般用于通过两个不同时钟域的数据传输。一个水池有进和出两个通道,由于进出口水流不一致所以需要水池加以缓冲。堆栈也是相当于水池的作用。如果输入端不是连续的数据流,可以通过堆栈来调节使数据以稳定的状态输出。如果数据的输入时钟大于输出,那么总有一个时间使堆栈溢出则溢出的这部分会被舍弃。一般异步时钟需要同步,本文只是基于FIFO的基本原理编程。后续会对FIFO进行技术上的改进。
代码:
1 module FIFIO(input clkin,input write,input [7:0] datain,input clkout,input read,output reg [7:0] dataout,output reg empty,output reg full); 2 reg [7:0]stack[16383:0]; 3 reg [9:0]data_in_point=0; 4 reg [10:0] data_in_count=0; 5 reg [10:0]data_out_point=0; 6 reg data_in_num=0; 7 reg data_out_num=0; 8 always@(posedge clkin) 9 begin 10 11 case(data_in_num) 12 0:if(write) begin if((data_in_count-data_out_point)>10'h3fff) begin full<=1;data_in_num<=0;end else begin data_in_point<=data_in_count[9:0];data_in_num<=1;full<=0;end end 13 1:begin stack[data_in_point]<=datain;data_in_count<=data_in_count+1;data_in_num<=0;end 14 endcase 15 16 end 17 always@(posedge clkout) 18 begin 19 20 case(data_out_num) 21 0:if(read) begin if((data_in_count-data_out_point)==0) begin empty<=1;data_out_num<=0;end else begin empty<=0;data_out_num<=1;end end 22 1:begin dataout<=stack[data_out_point];data_out_num<=0;if(data_out_point==10'h3fff)data_out_point<=0;else data_out_point<=data_out_point+1; end 23 endcase 24 25 end 26 27 endmodule
验证代码:
1 module fifibench(); 2 reg clkin,clkout; 3 reg write,read; 4 wire empty,full; 5 wire [7:0]dataout; 6 reg [7:0] datain; 7 FIFIO M0 (.clkin(clkin),.write(write),.datain(datain),.clkout(clkout),.read(read),.dataout(dataout),.empty(empty),.full(full)); 8 initial begin clkin=0;clkout=0;write=0;read=0;datain=0;end 9 always begin #2 clkin=!clkin;end 10 always begin #18 clkout=!clkout;end 11 always begin #18 write=!write;end 12 always begin #100 read=!read;end 13 always begin #40 datain=datain+1; end 14 initial #10000 $stop; 15 endmodule