2016)/EE/Naila_Munaf/Lab... · Web vie

87
Electrical Engineering Department CAO Computer Architecture and Organization Lab Manual

Transcript of 2016)/EE/Naila_Munaf/Lab... · Web vie

Page 1: 2016)/EE/Naila_Munaf/Lab... · Web vie

Electrical Engineering Department

CAO Computer Architecture and Organization

Lab Manual

Page 2: 2016)/EE/Naila_Munaf/Lab... · Web vie

II

TABLE OF CONTENTS

PREFACE..............................................................................................................................................III

EXPERIMENT NO 1................................................................................................................................2

INTRODUCTION TO ASSEMBLY LANGUAGE PROGRAMMING .............................................2

EXPERIMENT NO 2..............................................................................................................................10

INPUT AND OUTPUT ..........................................................................................................................10

EXPERIMENT NO 3..............................................................................................................................17

SEGMENTATION AND ADDRESSING MODES ............................................................................17

EXPERIMENT NO 4..............................................................................................................................25

INDEXING AND DATA MANIPULATION......................................................................................25

EXPERIMENT NO 5..............................................................................................................................31

ARITHMETIC AND LOGICAL INSTRUCTIONS ..........................................................................31

EXPERIMENT NO 6..............................................................................................................................38

SHIFT ROTATE AND JUMP INSTRUCTIONS ...............................................................................38

EXPERIMENT NO 7..............................................................................................................................45

SUBROUTINE HANDLING INSTRUCTIONS AND MACROS .....................................................45

EXPERIMENT NO 8..............................................................................................................................55

STRING HANDLING INSTRUCTIONS............................................................................................55

EXPERIMENT NO 9..............................................................................................................................62

ACCESSING VIDEO MEMORY........................................................................................................62

EXPERIMENT NO 10............................................................................................................................80

INTERRUPTS........................................................................................................................................80

EXPERIMENT NO 11............................................................................................................................94

USING THE MOUSE ............................................................................................................................94

EXPERIMENT NO 12..........................................................................................................................102

SERIAL COMMUNICATIONS .........................................................................................................102

Page 3: 2016)/EE/Naila_Munaf/Lab... · Web vie

III

King Fahad University of Petroleum and Minerals

Computer Engineering Department

Preface

About the Manual:

The lab manual was prepared during the term 982, and updated during the terms 991, 992 and 993. Some experiments have been added with respect to previous terms. The manual includes now 12 experiments. Each experiment is divided into two parts, a theoretical part that explains the theory required to carry out the experiment in a proper manner. The second part is practical; it consists of a set of programs that the student has to run to understand the functioning of the tools introduced in the first part. The student then modifies some of these programs to accomplish given tasks. Finally, the student has to write his own programs in order to show his understanding of the material given in each lab session.

The first experiment is an introduction to the tools that will be used throughout the lab. Experiments 2 to 8 constitute an overall view of assembly language programming. Experiments 9 to 12 deal with video, interrupts, mouse and serial communications. Finally, a project is given at the end of the term. The experiments are organized as follows and are scheduled on a weekly basis.

1) Introduction to assembly language programming using MASM2) Input and Output3) Segmentation and Addressing Modes4) Indexing and Data Manipulation5) Logic Instructions6) Shift Rotate and Jump Instructions7) Subroutine Handling Instructions and Macros8) String Handling Instructions9) Accessing Video Memory10) Interrupts11) Using the Mouse12) Serial Communications

Software:

The software used is the MASM 6.11 that includes a set of tools, such as a workbench, and a debugger. The software is licensed, and is available on the network of the university.

Projects:

The last part of the lab is dedicated to a project in which the student is required to use all knowledge he has gained in the course. The project involves understanding of the hardware a s well as software of the PC.

Page 4: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 1

2

Experiment No 1

Introduction to Assembly Language Programming

Introduction:

The aim of this experiment is to introduce the student to assembly language programming, and the use of the tools that he will need throughout the lab experiments. This first experiment let the student use the DOS Debugger and the Microsoft Macro Assembler (MASM). MASM related tools are introduced; these include the Programmer’s WorkBench (PWB) and CodeView (CV). Such tools are interactive means for writing linking, and debugging assembly language programs.

Objectives:

1- Introduction to the Microsoft Macro Assembler (MASM) 2- General structure of an assembly language program3- Use of the Dos Debugger program4- Use of the PWB, and Code View (CV).5- Introducing Data representation in assembly

Overview:

In general, programming of a microprocessor usually takes several iterations before the right sequence of machine code instructions is written. The process, however, is facilitated using a special program called an “Assembler”. The Assembler allows the user to write alphanumeric instructions, or mnemonics, called Assembly Language instructions. The Assembler, in turn, generates the desired machine instructions from the Assembly Language instructions.

Assembly Language programming consists of the following steps:

STEP PRODUCES1 Editing Source File2 Assembling Object File3 Linking Executable File4 Executing Results

Table 1.1 : Assembly Language Programming Phases

Page 5: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 1

3

Assembling the program:

The assembler is used to convert the assembly language instructions to machine code. It is used immediately after writing the Assembly Language program. The assembler starts by checking the syntax, or validity of the structure, of each instruction in the source file. If any errors are found, the assembler displays a report on these errors along with a brief explanation of their nature. However, if the program does not contain any errors, the assembler produces an object file that has the same name as the original file but with the “obj” extension.

Linking the program :

The linker is used to convert the object file to an executable file. The executable file is the final set of machine code instructions that can directly be executed by the microprocessor. It is different than the object file in the sense that it is self-contained and re-locatable. An object file may represent one segment of a long program. This segment can not operate by itself, and must be integrated with other object files representing the rest of the program, in order to produce the final self-contained executable file.

In addition to the executable file, the linker can also generate a special file called the “map” file. This file contains information about the start, end, and the length of the stack, code, and data segments. It also lists the entry point of the program.

Executing the program

The executable file contains the machine language code. It can be loaded in the RAM and be executed by the microprocessor simply by typing, from the DOS prompt, the name of the file followed by the Carriage Return Key (Enter Key). If the program produces an output on the screen, or a sequence of control signals to control a piece of hardware, the effect should be noticed almost immediately. However, if the program manipulates data in memory, nothing would seem to have happened as a result of executing the program.

Debugging the program

The Debugger can also be used to find logical errors in the program. Even if a program does not contain syntax errors it may not produce the desired results after execution. Logical errors may be found by tracing the action of the program. Once found, the source file should be reedited to fix the problem, then re-assembled and re- linked. A special program called the “Debugger” is designed for that purpose.

The debugger allows the user to trace the action of the program, by single stepping through the program or executing the program up to a desired point, called break point. It also allows the user to inspect or change the contents of the microprocessor internal registers or the contents of any memory location.

Page 6: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 1

4

The DOS-Debugger:

The DOS “Debug” program is an example of a simple debugger that comes with MS- DOS. Hence, it is available on any PC. It was initially designed to give the user the capability to trace logical errors in executable files. It allows the user to take an existing executable file and unassemble it, i.e. convert it to assembly language. Also, it allows the user to write assembly language instructions directly, and then convert them to machine language. The program is simple and easy to use, but offers limited capabilities, which make it unsuitable for serious Assembly language programming.

Below, are summarized the basic DOS-Debugger commands.

COMMAND SYNTAXAssemble A [address]Compare C range addressDump D [range]Enter E address [list]Fill F range listGo G [=address] [addresses]Hex H value1 value2Input I portLoad L [address] [drive] [first sector] [number]Move M range addressName N [pathname] [argument list]Output O port byteProceed P [=address] [number]Quit QRegister R [register]Search S range listTrace T [=address] [value]Unassemble U [range]Write W [address] [drive] [first sector] [number]

Table 1.2 : Common DOS-Debug commands

MS-MASM:

Microsoft’s Macro Assembler (MASM) is an integrated software package written by Microsoft Corporation for professional software developers. It consists of an editor, an assembler, a linker and a debugger (CodeView). The programmer’s workbench combines these four parts into a user-friendly programming environment with built in on line help.

Page 7: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 1

5

The following are the steps used if you are to run MASM from DOS.

COMMAND FILE NAME1 Edit, any editor will do Name.asm2 Masm Filename Name.obj3 Link Filename Name.exe4 Filename

Note: Steps 2 and 3 may be done in one single command: ML filename.asm

Name.asm and Name.obj

Table 1.3 : Assembly Language Programming Phases

MS-PWB:

The PWB allows the user to define a project that may contain one or more files. Then, the user may select and save all the necessary assembling, linking, and debugging options for that project. Once these options are set, the user need not set them again for that project. The PWB allows the user to edit, assemble, run, or debug his program without leaving the PWB environment. It also allows the user to get help on any keyword by pointing to the keyword and pressing the F1 key.

Notes on the use of MS-MASM:

