---
title: Sequential logic in Verilog
heading: Registers, resets, enables and counters
eyebrow: S3 · Lesson 3 · Sequential logic in Verilog
xp: 50
---

::: hook
Everything that remembers in a synchronous design is a flip-flop, and nearly every flip-flop has the same three questions attached: what resets it, what enables it, and what clock drives it. Get them right and a design simulates and synthesizes the same way. Get them wrong (a gated clock, a reset released at the wrong moment, an enable written as a clock) and a design can pass simulation and still fail in silicon. This lesson writes registers, counters and dividers the way production RTL does, and counts what they cost.
:::

::: play
- A 2-bit synchronous counter with an enable EN and a synchronous reset R, written as two flip-flops: `Q0 <= Q0 ^ EN` and `Q1 <= Q1 ^ (EN & Q0)`.
- While EN is high it counts 0, 1, 2, 3, 0 on successive rising edges; drop EN and it holds. Every flip-flop sees the same clock; the enable is logic in front of the D input, never a gate on the clock.
- Raise R: the next edge clears the counter, since a synchronous reset acts only at clock edges.
:::
:::

```sim logic
module counter2(input CLK, input EN, input R, output Q0, output Q1);
always @(posedge CLK) if (R) Q0 <= 0; else Q0 <= Q0 ^ EN;
always @(posedge CLK) if (R) Q1 <= 0; else Q1 <= Q1 ^ (EN & Q0);
endmodule
clock CLK 8
stim EN 1@2 0@42 1@58
stim R 0@0 1@74 0@84
wave: CLK, EN, R, Q0, Q1
time: 100
```

::: predict
## A designer stops a register from loading by ANDing its clock with an enable signal. What's the risk?

- [ ] None: it saves power
- [x] Glitches on the enable become extra clock edges, and the gated clock arrives late (skew)
- [ ] The register stops holding its value
- [ ] It works only with asynchronous resets

::: reveal
Logic in the clock path is dangerous. If the enable changes while the clock is high, the AND gate's output can pulse, clocking the register when nobody meant to. The gate also delays the clock relative to other registers, breaking the timing assumptions between them. The safe form is a clock enable: a multiplexer in front of D that feeds back Q when the enable is off. (Real clock gating for power, lesson 20, uses special latch-based cells that can't glitch.)
:::
:::

::: nameit
## Registers

```verilog
always @(posedge clk)
  if (rst)     q <= 0;
  else if (en) q <= d;
```

That's a register with a synchronous reset and an enable: the reset and enable become logic in front of D. Every bit of q is one flip-flop.

## Resets

- **Synchronous** (`if (rst)` inside a `posedge clk` block): acts on clock edges, behaves like any other logic, and is easy to time.
- **Asynchronous** (`always @(posedge clk or posedge rst)`): acts immediately, even without a clock, which is useful at power-up. Its *release* must still be synchronized to the clock, or flip-flops may leave reset on different cycles; a **reset synchronizer** (two flip-flops) does that.

## Enables, not gated clocks

A disabled register reloads its own output through a multiplexer; the clock still runs. One clock net, distributed with balanced delay, drives every flip-flop.

## Counters and dividers

- A synchronous n-bit counter: each bit toggles when all lower bits are 1. Its carry chain sets its speed.
- A divide-by-N counter makes one output pulse every N clocks: $f_\text{out} = f_\text{clk}/N$.
- An LFSR (C7) cycles through $2^n - 1$ states using only XOR feedback: a cheap pseudo-random sequence or a fast counter when the order doesn't matter.

## Flip-flop timing

Each flip-flop needs its D input stable $t_\text{setup}$ before the edge and $t_\text{hold}$ after it, and its output changes $t_{clk\text{-}q}$ after the edge. Violating setup or hold risks metastability (lesson 24).
:::

::: example
## A 100 MHz system needs a 1 kHz tick and a 12-bit free-running counter. How many flip-flops do the divider and the counter need, and how often does the counter wrap?

::: solution
1. **The divider.** Dividing by $10^5$ needs a counter that reaches 99,999:
   $$\lceil\log_2 10^5\rceil = 17\ \text{bits}$$
2. **The 12-bit counter's wrap.** It wraps every $2^{12} = 4096$ clocks, which at 100 MHz is 40.96 µs.
3. **Total.**
   $$17 + 12 = 29\ \text{flip-flops}$$
4. **Using the tick.** The tick output is a one-clock enable pulse used by slower logic, never a clock in its own right.

**Answer:** 17 flip-flops for the divider and 12 for the counter, 29 in all; the counter wraps every 40.96 µs.
:::
:::

::: example
## A 16-bit LFSR and a 16-bit binary counter both run from the same clock. How long are their sequences, and why might a designer pick the LFSR?

::: solution
1. **The counter's sequence.** It cycles through all $2^{16} = 65{,}536$ states.
2. **The LFSR's sequence.** It skips the all-zeros state:
   $$2^{16} - 1 = 65{,}535\ \text{states}$$
3. **Why pick the LFSR.** Its next state is a few XORs on a shift register, with no carry chain, so it runs at nearly the flip-flop's limit regardless of width. That suits fast timeouts and test-pattern generation, where the counting order doesn't matter.

**Answer:** 65,536 states for the counter and 65,535 for the LFSR; the LFSR has no carry chain, so it stays fast at any width.
:::
:::

::: example
## A UART on a 50 MHz clock needs a tick at 115 200 baud. What division ratio does it use, how big is the frequency error, and how many flip-flops does the divider take?

::: solution
1. **Division ratio.**
   $$\frac{50\ \text{MHz}}{115\,200} = 434.03$$
   so divide by 434.
