Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Course Material Verilog Module

Uploaded by

vr46shreyas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Course Material Verilog Module

Uploaded by

vr46shreyas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

Verilog www.cranesvarsity.

com

VERILOG

It is advised that the participants revise the basic concepts of Electronics


Prerequisite
and Computer concepts.

© Cranes Varsity V1.1-2020-21 1/ 86


Verilog www.cranesvarsity.com

No. of
Sl # Topics / Subtopics Session Lab - Y/N Page #
1 Introduction to VLSI 1 N 4-7
1.1 Design flow of VLSI
1.2 Hardware Description Language
1.3 Design methodology
1.4 Stimulus Block
2 Basic Concepts of Verilog HDL 1 N 8-11
2.1 Whitespace
2.2 Comments
2.3 Operators
Number Specification -Sized numbers,Unsized
2.4 numbers
2.5 X or Z values
2.6 Negative numbers
2.7 Underscore characters and question marks
2.8 Identifiers and Keywords
2.9 Escaped Identifiers
3 Data types 1 N 12-19
3.1 Value Set
3.2 Wire / Net
3.3 Reg
3.4 Vectors
3.5 Input, Output, Inout
3.6 Integer
3.7 Real
3.8 Time
3.9 Parameter
3.10 Arrays
3.11 Memories
3.12 Strings
4 Operators in verilog 1 Y 20-27
4.1 Arithmetic Operators
4.2 Relational Operators
4.3 Bit-wise Operators
4.4 Logical Operators
4.5 Reduction Operators
4.6 Shift Operators
4.7 Concatenation Operator
4.8 Replication Operator
4.9 Conditional Operator: “?”
4.10 Operator Precedence
4.11 Operands
5 Modules and Ports 1 Y 28-33
5.1 Module
5.2 Ports
5.3 Port Connection Rules
6 Gate Level Modeling 1 Y 34-43
6.1 Gate Types
6.2 Gate Delays
6.2.1 Rise Delay

© Cranes Varsity V1.1-2020-21 2/ 86


Verilog www.cranesvarsity.com

6.2.2 Fall Delay


6.2.3 Turn-off Delay
7 Data flow modeling 1 Y 44-47
7.1 Continuous Assignments
7.2 Implicit Continuous Assignment
7.3 Net Declaration Delay
7.4 Operator Types
7.5 Operator Precedence
8 Behavioral modeling 1 Y 48-56
8.1 Structured Procedures
8.2 Procedural Assignments
8.3 Timing Controls
8.3.1 Delay-Based Timing Control
8.3.2 Regular delay control
8.3.3 Intraassignment delay control
8.3.4 Event-Based Timing Control
8.4 case Statement
8.5 LOOPS
8.5.1 While Loop
8.5.2 For Loop
8.5.3 Repeat Loop
8.5.4 Forever loop
8.6 Block Types
9 Tasks and Functions 1 Y 56-60
9.1 Tasks
9.2 Functions
10 Design of digital devices 21 Y 61-86
10.1 Combinational Circuits
10.2 Sequential circuits
10.3 Counter
10.4 Shift registers- SISO, SIPO, PISO, PIPO
Shift operations- Right shift , Left shift, Right round
10.5 shift, Left round shift
10.6 Clock divider
10.7 FSM: Mealy machine, Moore machine
10.8 Memory Modeling
10.9 ALU, MAC unit
10.10 PWM,Error detector- CRC
10.11 UART
10.12 SPI
10.13 I2C

© Cranes Varsity V1.1-2020-21 3/ 86


Verilog www.cranesvarsity.com

Chapter – 1

Introduction to VLSI
Very-large-scale integration (VLSI) is the process of creating an integrated circuit (IC) by combining
thousands of transistors into a single chip.

Design Flow of an IC

Specification

System architecture /
Algorithm

Behavioral / Functional
Design

Logic / RTL/ Circuit Design

Physical design

Fabrication

Packaging, Testing and


Debugging

Fig1.1 Design Flow of an IC

© Cranes Varsity V1.1-2020-21 4/ 86


Verilog www.cranesvarsity.com

The very first step is Specifications which describes abstractly the functionality, interface, and overall
architecture of the digital circuit to be designed. At this point, the architects do not need to think about
how they will implement this circuit. Then we have behavioral description which is created to analyze
the design in terms of functionality, performance, and other high-level issues. The behavioral description
is manually converted to an RTL description in an HDL. The designer has to describe the data flow that
will implement the desired digital circuit. Once the behavioral description is converted to RTL
description, logic synthesis process takes place which converts the RTL description to a gate-level netlist.
A gate-level netlist is a description of the circuit in terms of gates and connections between them. Logic
synthesis tools ensure that the gate-level netlist meets timing, area, and power specifications. The gate-
level netlist is an input to an Automatic Place and Route tool, which creates a layout. The layout is
verified and then fabricated on a chip.
Introduction to HDL
HDL stands for hardware description language that describes the functionality of any hardware of digital;
system in the form of text.
Evolution of HDL
For a long time, programming languages such as FORTRAN, Pascal, and C were being used to
describe computer programs that were sequential in nature. Similarly, in the digital design field,
designers felt the need for a standard language to describe digital circuits. Thus, Hardware
Description Languages (HDLs) came into existence. HDLs allowed the designers to model the
concurrency of processes found in hardware elements. Therefore Engineers started to use HDL
for system-level design. HDLs were used for simulation of system boards, interconnect
buses,FPGAs (Field Programmable Gate Arrays),and PALs (Programmable Array Logic). A
common approach is to design each IC chip, using an HDL, and then verify system functionality
via simulation.
HDLs have many advantages compared to traditional schematic-based design.
• Designs can be described at a very abstract level by use of HDLs. I.e Designers can write their
RTL description without choosing a specific fabrication technology. Hence Logic synthesis tools
can automatically convert the design to any fabrication technology. If a new technology emerges,
designers do not need to redesign their circuit. They simply input the RTL description to the
logic synthesis tool and create a new gate-level netlist, using the new fabrication technology. The
logic synthesis tool will optimize the circuit in area and timing for the new technology.

© Cranes Varsity V1.1-2020-21 5/ 86


Verilog www.cranesvarsity.com

• By describing designs in HDLs, functional verification of the design can be done early in the
design cycle. Since designers work at the RTL level, they can optimize and modify the RTL
description until it meets the desired functionality. Most design bugs are eliminated at this point.
This cuts down design cycle time significantly because the probability of hitting a functional bug
at a later time in the gate-level netlist or physical layout is minimized.
• Designing with HDLs is analogous to computer programming. I.e A textual description with
comments is an easier way to develop and debug circuits. One can design any hardware at any
level

There are two hardware description language


1. VHDL (Very High Speed Integration Circuit Hardware Description Language)
2. Verilog HDL
A verilog program for a particular application consist of two main blocks
1. Design Block
2. Simulation block

Design Methodology
There are two different ways to design the design block
1. Top-down design methodology
2. Bottom-up design methodology.
In a top-down design methodology, we define the top-level block and identify the sub-blocks necessary to
build the top-level block. We further subdivide the sub-blocks until we come to leaf cells, which are the
cells that cannot further be divided.
In a bottom-up design methodology, we first identify the building blocks that are available to us. We
build bigger cells, using these building blocks. These cells are then used for higher-level blocks until we
build the top-level block in the design.
A combination of these two methodologies is used in today's digital designs. As designs become very
complex, it is important to follow these structured approaches to manage the design process. Design
architects define the specifications of the top-level block whereas the Logic designers decide how the
design should be structured by breaking up the functionality into blocks and sub-blocks. At the same
time, circuit designers are designing optimized circuits for leaf-level cells. They build higher-level cells
by using these leaf cells. The flow meets at an intermediate point where the switch-level circuit designers

© Cranes Varsity V1.1-2020-21 6/ 86


Verilog www.cranesvarsity.com

have created a library of leaf cells by using switches, and the logic level designers have designed from
top-down until all modules are defined in terms of leaf cells.
Stimulus Block
The functionality of the design block can be tested by applying stimulus and checking results. We call
such blocks as stimulus block. It is good practice to keep the stimulus and design blocks separate. The
stimulus block can be written in Verilog. A separate language is not required to describe stimulus. The
stimulus block is also commonly called a test bench. Different test benches can be used to thoroughly test
the design block.
Two styles of stimulus application are possible. In the first style, the stimulus block instantiates the design
block and directly drives the signals in the design block.
The second style of applying stimulus is to instantiate both the stimulus and design blocks in a top-level
dummy module. The stimulus block interacts with the design block only through the interface

© Cranes Varsity V1.1-2020-21 7/ 86


Verilog www.cranesvarsity.com

Chapter – 2

Basic Concepts of Verilog HDL


Lexical Conventions

The basic lexical conventions used by Verilog HDL are similar to those in the C programming language.
Verilog contains a stream of tokens. Tokens can be comments, delimiters, numbers, strings, identifiers,
and keywords. Verilog HDL is a case-sensitive language. All keywords are in lowercase.

Whitespace

Blank spaces (\b) , tabs (\t) and newlines (\n) comprise the whitespace. Whitespace is ignored by Verilog
except when it separates tokens. Whitespace is not ignored in strings.

Comments

Comments can be inserted in the code for readability and documentation. There are two ways to write
comments. A one-line comment starts with "//". Verilog skips from that point to the end of line. A
multiple-line comment starts with "/*" and ends with "*/". Multiple-line comments cannot be nested.

a = b &&c; / / This is a one-line comment


/ * This is a multiple line
comment * /
/ * This is / * an illegal * / comment * /

Operators
Operators are of three types, unary, binary, and ternary. Unary operators precede the operand. Binary
operators appear between two operands. Ternary operators have two separate operators that separate three
operands.

a = - b; / / - is a unary operator. b is the operand


a = b &&c; / / &&is a binary operator. b and c are operands
a = b ? c : d; / / ?: is a ternary operator. b, c and d are operands

© Cranes Varsity V1.1-2020-21 8/ 86


Verilog www.cranesvarsity.com

Number Specification
There are two types of number specification in Verilog: sized and unsized.

Sized numbers

Sized numbers are represented as <size>I <base format><number>. <size>is written only in decimal
and specifies the number of bits in the number.

Legal base formats are decimal ('d or 'D), hexadecimal ('h or 'H), binary ('b or 'B) and octal ('0 or '0). The
number is specified as consecutive digits from 0,1,2,3,4,5, 6, 7, 8, 9, a, b, c, d, e, f. Only a subset of these
digits is legal for a particular base. Uppercase letters are legal for number specification.

4'bllll / / This is a 4-bit binary number


l2'habc / / This is a 12-bit hexadecimal number
16'd255 / / This is a 16-bit decimal number.

Unsized numbers

Numbers that are specified without a <base format>specification are decimal numbers by default.
Numbers that are written without a <size> specification have a default number of bits that is simulator-
and machine-specific (must be at least 32).

23456 / / This is a 32-bit decimal number by default


'hc3 / / This is a 32-bit hexadecimal number
'O21 / / This is a 32-bit octal number

X or Z values

Verilog has two symbols for unknown and high impedance values. These values are very important for
modeling real circuits. An unknown value is denoted by an X. A high impedance value is denoted by z.

