You are on page 1of 97

MIL Manual

ASSIGNMENT No: 1

Title of Assignment: Study of 8086 pin diagram. Write an Assembly Language Program
(ALP) in 8086 to add an array of N nos. stored in the memory

Relevant Theory:

(A) Study Of 8086

16-bit microprocessor with a 16-bit data bus

Pin functions:

• AD15-AD0
o Multiplexed address(ALE=1)/data bus(ALE=0).
• A19/S6-A16/S3 (multiplexed)
o High order 4 bits of the 20-bit address OR status bits S6-S3.
• M/IO
o Indicates if address is a Memory or IO address.
• RD
o When 0, data bus is driven by memory or an I/O device.
• WR
o Microprocessor is driving data bus to memory or an I/O device.
When 0, data bus contains valid data.
• ALE (Address latch enable)
o When 1, address data bus contains a memory or I/O address.
• DT/R (Data Transmit/Receive)
o Data bus is transmitting/receiving data.
• DEN (Data bus Enable)
o Activates external data bus buffers.

1
MIL Manual

• S7, S6, S5, S4, S3, S2, S1, S0


o S7: Logic 1, S6: Logic 0.
o S5: Indicates condition of IF flag bits.
o S4-S3: Indicate which segment is accessed during current bus cycle:

o S2, S1, S0 : Indicate function of current bus cycle (decoded by 8288).

• INTR
o When 1 and IF=1, microprocessor prepares to service interrupt. INTA
becomes active after current instruction completes.
• INTA
o Interrupt Acknowledge generated by the microprocessor in
response to INTR. Causes the interrupt vector to be put onto the data
bus.
• NMI
o Non-maskable interrupt. Similar to INTR except IF flag bit is not
consulted and interrupt is vector 2.

• CLK
o Clock input must have a duty cycle of 33% (high for 1/3 and low for
2/3s)
• VCC/GND
o Power supply (5V) and GND (0V).
• MN/ MX
o Select minimum (5V) or maximum mode (0V) of operation.
• BHE
o Bus High Enable. Enables the most significant data bus bits (D 15 -D 8
) during a read or write operation.

• READY
o Used to insert wait states (controlled by memory and IO for
reads/writes) into the microprocessor.
• RESET
o Microprocessor resets if this pin is held high for 4 clock periods.
o Instruction execution begins at FFFF0H and IF flag is cleared.

2
MIL Manual

• TEST
o An input that is tested by the WAIT instruction.
o Commonly connected to the 8087 coprocessor.
• HOLD
o Requests a direct memory access (DMA). When 1, microprocessor
stops and places address, data and control bus in high-impedance
state.
• HLDA (Hold Acknowledge)
o Indicates that the microprocessor has entered the hold state.
• RO/GT1 and RO/GT0
o Request/grant pins request/grant direct memory accesses (DMA)
during maximum mode operation.

• LOCK
o Lock output is used to lock peripherals off the system. Activated by
using the LOCK: prefix on any instruction.
• QS1 and QS0

The queue status bits show status of internal instruction queue. Provided for access by the numeric
coprocessor (8087).

(B) Assembly Language Program (ALP) in 8086 to add an array of N nos. stored in
the memory:

All the ALP assignments are to be implemented using MASM.

The Microsoft Macro Assembler (abbreviated MASM) is an assembler for the x86
family of microprocessors. It was originally produced by Microsoft for development
work on their MS-DOS operating system, and was for some time the most popular
assembler available for that operating system. It supported a wide variety of macro
facilities and structured programming idioms, including high-level constructions for
looping, procedure calls and alternation (therefore, MASM is an example of a high-
level assembler). Later versions added the capability of producing programs for the
Windows operating systems that were released to follow on from MS-DOS. MASM
is one of the few Microsoft development tools (another was NMAKE) for which one
version targets both 16-bit and 32-bit. Early version were MS-DOS applications.
Later versions also were OS/2 applications (versions 5.1 and 6.0) and later versions
after that (versions 6.1+) were Win32 console applications (initially (in versions 6.1
and 6.11) with the Phar Lap TNT DOS extender included to run these versions of
MS-DOS). However see Phar Lap (company) for the whole debacle that cause early
versions that were Win32 console applications (version 6.1) to fail to run on final
versions of Windows NT.

3
MIL Manual

Design Analysis/ Implementation Logic:

1. Assume: the numbers are stored in the memory.


2. Define the model type and access the numbers stored in the
memory
3. Add the numbers and store the result in a variable
4. Display all the numbers in the memory
5. Display the summation.

Testing:

1. Save the ALP with .asm extension


2. Use ML command to convert .asm file to .obj and then to .exe
3. execute the executable file and see whether valid output is obtained.
4. Modify program to accept the numbers from users.

For MASM Assembler :

C:\masm61\bin\>MASM sample.asm
C:\masm61\bin\>LINK sample.obj
C:\masm61\bin\>EXE2BIN sample sample.com

Sample output:

C:\MASM611>ml assgn1.asm
Microsoft (R) Macro Assembler Version 6.11
Copyright (C) Microsoft Corp 1981-1993. All rights reserved.

Assembling: assgn1.asm

Microsoft (R) Segmented Executable Linker Version 5.31.009 Jul 13 1992


Copyright (C) Microsoft Corp 1984-1992. All rights reserved.

Object Modules [.obj]: assgn1.obj


Run File [assgn1.exe]: "assgn1.exe"
List File [nul.map]: NUL
Libraries [.lib]:

4
MIL Manual

Definitions File [nul.def]:


LINK : warning L4038: program has no starting address

C:\MASM611>assgn1

The Nos in memory:


10
11
12
13
14

Addition:60
C:\MASM611>

Conclusion:
ALP to add ‘N’ numbers is written, compiled and executed successfully.

5
MIL Manual

ASSIGNMENT No: 2

Title of Assignment: Write an ALP in 8086 to count Odd and Even nos. from the array
stored in Memory

Relevant Theory:

Introduction to 8086 Assembly Language


CS 272
Sam Houston State University
Dr. Tim McGuire

Structure of an assembly language program

• Assembly language programs divide roughly into five sections


o header
o equates
o data
o body
o closing

The Header

• The header contains various directives which do not produce machine code
• Sample header:

%TITLE "Sample Header"


.8086
.model small
.stack 256
Named Constants

• Symbolic names associated with storage locations represent addresses


• Named constants are symbols created to represent specific values determined by
an expression
• Named constants can be numeric or string
• Some named constants can be redefined
• No storage is allocated for these values

Equates

6
MIL Manual

• Constant values are known as equates


• Sample equate section:

Count EQU 10
Element EQU 5
Size = Count * Element
MyString EQU "Maze of twisty passages"
Size = 0

• = is used for numeric values only


• Cannot change value of EQU symbol
• EQUated symbols are not variables
• EQU expressions are evaluated where used; = expressions are evaluated where
defined

The Data Segment

• Begins with the .data directive


• Two kinds of variables, initialized and uninitialized.
• Initialized variables take up space in the program's code file
• Declare uninitialized variables after initialized ones so they do not take up space
in the program's code file

Reserving space for variables

• Sample DATA SEGMENT

.data
numRows DB 25
numColumns DB ?
videoBase DW 0800h

• DB and DW are common directives (define byte) and (define word)


• The symbols associated with variables are called labels
• Strings may be declared using the DB directive:

aTOm DB "ABCDEFGHIJKLM"
Program Data and Storage

• Pseudo-ops to define data or reserve storage


o DB - byte(s)
o DW - word(s)
o DD - doubleword(s)
o DQ - quadword(s)
o DT - tenbyte(s)

7
MIL Manual

• These directives require one or more operands


o define memory contents
o specify amount of storage to reserve for run-time data

Defining Data

• Numeric data values


o 100 - decimal
o 100b - binary
o 100h - hexadecimal
o '100' - ASCII
o "100" - ASCII
• Use the appropriate DEFINE directive (byte, word, etc.)
• A list of values may be used - the following creates 4 consecutive words

DW 40Ch,10b,-13,0

• A ? represents an uninitialized storage location

DB 255,?,-128,'X'

Naming Storage Locations

• Names can be associated with storage locations

ANum DB -4
DW 17
ONE
UNO DW 1
X DD ?

• These names are called variables


• ANum refers to a byte storage location, initialized to FCh
• The next word has no associated name
• ONE and UNO refer to the same word
• X is an uninitialized doubleword

Arrays

• Any consecutive storage locations of the same size can be called an array

X DW 040Ch,10b,-13,0
Y DB 'This is an array'
Z DD -109236, FFFFFFFFh, -1, 100b

• Components of X are at X, X+2, X+4, X+6


• Components of Y are at Y, Y+1, …, Y+15
• Components of Z are at Z, Z+4, Z+8, Z+12

8
MIL Manual

DUP

• Allows a sequence of storage locations to be defined or reserved


• Only used as an operand of a define directive

DB 40 DUP(?)
DW 10h DUP(0)
DB 3 DUP("ABC")
DB 4 DUP(3 DUP (0,1), 2 DUP('$'))
Word Storage

• Word, doubleword, and quadword data are stored in reverse byte order (in
memory)

Directive Bytes in Storage


DW 256 00 01
DD 1234567h 67 45 23 01
DQ 10 0A 00 00 00 00 00 00 00
X DW 35DAh DA 35
Low byte of X is at X, high byte of X is at X+1

The Program Body

• Also known as the code segment


• Divided into four columns: labels, mnemonics, operands, and comments
• Labels refer to the positions of variables and instructions, represented by the
mnemonics
• Operands are required by most assembly language instructions
• Comments aid in remembering the purpose of various instructions

An example
Label Mnemonic Operand Comment
---------------------------------------------------------
.data
exCode DB 0 ;A byte variable
myWord DW ? ;Uninitialized word var.
.code
MAIN:
mov ax,@data ;Initialize DS to address
mov ds,ax ; of data segment
jmp Exit ;Jump to Exit label
mov cx,10 ;This line skipped!
Exit: mov ah,04Ch ;DOS function: Exit prog
mov al, exCode ;Return exit code value
int 21h ;Call DOS. Terminate prog
END MAIN ;End Program and specify entry point

The Label Field

• Labels mark places in a program which other instructions and directives reference
• Labels in the code segment always end with a colon
• Labels in the data segment never end with a colon

9
MIL Manual

• Labels can be from 1 to 31 characters long and may consist of letters, digits, and
the special characters ? . @ _ $ %
• If a period is used, it must be the first character
• Labels must not begin with a digit
• The assembler is case insensitive

Legal and Illegal Labels

• Examples of legal names


o COUNTER1
o @character
o SUM_OF_DIGITS
o $1000
o DONE?
o .TEST
• Examples of illegal names
o TWO WORDS contains a blank
o 2abc begins with a digit
o A45.28 . not first character
o YOU&ME contains an illegal character
o

The Mnemonic Field

• For an instruction, the operation field contains a symbolic operation code


(opcode)
• The assembler translates a symbolic opcode into a machine language opcode
• Examples are: ADD, MOV, SUB
• In an assembler directive, the operation field contains a directive (pseudo-op)
• Pseudo-ops are not translated into machine code; they tell the assembler to do
something

The Operand Field

• For an instruction, the operand field specifies the data that are to be acted on by
the instruction. May have zero, one, or two operands

NOP ;no operands -- does nothing


INC AX ;one operand -- adds 1 to the
contents of AX
ADD WORD1,2 ;two operands -- adds 2 to the
contents
; of memory word WORD1

10
MIL Manual

• In a two-operand instruction, the first operand is the destination operand. The


second operand is the source operand.
• For an assembler directive, the operand field usually contains more information
about the directive.

The Comment Field

• A semicolon marks the beginning of a comment field


• The assembler ignores anything typed after the semicolon on that line
• It is almost impossible to understand an assembly language program without good
comments
• Good programming practice dictates a comment on almost every line

Good and Bad Comments

• Don't say something obvious, like

MOV CX,0 ;move 0 to CX

• Instead, put the instruction into the context of the program

MOV CX,0 ;CX counts terms, initially 0

• An entire line can be a comment, or be used to create visual space in a program

;
; Initialize registers
;
MOV AX,0
MOV BX,0

The Closing

• The last lines of an assembly language program are the closing


• Indicates to assembler that it has reached the end of the program and where the
entry point is

MAIN ENDP ;End of program


END MAIN ; entry point for linker use

• END is a pseudo-op; the single "operand" is the label specifying the beginning of
execution, usually the first instruction after the .code pseudo-op

11
MIL Manual

Design Analysis/ Implementation Logic:

Algorithm:

1. Assume: the numbers are stored in memory.

2. Fetch each number and decide whether it is even or odd.


(Check the status of LSB)
3. Accordingly count total no. of odd and even numbers.
4. Display all the numbers in the memory
5. Display the odd count
6. Display the odd numbers
7. Display the even count
8. Display the even numbers
9.

Testing:

Sample Output:

Microsoft Windows XP [Version 5.1.2600]


(C) Copyright 1985-2001 Microsoft Corp.

C:\DOCUME~1\MAE>cd\

C:\>cd masm611

C:\MASM611>ml assgn2.asm
Microsoft (R) Macro Assembler Version 6.11
Copyright (C) Microsoft Corp 1981-1993. All rights reserved.

Assembling: assgn2.asm

Microsoft (R) Segmented Executable Linker Version 5.31.009 Jul 13 1992


Copyright (C) Microsoft Corp 1984-1992. All rights reserved.

Object Modules [.obj]: assgn2.obj


Run File [assgn2.exe]: "assgn2.exe"
List File [nul.map]: NUL

12
MIL Manual

Libraries [.lib]:
Definitions File [nul.def]:
LINK : warning L4038: program has no starting address

C:\MASM611>assgn2

The Nos in memory:


10
11
12
13
14

The odd no count02


The even no count:03
Odd Nos:
11
13

Even Nos:
10
12
14

C:\MASM611>

Conclusion:
All the odd and even numbers are correctly classified and displayed.

13
MIL Manual

