Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 57 ยท Memory and Programmable Logic

Hardware Description Languages (Verilog and VHDL)

Learn what a hardware description language is. Read Verilog modules, assign statements, always blocks and testbenches, and see each one modeled in Python.

So far you have drawn circuits with gates and wires. That works for a full adder, but nobody draws a modern processor with a pencil: it has billions of transistors. Engineers describe hardware in text instead, using a hardware description language, or HDL. The two big ones are Verilog (and its newer form SystemVerilog) and VHDL.

An HDL looks like a programming language, but it is not one. A program says "do this, then that". An HDL says "this is what exists, and how the parts are wired". Every statement describes a piece of hardware that is always there and always working, all at the same time. This lesson shows the four building blocks you will meet first (modules, assign, always blocks and testbenches), explains the difference between simulating and synthesizing a design, and maps each Verilog idea to a small Python model you can run here.

The site cannot run Verilog or VHDL, so the HDL snippets below are read-only. Every idea is paired with a runnable Python model that behaves the same way. The Python is a teaching stand-in, not a real simulator.

Describing hardware, not running a program

Imagine a circuit with two AND gates feeding an OR gate. In a normal language, the order of statements matters: line 2 runs after line 1. In hardware, all three gates exist at once and react to their inputs continuously. If an input changes, the effect ripples through the wires.

HDL versus a normal program

Structure Statements describe parts and wires.
Parallel Everything works at the same time.
Signals Values flow along wires, not through variables.

Think "circuit diagram in text", not "list of steps".

1 / 2

Verilog has been popular in industry since the 1980s and is compact and C-like. VHDL grew out of a US defense program, is stricter and more verbose, and is common in Europe and in aerospace. Both can describe exactly the same circuits. This lesson uses Verilog because it is shorter.

Modules: the unit of hardware

A module is a box with named ports. It is the HDL version of a chip or a subcircuit. Here is a half adder (the sum and carry circuit from Half Adders and Full Adders):

VERILOG
module half_adder (
    input  wire a,
    input  wire b,
    output wire sum,
    output wire carry
);
    assign sum   = a ^ b;
    assign carry = a & b;
endmodule

The pieces:

  • module half_adder (...) names the box and lists its ports.
  • input and output give the direction of each port. wire is a plain connection.
  • assign is a continuous assignment: the output is permanently tied to the expression on the right. It is not executed once. It is a wire with logic in front of it.
  • endmodule closes the box.

The operators are the same ones you know from bit manipulation: & is AND, | is OR, ^ is XOR and ~ is NOT.

The closest Python equivalent is a function from input values to output values. Calling it again with new inputs corresponds to the hardware "reacting" to a change.

Python A module as a Python function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The full_adder function builds a bigger circuit out of smaller ones. In Verilog you do the same by instantiating modules inside other modules:

VERILOG
module full_adder (
    input  wire a, b, cin,
    output wire sum, cout
);
    wire s1, c1, c2;
    half_adder ha1 (.a(a),  .b(b),   .sum(s1),  .carry(c1));
    half_adder ha2 (.a(s1), .b(cin), .sum(sum), .carry(c2));
    assign cout = c1 | c2;
endmodule

Each instance (ha1, ha2) is a separate copy of the half adder, with the ports connected by name. That is structural description: you describe how parts are wired. When you write expressions with assign instead, you are using a dataflow style. Both produce hardware.

assign for combinational logic

Anything that is a pure function of the current inputs (a mux, a decoder, an adder) can be written with assign. The conditional operator ? : is the HDL way to write a multiplexer:

VERILOG
module mux2 (
    input  wire [3:0] d0, d1,
    input  wire       sel,
    output wire [3:0] y
);
    assign y = sel ? d1 : d0;
endmodule

The notation [3:0] declares a 4-bit bus: bit 3 is the most significant bit and bit 0 the least. A Python integer masked to four bits plays the same role.

Python Buses, masks and a 2:1 multiplexer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Slicing and concatenation are everywhere in HDL code. x[7:4] picks four bits and {a, b} glues buses together, with no cost in hardware: they are just different groups of wires.

always blocks: logic with memory

Some circuits remember. For those, Verilog uses an always block with a sensitivity list that says when the block "wakes up".

VERILOG
module counter4 (
    input  wire       clk,
    input  wire       reset,
    output reg  [3:0] count
);
    always @(posedge clk) begin
        if (reset)
            count <= 4'b0000;
        else
            count <= count + 1;
    end
endmodule

Read it as: "on every rising edge of clk, update count". The synthesis tool turns this into four flip-flops and an incrementer. Two details matter:

  • reg marks a signal that is assigned inside an always block. It does not always mean a physical register. It depends on the block.
  • <= is a non-blocking assignment. All the right-hand sides are evaluated first, using the values from before the clock edge, and then all the left-hand sides are updated together. That is how flip-flops behave: they all sample at the same instant.

For combinational logic you write always @(*) and use the blocking =. The rule of thumb for beginners: <= in clocked blocks, = in combinational blocks.

