Volume 06 Beginner 5 sub-modules ~25 min read

Sequence Detectors Masterclass

Hand someone a whiteboard and ask for a 1011 detector: it is the most common state machine question there is. This volume teaches one method that works for any pattern, every time. Then it stretches that method to several patterns at once, to divisibility checkers, and to a testbench that proves your detector right with thousands of random bits.

You will learn
  • The difference between overlapping and non-overlapping detection
  • A step-by-step method that builds a detector for any pattern
  • Mealy and Moore detectors for 101 and 1011
  • How to detect several patterns at once
  • How a three-state machine checks divisibility by 3
  • How to test a detector against a reference model
You need

6.1 Overlapping vs non-overlapping

A sequence detector watches a stream of bits, one per clock cycle, and says "found it" whenever the latest bits match a pattern. Overlapping detection lets the end of one match be the start of the next.

The job

Data often arrives one bit at a time, one bit per clock cycle, on a single wire. Such a series of bits is a bit stream. Serial links, radio receivers and disk drives all produce them. Very often a circuit must spot a special pattern in the stream - a start marker, a password, a sync word. The circuit that does this is a sequence detector.

Throughout this volume, the input is x (one bit per cycle) and the output is z (1 when the pattern has just been seen).

Two ways to count a match

Take the pattern 101 and this stream, one bit per cycle:

Cycle 0 1 2 3 4 5 6 7
x 1 0 1 0 1 1 0 1

The bits in cycles 0, 1 and 2 are 1 0 1 - a match. Now look at cycles 2, 3 and 4: also 1 0 1. The 1 in cycle 2 is both the end of the first match and the start of the second. Should it count twice?

Overlapping and non-overlapping detection of 101 on the same bit stream 0 1 2 3 4 5 6 7 clk x z_overlap z_non_overlap
Figure 6.1 - The same stream, two rules. The overlapping detector reuses the last 1 of each match, so it finds 101 three times. The non-overlapping detector starts afresh after each match, so it misses the one ending in cycle 4.

These are Mealy outputs: z rises in the same cycle as the last bit of the match, as in Volume 02.

Remember

Overlapping or not is part of the specification, not a design choice. If a question does not say, ask. Most interview questions want overlapping detection.

Think of it like this

Think of reading the word "banana" and counting the pattern "ana". Reading with overlap, you find it twice: b-ANA-na and ban-ANA. Reading without overlap, once you have used a letter you cannot use it again, so you find it only once.

Common mistake

Do not decide the rule by yourself and then design. The two rules give different machines, and a perfect overlapping detector is a wrong answer to a non-overlapping question.

Quick check

How many times does the pattern 11 appear in the stream 1 1 1 1 with overlapping detection?

Show the answer

Answer: B. With overlapping, every pair of neighbouring 1s counts: bits 0-1, bits 1-2 and bits 2-3. That is 3 matches. Without overlapping, it would be 2: bits 0-1, then bits 2-3.

6.2 Detecting 101 and 1011 (Mealy and Moore)

Name each state after the longest start of the pattern that the stream ends with. Then every arrow can be worked out by one simple rule.

The method

Detectors are easy to get wrong by guessing. This method never guesses.

A prefix of a pattern is its first few bits. The prefixes of 101 are 1, 10 and 101. Now:

  1. Make one state per prefix. Include the empty prefix - "nothing matched yet". For 101: S0 (nothing), S1 (seen "1"), S10 (seen "10").
  2. For each state and each input bit, add the bit to the end of that state's prefix.
  3. If the result is the whole pattern, the output is 1.
  4. Find the next state: the longest prefix of the pattern that the result ends with. For overlapping detection, this rule applies even after a full match.

The last step is the heart of it. It asks: "of what I have seen, how much could still be the start of a new match?"

The 101 detector, Mealy, overlapping

Work through every state and input:

State Input Bits seen, ending Whole pattern? Longest prefix it ends with Next
S0 0 0 no (none) S0
S0 1 1 no 1 S1
S1 0 10 no 10 S10
S1 1 11 no 1 S1
S10 0 100 no (none) S0
S10 1 101 yes: z = 1 1 S1

Look at the row S1 with input 1. The bits are "11". That is not a prefix, but it ends with "1", which is. So the machine stays in S1: the new 1 could start a match. And the last row: after 101, the final 1 could start the next match - so the machine goes to S1, not S0. That single arrow is what makes the detector overlapping.

Mealy state diagram of an overlapping 101 sequence detector with states S0, S1 and S10 S0 S1 S10 1/0 0/0 1/1 0/0 0/0 1/0 reset
Figure 6.2 - The overlapping 101 detector as a Mealy machine. Arrows read input / output. The arrow from S10 back to S1 carries the match, and keeps the final 1 as a fresh start.

For non-overlapping detection, only one arrow changes: after a match, go back to S0 instead of S1. So the arrow S10 --1/1--> goes to S0.

The 101 detector, Moore

A Moore machine needs a state for "the whole pattern has just been seen", in which z = 1. Add S101. Its arrows follow the same rule. From 101, a 0 gives "1010", which ends with the prefix "10", so the machine goes to S10. A 1 gives "1011", which ends with the prefix "1", so it goes to S1.

Moore state diagram of an overlapping 101 sequence detector with four states S0 z=0 S1 z=0 S10 z=0 S101 z=1 1 0 1 0 1 0 0 1 reset
Figure 6.3 - The Moore 101 detector. S101 is the only state with z = 1. The two diagonal arrows cross, but their labels sit well apart.

Figure 6.4 runs both 101 detectors on the stream from sub-module 6.1, plus one more bit. As always, the Moore output comes one cycle after the Mealy output.

The Mealy and Moore 101 detectors on the same stream 0 1 2 3 4 5 6 7 8 clk x mealy_state S0 S1 S10 S1 S10 S1 S10 S1 mealy_z moore_state S0 S1 S10 S101 S10 S101 S1 S10 S101 moore_z
Figure 6.4 - Mealy and Moore on the same stream. Each Moore pulse comes one cycle after the matching Mealy pulse, while the machine sits in S101.

The 1011 detector

The same method, with one more prefix. The states are S0, S1, S10 and S101, and a Moore machine adds S1011:

State x = 0 x = 1
S0 S0 S1
S1 ("1") S10 S1 - "11" ends with "1"
S10 ("10") S0 - "100" ends with no prefix S101
S101 ("101") S10 - "1010" ends with "10" Mealy: z = 1, go to S1. Moore: go to S1011
S1011 (Moore only, z = 1) S10 - "10110" ends with "10" S1 - "10111" ends with "1"

Here is the Moore 1011 detector in Verilog. Each row of the table becomes one line of the case statement:


module seq1011_moore (
  input  wire clk, rst, x,
  output wire z
);
  localparam [2:0] S0 = 3'd0, S1 = 3'd1, S10 = 3'd2, S101 = 3'd3, S1011 = 3'd4;
  reg [2:0] state, next_state;

  always @(posedge clk)
    if (rst) state <= S0;
    else     state <= next_state;

  always @(*) begin
    case (state)
      S0:      next_state = x ? S1    : S0;
      S1:      next_state = x ? S1    : S10;
      S10:     next_state = x ? S101  : S0;
      S101:    next_state = x ? S1011 : S10;
      S1011:   next_state = x ? S1    : S10;
      default: next_state = S0;          // unused codes 5, 6, 7: start again
    endcase
  end

  assign z = (state == S1011);           // Moore output
endmodule
Common mistake

The classic bug is sending S1 back to S0 when another 1 arrives. It seems natural - "11 is not part of 1011" - but the second 1 could be the start of a match. With that bug, the stream 1 1 0 1 1 never raises z, even though it ends in 1011. Always apply the longest-prefix rule, never a guess.

