Top Banner

of 38

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 5/21/2018 Lab+Manual+-+EEE3231

    1/38

    Lab Manualfor

    Microprocessors Lab (EEE3231)

    Peter Csaszar

    Department of Electrical and Computer EngineeringLawrence Technological University

    All Rights Reserved

    Version 1.0.0

  • 5/21/2018 Lab+Manual+-+EEE3231

    2/38

    EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)

    Peter Csaszar Lawrence Technological University, ECE Department 2

    Table of Contents

    Preface................................................................................................................................. 3Lab Report Content Requirements...................................................................................... 4

    Experiment 1:Introduction to the Assembly Program Development Procedure.............. 6Experiment 2:Introduction to Advanced Debug Features (Bubble Sort)......................... 8Experiment 3:Understanding the Addressing Modes .................................................... 11Experiment 4:Developing a Simple 68000 Assembly Code (Block Copy)................... 14Experiment 5:68000 Integer Arithmetic ........................................................................ 16Experiment 6:68000 Integer Arithmetic with Error Detection ...................................... 19Experiment 7:String Manipulation & Hierarchical Design ........................................... 22Experiment 8:Matrix Arithmetic.................................................................................... 25Experiment 9:Matrix Multiplication .............................................................................. 27Experiment 10:Embedded System Firmware Design .................................................... 29Experiment 11:Implementation of a Recursive Algorithm (Fibonacci) ........................ 33

    Experiment 12:Assembly Implementation of a C Program (Insertion Sort).................. 36

  • 5/21/2018 Lab+Manual+-+EEE3231

    3/38

    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 thedevelopment and ongoing maintenance of the EASy68K suite, a truly remarkable software toolkitfor the 68000 microprocessor. Professor Kelly happily received all bug reports and (occasionallyfrivolous) suggestions from the author, and integrated virtually all feedback into EASy68K withlightning speed. Without Professor Kellys efforts, this lab manual would not have been possible.

    ! Dr. Michael Cloud (Lawrence Technological University, Southfield, Michigan) for his devotedefforts to proofread each experiment write-up, which not only polished this lab manual, but also

    the authors own English language skills.! Dr. Hassan Hassan and Dr. Birham Mirshab (Lawrence Technological University, Southfield,

    Michigan) for the select experiments in the previous lab manual that served as inspiration to someof this lab manuals experiments.

    References

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

    1. Motorola, Inc.: M68000 8-/16-/32-bit Microprocessors Users Manual. (Reprinted by multiplepublishers, e.g.Prentice Hall, 1989;Barnes & Noble, 1991.)

    2. James L. Antonakos:The 68000 Microprocessor. Fifth Edition.Pearson Prentice Hall, 2004.3. Peter Csaszar: EASy68K Beginners Guide. (Microprocessors Lab supplementary material.) Lawrence

    Technological University, 2006.

    4. Peter Csaszar: 68000 Quick Start Guide. (Microprocessors Lab supplementary material.) LawrenceTechnological University, 2006.

    5. Charles Kelly: EASy68K Assembly Language Tool Online Help. (Edit68KHelp > Help menu itemor Sim68KHelp > Sim68K Help menu item.)

  • 5/21/2018 Lab+Manual+-+EEE3231

    4/38

    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 formattingrequirements (typesetting guidelines, format of the cover page, stapling vs. clipping, etc.) are typicallycovered in the lab instructors syllabi, and are easy to assess as well as enforce. However, the semanticstend 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, beable 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 issimilar to the Objective section of the lab manuals experiments; however, your introduction should onlyfocus 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 typicallymean the EASy68K Assembly Language Toolkit. However, if for certain calculations you used an Excelspreadsheet, for example, you will need to list this software tool as well. (This situation will occur in someof the upcoming experiments.) If an experiment involves hardware prototyping, you will need to provide aParts List in this section as well. (It will not be typical to this labs experiments, but remember it as ageneral guideline.) However, please write the truth, and only the truth. For example, don't list MS Excel foran experiment, where you did not use MS Excel at all! Imagine the utter confusion of the person readingyour 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, theformula for matrix multiplication.)

    ! Program design, algorithm- and/or flowcharts. (Only include a flowchart if it is meaningful, andhelps to understand the gist of your algorithm. Overly terse or ridiculously detailed flowcharts arenot 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 softwaredevelopment, or observations you made and find it helpful for other people to be aware of. (Anexcellent example is bug reports or feature suggestions for the EASy68K software.)

    4. Conclusions

    In this section you would include:

    ! The discussion of your results.

  • 5/21/2018 Lab+Manual+-+EEE3231

    5/38

    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 thereasons 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 sourcefile directly from the EASy68K Editor/Assembler (Edit68K).

    ! Log file (*.txt): This is the file generated by the EASy68K Simulator (Sim68K), containing theregister/memory dump of a single-step execution (Execution Log) or all text output sent to theconsole screen (Output Log), depending on the requirements of the experiment. The EASy68Kautomatically generates the default filenames from the filename of the currently simulatedprogram; however, you have the right to use a filename of your own choice. In either case, you arestrongly recommended to keep the .txt extension; this will make it easier to open the file inNotepad, from where you can print it out. (Another option is to pull the file into the EASy68Keditor, and print it out from there. In this case, make sure to select Any File from the pull-downlist 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 theSimulator for source-level debugging. You need to include this file in your lab report as a proof ofvalidity for your source code; also, it may help another person to diagnose the cause of bugs inyour software. Double-clicking this file will open it in the EASy68Ks editor, from where you canprint it out. (The author of this handout has suggested the EASy68K developers to implement thepossibility 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 andconfidence. Furthermore, you can always consult your lab instructor if you need specific suggestions.

  • 5/21/2018 Lab+Manual+-+EEE3231

    6/38

    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 developmentprocess. Through a simple example provided below, students will learn how to use edit, assemble andsimulate 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 : * Date :

  • 5/21/2018 Lab+Manual+-+EEE3231

    7/38

    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 theProblemsection. (Use the Tabkey to separate the fields.)

    2. Try to assemble the program. It contains a bug (more exactly a typo), which is so trivial that evenwith no prior experience you should be able to correct it. Fix and re-assemble the program until noerrors orwarnings are left.

    3. Hit the Execute button in the dialog box that pops up after the successful assembly. This willinvoke Sim68K, the EASy68K suites simulator/debugger utility. (Note: Even though simulationis enabled if the program only contains warnings, it is highly recommended that you get rid of allwarnings 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 andMemory in the Execution Log Type group; the range of logged memory shall be 10 bytesfrom 1000. (Remember, these values are in hexadecimal!) Leave the output log disabled in theOutput 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 beingappended to this logfile.)

    7. Exit all programs. (Make sure the assembly code you typed into Edit68K is saved!)

    Requirements for This Lab

    ! PrelabDownload the latest version of the EASy68K assembly language tool from the Web. Install thepackage and configure the utilities of the suite.

    ! Lab ReportWrite your report according to the usual guidelines. The Descriptionsection must include a briefexplanation of your experimentation with the EASy68K, including any special circumstances.Attach a hardcopy of the source code, the generated execution logand the list fileto your report.

    Next Lab Alert

    The next experiment will continue focusing on the features of the EASy68K development suite; make sureyou fully understand the material covered in this lab.

  • 5/21/2018 Lab+Manual+-+EEE3231

    8/38

    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 specialemphasis on the Simulators graphic debug facilities. This time the program under scrutiny is the 68000assembly 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 : * Date :

  • 5/21/2018 Lab+Manual+-+EEE3231

    9/38

    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 themovement 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; thisconditional swap (swapfor short) is followed by the swap of the second and third elements, and so on, untilthe next to last and the last elements are processed. As a result, at the end of the sweep the largest elementin the array will land at the arrays last position.

    Subsequent sweeps make the larger elements bubble up towards the right side of the array, until theirappropriate positions are reached. If the number of elements is n, the first sweep executes n1swaps, thesecond n2 swaps, and so on; the last sweep only consists of a single swap, taking care of the first andsecond 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 algorithms execution speed forindefinitely many elements. This is also referred to as the complexityof the algorithm, and is expressedusing the O-notation. The Bubble Sort algorithms complexity is O(n), thank to the presence of the ntermin the above polynomial expression. The best sorting algorithms only have a complexity of O(nlog n).

    Implementation Comments

    Sorting algorithms work for any object that defines a relational semantics, i.e., the elements can becompared to each other in terms of being greater-than, less-than or equal. (For example, real numbers canbe 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 memorydump that uses hexadecimal values will be easier to interpret. The data type (byte in this case) is coded intothe data transfer/comparison instructions, and theDCassembler directive defining the vubSortarray. Whatmakes this implementation sort unsigned values in increasing order is the choice of BLS as conditional

    branching instruction in line bl s NoSwap.

    Procedure

    Complete the following tasks.

    1. Enter the program provided in the Problemsection. Assemble it, and hit the Execute button inthe assembly completion dialog box to invoke the Simulator.

    2. Turn on execution logging by selecting Instructions, Registers and Memory in the ExecutionLog Type group; the range of logged memory shall be 10 bytes from address 1000 (all valuesare 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 locationto capture thememory 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 fora register/memory dump to be placed in the logfile. Use the Run toolbar button (F9 hotkey) toskip between breakpoint stops.

    4. Disable execution logging. (This will prevent the log of subsequent executions from beingappended 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-F3hotkey), as opposed to the Reset Program toolbar button (Ctrl-F2 hotkey). Both commands reset the

  • 5/21/2018 Lab+Manual+-+EEE3231

    10/38

    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 theDCandDCBassembler directives. (Reset Program would only make your program re-sort an already sorted array!)

    Requirements for This Lab

    ! PrelabReview the EASy68K Simulators debug features, including the placement of breakpoints.

    ! Lab ReportWrite your report according to the usual guidelines. The Descriptionsection must include a briefexplanation of your experimentation with the EASy68K, including any special circumstances.Attach a hardcopy of the source code, the generated execution logand the list fileto your report.

    Next Lab Alert

    The next experiment will require a considerable amount of review, and the clear understanding of therequired procedure. Begin your preparation on time, and come to the lab fully prepared.

  • 5/21/2018 Lab+Manual+-+EEE3231

    11/38

    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 68000instructions using different addressing modes, with details beyond typical classroom coverage. Supportedaddressing modes and addressing mode combinations are a key factor in determining a processors powerin 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 : * Date :

  • 5/21/2018 Lab+Manual+-+EEE3231

    12/38

    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 rathertrivial, 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 operandsaddressing mode is a variant of Address Register Indirect (ARI), you are recommended torely 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 howeverthat 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; inorder to refer to a memory position, the value must be put between square brackets!

    Caveat!In some cases, an operands data type is different from what would be expected from theinstructions data type designator.(One example is the source operand of MOVEQ, and anotherone is related to a certain addressing mode being a destination. The example code containsinstances 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 executionrespectively, indicated as a 4-byte hexadecimal value(without the $ designator, but separatingthe bytes with spaces to make it easier to read the values), much like the format of a debuggersregister- or memory dump. (Note: With 4 bytes we are prepared for the worst, i.e., that theoperands are longwords.) Use the EASy68K Simulator to determine the contents of the threecolumns. With bold face, highlight the section of the 4 bytes that actually participates in the givenoperation. Due to the nature of how the 68000 implements the addressing modes,

    o a registeroperands participating bytes are aligned to the right.o a memory-storedoperands participating bytes are aligned to the left.

    For a constantoperand, the question does not apply; only show as many bytes as contained in thedata type, in which the constant is being used [typically the operations data type, but not always].

    Examples: FF FF FF 01: Byte in register; F9 F908 09: Word in memory; FF FF 00 03:Longword [wherever]; FE: Byte constant; 00 00 10 00: Longword constant.

    Operand ValueInstruction

    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 0304 05 06 00 00 00 03add. 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 F908 09

    move. l d2, - ( a0)

  • 5/21/2018 Lab+Manual+-+EEE3231

    13/38

    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 Problemsection. Assemble it, and hit the Execute button inthe assembly completion dialog box to invoke the Simulator.

    2. Set up the Simulators Execution Logging facility to log the instructions, registers and the 16-bytememory area beginning at address $1000.

    3. Execute the program step-by-step, and fill in the entire Table 1. (Forgot to take note of thecontents of the destination before the instruction executed? It is an excellent opportunity to call theExecution Log for help!) Before executing each instruction, try to calculate the value in the lastcolumn, and then compare it with the Simulators results. If you observe discrepancies, it is a clearindication 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 forrepeated executions. This will not only reset all data- and address registers to 0, but will also restore the

    memory area defined by theDCassembler directive.

    Requirements for This Lab

    ! PrelabReview the 68000 addressing modes and data types. Study Table 1 very carefully, and through theexamples of the pre-filled fields, try to understand the logic and purpose of the table. Prepareyourself to ask questions during the lab session, so that you will be able to complete theexperiment successfully.

    ! Lab ReportComplete the tasks laid out in the Procedure section, and write your report according to the usualguidelines. TheDescriptionsection 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 ahardcopy of the source code, the generated execution logand the list fileto your report.

    Next Lab Alert

    The next experiment will require the understanding of certain microprocessor instructions; come to the labwell-prepared.

  • 5/21/2018 Lab+Manual+-+EEE3231

    14/38

    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 makeslight modifications to it. The problem specification is given as a verbal description; the key deliverable is afully 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!) ofthe quotation below (essentially,the basic mantra of this entire lab) from memory address $1000 to $1080.

    Ever ythi ng shoul d be made as si mpl e as possi bl e, but not si mpl er. ( Al bert Ei nstei n)

    The code must begin at address $1100, and has to be prepared in fourvariants:

    1. Copy the characters byte-by-byte; use theBcc instruction to implement the loop.2. Copy the characters word-by-word; still use theBccinstruction to implement the loop.3. Copy the characters longword-by-longword; still use theBccinstruction to implement the loop.4. Copy the characters longword-by-longword; use theDBccinstruction to implement the loop.

    Hints: Utilize the DC.B assembler directive to provide the Einstein quotation as the sourcecharacter block at address $1000; furthermore, use the DCB.B ,directive toblank thedestination block by placing 64 zeros at address $1080, so that when you reload the program, thedestination block will be clear again. Precede the block definitions and your assembly program code byORGdirectives, in order to set the Location Counter to the appropriate positions.

    Theoretical Comments

    Recall the difference between the Bccand 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 anecessary condition for the jump to ], which also maintains a loop counter by decrementing thechosen data register Dn.W, and comparing its value against 1.

    Bcc DBcc

    Previous

    Cond. true?

    Next

    Y

    N

    Previous

    Next

    Y

    N

    Dn.W = Dn.W1

    Dn.W = 1?N

    Y

    Cond. true?

  • 5/21/2018 Lab+Manual+-+EEE3231

    15/38

    EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)

    Peter Csaszar Lawrence Technological University, ECE Department 15

    When using theDBccinstruction in this problem, it is important to figure out how to disable its primarybranching condition (so that it only pays attention to the counter being consumed), and to determine theinitial 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 makethe memory transfer operation as simple as possible. (Hint: Remember, the MOVE instruction is theMother of All Orthogonality.)

    Procedure

    Write the code for all four variantsof the program, and complete the following list of tasks:

    1. Fill in the table below, and discuss your findingsbriefly, 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 thecode 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 theblock 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 memoryscenarios, and that the memory blocks are clearly shown. Points will be deducted for very longand/or non-demonstrative logs!

    Note:Use the Reload Program toolbar button (Ctrl-F3 hotkey) as opposed to the Reset Program forrepeated executions, in order to restore the memory areas defined by theDCBassembler directives.

    Requirements for This Lab

    ! PrelabRefresh your understanding about the conditional branching instructions.

    ! Lab DemoYou must demonstrate your assembly programs to the lab instructor, who will sign off on theexperiment. The ground rules regarding the demonstration are explained in the lab syllabus.

    ! Lab ReportWrite your report according to the usual guidelines. The Description section must include theresults of all required tasks described in the Proceduresection of the experiment. To your report,attach a hardcopy of the source code of all three variants, the generated execution log runningone 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 toyour lab instructor; begin your preparation on time, and come to the lab fully prepared.

  • 5/21/2018 Lab+Manual+-+EEE3231

    16/38

    EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)

    Peter Csaszar Lawrence Technological University, ECE Department 16

    Experiment 5

    68000 Integer Arithmetic

    Objectives

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

    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!)

    xgh

    y

    zx

    g

    zyzx

    f

    '%'&

    '(&

    ''%'

    &

    )43(

    20010

    1003

    The program prompts the user for the input variables with the message Please enter x:, etc., and beginsthe calculations. As soon as a formulas calculation is finished, its result is printed on the screen, e.g.Result: f= for variable f, followed by the same procedure for g and h. After completion, theprogram 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 suiteof 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 andrequires an understanding of the 68000s data types and arithmetic instructions. The participants and theirdata 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 upperword of the quotients register is tainted with the value of the 16-bit remainder!)

    ! Addition & subtraction: All data types are supported. For the largest range of possible inputvalues, this experiment requires that all additions and subtractions (including in the expression forvariable h)work with longworddata!

    For further analysis, the formulas must be modified a bit; the procedure will be demonstrated using theexpression for variable A. First, the formula must be fully parenthesized, i.e., each operator and itsoperands 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 decoratedwith data type designators. These are single uppercase characters, W & L representing word &

  • 5/21/2018 Lab+Manual+-+EEE3231

    17/38

    EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)

    Peter Csaszar Lawrence Technological University, ECE Department 17

    longword respectively; ? stands for uncommitted. The designator suffix indicates a terms actual datatype, in compliance with the notation used in Experiment 3 to describe an instruction operands data type.This time, however, we also introduce the designatorprefixthat indicates the desireddata 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.?].WL.[ W.( W.100.?* W.y.L).L* W.z.L].L}.L

    Look totally confusing, even crazy? It shouldnt! From the previous discussion, the following can be said:! The actualdata type of a variable is longword, due to the Simulators integer input function call.

    ! The desired final data type of an entire expression is longword, imposed by the Simulatorsinteger output function call.

    ! The desired data type of a multiplications two operands is word, and the actualdata type of theproduct is longword.

    ! The desired data type of a divisions dividend and divisor are longword and word respectively,and the actualdata type of the quotient [and also the remainder] is word.

    ! The actualdata type of a constant is uncommitted, i.e., it is free to assume the desired data typeimposed by its context. (However, if its value is out of range, the assembler will give an error.)

    Take variableyas an example: it is provided as a longword by the Simulators integer input function call,but, being the multiplier in a multiplication, it is expected to be a word. The result of multiplication (100*y)

    is a longword, but appearing as the multiplicand in a subsequent multiplication, its value is also expected tobe a word. (Remember, the final expressions desired data type is longword, imposed by the EASy68KSimulators integer output function call.)

    From all of the above it is now clear that if an expressions prefix and suffix data type designators aredifferent, we have a problem. What is required is an operation called data type conversion, which is alsoreferred to as castingin elegant C programming circles. Rewriting the above formula with the use of the() 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 challengeleft is to figure out how to implement the word()down-casting, and the long()up-casting operations in68000 assembly. (Notice that the casting operators only need to add parentheses around single variables; ifthey precede a parenthesized sub-expression, the operators own parentheses can be omitted.)

    Implementation Comments

    The completion of this experiment requires the use of the simulator softwares text I/O function calls. In theEASy68K Simulator, all function calls are activated through a TRAP #15 instruction in the runningassembly program. The desired operations so-called task codemust be placed into register D0.L before thefunction call. The operations needed in this experiment are:

    ! Task #3: Display the contents of D1.L as a signed decimal number.

    ! Task #4: Read a signed decimal number from the keyboard into D1.L.

    ! Task #5: Read a single character from the keyboard into D1.B.

    ! Task #13/#14: Display the 0-terminated string at (A1) [max 255 characters] with/without Newline.

    ! Task #17/#18: Combination of Tasks #14 and #3/#4. (Great for prompting and displaying results.)The detailed use of the function calls is shown in EASy68Ks online Help, under Simulator I/O > Text.

    Note:Some of these calls are compatible with services provided by other 68000 simulators, but some arenot; 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 usingthem for any other purpose within the program (except for short-term roles, or for results ready to be usedand 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 datatemporarily. (Now the reason behind 32-bit, rather than 24-bit address registers suddenly becomes clear)

  • 5/21/2018 Lab+Manual+-+EEE3231

    18/38

    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 EASy68KSimulator as you are executing all four setsof calculations shown in the table. The output log willcontain 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 anunlimited 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 notmatch 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 TRUNCfunction.

    Requirements for This Lab

    ! Prelab

    You must answer all 5 questions listed in the Procedure section. However, only the ExpectedResults columns of the table need to be filled in; the actual results will be provided by yourcompleted assembly program, and shown in your lab report.

    ! Lab DemoYou must demonstrate your assembly program to the lab instructor, who will sign off on theexperiment. The ground rules regarding the demonstration are explained in the lab syllabus.

    ! Lab ReportWrite your report according to the usual guidelines. The Description section must include theresults of all required tasks described in the Procedure section of the experiment. Attach a

    hardcopy of the source code, the generated output logand the list fileto your lab report.Note: From this lab on, including this very lab, you will no longer need the execution logshowing the register and memory contents, therefore you dont need to generate and submit it; youwill onlybe working with the output loginstead.

    Next Lab Alert

    The next experiment will also require a substantial amount of Prelab work; begin your preparation on time.

  • 5/21/2018 Lab+Manual+-+EEE3231

    19/38

    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 overflowand division-by-zero occurrences. The experiment also serves as an introduction to exception handling.

    Required Resources

    EASy68K 68000 Assembly Language Programming Tool

    Problem

    This experiments 68000 assembly program will again calculate the followingsigned integerformulas.

    xgh

    y

    zx

    g

    zyzx

    f

    '%'&

    '(&

    ''%'

    &

    )43(

    20010

    1003

    As in the previous experiment, the program prompts the user for the input variables with the messagePlease enter x:, etc., and prints the results with the message Result: f=, etc. This time, however,your program must also look vigilantly for different adverse conditionsduring the calculations, and printone 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 theprogram says good-bye and terminates; otherwise the calculations will be run on a new suite of input valuesprovided by the user.

    Theoretical Comments

    Three different situations may cause the 68000 assembly implementation of the above formulas to provideincorrect results:

    1. Operation overflow. This occurs when the result of an operation no longer fits into the data typesupported by the given operation. Aside from multiplication, all arithmetic operations in the aboveformulas are prone to operation overflow. When the 68000 detects a signed overflow, it asserts theV (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 willbe set, but the destination data registers contents will remain unchanged.

    2. Division-by-zero. This condition is caused by a division, in which the divisor is zero. Consideringthe 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 beundefined.

    3. Conversion overflow. This may occur during conversion between data types (obviously only whenthe number of bits in the data type representation is reduced). Unfortunately, the 68000 providesno facility to detect this condition; it must be implemented by the programmer [i.e., you].

  • 5/21/2018 Lab+Manual+-+EEE3231

    20/38

    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 aslightly different philosophy.

    1. Arithmetic operations. Unlike the 68000s multiplication and division instructions, theseoperations in C do not jump between data types; all operands and the result are within the samedata type. Nor does C provide overflow notification; it merely proceeds with incorrect results.However, the operations do support multiple data types; it is the implementors responsibility to

    choose the data type suitable for a given problem.2. Data type conversion.Since the operations in C stay within the same data type, there is hardly a

    need for down-casting in a C program. On the rare occasion when it is required, one should usethe appropriate casting operator explicitly. If the C compiler notices an implicit down-casting, itissues 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 correspondingwarning messages; the most practical way to accomplish this task is to create three special subroutines, theexception handlers.

    1. Operation overflow. There is a handy facility in the 68000 assembly, specifically designed foroverflow monitoring: the TRAPV instruction. If the V flag is set when the TRAPV instruction isencountered, it will cause an exception with vector #7. (This is not to be confused with theTRAP #7 instruction, which generates an exception with vector #39!) If the V flag was not set,execution continues normally with the next instruction.

    2. Division by zero.In this case, the exception handler neednt be invoked manually; the offendingoperation itself will cause an exception with vector #5.

    3. Conversion overflow. This condition could be managed using a normal subroutine. However,since it will be invoked frequently (and because of the phenomenons similarity to operationoverflow), this experiment requires that it alsobe written as an exception handler, invoked by auser TRAP #0 instruction [vector #32]. (As a matter of fact, any TRAP would work, other thanTRAP #15, which is devoted to the EASy68K simulators API.) This routine should check first if a

    conversion overflow is about to occur, and print the warning only if the diagnosis is positive.Pitfall warning!When implementing the algorithm to detect conversion overflow, keep in mindthat you are dealing with signednumbers! (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. Loperation; based onthis insight, you can conceive a very simple and elegant solution.)

    Helpful tip:Do not forget to reserve registers D0 and D1 for the EASy68K Simulators TRAP #15calls.Also, you will need to dedicate a data register as the input parameter for your conversion overflowsubroutine. However, since this input parameter is also filled in on a call-by-call basis, much like D0 andD1 for the TRAP #15calls, 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 setup. 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 aboutanything complicated here; the [longword] value of the starting address of each exception handlermust 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 equallyspecial Return instruction!

    ! It isessential 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 enabledthrough the SIM68Ks Options > Enable Exceptions menu item. Also, use the Task #9function call instead of the STOPassembly instruction to terminate your program from now on.

  • 5/21/2018 Lab+Manual+-+EEE3231

    21/38

    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 programyou prepared for Experiment #5 such that it satisfies thenew requirements described in theProblemsection; 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 TRAPVand TRAP #0instructions must appear in the program.

    3. Explain how your conversion overflow detection algorithmworks.4. Create and fill in the table below; capture the entire sessionin 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 expectedresults. The tables new Error Condition(s) columns should show the cause of the discrepancies:denote operation overflow by O, division-by-zero by D and conversion overflow by C (onecharacter for each occurrence). Because of interdependencies, an expression without errors maystill give the wrong answer; conversely, a result may end up being correct despite an errorcondition. The only true statement is that if none of the expressions have any error, all results willbe correct. (With fancy mathematical terms, an error-free session is a sufficient condition for

    correct results, and therefore correct results are a necessary conditionfor 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 fromExperiment 5 (above the thick line).

    2. A table showing the expected values for f, gand h, using the values of the four newinputsuites(under the thick line of the above table).

    ! Lab DemoYou 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 ReportWrite your report according to the usual guidelines. The Description section must include theresults of all required tasks described in the Procedure section of the experiment. Attach ahardcopy of the source code, the generated output logand the list fileto your lab report.

    Next Lab Alert

    The next experiment will focus on string handling; review this material prior to coming to the lab.

  • 5/21/2018 Lab+Manual+-+EEE3231

    22/38

    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 andQuit. 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 passwordin the beginning of your program.) If the password is correct, the program displays the secret message; ifnot, the user is prompted to re-enter the password. After three unsuccessful attempts, a message is printedthat the users request has been denied. (In a situation like this, a real-life system would also suspend theusers access for an extended period of time; however, you can leave this nasty feature off from yourprogram in this experiment.)

    When Change password is selected, the user is again prompted for the [current] password. Theauthentication 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 passwordentry; 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, whenQuit is selected, the program says good-bye and terminates. (Obviously, this command does not requirepassword authentication.!)

    Theoretical Comments

    This experiments theoretical content focuses on the computer science concepts of proceduralprogrammingand top-down hierarchical design.

    Although this problem is fairly complex, it can be broken into simpler parts (in this case the individualcommands). These can then be further partitioned into simpler and simpler tasks. This consecutivepartitioning 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 examplethe entire procedure of user authentication, as well as the string manipulation primitives. Take advantage ofthis 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 theprogram, after which execution will resume at the instruction following the subroutine call.

  • 5/21/2018 Lab+Manual+-+EEE3231

    23/38

    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 multiplecontexts, you must pass different values (parameters) to the subroutine; also realize that somesubroutines 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 valuesin 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 calloffered by the EASy68K simulator:

    Task #2: Read a 0-terminated string from the keyboard and store it at (A1); return the numberof 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 theinput string is assigned to D1.W, but the string is also terminated by a 0-character. This is goodnews: 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 allocatedinput string buffer must be at least 81 bytes long, otherwise a malicious user would be able tolaunch a successfulBuffer Overrun attackagainst your program. Since password length is limited

    to 16 characters by the problem specification, it is sufficient to define all other password-relatedbuffers 17 bytes long. Warning! Make sure that even if a password is truncated, it is stillterminated 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, exactlythe way it is specified.

    i) Choose the Retrieve secret message command, but get rejected by providing three wrongpasswords. 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 wrongpasswords. Obviously, no password change should occur.

    iv) Choose Change password again, and this time provide the right password. Specify the newpassword, but make a mistake with the second entry; this should leave the passwordunchanged.

    v) Choose Change password and authenticate yourself again. Enter the new password andconfirm it successfully; the program should announce the password change.

    vi) Choose Retrieve secret message, and enter this new password; your program shouldrecognize 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 thispassword. (The confirmation string that works in this case depends on your exactimplementation.) The program should announce the password change.

    viii)Choose Retrieve secret message, and enter the first 16 characters of the password you justspecified; 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 sessionin an output log.

  • 5/21/2018 Lab+Manual+-+EEE3231

    24/38

    EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)

    Peter Csaszar Lawrence Technological University, ECE Department 24

    Requirements for This Lab

    ! PrelabRefresh your understanding about string handling.

    ! Lab DemoYou must demonstrate your assembly program to the lab instructor, who will sign off on theexperiment. The ground rules regarding the demonstration are explained in the lab syllabus.

    ! Lab ReportWrite your report according to the usual guidelines. The Description section must include theresults of all required tasks described in the Procedure section of the experiment. Attach ahardcopy of the source code, the generated output logand the list fileto your report.

    Next Lab Alert

    The next experiments Prelab will require matrix calculations to be completed and demonstrated to yourlab instructor; begin your preparation on time.

  • 5/21/2018 Lab+Manual+-+EEE3231

    25/38

    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 exampleof 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 ofsigned longwords; in the next experiment, you will add the multiplication functionality. Since the finalprogram 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 inyour 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 isprinted on the console. The same procedure is followed for matrix B. The matrices must be printed in aproperly tabulated format; the below example shows the printout for an arbitrary 33 matrix as matrixA:

    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, matrixBis subtracted from matrixA, and the result is printed after AB =.

    When Multiply is selected, the program for this experiment only prints Under Construction.

    After the completion of the above commands, the program returns to the main menu. However, whenQuit is selected, the program says goodbye and terminates.

    Important requirement:In order to make testing easier, your program must define the following defaults:

    ))))))

    *

    +

    ,,,,,,

    -

    .

    &

    ))))))

    *

    +

    ,,,,,,

    -

    .

    &

    12345

    678910

    1112131415

    1617181920

    2122232425

    2524232221

    2019181716

    1514131211

    109876

    54321

    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 mnmatrices:

    )1,1( njmibacBAC ijijij ////0&10&

    For a square matrix, mand nare equal.

  • 5/21/2018 Lab+Manual+-+EEE3231

    26/38

    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 ofyour program and minimize code repetition.

    2. EASy68K Function Call of the Day.In this program, you will take advantage of a specific text I/O

    function call offered by the EASy68K simulator:

    Task #20: Display the signed longword contents of D1.L in decimal, using D2.B fields.

    (Using a C-analogy, this can be represented as pr i nt f ( "%*l d", D2. B, D1. L); .)

    This particular function call will keep the columns of the matrices neatly right-aligned. Thelongest signed longword would occupy as many as 11 fields; in your implementation you areallowed 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 aslarge as 1010; allocate the necessary buffers accordingly. Furthermore, you will need to providethe default values for matricesAandB; one solution is to provide assembly-time definition usingthe appropriate assembler directives and the DS-overstrike trick (in which the buffer defined bythe 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 runningpointers. The input/output functions need to be aware of each elements exact position within thematrix for printout, therefore these operations must implement double nested loops. The same isrecommended for the addition and subtraction algorithms for symmetry reasons, although in theseparticular 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,60

    000,70000,80

    000,40000,30

    000,20000,10BA

    Requirements for This Lab

    ! PrelabYour Prelab Report must include the results of calculations described in theProceduresection.

    ! Lab DemoYou 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 ReportWrite your report according to the usual guidelines. The Description section must include theresults of all required tasks described in the Procedure section of the experiment. Attach ahardcopy of the source code, the generated output logand the list fileto your report.

    Next Lab Alert

    The next experiment will require more matrix calculations for the Prelab; begin your preparation on time.

  • 5/21/2018 Lab+Manual+-+EEE3231

    27/38

    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 ofadvanced 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 ofmatrix multiplication. Obviously, the two operands and the result remain square matrices of signedlongwords, with maximum size of 1010.

    The program must now respond to the Multiply command, upon which the two matrices are multiplied,and the result is printed after the caption A*B =.

    Theoretical Comments

    Recall the general formula for matrix multiplication:

    )1,1(1

    njmibacBACp

    k

    kjikij ////'&1'& $&

    where matricesA,Band Care of size mp, pnand mnrespectively. This experiment only deals withsquare 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 structureinherent to the matrix multiplication algorithm. (Two loops maintain running variables iandj; thethird loop implements summation over k.) In the code design phase, you must identify the tasks tobe carried out before, during and after each of the loops; plan carefully or your job will be muchmore difficult.

    Attention! Any solution that can only multiply matrices with a certain fixed size will not beaccepted(even for partial credit)!

    2. Multiplication with Implicit Downcasting. The 68000 Integer Arithmetic experiment clearlydemonstrated the pitfalls inherent in the 68000s multiplication and division instructions.

    Multiplication, for example, takes both of its arguments as word operands (even if thosearguments originated from operations with longword results); this behavior is called implicitdowncasting.

    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-endiansystem places the highest-order byte of multi-byte data at the lowest memory address, theoperation attempting implicit downcasting of such an argument will definitely work with anincorrect value. To avoid this problem, the pointer addressing the argument to be downcast mustbe adjusted accordingly before the operation takes place. (This inconvenience was probably themajor factor behind the eventual demise of the big-endian system.)

  • 5/21/2018 Lab+Manual+-+EEE3231

    28/38

    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; individualsolutions may differ in terms of efficiency, ease of implementation and mathematical elegance. Inassembly, the typical method for accessing elements in one- and multi-dimensional arrays appliesrunning pointers. This particular problem is no different; we highly recommend a solution thatmaintains the following five running pointers:

    i) Pointer to the beginning of the current row of matrixA

    ii) Pointer to the beginning of the current column ofBiii) Pointer to the current column [element] in the current row ofAiv) Pointer to the current row [element] in the current column ofBv) Pointer to the current element in C

    But these are only guidelines; feel free to use a different approach in your implementation if youwish so.

    Procedure

    Write the multiplication subroutine, integrate it into your existing program, and complete the followingtasks for your lab report.

    1. Complete the addition, subtraction and multiplication of the two default matrices.

    2. Repeat for the matrices below:

    )))

    *

    +

    ,,,

    -

    .

    %%

    %

    %

    &)))

    *

    +

    ,,,

    -

    .

    &

    113

    011

    101

    112

    121

    111

    BA

    Requirements for This Lab

    ! PrelabYour Prelab Report must include the 68000 assembly code you will test and debug during the lab,and the results of calculations described in theProceduresection.

    ! Lab DemoYou must demonstrate your assembly program to the lab instructor, who will sign off on theexperiment. The ground rules regarding the demonstration are explained in the lab syllabus.

    ! Lab ReportWrite your report according to the usual guidelines. The Description section must include theresults of all required tasks described in the Procedure section of the experiment. Attach ahardcopy of the source code, the generated output logand the list fileto your report.

    Next Lab Alert

    The next experiment will require the understanding of interrupt handling; come to the lab well-prepared.

  • 5/21/2018 Lab+Manual+-+EEE3231

    29/38

    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 theexample of a fictitious process-monitoring device, responsible for guarding the temperature of a chemicalcompound. The demonstration of the concepts takes full advantage of the features provided by theEASy68K suites hardware simulation facility.

    Required Resources

    EASy68K 68000 Assembly Language Programming Tool

    Problem

    Consider a water-based chemical solution that needs to be stored and transported safely. The compound isnot particularly sensitive, but it must be maintained in liquid form at all times. Your assignment is to designthe firmware of a temperature monitoring device attached to the storage tank. This device consists of atemperature 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 whennecessary). 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 operatingconditions. The gadgets Hardware Reset button resets the device after a critical temperature error.

    The device reads the sensor in one-second intervals, utters a ticking sound, and shows the temperature onthe 7-segment display as a leading-zero-suppressed decimal value (for example 75 F for 75 F). Eachtime the value is below the freezing point (32 F), or above the boiling point (212 F), a warning clicksounds and one more light turns on, indicating an increasing severity of warnings. Once the temperature isback to the normal range, all lights are cleared and the warning level is reset to zero. However, eightconsecutive out-of-range readings constitute a critical errorproducing 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 thesample was exposed to harsh conditions for an unacceptably long time and must be destroyed. If a criticalerror occurs, the device goes to afrozen state,i.e., it only responds to the Hardware Reset button. (For codesimplicity, 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 abovespecifications. The 7-segment display, the row of lights and the Hardware Reset button are readily availablein the EASy68K Hardware window, while the 8-bit temperature sensor data is simulated by the set of eighttoggle switches. The time base for the one-second sampling is provided by the Auto Interval option thatcan be associated with any interrupt, and its cycle time can be specified in milliseconds. Finally, the soundchip 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 areal-life microcontroller implementation.

    Interrupts and the Interrupt Service Routines (ISRs)

    Real-time embedded systems utilize the processing units interrupt facility to be in close correspondencewith 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 theembedded designers arsenal is the timer-driven interrupt.This occurs with a predetermined frequency, andits interrupt service routine (ISR) takes care of environment-related chores such as polling the input

  • 5/21/2018 Lab+Manual+-+EEE3231

    30/38

    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 thatcan generate this regular interrupt. The disadvantage of this method is that the systems reaction to externalstimuli is no longer real-time, but is determined by the interrupt cycle time. However, with this timeappropriately selected, the complexity of the software design is drastically reduced, leading to higherrobustness 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 areimplemented, they can all be serviced quickly enough. (The invocation of an ISR while another is runningis dangerous and should be avoided; the design of some microcontrollers even makes it virtuallyimpossible.) At the same time, the ISR must complete all of its essential tasks. For this reason, longer tasksshould be placed in the non-ISR code of the firmware, known as the background code.

    In this extremely simpleexample, the device must merely read and display the temperatures measured bythe 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 reducedto a simplespinning loop[i.e., a loop with an empty loop core] or an instruction equivalent to the68000s STOP.

    2. One can put everything in the background code instead. Here the execution is also halted betweentimer interrupts, but the only role of the interrupt is to notify the background code that the time hascome 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 allactivities and respond only to the Hardware Reset button. (Multiple good solutions exist; however, youmust not use the Task #9 function call for the purpose, as it is only a construct within the simulatedplatform , 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-alonedevice (and as such, is called firmware) instead of loading into a generic computers memory as anapplication program. The firmware, including the constant data definitions, is burned into a Read-Only

    Memory(ROM) starting at address 0, so that it can also include the 68000s exception vectors. On the otherhand, the variables and the stack are placed in a Random Access Memory(RAM). In this simple problem,the 68000s registers are enough to store all necessary data; however, if you wish to use memory variables,assume that a 256-byte RAM exists at address $FFFF00.

    As mentioned above, the vectors of the handled exceptions must be provided by the ROM as part of thefirmware. A 100% robust solution would handle all exceptions that could possibly occur; however, youmay simply handle the autovector interrupt of your choice along with the Reset exception, which requiresthe 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) aspart of the exercise.

    Character Generation

    The BCD-to-decimal decoder and 7-segment display driver modular logic chip is probably familiar toyou from digital electronics; what this program needs is thesoftware equivalentof the above. The linkagebetween the two is stronger than it may initially seem. The display driver chip implements a 4-input7-output Boolean function, which is easily created using a special type of Programmable Logic Device(PLD) known as ROM! This ROMs contents are the Boolean functions truth table.The same sort of

    data in a computer program (in this case an embedded systems firmware code) is referred to as a lookuptable, 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 68000assembly, one of the addressing modes will be particularly suitable for the task of table lookup. Whichone?)

    Note, however, that before the digits can be displayed, the temperature byte-value must be decomposedinto three decimal digits by a suitable binary-to-decimal conversion algorithm. (Luckily, the sensors outputis a binary value, therefore no decimal-to-binary conversion on the front-end of the program.)

  • 5/21/2018 Lab+Manual+-+EEE3231

    31/38

    EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)

    Peter Csaszar Lawrence Technological University, ECE Department 31

    Signed or Unsigned?

    The temperature sensor provides its measurement as an unsigned byte value, per the sensors specifications.Hence the firmware code must consistentlytreat these values as unsigned bytes, erratic behavior will resultotherwise. (The classic example of a similar issue, but on a much grander scale, is the bug that caused thefiery demise of the firstAriane 5rocket on June 4, 1996.)

    Implementation Comments

    This section pertains to the mockup implementation of the device using the EASy68K Simulator.

    The Simulated 7-Segment Display and Other Widgets

    The EASy68K Simulators 7-segment display is simulated as a byte peripheralbeginning at default address $E00000, which represents the displays leftmostdigit. Since the 68000s data bus is 16 bits wide, the subsequent digits aremapped to a series of peripheral addresses increasing by two ($E00002,$E00004, etc.); this minor nuisance must be handled by the program. The figureon 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 isbetter to load all necessary sounds from disk to memory at the start of the program with Task #71, and playthem as often as necessary with Task #72 with no lead time due to disk access.

    You can be creative with the different sounds. You could, for example, use Wi ndows XP Def aul t . wav for

    the warning click and Wi ndows XP Hardwar e Fai l . wav for the error beep, as both sound sufficientlydramatic for the purpose. A sufficiently pleasant, but well-audible sound for the tick would be Wi ndows XP

    Bal l oon. wav. At the time of this writing, these files are located in the C: \ Wi ndows\ Medi a directory of acomputer 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, itis very important that you use Task #9 instead of the STOPassembly instruction to terminate your program.

    Procedure

    Write the program and then complete the following tasks for your lab report.

    1. Briefly explain your program design: what the background code and the ISR contain, which

    interrupt you chose for the timer, and how the devices frozen state was achieved.

    2. Explain how you initialized the Reset exception vectors.

    3. Set the timer auto-interval value to 1000 ms. Start execution with the Reset button in theEASy68K Hardware window (and notwith 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 displayedtemperature values are correct. Take three screenshotsof the EASy68K Hardware window; theyshould show the HELLO! message, the exact temperature value of 27 F, and one of the twoerror messages. Add these screenshots to your lab report.

    0

    1

    2

    5

    4

    6

    3 7

  • 5/21/2018 Lab+Manual+-+EEE3231

    32/38

    EEE3231 Microprocessors Lab Lab Manual (Version 1.0.0)

    Peter Csaszar Lawrence Technological University, ECE Department 32

    Requirements for This Lab

    ! PrelabRefresh your understanding about interrupt handling. Study and understand the usage of thedifferent widgets in the EASy68K Hardware window.

    ! Lab Demo

    You must demonstrate your assembly program to the lab instructor, who will sign off on theexperiment. The ground rules regarding the demonstration are explained in the lab syllabus.

    ! Lab ReportWrite your report according to the usual guidelines. The Description section must include theresults of all required tasks described in the Proceduresection of the experiment. (Make sure toalso include the screenshots you took!) Attach a hardcopy of the source codeand the list file toyour report.

    Next Lab Alert

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

  • 5/21/2018 Lab+Manual+-+EEE3231

    33/38

    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 68000assembly language. As the Enabling Technology, the method of stack-based parameter passing will alsoreceive 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 theelements of the Fibonacci Series.(In recursive formulas, results are determined by the application of thesame formula to preceding terms.) The algorithm for the Fibonacci Series is defined as follows:

    f(k) = f(k1) + f(k2) f(0)=0, f(1)=1

    The first few elements of the Fibonacci Series are:

    0 1 1 2 3 5 8 13 21 34 55 89

    The program prompts the user for the index of the Fibonacci Series element (a.k.a. Fibonacci Number) to

    be printed, calculates the result and prints it on the screen. (For example, f ( 6) = 8.) The programprompts the user for another index and repeats the calculation and printout detailed above, until the userenters a negative number, in which case the program says good-bye and quits.

    Theoretical CommentsThe Fibonacci Series was invented by (guess who) Fibonacci (a.k.a. Leonardo da Pisa) in the early 13 thcentury, 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 anawesome mathematical Wonderland, which mysteriously links seemingly unrelated phenomena acrossscience and nature, such as the Golden Section, the shape of ammonites, the arrangement of seeds in asunflower, and so on; a Web search with one or more of the above keywords is a good start to enter thisenchanting world. The very first interesting fact to muse about is the closed [i.e., non-recursive] formexpression of the Fibonacci Series:

    2 3kk

    kk

    kf 4%5&))

    *

    +

    ,,

    -

    .

    667

    8

    99:

    ; %

    %667

    8

    99:

    ; (

    & 5

    1

    2

    51

    2

    51

    5

    1

    )(

    Incredible as it may sound, this formula, which includes powers and a reciprocal of hideous irrational

    numbers, does indeed churn out perfect integers for each integer value of k. The expression 5(named suchto honor Fibonacci) evaluates to 1.6180339887, and is the famous and infamous Golden Section itself.

    The value of 4is 0. 6180339887, from which it also follows that 5+4= 1 (just some food for thought).Amazed enough? Great; then lets move on from Theory to Practice!

  • 5/21/2018 Lab+Manual+-+EEE3231

    34/38

    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