Você está na página 1de 38

Lab Manual

for
Microprocessors Lab (EEE3231)



Peter Csaszar
Department of Electrical and Computer Engineering
Lawrence Technological University

All Rights Reserved













Version 1.0.0
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 2
Table of Contents


Preface................................................................................................................................. 3
Lab Report Content Requirements...................................................................................... 4
Experiment 1: Introduction to the Assembly Program Development Procedure.............. 6
Experiment 2: Introduction to Advanced Debug Features (Bubble Sort)......................... 8
Experiment 3: Understanding the Addressing Modes .................................................... 11
Experiment 4: Developing a Simple 68000 Assembly Code (Block Copy)................... 14
Experiment 5: 68000 Integer Arithmetic ........................................................................ 16
Experiment 6: 68000 Integer Arithmetic with Error Detection ...................................... 19
Experiment 7: String Manipulation & Hierarchical Design ........................................... 22
Experiment 8: Matrix Arithmetic.................................................................................... 25
Experiment 9: Matrix Multiplication .............................................................................. 27
Experiment 10: Embedded System Firmware Design .................................................... 29
Experiment 11: Implementation of a Recursive Algorithm (Fibonacci) ........................ 33
Experiment 12: Assembly Implementation of a C Program (Insertion Sort).................. 36
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 3
Preface

About This Lab
This is the lab manual for Microprocessors Lab (EEE3231). Please consult the lab syllabus for the specific
lab requirements, policies and guidelines.

Acknowledgements
The author would like to express his appreciation to the following individuals:
! Professor Charles Kelly (Monroe County Community College; Monroe, Michigan) for the
development and ongoing maintenance of the EASy68K suite, a truly remarkable software toolkit
for the 68000 microprocessor. Professor Kelly happily received all bug reports and (occasionally
frivolous) suggestions from the author, and integrated virtually all feedback into EASy68K with
lightning speed. Without Professor Kellys efforts, this lab manual would not have been possible.
! Dr. Michael Cloud (Lawrence Technological University, Southfield, Michigan) for his devoted
efforts to proofread each experiment write-up, which not only polished this lab manual, but also
the authors own English language skills.
! Dr. Hassan Hassan and Dr. Birham Mirshab (Lawrence Technological University, Southfield,
Michigan) for the select experiments in the previous lab manual that served as inspiration to some
of this lab manuals experiments.

References
For successfully solving the experiments of this lab manual, the following documents may prove to be
helpful (listed from the more general to the more specific):

1. Motorola, Inc.: M68000 8-/16-/32-bit Microprocessors Users Manual. (Reprinted by multiple
publishers, e.g. Prentice Hall, 1989; Barnes & Noble, 1991.)
2. James L. Antonakos: The 68000 Microprocessor. Fifth Edition. Pearson Prentice Hall, 2004.
3. Peter Csaszar: EASy68K Beginners Guide. (Microprocessors Lab supplementary material.) Lawrence
Technological University, 2006.
4. Peter Csaszar: 68000 Quick Start Guide. (Microprocessors Lab supplementary material.) Lawrence
Technological University, 2006.
5. Charles Kelly: EASy68K Assembly Language Tool Online Help. (Edit68K Help > Help menu item
or Sim68K Help > Sim68K Help menu item.)


EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 4
Lab Report Content Requirements

The Purpose of Lab Reports
Lab report requirements have traditionally been a subject of obscurity, confusion and student/grader
debates, causing a recurrent headache for all participants from students to instructors. The formatting
requirements (typesetting guidelines, format of the cover page, stapling vs. clipping, etc.) are typically
covered in the lab instructors syllabi, and are easy to assess as well as enforce. However, the semantics
tend to remain a terra incognita. This document aims to fill in this gaping hole.
The overall goal is to make a colleague, who is familiar to the field, but not to the experiment itself, be
able to reproduce your experiment, and compare results and conclusions.

The Individual Sections of the Lab Report
The required sections of an admissible Lab Report are listed below.

1. Introduction
This section should contain a couple of sentences about the overall purpose of the lab experiment. This is
similar to the Objective section of the lab manuals experiments; however, your introduction should only
focus on technical aspects, omitting the educational benefits highlighted in the lab manual.

2. Required Resources
Here you have to list the resources you were using to complete the experiment. In this lab, it will typically
mean the EASy68K Assembly Language Toolkit. However, if for certain calculations you used an Excel
spreadsheet, for example, you will need to list this software tool as well. (This situation will occur in some
of the upcoming experiments.) If an experiment involves hardware prototyping, you will need to provide a
Parts List in this section as well. (It will not be typical to this labs experiments, but remember it as a
general guideline.) However, please write the truth, and only the truth. For example, don't list MS Excel for
an experiment, where you did not use MS Excel at all! Imagine the utter confusion of the person reading
your lab report, trying to figure out just what you could possibly use Excel for, when all your program does
is validating passwords

3. Description of the Experiment
This is where, well, you describe the experiment. Listed are the possible sections that apply in most cases.
! Theory you used for designing your algorithm and writing your program, if any. (For example, the
formula for matrix multiplication.)
! Program design, algorithm- and/or flowcharts. (Only include a flowchart if it is meaningful, and
helps to understand the gist of your algorithm. Overly terse or ridiculously detailed flowcharts are
not helpful whatsoever.) You can use MS Word or dedicated packages to draw the flowcharts.
! Calculations (if applies).
! Calculation results and/or answers to the question in the lab manual (whichever applies).
! Anything else you deem appropriate, for example some special hurdles in the software
development, or observations you made and find it helpful for other people to be aware of. (An
excellent example is bug reports or feature suggestions for the EASy68K software.)

4. Conclusions
In this section you would include:
! The discussion of your results.
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 5
! The discussion of any differences with the theory (if any), followed by your understanding of the
reasons behind those differences.
! The summary of particular circumstances surrounding the completion of the experiment.

5. Attachments
At the end of your report, you will need to attach the hardcopy of the following files:
! Source file (*.X68): This file provides the most insight for a person trying to understand your
work. Therefore, please make sure to sufficiently comment your code! You can print the source
file directly from the EASy68K Editor/Assembler (Edit68K).
! Log file (*.txt): This is the file generated by the EASy68K Simulator (Sim68K), containing the
register/memory dump of a single-step execution (Execution Log) or all text output sent to the
console screen (Output Log), depending on the requirements of the experiment. The EASy68K
automatically generates the default filenames from the filename of the currently simulated
program; however, you have the right to use a filename of your own choice. In either case, you are
strongly recommended to keep the .txt extension; this will make it easier to open the file in
Notepad, from where you can print it out. (Another option is to pull the file into the EASy68K
editor, and print it out from there. In this case, make sure to select Any File from the pull-down
list of File of type: in the Open File dialog box.)
! List file (*.L68): This file is generated by the EASy68K Editor/Assembler, and is used by the
Simulator for source-level debugging. You need to include this file in your lab report as a proof of
validity for your source code; also, it may help another person to diagnose the cause of bugs in
your software. Double-clicking this file will open it in the EASy68Ks editor, from where you can
print it out. (The author of this handout has suggested the EASy68K developers to implement the
possibility of printing the list file from the Simulator.)
The write-up of the individual lab experiments will mention if any other attachments are needed.
Diligently observing the above guidelines will enable you to prepare top-quality lab reports with ease and
confidence. Furthermore, you can always consult your lab instructor if you need specific suggestions.
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 6
Experiment 1
Introduction to the Assembly Program Development Procedure

Objectives
In this experiment, students will get an introduction to the 68000 assembly language program development
process. Through a simple example provided below, students will learn how to use edit, assemble and
simulate programs using the EASy68K suite.

Required Resources
EASy68K 68000 Assembly Language Programming Tool

Problem
Consider the following 68000 assembly language program:

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* Pr ogr amNumber : EEE3231 Exper i ment 1
* Descr i pt i on : I nt r oduct i on t o t he Assembl y Pr ogr amDevel opment Pr ocedur e
* Wr i t t en by : <Your name her e>
* Dat e : <Today' s dat e her e>
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


* Const ant Def i ni t i ons

ORWELL equ 1984 ; Numer i c const ant ( No pr ef i x: Deci mal )


* Dat a Def i ni t i ons

or g $1000 ; St ar t i ng addr ess
dcb. b 16, 0 ; I ni t i al memor y cl ean- up
or g $1000 ; Reset Locat i on Count er t o st ar t i ng addr ess

bMyByt e dc. b %1001 ; Byt e def i ni t i on ( ' %' : Bi nar y)
wMyWor d dc. w ORWELL ; Wor d def i ni t i on ( Uses const ant )
l MyLong dc. l $5043F840 ; Long def i ni t i on ( ' $' : Hexadeci mal )
l MyResul t ds. l 1 ; Def i ni t i on of one uni ni t i al i zed l ong


* Pr ogr amCode

St ar t move. l #@370, d0 ; I ni t i al i ze D0 ( ' @' : Oct al )
add. b bMyByt e, d0 ; Add byt es ( upper 3 byt es unchanged)
cl r . l d1 ; Cl ear ent i r e D1 r egi st er
move. w wMyWor d, d1 ; Load wMyWor d t o D1
add. l l MyLong, d1 ; Add l ongs ( al l 4 byt es i nvol ved)
subq. w #1, d1 ; Decr ement l ower 2 byt es of D1
l ea l MyResul t , a0 ; Poi nt er t o l MyResul t l ong var i abl e
moov. l d1, ( a0) ; St or e r esul t i n l MyResul t
st op #$2700 ; Ter mi nat e pr ogr am( si mpl er ver si on)


end St ar t ; St ar t execut i on at l abel " St ar t "

Since this is the first lab in the semester, you may not understand the meaning of the different statements.
Everything will be explained in detail as the Microprocessors course progresses; in this experiment, you
will get introduced to the use of the assembly language programming tool.

EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 7
Warning! Watch out for the difference between the lower-case l (as in Lima) and the digit 1 (one).
Observe their appearance in the Courier New font side-by-side:
letter l " l 1 # number 1

