Sunteți pe pagina 1din 132

Laboratory

Manual
Student Name: _____________________
Student Number: __________________

Semester 1, 2012

Components
Pack
Received

ELEC2141 Laboratory Manual


Welcome to ELEC2141. We hope you will enjoy this course. This course consists
of many components of which the laboratory is one of them. In this lab manual,
you will find all the information you need to complete your laboratory and gain
lab marks, which go towards your assessment. It is hoped that you will find this
manual informative, easy to read and of great use when completing the labs.
Much information has been provided to assist you with the activities and to
explain the phenomena which you will observe along the way. It is therefore
imperative that you spend some time before your laboratory session to read up
on what is required so as to make the most of the time available in the lab. Lab
demonstrators will be available to assist you with your work, however, it is
normally expected that students will be able to complete the labs just by
following the handbook and making sure they understand the information
provided. It is expected that each lab exercise will take one lab session to
complete. When you have completed the lab up to a checkpoint, you should add
your name to the marking sheet so that the lab demonstrators can come and
mark your work when they are ready. Be prepared to answer any additional
questions which may be based on the material you have read prior to the lab. If
you do not understand something, please ask. While working, it would be a good
idea to save your work and keep a copy of it in case the demonstrators do not
have the time to mark you in the class time allocated, or you need to refer to it in
a later lab. Other necessary resources such as datasheets have been placed in
appendices at the end of this manual as well as on the course webpage. Make
sure that you refer to them while working.

This laboratory manual was produced under the guidance of Nonie Politi. Major
sections of this document were written by George Lam and Gough Lui, and edited
by Nonie Politi.
1

Outcomes
The laboratory exercises are designed to enhance your ability in:

Extracting and interpreting information from datasheets.

Constructing combinational logic circuits with multiple inputs.

Constructing circuits using sequential logic.

Analysing and constructing Synchronous State Machines.

Using an Integrated Development Environment (IDE) to program and


implement circuits using FPGA hardware.

Constructing designs using a hardware description language.

Overview

Lab 0 Introduction to Breadboard Circuit Construction.

Lab 1 Working with Integrated Circuits.

Lab 2 Introduction to Xilinx ISE and Digilent Nexys.

Lab 3 Comprehensive Guide to FPGA Programming.

Lab 4 Flip-Flop Basics.

Lab 5 State Machine Basics.

Lab 6 Counters and 7-Segment Display (Part I).

Lab 7 Counters and 7-Segment Display (Part II).

Lab 8 Musical Logic (Part I).

Lab 9 Musical Logic (Part II).

Lab 10 Arithmetic-Logic Unit (ALU) Design.

Appendix A Digilent Nexys Board Reference Manual.

Appendix B Digilent Nexys Board Schematic.

Appendix C 7400 Series Datasheets.

Discrete ICs Used in This Lab

7400 (SN74HC00) Quad 2-Input Positive-NAND Gates.

7414 (SN74HC14) Hex Schmitt-Trigger Inverters.

7474 (SN74HC74) Dual D-Type Positive-Edge-Triggered Flip-Flops.

7486 (SN74HC86) Quad 2-Input Exclusive-OR Gates.

Laboratory Regulations
1. All laboratory users must undergo induction and agree to comply with
laboratory rules, plus they should read any required safety manuals.
2. No bare feet or exposed, open footwear ( e.g. sandals ) are permitted.
3. Food and drink are not to be consumed at any time in laboratories.
4. Under no circumstance is the 240v 50Hz mains power to be used for any
purpose other than that approved by the School. Only authorised
personnel are allowed to alter power connections (50v above) or connect
any equipment to mains power.
5. Tampering with or removal of laboratory equipment is strictly forbidden.
6. Data network connections should not be altered. Personal equipment may
not be connected to the School data network without first seeking
permission.
7. Personal mobile phones are not to be operated at any time within a
laboratory.
8. Students are expected to conduct themselves in a reserved manner at all
times. All noise is to be kept to a minimum.
9. All bags should be stored under benches.
10. Students should clean and tidy their workstations when they have
finished and return all leads before leaving the laboratory.
11. Faulty equipment should be reported to laboratory staff who may not
otherwise be aware of the problem.

Other Rules and Information

Take note and follow the laboratory regulations. Pay special attention to
the bolded sections. Students who do not comply with the regulations will
be asked to leave the laboratory.

Ten minutes before the end of the lab period, the marking sheet will be
closed off, and no further students will be accepted for marking. Students
still waiting for marking should wait patiently to be marked, while other
students should begin packing up their gear.

You are encouraged to keep a backup of your files. If you use a USB-drive,
please remember to take it with you at the end of the lab. Label your USBdrive with your name and student number, or place a file on the USBdrive so it can be returned to you in case you leave it behind.

Plagiarism of any form is strictly forbidden. Although healthy student


discussion of the laboratory material is highly encouraged, any blatant
copying of work will result in a zero mark for the entire laboratory
component.

Support files for labs that require them are placed at G:\labx where x is
the lab exercise number.

Marking Guide
Each checkpoint will be graded out of 5 possible marks as follows:
0 Checkpoint not attempted.
1 Parts of the exercise were completed.
2 Exercise completed but could not answer any of the questions.
3 Exercise completed and could answer few questions.
4 Exercise completed and could answer most questions.
5 Exercise completed and could answer all questions.
Note that in order to obtain full marks for a checkpoint, a full understanding of
the exercise and the underlying theory behind it is required!

Lab 0 Introduction to Breadboard Circuit Construction


In this laboratory, we will be constructing inputs and outputs for our digital
circuits onto breadboards. These will be used in future labs as an interface to the
Digital Logic Integrated Circuits.

Introducing Your Breadboard


Your breadboard is essentially a set of wires which have been arranged into a
pattern to allow easy solder-less prototyping of circuits. By slotting devices and
wires into the holes, you can make connections between terminals. The
breadboard is internally connected as follows:

We normally prefer that you hold the board as shown in the above orientation.
The two circles represent banana sockets or binding posts which are used to
supply power to the board. The eight horizontal strips are called buses. Wires
and components are simply put into the respective holes to make the
appropriate connections and can be removed and replaced as many times as you
like. Integrated circuits (ICs or chips) are placed across the break that runs
through the centre so they straddle the gap that runs across the middle of the
board.

Preparing Your Breadboard


If you have just purchased a new breadboard, there are a few things which you
might have to do to get it ready for use. If your breadboard was supplied with
banana sockets or binding posts, these should be securely fitted to the board first.
Then, these should be connected by a short piece of wire to the buses on your
breadboard. You may also choose to prepare some more short pieces of wire to
5

complete your buses. Usually the positive rail (normally coloured red) is at the
top and the negative rail (normally coloured black) is at the bottom. Your board
should look like this when it is prepared.

General Construction Hints


When building circuits on breadboards, please make sure you do the following:

Colour code your wires. Use standard colours red for Vcc, black for
GND, blue for inputs, yellow for outputs and green between chips. It will
make troubleshooting a lot easier.

Keep wires as short as possible so that they stay close to the


breadboard. This makes storing your circuit easier as well as the wires
are less likely to be pulled off in transport.

Be careful when stripping wires avoid stripping too much off the end
of the wire as this will leave exposed wire that could be a source of short
circuits later on. Try not to press too hard on the tool when stripping or
the wire may snap when you insert it into your breadboard.

Think ahead and try to construct the circuit in a smaller area of board.
This may make it easier for you to troubleshoot and maintain your design
as you wont have wires going everywhere.

Take care when handling integrated circuits most integrated circuits


are static sensitive and can be damaged by static charges accumulated by
your body from your clothing and from walking around. Before handling
integrated circuits, touch a large piece of grounded metal such as a
computer chassis and avoid handling the pins of the IC. Furthermore, the
6

pins on the IC are fragile, it is recommended you store them with care and
leave them plugged into your breadboard while in transit.

Producing Inputs to Digital Logic


Digital logic is often thought to be a binary state either a 1 or a 0, a high or a low.
The inputs to a digital circuit, however, are usually analog voltages which are
continuously variable. Commonly, a 1 is represented by a high voltage (e.g. close
to Vcc the supply voltage) and a 0 as a low voltage (e.g. close to GND the
ground rail voltage). In order to produce some input to our IC, we have to alter
the voltages going to the inputs of the IC. You have been provided four slide DIP
switches which we will use as inputs. These switches can be in one of two states:
an open circuit or a closed circuit.
But how are we to use these switches? Can you see a problem with the following
two possible designs? What happens when the switch is opened or closed?
Input to IC

Vcc

Input to IC

Ground

The problem with these two designs is that the value of the input to a digital
circuit is not known if the pin is left floating that is, unconnected. You cannot
automatically assume that the input to a digital circuit is 0 when it is
unconnected! As they are high-impedance inputs stray voltages from inside
the IC itself, or from adjacent inputs can cause unpredictable behaviour of inputs
which are left unconnected. Whenever building circuits with ICs, tie all the
unused inputs to an appropriate logic level to avoid problems while not
interfering with the operation of your circuit.
7

Instead of the suggested designs above, we will use this circuit here as an input
to our circuits:
Vcc

Input to IC

10k

Ground

The resistor is there to limit the current flow when the switch is closed,
otherwise we would have a short circuit! Make sure you can explain why this
circuit avoids the issues with the above designs!
Question: What electrical conditions need to be fulfilled so that the potential on
the input to the IC is equal to ground?

Displaying Output from Digital Logic


The output of the IC is a voltage either high or low. But how can we visualise
this so we know what is happening? You could measure the voltage with a
voltmeter or plot the output on an oscilloscope. However, in this lab we will be
showing the output on a Light Emitting Diode (LED).
An LED is a special form of diode that produces light when current flows through
it. Normally, LEDs have about 2v forward voltage drop and 20mA nominal
current to produce their rated output. If more voltage is applied, a larger current
flows which will cause thermal runaway and damage the LED. This means that
8

we cannot just connect the LED to the output, but rather we will have to put the
LED in series with a resistor that limits the current flow and prevents damage.
The output is thus constructed as shown below:
Output from IC

680

Putting it all together on a Breadboard


We now have to put all of this together on our breadboard. You have been
supplied with two different types of switches a four-way DIP switch and a
push-button. You should also find four LEDs, five 10k resistors, four 680
resistors, and a 100F capacitor.
While constructing these inputs and outputs, take care to colour code your
wires remember: red for Vcc, black for GND, blue for inputs, yellow for outputs
and green between chips. Also try to construct the circuits neatly, and as
compactly as possible preferably towards the left-hand side of the breadboard.
This will leave us room in the future to build up digital circuits using ICs in the
remaining area. By building it carefully, you will also save time by not having to
rebuild these interfaces in the future as they will stay on your breadboard for the
rest of the session.

We will begin by constructing four slide-switch inputs using the DIP switches,
and four of the 10k resistors. The DIP switch is essentially a block of four
individual switches combined into a single unit as you can see in the diagram
below.

ON
1

Physical View

Schematic Representation

Make sure you mount the DIP switch so that it straddles the centre ridge that
runs along your breadboard. You should have it mounted so that ON is upward
towards Vcc. Follow the schematic presented earlier for each input. Repeat for
each slide-switch to complete building all four slide-switch inputs. Keep things
neat by trimming the legs of your resistors as you go along. Keep the resistors as
flat as possible on the breadboard.
We will now construct another form of input one using a push-button instead
of a slide-switch. The principle is the same just that the wiring for the pushbutton is different.

Side View

Top View

Schematic Representation
Take notice that the push-button is not round all the way around its base. There
is a flattened side; this flattened side must run parallel to the buses on your
10

breadboard, otherwise the switch will not work! Use a resistor in combination
with the push-button as shown earlier in the schematic to build this input.
Now, we can construct our outputs by using an LED and an appropriate valued
resistor. Make sure you have oriented the LED the correct way as it will not light
up if reversed! The longer leg of your LED is the positive (anode) terminal, the
shorter leg is the negative (cathode) terminal. If you have cut the legs of your
LED, you can identify the polarity by looking for a flat surface around the base of
the LED. The flat surface is adjacent to the negative terminal.
Positive (anode) Leg
Negative (cathode) Leg

Longer Leg

Flat Surface

Trim the legs of your LED carefully so they sit flush to the surface of your
breadboard. Use the schematic presented earlier to produce one LED input, and
repeat to construct all four.
By now, you should have constructed a total of five logic inputs four slideswitches, and one push-button. You should have also constructed four LED
outputs. It should look something like the following:

11

In order to reduce noise and interference on the power supply as well as ensure
a stable voltage level, large capacitors, in the order of 10F 100F are often
placed across the power supply rails as illustrated below. This is a common
practice in all forms of electronics and one which students are encouraged to
follow. Therefore, connect the supplied 100F capacitor as shown in the diagram.
Make sure you place the capacitor in the right orientation with respect to its
polarity!

100F

Now, we can proceed to test the circuit. First we will test the slide-switch inputs.
Connect each slide-switch input to its own LED output. Connect your breadboard
to the bench-top supply by using the supplied leads in the laboratory. Use the
fixed 5v output on the right-hand side of the power supply. Switch on the power
supply and begin toggling the switches. You should see that when each switch is
toggled to the ON position, its respective LED lights up.
If thats not what you are observing, then its time for a bit of troubleshooting. If
there were no LEDs lighting up make sure that you havent neglected to
connect the Vcc side of each input or the ground side of each output. Make sure
that the LEDs are placed in the correct orientation as they are sensitive to
polarity, and that you have connected the power supply correctly. Check that the
power supply isnt indicating a short (the red LED on the power supply
indicating overload on the 5v fixed output should be off) and that you havent got
wires touching each other where they shouldnt be. If the LEDs are always lit
check that you have taken the switch input from the correct node you might
have accidentally connected the LEDs to Vcc directly, bypassing the switch. If
there is smoke, then it is likely that you have omitted a resistor and damaged
some component. You will probably need to identify which component had been
damaged and ask a demonstrator to replace it. If all else fails, ask a demonstrator
for assistance.
12

