Verilog Course
Verilog Course
com
Course Curriculum
Summer Training
Verilog
HDL
Verilog HDL 1
www.dkoplabs.com
Contents
• Basics of Verilog HDL language
Introduction
History
Need
HDL vs. Programming Languages : Basic Difference
Simulation model
digital design flow : steps & tools
modeling styles in verilog
References
Gate level modeling
gate primitives
single gate h/w model
more than one gate modeling and concept of wire
about wire
Verilog HDL 2
www.dkoplabs.com
Contents
• Basics of Verilog HDL language
Gate Level Modeling (cont.)
4 value logic system
hierarchy creation
module instantiation
ports and their mapping
writing a test bench
reg
regular delay
stimulus writing
system task
concept of initial block
Dataflow modeling
Verilog HDL 3
www.dkoplabs.com
Contents
• Basics of Verilog HDL language
Operators
bitwise
arithmetic
logical
reduction
shift
relational
equality
concatenation
replication
conditional
operator precedence
Verilog HDL 4
www.dkoplabs.com
Contents
• Basics of Verilog HDL language
Verilog Language & data types
keywords
bnf, syntax and semantics
case sensitive, comments
naming convention for identifiers, escaped identifiers
number representation & formats
strings
data types
vectors
arrays – memories, mda’s
array of instances
bit & part select and width mismatch
Verilog HDL 5
www.dkoplabs.com
Contents
• Basics of Verilog HDL language
Modeling Delays
Behavioral modeling
initial & always procedural blocks
different methods of generating a clock
blocking and non blocking assignments
execution control in procedural blocks
delays – regular, intra-assignment, zero
event control (sequential circuit modeling)
edge triggered
level triggered
procedural statements
single if, if else, nested if i.e. if – else if
case, casex, casez
Verilog HDL 6
www.dkoplabs.com
Contents
• Basics of Verilog HDL language
Behavioral modeling contd.
procedural statements contd.
for, while, repeat, forever
disable
constants – localparam, parameter, defparam
functions & tasks
generate – for, if, case – verilog 2001 feature
System tasks
Compiler directives
File I/O
Verilog HDL 7
www.dkoplabs.com
Contents
• Basics of Verilog HDL language
Design Examples
How to model same logic in all the modeling styles
FSM
ALU
ROM & RAM
TRAFFIC LIGHT SIGNAL
Verilog HDL 8
www.dkoplabs.com
Session I
Introduction
Verilog HDL 9
www.dkoplabs.com
History
• Word Verilog is derived from Latin word veritas (meaning truth), and
Greek word logos (meaning reason, idea, word)
• Verilog therefore means expressing the truth of your idea
• Verilog originated at Gateway Design Automation in 1983-1984 for
simulation of digital circuits
• Prabhu Goel, a founder member of Gateway Design Automation,
along with Phill Moorby released Verilog HDL in 1983
• Enhanced for ASIC design 1987–1989
• Synopsys introduced Verilog logic synthesis 1987
• Cadence acquired Gateway Design Automation in 1990 and puts
Verilog HDL in the public domain by donating it to IEEE
• Open Verilog International (OVI) formed to maintain Verilog
standards
• IEEE standardize Verilog and creates LRM – IEEE-1364 in 1995
• LRM revised in 2001 - IEEE-1364 – 2001 (many enhancements)
Verilog HDL 10
www.dkoplabs.com
Need
• Integral part of the Design Process for Digital Circuit Design
• Universally available as a Public Document
• Provide constructs that are natural to a h/w designer
• Flexible and easily extendable by the user
• Support multiple levels of abstraction and modeling
• Allow different design approaches(methodologies)
• top – down
• bottom - up
• Technology and Process Independence
• Ease of Design Exchange and Re-use
• Primarily aimed at Designing once and using a synthesis tool to target
different implémentations technologies:
• ASIC
• FPGA
• CPLD
Verilog HDL 11
www.dkoplabs.com
Elaborator/
Hardware
linker
Executable/
application
Verilog HDL 12
www.dkoplabs.com
Simulation Model
• A simulator work as an Operating System (Why?)
• Does Scheduling of signal(s) and process(es)
• Advances Simulation Time (Cycle)
• Elaboration and initialization done before simulation
Start Simulation
End Simulation
Verilog HDL 13
www.dkoplabs.com
Modeling Styles
• Gate Level
• Hardware implemented in terms of logic gates with
interconnections between these gates
• Design at this level is similar to describing the design in
terms of gate level logical diagram (white box)
• mainly used to model combinational logic design
• Dataflow
• Hardware implemented by specifying the data flow
• Designer is aware of how the data flows between registers
functionally (black box)
• Also used to describes data flow between registers known as
RTL (Register Transfer Level) – a type of dataflow modeling
used for the purpose of synthesis
Verilog HDL 15
www.dkoplabs.com
Modeling Styles
• Behavioral
• Used to model the behavior of a design without the concern
for the hardware implementation details, i.e., at the abstract
level or highest level of abstraction (black box)
• Designing at this level is very similar to C programming but
with h/w design in the mind
• Mainly used to model sequential logic design
• Also used to describe RTL (Register Transfer Level) – a type of
behavioral modeling used for the purpose of synthesis
• Switch Level
• Lowest level of abstraction provided by verilog with
switches/transistors having nodes and interconnection
between them (white box)
• experienced designers use this style
Verilog HDL 16
www.dkoplabs.com
References
• Verilog Primer
By J. Bhasker
• Web-Site : www.asic-world.com
Verilog HDL 17
www.dkoplabs.com
Session II
Gate Level Modeling
Verilog HDL 18
www.dkoplabs.com
Gate Primitives
• Gate Level Primitives
• Verilog HDL
provides basic
gates as built-in
primitives as
shown
Verilog HDL 19
www.dkoplabs.com
Verilog HDL 20
www.dkoplabs.com
Verilog HDL 21
www.dkoplabs.com
Verilog HDL 22
www.dkoplabs.com
About wire
•Electrically connect different parts of a h/w together
i.e. act as an interconnection mechanism between
different hardware elements
•Usually used on the left hand side in an assignment
statement
• it is said to be driven
•Can have multiple drivers “Fan-Out”
•Multiple drivers are resolved using resolution table
•Used to tie gates and behavioral blocks together
• Defaults to a logic value ‘z’ i.e. high impedance state
if no driver or if not connected
Verilog HDL 23
www.dkoplabs.com
Verilog HDL 24
www.dkoplabs.com
Hierarchy Creation
• Design Hierarchy : h/w inside h/w or design inside design
• Higher level design instantiates lower level designs
• Draw the design hierarchy for the following CPU model
Verilog HDL 25
www.dkoplabs.com
Module Instantiation
• Using half-adder instances to create full-adder
Verilog HDL 26
www.dkoplabs.com
Ports
• input, output
• inout - bi-directional (can drive, can be driven)
Verilog HDL 27
www.dkoplabs.com
Ports
• ports provide an interface by which a module can
communicate with its environment
• if an output port has to hold a value then it must be
declared as reg
• all port declarations are implicitly declared as wire
• input/output ports can be declared as reg
• when modules are instantiated within another
• input must always be treated like a wire (net) which
externally connect to a reg or net
• output can be considered as a net or reg, it must externally
connect to a net
• inout must always be treated like a net which externally
connect to a net
Verilog HDL 28
www.dkoplabs.com
Port Mapping
• port association – named vs. positional
module mux4_to_1(out, i0, i1, i2, i3, s1, s0); // design module
output out;
input i0, i1, i2, i3, s1, s0;
…………
endmodule
Verilog HDL 29
www.dkoplabs.com
Writing a test-bench
• Points to remember for writing a test-bench
• No input/output port declarations
• h/w to be tested is instantiated as module instance
• h/w inputs declared as reg, outputs declared as wire in TB
• Stimulus i.e. input value changes are written in an initial block
• Output values are monitored whenever input values change,
monitor matches printf in “C” and its called a system task
represented with the first character as $
• Initial block is written to change initial values at different
simulation times and to monitor them
• Regular or absolute delays are used with # as first character
• reg assignment and initialization happens through bit format
• Bit format is <length>’<base_format><actual_value> e.g. 2’b11
Verilog HDL 30
www.dkoplabs.com
Writing a Test-Bench
module tb_half_adder;
wire s, c; //outputs
reg a, b; //inputs
half_adder ha1(s, c, a, b);
initial
begin
$monitor(“time = %d, s = %b, c = %b, a = %b, b = %b”, $time, s, c, a, b);
end
initial
A B C S
begin
#10 a = 1’b0; b = 1’b0; 0 0 0 0
#10 a = 1’b0; b = 1’b1;
0 1 0 1
#10 a = 1’b1; b = 1’b0;
#10 a = 1’b1; b = 1’b1; 1 0 0 1
end 1 1 1 0
endmodule
Verilog HDL 31
www.dkoplabs.com
Writing a Test-Bench
• Test-Bench components
• reg (registers – storage element)
• Defines storage, but not necessarily a data latch
• Can only be changed by assigning new value to them
• defaults to logic value ‘x’ – unknown
• System task
• $monitor(“time=%d, s=%b, c=%b, a=%b, b=%b”, $time, s, c,
a, b);
• %d means decimal format, %b means binary format
• $monitor is a system tasks for monitoring value changes in s,
c, a, b, $time represents the current simulation time
• try the test-bench without the $ sign and see what happens
• monitor will be treated as any other name
• what kind of error will it be - compilation or simulation?
Verilog HDL 32
www.dkoplabs.com
Writing a Test-Bench
• Test-Bench components
• initial block
• Used for initializing values
• LRM says that initial block is executed once and only once at
the start of simulation i.e. at 0 time
• Different initial block executes concurrently
• keywords begin and end are used to enclose multiple
statements
• Regular delay, format, assignment
• #10 a = 1’b0; b = 1’b0;
• #10 represents regular delay (in the unit of simulation time)
• 1’b0 bit format, b means binary and 1 means 1 bit
• b = 1’b0 means assignment where = is assignment operator
Verilog HDL 33
www.dkoplabs.com
Waveform Viewing
Verilog HDL 34
www.dkoplabs.com
Session III
Data Flow Modeling
Verilog HDL 35
www.dkoplabs.com
Verilog HDL 36
www.dkoplabs.com
Verilog HDL 37
www.dkoplabs.com
Operators
• Bitwise operators
• Operates on each bit of operand
• Result is in the size of the largest operand
• Left extended if the sizes are different
Verilog HDL 39
www.dkoplabs.com
Operators
• Arithmetic operators
• If any operand contains z or x the result is unknown
• If result and operand are of same size then carry is lost
• Treats vectors as a whole value
Verilog HDL 40
www.dkoplabs.com
Operators
• Logical operators
• Can evaluate to 1, 0, x values
• The results is either true (1) or false (0)
Verilog HDL 41
www.dkoplabs.com
Operators
• Reduction operators
• Operator work on each bit of the operand
Verilog HDL 42
www.dkoplabs.com
Operators
• Shift operators
• Shifts the bit of a vector left or right
• Shifted bits are lost
• Arithmetic shift right fills the shifted bits with sign bit
• All others fill the shifted bits by zero
Verilog HDL 43
www.dkoplabs.com
Operators
• Relational operators
• Evaluates to 1, 0, x
• Result in x if any operand bit is z or x
Verilog HDL 44
www.dkoplabs.com
Operators
• Equality – case & if operators
• assign WriteMe = (wr == 1) &&
((a >= 16’h7000) && (a < 16’h8000));
Verilog HDL 45
www.dkoplabs.com
Operators
• Concatenation, Replication, Conditional operators
• Concatenation {}
• wire [3:0] apart;
• wire abit;
• wire [7:0] cbus;
• assign cbus = ,apart, 3’b000, abit};
• Replication (repeat by a number)
• assign cbus = {4{abit-, 4’b0000-;
• Conditional ? :
• assign y = (sel ? a : b); // mux
• assign y = (s1 ? (s0 ? i1 : i2) : (s0 ? i3 : i4)); // can be nested
Verilog HDL 46
www.dkoplabs.com
Operators
• Example - 4 bit comparator, 4 bit divider
Verilog HDL 47
www.dkoplabs.com
Operators
• Example - Concatenation – 4 bit adder
• Example - Conditional – 8 bit comparator (>=)
module binary_adder (S, Cout, A , B , Cin);
output [3:0] S;
output Cout;
input [3:0] A, B;
input Cin;
assign {Cout , S} = A + B + Cin;
endmodule
Verilog HDL 48
www.dkoplabs.com
Operator Precedence
• Operator precedence
• Parenthesis can be used to override the precedence
Verilog HDL 49
www.dkoplabs.com
Session IV
Verilog Language
&
Data Types
Verilog HDL 50
www.dkoplabs.com
Keywords - 1995
Verilog HDL 51
www.dkoplabs.com
Keywords – 2001
automatic cell
config design
endconfig endgenerate
generate genvar
incdir include
instance library
uwire use
Verilog HDL 52
www.dkoplabs.com
Grammar Interpretation
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
Verilog HDL 53
www.dkoplabs.com
Verilog HDL 54
www.dkoplabs.com
Verilog HDL 55
www.dkoplabs.com
Conventions – Naming
• Naming convention
• objects are given different names called identifiers
• Identifiers can be build using a combination of letters [A-Z], [a-z],
digits [0-9+ (can’t be used as the first character in the identifier),
underscore _, $ character (can’t be used as the first character in
the identifier), max 1024 characters allowed in an identifier
• white spaces not allowed
• statements are terminated by ;
• e.g. myid, m_y_id, _myid, myid3 are valid
• $myid, 3my_id are invalid
• Escaped identifiers
• They start with a \ and end with a white space
• They can include printable ASCII characters
• E.g. \ 546 , \ .*.& , \ {***} , \ a+b-c , \Gate#3
Verilog HDL 56
www.dkoplabs.com
Verilog HDL 57
www.dkoplabs.com
Verilog HDL 58
www.dkoplabs.com
Verilog HDL 60
www.dkoplabs.com
Strengths
• net data type strengths
• Verilog allows signals to have logic values and strength values
• Logic values are 0 , 1 , x , z
• Strength values are used to resolve combinations of multiple
signals and to represent behavior of actual hardware elements as
accurately as possible
• Driving strengths are used for signal values that are driven on a
net
• Storage strengths are used to model charge storage in trireg type
nets
• Strength values can be used to resolve signal contention on nets
that have multiple drivers
• There are many rules applicable to resolution of contention
Verilog HDL 64
www.dkoplabs.com
Verilog HDL 65
www.dkoplabs.com
Array of Instances
If the same module needs
to be instantiated in the
Design a number of times
with changing i/o then
one can use array of
instances and Vectors
Example :
// 8 bit ripple carry adder
// using halfadder, fulladder
Fulladder inst[i]
( a[i], b[i], pc[i], s[i], pc[i+1] );
Verilog HDL 66
www.dkoplabs.com
Verilog HDL 67
www.dkoplabs.com
Width Mismatch
• Examples
• wire [15:0] y;
• wire *7:0+ a = ‘hff; // assigns b’11111111
• wire signed [7:0] b = -1 ; // assigns b’11111111
• wire *7:0+ c = 8’bx1010101;
• wire *7:0+ d = 8’bz;
• assign y = a; // fills with ‘b0000000011111111
• assign y = b; // fills with ‘b1111111111111111
• assign y = c; // fills with ‘bxxxxxxxxx1010101;
• assign y = d; // fills with ‘bzzzzzzzzzzzzzzzz;
Verilog HDL 68
www.dkoplabs.com
Session V
Modeling Delays
Verilog HDL 69
www.dkoplabs.com
Verilog HDL 70
www.dkoplabs.com
Delay Example
module delay_tb();
reg a = 1, b = 0, c = 0, d = 0;
initial begin
#15 a = 0;
#20 $finish;
end
initial begin
/* regular delay control where we
evaluate expression at time = 10 */
#10 c = a | b;
/* Intra-assignment delay control where we
evaluate expression now then wait 10 times
to assign value to d */
d = #10 a | b;
end
endmodule
Verilog HDL 71
www.dkoplabs.com
Gate Delays
• Rise delay – transition from 0, x, z to 1
• Fall delay – transition from 1, x, z to 0
• Turn off delay – transition from 0, 1, x to z
• Minimum (min), typical (typ), maximum (max) gate delays
<component_name> #(Rise, Fall, Turnoff) <instance_name> (port_list);
Example :
and #(2) u1(co, a, b); // Delay of 2 for all transitions
and #(1, 3) u2(co, a, b); // Rise = 1, Fall = 3
bufif0 #(1, 2, 3) u3(out, in, enable); // Rise = 1, Fall = 2, Turn-off = 3
Verilog HDL 72
www.dkoplabs.com
Verilog HDL 73
www.dkoplabs.com
wire #2 y_tran;
and #3 and1(y_tran, x1, x2);
buf #1 buf1(buf_out, y_tran);
and #3 and2(y_inertial, x1, x2);
Verilog HDL 74
www.dkoplabs.com
x2
2 4 6 8 10
y_inertial
2 4 6 8 10
y_tran
2 4 6 8 10
buf_out
2 4 6 8 10
Verilog HDL 75
www.dkoplabs.com
x1 x2 x3 f1 f2
0 0 0 0 0
0 0 1 0 1
0 1 0 0 0
0 1 1 0 1
1 0 0 0 0
1 0 1 0 1
1 1 0 1 1
1 1 1 1 1
Verilog HDL 76
www.dkoplabs.com
Verilog HDL 77
www.dkoplabs.com
Session VI
Behavioral Modeling
Verilog HDL 78
www.dkoplabs.com
Behavioral Modeling
• Behavioral modeling style is modeled by initial and always blocks
• initial block - used to initialize behavioral statements
• always block - used to describe the functionality using behavioral
statements
• assign values to register data types (reg, integer, real, time)
• each always and initial block represents a separate parallel process
• processes run in parallel and start at simulation time 0
• statements inside a process execute either
• sequentially (begin - end)
• concurrently (fork - join)
• always and initial blocks cannot be nested
Verilog HDL 79
www.dkoplabs.com
Behavioral Modeling
• Inside initial and always blocks
Verilog HDL 80
www.dkoplabs.com
Behavioral Modeling
• Inside initial and always blocks
Verilog HDL 81
www.dkoplabs.com
Initial Block
• initial block
• initial blocks execute only once during simulation at 0 time and
does not execute again
• Multiple behavioral statement inside an initial block must be
grouped using begin-end or fork-join
• Multiple initial blocks execute concurrently
• initial blocks are generally not synthesizable – mostly used in test-
benches to apply stimulus sequences
• Synthesizable only when used to initialize ROM/RAM contents
• Assignment statements within an initial block
• between begin and end execute sequentially – statement
order matters
• between fork and join execute concurrently – statement
order doesn’t matter
Verilog HDL 82
www.dkoplabs.com
Initial Block
• In an initial block (procedural block), statements are
grouped together to execute sequentially or in parallel
• sequential execution
• statements are enclosed within the keywords begin, end
• statements are processed in the order in which they are specified
• delays specified are additive
reg x, y;
initial
begin
x = 1’b0; //execute at t = 0
y = 1’b1;
#10 x = 1’b1; //executes at t = 10
#15 y = 1’b0; //executes at t = 25
end
Verilog HDL 84
www.dkoplabs.com
Initial Block
• parallel execution
• statements are enclosed within the keyword fork, join
• all statements are executed concurrently
• ordering of statements is controlled by delay or event control
assigned to each statement
• if delay is specified, it is relative to the time the block started
reg x, y;
initial
fork
x = 1’b0;
y = 1’b0;
#10 x = 1’b1;
#20 y = 1’b0;
#20 x = 1’b0;
#40 y = 1’b1;
join
Verilog HDL 85
www.dkoplabs.com
Always Block
• always block
• Used to model a process that is repeated continuously in a digital
circuit
• An always block starts at time 0 and executes the behavioral
statements continuously in an event based looping fashion
• Multiple behavioral statements inside an always block must be
grouped using begin-end or fork-join
• Assignment statements within an always block
• between begin and end execute sequentially – statement
order matters (synthesizable)
• between fork and join execute concurrently – statement
order doesn’t matter (not synthesizable)
Verilog HDL 86
www.dkoplabs.com
Verilog HDL 87
www.dkoplabs.com
module clkgen_25_75_dc;
module clkgen_forever;
reg clk;
reg clk;
initial begin
initial begin
clk = 0;
clk = 0;
end
end
always begin
always begin
#25 clk = 0;
#10 clk = ~clk;
#75 clk = 1;
end
end
endmodule
endmodule
Verilog HDL 88
www.dkoplabs.com
Verilog HDL 89
www.dkoplabs.com
initial begin
a = 1;
b = 0;
a <= b; // a = 0;
b <= a; // b = 1;
end
Verilog HDL 90
www.dkoplabs.com
Verilog HDL 93
www.dkoplabs.com
a sum
Add_half
b c_out
Verilog HDL 96
www.dkoplabs.com
Verilog HDL 97
www.dkoplabs.com
Level Triggering
• level triggering (“wait”)
• Provides level sensitive timing control
• Activity flow is suspended if expression is false
• It resumes when the expression is true
• Other processes keep going
module modA (…); begin
… wait ( !enable ) #10 a = b;
end
always
If the value of enable is 1 when block is
begin entered, the wait statement will delay
… the evaluation of the statement (#10 a =
wait ( enable ) ra = rb; b;) until the value of enable changes to 0.
… If enable is already 0 when the
block is entered, then the assignment “a
end
= b;” is evaluated after a delay of 10 and
endmodule no additional delay occurs.
Verilog HDL 98
www.dkoplabs.com
Race Condition
• 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
endmodule
endmodule
if - else
• if without else implies storage
if – else - Example
• Modeling a D Latch
if – else - Example
• Modeling a flip flop – if else - example
if – else - Example
• Modeling a comparator2
if – else - Example
• Modeling an 8 to 3 bit priority encoder
module priority_encoder(code, sel);
output [2:0] code;
reg [2:0] code;
input [7:0] sel;
always @(sel) begin
if (sel[0]) code <= 3'b000;
else if (sel[1]) code <= 3'b001;
else if (sel[2]) code <= 3'b010;
else if (sel[3]) code <= 3'b011;
else if (sel[4]) code <= 3'b100;
else if (sel[5]) code <= 3'b101;
else if (sel[6]) code <= 3'b110;
else if (sel[7]) code <= 3'b111;
else code <= 3'bxxx;
end
endmodule
if – else - Example
• Modeling a 2x1 and 4x1 mux
module mux4x1(f, s, w0, w1, w2,
module mux2x1(f, s, w0, w1); w3);
output f;
output f;
reg f;
reg f;
input w0, w1, w2, w3;
input w0, w1, s; input [1:0] s;
always @ (*)
always @ (*) if (s == 2’b00)
begin f = w0;
if (s == 0) else if (s == 2’b01)
f = w0; f = w1;
else else if (s == 2’b10)
f = w2;
f = w1;
else if (s == 2’b11)
end
f = w3;
else
endmodule f = 1’bx;
endmodule
Verilog HDL 111
www.dkoplabs.com
if – else - Example
• Modeling an up counter
// 8 bit up counter
module up_counter(out, enable, clk, reset );
output [7:0] out;
input enable, clk, reset;
reg [7:0] out;
always @(posedge clk)
if (reset) begin
out <= 8'b0 ;
end else if (enable) begin
out <= out + 1;
end
endmodule
if – else - Example
• Exercises
• Write an 8 bit down counter
• Write a 4 bit up - down counter with a built in test-bench with up
and down limits checking
if – else - Example
• Modeling an up-down counter using parallel if when the conditions
are mutually exclusive
module parallel_if();
reg [3:0] counter;
reg clk, reset, enable, up_en, down_en;
always @ (posedge clk)
if (reset == 1'b0) // when reset is asserted
counter <= 4'b0000;
else begin
// If counter is enable and up count is mode
if (enable == 1'b1 && up_en == 1'b1)
counter <= counter + 1'b1;
// If counter is enable and down count is mode
if (enable == 1'b1 && down_en == 1'b1)
counter <= counter - 1'b1;
end else
counter <= counter; // see the TB on next page
endmodule
Verilog HDL 114
www.dkoplabs.com
if – else - Example
• Modeling an up-down counter using parallel if when the conditions
are mutually exclusive
initial begin
$monitor("@%0d ns reset=%b enable=%b up=%b down=%b count=%b",
$time, reset, enable, up_en, down_en, counter);
$display("@%0d ns Driving all inputs to know state", $time);
clk = 0; reset = 0; enable = 0; up_en = 0; down_en = 0;
#30 reset = 1;
$display("@%0d ns De-Asserting reset", $time);
#40 enable = 1;
$display("@%0d ns De-Asserting reset", $time);
#40 up_en = 1;
$display("@%0d ns Putting counter in up count mode", $time);
#100 up_en = 0; down_en = 1;
$display("@%0d ns Putting counter in down count mode", $time);
#800 $finish;
end
always #10 clk = ~clk;
Behavioral Modeling
• Procedural statements – case, casex, casez
• case construct in Verilog gives another way to organize a
conditional expression with many alternatives
• behaves like nested if - else statement where case items are
examined in order
• simulation is capable of comparing ‘x’s and ‘z’s explicitly
• casez treats ‘z’ as don’t cares
• casex treats both ‘x’ and ‘z’ as don’t cares
• exact match between case expression and case item
always @(a or b or c or d or s)
begin
case (s)
2'b00 : out = a;
2'b01 : out = b;
2'b10 : out = c;
default : out = d;
endcase
end
endmodule
Procedural Statements
• Procedural statements – forever, repeat, while, for
• Looping statements appear inside procedural blocks only
• forever
• The forever loop executes continuously i.e. the loop never ends
• Normally we use forever statements in initial blocks for clock
generation and synchronization with other hardware in test-
benches
• One should be very careful in using a forever statement because
if no timing construct is present in the forever statement the
simulation could hang
forever - Example
• Procedural statements – forever – named block example
parameter half_cycle = 50;
initial
begin : clock_loop
clock = 0;
forever
begin
#half_cycle clock = 1;
#half_cycle clock = 0;
end
end
initial
#350 disable clock_loop;
repeat - Example
• Procedural statements – repeat – executes the loop a fixed
number of times
integer count; …
initial begin w_address = 0;
count = 0;
repeat ( memory_size )
// repeat the block 128 times
repeat (128) begin
begin memory [w_address] = 0;
$display(“count = %d \n” , count); w_address = w_address + 1;
count = count + ‘1’ ; end
end
…
end
while - Example
• Procedural statements – while – executes the loop as long
as the condition evaluates to true
module while_example(); $display ("DATA = %b,
reg [5:0] loc; LOCATION = %d",
reg [7:0] data; data, loc);
always @ (data or loc) end
begin
loc = 0; initial begin
// when data=0, loc=32 (invalid value) #10 data = 8'b11;
if (data == 0) begin #10 data = 8'b100;
loc = 32; #10 data = 8'b1000;
end else begin #10 data = 8'b1000_0000;
while (data[0] == 0) begin #10 data = 8'b0;
loc = loc + 1; #10 $finish;
data = data >> 1; end
end endmodule
end
Verilog HDL 130
www.dkoplabs.com
for - Example
• Procedural statements – for – example
module for_example();
integer i;
reg [7:0] ram [0:255];
initial begin
for (i = 0; i < 256; i = i + 1) begin
#10 $display("Address = %g Data = %h“, i, ram[i]);
ram[i] <= 0; // Initialize the RAM with 0
#10 $display("Address = %g Data = %h", i, ram[i]);
end
#10 $finish;
end
endmodule
Session VII
Parameters
Functions
Tasks
Verilog HDL 132
www.dkoplabs.com
Parameters
• parameter work like a constant in a module or its port list
• they are not variables i.e. they assign value to a symbolic name
• help in parameterization of a module
• can be changed using defparam at module instantiation
• instead if localparams are defined they can not be changed
Parameters
assign C[0] = carryin;
assign carryout = C[n];
xor x0[n-1:0] (S, X, Y, C[n-1:0]);
and a0[n-1:0] (z1, X, Y);
and a1[n-1:0] (z2, X, C[n-1:0]);
and a2[n-1:0] (z3, Y, C[n-1:0]);
or o0[n-1:0] (C[n:1], z1, z2, z3);
endmodule
Parameters
module tb_parity;
reg [15:0] data;
wire y;
parity #(16) io0(y, data);
parity #(.size(16)) io1(y, data);
endmodule
• Can be included in module declaration before module
port list
module adder #(parameter MSB = 32, LSB = 0)
(output reg [MSB:LSB] sum,
output reg co,
input wire [MSB:LSB] a, b,
input wire ci, ……
)
...
endmodule
Verilog HDL 135
www.dkoplabs.com
Functions
• Procedural statements – function
• functions are defined in the module (local) in which they are used
• It is possible to define functions in separate files and use compile
directive 'include to include the function in the file in which it is
called
• functions can not include timing delays e.g. posedge, negedge, #
delay, that means functions should be executed in "zero" time delay
i.e. functions can be used for modeling combinational logic only
• functions can call other functions, but can not call tasks
• functions can have any number of inputs but only one and only one
output and that must be returned by the name of the function
• The variables declared within the function are local to that function
• The order of declaration of inputs within the function defines how
the variables are passed to the function by the caller
Functions
• functions can take, drive, and source global variables, when no local
variables are used
• When local variables are used, basically output is assigned only at the
end of function execution
• A function return the value that is assigned to function name
Functions - Example
// myfunction.v
function myfunction;
input a, b, c, d;
begin
myfunction = ((a+b) + (c-d));
end
endfunction
Functions - Example
module word_aligner (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
Functions - Example
Functions - Example
• Model the following logic diagram using function definition
Functions - Example
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
Tasks
• Procedural statement – task
• Verilog provides tasks and functions to break up large behavioral
designs into smaller pieces
• Tasks and functions allow the designer to abstract verilog code that is
used at many places in design reducing code repetition
• Tasks are used in all programming languages, generally known as
procedures or subroutines and they include verilog behavioral code
only enclosed in task…..endtask keywords
• 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 compile
directive 'include to include the task in the file in which it is instantiated
• Tasks can have any number of input, output and inout arguments
• The order of declaration within the task defines how the arguments are
passed to the task by the caller
Tasks
• The variables declared within the task are local to that task
• tasks can include timing delay e.g. posedge, negedge, #delay & wait
• tasks can take, drive and source global variables, when no local
variables are used
• When local variables are used, basically output is assigned only at the
end of task execution
• tasks can call another task or function
• tasks can be used for modeling combinational & sequential logic
• A task must be specifically called with a statement, it cannot be used
within an expression as a function can
task task_name;
input, output, and inout declarations
local variable declarations
procedural_statement or statement_group
endtask
Tasks - Example
// mytask.v
module callingtask (temp_a,
task convert;
temp_b, temp_c, temp_d);
input [7:0] temp_in;
input [7:0] temp_a, temp_c;
output [7:0] temp_out;
output [7:0] temp_b, temp_d;
begin
reg [7:0] temp_b, temp_d;
temp_out = (9/5) *( temp_in + 32);
`include "mytask.v"
end
always @ (temp_a)
endtask
begin
convert (temp_a, temp_b);
end
always @ (temp_c)
begin
convert (temp_c, temp_d);
end
endmodule
Tasks – Example
module bit_counter (data, count);
input [7:0] data;
output [3:0] count; reg [3:0] 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
Session VIII
Generate for-if-case
System Tasks
Compiler Directives
File I/O
Verilog HDL 147
www.dkoplabs.com
Generate - for
• Work as a parallel block therefore allows following
• instance creation, continuous assignment
• initial and always blocks, local variable declaration
• nesting of generate is allowed for all generate stmt. - for, if, case
module RCAdder (a, b, ci, s);
parameter N = 64;
input [N-1:0] a, b;
input ci;
output [N-1:0] s;
wire [N:0] pc;
genvar i;
generate for (i=0; i<N; i=i+1) begin : u1
fulladder inst[i](a[i], b[i], pc[i], s[i], pc[i+1]);
end
endmodule
Generate - if
• Select at most one generate block from a set of alternative generate
blocks based on constant expression
module multiplier(a,b,product);
parameter a_width = 8, b_width = 8;
localparam product_width = a_width + b_width;
input [a_width-1:0] a;
input [b_width-1:0] b;
output [product_width-1:0] product;
generate
if ((a_width < 8 || b_width <8) ) begin : mult
cla_multiplier #(a_width, b_width) u1(a,b,product);
end
else begin : mult
wallace_multiplier #(a_width, b_width) u1(a,b,product);
end
endgenerate
endmodule
Generate - case
• Select at most one generate block from a set of alternative generate
blocks based on constant expression
generate
case (WIDTH)
1: begin : adder
adder_1bit x1(co, sum, a, b, ci);
end
2: begin : adder
adder_2bit x1(co, sum, a, b, ci);
end
default: begin : adder
adder_cla #(WIDTH) x1(co, sum, a, b, ci);
end
endcase
endgenerate
System Tasks
• System tasks are used for various purposes during simulation and
they start with a $ sign
• For displaying text on screen during simulation
• $display – display text only once whenever this is executed
• $strobe – display text only once every time this is executed at the
very end of the current simulation time
• $monitor – executes and displays every time if any of its
parameter changes
• For displaying current simulation time
• $time – as a 64 bit integer
• $stime – as a 32 bit integer
• $realtime – as a real number
• For generating random numbers
• $random – a seed may be given otherwise seed is derived from
system clock
Verilog HDL 151
www.dkoplabs.com
System Tasks
• Controlling the simulation
• $reset – resets the simulation back to time 0
• $stop – halt the simulation and put it in interactive mode for user
to enter the commands
• $finish – exit the simulation completely and return to OS
Session IX
Design Examples
Design Examples - 1
• How to model same logic in all modeling styles
• Problem 1 (simple gate) : Given the following diagram how would
you model it using the three modeling styles i.e. gate level,
continuous assignment and behavioral
Design Examples - 2
• How to model same logic in all modeling styles
• Problem 2 (tri-stated buffer) : Given the following diagram how
would you model it using the three modeling styles i.e. gate level,
continuous assignment and behavioral
Design Examples - 3
• How to model same logic in all modeling styles
• Problem 3 (mux) : Given the following diagram how would you
model the logic using behavioral & continuous assignment
modeling styles
Design Examples - 4
• How to model same logic in all modeling styles
• Problem 4 (latch) : Given the following diagrams how would you
model the logic using behavioral modeling
Design Examples - 5
• How to model same logic in all modeling styles
• Problem 5 (flip-flop) : Given the following diagrams how would
you model the logic using behavioral modeling
init
State Register
s(t+1)
C1 next s(t)
x(t) state present z(t)
state C2
clk
ALU
• ALU – Arithmetic Logic Unit
• ALU is a digital circuit that performs arithmetic , logical operations
• It also constitute as a building block for the central processing unit
(CPU) of a computer
• Three gates are used to perform logical operation
• Full adder is used to perform arithmetic operation
• MUX is used to select the logical block or arithmetic block
ALU
• ALU – Arithmetic Logic Unit
S1 S0
A
B
A
B 4:1 F
A MUX
Control Operation
B signal
A
B ADD S1 S0
C
0 0 A and B
0 1 A or B
Cout0
1 0 A xor B
Block diagram for 1-bit ALU
1 1 A add B
Verilog HDL 167
www.dkoplabs.com
ALU
• ALU – Arithmetic Logic Unit
S1 a
b 1
o
c 0
4:1
A MUX
B
A
B ADD
C
Cout0
Block diagram for 1-bit ALU
Verilog HDL 168
www.dkoplabs.com
ALU
• ALU – Arithmetic Logic Unit
// 1-bit alu // 1-bit alu
module mux(f, s0, s1, w, x, y, z);
output f; module alu(F, CO, S0, S1, A, B, C);
input s0, s1, w, x, y, z; output F, CO;
input S0, S1, A, B, C;
assign f = s1 ? (s0 ? x : y) : wire w, x, y, z;
(s0 ? w : z);
and a1(w, A, B);
endmodule
or o1(x, A, B);
module fulladder(z, c0, a, b, c);
output z,c0; xor x1(y, A, B);
input a,b,c;
fulladder f1(z, CO, A, B, C);
assign z = a ^ b ^ c;
assign c0 = (a&b) | (b&c) | (c&a); mux m1(F, S0, S1, w, x, y, z);
endmodule endmodule
ALU
• Model the following ALU
S1 S0
A0
B0 1-bit ALU F0
C0
Cout0
A1 F1
B1 1-bit ALU
Cout1
A2 F2
1-bit ALU
B2
Cout2
A3 1-bit ALU F3
B3
Cout3
Diagram for 4-bit ALU
Verilog HDL 170
www.dkoplabs.com
ALU
• Solution
module alu4bit(f, a, b, s);
output [3:0] f;
reg [3:0] f;
input [3:0] a, b;
input [0:2] s;
always @ (s,a,b)
begin
case(s)
3’b000 : f = 4’b0000;
3’b001 : f = b-a;
3’b010 : f = a-b;
3’b011 : f = a+b;
3’b100 : f = a&b;
3’b101 : f = a^b;
3’b110 : f = a|b;
3’b111 : f = 4’b1111;
endcase
end
endmodule
ROM
• ROM – Read Only Memory
• It’s a memory which is fabricated with the desire that the data be
permanently stored in it and that it can never be modified
ROM - Example
ROM - Example
ROM - Example
• Synchronous and Asynchronous
RAM
• Random Access Memory
• It’s a form of computer data storage
• The keyword random refers to the fact that any piece of data can
be returned in a constant time (regardless of its physical location
and whether or not it is related to the previous piece of data)
• There are two types of RAM’s
• SRAM
Block Diagram of a RAM
• DRAM
RAM
• DRAM - Dynamic RAM stores each bit of data in a separate
capacitor within an integrated circuit
READ OPERATION
Verilog HDL 177
www.dkoplabs.com
RAM - Example
module RamChip (Address, Data, CS, WE, OE);
parameter AddressSize = 1;
parameter WordSize = 1;
input [AddressSize-1:0] Address;
inout [WordSize-1:0] Data;
input CS, WE, OE;
reg [WordSize-1:0] Mem [0 : (1 << AddressSize) - 1];
assign Data = (!CS && !OE) ? Mem[Address] : {WordSize{1'bz}};
always @ (CS or WE)
if (!CS && !WE)
Mem[Address] = Data;
always @ (WE or OE)
if (!WE && !OE)
$display ("Operational error in RamChip: OE and WE both active");
endmodule
RAM - Example
module ram_sp_sr_sw (
clk , // Clock Input
address , // Address Input
data , // Data bi-directional
cs , // Chip Select
we , // Write Enable/Read Enable
oe); // Output Enable
parameter DATA_WIDTH = 8 ;
parameter ADDR_WIDTH = 8 ;
parameter RAM_DEPTH = 1 << ADDR_WIDTH;
input clk ;
input [ADDR_WIDTH-1:0] address ;
input cs ;
input we ;
input oe ;
inout [DATA_WIDTH-1:0] data ;
reg [DATA_WIDTH-1:0] data_out ;
reg [DATA_WIDTH-1:0] mem [0:RAM_DEPTH-1];
RAM - Example
// Tri-State Buffer control
// output : When we = 0, oe = 1, cs = 1
assign data = (cs && oe && !we) ? data_out : 8'bz;
// Memory Write Block
// Write Operation : When we = 1, cs = 1
always @ (posedge clk)
begin : MEM_WRITE
if ( cs && we ) begin
mem[address] = data;
end
end
// Memory Read Block
// Read Operation : When we = 0, oe = 1, cs = 1
always @ (posedge clk)
begin : MEM_READ
if (cs && !we && oe) begin
data_out = mem[address];
end
end
endmodule