Вы находитесь на странице: 1из 29

Departmen

nt of Electriccal and Com


mputer Engin
neering

ECE
E 124 Lab M
Manua
al
Digital Circu
uits and
d System
ms

This manual
m
is for the exxclusive use
u of registered students in the coursse.
Rep
production
n for any other purrpose is prohibited..



Spring 2014

This documen
nt is under revisiion. Your feedback is valuable! Please send your comments to Mo
ohamed Ahmed: m2sadek@uwatterloo.ca

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

Table of Conte
ents
1

Introduction
eld Programm
mable Gate Arrays (FPG
GAs)
1.1 Fie
1.2 Altera Quartus
s-II FPGA de
esign software
1.3 DE
E2 FPGA board peripherrals
1.3.1
Light Emittting Diodes (LEDs)
7-Segmen
nt display
1.3.2
HDL basics
1.4 VH
2 Lab 1 Design enttry using Alte
era Quartus--II
2.1 Pre
elab
2.2 VH
HDL design entry
e
using Altera
A
Quartus-II
2.2.1
Pin assign
nment
Adding VH
HDL codes
2.2.2
2.1 Understtanding VHD
DL structure
2.2.2
2.2.2
2.2 Understtanding the VHDL
V
code
2.2.3
Compiling
g the design for the FPGA
Simulation
n
2.2.4
Timing analysis
2.2.5
ming the FPG
GA
Programm
2.2.6
Test the design
d
on DE
E2 board
2.2.7
esign your ow
wn circuit Car-Controll
C
er
2.3 De
2.4 Po
ost-lab
3 Lab 2 Combinatio
onal circuits;; Arithmetic Logic
L
Unit - VHDL Desig
gn
3.1 Pre
elab
3.2 Lab requireme
ent ALU VH
HDL design
ostlab
3.3 Po
4 Lab 3 Combinatio
onal circuits;; Elevator Co
ontroller S
Schematic de
esign
4.1 Pre
elab
4.2 Schematic des
sign entry us
sing Altera Quartus-II
Q
4.3 Lab requireme
ent EC schematic desig
gn
ostlab
4.4 Po
5 Lab 4 Sequential circuits; Tra
affic Light Co
ontroller V HDL design
5.1 Pre
elab
5.2 Lab requireme
ent
Step 1: Crreating a seq
quence of sy
ynchronized events
5.2.1
Step 2: Trraffic Light Controller
C
5.2.2
Simulation
n
5.2.3
5.3 Po
ost-lab
6 Lab 5 Sequential circuits; Adv
vanced TLC
C VHDL de
esign
6.1 Pre
elab
6.2 Lab requireme
ent
mulation
6.3 Sim
6.4 Po
ost-lab
7 Append
dix I DE2 pin
p assignme
ent file



2

3
4
5
5
6
6
6
7
7
7
7
8
8
8
9
9
11
12
12
12
13
14
14
14
16
17
17
17
18
19
20
21
21
21
23
24
25
26
26
26
28
28
29

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

1 Introd
duction
The Lab Exp
periments arre done in grroups of two. Find a lab p
partner as soon as possiible. Each lab
boratory
experiment has several p
parts:
1. A preelab will incllude materiaal to read, and
d a circuit to design.
2. A threehour lab
boratory session during which help is available, progress iss demonstraated, and
ugging is don
ne.
debu
3. A fin
nal report, on
ne day (24Ho
our) after yo
our demo, reggarding the gguidelines in the lab man
nual. Late
lab rreports will lo
ose mark 10 % per day. T
There is a LatteSubmissio
on Drop Box..
4. Abso
olutely no fo
ood or drink
k in the laboratories. Do not leave th
he doors or windows op
pen. The
room
m will be clossed after hou
urs if the rulees cannot be ffollowed.
5. You must make aa reasonablee attempt at tthe labs in oorder to passs the course. Failure to do so will
result in a grade of INCompleete.
Each worksttation in the ECE 124 lab is equipped with:
1. Alterra DE2 Board housing a Cyclone II
I Field Proggrammable Gate Array (FPGA) chip and a
multtitude of periipheral comp
ponents
2. Alterra QuartusIII FPGA Desiggn Software
In this sectio
on you are go
oing to be briiefly introduced the onb
board components.


Figure 1 The DE2 board
d

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~


Figure
e 2 FPGA blocck diagram of D
DE2 board