MASM may be run under DOS environment, or through PWB.Running MASM and CodeView Debugger from the MSDOS prompt: If you don't like the integrated PWB, you might run just the necessary programs from the MSDOS prompt. Here are the steps, assuming that your program is called "proj":

1. Open a DOS window.2. Set the PATH so that the MASM programs are available

The MASM programs are on the E drive; set the path so that DOS can find them. This only needs to be done once each time you open a MSDOS prompt.set PATH=%PATH%;E:\masm611\bin; E:\masm611\binr

3. Use a Text Editor to Edit the .ASM FileCreate your file using one of the following programs:

notepad proj.asm wordpad proj.asm edit proj.asm

Make sure it has a .ASM ending. Also, be sure you are doing your work on the A: drive, or on the D:\WORKAREA, and not in the C:\WINDOWS directory, or other drives.

4. Run the Compiler/Linker to generate an .EXE file from the .ASM fileml /Fl /Zi proj.asm

Page 8: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 1

6

Make sure you use the two switches: /Fl creates a listing (.LST) file (the letter to the right of the F is a lower-case L); /Zi makes the finished product compatible with the CodeView debugger.You'll be notified of any errors with your program, and error statements should be placed in your .LST file (proj.lst in this case).

5. Run the ProgramYour final program (if there were no errors in the previous step) will have a.EXE ending. To just run it, type:proj

If you want to use the CodeView debugger to examine the instructions, registers, etc.:cv proj

This brings up the regular full-screen version of CodeView.

Running MASM and CodeView PWB : The basic steps for creating, building, and debugging an assembly language program are given below. The examples given in this first session are very simple; their main purpose is to show how o uses the PWB environment.A project is a complete set of files needed to define and build an assembly language program. The source language files for your programs are, of course, part of this project, but also there are listing files, and symbol table files for debugging, and files giving directions for building your program.It is best to create a separate folder to contain the project files for each programming assignment. You should copy this folder on a floppy disk for later use.

1. Create a folder for your new project. For the first assignment, the folder name could be lab1.

2. Copy any files that are needed from your floppy disk into your folder.3. Run PWB.EXE by double clicking on the file or its shortcut in the C:\

MASM611\BIN folder. The shortcut may be copied and the copy moved to the desktop to make it easier to find the PWB.

4. Once the PWB is running (and the DOS window appears), you may create a new project using the project menu. Type the correct path to the new project folder with project name and press the set project template button. Select Runtime support: None, Project Templates: DOS:EXE, and press OK.

5. You don't have any program files to add to the project yet, so click save listwhen the add file window appears.

6. Under the Options menu, select build options. Select Use Debug Options.Select OK.

7. Using the Options menu:language options:MASM, select Set Debug Options. Check the boxes that will create a listing file with source, machine language, and symbol table: Generate Listing File, List Generated Instructions, Include all Source Lines, CodeView Debugger. Press OK.

8. Using the Options menu:link options, select CodeView debugger, debug options. Press the additional debug options "button" and select Full map output. This will give you a link map that tells where each program component will be loaded. Select OK.

Page 9: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 1

7

9. Select new under the file menu to get an editor window for your program. Enter the program. Save your program naming it with a .ASM suffix, e.g. : P11.ASM

10. Select edit project from the project menu, and add your new assembly program into the project list. Save the list.

11. Start the debugger, running your program, by selecting debug from the Run menu. It will ask you to build your project. That is a good idea, select Rebuild All. The Assembler will assemble your code, the linker will be called, and if there are no errors, the debugger window will appear. You can then start debugging.

12. If there were any errors, select View Results, then click next error under the project menu. It will show you the line containing the error in your source program, and you can correct it at this point.

13. Continue asking to see the next error until you run out of errors.14. Select debug from the project window to have another try.15. Repeat this procedure until you finally get the debugger.16. Now you can run your program. You may step through your program one line

at a time by using F8 and F10, or you may select go (F5) and run it without interruption.

17. In order to watch the contents of memory change, you need to select the memory window options in the options menu (of the debugger). Check the box which requests that the memory window be continually re-evaluated. If you don't check this box, the memory window will continue to reflect memory contents just before your program started running.

18. Breakpoints may be inserted at any line of code using the set breakpoint item in the Data menu, or press F9. If go (or F5) is selected, the program will stop on any line encountered with a breakpoint that is set.

19. Selecting source window options from the window menu allows you to have mixed source lines and object code. This will allow you to compare the instructions that are actually running with the lines of source code that you provided.

20. F10 will single step through your code, but will not single step through any called subroutines (It will "step-over" the subroutine call.) The subroutine will be called correctly; it will simply not be debugged. This is handy when you are using a subroutine that has already been debugged, or when a system routine is called.

21. F8 will single "step-into" a subroutine that is called, allowing you to debug the subroutine itself.

22. You may execute down to a given instruction by right clicking on the source line, moving the cursor to the source line, and then pressing the F7 key.

23. Taking the time to add comments to your code while first entering it will save much time in the long run. It is very hard to figure out what an undocumented assembly language program is doing after even a brief intermission. Comments help you to quickly locate desired sections of code.

24. Note: On the machines at the lab, it is frequently necessary to make sure the path is set correctly for the PWB to run. Right mouse-click on the PWB shortcut icon. Select Properties, and then select the Program tab. Under Batch file, type C:\MASM611\BIN\NEW-VARS. In the lab, only the network administrator can do this procedure.

Page 10: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 1

8

Pre Lab Work :

In this experiment you will practice editing, assembling, and linking an Assembly language program. First you will type a short program, using DOS Edit, then assemble and link the program using the MASM Assembler and Linker. Second you will practice the DOS-Debugger, and compare it to MASM’s CodeView. Finally, you will use MS-PWB to develop a project around your short program and practice some of the advantages of PWB.

1- Study the material given in part I of this manual. 2- Review the material related to data representation.3- Write the attached programs and bring them on a floppy disk to the lab.

Use the DOS editor or the Windows notepad. If you use a word processor, make sure that you chose the option Save As Text while saving

Note:The Exit function :The following instructions terminate the program and exit to DOS.

MOV AH, 4CH INT 21H

Lab Work:

1- Assemble, Link and Run program 1.2- Use the Debugger to run your program.3- Notice the values given by the assembler to the numbers you used in your

program. Draw a table and write each value with its corresponding representation. What do you conclude?

4- Repeat the same procedure using PWB and CodeView. What do you conclude?

6- Dress a table and write the values assigned by the assembler to the values you wrote in the editor. Explain that.

5- Assemble, Link and Run program 2.6- What value do you find in DX register?7- Repeat the same procedure using PWB and CodeView. 8- Change the line:

MULT1 EQU 25By: MULT1 EQU 25H,and run the program again. What do you notice?

9- Can you explain what the program does?

Page 11: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 1

9

; The following lines are just comments, they may be omitted,; However, they are very useful.

; COE 205: Lab Exp. # 1 Program # 1; Student Name: Student ID: Section:

TITLE “A simple program”.MODEL SMALL.STACK 32.CODE

MOV AX,2000 MOV BX,2000HMOV CX,10100110B MOV DX, -4567 MOV AL,'A'MOV AH,'a'

END

MOV AX,4C00H INT 21H

; COE 205: Lab Exp. # 1 Program # 2; Student Name: Student ID: Section:

TITLE "Our second program".MODEL SMALL.S TACK 32.DATA

.CODE

MULT1 EQU 25MULT2 DW 5

MOV AX,@DATA MOV DS,AX

MOV AX,00 MOV BX,MULT1 MOV CX,MULT2

MULT: ADD AX,BXDEC CX JNZ MULT MOV DX,AX

END

MOV AX,4C00H INT 21H

Page 12: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 2

10

Experiment No 2

Input and Output

Introduction:

In this experiment you will be introduced to the basic Input and Output (I/O) operations using assembly language. You will use the DOS interrupt (INT 21H) function calls to access the keyboard and video display. More details will also be given on the structure of an assembly language program.

The following major points are discussed:- Variable declaration using: DB, DW, DD- Constant declaration using: EQU- OFFSET operator- INT 21H with the functions 1, 2, 8 and 9.

Objectives:

1- Demonstrate keyboard access using the DOS INT 21H function calls 01, 02 and 08.

2- Demonstrate string display using the DOS INT 21H function call 09.3- Show the difference between keyboard read functions, with echo and

without echo.

References:Textbook: Sections 2.1, 2.2, 2.3, 2.5 and 3.3.

I/O DOS Function Calls: Table 2. 1 summarizes the main I/O functions. These functions are mainly used to read a character or a string from the keyboard, which could be an input data to a program, and display characters or strings, which could be results, or an output, of a program:

Function Input in Output in Effect01H AH AL Read a character with echo on the

screen.02H, 06H AH,

Character in DLNo output Display a character on the screen.

Note: Interrupted by Ctrl + Break08H AH AL Read character without echo.09H AH No output Display a string terminated by a

‘$’ sign0AH AH Offset

