0% found this document useful (0 votes)
21 views126 pages

Kcs Verilog 22-23 P21ec404 Unit-1

The document outlines the basic concepts of digital design using Verilog HDL, including lexical conventions, data types, modules, and ports. It covers various modeling techniques such as gate-level and dataflow modeling, as well as system tasks and compiler directives. Additionally, it explains the representation of numbers, operators, and the use of nets and registers in Verilog for hardware design.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views126 pages

Kcs Verilog 22-23 P21ec404 Unit-1

The document outlines the basic concepts of digital design using Verilog HDL, including lexical conventions, data types, modules, and ports. It covers various modeling techniques such as gate-level and dataflow modeling, as well as system tasks and compiler directives. Additionally, it explains the representation of numbers, operators, and the use of nets and registers in Verilog for hardware design.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 126

DIGITAL DESIGN USING VERILOG HDL

(P18EC43)

UNIT-I: Basic Concepts


COURSE CONTENT
• Basic Concepts: Lexical Conventions.
• Data Types. System Tasks and Compiler Directives.
• Modules and Ports: Modules.
• Ports.
• Hierarchical Names.
• Gate-Level Modeling: Gate Types.
• Gate Delays.
• Dataflow Modeling: Continuous Assignments.
• Delays.
• Expressions,
• Operators, and Operands.
• Operator Types. Examples.
Learning Objectives
• Understand lexical conventions for operators,
comments, whitespace, numbers, strings, and
identifiers.
• Define the logic value set and data types such as nets,
registers, vectors, numbers, simulation time, arrays,
parameters, memories, and strings.
• Identify useful system tasks for displaying and
monitoring information, and for stopping and
finishing the simulation.
• Learn basic compiler directives to define macros and
include files.
Typical Design Flow
Operators Number Specification

Lexical
convention
Whitespace Comments

Basic concepts
`define `include
Value set strength level
System tasks and
Complier Data Types
directives
Nets Registers Integer Real
$display $monitor $stop $finish
Lexical Conventions
Whitespace
Blank spaces (\b)
Tabs (\t)
Newlines (\n) comprise the whitespace.
Comments
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
a = ~ b; // ~ is a unary operator. b is the operand
Binary
a = b && c; // && is a binary operator. b and c are operands

Ternary
a = b ? c : d; // ?: is a ternary operator. b, c and d are
operands
Number Specification
Sized numbers
Sized numbers are represented as
<size> ‘<base format> <number>.
4'b1111 // This is a 4-bit binary number
12'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
'021 // This is a 32-bit octal number
X or Z values
12’h13x // This is a 12-bit hex number; 4 least significant
bits unknown
6’hx //This is a 6-bit hex number
32'bz //This is a 32-bit high impedance number

Negative numbers
-8'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.

12'b1111_0000_1010 // Use of underline characters


for readability
4'b10?? // Equivalent of a 4'b10zz
Strings
"Hello Verilog World" // is a string
“a / b” // is a string
Identifiers and Keywords
Keywords are special identifiers reserved to define the
language constructs.
Identifiers are names given to objects so that they can be
referenced in the design.
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).
• Escaped identifiers are used when translating the Verilog
source from some other design representation which
allows funny characters in names.

\wire*
\busa+index
\-clock
\***error-condition***
\net1/\net2
Data Types
Value Set
Value Level Condition in Hardware Circuits
0 Logic zero, false condition
1 Logic one, true condition
X Unknown value
Z High impedance, floating state
Strength Levels
Strength Level TYPE Degree

supply Driving strongest


strong Driving
pull Driving
large Storage
weak Driving
medium Storage
small Storage
highz High Impedance weakest
If two signals of unequal strengths are driven on a
wire, the stronger signal prevails.
For example, if two signals of strength strong1 and
weak0 contend, the result is resolved as a strong1.
If two signals of equal strengths are driven on a
wire, the result is unknown.
If two signals of strength strong1 and strong0
conflict, the result is an X
Nets
Nets represent connections between hardware elements.
Just as in real circuits, nets have values continuously driven
on them by the outputs of devices that they are connected
to.
Nets are declared primarily with the keyword wire.
The terms wire and net are often used interchangeably.
The default value of a net is Z (except the trireg net, which
defaults to X ).
wire O; // Declare net a for the above circuit
wire b, c; // Declare two wires b,c for the above circuit
wire d = l’b0; // Net d is fixed to logic value 0 at declaration.
tri
The keywords wire and tri have identical syntax and
function.
Separate names are provided to indicate the purpose of
the net.
Keyword wire denotes nets with single drivers, and tri is
denotes nets that have multiple drivers.
module mux(out, a, b, control) ;
output out;
input a, b, control;
tri out;
wire a, b, control;
bufif0 b1 (out, a, control) ; //drives a when control = 0; z otherwise
bufif1 b2 (out, b, control) ; //drives b when control = 1; z otherwise
endmodule
Trireg
Keyword trireg is used to model nets having capacitance
that stores values. The default strength for trireg nets is
medium.
Driven state- At least one driver drives a 0, 1, or X value
on the net. The value is continuously stored in the trireg
net. It takes the strength of the driver.
Capacitive state- All drivers on the net have high
impedance (z) value. The net holds the last driven value
The strength is small, medium, or large (default is
medium).
trireg (large) out;
wire a, control;
bufif1(out, a, control); // net out gets value of a when control
= 1;
//when control = 0, out retains last value
// of a instead of going to z. strength is large.
tri0 and tri1
Keywords tri0 and tri1 are used to model resistive
pulldown and pullup devices.
A tri0 net has a value 0 if nothing is driving the net.
Similarly, tri1 net has a value 1 if nothing is driving the
net. The default strength is pull.
tri0 out;
wire a, control;
bufif1 (out, a, control) ; //net out gets the value of a when control = 1;
//when control = 0, out gets the value 0
// instead of z. If out were declared as tri1, the
//default value of out would be 1 instead of 0.