Quick check

In the 1011 detector, the machine is in S101 and x = 0. Where does it go?

Show the answer

Answer: A. The bits seen are now "1010". Its endings are "010", "10" and "0". The longest one that is also a prefix of 1011 is "10". So the machine goes to S10: the last two bits could still start a match.

Try it in FSM StudioRun the 101 detector in FSM Studio. Type 1 0 1 0 1 into the sequence box and watch z go to 1 twice, then use Checks to turn it into the Moore version.
Open FSM Studio

6.3 Longer and multiple patterns

The same method handles long patterns and several patterns at once. For long fixed patterns, a shift register and a comparator can do the job with no state diagram at all.

A longer pattern: 1101

Longer patterns need no new ideas - only more rows. For 1101, the prefixes give the states S0, S1, S11 and S110:

State x = 0 x = 1
S0 S0 S1
S1 ("1") S0 - "10" ends with no prefix of 1101 S11
S11 ("11") S110 S11 - "111" ends with "11"
S110 ("110") S0 - "1100" ends with no prefix match, z = 1; "1101" ends with "1", so go to S1

Notice the row S1 with x = 0. For the pattern 101, "10" was a prefix. For 1101 it is not - the second bit of 1101 is a 1. The method takes care of this for you: the rows depend on the pattern, so you must work each one out, never copy them from another detector.

Remember

A Mealy detector for an n-bit pattern needs n states. A Moore detector needs n + 1.

Several patterns at once

Suppose the machine must say z = 1 when it sees either 101 or 110. Make one state for every prefix of either pattern: S0, S1, S10 (from 101) and S11 (from 110). Then use the same rule - the longest ending that is a prefix of any pattern:

State x = 0 x = 1
S0 S0 S1
S1 S10 S11
S10 S0 "101" - match, z = 1; go to S1
S11 "110" - match, z = 1; "110" ends with "10", so go to S10 S11

Four states detect both patterns, overlapping each other freely. If the two patterns need separate outputs - z1 for 101 and z2 for 110 - the states stay the same; only the output logic splits.

The engineer's shortcut: a shift register

For a fixed pattern of n bits, there is a second way. Keep the last n bits in a shift register - a row of flip-flops that moves each bit along one place per cycle - and compare them with the pattern:


reg [3:0] last4;                                   // the last four bits
always @(posedge clk)
  if (rst) last4 <= 4'b0000;
  else     last4 <= {last4[2:0], x};               // shift the new bit in
