TutorialHubASIC Verification Engineer · Phase 0 · Foundations
Study page · Area 02 of 14

Verilog HDL & RTL Basics

How Verilog describes hardware, how the simulator schedules it, and the first testbench that checks a real design — a UART transmitter.

16 h of study 4 modules 9 diagrams · 3 interactiveFree tools · Windows, macOS, Linux 20-question test · 70% to pass Lab: UART TX + testbench
1 · Modules 2 · = vs <= 3 · FSMs 4 · Testbench Lab · UART Area test · 70% ports · nets · 4-stateevent queue · racestwo-process styledriver · monitor · checkfind the planted bug20 questions
Before you start · A

Who this area is for

Verilog is the language every chip, FPGA and verification job is built on. If any of these describe you, start here.

🎓

EE / ECE students

Final-year and master's students preparing for VLSI internships and campus placements in design or verification.

🔁

Software engineers

Developers moving into hardware: you already know loops and functions; this area teaches you why hardware code runs in parallel.

🧪

QA & test engineers

Test automation people heading into design verification — the same mindset (stimulus, check, coverage) applied to silicon.

🔌

FPGA & embedded engineers

You write some Verilog already and want the simulator's rules, race-free coding and a proper testbench habit.

🧩

RTL designers

Designers who want to move to verification and need to think like the person checking their code.

🔄

Career returners

Engineers refreshing HDL fundamentals before interviews after time away from hands-on work.

Prerequisites

You needLevelWhere to get it
Binary, hex, two's complementComfortableArea 01 · Module 1
Gates, multiplexers, addersCan draw themArea 01 · Module 3
Flip-flops, setup/hold, state machinesKnow the ideaArea 01 · Module 4
Any programming languageBasic (variables, if, loops)Helpful, not required
Command lineCan run a command and read its outputInstall guide below walks you through it

Where Verilog sits in the chip flow — and the roles that use it

Spec RTL designwrites Verilog Verificationtests Verilog Synthesisreads Verilog DFTedits netlist Physical design Tape-out &post-silicon bugs found → fixed in RTL Design engineerVerification engineerSynthesis / STADFT engineerPD engineerValidation Teal boxes: where this area's skills are used every day
Verilog is the hand-off format of the whole flow. Designers write it, verification engineers test it, synthesis turns it into gates and DFT engineers edit the result.
RoleHow you use this area on the jobTypical first title
Design verification (DV)Read RTL to debug failures, write testbenches, understand races in waveformsDV Engineer / Verification Engineer I
RTL designWrite synthesizable modules, FSMs and clean resetsASIC Design Engineer / RTL Engineer
FPGAWrite and simulate Verilog before loading it on a boardFPGA Engineer
DFTRead netlists and RTL, simulate scan and BIST patternsDFT Engineer
Post-silicon validationReproduce silicon failures in simulation, read the RTL behind themValidation Engineer
Before you start · B

What you will be able to do

Every outcome is practised in the lab and checked by the area test.

  • Write modules with ports, parameters, nets and variables, and connect them by name.
  • Explain how assign, always @* and always @(posedge clk) become hardware.
  • Predict blocking and non-blocking results and spot race conditions in a waveform.
  • Describe the simulator's event regions and why $display and $strobe differ.
  • Write a synthesizable two-process state machine with a clean reset and no latches.
  • Tell synthesizable code from simulation-only code.
  • Build a clocked testbench with a driver, monitor, expected queue and checker.
  • Find a real bug in a UART transmitter from the first mismatch.
Before you start · C

Tools & software

Everything in this area runs on free, open-source tools. Commercial simulators used at work are listed so you recognise them in job posts.

ToolWhat it doesUsed in this area forCost
Icarus Verilog iverilog + vvpEvent-driven Verilog simulator: compiles then runsEvery example and the lab (make sim)Free
VerilatorVery fast simulator that compiles Verilog/SystemVerilog to C++; also a strict linterSecond simulator and lint checks (make verilator)Free
GTKWave or SurferWaveform viewers for .vcd / .fst dumpsLooking at clocks, states and the UART lineFree
VS Code + Verilog extensionEditor with syntax highlighting and lint on saveWriting RTL and testbenchesFree
EDA PlaygroundBrowser-based simulators, including commercial ones, after a free sign-upZero-install option; also lets you try commercial toolsFree
make and gitRun builds with one command; track your changesLab Makefile; saving your workFree

Commercial simulators you will meet at work

SimulatorVendorNotes
VCSSynopsysWidely used for SystemVerilog/UVM regressions
XceliumCadenceSuccessor of Incisive / NC-Sim; often paired with SimVision or Verisium
QuestaSiemens EDASuccessor of ModelSim; ModelSim/Questa starter editions ship with FPGA tools
i
Same language, same rules

Code that is correct by the standard (IEEE 1364 Verilog, IEEE 1800 SystemVerilog) behaves the same on free and commercial simulators. Learning on Icarus and Verilator transfers directly; only the command lines change.

Before you start · D

Install step by step

Pick your computer. About 15 minutes. If anything fails, the browser option works with nothing installed.

Recommended: WSL 2 (Ubuntu inside Windows). You get the same commands as Linux and as most companies' compute farms.

  1. Turn on WSL and install UbuntuOpen PowerShell as Administrator and run the command below, then restart the computer.
    wsl --install
    After the restart an Ubuntu window opens: choose a user name and password.
  2. Update Ubuntu and install the toolsIn the Ubuntu window:
    sudo apt update
    sudo apt install -y iverilog verilator gtkwave make git
  3. Install VS Code and connect it to WSLInstall VS Code from code.visualstudio.com, add the WSL extension, then in Ubuntu type code . to open the current folder.
  4. Add Verilog supportIn VS Code's Extensions panel install Verilog-HDL/SystemVerilog/Bluespec SystemVerilog (publisher mshr-h).
  5. Check it works
    iverilog -V | head -1
    verilator --version
    Each prints a version line. Waveforms: run gtkwave (Windows 11 shows Linux windows directly).
