---
title: Writing Verilog
heading: Describing hardware so a tool can build it
eyebrow: C7 · Lesson 49 · Writing Verilog
xp: 40
---

::: hook
Lesson 48 read Verilog; this lesson writes it. The language looks like a programming language, but it describes hardware: every `assign` is a permanent network of gates, every `always @(posedge clk)` block is a bank of flip-flops, and the synthesis tool's job is to turn the description into exactly those circuits. Writing it well means writing descriptions whose hardware you can picture, and avoiding the few patterns (missing branches, mixed assignment styles) that produce circuits you didn't intend.
:::

::: play
- A 2-bit counter with an enable EN and a synchronous reset R, written the way a synthesis tool expects: each bit is a flip-flop, the reset takes priority, and a bit toggles when every lower bit is 1 and the counter is enabled.
- The waveform shows it counting 0, 1, 2, 3, 0, ..., holding while EN is low, and clearing at the first clock edge after R goes high.
:::
:::

```sim logic
clock CLK 8
input EN, R
output Q1, Q0
stim EN 1@0 0@38 1@54
stim R 0@0 1@66 0@74
always @(posedge CLK) if (R) Q0 <= 0; else Q0 <= Q0 ^ EN;
always @(posedge CLK) if (R) Q1 <= 0; else Q1 <= Q1 ^ (Q0 & EN);
wave: CLK, EN, R, Q1, Q0
time: 96
```

::: predict
## In a clocked block, `a <= b; b <= a;` runs on each edge. What happens to a and b?

- [ ] Both become b's old value
- [x] They swap
- [ ] Both become a's old value
- [ ] Nothing changes

::: reveal
They swap. Nonblocking assignments (`<=`) read every right-hand side first, then update all the flip-flops together, just as two flip-flops cross-wired to each other would. With blocking assignments (`=`), a would take b's value and then b would read the new a, so both would end up as b's old value.
:::
:::

::: nameit
## Modules and structure

```verilog
module counter #(parameter W = 8) (input clk, input rst, input en, output reg [W-1:0] q);
  always @(posedge clk)
    if (rst)     q <= 0;
    else if (en) q <= q + 1;
endmodule
```

A module has ports; `#(parameter W = 8)` makes its width adjustable; **instances** of modules inside others build hierarchy (`counter #(.W(4)) c1 (.clk(clk), .rst(r), .en(1'b1), .q(count));`). A vector `[W-1:0]` is W wires, and `q + 1` on it synthesizes a W-bit incrementer.

## Combinational logic

Use `assign` for simple expressions, or `always @(*)` with `case` for anything with branches:

```verilog
always @(*)
  case (sel)
    2'b00: y = a;
    2'b01: y = b;
    2'b10: y = c;
    default: y = 0;
  endcase
```

**Every output must be assigned on every path.** If some branch leaves y unassigned, y must hold its old value, and the tool builds a **latch**: almost always a bug. A `default` (or assigning y before the `case`) prevents it.

## Sequential logic and assignment styles

- In `always @(posedge clk)` blocks use **nonblocking** `<=`: all flip-flops update together.
- In `always @(*)` blocks use **blocking** `=`: statements behave in order, like gates feeding gates.
- Never assign one signal from two blocks.

## State machines

Three parts: a state register (`always @(posedge clk) state <= next;`), next-state logic (`always @(*) case (state) ...`), and output logic. Name states with `localparam` so the code reads like the diagram.

## Testbenches

A testbench is a module with no ports that instantiates the design, drives its inputs with `initial` blocks and delays (`#10 en = 1;`), and checks outputs with `$display` or assertions. It runs in a simulator and is never synthesized.
:::

::: example
## What hardware does this describe? `always @(posedge clk) if (load) r <= d; else r <= {r[6:0], 1'b0};` with `reg [7:0] r`.

::: solution
1. **The registers.** Eight flip-flops with a 2:1 multiplexer in front of each.
2. **Load.** When load is 1 they take d.
3. **Shift.** Otherwise each takes its lower neighbor's value and bit 0 takes 0.

**Answer:** a loadable shift register that shifts left one place per clock.
:::
:::

::: example
## This combinational block has a bug: `always @(*) if (en) y = a;`. What does it build, and how do you fix it?

::: solution
1. **Find the missing path.** When en is 0 nothing assigns y, so y must remember its value: the tool infers a latch enabled by en.
2. **Fix it.** Add `else y = 0;` (or whatever y should be) so y is assigned on every path.

**Answer:** a latch enabled by en; adding an `else` that assigns y removes it.
:::
:::

::: example
## Compare `always @(posedge clk) begin b = a; c = b; end` with the same block using `<=`. What hardware does each build?

::: solution
1. **With blocking assignments.** With `=`, the statements run in order within the clock edge: b takes a, then c takes the new b, which is a.
2. **What that builds.** Both registers load a, so c is just a copy of b, one stage.
3. **With nonblocking assignments.** With `<=`, every right-hand side is read before any register updates: b takes a, and c takes the old b.
4. **What this builds.** Two flip-flops in a chain, a shift register.
5. **Which to use.** Clocked blocks use `<=` so that the code means the hardware it looks like.

