top of page

Verilog Syntax, Coding Guidelines and Designing a Half Adder

Nov 13
13 min read
Verilog Syntax, Coding Guidelines and Designing a Half Adder
Verilog Syntax, Coding Guidelines and Designing a Half Adder

Verilog becomes much easier to understand when you learn its syntax first and then apply each rule while designing a simple digital circuit. A half adder is an excellent starting point because it demonstrates how to declare a module, define inputs and outputs, use identifiers and keywords, write comments, and implement Boolean logic.


This guide covers the basic Verilog syntax with examples, practical coding guidelines, and a complete half adder design with a testbench. The final design brings these concepts together so you can follow the same procedure when writing Verilog for other combinational circuits.



Table of Contents



1. Introduction to Verilog HDL


Verilog HDL (Hardware Description Language) is used to describe the structure and behavior of digital electronic circuits. It allows designers to represent hardware such as logic gates, adders, multiplexers, counters, and registers.


Unlike a conventional programming language, Verilog describes hardware that can operate concurrently. For example, an XOR gate and an AND gate in a half adder can process the same two inputs at the same time.


A Verilog design generally involves three stages:

  • Design: Describe the hardware functionality using Verilog code.

  • Verification: Write a testbench to apply input combinations and check the outputs.

  • Simulation: Run the design and testbench to verify the expected behavior.


Before designing a circuit, it is useful to understand the language elements that make up a Verilog program.



2. Verilog Identifiers


An identifier is a name given to an element in a Verilog design. Identifiers help us refer to modules, signals, variables, parameters, and other design elements.


For example:

module half_adder;
    input a;
    input b;
    output sum;
    output carry;
endmodule

Here, half_adder, a, b, sum, and carry are identifiers.


Rules for writing identifiers

  1. An identifier can contain letters, digits, underscores (_), and dollar signs ($).

  2. It must not begin with a digit.

  3. Verilog identifiers are case-sensitive.

  4. An identifier must not be a reserved Verilog keyword.

  5. Meaningful names make the design easier to read and maintain.


Examples

Identifier

Validity

Reason

half_adder

Valid

Uses letters and an underscore

sum1

Valid

Contains letters and a digit

carry_out

Valid

Descriptive name

1sum

Invalid

Begins with a digit

module

Invalid

Reserved keyword

Sum and sum

Both valid

Different identifiers because Verilog is case-sensitive

For example, if a signal is declared as sum, referring to it later as Sum does not refer to the same signal.



3. Verilog Keywords


Keywords are reserved words that have predefined meanings in Verilog. They define the structure of a design, declare signals, control procedural execution, and describe hardware behavior.


Some commonly used keywords are:

Keyword

Purpose

module

Begins a module declaration

endmodule

Ends a module declaration

input

Declares an input port

output

Declares an output port

wire

Declares a net

reg

Declares a variable that can hold a value in procedural code

assign

Specifies a continuous assignment

always

Defines a procedural block

begin

Begins a group of procedural statements

end

Ends a group of procedural statements

parameter

Defines a named constant

initial

Defines a procedural block that starts at simulation time zero


Example of keywords in a module

module logic_example (
    input a,
    input b,
    output sum
);

    assign sum = a ^ b;

endmodule

In this example:

  • module starts the module.

  • input declares the input ports.

  • output declares the output port.

  • assign continuously drives the output with the XOR of the inputs.

  • endmodule closes the module.


The names logic_example, a, b, and sum are identifiers, not keywords.



4. Verilog Comments


Comments explain the purpose of code and make a design easier to understand. The Verilog compiler or simulator ignores comments when interpreting the design.

Verilog supports two types of comments.


4.1 Single-line comments

A single-line comment begins with //. Everything after these symbols on the same line is treated as a comment.

// This module performs XOR operation
module xor_gate (
    input a,
    input b,
    output sum
);

    assign sum = a ^ b; // XOR operation

