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

Verilog Course

The document describes a course curriculum for Verilog HDL (Hardware Description Language). The curriculum covers basics of Verilog HDL including modeling styles, gate level modeling, data types, behavioral modeling, operators, and design examples. It includes 8 sections that progress from introductions to more advanced topics like generate statements and system tasks. The goal is to teach students how to model digital designs at different levels of abstraction using Verilog.

Uploaded by

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

Verilog Course

The document describes a course curriculum for Verilog HDL (Hardware Description Language). The curriculum covers basics of Verilog HDL including modeling styles, gate level modeling, data types, behavioral modeling, operators, and design examples. It includes 8 sections that progress from introductions to more advanced topics like generate statements and system tasks. The goal is to teach students how to model digital designs at different levels of abstraction using Verilog.

Uploaded by

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

www.dkoplabs.

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

HDL vs. Programming Language


• Instances vs. Functions
• Concurrent vs. Sequential
• Time vs. Execution

Application Programs parser

Kernel or OS Code generator

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

Update Signals Execute Processes

End Simulation
Verilog HDL 13
www.dkoplabs.com

Digital Design Flow


Steps & Tools
• Truth Tables – Way to express digital design behavior, used in
writing test-benches or for verification
• Schematic - Most schematic capture tools can automatically
generate a Verilog netlist for simulation
• HDL’s Logic Simulation
Used for logic Verification
• VHDL
MODELSIM aka QUESTA : Mentor Graphics
• Verilog NCSIM : Cadence
• Tools available for VCS : Synopsys
Logic Synthesis
HDL Simulation & Creates a gate level logic circuit for an HDL
PRECISION : Mentor Graphics
Synthesis RC COMPILER : Cadence
DESIGN COMPILER : Synopsys
• see the block
Verilog HDL 14
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 HDL: A guide to Digital Design & Synthesis


By Samir Palnitkar

• 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

Single Gate h/w Design


• Writing gate level h/w model for an “and” gate
• module keyword implements a h/w
• unique name for the identification of the h/w
• input, output ports or pins declarations
• by convention output ports are declared first
• body of module/hardware represents behavior
• concept of instantiation

module and_gate_2_input(O, A, B);


output O;
input A, B;
and and1(O, A, B);
endmodule

Verilog HDL 20
www.dkoplabs.com

Two Gate h/w Design


• Designing a single bit half adder gate level model

// GATE LEVEL HALF-ADDER


module half_adder (s , c , a , b);
output s , c; //outputs
input a , b; //inputs

//Instantiate logic gates


xor xor1(s , a , b); A B C S
and and1(c , a , b); 0 0 0 0
0 1 0 1
endmodule
1 0 0 1
1 1 1 0

Verilog HDL 21
www.dkoplabs.com

Multiple Gate h/w Design


• Designing a single bit full adder gate level model
• Use concept of wire
// GATE LEVEL FULL-ADDER
module full_adder (Cout , S , A , B, Cin);
output Cout , S; //outputs
input A, B, Cin; //inputs
wire w1, w2, w3; // wires
xor xor1(w1 , A, B);
xor xor2(S, w1, Cin);
and and1(w2 , w1, Cin);
and and2(w3 , A, B);
or or1(Cout, w2, w3);
endmodule

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

4 Value Logic System


• Verilog HDL follows 4 value logic system as shown

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

module full_adder (co , s , a , b, ci);


output co , s; //outputs
input a, b, ci; //inputs
wire w1, w2, w3; // wires
half_adder ha1(w1, w2, a, b);
half_adder ha2(s, w3, w1, ci);
or or1(co, w2, w3);
endmodule

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

module stimulus; // stimulus module (no ports)


reg IN0, IN1, IN2, IN3, S1, S0; //declare variables connected to inputs
wire OUTPUT; // declare output wire
// instantiate the mux – connected by position or order
mux4_to_1 mymux1(OUTPUT, IN0, IN1, IN2, IN3, S1, S0);
// instantiate the mux – connected by name or any order
mux4_to_1 mymux2(.s0(S0), .s1(S1), .i3(IN3), .i2(IN2),
.i1(IN1), .i0(IN0), .out(OUTPUT));
………..
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

Data Flow Modeling


• AKA black box modeling where bitwise operators are used for data
flow between registers
• keyword assign is used for dataflow modeling
• usage of assignment operator = results in continuous assignment
• table below shows bitwise operators

Verilog HDL 36
www.dkoplabs.com

Data Flow Modeling