If the slide-switches are working correctly, proceed to disconnect one of the


LEDs from the slide-switches and instead connect it to the push-button. Now you
should observe that the LED lights up only when the push-button is pressed.
Show your working board to a demonstrator. Leave the constructed circuits on
your breadboard as you will need it for future labs.

Checkpoint 0.1

Assessor

Marks

END

13

Date

Lab 1 Working with Integrated Circuits


Integrated Circuits (ICs), commonly known as chips or microchips, are electronic
devices that contain a miniaturised circuit etched onto the surface of a thin
substrate of semiconductor material, such as Silicon. It allows for complex
circuits to be built into small packages, reducing their size, as well as enabling
faster operation and lower power consumption.
The basic mechanism of a digital circuit lies in the ability to turn an output on
and off. Since the invention of the transistor, this can be done using solely
transistors and other discrete passive elements. However, building these circuits
for fundamental logic operations is repetitive, tedious and inefficient. The
diagram below shows one possible implementation of a 2-input inverted AND
gate:

A few of these gates would have occupied an area of around the size of a business
card if constructed using individual discrete components. However, hundreds of
these circuits can be manufactured into an IC which is the size of a coin. This fact
alone allows great reductions in the size of finished circuits.

15

7400 series
The cost of the production overheads to manufacture just a single gate in its own
package is quite high. Therefore, it is not feasible to manufacture packages
containing individual gates, but rather IC packages with several gates of the same
type in them. The 7400 digital logic series of ICs features such a collection of
commonly used logical functions and some special purpose devices. These ICs
are readily available from hobbyist electronics supply stores such as Jaycar or
Farnell.
Each member of the 7400 series is identified by a part number beginning with
the digits 74, followed by the type number. For example, 7400 is type 0 of the
7400 series and it is a Quad 2-input NAND gate; 7427 is type 27 of the series and
it is a Triple 3-input NOR gate, and 74118 is type 118 of the series and it is a Hex
Set/Reset Latch.
Each type may be made up of multiple gates of the same type. For example, a
Quad 2-input NAND gate has four distinct 2-input NAND gates available while a
Hex Inverter has six inverter gates available.
A single type of IC may also come in a different speed or power consumption
level. This is indicated by the letters between the family prefix, 74, and the part
number. For example, 74LS00 indicates a low power Schottky version of 7400
while 74HC00 indicates a high speed CMOS variant.

16

The following table shows a list of just a few of the most commonly used types of
ICs in the 7400 series:
Part Number

Function

7400

2-input NAND Gates

7402

2-input NOR Gates

7404

Inverter

7408

2-input AND Gates

7432

2-input OR Gates

7474

D-Flip-Flop

7486

2-input XOR Gates

74157

1-bit 2-1 Multiplexer

74192

Decade Counter

74193

Binary Counter

Packaging
The following diagram shows the pin-out of the 7400 Quad 2-Input NAND IC:

The truth table may not be in a format that you are normally accustomed to,
using logic 0s and 1s this is because it is written in terms of voltage levels. H
stands for a High level voltage (typically 5v) which is equivalent to logic 1,
whereas L stands for Low level voltage (typically 0v) which is equivalent to logic
0. An X symbol stands for dont-care which can be either a 0 or a 1.

17

The pinout diagram above indicates the following:

Notch (or sometimes a dimple) This helps you orient the IC and locate
Pin 1.

Notch
Pin 1

Vcc This is the positive power supply rail (typically 5v).

GND This is the negative power supply rail (typically 0v).

Pin Labels This indicates the inputs and outputs of the logic gates the
number indicates which pins belong to which logic gate and the letters
represent the input and outputs as shown in the truth table.

The diagram below graphically represents how the gates within the IC are
connected to the pins.

Each type of 7400 series IC may have different number of pins a 7400 has 14
pins while a 7476 has 16 pins. However, the ICs from this series all come in
standard packages such as the Dual Inline-Package (DIP) or Small Outline
Package (SOP) as shown below. This allows for easy prototyping on breadboards
and populating onto printed circuit boards.

18

Dual-Inline Package (DIP)

Small Outline Package (SOP)

There are other types of standard IC packages such as Quad Flat Package, Quad
Flat No-lead, Grid Array, Ball Grid Array and Low Insertion Force Socket. The
package type is usually chosen by the manufacturer based on circuit
requirements, size, cost of production and ease of population.

Datasheets
A datasheet is a document summarising the performance and other
characteristics of a component (e.g. an electronic component), a sub-system (e.g.
a power supply) or software in sufficient detail to be used by a design engineer
to design the component into a system. Typically, a datasheet is created by the
component manufacturer and begins with an introductory page describing the
rest of the document. This is followed by listings of specific components, with
further information on the connectivity of the devices and their nominal
performance parameters and operational conditions. In cases where there is
relevant source code to include, it is usually attached near the end of the
document as an appendix or separated into another file.
An example of information which a datasheet may provide includes packaging,
pin layout, functionality, speed, power dissipation and operating conditions. See
the sample datasheets provided in Appendix C.

Basic Logic Gates


It can be shown that any logic function can be implemented using NAND gates
only. A NAND gate is simply an AND gate with its output inverted.

19

Example: Using one NAND gate from a 7400 IC, construct an inverter
More specifically, the output of the circuit should be the negation of the input:
A

Out

There are two inputs for a NAND gate. What should be done with input B?
The answer is that B can either be connected to Vcc (logic high) or to A, as
suggested by the NAND gate truth table.

Vcc

Out

Out

The last step is to draw up the connection of the circuit. Here, the pins for the
first gate (1A, 1B and 1Y) are used, with 1B connected to 1A and 1Y as the
output:

20

Exercise: Use two NAND gates to construct a 2-input AND gate


Begin by filling out the following truth table for an AND gate:
A

Out

Now compare the this truth table with the NAND gate truth table. What
additional logic should be applied to the output to obtain an AND gate? Draw the
logic diagram in the space below.

Construct the above circuit on a breadboard and verify that it follows the AND
gate truth table.
Question: If NOR gates are used to replace the NAND gates, a different logic gate
is implemented. What is the function of such logic gate?

21

Exercise: Use NAND gates to construct an XOR (Exclusive-OR) gate


The following circuit connection implements an XOR gate:

Fill in the following cascaded truth table to derive the truth table for an XOR gate:
A

Out

In your own words, describe the logical behaviour of the XOR gate as a function
of its inputs:

Construct the above circuit on a breadboard and demonstrate it to your assessor.


Question: If NOR gates are used to replace the NAND gates, a different logic gate
is implemented. What is the function of such logic gate?

Checkpoint 1.1

Assessor

Marks

22

Date

Multiple-input logic gates


There are situations where more than 2 inputs to a logic gate are required.
For example, a 3-input AND gate can be synthesised using two 2-input AND gates:

Out

Out

Likewise, a 3-input OR gate can be synthesised using two 2-input OR gates by


cascading the output of the first stage to the input of the next (i.e. replace the
AND gates with OR gates in the above circuit). The same can be done for an XOR
gate. However, this method does not work for NAND, NOR or XNOR gates, as
illustrated in the following exercise.

23

Exercise: Constructing a 3-input NAND gate


The following is the truth table for a 3-input NAND gate.
A

Out

Show that the following circuit does not implement a 3-input NAND gate by
completing the truth table for the following circuit.

24

Out

Exercise: With only 2-input NAND gates at your disposal, suggest a way to
modify the above circuit so that a 3-input NAND gate is implemented correctly.
Draw the logic diagram in the space below. Construct this circuit on your
breadboard and verify its operation.

Checkpoint 1.2

Assessor

Marks

END

25

Date

Lab 2 Introduction to Xilinx ISE and Digilent Nexys


In this lab and some of the following labs, we will be using the Digilent Nexys
development board equipped with a Xilinx Spartan3 FPGA. The term FPGA
stands for Field Programmable Gate Array. FPGAs are programmable ICs which
incorporate a large number of logic blocks and interconnects which can be
electronically switched (programmed) so as to wire up the logical blocks
together in a certain way in order to perform the function of a circuit normally
involving many logic gates and flip-flops. We can thus produce any circuit that is
a combinational or sequential function solely with an FPGA. There are many
types of FPGAs in the market, each differ in electrical and physical characteristics
such as speed, capacity and power consumption. The Digilent Nexys
development board offers numerous I/O interfaces integrated onboard, which
makes it ideal for an introductory course such as this one.
Throughout this lab, you will be exposed to the workflow involved in designing
digital circuits and programming FPGAs using Xilinx ISE, which you will be using
in future labs when working with the Digilent Nexys development board.

Downloading a Program to the FPGA


Downloading a program to the FPGA is very similar in principle to installing and
running an application on a computer. However, instead of an application, we
will take a pre-compiled design, load it and run it on the development board.
Begin by locating G:\lab2\directio.bit on the laboratory file server. Copy this
file into your personal working directory (Z: drive). Also ensure that you have a
Digilent Nexys board plugged to your computer before continuing. On your
Digilent Nexys board, locate the power switch (in the bottom left-hand corner)
and toggle the switch to the on position. The LEDs should light up indicating that
the board is ready for use.

27

Start Adept from the Start menu by selecting:


Start All Programs Digilent Adept Adept
You should see the following screen:

28

Click Browse to the right of the FPGA chip and locate Z:\directio.bit.

Click on the Program button. This will start transferring the bit-file onto the
board. During this process, be careful not to disturb the board.

Once this is complete you will see Programming Successful in the status box.

29

Your board is now loaded with a program that does the following:

The switches turn on the corresponding LEDs (e.g. SW0 turns on LED0).

The push-buttons turn on the corresponding 7-segment display. (e.g.


BTN3 turns on the leftmost 7-segment display, showing an 8 figure).

The decimal segment for the activated 7-segment display flashes at


around 1-2Hz.

Test that all of the switches and buttons work by toggling them on and off. If your
board does not behave as expected, ask a demonstrator for help.

Downloading Another Program to the FPGA Your Turn


Turn all eight switches to the off position. This time, copy the following bit file to
your personal working directory: G:\lab2\eleccool.bit, and download it onto
the FPGA in a similar way to the previous example.
Question: What do you see on the 7-segment display?
Turn SW0 on. What happens to the 7-segment display?

Drawing a Schematic in Xilinx


The Adept utility is only used to download compiled logic designs onto the FPGA.
In order to create and build new designs, we need to use Xilinx ISE.
We are going to implement a NOR gate with SW0 and SW1 as inputs and LED0
as the output. Start Xilinx ISE from the Start menu by selecting:
Start All Programs Xilinx ISE Design Suite 13.1 ISE Design Tools
Project Navigator
Alternatively, double-click on the Xilinx ISE Design Suite 13.1 shortcut on your
desktop.

30

Now we need to create a new project. To do so:


1. Select New Project under the Project Commands area; the New
Project Wizard appears. (Alternatively, select File New Project).
2. Enter Z:\lab2 in Project Location. The Working Directory field will be
filled out for you automatically. Please avoid creating projects under My
Documents on the lab computers as the files may be deleted on the next
system start-up . Optionally enter a description for your project.
3. Type mynor in the Project Name field.
4. For this project, choose Schematic as the Top-Level Source Type list.
5. Click Next to move to the device properties page.
6. Change only the properties in the table as shown below:

Family: Spartan3

Device: XC3S400

Package: FT256

Speed Grade: -4

Synthesis Tool: XST (VHDL/Verilog)

Simulator: ISim (VHDL/Verilog)

Preferred Language: Verilog

Leave all other boxes at default settings.

31

7. Click Next and then Finish to create an empty new project.


To create a blank top-level schematic:
8. Right-click in the Heirachy area inside the Design Pane near the top left
hand side of your screen and select New Source ...
9. Select Schematic as the source type.
10. Type in the file name mynor (same as the project name).
11. Verify that the Add to project checkbox is selected.
12. Click Next and then Finish.
Xilinx ISE now shows your newly created schematic file. You can close the
schematic by clicking on the x symbol in the tab bar just below the schematic
area or the one underneath the main title bar. After closing the schematic, you
will see the Design Summary screen:

On the upper left-hand side of the screen, locate the Heirachy view by clicking
on the Design tab. Double-click on mynor (mynor.sch) to open the schematic. If
it is already open, you will find it in the files tab bar just above the Console area
at the bottom of the screen. You can just click the tab to view the file.

32

To insert a symbol, we need to switch to the Symbols tab. Click on the tab to
switch the view.

Type nor2 under Symbol Name Filter.

33

Double-click on nor2 under Symbols (that begin with nor2). Move your
pointer to the right into the schematic design area. You should see that the
mouse cursor is now a cross, with a NOR symbol next to it.

Clicking on the screen inside the design area will place a NOR gate onto the
schematic. The symbol might be very small. Place your mouse cursor on the
centre of the circuit and press F8 to zoom-in until it is large enough to view
comfortably.

To draw a wire, press Ctrl-W or click on the pencil with a red line icon on the
left-hand side toolbar

the mouse cursor will change to a cross. Click on the

square at the end of one of the inputs. Move your cursor toward the left to extend
the wire, click once and press Esc to end.

Similarly draw a wire for the other input.

Now, press Ctrl-G or click on

button to add I/O markers. Click on the squares

at the end of the inputs and the output of the NOR Gate. The numbers on the

34

newly added I/O markers are random and you may get different labels. Press Esc
to stop adding more I/O markers.

Right-click on an I/O marker, for example XLXN_3 as on the above schematic.


Select Rename Port from the menu.

Rename the Branchs Net to A. Click OK.

Similarly, change the other input name to B and the output to Y.

The instructions thus far illustrate the basics of using schematic design such as
inserting symbols, connecting wires and adding I/O markers. Save and Close the
project.
35

Drawing a Schematic in Xilinx Your Turn