i
No WSL allowed on your laptop?

Install the native Icarus Verilog for Windows build (installer from bleyer.org/icarus, which also bundles GTKWave) and tick "Add executable folder to the user PATH". Use EDA Playground for Verilator.

Before you start · E

Your first simulation in 5 minutes

Prove the tools work end to end: write, compile, run, look at a waveform.

  1. Make a folder and a file called hello.v
    module hello;
      reg clk = 0;
      always #5 clk = ~clk;                // 10 ns clock
      initial begin
        $dumpfile("hello.vcd"); $dumpvars(0, hello);
        $display("Hello, hardware! t=%0t", $time);
        #50 $finish;
      end
    endmodule
  2. Compile it
    iverilog -g2012 -o hello.vvp hello.v
    -g2012 turns on SystemVerilog-2012 features; -o names the compiled output.
  3. Run it
    vvp hello.vvp
    Expected output:
    VCD info: dumpfile hello.vcd opened for output.
    Hello, hardware! t=0
    hello.v:7: $finish called at 50 (1s)
  4. Open the waveform
    gtkwave hello.vcd
    Click hello in the hierarchy, drag clk into the signal list: five full clock periods.
Before you start · F

Two-week study plan

16 hours at about 8 hours a week. Read, try every code block, then lab, then test.

SessionDo thisTime
Day 1Install tools · first simulation · Module 1 (modules, nets, four-state, vectors)3 h
Day 2Module 2 (hardware mapping, blocking vs non-blocking, event queue); try the shift-register switch3 h
Day 3Module 3 (FSMs, synthesizable subset); type the UART FSM and simulate it2.5 h
Day 4Module 4 (testbench architecture, UART monitor)2.5 h
Day 5Lab: complete the monitor, find and fix the bug, reach PASS3 h
Day 6Cheat sheet review · interview questions · area test (70% to pass)2 h
Module 1 of 4

Modules, ports & nets

A module is a box of hardware. Learn to read its boundary, what flows across it, and which values a wire can hold.

  • Module anatomy: ports, parameters, instances
  • Nets vs variables, and why reg is misleading
  • Four-state logic: 0, 1, X, Z
  • Vectors, part-selects, concatenation
⏱ 4 hoursArea 02 · Verilog
▶

Start from zero

New to this? Work through these steps first, in order. Already comfortable? Skim them and jump to the reference below.

1
Step 1

Verilog describes hardware, not steps

≈In plain words

A software program runs one line after another. Verilog is different: each statement describes a piece of hardware that exists all the time, and all the pieces work at once.

☀Think of it like

A recipe says “first do this, then that”. A building plan says “here is a door, here is a window” — they all exist together. Verilog is the building plan.

✎Worked example
assign y = a & b;   // not “compute once”: an AND gate that is always there

Whenever a or b changes, y changes — forever, just like a real gate.

AaThe word for it

A hardware description language (HDL). The code you verify is called RTL (register-transfer level).

!Why it matters

If you read RTL like a program you will predict the wrong values. Read it as a circuit: every line is always active.

2
Step 2

A module is a box with pins

≈In plain words

Every design is built from modules. A module is a box: it has named pins (ports) for signals going in and out, and logic inside.

☀Think of it like

A phone charger: you only care about the socket and the plug. What's inside is its own business.

✎Worked example
module half_adder sum = a ^ bcarry = a & b input ainput bsumcarry ports are the pins · the outside only sees the pins
The half adder from Area 01, as a Verilog module.
module half_adder (input  a, b,
                   output sum, carry);
  assign sum   = a ^ b;
  assign carry = a & b;
endmodule
AaThe word for it
module, ports (input, output, inout).
!Why it matters

The design you verify is a module (the DUT, device under test). Your testbench only touches its ports.

3
Step 3

Modules inside modules

≈In plain words

Big designs are built by placing modules inside other modules and wiring their ports together.

☀Think of it like

LEGO: small bricks make a wall, walls make a house.

✎Worked example
module full_adder (input a, b, cin, output sum, cout);
  wire s1, c1, c2;
  half_adder ha1 (.a(a),  .b(b),   .sum(s1),  .carry(c1));   // one copy
  half_adder ha2 (.a(s1), .b(cin), .sum(sum), .carry(c2));   // another copy
  assign cout = c1 | c2;
endmodule

.a(s1) means: plug my wire s1 into the copy's pin a.

AaThe word for it

Each placed copy is an instance; the result is a hierarchy.

!Why it matters

Waveform viewers show the hierarchy as a tree (tb.dut.ha2.sum). You will navigate it daily to find signals.

4
Step 4

wire versus reg

≈In plain words

A wire just shows whatever drives it, all the time. A reg holds the last value an always block gave it.

☀Think of it like

A wire is a water pipe: it carries whatever flows in. A reg is a bucket: it keeps what you last poured in until you pour again.

✎Worked example
You writeUseBecomes
assign y = a | b;wire ya gate
always @(*) y = a | b;reg ythe same gate!
always @(posedge clk) q <= d;reg qa flip-flop
AaThe word for it
Nets (wire) and variables (reg). Despite the name, a reg is not always a register.
!Why it matters

Seeing reg and assuming “flip-flop” is a classic beginner mistake when reading RTL.

5
Step 5

Every bit has four values: 0, 1, X, Z

≈In plain words

In simulation a bit can be 0, 1, X (unknown) or Z (not driven by anyone).

☀Think of it like

X is a smudged meter reading — it's there but you can't tell what. Z is an unplugged cable — nothing is driving it.

