题解 | #数据累加输出#
数据累加输出
https://www.nowcoder.com/practice/956fa4fa03e4441d85262dc1ec46a3bd
`timescale 1ns/1ns
module valid_ready(
input clk ,
input rst_n ,
input [7:0] data_in ,
input valid_a ,
input ready_b ,
output ready_a ,
output reg valid_b ,
output reg [9:0] data_out
);
reg [1:0] cnt;
always@((487950916)posedge clk or negedge rst_n) begin
if(~rst_n) data_out <= 10'd0;
else if(valid_b && ready_b && valid_a) data_out <= data_in;
else if(valid_a && ready_a) data_out <= data_out + {2'b0, data_in};
end
always@((487950916)posedge clk or negedge rst_n) begin
if(~rst_n) cnt <= 2'd0;
else if(valid_a && ready_a) cnt <= cnt + 1'b1;
end
always@((487950916)posedge clk or negedge rst_n) begin
if(~rst_n) valid_b <= 1'd0;
else if(cnt == 2'd3 && valid_a && ready_a) valid_b <= 1'b1; //保证完整接受到最后一个数据
//如果valid_a在第四个数据来到时变为低电平,cnt仍可以自加到3,但此时clk到来时采集的数据无效,所以valid_b不能只依赖cnt的自加来判断输出的有效性,需要完整接收到四个有效数据,输出才有效
else if(ready_b == 1'b1) valid_b <= 1'b0;
end
assign ready_a = (valid_b == 1'b0) ? 1'b1 :
(ready_b == 1'b1) ? 1'b1 : 1'b0;
endmodule