Procedure
Complete the following tasks.
1. Launch the EASy68K Editor/Assembler (Edit68K), and enter the program provided in the
Problem section. (Use the Tab key to separate the fields.)
2. Try to assemble the program. It contains a bug (more exactly a typo), which is so trivial that even
with no prior experience you should be able to correct it. Fix and re-assemble the program until no
errors or warnings are left.
3. Hit the Execute button in the dialog box that pops up after the successful assembly. This will
invoke Sim68K, the EASy68K suites simulator/debugger utility. (Note: Even though simulation
is enabled if the program only contains warnings, it is highly recommended that you get rid of all
warnings as well.)
4. As soon as the Simulator is loaded, turn on execution logging by opening the Log Output dialog
box (Options > Log Output menu item) and selecting Instructions, Registers and
Memory in the Execution Log Type group; the range of logged memory shall be 10 bytes
from 1000. (Remember, these values are in hexadecimal!) Leave the output log disabled in the
Output Log Type group.
5. Execute the program instruction-by-instruction with the Trace Into command (hotkey: F7).
Warning! Single-step execution is necessary in order for the log to be generated!
6. Disable execution logging. (This will prevent the log of subsequent executions from being
appended to this logfile.)
7. Exit all programs. (Make sure the assembly code you typed into Edit68K is saved!)

Requirements for This Lab
! Prelab
Download the latest version of the EASy68K assembly language tool from the Web. Install the
package and configure the utilities of the suite.
! Lab Report
Write your report according to the usual guidelines. The Description section must include a brief
explanation of your experimentation with the EASy68K, including any special circumstances.
Attach a hardcopy of the source code, the generated execution log and the list file to your report.

Next Lab Alert
The next experiment will continue focusing on the features of the EASy68K development suite; make sure
you fully understand the material covered in this lab.
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 8
Experiment 2
Introduction to Advanced Debug Features (Bubble Sort)

Objectives
In this experiment, students will continue to familiarize themselves with the EASy68K suite, with special
emphasis on the Simulators graphic debug facilities. This time the program under scrutiny is the 68000
assembly porting of Bubble Sort, an inefficient but elegant and easy-to-implement sorting algorithm.
Through this example, the use of strategically positioned breakpoints will be demonstrated.

Required Resources
EASy68K 68000 Assembly Language Programming Tool

Problem
Consider the following 68000 assembly language program:

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* Pr ogr amNumber : EEE3231 Exper i ment 2
* Descr i pt i on : I nt r oduct i on t o Advanced Debug Feat ur es ( Bubbl e Sor t )
* Wr i t t en by : <Your name her e>
* Dat e : <Today' s dat e her e>
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


* Const ant Def i ni t i ons

NUMVALS equ 16 ; Number of val ues t o be sor t ed
I NI TCNT equ NUMVALS- 2 ; I ni t i al val ue of count down


* Dat a Def i ni t i ons

or g $1000 ; St ar t i ng addr ess

vubSor t dc. b 254, 52, 15, 202, 9, 171, 37, 186, 63, 190, 86, 141, 186, 8, 141, 1
; Unsi gned byt e vect or t o be sor t ed

* Pr ogr amCode

BubSor t move. w #I NI TCNT, d0 ; Sweep Loop count down
SweepLp l ea vubSor t , a0 ; Runni ng poi nt er : begi nni ng of vect or
move. w d0, d1 ; Swap Loop count down
SwapLp move. b ( a0) +, d2 ; Fet ch el ement & move poi nt er
cmp. b ( a0) , d2 ; Compar e el ement s
bl s NoSwap ; Pr ecedi ng <= cur r ent : no swap!
move. b ( a0) , - 1( a0) ; Bump cur r ent el ement 1 posi t i on down
move. b d2, ( a0) ; Pr ecedi ng el t . t o cur r ent posi t i on
NoSwap dbf d1, SwapLp ; Next Swap Loop i t er at i on
dbf d0, SweepLp ; Next Sweep Loop i t er at i on
st op #$2700 ; Ter mi nat e pr ogr am( si mpl er ver si on)


end BubSor t ; St ar t execut i on at l abel " BubSor t "

The above Bubble Sort algorithm sorts the elements in the unsigned byte vector vubSort in increasing
order. The number of elements in the vector must be specified by the NUMVALS constant.
Some of the instructions may still be unfamiliar to you. However, even to the novice observer, the program
well demonstrates the inner workings of a sorting algorithm and the implementation of nested loops.
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 9

