Search code examples
for-loopvhdl

Why in VHDL for-loop is not working?


I tried simulating a for loop in ModelSim, but it is not working properly. I know it cannot synthesized, but I don't know why it is not simulating properly.

When simulated, it is not showing any error. But final result is "00000001" (ie incremented only once) instead of the expected output of "00000011".

library ieee;
use ieee.std_logic_1164.all;
use IEEE.STD_LOGIC_unsigned.ALL;

entity forloop is 
port(   enable      : in std_logic;         
     data_out       : out std_logic_vector(7 downto 0)); 
end forloop;

architecture behaviour of forloop is

signal temp     : std_logic_vector(7 downto 0) := "00000000";

begin

process(enable)         
begin   

    for i in 0 to 3 loop            
        temp <= temp +1;
    end loop;
end process;        
data_out <= temp;       
end behaviour;

Solution

  • The simulation output is correct. The for loop in VHDL expands to parallel assignments and not what you get in C (sequential assignments). This means that

    for i in 0 to 3 loop            
        temp <= temp +1;
    end loop;
    

    will become

        temp <= temp +1;
        temp <= temp +1;
        temp <= temp +1;
        temp <= temp +1;
    

    Note that temp is a signal and will be updated in the next cycle, hence the +1 is assigned to the same temp value for all 4 lines of code. Besides that, you don't use the enable signal in the sensitivity list. And are you sure you want to use an asynchronous process?