ASSIGNMENT No: 3

Title of Assignment: Write an ALP in 8086 to find and count Negative nos. from the
array of signed nos. stored in Memory

Relevant Theory:

Signed numbers: (sign-magnitude notation) in computers is the use of the high-order bit
(left end) of a binary word to represent the numeric sign: 0 for + and 1 for - followed by a
binary number that is an absolute magnitude or a two's complement of an absolute
magnitude. For example, 01001 means plus 9. In 2's complement: 11101 means minus 3
and 10111 means minus 9.

8 Bit Signed Magnitude

Binary value Signed magnitude interpretation Unsigned interpretation

00000000 0 0

00000001 1 1

... ... ...

01111111 127 127

10000000 −0 128

... ... ...

11111111 −127 255

14
MIL Manual

INT 10h structure:


Video Services
AH=00h Set Video Mode
AH=01h Set Cursor Shape
AH=02h Set Cursor Position
AH=03h Get Cursor Position And Shape
AH=04h Get Light Pen Position
AH=05h Set Display Page
AH=06h Clear/Scroll Screen Up
AH=07h Clear/Scroll Screen Down
AH=08h Read Character and Attribute at Cursor
AH=09h Write Character and Attribute at Cursor
AH=0Ah Write Character at Cursor
AH=0Bh Set Border Color
AH=0Eh Write Character in TTY Mode
AH=0Fh Get Video Mode
AH=13h Write String

Sample Macro to display a string


prnstr macro msg
mov ah,09h
lea dx,msg
int 21h
endm

Sample Macro to read number from K/B


readnum macro num
mov ah,01h
int 21h
sub al,'0'
mov num,al
endm

Design Analysis/ Implementation Logic:


Algorithm:
Assume: the numbers are stored in memory.
Fetch each number and decide whether it is +ve or -ve. (Check the status of MSB)
Accordingly count total no. of +ve and -ve numbers.
Display all the numbers in the memory
Display the +ve count
Display the +ve numbers
Display the -ve count
Display the -ve numbers

15
MIL Manual

Testing:
Sample Output:
C:\MASM611>ml assgn3.asm
Microsoft (R) Macro Assembler Version 6.11
Copyright (C) Microsoft Corp 1981-1993. All rights reserved.
Assembling: assgn3.asm

Microsoft (R) Segmented Executable Linker Version 5.31.009 Jul 13 1992


Copyright (C) Microsoft Corp 1984-1992. All rights reserved.

Object Modules [.obj]: assgn3.obj


Run File [assgn3.exe]: "assgn3.exe"
List File [nul.map]: NUL
Libraries [.lib]:
Definitions File [nul.def]:
LINK : warning L4038: program has no starting address

C:\MASM611>assgn3
The Nos in memory:
10
111
12
13
144

The negative no count01


The positive no count:04
Negative Nos:
144

Positive Nos:
10
111
12
13

C:\MASM611>

Conclusion:
All the odd and even numbers are correctly classified and displayed.

16
MIL Manual

ASSIGNMENT No: 4

Title of Assignment: Write an ALP in 8086 to find


i) Factorial of a No.
ii) Whether the no. entered from keyboard is prime no. Or not

Relevant Theory:

DOS Interrupt 21H

•Option 1 –Inputs a single character from keyboard and echoes it to the


monitor.
•Registers used:
–AH = 1
–AL = the character inputted from keyboard.
•Ex:
–MOV AH,1
–INT 21H

•Option 2 –Outputs a single character to the monitor.


•Registers used:
–AH = 2
–DL = the character to be displayed.
•Ex:
–MOV AH,2
–MOV DL,’A’
–INT 21H

•Option 9 –Outputs a string of data, terminated by a $ to the monitor.


•Registers used:
–AH = 9
–DX = the offset address of the data to be displayed.
•Ex:
–MOV AH,09
–MOV DX,OFFSET MESS1
–INT 21H

17
MIL Manual

•Option 4CH –Terminates a process, by returning control to a parent


process or to DOS.
•Registers used:
–AH = 4CH
–AL = binary return code.
•Ex:
–MOV AH,4CH
–INT 21H

Model definition
•.MODEL SMALL
–Most widely used memory model.
–The code must fit in 64k.
–The data must fit in 64k.

•.MODEL MEDIUM
–The code can exceed 64k.
–The data must fit in 64k.

•.MODEL COMPACT
–The code must fit in 64k.
–The data can exceed 64k.
•MEDIUM and COMPACT are opposites.

•Segment definition formats:


–Simplified segment definition.
–Full segment definition.
•The Simplified segment definition uses the following directives to
define the segments:
–.STACK
–.DATA
–.CODE
–These directives mark the beginning of the segments they represent.

Design Analysis/ Implementation Logic:

Algorithm:

18
MIL Manual

Accept the number from the user


Check if number is 0 or 1 and display it as a prime no
Else divide the number by 2 to n-1
If carry generated at every stage, no is prime else not
Find the factorial of the number
Understand why factorials of numbers only till 8 can be correctly calculated
Display both the results

Testing:

Sample Output:

C:\MASM611>ml assgn4.asm
Microsoft (R) Macro Assembler Version 6.11
Copyright (C) Microsoft Corp 1981-1993. All rights reserved.

Assembling: assgn4.asm

Microsoft (R) Segmented Executable Linker Version 5.31.009 Jul 13 1992


Copyright (C) Microsoft Corp 1984-1992. All rights reserved.

Object Modules [.obj]: assgn4.obj


Run File [assgn4.exe]: "assgn4.exe"
List File [nul.map]: NUL
Libraries [.lib]:
Definitions File [nul.def]:
LINK : warning L4038: program has no starting address

C:\MASM611>assgn4

Enter no:05
It is a Prime Number!!!
Factorial = 120
C:\MASM611>

Conclusion:
Factorial of the number is calculated and displayed. The number is classified as a prime
or not successfully.

ASSIGNMENT No: 5

19
MIL Manual

Title of Assignment: Write an ALP in 8086 to find the Largest No. in a given Array.

Relevant Theory:

CMP Instruction
� CMP operand1,operand2
� operand1 - operand2
� Flags are updated and the result is discarded.
� CMP AL,BL
� CMP BX,0ABCH
� CMP DL,[BX]

Conditional Transfers
� Used with unsigned integers
� JA/JNBE – Jump if above – Z=0 and C=0
� JAE/JNB – Jump if above or equal – C=0
� JB/JNA – Jump if below – C=1
� JBE/JNA – Jump if below or equal – Z=1 and C=1
� CMP AL,BL
� JA NEXT
� MOV CL,0
� .
� .
� NEXT:

Used with signed integers


� JG/JNLE – Jump if greater – Z=0 and S=0
� JGE/JNL – Jump if greater or equal – S=0
� JL/JNGE – Jump if less – S<>0
� JLE/JNG – Jump if less or equal – Z=1 and S<>0
� CMP AL,BL
� JLE NEXT
� MOV CL,0
�.
�.
� NEXT:

� Other conditions
� JE/JZ – Jump if equal – Z=1

20
MIL Manual

� JNE/JNZ – Jump if not equal – Z=0


� JC – Jump if carry - C=1
� JNC – Jump if not carry – C=0
� JS – Jump if sign – S=1
� JNS – Jump if not sign – S=0
� JO – Jump if overflow – O=1
� JNO – Jump if not overflow – O=0

� JP/JPE – Jump if parity/parity even – P=1


� JNP/JPO – Jump if not parity/parity odd – P=0
� JCXZ – Jump if CX is zero
� JECXZ – Jump if ECX is zero

Design Analysis/ Implementation Logic:

Algorithm:
Assume: numbers are stored in the memory
Maintain a temporary storage space say temp
Compare first two numbers
Store larger number in temp
Compare next pair of numbers and maintain the largest number in temp
Display all the numbers and the largest number.

Testing:

Sample Output:

Microsoft Windows XP [Version 5.1.2600]


(C) Copyright 1985-2001 Microsoft Corp.

C:\DOCUME~1\MAE>cd\

C:\>cd masm611

C:\MASM611>ml assgn5.asm
Microsoft (R) Macro Assembler Version 6.11
Copyright (C) Microsoft Corp 1981-1993. All rights reserved.

Assembling: assgn5.asm

Microsoft (R) Segmented Executable Linker Version 5.31.009 Jul 13 1992

21
MIL Manual

Copyright (C) Microsoft Corp 1984-1992. All rights reserved.

Object Modules [.obj]: assgn5.obj


Run File [assgn5.exe]: "assgn5.exe"
List File [nul.map]: NUL
Libraries [.lib]:
Definitions File [nul.def]:
LINK : warning L4038: program has no starting address

C:\MASM611>assgn5

Nos in array:

0015
0005
000D
00FF
0011
00EF

Largest No:
00FF
C:\MASM611>

Conclusion:
Largest number is found and displayed.

ASSIGNMENT No: 6

Title of Assignment: Write an ALP in 8086 to convert 4-digit Hex No. To BCD No. and
vice versa

22
MIL Manual

Relevant Theory:

To BCD-encode a decimal number using the common encoding, each decimal digit is
stored in a four-bit nibble.

Decimal: 0 1 2 3 4 5 6 7 8 9
BCD: 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001

Thus, the BCD encoding for the number 127 would be:

0001 0010 0111

Since most computers store data in eight-bit bytes, there are two common ways of storing
four-bit BCD digits in those bytes:

• each digit is stored in one byte, and the other four bits are then set to all zeros, all
ones (as in the EBCDIC code), or to 0011 (as in the ASCII code)
• two digits are stored in each byte.

Unlike binary encoded numbers, BCD encoded numbers can easily be displayed by
mapping each of the nibbles to a different character. Converting a binary encoded number
to decimal for display is much harder involving integer multiplication or divide
operations. The BIOS in many PCs keeps the date and time in BCD format, probably for
historical reasons (it avoided the need for binary to ASCII conversion).

In mathematics and computer science, hexadecimal, base-16, or simply hex, is a numeral


system with a radix, or base, of 16, usually written using the symbols 0–9 and A–F, or a–
f. Its primary purpose is to represent the binary code in a format easier for humans to
read, and acts as a form of shorthand, in which one hexadecimal digit stands in place of
four binary bits. For example, the decimal numeral 79, whose binary representation is
01001111, is 4F in hexadecimal (4 = 0100, F = 1111). IBM introduced the current
hexadecimal system to the computing world; an earlier version, using the digits 0–9 and
u–z, had been introduced in 1956, and had been used by the Bendix G-15 computer.

Design Analysis/ Implementation Logic:

Algorithm:
Make a user friendly menu
Accept a BCD number
Convert into its Hex equivalent and display result

23
MIL Manual

Accept a Hex number


Convert into its BCD equivalent and display result
Exit program when user selects that option

Testing:

Sample Output:

C:\MASM611>ml assgn6.asm
Microsoft (R) Macro Assembler Version 6.11
Copyright (C) Microsoft Corp 1981-1993. All rights reserved.

Assembling: assgn6.asm

Microsoft (R) Segmented Executable Linker Version 5.31.009 Jul 13 1992


Copyright (C) Microsoft Corp 1984-1992. All rights reserved.

Object Modules [.obj]: assgn6.obj


Run File [assgn6.exe]: "assgn6.exe"
List File [nul.map]: NUL
Libraries [.lib]:
Definitions File [nul.def]:
LINK : warning L4038: program has no starting address

C:\MASM611>assgn6

---Enter Your Choice---


1) Hex to BCD
2) BCD to Hex
3) Quit
Enter Your Choice:1
Enter the Hex No:000F
Converted BCD No:0015
---Enter Your Choice---
1) Hex to BCD
2) BCD to Hex
3) Quit
Enter Your Choice:2
Enter the BCD No:0011

24
MIL Manual

Converted Hex No:000B


---Enter Your Choice---
1) Hex to BCD
2) BCD to Hex
3) Quit
Enter Your Choice:3
C:\MASM611>

Conclusion:
BCD-Hex and Hex-BCD conversion is successfully implemented.

ASSIGNMENT No: 7

Title of Assignment: Write an ALP in 8086 to Arrange nos. stored in array in


Ascending as well as Descending order. Write separate subroutines to arrange the Nos.
Accept a key from the user.
a)If user enters = 0, Arrange in Ascending Order

25
MIL Manual

b)If user enters = 1, Arrange in Descending Order

Relevant Theory: Use Bubble sort method

Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the
list to be sorted, comparing two items at a time and swapping them if they are in the
wrong order. The pass through the list is repeated until no swaps are needed, which
means the list is sorted. The algorithm gets its name from the way smaller elements
"bubble" to the top (i.e. the beginning) of the list via the swaps. Because it only uses
comparisons to operate on elements, it is a comparison sort. This is the easiest
comparison sort to implement.

A simple way to express bubble sort in pseudocode is as follows:

procedure bubbleSort( A : list of sortable items ) defined as:


do
swapped := false
for each i in 0 to length( A ) - 2 do:
if A[ i ] > A[ i + 1 ] then
swap( A[ i ], A[ i + 1 ] )
swapped := true
end if
end for
while swapped
end procedure

Design Analysis/ Implementation Logic:

Algorithm:

The algorithm can also be expressed as:

procedure bubbleSort( A : list of sortable items ) defined as:


for each i in 1 to length(A) do:
for each j in length(A) downto i + 1 do:
if A[ j ] < A[ j - 1 ] then
swap( A[ j ], A[ j - 1 ] )
end if
end for

26
MIL Manual

end for
end procedure

Display the results.

Testing:

Sample Output:

C:\MASM611>ml assgn7.asm
Microsoft (R) Macro Assembler Version 6.11
Copyright (C) Microsoft Corp 1981-1993. All rights reserved.

Assembling: assgn7.asm

Microsoft (R) Segmented Executable Linker Version 5.31.009 Jul 13 1992


Copyright (C) Microsoft Corp 1984-1992. All rights reserved.

Object Modules [.obj]: assgn7.obj