Theoretical Comments
The name of the algorithm, Bubble Sort, comes from the resemblance between the sorting action and the
movement of gas bubbles rising to the top of a glass of soda.
The algorithm repeatedly sweeps through the entire array. During the first sweep, the first and second
elements are compared, and if the former is greater than the latter, the two elements are swapped; this
conditional swap (swap for short) is followed by the swap of the second and third elements, and so on, until
the next to last and the last elements are processed. As a result, at the end of the sweep the largest element
in the array will land at the arrays last position.
Subsequent sweeps make the larger elements bubble up towards the right side of the array, until their
appropriate positions are reached. If the number of elements is n, the first sweep executes n1 swaps, the
second n2 swaps, and so on; the last sweep only consists of a single swap, taking care of the first and
second elements. Therefore, the total number of swaps during the sort is
$
%
&
' %
&
1
1
2
) 1 (
n
i
n n
i
For an array of 16 elements, this means 120 swaps altogether. What really matters in computer science, is
the asymptotic behavior of the above expression, characterizing the algorithms execution speed for
indefinitely many elements. This is also referred to as the complexity of the algorithm, and is expressed
using the O-notation. The Bubble Sort algorithms complexity is O(n), thank to the presence of the n term
in the above polynomial expression. The best sorting algorithms only have a complexity of O(nlog n).

Implementation Comments
Sorting algorithms work for any object that defines a relational semantics, i.e., the elements can be
compared to each other in terms of being greater-than, less-than or equal. (For example, real numbers can
be compared, but complex numbers cannot!) In 68000 assembly it is straightforward to work with bytes,
words or longwords, either signed or unsigned. This experiment uses unsigned bytes, so that the memory
dump that uses hexadecimal values will be easier to interpret. The data type (byte in this case) is coded into
the data transfer/comparison instructions, and the DC assembler directive defining the vubSort array. What
makes this implementation sort unsigned values in increasing order is the choice of BLS as conditional
branching instruction in line bl s NoSwap.

Procedure
Complete the following tasks.
1. Enter the program provided in the Problem section. Assemble it, and hit the Execute button in
the assembly completion dialog box to invoke the Simulator.
2. Turn on execution logging by selecting Instructions, Registers and Memory in the Execution
Log Type group; the range of logged memory shall be 10 bytes from address 1000 (all values
are in hexadecimal). Leave the output log disabled in the Output Log Type group.
3. Observing the array in the memory after each step, or even each individual swap would result in a
gargantuan logfile. Therefore, place a breakpoint to a strategically selected location to capture the
memory status only after each sweep. (Help: Put the breakpoint in line dbf d0, SweepLp.)
Warning! Once execution stops, hit the Trace Into toolbar button (F7 hotkey) once, in order for
a register/memory dump to be placed in the logfile. Use the Run toolbar button (F9 hotkey) to
skip between breakpoint stops.
4. Disable execution logging. (This will prevent the log of subsequent executions from being
appended to this log. In the future you will have to remember to close the log after completion.)
Note: If you want to restart the program in the Simulator, use the Reload Program toolbar button (Ctrl-F3
hotkey), as opposed to the Reset Program toolbar button (Ctrl-F2 hotkey). Both commands reset the
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 10
simulated 68000 registers, but only Reload Program re-initializes the memory areas defined by the DC and
DCB assembler directives. (Reset Program would only make your program re-sort an already sorted array!)
Requirements for This Lab
! Prelab
Review the EASy68K Simulators debug features, including the placement of breakpoints.
! Lab Report
Write your report according to the usual guidelines. The Description section must include a brief
explanation of your experimentation with the EASy68K, including any special circumstances.
Attach a hardcopy of the source code, the generated execution log and the list file to your report.

Next Lab Alert
The next experiment will require a considerable amount of review, and the clear understanding of the
required procedure. Begin your preparation on time, and come to the lab fully prepared.
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 11
Experiment 3
Understanding the Addressing Modes

Objectives
In this experiment, students will receive hands-on experience studying the behavior of select 68000
instructions using different addressing modes, with details beyond typical classroom coverage. Supported
addressing modes and addressing mode combinations are a key factor in determining a processors power
in terms of code efficiency; therefore the full understanding of addressing modes is absolutely crucial.

Required Resources
EASy68K 68000 Assembly Language Programming Tool

Problem
Consider the following 68000 assembly language program:
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* Pr ogr amNumber : EEE3231 Exper i ment 3
* Descr i pt i on : Under st andi ng t he Addr essi ng Modes
* Wr i t t en by : <Your name her e>
* Dat e : <Today' s dat e her e>
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


* Dat a Def i ni t i ons

or g $1000

dc. b 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15


* Pr ogr amCode

St ar t moveq #- 2, d0
movea. l #$1000, a0
move. l #- 65533, d1
adda. w d1, a0
move. b ( a0) +, d2
add. b d2, d0
move. l d0, 5( a0, d1. w)
move. w d0, d2
sub. l d2, d0
neg. w $1006
move. l d2, - ( a0)
st op #$2700


end St ar t

The table below will be used for the detailed analysis of the above code. While the procedure may seem
tedious at first, this is really the only way to properly demonstrate the effect of the individual instructions.
The columns shall contain the following information for each individual instruction:
! Instruction: The instruction with its operands (but without the label).
! Operand Source & Dest.: The indication of the source and destination operands of the given
instruction (but not the contents of the operands), resulting from the data type of the instruction
and the applied source / destination addressing modes. The entry shall also show the data type of
the operands. The possible different cases are the following:
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 12
o Register (from a register direct addressing mode), e.g., A0.L or D2.B. This is rather
trivial, and can be done by the inspection of the instruction.
o Memory location (from a memory addressing mode), e.g., [$100C].L or [$1006].W.
(Notice the square brackets surrounding the address!) Be careful; when an operands
addressing mode is a variant of Address Register Indirect (ARI), you are recommended to
rely on the EASy68K Simulator to determine the effective address from the current value
of the register(s) involved with the addressing mode.
o Constant (from an immediate addressing mode), e.g., 2.B or 65533.L. Like in the
case of registers, this can be accomplished through mere inspection. (Notice however
that in this notation the # is not used to denote an immediate operand!)
o Not applicable; in this case put a in the table entry.
Note: This formalism is in line with how textbooks explain the 68000 addressing modes.
Remember once again that a numeric value, without the # operator, refers to a constant; in
order to refer to a memory position, the value must be put between square brackets!
Caveat! In some cases, an operands data type is different from what would be expected from the
instructions data type designator. (One example is the source operand of MOVEQ, and another
one is related to a certain addressing mode being a destination. The example code contains
instances of both.) The filled-in values show the actual source operands as a helper; however, pay
special attention when determining how the destination operands will be affected!
! Value Source, Dest. Before & Dest. After: The contents of the source operand, the destination
operand before instruction execution, and the destination operand after instruction execution
respectively, indicated as a 4-byte hexadecimal value (without the $ designator, but separating
the bytes with spaces to make it easier to read the values), much like the format of a debuggers
register- or memory dump. (Note: With 4 bytes we are prepared for the worst, i.e., that the
operands are longwords.) Use the EASy68K Simulator to determine the contents of the three
columns. With bold face, highlight the section of the 4 bytes that actually participates in the given
operation. Due to the nature of how the 68000 implements the addressing modes,
o a register operands participating bytes are aligned to the right.
o a memory-stored operands participating bytes are aligned to the left.
For a constant operand, the question does not apply; only show as many bytes as contained in the
data type, in which the constant is being used [typically the operations data type, but not always].
Examples: FF FF FF 01: Byte in register; F9 F9 08 09: Word in memory; FF FF 00 03:
Longword [wherever]; FE: Byte constant; 00 00 10 00: Longword constant.
Operand Value
Instruction
Source Dest. Source Dest. Before Dest. After
moveq #- 2, d0
2.B D0.L FE 00 00 00 00 FF FF FF FE
movea. l #$1000, a0
$1000.L A0.L 00 00 10 00 00 00 00 00 00 00 10 00
move. l #- 65533, d1
FF FF 00 03
adda. w d1, a0
D1.W 00 00 10 00
move. b ( a0) +, d2
03 04 05 06 00 00 00 03
add. b d2, d0
FF FF FF 01
move. l d0, 5( a0, d1. w)
[$100C].L
move. w d0, d2
00 00 00 03
sub. l d2, d0

neg. w $1006
[$1006].W F9 F9 08 09
move. l d2, - ( a0)

EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 13
Notes:
1. Remember, after each Reset or Reload, all data- and address registers are reset to 0.
2. Pay special attention to the ARI with predecrement / postincrement addressing modes!

Procedure
Complete the following tasks.
1. Enter the program provided in the Problem section. Assemble it, and hit the Execute button in
the assembly completion dialog box to invoke the Simulator.
2. Set up the Simulators Execution Logging facility to log the instructions, registers and the 16-byte
memory area beginning at address $1000.
3. Execute the program step-by-step, and fill in the entire Table 1. (Forgot to take note of the
contents of the destination before the instruction executed? It is an excellent opportunity to call the
Execution Log for help!) Before executing each instruction, try to calculate the value in the last
column, and then compare it with the Simulators results. If you observe discrepancies, it is a clear
indication that your understanding of the involved addressing modes is not yet perfect.
Note: Use the Reload Program toolbar button (Ctrl-F3 hotkey) as opposed to the Reset Program for
repeated executions. This will not only reset all data- and address registers to 0, but will also restore the
memory area defined by the DC assembler directive.

Requirements for This Lab
! Prelab
Review the 68000 addressing modes and data types. Study Table 1 very carefully, and through the
examples of the pre-filled fields, try to understand the logic and purpose of the table. Prepare
yourself to ask questions during the lab session, so that you will be able to complete the
experiment successfully.
! Lab Report
Complete the tasks laid out in the Procedure section, and write your report according to the usual
guidelines. The Description section must contain the reproduced version of Table 1 with all fields
filled in, and provide a brief explanation about what the table is trying to demonstrate. Attach a
hardcopy of the source code, the generated execution log and the list file to your report.

Next Lab Alert
The next experiment will require the understanding of certain microprocessor instructions; come to the lab
well-prepared.
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 14
Experiment 4
Developing a Simple 68000 Assembly Code (Block Copy)

Objectives
In this experiment, the student will complete the full development cycle of a simple program, then make
slight modifications to it. The problem specification is given as a verbal description; the key deliverable is a
fully functional 68000 assembly code, which will be demonstrated in the simulation environment.

Required Resources
EASy68K 68000 Assembly Language Programming Tool

Problem
Write a 68000 assembly language program to copy the first 64 characters (and not a character more!) of
the quotation below (essentially, the basic mantra of this entire lab) from memory address $1000 to $1080.
Ever yt hi ng shoul d be made as si mpl e as possi bl e, but not si mpl er . ( Al ber t Ei nst ei n)
The code must begin at address $1100, and has to be prepared in four variants:
1. Copy the characters byte-by-byte; use the Bcc instruction to implement the loop.
2. Copy the characters word-by-word; still use the Bcc instruction to implement the loop.
3. Copy the characters longword-by-longword; still use the Bcc instruction to implement the loop.
4. Copy the characters longword-by-longword; use the DBcc instruction to implement the loop.
Hints: Utilize the DC.B <value list> assembler directive to provide the Einstein quotation as the source
character block at address $1000; furthermore, use the DCB.B <length>,<value> directive to blank the
destination block by placing 64 zeros at address $1080, so that when you reload the program, the
destination block will be clear again. Precede the block definitions and your assembly program code by
ORG directives, in order to set the Location Counter to the appropriate positions.

Theoretical Comments
Recall the difference between the Bcc and DBcc instructions. The former is a simple conditional branch;
the latter, however, is a buy-one-get-one-free scheme: a reverse conditional branch [i.e., its falseness is a
necessary condition for the jump to <label>], which also maintains a loop counter by decrementing the
chosen data register Dn.W, and comparing its value against 1.
Bcc DBcc











Previous
Cond. true?
Next
<label>
Y
N
Previous
Next
<label>
Y
N
Dn.W = Dn.W1
Dn.W = 1?
N
Y
Cond. true?
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 15
When using the DBcc instruction in this problem, it is important to figure out how to disable its primary
branching condition (so that it only pays attention to the counter being consumed), and to determine the
initial value of the loop counter (so that exactly the desired number of loop iterations will take place).

Implementation Comments
One of the pivotal points of this exercise is the appropriate choice of addressing modes, which will make
the memory transfer operation as simple as possible. (Hint: Remember, the MOVE instruction is the
Mother of All Orthogonality.)

Procedure
Write the code for all four variants of the program, and complete the following list of tasks:
1. Fill in the table below, and discuss your findings briefly, with special emphasis on clock cycles.

Variant 1 Variant 2 Variant 3 Variant 4
Number of Instructions
Code Size [Bytes]
Number of Clock Cycles

Hint: The EASy68K Simulator shows the number of clock cycles executed. The length of the
code you can calculate with the help of the list file.
2. For one of the four variants, single-step through an instruction of the code before and after the
block copy takes place, and log the section of the memory containing the two character blocks.
The log is supposed to clearly show the effects of the block copy on the memory.
Warning! Make sure that your execution log only shows the before and after memory
scenarios, and that the memory blocks are clearly shown. Points will be deducted for very long
and/or non-demonstrative logs!
Note: Use the Reload Program toolbar button (Ctrl-F3 hotkey) as opposed to the Reset Program for
repeated executions, in order to restore the memory areas defined by the DCB assembler directives.

Requirements for This Lab
! Prelab
Refresh your understanding about the conditional branching instructions.
! Lab Demo
You must demonstrate your assembly programs to the lab instructor, who will sign off on the
experiment. The ground rules regarding the demonstration are explained in the lab syllabus.
! Lab Report
Write your report according to the usual guidelines. The Description section must include the
results of all required tasks described in the Procedure section of the experiment. To your report,
attach a hardcopy of the source code of all three variants, the generated execution log running
one of the variants, and the list file of one of the variants.

Next Lab Alert
The next experiment will require a considerable amount of Prelab work that needs to be demonstrated to
your lab instructor; begin your preparation on time, and come to the lab fully prepared.
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 16
Experiment 5
68000 Integer Arithmetic

Objectives
This experiment focuses on the proper use of the 68000s integer arithmetic instructions. This is also an
ample opportunity to become familiar with the text input/output function calls provided by the 68000
simulator.

Required Resources
EASy68K 68000 Assembly Language Programming Tool

Problem
Write a 68000 assembly language program that implements the following signed integer formulas.
(Warning! Even though addition and multiplication are commutative operations, your implementation
must follow the exact order of operations in the formulas!)
x g h
y
z
x
g
z y
z x
f
' % ' &
' (
&
' ' %
'
&
) 4 3 (
200
10
100
3

The program prompts the user for the input variables with the message Please enter x:, etc., and begins
the calculations. As soon as a formulas calculation is finished, its result is printed on the screen, e.g.
Result: f=<value> for variable f, followed by the same procedure for g and h. After completion, the
program prompts the user to press the Esc key to quit, for which the program says good-bye and terminates;
otherwise the calculations will be run on a new suite of input values provided by the user. For full credit,
the program must communicate with the user as described above.

Theoretical Comments
Despite the apparent simplicity of the above formulas, the 68000 assembly implementation is nontrivial and
requires an understanding of the 68000s data types and arithmetic instructions. The participants and their
data type involvement are listed below:
! Simulator text I/O function calls: Both the input and the output values are longwords.
! Multiplication: The multiplicand & multiplier are words, the product is a longword.
! Division: The dividend is a longword, the divisor and quotient are words. (Warning! The upper
word of the quotients register is tainted with the value of the 16-bit remainder!)
! Addition & subtraction: All data types are supported. For the largest range of possible input
values, this experiment requires that all additions and subtractions (including in the expression for
variable h) work with longword data!
For further analysis, the formulas must be modified a bit; the procedure will be demonstrated using the
expression for variable A. First, the formula must be fully parenthesized, i.e., each operator and its
operands must be put between a matching pair of parentheses.
f = { [ ( x * z ) / 3 ] [ ( 100 * y ) * z ] }
In the next step, all terms [single variables and parenthesized expressions alike] are extensively decorated
with data type designators. These are single uppercase characters, W & L representing word &
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 17
longword respectively; ? stands for uncommitted. The designator suffix indicates a terms actual data
type, in compliance with the notation used in Experiment 3 to describe an instruction operands data type.
This time, however, we also introduce the designator prefix that indicates the desired data type of the term.
In this advanced notation, the original formula takes the following form:
f = L.{ L.[ L.( W.x.L * W.z.L ).L / W.3.? ].W L.[ W.( W.100.? * W.y.L ).L * W.z.L ].L }.L
Look totally confusing, even crazy? It shouldnt! From the previous discussion, the following can be said:
! The actual data type of a variable is longword, due to the Simulators integer input function call.
! The desired final data type of an entire expression is longword, imposed by the Simulators
integer output function call.
! The desired data type of a multiplications two operands is word, and the actual data type of the
product is longword.
! The desired data type of a divisions dividend and divisor are longword and word respectively,
and the actual data type of the quotient [and also the remainder] is word.
! The actual data type of a constant is uncommitted, i.e., it is free to assume the desired data type
imposed by its context. (However, if its value is out of range, the assembler will give an error.)
Take variable y as an example: it is provided as a longword by the Simulators integer input function call,
but, being the multiplier in a multiplication, it is expected to be a word. The result of multiplication (100*y)
is a longword, but appearing as the multiplicand in a subsequent multiplication, its value is also expected to
be a word. (Remember, the final expressions desired data type is longword, imposed by the EASy68K
Simulators integer output function call.)
From all of the above it is now clear that if an expressions prefix and suffix data type designators are
different, we have a problem. What is required is an operation called data type conversion, which is also
referred to as casting in elegant C programming circles. Rewriting the above formula with the use of the
<desired data type>() casting operators known from the C language (but with a neater syntax), we get
f = { long[ ( word(x) * word(z) ) / 3 ] [ word( 100 * word(y) ) * word(z) ] }
Now we only see instances of casting, where a data type conversion is indeed required. The only challenge
left is to figure out how to implement the word() down-casting, and the long() up-casting operations in
68000 assembly. (Notice that the casting operators only need to add parentheses around single variables; if
they precede a parenthesized sub-expression, the operators own parentheses can be omitted.)

Implementation Comments
The completion of this experiment requires the use of the simulator softwares text I/O function calls. In the
EASy68K Simulator, all function calls are activated through a TRAP #15 instruction in the running
assembly program. The desired operations so-called task code must be placed into register D0.L before the
function call. The operations needed in this experiment are:
! Task #3: Display the contents of D1.L as a signed decimal number.
! Task #4: Read a signed decimal number from the keyboard into D1.L.
! Task #5: Read a single character from the keyboard into D1.B.
! Task #13/#14: Display the 0-terminated string at (A1) [max 255 characters] with/without Newline.
! Task #17/#18: Combination of Tasks #14 and #3/#4. (Great for prompting and displaying results.)
The detailed use of the function calls is shown in EASy68Ks online Help, under Simulator I/O > Text.
Note: Some of these calls are compatible with services provided by other 68000 simulators, but some are
not; if you are working with a different development tool, consult its help documentation.
Suggestion: It is a good idea to reserve all registers involved with the function calls, and refrain from using
them for any other purpose within the program (except for short-term roles, or for results ready to be used
and then discarded). In this way, inadvertent destruction of cherished register contents can be avoided.
Trick: Feel free to use any address registers (other than A7, the Stack Pointer) to store 16/32-bit data
temporarily. (Now the reason behind 32-bit, rather than 24-bit address registers suddenly becomes clear)
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 18
Procedure
Write the program based on the above help, and then complete the following tasks for your lab report:
1. Write down all three expressions fully parenthesized.
2. Write down all three expressions decorated with the prefix and suffix data type designators.
3. Write down all three expressions supplied with the inspired-by-C casting operators.
4. Explain how the two casting operators can be implemented in 68000 assembly.
5. Create and fill in the table below. While doing so, capture the output log of the EASy68K
Simulator as you are executing all four sets of calculations shown in the table. The output log will
contain all text output (and also user input) that took place during the simulation session.
Input Expected Results Actual Output
x y z f g h f g h
10 10 10 9,967
1 2,000 3
3 2 500 31,072
20,000 300 20,000
510,240,000
Notes:
! For the Expected Results section, assume an integer arithmetic engine with an
unlimited range of values. This means that no overflow conditions would ever occur;
however, division must still be treated as integer division.
! In the shaded fields, the actual output will not match the expected results.
Tip: Use an Excel spreadsheet to calculate the expected results. To implement integer division,
remove the fractional part of the ordinary division using the TRUNC function.

Requirements for This Lab
! Prelab
You must answer all 5 questions listed in the Procedure section. However, only the Expected
Results columns of the table need to be filled in; the actual results will be provided by your
completed assembly program, and shown in your lab report.
! Lab Demo
You must demonstrate your assembly program to the lab instructor, who will sign off on the
experiment. The ground rules regarding the demonstration are explained in the lab syllabus.
! Lab Report
Write your report according to the usual guidelines. The Description section must include the
results of all required tasks described in the Procedure section of the experiment. Attach a
hardcopy of the source code, the generated output log and the list file to your lab report.
Note: From this lab on, including this very lab, you will no longer need the execution log
showing the register and memory contents, therefore you dont need to generate and submit it; you
will only be working with the output log instead.

Next Lab Alert
The next experiment will also require a substantial amount of Prelab work; begin your preparation on time.
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 19
Experiment 6
68000 Integer Arithmetic with Error Detection

Objectives
Here we expand on Experiment 5 by coupling integer calculations with rigorous monitoring of overflow
and division-by-zero occurrences. The experiment also serves as an introduction to exception handling.

Required Resources
EASy68K 68000 Assembly Language Programming Tool

Problem
This experiments 68000 assembly program will again calculate the following signed integer formulas.
x g h
y
z
x
g
z y
z x
f
' % ' &
' (
&
' ' %
'
&
) 4 3 (
200
10
100
3

As in the previous experiment, the program prompts the user for the input variables with the message
Please enter x:, etc., and prints the results with the message Result: f=<value>, etc. This time, however,
your program must also look vigilantly for different adverse conditions during the calculations, and print
one of the following messages to warn the user each time a problem is encountered:
! WARNING! Operation overflow detected; result may be incorrect! or/and
! WARNING! Division-by-zero detected; result may be incorrect! or/and
! WARNING! Conversion overflow detected; result may be incorrect!
When all the calculations are completed, the user is prompted to push the Esc key to quit, for which the
program says good-bye and terminates; otherwise the calculations will be run on a new suite of input values
provided by the user.

Theoretical Comments
Three different situations may cause the 68000 assembly implementation of the above formulas to provide
incorrect results:
1. Operation overflow. This occurs when the result of an operation no longer fits into the data type
supported by the given operation. Aside from multiplication, all arithmetic operations in the above
formulas are prone to operation overflow. When the 68000 detects a signed overflow, it asserts the
V (Overflow) flag. Division is handled a bit differently: the arguments are checked before the
operation is carried out in order to see whether overflow is about to occur; if yes, the V flag will
be set, but the destination data registers contents will remain unchanged.
2. Division-by-zero. This condition is caused by a division, in which the divisor is zero. Considering
the seriousness of the situation, the 68000 responds by throwing a Divide-by-Zero exception
(vector #5). The destination register will again remain unchanged, but the V flag will be
undefined.
3. Conversion overflow. This may occur during conversion between data types (obviously only when
the number of bits in the data type representation is reduced). Unfortunately, the 68000 provides
no facility to detect this condition; it must be implemented by the programmer [i.e., you].
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 20
Notes related to C language. Arithmetic in high-level languages, for example in C, is implemented with a
slightly different philosophy.
1. Arithmetic operations. Unlike the 68000s multiplication and division instructions, these
operations in C do not jump between data types; all operands and the result are within the same
data type. Nor does C provide overflow notification; it merely proceeds with incorrect results.
However, the operations do support multiple data types; it is the implementors responsibility to
choose the data type suitable for a given problem.
2. Data type conversion. Since the operations in C stay within the same data type, there is hardly a
need for down-casting in a C program. On the rare occasion when it is required, one should use
the appropriate casting operator explicitly. If the C compiler notices an implicit down-casting, it
issues a message such as Warning! Conversion may lose significant bits.
However, the 68000 assembly is not C; it has its own idiosyncrasies that need to be dealt with accordingly.

Implementation Comments
You will need to detect the occurrence of the three different adverse conditions, and print the corresponding
warning messages; the most practical way to accomplish this task is to create three special subroutines, the
exception handlers.
1. Operation overflow. There is a handy facility in the 68000 assembly, specifically designed for
overflow monitoring: the TRAPV instruction. If the V flag is set when the TRAPV instruction is
encountered, it will cause an exception with vector #7. (This is not to be confused with the
TRAP #7 instruction, which generates an exception with vector #39!) If the V flag was not set,
execution continues normally with the next instruction.
2. Division by zero. In this case, the exception handler neednt be invoked manually; the offending
operation itself will cause an exception with vector #5.
3. Conversion overflow. This condition could be managed using a normal subroutine. However,
since it will be invoked frequently (and because of the phenomenons similarity to operation
overflow), this experiment requires that it also be written as an exception handler, invoked by a
user TRAP #0 instruction [vector #32]. (As a matter of fact, any TRAP would work, other than
TRAP #15, which is devoted to the EASy68K simulators API.) This routine should check first if a
conversion overflow is about to occur, and print the warning only if the diagnosis is positive.
Pitfall warning! When implementing the algorithm to detect conversion overflow, keep in mind
that you are dealing with signed numbers! (Hint: A signed longword can only be downcast to a
signed word successfully if and only if its value can be the result of an EXT. L operation; based on
this insight, you can conceive a very simple and elegant solution.)
Helpful tip: Do not forget to reserve registers D0 and D1 for the EASy68K Simulators TRAP #15 calls.
Also, you will need to dedicate a data register as the input parameter for your conversion overflow
subroutine. However, since this input parameter is also filled in on a call-by-call basis, much like D0 and
D1 for the TRAP #15 calls, you can use D0 or D1 for this particular purpose as well, if you wish.
Notes:
! Before any of the involved exceptions can occur, the corresponding exception handlers must be set
up. This means depositing the starting address of the subroutine, which will handle the overflow
exception, to the appropriate entry in the Exception Vector Table. (Hint: Do not think about
anything complicated here; the [longword] value of the starting address of each exception handler
must be copied to the memory address of the corresponding exception vector.)
! Remember, the exception is a special subroutine, therefore it must be terminated with an equally
special Return instruction!
! It is essential that you allow the program running in the EASy68K simulator to throw exceptions;
otherwise the simulation will stop with an error message. Simulation of exceptions can be enabled
through the SIM68Ks Options > Enable Exceptions menu item. Also, use the Task #9
function call instead of the STOP assembly instruction to terminate your program from now on.
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 21
Procedure
Based on the hints above, expand the program you prepared for Experiment #5 such that it satisfies the
new requirements described in the Problem section; then complete the following tasks for your lab report.
1. Show an example demonstrating how to set up the exception handlers.
2. Explain in general where the TRAPV and TRAP #0 instructions must appear in the program.
3. Explain how your conversion overflow detection algorithm works.
4. Create and fill in the table below; capture the entire session in an output log.
Input Actual Output Error Condition(s)
x y z f g h f g h
10 10 10 9,967
1 2,000 3
3 2 500 31,072 C
20,000 300 20,000 510,240,000

10 0 10 2,001
1 255 10,000
40,000 1 0 -306,329,856
C
0 1 40,000 4,698 CC CO
Note: Shaded fields indicate where the actual output was not supposed to match the expected
results. The tables new Error Condition(s) columns should show the cause of the discrepancies:
denote operation overflow by O, division-by-zero by D and conversion overflow by C (one
character for each occurrence). Because of interdependencies, an expression without errors may
still give the wrong answer; conversely, a result may end up being correct despite an error
condition. The only true statement is that if none of the expressions have any error, all results will
be correct. (With fancy mathematical terms, an error-free session is a sufficient condition for
correct results, and therefore correct results are a necessary condition for an error-free session.)

Requirements for This Lab
! Prelab
The following must be part of the Prelab Report presented to your instructor:
1. The above table with the Actual Output columns filled in from your results from
Experiment 5 (above the thick line).
2. A table showing the expected values for f, g and h, using the values of the four new input
suites (under the thick line of the above table).
! Lab Demo
You must demonstrate your assembly program to the lab instructor, who will sign off on the
experiment. The ground rules regarding the demonstration are explained in the lab syllabus.
! Lab Report
Write your report according to the usual guidelines. The Description section must include the
results of all required tasks described in the Procedure section of the experiment. Attach a
hardcopy of the source code, the generated output log and the list file to your lab report.

Next Lab Alert
The next experiment will focus on string handling; review this material prior to coming to the lab.
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 22
Experiment 7
String Manipulation & Hierarchical Design

Objectives
In this experiment, students will practice the manipulation of character arrays (a.k.a. strings). Furthermore,
the solution of the assignment requires a hierarchical design approach and subroutine implementation.

Required Resources
EASy68K 68000 Assembly Language Programming Tool

Problem
Write a 68000 assembly language program that reveals a password-protected secret message.
The program offers a menu of three commands: Retrieve secret message, Change password and
Quit. The user can select each command by pressing an associated key. (Remember to indicate these
keys in your menu printout!)
When Retrieve secret message is selected, the user is prompted for the password. (You must provide a
default password in your code, for example eee3231. Thus default must be made the current password
in the beginning of your program.) If the password is correct, the program displays the secret message; if
not, the user is prompted to re-enter the password. After three unsuccessful attempts, a message is printed
that the users request has been denied. (In a situation like this, a real-life system would also suspend the
users access for an extended period of time; however, you can leave this nasty feature off from your
program in this experiment.)
When Change password is selected, the user is again prompted for the [current] password. The
authentication procedure (including potential request denial) is the same as described above; if successful,
the user is prompted for the new password. (Passwords longer than 16 characters must be truncated!)
The user is then asked to re-enter the new password, in order to filter out inadvertent typos during password
entry; if the two strings match, the password is changed and an acknowledgement message is printed on the
screen. Otherwise the program complains and leaves the original password unchanged.
After the completion of the above commands, the program returns to the main menu. However, when
Quit is selected, the program says good-bye and terminates. (Obviously, this command does not require
password authentication. ! )

Theoretical Comments
This experiments theoretical content focuses on the computer science concepts of procedural
programming and top-down hierarchical design.
Although this problem is fairly complex, it can be broken into simpler parts (in this case the individual
commands). These can then be further partitioned into simpler and simpler tasks. This consecutive
partitioning of procedures into a hierarchy is referred to as top-down design.
As you identify the building blocks of your program, notice that certain tasks occur repeatedly, for example
the entire procedure of user authentication, as well as the string manipulation primitives. Take advantage of
this fact, and develop a code eliminating repetitive sections.
Use the subroutines of the 68000 assembly language to implement the procedures described above.
Because of the return address stored on the stack, subroutines can be invoked from any point of the
program, after which execution will resume at the instruction following the subroutine call.
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 23
Implementation Comments
The following hints will help you with the program implementation.
1. Communicating with Subroutines. Notice that in order to use the same subroutine in multiple
contexts, you must pass different values (parameters) to the subroutine; also realize that some
subroutines may produce a result (called the return value). Later you will learn how high-level
languages manage parameter passing; in this experiment, simply pass parameters and return values
in data registers. (Boolean return values can also be passed using one of the CCR flags.)
2. EASy68K Function Call of the Day. In this program, you will use another text I/O function call
offered by the EASy68K simulator:
Task #2: Read a 0-terminated string from the keyboard and store it at (A1); return the number
of input characters in D1.W (maximum 80).
Notice that this function call is the inverse of Task #1 and Task #14 in one: the length of the
input string is assigned to D1.W, but the string is also terminated by a 0-character. This is good
news: it is much easier to manipulate 0-terminated strings than length-defined ones.
3. Required Buffers. The above properties of the Task #2 function call also mean that the allocated
input string buffer must be at least 81 bytes long, otherwise a malicious user would be able to
launch a successful Buffer Overrun attack against your program. Since password length is limited
to 16 characters by the problem specification, it is sufficient to define all other password-related
buffers 17 bytes long. Warning! Make sure that even if a password is truncated, it is still
terminated by a 0-character.

Procedure
Write the program based on the above help, and then complete the following tasks for your lab report.
1. Briefly explain the hierarchical design of your program.
2. Complete each step of the test sequence below, exactly the way it is specified.
i) Choose the Retrieve secret message command, but get rejected by providing three wrong
passwords. Among the failed attempts you must provide a substring and a superstring of the
correct password, for example eee3 and eee3231rocks (for default password eee3231).
ii) Choose Retrieve secret message again, but this time provide the right password for the
second attempt; your program should reveal the secret message.
iii) Choose the Change password command, and get kicked out again after three wrong
passwords. Obviously, no password change should occur.
iv) Choose Change password again, and this time provide the right password. Specify the new
password, but make a mistake with the second entry; this should leave the password
unchanged.
v) Choose Change password and authenticate yourself again. Enter the new password and
confirm it successfully; the program should announce the password change.
vi) Choose Retrieve secret message, and enter this new password; your program should
recognize it and reveal the secret message.
vii) Choose Change password and authenticate yourself once again. Enter the new password,
but make sure that this time it is longer than 16 characters. Successfully confirm this
password. (The confirmation string that works in this case depends on your exact
implementation.) The program should announce the password change.
viii) Choose Retrieve secret message, and enter the first 16 characters of the password you just
specified; it should be successfully recognized as the right password.
ix) Choose Quit; the program should successfully terminate.
Note: Do not forget to capture the entire session in an output log.
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 24
Requirements for This Lab
! Prelab
Refresh your understanding about string handling.
! Lab Demo
You must demonstrate your assembly program to the lab instructor, who will sign off on the
experiment. The ground rules regarding the demonstration are explained in the lab syllabus.
! Lab Report
Write your report according to the usual guidelines. The Description section must include the
results of all required tasks described in the Procedure section of the experiment. Attach a
hardcopy of the source code, the generated output log and the list file to your report.

