Home / Learn Chip Programming / Finite State Machines in Verilog

Finite State Machines in Verilog

The standard 3 block FSM style, with a working sequence detector and traffic light.

In shortThe standard 3 block FSM style, with a working sequence detector and traffic light.

Theory in plain words

Traffic light FSMREDRED_YELLOWGREENYELLOWclk
Traffic light FSM

What it is

FSM in Verilog: a state register (sequential), next-state logic (combinational) and output logic (Moore or Mealy). States are defined with localparam or enum.

Why we use it

Controllers, protocols and CPUs control units are FSMs. Clean coding style avoids bugs and makes synthesis tools infer FSM optimisations.

How it works

Block 1: always @(posedge clk) state <= next_state. Block 2: always @(*) case(state) computes next_state. Block 3: outputs from state (and inputs for Mealy).

Where it is used

  • Protocol controllers (UART, SPI, I2C)
  • CPU control unit
  • Button handlers and timers

Run the FSM

Traffic light with timers (clock ticks)Try it Yourself

The timer counts clock cycles in the current state and resets on each state change.

Sequence detector 1011 (Mealy)
module seq1011 (input clk, rst, din, output reg found);
    localparam S0 = 2'd0, S1 = 2'd1, S2 = 2'd2, S3 = 2'd3;
    reg [1:0] state, next;
    always @(posedge clk) if (rst) state <= S0; else state <= next;
    always @(*) begin
        next = state; found = 1'b0;                      // defaults
        case (state)
            S0: if (din) next = S1;
            S1: if (!din) next = S2;
            S2: if (din) next = S3; else next = S0;
            S3: if (din) begin next = S1; found = 1'b1; end else next = S2;
        endcase
    end
endmodule
Tip:Give outputs and next-state defaults at the top of the combinational block: the code stays short and latch free.

Quick quiz

1. How many blocks in the 3 block FSM style?

2. Moore outputs depend on...