0
0
VhdlHow-ToBeginner · 4 min read

How to Use While Loop in VHDL: Syntax and Example

In VHDL, a while loop repeats a block of statements as long as a condition is true. It is used inside processes or subprograms and has the syntax while condition loop ... end loop;. The loop stops when the condition becomes false.
📐

Syntax

The while loop in VHDL has this structure:

  • while condition loop: The loop runs while this condition is true.
  • statements: The code inside the loop to execute repeatedly.
  • end loop;: Marks the end of the loop.

The condition must be a boolean expression. The loop must eventually make the condition false to avoid infinite loops.

vhdl
while condition loop
    -- statements to repeat
end loop;
💻

Example

This example shows a process that counts from 0 to 4 using a while loop and stores the values in an array.

vhdl
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity while_loop_example is
end entity;

architecture behavior of while_loop_example is
    type int_array is array (0 to 4) of integer;
    signal data : int_array := (others => 0);
begin
    process
        variable i : integer := 0;
    begin
        while i < 5 loop
            data(i) <= i;
            i := i + 1;
        end loop;
        wait;
    end process;
end architecture;
Output
Signal 'data' will hold values [0, 1, 2, 3, 4] after the loop completes.
⚠️

Common Pitfalls

Common mistakes when using while loops in VHDL include:

  • Not updating the variable in the loop, causing an infinite loop.
  • Using a signal in the condition instead of a variable, which does not update immediately inside the loop.
  • Placing while loops outside processes or subprograms, which is not allowed.

Always use variables for loop control and ensure the condition changes inside the loop.

vhdl
process
    variable i : integer := 0;
begin
    -- Wrong: condition never changes, infinite loop
    while i < 5 loop
        -- missing i := i + 1;
    end loop;
    wait;
end process;

-- Correct:
process
    variable i : integer := 0;
begin
    while i < 5 loop
        i := i + 1;
    end loop;
    wait;
end process;
📊

Quick Reference

Tips for using while loops in VHDL:

  • Use while loops inside processes or subprograms only.
  • Control the loop with a variable, not a signal.
  • Make sure the loop condition will become false to avoid infinite loops.
  • Use while loops for unknown iteration counts; use for loops when the number of iterations is fixed.

Key Takeaways

Use while loops inside processes or subprograms with a boolean condition.
Control the loop with a variable that changes inside the loop to avoid infinite loops.
The loop runs while the condition is true and stops when it becomes false.
Avoid using signals in the loop condition because they update only after the process ends.
Use while loops for variable iteration counts; prefer for loops for fixed counts.