Python Non-blocking assignment: swap with two registers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With <= the two registers swap on every edge, exactly like two flip-flops wired crosswise. With blocking = in a clocked block the second line sees the new value of a, so the values collapse into one. That is a classic beginner bug.

Here is the 4-bit counter as a Python class, with a synchronous reset and a 4-bit wrap-around:

Python The 4-bit counter always block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The count reaches f (15) and wraps back to 0, just as four flip-flops do. A reset on any edge forces the count to zero on that same edge. That is what synchronous reset means.

Verilog data types and four-valued logic

Before modeling latches and flip-flops, two details of the language's type system matter, because they explain the reg and x you keep seeing.

wire and reg. A wire is a connection. It has no memory and must be driven by an assign, by a module output, or by a gate. A reg is a variable that keeps its value until it is assigned again, and it is the only type you may assign inside an always or initial block. A reg is not automatically a flip-flop: in an always @(*) block it becomes plain combinational logic, and in always @(posedge clk) it becomes flip-flops. (SystemVerilog renames the common case to logic, which can be used for both.) Other types you will meet are integer (a 32-bit variable for loops and testbenches), parameter (a named constant, such as a bus width), and vectors declared as reg [7:0] data;, with literals like 4'b1010 (4 bits, binary) or 8'hFF (8 bits, hexadecimal).

Four values. A Verilog signal is not just 0 or 1. It can be:

Value Meaning
0 logic low
1 logic high
x unknown: uninitialized, or conflicting drivers
z high impedance: nothing is driving the wire (the output of a disabled tri-state buffer)

Every reg starts out as x in simulation until the first assignment, which is why the waveform of a freshly started design is red or blank. The operators handle unknowns in the safest way: 0 & x is 0 (a single 0 decides an AND), but 1 & x is x. When two drivers connect to the same wire, the simulator resolves their values: z yields to the other driver and two different strong values give x.

Python Four-valued logic and wire resolution

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the AND table along the 0 row and column: it is all zeros, because a known 0 makes the result known. The x and z rows give x for everything else. In the last table, the z row and column reproduce the other driver, which is how several tri-state buffers share a bus, and the entries 0 against 1 give x: a bus conflict. When a simulation shows x where you expected a value, it usually points at an input that was never initialized or at two outputs driving the same wire.

HDL models of latches and flip-flops

Memory elements are written as always blocks, and the sensitivity list decides what kind of memory the synthesizer builds.

A D latch is level-sensitive: it follows the data input for as long as the enable is high.

VERILOG
always @(*)
    if (en) q = d;          // no else branch: q must keep its old value, so a latch is built

A D flip-flop wakes up only on a clock edge, and uses the non-blocking assignment:

VERILOG
always @(posedge clk)
    q <= d;

Reset comes in two flavors, which differ in one word of the sensitivity list:

VERILOG
// synchronous reset: only looked at on a clock edge
always @(posedge clk)
    if (rst) q <= 1'b0;
    else     q <= d;

// asynchronous reset: acts at once, whatever the clock does
always @(posedge clk or posedge rst)
    if (rst) q <= 1'b0;
    else     q <= d;

The JK and T flip-flops of the flip-flop lesson follow the same pattern, with a case on the control inputs:

VERILOG
always @(posedge clk)
    case ({j, k})
        2'b00: q <= q;          // hold
        2'b01: q <= 1'b0;       // reset
        2'b10: q <= 1'b1;       // set
        2'b11: q <= ~q;         // toggle
    endcase

always @(posedge clk)           // T flip-flop
    if (t) q <= ~q;

The next program models four of these in Python, each class with the matching Verilog as its docstring, and drives them with the same sequence of inputs. The model keeps the x that every reg starts with.

Python Latch, flip-flop, synchronous and asynchronous reset

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Follow the columns down. At step 2 the data input falls while the clock is still high: the latch follows it (0), while the three flip-flops keep the 1 they sampled at the edge. At step 4 the reset goes high between clock edges: only the asynchronous version reacts (0); the synchronous one waits for the edge at step 5, and the plain flip-flop has no reset at all, so it only takes d at the edge (which happens to be 0 here). Then from step 7 on, reset is off again, and all three flip-flops capture 1 at the rising edge. Before the first edge, every model still shows x: unlike a real chip, a simulated register has no value until you give it one, which is why designs include a reset.

Two practical rules follow. Use non-blocking assignments (<=) for everything clocked. And never leave a branch of a combinational always @(*) block unassigned, or the tool will quietly insert a latch, as the first Verilog snippet shows on purpose.

Testbenches: checking a design

How do you know a design works? You write a testbench: a module with no ports that creates the design under test, drives its inputs and checks its outputs. Testbenches are never turned into hardware. They only run in a simulator.

