lab manual - eee3231 - wix.com

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

Upload: others

Post on 12-Sep-2021

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lab Manual - EEE3231 - Wix.com

Lab Manual for

Microprocessors Lab (EEE3231)

Peter Csaszar Department of Electrical and Computer Engineering

Lawrence Technological University

All Rights Reserved

Version 1.0.0

Page 2: Lab Manual - EEE3231 - Wix.com

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

Page 3: Lab Manual - EEE3231 - Wix.com

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 Kelly’s 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 author’s 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 manual’s 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 Beginner’s 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.)

Page 4: Lab Manual - EEE3231 - Wix.com

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 manual’s 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 lab’s 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.

Page 5: Lab Manual - EEE3231 - Wix.com

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 EASy68K’s 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.

Page 6: Lab Manual - EEE3231 - Wix.com

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: *--------------------------------------------------------------------------------------- * Program Number: EEE3231 Experiment 1 * Description : Introduction to the Assembly Program Development Procedure * Written by : <Your name here> * Date : <Today's date here> *--------------------------------------------------------------------------------------- * Constant Definitions ORWELL equ 1984 ; Numeric constant (No prefix: Decimal) * Data Definitions org $1000 ; Starting address dcb.b 16,0 ; Initial memory clean-up org $1000 ; Reset Location Counter to starting address bMyByte dc.b %1001 ; Byte definition ('%': Binary) wMyWord dc.w ORWELL ; Word definition (Uses constant) lMyLong dc.l $5043F840 ; Long definition ('$': Hexadecimal) lMyResult ds.l 1 ; Definition of one uninitialized long * Program Code Start move.l #@370,d0 ; Initialize D0 ('@': Octal) add.b bMyByte,d0 ; Add bytes (upper 3 bytes unchanged) clr.l d1 ; Clear entire D1 register move.w wMyWord,d1 ; Load wMyWord to D1 add.l lMyLong,d1 ; Add longs (all 4 bytes involved) subq.w #1,d1 ; Decrement lower 2 bytes of D1 lea lMyResult,a0 ; Pointer to lMyResult long variable moov.l d1,(a0) ; Store result in lMyResult stop #$2700 ; Terminate program (simpler version) end Start ; Start execution at label "Start"

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.

Page 7: Lab Manual - EEE3231 - Wix.com

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 suite’s 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.

Page 8: Lab Manual - EEE3231 - Wix.com

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 Simulator’s 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: *--------------------------------------------------------------------------------------- * Program Number: EEE3231 Experiment 2 * Description : Introduction to Advanced Debug Features (Bubble Sort) * Written by : <Your name here> * Date : <Today's date here> *--------------------------------------------------------------------------------------- * Constant Definitions NUMVALS equ 16 ; Number of values to be sorted INITCNT equ NUMVALS-2 ; Initial value of countdown * Data Definitions org $1000 ; Starting address vubSort dc.b 254,52,15,202,9,171,37,186,63,190,86,141,186,8,141,1 ; Unsigned byte vector to be sorted * Program Code BubSort move.w #INITCNT,d0 ; Sweep Loop countdown SweepLp lea vubSort,a0 ; Running pointer: beginning of vector move.w d0,d1 ; Swap Loop countdown SwapLp move.b (a0)+,d2 ; Fetch element & move pointer cmp.b (a0),d2 ; Compare elements bls NoSwap ; Preceding <= current: no swap! move.b (a0),-1(a0) ; Bump current element 1 position down move.b d2,(a0) ; Preceding elt. to current position NoSwap dbf d1,SwapLp ; Next Swap Loop iteration dbf d0,SweepLp ; Next Sweep Loop iteration stop #$2700 ; Terminate program (simpler version) end BubSort ; Start execution at label "BubSort"

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.

Page 9: Lab Manual - EEE3231 - Wix.com

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 array’s 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 n–1 swaps, the second n–2 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

nni

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 algorithm’s 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 algorithm’s 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(n·log 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 “bls 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

Page 10: Lab Manual - EEE3231 - Wix.com

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 Simulator’s 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.

Page 11: Lab Manual - EEE3231 - Wix.com

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 processor’s 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:

*--------------------------------------------------------------------------------------- * Program Number: EEE3231 Experiment 3 * Description : Understanding the Addressing Modes * Written by : <Your name here> * Date : <Today's date here> *--------------------------------------------------------------------------------------- * Data Definitions org $1000 dc.b 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 * Program Code Start 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) stop #$2700 end Start

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:

Page 12: Lab Manual - EEE3231 - Wix.com

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 operand’s 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 operand’s data type is different from what would be expected from the instruction’s 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 debugger’s 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 operand’s participating bytes are aligned to the right. o a memory-stored operand’s 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 operation’s 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)

