Contact me for VHDL or Verilog projects and assignments

Monday, March 8, 2010

How to do a clocked 'for' loop

Consider the following code.The expected output is 0,1,...,9,1,2....,10,2,3,....,11,3,4,....12 etc and they change at every positive edge of the clock cycle.The final value will be 18.But if I run the program I will get a constant value 18 as the output at the first positive edge of clock cycle.

process(clk)
begin
if (clk'event and clk = '1') then
for x in 0 to 9 loop
   for y in 0 to 9 loop
       output <= x + y;
   end loop;
end loop;
end if;
end process;

The above code shows that it is not possible to write a clocked function using 'for' loop.So what do we do in such cases.We can use two cascaded if statements in such case to get the functionality of a 'for' loop.The following code illustrates the concept.

--I hope the code is self explanatory.
process(clk)
begin
if(clk'event and clk='1') then
if (x<10) then
  if(y<10) then
      --write your code here..
      output <= x+y;    
        y<=y+1;  --increment the pointer 'j'.
  end if;
  if(y=10) then
   x<=x+1;   --increment the pointer 'i' when j reaches its maximum value.
   y<=0;    --reset j to zero.
  end if;
end if;   ----End of "if (i<10) then"
end if;   --End of "if(clk'event and clk='1') then"
end process;

Note :- Use this cascaded if's,only if you want a clocked 'for' loop.Otherwise stick to the conventional use of 'for' loops.They are easy to use and easy to understand.

6 comments:

  1. Very informative and helpful! I'm doing FPGA programming and was frustrated about the loop.

    Thanks!

    ReplyDelete
  2. Can u pls tell me how to do it for three nested loops ?

    ReplyDelete
  3. Hi mate, thanks for the tutorial! it was very insightful. this solution will make inferred latches thought right? for a FSM there is no way to avoid it?

    ReplyDelete

Related Posts with Thumbnails