Sie sind auf Seite 1von 103

VERILOG HDL:

AN EASY APPROACH
FOR
THE BEGINNERS

Md. Liakot Ali


Ishak Aris
Roslina Sidek
2
Preface

Verilog HDL has emerged as the most efficient solution for designing complex VLSI chip. It is
IEEE accepted, industry standard and technology independent VLSI design tool. Today millions of
transistors are being integrated on a single chip named as Application Specific Integrated Circuit
(ASIC)/System-on-a-Chip (SoC) following the HDL based design approach.

This book is intended specially for undergraduate and postgraduate students, and engineers who like
to learn Verilog HDL within a short time even in a day. An approach of “Learn by Example” is
adopted in writing this book. Having a basic background of digital logic design, the reader can
easily learn all about designing digital circuit using Verilog HDL. Chapter 1 of this book describes
a brief about Verilog HDL and modern approach in designing and implementation of complex
digital system. Chapter 2 presents the grammar of Verilog HDL. Then the following three chapters
include the design examples and explanation of simple to complex digital circuits using Verilog
HDL. Chapter 6 describes efficient coding style and functional verification of digital design which
is essential once the reader of this book is familiar in writing Verilog code. Chapter 7 presents the
FPGA implementation of digital design.

We like to thank everybody who has directly or indirectly helped us to make this book into
realization. Views and suggestions from the readers are most welcome for further enhancement of
this book.

Md. Liakot Ali


Ishak Aris
Roslina Sidek

3
4
CONTENTS

CHAPTER

1 Verilog HDL in Digital Design 1.1


1.1 Introduction 1.1
1.2 Advantages of HDL based Design Technique 1.1
1.3 Why Verilog HDL 1.2
1.4 Types of Verilog Coding Style 1.2
1.5 Digital System Design and Implementation 1.5
1.6 Summary 1.10

2 Grammar of Verilog HDL 2.1


2.1 Introduction 2.1
2.2 Basic Syntax and Operators of Verilog Language 2.1
2.3 Verilog Syntax 2.3
2.4 Verilog Operators 2.7
2.5 Summary 2.8

3 Structural Verilog Coding 3.1


3.1 Introduction 3.1
3.2 Primitives in Structural Coding 3.1
3.3 Example of Structural Verilog Coding in Designing Digital Circuits
3.2
3.4 Exercise related to Structural Verilog Code 3.5
3.5 Summary 3.6

4 Verilog Coding for Combinational Circuit 4.1


4.1 Introduction 4.1
4.2 RTL Coding of Digital Circuit 4.1
4.2.1 RTL Coding using Continuous Assignment 4.1
4.2.2 Examples and Exercises of RTL Verilog Coding using
Continuous Assignment 4.2
4.2.3 RTL Verilog Coding using Procedural Assignment 4.5
4.2.4 Examples and Exercises of RTL Coding using Procedural
Assignment 4.5
4.3 Summary 4.11

5 Verilog Coding for Sequential Circuit 5.1


5.1 Introduction 5.1
5.2 RTL Coding of Sequential Logic Circuit
5.3 Examples of RTL Coding for Sequential Circuits 5.1
5.4 Interconnection between Modules 5.16
5.5 Finite State Machine Design 5.20
5.6 Summary 5.32

6 Efficient Verilog HDL Coding and Verification 6.1


6.1 Introduction 6.1
6.2 Good Coding Style 6.1
6.2.1 Naming of Signals 6.1

5
6.2.2 Design Partitioning 6.2
6.2.3 Sensitivity List 6.2
6.2.4 Blocking and Nonblocking Assignment 6.5
6.2.5 Gated Clock and Internally Generated Clock 6.10
6.3 Simulation for Design Verification 6.11
6.3.1 Test Bench 6.12
6.4 Summary 6.14

7 FPGA Implementation of Digital Design 7.1


7.1 Introduction 7.1
7.2 Field Programmable Gate Array (FPGA) or Programmable Logic
Devices (PLD) 7.2
7.3 Operation of Quartus II Software 7.2
7.3.1 Start of Quartus II Software 7.2
7.3.2 Create a New Project 7.4
7.3.3 Create a Schematic based Design 7.8
7.3.4 Simulate the Design 7.10
7.3.5 Pin Assignments 7.15
7.3.6 Programming the FPGA 7.16
7.4 Summary 7.19

8 References R.1

6
Chapter 1: Verilog HDL in Digital Design

1.1 Introduction

The impact of digital electronics in our daily life is so much now a days, the current period is named
as digital age. Digital solutions are being observed in all areas such as telecommunications,
consumer electronics, controls, data manipulations etc. To design a digital system, once the
conventional approach such as hand-draw, schematic based design technique etc. was the only
choice to the designer. However the scenario has been changed. Now millions of transistors are
being integrated on a single chip integrated circuit (IC) where the conventional design technique is
impossible to be used [1]. It points towards a new approach for designing today’s complex digital
system and that new approach is designing VLSI chip using Hardware Description Language
(HDL).

1.2 Advantages of HDL based Design Technique

HDL based design technique has been emerged as the most efficient solution for any complex
digital design. It offers the following advantages over conventional design approaches [2-5]:
• It is technology independent. If a particular IC fabrication process becomes outdated, it is
possible to synthesize a new design by only changing the technology file but using the same
HDL code
• HDL shortens the design cycle of a chip by efficiently describing and simulating the
behavior of the chip. A complex circuit can be designed using a few lines of HDL code
• It lowers the cost of design of an IC
• It improves design quality of a chip. Area and timing of the chip can be optimized and
analyzed in different stages of design of a chip.

1.3 Why Verilog HDL

There are different types of HDL available in the market. Some of it are vendor dependent where
the HDL code is only usable under the software provided by the specific vendor. For example,
AHDL (Altera hardware description language) from Altera company, Lola (Logic Language) from
European Silicon Structure (ES2) company etc. are some of the examples of vendor dependent
HDL tools. However, Verilog HDL and VHDL (Very high speed IC Hardware Description
Language) are now widely accepted industry standard and vendor independent tool for digital
7
system design [6-9]. Verilog HDL is introduced by Cadence Data Systems, Inc. and later its control
is transferred to a consortium of companies and universities known as open Verilog international
(OVI) whereas VHDL is used primarily by defense contractors. VHDL is popular in European
countries whereas Verilog HDL is widely used in Asia and America. Currently Verilog is used by
the famous IC design companies such as Motorolla, Intel etc. Verilog HDL is IEEE standard and
easier than VHDL. In VHDL, libraries to be used for a program have to be declared whereas it is
not necessary in Verilog HDL programming. It is also less error prone. It has many pre-defined
features very specific to IC design.

1.4 Types of Verilog Coding Style

There are three types of Verilog coding style as follows:


• RTL Verilog Code: Digital circuit can be represented in different ways such as gate level
representation, transistor level representation etc. RTL, acronym of Register transfer Level
(RTL), is also another type of representation style for digital circuit. The reason why it is named
as RTL is that any complex digital system can be partitioned into different modules where each
module is basically consists of registers and gates. Information is stored in the registers and
specific operation is performed using the information, and then it is transferred among the
registers. Hence the said representation style is known as RTL. For example, we may define an
addition event: X=A+B; It means that the sum of the content of register A and register B is
transferred to the storage device X. Figure 1.1 shows the example of RTL code of a 2/1 Mux.

module mux_21(A, B, S, Y);


input A, B, S;
output Y;
A reg Y;
2/1 Y
always @ (S or A or B) begin
B Mux
if (S= =1) Y=A;
else Y=B;
S endmodule

Figure 1.1: (a) Block diagram of a A 2/1 Mux (b) Example of RTL Code Showing a 2/1 Mux

8
• Structural Verilog Code: It describes the components and interconnections present in a design.
Electronic Design Automation (EDA) tool compiles and synthesizes the RTL code of a design
and produces the netlist of the design in the form of structural code. Table 1.1 shows the
example of structural code for a circuit of a 2/1 Mux as shown in Figure 1.2.

Table 1.1: Example of Structural Code Showing a 2/1 Mux


module mux (A, B, S, Out);
input A, B, S;
output Out;
wire M, N, P;
and g1 (N, B, S);
and g2 (P, M, A);
not g3 (M, S);
or g4 (Out, N, P);
endmodule

AND2
A INPUT
VCC
P
NOT inst
S INPUT OR2
VCC g2
inst3 M OUTPUT Out
g3 inst2
AND2 g4
B INPUT
VCC
inst1
N
g1

Figure 1.2: Logic diagram of a 2/1 Mux

Behavioral Verilog code: Behavioral code describes the functionality and behavior of the

functional block diagram of a design. It is often used for system level modeling and simulation of a

design. Table 1.2 shows an example of behavioral Verilog code (using fork and join). Usually many

of the commands in behavioral code are not synthesizable (for example, wait command as shown in

Table 1.2) and the code length of a design is much smaller than to write for RTL code of the same

design because it is only for simulation purpose.

9
Table 1.2: Example of Behavioral Verilog Code
fork
// start of fork block 1
begin
wait (y != 0);
a = y;
end
// start of fork block 2
begin
wait (z != 0);
b = z;
end
join

1.5 Digital System Design and Implementation

To realize the design of a semiconductor device into physical hardware, it can be sent to foundry for
fabrication or it can be downloaded into Programmable Logic Device (PLD) or Field Programmable
Gate Array (FPGA). PLD or FPGA is a semiconductor device with programmable gates and
interconnects [10]. It is available in the market for the designers to use. Details about FPGA are
presented in Chapter 7.

Hardware Realization of a Design upon Fabrication: Figure 1.3 shows the design flow and all
the steps for fabrication of a semiconductor device. The most important step of a design is system
idea or specification. It is said that specification is 1/3 of total IC design project!. It requires
extensive experience to define the best compromise between what is wanted and what can be made.
Detailed specifications must be agreed upon with the system people because any major changes
during design will result in significant delays.

10
Semiconductor System Design Flow

Figure 1.3: Design Flow of a Semiconductor System [11]

11
Design approach can be top-down or bottom-up. It depends on the nature of application of the
design. When performance, reliability and accuracy are prime importance (for example: space
application, scientific application etc.) then bottom-up approach is followed although it is labor
intensive and burdened with high cost and long design time whereas top-down approach is well
suited for purely digital design with relatively short turn-around time and moderate area-
performance requirements.

In the top-down approach, HDL code of a design is written (using software provided editor) and
then it is compiled and simulated to test the expected functionality using EDA tool. However for
simulation, test bench of the design is written in Verilog code in another file where a set of stimulus
is written for the inputs to produce expected output waveforms. Some EDA tools (usually FPGA
vendor provided tools) support interactive simulation where there is no need to write the test bench
but inputs can be applied graphically. If the output waveforms do not match then the designer
should go for debugging in the HDL code of the design.

Once the functional simulation of a design is completed then the RTL code of the design is
synthesized into logic gates using EDA tool. In this process, EDA tool uses ‘technology library’
where pre-designed standard cells are available. User can optimize the speed and area of the logic
design. A gate level netlist is generated after synthesis.

Using the gate level netlist, timing simulation and analysis are performed to ensure that the design
has no timing violations. Then the synthesized logic gates are placed and routed. Most designs have
critical paths that are tight in terms of timing. These paths are routed first before routing other paths.
After place and routing is completed, post layout simulation and timing analysis are again
performed. In this step, net delay and other violations are measured accurately, and it is fixed if
necessary.

Once post-layout simulation is completed then logic verification of the overall design is again
performed based on the real layout data. If there is any mismatch, it is fixed. When all the above
steps are performed, the design proceeds to Tape-out.

