---
title: Finite state machines in HDL
heading: Moore and Mealy machines, state encoding, and the three-block style
eyebrow: S3 · Lesson 4 · Finite state machines in HDL
xp: 50
---

::: hook
Control logic, protocols, sequencers and interface handshakes are all finite state machines. C7 designed them on paper with Karnaugh maps; real designs write them in HDL and let the synthesizer do the algebra, but the designer still makes the choices that matter: Moore or Mealy outputs, and how to encode the states. Binary encoding uses the fewest flip-flops, one-hot the simplest and fastest logic, Gray the fewest bits changing per transition. And every encoding leaves unused codes that a radiation upset or power glitch can land in, so a robust machine says what happens there too.
:::

::: play
- A Moore machine that raises Y after seeing two 1s in a row on X, with states S0 (00), S1 (01) and S2 (10) in two flip-flops: `Q0 <= X & ~Q1 & ~Q0`, `Q1 <= X & (Q0 | Q1)`, and `Y = Q1`.
- Y comes from the state alone, so it changes only just after clock edges, one clock after the second 1 arrives.
- Code 11 is never used. Work out where the machine goes from it: here, S2 if X is 1 and S0 if it's 0, so it recovers on its own.
:::
:::

```sim logic
module two_ones(input CLK, input X, output Y);
always @(posedge CLK) Q0 <= X & ~Q1 & ~Q0;
always @(posedge CLK) Q1 <= X & (Q0 | Q1);
assign Y = Q1;
endmodule
clock CLK 8
stim X 0@0 1@2 0@10 1@18 1@26 1@34 0@42 1@58
wave: CLK, X, Q0, Q1, Y
time: 72
```

::: predict
## A state machine with 10 states is encoded one-hot. How many flip-flops does it use, and how many unused codes does it leave?

- [ ] 4 flip-flops, 6 unused codes
- [x] 10 flip-flops, 1014 unused codes
- [ ] 10 flip-flops, no unused codes
- [ ] 1024 flip-flops

::: reveal
Ten flip-flops, one per state, and $2^{10} - 10$ = 1014 codes that should never occur (any pattern without exactly one 1). Binary would use 4 flip-flops and leave 6 unused. One-hot's next-state logic is simple (each state's flip-flop is set by an OR of its incoming transitions), so it's fast, and FPGAs have flip-flops to spare. A safe design detects illegal codes, for one-hot by checking that exactly one bit is set, and returns to a known state.
:::
:::

::: nameit
## Moore and Mealy

- **Moore:** outputs depend only on the state. They change just after clock edges and are glitch-free if registered.
- **Mealy:** outputs depend on state and inputs, so they can react in the same cycle, often with one fewer state, but they're combinational paths from input to output and can glitch.

A detector for an L-bit pattern needs about L states as a Mealy machine and L + 1 as a Moore machine.

## The three-block style

```verilog
always @(posedge clk) if (rst) state <= S0; else state <= next;   // state register
always @* begin next = state; case (state) ... endcase end          // next-state logic
always @* begin y = 0; case (state) ... endcase end                 // output logic
```

Defaults (`next = state;`, `y = 0;`) prevent latches and make unlisted cases hold.

## State encoding

| Encoding | Flip-flops for N states | Notes |
|---|---|---|
| binary | $\lceil\log_2N\rceil$ | fewest flip-flops, most complex logic |
| Gray | $\lceil\log_2N\rceil$ | one bit changes per step along a sequence: low power, safe across clock domains |
| one-hot | N | simple, fast logic; easy to decode |

## Unused states

Binary encoding of N states leaves $2^{\lceil\log_2N\rceil} - N$ unused codes; one-hot leaves $2^N - N$. A `default` branch that sends any illegal state to the reset state makes the machine recover from upsets, though synthesis tools may optimize it away unless told to keep "safe" encoding.
:::

::: example
## A UART receiver controller has 11 states. Compare binary, Gray and one-hot encodings.

::: solution
1. **Binary and Gray.** Each uses $\lceil\log_2 11\rceil = 4$ flip-flops, leaving
   $$16 - 11 = 5\ \text{unused codes}$$
2. **One-hot.** It uses 11 flip-flops, leaving
   $$2048 - 11 = 2037\ \text{unused codes}$$
3. **When Gray helps.** If the machine mostly steps through states in order (start bit, 8 data bits, stop bit), Gray encoding changes one flip-flop per step, which saves power and makes the state safe to sample from another clock domain.

**Answer:** binary and Gray need 4 flip-flops with 5 unused codes; one-hot needs 11 with 2037 unused codes.
:::
:::

::: example
## Design the state count for detecting the pattern 1011 on a serial input, as Moore and Mealy machines.

::: solution
1. **Mealy machine.** It needs a state for each prefix matched so far: nothing, 1, 10 and 101. That's 4 states, with the output raised on the transition that completes 1011.
2. **Moore machine.** It also needs a state meaning "just matched 1011", where the output is 1, so 5 states.
3. **Overlapping matches.** With overlaps allowed, the machine goes from "matched" to the state for the longest suffix that's also a prefix, here "1".

**Answer:** 4 states as a Mealy machine and 5 as a Moore machine.
:::
:::

::: example
## An 8-state machine steps through its states in a fixed order, like a counter. How many flip-flops toggle per step on average with binary and with Gray encoding?

::: solution
1. **Binary toggles.** Over one full cycle of 3-bit binary, bit 0 toggles 8 times, bit 1 four times and bit 2 twice:
   $$\frac{8 + 4 + 2}{8} = 1.75\ \text{per step}$$
