---
title: Finite state machines in Verilog
heading: Writing a state machine as a state register, next-state logic and output logic, Moore and Mealy outputs, encoding states in binary or one-hot, a rising-edge detector as the smallest useful example, and timers built from counters for machines that wait
eyebrow: D10 · Lesson 6 · Finite state machines in Verilog
xp: 40
---

::: hook
The controller of lesson 3, a traffic light, a USB protocol engine and a vending machine are all **finite state machines**: a register remembering which state the system is in, logic deciding the next state from the current state and the inputs, and logic producing outputs. Verilog designers write them in a fixed, recognizable pattern, because a state machine written any other way is hard to read and easy to get wrong. The smallest useful one fits in two lines: a detector that fires for one clock when a button goes from released to pressed.
:::

::: play
- A rising-edge detector: a flip-flop Q remembers the input X from the previous clock, and the output P = X & ~Q is 1 for exactly the first clock cycle after X rises.
- Hold X high for many cycles: P still pulses once. That's how a button press becomes a single event.
- This is a two-state machine (Q = 0 or 1) with a Mealy output, one that depends on the input as well as the state.
:::

```sim logic
clock CLK 8
input X
output P
always @(posedge CLK) Q <= X;
assign P = X & ~Q;
stim X 0@0 1@10 0@42 1@58
wave: CLK, X, Q, P
time: 80
```

::: predict
## A traffic light must stay green for 30 s, and its state machine counts ticks of a 1 kHz clock. How many bits does its timer need?

- [ ] 5
- [ ] 10
- [x] 15
- [ ] 30,000

::: reveal
30 s at 1 kHz is 30,000 ticks, and $2^{14}$ = 16,384 < 30,000 ≤ $2^{15}$ = 32,768, so a 15-bit counter. The state machine resets the counter on entering green and moves on when it reaches 29,999: timers like this are how state machines wait.
:::
:::

::: nameit
## The three-part pattern

```verilog
// 1. state register
always @(posedge clk)
  if (reset) state <= IDLE;
  else       state <= next;

// 2. next-state logic
always @(*) begin
  next = state;
  case (state)
    IDLE: if (coin) next = PAID;
    PAID: if (push) next = IDLE;
  endcase
end

// 3. output logic
assign unlocked = (state == PAID);
```

## Moore and Mealy

- A **Moore** output depends only on the state, so it changes only at clock edges and is glitch-free.
- A **Mealy** output depends on the state and the inputs, so it can respond in the same cycle, as the edge detector's P does, but it can glitch when the inputs do.

## Encoding

- **Binary**: S states in $\lceil\log_2S\rceil$ flip-flops; n flip-flops hold up to $2^n$ states.
- **One-hot**: one flip-flop per state, exactly one set at a time; more flip-flops but simpler, faster logic, which suits FPGAs with their plentiful flip-flops.
- **Gray**: adjacent states differ in one bit, useful when the state crosses clock domains (lesson 8).

## Timers

A machine that waits counts clock ticks: waiting T seconds at f hertz takes $\lceil\log_2(Tf)\rceil$ counter bits.
:::

::: example
## A vending machine has 9 states. How many flip-flops do binary and one-hot encodings need? How long a timer for a 250 ms debounce at 50 MHz?

::: solution
1. **Binary encoding.**
   $$\lceil\log_2 9\rceil = 4\ \text{flip-flops}$$
   giving 16 codes, 7 unused.
2. **One-hot encoding.** One flip-flop per state: 9.
3. **Debounce ticks.** 0.25 s at 50 MHz is
   $$\begin{aligned} &0.25 \times 50 \times 10^6 \\ &= 12.5\ \text{million ticks} \end{aligned}$$
4. **Timer width.**
   $$\lceil\log_2 (1.25 \times 10^7)\rceil = 24\ \text{bits}$$

**Answer:** 4 flip-flops in binary and 9 in one-hot, and a 24-bit timer for the debounce.
:::
:::

::: example
## X is 0 for two clocks, then 1 for five, 0 for one, and 1 for three. How many pulses does the edge detector produce?

::: solution
1. **What makes a pulse.** The edge detector makes one pulse at each 0-to-1 transition, regardless of how long X then stays high.
2. **Count the transitions.** X rises once after its first two clocks of 0, and again after its one clock of 0.

**Answer:** two pulses.
:::
:::

