RTL Design· SiliCode Team· 15 min read· 19

Finite State Machine (FSM) in Verilog: Design, Examples and Testbench

Finite state machine in Verilog showing overlapping 1011 sequence detector code and 2391 simulation checks with zero mismatches

A finite state machine (FSM) in Verilog is a sequential circuit that remembers its current state and moves between a finite set of states according to its inputs. A synchronous FSM usually contains a state register, combinational next-state logic, and output logic.

State machines appear in UART controllers, memory interfaces, packet parsers and almost any hardware block that performs operations in a particular order. The difficult part is rarely writing the case statement. It is deciding what happens when an operation is interrupted, an input arrives unexpectedly, or a partial match must be preserved.

In this guide, we design an overlapping 1011 sequence detector from a specification, compare Moore and Mealy architectures, and verify the Moore implementation using a real SiliCode run. Its final simulation completed 2,391 checks with zero mismatches.

How Does a Finite State Machine Work?

Consider a controller with three states: IDLE waits for a request, BUSY processes it, and DONE reports completion. The same request can mean different things depending on the current state. In IDLE it might start an operation; in BUSY it might be ignored.

ComponentResponsibility
State registerStores the current state
Next-state logicCalculates the state to load on the next active clock edge
Output logicProduces outputs from the state, or from the state and inputs

In a synchronous FSM, the state register changes on its active clock edge. Combinational logic determines what happens next. Separating these responsibilities makes the timing easier to follow.

Moore vs. Mealy State Machines in Verilog

Moore FSM

A Moore output depends only on the current state. For example, a controller can assert done while it occupies its DONE state.

assign done = (state == DONE);

The logical output follows the state register. A combinational decode of several state bits is not necessarily glitch-free in physical hardware, however. Register an output if its interface requires that property.

Mealy FSM

A Mealy output depends on both the current state and current inputs.

assign done = (state == BUSY) && finish;

Here, done can respond to finish before another clock edge. That can remove a state or reduce response latency, but it introduces a combinational input-to-output path.

FeatureMooreMealy
Output depends onCurrent stateCurrent state and inputs
ResponseFollows state changesMay change between clock edges
State countMay need additional statesOften fewer states
Timing considerationState decodeDirect input-to-output path

Neither architecture is universally better. Choose according to the interface timing requirements. Both are supported by AMD Vivado FSM synthesis.

Block diagram comparing Moore and Mealy FSM architectures with state registers, next-state logic, and direct input-to-output paths
Moore outputs depend only on the current state, while Mealy outputs depend on both the current state and inputs, allowing a response between clock edges.

One-Block vs. Two-Block vs. Three-Block FSM

A one-block FSM can put transitions and registered outputs into a single clocked process. A two-block style separates the state register from combinational decisions. A three-block style separates state storage, next-state logic and output logic into distinct processes.

For example, here is the state register of a two-block implementation:

always @(posedge clk) begin
    if (!rst_n)
        state <= IDLE;
    else
        state <= next_state;
end

Its combinational next-state process might look like this:

always @(*) begin
    next_state = state;
    case (state)
        IDLE: if (start) next_state = BUSY;
        BUSY: if (finish) next_state = DONE;
        DONE: next_state = IDLE;
        default: next_state = IDLE;
    endcase
end

These snippets omit surrounding declarations. The complete example below uses three processes and SystemVerilog syntax. SystemVerilog extends Verilog with constructs such as logic, always_ff and always_comb.

The block count is independent of whether a design is Moore or Mealy. Use nonblocking assignments for persistent clocked state and blocking assignments for combinational calculations. See our guide to blocking vs. nonblocking assignments in Verilog for the scheduling details.

Start With the FSM Specification

Before implementing the controller, decide its initial state, sampling edge, reset behavior, transitions, output timing, priority and illegal-state recovery. A requirement such as "report completion when the transaction finishes" is incomplete: is completion a pulse, a level held until acknowledged, or a combinational indication?

Writing these details down makes verification much less ambiguous. Our RTL design specification guide covers the same approach for larger modules.

Worked Example: Overlapping 1011 Sequence Detector