2. **Gray toggles.** A Gray sequence changes exactly one bit per step, 1.0.
3. **The saving.** Clock and data power scale with toggles, so Gray saves
   $$1 - \frac{1}{1.75} = 43\%$$
   of the state register's switching.

**Answer:** 1.75 flip-flops toggle per step in binary and 1.0 in Gray, a 43% saving.
:::
:::

::: check
given: N = 5 | 11 | 27
answer: 2^ceil(log(N)/log(2)) - N
tolerance: 0

## A binary-encoded machine has {N} states. How many unused codes does it leave?

::: right
Right. $2^{\lceil\log_2N\rceil} - N$ = {answer}.
:::

::: misses
- [any] Not yet. Count the codes the flip-flops can hold, minus the states.
:::
:::

::: check
given: N = 4 | 7 | 9
answer: 2^N - N
tolerance: 0

## A one-hot machine has {N} states. How many unused (illegal) codes does it leave?

::: right
Right. $2^N - N$ = {answer}.
:::

::: misses
- [2^N] Subtract the N legal one-hot codes.
- [any] Not yet. Every pattern without exactly one 1 is illegal.
:::
:::

::: check
given: L = 3 | 5 | 8
answer: L + 1
tolerance: 0

## How many states does a Moore machine need to detect a non-overlapping {L}-bit pattern?

::: right
Right. L + 1 = {answer}: one per prefix matched, plus a state that holds the output.
:::

::: misses
- [L] That's the Mealy count; a Moore machine needs a state to hold the output.
- [any] Not yet. One state per partial match, plus the matched state.
:::
:::

::: check
given: N = 6 | 13 | 33
answer: N - ceil(log(N)/log(2))
tolerance: 0

## How many more flip-flops does one-hot use than binary for {N} states?

::: right
Right. $N - \lceil\log_2N\rceil$ = {answer}.
:::

::: misses
- [any] Not yet. N against $\lceil\log_2N\rceil$.
:::
:::

::: check
kind: boolean
vars: X, Q1, Q0
answer: X & (Q0 | Q1)
ops: and, or, not

## In the two-ones detector (S0 = 00, S1 = 01, S2 = 10), write the next value of Q1: it's 1 when X = 1 and the machine is in S1 or S2.

::: right
Right. $X(Q_0 + Q_1)$; code 11 never occurs, so including it costs nothing.
:::

::: misses
- [X & Q0] S2 must stay in S2 while X stays 1: include $Q_1$.
- [any] Not yet. List the states that lead to S2 when X = 1.
:::
:::

::: check
given: n = 4 | 8 | 16
answer: n
tolerance: 0

## An {n}-bit binary counter wraps from all ones back to zero. How many flip-flops change at once? (A Gray counter would change one.)

::: right
Right. All {answer} of them: the biggest burst of switching a binary counter makes, and a hazard if another clock domain samples it mid-change.
:::

::: misses
- [1] That's a Gray counter; binary flips every bit at the wrap.
- [any] Not yet. Compare 11...1 with 00...0.
:::
:::

::: check
kind: parts
given: S = 5 | 7 | 11 | 13

## A state machine has {S} states.

::: part
answer: ceil(log(S)/log(2))
tolerance: 0

### How many flip-flops does binary encoding use?

::: misses
- [any] $\lceil\log_2S\rceil$.
:::
:::

::: part
answer: 2^ceil(log(S)/log(2)) - S
tolerance: 0

### How many codes does it leave unused?

::: misses
- [any] $2^{\lceil\log_2S\rceil} - S$.
:::
:::

::: part
answer: 2^S - S
tolerance: 0

### How many codes does one-hot encoding leave unused?

::: misses
- [S] One-hot uses S flip-flops, so it has $2^S$ codes.
- [any] $2^S - S$.
:::
:::
:::

::: check
kind: derivation
vars: n = 1..24

## An n-bit state register steps through all $2^n$ codes in order, once around.

::: step
answer: 2^(n + 1) - 2

### How many bit toggles does a binary count make in one full cycle?
:::

::: step
answer: 2 - 2^(1 - n)

### How many per step on average?
:::

::: step
answer: 1/(2 - 2^(1 - n))

### What fraction of that does a Gray sequence need?
:::

::: right
Right. Binary counting averages almost two toggles per step for any width, Gray exactly one.
:::
:::

::: explain
## Why do Moore outputs avoid glitches that Mealy outputs can have?

::: model
A Moore machine's outputs are a function of the state alone, and the state lives in flip-flops that all change together just after a clock edge. Once the output logic settles after that edge, the outputs stay put for the rest of the cycle, and if they're taken straight from flip-flops (or registered) they don't glitch at all. A Mealy machine's outputs also depend on the inputs, which can change at any time during the cycle, possibly with several bits changing at slightly different moments. The output logic then passes those transients through as glitches, and it creates a combinational path from the machine's inputs to its outputs that the surrounding timing must accommodate.
:::
:::

::: practice

::: check
given: N = 5 | 7 | 10 | 13 | 20 | 33
answer: 2^ceil(log(N)/log(2)) - N
tolerance: 0

## Unused binary codes for {N} states?

::: misses
- [any] $2^{\lceil\log_2N\rceil} - N$.
:::
:::

::: check
given: N = 4 | 5 | 6 | 8 | 10 | 12
answer: 2^N - N
tolerance: 0

## Illegal one-hot codes for {N} states?

::: misses
- [any] $2^N - N$.
:::
:::

::: check
given: L = 3 | 4 | 5 | 6 | 7 | 8
answer: L + 1
tolerance: 0

## Moore states for an {L}-bit pattern?

::: misses
- [any] L + 1.
:::
:::
:::