12'h13x / / This is a 12-bit hex number; 4 least significant bits unknown


6'hx //This is a 6-bit hex number

© Cranes Varsity V1.1-2020-21 9/ 86


Verilog www.cranesvarsity.com

32'bz //This is a 32-bit high impedance number


An X or z sets four bits for a number in the hexadecimal base, three bits for a number in the octal base,
and one bit for a number in the binary base. If the most significant bit of a number is of X, or z, the
number is automatically extended to fill the most significant bits, respectively, with 0, X, or z. This makes
it easy to assign X or z to whole vector. If the most significant digit is I, then it is also zero extended.

Negative numbers

Negative numbers can be specified by putting a minus sign before the size for a constant number. Size
constants are always positive. It is illegal to have a minus sign between <base format> and <number>.

-6'd3 / / 8-bit negative number stored as 2's complement of 3


4'd-2 / / Illegal specification

Underscore characters and question marks

An underscore character "-" is allowed anywhere in a number except the first character. Underscore
characters are allowed only to improve readability of numbers and are ignored by Verilog.

A question mark "?" is the Verilog HDL alternative for z in the context of numbers. The ? is used to
enhance readability in the casex and casez statements discussed in Chapter 7, Behavioral Modeling,
where the high impedance value is a don't care condition.

12'b1111~0000~1010 / / Use of underline characters for readability


4'b10?? / / Equivalent of a 4'b10zz

Strings
A string is a sequence of characters that are enclosed by double quotes. The restriction on a string is that it
must be contained on a single line, that is, without a carriage return. It cannot be on multiple lines. Strings
are treated as a sequence of one-byte ASCII values.

"Hello Verilog World" / / is a string

© Cranes Varsity V1.1-2020-21 10/ 86


Verilog www.cranesvarsity.com

"a / b" / / is a string

Identifiers and Keywords


Keywords are special identifiers reserved to define the language constructs. Keywords are in lowercase.
Identifiers are names given to objects so that they can be referenced in the design. Identifiers are made up
of alphanumeric characters, the underscore ( - ) and the dollar sign ( $ ) and are case sensitive. Identifiers
start with an alphabetic character or an underscore. They cannot start with a number or a $ sign (The
$sign as the first character is reserved for system tasks, which are explained later in the book).

reg value; / / reg is a keyword; value is an identifier


input clk; / / input is a keyword, clk is an identifier

Escaped Identifiers
Escaped identifiers begin with the backslash ( \ ) character and end with whitespace (space, tab, or
newline). All characters between backslash and whitespace are processed literally. Any printable ASCII
character can be included in escaped identifiers. The backslash or whitespace is not considered a part of
the identifier.

© Cranes Varsity V1.1-2020-21 11/ 86


Verilog www.cranesvarsity.com

Chapter - 3

Data types

Value Set

Verilog supports four values and eight strengths to model the functionality of real hardware.

0 (logic zero, or false condition)


1 (logic one, or true condition)
x (unknown logic value) x and z have limited use for synthesis.
z (high impedance state)

In addition to logic values, strength levels are often used to resolve conflicts between drivers of different
strengths in digital circuits.

If two signals of unequal strengths are driven on a wire, the stronger signal prevails. For example, if two
signals of strength strong l and weak0 contend, the result is resolved as a strong l. If two signals of equal
strengths are driven on a wire, the result is unknown. If two signals of strength strong l and strong0
conflict, the result is an X.

Wire / Net
A wire represents a physical wire in a circuit and is used to connect gates or modules. The value of a wire
can be read, but not assigned to, in a function or block. See “Functions” on p. 19, and “Procedures:

© Cranes Varsity V1.1-2020-21 12/ 86


Verilog www.cranesvarsity.com

Always and Initial Blocks” on p. 18. A wire does not store its value but must be driven by a continuous
assignment statement or by connecting it to the output of a gate or module. Other specific types of wires
include:

wand (wired-AND) ;: the value of a wand depend on logical AND of all the drivers connected
to it.
wor (wired-OR) ;: the value of a wor depend on logical OR of all the drivers connected to it.
tri (three-state) ;: all drivers connected to a tri must be z, except one (which determines
the value of the tri).

Syntax
wire [msb:lsb] wire_variable_list;
wand [msb:lsb] wand_variable_list;
wor [msb:lsb] wor_variable_list;
tri [msb:lsb] tri_variable_list;

Example :
wirec // simple wire
wand d;
assign d = a; // value of d is the logical AND of
assign d = b; // a and b
wire [9:0] A; // a cable (vector) of 10 wires.

Reg

Declare type reg for all data objects on the left hand side of expressions in inital and always procedures,
or functions. A reg is the data type that must be used for latches, flip-flops and memories. However it
often synthesizes into leads rather than storage. In multi-bit registers, data is stored as unsigned numbers
and no sign extension is done for what the user might have thought were two’s complement numbers.

Syntax
reg [msb:lsb] reg_variable_list;

© Cranes Varsity V1.1-2020-21 13/ 86


Verilog www.cranesvarsity.com

Example :
reg a; // single 1-bit register variable
reg [7:0] tom; // an 8-bit vector; a bank of 8 registers.
reg [5:0] b, c; // two 6-bit variables

Vectors

Nets or reg data types can be declared as vectors (multiple bit widths). If bit width is not specified, the
default is scalar (l-bit).

wire a; / / scalar net variable, default


wire [7:0] bus; // 8-bit bus
wire [31:0] busA,busB,busC; // 3 buses of 32-bit width.
reg clock; // scalar register, default
reg[0:40] virtual-addr; // vector register, virtual address 41 bits wide

