coe 205 lab manual

110
King Fahd University of Petroleum and Minerals College of Computer Science and Engineering Computer Engineering Department COE 205 Computer Organization and Assembly Language Lab Manual Prepared By: Mr. Kamal Chenaoua (2000/2001)

Upload: madhu1983aug30

Post on 20-Jul-2016

34 views

Category:

Documents


8 download

DESCRIPTION

computer architecture

TRANSCRIPT

Page 1: COE 205 Lab Manual

King Fahd University of Petroleum and Minerals

College of Computer Science and Engineering

Computer Engineering Department

COE 205

Computer Organization and Assembly Language

Lab Manual

Prepared By:

Mr. Kamal Chenaoua (2000/2001)

Page 2: COE 205 Lab Manual

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: COE 205 Lab Manual

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 MASM 2) Input and Output 3) Segmentation and Addressing Modes 4) Indexing and Data Manipulation 5) Logic Instructions 6) Shift Rotate and Jump Instructions 7) Subroutine Handling Instructions and Macros 8) String Handling Instructions 9) Accessing Video Memory 10) Interrupts 11) Using the Mouse 12) 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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 1

COE Department KFUPM (2000 ) 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 program 3- Use of the Dos Debugger program 4- 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 PRODUCES 1 Editing Source File 2 Assembling Object File 3 Linking Executable File 4 Executing Results

Table 1.1: Assembly Language Programming Phases

Page 5: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 1

COE Department KFUPM (2000 ) 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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 1

COE Department KFUPM (2000 ) 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 SYNTAX Assemble A [address] Compare C range address Dump D [range] Enter E address [list] Fill F range list Go G [=address] [addresses] Hex H value1 value2 Input I port Load L [address] [drive] [first sector] [number] Move M range address Name N [pathname] [argument list] Output O port byte Proceed P [=address] [number] Quit Q Register R [register] Search S range list Trace 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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 1

COE Department KFUPM (2000 ) 5

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

COMMAND FILE NAME 1 Edit, any editor will do Name.asm 2 Masm Filename Name.obj 3 Link Filename Name.exe 4 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 File Create 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 file ml /Fl /Zi proj.asm

Page 8: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 1

COE Department KFUPM (2000 ) 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 Program Your 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 list when 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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 1

COE Department KFUPM (2000 ) 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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 1

COE Department KFUPM (2000 ) 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 25 By: MULT1 EQU 25H,

and run the program again. What do you notice? 9- Can you explain what the program does?

Page 11: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 1

COE Department KFUPM (2000 ) 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,2000H MOV CX,10100110B MOV DX, -4567 MOV AL,'A' MOV AH,'a' MOV AX,4C00H INT 21H END ___________________________________________________________________ ; COE 205: Lab Exp. # 1 Program # 2 ; Student Name: Student ID: Section: TITLE "Our second program" .MODEL SMALL .STACK 32 .DATA

MULT1 EQU 25 MULT2 DW 5 .CODE

MOV AX,@DATA MOV DS,AX

MOV AX,00 MOV BX,MULT1 MOV CX,MULT2 MULT: ADD AX,BX DEC CX JNZ MULT MOV DX,AX MOV AX,4C00H INT 21H END

Page 12: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 2

COE Department KFUPM (2000 ) 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 Effect 01H AH AL Read a character with echo on the

screen. 02H, 06H AH,

Character in DL No output Display a character on the screen.

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

‘$’ sign 0AH AH Offset in

DX Read a string of characters from the keyboard

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

Page 13: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 2

COE Department KFUPM (2000 ) 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, 06H MOV 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’, ‘$’ .CODE

MOV DX, OFFSET MESSAGE MOV AH, 09H INT 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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 2

COE Department KFUPM (2000 ) 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 Keyboard Entry 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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 2

COE Department KFUPM (2000 ) 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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 2

COE Department KFUPM (2000 ) 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 2 5- Replace the line: MOV DX, OFFSET MESSAGE

by: LEA DX, MESSAGE Then 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 3 8- 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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 2

COE Department KFUPM (2000 ) 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 .DATA X 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 .DATA MESSAGE DB ‘This is the message to be displayed’,’$’ .STACK 200 .CODE

MOV AX,@DATA MOV DS, AX MOV DX, OFFSET MESSAGE MOV AH, 09H INT 21H

MOV AX, 4C00H ; Exit to DOS

INT 21H END

Page 18: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 2

COE Department KFUPM (2000 ) 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 .DATA MESSAGE 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,09H INT 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,09H INT 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, MESSAGE2

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

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

Page 19: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 3

COE Department KFUPM (2000 ) 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 processor 2- 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.

Source operand Assuming: DS = 1000H, BX = 0200H, SI = 0300H

Addressing Mode

Example

Type Address Generation Address

Register MOV AX,BX Register - - Immediate MOV AX, 0F7H Immed. - - Direct MOV AX,[1234H] Mem. DS x 10H +1234H 11234H Register-Indirect MOV AX,[BX] Mem. DS x 10H +0200H 10200H Based MOVAX,[BX+06] Mem. DS x 10H +0200H + 0006H 10206H Indexed MOVAX,[SI+06] Mem. DS x 10H +0300H + 0006H 10306H Based-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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 3

COE Department KFUPM (2000 ) 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

.STACK

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

.DATA

Assembler directive that reserves a memory space for constants and variables .CODE

Assembler directive that defines the program instructions END

Assembler 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 combined SMALL Code and data segments must be no more than 64KB each MEDIUM Code can be more than 64KB, data still limited to no more than

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

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

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

larger than 64KB

Table 3.3: Memory Models

Page 21: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 3

COE Department KFUPM (2000 ) 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 .EXIT directive, which has exactly the same effect.

Page 22: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 3

COE Department KFUPM (2000 ) 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-2 3. 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 character MOV 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_read

Again: Start loop here ; Convert to small letters.

LOOP Again

Page 23: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 3

COE Department KFUPM (2000 ) 21

; This program displays a string terminated by a $ sign using INT 21H function 09H. TITLE “Program 3-1” .MODEL SMALL .STACK 200 .DATA MESSAGE 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 MOV AX,@DATA MOV DS,AX

LEA DX,MESSAGE MOV AH,09H INT 21H MOV AH, 0AH MOV DX, OFFSET BUF INT 21H LEA DX,MESSAGE2 MOV AH,09H INT 21H LEA DX, BUF MOV AH,09H INT 21H MOV AX,4C00H INT 21H

END

Page 24: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 3

COE Department KFUPM (2000 ) 22

TITLE “PROGRAM 2 EXPERIMENT 3” ; This program displays a message and reads a new message from the keyboard .MODEL SMALL .STACK 200 .DATA

CRLF 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,09H INT 21H MOV AH,0AH ;read into buffer

LEA DX, BUFFER INT 21H

LEA DX, CRLF ;move cursor to next line MOV AH,09H INT 21H LEA DX,STRING1 ;display string1 MOV AH,09H INT 21H ;now display the buffer i.e. what has been read. MOV AH,09H MOV BH,00H MOV 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,09H INT 21H LEA DX, CRLF ;move cursor to next line MOV AH,09H INT 21H

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

Page 25: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 3

COE Department KFUPM (2000 ) 23

COE 205

Experiment 3, Program #1:

Section: Student Name: Date: Student ID:

Source Destination Addressing Mode

Contents

Instruction Address/

Register Content Address/

Register Before After

MOV AX,@DATA

MOV DS,AX

LEA DX,MESSAGE

MOV AH,09H

INT 21H Before INT 21H, IP = After INT 21H, IP =

MOV AH, 0AH

MOV DX, OFFSET BUF

INT 21H Before INT 21H IP = After INT 21H IP =

LEA DX,MESSAGE2

MOV AH,09H

INT 21H Before INT 21H IP = After INT 21H IP =

LEA DX, BUF

MOV AH,09H

INT 21H Before INT 21H IP = After INT 21H IP =

MOV AX,4C00H

INT 21H S k i p

Page 26: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 3

COE Department KFUPM (2000 ) 24

COE 205

Experiment 3, Program #2:

Section: Student Name: Date: Student ID:

Addressing Modes

Instructions Source

Destination

LEA DX,PROMPT MOV AH,09H INT 21H MOV AH,0AH LEA DX, BUFFER INT 21H LEA DX, CRLF MOV AH,09H INT 21H LEA DX,STRING1 MOV AH,09H INT 21H MOV AH,09H MOV BH,00H MOV BL,BUFFER[1] MOV BUFFER[BX+2],'$' LEA DX,BUFFER[2] INT 21H LEA DX,STRING2 MOV AH,09H INT 21H LEA DX, CRLF MOV AH,09H INT 21H MOV AH, 02H MOV DL,BUFFER[1] ADD DL, 30H INT 21H MOV AX,4C00H INT 21H

Page 27: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 4

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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 4

COE Department KFUPM (2000 ) 26

Table 4.1: ASCII Table

Character Column # Row # Code (H) Code (10) a 6 1 61 96 + 1 = 97 A 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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 4

COE Department KFUPM (2000 ) 27

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,33 RowSize EQU 3 Based addressing mode: MOV BX, OFFSET Array1 ; Address Array1 MOV AL,[BX+4] ; Access 5th element of Array1 Indexed addressing mode: MOV DI, OFFSET Array2 ; Address Array2 MOV [DI+6],AL ; Copy to 7th element of Array2 MOV SI,3 MOV 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 row MOV 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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 4

COE Department KFUPM (2000 ) 28

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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 4

COE Department KFUPM (2000 ) 29

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 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: ','$' .CODE .STARTUP LEA DX,PROMPT1 ;DISPLAY PROMPT1 MOV AH,09H INT 21H MOV AH,01H ;READ FIRST NUMBER INT 21H SUB AL,30H ;Convert character to number

MOV CL,AL ;SAVE THE NUMBER IN CL LEA DX,CRLF ;MOVE CURSOR TO NEXT LINE MOV AH,09H INT 21H

LEA DX,PROMPT2 ;DISPLAY PROMPT2 MOV AH,09H INT 21H MOV AH,01H ;READ SECOND NUMBER INT 21H SUB AL,30H ;Convert character to number ADD AL,CL ;PERFORM ADDITION AND SAVE RESULT IN CL MOV CL,AL ADD CL,30H ;CONVERT DIGIT TO CHARACTER LEA DX,CRLF ;MOVE CURSOR TO NEXT LINE MOV AH,09H INT 21H LEA DX,PROMPT3 ;DISPLAY PROMPT3 MOV AH,09H INT 21H MOV DL,CL ;DISPLAY SUM MOV AH,02H INT 21H .EXIT END

Page 32: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 4

COE Department KFUPM (2000 ) 30

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 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 ? .CODE .STARTUP LEA DX,PROMPT1 ;DISPLAY PROMPT1 MOV AH,09H INT 21H MOV AH,01H ;READ FIRST NUMBER INT 21H SUB AL,30H ;Convert character to number MOV NUM1,AL ;SAVE NUM1 LEA DX,CRLF ;MOVE CURSOR TO NEXT LINE MOV AH,09H INT 21H LEA DX,PROMPT2 ;DISPLAY PROMPT2 MOV AH,09H INT 21H MOV AH,01H ;READ SECOND NUMBER INT 21H SUB AL,30H ;Convert character to number MOV NUM2,AL ;SAVE NUM2 ADD AL,NUM1 ;PERFORM ADDITION MOV RES,AL ;SAVE RESULT IN RES LEA DX,CRLF ;MOVE CURSOR TO NEXT LINE MOV AH,09H INT 21H LEA DX,PROMPT3 ;DISPLAY PROMPT3 MOV AH,09H INT 21H ;DISPLAY SUM MOV DL,RES ;RETREIVE RES FROM MEMORY ADD DL,30H ;CONVERT DIGIT TO CHARACTER MOV AH,02H INT 21H .EXIT END

Page 33: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 5

COE Department KFUPM (2000 ) 31

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 Instructions 2- 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.

Flags Affected Type Instruction Example Meaning OF SF ZF AF PF CF

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

Addition

DAA DAA ? * * * * * SUB SUB CL,AH CL ← CL – AH * * * * * * SBB SBB CL,AH CL ← CL – AH – CF * * * * * * DEC DEC DAT [DAT] ← [DAT] – 1 * * * * * - DAS DAS ? * * * * *

Subtraction

NEG NEG CX CX ← 0 – CX * * * * * * MUL MUL CL

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

* ? ? ? ? * Multiplication

IMUL IMUL BYTE PTR X IMUL WORD PTR X

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

* ? ? ? ? *

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

? ? ? ? ? ? Division

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

? ? ? ? ? ?

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

Table 5.1: Summary of Arithmetic Instructions of the 8086 microprocessor

Page 34: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 5

COE Department KFUPM (2000 ) 32

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.

Flags Instruction Example Meaning

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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 5

COE Department KFUPM (2000 ) 33

Operation Effect b AND 0 = 0 Reset the bit b OR 1 = 1 Set the bit b XOR 1 = b Complement the bit b 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 21H SUB AL, 30H MOV CH, AL ; Read high digit e.g. 8 MOV AH, 01H INT 21H SUB 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 left XOR AH, AH ; Clear AH

OR 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, CL DAA ; 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 AL

XOR AH, AH ; Clear AH MOV BL, 10000B DIV 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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 5

COE Department KFUPM (2000 ) 34

; Now Display AL as high digit first MOV AL, CL ; Read number again

AND 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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 5

COE Department KFUPM (2000 ) 35

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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 5

COE Department KFUPM (2000 ) 36

TITLE “Program 5.1: Logic Instructions” ; This program shows the effect of the logic instructions .MODEL SMALL .STACK 200 .DATA