Next Lab Alert
The next experiments Prelab will require matrix calculations to be completed and demonstrated to your
lab instructor; begin your preparation on time.
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 25
Experiment 8
Matrix Arithmetic

Objectives
In this experiment, students will practice the manipulation of two-dimensional arrays through the example
of algebraic matrices. This problem will again require a hierarchical design approach.

Required Resources
EASy68K 68000 Assembly Language Programming Tool

Problem
Write a 68000 assembly language program that performs the addition and subtraction of two matrices of
signed longwords; in the next experiment, you will add the multiplication functionality. Since the final
program is expected to perform all these operations on the same matrices, both matrices must be square and
of equal size; your implementation must accept an arbitrary size between 1 and 10.
The program offers a menu of five commands: Input matrices, Add, Subtract, Multiply and Quit.
The user can select each command by pressing the associated key. (Remember to indicate these keys in
your menu printout!)
When the Input matrices command is selected, the user is prompted for the single Size parameter first.
Then the program displays Please enter matrix A, and prompts for the individual elements one by one
(e.g., Enter (1,1):, Enter (1,2):, etc.). When all elements of the matrix have been entered, the matrix is
printed on the console. The same procedure is followed for matrix B. The matrices must be printed in a
properly tabulated format; the below example shows the printout for an arbitrary 33 matrix as matrix A:
A =
1 4 23
132 62 0
9 11 7
When Add is selected, the two matrices are added together, and the result printed after caption A+B =.
When Subtract is selected, matrix B is subtracted from matrix A, and the result is printed after AB =.
When Multiply is selected, the program for this experiment only prints Under Construction.
After the completion of the above commands, the program returns to the main menu. However, when
Quit is selected, the program says goodbye and terminates.
Important requirement: In order to make testing easier, your program must define the following defaults:
)
)
)
)
)
)
*
+
,
,
,
,
,
,
-
.
&
)
)
)
)
)
)
*
+
,
,
,
,
,
,
-
.
&
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
25 24 23 22 21
20 19 18 17 16
15 14 13 12 11
10 9 8 7 6
5 4 3 2 1
B A
This means that these two matrices are in effect even prior to the first Input matrices command request.

