同步FIFO与异步FIFO代码
时间: 2024-01-09 13:42:48 浏览: 110
同步FIFO与异步FIFO的Verilog实现(附源代码和测试代码).doc
同步 FIFO 的 Verilog 代码:
```
module sync_fifo (
input clk, // 时钟信号
input reset, // 复位信号
input write_en, // 写入使能信号
input read_en, // 读取使能信号
input [DATA_WIDTH-1:0] data_in, // 写入数据
output reg full, // FIFO 满信号
output reg empty, // FIFO 空信号
output reg [DATA_WIDTH-1:0] data_out // 读取数据
);
parameter DEPTH = 8; // FIFO 的深度
parameter DATA_WIDTH = 8; // 数据宽度
reg [DEPTH-1:0] mem; // FIFO 存储器
reg [DEPTH-1:0] read_ptr; // 读指针
reg [DEPTH-1:0] write_ptr; // 写指针
// 写入数据
always @(posedge clk) begin
if (reset) begin
write_ptr <= 'd0;
full <= 1'b0;
end else if (write_en && !full) begin
mem[write_ptr] <= data_in;
write_ptr <= write_ptr + 1;
if (write_ptr == DEPTH-1) begin
write_ptr <= 'd0;
end
if (write_ptr == read_ptr) begin
full <= 1'b1;
end
end
end
// 读取数据
always @(posedge clk) begin
if (reset) begin
read_ptr <= 'd0;
empty <= 1'b1;
end else if (read_en && !empty) begin
data_out <= mem[read_ptr];
read_ptr <= read_ptr + 1;
if (read_ptr == DEPTH-1) begin
read_ptr <= 'd0;
end
if (read_ptr == write_ptr) begin
empty <= 1'b1;
end
end
end
// FIFO 状态
always @(posedge clk) begin
if (reset) begin
full <= 1'b0;
empty <= 1'b1;
end else begin
if (write_en && !full) begin
empty <= 1'b0;
end
if (read_en && !empty) begin
full <= 1'b0;
end
end
end
endmodule
```
异步 FIFO 的 Verilog 代码:
```
module async_fifo (
input clk, // 时钟信号
input reset, // 复位信号
input write_en, // 写入使能信号
input read_en, // 读取使能信号
input [DATA_WIDTH-1:0] data_in, // 写入数据
output reg full, // FIFO 满信号
output reg empty, // FIFO 空信号
output reg [DATA_WIDTH-1:0] data_out // 读取数据
);
parameter DEPTH = 8; // FIFO 的深度
parameter DATA_WIDTH = 8; // 数据宽度
reg [DEPTH-1:0] mem; // FIFO 存储器
reg [DEPTH-1:0] read_ptr; // 读指针
reg [DEPTH-1:0] write_ptr; // 写指针
// 写入数据
always @(posedge clk) begin
if (reset) begin
write_ptr <= 'd0;
full <= 1'b0;
end else if (write_en && !full) begin
mem[write_ptr] <= data_in;
write_ptr <= write_ptr + 1;
if (write_ptr == DEPTH-1) begin
write_ptr <= 'd0;
end
if (write_ptr == read_ptr) begin
full <= 1'b1;
end
end
end
// 读取数据
always @(posedge clk) begin
if (reset) begin
read_ptr <= 'd0;
empty <= 1'b1;
end else if (read_en && !empty) begin
data_out <= mem[read_ptr];
read_ptr <= read_ptr + 1;
if (read_ptr == DEPTH-1) begin
read_ptr <= 'd0;
end
if (read_ptr == write_ptr) begin
empty <= 1'b1;
end
end
end
// 异步 FIFO 读写指针更新
always @(posedge clk) begin
if (reset) begin
write_ptr <= 'd0;
read_ptr <= 'd0;
end else begin
if (write_en) begin
write_ptr <= write_ptr + 1;
if (write_ptr == DEPTH-1) begin
write_ptr <= 'd0;
end
end
if (read_en) begin
read_ptr <= read_ptr + 1;
if (read_ptr == DEPTH-1) begin
read_ptr <= 'd0;
end
end
end
end
// FIFO 状态
always @(posedge clk) begin
if (reset) begin
full <= 1'b0;
empty <= 1'b1;
end else begin
if (write_en && !full) begin
empty <= 1'b0;
end
if (read_en && !empty) begin
full <= 1'b0;
end
end
end
endmodule
```
阅读全文