Run File [assgn7.exe]: "assgn7.exe"
List File [nul.map]: NUL
Libraries [.lib]:
Definitions File [nul.def]:
LINK : warning L4038: program has no starting address

C:\MASM611>assgn7

Enter the choice (0=Asc/1=Dsc) :


0
The No.s in Ascending order:
10
11
12
13
14

C:\MASM611>assgn7

Enter the choice (0=Asc/1=Dsc) :


1
The No.s in Descending order:
14
13

27
MIL Manual

12
11
10

C:\MASM611>

Conclusion:
Bubble sort method is successfully implemented for sorting the numbers in ascending as
well as descending order.

ASSIGNMENT No: 8

Title of Assignment: Write an ALP in 8086 to convert a string entered from Keyboard
from Lower Case to Upper Case and vice versa

28
MIL Manual

Relevant Theory:

ASCII Table:

Design Analysis/ Implementation Logic:

Algorithm:
Accept the string from user
Accepted string will be in its ASCII equivalent form
Find capital letters by checking the bounds of 41h-5Ah for their ASCII Hex equivalents
Add 20h to get their equivalent small letters
Find small letters by checking the bounds of 61h-7Ah for their ASCII Hex equivalents
Subtract 20h to get their equivalent capital letters
Display the results and exit

Testing:

29
MIL Manual

Sample Output:

C:\MASM611>ml assgn8.asm
Microsoft (R) Macro Assembler Version 6.11
Copyright (C) Microsoft Corp 1981-1993. All rights reserved.

Assembling: assgn8.asm

Microsoft (R) Segmented Executable Linker Version 5.31.009 Jul 13 1992


Copyright (C) Microsoft Corp 1984-1992. All rights reserved.

Object Modules [.obj]: assgn8.obj


Run File [assgn8.exe]: "assgn8.exe"
List File [nul.map]: NUL
Libraries [.lib]:
Definitions File [nul.def]:
LINK : warning L4038: program has no starting address

C:\MASM611>assgn8

Enter the string in Lower case:microprocessor


The string in upper case:MICROPROCESSOR

Enter the string in upper case:INTERFACING


The string in Lower case:interfacing

C:\MASM611>

Conclusion:
An 8086 ALP to swap capital and small letters is successfully implemented.

ASSIGNMENT No: 9

Title of Assignment: Write your own Interrupt Service Routine to handle INT-4
Overflow OR Write your own Interrupt Service Routine to handle INT-0 Divide Error

Relevant Theory:

An interrupt handler, also known as an interrupt service routine (ISR), is a callback


subroutine in an operating system or device driver whose execution is triggered by the

30
MIL Manual

reception of an interrupt. Interrupt handlers have a multitude of functions, which vary


based on the reason the interrupt was generated and the speed at which the Interrupt
Handler completes its task.

An interrupt handler is a low-level counterpart of event handlers. These handlers are


initiated by either hardware interrupts or interrupt instructions in software, and are used
for servicing hardware devices and transitions between protected modes of operation
such as system calls.

The Interrupt Descriptor Table (IDT) is a data structure used by the x86 architecture to
implement an interrupt vector table. The IDT is used by the processor to determine the
correct response to interrupts and exceptions.

Use of the IDT is triggered by three types of events: hardware interrupts, software
interrupts, and processor exceptions, which together are referred to as "interrupts". The
IDT consists of 256 interrupt vectors.

Interrupt Table
Interrupt Description
INT 00h CPU: Division by Zero
INT 01h CPU: Single Step for debugging
INT 02h CPU: NMI, used e.g. by POST for memory errors
INT 03h CPU: Breakpoint for debugging
INT 04h CPU: Numeric Overflow
INT 05h Print Screen
INT 08h IRQ0: Called by system timer 18.2 times per second
INT 09h IRQ1: Called by keyboard
INT 0Bh IRQ3: Called by 2nd serial port COM2
INT 0Ch IRQ4: Called by 1st serial port COM1
IRQ5: Called by hard disk controller (PC/XT) or 2nd parallel port
INT 0Dh
LPT2 (AT)
INT 0Eh IRQ6: Called by floppy disk controller
INT 0Fh IRQ7: Called by 1st parallel port LPT1 (printer)

DOS INTERRUPT 21h

Function 25h - Set interrupt vector

31
MIL Manual

Action: Initialises an interrupt vector to point to the supplied address.


On entry: AH = 25h
AL = Interrupt number
DS:DX = segment:offset of new vector address
Returns: Nothing
Notes: This is the approved way to amend interrupt vector contents.

Before changing the contents of a vector, Function 35h should be used to


obtain the original entry, which should be re-instated when your code
terminates. The only exceptions to this rule are interrupt vectors 22h to 24h,
which are automatically restored from the PSP on program termination.

Function 35h - Get interrupt vector

Action: Returns the segment:offset of a nominated vector.


On entry: AH = 35h
AL = interrupt number
Returns: ES:BX = Segment offset of interrupt vector contents
Notes: This is the approved way to read interrupt vector contents. The original
contents of the vector, after storage, can be amended by a call to function 25h.

Design Analysis/ Implementation Logic:

Algorithm:
Write your own ISR
Store the original address of that ISR from IVT into a variable
Replace the original address on IVT with your sub-routine
Simulate a condition to activate your ISR
Restore back the original address at appropriate location in IVT
Verify the results

Testing:

Sample Output:

C:\MASM611>ml assgn9.asm
Microsoft (R) Macro Assembler Version 6.11
Copyright (C) Microsoft Corp 1981-1993. All rights reserved.

Assembling: assgn9.asm

32
MIL Manual

Microsoft (R) Segmented Executable Linker Version 5.31.009 Jul 13 1992


Copyright (C) Microsoft Corp 1984-1992. All rights reserved.

Object Modules [.obj]: assgn9.obj


Run File [assgn9.exe]: "assgn9.exe"
List File [nul.map]: NUL
Libraries [.lib]:
Definitions File [nul.def]:
LINK : warning L4038: program has no starting address

C:\MASM611>assgn9

Overflow has Occured!!!


Result is Set to zero
Overflow has Occured!!!
Result is Set to zero

Conclusion:
The ISR is written and successfully run by making appropriate changes in the IVT and
simulating related situations.

ASSIGNMENT No: 10

Title of Assignment: Write an ALP in 8086 for following operations on strings----


i) Accept a string & calculate the length of string.
ii) Reverse a string & Check it for palindrome

Relevant Theory:

The most familiar palindromes, in English at least, are character-by-character: the written
characters read the same backwards as forwards. Palindromes may consist of a single
word (such as “civic” or “level” ), a phrase or sentence (“Neil, a trap! Sid is part alien!”,

33
MIL Manual

"Was it a rat I saw?") or a longer passage of text (“Sit on a potato pan, Otis.”) Spaces,
punctuation and case are usually ignored.

String Instructions

•String instructions were designed to operate on large data structures.


•The SI and DI registers are used as pointers to the data structures
being accessed or manipulated.
•The operation of the dedicated registers stated above are used to
simplify code and minimize its size.

•The registers(DI,SI) are automatically incremented or decremented


depending on the value of the direction flag:
–DF=0, increment SI, DI.
–DF=1, decrement SI, DI.
•To set or clear the direction flag one should use the following
instructions:
–CLD to clear the DF.
–STD to set the DF.

•The REP/REPZ/REPNZ prefixes are used to repeat the operation it


precedes.
•String instructions we will discuss:
–LODS
–STOS
–MOVS
–CMPS
–SCAS

LODS/LODSB/
LODSW/LODSD

•Loads the AL, AX or EAX registers with the content of the memory
byte, word or double word pointed to by SI relative to DS. After the
transfer is made, the SI register is automatically updated as follows:
–SI is incremented if DF=0.
–SI is decremented if DF=1.

LODS/LODSB/
LODSW/LODSD

•Examples:

34
MIL Manual

–LODSB
AL=DS:[SI]; SI=SI ±1
–LODSW
AX=DS:[SI]; SI=SI ±2
–LODSD
EAX=DS:[SI]; SI=SI ±4
–LODS MEAN
AL=DS:[SI]; SI=SI ±1 (if MEAN is a byte)
–LODS LIST
AX=DS:[SI]; SI=SI ±2(if LIST is a word)
–LODS MAX
EAX=DS:[SI]; SI=SI ±4(if MAX is a double word)

LODS/LODSB/
LODSW/LODSDExampleAssume:LocationContentRegister
SI500HMemory location 500H'A'Register AL'2'After execution of
LODSBIf DF=0 then:LocationContentRegister SI501HMemory location
500H'A'Register AL'A'Else if DF=1 then:LocationContentRegister
SI4FFHMemory location 500H'A'Register AL'A'

STOS/STOSB/
STOSW/STOSD

•Transfers the contents of the AL, AX or EAX registers to the memory


byte, word or double word pointed to by DI relative to ES. After the
transfer is made, the DI register is automatically updated as follows:
–DI is incremented if DF=0.
–DI is decremented if DF=1.

STOS/STOSB/
STOSW/STOSD

•Examples:
–STOSB
ES:[DI]=AL; DI=DI ±1
–STOSW
ES:[DI]=AX; DI=DI ±2
–STOSD
ES:[DI]=EAX; DI=DI ±4
–STOS MEAN
ES:[DI]=AL; DI=DI ±1 (if MEAN is a byte)
–STOS LIST
ES:[DI]=AX; DI=DI ±2(if LIST is a word)
–STOS MAX
ES:[DI]=EAX; DI=DI ±4(if MAX is a double word)

35
MIL Manual

STOS/STOSB/
STOSW/STOSDExampleAssume:LocationContentRegister
DI500HMemory location 500H'A'Register AL'2'After execution of
STOSBIf DF=0 then:LocationContentRegister DI501HMemory location
500H'2'Register AL'2'Else if DF=1 then:LocationContentRegister
DI4FFHMemory location 500H'2'Register AL'2'

MOVS/MOVSB/
MOVSW/MOVSD

•Transfers the contents of the the memory byte, word or double word
pointed to by SI relative to DS to the memory byte, word or double
word pointed to by DI relative to ES. After the transfer is made, the DI
register is automatically updated as follows:
–DI is incremented if DF=0.
–DI is decremented if DF=1.

MOVS/MOVSB/
MOVSW/MOVSD

•Examples:
–MOVSB
ES:[DI]=DS:[SI]; DI=DI ±1;SI=SI ±1
–MOVSW
ES:[DI]= DS:[SI]; DI=DI ±2; SI=SI ±2
–MOVSD
ES:[DI]=DS:[SI]; DI=DI ±4; SI=SI ±4
–MOVS MEAN
ES:[DI]=DS:[SI]; DI=DI ±1; SI=SI ±1 (if MEAN is a byte)
–MOVS LIST
ES:[DI]=DS:[SI]; DI=DI ±2; SI=SI ±2(if LIST is a word)
–MOVS MAX
ES:[DI]=DS:[SI]; DI=DI ±4; SI=SI ±4(if MAX is a double word)

MOVS/MOVSB/
MOVSW/MOVSDExampleAssume:LocationContentRegister
SI500HRegister DI600HMemory location 500H'2'Memory location
600H'W'After execution of MOVSBIf DF=0
then:LocationContentRegister SI501HRegister DI601HMemory location
500H'2'Memory location 600H'2'Else if DF=1
then:LocationContentRegister SI4FFHRegister DI5FFHMemory location
500H'2'Memory location 600H'2'

CMPS/CMPSB/
CMPSW/CMPSD

36
MIL Manual

•Compares the contents of the the memory byte, word or double word
pointed to by SI relative to DS to the memory byte, word or double
word pointed to by DI relative to ES and changes the flags accordingly.
After the comparison is made, the DI and SI registers are automatically
updated as follows:
–DI and SI are incremented if DF=0.
–DI and SI are decremented if DF=1

SCAS/SCASB/
SCASW/SCASD

•Compares the contents of the AL, AX or EAX register with the memory
byte, word or double word pointed to by DI relative to ES and changes
the flags accordingly. After the comparison is made, the DI register is
automatically updated as follows:
–DI is incremented if DF=0.
–DI is decremented if DF=1.

Design Analysis/ Implementation Logic:

Algorithm:
Prepare a user friendly menu
Accept a string from user
Calculate the length and display
Reverse the string and display
Check if palindrome and display
Exit when user selects that option

Testing:

Sample Output:

C:\MASM611>ml assgn10.asm
Microsoft (R) Macro Assembler Version 6.11
Copyright (C) Microsoft Corp 1981-1993. All rights reserved.

Assembling: assgn10.asm

Microsoft (R) Segmented Executable Linker Version 5.31.009 Jul 13 1992


Copyright (C) Microsoft Corp 1984-1992. All rights reserved.

37
MIL Manual

Object Modules [.obj]: assgn10.obj


Run File [assgn10.exe]: "assgn10.exe"
List File [nul.map]: NUL
Libraries [.lib]:
Definitions File [nul.def]:
LINK : warning L4038: program has no starting address

C:\MASM611>assgn10

1) Enter the String

2) Length of String

3) Reverse String

4) Check Palindrome

5) Exit

Enter the choice:


1
Enter String
madam
String:madam

1) Enter the String

2) Length of String

3) Reverse String

4) Check Palindrome

5) Exit

Enter the choice:


2
String Length:05

1) Enter the String

2) Length of String

3) Reverse String

38
MIL Manual

4) Check Palindrome

5) Exit

Enter the choice:


3
Reversed String:madam

1) Enter the String

2) Length of String

3) Reverse String

4) Check Palindrome

5) Exit

Enter the choice:


4
Palindrome

1) Enter the String

2) Length of String

3) Reverse String

4) Check Palindrome

5) Exit

Enter the choice:


5
C:\MASM611>

Conclusion: String is accepted and its length the calculated. The string is reversed and
checked for palindrome. All the results are displayed.

ASSIGNMENT No: 11

Title of Assignment: Write an ALP in 8086 to find no. of words, characters, lines &
capital letters from given text and no. of occurrences of sub-string in Data Segment