The detector samples one binary input bit per rising clock edge. It asserts detected after the edge that samples the last bit of 1011, keeps the output high for one clock period, and permits overlapping matches. A synchronous active-low reset clears previous input history.

SignalDirectionMeaning
clkInputRising-edge sampling clock
rst_nInputSynchronous active-low reset
dinInputSerial bit
detectedOutputOne-clock detection indication

Consider the stream 1011011. Bits 1–4 and 4–7 both form 1011. A detector that discards all history after the first match misses the second one.

Designing the State Transition Table

Each state represents the longest suffix of the sampled history that also forms a prefix of the target pattern. The full match state also drives the Moore output high.

Current stateMeaningdin = 0din = 1detected
IDLENo matching prefixIDLES10
S11S10S10
S1010IDLES1010
S101101S10S10110
S10111011S10S11

Two transitions are easy to overlook. After 101 followed by 0, the history ends in 10, so S101 must return to S10. After a complete match followed by 0, the history also ends in 10. Returning to S10 rather than IDLE preserves the overlap.

For a non-overlapping version of this Moore detector, only one transition changes: from S1011 with din = 0, go to IDLE instead of S10, because the matched bits may not be reused. With din = 1, S1011 still moves to S1.

Overlapping 1011 Moore FSM state diagram showing five states, binary input transitions, reset behavior, and detection output
The five-state Moore FSM detects the serial pattern 1011 while preserving partial matches to support overlapping sequences. The detected output is high only in state S1011.

Complete Moore FSM Code

The following is the actual RTL exported from SiliCode run #471. Save it as sequence_detector.sv. It uses SystemVerilog, so enable SystemVerilog support in your compiler.

`default_nettype none
// Moore FSM, overlapping detector for serial pattern 1011.
module sequence_detector (
    input  wire clk,
    input  wire rst_n,   // synchronous, active low
    input  wire din,
    output logic detected
);
    localparam [2:0] IDLE   = 3'd0;
    localparam [2:0] S1     = 3'd1;
    localparam [2:0] S10    = 3'd2;
    localparam [2:0] S101   = 3'd3;
    localparam [2:0] S1011  = 3'd4;

    logic [2:0] state;
    logic [2:0] next_state;

    // State register
    always_ff @(posedge clk) begin
        if (!rst_n) state <= IDLE;
        else        state <= next_state;
    end

    // Next-state logic
    always_comb begin
        next_state = IDLE;
        case (state)
            IDLE:    next_state = din ? S1   : IDLE;
            S1:      next_state = din ? S1   : S10;
            S10:     next_state = din ? S101 : IDLE;
            S101:    next_state = din ? S1011 : S10;
            S1011:   next_state = din ? S1   : S10;
            default: next_state = IDLE;
        endcase
    end

    // Moore output
    always_comb begin
        detected = (state == S1011);
    end
endmodule
`default_nettype wire

The state register uses always_ff and nonblocking assignments. The next-state and Moore output processes use always_comb and blocking assignments. A default assignment prevents incomplete next-state logic.

Reset is synchronous: lowering rst_n between clock edges does not immediately clear the state. The next rising edge loads IDLE. See synchronous vs. asynchronous reset in Verilog for the timing differences.

The Same FSM With a SystemVerilog enum

An enumerated type lets the compiler check what is assigned to the state variables, and many waveform tools can show state names. The version below uses if/else because some compilers, including Icarus Verilog 12.0, require an explicit cast when a conditional operator is assigned to an enum.

module sequence_detector_enum (
    input  logic clk, rst_n, din,
    output logic detected
);
    typedef enum logic [2:0] {IDLE, S1, S10, S101, S1011} state_t;
    state_t state, next_state;

    always_ff @(posedge clk)
        if (!rst_n) state <= IDLE;
        else        state <= next_state;

    always_comb begin
        next_state = IDLE;
        case (state)
            IDLE:    if (din) next_state = S1; else next_state = IDLE;
            S1:      if (din) next_state = S1; else next_state = S10;
            S10:     if (din) next_state = S101; else next_state = IDLE;
            S101:    if (din) next_state = S1011; else next_state = S10;
            S1011:   if (din) next_state = S1; else next_state = S10;
            default: next_state = IDLE;
        endcase
    end

    assign detected = (state == S1011);