supply0 and supply1


supply1 vcc; //all nets connected to vcc are connected to power supply
supply0 gnd; //all nets connected to gnd are connected to ground
wor, wand, trior, and triand
When there is logic contention, if we simply use a tri
net, we will get an X. This could be indicative of a
design problem.
Keywords wor, wand, trior, and triand are used to
resolve such conflicts. Nets wand perform the and
operation on multiple driver logic values. If any value is
0, the value of the net wand is 0.
Net wor performs the or operation on multiple driver
values. If any
wand value is 1, the net wor is 1.
out1;
wor out2;
buf (out1, 1'bO);
buf (out1, 1'b1); //out1 is a wand net; gets the final value 1'b0
buf (out2, 1'bO);
buf (out2, 1'b1); //out2 is a wor net; gets the final value 1'b1
Registers
 Registers represent data storage elements. Registers retain value
until another value is placed onto them.
 Unlike a net, a register does not need a driver. Verilog registers
do not need a clock as hardware registers do.
 Values of registers can be changed anytime in a simulation by
assigning a new value to the register
 Register data types are commonly declared by the keyword reg.
The default value for a reg data type is X.
reg reset; // declare a variable reset that can hold its value
initial // this construct will be discussed later
begin
reset = 1'b1; //initialize reset to 1 to reset the digital circuit.
#100 reset = 1'b0; // after 100 time units reset is deasserted.
end
Vectors
 Nets or reg data types can be declared as vectors (multiple
bit widths). If bit width is not specified, the default is scalar
(1-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.
Vector Part Select

busA[7] // bit # 7 of vector busA


bus[2:0] // Three least significant bits of vector bus,
// using bus[0:2] is illegal because the significant bit
//should always be on the left of a range
specification

Virtual_addr[0:1] //TWO most significant bits of


vector virtual_addr
Variable Vector Part Select
This allows part selects to put in for loop to select
various parts of the vector.
There are two special part-select operators
[<starting_bit> +:width]- part-select increments from staring bit
[<starting_bit> -:width]- part-select decrements from staring bit
reg [255:0] datal; //Little endian notation
reg [0:255] data2; //Big endian notation
reg [7:0] byte;
//Using a variable part select, one can choose parts
byte = datal[31~:8] ; //starting bit = 31, width =8 => data[31:24]
byte = datal[24+:8] ; //starting bit = 24, width =8 => data[31:24]
byte = data2[31-:8] ; //starting bit = 31, width =8 => data[24:31]
byte = data2[24+:8] ; //starting bit ^ 24, width =8 => da'ta [24:31]
//The starting bit can also be a variable. The width has
//to be constant. Therefore, one can use the variable part select
//in a loop to select all bytes of the vector.
for (j=0; j<=31; j=j+l)
byte'='datal["(j*8)+:8]; //Sequence is [7:0], [15:8]... [255:248]
//Can initialize a part of the vector
datal [ (byteNum*8) +: 8] = 8-b0; //If byteNum=1, clear 8 bits
[15:8]
Integer
 An integer is a general purpose register data type
used for manipulating quantities.
 Integers are declared by the keyword integer.
 The default width for an integer is the host-machine
word size, which is implementation specific but is at
least 32 bits.
 Registers declared as data type reg store values as
unsigned quantities, whereas integers store values as
signed quantities.
integer counter; // general purpose variable used as a counter.
initial
counter = -1; // A negative one is stored in the counter
Real
 Real number constants and real register data types are
declared with the keyword real.
 They can be specified in decimal notation or in scientific
notation.
 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
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)
Time
 Verilog simulation is done with respect to
simulation time.
 A special time register data type is used in Verilog
to store simulation time.
 A time variable is declared with the keyword time.
 The width for time register data types is
implementation specific but is at least 64 bits.
time save_sim_time; // Define a time variable save_sim_time
initial
Save_sim_time = $time; // Save the current simulation time

Simulation time is measured in terms of simulation seconds


Arrays
 Arrays are allowed in Verilog for reg, integer, time, Real, realtime and vector
register data types.
 Multi-dimensional arrays can also be declared with any number of
dimensions.
 Arrays of nets can also be used to connect ports of generated instances.
 Each element of the array can be used in the same fashion as a scalar or vector
net.
 Arrays arc accessed by <array_name> [<subscript>}.
 For multi-dimcnsional arrays, indexes need to be provided for each dimension.

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


reg bool[31:0]; //Array of 32 one_bit boolean register variables
time chk_point[1:100]; //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][0:255]; // Two dimensional array of integers
reg (63:0] array_4d [15:0] 17:0][7:0][255:0]; //Four dimensional array
wire [7:0] w_array2 [5:0], //Declare an array of 8 bit vector wire
wire warrayl[7=o] [5:0]; //Declare an array of aingle bit wires
 A vector is a single element that is n-bits wide.
 Arrays are multiple elements that are 1-bit or n-bits
wide.

count[5] // 5th element of array of count variables


chk_point[100]=0 //100th time check point value
port_id[3]=0 //3rd element of port_id array. This is a 5-bit
value.

matrix[1] [0] = 33559; //Set value of element indexed by [1] [0] to 33559
array_4d [0] [0] [0] [0] [15:0] =0; //Clear bits 15:0 of the
register
//accessed by indices [0] [0] [0] [0]
port_id =0; //Illegal syntax - Attempt to write the entire array
matrix [1] = 0; //Illegal syntax - Attempt to write [1] [0] .. [1] [255]
Memories
 In digital simulation modeling of register files, RAMs, and
ROMs is done.
 Memories are modeled in Verilog simply as a one-
dimensional array of registers.
 Each element of the array is known as an element or word
and is addressed by a single array index.
 It is important to differentiate between n 1-bit registers
and one n-bit register.
 A particular word in memory is obtained by using the
address as a memory array subscript.
reg mem1bit[0:1023]; //memory mem1bit with 1K 1-bit words
reg [7 : 0] membyte [0 : 1023]; // memory membyte with 1K
// 8-bit words (bytes)
membyte[511] // fetches 1 byte word whose address is 511.
Parameters
 Verilog allows constants to be defined in a module by
the keyword parameter.
 Parameters cannot be used as variables.
 Parameter values for each module instance can be
overridden individually at compile time.
 This allows the module instances to be customized.
 Parameter types and sizes can also be defined.
parameter port_id = 5; //Defines a constant port_id
parameter cache_line_width=256;//constant defines
//width of cache line
parameter signed [15:0] WIDTH; // Fixed sign and range for
// parameter WIDTH
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*19:1] string_value; //Declare a variable that is 19 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
System Tasks
 Verilog provides standard system tasks to do certain
routine operations.
 All system tasks appear in the form $<keyword>.

Displaying information
$display is the main system task(most useful) for
displaying values of variables or strings or expressions.
$display(pl, p2, p3 ,....., pn);
pl, p2, p3, ..., pn can be quoted strings or variables or
expressions.
A $display inserts a newline at the end of the string by
default.
Format Display
%d or %D Display variable in decimal
%b or %B Display variable in binary
%S or %S Display string
%h or %H Display variable in hex
%c or %C Display ASCII character
%m or %M Display hierarchical name (no argument required)
%v or %V Display strength
%o or %O Display variable in octal
%t or %T Display in current time format
%e or %E Display real number in scientific format (e.g., 3e10)
%f or %F Display real number in decimal format (e.g., 2.13)
%g or %G Display real number in scientific or decimaI,
//Display the string in quotes
$display("Hello Verilog World");
-- Hello Verilog World
//Display value of current simulation time 230
$display ($time) ;
-- 230
//Display value of 41-bit virtual address 1fe0000001c and
time 200
reg [0:40] virtual_addr;
$display("At time %d virtual address is %h”, $time,
virtual_addr);
-- At time 200 virtual address is 1fe0000001c
//Display value of port-id 5 in binary
reg [4:0] port-id;
$display("ID of the port is %b", port-id);
-- ID of the port is 00101
//Display X characters
//Display value of 4-bit bus 10xx (signal contention) in binary
reg [3:0] bus;
$display("Bus value is %b”, bus);
-- Bus value is 10xx
//Display the hierarchical name of instance p1 instantiated under
//the highest-level module called top. No argument is required.
// This is a useful feature)
$display(“This string is displayed from %m level of hierarchy");
-- This string is displayed from top.pl level of hierarchy
Monitoring information
Verilog provides a mechanism to monitor a signal when its
value changes. This facility is provided by the $monitor task.
$monitor(p1 ,p2,p3 ,...., pn);
The parameters pl, p2, ... , pn can be variables, signal
names, or quoted strings.
 Unlike $display, $monitor needs to be invoked only once.
 Only one monitoring list can be active at a time. If there is
more than one $monitor statement in your simulation,
the last $monitor statement will be the active statement.
 The earlier $monitor statements will be overridden.
 Two tasks are used to switch monitoring on and off.
//Monitor time and value of the signals clock and reset
//Clock toggles every 5 time units and reset goes down at 10 time
unit:
initial
begin
$monitor($time, “Value of signals clock = %b reset = %b”, clock,
reset);
end
Partial output of the monitor statement:
-- 0 Value of signals clock = 0 reset = 1
-- 5 Value of signals clock = 1 reset = 1
-- 10 Value of signals clock = 0 reset = 0
Stopping and finishing in a
simulation
The task $stop is provided to stop during a simulation.
Usage: $stop;
The $stop task puts the simulation in an interactive
mode. The designer can then debug the design from
the interactive mode. The $stop task is used whenever
the designer wants to suspend the simulation and
examine the values of signals in the design.
The $finish task terminates the simulation.
Usage: $finish;
// Stop at time 100 in the simulation and examine the results
// Finish the simulation at time.
initial // to be explained later. time = 0
begin
clock = 0;
reset = 1;
#100 $stop; // This will suspend the simulation at time =100
#900 $finish; // This will terminate the simulation at time =900

end
Compiler Directives
'define
The 'define directive is used to define text macros in Verilog
//define a text macro that defines default word size
//Used as 'WORD_SIZE in the code
'define WORD_SIZE 32
//define an alias. A $stop will be substituted wherever 'S appears
'define S $stop.
//define a frequently used text string
'define WORD_REG reg [31:0]
// you can then define a 32_bit register as 'WORD-REG reg32;
'include
 The ' include directive allows you to include entire
contents of a Verilog source file in another Verilog file
during compilation.
 This directive is typically used to include header files,
which typically contain global or commonly used
definitions
// Include the file header.v, which contains declarations in //the
main verilog file design.v
'include header.v
...
...
<Verilog code in file design.vz>
Modules and Ports
Modules

Components of a Verilog Module


// This example illustrates the different components of a module
// Module name and port list
// SR-latch module
module SR_latch (Q, Qbar, Sbar, Rbar) ;
//Port declarations
output Q, Qbar;
Input Sbar, Rbar;
// Instantiate lower-level modules
// In this case, instantiate Verilog primitive nand gates
// Note, how the wires are connected in a cross-coupled fashion.
nand n1 (Q, Sbar, Qbar) ;
nand n2 ( Qbar , Rbar , Q) ;
endmodule
// Stimulus module
module Top;
wire q, qbar; // Declarations of wire, req, and other variables
reg set, reset;.
// Instantiate lower-level modules.In this case, instantiate SR-latch
// Feed inverted set and reset signals to the SR latch
SR-latch ml(q, qbar, ~set, ~reset);
Initial // Behavioral block, initial
begin
$monitor($time, " set = %b, reset= %b, q= %b\n”,set,reset,q);
set = 0; reset = 0;
#5 reset = 1;
#5 reset = 0;
#5 set = 1;
end
endmodule
Ports
 Ports provide the interface by which a module
can communicate with its environment.
 The internals of the module are not visible to
the environment.
List of Ports

module fulladd4(sum, c_out, a, b, c_in);


//Module with a list of ports
module Top;
// No list of ports, top-level module in simulation
Port Declaration
Verilog Keyword Type of Port
input Input port
output Output port
inout Bidirectional port
module fulladd4(sum, c _ out, a, b, c _ in);
//Begin port declarations section
output [3 : 0] sum;
output c _ out;
input [3:0] a, b;
input c _ in;
//End port declarations section
...
<module internals>
... module fulladd4(output reg [3 : 0] sum;
endmodule output reg c _ out;
input [3:0] a, b;
input c_in);
...
<module internals>
...
endmodule
 All port declarations are implicitly declared as
wire in Verilog.
 If a port is intended to be a wire, it is sufficient to
declare it as output, input, or inout.
 If ports value need to be stored, they must be
declared as reg.
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
Port Connection Rules

• Width matching
• Unconnected ports
fulladd4 faO(SUM, , A, B, C_IN); // Output port c-out is
unconnected
Illegal Port Connection
module Top;
//Declare connection variables
reg [3:0]A,B;
reg C_IN;
reg [3:0] SUM;
wire C_OUT;
//Instantiate fulladd4, call it fa0
fulladd4 fa0(SUM, C_OUT, A, B, C_IN);
//Illegal connection because output port sum in module fulladd4
//is connected to a register variable SUM in module Top.
………
………
<Stimulus>
..
endmodule
Connecting Ports to External Signals
Connecting by ordered list
module Top;
//Declare connection variables
reg [3:O]A,B;
reg C_IN;
wire [3:0] SUM;
wire C_OUT;
//Instantiate fulladd4, 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
Connecting ports by name
// 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));

fulladd4 fa_byname ( .sum(SUM),.b(B), .c_in


(C_IN), .a(A)) ;
Hierarchical Names
Gate-Level Modeling
Gate Types
 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.
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.
wire OUT, IN1, IN2;
// basic gate instantiations.
and a1(OUT, IN1, IN2);
nand na1 (OUT, IN1, IN2 ) ;
or or1(OUT, IN1, IN2);
nor nor1 (OUT, IN1, IN2 ) ;
xor x1 (OUT, IN1, IN2 ) ;
xnor nx1 (OUT, IN1, IN2 ) ;
// More than two inputs; 3 input nand gate
nand na1_3inp (OUT, IN1, IN2, IN3 ) ;
// gate instantiation without instance name
and (OUT, IN1, IN2); // legal gate instantiation
Buf/Not Gates
 Buf/not gates have one scalar input and one or more
scalar outputs.
 Two basic buf/not gate primitives are provided in
Verilog.

// basic gate instantiations.


buf b1(OUT1, IN);
not n1(OUT1, IN);
// More than two outputs
buf b1_2out (OUT1, OUT2, IN);
// gate instantiation without instance name
not (OUT1, IN); // legal gate instantiation
Bufif/notif
//Instantiation of bufif gates. //Instantiation of notif gates
bufif1 b1 (out, in, ctrl) ; notif1 n1 (out, in, ctrl) ;
bufif0 b0 (out, in, ctrl) ; notif0 n0 (out, in, ctrl) ;
Array of Instances
Wire [7:0] out, in1,in2;
//Basic gate instantiations
nand n_gate [7:0] (out,in1,in2);
// this is equivalent to the following 8 instantiations
nand n_gate (out[0],in1[0],in2[0]);
nand n_gate (out[1],in1[1],in2[1]);
nand n_gate (out[2],in1[2],in2[2]);
nand n_gate (out[3],in1[3],in2[3]);
nand n_gate (out[4],in1[4],in2[4]);
nand n_gate (out[5],in1[5],in2[5]);
nand n_gate (out[6],in1[6],in2[6]);
nand n_gate (out[7],in1[7],in2[7]);
Example

OUT+ + s1s03
module mux4_to_1 (out, i0, il, i2, i3, sl, S0);
output out;
input i0, i1, i2, i3 ,s1, s0;
wire s1n, s0n, y0, yl, y2, y3;
not (s1n, s1) ;
not (s0n, s0);
// 3-input and gates instantiated
and (y0, i0, s1n, s0n);
and (y1, i1, s1n, s0);
and (y2, i2, s1, s0n);
and (y3, i3, s1, s0);

// 4-input or gate instantiated


or (out, y0, y1, y2, y3);
endmodule
module stimulus;
reg IN0, IN1, IN2, IN3;
reg S1, S0;
Mux4_to_1 mymux (OUTPUT, IN0, IN1, IN2, IN3, S1, S0) ;
initial
begin
IN0 = 1; IN1 = 0; IN2 = 1; IN3 = 0;
#1 $display("INO= %b, IN1= %b, IN2= %b, IN3=%b\n”, INO, IN1, IN2,
IN3);
S1 = 0; S0 = 0;
#1 $display("S1 = %b, S0 = %b, OUTPUT = %b \n”, S1, S0, OUTPUT);
S1 = 0; S0 = 1;
#1 $display("S1 = %b, S0 = %b, OUTPUT = %b \n", S1, S0, OUTPUT);
S1 = 1; S0 = 0;
#1 $display("S1 = %b, S0 = %b, OUTPUT = %b \n”, S1, S0, OUTPUT);
S1 = 1; S0 = 1;
#1 $display("S1 = %b, S0 = %b, OUTPUT = %b \n”, S1, S0, OUTPUT);
end
endmodule
4 – Bit Ripple Carry Full Adder
1-Bit Full Adder
module fulladd (sum, c_out, a, b, c_in) ;
output sum, c_out;
input a, b, c_in;

wire s1, c1, c2;

xor (s1, a, b);


and (c1, a, b);

xor (sum, s1, c_in) ;


and (c2, s1, c_in);

or (c_out, c2, c1);

endmodule
module fulladd4 (sum, c_out, a, b, c_in);
output [3:0] sum;
output c_out;
input [3 : 0] a, b;
input c_in;
wire c1, c2, c3;

fulladd fa0(sum[O], c1, a[0], b[0], c_in);


fulladd fa1(sum[1], c2, a[1], b[1], c1);
fulladd fa2(sum[2], c3, a[2], b[2], c2);
fulladd fa3(sum[3], c_out, a[3], b[3], c3);

endmodule
module stimulus;
reg [3:0] A, B;
reg C_IN;
wire [3:0] SUM;
wire C_OUT;
fulladd4 FA1_4(SUM, C_OUT, A, B, C_IN) ;
initial
begin
$monitor($time," A= %b, B=%b, C_IN= %b,--- C_OUT= %b, SUM= %b\n”,
A, B, C_IN, C_OUT, SUM);
end
initial
begin
A = 4'd0; B = 4'd0; C_IN = 1'b0;
#5 A = 4'd10; B = 4'd5; C_IN = 1'b1;
#5 A = 4'd12; B = 4'd8; C_IN = 1'b1;
end
endmodule
Gate Delays
• Rise delay

• Fall delay
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.
// Delay of delay-time for all transitions
and #(delay_2time) a1(out, i1, i2);

// Rise and Fall Delay Specification.


and # (rise_val, fall_val) a2 (out, i1, i2) ;

// Rise, Fall, and Turn-off Delay Specification


bufif0 #(rise_val, fall_val, turnoff_val) bl (out, in, control);

and #(5) a1(out, i1, i2); //Delay of 5 for all transitions


and #(4,6) a2(out, i1, i2); // Rise = 4, Fall = 6
bufif0 # (3,4,5) b1(out, in, control); // Rise= 3, Fall = 4, Turn-off = 5
Min/Typ/Max Values
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.
// One delay
// if +mindelays, delay= 4
// if +typdelays, delay= 5
// if +maxdelays, delay= 6
and #(4:5:6) a1(out, i1, i2);
// Two delays
// if +mindelays, rise= 3, fall= 5, turn-off = min(3,5)
// if +typdelays, rise= 4, fall= 6, turn-off = min(4,6)
// if +maxdelays, rise= 5, fall= 7, turn-off = min(5,7)
and #(3:4:5, 5:6:7) a2(out, i1, 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
//invoke simulation with maximum delay
> verilog test.v +maxdelays
//invoke simulation with minimum delay
> verilog test.v +mindelays
//invoke simulation with typical delay
> verilog test.v +typdelays

If min or max delay is not specified, default it will


take typical delay
Delay Example

module D (out, a, b, c);


output out;
input a, b, c;
wire e;
and #(5) a1 (e, a, b) ; //Delay of 5 on gate a1
or #(4) o1(out, e, c); //Delay of 4 on gate 01
endmodule
module stimulus;
reg A, B, C;
wire OUT;
D d1( OUT, A, B, C);
initial
begin
A= 1'b0; B= 1'b0; C= 1'b0;
#l0 A= 1'b1; B= 1'b1; C= 1'b1;
#l0 A= 1'b1; B= 1'b0; C= 1'b0;
#20 $finish;
end
endmodule
Dataflow Modeling
Continuous Assignments
• A continuous assignment is the most basic statement
in dataflow modeling, used to drive a value onto a net

//Syntax of assign statement in the simplest form


continuous_assign::=assign[drive_strength] [delay3]
list_of _net _assignments;
list_of_net_assignments : : = net_assignment { ,
net_assignment }
net_assignment : : = net_lvalue = expression
Continuous assignments
characteristics
 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.
 Continuous assignments are always active.
 The operands on the right-hand side can be
registers or nets or function calls.
 Delay values can be specified for assignments in
terms of time units.
// Continuous assign. out is a net. i1 and i2 are nets
assign out = i1 & i2;
// Continuous assign for vector nets. addr is a 16-bit vector
//net
// addr1 and addr2 are 16-bit vector registers.
assign addr[15:0] = addr1_bits[15:0] ^ addr2_bits[15:0];
// Concatenation. Left-hand side is a concatenation of a
// scalar net and a vector net.
assign {c_out, sum[3:0]} = a[3:0] + b[3:0] + c_in;
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.
//Regular continuous assignment
wire out;
assign out = in1 & in2;
//Same effect is achieved by an implicit continuous
//assignment
wire out = in1 & in2;
Implicit Net Declaration
If a signal name is used to the left of the continuous
assignment, an implicit net declaration will be inferred for
that signal name.
If the net is connected to a module port, the width of the
inferred net is equal to the width of the module port.
//continuous assign. Out is a net
wire in1,in2;
assign out = in1 & in2;
/*note that out was not declared as a wire but an implicit
wire declared as a wire declaration for out is done by
simulator. */
Delays
Regular assignment delay, implicit continuous
assignment delay, and net declaration delay
Regular Assignment Delay
assign #10 out = in1 & in2;
//Delay in a continuous assign
 When signals in1 and in2 go high at time 20, out goes to
a high 10 time units later (time = 30).
 When in1 goes low at 60, out changes to low at 70.
 However, in1 changes to high at 80, but it goes down to
low before 10 time units have elapsed.
 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 is not
propagated to the output.
Implicit Continuous
Assignment Delay
//implicit continuous assignment delay
wire #10 out = in1 & in2;
//same as
wire out;
assign #10 out = in1 & in2;
Net Declaration Delay
//Net Delays
wire # 10 out;
assign out = in1 & in2;
//The above statement has the same effect as the
following
wire out;
assign #10 out = in1 & in2;
Expressions, Operators, and
Operands
Expressions
Expressions are constructs that combine operators
and operands to produce a result
a^b
addr1[20:17] + addr2[20:17]
in1 | in2
Operands
Operands can be constants, integers, real numbers, nets, registers,
times, bit-select (one bit of vector net or a vector register), part-select
(selected bits of the vector net or register vector), memories or
function calls (functions are discussed later).
integer count, final_count;
Final_count = count + 1;//count is an integer operand
real a, b, c;
c = a - b; //a and b are real operands
reg [15:0] reg1, reg2;
reg [3 :0] reg_out;
reg_out = reg1[3:0] ^ reg2[3:0l;//reg1[3:0] and reg2[3:0] are part-
//select register operands
reg ret_value;
Ret_value = calculate_parity(A, B);//calculate parity is a function
//type operand
Operators
Operators act on the operands to produce desired
results.
d1 && d2 // && is an operator on operands d1 and d2
!a[0] // ! is an operator on operand a[0]
B >> 1 // >> is an operator on operands B and 1

• Operator Types
arithmetic, logical, relational, equality, bitwise,
reduction, shift, concatenation, or conditional
Arithmetic Operators
Binary Operators:
A = 4'b0011; B = 4'b0100; // A and B are register
vectors
D = 6; E = 4; // D and E are integers
A * B // Multiply A and B. Evaluates to 4'b1100
D / E // Divide D by E. Evaluates to 1. Truncates any
//fractional part
A + B // Add A and B. Evaluates to 4'b0111
B - A // Subtract A from B. Evaluates to 4'b0001
13 % 3 // evaluate to 1
in1 = 4'b101x;
in2 = 4'b1010;
sum = in1 + in2; // sum will be evaluated to the value 4'bx
Unary operators
The operators + and - can also work as unary operators.
-4 // Negative 4
+5 // Positive 5
-10 / 5 // Evaluates to -2
-’d10 / 5 // is equivalent (2's complement of 10) /5 = (2^32 -10) /5
Logical Operators
// Logical operations
A = 3; B = 0;
A && B // Evaluates to 0. Equivalent to (logical-1 && logical-0)
A II B // Evaluates to 1. Equivalent to (logical-1 || logical-0)
! A / / Evaluates to 0. Equivalent to not(logical-1)
!B // Evaluates to 1. Equivalent to not(logica1-0)
// Unknowns
A = 2'b0x; B = 2'b10;
A && B // Evaluates to X. Equivalent to (X && logical 1)

// Expressions
(a == 2) && (b == 3) // Evaluates to 1 if both a == 2 and
// b== 3 are true. Evaluates to 0 if either is false.
Logical operators
follow these conditions:
 Logical operators always evaluate to a l-bit value, o
(false), 1 (true), or X (ambiguous).
 If an operand is not equal to zero, it is equivalent to a
logical 1 (true condition). If it is equal to zero, it is
equivalent to a logical o (false condition). If any
operand bit is X or z, it is equivalent to X (ambiguous
condition) and is normally treated by simulators as a
false condition.
 Logical operators take variables or expressions as
operands.
Relational Operators
//A=4,B=3
// X = 4'b1010, Y = 4'b1101, Z = 4'b1xxx
A <= B // Evaluates to a logical 0
A > B // Evaluates to a logical 1
Y >= X // Evaluates to a logical 1
Y < Z // Evaluates to an X
Equality Operators
Expression Description Value
a == b a equal to b, result unknown if X or 0, 1, X
Z in a or b

a != b a not equal to b, result unknown if 0, 1, X


X or Z in a or b

a === b a equal to b, including X and Z 0, 1

a !== b a not equal to b, including X and Z 0, 1


//A=4,B=3
//x=4’b1010,Y=4’b1101
//Z=4’b1xxz,M=4’b1xxz,N=4’b1xxx

A == B // Results in logical 0
X != Y // Results in logical 1
X == Z // Results in X
Z === M //results in logical 1 (all bits match, including
X and Z)
Z === N //results in logical 0 (least significant bit does
not match)
M !== N // Results in logical 1
Bitwise Operators
and 0 1 X Or 0 1 X xor 0 1 X xnor 0 1 X
0 0 0 0 0 0 1 X 0 0 1 X 0 1 0 X
1 0 1 X 1 1 1 1 1 1 0 X 1 0 1 X
X 0 X X X X 1 X X X X X X X X X

//x=4’b1010,y=4’b1101
//z=4’b10x1 Not Result
0 1
~X // Negation. Result is 4'b0101 1 0
X & Y // Bitwise and. Result is 4'b1000 X X
X | Y // Bitwise or. Result is 4'b1111
X ^ Y // Bitwise xor. Result is 4'b0111
X ^~ Y // Bitwise xnor. Result is 4’b1000
X&Z // Result is 4’b10x0

//X= 4'b1010, Y= 4’b0000

X | Y // bitwise operation. Result is 4'b1010


X || Y // logical operation. Equivalent to 1|| 0. Result is 1
Reduction Operators
&X //Equivalent to 1 & 0 & 1 & 0. Results in 1’b0
|X //~quivalentto 1 I 0 I 1 I 0. Results in 1'b1
^X //Equivalent to 1 ^ 0 ^ 1 ^ 0. Results in 1’b0
//A reduction xor or xnor can be used for
// even or odd parity generation of a vector.
Shift Operators
// x=4’b1100
Y = X >> 1; // Y is 4'b0110.Shift right 1 bit. 0 filled in
//MSB position
Y = X << 1; // Y is 4'b1000.Shift left 1 bit.0 filled in LSB
//position.
Y = X << 2; //Y is 4'b000.Shift left 2 bits.
Concatenation Operator
// A = 1'b1, B = 2'b00, C = 2'b10, D = 3'b110

Y = {B , C} // Result Y is 4'b0010
Y = {A , B , C , D , 3'b001) // Result Y is 11'b10010110001
Y = {A , B[0], C[1] } // Result Y is 3'b101
Replication Operator
reg A;
reg [1:0] B, C;
reg [2:0] D;
A = 1'b1; B = 2'b00; C = 2'b10; D = 3'b110;
Y = { 4{A} } // Result Y is 4'b1111
Y = { 4{A} , 2{B} } // Result Y is 8'b11110000
Y = { 4{A} , 2{B} , C } // Result Y is 10'b1111000010
Conditional Operator
Usage: condition_expr ? True_expr : false_expr ;

//model functionality of a tristate buffer


assign addr_bus = drive_enable ? Addr_out : 36'bz;
//model functionality of a 2-to-1 mux
assign out = control ? in1 : in0;
assign out = (A == 3) ? ( control ? X : Y ): ( control ? m : n) ;
Operator Precedence
4-to-1 Multiplexer
// Module 4-to-1 multiplexer using data flow.
//logic equation Compare to gate-level model
module mux4-to-l (out, i0, i1, i2, i3, S1, S0);
// port declarations from the I/O diagram
output out;
input i0, i1, i2, i3;
input S1, S0;
//Logic equation for out
assign out = (~S1 & ~S0 & i0)| (~S1 & S0 & i1) | (S1 & ~S0
& i2) | (S1& S0 &i3);
endmodule
Conditional operator.
module mux4-to-l (out, i0, i1, i2, i3, S1, S0);
// port declarations from the I/O diagram
output out;
input i0, i1, i2, i3;
input S1, S0;
// Use nested conditional operator
assign out = S1 ? ( S0 ? i3 : i2) : (S0 ? i1 : i0) ;
endmodule
4-bit Full Adder
4-bit full adder by using
dataflow statements
module fulladd4 (sum, c_out, a, b, c_in) ;
// I/O port declarations
output [3:0] sum;
output c_out;
input [3: 0] a, b;
input c_in;
// Specify the function of a full adder
assign {c_out, sum} = a + b + c_in;
endmodule
Ripple Counter
// Ripple counter
module counter (Q , clock, clear) ;
// I/0 ports
output [3:01 Q;
input clock, clear;
// Instantiate the T flipflops
T_FF tff0 (Q[0] , clock, clear) ;
T_FF tff1 (Q[1], Q[0], clear) ;
T_FF tff2 (Q[2], Q[1], clear) ;
T_FF tff3 (Q[3], Q[2], clear) ;
endmodule
// Edge-triggered T-flipflop. Toggles every clock cycle.
module T_FF (q, clk, clear) ;
// I/0 ports
output q;
input clk, clear;
// Instantiate the edge-triggered DFF
// Complement of output q is fed back.
// Notice qbar not needed. Unconnected port.
edge_dff ff1( q, , ~q, clk, clear);
endmodule
Negative edge triggered D-
flipflop
module edge_dff(q, qbar, d, clk, clear);
output q, qbar;
input d, clk, clear;
// Internal variables
wire S, sbar, r, rbar, cbar;
// dataflow statements Create a complement of signal clear
assign cbar = ~clear;
// Input latches; A latch is level sensitive. An edge-sensitive
// flip-flop is implemented by using 3 SR latches.
assign sbar = ~(rbar & S),
S = -(sbar & cbar & ~clk),
r = -(rbar & ~clk & S),
rbar = ~(r & cbar & d);
// Output latch
assign q = ~ (S & qbar) ,
qbar = ~(q & r & cbar);
endmodule

You might also like