Verilog HDL Principles, Syntax, and Digital Circuit Design
Overview of Hardware Description Languages and Design Flow
Definition and Origins of Verilog HDL:
Verilog is a standardized hardware description language (HDL) utilized to model, simulate, and verify digital systems and electronic circuits through code.
It was originated and developed by Gateway Design Automation in the mid-1980s.
Cadence Design Systems acquired Gateway Design Automation and subsequently transferred the language specification to Open Verilog International (OVI), placing it in the public domain and leading to IEEE standardization.
The language serves dual primary design roles: simulation-based design verification and synthesis-based physical design for Application-Specific Integrated Circuits (ASICs) as well as Field-Programmable Gate Arrays (FPGAs).
Comparison of IEEE Standard HDLs:
VHDL (VHSIC Hardware Description Language): Originating from an initiative sponsored by the United States Department of Defense, developed for Very-High-Speed Integrated Circuits (VHSIC).
Verilog HDL: Originated in the commercial Electronic Design Automation (EDA) sector by Gateway Design Automation/Cadence, known for syntax analogous to the C programming language and widespread industry adoption.
VLSI Design Flow Architecture:

Design Specification: Formal abstract documentation defining performance, functionality, timing constraints, and physical packaging requirements of the electronic circuit.
Behavioral Description: Algorithm-level modeling defining functional behaviors without microarchitectural or timing constraints.
RTL Description (HDL): Register-Transfer Level coding describing the hardware registers, state machines, and data transfers via combinational/sequential logic.
Functional Verification and Testing: Simulation against testbenches ensuring RTL logic strictly matches functional requirements; feeds back directly to the RTL description phase upon detected errors.
Logic Synthesis and Timing Verification: Automated translation of the RTL description into technology-specific target library cells while calculating propagation paths against clock constraints.
Gate-Level Netlist: Logical interconnect graph representing elementary primitive standard cells and their physical pin-to-pin connections.
Logical Verification and Testing: Post-synthesis simulation confirming the gate-level netlist operates correctly and preserved logical equivalence with the RTL source; feeds back to the RTL description phase if functional discrepancies emerge.
Floor Planning and Automatic Place and Route (APR):
Floor Planning: Defining the physical die perimeter, I/O pad placement, internal block allocations, core power meshes, and macro isolation.
Place and Route: Deterministic algorithm placing library cells on rows and routing metal tracks for all interconnect signals; errors at this stage feed back to RTL description.
Physical Layout: Detailed geometrical representation (GDSII/OASIS mask data) containing polygonal representations of physical semiconductor layers.
Layout Verification: Rigorous Design Rule Checking (DRC) for manufacturing constraints, Electrical Rule Checking (ERC), and Layout Versus Schematic (LVS) equivalence matching; discrepancies feed back to the RTL description.
Implementation: Silicon fabrication on semiconductor wafers followed by packaging, lead assembly, physical chip testing, and product delivery.
Verilog Module Concepts, Structure, and Port Interconnection Rules
The Concept of a Module:
The module is the fundamental, indivisible building block in Verilog HDL.
It defines structural boundaries and communicates with external environments via an explicit port interface (input, output, and bidirectional terminals).
Internal architectures, state elements, and algorithmic implementations remain completely encapsulated, enabling modular modifications without altering peripheral circuit interfaces.
Declared with the mandatory keyword
moduleand terminated with the mandatory keywordendmodule.
Structural Syntax of a Module:
Syntax template:
verilog module module_name (port_list); // Declarations: input, output, inout, wire, reg, parameter, integer, etc. // System Modeling: gate-level, dataflow, or behavioral statements endmodule
Internal Components of a Verilog Module:

Module Header: Explicit definition comprising the identifier
module_name,port_list, and optionalparameterdeclarations.Variable Declarations: Specification of internal signals, including
wire,reg, vectors, integers, memories, and arrays.Dataflow Modeling Elements: Concurrent continuous signal driver statements declared via the
assignkeyword.Structural Instantiations: Lower-level module instances and primitive gate invocations.
Behavioral Structured Procedures: Procedural execution blocks declared via
alwaysandinitialkeywords enclosing algorithmic logic.Subroutines: Encapsulated reusable hardware blocks defined through
taskandfunctionconstructs.Closing Statement: The terminal keyword
endmodule.
Levels of Design Abstraction:
Behavioral / Algorithmic Level: Highest design abstraction; models algorithmic signal computation without implementation-specific circuit details. Highly resembles sequential C programming.
Dataflow Level: Models explicit transfers between hardware storage registers by manipulating data streams through expressions, operators, and continuous assignments.
Gate Level: Structural abstraction defining circuit operations using interconnected logic gates (AND, OR, NOT, NAND, NOR, XOR, XNOR) reflecting schematic circuit diagrams.
Switch Level: Lowest abstraction modeling MOS transistors, storage nodes, pass gates, and physical charge transmissions (requires transistor-level switch mechanics).
Port Classifications and Declarations:
Ports represent external pins or physical connectors linking a module to other entities.
Keywords:
input: Input-only terminal delivering external signals inward.output: Output-only terminal broadcasting internal signals outward.inout: Bidirectional terminal supporting bidirectional signal transmission.By default, all declared ports are implicitly typed as continuous physical conductors (
wire).If an output port is required to retain its assigned state across procedural cycles, it must be explicitly redeclared with the variable storage keyword
reg.
Port Connection and Interfacing Rules:

Internal Rules:
An internal
inputport must be of net type (wire).An internal
outputport can be driven as a net type (wire) or maintained as a variable storage type (reg).An internal
inoutport must strictly be declared as a net type (wire).External Rules:
An external driver feeding an
inputport may be driven by aregor anet.An external receiver connected to an
outputport must connect to anet(cannot connect directly to an externalreg).An external line connecting to an
inoutport must strictly connect to anet.
Lexical Conventions, Data Types, and Number Formats
Lexical Formatting and Comments:
Single-Line Comment: Begins with
//and extends to the immediate newline boundary (e.g.,a = b && c; // This is a one-line comment).Multi-Line Block Comment: Begins with
/*and terminates with*/(e.g.,/* This is a multiple line comment */).Nesting Rules: Embedded single-line comments within multi-line comments are completely legal (e.g.,
/* This is //a legal comment */). Nesting multi-line comments within other multi-line comments is illegal syntax (e.g.,/* This is /* an illegal */ comment */).
Number Representation and Specifications:
Sized Numbers: Stated with the standard syntax format
.<size>: Expressed purely in decimal, defining the absolute bit-width allocated to the constant.'<base_format>: Legal base prefixes include decimal ('dor'D), hexadecimal ('hor'H), binary ('bor'B), and octal ('oor'O).<number>: Digits matching the base set (binary:; octal:; decimal:; hexadecimal:). Case-insensitive.Examples:
4'b1111: 4-bit binary constant equivalent to decimal.12'habc: 12-bit hexadecimal number.16'd255: 16-bit decimal value.
Unsized Numbers:
Values specified without a leading base format default universally to decimal (e.g.,
23456is a 32-bit decimal number).Values declared without an explicit bit-width size allocate a machine- and simulator-dependent width of at least
(e.g.,'hc3is a 32-bit hex number;'o21is a 32-bit octal number).
Four-Valued Logic System and Special States:
Verilog models real hardware using four fundamental discrete value levels:
0: Logic zero, representing ground potential or a false condition.1: Logic one, representing power supply voltage or a true condition.x/X: Unknown logic state (uninitialized register, contention, floating logic input, or indeterminate timing).z/Z: High-impedance, un-driven open circuit or floating tri-state bus terminal.Bit extension mechanics:
In hexadecimal strings, an
xorztoken represents.In octal strings, an
xorztoken represents.In binary strings, an
xorztoken represents.If the most significant bit (MSB) evaluates to
0,x, orz, automatic extension occurs to match the vector size (e.g.,12'h13xdefines a 12-bit hex number with theunknown;6'hxevaluates to a 6-bit value of unknown state;32'bzexpands to a 32-bit high-impedance field).
Signed Representation and Negation Constraints:
Negative integer constants are generated by placing a minus sign directly before the bit-width declaration (e.g.,
-6'd3stores the two's complement ofwithin a 6-bit vector).Signed math operations require explicit signed designators (e.g.,
-6'sd3).It is strictly illegal to place a negative sign between the base designator and the digit literal (e.g.,
4'd-2is an illegal specification).
Formatting Characters:
The underscore character
_can appear anywhere in an integer literal except as the initial character, functioning strictly as a visual spacer that the compiler ignores (e.g.,12'b1111_0000_1010).The question mark character
?is an alternative representation for high-impedancezin casex/number formats (e.g.,4'b10??is completely equivalent to4'b10zz).
Verilog Data Types:
Nets: Physical conductive interconnects that cannot store charge or state autonomously; must be continuously driven by a primitive gate, module output, or
assignstatement. Includeswire,wand(wired-AND),wor(wired-OR),tri,triand,trior, andtrireg.verilog wire a; // Scalar net declaration wire b, c; // Multiple net declaration wire d = 1'b0; // Continuous net declaration fixed to logic 0 Registers (
reg): Data storage abstractions that retain assigned values until modified by an active procedural assignment. Does not require a continuous driver.verilog reg reset; // Scalar register declaration initial begin reset = 1'b1; // Reset initialized high at simulation t=0 #100 reset = 1'b0; // Deasserted after 100 time units end Vectors: Multi-bit bus definitions for net or register types using the syntax
[MSB:LSB]. Omitting range specifications defaults the variable to a 1-bit scalar.verilog wire [7:0] bus; // 8-bit bus net wire [31:0] busA, busB, busC; // Three 32-bit wide bus nets reg clock; // Default 1-bit scalar register reg [0:40] virtual_addr; // 41-bit wide vector register Integer: General-purpose signed arithmetic registers declared with
integer, defaulting to a machine-dependent bit width (typically).verilog integer counter; initial counter = -1; Real: Floating-point numeric registers declared with
real, conforming to IEEE double-precision conventions. Can be defined using decimal notation (e.g.,3.14) or scientific notation (e.g.,3e6denoting). Does not support bit-width slicing. Default value is. Casting real values into integer types automatically rounds them to the nearest integer.verilog real delta; integer i; initial begin delta = 4e10; delta = 2.13; i = delta; // i evaluates to 2 end Time: Scaled simulation clock variables declared with
time, storing elapsed intervals as an unsignedinteger, populated by the system task$time.verilog time save_sim_time; initial save_sim_time = $time; Arrays: Multi-element storage structures allowable across
reg,integer,time,real, and vector constructs, accommodating arbitrary dimensions.verilog integer count[0:7]; // Array of 8 integer variables reg bool[31:0]; // Array of 32 one-bit register flags time chk_point[1:100]; // Array of 100 time checkpoints reg [4:0] port_id[0:7]; // Array of 8 elements; each element is a 5-bit vector integer matrix[4:0][0:255]; // Two-dimensional integer array Memories: One-dimensional arrays composed of
regwords modeled to represent RAM, ROM, or register files.verilog reg mem1bit[0:1023]; // 1K x 1-bit memory array reg [7:0] membyte[0:1023]; // 1K x 8-bit memory (1024 bytes) // Accessing address 511: // membyte[511] extracts the specific 8-bit byte at index 511 Parameters: Module-level constants declared using the keyword
parameter. Cannot be reassigned as variables at run time, but can be overridden on an instance basis during compilation.verilog parameter port_id = 5; parameter cache_line_width = 256; parameter signed [15:0] WIDTH = 16'd8; Strings: Alphanumeric string literals stored inside
regvectors sized to at least, whererepresents the total number of characters (per character).verilog reg [8*18:1] string_value; // 18-byte wide register (144 bits) initial string_value = "Hello Verilog World";
Gate-Level Modeling and Primitive Gate Instantiations
Built-in Primitive Gates:
Verilog features predefined logic gate primitives that do not require explicit module definitions.
Class 1: AND/OR Gates (One scalar output, multiple scalar inputs; first listed terminal is always the output):

and: Output is1if all inputs are1; otherwise0.nand: Inverted AND; output is0if all inputs are1.or: Output is1if at least one input is1.nor: Inverted OR; output is0if any input is1.xor: Output is1if an odd number of inputs are1.xnor: Inverted exclusive OR; output is1if inputs are identical.Gate instantiation syntax examples:
wire OUT, IN1, IN2, IN3; and a1 (OUT, IN1, IN2); nand na1 (OUT, IN1, IN2); or or1 (OUT, IN1, IN2); nor nor1 (OUT, IN1, IN2); xor x1 (OUT, IN1, IN2); xnor nx1 (OUT, IN1, IN2); nand na1_3inp (OUT, IN1, IN2, IN3); // 3-input NAND gate and (OUT, IN1, IN2); // Legal instantiation without an instance name ``` * **Class 2: Buffer/Inverter Gates** (One scalar input, one or more scalar outputs; input is listed as the last terminal):  * `buf`: Non-inverting buffer passing input directly to output. * `not`: Inverting logic NOT gate. * Instantiation syntax examples:verilog buf b1 (OUT1, IN); not n1 (OUT1, IN); buf b1_2out (OUT1, OUT2, IN); // One input driving multiple outputs not (OUT1, IN); // Legal unnamed instantiation ```
Three-State (Tri-State) Buffer Primitives:

Features an additional control terminal
ctrlto establish a high-impedance state (z). Terminal port order:(out, in, ctrl).bufif1: Drivesout = inwhenctrl == 1; drivesout = zwhenctrl == 0.bufif0: Drivesout = inwhenctrl == 0; drivesout = zwhenctrl == 1.notif1: Drivesout = ~inwhenctrl == 1; drivesout = zwhenctrl == 0.notif0: Drivesout = ~inwhenctrl == 0; drivesout = zwhenctrl == 1.Instantiation syntax examples:
verilog bufif1 b1 (out, in, ctrl); bufif0 b0 (out, in, ctrl); notif1 n1 (out, in, ctrl); notif0 n0 (out, in, ctrl);
Gate-Level Structural Multiplexer (4-to-1 MUX):
The 4-to-1 multiplexer selects one of four inputs (
i0, i1, i2, i3) using two select lines (s1, s0).

Full gate-level implementation: ```verilog module mux4_to_1 (out, i0, i1, i2, i3, s1, s0); output out; input i0, i1, i2, i3; input s1, s0;
// Internal wire interconnect declarations wire s1n, s0n; wire y0, y1, y2, y3;
// Gate instantiations not (s1n, s1); not (s0n, s0);
and (y0, i0, s1n, s0n); and (y1, i1, s1n, s0); and (y2, i2, s1, s0n); and (y3, i3, s1, s0);
or (out, y0, y1, y2, y3); endmodule ```
Gate-Level 2-to-4-Line Decoders with Enable Inputs:
Variant 1 (Active-Low Outputs with Active-Low Enable Input
E):
When
E = 1, all outputsare forced to1.When
E = 0, the line matchingA, Bdecodes to0.Gate-level description:
module decoder_gl (A, B, E, D); input A, B, E; output [0:3] D; wire Anot, Bnot, Enot;not n1 (Anot, A), n2 (Bnot, B), n3 (Enot, E); nand n4 (D[0], Anot, Bnot, Enot), n5 (D[1], Anot, B, Enot), n6 (D[2], A, Bnot, Enot), n7 (D[3], A, B, Enot);endmodule
```
* **Variant 2 (Structural Form with Inverted Terminals `decoder_2_to_4_st_v`)**:

* Boolean logic equations:
* ``
* ``
* ``
* ``
* Verilog structural implementation:verilog
module decoder_2_to_4_st_v (E_n, A0, A1, D0_n, D1_n, D2_n, D3_n);
input E_n, A0, A1;
output D0_n, D1_n, D2_n, D3_n;
wire A0_n, A1_n, E;not g0 (A0_n, A0), g1 (A1_n, A1), g2 (E, E_n); nand g3 (D0_n, A0_n, A1_n, E), g4 (D1_n, A0, A1_n, E), g5 (D2_n, A0_n, A1, E), g6 (D3_n, A0, A1, E);endmodule
```
Gate Delays and Timing Specifications
Types of Gate Delays:
Physical digital logic gates exhibit finite signal propagation delays across physical junctions.
Rise Delay (
t_rise): The time elapsed during an output transition from any starting state (0,x, orz) up to a logical1.

Fall Delay (
t_fall): The time elapsed during an output transition from any starting state (1,x, orz) down to a logical0.

Turn-off Delay (
t_turnoff): The time elapsed during a transition from an active driving level to the high-impedance statez.Transition to Unknown (
x): If a transition changes toward the unknown statex, the effective delay is modeled as the mathematical minimum of the component delays:.
Delay Specification Syntax:
Single Delay Value: Applied universally across all output transitions (rise, fall, and turn-off).
and #(delay_time) a1 (out, i1, i2); and #(5) a1 (out, i1, i2); // Delay of 5 for all transitions ``` * **Two Delay Values**: Explicitly defines rise and fall delays; turn-off defaults to ``.verilog
and #(rise_val, fall_val) a2 (out, i1, i2);
and #(4, 6) a2 (out, i1, i2); // Rise = 4, Fall = 6
```Three Delay Values: Explicitly defines rise, fall, and turn-off delays.
verilog
bufif0 #(rise_val, fall_val, turnoff_val) b1 (out, in, control);
bufif0 #(3, 4, 5) b1 (out, in, control); // Rise = 3, Fall = 4, Turn-off = 5
Min, Typ, and Max Delay Formulations:
Circuit simulations accommodate process, voltage, and temperature (PVT) corners using
delay specifications:Min Value: Shortest propagation delay expected under best-case fabrication/operating conditions.
Typ Value: Nominal propagation delay expected under standard nominal operating conditions.
Max Value: Longest propagation delay expected under worst-case operating conditions.
Invoked at run time using simulator command line flags:
+mindelays,+typdelays, or+maxdelays.Code implementation examples:
```verilog
// Single delay specification: min:typ:max
and #(4:5:6) a1 (out, i1, i2);
// if +mindelays, delay = 4
// if +typdelays, delay = 5
// if +maxdelays, delay = 6
// Two delay specifications: (rise_min:rise_typ:rise_max, fall_min:fall_typ:fall_max)
and #(3:4:5, 5:6:7) a2 (out, i1, i2);
// if +mindelays, rise = 3, fall = 5, turn-off = min(3, 5) = 3
// if +typdelays, rise = 4, fall = 6, turn-off = min(4, 6) = 4
// if +maxdelays, rise = 5, fall = 7, turn-off = min(5, 7) = 5// Three delay specifications: (rise, fall, turn-off)
and #(2:3:4, 3:4:5, 4:5:6) a3 (out, i1, i2);
// if +mindelays, rise = 2, fall = 3, turn-off = 4
// if +typdelays, rise = 3, fall = 4, turn-off = 5
// if +maxdelays, rise = 4, fall = 5, turn-off = 6
```
Dataflow Modeling and Operator Reference
Continuous Assignment Fundamentals:
Used primarily in dataflow modeling to drive combinational logic nets.
Instantiated using the keyword
assign.A continuous assignment is perpetually active: any change in an operand on the right-hand side (RHS) triggers immediate re-evaluation and updates the left-hand side (LHS) net target.
The LHS target must always be a scalar or vector net (
wire), never a procedural register (reg).Code examples:
```verilog
// Basic continuous assignment
assign out = i1 & i2;
// Continuous assignment on vector nets
assign addr[15:0] = addr1_bits[15:0] ^ addr2_bits[15:0];// Concatenation on LHS combining scalar and vector nets
assign {c_out, sum[3:0]} = a[3:0] + b[3:0] + c_in;
```Implicit Continuous Assignment and Delays:
Instead of declaring a net and writing a separate
assignstatement, Verilog permits an implicit shorthand binding upon net declaration:
```verilog
// Regular assignment:
wire out;
assign out = in1 & in2;
// Equivalent implicit continuous assignment:
wire out = in1 & in2;
```Assignment Delays:
Regular continuous assignment delay:
assign #10 out = in1 & in2;Implicit continuous assignment delay:
wire #10 out = in1 & in2;(functionally equivalent towire out; assign #10 out = in1 & in2;).
Comprehensive Verilog Operator Taxonomy:
Arithmetic Operators:
Binary: Multiplication (
*), Division (/), Addition (+), Subtraction (-), Modulus (%). All take two operands.Integer division truncates fractional components (e.g.,
).Unary: Positive sign (
+), Negative sign (-). Takes one operand (e.g.,-4,+5).Demonstration:
// A = 4'b0011 (3), B = 4'b0100 (4), D = 6, E = 4 A * B // Evaluates to 4'b1100 (12) D / E // Evaluates to 1 (truncated) A + B // Evaluates to 4'b0111 (7) B - A // Evaluates to 4'b0001 (1) ``` * **Logical Operators**: * Negation (`!`), Logical AND (`&&`), Logical OR (`||`). * Operands evaluate to a single bit: `0` (false), `1` (true), or `x` (ambiguous). * Demonstration:verilog
// A = 3 (logical 1), B = 0 (logical 0)
A && B // Evaluates to 0
A || B // Evaluates to 1
!A // Evaluates to 0
!B // Evaluates to 1
// Unknowns: A = 2'b0x, B = 2'b10
A && B // Evaluates to x
(a == 2) && (b == 3) // Evaluates to 1 if both conditions hold
```Relational Operators:
Greater than (
>), Less than (<), Greater than or equal (>=), Less than or equal (<=).Evaluate to
0or1. If any operand bit containsxorz, the result evaluates tox.Demonstration:
// A = 4, B = 3, X = 4'b1010, Y = 4'b1101, Z = 4'b1xxx A <= B // Evaluates to logical 0 A > B // Evaluates to logical 1 Y >= X // Evaluates to logical 1 Y < Z // Evaluates to x ``` * **Equality Operators**: * Logical Equality (`==`): Evaluates to `1` (true), `0` (false), or `x` (if operands contain `x` or `z`). * Logical Inequality (`!=`): Evaluates to `1` (true), `0` (false), or `x` (if operands contain `x` or `z`). * Case Equality (`===`): Strict comparison including `x` and `z`. Evaluates strictly to `0` or `1`. * Case Inequality (`!==`): Strict comparison including `x` and `z`. Evaluates strictly to `0` or `1`. * Demonstration:verilog
// A = 4, B = 3, X = 4'b1010, Y = 4'b1101, Z = 4'b1xxz, M = 4'b1xxz, N = 4'b1xxx
A == B // Results in logical 0
X != Y // Results in logical 1
X == Z // Results in x
Z === M // Results in logical 1 (identical bit-by-bit)
Z === N // Results in logical 0 (LSB mismatch: z vs x)
M !== N // Results in logical 1
```Bitwise Operators:
Negation (
~), AND (&), OR (|), XOR (^), XNOR (^~or~^).Performed bit-by-bit across matching indices of vectors.
Demonstration:
// X = 4'b1010, Y = 4'b1101, Z = 4'b10x1 ~X // Evaluates to 4'b0101 X & Y // Evaluates to 4'b1000 X | Y // Evaluates to 4'b1111 X ^ Y // Evaluates to 4'b0111 X ^~ Y // Evaluates to 4'b1000 X & Z // Evaluates to 4'b10x0 ``` * **Reduction Operators**: * Unary operations folded across all bits of a single vector: AND (`&`), NAND (`~&`), OR (`|`), NOR (`~|`), XOR (`^`), XNOR (`^~` or `~^`). * Useful for parity checking and validation. * Demonstration:verilog
// X = 4'b1010
&X // 1 & 0 & 1 & 0 = 1'b0
|X // 1 | 0 | 1 | 0 = 1'b1
^X // 1 ^ 0 ^ 1 ^ 0 = 1'b0 (Even parity generation)
```Shift Operators:
Logical Right Shift (
>>), Logical Left Shift (<<). Vacated positions are filled with0.Demonstration:
// X = 4'b1100 Y = X >> 1; // 4'b0110 (Zero filled in MSB) Y = X << 1; // 4'b1000 (Zero filled in LSB) Y = X << 2; // 4'b0000 ``` * **Concatenation Operator (`{ }`)**: * Merges multiple scalar and vector components into a single vector. Unsized constants are strictly illegal inside concatenation blocks. * Demonstration:verilog
// A = 1'b1, B = 2'b00, C = 2'b10, D = 3'b110
Y = {B, C}; // 4'b0010
Y = {A, B, C, D, 3'b001}; // 11'b10010110001
Y = {A, B[0], C[1]}; // 3'b101
```Replication Operator (
{ { } }):Repeats a target expression a specified number of times:
.Demonstration:
verilog
// A = 1'b1, B = 2'b00, C = 2'b10
Y = { 4{A} }; // 4'b1111
Y = { 4{A}, 2{B} }; // 8'b11110000
Y = { 4{A}, 2{B}, C }; // 8'b1111000010
Conditional Operator (
? :):Ternary syntax:
.Evaluates
condition_expr. If1, executestrue_expr. If0, executesfalse_expr. If ambiguous (x), evaluates both branches and merges matching bits, placingxin differing positions.
Dataflow Circuit Descriptions:
4-to-1 Multiplexer (Conditional Operator):
module multiplexer4_to_1 (out, i0, i1, i2, i3, s1, s0); output out; input i0, i1, i2, i3; input s1, s0; assign out = s1 ? (s0 ? i3 : i2) : (s0 ? i1 : i0); endmodule ``` * **4-to-1 Multiplexer (Boolean Logic Equations)**:verilog
module mux4_to_1 (out, i0, i1, i2, i3, s1, s0);
output out;
input i0, i1, i2, i3;
input s1, s0;assign out = (~s1 & ~s0 & i0) |
(~s1 & s0 & i1) |
( s1 & ~s0 & i2) |
( s1 & s0 & i3);
endmodule
```2-to-1 Multiplexer:
module mux2x1_df (A, B, select, OUT); input A, B, select; output OUT; assign OUT = select ? A : B; endmodule ``` * **2-to-4-Line Decoder**:verilog
module decoder_df (A, B, E, D);
input A, B, E;
output [0:3] D;
assign D[0] = ~(~A & ~B & ~E),
D[1] = ~(~A & B & ~E),
D[2] = ~( A & ~B & ~E),
D[3] = ~( A & B & ~E);
endmodule
```
Behavioral Modeling and Procedural Constructs
Structured Procedures (
initialandalways):All procedural statements must reside inside
initialoralwaysblocks.initialBlock:Begins execution at simulation time
.Executes exactly once, expiring upon encountering the terminal statement.
Multiple
initialblocks run concurrently starting at.Typically used for initialization, testbench waveform stimuli, and simulation control.
Code example:
module stimulus; reg x, y, a, b, m;initial m = 1'b0; // Single procedural assignment initial begin #5 a = 1'b1; #25 b = 1'b0; end initial begin #10 x = 1'b0; #25 y = 1'b1; end initial #50 $finish;endmodule
```
* In-line variable initialization: Registers declared at the module level can be initialized directly at declaration (e.g., `reg clock = 0;`), which is completely equivalent to declaring `reg clock;` and writing `initial clock = 0;`.
* **`always` Block**:
* Begins execution at simulation time ``.
* Loops continuously in an infinite cycle throughout the simulation run.
* Standard structure for modeling sequential logic, clock generators, and combinational blocks guarded by event sensitivity lists.
* Clock Generator demonstration (period = ``):verilog
module clock_gen;
reg clock;initial clock = 1'b0; // Initialized to 0 at t=0 always #10 clock = ~clock; // Inverts every 10 time units initial #1000 $finish;endmodule
```Procedural Assignments: Blocking vs. Non-blocking:
Blocking Assignment (
=):Executes sequentially in the exact order written within the procedural block.
Prevents subsequent statements from executing until the current assignment completes.
Used primarily for combinational logic descriptions.
Syntax:
B = A; C = B + 1;Non-blocking Assignment (
<=):Evaluates the right-hand side expressions concurrently at the active simulation time step.
Defers updating left-hand side targets until the entire procedural block has been evaluated.
Essential for avoiding race conditions in synchronous sequential circuits.
Syntax:
B <= A; C <= B + 1;
Conditional Statements (
if-else):Evaluates conditional expressions; non-zero values are interpreted as
true, while0orxevaluates asfalse.Type 1 (No else branch):
if (<expression>) true_statement; ``` * **Type 2 (Single else branch)**:verilog
if () true_statement; else false_statement;
```Type 3 (Nested if-else-if cascade):
if (<expression1>) true_statement1; else if (<expression2>) true_statement2; else if (<expression3>) true_statement3; else default_statement; ``` * Demonstration: 2-to-1 Multiplexer behavioral model:verilog
module mux2x1_bh (A, B, select, OUT);
input A, B, select;
output OUT;
reg OUT;always @(select or A or B)
if (select == 1)
OUT = A;
else
OUT = B;
endmodule
```Multiway Branching (
case):Evaluates an expression against sequential alternatives; executes the matching branch.
If no alternatives match, the optional
defaultbranch executes.Enclosed within keywords
caseandendcase.Syntax template:
case (expression) alternative1: statement1; alternative2: statement2; alternative3: statement3; default: default_statement; endcase ``` * Behavioral 4-to-1 Multiplexer with Case statement:verilog
module mux4_to_1 (out, i0, i1, i2, i3, s1, s0);
output out;
input i0, i1, i2, i3;
input s1, s0;
reg out;always @(s1 or s0 or i0 or i1 or i2 or i3) begin
case ({s1, s0})
2'b00: out = i0;
2'b01: out = i1;
2'b10: out = i2;
2'b11: out = i3;
default: out = 1'bx;
endcase
end
endmodule
```
Timing Controls in Behavioral Verilog
Delay-Based Timing Control:
Explicitly specifies the elapsed time interval between encountering a statement and its actual execution.
Regular Delay Control: Non-zero delay placed to the left of the assignment statement.
x = 0; // Executed at t=0 #10 y = 1; // Delays execution of y=1 by 10 time units #latency z = 0; // Delay specified by an identifier parameter #(latency + delta) p = 1; // Delay specified by an expression #y x = x + 1; // Delay specified by variable value y #(4:5:6) q = 0; // Min:typ:max delay control ``` * **Intra-Assignment Delay Control**: Delay placed to the right of the assignment operator. The RHS expression is evaluated immediately at the current simulation time, but assignment to the LHS target is deferred until the delay period has elapsed.verilog
initial begin
x = 0; z = 0;
y = #5 x + z; // Evaluates x+z at t=0, then waits 5 time units to assign the result to y
end
```Zero Delay Control (
#0): Defers execution to the end of the current simulation time step, executing after all other scheduled active events. Used to resolve race conditions between concurrent threads.verilog
initial begin
x = 0; y = 0;
end
initial begin
#0 x = 1;
#0 y = 1;
end
Event-Based Timing Control:
Uses the
@symbol to stall procedural execution until a specified value change occurs on a net or register.Regular Event Control:
@ (clock) q = d; // Executes whenever clock changes value (any transition) @ (posedge clock) q = d; // Executes on positive edge (0->1, 0->x, 0->z, x->1, z->1) @ (negedge clock) q = d; // Executes on negative edge (1->0, 1->x, 1->z, x->0, z->0) q = @(posedge clock) d; // Intra-assignment event: d evaluated immediately, assigned at posedge clock ``` * **Named Event Control**: Capability to declare an event variable, manually trigger its occurrence using `->`, and recognize it elsewhere using `@`.verilog
event received_data; // Declare named eventalways @(posedge clock) begin
if (last_data_packet)
->received_data; // Trigger named event
endalways @(received_data) begin
// Awaits named event trigger, then concatenates data packets
data_buf = {data_pkt[0], data_pkt[1], data_pkt[2], data_pkt[3]};
end
```Event OR Sensitivity Lists: Triggers execution whenever any signal in a declared set changes state. Formatted using the
orkeyword or comma separator,.Level-sensitive latch with asynchronous reset:
// Using 'or' operator: always @(reset or clock or d) begin if (reset) q = 1'b0; else if (clock) q = d; end // Equivalent description using comma operator: always @(reset, clock, d) begin if (reset) q = 1'b0; else if (clock) q = d; end ``` * Edge-triggered D flip-flop with asynchronous reset:verilog
always @(posedge clk, negedge reset) begin
if (!reset) q <= 0;
else q <= d;
end
```The Implicit Sensitivity Wildcard Operator (
@*/@(*)):Eliminates omissions in long sensitivity lists for combinational logic blocks.
Automatically includes every input signal read inside the procedural block.
```verilog
// Manual entry: cumbersome and prone to omissions
always @(a or b or c or d or e or f or g or h or p or m) begin
out1 = a ? b+c : d+e;
out2 = f ? g+h : p+m;
end
// Optimized implementation using the wildcard operator:
always @(*) begin
out1 = a ? b+c : d+e;
out2 = f ? g+h : p+m;
end
```Level-Sensitive Timing Control (
wait):Stalls procedural execution until an expression evaluates to true (
1).Syntax:
always wait (count_enable) #20 count = count + 1;
Implementation of Combinational Circuits
Half Adder:

Computes the arithmetic sum of two 1-bit inputs
and, producing outputsSum() andCarry().Truth table:
| | | Sum () | Carry () |
| :---: | :---: | :---: | :---: |
| | | | |
| | | | |
| | | | |
| | | | |
Karnaugh maps:
Sum:
Carry:

Gate-Level Implementation:
verilog
module half_adder_s (sum, carry, a, b);
input a, b;
output sum, carry;
xor (sum, a, b);
and (carry, a, b);
endmodule
Dataflow Implementation:
verilog
module half_adder_d (sum, carry, a, b);
input a, b;
output sum, carry;
assign sum = a ^ b;
assign carry = a & b;
endmodule
Behavioral Implementation (Equations):
verilog
module half_adder_behavioral (input a, input b, output reg s, output reg c);
always @(*) begin
s = a ^ b;
c = a & b;
end
endmodule
Behavioral Implementation (Case Statement):
verilog
module half_adder (a, b, sum, cout);
input a, b;
output reg sum, cout;
always @(*) begin
case ({a, b})
2'b00: begin sum = 0; cout = 0; end
2'b01: begin sum = 1; cout = 0; end
2'b10: begin sum = 1; cout = 0; end
2'b11: begin sum = 0; cout = 1; end
default: begin sum = 0; cout = 0; end
endcase
end
endmodule
Full Adder:
Computes the arithmetic sum of three inputs: two operand bits
and an input carrycin.Structural / Gate-Level Model:
```verilog
module full_adder (sum, carry, a, b, cin);
output sum, carry;
input a, b, cin;
wire w1, w2, w3, w4;xor (w1, a, b);
xor (sum, w1, cin);
and (w2, a, b);
and (w3, b, cin);
and (w4, cin, a);
or (carry, w2, w3, w4);
endmodule
```Dataflow Model:
```verilog
module full_adder (sum, carry, a, b, cin);
output sum, carry;
input a, b, cin;assign sum = a ^ b ^ cin;
assign carry = (a & b) | (b & cin) | (cin & a);
endmodule
```Behavioral Model (if-else):
```verilog
module full_adder (sum, carry, a, b, cin);
output reg sum, carry;
input a, b, cin;always @(a or b or cin) begin
if (a==0 && b==0 && cin==0) begin sum=0; carry=0; end
else if (a==0 && b==0 && cin==1) begin sum=1; carry=0; end
else if (a==0 && b==1 && cin==0) begin sum=1; carry=0; end
else if (a==0 && b==1 && cin==1) begin sum=0; carry=1; end
else if (a==1 && b==0 && cin==0) begin sum=1; carry=0; end
else if (a==1 && b==0 && cin==1) begin sum=0; carry=1; end
else if (a==1 && b==1 && cin==0) begin sum=0; carry=1; end
else if (a==1 && b==1 && cin==1) begin sum=1; carry=1; end
end
endmodule
```Behavioral Model (case):
```verilog
module full_adder (sum, carry, a, b, cin);
output reg sum, carry;
input a, b, cin;always @(a or b or cin) begin
case ({a, b, cin})
3'b000: begin sum = 0; carry = 0; end
3'b001: begin sum = 1; carry = 0; end
3'b010: begin sum = 1; carry = 0; end
3'b011: begin sum = 0; carry = 1; end
3'b100: begin sum = 1; carry = 0; end
3'b101: begin sum = 0; carry = 1; end
3'b110: begin sum = 0; carry = 1; end
3'b111: begin sum = 1; carry = 1; end
endcase
end
endmodule
```Full Subtractor:
Computes the difference of two bits
andwith a borrow-inbin.Dataflow model:
```verilog
module FullSubstractor (a, b, difference, bin, bout);
input a, b, bin;
output difference, bout;assign difference = (a ^ b ^ bin);
assign bout = (~a & b) | (~a & bin) | (b & bin);
endmodule
```3-to-8 Decoder:
Decodes a 3-bit binary input vector into eight mutually exclusive active-high outputs:
```verilog
module Decoder (a, b, c, d0, d1, d2, d3, d4, d5, d6, d7);
input a, b, c;
output d0, d1, d2, d3, d4, d5, d6, d7;assign d0 = (~a & ~b & ~c),
d1 = (~a & ~b & c),
d2 = (~a & b & ~c),
d3 = (~a & b & c),
d4 = ( a & ~b & ~c),
d5 = ( a & ~b & c),
d6 = ( a & b & ~c),
d7 = ( a & b & c);
endmodule
```8-to-3 Encoder:
Structural gate-level model encoding eight active-high inputs down to a 3-bit code:
```verilog
module Encoder (do, d1, d2, d3, d4, d5, d6, d7, a, b, c);
input do, d1, d2, d3, d4, d5, d6, d7;
output a, b, c;or (a, d4, d5, d6, d7);
or (b, d2, d3, d6, d7);
or (c, d1, d3, d5, d7);
endmodule
```1-to-8 Demultiplexer:
Routes a single input line
into one of eight output lines based on a 3-bit select code:
```verilog
module Demultiplexer (in, s0, s1, s2, d0, d1, d2, d3, d4, d5, d6, d7);
input in, s0, s1, s2;
output d0, d1, d2, d3, d4, d5, d6, d7;assign d0 = (in & ~s2 & ~s1 & ~s0),
d1 = (in & ~s2 & ~s1 & s0),
d2 = (in & ~s2 & s1 & ~s0),
d3 = (in & ~s2 & s1 & s0),
d4 = (in & s2 & ~s1 & ~s0),
d5 = (in & s2 & ~s1 & s0),
d6 = (in & s2 & s1 & ~s0),
d7 = (in & s2 & s1 & s0);
endmodule
```8-to-1 Multiplexer (Behavioral):
Routes one of eight data inputs to a single output line based on a 3-bit select vector
sel:
```verilog
module Mulitplexer (d0, d1, d2, d3, d4, d5, d6, d7, sel, out);
input d0, d1, d2, d3, d4, d5, d6, d7;
input [2:0] sel;
output reg out;always @(sel) begin
case (sel)
3'b000: out = d0;
3'b001: out = d1;
3'b010: out = d2;
3'b011: out = d3;
3'b100: out = d4;
3'b101: out = d5;
3'b110: out = d6;
3'b111: out = d7;
endcase
end
endmodule
```
Review Questions and Study Exercises
Fundamental 2-Mark Review Questions:
Combinational Circuit Definition in Verilog HDL: A digital circuit whose logical outputs at any given instant depend solely and strictly on the contemporary input signal combination, without feedback paths or internal state storage memory.
Distinctions Between
assignStatements andalwaysBlocks:An
assignstatement executes continuously outside procedural blocks and can only drivewirenet targets.An
alwaysblock executes cyclically when triggered by an event sensitivity list and can only assign to proceduralregvariables.Function of a Multiplexer in Digital Systems: Acts as a digitally controlled single-pole multi-throw data selector that channels one of several input streams onto a single shared transmission path.
Verilog HDL Syntax for 2-to-1 MUX Using Conditional Operator (
? :):verilog
assign out = sel ? in1 : in0;
Two Common Modeling Styles for Combinational Circuits in Verilog: Dataflow modeling (using
assign) and Gate-level modeling (using primitive gates).Purpose of the
wireData Type in Combinational Design: Represents physical electrical conductors that connect output terminals of driving gates directly to the inputs of receiving elements.Key Differences Between
wireandregData Types:A
wirerepresents a physical conductor that requires a continuous driver and cannot hold charge or state.A
regrepresents a software-modeled data storage element that holds its value until overwritten by another procedural assignment.Output Evaluation for Boolean Expression: Given
assign y = a & b | c;with inputs:Intermediate AND product:
.Bitwise OR evaluation:
.Final evaluated result:
.Advantages of Parameterized Modules: Permits flexible customization of bus bit-widths, memory depths, or timing delays on an individual instance basis during compilation without rewriting the underlying RTL code.
Common Combinational Circuits Implemented in Verilog: Multiplexers, Demultiplexers, Encoders, Decoders, Half Adders, Full Adders, and Ripple Carry Adders.
Comprehensive 8-Mark Design Exercises:
Design and implement a 4-to-1 multiplexer across dataflow, behavioral, and structural modeling styles, verifying each with simulation testbenches.
Construct a 4-bit Binary to Gray Code converter with an exhaustive truth table, derivation equations, Verilog code, and simulation output.
Develop a Verilog HDL module for a BCD to 7-segment display decoder, including full segment mapping and an accompanying verification testbench.
Implement an 8-to-3 priority encoder in Verilog HDL and characterize its operation through simulation waveforms.
Build a 4-bit magnitude comparator module that produces greater-than, equal-to, and less-than comparison outputs.
Construct an even-parity generator and checker for 4-bit data words and verify correct error detection under simulation.
Implement gate-level structural models of a half adder and a full adder, validating their functionality with simulation testbenches.
Construct a 4-bit ripple carry adder by instantiating four 1-bit full adder modules hierarchically.
Develop a 4-bit barrel shifter capable of multi-bit left and right shifts based on external control lines.
Construct a 4-bit Arithmetic Logic Unit (ALU) capable of addition, subtraction, bitwise AND, and bitwise OR operations conditioned on a 2-bit operation selector.