Vectors can be declared at [high# : low#] or [low# : high#], but the left number in the squared brackets is
always the most significant bit of the vector. In the example shown above, bit 0 is the most significant bit
of vector virtual-addr. For the vector declarations shown above, it is possible to address bits or parts of
vectors.

Input, Output, Inout

These keywords declare input, output and bidirectional ports of a module or task. Input and inout ports
are of type wire. An output port can be configured to be of type wire, reg, wand, wor or tri. The default
is wire.

Syntax
input [msb:lsb] input_port_list;
output [msb:lsb] output_port_list;
inout [msb:lsb] inout_port_list;

Example :
module sample(b, e, c, a); //See “Module Instantiations” on p. 10

© Cranes Varsity V1.1-2020-21 14/ 86


Verilog www.cranesvarsity.com

input a; // An input which defaults to wire.


output b, e; // Two outputs which default to wire
output [1:0] c; /* A two-it output. One must declare its type in a
separate statement. */

reg [1:0] c; // The above c port is declared as reg.

Integer

Integers are general-purpose variables. For synthesis they are used mainly loops-indicies, parameters, and
constants. They are of implicitly of type reg. However they store data as signed numbers whereas
explicitly declared reg types store them as unsigned. If they hold numbers which are not defined at
compile time, their size will default to 32-bits. If they hold constants, the synthesizer adjusts them to the
minimum width needed at compilation.
Syntax
integer integer_variable_list;
... integer_constant ... ;

Example :
integer a; // single 32-bit integer
assign b=63; // 63 defaults to a 7-bit variable.

Real

Real number constants and real register data types are declared with the keyword real. They can be
specified in decimal notation (e.g., 3.14) or in scientific notation (e.g., 3e6, which is 3x10^6). Real
numbers cannot have a range declaration, and their default value is 0. When a real value is assigned to an
integer, the real number is rounded off to the nearest integer.

real delta; / / Define a real variable called delta


initial
begin
delta = 4e10; / / delta is assigned in scientific notation

© Cranes Varsity V1.1-2020-21 15/ 86


Verilog www.cranesvarsity.com

delta = 2.13; / / delta is assigned a value 2.13


end
integer i; / / Define an integer i
initial
i = delta; / / i gets the value 2 (rounded value of 2.13)

Supply0, Supply1

Supply0 and supply1 define wires tied to logic 0 (ground) and logic 1 (power), respectively.

Syntax
supply0 logic_0_wires;
supply1 logic_1_wires;

Example :
supply0 my_gnd; // equivalent to a wire assigned 0
supply1 a, b;

Time

Time is a 64-bit quantity that can be used in conjunction with the $time system task to hold simulation
time. Time is not supported for synthesis and hence is used only for simulation purposes.

Syntax
time time_variable_list;

Example
time c;
c = $time; //c = current simulation time

Parameter
Parameters allows constants like word length to be defined symbolically in one place. This makes it easy
to change the word length later, by change only the parameter. See also “Parameterized Modules” on page
11 . An alternative way to do the same thing is to use macro substitution.

© Cranes Varsity V1.1-2020-21 16/ 86


Verilog www.cranesvarsity.com

Syntax
parameter par_1 = value,
par_2 = value, .....;
parameter [range] parm_3 = value

Example :
parameter add = 2’b00, sub = 3’b111;
parameter n = 4;
parameter [3:0] st4 = 4’b1010;
...
reg [n-1:0] harry; /* A 4-bit register whose length is set by parameter n above. */
always @(x)
y = {{(add - sub){x}}; // The replication operator Sect. 5.8.
if (x) begin
state = st4[1]; else state = st4[2];
end

Arrays

Arrays are allowed in Verilog for reg, integer, time, and vector register data types. Arrays are not allowed
for real variables. Arrays are accessed by <array-name> [<subscript>l. Multidimensional arrays are not
permitted in Verilog.

integer count[0:7]; / / ~ an array of 8 count variables


reg bool[31:0]; //Array of 32 one-bit boolean register variables
time chkqoint[l:l00]; //Array of 100 time checkpoint variables
reg [4 : 0] port-id[0 :7] ; //Array of 8port-ids; each port-id is 5 bits wide
integer matrix[4:0][4:0]; // 11legaldeclaration.Multidimensional array
count[5] // 5th element of array of count variables
chk_point[100] //100th time check point value
port_id[3] //3rd element of port-id array. This is a 5-bit value.

© Cranes Varsity V1.1-2020-21 17/ 86


Verilog www.cranesvarsity.com

It is important not to confuse arrays with net or register vectors. A vector is a single element that is n-bits
wide. On the other hand, arrays are multiple elements that are l-bit or n-bits wide.

Memories

In digital simulation, one often needs to model register files, RAMS, and ROMs. Memories are modeled
in Verilog simply as an array of registers. Each element of the array is known as a word. Each word can
be one or more bits. It is important to differentiate between n l-bit registers and one n-bit register. A
particular word in memory is obtained by using the address as a memory array subscript.

reg memlbit[0:1023]; //~memory memlbit with 1K l-bit words


reg [7 : 0] membyte [O : 1023]; // ~memory membyte with 1K 8-bit words (bytes)
membyte[511] // fetches 1 byte word whose address is 511.

Strings

Strings can be stored in reg. The width of the register variables must be large enough to hold the string.
Each character in the string takes up 8 bits (1 byte). If the width of the register is greater than the size of
the string, Verilog fills bits to the left of the string with zeros. If the register width is smaller than the
string width, Verilog truncates the leftmost bits of the string. It is always safe to declare a string that is
slightly wider than necessary.

reg [8*18:1] string-value; //Declare a variable that is l8 bytes wide


initial
string-value = "Hello Verilog World"; // String can be stored in variable

Special characters serve a special purpose in displaying strings, such as newline, tabs and displaying
argument values. Special characters can be displayed in strings only when they are preceded by escape
characters.

© Cranes Varsity V1.1-2020-21 18/ 86


Verilog www.cranesvarsity.com

© Cranes Varsity V1.1-2020-21 19/ 86


Verilog www.cranesvarsity.com

Chapter - 4

Operators in verilog

Arithmetic Operators
These perform arithmetic operations. The + and - can be used as either unary (-z) or binary (x-y)
operators.

Operators
+ (addition)
- (subtraction)
* (multiplication)
/ (division)
% (modulus)

Example :
parameter n = 4;
reg[3:0] a, c, f, g, count;
f = a + c;
g = c - n;
count = (count +1)%16; //Can count 0 thru 15.

Relational Operators
Relational operators compare two operands and return a single bit 1or 0. These operators synthesize into
comparators. Wire and reg variables are positive Thus (-3’b001) = = 3’b111 and (-3d001)>3d110.
However for integers -1< 6.

Operators
< (less than)
<= (less than or equal to)
> (greater than)
>= (greater than or equal to)
== (equal to)
!= (not equal to)

© Cranes Varsity V1.1-2020-21 20/ 86


Verilog www.cranesvarsity.com

Example :
if (x = = y) e = 1;
else e = 0;
// Compare in 2’s compliment; a>b
reg [3:0] a,b;
if (a[3]= = b[3]) a[2:0] > b[2:0];
else b[3];

Bit-wise Operators
Bit-wise operators do a bit-by-bit comparison between two operands.

Operators
~ (bitwise NOT)
& (bitwise AND)
| (bitwise OR)
^ (bitwise XOR)
~^ or ^~ (bitwise XNOR)

Example :
module and2 (a, b, c);
input [1:0] a, b;
output [1:0] c;
assign c = a & b;
endmodule

Logical Operators
Logical operators return a single bit 1 or 0. They are the same as bit-wise operators only for single bit
operands. They can work on expressions, integers or groups of bits, and treat all values that are nonzero
as “1”. Logical operators are typically used in conditional (if ... else) statements since they work with
expressions.

© Cranes Varsity V1.1-2020-21 21/ 86


Verilog www.cranesvarsity.com

Operators
! (logical NOT)
&& (logical AND)
|| (logical OR)

Example :
wire[7:0] x, y, z; // x, y and z are multibit variables.
reg a;
...
if ((x == y) && (z)) a = 1; // a = 1 if x equals y, and z is nonzero.
else a = !x; // a =0 if x is anything but zero.

Reduction Operators
Reduction operators operate on all the bits of an operand vector and return a single-bit value. These are
the unary (one argument) form of the bit-wise operators above.

Operators
& (reduction AND)
| (reduction OR)
~& (reduction NAND)
~| (reduction NOR)
^ (reduction XOR)
~^ or ^~ (reduction XNOR)

Example :
module chk_zero (a, z);
input [2:0] a;
output z;
assign z = ~| a; // Reduction NOR

© Cranes Varsity V1.1-2020-21 22/ 86


Verilog www.cranesvarsity.com

endmodule

Shift Operators
Shift operators shift the first operand by the number of bits specified by the second operand. Vacated
positions are filled with zeros for both left and right shifts (There is no sign extension).

Operators
<< (shift left)
>> (shift right)

Example :

assign c = a << 2; /* c = a shifted left 2 bits;


vacant positions are filled with 0’s */

Concatenation Operator
The concatenation operator combines two or more operands to form a larger vector.

Operators
{ } (concatenation)

Example :
wire [1:0] a, b; wire [2:0] x;
wire [3;0] y, Z;
assign x = {1’b0, a}; // x[2]=0, x[1]=a[1], x[0]=a[0]
assign y = {a, b}; /* y[3]=a[1], y[2]=a[0], y[1]=b[1],y[0]=b[0] */
assign {cout, y} = x + Z; // Concatenation of a result

© Cranes Varsity V1.1-2020-21 23/ 86


Verilog www.cranesvarsity.com

Replication Operator
The replication operator makes multiple copies of an item.

Operators
{n{item}} (n fold replication of an item)

Example :

wire [1:0] a, b; wire [4:0] x;


assign x = {2{1’b0}, a}; // Equivalent to x = {0,0,a }
assign y = {2{a}, 3{b}}; //Equivalent to y = {a,a,b,b}

For synthesis, Synopsis did not like a zero replication. For example:-

parameter n=5, m=5;


assign x= {(n-m){a}}

Conditional Operator: “?”


Conditional operator is like those in C/C++. They evaluate one of the two expressions based on a
condition. It will synthesize to a multiplexer (MUX).

Operators
(cond) ? (result if cond true):
(result if cond false)

Example :
assign a = (g) ? x : y;
assign a = (inc = = 2) ? a+1 : a-1; /* if (inc), a = a+1, else a = a-1 */

© Cranes Varsity V1.1-2020-21 24/ 86


Verilog www.cranesvarsity.com

Operator Precedence
Table shows the precedence of operators from highest to lowest. Operators on the same level evaluate
from left to right. It is strongly recommended to use parentheses to define order of precedence and
improve the readability of your code.

Operands

Literals
Literals are constant-valued operands that can be used in Verilog expressions. The two common Verilog
literals are:

(a) String: A string literal is a one-dimensional array of characters enclosed in double

quotes (“ “).

(b) Numeric: constant numbers specified in binary, octal, decimal or hexadecimal.

© Cranes Varsity V1.1-2020-21 25/ 86


Verilog www.cranesvarsity.com

Number Syntax
n’Fddd..., where
n - integer representing number of bits
F - one of four possible base formats:
b (binary), o (octal), d (decimal),
h (hexadecimal). Default is d.
dddd - legal digits for the base format

Example :

“time is” // string literal


267 // 32-bit decimal number
2’b01 // 2-bit binary
20’hB36F // 20-bit hexadecimal number
‘o62 // 32-bit octal number

Wires, Regs, and Parameters

Wires, regs and parameters can also be used as operands in Verilog expressions.

Bit-Selects “x[3]” and Part-Selects “x[5:3]”

Bit-selects and part-selects are a selection of a single bit and a group of bits, respectively, from a wire, reg
or parameter vector using square brackets “[ ]”. Bit-selects and part-selects can be used as operands in
expressions in much the same way that their parent data objects are used.

Syntax
variable_name [index]
variable_name [msb:lsb]

© Cranes Varsity V1.1-2020-21 26/ 86


Verilog www.cranesvarsity.com

Example :
reg [7:0] a, b;
reg [3:0] ls;
reg c;
c = a[7]& b[7]; // bit-selects
ls = a[7:4] + b[3:0]; // part-selects

Function Calls

The return value of a function can be used directly in an expression without first assigning it to a register
or wire variable. Simply place the function call as one of the operands. Make sure you know the bit width
of the return value of the function call.

Syntax
function_name (argument_list)

Example :

assign a = b & c & chk_bc(c, b); // chk_bc is a function


... /* Definition of the function */
function chk_bc; // function definition
input c,b;
chk_bc = b^c;
endfunction

© Cranes Varsity V1.1-2020-21 27/ 86


Verilog www.cranesvarsity.com

Chapter 5

Modules and ports

Module

A module in Verilog consists of distinct parts.

A module definition always begins with the keyword module. The module name, port list, port
declarations, and optional parameters must come first in a moduledefinition. Port list and port
declarations are present only if the module has anyports to interact with the external environment.

The five components within amodule are - variable declarations, dataflow statements, instantiation of
lower modules, behavioral blocks, and tasks or functions. These components can be in any order andat
any place in the module definition.

The endmodule statement must alwayscome last in a module definition. All components except module,
module name, and endmodule are optional and can be mixed and matched as per design needs.

© Cranes Varsity V1.1-2020-21 28/ 86


Verilog www.cranesvarsity.com

Verilog allows multiple modules to be defined in a single file. The modules can be defined in any order in
the file.

Ports
Ports provide the interface by which a module can communicate with its environment. For example, the
input/output pins of an IC chip are its ports. The environment can interact with the module only through
its ports. The internals of the module are not visible to the environment. This provides a very powerful
flexibility to the designer. The internals of the module can be changed without affecting the environment
as long as the interface is not modified. Ports are also
referred to as terminals.

List of Ports
A module definition contains an optional list of ports. If the module does not exchange any signals with
the environment, there are no ports in the list. Consider a 4-bit full adder that is instantiated inside a top-
level module Top.

Notice that in the above figure, the module Top is a top-level module. The module fulladd4 is instantiated
below Top. The module fulladd4 takes input on ports a, b, and c-in and produces an output on ports sum
and c-out. Thus, module fulladd4 performs an addition for its environment. The module Top is a top-level
module in the simulation and does not need to pass signals to or receive signals from the environment.
Thus, it does not have a list of ports.

Port Declaration
All ports in the list of ports must be declared in the module. Ports can be declared as follows:

© Cranes Varsity V1.1-2020-21 29/ 86


Verilog www.cranesvarsity.com

Each port in the port list is defined as input, output, or inout, based on the direction of the port signal.

Example :

module fulladd4(sum, c-out, a, b, c-in); //Begin port declarations section


output [3 : 01 sum;
output c-cout;
input [3:0] a, b;
input c-in; //End port declarations section
...
<module internals>
...
Endmodule
Note that all port declarations are implicitly declared as w i r e in Verilog. Thus, if a port is intended to be
a wire, it is sufficient to declare it as output, input, or inout. Input or inout ports are normally declared as
wires. However, if output ports hold their value, they must be declared as reg. For example, in the
definition of DFF, we wanted the output q to retain its value until
the next clock edge.

module DFF(q, d, clk, reset) ;


output q;
reg q; / / Output port q holds value; therefore it is declared as reg.
input d, clk, reset;
...
...
Endmodule

Ports of the type input and inout cannot be declared as reg because reg variables store values and input
ports should not store values but simply reflectthe changes in the external signals they are connected to.

© Cranes Varsity V1.1-2020-21 30/ 86


Verilog www.cranesvarsity.com

Port Connection Rules


One can visualize a port as consisting of two units, one unit that is internal to the module another that is
external to the module. The internal and external units are connected. There are rules governing port
connections when modules are instantiated within other modules. The Verilog simulator complains if any
port connection rules are violated.

Inputs
Internally, input ports must always be of the type net. Externally, the inputs can be connected to a variable
which is a reg or a net.

Outputs
Internally, outputs ports can be of the type reg or net. Externally, outputs must always be connected to a
net. They cannot be connected to a reg.

Inouts
Internally, inout ports must always be of the type net. Externally, inout ports must always be connected to
a net.
Width matching
It is legal to connect internal and external items of different sizes when making inter-module port
connections. However, a warning is typically issued that the widths do not match.

Unconnected ports
Verilog allows ports to remain unconnected. For example, certain output ports might be simply for
debugging, and you might not be interested in connecting them to the external signals. You can let a port
remain unconnected by instantiating a module as shown below.

© Cranes Varsity V1.1-2020-21 31/ 86


Verilog www.cranesvarsity.com

fulladd4 faO(SUM, , A, B, C-IN); / / Output port c-out is unconnected

Connecting Ports to External Signals


There are two methods of making connections between signals specified in the module instantiation and
the ports in a module definition. The two methods cannot be mixed.

Connecting by ordered list


Connecting by ordered list is the most intuitive method for most beginners. The signals to be connected
must appear in the module instantiation in the same order as the ports in the port list in the module
definition. Once again, consider the module fulladd4 defined in Example. To connect signals in module
Top by ordered list, the Verilog code is shown in Example. Notice that the external signals SUM, C-OUT,
A, B, and CJN appear in exactly the same order as the ports sum, c-out, a, b, and c-in in module definition
of fulladd4.

module Top; //Declare connection variables


reg [3:O]A,B;
reg C-IN;
wire [3:0] SUM;
wire C-OUT;
//Instantiate fulladdl, call it fa-ordered.
//Signals are connected to ports in order (by position)

fulladd4 fa-ordered(SUM, C-OUT, A, B, C-IN);


<stimulus>
...
Endmodule

module fulladd4 (sum, c-out, a, b, c-in) ;


output [3 : 01 sum;
output c-cout;
input [ 3 : 0 ] a, b;

© Cranes Varsity V1.1-2020-21 32/ 86


Verilog www.cranesvarsity.com

input c-in;
...
<module internals>
...
Endmodule

Connecting ports by name


For large designs where modules have, say, 50 ports, remembering the order of the ports in the module
definition is impractical and error prone. Verilog provides the capability to connect external signals to
ports by the port names, rather than by position. We could connect the ports by name in Example above
by instantiating the module fulladd4, as follows. Note that you can specify the port connections in any
order as long as the port name in the module definition
correctly matches the external signal.

/ / Instantiate module fa-byname and connect signals to ports by name

fulladd4 fa-byname(.c-out(C-OUT), .sum(SUM), .b(B), .c-in(C-IN), .a(A), ) ;

Note that only those ports that are to be connected to external signals must be specified in port connection
by name. Unconnected ports can be dropped. For example, if the port c-out were to be kept unconnected,
the instantiation of filladd4 would look as follows. The port c-out is simply dropped from the port list.

/ / Instantiate module fa-byname and connect signals to ports by name

fulladd4 fa-byname( . sum(SUM) , . b ( B ) , .c-in (C-IN) , .a (A) , ) ;

Another advantage of connecting ports by name is that as long as the port name is not changed, the order
of ports in the port list of a module can be rearranged without changing the port connections in module
instantiations.

© Cranes Varsity V1.1-2020-21 33/ 86


Verilog www.cranesvarsity.com

Chapter - 6

Gate-Level Modeling
Gate Types
A logic circuit can be designed by use of logic gates. Verilog supports basic logic gates as predefined
primitives. These primitives are instantiated like modules except that they are predefined in Verilog and
do not need a module definition.

All logic circuits can be designed by using basic gates. There are two classes of basic gates: andlor gates
and buflnot gates.

And/Or Gates
AND/OR gates have one scalar output and multiple scalar inputs. The first terminal in the list of gate
terminals is an output and the other terminals are inputs. The output of a gate is evaluated as soon as one
of the inputs changes. The and/lor gates available in Verilog are shown below.

More than two inputs can be specified in a gate instantiation. Gates with more than two inputs are
instantiated by simply adding more input ports in the gate instantiation.

wire OUT, IN1, IN2; / / basic gate instantiations.


and al(OUT, IN1, IN2);
nand nal (OUT, IN1, IN2 ) ;
or orl(OUT, IN1, IN2);
nor nor1 (OUT, IN1, IN2 ) ;
xor xl (OUT, IN1, IN2 ) ;
xnor nxl (OUT, IN1, IN2 ) ; / / More than two inputs; 3 input nand gate
nand nal-3 inp (OUT, IN1, IN2, IN3 ) ; / / gate instantiation without instance name
and (OUT, IN1, IN2); / / legal gate instantiation

© Cranes Varsity V1.1-2020-21 34/ 86


Verilog www.cranesvarsity.com

The truth tables for these gates define how outputs for the gates are computed from the inputs. Truth
tables are defined assuming two inputs.

Buf/Not Gates

Buflnot gates have one scalar input and one or more scalar outputs. The last terminal in the port list is
connected to the input. Other terminals are connected to the outputs. We will discuss gates that have one
input and one output.

Two basic buflnot gate primitives are provided in Verilog.

© Cranes Varsity V1.1-2020-21 35/ 86


Verilog www.cranesvarsity.com

Bufif/notif
Gates with an additional control signal on buf and not gates are also available.
bufifl , notif l
bufifO , notif 0

These gates propagate only if their control signal is asserted. They propagate z if their control signal is
deasserted. Symbols for bufif / notif are,

© Cranes Varsity V1.1-2020-21 36/ 86


Verilog www.cranesvarsity.com

These gates are used when a signal is to be driven only when the control signal is asserted. Such a
situation is applicable when multiple drivers drive the signal. These drivers are designed to drive the
signal on mutually exclusive control signals.

//Instantiation of bufif gates.

bufifl bl (out, in, ctrl) ;


bufifO bO (out, in, ctrl) ;

//Instantiation of notif gates

notifl nl (out, in, ctrl) ;


notif0 no (out, in, ctrl) ;

Example :

4-bit full adder


In this example, We use primitive logic gates, and we apply stimulus to the 4-bit full adder to check
functionality . For the sake of simplicity, we will implement a ripple carry adder. The basic building block
is a l-bit full adder. The mathematical equations for a l-bit full adder are shown below.

sum= (a xor b xor cin)


cout = ab + bc+ ac;

© Cranes Varsity V1.1-2020-21 37/ 86


Verilog www.cranesvarsity.com

/ / Define a l-bit full adder

module fulladd(sum, c-out, a, b, c-in) ;


/ / I/O port declarations
output sum, c-out;
input a, b, c-in;
/ / Internal nets
wire sl, cl, c2;
/ / Instantiate logic gate primitives
xor (sl, a, b);
and (cl, a, b);
xor (sum, sl, c-in) ;
and (c2, sl, c-in);
or (c-out, c2, cl);
endmodule

A 4-bit ripple carry full adder can be constructed from four I-bit full adders, Notice that faO, fal, fa2, and
fa3 are instances of the module fulladd (l-bit full adder).

Note that the port names used in a l-bit full adder and a 4-bit full adder are the same but they represent
different elements. The element sum in a l-bit adder is a scalar quantity and the element sum in the 4-bit
full adder is a 4-bit vector quantity.

© Cranes Varsity V1.1-2020-21 38/ 86


Verilog www.cranesvarsity.com

Verilog keeps names local to a module. Names are not visible outside the module unless fullpath,
hierarchical name referencing is used. Also note that instance names must be specified when defined
modules are instantiated, but when instantiating Verilog primitives, the instance names are optional.

/ / Define a 4-bit full adder


module fulladd4(sum, c-out, a, b, c-in);
/ / I/O port declarations
output [3:01 sum;
output c-out;
input [3 : 01 a, b;
input c-in;
/ / Internal nets
wire cl, c2, c3;
/ / Instantiate four l-bit full adders.
fulladd fa0 (sum[Ol, cl, a[Ol, b[Ol, c-in);
fulladd fa1 (sum[ll, c2, a[ll, b[ll, cl);
fulladd fa2 (surn[21, c3, a[21, b[21, c2);
fulladd fa3 (sumt31, c-out, at31, b[31, c3);
endmodule

Gate Delays
Until now, we described circuits without any delays (i.e., zero delay). In real circuits, logic gates have
delays associated with them. Gate delays allow the Verilog user to specify delays through the logic
circuits. Pin-to-pin delays can also be specified in Verilog.

Rise, Fall, and Turn-off Delays


There are three types of delays from the inputs to the output of a primitive gate.

Rise delay
The rise delay is associated with a gate output transition to a 1 from another value.

© Cranes Varsity V1.1-2020-21 39/ 86


Verilog www.cranesvarsity.com

Fall delay
The fall delay is associated with a gate output transition to a o from another value.

Turn-off delay
The turn-off delay is associated with a gate output transition to the high impedance value (z) from another
value.
If the value changes to X, the minimum of the three delays is considered.

Three types of delay specifications are allowed. If only one delay is specified, this value is used for all
transitions. If two delays are specified, they refer to the rise and fall delay values. The turn-off delay is the
minimum of the two delays. If a11 three delays are specified, they refer to rise, fall, and turn-off delay
values. If no delays are specified, the default value is zero.

Example :Types of Delay Specification

/ / Delay of delay-time for all transitions


and #(delay-time) al(out, il, i2);
/ / Rise and Fall Delay Specification.
and # (rise-val, fall-val) a2 (out, il, i2) ;
/ / Rise, Fall, and Turn-off Delay Specification
bufifO #(rise-val, fall-val, turnoff-val) bl (out, in, control);

© Cranes Varsity V1.1-2020-21 40/ 86


Verilog www.cranesvarsity.com

Examples of delay specification are shown below.

and #(5) al(out, il, i2); //Delay of 5 for all transitions


and #(4,6) a2(out, il, i2); // Rise = 4, Fall = 6
buf if0 # (3,4,5)b l (out,i n, control); // ~ise= 3, Fall = 4, Turn-off = 5

Min/Typ/Max Values
Verilog provides an additional level of control for each type of delay mentioned above. For each type of
delay-rise, fall, and turn-off-three values, min, typ, and max, can be specified. Any one value can be
chosen at the start of the simulation.

Min/typ/max values are used to model devices whose delays vary within a minimum and maximum range
because of the IC fabrication process variations.

Min value
The min value is the minimum delay value that the designer expects the gate to have.

Typ val
The typ value is the typical delay value that the designer expects the gate to have.

Max value
The max value is the maximum delay value that the designer expects the gate to have. Min, typ, or max
values can be chosen at Verilog run time. Method of choosing a min/typ/max value may vary for different
simulators or operating systems. (For Verilog-XLTMt,h e values are chosen by specifying options
+maxdelays,+typdelay, and +minddays at run time. If no option is specified, the typical delay value is the
default). This allows the designers the flexibility of building three delay values for each transition into
their design. The designer can experiment with delay values without modifying the design.

Example : Min, Max and Typical Delay Values

/ / One delay
/ / if +mindelays, delay= 4
/ / if +typdelays, delay= 5

© Cranes Varsity V1.1-2020-21 41/ 86


Verilog www.cranesvarsity.com

/ / if +maxdelays, delay= 6

and #(4:5:6) al(out, il, i2);

/ / Two delays
/ / if +mindelays, rise= 3, fall= 5, turn-off = rnin
/ / if +typdelays, rise= 4, fall= 6, turn-off = rnin
/ / if +maxdelays, rise= 5, fall= 7, turn-off = rnin

and #(3:4:5, 5:6:7) a2(out, il, i2);

/ / Three delays
/ / 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

and #(2:3:4, 3:4:5, 4:5:6) a3(out, il,i2);

Delay Example
Let us consider a simple example to iIlustrate the use of gate delays to model timing in the logic circuits.
A simple module called D implements the following
logic equations:
The gate-level implementation is shown in Module D. The module contains two gates with delays of 5
and 4 time units.
The module D is defined in Verilog as shown in Example./
/ / Define a simple combination module called D
module D (out, a, b, c);
/ / 1/0 port declarations
output out;
input a,b,c;
/ / Internal nets

wire e;

© Cranes Varsity V1.1-2020-21 42/ 86


Verilog www.cranesvarsity.com

/ / Instantiate primitive gates to build the circuit


and # (5) a1 (e, a, b) ; //Delay of 5 on gate a1
or #(4) ol(out, e,c); //Delay of 4 on gate 01
endmodule

The waveforms from the simulation are shown in Figure to illustrate the effect of specifying delays on
gates. The waveforms are not drawn to scale. However, simulation time at each transition is specified
below the transition.

1. The outputs E and OUT are initially unknown.

2. At time 10, after A, B, and C all transition to I, OUT transitions to 1 after a delay of 4 time units
and E changes value to 1 after 5 time units.

3. At time 20, B and C transition to 0. E changes value to o after 5 time units, and OUT transitions
to 0, 4 time units after E changes.

It is a useful exercise to understand how the timing for each transition in the above waveform corresponds
to the gate delays shown in Module D.

© Cranes Varsity V1.1-2020-21 43/ 86


Verilog www.cranesvarsity.com

Chapter 7
Dataflow modeling
Continuous Assignments

A continuous assignment is the most basic statement in dataflow modeling, used to drive a value onto a
net. A continuous assignment replaces gates in the description of the circuit and describes the circuit at a
higher level of abstraction. A continuous assignment statement starts with the keyword assign.

Continuous assignments have the following characteristics.

1. The left hand side of an assignment must always be a scalar or vector net or a concatenation of
scalar and vector nets. It cannot be a scalar or vector register.

2. Continuous assignments are always active. The assignment expression is evaluated as soon as
one of the right-hand-side operands changes and the value is assigned to the left-hand-side net.

3. The operands on the right-hand side can be registers or nets or function calls. Registers or nets
can be scalars or vectors.

4. Delay values can be specified for assignments in terms of time units. Delay values are used to
control the time when a net is assigned the evaluated value. This feature is similar to specifying
delays for gates. It is very useful in modeling timing behavior in real circuits.

Implicit Continuous Assignment


Instead of declaring a net and then writing a continuous assignment on the net, Verilog provides a
shortcut by which a continuous assignment can be placed on a net when it is declared. There can be only
one implicit declaration assignment per net because a net is declared only once.

//Regular continuous assignment

wire out;
assign out = in1 & in2;

© Cranes Varsity V1.1-2020-21 44/ 86


Verilog www.cranesvarsity.com

//Same effect is achieved by an implicit continuous assignment


wire out = in1 & in2;

Regular Assignment Delay


The first method is to assign a delay value in a continuous assignment statement. The delay value is
specified after the keyword assign. Any change in values of in1 or in2 will result in a delay of 10 time
units before recomputation of the expression in1 &in2, and the result will be assigned to out. If in1 or in2
changes value again before 10 time units when the result propagates to out, the values of in1 and in2 at
the time of recomputation are considered. This property is called inertialdelay. An input pulse that is
shorter than the delay of the assignment statement does not propagate to the output.

assign $10 out = in1 & in2; / / Delay in a continuous assign

Waveform will be,

1. When signals in1 and in2 go high at time 20, out goes to a high 10 time units later (time = 30).
2. When in1 goes low at 60, out changes to low at 70.
3. However, in1 changes to high at 80, but it goes down to low before 10 time units have elapsed.
4. Hence, at the time of recomputation, 10 units after time 80, in1 is 0. Thus, out gets the value 0.

A pulse of width less than the specified assignment delay isnot propagated to the output.

Net Declaration Delay


A delay can be specified on a net when it is declared without putting a continuous assignment on the net.
If a delay is specified on a net out, then any value change applied to the net out is delayed accordingly.
Net declaration delays can also be used in gate-level modeling.

//Net Delays

wire # 10 out;
assign out = in1 & in2;

//The above statement has the same effect as the following

© Cranes Varsity V1.1-2020-21 45/ 86


Verilog www.cranesvarsity.com

wire out;
assign #l0 out = in1 & in2;

Opertor Types
Verilog provides many different operator types. Operators can be arithmetic, logical, relational, equality,
bitwise, yeduction, shift, concatenation, or conditional. Someof these operators are similar to the
operators used in the C programminglanguage. Each operator type is denoted by a symbol.

© Cranes Varsity V1.1-2020-21 46/ 86


Verilog www.cranesvarsity.com

Operator Precedence
Having discussed the operators, it is now important to discuss operator precedence. If no parentheses are
used to separate parts of expressions, Verilog enforces the following precedence.

© Cranes Varsity V1.1-2020-21 47/ 86


Verilog www.cranesvarsity.com

Chapter 8

Behavioral modeling

Structured Procedures
There are two structured procedure statements in Verilog : always and initial.
These statements are the two most basic statements in behavioral modeling. All other behavioral
statements can appear only inside these structured procedure statements.

Verilog is a concurrent programming language unlike the C programming language, which is sequential
in nature. Activity flows in Verilog run in parallel rather than in sequence. Each always and i n i t i a l
statement represents a separate activity flow in Verilog. Each activity flow starts at simulation time 0.

The statements always and i n i t i a l cannot be nested. The fundamental difference between the two
statements is explained in the following sections.

initial Statement
All statements inside an i n i t i a l statement constitute an i n i t i a l block. An i n i t i a l block starts at
time 0, executes exactly once during a simulation, and then does not execute again. If there are multiple i
n i t i a l blocks, each block starts to execute concurrently at time 0. Each block finishes execution
independently of other blocks. Multiple behavioral statements must be grouped, typically using the
keywords begin and end. If there is only one behavioral statement, grouping is not necessary.

module stimulus;
reg x,y, a,b, m;
initial

m = lfbO; //single statement; does not need to be grouped

initial
begin
#5 a = l'bl; //multiple statements; need to be grouped

© Cranes Varsity V1.1-2020-21 48/ 86


Verilog www.cranesvarsity.com

#25 b = llbO;
end

initial
begin
#l0 X = llbO;
#25 y = l'bl;
end

initial
#50 $finish;
endmodule

time statement executed

0 m = l'bO;
5 a = l'bl;
10 X = l'bO;
30 b = l'bO;
35 y = l'bl;
50 $finish;

always Statement
All behavioral statements inside an always statement constitute an always block. The always statement
starts at time 0 and executes the statements in the always block continuously in a looping fashion. This
statement is used to model a block of activity that is repeated continuously in a digital circuit. An example
is a clock generator module that toggles the clock signal every half cycle.

module clock-gen;
reg clock;

initial
clock = l'bO;

© Cranes Varsity V1.1-2020-21 49/ 86


Verilog www.cranesvarsity.com

always
#l0 clock = -clock;

initial
#l000 $finish;

endmodule

Notice that the initialization of clock has to be done inside a separate initial statement. If we put the
initialization of clock inside the always block, clock will be initialized every time the always is entered.
Also, the simulation must be halted inside an initial statement. If there is no $stop or $finish statement to
halt the simulation, the clock generator will run Forever.

Procedural Assignments
Procedural assignments update values of reg, integer, real, or t i m e variables. The value placed on a
variable will remain unchanged until another procedural assignment updates the variable with a different
value.

Blocking assignments
Blocking assignment statements are executed in the order they are specified in a sequential block. A
blocking assignment will not block execution of statements that follow in a parallel block.

Nonblocking Assignments
Nonblocking assignments allow scheduling of assignments without blocking execution of the statements
that follow in a sequential block. A <= operator is used to specify nonblocking assignments. Note that this
operator has the same symbol as a relational operator, less-than-equal-to. The operator <= is interpreted
as a relational operator in an expression and as an assignment operator in the context of a nonblocking
assignment.

Application of nonblocking assignments


Having described the behavior of nonblocking assignments, it is important to understand why they are
used in digital design. They are used as a method to model several concurrent data transfers that take

© Cranes Varsity V1.1-2020-21 50/ 86


Verilog www.cranesvarsity.com

place after a common event. Consider the following example where three concurrent data transfers take
place at the positive edge of clock.

always @(posedge clock)


begin
regl <= #l inl ;
reg2 <= @(negedge clock) in2 &in3;
reg3 <= #l regl; //The old value of regl
end

At each positive edge of clock, the following sequence takes place for the nonblocking assignments.

1. A read operation is performed on each right-hand-side variable, inl, in2, in3, and regl, at the
positive edge of clock. The right-hand-side expressions are evaluated, and the results are stored
internally in the simulator.

2. The write operations to the left-hand-side variables are scheduled to be executed at the time
specified by the intra-assignment delay in each assignment, that is, schedule "write" to regl after 1
time unit, to reg2 at the next negative edge of clock, and to reg3 after 1 time unit.

3. The write operations are executed at the scheduled time steps. The order in which the write
operations are executed is not important because the internally stored right-hand-side expression
values are used to assign to the left-hand-side values. For example, note that reg3 is assigned the
old value of regl that was stored after the read operation, even if the write operation wrote a new
value to regl before the write operation to reg3 was executed. Thus, the final values of regl, reg2,
and reg3 are not dependent on the order in which the assignments are processed.

Timing Controls
Various behavioral timing control constructs are available in Verilog. In Verilog, if there are no timing
control statements, the simulation time does not advance. Timing controls provide a way to specify the
simulation time at which procedural statements will execute. There are three methods of timing control:
delay-based timing control, event-based timing control, and level-sensitive timing control.

© Cranes Varsity V1.1-2020-21 51/ 86


Verilog www.cranesvarsity.com

Delay-Based Timing Control


Delay-based timing control in an expression specifies the time duration between when the statement is
encountered and when it is executed. We used delay-based timing control statements when writing few
modules in the preceding chapters but did not explain them in detail. In this section we will discuss delay-
based timing control statements. Delays are specified by the symbol #.

Regular delay control


Regular delay control is used when a non-zero delay is specified to the left of a procedural assignment.

parameter latency = 20;


parameter delta = 2;

reg X, Y, z , P, q;

initial
begin
X = 0; / / no delay control
#l0 y = 1; / / delay control with a number. Delay execution of
/ / y = 1 by 10 units

#latency z = 0; //~elayc ontrol with identifier.Delay of 20 units


#(latency + delta) p = 1; / / Delay control with expression
#y X = X + 1; / / Delay control with identifier. Take value of y.
# ( 4 : 5 : 6 ) q = 0; / / ~inimum,t ypical and maximum delay values.
end

Intra-assignment delay control


Instead of specifying delay control to the left of the assignment, it is possible to assign a delay to the right
of the assignment operator.

reg X, y, z;

initial

© Cranes Varsity V1.1-2020-21 52/ 86


Verilog www.cranesvarsity.com

begin
x=o;z=o;
y = $5 X + z; //Take value of X and z at the time=O, evaluate
//X + z and then wait 5 time units to assign value
//to y.
end

//Equivalent method with temporary variables and regular delay control

initial
begin
x=o;z=o;
temp-xz = X + z;
$5 y = temp-xz; //Take value of X + z at the current time and
//store it in a temporary variable. Even though X and z
//might change between 0 and 5,
//the value assigned to y at time 5 is unaffected.
end

Event-Based Timing Control


An event is the change in the value on a register or a net. Events can be utilized to trigger execution of a
statement or a block of statements. There are four types of event-based timing control: regular event
control, named event control, event ORcontrol, and level-sensitive timing control.

Regular event control


The Q symbol is used to specify an event control. Statements can be executed on changes in signal value
or at a positive or negative transition of the signal value. The keyword posedge is used for a negative
transition.

Named event control


Verilog provides the capability to declare an event and then trigger and recognize the occurrence of that
event. The event does not hold any data.A named event is declared by the keyword event. An event is
triggered by thesymbol ->. The triggering of the event is recognized by the symbol @.

© Cranes Varsity V1.1-2020-21 53/ 86


Verilog www.cranesvarsity.com

event received-data; //Define an event called received-data


always @(posedge clock) //check at each positive clock edge
begin
if(1ast-dataqacket) //If this is the last data packet
->received-data; //trigger the event received-data
end
always @(received-data) //Await triggering of event received-data
//When event is triggered, store all four
//packets of received data in data buffer
//use concatenation operator { }
data-buf = {dataqkt [O] , dataqkt [l], dataqkt [ 2 ] , dataqkt [3] ;

case Statement
The keywords case, endcase, and default are used in the case statement.

module mux4-to-l (out, iO, il, i2, i3, sl, SO);


output out;
input iO, il, i2, i3;
input sl, SO;
reg out;
always @(sl or SO or iO or il or i2 or i3)
case ({sl, SO))
2'dO : out = iO;
2'dl : out = il;
2'd2 : out = i2;
2'd3 : out = i3;
default: $display("Invalid control signals");
endcase
endmodule

© Cranes Varsity V1.1-2020-21 54/ 86


Verilog www.cranesvarsity.com

The case statement compares 0, 1, X, and z values in the expression and the alternative bit for bit. If the
expression and the alternative are of unequal bit width, they are zero filled to match the bit width of the
widest of the expression and the alternative.

casex, casez Keywords


There are two variations of the case statement. They are denoted by keywords,
casex and casez.

casez treats all z values in the case alternatives or the case expression as don't cares. All bit positions with
z can also represented by ? in that position.

casex treats all X and z values in the case item or the case expression as don't cares.

LOOPS
While Loop

The keyword while is used to specify this loop. The while loop executes until the while-expression
becomes false. If the loop is entered when the while-expression is false, the loop is not executed at all.

For Loop
The keyword for is used to specify this loop. The for loop contains three parts:

 An initial condition

 A check to see if the terminating condition is true

 A procedural assignment to change value of the control variable.

Repeat Loop
The keyword repeat is used for this loop. The repeat construct executes the loop a fixed number of
times. A repeat construct cannot be used to loop on a general logical expression. A while loop is used for
that purpose. A repeat construct must contain a number, which can be a constant, a variable or a signal

© Cranes Varsity V1.1-2020-21 55/ 86


Verilog www.cranesvarsity.com

value. However, if the number is a variable or signal value, it is evaluated only when the loop starts and
not during the loop execution.

Forever loop
The keyword forever is used to express this loop. The loop does not contain any expression and executes
forever until the $finish task is encountered. The loop is equivalent to a while loop with an expression
that always evaluates to true, e.g., while (1). A forever loop can be exited by use of the disable statement.

Block Types
There are two types of blocks: sequential blocks and parallel blocks.

Sequential blocks
The keywords begin and end are used to group statements into sequential blocks.

Sequential blocks have the following characteristics:

The statements in a sequential block are processed in the order they are specified. A statement is executed
only after its preceding statement completes execution (except for nonblocking assignments with
intraassignment timing control).

If delay or event control is specified, it is relative to the simulation time when the previous statement in
the block completed execution.

Parallel blocks
Parallel blocks, specified by keywords fork and join, provide interesting simulation features.

Parallel blocks have the following characteristics.

Statements in a parallel block are executed concurrently.


Ordering of statements is controlled by the delay or event control assigned to each statement.
If delay or event control is specified, it is relative to the time the block was entered.

© Cranes Varsity V1.1-2020-21 56/ 86


Verilog www.cranesvarsity.com

Chapter 9
Tasks and Functions

Adesigner is frequently required to implement the same functionality at many places in a behavioral
design. This means that the commonly used parts should be abstracted into routines and the routines must
be invoked instead of repeating the code. Most programming languages provide procedures or subroutines
to accomplish this. Verilog provides tasks and functions to break up large behavioral designs into smaller
pieces. Tasks and functions allow the designer to abstract Verilog code that is used at many places in the
design.

Tasks have input, output, and inout arguments; functions have input arguments. Thus, values can be
passed into and out from tasks and functions. Considering the analogy of FORTRAN, tasks are similar to
SUBROUTINE and functions are similar to FUNCTION.

Differences Between Tasks and Functions

Tasks and functions serve different purposes in Verilog. We discuss tasks and functions in greater detail
in the following sections.

© Cranes Varsity V1.1-2020-21 57/ 86


Verilog www.cranesvarsity.com

Both tasks and functions must be defined in a module and are local to the module. Tasks are used for
common Verilog code that contains delays, timing, event constructs, or multiple output arguments.
Functions are used when common Verilog code is purely combinational, executes in zero simulation time
and provides exactly one output. Functions are typically used for conversions and commonly used
calculations.

Tasks can have input, output, and inout ports; functions can have input ports. In addition, they can have
local variables, registers, time variables, integers, real, or events. Tasks or functions cannot have wires.
Tasks and functions contain behavioral statements only. Tasks and functions do not contain always or i n
i t i a l statements but are called from always blocks, i n i t i a l blocks, or other tasks and functions.

Tasks
Tasks are declared with the keywords task and endtask. Tasks must be used if any one of the following
conditions is true for the procedure. There are delay, timing, or event control constructs in the procedure.
The procedure has zero or more than one output arguments.
The procedure has no input arguments.

//define a module called operation that contains the task bitwise-operation:

module operation;
...
...
parameter delay = 10;
reg [15:0] A, B;
reg [ 15 : 0 ] AB-AND, AB-OR, AB-XOR;

always @(A or B) //whenever A or B changes in value


begin
bitwise-oper(AB-AND, AB-OR, AB-XOR, A, B);
end
...
...

© Cranes Varsity V1.1-2020-21 58/ 86


Verilog www.cranesvarsity.com

//define task bitwise-oper

task bitwise-oper;
output [15:01 ab-and, ab-or, ab-xor; //outputs from the task
input [15:0] a, b; //inputs to the task
begin
#delay ab-and = a & b;
ab-or = a | b;
ab-xor = a ^ b;
end
endtask
...
Endmodule

Functions
Functions are declared with the keywords function and endfunction. Functions are used if all of the
following conditions are true for the procedure. There are no delay, timing, or event control constructs in
the procedure. The procedure returns a single value. There is at least one input argument.

//Define a module that contains the function shift

module shifter:
,..
//Left/right shifter
'define LEFT-SHIFT l'bO
'define RIGHT-SHIFT l'bl
reg [31:0] addr, left-addr, right-addr;
reg control;
//Compute the right- and left-shifted values
// whenever a new address value appears
always @ (addr )
begin
//call the function defined below to do left and right shift.

© Cranes Varsity V1.1-2020-21 59/ 86


Verilog www.cranesvarsity.com

left-addr = shift(addr, 'LEFT-SHIFT);


right-addr = shift(addr, 'RIGHT-SHIFT);

end

//define shift function. The output is a 32-bit value.

Eunction [3l: 01 shift;


input [31:01 address;
input control;
begin

shift = (control == 'LEFT-SHIFT) ?(address << 1) : (address>> 1);

endfunction
endmodule

© Cranes Varsity V1.1-2020-21 60/ 86


Verilog www.cranesvarsity.com

Chapter 10
Design of digital devices

Shift Registers

Flip-flop is a 1 bit memory cell which can be used for storing the digital data. To increase the storage
capacity in terms of number of bits, we have to use a group of flip-flop. Such a group of flip-flop is
known as a Register. The n-bit register will consist of n number of flip-flop and it is capable of storing
an n-bit word.

The binary data in a register can be moved within the register from one flip-flop to another. The registers
that allow such data transfers are called as shift registers. There are four mode of operations of a shift
register.

 Serial Input Serial Output

 Serial Input Parallel Output

 Parallel Input Serial Output

 Parallel Input Parallel Output

Serial Input Serial Output

 Let all the flip-flop be initially in the reset condition i.e. Q3 = Q2 = Q1 = Q0 = 0. If an entry of a
four bit binary number 1 1 1 1 is made into the register, this number should be applied to Din bit
with the LSB bit applied first. The D input of FF-3 i.e. D3 is connected to serial data input Din.
Output of FF-3 i.e. Q3 is connected to the input of the next flip-flop i.e. D2 and so on.

Block Diagram

Operation

© Cranes Varsity V1.1-2020-21 61/ 86


Verilog www.cranesvarsity.com

Before application of clock signal, let Q3 Q2 Q1 Q0 = 0000 and apply LSB bit of the number to be entered
to Din. So Din = D3 = 1. Apply the clock. On the first falling edge of clock, the FF-3 is set, and stored
word in the register is Q3 Q2 Q1 Q0 = 1000.

Apply the next bit to Din. So Din = 1. As soon as the next negative edge of the clock hits, FF-2 will set
and the stored word change to Q3 Q2 Q1 Q0 = 1100.

Apply the next bit to be stored i.e. 1 to Din. Apply the clock pulse. As soon as the third negative clock
edge hits, FF-1 will be set and output will be modified to Q3 Q2 Q1 Q0 = 1110.

Similarly with Din = 1 and with the fourth negative clock edge arriving, the stored word in the register is
Q3 Q2 Q1 Q0 = 1111.

© Cranes Varsity V1.1-2020-21 62/ 86


Verilog www.cranesvarsity.com

Truth Table

Waveforms

Serial Input Parallel Output

 In such types of operations, the data is entered serially and taken out in parallel fashion.

 Data is loaded bit by bit. The outputs are disabled as long as the data is loading.

 As soon as the data loading gets completed, all the flip-flops contain their required data, the
outputs are enabled so that all the loaded data is made available over all the output lines at the
same time.

 4 clock cycles are required to load a four bit word. Hence the speed of operation of SIPO mode
is same as that of SISO mode.

Block Diagram

© Cranes Varsity V1.1-2020-21 63/ 86


Verilog www.cranesvarsity.com

Parallel Input Serial Output (PISO)

 Data bits are entered in parallel fashion.

 The circuit shown below is a four bit parallel input serial output register.

 Output of previous Flip Flop is connected to the input of the next one via a combinational circuit.

 The binary input word B0, B1, B2, B3 is applied though the same combinational circuit.

 There are two modes in which this circuit can work namely - shift mode or load mode.

Load mode

When the shift/load bar line is low (0), the AND gate 2, 4 and 6 become active they will pass B 1, B2,
B3 bits to the corresponding flip-flops. On the low going edge of clock, the binary input B0, B1, B2,
B3 will get loaded into the corresponding flip-flops. Thus parallel loading takes place.

Shift mode

When the shift/load bar line is low (1), the AND gate 2, 4 and 6 become inactive. Hence the parallel
loading of the data becomes impossible. But the AND gate 1,3 and 5 become active. Therefore the
shifting of data from left to right bit by bit on application of clock pulses. Thus the parallel in serial out
operation takes place.

Block Diagram

© Cranes Varsity V1.1-2020-21 64/ 86


Verilog www.cranesvarsity.com

Parallel Input Parallel Output (PIPO)

In this mode, the 4 bit binary input B0, B1, B2, B3 is applied to the data inputs D0, D1, D2, D3 respectively
of the four flip-flops. As soon as a negative clock edge is applied, the input binary bits will be loaded
into the flip-flops simultaneously. The loaded bits will appear simultaneously to the output side. Only
clock pulse is essential to load all the bits.

Block Diagram

Frequency Divider
Another useful feature of the D-type Flip-Flop is as a binary divider, for Frequency Division or as a
“divide-by-2” counter. Here the inverted output terminal Q (NOT-Q) is connected directly back to the
Data input terminal D giving the device “feedback” as shown below.

© Cranes Varsity V1.1-2020-21 65/ 86


Verilog www.cranesvarsity.com

Divide-by-2 Counter

It can be seen from the frequency waveforms above, that by “feeding back” the output from Q to the input
terminal D, the output pulses at Q have a frequency that are exactly one half ( ƒ ÷ 2 ) that of the input
clock frequency. In other words the circuit produces Frequency Division as it now divides the input
frequency by a factor of two (an octave).

Memory Modeling

A memory is just like a human brain. It is used to store data and instruction. Computer memory
is the storage space in computer where data is to be processed and instructions required for processing
are stored.The memory is divided into large number of small parts. Each part is called a cell. Each
location or cell has a unique address which varies from zero to memory size minus one.

For example if computer has 64k words, then this memory unit has 64 * 1024 = 65536 memory
location. The address of these locations varies from 0 to 65535.

Memory is primarily of two types

 Internal Memory − cache memory and primary/main memory

 External Memory − magnetic disk / optical disk etc.

RAM

© Cranes Varsity V1.1-2020-21 66/ 86


Verilog www.cranesvarsity.com

A RAM constitutes the internal memory of the CPU for storing data, program and program
result. It is read/write memory. It is called random access memory (RAM).Since access time in RAM is
independent of the address to the word that is, each storage location inside the memory is as easy to
reach as other location & takes the same amount of time. We can reach into the memory at random &
extremely fast but can also be quite expensive.

RAM is volatile, i.e. data stored in it is lost when we switch off the computer or if there is a
power failure. Hence, a backup uninterruptible power system (UPS) is often used with computers. RAM
is small, both in terms of its physical size and in the amount of data it can hold.

RAM is of two types

 Static RAM (SRAM)

 Dynamic RAM (DRAM)

ROM

ROM stands for Read Only Memory. The memory from which we can only read but cannot write on it.
This type of memory is non-volatile. The information is stored permanently in such memories during
manufacture.

A ROM, stores such instruction as are required to start computer when electricity is first turned on, this
operation is referred to as bootstrap. ROM chip are not only used in the computer but also in other
electronic items like washing machine and microwave oven.

© Cranes Varsity V1.1-2020-21 67/ 86


Verilog www.cranesvarsity.com

Following are the various types of ROM −

MROM (Masked ROM)

The very first ROMs were hard-wired devices that contained a pre-programmed set of data or
instructions. These kind of ROMs are known as masked ROMs. It is inexpensive ROM.

PROM (Programmable Read Only Memory)

PROM is read-only memory that can be modified only once by a user. The user buys a blank PROM and
enters the desired contents using a PROM programmer. Inside the PROM chip there are small fuses
which are burnt open during programming. It can be programmed only once and is not erasable.

EPROM (Erasable and Programmable Read Only Memory)

The EPROM can be erased by exposing it to ultra-violet light for a duration of upto 40 minutes. Usually,
an EPROM eraser achieves this function. During programming an electrical charge is trapped in an
insulated gate region. The charge is retained for more than ten years because the charge has no leakage
path. For erasing this charge, ultra-violet light is passed through a quartz crystal window (lid). This
exposure to ultra-violet light dissipates the charge. During normal use the quartz lid is sealed with a
sticker.

EEPROM (Electrically Erasable and Programmable Read Only Memory)

The EEPROM is programmed and erased electrically. It can be erased and reprogrammed about ten
thousand times. Both erasing and programming take about 4 to 10 ms (millisecond). In EEPROM, any
location can be selectively erased and programmed. EEPROMs can be erased one byte at a time, rather
than erasing the entire chip. Hence, the process of re-programming is flexible but slow.

© Cranes Varsity V1.1-2020-21 68/ 86


Verilog www.cranesvarsity.com

Error Detection in Computer Networks

Error
A condition when the receiver’s information does not match with the sender’s information. During
transmission, digital signals suffer from noise that can introduce errors in the binary bits travelling from
sender to receiver. That means a 0 bit may change to 1 or a 1 bit may change to 0.

Types of Errors

There may be three types of errors:

 Single bit error

In a frame, there is only one bit, anywhere though, which is corrupt.

 Multiple bits error

Frame is received with more than one bits in corrupted state.

 Burst error

Frame contains more than1 consecutive bits corrupted.

Error control mechanism may involve two possible ways:

 Error detection

 Error correction

 Error Detecting Codes (Implemented either at Data link layer or Transport Layer of OSI Model)
Whenever a message is transmitted, it may get scrambled by noise or data may get corrupted. To

© Cranes Varsity V1.1-2020-21 69/ 86


Verilog www.cranesvarsity.com

avoid this, we use error-detecting codes which are additional data added to a given digital
message to help us detect if any error has occurred during transmission of the message.
 Basic approach used for error detection is the use of redundancy bits, where additional bits are
added to facilitate detection of errors.
 Some popular techniques for error detection are:
1. Simple Parity check
2. Two-dimensional Parity check
3. Checksum
4. Cyclic redundancy check

Cyclic redundancy check (CRC)


An error detection mechanism in which a special number is appended to a block of data in order to detect
any changes introduced during storage (or transmission). The CRe is recalculated on retrieval (or
reception) and compared to the value originally transmitted, which can reveal certain types of error. For
example, a single corrupted bit in the data results in a one-bit change in the calculated CRC, but multiple
corrupt bits may cancel each other out.

Requirements of CRC :

A CRC will be valid if and only if it satisfies the following requirements:

1. It should have exactly one less bit than divisor.


2. Appending the CRC to the end of the data unit should result in the bit sequence which is exactly
divisible by the divisor.

The various steps followed in the CRC method are

1. A string of n as is appended to the data unit. The length of predetermined divisor is n+ 1.

2. The newly formed data unit i.e. original data + string of n as are divided by the divisor using binary
division and remainder is obtained. This remainder is called CRC.

3. Now, string of n Os appended to data unit is replaced by the CRC remainder (which is also of n bit).

4. The data unit + CRC is then transmitted to receiver.

5. The receiver on receiving it divides data unit + CRC by the same divisor & checks the remainder.

6. If the remainder of division is zero, receiver assumes that there is no error in data and it accepts it.

© Cranes Varsity V1.1-2020-21 70/ 86


Verilog www.cranesvarsity.com

7. If remainder is non-zero then there is an error in data and receiver rejects it.

UART

UART stands for Universal Asynchronous Receiver/Transmitter. A UART’s main purpose is to transmit
and receive serial data.

One of the best things about UART is that it only uses two wires to transmit data between devices.
In UART communication, two UARTs communicate directly with each other. The transmitting UART
converts parallel data from a controlling device like a CPU into serial form, transmits it in serial to the
receiving UART, which then converts the serial data back into parallel data for the receiving device. Only
two wires are needed to transmit data between two UARTs. Data flows from the Tx pin of the
transmitting UART to the Rx pin of the receiving UART:

UARTs transmit data asynchronously, which means there is no clock signal to synchronize the
output of bits from the transmitting UART to the sampling of bits by the receiving UART. Instead of a

© Cranes Varsity V1.1-2020-21 71/ 86


Verilog www.cranesvarsity.com

clock signal, the transmitting UART adds start and stop bits to the data packet being transferred. These
bits define the beginning and end of the data packet so the receiving UART knows when to start reading
the bits.When the receiving UART detects a start bit, it starts to read the incoming bits at a
specific frequency known as the baud rate. Baud rate is a measure of the speed of data transfer, expressed
in bits per second (bps). Both UARTs must operate at about the same baud rate. The baud rate between
the transmitting and receiving UARTs can only differ by about 10% before the timing of bits gets too far
off.
The UART that is going to transmit data receives the data from a data bus. The data bus is used to
send data to the UART by another device like a CPU, memory, or microcontroller. Data is transferred
from the data bus to the transmitting UART in parallel form. After the transmitting UART gets
the parallel data from the data bus, it adds a start bit, a parity bit, and a stop bit, creating the data packet.
Next, the data packet is output serially, bit by bit at the Tx pin. The receiving UART reads the data packet
bit by bit at its Rx pin. The receiving UART then converts the data back into parallel form and
removes the start bit, parity bit, and stop bits. Finally, the receiving UART transfers the data packet in
parallel to the data bus on the receiving end:

UART transmitted data is organized into packets. Each packet contains 1 start bit, 5 to 9 data bits
(depending on the UART), an optional parity bit, and 1 or 2 stop bits:

Start Bit
The UART data transmission line is normally held at a high voltage level when it’s
not transmitting data. To start the transfer of data, the transmitting UART pulls the transmission line from

© Cranes Varsity V1.1-2020-21 72/ 86


Verilog www.cranesvarsity.com

high to low for one clock cycle. When the receiving UART detects the high to low voltage transition, it
begins reading the bits in the data frame at the frequency of the baud rate.

Data Frame
The data frame contains the actual data being transferred. It can be 5 bits up to 8 bits long if a
parity bit is used. If no parity bit is used, the data frame can be 9 bits long. In most cases, the data is sent
with the least significant bit first.

Parity
Parity describes the evenness or oddness of a number. The parity bit is a way for the receiving
UART to tell if any data has changed during transmission. Bits can be changed by electromagnetic
radiation, mismatched baud rates, or long distance data transfers. After the receiving UART reads the data
frame, it counts the number of bits with a value of 1 and checks if the total is an even or odd number. If
the parity bit is a 0 (even parity), the 1 bits in the data frame should total to an even number. If the parity
bit is a 1 (odd parity), the 1 bits in the data frame should total to an odd number. When the parity bit
matches the data, the UART knows that the transmission was free of errors. But if the parity bit is a 0, and
the total is odd; or the parity bit is a 1, and the total is even, the UART knows that bits in the data frame
have changed.
Stop Bits
To signal the end of the data packet, the sending UART drives the data transmission line from a
low voltage to a high voltage for at least two bit durations.
Steps of UART Transmission

1. The transmitting UART receives data in parallel from the data bus:

2. The transmitting UART adds the start bit, parity bit, and the stop bit(s) to the data frame:

© Cranes Varsity V1.1-2020-21 73/ 86


Verilog www.cranesvarsity.com

3. The entire packet is sent serially from the transmitting UART to the receiving UART. The
receiving UART samples the data line at the pre-configured baud rate:

4. The receiving UART discards the start bit, parity bit, and stop bit from the data frame:

5. The receiving UART converts the serial data back into parallel and transfers it to the data bus on
the receiving end:

© Cranes Varsity V1.1-2020-21 74/ 86


Verilog www.cranesvarsity.com

Advantages
1. Only uses two wires
2. No clock signal is necessary
3. Has a parity bit to allow for error checking
4. The structure of the data packet can be changed as long as both sides are set up for it
5. Well documented and widely used method
Disadvantages

1. The size of the data frame is limited to a maximum of 9 bits

2. Doesn’t support multiple slave or multiple master systems

3. The baud rates of each UART must be within 10% of each other

SPI Protocol
SPI is a common communication protocol used by many different devices. For example, SD card
modules, RFID card reader modules, and 2.4 GHz wireless transmitter/receivers all use SPI to
communicate with microcontrollers.
One unique benefit of SPI is the fact that data can be transferred without interruption. Any number of bits
can be sent or received in a continuous stream. With I2C and UART, data is sent in packets, limited to a
specific number of bits. Start and stop conditions define the beginning and end of each packet, so the data
is interrupted during transmission.

Devices communicating via SPI are in a master-slave relationship. The master is the controlling device
(usually a microcontroller), while the slave (usually a sensor, display, or memory chip) takes instruction
from the master. The simplest configuration of SPI is a single master, single slave system, but one master
can control more than one slave (more on this below).

MOSI (Master Output/Slave Input) – Line for the master to send data to the slave.

© Cranes Varsity V1.1-2020-21 75/ 86


Verilog www.cranesvarsity.com

MISO (Master Input/Slave Output) – Line for the slave to send data to the master.
SCLK (Clock) – Line for the clock signal.
SS/CS (Slave Select/Chip Select) – Line for the master to select which slave to send data to.

Wires used 4
Maximum speed Upto 10Mbps
Synchronous / Asynchronous Synchronous
Serial / Parallel Serial
Maximum no. of master 1
Maximum no. of slave Theoretically unlimited

SPI working
The Clock
The clock signal synchronizes the output of data bits from the master to the sampling of bits by the slave.
One bit of data is transferred in each clock cycle, so the speed of data transfer is determined by the
frequency of the clock signal. SPI communication is always initiated by the master since the master
configures and generates the clock signal.

Any communication protocol where devices share a clock signal is known as synchronous. SPI is a
synchronous communication protocol. There are also asynchronous methods that don’t use a clock signal.
For example, in UART communication, both sides are set to a pre-configured baud rate that dictates the
speed and timing of data transmission.
The clock signal in SPI can be modified using the properties of clock polarity and clock phase. These two
properties work together to define when the bits are output and when they are sampled. Clock polarity can
be set by the master to allow for bits to be output and sampled on either the rising or falling edge of the
clock cycle. Clock phase can be set for output and sampling to occur on either the first edge or second
edge of the clock cycle, regardless of whether it is rising or falling.

Slave Select
The master can choose which slave it wants to talk to by setting the slave’s CS/SS line to a low
voltage level. In the idle, non-transmitting state, the slave select line is kept at a high voltage level.
Multiple CS/SS pins may be available on the master, which allows for multiple slaves to be wired in
parallel. If only one CS/SS pin is present, multiple slaves can be wired to the master by daisy-chaining.

© Cranes Varsity V1.1-2020-21 76/ 86


Verilog www.cranesvarsity.com

Multiple Slave
SPI can be set up to operate with a single master and a single slave, and it can be set up with multiple
slaves controlled by a single master. There are two ways to connect multiple slaves to the master. If the
master has multiple slave select pins, the slaves can be wired in parallel like this:

If only one slave select pin is available, the slaves can be daisy-chained like this:

MOSI AND MISO


The master sends data to the slave bit by bit, in serial through the MOSI line. The slave receives the data
sent from the master at the MOSI pin. Data sent from the master to the slave is usually sent with the most
significant bit first.

The slave can also send data back to the master through the MISO line in serial. The data sent from the
slave back to the master is usually sent with the least significant bit first.

© Cranes Varsity V1.1-2020-21 77/ 86


Verilog www.cranesvarsity.com

Steps of SPI Data Transmission


1. The master outputs the clock signal:

2. The master switches the SS/CS pin to a low voltage state, which activates the slave:

3. The master sends the data one bit at a time to the slave along the MOSI line. The slave reads
the bits as they are received:

4. If a response is needed, the slave returns data one bit at a time to the master along the MISO
line. The master reads the bits as they are received:

Advantages

1. No start and stop bits, so the data can be streamed continuously without interruption

2. No complicated slave addressing system like I2C

© Cranes Varsity V1.1-2020-21 78/ 86


Verilog www.cranesvarsity.com

3. Higher data transfer rate than I2C (almost twice as fast)

4. Separate MISO and MOSI lines, so data can be sent and received at the same time

Disadvantages

1. Uses four wires (I2C and UARTs use two)

2. No acknowledgement that the data has been successfully received (I2C has this)

3. No form of error checking like the parity bit in UART

4. Only allows for a single master

Introduction to I2C communication

I2C combines the best features of SPI and UARTs. With I2C, you can connect multiple
slaves to a single master (like SPI) and you can have multiple masters controlling single, or
multiple slaves. This is really useful when you want to have more than one microcontroller
logging data to a single memory card or displaying text to a single LCD.

Like UART communication, I2C only uses two wires to transmit data between devices:

SDA (Serial Data) – The line for the master and slave to send and receive data.
SCL (Serial Clock) – The line that carries the clock signal.
I2C is a serial communication protocol, so data is transferred bit by bit along a single wire (the
SDA line).

© Cranes Varsity V1.1-2020-21 79/ 86


Verilog www.cranesvarsity.com

Like SPI, I2C is synchronous, so the output of bits is synchronized to the sampling of bits by a
clock signal shared between the master and the slave. The clock signal is always controlled by
the master.

Wires used 2
Maximum speed Standard Mode = 100kbps
Fast mode = 400kbps
High speed mode = 3.4 Mbps
Ultra fast mode = 5Mbps
Synchronous / Asynchronous Synchronous
Serial / Parallel Serial
Maximum no. of master unlimited
Maximum no. of slave 1008

I2C WORKING
With I2C, data is transferred in messages. Messages are broken up into frames of data.
Each message has an address frame that contains the binary address of the slave, and one or more
data frames that contain the data being transmitted. The message also includes start and stop
conditions, read/write bits, and ACK/NACK bits between each data frame:

Start Condition: The SDA line switches from a high voltage level to a low voltage
level before the SCL line switches from high to low.
Stop Condition: The SDA line switches from a low voltage level to a high voltage
level after the SCL line switches from low to high.
Address Frame: A 7 or 10 bit sequence unique to each slave that identifies the slave when
the master wants to talk to it.
Read/Write Bit: A single bit specifying whether the master is sending data to the slave (low
voltage level) or requesting data from it (high voltage level).

© Cranes Varsity V1.1-2020-21 80/ 86


Verilog www.cranesvarsity.com

ACK/NACK Bit: Each frame in a message is followed by an acknowledge/no-acknowledge bit.


If an address frame or data frame was successfully received, an ACK bit is returned to the sender
from the receiving device.
Addressing
I2C doesn’t have slave select lines like SPI, so it needs another way to let the slave know
that data is being sent to it, and not another slave. It does this by addressing. The address frame
is always the first frame after the start bit in a new message.
The master sends the address of the slave it wants to communicate with to every slave connected
to it. Each slave then compares the address sent from the master to its own address. If the address
matches, it sends a low voltage ACK bit back to the master. If the address doesn’t match, the
slave does nothing and the SDA line remains high.

Read/Write Bit

The address frame includes a single bit at the end that informs the slave whether the master
wants to write data to it or receive data from it. If the master wants to send data to the slave, the
read/write bit is a low voltage level. If the master is requesting data from the slave, the bit is a
high voltage level.

Data Frame

After the master detects the ACK bit from the slave, the first data frame is ready to be sent.The
data frame is always 8 bits long, and sent with the most significant bit first. Each data frame is
immediately followed by an ACK/NACK bit to verify that the frame has been received
successfully. The ACK bit must be received by either the master or the slave (depending on who
is sending the data) before the next data frame can be sent.

After all of the data frames have been sent, the master can send a stop condition to the slave to
halt the transmission. The stop condition is a voltage transition from low to high on the SDA line
after a low to high transition on the SCL line, with the SCL line remaining high.

Steps of I2C Data Transmission

© Cranes Varsity V1.1-2020-21 81/ 86


Verilog www.cranesvarsity.com

1. The master sends the start condition to every connected slave by switching the SDA line from
a high voltage level to a low voltage level before switching the SCL line from high to low:

2. The master sends each slave the 7 or 10 bit address of the slave it wants to communicate with,
along with the read/write bit:

© Cranes Varsity V1.1-2020-21 82/ 86


Verilog www.cranesvarsity.com

3. Each slave compares the address sent from the master to its own address. If the address
matches, the slave returns an ACK bit by pulling the SDA line low for one bit. If the address
from the master does not match the slave’s own address, the slave leaves the SDA line high.

4. The master sends or receives the data frame:

5. After each data frame has been transferred, the receiving device returns another ACK bit to the
sender to acknowledge successful receipt of the frame:

© Cranes Varsity V1.1-2020-21 83/ 86


Verilog www.cranesvarsity.com

6. To stop the data transmission, the master sends a stop condition to the slave by switching SCL
high before switching SDA high:

Single Master with Multiple Slave


Because I2C uses addressing, multiple slaves can be controlled from a single master. With a 7 bit
address, 128 (27) unique address are available. Using 10 bit addresses is uncommon, but provides
1,024 (210) unique addresses. To connect multiple slaves to a single master, wire them like this,
with 4.7K Ohm pull-up resistors connecting the SDA and SCL lines to Vcc:

© Cranes Varsity V1.1-2020-21 84/ 86


Verilog www.cranesvarsity.com

Multiple Master With Multiple Slave

Multiple masters can be connected to a single slave or multiple slaves. The problem with
multiple masters in the same system comes when two masters try to send or receive data at the
same time over the SDA line. To solve this problem, each master needs to detect if the SDA line
is low or high before transmitting a message. If the SDA line is low, this means that another
master has control of the bus, and the master should wait to send the message. If the SDA line is
high, then it’s safe to transmit the message. To connect multiple masters to multiple slaves, use
the following diagram, with 4.7K Ohm pull-up resistors connecting the SDA and SCL lines to
Vcc:

© Cranes Varsity V1.1-2020-21 85/ 86


Verilog www.cranesvarsity.com

Advantages
1. Only uses two wires
2. Supports multiple masters and multiple slaves
3. ACK/NACK bit gives confirmation that each frame is transferred successfully
4. Hardware is less complicated than with UARTs
5. Well known and widely used protocol
Disadvantages
1. Slower data transfer rate than SPI
2. The size of the data frame is limited to 8 bits
3. More complicated hardware needed to implement than SPI

© Cranes Varsity V1.1-2020-21 86/ 86

You might also like