12
Hardware Realization of a Design using FPGA Device: Design of a digital system can be
realized into hardware using FPGA device. It reduces the time to market, reduces the cost and offers
the design flexibility. There are many FPGA vendors such as Altera, Xilinx, Latice, Philips etc. The
Vendors provide the EDA software for compilation, synthesis and simulation. Figure 1.4 shows
flow diagram of a design to be realized into FPGA hardware. In this case, the first three steps are
same as shown in Figure 1.3. Once the sub-modules of a design are identified, each of the modules
is designed, compiled and synthesized using FPGA vendor provided software. Then functional
simulation is performed upon each module. The correct simulation results ensure the proper
functionality of a design. Once the simulation results of all the sub-modules are as desired then they
are integrated and simulated again. Then for hardware realization, suitable FPGA device is selected
for the design, inputs and outputs are assigned to specific pins of the FPGA. It is again compiled
and synthesized. After that timing simulation of the design is performed to ensure that the design
functions in real time. Then the design is downloaded into the FPGA.

13
Design Flow for FPGA Implementation

System Idea

System Level
Verification

Identifying
Sub-blocks

Design, compile and synthesis of


each block using HDL Code

Functional simulation
of each block

No
OK

No Yes

No more block
Yes

Integrate all the sub-blocks


and functional simulate

Not OK OK

Device selection and pin


assignment of the Design

Design, compile and synthesis of


the Design

Timing simulation of
the Design
Not OK

Download design into FPGA/PLD

Figure 1.4: Digital System Design and Implementation using FPGA

14
1.6 Summary

A brief overview of digital design is presented in this chapter. The reader can get information about
various aspects of Verilog HDL and modern approach of digital design from this chapter.

15
Chapter 2: Grammar of Verilog HDL

2.1 Introduction

Convention and Syntax used in Verilog HDL are very much similar to those in C Programming
language. Some of the commonly used syntax are described in this chapter to make the designer
familiar with Verilog HDL code within short time.

2.2 Basic Syntax and Operators of Verilog Language

Let us try to design an adder. Figure 2.1 (a) and (b) shows its symbolic diagram and schematic
design (which is a conventional approach) respectively (The IC, part number 7482, is available in
the market).

A[1:0] Sum[1:0]

B[1:0] ADDER Cout

Cin

Figure 2.1(a): Symbolic diagram of a 2-bit Full-Adder

Figure 2.1 (b) shows the complex logic diagram of a simple 2-bit adder. We can imagine how
difficult it is to design a simple adder circuit using conventional approach. Moreover, it is also too
difficult to do any change in the design if it is needed. On the other hand, Verilog HDL can
efficiently describe the above design using few lines code only. It is shown in Table 2.1.

16
7482
INPUT XOR
1 Cin VCC NOT
XOR
INPUT 13 3 OUTPUT
4 A2 VCC NOT 9 SUM1
8

INPUT 14 AND3
5 A1 VCC NOT

INPUT 15 17
6 B2 VCC NOT AND3 XOR

INPUT 16 OR2
7 B1 VCC NOT 18 25

AND3
11 23 OR2

OUTPUT
19 28 SUM2
*A[1:0]=A1, A2 AND3 27
*B[1:0]=B1, B2
*SUM[1:0]=SUM1, SUM2 20
AND3 XOR

OR2
21 26

AND3
24

22
AND2

29
AND2

30
AND6

OR3

34

XOR OR3
32
AND2 OUTPUT
37 Cout
35 36

31
AND3

33
AND3

38 XOR
AND6

40

39

Figure 2.1 (b): Schematic diagram of a 2-bit adder [12]

Table 2.1: Verilog design of a 2-bit Adder Circuit


module ADDER (A, B, Cin, SUM, Cout);
input [1:0] A, B;
input Cin;
output [1:0] SUM;
output Cout;
assign {Cout, SUM}=A+B+Cin;
endmodule

From the example as shown in Table 2.1, we see that Verilog code is a C-like programming
language and it is so much easy to design a circuit using Verilog HDL code. We just need to
describe the functionality of the circuit using few lines of code. However, it is essential to be
familiar with its different syntax and operators to write the code properly. The following sections
describe some of the basic Verilog syntax and operators.

17
2.3 Verilog Syntax

Identifiers: Identifiers are the names used to give for an object (such as input, output, module etc.
as shown in Table 2.1) in the design. It must start with a letter or underscore (a-z, A-Z, _ ).
Identifiers may contain alphabetic characters, numeric characters, the underscore, and the dollar
sign (a-z, A-Z, 0-9, _ $). Never use the Verilog keywords as identifier. Identifiers can be up to
1024 characters long. Examples of identifiers are: input In1, In2, Out_1, i386A.

Keywords: Verilog has a number of keywords or reserved words that cannot be used as identifiers
or any other purposes than it is intended for. All keywords are used in lower case in the Verilog
code. Examples of some of the important keywords are as shown in Table 2.2.

Table 2.2: Important Keywords with Explanation


Keywords Explanation
always To describe the behavior of a circuit i.e what the
circuit always do.
and To declare primitive AND gate
assign To assign a value from RHS to LHS
begin To start a block of statement
case To start a multiple choice
default To indicate unspecified states
else To indicate alternative in a conditional statement
end To terminate of a block
endcase To terminate of a case statement
endmodule To end the Verilog code of a module
if It allows the program to select an action based on
the condition is true
inout To declare bidirectional ports
input To declare input ports
integer To declare a variable as integer type
module To start Verilog coding of a design
nand To declare primitive NAND gate
negedge To declare falling edge of a clock or a signal
nor To declare primitive NOR gate

18
not To declare primitive NOT gate
or To declare primitive OR gate
output To declare output ports
parameter To declare a constant/constants
posedge To declare rising edge of a clock or a signal
real To declare a variable as real type
reg To declare output as reg in procedural assignment
wire To declare a net
xnor To declare primitive XNOR gate
xor To declare primitive XOR gate

Case Sensitivity: Verilog is a case sensitive language. Lower case letters are unique from upper
case letters. All Verilog keywords are lower case.

Comments: Comment is written for clarification while designing using Verilog code and can be
used anywhere in the program. Single line comments starts with ‘//’ and multiple line comment
starts with ‘/*’ and ends with ‘*/’.
Example:

Single line comment: //This is a single line comment.

Multiple line comment: /* This is a multiple line comment


where more than 1 line is needed*/

White Space: White spaces are: Blank spaces, Tabs, Carriage returns etc. It is used to make code
more readable. Verilog is not a white space-sensitive language except inside quotes. An example of
Verilog code is given below to show the usefulness of white space. Code_1 and Code_2 as shown
below are Verilog code for a same design.

//Code_1
module addbit(a,b,ci,sum,co);
input a,b,ci;output sum co;
wire a,b,ci,sum,co;endmodule

//Code_2
module addbit (a, b, ci, sum, co);
input a,b,ci;

19
output sum co;
endmodule

In the above two examples, white space used in code_2 makes it more readable and more clear than
code_1. However white space within quote will be counted by Verilog. If it is written in Verilog to
display: (“Show Me”) then the space between show and me will be counted.

Logic Values: Logic values appearing on the signal lines, normally take two levels:

1 signifies high or true

0 signifies low or false

However for logic simulation, we need two more values to represent unknown values and high
impedance state. In Verilog HDL, X represents an unknown or uninitialized value. This corresponds
to don’t care condition in the logic circuits. Z represents a high impedance state. This is a state
when a signal line is tri-stated or left floating.

Numbers: Verilog allows a wide range of numbers to be used while writing Verilog HDL program.
A designer may use real, integer, unsigned, signed numbers etc. The type of the number needs to be
declared in Verilog program in the following way:
integer a, b, c // Here a, b, c are declared as integer
real a, b, c // Here a, b, c are declared as real
Example of integer number is 2, 20, 200, -240 etc. Example of real number is 4.3, 4.3e2, -4.3e2 etc.
Usually number is taken as 32 bits wide. The integer number 1 will be represented as
00000000000000000000000000000001. In Verilog, numbers can be represented in different
base/radix (decimal, binary etc). The default base is decimal. Table 2.3 shows different radix
specifiers while Table 2.4 shows examples of representation of numbers using different radix.

Table 2.3: Radix Specifiers


Radix Mark Radix
‘d ‘D Decimal (default)
‘b ‘B Binary
‘h ‘H Hexadecimal
‘o ‘O Octal

20
Table 2.4: Example of Different Number Representation Styles and Their Values
Number Values Comments
8'hAA 10101010 Hex representation; 8-bit
6'b100011 100011 Binary representation; 6-bit
Hex representation; it will be
'hF 00000000000000000000000000001111
considered as 32-bit
Hex representation; Lower 6-
6'hCA 001010
bit will be considered
6'hA 001010 6-bit hex representation
16'bZ ZZZZZZZZZZZZZZZZ 16-bit binary representation
8'bX XXXXXXXX 8-bit binary representation
8’hZX ZZZZXXXX 8-bit hex representation
8’h0Z 0000ZZZZ 8-bit hex representation
8’b0 00000000 8-bit binary representation
8’b1 00000001 8-bit binary representation
8’hZ1 ZZZZ0001 8-bit hex representation
9’d112 or 3 digit decimal number which
Decimal Number: 112
9’D112 is 9-bit

2.4 Verilog Operators

Verilog has a number of operators like C. A list of important Verilog operators is presented in Table
2.5.

Table 2.5: List of Important Verilog Operators

OPs Name Definition


{,} Concatenation It joins two operand
Example: X={A,B}; if A=2b’11; B=2b’00
then X=4b’1100
+ Addition Sums two operand;
Example: X=A + B
- Subtraction Difference between two operands
Example: X=A - B
* Multiplication Multiply two operands
Example: X=A*B
/ Division Divide two operands
Example: X=A/B
> Greater than Determine relative values
Example: if (A>B) -----

21
>= Greater than or equal Determine relative values
Example: if (A>=B) -----
< Less than Determine relative values
Example: if (A<B)
<= Less than or equa Determine relative values
Example: if (A<=B)
! Logical negation Converts a Zero value into 1 and vice versa
Example: if(!A)
&& Logical AND ANDs two logic values
Example: if(A&&B)
|| Logical OR ORs two logic values
Example: if(A||B)
== Logical equality Compares two values for equality
Example: if (A= =B)
!= Logical inequality Compares two values for inequality
if (A!=B)
~ Bitwise negation produces the bitwise NOT of two operands
Example: X=~A
Bitwise AND produces the bitwise AND of two operands
&
Example: X=A & B
~& Bitwise NAND produces the bitwise NAND of two operands
Example: X=A~&B
| Bitwise OR produces the bitwise OR of two operands
Example: X=A | B
~| Bitwise NOR produces the bitwise NOR of two operands
Example: X=A ~| B
^ Bitwise XOR produces the bitwise XOR of two operands
Example: X=A ^ B
~^ Bitwise XNOR produces the bitwise XNOR of two operands
Example: X=A ~^ B
<< Leftshift Shift the operand to the left by n bits
Example: X=A<<2
>> Rightshift Shift the operand to the Right by n bits
Example: X=A>>2

2.5 Summary

Important syntax and operators of Verilog HDL has been described in this chapter. At the end of
this chapter the reader can start designing a digital system using Verilog HDL.

22
Chapter 3: Structural Verilog Coding

3.1 Introduction

This chapter briefly discusses on how to write structural Verilog code for a digital circuit. Basically
structural Verilog HDL code represents the connectivity among different components of a design.
Attempts have been made to explain structural coding using several examples.

3.2 Primitives in Structural Coding

Verilog has a set of twenty-six built-in primitives representing gates and switches. Table 3.1 shows
a list of primitives.

Table 3.1: List of Primitives

Logic Gates

and or xor nand nor xnor

Buffers

buf bufif0 bufif1 not notif0 notif1

pulldown pullup

Transistors

nmos pmos cmos rnmos rpmos rcmos

tran tranif0 tranif1 rtran rtranif0 rtranif1