Start a new project named mypal, with the top-level schematic of the same name.
Draw the following on the schematic in Xilinx:

Save your work and show the schematic to a demonstrator.

Checkpoint 2.1

Assessor

Marks

Date

Simulation in Xilinx
Start a new project named mycomp, with the top-level schematic of the same
name. Draw the following on the schematic in Xilinx by selecting COMP8 in the
symbols tab. Rename the branchs bus by adding a New base name of Bus. Click
on Symbol Info when inserting COMP8 to open the datasheet for the block.
Write down what type of device this is in the space below:

36

Save your schematic by clicking on the Save button on the toolbar, or selecting
File Save and then close the schematic.

We would like to simulate the circuit in order to verify its correct operation. For
this purpose we need to create a test bench. Select Project New Source and
create a new Verilog Test Fixture. Name it mycomp_tbw. Click Next and select
mycomp to associate it with the schematic. Click on Next and then Finish. An
editor will open, presenting a Verilog Test Fixture with some code already filled
in. For the moment, we will only cover the basics of writing code in Verilog. You
will learn more detailed Verilog programming later in the course.
Verilog is a Hardware Description Language which can be used to build
implementations of digital logic circuits, as well as simulate them. We will be
writing a test bench (also known as a test fixture in Xilinx ISE) which allows us to
specify a set of signals to be input to the Unit Under Test (UUT otherwise known
as the circuit that you are testing, that is, the one you have associated your test
fixture with when you created it). We can specify values to be given to certain
input ports of our design, and specify delays between signal changes in order to
simulate and observe the result of our circuit.
Coding in Verilog is quite similar to programming in C. For the moment, we will
introduce you to a few key concepts which will allow you to write simple Verilog
test benches on your own.
Firstly, numbers are specified in Verilog in the format nBxxxx where n
represents the number of bits in the value, B represents the base and xxxx
represents the number in the specified base. For example 8 bits of 1 could be
notated as 8b11111111. Likewise, binary 1100 could be written as 4b1100.
Secondly, assignments can be made to inputs similar to C. For example, to assign
11111111 to A, you simply write A = 8b11111111; (to be accurate, this is
only valid inside a procedural block, as you will learn later in the course).

37