::: example
## A detector for the overlapping sequence 101 is built as a Moore and as a Mealy machine. How many states does each need?

::: solution
1. **Mealy machine.** Three states (nothing yet, seen 1, seen 10), with the output 1 on the transition from "seen 10" on input 1.
2. **Moore machine.** It needs a fourth state, "seen 101", whose output is 1, and the detection appears a clock later.
3. **The trade-off.** Mealy machines are smaller and faster; Moore outputs are glitch-free.

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

::: check
kind: boolean
vars: X, Q
answer: X & ~Q
ops: and, or, not

## A flip-flop Q holds the input X from the previous clock. Write the rising-edge detector's output P, which is 1 when X is 1 now but was 0 last clock.

::: right
Right. P = X & ~Q.
:::

::: misses
- [any] X now, and not X before.
:::
:::

::: check
given: T = 0.03 | 1 | 30; f = 1 | 50 | 100
answer: ceil(log(T*f*1e3)/log(2))
tolerance: 0.4

## A state machine must wait {T} s, counting a {f} kHz clock. How many bits does its counter need?

::: right
Right. $\lceil\log_2(Tf)\rceil$ = {answer} bits.
:::

::: misses
- [any] Not yet. Enough bits to count Tf ticks.
:::
:::

::: check
given: n = 3 | 5 | 8
answer: 2^n
tolerance: 0.4

## How many states can a binary-encoded state machine with {n} flip-flops have at most?

::: right
Right. $2^n$ = {answer}.
:::

::: misses
- [n] That's one-hot: n flip-flops for n states.
- [any] Not yet. Every bit pattern is a state.
:::
:::

::: check
kind: choice

## A state machine's output must never glitch, even when its inputs are noisy. Which kind of output should it use?

- [x] Moore: computed from the state alone
- [ ] Mealy: computed from the state and the inputs
- [ ] Either; glitches come only from the clock
- [ ] Neither; outputs always glitch

::: misses
- [2] A Mealy output follows input changes between clock edges, glitches included.
- [3] Combinational paths from noisy inputs can glitch at any time.
- [4] An output taken straight from flip-flops changes only at clock edges.
:::
:::

::: check
kind: parts
given: t = 10 | 50 | 250; f = 25 | 50 | 100

## A debounce timer must wait {t} ms on a {f} MHz clock.

::: part
answer: t/1000*f*1e6
unit: ticks
tolerance: 0.5%

### How many ticks is that?

::: misses
- [any] Time × clock.
:::
:::

::: part
answer: ceil(log(t/1000*f*1e6)/log(2))
unit: bits
tolerance: 0

### How wide must the counter be?

::: misses
- [any] $\lceil\log_2(\text{ticks})\rceil$.
:::
:::
:::

::: check
kind: parts
given: n = 3 | 4 | 5

## A detector for an overlapping {n}-bit sequence with no internal repeats (like 1000…01 patterns) is built as a Mealy machine.

::: part
answer: n
tolerance: 0

### How many states does it need (one for each prefix seen, from none to {n} − 1 bits)?

::: misses
- [any] One per prefix length, 0 to n − 1.
:::
:::

::: part
answer: n + 1
tolerance: 0

### And as a Moore machine, which needs a state for the full match?

::: misses
- [any] One more.
:::
:::
:::

::: explain
## Why is a state machine written as separate state-register, next-state and output parts?

::: model
The three parts are different kinds of hardware: the state register is a bank of flip-flops that changes only at clock edges, while the next-state and output logic are combinational circuits that react continuously. Writing each in its own block makes the code mirror that structure, so the synthesizer infers exactly the flip-flops intended and nothing else, and a reader can see at a glance which signals are registered. It also keeps the combinational parts complete, with a default next state and every output assigned, which avoids accidental latches, and it makes the transitions easy to check against the state diagram the design started from.
:::
:::

::: practice

::: check
given: T = 0.01 | 100; f = 1 | 200
answer: ceil(log(T*f*1e3)/log(2))
tolerance: 0.4

## Counter bits: {T} s at {f} kHz?

::: misses
- [any] $\lceil\log_2(Tf)\rceil$.
:::
:::

::: check
given: n = 1 | 2 | 4 | 6 | 10 | 16
answer: 2^n
tolerance: 0.4

## Maximum states with {n} binary flip-flops?

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