VERILOG
module tb_half_adder;
    reg  a, b;
    wire sum, carry;
    half_adder dut (.a(a), .b(b), .sum(sum), .carry(carry));

    integer i;
    initial begin
        for (i = 0; i < 4; i = i + 1) begin
            {a, b} = i;
            #10;                        // wait 10 time units
            if (sum !== (a ^ b) || carry !== (a & b))
                $display("FAIL a=%b b=%b", a, b);
        end
        $display("done");
        $finish;
    end
endmodule

initial runs once at the start of the simulation. #10 advances simulated time. $display prints, and !== compares including unknown (x) values. The structure is always the same: drive inputs, wait, compare to what you expected.

A Python testbench follows the same pattern, and for small designs you can test every input combination:

Python A self-checking testbench

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The testbench compares the design against a reference model written a different way (here, ordinary integer addition). That is the main trick of hardware verification: two independent descriptions of the same behavior must agree.

Simulation versus synthesis

The same HDL file can be used two ways, and they are not equivalent:

  • Simulation runs the code in software with a notion of time. Anything goes: initial blocks, delays like #10, printing, files. It is how you debug.
  • Synthesis converts the code into a netlist of gates, flip-flops and, on an FPGA, lookup tables like those in PLAs, FPGAs and Lookup Tables. Only a synthesizable subset of the language is allowed. Delays are ignored, and initial blocks are mostly for simulation.

A design can simulate perfectly and still synthesize into the wrong hardware. The usual culprits: forgetting a branch in a combinational always @(*) block (the tool must add a latch to remember the old value), mixing <= and = carelessly, or relying on delays. If your combinational code does not assign an output in every case, you have described memory by accident.

Modelling styles and SystemVerilog

A Verilog module can describe the same circuit at four levels of detail:

  • Gate level: instantiate primitives such as and g1 (y, a, b);. Closest to the schematic.
  • Structural: instantiate your own modules and wire them, like the two half adders above.
  • Dataflow: continuous assign statements describe how outputs depend on inputs.
  • Behavioral: always blocks with if, case and loops describe what the circuit does, and the synthesis tool decides the gates. It is the most compact and the most common for state machines and datapaths.

Behavioral code is easy to write badly: a combinational always block that does not assign its output in every branch silently creates a latch. Default assignments at the top of the block prevent it.

SystemVerilog (IEEE 1800) is a superset of Verilog: all Verilog code still works. It adds two groups of features.

For design: logic (one type instead of wire and reg), always_comb, always_ff and always_latch (blocks that state their intent, so the tool warns when the code does not match), enum types for state names, struct and packed arrays, interface bundles for groups of wires, and package for shared definitions.

For verification: classes, randomized stimulus, assertions (assert property), functional coverage and the UVM methodology used on large chips.

VERILOG
module counter (input logic clk, rst, output logic [3:0] q);
  always_ff @(posedge clk) begin
    if (rst) q <= 4'd0;
    else     q <= q + 4'd1;
  end
endmodule

Verilog's advantages are that it is small and quick to learn, supported by every tool, and enough for most synthesizable designs; its disadvantages are weak typing, easy accidental latches and few verification features. SystemVerilog's advantages are safer code, richer data types and powerful verification; its disadvantages are a much larger language, uneven tool support for the newest features and more to learn.

VHDL in one glance

VHDL splits a module into an entity (the ports) and an architecture (the contents). The same half adder:

VHDL
entity half_adder is
    port (a, b : in  std_logic;
          sum, carry : out std_logic);
end entity;

architecture rtl of half_adder is
begin
    sum   <= a xor b;
    carry <= a and b;
end architecture;

Concurrent assignments with <= here play the same role as assign in Verilog. Clocked logic goes in a process (clk) block. VHDL is strongly typed, so mixing a bit with a number needs an explicit conversion, which prevents some mistakes at the price of more typing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does assign y = a & b; describe in Verilog?

    A continuous assignment is a wire with logic in front of it. y follows a & b at all times, like a gate.
  2. 2. In a clocked always block, why use <= instead of =?

    Non-blocking assignment samples every right-hand side before any register changes, so two registers can swap values just as flip-flops do on one clock edge.
  3. 3. What is a testbench?

    A testbench exists only for simulation. It instantiates the design under test, applies stimulus and compares results against expectations.
  4. 4. A combinational always @(*) block assigns y only inside an if branch, with no else. What can happen when it is synthesized?

    If y is not assigned in every case, the hardware must remember its previous value when the condition is false. That is a latch, usually a bug.

Summary

  • Verilog signals have four values (0, 1, x, z); reg is a variable, not always a register; latches, flip-flops and reset styles are chosen by the sensitivity list of an always block.
  • An HDL describes hardware that exists and works in parallel, instead of a list of steps to run.
  • A module is a box with ports. Modules can be instantiated inside other modules to build bigger circuits.
  • assign and always @(*) describe combinational logic. always @(posedge clk) with <= describes registers.
  • A testbench drives inputs and checks outputs against a reference model, and is used only in simulation.
  • Simulation accepts anything, synthesis accepts only a subset, and a design must work in both.
  • Verilog is compact and C-like, VHDL is strict and verbose, and both describe the same circuits.

Next: Designing an ALU.