endmodule

Here, both the introductory comment and the inline comment explain the operation without affecting the circuit.


4.2 Multi-line comments

Multi-line comments begin with /* and end with */. They are useful for describing a design in greater detail.

/*
    Module Name: AND Gate
    Function: Produces 1 when both inputs are 1
*/

module and_gate (
    input a,
    input b,
    output y
);

    assign y = a & b;

endmodule

Coding tip: Use comments to explain the purpose of a module or a non-obvious operation. Avoid commenting every line when the code is already self-explanatory.



5. Module Declaration and Verilog Modules


A module is the basic building block of a Verilog design. It describes a hardware component and defines its interface through input and output ports.


A module can represent a simple logic gate, a half adder, a flip-flop, or a larger digital system made from smaller modules.


5.1 General module syntax

A commonly used Verilog-2001 module declaration follows this structure:

module module_name (
    input  signal_a,
    input  signal_b,
    output signal_y
);

    // Hardware description

endmodule

The important parts are:

  • module: Starts the declaration.

  • module_name: Identifier for the hardware block.

  • Port list: Defines the external input and output signals.

  • Semicolon (;): Terminates the module header.

  • Hardware description: Contains assignments, declarations, or other modules.

  • endmodule: Marks the end of the module.


5.2 Example of a complete Verilog module

Consider an AND gate with two inputs and one output.

module and_gate (
    input a,
    input b,
    output y
);

    assign y = a & b;

endmodule

The expression a & b performs a bitwise AND operation. The continuous assignment updates y whenever an input change affects the expression.


For a single-bit AND gate, the output is 1 only when both inputs are 1.


5.3 Understanding inputs, outputs, and internal signals

A module's ports define how it communicates with other hardware blocks.

Declaration

Meaning

Example

input

Receives a signal

input a

output

Sends a signal outside the module

output sum

wire

Represents a net used to connect signals

wire temp

reg

Holds a procedural variable value

reg result

In traditional Verilog, reg does not automatically mean a physical register or flip-flop. The hardware inferred depends on how the variable is used.


For example:

module example (
    input a,
    input b,
    output y
);

    wire temp;

    assign temp = a & b;
    assign y = temp;

endmodule

Here, temp is an internal net. It connects the AND expression to the output assignment. No flip-flop is required because the circuit is purely combinational.



6. Verilog Coding Guidelines with Examples


Good coding practices make Verilog designs easier to read, simulate, debug, and maintain. Consistent syntax also helps prevent common errors when a design becomes more complex.


Guideline 1: Use meaningful identifiers

Choose names that explain what a signal represents.

Poor naming:

module ha (input x, input y, output z);
    assign z = x ^ y;
endmodule

Improved naming:

module half_adder (
    input a,
    input b,
    output sum
);

    assign sum = a ^ b;

endmodule

The second example makes the purpose of the output clear. In a complete half adder, you would also declare and implement the carry output.


Guideline 2: Follow consistent indentation

Indent the module contents and align related declarations.

Poor formatting:

module and_gate(input a,input b,output y);
assign y=a&b;
endmodule

Improved formatting:

module and_gate (
    input a,
    input b,
    output y
);

    assign y = a & b;

endmodule

Both versions describe the same hardware, but the second is easier to read and modify.


Guideline 3: Use the correct operators

Verilog provides operators for bitwise logic, arithmetic, comparison, and other operations.

Operator

Operation

Example

&

Bitwise AND

y = a & b

\|

Bitwise OR

y = a \| b

^

Bitwise XOR

sum = a ^ b

~

Bitwise NOT

y = ~a

+

Addition

y = a + b

==

Equality comparison

if (a == b)

=

Procedural assignment

result = a

<=

Nonblocking assignment in procedural code

q <= d

The meaning of an operator depends on its context. For example, <= is a nonblocking assignment inside a procedural block, but it also serves as a less-than-or-equal comparison operator in expressions.


