Skip to content
systemcoding.dev
Hardware

The Complete Guide to Verilog for Firmware Engineers

Learn Verilog from a firmware engineer's view: wires, registers, clocked logic, state machines, testbenches and a first FPGA build, with worked code.

29 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the Raspberry Pi, STMicroelectronics and Nordic Semiconductor logos.

If you write firmware, you already think in registers, bits, interrupts and timing. Verilog describes the hardware those registers live in. That makes it less foreign than it looks, and also more dangerous, because the syntax resembles C while the meaning does not. This guide teaches Verilog as IEEE 1364-2005 defines it, from the viewpoint of someone who has configured a UART on a microcontroller and now wants to build one. It covers the mental model first, then modules, wires, registers, clocked logic, finite state machines, testbenches and a first synthesis run for a small FPGA. Every sample was written against Icarus Verilog 12.0 for simulation and Yosys 0.40 for synthesis, and every output block shows what those tools print for the code above it.

It is a hub for the Hardware cluster. Later posts take single topics from here and go deeper: blocking and non-blocking assignments, state machines, clock-domain crossing and block RAM. Read this one for the whole map.

What Verilog is, and what it is not

A program in C is a list of steps. A processor fetches one instruction, executes it, and moves to the next. Verilog has no such list. A Verilog design is a description of a circuit: gates, wires and flip-flops that all exist at the same moment and all react to their inputs continuously. When you write two assign statements one after the other, you have not written two steps. You have drawn two pieces of hardware that both work at once.

That single fact explains most of what trips up firmware engineers:

  • Order of statements usually does not matter for combinational logic, because every statement is always active.

  • Variables are not memory locations you read and write. A reg is a name for the output of a storage element, or sometimes just a wire that the language forces you to declare that way.

  • There is no call stack and no function that "runs". A module is instantiated, which means a copy of that hardware is built into the design, permanently.

  • Loops do not repeat over time. A for loop in synthesisable code is unrolled into parallel hardware at build time.

Verilog has two jobs. The first is simulation: a program called a simulator reads the text and models the signals changing over time, so you can check the design before building it. The second is synthesis: a tool reads the same text and turns it into a netlist of gates and flip-flops that an FPGA or chip can implement. Only a subset of the language synthesises. Constructs like #10 delays and $display exist for simulation and are ignored or rejected by synthesis tools. Keeping the two uses apart is the main discipline of the language.

The firmware mental model, translated

Here is a vocabulary map for someone who knows embedded C.

Firmware ideaHardware idea
A peripheral registerA group of flip-flops, one per bit
reg = value; in an ISRA flip-flop loading on a clock edge
if (a && b)An AND gate feeding a multiplexer
A clock tickA rising edge that updates every flip-flop at once
A switchA multiplexer, or a decoder
volatileNot needed. Nothing is cached
A function callA module instance, built once
A busy-wait loopA counter and a comparator, running beside everything else

The clock is the heartbeat. Almost every real design is synchronous: a clock wire goes to every flip-flop, and on each rising edge each flip-flop copies the value on its input to its output. Between two edges, signals ripple through combinational logic and settle. The designer's job is to make sure they settle before the next edge. Chapter after chapter of FPGA work comes down to that sentence.

Your first module

A module is the unit of hardware. It has a name, a list of ports and a body. This is a two-input AND gate:

and2.vverilog
module and2 (
    input  wire a,
    input  wire b,
    output wire y
);
    assign y = a & b;
endmodule

input and output give the direction of each port. wire is a connection: it holds no value of its own and simply carries whatever drives it. assign is a continuous assignment. It says that y is always a & b, and if a changes, y changes after the gate delay, which a simulator treats as zero time unless told otherwise.

A module with a reg output and a clock describes storage:

dff.vverilog
module dff (
    input  wire clk,
    input  wire d,
    output reg  q
);
    always @(posedge clk)
        q <= d;
endmodule

always @(posedge clk) means "whenever clk goes from 0 to 1, do this". The <= is a non-blocking assignment, and it is the correct operator for any storage. After every rising edge, q takes the value d had just before the edge. That is a D flip-flop, and it is the only primitive memory element you need to learn first.

Data types, vectors and literals

Verilog has four-valued logic in simulation: 0, 1, x (unknown) and z (high impedance). Synthesis only builds 0 and 1, but the simulator will show you x for any signal that has not been assigned yet, and that is a useful warning. Two net-like kinds matter: wire for connections and reg for anything assigned inside an always block. A reg does not necessarily become a register. Its name only means "assigned procedurally".

Vectors are declared with a range. wire [7:0] data; is an eight-bit bus whose most significant bit is data[7]. You select bits with data[3], slices with data[7:4], and concatenate with braces: {a, b} joins two signals.