• Example – 1-bit full-adder
module Half_Adder (s , c , a , b);
output s , c;
input a , b;
assign s = a ^ b;
assign c = a & b;
endmodule
module Full_Adder (co , s , a , b, ci);
output co , s; //outputs
input a, b, ci; //inputs
wire ps, pc0, pc1; // wires
Half_Adder ha1(ps, pc0, a, b);
Half_Aadder ha2(s, pc1, ps, ci);
assign co = pc0 | pc1;
endmodule

Verilog HDL 37
www.dkoplabs.com

Data Flow Modeling


• Example - 2 to 4 line decoder

module decoder(F, X, Y);


output [0:3] F;
input X, Y;
assign F[0] = ~X & ~Y;
assign F[1] = ~X & Y;
assign F[2] = X & ~Y;
assign F[3] = X & Y;
X Y F[0] F[1] F[2] F[3]
endmodule
0 0 1 0 0 0
0 1 0 1 0 0
1 0 0 0 1 0
1 1 0 0 0 1
Verilog HDL 38
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

module magcomp (ALTB, AGTB, AEQB, A, B);


output ALTB, AGTB, AEQB;
input [3:0] A, B;
assign ALTB = (A < B),
AGTB = (A > B),
AEQB = (A == B);
endmodule
module divider (dout, d1);
output [3:0] dout;
input [3:0] d1;
assign dout = d1 / 2;
endmodule

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

module comparator(Comp, A, B);


output Comp;
input [7:0] A, B;
assign Comp = ((A >= B) ? 1’b1 : 1’b0);
endmodule

Verilog HDL 48
www.dkoplabs.com

Operator Precedence
• Operator precedence
• Parenthesis can be used to override the precedence

+ , - , ! , ~ (unary) Highest Priority


*, /, %, **
+ , - (Binary)
<< , <<<, >>, >>>
< , > , <= , >=
== , !=, ===, !==
& , ~&
^ , ^~ or ~^
|, ~|
&&
||
? : (ternary) Lowest Priority

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

BNF, Syntax, Semantic


• Understanding bnf, syntax, semantics
• Backus Naur Form
• defines the grammar for the full language
• Syntax
• defines the way you can write HDL as a text file
• If not followed appropriately errors will get reported at
compile time
• Semantics
• defines the meaning of language constructs
• defines the multiple meaning of language constructs in
different contexts
• ? represents a ‘z’ value

Verilog HDL 54
www.dkoplabs.com

Conventions – Cases, Comments


• The basic lexical convention used by Verilog HDL are similar to
those in C programming
• All keywords must be in LOWER case i.e. the language is case
sensitive
• White spaces makes code more readable but are ignored by
compiler
• Blank space(\b) , tabs(\t) , newline(\n) are ignored by the compiler
• White spaces are not ignored by the compiler in strings
• Comments
• // single line comment style
• /* multi line
comment style */
• Nesting of comments not allowed

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

Number Representation, Format


• Representation
• Decimal d or D
• Hexadecimal h or H
• Octal o or O
• Binary b or B
• Value format
• <size>’<radix><format>
• When size not specified default value is 32 bits e.g. ‘bz, ‘h9
• When radix not specified default is taken as decimal e.g. 3
• 2’b10, 3’d6, 6’o57, 3’O4, 8’H2d, 32’haA19, 5’B110x0, 6’ozz,
12’hZXb
• For negative number use – sign e.g. -6’d3, -3’b11
• Underscore can be used to enhance readability e.g. 12’o07_24,
12’b000_111_010_100

Verilog HDL 57
www.dkoplabs.com

Value Printing Formats


• Printing formats
• %h or %H for hexadecimal
• %d or %D for decimal
• %o or %O for octal
• %c or %C for an ASCII character
• %m or %M for hierarchical name
• %v or %V for net signal value and strength
• %s or %S for string
• %t or %T for time
• %f or %F for real value in decimal format
• %g or %G real value in either exponential or decimal form
whichever is short
• %e or %E for real value in exponent form

Verilog HDL 58
www.dkoplabs.com

Data Types, Strings


• Strings
• A string is a sequence of characters enclosed by double
quotes
• Must be contained on a single i.e. without carriage return
• Strings are treated as a sequence of one-byte ASCII values
• e.g. string_val = “Hello Verilog”;
• Data types
• Net (physical connectivity) – default value z
• wire, wand, wor
• tri, triand, trior
• tri0, tri1, trireg
• supply0 (GND), supply1 VDD (VCC)
• Registers (physical storage elements) – default value x
• reg, integer, real
• time, realtime (time shown in real number format)
Verilog HDL 59
www.dkoplabs.com

Data Type - net


• “wor” performs “or” operation on multiple driver logic
• “wand” performs “and” operation on multiple driver logic
• “trior” and “triand” perform the same function as “wor” and
“wand”, but model outputs with resistive loads

net type modeling usage