assign z = (last4 == 4'b1011);                     // Moore timing

It is short, obviously right, and handles overlapping by itself. The cost is flip-flops: n of them, against about log2(n + 1) for the state machine. For a 32-bit sync word, that is 32 flip-flops against 6.

Common mistake

After reset, a shift register holds zeros that were never received. If the pattern starts with zeros - say 0001 - the detector can fire after only one real bit. Either reset to a value that cannot match, or ignore z until n real bits have arrived. The state-machine detector does not have this problem.

Quick check

A Mealy detector is needed for the 6-bit pattern 110110. How many states does it need?

Show the answer

Answer: C. One state per prefix, counting the empty prefix but not the whole pattern: nothing, 1, 11, 110, 1101 and 11011. That is 6 states. A Moore detector would add a seventh for the full match.

6.4 Divisibility checkers on a bit stream

A state machine can tell whether the binary number arriving on a bit stream is divisible by k, using only k states - one for each possible remainder.

The question

The bits arrive most significant first, and together they form a binary number. After every bit, the machine must say whether the number so far is divisible by 3. The number can grow without limit, so the machine cannot store it. Can a small machine still answer?

The trick: keep only the remainder

Reading a new bit b multiplies the number so far by 2 and adds b. Write the number as N. Then:

The remainder is all the machine needs to remember - and a remainder after dividing by 3 is only ever 0, 1 or 2. So three states are enough: R0, R1 and R2.

State (remainder r) b = 0: (2r) mod 3 b = 1: (2r + 1) mod 3 z
R0 0 → R0 1 → R1 1
R1 2 → R2 0 → R0 0
R2 1 → R1 2 → R2 0
State diagram of a divisible-by-3 checker with states R0, R1 and R2 R0 z=1 R1 z=0 R2 z=0 1 1 0 0 0 1 reset
Figure 6.5 - The divisible-by-3 checker. Each state is the remainder of the number so far. z = 1 in R0, when the remainder is 0.

Try it on the stream 1, 1, 0 - the number 110 in binary, which is 6:

  1. Start in R0. The number so far is 0, and 0 is divisible by 3.
  2. Read 1: the number is 1, remainder 1. Go to R1.
  3. Read 1: the number is 11 in binary, 3, remainder 0. Go to R0 - divisible.
  4. Read 0: the number is 110 in binary, 6, remainder 0. Stay in R0 - divisible, as expected.

The same idea works for any k: k states, and the arrow from state r on bit b goes to state (2r + b) mod k. It is one of the most popular state machine questions in written exams.

Going deeper: when the bits arrive least significant first

If the lowest bit arrives first, a new bit b adds b × 2i, where i is its position. The machine must now remember two things: the remainder, and 2i mod k. For k = 3, the powers of 2 go 1, 2, 1, 2 and so on, so the machine needs 3 × 2 = 6 states. The idea is the same - remember only what the answer depends on - but the machine is bigger.

Common mistake

It is easy to forget that the reset state is also an "accepting" state. Right after reset the number is 0, which is divisible by 3, so z = 1 before any bit arrives. That is mathematically correct - but if your specification says "only report after the first bit", you need one extra state for "nothing received yet".

Quick check

The divisible-by-3 checker is in R2, and the next bit is 0. Where does it go?

Show the answer

Answer: D. The new remainder is (2 × 2 + 0) mod 3 = 4 mod 3 = 1, so the machine goes to R1. A 0 does not leave the number unchanged - it doubles it.

6.5 Testing a detector thoroughly

Test a detector by feeding it thousands of bits and comparing its output, every cycle, with a simple reference model that is obviously correct.

Why hand-picked tests are not enough

A detector has many paths. The bugs hide in the rare ones: a near-miss such as 1010, a pattern straight after a match, a long run of 1s. You could write a test for each one by hand - a directed test - but you will always miss some.

A better plan uses two ideas together:

Every cycle, the testbench compares the design's output with the model's. Any difference is a bug.


module seq1011_tb;
  reg  clk = 0, rst = 1, x = 0;
  wire z;
  reg  [3:0] hist;                          // reference model: the last four bits
  integer i, errors = 0, matches = 0;

  seq1011_moore dut (.clk(clk), .rst(rst), .x(x), .z(z));

  always #5 clk = ~clk;

  always @(posedge clk)                     // the obviously-correct model
    if (rst) hist <= 4'b0000;
    else     hist <= {hist[2:0], x};

  initial begin
    repeat (2) @(negedge clk); rst = 0;
    for (i = 0; i < 5000; i = i + 1) begin
      @(negedge clk);                       // mid-cycle: check, then drive
      if (z !== (hist == 4'b1011)) begin
        errors = errors + 1;
        $display("MISMATCH in cycle %0d: z = %b", i, z);
      end
      if (z) matches = matches + 1;
      x = $random;                          // a random bit for the next cycle
    end
    $display("%0d matches seen", matches);
    if (errors == 0) $display("PASS"); else $display("FAIL: %0d mismatches", errors);
    $finish;
  end
endmodule

Four details make this testbench trustworthy:

  1. Same timing. The model samples x on the same rising edge as the design, so both have seen exactly the same bits when they are compared.
  2. Compare with !==. The !== comparison also catches an unknown x value on z, which a plain != would not.
  3. Count the matches. A test that never saw a match proves nothing. Random bits contain 1011 about once every 16 cycles, so 5000 cycles give roughly 300 matches.
  4. Report one verdict. PASS or FAIL, so nobody has to read a log.
Try it yourselfRun seq1011_moore.v with seq1011_tb.v. Then plant the classic bug from sub-module 6.2 - make S1 go to S0 when x = 1 - and watch the testbench report mismatches within a few dozen cycles.
Open EDA Playground

Directed tests still matter

Random bits find most bugs, but a few hand-written streams make a good first test, and they are easy to read when something fails:

Stream Why it is interesting Moore z should rise after
1011 the pattern alone the 4th bit
1011011 two overlapping matches the 4th and 7th bits
11011 a false start - the S1 bug the 5th bit
1010 1010 near misses only never
Common mistake

Do not let the reference model share code with the design. If both are built from the same mistaken idea, they agree with each other and the test passes - wrongly. A reference model is useful exactly because it is built in a completely different, simpler way.

Quick check

Why does the testbench count how many matches it saw?

Show the answer

Answer: B. If the random bits never contained 1011, the design and the model would both output 0 all the time. The test would then pass without ever checking a match. Counting matches proves that the important path was exercised.

What you learned

Key words from this volume

Every word below has a plain-English entry in the glossary.

Practice

Practice 1

Detect 110, Moore, overlapping

Design a Moore detector for 110 with overlapping. List its states and write its state table.

Show the solution

The prefixes give S0, S1 and S11; Moore adds S110 with z = 1.

State x = 0 x = 1 z
S0 S0 S1 0
S1 S0 - "10" is not a prefix of 110 S11 0
S11 S110 S11 - "111" ends with "11" 0
S110 S0 - "1100" ends with no prefix S1 - "1101" ends with "1" 1
Practice 2

Divisible by 5

Write the state table of a machine that says whether the number on a bit stream (most significant bit first) is divisible by 5.

Show the solution

Five states, R0 to R4, one per remainder. From state r, bit b leads to (2r + b) mod 5:

State b = 0 b = 1 z
R0 R0 R1 1
R1 R2 R3 0
R2 R4 R0 0
R3 R1 R2 0
R4 R3 R4 0

Check it with 1010 in binary, which is 10: R0 → R1 → R2 → R0 → R0. It ends in R0, and 10 is divisible by 5.

Practice 3

Spot the non-overlapping arrow

In the Mealy 1011 detector, which single arrow must change to make it non-overlapping, and where should it go instead?

Show the solution

The arrow that completes the match: from S101 on x = 1. For overlapping detection it goes to S1, because the final 1 can start a new match. For non-overlapping detection it must go to S0, so that no bit of the finished match is used again.

Interview corner

Interview question 1

Design a 1011 detector

"Design an overlapping 1011 sequence detector. How many states does it need?"

Show the solution

Talk through the method as you draw: "I name each state after the longest prefix matched so far - S0, S1, S10, S101. On each input I append the bit and take the longest suffix that is still a prefix. So S1 stays in S1 on another 1, S10 goes back to S0 on a 0, and S101 goes to S10 on a 0. On a 1 from S101 the pattern completes: as a Mealy machine I output 1 and go to S1, because the last 1 can start a new match. That is four states as Mealy, five as Moore." Then state which you would build, and why - usually Moore, or Mealy with a registered output.

Interview question 2

A counter for a sequence?

"Could you detect 1011 with a counter instead of a state machine?"

Show the solution

"Not with a simple counter of matched bits, because a mismatch does not always mean starting from zero - after 1010 you still hold '10'. A counter that resets to 0 on a mismatch would miss overlapping matches such as 1011 inside 11011. What does work without a hand-drawn state machine is a 4-bit shift register compared with 1011: simple and obviously correct, at the cost of four flip-flops instead of three."

Next, Volume 07 shows that counters, timers and debouncers - circuits you may not think of as state machines - are state machines too.