Search code examples
vhdlfpgaenumeration

Type enumeration in VHDL


What is the type enumeration in the VHDL? where can I use it, to make the code shorter and more understandable? for example, consider a bellow statement:

TYPE st_State IS (st_Idle, st_CheckHeader1, st_CheckHeader2, st_ReceiveData)

when must to use it.


Solution

  • Your example is only a declaration of a type with name st_State and this type contains four elements. Each element gets a number from 0 to Elements - 1. This is similar to a C typedef with an C enum.

    Please check this explanation for more detailed information.

    A typical application for this is a state machine to name the different states:

    architecture Top_Arch of Top is
        type State_Type is (S0, S1, S2, S3);
        signal CurrentState : State_Type := S0; 
    begin
        process(Clock)
        begin
            if(rising_edge(Clock)) then
                case CurrentState is
                    when S0 =>  ...
                    when S1 =>  ...
                    when S2 =>  ...
                    when S3 =>  ...  
                end case;
            end if;
    end Top_Arch;
    

    Using this method result in a more readable and cleaner code, but it is equivalent to this approach (untested):

    architecture Top_Arch of Top is
        signal CurrentState : INTEGER RANGE 0 to 3 := 0; 
    begin
        process(Clock)
        begin
            if(rising_edge(Clock)) then
                case CurrentState is
                    when 0 =>  ...
                    when 1 =>  ...
                    when 2 =>  ...
                    when 3 =>  ...  
                end case;
            end if;
    end Top_Arch;
    

    NOTE: Check the range statement. You have to use it, because you have to declare each value for your state machine. So you have to use when others or reduce the integer to 2 bits only. Otherwise you have to declare 2^32 - 1 states.

    So you need at least a type declaration with type <YourType> is ... to declare your custom type and a signal to use your type (CurrentState in the above example).