wire Net with single driver
Tri Net with multiple driver
wand, triand Model wired logic function at gate level
wor, trior
tri0, tri1 Pulls up or down the net at gate level
trireg Stores the value at previous level (gate)
supply0 Constant logic 0 at switch level
Supply1 Constant logic 1 at switch level

Verilog HDL 60
www.dkoplabs.com

Data Type – Net - Example


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 = 0;
#10 c = 0;
#10 b = 1; wor/ 0 1 x z
trior
#10 b = 0;
#10 c = 1; 0 0 1 x 0
#10 b = 1; 1 1 1 1 1
#10 b = 0; x x 1 x x
#10 $finish;
z 0 1 x z
end
endmodule
Verilog HDL 61
www.dkoplabs.com

Data Type – Net - Example


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 = 0;
#10 c = 0; wand/ 0 1 x z
#10 b = 1; triand
#10 b = 0; 0 0 0 0 0
#10 c = 1;
1 0 1 x 1
#10 b = 1;
#10 b = 0; x 0 x x x
#10 $finish;
z 0 1 x z
end
endmodule
Verilog HDL 62
www.dkoplabs.com

Data Type – Net - Example


module test_tri();
tri a;
reg b, c;
assign a = (b ? c : 1’bz);
initial begin
$monitor(“time = %d a = %b b = %b c = %b", $time, a, b, c);
b = 0;
c = 0;
#10 b = 1; wire/tri 0 1 x z
#10 b = 0;
#10 c = 1; 0 0 x x 0
#10 b = 1; 1 x 1 x 1
#10 b = 0;
x x x x x
#10 $finish;
end z 0 1 x z
endmodule
Verilog HDL 63
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

Bus, Vectors, Arrays


• Vectors
• wire [lsb : msb+ wire1, wire2,…..;
• reg [lsb:msb+ reg1, reg2, ………;
• wire [15:0] clear ; // 16 bit bus or wire
• reg [3:0] cla ; // 4 bit register , can be assigned cla = 0;
• Arrays – memories – allowed only for reg, integer, time
• reg [lsb:msb] mem [upper, lower]
• reg [3:0] mem [31:0] ; // memory consisting of 32, 4 bit registers
• reg mema [7:0] ; // array of 8 – 1 bit registers
• Can’t be assigned mem = 0 ; // illegal must use index
• Arrays – multi dimensional arrays (mda’s)
• wire [3:0] mda_wire [7:0][15:0];
• reg [7:0] mda_rega [7:0][7:0][7:0];

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

Bit-Part Select, Width Mismatch


• Bit or part select
• reg [15:0] Areg; // 16 bit register
• wire Abit; // a single bit wire
• wire [3:0] Apart; // 4 bit wire
• assign Abit = Areg[1]; // bit select – select one bit
• assign Apart = Areg[7:4]; // select parts of Areg – 4 bits
• Width mismatch
• What happens in an assignment when LHS is wider than RHS
• If RHS is unsigned and left most bit is 1 or 0, then LHS is extended
with 0
• If left most bit of RHS is Z, then LHS is extended with Z
• If left most bit of RHS is X, then LHS is extended with X
• If RHS is signed, then LHS is sign extended

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

All About Delays


• Regular delays (Inertial)
• Delay execution of assignment by specified delay
• assign #d1 y = a & b;
• Intra - assignment delays (Transport)
• Evaluate expression now and delay assignment by specified delay
• y = #d1 a & b;
• Mix of regular and intra-assignment delays
• assign #d1 y = #d2 a & b;
• Gate & Net delays
• input x1, x2; wire #5 y; and #3 and1(y, x1, x2);

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

#(Min : Typ : Max, Min : Typ : Max, Min :Typ : Max)


Example :
and #(1:2:3) u1(co, a, b);
and #(1:2:3, 1:2:3) u2(co, a, b);
bufif0 #(2:3:4, 2:3:4, 3:4:5) u3(out, in, enable);

Verilog HDL 72
www.dkoplabs.com

Gate Delay Example


module fa (cout, s, A, B, Cin);
input A, B, Cin;
output cout, s;
wire w1, w2, w3;

xor #(5, 4) a1(w1, A, B);


xor #(10) x1(s, w1, Cin);
and #(5, 4) a2(w2, A, B);
and #(5, 4) a3(w3, Cin, w1);
or #(5:6:7) o1(cout, w2, w3);
endmodule

Verilog HDL 73
www.dkoplabs.com

Gate + Net Delay


• What would be the waveform for the outputs in the
shown circuit with gate and wire delays modeled in the
model with the waveform for inputs x1 and x2 as shown

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

Waveform for Gate + Net delay


x1
2 4 6 8 10

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

Don’t Care Conditions


• design a gate level model for the following circuit with gate delays
mentioned
• use the input values from the table shown and check the results
• do you find any don’t care conditions?

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

Don’t Care Conditions


• for the previous circuit check the results when
• x1 = 0, x2 = 1, x3 = 0
• x1 = 0, x2 = 1, x3 = 1

module circuit(f1, f2, x1, x2, x3);


output f2;
input x1, x2, x3;
wire f1;
// gate level
and #50 a1(f1, x1, x2);
or #75 o1(f2, f1, x3);
endmodule

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 - Example


module initial_block;
reg a, b, c, d;
// single statement
initial
a = 1b’0;
// multiple statements grouped together
initial
begin
b = 1’b1;
#5 c = 1’b0;
#10 d = 1’b0;
end
initial
#20 $finish;
endmodule
Verilog HDL 83
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

Always Block - Example


• Clock generator

module clock_gen(output reg clk);


parameter period=50;
parameter duty_cycle=50;
initial
clk = 1b’0;
always
#(duty_cycle*period/100) clk = ~clk;
initial
#100 $finish;
endmodule

Verilog HDL 87
www.dkoplabs.com

Always Block - Example


• different methods for clock generation
module clkgen(output reg clock);
initial begin
#5 clock = 1;
forever #50 clock = ~clock;
end
endmodule

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

Blocking vs. Non-Blocking


• Blocking assignment “=“
• Statement order matters
• Completes the assignment in hand before moving on to the next
statement meaning “Blocks” the other assignments until the
current assignment completes
• Non blocking assignment “<=“
• Concurrent assignment i.e. it does not “Block” execution of
assignments in other statements
• Evaluates the RHS at the beginning of a time step
• Schedules the LHS update at the end of the time step
• Results less dependent on order of assignments
• If there are multiple non-blocking assignments to same variable in
same behavior, latter overwrites previous
• Not allowed in continuous assignments

Verilog HDL 89
www.dkoplabs.com

Blocking vs. Non-Blocking


• 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
Verilog HDL 90
www.dkoplabs.com

Blocking vs. Non-Blocking


• Blocking vs. Non-Blocking assignments in initial block with
absolute and intra-assignment delays
module blocking_nonblocking(); c = #10 0;c = #11 1;
reg a,b,c,d; c = #12 0;c = #13 1;
initial begin end
#10 a = 0; initial begin
#11 a = 1; d <= #10 0;d <= #11 1;
#12 a = 0; d <= #12 0;d <= #13 1;
#13 a = 1; end
end initial begin
initial begin $monitor("TIME = %g A = %b B
#10 b <= 0; = %b C = %b D = %b", $time, a, b,
#11 b <= 1; c, d);
#12 b <= 0; #50 $finish;
#13 b <= 1; end
end endmodule
initial begin
Verilog HDL 91
www.dkoplabs.com

Edge Triggering & Event Control


• Execution control in procedural blocks - within procedural
blocks how does time advance
• initial block executes once starting at time 0
• always block executes continuously starting at time 0
• delays using # i.e. delay assignment by a specific amount of time
(not synthesizable) using regular, intra-assignment, zero delays
• Event control using @ i.e. delay assignment until specific event
occurs (synthesizable)
• edge triggering (sensitive)
• 1→0 or 0→1 transition, or edge on signal
• “posedge” 0→1 only
• “negedge” 1→0 only
• level triggering (sensitive)
• use “wait” to delay execution until condition is true e.g.
wait (f == 0);
• Not synthesizable – used only in test-benches
Verilog HDL 92
www.dkoplabs.com

Edge Triggering & Event Control


• Execution control in procedural blocks
• Event control using @ i.e. delay assignment until specific event
occurs (synthesizable)
• edge triggering (sensitive)
• 1→0 or 0→1 transition, or edge on signal
• “posedge” 0→1 only
• “negedge” 1→0 only

@ (clk) q=d; // statement executed whenever signal clk changes value


@ (posedge clk) q=d; // executed whenever signal clk does a positive
// transition (0 to 1, x to z, x to 1, z to 1)
q=@(posedge clk)d; // d is evaluated immediately and assigned to q
// at positive edge of clk

Verilog HDL 93
www.dkoplabs.com

Edge Triggering & Event Control


• Event control using @ - combinational logic forms
always @(a) y = ~a; // equivalent to assign y = ~a;
always @(a or b) y = a & b; // equivalent to assign y = a & b;
always @(a) y = a & b; // what happens in this case
// verilog 2001 comma-separated event list
always @(s, a, b) y = s ? a : b;
// verilog 2001 * operator makes block sensitive to all
// changes on any of the input a, b, c, d
always @(*) begin
y1 = a + b;
y2 = c – d;
end
module parity (input [31:0] in, output p);
always @(in) p = ^in; // event list can include vectors
endmodule
Verilog HDL 94
www.dkoplabs.com

Edge Triggering & Event Control


• Event control using @ - sequential logic forms
// q = d executed whenever clock changes
always @(clock) q = d;

// q = d executed on rising edge (0  1) of clk


always @(posedge clk) q = d;

// q = d executed on falling edge (1  0) of clk


always @(negedge clk) q = d;

// flip – flop with asynchronous reset


always @(posedge clock, negedge reset_n)
if (!reset_n) q = 0;
else q = d;
Verilog HDL 95
www.dkoplabs.com

Behavioral Modeling - Example


• Modeling a half adder

a sum
Add_half
b c_out

module Add_half (sum, c_out, a, b);


output sum, c_out;
reg sum, c_out;
input a, b;
always @ ( a or b )
begin
sum = a ^ b; // Exclusive or
c_out = a & b; // And
end
endmodule

Verilog HDL 96
www.dkoplabs.com

Behavioral Modeling - Example


• Modeling D-latch & D-flip-flop using sequential logic forms

module latch(q, d, clk); module ff(q, d, clk);


output q; output q;
reg q; d q reg q;
input d, clk; input d, clk;
clk
initial initial
q = 0; q = 0;

always @ (clk) always @ (posedge clk)


begin begin
q=d; q=d;
end d q end

endmodule clk endmodule

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

Level Triggering - Example


• Execution control in procedural blocks – “wait” - example
module wait_example(); READY = %b DATA = %b",
reg mem_read, data_ready; $time, mem_read, data_ready, data);
reg [7:0] data_bus, data; data_bus=0;mem_read=0;
always @ (mem_read or data_bus data_ready=0;
or data_ready) #10 data_bus = 8'hDE;
begin #10 mem_read = 1;
data = 0; #20 data_ready = 1;
while (mem_read == 1'b1) begin #1 mem_read = 1;
// #1 is very important to #1 data_ready = 0;
// avoid infinite loop #10 data_bus = 8'hAD;
wait (data_ready == 1) #10 mem_read = 1;
#1 data = data_bus; #20 data_ready = 1;
end #1 mem_read = 1;
end #1 data_ready = 0;
initial begin #10 $finish;
$monitor ("TIME = %g READ = %b end endmodule
Verilog HDL 99
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

Verilog HDL 100


www.dkoplabs.com

Race Condition - Solution


• 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

Verilog HDL 101


www.dkoplabs.com

Blocking vs. Non-Blocking


• Write verilog code for the following circuits using blocking and non
blocking assignments
• Test these circuits by changing the order of the assignments
• Use a synthesis tool to showcase that assignments order does not
matter in non blocking assignments whereas it does matter in
blocking assignments

Verilog HDL 102


www.dkoplabs.com

Blocking vs. Non-Blocking


• Solutions
module design (clock, d, q0, q1);
output q0, q1;
reg q0, q1;
input d, clock;

// blocking // non blocking


always @ (posedge clock) always @(posedge clock)
begin begin
q0 = d; q0 <= d;
q1 = q0; q1 <= q0;
end end

endmodule

Verilog HDL 103


www.dkoplabs.com

Blocking vs. Non-Blocking


• Solutions
module design (g1, g2, clk, x1, x2, x3);
output g1, g2;
reg g1, g2;
input clk, x1, x2, x3;

// blocking // non blocking


always @ (posedge clk) always @(posedge clk)
begin begin
g2 = x1 & x2; g2 <= x1 & x2;
g1 = g2 | x3; g1 <= g2 | x3;
end end

endmodule

Verilog HDL 104


www.dkoplabs.com

Behavioral Modeling - if - else


• Procedural statements – if , if else if
• if-else statement conditionally controls a logic operation

• if-else implies multiplexing logic like conditional operator (? :)

Verilog HDL 105


www.dkoplabs.com

if - else
• if without else implies storage

• What is the value of Y when Sel = ‘0’?


• Verilog register variables hold their value when not driven, therefore
hardware storage elements are required
• From synthesis point of view it is a good design practice for every if to
have an else unless you need storage
• A continuous assignment establishes static binding for net variables
• A procedural continuous assignment “assign – deassign” establishes a
dynamic binding for register variables

Verilog HDL 106


www.dkoplabs.com

if – else - Example
• Modeling a D Latch

module d_latch (q, q_bar, clk, d);


output q, q_bar;
reg q, q_bar;
input clk, d;
always @(clk or d) begin
if (clk) begin
q <= d;
q_bar <= ~d;
end
end
endmodule

Verilog HDL 107


www.dkoplabs.com

if – else - Example
• Modeling a flip flop – if else - example

module Flip_flop (q, data_in, clk, rst );


output q;
reg q;
input data_in, clk, rst; rst
always @ ( posedge clk )
begin data_in q
if ( rst == 1)
q = 0;
else clk
q = data_in;
end
endmodule

Verilog HDL 108


www.dkoplabs.com

if – else - Example
• Modeling a comparator2

module comparator2 (c, a, b);


output c;
reg c;
input a;
input b;
always @ (a or b)
if (a == b)
c = 1'b1;
else
c = 1'b0;
endmodule

Verilog HDL 109


www.dkoplabs.com

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

Verilog HDL 110


www.dkoplabs.com

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

Verilog HDL 112


www.dkoplabs.com

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

Verilog HDL 113


www.dkoplabs.com

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;

Verilog HDL 115


www.dkoplabs.com

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

Verilog HDL 116


www.dkoplabs.com

case, casex, casez

Verilog HDL 117


www.dkoplabs.com

case, casex, casez - Example


module mux4x1 (out, s, a, b, c, d);
output out;
reg out;
input a, b, c, d;
input [1:0] s;

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

Verilog HDL 118


www.dkoplabs.com

case, casex, casez - Example


module decoder2to4 (y, w, en);
output [3:0]y;
reg [3:0]y;
input en;
input [1:0] w;
always @(*) begin
if (en == 0)
y = 4’b0000;
else
case (w)
2’b00 : y = 4’b1000;
2’b01 : y = 4’b0100;
2’b10 : y = 4’b0010;
2’b11 : y = 4’b0001;
endcase
end
endmodule
Verilog HDL 119
www.dkoplabs.com

case, casex, casez - Example


• Only case based decoder (previous example re-written)
module decoder2to4 (y, w, en);
output [3:0]y;
reg [3:0]y;
input en;
input [1:0] w;
always @(*) begin
case ({en, w})
3’b100 : y = 4’b1000;
3’b101 : y = 4’b0100;
3’b110 : y = 4’b0010;
3’b111 : y = 4’b0001;
default : y = 4’b0000;
endcase
end
endmodule
Verilog HDL 120
www.dkoplabs.com

case, casex, casez - Example


• BCD to 7 segment code converter

Verilog HDL 121


www.dkoplabs.com

case, casex, casez - Example


• Looking at designing arithmetic blocks – Function codes
for 74381 TTL ALU

Operation Inputs (S2 S1 S0) Functional output


CLEAR 000 0000
B-A 001 B-A
A-B 010 A-B
ADD 011 A+B
XOR 100 A xor B
OR 101 A or B
AND 110 A and B
PRESET 111 1111

Verilog HDL 122


www.dkoplabs.com

case, casex, casez - Example


• Looking at designing arithmetic blocks

Verilog HDL 123


www.dkoplabs.com

case, casex, casez - Example


• Procedural statements – case, casex, casez
• case :
• Bit-by-bit comparison
• All bits must match exactly
• casex :
• Bit-by-bit comparison
• All z’s and x’s are treated as
• don’t cares
• Useful for sparse truth tables
• casez :
• Bit-by-bit comparison
• All z’s are treated as don’t cares
• Useful for tri-state signals

Verilog HDL 124


www.dkoplabs.com

case, casex, casez - Example


module case_compare;
reg sel;
initial begin
#10 $display(“\n Driving 0”);
sel = 0;
#10 $display(“\n Driving 1”);
sel = 1;
#10 $display(“\n Driving x”);
sel = 1’bx;
#10 $display(“\n Driving z”);
sel = 1’bz;
#10 $finish;
end
always @ (sel)
case (sel)
1’b0 : $display(“Normal : Logic 0 on sel”);
1'b1 : $display("Normal : Logic 1 on sel");
1’bx : $display(“Normal : Logic x on sel”);

Verilog HDL 125


www.dkoplabs.com

case, casex, casez - Example


1’bz : $display(“Normal : Logix z on sel”);
endcase
always @ (sel)
casex (sel)
1’b0 : $display(“CASEX : Logic 0 on sel”);
1'b1 : $display(“CASEX : Logic 1 on sel");
1’bx : $display(“CASEX : Logic x on sel”);
1’bz : $display(“CASEX : Logix z on sel”);
endcase
always @ (sel)
casez (sel)
1’b0 : $display(“CASEZ : Logic 0 on sel”);
1'b1 : $display(“CASEZ : Logic 1 on sel");
1’bx : $display(“CASEZ : Logic x on sel”);
1’bz : $display(“CASEZ : Logix z on sel”);
endcase
endmodule

Verilog HDL 126


www.dkoplabs.com

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

Verilog HDL 127


www.dkoplabs.com

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;

Verilog HDL 128


www.dkoplabs.com

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

Verilog HDL 129


www.dkoplabs.com

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

Verilog HDL 131


www.dkoplabs.com

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

/* n – bit ripple carry adder */


module addern (carryin, X, Y, S, carryout);
parameter n = 32;
input carryin;
input [n-1:0] X, Y;
output carryout;
output [n-1:0] S;
wire [n:0] C;
wire [n-1:0] z1, z2, z3;

Verilog HDL 133


www.dkoplabs.com

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

/* 8 bit parity checker */


module parity #(parameter size = 8) (y, in);
input [size-1:0] in;
output y;
assign y = ^in;
endmodule

Verilog HDL 134


www.dkoplabs.com

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

Verilog HDL 136


www.dkoplabs.com

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

function [size_or_type] function_name;


input declarations
local variable declarations
procedural_statement or statement_group
endfunction

Verilog HDL 137


www.dkoplabs.com

Functions - Example
// myfunction.v
function myfunction;
input a, b, c, d;
begin
myfunction = ((a+b) + (c-d));
end
endfunction

module function_calling(a, b, c, d, e, f);


input a, b, c, d, e ;
output f;
wire f;
`include "myfunction.v"
assign f = (myfunction (a,b,c,d)) ? e : 0;
endmodule

Verilog HDL 138


www.dkoplabs.com

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

Verilog HDL 139


www.dkoplabs.com

Functions - Example

function [31:0] factorial;


input [3:0] operand;
reg [3:0] index;
begin
factorial = operand ? 1 : 0;
for (index = 2; index <= operand; index = index+1)
factorial = index * factorial;
end
endfunction

assign res = n * factorial(n);

Verilog HDL 140


www.dkoplabs.com

Functions - Example
• Model the following logic diagram using function definition

Verilog HDL 141


www.dkoplabs.com

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

Verilog HDL 142


www.dkoplabs.com

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

Verilog HDL 143


www.dkoplabs.com

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

Verilog HDL 144


www.dkoplabs.com

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

Verilog HDL 145


www.dkoplabs.com

Tasks – Example
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

Verilog HDL 146


www.dkoplabs.com

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

Verilog HDL 148


www.dkoplabs.com

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

Verilog HDL 149


www.dkoplabs.com

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

Verilog HDL 150


www.dkoplabs.com

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

• For enabling value change dump (vcd)


• $dumpfile, $dumpvars, $dumpon, $dumpoff, $dumpall
• For file input, output
• $fopen, $fdisplay, $fmonitor, $fwrite, $fstrobe

Verilog HDL 152


www.dkoplabs.com

Compiler Directives - `timescale


• `timescale <time_unit> / <time_precision>
• time_unit - the time multiplier for time values
• time_precision - minimum step size during simulation - determines
rounding of numerical values
• Allowed unit/precision values:
{1| 10 | 100, s | ms | us | ns | ps}
• Example: precision 10 ps / 1 ps
`timescale 10 ps / 1ps
nor #3.57 n1(z, x1, x2);
nor delay used = 3.57 x 10 ps = 35.7 ps => 36 ps
• Different timescales can be used for different sequences of
modules
• The smallest time precision determines the precision of the
simulation

Verilog HDL 153


www.dkoplabs.com

Session IX
Design Examples

Verilog HDL 154


www.dkoplabs.com

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

Verilog HDL 155


www.dkoplabs.com

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

Verilog HDL 156


www.dkoplabs.com

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

Verilog HDL 157


www.dkoplabs.com

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

Verilog HDL 158


www.dkoplabs.com

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

Verilog HDL 159


www.dkoplabs.com

FSM – Mealy Machine


• Mealy machine - outputs based on state & present inputs

init

State Register
s(t+1)
C1 next s(t)
x(t) state present z(t)
state C2

clk

Verilog HDL 160


www.dkoplabs.com

FSM - Mealy & Moore Machine


• sequence 1101 detector

Verilog HDL 161


www.dkoplabs.com

Mealy - Sequence 1101 detector


module seq1101_mealy(y, x, RESET); got110 : if (x) begin
output y; reg y; D <= got1; y <= 1;
input x, RESET; end
parameter start = 2'b00, got1 = 2'b01, else begin
got11 = 2'b11, got110 = 2'b10; D <= start; y <= 0;
reg [1:0] Q, D; // state, next state logic end
reg CLK; default : D <= 2'bxx;
initial CLK <= 0; endcase
always end
#10 CLK <= ~CLK; // state variables
// next state logic always @(posedge CLK or negedge RESET)
always @(x or Q) begin
begin if (~RESET)
y <= 0; Q <= 0;
case(Q) else
start: D <= x ? got1 : start; Q <= D;
got1: D <= x ? got11 : start; end
got11: D <= x ? got11 : got110; endmodule

Verilog HDL 162


www.dkoplabs.com

Moore - Sequence 1101 detector


module seq1101_moore(y, x, CLK, RESET); got1101: D = x ? got11 : start;
output y; default : D = 3’bxxx;
reg y; end
input x, CLK, RESET; // state variables
parameter start = 3'b000, got1 = 3'b001, always @(posedge CLK or
got11 = 3'b011, got110 = 3'b010; negedge RESET)
got1101 = 3’b110; begin
reg [2:0] Q; // state variables if (~RESET)
reg [2:0] D; // next state logic output Q = 0;
// next state logic else
always @(x or Q) begin Q = D;
case(Q) end
start: D = x ? got1 : start; // output logic
got1: D = x ? got11 : start; always @ (Q)
got11: D = x ? got11 : got110; y = Q[2];
got110: D = x ? got1101 : start; endmodule

Verilog HDL 163


www.dkoplabs.com

Moore - Sequence 011 detector


module moore_011 (z, clk, x); always @ (posedge clk)
output z; current = next;
reg z; always @ (current)
if (next == got011)
input clk, x;
z = 1;
reg[1:0] next, current;
else
parameter *1:0+ reset = 2’b00; z = 0;
parameter *1:0+ got0 = 2’b01; always @ (x or current)
parameter *1:0+ got01 = 2’b10; begin
parameter *1:0+ got011 = 2’b11; case (current)
initial reset: if (x) next = reset; else next = got0;
begin got0: if (x) next = got01; else next = got0;
current = reset; got01: if (x) next = got011; else next = got0;
got011: if (x) next = reset; else next = got0;
next = reset;
endcase
z = 0;
end
end endmodule

Verilog HDL 164


www.dkoplabs.com

Mealy – Sequence 011 detector


`define reset 2’b00 always @ (posedge clk)
`define got0 2’b01 current = next;
`define got01 2’b10 always @ (current or x)
module mealy_011 (z, clk, x); z = (current == `got01 && x) ? 1 : 0;
output z; always @ (x or current) begin
reg z; case (current)
input clk, x; `reset: if (x) next = `reset;
reg[1:0] next, current; else next = `got0;
`got0: if (x) next = `got01;
initial else next = `got0;
begin `got01: if (x) next = `reset;
current = `reset; else next = `got0;
next = `reset; endcase
z = 0; end
end endmodule

Verilog HDL 165


www.dkoplabs.com

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

Verilog HDL 166


www.dkoplabs.com

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

Verilog HDL 169


www.dkoplabs.com

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

Verilog HDL 171


www.dkoplabs.com

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

Verilog HDL 172


www.dkoplabs.com

ROM - Example

Verilog HDL 173


www.dkoplabs.com

ROM - Example

Verilog HDL 174


www.dkoplabs.com

ROM - Example
• Synchronous and Asynchronous

module rom_synch(data, clk, addr); module rom_asynch(data, addr);


output [7:0] data;
output [1:0] data; input [3:0] addr;
input clk; reg[7:0] dout_r;
input [1:0] addr;
assign data = dout_r;
always @(posedge clk) always @ (addr)
case (addr) case (addr)
2‘b00 : data <= 2‘b01; 8'd0 : dout_r <= 8'd7;
2‘b01 : data <= 2‘b10; 8'd1 : dout_r <= 8'd6;
2‘b10 : data <= 2‘b11; ……………………………….
2‘b11 : data <= 2‘b00; 8'd7 : dout_r <= 8'd0;
endcase endcase
endmodule endmodule

Verilog HDL 175


www.dkoplabs.com

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

Verilog HDL 176


www.dkoplabs.com

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

Verilog HDL 178


www.dkoplabs.com

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];

Verilog HDL 179


www.dkoplabs.com

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

Verilog HDL 180


www.dkoplabs.com

Traffic Light Signal - Example


module traffic_lights; end
reg clock, red, amber, green; // wait for 'tics' posedge clocks
parameter on = 1, off = 0, red_tics = 350, // before turning 'color' light off
amber_tics = 30, green_tics = 200; task light;
// initialize colors output color;
initial begin input [31:0] tics;
red = off; amber = off; green = off; begin
end repeat (tics)
// sequence to control the lights @(posedge clock);
always begin color = off; // turn light off
red = on; // turn red light on end
light(red, red_tics); // and wait. endtask
green = on; // turn green light on // waveform for the clock
light(green, green_tics); // and wait. always
amber = on; // turn amber light on #100 clock = ~clock;
light(amber, amber_tics); // and wait. endmodule // traffic_lights

Verilog HDL 181

You might also like