3.3 Example of Structural Verilog Code of a Digital Circuit

Figure 3.1 shows an example circuit. Its structural code is given in Table 3.2.

23
Figure 3.1 shows a simple digital circuit. Its structural coding is given in Table 3.2.
OR2
4 A INPUT
VCC M AND2

INPUT OUTPUT
6 B VCC 2 5 D
1
g1
g3
NOT
INPUT
7 C VCC
3
N
g2
example_ckt

Figure 3.1: Example of a simple digital circuit

OR2
INPUT
4 A VCC
INPUT
6 B VCC 2

Table 3.2: Verilog Code of the Circuit as shown in Figure 3.1

module exampl_ckt (A, B, C, D);


input A, B, C;
output D;
wire M, N;
or g1 (M, A, B);
not g2 (N, C);
and g3 (D, M, N);
endmodule

In the example as shown in Table 3.2, module, input, output, wire, or, not, and, endmodule are
keywords and hence it is in lowercase. g1, g2, and g3 are instance name of the logic gates. It is
optional. To write structural Verilog code of a circuit:
• Start Verilog coding using the keyword module
• Give an arbitrary name for the circuit that we want to design (For the circuit as shown in Figure
3.1, we name it example_ckt)
• Write all the inputs and outputs within a first bracket. Sequence is not matter.
• Declare which are inputs (that we have listed in the first bracket). If bit width is more than 1 bit
then it needs to be shown.
• Declare which are outputs including number of bits
• Declare the internal signals of the circuit
• Instantiate the logic gates that we have used in the design (or, not, and)

24
• Specify the output and inputs of the logic gate within a first bracket (after the instantiation
name). Sequence is name of the output and then input

Figure 3.2 shows another example of a digital circuit (2/1 Mux). Its structural Verilog code is given
in Table 3.3.

AND2
A INPUT
VCC M
inst
OR2
g1
NOT OUTPUT Out
S INPUT
VCC
inst6 N P
inst7
AND2
g2 g4
B INPUT
VCC
inst5
g3

Figure 3.2: Example circuit of a 2/1 Mux

Table 3.3: Verilog Code of the Circuit as shown in Figure 3.2


module mux (A, B, S, Out);
input A, B, S;
output Out;
wire M, N, P;
and g1 (M, A, S);
not g2 (N, S);
and g3 (P, N, B);
or g4 (Out, M, P);
endmodule

Figure 3.3 shows another digital circuit. Its structural Verilog code is as presented in Table 3.4.

25
NOT
M NAND3
INPUT
20 A VCC OUTPUT
14 25 D0
19
g1
g5
INPUT
NOT
N NAND2
22 B VCC
15 OUTPUT
26 D1
g2 12
g6
INPUT
NOT
P NAND2
21 C VCC OUTPUT
17 27 D2
13
g3
g7
NOR2

NOT OUTPUT
INPUT 28 D3
23 E VCC 11
16
Q
g8
g4

Figure 3.3: Digital circuit

Table 3.4: Verilog Code of the Circuit as shown in Figure 3.3

module digital_ckt(A, B, C, E, D);


input A, B, C, E;
output [3:0] D;
wire M, N, P, Q;
not
g1 (M, A),
g2 (N, B),
g3 (P, C), One Declaration is for same
primitive logic gates
g4 (Q, E);
nand
g5 (D[0], M, N, Q),
g6 (D[1], N, Q),
g7 (D[2], P, Q);
nor g8 (D[3], P, Q);
endmodule

The example in Table 3.4 shows that it is allowed one declaration for the same primitive logic
gates.

26
3.4 Exercises related to Structural Verilog Code
Exercise-1: Write Structural Code for the circuit as shown in Figure 3.4.

A INPUT
VCC AND2

B INPUT
VCC
inst1

C INPUT
VCC
AND2 AND4

NOT
D INPUT
VCC OUTPUT Out
inst13 inst

NOT OR2
E INPUT inst4
VCC
inst12

F INPUT inst6
VCC

OR2
G INPUT
VCC

H INPUT inst7
VCC

Figure 3.4: A digital circuit for writing structural Verilog Code

Exercise-2: Draw the logic diagram from the Verilog Code as shown in Table 3.5.

Table 3.5: Draw logic diagram from the following Verilog Code
module ckt (A, B, C, D, E, F, G, H, Out);
input A, B, C, D, E, F, G, H;
output Out;
wire M, N, O,P, Q,R, S;
not (M, A);
and (N, M, B);
or (O, N, C);
not (P, E);
or (Q, D, P);
xor (R, Q, F);
nand (S, G, H);
nor(Out, O, R, S);
endmodule

27
3.5 Summary
A brief discussion on structural Verilog code is presented in this chapter. The reader will be able to
write structural Verilog code at the end of completing this chapter.

28
Chapter 4: Verilog Coding for Combinational Circuit

4.1 Introduction

This chapter explains on how to write RTL Verilog code for combinational circuit. Different types
of Verilog operators will be used to design the circuits. The objective of this chapter is to make the
reader familiar with the use of Verilog operators in designing combinational circuit.

4.2 RTL Verilog Coding of Digital Circuit

Structural Verilog code is not practicable for designing complex circuit. RTL Verilog code of a
digital design can be written in two ways. One is using continuous assignment structures. It is also
named as modeling digital circuit at data flow level. Another is using procedural assignment
structure.

4.2.1 RTL Coding using Continuous Assignment

Modeling of digital circuit using continuous assignment structure is higher level of abstraction than
structural Verilog coding. It is named as continuous assignment because the assignments written in
this procedure are evaluated continuously whereas in procedural assignment structure execution of a
statement waits for the clock or other parameters. The expression (in continuous assignment
structure) is evaluated whenever any of the operands changes. RTL coding using continuous
assignment is usually used to model combinational circuit which is more complex than can be
handled by structural modeling.

4.2.2 Examples and Exercises of RTL Verilog Coding using Continuous Assignment

Table 4.1 shows the design of combinational circuits (as indicated by Logic Equations 1, 2, 3)
using continuous assignment structure of Verilog code.

29
Example-1: Combinational Circuits

M = ( AB + CD )( A B + C D) − − − − − − − − − − − − −(1)
N = AB (CDE + D E ) − − − − − − − − − − − − − − − −(2)
P = (CD + BE )( A + D B ) − − − − − − − − − − − − − (3)

Table 4.1: Verilog Code of the Logic Equations (1, 2, 3)

module ckt (A, B, C, D,E, M, N, P);

input A, B, C, D,E;

output M, N, P;

assign M=((A &B) | (C & D)) &((~A & ~B) | (~C&~D));

assign N=(A & ~B) &((C&D&E) |(~D&~E));

assign P= ~(((C&D)|(B&E)) & (A|(~D&B)));

endmodule

The example of continuous assignment in RTL coding as in Table 4.1 shows that the declaration

‘module’, ‘input’, ‘output’ and ‘endmodule’ are same as they are used in structural Verilog coding.

The keyword ‘assign’ is used to write a continuous assignment. Different Verilog operators have

been used to write the continuous assignment.

Exercise-1: Write Verilog code as represented by the Logic Equations 4 and 5.

M = AB + BC + C D − − − − − − − − − (4)
N = A B + BC + C D − − − − − − − − − (5)

30
Example-2: A single bit adder

Figure 4.1 shows a single bit adder. It’s Verilog code using continuous assignment structure is
given in Table 4.2.

In1
Sum
In2 Adder_single
Cout
Cin

Figure 4.1: A single bit Adder

Table 4.2: Verilog Code of a Single Bit Adder

module adder_single (In1, In2, Cin, Sum, Cout);

input In1, In2, Cin;

output Sum, Cout;

assign {Cout, Sum}=In1+In2+Cin;

endmodule

Exercise-2: Design a 4-bit adder circuit using continuous assignment structure of Verilog code

Example-2: Design a 4-bit adder-subtractor circuit

Table 4.3 presents the design of a 4-bit adder-subtractor (shown in Figure 4.2) using continuous
assignment structure of Verilog code
S

A
Sum
B Add-sub
Cout
Cin

Figure 4.2: 4-bit Adder-Subtractor

31
Table 4.3: Verilog Code using continuous assignment structure for a 4-bit Adder-
Subtractor

module add_sub(Sum, Cout, A, B, sel);

input [3:0] A, B;

input sel; //sel=0 addition; sel=1 subtraction

output [3:0] Sum; //4 bit sum or diff

output Cout; //carry for add, comp of borrow for subtract

assign {Cout, Sum} = sel? (A+~B+4’b0001) : (A+B);//2’s complement of B=~B+0001

endmodule

Example -3: Design a 2/1 Mux circuit

Table 4.4 presents the design of a 2/1 Mux (shown in Figure 4.3) using continuous assignment
structure of Verilog code.
A

B Mux2/1 Y

S
Figure 4.3: A 2/1 Mux

Table 4.4: Verilog Code of a 2/1 Mux

module mux_21 (A, B, S, Y);

input A, B, S;

output Y;

assign Y = S ? A : B;

endmodule

In the above example, when the value of S will be 1, A will be assigned to Y otherwise B will be
assigned to Y.

32
4.2.3 RTL Verilog Code using Procedural Assignment

Structural Verilog coding and Verilog coding using continuous assignment structure are used to

design simple digital circuit. This approach is practical when the functional complexities are not

much (gate count within few hundred). With the increase of functional complexities, the above two

approaches are not a suitable approach. I designing complex digital circuit, procedural assignment

approach is used. In this approach, the functional behavior of the circuit is described using the

keyword ‘always’. Sensitivity list is used with the ‘always’ statement. Sensitivity list indicates

‘output is sensitive to what?’ It contains the list of specific inputs, which have effect on the outputs.

Whenever any event (change) occurs in any of the parameters in the sensitivity list, the always loop

will be executed.

4.2.4 Examples and Exercises of RTL Coding using Procedural Assignment

Examples and exercises of some standard combinational circuit are presented in this subsection.

Example 1: Design a 2/1 Mux

Table 4.5 presents the design of a 2/1 Mux (shown in Figure 4.4) using procedural assignment
structure of Verilog code.

B Mux2/1 Y

Figure 4.4: A 2/1 Mux

33
Table 4.5: Verilog Code of a 2/1 Mux

module mux_21P(A, B, S, Y);

input A, B, S;

output Y;

reg Y; //all the outputs need to be declared as register

always @(A or B or S) begin

if(S==0)
Y=A;

else
Y=B;

end

endmodule

The example of procedural assignment of RTL coding as given in Table 4.5 shows that the

declaration ‘module’, ‘input’, ‘output’ and ‘endmodule’ are same as used in structural Verilog

coding and in RTL coding using continuous assignment structure. It is important to remember that

all the outputs have to be declared as register using the keyword ‘reg’. The keyword ‘always’ is

used to describe the behavior of the circuit. Sensitivity list has been placed inside the first bracket.

The keyword ‘begin’ and ‘end’ indicates start and completion of the always block respectively.

However, the use of ‘begin’ and ‘end’ is optional. It is just to increase the clarity of the code. Within

the always block, it is described ‘what does the circuit always do: which is basically the behavior of

the circuit’.

34
Example-2: Design a 4/1 Mux

Table 4.7 presents the design of a 4/1 Mux (shown in Figure 4.6) using procedural assignment
structure of Verilog code.

B Mux4/1
C Y

2 bit
S[1:0]
Figure 4.6: A 2/1 Mux

Table 4.7: Verilog Code of a 4/1 Mux

module mux_41P(A, B, C, D, S, Y);

input A, B, C, D;

input [1:0] S;

output Y;

reg Y;

always @(A or B or C or D or S) begin

case (S)

0: Y=A;

1: Y=B;

2: Y=C;

3: Y=D;

default: Y=0;

endcase

end

endmodule

35
Example 3: Design a 2/4 Decoder.