39
MIL Manual

Relevant Theory:

ASCII Table:

Note ASCII values of Enter (cr) = 13 and space = 32 to take into account words and
lines.

Design Analysis/ Implementation Logic:

Algorithm:
Prepare a user friendly menu
Assume the string is stored in the memory
Calculate total number of characters
Calculate total no of words by counting spaces (ASCII equ = 32)
Calculate total no of lines by counting crs (ASCII eqn = 13)

40
MIL Manual

Calculate total capital characters using Hex equivalent ASCII bound of 41h-5Ah
Calculate sub-string occurrences using DI and SI as pointers.
Display all the results

Testing:

Sample Output:

Microsoft (R) Segmented Executable Linker Version 5.31.009 Jul 13 1992


Copyright (C) Microsoft Corp 1984-1992. All rights reserved.

Object Modules [.obj]: assgn11.obj


Run File [assgn11.exe]: "assgn11.exe"
List File [nul.map]: NUL
Libraries [.lib]:
Definitions File [nul.def]:
LINK : warning L4038: program has no starting address

C:\MASM611>assgn11

Hi! How do you do?


Hope you are not mad
BYE FOR NOW!!

The string Length57


No of Lines
03
No of capital letters
12
No of words
10
No of chars
37
C:\MASM611>ml assgn11a.asm
Microsoft (R) Macro Assembler Version 6.11
Copyright (C) Microsoft Corp 1981-1993. All rights reserved.

Assembling: assgn11a.asm

Microsoft (R) Segmented Executable Linker Version 5.31.009 Jul 13 1992


Copyright (C) Microsoft Corp 1984-1992. All rights reserved.

Object Modules [.obj]: assgn11a.obj

41
MIL Manual

Run File [assgn11a.exe]: "assgn11a.exe"


List File [nul.map]: NUL
Libraries [.lib]:
Definitions File [nul.def]:
LINK : warning L4038: program has no starting address

C:\MASM611>assgn11a

Enter the String:


Kikokiko
Enter the Sub-String:
Ik
No of occurrences of a sub-string
02
C:\MASM611>

Conclusion:
From the given string total characters, capital letters, words and lines are accurately
calculated. Occurrence of sub-strings is successfully implemented.

ASSIGNMENT No: 12

Title of Assignment: Write an ALP in 8086 to perform String manipulation using FAR
Procedure to Concatenate & Compare two strings.
Note: Use PUBLIC & EXTERN directive. Create .OBJ files and link them to create an
EXE file

42
MIL Manual

Relevant Theory:

Procedures
� Also known as subroutines, these sets of
instructions usually perform a single task.
� They are reusable code, that can be
executed as often as needed by calling it.
� Procedures save memory, but the calling
of a procedure takes a small amount of
time.

� Format
� Name PROC [NEAR or FAR]
� Subroutine code
� RET
� ENDP
� Global procedures are defined as FAR.
� Local procedures are defined as NEAR.

� CALL destination
� Calls a subroutine at location destination.
� Different addressing modes may be used for
destination.
� CALL DELAY
� CALL EBX
� CALL ARRAY[BX]
� RET
� Returns execution of program to location
stored in stack.
� NEAR or FAR is dependent on procedure
definition.

The PUBLIC, EXTERN, and EXTRN Directives

Technically, the include directive provides you with all the facilities you need to create modular
programs. You can build up a library of modules, each containing some specific routine, and
include any necessary modules into an assembly language program using the appropriate
include commands. MASM (and the accompanying LINK program) provides a better way:
external and public symbols.

One major problem with the include mechanism is that once you've debugged a routine,
including it into an assembly wastes a lot of time since MASM must reassemble bug-free code
every time you assemble the main program. A much better solution would be to preassemble the
debugged modules and link the object code modules together rather than reassembling the entire

43
MIL Manual

program every time you change a single module. This is what the public and extern
directives provide for you. Extrn is an older directive that is a synonym for extern. It provides
compatibility with old source files. You should always use the extern directive in new source
code.

To use the public and extern facilities, you must create at least two source files. One file
contains a set of variables and procedures used by the second. The second file uses those
variables and procedures without knowing how they're implemented. To demonstrate, consider
the following two modules:

;Module #1:

public Var1, Var2, Proc1


DSEG segment para public 'data'
Var1 word ?
Var2 word ?
DSEG ends

CSEG segment para public 'code'


assume cs:cseg, ds:dseg
Proc1 proc near
mov ax, Var1
add ax, Var2
mov Var1, ax
ret
Proc1 endp
CSEG ends
end

;Module #2:
extern Var1:word, Var2:word, Proc1:near
CSEG segment para public 'code'
.
.
.
mov Var1, 2
mov Var2, 3
call Proc1
.
.
.
CSEG ends
end

Module #2 references Var1, Var2, and Proc1, yet these symbols are external to module #2.
Therefore, you must declare them external with the extern directive. This directive takes the
following form:

extern name:type {,name:type...}

Name is the name of the external symbol, and type is the type of that symbol. Type may be any
of near, far, proc, byte, word, dword, qword, tbyte, abs (absolute, which is a
constant), or some other user defined type.

44
MIL Manual

The current module uses this type declaration. Neither MASM nor the linker checks the declared
type against the module defining name to see if the types agree. Therefore, you must exercise
caution when defining external symbols. The public directive lets you export a symbol's value
to external modules. A public declaration takes the form:

public name {,name ...}

Each symbol appearing in the operand field of the public statement is available as an external
symbol to another module. Likewise, all external symbols within a module must appear within a
public statement in some other module.

Once you create the source modules, you should assemble the file containing the public
declarations first. With MASM 6.x, you would use a command like

ML /c pubs.asm

The "/c" option tells MASM to perform a "compile-only" assembly. That is, it will not try to link the
code after a successful assembly. This produces a "pubs.obj" object module.

Next, assemble the file containing the external definitions and link in the code using the MASM
command:

ML exts.asm pubs.obj

Assuming there are no errors, this will produce a file "exts.exe" which is the linked and executable
form of the program.

Note that the extern directive defines a symbol in your source file. Any attempt to redefine that
symbol elsewhere in your program will produce a "duplicate symbol" error. This, as it turns out, is
the source of problems which Microsoft solved with the externdef directive.

Design Analysis/ Implementation Logic:

Algorithm:
1. Accept the first string
2. Accept the second string
3. Call the far procedure to concatenate the strings
4. Maintain the stack pointer
5. Call the far procedure to compare the strings
6. Maintain the stack pointer
7. Display the results and exit

Testing:

Sample Output:

45
MIL Manual

Copyright (C) Microsoft Corp 1993. All rights reserved.

Invoking: ML.EXE /I. /Zm /c /Ta assgn12.asm

Microsoft (R) Macro Assembler Version 6.11


Copyright (C) Microsoft Corp 1981-1993. All rights reserved.

Assembling: assgn12.asm

C:\MASM611>masm pcon.asm
Microsoft (R) MASM Compatibility Driver
Copyright (C) Microsoft Corp 1993. All rights reserved.

Invoking: ML.EXE /I. /Zm /c /Ta pcon.asm

Microsoft (R) Macro Assembler Version 6.11


Copyright (C) Microsoft Corp 1981-1993. All rights reserved.

Assembling: pcon.asm

C:\MASM611>masm pcmp.asm
Microsoft (R) MASM Compatibility Driver
Copyright (C) Microsoft Corp 1993. All rights reserved.

Invoking: ML.EXE /I. /Zm /c /Ta pcmp.asm

Microsoft (R) Macro Assembler Version 6.11


Copyright (C) Microsoft Corp 1981-1993. All rights reserved.

Assembling: pcmp.asm

C:\MASM611>link assgn12+pcon+pcmp

Microsoft (R) Segmented Executable Linker Version 5.31.009 Jul 13 1992


Copyright (C) Microsoft Corp 1984-1992. All rights reserved.

Run File [assgn12.exe]:


List File [nul.map]:
Libraries [.lib]:
Definitions File [nul.def]:
LINK : warning L4038: program has no starting address

C:\MASM611>assgn12

Enter the first string:micro


Enter the second conc string:processor

46
MIL Manual

Concatenated string:microprocessor

Enter the first string:micro


Enter the second comp string:macro
Strings are not same!
C:\MASM611>

Conclusion:
String concatenation and comparison successfully implemented using far procedures.

ASSIGNMENT No: 13

Title of Assignment: Write an ALP in 8086 to interface 8255 (PPI) in INPUT/OUTPUT


Mode. Input data on Port A =15H & on Port B = 16H.Write 8086 ALP to out 56H on
Port C. Draw block diagram of 8255 & show the interfacing details with 8086

47
MIL Manual

Relevant Theory:

Study Apparatus:
DYNA-86: (8086-SDK board)
DYNA-8255 study card

DYNA 86 Specifications:
Microprocessors: 8086, operating frequency: 8 MHz
64 KB ROM with monitor firmware (in two 27256—U30 and U32)
64 KB battery backed static RAM (in two 62256—U31 and U33)
Support chips: 8254, 8251, 8259, 8255, 8279, socket for 8087

Memory Map:

Socket Address Chips Capacity

U31/U33 00000H – 0FFFFH Battery backed SRAM 64 KB (32+32)

U30/U32 F0000H – FFFFFH Firmware EPROM 64 KB (32+32)

Important serial mode commands:

Display Memory D[W][[seg:]strt[,end]]


Edit Memory E[W][[seg:]strt]
Copy Memory C[seg:]strt,end,[seg:]dest
Fill Memory F[W][seg:]strt,end,byte/word
Insert Byte/Word I[W][seg:]strt,end,byte/word
Delete Byte/Word DL[W][seg:]strt,end
Search Byte/Word S[W][seg:]strt,end,byte/word
Compare blocks CM[seg:]strt,end,[seg:]strt
Register R[reg]
Trace T[[seg:]strt]
Go G[[[seg:]strt],[[seg:]brk]]
Hex to Dec HDnum
Dec to Hex Dhnum

48
MIL Manual

Load file L[seg:]


Write file W[seg:],strt,end
Input from port IN[W]addr
Output to port O[W]addr,[byte/word]
Assemble A[[seg:]off]
Unassemble U[[seg:]off[,[seg:]off]]

Whenever the system resets or during power-on , the monitor


immediately terminates its present activity and jumps to its
initialization routine. This routine initializes interrupt vectors 1 through
3 as follows :
Interrupt 1 - Single Step : Used with Single Step command
Interrupt B - IRQ3 : Monitors [ INT ] key
Interrupt 3 - Breakpoint : Used with the GO command .

8255 Study Card:


Default port Addresses:

Port A: 30h
Port B: 31h
Port C: 32h
CWR : 33h

8255 Internal Architecture:


The 8255 is a PPI device whose function is that of a general purposes I/O component to
Interface peripheral equipment to the microcomputer system. The functional
configuration of the 8255A is programmed by the systems software so that normally no
external logic is necessary to interface peripheral devices or structures.

8255 Operating Modes:

There are three modes used for parallel data transfer from 8086 Microprocessor to output
devices and from input devices to 8086 Microprocessor. These are
1. Simple Input and Output
2. Simple strobe I/O
3. a. Single handshake I/O
b. Double handshake I/O

49
MIL Manual

1. Simple Input and Output


In order to receive data from input devices like switches ,connect the switches to
an input port and read it. As data is always present and ready so microprocessor can read
it. Likewise when microprocessor wants to send data to an external devices such as an
LED, connect the input of LED buffer on an output port pin. The LED are always there
and ready and hence data are transmitted on data lines to LED's at any time.

2. Simple Strobe I/O


In many applications, valid data is present on an external device only at a certain
time, so it must e read in at that time. An example of this is the ASCII encoded keyboard.
When a key is pressed, circuitry on the keyboard sends out the ASCII code for the
pressed key on eight parallel data lines and then sends out a strobe signal on another line
to indicate that valid data is present on eight data lines. The strobe line to an interrupt
input on the processor and have an interrupt service procedure read in the data when the
processor receives an interrupt. Here data transfer is time dependent.

3. a. Single Handshake I/O


The peripheral outputs some parallel data and sends an STB signal to the
microprocessor. The microprocessor detects STB signal on a polled or interrupt basis and
read in byte of data. Then the microprocessor sends an Acknowledge signal (ACK) to the
peripheral to indicate that the data has been read and that the peripheral can send the next
byte of data.

3 b. Double Handshake I/O


For data transfer where more coordination is required between the sending system
and receiving system, a double handshake is used. The sending device asserts its STB
line low to check whether the receiving device is ready. Receiving device raises ACK
line high if it is ready. The peripheral device then sends the data on the data lines, and

50
MIL Manual

raises STB signal high to indicate that valid data is present on the data lines. After the
data is read in by the receiving device it drops its ACK signal to indicate that data on the
data lines are read successfully.

Mode Selection
There are three basic modes of operation than can be selected by the system software:
Mode 0 - Basic Input/Output
Mode 1 - Strobed Input/Output
Mode 2 - Bi-directional Bus

The modes for Port A and Port B can be separately defined, while Port C is divided into
two portions as required by the Port A and Port B definitions.

I/O MODE

Mode 0 (Basic Input/Output).


This functional configuration provides simple input and output operations for each of the
three ports. No handshaking is required, data is simply written to or read from a specified
port. Mode 0 Basic Functional Definitions:

Mode 1 - (Strobed Input/Output)


This functional configuration provides a means for transferring I/O data to or
from a specified port in conjunction with strobes or “hand shaking” signals. In this mode,
port A and B use the lines on port C to generate or accept these “hand shaking” signals.

STB - Strobe Input : A “low” on this input loads data into the input latch.
IBF - Input Buffer Full : A “high” on this output indicates that the data has been loaded
into the input latch.

51
MIL Manual

INTR - Interrupt Request : A “high” on this output can be used to interrupt the CPU
when input device is requesting service.

