0% found this document useful (0 votes)
81 views172 pages

3ST Verilog STWT Slides

The document discusses the history and purpose of Verilog HDL. It originated in 1984 and was made an open standard in 1995. HDLs were created to allow hardware design through behavioral, structural and mixed level modeling for simulation and synthesis purposes, unlike programming languages which are sequential.

Uploaded by

Ranveer Pratap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views172 pages

3ST Verilog STWT Slides

The document discusses the history and purpose of Verilog HDL. It originated in 1984 and was made an open standard in 1995. HDLs were created to allow hardware design through behavioral, structural and mixed level modeling for simulation and synthesis purposes, unlike programming languages which are sequential.

Uploaded by

Ranveer Pratap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 172

Course Curriculum

Verilog
HDL

3ST Technologies Verilog HDL STWT 1


Contents
• Verilog HDL Part 1
❑ Introduction
▪ History
▪ Why HDL needed
▪ HDL vs. Programming Languages
▪ Compilation and Simulation Cycle
▪ Tools available in the market and References
❑ Modeling styles and Gate Level Modeling
▪ Curtain raiser – Gate level, Data flow, Behavioral modeling styles
▪ Design approaches – top down and bottom up
▪ Gate primitives
▪ gate instantiation
✓ simple gate
✓ more than one gate
3ST Technologies Verilog HDL STWT 2
Contents
• Verilog HDL Part 1
❑ Modeling styles and Gate Level Modeling
▪ gate instantiation
✓ multiple gates
▪ module instantiation
✓ hierarchy creation
✓ hierarchical object references
❑ Verilog Conventions and Test Bench Writing
▪ module and its parts
▪ ports and port connection rules
▪ wires and registers
▪ logic value system
▪ ports association – named and positional, gotcha(s)
▪ number system, keywords and grammar
3ST Technologies Verilog HDL STWT 3
Contents
• Verilog HDL Part 1
❑ Verilog Conventions and Test Bench Writing
▪ test bench writing
▪ examples and exercises
❑ Data Types
▪ wired and tri nets
▪ resolution tables
▪ strengths and strength resolution
▪ registers – reg, real, integer, time
▪ vectors, buses, arrays, multi dimensional arrays
▪ parameters – localparam, parameter, defparam, specparam
▪ examples and exercises
❑ Data Flow Modeling and Operators
▪ continuous assignment – assign keyword
3ST Technologies Verilog HDL STWT 4
Contents
• Verilog HDL Part 1
❑ Data Flow Modeling and Operators
▪ operators and their precedence
✓ arithmetic, relational, equality/inequality, reduction, bitwise
✓ logical, shift (logical/arithmetic), concatenation, repetition
✓ conditional (? :)
❑ Behavioral Modeling
▪ initial procedural block
✓ begin end, fork join block execution and their nesting
✓ named blocks using labeling and disabling
▪ always procedural block
✓ clock generators
✓ execution differences between initial and always blocks
✓ blocking (=) and non blocking (<=) assignment
3ST Technologies Verilog HDL STWT 5
Contents
• Verilog HDL Part 1
❑Behavioral Modeling
▪ always procedural block
✓ sequential and parallel execution
✓ event control (@) and wait
✓ edge control (posedge, negedge)
✓ if else construct
✓ case, casex, casez constructs
✓ LFSR, MISR modeling
✓ forever, while, for, repeat
✓ functions and tasks
✓ design examples
✓ FSM modeling
✓ Mealy machine
✓ Moore machines
✓ examples and exercises
3ST Technologies Verilog HDL STWT 6
Session I
Introduction

3ST Technologies Verilog HDL STWT 7


Introduction
• History
• Word verilog is derived from Latin word veritas (meaning
truth), and Greek word logos (meaning reason, idea)
• Verilog therefore means expressing the truth of your idea
• What does it mean in terms of VLSI design?

3ST Technologies Verilog HDL STWT 8


Introduction
• History
• Verilog Hardware Description Language (HDL) was designed
and implemented by Phil Moorby & Prabhu Goel at Gateway
Design Automation in 1984
• Used in the beginning of 1985, extended substantially by 1987
• Implementation through Verilog-XL simulator sold by Gateway
• Verilog was a proprietary language i.e. no other vendor was
allowed to make a simulator based on Verilog
• Cadence Design Systems acquired Gateway in December 1989,
and continued to market Verilog as a language along with
simulator Verilog-XL based on Verilog
• At the same time, Synopsys started marketing the top-down
design methodology using Verilog, a very powerful combination
• By 1990, Cadence recognized that if Verilog remained a closed
language, the pressures of standardization would eventually
cause the industry to shift to VHDL
3ST Technologies Verilog HDL STWT 9
Introduction
• History
• Cadence organized Open Verilog International (OVI), and gave the
Verilog HDL documentation to OVI in 1991 making Verilog an open
source language
• Verilog became IEEE standard in December, 1995
• When Cadence gave OVI the LRM, several companies began working
on Verilog simulators
• In 1992, the first of these is VCS, the Verilog Compiled Simulator, from
Chronologic Simulation which was acquired by Synopsys
• This was a true compiler as opposed to an interpreter, which is what
Verilog-XL was
• As a result, compile time may be substantial, but simulation execution
speed is much faster
• Verilog is heavily used than ever, and is growing faster than any other
hardware description language
• It has truly become the world standard hardware description language

3ST Technologies Verilog HDL STWT 10


Introduction
• Why HDL
• Primarily software programming languages do not include any
capability for expressing time explicitly, and this is why they cannot
function as hardware description languages
• Designs described in HDL are technology independent, easy to design
and debug and are usually more readable than schematics, particularly
for large circuits
• HDL’s need the ability to describe VLSI design in terms of
• Behaviour, Structural, Mixed level
so that they can be
• Simulated which means verification of the hardware behaviour
• Synthesized which means translational of behaviour to actual hardware is
done correctly
• Allow different design approaches (methodologies)
• Top - down
• Bottom – up
• HDL’s are primarily aimed at designing hardware once and then using
different synthesis tools to target different implementation technologies
like ASIC, FPGA, CPLD
3ST Technologies Verilog HDL STWT 11
Introduction
• HDL vs. Programming Languages
• HDL • Programming Languages
• Concurrent • Sequential
• Instances • Functions
• Compilation results in • Compilation result in OS
hardware model specific executable assembly
instructions
• HDL's syntax and • Software languages do not
semantics include include explicit notations for
explicit notations for expressing time and
expressing time and concurrency
concurrency which are
the primary attributes of
hardware
3ST Technologies Verilog HDL STWT 12
Introduction
• HDL execution elements : Concurrent vs. Sequential

~~~~~~~ ~~~~~~~
~~~~~~~ ~~~~~~~
~~~~~~~ ~~~~~~~
~~~~~~~ ~~~~~~~

~~~~~~~
~~~~~~~
~~~~~~~
~~~~~~~

3ST Technologies Verilog HDL STWT 13


Introduction
• Instance vs. Functions
• Same gate used multiple times is called Instance and not a
function

• Simulator works internally as an OS (Why?)


• It does Scheduling of signals/processes
• advances Simulation Time
3ST Technologies Verilog HDL STWT 14
Introduction
• Compilation results
• Elaboration and initialization are done before simulation

Programming HDL
Language C
parser
parser
model generator
Code generator
elaborator
linker
Application Program
Executable Operating System Simulator

Hardware

3ST Technologies Verilog HDL STWT 15


Introduction
• Simulation Cycle (Infinite Simulation Time)

Start Simulation

Update Signals Execute Processes

End Simulation
• First, write HDL code in any HDL tool and save it
• Compile the saved code and rectify the reported error if any
• Run the compiled code and check if the compiled code results are
meeting your design requirement, if not, try to find what could be the
possible error and rectify it ,save it, compile it and simulate it
• Repeat the above steps until you get the simulation result which exactly
matches your requirement
3ST Technologies Verilog HDL STWT 16
Introduction
• Software tools available in the market
• Logic Simulation
• Mentor Graphics – ModelSim (free) or QuestaSim
• Cadence – ncvlog, ncelab, ncsim or nclaunch
• Synopsys – vcs
• Logic Synthesis
• Mentor Graphics – leonardo or precision
• Cadence – rc-complier
• Synopsys – design compiler (dc)
• References
• Verilog HDL : A guide to Digital Design & Synthesis by Samir
Palnitkar
• Verilog Primer by J. Bhasker
• Web-Site : www.asic-world.com
3ST Technologies Verilog HDL STWT 17
Session II
Modeling Styles
Gate Level Modeling
Conventions
3ST Technologies Verilog HDL STWT 18
Modeling Styles
• Understanding level of abstraction
• Switch Level
• Gate Level
• Data flow
• Behavioral

• These modeling styles are given in increasing order of their


level of abstraction
• They fall in two categories
• White box modeling
• Black box modeling
• Can you name which modeling styles are white box and
which are black box and why?
• Gate Level being the simplest so we start with Gate Level
3ST Technologies Verilog HDL STWT 19
Modeling Styles
• Gate Level Model Writing – curtain raiser
• At Gate level, the hardware is designed using predefined Gate
primitive by instantiating them and setting interconnection between
these gates
• Gate level modelling is a lower level modelling and also called as
WHITE BOX modelling because everything is visible inside the design
• Usually used for designing combinational logic

module gatelevel ( o , a , b );
input a , b ;
output o ;

and a1( o , a , b );

endmodule

3ST Technologies Verilog HDL STWT 20


Modeling Styles
• Data Flow Model Writing – curtain raiser
• At this level the hardware is designed by specifying the data flow
• The designer is aware of how data flows between hardware registers and how the data
is processed in the design
• Continuous assignment assign keyword is used for data flow modelling, it is used to
drive a value on a NET or a WIRE
• RTL (Register Transfer Level) is a combination of dataflow/behavioural modelling
styles, a logic synthesis tool can be used to generate GATE LEVEL NETLIST using
RTL style
• Data flow modelling has higher level of abstraction over Gate level
• It is called BLACK box modelling style, used for designing combinational logic
module dataflow( o , a , b);
input a , b ;
output o ;

assign o = a & b ;

endmodule
3ST Technologies Verilog HDL STWT 21
Modeling Styles
• Behavioral Model Writing – curtain raiser
• Hardware design can be implemented in terms of the desired design without
concern for the hardware implementation details
• Designing at this level is very similar to C programming but with hardware in mind
• Verilog procedural statements are used to model design at behavioural level, it is a
higher Level of Abstraction than the other levels, also a Black box modelling style
• always keyword is used for behavioural modelling, initial for initializations
• Each always block represent a separate activity flow
• Different always blocks represent the concurrent activity flows which is an inherent
concurrent representation of hardware model
• The example below shows a behavioural model for which all the activity flows are
defined by the initial and always constructs which start together at simulation time
zero, the initial constructs execute once, and the always constructs execute
repetitively module behave;
reg a;
initial
a = 0;
always
#50 a = ~a;
endmodule
3ST Technologies Verilog HDL STWT 22
Modeling Styles
• Design Methodologies : Structural
• Top – Down
• Define top level block and identify sub-block necessary to build top-
level block

3ST Technologies Verilog HDL STWT 23


Modeling Styles
• Design Methodologies : Structural
• Bottom – Up
• Define basic building block that are available to us and build bigger cells
using these building blocks

3ST Technologies Verilog HDL STWT 24


Gate Level Modeling
• Gate Level
• Verilog HDL has built-in gate level primitives shown below
• What do you observe?
• Can you draw the circuit
diagrams for each one?

3ST Technologies Verilog HDL STWT 25


Gate Level Modeling
• Gate Level Models
• Observe

3ST Technologies Verilog HDL STWT 26


Gate Level Modeling
• Single Gate Hardware Design
• A sample

module orgate (y, a, b);

input a , b ;
output y ;
Declarative Part

or r1(y, a, b); Gate Instantiation


endmodule

3ST Technologies Verilog HDL STWT 27


Gate Level Modeling
• Two Gate Hardware Design
• A sample half adder design
A B Sum Carry
0 0 0 0
0 1 1 0
1 0 1 0
1 1 0 1
// Gate level Half adder
module half_adder (Sum, Carry, A, B);
output Sum, Carry;
input A, B;

xor x1(Sum, A, B); Logic Gate


and a1(Carry, A, B); Instantiation

endmodule

This will generate Sum = A xor B and


Carry= A and B
3ST Technologies Verilog HDL STWT 28
Gate Level Modeling
• Multiple Gate Hardware Design
• A sample full adder design

// Gate level Full Adder