Table 4.8 presents the design of a 2/4 Decoder (shown in Figure 4.7) using procedural assignment
structure.

Out1
A
2/4 Out2
B Decoder Out3
E Out4

Figure 4.7: 2/4 Decoder

Table 4.8: Verilog Code of a 2/4 Decoder

module dec2_4(E, A, B, Out);

input A, B, E;

output [3:0] Out;

reg [3:0] Out;

always @(A or B or E) begin

if(E==0) Out=0;

else begin

if (A==0 & B==0)Out=4'b0001;

else if (A==0 & B==1)Out=4'b0010;

else if (A==1 & B==0)Out=4'b0100;

else Out=4'b1000;

end

end

endmodule

The above design as mentioned in Example 3 can also be written in the following way as shown in
Table 4.9. However, we have declared ‘In’ as 2-bit input in replace of ‘A’ and ‘B’.

36
Table 4.9: Verilog Code of a 2/4 Decoder (Alternative Solution)

module dec2_4alt (E, In, Out);

input E;

input [1:0] In;

output [3:0]Out;

reg [3:0]Out;

always @(In or E) begin

if(~E)Out=4'b0000;

else begin

case (In)

0:Out=4'b0001;

1:Out=4'b0010;

2:Out=4'b0100;

3:Out=4'b1000;

endcase

end

end

endmodule

Example 4. Design a four input majority circuit where output is ‘1’ when three or more input
is ‘1’.

Table 4.10 presents the Verilog code of the majority circuit (shown in Figure 4.8). The circuit has
been simulated using Quartus II. The simulation result is shown in Figure 4.9.

Majority
In [3:0] Circuit Out

Figure 4.8: Four Input Majority Circuit

37
Table 4.10: Verilog Code of the Majority Circuit

module majority_ckt (E, In, Out);

input E;

input [3:0] In;

Output Out;

reg Out;

always @(In or E) begin

if(~E) Out=0;

else begin

case (In)

4b’0000:Out=0;

4b’0001:Out=0;

4b’0010:Out=0;

4b’0011:Out=0;

4b’0100:Out=0;

4b’0101:Out=0;

4b’0110:Out=0;

4b’0111:Out=1;

4b’1000:Out=0;

4b’1001:Out=0;

4b’1010:Out=0;

4b’1011:Out=1;

4b’1100:Out=0;

4b’1101:Out=0;

4b’1110:Out=1;

4b’1111:Out=1;

Default:Out=0;

38
endcase

end

end

endmodule

Figure 4.9: Simulation result of the majority circuit as shown in Figure 4.8

Exercise 1: Design a 5/1 Mux using case statement

Exercise 2: Design a Seven Segment Decoder as shown in Figure 4.10 where E and IN are
Enable Input and decoding input of the Seven Segment Decoder.

Seven
Segment Out [6:0]
In [2:0] Decoder
E

Figure 4.10: Seven Segment Decoder

Exercise 3: Design an adder-subtractor circuit using if else statement

39
4.3 Summary
A brief discussion on designing of combinational circuit using Verilog code is presented in this
chapter. Both the continuous assignment structure and procedural assignment structure are
discussed in this chapter. The reader will be able to design combinational circuit using Verilog code
at the end of completing this chapter.

40
Chapter 5: Verilog Coding for Sequential Circuit

5.1 Introduction

This chapter explains on how to write RTL Verilog code for sequential circuits (simple to complex).
Usually procedural assignment structure is used in designing sequential circuit using Verilog code.
The concept of designing Finite State Machine (FSM) is also introduced in this chapter.

5.2 RTL Coding of Sequential Logic Circuit

In this section, RTL Verilog coding for sequential circuit will be explained citing several examples.
Synchronous sequential circuit is either triggered by positive or negative edge of clock signal.

5.3 Examples of RTL Coding for Sequential Circuits

Example-1: Design a D-type Flip-Flop (D-FF) with Asynchronous Reset (Active Low)

Table 5.1 presents the design of a D-FF with asynchronous reset (shown in Figure 5.1) using
Verilog code. Active low reset and positive edge triggered clock input are considered in designing
the D-FF. Figure 5.2 shows the simulation results of the D-FF. It shows that the output ‘Q’ goes low
as soon as the ‘rst’ goes low.

D
Q
rst D-FF
clk

Figure 5.1: A D-FF with asynchronous reset

41
Table 5.1: Verilog Code of D-FF with asynchronous reset
module D_FF_asyn(D, clk, rst, Q);
input D, rst, clk;
output Q;
reg Q;
always @(posedge clk or negedge rst) begin
if(rst == 0) Q=0; //active low reset input; It can also be written as if(~rst) Q=0;
else Q=D;
end
endmodule

Output goes low

Figure 5.2: Simulation result of a D-FF with asynch. reset

The example as given in Table 5.1 shows that the declaration of ‘module’, ‘input’, ‘output’,
‘reg’, ‘always’, and ‘endmodule’ are same as used in RTL Verilog coding using procedural
assignment for combinational circuit. The positive edge and negative edge of the clock and other
signal (rst) are indicated using the keyword ‘posedge’ and ‘negedge’ respectively. Whenever any
event (change) occurs in the ‘rst’ or clock signal, the always loop will execute since it is included in
the sensitivity list. However if any event occurs in the ‘rst’ signal, the execution of the loop will not
wait for the clock edge and hence the FF is named as D-FF with asynchronous reset input.

Example-2: Design a D-FF with Synchronous Reset (active high)

Table 5.2 presents the design of a D-FF with synchronous reset (shown in Figure 5.3) using Verilog
code. Active high reset input is considered in designing the D-FF.

42
D
Q
rst D-FF
clk

Figure 5.3: A D-FF with synchronous reset

Table 5.2: Verilog Code of a D-FF with synchronous reset


module D_FF_syn (D, rst,clk, Q);
input D, rst, clk;
output Q;
reg Q;
always @(posedge clk) begin
if(rst == 1) Q=0; // Active high reset input; It can also be written as if(rst) Q=0;
else Q=D;
end
endmodule

In the example as shown in Table 5.2, the loop will be executed only when there is clock edge. Any
changes in the reset input do not have any effect on output until the clock edge occurs because the
reset input is not included in the sensitivity list. Hence it is named as D-FF with synchronous reset.
Figure 5.4 shows the simulation results of the D-FF with synchronous active high reset input. It
shows that although the ‘rst’ input is high, the output ‘Q’ goes low after the positive edge of the
clock appears.

Output goes low

Figure 5.4: Simulation result of a D-FF with synch. reset

43
Example-3: Design a T-FF with Synchronous Reset

Table 5.3 presents the design of a T-FF with synchronous reset (shown in Figure 5.5) using Verilog
code. Active high reset input is considered in designing the T-FF. Figure 5.6 shown the simulation
results of the T-FF.
T
Q
rst T-FF
clk

Figure 5.5: A T-FF with synchronous reset

Table 5.3: Verilog Code of a T-FF with synchronous reset


module T_FF_syn (T, clk, rst, Q);
input T, rst, clk;
output Q;
reg Q;
always @(posedge clk) begin
if(rst == 0) Q=0; //active low reset input
else begin
if (T) Q=~Q;
else Q=Q; // to hold the output
end
end
endmodule

Output toggles at clock edge

Figure 5.6: Simulation result of a T-FF with synch. reset

44
Exercise-1: Design the Logic Circuit as described by the Verilog Code as presented in Table
5.4
Table 5.4: Verilog Code of an unknown Logic Circuit
module ckt_cha5_unknown(A, B, C, clk, out);
input A, B, C,clk;
output out;
reg out;
wire P;
reg Q, R;
and (P,A,B);
always @(posedge clk) begin
Q=P;
R=C;
out=Q|R;
end
endmodule

Example-4: Design of a 4-bit binary up counter

Table 5.5 presents the design of a 4-bit up counter (shown in Figure 5.7) using Verilog code.
Positive edge clock input is considered in designing the counter.

4
Q
rst
Counter
clk

Figure 5.7: A 4-bit up counter

Table 5.5: Verilog Code of a 4-bit up counter


module count_4(rst, clk, Q);
input rst, clk;
output [3:0] Q;
reg [3:0] Q;
always @(posedge clk or negedge rst) begin
if (rst == 0) Q=0;

45
else Q=Q+1; //up counting
end
endmodule

Exercise-2: Design of an 8-bit down counter

Example-5: Design of a 4-bit binary up-down counter

Table 5.6 presents the design of a 4-bit binary up-down counter (shown in Figure 5.8) using Verilog
code. Positive edge clock input is considered in designing the counter.

4
Q
rst
Counter
clk

sel

Figure 5.8: A 4-bit binary up-down counter

Table 5.6: Verilog Code of a 4-bit Binary up-down counter


module count_4updn(rst, sel, clk, Q);
input rst, sel, clk;
output [3:0] Q;
reg [3:0] Q;
always @(posedge clk or negedge rst) begin
if (rst == 0) Q=0;
else begin
if (sel) Q=Q+1; //up counting
else Q=Q-1; //down counting
end
end
endmodule

46
Up Counting Down Counting

Figure 5.9: Simulation results of up-down counter

Example-6: Design of a counter having data loading facility

In some applications, it is necessary to have a counter to start counting from a particular value (not
from Zero). In that case the starting value needs to be loaded in the counter. Table 5.7 presents the
design of a 4-bit binary counter with data loading facility (shown in Figure 5.9 ) using Verilog code.
Positive edge clock input is considered in designing the counter. Simulation results of the counter
are shown in Figure 5.10.

rst
load 4
Counter Q
count
A 4

clk

Figure 5.9: A 4-bit binary counter with data loading facility

47
Table 5.7: Verilog Code of a 4-bit Binary with Data Loading Facility
module counter_load (count, load, clk, rst, A, Q);
input count, load, clk, rst;
input [3:0] A;
output [3:0] Q;
reg [3:0] Q;
always @(posedge clk or negedge rst) begin
if(~rst) Q=0;
else if (load) Q=A; //data laoding
else if (count) Q=Q+1; //up counting
else Q=Q;
end
endmodule

Counting starts from load value ‘A=5’

Figure 5.10: Simulation results of a counter having data loading facility

Exercise-3: Design of a 4-bit counter that has three control inputs for operations: up, down,
and load. The order of precedence is: load, up, and down as shown in Figure 5.11.

48
load
4
up Counter with Q
up, down and
down load
in 4

clk

Figure 5.11: A 4-bit binary counter with up, down and data loading facility

Example-8: Design a 4_BIT SHIFTREGISTER

Table 5.8 presents the design of a 4-bit shift register (shown in Figure 5.12) using Verilog code. In
designing shift register, sequence of assignment of stage value is very important. Improper
sequence may produce wrong simulation results. Positive edge clock and active high reset input are
considered in designing the shift register.

1st stage 2nd stage


3rd stage 4th stage

IN DFF
PRN O DFF
PRN N DFF
PRN M DFF
PRN OUT
IN INPUT D Q D Q D Q D Q OUTPUT Out
VCC

CLRN CLRN CLRN CLRN


inst3 inst inst1 inst2
clk
CLK INPUT
VCC

rst INPUT
VCC

rst Shift_4
Figure 5.12: A 4-bit shift register

49
Table 5.8: Verilog Code of a 4-bit Shift Register
module shift_4(IN, OUT, clk, rst);
input IN, clk, rst;
output OUT;
reg M, N, O, OUT;
always @(posedge clk or posedge rst) begin
if(rst) begin
OUT=0;
M=0;
N=0;
O=0;
end
else begin
OUT=M;
M=N;
N=O;
O=IN;
end
end
endmodule

Example-9: Design of a 4 bit ShiftReg using Alternative Approach