Thirdly, to specify a delay, use #xxxx; where xxxx represents the number of
time steps to delay for. The default time step is 1ns (configured in the
`timescale 1ns/1ps line). You will not need to change this. If a 500ns delay
is required, simply put #500; on a line of its own, and the simulator will delay
for 500ns when it reaches that line.
For your mycomp test bench, we want to have the following signals at the
following times:
Time (ns)

0 - 400

0b00000000

0b00000000

400 - 600

0b00010000

0b00000000

600 - 1000

0b00010000

0b00010000

Note that 0b in front of a number indicates that the number is specified in binary;
likewise, 0x in front of a number indicates that the number is in hexadecimal.
This is a programmers notation, which will need to be converted to the Verilog
notation stated earlier by specifying the number of bits explicitly i.e.
0b00010000 will become 8b00010000 and 0xA5 will become 8hA5.
In order to produce the above test pattern, we must code this into our test bench.
First of all, notice that under the // Inputs line, the inputs to our circuits are
defined as reg [7:0] A; and reg [7:0] B;. This means that our inputs
are A and B respectively, and each of them is a bus (input consisting of multiple
bits) numbered from 7 to 0 (from MSB to LSB). The reason our inputs are 8 bits
wide is because our unit under test is an 8 bit comparator.
For most of the test benches you will be writing, you will not need to concern
yourself too much with the code thats been provided. The code that is provided
simply does the tedious work of declaring your inputs, outputs and unit under
test what you are really concerned with is the section labelled Initialize Inputs.
It is under this section which all of the real simulating work is done.
Begin by commenting out the lines `ifdef auto_init and `endif by
adding // in front of them. Before // `endif, add end on a line of its own.
Now we can begin adding our signals to our test bench. Locate the line that says
38

A = 0; We want our signal to be 8 bits of zero, so change this to


A = 8b00000000; Similarly, change B = 0; to B = 8b00000000; This
condition is held for 400ns, so after the two lines, and on its own line, put #400;
Now, we repeat the same idea again, this time assigning appropriate values to A
and B and setting up another delay. This time, add A = 8b0001000; and
#200; There is no need to assign a new value to B as it stays constant
throughout this time. Continue by entering the appropriate lines for the last
condition.
After this, your Verilog test fixture should look like the following (lines in bold
indicate lines which were changed):
// Verilog test fixture created from schematic
`timescale 1ns / 1ps
module mycomp_mycomp_sch_tb();
// Inputs
reg [7:0] A;
reg [7:0] B;
// Output
wire EQ;
// Bidirs
// Instantiate the UUT
mycomp UUT (
.A(A),
.B(B),
.EQ(EQ)
);
// Initialize Inputs
//
`ifdef auto_init
initial begin
A = 8'b00000000;
B = 8'b00000000;
#400;
A = 8'b00010000;
#200;
B = 8'b00010000;
end
//
`endif
endmodule
39

Save your test fixture, and close the file. Now we are ready to begin simulating.
Make sure that you are in the Design tab on the left-hand side, and choose the
radio button for Sources to be Simulation (this is near the top).

Click on the test bench file (mycomp_mycomp_sch_tb) once to select it and then
go to the Processes pane just below, right-click Simulate Behavioral Model
and choose Process Properties. Make sure the Simulation Run Time is set to
1000ns (or any desired value in future simulations). Click OK.

40

Now, we need to verify that our simulation file is valid that is, its syntax is
correct. To do so, double-click on Behavioural Check Syntax in the Processes
pane. If the file is okay, you will get a green tick next to the line; if it is not, you
will get a red cross. If you do get a red cross, double-click on your test bench file
and inspect it carefully, correct any errors and save it. The red cross will change
into an orange question mark to indicate that you must re-run the process. Once
you have a green tick, you may proceed to double-click on Simulate Behavioral
Model which will bring up ISim Simulator. After a while, the simulation result
will be displayed. By default, you will only see a limited view of the simulation as
the time scale is zoomed in. Right-click in the black area and select To Full View
to see all of your simulation. Your result should be similar to the image below.
Note that the order of the signals displayed may be different.

From the result, we have verified that EQ is 1 when both numbers, each
represented by 8 bits, are equal to each other and 0 otherwise. Remember to
close the simulation when you are done. You can always re-run the simulation by
selecting Sources for Simulation, selecting the appropriate test bench file and
double-clicking on Simulate Behavioural Model.
41

Simulation in Xilinx Your Turn


Start a new project named mycompm, with the top-level schematic of the same
name. Draw the following on the schematic in Xilinx:

Using the datasheet for the symbol, determine the value of GT and LT for the
following inputs:
A

0x10

0x00

0x10

0x10

0x10

0x20

GT

LT

Write a test bench to test the above conditions. You should hold each signal for
100ns. Your demonstrator will check your simulation result against the above
table.

Checkpoint 2.2

Assessor

Marks

END

42

Date

Lab 3 Comprehensive Guide to FPGA Programming


In the previous lab, step-by-step instructions were provided to help you start
designing simple circuits. In this lab, we will give you an insight into the internal
processes that Xilinx ISE uses to produce implementations for the FPGA.

Compiling a project for downloading to the FPGA


During this lab, we will explore the complete process of digital logic design from
scratch from a bunch of gates, to compiling a design file ready to be
programmed onto the FPGA.
For this project, we will interface four sets of 2-input XOR gates with 8 switches
on the board. This project is split into two stages: developing the design on the
computer and downloading the design to the board.
The first stage requires the use of Xilinx ISE, so load the program on the
computer.
The next step is to create a new ISE project targeted for our FPGA device. For this
exercise, create a new folder called lab3 under your home drive and call the
project four_xor. There are hundreds of FPGA models in the market, and a
design compiled for one type may not work directly on another device without
modification. Xilinx simplifies this problem by applying device specific
constraints and optimisation appropriate for the FPGA we are targeting.
The Xilinx FPGA is categorised in terms of its family, its device type, its packaging
and its speed grade. FPGAs from different families differ in overall performance
and cost. The one used in this lab, a Spartan3, is a low cost FPGA. Another family,
called Virtex, is designed for higher performance and is generally more expensive
than the Spartan3 equivalent.

43

Different device types within the same family usually have a different number of
logical blocks which are used to implement logic cells, optimised multiplication,
memory and I/O pins. The XC3S400 used in the lab has about 400,000 gates with
a capacity of 8,000 logic cells large enough for a medium size design.
The physical package affects the number of I/O pins the device has and thus the
amount of devices that are able to connect to it. The FT256 package that the
XC3S400 comes in has provision for 173 I/O pins. The speed grade indicates the
maximum switching rate of the device. The lower the speed grade, the faster the
device can operate, and therefore, the faster the implemented circuit can be used.
This is of importance when implementing circuits which run at high clock speeds.
As an example, a grade -6 device has a shorter switching time compared to a
grade -4 device. For more details about the FPGA we are using, refer to its
datasheet available on the Xilinx website.
The next step is to add a top-level design. The top-level design specifies how the
logic gates themselves are to be connected together to create the final project. It
can be either a schematic (drawing) or a Hardware Description Language file
(coding). The principle is that the same design can be ported to a different
hardware by only changing the mapping of the nets in the design to the pins on
the device (by using a constraints file) without redesigning the underlying
functionality of the project. It is easier to conceptualise how each subsystem
interacts with each other using a schematic than it is using a HDL file, which is
why we elect to use top-level schematic. Xilinx automatically recognises a
schematic with the same name as the project to be the top-level design when
creating a new project.

44

The top-level schematic is indicated by the three-squares icon next to the module.

Now we have to insert the symbols that will be used in the design. We will
implement four parallel 2-input XOR gates. While we can use the Xilinx symbol
xor2, we are going to design our own, in order to illustrate how we can create
customised modules. First, we add a new schematic to the project.
1. Select Project New Source from the menu bar.
2. Select Schematic as the source type.
3. Type in the file name myxor.
4. Verify that the Add to project checkbox is selected.
5. Click Next and then Finish. You will be presented with myxor.sch, which
is currently blank.

45

In the schematic editor, we can place as many symbols as we require. In this case,
we will put four NAND2 blocks on the schematic, arranged as shown:

What we have done is to create many instances of the same NAND2 symbol.
Xilinx identifies each instance by a unique name. We connect instances together
using wires (otherwise known as nets).

Essentially, we have described a netlist in a pictorial form. A netlist stores the


connections between different instances within a design. A netlist may show
illegal net connections (e.g. two outputs connecting together). It is up to the
compiler to recognise and resolve such problems at a later stage.
Now we add I/O markers to the design. I/O markers specify the inputs and
outputs of the module. This is needed for every schematic as they are either used
as modules in another schematic or as a top-level design. Before adding the I/O
markers for A and B, draw short wires (to connect the I/O markers) from the
corners of the wires connected between the first NAND2 gate as shown in the

46

diagram. If you do not do this, you may get a warning that I/O markers can only
be connected to branch end-points. Label the inputs A and B, and the output Y.

This concludes the creation of our myxor module. Make sure you save and close
the schematic. The next step is to verify the design by simulation. Create a
Verilog Test Fixture for myxor and name it myxor_tbw. It is a convention to
name the test bench with the design name as the prefix and tbw as the suffix.
Make sure that you have chosen to associate the source with myxor and not
four_xor. The Verilog Test Fixture is automatically opened for editing, as before.
Next we need to decide the duration of the test. The test bench should check all
possible inputs for a logic design or boundary cases for an arithmetic design.
There are 2 inputs for each of the XOR gates; hence there are 4 different
combinations of inputs we need to test. Each input requires 100ns to simulate
under ISim (the simulator we are using). In addition we need 100ns for an initial
signal value.
The following are the suggested waveforms to test all combinations:

Time (ns)

0 - 100

100 - 200

200 - 300

300 - 400

400 - 500

47

The above uses Gray Code sequence to test the logic by changing one input at a
time. The reason for this choice is because in reality no two signals change
simultaneously and by using this sequence, we can ensure that only one signal
changes at any given time, avoiding unexpected results. We can therefore code
this into the Verilog Test Fixture as we did in Lab 2. In order to produce an
unknown value, we can use A = 1bx; which represents a 1 bit unknown.
Follow similar steps to produce the suggested simulation. Make sure you save
your file when complete.
Behavioural simulation checks the logical output of the design, assuming there
are no propagation delays through the logic gates. It is a useful tool to check if
the design has been implemented correctly in the functional sense. To begin, first
we have to switch to simulation mode. Under Sources, select the Simulation
radio button. Click on myxor_tbw the test bench we have just made.

48

In Xilinx ISE, the simulation time must be set manually. To do this, expand ISim
Simulator tree in the Processes view, right-click on Simulate Behavioural
Model and select Process Properties

Change Simulation Run Time to 500ns. Click OK. Now double-click on


Behavioural Check Syntax. You should get a green tick if not, check your
Verilog file. Once you have gotten a green tick, you can double-click on Simulate
Behavioural Model. In a moment you will see a green on black screen with the
simulated result.
Verify that Y is indeed giving a logic 1 when only one of A or B is 1. Once you
have finished verifying, close the simulation by closing the ISim program. You
will have to terminate the simulation if you want to change the testbench file as
well, otherwise you may not be able to save the file. Show the simulation result
and your Verilog Test Fixture to your demonstrator.

Checkpoint 3.1

Assessor

Marks

49

Date

The next step is to create a symbol out of this schematic. A symbol of the design is
needed before it can be used in another schematic, in our case, the top-level
design. To create a symbol, make sure you are in Sources for Implementation.
Click once on myxor (the schematic we want to make a symbol for) to select it,
then go to the Processes pane (just below) and double-click on Create
Schematic Symbol. You should see the message Process Create Schematic
Symbol completed successfully in the Console window at the bottom of your
screen when this is complete.
The final step is to prepare the design for testing on the FPGA. We are going to
use four myxor symbols and map them to the 8 switches and 4 LEDs on the
board. Open the four_xor schematic and draw in the following:

You will be able to find your newly created symbol under the Categories submenu: click on the one labelled <Z:/lab3/four_xor> (or similar) and you should
find that myxor is available under Symbols. Click on myxor in the Symbols area
and place them onto the schematic. Note that sometimes, a newly created symbol
may not appear in the symbols panel for selection. You can usually remedy this if
you first click in a blank area of the schematic where you intend to place this

50

symbol, and then returning to the symbols panel. This will refresh the list of
symbols, allowing you to select any newly created symbols. If you still have
trouble, you may need to restart Xilinx to get it working.
You now need to specify which marker corresponds to which physical pin on the
FPGA. Pins on FPGA are grouped into banks. Each bank is denoted by a letter, and
each pin in a bank is numbered from 1 to 16. For example L15 refers to pin 15 of
bank L. Some pins may be Vcc or GND, some may be clock input only, some may
be bidirectional and so on. Refer to the manual given in Appendix A for a
comprehensive description of all the pins.
We need to create a constraints file to tell Xilinx where we want the nets
connected to. To do this, go to File New and select Text File. You will be
presented with a blank text file. Click on File Save As and name it as
four_xor.ucf and click Save. By naming this file with the same name as the toplevel schematic, Xilinx knows to associate it with the top-level schematic when
we import it later.
Next, locate where the I/Os are connected. We are going to map the 8 switches
and 4 LEDs using the pin location table from Appendix A:

Net Name

Pin

Net Name

Pin

SW0

N15

LED0

L14

SW1

J16

LED2

M14

SW2

K16

LED4

N14

SW3

K15

LED6

P14

SW4

L15

SW5

M16

SW6

M15

SW7

N16

In the constraints editor type the following, which corresponds to the above pin
mapping:
51

NET "LED0"

LOC = "L14";

NET "LED2"

LOC = "M14";

NET "LED4"

LOC = "N14";

NET "LED6"

LOC = "P14";

NET "SW0"

LOC = "N15";

NET "SW1"

LOC = "J16";

NET "SW2"

LOC = "K16";

NET "SW3"

LOC = "K15";

NET "SW4"

LOC = "L15";

NET "SW5"

LOC = "M16";

NET "SW6"

LOC = "M15";

NET "SW7"

LOC = "N16";

Then, save the UCF file. Right-click in the Design pane and choose Add Source
Select four_xor.ucf, click Open, and then click OK to associate it with the project.

Design Synthesis
Synthesising the design means expressing all the schematics and any other
modules used into netlist files. Netlist files provide information on the design of
the modules (and their instances) and their relation (how they are connected
together).
To synthesise the design, select four_xor in the Sources view, and make sure
that Sources for Implementation is selected (and not Simulation). Next in the
Processes pane, double-click on Synthesize XST. The icon to the left of this
line should start animating. After a minute or two, you should get a green tick on
the left if you had followed the steps correctly. If you do not get a green tick,
check the Console tab at the bottom of your screen to see what warnings and/or
errors appear and try to correct them before trying again. Contact your lab
demonstrator if unsuccessful.

52

Design Implementation
There are three steps in the implementation stage: translate, map and place &
route.
The Translate process merges all of the netlist files and design constraints to
produce a Xilinx native generic database, which describes the logical design
reduced to Xilinx primitives. The Map process maps the logic defined during
translation into FPGA elements, such as logical blocks and I/O buffers. The
output design is a native circuit description file that physically represents the
design mapped to the components in the Xilinx FPGA. The Place & Route
process then produces an arrangement for the components within the FPGA and
describes how each of the components are interconnected via common
connection lines and how the pins are connected to the components.
To implement the design, make sure four_xor is still selected in the Sources
view, and we have chosen Sources for Implementation. Next in the Processes
view double-click on Implement Design. If the icon turns into a red cross or
orange question mark, then you can expand this item to see which of the

53

processes failed. If you have a problem, check the warnings and errors in the
Console tab at the bottom of your screen to get a hint to what the problem might
be. Contact your lab demonstrator if you still do not get a tick.

Programming File Generation


The Generate Programming File process produces a bitstream file for Xilinx
device configuration. After the design is completely routed, you must configure
the device so it can execute the desired function.
First set the FPGA start-up clock which is specific to this board. Right-click on
Generate Programming File under Processes view. Choose Process
Properties, and then click on Startup Options in the left-hand pane and select
JTAG Clock on the right for FPGA Start-Up Clock. Click OK.

54

You are now ready to compile your first bit-file. Double-click Generate
Programming File and wait until the Console view at the bottom of the screen
shows the completion message:

The generated bit file, four_xor.bit, will be located in the same folder as the
project. Download your design to the FPGA using the Adept utility (in a similar
way to the method used at the beginning of Lab 2). Verify the operation of the
XOR gates by using the switches and the LEDs. Show this to your demonstrator.

Checkpoint 3.2

Assessor

Marks

END

55

Date

Lab 4 Flip-Flop Basics


A storage element is a circuit which can maintain a binary state indefinitely
(while the circuit is powered). This is essentially memory, allowing us to store a
single bit. There are many ways to do this, including using a capacitor to store
charge, like DRAM in modern computers, or using feedback logic circuit. They
differ in terms of layout density, speed, power-consumption and complexity. In
this lab, we will focus on the feedback logic circuit type of storage element.
The binary information stored in these elements at any given time defines the
state of the circuit at that time, which can be changed by an input signal. The
most basic storage elements are latches, from which flip-flops are usually
constructed.
For the rest of this lab, we will adopt the /X notation as an alternative to the
overbar notation, to denote a variable negation.

SR-Latch
The simplest storage element is a latch. A latch has the ability to hold an input
state. An SR-Latch is a circuit with two cross-coupled NAND gates or two crosscoupled NOR gates. It has two useful states: the Set and Reset states. The two
outputs of the latch are normally complements of each other. However, when
both inputs are 1 (in an SR-Latch built with NOR gates) or 0 (in an SR-Latch built
with NAND gates), an undefined state with both identical outputs may occur.

57

Exercise: Operation of NAND SR-Latch


The following is the logic diagram for a SR-Latch built with NAND gates:

Build this circuit on your breadboard. Connect the inputs to switches and the
outputs to LEDs. Fill in the following truth table by testing out different input
combinations and recording the values of Q and /Q.

/S

/R

58

/Q

Verify the truth table using the given circuit by reading the outputs for the
waveform below:
/S
/R
Q
/Q

Exercise: Operation of SR-Latch with Control


The following is the circuit for SR-Latch with Control using four NAND gates:

Begin by answering the following questions:

If the CONTROL signal is 0, what are the values of /S and /R?

If the CONTROL signal is 0, are the values of /S and /R dependent on S


and R respectively?

59

Construct the circuit and verify its operation. Be ready to demonstrate the circuit
to your lab demonstrator.

Checkpoint 4.1

Assessor

Marks

Date

For the remainder of the lab, the following symbol will be used to denote a SRLatch with Control:

Exercise: Operation of a D-Latch


The following is the circuit of a D-Latch using a SR-Latch with Control and a
single inverter:

60

Construct the circuit and complete the following waveform diagram:


CONTROL
D
Q
/Q
What is the benefit of using a D-Latch over SR-Latch?

For the remainder of the lab, the following symbol will be used to denote a DLatch:

Flip-Flop
The output of a flip-flop can only change on the rising or falling edge of the
control signal. This change in control signal is called a trigger and it enables, or
triggers, the flip-flop. Triggering is achieved by having a D-Latch connected backto-back with an SR-Latch with complementary control lines. The idea is to use
the first D-Latch to capture the input at the moment the control signal switches
state and use the second SR-Latch to hold this state while the control signal
switches back. Essentially, this triggering only allows the state to change when
the control signal changes.

61

Exercise: Operation of a D-Flip-Flop


The following is the circuit of a D-Flip-Flop constructed using a D-Latch, an SRLatch with Control and a single inverter:

Fill in the following diagram showing the outputs that appear as a result of the
inputs shown:
CLOCK
D
Q
/Q
Flip-flops can change their state on either the rising-edge (or positive-edge) or
the falling-edge (or negative-edge) of the clock input, as illustrated below:
Rising Edge Type

Falling Edge Type

Clock Signal
Output

Construct the above circuit by combining two D-latches built with NAND gates.

62

Is the constructed D-flip-flop positive-edge triggered or negative-edge triggered?

How would you modify the circuit to obtain the other triggering type?

How many NAND gates would you need to construct a D-flip-flop if everything
was to be constructed with NAND gates only?

Demonstrate your circuit to your lab demonstrator.

Checkpoint 4.2

Assessor

Marks

END

63

Date

Lab 5 State Machine Basics


An application of a sequential logic circuit is to generate a fixed sequence of
numbers for simulation purposes. These numbers are usually generated based
on the previous output values of the circuit. A Linear Feedback Shift Register
(LFSR) is one method of generating a sequence of uniformly distributed random
numbers which can be implemented using integrated circuits.
The following symbol is used to denote a D-flip-flop:

Linear Feedback Shift Register (LFSR)


A register is typically a set of D-flip-flops with a common clock input. Multiple
bits are simultaneously stored at the same clock tick. A shift register is where the
output of one D-flip-flop becomes the input of the adjacent D-flip-flop. Registers
can be used for other applications besides simply storing bits. They are often
used to circulate, or shift values among storage elements. A special class of shift
registers is the Linear Feedback Shift Register (LFSR). Linear feedback shift
registers are n-bit counters exhibiting pseudo-random behaviour while using
simple circuitry. They have many applications, including in data communications,
computer graphics and pseudorandom number generation.

65

Consider the operation of the LFSR counter shown above. When the flip-flops are
all zero, it does nothing. Every Q output is zero, the feedback path is zero, and the
output of the XOR is zero, so the LFSR stays in this state. When a 1 is introduced,
the circuit counts through 24 - 1 = 15 different non-zero bit patterns. You can
build a similar circuit with any number of flip-flops, although you may need more
XOR gates. The table of primitive polynomials, given below, can be used to design
these circuits.

x2 + x + 1

x10 + x7 + 1

x18 + x11 + 1

x26+ x6 + x2 + x + 1

x3 + x2 + 1

x11 + x9 + 1

x19 + x6 + x2 + x + 1

x27+ x5 + x2 + x + 1

x4 + x3 + 1

x12 + x6 + x4 + x + 1

x20 + x17 + 1

x28 + x25 + 1

x5 + x3 + 1

x13 + x4 + x3 + x + 1

x21 + x19 + 1

x29 + x27 + 1

x6 + x5 + 1

x14 + x5 + x3 + x + 1

x22 + x21 + 1

x30 + x6 + x4 + x +1

x7 + x6 + 1

x15 + x14 + 1

x23 + x18 + 1

x31 + x28 + 1

x8 + x6 + x5 + x4 + 1

x16 + x15 + x13 + x4 + 1

x24 + x23 + x22 + x17 + 1

x32 + x22 + x2 + x1 + 1

x9 + x5 + 1

x17 + x14 + 1

x25 + x22 + 1

The rules for building a k-bit LFSR are simple. Number the flip-flops starting
from D1 on the left. The feedback path comes from the output of the end XOR
gate. Find the primitive polynomial of the form xk + + 1 in the table above. For
every xi term present in the polynomial, the ith flip-flop output feeds an XOR
input in the feedback chain. The right-most 1 in the polynomial (which stands for
x0) is an exception and does not need to be accounted for.
Note that we have deviated from our standard flip-flop numbering convention
(where we start numbering from D0) as starting from D1 produces a nice
correspondence between the flip-flop numbers and their respective polynomial
terms.

66

Exercise: State Transition Table


For the LFSR with polynomial x4 + x3 + 1, calculate the output of the XOR gate for
each of the following states, and hence the value for the next Q1. Express the next
state (Q4 - Q1) as a decimal state number.

Current State

Next State

Dec

q4

q3

q2

q1

10

11

12

13

14

15

Q4

Q3

Q2

Q1

Dec

Using the above state transition table, write the state sequence starting from 15:
15

67

15

Exercise: Implementing the LFSR using ICs


The LFSR will be constructed using two 7474 Dual D-flip-flop ICs and a 7486
Quad XOR Gate IC. The D-flip-flop comes with active-low preset and clear pins,
which will be used to initialise the state of the register.
Referring to the diagram above, and the datasheet for the 7474 (given in
Appendix C), connect two 7474 ICs together in an appropriate manner. Also
connect one of the XOR gates from the 7486 package as needed for the circuit.
Collect all the PRESET lines from each of your flip-flops and wire them to the
output of a slide-switch. Likewise, collect all the CLOCK lines from each of your
flip-flops and connect them to the push-button. Last, collect all the CLEAR lines
and connect them to Vcc. For the outputs, connect Q1, Q2, Q3 and Q4 to the
LEDs.

Exercise: Verifying the LFSR as implemented in a circuit


Make sure the CLOCK push-button is not pressed (i.e. the CLOCK signal is LOW).
Initialise the circuit by applying the active-low PRESET signal: set the PRESET
switch to LOW and then back to HIGH. Leave the switch in the HIGH position.
What is the value of the LFSR? Write the decimal value of the output.

According to your state transition table, what do you expect the next value to be?

68

Now toggle the CLOCK by pressing and releasing the push-button. A toggle on
this button applies a clock signal to the flip-flop. What is the value of the LFSR? Is
this what you expected?

Checkpoint 5.1

Assessor

Marks

Date

If you are not getting what you expect the reason is that when a push-button
switch is pressed, it does not simply open or close cleanly. Instead, the contacts
inside the switch bounce off one another, causing multiple pulses to appear on
the clock line, which is interpreted as a clock signal, advancing the LFSR several
states every time the button is pushed. The following diagram illustrates this:
Voltage
5v

High (Logic 1)
Undefined
Low (Logic 0)

0v
Button
Pressed

Button
Released

Time

Logic Input
HIGH
LOW
Time

69

Debouncing the Switch


A debounce circuit is used to eliminate the extra pulses due to the bouncing of the
contacts in the push-button switch. The circuit below shows such a debounce
circuit. This circuit comprises of a resistor-capacitor based (RC) filter and a
Schmitt trigger buffer. The buffer is required to isolate the filter circuit from the
inputs to the gates. If the buffer is not present, the filter capacitance adds with
the input capacitance of all the gates. This capacitance is too large to
charge/discharge and as a result the clock does not work.
Vcc

R1
Input to IC

R2

Ground

RC Filter
The RC filter works by introducing a delay. The delay is achieved through the
charge/discharge time of the capacitor. While charging/discharging, the input
voltage level does not swing past the logic voltage threshold on the short pulses
produced by the bouncing of contacts.

Schmitt Trigger
The Schmitt Trigger is a type of circuit that asserts its output high when its input
exceeds a particular threshold value. The output will be asserted low only when
a second, lower threshold level is reached. Schmitt triggers employ hysteresis in

70

order to accommodate several transition conditions. The operation of the


Schmitt trigger is best described with the diagram below which shows the input
vs. output for a non-inverting Schmitt trigger. The arrows indicate the transition
direction.

Output (v)
(V)

5
2.5

5 Input (v)

2.5

Schmitt triggers are commonly used in debouncing circuits because the


hysteresis prevents transitional changes unless the lower or upper thresholds
are reached. Thus, the effects of switching noise are greatly reduced. The symbol
for the Schmitt trigger is given below. Schmitt triggers come in both noninverting (left) and inverting (right) types.

Exercise: Debounce Circuit


Construct the debounce circuit above for your switch. Use R1 = 680, R2 = 10k
and C = 1F (notice that R2 is, in fact, already connected as your switchs pulldown resistor). What is the charge time of this circuit? Can you suggest a method
to determine the minimum charge time required to absorb the bouncing effect of
the switch?

71

Does the LSFR follows the truth table now?

What might happen if we made the charge time very long? What about if we
made it very short?

Demonstrate it to a lab demonstrator after you have verified your design.

Checkpoint 5.2

Assessor

Marks

END

72

Date

Lab 6 Counters and 7-Segment Display (Part I)


Assumed Knowledge

You are able to create a project in Xilinx ISE.

You are able to draw schematics in Xilinx ISE.

You are able to simulate a design in Xilinx ISE.

You know how to synthesise and implement a design in Xilinx ISE.

You know how to assign nets to the pins of the Nexys board in Xilinx ISE.

You know how to download a design onto the Nexys board via Digilent
Adept.

Outcome
In this lab and the next lab, you will design and implement a 4-bit timer, clocked
at around 1Hz, and display the time on the 7-segment LED displays.

Binary Counter
A counter is a digital circuit which stores the number of times the clock signal has
been toggled. There are many types of counters: binary, decade, modulo-n,
Johnson, and so on. They each differ in their output sequences, but are all
fundamentally similar.
The most basic counter is a 1-bit counter. It is essentially a D-flip-flop connected
as a Toggle flip-flop. Because the D-flip-flop triggers once per clock cycle, the
output toggles at half the frequency of the clock signal (make sure you
understand why!). It should also be noted that regardless of the duty cycle of the
clock signal, the duty cycle of the output clock will be 50% provided the input
clock frequency is constant.

73

Feedback Loop
D

Input Frequency
fIN

Output Frequency
f/2

>
/Q

Input Frequency

0
1

Output Frequency

If we represent a 1-bit counter as a divide-by-2 block, we can cascade the blocks


together by using the output of a previous stage to clock the next stage. In this
way, we can make a divide-by-4 or divide-by-8 and so forth counter.

QA

QB

f/2

D
Clock

>

Pulse

f/4

>
/Q

QC
f/8

Q
etc

>
/Q

/Q

The count held by this counter is read in the reverse order from the order in
which the flip-flops are triggered. Thus, output QC is the high order bit of the
count (most significant bit, or MSB), while output QA is the low order bit (least
significant bit, or LSB). The count held by the counter is then read as CBA, and
runs from 000 (decimal 0) to 111 (decimal 7). This is a 3-bit binary counter or
modulo-8 counter.
Cascading 1-bit counters up in such a fashion creates a ripple counter. One
problem with the ripple counter is that the output does not change coherently.
For example, when changing from 011 (decimal 3) to 100 (decimal 4), the
74

counter first changes the LSB, and at this moment the output becomes 010
(decimal 2) before the second stage D-flip-flop sees a new input and toggles to
become 000 (decimal 0) and finally the third flip-flop will then see a new input
and cause the output to flip over to 100 (decimal 4).
This causes no problem if the output is only to be read by human eyes the
ripple effect is too fast for us to perceive. However, if the count is to be used by
other digital circuits (such as a multiplexer or demultiplexer), the ripple effect
can cause unexpected circuit operation.
In order to prevent this, we need to be able to cause all of the flip-flops to change
state at the same moment. This is known as a synchronous counter.
The diagram below shows an implementation of a 4-bit synchronous counter.

75

Exercise: 4-bit synchronous counter


Xilinx provides an implementation of the 4-bit synchronous counter as a module.
In this exercise, you will familiarise yourself with the existing modules by
reading the supplied datasheets.
Firstly, create a new project called counter. Name the top-level schematic as
counter. Insert a CB4CE symbol on the schematic. To open the datasheet for the
CB4CE, right-click on the symbol and select Symbol Symbol Info. Write down
what each of the pins on this module do:

Interface the symbol with the following I/O markers as shown in the diagram:

76

We are going to connect the I/O markers to the I/O pins on the development
board with the same label. Create a UCF file (counter.ucf) as before with the
following constraints:
NET "LED0"

LOC = "L14";

NET "LED1"

LOC = "L13";

NET "LED2"

LOC = "M14";

NET "LED3"

LOC = "L12";

NET "LED7"

LOC = "R16";

NET "SW0"

LOC = "N15";

NET "SW7"

LOC = "N16";

NET "PB0"

LOC = "J13";

NET "PB0"

CLOCK_DEDICATED_ROUTE = FALSE;

You will notice that there is one extra line which you havent seen before the
last one. This line has been inserted into the UCF file to downgrade a compilation
Error message into a Warning message. In FPGAs, there are certain pins which
contain dedicated paths and can be used to distribute clocks throughout all the
logic units inside the FPGA with minimal delay. However, we wish to clock our
design from a push-button which is not connected to one of these pads due to the
design of the development board, which causes a sub-optimal delay that Xilinx
perceives as an error. By adding this line in, we are telling Xilinx that we dont
need a dedicated path for the Clock, thus allowing our design to be routed
successfully albeit with a warning instead of an error.
Next, we will create a Verilog Test Fixture for this project. The simulation will set
SW0 as 1 throughout the simulation to enable the counter. It will begin by
initially resetting the counter to 0, by setting SW7 to 1 for the first cycle and 0 for
the remainder of the simulation. It will also set PB0 to oscillate. Run this
behavioural simulation on the design for 20 clock periods, or 4000ns.

77

This Verilog Test Fixture makes use of syntax which you may not yet be familiar
with. The forever keyword is used in this Verilog file to create a loop that runs
forever to generate our PB0 clock input. The begin and end keywords specify a
block of procedural statements that run one after the other in sequence.

// Verilog test fixture created from schematic


`timescale 1ns / 1ps
module counter_counter_sch_tb();
// Inputs
reg SW7;
reg PB0;
reg SW0;
// Output
wire LED0;
wire LED1;
wire LED2;
wire LED3;
wire LED7;
// Bidirs
// Instantiate the UUT
counter UUT (
.SW7(SW7),
.PB0(PB0),
.LED0(LED0),
.LED1(LED1),
.LED2(LED2),
.LED3(LED3),
.LED7(LED7),
.SW0(SW0)
);
// Initialize Inputs
//
`ifdef auto_init
initial begin
SW7 = 1b0;
PB0 = 1b0;
SW0 = 1b0;
#100;
SW7 = 1b1;
SW0 = 1b1;
#100;
SW7 = 1b0;
forever begin
78

PB0 = 1b1;
#100;
PB0 = 1b0;
#100;
end
end
//
`endif
endmodule
Answer the following questions:

Which of the LEDs shows the least significant bit (LSB)?

Which of the LEDs shows the most significant bit (MSB)?

What is the purpose of the CEO output (shown on LED7)?

Based on the datasheet, what would happen to the outputs if input CE is 0


for the duration of the simulation?

Now generate a programming file for this counter and load it to the FPGA. You
will get a yellow exclamation mark that symbolises a warning, however, this is
not a problem for this design as we have explained earlier. Verify the design by
setting SW0 and SW7 to the appropriate values before you press PB0. Note that
PB0 might exhibit the contact bounce phenomenon as discussed in the previous
lab. If this happens, try pressing and releasing the push-button gently.

Binary-Coded Decimal (BCD) Counter


Binary counters are the simplest device which can be used to count clock pulses.
However, there is no simple way of displaying the count value in decimal format.
Because of this fact, the binary-coded decimal (BCD) counter is commonly used
instead. BCD is an encoding for decimal numbers in which each digit is
79

represented by its own 4-bit binary sequence. By utilising BCD, the manipulation
of numerical data for the display can be greatly simplified by treating each digit
as a separate 4-bit BCD counter. By connecting the output of these BCD counters
directly to a 7-segment LED display decoder, the values are shown in decimal.
Implementation of a BCD counter is similar to a synchronous counter, except that
the input to the D-flip-flop is a logic function of the current outputs.

Exercise: 4-bit BCD counter


Xilinx has already provided an implementation of the 4-bit synchronous BCD
counter as a module named CD4CE. This counter is pin compatible with the
previous 4-bit binary counter, and we can literally replace the block on the
schematic with the new one.
Return to the counter project. In the schematic delete the existing instance of the
4-bit binary counter, insert a CD4CE symbol in place of the previous counter and
re-run the simulation.
Question: How does the sequence differ from the one obtained from a 4-bit
binary counter?

Checkpoint 6.1

Assessor

Marks

80

Date

7-Segment LED Display


In this part of the lab, you will be introduced to the 7-segment display on the
development board. Each of the seven LED elements can be individually turned
on or off to produce simplified representations of the Hindu-Arabic numerals.
The segments of a 7-segment display are referred to by the letters A to G, where
the optional DP decimal point is used for the display of non-integer numbers.

Exercise: Interfacing 7-segment LED display


There are four 7-segment LED displays, each requiring 8 signals to control.
However, the development board does not provide access to the individual digits.
In this exercise you will investigate how to access each digit separately.
Create a new project called segment and name the top-level schematic segment
as well. Draw 12 BUF (buffers) on the schematic. Connect the 8 switches to the 8
segments beginning with SEGDx via a buffer. Also connect the push-buttons to
the four SEGAx via a buffer. Your schematic should look like the one shown
below.

81

You will have to make a new UCF file for this project. We havent provided the
mappings here, however, you can find it in Appendix A. Produce an appropriate
UCF file, save it, generate a programming file and download it to the FPGA.
Change all the switches to 0 (down). Do the LEDs light up?

All 7-segment displays should be displaying the same pattern. Now press and
hold PB3 (SEGA3 = 1), what happens to the four 7-segment displays? Note down
your observations as you will use this behaviour to display multiple digits.

A 7-segment display can display the digits 0 to 9 numerically by turning some of


the segments on and off. Experiment with different combinations and fill in the
table below to show how each of the 10 digits can be formed.

Digit

SEGDA

SEGDB

SEGDC

SEGDD

0
1
2
3
4
5
6
7
8
9

82

SEGDE

SEGDF

SEGDG

BCD to 7-Segment Decoder


The function of a BCD to 7-segment decoder is to convert the logic states at the
outputs of a BCD counter into a form which will drive a 7-segment LED display.
There are two important types of 7-segment LED display. In a common cathode
display, the cathodes of all the LEDs are joined together and the individual
segments are illuminated by HIGH voltages (logic 1) applied to the individual
anodes. In a common anode display, the anodes of all the LEDs are joined
together and the individual segments are illuminated by applying a LOW voltage
(logic 0) to the individual cathodes.

Exercise: Interfacing with a BCD to 7-segment decoder


The 7-segments on the development board are common anode displays, and the
7447 IC is designed to drive such displays. A module, written in Verilog, has been
supplied to mimic such a chip. Copy the module file, which can be found at
G:\lab6\bcdtoseg.v to your personal working directory (Z: drive).
Create a new project called bcdcount and create a top-level schematic of the
same name. A symbol must be created from the code written in Verilog before it
can be used in the schematic. First, add the Verilog file by right-clicking an empty
area in Design tab and select Add Copy of Source, then browse to the location of
bcdtoseg.v on your personal working directory, and click OK. Single-click on the
newly added file in Design tab to select the file. Then under the Processes view,
expand Design Utilities and double-click Create Schematic Symbol. After this,
the symbol will be available from the Symbol list.
Create the following design in the bcdcount schematic, which connects switches
SW0 to SW3 to the inputs of the decoder, and the outputs of the decoder directly
to the 7-segment displays. All other control lines are connected to logic 1 by
connecting them to Vcc. Buffers are required so that a single Vcc source can be
shared with different inputs without Xilinx complaining about different net
names for the same wire (as discussed earlier). SEGA1 to SEGA3 are turned off

83

by connecting to logic 1 while SEGA0 is turned on by connected to logic 0. This


enables only the right-most 7-segment display.

After adding the above I/O markers to the design, you need to create a new UCF
file. You can copy the constraints from the previous exercise, but ensure you do
not leave behind constraints that reference non-existing markers as the
Implement process will fail with an error.
Generate a programming file and load the design onto the FPGA. Try out different
switch combinations and verify that the display is showing the correct output.

Exercise: Displaying the counter on the 7-segment LED display


In this exercise, we will connect the outputs of a BCD counter to the inputs of the
BCD decoder, effectively turning this into a human-readable 0-9 counter.
Re-use the existing bcdcount project by opening up the top-level schematic.
Delete all of the I/O markers and wires connected to inputs A0 to A3 of bcdtoseg.
The reason is that if we leave these wires there, it will result in Xilinx getting
confused about net names and wire names. Insert a CD4CE BCD counter and
connect to the BCD decoder as shown in the diagram below. SW0 will be used as
Reset, SW1 as Enable and PB0 as a Clock signal. Again, we are going to use the
right-most display for now.

84

We will be doing another behavioural simulation in order to check this design. To


do this, we will need to create another Verilog Test Fixture. Create one called
bcdcount2_tbw. Write your own code, based on that used in Checkpoint 6.1, to
perform a simulation that initialises the counter by setting SW0 to 1 for one cycle,
and then to 0 for the remainder of the simulation, while keeping SW1 at 1 for the
entire duration and applying a clock to PB0 (oscillating between 0 and 1). Verify
that the outputs of the BCD decoder are repeating after 10 clock cycles.
Remember to set your simulation time so that you can see this!
Generate a programming file and load the design onto the FPGA. You will need to
update your UCF file for this remove any surplus entries as they will cause
problems. To edit your UCF file, select it from the Design tab by clicking on it
once. Go to the Processes pane below and expand User Constraints. Doubleclick on Edit Constraints (Text).
You will get a Xilinx warning about CEO having no load. It is safe to ignore this
warning and continue, since this is what we intended i.e. the CEO pin is not
connected to anything. Once you have loaded the design, initialise the display by
turning SW0 on and off. Repeat the experiment done with simulation on the
actual hardware and verify that the same outputs occur.

85

Checkpoint 6.2

Assessor

Marks

END

86

Date

Lab 7 Counters and 7-Segment Display (Part II)


Exercise: Four-digit 7-segment display
In this exercise, we will use the knowledge gathered earlier to use common
segment data lines (SEGDx) to display different digits on each display. This is
achieved by using a multiplexing technique.
In the previous exercise, we have seen that an individual display can be turned
on and off. However, if the frequency of the flashing is high enough, say higher
than 50Hz, the persistence of vision effect in our eyes causes it to appear as if it is
on all the time, just dimmer! Using this technique, we can display digits one at a
time on a rotating basis while the display appears to be displaying all digits
simultaneously.
To achieve this effect, we need three major components: a counter, a multiplexer
and a decoder. The role of the counter is to keep track of which digit we are
displaying. The multiplexer directs the digit to be displayed to the segment data
line. The decoder turns the corresponding display on and keeps the others off.
Start a new project named segmux and create a blank top-level schematic of the
same name. There are 4 digits to be displayed, and each digit has 4 bits. Hence
we need four 4-bit BCD counters and a 4x4 multiplexer. For ease of connection
we are going to use bus notation for the data line.
First, we must prepare the 4-bit BCD counter. The symbol provided by Xilinx
does not use bus notation, so we will need to modify it. Add a new schematic
named cd4cebus. Insert an instance of CD4CE. Connect wires to Q0, Q1, Q2 and
Q3 such that the lines are extended outward. Name the wires Q(0) to Q(3)
respectively by adding an I/O marker, then renaming it, clicking on the I/O
marker and then pressing the Delete key. This tells Xilinx that these signals are
part of a bus. Next, draw a wire somewhere underneath Q0, name it Q(3:0) and
connect an I/O marker at the other end. Notice the line becomes thicker,

87

indicating Xilinx recognises that Q is a bus. Attach I/O markers to all the
remaining pins and label them with the names as in the diagram below.

Save the schematic and use it to create a symbol.


The next step is to create the multiplexer. Again, Xilinx does not provide us with
a 4x4 multiplexer, so we can instead make our own using 4x1 multiplexers.
Essentially each multiplexer selects a bit from one of the four digits, and all four
multiplexers can share the same selector bits because they are selecting the same
digit. Add a new schematic named mux4_4 and insert four M4_1E 4x1
multiplexers. Label the nets and I/O markers as in the following diagram:

88

You will notice that E, S(0), and S(1) are common to multiple M4_1Es. You will
be warned that There is already a net named xxxx. Do you want to merge
them? Select Yes. Save the schematic and create a symbol for it as well. We do
not need to make a decoder as the one provided by Xilinx is sufficient for our
purposes.

Exercise: Four-Digit BCD Counter


In this exercise, you will build a timer that counts at around 1Hz up to 10,000
seconds. This exercise introduces you to internal clocking, including how to
derive a slower clock signal from a faster one using what is known as a prescaler.
Making a 4-digit BCD counter requires the following logic devices:

Four 4-bit BCD counters, one for each digit.

A 4x4 multiplexer for displaying one digit at a time.

A BCD to 7-segment decoder to display digits in human readable form.

A clock signal for controlling the multiplexers (i.e. which digit is shown).

A clock signal for the counter itself.

89

The final design for this exercise will look something like this:

We will now design this in a section-by-section manner.


Open the top-level segmux schematic. We will now prepare the synchronous
BCD counter. Insert four cd4cebus symbols and arrange them in a 2x2 layout.
The CLR pin of each counter will be connected to a net named RESET, while the
clock pin C will be connected to the counter clock named CLOCK. Chain the
counters together by connecting CEO of the previous stage to CE of the next stage.
This signal is generated on the negative edge when the counter rolls over from 9
to 0. Connect EN to CE of the first stage. A(3:0) will be the right-most digit while
D(3:0) will be the left-most digit.

90

To rename the buses, right-click the I/O marker you have added, select Rename
Bus and then under New Base Name of Bus, type A (for example A(3:0)) and
click OK. Select the I/O marker, and press the Delete key to remove the I/O
symbol, leaving only its name. Repeat for all the other buses.
Next we insert the multiplexer mux4_4. SEGSEL(1:0) will be used to select
which digit is to be displayed. The Enable signal (pin E) of the multiplexer will be
connected to a net named HIGH, which we will later connect to a constant logic 1.
BCD(3:0) will be the input of the BCD to 7-segment decoder.

In order to add the buses A(3:0) to D(3:0), we must merge them to the existing
nets. You can do this by selecting the I/O marker, select Rename Port under the
91

right-click menu, choose to Rename the Branch and put in the full name of the
branch e.g. A(3:0). Click OK and then use the Delete key to leave only its name.
Next we connect the multiplexer output to the BCD decoder bcdtoseg. You will
have to Add a Copy of Source from the previous lab and create a new symbol for
this.
As this is the last stage of the logic, we would like to have some means of
debugging the circuit if the output is not displaying the patterns that we expect.
In order to do this, weve added a function to the circuit that tests the display.
LAMPTEST is a push-button connected to a decoder that tests the illumination of
the display. If only one display is illuminated, then we know that there is a
problem with the multiplexer. If all displays are illuminated, but the number is
not changing, we know there is a problem with the BCD counter.
SEGDP is turned off by connecting it to logic 1. RBO is not used and is left
unconnected. The remaining outputs are connected to segment data lines SEGDx.
RBI and BI are not used, and so they are connected to logic 1. The decoder inputs
are connected to the multiplexer outputs via the BCD bus. This is shown in the
diagram below.

92

So far we have the logic to display one digit at a time, but we need a way to
automatically periodically rotate which digit we are displaying. To do this, we are
going to use a 2-bit counter, which rotates the illumination of each display. Insert
a CB2CE, a 2-bit binary counter, and a D2_4E, a 2-bit decoder, and connect them
as shown.

Make sure you right-click on the wire connecting between Q0 and A0 and choose
Rename the Selected Net and rename it to SIGSEL(0). Likewise, name the
wire connecting Q1 to A1 as SIGSEL(1).
The net called LOW serves as logic 0. We will connect this later. A logic 0
connection to CLR of CB2CE means the counter will never be reset manually. A
HIGH to CE of CB2CE means the counter will always count. SEGCLK, a clock
signal which will be generated later, is the rate at which the displays will be
cycled through. Note that the frequency of SEGCLK is dependent on how long we
want each display to be illuminated for, and how frequent we need to refresh
each display such that our eyes are tricked into seeing a solid display. In the
Nexys reference manual (Appendix A), it is indicated that this clock frequency
should be around 1 KHz. This clock signal will be supplied by the prescaler to be
built later, which uses the high frequency clock signal supplied by the Nexys
board.
The counter outputs are connected to the decoder. The purpose of the decoder is
to select one output at a time. For example, if the input is 2, then D2 is set to 1
while the other outputs are set to 0. Because the SEGAx pins are active low (i.e.

93

we turn the display on by setting logic 0), we need to connect inverters between
the outputs of the decoder and SEGAx. A HIGH signal connected to the Enable
pin E of the decoder keeps the decoder running permanently.
The final block to be added is the clock prescaler. A prescaler is an electronic
counting circuit used to reduce a high frequency electrical signal to a lower
frequency by integer division. A prescaler is essentially a counter-divider a BCD
counter can be used as a divide-by-2 or divide-by-5 counter, while a binary
counter can only be used as a divide-by-2.
A 100 MHz clock is supplied to the FPGA by the clock generator on the
development board. We will need two new clock signals at frequencies of around
1 KHz and 1 Hz. Considering we are only going to use a binary counter, how
many times do we need to divide a 100 MHz clock signal by 2 to get 1 KHz? We
use the following formula:
Number of times we need to halve the frequency =
log2 ( Faster Frequency / Slower Frequency )
So for the 1 KHz signal, we need:
Number of times we need to halve the frequency =
log2 ( 100 106 / 1 103 ) = 16.6
So, if the input clock to a binary counter is 100 MHz, the 17th bit of the output will
have a frequency just slightly under 1 KHz. However, the largest binary counter
provided by Xilinx is only 16-bit, therefore we need to cascade the two counters
together by connecting CEO of previous stage to CE of next stage.

94

Note that bit 0 of the next stage is bit 16 of the overall counter. Likewise, bit 1 of
the next stage is bit 17 of the whole counter. You can use this technique to slow
the clock down even more.
Question: How many times do we have to halve the frequency to get 1 Hz for the
timer from 100 MHz? Show all working below. Indicate which output bit you will
use to drive the clock.

After picking the output bits for clock driving, we need to use a buffer to
distribute the clock signal to the BCD counter and multiplexer counter. The
reason why we cant clock the circuit directly from the counter output is due to
the fan-out limit of each gate. Detailed explanation about fan-out limit of gates is
beyond the scope of this course.
Finally, we interface the inputs to switches and push-buttons. It is suggested that
SW7 will be used for LAMPTEST, SW6 for RESET and SW0 for EN. CLK is
connected to the on-board clock generator.

95

Verification on FPGA
We have already constructed the bulk of the BCD timer. The final piece of the
puzzle is creating a constraints file for pin mapping. For your convenience, the
table below summarises all of the pin connections needed for this exercise.

Net Name

Pin

Net Name

Pin

SW0

N15

SEGDA

F13

SW6

M15

SEGDB

E13

SW7

N16

SEGDC

G15

CLK

A8

SEGDD

H13

SEGA0

G14

SEGDE

J14

SEGA1

G12

SEGDF

E14

SEGA2

G13

SEGDG

G16

SEGA3

F12

SEGDP

H14

When you have completed the constraints file, implement the design. You will get
warnings corresponding to CLK_SLOW<15:4> and CLK_SLOW<2:1> these are
only warnings and we can ignore these as we do not use those outputs. You may
also get warnings about excessive clock skew, and unconnected CEO which are of
96

no big consequence to this design. If no other errors occur, generate the


programming file and upload the design to the FPGA.
To test the timer, first turn SW0, SW6 and SW7 off. All four 7-segment displays
should be illuminated. If not, there is a fault within the multiplexer. Next turn
SW7 on and toggle the SW6 switch. The display should be showing 0000 now. If
not, there is a fault within the BCD counter. Finally, turn SW0 on and the timer
should begin counting from 0000. Turning SW0 off should pause the timer.
Demonstrate the design to your demonstrator when your timer is running
correctly.

Checkpoint 7.1

Assessor

Marks

END

97

Date

Lab 8 Musical Logic (Part I)


In the following two labs, we will be building a digital circuit design using Verilog
that will be able to read music from memory, notated in binary form, produce
musical output on a speaker and display the note and duration on the LED 7segment displays.
When designing digital circuits, we have the option of choosing a schematicbased design tool or one based on a Hardware Description Language, otherwise
known as a HDL. Previously, you have used a schematic-based design tool to
design your circuits; in this lab, we will instead be using Verilog to describe our
design. You have already had some exposure to Verilog in the labs in building the
Verilog Test Fixtures which were used to simulate your circuits now you will
design your actual circuit with it as well.
We will be doing our design in parts each of which will be called a module. The
overall block representation of our system is as follows:
Memory

Tone
Generator

Speaker

Display
Controller

Display

Main
Controller

Clock

In the diagram, all the blocks with solid lines represent modules which we will be
designing with code. The blocks with dotted lines represent existing peripherals
that our modules will be interfacing with.

99

A Little Musical Background


Music is simply just a collection of sounds, of a particular frequency (or set of
frequencies), played for a particular length of time, in a particular sequence. You
may wonder how can we produce music from a digital circuit?
First, consider a tuning fork. When struck, the fork vibrates in the air, inducing a
sinusoidal oscillation into the air. This sinusoidal oscillation in air is perceived as
a note (or a pure tone). The frequency of its oscillation determines its pitch a
higher frequency corresponds to a higher pitch. Frequency and period are
inversely related so a high frequency signal has a short period.
Using a speaker, we can convert electrical oscillations into oscillations of the air.
If we apply a sinusoidal voltage to a speaker, it produces the corresponding
sinusoidal compression wave in air which we can hear. The human ear is often
quoted to have a frequency response of 20-20,000Hz. So, it stands to reason that
if we could produce oscillating voltages of the right frequencies, we can produce
a tone.
This is the principle by which this lab works we are going to produce a circuit
that is able to produce precisely timed sequences of oscillating voltages at
different frequencies. That is, the circuit will play a certain set of notes,
precisely timed to make music. We will store our musical scores in memory, and
our circuit should be able to read the score from memory and play it for us by
generating these voltages which we will send to a speaker to make the signal
audible.

A Slight Complication
While it may sound simple to generate voltages oscillating at the right
frequencies, you might wonder how we might be able to generate a sinusoidal
wave using digital logic in order to produce a pure tone. Unfortunately, the
answer is we dont. While it is possible, it is a very complex procedure.
However, it is more than acceptable to simply generate a square wave and feed
this to the speaker. This results in a harsh sounding, buzzy sound with many
100

strong harmonics instead of a pure tone. In reality, it is these harmonics which


control the timbre of the instrument (i.e. its what distinguishes a piano from a
clarinet for example). Generating our square wave is extremely simple as the
output of digital logic is either high or low and if we alternate between them at
a particular frequency, we can produce a square wave.
Furthermore, the perceived volume of a sound is determined by the amplitude of
the wave. The amplitude of the wave is in proportion to the voltage applied to
the speaker. Unfortunately, as we are using digital logic to make our sounds, we
wont have control over the volume.

Its All a Matter of Frequency and Timing!


Choosing the right frequencies is a matter of importance. In order to have our
music sound right, we must focus on a musical scale with a base reference. In
this lab, we use A = 440 Hz as our reference.
Furthermore, we have to choose a note-length reference as well, and a timing
scale. This will determine the tempo of the music, and how long each different
type of note is compared to another. There is an added complication here too
what if we have two consecutive notes of the same frequency? Instinctively, if
you were playing an instrument, you would leave a short rest in-between those
two notes. That is why we have to duplicate our timing scale one for the normal
duration of the note, and one slightly shorter to accommodate a short rest inbetween. That ensures that we keep our tempo consistent.
We have decided to only cover two octaves of the scale, and have only a limited
selection of timings to simplify our circuit. All of these timings will be derived
from the on-board clock generator.

101

Exercise: Tone Generator Module


Start a new project in Xilinx ISE called music, however, this time choose HDL
under the Top-level source type dropdown. Do not add or create any sources
for the moment. Copy all the files from G:\lab8 to your Z: drive. For now, use the
Add a Copy of Source option to add tone.v and tone.ucf to your project.
We begin building our design module by module. The first module to be
constructed is the tone generator module. Using the table below, we have 16
notes that can be represented with four bits. This part of the circuit has a 4 bit
input for choosing the note for this reason. It outputs an oscillating signal to the
speaker. This module will derive its timings from the onboard clock by counting
the appropriate amount of cycles of the onboard 100 MHz clock. We will test this
module by initially taking our four input bits from the on-board slide-switches,
and outputting to an I/O port, which is connected to the speaker.
The following table shows the bit-pattern-to-note mapping, and their respective
frequencies:
Combination
0x0
0x1
0x2
0x3
0x4
0x5
0x6
0x7
0x8
0x9
0xA
0xB
0xC
0xD
0xE
0xF

Note
-C4
D4
E4
F4
G4
A4
B4
C5
D5
E5
F5
G5
A5
B5
C6

102

Frequency (Hz)
Silence
261.63
293.66
329.63
349.23
392.00
440.00
493.88
523.25
587.33
659.26
698.46
783.99
880.00
987.77
1046.5

To make things easier, we have defined the tone module below, and given you
the constants as shown (in the file tone.v):
module tone(CLK, TONE, P);
input
CLK;
input
[3:0]
TONE;
output
P;
parameter

C4
D4
E4
F4
G4
A4
B4
C5
D5
E5
F5
G5
A5
B5
C6

=
=
=
=
=
=
=
=
=
=
=
=
=
=
=

22'd191110,
22'd170265,
22'd151685,
22'd143172,
22'd127551,
22'd113636,
22'd101239,
22'd95557,
22'd85131,
22'd75843,
22'd71586,
22'd63776,
22'd56818,
22'd50619,
22'd47778;

reg [21:0] counter;


// Your code goes here.
endmodule
Question: What do the constants stand for? How are they related to the tone
frequency? What is their relation with the clock? Show your working below.

Complete the module by writing the appropriate Verilog code that makes use of
these constants and produces its square wave output to P.

103

We will test this code by generating a bit file to load onto the FPGA, but first, we
need to create an appropriate constraints file to map the inputs and outputs to
their respective pins. At this point, you will notice that the speaker is not present
onboard the Nexys board but instead needs to be connected through one of the
I/O ports on the top of the board. We will be using the first peripheral module
connector, labelled JA, at the top left-hand side of the board. Obtain a speaker
from your lab demonstrator and plug it into the module connector. Refer to the
Nexys reference manual given in Appendix A for more information on the header
pins.
Question: For the JA header what is Pin 1 connected to (and where)? What is
Pin 5 connected to? What sort of protection is available for this port, and against
what problems?

To help you along, we have provided a ready-made constraints file which maps
the tone input to slide-switches 0 to 3, and outputs the tone on the JA header
using pins 1 and 5. You would have already added this file at the beginning of the
exercise.
You will notice that we have deviated from our normal path in the sense that
tone.v is now our top-level schematic, instead of music.v (which we dont yet
have). This is because we are building our design module-by-module, and this
will save you from having to create multiple projects and keep moving sources
around between them. It is actually quite easy to designate a particular source as
a top-level module just by right-clicking on it and selecting Set as Top Module.
However, since we only have one module at this time this is not yet necessary.

104

Synthesize, Implement and Generate Programming File as you normally


would. You should receive all green ticks. If so, use Digilent Adept to load
tone.bit to the board and verify that your tone generator works as expected by
toggling the slide-switches. Show your working design to a demonstrator.

Checkpoint 8.1

Assessor

Marks

Date

Exercise: Display Controller Module


Now, we will move on to create the display module. This module will take in a
4-bit input which represents the note that is being played, as well as a 4-bit input
that represents the duration of the played note. The bit pattern for the notes
remains identical to the previous module, however, there will be another
mapping to be concerned with that of the bit-pattern-to-duration mapping
which is as follows:
Combination
0x0
0x1
0x2
0x3
0x4
0x5
0x6
0x7
0x8
0x9
0xA
0xB
0xC
0xD
0xE
0xF

Duration (s)
EOF
1/8
1/4
3/8
1/2
3/4
1
2
1/32
1/8
1/4'
3/8
1/2'
3/4'
1
2

105

Display
-1
2
3
4
6
8
16
-.
1.
2.
3.
4.
6.
8.
16.

As you can see, some of the durations have been doubled up the ones with the
apostrophe are 1/32th of a second shorter than the ones without, so that
repeated notes can be evident. The 1/32th of a second duration is expected only
to be used for in-between repeating notes. Note that there is a combination of 0
which has a duration of 0 this is intended to indicate End of File. This will be
important when we come to build our controller.
For this exercise, we will be using the left-most two 7-segment displays to
display the note (e.g. C4, D4, etc.) and the right-most two 7-segment displays to
display the duration. The display column above shows what you should display
in the two 7-segment displays for the duration all of which are in units of 1/8th
of a second.
First, remove tone.ucf from your project. You will not need that file anymore.
Use the Add a Copy of Source tool to add display.v and display.ucf to your
project. You have been given the following in the display.v file.

module display(CLK, TONE, DURATION, SEGA, SEGD);


input
CLK;
input
[3:0]
TONE;
input
[3:0]
DURATION;
output
[3:0]
SEGA;
output
[7:0]
SEGD;
parameter

DISP_A
DISP_B
DISP_C
DISP_D
DISP_E
DISP_F
DISP_G

=
=
=
=
=
=
=

8'b00010001,
8'b00000001,
8'b01100011,
8'b10000101,
8'b01100001,
8'b01110001,
8'b00001001,

DISP_0
DISP_1
DISP_2
DISP_3
DISP_4
DISP_5
DISP_6
DISP_8
DISP_1_D

=
=
=
=
=
=
=
=
=

8'b00000011,
8'b10011111,
8'b00100101,
8'b00001101,
8'b10011001,
8'b01001001,
8'b01000001,
8'b00000001,
8'b10011110,

106

DISP_2_D
DISP_3_D
DISP_4_D
DISP_6_D
DISP_8_D

=
=
=
=
=

8'b00100100,
8'b00001100,
8'b10011000,
8'b01000000,
8'b00000000,

DISP_HYPH
= 8'b11111101,
DISP_HYPH_D = 8'b11111100,
DISP_BLANK = 8'b11111111;
// Your code goes here.
endmodule
Write the Verilog code to perform the display function. Refer to the previous lab
to remember how the LED display was used. You can rotate the display in a
range of frequencies refer to the Nexys reference manual (Appendix A) for
more details.
You will notice that the SEGA and SEGD lines have been defined in bus notation
with the provided UCF file, the MSB of SEGD corresponds to SEGDA and the LSB
corresponds to SEGDP. Also, the MSB of SEGA corresponds to SEGA0, and the
LSB corresponds to SEGA3. For your convenience, we have defined letter and
number constants. DISP_HYPH is used for the hyphen when the note is a silence,
DISP_HYPH_D is used for the duration of 1/32 as it displays a hyphen and a
decimal point. DISP_BLANK is used to blank out the left seven-segment in cases
where only a single digit is displayed, and DISP_x_D is used to display a number
with a dot for the shortened versions of the notes. All of the bits in the definition
are in the correct order for the defined SEGD bus lines.
We will be testing the module using the slide-switches for input. Examine the
UCF file to determine the switch mappings. Set display as the top-level
schematic by right-clicking on display in the Sources window and selecting Set
as Top Module. Synthesize, Implement Design and Generate Programming
File if needed, you may have to right-click and select Rerun if the process does
not run by double-clicking it. Test your design by loading display.bit on the
board and setting combinations of inputs.
107

Checkpoint 8.2

Assessor

Marks

END

108

Date

Lab 9 Musical Logic (Part II)


Exercise: Main Controller Module
Now, we can move on to implementing the control module. The control module
is responsible for issuing the tone combination and duration to the display
module, as well as issuing the appropriate tone combination to the tone module
for the specified time. As such, it reads the tone and its time, issues the correct
tone combination for the specified time to the tone module, and moves on to the
next tone in sequence to make music.
However, we would like to start off small: we will create a control module that,
when given a set tone and duration, and a command to start, plays that one tone
only for the specified duration. We will move on to add memory access later in
this lab to make it play music.
Start by removing the display.ucf file from your project. Copy control.v, music.v
and music.ucf from G:\lab9 to your working Z: drive. Use the Add a Copy of
Source option to add them to your project.
As before, we have given you some of the important declarations and constants
for you to use. In the control module, you have been given the following:
module control
DURATION);
input
input
input
input
output
output
parameter