OBF - Output Buffer Full : The OBF output will go “low” to indicate that the CPU has
written data out to be specified port.
ACK - Acknowledge Input: A “low” on this input informs the 8255 that the data from
Port A or Port B is ready to be accepted.
INTR - Interrupt Request: A “high” on this output can be used to interrupt the CPU
when an output device has accepted data transmitted by the CPU.

Mode 2 (Strobed Bi-Directional I/O)


The functional configuration provides a means for communicating with a
peripheral device or structure on a single 8-bit bus for both transmitting and receiving
data. “Hand shaking” signals are provided to maintain proper bus flow discipline similar
to Mode 1. The 5-bit control port (Port C) is used for control and status for the 8-bit, bi-
directional bus port (Port A)

Design Analysis/ Implementation Logic:

Sample Programs:

(I) Out 0AH on port A: Configure 8255 in mode 0. See the status of port A by
observing LEDs.

A 0100:0000

MOV AL,80
OUT 33,AL
MOV AL,0A
OUT 30,AL
INT 3

G 0100:0000

(II) Configure 8255 in mode 0, porst A-B-C as i/ps, read data in different
registers. The i/ps are given to the ports by grounding various port lines to
ground, using the TAB connectors. Observe the contents of the registers using
command R.

A 0100:0000
MOV AL,9B
OUT 33,AL
IN AL,30
MOV BL,AL

52
MIL Manual

IN AL,31
MOV CL,AL
INT 3

G 0100:0000

Testing:

For the various programs verify the output by observing the bits of the corresponding
ports, which is demonstrated by the associated LEDs.

Conclusion:
8255 is initialized in an I/O mode and experiments are performed on all the three ports.

ASSIGNMENT No: 14

53
MIL Manual

Title of Assignment: Write an ALP in 8086 to initialize 8255 in BSR Mode. Set & Reset
Bits 1,3 & 5 after every 2 Seconds. Draw block diagram of 8255 & show the interfacing
details with 8086

Relevant Theory:

Study Apparatus:
DYNA-86: (8086-SDK board)
DYNA-8255 study card

DYNA 86 Specifications:
Microprocessors: 8086, operating frequency: 8 MHz
64 KB ROM with monitor firmware (in two 27256—U30 and U32)
64 KB battery backed static RAM (in two 62256—U31 and U33)
Support chips: 8254, 8251, 8259, 8255, 8279, socket for 8087

Memory Map:

Socket Address Chips Capacity

U31/U33 00000H – 0FFFFH Battery backed SRAM 64 KB (32+32)

U30/U32 F0000H – FFFFFH Firmware EPROM 64 KB (32+32)

Important serial mode commands:

Display Memory D[W][[seg:]strt[,end]]


Edit Memory E[W][[seg:]strt]
Copy Memory C[seg:]strt,end,[seg:]dest
Fill Memory F[W][seg:]strt,end,byte/word
Insert Byte/Word I[W][seg:]strt,end,byte/word
Delete Byte/Word DL[W][seg:]strt,end
Search Byte/Word S[W][seg:]strt,end,byte/word
Compare blocks CM[seg:]strt,end,[seg:]strt
Register R[reg]

54
MIL Manual

Trace T[[seg:]strt]
Go G[[[seg:]strt],[[seg:]brk]]
Hex to Dec HDnum
Dec to Hex Dhnum
Load file L[seg:]
Write file W[seg:],strt,end
Input from port IN[W]addr
Output to port O[W]addr,[byte/word]
Assemble A[[seg:]off]
Unassemble U[[seg:]off[,[seg:]off]]

Whenever the system resets or during power-on , the monitor


immediately terminates its present activity and jumps to its
initialization routine. This routine initializes interrupt vectors 1 through
3 as follows :
Interrupt 1 - Single Step : Used with Single Step command
Interrupt B - IRQ3 : Monitors [ INT ] key
Interrupt 3 - Breakpoint : Used with the GO command .

8255 Study Card:


Default port Addresses:

Port A: 30h
Port B: 31h
Port C: 32h
CWR : 33h

8255 Internal Architecture:


The 8255 is a PPI device whose function is that of a general purposes I/O component to
Interface peripheral equipment to the microcomputer system. The functional
configuration of the 8255A is programmed by the systems software so that normally no
external logic is necessary to interface peripheral devices or structures.

8255 Operating Modes:

There are three modes used for parallel data transfer from 8086 Microprocessor to output
devices and from input devices to 8086 Microprocessor. These are
1. Simple Input and Output
2. Simple strobe I/O
3. a. Single handshake I/O
b. Double handshake I/O

55
MIL Manual

1. Simple Input and Output


In order to receive data from input devices like switches ,connect the switches to
an input port and read it. As data is always present and ready so microprocessor can read
it. Likewise when microprocessor wants to send data to an external devices such as an
LED, connect the input of LED buffer on an output port pin. The LED are always there
and ready and hence data are transmitted on data lines to LED's at any time.

2. Simple Strobe I/O


In many applications, valid data is present on an external device only at a certain
time, so it must e read in at that time. An example of this is the ASCII encoded keyboard.
When a key is pressed, circuitry on the keyboard sends out the ASCII code for the
pressed key on eight parallel data lines and then sends out a strobe signal on another line
to indicate that valid data is present on eight data lines. The strobe line to an interrupt
input on the processor and have an interrupt service procedure read in the data when the
processor receives an interrupt. Here data transfer is time dependent.

3. a. Single Handshake I/O


The peripheral outputs some parallel data and sends an STB signal to the
microprocessor. The microprocessor detects STB signal on a polled or interrupt basis and
read in byte of data. Then the microprocessor sends an Acknowledge signal (ACK) to the
peripheral to indicate that the data has been read and that the peripheral can send the next
byte of data.

3 b. Double Handshake I/O


For data transfer where more coordination is required between the sending system
and receiving system, a double handshake is used. The sending device asserts its STB
line low to check whether the receiving device is ready. Receiving device raises ACK
line high if it is ready. The peripheral device then sends the data on the data lines, and

56
MIL Manual

raises STB signal high to indicate that valid data is present on the data lines. After the
data is read in by the receiving device it drops its ACK signal to indicate that data on the
data lines are read successfully.

Mode Selection
There are three basic modes of operation than can be selected by the system software:
Mode 0 - Basic Input/Output
Mode 1 - Strobed Input/Output
Mode 2 - Bi-directional Bus

The modes for Port A and Port B can be separately defined, while Port C is divided into
two portions as required by the Port A and Port B definitions.

BSR MODE:

Mode 0 (Basic Input/Output).


This functional configuration provides simple input and output operations for each of the
three ports. No handshaking is required, data is simply written to or read from a specified
port. Mode 0 Basic Functional Definitions:

Mode 1 - (Strobed Input/Output)


This functional configuration provides a means for transferring I/O data to or
from a specified port in conjunction with strobes or “hand shaking” signals. In this mode,
port A and B use the lines on port C to generate or accept these “hand shaking” signals.

STB - Strobe Input : A “low” on this input loads data into the input latch.
IBF - Input Buffer Full : A “high” on this output indicates that the data has been loaded
into the input latch.
INTR - Interrupt Request : A “high” on this output can be used to interrupt the CPU
when input device is requesting service.

57
MIL Manual

OBF - Output Buffer Full : The OBF output will go “low” to indicate that the CPU has
written data out to be specified port.
ACK - Acknowledge Input: A “low” on this input informs the 8255 that the data from
Port A or Port B is ready to be accepted.
INTR - Interrupt Request: A “high” on this output can be used to interrupt the CPU
when an output device has accepted data transmitted by the CPU.

Mode 2 (Strobed Bi-Directional I/O)


The functional configuration provides a means for communicating with a
peripheral device or structure on a single 8-bit bus for both transmitting and receiving
data. “Hand shaking” signals are provided to maintain proper bus flow discipline similar
to Mode 1. The 5-bit control port (Port C) is used for control and status for the 8-bit, bi-
directional bus port (Port A)

Design Analysis/ Implementation Logic:

Sample Programs:

(III) BSR Mode (Applicable only for port C)

To set/reset bits of port C. After configuring Port C as o/p port, individual bits
of port C can be set/reset in this mode.

A 0100:0000

MOV AL,80
OUT 33,AL
go: MOV AL,01
OUT 33,AL
CALL 0040 -- Address of the delay routine
MOV AL,00
OUT 33,AL
CALL 0040
JMP go
INT 3

G 0100:0000

Delay Routine:

A 0100:0040

MOV BX,0A
l1: MOV CX,DA00

58
MIL Manual

l2: DEC CX
JNZ l2
DEC BX
JNZ l1
RET

Observe the corresponding bit(s) of port C getting set/reset.

Testing:

For the BSR programs verify the output by observing the bits of port C. Observed the
port C LEDs getting turned ON and OFF as bits are getting set and reset

Conclusion:
8255 is initialized in an BSR mode and experiments are performed on port C.

ASSIGNMENT No: 15

59
MIL Manual

Title of Assignment: Write an ALP in 8086 to initialize 8253 ( Programmable


Timer/Counter ) in all 6 Modes of operation. Observe the OUT pin for each mode &
draw the waveforms. Draw the block diagram of 8253 & show the interfacing details
with 8086

Relevant Theory:

Study Apparatus:
DYNA-86: (8086-SDK board)
DYNA-8253 study card

DYNA 86 Specifications:
Microprocessors: 8086, operating frequency: 8 MHz
64 KB ROM with monitor firmware (in two 27256—U30 and U32)
64 KB battery backed static RAM (in two 62256—U31 and U33)
Support chips: 8254, 8251, 8259, 8255, 8279, socket for 8087

Memory Map:

Socket Address Chips Capacity

U31/U33 00000H – 0FFFFH Battery backed SRAM 64 KB (32+32)

U30/U32 F0000H – FFFFFH Firmware EPROM 64 KB (32+32)

Important serial mode commands:

Display Memory D[W][[seg:]strt[,end]]


Edit Memory E[W][[seg:]strt]
Copy Memory C[seg:]strt,end,[seg:]dest
Fill Memory F[W][seg:]strt,end,byte/word
Insert Byte/Word I[W][seg:]strt,end,byte/word
Delete Byte/Word DL[W][seg:]strt,end
Search Byte/Word S[W][seg:]strt,end,byte/word

60
MIL Manual

Compare blocks CM[seg:]strt,end,[seg:]strt


Register R[reg]
Trace T[[seg:]strt]
Go G[[[seg:]strt],[[seg:]brk]]
Hex to Dec HDnum
Dec to Hex Dhnum
Load file L[seg:]
Write file W[seg:],strt,end
Input from port IN[W]addr
Output to port O[W]addr,[byte/word]
Assemble A[[seg:]off]
Unassemble U[[seg:]off[,[seg:]off]]

Whenever the system resets or during power-on , the monitor


immediately terminates its present activity and jumps to its
initialization routine. This routine initializes interrupt vectors 1 through
3 as follows :
Interrupt 1 - Single Step : Used with Single Step command
Interrupt B - IRQ3 : Monitors [ INT ] key
Interrupt 3 - Breakpoint : Used with the GO command .

8253 Study Card:


Default Addresses:

Counter 0: 30h
Counter 1: 31h
Counter 2: 32h
CWR : 33h

8253 Internal Architecture:

61
MIL Manual

8253 is a programmable Interval timer/counter specifically designed for use with the Intel
Micro computer systems. It is used for generation of accurate time delay under software
control. User initializes one of the counters of the 8253 with the desired quantity, then
upon command the 8253 will count-out the delay and interrupt the CPU when it has
completed its tasks.

Control Word Format:

8253 Operating Modes:

Sr No Mode 0 Status
01 After count is loaded , Output Goes Low
02 When TC (Termination Cnt) is reached High
03 GATE is HIGH Starts Counting
04 GATE is LOW Stops Counting
05 GATE RISING Pulse No Change
06 New Count is loaded in between Starts with new count

MODE 1: Programmable One-Shot.

Sr No Mode 1 Status

62
MIL Manual

01 After count is loaded , Output Goes Low


02 When TC is reached High
03 GATE is HIGH No Change
04 GATE is LOW No Change
05 GATE RISING Pulse Starts Counting
06 New Count is loaded in between No Effect

MODE 2: Rate Generator. Divide by N counter.

Sr Mode 2 Status
No
01 After count is loaded , Output High
Goes
02 When TC is reached Low for one period of input clock
03 GATE is HIGH Starts Counting
04 GATE is LOW Stops Counting
05 GATE RISING Pulse Starts Counting by reloading count value
again
06 New Count is loaded in between No Effect

MODE 3: Square Wave Rate Generator.

Sr Mode 3 Status
No
01 GATE is Starts Counting
HIGH
02 GATE is Stops Counting
LOW
03 GATE No Effect
RISING Pulse
04 New Count is No Effect
loaded in
between
Special output will remain high until one half the count has been
Feature completed (for even numbers) and go low for the other half of
the count. If the count is odd, the output will be high for
(N+1)/2 counts and low for (N-1)/2 counts.

MODE 4: Software Triggered Strobe.

Sr Mode 4 Status
No

63
MIL Manual

01 After count is loaded , Output High


Goes
02 When TC is reached Low for one period of input clock
03 GATE is HIGH Starts Counting
04 GATE is LOW Stops Counting
05 New Count is loaded in between Starts Counting by reloading count value
again
Special Feature Repeat Process again

MODE 5: Hardware Triggered Strobe.

Sr Mode 5 Status
No
01 After count is loaded , Output High
Goes
02 When TC is reached Low for one period of input clock
03 GATE is HIGH No Effect
04 GATE is LOW No Effect
05 GATE RISING Pulse Initiates Counting
06 New Count is loaded in between Starts Counting by reloading count value
again
Special Feature Repeat Process again

Design Analysis/ Implementation Logic:


Sample Codes:

Mode 0

A 0100:0000

MOV AL,11
OUT 33,AL
MOV AL,04 (COUNT VALUE)
OUT 30,AL
INT 3

Depending on the selected mode control word changes,


