Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 37 ยท FSMs and Design

FSM Coding Styles and State Encoding

Compare one-, two- and three-process Verilog FSM styles, learn binary, Gray and one-hot state encoding, default states and safe recovery, with a traffic light example.

Two engineers can write the same state machine and get very different code: one reads like a diagram, the other like a puzzle. How you split the FSM into always blocks changes readability, simulation behaviour, whether you get unwanted latches, and whether your outputs glitch. How you encode the states changes area, speed and power. This lesson gives you a house style you can follow, and the trade-offs behind it.

It builds on Moore and Mealy machines. Verilog here is read-only (no simulator on this site); the C programs are labelled stand-ins that model traffic-light timing and state encodings.

One, two or three processes?

Separate the state register (sequential) from the next-state and output logic (combinational). Every FSM in the previous lesson used this shape:

VERILOG
// 1. state register
always @(posedge clk or negedge rst_n)
  if (!rst_n) state <= IDLE;
  else        state <= next;

// 2. next-state logic
always @* begin
  next = state;                  // default: stay
  case (state)
    IDLE: if (start) next = RUN;
    RUN:  if (done)  next = IDLE;
    default:         next = IDLE;
  endcase
end

Outputs are either assign statements from state (Moore) or set in the combinational block (give them a default value at the top so that no latch is inferred).

Three-process style

Add a third block for outputs, registered or combinational:

VERILOG
// 3. registered Moore outputs: glitch-free, one cycle later
always @(posedge clk or negedge rst_n)
  if (!rst_n) busy <= 1'b0;
  else        busy <= (next == RUN);

Registering outputs removes glitches and makes timing easy, at the cost of one cycle of delay and some flip-flops. It is the preferred choice for outputs that leave the chip.

One-process style

Everything in one clocked block: state, outputs and transitions together.

VERILOG
always @(posedge clk or negedge rst_n)
  if (!rst_n) begin state <= IDLE; busy <= 1'b0; end
  else case (state)
    IDLE: if (start) begin state <= RUN;  busy <= 1'b1; end
    RUN:  if (done)  begin state <= IDLE; busy <= 1'b0; end
  endcase

It is compact and outputs are registered automatically, but it is easy to forget that busy changes with the transition, and it is harder to read when there are many states. Pick one style per project and stick to it.

Rules that prevent bugs

  1. Default assignment first. In the combinational block, assign next = state; and every output a default at the top, then override in the case. This guarantees all paths assign a value (no latches).
  2. Use localparam or an enum for state names, never magic numbers.
  3. Always include default: in the case that returns to a safe state.
  4. Use non-blocking <= in the clocked block and blocking = in always @*.
  5. Make reset set the state register, never leave it undefined: an FSM that starts in x may never leave it.

An FSM that only lists some of its inputs in a sensitivity list, or forgets an output assignment on some path, creates a latch. Use always @* (or always_comb in SystemVerilog) so the tool computes the sensitivity list, and give every output a default.

State encoding

The state needs a binary representation. The three classic choices:

Encoding Example for 4 states Flip-flops Properties
Binary 00, 01, 10, 11 log2(N) Smallest register, more decode logic; several bits can flip at once
Gray 00, 01, 11, 10 log2(N) Exactly one bit changes per step along a path: low power, glitch-free in sequences
One-hot 0001, 0010, 0100, 1000 N One flip-flop per state; very fast decoding; popular on FPGAs

FPGAs have many flip-flops and slow wide logic, so synthesis tools often re-encode an FSM to one-hot automatically (Vivado and Quartus both can). ASICs often prefer binary or Gray. You can steer this with a tool attribute ((* fsm_encoding = "one_hot" *) in Vivado), but check your tool's manual.

The first stand-in counts how many state-register bits flip when an FSM walks a 4-state ring under each encoding. Fewer flips mean less switching activity.