1.1 Field
d Program
mmable Ga
ate Arrayss (FPGAss)
A FPGA is a
a Field Progrrammable Gate Array; basically
b
an aarray of gen
neric gates tto perform aany logic
function. Maany FPGAs siimply use sm
mall blocks o
of memory, ccalled CLBs ((Combinational Logic Blocks), to
look up the aanswer to eq
quations of 4
4 or 5 variablles. In the paast, AND & OR gates would be interco
onnected
to solve equ
uations; but this
t
has been replaced with
w
CLB's aas they are m
more flexiblee and can be used as
memory blocks.
e
haave as little as 4 variab
bles; typical designs willl be spread
d over severral CLBs;
As not all equations
requiring sig
gnals to be ro
outed between the CLBs. Just how mu
uch circuitryy there is, and
d how fast it will run,
in a particu
ular FPGA, depends
d
upon the speed
d of CLBs, th
he amount o
of resourcess for routingg signals
between CLB
Bs, and how well a design
n can be "laid
d out" or optiimized.
4

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

Newer FPGA
As are tailoreed for speciffic circuits. The
T Cyclone II FPGA, wh
hich is in ourr labs, has hardware
multipliers aand adders, which run aat 250MHz, aallowing ultrrafast digitall signal proccessing circu
uits to be
built.
Configurablee interconneects are prov
vided between the chip resources ((CLBs, hardw
ware multiplliers and
memory blo
ocks for the Cyclone II FPGA).
F
The lo
ogic, circuitrry, and interrconnects in the architeccture are
configured b
by uploading
g a programm
ming file to tthe FPGA ch
hip. This prop
perty makess the FPGA cchip very
flexible sincee it is able to
o realize diffeerent digital ccircuits by up
ploading a different proggramming file. FPGAs
are differen
nt that microprocessors or microco
ontrollers beecause the d
designer is able to chaange the
hardware reealized by th
he chip by prrogramming it. Since harrdware is alw
ways faster tthan softwarre FPGAs
allow hardw
ware to be built with nearrly the speed of software developmen
nt.

1.2 Alterra Quartu


us-II FPGA
A design software
s
Quartus is a full FPGA deesign softwarre suite. It aids the design
ner through the differentt stages of deescribing
d targeting itt for a certain
n Altera FPG A chip. The d
design proceess proceeds through
the hardwarre design and
the following
g stages:

Desiign Entry: allows the dessigner to enteer a hardwarre design speecification ussing:
o Hardwarre Descriptiion Languag
ge: such as VH
HDL or Verilog (we use V
VHDL)
o Schemattic Entry: by
b connectin
ng blocks oof ranging ccomplexity. It can be used to
interconn
nect simple ccomponents such as simp
ple logic gattes, or to inteerconnect prreviously
created h
hardware mo
odules
designer
Desiign Compila
ation: Once tthe design haas been speccified and en
ntered into th
he tool, the d
mustt perform compilation wh
hich will takee the design through variious steps:
o Analysis and Synthe
esis: A HDL o
or schematicc file is analyyzed and thee hardware iss broken
down and mapped to
o the device resources ((CLBs, flip flo
ops, memoryy elements, .. etc) so
gn logic is im
mplemented v
via the availaable resourcees on the targget chip
that desig
o Place an
nd Route: acctual placemeent of design
n on certain
n device reso
ources and ro
outing it
through tthe programm
mable intercconnection taake place in tthis step
o Assemblly: a program
mming file is produced soo that it can b
be uploaded tto the FPGA cchip
Circu
uit Simulatiion: In orderr for a design
ner to verify tthe functionaality of theirr design simu
ulation is
requ
uired. The simulation sttep ensures that the ciircuit operattes in the eexpected maanner. A
simu
ulator is fed with the design descriiption files aand waveforrms describiing the inpu
ut values
again
nst time to the circuit under
u
test. The
T simulatoor then produces the lo
ogic values tthat will
appeear on the cirrcuit outputss as waveform
ms also again
nst time.
Timing Analysiss: It gives an
n accurate in
ndication of f how fast th
he circuit run
ns, and if sp
peed and
ng constraints can be meet. Electronicc circuits alw
ways have sp
peed requirem
ments to be met and
timin
being able to baallpark how fast
f
a design
n works with
hout having to build and
d measure itt greatly
n time.
speeeds up design
ng file is uplo
Prog
gramming th
he FPGA: In this step thee programmin
oaded to thee FPGA chip tto realize
the design.
d
The circuit can be physicallly tested aftterwards byy applying in
nputs and ob
bserving
outp
puts

1.3 DE2 FPGA bo


oard perip
pherals
The DE2 bo
oard is equip
pped with peripherals
p
that can be u
used to creaate various aapplications such as
SDRAM, SRA
AM and flash memory chiips, SD card ssocket, audioo CODEC, VGA
A digital to o
output conveertor and
5

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

many otherss. For the pu


urposes of th
he labs we are
a only usin
ng switches and push bu
uttons for su
upplying
inputs and th
he following peripherals for displayin
ng outputs:

1.3.1 Ligh
ht Emittin
ng Diodes (LEDs)
(
LEDs are electronic com
mponents wh
hich can em
mit light with
h much greater efficiency than incan
ndescent
Altera DE2 bo
oard has man
ny outputs but you will oonly use the L
LEDs.
lamps. The A

1.3.2 7-Seegment dissplay


A 7segment decoder taakes an input, typically a
a 4 bit binaryy number, aand correctlyy drives a 7segment
pposed to tryying to interp
pret the origiinal 4 bit
LED display so that a perrson can see a number orr letter as op
binary numb
ber.
The 7segment display is so called because it is
i 7 bar shaaped LEDs aarranged in ssuch a way that the
m number w
which can
numbers 0 tto 9, and lettters A to F, can be displaayed. Seven ssegments is tthe minimum
uniquely dissplay numberrs and that iss why they arre used for m
many calculattor or electro
onic displayss.

1.4 VHD
DL basics
VHDL is a laanguage used
d by a hardw
ware designeer to describ e the behaviior of hardw
ware. A synth
hesis tool
then converts this into aa circuit to bee built. VHDL
L is helpful ffor the design
n of digital ccircuits, and is one of
nguages in use; the otherr being Verilo
og. An array of other langguages is beccoming popu
ular such
two main lan
as SystemC and recently
y SystemVeriilog. Basic circuit constru
ucts such as AND, OR, NO
OT (gates) aand look
SELECT stateement), coun
nters and flip
pflops are s traight forw
ward. The VH
HDL languagee is very
up tables (S
complex and
d was originally designed for the sim
mulation of m
most anythin
ng. We encou
urage you to
o use the
provided examples and stick with w
what you kno
ow will workk. The most basic rule off VHDL is th
hat if you
can't undersstand how the CAD tooll will create the circuit w
FPGA; then iit's unlikely that the
within the F
design will d
do what you
u expect. Beccause of this,, it is vital th
hat you havee an understaanding of baasic logic
circuitry and
d design.

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

2 Lab 1 Design
n entry ussing Altera Quartu
us-II
The goal of tthis lab sessiion is to gain
n experience with the Alttera Quartus FPGA design
n software w
with both
circuit entry
y and simulation and theen modifyingg the provideed circuits. T
The student w
will be progrramming
the FPGA to
o verify that the circuit works
w
in haardware. No prior experience with d
digital design
n, Altera
Quartus or F
FPGAs is necessary; altho
ough experience with bassic digital loggic will enablle one to und
derstand
the circuit.

2.1 Prela
ab
No prelab work
w
is neccessary for the
t
first part, the introoduction, of this lab exxperiment. A
A simple
multiplexer circuit has been provid
ded. After th
he selfguide d introductiion the stud
dent will modify this
T lab startts with a br ief introducttion to the laboratory ro
oom, the
circuit to peerform a diffferent task. The
equipment aand the lab exxperiments. Lab 1 is com
mposed of fou
ur parts in wh
hich you willl:
1.
2.
3.
4.

Design entry of aa VHDL code for a small d


digital circuitt
ulate the circcuits to check
k that they op
perate correcctly
Simu
Prog
gram the FPG
GA and check
k that the harrdware impleementation ffunctions corrrectly
Modify the provided circuit to
o provide new functionallity, simulatee & test it and
d submit a reeport

2.2 VHD
DL design entry usin
ng Altera Quartus--II
To start the software clicck Start then
n select the p
program grou
up Altera. Th
hen click on the Altera Quartus II
o create a project selectt File > New
w Project W
Wizard and then enter as much
icon (use Veersion 9). To
information as you wish
h. Create a new
n
projectt called Lab1
1. In projectt wizard pagge 1 you mu
ust set a
our project. Y
You should u
use N:\ECE
E124\Lab1" or somethin
ng similar; crreating a
working directory for yo
u must selecct the name of your
unique, logical, directorry name whiich describess your projeect. Next you
1). Then click
k on Next and
d say yes
project that must be the same name aas your top level design eentity (Lab1
ows you to aadd VHDL files to your project. Skip tthis now
for the creattion of the directory. Pagge 2 then allo
by clicking on
o Next. In page
p
3 you must
m
select the
t Altera FP
Cyclone II, aand EP2C35
5F672C6
PGA family C
from availab
ble devices. In
n particular tthe DE2 boarrd uses a FB GA package with 672 pin
ns, and spee
ed grade
6. Once you've selected tthe correct part you shou
uld select Fin
nish in order
r to skip the n
next page.

2.2.1 Pin assignmen


nt
put signals o
Pin assignment is the prrocess which maps the in
nput and outp
of your desiggn to physicaal pins of
hip availablee on the harrdware boarrd. As mentiooned earlierr the chip haas a vast am
mount of
the FPGA ch
resources an
nd the design can be buiilt anywheree on the chip
p in the placee and route step. The inp
puts and
outputs can be exported
d to any pin
ns on the chip. Pin assiggnments act as constrain
nts to speciffy where
ported and arre necessaryy as the perip
pherals are already prew
wired. To
exactly yourr pins are goiing to be exp
use differen
nt DE2 boarrd peripheraals such as LEDs, buttoons and switches we m
must go thro
ough pin
assignment. Since each p
peripheral iss connected physically too a certain p
pin in the FPG
GA on the bo
oard, we
ur inputs and
d outputs to the peripherrals we targeet for use. Piin names
should makee sure the tool exports ou
are complexx to use so th
he pins assign
nment file giives a logicall name to eacch pin to be used througghout the
design and m
maps it to a ccertain physiical pin namee. You can op
pen the supp
plied file to seee how this m
mapping
is done.
7

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

Download the supplied pin assignm


ment file (DE2_pins.csv) from coursse web site and save it in your
on Assignme
ents>Imporrt Assignmeents, then cliick on the [...] to select th
he saved
project direcctory. Click o
pin assignment file (DE2
2_pins.csv), w
which you've saved to you
ur working d
directory and
d click OK.
For the Alteera DE2 FPG
GA board, un
nused pins should
s
all bee left as inpu
uts tristated
d. Unfortunaately the
default is to
o ground un
nused pins (tthis reducess noise and is what onee should do for a produ
uct to be
shipped). To
o change thiis setting click on Assign
nments>Seettings then select the D
Device categgory and
click on Dev
vice & Pin Op
ptions then select the Un
nused Pins ttab and chan
nge the valuee to Input triistated.
Click OK twiice to close th
he windows.

2.2.2 Add
ding VHDL
L codes
ownload
You may usee a VHDL or Schematic (B
Block Diagraam) design in
n your project. For this p
part of lab, do
the lab1.vhd file from web site and
d add this file to your prooject directo
ory. To add itt to the projeect, click
>Add/Remo
ove Files in P
Project, find and select th
he VHDL filee on your locaal directory aand click
on Project>
Add and thee OK.

2.2.2.1 Un
nderstandin
ng VHDL sttructure
VHDL is case insensitivee. For this reeason many ccoders use aall lower casee. VHDL langguage uses tw
wo main
o describe a d
design unit ((hardware bllock):
structures to
1. Entity: it declarees the design
n unit name aand the port s (which aree inputs and outputs of th
he entity
with it. Each p
port name, tyype (input o
or output) an
nd width (nu
umber of
or deesign unit) aassociated w
bits) is declared iin the entity..
2. Arch
hitecture: th
he architectu
ure specifiess the actual functionalitty of the entity. Notice that the
entitty has no info
ormation abo
out how the hardware bllock uses thee inputs to p
produce the o
outputs
that is the role off the architeccture associaated with the entity.
wo ways to deescribe the fu
unctionality of a certain b
block:
There are tw
1. Beha
avioral: wheere the relation between input and ou
utput is declaared using lo
ogical equatio
ons.
2. Stru
uctural: wherre you can use previously
y created en
ntities in yourr design unitt as componeents. For
exam
mple if you bu
uilt an adderr unit you can
n use it, as a component, in designingg a microproccessor.

2.2.2.2 Un
nderstandin
ng the VHD
DL code
Understandiing the given
n VHDL codee will help you in the up
pcoming labss. The given code consistts of one
design unit (single entitty and archittecture). Laab1 is the toop level entiity for the design. It hass 2 input
a
sw) and
d 2 output ports
p
(ledr and
a
ledg). N
Notice that th
he names of the ports are case
ports (key and
insensitive aand identicall to those on
nes in the pins assignmeent files and are similar to the namees on the
DE2 board. We are usin
ng those logiccal names in
n order to m ap our inputts to the keyys, switches, red and
green LEDss respectivelly. Analyze the code and try to ffamiliarize yyourself witth VHDL, it is fully
commented.. If you still cannot figure out a certain
n line ask forr help.

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

2.2.3 Com
mpiling thee design fo
or the FPG
GA
To compile the design
n and makee a program
mming file ffor the FPG
GA click on
n Processing
g>Start
Compilation
n or use Cttrl+L or thee arrow buttton on the ttoolbar. You will see aro
ound 100 m
messages;
mostly due to pins whicch have been
n defined bu
ut are not beeing used. Neear the botto
om of the Qu
uartus II
u will see seeveral tabs. You can clicck on Warn
ning or Crittical Warnin
ng or Error or Info
window you
messages to
o see the details. You sh
hould alwayss check the Error and C
Critical Warrning messaages and
resolve them
m. Prudent users
u
should
d also check
k the Warni ng messages if the desiign isn't working as
expected. If there are an
ny error(s), compilation
c
pped and onee can read th
he error messsage(s),
will be stop
y warnings beecause of thee pin assignm
ment file as itt defines
divine the prroblem and ffix it. Expect to see many
almost every
y pin on the F
FPGA and yo
ou will be warned, at leastt once, for eaach one that is not connected.
The followin
ng steps are done by thee software to convert th
he schematicc circuit and/or HDL (e.gg. VHDL,
Verilog) circcuit into a filee which is used to prograam the FPGA::

Anallysis & Syntthesis: This stage conveerts the desiggn into partss which are available wiithin the
seleccted FPGA. Parts
P
which are availablee are typicallly flip flops,, memory bllocks, looku
up tables
and aadders; and sometimes m
multipliers an
nd other com
mplex supporrt parts.
Fitte
er: This placees the parts within an FP
PGA, connectts them together and to tthe input and output
pins,, and optimizzes the layou
ut for the useer goals (typi cally speed).. A design maay require hu
undreds,
or th
housands of CLBs (Comb
binational Lo
ogic Elementts), LEs (Loggic Elementss) or LUTs (LookUp
Tables).
Asse
embler: Conv
verts the fitted design intto a file whicch can be useed to program
m the FPGA.

2.2.4 Sim
mulation
Altera QuartusII comess with a sim
mple simulattor which iss limited by its graphicaal nature. Th
he input
nd then the simulation is run and the output analyyzed. The sim
mulation
stimulus is aapplied as waaveforms, an
is not interaactive, and so
o can be quite slow for deebugging. It aalso does no
ot allow one tto view anytthing but
input and ou
utput pins an
nd internal reegisters.
To simulate your circuitt, a vector waaveform Filee must be creeated. This sspecifies the inputs to thee circuit.
on/Debugging Files tab
b and selectt Vector
To do this click on File>New theen select thee Verificatio
File. That wiill open a filee typically caalled Wavefo rm1.vwf. In the left wind
dow of that ffile, right
Waveform F
click and sellect Insert N
Node or Bus aand then clicck on the No
ode Finder b
button. In th
he filter tab sscroll up
and select Pins: Input and then click
k the List bu
utton to show
w all input piins. Click on the ">" arrow
w to add
pins sw(0), ssw(1), sw(3), and key(0) to the Seleccted Nodes ccolumn. You could repeatt this for
these input p
Pins: Outpu
ut (ledg[0], ledg[1],
l
ledrr[0]) but thiss is not neceessary as th
he simulator adds all outputs by
default, then
n click OK. Fo
or simulation
n you need tto set a seriees of 0s or 1
1s to inputs (input test p
pattern).
To assign periodic values, right clicck on a sign
nal and selecct Value>Cllock and theen set the fo
following
e
signal (Table 1). It will switch each signal between 0 and 1 at aa certain inteerval. By
period for each
_ _
choosing inttervals that increase by aa factor in po
ower of two ((2
), all po
ossible comb
binations
of inputs willl be generated (Figure 3)).
Tab
ble 1 Input signals clock assiignments

Inpu
uts sw[0] sw[1] sw
w[3] key[0]
Periiod 50ns 100ns 20 0ns 400ns
9

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

Dont forget to hit Ctrl+


+W or right click in the w
waveform w
window and sselect Zoom>Fit in Win
ndow. By
nments, all po
ossible comb
binations to tthe inputs wiill be generatted (an exhaaustive test), which is
these assign
only suitablee for automaated testing o
or where therre are a few ccombination
ns to visuallyy check. The OR and
AND logic gates are easy
e
to veriffy. One can force inputss to values o
other than aa periodic w
wave. For
hrough all poossible inputts as does the random m
method
instance, thee Value>Count Value leets you go th
but for a mo
ore complex ccircuit one w
would test sp
pecific combi nations of in
nputs, not all. When you aare done
nto your pro
creating you
ur vector wav
veform inputts, you should
d save the reesulting file in
oject directorry.


Figu
ure 3 Exhaustive test input
t generation for function F(X
X0,X1,X2,X3) = ~X0 & ~X1 & ~
~X2 & X3

There are tw
wo types of siimulation:

Funcctional: Thiis is a veriffication of the


t
basic fu
unctionality of the circcuit with no
o timing
inforrmation (i.e. gate delays) included.
Timing: Timing simulation uses
u
informaation about the circuit d
design, and h
how the circcuit is fit
delays for siggnals. This siimulation is slower; but it is also
into an FPGA, to estimate acccurate time d
d requiremen
nts.
neceessary to deteermine if a design can meeet the speed

Tool. Set thee End simullation at


Now, you caan run the simulator by cclicking on P
Processing>
>Simulator T
value to 1us (default). Th
hen Select Tiiming as Sim
mulation mod
de. For the Siimulation In
nput field sellect your
Wait until it finishes and
d then click tthe Report b
button to
simulation ffile just creatted. Then clicck on Start. W
see the simu
ulator outputt. Hit CtrlW
W, or right click and chooose Zoom>F
Fit in Windo
ow to view th
he entire
simulation.
hd code (line 45) that for example: lledg (0) = sw
w (0) | sw (1)).
Remember ffrom lab1.vh
10

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~


Figure 4
F
Timingmode simu
ulation report ffor Lab1.vhd d
design

For timing ssimulation, you may notice that theree are some vvery narrow spikes. Thesse are glitchees due to
the circuit, or
o the way that
t
simulatiion is done and
a can be ggenerally ign
nored for thiis course. Yo
ou'll also
notice that tthere is an ap
pproximately
y 10ns delay
y between th
he inputs chaanging and th
he outputs cchanging.
Under View
w, or via the magnifying glass icons, you will fin d zoom conttrols. Zoom out to show
w the full
simulation.
Sometimes, a functional simulation is also requirred in each laab. You mustt Select Funcctional as Sim
mulation
hen click on G
Generate Fu
unctional Simulation Neetlist tab to generate thee necessary ffiles. For
mode and th
a functional simulation, you will nott see any tim
me delay. Heere is a samp
ple result of a timing sim
mulation,
verify its fun
nctionality m
matches with the VHDL co
ode.

2.2.5 Tim
ming analyssis
Timing anallysis can only be run affter a design
n is successffully implem
mented and it gives an accurate
indication off how fast th
he circuit run
ns, and if speeed and timin
ng constrain
nts can be meet. Electronicc circuits
always havee speed requ
uirements to be met and being able tto ballpark h
how fast a deesign works without
having to bu
uild and meaasure it greattly speeds up
p design tim
me. To run th
he analyzer, cclick on Processing
>Classic Tim
ming Analyzzer Tool and
d click the Sttart button. C
Click on the tpd tab and n
note that thee slowest
signal is at th
he top of thee list. This is tthe time delaay from "P2P
P" (Pin to Pin
n). You likelyy have a valuee around
11ns. Other tabs providee you time deelays for morre complex ciircuits with fflipflops.
he circuit get analyzed an
nd listed. Theere are two caategories to consider:
By default, aall paths in th

tpd: This
T
is the time requireed for a sign
nal to go fr om an inpu
ut pin to an output pin through
comb
binational lo
ogic
11

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

tco: F
For registers and flipflop
ps, this is thee time requirred for an ou
utput to beco
ome valid affter the a
clock
k signal tran
nsition. Also p
pay attention to the tSU ttable. That ttable lists the length of ttimes for
whicch each dataa must be prresent (setup
p) before th
he clock tran
nsition. So th
he worst casse is the
slow
west sum for tCO plus any associate setup times. N ote that we'vve neglected
d the hold tim
me of the
data for clocked d
data and thiss can be impo
ortant in reaalworld designs.

To quickly g
get timing infformation, click on the Re
eport button
n and note th
he first row iinformation ("Worst
case tpd"). Frrom this anaalysis one caan see that th
he circuit woould work aat a maximum
m speed of >
>90MHz;
which isn't v
very fast com
mpared to the 3+GHz speeed of moderrn computers. However, much more complex
circuits wou
uld also worrk at the sam
me speed, and
a
this FPG
GA has otherr resources such as add
ders and
multipliers w
which work aat 250MHz allowing for rrealtime HD TV image maanipulation.

2.2.6 Prog
gramming the FPGA
A
Make sure that
t
the pow
wer to the FPGA
F
board is on (the rred button iin the upper right corn
ner). The
programmerr tool can bee found undeer Tools>Prrogrammer.. You will neeed to make ssure that thee correct
programmerr is selected.. Click on Ha
ardware Settup and selecct USBBlastter, if necesssary. Ensure that the
Currently selected hard
dware says U
USBBlaster [USB?]. Nexxt, ensure th
hat for your p
project the L
Lab1.sof
t box undeer Program//Configure, and then ju
ust click on tthe Start
file in the lisst has a checck mark in the
button in ord
der to prograam the FPGA
A.

2.2.7 Testt the desig


gn on DE2 board
Now the dessign can be teested on FPG
GA board. Verrify the functtionality regaarding to thee lab1.vhd ffile:

Turn
n on/off SW
W0 and SW1 inputs, to verify
v
the fu
unctions beh
hind outputss LEDG0 and
d LEDG1
(check with VHD
DL code in lab
b1.vhd)
n on/off SW1
1, SW3 and K
KEY0 inputs to verify thee function beehind outputt LEDR0 (check with
Turn
VHD
DL code in lab
b1.vhd)

2.3 Desiign your own


o
circuiit Car-C
Controller
For your demo, modify tthe lab1.vhd
d code to m
make its funcction as an au
utomotive co
ontroller. Th
he inputs
ble.
and outputs are defined in below tab
Tab
ble 2 CarContrrol circuit IO d
definition

Signal Typ
pe Signal N
Name Assiigned Port
De
escription
Gas
KEY[0]
Clutch
KEY[1]
Inputs
Brake
KEY[2]
Overrid
de
SW[1]
Master swittch to shut d
down the car
LEDG[0]
L
When ON ( logic 1), accceleration is given to the motor
GasControl
Outputss
BrakeCo
ontrol
LEDR[0]
L
When ON ( logic 1), thee brakes are engaged

12

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

Consider thee following guidelines in y


your design. A typical bloock diagram for your dessign is also sh
hown.

The pushbuttonss (KEY[3:0]) on the DE2 board are in


nverted. Theey are 1 when NOT presssed and
ome 0 when pressed.
beco
Notee that some keys
k
(KEY[3:0]) or switcches (SW[17
7:0]) do not work properrly sometimes (have
physsical damage). Replace th
hem with other ones.
Make sure that the inputs and outputss you need are in the V
VHDL code ENTITY decclaration.
move extra po
orts and signaals from the design.
Rem
Add a brake safetty so that thee Brake beiing ON, turnss off the GassControl.
Add a clutch safeety so that the Clutch beeing ON, turn
ns off the GaasControl.
Add an engine saafety so that the Overrid
de being ON
N, turns off th
he GasContrrol and turn
ns on the
BrakeControl.


Figure
e 5 CarContrrol circuit blocck diagram

2.4 Post--lab
Download, p
print and fill out the Lab
b1Submission
nForm.pdf fform and havve it when yo
ou demonstrrate your
CarControl design on sccheduled datte. Then sub
bmit the posttlab report on the drop
pbox on LEA
ARN, one
urs) after the end of thee demo sesssion. The sub
bmitted repo
ort for CarC
Control desiign must
day (24 hou
include:
1. A scaan of the com
mpleted Lab
b1Submissio
onForm as tthe report frront page. Do
ont forget to
o fill out
the total logic ellements in the form.
2. Impllementation procedure, design decisions, encou
untered prob
blems or bu
ugs with sollution to
them
m and debugg
ging techniqu
ues (2 pages max). Dont forget to incclude the RTL
L view of you
ur circuit
(Too
ols>Netlist Viewers>R
RTL Viewer).
3. Fully
y commented
d VHDL codee. Use meanin
ngful name foor your signaals.
4. Timiing simulatio
on waveform
m for the circu
uit showing tthat the circu
uit works in all cases (exxhaustive
test). Put a descrription (i.e. ttruth table) b
below the w
waveform to show your u
understandin
ng of the
waveeform (show
w only four to
o five differen
nt cases).
5. All p
postlab reports should bee submitted aas PDF.

13

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

3 Lab 2 Combiinationall circuits;; Arithmeetic Logicc Unit - V


VHDL Deesign
The goal is tto build a sim
mple VHDL ccircuit to cho
oose between
n various callculations an
nd logical opeerations.
This is basiccally a calculator which can perform
m multiple op
perations wiith no memo
ory, i.e. the ccircuit is
completely ccombinational.

3.1 Prela
ab
First downlo
oad the lab2
2.vhd code ffrom web sitte and open it a context sensitive editor or Quarttus II. At
the top of th
he file, a new entity for a ssevensegmeent is defined
d. Try to understand its IO
O mapping (E
ENTITY)
and function
n (ARCHITEC
CTURE). In th
his lab, we w
will instantiatte this entityy multiple tim
mes to displaay binary
values in hexxadecimal format.

3.2 Lab requireme


r
ent ALU
U VHDL design
d
Create a new
w project forr Lab2 and add
a the lab2
2.vhd file too the projectt. After comp
piling, program your
FPGA to waatch its functionality. Fo
or every VHD
DL design e ntry, you neeed to follow
w all instrucctions in
section 2.2. Test the circcuit with diffferent combiinations of in
nput signal vvalues and ccheck its outp
put with
ode.
the VHDL co
Now, for you
ur demo, modify the codee in lab2.vhd
d to make itts function ass an ALU. Th
he inputs and
d outputs
are defined in Table 3. You
Y may usee other meaningful signaal names in your design
n. Again, you need to
follow all insstructions in section 2.2.
Table 3 ALU d
design IO defin
nition

Signal Type
e
Inputs
Outputs

Signal N
Name
Assigned Porrt
Operand 1
1
SW[7..0]
Operand 2
2
SW[15..8]
Operator
SW[17..16]
Operation
nResult HEX
X2,HEX1,HEX
X0

Comment
8bit in put to be dissplayed on HEX5 and HEX
X4
8bit in put to be dissplayed on HEX7 and HEX
X6
2bit in put to be dissplayed on LE
EDR[17..16]
9bit ou
utput result tto be displayyed on LEDR[[8..0] too

Your design is supposed to implemen


nt a simple caalculator witth four pred
defined operaations.
Table 4 ALU operations
A
s

SW[17..16
6] Operato
or
00
AND
01
OR
10
XOR
11
ADD

D
Description
Logical A
AND of 8bit inputs
Logical O
OR of 8bit in
nputs
Logical X
XOR of 8bit iinputs
Binary A
ADD of 8bit iinputs

your design. A typical bloock diagram for your dessign is also sh


hown.
Consider thee following guidelines in y

SW[7
7..0] and SW
W[15..8] rep
present the inputs
i
from
m most significant bit (M
MSB) down to least
signiificant bits (LSB) for th
he first and second opeerands. Heree, SW[7] an
nd SW[15] aare most
signiificant bits.
14

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

The result is disp


played on HE
EX2, HEX1 an
nd HEX0. HEX
X2 shows thee most signifficant hex diggit of the
EX0 shows th
he least sign
nificant hex digit of thee result. Thiss makes you
ur result
result, while HE
dable on the b
board. Notice that we aree using 3 hexx digits to diisplay the ressult, though we have
read
8inp
put operandss. Thats because addition of two 8b
bit numbers ccan cause carry (9th bit) tto occur.
This is the only ccase in which
h HEX2 will display 1 insstead of bein
ng blank. To
o blank HEX2
2 use the
o blank or turrn it off.
blanking input to
Signaals are interrmediate values that must
m
be declaared using signal stattement in th
he VHDL
architecture befo
ore the begin
n statementt.
Simu
ulation for th
his lab has some extra com
mplications. Do not add tthe vector forr the inputs ((e.g. KEY
or SW
W) but add iindividual w
wires (e.g. KE
EY[0) and wh
hen they aree added, in th
he Vector W
Waveform
File one can group them toggether. One bundle
b
of 8 wires can b
be labeled ass "A". To gro
oup wire
ht click and cchoose "Grou
uping>Grou
up". Take caare about
togetther, select tthem and theen press righ
MSB and LSB of y
your grouped
d variable; ass you need too order them
m correctly.
To assign values to input opeerands and o
operators, firrst group theem with meaningful signaal names
alue>Arbitrrary Value", Value>Ra ndom Value
es or Value
e>Count Va
alue.
and tthen use Va
Insteead of lookin
ng at the raw 7segment o
outputs in th e simulator rreport (they are not meaaningful),
it maakes more sense
s
to look
k at the LED
DR[8..0] valu e (group theem togetherr) to have faster and
moree intuitive teesting. Remem
mber to display the operaation result o
on LEDR[8..0
0].
A WH
HEN statemeent can be ussed instead o
of an IF stateement to imp
plement a mu
ultiplexer as we have
in saample VHDL file lab2.vhd
d. This multtiplexer shou
uld be taken iinto considerration. As meentioned
earliier, HEX2 on
nly displays the carry out
o value in
n ADD operation. This can be achiieved by
conccatenation off A and B to a string of 4
4 zeros and tthen perform
ming addition
n. This will p
preserve
carry
y and should
d produce a 12 bit resullt. This resullt can be useed to drive tthe 3 seven segment
deco
oders. This is the heart of
f the project aand will takee 5 lines of VH
HDL code.
Notee that if the rresult is declared as a 12bit signal, aall operationss must produ
uce 12 bit reesults. So
conccatenation is not only req
quired only fo
or addition b
but also for alll other operrations too.
The most difficullt part will bee the add opeeration whilee the result h
has 9 bits and for binary addition
HDL signals must be decclared in unsigned type . We need to
o recast the signals to unsigned
in VH
type (which arre originally
y in logicall type std__logic_vecto
or) and theen recast aagain to
may use statement like thiis to recast ssignals:
std_llogic_vectorr type. You m

R <= sttd_logic_vector(unsigneed (A) + unssigned (B))

In to
otal, about 15 lines of VH
HDL code arre required tto be written. If your deesign is takin
ng much
moree than this ST
TOP, and talk
k to the lab staff.


Figure 6
6 A typical blo
ock diagram fo
or ALU design

15

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

3.3 Postllab
Download, print
p
and fiill out the Lab2Submis

ssionForm.pd
df from an
nd demonstrrate your deesign on
scheduled date. Then submit the posstlab report on the drop
pbox on LEA
ARN, one dayy (24 hours) after the
end of the deemo session.. The submittted report m
must include:
1. Scan
n of completeed Lab2 Sub
bmission Form as the rreport front page. Dont forget to filll out the
totaal logic elemeents and thee Worst Case Speed (ns) ttpd in the form
m.
2. Impllementation procedure, design decisions, encou
untered prob
blems or bu
ugs with sollution to
them
m, debugging techniques aand RTL view
w of your cir cuit (2 pagess max).
3. Fully
y commented
d VHDL codee.
4. Funcctional simu
ulation wav
veform with coverage for critical cases. Marrk your sim
mulation
waveeforms explaaining severaal different scenarios
s
forr each operaation. You m
must prove th
hat what
you have designeed is working. For instan
nce, testing w
with the inpu
uts set to 0 d
does not allow
w one to
operation fro
om another o
or if any operration in partticular is fullyy working. O
Often one
distinguish one o
ngs may breaak (i.e. overfflow). Do nott print waveforms of
testss critical casees the limitts where thin
all possible casess give samp
ples for criticcal cases of eeach operatio
on and explaain how you checked
p
operaation. The go
oal is to hav
ve a simulatiion to provee that the cirrcuit works; without
for proper
doing a full exhau
ustive test off all possible inputs. It sh ould prove tthat all operaations work ccorrectly
for eenough numb
bers to give cconfidence th
hat the circuiit is fully funcctional.


Figure 7 Sample fun
nctional simulaation output

16

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

4 Lab 3 Combiinationall circuits;; Elevatorr Controlller Sch


hematic d
design
The goal of tthis lab session is to dessign two simple circuits u
using truth ttables and K
KMaps. Translating a
written circu
uit descriptio
on into a Tru
uth Table is tthe basis of th
his circuit deesign. Optimiizing the dessign with
Kmaps allows one to m
make the design smaller aand faster. Y
You are to deesign and im
mplement a ccircuit to
ors (we will consider
control an eelevator. The circuit has four inputs tto define currrent and requested floo
only three flloors 01, 10, and 11) and
d two outputts to enable the motor and show thee up/down d
direction.
For safety, w
whenever you have 00 ass an input forr either the ccurrent and//or requested floor(s), th
he motor
has to be dissabled.

4.1 Prela
ab
To prepare ffor this lab th
he student sh
hould reducee the design descriptionss to truth tab
bles. The trutth tables
should be th
hen used to build KMap
ps. Extract lo
ogical expresssions from the KMaps and realize the two
circuits requ
uired as gatess.

4.2 Scheematic dessign entry using Alttera Quarttus-II


In this lab, we
w first creaate a simple project using the schem
matic editor aand then mo
odify it to im
mplement
Elevator Con
ntroller. To sstart, create a project and
d name it Laab3, repeat th
he same step
ps to import the pins
assignment file and to seet unused pin
ns to input trristate in seection 2.2.1. P
Proceed by aadding the scchematic
n File>New
w and select
t Design File
es>Block D
Diagram/Sch
hematic
using the scchematic ediitor. Click on
File. Primitive parts (AN
ND, OR, otherr gates) can b
be entered vvia the Symb
bol Tool which looks likee an AND
o it and theen expand th
he Librariess item to revveal primitiv
ves. Expand that to reveeal logic
gate. Click on
primitives such as gatess. You will allso need to use
u the pin aand other primitives such as input, output,
d or logic 0) as well as vcc (high or logic 1). T
The storage primitives iinclude flipfflops. To
gnd (ground
draw wires you will neeed to use the Orthogonal Node Tooll from the to
oolbox on thee left. Drawin
ng wires
Draw wires in
n pieces to m
make the task
k easier. To cconnect nets or wires
can be painfful as you willl discover. D
to the outsid
de world you
u will also need to use thee input and ooutput pin prrimitives. To
o name your pins just
double click on them and
d use the stan
ndard namess (e.g. sw[0], ledg[0]) wh
hich is defined in your pin
n out file,
matic above (documenteed in Append
dix A). Do N OT right clicck on a wiree or node, an
nd in the
on the schem
Properties tab
t assign a name. That sometimes results in a circuit whicch does noth
hing. Now, d
draw the
schematic sh
hown in Figu
ure 8:


Figurre 8 Lab3.bdff Schematic d
design file

17

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

Compile thiss design and


d download it to the FPGA for testingg. If you havee time, simu
ulate it by settting the
proper inpu
ut values as cclock periodss for all posssible scenariios (as done in previous labs). Remeember to
zoom and view the whole simulation
n with Ctrl+W
W.

4.3 Lab requireme


r
ent EC schematic
s
design
For your deemo, modify the lab3.bd
df file to maake it operatte as an elevvator contro
oller. The inp
puts and
outputs are defined in th
he Table 5.
Tab
ble 5 CarContrrol circuit IO d
definition

Signal Typ
pe Signal N
Name Assig
gned Port Description
n
CurrentFloor
SW
W[1..0]
Inputs
NextFloor
SW
W[3..2]
Enable
LEDG[0]
When ON (loogic 1), the motor is turrned on
Outputs
Direction
LE
EDR[0]
Define moviing direction
n (upwards: 1, downwarrds:0)
Design two versions of tthis circuit o
one using any
y types of 2input logic ggates and th
he other onlyy 2input
Kmaps help you minimizze a circuit w
with any typee of gates, bu
ut it will nott directly
NAND gates. Note that K
minimize a d
design wheree you are resttricted to usee a specific ggate type (e.gg. NAND, NOR
R). There
help you to m
are two way
ys to design the circuit:
1. Using only 2inp
put NAND gaates exclusiv
vely for the ffirst design aand minimizzing wires an
nd gates
using
g any gates aavailable for tthe second d
design
2. Startting with dessigning a circcuit with 2in
nput logic gaates of any tyypes and then
n replacing tthe gates
with
h 2input NAN
ND equivalen
nts
Considering one of above approaches, start the schematic ediitor to build your two deesigns using sswitches
LEDs for the o
outputs. Sim
mulate your d
designs and u
upload it to the FPGA for physical
for the four inputs and L
testing.


Figure 9 3floor elevato
3
or

Consider thee following guidelines in y


your design.
18

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

You can find a schematic inveerter in the Q


Quartus softw
ware called N
NOT under prrimitives > logic
KMaaps should b
be used to miinimize the eelevator circcuit size. Notee that there is no easy w
way to do
this, for the NAN
ND only design, without lots of experrience. Note that there aare many thiings that
be optimized
d for. One maay choose to
o design for tthe minimum
m number of
f wires OR gaates it's
can b
hard
d to minimize both at thee same time. We sugges t trying this several times and inclu
ude all in
yourr Lab Report..

4.4 Postllab
Download, print
p
and fiill out the Lab3Submis

ssionForm.pd
df form an
nd demonstrrate your deesign on
scheduled date. Then submit the posstlab report on the drop
pbox on LEA
ARN, one dayy (24 hours) after the
end of the deemo session.. The submittted report m
must include::
1. Scan
n of completeed Lab3 Submission Form
m as the froont page of yo
our report. D
Dont forget tto fill out
the number of g
gates and nu
umber of wirres in the foorm for demo
onstrated cirrcuit.
2. Impllementation procedure, design decisions, encou
untered prob
blems or bu
ugs with sollution to
them
m, debugging techniques aand RTL view
w of your cir cuit (2 pagess max).
3. Discu
ussion of exp
pandability o
of the design
n if the 4th flloor is added
d and effect of that on reeliability
th
(you
u don't need tto actually im
mplement the 4 floor exxtra logic). Co
number of w
wires and
onsider the n
gatess as being ind
dicators of reeliability.
4. How
w does the all NAND dessign comparre to the oth
her design? How many gates and w
wires are
requ
uired for each
h? Note: This lab used to
o be built an
nd so you should count A
ALL gates inverters
too as they all h
had to be wired up. Which
h would be m
more reliablee?
5. Inclu
ude the trutth table forr the elevattor controlleer, Kmaps and how yyou deduced
d logical
exprressions for tthe two circu
uits.
6. Scheematic print sscreen for the two circuitts
7. Simu
ulation waveeforms for th
he two circu
uits showing that they w
work in all caases (pleasee circle 4
points and identtify what thee inputs reprresent and w
why the outp
puts are corrrect accordin
ng to the
requ
uirements). D
Demonstrate that you can
n interpret th
he simulation
n waveformss.

19

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

5 Lab 4 Sequen
ntial circu
uits; Trafffic Lightt Controlller VHD
DL desig
gn
The goal of tthis lab is to design a trafffic light control system aas a sequenttial circuit wiith clock. Thee system
controls two
o traffic lightts on an interrsection usin
ng a state maachine. First you will learrn to implem
ment and
test, two clock dividers u
using modulu
us and binary
y counters.
mplement a clock
c
dividerr is to use aa binary coun
nter. Binary counters in
ncrement
The standarrd way to im
their value by
b one on ev
very rising/ffalling edge of its input clock signal. If you conssider an nbiit binary
counter, you
u notice that the first bit o
of the counteer (LSB) togggles in the peeriod of halfspeed of thee original
clock. If you look at the ssecond bit yo
ou would find
d it toggling at half speed
d of the first bit which meeans 1/4
th
t counter ooutput is a cclock in frequency of inp
put clock
the speed off the originaal clock. Thuss N bit in the
frequency divide by 2N+1 where N iss the bit position startingg from bit 0
0. The binaryy counter is not very
you need a cllock signal w
with precise ffrequency beecause the divisor is alw
ways in power of two.
accurate if y
So for accuraate timing orr clock division a modulu
us counter caan be used. A
A modulus co
ounter increm
ments up
to a certain n
number (term
minal count value) and th
hen resets too initial valuee. It toggles the clock sign
nal at the
terminal wh
hich is equal to half the period
p
of yo
our desired ooutput clock
k. Thus you n
need to calcu
ulate the
period of yo
our clock to d
determine th
he terminal v
value. Figuree 10 shows o
outputs of tw
wo 25bit bin
nary and
modulus cou
unters generated from a 5
50MHz inputt clock.
3
33,554,432
T0

F0=5
50MHz
T0=2
20ns

25bit Binarry Counter


33,554,4332=2^25

F~1.49Hz
T~0.67s
16,777,216 T0
5
50,000,000
T0

25bit Modullus Counter


25,0000,000

F=1Hz
T=1s
25,000,000 T0

Fig
gure 10 Binarry and Moduluss clock dividerrs by 25bit counters

In this lab yo
ou need to im
mplement sequential logiic in VHDL. SSequential loggic has "mem
mory" and th
he output
depends on the inputs aand what thee current statte or "memoory" is. This rrequires a PR
ROCESS stru
ucture in
your architeecture to imp
plement flipfflops and oth
her memory eelements.
Label_nam
me: Proces
ss (Sensiti
ivity_List
t)
Begin
.
.
.
End proce
ess;

The Label_
_name can be
b any nam
me like applle, orange, eetc. except reserved naames in VH
HDL. The
Sensitivit
ty_List is th
he list of sign
nals/variablees/inputs thaat the Proce
ess is sensittive to. These
e are the
signals that w
will trigger eexecution of the Process
s inside the simulator. Thus, any sign
nal that is reaad in the
Process, sh
hould appearr in the sensitivity list. M
Missing signaals from the sensitivity liist cause sim
mulation
synthesis miismatch.
20

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

The key staatement to im


mplement flip flops or sequential
s
loogic, is the IF (rising_e
edge (clock))) THEN
statement.
In VHDL, staate machiness are built in
nside a proceess block. A ccase statemeent can be ussed to determ
mine the
next state depending on
n the currentt state and other
o
signalss (inputs or ttime events)). On the edgge of the
urrent state is
i assigned the
t value of the next staate (determin
ned by the ccase statemeent). It is
clock the cu
worth mentiioning that sometimes yo
our decision can be stayin
ng in the sam
me state. To n
name your sttates you
may declare a new type iin your archiitecture and then declaree two signals of this type to keep yourr current
state and next state.

5.1 Prela
ab
In this lab experiment,
e
it is importaant to design
n and build yyour circuit incrementallly. Do NOT attempt
designing th
he whole circcuit at once. F
First downlo
oad the lab4
4.vhd file fro
om web site aand open by Quartus
II. Browse the
t VHDL co
ode carefully
y and try to understand all statemen
nts in the fille. Look at tthe clock
divider circu
uits and stud
dy how they work, how to change th
he frequencyy of the systeem clock, and how it
could be furrther divided
d by 10. Try to extract th
he embedded
d state mach
hine in this ccode and und
derstand
sequential lo
ogic design statements in
n VHDL.

5.2 Lab requireme


r
ent
There are tw
wo steps forr this lab. Th
he first step is just to geet you familliarized with
h creating seequential
hardware. The second sttep is what yo
ou will demo
onstrate and will be mark
ked for.

5.2.1 Step
p 1: Creatiing a sequeence of syn
nchronized
d events
Create a new
w project for Lab4 and ad
dd the lab4.v
vhd file to th
he project. F
For every VHDL design en
ntry, you
need to follo
ow all instru
uctions in secction 2.2, i.e., import pin assignment file, set unu
used pins to tristate,
compile, pro
ogram the deevice, etc. Teest the circuiit with differrent combinaations of inp
put signal values and
check its fun
nction with th
he VHDL cod
de. Do not try
y to simulate the design aat this moment.
Now, modiffy the lab4.vhd file to make a seq
quencer to ggenerate thee following pattern (Figgure 11)
repeatedly o
on green and
d red LEDs. The pattern sttarts with a fflashing lightt on a green LED for two seconds
followed by solid pattern
n for 5 secon
nds and then
n the same seequence with
h different du
urations on rred LED.
n Table 6. Yo
ou may use oother meanin
ngful signal n
names in your design.
The inputs aand outputs aare defined in
Again, you n
need to follow
w all the instrructions prov
vided in secttion 2.2.
0

GFLASH
2s

GSOLID
5s

10

RFLASH
3s

Green
G
LED ON, Red LED OFF

11

12

14

15

RSO
OLID
6
6s
Red LED ON
N, Green LED O
OFF

Figu
ure 11 Seque
encer timing diiagram

21

13

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

Table
T
6 Sequenccer circuit IO deefinition

Sig
gnal Type Signal Nam
me
Assig
gned Port
Input
Input Clock
CLO
OCK_50
Green LED
LE
EDG[8]
Red LED
LED
DR[11]
Clock 1Hz Bin
LE
EDG[2]
Outputs
Clock 1Hz M
Mod
LE
EDG[1]
Clock 10Hz Mod
LE
EDG[0]
State Number
HEX0
H
State Counteer
HEX2
H

D
Description
n
5
50MHz onbo
oard clock
G
Green light p
pattern
R
Red light patttern
1
1Hz output ffrom binary ccounter
1
1Hz output ffrom modulu
us counter
1
10Hz output
t from modullus counter
4
4bit internaal state numb
ber
4
4bit internaal state countter

Start your design


d
with modulus 10
0Hz and 1Hzz clock divid
ders. Use thiis 1Hz clock
k to drive yo
our state
machine. Keeep the binarry 1Hz clock
k output for y
your demo. F
Figure 12 sh
hows a typiccal block diaggram for
your design
n. You must be able to implement th
he sequenceer FSM in fo
our states. D
Display your internal
signals (state number an
nd counter) o
on SevenSeggment displayys to debug yyour circuit.

CLOCK_50

Use
erRedLEDs
LEEDR[17:0]

LED
DR[11]

50MHz

7SeggmentDisplay (x8)

Your
TLC Design
T
HEX4, HEX0

UserGreenLEDs
LEEDG[8:0]

PIN

LEDG[8],, LEDG[2:0]

PORT

FPGA

DE2

Figure 12 A ttypical block d


diagram for a ssequencer design

Try to build the required


d componentts one by onee to generate the timing d
diagram in Fiigure 11:
1. A mo
odulus clock divider to crreate a 10Hz clock from tthe board's 5
50MHz clock input.
2. A mo
odulus clock divider to crreate a 1Hz clock from th
he 10Hz clock
k.
3. The 1Hz clock will
w drive a counter to determine tthe time of transitions b
between staates. The
curreent state dettermines whiich LEDs are ON or OFF. Your states ccan be defineed as:

GFLASH: the
G
green LED is flashing at 10Hz, while red LED is O
OFF.
GSOLID: the
G
FF.
green LED is ON, while rred LED is OF
RFLASH: the
R
0Hz, while grreen LED is O
OFF (like amb
ber state).
red LED is fllashing at 10
RSOLID: the
R
red LED is O
ON, while greeen LED is OF
FF.

22

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

5.2.2 Step
p 2: Trafficc Light Co
ontroller
After buildin
ng the simplle state mach
hine and tessting that it is functionin
ng accordingg to the given timing
diagram, yo
ou are now required to extend thee designed ssequencer to
o implementt a real trafffic light
controller in
n transportattion system liike Figure 13
3.
00

07

NS Sensor

B
EW S
Sensor

EW Sensor

NS Sensor

Figure 13 Tra
affic Light Systtem

The traffic light acts norrmally as a simple


s
sequeencer, to tran
nsit between
n green, amb
ber and red lights in
nt have yello
ow or orang e LEDs on o
our evaluatio
on board, wee replace
real traffic light systemss. As we don
design. You m
may design itt in three staates as:
them with a flashing red light in our d

Go: the gre


G
een LED is ON
N. First two sseconds is flaashing at 10H
Hz for turning left cars.
PrepareToS
P
Stop: the red LED is flashing at 10H
Hz to warn drrivers to be p
prepared to sstop.
Stop: the r
S
red LED is ON.

As shown in
n Figure 14, the traffic light
l
controlller switchess between ab
bove states with the preedefined
durations (ii.e. 6 second
ds, 2 seconds and 8 seconds respecctively) conttinually. Note that in the first 2
seconds of G
Go state in tthis mode, th
he green LED
D is flashing.

Figure 14

Traffic Liight Controlller Timing D


Diagram
23

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

The inputs aand outputs ffor the extended traffic ligght logic are shown below
w:
Table 7 TLC circuit IO defin
nition

Signa
al Type Sig
gnal Name Assigned Port
In
nput
Inp
put Clock
CLOCK_50
LEDG[8
8]
Greeen LED NS
Red
d LED NS
LEDR[11]
Greeen LED EW
LEDG[7
7]
Red
d LED EW
LEDR[0
0]
Outtputs
Clo
ock 1Hz
LEDG[1
1]
Clo
ock 10Hz
LEDG[0
0]
Staate Number
HEX0
Staate Counter
HEX2

De
escription
50MH
Hz onboard clock
Green
n light patterrn for north//south bound
ds
Red l ight pattern for north/so
outh bounds
Green
n light patterrn for east/w
west bounds
Green
n light patterrn for east/w
west bounds
1Hz ooutput from m
modulus cou
unter
10Hzz output from
m modulus co
ounter
4bit internal statte number
4bit internal statte counter

Consider thee following guidelines


g
in
n your desiggn. A typical block diagrram for yourr design is shown in
Figure 12.

If your PROCESS
S has nested IF statementts then the reesulting hard
dware will bee a disaster aand hard
to deebug! Each IF
I statementt builds a 2x1 multiplexeer and nestin
ng IF statem
ments builds a circuit
that is deep and sslow at the leeast. For thiss circuit you n
never need m
more than a ssingle IF stattement.
gic elementss which can store inform
mation. In th
he sample VHDL code yo
ou see a
Flipflops are log
PRO
OCESS statem
ment. This is u
used to create flip flops sso that information can b
be stored in memory
or a counter. Thee Dtype flipflop is the on
ne primarily used in FPGA
As.
DL code, mu
ust be used tto build a counter or
The PROCESS sttatement, as given in thee sample VHD
ng within th
he clock edge detection statement IF (rising_ed
dge clock) T
THEN is
regisster. Anythin
automatically lattched. So A <
<= B will auttomatically laatch a signall A, which is set equal to B at the
ng edge of thee clock.
risin
Be sure that the sensitivity list
l includess all signalss read by a
a process orr simulation will not
k as expected
d.
work
Try tto minimize tthe number of states to m
minimum in yyour design.
Notee that your Quartus
Q
simulation has to employ tthe 50MHz p
provided by the board ((without
using
g the clock d
divisor). Yourr board test aand demo sh
hould employy the divided
d (slow) clock
k so that
you aare able to seee your desiggn running on the board.
Display internal state numbeer and transiition counterr. They are iin great help
p for debuggging your
gn.
desig

5.2.3 Sim
mulation
In order to ssimulate you
ur design before program
mming the F
FPGA device, you should change the terminal
count value for your first modulus co
ounter in clo
ock chain (10
0Hz) to skip from waitingg for 5,000,0
000 clock
0MHz. You caan set your terminal
cycles in your simulations to generaate one cyclee of 10Hz cloock from 50
0000000000
000000000000001" and then find a proper clocck period forr CLOCK_50 to have
count to "00
exactly 10Hzz and 1Hz clo
ocks in simullation wavefo
orms (Figuree 15).
Another waay of simulatting your deesign is com
mpletely byp
passing the cclock dividerr and provid
ding the
50MHz clock
k to the statee machine. Please notice tthat this straategy is only tto simulate yyour design.
24

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

your simulatiions
For y
bypass this di
b
ivider or redu
uce its length
h

F0=50MHz

10Hzz Clock Diviider


5,000,000

F1=10Hz
F

1Hz Clocck Divider

10

F2=1
1Hz

Fig
gure 15 Clock
k generation sccheme

5.3 Post--lab
Download, print
p
and fiill out the Lab4Submis

ssionForm.pd
df form an
nd demonstrrate your deesign on
scheduled date. Then submit the posstlab report on the drop
pbox on LEA
ARN, one dayy (24 hours) after the
end of the deemo session.. The submittted report m
must include::
1. Scan
n of completeed Lab4 Submission Form
m as the fro
ont page of yo
our report.
2. Dont forget to fiill out the T
Total logic eleements and
d Worst Casee Speed Paraameters in tthe form
for d
demonstrated
d circuit.
3. Impllementation procedure, design decissions, state m
machine diaggram with trransition con
nditions,
enco
ountered pro
oblems or bu
ugs with solu
ution to them
m, debuggin
ng techniquess and RTL aand State
view
w of your cirrcuit (4 pagges max). Usse Tools>N etlist Viewe
ers>State M
Machine Viewer. It
reveals all registeers and statees within a circuit.
y commen
nted VHDL
L code. Do not include the Seve
enSegment design
4. Fully
(ENT
TITY+ARCHITECTURE).
5. Funcctional Simulation Waveforms: Simu
ulation must be done to prove that tthe design w
works as
desirred. Please trry to cover aand explain w
what happen
ns in your waaveforms at different tim
me points
and h
how this is related to thee requiremen
nts.
N.B. Sav
ve your work
k in a separa
ate project fiile, you will need it again
n in lab-5.

25

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

6 Lab 5 Sequentiial circuitts; Advan


nced TLC
C VHDL
L design
This lab is an
a extension
n to the hardware that you develop
ped in lab4.. If you imaggine the traffic light
controller deeveloped in llab4 was forr normal opeeration, lets ccall it Day m
mode, then in
n this lab session you
will add a N
Night mode tto the system
m that someh
how gives prriority to onee direction (N
NorthSouth or East
West).

6.1 Prela
ab
Think of ad
dding the niight mode in
i a way th
hat you emp
ploy all circuit developeed in lab4 without
duplicating tthe hardware area. In oth
her words, do
o not implem
ment it like th
his:
If day_mo
ode then
The code
c
you de
eveloped in
i lab-4
Else -- Night-mode
N
e
The code
c
you de
eveloped in
i lab-4 mo
odified to
o work in n
night-mode
e
End if ;

Instead, thin
nk of method
ds that distiinguish daym
mode from n
nightmode when the time comes to
o switch
state. In this method the same hardw
ware is used iin both day aand night mo
odes.

6.2 Lab requireme


r
ent
In the nightt mode the traffic
t
light controller
c
haas a default (priority) sid
de (SW [16]) that trafficc light is
always green for it if th
here is no caar on the oth
her side. Wh
hen the time to switch liights (amberr to red)
mber light peeriod), if no car is detectted on the no
ondefault side, the systeem starts
reaches (at tthe end of am
another greeenamber (only solid greeen) period ffor the defau
ult side, otheerwise it actss like day mo
ode with
greenamberred period
ds for both sides.
s
For th
his mode, wee use car deetection senssors output for non
or transition
n between sttates. These sensors can be implemeented using ON/OFF
default side to decide fo
W [15:14]) on the board. When the sw
witch is ON, iit indicates tthe presence of a car on tthat side.
switches (SW
Figure 16 co
ompares the ttwo modes o
of day and nigght.
The inputs aand outputs ffor the extended traffic ligght logic are shown in Taable 8.

26

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

Figure 16 Traffic L
Light Controlleer Timing Diaggram
Table
T
8 TLC
C circuit IO defiinition

Signal Type
Inpu
uts

Outp
puts

Sig
gnal Name
Assigned
d Port
ut Clock
CLOCK
K_50
Inpu
Operration Mode
SW[1
17]
Defaault Side
SW[1
16]
Car S
Sensor NS
SW[1
15]
Car S
Sensor EW
SW[1
14]
LEDG[8]
Greeen LED NS
Red LED NS
LEDR[[11]
Greeen LED EW
LEDG[7]
Red LED EW
LEDR[0]
Statee Number
HEX
X0
Statee Counter
HEX
X2
Waitt Counter NS
S
HEX
X4
Waitt Counter EW
W
HEX
X6

D
Description
50M
MHz onboard
d clock
0: d
day, 1: nigh
ht
0: N
NS, 1: EW
Car detection seensor output for NS bound
Car detection seensor output for EW boun
nd
Greeen light patteern for north
h/south boun
nds
Red
d light pattern
n for north/ssouth bounds
Greeen light patteern for east//west boundss
Greeen light patteern for east//west boundss
4biit internal staate number
4biit internal staate counter
4biit internal waait counter fo
or NS bounds
4biit internal waait counter fo
or EW bound
ds

Consider thee following guidelines in y


your design.

Worst approach:: Duplicatingg the circuit area by consstructing a h


hardware thaat only work
ks at day
dware that on
nly works at night mode..
mode, and a hard
Incorporate the night mode with your current
c
lab4
4 design. Th
he number of states need
d not be
chan
nged. Only the transition cconditions arre required tto be changed.
The waitcounterr incrementss (counts up starting 0h) only if the light is red fo
or the corressponding
or is on for the same sid
h on the
side and cardettection senso
de otherwise it must bee reset to 0h
displlay.
The statecounteer is reset to 0h once the
t system eenters a new
w state. In o
other wordss, it only
new state.
increements withiin a state, and resets to zeero in each n
Display internal state numbeer and transiition counterr. They are iin great help
p for debuggging your
gn.
desig

27

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

6.3 Simu
ulation
Similar to laab4, you willl need to chaange the VHD
DL code sligh
htly in orderr to do the simulation. Fo
ollow the
same proced
dure and gen
nerate a simu
ulation waveform that prroves the circcuit is workin
ng properly in night
mode as welll as daymod
de.

6.4 Post--lab
Download, print
p
and fiill out the Lab5Submis

ssionForm.pd
df form an
nd demonstrrate your deesign on
scheduled date. Then submit the posstlab report on the drop
pbox on LEA
ARN, one dayy (24 hours) after the
end of the deemo session.. The submittted report m
must include::
1. Scan
n of completeed Lab5 Submission Form
m as the froont page of yo
our report. D
Dont forget tto fill out
the Total

logic elements and


a
Worst Case Speed Parameters in the form
m for demonstrated
circu
uit.
2. Impllementation procedure, design decissions, state m
machine diaggram with trransition con
nditions,
enco
ountered pro
oblems or bu
ugs with solu
ution to them
m, debuggin
ng techniquess and RTL aand State
view
w of your cirrcuit (4 pagges max). Usse Tools>N etlist Viewe
ers>State M
Machine Viewer. It
reveals all registeers and statees within a circuit.
y commen
nted VHDL
L code. Do not include the Seve
enSegment design
3. Fully
(ENT
TITY+ARCHITECTURE).
4. Funcctional Simulation Waveforms: Simu
ulation must be done to prove that tthe design w
works as
desirred. You need to show th
hat both nigh
ht mode and day mode w
work as desirred. Also you
u need to
show
w the different scenarios that can hap
ppen in nigh
ht mode (diffferent defaullt sides and d
different
car ssensor valuess) using num
merous waveforms. Finallly the wait co
ounters funcctionality sho
ould also
be shown. Please try to cov
ver and explain what haappens in yo
our waveform
ms at differeent time
points and how tthis is related
d to the requirements.


28

ECE124 Lab Manual Digital Circcuits and Systtems


~ece124/
https://ece.uwaterloo.ca/~

7 Appen
ndix I DE2
D pin aassignmeent file
Name
SW[0]
SW[1]
SW[2]
SW[3]
SW[4]
SW[5]
SW[6]
SW[7]
SW[8]
SW[9]
SW[10]
SW[11]
SW[12]
SW[13]
SW[14]
SW[15]
SW[16]
SW[17]
HEX0[0]
HEX0[1]
HEX0[2]
HEX0[3]
HEX0[4]
HEX0[5]
HEX0[6]
HEX1[0]
HEX1[1]
HEX1[2]
HEX1[3]
HEX1[4]
HEX1[5]
HEX1[6]
HEX2[0]
HEX2[1]
HEX2[2]
HEX2[3]

Location
PIN_N25
PIN_N26
PIN_P25
PIN_AE14
PIN_AF14
PIN_AD13
PIN_AC13
PIN_C13
PIN_B13
PIN_A13
PIN_N1
PIN_P1
PIN_P2
PIN_T7
PIN_U3
PIN_U4
PIN_V1
PIN_V2
PIN_AF10
PIN_AB12
PIN_AC12
PIN_AD11
PIN_AE11
PIN_V14
PIN_V13
PIN_V20
PIN_V21
PIN_W21
PIN_Y22
PIN_AA24
PIN_AA23
PIN_AB24
PIN_AB23
PIN_V22
PIN_AC25
PIN_AC26

Name
HEX2[4]]
HEX2[5]]
HEX2[6]]
HEX3[0]]
HEX3[1]]
HEX3[2]]
HEX3[3]]
HEX3[4]]
HEX3[5]]
HEX3[6]]
HEX4[0]]
HEX4[1]]
HEX4[2]]
HEX4[3]]
HEX4[4]]
HEX4[5]]
HEX4[6]]
HEX5[0]]
HEX5[1]]
HEX5[2]]
HEX5[3]]
HEX5[4]]
HEX5[5]]
HEX5[6]]
HEX6[0]]
HEX6[1]]
HEX6[2]]
HEX6[3]]
HEX6[4]]
HEX6[5]]
HEX6[6]]
HEX7[0]]
HEX7[1]]
HEX7[2]]
HEX7[3]]
HEX7[4]]