Theoretical Comments
Recall the general formulas for the addition and subtraction of mn matrices:
) 1 , 1 ( n j m i b a c B A C
ij ij ij
/ / / / 0 & 1 0 &
For a square matrix, m and n are equal.
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 26
Implementation Comments
The following hints will help you with program implementation.
1. Hierarchical Design. You must provide a hierarchical design, in order to increase the legibility of
your program and minimize code repetition.
2. EASy68K Function Call of the Day. In this program, you will take advantage of a specific text I/O
function call offered by the EASy68K simulator:
Task #20: Display the signed longword contents of D1.L in decimal, using D2.B fields.
(Using a C-analogy, this can be represented as pr i nt f ( " %*l d" , D2. B, D1. L) ; .)
This particular function call will keep the columns of the matrices neatly right-aligned. The
longest signed longword would occupy as many as 11 fields; in your implementation you are
allowed to choose a field length smaller than that (for example 6) for esthetic reasons.
3. Required Buffers. Remember that all three matrices contain longwords, and can have a size as
large as 1010; allocate the necessary buffers accordingly. Furthermore, you will need to provide
the default values for matrices A and B; one solution is to provide assembly-time definition using
the appropriate assembler directives and the DS-overstrike trick (in which the buffer defined by
the DS directive intentionally overlaps the previously defined default values).
4. Matrix Operations. If the elements of the matrices are stored in the memory contiguously
(recommended order: row-major), all operations can be implemented using simple running
pointers. The input/output functions need to be aware of each elements exact position within the
matrix for printout, therefore these operations must implement double nested loops. The same is
recommended for the addition and subtraction algorithms for symmetry reasons, although in these
particular cases single loops would work as well. (Do you understand why?)

Procedure
Write the program and then complete the following tasks for your lab report.
1. Briefly explain the hierarchical design of your program.
2. Execute the calculations below.
i) Complete the addition and subtraction of the two default matrices.
ii) Repeat for the matrices below:
)
*
+
,
-
.
% %
% %
&
)
*
+
,
-
.
&
000 , 50 000 , 60
000 , 70 000 , 80
000 , 40 000 , 30
000 , 20 000 , 10
B A