module fulladder (S, Cout , A, B, Cin);
output S, Cout ;
input A, B, Cin ; A B Cin S Cout
wire w1 , w2 ,w3 ;
0 0 0 0 0
xor x1(w1 , A, B) ; 0 0 1 1 0
xor x2(S, w1, Cin ) ; 0 1 0 1 0
and a1(w2, A , B ) ;
0 1 1 0 1
and a2(w3, w1, Cin) ;
or r1(Cout , w3 , w2); 1 0 0 1 0
1 0 1 0 1
endmodule
1 1 0 0 1
1 1 1 0 0
3ST Technologies Verilog HDL STWT 29
Gate Level Modeling
• Module Instantiation
• Hierarchy Creation
• Just like gates, modules can also be instantiated
• Module instantiation is sometimes referred as hardware inside hardware
• When a module is instantiated, simulator creates a unique view for each
such instantiation where each of its variables, parameters and I/O interface
has different linkages
• Higher level Design instantiate lower level design

top(root)

or1 nt2
qbar, q, reset
(or) (not)

n1 n2 x1
(and) (nand) (xor)
3ST Technologies Verilog HDL STWT 30
Gate Level Modeling
• Module Instantiation
• Hierarchical Naming
• Hierarchical names referencing allows us to denote every identifier in the
design hierarchy
• A hierarchical name is a list of identifier separated by dots ( “ . ” ) for each
level of hierarchy
• The top module is called the root module because it is not instantiated
anywhere in the hierarchy, basically it is the starting point
• To assign a unique name to an identifier , start from top level module and
trace the path along the design hierarchy to the desired identifier
• As an illustration here are some examples

top top.or1 top.qbar


top.q top.nt2 top.reset
top.or1.n2 top.nt2.x1 top.or1.n1

3ST Technologies Verilog HDL STWT 31


Gate Level Modeling
• Module Instantiation
• Example - Full adder using two half adder instantiation
module full_adder (sum , cout , a , b ,cin );
output sum, cout;
input a, b, cin ;
wire w1, w2, w3 ;

half_adder h1 (w1, w2, a, b) ;


half_adder h2 (sum, w3, w1, cin) ;
or r1 (cout, w2, w3) ;
a sum
endmodule half_adder cout
b

a w1 sum
h1 h2 w3
b
cin cout
w2

3ST Technologies Verilog HDL STWT 32


Gate Level Modeling
• Module Instantiation
• Example – 4 bit Ripple Carry Full Adder

module bit_4_fulladder(sum, cout, a, b, cin);


output [3:0] sum ;
output cout ;
input [3:0] a, b ;
input cin ;
wire w1, w2, w3;

full_adder f0(sum[0], w1, a[0], b[0], cin);


full_adder f1(sum[1], w2, a[1], b[1], w1);
full_adder f2(sum[2], w3, a[2], b[2], w2);
full_adder f3(sum[3], cout, a[3], b[3], w3);

endmodule

3ST Technologies Verilog HDL STWT 33


Conventions
• Basic Building Block - Module
• The “module” keyword is the basic unit of hardware/hierarchy in Verilog
• Modules describe
boundaries [module, endmodule]
inputs and outputs [ports]
how it works [behavioural or RTL code]
• Can be a single element or collection of lower level module i.e. can Instantiate one
module in another module to support hierarchical design
• A module in totality (with endmodule) should be contained within one file
• It is not necessary that a module name should match the name of the file in which
module is defined
• Multiple modules can reside within one file
• Modules contain RTL logic or other modules
• Modules provide a way to reuse designs
• Internal of each module can be defined with any of FOUR level of abstraction
behavioural, data flow, gate, switch or a mix depending upon the need of design
• Nesting of module is not allowed in verilog (why?)
3ST Technologies Verilog HDL STWT 34
Conventions
• Basic Building Block – Module and its parts
Module name,
Port list, Port Declarations (if ports present)
Parameters (optional)

Declarations of wires, Data flow statements


reg’s and other variables (assign)

always and initial blocks


Instantiation of lower
All behavioral statements
level modules
go in these blocks

Tasks and functions

endmodule statement

3ST Technologies Verilog HDL STWT 35


Conventions
• Basic Building Block – Module and its parts
• Ports
• Ports provide the interface by which a module can communicate with its
environment (input and output pins of an IC)
• Ports are referred as terminals or pins
• Ports are declared as
• input
• Always understood as a net within the module
• can only be read from
• output
• Understood as a net by default
• can be type reg if assigned in a procedural block (more later)
• inout
• It is bidirectional port
• Is always a net and can’t be of type reg

3ST Technologies Verilog HDL STWT 36


Conventions
• Basic Building Block – Module and its parts
• Port connection rules
• Ports have two views, one that is internal to the module and another that is
external to the module
• There are rules that govern port connections and the simulators complain if
any of the port connection rules are violated
• Each port connection shall be a continuous assignment of source to sink
• Only nets or structural net expressions shall be the sinks in an assignment
Inputs
Internally, input ports must always be of the type net
Externally, the inputs can be connected to 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

3ST Technologies Verilog HDL STWT 37


Conventions
• Basic Building Block – Module and its parts
• Wires or nets
• Represent physical connection between structural entities like gates or h/w blocks
• Values continuously driven on the net by the outputs of the drive they are
connected to
• Declared primarily with keyword ‘wire’
• It has one bit value by default when declared explicitly as wire
• Represent data types like wire, wor, wand, trior, triand, trireg
• Default value ‘z’ (High Impedance) except for “trireg” whose default value is ‘x’
• Can have multiple drivers “Fan Out“
• Multiple driven values are resolved using Resolution table
• If no driver is connected to a net, its value shall be high-impedance (z) unless the
net is a trireg, in which case it shall hold the previously driven value
• Variables or Registers or regs
• A variable is an abstraction of a data storage element which shall store a value
from one assignment to the next
• Declared with a keyword ‘reg’ (mostly used), ‘integer’, ‘real’, ‘time’, ‘realtime’
• The default value for reg, time and integer is unknown value ‘x’ but for real and
realtime it is 0.0
3ST Technologies Verilog HDL STWT 38
Conventions
• Basic Building Block – Module and its parts
• Logic value system
• Verilog follows 4 value logic system
Value Level Condition in hardware circuits
0 Logic zero, false condition
1 Logic one, true condition
x Unknown value
z High impedance, floating state

Verilog provides strength levels of logic 0: X


0
0
state to resolve conflict between drivers
of different strength in digital circuits 1: 1
1
x

If two signals of unequal strength are X or x: 0 X 1


driven on a wire, the stronger signal 1 0
prevails 0
Z or z : 1 z
3ST Technologies Verilog HDL STWT 39
Conventions
• Basic Building Block – Module and its parts
• A sample module
//-------------------------------------------------------
// one-bit full adder module
//-------------------------------------------------------
module fadder (a, b, cin, sum_out, carry_out );
input a, b, cin ;
output sum, carry_out ;
< design functionality>
endmodule
-------------------------------------------------------------
module fadder( input a, // data in a
input b, // data in b
input cin, // carry in
output sum_out, // sum output
output c_out // carry output
);
<design functionality>
endmodule
3ST Technologies Verilog HDL STWT 40
Conventions
• Connecting Module Ports to external signals
• Two methods of making connections between signals specified in the
module instantiation and the ports in a module definition
• These two methods cannot be mixed
• Connecting by “position” or by “name”
• Explain formal and actual
Connection by Ordered List called “Positional Mapping”
module Top; module full3add (sout, cout, a, b, cin);
reg [2:0] ain , bin; output [2:0] sout;
reg c; input [2:0] a, b;
wire [2:0] s ; output cout;
wire carry; input cin;

full3add fa(s, carry, ain, bin, c); <functionality>


endmodule endmodule
3ST Technologies Verilog HDL STWT 41
Conventions
• Connecting Module Ports to external signals
• Verilog provides the capability to connect external signals to ports by the port
names also rather than by positional mapping
• 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
• Note : The two types of module port connections cannot be mixed i.e. all the
connections to the ports of a particular module instance shall be either by
position or by name
Connection by naming called “Named Mapping”
module topmod; module modB(wa, wb, wc, wd);
inout wa, wb;
wire a,b,c,d; input wc,wd;
modB b1 ( .wb(b), .wa(c),
.wd(d), .wc(c)); <functionality>
endmodule endmodule
3ST Technologies Verilog HDL STWT 42
Conventions
• Lexical
• Comments
• Comments are signified in verilog the same way as in C
• One line comments begin with ”//”
• Multi-line comments start with /* and end with */
• These two comment definitions can’t be nested
• Identifiers and keywords - Verilog is case sensitive language
• Identifiers are the names given to objects so that they can be referenced
• They start with alphabetic chars or underscore (_)
• They cannot start with a number (0 to 9) or dollar sign ($) (why)
• All keywords are in lower case
• Some of the valid identifier are listed below
shiftreg_a, busa_index, error_condition, merge_ab, _bus3, n$657
• Escaped identifiers
• They start with a \ and end with a white space
• They can include printable ASCII characters
• E.g. \546 , \007 , \{***} , \Gate#3
3ST Technologies Verilog HDL STWT 43
Conventions
• Number System
• Numbers are written in format <size>’<base><number>
• size specifies the number of bits
• base specifies the type or radix of number e.g. for binary ( b or B )
• The underscore character (_) can be used anywhere in a number for
grouping its bits or digits for the purpose of readability
• Decimal ( d or D ) , Octal ( o or O ) ,Hexadecimal (h or H)
4'b1010 // This is a 4-bit binary number
16’b1001_0010_0011_1111 // underscore used to enhance readability
12'habc // This is a 12-bit hexadecimal number
9’o735 // This is a 9-bit octahedral number
-16'd255 // This is a 16-bit negative decimal number
16’-d255,16’d-255 // This is an illegal representation of a -ve number
• Constants in Verilog are integer or real, default size 32 bits
• Specification of integers can include ‘x’ and ‘z’ in addition to the
standard ‘0’ and ‘1’ logic values
3ST Technologies Verilog HDL STWT 44
Conventions
• Number System Formats
Format Display
%d or %D Display variables 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 arguments 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 numbers 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 decimal, whichever is shorter

3ST Technologies Verilog HDL STWT 45


Conventions
• Number System – More Examples
4’d6 0110 Decimal 6 is interpreted as a 4-bit number

8’b101 00000101 Binary 101 is turned into an 8-bit number


16’h5a_b_4 0101101010110100 Binary equivalent of hex
(underscore is ignored)
-8’b011 11111101 This is the 2’s complement of the
number

8’ha 00001010 Hexadecimal is expanded to


8 bits by padding zeros to its left

12’hzb zzzzzzzz1011 Hexadecimal zb is expanded to


12 bits by extending the left z

12’shc7 Signed 111111000111 This is an 8-bit number

-4’shd Signed 0011 The 2’s complement (because of the minus


sign) 4-bit d is regarded as a signed number
3ST Technologies Verilog HDL STWT 46
Conventions
• Verilog Keywords

3ST Technologies Verilog HDL STWT 47


Conventions
• Verilog Grammer - Backus Naur Form
module module_name [(port name{, port name})];
[parameter declaration]
[input declaration]
[output declaration]
[inout declaration]
[net declaration]
[reg declaration]
[time declaration]
[integer declaration]
[real declaration]
[event declaration]
[gate instantiation]
[UDP instantiation]
[function or task]
[continuous assign]
[specify block]
[initial statement]
[always statement]
[module instantiation]
endmodule
3ST Technologies Verilog HDL STWT 48
Session III
Test Bench Writing

3ST Technologies Verilog HDL STWT 49


