Enums & State Machines

Named states with typedef enum, enum methods, and a traffic-light FSM written the SystemVerilog way.

An enum gives a set of values names. For state machines this is a big improvement over Verilog's localparams: the state variable can only hold legal states, waveform viewers and $display show the names, and assigning a plain number by mistake is a compile error.

A traffic-light controller

state_t state, next; — both variables can only hold the four named values.

next = state; at the top of always_comb gives a default, so no latch can be inferred.

The timer counts clocks spent in the current state and restarts on every state change.

unique case: exactly one branch matches; with an enum covering all four values, no default is needed.

Enum methods and rules

localparam IDLE = 0, BUSY = 1; logic [1:0] state; state = 5; // no error typedef enum logic [1:0] {IDLE, BUSY} state_t; state_t state; state = state_t'(5); // explicit, and flagged as out of range

With an enum the compiler rejects plain integers, so illegal states have to be created on purpose.

What base type does typedef enum {A, B, C} t; have?

int (32-bit, 2-state) by default, with A = 0, B = 1, C = 2. Specify a base type such as logic [1:0] for hardware so the width and 4-state behaviour are what you want.

How do you print an enum variable's state name?

$display("%s", state.name()); — or %p, which also prints names.