State Machine Interview Vault and Revision
This last volume is for practice and revision. It puts the whole course on one page, then tests it from every side: 30 design problems with full solutions, 20 interview questions with model answers, 10 pieces of buggy Verilog to fix, and 40 flashcards.
- The whole course on one page, with the key numbers and rules
- 30 design problems, from parity checkers to arbiters, solved step by step
- Model answers to the questions interviewers ask most about FSMs
- How to spot the ten most common bugs in FSM code
- Flashcards for quick, regular revision
- Volumes 01 to 13 - or dip in, and follow the links back when a topic is new
14.1 One-page revision sheet
The whole course fits on one page: what a state machine is, how to design and write one, and how to make it fast, safe and well tested.
Read this sheet the evening before an exam or an interview. If a line feels unfamiliar, the first column links back to the volume that explains it.
The ideas, volume by volume
| Volume | Remember this |
|---|---|
| 01 What is a state machine? | A state is what the machine remembers about the past. States, inputs, outputs and transitions make the machine; the clock decides when it steps. |
| 02 Moore, Mealy, Medvedev | Moore outputs depend on the state only. Mealy outputs also depend on the inputs, so they react a cycle sooner. Medvedev outputs are the state bits themselves. |
| 03 Design by hand | Give the states codes, write the next-state table, use your flip-flop's excitation table, and simplify with K-maps. |
| 04 Verilog | A clocked block for the state register, a combinational block for the next state and outputs, defaults at the top, and a reset. |
| 05 State encoding | Binary uses the fewest flip-flops. One-hot uses one per state and gives fast, simple logic. Gray changes one bit per step. |
| 06 Sequence detectors | One state for each prefix of the pattern. After each bit, go to the longest prefix that the input now ends with. |
| 07 Counters and timers | Every counter is a state machine. A timer counts clock cycles; a debouncer waits until the input is steady. |
| 08 Real controllers | States for the phases of the job, counters for time, and registered outputs. |
| 09 Working together | A controller steers a datapath. Machines talk through handshakes. Signals from another clock need a synchroniser. |
| 10 Minimisation | Equivalent states give the same outputs, now and later, for every input. Merge them with the partition method. |
| 11 Safe FSMs | Plan for illegal states and recover to a safe one. Parity detects a flipped bit, a distance-3 code corrects it, and TMR outvotes it. |
| 12 Verification | Take every arrow at least once, measure coverage, write assertions, and let formal tools prove what can happen. |
| 13 Timing | The loop from the state register, through the next-state logic and back, sets the clock speed. Registered outputs are early and clean. |
Numbers and formulas
| What | Number or formula |
|---|---|
| Flip-flops for N states | binary or Gray: ⌈log₂ N⌉; one-hot: N; Johnson: ⌈N / 2⌉ |
| Detector for an n-bit pattern | Mealy: n states; Moore: n + 1 states |
| Divisible-by-N checker, most significant bit first | new remainder = (2 × remainder + bit) mod N; at most N states |
| Timer for T seconds at clock frequency f | T × f clock cycles |
| Counter for M different values | ⌈log₂ M⌉ bits |
| UART clock cycles per bit | clock frequency ÷ baud rate |
| Clock period of a state machine | at least clock-to-Q + next-state logic + setup time |
| Shortest test that takes every arrow | at least one input per arrow |
The sign ⌈ ⌉ means "round up to a whole number". For example, ⌈log₂ 12⌉ = 4: three bits give only 2³ = 8 codes, and four give 2⁴ = 16.
Flip-flop excitation tables
Each entry says what a flip-flop's inputs must be to take its output from one value to the next. X means that either value works.
| Flip-flop | 0 → 0 | 0 → 1 | 1 → 0 | 1 → 1 |
|---|---|---|---|---|
| D | D = 0 | D = 1 | D = 0 | D = 1 |
| T | T = 0 | T = 1 | T = 1 | T = 0 |
| JK | J = 0, K = X | J = 1, K = X | J = X, K = 1 | J = X, K = 0 |
| SR | S = 0, R = X | S = 1, R = 0 | S = 0, R = 1 | S = X, R = 0 |
The Verilog template
localparam [1:0] IDLE = 2'b00, RUN = 2'b01, DONE = 2'b10;
reg [1:0] state, next_state;
// 1. the state register
always @(posedge clk)
if (rst) state <= IDLE;
else state <= next_state;
// 2. the next-state logic
always @(*) begin
next_state = state; // default: stay
case (state)
IDLE: if (start) next_state = RUN;
RUN: if (last) next_state = DONE;
DONE: next_state = IDLE;
default: next_state = IDLE; // 11 is not a state: recover
endcase
end
// 3. a registered output, decided from next_state
always @(posedge clk)
if (rst) busy <= 1'b0;
else busy <= (next_state == RUN);
Choosing
- Moore or Mealy? Moore, or registered outputs, when an output leaves the block or must be clean. Mealy when answering one cycle sooner matters.
- Which encoding? One-hot on FPGAs and for speed. Binary or Gray for small machines on an ASIC. Output encoding when outputs must never glitch.
- Which reset? Follow the team's convention. If the reset is asynchronous, release it in step with the clock.
Before you call a machine finished
- A reset puts it in a known state, and every state can be reached from there.
- Every output and next_state has a default, so there are no latches.
- Codes that are not states lead back to a safe state.
- Inputs from pins or other clocks pass through a synchroniser.
- Every arrow has been taken in a test, and coverage proves it.
- Outputs that leave the block come from flip-flops.
- The timing report shows that the next-state loop fits in the clock period.
A T flip-flop must go from 1 to 0. What must T be?
Show the answer
Answer: B. A T flip-flop flips its output when T = 1 and keeps it when T = 0. Going from 1 to 0 is a change, so T must be 1. In general, T = old value XOR new value.
14.2 30 design problems, solved
Every design problem starts with the same question: what must the machine remember? Answer that, and the states almost name themselves.
Try each problem on paper before you open the solution. They are grouped by topic, and they get harder as you go. All of them were written for this course, in the style of university exams, GATE and chip-design interviews.
Drawing machines
Odd number of ones
Design a Moore machine with input x and output z. z must be 1 whenever an odd number of 1s has arrived so far. Give its state table.
Show the solution
The machine needs to remember one fact: is the number of 1s so far even or odd? That gives two states.
| State | x = 0 | x = 1 | z |
|---|---|---|---|
| EVEN (start) | EVEN | ODD | 0 |
| ODD | ODD | EVEN | 1 |
A 0 changes nothing, and a 1 flips the state. In hardware this is a single T flip-flop with T = x, and z is simply its output - a Medvedev machine.
A lamp that toggles
A lamp must change - off to on, or on to off - each time a button is pressed. The button input b is already clean: 1 while the button is held, 0 while it is released. Holding the button down must not toggle the lamp again. Design a Moore machine.
Show the solution
The machine must remember two facts: is the lamp on, and is the button already down? Two yes-or-no facts give four states.
| State | Meaning | b = 0 | b = 1 | lamp |
|---|---|---|---|---|
| OFF0 (start) | lamp off, button up | OFF0 | ON1 | 0 |
| ON1 | lamp on, button still down | ON0 | ON1 | 1 |
| ON0 | lamp on, button up | ON0 | OFF1 | 1 |
| OFF1 | lamp off, button still down | OFF0 | OFF1 | 0 |
The lamp changes only when the machine moves from a "button up" state to a "button down" state. Holding the button keeps the machine in ON1 or OFF1, so nothing more happens.
Two's complement, one bit at a time
A number arrives one bit per clock cycle, least significant bit first. Design a Mealy machine whose output z is the number's two's complement - its negative - also one bit per cycle.
Show the solution
There is a handy rule for two's complement. Starting from the right, copy the bits up to and including the first 1, then invert every bit after it. For example, 0110 1000 becomes 1001 1000.
So the machine needs to remember whether the first 1 has gone by yet. Entries read next state / output:
| State | x = 0 | x = 1 |
|---|---|---|
| COPY (start) | COPY / 0 | INVERT / 1 |
| INVERT | INVERT / 1 | INVERT / 0 |
In COPY the output equals the input, and in INVERT it is the opposite. It must be a Mealy machine, because each output bit depends on the input bit arriving in the same cycle.
A serial adder
Two numbers arrive side by side on inputs a and b, one bit of each per cycle, least significant bits first. Design a machine whose output s is their sum, also one bit per cycle.
Show the solution
When you add by hand, you work from the right and remember one thing between columns: the carry. So the state is the carry, and a serial adder needs only two states. In each cycle:
- the sum bit is s = a XOR b XOR carry - a Mealy output, because it uses the inputs now
- the next carry is 1 when at least two of a, b and the carry are 1
| State | ab = 00 | ab = 01 | ab = 10 | ab = 11 |
|---|---|---|---|---|
| C0 (carry 0, start) | C0 / 0 | C0 / 1 | C0 / 1 | C1 / 0 |
| C1 (carry 1) | C0 / 1 | C1 / 0 | C1 / 0 | C1 / 1 |
One flip-flop and a full adder can add numbers of any length. After the last pair of bits, the state holds the final carry.
Mealy or Moore: a change detector
Output z must be 1 for one cycle whenever the input x changes, from 0 to 1 or from 1 to 0. Assume x was 0 before reset. How many states does a Mealy machine need? How many does a Moore machine need?
Show the solution
Mealy: 2 states. The machine remembers the last value of x, in state L0 or L1. The output is z = x XOR last value, so it comes out in the same cycle as the change.
Moore: 4 states. A Moore output belongs to a state, so each state must also say whether a change has just happened:
| State | Meaning | x = 0 | x = 1 | z |
|---|---|---|---|---|
| A0 (start) | last 0, no change | A0 | B1 | 0 |
| A1 | last 0, just changed | A0 | B1 | 1 |
| B0 | last 1, no change | A1 | B0 | 0 |
| B1 | last 1, just changed | A1 | B0 | 1 |
The Moore output also arrives one cycle later, in the state after the change. This is the usual trade: Mealy is smaller and quicker, while Moore is steadier.
Designing by hand
An up/down counter with D flip-flops
Design a 2-bit counter Q1 Q0 with an input u. When u = 1 it counts up: 00, 01, 10, 11, 00 and so on. When u = 0 it counts down. Use D flip-flops, and find the equations for D1 and D0.
Show the solution
First, the next state for every present state and every value of u:
| Q1 Q0 | u = 0 (down) | u = 1 (up) |
|---|---|---|
| 00 | 11 | 01 |
| 01 | 00 | 10 |
| 10 | 01 | 11 |
| 11 | 10 | 00 |
For a D flip-flop, D is simply the next value.
- Bit 0 changes at every step, up or down: D0 = NOT Q0.
- Bit 1 flips when counting up from Q0 = 1, or counting down from Q0 = 0. So it flips exactly when Q0 equals u: D1 = Q1 XOR (Q0 XNOR u).
A K-map of D1 shows a checkerboard pattern - the sign of an XOR.
The same counter with T flip-flops
Build the counter of the last problem with T flip-flops instead.
Show the solution
A T flip-flop flips when T = 1, so T must be 1 exactly when a bit has to change. We already know when each bit changes:
- T0 = 1, because bit 0 changes at every step
- T1 = Q0 XNOR u, because bit 1 changes when Q0 equals u
That is why T flip-flops suit counters so well. Each equation simply answers the question "when does this bit flip?"
Check a JK counter
A counter should go 00 → 01 → 10 → 00, using two JK flip-flops. The designer chose J0 = NOT Q1, K0 = 1, J1 = Q0 and K1 = 1. Check that it counts correctly. What happens if something puts it in the unused state 11?
Show the solution
Remember the JK rules: J = 1 and K = 1 flips; J = 0 and K = 1 clears; J = 1 and K = 0 sets; J = 0 and K = 0 holds.
| Q1 Q0 | J1 K1 | J0 K0 | next Q1 Q0 |
|---|---|---|---|
| 00 | 0 1: clear | 1 1: flip | 01 |
| 01 | 1 1: flip | 1 1: flip | 10 |
| 10 | 0 1: clear | 0 1: clear | 00 |
| 11 | 1 1: flip | 0 1: clear | 00 |
The counter goes 00, 01, 10 and back to 00, as it should. From the unused state 11 it reaches 00 in one step, so it can never get stuck there. A counter like this is called self-correcting.
Writing Verilog
The lamp toggler in Verilog
Write the lamp machine from Practice 2 in Verilog, in the two-block style of Volume 04.
Show the solution
module lamp_toggle (
input wire clk,
input wire rst,
input wire b, // the button: already debounced and synchronised
output wire lamp
);
// Gray codes round the loop; bit 0 is the lamp
localparam [1:0] OFF0 = 2'b00, ON1 = 2'b01, ON0 = 2'b11, OFF1 = 2'b10;
reg [1:0] state, next_state;
always @(posedge clk)
if (rst) state <= OFF0;
else state <= next_state;
always @(*) begin
next_state = state; // default: stay
case (state)
OFF0: if (b) next_state = ON1; // pressed: lamp on
ON1: if (!b) next_state = ON0; // released
ON0: if (b) next_state = OFF1; // pressed again: lamp off
OFF1: if (!b) next_state = OFF0; // released
endcase
end
assign lamp = state[0]; // ON1 = 01 and ON0 = 11
endmodule
The codes were chosen with care. Round the loop they form a Gray sequence, so one bit changes per step. And bit 0 is 1 in exactly the two ON states, so the lamp comes straight from a flip-flop and cannot glitch. That is output encoding, from Volume 05. All four codes are used, so there is no illegal state to guard against.
The serial adder in Verilog
Write the serial adder from Practice 4 in Verilog.
Show the solution
module serial_adder (
input wire clk,
input wire rst, // clears the carry before a new sum
input wire a, b, // one bit of each number per cycle, LSB first
output wire s // one bit of the sum per cycle
);
reg carry; // the whole state: one flip-flop
assign s = a ^ b ^ carry; // Mealy output: uses the inputs now
always @(posedge clk)
if (rst) carry <= 1'b0;
else carry <= (a & b) | (a & carry) | (b & carry);
endmodule
With only two states, there is no need for named states or a case statement. The carry flip-flop is the state register, and the two equations are the whole machine.
Encodings
Counting flip-flops
A machine has 12 states. How many flip-flops does it need with binary, Gray, one-hot and Johnson encoding?
Show the solution
- Binary and Gray: 4. Three bits give only 8 codes; four give 16, which is enough.
- One-hot: 12. One flip-flop per state.
- Johnson: 6. A Johnson code with n flip-flops has 2n codes, so 6 flip-flops give 12.
Fewer flip-flops usually means more decoding logic. One-hot spends flip-flops to save logic.
Codes for a loop
A machine always steps round the same loop: A → B → C → D → A. Choose 2-bit codes so that only one bit changes at every step. Why might you want that?
Show the solution
Use a Gray code: A = 00, B = 01, C = 11 and D = 10. Every step changes one bit, including the step from D back to A.
With one bit changing at a time, gates that decode the state never see a false code in between, so decoded outputs cannot glitch (Volume 13). Fewer flip-flops toggle, too, which saves power.
Sequence detectors
Detect 110 (Mealy)
Design a Mealy machine with output z = 1 when the last three input bits were 1, 1, 0. Matches may overlap.
Show the solution
Keep one state for each prefix of the pattern that the input might be in the middle of: S0 (nothing useful yet), S1 (seen 1) and S11 (seen 11). Entries read next state / output:
| State | x = 0 | x = 1 |
|---|---|---|
| S0 | S0 / 0 | S1 / 0 |
| S1 | S0 / 0 | S11 / 0 |
| S11 | S0 / 1 | S11 / 0 |
Two entries deserve a second look. In S11, another 1 keeps the machine in S11, because the last two bits are still 11. And after a match the input ends in 0, which starts no new match, so the machine returns to S0.
Detect 1001 (Moore)
Design a Moore machine for the pattern 1001, with overlapping matches. How many states does it need?
Show the solution
Five: one for each prefix of the pattern, from nothing up to the whole of it. S1001 is the only state with z = 1.
| State | x = 0 | x = 1 | z |
|---|---|---|---|
| S0 | S0 | S1 | 0 |
| S1 | S10 | S1 | 0 |
| S10 | S100 | S1 | 0 |
| S100 | S0 | S1001 | 0 |
| S1001 | S10 | S1 | 1 |
The hard part is where each state goes when a bit breaks the pattern. Use the longest-prefix rule from Volume 06: find the longest ending of the input that is still a prefix of 1001. From S1001, a 0 makes the input end in ...10010, which ends with 10, so go to S10. From S100, a 0 makes ...1000. No ending of that is a prefix of 1001, so go back to S0.
Two patterns at once
Design a Mealy machine with z = 1 when the last three bits are either 101 or 110. Matches may overlap.
Show the solution
Use the prefixes of both patterns as states: S0 (nothing), S1 (1), S10 (10) and S11 (11). The two patterns share their first bit, so four states cover both. Entries read next state / output:
| State | x = 0 | x = 1 |
|---|---|---|
| S0 | S0 / 0 | S1 / 0 |
| S1 | S10 / 0 | S11 / 0 |
| S10 | S0 / 0 | S1 / 1 |
| S11 | S10 / 1 | S11 / 0 |
After 101 is found, the input ends in 1, so the machine goes to S1. After 110, it ends in 10 - the start of 101 - so the machine goes to S10, ready for a 1.
Overlapping or not?
The input is 1 0 1 1 0 1 1 0 1 1, first bit on the left. A detector looks for 1011. How many matches does it report if matches may overlap? And if they may not?
Show the solution
Number the bits from 1 to 10.
- Overlapping: 3 matches, ending at bits 4, 7 and 10. Each match shares its last 1 with the next one.
- Non-overlapping: 2 matches, ending at bits 4 and 10. After the first match the detector starts afresh at bit 5. The match ending at bit 7 needs bit 4, so it does not count.
In the machine, the only difference is where it goes after a match. An overlapping detector goes to the state for the longest prefix; a non-overlapping one goes back to S0.
Divisible by 5
A binary number arrives most significant bit first. Design a Moore machine with z = 1 whenever the number so far is divisible by 5.
Show the solution
Keep the remainder after dividing by 5: five states, R0 to R4. Each new bit doubles the number and adds the bit, so the new remainder is (2 × r + x) mod 5.
| State | x = 0 | x = 1 | z |
|---|---|---|---|
| R0 (start) | R0 | R1 | 1 |
| R1 | R2 | R3 | 0 |
| R2 | R4 | R0 | 0 |
| R3 | R1 | R2 | 0 |
| R4 | R3 | R4 | 0 |
Try it with 1010, which is ten: R0 → R1 → R2 → R0 → R0. It ends in R0, so z = 1, and ten is indeed divisible by 5.
Divisible by 3, backwards
Now the bits arrive least significant bit first. How many states does a divisible-by-3 checker need?
Show the solution
Only 3 - and the machine from Volume 06, with states R0, R1 and R2, works without any change. This is a favourite trick question.
Here is why. The place values in binary are 1, 2, 4, 8, 16 and so on. Divided by 3, they leave remainders 1, 2, 1, 2, 1 ... and when counting in threes, 2 is the same as −1. So a number's remainder is the number of 1s in the places worth 1, 4, 16 ... minus the number of 1s in the places worth 2, 8, 32 ... Reading the bits in the opposite order either keeps both groups as they are, or swaps them. At worst the remainder changes sign - and a remainder of 0 stays 0.
This needs a special property of 3, so do not expect it in general. For 5 it fails. 19 is 10011 in binary. Fed in backwards, the bits 1, 1, 0, 0, 1 look like 11001, which is 25, so the machine would wrongly call 19 divisible by 5.
Two conditions at once
Design a Moore machine with z = 1 when the number of 1s so far is a multiple of 3 and the number of 0s so far is even. Zero counts as both a multiple of 3 and even.
Show the solution
Think of two small machines running side by side. One counts the 1s in threes: A, B or C for 0, 1 or 2 ones so far, after taking away every full three. The other tracks whether the number of 0s is even (0) or odd (1). The combined machine is a product machine, with one state for each pair: 3 × 2 = 6 states.
| State | x = 0 | x = 1 | z |
|---|---|---|---|
| A0 (start) | A1 | B0 | 1 |
| A1 | A0 | B1 | 0 |
| B0 | B1 | C0 | 0 |
| B1 | B0 | C1 | 0 |
| C0 | C1 | A0 | 0 |
| C1 | C0 | A1 | 0 |
A 0 flips the digit, and a 1 moves the letter on: A → B → C → A. Only A0 has z = 1. No two of these states are equivalent, so 6 is the minimum.
Counters and timers
A 1 ms tick
A state machine with a 50 MHz clock must do something once every millisecond. Design the timer: what does its counter count to, and how many bits does it need?
Show the solution
At 50 MHz there are 50,000,000 cycles per second, so 50,000 per millisecond. Count 0, 1, 2 ... 49,999 and back to 0, and make a one-cycle tick when the count is 49,999. The largest value, 49,999, needs 16 bits, because 2¹⁶ = 65,536.
A common slip is to count up to 50,000. That is 50,001 different values, so the tick comes once every 50,001 cycles.
Size a debouncer
A push-button bounces for up to 5 ms, and the clock is 25 MHz. A debouncer accepts a new level only after the input has stayed steady for 5 ms. How big must its counter be?
Show the solution
5 ms at 25 MHz is 0.005 × 25,000,000 = 125,000 cycles. A counter that reaches 125,000 needs 17 bits: 2¹⁶ = 65,536 is too small, and 2¹⁷ = 131,072 is enough.
The counter restarts whenever the input differs from the accepted level. Only an input that stays steady for the whole 5 ms lets it reach the end.
A Johnson counter
Three flip-flops Q2 Q1 Q0 form a Johnson counter. At each clock edge, Q2 takes NOT Q0, Q1 takes Q2, and Q0 takes Q1. Starting from 000, list the states. How would you decode each one?
Show the solution
000, 100, 110, 111, 011, 001, and back to 000: six states from three flip-flops. A Johnson counter with n flip-flops always has 2n states.
| State | Recognised by |
|---|---|
| 000 | Q2 = 0 and Q0 = 0 |
| 100 | Q2 = 1 and Q1 = 0 |
| 110 | Q1 = 1 and Q0 = 0 |
| 111 | Q2 = 1 and Q0 = 1 |
| 011 | Q2 = 0 and Q1 = 1 |
| 001 | Q1 = 0 and Q0 = 1 |
Each state is recognised by a single 2-input gate. And since only one bit changes per step, these decoded outputs do not glitch. Those are two good reasons to use a Johnson counter for a simple sequencer.
Controllers
A vending machine that gives change
A drink costs 15. The machine accepts coins of 5 and 10, at most one per cycle. Once 15 or more has been paid, it releases a drink (vend) and, if 20 was paid, returns 5 (change). Design a Mealy machine with as few states as possible.
Show the solution
The machine must remember how much has been paid: 0, 5 or 10. That gives three states. When a coin brings the total to 15 or more, the outputs fire in the same cycle and the machine goes back to S0.
| State | coin of 5 | coin of 10 |
|---|---|---|
| S0 (start) | S5 | S10 |
| S5 | S10 | S0, vend |
| S10 | S0, vend | S0, vend and change |
With no coin, the machine stays where it is. You can check that no money is ever lost. Every coin adds to the amount the state stands for, and every drink (15) and every change (5) takes it back to 0.
UART numbers
A UART sends each character as a start bit, 8 data bits and a stop bit, at 115,200 baud. The clock is 50 MHz. How many clock cycles is one bit? One character? How many characters per second can it send at most? When should the receiver first look at the line?
Show the solution
- One bit: 50,000,000 ÷ 115,200 = 434.03, so 434 cycles. The real rate is then 115,207 baud - only 0.006% fast, far inside what a UART tolerates.
- One character: 10 bits, so 4,340 cycles.
- Characters per second: at most 115,200 ÷ 10 = 11,520.
- First look: half a bit, 217 cycles, after the start bit's falling edge. That is the middle of the start bit. The receiver checks that the line is still 0, then samples every 434 cycles, in the middle of each data bit.
A fair arbiter for two
Two blocks share a memory. Each raises a request, r0 or r1. An arbiter answers with a one-cycle grant, g0 or g1 - never both. If both ask at once, they must take turns. Design it.
Show the solution
The machine remembers whose turn it is when both ask: state P0 (requester 0 goes first) or P1.
| State | only r0 | only r1 | both | neither |
|---|---|---|---|---|
| P0 | g0, go to P1 | g1, stay in P0 | g0, go to P1 | stay |
| P1 | g0, stay in P1 | g1, go to P0 | g1, go to P0 | stay |
The rule is simple: whoever is served goes to the back of the queue. The grants are Mealy outputs, because they depend on the requests. When both ask all the time, the grants alternate g0, g1, g0, g1 and so on. A requester that keeps asking never waits more than one cycle. This is a round-robin arbiter, and the same idea works for more requesters.
Bigger systems
Trace a datapath and its controller
The GCD machine of Volume 09 repeats one rule: if A > B, then A = A − B; if B > A, then B = B − A. It stops when A = B. Trace it for A = 48 and B = 18. How many subtractions does it do, and what is the answer?
Show the solution
(48, 18) → (30, 18) → (12, 18) → (12, 6) → (6, 6). That is four subtractions, and the answer is 6.
The controller only chooses what happens in each cycle, from the comparison results. The datapath does the actual subtracting. That split is what makes an FSMD easy to design.
Minimisation
Minimise a Moore machine
Find the smallest machine that behaves exactly like this one.
| State | x = 0 | x = 1 | z |
|---|---|---|---|
| A | B | C | 0 |
| B | D | E | 0 |
| C | F | E | 0 |
| D | A | C | 1 |
| E | D | E | 0 |
| F | A | B | 1 |
Show the solution
Use the partition method from Volume 10. First, group the states by output: P0 = {A, B, C, E} {D, F}.
Next, see which group each state's arrows lead to:
- A goes to B and C, which are both in the first group.
- B, C and E go to the second group on 0, and to the first group on 1.
- D and F go to the first group on both inputs.
A behaves differently from B, C and E, so it splits off: P1 = {A} {B, C, E} {D, F}. Checking again changes nothing, so the machine needs only 3 states:
| State | x = 0 | x = 1 | z |
|---|---|---|---|
| A | BCE | BCE | 0 |
| BCE | DF | BCE | 0 |
| DF | A | BCE | 1 |
Safety
Correct a flipped bit, then vote
A machine uses distance-3 codes: S0 = 00000, S1 = 01011, S2 = 10101 and S3 = 11110. A particle flips one bit, and the register now holds 01111. Which state should the correction logic choose? Then: the three copies of a 4-bit state register under TMR read 0110, 0100 and 1110. What does the voter output?
Show the solution
Count the bits in which 01111 differs from each code: 4 from S0, 1 from S1, 3 from S2 and 2 from S3. The nearest is S1, one bit away, so correct to S1. Every pair of codes is at least 3 bits apart, so after one flipped bit the right code is always the strictly nearest.
The voter takes the majority of each bit: 0110. The second copy has one bad bit and the third has another, in a different place. So every bit still has two correct copies.
Verification
The shortest complete test
Find the shortest input sequence that starts at reset, in S0, and takes every arrow of the 110 detector from Practice 13 at least once.
Show the solution
The detector has 3 states × 2 inputs = 6 arrows, but 6 inputs are not enough. Look at S0: three arrows come into it (from S0, S1 and S11), but only two go out. The walk is in S0 at the start and after each of those three arrows, which makes four visits. Every visit except the last needs a way out, so S0 must be left at least three times. With only two arrows out, one of them must be used twice, so at least 7 inputs are needed.
Seven are enough: 0, 1, 0, 1, 1, 1, 0.
| Input | Arrow taken |
|---|---|
| 0 | S0 → S0 |
| 1 | S0 → S1 |
| 0 | S1 → S0 |
| 1 | S0 → S1, a second time |
| 1 | S1 → S11 |
| 1 | S11 → S11 |
| 0 | S11 → S0, with z = 1 |
Timing
Faster by encoding
A machine's next-state logic has 7 logic levels of 0.3 ns each. Its flip-flops have a clock-to-Q delay of 0.2 ns and a setup time of 0.1 ns. What is its fmax? After a switch to one-hot, the logic has 3 levels. What is fmax now?
Show the solution
- Before: 0.2 + 7 × 0.3 + 0.1 = 2.4 ns, so fmax = 1 ÷ 2.4 ns, about 417 MHz.
- After: 0.2 + 3 × 0.3 + 0.1 = 1.2 ns, so fmax is about 833 MHz - twice as fast.
The flip-flops did not change. All the gain came from shallower next-state logic.
How many states does a Mealy machine need to detect the 5-bit pattern 11010, with overlapping matches?
Show the answer
Answer: C. It needs one state for each prefix the input could be in the middle of: nothing, 1, 11, 110 and 1101. That is 5 states - n states for an n-bit pattern. The Moore version would need 6.
14.3 20 concept questions
Interviewers ask about state machines to see whether you understand hardware: time, clocks, reset, and what really gets built. A short, clear answer with a reason beats a long one.
Read each question, answer it out loud, and only then compare your answer with the model. The model answers are short on purpose. In an interview, a clear reason matters more than every detail.
What is a finite state machine?
"What is a finite state machine, and where would you use one?"
Show the solution
"It is a circuit that remembers where it is in a job, as one of a limited number of states. At each clock edge it looks at its state and its inputs, and moves to the next state. Its outputs depend on the state, and in a Mealy machine on the inputs too. Anything that follows steps is usually built as one: a protocol, a controller, a detector or a sequencer."
Moore versus Mealy
"What is the difference between a Moore and a Mealy machine?"
Show the solution
"In a Moore machine the outputs depend only on the current state, so they change only after a clock edge. In a Mealy machine they also depend on the current inputs, so they can react in the same cycle. Mealy machines often need fewer states and answer a cycle sooner. Moore outputs are steadier and easier to time, while a Mealy output can pass on a glitch from its inputs."
Why more states for Moore?
"Why does a Moore machine often need more states than a Mealy machine for the same job?"
Show the solution
"A Moore output belongs to a state, so every different output situation needs its own state. A Mealy machine can put the output on an arrow instead, so one state can give different outputs for different inputs. For example, a detector for an n-bit pattern needs n states as a Mealy machine, and n + 1 as a Moore machine."
Accidental latches
"How can FSM code produce a latch by accident, and how do you prevent it?"
Show the solution
"In a combinational always block, if some path through the code does not assign a signal, the signal
must keep its old value. Keeping a value needs memory, so synthesis builds a latch. I prevent it by
giving every output and next_state a default value at the top of the block, and by using
always @(*) or always_comb."
Synchronous or asynchronous reset?
"Do you prefer a synchronous or an asynchronous reset for a state machine?"
Show the solution
"A synchronous reset acts only at a clock edge, so it is easy to time and ignores short glitches, but it needs the clock running. An asynchronous reset acts at once, even without a clock, which helps at power-up. Its danger is the release: if it ends near a clock edge, flip-flops may leave reset in different cycles. So the usual answer is to assert it asynchronously and release it synchronously, through a reset synchroniser. Beyond that, I follow the team's convention."
Why one-hot on FPGAs?
"Why is one-hot encoding so popular on FPGAs?"
Show the solution
"An FPGA has a flip-flop beside every look-up table, so extra flip-flops cost almost nothing. With one-hot, each next-state bit depends on only a few other bits. That keeps the logic to one or two LUT levels, and the clock fast. Decoding is simple too, because each state is a single bit."
Illegal states
"What is an illegal state, and how can a machine get into one?"
Show the solution
"It is a code the state register can hold but the design never uses. Examples are 11 in a three-state machine with two bits, or two hot bits in a one-hot machine. A machine can get there through a particle strike, a glitch on the clock or reset, an unsynchronised input or a timing violation. A safe design detects illegal states and returns to a known state."
The vanishing default branch
"You wrote a default branch that sends illegal states back to IDLE, but it is missing from the synthesised design. Why?"
Show the solution
"Synthesis tools reason about the states the machine can actually reach. No legal transition leads to an illegal code, so the tool may treat the default branch as dead logic and remove it, especially after re-encoding the machine. To keep the recovery logic, I would use the tool's safe-FSM setting or attribute, as covered in Volume 11."
Metastability
"What is metastability, and why does a synchroniser use two flip-flops?"
Show the solution
"If a flip-flop's input changes too close to the clock edge, its output can hang between 0 and 1 for a while before it settles. A signal from another clock domain, or from a pin, can change at any moment, so this will happen sometimes. A second flip-flop gives the first a whole clock cycle to settle before anything uses the value. That makes failures extremely rare, though never impossible."
A pulse across clock domains
"How do you pass a one-cycle pulse from a fast clock domain to a slow one?"
Show the solution
"The slow clock might miss a short pulse completely. One fix is to turn the pulse into a toggle - a level that flips once per event - then synchronise that level and detect its changes on the other side. Another is a request and acknowledge handshake, holding the request until the other side answers. For a steady stream of data, I would use an asynchronous FIFO."
Overlapping detection
"What is the difference between overlapping and non-overlapping sequence detection?"
Show the solution
"With overlapping detection, the end of one match can also be the start of the next. In 10101, the pattern 101 is found twice. With non-overlapping detection, the detector starts afresh after each match, so it is found once. In the machine, the only difference is where it goes after a match."
How many states for a detector?
"How many states does a detector for an n-bit pattern need?"
Show the solution
"With the longest-prefix method, a Mealy detector needs n states: one for each prefix, from empty up to n − 1 bits. A Moore detector needs n + 1, adding a state for the full match that carries z = 1. For a single pattern, these numbers are also the minimum."
Equivalent states
"When are two states equivalent?"
Show the solution
"When no input sequence can tell them apart: for every input sequence, they produce the same outputs. In practice I check it step by step. The states must give the same outputs now, and for every input their next states must be equivalent too. Equivalent states can be merged, and the partition method or the implication table finds them systematically."
What is an FSMD?
"What is an FSMD, and why split a design that way?"
Show the solution
"It is a finite state machine with a datapath. The datapath holds the data - registers, adders, comparators - and does the work. The state machine is the controller. Cycle by cycle, it decides which registers load and which operation runs, and it watches status signals such as a comparison result. The split keeps each part simple, and each can be tested on its own."
Four-phase or two-phase?
"What is the difference between a four-phase and a two-phase handshake?"
Show the solution
"In a four-phase handshake, request and acknowledge are levels: req rises, ack rises, req falls, ack falls. That is four changes per transfer, and both wires end at 0. In a two-phase handshake, every change of req is a request and every change of ack is an answer. That is only two changes per transfer, so it is faster, but each side must remember the last level to spot a change."
What limits the clock speed?
"What limits the clock frequency of a state machine?"
Show the solution
"Its loop: from the state register, through the next-state logic, and back into the state register, all within one clock period. The period must be at least the clock-to-Q delay, plus the logic delay, plus the setup time. To go faster, I make the logic shallower: one-hot encoding, simpler conditions, look-ahead flags, or smaller machines."
Why register the outputs?
"Why would you register the outputs of a state machine?"
Show the solution
"A registered output comes straight from a flip-flop. It changes cleanly just after the clock edge, cannot glitch, and reaches the next block early in the cycle. Timing paths also stop at the block's edge. The cost can be a cycle of delay - unless the output is decided from next_state, which gives the same timing as a decoded Moore output."
Is state coverage enough?
"Is 100% state coverage enough to say a state machine is tested?"
Show the solution
"No. State coverage only says every state was visited. Bugs usually sit on the arrows - a wrong condition or a wrong target - so I want transition coverage: every arrow taken at least once. I would add assertions for rules that must always hold, and check the outputs against a reference model."
Formal versus simulation
"What can formal verification tell you that simulation cannot?"
Show the solution
"Simulation checks only the input sequences I run. A formal tool considers every possible input sequence. So it can prove that a state is unreachable, that an assertion can never fail, or that the machine always gets back to IDLE. When a property is false, it gives a counterexample: an input sequence that breaks it, ready to replay in simulation."
A stuck machine
"Your state machine is stuck in one state on the board. How do you debug it?"
Show the solution
"First, look at the arrows leaving that state and their conditions: the machine is waiting for one of them. Then check those inputs, in simulation or with an on-chip logic analyser. Are they ever true, are they in the right clock domain, and is their polarity right? I would also check that reset was released properly and that the state register holds a legal code. Finally, I would reproduce the problem in simulation with the same inputs."
An interviewer asks why a Mealy output can glitch while a registered output cannot. What is the key point?
Show the answer
Answer: A. A Mealy output is combinational: it follows the inputs through gates, whenever they change. A registered output comes from a flip-flop, which changes only at the clock edge.
14.4 Spot-the-bug drills
Most broken state machines fail in the same few ways. Once you have seen each bug, you will spot it in seconds - in your own code, or in an interview.
Each drill shows a short piece of Verilog with one bug. Find it, and decide how to fix it, before you open the answer.
The output that will not switch off
This block is meant to set busy while the machine is in RUN. What is wrong?
always @(*) begin
next_state = state;
case (state)
IDLE: if (start) next_state = RUN;
RUN: begin
busy = 1'b1;
if (done) next_state = IDLE;
end
endcase
end
Show the solution
busy gets a value only in RUN. In IDLE nothing assigns it, so it must keep its old value - and keeping a value needs memory. Synthesis builds a latch, and busy stays 1 for ever after the first run. Give it a default at the top:
always @(*) begin
next_state = state;
busy = 1'b0; // default: now every path assigns busy
case (state)
IDLE: if (start) next_state = RUN;
RUN: begin
busy = 1'b1;
if (done) next_state = IDLE;
end
endcase
end
Fine on the board, stuck in simulation
In simulation this machine never leaves IDLE, even when start is 1. The same code works on the FPGA. Why?
always @(state) begin
next_state = state;
case (state)
IDLE: if (start) next_state = RUN;
RUN: if (done) next_state = IDLE;
endcase
end
Show the solution
The sensitivity list holds only state. The simulator runs the
block again only when state changes - not when start or done change. So when start rises, next_state
is never worked out again, and the machine waits for ever. Synthesis ignores sensitivity lists and
builds the full logic, so the hardware works. Simulation and hardware now disagree, which is the
worst kind of bug. Use always @(*), which includes every signal the block reads.
A race between two blocks
With one simulator, was_run matches the state. With another, it is one cycle early. Find the problem.
always @(posedge clk)
if (rst) state = IDLE;
else state = next_state;
always @(posedge clk)
was_run <= (state == RUN);
Show the solution
The state register uses blocking assignments (=). Both blocks run at the same clock edge, in an order the simulator chooses. If the first block runs first, the second one already sees the new state; otherwise it sees the old one. The result depends on the simulator: a race. In clocked blocks, always use non-blocking assignments (<=). Then every block reads the values from before the edge.
always @(posedge clk)
if (rst) state <= IDLE;
else state <= next_state;
Reset upside down
The reset input rst_n is active low. After power-up, the machine never leaves IDLE.
always @(posedge clk or negedge rst_n)
if (rst_n) state <= IDLE;
else state <= next_state;
Show the solution
The _n in the name means active low: the reset is on while rst_n = 0. But this code resets while
rst_n is 1 - that is, all the time once reset has ended. And while the reset really is on, the
machine runs. Test for the low level instead: if (!rst_n) state <= IDLE;.
One cycle too many
The machine must stay in WAIT for exactly 10 cycles. count is 0 in the first WAIT cycle and goes up by 1 in each cycle after that. How long does WAIT really last?
always @(posedge clk)
if (state != WAIT) count <= 0;
else count <= count + 1;
// in the next-state logic:
WAIT: if (count == 10) next_state = GO;
Show the solution
Count the WAIT cycles: count is 0, 1, 2 ... 10. That is 11 values, so WAIT lasts 11 cycles - the
machine leaves at the edge after the cycle in which the test is true. For 10 cycles, compare with 9:
if (count == 9). Here is a rule worth keeping: to spend N cycles in a state with a counter that
starts at 0, compare with N − 1.
Two hot bits
btn comes straight from a push-button pin. The machine is one-hot. Once in a while, in the lab, it ends up with two hot bits, or none. Why?
localparam [1:0] IDLE = 2'b01, RUN = 2'b10; // one-hot
always @(*) begin
next_state = state;
case (state)
IDLE: if (btn) next_state = RUN;
RUN: if (done) next_state = IDLE;
endcase
end
Show the solution
btn is asynchronous: it can change at any moment, even just before a clock edge. In IDLE, btn decides the next value of both state bits. If it changes too close to the edge, one flip-flop may take the old value and the other the new one. The result is 11 or 00 - codes that are not states. A flip-flop may even go metastable. Pass btn through a two-flip-flop synchroniser first, and debounce it (Volume 07). Then use the clean version in the machine:
reg btn_s1, btn_s2;
always @(posedge clk) begin
btn_s1 <= btn; // may go metastable: it has a cycle to settle
btn_s2 <= btn_s1; // safe to use
end
// in the next-state logic:
IDLE: if (btn_s2) next_state = RUN;
The missing second match
This Mealy machine should find 101, with overlapping matches. Given 1 0 1 0 1, it reports only one match. Why?
always @(*) begin
next_state = state;
z = 1'b0;
case (state)
S0: if (x) next_state = S1;
S1: if (!x) next_state = S10;
S10: begin
z = x;
next_state = S0;
end
endcase
end
Show the solution
After a match, the final 1 of 101 can start the next match. But this code always goes back to S0 and
forgets it. With 1 0 1 0 1, the first match ends at bit 3, and the second match needs that same bit,
so it is missed. After a 1, go to S1: next_state = x ? S1 : S0;. Then both matches are found, at
bits 3 and 5.
An output one cycle late
vend_r should be 1 during the cycle in which the machine is in VEND. It comes one cycle late. Why?
always @(posedge clk)
if (rst) vend_r <= 1'b0;
else vend_r <= (state == VEND);
Show the solution
In each cycle, a registered value shows what was worked out in the cycle before. This test looks at
the current state, so vend_r becomes 1 in the cycle after the machine enters VEND. Decide it from
where the machine is going instead: vend_r <= (next_state == VEND);. Then vend_r and the state
change at the same edge, as in Volume 04.
Stuck for ever
A three-state machine uses 2-bit codes. A test flips a bit and puts 11 in the state register. The machine never recovers. Why?
localparam [1:0] IDLE = 2'b00, RUN = 2'b01, DONE = 2'b10;
always @(*) begin
next_state = state;
case (state)
IDLE: if (start) next_state = RUN;
RUN: if (last) next_state = DONE;
DONE: next_state = IDLE;
endcase
end
Show the solution
No case item matches 11, so the default at the top keeps next_state = state. The machine stays in 11 for ever: a lock-up. Add a default branch that leads back to a safe state, and make sure synthesis keeps it (Volume 11):
case (state)
IDLE: if (start) next_state = RUN;
RUN: if (last) next_state = DONE;
DONE: next_state = IDLE;
default: next_state = IDLE; // 11 is not a state: recover
endcase
Two owners for one register
An abort input must send the machine to IDLE at once. A designer added a second clocked block. What is wrong?
always @(posedge clk)
if (rst) state <= IDLE;
else state <= next_state;
always @(posedge clk)
if (abort) state <= IDLE;
Show the solution
state is now written by two always blocks. In simulation, both write at the same edge, and whichever runs last wins. Synthesis sees two drivers for one register, and either stops with an error or builds something nobody intended. A register must have exactly one owner. Put abort into the one block, with the priority you want:
always @(posedge clk)
if (rst || abort) state <= IDLE;
else state <= next_state;
Which of these bugs makes simulation and hardware behave differently?
Show the answer
Answer: B. Synthesis ignores sensitivity lists and builds the logic the code describes, while the simulator only re-runs the block for the signals listed. The other three bugs are wrong in simulation and in hardware alike.
14.5 Flashcards
A few minutes of flashcards each day beats a whole night of reading. Say the answer first, then check it.
Click a card to see its answer, and click again to hide it. Try to say the answer out loud first: the effort of remembering is what makes it stick.
01 State
02 Transition
03 Moore output
04 Mealy output
05 Medvedev machine
06 Why does a state machine need a clock?
07 Flip-flops for N states, binary
08 One-hot encoding
09 Gray code
10 Johnson counter
11 D flip-flop excitation
12 T flip-flop excitation
13 JK inputs for 0 → 1
14 JK inputs for 1 → 1
15 Where do accidental latches come from?
16 always @(*)
17 <= or =?
18 Synchronous reset
19 Asynchronous reset
20 Overlapping detection
21 Longest-prefix rule
22 States to detect an n-bit pattern
23 Divisible-by-N checker, MSB first
24 Debouncer
25 Rising-edge detector
26 FSMD
27 Four-phase handshake
28 Two-phase handshake
29 Metastability
30 Two-flip-flop synchroniser
31 Equivalent states
32 Partition method
33 Illegal state
34 Single-event upset
35 Parity on the state
36 Distance-3 code
37 TMR
38 Transition coverage
39 fmax of a state machine
40 Look-ahead
How many states does a Johnson counter with 4 flip-flops have?
Show the answer
Answer: B. A Johnson counter with n flip-flops has 2n states, so 4 flip-flops give 8. A ring counter would give 4, and a binary counter 16.
What you learned in this course
- Describe any step-by-step behaviour as a state machine: states, inputs, outputs and transitions.
- Choose between Moore, Mealy and Medvedev outputs, and convert one into another.
- Design next-state and output logic by hand, with excitation tables and K-maps.
- Write clean Verilog: a state register, next-state logic with defaults, a reset and registered outputs.
- Pick an encoding for size, speed, power or safety.
- Build detectors, counters, timers, debouncers and real controllers.
- Connect machines with datapaths, handshakes and synchronisers.
- Minimise, protect, verify and time a machine, and explain all of it in an interview.
Key words from this volume
Every word below has a plain-English entry in the glossary.
- State
- Prefix
- Two's complement
- Serial adder
- JK flip-flop
- Gray code
- Product machine
- Debouncer
- Johnson counter
- UART
- Arbiter
- Round-robin
- FSMD
- Triple modular redundancy (TMR)
- Latch
- Sensitivity list
- Blocking assignment (=)
- Race (in simulation)
- Synchroniser
- Lock-up
Where to go next
You now know state machines all the way from a single flip-flop to a safe, verified and timed design. Here is where that knowledge can take you next on BlinkNBuild:
- The Verilog and SystemVerilog course covers the whole language, testbenches and timing closure.
- The FPGA course puts your designs on real FPGA boards, with Vivado, Zynq and AXI.
- The ASIC course follows a design from RTL all the way to a chip layout.
- FSM Studio lets you design, draw, simulate and generate Verilog for any machine in this course.
- The GATE ECE digital circuits questions give you more exam-style practice.
Congratulations on finishing State Machines from Zero.