Test Bench Writing
• Why to write test bench
• A test bench writing is an automated way of verification and validation
• Simulation and test of a designed hardware system functionality before Hardware
generation called verification
• Detection of design errors and incompatibility of components used in the design
• A Verilog Test bench sometimes called as STIMULUS BLOCK contains
• A Verilog module
• Instantiation of Design Under Test (DUT)
• Applies data or stimulus to DUT
• Monitors the output
• Points to remember while writing a test bench
• No output and input port declarations
• H/W to be tested is instantiated as module instance
• Instantiated H/W inputs declared as reg, outputs declared as wire
• Stimulus written in initial block
• Initials block are written to change initial values at different simulation times
and monitor them
• Delays are specified between different stimulus using regular delays (delays
values preceding ‘#’ in left hand side assignment
3ST Technologies Verilog HDL STWT 50
Test Bench Writing
• A sample test bench
// TEST BENCH of a HALF ADDER // Gate level Half adder
module test_halfadder; module half_adder (sum, carry_out, a, b);
reg ain, bin ; output sum , carry_out ;
wire s, cout ; input a , b;
half_adder h1( .sum(s) ,
.carry_out (cout), xor x1(sum , a , b );
.a(ain) , .b(bin) ); and a1(carry_out , a , b);
initial
begin endmodule
#10 a=1’b0; b=1’b0;
#10 a=1’b1; b=1’b0;
#10 a=1’b0; b=1’b1;
#10 a=1’b1; b=1’b1;
end
initial
$monitor(“time=%d, ain=%b , bin=%b ,
sum=%b , cout=%b”, $time,
ain, bin, s, cout);
endmodule
3ST Technologies Verilog HDL STWT 51
Test Bench Writing
• test bench components
• Initial block
• initializes the value
• Different “initial” blocks executes concurrently at 0 simulation time
• Keywords “ begin ….. end ” are used to enclose multiple sequential
statements just like curly braces { } in C
• Regular delay
• Delays are specified by “#10”
• “#10” will suspend the assignment of right hand expression to left hand
variable by10 unit of time (ns, ps etc)
• System Task
• $monitor(“$time=%d, ain=%b, bin=%b, sum=%b, cout=%b”, $time, ain,
bin, s, cout);
• %d specifies decimal values , %b specifies binary values
• $monitor will run every time whenever there is any change in the value of
listed variable and signal

3ST Technologies Verilog HDL STWT 52


Test Bench Writing
• Another sample test bench
// Test Bench of a 4bit ripple carry adder
module test_4bitadder; module adder_4bit(sum, cout, a, b, cin);
reg [3:0] a , b ; input [3:0] a , b ;
reg cin; input cin;
wire [3:0] sum ; output [3:0] sum ;
wire cout ; output cout ;
wire w1,w2,w3;
adder_4bit a1(sum, cout, a, b, cin);
full_adder f1(s[0], w1, a[0], b[0], cin);
initial full_adder f2(s[1], w2, a[1], b[1], w1);
begin full_adder f3(s[2], w3, a[2], b[2], w2);
#10 a=4’b0000; b=4’b0101; cin=1’b0; full_adder f4(s[3], cout, a[3], b[2], w3);
#10 a=4’b0010; b=4’b1101; cin=1’b1;
#10 a=4’b0100; b=4’b1011; cin=1’b0; endmodule
#10 a=4’b1100; b=4’b1111; cin=1’b0;
#10 a=4’b1110; b=4’b0111; cin=1’b1;
#10 a=4’b1111; b=4’b1101; cin=1’b0;
end
endmodule
3ST Technologies Verilog HDL STWT 53
Test Bench Writing
• Sample output waveform

3ST Technologies Verilog HDL STWT 54


Exercises
• Gate Level
1. Design a half subtractor using gates and verify its truth table
2. Design a full subtractor using gates and verify its truth table
3. Design a full subtractor by instantiating half subtractor and verify its truth table
4. Design a 4x1 mux using following gate combinations and verify its truth table
a) and, or logic b) using tristated buffers
5. Design a 3 bit binary to grey converter
6. Design a 3 bit grey to binary converter
7. Design a 3 bit even parity generator and checker
8. Design a 4 bit odd parity generator and checker
9. Design the following combinational logic and verify its result by simulation

3ST Technologies Verilog HDL STWT 55


Session IV
Data Types

3ST Technologies Verilog HDL STWT 56


Data Types
• Net Types - Several distinct
• Wire and tri nets
• The net types wire and tri shall be identical in their syntax and functionality
• A wire net can be used for nets that are driven by a single gate or continuous
assignment
• The tri net type can be used where multiple drivers drive a net
• Logical conflicts from multiple sources of the same strength on a wire or a tri net
result in x (unknown) values
• Wired nets
• Wired nets are of type wor, wand, trior, and triand and are used to model wired logic
configurations
• Wired nets use different truth tables to resolve the conflicts that result when multiple
drivers drive the same net
• The wor and trior nets shall create wired or configurations so that when any of the
drivers is 1, the resulting value of the net is 1 and that they shall be identical in their
syntax and functionality
• The wand and triand nets shall create wired and configurations so that if any driver is
0, the value of the net is 0 and that they shall be identical in their syntax and
functionality
• Can you draw resolution
tables for wand/triand
wor/trior, wire/tri?
3ST Technologies Verilog HDL STWT 57
Data Types
• Net Types
• The resolution tables
Resolution table of wor/trior Resoluton table of wand /triand
module test_wor(y, a, b); module test_wand(y, a, b);
output wor y; output wand y;
input a,b; input a, b;
and a1( y, a, b ); and a1( y, a, b );
or o1( y, a, b ); or o1( y, a, b );
endmodule endmodule

3ST Technologies Verilog HDL STWT 58