Number literals carry a width, a base and a value. 8'hFF is eight bits holding 255. 4'b1010 is four bits holding ten. 3'd5 is three bits holding five. Always write the width. An unsized literal is 32 bits wide, and that mismatch causes silent truncation or extension that firmware engineers will recognise as the hardware version of an implicit integer promotion.

widths.vverilog
module widths;
    wire [7:0] a = 8'hA5;
    wire [3:0] hi = a[7:4];
    wire [3:0] lo = a[3:0];
    wire [7:0] swapped = {lo, hi};

    initial begin
        #1;
        $display("a=%h hi=%h lo=%h swapped=%h", a, hi, lo, swapped);
    end
endmodule
Text
a=a5 hi=a lo=5 swapped=5a

The initial block and the $display task are simulation features. The #1 waits one time unit so the continuous assignments have settled. Nothing here is synthesised, which is fine, because this module is a toy.

Combinational logic with always blocks

Assigning with assign is good for one-liners. For anything with if or case, use always @*. The * makes the block sensitive to every signal it reads, so it re-evaluates whenever any input changes:

mux4.vverilog
module mux4 (
    input  wire [1:0] sel,
    input  wire [7:0] a,
    input  wire [7:0] b,
    input  wire [7:0] c,
    input  wire [7:0] d,
    output reg  [7:0] y
);
    always @* begin
        case (sel)
            2'd0:    y = a;
            2'd1:    y = b;
            2'd2:    y = c;
            default: y = d;
        endcase
    end
endmodule

This uses blocking assignments, =, because the block describes a combinational function and statements within it should take effect in order. The default branch matters. If a case leaves some input values unhandled and y is not assigned on every path, the synthesiser has to remember the old value of y. Remembering is storage, so it quietly inserts a latch. A latch you did not intend is one of the classic beginner bugs. A later post in this cluster covers the habit of default assignments that prevents it.

Sequential logic: counters and registers

A counter is the hello world of synchronous design. This one counts clock edges and wraps:

counter8.vverilog
module counter8 (
    input  wire       clk,
    input  wire       rst,
    output reg  [7:0] count
);
    always @(posedge clk) begin
        if (rst)
            count <= 8'd0;
        else
            count <= count + 8'd1;
    end
endmodule

The reset here is synchronous: it is only looked at on a clock edge. The addition count + 8'd1 is eight bits wide, so 8'd255 + 8'd1 wraps to 0, exactly like an unsigned uint8_t in C. Notice how little code the whole device needs. There is no loop, no timer, no interrupt. The hardware is simply a register and an adder wired in a ring.

Why non-blocking for clocked logic

The difference between = and <= deserves a post of its own, and it has one. The short rule is this. In a clocked block, use <=. In a combinational block, use =. Mixing them in one block, or using = for state, builds simulations that disagree with the synthesised hardware. The reason is that <= schedules the update for the end of the current time step, so every flip-flop sees the old values of all the others, which is what real hardware does. = updates immediately, so a later statement in the same block sees the new value, and the result depends on statement order.

Consider a two-stage shift of a signal:

shift2.vverilog
module shift2 (
    input  wire clk,
    input  wire din,
    output reg  q1,
    output reg  q2
);
    always @(posedge clk) begin
        q1 <= din;
        q2 <= q1;
    end
endmodule

On each edge, q1 takes din and q2 takes the old q1. That is two flip-flops in a chain, a delay of two clocks. If the code used =, q2 would read the already-updated q1, and the chain would collapse into one delay in simulation, while synthesis might still build two flip-flops. That mismatch is the bug the rule prevents.

Parameters and reuse

A parameter is a compile-time constant. It lets one module serve many sizes, and it is the closest thing Verilog has to a template argument:

counter_n.vverilog
module counter_n #(
    parameter WIDTH = 8
) (
    input  wire             clk,
    input  wire             rst,
    output reg  [WIDTH-1:0] count
);
    always @(posedge clk) begin
        if (rst)
            count <= {WIDTH{1'b0}};
        else
            count <= count + 1'b1;
    end
endmodule

{WIDTH{1'b0}} is a replication: it repeats 1'b0 WIDTH times, giving an all-zeros vector of the right size. Instantiating the module with a different width is done with the #() syntax:

top_counters.vverilog
module top_counters (
    input  wire        clk,
    input  wire        rst,
    output wire [3:0]  small,
    output wire [15:0] large
);
    counter_n #(.WIDTH(4))  u_small (.clk(clk), .rst(rst), .count(small));
    counter_n #(.WIDTH(16)) u_large (.clk(clk), .rst(rst), .count(large));
endmodule

Each instance is a separate piece of hardware. They run in parallel, and nothing about one affects the other. Named port connections, .clk(clk), are strongly preferred over positional ones, because a swapped port in a positional list is a bug the compiler cannot see.

A testbench: simulating without hardware

A testbench is a module with no ports that instantiates your design, drives its inputs and prints what comes back. Here is one for counter8:

counter8_tb.vverilog
`timescale 1ns/1ps

module counter8_tb;
    reg        clk = 1'b0;
    reg        rst = 1'b1;
    wire [7:0] count;

    counter8 dut (.clk(clk), .rst(rst), .count(count));

    always #5 clk = ~clk;

    initial begin
        $dumpfile("counter8.vcd");
        $dumpvars(0, counter8_tb);
        #12 rst = 1'b0;
        #50;
        $display("count after 5 edges: %0d", count);
        $finish;
    end
endmodule

timescale 1ns/1ps sets the time unit to a nanosecond. always #5 clk = ~clk; toggles the clock every 5 ns, giving a 10 ns period. The reset is released at 12 ns, after one rising edge at 5 ns has already reset the counter. After 62 ns in total, rising edges have occurred at 5, 15, 25, 35, 45, 55 ns. The edge at 5 ns saw rst high, so the counter held zero. The release at 12 ns means the edges at 15, 25, 35, 45 and 55 ns each incremented once: five increments, so the count is 5. With Icarus Verilog 12.0, you compile and run in two commands:

Shell
iverilog -g2005 -o counter8_tb.vvp counter8.v counter8_tb.v
vvp counter8_tb.vvp
Text
VCD info: dumpfile counter8.vcd opened for output.
count after 5 edges: 5

The .vcd file is a waveform dump that a viewer such as GTKWave can open. For a first design, reading it is the fastest way to see what the clock, reset and counter did relative to each other. The line from the simulator about the dump file appears because of $dumpfile.

Self-checking is better than looking

Printing a number and eyeballing it does not scale. Make the testbench decide:

counter8_check.vverilog
`timescale 1ns/1ps

module counter8_check;
    reg        clk = 1'b0;
    reg        rst = 1'b1;
    wire [7:0] count;
    integer    errors = 0;

    counter8 dut (.clk(clk), .rst(rst), .count(count));

    always #5 clk = ~clk;

    initial begin
        #12 rst = 1'b0;
        repeat (3) @(posedge clk);
        #1;
        if (count !== 8'd3) begin
            $display("FAIL: expected 3, got %0d", count);
            errors = errors + 1;
        end
        if (errors == 0)
            $display("PASS");
        $finish;
    end
endmodule

The operator !== compares with four-valued logic, so an x in count counts as a mismatch instead of silently passing. After reset is released at 12 ns, the edges at 15, 25 and 35 ns are the three waited for, and the #1 lets the non-blocking update land before the check.

Text
PASS

Finite state machines

A state machine is the way hardware does what firmware does with a switch on a state variable. The usual shape has three parts: a state register, a next-state function and an output function. A pedestrian-crossing controller with three states shows it:

crossing.vverilog
module crossing (
    input  wire clk,
    input  wire rst,
    input  wire button,
    output reg  walk,
    output reg  stop
);
    localparam IDLE = 2'd0;
    localparam WAIT = 2'd1;
    localparam GO   = 2'd2;

    reg [1:0] state;
    reg [1:0] next;
    reg [3:0] timer;

    always @(posedge clk) begin
        if (rst) begin
            state <= IDLE;
            timer <= 4'd0;
        end else begin
            state <= next;
            if (state != next)
                timer <= 4'd0;
            else
                timer <= timer + 4'd1;
        end
    end

    always @* begin
        next = state;
        case (state)
            IDLE: if (button)         next = WAIT;
            WAIT: if (timer == 4'd3)  next = GO;
            GO:   if (timer == 4'd5)  next = IDLE;
            default:                  next = IDLE;
        endcase
    end

    always @* begin
        walk = (state == GO);
        stop = (state != GO);
    end
endmodule

Three things make this a good template. The state register is the only clocked part and it uses <=. The next-state block starts with next = state;, a default assignment that guarantees next is always driven and avoids a latch. The outputs depend only on the state, which makes this a Moore machine, so they change cleanly on clock edges and never glitch from an input. A later post in this cluster develops the synthesisable-FSM habits in full.

Memories and arrays

An array of registers describes a memory. Declare it as reg [7:0] mem [0:255];, which is 256 words of 8 bits. Reading and writing it inside a clocked block is the standard way to describe a small RAM:

ram256.vverilog
module ram256 (
    input  wire       clk,
    input  wire       we,
    input  wire [7:0] addr,
    input  wire [7:0] wdata,
    output reg  [7:0] rdata
);
    reg [7:0] mem [0:255];

    always @(posedge clk) begin
        if (we)
            mem[addr] <= wdata;
        rdata <= mem[addr];
    end
endmodule

Because the read is registered, the pattern matches what an FPGA's block RAM does, and the synthesis tool can map it to a block RAM primitive instead of hundreds of flip-flops. That is why the read of mem[addr] goes into a register named rdata rather than into a combinational output.

From simulation to an FPGA

Simulation proves the logic. A real FPGA also needs to know which physical pin each port uses and what the clock frequency is. A complete blinking design for a typical iCE40 board needs a top module with one clock input and one LED output, and a constraint file. The first post of the next cluster builds exactly that. Here is the shape in brief:

blink.vverilog
module blink (
    input  wire clk,
    output wire led
);
    reg [23:0] divider = 24'd0;

    always @(posedge clk)
        divider <= divider + 24'd1;

    assign led = divider[23];
endmodule

With a 12 MHz oscillator, bit 23 of a free-running counter toggles every 2^23 clock cycles, 8,388,608 of them, which is about 0.7 seconds. The LED therefore changes state roughly every 0.7 s and blinks with a period near 1.4 s. The initial value in the declaration, = 24'd0, is honoured by FPGA flows that load register contents from the bitstream. It is not a feature you can rely on in every chip technology, which is why real chips use a reset.

Synthesis with Yosys 0.40 for an iCE40 target, using the synth_ice40 command, prints a statistics report:

Shell
yosys -p "read_verilog blink.v; synth_ice40 -top blink; stat"
Text
=== blink ===

   Number of wires:                 51
   Number of wire bits:             99
   Number of public wires:           3
   Number of public wire bits:      27
   Number of memories:               0
   Number of memory bits:            0
   Number of processes:              0
   Number of cells:                 31
     SB_CARRY                       23
     SB_DFF                         24
     SB_LUT4                        25

Exact counts differ with the tool version and options, and these are shown only to illustrate the report's shape. The cell names tell you how the design maps to iCE40 hardware: SB_DFF is the flip-flop, SB_LUT4 a four-input lookup table and SB_CARRY the fast carry chain that makes the incrementer cheap. A 24-bit counter costs 24 flip-flops, and that is the whole cost of the timing feature. The next-cluster posts take this report through place and route to a bitstream.

Habits that keep designs correct

Firmware engineers pick these up faster when they are written as plain rules.

  1. One clock, one edge. Start with every flip-flop on posedge clk of a single clock. Multiple clocks add problems that deserve their own treatment.

  2. **Use <= for state, = for combinational logic.** Never mix them in one block.

  3. Assign every output on every path. Default assignments at the top of a combinational block, and a default: branch in every case.

  4. Declare widths on literals. 8'd0, not 0.

  5. Register your outputs. An output that comes straight from a flip-flop is easier to time than one that passes through a tree of logic.

  6. Reset what must be known. Control state needs a reset. Large data memories do not.

  7. Name every port in instances. .clk(clk), never positional.

  8. Keep simulation-only code out of design files. Put $display, # delays and initial stimulus into testbenches.

Reading warnings

Both Icarus Verilog and Yosys print warnings that matter. Yosys reports an inferred latch with a message such as Latch inferred for signal followed by the signal name. Treat that as an error unless you wanted storage. A port width mismatch reports as Port ... expects N bits, got M. Do not suppress these. A design that builds without warnings is the baseline, and everything beyond it is a bonus.

Common firmware-engineer mistakes

The following mistakes come up again and again, and they all come from carrying software expectations into hardware.

**Treating always as a function.** An always block does not run once. It describes hardware that is always present. Writing a long sequence of statements and expecting them to take several clock cycles will give you one cycle of wide logic, or something the tool rejects.

Expecting a variable to hold its value for free. In software a variable keeps its value until you change it. In hardware, a value only persists if you built a flip-flop to hold it. An always @* block that forgets to assign a branch builds a latch, which holds the value in a way the tools consider dubious.

**Using initial for hardware reset.** It works on some FPGAs and not on any ASIC. A reset signal is portable.

Reading an input that comes from outside the clock domain. A button wired straight into a state machine can change at any instant, including during a setup window, and the flip-flop it feeds can go metastable. Inputs from the outside world pass through a two-flip-flop synchroniser first. That topic has its own posts in this cluster.

**Writing if (a = b).** Verilog does not have the C trap, because = inside an if condition is a syntax error. But == against a value containing x yields x, and an if takes the else branch on x. Use === and !== in testbenches to see those.

A complete small design: a UART transmitter

To bring the pieces together, here is a transmitter for 8N1 serial. It takes a byte and a send pulse, shifts out a start bit, eight data bits and a stop bit at a baud rate set by a divider. For a 12 MHz clock and 115,200 baud, the divider is 12,000,000 divided by 115,200, which is 104.17, so the nearest integer 104 gives a rate within about 0.2 percent of the target, well inside the tolerance of an asynchronous receiver.

uart_tx.vverilog
module uart_tx #(
    parameter CLKS_PER_BIT = 104
) (
    input  wire       clk,
    input  wire       rst,
    input  wire       send,
    input  wire [7:0] data,
    output reg        tx,
    output wire       busy
);
    localparam IDLE  = 2'd0;
    localparam START = 2'd1;
    localparam DATA  = 2'd2;
    localparam STOP  = 2'd3;

    reg [1:0]  state;
    reg [6:0]  clk_count;
    reg [2:0]  bit_index;
    reg [7:0]  shifter;

    assign busy = (state != IDLE);

    always @(posedge clk) begin
        if (rst) begin
            state     <= IDLE;
            tx        <= 1'b1;
            clk_count <= 7'd0;
            bit_index <= 3'd0;
        end else begin
            case (state)
                IDLE: begin
                    tx <= 1'b1;
                    clk_count <= 7'd0;
                    bit_index <= 3'd0;
                    if (send) begin
                        shifter <= data;
                        state   <= START;
                    end
                end
                START: begin
                    tx <= 1'b0;
                    if (clk_count == CLKS_PER_BIT - 1) begin
                        clk_count <= 7'd0;
                        state     <= DATA;
                    end else
                        clk_count <= clk_count + 7'd1;
                end
                DATA: begin
                    tx <= shifter[bit_index];
                    if (clk_count == CLKS_PER_BIT - 1) begin
                        clk_count <= 7'd0;
                        if (bit_index == 3'd7)
                            state <= STOP;
                        else
                            bit_index <= bit_index + 3'd1;
                    end else
                        clk_count <= clk_count + 7'd1;
                end
                STOP: begin
                    tx <= 1'b1;
                    if (clk_count == CLKS_PER_BIT - 1) begin
                        clk_count <= 7'd0;
                        state     <= IDLE;
                    end else
                        clk_count <= clk_count + 7'd1;
                end
            endcase
        end
    end
endmodule

The structure is the FSM pattern in one clocked block, with a counter timing each bit. The seven-bit clk_count holds values up to 127, enough for 103. tx idles high, as the serial line standard requires, drops for the start bit, sends the least significant data bit first, and rises for the stop bit. A testbench can send 8'h55 and print the transitions on tx. The pattern 0x55 is 01010101, so the line, least significant bit first, reads start 0, then 1,0,1,0,1,0,1,0, then stop 1.

uart_tx_tb.vverilog
`timescale 1ns/1ps

module uart_tx_tb;
    reg        clk = 1'b0;
    reg        rst = 1'b1;
    reg        send = 1'b0;
    reg  [7:0] data = 8'h55;
    wire       tx;
    wire       busy;
    integer    i;

    uart_tx #(.CLKS_PER_BIT(4)) dut (
        .clk(clk), .rst(rst), .send(send), .data(data), .tx(tx), .busy(busy)
    );

    always #5 clk = ~clk;

    initial begin
        #22 rst = 1'b0;
        @(posedge clk);
        send <= 1'b1;
        @(posedge clk);
        send <= 1'b0;
        for (i = 0; i < 10; i = i + 1) begin
            repeat (4) @(posedge clk);
            #1 $write("%b", tx);
        end
        $write("\n");
        $finish;
    end
endmodule

The testbench shortens CLKS_PER_BIT to 4 so that it simulates quickly, and samples tx once per bit. After the send pulse, the machine spends one cycle moving from IDLE to START. The sampling loop waits four clocks and then reads, so the first sample lands inside the start bit's period, which gives the sequence below.

Text
0101010101

The ten characters are the start bit 0, the eight data bits 1,0,1,0,1,0,1,0 of 0x55 read least significant bit first, and the stop bit 1. The alternating pattern makes the result easy to eyeball, and the fixed CLKS_PER_BIT parameter shows why parameters are worth the typing.

Operators, expressions and the width rules

Verilog operators look like C's, with a few additions that matter in hardware. The bitwise operators &, |, ^ and ~ work bit by bit on vectors. The logical operators &&, || and ! reduce each operand to true or false first. The reduction operators are new to most firmware engineers: a unary &x ANDs every bit of x into one bit, |x ORs them all and ^x XORs them, which gives a parity bit in one expression.

reduce.vverilog
module reduce;
    wire [7:0] v = 8'b1011_0110;
    wire all_ones = &v;
    wire any_one  = |v;
    wire parity   = ^v;

    initial begin
        #1;
        $display("all=%b any=%b parity=%b", all_ones, any_one, parity);
    end
endmodule
Text
all=0 any=1 parity=1

The underscore in 8'b1011_0110 is only for readability. The value has five ones, an odd count, so the XOR reduction is 1.

Shifts are << and >> for logical shifts and <<< and >>> for arithmetic ones. An arithmetic right shift keeps the sign bit only when the operand is declared signed. Equality has two forms for simulation: == returns x if either side contains x or z, while === compares the four-valued bits exactly. Only == is synthesisable.

How wide is an expression?

Expression width is a source of real bugs. Verilog evaluates an expression at the width of its widest operand, including the left-hand side of an assignment. Consider adding two eight-bit values into a nine-bit sum:

addwidth.vverilog
module addwidth;
    reg  [7:0] a = 8'd200;
    reg  [7:0] b = 8'd100;
    wire [7:0] narrow = a + b;
    wire [8:0] wide   = a + b;

    initial begin
        #1;
        $display("narrow=%0d wide=%0d", narrow, wide);
    end
endmodule
Text
narrow=44 wide=300

The sum 300 does not fit in eight bits, so narrow keeps the low eight bits, 300 minus 256, which is 44. Because wide is nine bits, the context widens the addition to nine bits and carries the overflow. This is the hardware equivalent of promoting to uint16_t before adding, except that it happens by context rather than by a cast, so write the target width deliberately.

Signed arithmetic

By default every vector is unsigned. To compare or extend signed numbers correctly, declare them signed and keep all operands in the expression signed, because one unsigned operand makes the whole expression unsigned:

signed_cmp.vverilog
module signed_cmp;
    reg signed [7:0] x = -8'sd3;
    reg signed [7:0] y =  8'sd2;
    reg        [7:0] u =  8'd2;

    initial begin
        #1;
        $display("signed x<y: %b", x < y);
        $display("mixed  x<u: %b", x < u);
    end
endmodule
Text
signed x<y: 1
mixed  x<u: 0

In the mixed comparison, x is treated as unsigned 253, which is larger than 2, so the answer flips. If you have ever debugged a uint8_t against int8_t comparison in C, this is the same mistake, and it is just as silent.

Functions and tasks

Verilog has function for combinational computation and task for sequences that can wait. A function returns one value, takes no time, and is usually the better tool for small combinational pieces such as a parity check or a gray-code conversion:

gray.vverilog
module gray_demo;
    function [3:0] bin_to_gray;
        input [3:0] b;
        begin
            bin_to_gray = b ^ (b >> 1);
        end
    endfunction

    integer i;
    initial begin
        for (i = 0; i < 6; i = i + 1)
            $display("%0d -> %b", i, bin_to_gray(i[3:0]));
    end
endmodule
Text
0 -> 0000
1 -> 0001
2 -> 0011
3 -> 0010
4 -> 0110
5 -> 0111

Each consecutive code differs in exactly one bit, which is why Gray codes are used when a counter value crosses between clock domains. A function called inside a synthesisable block turns into logic, so it is inlined, not called. Tasks that contain delays or waits are for testbenches only.

Clock enables instead of divided clocks

Firmware engineers often want something to happen once a millisecond. The instinct is to build a slower clock with a divider and clock a block with it. In FPGA design that is usually the wrong choice, because a second clock creates a second clock domain and its own routing and timing problems. The better pattern keeps one fast clock and uses an enable pulse that is high for one cycle in every N:

tick.vverilog
module tick #(
    parameter DIV = 12000
) (
    input  wire clk,
    input  wire rst,
    output reg  tick
);
    reg [15:0] cnt;

    always @(posedge clk) begin
        if (rst) begin
            cnt  <= 16'd0;
            tick <= 1'b0;
        end else if (cnt == DIV - 1) begin
            cnt  <= 16'd0;
            tick <= 1'b1;
        end else begin
            cnt  <= cnt + 16'd1;
            tick <= 1'b0;
        end
    end
endmodule

With a 12 MHz clock and DIV of 12000, tick pulses once every 1 ms. Other logic then uses it as an enable inside the same clock domain:

ms_counter.vverilog
module ms_counter (
    input  wire        clk,
    input  wire        rst,
    input  wire        tick,
    output reg  [31:0] millis
);
    always @(posedge clk) begin
        if (rst)
            millis <= 32'd0;
        else if (tick)
            millis <= millis + 32'd1;
    end
endmodule

This is the hardware equivalent of a SysTick interrupt, and the structure maps well onto FPGA flip-flops, which have a built-in enable input, so the if (tick) costs no extra logic.

A memory-mapped register block

A firmware engineer's natural unit is a register map. Hardware that a CPU talks to is usually a small block that decodes an address and exposes a few registers. This example has a control register, a status register and a data register on a simple bus with a write strobe:

regblock.vverilog
module regblock (
    input  wire        clk,
    input  wire        rst,
    input  wire        wr,
    input  wire [1:0]  addr,
    input  wire [31:0] wdata,
    output reg  [31:0] rdata,
    output reg         enable,
    output reg  [7:0]  tx_byte,
    input  wire        busy
);
    localparam CTRL   = 2'd0;
    localparam STATUS = 2'd1;
    localparam DATA   = 2'd2;

    always @(posedge clk) begin
        if (rst) begin
            enable  <= 1'b0;
            tx_byte <= 8'd0;
        end else if (wr) begin
            case (addr)
                CTRL: enable  <= wdata[0];
                DATA: tx_byte <= wdata[7:0];
                default: ;
            endcase
        end
    end

    always @* begin
        case (addr)
            CTRL:    rdata = {31'd0, enable};
            STATUS:  rdata = {31'd0, busy};
            DATA:    rdata = {24'd0, tx_byte};
            default: rdata = 32'd0;
        endcase
    end
endmodule

The write side is clocked and sets state. The read side is combinational and builds the value the CPU sees from the registers and from the live busy input. The STATUS register is read-only because there is no write case for it, which is exactly how hardware read-only status bits work. A C driver for this block would be a pointer to a base address with offsets 0, 4 and 8, and the Verilog decoding here uses word addresses to keep the example short.

Reset styles

A synchronous reset is sampled only on the clock edge, as in every example above. An asynchronous reset acts at once, whatever the clock does:

async_rst.vverilog
module async_rst (
    input  wire clk,
    input  wire rst_n,
    input  wire d,
    output reg  q
);
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n)
            q <= 1'b0;
        else
            q <= d;
    end
endmodule

The sensitivity list adds negedge rst_n, and the _n suffix is the convention for an active-low signal. The trade-off is real. A synchronous reset is a normal logic input and is easy to time, but needs a running clock to take effect. An asynchronous reset works without a clock and maps onto the dedicated reset pin that most flip-flops have, but its release must be synchronised to the clock or the flip-flops can leave reset at slightly different times. The FPGA families used later in this cluster handle either style, and the safe default for a first design is the synchronous form.

Reading a waveform

When a design misbehaves, a waveform tells you more than any print statement. Open the .vcd dump in GTKWave, add the signals of interest, and ask three questions in order. Did the clock toggle at the expected period? Was reset released when you intended? What was the first signal to go to x or to differ from your expectation? The first wrong signal is nearly always the cause, and everything after it is a consequence. A habit that saves hours is to dump all signals of the design under test and to name your testbench instance dut so the hierarchy is easy to find.

Verilog next to C: a cheat sheet

In CIn Verilog
uint8_t x;reg [7:0] x; or wire [7:0] x;
x = a + b;assign x = a + b; or inside always @*
if (c) x = a; else x = b;assign x = c ? a : b;
x++ in a loopx <= x + 1; on every clock edge
switch (s)case (s) with a default
#define WIDTH 8parameter WIDTH = 8 or localparam
printf$display, simulation only
main()initial in a testbench, simulation only
A function callA module instance, or a function for pure logic
while (!ready) ;A state in a state machine, or a counter and a comparator

The last row is the one that matters. A software wait is a loop that burns instruction slots. A hardware wait is a state that does nothing for a number of cycles, and costs a state register and a comparator while everything else keeps running.

How the simulator schedules events

Understanding the simulator's scheduling model removes most of the mystery from race conditions. IEEE 1364-2005 divides each simulation time step into regions. In the active region, the simulator evaluates continuous assignments, runs blocking assignments and evaluates the right-hand sides of non-blocking assignments. In the non-blocking assignment region, which comes after the active events have run out, it performs the updates that the <= statements scheduled. Only then does the simulator check whether those updates woke any other blocks, and if so, it runs another round at the same time.

That is the mechanism behind the rule from earlier. At a rising clock edge, every always @(posedge clk) block wakes in the active region. Each one reads the current values of its inputs and schedules its non-blocking updates. None of the updates land until all of the blocks have read. So every flip-flop sees the values from before the edge, exactly as real flip-flops do, because real hardware has a small hold time during which the old value is still available. If a flip-flop were written with a blocking assignment, the update would land immediately, in the middle of the active region, and a second block that happened to run later would see the new value. Which block runs first is not defined by the standard, so the result can change between simulators or between versions of the same simulator. A design with that property is said to have a race, and the cure is the non-blocking rule rather than any attempt to control the order.

Testbenches have a similar trap. If a testbench drives an input with a blocking assignment at the same instant as the clock edge, the design may sample the old or the new value depending on scheduling. Driving testbench inputs with non-blocking assignments, or a short time after the clock edge, as in the #1 in the earlier checks, makes the testbench behave like an external device whose output changes slightly after the clock.

A testing strategy that scales

A first testbench prints a number. A good one is small, repeatable and loud when it fails. These habits keep it so:

  1. Test one module at a time. Each module gets a testbench that instantiates it as dut and drives every input. Combine modules only after each works alone.

  2. Test edges, not only the middle. For a counter, test reset, wrap-around and holding the enable low. For a state machine, test every transition and an illegal input. For an arithmetic block, test zero, the maximum value and a carry.

  3. Compare against a model. For anything computed, write the same computation in the testbench with a different method, such as a behavioural expression or a table, and compare each result with !==.

  4. Count failures and report once. Keep an error counter, print PASS or FAIL at the end, and call $finish. That makes it easy to run every testbench from a script and check the exit text.

  5. Dump waveforms only when needed. $dumpvars slows a big simulation and produces a large file, so gate it behind a plusarg when the design grows.

Verilator and Icarus Verilog differ here. Icarus Verilog interprets the design and handles delays and four-valued logic fully. Verilator compiles the design to C++ and runs much faster on large synchronous designs, but treats x as 0 or random and has stricter rules about what it accepts. Both are fine for the examples in this guide, and a later cluster covers Verilator properly.

Constraining a design for a real board

Simulation never needs to know which physical pin carries clk. A real build does. A constraint file connects each top-level port to a pin and states the clock frequency. The format depends on the toolchain. For the iCE40 family and the open toolchain, it is a PCF file where each line reads set_io port pin. For a Xilinx part in Vivado, it is an XDC file. Later posts in this cluster write both. Two things are worth knowing now.

First, the names in the constraint file must match the top module's port names exactly, including case. A mismatch is usually reported as an error that a port has no pin, or as a warning that a constraint matched nothing, and the second case is easy to miss. Second, the clock constraint is not decoration. The place-and-route tool uses it to decide how hard to work and reports whether the design meets the target frequency. A design that works in simulation but fails timing at the stated frequency may work at a lower frequency, behave erratically at the target, or fail only when the chip is warm, so treat a timing failure as a defect.

Debugging a design that does not work

When a design fails on a board, firmware habits help and hardware habits help more. A practical order is:

  1. Confirm the clock is running. Route it, divided down, to an LED or a pin, and check with a scope or by eye.

  2. Confirm reset is released. A design held in reset looks dead. An LED wired to the reset signal settles this in seconds.

  3. Re-run the simulation with the exact top module that was built, including its parameters. The most common cause of "works in simulation only" is that the board build used a different top-level wrapper or parameter value.

  4. Look for latches and width mismatches in the synthesis log, because those are the two warnings that most often precede real faults.

  5. Check pin assignments against the board schematic, since a swapped pin looks like a logic bug.

  6. Add a status signal that proves the design reached a given state, and expose it on a spare LED.

An FPGA cannot be stepped through with a breakpoint. What replaces a debugger is a mix of simulation, waveforms and a few well-chosen visible signals, and the discipline of writing designs small enough to understand.

Where Verilog stops being enough

Verilog-2005 is deliberately small, and some of its pain is the reason SystemVerilog exists. There is no logic type that unifies wire and reg. There is no always_ff or always_comb that tells the tool what you intended. There are no real enumerations for states and no interfaces to bundle bus signals. Many teams therefore write synthesisable code in a SystemVerilog subset, and the open toolchains read most of it. The next rung of this cluster covers always_ff, always_comb and logic. VHDL is the other mainstream language, stricter and more verbose, and a later post compares the three.

This guide's advice does not fit every situation. If you only need a soft processor with software on top, you may spend your time in C and treat the hardware as a library. If your target is an ASIC, resets, clock gating and test insertion add rules beyond what is here. If you need high-level synthesis from C or from a Python description, other tools exist and a later cluster covers some of them.

What to learn next

A sensible path through the Hardware cluster, once this guide is behind you:

  1. Write the blinking LED module and build it for a real board.

  2. Study blocking and non-blocking assignments until the rule feels natural.

  3. Write a state machine the synthesisable way.

  4. Learn the SystemVerilog subset: always_ff, always_comb, logic.

  5. Meet clock-domain crossing: the two-flop synchroniser, then an asynchronous FIFO.

  6. Infer block RAM and parameterise with generate.

  7. Study metastability and assertions at expert depth.

Each step is a short post, and each builds on the vocabulary in this one.

Reference sources

For exact semantics, the primary source is IEEE Std 1364-2005, the Verilog language standard, which defines the scheduling model that makes non-blocking assignment work. The Icarus Verilog documentation lists the flags used here, including -g2005. The Yosys manual documents read_verilog, synth_ice40 and stat. The IEEE 1800-2017 standard defines SystemVerilog, which is a superset of Verilog-2005.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.