Verilog finite-state machine example

Build a synthesizable Verilog FSM with separate state register and next-state logic, safe defaults, reset and output decoding.

A clear two-process FSM

A finite-state machine normally contains a state register and combinational next-state/output logic. This separation makes storage, transitions and default behavior visible during review.

localparam IDLE = 2'b00,
           RUN  = 2'b01,
           DONE = 2'b10;

reg [1:0] state, next_state;

always @(posedge clk or negedge rst_n) begin
  if (!rst_n) state <= IDLE;
  else        state <= next_state;
end

always @* begin
  next_state = state;
  busy       = 1'b0;
  complete   = 1'b0;

  case (state)
    IDLE: if (start) next_state = RUN;
    RUN: begin
      busy = 1'b1;
      if (last) next_state = DONE;
    end
    DONE: begin
      complete = 1'b1;
      next_state = IDLE;
    end
    default: next_state = IDLE;
  endcase
end

Design decisions

The example uses Moore outputs because busy and complete depend on the current state. A Mealy output can also depend on inputs and may respond within the current cycle, but it needs careful glitch and timing analysis.

The default branch provides deterministic recovery from an illegal encoding. Whether automatic recovery is appropriate depends on the safety requirements; some designs instead flag a fatal fault.

What to verify

  • Reset reaches IDLE and releases safely.
  • Every legal transition and intended self-loop is exercised.
  • Illegal or unknown state behavior is defined.
  • Outputs assert for exactly the intended cycles.
  • State encoding assumptions are not accidentally changed by synthesis constraints.

Continue into the complete lesson

Use the course lesson for the surrounding design rules, exercises, labs and knowledge check.

Open supporting lesson →
Related answers

Continue exploring this topic