**Answer:** with `=`, one stage (c is a copy of b); with `<=`, two flip-flops in a chain, a shift register.
:::
:::

::: check
given: m = 3 | 7 | 15 | 31
answer: m + 1
tolerance: 0

## How many wires does a vector declared `[{m}:0]` have?

::: right
Right. {answer}.
:::

::: misses
- [m] Count both ends: bits {m} down to 0.
- [any] Not yet. From the top index down to 0, inclusive.
:::
:::

::: check
given: w = 4 | 8; d = 1 | 3; n = 5 | 12; let s = 2^w - d
answer: s + n - 2^w*floor((s + n)/2^w)
tolerance: 0

## A `reg [{w}-1:0] q` starts at {s} and runs `q <= q + 1;` on every clock. What does it hold after {n} clocks?

::: right
Right. It wraps modulo $2^w$ for w = {w}: {answer}.
:::

::: misses
- [s + n] The register has only {w} bits; it wraps around.
- [any] Not yet. Add, then wrap modulo $2^w$.
:::
:::

::: check
given: w = 4 | 8 | 32
answer: w
tolerance: 0

## How many flip-flops does `reg [{w}-1:0] r; always @(posedge clk) r <= r + 1;` create?

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

::: misses
- [any] Not yet. Every bit assigned in a clocked block is a flip-flop.
:::
:::

::: check
kind: choice

## In a clocked block, `a = b; b = a;` (blocking) runs on each edge. What happens?

- [ ] a and b swap
- [x] Both end up with b's old value
- [ ] Both end up with a's old value
- [ ] The tool reports an error

::: misses
- [1] Blocking assignments happen in order: b reads the new a.
- [3] a is overwritten first.
- [4] It's legal, which is what makes it dangerous.
:::
:::

::: check
kind: choice

## A combinational `always @(*)` block assigns y in the `if` branch but not in the `else`. What does synthesis build?

- [ ] Exactly the gates written
- [x] A latch, because y must hold its value when not assigned
- [ ] A flip-flop clocked by the condition
- [ ] Nothing: unassigned outputs are 0

::: misses
- [1] Something has to remember y when the branch isn't taken.
- [3] Flip-flops come from edge-triggered blocks; this is level-sensitive.
- [4] Verilog keeps the old value, it doesn't default to 0.
:::
:::

::: check
kind: boolean
vars: S, A, B
answer: S & A | ~S & B
ops: and, or, not

## What does `assign y = s ? a : b;` compute? Write it with AND, OR and NOT (inputs S, A, B).

::: right
Right. $SA + \bar SB$: a 2:1 multiplexer that picks a when s is 1.
:::

::: misses
- [~S & A | S & B] The condition picks the first value when it's true.
- [any] Not yet. `s ? a : b` is a when s = 1, b otherwise.
:::
:::

::: check
kind: parts
given: N = 4 | 8 | 12; k = 1 | 2 | 3

## `always @(posedge clk) r <= {r[N-2:0], d};` with N = {N}, and a second block that copies its input through k nonblocking registers in a chain.

::: part
answer: N
tolerance: 0

### After how many clocks does a bit of d reach r[N−1]?

::: misses
- [N - 1] It enters r[0] on the first clock.
- [any] One stage per clock.
:::
:::

::: part
answer: N + k
tolerance: 0

### How many flip-flops do the two blocks build together?

::: misses
- [any] N for the shift register plus k.
:::
:::
:::

::: check
kind: boolean
vars: en, a, q
answer: en & a | ~en & q
ops: and, or, not

## The buggy block `always @(*) if (en) y = a;` infers a latch. Write its output y as a function of en, a, and the latch's stored value q.

::: right
Right: $y = en \cdot a + \overline{en}\,q$. When en is 0, y keeps its old value, which is exactly a latch.
:::

::: misses
- [any] Not yet. When en is 0 nothing assigns y, so it holds q.
:::
:::

::: explain
## Why do clocked blocks use nonblocking assignments and combinational blocks use blocking ones?

::: model
In real hardware every flip-flop on a clock captures its input at the same instant, from values that were all present before the edge. Nonblocking assignments model exactly that: all right-hand sides are read first, then all the registers update, so the order of statements doesn't matter. Combinational logic is the opposite: a gate's output feeds the next gate immediately, and blocking assignments, executed in order, let a later statement use a value computed by an earlier one in the same pass. Mixing them up makes the simulation disagree with the hardware the tool builds.
:::
:::

::: practice

::: check
given: m = 7 | 15; k = 2 | 4
answer: m - k + 1
tolerance: 0

## How many bits does the part-select `x[{m}:{k}]` contain?

::: misses
- [any] Inclusive at both ends.
:::
:::

::: check
given: n = 2 | 3 | 4
answer: 2^n
tolerance: 0

## A `case` on an {n}-bit selector can have how many distinct non-default items?

::: misses
- [any] One per value.
:::
:::

::: check
kind: boolean
vars: E, A
answer: E & A
ops: and, or, not

## `assign y = en & a;` with inputs E (en) and A. Write y.

::: misses
- [any] An AND gate.
:::
:::
:::