endmodule

This variant is not part of the SiliCode run. It was checked separately in Icarus Verilog 12.0 against a sliding-window model, using every 16-bit input stream after reset, with zero mismatches.

Understanding the Sequence Detector Cycle by Cycle

Here are the expected states and outputs after each sampling edge for the overlapping input stream.

Edgedin sampledState after edgedetected
Reset—IDLE0
11S10
20S100
31S1010
41S10111
50S100
61S1010
71S10111

The two detections occur after edges 4 and 7. Edge 5 is particularly useful when debugging an overlap failure: the machine should enter S10, not IDLE.

Implementing the Same Detector as a Mealy FSM

A combinational Mealy detector can remove S1011. Instead, it asserts its output when the state is S101 and the current input is 1.

Current statedin = 0: next / outputdin = 1: next / output
IDLEIDLE / 0S1 / 0
S1S10 / 0S1 / 0
S10IDLE / 0S101 / 0
S101S10 / 0S1 / 1

For reference, here is a conventional Verilog implementation of that alternative. This example is illustrative; the reported simulation and synthesis results in this article apply only to the Moore implementation.

module sequence_detector_mealy (
    input wire clk, rst_n, din,
    output wire detected
);
    localparam [1:0] IDLE=2'd0, S1=2'd1,
                     S10=2'd2, S101=2'd3;
    reg [1:0] state, next_state;

    always @(posedge clk)
        if (!rst_n) state <= IDLE;
        else state <= next_state;

    always @(*) begin
        next_state = IDLE;
        case (state)
            IDLE: next_state = din ? S1 : IDLE;
            S1:   next_state = din ? S1 : S10;
            S10:  next_state = din ? S101 : IDLE;
            S101: next_state = din ? S1 : S10;
            default: next_state = IDLE;
        endcase
    end

    assign detected = (state == S101) && din;
endmodule

The Mealy output can assert before the edge that accepts the fourth bit and deassert after that edge. It is not a drop-in replacement for the specified Moore output. If the interface needs a registered detection pulse, register the match condition and clear that output register on reset.

// Add inside sequence_detector_mealy, and declare
// "output reg detected_q" in the port list.
always @(posedge clk)
    if (!rst_n) detected_q <= 1'b0;
    else        detected_q <= detected;

detected_q goes high after the edge that samples the fourth bit and stays high for one clock period, which matches the timing of the Moore output.

Binary vs. One-Hot vs. Gray State Encoding

State names are symbolic. In hardware, the state is represented by bits. A five-state FSM needs at least three bits in binary encoding; conventional one-hot encoding uses five bits, one per state.

EncodingExample for five statesMain tradeoff
Binary000, 001, 010, 011, 100Fewer state bits
One-hot00001, 00010, 00100, 01000, 10000More state bits; potentially simpler decoding
GrayThree-bit assignments chosen for selected transitionsCan reduce switching on selected transitions

Gray encoding cannot make every transition in an arbitrary state graph a one-bit change. Likewise, one-hot is not guaranteed to be faster or smaller overall. Inspect synthesis and timing results for the actual target.

What the Synthesis Tool Actually Did

Although the exported RTL declares a three-bit state register, Yosys 0.52 recognized the FSM and selected one-hot encoding automatically. The synthesis log contains:

mapping auto encoding to `one-hot` for this FSM.

The resulting mapped design uses five FDRE flip-flops. This is a useful reminder that the number of bits in a source declaration does not necessarily equal the number of state registers in a synthesized netlist.

Vendor tools also provide encoding controls. See Vivado FSM_ENCODING and the Quartus state machine HDL guidelines. Start with readable symbolic states and change encoding when the implementation reports justify it.

Handling Reset and Illegal States

Define a known startup state. The Moore detector loads IDLE on reset and defaults to IDLE when no legal state matches. This describes recovery in RTL, but it does not establish recovery from physical state corruption. Synthesis may remove unreachable logic or recode the FSM.