Data Types
module test_wor();
wor a;
reg b, c;
assign a = b;
assign a = c;
initial begin
$monitor(“time = %d a = %b b = %b c = %b", $time, a, b, c);
#10 b = 1’b0; c = 1’b0;
#10 c = 1’b1;
wor/trior 0 1 x z
#10 c = 1’bx; 0 0 1 x 0
#10 c = 1’bz;
1 1 1 1 1
#10 b = 1’b1; c = 1’b0;
x x 1 x x
#10 c = 1’b1;
#10 c = 1’bx; z 0 1 x z
#10 c = 1’bz; // complete the TB on your own
#10 $finish;
end
endmodule
3ST Technologies Verilog HDL STWT 59
59
Data Types
module test_wand();
wand a;
reg b, c;
assign a = b;
assign a = c;
initial begin
$monitor(“time = %d a = %b b = %b c = %b", $time, a, b, c);
#10 b = 1’b0; c = 1’b0; wand/triand 0 1 x z
#10 c = 1’b1;
#10 c = 1’bx; 0 0 0 0 0
#10 c = 1’bz; 1 0 1 x 1
#10 b = 1’b1; c = 1’b0;
#10 c = 1’b1; x 0 x x x
#10 c = 1’bx;
z 0 1 x z
#10 c = 1’bz; // complete the TB on your own
#10 $finish;
end
endmodule
3ST Technologies Verilog HDL STWT 60
Data Type
module test_wire();
wire a;
reg b, c;
assign a = b;
assign a = c;
initial begin
$monitor(“time = %d a = %b b = %b c = %b", $time, a, b, c);
#10 b = 1’b0; c = 1’b0;
#10 c = 1’b1; wire/tri 0 1 x z
#10 c = 1’bx;
0 0 x x 0
#10 c = 1’bz;
#10 b = 1’b1; c = 1’b0; 1 x 1 x 1
#10 c = 1’b1;
#10 c = 1’bx; x x x x x
#10 c = 1’bz; // complete the TB on your own z 0 1 x z
#10 $finish;
end
endmodule
3ST Technologies Verilog HDL STWT 61
Data Types
• Reg Types
• Variables : data storage elements
• Verilog supports three types of variables : reg, integer, real, time
• The default initial value for reg, time, and integer data types shall be the
unknown value x
• The default initial value for real and real time variable data types shall be
0.0
• It is illegal to re-declare a name already declared by a net, parameter, or
variable declaration
• Caution
• Nets and variables can be assigned negative values, but only integer,
real, realtime and signed reg variables and signed nets shall retain the
significance of the sign
• Time and unsigned reg variables and unsigned nets shall treat the value
assigned to them as an unsigned value
• Integers
• declared by the keyword integer, the default width for an integer is the
host-machine word size, which is implementation-specific but it is at least
32 bits and store values as signed quantities
3ST Technologies Verilog HDL STWT 62
Data Types
• Reg Types
• Integers – example
// general purpose variable used as a count
integer count;
initial
count = -100 ; // A negative one is stored in the count
• Real
• Real constants and variable are declared with the keyword real
• They cannot have a range declaration, and their default value is 0.0
• When a real value is assigned to an integer, the real number is
rounded off to the nearest integer
• example
real myreal; // Define a real variable called myreal
initial
begin
myreal = 5e-5 ; // myreal is assigned in scientific notation
myreal = 4.13 ; // myreal is assigned a value 4.13
end
3ST Technologies Verilog HDL STWT 63
Data Types
• Reg Types
• Time
• A time variable is used for storing and manipulating simulation time
• This data type is typically used in conjunction with the $time system task
• The time variables shall behave the same as reg with 64 bits storage
• unsigned quantities, and unsigned arithmetic shall be performed on it
• Vectors
• A net or reg declaration without a range specification shall be considered
as1 bit wide and is known as a scalar
• Multi bit net and reg data types shall be declared by specifying a range,
which is known as a vector
• examples
wand w; // a scalar net of type "wand“
tri [15:0] bus a; // Little endian, a three-state 16-bit bus
reg a; // a scalar reg
reg [0:4] v; // Big endian notation
reg signed [3:0] signed_reg;
reg [-1:4] b;
3ST Technologies Verilog HDL STWT 64
Data Types
• Reg Types
• Vectors
• More examples
reg [4:0] x, y, z;
wire [7:0] bus; // 8-bit bus
wire [31:0] busA, busB, busC ; // 3 buses of 32-bit width
reg [0:40] virtual_addr; // virtual_addr with MSB as 0 and LSB as 40
• The most significant bit specified by the msb constant expression is the
left-hand value in the range
• The least significant bit specified by the lsb constant expression is the
right-hand value in the range
• Both the msb and the lsb constant expression must be constant integer
expression
• The msb and lsb constant expressions may be any integer value
positive, negative or zero
• Vector part select - it is possible to address bits or parts of vectors
[<starting_bit>+:size] - part-select increments from starting bit
[<starting_bit>-:size] - part-select decrements from starting bit
3ST Technologies Verilog HDL STWT 65
Data Types
• Reg Types
• Vectors
• Vector part select examples
busA [7] // bit # 7 of vector busA
busA [2:0] // Three least significant bits of vector bus,
virtual_addr [0:1] // Two most significant bits of vector virtual_addr
reg [31:0] data1; reg [0:31] data2;
byte = data1[31-:8]; // starting bit = 31, width =8 => data1[31:24]
byte = data1[24+:8]; // starting bit = 24, width =8 => data1[31:24]
byte = data2[31-:8]; // starting bit = 31, width =8 => data2[24:31]
byte = data2[24+:8]; // starting bit = 24, width =8 => data2[24:31]
• Arrays
• Verilog allows declaration and usage of multidimensional arrays for nets or regs
• The following declares array1 as a two-dimensional array of 8-bit words :
reg [7:0] array1 [0:7] [0:7];
• In an array declaration, the address range of the elements of the array comes after the
name of the array
• Range specifications are enclosed in square brackets
• The size and range specification of the elements of an array come after the net type e.g.
wire or reg keyword
• In the absence of a range specification before the name of the array, an element size of
one bit is assumed
3ST Technologies Verilog HDL STWT 66
Data Types
• Reg Types
• Arrays
7 0
// An 8-bit vector Areg
reg [7:0] Areg;

Amem
// A memory of 8 one-bit elements
reg Amem [7:0];

0
3ST Technologies Verilog HDL STWT 67
Data Types
• Reg Types
• Arrays 7

// A two-dimensional memory of one-bit elements


reg Bmem [7:0] [0:3];
Bmem

7
0
// A memory of four 8-bit words
reg [7:0] Cmem [0:3]; Cmem

3
3ST Technologies Verilog HDL STWT 68
Data Types
• Reg Types
• Arrays

3ST Technologies Verilog HDL STWT 69


Data Types
• Reg Types
• Arrays

3ST Technologies Verilog HDL STWT 70


Data Types
• Reg Types – some testing examples
module NumberTest;

reg [11:0] a = 8'shA6; initial $displayb ("a=",a); // a=111110100110


reg [11:0] b = 8'sh6A; initial $displayb ("b=", b); // b=000001101010
reg [11:0] c = 'shA6; initial $displayb ("c=", c); // c=000010100110
reg [11:0] d = 'sh6A; initial $displayb ("d=", d); // d=000001101010
reg [11:0] e = -8'shA6; initial $displayb ("e=", e); // e=000001011010
reg [11:0] f = -'shA6; initial $displayb ("f=", f); // f=111101011010
reg [11:0] g = 9'shA6; initial $displayb ("g=", g); // g=000010100110
reg [11:0] i = -9'shA6; initial $displayb ("i=", i); // i=111101011010
reg [11:0] j = -9'sh6A; initial $displayb ("j=", j); // j=111110010110
reg [11:0] k = 4692; initial $displayb ("k=", k); // truncate the extra bits
// k=001001010100
endmodule

3ST Technologies Verilog HDL STWT 71


Data Types
• Parameters – constants in verilog
• localparam, parameter, specparam, defparam
• Parameters do not belong to either the register or the net group
• Helps in parameterization of module
• Two types of parameters : module and specify parameters
• Can be declared as signed, real, integer, time or realtime
• Default size is 32 bit
• Local parameters (defined using keyword localparam) : identical to
parameters except that they cannot be directly modified with the
defparam statement, used to define parameters when their values
should not be changed Example Explanation
parameter a=6, b=7; 32 bit parameter
parameter [4:0] a=6, b=7; 5 bit parameter
parameter [31:0] a=6; 32 bit parameter
parameter signed [4:0] b=8; 5 bit signed parameter
parameter real a=3.14 real parameter
localparam me=4856 local parameter
3ST Technologies Verilog HDL STWT 72
Data Types
• Parameters – constants in verilog
• Examples – parameter accessing
module subtractor #(parameter size = 8, cnt=100 ) (borrow, diff, a, b, cin) ;
output [size-1:0] diff;
output borrow;
input [size-1:0] a, b;
input cin;
Positional mapping
assign {borrow, diff} = a - b - cin;
endmodule
module substractor_tb;
parameter size1= 9, cnt1=10 ;
parameter size2=10, cnt2=11 ;
reg [size1 - 1:0] a1, b1;
subtractor #(size1,cnt1) w1 (borrow1, diff1, a1, b1, c1);
reg [size2 – 1:0] a2 , b2;
reg c1, c2; subtractor #(.size(size2), .cnt(cnt2)) w2 (borrow2, diff2, a2, b2, c2);
wire [size1 – 1:0] diff1;
wire [size2 – 1:0] diff2;
wire borrow1 , borrow2;
named mapping
endmodule
3ST Technologies Verilog HDL STWT 73
Data Types
• Parameters – constants in verilog
• Example - defparam
// example of def param
module hello_vlsi;

localparam count = 0;
$display("Displaying hello vlsi id number = %d", count);

endmodule

module top;

hello_vlsi w1();
hello_vlsi w2();
defparam w1.count = 1, w2.count = 2;

endmodule
3ST Technologies Verilog HDL STWT 74
Exercises
• Data Types
1. Write a declaration for a wire and a bus of 16 bits
2. Write memory declarations for a 4K x 16-bit memory
3. Check the correctness of the following declarations
net n1, n2;
reg [63:0] r1, r2, r3;
reg [0:-5] r;
events e1, e2;
4. Write a declaration of a tri-stated wire with charge storage of medium capacitance

3ST Technologies Verilog HDL STWT 75


Session V
Data Flow Modeling
and
Operators
3ST Technologies Verilog HDL STWT 76
Data Flow Modeling
• Assign keyword
• Verilog allows a circuit to be designed in terms of the data flow between
registers through NETS
• Data flow modelling has higher level of abstraction than Gate level modelling
also called as black box modelling
• Data flow modelling make use of continuous assignment to drive a value
onto a net
• Continuous assignment replaces gates in the description of the circuit and
describes the circuit at a higher level of abstraction
• This assignment statement starts with the keyword assign
• A continuous assignment creates events on one or more nets whenever a
net or register in an expression changes value
• DATA FLOW modelling and Gate level modelling are mostly used for
designing COMBINATIONAL LOGIC
• Example
// Continuous assign : out is a net, i1 and i2 can be nets or registers
assign out = i1 & i2;
// write possible declarations for i1, i2 and out ?
3ST Technologies Verilog HDL STWT 77
Data Flow Modeling
• Assign keyword
• 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 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
• The operands on the right-hand side can be registers or nets or function calls
where registers or nets can be scalars or vectors
• 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

3ST Technologies Verilog HDL STWT 78


Data Flow Modeling
• Operators
• Arithmetic Operators
• a + b : a=4’b0100, b=4’b1111
a + b = 5’b10011 a**b a to the power of b
• a - b : a=4’b1111, b=4’b1010 a+b a plus b
a – b = 4’b0101
• a * b : a=4’b1001 , b=4’b1010
a-b a minus b
a * b = 7’b1011010 a*b a multiplied by b
• a / b : a=7, b=2
a/b a divided by b
a/b=3
• a % b : a= -7, b=2 a%b a modulo b
then a % b = -1;
• a % b : a=7, b= -2
then a % b = 1;
NOTE : The result take the sign of first operand in “%” operator
• a**b : 2 ** 0 = 1 // Anything to the zero exponent is 1
• 0 ** 0 = 1 // Zero to the zero exponent is also 1
• 2.0 ** –3'sb1 = 0.5 // 2.0 is real, giving real reciprocal
• 2 ** –3 'sb1 = 2 ** –1 = 1/2 // Integer division truncates to zero
• IntA = -12 / 3; // The result is -4
• IntA = -'d12 / 3; // The result is 1431655761
3ST Technologies Verilog HDL STWT 79
Data Flow Modeling
• Operators
• Arithmetic Operators
• IntA = -'sd12 / 3; // The result is -4
• IntA = -4'sd12 / 3; // -4'sd12 is the negative of the 4-bit
// quantity 1100, which is -4 ➔ -(-4) = 4
// The result is 1
• Relational Operators
• Relational operators are mostly used for comparing two numbers
• On the basis of the comparison some decision are made in If-else clause
• An expression using these relational operators shall yield the scalar value 0 if
the specified relation is false or the value 1 if it is true
• If either operand of a relational operator contains an unknown (x) or high
impedance (z) value, then the result shall be a 1-bit unknown value (x)
• Example : Let a=12 and b=33 then
• a>b will result in ‘0’ a<b a less than b
• a<b will result in ‘1’ a>b a greater than b
• a>=b will result in ‘0’
a<=b a greater than or equal to b
• a<=b will result in ‘1’
a>=b a less than or equal to b

3ST Technologies Verilog HDL STWT 80


Data Flow Modeling
• Operators
• Equality/Inequality Operators
• For the logical equality and logical inequality operators (== and !=), if,
there is any unknown or high-impedance bit in the operands, then the
result shall be a 1-bit unknown value (x)
• For the case equality and case inequality operators (=== and !==), the
comparison shall be done as follows
• bits that are x or z shall be included in the comparison and shall
match for the result to be considered equal, the result of these
operators shall always be a known value, either 1 or 0

a===b a equal to b ,including x and z

a!==b a not equal to b ,including x and z

a == b a equal to b , result can be unknown

a !=b a not equal to b , result can be unknown

3ST Technologies Verilog HDL STWT 81


Data Flow Modeling
• Operators
• Equality/Inequality Operators - examples
• If a = 4’b0010 and b = 4’b0100 then
a==b will result in ‘0’
a!=b will result in ‘1’
a===b will result in ‘0’
a!==b will result in ‘1’
• If a = 4’b10x0 b= 4’b01xx then Logical Equality
a==b will result in ‘x’
a!=b will result in ‘x’ Case Equality
a===b will result in ‘0’
a!==b will result in‘1’
• Note : Case equality matches for exact bit by bit value including ‘x’, ‘z’

3ST Technologies Verilog HDL STWT 82


Data Flow Modeling
• Operators
• Reduction Operators
• The unary reduction operators perform a bitwise operation on a single operand to
produce a single-bit result
• For reduction and, reduction or, and reduction xor operators, the first step of the
operation shall apply
• The operator between the first bit of the operand and the subsequent bits use the
respective logic to give 1 bit result either ‘0’ ,’1’ ox ‘x’
Unary “OR” Unary “AND” Unary XOR

1 0 1 x z 1 0 1 x z 1 0 1 x z
0 0 1 x x 0 0 0 0 0 0 0 1 x x

1 1 1 1 1 1 0 1 x x 1 1 0 x x

x x 1 x x x 0 x x x x x x x x
z 0 x x x z x x x x
z x 1 x x

3ST Technologies Verilog HDL STWT 83


Data Flow Modeling
• Operators
• Bitwise Operators Bitwise or (|) 0 1 x
• X = 4'b1110, Y = 4'b1001 , Z = 4'bx1x1
~X // Negation, Result is 4’b0001 0 0 1 x
X & Y // Bitwise and, Result is 4'b1000 1 1 1 1
X | Y // Bitwise or, Result is 4'b1111 x x 1 x
X ^ Y // Bitwise xor, Result is 4'b0111
X ^~ Y // Bitwise xnor, Result is 4'b1000 Bitwise and(&) 0 1 x
X & Z // Result is 4'bx1x0
0 0 0 0
Bitwise xor(^) 0 1 x 1 0 1 x
0 0 1 x x 0 x x
1 1 0 x
x x x x
Bitwise not(~)
Bitwise xnor(^~) 0 1 x
0 1 0 x 0 1
1 0 1 x 1 0
x x x x x x

3ST Technologies Verilog HDL STWT 84


Data Flow Modeling
• Operators
• Logical Operators – mostly used in conditions
• Logical and : (&&)
• Logical “And” operator holds logic ‘1’ value if both operands to
either side of the operator results in logic ‘1’ otherwise logic ‘0’
• If there is any ambiguous data to either side of the operand then
the result will be ‘x’
• Logical Or : (||)
• Logical “Or” operator holds logic ‘1’ value if either operands to both
side of the operator results in logic ‘1’ otherwise logic ‘0’
• If there is any ambiguous data to either side of the operand then
the result will be ‘x’
• Logical Not : (~)
• Logical “Not” operator holds logic ‘1’ value if the operand to it is
“False”
• If there is any ambiguous data in operand then the result will be ‘x’

3ST Technologies Verilog HDL STWT 85


Data Flow Modeling
• Operators
• Logical Operators – examples
• If A = 0 ; B = 4; then
A && B // Evaluate to 0, Equivalent to (logical-0 && logical-1)
A || B // Evaluate to 1, Equivalent to (logical-0 || logical-1)
!A // Evaluate to 1, Equivalent to not(logical-0)
!B // Evaluate to 0, Equivalent to not(logical-1)
• If A = 2'b0x; B = 2'b10; then
A && B // Evaluate to x, Equivalent to (x && logical 1)
• If a = 4 ; b = 7 then
(a == 4) && (b == 7) // Evaluate to 1 since both a==4, b==7 are true
• If a = 2 ; b = 3; then
(a == 4) || (b == 7) // Evaluate to 0 since both a==2, b==3 are not true
• If a = 9 then
~(a == 9) // Evaluate to ‘0’ since a is equal to 9
~(a != 9) // Evaluate to ‘1’ since a is equal to 9

3ST Technologies Verilog HDL STWT 86


Data Flow Modeling
• Operators
• Shift Operators
• The left shift operators, << and <<<, shall shift their left operand to the
left by the number of bit positions given by the right operand, in both
cases, the vacated bit positions shall be filled with zeroes
• The right shift operators, >> and >>>, shall shift their left operand to the
right by the number of bit positions given by the right operand
• The logical right shift shall fill the vacated bit positions with zeroes
• The arithmetic right shift shall fill the vacated bit position with the
M.S.B of the operand
• Examples : if X = 4’b1110 then
Y = X << 1; // Y is 4'b1100
Shift Operator Symbol
Y = X << 2; // Y is 4'b1000
Y = X <<< 1; // Y is 4'b1100 Left Shift <<
Y = X <<< 2; // Y is 4'b1000
Right Shift >>
Y = X >> 1; // Y is 4‘0111
Y = X >> 2; // Y is 4'b0011 Arithmetic left <<<
Y = X >>> 1; // Y is 4'b1111
Arithmetic Right >>>
Y = X >>> 2; // Y is 4'b1111
3ST Technologies Verilog HDL STWT 87
Data Flow Modeling
• Operators
• Concatenation Operator - Provides mechanism to append multiple bits

A = 2'b10, B = 3'b010, C = 4'b1010, D = 5'b01110


Y = {B , C} // Result Y is 7’b0101010
Y = {A , B , C , D , 3'b001} // Result Y is 17‘b10010101001110001
Y = {A , B[0], C[1]} // Result Y is 4’b1001

• Repetition Operator – Repetitive concatenation

Y = { 4{A} } // Result Y is 8'b10101010


Y = { 4{A}, 2{B} } // Result Y is 14'b10101010010010
Y = { 4{A}, 2{B} , C } // Result Y is 18’b101010100100101010
Y = 2{4{A}, 2{C}} // Result Y is 32’b10101010101010101010101010101010

3ST Technologies Verilog HDL STWT 88


Data Flow Modeling
• Operators
• Conditional Ternary Operator - ? : - can be nested
out = ((cond_expr) ? (expr1) : (expr2));
• If the condition evaluates to false (0), then expr2 is evaluated and used as the result
• If the condition evaluates to true (1), then expr1 is evaluated and used as the result
• If the condition evaluates to an ambiguous value (x or z), then both expr1 and expr2
shall be evaluated; and their results shall be combined, bit by bit
• See the truth table and the example
a=2’b10 ; b=2’b11; c=1;
assign out= ((c) ? (a + b) : (a – b));
assign out = ((a == 2’b11) ? (control ? x : y ) : ( control ? m : n)); // ?: nesting example

?: 0 1 x z
expr2
0 0 x x x
1 x 1 x x expr1
x x x x x
z x x x x

3ST Technologies Verilog HDL STWT 89


Data Flow Modeling
• Example - 2 to 4 line decoder

module decoder(F, X, Y);


output [0:3] F; X Y F[0] F[1] F[2] F[3]

input X, Y; 0 0 1 0 0 0

assign F[0] = ~X & ~Y; 0 1 0 1 0 0


assign F[1] = ~X & Y; 1 0 0 0 1 0
assign F[2] = X & ~Y; 1 1 0 0 0 1
assign F[3] = X & Y;
endmodule

3ST Technologies Verilog HDL STWT 90


Data Flow Modeling
• Example // 4 bit ripple carry using data flow
module full_adder4 (sum, carry, a, b, cin);
output [3:0] sum;
output carry;
input [3:0] a, b;
input cin;
assign {carry , sum} = a + b + cin ;
endmodule

3ST Technologies Verilog HDL STWT 91


Data Flow Modeling
• Example – Parameterization using data flow modelling
module parity (parity_bit , data ); module adder(sum , carry , a , b ,cin) ;
parameter size=32; parameter width=10;
output parity_bit; output [width-1:0] sum;
input [size-1:0] data; output carry;
assign parity_bit = ^data; input [width-1:0] a,b;
end input cin;
assign {carry, sum} = a + b + cin;
end

3ST Technologies Verilog HDL STWT 92


Data Flow Modeling
• Operators Precedence

W & X + Y A & B && C + D

+ & +

& &&
3ST Technologies Verilog HDL STWT 93
Exercises
• Data Flow Modeling
1. Given that a, b, c and d are declared as below
[7:0] a, b; wire [8:0]c1,c2;wire c ; wire [15:0] d;
Evaluate the following expressions
i) a = 255; b = 155; c1= a + b; /* Evaluate c */
ii) c2= 9'b000000001 + a + b; /* Evaluate c */
iii) d= { a, b };/* Evaluate d*/
iv) c3 = &b;
2. Design 4 bit shift (left shift , right shift, arithmetic left shift , arithmetic right shift,
circulatory left shift, circulatory right shift) registers using data flow
3. Design a 8X3 encoder using data flow
4. Design a 4 bit carry look ahead adder using data flow modelling
5. Design a 3X8 decoder using data flow
6. Design a 16x1 mux using 4x1 mux , 2x1 mux , 8x1 mux using data flow
7. Design a 4 bit full subtractor using data flow
8. Design a parity generator and checker using data flow modelling
9. Design a binary to grey and grey to binary using data flow