Page 13: Lab Manual - EEE3231 - Wix.com

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 Simulator’s 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 Simulator’s 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.

Page 14: Lab Manual - EEE3231 - Wix.com

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.

Everything should be made as simple as possible, but not simpler. (Albert Einstein)

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.W–1

Dn.W = –1?N

Y

Cond. true?

Page 15: Lab Manual - EEE3231 - Wix.com

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.

Page 16: Lab Manual - EEE3231 - Wix.com

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 68000’s 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!)

xghy

zxg

zyzxf

⋅−⋅=

⋅+=

⋅⋅−⋅

=

)43(

20010

1003

The program prompts the user for the input variables with the message “Please enter x:”, etc., and begins the calculations. As soon as a formula’s 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 68000’s 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 quotient’s 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 &

Page 17: Lab Manual - EEE3231 - Wix.com

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 term’s actual data type, in compliance with the notation used in Experiment 3 to describe an instruction operand’s 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 shouldn’t! From the previous discussion, the following can be said: • The actual data type of a variable is longword, due to the Simulator’s integer input function call. • The desired final data type of an entire expression is longword, imposed by the Simulator’s

integer output function call. • The desired data type of a multiplication’s two operands is word, and the actual data type of the

product is longword. • The desired data type of a division’s 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 Simulator’s 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 expression’s desired data type is longword, imposed by the EASy68K Simulator’s integer output function call.) From all of the above it is now clear that if an expression’s 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 operator’s own parentheses can be omitted.)

Implementation Comments The completion of this experiment requires the use of the simulator software’s 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 operation’s 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 EASy68K’s 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…)

Page 18: Lab Manual - EEE3231 - Wix.com

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 don’t 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.

Page 19: Lab Manual - EEE3231 - Wix.com

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 experiment’s 68000 assembly program will again calculate the following signed integer formulas.

xghy

zxg

zyzxf

⋅−⋅=

⋅+=

⋅⋅−⋅

=

)43(

20010

1003

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 register’s 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].

Page 20: Lab Manual - EEE3231 - Wix.com

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 68000’s 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 implementor’s 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 needn’t 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 phenomenon’s 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 simulator’s 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 Simulator’s 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 SIM68K’s “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.

Page 21: Lab Manual - EEE3231 - Wix.com

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 table’s 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.