(CLK, SW_TONE, SW_DURATION, PB_GO, TONE,


[3:0]
[3:0]
[3:0]
[3:0]

CLK;
SW_TONE;
SW_DURATION;
PB_GO;
TONE;
DURATION;
PERIOD_1_8
PERIOD_1_4
PERIOD_3_8
PERIOD_1_2
PERIOD_3_4
PERIOD_4_4
PERIOD_8_4
PERIOD_1_32
109

=
=
=
=
=
=
=
=

28'd12500000,
28'd25000000,
28'd37500000,
28'd50000000,
28'd75000000,
28'd100000000,
28'd200000000,
28'd3125000,

PERIOD_1_8A
PERIOD_1_4A
PERIOD_3_8A
PERIOD_1_2A
PERIOD_3_4A
PERIOD_4_4A
PERIOD_8_4A

=
=
=
=
=
=
=

28'd9375000,
28'd21875000,
28'd34375000,
28'd46875000,
28'd71875000,
28'd96875000,
28'd196875000;

reg [27:0] counter;


// Your code goes here.
endmodule
You are given the period definitions for each of the durations given in the table in
the previous lab. The tone and delay will be input by switches for testing to
SW_TONE and SW_DURATION respectively. For testing, PB_GO will be used to
tell the controller to play the specified tone for the specified duration. TONE and
DURATION will be outputs that will be connected to our tone and display
modules. Write your Verilog code, making use of these constants, to perform the
control function.
Since this module will need to interact with display and tone, we are going to
connect them together using a new top-level module called music that will
instantiate display, tone and control. The music module will connect the
appropriate nets together so that you will be able to set the switches to a given
tone and duration, press the push-button and the speaker will play the tone,
while the display will show the note and duration.
We have already written a music.v file containing the music top-level module.
Make sure you understand the code inside the file, and set music as the top-level
module before implementing your design on the FPGA. You have been already
given a UCF file which contains all the constraints so you dont have to write your
own.

110

Checkpoint 9.1

Assessor

Marks

Date

Exercise: Interfacing with Memory


Now that you have a working control module, we can integrate memory access
to it so that it can play a full song by itself by reading note and time combinations
direct from memory. The Digilent Nexys boards feature a flash memory chip
which is a programmable piece of non-volatile memory. This means that the
memory retains its contents while powered off. On the flash memory, at address
0, we have coded the binary patterns needed to play a few tunes we will be
reading from this flash memory as input to our circuit.

Working with Flash


Flash memory is very common in devices nowadays, however, working with it is
not always easy. There are many different types of flash on the market
described with terms such as serial, parallel, synchronous, asynchronous, singlelevel cell and multi-level cell. We need not be too concerned with all of the types
of flash available we will only be getting familiar with the asynchronous
parallel flash on the Nexys development board.
The type of flash memory is important as that determines the interfacing
requirements and the complexity of working with it. Luckily, the asynchronous
parallel flash on the Nexys board provides us the greatest ease in implementing a
working design. Put simply, we can consider the flash memory as a black box to
which we give addresses that we want retrieved on its address bus, and out pops
the data on the data bus, albeit with a short delay (of around 150ns). It is really
almost that simple, bar from setting a few control lines which enable the flash to
operate in various modes. Since we are only concerned with reading the flash in
this exercise, you should be aware of the meanings of the control lines, but
realise that all the appropriate values have already been set for you and there is
111

no need to change them. Writing to flash memory is a more complex procedure


which can be quite dependent on timing and will not be covered in this course.
The flash memory offers us a 24-bit address bus, and a 16-bit data bus. The flash
can operate in either byte mode (8-bits) or word mode (16-bits) this is fixed on
the development board as word mode (Refer to the Nexys Schematic given in
Appendix B for more details). As the chip is fixed in word mode, the addresses
must be incremented to even addresses only (as each address refers to a byte).
This is taken care for us, again, by the design of the board which ties the LSB of
the address bus to low, forcing any address increments to be even. That is why
you will find in the Verilog code, the address bus is defined as ADDR[23:1]
rather than ADDR[23:0]. Incrementing by 1 on the address bus will hence
increment the address pointer by a word. By now, you may have realised that the
note/delay pair combinations are only one byte each, and not a whole word. To
save complication, we have defined that only the lower byte of the word is used;
more specifically, DATA[7:4] will be the tone, DATA[3:0] will be the duration,
while DATA[15:8] is ignored.
Aside from the flash memory, the Nexys board provides us with a Cellular RAM
chip that can be accessed in a somewhat similar way to the flash. We will not use
the RAM in this project, however, we do need to consider its existence as it
shares the same address and data buses as the flash chip (see the Nexys
reference manual and schematic for more information). The idea behind this
kind of configuration is to enable the chip you would like to access while
disabling the other by using their respective chip enable input signals. The
disabled chip will simply ignore any signals on the address and data buses and
will not react to them. We should never have more than one chip enabled at a
time as this may cause signal clashes on the shared buses and any data read will
be corrupted.
Finally, there are several control lines to be aware of. We have already defined in
control2.v all of the values necessary. You are given control2.v as below:

112

module control2 (CLK, PB_GO, DATA, TONE, DURATION, OE,


WE, RP, CE, MTCE, ADDR);
input
CLK;
input
PB_GO;
input
[15:0]
DATA;
output
[3:0]
TONE;
output
[3:0]
DURATION;
output
[23:1]
ADDR;
output
OE;
output
WE;
output
CE;
output
RP;
output
MTCE;
assign
assign
assign
assign
assign

WE =
OE =
CE =
RP =
MTCE

1'b1;
1'b0;
1'b0;
1'b1;
= 1'b1;

// Your code goes here.


endmodule
WE stands for Write Enable and is active low. By setting it to a value of 1, we are
telling the chip that we want to disable writing. OE stands for Output Enable,
which is also active low by setting it to 0 we are telling the chip that we want
output from the chip (i.e. reading) to be enabled. CE is Chip Enable and is, as
you may have guessed, active low. Setting a 0 to this tells the chip that it is
enabled. RP stands for Reset/Power-down mode, setting this to high enables
normal operation of the chip. Finally, MTCE has been defined, and is the chip
enable signal for the RAM chip, which is set high to disable the chip.
In order to start building this project, you can first remove music.v and
music.ucf from your project. Copy music2.v, music2.ucf, and control2.v from
G:\lab9 to your Z: drive and use the Add Copy of Source to add them to your
project. We have left the control.v file still in the project it will not be
instantiated by music2.v which will only instantiate control2.v instead, it has
been left here for easy access as you may want to borrow code from your
working control module to build the control2 module.

113

Your control2 module should read its input from the flash memory. It should
have an address counter which counts upward to access the memory
sequentially. Your tones and durations should be coming off the DATA bus as
specified before. Your control2 module should only start playing when PB_GO is
pressed, and stop playing when it reaches

an EOF indicator (i.e.

DATA[3:0] = 4b0000). Pressing PB_GO again should play the tune from the
beginning.
Inspect the files, and use the information defined within them, and in the manual
to complete the exercise. We have given you a UCF file as before this time with
many constraints. You will notice that some of the DATA bus lines are not
defined in the UCF this is not a problem as they are not being used. Adding
them in will cause more warnings. Remove control.v to clean up your project,
and then Synthesize, Implement Design and Generate Programming File as
before. You will notice a warning about parts of the DATA bus not being used
this is what our project intends, so it is safe to ignore them. Proceed to load
music2.bit to your board. Press PB3 to begin results may vary Enjoy!

Checkpoint 9.2

Assessor

Marks

END

114

Date

Lab 10 Arithmetic-Logic Unit (ALU) Design


The specification for a computer consists of a description of its appearance to a
programmer at the lowest level, i.e. its instruction set architecture (ISA). The
high-level description of the hardware implementation to the ISA is called the
computer architecture. The architecture is typically divided into datapaths and
controls. The datapath is defined by three basic components:

A set of registers which hold the numeric data to be operated on.

Arithmetic-Logic Unit (ALU) which performs the microoperations on the


data stored in the registers.

The control interface which selects the appropriate registers and ALU
operation, based on the given control signals.

115

We are going to design a 4-bit ALU by cascading four 1-bit ALU blocks. The ALU
performs the following functions:

Adding and subtracting two numbers.

Performing bit-wise operations (AND, OR, XOR and NOT) between two
values.

In order to do this, we will be designing four separate schematics in Xilinx:


1. alu4.sch Top-level schematic implementing the 4-bit ALU using
multiple one-stage ALU blocks.
2. alu1.sch A one-stage ALU block.
3. arithm.sch Arithmetic circuit for the one-stage ALU block.
4. logic.sch Logic circuit for one-stage ALU block.
To do this, first open Xilinx ISE and create a project named alu4 with alu4.sch as
the top-level schematic. Then, in the Source window add three new schematics:
alu1.sch, arithm.sch and logic.sch. We will prepare these files, required for this
lab, later.

1-bit Arithmetic Circuit


Full Adder
A full adder is a combinational circuit that forms the arithmetic sum of three
input bits and has two output bits. Two of the input variables, denoted by X and
Y, represent the two significant bits to be added. The third input, Z, represents
the carry-in from the previous lower significant position. Two outputs are
designated by the symbols S (sum) and C (carry-out). Two bits are necessary
because the arithmetic sum of the three bits ranges in value from 0 to 3, and
binary values up to 3 need two digits for their representation.

116

Complete the following truth table for a 1-bit full adder.


Z

Based on the above truth table, write down the simplified sum-of-products
functions for the two outputs. Show all working below.

117

The following schematic shows an implementation of a full adder:

In the remainder of this lab, the following symbol will be used to denote the 1-bit
full adder:

118

Operand Logic
An arithmetic circuit is defined as a full adder with one of the operands
transformed logically. This extends the full adder to become a subtractor, as well
as providing auxiliary functionality. Let A, B, Cin, S0 and S1 denote the inputs to
the arithmetic circuit and G and Cout denote the outputs.
The operand transformation logic on input B is to have the following
characteristics:
S1

S0

Operation

Function

Y=0

False

Y=B

Buffer

Y = /B

Inverter

Y=1

True

In the space provided, construct a logic circuit implementing the above truth
table using only AND, OR and NOT gates.

119

Output Y, along with signals A and Cin, are then fed to the full adder as inputs.
Output S of the full adder will be output G of the arithmetic circuit. The following
table describes the overall function of the circuit:

S1

S0

Cin

Operation

Function

G=A

Transfer A

G=A+1

Increment A

G=A+B

Addition

G=A+B+1

Addition plus 1

G = A + /B

Subtraction minus 1

G = A + /B + 1

Subtraction

G=A1

Decrement A

G=A

Transfer A

As evident from the table above, the full-adder is now capable of performing
additions as well as subtractions, increments and decrements.
We will use the following symbol to denote 1-bit arithmetic circuit:

120

1-bit Logic Circuit


The logic circuit manipulates the bits of the operands by treating each bit in a
register as a binary variable, and performing bitwise operations on them. There
are four commonly used logic operations AND, OR, XOR, and NOT from which
others can be conveniently derived. The diagram below shows the
implementation of the logic circuit.

Complete the following function table for this logic circuit:


S1

S0

Operation

Function

G = AB

A AND B

We will use the following symbol to denote 1-bit logic circuit:

121

ALU
One-stage ALU block
The logic circuit can be combined with the arithmetic circuit to produce an ALU.
A selection variable S2 is used to switch between arithmetic output and logic
output.

When S2 = 0, the ALU is performing an arithmetic calculation. When S2 = 1, the


ALU is performing a logical operation. With this knowledge, the one-stage ALU
block can be produced.

122

Simulating in Xilinx
Arithmetic circuit
We are going to implement the arithmetic circuit of the ALU in Xilinx and test the
design via simulation.
1. Open arithm.sch.
2. Draw the operand logic on the left of the schematic (use the AND2, OR2
and INV symbols).
3. Draw 1-bit full adder on the right of the schematic (use the AND2, OR2
and XOR2 symbols).
4. Connect output Y of the operand transformation logic to any input of the
full adder.
5. Attach input markers for pins A, B, Cin, S1, and S0.
6. Attach output markers for pins G and Cout.
The next step is to verify the logical operation of the circuit by simulation. As this
is a combinational circuit with 5 inputs, we can verify the circuit by applying all
32 possible input combinations to the circuit with a test bench setup.
Create a test bench named arithm_tbw and associate this with arithm. Write
your own Verilog Test Fixture which causes all combinations of inputs to be
given to the circuit. We suggest using a 5-bit counter, which increments every
100ns, and assigning the individual counter bits to the circuit inputs. The most
significant bit should be assigned to S1, followed by S0, Cin, A and B. Each
assignment statement should look similar to:
assign S1 = counter[4];
Right-click Simulate Behavioral Model in the Processes view and set the
Simulation Run Time to 4000ns. Double-click on Simulate Behavioral Model
and wait until the simulation result is displayed on screen.

123

Verify the outputs against the predicted results:


Operation

Transfer A

Increment A

Addition

Addition plus 1

Subtraction minus 1

Subtraction

Decrement A

Transfer A

S1

S0

124

Cin

Cout

Logic circuit
In Xilinx:
1. Open logic.sch.
2. Draw the logic circuit using M4_1E, VCC, AND2, OR2, XOR2 and INV
symbols.
3. Connect pin E of M4_1E to VCC, thus enabling the multiplexer.
4. Attach input markers for pins A, B, S1 and S0.
5. Attach an output marker for pin G.
As before, create a test bench named logic_tbw.sch and associate this with logic.
Write a Verilog Test Fixture to test this circuit by applying all possible inputs. As
before, we suggest you count through all the possible combinations. Right-click
Simulate Behavioral Model in the Processes view and set the Simulation Run
Time to 2000ns.

125

Before simulating your design, write down the expected outputs in the following
table for verification later:
Operation

S1

A AND B

A OR B

A XOR B

NOT A

S0

Double-click on Simulate Behavioral Model and wait until the simulation result
is displayed on screen. Check the output against the expected results.

Checkpoint 10.1

Assessor

Marks

126

Date

4-bit ALU
The final step in making the ALU is to integrate both the arithmetic and logic
circuits together. We are going to build a 1-bit ALU, and then cascade four of
these together to build a 4-bit ALU.
The 1-bit ALU will have the following pins:

A, B which are the values to be operated on.

G the result bit.

S2, S1, S0 operation selector bits.

C0 carry-in for the entire word.

Cin carry-in for this particular stage, usually connected to the carry-out
from the previous stage.

Cout carry-out for this particular stage.

Create a schematic symbol for both arithm.sch and logic.sch using the Symbol
Wizard. Connect S0 and S1 of the logic circuit to C0 and S0 of the ALU
respectively. Connect the output G of the arithmetic and the logic circuit to the
inputs of a multiplexer (M2_1). Connect D0 (the arithmetic output) and D1 (the
logic output) such that when S2 = 0, the output is from the arithmetic circuit.

127

Your layout should look something like the diagram below:

We are now going to make a 4-bit ALU by cascading together four of the 1-bit
ALUs so that we can test the design as a whole.
Create a symbol out of alu1. Connect Cin and Cout of each stage as shown in the
diagram below.

128

Label A, B and G using bus notation. As previously done in an earlier lab, you will
first need to draw a horizontal wire on the page. Then add a net name, ending
with a number range enclosed in a bracket to one end of the wire. Xilinx ISE
automatically interprets that wire as a bus.
The next step is to prepare a test bench waveform for alu4. Like in previous
designs, name the Verilog Test Fixture as alu4_tbw and associate it with alu4. As
there is a large number of possible input combinations to this design, we are only
going to test a small subset of them.
Using the function tables for the arithmetic circuit and the logic circuit, write
down the expected output G for each of the input combinations:
Description

S2

S1

S0

C0

Cin

Cout

Transfer

0x5

Addition

0x5

0x6

Addition

0x5

0xC

Subtraction

0x5

0x4

Subtraction

0x5

0x6

Increment A

0x5

Decrement A

0x5

0x3

A AND B

0x5

0x3

A OR B

0x5

0x3

A XOR B

0x5

0x3

NOT A

0x5

We have created a Verilog Test Fixture to test your circuit with the combinations
above. To save you from typing the whole testbench, the file is provided at
G:\lab10\alu4_tbw.v. You should Add a Copy of Source, associate it with
alu4 and run the simulation.
Note that for Decrementing A, the value of B could be anything. However, for
simulation purposes we give it an arbitrary value to logically disable the halfadder.
129

Compare your simulation result with your expected output. Remember to change
the simulation time to 1200ns.
We will not implement this 4-bit ALU on the Nexys hardware as there are not
enough switches to fully control this design.

Checkpoint 10.2

Assessor

Marks

END

130

Date

S-ar putea să vă placă și