Guideline 4: Use assign for continuous combinational logic

Use a continuous assignment when an output or internal net is defined directly by a Boolean expression.

module or_gate (
    input a,
    input b,
    output y
);

    assign y = a | b;

endmodule

The output continuously reflects the OR operation on the inputs. This is appropriate for simple combinational logic.


Guideline 5: Match declarations to the intended logic

For traditional Verilog, continuous assignments drive nets such as wire, while procedural assignments inside always or initial blocks use variables such as reg.


Correct example:

module inverter (
    input a,
    output y
);

    assign y = ~a;

endmodule

A common mistake is to declare an output as a reg and then try to drive it using a continuous assign in traditional Verilog. Choose the declaration according to the assignment style.


Guideline 6: Terminate statements correctly

Most Verilog declarations and statements end with a semicolon. A module ends with endmodule, which does not require a semicolon.


Correct:

wire temp;
assign temp = a & b;

Incorrect:

wire temp
assign temp = a & b

Missing semicolons can cause syntax errors during compilation.


Guideline 7: Use comments and consistent capitalization

Comments should clarify the design's purpose. Use a consistent naming convention for modules, inputs, outputs, and internal signals.

// Calculate the sum of two one-bit inputs
assign sum = a ^ b;

This is more informative than a comment that merely says // assign sum.


Guideline 8: Verify every input combination

For small combinational circuits, test all possible input combinations. A circuit with two one-bit inputs has \(2^2 = 4\) possible input combinations.

For larger designs, use an appropriate testbench, assertions, and additional directed or randomized tests as needed.



7. Understanding the Half Adder


A half adder is a combinational digital circuit that adds two single-bit binary inputs, \(A\) and \(B\). It produces two outputs: Sum and Carry.


The Sum output represents the least significant bit of the addition, while the Carry output represents the bit carried into the next binary position.


7.1 Boolean expressions

The half adder uses two basic logic operations:


Boolean expressions
Boolean expressions

7.2 Half adder truth table

Input A

Input B

Sum

Carry

0

0

0

0

0

1

1

0

1

0

1

0

1

1

0

1

The truth table provides the expected output for every possible input combination. It will also serve as the reference when verifying the Verilog implementation.



8. Designing a Half Adder in Verilog


Now let's apply the syntax and coding guidelines to a complete half adder design.


Step 1: Understand the specification

Before writing the code, identify the inputs, outputs, and required behavior.

  • Inputs: a and b

  • Outputs: sum and carry

  • Sum logic: XOR operation

  • Carry logic: AND operation

  • Circuit type: Combinational


Step 2: Write the module declaration

Start by declaring the module and its ports.

module half_adder (
    input a,
    input b,
    output sum,
    output carry
);

endmodule

Syntax applied:

  • module and endmodule define the hardware block.

  • half_adder, a, b, sum, and carry are identifiers.

  • input and output are keywords.

  • Parentheses group the port declarations.

  • Commas separate the ports.

  • The semicolon terminates the module header.


At this stage, the interface is defined, but the actual logic has not yet been described.


Step 3: Implement the Boolean expressions

Add the continuous assignments inside the module.

assign sum   = a ^ b;
assign carry = a & b;

Here, assign is a keyword used for continuous assignment, ^ is the XOR operator, and & is the bitwise AND operator.


Because both expressions are combinational, the outputs respond to changes in the inputs without requiring a clock.


Step 4: Add comments and formatting

Comments explain the purpose of the module and each output. Indentation and aligned assignments improve readability.


Step 5: Complete the design

The following is the complete synthesizable Verilog design. Save it as half_adder.v.


/*
    Module Name: half_adder
    Function: Adds two 1-bit binary inputs
    Outputs: Sum and Carry
*/

module half_adder (
    input a,
    input b,
    output sum,
    output carry
);

    // Generate Sum using XOR logic
    assign sum = a ^ b;

    // Generate Carry using AND logic
    assign carry = a & b;

