The idea: one FSM, three blocks of code

A finite state machine is a state register plus two blocks of logic: one computes the next state, one computes the output. In SystemVerilog you write it the same way, as three separate blocks in one module. Each block becomes one block of hardware, so you can read the circuit straight from the code.

The page uses the 1011 detector: input x brings one bit per clock cycle, and output z says "the last four bits were 1011". Press Synthesize to light up each part of the code together with the hardware it makes. Press Clock to run one cycle of the stream 1101011 and watch the matching lines light up and the waveform grow.

The module's parts on the left, coloured like the hardware they become: typedef enum and always_ff in orange make the state register of 2 flip-flops, always_comb case in blue makes the next-state logic, assign z in green makes the output logic; state is fed back from the register to the next-state logic, and x reaches the output only in a Mealy machine
Each part of the code is one block of hardware; the register is the only part with memory.

typedef enum: the states and their encoding

typedef enum logic [1:0] {S0, S1, S2, S3} state_t; gives the states names and makes a type for them. Then state_t state, next; declares the two signals of the machine: state, what the register holds now, and next, what it will hold after the next clock edge. The names are for people; the logic [1:0] part is for the hardware. It says each state is 2 bits, so the register will be 2 flip-flops. Here S0 = 00, S1 = 01, S2 = 10, S3 = 11.

For the 1011 detector the states mean "how much of 1011 the last bits match": S0 nothing, S1 "1", S2 "10", S3 "101". The Moore version adds S4 "1011". How these states and their arrows are found is the topic of Sequence Detector FSM.

The state register: always_ff with reset

always_ff @(posedge clk, posedge reset)
  if (reset) state <= S0;
  else       state <= next;

This is the only block that remembers anything. At each rising edge of clk it copies next into state. Because posedge reset is in the list, reset is asynchronous: state goes to S0 at once, without waiting for a clock edge. Every run on the page starts with cycle 0, where reset is held at 1. Keep this block small: no logic in it, just the register.

The next-state case

always_comb
  case (state)
    S0: next = x ? S1 : S0;
    S1: next = x ? S1 : S2;
    S2: next = x ? S3 : S0;
    S3: next = x ? S1 : S2;
    default: next = S0;
  endcase

One case item per state, each saying where to go for x = 0 and x = 1. It is the state table written as code. always_comb makes it combinational: it reads state and x and computes next with no memory. During a Clock press, the item of the current state lights up together with the next-state block, and the block shows, for example, "S2, x=1 → S3". The default line sends any unused code back to S0 and makes sure next always gets a value.

Output logic: Mealy or Moore

The Mealy output reads the state and the input: assign z = (state == S3) & x;. So z = 1 in the same cycle as the last 1 of 1011. The Moore output reads only the state: assign z = (state == S4);. It needs the extra state S4, and z = 1 one cycle later, for the whole cycle. On the stream 1101011 (plus a final 0):

cycle12345678
x11010110
Mealy stateS0S1S1S2S3S2S3S1
Mealy z00000010
Moore stateS0S1S1S2S3S2S3S4
Moore z00000001

In cycle 5 the state is S3 ("101") but x = 0, so there is no match: "1010" ends in "10" and the machine goes to S2. The match comes in cycle 7 (Demo: Mealy on 1101011, z in cycle 7 and Demo: Moore on 1101011, z one cycle later). The general Moore and Mealy timing is in Finite State Machines.

Binary vs one-hot in the synthesis report

Change only the enum and the hardware changes. With one-hot encoding each state gets its own flip-flop and exactly one of them is 1: typedef enum logic [3:0] {S0 = 4'b0001, S1 = 4'b0010, S2 = 4'b0100, S3 = 4'b1000} state_t;. The rest of the module stays the same, and so does the waveform. Only the register and the report change:

MachineStatesBinary flip-flopsOne-hot flip-flops
Mealy 1011424
Moore 1011535

Binary needs the fewest flip-flops, enough bits to count the states (2 bits for 4 states, 3 bits for 5). One-hot needs one per state, but its next-state logic is simpler: "am I in S2?" is a single bit, not a compare. FPGAs have many flip-flops, so one-hot is often the faster choice there (Demo: one-hot, 4 flip-flops instead of 2, Demo: Moore one-hot, 5 flip-flops instead of 3).

Left: binary encoding, a register of 2 flip-flops holding S2 = 10. Right: one-hot encoding, a register of 4 flip-flops holding S2 = 0100, with one bit per state
The same S2 in two encodings: 2 flip-flops holding 10, or 4 flip-flops holding 0100.

The latch from a missing default

Here is the Mealy output written as a case instead of an assign, with no default:

always_comb
  case (state)
    S3: z = x;
  endcase           // S0, S1, S2: nothing assigns z

In S0, S1 and S2 no line gives z a value, so the language says z keeps its old one. Gates cannot keep anything, so the synthesizer adds a latch on z and warns "latch inferred for z". The waveform shows both faults. Until the machine first reaches S3, z is X (unknown) in simulation. And after the match in cycle 7, z stays 1 in cycle 8, although the state is S1 (Demo: no default, z becomes a latch).

