Course Material Verilog Module
Course Material Verilog Module
com
VERILOG
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
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
Physical design
Fabrication
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.
• 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
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
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
Chapter – 2
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.
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.
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.
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).
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.
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>.
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.
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.
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.
Chapter - 3
Data types
Value Set
Verilog supports four values and eight strengths to model the functionality of real hardware.
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:
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;
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).
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.
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
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.
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.
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.
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.
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.
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.
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)
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.
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
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 :
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
Replication Operator
The replication operator makes multiple copies of an item.
Operators
{n{item}} (n fold replication of an item)
Example :
For synthesis, Synopsis did not like a zero replication. For example:-
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 */
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:
quotes (“ “).
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 :
Wires, regs and parameters can also be used as operands in Verilog expressions.
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]
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 :
Chapter 5
Module
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.
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:
Each port in the port list is defined as input, output, or inout, based on the direction of the port signal.
Example :
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.
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.
input c-in;
...
<module internals>
...
Endmodule
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.
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.
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.
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.
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,
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.
Example :
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.
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.
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 delay
The rise delay is associated with a gate output transition to a 1 from another value.
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.
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.
/ / One delay
/ / if +mindelays, delay= 4
/ / if +typdelays, delay= 5
/ / if +maxdelays, delay= 6
/ / 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
/ / 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
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;
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.
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.
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.
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.
wire out;
assign out = in1 & in2;
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 Delays
wire # 10 out;
assign out = in1 & in2;
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.
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.
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
initial
begin
#5 a = l'bl; //multiple statements; need to be grouped
#25 b = llbO;
end
initial
begin
#l0 X = llbO;
#25 y = l'bl;
end
initial
#50 $finish;
endmodule
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;
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.
place after a common event. Consider the following example where three concurrent data transfers take
place at the positive edge of clock.
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.
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
reg X, y, z;
initial
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
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
case Statement
The keywords case, endcase, and default are used in the case statement.
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.
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
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
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.
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.
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.
Tasks and functions serve different purposes in Verilog. We discuss tasks and functions in greater detail
in the following sections.
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.
module operation;
...
...
parameter delay = 10;
reg [15:0] A, B;
reg [ 15 : 0 ] AB-AND, AB-OR, AB-XOR;
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.
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.
end
endfunction
endmodule
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.
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
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.
Truth Table
Waveforms
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
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
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.
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.
RAM
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.
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.
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 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.
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.
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.
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
Burst error
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
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
Requirements of CRC :
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).
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.
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
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
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:
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:
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
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.
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.
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:
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.
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
4. Separate MISO and MOSI lines, so data can be sent and received at the same time
Disadvantages
2. No acknowledgement that the data has been successfully received (I2C has this)
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).
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).
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.
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:
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.
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:
6. To stop the data transmission, the master sends a stop condition to the slave by switching SCL
high before switching SDA high:
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:
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