Table 5.9 presents an alternative approach of designing of a 4-bit shift register (shown in Figure
5.13) using Verilog code. Positive edge clock and active high reset input are considered in
designing the shift register. Figure 5.14 shows the simulation results of the shift register.

Dat_in DFF
PRN Dat_reg[3]
DFF
PRN Dat_reg[2]
DFF
PRN Dat_reg[1]
DFF
PRN
Dat_reg[0] Dat_out
IN INPUT OUTPUT Out
VCC D Q D Q D Q D Q

CLRN CLRN CLRN CLRN


inst3 inst inst1 inst2
clk
CLK INPUT
VCC

rst INPUT
VCC
rst Shift_4alt

Figure 5.13: A 4-bit shift register (alternative approach)

50
Table 5.9: Verilog Code of a 4-bit Shift Register using Alternative Approach
module shift_4alt(Dat_out, Dat_in, clk, rst);
input Dat_in, clk, rst;
output Dat_out;
reg [3:0] Dat_reg; /*Here the signal A, B, C, D, E as shown in the previous example is
declared as array Dat_reg[3:0]*/

assign Dat_out=Dat_reg[0];
always @(posedge clk) begin
if(rst) Dat_reg=0;
else Dat_reg={Dat_in, Dat_reg[3:1]};
end
endmodule

Value of input data ‘Dat_in=1’ Value of ‘Dat_reg’ increases with shift

Figure 5.14: Simulation results of a 4-bit shift register

Example-10: Design of a 4 bit Linear Feedback Shift Register (LFSR)

Table 5.10 presents the design of a 4-bit feedback shift register (shown in Figure 5.15) using
Verilog code. Positive edge clock and active high reset input are considered in designing the shift
register.

51
DFF DFF DFF DFF Dat_reg[0] Dat_out
PRN Dat_reg[3] PRN Dat_reg[2] PRN Dat_reg[1] PRN
D Q D Q D Q D Q OUTPUT Out

CLRN CLRN CLRN CLRN


inst3 inst inst1 inst2
clk
CLK INPUT
VCC

rst INPUT
VCC

rst LFSR_4

SEL Seed
kk INPUT
VCC

Figure 5.15: A 4-bit feedback shift register

Table 5.10: Verilog Code of a 4-bit Feedback Shift Register


module LFSR_4(clk, sel, seed, rst, Dat_out);
input clk, sel, rst;
input [3:0] seed; //seed is initial value of LFSR
output out;
reg out;
reg [3:0] Dat_reg;
always @(posedge clk) begin
if(rst) Dat_reg=0; // rst is active high
else if(sel) Dat_reg=seed; //sel (control input) to initialize the LFSR to a given value
else Dat_reg[3:0]={Dat_reg[0],Dat_reg[3:1]};
out=Dat_reg[0];
end
endmodule

Example-11: Design of a RAM

Table 5.11 presents the design of a 128X8 bit Random Access Memory (RAM) (shown in Figure
5.16) using Verilog code. Positive edge clock input is considered in designing the RAM. Figure
5.17 shows the simulation results of the RAM.

52
we 8
datout
clk RAM

add 7

datin 8

Figure 5.16: Random Access Memory (RAM)

Table 5.11: Verilog Code of a 128X8-bit RAM


module ram_8bit (we,re, clk, add, datin, datout);
input [6:0] add;
input we, re, clk;
input [7:0] datin;
output[7:0] datout;
reg [7:0] datout;
reg [7:0] mem [127:0];
always @(posedge clk) begin
if (we) mem[add] <= datin; //data write
else if (re)datout = mem[add]; //data read
else datout=datout;
end
endmodule

Data write in memory Data read from memory

Figure 5.17: Simulation results of RAM

53
Example-12: Verilog code of a Circuit having Bi-directional Input/output Ports

Figure 5.18 shows an example circuit with bi-directional input output. In this circuit, when rw=1
then the data in the ‘W [7:0]’will pass to ‘din[7:0]’ which is the input of a latch. After that when the
latch will be enabled then it will pass to the output of the latch. Here W acts as an input. During this
time the signal ‘Sig_dat[7:0]’ will be in high impedance state so that the data in ‘Sigdat [7:0]’ does
not conflict with the data in ‘din[7:0]’. Again when rw=0 then the data in ‘Sig [7:0]’ will pass to W
[7:0]. Here W [7:0] acts as output. Hence W is overall is a bi-directional input output. Table 5.12
presents the design of an example circuit having bi-directional input and output (shown in Figure
5.18) using Verilog code.

Sig[7:0]

rw Tristate
Buffer
en
Sig_dat[7:0]

Latch Data[7:0]
din[7:0]

Bi-directional
buffer W[7:0]

Figure 5.18: An Example Circuit with bi-directional input/output

Table 5.12: Verilog Code of Circuit with Bi-directional Input/Output


module bidir_sys (sig, rw, w, en, data);
input rw, en;
input [7:0] sig;
output [7:0]data;
inout [7:0] w;
reg [7:0] sig_dat, din,data;
reg [7:0] w;

always @(rw or w) begin

if(rw)begin
sig_dat=8'bZ;
din=w;
end
else begin
sig_dat=sig;
54
w=sig_dat;
end
if (en) data=din;
end
endmodule

5.4 Interconnection between Modules

Modules developed using Verilog code can be interconnected using the following ways. Two
techniques have been described below:

Using Graphical Editor/Schematic Editor: It is applicable for a design having not many modules.
In this technique, the symbol of the modules (developed using Verilog HDL) is created and saved in
the work directory. Then Schematic editor is opened and the symbol of the modules is invoked
there. Then interconnections are made between the modules in the schematic editor (connectors,
wires are provided there). It is shown in Figure 5.19. Here we want to design a 4-bit decoded
counter where a 4-bit counter has to be connected with a 4/16 decoder. In Figure 5.19, the symbol
of the counter and decoder has been generated using their respective Verilog HDL code and then
they have been connected. This technique is not suitable for complex circuits having many modules.

Figure 5.13(a): Showing symbol of modules in the Schematic Editor

Figure 5.19(b): Showing connections of modules in the Schematic Editor

55
Using Verilog Code: Module interconnects can also be performed using Verilog code. It is a better
approach for any complex design. In this technique, Verilog code of different modules of a complex
design is written in the same working directory. Then Verilog code for the full chip is written where
instantiation and integration of different modules are performed using Verilog code. To explain this,
again we assume that we want to design a 4-bit decoded counter as shown in Figure 5.20.

rst en

RST rst
EN en 4-bit 4/16 out OUT
Counter Q_C Decoder
CLK clk

m_counter m_decoder

dec_coun

Figure 5.20: Decoded Counter

For designing a decoded counter as shown in Figure 5.20, Verilog code for a 4-bit counter and a
4/16 decoder are written in separate files. Each design is simulated to ensure its proper
functionality. Once the desired simulation result is achieved, Verilog code is written in another file
(but in the same working directory) for the decoded counter. Verilog code for the counter, for the
decoder, and for the decoded counter is shown in Table 5.13, Table 5.14 and Table 5.15
respectively.

Table 5.13: Verilog Code of a 4-bit Counter


module counter_4 (clk, rst, en, Q);
input clk, rst, en;
output [3:0] Q;
reg [3:0] Q;
always @(posedge clk or negedge rst) begin
if(~rst) Q=0;
else if (en) Q=Q+1;
else Q=Q;
end
endmodule

56
Table 5.14: Verilog Code of 4/16 Decoder
module decoder(rst, en, in, out);
input rst, en;
input [3:0] in;
output [15:0] out;
reg [15:0] out;
always @( rst or en) begin
if(~rst)out=0;
else if (en) begin
case (in)
4'b0000: out=16'b0000000000000001;
4'b0001: out=16'b0000000000000010;
4'b0010: out=16'b0000000000000100;
4'b0011: out=16'b0000000000001000;
4'b0100: out=16'b0000000000010000;
4'b0101: out=16'b0000000000100000;
4'b0110: out=16'b0000000001000000;
4'b0111: out=16'b0000000010000000;
4'b1000: out=16'b0000000100000000;
4'b1001: out=16'b0000001000000000;
4'b1010: out=16'b0000010000000000;
4'b1011: out=16'b0000100000000000;
4'b1100: out=16'b0001000000000000;
4'b1101: out=16'b0010000000000000;
4'b1110: out=16'b0100000000000000;
4'b1111: out=16'b1000000000000000;
endcase
end
else out=out;
end
endmodule

57
Table 5.15: Verilog Code of the Decoded-Counter
module dec_coun (RST, EN, CLK, OUT);

input RST, EN, CLK;

output [15:0] OUT;

wire [3:0] Q_C; Connecting wire between the two modules

module name of the


4-bit counter same name as
module counter_4
counter_4 m_counter (

.clk(CLK), same name as module


arbitrary instance dec_coun
name .rst(RST),

.en(EN),

.Q(Q_C),

);

decoder m_decoder (

.in(Q_C),

.out(OUT),

.rst(RST),

.en(EN),

);

endmodule

5.5 Finite State Machine Design

State machine or Finite State Machine (FSM), is a computing device designed with some
operational states required to solve a specific problem. It is a sequential circuit that are minimized,
specialized and optimized for an application. For example, chips in audio, video and imaging
controllers are often designed as state machines, because they can provide faster performance at
lower cost than a general-purpose CPU. Automatic ticket dispensing machines are another example

58
of state machine. There are countless special-purpose devices built using state machines. FSMs are
often used in real-time systems to control devices such as toaster ovens, elevators, nuclear power
plants, JOCKEY etc. FSM is represented using state diagram. Figure 5.21 shows an example (just
to show only) of state diagram of an FSM used for transmitter module of a Universal Asynchronous
Receiver and Transmitter (UART).

reset event_count event_count


start_pulse !=16 !=16
==0
start_pulse
t_idle ==1 t_start t_wait t_shift

bit_count==
word_length

t_stop

event_count
!=16
Figure 5.21: State diagram of the transmitter module of UART [12]

Finite state machine can be modeled in the following two ways as described below:

Mealy Machine: In mealy machine, outputs of the FSM are function of both the present states and
inputs of the circuit. i.e Output = F(inputs, present states). Example of Mealy model circuit is shown
in Figure 5.22. In this figure Out=F(X,Q) where X and Q indicate input and present state of the
circuit.

OR2
NOT OUTPUT Out

inst3 Q inst2
AND2 DFF
PRN
INPUT D Q
X
VCC
inst1

CLRN
inst
CLK INPUT
VCC

Figure 5.22: Mealy machine

59
Moore Machine: In Moore machine, outputs of the FSM are function of present states of the
sequential circuit only. i.e Output = F (present state). Example of sequential circuit representing a
Moore machine is shown in Figure 5.23. In this figure Out=F(Q1, Q2) where Q1 and Q2 indicate
present state of the circuit.

XOR DFF
X INPUT
VCC
D
PRN
Q
Q1 NAND2
OUTPUT Out
inst2
inst3
CLRN
inst

DFF
PRN Q2
D Q

CLK INPUT
VCC
CLRN
inst1

Figure 5.23: Moore Machine

The models selected will influence a design but there are no general indications as to which model
is better. Choice of a model depends on the application, and personal preferences of a designer. In
practice, mixed models are often used for complex application.

To design the finite state machine using the conventional approach, the following time consuming
steps are involved: (i) draw state diagram, (ii) draw state table, (iii) state reduction (iv) K-map to
find the logic equations (v) draw the logic circuit from the logic equations. However, to design the
FSM using Verilog HDL, the designer only need to draw state diagram and then can start design.
Example-13 presents the design problem of an FSM. It has been designed using conventional
approach and then the same FSM has been designed using Verilog HDL to show the ease of design
in this approach.

Example-13: Design an FSM (as shown in Figure 5.24) having one input and one output. It should

be able to recognize three consecutive one (111) (Overlapping sequence is considered and also

detected by the FSM.) Figure 5.24 (a) shows the block diagram of the FSM. X is the input and Z is