NUM1 DW 0FA62H NUM2 DB 94H .CODE .STARTUP

MOV AX, NUM1 ;load AX with number NUM1

AND AX, 0FFDFH ;Reset 6th bit of AX OR AL, 20H ;Set 6th bit of AL

XOR NUM1, 0FF00H ;Complement the high order byte of ; NUM1 NOT NUM2 ;Complement NUM2 XOR AX, AX ;Clear AX MOV AX, NUM1 AND AX, 0008H ; Isolate bit 4 of NUM1 XOR AX, 0080H ;Complement 4th bit of AX .EXIT END Fill in table 5.3 while running the above program using CodeView.

Destination Content Status Flags Statement

Before After OF

DF

IF

SF

ZF

AF

PF

CF

1. MOV AX, NUM1 2. AND AX, 0FFDFH 3. OR AL, 20H 4. XOR NUM1, 0FF00H 5. NOT NUM2 6. XOR AX, AX 7. MOV AX, NUM1 8. AND AX, 0008H 9. XOR AX, 0080H

Table 5.4: Effects of Executing Program 5.1

Page 39: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 5

COE Department KFUPM (2000 ) 37

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

RADIX DB 10 ;radix: 10 for decimal NUM DW 0EFE4H ;the number to be converted ;put here any other number.

;Note that: 0EFE4H = 6141210 TEMP DB 10 DUP(?) ;Used to simulate a stack

.CODE .STARTUP

MOV AX, NUM ;load AX with number NUM ;display AX in decimal

MOV CX, 0 ;clear digit counter XOR BH, BH ;clear BH MOV BL, RADIX ;set for decimal XOR SI, SI ;Clear SI register DISPX1: MOV DX, 00 ;clear DX DIV BX ;divide DX:AX by 10 MOV TEMP[SI], DL ;save remainder INC SI INC CX ;count remainder OR AX, AX ;test for quotient of zero JNZ DISPX1 ;if quotient is not zero DEC SI DISPX2: MOV DL, TEMP[SI] ;get remainder MOV AH, 06H ;select function 06H ADD DL, 30H ;convert to ASCII INT 21H ;display digit DEC SI DEC CX ;repeat for all digits JNZ DISPX2 .EXIT ;exit to dos END

Page 40: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 6

COE Department KFUPM (2000 ) 38

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 change their 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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 6

COE Department KFUPM (2000 ) 39

F. Flags Type

Instruction

Example

Meaning OF SF ZF AF PF CF

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 * ? * *

Shift

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

* * * ? * *

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.

* - - - - *

Rotate

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 8086

Microprocessor 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 Meaning

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

CMP

CMP AX, BX