3ST Technologies Verilog HDL STWT 94


Session VI
Behavioral Modeling

3ST Technologies Verilog HDL STWT 95


Behavioral Modeling
• Basics of Behavioral modeling
• This style represents the highest level of abstraction in Verilog
• It’s called procedural assignment modelling
• It is modelled using initial and always blocks aka procedural blocks
• always block – used to describe the functionality using behavioural or
procedural statements
• initial block – used to initialize behavioural block statements with initial
values i.e. assign values to register data types like reg, real, integer,
time
• always and initial blocks are processes that run in parallel and start at
‘0’ time simulation and can’t be nested
• Procedural blocks contains two types of procedural assignment
statements
• Blocking
• Non Blocking
• Procedural assignments update the value of variables under the
control of the procedural flow constructs that surround them
3ST Technologies Verilog HDL STWT 96
Behavioral Modeling
• Basics of Behavioral modeling
Continuous assignment Procedural assignment
Used to infer combinational logic Used to infer both storage elements
like FF and latches and combinational
logic also
Assignment occurs whenever the value The value of the previous assignment
on the RHS of the expression changes is held until another assignment is
as a continuous process made to the variable
Occurs in assignments to wire, port Occurs in construct like always, initial,
and net type task, function
For example For example
wire out = in1 & in2; always @ (posedge clk)
Or reg1 <= in1;
assign out = in1 & in2; always @ (a or b or s)
y = ((s ==1) ? a : b);

3ST Technologies Verilog HDL STWT 97


Behavioral Modeling
• Inside Behavioral modeling

Always /initial block

Procedural Behavioural
assignment
Processes Blocks Timing control
statement

Delay based
Blocking (=) Combinatorial If -else Sequential

Non-blocking
Clocked Case Concurrent Event based
(<=)

Loops

3ST Technologies Verilog HDL STWT 98


Behavioral Modeling
• Initial Block
• An initial block starts at 0 simulation time, executes exactly once
• Multiple initial blocks start to execute concurrently at 0 time
• Each block finishes execution independent of other blocks
• Multiple behavioural statements must be grouped using keywords begin and end
• initial blocks are not synthesizable i.e. they are mostly used in modelling test benches
• Assignment statement within an initial block execute
• sequentially when begin – end construct used
• concurrently when fork – join construct used
module behave;
reg [1:0] a, b; a
initial begin b
a = 1'b1; b = 1'b0;
end
initial
#50 a=0;
initial
#10 b=1;
initial
#60 $finish;
endmodule
3ST Technologies Verilog HDL STWT 99
Behavioral Modeling
• Initial Block – sequential execution – begin - end
• A begin-end block must contain at least one statement
• Statements in a begin - end block are executed in sequence, timing
controls are relative to the previous statement
• The begin - end block completes when the bottom most statement
completes
• Order of statement matters in begin – end block (order dependence)
• begin - end and fork - join blocks may be nested within themselves
and each other
• A begin - end block can contain local declarations
• If a begin - end block is to be disabled, it must be named or labelled
reg load, enable, reset ; reset = 0;
initial #10 reset = 1; // Time 10
begin #25 enable = 1; // Time 35
load = 0; // Time 0 #100 load = 1; // Time 135
enable = 0; end

3ST Technologies Verilog HDL STWT 100


Behavioral Modeling
• Initial Block – parallel execution – fork - join
• fork – join group statements in a block to be executed concurrently
• The order of execution of statements within a fork - join block doesn’t
matter
• Timing controls are relative to the time at which the block was entered
• A fork - join block completes when all included statements have been
completed
• begin - end and fork - join blocks can be nested within themselves and
each other
reg a, b;
initial a
fork b
a=1; b=0;
#10 a=0;
#10 b=1;
#15 a=1;
#15 b=0;
join
3ST Technologies Verilog HDL STWT 101
Behavioral Modeling
• Initial Block – nested fork – join, begin – end blocks
• Execution of nested begin – end and fork – join blocks
reg a, b, [1:0] c, [2:0] d;
initial
begin a
a = 1'b0; b
#10 b=1'b1; d
fork c
#5 b = 1'b0;
#10 c = {a, b};
join
#20 d = {a, c};
end

initial
#60 $finish;

3ST Technologies Verilog HDL STWT 102


Behavioral Modeling
• Always Block – basics
• Contains one or more statements which are executed repeatedly throughout a
simulation run, as directed by their timing controls
• The always construct, because of its looping nature, is only useful when used in
conjunction with some form of timing control
• An always block starts at 0 time and executes the behavioural statements
continuously in an event based fashion, example – clock generators
module clock_gen (output reg clock);
initial module clk_gen(clk);
clock = 1'b0; output clk=0;
always parameter on_cycle =10;
#10 clock = ~clock; parameter off_cycle = 5;
// Toggle clock every half-cycle (time period = 20) always
end begin
module clkgen (clock); #on_cycle clk=1’b1;
output clock =0; #off_cycle clk=1’b0;
initial end
#10 forever clock = ~clock; endmodule
endmodule
3ST Technologies Verilog HDL STWT 103
Behavioral Modeling
• Basics of Behavioral modeling
initial Always
Assignments in an initial block begin to execute Assignments in an always block also begin from
from time 0 in simulation and proceed in the time 0 in simulation but repeat forever as a
specified sequence function of changes on the blocks of sensitivity
list
Execution of statements in an initial begin-end Execution continuously repeats from the begin to
block stops when the end of the block is reached the end of the process unless held by a wait
i.e. executed only once in simulation construct throughout the simulation session

Non synthesizable construct Synthesizable construct

For example For example


reg [1:0] out1, out2; reg [1:0] out1, out2;
initial begin always @ (posedge clk)
out1 = 2’b10; begin
#5 out2 = 2’b01; out1 <= in1;
end out2 <= out1 & in2;
end
3ST Technologies Verilog HDL STWT 104
Behavioral Modeling
• Procedural assignment modeling
• Procedural assignment evaluation can be modelled as
• Blocking
• Non-blocking
• Procedural assignment execution can be modelled as
• Sequential
• Concurrent
• Procedural assignment timing control can be modelled as
• Delayed evaluations
• Delayed assignments
• Blocking procedural assignment
• Represented by = token
• Evaluated and assigned in a single step
• Execution within the procedure is blocked until the assignment completes
• Evaluations of concurrent statements in the same time step are blocked
until the assignment is completes
• Order of statement matters in blocking procedural assignment

3ST Technologies Verilog HDL STWT 105


Behavioral Modeling
• Procedural assignment modeling
• Blocking procedural assignment – example – following examples are not going
to work correctly – why??
always @(negedge clk) always @(negedge clk)
begin fork
data[15:8] = data[ 7:0]; data2[15:8] = data2[ 7:0];
data[ 7:0] = data[15:8]; data2[ 7:0] = data2[15:8];
end join

• Non blocking procedural assignment


• Represented by <= token
• Evaluated and assigned in two steps
• The right-hand side is evaluated immediately
• The assignment to the left-hand side is postponed until other
evaluations in the current time step are completed
• Execution flow within the procedure continues until a timing control is
encountered (flow is not blocked)
• Order of statement does not matter
3ST Technologies Verilog HDL STWT 106
Behavioral Modeling
• Procedural assignment modeling
• Non Blocking procedural assignment – example – following examples are
going to work correctly – why??
always @(negedge clk) always @(negedge clk)
begin fork
data[15:8] <= data[ 7:0]; data2[15:8] <= data2[ 7:0];
data[ 7:0] <= data[15:8]; data2[ 7:0] <= data2[15:8];
end join
• Procedural assignment timing control - Verilog HDL has two types of explicit
timing control for procedural statements
• A delay control using the symbol “#” (already discussed)
• Event expression or control
delay_control ::= • allows statement execution to be delayed until the
# delay_value | occurrence of some simulation event that may occur in a
# ( mintypmax_expression )
event_control ::=
procedure executing concurrently with respect to this
@ hierarchical_event_identifier procedure
| @ ( event_expression ) • Most often an event control is a positive or negative edge
| @* on a clock signal
| @ (*)
• A delay control introduced by the symbol “@”
3ST Technologies Verilog HDL STWT 107
Behavioral Modeling
• Procedural assignment modeling – Event Control
• Edge Triggering - An edge event shall be detected only on the least significant
bit of the expression also known as REGULAR EVENT CONTROL
• A negedge shall be detected when a transition from 1 to x or 0 or from x or z to
0 happens
• A posedge shall be detected when a transition from 0 to x, z, or 1 or from x or
z to 1 happens
• Edge triggering is synthesizable

@(posedge clk)
@ (clock)
rega <= regb;
rega <= regb ;
@(negedge clk)
rega<=regb;

This will create


