12Implementation
Design a three-state detector from its contract
Problem
Contract. two_ones samples the 1-bit input din at every rising edge
of clock. Its output seen is 1 while the last two values sampled since
reset were both 1, and 0 otherwise. A run of three or more 1s keeps seen
high; a single 0 drops it. seen is a Moore output: it depends on the
state only, so it changes only at rising edges and never follows din
inside a cycle. Reset is synchronous and active-high: after a reset edge no 1
has been seen yet and seen is 0.
Starting point. The starter has the ports and a placeholder that drives
seen to 0. Everything else is yours: state names, state register,
next-state logic and output logic. The public testbench below the marker is
read-only.
Step 1: write the state table before any code
The machine needs to remember how many 1s in a row it has seen, counting no
further than two. Name one state per count, for example ZERO, ONE and
TWO, and fill in one row per state and input value:
| Current state | din | Next state | seen in the current state |
|---|---|---|---|
ZERO | 0 | ? | ? |
ZERO | 1 | ? | ? |
ONE | 0 | ? | ? |
ONE | 1 | ? | ? |
TWO | 0 | ? | ? |
TWO | 1 | ? | ? |
Then use it to predict the seen column of the public run: pattern
0110_1110_1011, each line printed just after the edge that sampled that
line's din.
Step 2: translate the table
Follow the three parts of the chapter: a state register written only in one
always @(posedge clock) block with the reset branch first, a next-state
always @* case with a default, and output logic that reads the state
alone. Three states need two state bits; the fourth code is covered by the
default.
Step 3: run, compare, and look at the waveform
Compare the printed seen column with your prediction line by line. In the
waveform, check that seen changes only at rising edges, even where din
changes in the middle of a cycle.
Completion check
- For every input pattern,
seenafter each rising edge is 1 exactly when the last two sampled values were 1. seendoes not change between rising edges, whateverdindoes.- Reset in the middle of a run of 1s starts the count again.
- Any correct encoding passes: binary, one-hot, or a saturating counter.
Grading reports the first failing cycle after reset, whether it was checked
before or after the edge, the expected and the actual
seen.
Progressive hints
Hint 1
Which input value sends every state back to the same place? Fill those three rows first.
Hint 2
From TWO, another 1 still means "the last two were 1". Where does the
machine go?
Hint 3
If seen uses din as the second 1 before it is sampled, it becomes a
Mealy output and rises before the required edge. Compare the "before edge" and "after edge"
checks in the grading message.
Transfer experiment
Change the contract to "three 1s in a row". How many states do you need, how many state bits, and which rows of the table change? Predict the new column for the public pattern before you run.