Mode 0 : CWR 11
Mode 1 : CWR 13
Mode 2 : CWR 15
Mode 3 : CWR 17
Mode 4 : CWR 19
Mode 5 : CWR 1B

64
MIL Manual

65
MIL Manual

Testing:

Observe the status of the o/p of the selected counter.


Always connect clk to the pulsar tag and connect Gate to either Vcc or Gnd, depending
on the selected mode.

Conclusion:

8253 is successfully interfaced with 8086 system. 8253 is configured in all the six modes
and the output is observed with the help of the respective LEDs.

ASSIGNMENT No: 16

66
MIL Manual

Title of Assignment: Write an ALP in 8086 to initialize 8279 in Display mode for
scrolling display.
• Initialize 8279 in 8*8 bit character display, Left Entry Decoded Mode.
• Initialize 8279 in 16*8 bit character display, Right Entry Encoded Mode.
Draw the block diagram of 8279 & show the interfacing details with 8086

Relevant Theory:

Study Apparatus:
DYNA-86: (8086-SDK board)
DYNA-8279 study card

DYNA 86 Specifications:
Microprocessors: 8086, operating frequency: 8 MHz
64 KB ROM with monitor firmware (in two 27256—U30 and U32)
64 KB battery backed static RAM (in two 62256—U31 and U33)
Support chips: 8254, 8251, 8259, 8255, 8279, socket for 8087
Memory Map:

Socket Address Chips Capacity

U31/U33 00000H – 0FFFFH Battery backed SRAM 64 KB (32+32)

U30/U32 F0000H – FFFFFH Firmware EPROM 64 KB (32+32)

Important serial mode commands:

Display Memory D[W][[seg:]strt[,end]]


Edit Memory E[W][[seg:]strt]
Copy Memory C[seg:]strt,end,[seg:]dest
Fill Memory F[W][seg:]strt,end,byte/word
Insert Byte/Word I[W][seg:]strt,end,byte/word
Delete Byte/Word DL[W][seg:]strt,end
Search Byte/Word S[W][seg:]strt,end,byte/word

67
MIL Manual

Compare blocks CM[seg:]strt,end,[seg:]strt


Register R[reg]
Trace T[[seg:]strt]
Go G[[[seg:]strt],[[seg:]brk]]
Hex to Dec HDnum
Dec to Hex Dhnum
Load file L[seg:]
Write file W[seg:],strt,end
Input from port IN[W]addr
Output to port O[W]addr,[byte/word]
Assemble A[[seg:]off]
Unassemble U[[seg:]off[,[seg:]off]]

Whenever the system resets or during power-on , the monitor


immediately terminates its present activity and jumps to its
initialization routine. This routine initializes interrupt vectors 1 through
3 as follows :
Interrupt 1 - Single Step : Used with Single Step command
Interrupt B - IRQ3 : Monitors [ INT ] key
Interrupt 3 - Breakpoint : Used with the GO command .

8279 Study Card:


Default Addresses:

Control/Status port: 31h


Data Port : 30h

Block Diagram of 8279.

SYMBOL DESCRIPTION
DB0-DB7 BI-DIRECTIONAL DATA BUS: All data and commands between the
CPU
and 8279 are transmitted on these lines.

68
MIL Manual

RESET A high signal on this pin resets the 8279. After being reset the 8279 is
placed in 16 8-bit character display-left entry and Encoded scan
keyboard-2 key lockout. Along with this the program clock prescaler is
set to 31.
A0 A high on this line indicates the signals in or out are interpreted as a
command or status. A low indicates that they are data.
IRQ In a keyboard mode, the interrupt line is high when there is data in the
FIFO/Sensor RAM. The interrupt line goes low with each FIFO/Sensor
RAM read and returns high if there is still information in the RAM. In a
sensor mode, the interrupt line goes high whenever a change in a sensor is
detected.
SL0-SL3 Scan lines, which are used to scan the key switch or sensor matrix and
display digits. These lines can be either encoded (1 of 16) or decoded (1
of 4).
RL0-RL7 Return line inputs which are connected to the scan lines through the keys
or sensor switches. They have active internal pull-ups to keep them high
until a switch closure pulls one low. They also serve as 8-bit Input in
Strobed Input Mode.
SHIFT The shift input status is stored along with the key position on key closure
in the Scanned Keyboard modes.
CNTL/STB For keyboard mode this line is used as a control input and stored like
status on a key closure. The line is also the strobe line that enters the data
into the FIFO in the strobed input mode. (Rising Edge).
OUT A0-A3 These two ports are the outputs for the 16x4 display refresh registers. The
OUT B0-B3 data from these outputs is synchronized to the scan lines (SL0 – SL3) for
multiplexed digit displays. The two 4-bit ports may be blanked
independently and considered as one 8-bit port.
BD This output is used to blank the display during digit switching or by a
display blanking command.

The Intel 8279 is a general purpose Programmable Keyboard and Display I/O Interface
device designed for use with Intel Microprocessors.

The 8279 has two sections: keyboard and display. CPU is relieved from scanning the
keyboard or refreshing the display.
1) The Keyboard portion can provide a scanned interface to a 64-contact key
matrix.
The keyboard section will also interface to regular typewriter style keyboards
or random toggle or thumb switches, array of Sensors or Strobed Interface
Keyboards.
Key depressions can be 2-key lockout or N-key rollover.
Keyboard entries are debounced and strobed in an 8-char FIFO.
2) The display portion provides a scanned display interface for LED,
incandescent and other popular display technologies. Both numeric and
alphanumeric segment displays may be used.

69
MIL Manual

The display section drives alphanumeric displays or a bank of indicator lights.


Thus the
CPU is relieved from scanning the keyboard or refreshing the display.
(Advantages over
8255).
The 8279 has 16x8 Display RAM, which can be organized into dual 16x4.
The RAM
can be loaded or interrogated by CPU. Both right entry, calculator and left
entry
typewriter display formats are possible. Both read and write of the display
RAM can be
done with auto-increment of the display RAM address.

Input Modes
1. Scanned Keyboard-with encoded (8 x 8 key keyboard) or decoded (4 x 8 key
keyboard) scan lines. A key depression generates a 6-bit encoding of key position.
Position and shift and control status are stored in the FIFO.
2. Scanned Sensor Matrix-with encoded (8 x 8 matrix switches) or decoded (4 x 8
matrix switches) scan lines. Key status (open or closed) stored in RAM addressable by
CPU.
3. Strobed Input-Data on return lines during control line strobe is transferred to FIFO.

Output Modes
1. 8 or 16 character-multiplexed displays that can be organized as dual 4-bit or single 8
bit
2. Right entry or left entry display formats.

Scan Counter: The scan counter has two modes. In the encoded mode, the counter
provides a binary count that must be externally decoded to provide the scan lines for the
keyboard and display. In the decoded mode, the scan counter decodes the least significant
2 bits and provides a decoded 1 of 4 scan.
In the Encoded mode, the scan lines are active high outputs.
In the Decoded mode, the scan lines are active low outputs.

Return Buffers and Keyboard Debounce and Control


1. In the keyboard mode, these lines are scanned, looking for key closures in that row. If
the debounce circuit detects a closed switch, it waits about 10 ms to check if the switch
remains closed. If it does, the address of the switch in the matrix plus the status of SHIFT
and CONTROL are transferred to the FIFO.
2. In the scanned Sensor Matrix modes, the contents of the return lines are directly
transferred to the corresponding row of the Sensor RAM (FIFO) each key scan time.

70
MIL Manual

3. In Strobed input mode, the contents of the return lines are transferred to the FIFO on
the rising edge of the CNTL/STB line pulse.

Display Address Registers and Display RAM


The Display Address Register hold the address of the word currently being
written/read by the CPU and two 4-bit nibbles being displayed. They also can be set to
auto increment after each read or write. The CPU can directly read the Display RAM
after the correct mode and address is set.

FIFO / Sensor RAM and Status


This block is a dual function 8x8 RAM. In Keyboard/ Strobed Input Mode, it is a
FIFO. FIFO Status keeps track of the no. of characters in the FIFO and whether it is full
or empty.
The status logic also provides IRQ signal when the FIFO is not empty.

Commands used in 8279?

The following commands program the 8279 operating modes. The commands are
sent on the Data Bus with CS low and A0 is high and are loaded to the 8279 on the rising
edge of WR.

71
MIL Manual

Data Display in 8279?

Left Entry : Left Entry mode is the simplest display format in that each display position
directly corresponds to a byte (or nibble) in the Display RAM. Address 0 in the RAM is
the left-most display character and address 15 (or address 7 In 8 character display) is the
right most display character.

Right Entry : Right entry is the method used by most electronic calculators. The first
entry is placed in the right most display character. The next entry is also placed in the
right most character after the display is shifted left one character.

72
MIL Manual

FIFO Status Register ?

FlFO status is used in the Keyboard and Strobed Input modes to indicate the number of
characters in the FIFO and to indicate whether an error has occurred. There are two types
of errors possible: overrun and under run. Overrun occurs when the entry of another
character into a full FlFO is attempted. Under run occurs when the CPU tries to read an
empty FIFO. The FlFO status word also has a bit to indicate that the Display RAM was
unavailable because a Clear Display or Clear All command had not completed its
clearing operation. In Special Error Mode the S/E bit is showing the error flag and serves
as an indication to whether a simultaneous multiple closure error has occurred.

DU S/E O U F N N N

NNN  Indicates number of characters in FIFO.


F  FIFO Full
U  Under run error
O  Error Over run
S/E  Sensor Closure / Error Flag multiple closures
DU  Display Unavailable.

8279 Study Card Display connections :

(i) For decoded mode :

Connect SL0-SL3 lines to CSL0-CSL3

(ii) For encoded mode :

Connect SL0-SL3 lines to BSL0-BSL3


These lines (BSL lines) are the input lines to the external decoder
Connect M0-M3 lines to CSL0-CSL3 lines
M lines are the o/p of decoder and CSL lines either enable or disable the
display unit (through the driver ICs).

Design Analysis/ Implementation Logic:

SAMPLE CODES :

73
MIL Manual

8x8-bit right entry decoded mode rolling display (max 4 characters)

A 0100 :0000

back : MOV AL,01


OUT 31,AL
MOV AL,90
OUT 31,AL
MOV CL,04
MOV AX,CS
MOV DS,AX
MOV BX,0030
Go : MOV AL,[BX]
OUT 30,AL
CALL 0040
INC BX
DEC CL
JNZ Go
JMP back
INT 3

A 0100 :0040

MOV SI,0A
L1 : MOV DI,DA00
L2 : DEC CX
JNZ L2
DEC BX
JNZ L1
RET

E 0100 :0030
0030 : 7 E
0031 : 4 6
0032 : E 6
0033 : E C

This will display ‘andy’ on the display.

16x8-bit right entry encoded mode rolling display (max 4 characters)

A 0100 :0000

back : MOV AL,18

74
MIL Manual

OUT 31,AL
MOV CL,10
MOV AX,CS
MOV DS,AX
MOV BX,0030
Go : MOV AL,[BX]
OUT 30,AL
CALL 0040
INC BX
DEC CL
JNZ Go
JMP back
INT 3

A 0100 :0040

MOV SI,0A
L1 : MOV DI,DA00
L2 : DEC CX
JNZ L2
DEC BX
JNZ L1
RET

E 0100 :0030
0030 : 7 E
0031 : 4 6
0032 : E 6
0033 : E C…….add 16 character codes.

This will display 16 characters on the display.

Testing:

Observe the display. Verify the left and right entry of the display characters.

Conclusion:

8279 successfully interfaced with 8086 system. The decoded and encoded modes for
displaying information are implemented.

75
MIL Manual

ASSIGNMENT No: 17

Title of Assignment: Write an ALP in 8086 to initialize 8279 in Keyboard mode.


i. Keyboard in Encoded scan 2 key Lockout mode.
ii. Keyboard in Encoded scan N key Rollover mode.
iii. Keyboard in Decoded scan 2 key Lockout mode.
iv. Keyboard in Decoded scan N key Rollover mode.
Draw the block diagram of 8279 & show the interfacing details with 8086

Relevant Theory:

Study Apparatus:
DYNA-86: (8086-SDK board)
DYNA-8279 study card

DYNA 86 Specifications:
Microprocessors: 8086, operating frequency: 8 MHz
64 KB ROM with monitor firmware (in two 27256—U30 and U32)
64 KB battery backed static RAM (in two 62256—U31 and U33)
Support chips: 8254, 8251, 8259, 8255, 8279, socket for 8087
Memory Map:

Socket Address Chips Capacity

U31/U33 00000H – 0FFFFH Battery backed SRAM 64 KB (32+32)

U30/U32 F0000H – FFFFFH Firmware EPROM 64 KB (32+32)

Important serial mode commands:

Display Memory D[W][[seg:]strt[,end]]


Edit Memory E[W][[seg:]strt]
Copy Memory C[seg:]strt,end,[seg:]dest
Fill Memory F[W][seg:]strt,end,byte/word

76
MIL Manual

Insert Byte/Word I[W][seg:]strt,end,byte/word


Delete Byte/Word DL[W][seg:]strt,end
Search Byte/Word S[W][seg:]strt,end,byte/word
Compare blocks CM[seg:]strt,end,[seg:]strt
Register R[reg]
Trace T[[seg:]strt]
Go G[[[seg:]strt],[[seg:]brk]]
Hex to Dec HDnum
Dec to Hex Dhnum
Load file L[seg:]
Write file W[seg:],strt,end
Input from port IN[W]addr
Output to port O[W]addr,[byte/word]
Assemble A[[seg:]off]
Unassemble U[[seg:]off[,[seg:]off]]

Whenever the system resets or during power-on , the monitor


immediately terminates its present activity and jumps to its
initialization routine. This routine initializes interrupt vectors 1 through
3 as follows :
Interrupt 1 - Single Step : Used with Single Step command
Interrupt B - IRQ3 : Monitors [ INT ] key
Interrupt 3 - Breakpoint : Used with the GO command .

8279 Study Card:


Default Addresses:

Control/Status port: 31h


Data Port : 30h

Block Diagram of 8279.

SYMBOL DESCRIPTION

77
MIL Manual

DB0-DB7 BI-DIRECTIONAL DATA BUS: All data and commands between the
CPU
and 8279 are transmitted on these lines.
RESET A high signal on this pin resets the 8279. After being reset the 8279 is
placed in 16 8-bit character display-left entry and Encoded scan
keyboard-2 key lockout. Along with this the program clock prescaler is
set to 31.
A0 A high on this line indicates the signals in or out are interpreted as a
command or status. A low indicates that they are data.
IRQ In a keyboard mode, the interrupt line is high when there is data in the
FIFO/Sensor RAM. The interrupt line goes low with each FIFO/Sensor
RAM read and returns high if there is still information in the RAM. In a
sensor mode, the interrupt line goes high whenever a change in a sensor is
detected.
SL0-SL3 Scan lines, which are used to scan the key switch or sensor matrix and
display digits. These lines can be either encoded (1 of 16) or decoded (1
of 4).
RL0-RL7 Return line inputs which are connected to the scan lines through the keys
or sensor switches. They have active internal pull-ups to keep them high
until a switch closure pulls one low. They also serve as 8-bit Input in
Strobed Input Mode.
SHIFT The shift input status is stored along with the key position on key closure
in the Scanned Keyboard modes.
CNTL/STB For keyboard mode this line is used as a control input and stored like
status on a key closure. The line is also the strobe line that enters the data
into the FIFO in the strobed input mode. (Rising Edge).
OUT A0-A3 These two ports are the outputs for the 16x4 display refresh registers. The
OUT B0-B3 data from these outputs is synchronized to the scan lines (SL0 – SL3) for
multiplexed digit displays. The two 4-bit ports may be blanked
independently and considered as one 8-bit port.
BD This output is used to blank the display during digit switching or by a
display blanking command.

The Intel 8279 is a general purpose Programmable Keyboard and Display I/O Interface
device designed for use with Intel Microprocessors.

The 8279 has two sections: keyboard and display. CPU is relieved from scanning the
keyboard or refreshing the display.
3) The Keyboard portion can provide a scanned interface to a 64-contact key
matrix.
The keyboard section will also interface to regular typewriter style keyboards
or random toggle or thumb switches, array of Sensors or Strobed Interface
Keyboards.
Key depressions can be 2-key lockout or N-key rollover.
Keyboard entries are debounced and strobed in an 8-char FIFO.

78
MIL Manual

4) The display portion provides a scanned display interface for LED,


incandescent and other popular display technologies. Both numeric and
alphanumeric segment displays may be used.
The display section drives alphanumeric displays or a bank of indicator lights.
Thus the
CPU is relieved from scanning the keyboard or refreshing the display.
(Advantages over
8255).
The 8279 has 16x8 Display RAM, which can be organized into dual 16x4.
The RAM
can be loaded or interrogated by CPU. Both right entry, calculator and left
entry
typewriter display formats are possible. Both read and write of the display
RAM can be
done with auto-increment of the display RAM address.

Input Modes
1. Scanned Keyboard-with encoded (8 x 8 key keyboard) or decoded (4 x 8 key
keyboard) scan lines. A key depression generates a 6-bit encoding of key position.
Position and shift and control status are stored in the FIFO.
2. Scanned Sensor Matrix-with encoded (8 x 8 matrix switches) or decoded (4 x 8
matrix switches) scan lines. Key status (open or closed) stored in RAM addressable by
CPU.
3. Strobed Input-Data on return lines during control line strobe is transferred to FIFO.

Output Modes
1. 8 or 16 character-multiplexed displays that can be organized as dual 4-bit or single 8
bit
2. Right entry or left entry display formats.

Scan Counter: The scan counter has two modes. In the encoded mode, the counter
provides a binary count that must be externally decoded to provide the scan lines for the
keyboard and display. In the decoded mode, the scan counter decodes the least significant
2 bits and provides a decoded 1 of 4 scan.
In the Encoded mode, the scan lines are active high outputs.
In the Decoded mode, the scan lines are active low outputs.

Return Buffers and Keyboard Debounce and Control


1. In the keyboard mode, these lines are scanned, looking for key closures in that row. If
the debounce circuit detects a closed switch, it waits about 10 ms to check if the switch
remains closed. If it does, the address of the switch in the matrix plus the status of SHIFT
and CONTROL are transferred to the FIFO.

79
MIL Manual

2. In the scanned Sensor Matrix modes, the contents of the return lines are directly
transferred to the corresponding row of the Sensor RAM (FIFO) each key scan time.
3. In Strobed input mode, the contents of the return lines are transferred to the FIFO on
the rising edge of the CNTL/STB line pulse.

Display Address Registers and Display RAM


The Display Address Register hold the address of the word currently being
written/read by the CPU and two 4-bit nibbles being displayed. They also can be set to
auto increment after each read or write. The CPU can directly read the Display RAM
after the correct mode and address is set.

FIFO / Sensor RAM and Status


This block is a dual function 8x8 RAM. In Keyboard/ Strobed Input Mode, it is a
FIFO. FIFO Status keeps track of the no. of characters in the FIFO and whether it is full
or empty.
The status logic also provides IRQ signal when the FIFO is not empty.

Commands used in 8279?

The following commands program the 8279 operating modes. The commands are
sent on the Data Bus with CS low and A0 is high and are loaded to the 8279 on the rising
edge of WR.

80
MIL Manual

Data Display in 8279?

Left Entry : Left Entry mode is the simplest display format in that each display position
directly corresponds to a byte (or nibble) in the Display RAM. Address 0 in the RAM is
the left-most display character and address 15 (or address 7 In 8 character display) is the
right most display character.

Right Entry : Right entry is the method used by most electronic calculators. The first
entry is placed in the right most display character. The next entry is also placed in the
right most character after the display is shifted left one character.

81
MIL Manual

FIFO Status Register ?

FlFO status is used in the Keyboard and Strobed Input modes to indicate the number of
characters in the FIFO and to indicate whether an error has occurred. There are two types
of errors possible: overrun and under run. Overrun occurs when the entry of another
character into a full FlFO is attempted. Under run occurs when the CPU tries to read an
empty FIFO. The FlFO status word also has a bit to indicate that the Display RAM was
unavailable because a Clear Display or Clear All command had not completed its
clearing operation. In Special Error Mode the S/E bit is showing the error flag and serves
as an indication to whether a simultaneous multiple closure error has occurred.

DU S/E O U F N N N

NNN  Indicates number of characters in FIFO.


F  FIFO Full
U  Under run error
O  Error Over run
S/E  Sensor Closure / Error Flag multiple closures
DU  Display Unavailable.

8279 Study Card Display connections :

(iii) For decoded mode :

Connect SL0-SL3 lines to CSL0-CSL3

(iv) For encoded mode :

Connect SL0-SL3 lines to BSL0-BSL3


These lines (BSL lines) are the input lines to the external decoder
Connect M0-M3 lines to CSL0-CSL3 lines
M lines are the o/p of decoder and CSL lines either enable or disable the
display unit (through the driver ICs).

Design Analysis/ Implementation Logic:

SAMPLE CODES :

82
MIL Manual

Encoded 2-key lockout K/B mode :

A 0100 :0000

MOV AL,00
OUT 31,AL
GO : IN AL,31
AND AL,07
JZ GO
IN AL,30
INT 3

The execution will come out of loop only after the key press. Depending on which
key is pressed (C0,C1,C8,C9), corresponding code will be stored in AL, which
can be checked using R command.

Encoded N-key rollover lockout K/B mode :

A 0100 :0000

MOV AL,02
OUT 31,AL
GO : IN AL,31
AND AL,07
JZ GO
IN AL,30
INT 3

Decoded 2-key lockout K/B mode :

A 0100 :0000

MOV AL,01
OUT 31,AL
GO : IN AL,31
AND AL,07
JZ GO
IN AL,30
INT 3

Decoded N-key rollover K/B mode :

A 0100 :0000

83
MIL Manual

MOV AL,03
OUT 31,AL
GO : IN AL,31
AND AL,07
JZ GO
IN AL,30
INT 3

Use encoded 2-key lockout mode to accept a key-stature and display the same
using decoded 8*8-bit right entry rolling display.

A 0100 :0000

MOV AL,00
OUT 31,AL
GO : IN AL,31
AND AL,07
JZ GO
IN AL,30
MOV BL,AL
MOV AL,01
OUT 31,AL
MOV AL,90
OUT 31,AL
MOV AL,BL
OUT 30,AL
INT 3

CONNECTIONS : Since the K/B i/p is encoded i/p connect K0-K1 to L0-L1, and
since display is decoded connect SL3 to CSL3 (right entry !!).

Testing:

Observe the contents of registers to check which key is pressed. Verify the N-key
rollover as well as 2-key lockout options for both encoded as well as decoded modes.

Conclusion:

8279 successfully interfaced with 8086 system. The decoded and encoded modes for
using 2-key rollover as well as N-key lockout key sensing are tested.

84
MIL Manual

ASSIGNMENT No: 18

Title of Assignment: Write an ALP in 8086 to interface DAC & generate the following
waveforms on oscilloscope
• Square wave
• Sine wave
• Ramp wave
• Triangular wave

Relevant Theory:

Study Apparatus:
DYNA-86: (8086-SDK board)
DYNA-DAC study card

DYNA 86 Specifications:
Microprocessors: 8086, operating frequency: 8 MHz
64 KB ROM with monitor firmware (in two 27256—U30 and U32)
64 KB battery backed static RAM (in two 62256—U31 and U33)
Support chips: 8254, 8251, 8259, 8255, 8279, socket for 8087
Memory Map:

Socket Address Chips Capacity

U31/U33 00000H – 0FFFFH Battery backed SRAM 64 KB (32+32)

U30/U32 F0000H – FFFFFH Firmware EPROM 64 KB (32+32)

Important serial mode commands:

Display Memory D[W][[seg:]strt[,end]]


Edit Memory E[W][[seg:]strt]
Copy Memory C[seg:]strt,end,[seg:]dest

85
MIL Manual

Fill Memory F[W][seg:]strt,end,byte/word


Insert Byte/Word I[W][seg:]strt,end,byte/word
Delete Byte/Word DL[W][seg:]strt,end
Search Byte/Word S[W][seg:]strt,end,byte/word
Compare blocks CM[seg:]strt,end,[seg:]strt
Register R[reg]
Trace T[[seg:]strt]
Go G[[[seg:]strt],[[seg:]brk]]
Hex to Dec HDnum
Dec to Hex Dhnum
Load file L[seg:]
Write file W[seg:],strt,end
Input from port IN[W]addr
Output to port O[W]addr,[byte/word]
Assemble A[[seg:]off]
Unassemble U[[seg:]off[,[seg:]off]]

Whenever the system resets or during power-on , the monitor


immediately terminates its present activity and jumps to its
initialization routine. This routine initializes interrupt vectors 1 through
3 as follows :

Interrupt 1 - Single Step : Used with Single Step command


Interrupt B - IRQ3 : Monitors [ INT ] key
Interrupt 3 - Breakpoint : Used with the GO command .

Two 8255 chips are interfaced as 16 bit I/O.

8255 (#1) is reserved for printer interface. Hence for interfacing DAC, 8255 (#2) is used.

It has following port addresses:


Port A: 61h
Port B: 63h
Port C: 65h
CWR: 67h

DAC study card:

The DAC-01 Digital to Analog Converter card interfaces with the any of the Dynalog's
Microprocessor kit. It is used to implement analog and digital signal processing and real
time process control applications.

The DAC-01A is designed around DAC-0800 monolithic 8 bit high speed current output
digital to analog converter featuring 100 nsecs settling time (typical). DAC-01A has
adjustable voltage reference which permits full scale voltage. The Vref to full scale
current matching of better than ± 1 LSB gives ± LSB full scale error.

Precision Opamp based current to voltage converter has 20 mA output load driving
capacity. Analog input is polarity protected and buffered and has 10 ohms input

86
MIL Manual

impedance. Analog comparator has medium switching speeds (in milliseconds) and its
output is converted to TTL level and latched to avoid oscillating comparator status
reading which occures when two analog inputs of the comparator are nearly equal.
The PCB track design is sheilded to keep low noise level in the analog paths and this card
gives stable readings of the analog input. The DAC-01A card is also protected for reverse
supply polarity.

BLOCK DIAGRAM

PA0- PA0-
PA7 PA7 Analog O/p
D to A
DATA PA0- Converter
26 PIN LATCH PA7 DAC 0800
FRC

CRO

PB0 enable/disable latch

Port A and B of 8255 are designed as o/p ports and port C is designed as i/p port. The 8-
bit data i/p for DAC 0800 is written into the port A output register by the CPU. The data
is latched into LS373 by applying a soft ware generated positive going latching pulse
through bit PB0 of port B.

Design Analysis/ Implementation Logic:

Sample Codes:

(i) Ramp Wave

MOV AL,89
OUT 67,AL
MOV AL,01
OUT 63,AL
MOV AL,00
GO:OUT 61,AL
INC AL
JMP GO

87
MIL Manual

INT 3

(ii) Triangular Wave

MOV AL,89
OUT 67,AL
MOV AL,01
OUT 63,AL
BACK:MOV AL,00
GO:OUT 61,AL
INC AL
CMP AL,FF
JNE GO
G1:DEC AL
OUT 61,AL
CMP AL,00
JNZ G1
JMP BACK
INT 3

(iii) Square Wave

MOV AL,89
OUT 67,AL
MOV AL,01
OUT 63,AL
BACK:MOV AL,00
OUT 61,AL
CALL 0040
MOV AL,FF
OUT 61,AL
CALL 0040
JMP BACK
INT 3

Delay Routine:

MOV BX,000A
G1:MOV CX,0020
G2:DEC CX
JNZ GO
DEC BX
JNZ G1
RET

88
MIL Manual

(iv) Stair Case:

MOV AL,89
OUT 67,AL
MOV AL,01
OUT 63,AL
BACK:MOV AL,00
GO:OUT 61,AL
ADD AL,10
CALL 0040
CMP AL,F0
JNE GO
G1:SUB AL,10
OUT 61,AL
CALL 0040
CMP AL,10
JNE G1
JMP BACK
INT 3

Delay Routine:

MOV BX,000A
G1:MOV CX,0020
G2:DEC CX
JNZ GO
DEC BX
JNZ G1
RET

Testing:
Observe various waveforms on the C.R.O. and correlate the delays observed
on the C.R.O. screen with the delay routines evaluated for the given clock
speed.

Conclusion:

DAC study kit is successfully interfaced with 8086 system and various waveforms are
generated , which are observed on the C.R.O.

89
MIL Manual

ASSIGNMENT No: 19

Title of Assignment: Write a TSR Program to implement Real Time Clock (RTC). Read
the Real time from CMOS chip by suitable INT & display the RTC at the top right corner
on the screen. Access the video RAM directly in your routine

Relevant Theory:

Difference between .EXE and .COM Files

No .EXE program .COM program


1 These programs can have multiple Max only one segment is present. Data
code, data and stack segments. ,code and stack reside in one segment.
2 .EXE programs can be as large as .COM program can have maximum size
available memory. of 64KB.
(Actual Size is 64KB - Size of PSP – 2
Bytes for stack)
3 .EXE programs fit in the small, .COM programs fit in the tiny model, in
medium or large model. which all segment registers contain the
same value.
4 NEAR and FAR calls can be used. Only NEAR calls.
5 Due to the file header .EXE programs File header is not present in .COM
is larger than corresponding .COM programs hence it always compact than
program .EXE.
6 The entry point of .EXE program will The entry point of .COM program is
never be fixed and varies according to 0100H (the length of PSP) which is
the file header size. always fixed.
7 .EXE files contains unique header, a The .COM files are compact and are
relocation map and other information loaded slightly faster then equivalent
used by DOS along with the execution .EXE file since these contain only the
code. execution code.

Method: .COM files are created

To convert .COM program it is necessary to create .EXE program

Step 1) To create .EXE, .ASM program is first assembled using macro assembler to
produce .OBJ program.
Step 2) The object program is linked with the help of linker to produce .EXE program.
Step 3) A Program named EXE2BIN converts .EXE programs to .COM. EXE2BIN
specifies that convert exe to binary format (.COM). Since the operand of the command
always references an .EXE file, it is not necessary to write .EXE extension. The second
operand could be a name of .COM file. If we omit the extension EXE2BIN assumes BIN
which we want to rename as .COM in order to execute the program.

