Write a Finite State Machine in Verilog the Synthesisable Way
Build a Moore finite state machine in Verilog with a state register, next-state logic and outputs, using defaults that avoid latches in synthesis.

A finite state machine, or FSM, is the standard way to turn a sequence of actions into hardware. The software version is a switch on a state variable. The hardware version has the same idea but needs more care, because the code must synthesise into clean registers and logic with no latches. This post builds a small FSM in Verilog following the three-part structure that tools handle best, then tests it with a self-checking testbench. It targets Verilog-2005 as in IEEE 1364-2005, simulated with Icarus Verilog 12.0 and synthesised with Yosys 0.40.
The structure: state, next state, outputs
Every synchronous FSM has three pieces:
A state register, a set of flip-flops holding the current state, updated on the clock edge.
Next-state logic, combinational, computing the state to load from the current state and the inputs.
Output logic, combinational, computing the outputs. In a Moore machine outputs depend only on the state. In a Mealy machine they also depend on inputs.
Writing these as separate blocks keeps the clocked part and the combinational parts clearly apart, which is the key to avoiding blocking-versus-non-blocking trouble.
The example: a serial pattern detector
The machine watches a serial bit stream, one bit per clock, and raises found for one cycle after seeing the sequence 1 0 1. It must allow overlapping matches, so 10101 contains two.
States record how much of the pattern has been matched:
S0: nothing matched yet.S1: matched1.S2: matched1 0.S3: matched1 0 1, the output state.
module detect101 (
input wire clk,
input wire rst,
input wire bit_in,
output reg found
);
localparam [1:0] S0 = 2'd0,
S1 = 2'd1,
S2 = 2'd2,
S3 = 2'd3;
reg [1:0] state;
reg [1:0] next;
// State register
always @(posedge clk) begin
if (rst)
state <= S0;
else
state <= next;
end
// Next-state logic
always @* begin
next = state;
case (state)
S0: next = bit_in ? S1 : S0;
S1: next = bit_in ? S1 : S2;
S2: next = bit_in ? S3 : S0;
S3: next = bit_in ? S1 : S2;
default: next = S0;
endcase
end
// Output logic (Moore)
always @* begin
found = (state == S3);
end
endmoduleThe comment lines use //, which is safe. Notice the details that matter for synthesis.
next = state; appears first in the combinational block. That is a default assignment: whatever the case does, next has a value on every path, so the tool cannot infer a latch.
The default: branch handles the unused encoding. With two bits there are four states and all four are named, so default is unreachable here, but it is still good practice. If you add a fifth state later, it protects you, and it gives the tool a recovery path if a glitch puts the register into an illegal value.
Transitions on a mismatch deserve thought. In S3, which has just matched 1 0 1, a 1 goes to S1 because that 1 could start a new pattern, and a 0 goes to S2 because the last 1 of the previous match plus this 0 is already 1 0. That is what makes overlapping matches work.
Testing it with a self-checking bench
The test feeds a known stream, and compares the sequence of found values to the expected one. Stream 1 0 1 0 1 1 0 1 has matches finishing at positions 3, 5 and 8, counting from 1.
`timescale 1ns/1ps
module detect101_tb;
reg clk = 1'b0;
reg rst = 1'b1;
reg bit_in = 1'b0;
wire found;
reg [7:0] stream = 8'b10101101;
reg [7:0] expected = 8'b00101001;
reg [7:0] seen;
integer i;
integer errors = 0;
detect101 dut (.clk(clk), .rst(rst), .bit_in(bit_in), .found(found));
always #5 clk = ~clk;
initial begin
#12 rst = 1'b0;
for (i = 7; i >= 0; i = i - 1) begin
bit_in = stream[i];
@(posedge clk);
#1 seen[i] = found;
end
for (i = 7; i >= 0; i = i - 1)
if (seen[i] !== expected[i]) begin
$display("FAIL at bit %0d: expected %b got %b", i, expected[i], seen[i]);
errors = errors + 1;
end
$display("seen = %b", seen);
if (errors == 0) $display("PASS");
$finish;
end
endmoduleSince the output is Moore, found is high in the cycle after the state register has entered S3. The bench samples after the edge that loads the third matching bit, so found reads 1 at the positions where the state became S3. The first match completes with the third bit, the second with the fifth, the third with the eighth. The expected vector 00101001 has ones in the third, fifth and eighth positions counting from the left. The run prints:
seen = 00101001
PASSIf seen came out as xxxxxxxx, the usual cause is a reset that was never released, or a testbench that started the stream before the first reset edge. The bench waits 12 ns and the clock has already toggled once at 5 ns with reset high, so the machine is in S0.
Encoding states with named constants
localparam gives the states names, which is important for readability and for debugging in a waveform viewer. The encoding you choose is a design decision. Binary encoding, as above, uses the fewest flip-flops: two bits for four states. One-hot encoding uses one flip-flop per state, so four states take four flip-flops, but each next-state equation is simpler, because testing a state is a single bit. FPGAs have plenty of flip-flops and fast single-bit logic, so one-hot often gives higher clock rates there. The Yosys fsm pass can recode a recognised FSM automatically, which is another reason to write the three-block structure: it is the pattern the tool recognises.
Moore or Mealy
A Mealy output reacts to an input in the same cycle, so it can be one cycle earlier than a Moore output. The cost is that a glitch on an input can reach the output, and long input-to-output paths limit the clock rate. This detector as a Mealy machine would drop S3 and assert found when in S2 with bit_in high:
module detect101_mealy (
input wire clk,
input wire rst,
input wire bit_in,
output reg found
);
localparam [1:0] S0 = 2'd0, S1 = 2'd1, S2 = 2'd2;
reg [1:0] state, next;
always @(posedge clk) begin
if (rst) state <= S0;
else state <= next;
end
always @* begin
next = state;
found = 1'b0;
case (state)
S0: next = bit_in ? S1 : S0;
S1: next = bit_in ? S1 : S2;
S2: begin
if (bit_in) begin
found = 1'b1;
next = S1;
end else
next = S0;
end
default: next = S0;
endcase
end
endmoduleBoth outputs are given defaults at the top of the combinational block. For a first design, prefer Moore: its outputs are glitch-free and easy to time, and registering a Mealy output afterwards gives the Moore timing anyway.
What to check in synthesis
Run Yosys and read the report:
yosys -p "read_verilog detect101.v; synth_ice40 -top detect101; stat"The log from the fsm pass includes lines like these when it recognises the machine:
Extracting FSM `\state' from module `\detect101'.
found FSM state register: \state
FSM state signal is \stateIf you instead see Latch inferred for next or found, a path in a combinational block left an output unassigned. The fix is a default assignment at the top of the block. If the FSM is not extracted, the state register is probably driven from more than one place or reset in an unusual way.
Common mistakes
Putting outputs in the clocked block by accident. That registers them and adds a cycle of latency without saying so.
**Forgetting
default.** Acaseover a two-bit value that names three states leaves one unhandled and builds a latch.Using blocking assignments in the state register block. Keep
<=there.No reset. Without one, the state is unknown at power-up in simulation and arbitrary on some targets.
Asynchronous inputs. A button into
bit_inneeds a synchroniser first, covered later in this cluster.
Making the machine safe
A machine with four states fits exactly in two bits, so every encoding is legal. Many machines have fewer states than encodings, and then the unused encodings are a risk. A radiation upset or a power glitch can flip a flip-flop and put the register in an unused state. The default branch is what recovers: it sends the next state back to a known one. Without it, a synthesis tool is free to treat the unused encodings as "don't care", which makes the logic smaller and removes the recovery path.
For safety-relevant designs, check the policy of your tool. Yosys, for instance, can be told to keep or recode FSMs, and vendor tools often have an attribute for "safe state machine". For a hobby design, the default branch is enough. For anything that must recover, add a state-valid check or a watchdog that forces a reset if the machine stays in one state too long.
Choosing between a state machine and a counter
Not every sequence needs an FSM. If the behaviour is "wait N cycles, then do one thing", a counter and a comparator are smaller and clearer. An FSM earns its place when the next action depends on inputs or when there are several distinct phases. The serial detector above has one state per prefix of the pattern, which is the shape that suits it. A UART transmitter combines both: a small FSM for the phase (idle, start, data, stop) and a counter inside it for the bit time, as the guide to Verilog in this cluster shows.


