COE 205 Lab Manual Computer Engineering Department

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)
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
II
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)
2)
3)
4)
5)
6)
7)
8)
9)
10)
11)
12)
Introduction to assembly language programming using MASM
Input and Output
Segmentation and Addressing Modes
Indexing and Data Manipulation
Logic Instructions
Shift Rotate and Jump Instructions
Subroutine Handling Instructions and Macros
String Handling Instructions
Accessing Video Memory
Interrupts
Using the Mouse
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.
III
Experiment No 1
COE 205 Lab Manual
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:
12345-
Introduction to the Microsoft Macro Assembler (MASM)
General structure of an assembly language program
Use of the Dos Debugger program
Use of the PWB, and Code View (CV).
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:
1
2
3
4
STEP
Editing
Assembling
Linking
Executing
PRODUCES
Source File
Object File
Executable File
Results
Table 1.1: Assembly Language Programming Phases
COE Department
2
KFUPM (2000 )
Experiment No 1
COE 205 Lab Manual
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 relinked. 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.
COE Department
3
KFUPM (2000 )
Experiment No 1
COE 205 Lab Manual
The DOS-Debugger:
The DOS “Debug” program is an example of a simple debugger that comes with MSDOS. 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
Assemble
Compare
Dump
Enter
Fill
Go
Hex
Input
Load
Move
Name
Output
Proceed
Quit
Register
Search
Trace
Unassemble
Write
SYNTAX
A [address]
C range address
D [range]
E address [list]
F range list
G [=address] [addresses]
H value1 value2
I port
L [address] [drive] [first sector] [number]
M range address
N [pathname] [argument list]
O port byte
P [=address] [number]
Q
R [register]
S range list
T [=address] [value]
U [range]
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.
COE Department
4
KFUPM (2000 )
Experiment No 1
COE 205 Lab Manual
The following are the steps used if you are to run MASM from DOS.
1
2
3
4
COMMAND
FILE NAME
Edit, any editor will do
Name.asm
Masm Filename
Name.obj
Link Filename
Name.exe
Filename
Note: Steps 2 and 3 may be done in one Name.asm and
single command: ML filename.asm
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
COE Department
5
KFUPM (2000 )
Experiment No 1
COE 205 Lab Manual
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.
COE Department
6
KFUPM (2000 )
Experiment No 1
COE 205 Lab Manual
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.
COE Department
7
KFUPM (2000 )
Experiment No 1
COE 205 Lab Manual
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?
COE Department
8
KFUPM (2000 )
Experiment No 1
COE 205 Lab Manual
; The following lines are just comments, they may be omitted,
; However, they are very useful.
; COE 205: Lab Exp. # 1
; Student Name:
Program # 1
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
; Student Name:
Program # 2
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
MOV
MOV
MULT: ADD
DEC
JNZ
MOV
AX,00
BX,MULT1
CX,MULT2
AX,BX
CX
MULT
DX,AX
MOV AX,4C00H
INT 21H
END
COE Department
9
KFUPM (2000 )
Experiment No 2
COE 205 Lab Manual
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
01H
Input in
AH
Output in
AL
02H, 06H AH,
Character in DL
08H
AH
09H
AH
No output
0AH
Offset in
DX
AH
AL
No output
Effect
Read a character with echo on the
screen.
Display a character on the screen.
Note: Interrupted by Ctrl + Break
Read character without echo.
Display a string terminated by a
‘$’ sign
Read a string of characters from
the keyboard
Table 2. 1: Simple I/O DOS function calls
COE Department
10
KFUPM (2000 )
Experiment No 2
COE 205 Lab Manual
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
MOV DL, Character Code
INT 21H
;(Or: MOV AH, 02H)
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.
COE Department
11
KFUPM (2000 )
Experiment No 2
COE 205 Lab Manual
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
Entry
Exit
Read from Keyboard
AH = 0AH ; DX = address of keyboard input buffer
First byte of buffer contains the size of the buffer (up to 255)
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.
COE Department
12
KFUPM (2000 )
Experiment No 2
COE 205 Lab Manual
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:
COE Department
13
KFUPM (2000 )
Experiment No 2
COE 205 Lab Manual
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.
COE Department
14
KFUPM (2000 )
Experiment No 2
COE 205 Lab Manual
; 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’
INT 21H
; LOAD CHARACTER TO BE DISPLAYED
; CALL INTERRUPT 21H
MOV DL,X
INT 21H
; LOAD CHARACTER TO BE DISPLAYED
; CALL INTERRUPT 21H
MOV DL,Y
INT 21H
; LOAD CHARACTER TO BE DISPLAYED
; 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
INT 21H
; Exit to DOS
END
COE Department
15
KFUPM (2000 )
Experiment No 2
COE 205 Lab Manual
; 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
MOV DL,AL
INT 21H
; Function 02H, display character
; Load character to be displayed
;
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
MOV DL,BL
INT 21H
; Function 02H, display character
; Load character to be displayed from BL
MOV AH,4CH
INT 21H
; Exit to DOS
END
COE Department
16
KFUPM (2000 )
Experiment No 3
COE 205 Lab Manual
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.
Addressing
Mode
Example
Register
Immediate
Direct
Register-Indirect
Based
Indexed
Based-Indexed
MOV AX,BX
MOV AX, 0F7H
MOV AX,[1234H]
MOV AX,[BX]
MOVAX,[BX+06]
MOVAX,[SI+06]
MOV AX,[BX+SI+06]
Source operand
Assuming: DS = 1000H, BX = 0200H, SI = 0300H
Type
Address Generation
Addres
s
Register
Immed.
Mem.
DS x 10H +1234H
11234H
Mem.
DS x 10H +0200H
10200H
Mem.
DS x 10H +0200H + 0006H
10206H
Mem.
DS x 10H +0300H + 0006H
10306H
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:
COE Department
17
KFUPM (2000 )
Experiment No 3
COE 205 Lab Manual
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
TINY
SMALL
MEDIUM
COMPACT
LARGE
HUGE
Size of Code and Data
Code and data no more than 64KB combined
Code and data segments must be no more than 64KB each
Code can be more than 64KB, data still limited to no more than
64KB
Code limited to no more than 64KB, data can be more than
64KB
Code and data can each be more than 64K, no array can be
larger than 64KB
Code and data can each be more than 64KB, arrays can be
larger than 64KB
Table 3.3: Memory Models
COE Department
18
KFUPM (2000 )
Experiment No 3
COE 205 Lab Manual
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.
COE Department
19
KFUPM (2000 )
Experiment No 3
COE 205 Lab Manual
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.
Again:
MOV CX, Number_of_bytes_read
Start loop here
; Convert to small letters.
LOOP Again
COE Department
20
KFUPM (2000 )
Experiment No 3
COE 205 Lab Manual
; 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
COE Department
21
KFUPM (2000 )
Experiment No 3
COE 205 Lab Manual
TITLE “PROGRAM 2 EXPERIMENT 3”
; This program displays a message and reads a new message from the keyboard
.MODEL SMALL
.STACK 200
.DATA
CRLF
PROMPT
STRING1
STRING2
DB
DB
DB
DB
0DH,0AH,'$'
'Enter a name of max. length 30 char.: ',0DH,0AH,'$'
'Mr. ','$'
' studies 8086 programming. ','$'
; Allocate 32 bytes for BUFFER, and put the value 31 in the second byte.
BUFFER
DB
31,32 DUP(?)
.CODE
.STARTUP
LEA DX,PROMPT
MOV AH,09H
INT 21H
;This directive initializes the DS and CS segments.
;display prompt
MOV AH,0AH
LEA DX, BUFFER
INT 21H
;read into buffer
LEA DX, CRLF
MOV AH,09H
INT 21H
;move cursor to next line
LEA DX,STRING1
MOV AH,09H
INT 21H
;display string1
;now display the buffer i.e. what has been read.
MOV AH,09H
MOV BH,00H
MOV BL,BUFFER[1]
MOV BUFFER[BX+2],'$'
LEA DX,BUFFER[2]
INT 21H
;move in BL buffer length
;put a $ sign at the end of buf
;load actual length of buffer
LEA DX,STRING2
MOV AH,09H
INT 21H
;display string2
LEA DX, CRLF
MOV AH,09H
INT 21H
;move cursor to next line
MOV AH, 02H
MOV DL,BUFFER[1]
ADD DL, 30H
INT 21H
MOV AX,4C00H
INT 21H
; display number of characters read if less than 10
; read second byte of buffer
; convert to number
END
COE Department
22
KFUPM (2000 )
Experiment No 3
COE 205 Lab Manual
COE 205
Experiment 3, Program #1:
Section:
Student Name:
Date:
Student ID:
Source
Instruction
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
COE Department
Address/
Register
Destination
Content
Address/
Register
Addressing
Mode
Contents
Before
After
Before INT 21H, IP =
After INT 21H, IP =
Before INT 21H IP =
After INT 21H IP =
Before INT 21H IP =
After INT 21H IP =
Before INT 21H IP =
After INT 21H IP =
S
23
k
i
p
KFUPM (2000 )
Experiment No 3
COE 205 Lab Manual
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
COE Department
24
KFUPM (2000 )
Experiment No 4
COE 205 Lab Manual
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.
COE Department
25
KFUPM (2000 )
Experiment No 4
COE 205 Lab Manual
Table 4.1: ASCII Table
Character
a
A
β
%
Column #
6
4
E
2
Row #
1
1
1
5
Code (H)
61
41
E1
25
Code (10)
96 + 1 = 97
64 + 1 = 65
224 + 1 = 225
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:
COE Department
Y
DW
13EFH
26
KFUPM (2000 )
Experiment No 4
COE 205 Lab Manual
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
MOV [DI+6],AL
MOV SI,3
MOV Array2[SI],AL
; Address Array2
; Copy to 7th element of Array2
;Copy to 4th element of Array2
Based-Indexed addressing mode:
MOV BX, OFFSET Array3
MOV SI,1*RowSize
MOV DI,2*RowSize
MOV AL, [BX+SI+1]
MOV [BX+DI+2],AL
; Address Array3
; Beginning of 2nd row
; Beginning of 3rd row
; Access 2nd element of 2nd row
; Access 3rd element of 3rd row
Remark:
Notice that row R, has index (R-1), and element n has index (n-1).
COE Department
27
KFUPM (2000 )
Experiment No 4
COE 205 Lab Manual
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:
1234-
Assemble, Link and Run program 1.
How many digits can you enter each time? Explain this.
What happens when the sum exceeds 9? Explain this.
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).
COE Department
28
KFUPM (2000 )
Experiment No 4
COE 205 Lab Manual
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
INT
SUB
MOV
AH,01H
21H
AL,30H
CL,AL
;READ FIRST NUMBER
LEA
MOV
INT
LEA
MOV
INT
DX,CRLF
AH,09H
21H
DX,PROMPT2
AH,09H
21H
;MOVE CURSOR TO NEXT LINE
MOV
INT
SUB
ADD
AH,01H
21H
AL,30H
AL,CL
;READ SECOND NUMBER
MOV CL,AL
ADD CL,30H
LEA
MOV
INT
LEA
MOV
INT
.EXIT
END
DX,CRLF
AH,09H
21H
DX,PROMPT3
AH,09H
21H
MOV DL,CL
MOV AH,02H
INT 21H
COE Department
;Convert character to number
;SAVE THE NUMBER IN CL
;DISPLAY PROMPT2
;Convert character to number
;PERFORM ADDITION AND SAVE RESULT IN CL
;CONVERT DIGIT TO CHARACTER
;MOVE CURSOR TO NEXT LINE
;DISPLAY PROMPT3
;DISPLAY SUM
29
KFUPM (2000 )
Experiment No 4
COE 205 Lab Manual
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
COE Department
30
KFUPM (2000 )
Experiment No 5
COE 205 Lab Manual
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.
Type
Instruction
Example
Meaning
Addition
ADD
ADC
INC
DAA
SUB
SBB
DEC
DAS
NEG
MUL
AX ← AX + 7B
DIV
ADD AX,7BH
ADC AX,7BH
INC [BX]
DAA
SUB CL,AH
SBB CL,AH
DEC DAT
DAS
NEG CX
MUL CL
MUL CX
IMUL BYTE PTR X
IMUL WORD PTR X
DIV WORD PTR X
IDIV
IDIV BH
CBW
CWD
CBW
CWD
Subtraction
Multiplication
IMUL
Division
Sign Extension
Flags Affected
OF
SF
ZF
AF
PF
CF
*
*
*
?
*
*
*
?
*
*
*
*
*
*
*
*
*
*
*
?
*
*
*
*
*
*
*
*
*
?
*
*
*
*
*
*
*
*
*
?
*
*
*
*
*
*
*
*
*
?
*
*
*
*
*
*
*
*
AX ← AL * [X]
(DX,AX) ← AX* [X]
*
?
?
?
?
*
AX ← Q(([DX,AX])/[X])
DX ←R(([DX,AX])/[X])
AL ← Q(AX/BH)
AH ←R(AX/BH)
AH ← MSB(AL)
?
?
?
?
?
?
?
?
?
?
?
?
-
-
-
-
-
-
AX ← AX + 7B +CF
[BX]←[BX]+1
CL ← CL – AH
CL ← CL – AH – CF
[DAT] ← [DAT] – 1
CX ← 0 – CX
AX ← AL * CL
(DX,AX) ← AX* CX
DX ← MSB(AX)
Table 5.1: Summary of Arithmetic Instructions of the 8086 microprocessor
COE Department
31
KFUPM (2000 )
Experiment No 5
COE 205 Lab Manual
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 lowlevel control of input/output devices. The list of the logic operations of the 8086 is
given in Table 5.1, along with examples, and the effect of these operations on the
flags. The “*” in the table means that the corresponding flag may change as a result of
executing the instruction. The “-” means that the corresponding flag is not affected by
the instruction, whereas the “?” means that the flag is undefined after executing the
instruction.
Instruction
AND
OR
XOR
NOT
Example
AND AX, FFDFH
OR AL, 20H
XOR NUM1, FF00
NOT NUM2
Meaning
AX ← AX AND FFDFH
AL ← AL OR 20H
[NUM1]←[NUM1]XOR FF00
_______
[NUM2]←[ NUM2]
Flags
OF
SF
ZF
AF
PF
0
0
0
-
*
*
*
-
*
*
*
-
?
?
?
-
*
*
*
-
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:
COE Department
32
KFUPM (2000 )
Experiment No 5
COE 205 Lab Manual
Operation
b AND 0 =
b OR 1 =
b XOR 1 =
b XOR 0 =
0
1
b
b
Effect
Reset the bit
Set the bit
Complement the bit
-
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
MUL CH
XOR AH, AH
OR AL, CL
; Use MUL by 10000B to shift left by 4 bits
; Shift AL 4 bits to the left
; Clear AH
; 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
COE Department
33
KFUPM (2000 )
Experiment No 5
COE 205 Lab Manual
; 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.
2.
3.
4.
Divide the number to be converted by the desired radix (number base r).
Save the remainder as a significant digit of the result.
Repeat steps 1 and 2 until the resulting quotient is zero.
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.
COE Department
34
KFUPM (2000 )
Experiment No 5
COE 205 Lab Manual
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.
COE Department
35
KFUPM (2000 )
Experiment No 5
COE 205 Lab Manual
TITLE “Program 5.1: Logic Instructions”
; This program shows the effect of the logic instructions
.MODEL SMALL
.STACK 200
.DATA
NUM1 DW
NUM2 DB
.CODE
.STARTUP
MOV
AND
OR
XOR
0FA62H
94H
AX, NUM1
AX, 0FFDFH
AL, 20H
NUM1, 0FF00H
;load AX with number NUM1
;Reset 6th bit of AX
;Set 6th bit of AL
;Complement the high order byte of
; NUM1
;Complement NUM2
;Clear AX
NOT NUM2
XOR AX, AX
MOV AX, NUM1
AND AX, 0008H
XOR AX, 0080H
; Isolate bit 4 of NUM1
;Complement 4th bit of AX
.EXIT
END
Fill in table 5.3 while running the above program using CodeView.
Destination Content
Statement
1.
2.
3.
4.
5.
6.
7.
8.
9.
Before
After
Status Flags
O
F
D
F
I
F
S
F
Z
F
A
F
P
F
C
F
MOV AX, NUM1
AND AX, 0FFDFH
OR AL, 20H
XOR NUM1, 0FF00H
NOT NUM2
XOR AX, AX
MOV AX, NUM1
AND AX, 0008H
XOR AX, 0080H
Table 5.4: Effects of Executing Program 5.1
COE Department
36
KFUPM (2000 )
Experiment No 5
COE 205 Lab Manual
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
NUM DW 0EFE4H
;radix: 10 for decimal
;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
MOV
XOR
MOV
XOR
DISPX1:
MOV
DIV
MOV
INC
INC
OR
JNZ
DEC
DISPX2:
MOV
MOV
ADD
INT
DEC
DEC
JNZ
.EXIT
END
COE Department
CX, 0
BH, BH
BL, RADIX
SI, SI
DX, 00
BX
TEMP[SI], DL
SI
CX
AX, AX
DISPX1
SI
DL, TEMP[SI]
AH, 06H
DL, 30H
21H
SI
CX
DISPX2
;load AX with number NUM
;display AX in decimal
;clear digit counter
;clear BH
;set for decimal
;Clear SI register
;clear DX
;divide DX:AX by 10
;save remainder
;count remainder
;test for quotient of zero
;if quotient is not zero
;get remainder
;select function 06H
;convert to ASCII
;display digit
;repeat for all digits
;exit to dos
37
KFUPM (2000 )
Experiment No 6
COE 205 Lab Manual
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:
12345-
Shift Instructions.
Rotate Instructions.
Compare Instruction.
Jump Instructions.
Loop Instructions.
-
Textbook: Sections 3.4, 3.5 and 4.1,
Lecture notes.
References:
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 bitlocation. 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.
COE Department
38
KFUPM (2000 )
Experiment No 6
COE 205 Lab Manual
Type
F. Flags
Instruction
Example
Shift
Rotate
SHL
SHL AX,1
SAL
SAL AX,1
SHR
SHR NUM2,CL
SAR
SAR NUM2,CL
ROL
ROL BH,CL
RCL
RCL BH,CL
ROR
ROR NUM1,1
RCR
RCR NUM1,1
Meaning
Shift AX left by 1 bit. Fill
vacated bit with 0.
Shift AX left by 1 bit. Fill
vacated bit with 0.
Shift NUM2 right by the
number of bits indicated in CL.
Fill vacated bits with 0.
As SHR but fill vacated bits
with the sign bit.
Same as SHL, but shifted bits
are fed back to fill vacated bits.
Same as ROL, but carry flag is
appended as MSB, and its
content is shifted with the
number.
Same as SHR, but shifted bits
are fed back to fill vacated bits.
Same as ROR, but carry flag is
appended as LSB, and its
content is shifted with the
number.
OF
SF
ZF
AF
PF
CF
*
*
*
?
*
*
*
*
*
?
*
*
*
0
*
?
*
*
*
*
*
?
*
*
*
-
-
-
-
*
*
-
-
-
-
*
*
-
-
-
-
*
*
-
-
-
-
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
CMP
Example
CMP AX, BX
Meaning
If (AX = BX) then ZF Í 1 and CF Í 0
If (AX < BX) then ZF Í 0 and CF Í 1
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 intrasegment 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.
COE Department
39
KFUPM (2000 )
Experiment No 6
COE 205 Lab Manual
Type
Unconditional
Comparisons
Carry
Overflow
Parity Test
Sign Bit
Zero Flag
Instruction
Meaning (jump if)
Condition
JMP
JA
JAE
JB
JBE
JE
JNE
JG
JGE
JL
JLE
JCXZ
JC
JNC
JNO
JO
JNP
JP
JNS
JS
JZ
JNZ
unconditional
above (not below or equal)
above or equal (not below)
below (not above or equal)
below or equal (not above)
equal ( zero)
not equal (not zero)
greater (not lower or equal)
greater or equal (not lower)
lower (not greater or equal)
lower or equal (not greater)
CX register is zero
Carry
no carry
no overflow
overflow
no parity (parity odd)
parity (parity even)
no sign
sign
zero
non-zero
None
CF = 0 and ZF = 0
CF = 0
CF = 1
CF = 1 or ZF = 1
ZF = 1
ZF = 0
ZF = 0 and SF = OF
SF = OF
(SF xor OF) = 1 i.e. SF ≠ OF
(SF xor OF or ZF) = 1
(CF or ZF) = 0
CF = 1
CF = 0
OF = 0
OF =1
PF = 0
PF = 1
SF = 0
SF = 1
ZF = 1
ZF = 0
jnbe
jnb
jnae
jna
jz
jnz
jnle
jnl
jnge
jng
loop
jpo
jpe
Table 6. 3: Jump Instructions of the 8086 Microprocessor
Label
Pointer
Short
Near
Far
*
Range
Addressing
Mode
Specified By
Encoded As
Directive
+127/-128 bytes
IP Í IP + Offset
Intra-segment
IP Í Address
Immediate
Word
Differentially*
SHORT
Immediate
Word
Differentially
Register
Word
Absolute address
Memory
Word
Absolute address
Immediate
Double Word
Absolute address
Memory
Double Word
Absolute address
Inter-segment
IP Í Address
CS Í Segment
NEAR PTR
FAR PTR
Differentially = Difference between current and next address.
Table 6. 4: Jump Instructions and Addressing Modes
Instruction
JMP
JNZ
JE
JC
Example
Meaning
JMP FAR PTR [BX]
JNZ END
JE FIRST
JC SECOND
IP Í [BX], CS Í[BX+2]
If (ZF=0) Then IP Í Offset of END
If (ZF=1) Then IP Í Offset of FIRST
If (CF=1) Then IP Í Offset of SECOND
Table 6. 5: Examples of Jump Instructions of the 8086 Microprocessor
COE Department
40
KFUPM (2000 )
Experiment No 6
COE 205 Lab Manual
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
LOOP
LOOPE
LOOPZ
LOOPNE
LOOPNZ
Example
Meaning
LOOP Label1
LOOPE Label1
If (CX≠0) then IP Í Offset Label1
If (CX≠0 and ZF = 0) then IP Í Offset Label1
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
Code
Repeat-Until
; Repeat until CX = 0
MOV CX, COUNT
Again:
LOOP Again
-
While-Do
; While (CX ≠ 0) Do
MOV CX, COUNT
Again:
JZ Next
LOOP Again
Next:
-
Table 6. 7: The Loop Program Structure.
COE Department
41
KFUPM (2000 )
Experiment No 6
COE 205 Lab Manual
Pre Lab Work:
1.
2.
3.
4.
5.
6.
Complete program 6.1, according to the given guidelines.
Check on some values and see if it is working properly.
Comment on the program, trying to understand how conversion is done.
Write program 6.2 and make sure it contains no errors.
Do the modifications given in the guidelines. This will be program 6.3.
Bring your work to the lab.
Lab Work:
12345-
Show program 6.1 and your comments to your lab instructor.
Run program 6.2 using CodeView.
See what the effect of such program on NUM1 is.
Run program 6.3, and see the effect on NUM1 after displaying NUM2.
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.
7
6
5
4
3
Bit ( i ) Í Bit ( 7- i )
2
for
1
0
i =0–7
Figure 6. 1: Bit Shuffling
COE Department
42
KFUPM (2000 )
Experiment No 6
COE 205 Lab Manual
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
;DISPLAY PROMPT3
CALL RESULT
; ADD THE TWO NUMBERS
.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
COE Department
43
KFUPM (2000 )
Experiment No 6
COE 205 Lab Manual
;***************************************************
; 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
COE Department
44
KFUPM (2000 )
Experiment No 8
COE 205 Lab Manual
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:
12345-
Procedures and Procedure Calls
Parameter Passing through Memory, Registers and the Stack
Use of Macros
Look-up Tables
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
COE Department
45
KFUPM (2000 )
Experiment No 8
COE 205 Lab Manual
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.
COE Department
46
KFUPM (2000 )
Experiment No 8
COE 205 Lab Manual
Instruction
PUSH
Example
PUSH AX
POP
POP NUM1
PUSHF
PUSHF
POPF
POPF
Meaning
[SP] Í AH
[SP-1] Í AL
SP
Í SP –2
[NUM1] Í [SP]
[NUM+1] Í [SP+1]
SP
Í SP + 2
[SP-1] Í MSB(FR)
[SP-2] Í LSB(FR)
SP
Í SP –2
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 (intersegment).
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.
COE Department
47
KFUPM (2000 )
Experiment No 8
COE 205 Lab Manual
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 fivebyte 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
COE Department
48
KFUPM (2000 )
Experiment No 8
COE 205 Lab Manual
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.
Note:
Instruction
CALL
Example
CALL SQRT
RET
RET
Effect
[SP-1] Í 34
[SP-2] Í 5B
SP
Í SP-2
IP
Í 34A0
LSB(IP) Í [SP]
MSB(IP) Í [SP+1]
SP
Í SP + 2
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.
COE Department
49
KFUPM (2000 )
Experiment No 8
COE 205 Lab Manual
Effect: Read system date
Function
ENTRY
2AH
Note
Exit
AH = 2AH
AL = Day of the week
CX = Year (1980-2099)
DH = Month
DL = Day of the month
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.
COE Department
50
KFUPM (2000 )
Experiment No 8
COE 205 Lab Manual
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.
COE Department
51
KFUPM (2000 )
Experiment No 8
COE 205 Lab Manual
TITLE “Program 7.1”
; a program that display OK on the monitor screen using procedure DISP
.MODEL TINY
.CODE
.STARTUP
; select TINY model
; indicate start of CODE segment
; indicate start of program
MOV BX, OFFSET DISP
MOV DL, 'O'
CALL BX
MOV DL, 'K'
CALL BX
.EXIT
; address DISP with BX
; display 'O'
; display 'K'
; 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
TABLE DW
DW
DW
.CODE
ONE PROC
MOV
MOV
INT
RET
ONE
ENDP
TWO
TWO
PROC
MOV
MOV
INT
RET
ENDP
COE Department
ONE
TWO
THREE
; indicate start of DATA segment
; define lookup table
; indicate start of CODE segment
NEAR
AH, 2
DL, 'A'
21H
NEAR
AH, 2
DL, 'B'
21H
; display a letter A
; display letter B
52
KFUPM (2000 )
Experiment No 8
COE 205 Lab Manual
THREE PROC
MOV
MOV
INT
RET
THREE ENDP
NEAR
AH, 2
DL, 'C'
21H
; display letter C
; 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
.STACK
100
.DATA
CRLF DB 0DH,0AH,'$'
PROMPT1 DB 'Today is : ','$'
; select SMALL model
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
MOV AH, 09H
INT 21H
;MOVE CURSOR TO NEXT LINE
.EXIT
END
COE Department
53
KFUPM (2000 )
Experiment No 8
COE 205 Lab Manual
TITLE “Program 7.4”
; This program reads a string of 200 characters max. and encrypts it.
.MODEL SMALL
.STACK 100
.DATA
CRLF
PROMPT1
STRING
CODED
UTAB
LTAB
DB
DB
DB
DB
DB
DB
0DH,0AH,'$'
'Enter a string : ','$'
100 DUP(?)
100 DUP(?)
'MNBVCXZLKJHGFDSAPOIUYTREWQV'
'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
COE Department
54
KFUPM (2000 )
Experiment No 8
COE 205 Lab Manual
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
CLD
STD
Operation
Clear DF; (DF) Å 0
Set DF;
(DF) Å 1
Mode
Auto Increment
Auto Decrement
Effect
SI Å SI + 1; DI Å DI +1
SI Å SI - 1; DI Å DI -1
Table 8. 1: Auto- incrementing and decrementing in string instructions
COE Department
55
KFUPM (2000 )
Experiment No 8
COE 205 Lab Manual
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
LODS
STOS
Meaning
Format
Load string
LODSB
LODSW
STOSB
STOSW
MOVSB
MOVSW
Store string
Move string
MOVS
Operation
As per Direction Flag
Flags
affected
(AL or AX) Å ((DS)0+(SI))
(SI) Å (SI) ± 1 or 2
((ES)0 + (DI)) Å (AL or AX))
(DI) Å (DI) ± 1 or 2
((ES)0 + (DI)) Å ((DS)0+(SI))
(SI) Å (SI) ± 1 or 2
(DI) Å (DI) ± 1 or 2
None
None
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
LEA SI, BLK1
LEA DI, BLK2
MOV CX, N
CLD
NEXT: MOVSB
COE Department
; Make ES = DS
; Source address for block1
; Destination address for block2
; N = number of bytes to move
; Set Auto-Increment mode
; Move one byte at a time
LOOP NEXT
56
KFUPM (2000 )
Experiment No 8
COE 205 Lab Manual
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
CMPS
Compare
strings
CMPSB
CMPSW
SCAS
Scan string
SCASB
SCASW
Set flags as per:
((ES)0 + (SI)) – ((ES)0+(DI))
(SI) Å (SI) ± 1 or 2
(DI) Å (DI) ± 1 or 2
Set flags as per:
(AL or AX) – ((ES)0+(DI))
(DI) Å (DI) ± 1 or 2
Flags
affected
CF,PF,AF,
ZF,SF,OF
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
COE Department
57
KFUPM (2000 )
Experiment No 8
COE 205 Lab Manual
Prefix
Used with
Meaning
REP
MOVS
STOS
CMPS
SCAS
CMPS
SCAS
Repeat while not end of string
CX ≠ 0
Repeat while not end of string and strings are equal
CX ≠ 0 and ZF = 1
Repeat while not end of string
And strings are not equal
CX ≠ 0 and ZF = 0
REPE
REPZ
REPNE
REPNZ
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
CLD
MOV CX, 100
MOV AL, 45H
REPNE SCASB
;address data
;auto-increment
;load counter
;AL = 45H
;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
MATCH
COE Department
PROC FAR
MOV SI, OFFSET LINE
MOV DI, OFFSET TABLE
CLD
MOV CX, 10
REPE CMPSB
RET
ENDP
58
KFUPM (2000 )
Experiment No 8
COE 205 Lab Manual
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.
COE Department
59
KFUPM (2000 )
Experiment No 8
COE 205 Lab Manual
TITLE “Program 8.1”
;This program clears the video text display
.MODEL TINY
.CODE
.STARTUP
CLD
MOV
MOV
AX,0B800H
ES,AX
;select increment mode
;address segment B800H
MOV
MOV
MOV
DI,0000
CX,25*80
AX,0720H
;Video Text Memory = B800:0000
;address offset 0000
;load count: 25 lines per 80 columns
;load data AH= 07H = color: white text on black
;background. AL = 20H = space
REP
STOSW
;clear the screen
.EXIT
END
;exit to DOS
;end of file
;-------------------------------------------------------------
TITLE “Program 8.2”
;This program scrolls the display one line up
.MODEL TINY
.CODE
.STARTUP
;select TINY model
;indicate start of CODE segment
;indicate start of program
CLD
MOV
MOV
MOV
AX,0B800H
ES, AX
DS, AX
MOV
MOV
MOV
REP
SI,160
DI,0
CX,24*80
MOVSW
MOV DI,24*80*2
MOV CX,80
MOV AX,0720H
REP STOSW
.EXIT
END
COE Department
;select increment
;load ES and DS with B800
;address line 1: 160 = 2 * 80
;address line 0
;load count
;scroll screen
;clear bottom line
;exit to DOS
;end of file
60
KFUPM (2000 )
Experiment No 8
COE 205 Lab Manual
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
COE Department
61
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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
COE Department
62
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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.
P0
P0
P1
P2
P3
P1
Plane 0
P0
P1
P1
P1
Plane 1
Plane 2
Plane 3
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
MOV AL, 08
OUT DX, AL
; Select VGA address card
; Index of 8
; 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.
COE Department
63
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
MOV DX, 03CFH
MOV AL, 80H
OUT DX, AL
; Select BMR
; Place mask in 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
MOV AL, 02
OUT DX, AL
; Select VGA sequencer register
; Index of 2
; Select Index 2
MOV DX, 03C5H
MOV AL, 0FH
OUT DX, AL
; Address MMR
; Mask to 1111 binary
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
GAR
BMR
MMR
Meaning
Graphics Address Register
Bit Mask Register
Map Mask Register
Address
03CEH
03CFH
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
COE Department
64
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
br
0
0
0
0
0
0
0
0
1
1
1
1
1
1
1
1
Code
R G
0
0
0
0
0
1
0
1
1
0
1
0
1
1
1
1
0
0
0
0
0
1
0
1
1
0
1
0
1
1
1
1
B
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
Color
Black
Blue
Green
Cyan
Red
Magenta
Brown
White
Grey
Bright Blue
Bright Green
Bright Cyan
Bright Red
Bright Magenta
Yellow
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
MOV DI , 0
FILL_PAGE:
MOV WORD PTR [DI] , 7041h
ADD DI , 2
LOOP FILL_PAGE
MOV AH , 08H
; 2000 words
; black A on white
; 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:
COE Department
65
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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
SHL AX , 1
SHL AX , 1
SHL AX , 1
SHL AX , 1
MOV DI , AX
SHL AX , 1
SHL AX , 1
ADD DI , AX
MOV AH , 0
MOV AL , DL
ADD DI , AX
SHL DI , 1
POP AX
RET
CALC_ADDRESS ENDP
; AX := row#
; AX := row# * 2
; AX := row# * 4
; AX := row# * 8
; AX := row# * 16
; DI := row# * 16
; AX := row# * 32
; AX := row# * 64
; DI := row# * 80
; AX := column#
; DI := row# * 80 + column#
; DI := ( row# * 80 + column# ) * 2
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
MOV DL , 37
CALL CALC_ADDRESS
MOV AH , 10101110B
MOV AL , ‘T’
STOSW
; row#6
; column#37
; attribute: yellow on green
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.
COE Department
66
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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
INT 10H
PUSH AX
…………
POP AX
MOV AH,00
INT 10H
;Get current video mode
;Save Video mode AL and Number of columns AH
;Restore Video mode AL and Number of columns AH
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
MOV
OR
INT
AH, 00
AL, VIDEO_MODE
AL, 80H
10H
Get Current Video Mode:
MOV AH, 0FH
INT 10H
PUSH AX
; Or MOV Old_Video_Mode, AX
Restore Video Mode:
POP AX
MOV AH, 00H
INT 10H
; Or MOV AX, Old_Video_Mode
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
COE Department
67
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
MOV
MOV
MOV
INT
BH, Current_Video_Page_Number ;Usually 0
DH, Row_Number
DL, Column_Number
10H
Get Cursor Position:
MOV
MOV
INT
MOV
MOV
MOV
AH, 03H
BH, Current_Video_Page_Number ;Usually 0
10H
Save_Cursor, CX
Current_Row, DH
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
1
2
3
4
5
6
7
default
default
0
1
2
3
4
5
6
7
8
9
0A
0B
0C
Figure 9. 3: Cursor Size
MOV
MOV
MOV
INT
COE Department
AH, 01H
CH, Start_Scan_Line#
CL, End_Scan_Line#
10H
68
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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
INT 10H
; Or MOV
CX, 2000H
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
MOV
MOV
MOV
INT
DH, 25
DL, 00
AH, 02H
BH, 00
10H
;Row number
;Column number
;Video page # 0
Set Border Color:
MOV
MOV
MOV
INT
COE Department
AH,0BH
BH,00H
BL,04H
10H
69
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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.
COE Department
70
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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
MOV
MOV
INT
AH,2
BH,0
DX,0
10H
;home cursor
;page 0
;row 0, char 0
MOV
MOV
INT
.EXIT
END
DX,OFFSET MES
AH,9
21H
;display "This is a test line."
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
MOV
CLD
MOV
AX,0A000H
ES,AX
;address segment A000 with ES
DI,0
;select increment
;address offset 0000
MOV
CALL
AL,0
BAND
;load starting test color of 00H
;display one band of 64 colors
MOV
CALL
AL,64
BAND
;load starting color of 40H
;display one band of 64 colors
MOV
CALL
AL,128
BAND
;load starting color of 80H
;display one band of 64 colors
MOV
CALL
AL,192
BAND
;load starting color of C0H
;display one band of 64 colors
MOV
INT
AH,1
21H
;wait for any key
MOV
INT
.EXIT
AX,3
10H
;switch back to DOS video mode
;
;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
COE Department
BH,40
;load line count
71
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
BAND1:
PUSH
MOV
AX
CX,64
;save starting color
;load color across line count
MOV
BL,5
;load times color is displayed
STOSB
DEC
JNZ
INC
LOOP
POP
DEC
JNZ
ADD
RET
BL
BAND3
AL
BAND2
AX
BH
BAND1
DI,320*10
BAND2:
BAND3:
BAND
;store color
;repeat 5 times
;change to next color
;repeat for 64 colors
;restore starting color
;repeat for 40 lines
;skip 10 lines
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
MOV
CLD
AX,0A000H
ES,AX
;address segment A000 with ES
MOV
MOV
MOV
MOV
MOV
MOV
CH,0
CL,0
DH,0
BX,80H
AX,1010H
DL,64
;green value
;blue value
;red value
;color register number 80H
;change palette color function
;count to change colors 80H to BFH
INT
INC
INC
DEC
JNZ
10H
DH
BX
DL
PROG1
;change a color value
;next color of red
;next color palette register
;repeat for 64 colors
MOV
MOV
CALL
DI,0
AL,80H
BAND
;address offset 0000
;starting color number
;display 64 colors
MOV
INT
AH,1
21H
;wait for any key
MOV
INT
.EXIT
AX,3
10H
;switch back to DOS video mode
;select increment
PROG1:
;
;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
PUSH
MOV
AX
CX,64
;save starting color number
;color count of 64
MOV
BL,5
;load times color is displayed
BAND1:
BAND2:
BAND3:
STOSB
;store color
DEC
BL
COE Department
72
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
JNZ
INC
LOOP
POP
DEC
JNZ
ADD
RET
BAND
BAND3
AL
BAND2
AX
BH
BAND1
DI,320*10
;repeat 5 times
;get next color number
;repeat for all 64 colors
;restore original color number
;repeat for 40 raster lines
;skip 10 raster lines
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
INT
AX,13H
10H
;select mode 13H
;this also clears the screen
MOV
MOV
MOV
MOV
CALL
AL,2
CX,100
SI,10
BP,75
BOX
;use color 02H (green)
;starting column number
;starting row number
;size
;display box
MOV
INT
AH,1
21H
;wait for any key
MOV
INT
.EXIT
AX,3
10H
;switch to DOS video mode
;
;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
MOV
PUSH
MOV
MUL
MOV
ADD
POP
PUSH
MOV
BX,0A000H
ES,BX
AX
AX,320
SI
DI,AX
DI,CX
AX
DI
CX,BP
;address segment A000 with ES
REP
MOV
SUB
STOSB
CX,BP
CX,2
;draw top line
POP
ADD
PUSH
STOSB
ADD
SUB
STOSB
LOOP
DI
DI,320
DI
POP
ADD
MOV
REP
RET
DI
DI,320
CX,BP
STOSB
;save color
;find starting PEL
;address start of BOX
;save starting offset address
;save size in BP
BOX1:
;adjust CX
BOX2:
COE Department
;address next row
;draw PEL
DI,BP
DI,2
;draw PEL
BOX2
;address last row
73
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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
INT
AX,12H
10H
;set mode to 12H
;and clear screen
MOV
MOV
MOV
MOV
CX,10
BX,10
SI,100
DL,3
CALL
INC
LOOP
DOT
SI
MAIN1
;set dot count to 10
;row address
;column address
;color 3 (cyan)
;plot 10 dots
;display one dot
MOV
MOV
MOV
CALL
BX,40
SI,200
DL,4
DOT
;row address
;column address
;color 4 (red)
;display one red dot
MOV
INT
AH,1
21H
;wait for key
MOV
INT
.EXIT
AX,3
10H
MAIN1:
;repeat 10 times
;return to DOS video mode
;
;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
PUSH
MOV
MUL
MOV
MOV
MOV
DIV
MOV
MOV
ADD
CX
DX
AX,80
BX
DI,AX
AX,SI
DH,8
DH
CL,AH
AH,0
DI,AX
MOV
SHR
PUSH
AL,80H
AL,CL
AX
MOV
MOV
OUT
DX,3CEH
AL,8
DX,AL
;graphics address register
;select bit mask register
MOV
POP
OUT
DX,3CFH
AX
DX,AL
;bit mask register
;get bit mask
MOV
MOV
OUT
DX,3C4H
AL,2
DX,AL
;sequence address register
;select map mask register
MOV
DX,3C5H
;map mask register
COE Department
;save color
;find row address byte
;save it
;find column address byte
;get shift count
;form address of PEL byte
;find bit in bit mask register
;save bit mask
74
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
DOT
MOV
OUT
AL,0FH
DX,AL
;enable all planes
MOV
MOV
POP
PUSH
OUT
MOV
AL,[DI]
;must read first
BYTE PTR [DI],0
;clear old color
AX
;get color from stack
AX
DX,AL
BYTE PTR [DI],0FFH
;write memory
POP
POP
RET
DX
CX
;restore registers
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
INT
AX,12H
10H
;set mode to 12H
;and clear screen
MOV
MOV
MOV
MOV
CX,80
BX,0
SI,0
DL,3
CALL
INC
LOOP
BLOCK
SI
MAIN1
;block count
;row address
;column address
;color 3 (cyan)
;plot 80 blocks
;display a block
;address next column
;repeat 80 times
MOV
MOV
MOV
BX,1
DL,7
DH,52
;row address
;color 7 (white)
;row count
MOV
MOV
SI,0
CX,80
;column address
;column count
CALL
INC
LOOP
INC
DEC
JNZ
BLOCK
SI
MAIN3
BX
DH
MAIN2
;display a block
;address next column
;repeat 80 times
;increment row address
MOV
INT
AH,1
21H
;wait for key
MOV
INT
.EXIT
AX,3
10H
MAIN1:
MAIN2:
MAIN3:
;repeat 52 times
;return to DOS video mode
;
;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
PUSH
CX
DX
MOV
MOV
OUT
DX,3CEH
AL,8
DX,AL
COE Department
;save color
;graphics address register
;select bit mask register
75
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
MOV
MOV
OUT
DX,3CFH
AL,0FFH
DX,AL
;bit mask register
;enable all 8 bits
MOV
MOV
OUT
DX,3C4H
AL,2
DX,AL
;sequence address register
;select map mask register
MOV
MUL
MOV
ADD
AX,80*9
BX
DI,AX
DI,SI
;find row address byte
MOV
MOV
POP
PUSH
MOV
CX,9
DX,3C5H
AX
AX
AH,AL
MOV
OUT
MOV
MOV
MOV
OUT
MOV
ADD
LOOP
AL,0FH
;enable all planes
DX,AL
AL,[DI]
;must read first
BYTE PTR [DI],0
;clear old color
AL,AH
DX,AL
BYTE PTR [DI],0FFH
;write memory
DI,80
BLOCK1
POP
POP
RET
DX
CX
;save it
;form address of PEL byte
;byte count
;map mask register
;get color
BLOCK1:
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
INT
AX,12H
10H
;set mode to 12H
;and clear screen
MOV
MOV
MOV
MOV
CALL
AL,'A'
DL,3
BX,5
SI,20
CHAR
;display 'A'
;cyan
;row 5
;column 0
;display cyan 'A'
MOV
MOV
MOV
MOV
CALL
AL,'B'
DL,12
BX,0
SI,0
CHAR
;display 'B'
;bright red
;row 0
;column 0
;display bright red 'B'
MOV
INT
AH,1
21H
;wait for key
MOV
INT
.EXIT
AX,3
10H
;return to DOS video mode
;
;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)
;
COE Department
76
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
CHAR
PROC
NEAR
PUSH
PUSH
PUSH
PUSH
MOV
MOV
INT
POP
MOV
SHL
SHL
SHL
ADD
POP
CX
DX
BX
AX
AX,1130H
BH,3
10H
AX
AH,0
AX,1
AX,1
AX,1
BP,AX
BX
MOV
AX,80*9
BX
DI,AX
DI,SI
CX,8
MUL
MOV
ADD
MOV
;save row address
;save ASCII
;get 8 x 8 set
;segment is in ES
;get ASCII code
;multiply by 8
;index character in ROM
;get row address
;find row address
;add in column address
;set count to 8 rows
C1:
MOV
MOV
MOV
INC
OUT
MOV
MOV
OUT
INC
MOV
MOV
POP
PUSH
OUT
MOV
ADD
LOOP
POP
POP
RET
CHAR
DX,3CEH
;address bit mask register
AL,8
;load index 8
AH,ES:[BP]
;get character row
BP
;point to next row
DX,AX
;modify bit mask register
DX,3C4H
;address map mask register
AX,0F02H
DX,AX
;select all planes
DX
AL,[DI]
;read data
BYTE PTR [DI],0 ;write black
AX
;get color
AX
DX,AL
;write color
BYTE PTR [DI],0FFH
DI,80
;address next raster row
C1
;repeat 8 times
DX
CX
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
MOV
DS,AX
CLD
;address video RAM
MOV
INT
AX,12H
10H
;set mode to 12H
;and clear screen
MOV
MOV
MOV
DL,3
DH,53
BX,0
;color cyan
;row counter
;row 0
MOV
MOV
CX,80
SI,0
;column counter
;column 0
CALL
INC
LOOP
BLOCK
SI
MAIN2
;display a cyan block
;address next column
;repeat 80 times
;select increment
MAIN1:
MAIN2:
COE Department
77
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
INC
DEC
JNZ
BX
DH
MAIN1
;address next row
;decrement row counter
;repeat for 53 rows
MOV
MOV
AX,@DATA
ES,AX
;address data segment
;with ES
MOV
MOV
MOV
MOV
CALL
DL,9
;bright blue text
BX,5
;row 5
SI,0
;column 0
DI,OFFSET MES1 ;address MES1
LINE
;display bright blue MES1
MOV
MOV
MOV
MOV
CALL
DL,12
;bright red
BX,15
;row 15
SI,0
;column 0
DI,OFFSET MES2 ;address MES2
LINE
;display bright red MES2
MOV
INT
AH,1
21H
MOV
INT
.EXIT
AX,3
10H
;wait for key
;return to DOS video mode
;
;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
OR
JZ
PUSH
PUSH
PUSH
CALL
POP
POP
POP
INC
INC
JMP
AL,ES:[DI]
AL,AL
LINE1
ES
DI
SI
CHAR
SI
DI
ES
SI
DI
LINE
;get character
;test for null
;if null
;save registers
;display characters
;restore registers
;address next column
;address next character
;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
PUSH
PUSH
PUSH
MOV
MOV
INT
POP
MOV
SHL
SHL
SHL
ADD
POP
MOV
COE Department
CX
DX
BX
AX
AX,1130H
BH,3
10H
AX
AH,0
AX,1
AX,1
AX,1
BP,AX
BX
AX,80*9
;save row address
;save ASCII
;get 8 x 8 set
;get ASCII code
;multiply by 8
;index character in ROM
;get row address
;find row address
78
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
MUL
MOV
ADD
MOV
BX
DI,AX
DI,SI
CX,8
MOV
MOV
MOV
INC
OUT
MOV
MOV
OUT
INC
MOV
MOV
POP
PUSH
OUT
MOV
ADD
LOOP
POP
POP
RET
DX,3CEH
;address bit mask register
AL,8
;load index 8
AH,ES:[BP]
;get character row
BP
;point to next row
DX,AX
DX,3C4H
;address map mask register
AX,0F02H
DX,AX
;select all planes
DX
AL,[DI]
;read data
BYTE PTR [DI],0
;write black
AX
;get color
AX
DX,AL
;write color
BYTE PTR [DI],0FFH
DI,80
;address next raster row
C1
;repeat 8 times
DX
CX
;add in column address
;set count to 8 rows
C1:
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
MOV
OUT
MOV
MOV
OUT
DX,3CEH
AL,8
DX,AL
DX,3CFH
AL,0FFH
DX,AL
;graphics address register
;select bit mask register
MOV
MOV
OUT
DX,3C4H
AL,2
DX,AL
;sequence address register
;select map mask register
MOV
MUL
MOV
ADD
AX,80*9
BX
DI,AX
DI,SI
;find row address byte
MOV
MOV
POP
PUSH
MOV
CX,9
DX,3C5H
AX
AX
AH,AL
MOV
OUT
MOV
MOV
MOV
OUT
MOV
ADD
LOOP
AL,0FH
;enable all planes
DX,AL
AL,[DI]
;must read first
BYTE PTR [DI],0
;clear old color
AL,AH
DX,AL
BYTE PTR [DI],0FFH
;write memory
DI,80
BLOCK1
POP
POP
RET
DX
CX
;bit mask register
;enable all 8 bits
;save it
;form address of PEL byte
;byte count
;map mask register
;get color
BLOCK1:
BLOCK
END
ENDP
COE Department
79
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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:
1234-
Install, use and uninstall an Interrupt Service Routine (ISR).
Install interrupt service procedures (hooks) as TSR software.
Install a TSR interrupt hook that uses the clock tick interrupt (INT 8).
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 softwareinterrupt. 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
COE Department
80
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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.
COE Department
81
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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
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. If
the 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.
INTO
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
COE Department
82
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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.
COE Department
83
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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
COE Department
84
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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
COE Department
85
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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
25H
31H
35H
Effect
Set Interrupt Vector
Make ISR as TSR
Get Interrupt Vector for
a Specified Interrupt.
Input
DS:DX = Segment Offset
Address
DX= number of paragraphs
to be kept in memory
AL = Interrupt number
Output
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:
COE Department
86
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
MOV DX, Offset Installation_Routine
MOV CL, 04
SHR DX, CL
; Divide by 16
INC DX
; to take care of truncation if any
Installation_Routine ENDP
. . . . .
Installation_Routine PROC
Service Section
Number_Of_Paragraphs
=
Offset Installation_Routine/
16
CS
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
COE Department
87
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
DISPLAY_LOOP:
DECIMAL_DISPLAY
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
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
MOV AL, 09H
INT 21H
MOV WORD PTR VAR,BX
MOV WORD PTR VAR+2,BX
;Get Int. Vector
;For INT 09H
;Store Offset Address
;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
CLI
STI
COE Department
Meaning
Flags Affected
Clear Interrupt Flag; Disable Maskable IF = 0
Interrupts
Set Interrupt Flag; Re-enable Maskable IF = 1
Interrupts
Table 10. 3: Interrupt Flag Set and Clear Instructions
88
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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
Bit 0: Right Shift Key Down
Bit 1: Left Shift Key Down
Bit 2: Ctrl Key Down
Bit 3: Alt Key Down
2
1
0
Bit 4:Insert On
Bit 5: Caps Lock On
Bit 6: num Lock On
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.
COE Department
89
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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.
COE Department
90
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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
.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
;Force code at Offset 100H
MSG DB 'Welcome To The Interesting World Of TSR
Routines',0DH,0AH,'$'
INSTALL PROC
MOV
MOV
MOV
MOV
MOV
INT
MOV
MOV
MOV
MOV
SHR
INC
INT
INSTALL ENDP
END
AX,
DS,
AH,
AL,
DX,
21H
AH,
AL,
DX,
CL,
DX,
DX
21H
CS
AX
25H
60H
OFFSET ISR_60H
31H
00H
OFFSET INSTALL
04
CL
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
COE Department
91
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
TITLE ‘Program 10.3’
;The following code redefines an existing ISR
VAR DD ?
;Used to store the Old Interrupt Vector
...
INSTALLATION_ROUTINE PROC
CLI
;GET OLD INTERRUPT VECTOR
MOV AH, 35H
MOV AL, INTERRUPT_NUMBER
INT 21H
;SAVE THE INTERRUPT VECTOR
MOV WORD PTR VAR,BX
MOV WORD PTR VAR+2,ES
;Clear IF to prevent Hardware Interrupt
;Store Offset Address
;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
INT 21H
INSTALLATION_ROUTINE ENDP
; Set IF to enable Hardware Interrupt
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
COE Department
92
KFUPM (2000 )
Experiment No 10
COE 205 Lab Manual
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
COE Department
93
KFUPM (2000 )
Experiment No 11
COE 205 Lab Manual
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
00
01
Description
Reset Mouse
Show Mouse
Cursor
Hide Mouse
Cursor
Read Mouse
Status on the fly
Entry
AH = 00H
AH = 01H
Exit
BX = Number of Mouse Buttons
Displays the mouse cursor
AH = 02H
Hides the mouse cursor
AH = 03H
BX = Button Status
CX= Horizontal Cursor Position
DX= Vertical Cursor Position
04
Set Mouse
Cursor Position
05
Get Button
Press
Information
AH = 04H
CX= Horizontal Cursor
Position
DX= Vertical Cursor
Position
AH = 05H
BX= Desired button
0 for left and 1 for right
02
03
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
COE Department
94
KFUPM (2000 )
Experiment No 11
COE 205 Lab Manual
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
M1
M2:
M3:
ENDM
COE Department
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
DB
13, 10,’*** MOUSE PRESENT ***’
PUSH DS
MOV AX, CS
MOV DS, AX
;DISPLAY M1
POP DS
STC
POP ES
;Show no mouse
;If no mouse, carry =1
95
KFUPM (2000 )
Experiment No 11
COE 205 Lab Manual
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
MOV AX, 0001H
INT 33H
ENDM
;Enable Mouse Pointer
MOFF MACRO
MOV AX, 0002H
INT 33H
ENDM
;Disable Mouse Pointer
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
Bit 1
Bit 2
BX
CX
DX
= 1 for the left button
= 1 for the right button
= 1 for the middle button
= number of times the button has been pressed, since the last
time this function was called.
= horizontal position
= vertical position
The following Macro is used for the above purpose:
MBUT MACRO NUM
MOV AX, 0005H
MOV BX, NUM
INT 33H
ENDM
COE Department
;Read Button
;NUM = 0 for left
; NUM = 1 for right
; NUM = 4 for middle
96
KFUPM (2000 )
Experiment No 11
COE 205 Lab Manual
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
MOV AX, 0003H
INT 33H
;Read Mouse Status
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
02H
Description
Move Mouse Cursor
Entry
AH = 02
DH = Line Number
DL = Column Number
Table 11. 2: Move Cursor Function
COE Department
97
KFUPM (2000 )
Experiment No 11
COE 205 Lab Manual
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.
COE Department
98
KFUPM (2000 )
Experiment No 11
COE 205 Lab Manual
TITLE "Program 11-1"
INCLUDE MACROS.INC
.MODEL SMALL
.STACK 200H
.DATA
.CODE
.STARTUP
MOV AX, 12H
INT 10H
MP
JC MAIN2
MON
;Switch to mode 12H
;Test for mouse
;If no mouse
;Enable mouse pointer
MAIN1:
MRTIME
CMP BX, 3
JNE MAIN1
;Read Mouse Status on-the-fly
;Test for left and right buttons
;If both not pressed repeat
MAIN2:
MOFF
MOV AX, 03H
INT 10H
;Disable mouse pointer
;Switch to mode 3
.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
JNE
CMP
JE
MAIN2:
MOV
MOV
MOV
MOV
CALL
MOV
COE Department
CX,X
MAIN2
DX,Y
MAIN1
;if X position changed
;if Y position did not change
X,CX
;save new position
Y,DX
DI,OFFSET MX
AX,CX
PLACE
;store ASCII X
DI
99
KFUPM (2000 )
Experiment No 11
COE 205 Lab Manual
,OFFSET MY
MOV
CALL
MOV
INT
AX,Y
PLACE
AX,2
33H
;store ASCII Y
;hide mouse pointer
MOV
MOV
INT
AH,9
DX,OFFSET MES
21H
;display position
MOV
INT
AX,1
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
CALL
JC
MOV
INT
CLC
TM_ON1:
RET
TM_ON ENDP
COE Department
NEAR
CHKM
TM_ON1
AX,1
33H
;test for mouse
;show mouse pointer
100
KFUPM (2000 )
Experiment No 11
COE 205 Lab Manual
;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
MOV
PLACE1:
MOV
DIV
PUSH
INC
CMP
JNE
PLACE2:
MOV
SUB
PLACE3:
POP
ADD
MOV
INC
LOOP
CMP
JE
MOV
PLACE4:
MOV
INC
LOOP
PLACE5:
RET
CX,0
BX,10
;clear count
;set divisor
DX,0
BX
DX
CX
AX,0
PLACE1
;clear DX
;divide by 10
;repeat until quotient 0
BX,5
BX,CX
DX
DL,30H
[DI],DL
DI
PLACE3
BX,0
PLACE5
CX,BX
;convert to ASCII
;store digit
BYTE PTR [DI],20H
DI
PLACE4
PLACE ENDP
END
COE Department
101
KFUPM (2000 )
Experiment No 12
COE 205 Lab Manual
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:
1234-
Serial data transmission
Use of Interrupt 14H
Port configuration.
Sending and receiving data through the serial ports.
References:
1- Barry B. Brey, “Programming the 80286, 80386, 80486, and PentiumBased 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
COM 1
COM 2
COM 3
COM 4
Address
3F8 H
2F8 H
3E8 H
2E8 H
IRQ
4
3
4
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.
COE Department
102
KFUPM (2000 )
Experiment No 12
COE 205 Lab Manual
INT 14H:
INT 14h supports the four sub-functions, shown in table 12.2.
Function
Input in
Output in
Effect
00
01
02
AH
AH, Character in AL
AH
No output
Status in AX
Status in AX
03
AH
Status in AX
Initialize Serial Port
Write a Character to the Serial Port
Read a character from the Serial
Port
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
5..7
0..1
2
3..4
1
1
1
Function
Baud Rate
Character Size
Stop Bits
Parity Bits
0
0
1
Character Size
7 bits
8 bits
7
0
0
0
0
1
1
1
1
6
0
0
1
1
0
0
1
1
5
0
1
0
1
0
1
0
1
Baud Rate
110
150
300
600
1200
2400
4800
9600
4
0
0
1
1
2
0
1
3
0
1
0
1
Parity
No parity
Odd parity
No parity
Even parity
Stop bits
One stop bit
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
MOV AL, 10100111B
MOV DX, 0
INT 14H
;INITIALIZE OPCODE
;PARAMETER DATA.
;COM1: PORT.
After the call to the initialization code, the serial port status is returned in AX (see
Serial Port Status, AH = 3, below).
COE Department
103
KFUPM (2000 )
Experiment No 12
COE 205 Lab Manual
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:
COE Department
104
KFUPM (2000 )
Experiment No 12
COE 205 Lab Manual
AX
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Bit Meaning
Clear to send
Data set ready
Trailing edge ring detector
Receive line signal detect
Clear to send (CTS)
Data set ready (DSR)
Ring indicator
Receive line signal detect
Data available
Overrun error
Parity error
Framing error
Break detection error
Transmitter holding register empty
Transmitter shift register empty
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.
COE Department
105
KFUPM (2000 )
Experiment No 12
COE 205 Lab Manual
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.)
COE Department
106
KFUPM (2000 )
Experiment No 12
COE 205 Lab Manual
TITLE ‘Program 12.1’
;This program configures the serial port (COM1) and sends a character through that port.
.MODEL SMALL
.STACK 200
.DATA
PROMPT
SENT
sent’,’$’
ERROR
again.’,’$’
DB
DB
DB
‘Enter the character to be sent’,0DH,0AH,’$’
‘The
character
has
successfully
been
‘An error occurred. Please check your hardware and try
.CODE
.STARTUP
MOV
MOV
MOV
INT
AH, 0H
AL, 10100111B
DX, 0H
14H
; INITIALIZE OPCODE
; PARAMETER DATA.
; COM1: PORT.
LEA DX, PROMPT
MOV AH, 09H
INT 21H
; DISPLAY PROMPT ON SCREEN
MOV AH, 01H
INT 21H
; READ THE CHARACTER FROM KEYBOARD
MOV DX, 0H
MOV AH, 1H
INT 14H
TEST AH, 80H
JNZ PORTERROR
; SELECT COM1:
; TRANSMIT OPCODE
LEA
MOV
INT
JMP
DX, SENT
AH, 09H
21H
FINISH
PORTERROR:
LEA DX, ERROR
MOV AH, 09H
INT 21H
; CHECK FOR ERROR
; DISPLAY THAT THE CHARACTER WAS SENT
; DISPLAY THAT THERE WAS AN ERROR
FINISH:
.END
COE Department
107
KFUPM (2000 )
Experiment No 12
COE 205 Lab Manual
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
wait.’,0DH,0AH,’$’
RECEIVED
DB
received.’,0DH,0AH,’$’
ERROR
again.’,’$’
DB
CHAR
DB
‘Receiving
‘The
character.
character
Please
has
been
‘An error occurred. Please check your hardware and try
‘The received character is: ‘,’$’
.CODE
.STARTUP
MOV
MOV
MOV
INT
AH, 0H
AL, 10100111B
DX, 0H
14H
; INITIALIZE OPCODE
; PARAMETER DATA.
; COM1: PORT.
LEA DX, PROMPT
MOV AH, 09H
INT 21H
; DISPLAY PROMPT ON SCREEN
MOV DX, 0H
MOV AH, 02H
INT 14H
TEST AH, 80H
JNZ PORTERROR
; SELECT COM1:
; RECEIVE OPCODE
LEA DX, RECEIVED
RECEIVED
MOV AH, 09H
INT 21H
; CHECK FOR ERROR
;
DISPLAY
THAT
THE
CHARACTER
LEA DX, CHAR
MOV AH, 09H
INT 21H
; DISPLAY CHAR MESSAGE
MOV
MOV
INT
JMP
; DISPLAY THE CHARACTER ON SCREEN
DL, AL
AH, 02H
21H
FINISH
PORTERROR:
LEA DX, ERROR
MOV AH, 09H
INT 21H
WAS
; DISPLAY THAT THERE WAS AN ERROR
FINISH:
.END
COE Department
108
KFUPM (2000 )