If (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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 6

COE Department KFUPM (2000 ) 40

Type Instruction Meaning (jump if) Condition Unconditional JMP unconditional None

JA jnbe above (not below or equal) CF = 0 and ZF = 0 JAE jnb above or equal (not below) CF = 0 JB jnae below (not above or equal) CF = 1 JBE jna below or equal (not above) CF = 1 or ZF = 1 JE jz equal ( zero) ZF = 1 JNE jnz not equal (not zero) ZF = 0 JG jnle greater (not lower or equal) ZF = 0 and SF = OF JGE jnl greater or equal (not lower) SF = OF JL jnge lower (not greater or equal) (SF xor OF) = 1 i.e. SF ≠ OF JLE jng lower or equal (not greater) (SF xor OF or ZF) = 1

Comparisons

JCXZ loop CX register is zero (CF or ZF) = 0 JC Carry CF = 1 Carry JNC no carry CF = 0 JNO no overflow OF = 0 Overflow JO overflow OF =1 JNP jpo no parity (parity odd) PF = 0 Parity Test JP jpe parity (parity even) PF = 1 JNS no sign SF = 0 Sign Bit JS sign SF = 1 JZ zero ZF = 1 Zero Flag JNZ 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

Immediate Word Differentially

Register Word Absolute address

Near Intra-segment IP Address

Memory Word Absolute address

NEAR PTR

Immediate Double Word Absolute address

Far Inter-segment IP Address CS Segment Memory Double Word Absolute address

FAR PTR

*Differentially = Difference between current and next address.

Table 6. 4: Jump Instructions and Addressing Modes Instruction Example Meaning JMP 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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 6

COE Department KFUPM (2000 ) 41

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 Meaning LOOP LOOP Label1 If (CX≠0) then IP Offset Label1 LOOPE LOOPZ

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

LOOPNE LOOPNZ

LOOPNZ Label1 If (CX≠0 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 - MOV CX, COUNT Again: - - - - - - LOOP Again - -

; While (CX ≠ 0) Do - MOV CX, COUNT Again: JZ Next - - - - - LOOP Again Next: - -

Table 6. 7: The Loop Program Structure.

Page 44: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 6

COE Department KFUPM (2000 ) 42

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 and 255. 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.

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

Figure 6. 1: Bit Shuffling

7 6 5 4 3 2 1 0

Page 45: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 6

COE Department KFUPM (2000 ) 43

TITLE “Experiment 6, Program 1” ; This program adds 2 binary numbers and prints the result in binary format .MODEL SMALL .STACK 200 .DATA

CRLF 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 ; DISPLAY PROMPT1 ; READ AND CONVERT THE FIRST NUMBER

CALL READ MOV NUM1,BX ; READ FROM STACK MOV DX, OFFSET CRLF MOV AH, 09H INT 21H ; DISPLAY PROMPT2

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

MOV BX, NUM1 ADD BX, NUM2 ; ADD THE TWO NUMBERS ;DISPLAY PROMPT3 CALL RESULT .EXIT ;*************************************************** ; PROC READ A NUMBER AND CONVERT IT TO BINARY READ PROC NEAR MOV BX, 0000 MOV CX, 0008 MOV AH, 01H L1: INT 21H

SUB AL, 30H SHL BL, 1 OR BL, AL LOOP L1 XOR BH, BH RET READ ENDP END

Page 46: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 6

COE Department KFUPM (2000 ) 44

;*************************************************** ; 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 21H

JMP 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 .DATA

NUM1 DB ? NUM2 DB ?

.CODE .STARTUP ; READ NUMBER NUM1 MOV AL, NUM1 AND 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 ; CONVERT NUM2 TO BINARY ; DISPLAY NUMBER NUM2 .EXIT END

Page 47: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 8

COE Department KFUPM (2000 ) 45

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 Calls 2- Parameter Passing through Memory, Registers and the Stack 3- Use of Macros 4- Look-up Tables 5- 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 STRING

MOV DX,OFFSET STRING MOV AH,09H INT 21H

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

DISPLAY MESSAGE

Page 48: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 8

COE Department KFUPM (2000 ) 46

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 STRING

Local 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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 8

COE Department KFUPM (2000 ) 47

Instruction Example Meaning PUSH PUSH AX [SP] AH

[SP-1] AL SP 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: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 8

COE Department KFUPM (2000 ) 48

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

Page 51: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 8

COE Department KFUPM (2000 ) 49

of the three subroutines using the CALL TABLE[BX] instruction. When this program executes, the letter A is displayed when a 1 is typed, B if 2 and C if 3 is typed. The CALL instruction can also reference far pointers if the data in the table are defined as double-word data with the DD directive, using the CALL FAR PTR[SI] or CALL TABLE[SI] instructions. These instructions retrieve a 32-bit address from the data segment memory location addressed by SI and use it as the address of a far procedure. Parameter Passing: To pass data (parameters) between the main program and the routines, data may be left in the general-purpose registers. This method has the disadvantage of changing the contents of the registers every time the subroutine is called. A more elegant way is to exchange data through the stack, or through memory. The data to be passed to a subroutine is saved in the memory before calling the subroutine. All the registers that need to be saved, and are used by the subroutine, should also be saved and retrieved afterwards.

Instruction Example Effect CALL CALL SQRT [SP-1] 34

[SP-2] 5B SP SP-2 IP 34A0

RET RET LSB(IP) [SP] MSB(IP) [SP+1] SP SP + 2

Note: Assuming SQRT is a Near Procedure, starting at CS:34A0H, and the instruction

CALL is at CS:345BH.

Table 7. 2: Summary of the Subroutine Handling Instructions Reading the System Date: Function 2AH, INT 21H: Function 2AH of Interrupt INT 21H is used to read the system date. It returns the Day of the week in AL register, the year in CX register, the month in DH register and the day of the month in DL register. Note that as indicated in Table 7. 3, the returned values are in hexadecimal format, which, in order to be displayed, need to be converted to decimal, as indicated in experiment 5.

Page 52: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 8

COE Department KFUPM (2000 ) 50

Effect: Read system date Function

ENTRY Exit

AL = Day of the week CX = Year (1980-2099) 2AH AH = 2AH DH = Month DL = Day of the month

Note The day of the week is encoded as Sunday = 00 through Saturday = 06. The year is a binary number equal to 1980 through 2099.

Table 7. 4: Read Time and Date Function: 2AH, INT 21H

Note on the use of the XLAT instruction: The XLAT instruction adds the contents of AL to the contents of BX to form an address in a look-up-table. It then transfers the contents of the data at that address [BX+AL] to the AL register. MOV BX, OFFSET TABLE ; BX Offset TABLE MOV AL, INDEX ; AL Index of the element in table XLAT ; AL [BX+AL] ; AL will contain the data in TABLE at index INDEX.

Page 53: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 8

COE Department KFUPM (2000 ) 51

Pre Lab Work:

1. Write, assemble, link and run program 7.1 and 7.2. Try to understand how the different routines are written and how they are called. See also how the different procedures pass parameters between them.

2. Write, assemble, link and run program 7.3. See how Macros are used. 3. Rewrite program 6.1, from Experiment 6, using Procedures and Macros.

Call it program 7.4. 4. Bring your work to the lab.

Lab Work:

1- Show programs 7.3 and 7.4 to your lab instructor. 2- Modify program 6.3, from experiment 6, using Procedures and Macros.

Call it program 7.5. 3- Program 7.4 reads a string and encrypts it. Complete the program and use

Macros and Procedures. 4- Modify Program 7.4, so that it reads an encrypted string and converts it

back to the original one. Write this program using procedures and Macros. Call it program 7.6.

Lab Assignment: DOS Function 2CH reads the system time, and works as described below:

MOV AH,2CH INT 21H ; and returns (in binary) the time as follows: CH: hours (0-23); CL: minutes (0-59); DH: seconds (0-59); and DL: hundredths of a second.

Use program 7.3, and the above function, to develop a program that reads the date, and displays it in the following format:

Today is: Sunday 24/October/1999, The Time is: 12:02:32 Make the program loop for a large number of times, so that you can see the time changing.

Page 54: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 8

COE Department KFUPM (2000 ) 52

TITLE “Program 7.1” ; a program that display OK on the monitor screen using procedure DISP .MODEL TINY ; select TINY model .CODE ; indicate start of CODE segment .STARTUP ; indicate start of program MOV BX, OFFSET DISP ; address DISP with BX MOV DL, 'O' ; display 'O' CALL BX MOV DL, 'K' ; display 'K' CALL BX .EXIT ; exit to DOS ; ; a procedure that displays the ASCII contents of DL on the monitor screen. ; ************************************************** DISP PROC NEAR MOV AH, 2 ; select function 02H INT 21H ; execute DOS function RET ; return from procedure DISP ENDP END ; end of file ; ___________________________________________________________________ TITLE “Program 7.2” ; program that uses a CALL lookup table to access one of three different procedures: ; ONE, TWO, or THREE. .MODEL SMALL ; select SMALL model .DATA ; indicate start of DATA segment

TABLE DW ONE ; define lookup table DW TWO DW THREE .CODE ; indicate start of CODE segment ONE PROC NEAR MOV AH, 2 ; display a letter A MOV DL, 'A' INT 21H RET ONE ENDP TWO PROC NEAR MOV AH, 2 ; display letter B MOV DL, 'B' INT 21H RET TWO ENDP

Page 55: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 8

COE Department KFUPM (2000 ) 53

THREE PROC NEAR MOV AH, 2 ; display letter C MOV DL, 'C' INT 21H RET THREE ENDP ; Start of Main Program .STARTUP TOP: MOV AH, 1 ; read key into AL INT 21H SUB AL, 31H ; convert from ASCII to 0, 1, or 2 JB TOP ; if below 0 CMP AL, 2 JA TOP ; if above 2 MOV AH, 0 ; form lookup address MOV BX, AX ADD BX, BX CALL TABLE [BX] ; call procedure ONE, TWO, or THREE .EXIT ; exit to DOS END ; end of file ; ___________________________________________________________________ TITLE “Program 7.3” ; This program uses the function read time and displays the current day .MODEL SMALL ; select SMALL model .STACK 100 .DATA CRLF DB 0DH,0AH,'$' PROMPT1 DB 'Today is : ','$' DAY DW D0,D1,D2,D3,D4,D5,D6 D0 DB ‘SUNDAY’,’$’ D1 DB ‘MONDAY’,’$’ D2 DB ‘TUESADY’,’$’ D3 DB ‘WEDNESDAY’,’$’ D4 DB ‘THURSDAY’,’$’ D5 DB ‘FRIDAY’,’$’ D6 DB ‘SATURDAY’,’$’ .CODE .STARTUP

; Display Prompt1 MOV AH, 2AH ;GET SYSTEM DATE

INT 21H MOV SI, OFFSET DAY MOV AH, 00 ADD AX, AX ADD SI, AX MOV DX, [SI] MOV AH, 09H INT 21H LEA DX, CRLF ;MOVE CURSOR TO NEXT LINE MOV AH, 09H INT 21H .EXIT END

Page 56: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 8

COE Department KFUPM (2000 ) 54

TITLE “Program 7.4” ; This program reads a string of 200 characters max. and encrypts it. .MODEL SMALL .STACK 100 .DATA CRLF DB 0DH,0AH,'$' PROMPT1 DB 'Enter a string : ','$' STRING DB 100 DUP(?) CODED DB 100 DUP(?) UTAB DB 'MNBVCXZLKJHGFDSAPOIUYTREWQV' LTAB DB 'bgtnhymjukilopvfrcdexswzaq' .CODE .STARTUP

; DISPLAY PROMPT1

; Read a string from the keyboard, save it in the array STRING

; Scan the string STRING, and do the following: ; if character is an upper case letter ; that is: ; if AL >= 'A' and AL =< 'Z'

MOV BX, OFFSET LTAB

SUB AL, 41H XLAT ; Save the character in AL in the array CODED. ; if character is a lower case letter ; i.e. ; if AL >= 'a' and AL =< 'z' MOV BX, OFFSET UTAB SUB AL, 61H XLAT ; Save the character in AL in the array CODED. ; MOVE CURSOR TO NEXT LINE

; Display the array CODED. ; exit to DOS

END

Page 57: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 8

COE Department KFUPM (2000 ) 55

Experiment No 8

String Handling Instructions

Introduction: In this experiment you will deal with string handling instructions, such as reading a string, moving a string from one memory location to another, and comparing two strings. You will need some of the programs developed in previous experiments to rewrite them in a more structured way. Objectives:

1- More on Macros, Subroutine Calls and Stack operation. 2- String Handling Instructions. 3- Introduction to the video display.

References:

- Textbook: Sections 3.4, 3.5, - Lecture notes.

String Handling Instructions:

String handling instructions are very powerful because they allow the programmer to manipulate large blocks of data with relative ease. Block data manipulation occurs with the string instructions indicated in Table 8. 3, Table 8. 4 and Table 8. 4. Each of the string instructions indicated in Table 8. 2 define an operation for one element of a string only. Thus, these operations must be repeated to handle a string of more than one element. For repeating prefixes, see Table 8. 4.

String handling instructions use the direction flag, SI and DI registers. The

Direction Flag (DF) selects auto-increment or auto-decrement operation for the DI and SI registers during string operations. Whenever a string instruction transfers a byte, the contents of SI and/or DI increment or decrement by 1. If a word is transferred, the contents of SI and/or DI increment or decrement by 2.

Format Operation Mode Effect CLD Clear DF; (DF) 0 Auto Increment SI SI + 1; DI DI +1 STD Set DF; (DF) 1 Auto Decrement SI SI - 1; DI DI -1

Table 8. 1: Auto- incrementing and decrementing in string instructions

Page 58: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 8

COE Department KFUPM (2000 ) 56

The LODS Instruction: LODS loads AL or AX with data stored at the data-segment offset address indexed by the SI register. The LODSB causes a byte to be loaded into AL, and the LODSW causes a word to be loaded into AX. The STOS Instruction: The STOS instruction stores AL or AX at the extra-segment memory location addressed by the DI register, (in fact ES:DI). The STOSB stores a byte in AL at the extra-segment memory indicated by DI. The STOSW stores a word in AX at the extra-segment memory indicated by DI. Program 8.1 gives an example on the use of STOS instruction to clear the video memory. The MOVS Instruction: The MOVS instruction transfers data from one memory location to another. This is the only memory-to-memory transfer allowed in the Intel family of Microprocessors. The MOVS instruction transfers a byte or a word from the data-segment location addressed by SI to the extra-segment location addressed by DI. The pointers then increment or decrement as indicated by the direction flag (Table 8. 2).

Mnemonics Meaning Format Operation As per Direction Flag

Flags affected

LODS Load string LODSB LODSW

(AL or AX) ((DS)0+(SI)) (SI) (SI) ± 1 or 2

None

STOS Store string STOSB STOSW

((ES)0 + (DI)) (AL or AX)) (DI) (DI) ± 1 or 2

None

MOVS Move string MOVSB

MOVSW ((ES)0 + (DI)) ((DS)0+(SI)) (SI) (SI) ± 1 or 2 (DI) (DI) ± 1 or 2

None

Note: B stands for Byte and W for Word.

Table 8. 2: Basic String Handling Instructions Example of a move string: Below is an example of the MOVS instruction. The same example is repeated later but with the use of the REP prefix. MOV AX, @DATA MOV DS, AX MOV ES, AX ; Make ES = DS LEA SI, BLK1 ; Source address for block1 LEA DI, BLK2 ; Destination address for block2

MOV CX, N ; N = number of bytes to move CLD ; Set Auto-Increment mode

NEXT: MOVSB ; Move one byte at a time LOOP NEXT

Page 59: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 8

COE Department KFUPM (2000 ) 57

String Comparisons: In order to allow a section of memory to be compared against a constant or another section of memory, the String Scan instruction SCAS (Table 8. 3) is used. The SCAS instruction compares the content of the AL register with a byte block of memory, or the AX register with a word block of memory. The opcode used for byte comparison is SCASB and for word comparison is SCASW (Table 8. 3). The Compare Strings Instruction (CMPS) compares two sections of memory data as bytes (CMPSB), or words (CMPSW). The contents of the data-segment memory indicated by SI are compared with the contents of the data-segment memory indicated by DI. The CMPS instruction increment both SI and DI if the direction flag (DF) is zero, or decrements both of them if DF is set to one. The CMPS instruction is normally used with either the REPE or REPNE prefix. Alternates to these prefixes are REPZ (repeat while zero) and REPNZ (repeat while not zero), though REPE and REPNE are more common (Table 8. 4). Mnemonics Meaning Format Operation Flags

affected CMPS Compare

strings

CMPSB CMPSW

Set flags as per: ((ES)0 + (SI)) – ((ES)0+(DI)) (SI) (SI) ± 1 or 2 (DI) (DI) ± 1 or 2

CF,PF,AF, ZF,SF,OF

SCAS Scan string

SCASB SCASW

Set flags as per: (AL or AX) – ((ES)0+(DI)) (DI) (DI) ± 1 or 2

CF,PF,AF, ZF,SF,OF

Note: B stands for Byte and W for Word.

Table 8. 3: String Compare Instructions Repeat Prefixes: Table 8. 4 summarizes the repeat prefixes to be used with the string instructions given in Table 8. 2 and Table 8. 3. The REP prefix: The REP prefix is added to any data transfer or compare instruction, except the LODS instruction. The REP prefix causes the CX register to decrement by 1 each time the string instruction executes. If CX reaches 0, the instruction terminates and the program continues with the next sequential instruction. The following example illustrates the of a move string using the REP prefix: MOV AX, @DATA MOV DS, AX MOV ES, AX ; Make ES = DS CLD ; Set Auto-Increment mode MOV CX, 20H MOV SI, OFFSET DATA1 MOV DI, OFFSET DATA2 REP MOVSB

Page 60: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 8

COE Department KFUPM (2000 ) 58

Prefix

Used with

Meaning

REP MOVS STOS

Repeat while not end of string CX ≠ 0

REPE REPZ

CMPS SCAS

Repeat while not end of string and strings are equal CX ≠ 0 and ZF = 1

REPNE REPNZ

CMPS SCAS

Repeat while not end of string And strings are not equal CX ≠ 0 and ZF = 0

Note: B stands for Byte and W for Word.

Table 8. 4: Prefixes fo use with basic string instructions

Examples on the use of the SCAS and CMPS instructions: The following example shows how to search a memory section of 100 bytes in length and starting at location BLOCK. The program searches if any location contains the value 45H. MOV DI, OFFSET BLOCK ;address data CLD ;auto-increment MOV CX, 100 ;load counter MOV AL, 45H ;AL = 45H REPNE SCASB ;search The next example illustrates a short procedure that compares two sections of memory searching for a match. The CMPSB instruction is prefixed with a REPE. This causes the search to continue as long as an equal condition exists. When the CX register becomes 0, or an unequal condition exists, the CMPSB instruction stops execution. After the CMPSB instruction ends, the CX register is zero or the flags indicate an equal condition when the two strings match. If CX is not zero or the flags indicate a not-equal condition, the strings do not match. MATCH PROC FAR

MOV SI, OFFSET LINE MOV DI, OFFSET TABLE CLD MOV CX, 10 REPE CMPSB RET

MATCH ENDP

Page 61: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 8

COE Department KFUPM (2000 ) 59

Pre Lab Work:

1. Read the manual and understand how the string instructions work. 2. Write programs 8.1, 8.2 and 8.3 and check their functionality. 3. Bring your work to the lab.

Lab Work:

1- Show programs 8.1, 8.2 and 8.3 to your lab instructor. 2- Clear the screen using program 8.2 and write the word BUG somewhere

on the display. Run program 8.3 and check that it really detects the word BUG on the screen. Clear the screen with program 8.2 and check again with program 8.3.

3- Modify program 8.3 so that it looks for the word MOV on the display, and counts the number of times it occurs. Call it program 8.4.

4- Edit one of your assembly language programs on the screen using the following:

TYPE program.asm

5- Check with program 8.4, how many times you have the word MOV on the screen.

Lab Assignment: Rewrite the program that reads a password without echo from the keyboard in a more structured way, using Macros and Procedures. To check for password validity use the string handling instructions CMPSB or SCASB.

Page 62: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 8

COE Department KFUPM (2000 ) 60

TITLE “Program 8.1” ;This program clears the video text display .MODEL TINY .CODE .STARTUP CLD ;select increment mode MOV AX,0B800H ;address segment B800H MOV ES,AX ;Video Text Memory = B800:0000 MOV DI,0000 ;address offset 0000 MOV CX,25*80 ;load count: 25 lines per 80 columns MOV AX,0720H ;load data AH= 07H = color: white text on black

;background. AL = 20H = space REP STOSW ;clear the screen .EXIT ;exit to DOS END ;end of file ;------------------------------------------------------------- TITLE “Program 8.2” ;This program scrolls the display one line up .MODEL TINY ;select TINY model .CODE ;indicate start of CODE segment .STARTUP ;indicate start of program

CLD ;select increment

MOV AX,0B800H ;load ES and DS with B800 MOV ES, AX MOV DS, AX MOV SI,160 ;address line 1: 160 = 2 * 80 MOV DI,0 ;address line 0 MOV CX,24*80 ;load count REP MOVSW ;scroll screen MOV DI,24*80*2 ;clear bottom line MOV CX,80 MOV AX,0720H REP STOSW .EXIT ;exit to DOS END ;end of file

Page 63: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 8

COE Department KFUPM (2000 ) 61

TITLE “Program 8.3” ;This program tests the video display for the word BUG ;if BUG appears anywhere on the display the program display Y ;if BUG does not appear, the program displays N ; .MODEL SMALL ;select model SMALL .DATA ;indicate start of DATA segment DATA1 DB 'BUG' ;define BUG .CODE ;indicate start of CODE segment .STARTUP ;indicate start of program MOV AX,0B800H ;address segment B800 with ES MOV ES,AX MOV CX,25*80 ;set count CLD ;select increment MOV DI,0 ;address first display position L1: MOV SI,OFFSET DATA1 ;address BUG PUSH DI ;save display address CMPSB ;test for B JNE L2 ;if display is not B INC DI ;address next display position CMPSB ;test for U JNE L2 ;if display is not U INC DI ;address next display position CMPSB ;test for G MOV DL,'Y' ;load Y for possible BUG JE L3 ;if BUG is found L2: POP DI ;restore display address ADD DI,2 ;point to next display position LOOP L1 ;repeat until entire screen is tested PUSH DI ;save display address MOV DL,'N' ;indicate N if BUG not found L3: POP DI ;clear stack MOV AH,2 ;display DL function INT 21H ;display ASCII from DL .EXIT ;exit to DOS END ;end of file

Page 64: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 62

Experiment No 9

Accessing Video Memory Introduction: This experiment introduces the use of the VGA controller and BIOS INT 10H functions to access video memory using mode 12H graphics mode. You will be provided with some routines that use the video modes. These routines can be inserted into your programs. Objectives:

3- Use the 640x480 16-color graphics display mode. 4- Use mode 12H to divide the screen into a 53 line by 80 character per line

to display blocks of colors. 5- Display text on the 640x480 16-color graphics display without changing

the background color. References:

- Textbook: Sections - Lecture notes.

Text Mode: In DOS mode, the video text memory is located at B800:0000 through B800:FFFF and contains ASCII data and attributes for display. In text mode, the following functions are used to display data on the screen. Function 02H: Displays one character. May be interrupted by a Ctrl Break Function 06H: May not be interrupted by a Ctrl Break Function 09H: Used to display a character string terminated by a $ sign. Graphics Mode: The 640x480 16-color graphics display mode uses memory location A000:0000 through A000:FFFF to access graphics data. In order to display 16 colors with a resolution of 640x 480 a memory greater than 64K bytes is required. Because 16 colors require 4 bits, and the resolution is 640 x 480 (i.e. 307,200 pixels), the memory system requires 640 x 480 x 4 (i.e. 1,228,800 bits ) or 153,600 bytes of video memory in this display mode. To allow access to such as amount of memory, mode 12H display is designed to be accessed in bit planes. A bit plane is a linear section of memory that contains one of the four bits to display the 16 colors. Each bit plane requires 307,200 bits of memory, stored in 38,400 bytes of memory. The 64K bytes at segment A000H are enough to only address a single bit plane at a time. The bit plane is addressed at memory

Page 65: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 63

locations A000:0000 through A000:95FF. In a 640x480 display, location A000:0000 represents the upper leftmost 8 pixels, and location A000:95FF represents the lower rightmost 8 pixels. There are four planes, or banks of memory, that overlap this address range to represent the four bits or color for each pixel ( Figure 9. 1). To change the color of one pixel, on the video display, four bits need to be changed, one in each bit plane. The color codes used for a standard VGA display are shown in Table 9.2. If all 4 bit planes are cleared, black is the pixel color.

Figure 9. 1: The four bit-planes of the 640x480, 16-color VGA display

Accessing the Video Memory: Access to video memory in mode 12H is accomplished through the following steps: Step 1: Read the byte of memory to be changed, to load the bit plane information into

the video card. Step 2: Select and address a single pixel (bit) through the graphics address register

(GAR) and bit mask register (BMR). This is accomplished by sending an 8 out to I/O port 03CEH, which represents the GAR.

Steps 1 and 2 are done through the following set of instructions:

MOV DX, 03CEH ; Select VGA address card MOV AL, 08 ; Index of 8 OUT DX, AL ; Select Index 8

Step 3: Load AL with the bits to be changed (a one bit represents a pixel to be

changed), and send this out to the Bit Mask Register (BMR), or I/O port 03CFH.

P0

P0

P1

P1

P1

P1

P0 P1 P2

Plane 3

Plane 2

Plane 1

Plane 0

P3

Page 66: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 64

MOV DX, 03CFH ; Select BMR MOV AL, 80H ; Place mask in AL

OUT DX, AL ; Select leftmost bit, in this case ; using 80H.

Step 4: Set all mask bits to 1’s (1111 or 0FH) in the Map Mask Register (MMR) at

sequencer offset 2, and write color 0 to the VGA card (black) to the address containing the pixel, to clear the old color from the pixel. Mask bits select the bit planes to be changed. If all are selected and a color 0 is written, all four-bit planes are cleared to zero. To do so, use the following code: MOV DX, 03C4H ; Select VGA sequencer register MOV AL, 02 ; Index of 2 OUT DX, AL ; Select Index 2 MOV DX, 03C5H ; Address MMR MOV AL, 0FH ; Mask to 1111 binary OUT DX, AL

Step 5: Send the desired color number to the MMR and write an FFH to the video memory. This places a logic one in only the selected bit planes. To write a new color to a pixel on the screen, use the following instructions: MOV AL, Color ; Choose color; e.g. 03 for cyan OUT DX, AL ; Select color ; Next write an FFH to the selected video memory location

Register Meaning Address GAR Graphics Address Register 03CEH BMR Bit Mask Register 03CFH MMR Map Mask Register 03C4H to access

03C5H to select bit planes

Table 9. 1: Registers used in Video Mode

bl R G B br R G B Character Background Blinking

br : Brightness

Figure 9. 2: The Bit Pattern Available to VGA, Mode 12H

Page 67: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 65

Code br R G B

Color

0 0 0 0 Black 0 0 0 1 Blue 0 0 1 0 Green 0 0 1 1 Cyan 0 1 0 0 Red 0 1 0 1 Magenta 0 1 1 0 Brown 0 1 1 1 White 1 0 0 0 Grey 1 0 0 1 Bright Blue 1 0 1 0 Bright Green 1 0 1 1 Bright Cyan 1 1 0 0 Bright Red 1 1 0 1 Bright Magenta 1 1 1 0 Yellow 1 1 1 1 Bright White

Table9.2: Colors Available to VGA, Mode 12H

DIRECT VIDEO ACCESS IN TEXT MODE The characters seen on the video monitor correspond directly to ASCII bytes stored in the video RAM. Thus to display a character, by direct video access, one need only place the ASCII code for that character into the correct video RAM location. Example: The following program fills a screen with A’s by direct video access. It uses the default text mode 3 ,STACK 200 .CODE .STARTUP

MOV AX , 0B800H MOV DS , AX MOV CX , 2000 ; 2000 words MOV DI , 0 FILL_PAGE: MOV WORD PTR [DI] , 7041h ; black A on white ADD DI , 2 LOOP FILL_PAGE MOV AH , 08H ; wait for a keystroke INT 21H ; .EXIT END The formula for calculating a video memory offset address, in video page 0, given a screen row and column coordinate pair is:

Character offset = ( row# * 80 + column# ) * 2 = ( row# * (64 + 16) + column# ) * 2 Using the above formula the following procedure calculates an 80 * 25 text-mode memory address from a pair of row and column coordinates, contained in DH and DL respectively:

Page 68: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 66

CALC_ADDRESS PROC ; input: DH = row number (0 - 24) , DL = column number (0 - 79) , VIDEO_SEG a constant

which contains ; either B000H or B800H ; output: ES:DI contains the required segment : offset address PUSH AX MOV AX , VIDEO_SEG MOV ES , AX MOV AH , 0 MOV AL , DH ; AX := row# SHL AX , 1 ; AX := row# * 2 SHL AX , 1 ; AX := row# * 4 SHL AX , 1 ; AX := row# * 8 SHL AX , 1 ; AX := row# * 16 MOV DI , AX ; DI := row# * 16 SHL AX , 1 ; AX := row# * 32 SHL AX , 1 ; AX := row# * 64 ADD DI , AX ; DI := row# * 80 MOV AH , 0 MOV AL , DL ; AX := column# ADD DI , AX ; DI := row# * 80 + column# SHL DI , 1 ; DI := ( row# * 80 + column# ) * 2 POP AX RET CALC_ADDRESS ENDP Thus, for example, to display a yellow blinking T on a green background at row 6 and column 37, by direct video access, use : MOV DH , 6 ; row#6 MOV DL , 37 ; column#37 CALL CALC_ADDRESS MOV AH , 10101110B ; attribute: yellow on green MOV AL , ‘T’ STOSW Note: The effect of STOSW is: MOV ES:[DI] , AL MOV ES:[DI + 1] , AH Using BIOS INT 10H to access the video display: Another way of accessing video memory is through INT 10H. This method is recommended for most applications, since it frees the user from the burden of calculating video memory addresses. The following are most functions used with INT 10H, these allow most useful video tasks. Note that INT 10H preserves only the BX, CX, DX, and the segment registers Accessing the Video Memory: Note that color codes are arranged so that the leftmost bit represents bright, and the next three bits represent red, blue and green respectively. Access to the video memory is explained in the following sections.

Page 69: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 67

Before accessing video, make sure that you save the current video mode so that you can restore it once you finish your program. This can be done using the following sequence of instructions: ( INT 10H ) MOV AH,0FH ;Get current video mode INT 10H PUSH AX ;Save Video mode AL and Number of columns AH ………… POP AX ;Restore Video mode AL and Number of columns AH MOV AH,00 INT 10H Select Video Mode: MOV AH, 00 MOV AL, VIDEO_MODE INT 10H Function 00 automatically clears the screen. To preserve the screen while changing the mode set the most significant bit of AL to 1. MOV AH, 00 MOV AL, VIDEO_MODE OR AL, 80H

INT 10H Get Current Video Mode: MOV AH, 0FH INT 10H PUSH AX ; Or MOV Old_Video_Mode, AX Restore Video Mode: POP AX ; Or MOV AX, Old_Video_Mode

MOV AH, 00H INT 10H Cursor Positioning: - If the row and column numbers are in Hexadecimal they can directly be assigned

to the DX register. - The cursor positioning on a video page is independent of the other video pages. Set CursorPosition:

MOV AH, 02H

Page 70: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 68

MOV BH, Current_Video_Page_Number ;Usually 0 MOV DH, Row_Number MOV DL, Column_Number INT 10H Get Cursor Position:

MOV AH, 03H MOV BH, Current_Video_Page_Number ;Usually 0 INT 10H

MOV Save_Cursor, CX MOV Current_Row, DH MOV Current_ Column, DL

Set Cursor Size: The cursor is displayed using starting and ending scan lines. In Mono mode the cursor uses 12 lines (0,1,2, .. 0BH,0CH), whereas in color mode it uses 8 lines (0,1, ..,6,7).

CGA/EGA MONOCHROME 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 default 7 8 9 0A default 0B 0C

Figure 9. 3: Cursor Size

MOV AH, 01H MOV CH, Start_Scan_Line# MOV CL, End_Scan_Line# INT 10H

Page 71: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 69

To set the cursor to its maximum size in color mode: MOV AH, 01H MOV CX, 0007H INT 10H To set the cursor to its maximum size in monochrome mode: MOV AH, 01H MOV CX, 000CH INT 10H Write Pixel:

MOV AH, 0CH INT 10H Save the current cursor size: MOV Cursor_Size, CX Restore the current cursor size: MOV AH, 01H MOV CX, Cursor_Size INT 10H Make the Cursor Invisible: Set the starting scan line to an illegal value by setting bit 5 in CH to 1. MOV AH, 01H OR CH, 00100000B ; Or MOV CX, 2000H INT 10H Another way of hiding the cursor is to place it in the undisplayed portion of the video page, e.g. row #25 column # 0. MOV DH, 25 ;Row number MOV DL, 00 ;Column number MOV AH, 02H MOV BH, 00 ;Video page # 0 INT 10H Set Border Color:

MOV AH,0BH MOV BH,00H MOV BL,04H INT 10H

Page 72: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 70

Pre Lab Work:

4- Write two Macros: one to get the current video mode, and the other restore the video mode.

5- Write and run programs 9.1 and 9.2. Write your programs using macros and procedures.

6- Prepare all programs in this experiment by writing them using macros and procedures.

Lab Work:

7- Show programs 9.1 and 9.2 to your lab instructor. 8- Write and run programs 9.3 and 9.4. 9- Write a program that displays the time on the top right hand corner of the

display. Use INT 10H function 02, which inputs the column and row numbers in DL and DH respectively, and Video page (usually 0) in BH.

Lab Assignment: Rewrite the program that displays the time on the screen using graphics mode only. Review the part that shows how to display text in video mode.

Page 73: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 71

Title ‘Program 7-1’ ; A program that blanks the test mode screen and makes it red. ; It then displays the message This is a test line. before ; returning to DOS. ; .MODEL SMALL .DATA

MES DB 'This is a test line.$' .CODE .STARTUP MOV AX,0B800H ;address text segment MOV ES,AX CLD ;select increment MOV DI,0 ;address text offset MOV AH,40H ;attribute black on red MOV AL,20H ;character is space MOV CX,25*80 ;set count REP STOSW ;clear screen and change attributes MOV AH,2 ;home cursor MOV BH,0 ;page 0 MOV DX,0 ;row 0, char 0 INT 10H MOV DX,OFFSET MES ;display "This is a test line." MOV AH,9 INT 21H .EXIT END

Title ‘Program 7-2’ ;a program that displays all of 256 colors available to the ;320 x 200 video display mode (13H) ;***uses*** ;the BAND procedure to display 64 colors at a time in a band ;on the display. ; .MODEL TINY .CODE .STARTUP MOV AX,13H ;select mode 13H INT 10H MOV AX,0A000H ;address segment A000 with ES MOV ES,AX CLD ;select increment MOV DI,0 ;address offset 0000 MOV AL,0 ;load starting test color of 00H CALL BAND ;display one band of 64 colors MOV AL,64 ;load starting color of 40H CALL BAND ;display one band of 64 colors MOV AL,128 ;load starting color of 80H CALL BAND ;display one band of 64 colors MOV AL,192 ;load starting color of C0H CALL BAND ;display one band of 64 colors MOV AH,1 ;wait for any key INT 21H MOV AX,3 ;switch back to DOS video mode INT 10H .EXIT ; ;the BAND procedure displays a color band of 64 colors ;***input parameter*** ;AL = starting color number ;ES = A000H ;DI = starting offset address for display ; BAND PROC NEAR MOV BH,40 ;load line count

Page 74: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 72

BAND1: PUSH AX ;save starting color MOV CX,64 ;load color across line count BAND2: MOV BL,5 ;load times color is displayed BAND3: STOSB ;store color DEC BL JNZ BAND3 ;repeat 5 times INC AL ;change to next color LOOP BAND2 ;repeat for 64 colors POP AX ;restore starting color DEC BH JNZ BAND1 ;repeat for 40 lines ADD DI,320*10 ;skip 10 lines RET BAND ENDP END

Title ‘Program 7-3’ ;a program that displays all the possible brightness levels of the ;color red for the 320 x 200, 256 color mode (13H) ; .MODEL TINY .CODE .STARTUP MOV AX,13H ;switch to mode 13H INT 10H MOV AX,0A000H ;address segment A000 with ES MOV ES,AX CLD ;select increment MOV CH,0 ;green value MOV CL,0 ;blue value MOV DH,0 ;red value MOV BX,80H ;color register number 80H MOV AX,1010H ;change palette color function MOV DL,64 ;count to change colors 80H to BFH PROG1: INT 10H ;change a color value INC DH ;next color of red INC BX ;next color palette register DEC DL JNZ PROG1 ;repeat for 64 colors MOV DI,0 ;address offset 0000 MOV AL,80H ;starting color number CALL BAND ;display 64 colors MOV AH,1 ;wait for any key INT 21H MOV AX,3 ;switch back to DOS video mode INT 10H .EXIT ; ;the BAND procedure displays a color band of 64 colors ;***input parameter*** ;AL = starting color number ;ES = A000H ;DI = starting offset address for display ; BAND PROC NEAR MOV BH,40 ;line count of 40 BAND1: PUSH AX ;save starting color number MOV CX,64 ;color count of 64 BAND2: MOV BL,5 ;load times color is displayed BAND3: STOSB ;store color DEC BL

Page 75: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 73

JNZ BAND3 ;repeat 5 times INC AL ;get next color number LOOP BAND2 ;repeat for all 64 colors POP AX ;restore original color number DEC BH JNZ BAND1 ;repeat for 40 raster lines ADD DI,320*10 ;skip 10 raster lines RET BAND ENDP END

Title ‘Program 7-4’ ;a program that displays a green box on the video screen using ;video mode 13H. ; .MODEL TINY .CODE .STARTUP CLD ;select auto-increment MOV AX,13H ;select mode 13H INT 10H ;this also clears the screen MOV AL,2 ;use color 02H (green) MOV CX,100 ;starting column number MOV SI,10 ;starting row number MOV BP,75 ;size CALL BOX ;display box MOV AH,1 ;wait for any key INT 21H MOV AX,3 ;switch to DOS video mode INT 10H .EXIT ; ;the BOX procedure displays a box on the mode 13H display. ;***input parameters*** ;AL = color number (0-255) ;CX = starting column number (0-319) ;SI = starting row number (0-199) ;BP = size of box ; BOX PROC NEAR MOV BX,0A000H ;address segment A000 with ES MOV ES,BX PUSH AX ;save color MOV AX,320 ;find starting PEL MUL SI MOV DI,AX ;address start of BOX ADD DI,CX POP AX PUSH DI ;save starting offset address MOV CX,BP ;save size in BP BOX1: REP STOSB ;draw top line MOV CX,BP SUB CX,2 ;adjust CX BOX2: POP DI ADD DI,320 ;address next row PUSH DI STOSB ;draw PEL ADD DI,BP SUB DI,2 STOSB ;draw PEL LOOP BOX2 POP DI ADD DI,320 ;address last row MOV CX,BP REP STOSB RET

Page 76: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 74

BOX ENDP END

Title ‘Program 7-5’ ;a program that displays a short cyan line that is 10 Pixels wide ;with a red dot below and to the right of the cyan line. ; .MODEL TINY .CODE .STARTUP MOV AX,0A000H ;address video RAM at segment A000 MOV DS,AX CLD ;select increment MOV AX,12H ;set mode to 12H INT 10H ;and clear screen MOV CX,10 ;set dot count to 10 MOV BX,10 ;row address MOV SI,100 ;column address MOV DL,3 ;color 3 (cyan) MAIN1: ;plot 10 dots CALL DOT ;display one dot INC SI LOOP MAIN1 ;repeat 10 times MOV BX,40 ;row address MOV SI,200 ;column address MOV DL,4 ;color 4 (red) CALL DOT ;display one red dot MOV AH,1 ;wait for key INT 21H MOV AX,3 INT 10H ;return to DOS video mode .EXIT ; ;the DOT procedure displays one dot or PEL on the video display. ;BX = row address (0 to 479) ;SI = column address (0 to 639) ;DL = color (0 to 15) ; DOT PROC NEAR PUSH CX PUSH DX ;save color MOV AX,80 ;find row address byte MUL BX MOV DI,AX ;save it MOV AX,SI ;find column address byte MOV DH,8 DIV DH MOV CL,AH ;get shift count MOV AH,0 ADD DI,AX ;form address of PEL byte MOV AL,80H SHR AL,CL ;find bit in bit mask register PUSH AX ;save bit mask MOV DX,3CEH ;graphics address register MOV AL,8 ;select bit mask register OUT DX,AL MOV DX,3CFH ;bit mask register POP AX ;get bit mask OUT DX,AL MOV DX,3C4H ;sequence address register MOV AL,2 ;select map mask register OUT DX,AL MOV DX,3C5H ;map mask register

Page 77: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 75

MOV AL,0FH ;enable all planes OUT DX,AL MOV AL,[DI] ;must read first MOV BYTE PTR [DI],0 ;clear old color POP AX ;get color from stack PUSH AX OUT DX,AL MOV BYTE PTR [DI],0FFH ;write memory POP DX ;restore registers POP CX RET DOT ENDP END Title ‘Program 7-6’ ;a program that display a cyan bar across the top of a white ;screen. ; .MODEL TINY .CODE .STARTUP MOV AX,0A000H ;address video RAM at segment A000 MOV DS,AX CLD ;select increment MOV AX,12H ;set mode to 12H INT 10H ;and clear screen MOV CX,80 ;block count MOV BX,0 ;row address MOV SI,0 ;column address MOV DL,3 ;color 3 (cyan) MAIN1: ;plot 80 blocks CALL BLOCK ;display a block INC SI ;address next column LOOP MAIN1 ;repeat 80 times MOV BX,1 ;row address MOV DL,7 ;color 7 (white) MOV DH,52 ;row count MAIN2: MOV SI,0 ;column address MOV CX,80 ;column count MAIN3: CALL BLOCK ;display a block INC SI ;address next column LOOP MAIN3 ;repeat 80 times INC BX ;increment row address DEC DH JNZ MAIN2 ;repeat 52 times MOV AH,1 ;wait for key INT 21H MOV AX,3 INT 10H ;return to DOS video mode .EXIT ; ;The BLOCK procedure displays one block that is 8 pixels ;wide by 9 pixels high. ;BX = row address (0 to 52) ;SI = column address (0 to 79) ;DL = block color (0 to 15) ; BLOCK PROC NEAR PUSH CX PUSH DX ;save color MOV DX,3CEH ;graphics address register MOV AL,8 ;select bit mask register OUT DX,AL

Page 78: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 76

MOV DX,3CFH ;bit mask register MOV AL,0FFH ;enable all 8 bits OUT DX,AL MOV DX,3C4H ;sequence address register MOV AL,2 ;select map mask register OUT DX,AL MOV AX,80*9 ;find row address byte MUL BX MOV DI,AX ;save it ADD DI,SI ;form address of PEL byte MOV CX,9 ;byte count MOV DX,3C5H ;map mask register POP AX ;get color PUSH AX MOV AH,AL BLOCK1: MOV AL,0FH ;enable all planes OUT DX,AL MOV AL,[DI] ;must read first MOV BYTE PTR [DI],0 ;clear old color MOV AL,AH OUT DX,AL MOV BYTE PTR [DI],0FFH ;write memory ADD DI,80 LOOP BLOCK1 POP DX POP CX RET BLOCK ENDP END

Title ‘Program 7-7’ ;program that display a bright red B at row 0, column 0, and a ;cyan A at row 5, column 20. .MODEL TINY .CODE .STARTUP MOV AX,0A000H ;address video RAM at segment A000 MOV DS,AX CLD ;select increment MOV AX,12H ;set mode to 12H INT 10H ;and clear screen MOV AL,'A' ;display 'A' MOV DL,3 ;cyan MOV BX,5 ;row 5 MOV SI,20 ;column 0 CALL CHAR ;display cyan 'A' MOV AL,'B' ;display 'B' MOV DL,12 ;bright red MOV BX,0 ;row 0 MOV SI,0 ;column 0 CALL CHAR ;display bright red 'B' MOV AH,1 ;wait for key INT 21H MOV AX,3 INT 10H ;return to DOS video mode .EXIT ; ;The CHAR procedure displays a character (8 x 8) on the ;mode 12H display without changing the background color. ;AL = ASCII code ;DL = color (0 to 15) ;BX = row (0 to 52) ;SI = column (0 to 79) ;

Page 79: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 77

CHAR PROC NEAR PUSH CX PUSH DX PUSH BX ;save row address PUSH AX ;save ASCII MOV AX,1130H ;get 8 x 8 set MOV BH,3 INT 10H ;segment is in ES POP AX ;get ASCII code MOV AH,0 SHL AX,1 ;multiply by 8 SHL AX,1 SHL AX,1 ADD BP,AX ;index character in ROM POP BX ;get row address MOV AX,80*9 ;find row address MUL BX MOV DI,AX ADD DI,SI ;add in column address MOV CX,8 ;set count to 8 rows C1: MOV DX,3CEH ;address bit mask register MOV AL,8 ;load index 8 MOV AH,ES:[BP] ;get character row INC BP ;point to next row OUT DX,AX ;modify bit mask register MOV DX,3C4H ;address map mask register MOV AX,0F02H OUT DX,AX ;select all planes INC DX MOV AL,[DI] ;read data MOV BYTE PTR [DI],0 ;write black POP AX ;get color PUSH AX OUT DX,AL ;write color MOV BYTE PTR [DI],0FFH ADD DI,80 ;address next raster row LOOP C1 ;repeat 8 times POP DX POP CX RET CHAR ENDP END

Title ‘Program 7-8’ ;a program that displays two test lines of text on a cyan graphics ;background screen. ; .MODEL SMALL .DATA MES1 DB 'This is test line 1.',0 MES2 DB 'This is test line 2.',0 .CODE .STARTUP MOV AX,0A000H ;address video RAM MOV DS,AX CLD ;select increment MOV AX,12H ;set mode to 12H INT 10H ;and clear screen MOV DL,3 ;color cyan MOV DH,53 ;row counter MOV BX,0 ;row 0 MAIN1: MOV CX,80 ;column counter MOV SI,0 ;column 0 MAIN2: CALL BLOCK ;display a cyan block INC SI ;address next column LOOP MAIN2 ;repeat 80 times

Page 80: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 78

INC BX ;address next row DEC DH ;decrement row counter JNZ MAIN1 ;repeat for 53 rows MOV AX,@DATA ;address data segment MOV ES,AX ;with ES MOV DL,9 ;bright blue text MOV BX,5 ;row 5 MOV SI,0 ;column 0 MOV DI,OFFSET MES1 ;address MES1 CALL LINE ;display bright blue MES1 MOV DL,12 ;bright red MOV BX,15 ;row 15 MOV SI,0 ;column 0 MOV DI,OFFSET MES2 ;address MES2 CALL LINE ;display bright red MES2 MOV AH,1 ;wait for key INT 21H MOV AX,3 INT 10H ;return to DOS video mode .EXIT ; ;The line procedure displays the line of text addressed by ES:DI ;DL = color of text (0 to 15). ;The text must be stored as a null string ;BX = row ;SI = column ; LINE PROC NEAR MOV AL,ES:[DI] ;get character OR AL,AL ;test for null JZ LINE1 ;if null PUSH ES ;save registers PUSH DI PUSH SI CALL CHAR ;display characters POP SI ;restore registers POP DI POP ES INC SI ;address next column INC DI ;address next character JMP LINE ;repeat until null LINE1: RET LINE ENDP ; ;The CHAR procedure displays a character (8 x 8) on the ;mode 12H display without changing the background color. ;AL = ASCII code ;DL = color (0 to 15) ;BX = row (0 to 52) ;SI = column (0 to 79) ; CHAR PROC NEAR PUSH CX PUSH DX PUSH BX ;save row address PUSH AX ;save ASCII MOV AX,1130H ;get 8 x 8 set MOV BH,3 INT 10H POP AX ;get ASCII code MOV AH,0 SHL AX,1 ;multiply by 8 SHL AX,1 SHL AX,1 ADD BP,AX ;index character in ROM POP BX ;get row address MOV AX,80*9 ;find row address

Page 81: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 79

MUL BX MOV DI,AX ADD DI,SI ;add in column address MOV CX,8 ;set count to 8 rows C1: MOV DX,3CEH ;address bit mask register MOV AL,8 ;load index 8 MOV AH,ES:[BP] ;get character row INC BP ;point to next row OUT DX,AX MOV DX,3C4H ;address map mask register MOV AX,0F02H OUT DX,AX ;select all planes INC DX MOV AL,[DI] ;read data MOV BYTE PTR [DI],0 ;write black POP AX ;get color PUSH AX OUT DX,AL ;write color MOV BYTE PTR [DI],0FFH ADD DI,80 ;address next raster row LOOP C1 ;repeat 8 times POP DX POP CX RET CHAR ENDP ; ;The BLOCK procedure displays one block that is 8 pixels ;wide by 9 pixels high. ;BX = row address (0 to 52) ;SI = column address (0 to 79) ;DL = block color (0 to 15) ; BLOCK PROC NEAR PUSH CX PUSH DX ;save color MOV DX,3CEH ;graphics address register MOV AL,8 ;select bit mask register OUT DX,AL MOV DX,3CFH ;bit mask register MOV AL,0FFH ;enable all 8 bits OUT DX,AL MOV DX,3C4H ;sequence address register MOV AL,2 ;select map mask register OUT DX,AL MOV AX,80*9 ;find row address byte MUL BX MOV DI,AX ;save it ADD DI,SI ;form address of PEL byte MOV CX,9 ;byte count MOV DX,3C5H ;map mask register POP AX ;get color PUSH AX MOV AH,AL BLOCK1: MOV AL,0FH ;enable all planes OUT DX,AL MOV AL,[DI] ;must read first MOV BYTE PTR [DI],0 ;clear old color MOV AL,AH OUT DX,AL MOV BYTE PTR [DI],0FFH ;write memory ADD DI,80 LOOP BLOCK1 POP DX POP CX RET BLOCK ENDP END

Page 82: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 80

Experiment No 10

Interrupts

Introduction: On the 80x86, there are three types of events commonly known as interrupts: traps, exceptions, and interrupts (hardware interrupts). In this experiment we will describe each of these forms and discuss their support on the 80x86 CPU’s and PC compatible machines. We will also describe Interrupt Service Routines (ISR) and Terminate and Stay Resident (TSR) programs. A TSR is a program that remains in memory after execution. The purpose of a TSR is to install an interrupt hook. This experiment illustrates the installation of TSR software using interrupt hooks and hot-key sequences. In most cases, a TSR is activated by either an INT 8 clock tick, or a hot-key sequence. Objectives:

1- Install, use and uninstall an Interrupt Service Routine (ISR). 2- Install interrupt service procedures (hooks) as TSR software. 3- Install a TSR interrupt hook that uses the clock tick interrupt (INT 8). 4- Install a TSR interrupt hook that intercepts the keyboard and responds to a

particular key code or hot-key.

References: 1. Barry B. Brey, “Programming the 80286, 80386, 80486, and Pentium- Based

Personal Computer”, Prentice Hall, (1996). 2. Randall Hyde, “The Art of Assembly Language Programming”,

http://webster.cs.ucr.edu/Page_asm/ArtofAssembly/ArtofAsm.html Interrupts, Traps, and Exceptions: On the 80x86, there are three types of interrupts: traps, exceptions, and interrupts (hardware interrupts). In the following we will describe each of these forms and discuss their implementation. Although the terms trap and exception are often used synonymously, we will use the term trap to denote a programmer initiated and expected transfer of control to a special handler routine. Traps: Traps, or software interrupts, are specialized subroutine calls invoked by a software- interrupt. The 80x86 int instruction is the main instruction for executing a trap. Since traps execute via an explicit instruction, it is easy to determine exactly which instructions in a program will invoke a trap handling routine. There are two main differences between a trap and an arbitrary far procedure call: the instruction used to

Page 83: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 81

call the routine (CALL vs. INT) and the fact that a trap pushes the flags on the stack so you the IRET instruction must be used to return from it. The main purpose of a trap is to provide a fixed subroutine that various programs can call without having to actually know the run-time address. The INT 21h instruction is an example of a trap invocation. Programs do not have to know the actual memory address of DOS entry point to call DOS. Instead, DOS patches the interrupt 21h vector when it loads into memory. When an INT 21h is executed, the 80x86 automatically transfer control to DOS entry point. Traps are used to call a resident program function. By patching an interrupt vector to point at a subroutine within the resident code, other programs that run after the resident program terminates can call the resident subroutines by executing the appropriate INT instruction. Most resident programs do not use a separate interrupt vector entry for each function they provide. Instead, they usually use a single interrupt vector and transfer control to an appropriate routine through a function number that the caller passes in a register, usually and conventionally the AH register. A typical trap handler would execute a case statement on the value in the AH register and transfer control to the appropriate handler function. Exceptions: An exception is an automatically generated trap, forced rather than requested, that occurs in response to some exceptional condition. Generally, there isn't a specific instruction associated with an exception, instead, an exception occurs in response to some erroneous behavior of normal program execution. Examples of conditions that may cause an exception include executing a division instruction with a zero divisor, executing an illegal opcode, and a memory protection fault. Whenever such a condition occurs, the CPU immediately suspends execution of the current instruction and transfers control to an exception handler routine. This routine can decide how to handle the exceptional condition; it can attempt to rectify the problem or abort the program and print an appropriate error message. Exceptions occur when an abnormal condition occurs during execution. There are fewer than eight possible exceptions on machines running in real mode. Protected mode execution provides many others. Although exception handlers are user defined, the 80x86 hardware defines the exceptions that can occur. The 80x86 also assigns a fixed interrupt number to each of the exceptions. Table 10. 1 describes each of these exceptions in detail. In general, an exception handler preserves all registers. However, there are several special cases where you may want to tweak a register value before returning. Nevertheless, you should not arbitrarily modify registers in an exception handling routine unless you intend to immediately abort the execution of your program.

Page 84: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 82

INT # Exception Function Description

INT 0 Divide Error Occurs whenever an attempt to divide a value by zero or the quotient does not fit in the destination register when using the div or IDIV instructions. The FPU's FDIV and FDIVR instructions do not raise this exception.

INT 1 Single Step (Trace) Occurs after every instruction if the trace bit in the flag register is set. Debuggers will often set this flag to trace the execution of a program.

INT 3 Breakpoint This exception is actually a trap, not an exception. It occurs when the CPU executes an INT3 instruction. However, it is considered as an exception since programmers rarely put INT 3 instructions directly into their programs. Instead, a debugger like CodeView often manages the placement and removal of INT 3 instructions.

INT 4

INTO

Overflow Like INT 3, this exception is technically a trap. It is raised when an INTO instruction is executed and the overflow flag is set. If the overflow flag is clear, the INTO instruction is a NOP. Ifthe overflow flag is set, INTO behaves like an INT 4 instruction. An INTO instruction can be inserted after an integer computation to check for an arithmetic overflow.

INT 6 Invalid Opcode The 80286 and later processors raise this exception if an attempt to execute an opcode that does not correspond to a legal 80x86 instruction is made. These processors also raise this exception if you attempt to execute a bound, LDS, LES, LIDT, or other instruction that requires a memory operand but you specify a register operand in the mod/rm field of the mod/reg/rm byte.

INT 7 Coprocessor Not Available

The 80286 and later processors raise this exception if an FPU (or other coprocessor) instruction is attempted to execute without having the coprocessor installed. This exception can be used to simulate the coprocessor in software.

Table 10. 1: Exceptions

Hardware interrupts: Hardware interrupts, or simply interrupts, are program control interruptions based on an external hardware event (external to the CPU). These interrupts generally have nothing at all to do with the instructions currently executing; instead, some event, such as pressing a key on the keyboard or a time out on a timer chip, informs the CPU that a device needs some attention. The CPU interrupts the currently executing program, services the device, and then returns control back to the program. On the PC, interrupts come from many different sources. The primary sources of interrupts, however, are the timer chip, keyboard, serial ports, parallel ports, disk drives, CMOS real-time clock, mouse, sound cards, and other peripheral devices. These devices connect to an Intel 8259A programmable interrupt controller (PIC) that prioritizes the interrupts and interfaces with the 80x86 CPU. The 8259A chip adds considerable complexity to the software that processes interrupts, so it makes perfect sense to discuss the PIC first, before trying to describe how the interrupt service routines have to deal with it. Afterwards, this section will briefly describe each device

Page 85: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 83

and the conditions under which it interrupts the CPU. This text will fully describe many of these devices in later chapters, so this chapter will not go into a lot of detail except when discussing the timer interrupt. 80x86 Interrupt Structure and Interrupt Service Routines: An interrupt service routine is a procedure written specifically to handle a trap, exception, or interrupt. Although different phenomenon cause traps, exceptions, and interrupts, the structure of an interrupt service routine, or ISR, is approximately the same for each of these. The 80x86 allow up to 256 vectored interrupts. This means that up to 256 different sources can exist for an interrupt and the 80x86 will directly call the service routine for that interrupt without any software processing. Non-vectored interrupts transfer control directly to a single interrupt service routine, regardless of the interrupt source. The 80x86 provides a 256 entry interrupt vector table beginning at address 0000:0000 in memory. This is a 1Kbyte table containing 256 4-byte entries. Each entry in this table contains a segmented address that points at the interrupt service routine in memory. Generally, we will refer to interrupts by their index into this table, so the address (vector) of interrupt n is at memory location 0000:n*4. Interrupt zero's vector is at address 0000:0000, interrupt one's vector is at address 0000:0004, etc. When an interrupt occurs, regardless of its source, the 80x86 does the following:

1. The CPU pushes the flags register onto the stack. 2. The CPU pushes a far return address (segment:offset) onto the stack,

segment value first. 3. The CPU determines the cause of the interrupt, i.e., the interrupt number,

and fetches the four byte interrupt vector from address 0000:vector*4. 4. The CPU transfers control to the routine specified by the interrupt vector

table entry. After completion of these steps, the ISR takes control. When the ISR wants to return control, it must execute an IRET (interrupt return) instruction. The interrupt return pops the far return address and the flags off the stack. Note that executing a far return is insufficient since that would leave the flags on the stack. Hardware interrupts are processed differently than other types of interrupts. Upon entry into the hardware ISR, the 80x86 disables further hardware interrupts by clearing the interrupt flag. Traps and exceptions do not do this. If further hardware interrupts are to be disabled within a trap or exception handler, one must explicitly clear the interrupt flag with a clear interrupt flag instruction (CLI). Conversely, if interrupts are to be enabled within a hardware ISR, one must explicitly turn them back on with a Set Interrupt instruction (STI). Note that the 80x86's interrupt disable flag only affects hardware interrupts. Clearing the interrupt flag will not prevent the execution of a trap or an exception.

Page 86: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 84

ISRs are written like almost any other assembly language procedure except that they return with an IRET instruction rather than ret. Although the distance of the ISR procedure (near vs. far) is usually of no significance, you should make all ISRs far procedures. This will make programming easier if you decide to call an ISR directly rather than using the normal interrupt handling mechanism. Exceptions and hardware interrupts ISRs have a very special restriction: they must preserve all registers they modify. DOS Memory Usage and TSRs When DOS is first booted, the memory layout will look something like Figure 10. 1. DOS maintains a free memory pointer that points to the beginning of the block of free memory.

Figure 10. 1: DOS Memory with no active application When an application program is run, DOS loads this application starting at the address the free memory pointer contains. Since DOS runs only a single application at a time, all the memory, starting from the free memory pointer to the end of RAM (0BFFFFh), is available for the application’s use. When the program terminates normally, via DOS function 4CH, MS-DOS reclaims the memory in use by the application and resets the free memory pointer to just above DOS in low memory.

Figure 10. 2: DOS Memory with no active application

Page 87: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 85

MS-DOS provides a second termination call which is identical to the terminate call e except that it does not reset the free memory pointer to reclaim all the memory in use by the application. Instead, this terminate-and-stay-resident call frees all but a specified block of memory. The TSR call (AH = 31H) requires two parameters, a process termination code in the AL register (usually zero) and DX must contain the size of the memory block in paragraphs to protect. When DOS executes this code, it adjusts the free memory pointer so that it points at a location DX*16 bytes above the program’s PSP. This leaves memory looking like this:

Figure 10. 3: DOS Memory Organization for a Resident Program

When the user executes a new application, DOS loads it into memory at the new free memory pointer address, protecting the resident program in memory:

Figure 10. 4: DOS Memory with a Resident Application

Page 88: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 86

Writing and Installing a TSR program: A TSR program consists of two parts an installation section and a service routine. The service routine may consist of more than one ISR. The installation section is executed only at load time. The ISR is executed each time the interrupt is invoked. An ISR must end with a IRET instruction or a FAR JMP to another ISR. 1 / Installing an ISR: The installation section prepares the TSR program’s service routine to be used by other programs or to service a hardware interrupt. The installation uses INT 21H Function 25H. The following code is a typical installation section: MOV AX, CS MOV DS, AX MOV DX, Offset Pgm_ISR MOV AH, 25H MOV AL, Int_Number INT 21H 2 / Make an ISR a TSR: This procedure uses INT 21H Function 31H. DX contains the number of paragraphs to be kept in memory. The following code makes the installed ISR a TSR routine.

MOV DX, Number_Of_Paragraphs MOV AL, Return_Code MOV AH, 31H INT 21H

Function Effect Input Output

25H Set Interrupt Vector DS:DX = Segment Offset Address

31H Make ISR as TSR DX= number of paragraphs to be kept in memory

35H Get Interrupt Vector for a Specified Interrupt.

AL = Interrupt number ES:BX = Segment Offset Address

Table 10. 2: ISR Function Manipulation

Notes: 1 - The code for an installation routine of a TSR should come after the service section, to ensure that it is freed by INT 21H Function 31H, which return control to DOS. Therefore, such a procedure does not need to have a RET instruction. 2 - The number of paragraphs to be kept resident in memory is found by dividing the number of bytes to be kept resident by 16. The following code performs such an operation:

Page 89: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 87

MOV DX, Offset Installation_Routine MOV CL, 04 SHR DX, CL ; Divide by 16 INC DX ; to take care of truncation if any

Figure 10. 5: Memory Structure after a TSR program is installed User Defined TSRs: The software vectors from 60H through 67H and those from 0F1H through 0FFH in the Interrupt Vector Table are undefined and available for user defined ISRs. Program 10.1 installs an ISR at INT 60H. From the time the ISR is installed until either the system is powered down or INT60H is re-vectored to address some other routine, any program that contains the sequence: MOV AX, Operand

INT 60H will display the message “Welcome To The Interesting World Of TSR Routines'. If we change the body of program 10.1, in the following way: DECIMAL_DISPLAY PROC FAR

MOV SI, 0000 MOV BX, 10 DIV_LOOP: MOV AX,operand

DIV BX MOV CS:ARRAY[SI], DL INC SI CMP AX, 0000 JNZ DIV_LOOP

Installation_Routine ENDP

. . . . .

Installation_Routine PROC

Service SectionNumber_Of_Paragraphs

=Offset Installation_Routine/

16

CS

Page 90: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 88

DISPLAY_LOOP: DEC SI MOV AH, 02H MOV DL, CS:ARRAY[SI] OR DL, 30H INT 21H CMP SI, 00 JNZ DISPLAY_LOOP POP SI POP BX POP AX IRET DECIMAL_DISPLAY ENDP In this case a call to INT 60H will display the contents of AX register (operand) on the console screen in decimal notation. Another program, which displays a number passed through DX in different numbering systems will be given in the lab. The numbering system is decided by the value given in the AH register. Redifinition of an existing ISR: An existing system ISR can be redefined by replacing its vector by the vector of a user defined ISR. If execution is to resume at the redefined ISR, DOS function 35H is used to retrieve the segment:Offset address of the interrupt to be redefined. This address is then stored in a double-word variable (VAR). The address is then used by the new ISR to return control to the redefined ISR by executing the FAR jump:

JMP CS:VAR If control is not to resume at the redefined ISR, the new ISR ends with an IRET. INT 21H Function 25H returns the 32-bit vector address of a specified interrupt vector in ES:BX (Table 10. 2). The following code retrieves the vector address of INT 09H: MOV AH, 35H ;Get Int. Vector MOV AL, 09H ;For INT 09H INT 21H MOV WORD PTR VAR,BX ;Store Offset Address MOV WORD PTR VAR+2,BX ;Store Segment Number When an existing system interrupt is being redefined, it is better to disable maskable interrupts. Hardware interrupts can occur at any time. For this reason, interrupts should be disabled while making changes in the vector table, in order to avoid the risk of an interrupt taking place while there is no valid address for a service routine. The CLI and STI instructions are used for this purpose (Table 10. 3). A typical installation routine is given in program 10.3.

Instruction Meaning Flags Affected CLI Clear Interrupt Flag; Disable Maskable

Interrupts IF = 0

STI Set Interrupt Flag; Re-enable Maskable Interrupts

IF = 1

Table 10. 3: Interrupt Flag Set and Clear Instructions

Page 91: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 89

Typical Case, Interception of the Keyboard Interrupt: The keyboard port: When a key is pressed, the keyboard controller sends an 8-bit scan code to to port 60H. The key stroke triggers a hardware interrupt, which prompts the CPU to cal INT 09H. This interrupt inputs then the scan code from the port. The DOS keyboard status flag: The keyboard status flag is located at 0040:0017H. This status flag can be obtained either by:

1 – Using BIOS INT 16H, function 02H: MOV AH, 02H INT 16H ;Status flag returned in AL register

or: 2 – Directly reading segment 40H: MOV AX, 0040H MOV ES, AX MOV DI, 0017H MOV AL, ES:[DI]

To test for the status of a bit use the TEST instruction.

TEST AL, 00100000B ; Test Num Lock

7 6 5 4 3 2 1 0

Bit 0: Right Shift Key Down Bit 4:Insert On Bit 1: Left Shift Key Down Bit 5: Caps Lock On Bit 2: Ctrl Key Down Bit 6: num Lock On Bit 3: Alt Key Down Bit 7: Scrol Lock On

Figure 10. 6: Keyboard Status Register

Program 10.4 is a TSR that beeps the speaker once when the numeric keypad is used, provided that the Num Lock is on. Note that the scan codes of the keys in the numeric keypad area are from 71 to 83. Important Note: All ISR or TSR programs are COM (not EXE) files. To generate a COM file, assemble your program either using the option: assemble as COM in the PWB environment, or using the command: ML /at.

Page 92: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 90

Pre Lab Work:

1- Write, assemble link and run program 10.1. Use the command ML /AT to generate a COM file.

2- Write, assemble link and run program 10.2. 3- Change Program 10.1 using the code given to display a number in AX in

decimal format. 4- Write a program that displays a number in decimal format using INT 60H. 5- Bring your work to the lab.

Lab Work:

1- Show programs 10.1 and 10.2 to your lab instructor. 2- Write a Program that checks for the validity of your password, and beeps

the speaker once if the password is right, and twice if not. Guidelines: - First use the program already developed in previous experiment to check

for password validity. - Second use macros as much as you can. - Third make the password checking routine as a TSR program. Call it INT

60H. When invoked this procedure checks for password validity and returns AL = 00H if the password is correct, and AL = 0FFH is the password is incorrect.

Page 93: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 91

TITLE ‘Program 10.1’ ;This program installs an ISR at INT 60H. Whenever invoked, as in ;Program 10.2, INT 60H displays the message 'Welcome To The ;Interesting World Of TSR Routines' .MODEL TINY .CODE ORG 100H ;Force code at Offset 100H .STARTUP JMP INSTALL ISR_60H PROC FAR PUSH AX PUSH DX PUSH DS MOV AX, CS MOV DS, AX MOV DX, OFFSET MSG MOV AH, 09H INT 21H POP DS POP DX POP AX IRET ISR_60H ENDP MSG DB 'Welcome To The Interesting World Of TSR Routines',0DH,0AH,'$' INSTALL PROC MOV AX, CS MOV DS, AX MOV AH, 25H MOV AL, 60H MOV DX, OFFSET ISR_60H INT 21H MOV AH, 31H MOV AL, 00H MOV DX, OFFSET INSTALL MOV CL, 04 SHR DX, CL INC DX INT 21H INSTALL ENDP END TITLE ‘Program 10.2’ ; This program uses the newly installed INT 60H .MODEL TINY .CODE .STARTUP MOV CX, 5 ; Loop 5 times L1: INT 60H ; Display the message LOOP L1 .EXIT END

Page 94: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 92

TITLE ‘Program 10.3’ ;The following code redefines an existing ISR VAR DD ? ;Used to store the Old Interrupt Vector ... INSTALLATION_ROUTINE PROC CLI ;Clear IF to prevent Hardware Interrupt ;GET OLD INTERRUPT VECTOR MOV AH, 35H MOV AL, INTERRUPT_NUMBER INT 21H

;SAVE THE INTERRUPT VECTOR MOV WORD PTR VAR,BX ;Store Offset Address MOV WORD PTR VAR+2,ES ;Store Segment Number

;INSTALL NEW INTERRUPT VECTOR MOV AX, CS MOV DS, AX MOV AH, 25H MOV AL, INTERRUPT_NUMBER

MOV DX, OFFSET NEW_ISR INT 21H

;TERMINATE AND STAY RESIDENT MOV AH, 31H MOV AL, 00H STI ; Set IF to enable Hardware Interrupt INT 21H INSTALLATION_ROUTINE ENDP TITLE ‘Program 10.4’ ; .MODEL TINY .CODE ORG 100H ;Force code at Offset 100H .STARTUP JMP INSTALL NEW_09H_ISR PROC FAR PUSHF

PUSH AX PUSH ES

PUSH DI PUSH DX

;Point ES:DI to the keyboard flag byte MOV AX, 40H MOV ES, AX

MOV DI, 17h MOV AL, ES:[DI] TEST AL, 00100000B ;NUM LOCK STATE ? JZ LAST IN AL, 60H CMP AL, 71H JL LAST

CMP AL, 83H JG LAST MOV AH, 02H

Page 95: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 10

COE Department KFUPM (2000 ) 93

MOV DL, 07H INT 21H

LAST: POP DI POP ES

POP AX POPF

IRET JMP CS:OLD_09H_VECTOR NEW_09H_ISR ENDP OLD_09H_VECTOR DD ? INSTALL PROC

MOV AH, 35H MOV AL, 09H INT 21H ;SAVE OLD VECTOR MOV WORD PTR OLD_09H_VECTOR, BX MOV WORD PTR OLD_09H_VECTOR + 2, ES ;INSTALL NEW INT. VECTOR MOV AX, CS MOV DS, AX MOV AH, 25H MOV AL, 09H MOV DX, OFFSET NEW_09H_ISR INT 21H MOV AX, 3100H

MOV DX, OFFSET INSTALL MOV CL, 04 SHR DX, CL INC DX INT 21H INSTALL ENDP END

Page 96: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 11

COE Department 94 KFUPM (2000 )

Experiment No 11

Using the Mouse

Introduction: The mouse is an I/O device that replaces the arrow keys on the keyboard for graphical and text style programs. This experiment shows how to add the mouse to applications through a series of macros that enable and allow the mouse to function. Objectives:

1- Develop macros that detect the mouse and enable it for applications. 2- Develop macros that track the mouse position and test button status. 3- Use the mouse in simple programs.

References: 1. Barry B. Brey, “Programming the 80286, 80386, 80486, and Pentium-Based

Personal Computer”, Prentice Hall, (1996). INT 33H: The mouse is controlled through INT 33H function call instructions. There are actually more than 50 functions for mouse control. However, we will limit ourselves to the most commonly used functions. These functions are listed in Table 11. .

Function Description Entry Exit 00 Reset Mouse AH = 00H BX = Number of Mouse Buttons 01 Show Mouse

Cursor AH = 01H Displays the mouse cursor

02 Hide Mouse Cursor

AH = 02H Hides the mouse cursor

03 Read Mouse Status on the fly

AH = 03H BX = Button Status CX= Horizontal Cursor Position DX= Vertical Cursor Position

04 Set Mouse Cursor Position

AH = 04H CX= Horizontal Cursor Position DX= Vertical Cursor Position

05 Get Button Press Information

AH = 05H BX= Desired button 0 for left and 1 for right

AX = Button Status BX = Number of presses CX= Horizontal Position of Last Press DX= Vertical Position of Last Press

Table 11. 1:Mouse (INT 33H) Functions

Page 97: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 11

COE Department KFUPM (2000 ) 95

Test the mouse: To be able to use the mouse it must be first tested wether it is present or not. To detect the presence of the mouse and be able to use it, the following steps are to be followed. Step 1: Test Interrupt Vector 33H to see if it contains a value other than zero. A zero

indicates that the mouse driver has not been installed yet. Step 2: If the vector is not zero, check if it points to an IRET (value CFH) instruction.

For some operating systems, an IRET indicates that the vector is unsued. Step 3: If the vector is neither zero nor does it point to an IRET instruction, then use

the following code to test for the presence of the mouse. MOV AX, 0000 INT 33H

If a zero is returned in AX, ther is no mouse otherwise, the mouse is present. The following MACRO tests for the presence of the mouse: MP MACRO ;Is mouse present?

LOCAL M1, M2, M3 PUSH ES MOV AX, 3533H ;Read vector 33H INT 21H MOV AX, ES OR AX, BX ;Test for ES:BX= 00 JZ M2 CMP BYTE PTR[BX], 0CFH ;Test for 0CFH JZ M2 ;If not, end macro MOV AX, 0000 ;Start mouse INT 33H OR AX, AX JZ M2 ;No mouse CLC ;If mouse, Carry = 0 JMP M3

M1 DB 13, 10,’*** MOUSE PRESENT ***’ M2: PUSH DS MOV AX, CS MOV DS, AX ;DISPLAY M1 ;Show no mouse POP DS STC ;If no mouse, carry =1 M3: POP ES ENDM

Page 98: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 11

COE Department KFUPM (2000 ) 96

Enabling the Mouse: The presence of a mouse does not mean that it can be used, unless it is enabled. The mouse cursor is enabled with INT 33H function number 01H, and disabled with function number 02H. Neither of these functions returns any information to the caller. The following macros (see below) turn the cursor ON and OFF. The mouse cursor is off until the mouse driver is enabled. If the mouse cursor is enabled and data are displayed to the screen, the computer places a copy of the mouse pointer on the screen. If n items are displayed on the screen, the mouse pointer is also displayed n times. To avoid this problem, the mouse pointer should always be turned OFF before updating the video information, and then turned ON after the update is complete. MON MACRO ;Enable Mouse Pointer MOV AX, 0001H INT 33H ENDM MOFF MACRO ;Disable Mouse Pointer MOV AX, 0002H INT 33H ENDM Tracking the Mouse Button: Mouse INT 33H function number 5 returns the button information and position of the last press. When called AX = 5 and BX = the button being tested = 0, 1 and 4 for respectively left, right and middle in case of a three button mouse. On return from function 5, AX gives the button status, i.e. if a button is being pressed.

Bit 0 = 1 for the left button Bit 1 = 1 for the right button Bit 2 = 1 for the middle button BX = number of times the button has been pressed, since the last

time this function was called. CX = horizontal position DX = vertical position

The following Macro is used for the above purpose: MBUT MACRO NUM ;Read Button MOV AX, 0005H ;NUM = 0 for left MOV BX, NUM ; NUM = 1 for right INT 33H ; NUM = 4 for middle ENDM

Page 99: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 11

COE Department KFUPM (2000 ) 97

Tracking the Mouse Position: In the 80x25-text mode, the values in CX range from 0 to 632 and the values in DX range from 0 to 192 by increments of 8. As an example line 1 position 3 returns CX = 8 and DX = 24. Function 5 returns the mouse cursor position at the most recent button press, whereas function 3 returns the mouse position on the fly, i.e. in real-time, as it occurs. The following macro is used for that purpose.

MRTime MACRO NUM ;Read Mouse Status MOV AX, 0003H INT 33H

ENDM The Mouse in Graphics Mode: To have a good understanding of how the mouse works in video mode, it is of benefit to try program 11.2. To mode the mouse cursor to position X (horizontal) and Y (vertical), use INT 10H function 02H.

Function Description Entry 02H Move Mouse Cursor AH = 02

DH = Line Number DL = Column Number

Table 11. 2: Move Cursor Function

Page 100: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 11

COE Department KFUPM (2000 ) 98

Pre Lab Work:

7- Write all macros given in the manual, and add them to your MACROS.INC file.

8- Write a program that tests the presence of the mouse using the macros given in the text.

9- Write a program that displays the word LEFT if the left button is pressed and RIGHT if the right button is pressed. Exit the program if AX indicates that both left and right buttons are pressed together. Do not forget to turn off the mouse pointer before displaying LEFT or RIGHT, and turn it back on afterwards.

10- Bring your work to the lab. Lab Work:

1- Write, link and run program 11-1. Compare the mouse pointer generated in graphics mode with the pointer generated in text mode.

2- Modify Program 11.1, so that it displays the mouse position on the top right corner of the screen. Call this program 11.3

Assignment: Write a program that displays a green square on the middle of the screen. Use the mouse, so that when the mouse enters the square, the color of the square changes to red. Modify the above program, so that when the mouse is inside the square and you want to leave the square red just press the left button.

Page 101: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 11

COE Department KFUPM (2000 ) 99

TITLE "Program 11-1" INCLUDE MACROS.INC .MODEL SMALL .STACK 200H .DATA .CODE .STARTUP MOV AX, 12H ;Switch to mode 12H INT 10H MP ;Test for mouse JC MAIN2 ;If no mouse MON ;Enable mouse pointer MAIN1: MRTIME ;Read Mouse Status on-the-fly CMP BX, 3 ;Test for left and right buttons JNE MAIN1 ;If both not pressed repeat MAIN2: MOFF ;Disable mouse pointer MOV AX, 03H ;Switch to mode 3 INT 10H .EXIT END TITLE "Program 11-2" ;a program that displays the mouse pointer and its X and Y ;position in text mode. ; .MODEL SMALL .DATA MES DB 13,'X Position = ' MX DB ' ' DB 'Y Position = ' MY DB ' $' X DW ? ;X position Y DW ? ;Y position .CODE .STARTUP CALL TM_ON ;enable mouse JC MAIN4 ;if no mouse MAIN1: MOV AX,3 ;get mouse status INT 33H CMP BX,1 JE MAIN3 ;if left button pressed CMP CX,X JNE MAIN2 ;if X position changed CMP DX,Y JE MAIN1 ;if Y position did not change MAIN2: MOV X,CX ;save new position MOV Y,DX MOV DI,OFFSET MX MOV AX,CX CALL PLACE ;store ASCII X MOV DI

Page 102: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 11

COE Department 100 KFUPM (2000 )

,OFFSET MY MOV AX,Y CALL PLACE ;store ASCII Y MOV AX,2 INT 33H ;hide mouse pointer MOV AH,9 MOV DX,OFFSET MES INT 21H ;display position MOV AX,1 INT 33H ;show mouse pointer JMP MAIN1 ;do again MAIN3: MOV AX,0 ;reset mouse INT 33H MAIN4: .EXIT ; ;procedure that tests for the presence of a mouse driver ;***Output parameters*** ;Carry = 1, if no mouse present ;Carry = 0, if mouse is present ; CHKM PROC NEAR MOV AX,3533H ;get INT 33H vector INT 21H ;returns vector in ES:BX MOV AX,ES OR AX,BX ;test for 0000:0000 STC JZ CHKM1 ;if no mouse driver CMP BYTE PTR ES:[BX],0CFH STC JE CHKM1 ;if no mouse driver MOV AX,0 INT 33H ;reset mouse CMP AX,0 STC JZ CHKM1 ;if no mouse CLC CHKM1: RET CHKM ENDP ;the TM_ON procedure tests for the presence of a mouse ;and enables mouse pointer. ;uses the CHKM (check for mouse) procedure ;***output parameters*** ;Carry = 0, if mouse is present pointer enabled ;Carry = 1, if no mouse present TM_ON PROC NEAR CALL CHKM ;test for mouse JC TM_ON1 MOV AX,1 ;show mouse pointer INT 33H CLC TM_ON1: RET TM_ON ENDP

Page 103: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 11

COE Department KFUPM (2000 ) 101

;The PLACE procedure converts the contents of AX into a ;decimal ASCII coded number stored at the memory location ;addressed by DS:DI ;***input parameters*** ;AX = number to be converted to decimal ASCII code ;DS:DI = address where number is stored ; PLACE PROC NEAR MOV CX,0 ;clear count MOV BX,10 ;set divisor PLACE1: MOV DX,0 ;clear DX DIV BX ;divide by 10 PUSH DX INC CX CMP AX,0 JNE PLACE1 ;repeat until quotient 0 PLACE2: MOV BX,5 SUB BX,CX PLACE3: POP DX ADD DL,30H ;convert to ASCII MOV [DI],DL ;store digit INC DI LOOP PLACE3 CMP BX,0 JE PLACE5 MOV CX,BX PLACE4: MOV BYTE PTR [DI],20H INC DI LOOP PLACE4 PLACE5: RET PLACE ENDP END

Page 104: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 12

COE Department 102 KFUPM (2000 )

Experiment No 12

Serial Communications

PC Interfacing Through The Serial Ports

Introduction: In general, most PCs have two or more serial ports used to interface the PC to some peripherals, printer, modem, mouse, …etc. In this experiment you will be introduced to the interfacing of two PC's through their serial ports. You will also transfer data between the two PC's. This experiment would be of interest to students who are taking COE 342 "Data Communication" course. Objectives:

1- Serial data transmission 2- Use of Interrupt 14H 3- Port configuration. 4- Sending and receiving data through the serial ports.

References:

1- Barry B. Brey, “Programming the 80286, 80386, 80486, and Pentium-Based Personal Computer”, Prentice Hall, (1996).

2- Randall Hyde, “The Art of Assembly Language Programming”, http://webster.cs.ucr.edu/Page_asm/ArtofAssembly/ArtofAsm.html

3- COE 342 "Data Communication" lecture notes. Serial Port Programming: The PC serial ports may be accessed using two different ways, either through direct programming, or using INT 14H. Programming directly the serial ports requires a deep understanding of the serial port hardware. Table 12.1 gives the addresses of the different PC serial ports, and the associated interrupt numbers.

Name Address IRQ COM 1 3F8 H 4 COM 2 2F8 H 3 COM 3 3E8 H 4 COM 4 2E8 H 3

Table 12.1: Standard Port Addresses

However, in this lab we are going to restrict ourselves to the use of INT 14H to access the serial port.

Page 105: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 12

COE Department KFUPM (2000 ) 103

INT 14H: INT 14h supports the four sub-functions, shown in table 12.2. Function Input in Output in Effect 00 AH No output Initialize Serial Port 01 AH, Character in AL Status in AX Write a Character to the Serial Port 02 AH Status in AX Read a character from the Serial

Port 03 AH Status in AX Get status of the serial port

Table 12.2: Interrupt 14h

The serial port number (0 to 3) is specified in the DX register (0=COM1:, 1=COM2:, etc.). INT 14h expects and returns other data in the AL or AX register. The different uses of the functions of INT 14H are summarized in the following sections. AH = 0: Serial Port Initialization: Sub-function zero initializes a serial port. This call lets you set the baud rate, select parity modes, select the number of stop bits, and the number of bits transmitted over the serial line. These parameters are all specified by the value in the AL register using the following bit encoding:

Bits Function 7 6 5 Baud Rate 4 3 Parity 5..7 Baud Rate 0 0 0 110 0 0 No parity 0..1 Character Size 0 0 1 150 0 1 Odd parity 2 Stop Bits 0 1 0 300 1 0 No parity 3..4 Parity Bits 0 1 1 600 1 1 Even parity 1 0 0 1200 1 0 Character Size 1 0 1 2400 2 Stop bits 1 0 7 bits 1 1 0 4800 0 One stop bit 1 1 8 bits 1 1 1 9600 1 Two stop bits

Table 12.3: Configuring a serial port

MSDOS, PC BIOS, and File I/O: Although the standard PC serial port hardware supports 19,200 baud, some BIOS's may not support this speed. Example: Initialize COM1: to 2400 baud, no parity, eight bit data, and two stop bits.

MOV AH, 0 ;INITIALIZE OPCODE MOV AL, 10100111B ;PARAMETER DATA. MOV DX, 0 ;COM1: PORT. INT 14H

After the call to the initialization code, the serial port status is returned in AX (see Serial Port Status, AH = 3, below).

Page 106: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 12

COE Department KFUPM (2000 ) 104

AH = 1: Transmit a Character to the Serial Port: This function transmits the character in the AL register through the serial port specified in the DX register. On return, if AH contains zero, then the character was transmitted properly. If bit 7 of AH contains one, upon return, then some sort of error occurred. The remaining seven bits contain all the error statuses returned by the GetStatus call except time out error (which is returned in bit seven). If an error is reported, you should use sub-function three to get the actual error values from the serial port hardware. Example: Transmit a character through the COM1 port

MOV DX, 0 ; SELECT COM1: MOV AL, ‘A’ ; CHARACTER TO TRANSMIT MOV AH, 1 ; TRANSMIT OPCODE INT 14H TEST AH, 80H ; CHECK FOR ERROR JNZ SERIALERROR

This function will wait until the serial port finishes transmitting the last character (if any) and then it will store the character into the transmit register. AH=2: Receive a Character from the Serial Port: Sub-function two is used to read a character from the serial port. On entry, DX contains the serial port number. On exit, AL contains the character read from the serial port and bit 7 of AH contains the error status. When this routine is called, it does not return to the caller until a character is received at the serial port. Example: Reading a character from the COM1 port

MOV DX, 00 ; SELECT COM1: MOV AH, 02 ; RECEIVE OPCODE INT 14H TEST AH, 80H ; CHECK FOR ERROR JNZ SERIALERROR <RECEIVED CHARACTER IS NOW IN AL>

AH=3: Serial Port Status: This call returns status information about the serial port including whether or not an error has occurred, if a character has been received in the receive buffer, if the transmit buffer is empty, and other pieces of useful information. On entry into this routine, the DX register contains the serial port number. On exit, the AX register contains the following values:

Page 107: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 12

COE Department KFUPM (2000 ) 105

AX Bit Meaning

0 Clear to send 1 Data set ready 2 Trailing edge ring detector 3 Receive line signal detect 4 Clear to send (CTS) 5 Data set ready (DSR) 6 Ring indicator 7 Receive line signal detect 8 Data available 9 Overrun error

10 Parity error 11 Framing error 12 Break detection error 13 Transmitter holding register empty 14 Transmitter shift register empty 15 Time out error

Table 12.4: Getting the status of a serial port

There are a couple of useful bits, not pertaining to errors, returned in this status information. If the data available bit is set (bit #8), then the serial port has received data and you should read it from the serial port. The Transmitter holding register empty bit (bit #13) tells you if the transmit operation will be delayed while waiting for the current character to be transmitted or if the next character will be immediately transmitted. By testing these two bits, you can perform other operations while waiting for the transmit register to become available or for the receive register to contain a character.

Page 108: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 12

COE Department KFUPM (2000 ) 106

Pre Lab Work:

1- Read and understand material related to INT 14h. 2- Write program 12.1 and understand what the program is doing. 3- Write program 12.2 and understand what the program is doing.

Lab Work:

1- To be able to run the programs, you need to connect the PC's through their serial ports COM1 or COM2, with serial cables terminated by D9 type connectors. You will be supplied with such cables in the lab. You need also to work in groups of two.

2- Run program 12.1 and notice what the program is doing. 3- Run program 12.2 and notice what the program is doing 4- Modify program 12.1 to make it send at a baud rate of 9600. 5- Modify program 12.1 to make it send a string of 3 characters. 6- Modify program 12.2 to make it receive a string of 3 characters at a baud

rate of 9600. Lab Assignment: Develop a program that displays a menu consisting of the following choices:

• Configure Serial Port: prompts the user to enter one of the standard baud rate values. The program then configures the COM1 port with the given baud rate. (The rest of the configuration with default values)

• Send String: prompts the user to enter the length of the string and then enter the string character by character. The program sends each character as soon as it is entered.

• Receive String: prompts the user to enter the length of the string. It then receives the string character by character and displays it on the screen.

• Send File (Optional): prompts the user to enter the location of the file and then sends that file. (Needs more information about handling files. Ask the instructor for References to that information.)

• Receive File (Optional): receives the file. (Needs more information about handling files. Ask the instructor for References to that information.)

Page 109: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 12

COE Department KFUPM (2000 ) 107

TITLE ‘Program 12.1’ ;This program configures the serial port (COM1) and sends a character through that port. .MODEL SMALL .STACK 200 .DATA PROMPT DB ‘Enter the character to be sent’,0DH,0AH,’$’ SENT DB ‘The character has successfully been sent’,’$’

ERROR DB ‘An error occurred. Please check your hardware and try again.’,’$’ .CODE .STARTUP

MOV AH, 0H ; INITIALIZE OPCODE MOV AL, 10100111B ; PARAMETER DATA. MOV DX, 0H ; COM1: PORT. INT 14H LEA DX, PROMPT ; DISPLAY PROMPT ON SCREEN MOV AH, 09H INT 21H MOV AH, 01H ; READ THE CHARACTER FROM KEYBOARD INT 21H MOV DX, 0H ; SELECT COM1: MOV AH, 1H ; TRANSMIT OPCODE INT 14H TEST AH, 80H ; CHECK FOR ERROR JNZ PORTERROR LEA DX, SENT ; DISPLAY THAT THE CHARACTER WAS SENT MOV AH, 09H INT 21H JMP FINISH PORTERROR: LEA DX, ERROR ; DISPLAY THAT THERE WAS AN ERROR MOV AH, 09H INT 21H FINISH:

.END

Page 110: COE 205 Lab Manual

COE 205 Lab Manual Experiment No 12

COE Department KFUPM (2000 ) 108

TITLE ‘Program 12.2’ ;This program configures the serial port (COM1) and receives a character through that port. .MODEL SMALL .STACK 200 .DATA PROMPT DB ‘Receiving character. Please wait.’,0DH,0AH,’$’ RECEIVED DB ‘The character has been received.’,0DH,0AH,’$’

ERROR DB ‘An error occurred. Please check your hardware and try again.’,’$’

CHAR DB ‘The received character is: ‘,’$’ .CODE .STARTUP

MOV AH, 0H ; INITIALIZE OPCODE MOV AL, 10100111B ; PARAMETER DATA. MOV DX, 0H ; COM1: PORT. INT 14H LEA DX, PROMPT ; DISPLAY PROMPT ON SCREEN MOV AH, 09H INT 21H MOV DX, 0H ; SELECT COM1: MOV AH, 02H ; RECEIVE OPCODE INT 14H TEST AH, 80H ; CHECK FOR ERROR JNZ PORTERROR LEA DX, RECEIVED ; DISPLAY THAT THE CHARACTER WAS

RECEIVED MOV AH, 09H INT 21H LEA DX, CHAR ; DISPLAY CHAR MESSAGE MOV AH, 09H INT 21H MOV DL, AL ; DISPLAY THE CHARACTER ON SCREEN MOV AH, 02H INT 21H JMP FINISH PORTERROR: LEA DX, ERROR ; DISPLAY THAT THERE WAS AN ERROR MOV AH, 09H INT 21H FINISH:

.END