我正在尝试构建移动平均模块。它应该使用值的数量作为参数。
如何在一个时钟周期内使用tmp
- 或for
- 块来获取所有n gernerate
个寄存器的总和?
reg [WORDLEN - 1:0] tmp [SIZE - 1:0];
reg [WORDLEN + SIZE / 2 - 1:0] sum;
always @(posedge clk)
sum <= sum(tmp) // Like <= tmp[0] + tmp[1] + ... + tmp[SIZE-1]
答案 0 :(得分:1)
如果您首先拆分同步和组合部分,这样的循环往往更容易理解。首先,我们有一个组合循环,它可以展开到可配置数量的加法。然后暗示了结果的触发器。
integer i;
reg [WORDLEN + SIZE / 2 - 1:0] sum_comb;
always @* begin
sum_comb = 'd0;
for( i=0; i< SIZE; i=i+1) begin
sum_comb = sum_comb + tmp[i];
end
end
always @(posedge clk) begin
sum <= sum_comb;
end
答案 1 :(得分:0)
如果你使用SystemVerilog,你可以写:
always @(posedge clk)
sum <= tmp.sum;
以下是完整的示例代码:
module test;
parameter WORDLEN = 8;
parameter SIZE = 4;
reg [WORDLEN - 1:0] tmp [SIZE - 1:0];
reg [WORDLEN + SIZE / 2 - 1:0] sum;
logic clk = 0;
initial begin
tmp = '{ '{1}, '{4}, '{6}, '{7}};
forever begin
clk = ~clk;
#10;
tmp [0] = tmp[0] + 1; //Increment tmp[0] twice during each clock for testing
end
end
always @(posedge clk) begin
sum <= tmp.sum ;
$display ("sum(tmp) = sum(%p) = %d", tmp, sum) ;
end
endmodule
输出:
# sum(tmp) = sum('{1, 4, 6, 7}) = 18
# sum(tmp) = sum('{1, 4, 6, 9}) = 20
# sum(tmp) = sum('{1, 4, 6, 11}) = 22
# sum(tmp) = sum('{1, 4, 6, 13}) = 24
# sum(tmp) = sum('{1, 4, 6, 15}) = 26
# sum(tmp) = sum('{1, 4, 6, 17}) = 28