0
0
VHDLprogramming~5 mins

Conditional assignment (when-else) in VHDL

Choose your learning style9 modes available
Introduction

Conditional assignment lets you choose a value based on a condition in a simple way. It helps decide what signal should be set depending on some test.

You want to set a signal to one value if a condition is true, and another value if it is false.
You need to assign values to signals based on simple yes/no checks.
You want to write clear and short code for choosing between two options.
You want to avoid writing full if-then-else blocks for simple assignments.
Syntax
VHDL
signal_name <= value1 when condition else value2;

The condition is a boolean expression that decides which value to assign.

The value before when is assigned if the condition is true; otherwise, the value after else is assigned.

Examples
Assigns '1' to output if input is '1', else assigns '0'.
VHDL
output <= '1' when input = '1' else '0';
If sel is '0', result gets a, otherwise b.
VHDL
result <= a when sel = '0' else b;
Sets flag to 'T' if count is greater than 10, else 'F'.
VHDL
flag <= 'T' when count > 10 else 'F';
Sample Program

This program assigns result to a if sel is '0'. Otherwise, it assigns b. It shows how to use conditional assignment with when-else.

VHDL
library ieee;
use ieee.std_logic_1164.all;

entity conditional_example is
    port(
        sel : in std_logic;
        a, b : in std_logic_vector(3 downto 0);
        result : out std_logic_vector(3 downto 0)
    );
end conditional_example;

architecture Behavioral of conditional_example is
begin
    -- Assign result based on sel
    result <= a when sel = '0' else b;
end Behavioral;
OutputSuccess
Important Notes

Conditional assignment is a concurrent statement, so it runs continuously in hardware.

You can chain multiple when-else statements for more conditions, but readability may suffer.

Use this for simple two-choice assignments to keep code clean and easy to read.

Summary

Conditional assignment chooses between two values based on a condition.

It uses the syntax: signal <= value1 when condition else value2;

This is useful for simple, clear signal assignments in VHDL.