Verilog For Loop For Array Multiplication

元气小坏坏 提交于 2019-12-13 02:37:14

问题


This may seem like a rather stupid question, but the transition from software to HDL's is sometimes rather frustrating initially!

My problem: I have an array multiplication I am trying to accomplish in Verilog. This is a multiplication of two arrays (point by point) which are of length 200 each. The following code worked fine in the testbench:

for (k=0; k<200; k=k+1)
    result <= result + A[k] * B[k]; 

But it doesn't even come close to working in the Verilog module. I thought the reason was because the operation should take place over many many clock cycles. Since it involves writing out 200 multiplications and 199 additions if I do it by hand (!), I was wondering if there was a trick in making the for loop work (and be synthesizable)?

Thanks,

Faisal.


回答1:


You don't want to use a for loop there, you want to use a block of clocked logic. For loops are only for describing parallel structures that don't feedback on themselves, they are only rarely useful and not for the same kinds of things you would use them for in a software program.

To do what you're trying to achieve, you should have a block like so:

always @(posedge clk or posedge reset)
    if (reset) begin
        result <= 0;
        k <= 0;
        result_done <= 0;
    end else begin
        result      <= result_done ? result : (result + A[k] * B[k]);
        k           <= result_done ?      k : k + 1;
        result_done <= result_done ?      1 : (k == 200); 
    end
end

This zeros the result on reset, adds A[k] * B[k] to a sum for 200 clocks, and then stops counting when k == 200 and asserts a 'done' signal.



来源:https://stackoverflow.com/questions/15037762/verilog-for-loop-for-array-multiplication

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!