Waveform of z on the stream 1101011 for cycles 1 to 8. With default: 0 0 0 0 0 0 1 0. Without default: X X X X 0 0 1 1, z is unknown at first and stays 1 in cycle 8
Without a default, z is X at the start and keeps the 1 after the match: a latch, not logic.

There are two fixes. Add default: z = 1'b0; to the case, or write z = 1'b0; as the first line of the block, before the case. Either way every path assigns z. The next-state case uses the same habit: its default: next = S0; line covers every code the enum does not name. For the one-hot enum that is 12 of the 16 codes.

Running it for real

To simulate, compile the module with a testbench, for example iverilog -g2012 -o sim det1011.sv tb_det1011.sv and then vvp sim. Verilator works too. The testbench holds reset, drives x one bit per clock and checks z, as the page Verilog Testbench shows. To see the hardware, run yosys -p "read_verilog -sv det1011.sv; synth -top det1011; stat". The stat list counts the cells, flip-flops among them. A latch shows up as a warning and as a latch cell. Synthesizers that recognise an FSM may change its encoding (Yosys's fsm pass, Vivado's fsm_encoding setting), so read the report rather than assume.

See also From Verilog to Hardware for the gates, muxes and flip-flops each construct makes, and Sequential Logic for how a latch and a flip-flop are built.

See also ASMD Chart: a GCD Datapath and Its Controller for an FSM whose outputs drive a datapath, from ASMD chart to Verilog.

See also A Self-Checking Verilog Testbench for how a design like this detector is simulated with a clock, stimulus, $monitor and a check task that prints PASS or FAIL.

See also Asynchronous FIFO: Gray Pointers Across Two Clock Domains for registered full and empty flags and 2-flop synchronizers written as non-blocking register updates.

What the page leaves out

The hardware is drawn as three blocks, not as gates. The gate-level circuit of this detector is on Sequence Detector FSM. Left out: synchronous reset, writing the FSM in one or two always blocks, registered outputs, unique case and priority case, enum methods such as .name(), Gray and other encodings, X propagation in more detail, and timing. The stimulus is fixed, and the latch's start value X is what a simulator shows, not what real hardware does.

On the mind map

Open the Computer Architecture mind mapComputerArchitectureAbstraction and numbers: layers and bit patternsAbstraction and numbersCombinational logic: output depends only on inputsCombinational logicSequential logic: state held by a clockSequential logicMIPS software: how C becomes machine wordsMIPS softwareThe processor: datapath plus controlThe processorPipelines and parallelism: more instructions at oncePipelines and parallelismMemory and I/O: small fast near, big slow farMemory and I/OLatches and flip-flopsLatches and flip-flopslatch is level, flip-flop is edgeFlip-flops and counter designFlip-flops and counter designexcitation = characteristic backwardsLatch from transistorsLatch from transistorstransmission gates plus inverter loopCMOS layout, DRC, LVSCMOS layout, DRC, LVSDRC: can it be built? LVS: right circuit?Timing analysisTiming analysissetup limits clock, hold limits short pathsAsync FIFO (CDC)Async FIFO (CDC)Gray pointers cross; flags clear lateStuck-at fault testingStuck-at fault testingActivate, propagate, justify: D-algorithmStatic Timing AnalysisStatic Timing AnalysisSlack = required − arrival, every nodeLogical effort sizingLogical effort sizingd = gh + p; equal effort F^(1/N)Scan chainsScan chainsShift in, capture once, shift outFinite state machinesFinite state machinesMoore: output from state; Mealy: +inputsASMD chart and datapathASMD chart and datapathTransfers land at the edge leaving the state1011 Sequence Detector1011 Sequence DetectorA wrong bit keeps the longest prefixFSM in SystemVerilogenum, always_ff, always_comb; default!Shift registers and countersShift registers and countersChained flip-flops shift or count each clockOpen the Computer Architecture mind mapComputer Architecturestate held by a clockSequential logicLatches and flip-flopsLatches and flip-flopslatch is level, flip-flop is edgeFlip-flops and counter designFlip-flops and counter designexcitation = characteristic backwardsLatch from transistorsLatch from transistorstransmission gates plus inverter loopCMOS layout, DRC, LVSCMOS layout, DRC, LVSDRC: can it be built? LVS: right circuit?Timing analysisTiming analysissetup limits clock, hold limits short pathsAsync FIFO (CDC)Async FIFO (CDC)Gray pointers cross; flags clear lateStuck-at fault testingStuck-at fault testingActivate, propagate, justify: D-algorithmStatic Timing AnalysisStatic Timing AnalysisSlack = required − arrival, every nodeLogical effort sizingLogical effort sizingd = gh + p; equal effort F^(1/N)Scan chainsScan chainsShift in, capture once, shift outFinite state machinesFinite state machinesMoore: output from state; Mealy: +inputsASMD chart and datapathASMD chart and datapathTransfers land at the edge leaving the state1011 Sequence Detector1011 Sequence DetectorA wrong bit keeps the longest prefixFSM in SystemVerilogenum, always_ff, always_comb; default!Shift registers and countersShift registers and countersChained flip-flops shift or count each clock
This page on the Computer Architecture mind map · 76 pages in 7 branches · open it to see the whole map and test yourself in recall mode.