Requirements for This Lab
! Prelab
Your Prelab Report must include the results of calculations described in the Procedure section.
! Lab Demo
You must demonstrate your assembly program to the lab instructor, who will sign off on the
experiment. The ground rules regarding the demonstration are explained in the lab syllabus.
! Lab Report
Write your report according to the usual guidelines. The Description section must include the
results of all required tasks described in the Procedure section of the experiment. Attach a
hardcopy of the source code, the generated output log and the list file to your report.

Next Lab Alert
The next experiment will require more matrix calculations for the Prelab; begin your preparation on time.
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 27
Experiment 9
Matrix Multiplication

Objectives
In this experiment, students will implement the multiplication of algebraic matrices as an example of
advanced algorithms involving two-dimensional arrays.

Required Resources
EASy68K 68000 Assembly Language Programming Tool

Problem
Augment the 68000 assembly language program you prepared for Experiment 8 with the functionality of
matrix multiplication. Obviously, the two operands and the result remain square matrices of signed
longwords, with maximum size of 1010.
The program must now respond to the Multiply command, upon which the two matrices are multiplied,
and the result is printed after the caption A*B =.

Theoretical Comments
Recall the general formula for matrix multiplication:
) 1 , 1 (
1
n j m i b a c B A C
p
k
kj ik ij
/ / / / ' & 1 ' &
$
&

where matrices A, B and C are of size mp, pn and mn respectively. This experiment only deals with
square matrices, therefore m = p = n.

Implementation Comments
The following hints will help you with program implementation.
1. Nested Loops. Take a closer look at the formula, and recognize the triple nested loop structure
inherent to the matrix multiplication algorithm. (Two loops maintain running variables i and j; the
third loop implements summation over k.) In the code design phase, you must identify the tasks to
be carried out before, during and after each of the loops; plan carefully or your job will be much
more difficult.
Attention! Any solution that can only multiply matrices with a certain fixed size will not be
accepted (even for partial credit)!
2. Multiplication with Implicit Downcasting. The 68000 Integer Arithmetic experiment clearly
demonstrated the pitfalls inherent in the 68000s multiplication and division instructions.
Multiplication, for example, takes both of its arguments as word operands (even if those
arguments originated from operations with longword results); this behavior is called implicit
downcasting.
In the aforementioned experiment, the involved operands were located in registers. Now, however,
the situation is even more complicated, as the operands are stored in memory. Because the big-
endian system places the highest-order byte of multi-byte data at the lowest memory address, the
operation attempting implicit downcasting of such an argument will definitely work with an
incorrect value. To avoid this problem, the pointer addressing the argument to be downcast must
be adjusted accordingly before the operation takes place. (This inconvenience was probably the
major factor behind the eventual demise of the big-endian system.)
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 28
3. The Winning Strategy. There are various ways to approach this programming challenge; individual
solutions may differ in terms of efficiency, ease of implementation and mathematical elegance. In
assembly, the typical method for accessing elements in one- and multi-dimensional arrays applies
running pointers. This particular problem is no different; we highly recommend a solution that
maintains the following five running pointers:
i) Pointer to the beginning of the current row of matrix A
ii) Pointer to the beginning of the current column of B
iii) Pointer to the current column [element] in the current row of A
iv) Pointer to the current row [element] in the current column of B
v) Pointer to the current element in C
But these are only guidelines; feel free to use a different approach in your implementation if you
wish so.

Procedure
Write the multiplication subroutine, integrate it into your existing program, and complete the following
tasks for your lab report.
1. Complete the addition, subtraction and multiplication of the two default matrices.
2. Repeat for the matrices below:
)
)
)
*
+
,
,
,
-
.
% %
%
%
&
)
)
)
*
+
,
,
,
-
.
&
1 1 3
0 1 1
1 0 1
1 1 2
1 2 1
1 1 1
B A

Requirements for This Lab
! Prelab
Your Prelab Report must include the 68000 assembly code you will test and debug during the lab,
and the results of calculations described in the Procedure section.
! Lab Demo
You must demonstrate your assembly program to the lab instructor, who will sign off on the
experiment. The ground rules regarding the demonstration are explained in the lab syllabus.
! Lab Report
Write your report according to the usual guidelines. The Description section must include the
results of all required tasks described in the Procedure section of the experiment. Attach a
hardcopy of the source code, the generated output log and the list file to your report.

Next Lab Alert
The next experiment will require the understanding of interrupt handling; come to the lab well-prepared.
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 29
Experiment 10
Embedded System Firmware Design

Objectives
In this experiment, students will learn the fundamentals of embedded system firmware design through the
example of a fictitious process-monitoring device, responsible for guarding the temperature of a chemical
compound. The demonstration of the concepts takes full advantage of the features provided by the
EASy68K suites hardware simulation facility.

Required Resources
EASy68K 68000 Assembly Language Programming Tool

Problem
Consider a water-based chemical solution that needs to be stored and transported safely. The compound is
not particularly sensitive, but it must be maintained in liquid form at all times. Your assignment is to design
the firmware of a temperature monitoring device attached to the storage tank. This device consists of a
temperature sensor chip with an 8-bit digital output indicating readings between 0 F and 255 F, and an 8-
digit 7-segment LED display that shows the measured temperature values (and error messages when
necessary). The device also has a row of lights that warn about the length of temperature range violations,
and a sound chip with its own memory, preprogrammed to give audible indication of the different operating
conditions. The gadgets Hardware Reset button resets the device after a critical temperature error.
The device reads the sensor in one-second intervals, utters a ticking sound, and shows the temperature on
the 7-segment display as a leading-zero-suppressed decimal value (for example 75 F for 75 F). Each
time the value is below the freezing point (32 F), or above the boiling point (212 F), a warning click
sounds and one more light turns on, indicating an increasing severity of warnings. Once the temperature is
back to the normal range, all lights are cleared and the warning level is reset to zero. However, eight
consecutive out-of-range readings constitute a critical error producing an error beep and an error message
(which is Abort Lo if the temperature was too low or Abort Hi if it was too high); this means that the
sample was exposed to harsh conditions for an unacceptably long time and must be destroyed. If a critical
error occurs, the device goes to a frozen state, i.e., it only responds to the Hardware Reset button. (For code
simplicity, assume there is at least one in-range sample between an under-range and an over-range reading;
this assumption is perfectly valid in real-life.)
The EASy68K Simulator has everything needed to implement the simulated version of the above
specifications. The 7-segment display, the row of lights and the Hardware Reset button are readily available
in the EASy68K Hardware window, while the 8-bit temperature sensor data is simulated by the set of eight
toggle switches. The time base for the one-second sampling is provided by the Auto Interval option that
can be associated with any interrupt, and its cycle time can be specified in milliseconds. Finally, the sound
chip is implemented by a specific group of simulator function calls.