sequential design
This will create
sequential design
3ST Technologies Verilog HDL STWT 108
Behavioral Modeling
• Procedural assignment modeling – event or control
• or control for events
• Implicit event expression list
• use @ * which means all inputs or registers that appear in the LHS of an
assignment statement will be automatically added to the event expression list
module parity (input [31:0] in, output p);
always @ (posedge reset or negedge clock)
always @(in) p = ^in; // event list can include vectors
begin
endmodule
if (reset)
always @(a, b, c, d, e) q = 1'b0;
always @(posedge clk, negedge rstn) else if(clock)
always @(a or b, c, d or e) q = d;
always @ (*) end
// equivalent to @ (m or n or q or r)
// This can also be done using comma operator
y = (m | n) & (q ^ r)
always @(posedge reset , negedge clock )
always @ * begin begin
// equivalent to @(n or m or q or p or tmp1 or tmp2) if (reset)
tmp1 = n | m; q = 1'b0;
tmp2 = q & p; else if(clock)
y = tmp1 ^ tmp2; q = d;
end end
3ST Technologies Verilog HDL STWT 109
Behavioral Modeling
• Procedural assignment modeling – event or control
• Implicit event expression list
• Variables or registers that appear on the right-hand side of
assignments, in function and task calls, in case and conditional expressions,
as an index variable on the left-hand side of assignments, or as variables in
case item expressions shall all be included in implicit expression list
• Level Sensitiveness
• keyword “wait” is used always @*
• use “wait” to delay execution until // same as @ (first, se, th, finish, com )
condition is true begin
first = 8’b00;
• wait is not synthesizable e.g. case (1'b1)
• wait (enable) #10 count=count+1; pos[first] : if (com) pos2[se] = 2'b1;
else pos2[first] = 1'b1;
always @* pos[se] : pos2[th ] = 1'b1;
// same as @ (b or enable) pos[th ] : if (!ws) pos2[finish] = 1'b1;
begin else pos2[se] = 1'b1;
y22 = 12’hfab; pos[finish] : pos2[first] = 1'b1;
y[b] = !enable; endcase
end end

3ST Technologies Verilog HDL STWT 110


Behavioral Modeling
• Procedural assignment modeling – event or control
• Blocking and non blocking execution
• A sequential blocking assignment evaluates and assigns before continuing
on in the procedure
always @ (negedge clock)
begin
ain = 1; // evaluate and assign ain immediately
#10 bin = bin + 1; // delay 10 time units, then evaluate and assign bin
end
• A sequential non-blocking assignment evaluates, then continues on to the
next timing control before assigning
always @ (negedge clock)
begin
A <= 1; // evaluate RHS immediately; assign to LHS at end of time step
#15 B <= A + 1; // delay 15 time units, then evaluate RHS; then assign at
// the end of time step (clock + 15) to LHS
end
3ST Technologies Verilog HDL STWT 111
Behavioral Modeling
• Blocking vs. Non-Blocking assignments in initial block
initial begin
a = 1;
b = 0;
a = b; // a = 0;
b = a; // b = 0;
end
initial begin
a = 1;
b = 0;
a <= b; // a = 0;
b <= a; // b = 1;
end

3ST Technologies Verilog HDL STWT 112


Behavioral Modeling
• Procedural assignment modeling – event or control
• Blocking and non blocking execution
• Concurrent blocking assignments on same variable may have unpredictable
results
always @(posedge clk) This would create RACE CONDITION
#10 A = A + 1; (new value of B could be evaluated
always @(posedge clk) before or after A changes)
#10 B = A + 1;

• Concurrent non blocking assignments on same variable will have predictable


