FRCD Lab Activity Manual - V7 00-2
FRCD Lab Activity Manual - V7 00-2
Table of Contents
Table of Contents
Acknowledgements ........................................................................................................ - 3 -
Lab Work Submission Guidelines.................................................................................. - 4 -
Lab Activity Report Guidelines ..................................................................................... - 6 -
General Comments Regarding Lab Activity Reports: ................................................... - 8 -
Notes on Lab Activity Report Deliverables ................................................................... - 9 -
Experiment #1: ............................................................................................................. - 10 -
Experiment #2 .............................................................................................................. - 15 -
Experiment #3: ............................................................................................................. - 18 -
Experiment #4: ............................................................................................................. - 24 -
Experiment #5: ............................................................................................................. - 30 -
Experiment #6: ............................................................................................................. - 34 -
Experiment #7: ............................................................................................................. - 39 -
Experiment #8: ............................................................................................................. - 45 -
Experiment #9: ............................................................................................................. - 50 -
Experiment #10: ........................................................................................................... - 56 -
Experiment #11: ........................................................................................................... - 61 -
Experiment #12: ........................................................................................................... - 66 -
Appendix ...................................................................................................................... - 69 -
Troubleshooters Guide to Xilinx ISE.................................................................................................. - 70 -
Implementation Constraint File Quirks and Problems ......................................................................... - 71 -
General Synthesis Problems ................................................................................................................. - 72 -
Lab Grading Acronyms ........................................................................................................................ - 73 -
VHDL Style File .................................................................................................................................. - 74 -
RAT MCU Architecture and Assembly Language Cheat Sheet .......................................................... - 76 -
RAT MCU Assembly Language Style File .......................................................................................... - 77 -
VHDL Cheat-Sheet .............................................................................................................................. - 79 -
Finite State Machine Modeling using VHDL Behavioral Models ....................................................... - 81 -
RAT MCU Architecture Diagram ........................................................................................................ - 82 -
VHDL TestBenches: A Quick Overview ............................................................................................. - 83 -
FRCD
-2-
Acknowledgements
Acknowledgements
First, Id want to acknowledge David Schoonover for allowing the use of the image on the cover for this
manual. Thanks David; I appreciate it.
The Free Range Computer Design textbook outlines the complete history of the RAT MCU-based course,
but some of the highlights are well worthy of mention here. While good ideas are a dime-a-dozen, it takes a
special person to actually make good things happen, particularly in academia. While the original
idea/approach for the course was Bryans, Jeff Gerfen made this new course happen by being the first to
teach the course, including the lab portion of the course. Jeff took the idea and gave it legs. Specifically,
Jeff is responsible for the initial creation/offering of the Computer Design course as well as the design of its
original experiments.
I would also like to thank Bridget Benson for many contributions and thoughtful edits to the experiments.
FRCD
-3-
FRCD
-4-
FRCD
-5-
Lab reports should be written using a word processor and submitted in hard copy form.
Each lab group should submit one lab report. Each member of the lab group should write their own
conclusion independently from other group members and submit it with the lab report.
Reports should not have a title page. The experiment title should be boldly centered on the first page. The
course and section number, and the names of group members should also appear on the first page.
Wording in the lab report should be brief but concise. Longer lab reports rarely correlate to higher quality
lab reports. Moreover, using concise wording save you time writing the report and saves someone else
time reading it.
Wording in the lab report should use good English and appropriate technical style. Correct spelling,
appropriate use of technical terms, and appropriate technical style allows you to create a professional
document that highlights your lab activities. If you are new to technical report writing, strongly consider
having someone else read over your report before you submit it. There are also many features in MS
Word that can help you with the grammar.
Lab reports should be neat and intelligently organized. Hand-written and hand-drawn items such as
circuit diagrams should be neat (use appropriate drawing software if necessary).
All figures and diagrams should contain captions and/or titles and should be referenced from the body of
the report (do not say things like in the figure below). Plan to use the referencing feature of your word
processor.
Different sections and diagrams in the lab report should be well delineated from each other. Using extra
space to in the lab report generally creates a more professional looking document.
Report Format:
Each lab report should at least contain the following clearly indicated sections. More sections are permissible but
the document should remain concise and well organized.
FRCD
Objectives (Say why youre bothering): This section states that point of performing the lab activity. This
section is generally a rewording of the stated activities objectives in such a way as to show that
understood what youre attempting to do with in the lab activity. Dont just copy the state lab activitys
objectives; use your own words instead.
-6-
Procedures (Say what you did): Describe what you did during the lab activity.
The use of words in this section should be minimized in favor of more expressive items such as
truth tables, equations, circuit diagrams, block diagrams, timing diagrams.
Someone should be able to read though this section and know exactly where you started, where
you ended, and the steps you used to arrive at your destination. The flow of this section should
match the flow of tasks during the lab activity. This section should not depend on the description
of the lab. In other words, assume that the person reading your lab report does not have a copy of
the lab description.
This section should be written using normal English sentences and paragraphs as opposed to
bulleted or numbered lists of tasks and/or commands.
Testing (Say why you think you did it correctly): Describe the testing procedures you used to verify your
circuitry met the design criteria.
Questions (Say what youre supposed to say): Be sure to include the answers to any questions that may
appear at the end of lab activity description in your lab report.
The Conclusion:
FRCD
-7-
Lab reports should be stapled in the upper-upper-left corner. Staples that drift away from the upper-left
corner make the report harder to read through. Please do not submit unstapled lab reports.
Attach all source code (VHDL, assembly language, etc.) to the end of the report. Generally speaking, you
should print your VHDL code from the Xilinx environment as it does a good job handling printer-based
format issues. Do not include source code in the body of the report; reference the source code from the
body of the report if necessary. If fragments of source code are included in the report, you should use a
courier font to make the code readable.
All source code (VHDL, assembly language, etc) should use appropriate form. This includes indentation
(associated with the particular language), proper vertical spacing (different sections of code should be
well delineated), proper commenting (dont state what is patently obvious), and an overall highly
professional appearance. Use whitespace (blank lines and indentation) to make your code look more neat
and organized. See the VHDL Style File document for further details.
Your VHDL code should take a strong self-commenting approach. This means that file, entity,
architecture, process, module instantiations, function, procedure, signal, and variable names should all
indicate the purpose of the item. At the same time, these labels should be as short as possible so as not to
obfuscate you code.
In addition to self-comment labels, signal and variable names should use a prefix that indicates how their
usage. Signal names should use a s_ prefix unless they are used as memory, in which case they should
use a r_ prefix. Variables should use a v_ prefix.
Unless told otherwise, do not include the VHDL code for modules that were provided for you in the lab
activity.
Make sure you verify that the hardcopy of your source matches the appearance of the source code on your
computer monitor. In particular, you should also have no line-wrap in code or comments. A major issue
here is that printers interpret tabs differently, so what you see on your monitor is not always what the
printer prints.
All source code (VHDL, assembly language, etc.) should be well commented and contain a file banner.
The file banner should include appropriate information such as the names of experimenters, description of
file contents, revision numbers, and pertinent dates.
Dont submit a crappy lab report in an effort to obtain partial credit. Instead, plan ahead and submit a
timely, neat, and organized report.
FRCD
-8-
Any non-trivial calculation you performed in order to complete the lab activity
All VHDL models generated in the lab activity: properly formatted, well commented and with a
really nice header
Questions to that may or may not appear at the end of the lab activity
Some other stuff that I cant think of now and that Ill tell you about later.
In addition, there is often other stuff you need to include that is unique to a given lab activity. In this case,
there is a Special Deliverables section of the lab report. These deliverables are in addition to the stuff
listed above.
FRCD
-9-
Experiment #1
Experiment#1:
DigitalDesign
withVHDLRAMModels
Learning Objectives:
To refresh your VHDL skills regarding sequential, combinatorial and arithmetic circuits
To review the basic operation of the Xilinx simulator
To implement a simple but potentially useful circuit using a RAM modeled in VHDL
The Big Picture: This experiment is most likely your first time working the structured memory.
Out there in computer-land, there are many types of structure memory devices, but you can classify
them as either RAM or ROM. VHDL allows you to model both types of structured memory using
familiar VHDL syntax. As long as your structured memory models do not become overly complex,
modeling these devices in VHDL is straightforward and generally involves finding a model similar
to what you need and adjusting the model to suit your particular needs.
This is a course in computer design, which is a subset of digital design. Youll soon find out that a
computer is nothing more than a large digital circuit containing many standard (and familiar)
sequential and combinatorial elements under the control of an FSM. This experiment has all those
characteristics but cannot do as many interesting things as a computer can. The good news is that if
you complete and understand this experiment, youll not see too much new material as you build
your computer in this course. In other words, the lab experiments associated with this course do not
become any harder to understand than the concepts contained in this experiment.
The Modern Approach to Digital Design: The best place to start is to define digital design.
Digital design involves using digital circuits to solve problems. There are many approaches to use
for solving problems; digital design is just one of them. Moreover, there are also different levels
of digital design. For example, I can buy a digital thermostat to replace the analog thermostat on the
heater that warms my home. While this fits well under the definition of digital design, it is not an
overly impressive level of digital design.
The information associated with this course deals with digital design at the engineering level.
Well avoid defining this level, but suffice to say it involves something more than determining an
off-the-shelf solution to problems. Engineering is simply an efficient process from going from
problem to solution. Once again, there are many paths to the solutions to your problems, but the
engineering path is the efficient path. Additionally, part of the engineering solution is to question
your solution once you arrive at it: could you have solved the problem better? Could you have taken
a different and better path from problem to solution? In summary, engineering is not solely about
FRCD
- 10 -
Experiment #1
solving problems; it about solving problems in an efficient manner and learning enough along the
way to think of a better solution once you arrive at your first solution.
The modern engineering-based digital design paradigm includes two basic aspects: 1) modern
digital designs are hierarchical in nature, and, 2) modern digital designs are modular in nature. How
these aspects relate to the engineering-based approach to digital are the following.
In order to understand anything other than simple digital designs, you must constantly
abstract the designs to higher levels. If you remain at lower design levels, you find it harder
to find the best path to your solution in an efficient manner. There are of course times where
you must deal with lower-level design issues, but you avoid this where possible in the name
of efficiency. The general model is to collect your lower-level designs, and then place them
in a box (an abstracted module). The box is a higher-level than the components in the box,
and you thus now have a hierarchical design.
In order to design efficiently, your approach is to take various boxes (or modules), place
them into your design, and connect the modules in such a way as to solve the problem at
hand. There was a time when most digital designs started from scratch (at a low level) and
slowly built upwards, but like the dinosaurs, those times have generally passed. Modern
engineering-based digital design primarily concerns the interfacing of pre-designed
components in such a way as to solve your problem. Inherent in this definition is the need to
understand all usage aspects of the modules you use in your design, which facilitates your
search for an efficient path to the solution. In other words, if you dont understand how the
modules control inputs affect the operation of the modules, you wont be able to effectively
use that module and thus the overall efficiency of your design will suffer. Most
conveniently, many complex digital circuits are created using the most basic digital
modules, which are relatively few and simple to understand (modules such as MUXes,
decoders, registers, counters, and basic logic gates).
Lab Assignment: Design a circuit that writes the first 16 Fibonacci sequence numbers (1, 1, 2, 3, 5,
8) to a RAM and then displays those numbers continuously. Figure 1 shows the partial black box
diagram for the RAM module you need to model while Figure 2 shows the top-level black box
diagram for this circuit. Minimize the amount of hardware you use in your design.
FRCD
The circuit initially displays the RAMs contents upon power-up. In other words, the circuit
continuously indexes through the RAM in counting order until the user presses the button.
When the user presses the left-most button on the development board, the FSM proceeds to
write the Fibonacci numbers to RAM and then constantly displays them in ascending order
after it writes them. Drive the 7-segment display as you write the Fibonacci numbers to the
RAM, recalling that the 7-segment driver uses a faster clock.
Your FSM should include a display state that does nothing more than displays the
contents of the RAM in a sequential manner. The FSM should return to this state after it
writes the Fibonacci sequence to the RAM.
Display the address input of the RAM to the four right-most LEDs on the development
board. In this way, youll display every RAM access (reading or writing) on the LEDs.
- 11 -
Experiment #1
Figure 1: The RAM you need to model and use in this experiment.
FRCD
Only use one clock frequency for both reading and writing the RAM.
You need an FSM to control this circuit; dont use more than ten states in your FSM.
Only use standard digital modules in your design. Dont use VHDL to model non-standard
circuits. Standard circuits include registers, counters, MUXes, decoders, etc.
Dont use VHDL mathematical operators anywhere except in RCA or counter circuits
Your FSM should be 100% independent of the length of the requested Fibonacci sequence.
This means if the length of your Fibonacci sequence changes, you will not need to change
the FSM in your design.
The FSM should not respond to another button press until the Fibonacci sequence is in the
RAM and the current button press is released
- 12 -
Experiment #1
Hints:
There are many ways to implement this design; whatever way you choose, make it work.
Think about it before choosing what you feel is the best approach. Strive to keep your
circuit as simple as possible by only using standard digital modules. If you run into issues,
youll need to use the simulator to work through them.
Questions:
1. Briefly but completely state and explain in your own words the two main aspects of the
modern digital design paradigm.
2. In your own words, provide a complete written description of how your circuit operates. Be
sure to reference the block diagram for your circuit. This description should not be a
detailed description of the FSM.
3. Based on the requested clock speed and FSM you used in your circuit, how long does it take
to load the RAM with the Fibonacci sequence after the user presses the button? Show your
calculations for this problem.
4. Consider a Moore-type FSM output; if an output becomes asserted when it enters a given
state, what is the soonest that output could take effect for an external hardware module? For
this problem, assume the external hardware module is synchronous and shares the same
clock as the FSM. Also, assume the FSM and external module are both RET devices.
5. Describe whether you implemented your circuit as a Mealy or Moore-type FSM. State the
reasons why you choose one FSM model over the other.
6. Could you have completed this circuit without using an FSM? Briefly but completely
explain.
7. Limiting the number of states in the design forces you to create a generic design, which
roughly means you reused some states in your FSM as it calculated/stored the Fibonacci
sequence. Briefly but completely explain the main benefit of implementing a generic
design.
8. Briefly describe the changes you would need to make to your circuit if you had to write the
first 32 Fibonacci numbers. Assume you want to minimize the hardware in all aspects of
this implementation.
9. Briefly explain what you think is the limiting factor in decreasing the amount of time
required to write to every RAM location with the Fibonacci sequence. In other words,
speculate on what would limit the system clock speed for your design. For this problem,
assume the development board can provide any possible clock frequency.
10. Could you use the circuit you designed in this problem to reverse the order of the sequence
in already in the RAM? If so, briefly explain how you would do it. If not, briefly describe
the modifications you would need to make to the circuit to complete this task.
FRCD
- 13 -
Experiment #1
Programming Assignment:
1. Write a fragment of C code that stores the first 16 number of the Fibonacci sequence into an
array. Dont exceed 12 lines of code for this problem.
2. Based on the array in the previous problem, write a fragment of C code that will reverse the
order of the sequence that contains the Fibonacci sequence.
Hardware Design Assignment:
Show a block diagram, including an FSM, that you could use to solve the following problems. Also
include a state diagram that describes the operation of the FSM to obtain the requested result. For this
problem, do not use modules other than standard digital modules with typical inputs and outputs
(counters, registers, shift register, comparators, RAMs, MUXes, RCAs, and decoders). If you use a
decoder, be sure to provide an adequate model for it. Minimize the amount of hardware you use in your
design including bit-widths of various modules.
Design a circuit that adds the contents of a 16x8 RAM and stores the result in an accumulator. The
circuit adds these values when a button is pressed.
FRCD
- 14 -
Experiment #2
Experiment#2
WorkingwithVHDLRAM
Models
Learning Objectives:
To refresh your VHDL skills regarding sequential, combinatorial and arithmetic circuits
To review the basic operation of the Xilinx simulator
To implement a simple but rather pointless circuit using a RAM modeled in VHDL
The Big Picture: This experiment is most likely your first time working the structured memory.
Out there in computer land, there are many types of structure memory devices, but you can classify
them as either RAM or ROM. VHDL allows you to model both types of structured memory using
familiar VHDL syntax. As long as your structured memory models do not become overly complex,
modeling these devices in VHDL is straightforward and generally involves finding a model similar
to what you need and adjusting the model to suit your particular needs.
Assignment Design a circuit that displays the values stored in a RAM. Youll feed the output of the
RAM to the standards 7-segment display module you used extensively in CPE 133, which mean the
values youll store in the RAM are BCD values. Figure 1 shows the BBD for the RAM module you
need to model while Figure 2 shows the top-level BBD.
Experiment Details The following bullets describe the complete operation of the circuit.
FRCD
When no button is pushed, the circuit feeds the contents of the RAM to the sseg_disp
module in order to display the individual RAM contents are decimal numbers. Use a
counter to automatically step through the 16 individual RAM locations. The counter should
display the RAM contents at about a 2Hz rate.
When you hit BTN0 (button 0), the circuit fills the RAM with a binary count. Specifically,
RAM location 0 should contain 0000; RAM location 1 should contain 0001, etc. Write
to the RAM fast enough so that the user cant detect anything strange on the development
boards 7-segment displays. This step results in the 7-segment display showing a decimal
count (015).
When you hit BTN1 (button 1), the circuit fills every RAM location with the value
represented by the development boards four lowest switch positions. So if the switches have
are set to 1011, fill every RAM location with 1011. This results in a decimal 11 being
- 15 -
Experiment #2
displayed on the 7-segment display; this number will not appear to change as 1011 should
now be in every RAM location. Once again, the writing to RAM should be fast enough so
that the user cant detect anything funny on the development boards 7-segment displays.
Figure 3: The RAM you need to model and use in this experiment.
Constraints:
Sorry folks, youre going to need a FSM to control this circuit. Do not use more than twelve
states in your FSM.
Hints:
FRCD
Youre going to need both a fast clock (for writing to the RAM) and a slow clock (for
displaying the RAM contents). You can connect the system clock to the sseg_disp modules.
There are bound to be debounce issues with the buttons; dont worry about them.
This circuit is both complicated and simple at the same time. Its complicated when it does
not work and its simple when it does work. If your circuit is complicated, youll know its
time to fire-up the simulator in order to help you see what is not going right with your
circuit.
- 16 -
Experiment #2
Questions:
1. In your own words, provide a written description of how your circuit operates. Be sure to
reference the block diagram for your circuit.
2. Could you have completed this circuit without using a FSM? Briefly but completely
explain.
3. Briefly explain why you think it was that the number of states in the FSM was limited to 12.
4. Briefly explain an approach you could use to determine how fast you can write to every
location in memory.
5. Briefly explain what you think is the limiting factor in decreasing the amount of time it
requires to write to every RAM location.
6. This experiment used on RAM to store two different types of data. The issue was that when
the set of data you wanted to use was not in the RAM, your circuit had to take the time to
load the new data. Briefly describe the changes you would need to make to this circuit if
you had two RAM devices, each of them holding the appropriate data. Be sure to state if
you would need the button inputs or not.
Deliverables:
1. Answers to the questions in the previous section.
2. Black box circuit diagrams for the two highest levels of your design. (Figure 1 shows the
black box model for the highest level).
3. VHDL code for all modules that you write; dont submit the modules that the experiment
provides for you.
4. State diagram for FSM. Make sure your state diagram uses symbolic names for both the
states in your state diagram as well as the input and output signals.
FRCD
- 17 -
Experiment #3
Experiment#3:
CountersasProgramCounters
Learning Objectives:
To understand how to use an n-bit register (counter) and MUX, which can implement the
features typically required of a program counter
To become familiar with integration the prog_rom.vhd file into a VHDL wrapper
The Big Picture: While there are many different computer architectures that include many different
modules, one module in most all architectures is the Program Counter (PC). The basic definition of
a computer is a circuit that executes instruction stored in memory to give a desired result. The PC is
the component that provides the address of the instruction in program memory that is either
executing or is scheduled for execution (depending on the time you examine it). Nevertheless, as
important as the functionality of a PC sounds, the PC (and its supporting hardware) is a relatively
simple device.
General Notes: A counter is a special form of register that performs operations typically associated
with counting. Counters generally operate synchronously (an active clock edge synchronizes all
output changes) but they also can have functions that are asynchronous (such as load, clear, etc.).
Modeling counters in VHDL is relatively simple as you can model an n-bit VHDL counter model
as n parallel D flip-flops. Thus we effectively extend the single-bit flip-flop is model to a vector,
which allows for various parallel operations on the bits in the counter.
The PC in this experiment includes external loading control for the PC with the addition of a MUX.
When the PC is operating in a computer, it operates normally by incrementing the count in order
to access the next instruction in program memory. The PC must also be able to parallel load values
to support computer executing instructions that are not the next instruction in program memory
sequence (such as branch instructions, subroutine calls, return from subroutines, etc.).
Program memory stores the machine code associated with a given RAT MCU program. The RAT
MCU architecture refers to program memory as the prog_rom as the assembler automatically
generates a VHDL model for the program memory and names it prog_rom.vhd. The assembler
assigns values to the prog_rom; these values can only be read not be changed (written to) by any
aspect of the RAT MCU hardware or firmware. The prog_rom is 1024 locations deep by 18 bits
wide (1024 x 18 or 1k x 18); hence, it has 10 address lines and 18 data lines. The data lines are for
the RAT instructions, each of which is 18-bits wide. The RAT MCU architecture configures the
prog_rom to have synchronous reads where the ten-bit output of the PC acts as an address input into
the prog_rom. Because the PC has ten address lines, the program memory can address 210, (1024 or
1k) unique instructions in program memory.
FRCD
- 18 -
Experiment #3
Assignment:
1. Design a PC and associated input selection MUX. Figure 5 shows the PC while Figure 6
shows the PC and the associated input selection MUX. Use at least two modules in your
design, one for the PC and one for the MUX; these modules can be either two separate
entities (two-level design) or two processes in the same entity (one-level design).
2. Assemble the following program in order to generate a prog_rom.vhd file and include it
with the PC hardware you modeled in the previous step. Figure 7 shows a high-level
diagram of this step.
.EQU LED_PORT
= 0x30
.EQU SWITCH_PORT = 0x40
.CSEG
.ORG
0x10
main:
IN
ADD
OUT
BRN
r10,SWITCH_PORT
r10,0x01
r10,LED_PORT
main
; endless loop
3. Write a testbench that tests the operation of your PC hardware connected to the
prog_rom from the previous step. Make sure you test the following operations for the
PC/prog_rom circuit:
RST
PC_OE
PC_LD: test all three data inputs to the MUX (FROM_IMMED, FROM_STACK,
& 0x3FF)
PC_INC: test by loading an immediate value (FROM_IMMED) of 0x10 into the
PC. Make sure you show each of the five instructions in the given program.
4. Verify that the output of the prog_rom matches the instruction bits by comparing the
18-bit IR output to the output of the assembly listing file generated by the RAT
assembler. Note that the assembly listing file will have the same name as the assembly
source file but with an .asl file extension. Include the well annotated simulator output
and a partial .asl file (showing the machine code for the instructions) in your lab
submission.
Circuit Details:
Figure 5 shows the top-level black box model of the PC youll implement. Table 1 provides an
overview of the PCs operation in the context of the signals in Figure 5.
FRCD
- 19 -
Experiment #3
Comment
PC_COUNT
The current value in the PC; the PC uses this value as an address to access
values in the program memory.
PC_TRI
The current value in the PC under tri-state control. When PC_OE is asserted,
this output equals PC_COUNT; otherwise it outputs high impedance.
RST
PC_LD
An active high signal that synchronously loads D_IN into the PC. This signal
has a higher precedence than the PC_INC input.
PC_OE
PC_INC
An active high signal that synchronously increments the value in the PC.
CLK
Figure 6 shows that you can load the PC from various sources. The MUX allows the PC to
change according to the currently executing instruction. The MUX inputs include:
FRCD
FROM_IMMED: Branch and Call instructions obtain the new value of the PC from the
immediate value included as part of those individual instruction formats.
0x3FF: Interrupts (when the RAT acts on them) set the PC to the interrupt vector:
0x3FF.
- 20 -
Experiment #3
Programming Assignment:
Write a RAT assembly language program that endlessly does the following:
Reads data from input associated with port_id 0x99, divides the data by four, and outputs
the data to the output associated with port_id x033.
Reads data from input associated with port_id 0xA7, changes the sign of the data, and
outputs the data to the output associated with port_id x0B8. For this input, assume the data
read to the input port is in RC form.
- 21 -
Experiment #3
Design a circuit that sums the odd and even contents of a 16x8 RAM upon the pressing of a button. Place
the odd and even sums in separate accumulators.
Questions:
1. The PC has two types of input signals: control signals and data signals, where we consider
the clock input a type of control signal. List which inputs are data inputs and which are
control inputs.
2. If the PC were to increment every clock cycle, could the output of the prog_rom
simultaneously show the value on the current output of the PC? Briefly but fully explain
your answer.
3. We consider a basic increment normal operation for the PC. Briefly describe what the
notion of normal means to an executing computer program.
4. The PC in this experiment is a loadable up-counter. Briefly describe a scenario where you
could possibly use a loadable up/down counter or describe why an up/down counter
would be a strange idea for the PC.
5. In terms of an executing computer program, briefly describe why the FROM_IMMED input
is associated with BRANCH and CALL-type instructions and why FROM_STACK is
associated with RETURN-type instructions.
6. List two instructions from the RAT instruction set that would use the PCs
FROM_IMMED input.
7. List two instructions from the RAT instruction set that would use the PCs
FROM_STACK input.
8. This experiments instructions asked you to keep the MUX and PC modules separate (not in
the same process statement). Though you could have modeled the hardware in this
experiment in one process statement, briefly explain why keeping the modules separate is a
good idea.
9. The RST signal places the state of the PC at 0x000. Describe a situation where you would
want your computer to reset to some location other than 0x000.
10. PC_COUNT and PC_TRI output the same information; the difference being that PC_TRI is
under tri-state control. In the context of shared resources, briefly explain why is it that we
cant remove PC_TRI and have the PC_COUNT always connected to the shared resource
(the MULTI_BUS).
FRCD
- 22 -
Experiment #3
Deliverables:
1. Complete, well-reasoned answers to the questions in Questions section. Completeness
counts. Feel free to include diagrams in your answer.
2. A complete solution to the Programming Assignment. Completeness counts.
3. A complete solution to the Hardware Design Assignment. Completeness and neatness
counts.
4. VHDL code for the PC and support hardware you modeled in this experiment.
5. Schematic diagram showing the three modules you used in this experiment and their
interconnections.
6. Fragment of the assembly language listing file showing the machine code for the program
used in this experiment.
7. Fully annotated simulator output for your testbench (see assignment section for further
details).
FRCD
- 23 -
Experiment #4
Experiment#4:
IntroductiontoAssemblyLanguage
Programming
(andadashofReverseEngineering)
Learning Objectives:
General Notes: This lab demonstrates the concept of reverse engineering as an approach to
present the architecture of the RAT MCU and basic assembly language programming. Reverse
engineering has its place in computer system development as companies vie for market share.
This experiment uses the painful approach or reverse engineering an assembly program (also
known as disassembly) to demonstrate the structure, form, and content of assembly language
instructions.
Assignment: This assignment has two different parts.
Part 1:
a) Figure 8 shows Program #1, an example RAT assembly language program. Enter and
assemble this program in the RAT Simulator. Be sure to include a blank line after the
last line of code.
.EQU LED_PORT
= 0x10
.EQU SWITCH_PORT = 0x40
.CSEG
.ORG
main:
0x40
IN
MOV
MOV
ADD
ADD
SUB
MOV
OUT
BRN
r20,SWITCH_PORT
r10,0xFE
r11,0x02
r10,r11
r10,0x14
r10,0x03
r25,r10
r10,LED_PORT
main
; endless loop
FRCD
- 24 -
Experiment #4
b) Step through the program with the RAT simulator and analyze Program #1 to
determine various values as the program executes. Complete Table 2 by including the
following information after the simulator executes the instruction in the "instruction
column. The value in Table 2 is an example of how one line in the completed table
should appear. The completed table should have one line for each instruction in the
program.
PC Val
(hex)
Instruction
MOV
Dest/Value
R10,0x05
R10 / 0x05
Source/Value
Immed / 0x05
C
Val
Z
Val
Port Address
(if applicable)
N/A
Part 2:
a) Figure 9 shows excerpt from the prog_rom.vhd file associated with a certain program.
Your mission in this part of the experiment is to reverse engineer the machine code and
provide a source code listing for the program that generated the machine code. Note that
you may disregard any other lines from this VHDL file, as the code below provides you
with all the information you need to disassemble the machine code. Also, note that
because the code is located in INIT_02 and fills starting from the least significant byte of
the given listing, the address of the first instruction is located at 0x20.
See the example of reverse engineering a RAT MCU prog_rom.vhd file at the end of this
experiment description. Complete Table 3 for your reverse engineered program (add as
many rows as you need) and include the table in your lab report.
FRCD
- 25 -
Experiment #4
2-bit pairs
from
INITP_00
2 bytes from
INIT_05
(hex)
Assembly Instruction
prog_rom
Mem Loc.
(hex)
b) Enter the reverse engineered program in the RAT MCU simulator; make sure this
program has proper programming style. Step through the program using the RAT MCU
simulator and perform an analysis of your reverse engineered program to determine the
contents of various registers as the program executes. Complete Table 4 for each line of
code in the program.
c) Write a brief but complete comment about what exactly the code in this problem did.
PC Val
(hex)
Instruction
MOV
Dest/Value
R10,0x05
R10 / 0x05
Source/Value
Immed / 0x05
C
Val
Z
Val
Port Address
(if applicable)
N/A
Programming Assignment:
Write a RAT assembly language program that endlessly does the following: inputs ten values
from the input associated with the port_id of 0x9A. Sum these values and store the results in
register r30 (lower byte) and register r31 (upper byte). After you sum these ten values,
continually divide the total by 2 as many times as it takes to make the upper byte (register 31)
equal to zero. Use the RAT Simulator to ensure you program performs as desired.
- 26 -
Experiment #4
Design a circuit that counts the number of values in a 16x8 RAM that are in the range [38,78] upon
the pressing of a button. Consider the contents of RAM to be unsigned binary numbers. Use a counter
module to store the resulting quantity value.
Questions:
1. Briefly describe why the prog_rom.vhd is tedious to interpret.
2. Briefly describe what (or who) determines the number of instruction formats a given
computer architecture contains.
3. List the five RAT MCU distinct instruction formats.
4. The five RAT MCU instruction formats contain different fields for different instructions.
Briefly describe how it is possible for the same sets of bits to satisfy these different field
requirements.
5. Why is it necessary to have assembly language programming when there are much more
portable languages such as C, Java, etc. available?
6. When reverse engineering assembly code, briefly but completely explain why there are
not any text-based label values.
7. Are there any RAT MCU instructions that change the value of the source register?
Briefly but completely explain.
8. What entity provides values to the labels that appear in an assembly language program?
Briefly but completely explain.
9. Is it possible to have two of the same labels in an assembly language program? Briefly
but completely explain.
10. Is it possible to have two or more labels in an assembly language program with the same
numerical value? Briefly but completely explain.
11. The programs you worked with in this experiment were implemented as endless loops.
Using the RAT MCU assembly code, could you write a program in such a way as to stop
the program from executing instructions under program control? Briefly but completely
explain.
12. Briefly but completely describe an instance in which reverse engineering could or has led
to a significant business advantage.
Deliverables:
1. Complete, well-reasoned answers to the questions in Questions section. Completeness
counts. Feel free to include diagrams in your answer.
2. A complete solution to the Programming Assignment. Completeness counts.
FRCD
- 27 -
Experiment #4
.CSEG
.ORG
main:
0x00
MOV
MOV
ADD
ADD
MOV
OUT
BRN
r10,0x05
r11,0x64
r10,r11
r10,0x14
r20,r10
r20,LED_PORT
main
; endless loop
2.) This program produces the following lines in the prog_rom.vhd file. To reverse engineering
the hex values listed in the associated prog_rom.vhd file, extract the contents of the populated
rows from prog_rom.vhd. The underlining shows the bytes of interest.
attribute INIT_00 of ram_1024_x_18 : label is
"0000000000000000000000000000000000008000541054518A142A586B646A05";
attribute INITP_00 of ram_1024_x_18 : label is
"0000000000000000000000000000000000000000000000000000000000000C8F";
3.) Extract the lower 28 bytes of INIT_00 and divide them into two-byte pairs. Notice that there
are seven 2-byte pairs which are non-zero and that our original assembly program had seven
instructions:
FRCD
- 28 -
Experiment #4
equivalent program address
-------------------------0
1
2
3
4
5
6
7
4.) Extract the four non-zero bytes of INITP_00, break into binary equivalent values, and then
break these into 2-bit pairs. Note that you only want the lower seven 2-bit pairs since the
original assembly program had seven instructions:
0C8F = 0000 1100 1000 1111
= 00 00 11 00 10 00 11 11
= 0x00 0x00 0x03 0x00 0x02 0x00 0x03 0x03
5.) Concatenate each 2-bit pair (MSBs) with each 2-byte pair from step #3 to create the 18-bit
instruction. This 18-bit field is the machine code representation of one assembly language
instruction. For example, the right most 2-bit pair of 11 combines with the right-most 2-byte
pair of 0x6A05 to create the 18-bit machine code for the equivalent assembly instruction.
You can now recreate the assembly instructions from the 18-bit binary equivalent of each
instruction by comparing the opcodes and field codes of this instruction to the instruction
format in the RAT Assembler Manual.
2-bit
pairs
from
INITP_00
2 bytes
from
INIT_00
11
0x6A05
MOV
R10,0X05
11
0x6B64
MOV
R11,0X64
00
0x2A58
ADD
R10,R11
10
0x8A14
ADD
R10,0X14
00
0x5451
MOV
R20,R10
11
0x5410
OUT
R20,LED_PORT
00
0x8000
BRN
main_loop
Assembly
Instruction
ProgRom
Mem
Loc.
FRCD
- 29 -
Experiment #5
Experiment#5:
TheRATMCUMemoryModules
Learning Objectives:
- 30 -
Experiment #5
2) Scratch RAM: The RAT MCU implements the scratch memory as a random access
memory (RAM). The Scratch RAM serves two main purposes. First, the scratch RAM
provides temporary storage of data that is accessible using the RAT instruction set. In this
manner, RAT instructions transfer data between the register file and the scratch RAM.
Second, the RAT architecture also uses (shares) the scratch RAM as the storage device
for the stack. The RAT Scratch RAM is 256 locations deep and ten bits wide (256x10).
Data storage on the scratch RAM only uses eight of the ten bits while address storage
uses all ten bits. The RAT MCU reads the scratch RAM asynchronously and writes to it
synchronously (rising edge of clock).
Programming Assignment:
Write a RAT assembly language subroutine converts a three-digit decimal value to binary value.
As indicated below, the 100s digit of the decimal value is stored in the lower nibble of r21, while
the 10s and 1s digits are stored in the upper and lower nibbles of r20, respectively. The CDC
(Center for Disease Control) assures you that the given decimal number is not greater than 255.
Place the final binary number in register r31. Minimize the number of instructions in your
solution.
FRCD
- 31 -
Experiment #5
FRCD
- 32 -
Experiment #5
Deliverables
1. Complete, well-reasoned answers to the questions in Questions section. Completeness
counts. Feel free to include diagrams in your answer.
2. A complete solution to the Programming Assignment. Completeness counts.
3. A complete solution to the Hardware Design Assignment. Completeness and neatness
count.
4. Part 1: Fibonacci sequence using a dual-port RAM
a. Black box diagram for your circuit showing all modules and their interconnections
b. State diagram describing your circuits FSM (with timing calculations)
c. VHDL code for FSM model
d. Demonstrate your working circuit to the instructor or Teaching Assistant
5. Part 2: Fibonacci sequence using a bi-directional RAM
a. Black box diagram for your circuit showing all modules and their interconnections
b. State diagram describing your circuits FSM (with timing calculations)
c. VHDL code for FSM model
d. Demonstrate your working circuit to the instructor or Teaching Assistant
FRCD
- 33 -
Experiment #6
Experiment#6:
TheArithmeticLogicUnit(ALU)
Learning Objectives:
To utilize the relationship between the Arithmetic Logic Units (ALU) requirements and
the ALU-based RAT MCU instructions it supports
To design a basic ALU that supports the RAT MCU bit-crunching operations
To utilize both VHDL variables and signals in a VHDL model
General Notes: The ALU is part of the RAT MCUs central processing unit (CPU). As with
many computers, the ALU is responsible for performing all number crunching operations
including those falling outside of the label of arithmetic or logic. In short, the ALU is
responsible for performing the bit-crunching operations required by many of the RAT MCU
instructions. The ALU is a relatively complex device, but as youll see in this experiment, the
power of VHDL can successfully manage this complexity using behavioral modeling. This
experiment requires that you use VHDL variables in your design; these are slightly different from
signals so you must understand these differences.
Assignment:
1. Implement the 15 RAT MCU arithmetic and logic functions in an ALU. Youll need to
refer to the RAT Assembler manual for an expanded explanation of each of the
associated RAT MCU instructions. Figure 13 shows the black box diagram for the ALU;
Table 5 shows the SEL values you should use for the RAT MCU instructions that require
the ALU.
Figure 13: Black box diagram for the RAT MCUs ALU.
FRCD
- 34 -
Experiment #6
SEL
0000
0001
0010
0011
0100
0101
0110
0111
Instruction
ADD
ADDC
SUB
SUBC
CMP
AND
OR
EXOR
SEL
1000
1001
1010
1011
1100
1101
1110
1111
Instructions
TEST
LSL
LSR
ROL
ROR
ASR
MOV
not used
Instruction
ADD
ADDC
SUB
SUBC
CMP
AND
OR
EXOR
TEST
LSL
LSR
ROL
ROR
ASR
MOV
0xAA,
0x37,
0x64,
0xC8,
0xFF,
0xAA,
0xCC,
0xAA,
0xAA,
0x55,
0x12,
0x33,
0xAB,
0x3C,
0x81,
0x30,
Expected Result
(hex)
Result-based
C_FLAG
Result-based
Z_FLAG
0
1
0
1
0
0
0
0
0
0
1
0
1
0
0
0
FRCD
- 35 -
Experiment #6
Hints:
1) There are a few examples of ALUs modeling using VHDL in the course textbook. These
will be a good starting point for this experiment.
2) Try to keep your code as generic as possible. Keep in mind that your ALU can generate
any Z and C value you please, but it doesnt have to save those values in the C and Z flag
registers (the C and Z flag are part of a future experiment). Note that not all instructions
handle the C and Z flags in a similar manner.
Programming Assignment:
Write a RAT assembly language subroutine that converts an 8-bit unsigned value in register r25
to a three-digit decimal value stored in registers r21 and r20. The result should be in BCD format;
Figure 14 shows the weighting associated with the result. Be sure to clear the upper nibble of
register r21. Minimize the number of instructions in your solution.
Questions:
1. Briefly describe at least two limitations of the RAT ALU.
FRCD
- 36 -
Experiment #6
2. Briefly describe how the CMP instruction allows the assembly language programmer to
determine less than, greater than, and equal to relationships between the
instructions operands.
3. There is an ASR instruction but no arithmetic shift left instruction. Describe how you
could use the given RAT instruction set in order to perform an arithmetic shift left
operation (show a fragment of RAT assembly code that implements an ASR). An
arithmetic shift-left instruction performs a shift left operation but preserves the sign bit of
the register.
4. The TEST instruction is massively useful as it allows you to do certain functions using
fewer instructions. If the TEST instruction did not exist, show the RAT instructions that
would be required to perform the same operation as the TEST instruction.
5. In general, adding new instructions to an instruction set requires that you also provide
extra hardware to support that instruction. Did adding instructions such as TEST or CMP
increase the amount of hardware required by the RAT ALU architecture. Support your
answer with brief but adequate explanation; make sure you can back your answer with
actual evidence.
6. The RAT MCU uses the TEST and AND instructions for bit masking. Describe how you
would need to modify the RAT MCU if you needed to do bit-masking with an OR
instruction.
7. Briefly describe a scenario in which you would you utilize the ADDC vs. the ADD
assembly language instruction.
8. If the ADDC instruction did not exist, show the RAT assembly code that you would use
to implement the same ADDC functionality.
9. Since the AND instruction does not use the C flag, you can use it for something of your
choosing. For this problem, show the VHDL code for the AND instruction if the C flag is
used to describe the parity of the result; assume C = 1 indicates odd parity.
10. The particular form of the LSL and LSR instructions necessitate the need for the CLC
and SEC instructions. Briefly but completely describe why this is so.
11. Briefly describe why there is no need for instructions that do nothing other than alter the
value of the Z flag.
12. The RAT MCUs ALU is a combinatorial circuit. Briefly describe the ramifications in the
context of the RAT MCU architecture if the ALU was not combinatorial. Note that many
ALUs register the result; this register is typically referred to as an accumulator.
FRCD
- 37 -
Experiment #6
Deliverables:
1. Complete, well-reasoned answers to the questions in Questions section. Completeness
counts. Feel free to include diagrams in your answer.
2. A complete solution to the Programming Assignment. Completeness counts.
3. A complete solution to the Hardware Design Assignment. Completeness counts.
4. VHDL source code for your ALU
5. A completed Table 6 (do the operations and include the correct values where possible)
6. An annotated simulator printout that includes each of the instructions in Table 6.
FRCD
- 38 -
Expperiment #7
Experim
E
ent#7:
ItsAlive!
Learnin
ng Objectivess:
To implemen
nt the basic fu
unctionality an
nd implement
ntation (FSM) of a MCU coontrol unit
To implemen
nt a basic fetcch/execute insstruction cyclees for the RA
AT MCU
To actuate th
he appropriatee control signaal for a the RA
AT MCUs innstructions
To implemen
nt your RAT MCU
M
on the development
d
board
FRCD
- 39
3 -
F
FRCD Lab Activvity Manual
Experiment #7
main:
IN
MOV
SUB
OUT
BRN
r10,SWITCH_PORT
r11,0x01
r10,r11
r10,LED_PORT
main
FRCD
- 40 -
Experiment #7
FRCD
- 41 -
Experiment #7
Programming Assignment:
Write a RAT MCU assembly language subroutine that counts the number of bits that are set in register
r10 and r11. If both registers have the same number of bits set, clear both registers. Otherwise, replace
the value in the register with more bits set with the number of bits that are set in that register (dont alter
the other register). Minimize the number of instructions you use in your solution.
FRCD
- 42 -
Experiment #7
Device
prog_rom
register file
program counter
stack pointer
flags(I,Z,C,shZ,shC)
scratch RAM
Size
1024 x 18
32 x 8
10
8
5x1
256 x 10
TOTAL
# bits
18432
256
10
8
5
2560
21,271
Questions:
1. How many different instruction formats does the program in this experiment use? Make a list of
the instruction and their formats for this question.
2. In your own words, briefly but completely describe the purpose of the RAT wrapper.
3. Briefly but completely describe the relationship between the IN and OUT instructions and the
port_IDs assigned in the RAT Wrapper VHDL model.
4. Which of the modules you used in this experiment are combinatorial and which are sequential
circuits? Be sure to include a complete list of modules when you answer this question.
5. This experiment implements the C and Z flags as flip-flops. Briefly describe why the RAT
MCU architecture requires that these devices have different control features.
6. The RAT MCU implementation in this experiment lacks a few important RAT MCU modules.
Estimate which percentage of RAT MCU instructions you can fully implement with the RAT
MCU hardware in this experiment.
7. Briefly explain in the context of the RAT MCU control unit why all FSM outputs were
scheduled to be assigned values as the first step in the control units combinatorial process.
8. This experiment asked you to include only the control signals that a particular instruction used
regardless of whether they were previously scheduled to be assigned to zero(s). Briefly state
why this approach represents excellent VHDL coding style.
9. How much memory does the control unit use in this experiment contain? Also, state which
signal represents that memory.
10. In assembly language-land, we refer to instructions that do nothing as nops (pronounced
know ops). Many assembly language instructions actually have dedicated nop instructions,
but the RAT MCU does not. What is the one and only way to effectively fake a nop instruction
using the RAT MCU instruction set?
FRCD
- 43 -
Experiment #7
11. Describe a situation where a NOP instruction or a NOP-type instruction would be useful.
12. Briefly describe the difference in control signals between reg/reg and a reg/imm-type instruction
for any ALU-based instruction. Comment on whether these differences will expedite your work
when youre required to implement a majority of the RAT instructions in the next experiment.
Deliverables:
1. Complete, well-reasoned answers to the questions in Questions section. Completeness counts.
Feel free to include diagrams in your answer.
2. A complete solution to the Programming Assignment. Completeness counts.
3. A complete solution to the Hardware Design Assignment. Completeness counts.
4. An annotated simulator printout showing correct functionality of your RAT MCU for the test
program. At the very least, show that you can read in a value from the switches and output one
less than that value to the LEDs on the development board (according to the provided assembly
language program). Be sure to include the PC output, the prog_rom output, and the IO_STRB
output in your simulator timing diagram.
5. VHDL source code for the control unit module.
FRCD
- 44 -
Experiment #8
Experiment#8:
FullBoogieMCUGeter
Done
Learning Objectives:
General Notes: Most every MCU design contains both the notion of a stack and an other generic
memory to store data under program control. Many MCUs, such as the RAT MCU, use the same
physical memory device (the scratch RAM) for both the stack for generic data storage. The overall
purpose of the RAT MCUs scratch RAM is to store information vital to the operation of the RAT
MCU.
The notion of stack oriented instructions includes instructions that modify both the scratch RAM and
stack pointer. Memory oriented instructions use scratch RAM without modifying the stack pointer as
part of generic data storage operations under program control. Table 7 lists the instructions associated
with and/or using the scratch RAM.
Stack-Oriented Instructions
Memory-Oriented Instructions
WSP
CALL
RET
PUSH
POP
LD
ST
(register indirect)
(register indirect)
LD
ST
(immed indirect)
(immed indirect)
The scratch RAM in the RAT MCU is a memory device that can of store two types of data. The RAT
MCU needs the ability to store 8-bit values data from memory-type instructions (data values) and 10-bit
data from stack-type operations (address values). The ST (store) or PUSH instructions write 8-bit data
values to the scratch RAM from registers; the LD (load) or POP instructions read 8-bit data from the
FRCD
- 45 -
Experiment #8
scratch RAM and write the data to registers. The 10-bit values represent the address of instructions in
program memory; CALL instructions write these addresses to scratch RAM and return-type instructions
(RET, RETIE, & RETID) read these addresses from scratch RAM and copy them to the program
counter. While LD and ST instructions do not involve the stack, the PUSH/POP and CALL/RET
instructions utilize the stack. Using the scratch RAM for both stack and generic data storage operations
creates extra management work for the programmer because the programmer is responsible for
maintaining the integrity of the stack while having the program operate properly.
The key to stack integrity starts with the stack pointer. The RAT MCU uses the stack pointer as a
storage device to hold the address of the current top-of-the stack. Recall that the top-of-the-stack is
address of the most-recent item stored on the stack. Thus, the stack pointer is a register, or a counter to
be exact, that contains the address of the most recent data stored on the stack. Integral to the proper
stack operation is to place the stack pointer in a known state, or in other words, intentionally place a
value into the stack pointer; the RAT MCU uses the WSP (write stack pointer) instruction for this
purpose. The result is that the initialization portion of every viable RAT MCU assembly language
program necessary contains a WSP instruction. The MCU developer may also use the reset signal to
initialize the stack pointer to zero, ensuring that a known the stack pointer value upon system reboot, but
many embedded systems contain no such magic reset-ability.
The RAT Assembler Manual states that the stack pointer is pointing to the most recent item stored on
the stack, or the top of the stack. You can ascertain this approach by examining the RTL equations
associated with various stack-oriented instructions. For this description, well examine only the PUSH
and POP instructions, which we highlight in Table 8.
The implementation of the PUSH instruction involves decrementing the stack pointer. Though it may
seem strange, the fact is that most computer architectures point the stack pointer to some relatively high
memory address and use decrements as part of the storage process (and increments as part of the
retrieval process). In this way, the stack grows from higher memory addresses towards lower memory
addresses, staying as far away as possible from memory that may have been defined as part of the startup code or under program control (using LD-type instructions). This provides the opportunity for the
stack to be as large as possible given the memory constraints provided by programmer-initiated data
definitions (assembler directives). Once again, maintaining stack integrity is part of the programmers
responsibility; programmers need to understand the software tools (primarily the assembler) and the
underlying hardware (scratch RAM usage) in order to ensure stack integrity.
PUSH
RTL
(SP1)Rd,SPSP1
POP
Description
RTL
Description
Rd(SP),SPSP+1
FRCD
- 46 -
Experiment #8
Assignment:
1. Create your stack pointer module according to Figure 19. The best starting point for this step is
the generic counter template.
LD is a synchronous control signal that enables the loading of input data to the stack
pointer. When LD is 1, the stack pointer loads the DATA input value.
Keep in mind that if neither INCR, DECR, nor LD are asserted, the stack pointer does not
change state. The precedence of these signals does not matter as youll design your control unit
to never assert more than one of these signals at a time. Generally speaking, load inputs have
precedence over the increment and decrement inputs.
- 47 -
Experiment #8
Special RAT MCU Testing Requirements: You cant overstate the importance of ensuring that your
RAT MCU is working properly. Accordingly, there a relatively large suite of test programs that you
should use to test your RAT MCU design. There are seven main test programs; some of these test
programs have slightly different versions. Additionally, you can find all the test programs concatenated
into one assembly language program: testAll.asm
The nice part about the testAll.asm program is that it provides a means to visually your hardware. If
your program passes the visual test, you probably implemented your hardware correctly; otherwise,
youll need to delve down into the guts of the assembly language program in order to ascertain what
instruction caused the test to fail, and/or debug the program in the simulator.
Programming Assignment:
You decided that you need another stack, but your only option is to create a firmware-based stack.
Using r31 as a stack pointer, write push and pop subroutines that would allow you to simulate a
stack starting at scratch RAM address 0xD0. Assume register r30 will be the register you use to pass
data to your stack (the push subroutine) and from your stack (the pop subroutine). Dont allow these
subroutines to permanently change any register values other than r30 and r31.
Device
prog_rom
register file
program counter
stack pointer
flags(I,Z,C,shZ,shC)
scratch RAM
Size
1024 x 18
32 x 8
10
8
5x1
256 x 10
TOTAL
# bits
18432
256
10
8
5
2560
21,271
Questions:
1. Rewrite the RTL equations of Table 8 to reflect the notion of a PUSH incrementing the stack
pointer and a POP decrementing the stack pointer. Additionally, add intelligent comments on
whether you feel there is an advantage to doing it one way or the other.
2. Three modules in the RAT architecture are capable of driving the MULTI_BUS. For each of
these three devices list the RAT instructions that cause that particular device to drive the
MULTI_BUS.
3. We refer to the scratch RAM as a higher level of memory compared to the register file.
Briefly describes what this means in the context of the RAT MCU.
FRCD
- 48 -
Experiment #8
4. The scratch RAM is a 256x10 RAM. Briefly but complete describe why the scratch RAM is 10bits wide yet the registers in the register file are only 8-bits wide.
5. In the context of using an FPGA to implement your RAT MCU, briefly but completely describe
whether you can be sure where the stack pointer is if you dont specifically initialize it using a
WSP instruction.
6. In this lab activity, you implemented the stack pointer as a counter. Briefly describe the
supporting hardware if you had to implement the stack pointer as a loadable register.
7. Write a RAT assembly language subroutine that swaps the data in two locations in scratch
RAM. Registers r30 and r31 contain the addresses in scratch RAM of the two locations that
require swapping. Make sure the subroutine does not permanently change any register values.
8. Write a RAT assembly language subroutine that initializes all scratch RAM memory locations
to 0x00. Dont use PUSH instructions in your solution.
9. Write a RAT assembly language subroutine that initializes all scratch RAM memory locations
to 0xFF. Dont use ST instructions in your solution.
10. Write a RAT assembly language program that swaps the values in two different registers
without accessing memory or changing the value in any register other than the two registers in
question.
11. Briefly but completely describe the changes to the RAT MCU architecture required if you were
to implement the stack and data storage RAM as separate modules.
12. Briefly but completely discuss the advantages, if any, of implementing the stack and generic
storage RAM as separate modules.
Deliverables:
1. Complete, well-reasoned answers to the questions in Questions section. Completeness counts.
Feel free to include diagrams in your answer.
2. A complete solution to the programming Assignment. Completeness counts.
3. A complete solution to the Hardware Design Assignment. Completeness counts.
4. VHDL source code for your stack pointer
5. Well-commented test program source code
FRCD
- 49 -
Experiment #9
Experiment#9:
Interrupts
Learning Objectives:
General Design Notes: Interrupts: If youre like most humans, you occasionally need a haircut. It
would be a strange world if the person who cuts your hair called you every five minutes and asked you
if your hair needs cutting. Naturally, a better approach (more efficient? less annoying?) would be that
when you needed a haircut, you simply call the person who cuts your hair and schedule an appointment.
Requesting some type of service is the general approach humans take in most facets of their lives
(unless you work in the sales where youre required to continually ask others if they want service).
Not surprisingly, an analogous situation exists in microcontroller applications. Programs you write
generally do something, i.e., they execute some finite number of relatively useful tasks. The two
approaches to implementing tasks are analogous to the example above: you either constantly check to
see if tasks need doing and perform them if they do, or you perform those tasks only when they ask
you to perform them (generally, theyll only ask when the task needs doing). Microcontroller lingo
refers to the act of constantly asking if a task needs attention as polling. We refer to handling these
tasks only when the task requests service as interrupt driven, or real-time, and thus require the use of
the MCUs interrupts.
This experiment introduces some of the theory and concepts behind implementing the hardware that
support writings assembly language programs that utilize interrupts. Because of the simple nature of the
RAT MCUs interrupt architecture and the fact that an in-depth study of interrupt-driven systems is
beyond the scope of this experiment, the approach taken in this experiment only touches upon the basics
of interrupt handling. Please refer to the course text for further details.
Polling is a relatively simple concept but it does have one large drawback: its inefficient to continually
ask a device if it needs something when the device has nothing that needs doing. In terms of MCU
processing, if the MCU is polling, it is not doing something else that could be potentially more
important (as in time critical). The result is that you lower the overall throughput of your system if
youre wasting clock cycles in a polling loop. Once again, a more efficient approach in terms of MCU
processing is to allow individual circuit elements that occasionally need attention from the MCU to have
those circuit elements directly request processing from the MCU. The notion of a hardware interrupt
provides a mechanism for such a request. Note that its comfortable to say polling is bad, but in reality,
its only bad if the processor has something more important to do. In real life, your MCU may be idle
sometimes when nothing needs doing; during those times, you can consider polling acceptable. Thus,
there are gray areas in this discussion.
FRCD
- 50 -
Experiment #9
The term interrupt comes from the fact the normal operation of the microcontroller is temporarily
interrupted to handle some other task. Once microcontroller handles the other task, the microcontroller
returns to the task it was executing when it received the interrupt. Though microcontrollers in general
use three types of interrupts (internal interrupts, external interrupts, and software interrupts), the RAT
MCU only handles one external interrupt. Unfortunately, there is no single method used by all
microcontrollers to handle interrupts, so examining the interrupt architecture is one of the first things
you typically do when working with a new microcontroller.
We refer to the interrupt handling mechanism in the RAT MCU as a vectored interrupt. Once the RAT
MCU receives an interrupt, program control transfers to a pre-determined address in instruction memory
after execution of the current instruction completes. We refer to this address as a vector address, and the
instruction at this address generally contains a BRN instruction (unconditional branch). The instruction
branched to is the starting address of the interrupt service routine (ISR). The code in the ISR generally
implements some task that appropriately handles the interrupt, which is why people sometimes refer to
ISRs as interrupt handlers. When the MCU finishes executing the ISR, the MCU returns program
control to the instruction following the instruction the MCU was processing when it detected the
interrupt.
The concept of an interrupt is essentially provides a method for hardware to call a special subroutine:
the interrupt service routine, or ISR. When the RAT MCU receives an interrupt, part of the automatic
response of the hardware is to prevent the RAT MCU from acknowledging any further interrupts until it
completes processing of the current interrupt (the ISR is executed). We refer to the act of preventing the
RAT MCU from processing interrupts as interrupt masking. Remember, preventing the RAT MCU
from acting on interrupts does not prevent the interrupts from happening; it only allows the RAT MCU
to ignore any occurrence of an interrupt. You can use the SEI instruction (set interrupt enable) to allow
the RAT MCU to unmasking interrupts or the CLI instruction (clear interrupt enable) to mask interrupts.
The concept of ISRs is similar to a simple subroutine. The big difference is that programs call
subroutines under program control (firmware) while ISRs are called under external hardware control.
The ramifications of this difference is that ISRs are asynchronous in that they can happen anytime,
while subroutines are under program control and are thus synchronous.
The RAT MCU Interrupt Architecture: Low-Level Details of Interrupt Handling: The RAT MCU
handles the low-level mechanics of interrupt processing in a manner similar to the handling of
subroutine CALLs and RETs, which makes interrupt processing simply another form of flow control
management in the RAT MCU. When the RAT MCU senses that the signal attached to its interrupt
input is asserted and the interrupts are currently unmasked, it completes execution of the current
instruction before it starts processing the interrupt. The first step in the processing of the interrupt is to
place the vector address in the program counter, which forces the RAT MCU to next execute the
instruction at location of the vector address. The RAT MCU hardwires the vector address to 0x3FF. At
the same time, the RAT MCU pushes the address of the next instruction that would have been executed
had it not acted on an interrupt onto the stack. In addition, the RAT MCU simultaneously saves the
context of the RAT MCU by saving the current values of the carry and zero flags into the shadow
carry and zero flag registers.
Processing the ISR begins with the RAT MCU acting on an interrupt and continues until the RAT MCU
encounters a RETIE or a RETID instruction. Execution of one these instructions causes the RAT MCU
to pop an address off the stack and into the PC; this instruction should be the address of the next
instruction that would have been executed had the MCU not acted on the interrupt. In addition, the RAT
FRCD
- 51 -
Experiment #9
MCU simultaneously restores the context of the processor at the time the interrupt was received by
copying the contents of the shadow carry and zero flags into the actual carry and zero flags. Figure 20
provides a summary of these steps in a rough order of occurrence (many items occur simultaneously).
The RAT MCU detects an asserted signal on the interrupt input (assume the RAT MCU has not masked the
interrupt)
Execution of the current instruction completes and the RAT MCU goes into an interrupt cycle
The RAT MCU automatically mask the interrupt so it will ignore further interrupts
Address of next instruction (not in ISR) is stored on the stack
The program counter is loaded with 0x3FF
The present state of the RAT MCU is saved (zero and carry flags are copied to shadow flags)
The instruction at location 0x3FF is executed (a branch instruction that directs program control to the address of
ISR)
Execution of the ISR begins.
Execution of the ISR completes
The program issues a RETIE or RETID instruction
The RAT MCU pops the address of the next instruction to execute off the stack and places it in the program
counter
The context is restored by copying the shadow carry and zero flags to the actual carry and zero flags
Execution resumes at the instruction following the one that was executing when the RAT MCU got the interrupt
General Design Notes: The RAT MCU Control Unit Modifications for Interrupts: Interrupts on the
RAT MCU are primary handled by the control unit. For this experiment, you must modify the control
unit so that it contains an extra state that handles the needs of the RAT MCUs interrupt architecture.
The proper vernacular for this modification is to include an interrupt cycle in the current FSM. Try not
to panic; Figure 21 shows the required modifications to the RATs control unit in order to support an
interrupt cycle. Note that entry into the interrupt cycle occurs when the RATs INT input is asserted at
the end of the execute cycle. In the INTERRUPT state, the control unit asserts the controls signals
required to implement the various hardware aspects of interrupt architecture.
Figure 21: The RAT control unit state diagram showing interrupt cycle.
As you can gather from Figure 21, modifications to the control unit are relatively trivial due to your
burgeoning expertise in the area of modeling FSMs in VHDL. Possibly the hardest part with this
modification is that youll need to remember to add INT to the process sensitivity list of the
FRCD
- 52 -
Experiment #9
combinatorial process associated with the FSM. Figure 22 provides you with some code to get your
modification juices flowing.
Figure 22: Control unit modification overview for the interrupt cycle.
Assignment:
1) Add/modify the following modules in your RAT MCU (consult the architectural diagram for
details):
Modify the FLAGS module to include the shadow carry and zero flags
2) Modify your RAT MCU such that it can process interrupts and execute the following RAT
assembly instructions: RETIE, RETID, SEI, and CLI. This step includes control unit
modifications for both the structure of the FSM as well as the implementation of these
instructions.
3) Test your interrupt functionality using the simulator. Make sure you show both an interrupt
cycle and a return from interrupt. Include the PC, interrupt signal, and FSM state (PS) in your
timing diagram output.
Programming Assignment:
Write an interrupt driven program that blinks the LEDs. Every interrupt alternately turns on/off the
LEDs. The LEDs that turn on are the ones corresponding to the most recent value on the switches.
Minimize the number of instructions you use in your neatly written solution. Constraint: Do not use IN
instructions inside the ISR.
.EQU
.EQU
FRCD
LEDS
SWITCHES
= 0x74
= 0x75
- 53 -
Experiment #9
Device
prog_rom
register file
program counter
stack pointer
flags(I,Z,C,shZ,shC)
scratch RAM
Size
1024 x 18
32 x 8
10
8
5x1
256 x 10
TOTAL
# bits
18432
256
10
8
5
2560
21,271
Questions:
1. List the differences between a RETIE instruction and a RET instruction.
2. Based on the state diagram in Figure 21, would it be possible to assert the interrupt signal and
not enter into an interrupt cycle? Briefly but completely explain. Assume the interrupt is
unmasked.
3. Interrupt architectures generally always automatically mask interrupts upon receiving an
interrupt. Briefly but completely describe why this is the a good approach.
4. For the RAT MCU, there is only one state associated with the interrupt cycle, which means
there is only one associated clock cycle. Briefly but completely describe in general what
dictates how many clock cycles a given MCU requires for the interrupt cycle.
5. We generally consider interrupts asynchronous in nature. However, looking at Figure 21, the
interrupts appear to be synchronous. Briefly describe what it means for the interrupts to be
asynchronous.
6. The RAT MCUs idea of saving context is to save the C and Z flags to the shadow C and Z flag.
Describe a set of modifications you would need to make to the RAT MCU hardware to support
the saving of all the registers in the register file.
7. The previous question had a major drawback: saving all the registers. Briefly describe all
aspects of why saving all the registers would be a drawback.
8. Briefly describe an approach that could save and restore registers under program control when
the RAT MCU acts upon an interrupt.
9. Briefly but completely describe the major problem with the RAT MCU receiving an interrupt
while it is in the act of processing an interrupt. For this problem, consider both the notion of
interrupts being masked and unmasked (two cases).
FRCD
- 54 -
Experiment #9
10. I had this great idea to make interrupt processing faster: I would enter the interrupt cycle after
the fetch cycle when possible. Briefly but completely describe how you would implement this
and whether it is worth the effort or not.
11. Briefly but completely describe why the interrupt vector addresses are typically placed at the
end of program memory.
Deliverables:
1) Complete, well-reasoned answers to the questions in Questions section. Completeness counts.
Feel free to include diagrams in your answer.
2) A complete solution to the programming Assignment. Completeness counts.
3) A complete solution to the Hardware Design Assignment. Completeness counts.
4) VHDL code showing the modifications to the RAT MCU control unit for this experiment.
Please dont print the entire control unit module.
5) A simulator generated timing diagram (with annotations) showing that your interrupt works
properly. Base this timing diagram on a simple interrupt driven program. Be sure the timing
diagram includes the program counter output, the interrupt signal, and the control unit state
output. Make sure your timing diagram includes a return from the interrupt.
FRCD
- 55 -
Experiment #10
Experiment#10:
SwitchDebouncingand
FirmwareDisplayMultiplexing
inandaRealTimeEnvironment
Learning Objectives:
To review the RAT interrupt architecture and use interrupts in an actual application
To learn about switch bounce and debouncing requirements for external input
To learn the concepts of seven-segment display multiplexing
To implement a firmware look-up table on the RAT MCU
General Design Notes: Switch Bounce: Mechanical switches present design challenges when you use
them in conjunction with fast devices such as MCUs. Mechanical switches tend to bounce when
actuated; this means that when you actuate a switch (move it from the off to on position), the switch can
bounce back and forth between on and off before the switch eventually settles in the on state.
The result is that one intentional physical button press may effectively result in many unintentional
button presses. Because MCUs typically execute instructions on the nanosecond level, hardware
designers and/or firmware programmers must account for these unintentional actuations in order to
ensure proper operation of their designs. Figure 23 shows an example of switch bounce switch. (source:
http://www.ganssle.com/debouncing.htm).
- 56 -
Experiment #10
the firmware solution unnecessarily complicates your firmware, which is something you always want to
avoid (particularly when we only have one interrupt available). This experiment depends on button
presses, so youll need to debounce the button in hardware in order for the experiment to work properly.
The good news is that this experiment provides you with a viable hardware switch debouncer; youre
mission will be to declare it and instantiate it in your design. This device actually serves two functions:
it debounces the button and provides an output with one-shot characteristics. The one-shot ensures
Real-Time Program Architecture: The notion of real-time programming essentially means that youre
using interrupts in your program. The real-time label comes from that fact that if youre using
interrupts, your program will be able to react instantly to something in your system that requires
attention. This is somewhat of an advanced concept, so well not go there in this course. What is
important to know is that we divide the assembly code in real-time programs into two distinct parts: the
main code and the ISR code, also referred to as the foreground task (the main code, the task code) and
the background task (the ISR code).
You can model an interrupt driven program as the MCU executing the foreground task while it is
essentially waiting for an interrupt; when it receives an interrupt, the MCU executes the code associated
with the background task. The important thing to realize is that the RAT MCU is always executing some
instructions; what we can officially say is that the MCU executes the main code while waiting for an
interrupt. When the MCU receives an interrupt, it switches to executing the ISR. What you need to be
thinking is for relatively simple programs such as the one in this experiment is what are the
responsibilities of the main code and what are the responsibilities of the ISR code.
Once again, many of the details of real-time programming are outside of the scope of the course. But,
the one embedded systems principle you should follow is the notion that you should keep your ISR as
short as possible. Why? Because it protects the real-time nature of your program. Recall that when you
receive an interrupt, the RAT hardware automatically masks the interrupts. When the interrupts are
masked, you cant receive any more interrupts, which means if there is some device that requires the
MCU attention (such as your pacemaker), the device is not going to get that attention until the interrupts
are unmasked under program control. Massively interesting!
Assignment:
1) Modify your RAT MCU so that the left-most button on the development board connects to the
interrupt input on the RAT Wrapper.
2) Modify your RAT MCU to include the debounce/one-shot circuitry. The output of the
debounce/one-shot circuitry connects to the interrupt hardware portion of the RAT MCU. Make
your modifications on the RAT MCU level and not in the RAT Wrapper.
3) Write a RAT assembly language program that does the following:
a. Counts the number of interrupts received by the system; a push of the left-most button
on the development board should generate an interrupt.
b. Displays the number of interrupts received by the system (in decimal) on the two rightmost 7-segment displays of the development board. After the interrupt count reaches
49, the display rolls over to zero and the interrupt counting continues. Be sure to
employ lead-zero blanking on the 7-segment display.
4) Demonstrate your working program to your instructor or TA.
FRCD
- 57 -
Experiment #10
NOTE: You must avoid the ghosting effect; the code you write should drive the two 7-segment displays
in a clear manner. If a display or segment appears dim, then you are driving that segment when you
should not be. To avoid the ghosting effect, make sure that your code enables the correct 7-segment
displays only after you write the correct data to the displays segments.
Hints: Any time you work with interrupts, the first order of business when debugging you unit (the
firmware and hardware package) is to verify youre program makes it to the ISR. In other words, you
need to verify youre receiving an interrupt and the unit is acting properly when youre receiving that
interrupt. The best approach to do this is to first verify you can turn on an LED outside of the ISR (in
your main code). If you can do this, then you know you can turn on an LED inside of the ISR. The next
task is then to turn on an LED inside of the ISR and immediately stop your program. You of course
cant stop your program but you can make it seem as if it is stopped by inserting the following line into
your assembly code: killme: BRN
killme. And if you have any better tricks, Id love to hear
about them.
Suggested Implementation Approach: This experiment uses a hardware interrupt, which means that
there is a signal physically attached to the interrupt pin on the RAT MCU. When this signal is asserted
(goes to 1 in this case), the RAT MCU enters into a preset sequence of events. Future interrupts will
only be handled if the interrupts are re-enabled under software control (with either a RETIE or SEI
instruction). For this experiment, you connected the left-most button (an arbitrary choice) to a
debounce/one-shot circuit, which you then connected to the RATs interrupt pin.
The general structure of an interrupt-driven program is to have the program spend most of the time in
the foreground task and enter the background task when the MCU processes an interrupt. The best way
to approach this experiment is to implement the foreground task, and then add the background task (the
interrupt processing) once the foreground task is working properly. The foreground task you should
implement is this: have the RAT MCU read from two registers; each of these registers holds a BCD
number (a tens digit value and a ones digit value). Display these two numbers on two digits of the 7segment display. Youll need to multiplex the displays in order to view both numbers simultaneously.
Once you complete the above foreground task, you then include the background task in your program.
For this experiment, the background task consists of handling button presses connected to the RAT
MCU interrupt. The background task keeps tracks the number of button presses in two registers (the
tens value and the ones value). In this way, the background task handles updates of the count while the
foreground task handles the display of the count. Keep in mind that you should place all major functions
in subroutines and the main body of your code should primarily be comprised of a series of subroutine
calls.
Programming Assignment:
Write an interrupt driven program that toggles LEDS(0) based on the switch settings. If SWITCHES(0)
is set, LEDS(0) toggles every eighth received interrupt; otherwise LEDS(0) toggles every fifth received
interrupt (assume some external device generates interrupts). Make sure that a change in SWITCHES(0)
restarts the interrupt count at zero. Minimize the number of instructions you use in your neatly written
solution. Constraint: Do not use IN instructions inside the ISR.
.EQU
.EQU
FRCD
LEDS
SWITCHES
= 0x44
= 0x45
- 58 -
Experiment #10
Device
prog_rom
register file
program counter
stack pointer
flags(I,Z,C,shZ,shC)
scratch RAM
Size
1024 x 18
32 x 8
10
8
5x1
256 x 10
TOTAL
# bits
18432
256
10
8
5
2560
21,271
Questions:
1. Briefly but completely explain why, in general, why is it important to keep your ISRs as short
as possible.
2. We often consider the ISR code as having a higher priority than the non-interrupt code.
Briefly but fully explain this concept.
3. If you were not able to use a LUT for this experiment, briefly but completely describe the
program you would need to write in order to translate a given BCD number into its 7-segment
display equivalent.
4. If you needed another LUT for this experiment that used some other 7-segment display
representation for BCD numbers, show some code that you could use to access that LUT.
Assume this LUT starts at scratch RAM address 0x80.
5. What is the minimum amount of time an ISR requires to execute? This is the time from when
the MCU switches to the interrupt state to when the processor begins executing the next
intended instruction, which was scheduled to be executed before the interrupt processing
started. Provide a concise answer with adequate description. Assume the interrupts return from
the ISR in the disabled state.
6. As you know, part of the interrupt architecture includes the RAT MCU automatically masking
the interrupts. This being the case, why then is there a need to keep the overall output pulse
length of the interrupt relatively short?
7. As you know, there are such things as nested subroutines; there also is a notion of nested
interrupts? Briefly explain how you could allow nested interrupts to occur under program
control on the RAT MCU.
8. In theory, how deep could you nest interrupts on the RAT MCU? Briefly but concisely, explain.
FRCD
- 59 -
Experiment #10
9. Briefly but completely describe how you could use a LUT to make the output of an up counter
appear on the display as if it were a down counter.
10. Write some RAT assembly code that would effectively implement a firmware debounce for a
given button. For this problem, assume the button youre debouncing is associated with the LSB
of buttons addressed by port_ID 0x55. Make sure to fully describe your code with instruction
comments and header comments.
11. Write a subroutine that compliments each value associated with a BCD-to-7-segment decoder.
Assume the address of the LUT starts at the value in register r31. Make sure your subroutine
does not permanently change the value of any register. Assume the value in r31 is less than
0xF5.
12. Describe why the previous problem includes an assumption that the starting address of the LUT
is less than 0xF5.
Deliverables:
1) Complete, well-reasoned answers to the questions in Questions section. Completeness counts.
Feel free to include diagrams in your answer.
2) A complete solution to the Programming Assignment. Completeness counts.
3) A complete solution to the Hardware Design Assignment. Completeness counts.
4) Well-structured and well-commented RAT assembly code for your RAT program
5) A flowchart(s) for your RAT assembly code
FRCD
- 60 -
Experiment #11
Experiment#11:
InterfacingtheRATMCUtoan
ExternalPeripheral
Learning Objectives:
To use the RAT MCU to interface with an external a timer-counter peripheral device
To write an interrupt driven RAT assembly program
General Design Notes: External Device Interfacing: Microcontrollers are useful because of their
ability to interface with other digital devices in a digital system. We typically refer to such digital
devices as computer peripherals, or peripherals. Having peripherals out there fulfills the
microcontroller promise in that that micro refers to computer and controller describes the main
purpose of that computer device. Lets face it, embedded systems are what currently run the world; at
the heart of an embedded system is an embedded computer. While there are many devices out there such
as computers (desktops, laptops, pads, etc.) there are actually orders of magnitude more embedded
systems out there.
This experiment is uses a relatively simple version of one of the most popular peripherals out there: the
timer-counter. This peripheral is so common and so powerful that many high-end MCUs have more than
ten different independent timer-counters on one MCU device. Timer-counters typically come in the
form of internal peripherals, meaning that they are included on the same piece of silicon as the MCU
itself. There are also many external peripherals dedicated to timing-type tasks, which you can include in
your designs in case your MCU does not provide all the internal timers you need. The timer-counters on
hardcore MCUs are much more feature-laden then the timer-counter in this experiment.
High-Level Timer-Counter Description: Figure 24 shows the black-box diagram for the timer-counter
module. The timer-counter is an up counter that automatically counts up when the device is enabled.
The user can preset a terminal count for the timer-counter; when the timer-counter reaches that
terminal count, the timer-counter outputs a positive output pulse that is two clock periods wide. You can
use this pulse output as an input to the RATs interrupt input. In this way, the timer-counter can
automatically generate interrupts in at a frequency specified by the programmer by writing to the timercounters registers that hold the terminal count. The timer-counter also has a clock pre-scaling feature to
allow programmers to further reduce the frequency of generated interrupts.
FRCD
- 61 -
Experiment #11
Signal
Description
tcen
ps(3:0)
FRCD
- 62 -
Experiment #11
Assignment A:
Write an interrupt driven program that uses the provided timer-counter module to blink an LED at
various rates. Specifically, implement the following functionality:
If only the left-most switch on the development board is on, the right-most LED blinks at a
0.5Hz rate
If only the right-most switch is on the development board is on, the right-most LED blinks
at a 10Hz rate
For any other switch setting, all the LEDs are off
Assignment B:
Write an interrupt driven program that uses the provided timer-counter module to blink an LED
with various attributes. Specifically, implement the following functionality:
If only the left-most switch on the development board is on, the right-most LED blinks at a
0.5Hz rate and a 50% duty cycle.
If only the right-most switch is on the development board is on, the right-most LED blinks
at a 1Hz rate with a 10% duty cycle.
For any other switch setting, all the LEDs are off
Constraints:
You must use the timer-counter module to generate interrupts to create the required blink rates. For
this experiment, you dont need to debounce the switches.
HINTS:
Dont do both assignments; do the one your instructor directs you to do.
While we always consider polling to be a bad thing, you must poll the switches for this
experiment. This is because the timer-counter module is using the RAT MCUs interrupt input,
which would be the most desirable option.
Be sure to examine and understand the example timer-counter program associated with the
timer-counter module. Understanding this program makes this experiment rather straightforward.
FRCD
- 63 -
Experiment #11
Programming Assignment:
Write a RAT MCU assembly language subroutine that ensures the values in a range of unsigned binary
values stored in scratch RAM are all odd. For this problem, you may need to modify the values stored in
scratch RAM; in this case, change the magnitude of the number by the smallest amount to achieve odd parity.
For non-trivial problems such as this one, you should structure the program to include subroutine calls. Also,
include a flowchart that describes your subroutine. This subroutine should not change any register values.
Device
prog_rom
register file
program counter
stack pointer
flags(I,Z,C,shZ,shC)
scratch RAM
Size
1024 x 18
32 x 8
10
8
5x1
256 x 10
TOTAL
# bits
18432
256
10
8
5
2560
21,271
Questions
1. If you did not have a timer-counter peripheral, briefly explain how you would use the RAT
assembly language to blink an LED at a given frequency.
2. In the context of the previous question, why is blinking an LED more efficient when you use
the timer-counter to generate interrupts as compared to your answer to the previous question.
3. The timer-counter module uses a clock pre-scaler. Briefly describe how you would model the
timer-counter without the pre-scaler yet still be able to attain approximately the same blink rates
as with the prescaler.
4. Examine the VHDL model for the timer-counter and briefly but completely describe how it
operates. Be sure to mention both the counter portion as well as the pre-scaler.
5. If the program changes the clock pre-scaler value while the timer-counter is counting, briefly
explain when will the new pre-scaler value actually take affect?
6. If you configured the timer-counter to generate an interrupt on the RAT MCU every 10ms, what
is the highest frequency blink rate of an LED using that interrupt? Briefly explain your answer.
7. Briefly but completely explain how using the clock prescaler will prevent the firmware
programmer from blinking the LED at all possible frequencies lower than the system clock
frequency. For this problem, assume the timer-counter module uses the system clock.
FRCD
- 64 -
Experiment #11
FRCD
- 65 -
Experiment #12
Experiment#12:
TheFinalProject
Learning Objectives:
General Overview: Though you technically know everything there is to know about the RAT MCU,
youre still a bit thin on actual RAT programming experience. Specifically, while Experiment 10 used
many aspects of the RAT MCU including indirect memory access and interrupts, the programming
required by the solution was actually quite short. Additionally, youve not had to interface with a
significant number of peripheral devices in the experiments thus far.
The underlying goal of this experiment is to provide you with a path that will enable you to tie together
any loose ends in this course by allowing you to choose implement a your own project rather than have
someone tell you what to do. This open-ended approach to the final experiment has led to many cool
and interesting projects by past students taking this course.
The RAT MCU provides you with a relatively generic engine to drive other system peripherals. The
technical field uses the term peripheral to describe devices that devices such as MCUs commonly
interface with. This somewhat good news about this experiment is that there are several peripheral
devices out there that you can use with your final project. These devices exist in one form or another
and you can find the list on the course website. The listed devices are a growing list; these devices have
been out there for a while but they lacked sufficient documentation or operated in a way that made them
hard to use for students with only a few weeks remaining in the quarter. Most of the peripherals are now
tested and documented to the point that you can use quickly use these devices in your projects.
Final Project Issues: The final project represents a relatively small portion of your final grade in this
course. Embarking upon and completing a final project is not going to make or break your final course
grade. Thus, the main goal of the final project is to allow you to develop and/or improve your
programming skills so that you can do well on both the lecture and lab final exams. In other words, the
final project is a tool for you to use to develop programming and interface skills that will help you in
other areas of this course and beyond. You should keep these notions in mind when selecting a final
project. The main issues is that you dont have to selection a project that saves the world or a project
that is better than every other previously done project in this or a similar course. Its completely OK to
re-implement a project that has already been done and it is OK to complete a relatively simple project.
This is your learning experience; choose wisely.
FRCD
- 66 -
Experiment #12
- 67 -
Experiment #12
changes. The overall package includes a RAT Wrapper program, constraints file, an assembly
language driver program, and supporting documentation.
Assignment:
1) Choose a project and submit a one-page outline of your project to your instructor for approval.
2) Implement your approved project using your RAT MCU.
3) Document your project with both code and a general description.
4) Demonstrate your final project to the course instructor.
Deliverables: This experiment has three main deliverables; Ill determine your grade for this
experiment based on the overall quality of these deliverables.
1. A white-paper describing your final project: This paper is an executive summary of your
project, which means is should as short as possible while still being complete. The project
should be no more than two pages in length. Issue you should include in this paper are a
description of your projects including block diagrams, a description of any pressing issues you
faced, and an operating manual where applicable. Make this paper professional looking a
reading; plan on writing in active voice.
2. The RAT assembly code associated with your experiment and any significant VHDL code you
wrote also. Keep in mind that this code represents your terminal experience for this course so
Ill be grading it for proper form and appearance. This means items such as properly
commented, file banners, subroutine banners, assembler directives, proper indentation, etc. Be
sure to check out the RAT MCU style file before you submit anything. Also, feel free to allow
me to look over your code before you submit it.
3. Demonstrate your final project to the course instructor. For this part, make sure you find me
during the class meeting time of during office hours to allow me to check off your project.
Submitting the other two deliverables is not sufficient to skip an actual demonstration.
FRCD
- 68 -
Appendix
Appendix
FRCD
- 69 -
Make sure there are no spaces in the path name to your project. If there are spaces, any one of a number
of problems may arise that will prevent you from completing your project.
Make sure you do not save project in the folder that contains the Xilinx software. You should always
create a special folder for yourself away from system software areas.
Entity and architecture names must not start with a numeric character (VHDL)
All dealings with Xilinx should be done on the local drive. Completed projects should be saved to your
own personal storage device such as a USB drive. Leaving files on a lab computer is extremely
problematic if you ever hope to see your work again. In addition, working from local drive increases the
speed at which you can traverse the Xilinx Design Methodology.
Working off a USB drive is doable without problems but it is much slower than working from the host
computers hard drive.
1) Select the cleanup project files option. 2) Save your project in a new location. 3) Recompile your
project.
1) Select the cleanup project files option. 2) Save your project in a new location. 3) Exit the Xilinx ISE
software. 4) Re-launch Xilinx ISE. 5) Recompile your project.
1) Select the cleanup project files option. 2) Save your project in a new location. 3) Exit the Xilinx ISE
software. 4) Restart your computer. 5) Re-launch Xilinx ISE. 6) Recompile your project.
1) Select the cleanup project files option. 2) Save your project in a new location. 3) Exit the Xilinx ISE
software. 4) Restart your computer. 5) Re-launch Xilinx ISE. 6) Recompile your project. 7) Plan on
switching your major to business.
FRCD
- 70 -
Possible Causes/Solutions
You must remove the cursor from the final entry box before
saving the Implementation Constraints File. If you dont do
this, ISE will not take the final entry but you can still
download the circuit the development board.
FRCD
- 71 -
Synthesis Problems
Possible Causes/Solutions
You are most likely viewing the wrong file. Verify that you
are viewing the correct file by comparing the file specified by
the error message to the file in the active window.
FRCD
- 72 -
ANN
BE
BV
CAP
G
IND
MC
MH
MP
MQ
MS
MW
NC
NR
RG
REF
SIG
TT
TSH
TSM
WC
FRCD
- 73 -
FRCD
- 74 -
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
entity comp3
Port ( A,B,C : in STD_LOGIC_VECTOR (9 downto 0);
EQ3 : out STD_LOGIC);
end comp3;
architecture my_comp3 of comp3 is
-- all items in declarative region of architecture are indented
-- component declaration
component comp2
Port ( A,B : in STD_LOGIC_VECTOR (9 downto 0);
EQ : out STD_LOGIC);
end component;
-- intermediate signals: note proper prefixing
signal s_eq1, s_eq2 : std_logic;
begin
-- blank lines are used to delineate instantiations
-- and signal assignment statements
-- component instantiations:
-- label and entity name one first line
-- port mappings on subsequent lines
--- port mappings are neat and aligned
eq1: comp2
port map (A => A,
B => B,
EQ => s_eq1);
-- component instantiation
-- another form of alignment used
eq2: comp2
port map ( A => A,
B => C,
EQ => s_eq2);
-- basic logic for final output
EQ3 <= s_eq1 AND s_eq2;
end;
FRCD
- 75 -
programming model
schematic diagram
label
label
label
label
BRN
label
CALL
RET
label
rX,rY
rX,rY
rX,rY
rX,rY
ADD
ADDC
SUB
SUBC
CMP
Logical
AND
OR
EXOR
TEST
CLC
SEC
WSP
AND
OR
EXOR
TEST
rX,kk
rX,kk
rX,kk
rX,kk
rX,kk
ADD
ADDC
SUB
SUBC
CMP
Fun Facts:
Max program size: 1024 instructions (18-bit/instr)
32 8-bit general purpose registers (GPRs)
Stack: implemented in scratch RAM
I/O:
Port Mapped device (8-bit port addresses)
8-bit GPR-based Input and Output
Bit Masking:
bit setting: OR with 1
r3,0x01 ;set bit 0
IN
OUT
not_zero:
out_val:
iterative construct
(known iterative value)
loop:
loop_done:
conditional construct
(unknown iterative value)
rX,rY
rX,rY
rX,rY
rX,rY
rX,rY
Storage
LSL
LSR
ROL
ROR
ASR
ST
ST
LD
LD
rX
rX
rX
rX
rX
loop:
loop_done:
rX,pp
rX,pp
rX,imm
rX,(rY)
rX,imm
rX,(rY)
PUSH
POP
rX
rX
MOV
MOV
rX,rY
rX,imm
Interrupt Architecture:
Interrupt on: interrupt input high voltage & interrupt enabled
One maskable external interrupt (see interrupt group)
Vector interrupt: vector address 0x3FF
Context saving: C & Z flags saved on interrupt
Interrupt automatically disabled on interrupt
Context restoration: C & Z flags restored on RETID or RETIE instructions
Conditional Constructs:
if/else construct
r3,0xFE
;clear bit 0:
IN
CMP
BRNE
MOV
BRN
r0,IN_PORT
r0,0x00
not_zero
r1,0x0A
out_val
MOV
OUT
r1,0x0B
r1,OUT_PORT
;
;
;
;
;
;
;
;
EXOR
r3,0x01
;toggle bit 0
grab data
test to see if byte is 0x00
jump if r0 is not 0x00
place 0x0A in r1
jump to output instruction
place 0x0B in r1
output some data
MOV
r3,0x08
;
;
SUB
r3,0x01
BRNE
loop
;
; do something else
MOV
IN
ADD
BRCC
;
;
;
;
r0,0x00
r1,IN_PORT
r0,r1
loop
clear register
grab some data
add some value to r0
repeat if no carry
; do something else
Equality/Inequality:
Operation:
between registers:
FRCD
Input/Output
RETID
RETIE
SEI
CLI
Arithmetic
rX,kk
rX,kk
rX,kk
rX,kk
OR
rX
Interrupt
- 76 -
SUB
CMP
rA, rB
rA, rB
Comment
0
1
-
0
0
1
rA > rB
rA < rB
rA = rB
SEI
main_loop:
IN
AND
BRN
wank:
bit3:
; enable interrupts
r0, BTN_PORT
r0, BTN2_MASK
bit_wank
FRCD
- 77 -
bit2:
fin_out:
My_sub:
FRCD
LD
OR
r0, B1_MASK
; set bit1
LSR
r1
; shift msb into carry bit
BRCS
bit3
; jump if carry not set
;------------------------------------------------------------CALL
My_sub
; subroutine call
OUT
r0,LED_PORT
; output data to LEDs
BRN
main_loop
; endless loop
;-------------------------------------------------------------
- 78 -
VHDL Cheat-Sheet
Concurrent Statements
Concurrent Signal Assignment
Sequential Statements
Signal Assignment
(dataflow model)
A <= B AND C;
DAT <= (D AND E) OR (F AND G);
A <= B AND C;
DAT <= (D AND E) OR (F AND G);
if (condition) then
{ sequence of statements }
elsif (condition) then
{ sequence of statements }
else --(the else is optional)
{ sequence of statements }
end if;
if
(SEL =
elsif (SEL =
elsif (SEL =
elsif (SEL =
else F_CTRL
end if;
else
else
111) then
110) then
101) then
000) then
<= 0;
F_CTRL
F_CTRL
F_CTRL
F_CTRL
<=
<=
<=
<=
D(7);
D(6);
D(1);
D(0);
case statements
case (expression) is
when choices =>
{sequential statements}
when choices =>
{sequential statements}
when others => -- (optional)
{sequential statements}
end case;
if statements
(dataflow model)
case ABC is
when 100 =>
when 011 =>
when 111 =>
when others =>
end case;
11,
10,
01,
00,
others;
F_OUT
F_OUT
F_OUT
F_OUT
<=
<=
<=
<=
1;
1;
1;
0;
Process
(behavioral model)
opt_label: process(sensitivity_list)
begin
{sequential_statements}
end process opt_label;
proc1: process(A,B,C)
begin
if (A = 1 and B = 0) then
F_OUT <= 1;
elsif (B = 1 and C = 1) then
F_OUT <= 1;
else
F_OUT <= 0;
end if;
end process proc1;
FRCD
- 79 -
CKT Diagram
4:1 Multiplexor
2:4 Decoder
downto 0);
downto 0);
else
else
else
else
entity DECODER is
Port ( SEL : in std_logic_vector(1 downto 0);
F : out std_logic_vector(3 downto 0));
end DECODER;
architecture my_dec
begin
with SEL select
F <= "0001" when
"0010" when
"0100" when
"1000" when
"0000" when
end my_dec;
8-bit register
with load enable
else
else
of DECODER is
"00",
"01",
"10",
"11",
others;
entity REG is
port ( LD,CLK : in std_logic;
D_IN : in std_logic_vector (7 downto 0);
D_OUT : out std_logic_vector (7 downto 0));
end REG;
architecture my_reg of REG is
begin
process (CLK,LD)
begin
if (LD = '1' and rising_edge(CLK)) then
D_OUT <= D_IN;
end if;
end process;
end my_reg;
8-bit up/down
counter with
asynchronous
reset
entity COUNT_8B is
port ( RESET,CLK,LD,UP : in std_logic;
DIN : in std_logic_vector (7 downto 0);
COUNT : out std_logic_vector (7 downto 0));
end COUNT_8B;
architecture my_count of COUNT_8B is
signal t_cnt : std_logic_vector(7
begin
process (CLK, RESET)
begin
if (RESET = '1') then
t_cnt <= (others => 0); -elsif (rising_edge(CLK)) then
if (LD = '1') then
t_cnt
else
if (UP = '1') then t_cnt
else
t_cnt
end if;
end if;
end if;
end process;
COUNT <= t_cnt;
end my_count;
FRCD
- 80 -
downto 0);
clear
<= DIN;
-- load
FRCD
- 81 -
FRCD
- 82 -
VHDL TestBenches
VHDL modeling
To learn the basic of writing VHDL test benches
2.
The Simulator
To learn to simulate your circuits using the simulator
To get a feel for some of the power and features of the simulator
- 83 -
VHDL TestBenches
The stimulus driver is really nothing special in terms of a VHDL model. The main difference here is
that instead of dealing with signals which interface with the outside world (such a switches and LEDs),
were now dealing with signals that are driving the unit we intend to test. Note that in Figure 26 there
are no signals touching the dotted line; therefore, you can probably guess right away that the entity
declaration of the test bench is going to be fairly simple. And one last note before we go on this is
just a brief introduction to the concept of writing test benches.
A Simple Test Bench
Lets write a simple test bench and fill in the blanks as we go along. First thing to note is that the test
bench is necessarily going to be structural model as the diagram in Figure 26 implies. One approach
would be to make it purely structural and which would require the instantiation of both the stimulus
driver as well as the device under test. A better approach, especially considering that our test benches
wont be overly complex, is to instantiate only the device under test and to model the stimulus using
concurrent statements in the body of the test bench architecture. This is what is shown in Figure 27.
FRCD
- 84 -
VHDL TestBenches
entity my_nand2 is
port(
a,b : in std_logic;
f : out std_logic);
end my_nand2;
architecture my_nand2 of my_nand2 is
begin
f <= a NAND b;
end my_nand2;
entity testnand is
end testnand;
architecture stimulus of testnand is
component my_nand2
port(
a,b : in std_logic;
f : out std_logic);
end component;
signal A,B,Y : std_logic;
begin
-- instantiate the NAND gate
n1: my_nand2
port map (a,b,y);
process
constant PERIOD: time := 40 ns;
begin
A <= '1'; B <= '1';
wait for PERIOD;
-- lets be generic
Here are some interesting things to note about the test bench provided in Figure 27:
The first portion of the test bench is a 2-input NAND gate. This simple gate is considered the
device under test for this example. There is nothing else worth noting in this model.
The entity declaration for the test bench is missing a port clause. This is because the test bench
module essentially has no contact with the outside world. In other words, the port clause is
used to describe the models interface; the test bench model in this example has no interface
with the outside world.
The NAND gate is declared and instantiated as you would with any circuit. The only thing new
here is that there is nothing new here: massive similarities with other models youve created.
FRCD
- 85 -
VHDL TestBenches
Some intermediate signals have been declared. These act as the inputs to the device under test.
Note there is no output from the device under test in this particular model.
The architecture body has one process. This one process provides the required stimulus to the
device under test. The process contains no sensitivity list which requires that it rely on wait
statements instead. The process uses the wait for form of wait statements which happens to be
the one type we did not discuss in the previous section of these notes. Be sure to note that the
coding of the signals in the process statement under control of the wait statements has a hardcoded feel. Although this approach somewhat lacks genericity, its adequate for what we need
to do.
Also worthy of note is the use of a VHDL constant. This helps make the test bench more
generic and brings general happiness to the VHDL Gods.
the process suspends (but only remains suspended for the stated period)
when the process resumes, the value of the A and B signals are reassigned before another
wait statement is encountered; this happens a few times.
The final wait statement has no parameters. This means that the process is essentially dead
because there is nothing to make it resume. The simulation has therefore ended.
Figure 28 shows a cleaner example of a test bench. The main difference between this test bench and the
previous one is that the both the processes have a way to officially terminate, never to be resumed
again. Keep in mind that you are free to stop the simulation anytime you want but it just seems more
complete to have all the processes end before the simulation stops. The dual termination mechanism
relies on the ability for the two processes to communicate with one another. So once the process that is
generating the A and B test signals is done, it asserts the done signal which in turns terminates the
process that is generating the clock.
FRCD
- 86 -
VHDL TestBenches
Figure 28: A test bench for a 2-input NAND gate with two processes that terminate.
FRCD
- 87 -