90
MIL Manual

For MASM Assembler :


C:\masm61\bin\>MASM sample.asm
C:\masm61\bin\>LINK sample.obj
C:\masm61\bin\>EXE2BIN sample sample.com

For TASM Assembler


C:\TASM> TASM sample.asm
C:\TASM> TLINK sample.obj
C:\TASM> EXE2BIN sample sample.com or
C:\TASM> TLINK /T sample

The conditions for .COM Files.


1. It must be less than 64KB in length (tiny model)
2. It cannot contain more then one segment
3. It must have an origin at 0100H. (ORG 100H statement must be present)

EXEC Function
The DOS EXEC function (INT 21H Function 4BH) allows to load .COM and
.EXE programs from disk files, execute it and then regain control when the program is
finished. It also allows a program (called the parent) to load any other program (called the
child) from disk, execute it and then regain control when the child program is finished.

Step 1) Creates special data structure called a program segment prefix (PSP) in the
transient program memory (TPA).
Step 2) EXEC function loads the program, just before the PSP and performs any
relocation if required in case of .EXE only.
Step 3) It then sets up the segment registers and stack and transfers the control to the
program.

For .EXE programs the EXEC function may also do some additional processing like
passing parameters from parent to child through the environmental block. This block
holds certain information used by the system's command interpreter (usually
COMMAND.COM) and may also hold information to be used by transient programs
(.COM and .EXE).

PSP:
The PSP contains various linkages and pointers needed by the application
programs. It is a special data structure of 256 bytes. This structure is loaded by DOS
before the transient program is loaded. It occupies the base of the memory block
allocated to a transient program.

What is FCB:
FCB block is a special data structure used to access a file and contains FCB
functions which allow the programmer to create, open, close and delete files and to read
or write records of any size at any record position within such files.

91
MIL Manual

TSR:
Programs which remain running and resident in memory while other programs are
running are known as a "Terminate and Stay Resident" or "TSR" program. Example:
Doskey, background printing or popping off a calculator on a screen etc. Thus TSR is an
ordinary program which terminates not through the usual DOS terminate function, but
through the DOS "keep" function - interrupt 27H. This function reserves an area of
memory, used by the program so that no other programs will overwrite it. The terminate-
and-stay-resident function (Function 31H) is one of the MS-DOS services invoked
through Interrupt 21H.
Structure of a TSR:
TSR’s consist of two distinct parts that execute at different times. The first part is
the installation section, which executes only once, when MS-DOS loads the program.
The installation code performs any initialization tasks required by the TSR and then exits
through the terminate-and-stay-resident function.

The second part of the TSR, called the resident section, consists of code and data
left in memory after termination. The TSR’s resident code must be able to regain control
of the processor and execute after the program has terminated.

Types of TSR:
The simplest way to execute a TSR is to transfer control to it explicitly from
another program. Because the TSR in this case does not solicit processor control, it is
said to be passive. If the calling program can determine the TSR’s memory address, it can
grant control via a far jump or call. More commonly, a program activates a passive TSR
through a software interrupt. The installation section of the TSR writes the address of its
resident code to the proper position in the interrupt vector table. Any subsequent
program can then execute the TSR by calling the interrupt.

The second method of executing a TSR involves signaling it through some


hardware event, such as a predetermined sequence of keystrokes. This type of TSR is
“active” because it must continually search for its startup signal. The advantage of active
TSR lies in their accessibility. They can take control from any running application,
execute, and return, all on demand.
An active TSR, however, must not seize processor control blindly. It must contain
additional code that determines the proper moment at which to execute. The extra code
consists of one or more routines called “interrupt handlers,”.

CMOS RTC:
CMOS is always present on Motherboard is of 64 bytes long. (MC146818) which stores
date and time. There are total 64 registers are present. There are also two ports which are
used 70H and 71H . 70H is write CMOS address port and 71H is data port which is used
to read or set data. In order to read seconds our code will looks like this :

MOV AL,02 ;02 transmitted to 70H to read seconds from 71H, 04 for min,06 for
hrs.
OUT 70H,AL

92
MIL Manual

IN AL, 71H ;returns seconds in AL registers.

Example: Screen Saver


While implementing Screen saver, 08 and 09 Interrupts are used. INT 08H is timer
interrupt and INT 09H is KB interrupt. INT 08H is generated after every 55 ms and thus
in 1 second, 08H interrupt get generated for 18.2 times. INT 09H is generated after every
press or release of a key.

When the machine is idle for specified time duration, screen saver pops up which could
be a blank screen or some data or picture displayed on screen. When the key is pressed,
original data get displayed on the screen by removing screen saver.

Design Analysis/ Implementation Logic:

Algorithm:

1. ISR for INT 08H


1. Decrement the counter by 1 every time until it reaches zero. Also check the count
value. For non zero value - go to the end and for zero value - proceed.
2. Save entire screen contents into buffer (4000 Bytes)
3. Send any specific character (Blank space) over the entire screen (4000 Bytes)
3. Set the flag for indication that screen saver is on.

2. ISR for INT 09H


1. Check the flag status whether the screen saver is on. If yes – proceed else set the
counter value to its original value and go to the end.
2. Entire buffer contents are transferred on to the screen
3. Reset the flag used for indication of screen saver.
4. Also set the counter value to its original value. Counter value is decided as (Idle time
for screensaver / 55 ms ). For example, 5 second idle time, counter values is closer to
100.

Testing:

The RTC gets displayed on the screen and gets continuously updated.

Conclusion:

TSR for RTC is successfully implemented.

93
MIL Manual

ASSIGNMENT No: 20

Title of Assignment: Write a TSR Program to Activate a Beep Sound when any key is
pressed

Relevant Theory:

Through its memory-management system, MS-DOS allows a program to remain resident


in memory after terminating. The resident program can later regain control of the
processor to perform tasks such as background printing or “popping up” a calculator on
the screen. Such a program is commonly called a TSR, from the terminate-and-stay-
resident function it uses to return to MS-DOS.
This chapter explains the techniques of writing memory-resident software. The first two
sections present introductory material. Following sections describe important MS-DOS
and BIOS interrupts and focus on how to write safe, compatible, memory-resident
software. Two example programs illustrate the techniques described in the chapter. The
MASM 6.1 disks contain complete source code for the two example TSR programs.

Terminate-and-Stay-Resident Programs
MS-DOS maintains a pointer to the beginning of unused memory. Programs load into
memory at this position and terminate execution by returning control to MS-DOS.
Normally, the pointer remains unchanged, allowing MS-DOS to reuse the same memory
when loading other programs.
A terminating program can, however, prevent other programs from loading on top of it.
These programs exit to MS-DOS through the terminate-and-stay-resident function, which
resets the free-memory pointer to a higher position. This leaves the program resident in a
protected block of memory, even though it is no longer running.
The terminate-and-stay-resident function (Function 31h) is one of the MS-DOS services
invoked through Interrupt 21h. The following fragment shows how a TSR program
terminates through Function 31h and remains resident in a 1000h-byte block of memory:
mov ah, 31h ; Request DOS Function 31h
mov al, err ; Set return code
mov dx, 100h ; Reserve 100h paragraphs
; (1000h bytes)
int 21h ; Terminate-and-stay-resident

Note In current versions of MS-DOS, Interrupt 27h also provides a terminate-and-stay-


resident service. However, Microsoft cannot guarantee future support for Interrupt 27h
and does not recommend its use.

94
MIL Manual

Structure of a TSR
TSRs consist of two distinct parts that execute at different times. The first part is the
installation section, which executes only once, when MS-DOS loads the program. The
installation code performs any initialization tasks required by the TSR and then exits
through the terminate-and-stay-resident function.
The second part of the TSR, called the resident section, consists of code and data left in
memory after termination. Though often identified with the TSR itself, the resident
section makes up only part of the entire program.
The TSR’s resident code must be able to regain control of the processor and execute after
the program has terminated. Methods of executing a TSR are classified as either passive
or active.

Passive TSRs
The simplest way to execute a TSR is to transfer control to it explicitly from another
program. Because the TSR in this case does not solicit processor control, it is said to be
passive. If the calling program can determine the TSR’s memory address, it can grant
control via a far jump or call. More commonly, a program activates a passive TSR
through a software interrupt. The installation section of the TSR writes the address of its
resident code to the proper position in the interrupt vector table (see “MS-DOS
Interrupts” in Chapter 7). Any subsequent program can then execute the TSR by calling
the interrupt.
Passive TSRs often replace existing software interrupts. For example, a passive TSR
might replace Interrupt 10h, the BIOS video service. By intercepting calls that read or
write to the screen, the TSR can access the video buffer directly, increasing display
speed.
Passive TSRs allow limited access since they can be invoked only from another program.
They have the advantage of executing within the context of the calling program, and thus
run no risk of interfering with another process. Such a risk does exist with active TSRs.

Active TSRs
The second method of executing a TSR involves signaling it through some hardware
event, such as a predetermined sequence of keystrokes. This type of TSR is “active”
because it must continually search for its startup signal. The advantage of active TSRs
lies in their accessibility. They can take control from any running application, execute,
and return, all on demand.
An active TSR, however, must not seize processor control blindly. It must contain
additional code that determines the proper moment at which to execute. The extra code
consists of one or more routines called “interrupt handlers,” described in the following
section.

95
MIL Manual

Interrupt Handlers in Active TSRs


The memory-resident portion of an active TSR consists of two parts. One part contains
the body of the TSR — the code and data that perform the program’s main tasks. The
other part contains the TSR’s interrupt handlers.
An interrupt handler is a routine that takes control when a specific interrupt occurs.
Although sometimes called an “interrupt service routine,” a TSR’s handler usually does
not service the interrupt. Instead, it passes control to the original interrupt routine, which
does the actual interrupt servicing. (See the section “Replacing an Interrupt Routine” in
Chapter 7 for information on how to write an interrupt handler.)
Collectively, interrupt handlers ensure that a TSR operates compatibly with the rest of the
system. Individually, each handler fulfills one or more of the following functions:
Auditing hardware events that may signal a request for the TSR
Monitoring system status
Determining whether a request for the TSR should be honored, based on current system
status

Auditing Hardware Events for TSR Requests


Active TSRs commonly use a special keystroke sequence or the timer as a request signal.
A TSR invoked through one of these channels must be equipped with handlers that audit
keyboard or timer events.
A keyboard handler receives control at every keystroke. It examines each key, searching
for the proper signal or “hot key.” Generally, a keyboard handler should not attempt to
call the TSR directly when it detects the hot key. If the TSR cannot safely interrupt the
current process at that moment, the keyboard handler is forced to exit to allow the process
to continue. Since the handler cannot regain control until the next keystroke, the user has
to press the hot key repeatedly until the handler can comply with the request.
Instead, the handler should merely set a request flag when it detects a hot-key signal and
then exit normally. Examples in the following paragraphs illustrate this technique.

Design Analysis/ Implementation Logic:

Algorithm:

Keybrd PROC FAR


sti ; Interrupts are okay
push ax ; Save AX register
in al, 60h ; AL = key scan code
call CheckHotKey ; Check for hot key
.IF carry? ; If hot key pressed,
mov cs:TsrRequestFlag, TRUE ; raise flag and
. ; set up for exit

96
MIL Manual

Testing:

A beep sound should be heard whenever a key is pressed.

Conclusion:

TSR to activate a beep sound on a key press in successfully implemented.

97

You might also like