the output of the FSM. The functional behavior of the FSM has been explained using the example

as shown in Figure 5.24 (b).

60
X X = 010011011111010
FSM Z
clk
Z = 000000000111000
Figure 5.24 (a): Symbol of FSM (FSM_mealy) Figure 5.24 (b): Example showing the
behavior of the FSM

Design using Conventional Approach: The design of the FSM (as shown in Figure 5.24) using
conventional technique is a big job. To design it this approach, the designer has to follow the steps
as below:
• Draw state diagram,
• Draw state table
• Draw Binary coded state Table
• Find the K-map
• Find the Logic Equations
• Draw the Logic Circuit

To design the FSM, three states are required. Figure 5.25 and 5.26 shows the state diagram and
state table of the FSM respectively. Here S0, S1, S2 are the required states. Assume that D-FF
will be used to design the FSM. Since there are three states, two D-FFs are required. Again
assume S0=00, S1=01, S2=11; We assume that S3 is the unused state where S3=10. If the FSM
goes to S3 due to any reason then the FSM will be forced to comeback to S0 (initial state) with
Zero output.

1/0 1/0

Figure 5.25: State Diagram of the FSM as shown in Figure 5.24

61
Present State Input

y1y2 X
Next state and Output
S0 S0/0 S1/0

S1 S0/0 S2/0

S2 S0/0 S2/1

5.26: State Table of the FSM

To design the FSM, the symbolic representation of the states needs to be coded into binary as
shown in Figure 5.27.

Present State Input

y1y2 X
Next state and Output
00 00/0 01/0

01 00/0 11/0

11 00/0 11/1

5.27: Binary Coded State Table of the FSM

Figure 5.28 shows the block representation of the FSM as shown in Figure 5.24. We need to find
out the logic equation of Z, D1 and D2.

X
Combinational Z
Logic Block -3
Combinational D-FF_1 y1
Logic Block-1
D1

y2
Combinational D-FF_2
Logic Block-2
D2
Figure 5.28: Block representation of the FSM

62
To find the logic equation of the Output of combinational logic block-3 (Z), combinational logic
block-1 (D1), combinational logic block-2 (D2), K-map has been drawn as shown in Figure 5.29,
Figure 5.30 and Figure 5.31 respectively.

y1y2 X y1y2 X y1y2 X

00 0 0 00 0 0 00 0 10
1 11
01 0 0 01 0 01 0
1 1 1

11 0 11 0 11 0

5.29: K-map to find output Z 5.30: K-map to find output D1 5.31: K-map to find output D2

From the above K-maps, we get the following logic equations:

Z=Xy1y2

D1=Xy2

D 2 = X y1 + Xy 2

From the above logic equations we can draw the logic circuits of the FSM as shown in Figure 5.32.

AND3
X
Z
AND2
X inst4
DFF
y2 PRN y1
inst2 D Q

CLRN
inst

AND2
X
y2 inst3
OR2 DFF
PRN
D Q
X AND2
inst5
y2
NOT
y1 inst7 inst6 inst1
CLRN

CLK
Figure 5.32: Logic Circuit of the FSM

63
FSM Design using HDL based Approach: It is seen that all the above steps need a lot of time and
can cause errors easily. However, to design the FSM using Verilog HDL, the designer has to draw
state diagram of the FSM and then he can start designing of FSM. Table 5.16 shows the Verilog
code of the FSM. To design the FSM, mealy approach has been followed.

64
Table 5.16: Verilog Code of the FSM as shown in Figure 5.24
module FSM_mealy1 (X, CLK, RST, Z); // RST is the reset input of the FSM
input RST, X, CLK;
output Z;
reg Z;
reg [1:0] presentstate, nextstate;

parameter [1:0] S0=2’b00,


S1=2’b01,
S2=2’b11,
S3=2’b10;

always @(posedge CLK or posedge RST) begin


if(RST) begin
presentstate=S0;
end
else
presentstate=nextstate;
end

always @(X or presentstate) begin


case (presentstate)
S0: begin
if (X== 0) begin
Z=0;
nextstate=S0;
end
else begin
Z=0;
nextstate=S1;
end
end

S1: begin
if (X== 0) begin
Z=0;
nextstate=S0;
end
else begin
Z=0;
nextstate=S2;
end
end

S2: begin
if (X== 0) begin
Z=0;
nextstate=S0;
end
else begin
Z=0;

65
Example -14: Design the same FSM as mentioned in Example-13 except the overlapping is not

considered. The functional behavior is shown in Figure 5.33 (b).

X X = 010011011111010
FSM Z
clk
Z = 000000000100000
Figure 5.33 (b): Example showing the
Figure 5.33 (a): Symbol of FSM (FSM_mealy2) behavior of the FSM

Figure 5.34 shows the state diagram of the FSM as shown in Figure 5.33. Verilog coding can be
done in the same way as shown in Table 5.16.

1/0 1/0

Figure 5.34: State diagram of the FSM as shown in Figure 5.33

Example-15: Design the same FSM as mentioned in Example-13 using Moore model.

Figure 5.35 shows the block diagram of the FSM and it’s functional behavior. State diagram of the

FSM is shown in Figure 5.36. The Verilog code of the FSM is given in Table 5.17.

66
X
FSM Z X = 010011011111010
clk
Z = 000000000010000
Figure 5.33 (b): Example showing the
Figure 5.35 (a): Symbol of FSM behavior of the FSM

1 1 1

Figure 5.36: State Diagram of the FSM (Moore model)

67
Table 5.17: Verilog Code of the FSM as stated in Example-15
module FSM_moore (RST, X, CLK, Z);
input RST, X, CLK;
output Z;
reg Z;
reg [1:0] presentstate, nextstate;

parameter [1:0] S0=2’b00,


S1=2’b01,
S2=2’b11,
S3=2’b11;
always @(posedge CLK or posedge RST) begin
if (RST) presentstate=S0;
else presentstate=nextstate;
end
always @(presentstate) begin
case (presentstate)
S0: begin
Z=0;
if (X== 0) nextstate=S0;
else nextstate=S1;
end
S1: begin
Z=0;
if (X== 0) nextstate=S0;
else nextstate=S2;
end
S2: begin
Z=0;
if (X== 0) nextstate=S0;
else nextstate=S3;
end
S3: begin
Z=1;
nextstate=S0;

68
5.6 Summary

A brief discussion on designing of sequential circuit using Verilog HDL is presented in this chapter.
It presents a number of examples on designing simple to complex sequential circuits. The reader
will be able to design any sequential circuits using Verilog code at the end of completing this
chapter.

69
Chapter 6: Efficient Verilog HDL Coding and Verification

6.1 Introduction

It is not enough for a designer to be able to write Verilog code for a complex digital design. The
code should produce optimal synthesis result. At the same time, the design should be simulated to
ensure its proper functionality. In this chapter, some tips are discussed as a guideline for efficient
coding.

6.2 Good Coding Style

There is a proverb “garbage in, garbage out”. Good coding style is necessary for efficient
optimization during synthesis. It will also help the designer to avoid many unseen hassles and make
life easy in writing Verilog HDL code for a complex design. Some guidelines are described below
for synthesis friendly coding.

6.2.1 Naming of Signals

Well-defined and constant naming convention is extremely important to avoid a lot of unseen
problems in the later stages of a design especially during the integration of different modules of a
complex design. If a proper naming convention is followed, then it becomes easier to connect
different modules with each other. For example, Figure 6.1 shows the connection between two
modules where the following rules can be followed.

rst_in scanin_M2N
data_out [7:0]
Module N
Module M
data_in [7:0] sout_N2M

Figure 6.1: Showing naming of input, output and signal of a full chip

1. While naming any input or output or any signal, it should resembles with its functionality.
For example, ‘rst_in’ can be used to name a reset input cs_in for chip select input, out_dat
for data output etc.
2. Input name can be the name of the input with underscore ‘in’ such as rst_in

70
3. Output name can be the name of the output with underscore ‘out’ such as out_dat
4. Intermediate signal can be name of the signal with underscore source module to destination
module such as scanin_M2N, sout_N2M

6.2.2 Design Partitioning

It is a standard practice to partition a complex design into different modules based on their specific
functionality and features. However, the designer needs to be cautious to make partitioning because
good partitioning brings advantages such as ease of manageability over the modules and good
synthesis optimization. At the same time bad partitioning brings disadvantages such as difficulties
in manageability of the modules, congestion on routing and increasing the die-size [5]. Modules that
are too large will be difficult to be coded as well as synthesized to obtain optimal synthesis results.
Modules that are too small will not be able to yield good synthesis result. Moreover partitioning
into many modules creates more signals for interfacing. Acceptable module size, that is manageable
and allows good synthesis optimization, from coding point of view, would be around 5,000 to
15,000 gate count.

6.2.3 Sensitivity List

The designer should carefully choose the parameters in the sensitivity list otherwise the simulation
result might be inaccurate. Importance of sensitivity list can be explained with the following
examples. Verilog code of a 4/16 decoder and its simulation result are given as below:

/*Verilog code of a 4/16 decoder with inaccurate sensitivity list. Here the always loop will
execute whenever there is any edge in the ‘rst’ input or in ‘en’ input.*/

module decoder(rst, en, in, out);


input rst, en;
input [3:0] in;
output [15:0] out;
reg [15:0] out;
always @(negedge rst or posedge en) begin
if(~rst)out=0;
else if (en) begin
71
case (in)
4'b0000: out=16'b0000000000000001;
4'b0001: out=16'b0000000000000010;
4'b0010: out=16'b0000000000000100;
4'b0011: out=16'b0000000000001000;
4'b0100: out=16'b0000000000010000;
4'b0101: out=16'b0000000000100000;
4'b0110: out=16'b0000000001000000;
4'b0111: out=16'b0000000010000000;
4'b1000: out=16'b0000000100000000;
4'b1001: out=16'b0000001000000000;
4'b1010: out=16'b0000010000000000;
4'b1011: out=16'b0000100000000000;
4'b1100: out=16'b0001000000000000;
4'b1101: out=16'b0010000000000000;
4'b1110: out=16'b0100000000000000;
4'b1111: out=16'b1000000000000000;
endcase
end
else out=out;
end
endmodule

Figure 6.2: Inaccurate Simulation Result of a 4/16 decoder

In the simulation result as shown in Figure 6.2, it is shown that output of the decoder is not changed
with the change of the input. It is due to the fact that sensitivity list is not accurately declared
(output will change with the edge of the input).

72
/*Verilog code of a 4/16 decoder with accurate sensitivity list. Here the always loop will
execute whenever any changes input: rst or en*/

module decoder(rst, en, in, out);


input rst, en;
input [3:0] in;
output [15:0] out;
reg [15:0] out;
always @( rst or en) begin
if(~rst)out=0;
else if (en) begin
case (in)
4'b0000: out=16'b0000000000000001;
4'b0001: out=16'b0000000000000010;
4'b0010: out=16'b0000000000000100;
4'b0011: out=16'b0000000000001000;
4'b0100: out=16'b0000000000010000;
4'b0101: out=16'b0000000000100000;
4'b0110: out=16'b0000000001000000;
4'b0111: out=16'b0000000010000000;
4'b1000: out=16'b0000000100000000;
4'b1001: out=16'b0000001000000000;
4'b1010: out=16'b0000010000000000;
4'b1011: out=16'b0000100000000000;
4'b1100: out=16'b0001000000000000;
4'b1101: out=16'b0010000000000000;
4'b1110: out=16'b0100000000000000;
4'b1111: out=16'b1000000000000000;
endcase
end
else out=out;
end
endmodule

73
Figure 6.3: Accurate Simulation Result of a 4/16 decoder

