1
votes

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

1 Answers

5
votes

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.