C Stand-in: bit flips for binary, Gray and one-hot encodings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Gray flips the fewest bits (one per step, 4 per lap). Binary flips 6, because 01 to 10 and 11 to 00 change two bits at once. One-hot flips 8 (one bit clears and one sets on every step) and needs four flip-flops instead of two, yet each state is recognised from a single bit. Total flips are not the only goal: one-hot buys speed, not low switching.

One-hot in Verilog

A neat idiom for one-hot machines is the case (1'b1) form, which tests each state bit:

VERILOG
localparam IDLE = 0, RUN = 1, DONE = 2;      // bit indices
reg [2:0] state, next;

always @* begin
  next = 3'b000;
  case (1'b1)                                // "reverse case"
    state[IDLE]: next[start ? RUN : IDLE] = 1'b1;
    state[RUN]:  next[done  ? DONE : RUN] = 1'b1;
    state[DONE]: next[IDLE] = 1'b1;
    default:     next[IDLE] = 1'b1;
  endcase
end

Reset must put the register in a legal one-hot value (3'b001), and the default branch recovers from illegal values such as 3'b101.

Safe FSMs

A single event upset (radiation, a glitch, or a missing reset) can put the register into an unused code. Binary encodings with unused codes need a default: that returns to the idle state; fully specified one-hot encodings need extra logic to detect illegal patterns. Safety-critical designs (aerospace, automotive) use "safe" encoding options in the synthesis tool. For ordinary projects, a proper reset plus default: is enough.

Example: traffic light

A Moore traffic-light controller cycles GREEN, YELLOW, RED with fixed durations, using a counter to time each state:

VERILOG
module traffic (input clk, rst_n, output reg [2:0] lamp);  // {red,yellow,green}
  localparam GREEN = 2'd0, YELLOW = 2'd1, RED = 2'd2;
  reg [1:0] state, next;
  reg [3:0] timer;

  wire expired = (timer == 4'd0);

  always @(posedge clk or negedge rst_n)
    if (!rst_n) begin state <= GREEN; timer <= 4'd5; end
    else if (expired) begin
      state <= next;
      timer <= (next == GREEN) ? 4'd5 : (next == YELLOW) ? 4'd1 : 4'd4;
    end else timer <= timer - 4'd1;

  always @* begin
    next = state;
    case (state)
      GREEN:  next = YELLOW;
      YELLOW: next = RED;
      RED:    next = GREEN;
      default: next = GREEN;
    endcase
  end

  always @* case (state)
    GREEN:   lamp = 3'b001;
    YELLOW:  lamp = 3'b010;
    default: lamp = 3'b100;
  endcase
endmodule

Here the state register advances only when the timer expires, so one FSM handles both "what state" and "how long". The C stand-in below models exactly this timing and prints which lamp is on for 16 cycles.

C Stand-in: traffic light with a timer, cycle by cycle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Green lasts six cycles (timer 5 down to 0), yellow two and red five, matching the reload values in the Verilog. Notice the off-by-one: a timer loaded with N expires after N+1 cycles. Decide whether you want "load N" or "load N-1" and document it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why assign next = state; at the top of the combinational block?

    A default assignment guarantees that next gets a value on all branches. Missing branches in combinational code create latches.
  2. 2. Which encoding changes exactly one state bit per step along a path?

    Gray code sequences differ by one bit between neighbours, which reduces switching and avoids multi-bit glitches.
  3. 3. Why is one-hot encoding popular on FPGAs?

    One-hot needs N flip-flops but each state is decoded from a single bit, which makes the logic fast.
  4. 4. What is the advantage of a registered (three-process) output?

    Registering outputs filters combinational glitches and gives a clean clock-to-output time, but the output appears one clock later.

Summary

  • Prefer the two-process style (register plus combinational logic); use registered outputs when they leave the chip.
  • Default-assign next and all outputs, name states with localparam, include default: and reset.
  • Binary is compact, Gray reduces flips, one-hot is fast and flip-flop heavy; tools may re-encode.
  • A timer inside a state is a common pattern; mind the off-by-one in counter reloads.

Next: Datapath and Controller Design