Module 911 min

Finite State Machines

The pattern behind almost every real controller

A finite state machine, or FSM, is a circuit that moves through a small set of named situations called states, based on its inputs. A traffic light is an FSM: Red, then Green, then Yellow, and back to Red. It is the single most useful design pattern in digital hardware.

The clean three-block style

Professionals write FSMs in three clear pieces. Keeping them separate makes the design easy to read, easy to debug, and friendly to the tools.

  1. State register - one clocked block that remembers the current state.
  2. Next-state logic - one combinational block that decides where to go next.
  3. Output logic - decides the outputs based on the state.

A worked example - a simple traffic light

verilog
module traffic (
  input  wire       clk,
  input  wire       rst,
  output reg  [1:0] light   // 00=red 01=green 10=yellow
);
  // Give the states readable names
  localparam RED = 2'd0, GREEN = 2'd1, YELLOW = 2'd2;

  reg [1:0] state, next;

  // 1) State register - the only clocked block
  always @(posedge clk) begin
    if (rst) state <= RED;
    else     state <= next;
  end

  // 2) Next-state logic - pure combinational
  always @(*) begin
    next = state;            // default: stay put
    case (state)
      RED:    next = GREEN;
      GREEN:  next = YELLOW;
      YELLOW: next = RED;
      default: next = RED;
    endcase
  end

  // 3) Output logic - what each state shows
  always @(*) begin
    light = state;           // here outputs map straight to state
  end
endmodule

Why this structure wins

  • The clocked block uses <=, the combinational blocks use = - the rule from lesson 8, applied cleanly.
  • localparam gives states readable names instead of mystery numbers.
  • next = state as the default means an unlisted case safely stays put - no latch, no surprise.
  • You can add inputs (like a sensor) by branching inside the next-state case.
Pro tip

Almost every controller you will ever write - a UART, a bus interface, a button debouncer - is an FSM underneath. Master this three-block template and you can build the control logic for real designs.

Watch out

Always include a default in the next-state case and a reset in the state register. Without a reset, the FSM powers up in an unknown state (x) and can get stuck. Without a default, an unexpected state value can wedge the machine.