2. **Frequency error.** The tick runs at 115 207 Hz, 0.0064% fast. Receivers tolerate a few percent, so the error is harmless.
3. **Divider size.** Counting 0 to 433 takes
   $$\lceil\log_2 434\rceil = 9\ \text{flip-flops}$$

**Answer:** divide by 434, which runs 0.0064% fast (115 207 Hz), with a 9-flip-flop divider.
:::
:::

::: check
given: f = 50 | 100 | 200; N = 10 | 1000 | 50000
answer: f*1e6/N
unit: Hz
tolerance: 0.1%

## A divide-by-{N} counter runs from a {f} MHz clock. What's its output frequency?

::: right
Right. $f_\text{clk}/N$ = {answer} Hz.
:::

::: misses
- [f*1e6/(2*N)] One output pulse per N clocks: there's no extra factor of 2.
- [any] Not yet. One output event per N input clocks.
:::
:::

::: check
given: f = 10 | 50 | 100; t = 3 | 777 | 4700
answer: ceil(log(f*1e6/(t*1e3))/log(2))
tolerance: 0

## How many bits does a counter need to divide a {f} MHz clock down to a {t} kHz tick?

::: right
Right. It must count to $N = f_\text{clk}/f_\text{tick}$: $\lceil\log_2N\rceil$ = {answer} bits.
:::

::: misses
- [any] Not yet. Find N, then the bits to hold it.
:::
:::

::: check
given: n = 7 | 12 | 23
answer: 2^n - 1
tolerance: 0

## How many states does a maximal-length {n}-bit LFSR cycle through?

::: right
Right. $2^n - 1$ = {answer}: every state except all zeros.
:::

::: misses
- [2^n] All zeros is a stuck state for XOR feedback.
- [any] Not yet. Maximal length skips one state.
:::
:::

::: check
given: n = 4 | 6 | 8; f = 50 | 125
answer: 2^n/(f*1e6)*1e6
unit: µs
tolerance: 0.1%

## A free-running {n}-bit counter runs at {f} MHz. How often does it wrap around?

::: right
Right. $2^n/f_\text{clk}$ = {answer} µs.
:::

::: misses
- [(2^n - 1)/(f*1e6)*1e6] It passes through all $2^n$ states, including zero.
- [any] Not yet. One full pass through every state.
:::
:::

::: check
given: c = 40 | 70; h = 10 | 20 | 30; s = 20 | 40
answer: c + s
unit: ps
tolerance: 0.1%

## A flip-flop has clock-to-Q {c} ps, setup {s} ps and hold {h} ps. How much of every clock period does it cost a path that starts and ends at such flip-flops?

::: right
Right. $t_{clk\text{-}q} + t_\text{setup}$ = {answer} ps. Hold time doesn't cost period; it constrains the shortest paths (lesson 16).
:::

::: misses
- [c + s + h] Hold time doesn't add to the period: it's about the earliest arrival, not the latest.
- [any] Not yet. Launch overhead plus capture overhead.
:::
:::

::: check
given: N = 4 | 16 | 64
answer: N
tolerance: 0

## A register file of {N} registers, each with its own write enable, needs how many 2-to-1 multiplexers per bit to implement the enables?

::: right
Right. One per register bit: {answer} per bit position.
:::

::: misses
- [any] Not yet. Each enabled register selects between D and its own Q.
:::
:::

::: check
kind: parts
given: f = 50 | 100; o = 1 | 10; n = 16 | 24 | 32

## A {f} MHz design needs a {o} kHz tick, and has an {n}-bit free-running counter.

::: part
answer: f*1000/o
tolerance: 0

### What division ratio makes the tick?

::: misses
- [any] $f_\text{clk}/f_\text{tick}$.
:::
:::

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

### How many flip-flops does the divider's counter need?

::: misses
- [any] $\lceil\log_2N\rceil$.
:::
:::

::: part
answer: 2^n/(f*1e6)*1000
unit: ms
tolerance: 0.5%

### How often does the free-running counter wrap?

::: misses
- [any] $2^n/f_\text{clk}$.
:::
:::
:::

::: check
kind: derivation
vars: f = 1e6..1e9, i = 0..30, n = 1..32

## An n-bit synchronous binary counter runs at clock frequency f.

::: step
answer: f/2^(i + 1)

### At what frequency does bit i toggle (bit 0 the least significant)?
:::

::: step
answer: 2^n/f

### How long is a full cycle of the counter?
:::

::: step
answer: (2^n - 1)/f

### How long is the full sequence of an n-bit maximal-length LFSR on the same clock?
:::

::: right
Right. Each bit runs at half the rate of the one below it; an LFSR skips only the all-zero state.
:::
:::

::: explain
## Why should a register be disabled with a clock enable rather than by gating its clock?

::: model
Synchronous design assumes that every flip-flop sees the clock edge at very nearly the same instant and that nothing but the clock causes edges. Putting logic in the clock path breaks both. The gate delays the clock, so the gated register samples later than its neighbors, which can let data race through or arrive too late. And any glitch on the enable while the clock is high passes through the gate as a spurious clock edge. A clock enable keeps the clock clean and instead adds a multiplexer in the data path that reloads the register's own value when it shouldn't change. Timing tools analyze that like any other logic.
:::
:::

::: practice

::: check
given: f = 25 | 150; N = 25 | 2500
answer: f*1e6/N
unit: Hz
tolerance: 0.1%

## Divide-by-{N} from {f} MHz?

::: misses
- [any] $f/N$.
:::
:::

::: check
given: n = 4 | 5 | 8 | 9 | 12 | 16 | 17
answer: 2^n - 1
tolerance: 0

## LFSR states, {n} bits?

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

::: check
given: n = 10 | 20; f = 40 | 200
answer: 2^n/(f*1e6)*1e6
unit: µs
tolerance: 0.1%

## Wrap time: {n}-bit counter at {f} MHz?

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