in DXRead a string of characters from the keyboard

Table 2. 1 : Simple I/O DOS function calls

Page 13: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 2

11

DOS Display Functions:

These are DOS functions 02 and 06 for a single character display, and 09 for a string display.

DOS Functions 02 and 06:

Both functions are identical, except that function 02 can be interrupted by a control break (Ctrl-Break), while function 06 cannot. To display a single character ASCII character at the current cursor position use the following sequence of instructions:

MOV AH, 06H ;(Or: MOV AH, 02H)MOV DL, Character Code INT 21H

The Character Code may be the ASCII code of the character taken from the ASCII table (See Experiment 4 Table 4.1) or the character itself written between quotes.

The following displays number 2 using its ASCII code:

MOV AH, 06HMOV DL, 32H INT 21H

This code also displays 2:

MOV AH, 06H MOV DL, ‘2’ INT 21H

DOS Functions 09:

This function is used to display a string of characters ended with a ‘$’ sign. The following code displays the string MESSAGE defined as:

MESSAGE DB ‘This is the Message to be displayed’, ‘$’

.CODEMOV DX, OFFSET MESSAGE MOV AH, 09HINT 21H

DOS Input functions:

These include reading a single character, with or without echo, functions 01 and 08, and reading a whole string.

Page 14: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 2

12

Function 01H and 08H INT 21H:

To read single character and have it echoed (displayed) on the screen, use the following code:

MOV AH, 01H INT 21H;AL contains now the ASCII code of the character read from the;keyboard.

If the character is to be read without echo, such as reading a password, use the following code:

MOV AH, 08H INT 21H;AL contains now the ASCII code of the character read

Reading a String:

Reading a string is accomplished by Function 0AH INT 21H. DOS function 0AH will accept a string of text entered at the keyboard and copy that string into a memory buffer. DOS 0AH is invoked with DS:DX pointing to an input buffer, whose size should be at least three bytes longer than the largest input string anticipated.

Before invoking DOS function 0AH, you must set the first byte of the buffer with the number of character spaces in the buffer. After returning from DOS function 0AH, the second byte of the buffer will contain a value giving the number of characters actually read form the keyboard (Table 2.2 ).

Buffer Length

Actual Length

Figure 2. 1 : Keyboard buffer structure

Function 0AH Read from KeyboardEntry AH = 0AH ; DX = address of keyboard input buffer

First byte of buffer contains the size of the buffer (up to 255)Exit Second byte of buffer contains the number of characters read.

Reading operation continues until buffer full, or a carriage return (CR = 0DH) is typed.

Table 2. 2 : : Functions 0AH of DOS interrupt.

Page 15: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 2

13

Example:

Below is an example on the use of function 0AH, when the user enters the word “hello”.

Input:

08 XX XX XX XX XX XX XX XX XX

MOV AH, 0AH INT 21H;Read from keyboard the word “hello”

Output:

08 05 68 65 6C 6C 6F 0D XX XX

Empty String :

Page 16: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 2

14

Pre Lab Work :

Review the material given in experiment number 1 for the use of PWB, and CodeView.

1. Study the attached hand out.2. Review the material related to data representation.3. Write the attached programs and bring them on a floppy disc to the lab.

Use the PWB or DOS editor, or even the Windows notepad, to write your programs.

Note: Give meaningful names to your programs, so that you can differentiate between them easily, e.g. pgm21.asm, stands for experiment 2 program 1.

Lab Work:

1- Assemble and Link program 1.2- Type the program’s name at the prompt to run the program.3- What does the program do? Notice how the program handles the three

different characters.

4- Assemble, Link and Run program 25- Replace the line: MOV DX, OFFSET MESSAGE

by: LEA DX, MESSAGEThen repeat step 4, what do you notice?

6- Check with CodeView the effects of the instruction LEA and the OFFSET operator?

7- Assemble, Link and Run program 38- After running the program, notice here the effect of the characters 0DH

and 0AH at the end of the line containing: MESSAGE. What is your conclusion?

9- Notice also the effects of the function calls 01H, 08H.

10- Write down all your conclusions.

Lab Assignment:

Write an assembly language program that prompts you to enter a password of 3 characters in length. The password should not be echoed to the screen. The program then displays your name and ID number on the screen.

Submit your work at the end of the lab.

Page 17: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 2

15

; Student Name: Student ID: Section:

Title “Exp. 2 Prog. 1”; This program displays the characters A B C, using INT 21H function 02.

.MODEL SMALL

.DATAX EQU ’B’ Y DB 43H

.STACK 200

.CODE

MOV AX,@DATA MOV DS,AX

MOV AH,02 ; LOAD FUNCTION 02

MOV DL,’A’ ; LOAD CHARACTER TO BE DISPLAYED INT 21H ; CALL INTERRUPT 21H

MOV DL,X ; LOAD CHARACTER TO BE DISPLAYED INT 21H ; CALL INTERRUPT 21H

MOV DL,Y ; LOAD CHARACTER TO BE DISPLAYED INT 21H ; CALL INTERRUPT 21H

MOV AX,4C00H; Exit to DOS INT 21H

END

Title “Exp. 2 Prog. 2”; This program displays a string terminated by a $ sign using INT 21H function 09H.

.MODEL SMALL

.DATAMESSAGE DB ‘This is the message to be displayed’,’$’

.STACK 200

.CODE

END

MOV AX,@DATA MOV DS, AX

MOV DX, OFFSET MESSAGE MOV AH, 09HINT 21H

MOV AX, 4C00H ; Exit to DOS INT 21H

Page 18: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 2

16

; Character input with echo INT 21H, function call 01H; Character input without echo INT 21H, function call 08H

Title “Exp. 2 Prog. 3”

.MODEL SMALL

.DATAMESSAGE DB ‘Enter a character: ’,’$’MESSAGE2 DB ‘The character you typed is: ’,0DH, 0AH,’$’

.STACK 200

.CODE

MOV AX,@DATA MOV DS,AX

LEA DX, MESSAGE MOV AH,09HINT 21H ; Display message

MOV AH,02 ; Function 02H, display character MOV DL,AL ; Load character to be displayed INT 21H ;

LEA DX, MESSAGE MOV AH,09HINT 21H

MOV AH, 08H ; Function read character without echo.INT 21H ; Character read is returned in AL register. No echo on the display.

MOV BL,AL ;Save character read in BL register

LEA DX, MESSAGE2MOV AH,09H ;Display MESSAGE2 INT 21H

MOV AH,02 ; Function 02H, display characterMOV DL,BL ; Load character to be displayed from BL INT 21H

END

MOV AH,4CH ; Exit to DOS INT 21H

Page 19: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 3COE 205 Lab Manual

17

Experiment No 3

Segmentation and Addressing Modes

Introduction:

In this experiment you will be introduced to physical segmentation of the memory, and the logical segmentation of programs. You will also deal with the different addressing modes, and learn how to calculate the physical and offset addresses.

Objectives:

1- Addressing modes in the 8086 processor2- Segmentation: Physical Segments and Logical Segments.

References: Textbook:

- Addressing modes: section 4.3,- Segmentation: section 3.1,- Lecture notes.

Addressing Modes:

The following table summarizes all addressing modes used by the 8086 processor.

Addressing Mode Example

Source operandAssuming: DS = 1000H, BX = 0200H, SI = 0300H

Type Address Generation Addres s

Register MOV AX,BX Register - -Immediate MOV AX, 0F7H Immed. - -Direct MOV AX,[1234H] Mem. DS x 10H +1234H 11234HRegister-Indirect MOV AX,[BX] Mem. DS x 10H +0200H 10200HBased MOVAX,[BX+06] Mem. DS x 10H +0200H + 0006H 10206HIndexed MOVAX,[SI+06] Mem. DS x 10H +0300H + 0006H 10306HBased-Indexed MOV AX,[BX+SI+06] Mem. DS x 10H +0200H +0300H + 0006H 10506H

Table 3.1: Addressing modes

Structure of an Assembly Language Program:

An assembly language program is written according the following structure and includes the following assembler directives:

Page 20: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 3COE 205 Lab Manual

18

TITLE “Optional: Write the Title of your program”.MODEL SMALL

Assembler directive that defines the memory model to use in the program. The memory model determines the size of the code, stack and data segments of the program

.STACKAssembler directive that reserves a memory space for program instructions in the stack

.DATAAssembler directive that reserves a memory space for constants and variables

.CODEAssembler directive that defines the program instructions

ENDAssembler directive that finishes the assembler program

Each of the segments is called a logical segment. Depending on the memory, the code and data segments may be in the same or in different physical segments according to table 3.3.

Memory Model Size of Code and Data

TINY Code and data no more than 64KB combinedSMALL Code and data segments must be no more than 64KB eachMEDIUM Code can be more than 64KB, data still limited to no more than

64KBCOMPACT Code limited to no more than 64KB, data can be more than

64KBLARGE Code and data can each be more than 64K, no array can be