Theoretical Comments
The explanations in this section refer to the solution of the problem in general, with special emphasis on a
real-life microcontroller implementation.
Interrupts and the Interrupt Service Routines (ISRs)
Real-time embedded systems utilize the processing units interrupt facility to be in close correspondence
with their environment; this provides a way to detect, and react to, external stimuli in a timely manner
the most important requirement imposed on real-time systems. However, an important tool in the
embedded designers arsenal is the timer-driven interrupt. This occurs with a predetermined frequency, and
its interrupt service routine (ISR) takes care of environment-related chores such as polling the input
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 30
peripherals and updating the output peripherals. Virtually all microcontrollers contain an on-chip timer that
can generate this regular interrupt. The disadvantage of this method is that the systems reaction to external
stimuli is no longer real-time, but is determined by the interrupt cycle time. However, with this time
appropriately selected, the complexity of the software design is drastically reduced, leading to higher
robustness and reliability.
What must be put into the ISR? The answer is not always easy, and will depend on the problem at hand.
Generally, the execution time of any ISR should be minimized so that if multiple interrupts are
implemented, they can all be serviced quickly enough. (The invocation of an ISR while another is running
is dangerous and should be avoided; the design of some microcontrollers even makes it virtually
impossible.) At the same time, the ISR must complete all of its essential tasks. For this reason, longer tasks
should be placed in the non-ISR code of the firmware, known as the background code.
In this extremely simple example, the device must merely read and display the temperatures measured by
the sensor. Since these tasks can be completed quickly, there are two different, but equally good solutions:
1. One can implement the entire functionality within the ISR. Here the background code is reduced
to a simple spinning loop [i.e., a loop with an empty loop core] or an instruction equivalent to the
68000s STOP.
2. One can put everything in the background code instead. Here the execution is also halted between
timer interrupts, but the only role of the interrupt is to notify the background code that the time has
come to execute another iteration of the temperature manipulation code.
In either case, if a critical error occurs the device must finish in a catatonic state. It must freeze all
activities and respond only to the Hardware Reset button. (Multiple good solutions exist; however, you
must not use the Task #9 function call for the purpose, as it is only a construct within the simulated
platform , and has no real-life equivalent.)
Firmware Memory and the Exception Vectors
This experiment differs from the others because in this case the software will become part of a stand-alone
device (and as such, is called firmware) instead of loading into a generic computers memory as an
application program. The firmware, including the constant data definitions, is burned into a Read-Only
Memory (ROM) starting at address 0, so that it can also include the 68000s exception vectors. On the other
hand, the variables and the stack are placed in a Random Access Memory (RAM). In this simple problem,
the 68000s registers are enough to store all necessary data; however, if you wish to use memory variables,
assume that a 256-byte RAM exists at address $FFFF00.
As mentioned above, the vectors of the handled exceptions must be provided by the ROM as part of the
firmware. A 100% robust solution would handle all exceptions that could possibly occur; however, you
may simply handle the autovector interrupt of your choice along with the Reset exception, which requires
the setup of two vectors. With the RAM configuration mentioned above, the Supervisor Stack Pointer
(SSP) must be initialized to $1000000; you must determine the initial value of the Program Counter (PC) as
part of the exercise.
Character Generation
The BCD-to-decimal decoder and 7-segment display driver modular logic chip is probably familiar to
you from digital electronics; what this program needs is the software equivalent of the above. The linkage
between the two is stronger than it may initially seem. The display driver chip implements a 4-input
7-output Boolean function, which is easily created using a special type of Programmable Logic Device
(PLD) known as ROM! This ROMs contents are the Boolean functions truth table. The same sort of
data in a computer program (in this case an embedded systems firmware code) is referred to as a lookup
table, and since this particular table contains character graphics, it further qualifies as a character
generator. (In the hardware version, the digital inputs address the individual entries directly; in 68000
assembly, one of the addressing modes will be particularly suitable for the task of table lookup. Which
one?)
Note, however, that before the digits can be displayed, the temperature byte-value must be decomposed
into three decimal digits by a suitable binary-to-decimal conversion algorithm. (Luckily, the sensors output
is a binary value, therefore no decimal-to-binary conversion on the front-end of the program.)

EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 31
Signed or Unsigned?
The temperature sensor provides its measurement as an unsigned byte value, per the sensors specifications.
Hence the firmware code must consistently treat these values as unsigned bytes, erratic behavior will result
otherwise. (The classic example of a similar issue, but on a much grander scale, is the bug that caused the
fiery demise of the first Ariane 5 rocket on June 4, 1996.)

Implementation Comments
This section pertains to the mockup implementation of the device using the EASy68K Simulator.
The Simulated 7-Segment Display and Other Widgets
The EASy68K Simulators 7-segment display is simulated as a byte peripheral
beginning at default address $E00000, which represents the displays leftmost
digit. Since the 68000s data bus is 16 bits wide, the subsequent digits are
mapped to a series of peripheral addresses increasing by two ($E00002,
$E00004, etc.); this minor nuisance must be handled by the program. The figure
on the right shows how the individual bits correspond to the display segments.
The rows of lights and switches are located at default address $E00010 and
$E00012 respectively; the leftmost device is mapped to the most significant bit
in each case.
Playing Sound Files
Among the more exotic EASy68K Simulator function calls are those that support the playing of WAV-
format sound files. Here we summarize the function calls and their task codes:
! Task #70: Play a WAV-file; the path is the 0-terminated string at (A1).
! Task #71: Load a WAV-file with identifier D1.B; the path is the 0-terminated string at (A1).
! Task #72: Play the WAV-file with identifier D1.B, previously loaded with Task #71.
Tasks #71 and #72 are the decomposition of Task #70. Although it may seem simpler to use Task #70, it is
better to load all necessary sounds from disk to memory at the start of the program with Task #71, and play
them as often as necessary with Task #72 with no lead time due to disk access.
You can be creative with the different sounds. You could, for example, use Wi ndows XP Def aul t . wav for
the warning click and Wi ndows XP Har dwar e Fai l . wav for the error beep, as both sound sufficiently
dramatic for the purpose. A sufficiently pleasant, but well-audible sound for the tick would be Wi ndows XP
Bal l oon. wav. At the time of this writing, these files are located in the C: \ Wi ndows\ Medi a directory of a
computer running the Windows XP operating system.
Exception Simulation and Program Termination
Remember to enable the simulation of exceptions. Also, since interrupts are involved in this experiment, it
is very important that you use Task #9 instead of the STOP assembly instruction to terminate your program.

Procedure
Write the program and then complete the following tasks for your lab report.
1. Briefly explain your program design: what the background code and the ISR contain, which
interrupt you chose for the timer, and how the devices frozen state was achieved.
2. Explain how you initialized the Reset exception vectors.
3. Set the timer auto-interval value to 1000 ms. Start execution with the Reset button in the
EASy68K Hardware window (and not with the Reset Program toolbar button!). Once HELLO!
appears on the 7-segment display, associate the timer with the interrupt of your choice.
4. Play around with the switches representing the temperature sensor, and see if the displayed
temperature values are correct. Take three screenshots of the EASy68K Hardware window; they
should show the HELLO! message, the exact temperature value of 27 F, and one of the two
error messages. Add these screenshots to your lab report.
0
1
2
5
4
6
3 7
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 32
Requirements for This Lab
! Prelab
Refresh your understanding about interrupt handling. Study and understand the usage of the
different widgets in the EASy68K Hardware window.
! Lab Demo
You must demonstrate your assembly program to the lab instructor, who will sign off on the
experiment. The ground rules regarding the demonstration are explained in the lab syllabus.
! Lab Report
Write your report according to the usual guidelines. The Description section must include the
results of all required tasks described in the Procedure section of the experiment. (Make sure to
also include the screenshots you took!) Attach a hardcopy of the source code and the list file to
your report.

Next Lab Alert
The next experiment will require the clear understanding of stack frames, and familiarity with recursive
algorithms. This is a tough experiment; come to the lab exceptionally well-prepared.


EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 33
Experiment 11
Implementation of a Recursive Algorithm (Fibonacci)

Objectives
In this experiment, students will complete the implementation of a recursive algorithm in the 68000
assembly language. As the Enabling Technology, the method of stack-based parameter passing will also
receive special emphasis in this exercise.

Required Resources
EASy68K 68000 Assembly Language Programming Tool

Problem
Write a 68000 assembly language program, which implements the recursive formula to calculate the
elements of the Fibonacci Series. (In recursive formulas, results are determined by the application of the
same formula to preceding terms.) The algorithm for the Fibonacci Series is defined as follows:
f(k) = f(k1) + f(k2) f(0)=0, f(1)=1
The first few elements of the Fibonacci Series are:
0 1 1 2 3 5 8 13 21 34 55 89
The program prompts the user for the index of the Fibonacci Series element (a.k.a. Fibonacci Number) to
be printed, calculates the result and prints it on the screen. (For example, f ( 6) = 8.) The program
prompts the user for another index and repeats the calculation and printout detailed above, until the user
enters a negative number, in which case the program says good-bye and quits.

Theoretical Comments
The Fibonacci Series was invented by (guess who) Fibonacci (a.k.a. Leonardo da Pisa) in the early 13
th