Page 22: Lab Manual - EEE3231 - Wix.com

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 user’s request has been denied. (In a situation like this, a real-life system would also suspend the user’s 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 experiment’s 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.

Page 23: Lab Manual - EEE3231 - Wix.com

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.

Page 24: Lab Manual - EEE3231 - Wix.com

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 experiment’s Prelab will require matrix calculations to be completed and demonstrated to your lab instructor; begin your preparation on time.

Page 25: Lab Manual - EEE3231 - Wix.com

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 3×3 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 “A–B =”. 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:

=

=

12345678910

111213141516171819202122232425

25242322212019181716151413121110987654321

BA

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 m×n matrices:

)1,1( njmibacBAC ijijij ≤≤≤≤±=⇒±=

For a square matrix, m and n are equal.

Page 26: Lab Manual - EEE3231 - Wix.com

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 “printf("%*ld", 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 10×10; 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 element’s 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,50000,60000,70000,80

000,40000,30000,20000,10

BA

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.

Page 27: Lab Manual - EEE3231 - Wix.com

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 10×10. 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

njmibacBACp

kkjikij ≤≤≤≤⋅=⇒⋅= ∑

=

where matrices A, B and C are of size m×p, p×n and m×n 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 68000’s 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.)

Page 28: Lab Manual - EEE3231 - Wix.com

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:

−−−−

=

=

113011101

112121111

BA

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.

Page 29: Lab Manual - EEE3231 - Wix.com

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 suite’s 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 gadget’s 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 (ISR’s) Real-time embedded systems utilize the processing unit’s 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 designer’s 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

Page 30: Lab Manual - EEE3231 - Wix.com

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 system’s 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 68000’s 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 computer’s 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 68000’s exception vectors. On the other hand, the variables and the stack are placed in a Random Access Memory (RAM). In this simple problem, the 68000’s 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 ROM’s contents are the Boolean function’s truth table. The same sort of data in a computer program (in this case an embedded system’s 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 sensor’s output is a binary value, therefore no decimal-to-binary conversion on the front-end of the program.)

Page 31: Lab Manual - EEE3231 - Wix.com

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 sensor’s 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 Simulator’s 7-segment display is simulated as a byte peripheral beginning at default address $E00000, which represents the display’s leftmost digit. Since the 68000’s 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 “Windows XP Default.wav” for the warning click and “Windows XP Hardware Fail.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 “Windows XP Balloon.wav”. At the time of this writing, these files are located in the “C:\Windows\Media” 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 device’s 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

Page 32: Lab Manual - EEE3231 - Wix.com

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.

Page 33: Lab Manual - EEE3231 - Wix.com

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(k–1) + f(k–2) 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 13th 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:

[ ]kk

kk

kf ϕ−Φ=

−−

+=

51

251

251

51)(

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 Φ (named such to honor Fibonacci) evaluates to 1.6180339887…, and is the famous and infamous Golden Section itself. The value of ϕ is –0. 6180339887…, from which it also follows that Φ+ϕ = 1 (just some food for thought). Amazed enough? Great; then let’s move on from Theory to Practice!

Page 34: Lab Manual - EEE3231 - Wix.com

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: long Fib(long k) /* k: Function parameter */ { if (k<=1) return k; /* <<< Breakpoint here for Procedure #3 */ else return Fib(k-1)+Fib(k-2); /* THE TWO RECURSIVE 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 subroutine’s parameter has to be passed through the stack. The arithmetic must be done over longwords, so the 68000’s 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 “LINK 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 subroutine’s 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:

=−⋅

=

10

)0()1(0111

)( fff kk

The Fibonacci Numbers are provided by the f1(k) element. The gist of this idea is that instead of unleashing an entire new chain of recursion for each f(k–2) [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

Page 35: Lab Manual - EEE3231 - Wix.com

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 Simulator’s 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 Simulator’s 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.

Page 36: Lab Manual - EEE3231 - Wix.com

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: /*------------------------------------------------------------------------------------*/ /* Program Number: EEE3231 Experiment 12 */ /* Description : Assembly Implementation of a C Program (Insertion Sort) - C source */ /* Written by : Peter Csaszar */ /*------------------------------------------------------------------------------------*/ /* This C program sorts the contents of an integer array in ascending order using the */ /* Insertion Sort algorithm. This is the code to be transcribed into 68000 assembly. */ #include <stdio.h> #define ARRLEN 10 void main() { int viSortArray[] = { 24, 43, 107, -333, 24, 6, 7, 514, 0, -21 }; int i, j, iCurrNum; int *piCurrPtr, *piRunPtr, *piSrcPtr, *piDestPtr; printf("EE3231 Experiment 12: Insertion Sort\n\n"); printf("Written by Peter Csaszar\n\n\n"); /* Put YOUR name in the transcribed code */ piCurrPtr = viSortArray; /* Start sorting from the first element */ for (i=ARRLEN-1 ; i>-1 ; i--) { /* Maul through the array */ iCurrNum = *piCurrPtr; /* Fetch current number awaiting relocation */ piRunPtr = viSortArray; /* Find new location from the first element */ do /* Find current number's new location */ ; /* Nothing else to be done within this loop */ while (iCurrNum>*piRunPtr++); /* Current number's new location found! */ piSrcPtr = piCurrPtr; /* Prepare source for relocation procedure */ piDestPtr = piCurrPtr; /* Prepare dest. for relocation procedure */ piDestPtr++; /* Destination position: right-side neighbor */ while (piSrcPtr>=piRunPtr) /* Bump affected numbers one position right */ *--piDestPtr = *--piSrcPtr; /* Copy neighbors; MUST decrease addresses */ *piSrcPtr = iCurrNum; /* Insert number into its new position */ piRunPtr = viSortArray; /* Print the array from the first element */ for (j=ARRLEN-1 ; j>-1 ; j--) /* Sweep through the array */ printf("%6d",*piRunPtr++); /* Print array element */ printf("\n"); /* Print a newline */ piCurrPtr++; /* Move on to the next number to be relocated */ } printf("\nOperation complete\n\n"); }

Observe this C code carefully, and generate its equivalent written in 68000 assembly language.

Page 37: Lab Manual - EEE3231 - Wix.com

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 machine’s 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 pointer’s value within the same operation. • Use the Simulator’s different text I/O function calls to implement all “printf” statements.

CAVEAT! Contrary to the last bullet item above, the 68000 has no addressing mode support for operations where a pointer’s 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 68000’s special addressing modes in these scenarios as well, but with a little trick. For example, by replacing the line “piDestPtr++;” by “!!*piDestPtr++;” in the C program, we get a logic test of the object pointed to by piDestPtr, 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

Page 38: Lab Manual - EEE3231 - Wix.com

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 pointer’s 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! ☺