0

I'm getting familiar with Verilog doing small exercises and right now I am trying to implement a linear feedback shift register.

I'm trying to model the flipflop chain inside an always block using a for-loop, yet iverilog keeps giving me the error register ``i'' unknown in lfsr where "i" is the iteration variable and lfsr is my module.

always @(posedge clk or negedge res_n) begin
    if(res_n == 0) begin
        // ... implement reset
    end

    else begin
        flops[0] <= input_wire;
        for (i = 0; i <= width-2; i = i+1) begin
            flops[i+1] <= flops[i];
        end
    end

end

Could somebody help me out?

Thanks.

Jersey
  • 423
  • 4
  • 13

2 Answers2

1

You should declare the variable i first, or i will be regarded as an register with no specification. And this will let the compiler returns the unknown register error.

Declare i as an integer outside the for code block as below:

integer i;
Haotian Liu
  • 886
  • 5
  • 19
  • That did it, indeed. It's curious that the Verilog tutorials I read did not tell me to do so. Is this something that's compiler dependent? – Jersey Jan 30 '17 at 10:07
  • @Jersey I am not sure whether this is compiler dependent. But for my understand of Verilog, in order not to make weird or mysterious errors or bugs, you'd better specify every register, wire, or variable as much as possible. – Haotian Liu Jan 30 '17 at 10:08
  • 1
    It's not compiler dependent: you do need to declare the loop variable in a `for` loop. – Matthew Taylor Jan 30 '17 at 10:27
1

You need to declare the loop variable in a for loop, as another answer has stated. However, this does not need to be outside the always block. Instead, if (and only if) you label a begin...end block, you can declare the loop variable inside it. This declcartion has to be first inside the block. This has the advantage of better encapsulation:

always @(posedge clk or negedge res_n) begin
    if(res_n == 0) begin
        // ... implement reset
    end

    else begin : SOME_NAME
//                   ^
//                   |
//             this is a label

        integer i;     // declaring i here results in better encapsulation
                       // the declaration HAS to be before "imperative" (ie executable) code

        flops[0] <= input_wire;
        for (i = 0; i <= width-2; i = i+1) begin
            flops[i+1] <= flops[i];
        end
    end

end
Matthew Taylor
  • 13,365
  • 3
  • 17
  • 44