larger than 64KBHUGE Code and data can each be more than 64KB, arrays can be

larger than 64KB

Table 3.3 : Memory Models

Page 21: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 3COE 205 Lab Manual

19

Stack Directive:

- Directive is .stack for stack segment- Should be declared even if program itself doesn't use stack needed

for subroutine calling (return address) and possibly passing parameters

- May be needed to temporarily save registers or variable content- Will be needed for interrupt handling while program is running

Memory allocation :

- Directive is .data for data segment- All variables must be declared, and memory space for each allocated.- Data definition directive can be followed by a single value, or a list

of values separated by commas- Different data definition directives for different size types of memory

1. DB - define byte (8 bits)2. DW - define word (16 bits)3. DD - define double word (32 bits)4. DQ - define quad word (64 bits)

Code Segment:- Directive is .code for code segment- The "program" resides here

End of Program: - Directive is End- Tells assembler that this is the end of the program

Note:

The sequence of instructions at the beginning of a program used to assign the data segment:

MOV AX, @DATA MOV DS, AX

May be replaced by the following directive:

.STARTUP

which assigns both DATA and CODE segments, and hence no warning will be issued by the assembler. However, it should be noted that the program would start at address CS:0017h. The Startup directive occupies the bytes CS:0000 to CS:0017.

Identically, the sequence used to terminate and exit to DOS can be replaced by the.E XIT directive, which has exactly the same effect.

Page 22: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 3COE 205 Lab Manual

20

Pre Lab Work :

1. Study the attached hand out, and review the material related to segmentation and addressing modes.

2. Write programs 3-1 and 3-23. Write the program given in assignment.4. Fill in the tables associated with the different programs.5. Bring your work to the lab.

Lab Work:

1- Assemble, Link and Run program 1.2- Use CodeView Debugger to fill in the table associated with program 3.1.3- Calculate both the effective and physical addresses of each instruction. Put

the results on the given table.4- Assemble, Link and Run program 2.5- Fill in table 2, associated with program 2, in which you specify only the

addressing mode, for both source and destination, for each instruction.

6- Show all tables to the instructor.7- Submit all your work at the end of the lab session.

Lab Assignment:

Write a program that prompts the user to enter a string, in capital letters, of a maximum length of 20 characters. Read the string in capital letters and convert it to small letters. Then display the new string.

Note:To convert a capital letter to a small one, use the following instruction:

;Read characterMOV AL, character_read ADD AL, 20H; Display character in AL register

Use the following to loop through the string you just entered.

MOV CX, Number_of_bytes_readAgain: Start loop here

; Convert to small letters.

LOOP Again

Page 23: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 3COE 205 Lab Manual

21

; This program displays a string terminated by a $ sign using INT 21H function 09H.

TITLE “Program 3-1”.MODEL SMALL

.STACK 200

.DATAMESSAGE DB ‘This is the message to be displayed: ’, ‘$’ MESSAGE2 DB ‘The message you just entered : ;’ , ‘$’ BUF DB 10 ; Number of characters to be read

DB 10 DUP(?); Reserve 10 bytes for string

.CODE

END

MOV AX,@DATA MOV DS,AX

LEA DX,MESSAGE MOV AH,09HINT 21HMOV AH, 0AHMOV DX, OFFSET BUF INT 21H

LEA DX,MESSAGE2 MOV AH,09HINT 21H

LEA DX, BUF MOV AH,09H INT 21H

MOV AX,4C00H INT 21H

Page 24: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 3COE 205 Lab Manual

22

TITLE “PROGRAM 2 EXPERIMENT 3”; This program displays a message and reads a new message from the keyboard

.MODEL SMALL

.STACK 200

.DATACRLF DB 0DH,0AH,'$'PROMPT DB 'Enter a name of max. length 30 char.: ',0DH,0AH,'$' STRING1 DB 'Mr. ','$'STRING2 DB ' studies 8086 programming. ','$'

; Allocate 32 bytes for BUFFER, and put the value 31 in the second byte. BUFFER DB 31,32 DUP(?)

.CODE

.STARTUP ;This directive initializes the DS and CS segments.LEA DX,PROMPT ;display prompt MOV AH,09HINT 21H

MOV AH,0AH ;read into buffer LEA DX, BUFFERINT 21H

LEA DX, CRLF ;move cursor to next line MOV AH,09HINT 21H

LEA DX,STRING1 ;display string1 MOV AH,09HINT 21H

;now display the buffer i.e. what has been read.

MOV AH,09HMOV BH,00HMOV BL,BUFFER[1] ;move in BL buffer length MOV BUFFER[BX+2],'$' ;put a $ sign at the end of buf LEA DX,BUFFER[2] ;load actual length of buffer INT 21H

LEA DX,STRING2 ;display string2 MOV AH,09HINT 21H

LEA DX, CRLF ;move cursor to next line MOV AH,09HINT 21H

END

MOV AH, 02H ; display number of characters read if less than 10MOV DL,BUFFER[1] ; read second byte of bufferADD DL, 30H ; convert to number INT 21HMOV AX,4C00H INT 21H

Page 25: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 3COE 205 Lab Manual

23

COE 205

Experiment 3, Program #1:

Section:

Student Name: Date:

Student ID:

Instruction

Source Destination Addressing Mode

Address/ Register

Content Address/ Register

ContentsBefore After

MOV AX,@DATAMOV DS,AXLEA DX,MESSAGEMOV AH,09HINT 21H Before INT 21H, IP = After INT 21H, IP =MOV AH, 0AHMOV DX, OFFSET BUFINT 21H Before INT 21H IP = After INT 21H IP =LEA DX,MESSAGE2MOV AH,09HINT 21H Before INT 21H IP = After INT 21H IP =LEA DX, BUFMOV AH,09HINT 21H Before INT 21H IP = After INT 21H IP =MOV AX,4C00HINT 21H S k i p

Page 26: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 3COE 205 Lab Manual

24

COE 205

Experiment 3, Program #2:

Section:

Student Name: Date:

Student ID:

InstructionsAddressing Modes

Source DestinationLEA DX,PROMPTMOV AH,09HINT 21HMOV AH,0AHLEA DX, BUFFERINT 21HLEA DX, CRLFMOV AH,09HINT 21HLEA DX,STRING1MOV AH,09HINT 21HMOV AH,09HMOV BH,00HMOV BL,BUFFER[1]MOV BUFFER[BX+2],'$'LEA DX,BUFFER[2]INT 21HLEA DX,STRING2MOV AH,09HINT 21HLEA DX, CRLFMOV AH,09HINT 21HMOV AH, 02HMOV DL,BUFFER[1]ADD DL, 30HINT 21HMOV AX,4C00HINT 21H

Page 27: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 4COE 205 Lab Manual

COE Department 25 KFUPM (2000 )

Experiment No 4

Indexing and Data Manipulation

Introduction:

In this experiment you will be introduced to data transfer and arithmetic instructions. You will also deal with indexing, and array manipulation.

Objectives:

1- Basic arithmetic instructions 2- Use of the ASCII table.3- Manipulation of arrays

References:

Textbook:- Sections 3.1 and 3.2,- Lecture notes.

ASCII code Table:

The ASCII table is a double entry table, which contains all alphanumeric characters and symbols. Each symbol, or character, has its own ASCII code. This code can either be in decimal or hexadecimal format. The code of a given character is found by concatenating the column number with the row number, if the code is to be expressed in hexadecimal. The row number is to be the least significant. For the same code to be expressed in decimal, the row number is added to the column number (See example given below).

As an example, the symbol’ $’ is at the intersection of row 4 and column 2, therefore its ASCII code is 24H. The decimal equivalent of this code can be found by adding 4 to 32, which yields 36.

The following tables show the ASCII codes (Table 4.1), and examples on the use of the ASCII table (Table 4.2), and how to calculate the ASCII codes for different characters and symbols.

Page 28: 2016)/EE/Naila_Munaf/Lab... · Web vie

COE Department 26 KFUPM (2000 )

Experiment No 4COE 205 Lab Manual

Table 4.1 : ASCII Table

Character Column # Row # Code (H) Code (10)a 6 1 61 96 + 1 = 97A 4 1 41 64 + 1 = 65 E 1 E1 224 + 1 = 225% 2 5 25 32 + 5 = 37

Table 4.2 : Examples on the use of the ASCII table:

Note on the use of arrays:

The DB and DW directives are respectively used to declare a variable of size byte or word. The following declaration defines a variable X of size byte and assigns it the value 10H.

X DB 10H

Identically the following will define a variable of size word, and assigns it the value

13EFH: Y DW 13EFH

Page 29: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 4COE 205 Lab Manual

COE Department 27 KFUPM (2000 )

The DUP directive may be used to reserve more than one consecutive data item and initialize reserved items to the same value. For example, the instruction:

ByteArray DB 100 DUP(0)

