module pingpang(
input clk,
input rst_n,
input [7:0] data_in,
output reg [7:0] data_out
);
reg [7:0] buffer0,buffer1;
reg write_flag; //write_flag=0 写buffer0, write_flag=1 写buffer1
reg read_flag; //read_flag=0 读buffer0, read_flag=1 读buffer1
reg state; //state=0 写buffer0,读buffer1 ; state=1 写buffer1,读buffer0
always@(posedge clk or negedge rst_n)
begin
if(!rst_n)
state <= 1'b0;
else
state <= !state;
end
always@(state) //状态输出
begin
case(state)
1'b0:
begin
write_flag <= 1'b0;
read_flag <= 1'b1;
end
1'b1:
begin
write_flag <= 1'b1;
read_flag <= 1'b0;
end
default:
begin
write_flag <= 1'b0;
read_flag <= 1'b1;
end
endcase
end
//写buffer
always@(posedge clk or negedge rst_n)
begin
if (!rst_n)
begin
buffer0 <= 8'b0;
buffer1 <= 8'b0;
end
else
begin
case(write_flag)
1'b0: buffer0 <= data_in;
1'b1: buffer1 <= data_in;
default:
begin
buffer0 <= 8'b0;
buffer1 <= 8'b0;
end
endcase
end
end
//读buffer
always@(posedge clk or negedge rst_n)
begin
if (!rst_n)
begin
data_out <= 8'b0;
end
else
begin
case(read_flag)
1'b0: data_out <= buffer0;
1'b1: data_out <= buffer1;
default: data_out <= 8'b0;
endcase
end
end
endmodule
2.2仿真代码
module pingpang_test;
reg clk;
reg rst_n;
reg [7:0] data_in;
wire [7:0] data_out;
initial
begin
clk = 1'b0;
rst_n = 1'b0;
#100
rst_n = 1'b1;
forever #10 clk = ~clk;
#100000 $stop;
end
always@(posedge clk or negedge rst_n)
begin
if(!rst_n)
data_in <= 8'b0;
else
data_in <= data_in + 1'b1;
end
pingpang u_pingpang(
.clk(clk),
.rst_n(rst_n),
.data_in(data_in),
.data_out(data_out)
);
endmodule
2.3仿真结果