endmodule

How the syntax and guidelines are applied

Verilog element

Application in the design

Identifiers

half_adder, a, b, sum, carry

Keywords

module, input, output, assign, endmodule

Comments

Explain the module and Boolean expressions

Module declaration

Defines the half adder interface

Continuous assignment

Describes the Sum and Carry logic

Operators

^ for XOR and & for AND

Naming convention

Descriptive module and output names

Formatting

Consistent indentation and aligned statements

Semicolons

Terminate the header and assignment statements

Notice that the code does not use always, initial, or a clock. None is required for this simple combinational design.



9. Writing a Half Adder Testbench


A design describes the hardware, while a testbench applies inputs and checks whether the outputs behave as expected.


For a two-input half adder, all four input combinations must be tested. The testbench below uses a procedural initial block to apply the inputs and compare the outputs against their expected values.


Save this code as half_adder_tb.v.


`timescale 1ns/1ps

module half_adder_tb;

    // Testbench input signals
    reg a;
    reg b;

    // Signals connected to the design outputs
    wire sum;
    wire carry;

    // Instantiate the half adder
    half_adder uut (
        .a(a),
        .b(b),
        .sum(sum),
        .carry(carry)
    );

    initial begin
        // Test 1: 0 + 0
        a = 0; b = 0;
        #10;
        if (sum !== 0 || carry !== 0)
            $display("FAIL: A=0, B=0");
        else
            $display("PASS: A=0, B=0");

        // Test 2: 0 + 1
        a = 0; b = 1;
        #10;
        if (sum !== 1 || carry !== 0)
            $display("FAIL: A=0, B=1");
        else
            $display("PASS: A=0, B=1");

        // Test 3: 1 + 0
        a = 1; b = 0;
        #10;
        if (sum !== 1 || carry !== 0)
            $display("FAIL: A=1, B=0");
        else
            $display("PASS: A=1, B=0");

        // Test 4: 1 + 1
        a = 1; b = 1;
        #10;
        if (sum !== 0 || carry !== 1)
            $display("FAIL: A=1, B=1");
        else
            $display("PASS: A=1, B=1");

        $finish;
    end

endmodule

Understanding the testbench syntax

  • `timescale 1ns/1ps sets the simulation time unit and precision for this file.

  • reg a and reg b allow the testbench to assign values to the input variables procedurally.

  • wire sum and wire carry receive the outputs driven by the design.

  • half_adder uut (...) instantiates the design under test. Here, uut is the instance identifier.

  • .a(a) and the other named connections associate the testbench signals with the corresponding module ports.

  • initial begin ... end runs the test sequence once at the beginning of simulation.

  • #10 waits 10 nanoseconds before checking the result.

  • !== compares values case-inequality style, including unknown (x) and high-impedance (z) states.

  • $display prints the test result, and $finish ends the simulation.


The reg declarations in this testbench do not mean that the half adder itself contains physical registers. They are used to drive test inputs in simulation.



10. Simulation and Verification


EDA Playground is an online platform that lets you write, compile, and simulate Verilog code directly in your browser. You do not need to install a simulator on your computer.


Step 1: Open EDA Playground

Visit EDA Playground and open a new playground. Select Verilog as the design language and choose a compatible simulator from the available options.


Step 2: Enter the Verilog design and testbench

Copy the half adder design into the Design editor and the testbench into the Testbench editor.

  • Design: half_adder.v

  • Testbench: half_adder_tb.v


EDA Playground provides separate editor areas, so you can enter both codes without creating files on your computer.


Step 3: Select the language and simulator

In the settings panel:

  • Set the design language and testbench language to Verilog.

  • Choose a compatible simulator from the Tools & Simulators menu.


The available simulators may depend on your account and access settings.


Step 4: Run the simulation

Click the Run button. EDA Playground will compile and execute the design and testbench, then display the simulation output in the results pane.


