BitFlow

How to write a finite state machine (FSM) in Verilog

Moore and Mealy state machines in Verilog: the three-block template, a complete 1011 sequence detector in both styles, state encoding, and the mistakes that create latches.

By BitFlow · · 9 min read

The short answer

A finite state machine (FSM) in Verilog is a state register plus next-state logic plus output logic. Write the register in a clocked block with nonblocking assignments (<=), and the two pieces of logic in combinational blocks with blocking assignments (=). Give every signal a default at the top of each combinational block so no latch is inferred.

  • Moore machine: outputs depend only on the current state. They change only at a clock edge.
  • Mealy machine: outputs depend on the current state *and* the inputs. They can react in the same cycle, and usually need fewer states.

The three-block template

Most teams write FSMs the same way, because it maps one-to-one onto the hardware and is easy to review:

localparam [1:0] IDLE = 2'd0, RUN = 2'd1, DONE = 2'd2;
reg [1:0] state, next;

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

// 2. Next-state logic: combinational
always @(*) begin
  next = state;               // default: stay put (prevents a latch)
  case (state)
    IDLE: if (start) next = RUN;
    RUN:  if (finish) next = DONE;
    DONE: next = IDLE;
    default: next = IDLE;     // recover from unused encodings
  endcase
end

// 3. Output logic: combinational (Moore: depends on state only)
always @(*) begin
  busy = (state == RUN);
end
A three-state Moore machine in the three-block style

You can merge blocks 2 and 3, or put the outputs in assign statements. What matters is the split between the one clocked block and the combinational logic around it.

Example: a 1011 sequence detector (Moore)

The classic interview and lab exercise: a serial input x arrives one bit per clock, and the output y goes to 1 when the last four bits were 1, 0, 1, 1. Overlaps count, so in 1011011 the detector fires twice.

A Moore machine needs one state per prefix of the pattern it has matched so far, plus a state that means "just matched", where the output is 1:

StateMeaningx = 0 →x = 1 →y
S0nothing matchedS0S10
S1seen 1S10S10
S10seen 10S0S1010
S101seen 101S10S10110
S1011seen 1011S10S11

The transitions out of S1011 are where overlap lives: after 1011, a 0 leaves 10 as a useful prefix, and a 1 leaves 1.

module seq1011_moore (input clk, input rst, input x, output y);
  localparam [2:0] S0 = 3'd0, S1 = 3'd1, S10 = 3'd2, S101 = 3'd3, S1011 = 3'd4;
  reg [2:0] state, next;

  always @(posedge clk)
    if (rst) state <= S0;
    else     state <= next;

  always @(*) begin
    next = S0;
    case (state)
      S0:    next = x ? S1    : S0;
      S1:    next = x ? S1    : S10;
      S10:   next = x ? S101  : S0;
      S101:  next = x ? S1011 : S10;
      S1011: next = x ? S1    : S10;
      default: next = S0;
    endcase
  end

  assign y = (state == S1011);
endmodule
Try it: 1011 detector (Moore) →Write this machine yourself and BitFlow grades it against hidden tests, including overlapping patterns.

The same detector as a Mealy machine

A Mealy machine can raise y during the clock cycle in which the final 1 arrives, so it does not need the "just matched" state. Four states are enough:

module seq1011_mealy (input clk, input rst, input x, output y);
  localparam [1:0] S0 = 2'd0, S1 = 2'd1, S10 = 2'd2, S101 = 2'd3;
  reg [1:0] state, next;

  always @(posedge clk)
    if (rst) state <= S0;
    else     state <= next;

  always @(*) begin
    next = S0;
    case (state)
      S0:   next = x ? S1 : S0;
      S1:   next = x ? S1 : S10;
      S10:  next = x ? S101 : S0;
      S101: next = x ? S1 : S10;   // on x = 1 we have just matched 1011
    endcase
  end

  assign y = (state == S101) && x;   // output depends on the input too
endmodule
MooreMealy
States for 101154
Output reactsOne clock after the last bitIn the same cycle as the last bit
Glitches on the outputNone from input changesPossible, since inputs feed the output directly
Typical fixNone neededRegister the output if it leaves the block
Try it: 1011 detector (Mealy) →The Mealy version of the same problem, graded on BitFlow.

State encoding: binary, one-hot or Gray

EncodingFlip-flops for N statesGood for
Binary⌈log₂ N⌉ASICs and small machines, where flip-flops are the cost
One-hotNFPGAs, which have flip-flops to spare; next-state logic is simple and fast
Gray⌈log₂ N⌉Machines that step through states in order; only one bit changes per step

Write the states as localparam names and let the synthesis tool re-encode them if it wants to; most FPGA tools pick one-hot automatically. If you choose one-hot by hand, check for exactly one bit set, and decide what happens if a glitch ever leaves the machine in an illegal state.

Try it: one-hot 1011 detector →Hand-code the detector with one flip-flop per state.

Mistakes that break FSMs

  • No default in the combinational block. If some path through the case does not assign next (or an output), synthesis infers a latch. Assign a default first, then override.
  • Blocking assignments in the state register. Use <= in the clocked block, or simulation and hardware can disagree.
  • Missing `default:` in the case. With a 3-bit register and 5 states, 3 encodings are unused. A default sends the machine somewhere safe if it ever lands there.
  • Incomplete sensitivity list. Write always @(*), not a hand-made list that forgets an input.
  • Asynchronous inputs straight into the next-state logic. A button or a signal from another clock domain must go through a synchroniser first, or the machine can jump to a state no transition leads to.
TipDraw the machine first. BitFlow's FSM designer lets you draw states and transitions, step the machine clock by clock, and export the Verilog with a self-checking testbench.

Questions

What is the difference between a Moore and a Mealy machine?

In a Moore machine the outputs depend only on the current state, so they change only at clock edges. In a Mealy machine the outputs depend on the current state and the current inputs, so they can respond in the same cycle and the machine usually needs fewer states.

How many always blocks should an FSM in Verilog have?

One clocked block for the state register, plus combinational logic for the next state and the outputs. Two or three always blocks are both common; the essential rule is that only the state register is clocked.

Why does my Verilog FSM infer a latch?

A combinational always block left a signal unassigned on some path, for example a case without a default or an if without an else. Assign every output and the next state a default value at the top of the block.

Should I use one-hot or binary state encoding?

One-hot is usually faster and is the common choice on FPGAs, which have plenty of flip-flops. Binary uses the fewest flip-flops and suits ASICs and small machines. Most synthesis tools can re-encode the states for you.

Was this article helpful?

Keep going