Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

DSD (U5)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

CS T34 DIGITAL SYSTEM DESIGN Y2/S3

UNIT V
Digital Design with Verilog HDL: Hierarchical Modeling concepts – 4-bit ripple carry counter
– modules – instances – Data types – Arrays – System tasks – directives – Modules and Ports –
Gate-Level Modeling – Dataflow Modeling – Design of Multiplexers, counters and full adders –
Introduction to Behavioral Modeling.
2 MARKS
1. What is VHDL? (APRIL 2013) (APRIL/MAY 2012)

Verilog, standardized as IEEE 1364, is a hardware


description language (HDL) used to model electronic systems. It is most commonly used in the
design and verification of digital circuits at the register-transfer level of abstraction. It is also
used in the verification of analog circuits and mixed-signal circuits.

2. Define constant. (NOV 2011) (NOV 2012)

Used to have an identifier name for a constant value. The value cannot be changed by
any executable code.
SYNTAX

constant identifier : subtype_indication := constant_expression;

Example
constant Pi : real := 3.14159;
constant Half_Pi : real := Pi/2.0;
constant cycle_time : time := 2 ns;
constant N, N5 : integer := 5;

A deferred constant has no := constant_expression can only be used in a package


declaration and a value must appear in the package body.

3. Define procedure. (NOV 2011)

A procedure is a subprogram that defines algorithm for computing values or exhibiting


behavior. Procedure call is a statement.
Syntax
procedure procedure_name ( formal_parameter_list )
procedure procedure_name ( formal_parameter_list ) is
procedure_declarations
begin
sequential statements
end procedure procedure_name;
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
4. Describe packages in VHDL? (APRIL/MAY 2012)(APRIL 2013)
A package can basically be divided in two parts: package declaration and a package
body. Package declaration and package body relate to each other in quit a similar way as the
relation between ENTITY and its corresponding ARCHITECTURE. The difference is that
only one package body can exist for a package.

The syntax for a package declaration is as follows:

package_declaration
PACKAGE identifier IS
package_declarative_part
END [ PACKAGE ] [ package_simple_name ] ;

package_declarative_part

{ package_declarative_item }

Within a package declaration all package information may be gathered. This information
is declared only once and should not be subsequently modified. They are visible also in
the package body. The package declaration builds in this way the interface of the
package.

5. Write the structure of VHDL program (NOV 2012)


CS T34 DIGITAL SYSTEM DESIGN Y2/S3
VHDL Programming Structure:
Entity and Architecture are the two main basic programming structures in VHDL.

Entity

Entity can be seen as the black box view of the system. We define the inputs and outputs
of the system which we need to interface.

Entity ANDGATE is
Port (A : In std_logic;
B: in std_logic;
Y : out std_logic);
End entity ANDGATE;

Entity name ANDGATE is given by the programmer, each entity must have a name.

6. Write about 4-bit Ripple Carry Counter?

The ripple carry counter shown in Figure 2-3 is made up of negative edge-triggered
toggle flip flops (T_FF).

7. Define modules

A module is the basic building block in Verilog. A module can be an element or a


collection of lower-level design blocks. Typically, elements are grouped into modules to provide
common functionality that is used at many places in the design. A module provides the necessary
functionality to the higher-level block through its port interface (inputs and outputs), but hides
the internal implementation.
SYNTAX

module<module_name> (<module_terminal_list>);
...
<module internals>
...
...
Endmodule
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
Specifically, the T-flipflop could be defined as a module as follows:
module T_FF (q, clock, reset);
.
.
<functionality of T-flipflop>
.
.endmodule

8. Define instances.
A module provides a template from which you can create actual objects. When a module
is invoked, Verilog creates a unique object from the template. Each object has its own name,
variables, parameters, and I/O interface. The process of creating objects from a module template
is called instantiation, and the objects are called instances.

9. What are the data types in VHDL?

Data types in Verilog model actual data storage and switch elements in hardware very
closely.data types such as nets, registers, vectors, numbers, simulation time, arrays, parameters,
memories, and strings.

10. Explain Nets in VHDL


Nets represent connections between hardware elements. Just as in real circuits, nets have
values continuously driven on them by the outputs of devices that they are connected to. Net a
will continuously assume the value computed at the output of gate g1, which is b & c.
Figure 3-1. Example of Nets

Nets are declared primarily with the keyword wire.


wire a; // Declare net a for the above circuit
wireb,c; // Declare two wires b,c for the above circuit
wire d = 1'b0; // Net d is fixed to logic value 0 at declaration.

11. What is Register in VHDL?

In Verilog, the term register merely means a variable that can hold a value. Unlike a net,
a register does not need a driver. Verilog registers do not need a clock as hardware registers do.
Values of registers can be changed anytime in a simulation by assigning a new value to the
register.
Register data types are commonly declared by the keyword reg.
The default value for areg data type is x.
Example of Register
reg reset; // declare a variable reset that can hold its value
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
initial // this construct will be discussed later
begin
reset = 1'b1; //initialize reset to 1 to reset the digital circuit.
#100 reset = 1'b0; // after 100 time units reset is deasserted.
End
12. Define Vectors.