Where hardware fault recovery is a requirement, evaluate dedicated synthesis options such as Vivado FSM_SAFE_STATE and verify the implemented behavior. The run reported here did not test injected state faults.

How to Verify a Finite State Machine

A state diagram is a useful starting point, but it is not a test. For this detector, an independent four-bit sliding-window model provides a simple reference. After each sampled bit, it shifts the input into its history and checks whether that history equals 1011. The model clears its history on reset.

TestPurpose
1011Single match
1011011Two overlapping matches
10101011Fallback after a partial match
16 zeros and 16 onesNo false detections
Reset during 101Discard partial history
Reset after detectionClear output and prevent stale matches
All 256 eight-bit streamsCheck every short binary input combination of this length

The reference model is intentionally different from the FSM implementation. It checks the observable behavior without copying the transition table, which reduces the chance of reproducing the same transition error in both places.

Complete Self-Checking FSM Testbench

This is the final exported testbench from run #471, saved as tb_sequence_detector.sv.

`timescale 1ns/1ps
`default_nettype none
module tb_sequence_detector;
    logic clk;
    logic rst_n;
    logic din;
    logic detected;

    integer checks;
    integer detections;   // detections observed on DUT
    integer ref_detections;
    integer errors;
    integer i;
    integer k;

    logic [3:0] win;      // independent sliding-window reference
    logic       exp_det;
    logic [31:0] seq_bits;

    sequence_detector dut (.clk(clk), .rst_n(rst_n), .din(din), .detected(detected));

    initial clk = 1'b0;
    always #5 clk = ~clk;

    initial begin
        $dumpfile("sequence_detector.vcd");
        $dumpvars(0, tb_sequence_detector);
    end

    task automatic check_out(input [255:0] name);
        begin
            checks = checks + 1;
            if (exp_det) ref_detections = ref_detections + 1;
            if (detected) detections = detections + 1;
            if (detected !== exp_det) begin
                errors = errors + 1;
                $display("ERROR [%0s] t=%0t seq/idx=%0d din=%b exp=%b got=%b win=%b",
                         name, $time, i, din, exp_det, detected, win);
            end
        end
    endtask

    task automatic send_bit(input b);
        begin
            din = b;
            @(posedge clk);
            #1;
            win = {win[2:0], b};
            exp_det = (win == 4'b1011);
            check_out("bit");
        end
    endtask

    task automatic do_reset;
        begin
            rst_n = 1'b0;
            @(posedge clk);
            #1;
            win = 4'b0000;
            exp_det = 1'b0;
            check_out("reset");
            rst_n = 1'b1;
        end
    endtask

    task automatic send_str(input [31:0] bits, input integer n);
        integer j;
        begin
            for (j = n - 1; j >= 0; j = j - 1) send_bit(bits[j]);
        end
    endtask

    initial begin
        checks = 0; detections = 0; ref_detections = 0; errors = 0; i = 0;
        win = 4'b0; exp_det = 1'b0; din = 1'b0; rst_n = 1'b0;
        repeat (2) @(posedge clk);
        #1;
        do_reset;

        // single pattern
        i = 1000; send_str(32'b1011, 4);
        do_reset;
        // overlapping 1011011 (two detections)
        i = 1001; send_str(32'b1011011, 7);
        do_reset;
        // partial-match fallback
        i = 1002; send_str(32'b10101011, 8);
        do_reset;
        // all zeros / all ones
        i = 1003; send_str(32'h0, 16);
        do_reset;
        i = 1004; send_str(32'hFFFF, 16);
        do_reset;
        // reset during partial match: 101 then reset then 1 (must not detect)
        i = 1005; send_str(32'b101, 3);
        do_reset;
        send_str(32'b1, 1);
        send_str(32'b011, 3); // fresh 1011 -> detect
        do_reset;
        i = 1006; send_str(32'b101, 3);
        do_reset;
        send_str(32'b1, 1); // would have matched had state survived
        do_reset;
        // reset immediately after detection (detected high before reset edge)
        i = 1007; send_str(32'b1011, 4);
        do_reset;
        send_str(32'b0, 1);
        // reset asserted while detected is high, then pattern tail must not match
        i = 1008; send_str(32'b1011, 4);
        do_reset;
        send_str(32'b011, 3);
        do_reset;

        // exhaustive 8-bit sequences
        for (k = 0; k < 256; k = k + 1) begin
            i = k;
            do_reset;
            seq_bits = k;
            send_str(seq_bits, 8);
        end

        $display("Checks=%0d DUT_detections=%0d REF_detections=%0d Errors=%0d",
                 checks, detections, ref_detections, errors);
        if (errors == 0 && detections == ref_detections && checks > 0)
            $display("SIMULATION PASSED");
        else
            $display("SIMULATION FAILED");
        $finish;
    end

    initial begin
        #50000000;
        $display("TIMEOUT");
        $finish;
    end
endmodule
`default_nettype wire

The testbench samples the output one nanosecond after the rising edge. By then the nonblocking state update and combinational output decode have settled in this zero-delay RTL simulation. The case-inequality comparison (!==) catches unexpected unknown outputs.

For automated CI, consider replacing failure-only messages with a nonzero exit mechanism such as $fatal. The original testbench is reproduced here unchanged, including its printed pass/fail result.

If testbenches are new to you, start with What Is a Testbench in Verilog? For additional reference-model and assertion techniques, see How to Write a Self-Checking Testbench in Verilog.

Running the Simulation: Actual Results

To reproduce the example locally with Icarus Verilog, compile both SystemVerilog files:

iverilog -g2012 -s tb_sequence_detector -o sim sequence_detector.sv tb_sequence_detector.sv
vvp sim

The final simulation log exported by SiliCode reports:

VCD info: dumpfile sequence_detector.vcd opened for output.
Checks=2391 DUT_detections=87 REF_detections=87 Errors=0
SIMULATION PASSED

Compiling the published RTL and testbench with Icarus Verilog 12.0 reproduces the same check, detection and error counts.

MetricObserved result
Total checks2,391
Eight-bit input streams256
DUT detections87
Reference detections87
Errors0

The total includes 2,048 input checks from the exhaustive eight-bit loop, 74 additional directed input checks and 269 reset checks. Two initial reset clock edges are used for startup and are not included in the checked count. These results cover the supplied tests; they are not a proof of correctness for all possible longer streams or physical implementation conditions.

A Testbench Timing Bug Found During Verification

According to the run transcript, the first simulation reported 17 mismatches. The agent attributed them to stimulus timing after reset, where an extra sampling edge could consume a stale input. It reported correcting the testbench timing without changing the RTL. The final exported log shows zero errors. The initial failing log is not included in the exported artifacts.

This is a useful distinction: a mismatch can originate in the design, the testbench or the timing assumptions. Investigate the sampling relationship before changing the FSM.

Reading the FSM Waveform in GTKWave

The testbench requests a VCD file named sequence_detector.vcd. The final log confirms that the simulator opened it for output. Re-running the testbench locally lets you inspect it:

gtkwave sequence_detector.vcd

Add clk, rst_n, din, detected, dut.state and dut.next_state. Follow the seven-bit overlap example and compare the sampled values with the cycle table above. If the second detection is missing, inspect the transition immediately after the first match.

Remember that next_state is the value calculated for the next sampling edge, not the current state. Our guide to reading Verilog waveforms covers this debugging approach.

Actual FPGA Synthesis Results

SiliCode FSM verification results showing 2391 simulation checks, 87 matching detections, zero errors, and FPGA synthesis utilization
SiliCode run #471 completed 2,391 simulation checks with zero mismatches. Yosys synthesis targeting AMD/Xilinx 7-series mapped the design to five LUTs and five flip-flops.

The exported synthesis report uses Yosys 0.52 targeting AMD/Xilinx 7-series logic. It reports the following mapped resources:

ResourceCount
LUTs5 (2 LUT3, 1 LUT4, 2 LUT5)
Flip-flops5 FDRE
Carry cells0
DSP0
BRAM0
Total mapped cells15 (includes I/O and clock buffers)

The report labels two messages as warnings, but both indicate that no latch was inferred for the respective combinational outputs. The full log also contains an ABC informational warning about its combinational network; Yosys design checks report zero problems. These are synthesis resource estimates, not placed-and-routed Vivado utilization or timing and power results.

You can reproduce the cell counts with Yosys 0.52:

yosys -p "read_verilog -sv sequence_detector.sv; synth_xilinx -family xc7 -top sequence_detector; stat; check"

Inspect the original shared SiliCode run for the implementation and verification artifacts.

Common FSM Design Mistakes

MistakeBetter approach
Incomplete combinational assignmentsProvide a default and cover every relevant path.
Blocking assignments for persistent stateUse nonblocking assignments in the clocked state process.
Multiple drivers for the same stateGive the state register one procedural owner.
Returning to IDLE on every mismatchPreserve useful suffixes for overlapping patterns.
Decoding next_state instead of state without intentSpecify output timing first.
Feeding asynchronous inputs directly into an FSMUse an appropriate CDC mechanism.
Checking only state coverageCheck transitions, outputs, priority and reset interruption.

State coverage alone cannot show whether the right transition occurred at the right time. And passing functional simulation cannot establish clock-domain safety or implementation timing closure.

Practical FSM Design Checklist

  • Define each state, transition, reset condition and output timing.
  • Give each state register one procedural owner.
  • Assign every combinational output on every path.
  • Test legal transitions, fallbacks, reset interruption and priority.
  • Review clock-domain crossings and any fault recovery requirements.
  • Inspect FSM extraction, encoding, resource use and implementation timing.

Designing and Verifying FSMs With SiliCode

A prompt such as "design a sequence detector" leaves too much unspecified. A useful specification defines the pattern, overlap behavior, sampling edge, reset style and output latency. It also states which behaviors the testbench must check.

SiliCode works as an AI Verilog generator that verifies what it builds. In this worked example, it generated the Moore RTL and a self-checking testbench, ran simulation, and synthesized the design. The exported artifacts show how the timing contract was checked and how the FSM was encoded. The results do not guarantee correctness beyond the test scope or establish timing closure.

Try SiliCode with your own FSM specification →

Frequently Asked Questions

What is a finite state machine in Verilog?

An FSM stores a current state and selects its next state according to defined inputs and transitions. It typically uses a state register, next-state logic and output logic.

What is the difference between Moore and Mealy FSMs?

Moore outputs depend only on current state. Mealy outputs depend on current state and inputs, and can respond between clock edges.

How many always blocks should an FSM have?

One, two or three are common organizational styles. Separating the clocked state from combinational decisions can improve readability.

Is one-hot encoding always better for FPGA state machines?

No. One-hot can simplify decoding at the cost of more state bits. Compare the mapped resource use and timing for your target.

Why does my Verilog FSM infer a latch?

Incomplete combinational assignments may require storage to preserve a previous value. Provide a default and cover every relevant path.

How does an overlapping sequence detector work?

It preserves a matching suffix that is also a prefix of the pattern, so successive matches can share input bits. A non-overlapping detector discards those bits and begins a new match after each detection.

How do I verify an FSM in Verilog?

Drive input sequences and compare outputs with an independent reference model. Include reset, fallback, priority and timing cases.

Does a default case guarantee illegal-state recovery?

No. Synthesis may optimize unreachable states or change encoding. Physical fault recovery requires explicit design and verification.

Should I use SystemVerilog for FSMs?

SystemVerilog offers logic, always_ff, always_comb and enumerated state types. These make design intent clearer; conventional Verilog remains usable.

Conclusion: A State Machine Is a Timing Contract

When you design an FSM in Verilog, start with the transition table, define when outputs become valid, and make reset behavior explicit. Keep clocked storage separate from combinational decisions where practical, then verify observable behavior against an independent reference model. The result is a state machine that is easier to debug, integrate and review.

Keep reading

Finite State Machine in Verilog: Examples & Testbench · SiliCode