Location
PIN_AB2 6
PIN_AB2 5
PIN_Y24
PIN_Y23
PIN_AA225
PIN_AA226
PIN_Y26
PIN_Y25
PIN_U222
PIN_W244
PIN_U9
PIN_U1
PIN_U2
PIN_T4
PIN_R7
PIN_R6
PIN_T3
PIN_T2
PIN_P6
PIN_P7
PIN_T9
PIN_R5
PIN_R4
PIN_R3
PIN_R2
PIN_P4
PIN_P3
PIN_M2
PIN_M3
PIN_M5
PIN_M4
PIN_L3
PIN_L2
PIN_L9
PIN_L6
PIN_L7


29

Nam
me
HEX77[5]
HEX77[6]
KEY[0]
KEY[1]
KEY[2]
KEY[3]
LEDR
R[0]
LEDR
R[1]
LEDR
R[2]
LEDR
R[3]
LEDR
R[4]
LEDR
R[5]
LEDR
R[6]
LEDR
R[7]
LEDR
R[8]
LEDR
R[9]
LEDR
R[10]
LEDR
R[11]
LEDR
R[12]
LEDR
R[13]
LEDR
R[14]
LEDR
R[15]
LEDR
R[16]
LEDR
R[17]
LEDG
G[0]
LEDG
G[1]
LEDG
G[2]
LEDG
G[3]
LEDG
G[4]
LEDG
G[5]
LEDG
G[6]
LEDG
G[7]
LEDG
G[8]
CLOC
CK_27
CLOC
CK_50

Loccation
PIN_P9
PIN_N9
PIN_G26
PIN_N23
PIN_P23
PIN_W26
PIN_AE23
PIN_AF23
PIN_AB21
PIN_AC22
PIN_AD22
PIN_AD23
PIN_AD21
PIN_AC21
PIN_AA14
PIN_Y13
PIN_AA13
PIN_AC14
PIN_AD15
PIN_AE15
PIN_AF13
PIN_AE13
PIN_AE12
PIN_AD12
PIN_AE22
PIN_AF22
PIN_W19
PIN_V18
PIN_U18
PIN_U17
PIN_AA20
PIN_Y18
PIN_Y12
PIN_D13
PIN_N2

Вам также может понравиться