Switch in VHDL

Switch statements express conditionals across many branches.

Here’s a basic switch.

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

entity SwitchExample is
end entity SwitchExample;

architecture Behavioral of SwitchExample is
begin
  process
    variable i: integer := 2;
  begin
    report "Write " & integer'image(i) & " as ";
    case i is
      when 1 =>
        report "one";
      when 2 =>
        report "two";
      when 3 =>
        report "three";
      when others =>
        report "other";
    end case;
    wait;
  end process;
end architecture Behavioral;

You can use commas to separate multiple expressions in the same case statement. VHDL does not have a direct default case, so we use when others instead.

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
use std.env.all;

entity WeekdayExample is
end entity WeekdayExample;

architecture Behavioral of WeekdayExample is
begin
  process
    variable day: time;
  begin
    day := get_simulation_time;
    case week_day(day) is
      when Saturday | Sunday =>
        report "It's the weekend";
      when others =>
        report "It's a weekday";
    end case;
    wait;
  end process;
end architecture Behavioral;

Switch without an expression is an alternate way to express if/else logic. Here we also show how the case expressions can be non-constants.

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
use std.env.all;

entity TimeOfDayExample is
end entity TimeOfDayExample;

architecture Behavioral of TimeOfDayExample is
begin
  process
    variable t: time := now;
  begin
    case true is
      when t'val(t) < time'val(12 * 3600 * 1000000) =>
        report "It's before noon";
      when others =>
        report "It's after noon";
    end case;
    wait;
  end process;
end architecture Behavioral;

A type switch compares types instead of values. Since VHDL does not support this kind of type checking directly, you would typically use a combination of different VHDL constructs to handle multiple types.

Here’s an example demonstrating handling different types:

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
use std.env.all;

entity TypeExample is
end entity TypeExample;

architecture Behavioral of TypeExample is
begin
  process
    procedure whatAmI (signal i : in std_logic) is
    begin
      report "I'm a boolean";
    end procedure whatAmI;

    procedure whatAmI (signal i : in integer) is
    begin
      report "I'm an integer";
    end procedure whatAmI;

    procedure whatAmI (signal i : in string) is
    begin
      report "I'm a string";
    end procedure whatAmI;

  begin
    whatAmI('1');
    whatAmI(1);
    whatAmI("hey");
    wait;
  end process;
end architecture Behavioral;