Enums in Verilog

Our enum type ServerState has an underlying int type in the target language, Verilog. The possible values for ServerState are defined as parameters.

module enums;

    // Define an enumerated type for ServerState
    typedef enum int {
        StateIdle,
        StateConnected,
        StateError,
        StateRetrying
    } ServerState;

    // Function to get the string representation of a state
    function automatic string stateToString(ServerState state);
        case (state)
            StateIdle:      stateToString = "idle";
            StateConnected: stateToString = "connected";
            StateError:     stateToString = "error";
            StateRetrying:  stateToString = "retrying";
            default:        stateToString = "unknown";
        endcase
    endfunction

    // Task to emulate a state transition for a server
    function automatic ServerState transition(ServerState s);
        case (s)
            StateIdle: transition = StateConnected;
            StateConnected, StateRetrying: transition = StateIdle;
            StateError: transition = StateError;
            default: $fatal(1, "unknown state: %0d", s);
        endcase
    endfunction

    // Initial block to showcase changing states and printing them
    initial begin
        ServerState ns = StateIdle;
        $display("%s", stateToString(ns));

        ns = transition(ns);
        $display("%s", stateToString(ns));

        ServerState ns2 = transition(ns);
        $display("%s", stateToString(ns2));
    end
endmodule

To run the program, simulate the Verilog module using a simulator like iverilog or ModelSim. Here’s an example using iverilog:

$ iverilog -o enums.vvp enums.v
$ vvp enums.vvp
idle
connected
idle

In this example, we created an enumerated type ServerState with possible states. Then, we used a function to convert these states to strings and another function to transition between states. An initial block was used to demonstrate state transitions and print them.

Now that we can handle enums in Verilog, let’s learn more about the language.