✎Worked example
SituationValue
reg never assigned, or no resetX
wire with nothing connectedZ
two drivers fighting (0 and 1)X
X & 00 (AND with 0 is 0 anyway)
X & 1X
AaThe word for it
Four-state logic.
!Why it matters

Real silicon has no X — so an X in simulation is a warning that hardware may behave randomly. Good checkers treat X as a failure.

What is 1'bx | 1'b1? And 1'bx | 1'b0?

OR with 1 is always 1 → 1. OR with 0 passes the other input → X.

6
Step 6

Vectors: many bits in one name

≈In plain words

A vector is a group of bits with one name, like an 8-bit bus. You can pick single bits, slices, join vectors and repeat them.

☀Think of it like

A ribbon cable of 8 wires, numbered 7 down to 0.

✎Worked example
  1. wire [7:0] data = 8'hB6; → 1011_0110.
  2. One bit: data[7] = 1.
  3. A slice: data[3:0] = 4'h6.
  4. Join (concatenate): {data[3:0], data[7:4]} = 8'h6B (nibbles swapped).
  5. Repeat: {4{1'b1}} = 4'b1111.
AaThe word for it
Vector, part-select, concatenation { }, replication {n{ }}.
!Why it matters

Packets, registers and buses are all vectors; your checks slice them into fields.

What is {2'b10, 2'b01}? And 8'hB6 bits [7:4]?
4'b1001. Bits [7:4] of 1011_0110 are 1011 = 4'hB.
7
Step 7

Number literals: size, base, value

≈In plain words

Verilog numbers are written as size ' base value.

☀Think of it like

Like writing a price with its currency: “8 bits, hex, B6”.

✎Worked example
LiteralMeansBits
4'b10104 bits, binary1010
8'hFF8 bits, hex1111_1111
8'd108 bits, decimal0000_1010
'1all ones, any width1…1
10unsized decimal = 32 bits0…01010
AaThe word for it
Sized literals; underscores (8'b1011_0110) are just for readability.
!Why it matters

Unsized or wrongly sized numbers silently truncate or widen values — a common source of mismatches.

≡

Going further: the reference

The same ideas at the next level: precise definitions, tables, rules and interview questions.

module counter #(W = 8) clk rst_n en count[W-1:0] register D → Q +1 count feeds back clock edge
The module boundary. Ports carry signals in and out; parameters (W) let one description build many sizes: counter #(.W(16)) u_cnt (...).

Key definitions

HDL
Hardware Description Language. Describes circuits that all operate at once, not instructions run one after another.
RTL (Register-Transfer Level)
Describing a design as registers plus the combinational logic that moves data between them on each clock edge.
Module
The unit of design in Verilog: a named block with ports. A chip is a hierarchy of module instances.
Port
A signal crossing the module boundary: input, output or inout.
Parameter
A compile-time constant that sizes or configures a module, overridden per instance with #( ).
Instance
One copy of a module placed inside another, with its own name (e.g. u_cnt).
Net (wire)
A connection driven continuously by something else; it holds no value of its own.
Variable (reg/logic)
Holds the last value assigned to it in a procedural block until assigned again.

A complete module

module counter #(parameter int W = 8) (
  input  wire         clk,
  input  wire         rst_n,   // active-low asynchronous reset
  input  wire         en,
  output reg  [W-1:0] count
);
  always @(posedge clk or negedge rst_n)
    if (!rst_n)  count <= '0;
    else if (en) count <= count + 1'b1;
endmodule

Nets versus variables

KindDeclared asGets its value fromUse for
Netwirecontinuous drivers: assign, module outputsconnections between blocks
Variablereg / logicprocedural assignment in always / initialanything assigned in a block
!
reg does not mean register

A reg assigned in always @* is plain combinational logic. Only a clocked block makes a flip-flop. New code uses logic.

Every bit has four values

0
Logic low

Driven to ground.

1
Logic high

Driven to supply.

X
Unknown

Unreset flop, two drivers fighting, undriven read.

Z
High-impedance

Nobody drives the wire (tri-state bus released).

Vectors: slice, join, repeat

word byte_q [31:24] byte_q [23:16] 16'h00FF [15:0] 310 low = word[7:0] {4{2'b10}} → 8'b10_10_10_10
Concatenation builds wide buses, part-selects take them apart. {byte_q, byte_q, 16'h00FF} is 32 bits, MSB on the left.

Hierarchy: modules inside modules

module top (input wire clk, rst_n, output wire [15:0] events);
  counter #(.W(16)) u_cnt (     // instance name: u_cnt
    .clk  (clk),
    .rst_n(rst_n),
    .en   (1'b1),
    .count(events)
  );
endmodule

The hierarchical path top.u_cnt.count names the counter's output anywhere in a simulation — testbenches and waveform viewers use these paths constantly.

Number literals you will read every day

LiteralMeaningValue
8'hA58 bits, hexadecimal1010_0101
4'b10_014 bits, binary; underscores are ignored9
16'd30016 bits, decimal300
8'sd-3 / -8'sd3signed 8-bit1111_1101
'0, '1, 'xfill every bit (SystemVerilog)all zeros / ones / X
4'bx01zbits can be X or ZX 0 1 Z
✗
Common mistakes

Connecting ports by position (breaks silently when ports are reordered) · forgetting a width so 8'hFF + 1 wraps to 0 · leaving a wire undriven so it reads Z · assigning a wire inside an always block (compile error).

Interview corner

Q. What is the difference between wire and reg? A. A wire is driven continuously by an assign or an output; a reg holds the value last assigned in a procedural block. Neither word decides whether hardware has a flip-flop — the clocking of the block does.

Q. When do you see Z on a wire? A. When nothing drives it, or every tri-state driver is released.

Key takeaways

  1. A module is hardware with a boundary; instances build hierarchy.
  2. Nets connect, variables hold; reg does not imply a register.
  3. X means unknown — treat any X on a DUT output as a bug until explained.
  4. Always size literals and connect ports by name.
Module 2 of 4

Blocking vs non-blocking

The single most important rule in RTL. See what each assignment builds, then step through the simulator's event queue.

  • Mapping code to gates, muxes and flip-flops
  • = vs <= with a live shift register
  • The event queue, region by region
  • Five rules that prevent races
⏱ 4 hoursArea 02 · Verilog
▶

Start from zero

New to this? Work through these steps first, in order. Already comfortable? Skim them and jump to the reference below.

1
Step 1

Three ways to write three kinds of hardware

≈In plain words

Almost all RTL is written in three forms, and each turns into a different kind of hardware.

☀Think of it like

Three kitchen tools: a pipe (always flowing), a mixing bowl (recalculated whenever an ingredient changes), and a fridge (stores things at set times).

✎Worked example
You writeIt becomesAssign with
assign y = …;gates (combinational)—
always @(*) …gates (combinational)=
always @(posedge clk) …flip-flops (sequential)<=
AaThe word for it
Continuous assignment and procedural blocks.
!Why it matters

When you look at a line of RTL, the first question is “is this a gate or a flip-flop?” — the form tells you.

2
Step 2

Everything runs at the same time

≈In plain words

All assign statements and always blocks run in parallel. There is no “line 1 runs before line 50”.

☀Think of it like

An orchestra: every instrument plays at once, following the same conductor (the clock).

✎Worked example

Two always @(posedge clk) blocks in different files both wake up on the same edge. Neither goes first in any meaningful sense.

AaThe word for it
Concurrency.
!Why it matters

This is why the order of assignments needs special rules — the next lessons.

3
Step 3

Blocking “=”: right now, in order

≈In plain words

With = the variable changes immediately, and the next line already sees the new value.

☀Think of it like

Passing a note along a row: the second person reads what the first just wrote.

✎Worked example
  1. a = 1; b = a;
  2. After line 1, a = 1.
  3. Line 2 reads the new a → b = 1.
AaThe word for it
Blocking assignment.
!Why it matters

Correct for combinational logic, where you calculate step by step inside one block.

4
Step 4

Non-blocking “<=”: everyone at the same instant

≈In plain words

With <= all right-hand sides are read first, using the old values; then all the left-hand sides update together.

☀Think of it like

A class photo: everyone freezes at the same click; nobody sees anyone else move first.

✎Worked example
q1 <= d; q2 <= q1; → two flip-flops ✓q1 = d; q2 = q1; → q2 gets d at once: one flip-flop ✗ FF q1 FF q2 FF dq2 (2 cycles late)dq1q2 (same as q1)
Same two lines, different assignment, different hardware.
  1. Swap with <=: a <= b; b <= a; → both read old values → a and b really swap ✓
  2. Swap with =: a = b; b = a; → b reads the new a → both end up equal ✗
AaThe word for it
Non-blocking assignment (NBA).
!Why it matters

Flip-flops all sample at the same edge. <= models exactly that, so the simulation matches the silicon.

At a rising edge, d = 1, q1 = 0, q2 = 0. After q1 <= d; q2 <= q1; what are q1 and q2? And with =?

With <=: q1 = 1, q2 = 0 (q2 got the old q1). With =: q1 = 1, q2 = 1 — the shift register collapsed.

5
Step 5

Five rules that keep you safe

≈In plain words

Follow these and races between blocks cannot happen.

☀Think of it like

Traffic rules: they look strict, but everyone arrives safely.

✎Worked example
  1. Flip-flops (always @(posedge clk)): use <=.
  2. Combinational (always @(*)): use =.
  3. Don't mix = and <= in one block.
  4. Assign each variable from only one always block.
  5. Use @(*) so the block wakes on every input.
AaThe word for it
Race condition: a result that depends on which block the simulator happens to run first.
!Why it matters

Races make tests pass on one simulator and fail on another. Reviewers check these rules first.

6
Step 6

Inside one time step

≈In plain words

At each moment the simulator first runs everything that's ready (blocking assignments, gate updates), and only then applies all the <= updates.

☀Think of it like

A teacher collects every answer sheet first, and only then marks them — so no one can copy a marked answer.

✎Worked example
  1. Clock rises.
  2. All flip-flop blocks wake and read their inputs (old values).
  3. Their <= updates are queued.
  4. Queued updates are applied together; gates re-evaluate.
AaThe word for it

The event queue: active region, then the NBA region.

!Why it matters

This explains every “why did my signal change one cycle late?” question you will meet.

7
Step 7

A testbench race, and how to avoid it

≈In plain words

If the testbench changes an input with = exactly at the clock edge, the design may see the old or the new value — it depends on the order the simulator picks.

☀Think of it like

Two people grabbing the same door handle at the same instant.

✎Worked example
// risky: same edge, blocking
@(posedge clk) din = 1;
// safe: drive with <= (or on the falling edge)
@(posedge clk) din <= 1;
AaThe word for it

A testbench race.

!Why it matters

Drive inputs away from the sampling edge. It's the first habit of a reliable testbench.

≡

Going further: the reference

The same ideas at the next level: precise definitions, tables, rules and interview questions.

Three kinds of hardware, three ways to write them

assign y = a & b; aby continuous · gate always_comb (=) abysel · mux always_ff (<=) DQ clkedge-triggered · flip-flop
Pick the block by the hardware you want. Combinational logic uses blocking =; flip-flops use non-blocking <=.

Try it: a two-stage shift register


    

Inside one time step: the event queue

Within a single simulation time the simulator runs regions in a fixed order. Step through what happens to count <= count + 1 at a clock edge.

Active Inactive (#0) NBA Observed Postponed evaluate RHS, run =avoid thisapply all <= updatesassertions$strobe, $monitor
count = 4 before the edge. Press Step.
★
Five rules that prevent races

1 Sequential: <= only. 2 Combinational: = only, default every output first. 3 One variable, one always block. 4 Never mix = and <= on a variable. 5 Testbenches drive inputs away from the active edge.

Key definitions

Blocking assignment =
Updates the left side immediately; the next statement in the block sees the new value.
Non-blocking assignment <=
Evaluates the right side now and schedules the update for the NBA region of the same time step.
Time step
All the activity at one simulation time. Many events and regions can run inside it with zero time passing.
Delta cycle
One pass through the active regions inside a time step; updates can trigger more deltas before time advances.
Race condition
A result that depends on the order the simulator happens to run two processes in — legal for the simulator, unpredictable for you.
Sensitivity list
What wakes a block: @(posedge clk), @* (every input it reads).

Worked example: a testbench race

// DUT samples d at posedge clk
always @(posedge clk) q <= d;

// Testbench A — RACE: changes d with = exactly at the edge
initial begin @(posedge clk); d = 1; end

// Testbench B — safe: drive on the falling edge
initial begin @(negedge clk); d = 1; end

In A, whether q captures 0 or 1 at that edge depends on which process the simulator runs first. Two simulators — or the same one after a code change — can disagree. B moves the change half a cycle away, so there is nothing to race.

✗
Common mistakes

Using = in clocked blocks · incomplete sensitivity lists like always @(a) when the block also reads b (simulation and synthesis then disagree; use @*) · driving the same signal from two always blocks · adding #1 delays to "fix" a race instead of removing it.

Interview corner

Q. Swap two registers without a temp variable. A. always @(posedge clk) begin a <= b; b <= a; end — both right sides are sampled before either update.

Q. Why is #0 discouraged? A. It only pushes an event to the Inactive region; it reorders a race instead of removing it.

Key takeaways

  1. Flip-flops: <=. Combinational logic: = with @*.
  2. Inside one time step, regions run in a fixed order; NBA updates come after all Active evaluation.
  3. Races come from ordering; fix them with coding style, never with delays.
Module 3 of 4

Synthesizable state machines

The UART transmitter you test in the lab is a four-state machine. Read it as a diagram first, then as code.

  • Moore vs Mealy, encoded with enum
  • The two-process FSM template
  • Synthesizable vs simulation-only constructs
  • Reset strategy that verification can trust
⏱ 3.5 hoursArea 02 · Verilog
▶

Start from zero

New to this? Work through these steps first, in order. Already comfortable? Skim them and jump to the reference below.

1
Step 1

A state machine, coded

≈In plain words

From Area 01: an FSM is a state register plus next-state logic. In Verilog that becomes one clocked block and one combinational block.

☀Think of it like

A board game: the counter on the board (state) and the rule card that says where to move next (logic).

✎Worked example
always @(posedge clk) if (rst) state <= IDLE; else state <= next;   // register
always @(*) begin next = state; case (state) … endcase end       // logic
AaThe word for it

The two-process FSM template.

!Why it matters

Every protocol controller you verify is built this way, so you'll recognise the structure instantly.

2
Step 2

Give states names

≈In plain words

States are just numbers in hardware, but you should give them names.

☀Think of it like

Rooms called “Kitchen” and “Bedroom” instead of “Room 2” and “Room 3”.

✎Worked example
localparam IDLE = 2'd0, START = 2'd1, DATA = 2'd2, STOP = 2'd3;
// SystemVerilog: typedef enum logic [1:0] {IDLE, START, DATA, STOP} state_t;
AaThe word for it
State encoding: binary, one-hot or Gray (details below).
!Why it matters

Waveform viewers show enum names, so you read “DATA” instead of decoding 2 in your head.

3
Step 3

Moore or Mealy?

≈In plain words

A Moore output depends only on the state. A Mealy output depends on the state and the current input.

☀Think of it like

Moore: a sign that says “READY” while the machine is in the ready state. Mealy: the snack drops the very moment you press the button.

✎Worked example
MooreMealy
Output fromstatestate + input
Reactsnext cyclesame cycle
Glitches on outputnocan follow input glitches
AaThe word for it
Moore machine, Mealy machine.
!Why it matters

It decides when your checker should expect the output: one cycle later, or immediately.

4
Step 4

The accidental latch

≈In plain words

In a combinational block, every output must get a value on every path. If one path forgets, the tool builds a latch to remember the old value.

☀Think of it like

A door with no spring: if nobody pushes it, it stays wherever it was last left.

✎Worked example
always @(*) if (en) y = a;          // en = 0: y not assigned → latch ✗
always @(*) begin y = 0; if (en) y = a; end   // default first → plain logic ✓
AaThe word for it

An inferred latch; the fix is a default assignment (next = state;) at the top.

!Why it matters

Synthesis and lint tools warn about latches; you'll see these warnings in reports and must know what they mean.

5
Step 5

What becomes hardware, and what doesn't

≈In plain words

Some Verilog only makes sense in simulation and is ignored (or rejected) by synthesis.

☀Think of it like

Stage directions in a script: the actors read them, but the audience never hears them.

✎Worked example
CodeIn silicon?
assign, always @(*), always @(posedge clk)Yes
#5 delaysNo — ignored
$display, $finishNo
initial blocksNo (except some FPGA init)
AaThe word for it
Synthesizable versus simulation-only constructs.
!Why it matters

Testbenches use everything; RTL may use only the synthesizable part. A #5 in RTL is a red flag in review.

Which of these end up as hardware: assign, #10, $display, always @(posedge clk)?

Only assign and always @(posedge clk).

6
Step 6

A reset you can trust

≈In plain words

Every state register needs a reset that puts the FSM in a known state (usually IDLE).

☀Think of it like

Pressing “home” on a game controller: wherever you were, you're back at the menu.

✎Worked example
StyleCodeActs
Synchronousalways @(posedge clk) if (rst) …on the next clock edge
Asynchronousalways @(posedge clk or posedge rst) if (rst) …immediately
AaThe word for it
Synchronous and asynchronous reset.
!Why it matters

The first check of any FSM test: after reset, the state is IDLE and the outputs are idle values.

≡

Going further: the reference

The same ideas at the next level: precise definitions, tables, rules and interview questions.

startticktick && last tick: next bittick IDLE START DATA STOP tx = 1tx = 0tx = data[i]tx = 1
One frame, four states. The line idles high, drops for the start bit, sends eight data bits LSB first, then a high stop bit. Press Send to watch the machine and the wire move together.
typedef enum logic [1:0] {IDLE, START, DATA, STOP} state_t;
state_t state, next;

always_ff @(posedge clk or negedge rst_n)       // 1) state register
  if (!rst_n) state <= IDLE; else state <= next;

always_comb begin                                // 2) next-state logic
  next = state;                                   // default: stay — no latches
  case (state)
    IDLE:  if (start)        next = START;
    START: if (tick)         next = DATA;
    DATA:  if (tick && last) next = STOP;
    STOP:  if (tick)         next = IDLE;
  endcase
end
Synthesizable
assign, always_comb, always_ff
if, case, for with constant bounds
arithmetic, shifts, compares, parameters
Simulation only
initial, #delays, wait
$display, $random, file I/O
force / release

Key definitions

Finite state machine (FSM)
Logic with a state register and rules that pick the next state from the current state and inputs.
Moore machine
Outputs depend only on the current state. Glitch-free, one cycle later to react.
Mealy machine
Outputs depend on state and inputs. Reacts in the same cycle; outputs can glitch with inputs.
Latch
Level-sensitive storage, usually created by accident when a combinational block does not assign an output on every path.
Synthesis
Turning RTL into a gate-level netlist. Only a subset of Verilog (the synthesizable subset) can be turned into gates.
Reset
Forces registers to a known value. Asynchronous resets act immediately; synchronous ones on the next clock edge.

State encodings

Encoding4 states asFlip-flopsGood for
Binary00, 01, 10, 112Smallest area
One-hot0001, 0010, 0100, 10004Fast decode; common on FPGAs
Gray00, 01, 11, 102One bit changes per step; counters crossing clock domains
★
Verification habit: check after reset

Right after reset is released, assert that every output is known: if ($isunknown(tx)) $error("tx is X after reset");. Unreset state is one of the most common silicon bugs.

✗
Common mistakes

Missing default / default assignment → latch · next-state logic in the clocked block (works, but hard to read and to cover) · forgetting to reset the state register · comparing state to raw numbers instead of enum names.

Interview corner

Q. How would you detect an unintended latch? A. Synthesis and lint (Verilator -Wall) warn about inferred latches; in review, look for combinational blocks without default assignments.

Q. Moore or Mealy for a UART transmitter? A. Moore: the line value must be stable for a whole bit period, so it should depend only on state.

Key takeaways

  1. Two processes: a clocked state register and a combinational next-state block.
  2. Default the next state at the top of always_comb.
  3. Keep delays, prints and initial out of RTL.
Module 4 of 4

Your first testbench

Every testbench — from this lab to a full UVM environment — has the same four jobs. Build them as separate pieces from day one.

  • Clock, reset and stimulus
  • Driver, monitor, reference model, checker
  • Sampling a serial line correctly
  • Self-checking PASS / FAIL reporting
⏱ 4.5 hoursArea 02 · Verilog
▶

Start from zero

New to this? Work through these steps first, in order. Already comfortable? Skim them and jump to the reference below.

1
Step 1

What a testbench is

≈In plain words

A testbench is Verilog code that surrounds your design, feeds it inputs and checks its outputs. It has no ports and never becomes hardware.

☀Think of it like

A car on a test bench in a garage: rollers spin the wheels, sensors read the engine — the car doesn't know it isn't on a road.

✎Worked example
module tb — no ports, never becomes hardware clock · reset driver DUT monitor checker reference model PASS / FAIL
The parts of every self-checking testbench.
AaThe word for it
Testbench; the design inside it is the DUT.
!Why it matters

This picture is the skeleton of everything you'll build — up to full UVM environments in later areas.

2
Step 2

Making a clock and a reset

≈In plain words

The testbench creates the clock by flipping a signal forever, and holds reset for a few cycles at the start.

☀Think of it like

Starting a metronome, then counting “one, two” before the band starts playing.

✎Worked example
reg clk = 0, rst = 1;
always #5 clk = ~clk;            // period 10 ns → 100 MHz
initial begin
  repeat (3) @(posedge clk);   // 3 cycles in reset
  rst <= 0;
end
AaThe word for it
Clock generation and the reset sequence.
!Why it matters

Wrong clock periods and too-short resets are behind many “the design does nothing” first runs.

With always #5 clk = ~clk; in a 1 ns timescale, what is the clock frequency?

High 5 ns + low 5 ns = 10 ns period → 100 MHz.

3
Step 3

Driving inputs

≈In plain words

A driver sets the DUT's inputs, cycle by cycle. Wrap repeated actions in a task.

☀Think of it like

A robot arm pressing buttons in a fixed rhythm.

✎Worked example
task send(input [7:0] b);
  @(posedge clk); data <= b; valid <= 1;
  @(posedge clk); valid <= 0;
endtask
initial begin send(8'h41); send(8'h03); end
AaThe word for it

A driver and a task.

!Why it matters

Tasks turn stimulus into readable sentences — “send A, then send 3” — which you'll extend into sequences later.

4
Step 4

Sampling a serial line

≈In plain words

A UART sends one byte as a frame: a start bit (0), eight data bits least significant first, then a stop bit (1). A monitor rebuilds the byte by sampling each bit in the middle of its time slot.

☀Think of it like

Reading a ticker tape: you read each letter in the centre of its box, not on the line between boxes.

✎Worked example
startd0d1d2d3d4d5d6d7stop 10000010 8'h41 = 0100_0001 is sent LSB first: 1 0 0 0 0 0 1 0● sample each bit in the middle of its slot, never at the edges
How 8'h41 (the letter “A”) appears on the wire.
AaThe word for it
Frame, LSB-first, mid-bit sampling.
!Why it matters

Lab 02's planted bug sends bits in the wrong order. A correct monitor is what catches it.

Write the line bits (start to stop) for 8'h03, sent LSB first.
8'h03 = 0000_0011 → data bits LSB first are 1 1 0 0 0 0 0 0. Frame: 0 · 1 1 0 0 0 0 0 0 · 1.
5
Step 5

Checking against a reference model

≈In plain words

A reference model computes what the output should be in plain code. The checker compares the DUT's result with it and counts mismatches.

☀Think of it like

Marking a test with the answer key.

✎Worked example
expected = model(byte_sent);
if (got !== expected) begin
  errors = errors + 1;
  $display("MISMATCH sent %h got %h", expected, got);
end
AaThe word for it
Reference model, checker. Use !==: it treats X and Z as differences, while != would hide them.
!Why it matters

A testbench that only drives inputs proves nothing. Self-checking is what makes it a test.

6
Step 6

PASS or FAIL, honestly

≈In plain words

At the end, print one clear line: how many checks ran and whether all passed.

☀Think of it like

A scoreboard at the end of a match — no one has to watch the whole game to know the result.

✎Worked example
if (checks == 0)        $display("FAIL: no checks ran");
else if (errors == 0) $display("PASS %0d/%0d", checks, checks);
else                    $display("FAIL %0d errors", errors);
AaThe word for it

A self-checking testbench.

!Why it matters

“PASS with zero checks” is a silent failure. Always prove that the checks actually ran.

≡

Going further: the reference

The same ideas at the next level: precise definitions, tables, rules and interview questions.

module tb_uart_tx Stimulus Driver DUTuart_tx Monitor Checker Expectedqueue of bytes bytestart, datatxbytepushpop PASS 54/54 · or · MISMATCH
Four parts, one loop. The driver turns transactions into pin wiggles, the monitor turns pins back into transactions, and the checker compares them with what was sent. UVM formalises exactly these parts in Areas 08–12.
PartJob in this labBecomes in UVM
Driversend(b) task pulses start with datauvm_driver
Monitorfinds the start bit, samples mid-bit, rebuilds the byteuvm_monitor
Reference modelqueue of bytes in send orderpredictor
Checkercompares, counts, prints PASS / FAILuvm_scoreboard
i
Sample in the middle of the bit

After the falling edge of the start bit, wait CLKS_PER_BIT/2 clocks, confirm the line is still 0, then sample every CLKS_PER_BIT clocks. The middle has the most margin against timing error.

Key definitions

DUT
Design Under Test: the module being verified, instantiated inside the testbench.
Testbench
A top-level module with no ports that creates clocks, drives inputs, observes outputs and reports results.
Transaction
A unit of work at a higher level than pins, such as "send byte 0xA5".
Self-checking
The testbench decides PASS or FAIL itself, so nobody has to read waveforms to know the result.
Reference model
An independent prediction of what the DUT should do — here simply the list of bytes sent.
Regression
Running many tests, usually every night or on every change, to catch anything that broke.

The complete monitor (the pattern you will write in the lab)

initial begin
  @(posedge rst_n);
  forever begin
    @(negedge tx);                           // start bit begins
    repeat (CPB/2) @(posedge clk);             // move to its middle
    if (tx !== 1'b0) $error("false start");
    for (i = 0; i < 8; i = i + 1) begin
      repeat (CPB) @(posedge clk);
      rx[i] = tx;                                // LSB first
    end
    repeat (CPB) @(posedge clk);
    if (tx !== 1'b1) $error("bad stop bit");
    if (rx !== expected[n_checked]) n_errors = n_errors + 1;
    n_checked = n_checked + 1;
  end
end

System tasks every testbench uses

TaskDoes
$display / $writePrint now (with / without newline)
$strobe / $monitorPrint at the end of the time step / whenever an argument changes
$time, %0tCurrent simulation time and how to print it
$random, $urandomRandom numbers for stimulus
$dumpfile, $dumpvarsWrite a VCD waveform file
$error, $fatalReport a failure (and stop, for $fatal)
$finishEnd the simulation
✗
Common mistakes

Ending the test before the last byte is checked · printing PASS when zero items were checked · comparing with != so X slips through · sampling exactly on an edge.

Interview corner

Q. What makes a testbench self-checking? A. An independent expected result, an automatic comparison, and a summary that fails loudly — including when nothing was checked.

Q. Why separate driver and monitor? A. So the monitor checks what really appeared on the pins, not what the driver intended; it also lets you reuse the monitor when another block drives the bus.

Key takeaways

  1. Driver, monitor, reference model, checker — even in a 50-line testbench.
  2. Compare with !==; count checks; fail when nothing was checked.
  3. Sample serial data in the middle of the bit.
Practice

Check yourself

Answer in your head, then open each card. The area test has 20 more.

Why doesn't reg imply a flip-flop?
reg only means "assigned in a procedural block". The block's sensitivity decides the hardware: always @* gives logic, always @(posedge clk) gives flops.
After one edge in the blocking shift register, what does q2 hold?
The new d. Blocking updates q1 immediately, so q2 = q1 reads the new value and the two stages collapse into one.
Why does $strobe print the new value but $display the old one?
$display runs in the Active region, before the NBA region applies <= updates. $strobe runs in Postponed, after everything settled.
Name two reasons an output can be X after reset.
A register feeding it has no reset and was never written; or two drivers fight over the same net.
What hardware does assign y = sel ? a : b; build?
A 2:1 multiplexer: sel chooses which input reaches y.
A combinational always @* block assigns y only inside if (en). What happens?
When en is 0, y must keep its value, so synthesis infers a latch. Add y = '0; (or a default) before the if.
How many clocks does one UART frame take at CLKS_PER_BIT = 8?
10 bits (start + 8 data + stop) × 8 = 80 clocks.
Your testbench prints PASS but checked 0 bytes. Why is that a bug?
A test that checks nothing passes for any design. Always require n_checked == n_sent and n_checked > 0.
Reference

Interview questions

Asked in DV and RTL interviews at every level. Try an answer out loud before opening.

Explain blocking vs non-blocking with an example.
Show the two-stage shift register: with <= you get two flops, with = the second stage collapses. Then state the rule: <= in sequential, = in combinational blocks.
What is the difference between == and ===?
== returns X if either operand has X or Z bits; === compares X and Z literally and always returns 0 or 1. Testbenches use ===/!==.
How does synthesis treat an initial block?
ASIC synthesis ignores it. Some FPGA tools use it to set power-up register values. Never rely on it for ASIC reset.
What is a full case / parallel case problem?
If a case doesn't cover every value and there's no default, combinational logic infers a latch. Synthesis pragmas (full_case, parallel_case) can make synthesis and simulation disagree — prefer a default and SystemVerilog unique/priority.
Write a divide-by-2 clock.
always @(posedge clk or negedge rst_n) if (!rst_n) clk2 <= 0; else clk2 <= ~clk2; — and mention that real designs prefer clock enables over generated clocks.
Asynchronous vs synchronous reset?
Async acts immediately (in the sensitivity list), needs a synchronised release; sync acts on the clock edge and needs the clock running. Both are common; follow the project's convention.
What does $monitor do differently from $display?
$monitor prints whenever any of its arguments changes, at the end of the time step; only one is active at a time.
How do you make a testbench fail if the DUT hangs?
Add a watchdog: initial begin #1ms; $fatal(1, "timeout"); end, or a cycle counter that errors if busy stays high too long.
Reference

Glossary

Every term used on this page, A to Z.

Active regionWhere processes run and blocking assignments update within a time step.
Asynchronous resetReset in the sensitivity list; takes effect without a clock edge.
Combinational logicOutputs depend only on current inputs; no memory.
Concatenation{a, b} joins vectors into a wider one.
Delta cycleA zero-time pass through the scheduler inside one time step.
DUTDesign under test.
Event queueThe simulator's ordered list of things to do at each time.
Flip-flopEdge-triggered storage element; built from always @(posedge clk).
FSMFinite state machine: state register + next-state logic.
InstanceA named copy of a module inside another module.
LatchLevel-sensitive storage, often inferred by mistake.
LintStatic checks for suspicious code (Verilator --lint-only -Wall).
MonitorTestbench part that turns pin activity into transactions.
NBA regionWhere scheduled non-blocking updates are applied.
NetA continuously driven connection (wire).
NetlistThe gate-level design produced by synthesis.
ParameterCompile-time constant that configures a module.
Part-selectv[7:0]: a contiguous slice of a vector.
Race conditionBehaviour that depends on process execution order.
RTLRegister-transfer level: registers plus the logic between them.
Self-checking testbenchDecides PASS/FAIL automatically.
SynthesisConverting RTL into gates.
UART 8N1Serial format: 8 data bits, no parity, 1 stop bit, LSB first.
VCDValue Change Dump: the standard waveform file format.
X / ZUnknown / high-impedance values in four-state logic.
Reference

FAQ & troubleshooting

The errors learners hit most in this area, and the fix for each.

You seeWhyFix
iverilog: command not foundNot installed, or not on PATHRe-run the install step; on Windows reopen the terminal after the installer
Unknown module type: uart_txThe design file wasn't passed to the compilerList every file: iverilog -o sim.vvp uart_tx.v tb_uart_tx.v
syntax error on logic or always_ffSystemVerilog keywords without SV modeAdd -g2012 (Icarus) or name the file .sv
Simulation never endsNo $finish, or waiting on a signal that never changesAdd a watchdog timeout; check the wait condition
Output is X foreverReset never asserted, or a register isn't resetHold rst_n low for a few clocks at the start
Waveform file is emptyNo $dumpvars, or $finish before anything happenedAdd the dump block at time 0
Results differ between Icarus and VerilatorA race or X-dependent codeApply the five race rules; check for X with $isunknown
Reference

Further reading

Go deeper when you are ready. Standards are the final word on simulator behaviour.

ResourceWhy read it
IEEE 1364-2005 (Verilog) and IEEE 1800 (SystemVerilog) standardsThe scheduling regions and every language rule, defined exactly
Clifford E. Cummings, Nonblocking Assignments in Verilog Synthesis, Coding Styles That Kill! (SNUG 2000)The classic paper behind the race-free coding rules
Samir Palnitkar, Verilog HDL: A Guide to Digital Design and SynthesisThorough language reference with exercises
Harris & Harris, Digital Design and Computer ArchitectureDigital logic and HDL side by side
Icarus Verilog and Verilator user guidesCommand-line options, warnings and lint flags
Hands-on lab · about 3 hours

Lab 02 · UART transmitter and its first testbench

You get uart_tx.v (8N1, one planted bug), tb_uart_tx.v with a driver and an empty monitor, and a Makefile for Icarus Verilog or Verilator.

  1. Complete the monitor: detect the start bit, sample each bit mid-period, check the stop bit, rebuild the byte.
  2. Compare every received byte with the expected queue.
  3. Send 0x00, 0xFF, 0xA5, 0x5A and 50 random bytes — the mismatches reveal the bug's pattern.
  4. Fix the RTL and re-run until you see PASS: 54/54 bytes.