Search code examples
loopsvhdlfpga

VHDL: compare a signal against multiple values


I want to compare a signal against the list of pre-defined values and check if there is at least equal value it this list (or, alternatively, if there is no equal values in the list).

Example application: compare received command to the pre-defined list of valid commands and go to error state if the command is invalid. Imagine, we have only 3 valid commands: 0x00, 0x01 and 0xFF. Then this code would do the job:

--valid commands: 0x00, 0x01, 0xFF

process(clk) is
--somewhere in the middle of FSM
  if cmd /= x"00" and cmd /= x"01" and cmd /= x"01" then
    next_state <= error;
  end if;
end process;

But I wonder how to efficiently (in terms of coding style) implement the same thing for longer lists, without having to manually compare against each value (i.e. avoid writing lines like this:)

if cmd=val1 or cmd=val2 or ... or cmd=valN then --imagine N=100

I imagine it's something to do with arrays and loops?


Solution

  • A loop over an array of reference values is probably easier to maintain:

    subtype ref_value is std_ulogic_vector(7 downto 0);
    type ref_value_array is array (natural range <>) of ref_value;
    constant ref_values: ref_value_array(0 to 2) := (x"00", x"01",...);
    ...
    next_state <= error;
    for i in ref_values'range loop
      if cmd = ref_values(i) then
        next_state <= no_error;
        break;
      end if;
    end loop;