century, as a result of his rudimentary model approximating the growth of a breeding rabbit population.
(Fibonacci, the genius of the era, is also responsible for introducing the decimal system to the Latin-
speaking world.) In spite of its simple definition, the Fibonacci Series turned out to be the key to an
awesome mathematical Wonderland, which mysteriously links seemingly unrelated phenomena across
science and nature, such as the Golden Section, the shape of ammonites, the arrangement of seeds in a
sunflower, and so on; a Web search with one or more of the above keywords is a good start to enter this
enchanting world. The very first interesting fact to muse about is the closed [i.e., non-recursive] form
expression of the Fibonacci Series:
2 3
k k
k k
k f 4 % 5 &
)
)
*
+
,
,
-
.
6
6
7
8
9
9
:
;
%
%
6
6
7
8
9
9
:
;
(
&
5
1
2
5 1
2
5 1
5
1
) (
Incredible as it may sound, this formula, which includes powers and a reciprocal of hideous irrational
numbers, does indeed churn out perfect integers for each integer value of k. The expression 5 (named such
to honor Fibonacci) evaluates to 1.6180339887, and is the famous and infamous Golden Section itself.
The value of 4 is 0. 6180339887, from which it also follows that 5+4 = 1 (just some food for thought).
Amazed enough? Great; then lets move on from Theory to Practice!

EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 34
Implementation Comments
Your implementation needs to be based on the following C-style pseudocode:

l ong Fi b( l ong k) / * k: Funct i on par amet er */
{
i f ( k<=1)
r et ur n k; / * <<< Br eakpoi nt her e f or Pr ocedur e #3 */
el se
r et ur n Fi b( k- 1) +Fi b( k- 2) ; / * THE TWO RECURSI VE CALLS! */
}

In order to get the desired element of the Fibonacci Series, the main program has to invoke this function
with the index entered by the user, and print the result on the screen. Since this is a recursive function, it
must be re-entrant; therefore the subroutines parameter has to be passed through the stack. The arithmetic
must be done over longwords, so the 68000s full capabilities will be utilized. Due to the exponential
progression of the series, storing the value of k in a byte would be far sufficient; however, in order to study
the contents of the stack easier, it is practical to implement k as a longword too.
It is not necessary to support true local variables in this simple problem, but registers implementing quasi
local variables (partial results of the Fibonacci calculation in this experiment) will need to be saved on the
stack after entering the subroutine (and restored from the stack before exit, obviously). Even in this case,
the most elegant [and practical] solution is to build a full-fledged stack frame, in order to nail an address
register (say A0) to the top of the stack before the quasi local variables are saved. This can be done using
the LI NK A0, #0 instruction, where #0 means that no stack is allocated for true local variables.
(Keeping the changeable A7 to reference the function parameters would be very tedious and error-prone!)
The subroutines return value can be passed in a data register (e.g. D7), per the commonly used convention.

Note: The truth of the matter is that the original Fibonacci formula containing the double recursion
produces an implementation quite wasteful, in which some of the f(k) values are calculated over and over
again, several times. Consider, for example, the recursion tree for f(5). (The bubbles show the value of k.)


From the figure it is obvious that the nodes encircled by the ellipse represent calculations that have already
been completed before. This multi-dipping can be eliminated with the recursive vector formula below:
)
*
+
,
-
.
& % '
)
*
+
,
-
.
&
1
0
) 0 ( ) 1 (
0 1
1 1
) ( f f f k k
The Fibonacci Numbers are provided by the f
1
(k) element. The gist of this idea is that instead of unleashing
an entire new chain of recursion for each f(k2) [in the original formula], its value is provided in every
recursive call by saving the result of the previous call, and passing it on upstream. However, the
implementation of this advanced algorithm is beyond the scope of this lab experiment.
1
5
4
3
3
1
2 1
1
0
0
2
2 1 0
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 35
Procedure
Write the program specified in the Problem section, and complete the following tasks for your lab report.
1. Turn on the Output Log, and run the program with values 0, 1, 2, 5, 10, 15, 20, 25 and 30.
(Observe that for higher values, the algorithm slows down noticeably; the execution takes several
minutes on 2.8 GHz Pentium 4 PC.)
2. Turn off the Output Log, and run the program with the list of values provided above. However,
this time quit after every calculation, and observe the number of executed memory cycles
(Cycles text box in the EASy68K Simulators main window). Create a table showing the
index, the Fibonacci number and the number of executed memory cycles. What can you say about
the Fibonacci numbers and memory cycles as the index increases by 5?
3. Put a breakpoint to the instruction in your program, which is equivalent to the line of the C-style
pseudocode with the <<< mark [if your current implementation does not have an exclusive
instruction line for this condition, make one], and run the program with k=3. When the execution
reaches the breakpoint, capture the EASy68K Simulators stack window, and explain the contents
of the entire stack.
WARNING! A non-recursive solution to the required calculation cannot be accepted, as it completely
misses the point! The real purpose of this experiment is not to generate the Fibonacci Series per se; it is
merely used as a simple, but sufficiently interesting example to demonstrate the implementation of
recursive subroutine calls.

Requirements for This Lab
! Prelab
Refresh your understanding about stack frames and recursive algorithms.
! Lab Demo
You must demonstrate your assembly program to the lab instructor, who will sign off on the
experiment. The ground rules regarding the demonstration are explained in the lab syllabus.
! Lab Report
Write your report according to the usual guidelines. The Description section must include the
results of all required tasks described in the Procedure section of the experiment. Attach a
hardcopy of the source code, the generated output log and the list file to your report.

Next Lab Alert
The next experiment will require the understanding of the C programming language; come to the lab with
the sufficient amount of review completed, with special emphasis on pointer arithmetic.
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 36
Experiment 12
Assembly Implementation of a C Program (Insertion Sort)

Objectives
In this experiment, students will learn about the correlation between programs written in assembly and
high-level languages using the example of the 68000 assembly and the C programming language, where the
correlation is particularly close. The concepts are demonstrated through the implementation of the classic
Insertion Sort algorithm.

Required Resources
EASy68K 68000 Assembly Language Programming Tool

Problem
Consider the following C language program:

/ *- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/ * Pr ogr amNumber : EEE3231 Exper i ment 12 */
/ * Descr i pt i on : Assembl y I mpl ement at i on of a C Pr ogr am( I nser t i on Sor t ) - C sour ce */
/ * Wr i t t en by : Pet er Csaszar */
/ *- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

/ * Thi s C pr ogr amsor t s t he cont ent s of an i nt eger ar r ay i n ascendi ng or der usi ng t he */
/ * I nser t i on Sor t al gor i t hm. Thi s i s t he code t o be t r anscr i bed i nt o 68000 assembl y. */

#i ncl ude <st di o. h>

#def i ne ARRLEN 10

voi d mai n( )
{
i nt vi Sor t Ar r ay[ ] = { 24, 43, 107, - 333, 24, 6, 7, 514, 0, - 21 };
i nt i , j , i Cur r Num;
i nt *pi Cur r Pt r , *pi RunPt r , *pi Sr cPt r , *pi Dest Pt r ;

pr i nt f ( " EE3231 Exper i ment 12: I nser t i on Sor t \ n\ n" ) ;
pr i nt f ( " Wr i t t en by Pet er Csaszar \ n\ n\ n" ) ; / * Put YOUR name i n t he t r anscr i bed code */
pi Cur r Pt r = vi Sor t Ar r ay; / * St ar t sor t i ng f r omt he f i r st el ement */
f or ( i =ARRLEN- 1 ; i >- 1 ; i - - ) { / * Maul t hr ough t he ar r ay */
i Cur r Num= *pi Cur r Pt r ; / * Fet ch cur r ent number awai t i ng r el ocat i on */
pi RunPt r = vi Sor t Ar r ay; / * Fi nd new l ocat i on f r omt he f i r st el ement */
do / * Fi nd cur r ent number ' s new l ocat i on */
; / * Not hi ng el se t o be done wi t hi n t hi s l oop */
whi l e ( i Cur r Num>*pi RunPt r ++) ; / * Cur r ent number ' s new l ocat i on f ound! */
pi Sr cPt r = pi Cur r Pt r ; / * Pr epar e sour ce f or r el ocat i on pr ocedur e */
pi Dest Pt r = pi Cur r Pt r ; / * Pr epar e dest . f or r el ocat i on pr ocedur e */
pi Dest Pt r ++; / * Dest i nat i on posi t i on: r i ght - si de nei ghbor */
whi l e ( pi Sr cPt r >=pi RunPt r ) / * Bump af f ect ed number s one posi t i on r i ght */
*- - pi Dest Pt r = *- - pi Sr cPt r ; / * Copy nei ghbor s; MUST decr ease addr esses */
*pi Sr cPt r = i Cur r Num; / * I nser t number i nt o i t s new posi t i on */
pi RunPt r = vi Sor t Ar r ay; / * Pr i nt t he ar r ay f r omt he f i r st el ement */
f or ( j =ARRLEN- 1 ; j >- 1 ; j - - ) / * Sweep t hr ough t he ar r ay */
pr i nt f ( " %6d" , *pi RunPt r ++) ; / * Pr i nt ar r ay el ement */
pr i nt f ( " \ n" ) ; / * Pr i nt a newl i ne */
pi Cur r Pt r ++; / * Move on t o t he next number t o be r el ocat ed */
}
pr i nt f ( " \ nOper at i on compl et e\ n\ n" ) ;
}

Observe this C code carefully, and generate its equivalent written in 68000 assembly language.
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 37
Theoretical Comments
The above C program sorts the contents of an integer array in ascending order using the Insertion Sort
algorithm; it also displays the array as it is being transformed from an unsorted into a sorted data structure.
Insertion Sort is another sorting algorithm, whose running time does not reach the theoretical minimum,
however due to its simplicity (and therefore ease of implementation) it is often a preferred algorithm for
sorting small data arrays. In principle, it is similar to the way people sort a hand of cards once the cards
have been picked up. The figure below demonstrates the algorithm on an integer array.


The array is sorted by observing each element from left to right, finding its place in the sorted portion of the
array, and then relocating it to the appropriate position. The sorted portion is growing from left to right, and
it is always between the beginning of the array and the currently observed element.
In an array of size n, finding the right spot for an element takes O(n) time, and so does the relocation of the
element that requires bumping O(n) elements up one position. Since this procedure is repeated for all n
elements, the final complexity of the algorithm is O(n); the same as that of Bubble Sort, see Experiment 2.

Implementation Comments
Since this is a winding down experiment, it is quite easy, despite the initially somewhat intimidating look
of the C code. The program was intentionally written up such that it can be directly translated into 68000
assembly, just by observing the C statements carefully. (The explanation of the often counter-intuitive
pointer behavior is the effort to use the addressing modes available on the 68000.) But here are some hints:
! The exact representation of the int data type in C is implementation-dependent, often determined
by the architecture of the host machines processor; it is defined as either 2 or 4 bytes. This means
that you can also to use either words or longwords for the integer array in your assembly program.
However, in order to keep things simpler, use the word data type in this experiment.
! Use the appropriate assembler directives for the definition of the constant and the array.
! It is not necessary to define the data variables as actual variables in the assembly program; they
can be represented by data registers.
! In the same token, the pointer variables can be implemented using address registers.
! Make sure to use the dedicated addressing modes of the 68000 that are equivalent of accessing an
object referred to by a pointer, and adjusting the pointers value within the same operation.
! Use the Simulators different text I/O function calls to implement all pr i nt f statements.
CAVEAT! Contrary to the last bullet item above, the 68000 has no addressing mode support for operations
where a pointers value is adjusted, without accessing an element referenced by the pointer. In this case
your assembly program must adjust the pointer explicitly, but make sure that the adjustment uses the correct
value! (As a matter of fact, it is possible to use the 68000s special addressing modes in these scenarios as
well, but with a little trick. For example, by replacing the line pi Dest Pt r ++; by ! ! *pi Dest Pt r ++; in
the C program, we get a logic test of the object pointed to by pi Dest Pt r , but the result of the logic test has
been thrown away. Can you find the 68000 assembly equivalent of this modified statement?)
-333 6 24 24 43 107
7
514 0 -21
Sorted Unsorted
EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)
Peter Csaszar Lawrence Technological University, ECE Department 38
Procedure
Write the program using the above guidelines, and then complete the following tasks for your lab report:
6. Explain which addressing modes you decided to use to access an object referred to by a pointer,
and adjust the pointers value within the same operation.
7. Explain why the elements must be copied with decreasing addresses in the relocation procedure.

Requirements for This Lab
! Prelab
Dust off your C programming skills, with special emphasis on pointer arithmetic.
! Lab Demo
You must demonstrate your assembly program to the lab instructor, who will sign off on the
experiment. The ground rules regarding the demonstration are explained in the lab syllabus.
! Lab Report
Write your report according to the usual guidelines. The Description section must include the
results of all required tasks described in the Procedure section of the experiment. Attach a
hardcopy of the source code, the generated output log and the list file to your lab report.

Next Lab Alert
There is no next lab! !