Instructs the assembler to reserve an array of 100 bytes, and initializes each byte to the value zero. If the “0” in the above declaration is replaced with “?”, the assembler will not initialize the bytes of the array to any value.

To access the different elements of an array, we use one of the following addressing modes (See Experiment # 3).

- Based addressing mode.- Indexed addressing mode.- Based-Indexed addressing mode.

The Based-Indexed addressing mode may be used to access a two-dimensional array. Here are examples of each case.

Array1 DB 0,1,2,3,4,5,6,7,8,9 Array2 DB 10 DUP(0)Array3 DB 11,12,13,21,22,23,31,32,33RowSize EQU 3

Based addressing mode:

MOV BX, OFFSET Array1 ; Address Array1MOV AL,[BX+4] ; Access 5th element of Array1

Indexed addressing mode:

MOV DI, OFFSET Array2 ; Address Array2MOV [DI+6],AL ; Copy to 7th element of Array2 MOV SI,3MOV Array2[SI],AL ;Copy to 4th element of Array2

Based-Indexed addressing mode:

MOV BX, OFFSET Array3 ; Address Array3 MOV SI,1*RowSize ; Beginning of 2nd row MOV DI,2*RowSize ; Beginning of 3rd rowMOV AL, [BX+SI+1] ; Access 2nd element of 2nd row MOV [BX+DI+2],AL ; Access 3rd element of 3rd row

Remark :

Notice that row R, has index (R-1), and element n has index (n-1).

Page 30: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 4COE 205 Lab Manual

COE Department 28 KFUPM (2000 )

Pre Lab Work :

1. Study programs 4.1 and 4.2, and review the material related to indexing and data manipulation.

2. Write both programs and see how program 4.1 manipulates the variables in internal registers, and how program 4.2 uses memory for the same purpose.

3. Modify program 4.1 so that it adds two numbers of two digits each. Use only registers, and make sure to take care of the carry when adding the two most significant digits. Call this program 4.3.Note: In this case try to understand how the program reads the numbers and how it manipulates them. This will help you in writing your program. As a hint, one should know that numbers are given in decimal to the program.

4. Modify program 4.3 so that it can handle numbers of four digits. Use arrays in this case. Call this program 4.4.

5. Bring your work to the lab.

Lab Work:

1- Assemble, Link and Run program 1.2- How many digits can you enter each time? Explain this. 3- What happens when the sum exceeds 9? Explain this.4- Assemble, Link and Run program 2. Dress a table and show some inputs

and outputs.5- Repeat step 4 with program 3.6- Show all your work to the instructor.7- Submit all your work at the end of the lab session.

Lab Assignment:

Write a program that prompts the user to enter two numbers of 4 digits each. Then the program calculates the quotient and remainder of the division of the two numbers. The two numbers are entered as two arrays of size four (4).

Page 31: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 4COE 205 Lab Manual

COE Department 29 KFUPM (2000 )

TITLE "PROGRAM 1 EXPERIMENT 4"

; This program reads two numbers from the keyboard and; gives their sum. This program uses internal registers; to store the variables.

.MODEL SMALL

.STACK 200

.DATA

.CODE

.STARTUP

CRLF DB 0DH,0AH,'$'PROMPT1 DB 'Enter the first positive integer: ','$' PROMPT2 DB 'Enter the second positive integer: ','$' PROMPT3 DB 'The sum of the two numbers is: ','$'

LEA DX,PROMPT1 ;DISPLAY PROMPT1 MOV AH,09HINT 21H

MOV AH,01H ;READ FIRST NUMBER INT 21HSUB AL,30H ;Convert character to number MOV CL,AL ;SAVE THE NUMBER IN CL

LEA DX,CRLF ;MOVE CURSOR TO NEXT LINE MOV AH,09HINT 21HLEA DX,PROMPT2 ;DISPLAY PROMPT2 MOV AH,09HINT 21H

MOV AH,01H ;READ SECOND NUMBER INT 21HSUB AL,30H ;Convert character to numberADD AL,CL ;PERFORM ADDITION AND SAVE RESULT IN CL

MOV CL,ALADD CL,30H ;CONVERT DIGIT TO CHARACTER

LEA DX,CRLF ;MOVE CURSOR TO NEXT LINE MOV AH,09HINT 21HLEA DX,PROMPT3 ;DISPLAY PROMPT3 MOV AH,09HINT 21H

.EXIT END

MOV DL,CL ;DISPLAY SUM MOV AH,02HINT 21H

Page 32: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 4COE 205 Lab Manual

COE Department 30 KFUPM (2000 )

TITLE "PROGRAM 2 EXPERIMENT 4"; This program reads two numbers from the keyboard and; displays their sum. This program uses the memory to; store the variables..MODEL SMALL.STACK 200.DATA

.CODE

.STARTUP

CRLF DB 0DH,0AH,'$'PROMPT1 DB 'Enter the first positive integer: ','$' PROMPT2 DB 'Enter the second positive integer: ','$' PROMPT3 DB 'The sum of the two numbers is: ','$' NUM1 DB ?NUM2 DB ?RES DB ?

LEA DX,PROMPT1 ;DISPLAY PROMPT1 MOV AH,09HINT 21HMOV AH,01H ;READ FIRST NUMBER INT 21HSUB AL,30H ;Convert character to number MOV NUM1,AL ;SAVE NUM1LEA DX,CRLF ;MOVE CURSOR TO NEXT LINE MOV AH,09HINT 21HLEA DX,PROMPT2 ;DISPLAY PROMPT2 MOV AH,09HINT 21HMOV AH,01H ;READ SECOND NUMBER INT 21HSUB AL,30H ;Convert character to number MOV NUM2,AL ;SAVE NUM2ADD AL,NUM1 ;PERFORM ADDITION MOV RES,AL ;SAVE RESULT IN RESLEA DX,CRLF ;MOVE CURSOR TO NEXT LINE MOV AH,09HINT 21HLEA DX,PROMPT3 ;DISPLAY PROMPT3 MOV AH,09HINT 21H

.EXIT

END

;DISPLAY SUMMOV DL,RES ;RETREIVE RES FROM MEMORY ADD DL,30H ;CONVERT DIGIT TO CHARACTER MOV AH,02HINT 21H

Page 33: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 5COE 205 Lab Manual

COE Department 31 KFUPM (2000 )

Experiment No 5

Arithmetic and Logical Instructions

Introduction:

In this experiment, you will be introduced to the logic instructions of the 8086 family of processors. You will also deal with the conversion of numbers from one radix to another.

Objectives: 1- Logic Instructions2- Base conversion

References: Textbook:- Section 3.2- Section 4.1- Lecture notes.

Arithmetic Instructions:

The following table (Table 4.3) summarizes the arithmetic instructions used in the 8086 microprocessor. It also shows the effect of each instruction, a brief example, and the flags affected by the instruction. The “*” in the table means that the corresponding flag may change as a result of executing the instruction. The “-“ means that the corresponding flag is not affected by the instruction, whereas the “?” means that the flag is undefined after executing the instruction.

Type Instruction Example Meaning Flags AffectedOF SF ZF AF PF CF

Addition ADD ADD AX,7BH AX AX + 7B * * * * * *ADC ADC AX,7BH AX AX + 7B +CF * * * * * *INC INC [BX] [BX][BX]+1 * * * * * -DAA DAA ? * * * * *

Subtraction SUB SUB CL,AH CL CL – AH * * * * * *SBB SBB CL,AH CL CL – AH – CF * * * * * *DEC DEC DAT [DAT] [DAT] – 1 * * * * * -DAS DAS ? * * * * *NEG NEG CX CX 0 – CX * * * * * *

Multiplication MUL MUL CL MUL

AX AL * CL (DX,AX) AX* CX

* ? ? ? ? *

IMUL IMUL BYTE PTR X IMUL WORD PTR

AX AL * [X] (DX,AX) AX* [X]

* ? ? ? ? *

Division DIV DIV WORD PTR X AX Q(([DX,AX])/[X])DX R(([DX,AX])/[X])

? ? ? ? ? ?

IDIV IDIV BH AL Q(AX/BH) AH R(AX/BH)

? ? ? ? ? ?

Sign Extension CBW CBW AH MSB(AL) - - - - - -CWD CWD DX MSB(AX) - - - - - -

Table 5.1 : Summary of Arithmetic Instructions of the 8086 microprocessor

Page 34: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 5COE 205 Lab Manual

COE Department 32 KFUPM (2000 )

Notes:

The DAA (Decimal Adjust after Addition) instruction allows addition of numbers represented in 8-bit packed BCD code. It is used immediately after normal addition instruction operating on BCD codes. This instruction assumes the AL register as the source and the destination, and hence it requires no operand. The effect of DAS (Decimal Adjust after Subtraction) instruction is similar to that of DAA, except the fact that it is used after performing a subtraction.

CBW and CWD are two instructions used to facilitate division of 8 and 16 bit signed numbers. Since division requires a double-width dividend, CBW converts an 8-bit signed number (in AL), to a word, where the MSB of AL register is copied to AH register. Similarly, CWD converts a 16-bit signed number to a 32-bit signed number (DX,AX).

Logical Instructions:

Logic shift and rotate instructions are called bit manipulation operations. These operations are designed for low-level operations, and are commonly used for low- level control of input/output devices. The list of the logic operations of the 8086 is given in Table 5.1, along with examples, and the effect of these operations on the flags. The “*” in the table means that the corresponding flag may change as a result of executing the instruction. The “-” means that the corresponding flag is not affected by the instruction, whereas the “?” means that the flag is undefined after executing the instruction.

Instruction Example MeaningFlags

OF SF ZF AF PF

AND AND AX, FFDFH AX AX AND FFDFH 0 * * ? *

OR OR AL, 20H AL AL OR 20H 0 * * ? *

XOR XOR NUM1, FF00 [NUM1][NUM1]XOR FF00 0 * * ? *

NOT NOT NUM2

[NUM2][ NUM2]

- - - - -

Table 5.2 : Summary of the Logic Instructions of the 8086 Microprocessor

The logic operations are the software analogy of logic gates. They are commonly used to separate a bit or a group of bits in a register or in a memory location, for the purpose of testing, resetting or complementing. For example, if b is the value of a certain bit in a number. The related effects of the basic operations on a single bit are indicated in Table 5.3:

Page 35: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 5COE 205 Lab Manual

COE Department 33 KFUPM (2000 )

Operation Effectb AND 0 = 0 Reset the bitb OR 1 = 1 Set the bitb XOR 1 = b Complement the bitb XOR 0 = b -

Table 5.3: Effects on bits of the basic logic instructions

Byte manipulations for reading and displaying purposes :

1 / To put two decimal digits into the same byte use the following:

MOV AH, 01H INT 21HSUB AL, 30H MOV CH, AL ; Read high digit e.g. 8

MOV AH, 01H INT 21HSUB AL, 30H MOV CL, AL ; Read low digit e.g. 3

MOV AL, 10000B ; Use MUL by 10000B to shift left by 4 bits MUL CH ; Shift AL 4 bits to the leftXOR AH, AH ; Clear AHOR AL, CL ; Result in AL 83

If we want to perform addition:

; If AL contains the first number in BCD format; and CL contains the second number in BCD format ADD AL, CLDAA ; Decimal adjust; New result in AL in BCD format MOV CL, AL; Number in CL register. See next how to display it as decimal number.

2 / To display a number in BCD format use the following:

; The number is in the CL register: MOV AL, CL ; Move CL to ALXOR AH, AH ; Clear AH MOV BL, 10000BDIV BL ; Shift AX 4 bits to the right AND AL, 0FH ; Clear 4 high nibbles of AL ADD AL, 30H ; Convert to character

Page 36: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 5COE 205 Lab Manual

COE Department 34 KFUPM (2000 )

; Now Display AL as high digit firstMOV AL, CL ; Read number againAND AL, 0FH ; Clear 4 high nibbles of AL ADD AL, 30H ; Convert to character; Now Display AL as low digit second

Displaying Data in any Number Base r :

The basic idea behind displaying data in any number base is division. If a binary number is divided by 10, and the remainder of the division is saved as a significant digit in the result, the remainder must be a number between zero and nine. On the other hand, if a number is divided by the radix r, the remainder must be a number between zero and (r-1). Because of this, the resultant remainder will be a different number base than the input which is base 2. To convert from binary to any other base, use the following algorithm.

Algorithm:

1. Divide the number to be converted by the desired radix (number base r).2. Save the remainder as a significant digit of the result.3. Repeat steps 1 and 2 until the resulting quotient is zero.4. Display the remainders as digits of the result.

Note that the first remainder is the least significant digit, while the last remainder is the most significant one.

Page 37: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 5COE 205 Lab Manual

COE Department 35 KFUPM (2000 )

Pre Lab Work :

1. Study program 5.2, and explain how base conversion is performed?2. Write, assemble and link program 5.1. You will run it in the lab using

CodeView.3. Write, assemble, link and run program 5.2.4. Modify the program so that it prompts the user for the RADIX and

the number NUM to be converted. Call the new program prog-5.3.5. Write a program that converts from decimal to hexadecimal. Name it

Prog-5.4.6. Bring your work to the lab.

Lab Work:

1- Use CodeView to trace program 5.1. Fill in table 5.3. Notice any changes in the status flags, and explain them.

2- Run program 5.2, and see what value is displayed.3- Change the value of the variable NUM and see the output value. 4- Now change the value of RADIX and see the value displayed.5- Write a program that prompts the user to enter two numbers of 4 digits

each. Converts these numbers to hexadecimal. Then calculates the sum, the difference of the two numbers, and finally displays the result in decimal format. Name it program 5.5.

6- Show all your work to the instructor.7- Submit all your work at the end of the lab session.

Lab Assignment:

Write a program that reads two binary numbers of 8 digits each, stores them inside the internal registers. Multiply the two numbers using a simple MUL operation, and display the result in decimal format.

To ease bit manipulation and shifting, use division and multiplication by 2, to perform right shift and left shift.

Page 38: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 5COE 205 Lab Manual

COE Department 36 KFUPM (2000 )

TITLE “Program 5.1: Logic Instructions”; This program shows the effect of the logic instructions

.MODEL SMALL

.STACK 200

.DATA

.CODE

.STARTUP

NUM1 DW 0FA62H NUM2 DB 94H

.EXIT END

MOV AX, NUM1 ;load AX with number NUM1 AND AX, 0FFDFH ;Reset 6th bit of AXOR AL, 20H ;Set 6th bit of ALXOR NUM1, 0FF00H ;Complement the high order byte of

; NUM1NOT NUM2 ;Complement NUM2XOR AX, AX ;Clear AX MOV AX, NUM1AND AX, 0008H ; Isolate bit 4 of NUM1XOR AX, 0080H ;Complement 4th bit of AX

Fill in table 5.3 while running the above program using CodeView.

StatementDestination Content Status Flags

Before After O F

D F

I F

S F

Z F

A F

P F

C F

1. MOV AX, NUM12. AND AX, 0FFDFH3. OR AL, 20H4. XOR NUM1, 0FF00H5. NOT NUM26. XOR AX, AX7. MOV AX, NUM18. AND AX, 0008H9. XOR AX, 0080H

Table 5.4 : Effects of Executing Program 5.1

Page 39: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 5COE 205 Lab Manual

COE Department 37 KFUPM (2000 )

TITLE “Lab Exp. # 5Program # 5.2”; This program converts a number NUM from Hexadecimal,; to a new numbering base (RADIX).

.MODEL SMALL

.STACK 200

.DATARADIX DB 10 ;radix: 10 for decimal NUM DW 0EFE4H ;the number to be converted

;put here any other number.;Note that: 0EFE4H = 6141210TEMP DB 10 DUP(?) ;Used to simulate a stack

.CODE

.STARTUPMOV AX, NUM ;load AX with number NUM

;display AX in decimalMOV CX, 0 ;clear digit counterXOR BH, BH ;clear BHMOV BL, RADIX ;set for decimalXOR SI, SI ;Clear SI register

DISPX1:MOV DX, 00 ;clear DXDIV BX ;divide DX:AX by 10 MOV TEMP[SI], DL ;save remainderINC SIINC CX ;count remainderOR AX, AX ;test for quotient of zeroJNZ DISPX1 ;if quotient is not zero DEC SI

DISPX2:MOV DL, TEMP[SI] ;get remainder MOV AH, 06H ;select function 06HADD DL, 30H ;convert to ASCIIINT 21H ;display digit DEC SIDEC CX ;repeat for all digits JNZ DISPX2

.EXIT ;exit to dosEND

Page 40: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 6COE 205 Lab Manual

COE Department 38 KFUPM (2000 )

Experiment No 6

Shift Rotate and Jump Instructions

Introduction:

In this experiment you will be introduced to the shift and rotate instructions. You will also practice how to control the flow of an assembly language program using the compare instruction, the different jump instructions and the loop instructions.

Objectives: 1- Shift Instructions.2- Rotate Instructions.3- Compare Instruction.4- Jump Instructions.5- Loop Instructions.

References: - Textbook: Sections 3.4, 3.5 and 4.1,- Lecture notes.

The Shift Operations:

The shift operations are used to multiply or divide a number by another number that is a power of 2 (i.e. 2n or 2 –n). Multiplication by 2 is achieved by a one-bit left shift, while division by 2 is achieved by a one-bit right shift. The Shift Arithmetic Right (SAR) instruction, is used to manipulate signed numbers. The regular Right Shift (SHR) of a signed number affects the sign bit, which could cause numbers to changetheir sign. The SAR preserves the sign bit by filling the vacated bits with the sign of the number. Shift Arithmetic Left (SAL) is identical in operation to SAR.

The rotate operations are very similar to the shift operations, but the bits are shifted out from one end of a number and fed back into the other end to fill the vacated bits. They are provided to facilitate the shift of long numbers (i.e. numbers of more than 16 bits). They are also used to reposition a certain bit of a number into a desired bit- location. The rotate right or left instructions through the carry flag (RCL and RCR) are similar to the regular rotate instructions (ROL and ROR), but the carry flag is considered as a part of the number. Hence, before the rotate operation, the carry flag bit is appended to the number as the least significant bit in the case of RCL, or as the most significant bit in the case of RCR.

Page 41: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 6COE 205 Lab Manual

COE Department 39 KFUPM (2000 )

Type Instruction Example Meaning

F. Flags

OF SF ZF AF PF CF

Shift

SHL SHL AX,1 Shift AX left by 1 bit. Fill vacated bit with 0.

* * * ? * *

SAL SAL AX,1 Shift AX left by 1 bit. Fill vacated bit with 0.

* * * ? * *

SHR SHR NUM2,CL Shift NUM2 right by the number of bits indicated in CL. Fill vacated bits with 0.

* 0 * ? * *

SAR SAR NUM2,CL As SHR but fill vacated bits with the sign bit.

* * * ? * *

Rotate

ROL ROL BH,CL Same as SHL, but shifted bits are fed back to fill vacated bits.

* - - - - *

RCL RCL BH,CL Same as ROL, but carry flag is appended as MSB, and its content is shifted with the number.

* - - - - *

ROR ROR NUM1,1 Same as SHR, but shifted bits are fed back to fill vacated bits.

* - - - - *

RCR RCR NUM1,1 Same as ROR, but carry flag is appended as LSB, and its content is shifted with the number.

* - - - -

Table 6. 1 : Summary of the Shift and Rotate Instructions of the 8086Microprocessor

Compare instruction :

The compare instruction is used to compare two numbers. At most one of these numbers may reside in memory. The compare instruction subtracts its source operand from its destination operand and sets the value of the status flags according to the subtraction result. The result of the subtraction is not stored anywhere. The flags are set as indicated in Table 6. 2.

Instruction Example MeaningCMP CMP AX, BX If (AX = BX) then ZF 1 and CF 0

If (AX < BX) then ZF 0 and CF 1If (AX > BX) then ZF 0 and CF 0

Table 6. 2: The Compare Instruction of the 8086 Microprocessor

Jump Instructions :

The jump instructions are used to transfer the flow of the process to the indicated operator. When the jump address is within the same segment, the jump is called intra- segment jump. When this address is outside the current segment, the jump is called inter-segment jump. An overview of all the jump instructions is given in Table 6. 3. Table 6. 4 lists the possible addressing modes used with the jump instructions. Whereas,Table 6. 5 gives examples on the use of such instructions.

Page 42: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 6COE 205 Lab Manual

COE Department 40 KFUPM (2000 )

Type Instruction Meaning (jump if) ConditionUnconditional JMP unconditional NoneComparisons JA jnbe above (not below or equal) CF = 0 and ZF = 0

JAE jnb above or equal (not below) CF = 0JB jnae below (not above or equal) CF = 1JBE jna below or equal (not above) CF = 1 or ZF = 1JE jz equal ( zero) ZF = 1JNE jnz not equal (not zero) ZF = 0JG jnle greater (not lower or equal) ZF = 0 and SF = OFJGE jnl greater or equal (not lower) SF = OFJL jnge lower (not greater or equal) (SF xor OF) = 1 i.e. SF OFJLE jng lower or equal (not greater) (SF xor OF or ZF) = 1JCXZ loop CX register is zero (CF or ZF) = 0

Carry JC Carry CF = 1JNC no carry CF = 0

Overflow JNO no overflow OF = 0JO overflow OF =1

Parity Test JNP jpo no parity (parity odd) PF = 0JP jpe parity (parity even) PF = 1

Sign Bit JNS no sign SF = 0JS sign SF = 1

Zero Flag JZ zero ZF = 1JNZ non-zero ZF = 0

Table 6. 3: Jump Instructions of the 8086 Microprocessor

Label Pointer

Range Addressing Mode

Specified By Encoded As Directive

Short +127/-128 bytes IP IP + Offset

Immediate Word Differentially* SHORT

Near Intra-segment IP Address

Immediate Word Differentially

NEAR PTRRegister Word Absolute address

Memory Word Absolute address

Far Inter-segment IP Address CS Segment

Immediate Double Word Absolute addressFAR PTR

Memory Double Word Absolute address

*Differentially = Difference between current and next address.

Table 6. 4 : Jump Instructions and Addressing Modes

Instruction Example MeaningJMP JMP FAR PTR [BX] IP [BX], CS [BX+2]

JNZ JNZ END If (ZF=0) Then IP Offset of END

JE JE FIRST If (ZF=1) Then IP Offset of FIRST

JC JC SECOND If (CF=1) Then IP Offset of SECOND

Table 6. 5: Examples of Jump Instructions of the 8086 Microprocessor

Page 43: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 6COE 205 Lab Manual

COE Department 41 KFUPM (2000 )

The LOOP Instructions :

The LOOP instruction is a combination of a DEC and JNZ instructions. It causes execution to branch to the address associated with the LOOP instruction. The branching occurs a number of times equal to the number stored in the CX register. All LOOP instructions are summarized in Table 6. 6.

Instruction Example MeaningLOOP LOOP Label1 If (CX0) then IP Offset Label1LOOPE LOOPZ

LOOPE Label1 If (CX0 and ZF = 0) then IP Offset Label1

LOOPNE LOOPNZ

LOOPNZ Label1 If (CX0 and ZF = 0) then IP Offset Label1

Table 6. 6: Summary of the LOOP Instructions.

The Loop Program Structure, Repeat-Until and While-Do:

Like the condionnal and unconditionnal jump instructions which can be used to simulate the IF-Then-Else structure of any programming language, the Loop instructions can be used to simulate the Repeat-Until and While-Do loops. These are used as shown in the following (Table 6. 7).

Structure Repeat-Until While-Do

Code

; Repeat until CX = 0 ; While (CX 0) Do- -MOV CX, COUNT MOV CX, COUNT

Again: - Again: JZ Next- -- -- -- -- -LOOP Again LOOP Again- Next: -- -

Table 6. 7 : The Loop Program Structure.

Page 44: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 6COE 205 Lab Manual

COE Department 42 KFUPM (2000 )

Pre Lab Work :

1. Complete program 6.1, according to the given guidelines.2. Check on some values and see if it is working properly.3. Comment on the program, trying to understand how conversion is done.4. Write program 6.2 and make sure it contains no errors.5. Do the modifications given in the guidelines. This will be program 6.3.6. Bring your work to the lab.

Lab Work:

1- Show program 6.1 and your comments to your lab instructor. 2- Run program 6.2 using CodeView.3- See what the effect of such program on NUM1 is.4- Run program 6.3, and see the effect on NUM1 after displaying NUM2.5- Modify program 6.2, using program 6.1, such that you enter an 8-bit

binary number from the keyboard, and invert swap the high and the low nibbles of the number, and finally display it. Call this program 6.4.

6- Show all your work to the instructor, and submit it at the end of the lab session.

Lab Assignment:

Write a program that prompts the user to enter an 8 bit binary number, between 0 and255. The program then inverts all bits according to the figure below. This program is useful in Signal Processing for the calculation of the Fast Fourier Transform (FFT). The operation is called Decimation (in time or frequency), and the bit manipulation is called bit shuffling i.e. rearrangement of bits.

7 6 5 4 3 2 1 0

Bit ( i ) Bit ( 7- i ) for i = 0 – 7

Figure 6. 1 : Bit Shuffling

Page 45: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 6COE 205 Lab Manual

COE Department 43 KFUPM (2000 )

TITLE “Experiment 6, Program 1”; This program adds 2 binary numbers and prints the result in binary format

.MODEL SMALL

.STACK 200

.DATACRLF DB 0DH, 0AH, '$'PROMPT1 DB 'Enter the first 8-bit binary number: ','$' PROMPT2 DB 'Enter the second 8-bit binary number: ','$' PROMPT3 DB 'The sum of the two numbers in binary is: ','$' NUM1 DW ?NUM2 DW ?

.CODE

.STARTUP

.EXIT

; DISPLAY PROMPT1; READ AND CONVERT THE FIRST NUMBER

CALL READ

MOV NUM1,BX ; READ FROM STACK

MOV DX, OFFSET CRLF MOV AH, 09HINT 21H; DISPLAY PROMPT2

; READ AND CONVERT THE SECOND NUMBER CALL READMOV NUM2,BX ; READ FROM STACK

MOV BX, NUM1ADD BX, NUM2 ; ADD THE TWO NUMBERS;DISPLAY PROMPT3 CALL RESULT

;***************************************************; PROC READ A NUMBER AND CONVERT IT TO BINARY READ PROC NEAR

MOV BX, 0000MOV CX, 0008 MOV AH, 01H

L1: INT 21HSUB AL, 30H SHL BL, 1 OR BL, AL LOOP L1 XOR BH, BH RET

READ ENDP END

Page 46: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 6COE 205 Lab Manual

COE Department 44 KFUPM (2000 )

;***************************************************; PROC. DISPLAY RESULT RESULT PROC NEAR

MOV CX, 0008 ; DISPLAYING CLC

NEXT: RCL BL, 1 JNC BIT_0 MOV DL, '1' MOV AH, 02H INT 21HJMP LAST

BIT_0: MOV DL, '0' MOV AH, 02H INT 21H

LAST: LOOP NEXT RET

RESULT ENDP

;***************************************************;***************************************************TITLE “PROGRAM 2 EXPERIMENT 6”; This program shows how to manipulate a two-digit numbers

.MODEL SMALL

.STACK 200

.DATANUM1 DB ? NUM2 DB ?

.CODE

.STARTUP

; READ NUMBER NUM1

MOV AL, NUM1AND AL, 0FH MOV CL, 04H SHL AL,CL MOV BL, AL

MOV AL, NUM1 AND AL, 0F0H

MOV CL, 04H SHR AL, CL

OR BL, AL MOV NUM2, BL

; DISPLAY NUMBER NUM1

.EXIT END

; CONVERT NUM2 TO BINARY; DISPLAY NUMBER NUM2

Page 47: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 8COE 205 Lab Manual

COE Department 45 KFUPM (2000 )

Experiment No 7

Subroutine Handling Instructions and Macros

Introduction:

In this experiment you will be introduced to subroutines and how to call them. You will verify the exchange of data between a main program and a subroutine in the 8086 environment. You will also use Macros, and as applications you will deal to a useful data representation: look-up tables. .

You will need some of the programs developed in previous experiments to rewrite them in a more structured way.

Objectives:

1- Procedures and Procedure Calls2- Parameter Passing through Memory, Registers and the Stack 3- Use of Macros4- Look-up Tables5- Real-time clock reading,

References: Textbook:

- Section 3.4,- Section 3.5,- Lecture notes.

Macros:

Macro sequences relieve the programmer from retyping the same instructions. They allow you create your own pseudo language for instruction sequences that often appear in programming. A macro sequence starts by the MACRO directive and ends by an ENDM directive. Associated with MACRO is the name of the macro and any parameters that are carried with the macro to the instructions between MACRO and ENDM statements. Program 7.3 contains two macros. A MACRO is declared and used as shown in the following example

DISPLAY MACRO STRINGMOV DX,OFFSET STRING MOV AH,09HINT 21H

ENDM

;If “Message”is the string to be displayed, the; Macro is called as follows:

DISPLAY MESSAGE

Page 48: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 8COE 205 Lab Manual

COE Department 46 KFUPM (2000 )

Macros can be saved in a separate file, to which a name such as “MACRO.INC” can be given. This file can then be used as a library, and therefore can be included in the program using the directive INCLUDE, in the following manner:

INCLUDE MACRO.INC

Provided that both, the program and the macro library are in the same directory. Alternatively the path has to be specified as follows:

INCLUDE Path\MACRO.INC

Labels local to a Macro :

When a MACRO contains labels, and the Macro is used more than once in a program, which is usually the case, the assembler gives the following error: Label referenced more than once. To avoid such an error, these labels should be made local to the MACRO, this is done using the following:

DISPLAY MACRO STRINGLocal Label1

Label1:……

ENDM

The Stack:

The stack is a special segment in memory used to facilitate subroutine handling. The SS register contains the Stack Segment number where the stack is stored. The ".STACK" directive instructs the assembler to reserve a stack segment of a desired size. For example, to reserve a stack segment of size 80 bytes, “.STACK 50” is used before the ".CODE" directive. In this case, the “.STACK” directive initializes the Stack Pointer to 50H. If the “.STACK” directive is missing from a program, the assembler issues the warning: “LINK: Warning L4021: no stack segment”.

The stack always starts at a high address and grows towards the beginning of the stack segment at a lower address. When a program starts, the stack is empty, and its size is zero. The microprocessor stores data on the stack as needed, and uses the SP register to point to the last item stored on the stack. The stack size dynamically changes as data is stored or retrieved from the stack.

The stack handling instructions are summarized in Table 7. 1. The PUSH instruction is used to store the content of a 16-bit register, or memory location, on the stack. It first decreases the content of SP by two and then stores the data into the two bytes on the top of the stack. The high order byte of the data goes to the high addressed byte in the stack.

Page 49: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 8COE 205 Lab Manual

COE Department 47 KFUPM (2000 )

Instruction Example MeaningPUSH PUSH AX [SP] AH

[SP-1] ALSP SP –2

POP POP NUM1 [NUM1] [SP] [NUM+1] [SP+1] SP SP + 2

PUSHF PUSHF [SP-1] MSB(FR)[SP-2] LSB(FR) SP SP –2

POPF POPF LSB(FR) [SP] MSB(FR) [SP+1] SP SP + 2

Note: FR = Flag Register

Table 7. 1 : Summary of the Satck Handling Instructions

The PUSHF instruction is similar to the PUSH instruction, except that the PUSHF is used to push the contents of the flag register onto the stack. The POP and POPF instructions have a reverse action of the PUSH and PUSHF, respectively. The POP instruction retrieves a word from the stack and then increases SP by two. The POPF has the same effect, except that the word retrieved is saved to the flag register.

Subroutine calls :

A procedure is a reusable section of the software that is stored in memory once, but used as often as necessary. The CALL instruction links to the procedure and the RET (return) instruction returns from the procedure. The Stack stores the return address whenever a procedure is called during the execution of a program. The CALL instruction pushes the address of the instruction following the CALL (return address) onto the stack. The RET instruction removes an address from the stack, so the program returns to the instruction following the CALL.

With the Assembler (MASM) there are specific ways for writing, and storing, procedures. A procedure begins with the PROC directive and ends with the ENDP directive. Each directive appears with the name of the procedure. The PROC directive is followed by the type of the procedure: NEAR (intra-segment) or FAR (inter- segment).

In MASM version 6.X, a NEAR or FAR procedure can be followed by the USES statement. The USES statement allows any number of registers to be automatically pushed onto the stack and popped from the stack within the procedure.

Procedures that are to be used by all software (global) should be written as FAR procedures. Procedures that are used by a given task (local) are normally defined as NEAR procedures.

Page 50: 2016)/EE/Naila_Munaf/Lab... · Web vie