Step 5: Check the simulation results

If you use the testbench provided above, the expected output is:

PASS: A=0, B=0
PASS: A=0, B=1
PASS: A=1, B=0
PASS: A=1, B=1

These results indicate that the half adder produces the expected Sum and Carry values for all four input combinations.


Step 6: View the waveforms (Optional)

To inspect how the inputs and outputs change over time, enable Open EPWave after run before running the simulation. If your selected simulator supports this option, EDA Playground can open the EPWave waveform viewer after execution.


In the waveform viewer, examine the signals a, b, sum, and carry to confirm that the outputs match the truth table.


Verification tip: A successful simulation confirms the expected behavior for the test cases you ran. For this half adder, all four input combinations should pass.



11. Common Mistakes to Avoid


When writing Verilog code, small syntax errors or incorrect logic operators can lead to compilation errors or unexpected simulation results. The following are some common mistakes to watch out for when designing a half adder.


1. Incorrect capitalization of identifiers

Verilog is case-sensitive, so Sum and sum are treated as different identifiers.

Avoid this: Use consistent signal names throughout the design.


2. Missing semicolons

Most Verilog declarations and statements must end with a semicolon. Forgetting one can cause compilation errors.

Incorrect:

assign sum = a ^ b

Correct:

assign sum = a ^ b;

3. Using the wrong logic operator

The Sum output requires XOR (^), while the Carry output requires AND (&).

Incorrect:

assign sum = a | b;

Correct:

assign sum = a ^ b;
assign carry = a & b;

4. Omitting port declarations

Every required input and output should be declared in the module interface. For a half adder, these are a, b, sum, and carry.


5. Using the wrong module name during instantiation

The module name used in the design must match the name referenced when instantiating it in the testbench. Otherwise, the simulator may report that the module cannot be found.


6. Testing only one input combination

A half adder has four possible input combinations. Test all four to verify that both Sum and Carry behave correctly.


7. Using assignment styles incorrectly

In traditional Verilog, continuous assignments using assign drive nets such as wire, while procedural assignments inside always or initial blocks operate on variables such as reg.


Choose the appropriate declaration and assignment style for the intended design.


Final verification tip: Pay special attention to the 1 + 1 case. The expected outputs are sum = 0 and carry = 1. If either output is incorrect, check the Boolean expressions, port connections, and testbench before proceeding.



12. Conclusion


Understanding Verilog syntax is the foundation for writing reliable RTL designs. Identifiers name signals and modules, keywords define language constructs, comments explain the code, and module declarations establish the hardware interface. Consistent naming, indentation, correct operators, and proper signal declarations make designs easier to understand and debug.


The half adder brings these concepts together in a practical example. Its XOR-based Sum and AND-based Carry outputs demonstrate how Boolean expressions become Verilog assignments. By writing a testbench and checking all four input combinations, you also learn the basic verification process.


Once this workflow becomes familiar, you can apply it to other combinational circuits, such as half subtractors, full adders, multiplexers, and decoders, before moving on to sequential designs such as flip-flops and counters.



Frequently Asked Questions (FAQs)


1. What is an identifier in Verilog?

An identifier is a name assigned to a module, signal, variable, or other design element. For example, half_adder, sum, and carry are identifiers.


2. What is the difference between a keyword and an identifier?

A keyword has a predefined meaning in Verilog, such as module or assign. An identifier is a user-defined name, such as sum or half_adder.


3. What is the purpose of endmodule?

endmodule marks the end of a Verilog module declaration.


4. Why is assign used in the half adder?

assign continuously drives the Sum and Carry nets according to their Boolean expressions.


5. Why do we need a testbench?

A testbench applies input values to a design and checks whether its outputs match the expected results.


6. Is a half adder a sequential circuit?

No. A half adder is a combinational circuit because its outputs depend on the current inputs, not on a clock or stored state.

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page