Finite State Machines (Moore & Mealy)
The three-part FSM template, a '1011' sequence detector built both ways, and how synthesis re-encodes states.
A finite state machine (FSM) is the standard way to build controllers: protocol handlers, sequence detectors, traffic lights, CPU control units. It has a state register, next-state logic that decides where to go, and output logic. In a Moore machine the outputs depend only on the state; in a Mealy machine they also depend on the current inputs.
A '1011' sequence detector
localparam names the states, so the code reads like the state diagram.
The Moore machine needs a fifth state, S1011, in which found is 1.
The Mealy machine raises found in state S101 as soon as din is 1, without a separate state.
default: next = S0 makes an illegal state recover instead of getting stuck.
State encoding
always @(*) case (state) S0: if (din) next = S1; ...
always @(*) begin next = state; // default: stay case (state) S0: if (din) next = S1; ... default: next = S0; endcase end
Without a default assignment, paths that do not assign next infer latches. A default (stay in the same state) plus a default case branch keeps the next-state logic combinational and recoverable.
always @(posedge clk) case (state) S0: if (din) state <= S1; ... // outputs also assigned here
Separate the state register, next-state logic and output logic
One big clocked block works, but it registers every output (adding a clock of delay) and mixes concerns. The three-part template is easier to verify and review.
What is the difference between a Moore and a Mealy machine?
Moore outputs depend only on the current state; Mealy outputs depend on the state and the current inputs. Mealy reacts a clock earlier and often needs fewer states; Moore outputs are glitch-free and registered-friendly.
How many flip-flops does a 10-state FSM need in binary and in one-hot encoding?
Binary: 4 (2^4 = 16 >= 10). One-hot: 10, one per state.
What happens if an FSM enters an unused state (e.g. after a glitch or radiation upset)?
Without handling it could stay there forever. A default branch that returns to a known state (or explicit recovery logic) makes the FSM safe.