results
always @(posedge clk)
#10 A <= A + 1; This would create NO RACE CONDITION
always @(posedge clk) (new value of B could be evaluated before
#10 B <= A + 1; A changes)

3ST Technologies Verilog HDL STWT 113


113
Behavioral Modeling
• Blocking vs. non blocking assignments – Race condition
• When blocking assignments in two or more always blocks are scheduled to
execute in the same time step , order of execution is indeterminate and it can
result in a race condition
always @ (posedge clk)
a = b;
always @ (posedge clk)
b = a;
• Race condition (blocking statements)
• whether a = b or b = a ??
• Recommended : use blocking assignments for modeling combinational
logic in procedural blocks
• Non blocking statements can be used to eliminate the race condition

3ST Technologies Verilog HDL STWT 114


Behavioral Modeling
• Blocking vs. non blocking - Non blocking statements can be used to eliminate the
race conditions but how
• At positive edge of clock, the values of all R.H.S variables are “read” and R.H.S
expressions are evaluated and stored in temporary variables
• During “write” operation, the values stored in temporary variables are assigned to
L.H.S variables
• Separating the read/write operations ensures that the values of registers a and b
are swapped correctly always @(posedge clk) begin
//read operation
always @ (posedge clk)
temp_a = a;
a <= b; temp_b = b;
always @ (posedge clk) //write operation
a = temp_b;
b <= a; b = temp_a;
end
• Recommended : use non blocking assignments for modeling clocked
processes in sequential logic in procedural blocks
3ST Technologies Verilog HDL STWT 115
115
Behavioral Modeling
• Blocking vs. Non-Blocking assignments in initial block with inter and
intra-assignment delays
module blocking_nonblocking(); initial begin
reg a,b,c,d; c = #10 0;c = #11 1;
initial begin c = #12 0;c = #13 1;
#10 a = 0; end
#11 a = 1; initial begin
#12 a = 0; d <= #10 0;d <= #11 1;
#13 a = 1; d <= #12 0;d <= #13 1;
end end
initial begin initial begin
#10 b <= 0; $monitor("TIME = %g A = %b B = %b
#11 b <= 1; C = %b D = %b", $time, a, b, c, d);
#12 b <= 0; #50 $finish;
#13 b <= 1; end
end endmodule

3ST Technologies Verilog HDL STWT 116


Behavioral Modeling
• Procedural assignment modeling - Questions
• Which of the following procedural assignment should be used to model a
combinational logic buffer?

always @ (in) always @ (in)


#10 out = in; #10 out <= in;

always @ (in) always @ (in)


out = #10 in; out <= #10 in;

• Which of the following procedural assignment should be used to model a


sequential logic flip-flop?

always @ (posedge clk) always @ (posedge clk)


#10 q = d; #10 q <= d;

always @ (posedge clk) always @ (posedge clk)


q = #10 d; q <= #10 d;
3ST Technologies Verilog HDL STWT 117
Behavioral Modeling
• Procedural assignment modeling - Questions
• How will these procedural assignments behave?
always @ (in)
o1 = in;

always @ (in)
o2 <= in;

always @ (in) 0 5 10 20 30 32 35 40 45 50
#5 o3 = in; in

clk
always @ (in)
#5 o4 <= in;

always @ (in)
o5 = #5 in;

always @ (in)
o6 <= #5 in; Verilog HDL STWT
3ST Technologies 118
Behavioral Modeling
• Behavioral Modeling Examples
• Half Subtractor – combinational logic
module half_sub(diff, borrow, x, y);
output reg diff, borrow;
input x, y ; X diff
always @ (x, y) Y half subtractor borrow
begin
diff=x^y;
borrow=(~x)&y;
end
endmodule

• Synchronous D – Latch, D Flip Flop


module dff (q, clk, d, en);
module dff (q, clk, d); output reg q;
output reg q; input clk, d, en;
input clk, d; always @ (en, d)
always @(posedge clk ) if (en)
q<=d; q<=d;
endmodule endmodule
3ST Technologies Verilog HDL STWT 119
Behavioral Modeling
• Behavioral Modeling Exercises
• Write Verilog source code in behavioural modelling style for the following
circuits and verify them using blocking and non blocking assignments

3ST Technologies Verilog HDL STWT 120


Behavioral Modeling
• Procedural assignment modeling - Questions
• What is the hardware created by the following Verilog code?
input in; output out; reg a,b,c;
always @ (posedge clk)
begin
a = in;
b = a;
c = b;
out = c;
end
• What is the hardware created by the following Verilog code?
always @ (posedge clk)
begin
a <= in;
b <= a;
c <= b;
out <= c;
end
3ST Technologies Verilog HDL STWT 121
Behavioral Modeling
• Behavioral Modeling – if – else construct
• If – else statement conditionally controls a logic operation and is used to
make a decision about whether a statement is executed or not
• If the expression in the if condition evaluates to true then that branch shall
execute, if it evaluates to false, then the other branch shall execute, can be
nested
• If without else implies storage (or a latch) i.e. Verilog register variable hold
their value when not driven, therefore hardware storage elements are
required (a latch)
• From synthesis point of view it is a good design practise for every “if” to
have an “else” statement unless you need storage
• In the examples on the next slide check that which code infer a latch and
which one does not (check the inclusion of “else” statement)
if (count > 0) begin
if (a > b) out = a;
else out=c;
end
else out = b;
3ST Technologies Verilog HDL STWT 122
Behavioral Modeling
• Behavioral Modeling – if – else construct - examples
module latch(x, y, sel);
output reg x;
input sel, y;
always @ (*)
begin
if (sel)
x=y;
end
endmodule

module latch(x, y, sel);


output reg x ;
input sel, y;
always @ (*)
begin
if (sel) x=y;
else x=1;
end
endmodule
3ST Technologies Verilog HDL STWT 123
Behavioral Modeling
• Behavioral Modeling – if – else construct – examples
• Modelling an ALU using if - else
module alu ( result , a , b , c, sel, enable ) ;
output reg [15:0] result;
input [3:0] a, b, c;
input [2:0] sel;
always @ (posedge enable)
begin
if (sel==2’b00)
result=a+b;
else if (sel==2’b01)
result=a-b;
else if (sel==2’b10)
result=a*b;
else result=a%b;
end
endmodule
3ST Technologies Verilog HDL STWT 124
Behavioral Modeling
• Behavioral Modeling – if – else construct – examples
• Modelling a 4 bit up down counter
module counter (count, data_in, clk, reset, load, up);
output reg [3:0] count;
input clk, reset, load, up;
input [3:0] data_in;

always @( posedge clk , negedge reset)


begin
if( !reset)
q <= 4'b0000;
else if( load )
q <= data_in;
else if( up)
q <= q + 1;
else
q <= q - 1;
end
endmodule
3ST Technologies Verilog HDL STWT 125
Behavioral Modeling
• Behavioral Modeling – if – else construct – examples
• Modelling an asynchronous set/reset d flip flop
module dff_sr_asynch (input d, set, rst, clk, output reg q, q_bar );

always @(posedge clk, negedge rst , negedge set)


begin
if ( !set ) begin
q <= #4 1'b1;
q_bar <= #3 1'b0;
end else if( !rst ) begin
q <= #4 1'b0;
q_bar <= #3 1'b1;
end else begin
q <= #4 d;
q_bar <= #3 ~d;
end
end
endmodule

3ST Technologies Verilog HDL STWT 126


Behavioral Modeling
• Behavioral Modeling – if – else construct – examples
• Modelling 4 bit shift register
module shift_reg(q, s_cnt , sr, sl, ld, rst, d_in, clk);
input [3:0] d_in, [1:0] s_cnt;
input clk, sr, sl, ld, rst;
output reg [3:0] q;
reg [3:0] int_q;
always @(d_in, q, s_cnt, sr, sl, ld) begin : combinational
if ( ld )
int_q = d_in;
else if ( sr )
int_q = q >> s_cnt;
else if ( sl )
int_q = q << s_cnt;
else int_q = q;
end : combinational
always @( posedge clk ) begin : register
if (rst) q <= 0;
else q <= int_q;
end : register
endmodule
3ST Technologies Verilog HDL STWT 127
Behavioral Modeling
• Behavioral Modeling – Exercise
• Model the following sequential logic using behavioural modelling style

3ST Technologies Verilog HDL STWT 128


Behavioral Modeling
• Behavioral Modeling – Exercise
• Design a 4 bit up down counter and make it configurable
• Design a 4 bit Parallel In Serial Out (PISO) register, Serial In Parallel Out
(SIPO) register, Serial In Serial Out (SISO) register, Parallel In Parallel Out
(PIPO) register
• Design a master slave “d f f ” using two d latch

3ST Technologies Verilog HDL STWT 129


Behavioral Modeling
• Behavioral Modeling – case, casex, casez constructs
• executes at most one branch, depending on the value of the case
expression
• case construct provides another way of multi branch conditional expression
with many alternatives
• case item expressions shall be evaluated and compared in the exact order in
which they are given
• If all comparisons fail and the default item is given, then the default item
statement shall be executed
• If the default statement is not given and all of the comparisons fail, then none
of the case item statements shall be executed
case_statement ::=
case ( expression )
case_item { case_item } endcase
| casez ( expression )
case_item { case_item } endcase
| casex ( expression )
case_item { case_item } endcase
| default [ : ] statement_or_null
3ST Technologies Verilog HDL STWT 130
Behavioral Modeling
• Examples – case, casex, casez
• Handling case with don’t care conditions
• Verilog provide two other cases vs. casex and casez for handling don’t
care conditions
• casex treats ‘x’ and ‘z’ as don’t care
• casez treats ‘z’ as don’t care only
• The syntax of literal numbers allows the use of the question mark (?) in
place of z in these versions of case statement
• casex and casez always matches the case item bit by bit
reg [4:0] instr;
casez (instr) It demonstrates an instruction decode,
where values of the most significant
5'b1???? : opcode (instr1);
bits select which task should be called.
5'b01??? : opcode (instr2); If the most significant bit of instr is a 1,
5'b0001? : opcode (instr3); then the task instr1 is called, regardless
5'b00001 : opcode (instr4); of the values of the other bits of instr.
default : opcode(instr1);
endcase
3ST Technologies Verilog HDL STWT 131
case, casex, casez - Example
module case_compare; 1’bz : $display(“Normal : Logix z on sel”);
reg sel; endcase
initial begin always @ (sel)
#10 $display(“\n Driving 0”); casex (sel)
sel = 0; 1’b0 : $display(“CASEX : Logic 0 on sel”);
#10 $display(“\n Driving 1”); 1'b1 : $display(“CASEX : Logic 1 on sel");
sel = 1; 1’bx : $display(“CASEX : Logic x on sel”);
#10 $display(“\n Driving x”); 1’bz : $display(“CASEX : Logix z on sel”);
sel = 1’bx; endcase
#10 $display(“\n Driving z”); always @ (sel)
sel = 1’bz; casez (sel)
#10 $finish; 1’b0 : $display(“CASEZ : Logic 0 on sel”);
end 1'b1 : $display(“CASEZ : Logic 1 on sel");
always @ (sel) 1’bx : $display(“CASEZ : Logic x on sel”);
case (sel) 1’bz : $display(“CASEZ : Logix z on sel”);
1’b0 : $display(“Normal : Logic 0 on sel”); endcase
1'b1 : $display("Normal : Logic 1 on sel"); endmodule
1’bx : $display(“Normal : Logic x on sel”);

3ST Technologies Verilog HDL STWT 132


Behavioral Modeling
• Examples – case, casex, casez
module encoder(result, a);
input [7:0] a;
output reg [2:0] result;
always @ (a) begin
case (a)
8'b00000001: result = 3'b000;
8'b00000010: result = 3'b001;
8'b00000100: result = 3'b010;
8'b00001000: result = 3'b011;
8'b00010000: result = 3'b100;
8'b00100000: result = 3'b101;
8'b01000000: result = 3'b110;
8'b10000000: result = 3'b111;
default : result = 3'b111;
endcase
end
endmodule
3ST Technologies Verilog HDL STWT 133
Behavioral Modeling
• Examples – case, casex, casez
• Modeling 4 x 1 mux using case statement
module mux_4x1 (y, a, b, c, d, sel);
input a, b, c, d;
input [1:0] sel;
output y;
always @(a, b, c, d, sel)
begin
case(sel)
2’b00 : y=a;
2’b01 : y=b;
2’b10 : y=c;
2’b11 : y=d;
endcase
end
endmodule

3ST Technologies Verilog HDL STWT 134


Behavioral Modeling
• Examples – case, casex, casez
• Modeling 4 x 1 mux using case statement
module mux_4x1 (y, a, b, c, d, sel);
input a, b, c, d;
input [1:0] sel;
output y;
always @(a, b, c, d, sel)
begin
case(sel)
2’b00:y=a;
2’b01:y=b;
2’b10:y=c;
default y=1;
endcase
end
endmodule

3ST Technologies Verilog HDL STWT 135


Behavioral Modeling
• Examples – case, casex, casez
• Modeling 4 x 1 mux using case statement
// this will create a latch as there is no default
// statement and not all options are covered
module mux_4x1 (y, a, b, c, d, sel);
input a, b, c, d;
input [1:0] sel;
output y;
always @(a, b, c, d, sel)
begin
case(sel)
2’b00 : y=a;
2’b01 : y=b;
2’b10 : y=c;
endcase
end
endmodule
3ST Technologies Verilog HDL STWT 136
Behavioral Modeling
• Behavioral Modeling – Guess the model
module display(led , clk)
input clk;
output reg [6:0] led ;
integer count = 1;
always @ (posedge clk)
count <= count+1;
always @ (posedge clk) begin
case(count)
0 : y <= 7'b0000001;
1 : y <= 7'b1001111;
2 : y <= 7'b0010010;
3 : y <= 7'b0000110;
4 : y <= 7'b1001100;
5 : y <= 7'b0100100;
6 : y <= 7'b0100000;
7 : y <= 7'b0001111;
8 : y <= 7'b0000000;
9 : y <= 7'b0000100;
endcase end endmodule
3ST Technologies Verilog HDL STWT 137
Behavioral Modeling
• Examples – case, casex, casez
• Handling case with don’t care conditions
module priority_encoder (sel, bitencoded);
input [4:0] sel;
output reg [2:0] bitencoded;
always @(sel)
begin
casex(sel)
5'bxxxx1 : bitencoded=1;
5'bxxx10 : bitencoded=2;
5'bxx100 : bitencoded=3;
5'bx1000 : bitencoded=4;
5'b10000 : bitencoded=5;
default bitencoded=0;
endcase
end
endmodule
3ST Technologies Verilog HDL STWT 138
Behavioral Modeling
• Procedural loops : forever, while, for, repeat, do while
• repeat : executes a statement a fixed number of times, if the expression
evaluates to unknown or high impedance, it shall be treated as zero, and no
statement shall be executed
• forever : continuously executes a statement
• while : executes a statement until an expression becomes false, if the
expression starts out false, the statement shall not be executed at all
• for : controls execution of its associated statement(s) by a three-step
process, as follows:
• An initial condition
• A check to see if the terminating condition is true
• A procedural assignment to change value of the control variable
• do-while : execute once and then check for expression condition to be
false/true, if false stop the execution else continue execution

3ST Technologies Verilog HDL STWT 139


Behavioral Modeling
• Procedural loops : repeat
• repeat : executes statements within its begin-end block a fixed number of
times that is evaluated once at the beginning of the loop
integer var1, i; parameter cycle=8;
initial begin always @(posedge clock)
var1=8; begin
i=0; if (data_start) // data start signal is true
repeat (var1) begin : repeat_loop begin
i=i+1; i = 0;
$display(“i=%d”, i); repeat (cycle) begin
end : repeat_loop @(posedge clock) buffer[i] = data;
end i = i + 1;
end
initial begin end
count = 255; end
repeat (255) begin endmodule
$display("Count = %d", count);
count =count - 2; This will decrease the value of
end count by 2 and repeat this
end procedure 255 times
3ST Technologies Verilog HDL STWT 140
Behavioral Modeling
• Procedural loops : forever
• forever : executes the statements within its begin-end block forever, without
any variable to control it until the simulation session terminates
• It is therefore important to have a suspension mechanism for forever
• Forever block must always be used in test bench
• $finish system task can be used to finish off a forever block

reg clk;
initial begin
clk=0;
forever #5 clk=~clk;
end

reg clock; This will run the forever


reg x, y; block synchronous with
initial posedge of clock
forever @ (posedge clock) x = y;

3ST Technologies Verilog HDL STWT 141


Behavioral Modeling
• Procedural loops : while
• while : executes the statements within its begin-end block indefinitely, until its
expression becomes false
• The loop expression will also evaluate to false if it has an x or z value
module PYTHAGORAS (X, Y, Z);
input [63:0] X, Y;
output [63:0] Z;
parameter Epsilon = 1.0E-6;
real RX, RY, X2Y2, A, B; initial begin
always @(X or Y) begin
i = 0;
RX = $bitstoreal(X);
RY = $bitstoreal(Y);
while ( i < 12 )
X2Y2 = (RX * RX) + (RY * RY); begin
B = X2Y2; $display("Count = %d", i);
A = 0.0; i = i +1;
while ((A - B) > Epsilon || (A - B) < -Epsilon) begin end
A = B; end
B = (A + X2Y2 / A) / 2.0;
end
end
assign Z = $realtobits(A);
endmodule
3ST Technologies Verilog HDL STWT 142
Behavioral Modeling
• Procedural loops : for, do while
• for : executes the statements within its begin-end block, based on the
number of times its variable is modified, in steps, until the variable evaluates
to X or Z or false integer i ;
initial begin
for ( i=0 ; i<100 ; i=1+1 ) begin
$display(“count=%d “, i)
end
end
• do while : executes the statements within its begin-end block, until the
variable within the while statement evaluates to X or Z or false, the
expression is evaluated at the end of the loop (the loop runs at-least once)
module test_do_while;
integer i;
initial begin
i = 4’d2;
do begin
i++;
end while (i <= 4’d15);
$display(“ i = %0d”, i);
end
endmodule
3ST Technologies Verilog HDL STWT 143
Session VII
Functions
and
Tasks
3ST Technologies Verilog HDL STWT 144
Functions and Tasks
• Functions – procedural blocks
• Functions are defined inside the module in which they are used
• It is possible to define functions in separate files and use compile
directive `include to include the function definition within a module, this
is usually done when a function is to be included in different modules
• Function can call another function and itself but can not call task i.e.
there is a difference in the way functions and tasks work
• There are no delay, no timing or event control constructs used inside a
function i.e. you can’t use #, @, wait, <=
• The function (procedure) returns a single value
• There must be at least one input argument
• There are no output or inout arguments
• The output of the function is returned by the name of the function
• The variables declared within the function remain local to the function
• The order of declaration of inputs within the function defines how the
variables are passed to the function by caller
3ST Technologies Verilog HDL STWT 145
Functions and Tasks
• Functions – procedural blocks - examples
function [automatic] [function_range_or_type] function_identifier ;
function_item_declaration { function_item_declaration }
function_statement
endfunction SYNTAX OF FUNCTION DEFINITION

Defining a
Function
function [7:0] getbytexor;
input [15:0] data;
begin
getbytexor = ^data;
end function [7:0] getbyteor (input [15:0] data);
endfunction begin
getbyteor = |data;
end
endfunction
3ST Technologies Verilog HDL STWT 146
Functions and Tasks
• Functions – procedural blocks - examples
module arithmetic_unit (res_1, res_2,
operand_1, operand_2);
output [4:0] res_1, [3:0] res_2;
input [3:0] operand_1, operand_2;
reg[7:0] CheckSum; assign res_1 = sum_operands (operand_1, operand_2);
function[7:0] doCheckSum; assign res_2 = largest_of_two (operand_1, operand_2);
input[63:0] DataArray; function [4:0] sum_operands ;
reg[15:0] temp1, temp2; // local declarations input [3:0] operand_1, operand_2;
begin begin
temp1 = DataArray[15:0] ^ DataArray[31:16]; sum_operands= operand_1 + operand_2;
temp2 = DataArray[63:48] ^ DataArray[47:32]; end
doCheckSum = temp1[7:0] + endfunction
temp2[7:0] ^ temp1[15:8] + function [3:0] largest_of_two;
temp2[15:8]; input operand_1, operand_2;
end begin
endfunction largest_of_two= (operand_1 > operand_2) ?
operand_1 : operand_2;
end
endfunction
endmodule

3ST Technologies Verilog HDL STWT 147


Functions and Tasks
• Functions – simple processor using functions example
module simple_processor (instruction, outp); 8’b10001010: begin // increment operand
input [31:0] instruction; add_func = 1;
output [7:0] outp; opr2 = 8’b00000001;
reg [7:0] outp;; // one can assign it always block end
reg func; default : begin; // decrement operand
reg [7:0] opr1, opr2; add_func = 0;
function [16:0] decode_add; opr2 = 8’b00000001;
input [31:0] instr; // returns 1 1-bit plus 2 8-bits end
reg add_func; endcase
reg [7:0] opcode, opr1, opr2; // concatenated into 17-bits
begin decode_add = {add_func, opr2, opr1};
opcode = instr[31:24]; end
opr1 = instr[7:0]; endfunction
case (opcode) // ----------------------------------------- -----------------
8’b10001000: begin // add two operands always @(instruction) begin
add_func = 1; {func, op2, op1} = decode_add (instruction);
opr2 = instr[15:8]; if (func == 1)
end outp = op1 + op2;
8’b10001001: begin // subtract two operands else
add_func = 0; outp = op1 - op2;
opr2 = instr[15:8]; end
end endmodule
3ST Technologies Verilog HDL STWT 148
Functions and Tasks
• Functions – procedural blocks – keyword automatic
module factorialtb;
What is this?
function automatic integer factorial;
What does keyword
input [31:0] operand;
integer i;
“automatic” do
begin
Problem : Functions are normally used
if (operand >= 2)
factorial = factorial (operand - 1) * operand; as non recursively. If a function is called
else concurrently from two locations, the
factorial = 1; results are non deterministic because
end both calls operate on the same variable
endfunction space.
integer result;
integer n; Solution : the “automatic keyword can
initial begin be used to declare a recursive
for (n = 0; n <= 7; n = n+1) begin
(automatic) function where all function
result = factorial(n);
$display("%0d factorial=%0d", n, result); declarations are allocated dynamically
end for each recursive calls. Each call to an
end automatic function operates in an
endmodule independent stack or variable space.
3ST Technologies Verilog HDL STWT 149
Functions and Tasks
• Functions – procedural blocks – example
module wd_algn (w_in, w_out);
input [7:0] w_in;
output [7:0] w_out;
assign w_out = align (w_in);
function [7:0] align;
input [7:0] word;
begin
align = word;
if (align != 0)
while (align[7] == 0)
align = align << 1;
end
endfunction
endmodule

3ST Technologies Verilog HDL STWT 150


Functions and Tasks
• Functions – procedural blocks – exercise
• Model the following diagram using function definition for the combinational logic
part ‘+’ and ‘x’ and use always block to model the sequential part

3ST Technologies Verilog HDL STWT 151


Functions and Tasks
• Functions – procedural blocks – exercise
• The ‘x’ part is shown as sampled model
function [15:0] mult;
input [7:0] a, b;
reg [15:0] r;
integer i;
begin
if (a[0] == 1) r = b;
else r = 0;
for (i = 1; i < 8; i = i + 1)
begin
if (a[i] == 1)
r = r + b << i;
end
mult = r;
end
endfunction
3ST Technologies Verilog HDL STWT 152
Functions and Tasks
• Tasks – procedural blocks
• Provide a way out to break a large behavioural design into smaller pieces
• Task and function allow the designer to abstract verilog code that is used at
many places in the design reducing code repetition
• Task are declared with the keywords task and endtask
• Usually Tasks are defined in the module (local) in which they are used
• It is possible to define a task in a separate file also and use the complier
directive `include to include the task in the file in which it is instantiated
• The order of declaration of arguments within the task defines how the
argument are passed to the task by the caller
• The variable declared within the task are local to that task
• Task may have delay, timing, or event control constructs in the procedure
• The procedure can have zero or more than zero input, output arguments
• A task can call another task and functions also
• A task can be used for modelling combinational as well as sequential logic
• The following are the restrictions of using automatic tasks & functions
• Only blocking assignments can be used on automatic variables
• The variables in an automatic task shall not be referenced by procedural
continuous assignments or procedural force statements
3ST Technologies Verilog HDL STWT 153
Functions and Tasks
• Tasks – procedural blocks – declaration and example
task_declaration ::=
task [ automatic ] task_identifier (task_port_list ) ;
{ task_item_declaration } // file task.v
statement task operation;
endtask output [3:0] ab_and, ab_or, ab_xor; //outputs from the task
input [3:0] a, b; //inputs to the task
begin
Defining a task #10 ab_and = a & b;
ab_or = (a | b);
ab_xor = a ^ b;
end
endtask
module decl_task (cd_and, cd_or, cd_xor, c, d);
ouptut reg [3:0] cd_and, cd_or, cd_xor;
input [3:0] c, d;
`include “task.v”
always @(c, d)
operation(cd_and, cd_or, cd_xor, c, d);
endmodule
3ST Technologies Verilog HDL STWT 154
Functions and Tasks
• Tasks – procedural blocks – example traffic light
module traffic_lights;
reg clock, red, amber, green; task light;
parameter on = 1, off = 0, red_tics = 350, output color;
amber_tics = 30, green_tics = 200; input [31:0] tics;
initial begin begin
red = off; amber = off; green = off; repeat (tics) @ (posedge clock);
end color = off; // turn light off
always begin // sequence to control the lights. end
red = on; // turn red light on endtask
light(red, red_tics); // and wait. endmodule
green = on; // turn green light on
light(green, green_tics); // and wait.
amber = on; // turn amber light on
light(amber, amber_tics); // and wait.
end
always begin
#100 clock = 0;
#100 clock = 1;
end
3ST Technologies Verilog HDL STWT 155
Functions and Tasks
• Tasks – example – What does the following task do?
module bit_counter (data, count);
input [7:0] data;
output [3:0] count; reg [3:0] count;

always @(data) t(data, count);

task t;
input [7:0] a; output [3:0] c; reg [3:0] c; reg [7:0] tmp;
begin c = 0; tmp = a;
while (tmp)
begin
c = c + tmp[0];
tmp = tmp >> 1;
end
end
endtask
endmodule

3ST Technologies Verilog HDL STWT 156


Functions and Tasks
• Differences – automatic & static
Reentrant task Static task
Has the keyword automatic between Doesn’t have the keyword automatic
the task keyword and identifier between the task keyword and the
identifier
Variables declared within the task are Variable declarations within the task
allocated dynamically for each are allocated statically
concurrent task call
All variables will be replicated in each Each concurrent call to task will
concurrent call to store state specific overwrite the statically allocated local
to that invocation variables of the task from all other
concurrent calls to the task
Task items can’t be accessed by Task items can be accessed by
hierarchical inferences hierarchical inferences
Task items shall be allowed to be new Task items can be shared across all
across all uses of the task executing uses of the task executing concurrently
concurrently
3ST Technologies Verilog HDL STWT 157
Session VIII
FSM

3ST Technologies Verilog HDL STWT 158


Finite State Machines
• FSM
• State memory : Set of n flip-flops that hold the state of the machine (up to
2^n distinct states)
• Next state logic : Combinational circuit that determines the next state as a
function of the current state and the input
• Output logic: Combinational circuit that determines the output as a function
of the current state and the input
PREVIOUS STATE

STATE MEMORY
SET
D Q
OUTPUTS
NEXT CLR Q
NEXT STATE STATE OUTPUT LOGIC
INPUTS LOGIC ...
SET
D Q

CLR Q

CLK
3ST Technologies Verilog HDL STWT 159
Finite State Machines
• FSM – Mealy and Moore machines
• Mealy machine : The output depends on the current state and inputs
PREVIOUS STATE

STATE MEMORY
SET
D Q
OUTPUTS
NEXT CLR Q
COMBINATIONAL STATE OUTPUT LOGIC

...
INPUTS LOGIC
SET
D Q

CLR Q

CLK

3ST Technologies Verilog HDL STWT 160


Finite State Machines
• FSM – Mealy and Moore machines
• Moore machine : The output depends only on the current state
• State = output state machine : a Moore type FSM where the current
state is the output
PREVIOUS STATE

STATE MEMORY
SET
D Q

NEXT CLR Q OUTPUTS


COMBINATIONAL STATE
...

INPUTS LOGIC
D
SET
Q PREVIOUS STATE

CLR Q
STATE MEMORY
SET
D Q
OUTPUTS
NEXT CLR Q
CLK COMBINATIONAL OUTPUT LOGIC
STATE

...
INPUTS LOGIC
SET
D Q

CLR Q

CLK
3ST Technologies Verilog HDL STWT 161
Finite State Machines
• FSM – Mealy machines – State Table
A B x A+ B+ y
0 0 0 0 0 0
0 0 1 0 1 0
0 1 0 0 0 1
0 1 1 1 1 0
1 0 0 0 0 1
1 0 1 1 0 0
1 1 0 0 0 1
1 1 1 1 0 0

3ST Technologies Verilog HDL STWT 162


Finite State Machines
• FSM – Mealy machines – State Diagram
• A state diagram represents the states as circles and the transitions between
them as arrows annotated with inputs and outputs
1/0
0/0
0/1
00 10

0/1
1/0 0/1 1/0

1/0
01 11

3ST Technologies Verilog HDL STWT 163


Finite State Machines
• Mealy machines – Solving equations using K - Map
A B x A+ B+ y AB
00 01 11 10
0 0 0 0 0 0 x
0 0 1 0 1 0
0 0 0 0 0
0 1 0 0 0 1
0 1 1 1 1 0 1
1 0 0 0 0 1 0 1 1 1
1 0 1 1 0 0 A+ = Ax + Bx
1 1 0 0 0 1
1 1 1 1 0 0
AB 00 01 11 10
AB00 01 11 10
x x
0 0 0 0 0 0 0 1 1 1

1 1
1 1 0 0 0 0 0 0

B+ = A’x y=(A+B)x΄
3ST Technologies Verilog HDL STWT 164
Finite State Machines
• Mealy machine – Gate Level Implementation using DFF

3ST Technologies Verilog HDL STWT 165


Finite State Machines
• Mealy machine – Verilog Implementation
module mealymachine (y, x, reset, clk);
output reg y;
input x, clk, reset;
reg [1:0] state;
reg [1:0] next_state;
parameter A=2'b00, B=2'b01, C=2'b10, D=2'b11;
always @(x, state) begin
case (state)
A : begin next_state = x ? C : A; y=0; end
B : begin next_state = x ? B : A; y = x ? 0 : 1; end
C : begin next_state = x ? D : A; y = x ? 0 : 1; end
D : begin next_state = x ? B : A; y = x ? 0 : 1; end
endcase
end
always @(posedge clk) begin
if (reset)
state = A;
else
state = next_state;
end
endmodule
3ST Technologies Verilog HDL STWT 166
Finite State Machines
• Mealy and Moore machine – Sequence 11011 Detector
• Write verilog implementation of mealy and moore machine for
the following FSM

3ST Technologies Verilog HDL STWT 167


Finite State Machines
• Mealy machine – Sequence 11011 Detector
module mealymachine(y, x, reset, clk);
output reg y;
input x,clk,reset;
reg [2:0]state; // assignment of next state
reg [2:0] next_state; // to present state
parameter A=3'b000, B=3'b001, C=3'b010, always @(posedge clk)
D=3'b100, E=3'b101; begin
// next state logic and output logic if (reset)
always@(x, state) state = A;
begin else
case(state) state = next_state;
A : begin next_state = x ? B : A; y = 0; end end
B : begin next_state = x ? C : A; y = 0; end endmodule
C : begin next_state = x ? C : D; y = 0; end
D : begin next_state = x ? E : A; y = 0; end
E : begin next_state = x ? C : A; y = x ? 1 : 0; end
default: begin next_state = 3'bxxx; y = ‘bx; end
endcase
end
3ST Technologies Verilog HDL STWT 168
Finite State Machines
• Moore machine – Sequence 11011 Detector
module mooremachine(y, x, reset, clk); // assignment of next state
output reg y; // to present state
input x,clk,reset; always @(posedge clk)
reg [2:0] state; begin
reg [2:0] next_state; if (reset)
parameter A=3'b000, B=3'b001, C=3'b010, state = A;
D=3'b100, E=3'b101; else
state = next_state;
// next state logic end
always@(x, state) // output logic
begin always@(state)
case(state) begin
A : begin next_state = x ? B : A; end if (state==E)
B : begin next_state = x ? C : A; end y = x ? 1 : 0;
C : begin next_state = x ? C : D; end else
D : begin next_state = x ? E : A; end y = 0;
E : begin next_state = x ? C : A; end end
default : begin next_state = 3'bxxx; end endmodule
endcase
end
3ST Technologies Verilog HDL STWT 169
Finite State Machines
• FSM - Exercises
• Construct an FSM that outputs 1 iff the input bits read so far are 111 and write its
verilog code and simulate it
• Construct a finite state machine that gives an output of 1 if the number of bits read so
far is divisible by 3 and an output of 0 otherwise
• Construct a finite state machine that determines whether the input bits has a 0 in the
third to the last position read so far. (e.g. the output for the input bits 00001011 is:
00110100)
• Design the circuit for the left and right indicator lights in a car
Inputs : Clock : Frequency equal to the flashing rate
Reset : for initializing flip-flops
Left, Right : normally zero, remain one for the duration of the turn
Emergency: Rising edge active, both lights should be flashing
• Write verilog code for this following state machine

3ST Technologies Verilog HDL STWT 170


Finite State Machines
• FSM – Intelligent Traffic Light Controller
• To use a finite state machine to control the traffic lights at an intersection of
a north-south route and an east-west route
• Consider only the green and red lights
• Consider the lights to change no faster than 30 seconds in each direction so
we use a 0.033 Hz clock

3ST Technologies Verilog HDL STWT 171


Finite State Machines
• FSM – Intelligent Traffic Light Controller
• There are two output signals
• NSlite : When the signal is asserted, the light on the north-south route is
green; otherwise, it should be red
• EWlite : When the signal is asserted, the light on the east-west route is
green; otherwise, it should be red
• There are two inputs
• NScar : Indicates that there is at least one car that is over the detectors
placed in the roadbed in the north-south road
• EWcar : Indicates that there is at least one car that is over the detectors
placed in the roadbed in the east-west road
• The traffic lights should only change from one direction to the other only if
there is a car waiting in the other direction
• Otherwise, the light should continue to show green in the same direction

3ST Technologies Verilog HDL STWT 172

You might also like