Experiment No 8COE 205 Lab Manual

COE Department 48 KFUPM (2000 )

The CALL Instruction:

The CALL instruction transfers the flow of the program to the procedure. The CALL instruction differs from the jump instruction in the sense that a CALL saves a return address on the stack. The RET instruction return control to the instruction that immediately follows the CALL. There exist two types of calls: FAR and NEAR, and two types of addressing modes used with calls, Register and Indirect Memory modes.

Near CALL:

A near CALL is three bytes long, with the first byte containing the opcode, and the two remaining bytes containing the displacement or distance of 32 K. When a NEAR CALL executes, it pushes the offset address of the next instruction on the stack. The offset address of the next instruction appears in the IP register. After saving this address, it then adds the displacement from bytes 2 and 3 to the IP to transfer control to the procedure. A variation of NEAR CALL exists, CALLN, but should be avoided.

Far CALL:

The FAR CALL can call a procedure anywhere in the system memory. It is a five- byte instruction that contains an opcode followed by the next value for the IP and CS registers. Bytes 2 and 3 contain the new contents of IP, while bytes 4 and 5 contain the new contents for CS. The FAR CALL instruction places the contents of both IP and CS on the stack before jumping to the address indicated by bytes 2 to 5 of the instruction. This allows a call to a procedure anywhere in memory and return from that procedure. A variant of the FAR CALL is CALLF but should be avoided.

CALLs with register operand :

CALLs can contain a register operand. An example is CALL BX, in which the content of IP is pushed into the stack, and a jump is made to the offset address located in register BX, in the current code segment. This type of CALL uses a 16-bit offset address stored in any 16-bit register, except the segment registers.

Program 7.1 illustrates the use of the CALL register instruction to call a procedure that begins at offset address DISP. The offset address DISP is placed into the BX register, then the CALL BX instruction calls the procedure beginning at address DISP. This program displays “OK” on the monitor screen.

CALLs with Indirect Memory Address :

A CALL with an indirect memory address is useful when different subroutines need to be chosen in a program. This selection process is often keyed with a number that addresses a CALL address in a lookup table.

Program 7.2 shows three separate subroutines referenced by Number 1,2 and 3 as read from the keyboard. The calling sequence adjusts the value of AL and extends it to a 16-bit number before adding it to the location of the lookup table. This references one