Nets or reg data types can be declared as vectors (multiple bit widths).
If bit width is notspecified, the default is scalar (1-bit).
Example :
wire a; // scalar net variable, default
wire [7:0] bus; // 8-bit bus
wire [31:0] busA,busB,busC; // 3 buses of 32-bit width.
reg clock; // scalar register, default
reg [0:40] virtual_addr; // Vector register, virtual address 41 bits
Vectors can be declared at [high# : low#] or [low# : high#], but the left number in the
Squared brackets is always the most significant bit of the vector. In the example
shownabove, bit 0 is the most significant bit of vector virtual_addr.
13. Define numbers and Time in VHDL.
Integer, real, and time register data types are supported in Verilog.

An integer is a general purpose register data type used for manipulating quantities.
Integers are declared by the keyword integer.

Registers declared as data type reg store values as unsigned quantities, whereas integers
store values as signed quantities.
integer counter; // general purpose variable used as a counter.
counter = -1; // A negative one is stored in the counter

Verilog simulation is done with respect to simulation time. A special time register data
type is used in Verilog to store simulation time. A time variable is declared with the keyword
time.
The width for time register data types is implementation-specific but is atleast 64 bits.The
system function $time is invoked to get the current simulation time.

14. Define Real in VHDL.

Real number constants and real register data types are declared with the keyword
real.They can be specified in decimal notation (e.g., 3.14) or in scientific notation (e.g.,
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
3e6,which is 3 x 106 ). Real numbers cannot have a range declaration, and their default valueis 0.
When a real value is assigned to an integer, the real number is rounded off to thenearest integer.
real delta; // Define a real variable called delta
initial
begin
delta = 4e10; // delta is assigned in scientific notation
delta = 2.13; // delta is assigned a value 2.13
end
integer i; // Define an integer i
initial
i = delta; // i gets the value 2 (rounded value of 2.13)

15. Define Arrays in VHDL?

Arrays are allowed in Verilog for reg, integer, time, real, realtime and vector register data
types. Multi-dimensional arrays can also be declared with any number of dimensions.

Arrays of nets can also be used to connect ports of generated instances. Each element of
the array can be used in the same fashion as a scalar or vector net. Arrays are accessed by
<array_name>[<subscript>]. For multi-dimensional arrays, indexes need to be provided for each
dimension.
Example
integer count[0:7]; // An array of 8 count variables
regbool[31:0]; // Array of 32 one-bit boolean register variables
timechk_point[1:100]; // Array of 100 time checkpoint variables

11 MARKS
Hierarchical Modeling concepts
There are two basic types of digital design methodologies:
 a top-down design methodology and
 a bottom-up design methodology.

In a top-down design methodology, we define the top-level block and identify the sub-blocks
necessary to build the top-level block.
We further subdivide the sub-blocks until we come to leaf cells, which are the cells that cannot
further be divided.
Figure 2-1 shows the top-down design process.
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
Figure 2-1. Top-down Design Methodology

In a bottom-up design methodology, we first identify the building blocks that are available to us.
These cells are then used for higher-level blocks until we build the top-level block in the design.
Figure 2-2 shows the bottom-up design process.

Figure 2-2. Bottom-up Design Methodology

Typically, a combination of top-down and bottom-up flows is used.


Design architects define the specifications of the top-level block.
Logic designers decide how the design should be structured by breaking up the functionality
into blocks and sub-blocks.
At the same time, circuit designers are designing optimized circuits for leaf-level cells.
They build higher-level cells by using these leaf cells.
The flow meets at an intermediate point where the switch-level circuit designers have created a
library of leaf cells by using switches, and the logic level designers have designed from top-
down until all modules are defined in terms of leaf cells.

4-bit Ripple Carry Counter


The ripple carry counter shown in Figure 2-3 is made up of negative edge-triggeredtoggle
flipflops (T_FF). Each of the T_FFs can be made up from negative edge-triggeredD-flipflops
(D_FF) and inverters (assuming q_bar output is not available on the D_FF),as shown in Figure 2-
4.
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
4-bit Ripple Carry Counter

FIGURE: T-flipflop

Thus, the ripple carry counter is built in a hierarchical fashion by using building blocks. The
diagram for the design hierarchy is shown in Figure 2-5.
Figure 2-5. Design Hierarchy

 In a top-down design methodology, we first have to specify the functionality of the ripple
carry counter, which is the top-level block.
 Then, we implement the counter with T_FFs. We build the T_FFs from the D_FF and an
additional inverter gate.
 Thus, we break bigger blocks into smaller building sub-blocks until we decide that we
cannot break up the blocks any further.
 A bottom-up methodology flows in the opposite direction.
 We combine small building blocks and build bigger blocks; e.g., we could build D_FF
from and and or gates, or we could build a custom D_FF from transistors.
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
 Thus, the bottom-up flow meets the top-down flow at the level of the D_FF.

Levels of Modules

A module can be an element or a collection of lower-level design blocks.


Typically, elements are grouped into modules to provide common functionality that is used at
many places in the design.
A module provides the necessary functionality to the higher-level block through its port interface
(inputs and outputs), but hides the internal implementation.
This allows the designer to modify module internals without affecting the rest of the design.

In Verilog, amodule is declared by the keyword module. A corresponding keyword endmodule


must
appear at the end of the module definition.
Each module must have a module_name, which is the identifier for the module, and a
module_terminal_list, which describes theinput and output terminals of the module.

module <module_name> (<module_terminal_list>);


...
<module internals>
...
...
endmodule
Specifically, the T-flipflop could be defined as a module as follows:
module T_FF (q, clock, reset);
.
.
<functionality of T-flipflop>
.
.
Endmodule

Verilog is both a behavioral and a structural language. Internals of each module can bedefined at
four levels of abstraction, depending on the needs of the design. The modulebehaves identically
with the external environment irrespective of the level of abstractionat which the module is
described. The internals of the module are hidden from theenvironment.

Thus, the level of abstraction to describe a module can be changed withoutany change in the
environment.

Behavioral or algorithmic level


• This is the highest level of abstraction provided by Verilog HDL. A module canbe
implemented in terms of the desired design algorithm without concern for thehardware
implementation details. Designing at this level is very similar to Cprogramming.
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
Dataflow level
• At this level, the module is designed by specifying the data flow. The designer isaware of how
data flows between hardware registers and how the data isprocessed in the design.

Gate level
• The module is implemented in terms of logic gates and interconnections betweenthese gates.
Design at this level is similar to describing a design in terms of agate-level logic diagram.

Switch level
• This is the lowest level of abstraction provided by Verilog. A module can beimplemented in
terms of switches, storage nodes, and the interconnectionsbetween them. Design at this level
requires knowledge of switch-levelimplementation details.

Instances

A module provides a template from which you can create actual objects. When a moduleis
invoked, Verilog creates a unique object from the template. Each object has its ownname,
variables, parameters, and I/O interface. The process of creating objects from amodule template
is called instantiation, and the objects are called instances.

In Example 2-1, the top-level block creates four instances from the T-flipflop (T_FF) template.
Each
T_FF instantiates a D_FF and an inverter gate. Each instance must be given a uniquename. Note
that // is used to denote single-line comments.

Example 2-1 Module Instantiation


// Define the top-level module called ripple carry
// counter. It instantiates 4 T-flipflops. Interconnections are
// shown in Section 2.2, 4-bit Ripple Carry Counter.
module ripple_carry_counter(q, clk, reset);
output [3:0] q; //I/O signals and vector declarations
//will be explained later.
input clk, reset; //I/O signals will be explained later.
//Four instances of the module T_FF are created. Each has a unique
//name.Each instance is passed a set of signals. Notice, that
//each instance is a copy of the module T_FF.
T_FF tff0(q[0],clk, reset);
T_FF tff1(q[1],q[0], reset);
T_FF tff2(q[2],q[1], reset);
T_FF tff3(q[3],q[2], reset);
endmodule
// Define the module T_FF. It instantiates a D-flipflop. We assumed
// that module D-flipflop is defined elsewhere in the design. Refer
// to Figure 2-4 for interconnections.
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
module T_FF(q, clk, reset);
//Declarations to be explained later
output q;
input clk, reset;
wire d;
D_FF dff0(q, d, clk, reset); // Instantiate D_FF. Call it dff0.
not n1(d, q); // not gate is a Verilog primitive. Explained later.
endmodule

Data Types

Value Set
Verilog supports four values and eight strengths to model the functionality of realhardware. The
four value levels are listed in Table 3-1.

Value Levels

In addition to logic values, strength levels are often used to resolve conflicts betweendrivers of
different strengths in digital circuits. Value levels 0 and 1 can have the strengthlevels listed in
Table 3-2.
Table 3-2. Strength Levels
CS T34 DIGITAL SYSTEM DESIGN Y2/S3

 If two signals of unequal strengths are driven on a wire, the stronger signal prevails.
 Forexample, if two signals of strength strong1 and weak0 contend, the result is resolved
as a
 strong1.
 If two signals of equal strengths are driven on a wire, the result is unknown. Iftwo signals
of strength strong1 and strong0 conflict, the result is an x.

Nets
 Nets represent connections between hardware elements.
 Just as in real circuits, nets havevalues continuously driven on them by the outputs of
devices that they are connected to.
 In Figure 3-1 net a is connected to the output of and gate g1.
 Net a will continuouslyassume the value computed at the output of gate g1, which is b &
c.
Figure 3-1. Example of Nets

 Nets are declared primarily with the keyword wire. Nets are one-bit values by
defaultunless they are declared explicitly as vectors.
 The terms wire and net are often usedinterchangeably. The default value of a net is z.
 Nets get the output value of their drivers. If a net has no driver, it gets the value z.

wire a; // Declare net a for the above circuit


wire b,c; // Declare two wires b,c for the above circuit
wire d = 1'b0; // Net d is fixed to logic value 0 at declaration.

Registers
 Registers represent data storage elements. Registers retain value until another value
isplaced onto them.
 In Verilog, the term register merely means a variable that can hold a value. Unlike a net,
a register does not need a driver.
 Verilog registers do not need a clock as hardware registers do. Values of registers can
bechanged anytime in a simulation by assigning a new value to the register.
 Register data types are commonly declared by the keyword reg. The default value for
areg data type is x. An example of how registers are used is shown Example 3-1.

Example 3-1 Example of Register


reg reset; // declare a variable reset that can hold its value
initial // this construct will be discussed later
begin
reset = 1'b1; //initialize reset to 1 to reset the digital circuit.
#100 reset = 1'b0; // after 100 time units reset is deasserted.
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
end
Registers can also be declared as signed variables. Such registers can be used for signed
arithmetic. Example 3-2 shows the declaration of a signed register.

Vectors
Nets or reg data types can be declared as vectors (multiple bit widths). If bit width is
notspecified, the default is scalar (1-bit).
wire a; // scalar net variable, default
wire [7:0] bus; // 8-bit bus
wire [31:0] busA,busB,busC; // 3 buses of 32-bit width.
reg clock; // scalar register, default
reg [0:40] virtual_addr; // Vector register, virtual address 41 bits
wide
Vectors can be declared at [high# : low#] or [low# : high#], but the left number in thesquared
brackets is always the most significant bit of the vector. In the example shownabove, bit 0 is the
most significant bit of vector virtual_addr.

Integer , Real, and Time Register Data Types

Integer
An integer is a general purpose register data type used for manipulating quantities.Integers are
declared by the keyword integer.
integer counter; // general purpose variable used as a counter.
initial
counter = -1; // A negative one is stored in the counter

Real
Real number constants and real register data types are declared with the keyword real.They can
be specified in decimal notation (e.g., 3.14) or in scientific notation (e.g., 3e6,which is 3 x 106 ).
Real numbers cannot have a range declaration, and their default valueis 0. When a real value is
assigned to an integer, the real number is rounded off to thenearest integer.
real delta; // Define a real variable called delta
initial
begin
delta = 4e10; // delta is assigned in scientific notation
delta = 2.13; // delta is assigned a value 2.13
end
integer i; // Define an integer i
initial
i = delta; // i gets the value 2 (rounded value of 2.13)

Time
Verilog simulation is done with respect to simulation time. A special time register datatype is
used in Verilog to store simulation time.
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
A time variable is declared with thekeyword time. The width for time register data types is
implementation-specific but is atleast 64 bits.The system function $time is invoked to get the
current simulation time.
time save_sim_time; // Define a time variable save_sim_time
initial
save_sim_time = $time; // Save the current simulation time
Simulation time is measured in terms of simulation seconds. The unit is denoted by s, the
same as real time.

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

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


reg bool[31:0]; // Array of 32 one-bit boolean register variables
time chk_point[1:100]; // Array of 100 time checkpoint variables
reg [4:0] port_id[0:7]; // Array of 8 port_ids; each port_id is 5 bits
wide
integer matrix[4:0][0:255]; // Two dimensional array of integers
reg [63:0] array_4d [15:0][7:0][7:0][255:0]; //Four dimensional array
wire [7:0] w_array2 [5:0]; // Declare an array of 8 bit vector wire
wire w_array1[7:0][5:0]; // Declare an array of single bit wires

It is important not to confuse arrays with net or register vectors. A vector is a singleelement that
is n-bits wide. On the other hand, arrays are multiple elements that are 1-bitor n-bits wide.

Examples of assignments to elements of arrays discussed above are shown below:


count[5] = 0; // Reset 5th element of array of count variables
chk_point[100] = 0; // Reset 100th time check point value
port_id[3] = 0; // Reset 3rd element (a 5-bit value) of port_id array.
matrix[1][0] = 33559; // Set value of element indexed by [1][0] to33559
array_4d[0][0][0][0][15:0] = 0; //Clear bits 15:0 of the register
//accessed by indices [0][0][0][0]
port_id = 0; // Illegal syntax - Attempt to write the entire array
matrix [1] = 0; // Illegal syntax - Attempt to write [1][0]..[1][255]
CS T34 DIGITAL SYSTEM DESIGN Y2/S3

System tasks

System Tasks
Verilog provides standard system tasks for certain routine operations. All system tasksappear in
the form $<keyword>. Operations such as displaying on the screen, monitoringvalues of nets,
stopping, and finishing are done by system tasks.
Displaying information

$display is the main system task for displaying values of variables or strings orexpressions.
This is one of the most useful tasks in Verilog.

Usage: $display(p1, p2, p3,....., pn);

p1, p2, p3,..., pn can be quoted strings or variables or expressions. The format of $displayis very
similar to printf in C.
Table 3-4. String Format Specifications

Example 3-3 shows some examples of the $display task. If variables contain x or zvalues, they
are printed in the displayed string as "x" or "z".

Example 3-3 $display Task


//Display the string in quotes
$display("Hello Verilog World");
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
-- Hello Verilog World
//Display value of current simulation time 230
$display($time);
-- 230
Monitoring information
Verilog provides a mechanism to monitor a signal when its value changes. This facility is
provided by the $monitor task.
Usage: $monitor(p1,p2,p3,....,pn);
 The parameters p1, p2, ... , pn can be variables, signal names, or quoted strings.
 A formatsimilar to the $display task is used in the $monitor task.
 $monitor continuously monitors
 the values of the variables or signals specified in the parameter list and displays
allparameters in the list whenever the value of any one variable or signal changes.
 Only one monitoring list can be active at a time. If there is more than one
$monitorstatement in your simulation, the last $monitor statement will be the active
statement.
 The earlier $monitor statements will be overridden.
 Two tasks are used to switch monitoring on and off.
Usage:
$monitoron;
$monitoroff;
 The $monitoron tasks enables monitoring, and the $monitoroff task disables
monitoringduring a simulation.
 Monitoring is turned on by default at the beginning of the simulationand can be
controlled during the simulation with the $monitoron and $monitoroff tasks.

 Examples of monitoring statements are given in Example 3-5. Note the use of $time in
 the $monitor statement.

/Monitor time and value of the signals clock and reset


//Clock toggles every 5 time units and reset goes down at 10 time units
initial
begin
$monitor($time,
" Value of signals clock = %b reset = %b", clock,reset);
end
Partial output of the monitor statement:
-- 0 Value of signals clock = 0 reset = 1
-- 5 Value of signals clock = 1 reset = 1
-- 10 Value of signals clock = 0 reset = 0
Stopping and finishing in a simulation
The task $stop is provided to stop during a simulation.
Usage: $stop;
 The $stop task puts the simulation in an interactive mode. The designer can then
debugthe design from the interactive mode.
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
 The $stop task is used whenever the designer wantsto suspend the simulation and
examine the values of signals in the design.
 The $finish task terminates the simulation.
Usage: $finish;
Examples of $stop and $finish are shown in Example 3-6.
Example 3-6 Stop and Finish Tasks
// Stop at time 100 in the simulation and examine the results
// Finish the simulation at time 1000.
initial // to be explained later. time = 0
begin
clock = 0;
reset = 1;
#100 $stop; // This will suspend the simulation at time = 100
#900 $finish; // This will terminate the simulation at time = 1000
End

Compiler Directives
Compiler directives are provided in Verilog. All compiler directives are defined by using
the `<keyword> construct. We deal with the two most useful compiler directives.

`define

The `define directive is used to define text macros in Verilog (see Example 3-7). TheVerilog
compiler substitutes the text of the macro wherever it encounters a`<macro_name>. This is
similar to the #define construct in C. The defined constants ortext macros are used in the Verilog
code by preceding them with a ` (back tick).
Example 3-7 `define Directive
//define a text macro that defines default word size
//Used as 'WORD_SIZE in the code
'define WORD_SIZE 32
//define an alias. A $stop will be substituted wherever 'S appears
'define S $stop;
//define a frequently used text string
'define WORD_REG reg [31:0]
// you can then define a 32-bit register as 'WORD_REG reg32;

`include
The `include directive allows you to include entire contents of a Verilog source file inanother
Verilog file during compilation. This works similarly to the #include in the Cprogramming
language. This directive is typically used to include header files, whichtypically contain global or
commonly used definitions (see Example 3-8).
Example 3-8 `include Directive
// Include the file header.v, which contains declarations in the
// main verilog file design.v.
'include header.v
...
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
...
<Verilog code in file design.v>
...
...
Two other directives, `ifdef and `timescale, are used frequently.

Modules and Ports

 A module definition always begins with the keyword module.


 The module name, portlist, port declarations, and optional parameters must come first in
a module definition.
 Port list and port declarations are present only if the module has any ports to interact
withthe external environment.
 The five components within a module are: variable declarations,dataflow statements,
instantiation of lower modules, behavioral blocks, and tasks orfunctions.
 These components can be in any order and at any place in the moduledefinition.
 The endmodule statement must always come last in a module definition.
 Allcomponents except module, module name, and endmodule are optional and can be
mixedand matched as per design needs.
 Verilog allows multiple modules to be defined in asingle file. The modules can be
defined in any order in the file.

To understand the components of a module shown above, let us consider a simpleexample of an


SR latch, as shown in Figure 4-2.
CS T34 DIGITAL SYSTEM DESIGN Y2/S3

The SR latch has S and R as the input ports and Q and Qbar as the output ports. The SRlatch and
its stimulus can be modeled as shown in Example 4-1.
Example 4-1 Components of SR Latch
// This example illustrates the different components of a module
// Module name and port list
// SR_latch module
module SR_latch(Q, Qbar, Sbar, Rbar);
//Port declarations
output Q, Qbar;
input Sbar, Rbar;
// Instantiate lower-level modules
// In this case, instantiate Verilog primitive nand gates
// Note, how the wires are connected in a cross-coupled fashion.
nand n1(Q, Sbar, Qbar);
nand n2(Qbar, Rbar, Q);
// endmodule statement
endmodule
// Module name and port list
// Stimulus module
module Top;
// Declarations of wire, reg, and other variables

wire q, qbar;
reg set, reset;
// Instantiate lower-level modules
// In this case, instantiate SR_latch
// Feed inverted set and reset signals to the SR latch
SR_latch m1(q, qbar, ~set, ~reset);
// Behavioral block, initial
initial
begin
$monitor($time, " set = %b, reset= %b, q= %b\n",set,reset,q);
set = 0; reset = 0;
#5 reset = 1;
#5 reset = 0;
#5 set = 1;
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
endendmodule
Notice the following characteristics about the modules defined above:
• In the SR latch definition above , notice that all components described in Figure4-1 need not be
present in a module. We do not find variable declarations,dataflow (assign) statements, or
behavioral blocks (always or initial).
• However, the stimulus block for the SR latch contains module name, wire, reg,and variable
declarations, instantiation of lower level modules, behavioral block(initial), and endmodule
statement but does not contain port list, port declarations,and data flow (assign) statements.
• Thus, all parts except module, module name, and endmodule are optional and canbe mixed and
matched as per design needs.

Ports
 Ports provide the interface by which a module can communicate with its environment.
 For example, the input/output pins of an IC chip are its ports.
 The environment caninteract with the module only through its ports. The internals of the
module are notvisible to the environment.
 This provides a very powerful flexibility to the designer. Theinternals of the module can
be changed without affecting the environment as long as theinterface is not modified.
Ports are also referred to as terminals.

List of Ports
 A module definition contains an optional list of ports.
 If the module does not exchangeany signals with the environment, there are no ports in
the list. Consider a 4-bit full adderthat is instantiated inside a top-level module Top.
 The diagram for the input/output portsis shown in Figure 4-3.

I/O Ports for Top and Full Adder

Notice that in the above figure, the module Top is a top-level module.
The modulefulladd4 is instantiated below Top. The module fulladd4 takes input on ports a, b,
andc_in and produces an output on ports sum and c_out.
Thus, module fulladd4 performs anaddition for its environment. The module Top is a top-level
module in the simulation anddoes not need to pass signals to or receive signals from the
environment.
Thus, it does nothave a list of ports. The module names and port lists for both module
declarations inVerilog are as shown in Example 4-2.
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
Example 4-2 List of Ports
module fulladd4(sum, c_out, a, b, c_in); //Module with a list of ports
module Top; // No list of ports, top-level module in simulation 4.2.2 Port

Declaration
All ports in the list of ports must be declared in the module. Ports can be declared asfollows:

Each port in the port list is defined as input, output, or inout, based on the direction of theport
signal. Thus, for the example of the fulladd4 in Example 4-2, the port declarationswill be as
shown in Example 4-3.
Example 4-3 Port Declarations
module fulladd4(sum, c_out, a, b, c_in);
//Begin port declarations section
output[3:0] sum;
output c_cout;
input [3:0] a, b;
input c_in;
//End port declarations section
...
<module internals>
...
endmodule
Note that all port declarations are implicitly declared as wire in Verilog. Thus, if a port
isintended to be a wire, it is sufficient to declare it as output, input, or inout. Input or inoutports
are normally declared as wires.

Port Connection Rules


One can visualize a port as consisting of two units, one unit that is internal to the moduleand
another that is external to the module. The internal and external units are connected.There are
rules governing port connections when modules are instantiated within othermodules. The
Verilog simulator complains if any port connection rules are violated.These rules are
summarized in Figure.
CS T34 DIGITAL SYSTEM DESIGN Y2/S3

Inputs
Internally, input ports must always be of the type net. Externally, the inputs can beconnected to a
variable which is a reg or a net.
Outputs
Internally, outputs ports can be of the type reg or net. Externally, outputs must always
beconnected to a net. They cannot be connected to a reg.
Inouts
Internally, inout ports must always be of the type net. Externally, inout ports must alwaysbe
connected to a net.
Width matching
It is legal to connect internal and external items of different sizes when making intermoduleport
connections. However, a warning is typically issued that the widths do notmatch.
Unconnected ports
Verilog allows ports to remain unconnected. For example, certain output ports might besimply
for debugging, and you might not be interested in connecting them to the externalsignals. You
can let a port remain unconnected by instantiating a module as shownbelow.

fulladd4 fa0(SUM, , A, B, C_IN); // Output port c_out is unconnected

Connecting by ordered list


Connecting by ordered list is the most intuitive method for most beginners. The signals tobe
connected must appear in the module instantiation in the same order as the ports in theport list in
the module definition.

Notice that the external signals SUM, C_OUT, A, B, and C_INappear in exactly the same order
as the ports sum, c_out, a, b, and c_in in moduledefinition of fulladd4.
Example 4-7 Connection by Ordered List
module Top;
//Declare connection variables
reg [3:0]A,B;
reg C_IN;
wire [3:0] SUM;
wire C_OUT;
//Instantiate fulladd4, call it fa_ordered.
//Signals are connected to ports in order (by position)
fulladd4 fa_ordered(SUM, C_OUT, A, B, C_IN);
...
<stimulus>
...
Endmodule

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


output[3:0] sum;
output c_cout;
input [3:0] a, b;
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
input c_in;
...
<module internals>
...
Endmodule

GATE-LEVEL MODELING

Gate types
A logic circuit can be designed by use of logic gates. Verilog supports basic logic gatesas
predefined primitives. These primitives are instantiated like modules except that theyare
predefined in Verilog and do not need a module definition. All logic circuits can bedesigned by
using basic gates. There are two classes of basic gates: and/or gates andbuf/not gates.

1. And/Or Gates
And/or gates have one scalar output and multiple scalar inputs. The first terminal in thelist of
gate terminals is an output and the other terminals are inputs. The output of a gateis evaluated as
soon as one of the inputs changes. The and/or gates available in Verilogare shown below.

and or xor
nand nor xnor

The corresponding logic symbols for these gates are shown in Figure 5-1. We consider
gates with two inputs. The output terminal is denoted by out. Input terminals are denoted
by i1 and i2.

Figure 5-1. Basic Gates

These gates are instantiated to build logic circuits in Verilog. Examples of gateinstantiations are
shown below. In Example 5-1, for all instances, OUT is connected tothe output out, and IN1 and
IN2 are connected to the two inputs i1 and i2 of the gateprimitives. Note that the instance name
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
does not need to be specified for primitives. Thislets the designer instantiate hundreds of gates
without giving them a name.More than two inputs can be specified in a gate instantiation. Gates
with more than twoinputs are instantiated by simply adding more input ports in the gate
instantiation (seeExample 5-1). Verilog automatically instantiates the appropriate gate.

Example 5-1 Gate Instantiation of And/Or Gates


wire OUT, IN1, IN2;
// basic gate instantiations.
and a1(OUT, IN1, IN2);
nand na1(OUT, IN1, IN2);
or or1(OUT, IN1, IN2);
nor nor1(OUT, IN1, IN2);
xor x1(OUT, IN1, IN2);
xnor nx1(OUT, IN1, IN2);
// More than two inputs; 3 input nand gate
nand na1_3inp(OUT, IN1, IN2, IN3);
// gate instantiation without instance name
and (OUT, IN1, IN2); // legal gate instantiation
The truth tables for these gates define how outputs for the gates are computed from the
inputs. Truth tables are defined assuming two inputs. The truth tables for these gates are
shown in Table 5-1. Outputs of gates with more than two inputs are computed by
applying the truth table iteratively.
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
Buf/Not Gates
Buf/not gates have one scalar input and one or more scalar outputs. The last terminal inthe port
list is connected to the input. Other terminals are connected to the outputs. Wewill discuss gates
that have one input and one output.Two basic buf/not gate primitives are provided in Verilog.

1.buf 2. not

These gates are instantiated in Verilog as shown Example 5-2. Notice that these gates canhave
multiple outputs but exactly one input, which is the last terminal in the port list.

Example 5-2 Gate Instantiations of Buf/Not Gates


// basic gate instantiations.
buf b1(OUT1, IN);
not n1(OUT1, IN);
// More than two outputs
buf b1_2out(OUT1, OUT2, IN);
// gate instantiation without instance name
not (OUT1, IN); // legal gate instantiation
The truth tables for these gates are very simple. Truth tables for gates with one input and
one output are shown in Table 5-2.

Bufif/notif
Gates with an additional control signal on buf and not gates are also available.
bufif1 notif1
bufif0 notif0
These gates propagate only if their control signal is asserted. They propagate z if theircontrol
signal is deasserted. Symbols for bufif/notif are shown in Figure 5-3.
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
Figure 5-3. Gates Bufif and Notif

Table 5-3. Truth Tables for Bufif/Notif Gates

These gates are used when a signal is to be driven only when the control signal is asserted. Such
a situation is applicable when multiple drivers drive the signal.

These drivers are designed to drive the signal on mutually exclusive control signals.
Example 5-3 shows examples of instantiation of bufif and notif gates.

Example 5-3 Gate Instantiations of Bufif/Notif Gates


//Instantiation of bufif gates.
bufif1 b1 (out, in, ctrl);
bufif0 b0 (out, in, ctrl);
//Instantiation of notif gates
notif1 n1 (out, in, ctrl);
notif0 n0 (out, in, ctrl);

Gate-level multiplexer
We will design a 4-to-1 multiplexer with 2 select signals. Multiplexers serve a usefulpurpose in
logic design. They can connect two or more sources to a single destination.They can also be used
to implement boolean functions. We will assume for this examplethat signals s1 and s0 do not
get the value x or z. The I/O diagram and the truth table forthe multiplexer are shown in Figure
5-4. The I/O diagram will be useful in setting up theport list for the multiplexer.
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
Figure 5-4. 4-to-1 Multiplexer

We will implement the logic for the multiplexer using basic logic gates. The logicdiagram for the
multiplexer is shown in Figure 5-5.

Verilog Description of Multiplexer


// Module 4-to-1 multiplexer. Port list is taken exactly from
// the I/O diagram.
module mux4_to_1 (out, i0, i1, i2, i3, s1, s0);
// Port declarations from the I/O diagram
output out;
input i0, i1, i2, i3;
input s1, s0;
// Internal wire declarations
wire s1n, s0n;
wire y0, y1, y2, y3;
// Gate instantiations
// Create s1n and s0n signals.
not (s1n, s1);
not (s0n, s0);
// 3-input and gates instantiated
and (y0, i0, s1n, s0n);
and (y1, i1, s1n, s0);
and (y2, i2, s1, s0n);
and (y3, i3, s1, s0);
// 4-input or gate instantiated
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
or (out, y0, y1, y2, y3);
endmodule

This multiplexer can be tested with the stimulus shown in Example 5-6. The stimuluschecks that
each combination of select signals connects the appropriate input to theoutput. The signal
OUTPUT is displayed one time unit after it changes. System task$monitor could also be used to
display the signals when they change values.

Example 5-6 Stimulus for Multiplexer


// Define the stimulus module (no ports)
module stimulus;
// Declare variables to be connected
// to inputs
reg IN0, IN1, IN2, IN3;
84
reg S1, S0;
// Declare output wire
wire OUTPUT;
// Instantiate the multiplexer
mux4_to_1 mymux(OUTPUT, IN0, IN1, IN2, IN3, S1, S0);
// Stimulate the inputs
// Define the stimulus module (no ports)
initial
begin
// set input lines
IN0 = 1; IN1 = 1; IN2 = 1; IN3 = 1;
#1 $display("IN0= %b, IN1= %b, IN2= %b, IN3= %b\n",IN0,IN1,IN2,IN3);
// choose IN0
S1 = 0; S0 = 0;
#1 $display("S1 = %b, S0 = %b, OUTPUT = %b \n", S1, S0, OUTPUT);
// choose IN1
S1 = 0; S0 = 1;
#1 $display("S1 = %b, S0 = %b, OUTPUT = %b \n", S1, S0, OUTPUT);
// choose IN2
S1 = 1; S0 = 0;
#1 $display("S1 = %b, S0 = %b, OUTPUT = %b \n", S1, S0, OUTPUT);
// choose IN3
S1 = 1; S0 = 1;
#1 $display("S1 = %b, S0 = %b, OUTPUT = %b \n", S1, S0, OUTPUT);
end
endmodule

The output of the simulation is shown below. Each combination of the select signals is
tested.
IN0= 1, IN1= 1, IN2= 1, IN3= 1
S1 = 0, S0 = 0, OUTPUT = 1
S1 = 0, S0 = 1, OUTPUT = 1
S1 = 1, S0 = 0, OUTPUT = 1
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
S1 = 1, S0 = 1, OUTPUT = 1

DATAFLOW MODELING

For small circuits, the gate-level modeling approach works very well because the numberof gates
is limited and the designer can instantiate and connect every gate individually.Also, gate-level
modeling is very intuitive to a designer with a basic knowledge of digitallogic design. However,
in complex designs the number of gates is very large. Thus,designers can design more effectively
if they concentrate on implementing the function ata level of abstraction higher than gate level.
Dataflow modeling provides a powerful wayto implement a design. Verilog allows a circuit to be
designed in terms of the data flowbetween registers and how a design processes data rather than
instantiation of individualgates.

Continuous Assignments
A continuous assignment is the most basic statement in dataflow modeling, used to drivea value
onto a net. This assignment replaces gates in the description of the circuit anddescribes the
circuit at a higher level of abstraction. The assignment statement starts withthe keyword assign.
The syntax of an assign statement is as follows.

continuous_assign ::= assign [ drive_strength ] [ delay3 ]


list_of_net_assignments ;
list_of_net_assignments ::= net_assignment { , net_assignment }
net_assignment ::= net_lvalue = expression

Continuousassignments have the following characteristics:


1. The left hand side of an assignment must always be a scalar or vector net or aconcatenation of
scalar and vector nets. It cannot be a scalar or vector register.
2. Continuous assignments are always active. The assignment expression isevaluated as soon as
one of the right-hand-side operands changes and the value isassigned to the left-hand-side net.
3. The operands on the right-hand side can be registers or nets or function calls.
Registers or nets can be scalars or vectors.
4. Delay values can be specified for assignments in terms of time units. Delay valuesare used to
control the time when a net is assigned the evaluated value. Thisfeature is similar to specifying
delays for gates. It is very useful in modelingtiming behavior in real circuits.

Examples of continuous assignments are shown below. Operators such as &, ^, |, {, } and
+ used in the examples, Operator Types. At this point,concentrate on how the assign statements
are specified.

Example 6-1 Examples of Continuous Assignment


// Continuous assign. out is a net. i1 and i2 are nets.
assign out = i1 & i2;
// Continuous assign for vector nets. addr is a 16-bit vector net
// addr1 and addr2 are 16-bit vector registers.
assign addr[15:0] = addr1_bits[15:0] ^ addr2_bits[15:0];
// Concatenation. Left-hand side is a concatenation of a scalar
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
// net and a vector net.
assign {c_out, sum[3:0]} = a[3:0] + b[3:0] + c_in;
We now discuss a shorthand method of placing a continuous assignment on a net.

Delays
Delay values control the time between the change in a right-hand-side operand and whenthe new
value is assigned to the left-hand side. Three ways of specifying delays incontinuous assignment
statements are regular assignment delay, implicit continuousassignment delay, and net
declaration delay.

6.2.1 Regular Assignment Delay

EXAMPLE:

assign #10 out = in1 & in2; // Delay in a continuous assign

The waveform in Figure 6-1 is generated by simulating the above assign statement. Itshows the
delay on signal out. Note the following change:
1. When signals in1 and in2 go high at time 20, out goes to a high 10 time units later(time = 30).
2. When in1 goes low at 60, out changes to low at 70.
3. However, in1 changes to high at 80, but it goes down to low before 10 time unitshave elapsed.
4. Hence, at the time of recomputation, 10 units after time 80, in1 is 0. Thus, outgets the value 0.
A pulse of width less than the specified assignment delay is notpropagated to the output.

Expressions, Operators, and Operands


Dataflow modeling describes the design in terms of expressions instead of primitivegates.
Expressions, operators, and operands form the basis of dataflow modeling.
6.3.1 Expressions
Expressions are constructs that combine operators and operands to produce a result.
// Examples of expressions. Combines operands and operators
a^b
addr1[20:17] + addr2[20:17]
in1 | in2
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
Operands
Operands can be constants, integers, real numbers, nets, registers, times, bit-select (one bit of
vector net or a vector register),part-select (selected bits of the vector net or register vector), and
memories or functioncalls (functions are discussed later).
integer count, final_count;
final_count = count + 1;//count is an integer operand
real a, b, c;
c = a - b; //a and b are real operands
reg [15:0] reg1, reg2;
reg [3:0] reg_out;
reg_out = reg1[3:0] ^ reg2[3:0];//reg1[3:0] and reg2[3:0] are
//part-select register operands
reg ret_value;
ret_value = calculate_parity(A, B);//calculate_parity is a
//function type operand

Operators
Operators act on the operands to produce desired results. Verilog provides various typesof
operators. Operator types are discussed in detail in Section 6.4, Operator Types.d1 && d2 // &&
is an operator on operands d1 and d2
!a[0] // ! is an operator on operand a[0]
B >> 1 // >> is an operator on operands B and 1

Operator Types
Verilog provides many different operator types. Operators can be arithmetic, logical,relational,
equality, bitwise, reduction, shift, concatenation, or conditional. Some of theseoperators are
similar to the operators used in the C programming language. Each operatortype is denoted by a
symbol.
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
Design of Multiplexers, counters and full adders

Design of halfadder
1. Logic circuit of half adder
2. Gate level code for half adder

halfadder.v
module
halfadder(a,b,sum,carry);
input a,b;
output sum, carry;
wire sum, carry;
assign sum = a^b; // sum bit
assign carry = (a&b) ; //carry bit
endmodule

3. Test bench code


tb_halfadder.v
module main;
reg a, b;
wire sum, carry;
halfadder add(a,b,sum,carry);
always @(sum or carry)
begin
$display("time=%d:%b + %b = %b,carry = %b\n",$time,a,b,sum,carry);
end
initial
begin
a = 0; b = 0;
#5
a = 0; b = 1;
#5
a = 1; b = 0;
#5
a = 1; b = 1;
end
initial begin
$dumpfile ("halfadder.vcd");
$dumpvars;
end
endmodule

Design of fulladder
1. Logic circuit of full adder
2. Gate level code for fulladder

Fulladder.v
module fulladder(a,b,c,sum,carry);
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
input a,b,c;
output sum,carry;
wire sum,carry;
assign sum=a^b^c; // sum bit
assign carry=((a&b) | (b&c) | (a&c)); //carry bit
endmodule

3. Test bench code for full adder


tb_fulladder.v
module main;
reg a, b, c;
wire sum, carry;
fulladder add(a,b,c,sum,carry);
always @(sum or carry)
begin
$display("time=%d:%b + %b + %b = %b, carry =%b\n",$time,a,b,c,sum,carry);
end
initial
begin
a = 0; b = 0; c = 0;
#5
a = 0; b = 1; c = 0;
#5
a = 1; b = 0; c = 1;
#5
a = 1; b = 1; c = 1;
end
initial begin
$dumpfile ("fulladder.vcd");
$dumpvars;
end
endmodule

Design of multiplexer
1. Logic circuit of multiplexer
2. Gate level code for multiplexer

mux4_to_1.v
// Module 4-to-1 multiplexer. Port list is taken exactly from the I/O diagram.
module mux4_to_1 (out, i0, i1, i2, i3, s1, s0);
// Port declarations from the I/O diagram
output out;
input i0, i1, i2, i3;
input s1, s0;
// Internal wire declarations
wire s1n, s0n;
wire y0, y1, y2, y3;
// Gate instantiations
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
// Create s1n and s0n signals.
not (s1n, s1);
not (s0n, s0);
// 3-input and gates instantiated
and (y0, i0, s1n, s0n);
and (y1, i1, s1n, s0);
and (y2, i2, s1, s0n);
and (y3, i3, s1, s0);
// 4-input or gate instantiated
or (out, y0, y1, y2, y3);
endmodule

3. Test bench code for multiplexer


tb_mux4.v
// Define the stimulus module (no ports)
module stimulus;
// Declare variables to be connected
// to inputs
reg IN0, IN1, IN2, IN3;
reg S1, S0;
// Declare output wire
wire OUTPUT;
// Instantiate the multiplexer
mux4_to_1 mymux(OUTPUT, IN0, IN1, IN2, IN3, S1, S0);
// Stimulate the inputs
// Define the stimulus module (no ports)
initial
begin
// set input lines
IN0 = 1; IN1 = 1; IN2 = 1; IN3 = 1;
#1 $display("IN0= %b, IN1= %b, IN2= %b, IN3= %b\n",IN0,IN1,IN2,IN3);
// choose IN0
S1 = 0; S0 = 0;
#1 $display("S1 = %b, S0 = %b, OUTPUT = %b \n", S1, S0, OUTPUT);
// choose IN1
S1 = 0; S0 = 1;
#1 $display("S1 = %b, S0 = %b, OUTPUT = %b \n", S1, S0, OUTPUT);
// choose IN2
S1 = 1; S0 = 0;
#1 $display("S1 = %b, S0 = %b, OUTPUT = %b \n", S1, S0, OUTPUT);
// choose IN3
S1 = 1; S0 = 1;
#1 $display("S1 = %b, S0 = %b, OUTPUT = %b \n", S1, S0, OUTPUT);
end
initial begin
$dumpfile ("mux4_to_1.vcd");
$dumpvars;
end
endmodule
CS T34 DIGITAL SYSTEM DESIGN Y2/S3

Design of upcounter
1. Logic circuit of upcounter
2. Gate level code for upcounter

UPcounter.v
`define TICK #2
module downCntr(clk, reset, Q);
input clk, reset;
output [3:0] Q;
reg [3:0] Q;
//Behavioral Code for a Down Counter
always @ (posedgeclk) begin
if (~reset) begin
Q <= `TICK Q+1;
end
end
always @ (posedge reset) begin
Q <= 4'b0000;
end
endmodule

3. Test bench code for upcounter


tb_UPncounter.v

module main;
regclk, reset;
wire [3:0] Q;
downCntr dnCntr1(clk, reset, Q);
always @(posedgeclk)begin
$display(" clk=%b, reset=%b,Q=%b\n", clk, reset, Q);
end
initial begin
forever begin
clk<= 0;
#5
clk<= 1;
//#5
//clk<= 0;
end
end
initial begin
reset = 1;
#2
reset = 0;
#85 $finish;
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
//#17
//reset = 1;
//#12
//reset = 0;
//#85 $finish;
end
initial begin
$dumpfile ("upcounter.vcd");
$dumpvars;
end
endmodule

Design of downcounter
1. Logic circuit of downcounter
2. Gate level code for downcounter

downcounter.v
`define TICK #2
module downCntr(clk, reset, Q);
input clk, reset;
output [3:0] Q;
reg [3:0] Q;
//Behavioral Code for a Down Counter
always @ (posedgeclk) begin
if (~reset) begin
Q <= `TICK Q-1;
end
end
always @ (posedge reset) begin
Q <= 4'b0000;
end
endmodule

3. Test bench code for downcounter


tb_downcounter.v

module main;
regclk, reset;
wire [3:0] Q;
downCntr dnCntr1(clk, reset, Q);
always @(posedgeclk)begin
$display(" clk=%b, reset=%b,Q=%b\n", clk, reset, Q);
end
initial begin
forever begin
clk<= 0;
#5
clk<= 1;
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
//#5
//clk<= 0;
end
end
initial begin
reset = 1;
#2
reset = 0;
#85 $finish;
//#17
//reset = 1;
//#12
//reset = 0;
//#85 $finish;
end
initial begin
$dumpfile ("downCntr.vcd");
$dumpvars;
end
endmodule

Introduction to Behavioral Modeling

Verilog provides designers the ability to describe design functionality in an algorithmicmanner.


In other words, the designer describes the behavior of the circuit. Thus,behavioral modeling
represents the circuit at a very high level of abstraction. Design atthis level resembles C
programming more than it resembles digital circuit design.Behavioral Verilog constructs are
similar to C language constructs in many ways. Verilogis rich in behavioral constructs that
provide the designer with a great amount offlexibility.

Structured Procedures
There are two structured procedure statements in Verilog: always and initial. Thesestatements
are the two most basic statements in behavioral modeling. All other behavioralstatements can
appear only inside these structured procedure statements.

initial Statement
All statements inside an initial statement constitute an initial block. An initial block startsat time
0, executes exactly once during a simulation, and then does not execute again. Ifthere are
multiple initial blocks, each block starts to execute concurrently at time 0. Eachblock finishes
execution independently of other blocks. Multiple behavioral statementsmust be grouped,
typically using the keywords begin and end. If there is only onebehavioral statement, grouping is
not necessary. This is similar to the begin-end blocks inPascal programming language or the { }
grouping in the C programming language.
Example 7-1 illustrates the use of the initial statement.
Example 7-1 initial Statement
module stimulus;
reg x,y, a,b, m;
initial
CS T34 DIGITAL SYSTEM DESIGN Y2/S3
m = 1'b0; //single statement; does not need to be grouped
initial
begin
#5 a = 1'b1; //multiple statements; need to be grouped
#25 b = 1'b0;
end
initial
begin
#10 x = 1'b0;
#25 y = 1'b1;
end
initial

#50 $finish;
Endmodule

In the above example, the three initial statements start to execute in parallel at time 0. If adelay
#<delay> is seen before a statement, the statement is executed <delay> time unitsafter the current
simulation time. Thus, the execution sequence of the statements insidethe initial blocks will be as
follows.
time statement executed
0 m = 1'b0;
5 a = 1'b1;
10 x = 1'b0;
30 b = 1'b0;
35 y = 1'b1;
50 $finish;
The initial blocks are typically used for initialization, monitoring, waveforms and otherprocesses
that must be executed only once during the entire simulation run. Thefollowing subsections
discussion how to initialize values using alternate shorthandsyntax. The use of such shorthand
syntax has the same effect as an initial block combinedwith a variable declaration.

always Statement
All behavioral statements inside an always statement constitute an always block. Thealways
statement starts at time 0 and executes the statements in the always blockcontinuously in a
looping fashion. This statement is used to model a block of activity thatis repeated continuously
in a digital circuit. An example is a clock generator module thattoggles the clock signal every
half cycle. In real circuits, the clock generator is activefrom time 0 to as long as the circuit is
powered on. Example 7-5 illustrates one method tomodel a clock generator in Verilog.
Example 7-5 always Statement
module clock_gen (output reg clock);
//Initialize clock at time zero
initial
clock = 1'b0;
//Toggle clock every half-cycle (time period = 20)
always
#10 clock = ~clock;
CS T34 DIGITAL SYSTEM DESIGN Y2/S3

initial
#1000 $finish;
endmodule
In Example 7-5, the always statement starts at time 0 and executes the statement clock =
~clock every 10 time units.

UNVERSITY QUESTIONS

1. Explain in detail the VHDL for combinational circuit. (11) (NOV'12)


2. Explain in detail the structure of VHDL. (11) (NOV'11)
3. Explain in detail the VHDL for sequential circuit. (11) (NOV'11)
4. Write a VHDL description to model a ripple counter. (11) (APR'12)
5. Explain how will you model the combinational logic using VHDL. (11) (APR'12)
6. Explain function and procedure in VHDL in detail. (11) (APR/MAY'12)
7. Give the design description of 2- to -4 Decoder circuit. (11) (APR'13 - IT)
8. Elaborate various levels of design description in Verilog. (11) (APR'13 - IT)

You might also like