In the simulation result as shown in Figure 6.3, it is shown that output of the decoder is changed
with the change of the input. It is due to the fact that no edge of the input parameter is declared in
the sensitivity list.

6.2.4 Blocking and Nonblocking Assignment

Two types of procedural assignment are usually used in Verilog coding: (i) blocking assignment (ii)
nonblocking assignment. It is important to understand the scheduling of Verilog blocking and
nonblocking assignment to avoid the mismatch between simulation and synthesis results, and from
the Verilog race condition (Verilog race condition occurs when two or more statements that are
scheduled to execute in the same simulation time-step, would give different results when the order
of statement execution is changed).

The blocking assignment operator is represented by equal sign ("="). A blocking assignment gets its
name because a blocking assignment must evaluate the RHS (Right Hand Side) arguments and
complete the assignment without interruption from any other Verilog statement. The assignment is
named as blocking assignment because it blocks other assignments until the current assignment has
evaluated completely.

74
The nonblocking assignment operator is represented by the less-than-or-equal-to operator ("<="). A
nonblocking assignment gets its name because it does not block other Verilog statements from
being evaluated. From the user perspective, the execution of the nonblocking assignments occurs in
parallel. Nonblocking assignments are only made to register data types and are therefore only
permitted inside of procedural blocks such as always blocks. Nonblocking assignments are not
permitted in continuous assignments.

To save the designer from the death by Verilog, Some important guidelines for using blocking and
nonblocking assignment are given below [13]:
 When modeling sequential logic, use nonblocking assignments.
 When modeling latches, use nonblocking assignments.
 When modeling combinational logic with an always block, use blocking
assignments.
 When modeling both sequential and combinational logic within the same always
block, use nonblocking assignments.
 Do not mix blocking and nonblocking assignments in the same always block.
 Do not make assignments to the same variable from more than one always block.

Importance of proper use of blocking and nonblocking assignment is explained with the following

examples.

Example 1 [13]: This example shows how the different ordering of blocking assignments causes
problems in designing sequential circuit. Figure 6.4 shows a block diagram for a shift register.

Figure 6.4: 3-bit shift register

75
If the Verilog code to design the shift register is written as shown in Table 6.1 then the use of
blocking assignment causes the value of ‘d’ to be placed on the output of every register on each
clock cycle and end synthesis result will produce a single register as shown in Figure 6.5. So the
shift register that we want to design as shown in Figure 6.4 will not be realized. However by careful
reordering the assignment as shown in Table 6.2, the shift register as shown in Figure 6.4 can be
realized.

Table 6.1: Wrong Verilog code for the shift register as shown in Figure 6.4
module shifreg_w (q3, d, clk);
output q3;
input d, clk;
reg q3, q2, q1;
always @(posedge clk) begin
q1 = d;
q2 = q1;
q3 = q2;
end

endmodule

Figure 6.5: Showing synthesized circuit from the Verilog code as shown in Table 6.1

Table 6.2: Accurate Verilog code for the shift register as shown in Figure 6.4
module shifreg_R (q3, d, clk);
output q3;
input d, clk;
reg q3, q2, q1;

76
always @(posedge clk) begin
q3 = q2;
q2 = q1;
q1 = d;
end

endmodule

If the Verilog code for the shift register as shown in Figure 6.4 is rewritten using the nonblocking
assignment as shown in Table 6.3 then whatever ordering the assignment is, it will always produce
the accurate and desired circuit.

Table 6.3: Verilog code for the shift register as shown in Figure 6.4
module shifreg_R1 (q3, d, clk);
output q3;
input d;
input clk;
reg q3, q2, q1;
always @(posedge clk) begin
q1 <= d;
q2 <= q1;
q3 <= q2;
end
endmodule

Example 2 [13]: This example shows how blocking assignment causes Verilog race condition. A
problem with blocking assignments occurs when the RHS variable of one assignment in one
procedural block is also the LHS variable of another assignment in another procedural block and
both equations are scheduled to execute in the same simulation time step, such as on the same clock
edge. If blocking assignments are not properly ordered, a race condition can occur. Verilog code as
shown in Table 6.4 explains this point.

77
Table 6.4: Verilog code for the shift register as shown in Figure 6.4
module Race_1 (y1, y2, clk, rst);
output y1, y2;
input clk, rst;
reg y1, y2;
always @(posedge clk or posedge rst) begin
if (rst) y1 = 0; // reset
else y1 = y2;
end
always @(posedge clk or posedge rst) begin
if (rst) y2 = 1; // preset
else y2 = y1;
end
endmodule

According to the IEEE Verilog Standard, the two always blocks can be scheduled in any order. In
the example as presented in Table 6.4, if the first always block executes first after a reset, both y1
and y2 will take on the value of 1. If the second always block executes first after a reset, both y1
and y2 will take on the value 0. This clearly represents a Verilog race condition.

If the same Verilog code as shown in Table 6.4 is written using nonblocking assignment as shown
in Table 6.5 then it will remove the problem of Verilog race condition as stated for the code as
shown in Table 6.4.

Table 6.5: Verilog code for the shift register as shown in Figure 6.4
module Race_2 (y1, y2, clk, rst);
output y1, y2;
input clk, rst;
reg y1, y2;
always @(posedge clk or posedge rst) begin
if (rst) y1 <= 0; // reset
else y1 <= y2;
end

78
always @(posedge clk or posedge rst) begin
if (rst) y2 <= 1; // preset
else y2 <= y1;
end
endmodule

6.2.4 Gated Clock and Internally Generated Clock

When clock signal passes through a gate such as AND gate as shown in Figure 6.6 then it is named
as gated clock. When Enable signal is zero then the clock is gated. Sometimes the designer needs
gated clock to incorporate power saving feature in a design. To realize the gated clock, the Verilog
code “assign gated = Clock & Enable” can be used or an AND gate can be instantiated in the design
[5]. Among this two techniques gate instantiation method is preferable.

Figure 6.6: Diagram showing gated clock

Internally generated clock refers to when we generate clock of different frequency from the mother

clock signal of a design. It should be little used in the design because it complicates the timing

analysis [5].

6.3 Simulation for Design Verification

It is a usual practice that once the design of a circuit is completed, it is simulated to check the
desired functionality. Designer has to apply the input stimulus and need to compare between the
achieved outputs (with respect to the input and) and the expected outputs. Design can be simulated
in different ways. One of the approaches is to use interactive simulator where input stimulus can be
applied from the in-built icons in the graphical user interface. Designer can easily apply clock and
make a signal or a portion of timeframe of a signal high or low. This is useful for not much complex
design. Most of the FPGA vendors provide interactive simulator.

79
Another approach is to write test bench for simulating a design. Test bench for a ‘design under test
(DUT)’ is also written using Verilog code. A test bench has no external input and output because it
wraps around the DUT and is connected with its input and output as shown in Figure 6.7. The input
of the DUT is connected with the output of the test bench through which the stimulus is supplied
and hence it is declared as ‘reg’. The output of the DUT is connected with input of the test bench
through which the output is captured for monitoring and hence it is declared as ‘wire’.

Test Bench

. DUT .
. .
. .

Figure 6.7: Diagram showing test bench connected with a DUT

6.3.1 Test Bench

Example 3: Verilog code of an 8-bit adder circuit is given in Table 6.6 for which we want to write
a test bench. The test bench is given in Table 6.7.

Table 6.6: Verilog code of an 8-bit adder circuit


module adder8 (A, B, Cin, SUM, Cout);
input [7:0] A, B;
input Cin;
output [7:0] SUM;
output Cout;
reg [7:0] SUM;
reg Cout;

assign {Cout,SUM}=A+B+Cin;
endmodule

80
Table 6.7: Verilog code for the Test Bench of the 8-bit adder as shown in Table 6.6
module testbench_adder8 ();
reg [7:0] A, B;
reg Cin;
wire [7:0] SUM;
wire Cout;

adder8 m_adder8 (
.A(A),
.B(B),
.SUM(SUM),
.Cout(Cout),
);
initial begin
A=0;
B=0;
Cin=0;
#10 A=10;
#20 A=10; B=10;
#30 A=20; B=20; Cin=1;
end
endmodule

Example 4: Verilog code of a 4-bit counter and its test bench is given in Table 6.8 and Table 6.9
respectively.

Table 6.8: Verilog code for a 4-bit Counter


module counter4 (clk, rst, en, Q);
input clk, rst, en;
output [3:0] Q;
reg [3:0] Q;
always @(posedge clk or negedge rst) begin

81
if(~rst) Q=0;
else if (en) Q=Q+1;
else Q=Q;
end
endmodule

Table 6.9: Test Bench of the Counter as shown in Table 6.8


module testbench_counter4 ();
reg en, rst, clk;
wire [3:0] Q;

counter4 m_counter4 (
.rst(rst),
.en(en),
.clk(clk),
.Q(Q),
);

initial begin
clk=0;
forever #50 clk=~clk;
end

initial begin
rst=0;
en=0;
#10 rst=1; en=1;
#50 en=0;
#50 rst=0;
end
endmodule

82
6.4 Summary
A brief discussion on writing efficient Verilog HDL code for a digital and simulation technique of a
design is discussed in this chapter. At the end of this chapter, the reader will be able to write
Verilog code following efficient style for a design.

83
Chapter 7: FPGA Implementation of Digital Design

7.1 Introduction

This chapter discusses on hardware implementation of digital design using FPGA. FPGA device
“Cyclone II” and the EDA software “Quartus II” provided by the Altera company have been used to
implement the design. The operation of Quartus II software is also described step by step manner to
enable the beginners to start design and perform its simulation and then implement it into FPGA.

7.2 Field Programmable Logic Device and Programmable Logic Device

A Field Programmable Gate Array (FPGA) and Programmable Logic Device (PLD) are both
semiconductor devices containing programmable logic components and programmable
interconnects [14-15]. It contains up to thousands of gates. The programmable logic components
can be programmed to duplicate the functionality of basic logic gates such as AND, OR, XOR,
NOT or more complex combinational functions such as decoders or simple math functions. In most
FPGAs, these programmable logic components also include memory elements, which may be
simple flip-flops or more complete blocks of memories.These logic blocks and interconnects can be
programmed after the manufacturing process by the customer/designer (hence the term "field
programmable", i.e. programmable in the field) so that the FPGA can perform whatever logical
function is needed. Figure 7.1 shows a part of interconnection matrix of an FPGA.

Figure 7.1: Interconnection in FPGA/PLD

The vertical lines are connected to the signal inputs, through buffers which also give the inverses of
the signals. An electrical connection at an intersection is shown by a dot otherwise there is no

84
connection where the vertical and horizental lines cross. The horizental lines are also shown as
connected to a symbol that looks like a single-input AND gate which is a convention used to
indicate that the output is an AND function of the inputs as selected by the dots.

There are various manufacturers for different types of FPGA chip such as Altera, Xilinx, Lattice
Semiconductor, Actel, Quick Logic, Cypress Semiconductor, Atmel, Achronix Semiconductor etc.
Among them Altera and Xilinx are the most famous FPGA companies since both of the companies
have lot of varitties of FPGA device from small number of gate counts to higher number of gate
counts. However Altera devices offer the general benefits of PLDs as innovative architectures,
advanced process technologies, state-of-the-art development tools, and a wide selection of
megafunction. Other common advantages of Altera devices include: high performance, high-density
logic integration, cost-effectiveness, short development cycles with the Quartus II software,
megaCore functions, benefits of in-system programming. Moreover, Quartus II software provides a
simple, automated mechanism to allow designers to obtain the best performance for their designs. In
addition, Quartus II software performs detailed timing analysis by default to minimize the risk of
design failures due to improper timing analysis.

7.3 Operation of Quartus II Software


The operation of the EDA software Quartus II is described step by step as follows:

7.3.1. Start: Start the Quartus II software by clicking the ‘Quartus II’ icon on the
Quartus II 7.0 Web Edition.lnk
desktop. You will get the display as shown in Figure 7.2. It consists of several windows and Menus.
Most of the commands are available under different Menus.

85
Menubar Standard Toolbar

Status Window Main Window

Project Navigator Window

Message Window

Figure 7.2: Main window of Quartus II

To realize a design into FPGA hardware, the steps as shown in Figure 7.3 are followed in Quartus
II.

86
Figure 7.3: Steps followed in Quartus II to realize a design into hardware

7.3.2. Create/Start a New Project:

1. From the File Menu, select File > New Project Wizard to open the window as shown in
Figure 7.4, Press Next button to get the window shown in Figure 7.5.

Figure 7.4: New Project Wizard

87
Figure 7.5: Creation of project in a new directory

2. Type the name of the directory, Project name and top level design entity name which is
usually same as project name. If the directory is not there, then Quartus will create the directory.
You will get the display as in Figure 7.6 and click Yes. Then you will get the display as shown in
Figure 7.7.

Figure 7.6: Create new directory

Figure 7.7: To include if any existing File

88
3. The wizard makes it easy to specify which existing files (if any) should be included in the
project. Assuming that we do not have any existing files, click Next in Figure 7.7 which leads to the
window as shown in Figure 7.8.

Figure 7.8: To Select FPGA Device

4. We have to specify the type of device in which the designed circuit will be implemented.
Choose Cyclone II as the target device family. We can let Quartus II software select a specific
device in the family, or we can choose the device explicitly. We will take the latter approach.
From the list of available devices, choose the device called EP2C20F484C7 which is the FPGA
used on Altera’s DE1 board. Press Next button which opens the window as shown in Figure 7.9.

Figure 7.9: To specify third party EDA Tool

89
5. Since we are not using any third party tool, press Next and you will get the window as shown
in Figure 7.10. Now your project has been created and you can start your design.

Figure 7.10: Ready to start a Design

7.3.3. Create a Schematic Based Design

Let us assume that we like to design a 2/4 decoder as shown in Figure 7.11.

NOT AND3
a INPUT
VCC OUTPUT out1
inst10
inst
NOT
b INPUT
VCC
inst11

AND3

OUTPUT out2

inst12

AND3

OUTPUT out3

inst13

AND3

OUTPUT out4

en INPUT inst14
VCC

Figure 7.11: Schematic diagram of a 2/4 Decoder

90
To open a file to start design, click on File Menu >New then you will get the window as shown in
Figure 7.12.

Figure 7.12: To specify type of design

Choose Block Diagram/Schematic File, and click OK. This opens the window as in Figure 7.13.
Choose Block Diagram/Schematic File (*.bdf). In the box labeled File name decsch2_4, Click
Save, which puts the file into the directory day_1 and leads to the Graphic Editor window as shown
in Figure 7.14.

Figure 7.13: To Specify File name

91
Figure 7.14: Graphic Editor to draw a schematic design

The Graphic Editor of Quartus II provides many libraries where in-built components including
primitives are there. Choose the components based on the given diagram as shown in Figure 7.11
and connect them as required. Now compile the design by selecting from the Menu ‘Processing >
Start Compilation’ (Icon also available). You will get the window as in Figure 7.15 after
successful compilation. You will get message if any error is in design.

Figure 7.15: Window after successful compilation

92
7.3.4 Simulating the Design

1. Functional Mode: For functional simulation, you need to open the Waveform Editor window.
Select File > New, which opens the window as shown in Figure 7.16. Click on the Other Files tab
to reach the window displayed in Figure 7.17. Choose Vector Waveform File and click OK.

Figure 7.16: To open waveform editor

Figure 7.17: To open waveform editor

The waveform Editor window is depicted in Figure 7.18. Save the file under the name
decsch2_4.vwf; note that this changes the name in the displayed window. Set the desired simulation
to run from 0 to 200 ns by selecting Edit > End Time and entering 200 ns in the dialog box that
pops up. Selecting View > Fit in Window displays the entire simulation range of 0 to 200 ns in the
window, as shown in Figure 7.19.

93
Figure 7.18: Waveform editor window

Figure 7.19: Waveform Editor window

Next, we want to include the input and output nodes of the circuit to be simulated. Click Edit >
Insert Node or Bus to open the window as shown in Figure 7.20. Click on the button labeled Node
Finder to open the window as shown in Figure 7.21. The Node Finder utility has a filter used to
indicate what type of nodes are to be found. Since we are interested in input and output pins, set the
filter to Pins: all. Click the List button to find the input and output nodes as indicated on the left
side of the figure. Click the button >> to move the input/outputs to the right side and then click OK
to open the window as in Figure 7.22. Specify the inputs using the tool as given in the left side of
Figure 7.22 and save as decsch2_4.vwf.

Figure 7.20: To find the input and output

94
Figure 7.21: To find the input and output

Figure 7.22: Showing input outputs of the design

To perform the functional simulation, select Assignments > Settings to open the Settings window.
On the left side of this window click on Simulator Settings to open the window as shown in Figure
7.23, choose Functional as the simulation mode and apply the decsch2_4.vwf as simulation
input, and click OK. Before running the functional simulation it is necessary to create the required
netlist, which is done by selecting Processing > Generate Functional Simulation Netlist. Now
simulation of the design can be started by Processing >Start Simulation, or by clicking the icon.
At the end of the simulation, Quartus II software indicates its successful completion and displays a
simulation results as in Figure 7.24.

95
Figure 7.23: Window to set the simulator

Figure 7.24: Simulation results

2. Timing Simulation: To perform the timing simulation, select Assignments > Settings to open
the ‘Settings window’ as in Figure 7.23. Specify the simulation mode as timing and click OK.
Then run the simulation as before. You will get the window as in Figure 7.25. It shows that the
simulation results in Functional mode and in timing mode are different due to propagation delay.

96
Figure 7.25: Simulation results in timing mode

7.3.5 Pin Assignments

During the compilation above, Quartus II compiler was free to choose any pin on the selected
FPGA to serve as inputs and outputs. However, the DE1 board has hardwired connections between
the FPGA pins and the other components such as LEDs, Seven segments etc. on the board. The pin
details are given in the DE1_pin_assigments.csv file under DE1_lab_exercises directory in the
CD-ROM. Pin assignments are made by using the Assignment Editor. Select Assignments > Pins
to reach the window as shown in Figure 7.26. Assign the pins based on your application. In our 2/4
decoder, we like to apply the input by sliding switches and want to see the results by red LEDs.
After pin assignment, save and close the window and recompile again. Check whether the pins are
assigned as your desire by clicking Assignments>pin planner.

Figure 7.26: Window to specify the pins

97
7.3.6 Programming the FPGA

The FPGA device must be programmed and configured to implement the designed circuit. Altera’s
DE1 board allows the configuration to be done in two different ways, known as JTAG and AS
modes. The configuration data is transferred from the host computer (which runs the Quartus II
software) to the board by means of a cable that connects a USB port on the host computer to the
leftmost USB connector on the board. Before using the board, make sure that the USB cable is
properly connected and USB driver is installed. Turn on the power supply switch on the board. In
the JTAG mode, the configuration data is loaded directly into the FPGA device. If the FPGA is
configured in this manner, it will retain its configuration as long as the power remains turned on.
The configuration information is lost when the power is turned off. The second possibility is to use
the Active Serial (AS) mode. In this case, a configuration device that includes some flash memory
is used to store the configuration data. Quartus II software places the configuration data into the
configuration device on the DE1 board. Then, this data is loaded into the FPGA upon power-up or
reconfiguration. Thus, the FPGA need not be configured by Quartus II software if the power is
turned off and on. The choice between the two modes is made by the RUN/PROG switch on the
DE1 board. The RUN position selects the JTAG mode, while the PROG position selects the AS
mode.

1. JTAG Programming: The programming and configuration task is performed as follows. Flip
the RUN/PROG switch into the RUN position. Select Tools > Programmer to reach the window
as in Figure 7.27. Here it is necessary to specify the programming hardware and the mode that
should be used. If not already chosen by default, select JTAG in the Mode box. Also, if the USB-
Blaster is not chosen by default, press the Hardware Setup button and select the USB-Blaster in the
window that pops up, as shown in Figure 7.27. Once all the setup is done then click Start to
download the decsch2_4.sof file into the FPGA. Now you can test whether the DE1 board works as
per your design or not.

98
Figure 7.27: FPGA programming window

2. Active Serial Mode Programming: In this case, the configuration data has to be loaded into
the configuration device on the DE1 board, which is identified by the name EPCS4. To specify
the required configuration device select Assignments > Device, which leads to the window in
Figure 7.28. Click on the Device & Pin Options button to reach the window in Figure 7.29.
Now, click on the Configuration tab to obtain the window in Figure 7.30. In the Configuration
device box (which may be set to Auto) choose EPCS4 and click OK. Upon returning to the
window in Figure 7.28, click OK. Recompile the designed circuit.

99
Figure 7.28: Window to specify configuration device

Figure 7.29: Window to specify configuration device

100
Figure 7.30: Window to specify configuration device

Open the programming window as before. Select the active serial mode. Set the switch in the
DE1 board in the PROG position. Now download the decsch2_4.pof file as before. Again set the
switch in the RUN position. Now you can test whether the DE1 board works as per your design or
not. You can power off and then ON and see that still the design does not erased.

7.4 Summary

The completion of this chapter will enable the reader how to use the EDA tool ‘Quartus II’. They
will learn how to compile and simulate the design for verification. Then they will be able to
implement the design in FPGA.

101
REFERENCES
1. L. Ali, R. Sidek, I. Aris, M. A. Mohd. Ali, B. Sunaryo Suparjo, “Challenges and Directions
for IC testing”, Integration, the VLSI Journal, pp. 17-28, Vol 37(1), Elsevier Science,
Netherland, 2004.

2. J. M. Lee, “Verilog Qucikstart: A practical guide to simulation and synthesis in verilog”,


Kluer academic publisher, Boston, USA 1999.

3. M. D. Ciletti, “Advanced digital design with the Verilog HDL” Prentice Hall, USA, 2003.

4. D. E. Thomas and P. R. Moore, “The Verilog Hardware Description Language”, Kluer


academic publisher, Boston, USA 1996.

5. W. F. Lee “Verilog Coding for Logic Synthesis”, John Wiley & Sons, USA, 2003.

6. T. R. Padmanabhan and B. Bala Tripura Sundari, “Design through Verilog HDL”, John
Wiley & Sons, USA, 2004

7. S. Brown and Vranesic, “Fundamentals of Digital Logic with Verilog Design”, MacGraw-
Hill, Boston, USA, 2008.

8. D. L. Perry, “VHDL: Programming by Example”, Mc-Graw Hill, USA, 2002

9. J. Bhasker, “A VHDL Synthesis Primer”, S. G. Publishing, USA, 1998

10. R. C. Cofer and Harding, Rapid System Prototyping with FPGAs: Accelerating the Design
Process, Newres, Amsterdam, 2006.

11. http://www.jbtechindia.com/UPLOAD/VLSI_Design_Flow/VLSI_Design_Flow.html

12. L. Ali, R. Sidek, I. Aris, M. A. Mohd. Ali, B. S. Suparjo, “Design of a Micro-UART for
SoC application”, International Journal of Computers & Electrical Engineering, Elsevier
Science, pp. 257-268,Vol. 30(4), USA. 2004.

13. http://csg.csail.mit.edu/6.375/papers/cummings-nonblocking-snug99.pdf

14. Z. Navabi, “Digital Design and Implementation with Field Programmable Devices”, Kluwer
Academic Publishers, USA, 2005.

15. James O. Hamblen, Michael D. Furman, “Rapid Prototyping of Digital Systems”, Kluwer
Academic Publishers, USA, 2001

102
103