Sie sind auf Seite 1von 563

Microprocessors

and Interfacing

A. P. Godse
D. A. Godse

Technical Publications rune ~


Strictly According to the Revised Syllabus of
JNTU 2005 Course
Microprocessors
& Interfacing
{ECIUH{ niN IW,B. Ttd.,-H(ECE!f.Ja. I c -! Eia. lr T"-'iall.tl/1/dldb/J
niN IW, B. Ttd.,- . f (lMinl. .I c....Q

Atul P. Godse
M. S. Software Systems (BITS Pian)
B.E. Industrial Electrooics
Fonnerty Leduret., Oepot1ment of Electronics E119g.
Vlshwakarma Institute of Technology
Pune

Mrs. Deepall A. Godse


B.E.Indus:rial Electrorics, M. E. (Compule<)
Asa.istant Professor in Bharati Vidyapeeih's
Women's College of Englneeri119
Puno

Price Rs. 285/-

Visit us at : www.vtubooks.com

~@
6
Thchnical Publications Pune

T hJ.e One
(1)
Syllabus (Microprocessors & Interfacing)
Unit-1 (Chapter-1, 21
An ovetview of 8085, Architecture of 8086, Microprocessor. Spec:la! fUflctlons of general purpose
registers, 8086 flag register and func6on of 8086 flags.

UNJT-11 (Chapter-31
Addressing modes of 8086, Instruction sel of 8086, Assembter directives simple programs.
Procedures. and Macros.

UNIT-Ill (Chapter-41
Assatnbly language progtall'l$ Involving logical, Branch and catl ln:structions, Sortfng, Evatuatlon
of arittwnetic expressions., String manipulation.

UNIT-IV (Chapter-s, 6)
Pin di&9f&rri of 8086 Minlmum mode and maximum mode of operation, Timing diagram, Memory
4

interfacing tQ 8086 (Static RAM and EPROM). Need for OMA, OMA data lransfef method, lnterfac:ing
with 8237/8257.

UNIT-V <Chapter-?)
8255 PPI-Various mOde-s of operation and interfacing to 8086. Interfacing keyboard, Displays,
Stepper motor and &etuatOfS. OIA and AID converter interfacing.

UNIT-VI (Chapter-s, 9)
Interrupt structure of 8086, Vector interrupt table , Interrupt service routines. IntroduCtiOn to DOS
and BIOS Interrupts, 8259 PIC archttectute and interfacing cascading of Interrupt oontroller and its
importance.

UNIT-VII (Chapter-10)
Serial data transfer schemes. Asynchronous and synchronous data transfer sdlemes. 8251
USART architecture and interfacing, TTL to RS 232C and RS232C to TTL oonvSion, Sample
program of serial data transfer, Introduction to High...s,peed serial oommunicetions standilrds. USB.

UNIT-VIII (Chapter-H)
8051 Mk:rocontrOIIef ai'Chit&eturo. Regist&f set or 8051, Modes of dmet operation, Serial port
operation, Interrupt structure of 8051 , Memory arxl 1/0 interfacing 8051.

{2)

Copyrighted material
Table of Contents :
Chapter 1 : An Overview of 8085 {11)to{166)
Chapter 2 : Arohttecture of 8086 Microprocessor {21)to{2 14)
Chal)ter 3 : 8086 Instruction Set and Assembly Language Programming {31)to{3-110)
Chapter 4 : Assembly Language Programs {41)to{4 -74)
Chapter 5 : 8086 System Coofiguration {51) to (534)
Chapter 6: D!recl Memory Access {DMA) 823718257 {6 1) 10 (6 28)
Chapter 7 : 8255 PPI {Programmable Periplleral lnterface) {1 1) to (7 64)
Chapter 8: 80861nterrupts {81) to (8 28)
Chapter 9 : lntroduclion to DOS and BIOS Interrupts {9 1) to (9 30)
Chapter 10: Serial Communication {10 1) to (10 38)
Chapter 11 : 8051 Microconlroller {1 1 1) to (11 38)
Appendix A (A1)to(A6)
Appendix B (B 1) to {B 10)
Appendix C {C 1)to{C 8)
Chapte!Wise University Questions with Answers {P1)to{P 34)

.... ... ...... ... .......................................................................................................


.: Features of Book

:
,,.. 8085. 8086/88 Architecture. programming and interfacing.
,,.. Free download 8086 programs on www.vtubooks.com.
8051 Microcontroller architecture.
Large number of programming examples.
Programs using modular programming approach.
Practical interfacing design examples.
.....................................................................................................................................

(3)

Copyrighted material
Microprocessors
& Interfacing

Atul P. Godse
M. S. Softw311! Systems (BfTS Pilaro)
B.E. lrduSirial Electrorics
Formerty Lecturer ln Occ:>artment of Elcctrorics Engg.
Vlshwakarrna Institute of Technology
Pune

Mrs. Deepali A. Godse


B.E. lnduslrial Electronics, M. E. (Compute<)
Assistant Professor in 81\arati Vtdyapeeth's
Women's College of Engineering
Pune

Visit us at : www.vtubooks.com

e
~ 6
_'Jechnical Publications Pune

Copyrighted material
Microprocessors & Interfacing
ISBN 9788184311259
All rights res.rved wi*' Technicot Pvblicotions. No pot1 of this bool: ahould be
reproduced In ony form, Eledroni(, Mechonicol, Pholoc::opr or ony inbmolion storage ond
retrieYol system without prior permission In writing. from Techricof Public:otionJ, Pune.

Publisl..d by :
1tthnlcaii'\Jbllcallons 1'\Jne
" ..... L.ldoo<v. -IW>. 1\.w- ... 030, ......

___
1'11nters :
Ylkr..... l'rlnterS
34.---e..
Puno <11008.

. , ., -. . ;; "." ~ . - .. . . . -~" _. -

Copyrighted material
Preface
Thanks to professors, students and authors of various technical books
for their overwhelming response to our books. Looking at the feedback and
the response we received from previous books, We are very pleased to
release a text book on Microprocessors and its Applications.

The purpose of this book is to fulfil a need for text stating in plain, lucid
and simple everyday language. This book provides a logical method for
explaining and it prepares a background of the topic with essential
tnustrations. This text is provided with number of solved design examples
which helps students to understand the application of microprocessor and
microcontroller based systems.

The rapid spread of microprocessors in society has both simplified and


complicated our lives. To get the conceptua.l view of the microprocessors, it
is better to study them from the popular family ii.ke Intel. So we felt it is
necessary to introduce a book which covers microprocessors and
microcontrotler with their features, internal architecture, intemaJ organization
and design details.

This text begins with the architecture of 8085 microprocessor. It explains


all the details of 8085 microprocessor such as its architecture, pin
description instruction set, memory and 1/0 intedacing and interrupts. The
text then introduces a 16-bit microprocessor 8086. It also eJCPtains the
details of 8086 like 8085. The text also explains various peripherals and
their interfacing wi)h microprocessors.

Finally, the text explains the 8051 microrontroller.


Acknowledgement
We wish to express our profound thanks to all those who helped In
making this book a reality. Much needed moral support and encouragement
is provided on numerous occasions by our whole family.

We are spedally grateful to the great teacher Prof. A.V. Bakshi for h1s
time to time, much needed, valuable guidance. Without the full support and
cheerful encouragement of Mr. Uday Bakshi the book would not have
been completed In time.

Finally. we wish to thank Mr. Avinash Wani, Mr. Ravindra Wani and
the entire team of Technical Publications who have taken immense pain to
get the quality printing In time.

Any suggestions for the improvement of the book will be acknowledged


and appreciated.

Authors
Atul Godse
Deepali Godse

Dediclled 1o Neba & Ruturaj

- - - - -~ - L r ~ ._- - - -

Table of Contents
1.1 8085 Microprocessor ............................................................................1 - 1
1.2 Architecture of 8085 .., ...., .... , , , , , .. , , , , .. , .. , , , , , , , , , , ......, .. , , , , 1 - 2
1.2. 1Regjster Struci!Jre ... . . . . .. . . . . ... . . . . . . .. .. .. . . 1 3
1.2.2 AriUvnetic Logic U n~ (ALU) . ... . .. . . . . . . . . . .. . . . . .. . . . .. . . . .. . . .... . . . . . . 1 6
1 2 3 lnstructjon Derater 1 6
1.2 4 Address Buffer I I I I
. 1. 6
1 2 5 Addre,cwData Buffer 1 7
1 2 6 tnaementerttlecremeoter Address Latch 1 7
1.2.7 lnlemJpl Conlrol... . . . .. . . . . . . . . . .. . . . . . . . .... . . . .. . .... . .. . . .. . . . . .. . . .. 1 - 7
1.2.8 Serial vo Control " " .. " .. . " " . . . . . . . . ..... " " " " " " " . " . " " " . . 1 7
1.2.9 Tiering and Conlrol Cirt>Jilry . . . . . . .. ... . . . . . .. . . . .... . .. . . . .. . .. . . . .. . . . . .. 1 - 7
1.3 Pin Definitions of 8085 , , ....,, .., ........,,,, .........., ......, ..........,,, ......1 - 8
1.3.1Power S'4J!)!y and Frequency Signals.......... . ... ... .. . . . . ... . .. . ...... . . . . 1 9
1 3 2 Data Bus and Addre:ss: Bus , , , 1- 9
1.3.3 Conlrol and Status Signals . . . .. . . . . . . . . . .. ... . ... . .... . .. . . . .. . .. . . . . . . .. . 1 9
1.3.4 Interrupt Signals . . .. . . . . . . ... . . . . . . . . .. . . . . .. . . ...... . ...... . .. . . . . . .. . 1 -10
1.3.5 Serial I/O Signals . . . . . . . . .. . . . . . . . . ... . ... . .... . . . ..... . . . .. . .. . . . . .. . . . 1 10
1.3.6 OMA Signal . . . . . .. . . . . .... . . . . . . . . ...... . .... . . .. . . .. . . .. . .. . . . . .. . . . . 1 10
1.3.7 Rese1 Signals . . . . . . . . ... . . . . . . .. ......... . .. . . .. . . . .. . . 11 0
1.4 Bus Organisation ................................................................................ 1 -10
1 4 1 Clock Cjrcujts I I , .. , , , 1 11
1.4.2 Oemultiplexing AD, AD, . . . . . . . . . . . . . . . . . . . . . . .. . . .. . .. . . . . . . . .. . . . . . . 1 - 12
1 4 3 Rese! Cjo;ujt , , , , , , " :z 1 - 12
1.4.4 Generation of CoQtrol Signals . .... . . ... . . . . .. . . . . . . . . . 1 - 14
1.4.5 Bus Drivers .. . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . .. . .. . . .. . . . . . .. . . . . . 1 15
1.4.6 Typical Configuration.......... . ..... . . . . .. .. . . . . .. . . .. . . . . . . .. . .. ... . . .. 1 17
1.5 Timing and Control ............................................................................. 1 - 18
1.5.1 8085 Machine Cydes and their Tmings . . . . . . .... . . .. .... . .. . ... . ... . .. . ... . 1 - 24
1.5.2 Conceot of Wait Slates . ,. . . ,. . ,. ,. ,. ,. .. . .. . . . .. .... ....... . .. . ,. .... . 1- 35
1.6 Instruction Set of 8085 .. , , , , ......, ......, , , , ...., ... , .. .. , .., . . . 1 - 37
1.6.1 Data Transfer Group . . . . . .... . . . . . . . .". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 37
1.6.2 Arithmetic Group . .. . ........ . . . . . . ...... . . . .. . . .. . .. . . ...... ...... 1 39
1.6.3 Branch Group ..... . . . . . . . .. . . . . . ... . .... . . . .. . . . .. . ... . . .. . . .... . , .. . 1 - 45
1.6.4Logic Group . . .. . . . .. . . . . . . . .. . . . . . . . . . .. . . . . .. . .. . . . .. . . .. . . . .. . .... . . 1 - 48
1.6.5 Slack Operations . . . .. .... . . . . . . . .. . ........ . . .. . ... . ..... . .... 1 - 52
1.6.6 Machine Coolrlll Group .. . . . . . . ... . . ..... .. . . . .... ... . .. . . . ... .. . . . . . .. . . 1 - 54
1.7 80851nterrupt Structure and Operation ..............................................1- 55
1.7.1 Types ollnterrupts... . .. . . . . . .... . .......... . . . . . . . . .... . . .. . . ... . ...... 1 - 55
1.7.2 Overall Interrupt StnxUe . . .... ... .. . ... .. .. . . . . . . . ... . ... . .. . .... . ...... 1 - 56
1.72.1 - lnl!!!!!ps in 8085. 1 56
1.722 Sollware lnlemJpts In 8085 1 60
1.7.3 Masb!g I UnrnasU!g ol lr!ten!!J!s . ... . ... . . .. . ... .. .. . .... . . . . .. .. ... . .... 1 - 60
1.7.4 Pending Interrupts . .. . . . .. . . . . . ............... . . . .. . .. . .... . .. . .. . . . .... 1 62
Reyjew Questions . . . , . " ' ' " """ "' ' '
, ' ' 1-65

2 1 EeabJres of 8086 2-1


2 2 Architecture of 8086 2-2
2.2.1 Bus Interface Unit (BIUI . . ..... ... . . ..... . . . .... . . ... .... . ... . .. . . . .... . ... 2 2
2.2.2 Exerution UnK lEU) .. . . . . . .... . . . ...... . . . . . .. . . . .. . .. . .... . .. . .... . . . . . . 2 - 4
2.3 Register Organisation ........................................................................... 2- 5
2.3.1 General Pl!rpose RegistetS . . .. . . . . ....... ......... . .... .. . .. . .. . . . . . . . . ... 2 5
2.3.2 Segment RegisteR .. . . . .. . . . . . . .... ... . . . . . .. . . . . .. . .. . . .. . .. . .. . . . . . .. . 2 - 5
2.3.3 Pointers and Index Registers .. . . . .. . . . . . . .. . . . . .. .. . . . .. . . . . . . . . 2 - 7
2.3.4 Flag Register . . . . . ... . . . ... . .... . . . . . . . . .. . . . . . .. . . .. . . .. . .. . ..... . ... . 2- 7
2.4 Bus Operation .......................................................................................2- 9
2.5 Memory Segmentation ............... .......................................................... 2- 9
Review Questions .,....., .., ...,, .., , , , ,.,., .., , , ..,.,. ......, ,, .., .., ...,,.....2 - 14
3 1 lnlmdudloo . 00 ... 3 1
3.2 Addressing Modes ............................................................................... 3 1
3.2.1 DID ~ Modas ................ .................................. 3 1
3U Propn Memory Ad!tess!tg Modes .............. .......................... 3 . 9
3.2.3 Stick lleiTICWY Adck!!ssi!g a.todes ..... .................................... 3 11
3 3 Instruction Set of 8086(8088 ... ........ ...........3 14 ,,,,,

3.4 Data Movement Instructions ,,,, .. , ,,, ,, ... .. , , ............ , ............... 3 15


34 I IMlY klllructigo . , , , , + ' .. .......... .. 3- 15
3.4.2 PUSH/POP ID!Irudjoos.... ' , ' , Off ft t 0 0 0 0 0 0 I . f ft 0 f 0 f 0 ! 0 3 16
3 4 3 I oad Eftec:!!w! AMBos t t t
.. . 3 - 18
3.4.4 String Data Ttanlfet lnsbuctions . ... . . . . . . . .. ..... 3 19
3' 5 Uisre!MMtts DNa Trpnsipr lnsfndjons 3-21
3.5 Arithmetic and I nstruc:::tic>ns .........................................................3 . 23
351 McMinn " 0 0 0 0 0
........... . 323
3 5 2 $tHtarJirn 3-25
3.5.3 Couptiron .. , . , ..................................................... 3 . 26
3.5.4U. ............... 317
3 55 !'!Mob! ......................... 328
3 56 BCD and ASCU Mtvne1ic t f I I I I eo eo tt!!!n!oftt ttOt000 328

356 1 BCOM!m* 3 29
3.5.&,2 ASCU Mhi1lllc .. 3 30
3.5.7 Basic LAgle lnsbuctions .. .. .3 32
3,5 8 Shift end Rntale .. . , .. .. I I ' ' .. . . . .. . .. . ........ . 336
3.5.0.1 SH11 . 336
3.U.2- 339
3.8 String lnttnJetiont ...............................................................................3 42
3.7 Program Control Transfer lnstructions................................................3 44
3 7 1 CAll arxl RET .klstnr#km I I I I I I I I I I I I I I I I I T I I I 1 I I I I 1 , I I I I I I I t 3 -44
3 7 2 .IMP lnstrucfigo f t f t ft t t t t t t t t t t 0 0 I t 0 I 0 0 0 0 J 0 0 0 I t 0 J I 1 I I I l I f I I I f I J f 0 0 0 0 0 0 0 0 3 46
f

3.7.3 Cood . Coodilional ~ -" " ....... " " .. " ........... ' ............ 3. 48
3 8 lteratlon Control Instructions ....... :..............................., . , ...................3 49
3 9 Processor Coolml lnslructioos .. , , , , .. , , , , ............ ., .......................3 49
3.10 External Hardware Synchronization Instructions .............................3 - 50
3.11 Interrupt Instructions .........................................................................3 - 51
3 12 Assembler D jrectjves 3-52
3.12.1 S<Jmmary of Assembler Directives ........ . .... . .... . ....... . .. . .......... 3- 58
3.12.2 Variables. S<Jffix and Operntors .... . ......... .. . .... . .. . .... . .. . ......... . 3-58
3.12.3 Accessing a Procedure and Data from anodler Assembly Module . . . . . ... . ... . .. . 3- 59
3.13 Assembly language Programming ...................................................3 - 60
3.13.1 Assembly Language P!O<Jams ................ . ....... . ..... .. . .... ... .. . 3- 62
3.13.2 Assembly Language Programming TillS .. .. . . . .. . . . .. .. . .. . .. . .. . .. .. . .. .. . 3 - 63
3.13.3 Programming with an Assembler. . .. .. .. .. .. . .. .. .. . .. . .. . .. .. . .. . .. .. . .. . 3 - 65
3.13.3.1 Assembling Process . 3 -66
3.13.32 UMing Process . . . . . . . . . . . . . . . . . . . . . . . . 3 67
3.13.3.3 Debugging Process . . . . . . . . . . . . . . . . . . . . . . . . . 3 67
3.14 Assembly language Example Programs ..........................................3 - 69
3.15 Timings and Delays .................................................. ........................3 - 72
3.15.1 Timer Delay using NOP Instruction . .. . . .. . .. .. . .. .. . .. .. . .. . .. . .. . .. .. .... 3 n
3.15.2 Timer Delay using Counters .. " " " . " " " . " " " . " . . . " . " . " . " " " .. 3. n
3.15.3 Timer Delay using Nested Loops .... . .. ...... . .... .... .... . .. . .. . .. .... . . 3 74
3.16 Data Conversions , ......, ......, .. , , ..,, , , .., , ........, .., , , .., .., , .., ,,3 - 75
3.16.1 Routines to Conwrt Binary to ASCII ......... ... .... . .. . .. .. . .. . .. . .... . ... 3 76
3.16.1.1 By AAM lnslruclion fFor rwmber less !liM 100). . . . . . . . . . . . . . . . 3 76
3.16.1.2 By Series o1 Decimal OMsion. . . . . . . . . . . . . . . . . . 3 79
3.16.2 Routine to Convert ASCII to Binary . ............ ... . .. . . .. . ...... . . . . 3 82
3 16 3 Routine In Read Hexadpdmal Data 3 - 85
3.16.4 Routine to Display Hexadecimal Data ........ . ...... . .. . .. . .. . .. . .. . ...... . 3 90
3.16.5 Loolrup Tabies fO< Data Conversions .. .. .... . .. . . . .... . .. . ..... . .... . .. . . . 3 93
3 17 Pmced! !res 3 .. 96
3 17 1 Reentrant Procedure 3-98
3 17 2 Reausjve Prooedum 3-98
3 18 Macro . ..... ...................3 - 99
3 19 lnstructjoo Formats ........... 3 - 100
Review OtJestjoos 3-107

Copyrighted material
Program 1 : Read keyboard input and display it on monitor ......................4- 1
Program 2: Addition of two 32-bit numbers................................................4 - 1
Program 3 : Addition of 3 x 3 matrix ...........................................................4 - 2
Program 4 : Program to read a password and validate user .....................4 - 4
Program 5 : Program to calculate factorial of a number ............................4 - 5
Program 6 : Reverse the words in string .................................................. .. .4- 7
Program 7 : Search numbers, alphabets, special characters .....................4- 9
Program 8 : Program to find whether string is palindrome or not ............ .4 - 12
Program 9 : Program to display string in lowercase ................................ .4 - 13
Program 10: Write an 8086 assembly language program (ALP) to add
array of N number stored In the memory ............................ .4 - 14
Program 11 : Write 8086 ALP to perform non-over1ai>P8d block transfer. 4 - 18
Program 12: Write 8086 ALP to find and count negative numbers from
the array of signed numbers stored in memory...................4- 23
Program 13 : Convert BCD to HEX and HEX to BCD ...............................4- 26
Program 14 : Multiplication of two 8-bit numbers ......................................4- 32
Program 15 : Divide 4 digit BCD number by 2 digit BCD number............4- 38
Program 16 : To perforrn conversion of temperature from "F to "C ..........4 - 41
Program 17 : String operation ...................................................................4 - 44
Program 18: String Manipulations............................................................4- 52
Program 19 : Sorting of Array ...................................................................4- 62
Program 20 : Program to search a given byte in the string .......................4- 66
Program 21 : Program to find LCM of two 16-bit unsigned numbers ........4- 67
Program 22 : Program to find HCF of two numbers.................................4 - 68
Program 23 : Program to find LCM of two given numbers........................4 - 70

5,1 Introduction ...........................................................................................5-1


5.2 Signal Description of 8086 ....................................................................5 - 1
5.2.1Signals with Common Functions in Both Modes . . .. . . . .. . . .. . .. . . .. . .. . . . . .. . . . 5 2
5.2.2 Signal Definitions (24to 31) fO< Mlninum Mode . .. . . . . .. . .. . . . . . . .. . . . . .. . . . . . . 5-4
'
52.3 Signal Definitions (24 to 31) for Maxinun Mode..... . .... . .. . .... . .. . ...... . . . 5-4
5.3 Physical Memory Organisation ......:.....................................................:5 - 5
5.4 110 Addressing Capability ..................................................................... 5 - 7
5.5 General 8086 System Bus Struclure and Operation .............................5 - 8
5.6 Minimum Mode 8086 System and Timings ............... ........ .... .... ..........5 - 10
5.6.1Minimum Mode Configuration .... . . . . . . . . . . .. . . . . ... . .. . . . . . . .... . . . . ... 5- 10
5.62 Minimum Mode 8086 System ....... . . .. . ..... . ... . .. . ........ . . . .. .. 5 - 15
5.6.3 Bus Tomings for Mininum Mode . . .......... . ... . ... .. . . .... .. . . . . . . 5 . 16
5.6.3.1Tmings for Read and Wrile Operalions . . . . . . . . . . . . . . 5 16
5.6.3.2 HOI.D R- Seqoence . . . . . . . . . . . . . . . . . . . . . 5 -18
5.7 Maximum Mode 8086 System and Trilg$ ........................................5 - 18
5.7.1 Maxinum Mode CclrJt9.ralion .............. ........ ......... ... ........ . 5 - 18
5.7.2 Maxinum Mode 8086 Syslem . . . . .. . . . . .. . .. . . ... . . . . .. .. ... . .... . . 5 - 20
5.7.3 Bus Tomi!!!)S lor Maximum Mode .. .. . .......... .. .. . .. . .. .. . .. . .. . ....... . 5- 22
5.7.3.1TI!Tings lor Read and Wrile Opetaliool . . . . . . . . . . . . . . . . . 5 -22
5.7.32Trilgs loriil'WTSV>* . . . . . . . . . . . . . . . . . . . . . . . . 5 -23
5,8 Memory Structure and its Requirements ............................................5 - 24
5.9 Basic Concepts in Memory Interfacing ...............................................5 - 25
5.9.1 Address Oeaxling Tec:hni<JJe$ ...... . ........ . ..... . ... ......... . .... . . 5-26
5.10 Interfacing Examples ........................................................................5- 28
5.11 Wait State Generator Circuit .. ....................................... ....................5- 32
Review Questions ,,,....,, ....... ........., ..,, ... ........................ ................ ..........,,5 - 33
' , ' ' ....... ~~- ' .. ,. ., . . ' ,. .. -
' . ..
-
, '

6,1 Features of 8257 ............................................................................. ,.....6- 3


6.2 Pin Oia ram of 8257 ............................................................................6 - 4
6.3 Block Dia ram of 8257..........................................................................6 - 6
6.4 Operating Modes of 8257 .................................................................... 6 - 9
6.5 DMA Cycles .... ............... .... .................... ............................................ 6- 10
6.6 Interfacing 8257 in 1/0 Mapped 1/0 ........ .............. .... .... ...................... 6 - 11
6.7 Features of 8237A .................................................. c ......................... 6- 11
6.8 Pin Diagram of 8237A ........................................................................ 6 - 13
6.9 Block Diagram of 8237A .................................................................... 6- 14

Copyrighted material
6.10 Transfer Types ................................ ............................................... 6-20
6.10.1 Memory.ro.Memory Transfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . 6 20
6.10.2 Autoinitiafrze . . . .. . . . .. . . . . . . . .... . . . . . . . .... . . . .. . .. . .... . .. . . . .. . . . . 6 21
6.11 Priority .. ........ .. :..................... .................. ................... ................... ... 6- 21
6.11.1 RxedPriority. . . .. . ..... ... . . . . . . . . .. . . . . ..... . . .. .. . ...... . . 6-21
6.11.2 R!lta!i1g Priority .. . . . .... .. . . . . . .. . . . . ...... . ... .. . .. . . . .. . .. . . .. . . . . . 6 - 21
6.12 Register Description ......................................................................... 6- 22
6.13 Interfacing ....................................................................................... 6 - 27
Review Questions 6 - 28
;:_', ., -~ -! . ... , . . . . . .~ . ._ ' . ... . . :"''1.-. . ?..(;' :; ~ ~j"t~i-;'}',_
... '"" .., u ' ~ < - < ,. ~' ..

7.1 Features of 8255A ...............................................................................7 - 1


7.2 Pin Diagram ..........................................................................................7 - 2
7.3 Btock Diagram .......................................... :............................................7 - 4
73 1 Oala Bus Buller 7-5
7.3.2 Controllo!;c .. . . . .. . . . .. ...... . .... .. . . . ...... . ................ .... . ... 7 - 5
7.3.3 Group A and Group 8 Controls .. . .. .. . ... . ... .. ... ............... . .... . .... 7-5
7.4 Operation Modes ..................................................................................7- 5
7.4.1 ~Set-Reset (BSR) Mode............ ... . .... . .... . .... .. ... .. .. .......... 7- 5
7.4.2 vo Modes ................ . ...... . .. . . .... . . . . . .. .. . . . . .. . ........... . . 7-5
7 5 Control Word Fonnats .. , ,.......... , .. , .7 - 7
7.6 8255 Programming and Operation ......................................................7 -11
.
7.6.1 Programming in Mode 0 ... .. ..... .. . ... . .... . ............ ... .. . .. . ...... 7 - 11
7.6.2 Programming In Mode 1 (lnpoJt / Outputwitll Handshake) ..... . .. . ....... . ...... 7-13
7.6.3 Programming In Mode 2 (Strobes Bkliredlonal Bus VO) . .. . . . . . .. . . . . .. . . ... 7- 18
7.7 Interfacing 8255 to 80861n 110 Mapped 110 Mode..........................'....7- 21
7.8 Interfacing 8255 to 80861n Memory Mapped 1/0 .... ...........................7- 22
7.9 D/A Converter and 1heir ln1erfacing with 8086 ....................................7- 23
7.9.11C 1408 .......................................... ... . ............... . 7-23
7.9.2 DAC0830 . .... .... . ................................ . .... , .... .. . . . .... 7 26
7.10 AID Converters and 1heir Interfacing with 8086 ................................7 - 34
7.10.1AOC0804Famiy . . .... ...................... . .... . .. . .. . . . .. . ...... . . 7-34
7 10 2 ADC 08081Q809 . . . . . . .. . . . . . . 7-41
7.11 Stepper Motor Interfacing ................................................................7 - 43

Copyrighted material
7.12 Control of High Power Devices using 8255 ......................................7 - 4 7
7.1 2.11n~ated Cirruit Buffess . ...... . .. . . . . .. . . . .. . . . . .. .. ... . . . . 7. 47
7 12 2 Traosjsto Buffea 7 - 48
7.12.3 Isolation Circuits . . . . . . . . . . . . . . . . .. . . .. .. . .. . . . . .. . .. . . . . . .. . .. . . . . 7 50
7.12.3.1 El<!drcmagne1leRelays .. . . . . .. . . . . . . . . . . . . . 7 50
7.12.3.2SolidSia18Relays . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-51
7.13 Keyboard and Display lnterfacing .....................................................7 - 51
7 15 Centronics Printer Interlace 7 - 58
Review Questions ...................................................................................7 - 64

8.1 Introduction,, .......... , .. , .. ,,,, .. , .. , ,,, .. , .. , , . , .... ,,,,,. , . . 8- 1


8.2 Interrupt Cycle of 8086/88 .................................................................... 8 - 2
82.1 External Signal (Hardware Interrupt) ........................................ 8 2
82.2 Speciallnslrudion .. .......... .. ........................................ 8 2
82.3 Condition Produced by Instruction .. . ........ . ...... . .. . ....... . .... . .. . . . .. 8 2
8.3 8086 Interrupt Types ............................................................................ 8 - 4
8.3.1 Dime by Zero Interrupt (Type 0) ... . ...... .. . ...... . .. . .... . .. . .. .. . .... . .. 8 4
8.3.2 Single Step Interrupt (Type I ) . .. .. .. . .. .. .. .. . .. .. . .. .. . . .. .. .. . .. . .. .. . .. 8 4
8.3.3 Non Masl<able lntenupl (Type 2) . .. .. . .. .. .. . . . .. .. . .. . .. .. . .. . .. .. . .. .. . .. 8- 5
8.3.4 Breakpoint Interrupt (Type 3) .... .... . ... . ... ... . . . ..... ... . .. . . . 8 5
8.3.5 Ovetftow Interrupt (Type 4) .. ...... . .. ... ... . ...... . .. . .... . .. . .. . .... ..... 8 5
8.3.6 Software Interrupts .. . .. .. . .. .. .. .. . .. .. .. .. . .. .. . .. .. . .. . .. . .. . .. .. .. .. . 8- 6
8.3. 7 Maskable Interrupt (INTR) .. .. .. .. . .. .. .. .. . .. .. .. . .. . .. .. . .. . .. . .. .. .. . .. 8 7
8.4 Interrupt Priorities ................................................................................ 8 - 8
8.5 Expanding Interrupt Structure using PIC 8259 .................................... 8 - 8
8 5 1 feab ups a( 8259 8 -9
8.5.2 Block Diagram ol 8259A ................................................ 8 9
8.5.3 Interrupt Sequence .. . .... ... .... ....... .. . ...... ...... ..... ......... .. . 8 11
8.5.4 Priority Modes and Other Features ........ . .... . ... . .. . .. . . . .. . ... . .... . . . 8 12
8.5.5 Programming the 8259A .... ... .... ... . ........ .. . .. ........ .. . .. ...... . 8 15
8.5.6 8259A Interfacing . .. . .. .. . ...... . .. .... .. . ...... . .. . .... . .... ... . ...... 8 22
8.6 Interrupt Example.............................................................................. 8 - 26
Review Questions .................................................................................... 8 - 28

Copyrighted material
9.1 Character Input Functions .....................................................................9 3
9.2 Character Display Functions ............... ..................................................9 - 7
9,3 File Control Block Functions .. . ... . . .. .. .. .. .. .... ...... .. .......... ,9 - 8
9.4 Handle Functions ......... .......................................................................9 15
9.5 Memory Management Functions ........................................................9- 22
9.6 Display Functions Provided by ROM 8105 .........................................9 25
9 .7 Printer Functions .................................................................................9 28

10 1 Classification . " t t , t " " " " " " , . ,


.10 . 1
10.1.1 Sinplex . . .. .. . .. .. . .. ...... . . . ...... . ...... . .. . .. ... .. . .. . ...... . .. . 10 1
10.1.2 Half Duplex . .. . .... . ........ . .. ...... . .. .. .. . .. . . . .. . ............ . ... 10 . 2
10.1.3 Ful lluplex .. ... .... . . ........ .......... ...... .... . .. . .. . .. . ...... .... 10 - 2
10 2 Transmission Formats .... .......................................................... ........ 10 2
10.2.1 Asynchronous . . .. .. ........... . ........ . .... . .... . .. . .. . .. ... .... . .. . 10 2
10.2.2 Synchronous .... . ... . .. . .. . .. . . . .. . .. . . . . . . ... . . . . . .. . .. . . . . . . 10 3
10.3 Interfacing Requirements ............................................................ .....10 3
10 4 IISART 8 251 . .. . . ... ... . ,10 . 4
10 4 1 features .. ' ' .. ' .......... .. .... . 10 - 4
I I I

10.4.2 Pin Diagram oi8251A.... . . . . . .... . ........ . .... ... . . ... . .. . .... . ...... 10 5
10.4.3 Blook Diagram .......... .. . .. .... .... . .... . .. .... . .. . ...... .... .. ..... 10 7
10.4.4 8251AControl W<llds .... . . . . . . . .. . . . . . . . .... . . . .. . . . ... . .. . .. . .. . . . ... 10 9
1Q.4.5 8251ASta!usW<lld . .... .. .. . .. . .. .... .. . ....... ..... ... .. . .. . ...... . . 10 11
10.4.6 Oa1a Cormulicalion Types ...................... . . . . . . .. . . . . . .. . . . . . 10 12
10.4.7 1nte!facing 8251A to 8066 in 110 Mapped 110 Mode . .. . .......... . .. .. . ...... 10 14
10.4.8 ~ 8251AID 8066 in Memory Mapped 110 . .. . . ..... . . . . . . . ......... 10 15
10.4.9 F'!l!granmil1g Examples ........ . . . ...... . .. .. .. .. .. .... . ....... . ...... 10 - 16
10.5 Serial Communication Protocol (RS232C) ......................................10 17
10.6 Sa mple Programs of Serial Data Transfer......... ..............................10 19
10.6.1 Pro!JllmtoTraMIIIHlneCharaeter ...... .. . ........................... .. 10 - 19
10.6.2 Program to ReceM! One Charaeter ............................. . .. . . . .. . 10 20
10.6.3 PIO!JMl to Transmit Fie . ... ............ . ... ... .... . ... . .. . . . ... 10 20
10.7 Introduction to High-Speed SeriaiCQ!nmunication
Standards. USB ...........................................................,.,..............10 - 22
10.7.1 USB FeallKes ... . .... . . . . . . . ....... . .... . . . .. . . . . . .. . . ... . . . . . . .. . 10 23
10.7.2 Umilation of USB . . . . . .. . . . . . . .. . .. .... . .... . .... . .. . .... . .. . .. . .. . .. . 10-25
10.7.3 Minim\Mn PC Requirements for USB Support .......... . ... . . ....... . .. . . . . . 10 26
10.7.4 USB 'tiered slar" Topology ................. . .............. . .... . .... . .. 10 27
10.7.5 Terminologyusedin USB ......................... . .. ........... .. .. . .. 10-28
10.7.6 Host's Functions . ...... ... .... .. . ...... , ., ........ . .. ... .. . ......... . 10 30
10.7.7 Perip/lela! Fooctions .. . . ... ............ ...... . ..... , .. . .... . .... ... .. . 10-31
10.7.8 USB Cornrnunication . .. . . . . . . .. . ... . ... . .. . . , . . . ... .. ... . . . . , . . . .. . . 10-32
10.7.9 Elements of Transfer .. . . .... . ... .. ..... . .. ... .. ... .. ... ... ... .. . . .... . 1032
10.7.10 Data Transfer Types . .. .. . .... .... .. .. .. .. ... .. . .. . .... .. .... .. . ..... 10 - 34
10.7.1 1 USB Controller. .. . ....... ... .. .. .. ..... ... . .... . ..... ..... .... . . ... . 10 36
Review Questions .................................................................................10 - 37

11 .1 lntroductjon ............ .. .......... ....... ............. .. .. ........................... .. .. ...... ,11- 1


11 .2 Featuresof8051 ..,,, ........... ,, .... , , , . I t It " " " !! ' "" I
11-3
11 3 8051 Microrontm!!er Hardware 11 - 3
'-
11.3.1 Pin-oot of6051 .. . .... . .... .... .. . .. .... . ........ .. ..... .... .. ..... . . . 11- 5
11.3.2 Central Processing Un~ (CPU) ........ .. . .. ................ . .. ..... . ..... 11 7
11.3.31ntema1RAM .. .. ....... .. .. . .......... . , ..... . ......... . ......... . .. . 11 - 7
11 3 4 !n!emal ROM I I 11 - 9
11.3.5 Input/Output Ports .... . .. .. ...... .............. .... ....... .... . ........ 11 9
11.3.6 RegislerSetof6051 .... ' ...... " .. " ' " .. .. .. ' .. .. ' ... " .. ' .... ' " . .. 11 - 10
11.3.6.1 RA!gisle!A(!\cX:ul!Aata!) . .. .. . . . . 11 - 10
11.3.6.2 Regjolor 8. . . . . . . . ' . . . 11 - 11 -

11.3.6.3 Progwn SlaU- (Flog~~


11 .3.6.4 $lad< lr1d S1ad< Poinll!r . . . . . .
. . .. . . . . . 11-11
' 11-11
11.3.6.5 Dela Poinll!r (OI'TR) . . . . 11 - 11
11.3.6.6 Progwn eo... . . . . . 11-12
11.3.6.7 Spedaj Fundlon ~ai 11' I . . . . . . . . . . . . . ' ' 11 - 12

. - b , , . ,

Copyrighted material
11.4 Memory Organization in 8051 .........................................................11 - 15
11.5 Input/Output Pins, Ports and Circuits .............................................. 11 - 16
11.6 Extemal Data Memory and Program Memory ................................ 11 - 19
11.6.1 ExtemaiProgram Me1110fY. .... ..................... . .......... . .. ... . . . 11 19
11.6.2ExtemaiDalaMemocy . .. . . . . . .... . . . ......... . ..... . .... .. . .. . .... . .. . 11-21
11.6.3 lmporlant P<lints to Remember in Aa:essing External Memory . . . .. . ... . .. .. . 11 23
11.7 Timers and Counters ......................................................................11 - 24
11.7.1 Timer/Counter Control Logic . . . . . . . . . . . . . . . . . . . . .. . .. . .. . . . . . . . . .... , . 11 24
11. 7.2 Timer 0 and Timer 1 ..............,,... , .... , ..,,,,.. , ..................,,,,11 - 25
11.8 Serial Port .......................................................................................11 - 29
11.8.1 Operating Modes fo< Serial Port . . . .. ..... ........ .. .. . .. ... .. .. . .. . . .. . . 11 30
11.8.2 Serial Port Control Register .... . . . .... .. . ... .. ... .. ..... .. . . . .. ...... . .. 11 - 31
11.8.3 Generatilg Bald Rates . . .... . . . . .. . . . . . . .. . . .. . . .... . . . . .. .... . .. . . . . . 11 31
11.9 Interrupt Structure ...........................................................................11 -.33
11.9.1 Priority Level Slruclura . . . . .... . . . . . . .. . . .... . . . ....................... 11 34
11.9.2 Extemal lnteiT\JI)ts . . . . .. . . . . . . .. . . . . . . . .. . . .. . . . .. . .. . .. , . . . . . , . . .. . . . 11 36
11.9.3 Sif9&-Step Operation .... . . . . . . .. . . . . . .. . . . .. ... .. . .. . . . .. .. . . . . . . .. . . 11 36
11 .10 Interfacing 8255 for 1/0 Expansion ...............................................11 - 37
Review Questions ..................................................................................11 - 38
8086 Programs
Peogrom Add two numbe<$ ... ......................... .............................. .......................... .(3 - 69)
Program Find the overage oi tw"o numbers ............... ............. ............. .. ..... ...... ........ .(3 69)
Pmgrom . Find the moximu1n number in lhe Ofi"'y ... ... ... .......... ... .. ..... ... .. ... ..... ....... ... .. (3 - 69)
Progra m - Sea rch o number 1n the o rroy ... ........... ... .. ... .... . ......... ..... .. .. ... ..... ...... . ... ..... (3 70)
Pr rom- Find sum of numbers in the orro ................................. .................... ... ... .... 3 70
Program . Scporo1e even ond odd numbeB in the orroy.............. ....................... .........{J - 7 1)
Program Reod keyboard input ond display it on monitor ............................ .................{4 -1)
Pfogfom Addi~on of lwo 32-bil number> ........... ................. ............. ............. .............(4 - 1)
Program - Addition o f 3 x 3 matrix .. .. ...... ..... ... ... ... ...... ... ............. ... .. ... .. ... .. ... .. ...... .. ...(4 - 2)
Program Reod a password a nd validate uw...................... .......... ... ............... ...........(4 . 4)
Pro g ram Calculate ladOfial of o number ........ ........ ...... ... ..... .......... ..... ..... ........ ........(4 - 5)
Prog ram Reverse the words in string .. ............................ ........ ..... .......... ............. ........(4 7)
Program SeorGh numbers, ofphobets, special characters .............. ... ... m (4 9)
......... ... .. ........

Progrom -Find whether string is palindrome o r not.... ......... ..... ........ .......... ....~.............(-4 12)
Program - To display string.in lowercose ....... ... ..... ...... ............................... ... .......... ...(4 . 13)
Program Write on 8086 assembly longooge program (Al P} lo o dd a rray of N number
stored in the memory.... ...... ......... ..... ...... ... ........ .......... ., ...... .................... (4 14 )
Pro g ram Write 8086 ALP to perform non-cwerlopped block tra nsfer........................... (4 ) 8)
Program - Write 8086 ALP to fi nd ond count negative numbers from the army o f sig ned
numbe($ stored in memory. ............................................ ............... ...........{4 23)
P,og,om Corwert BCV lo HEX and HEX lo BCD .................................. .....................{4 26)
f f0gf0m - MuiNplicoNon of two Bbil numbefS .... ......... ...............................................{4 321
Progom - Divide 4 digit BCD number by 2 diga BCD number...................... ............... (4 - 38)
Ptogrom To pe<fonn convenion oflempe<Oiufe from 'f lo "C........ .................. .......... (4 - 4 1)
Program String operolions .... ..... ......... .. ...... ........ ......... ........ ............. ..... ....... .......... (4 - 44)
Ptogrom Siring Monipulat;ons ................................................................................ (4 - 521
Ptogmm Sot1ing of A"oy.............. ........ ...... ........................................................ .... (4 - 62)
Program Search o g iven byte in the string .......... .. .................................................... (4 ~ 661
ProgfQm Find LCM of two 16 bil uos;gned numbefS ............................................... .. (4 . 67)
Program f;nd HCF of two numbers............. ......................... ...................................(4 - 68)
Pr rom Find lCM of two iven numbets............... ................................................. 4 ~ 70

r h\r
An Overview of 8085

1.1 8085 Microprocessor


In this chapter we will see features, pin diagram, architecture, register structure, bus
organis.ltion, timing and control and instmction set of I:Kl85 microprocessor.
Til<' features of 8085 microprocessor <.\n~ as given below :
1. It is an g...bit mi<.:roprocessor i.e. it c;;m accept, process, or provide 8-bit data
simultaneously.
2. 1t operates on a single +5V power s upply connected at Vee; power supply ground
is connected to V St~'
3. It operates on clock cycle with 50% duty cycle.
4. Jt has on chip clock generator. This internal clock generator requir<.os tuned circuit
like LC, RC \')t CT)'Shll. The internal clock gl.'llE!'T<ltor d ivides oscillator fn.~UL~C)' by
2 and gcn('fatL>s clock signal, which can be uSt.~ for synchroJUz.ing external d('vices.
5. It can operate with a 3 MHz clock frt-quL>flC'y. TI\e 808SA2 vcr~ion can operate ,H
tlw maxlmum frequency of 5 MHz.
6. It has 16 address lines, hence it can access (2 16 ) 64 Kbytcs of m('mory.
7. It provides 8 bit 1/ 0 add""'"'-"' to acro;s (28 ) 256 l/0 ports.
8. In 8085, the lower 8-bit address bus (Ao A , ) and data bus (Do O,) are
multiplexed to reduce number of external pins. Out due to this, exte.mal hardware
(latdl) is rcquii"L~ to scparntc addn..--ss lint!S a.nd dab lines.
9. It s upports 74 instructions with the follc,lwing addressing mod~ :
a) Immediate b) Register c) Direct d) Indirect e) Implied
10. The Arithmetic Logic Unit (ALU) ol 8085 perlonns :
a) 8 bit binary addition with or without aury
b) 16 bit binary addition. c) 2 digit BCD addition.
d) &-bit binary ~"ltbtraction with or without borrow
e) 8-bit logical AND. OR, EX.OR. complem<.'llt (NOl), aJ\<.1 bit shift oper.llion..

(1 1)

Copyrighted material
Microprocessors and Interfacing 12 An Overview of 11085

11. It has S~bit accumulator, flag register, instruction regis ter, :;:;ix: S.bit ~cneral purpose
registers (6, C, 0 , E, H and L) and two 16-bit registers (SP and PC). Getting the
operand from the general purpose registers is more faster than from memory.
Hence skilled programmers always prefer general purpose registers to store
program v:l.riablcs than memory. ,
12. It p rovides five hardware interrupts : TRAP, RST 7.5, RST 6.5, RST 5.5 and INTR.
13. It has serial 1/0 control wh.ich allows serial communication.
t4. It provides control s ignals (10/M, RD, WR) to control the bus cycles, and hence
external bus COQtroller is not required.
15. The extem..'\1 hardware (another micropnxes.."ttr or equivalent master} can detect
which machine cycle microprocessor is executing using s tatus signals (10/M, S,
5 1). This feature is very useful when more than one processors are using common
system resources (memory and 1/ 0 devices).
16. It has a .n:'echanism by which it is possible to increase its interrupt handling
ca pad ty.
17. The 8085 has an ability to share system bus with Direct Memory Access controller.
This feah.ue allows to transfer large amoun t of data from l/0 device to memory or
from memory to 1/ 0 device wlth high speeds.
18. It c.m be used to implement three ~p microcomputer with supporting 1/0
devices like IC 8155 and IC 8355.

1.2 Architecture of 8085


Fig. 1.1 (See Fig. on next pagt~) s hnws the arch~tecture of 8085.
lt consists of various functlon.u llll~t..~ ~'s lis ted below:
Registers
Arithme tic an d logic Unit
lnstructlon decoder and milchi1te cycle encoder
Address bu ff~r

Addres..~/Data buffer
lnrrementer / O.Crementer Address Latch
lnterrupt control
Serial 1/ 0 contro l
Tinting and control circuitry.

Copyrighted material
Mlcn>processors and Interfacing 13 An Overview of 8085

RST8.6 TRAP

ljR"
A

RS~5, 5

Interrupt control
R$~ 7 .5
sr sj
SonO'll IJO control

~ 8 801 in1erntlt <tale ~ ~


u lJ lJ
I ""'""""'""' I
I
I
Temporary
register
II
1 F~ regls.1or

I
j I k'lsti'Uction
rogh;tQr
~ WR. .
BR
o Reo
HR
c-
ZRoo

ER. .
L Re

"'""""
S lo:l(lk polntor
... ~
unit
ln!llt'Uetion
do<adO<
~
.._.m
coun1er
,r (Ai.U )
"""
.,..,.
"'<>V>'ER { - 5 V
.......,
maehlno
tnctementerf
000'011'1e01Ct
Addreee 18tdl
~' ~>P\.Y -GI>IO
I
J
- ------
CU< x, - Timir'IO tl<~CI COt'ltrol
IN
C LK
GEN
CONTROl. STAl\.15 OMA
----.. RESET
----.. ----..
I Addross
bvl'fer
I IAddress 1 Data
buller
I
Jo Je J. j LD
CU<LuT
w~ ,a,;;;
I
RESET IN u
Au; "e
_U
AD7 ADo
READY HLOA RESET OUT
Addrossbus 0;ll~
....
I AddtCISil

Fig. 1.1 Architecture of 8085

1.2.1 Register Structure


The Fig. 1.2 s hows the register
I Tempotary I
register structur~ of 8085. 11lc shaded portion of

WReg ZRog this register model is caned programmer's


model of 8085. It includes six 8-bit
A Reg Flag Reg registers {8, C, 0, E. H and L) one
BReg CReg accumulator, one flag register and two
16-bit registe"' (51' a.nd PC). All these
DReg EReg
n.'gb;tcrs are aca.._~ible to programmer and
!<Reg LReg hence they are included in the
Slack po;nter (SP) programmer's model. The remaining
registers temporary. W and Z are not
Program counter {PC)
accessible to the programmers; they are
Fig. 1.2 Register struc1ure of 8085 used by microproces.o;or for int'c mal,
intermediate operations.

Copyrighted material
Microprocessors and Interfacing 1-4 An Over,iew of 8085

1. General Purpose Registers

2. Temporary Registers
a) Temporary d?~ta regist~ r b) W and Z regi:;ters
3. Special Purpose Registers
a) Accumulator b) Flng registers c) Ins truction n.."gister

4. Sixteen Bit Registers


a) J''rogram Counter (!'C) b) Sta<:k Pointer (SP)
1. General Purpose Registers :
B. C, 0, E. H, and l arc S..bit general purpose register.;; can be used as a scpnrnte S~bit
registers or as 16-bit regist('r pairs, BC, DE, and HL. When used in register pair mode, the
high order byte n..-sides in the tlrst register (i.e. in B when BC is used. as a register pair)
and the low order byte in the second (i.e. in C when BC is used as a register pair).
Hl pair a1so functions as a data pointer or memory pointer. These arc also caUed
scratchpad regis ters, as user can s tore data in them. To store and read data from these
registers bus access is not required, it is an internal operation. Thus it provides an efficient
way to s tore intermediate results and usc them wMn required. 11lc efficient programmer
prefers to use these registers to store intermediate results than Uw mf.'mory locations which
require bus aro.--ss and hence more time to per-fonn the operation.
2. Temporary Registers
a) Temporary Oat.:. Register : The ALU has two inputs. One input is supplied by the
accumulator and other from temporary data regi.o;:ter. The p rogrnmmer an not access this
temporary data register. However, it is lntemaUy used for execution of most of the
arithmetic and logical instructions.
For example : ADD B is the instruction in the arithmetic group of instructions which
adds the contents of register A and register B and s tores result in register A. The addition
operation is performed by ALU. The ALU tak.. inputs from register A and temporary
data register. The contents of register 8 are transferred to temporary data reg;ster for
applying second input to the ALU.
b) W ..,d Z Registers : W and Z registers are tempomry registers. Thet;e registers are
uSt..~ It) hold 8-bit datn during execution of some instructiort.'i. 1hese registers are not
available for prQgrammer~ since ~ uses them internally.
Use of W and Z registers :
The CALL in.'ltruction is used to transfer program control to a subprogram or
subroutine. Thls instruction pushes the current PC contents onto the s tack and Joads the
given address into the PC. The given address is temporarily s tored in the W and Z
registers and placed on the bus fa< the fetch cycle. Thus the program control is transferred

,_
. Copyrighted material
Microprocessors and Interfacing 15 An Overview of 8085

to the addrt.."S.'i given in lhc ins truction. XCHG instruction exchanges the contents of H with
0 and L \\o'ilh E. At the time of exchange W and Z n ..'gi:->ters are u$4..-:.d for tcmpornry
storage of data.
3. Special Purpose Registers :
a) Register A (Accumulator) : It is a tri-state eight bit register. It is extensively used in
arithmetic... logics load, and store opcrations, as well as in,. input/output (1/ 0) operations.
Most or the times thE.> result of arithmetic and logical operations is stored in the register A.
Hence it i~ a lso identified as accumulator.
b) Flag Register : It is an 8-bit register, in which five of the bits carry significant
information in the form of flags : 5 (Sign llag), Z (Zero flag), AC (Auxiliary carry llag), P
(Parity flag), and CY (carry flag), as shown in Fig. 1.3.
o7 o6 o5 o" o3 ~ 01 o0
s z xiAclx iP i x cv
Fig. 1.3 Flag register
5-Sign flag : Aftcr the I!Xt..'Cu tiOJt of arithmetic: or logiC<tl OJX'r.tlions, if bit ~ of the
resull is 1, the sign flag i~ set. In a given byte if 0, is 1, the number wiJI be viewed as
negative number. Tf 0 1 is 0. the number will be ronsiden.>d . as positive number.
ZZero flag : Tile zero flag sets if the result of operation in ALU is zero and flag resets
if result is non zero. The zero flag is also .set if n certain register content lx.'C(,mes 7..t!'n,_)
foUowing an increment or decrement operation of that register.
AC..Auxilia.ry Carry flag : l his flag is set if there ls an overflow out of bit 3 i.e. , carry
from lower nibble to h.igher nibble (03 bit to 0 4 bit). This Oag is used for BCD operations
and it is not .wailable fo r the programmer.
P-Parity flag : Parity is defill(.-'d by the number of ones present in the accumulator.
After an a.rithmctic or logical operation if the result has nn even number of ones, i.e. even
parity, the flag is set If the parity is odd, flag is reset
CY.Carry flag : This flag is set if th~Jre is an overflow l--.ut or bit 7. The carry flilg al:o><)
serves as a botTQw flag for subtraction. In both the ('Xamples s hown below, the c.ury (ln.g
is set.
ADDinCN SUBTRACTION

9BH 1001 1011 89H 1000 1001


+ 75 H 0111 0 10 1 - ABH - 1010 10 11
C..o y ffi10 H m ooo1 0000 Borrow ffioe H m 1101 1110

c) Ins truction Register : ln a typical proces..">>r operation, the paocessor first fNches the
opcodc of instruction from memory (i.e. it places an address on the addre;.'$s bus and
memory responds by placing the data stored at the specified addn.~s on th(' dnta bus). The
CPU stores thi~ opcode in a register called lhc instruction rC'gis tcr. This opcodc is further
sent to ~ instmction decoder to scJcct one of the 256 a ltcm atin..--s.

Copyrighted material
Microproc;e,&,llors ~nil Interfacing 1 -6 An OVerview of 8085

<4. Sixteen Bit Registers


a) Program Counter (PO : Prob'Tam is a sequence of in.o;tructions. As mt!'ntioned ea.rlier,
microprocessor fetche-s these instructions from the memory and executes them sequentially.
The program counter is a special purpo5e register which, at a given time, storL"S the
address of the next instruction to be fetched. Program Counter acts as a pointer to the next
instruction. How p rocessor increments program counter depends <m the nature of the
imHruction; for OI\C byte instruction it increments p rogram counter by one, for two byte
instruction it increments program counter by two and for three byte instruction it
increments program counter by three such that program counter always points to the
address of the next instruction.
In case of JUMP and CALL instructions, address followed by JUMP and CALL
instructions is placed in the program counter. The processor then fetches the next
instnJction from the new address specified by JUMP or CALL in~tru ction. ln conditional
JUMJ' and COI"Iditional CALL instructions~ if the condition ls not satisfied,, the proo..--ssor
increments program COUJlter by three so that it points the instruction fo llowed by
condition,U JUMP or CALL instruction; otherwise processor fetches the next instruction
from the new address specified by JUMP or CALL instruction.
b) Slack Pointor (SP) : The stack is a reserved area of the memory in the RAM where
temporary infonnation may be slored. A 16-bit stack pointer is used to hold the addn!SS of
the most recent stack entry.

1.2.2 Arithmetic Logic Unit (ALU)


The 808S's ALU rerforms arithmetic and logical functions on eight bit variables. The
arithmetic unit performs bitwise fundamental arithmetic operl"tions such as addition and
subtraction. The logic unit performs logical operations such as complement, AND, OR and
EX.OR, as well as rotate and dear. The ALU also looks after the branching decisions.

1.2.3 Instruction Decoder


As mentioned earlier, the processor first fetches the oprodc of instruction from
memory and stores this opcode in the instruction register. It is thet"' sent to the instruction
decoder. The instruction dt-coder decodes it and accordingly gives the timing and control
signals which conlrol the regisler, lhe data buffers, ALU and external peripheral signals
(explained in later sections) depending on the nature of the instruction.
The 8085 executes seven different types of machine cycles. It gives the information
about which ma chin~ cycle is currently executing in the encoded fo rm on the So. 5 1 and
10 / M lines. This task is d01"1e by machine cycle encoder.

1.2.4 Address Buffer


TIUs is an 8-bit' unidirectional buffer. It is used lo drive external high order address
bus (A 1s-A8 ). 11 is ,1lso used to tri-statt> the high order address bu.s under certain conditions
such a~ r(~ct. hold, halt, and when address liJ'a-os are not in usc.

Copyrighted material
Microprocessors and Interfacing 1 7 An Overview of 8085

1.2.5 Address/Data Buffer


This is an 3-bit bi-<lire<;tional buffer. It is tlscd to drive multiplexed address/ data bus,
i.e. low order addrcs....; bus (Ar J\o) and data bus (D,..D0 ). It bo also used to tri-sl:at(' lhe
muJtiplcx<."<i ,,ddrcss/ dnt., bus under certain conditions s uch as reset., hold, halt and when
the bus is not in lL-~.
The address and data buffers <\rc used to drive external addres.~ and d:1ta buses
respectively. Due to these buffers the address t1nd data buSL--s can be tri-stnled when they
are not in u.~.

1.2.6 lncrementer/Decrementer Address Latch


This 16-bit n..'gistcr is tascd to increment or dccrem~;nt the oont4.nts o( program counter
or stack pointer as a part o( execution of instnactions rel11ted to them.

1.2.7 Interrupt Control


The processor fetches, decodes and execUtes instructions in a sequence. Sometimes it is
ncccs...;."\ry to havc proa.:>Ssor the automaticnlly execute one of a collection of spt..>cial
routines whenever special condition exis ts within a progrl.lm or the microcomputer system.
The mClSt important thing; is that, after execution of the special routine, the program
control must be transferred h> the program which proces..<;or was executing before the
occurrence of the special condition. T!.e occurrence of this special condition is referred as
interrupt. Tiw interrupt control block has five interrupt inputs R5T 5.5, RST 6.5, RST 7.5,
TRAP and INTR and one acknow1t."tige s ignal lNT A.

1.2.8 Serial 110 Control


ln situations like, data transmission over long distance and communication with
cassette tapes or a CRT terminal, it is nectossary to tran.t;-mit data bit by bit to reduce the
cost of cabling. In setial communication one bit is transferred at a time over a single line.
The SOSS's serial 1/ 0 control provides two lines, SOD and SID lor serial communication.
The seriol output data (SOD) line is used to send data serially and serial input data (SID)
line is used to receive data serially.

1.2.9 Timing and Control Circuitry


The control cirC1.aitry in the proc.essor 8085 is responsible for all the operations. The
corttrol circuitry and hence the operations in 8085 are synchronized wJth the help of clock
s ignal. Along with the control of fetching an.d dcroding operations and generating
appropriate signals for instruction execution, control circuitry also generate~ signals
required to inte.rfac~ external devices to the processor, 8085.

Copyrighted material
Microprocessors and Interfacing 18 An Overview of 8085

1.3 Pin Definitions of 8085


Fi~. i..J ('-lJ .md (b) s how 8085 pin configua\ltion and functional pin diagram of 8085
rcspt..-:.ctively. The sir--11$ of 8085 can be classified into seven g:rou~ according to their
functions.

~
2
l
SV

""
~0
tv,...
x, Vee .. SID <
x, X, Vee
110 SOD
xz HOeD

..
28
RESETOlfT HU>A
.............
SOD Cu<{OUT) ,...,
bLa
address
y
~
"'" RT:.SET IN RST75
RSTts.S
7


""'"
~Sl7.S
READY

10/ Ii ..
RSTS..5
,.,.

ADo

AD,
.......,....
Multlpfelle<l )

RS1 6,5
1\,; ""'
READY
R5f5,5 Ro H04.0 ,.
35

NTR WR RESET IN 38
......
iNTA

"""
AD,
.....
ALE

INTA 11

..."",. "'
... ALE

...,, s,
AD2 29
33
AD,

AD, ,. 110 I M 1181

... Ro

...
AD, 31
Wif
ADo

AD,

v~,
..... 31
Fig. 1.4 (a) Pin configuration
Rt;SET OU f
"''
CIJ< 0\IT
Fig. 1.4 (b) Functional pin diagram
a) Power supply a !'\d frequency s ignals.
b) Data bus and address bus
c) Control bus
d) interrupt signals
e) Serial 1/0 signals
I) OMA signals
g) Reset signaL

Copyrighted material
Mlci'O!>'ocessors and Interfacing 1 -9 An Ove<VIew of 8085

1.3.1 Power Supply and Frequency Signals


i) Vee : II requires a single +5 V power supply.
ii) Vss : Ground reference.
ili) X, and X, : A tuned circuit like LC. RC or crystal is connected a t tlwse two pins.
The internal clock generator divides oscillator frequency by 2, therefore, to operate a
system a t 3 MHz. the crystal of tuned circuit must have a frequency of 6 MHz.
iv) CLK OUT : This s ignal is used a~ a sy~ te:m clock for other devices.. Its frequency is
half the oscillator frequency.

1.3.2 Data Bus and Address Bus


A) AD0 to AD, : The 8 bit data bus (D0 D7) is multiplexed with the lower half (Ao
A7) of the 16 bit address bus. During first part of t~ machine cycle (T1), lower 8 bits of
tnt.'lnory addn...-ss or l/0 address appear on the bus. During remaining part t.)f the m..1chi~
C)rde (1'2 and T3 ) tht."Se linL--s are used as a bi-dircction.'tl data bu:;.
8) As to AI$ : nu~
upper half of the 16 bit addn.ss <~ppea rs t)O the addrL'S.'O lines As to
These lines are exclusively used for the most significant 8 bits of the 16 bit address
A 1,s.
lines.

1.3.3 Control and Status Signals


A) ALE (Address Latch Enable) : We know that AD0 to AD, lines are multipleX<'<~ and
the lower half of address (Ao A7) is available only during T1 of the machine cycle. This
lower hall of nddrcss is also necessary during T2 and T3 o( mnchinl! cycle to access specific
location in memory or 1/0 port. This means that the lower half of an add.ress must be
la tched in T1 of the machine cyde so that it is available throughout the machine cycle. Tile
1

mtching of lower half of an address bus is done by using external latch and ALE signal
from 8085.
8) iO and WR : These sign..1J:s are basicaUy used to control the direction of the data
flow between processor and memory or l/ 0 device/port. A low on RD indicah.'S that the
data must be read from the selected memory location or l/0 port via data bus. A low on
WR i nd i cat~$ that the data rr,u$1 be written into th<' ~k-ctcd memory locntion or 1/0 port
via datil bus.
0 IOIM1 5 0 and S 1 10/M ind ict\fet' whether 1/0 opc-rt~tion or memory operation ls
:
being carried out. 5 1 and Su indicate the type of machine cycle in prog-ress.
0) READY : It is uS(.od by the microprocessor to sense whether a ~riphcral is ready or
not for dat.l transfer. lf not, the processor waHs. Jt is thus used to sync.hronire s lower
peripherals to tht- microprocessor.

Copyrighted material
Mlcroproc:.ssors and lnt.rfaclng 110 An Overv~w of 8085

1.3.4 Interrupt Signals


The 8085 has live hardware interrupt Sig1l'IIS : RST 5.5, RST 6.5, R5T 7.5, TRAP and
INTR. Tile microprocessor recognizes interrupt requests on these lines a t the end of the
current instruction execution.
The INTA (Interrupt Acknowledge) signal is used to indicate that the processor has
acknowledged an INTR interrupt.

1.3.5 Serial 110 Signals


A) SID (Serial liP Data) : This input s ignal is used to accept serial data bit by bit from
the external device.
E) SOD (Serial 0/P Data) : This is .1n output signaJ which enables the transmission o(
serial data bit by bit to the external device.

1.3.6 DMA Signal


A) HOLD : This signal indicates that another master is requesting for the use of
address bus. data bus a1\d control bu.i.
8) HLOA : This active high sig1l'll is used to acknowledge HOLD request.

1.3.7 Reset Signals


A) RESET IN : A low on this pin
I) Sets the program counter to zero (OOOOH).
2) Resets the interrupt enable and HLDA flipflops.
3) Tristates tht! data bus, address bu. and control bus. (Note : Only during RESET is
active).
4) Affects the contents of processor's internal registers randomly.
On reset, the PC sets to OOOOH which causes the 8085 to eJ<ecute the first instruction
from address OOOOH. For proper reset operation reset signal must be held low for at least 3
dock cycles. The power-on reset circuit can be used to ensure execution of first instruction
from address OOOOH.
B) RESET OUT : This active high signal indicates that processor is being reset. This
signal is synchtoni.zed to the processor clock and it can be used to reset other devices
connected in the system.

1.4 Bus Organisation


In this section we are going to see how we can use various buses of 8085. how to
demultiplex address and data bus. how to generate control signals, how to provide clock
and reset signals to 8085 and so on.

Copyrighted material
MlctoprocHoors ond Interfacing 1 -1 1 An Overview of 808S

1.4.1 Clock Circuits


The 8085 has on chip dock generator. Fig. 1.5 shows the internal block diagram of the
on chip clock generator. Tile interna l clock generator requires tuned circuit like LC, RC or
crystal. or external dock source as an input to generate the clock. The internal Tflip flop
divldc.1s the frequency by 2. Hence the operating frequency of the 8085 i.o; always hnlf of th\'
oscillator frequency.
Vcc(+ SV) - ClkOut

'-- T a
X
'
Clk
' 0

X

Fig. 1.5 Block diagram of built-in clock generotor

LC Tuned Circuit :
It is a LC rt$0n., nt tank circuit. The
resonant frequency for this circuit is given by
x,
L c~= I
f, =
2nJL(C..., +C;~ )
X:!
Where Cin, is the internal capacita.nce: and
it is normally 15 pF. The output frequency of
Fig. 1.6 LC circuit
this circuit has 10% variations. To minimize
the variations in the output frequency, U is recommended to have Cex1 at lei\St twice that
of c,. i.e. 30 pF.
RC Tuned Circuit : Fig. 1.7 shows the RC tuned
circuit. The output frequency of this circuit Is also
not exactly stable. But this circuit has an advantage
x,
that its component cost is less. c R

I-
.
Crystal Ooclllator Circuit : Fig. 1.8 shows the Xz
crystal oscillator circu..it. It is the most s table drcuit.
The 20 pF capacitor in the circuit is connected to
assure oscillator s tart-up at the correct frequency. Fig. 1.7 RC Circuit

Copyrighted material

Microprocessors and Interfacing 1 - 12 An OvOfView of 8085

SV

x, Pull-up

Crystal~ resistance

External
+-- -IX2 dook x,
8085
c-
I ~"~----i~X!
(NC)
___________j
Fig. 1.8 Crystal clock circuit Ftg. 1.9 External frequency source

External Clock :
Fig. 1.9 shows how to drive dock input of 8085 with e:xt{>mal fn:..>q ut!ncy source. Here
external clock is ;sppliccl at X1 input and X 2 input is kept open.

1.4.2 Demultiplexing A0 1 -AOo


We know th.-11 AD0 to AD7 lines are mdtiplexed and the lower h.llf of address
(A, - A7 ) is available oruy during T 1 of the machine cycle. This lower half of addr... is also
nl.'C\."SS<lry during T 2 and T 3 of machine cycle to access specific IOC<ltion in memory or l/0
port. This means that the lower half of an nddress bus must be latched in T1 of the
machine cycle, so that H is available throughout the machine cycle. Tile latching of lower
half of an address is done by using external latch and ALE s ignal from 8085. The Fig. 1.10
shows the h..'lrdware connection for latching the lower half of an address. The IC 74LS373
is an 8-bit latch, having 8 D flip-nops. The input is transferred to the output only when
dock is high. This clock s ignal is driven by ALE signal from 8085. The ALE signal is
activated only during T 1, so input is transferred to the output only during T 1 i.e. address
(A, - A,) on the AD0 to AD7 multiplexed bus. In the remaining part of the machine cycle,
ALE s ignal is disabled so output of the latch (A, - A1 ) remains unchanged. To latch lower
half of an address, in each m ..'lchinc cycle:, the 8085 gives ALE signal high during T 1 of
every machine cyde.

1.4.3 Reset Circuit


On reset, the PC sets to OOOOH which Cil\1~ the 8085 to execute the firs t inlitn~etion
from address <XXJOH. For p roper n.~t operation n.."SCt signal must be held low for at least 3
clock cycles. The power-on reset circuit can be used to ensure execution of first instruction
from address OOXJH. Fig. 1.11 s hows the power-on reset circtit with typical R, C values.
(Note : R, C values may vary due to power supply ramp up time).
Upon power-up, RESET IN must remain low for a t least 10 ms after minimum Vee has
been reached, in the circuit shown in Fig. 1.'11. Upon power up or key prClil:'l, th~ RESET
IN goes low and slowly ri.s4..--s to +SV, providing suffident time fo r th' processor to rCS<'t
the system. The diode is connected to discharg.: the capacitor immediately when power
supply is switched OFF.

Copyrighted material
Microprocessors and Interfacing 1 1 3 An Overview of 8085

IC 74LS373

ADo
AD 1
D o:-{1
ADz
CU<
AD3
AD4
ADs
AD6
AD7
G ~
Enable Output con
ALE -
Do
D,
Dz
D,
D,
D.
D.
D,
Fig. 1.10 Latchi ng cln:ult
SV

IN 4148 7SK

1000
+---~~To 8085
....
~

Fig. 1.11 Power on """'t


After RESET. 8085 loads OOOOH in PC register and clears the INTE flag. Before going to
execute interrupt service routine, it is n.ec:essary to setup certain para.rneters, required to
execute interrupt service routine. To avoid interrupt to occur before completion of these
initial requirements. alter power on or reset, INTE flip-flop is cleared to disable interrupts.
It can be enabled by El instruction alter initial settings,

Copyrighted material
Mieropt"ocessors and Interfacing 1 14 An Overview of 8085

As we know that, a fter power up or reset 8085 etches its first in.~truction (rom OIXX)H
address, and it has to be tht> first instn1ction from monitor program. Therefore EPROM
consisting o monHor prot,7"fclm must be located from address CXlOOH in any 8085
micropr<.lCt..~Sor system.

1.4.4 Generation of Control Signals


Tho~! 8085 microproc::es..'>Or pn:wides RD ai\d WR signals to initiate read or write cyde.
Because these signals arc l.lS('(j both for reading/writing memory and for reading/writing
an input device, it is necess..1ry to generate separate read and write signals for memory
and l/0 devices.
The 8085 p rovides 10/M signal to indicate whether the initiated cycle is for 1/ 0 device
o r for memory device. Us ing 10/ M signal along with RD and WR.. it is possible to
~enernte separate four control signals :

MEMR (Memory Read) : Tn read data from memory.


MEMW (Memory Write) : To write data in memory.
'i'O'R (1/0 Read) : To read data from 1/0 device.
lOW (1/0 Write) : To write data in 1/0 device.
fig. 1.12 shows the circuit which generates MEMR, MEMW, iOR and lOW signals.

8085
101!:1
R!!
I'm
-"'
_/ IIDm

_/ MEMW
'7
) lOR

= ,/ lOW

Fig. 1.12 Generation of MEMR, MEMW, lOR and lOW signals


W e know th.,t (or OR gate, when both the lnputs are low thc~nly output is low.
Table 1.1 shows the truth table used to g'>nerate MEMR, MEMW, lOR and lOW signals.
The signal 10/M goes low lor memory operation. This signal is logically ORed with RD
and WR to get MEMR and MEMW signals. When both RD ~nd 10/M signals go low,
MEMR signal goes low. Similarly, when both WR and 10/M signals ~ low, MEMW
signal 8"""' low. To generate lOR' and lOW signals for l/0 operation, 10/ M signal is fir.~t
invertc..>d and then loglCCllly ORL--<1 with RD and WR signals.

Copyrighted material
Microprocessors and Interfacing 1 -15 An Overview of 8085

10/M RO WR M EMR MEMW tOR lOW


Ro + 10/M Wii + t0/ 1\1 -RD + 10j'f:1' Wii + tO/M

0 0 0 Condit)on never exists, because RO ctnd WR signals does I'\Ot go


low simultaneousty

0 0 1 0 1 1 1

0 1 0 1 0 1 ,
0 , 1 1 1 1 1

1 0 0 Condition never exists, because RO and WR signals does not go


low si""Jitaneously
1 0 1 1 1 0 1

1 , 0 1 , 1 0
, 1 1 , 1 1 1

Table 1.1
S.1me truth table can be implemented using 3:8 decoder as shown in fig. 1.13.

y- sv
I
G Vee Yo
Y,
3:8
v,
WR A Decoder v,
Ro B v,
10lM c (74l$13a) v,
Y,
v,
~. ~

I
.l
Fig. 1.13 Generation of control signals using 3:8 decoder

1.4.5 Bus Drivers


Typically, the 8085 buses can source 400 .,.A and sink 2 mA of current, i.e . it can drive
only one m. load. Therefore, it is necessary to increa"" d riving capacity of the 8085 buses.
Sus drivers, buffers a re used to increase the driving capacity of the buses.

Copyrighted material
,

Microprocessors and Interfacing 1 - 16 An Overview of 8085

Unidirectional Buffers : I
20
As we know, the address bus is 1A1 Vee~ m
unidirectiona l. 8hit unidin.'Ction:;tl b u ff~r.
2
"'(.
IY I
I

I._, IY2

..
74lS244 is usc.->d to buffer higher address I
bus. The Fig. 1.14 ~h Ow$ the logic ,...
diagram of 74LS244. ll consists of eight , "1..
IY,
I

noninverting buffers with b'istate
'"
IY,
outputs. Each one can sink 24 mA and 1-?
,...
I
'
sourtt IS mA of current. Th ~ :c bufferS
are d ivided into two groups. The
..... zv,

12'1. 2Y,
enabling and dlsabUng ~these groups ../",
J re controlled by IG a.nd 2G lines. " ,., zv,
'
Bi-directional Buffer : "
To incr~"~se the d riving capacity of 17
..... ,... 2Y,

data bus, bi-din.""'CtiOJl<d builer is used.


Fig. 1. 15 shows the logic d iagram of the
GNO
,,
m
bi-directional buffer 74LS245, a lso called
an oct,tl bus h\tnsceivers. It consists of Fig. 1.14 Logic diagram of the 74LS244
sixteen non-inverting buffe_rs, eight for
each d irection, w ith tri--state output The d irection of data flow is controlled by the pin
DJR. Whc.n DIR is high, data flows from the A bus to the B bus; when it is low, data
flows from B to A . The act ive low enable signal and the OrR signal Me ANlA--d to activate
the bus lines. Each buffer in this device can sink 24 mA and source 15 mA of current.
20 74LS245 10
Vee GNO
2 AI
[', e, 18
Function table
3 A, a, 17


5 ~
A,
<ll- a.,
e,
18

15
Enable
ll"
Ofredion
control
OIR
Opet atiOn

,
L L 8 Data to A Bus
6
7
Ao ,. ..... .....
e.
a.
14 L
H
H
X
A Data to B Sus
ISOlation

8 A,
"" s,
13

12
H=High tevei,.L=Low levei,X=IrreleYanl
T
9 Ae
DIR ll"
a. 11

1 19
Diledion Enable
conlrol

Fig. 1.15 Logic diag"'m of the 74LS245

Copyrighted material
~andlnle<fadng 1 17 An Ov..vt.w of 8085

1.4.6 Typical Configuration


Fig. 1.16 shows schematic of the 8085 mlcroprcx..."S.iOr dcmultiplexed i'1 ddn:.'8S bus ;md
rontrul signals.

741.SJ73

J.!--.... - -...
LDw

1085A
SV

J4UI2AS

1K
I ....
8klir'Ktional

""-

-
T-.a131

d loccdlr

Fig. 1.16 Typical 8085 configuration



Microprocessors and Interfacing 1 -18 An Overview of 8085

It also shows d ock <u\d reset cin:uiht Interrupt lines whkh arc not in usc are
grotmded. This is nccess.u y bccau~efloating intetrupt line may cause false triggC'ring of
interrupt. Similarly, since the DMA controller is not used, HOLD line iot also grounded. As
~'-'C know READY signal is used to synchronize slow peripherals with the mkropn:>ees.~r.
When it is low, microproces.._.;;or enters in the wait s tate and when it is high, it indicak"S
that the memory or pl>Tipher<tl is ready to send or receive data. Here, the READY s ignal is
tied high to prevent the microprocessor from entering the wait state. ALE signal is
connected to the clock input of the latch, to latch the low order oddress in T , of the
mt'lchinc cyc.le. To control the direction of the bi..mrecti<mal buffer 74LS245, RD signal from
8085 is conncct'ed to DIR input of tM bi-directional buffer. Thus, w~ RD signal is low,
DIR is low and data flows f-rom memory or 1/0 device to the microprocessor, performing
read operation. When RD signal is high. DJR is high <'11\d data flows from microprocessor
to memory or l/0 device performing write operation

1.5 Timing and 'Contr ol


During normal operation, the microprocessor sequentially fetches, decodes and
CX(.'!Cutc;:; one ins t-ruction after another until a halt instruction (HLT) L;;. executed. Tile
fetching. decoding and t:'Xccution of a single instntction ('01\Stitutes a.n instruction cycle,
whkh oonsists of one to Hve rea.d or write operations between processor and memory or
input/output devices. Each memory or [/0 operation requires a particular time period,
c.alled m-.chine cycle. In other words, to move byte of data in or out of the
microprocessor, a madlinc cycle is rcquirt..--d. Each machine cycle consists of 3 to 6 d ock
periods/cycles, referred to as T -stales. Tiwreforc we can say that, one instruction cycle
ron..'\ists of one to five machine cycles and one machine cyd e consists of thret~ to six
T-statcs i.e. thr~ to six dock p.:-riods, as shown in the Fig. 1.17.

lhsttuction cycle

Machine cycle 1 Machine cycle 2 Machine cyde 5

T- stale 1 T state 2 T-state3 .... ...... ...... ...... . T-state6

Fig. 1.17 Relation between instruction eye'-, machine cycle and T--state
There arc Sl'Ven different types of machine cycles in the BOSSA. nucc status s ignals
10/M, 5 1 and S, identify each type as shown in Table 1.2. These signals are generated at
the beginning of each machine cycle and remained valid for th~ duration of the cycle.

Copyrighted material
Microprocessors and Interfacing 1 -19 An Overview of 8085

Machine Cyel" Status Conln>l

10/M $1 So RD WR tNTA

Opoode Fetch 0 I 1 0 1 1

Memory Read 0 1 0 0 1 1

Memo<y Wri1e 0 0 1 1 0 1

110 Read 1 1 0 0 1 1

LfO W rite 1 0 1 1 0 1

INTR Acknowledge 1 1 1 1 1 0
Sus ldte 0 0 0 1 1 1

Tabla 1.2 8085 machine cycles

Representation of Signals
Before btling to see the timing diagram, w~ wiiJ see the signals and thcjr
n...,rescntation u..-;,.."'<1 i1\ the timing diagrams.

1. Clock Signal :
The 8085 divides the dock frcqul'ncy provided at X1 and X2 inputs by 2., which is
c:aUOO operating frequency. All the operations within the 8085 are synchronized with this
operating frequency. lllerefore in the timing d iagram operating frequency clock is shown
on the top and then the signals are s hown with referen~ to opt.~ating frequency dock.
Ideally, the dock signal should be square wave with zero rise time and fall time, as shown
in the figure. But in practice, we don't get zero rise time and fall time. Therefore the dock
and other signals are always ~hown with finite rise :md fall times. Fig. 1.18 shows the
practical way of representing dock signal

(a) Ideal (b) Practical


Fig. 1.18 Clock signal representation

Sll)llle Signal :
Single signal is represented by a line. It may have status either logic 0 or logic 1 or
tri--state. The change in the state of the signal takes finite time and hence the state change
of signal is represented with finite rise time and fall time, as shown in the Fig. 1.19.

Copyrighted material
Microprocessors and Interfacing 1. 20 An Overview of 801$5

Logic 1 Log;< 1
( ((
) ))
Logic 0 ~I I
Tri-state /
\ LogicO
T,-i !.- r,-. r -

Fig. 1.19 Single signal reprHentatlon


Group of Signals :
Group of signals is also called a bus e.g. address bus and data bus. To avoid
complications in the timing diagram these signal are grouped and shown in the torm o(
block as shown in Fig. 1.20.

___,X,- 7
X 1
~ - -~..__
! 1 Tristatet-
_ _X
"-.State cnange !- Valid state- n i

Fig. 1.20 Group of signals representation


ln the group representation individual state is not considered, but the group state is
considered. Change in s~'te of s ingle signal changes the state of group. It is represented by
the cross as s hown the Fig. 1.20. The tri -~ tate condition of the group signa l~ i-. shown by
dotted lint.--s. Two straight lines repn_~nt valid state/stable- state.
In micropr~r systems, activation of signal/signals depends on the state of other
signal/signals. Such situations are shown in the timing d.iagmms with the help of specific
symbols. There are four possibilities :
Activation of a signal with the change in state of other signal.
Activation of a signal with the change in s tate of other signals.
Activation of signals with the change in sl<lte of other signal.
Activation of signals with the change in state of other signals.
Fig. 1.21 shows the representation of dependence of the signal/signals, in the timing
diagram.

Copyrighted material
Microprocessors and Interfacing , ~1 21 An Overview of 8085

'
;1 Others!
A
'-l 11 '-l
\
~ Actlva
"'-..
signal

(a) Activation of signal with the (b) Activation of signal with the
change in state of other signal change In state of other signal

(e) Activation of a signal with the (d) Activation of signals with the
change in state of othef' signals change in stale of other signals
Fig. 1.21
Signal Timings
In 8085 microprocessor, signals are activah..'<i at spedfic instant for specific time period.
Once we understand thi!', it i~ very easy to draw liming diagrams. The following St."Ction
explains wht'1' the signals are activated and for what period they ren\llin in acti\'C state.
ALE (Address Latch Enable) :
This signal is active high signal It is activated in the lx.>ginning of lhc T 1 state o( each
machine cycle, except btL~ tdlc machine cycle, and it remains active ln the T 1 state as
shown in the Fig. 1.22.

Copyrighted material
Microprocessors and Interfacing 1 -22 An OVerview ol 8085
''

- - - - - - - - - - - + ---Ma<...,.oyde2- ---f
'

Fig. 1.22 ALE activation and its period


A,- A 7 (Lower byte address) :
The lower byte of address is available on the multiplexed address/data bus (AD0-AD7)
during T 1 ~ tate of each machine cycle, except bus idJe machine cycle, as shown in Fig. 1.23.

- - - - -Machine cycle 1-------l- - - Machine cyolo 2 - - - - i

T1 I
I I
8
! I

Fig. 1.23 Lower address on the multiplexed bus


D0-D7 (Data Buo) :
The data from memory or 1/0 device and from microprocessor to memory or 1/0
device is transferred during T2 and T3-statcs. It is important to note that in read machine
cycle, data will appear on the data bus during the later part o f the Tz-state, as shown in
the fig. 1.24, where-as in write cyde data wliJ nppcar on the da~ bus at the beginning of
the T2-state, as shown in the Fig. 1.24.

I
'' '' ''
'' '
!' !'
}-------{ 0.1>
~
i ~' - X .,... ~!

(a) Fig. 1.24 Data bus (b)

Copyrighted material
~lcroprocessors and Interfacing _ _ ' 1 - 23 . An Overview of 8085

To read data from memory or l/0 d(!Vicc it is n l"CCSS.1ty to scled memory or 1/0
devire. Alter selection. devlre will put t.he dota from selecled location on the data bus.
nus action needs finil'e time. ThJs time is rck-rr(.-d to t\S acce:ss Umt " . In case of write
cycle, data is available in the regl~tcrs of the miCTOpi'OCeSI50r and H can put that data on
the data bus with zero access time.

Ao-A, 5 (Higl>er byte addres s) :


The higher byte of address 15 available on the ArA 15 bus during T 1, T 2 and T, -states
ol each machine cycle, exrept bus Idle madtine cycle, as shown In Fig. 1.25.

Fig. 1.25 Higher byto address o n A8-A1 5


10/M, So- 5 1 :

- - - - Oo<odt lo4ch -----f--- Mtmo<y <80d - - - - j

Fig. 1.26 Status s ignals


These s ignals are called s tatus s lgnols. They decide Ute type of machine cycle to be
executed. They are activated at the beginning of T 1-state of each machine cycle and remain
active till the end of t.he machine C) clc.
RD and WR :
1hese signals decide the direction of the data tr.uufer. When RO sigruaJ is active, data
is transmitted from n1emory or 1/0 device to the microprocessor, and when WR signa) is
active, data is transmitted from microprocessor to the memory or 1/0 device. Both signals
are n?vcr active at a ti~.

As we know data transfer in 8085 tak'-"S pl.,ce during T2 and TJt lhese signals are
activated during T, and T_,. as shown in the r'S 1.27.

ate
r

Microprocessors and Interfacing An Ovet'VIew of 8085


--
f - - - - - - R e a d cyde ---P---- Write eyota ------,

r, r, r,

1!0+---+.

Fig. 1.27 RD and WR signals


1.5.1 8085 Machine Cycles and their Timings
nw BOOS h.\$ :o;cvcn machlne cydcs. ThL'SC arc :
1. Op<:ode Fetch
2. Ml'mory Read
3. Memory Write
4. l/ 0 Read
5. l/ 0 Write
6. Interrupt Acknowledge
7. Bus Idle

1. Opeode Fetch Cycle :


The fi rst machine cycle of every ins truction is opcode felch cycle in which tilt? 8085
finds the nature of the instruction to be ex(.'CUtcd. In lhis mac.h.inc cycle, processor places
the contents of the Program Counter on the address lines, and through the read process,
reads the oprode of the instruction. Fig. 1.28 (a) (See Fig. on next page) shows flow of data
(oprode) from memory to the microprocessor and Fig. 1.28 (b) shows the timing diagram
for opcode ~etch machine cycle. The length of this cycle is not fixed. It varies from 4T
state;; to 6T states as per the instmction. The following section de;;crlbes the opcode fetch
w;l~ in 'llf'p by ~l r m.mncr.

Step 1 : (State T 1) In T 1 statt, th" &l65 places the contents of program rowtter on the
address bus. The rugh-order byte of the PC is placed on the A8-A 15 lines. The low-order
byte of the PC is placed on the A00 A07 lines which stays on only during T 1 Thus
microproc:e.o;or activates ALE (Address Latch En.1ble) which is used to latch the low-order
byte of the address in external latch before It disappears.
In T1, 8085 also ..,nds slants s ignals 10/M, 51, and S,. 10/M specifies whether it is a
memory or l/0 operation, 51 s tatus specifies whether it is read/write operation; 5 1 and So
togctht."'!' indici\tes read, write, oprode (etch, machine cycle opention., or whether it is in
HALT state. In opcode retd 1 m.:1<:hine cycle status s:ign.'lls a re: 10/M 0, 5 1 1, So t.

Copyrighted material
IR ~-- dill 1:
r---------------------------------------
Opoode leleh

lnstru<::tlon B c T, r, T, r,
reglsle<
(!R) 0
H
E
l I Cll
\ - 1\ - L 1\ r l
Instruction
dooodor
(!D) '
---
SP
PC

'
........................ I
'''
'''
-''
A,
Ao'::X
High order memory addresa Unspedl\od
\
I
)( oil
'
':Ao7~ADo
:r
AO,
-yLow ...., }-< Opoodo --- -- --

-
AO,
' Tuning AI.E ' Latch
- Mtm<wy
' odd"'" 1
and ~

''' ''
'
1/
t:
: A7 ALE
:
' - - - ~imcwy---------------- ' "" \
101 M
iH Stalus 10 t tlO.S0 1,S,1 Opoodefetoh }
i~
A 15
' - i

J
mli
\) I
' ~

i
IAemoty
...d
0 o.......
0
"0
b
'< - ll'ldltetes dte flow. - - lndicales address f'low
~

<0' (b) Opeode ftotch machine eye.. !1.


::r (a) Oato (opeode) !!qw from ""'mory to mlc<proc...or
~
3
Fig. 1.28
I
*"'
"'
Ml~ nd lnleffacing An Ovei'VMw of 8085

Step 2 : (State T,) In T2, low-order addre<S disappearS from the AD0 AO, lines.
(However Ao A7 remain availabl~ as they were Ia~ during T1). In T2, 80&5 scnd'i RD
signal low to enable the addressed memory location. Dle memory device then places the
contents of addressed memory location on the data bus (AD0 AO,).
Step 3 : (State T,)_During T,_ 8085 loads the data from the data bus in its Instruction
Register and raises RD to high which disables the memory device.
Step 4 : (State T4 ) In T4 , microprocessor decodes the oprode, and on the basis of the
instruction received, it decides whether to enter state T5 or to enter s tate T1 of the next
machine cyd e. One byte ins tn tctions those operate on eight bit data (8 bit operand) are
r..
ext."Ctlted in .
For example : MOV A, B, ANA D, ADD 13, lNR L, OCR C, RAL and many more.
Note : For one byte in.o;tructions which operate on eight bit data_, data is a lways available
in the internal memory of 8085 i.e. registers.

Step 5 : (State T and T 6)


State T5 and T,c.. when entered, are used for internal mkroprocessor operations
required by the in~ tn1 ction. During Ts and T61 8085 performs stack write? internal 16 bit,
and conditional return operations depending upon the type of instruction. One byte
instructions those operate on sixteen bH data (16 bit operand) are executed in T 5 and T 6
For example DCX H. PCHL, SPHL, INX H, etc.
2. Memory Read Cycle :
The 8085 ~xccu tes the memory read cycle to read the contents of R/ W memory or
ROM. The length of this machine cycle is 3-T stites (T1 T,). In this machine cycle,
processor places the addres.~ on the address lines from the s tack pointer, general purpose
register pair or program counter, and through the read process, reads the data from the
addressed memory location. Fig. 1.29 (a) (See Fig. on next page) shows flow of data from
memory to the microprocessor and Fig. 1.29 (b) shows the timing d iagram for memory
read machine cycle. Memory read machine cycle is s imilar to the opcode fe tch machine
cycle. However, they use only stales T 1 to T,_ and the stilus signal values (10/M s 0,
5 1 = I, S, = OJ appropriate for memory read machine cycle are issued in T1 The following
section describes the memory read machine cycle in s tep by step manner.
Step 1 : (State T1) In T1 state, m icroprocessor plares the address on the address lines
from stac,k pointer, general purpose register pair or program counter and activates ALE
signal in order to latch low-order byte of address.
During T 1, 8085 sends s tatus signals : 10/M =0, 5 1 = I, and S., = 0 tor memory read
machine cycle.

Copyrighted material
r---------------------------------------------j ~
'

Me"""" Road
A IR
II
p I-
t-
T, r, r,

H 1- CLK l
SPI-
PC f-
lO
--- -------
''tAD, ADo
A,s - Ae MemOf)' address J
: r t--
11mi11Q
and
ALE ''

j:h
AI.
~
-
control :
: A; Ao '
AO, - ADo - Data from memory --- !:l
---- ----~----- --------

A,. PvJ 10 II!, S,, S,. 10 / f;;hO, S 1 1, So O ~


-.
m:;

~
Memory t Data bus

I
---------
read ! L
1

0
0
"0
'<
~
- fn$1iC@..teS data flow, - - Indicates address now
<0' {a) Data now from memory to microprocessor (b) Memory read machine cycle !1.
::r
~
3
Fig . 1.29
I
*"'
"'
~-- - - - - - - --- - ------ - --------------- - -- - - -- - ----- 0

l... Memory Write

A B c r, r, r,
IR
0 E

10 '
H
SP
PC
l

'
''
'''
'''
__,''
CLK

v v v &.
i
~
' :A
--- -------
'
' ~ADo
A15 - Aa
~ Memory address
il

Timing
and
ALE
''
'' Latch ALE V\ -
.''' ,..,
conlrd
h
X..,_... X
- ................M.-.,;;;- ..........................
' "<>
A01 - A00
,..- Data from CPU
tl

10/M ~ 10/ Q a Q, S 1 0. So 1
A,s i Ae
-'

0
0
'
Memory
' ;;.
I'm
r ,..
"
write

I
"0
'<
~
cO.
::r
1tr Data bus

~ - Indicates data ftow, .. - Indicates address flow


!!.
3 (a) ON flow mlcroproc::Haor to memory (b) Memot)' wrtt maehlM cycle
Fig. 1.30
~
*"'
"'
1. 29 An Overview of 8085

Step 2 : (State T 2) In T 2, 8085 sends RD s ignal low to enable the addressed memory
location. The memory device then p laces the contents of addressed memory location on the
data bu< (AD0 -AD1).
Step 3 : (Sta1e T, ) During T3- 8085 loads the data from the data bus into specified
register (F, A, B, C, D, E, H, and L) and raises RD to high which disables the memory
device.
3. Memory Write Cycle
The 8085 executes the memory write cydc to s tore the data into data memory or ~ lack
memory. The length of this machine cycle is 3T states (T1 - T,). In this machine cycle,
processor places the address on th(' address lines from the stack pointer or general
purpose register pair and through the write process_, stores the data into the addressed
memory location. Fig. 1.30 (~ Fig. on previous page) shows the timing diagram for
memory write machine cydl'. The memory write timing dingram is s imilar to the memory
read timing diagram, except that instead of RO, WR signal goes low during T2 and T3. The
st<ltus s ignals for memory write cycle are : 10/M :: 0, S1 :: 0, 5o :: 1. The following section
describes the memory write machine cycle in step by step manner.
Stop 1 : (State T 1) In T 1 s tate, the 8085 places the add ress on the address lines from
stack pointer or ge1'\crnl purpose regio;ter pa ir and activ<'!tes ALE signal in order to latch
low~rder byte of address. During T 1, 8085 sends status s ignals :

10/M = 0, 51 = 0 and So= I for memory write machir.e cycle.


Step 2 : (State T 2) In T 2, 8085 pla<:e> data on the data bus and sends WR s ignal low fo r
writing into the addressed memory location.
Step 3 : (Sta1e T,) During T,. WR signal go..'S high, which disables the memory device
and terminates the write operation.
4, 5. 1/0 Read and UO Write Cycles
1lle 1/0 read and 1/ 0 write machine cycles are similar to the 11'\t?mory read and
memory write machine cycles, respectively, except that the 10/ M signal is high for 1/0
read and 1/0 write machine cycles. High 10/M signal indicates that it is an 1/0 operation.
Fig. 1.31 (b) and Fig. 1.32 (b) show the timing diagrams for 1/0 read and 1/0 write cycles,
respectively.
6. Interrupt Ad<nowtedge Cycle
In response to INfR s ignal, 8085 executes interrupt acknowledge !ThlChine cycle to read
an instruction from the external device. Theoretically, the external device can place any
instruction on the data bus in response to INTA. However. only RST and CALL. save the
PC contents (retum address) be-fore transferring control to the interrupt service routine.
The next &..-octions explain interrupt acknowledge cycles for RST and CALL instructions.

Copyrighted material
1:
~---------------------------------- ------ --- --- - ---,
=: f
A 8 c T,
1/0 Read

r, T,
i
IR

v v v
0 E

H l
'
0
- &

10 ' '
SP
PC

-- --- '' -------- ' 1


All
f
~

' AD, I' AD


0
A,$-
IX 1/ 0Addr

..,.,
lmlng

conlrol
ALE
1- La!Ch
ADr - Allo X 1/ 0Add } 1/00ela
-
IS
'''
',_ ---------------------------

........ '
'
~u
~
\ I
Input
' OOIIJ. $1 ,s, X 10~0 1, S, 1, SoO
OR '
device
0
0 ..,.... 4--'
~
IL
"0 1/0

I
'< rea<!
~ Data bus
<0'
::r
- lndicetes data flow, -- Indicates address flow
~
3
(a) ON flow from Input device to mJcroproceuor (b) UO read memory cycle a
Fig. 1.31
i
*"'
"'
ll:
~----------- ------------- ------ - - - - -- - - --- ---------

1/0 Write
8 c
A
IR
0 E
T, r, ..a
I -
H
SP
PC
L
CLK
v v v i
I' --- '
10 :I

--'' ------- I
AD, l1AD0
ALE
"'
''
nm~~>g
''
''
A,s ... Ae X 1/ 0Addr
-
ALE ~
on<l 1-' La1C11
''
c:onlrOI A~ - AD0
' X "o"""' Data from MPU "'
~

''
---------------------------'

A,Aa '
I
1'\lft
r'
--' IO~ M= 1,S 1 =0.S<l = 1
Output
deYi<:e OR '
10 / M, S1, So X
'
ArAo ~
1/0
wri1e J ~ Dota bus

f
0
0
"0 - Indicates data flow, - ..... Indicates address flow
'<
~

<0' () o.ta now from mlcroproceuor to output devlc. (b) 110 write machine cycle 9.
::r
~
Fig. 1.32
!...
3

*"'
"'
MicroproceHOrs and Interfacing 1-32 An Overview of 8085

Interrupt acknowledge cycle for RST instruction


Fig. L.JJ shows the timing diagram of the interrupt acknowled~ machine cyde and
cxccution of RST instruction. n,e interrupt acknowledge cycle is similar to the oprodc
fetch cycle, w ith two exceptions.
1. The iNTA signal ls activated instt-ad of the RD signal.
2. Tho status lines (10/M, S, and 5 1) are lll instead of 011.
During interrupt acknowledge machine cycle (M 1), the RSf is decoded, which initiates
1 byte CALL instruction to the specific vector location. Tho machine cycles M, and M3 are
memory write cycles that store :"'c contl"llts of the progntnl counter on the stack.. and then
a new instruction cycle lx-gins.

r, r,
M
r,
Re$1811 1nsttuc1i0n
M1
r, r,
..,r, r,
r, T,
' T, T,
ClOCK

A 8-A15
J v J v J v J vv J (SP-1)H
V' v
(SP-2)1-t
'-

I
AD4-AD1 R T --- --- --- .... 0 ,(PCH) ..., il!E
AlE_ { \ '\ '\ ...
INTR
~ 1--
INTA

OIM.s,.s,
" (1,1,1 10. ,1} (0,0.1)

1m

1'11'1 r r-

Fig. 1.33 Restart inslruction

Interrupt acknowledge cycle for CALL lnslruction


Fig. 1.34 shows the timing diagram of the interrupt acknowledge machine cycle and
execution of a CALL instruction. For CALL instruction, it is necessary to fetch the two
bytes of the CALL address through two additional interrupt acknowledge machine cycles
(M, and M3 in the 3.21). The machine cycles M, and M5 are memory write cycl.. that store
the contents of the progr>m counter on the s~1<:k, and then a new instruction cycle begins.

Copyrighted material
Microprocessors and Interfacing 1 - 33 An Overview of 8085

1.: ~ l..

~~ ;..:' 'j

)
l{
;. "
1,: >< c
I'"" ~
~ -t
;,.!' 'j
1,: ) >< ~ c :>::<

"
"
I'""
1.:
I'"'"
s1
~ >< c
---1
~
>
)
~
1>-" I
,r 1.: ~
1.: 'j >< c ><
1,.!' ) ~

t -"
1.: ~ 5 .:~

-"' !... 'j >< ;;;.


) !i ~
~
,! Q

') >< 1!1 (


I "I I -' w,l I -!' I ~
g" ~
~ ~ ~ iii 0
~
0

7. - Idle Cycle
'There are few situations where the machine cycles are neither Read nor Write. These
situations are :

Copyrighted material

Microprocessors and Interfacing 1 -34 An Overview of 8085

1. For exenation of DAD instruction (this instruction adds the contents of a s pecified
rcg:ist~ r pa ir h) the contents of Hl register pair) ten T s tates are required. This means that
after CXL>eution of opcodc fetch machine cycle, DAD instruction rcquir('S 6 extra T-stat~ to
add 16 bit (Ontents of a specified rt"gislcr pair to the contents of HL register pair . These
extra Tstatcs which are divided into two machine cycles do no t involve any memory or
1/ 0 operation. These machine cycles arc called BUS IDLE machine cycles. Fig. 1.35 shows
Bus Idle Machine Cycle for DAD instruction.

Instruction cyde of DAD lnstruotion

'Fet<h Bus Idle


T, r, r, T, T, r, r, T, r, T,

ClOCK \.J ~ \.J ~ \.J lr ~ \.J ~ \.J


ALE f\
I
AurAs X
~
I'""
A01 -A00 )6;3
tOiiii.s,.s,
I
1m

;;m __/

INTA __/

Fig . 1.35 Timing diagram for DAD lnolructlon

In the case of DAD, these Bus Idle cycles arc s imilar to mt.>mory road cycles, except RO
and ALE s ignal'\ are not activated.
2. During internal opcode generations, for TRAP and RST interrupts, 8085 executes Bus
Idle Machine Cycles. Fig. 1.36 shows the Bus Idle Machine Cycle for TRAP. In response to
TRAP interrupt, 8085 enter> into a Bus Idle Machine Cycle d uring which it invokes restart
instruction, stores the contents of PC onto the stack and p1aces ()()24_H (Vector addrcs."'i of
TRAP) onto the progrnm counter.

Copyrighted material
Microprocessors and Interfacing 1. 35 An OvOfView of 8085

M t(OF) M1(81) M2(MW)


SIGNALS
r, T, T, r, r, T, r, r, T, r,
ClOCK

TRAP
f._/1
sv v v v v \J \J \J

10/M

s,.s,
......... 0'<-'" ""'
($P.1)l

IN OUT OUT IN
A00 A01 --- PC' --- - f-- -- ---- ""'" PCH

AI.E h h
tNTA

1m
1-'
\VI!
READY
I

Fig. 1.36 Bus idle machine cycle for trap


The nwnber of machine cycles required to fetch complete instruction depends on the
im~tructiot\ type :
I. One byte 2. Two byte or 3. Three byte
One byte instruction doesn't require any additional machine cycle. Two byte
in.~tructi on r~uires one additional memory read machine cyd~, whe:rea.o; three by'te
instruction requires two additional memory read machine cycles.
The number of machine cycles required to execute the instruction depends on the
particular instruction. 1he total number of machine cycles required va_ries from one to five.
Jt is possible that memory read and memory write madline cycles occur moi"C than once in
a single instruction cycle. The following examples illustrate the timing diagroms and
machine cycles used for few 8085 instructions.

1.5.2 Concept of Walt States


In some applications, speed of memory system and l/0 :,-ystem are not compa tible
with the microprocessor's timings. This means that they take longer time to read/write
data. In such situation.", the microprocessor has to confirm whcthf.."'t' a peripheral is ready lo

Copyrighted material
..
Microprocessors and Interfacing 1 - 31; An Overview of 8085

transfer data or not. lf READY pin is high. the peripheral is r('a d y otherwi~ 8085 enters
wait state.
Fig. 1.37 show~ the timing d i,1 ~nun for memory rt!ad machine ~.--ycle with and without
wait state.

MR OR lOR MROR IOR

r, r, r, r, r, TWAir
'
1-
CLK
\J \J \J ~ ~ \J \J
1-
tx:Klt'O O(MRI OFt t(JORI. s,1, &, oX
1-
0 (MR) OR I(IOA). S 1
I
I
I ,~ 0
X.
1-
1-
:X I X I
X.
OUT N OUT IN
1-
AD0 - AD 7
1-
:X,._ ., -{ o.-o, A,- A, ~ - o, } 1-~
"( \
ALE h {\ I ',....
1-

I I

READY '-- \ I '--


~ l ~

Fig. 1.37 Rnd machine cycle with and without wait state

Wait states continue to be inserted as long as READY is Jaw. After the wajt state, 8085
continues with T3 of the- machine cycle. During a wait state the contents of the address
bu., lhe data bus, and lhe conlrol bus are all held conslanl
11le wait state thew\ gives an addl'l"SS4.>d memory or 1/0 port an extra dock cycle time
lo output valid dam on lhe data bus. This feajure allows to use cheaper memory a< 1/ 0
dl~ices that have longer aca..""'S..; times.

Copyrighted material
Microprocessors and Interfacing 1-37 An Overview of 8085

1.6 Instruction Set of 8085

1.6.1 Date Transfer Group


1. MVI r, data (8) This instruc-tion d irectly loads a specified register with an 8~bit data
given within the instruction. The register r is an 8-bit gene ral
pur-po:;.e register such as A, B, C, D, E, H and l.
Example :
MVI 8, 60H ; This instruction will load 60H directly into the B register.

2. MVI M, data (8) This instruction directly loads an 8-bit data given within the
instruction into a mentory location. The memory loc-ation is
specified by the contents of HL register pair.
Example : H =20H and L =SOH
MVI M, 40H ; This in.~truc-t:i ol\ will load 40H into
; memory whose address is 2050H.
3. MOV rd, rs This instruction et:lpies data from the source rcgl<tk.--r into destination
register. The rs and rd arc general purpose registers s uch as A.~ 8, C,
0, E. H and L The C()nten ts of the source register rema.in
unchanged after cx('C'ution of the instruction.
Example : A= 20H

MOV B, A ; This instruction wiU copy the contents


; of register A (20H) into n."'gister B.

4. MOV M, rs This instruction copies datn from the source register into memory
location pointed by the HL register pair. The rs is an 8-bit general
purpose register >-uch as A, 8, C, D, E, H and l.

Example : If HL = 2050H, 8 JOH.


MOV M, B ; This instr\lction will copy th\. con ten t~
; of B register (30H) into the n1emo r~r location
; wh<"" oddn:ss is sp<.>elfied by H L (20oOH).

5. MOV rd, M This ins truction copie~ data from rn~mory location whose addre:o:-o ito
specified by HL regis ter pair into destination register. Tht.- ronlenl..;
of the memory location remain \lnchanged. The rd is an S..bil
general purpose register such as A, B, C, D, E, H l'lnd L.
Example : HL = 2050H, content~
a t 2050H memory location = 40H
MOVC, M ; This instruction will copy the contents
; of memory location pointed by HL
; register pair (40H) into the C register.

Copyrighted material
.-
Microprocessors and Interfacing 1. 38 An Oveoylew of 8085

6. LXI rp, data (16) This iru;tn tction loads immediate 16 )it data specified within the
in..,truction into register pair or s tack pointer. The rp is 16--bit
rl!g-ister pair such as BC. DE. Hl or 16--bil stack pointer.
Example :
i. !.XI B. 1020H ; This instruction will load lOH into 6
; register and 20H in to C register.

7. STA addr Thi.s instruction stores the contents of A register into the memory
locatiOI\ whose address ls directly specified w ithin the instructiott.
The contents of A register remain unchanged.
Example : A SOH

STA 2000H ; This il\.o;truction will s tore the


; contents of A register (SOH) to
; memory location 2000H.
8. LOA addr This instruction copie:o the contents of the memory location whose
addres...:; is given within the instruction into the accumulator. Tile
contents of the memory location remain unchanged.
Example : (2000H) ~ 30H
LOA 2000H ; This instruction will copy the
; contents of memory location
; 2000H i.e. data 30H into the
; A register

9. SHLD addr This instruction stores the contents of L register in the memory
location given within the instruction and contents of H register at
address next to it. This instruction is used to store the contcnl~ of H
and l registers directly into the memory. The contents of the H and
L registers remain unchanged.
Example : H=30H, L= 60H
SHI.D 2SOOH ; This instruction will ropy
; the contents "' L register at
; address 2SOOH and the contents
; of H register at address 2SOIH,
10. LHLD addr This instruction copies the contents of the memory location given
within the instruction into the L register and the contents of the
next memory location into the H regisU!r.

Copyrighted material
Microprocessors and Interfacing 1 . 39 An Overview o f 8085

Example : (2500H) 30H, (2501H) = 60H


LHLD 2500H ; This instruction will copy the
; conte:nlo; o( memory location 2500H
; i.e. data 30H into the L register and
; the contents at memory location
; 2501H i.e. data OOH into the H register.

11. STAX rp This instn1ction copies the contents o( ACCtl.muliltor into the memory
location whtloSe address is specifit.'*CI by the sp~fi<.-'d register pair.
The rp is BC or DE register pair. Thi.o;; register pair is used as a
memory pointer. The contents of the nccumulator remain
unchanged.
Example : BC ~ 1020H, A = 50H

STAX B ; This instruction will copy the


; contents of A register (SOH) to the
; memory location Spl"'Clficd
; by BC register pnir (1020H).

12. LOAX rp This ii''IStrucliol\ copies the contents o( memory location whose
address is specified by the rcgish.'r pair into the accumulator. The rp
is BC or DE register pair. The register pair is used as a memory
poin ter.

Example : DE c 2030H, (2030H) = SOH


LOAX D ; This in.~truction wi11 copy the
; content'\ of memory location
; specified by DE register pair
; (2030H) into the accumulator.

13. XCHG TIUs instruction exchanges the con ten ts of the regis ter H w ith that
o f D and of L with that of E.
Exemple : DE = 2040H, Hl = 7080H
XCHG ; This instn1ction will load the data into registers as follows
; H = 20H., L = 40H, D = 70H and E 80

1.6.2 Arithmetic Group


1. ADD r This instruction adds the contents o f the specifi ed register to the
contents of accumulato r and s to res result U\ the atXUmulator. The r
ls 8-bit general purpose register such as A, 6, C. 0, E, H and L.

Copyrighted material
Microprocessors and Interfacing 1 -40 An Overview of 8085

Example : A = 20H, C = 30H.

ADDC ; This instructkm will add the contents of C reg:isrer~ i.e. data
; 30H to the contents of accumulator, i.e. data 20H and it will
; store the rt.--sult SOH in the accumulator.
2. ADD M This instruction adds the contents of the memory location pointed
by HL register pair to the contt..~ts of accumulator and stores rt..'SUH
in the accumulator. Tile HL register p:tir is used as a memory
pointer. This instruction affects all flags.
Example : A = 20H, HL = 2050H,
; (2050H) = lOH
ADDM ; This in..cotruction will .1dd the contents of memory loc.1tion
; pointed by HL register pair, 2050H i.e. data lOH to the
; contents of accumulator i e. data 20H and it will store the
; result, 30H in the accumulntor.
3. ADI data (8) Th.is instruction adds the 8 bit dllta given within the instruction to
the contents of accumulator and stores the result in the accumulator.
Example : A = 50H

AD! 70H ; This instruction wiU add 70H to the contents of the
; accumulator (SOH) and it will store the result in the
; accumulator (COH).
4. ADC r This lmtruction adds the contents of specified rL'gister to the
contents of accumulator with carry. This means, if the carry flag is
set by some previous operation. it adds I and the contents of the
specified register to the contents of accumulator, else it adds the
contents of the specified register only. The r is 8-bit general Plll'J'O""
register such as A. 8, C, D, E, H and L.
Example : Carry flog ~ 1, A c 50H., C 20H
ADCC ; This instruction will add the contents of C (20H) register to
; the contents of accumulator (50H) with carry (1) and
; it will store result, 71H (50H + 20H + 1 = 71H) in the
; accumulator
5. ADC M This instruction adds the contents of memory location pointed by
HL register pair to the conter\ts o( accumulator with c.1rry and
s tores tlle result in the accumulator. HL register pair is used as a
memory pointer.

Copyrighted material
Mlc:topn>cesiOI'S and lnterfaclf111 1 -41 An Overview of 8085

Example : Carry flag = 1, HL = 2050H_ A = 20H, (2050H) = 30H.


AOCM ; This instruction will add the contents of memory location
; pointed by HL register pair, 2050H, i.e. data 30H to the
; contents of accumulator, i.e. data 20H with carry flag (1).
i II will store the result (30 + 20 + 1 ~5 1 H) in the accumulator.

6. ACI data (8) This instruction adds 8 bit data given within the instruction to the
contents of accumulator with carry n.nd ston."S result in the
accumulator.

Example: A = 30H_ Crry flag = I


A CJ 20H ; This instruction will add 20H to the contents of accumulator,
; i.e. data 30H w ith <:al'Ty (1) and ~tO'I'eS the n..-sult,
; 5tH (30 + 20 + I = 51 H) in the accumulator.

7. DAD rp This instruction adds the contenl~ of the specified regislcr pair to
the contents of the HL register pair and stores the result in the HL
register pair. The rp is l~b it register pair such as BC. DE, Hl or
stack pointer. Only higher order regLter is to be specified for
register pair within the instruction.

Example: DE = I 020!-1, HL = 2050H


DADO ; This intruction will add the contents of DE register pair,
; 1020H to the contents of HL register pair, 2050H.
; It will store the result, 3070H in the HL register pair.

8. SUB r This instntction subtr-acts the contents of the specified register from
the contents of the accumulator and stores the result in the
aurnulator. The regis ter r is s.bit general purpose register such as
A, 8, C, 0, E, H and L
Example: A SOH, B 30H.
SUB B ; This ln.<truction will subtract the contents of B register (30H)
; from the contents of accumulator (SOH) and s tores the result
; (20H) in the accumulator.
9. SUB M This instruction subtracts the contents of the memory location
pointed by HL register pair from the contents of accumulator and
stores the result in the accumulator. Th~ HL register pair is used ns
a memory pointer.
Example : HL = 1020H, A = SOH, (1020H) = IOH

Copyrighted material
Microproc;euors and Interfacing 1 42 An Overview of 8085

SUB M ; This instructicn will subtract the conh..:onts of memory location


; pointed by HL r<>gister pair, 1020H, i.e. data IOH from the
; contents accumulator, i.e. data SOH and stores the result
; (40H) in accumulator.
10. SUI data (8) TI\is instruction s ubtracts nn 8 bit datn given within the instruction
from the contents of the accumulator and stores the result in the
accumulator.
Ex~mple : A= 40H,

SUI 20H ; This instruction will subtract 20H from the contents of
; accumulator (40H). It will store the result (20H) in the
; accumulator.
11. SBB r This instruction s ubtracts the specified register contents and borrow
flag from the accumulator contents. This means, if the carry flag
(borrow for subtraction) is set by some previous operation, it
subtracts 1 and the contents of the specified register from the
()ontents of ac:cumuJator" else it subtracts the contents of the
specified register onJy. The register r is 8-bit register such as A, B,
C, 0 , E, H and L.
Example : Carry flag = I, C = 20H, A = 40H
SBB C ; This instruction will subtract the con t~ ts of C register (20H)
; and carry flag (I) from the contents of accumulator (40H).
; It will store the result (40H - 20H- I e IFH) in the

; accumulator.
12. SBB M This instn1dion subtracts the contents of memory location pointed
by HL register pair from the contents of accumulator and botTOw
flag and s to.-es the r('SUit in the aCcumulator.
Exomple : Carry lias = I, HL = 2050H, A =5oH, (2050H ) = IOH.
SBB M ; This instruction wilJ subtract the contents of memory location
; pointc>d by HL register pair, 2050H, i.e. data !OH and borrow
; (Carry flag ~ I) from the contents of accumulator (SOH) and
; s tores tlw result 3FH in the accumulator (50 - 10 - 1 = 3F).
13. SBI data (8) This instruction subtracts 8 bit data given within the instruction and
borrow nag frorn the contents of accumulator and stores the result
in the accmnulator.

Copyrighted material
MlctOprocessors and Interfacing 1 43 An Overview of 8085

Example : Carry flag ~ I, A ~ SOH


SBI 20H ; This instruction wiJJ subtTact 20H and the carry Aag (1)
; from the contents of the accumulator (SOH). It will store
; the result (SOH - 20H - I = 2FH) in the accumulator.
14. DAA This instruction adjusts accumuJator to packed BCD {Binary Coded
Decimal) after adding two BCD numbers.
Example :
If, A = 0011 1001 ~ 39 BCD
and C ~ 0001 0010 12 BCD then
ADD C ; Gives A ~ 0100 101 1 ~ 4BH
DAA ; adds 0110 be<:ause 1011 > 9, A ~ 0101 0001 ~ 51

; BCD
If A ~ 1001 0 110 = 96 BCD
and D = 0000 01 11 = (17 BCD then
ADD D ; Gives A 1001 HOI 9 DH
DAA ; adds 0110 because 1101 > 9,
; A = 1010 0011 = AJH
; 1010 > 9 so adds 0110 0000
; A ~ 0000 0011 ~ 03 BCD, CF ~ I.

15. INR r This instruction increments the contents of specified register by !.


The result is stored in the same register. The register r is 8-bit
general purpose register such as A, B, C, D, E, H and L.
Example : 8 = JOH
INR 8 ; This instruction will increment the contents of 6 register
; (IOH) by one and stores the result (10 + I = IIH) in the
; same Le. B register.
16. INR M This instruction inaements the contents of memory Jocation pointed
by HL register pair by I. The result is s tored at the same memory
location. The HL register pair is used as a memory pointer.
Example : HL ~ 2050H, (20SOH) ~ 30H
INRM ; This instruction will increment the contents of
; memory location pointed by HL register pair, 2050H, i.e.

Copyrighted mat~da]
Microprocessors and Interfacing An Overview of 8085

; data JOH by one. II wiU store the result (30 + l = 3JH) at the
; same place.
17. INX '1' This instruction increments the contents of rc~;ister pair by one. 11le
result is stored in the same register pair. TI\c rp L~ n.--gister pair such
as BC, DE, HL or stacl< pointer (SP).
Example : HL = IOFFH
INX H ; This instruction will increment the contents of HL register
; pair ( IOFPH) by one. It will stnre the result
; (IOFF + I = IIOOH) in the same i.e. HL register pair.
18. OCR r This instnaction decrements the contents of the specified register by
ont.'. It s h.) res the result in till' samt> rt.ogister. The register r is 3-bit
gcner.-d purpose n.--gist('f' s uch as A, 6,~ C, D, E, H and L
Example : E = 20H
OCR E ; This in.o;truction will decrement the rontents of E register
; (201-fi by one. II will store the result (20 - I = IFH) in the
; same, l.e. E register.

19. OCR M This instruction decrements the contents of m<.'m()ry location


pointed by HL rlogister pair by 1. The HL n...or&ste:r pair is used as a
memory pointer. The result is stored in the same memory location.
Example: HL = 2050H, (2050H) = 21H
OCR M ; Thls instruction will decrement the contents of memory
; location pointed by HL register pair, 2050H, i.e. dala 21H by
; one. It will store the result (21 - I = 20H) in the same
; memory location.
20. OCX '1' This instruction decrements the contents of register pair by one. The
result b stored in tht> S<lme register pair. The rp is regi~tl~r pair such
as BC, DE, HL or stack pointer (SP). Only higher order register is to
be specified within the ins truction.
Example : DE= 1020H
DCX D ; This in.~tructjon will dt..~ent the contents of DE register
; prur (1020H) by ono and store thc result (1020 - I = lOlFH)
; in tM same? DE res,;ister pair.

Copyrighted material
Mlcrop,.,.,.ssors and Interfacing 1 -45 An Overview of 8035

1.6.3 Branch Group


1. JMP addr This instruction loads the PC with the address given within the
instruction and resumes the program execution from this location.
Example :
)MP 2000H ; This instruction will load PC with 2000H and processor will
; fetch next instruction from this address.
2. Jcond addr This instruction causes a jump to an address given in the instruction
if the desired condition occurs in the program before the execution
of the instruction. The table 1.3 shows the possible conditions for
jumps.

lnttntction code Doscrlptlon Condition for jump


JC Jump on carry CY a 1

JNC Jump on nee carry CY = 0


JP Jump on posiUve S o
JM Jump on mk'lus S 1
JPE Jump on parity even p: 1
JPO Jump on parity odd P O
JZ Jump on zero z: 1
JNZ Jump on not zero Z o
Table 1 .3 Conditional jumps

Example : Carry flag = I


JC 2000H ; This instruction wiU eal.ISe a jump to an nddrt:>SS 20JOH
; i.e. program counter will load with 2000H since CF = 1.
3. CALL addr The CALL in_o;truction is used to transfer program control to a
subprogram or subroutine. This in._"ttruction pushl..:.s the curn.~t PC
conteniS onto lhe slack and loods lhe given addn'SS into the PC.
Thus lhe prog<am conlrol is transferred to the add,.... given in lhe
instruction. St>ck pointer is decremented by two.

ExMiple : Stack pointer = 3000H.


6000H CALL 2000H ; This instruclion will store lhe address of instruction next to
6003H ; CALL (i.e. 6003H) on lhe stack and load PC with 2000H.

4. Cconcl - This instruction calls th! subroutine at the given add.rcss if a


specified condition is satisfied. Before call it sto...,. lhe addre;s of
instruction next to the call c.m the stack and dccremcn~ ~tack
pointer by two. The t>ble 1.4 shows lhe possible conditions for calls.

Copyrighted material
Microprocessors and Interfacing 1 - 46 An Overview of 8085

Instruction code Oescrlptlon CondiUon for CALL

cc Call on cany CY = 1
CNC Call on not cany CY = 0
CP Call on positive 5=0
CM Call on minus s =1
CPE Call on parity even P 1
CPO Call on parity Odd P= O

cz eon on zero z=1


CNZ Can on not zero Z=O

Table 1.4 Conditional calls


Example : Carry flag = ! , stack pointer = 4000H.
2000H CC 3000H ; This instruction will ston: the address of the next instruction
; i.e. 2003H on the stack and load the program
; counter with 3000H.
5. RET This mstruction pops the return addr (address of the ins truction
next to CALL in the main program) from the s tack and loadq
program counter with this return address. Thus transfers program
control to the instruction next to CALL in the main pmgmm.
Example If SP 27FDH and eontcnts on the stack arc as shown tht."fl

SP-+ 27FD 00

27FE 62

27FF

RET ; This instruction will load PC with 6200H and it wiU transfer
; program control to the addre<s 6200H. It will also increment
; the stack pointer by two.
6. R condition This instruction retum'> the control to the main program if the
specified condition is satisfied. Table 1.5 shows the possible
conditions for return.

Copyrighted material
Microprocessors and Interfacing 1. 47 An Overview of 8085

Instruction code Description Condition for RET


RC Return on carry CY = 1
RNC ' Re101'n on not cany CY 0
RP Retum on positive S=O
Rt.1 Return on minus S I
RPE Return on parity evon p =1
RPO Retum on parity odd P=O
RZ Return on z.ero Z I
RNZ Return on not zero ZO
Table 1.5 Conditions for return
7. PCHL Thls lrL~truction loods the contents of Hl r(.ogister pair into the
program counter. Thus the program control is transferred to the
location whose address is in HL register pair.
Example HL = 6000H
PCHL ; 1hi5 instruction wil1 load 6000H into the pn>gram rount~r
8. RST n This instruction tr.msf~rs th~ program control to the specific
memory address as shown in Table 1.6. This instruction is like a
fixed address CALL irLc;truction. Tht.."Se flxed addresses are also
referred to as vector addresses. Tile processor mu1tipli~-s the RST
number by 8 to calculate these vectt')r addresstS. BcJorc tran..Uening
the program control to the instruction following the vector address
RST instruction saves the current program counter contents on the
s tack like CALL instnKtion
Instruction code Vector Addreu
RST O Ox8 OOOOH
RST 1 lx8 = 0008H
RST 2 2 x 8 = OOIOH
RST 3 3 x8 = 0018H
RST 4 h8 0020H
RST 5 5 x 8 = 0028H
RST 8 6x8 = OOJOH
RST7 7 x8 = 0038H

Table 1.6 Vector addreues for mum Instructions


Example : SP = 3000H
2000H RST 6 ; This instruction will save the current contents of the program
; counter (i.e. address of next instruction 2001H) on U., slack
; and it will load the program counter with vector address
; (6 X 8 = 48,. = 30H) OOOOH.

Copyrighted material
Microprocessors and Interfacing 1 48 An OvMView of 8085

1.6.4 Logic: Group


1. ANA r This instruction logically ANDs the contents of the specified regi.c;ter
with the ront\!nts of accumulator and stores the result in the
accumula tor. E.1ch bit in tM accumulator is logically ANDt..".d with
the corresponding bit in register r, i.e. D<J bit in A with 0 0 bit irl
register r, 0 1 in A with 0 1 in r and so on upto 0 7 bit. The register r
is Sbit general purpose register such as A, 8, C, 0, E, H and L.
Example
; A 10101010 (AAH), B ~ 00001lll (OFH)
ANA 8 ; This instruction will logically AND the contents of 8 register
1010 1010 ; w ith the ""'ntcnts of accumulator. lt will s tore the result
; (OAH)
OOCIO 1111 ; in the ilCCumulator.

0000 1010 ~ OAH

2. ANA M Th.is instruction logically ANDs the contents of memc.uy location


pointed by HL register pair w ith tM contents of accumulator. The
resuJt is s tored in the accumulator. The HL register pair is used as a
memory pointer.
Example ; A 01010101 (55H), HL s 2050H
; (2050H) -+ 10110011 (B31i)
ANAM ; This instruction will logicaUy AND the contents of memory
0101 0101 ; location pointed by HL register pair (B3H) with the contents
1011 0011 ; of accumulator (SSH). It will store the result (llH) in
; the accumulator
0001 0001 11 H
3. ANI- This instruction logically ANDs the 8 bit data given in the
instruction with the contents of the accumulator and store5 the
result in the accumulator.
Example : A ~ lOll 0011 (B3H)
a
ANI3FH ; This instruction will logkally AND the contents
; of aa:wnulator (B3H) with 3FH. It will s tore the result (33H)
; in the accumulator.
1011 0011
0011 llll
0011 0011 ~ 33H

Copyrighted material
Microprocessors and lnterfaclng 1 - 49 An Overview of aoas

4. XRA r This instruction logically XORs lhe contents o f the specified register
with the contents of accumu1ator and stores the result in tl'\(>
accumulator. The reboister r ls 8--bit general p urpose n...ob.tcr :-;udl a:;
A, 8, C, 0, E, H and L.
Example A = 1010 1010 (AAH)
; C 0010 1101 (2DH)
XRAC ; This instruction will logically XOR the contents o f C register
1010 1010 ; w ith the oonte1\ts of accumulator. It will store the resu.lt
0010 1101 ; (87H) in the accumulator.

1000 0111 (87H)


5. XRA M This instruction logically XOR.*' the contents of memory I(.)Cation
pointed by Hl registN pair with the ront(>nts of accumulakr. T hl
HL register pair is used as a memory pointer.
Example
; A 0101 0101 (55H), HL = 2050H
; (2050H) -+ 101 1 0011 = (83H)
X!lAM ; This in:;truction will logically XOR the (Onh.: nt .. of "'"-'nh'ry
0101 0101 ; location pointed by HL register pair (2050H) i.e. doto IJ.'lH
1011 0011 ; with the contents of accumulator (55H). Il will ~tore the
; n..)~mlt (E6H) in the accumula to r.
1110 0110 = E6H
6. XRI data This instntction logically XOR~ the 8 bit daro ~.iven in the
instn1crion with the contents of the accumulatur and :->ltm:-,; tlw
result in the accumul3tor.
Example :
: A = 10110011 = (83H)
XRI 39H ; Thic; instruction will logically XOR the contents of
; accumulator (83H) with 39H.
1011 0011 ; It will !dore the n.~ul t (8 AH) in the accumulator.
0011 1001

1000 1010 = SAH

7. ORA r This ins truction log;ic41lly ORs tlw -conten ts vf ~pt.xoili...J r\.!:-;i:.h:l' with
the oontcr.ts of accumulator and stor...--s the result in thl .lC(tunul.lh lr.
Each bit in the accumulator i!' OR(od with cc-.rrl""'puud i n ~~ l'lit in
rt.-g:i~tcr r. i.e. 0.,1 b it in <
lccmnulato r i:-; ORtc-d \Vith D,, bu u1 .....~, ...:.._.,

Copyrighted material
Microprocessors and Interfaci ng 1-50 An Overview of 8085

r, 0 1 in A with 0 1 in r and so on upto 0, bit. The register r is S bit


general purpose register such as A. B, C, 0 , E, H and l.
Example ; A = 1010 1010 (AAH), B G 0001 0010 (12H)
ORA B ; This ins truction will logically OR the contents of B register
1010 1010 ; with the contents of accumu)ator. It will store the result
0001 0010 ; (BAH) in the accumulator.

1011 1010 : BAH


8. ORA M Thi:-; ins truc-tion logically ORs the contents of memory location
pointed by Hl register pair with the contents of accumulator. The
l"~ult is stored in the accumulator. The HL registP.r pair is used as a
memory pointer.
Example ; A = 0101 0101 = (SSH) HL ~ 2050H
; (2050H) .... 1011 0011 = (B3H)
ORAM ; This instruction will logically OR the oontents of memory
0101 010'1 ; location pointod by HL regis ter pair (B3H) with the contents
1011 0011 ; of accumulator (SSH). It will s tore the result (F7H) in the
; accumulator.
II II 0 111 . F7H

9. ORI data This instruction logically ORs the 8 bit data given in the in.'itruction
with thl" contents of the accumulator and s tores the result in the
accumu1ator.
Example A = 1011 0011 = (B3H)
O RJ O~H ; This instruction will logically OR the contents of accumulator
1011 0011 ; (B3H) with OSH. It will store the result (BBH) in the
ll(J(JO Ill()() ; accumulntor.

t()lt 1011 (BBH)

10. CMP r This instruction subtracts the contents of the specified register from
contents of the accumulator and sets the condition flags as a result
u( the s ubtraction. lt set-s Zt.>n> flag if A r and ~ carry flag if
A < r. The register r is S.bit general purpose register such ilS A, B,
C, 0, E, H and L.
Example : ; A 101'1 1000 (B8H) ond D 1011 100l(B9H)
CMPD ; This instruction will compare the contents of D register . ~ith

; th..- contt:nts of acct~mula tor. Here A < D so carry flag \'ill


; set a fter the execution of the instruction.

Copyrighted material
Microprocessor$ and Interfacing 1 51 An Overview of 8oS5

11. CMP M This ins truction subtracts the oon~ents of the memory location
specified by HL register pair from the contents of the accumulator
and s<!'ts the condition flags as a ~"Ult of ~mb traction. It ~ts zertt
flag if A = M and sets carry flag if A < M. The HL regis ter pair is
used as a memory pointer.
Example ; A = 1011 1000 (B8H), HL ~ 2050H
; and (2050H) 1011 1000 (B8H)
CMPM ; This instruction will compare the contents of Memory
; loca tion (88H) and the contents of accumulator. Here A = M
; so zero flag will set after the execution o the instn1ction.

12. CPI data nus instruction s ubtracts the 8 bit data given in the instruction from
the contents of the accumulator and sets the condition flags as a
result of subtraction. It sets zero flag if A = data and sets carry flag
if A < dati.
Example ; A 1011 1010 = (BAH)
CPI 30H ; This instruction will compare 30H with the contents of
; accumulator (BAH). Here A > data !1.0 n>ro and carry both
; flags will reset after the execution of the instntction.

13. STC This instruction sets carry flag = 1


Example Carry flag a o
STC ; This instruction will set the carry flag = 1
14. CMC This instruction complements the carry flag.
Example Carry flag a I
CMC ; This instruction will complement the carry flag
Le. carry flag = 0

15. CMA This instruction complements each bit of the Jccumulatur.


Example A = 1000 1000 = 88H
CMA ; This instruction will complement each bit of
; accumulator A = 0 111 0111 = ?7H

Rotate

1. RLC This instruction rotates the contents of the accumulator lcfl by one
position. Bit B, is placed in B, as well as in CY.
Example
; A 01010111 (57H) and CY I
RLC ; After execution of the instruction the accumulator c:c.mtent->
; will be (1010 l llO) AEH and carry fla~ will reset.

Copyrighted material
Microprocessors and Interfacing 1. 52 An Ove rview of 8085

2. RRC This instruction ro tates the contenn> of the accumulator right by o ne


position. Bit Bo is placed in ~ as we ll .ts in CY.
Example ; A 1001 1010 (9AH) ~nd CY 1
; After execution of th.e h,\struction the accumulator contents
; will be (0100 1101) 4DH and corry Oag will reset.
3. RAL This instruction rotates the contents of the accumulator hdt by o ne
position. Bit 0, is placed ir CY and CY i placed in s.
Example ; A 10101101 (ADH) and CY 0
RAL ; After execution of the instruc-tion accumulator contL"nts w iJJ
; be (0101 1010) SAH and carry flag will set.

4. RAR This instruction rotates the contents of the accumulator right by one
position. Bit B0 is placed in CY and CY is placed in 0,.
Example
RAR ; A 1010 0011 (A3H) and CY 0
; After f_)xCCution of the in.nruction nccumulator contents will
; be (0101 0001) SIH and carry flag will :;et.

1.6.5 Stack Operations


1. PUSH rp Thi:-- i n~tru ction decrement!; st.1ck pointer by On(.> .md copies the
higher byte of the register pair into the memory locatiOt\ pointt;..'CI by
stnck pointer. It then decrements the stack pointer again by one <:~nd
cvpics lhe lower byte of the resis ter pair into the memory location
puint"i by ~tack pointer. Th" rp is 16-bit regis t<'r petit such as BC,
Of:, H L. Only higher order n.gistcr is to be specified within the
ins truction.

Example SP 2000H, DE 1050H.


I'USH D ; 'Ibis in.~.truction will dl.~"'m4!nt th4! stack pointer (2000H) by one
(SP IFFFH) and copies the contents of D register (IOH) into the
nH.'Illflry lnci.ltion 1 FFFH. It then dt'Crcm cnt~ the;' $II'IC:k pointer agt~in
by unc (SP ;; I FFEH) and copies the contents of E register (SOH)
into the memory location 1 FFEH.

2. PUSH PSW This instruction decrements stack pointer by one and copies the
accumulator contents into the memory location pointed by stack
l'')inl\.1'. It tlwn ,k..:n.mlnls th< s tack pointer .tgain by one and
cupil.'S th\. flag n:gisll'f into the memory location poiutl.!d by tht.>
~ta..: k pointer.
Example : SP 2000H, A 20H, Flag n.'gi.ter SOH

This ins truction d ,-cremcnts the stac.k pointer (SP = 20<'CH) by one
{SP .::: IFFFH) .m._ t.:upi~.-~ lht. t.:ontcnts of th..- a ccu mul<~: lor (20H)into
the memory locatiun IFFFH. ll t..twm dl.~temcnts Lht." stack pt>i1\ler

~Copyrighted material
.. l@lf~~ssornf'd y!.rt'j!~9
~ . .,... .'h
1. 53
..
An OvervNw of-8085
".
.I
again by one (SP = 1FFEH) and copies the contents of the flag
t'cgister (SOH) into the memory location lFFEH.
3. POP rp This instruction copies the contents of memory location pointed by
the stack pointer into the lower byte of the specified register pair
and increments the stack pointer by one. It then copies the contents
of memory location pointed by stack pointer into the higher byte of
the specified register pair and increments the stack pointer again by
one. The rp is 16-bit register pair such as BC, DE, HL. Only higher
order register is to be specified within the instruction.
Example SP = 2000H, (2000H) 2 30H, (2001H) E SOH
POP B ; This instruction will copy the contents of memory location
; pointed by stack pointer, 2000H (i.e. data 30H) into the C
; register. It will then increment the stack pointer by one,
; 2001H and wtU copy the contents of memory location
; pointed by s tack pointer, 2001 H (i.e. data SOH) into B
; register, and increment the s tack pointer again by one.
4. POP PSW This instruction copies the contents of memory location pointed by
the stack pointer into the flag regis t~U and increm~ts the stack
pointer by one . It then copies the contents of memory loc-ation
pointed by stack pointer into the accumulator and increments the
stack pointer again by one.
Example : SP 2 2000H, (2000H) = 30H. (2001 H) = SOH
POPPSW ; This instruction will copy the contents of memory location
; pointed by the stack pointer, 2000H (i.e. data 30H ) into th<'
; flag register. It will then increment the stack pointer by one,
; 2001 H and will ropy the contents of memory location
; pointed by s tack pointer into the accumulator and increment
; the stack pointc:rr again by one.

5. SPHL This instruction copies the contents of Hl register pair into the s tilck
pointer. The contents of H register a rc copJed to higher order byte
of stack pointer and contl.!nts of L register are copied to the lower
byte of s tack pointer.
Example HL = 2500H
SPHL ; This instruction will copy 2500H into stack pointer. So after
; execution of instruction stack pointer contents will be 2500H.

6. XTHL This instruction exchanges the contents of memory loc.1tion pointt'xl


by the stack pointer with the contents of L register and the contents

Copyrighted material
MicfOP"OCUiors and Interfacing 1 - 54 . Ao:t Overvl~ qfJ!IM
of the next memory location with the content~ of. H ~egistq.'f~
instruction does not modify stack pointer contcnt.c;.
Eumple ; HL = 3040H and SP 2700H, (2700H) = SOH, (2701H) = 60H
XlHL ; This instruction witl exchange the contents of L register
; (40H) with the contents of memory location 2700H (i.e. SOH)
; and the contents of H register (30H) w ith the contents of
; memory location 2701 H (i.e. 60H).

Input/Output
1. IN addr(S-bit) This ins truc-tion copies the data at the port whose address is
specified in the instruction into the accumulator.

Example Port address = SOH, data s tored at port address SOH, (SOH) =10H
IN SOH ; This instruction will copy the data stored at address SOH, i.e.
; data 10H in the accumula tor.

2. OUT addr(8-bit) This instruction sends the contents of accumulator to the output
port whose address is specified within the instruction.
Example A = 40H
OUT SOH ; This instruction wiJJ send the contents of accumulator
; (40H) to the output port w hose address is SOH.

1-6.6 Machine Control Group


1. El This in:;tTuction sets the interrupt enable flip flop to enable
interrupt.,. When the microprocessor is re8et or after interrupt
ac:knowlcdgc, the interrupt enable fHpflop is reset. This instruction
1 1
iti used to reenable the interrupts.
2. Dl This instruction resets the interrupt enable flip-flop to disable
interrupts. This instruction disables all interrupts except TRAP since
TRAP is non-maskable i{lterrupt (cannot be disabled. It is always
... enabled).
3. Nol>' No operation is perfonncd.

4. ' HLT This instruction h..1.lts the proceSsor. It can be restarted by a valid
interrupt or by applying a RESET signal.

5. SIM This instruction masks the interrupts as desired. It also sends out
serial data through the SOD pin. For this instructic;>n command byte
must be lo.1ded in the accumulator.

Copyrighted material
1. 55 An Overview pf 81!~5

EJtlmple ': ! i) 1A'~ OEH '


o7 Ds Ds o4
l--"soo='-t--'s"'o"'e'-t-_.:,x ,_-+_R
::;S::.T7:..:..::.5'-I--'M"'S"'E"-+-'M=7.,_
5-l,_'"_M
= 6.:::5-ir M
"'5"'."'5-ll Register A
L-~o~~~o--L-~o~~~o~~~--~~~---~-L~o~-1 1 OEH I
SIM ; nus instruction wiJI mask RST 75 and RST 6.5 interrupts
; where as RST 5.5 interrupt will be unmasked. It will also
; dis..1ble serial output.
6. RIM This instruction copies the status of the interrupts into. the
accumulator. It a lso reads the seriitl data through the SID pin.
Example
RJM ; After execution of RIM instruction if the contents of
; accumulator are 4BH then we get following information.
0 0
' 0
' 0
,,
0 0v, 0,, 0uo
'
SID I 7.5 I 6.5 I 5.5 IE M7.5 M6.5 M5.5
0 1 0 0 1 0 1 1
i.e. a) RST 7.5 is pending
b) RST 5.5 and RST 6.5 arc masked
c) lnterrupl Enable flip -flop is set
d) Serial i/p data is zero.

1.7 8085 Interrupt Structure and Operation


.
1.7.1 Types of Interrupts
The 8085 has ~ultilevel interropt system. It supports two typ..~ of interrupts:
a. Hardware b. Software
Hardware : Some pins on. the Soss allow peripheral dcvi~ to intcrnpt th~ main
program for l /0 operations. Wh<m an interrupt occurs, the 8085 completes the instruction
it is currently executing and transfers the program C<altrol to a subroutine that services the
peripheral device. Upon completion of the service routine, the MPU returns tl) the main
program. These types of interrupts, where ~U pins are used to receive interrupt requests.
are called hardWare interrupts.
Software : In software interrupts, the cause of the interrupt is an execution of the
instruction. These are special instn:,ction.~ s upported by the microprocessor. After execution
of these instruc.tions microprocessor completes the execution of the instruction it l~
currently executing and transfers the program control to the subroutine program. Upon
completion of the execution of the subroutine program.. program contrOl returns to the
main program.

Copyrighted material
'I I ' IM.c ,..,.,_...,... and lnterf8clng
~
1 . 56 An Ovei')'~Cft~ !
' ' I ;-
1.7.2 Ove111ll Interrupt Structure .!

1.7.2.1 Hardware lnlerrupll In 80115


The 8085 has five hardware interrupts :
I. TRAP 2. RST 7.5 3. RST 6.5 4. RST 5.5 5. INTR
When any of these pins, except INTR, is active, the internal control circuit of the 8085
prod uoc-s a CALL to a pred.:termined memory loc.1tion. This memory location, where the
subroutine s tarts is referred to as vector location and such lnterrupts are called vectored
interrupts. The INTR is not a vectored interrupt It receives the address of the subroutine
from the external device.
In ~5. all interrupts except TRAP are maskable. When logic signal is applied to a
m.,~kable int\'rrupt input, the 8005 is inh!trupted only if that p..1.rticular input is enabJcd.
These interrupts can be enabled or disabled under program control. If disabled, ~
disables an intemopt request. The interrupt TRAP is nonmaskable whish means that it is
not maskable by program control. The Fig. 1.38 shows the interrupt structure of~. The

Priorily lnptll Pin Mask Veclo<


lOcations

2 _n_
ve edge
RST
7.5

M 7.5

Fig. 1.38 Interrupt structure of 8085


Copyrighted material
:. MJc:roproc:esaors and lnterfaelng 1 -57 ,. An_.OVrillow
~.lt"'-i'\.
'"' - 5
. ~fd rr .. I'
- .Vi ;,\.. .-,{if . 4
figure indicates that, the 8085 is designed to respond to edge triggering. leyel 'trlggring or
both.
TRAP : This interrupt is a nonmaskable inter.rupt. It is unaffected by any mask or
interrupt enable. TRAP has the highest priority. TRAP interrupt is edge and level
trigg(.~ed . This means that the TRAP must go high and remain high \mti1 H is
admowlcdged. ThL~ avoids fa.Lse triggering caused hy noise and transients.

TRAP

RESET tN

Fig. 1.39 Interrupt circuit for trap Interrupt


As shown in the Fig. 1.39, the positive edge of TRAP signal sets the D Oip-flop.
However, d ue to the AND gate, it is nt.>cess.1ry to sustain high level on the TRAP input.
There are two ways to clear TRAP interrupt :
1. By resetting microprocessor i.e. giving a low signal on RESETIN pin (External
signal).
2. By giving a high TRAP ACKNOWLEDGE (Internal sigl'al).
After n.-cognition of TRAP interrupt, 80&5 internally gencrah..'S a high TRAP
ACKNOWLEDGE which clear.; the flip flop. Once the TRAP is acknowledge'<!, the 8085
completes its current instruction. It then pushes the address of the next instruction i.e.
return address onto the stack and loads PC with the fixed vector ~dress 0024H. Due to
this, 8085 starts execution of instructions from address 0024H which ,is the starting "ddress
of an interrupt service routin<' for TRAP.
RST 7.S : The RST 7.S lntOrTUpt is maskable inteirupt. It has the second highest
priority. As shown in Fig. 1.3S, it is positive odge triggered and the positive edge trigger
is stored internally by the 0-flip flop until it is cleared by software reset using SIM
instruction or by internally generated ACKNOWLEDGE signal.
The positive edge signal on the RST 7.5 pin sets the D flip flop. If the rMsk bit M 7.5
is Qi.e. RST 7.5 is unmasked then 8085 completes ils current instruction. ll then pushes the
address of the next instruction onto the stack and loads PC with the fixed vector address
003C.H. Due to this, 8085 starts execution of instructions from address OOOCH which is the
starting address of an interrupt service routine for RST 7.5.

Copyrighted material
Mictopfoeeuors and Interfacing 1- 58 An Overv..w of 8085

RSl" 6.5 and RST 5.5 : The RST 6.5 and RST 5.5 both arc level triggered. These
intempn; ciln r c mas ked using SIM ins truction. The RST 6.5 has the third priority whereas
RST 5.5 has the fourth priority. The vector addresse; of RST 6.5 and RST 5.5 are 0034H
and 002CH respectively. After recognition of RST 6.5 or RST 5.5 interrupt, 8085 completes
its curn!'nt instmclion; pu<:~ the ?~ddrcss of next instruction onto the stack and loods PC
with c<.nresponding vector ,,ddress.
INTR : INTR ico a maskable interrupt, but not the vector intetTUpt. lt has the lowest priority.
The following sequcr'lcc of events occur when lNTR signal goes high.
1. The SOSS , hecks the status of INTR s ignal during execution of each instruction.
2. I( ll\'TR signal is high, then 8085 completes its cttJTC.nt instmction and sends an
active low interrupt llcknowledge signal (INTA) if the interrupt is enabled.
3. In response to the INTA signal, external logic places an instruction OPCODE on the
data bus. In the case of multibyte instruction, additjonal interrupt acknowledge
m..c,chinc :::ycles are generated by the 8085 to transfer the additional bytes into the
microprocessor.
4. On receiving the instruction, the 8085 saves tM address of next instruction on stack
and execut~ received instruction.
Note : Theoretically, the external logic can place any instruction code on the data bus
in response to the INTA. However~ only CALL and RST codes save the contents of the PC
on the stack and branch program control to the subroutine address.
Response for RST instruction : lf the external device places an opcodc for any one of
the RST instruction (RST 0 - RST 7), then 8085 pushes the contents of PC onto the stack. It
then brnncht.~ the p~ogmm control to the vector address of the corresponding RST
instruction.
.
Response for CALL instruction : If the external device places an opcode for CALL
instruction then~ generates two additional interrupt acknowledge cycles.
1. It sends an actlve low interrupt acknowJedge signal second time.
2. In response to second lNTA signal, external logic places the lower byte address for
the CALL instruction.
3. After receiving lower byte address, 8085 sends the third interrupt acknowledge
signal.
- .
4. In response to third lNTA s ignal, external logic places the higher byte address for
the CALL instruction.
5. After receiving sixteen bit address for CALL. 8085 pu.'lhes the contents of 1M PC
onto the stack and branches the program control to the b-ubroutine whose address
is received from the extema11ogic.

Copyrighted material
MlcroprocHaors and Interfacing 1. 59

Example : The Fig. !.40 shows the diagram of external Logic <that :gixcs .!he ,;RST 7
instTUction opcode on interrupt acknowledge. .

8085A
Mk::roproeessor

A0o-AD7 8
8
Three - state
mTA buffer

R
sv
INTR 5V

1
a ..... 0
Request from
CI.K ""'Lr 110 device for
an inlerrupt

I
Flip-llop

Fig. 1.40 Extei'TUII logic that gives the RST 7 Instruction opeode
External logic controls a tri-state buffer with the INTA signal i.n order to place an
opcode for RST 7 instruction. The INTA s ignal from the microproc!'S""r is used as an
Output Enable signal for the buffer as well a. reset signal for 0 flip flop. The request from
the 1/0 device is routed through the 0 fli p-flop to the INTR. The 0 flip fl o~sed to
hold the INTR signal high until 8085 gives interrupt acknowledge signal. The INTA signal
that ls generated enables the tri-state buffer whose data inputs are hardwired to the value
equal 1o the opoode fo r RST 7 (FFH) instruction. The 8085 receives this opcodc during
interrup t acknowledge cycle. After receiving the opcode 8085 pushes the contents of
progra m counter onto tt,c stack, thus saving the return address. It then branches the
program control to the address 0038H (Vector add'res5 of RST 7). Table I .7 shows the
summary of hardware interrupts in 8085.
' '

Copyrighted material
f nd<l!'!!!f; cing 1 -60 An Overview of 60"'
I>'I
'' .
. ..
'i~t:;:.;M lvi>e
.
,.,.. i'riggor Priority Masbble Vector address
TAAP Edge ana Level 1 (Highesl) No 0024H
RST 7.5 Edge 2"' Yes OOJCH
RST 6.5 Lev~' 3"' y .. 0034H
---
RST 5.5
~TR
te,-ei
l evel
"
5'11 (L.owHC)
Yes
Yes
002CH
.
~-

Table 1.7

1.7.2.2 Soltwa._ Interrupts in 8085


The 8085 has eight Mftwarc interrupts from R5r 0 to RST 7. The vector address for
ttw~ interrupts can be caJcuJated a:-. follows.

Interrupt number .x S = veclor ilddrt'S:>


For example : 5x 8 =40 =28H
:. Vector address for interrupt RST 5 is 0028H.
The Table 1.8 ~hows the vector addresses of all interrupts.

Instruction HEXc- Vector AddrH S


RST 0 C7 OOOOH
RST I CF 0008H
RST 2 07 0010H
RST 3 OF 0018H
RST 4 E7 0020H
RST 5 EF 0028H
RST 6 F7 OOJOH
RST 7 FF 0038H
'
Ta)>te 1.8 Vector addresses for software interrupts

1.7.3 Masking I Unmasking of Interrupts


As mentioned earlier, maskable interrupts are enabled and disabled under program
ront'rol. 1n this sec-tion we wHJ see how interrupts can be masked or unmasked using
p rogram control. There are four instructions used for control of interrupts :
!. El
2. OJ
3. RIM
4. SIM

Copyrighted material
Mlcropr~oro .and Interfacing 1 61 An Ovoo:view of 8085

El : Enable Interrupt
The El instruction sets the interrupt enable flip-flop, as shown in Fig. 1..38. Thus RST
7.5, RST 6.5, RST 5.5 and INTR are en.>bl<"<l using El instruction.
It is important to note that when any interrupt is lld<nowlcdgcd, interrupt cn.1b!c flip
flop resets and disables all interrupts. 1 o enable intern1pt in further process it is necessary
to execu t~ EI instruction within interrupt service routine.
01 : Disable Interrupt
The 01 instruction resets the interrupt enable flip nop, r.s s hown in Fig. 1..38. Thus H
disables RST 7.5, RST 6.5, RST 5.5 and INTR interrupts.
SIM : Sot Interrupt Mask
This instruction is used to set interrupt mask and to send serial output. Jt tTansfers the
a mtcnts of accumulator to interrupt control logic and serial 1/ 0 port. Thus it is necessary
to load appropriate contents in the 3\.\:umulator before execution of SlM instruclion.
SIM Instruction Fonnat :
Bits 0 2 will set/ reset tht: mils k bits for RST 5.5, RST 6.5, and RST 7.5 of the interrupt
mask reg-L'itcr.
Bit 3 enables th~ functioning of bits 0 2. It enables or d isables the mas king control.
Bit 4 is us.:.-..d to reset RST 7.5 n:oqucst; regardless of whe-ther or not RST 7,.r:; is masked.
Bit 5 ls don~t care.
Bit 6 enables the seria l output if it is set.
Bit 7 decides the data to be St:nt on the seriaJ output pin of 8085.

lnleaupc conttot logic

1soo 1soe 1 x I R7.5 I MSE I M7.5 I M6.5 I M5.5 I


I I
Serial output data _j I ' . 1 Mastc
If 1: serial data enable ~ ' - - - 0 Unmaal<
If 0: serial data disable Mask set enable
' - - -- - 1 MasiOnQ is enabled
o Masking is disabled

' - - - - - - - - Reset RST 7.5 IMenupt


Fig. 1.41 SIM lnstructlon lonna!

Copyrighted material
Mlcroproc:. .aon and Interfacing 1. 62 An Overview-~ eoes

Example 1 : To enable RST 6.5 and mask all other interrupts we m ust ex.ecute following
in.'itructions.

Is: I SDE
0
X

0
I :-51 I ;51 :51 ,5.51
R M: E M M M
DOH
MVI A, ODH ; Load control fonnat in accumulator
SIM ; Set interrupt mask.
Example 2 : The following instruction sequence enables RST 7.5 a nd RST 6.5 and
disables RST 5.5

I s:oI S~E X
0
I :51
R
MSE
1
I :51
M M :51 ,5.51
M
:

MVI A, 09H ; load control forma t in accumulator


SIM ; Set interrupt mask

1.7.4 Pending Interrupts


RIM : Read Interrupt Mas k
The Read Interrupt Mask, RIM, instruction loads the status of the interrupt mosk, the
pending interrup t~ and the conteniS of the scri;d inp u t datn line, SID, into the accumulator.
Thus, il is po55ible to monitor status of interrupt mask, pending interrupts and 5erial
in put. "11'\ere arc num~r of interrupts. Whl."'t"' one interrupt is being serviced, other
intemopt requests may occur. If the interrupt requests are of higher priority, 8085 branches
program control to the requested intearupt St.~vice routines. But when the interrup t
n.-qucsti arc of lower priority, 8085 store~ the information abuut these interrupt requests.
Such interrup ts are called pendi ng intenupts. The status of pending interrupts can be
monitorccl using RIM in.truction.
RIM Ins truction Form.t :
Bits Q-.2 give the status Of interrupt rnask. Logic 1 indicates the interrupt is masked.
Bit 3 gives the status of int~rrup t enable flag. If 1, interrupts are enabled.
Bits 4-6 give the status of pending interrupts.
Bit 7 gives the status of serial input data li1~.

Copyrighted material
Mic.oprocessors and lnterfaclnu 1. 63 An Overview of 8085

Pending

I ----
Senal inpul interrupts lntefrupt mask
........__ .
,.._.A--., ~ ...... ..-- ~

I SID I 17.5 I 16.5 I 15.5 I IE I


M7.5 M6.5 M5.5 I
I I
Intetrut~t MaSkS
1 = Mask. 0 = Unrna.sk
Interrupt ooablo ll.ly
1 = Enabloe, o =Disable

Pending In
1. Pending

Serial inpu1 dala

Fig. 1.42 RIM instruction format

Examp.. 3 : To check if RST 5.5 is pe1\ding; it is necessary to execute following


instructions

SID 17.5 I 6.5 I 5.5 IE M 7.5 M 6.5 M 5.5

0 0 0 1 0 0 0 0 = 10H

RIM Roa d interrupt mask and pending interrupts


ANI 10 H Ma s k all bits e xcept pending RST 5 . 5 bit.
CNZ 002CH Cal l interrupt service routine for RST S . S if it
i pendi n9 .
Example 4 : The following instruction ""'uence chLoe~ whether RST 7.5 ,is individually
moukOO or not.

liD t 7.5 I 1.5 I 5.5 IE 1;.! 7.5 M e.siMs.s


-
0 0 0 0 1 1 0 I 1 OOH

RIM ; Read interrupt mask


ANI 04H ; Mask all bits except RST 7 . 5
JNZ unmask ; Jump if not zero t eo unmask.

Example 5 : Write a program to diplay real time dock. Assume that a pt"Tiodic signal is
interrupting RST 7.5 signal after every 0.5 seconds.
Main program
MVI C, OOH ; Initialize counter
LXI H, OOOOH ; Initialize seconds , and minutes
0-IVI 0 , OOH ; Initialize hours
MVI A, OBH ;

.. Copyrighted material
Micr,oproces.sors~nd Interfacing 1-64 An Overview of 8085

Seconds= 0

lnc;rement Min count

No

and-
Display HOU'S, t.tins,

Enable anttrrupt

Fig. 1.43 Flowchart for Interrupt subroutine

Copyrighted material
lotk:topt~"'ora and Interfacing 1 -85 An OYeNiew of 1085
S!M ;
E! ; Enable RST 7,5 interrupt
HERE : JMP HERE ; Wait for interrupt.
ISR - lm.trupl ..Nice Routine
!NR C ; Increment counter
HOY A, c
CPI , 02H
JNZ LAST ; Check for 1 second
MVI C , OOH ; Reset. counter
MOV A, L ; Get seconds counter
AD! OIH ; Increment seconds counter
DM : Ad just for BCD
MOVL, A ; Save seconds counter
CP!60H ; Check fo r 60 seconds
JNZ LAST ; lf not 60 , goto display
HV! L, OOH : Reset seconds counter
HOV A,H ; Get minutes counte r
AD! OIH : Increment minutes counter
DM : Adjust f or BCD
HOV H,A ; Save minutes counter
CPI 60H Check for 60 ainutea
JNZ LAST ; If not 60, goto display
HVI H, OOH ; Reset m.1.nut.e3 counter
HOV A, D : Get hours counter
ADI OIH ; Increment hours counter
DM ; Adjust for BCD
HOV D, A ; Save hours counte t
CPI 24 H ; Ch~c k !or 24 houro
JNZ LAST ; If not 2 4, goto display
HVI D, OOH : Reset hours counter
LAST CALL DISPLAY : Call display subroutine
EJ ; Enable Interrupt
RET ; Return to main pco9ram

Revl- Questions
I. E.xp/llln thr fr<rtur of 8085.
2. Cittt tht rhri out frtq~ itnd lllllt timt, T, ~ n M>BSA opmtlitrg with Midi llj tltt folloui"g
fr"''"""' Ny$1111 : 6.25 MH;. 6.1 U MH;. 5 MH: oot/ 4 MH:..
J. List !Itt 11....., "''illm I OM, tlodr -rviotbu tmllnt.fllto. o...triW tit< pmwry fomdit>n
"' ..... wtifltr.
.. Cirt '"' ,..._ "'fWg ~ in .!085. EzpUi ..... JLrg.
5. 0... tltt fvNtiotwl - 4iogtnt "'""''""'""- .!085 "" ,.... i britf.
6. Ezplam 4tjfrmtt <OIT<ilipols OS<d loy SOIJS.
7. Why AD,.AD1 /Int:~ n ttwlliplc.nl ?
II. W1o.tt t. /Ito' ""' tl{ A l fislll I
9. Wlbtt h tllt' u~ iJf CLKOUT "'rJ RST OlfT sitmds of ,'11"1:5 prot'l':t'!()f' l

Copynghted materio~l
Microprocessors and Interfacing 1. 66 An Overview of 8085
10. Dt."ScriW Ill~ f unctkmof following pittS irr 8085.
n. READY b. IlL c. 10/M d. HOLD t. RST
11. Erploin the sig7wls used in DMA opm~tio11 in 8085.
JZ. Difitu-
1. lnslrutHon cycle 2. Machint' cycle .3. T stttlt
1.3. What is tluo necessity to haw tu.10 status lines SJ and 50 in 8085 ?
14. Explain wrlou$ nurchint tyc.lts $UJ1POrlt'd by 8085.
15. Draw rmd explain tht mrmory rtad cycle of 8085.
16. Drmu nnd explain IJtf mmuny wrltt' cytlt of 8085.
J 7. Drnw tmd uplain tire 1/0 read cycle of 8085.
JB. Ormo ond explain the 1/0 toritt cydf of 8085.
19. Explain the classijirolioll of tht instruction sd of 8085 micropi'OC't$$Or with suitable nnmplts.
20. With tlrt lrt'lp of ont" tXIItllp/(" in tJtCh ca~ explain ''"' effrct of tl1e following imtrudkms In 8085.
n. UIW addr b. ADD M
c. RST 4 d. XTHL
t . Dill! f CP 2000
g. DAD B II. IN 20H
i. RIM f. SIM
21. Write tle two woys to inWnliu stncJ.: poi11lt'T at FFFFH.
12. Compan tlw following ]'XIirs of instrudions with tltdr opcodes, o~rnlions, inslructiott bytes,
ndd~ing modt'S, ajfocUd flag-s tllld tltf m~uts.

n. MVI A, (J()N Rnd XRA A


b. SUB 8 nnd CMP 8
c. /MP 2700 tmd PCHL
d. XTHL and SPHL
t. LDA 2000H and LHLD 2000H
f. RRC and R/IR
23. Wlwt Jo you nk'lln by lutrdWQrt intmuptt?
24. Wlud do you men11 by software inturupls?
25. Explain tltt l~nrdwart interrupts supported by 8085.
26. What do you mNn by vtoml iJJt.urupts?
27. E.xplain how 8085 rtSponds to INTR int"'upl.
28. Explain IJ1e softwart illlfm~pts supported by 8085.
29. WJrat do yo' mt"On by masking lltt interrupt? How is it oduroed ;,. 8085?
JO. What do you mean by pending intrrrupts?

[J[J[J

'

Copyrighted material
2
Architecture of 8086 Microprocessor

In 1978, Intel came out with the 8086 processor. The Intel 8086 is a 16-bit
microprocessor, Implemented in N-channeL depletion load, silicon gate technology
(HMOS), and pnckag<'<l II in a 40 pin dual in line package. In this chapter, we s tudy
features, a rchJ tecturc~ rcgllj;tcr organisation, bus operation and memory segmentation.

2.1 Featu res of 8086


1. The 8086 ;. a 16-bil micropl'OC't'SSOr. The term "16-bil" means thai its arithmetic
logic unl~ lnremal registers and most of its instrucllon5 are designed to work with
16-blt blNry words.
2 The 8086 hAs a 16-bit data bus, so it can read data from or write data to memory
and ports either 16 bits or 8 bits at a time. The 8088, howevu, has an 8-bit data
bus. 10 it can only ...,.d data from or write data to memory and ports 8 bits at a
time.
3. The 8086 h.\s a 20-bit address bus, so it can directly ...,.,.. 2"' or 10148.576 (1Mb)
memory locations. Each of the 10, 48, 576 memory locations ;. byte wide.
lherefore, a sixteen-bit words arc stored in two consecutive memory locations. The
8088 also has a 2().bll address bus, so it can also address 220 or 10, 48, 576 memory
locations.
4. The 8086 can generate 16-bil 1/0 address, hence II can access 2 16 65536 1/ 0
porto.
5. The 8086 provides fourt""" 16-bil registers.
6. The 8086 h.\s multiplexed address and data bus which rtdu~ the number of pins
n<:<<d, but does tlow down the tnnsfer of dato (drawbock).
7. The 8086 requires one pha.se clock with a 33% duiy cycle to provide optimized
inlmlal tlmlng.
Range of clock rates (ref.. Fig. 21)
:ITO
are : 5 MHz for 8086
8 MHz lor 8066-2
T 10 MHz for 8066-1

Fig. 2.1 Clock eye:..


(2 1)

Gopynghted ma nrii-
Microprocessors and Interfacing 2-2 Architecture of 8086 Microprocessor

8. The 8086 is possible to perform bit, byte, word and block operations in 8086. It
perfonns the arithm(>tic and logical operations on bit, byte, word and docirnal
numbers including multiply and divide.
9. TI'te Intel 8086 is designed to operate in two mock-'S, J"'l mely the 1ninimum mode
and . t~ maximum mode. When : CJiiY. yne. 80~ a ,u . is to be lL<;t.~ in a
microcomputer system, the 8086 is usC!if if! the ri'lin.imum mode of opcrnt:ion. In
thL 'm'Ode the CP U isues the -control si~a~t'<!qtrired by memory and 110 devices.
In multiprCX"CSSOr (more than one processor in the systc m) systef1?.,.~ Oj."'Cratcs in
maximum mode. ln maximum mode, control signals arc genernted willi the help of
extcmal bus controller (8288).
10. The Intel 8086 supports multiprogramming. In multiprogramming, the code for
two or more processes Lo; in memory at the same time and is ex~uted in a
timemu ltiplc.-x..'<l fashion.
11. An interesting feature of the 8086 is that it fetches upto six instruction bytes
(4 instruction bytes for 8088) from me1nory and queue s tores them in ordl'r to
spcL-d up in~truction execution. Later we will discuss this in detail.
12. The 8086 provides powerful instruction set with the folJowing address ing modes :
Register, immediate, d irect, indirect through an index or base, indirect through the
~ur ll u( a b-ase a nd an i nd~x register, relative and implied.

2.2 A rchitecture of 8086


J:i,~o:. ~.2 ..hvw-. n block diagram of the 8086 internal ~rchitecture. It is intenlally divided
mh 1 lw<t ...,par.lk t'un<:tionnl unit~. Tht.-se arc the Bus Interface Unit (BTU) and the
Ext.'('Ution Unit (EU). Thl-'SC two hmctional units can work s.imuJtaneously to increase
:-oy~1...-m ~pt.-'\'l..i and hen~ the throughput. Throughput is a measure of number of
m~lrudiun s I.'Xl'C\Jt(.-d per unit time.

2.2.1 Bus Interface Unit [BIU)


Th., ll~ l:' int.. rt'.~o;., unit is the 8086's interfoct: to the outside world. It provides a fuJI
16-bit bi-directional data bus and 2().-bit address bus. The bus interface unit is responsible
for pt..:.rforming all external bus <'percttions, as listed bc1ow.
Functions of Bus Interface Unit

.
2. h fc lcht.~ in~lru ction fmm memory.
3. Jl n..1ds d,,ta from port/ memory.
4. 1t \\'ri ll~ d.lt,l into port/memory.
5. It ..;.upports in:-truction queuing.
V. It f' tu\'ldo.. the .1Jdn"!"S rchKatiOn facdty.

Copyrighted material
Architecture
~
2 3
'" lt ":':

(1=

)
,..-------- ~--- - -- ------- - ----- --- ------- - --- ---- - -------
BJU
~

.~
/. r .\
.,.. .
Bl>us 1 lnSJrucijon

.,..
s......

""""'
,--------- ---- ---- -- -- ~

'' ''
.............................''
Conoo
'
1-------- Sys.'em
'' EU
''
''
'
: ~
: ax p [
: ex
' OX ~
'--
\.' ......... logic Unll
/
''
'''
'--
''
'''
l I ''
' '
'
~---------------Fig.
-----
2.2--- -------
8086 -----------
Internal - ---- --- - ------'
block diagram
To implemlmt lhese functions the BJU contains lhe instnu:tion queue, segmt~nf regis ters
instruction pointer, address summer and bus control logic.

Instruction Queue
To speed up prob'Tam el(ecution, the BIU fetches six instruction bytes ahead of timt;>
from the memory. These prefetched instruction bytes a re held fo r the execution unit in . -,
group of regis ters caUOO Queue. With the help of queue it is possible to fetch~ next
instruction when current instruction is in execution. For example, current instructipn jn
execution is a multiplication instruction. ln 8086, operands for multip lication ?periltions arc
within registers. Still it requiT(.-"S tOO dock cydes to execute multiply ins truction. Like
multiplication there are number of other ins tructions in 8086 which need quite a large
number of dock cycles for execution. During this execution time the BIU ft:!tchcs the next
instruction or instructions from memory into the instruction queue instead of remaining
idle. The BlU continues this proces.~ as long M the queue is not full Due to this, execution
unit gets the ready instruction in the queue and instrUi tiori fetch time' is eliminlt'tcd. This is
illustrated in Fig. 2.J.
The queue operates on the principle first in first out (FIFO). So that the execution unit
gel~ the instructions for exccutjon in the order they are fetched. In C<l ..'W! of JUMP and
CALL instructions, instruction a lready fetched in queue arc of no usc. Hence, in thl'SC

Copyrighted material
Microprouuors and Interfacing 24

I~Jtne requittd tor P&eutiOn ol two inSttvctlons withOut ~llnl~


..,....,
;_Tme_;
S:~:~ .--:.:-,--,lro=-,-lr--::e,,. .-T"-.::-,-""Tj'::o,~~e=',::...,

OYerla~ { BIU
phases
EU I o, I E, e, o, j E3 .. .

Tirnt requir~ for tx.teuliOn Of two


1--- mtruction& becaule of pipelit'liog .I
Fig. 2.3 Plpellnlng
queue i. dumped and newly formed by loading instructions from new address
C."llieS
specified by JUMP or CALL instruction. Feature of fetching the. next instruction while the
current instruction is executing is called pipeUning.
The length of the queue should be such thot EU should get the next instmction from
the queue of the BlU immediately after the execution of the current in.~truction. To satisfy
this, number of pre-fetched instruction in the queue and hence the queue length depends
on the fetching speed and the execution s-peed. Sometime queue length nt3:Y be restricted
due to the space available on the CPU chip.

2.2.2 Execution Unit (EU)


The execution unit of 8086 tells the sru from where to fetch instructions or !data~
decodes instructions and executes instructions. It contains
Con trol Circuitry
Instruction Decoder
Arithmetic Logic Urut (ALU)
"
Register Organisation
Flag Regi~ter

General Purpose Registers


Pointers and lnde Registers
Control Circuitry, Instruction Decoder, ALU .'
The control circuitry in the EU directs the internal operations. A decoder in the EU
tTans\ates the instructions fetched hom memory into a ,series of ~ctions which the EU
performs. ALU is 16bit. It can add, subtract, ;\ND. OR, >,<qR. increment, decrements,
complement and shift binary numbers.

Copyrighted material
2-5 Architecture of 8086 Mlcrsll];rocsssqr,

2.3 Register Organisation


'The 8086 has a powerful set of registers. It includes general purpose registers, segment
registers, pointers and index registers, and flag register. The Fig. 2.4 shows the register
organisation of 8086. It is also known as programmer's model of 8086. The registers shown
in programmer's model are accessible to programmer. As shown in the fig. 2.4, all the
registers of 8086 arc 16-bit registers.

SP
15 8 7 0

A.H Al cs BP

BX BH Bl OS Sl

ex CH CL ES 01

OX DH OL $$ 8 IP

(b) Segment reglstrs {e} Flat~ reglswrs (d) Pointer and


tl'dtx regl1ters

Fig. 2.4 Registe r organisation of 8086

2.3.1 General Purpose Registers


The 8086 has four 16-bit general purpose registers labeled AX BX, CX and OX. Each
16-bit general purpose register can be split into two 8-bit registers. The letters L and H
specify the lower and higher bytes of a particular regis ter. For example, BH means the
higher byte (8-bits) of the BX register and BL means the lowe byte (8-bits) of the BX
register. The letter X is used to specify the complete 16-bit register. .
'The general purpose registers are either used for holding data; variables and
intermediate results temporarily. They can a1so be used as a counters or used for storing
offset address for some particular addressing modes. The register AX is used as 16-bit
accumulator whereas register AL (lowerbyh! of AX) is used as 8-bit accumulator. The
register BX is also used as offset s torage for generating phySical addresses in case of
certain addressing modes. On the other hand, the register CX is also used as a default
counter in case of string and loop instructions.

2.3.2 Segment Registers


The physlcal address of the 8086 is 20-bits wide to access I Mbyh! memory locations.
However, its registers and memory locations which contain logiCal aal:lresses are just
16-bits wide. Hence 8086 uses memory segmentation. It treats the I Mbyte' of memory as
divided into segments, with '..t m'a'x imum size of a segment as 64 Kbytes. Thus any location
within the segment can be accessed using 16 bits. The 8086 allows only four active

Copyrighted material
.

II
' .
b . Microprocessors and Interfacing 2-6 Architec.ture of 8086 Microproces,ort

segments at a time, as shown in the Fig. 2.5. For the selection of the four activi segments
1
the 16-bit segment registers are p rovided by the bus in terface unit (BIU) of the 8086. These
four registers are :

Address
FFFFFH

ElClra segment

Slack segment }64 K


1 Mbyte
phy$ical
memo<y
Oa la H gment }64K

Code segment }64 K

OOOOOH

Fig. 2.5 Memory segmentation and segment registers


Code s..>gmenl (CS) register, the data segment (OS) register, the s tack segment (55)
n.>gislcr, and the extra ..,gmont (E$) register. Th..., are used to hold the upper 16-bits of
the starting addresses of the four memory segments, on which 8086 works at a particular
time. For example. the value in CS identifies the starting address of 64 K-byte segment
known as rode segment. By ''starting addrcssN, we mean the lowest addressed byte in the
active code segment. Tile starting address is also known as bue address or segment base.
The BIU always inserts zeros for the lower 4 bits (nibble) in the contents of segment
regisk>r to generate 20-bit base address. For example, if the code ""gntOilt register contains
' segment will s tart at address 348AOH.
348AH, then code .
Functions of Segment Reglston
... (

I. The CS register holds the upper 16-bits of the starting address of !he ""S''enl from
which the BfU is currently fetching the instruction code byte.
2. The 55 register is u~ for the upper 16-bits of the starting address for the
program stack (all stack related instru,ctlons will operate on stack).

Copynghted matenal
2-7
IH
3. ES register and OS register are used to hold the upper 16-bits !'f the startirtg
address of the two memory segments which are used for data.
2.3.3 Pointers and Index Registers
All segment registers are t~bit wide. But it is necessary to genera te 2()..bit address
(physical address) on the address bu.<. To get 20-bit physical addn.'ss ore or more pointer
or index registers are associated with each segment register. The pointer registers IP, OP
and SP a re associated with code, data and stack segments, respectively. They hold the
offset within the code, data and stack segments, respectively. 1l1e index registers Dl and Sl
are used as a general purpose registers as wcll as for offset storage in Ctl.SC of indexed,
based indexed and relative based indexed addressing modes. The detail description of
pointers and index regi'\tcr is given in section 2..5.

2.3.4 Flag Register


A flag is a fli?""flop which indicates some condition produced by the execution of nn
instnac-tion or controls certain operations of the EU. The flag register contains nine active
flngs as shown in the Fig. 2.6.

BIT 15 14 13 12 11 10 9

I I
U Undefined

I cany Flag : Set by ClffY out ol MS8


Parity Aag : Set If resvl1 has even parity
Auxiliary Carry Rag for BCD
Zero Ftag : Set if result -a 0
Sign Flog MSB of resuft
Slogle step IOIP
lntenupe enable
Siring dire<llon
Overftow

Fig. 2.6 8086 flog register bit )>lltlom


Six. of them arc used to indicate some condition produced by instruction.
1. Cony Flog (CF) : In case of addition this Oag is set if there is a cany out of the MSB.
Th~ carry flag a lso servt..os as a borrow flag fo r subtraction. In case
of subtraction it is set when borrow is needed.

2. Parity Flog (PF) : II is set to I if result of byte operation or lower byte of the word
operation contain an even number of ones; otherwise it is zero.
3. Autlllary Flag (AF):This nag is set if there is an overflow out of bit 3 i.e., carry from
lower nibble to nigher nibble (03 bit to D, bit). This flag is used for
BCD operations and it is not ovailable for the p rogrammer.

Copyrighted material
2-8 Architecture of 8088 MICrot>fOC!tM!!'

4 . Zero Fl"11 (ZF) : "rhe zero flag sets if the result of operation in ALU i.s zero and
flag resets if the result is nonzero. The zero flag is also set if a
certain register content becomes zero following an increment or
decrement operation of that register.
5. Sign Flog (SF): After the execution of arithmetic or logical operations, if the MSB
of the result is 1, the sign bit i.s set. Sign bill indicates the result is
negative; otherwise it is positive.

6. Ove rflow Flag (OF):This flag is set if result is out of range. For addition this Rag is set
when there is a carry into the MSB and no carry out of the MSB or
vice-versa. For subtraction, it is set when the MSB needs a borrow
and there is no borrow from the MSB, or vice-versa.
,. Example 1 Givt> tlr~ contents of tile flag registtr after txtcution of following addWon.

0110 0101 1101 0001


+ 0010 0011 0101 1001
1000 1001 0010 1010
Solu1ion : SF s 1, ZF = 0, PF = 1, CF = 0, AF = 0 , OF = I
,... ~ample 2 ; GiVt' tiJr c.ontents of lire flag register after exution ofJollowi11g subtmctN:m

0110 0111 0010 1001


- 0011 0101 0 100 1010
0011 0001 1101 1111
Solu1ion : SF 0, ZF = 0, PF = I, CF = 0, AF = 1, OF = 0
The three remaining flags are used to control certain operations of the processor .

1. Trap Fl"11 (TF): One way to debug a program is to run the program one
instruction at a time and see the contents of used registers and
memory variables after execution of every instruction. This
process is called 'single s tepping' through a p rogram. Trap Rag is
used for single stepping through a p rogram. If set, a trap is
executed after execution of each instruction, i.~. interrupt service
routine , is executed which displays various registers and memory
Vt\riable contents on the display after execution of eac"
instruction. Thus programmer can easily trace and correct erTors
in the program.

Copyrighted material
...

M(.Cr6~8cesiors and Interfacing 2-9 Architecture-Cit- Mll*oprocesscilll

2. Inte rrupt Flag (IF) : It is used to allow /prohibit the interruption of a program. If se~ a
certain type of intemapt (a maskable interrupt) can be TE.'COb'11ized
by the 8086; otherwise, these interrupts are ignored.
3. Direction Flag (OF) :It is used with string instructions. If OF = 0, the string is
processed from its beginning with the first element having the
lowest address. Otherwise, the string is processed from the high
address towards the low address.

2.4 Bus Operation


The 8086 has a common address and data bus. The address and data are time
multiplexed, i.e. address anti data appear on this bus at diff~erit time interva ls. Thus bus
is commonly known as multiplexed address and data bus. The multiplexed address and
data bus provides the most efficient use of pins on the processor wtti.Jc pennitting the use
of a standard 40-Jead package. This multiplexed address and data bus has to be
demultiplexed externally with the use of latches and the ALE signal p rovided by 8086.
This bus can be buffered directly and used throughout the sys t~ with address latching
provided on memory and 1/ 0 modules or it can be demultiplexed at the processor with a
single set of address latches if a standard nonmultiplexed bus is desired for the system.
The control operation of 8086 is different in two different modes : minimuni mode and
maximum mode. The 8086 provides some signals which have d iflerent meanings in
minium mode and maximum mode. The minimum mode is used for a smaiJ systems with
a single processor and maximum mode is for medium size to large systems~ whkh often
include two or more processors.

2.5 Memory Segmentation



Two types of memory organisations are commonly used. These are linear addressing
and segmented addressing. In linear addressing the entire memory space is available to
the proces..'iOr in one linear array. In the segmented addressing, on the other hand, the
available memory space is divided into "chunks" called segments. Such a memory is
known as segmented memory. In 8086 system the available memory space is lMbytes.
This memory is divided into 'number of logical segments. Each segment is 64 K bytes in
size and addressed by one of the segm~.mt registers. The 16--bit contents of the segment
register gives the starting/base address of a particular segment, as shown in Fig. 2.7. To
atidress a specific memory location within a segment we need an offset address. the offset
address is also 16-bit wide and it is proVided by one of the associated pointer or index
register.

Copyrighted material
, l\liC:roproce$Sors jltW ll)lrfllclng 2 - 10 Architecture ot 8086 Microprocessor

""''Oiall " '"'"''"


im'FFI1 - ,!, -- - - - - - ,] - Htgh..l add<e.ss
7FfFF11 T - Top a( eltlla s9gmen1

6-tV.

7(XJOOH j_ f-- ------1 - EJ!tra 5eQ1'1'ienl base ES = 7000H

5FFFF1-t T f--------1 - Top or stack. segment

6 K

50000Hl f--------1 - Sta<lt segment t>aso SS ~ 5000H


"89FH T - Top or code "'9"""''
64 f(

348AOH 1 1-------l - Oode segmMl base CS-= 348AH

2FFFFH T f--------1 - Top oldala U'll'l'Onl

64 K

~~ 1 1-----;
~V\,IV\I'n -
---old
!;IV\'""'" ate segment
OOOOOH
Ph\ Sk:al momoty
Fig. 2.7 Memory segmentation
Rules for Memory Segmerotatlon

1. Th~ four segments can overlap (or small programs. ln a minimum system -all our
segments can start at the address OOOOOH.
2. Tit SL>grnent (an ll.>gin/Stort a t any m<!ntory address Whic:h is divisible by 16.
Advantages of Memory Segmentation

1. It allows the memory addressing capacity to be I Mbyte even though the address
associated with individual instruction_is only H)bit.
2. It allows instruction code, data, stack,. and portion of program to be more than
64 KB long by using more than one code, data, s ta<k segment, and extra segm<nL
3. lt fadlitares use of separate memory areas for program1 data and stack.
11. ll permits a p1ogram or its data to be put in different areas of memory, each time
the program is executed i.e. program can be relocated which is very useful in
muJtiprogramming.
MiCiOP<ocessOr.ianillnterfKing 2 11 Architec:tu,.. of 80118' Mlcroj!~-

O.neratlon of 20-blt Address

To access a spt..">Ciftc memory II)C(Itiun , from any segment we RL--ed 2Q..bit physicnl
address. The 8086 generates this address using the contents of segment register and the
offset register associated with il Let us b(.>e how 8086 access code byte within the code
segment
We know that the CS register holds the base addross of the code S<'8Jll"nt. 'llw 8086
provides an instruction poinh.r (IP) which holds the 16-bit addl'\..>ss of the next Ct..-xtc byte
within the code segment. The value contained in the IP is referred to as an offset. Tilis
value must lx> ofls<!t from (added to) the segment b - addr<'SS h CS to produce the
required 20-bit physical address.
The content. of the CS register are multiplied by 16. i.e shifted by 4 pusition to the
left by i.J\SC.'tting 4 uro bits and th~n the offset i.e. the contents of fP register are t:tdd&1 to
the shifted contents of CS to generate physical address. As shown in the Fig . 2.8, the
contents of CS register are 348AH, therefore the shifted con ten~ of CS register are
348AOH. When the BJU odds the ofO..,t of 4214H in the IP to thi starting oddress, we get
38A84H as a 20-bit physical address of memory. TI>is is illustrated in Fig. 2.8 (b).

Prl~l AddrH&M

r======~- Top

t-----1 -
of c::oOe aegment
4<489FH

Cocle.,..-
cs 13

Physieal8dclr\liS I~
e2 I 0
e
" .
A - implied zero
-)
4 zero bits

I
-
IP 4214H
CS 2 $48AH - $&111 of Code segment

(I ) (b)

Fig. 2.8
We have S<.'<.'l\ that how 20-bit physical add"""' is generated within the code segment.
In the similar way the 20-bit physical o'kidn.oss is generab..-'d in the ot.h..-r :;t."gmcnb.
However, it is important to note that each segment rc.:.quires particular St.--gment regi'iter
and ofls<!t r<>gistcr to generate 20-bit physical address.
Pointers and Index ReglstlfS

All ~o:rl\L"'\1 n.-gl:-;tc~ are 16--hit. But it is m-~s..1ry to plif 2()..bit addn.>s~ (phy~kal
addtes.~) on th<.- addn.-ss bus. To gt.'t 20-bit physical addn...~ one mon. n.'glstcr is a,:....~ah..'(l
with C'nch ~-ogmen t r(.'gister the way IP is associated with CS.
ThL'SC ad dition.1l l"l'glSh.rs belong to the poi1ltl't l\l'ld ind<.'x broup. Th-. pointt."r 1.1nd
inde-x group consisl, of ins truction pointer (ll'), s tack pointer (SP), BJ> {base pointer),
~l&r'C\. ind t.X (SI) and dt."":'ttin.ltion index (01) l'l>gi~tl'rs.

Copyrighted material
Microprocessors and Interfacing 2 - 12 Architecture of 8086 Microprocessor

Stock Pointer (SP) : The s tack pointer (SP) register contains the 16-bil offset from the
start of the segment to the top of s tack. For stack operation, physical address is produced
by adding the contents of s tack pointer register to the segment base address in SS. To do
this the contents of the s tack segment register are shifted four bits left and the contents of
SP are added to the shifted result. If the contents of SP arc 9F20H and SS are 4000H then
the physical address is calculated as follows. (Refer Fig. 2.9)
SS =4000H after shifting fou r bits left SS =40000H
Now
ss 40000H
+ SP 9F20H
Physical nddress 49F2QH

f-----j - End of stack s.egment 4FFFFH

.SP =9F20H

SS -= 4000H
1 1 - - - 1 - Topotstadt49F20H

1---1 - Start of stack segment 40000H

Fig. 2.9 Stack and stack pointer


BaM PolntiH'", Source Index and Outlnatton Index (BP, Sl and 01)

These three 1()-.bit registers c-an be used as general purpose registers. However, their
main use is to hold the 16-bit oft.et of the data word in one of the segments.
Base pointer : We can use the BP tegistcr instead of SP for accessing the stack using
the based addressing mode. In this case, the 20-bit physical stack a<ldress is calculated
from BP and SS. Addressing modes are dio;cussed in later section.
Soutu Index : Source index (51) can be used to hold the ofll!et of a data word in the
data segment. In this .case, the 20.bit physic.'! data address is calculated from 51 and OS.
Destination Index : The ES register points to the extra segment in which data is
s tored. String instnactions always use ES and 01 to determined the 20-bit physical address
for the destination.
Defauh and Alternate R1111iater Assignments

Table 2.1 shows that some memory references and their default and alternate segment
definitions. For example, instruction codes can only be stored in the code segment with IP
used as an oft.et. Similarly, for stack operations only SS and SP or BP registers can be
used to give segment and offset addresses respectively. On the other hand, for accessing
general data, string source, data pointed by BX and BP registers; it is possible to use
alternate segments by using segment override prefix. See examples given after Table 2.1.

Copyrighted material
Mlcroproc:eoaors and lnt.rfacin9 2-13 Archltectu,. of 8086 Mlcroprocnoor

Ty.,. of llomory Defou~ Segment A~I'Nite Segment 011. .1 {Loglcol


RAifo<onco Addro")

Instruction fetch cs N..,. IP


Stack _.tlon ss None SP.BP
General data OS cs. es. ss E1fedtve address

String source OS cs. es. ss Sl

String destination ES None 01

ex used as pointer OS cs. es. ss Etfective address

BP used as pointer ss CS. ES. Os Effective ad<Wess

Tobie 2.1 ~ult and altamn reglawr assignments


For the folJowtng t:!xamples we have assumed
CS IOOOH, OS = 2000H, SS = 3000H, ES = 4000H, BP = 0010 H,
BX = 0020H, 5P = 0030H, 51 = OOIOH, OJ = 0050H

Example 3 :

1) MOV AL, [BP)

This instruction copies a byte from memory


3000@1 H SS
location to the AL register. The effective address for
+ 001 0 H BP
the memory location is contained in the BP register.
Phyajcal Address 3 0 0 1 0 H
By defaul~ an effective address is added to the stack
segment (SS) to produce the physical memory address
{30010 H).

2) MOV CX, [BX)

This instruction copies a word from memory


2 000@)H OS
+ 002 0 H BX location to the ex register. The effective address is
Pllysical Addr... 2 0 0 2 0 H
contained in the BX register. By default an effective
address is added to the data segment {OS) to
produce the physical memory address (20020 H).
3) MOV AL, [BP+SI)
001 0 H 81' This instruction copies a byte from memory location
+ 004 0 H Sl
to the AL register. The effective address Is the
EWectiYeAddreaa 0 05 0 H
summation of the contents of the BP and 51 register.
The effective address is added to the slack
3000@)H SS
+ 005 0 H EA segment (SS) to get the physical addr.,...
PllyliceiA<Idreu 3 00 5 0 H

Copyrighted material
Mlc.....-.sson a nd Interfacing 2-14 Archile.c ture of 8086 Microprocessor

4) MOV CS : [BX], A L

This instruction copies a byte from th(.' AL register


1 000@]H CS to a memory location. The effectjve address for the
oo 2 o H ex memory location is contained in the BX register. By
Physk.al AddteS$ 1 0 0 2 0 H default an effective address in BX will be added to the
data segment (OS) to produce the physical memory
address. In this instruction, the CS: in front of (BX)
indicates that we want BJU to add the effective address to the code segment (CS) to
produce lhe physical a.ddrcss. The CS: is caJied segment override prefix.
S011ment Override Prefix
1he segment override pre~ allows the programmer to deviate from the default
segment. The segment override prefix is an-additional S..bit code which is put in memory
before the code lor the ""'t of the instruction. This additional code selects the alternate
segment register. The code byte for the segment override prefix as the format OO!XXllO.
The XX repres<.>nls a 2 bits which are as foUows : ES =00, CS =01, SS = 10 and OS = II. It
is impt')rtant to note th.'\t the segment override prefix may be added to almost any
insb"uction in any nenlory addressing mode.

Review Questions
1. U# lit<jnJt11m of 8086 microprtX'r'$$dr.
2. Explai" tllt" ardrit~~tun> of 8086 processor <viti! tilr lw.lp of u(dt block dillgranr.
3. What is 111,~ Jimrticm of bus lnkrfudns 1111il ?
4. What i-s t/11 instruction que.u~ ? x11/ain its ndnwtage.
5. Wllat is pipt'litring ?
6. E.xplai" tl1r l'fS;Strr <H'8f'11i..;;..ttio" of 80$6.
7. Wlwll Art segment rtgisltrs ? Explain tlrt f.mr~ of tlwm.
8. xplai11 tllf p11rpo5C' of polnt,-rs and indl!X rtghtm.
9. WINJt is tilt' Junctiou of flag reyi.!itt!r ?
10. H4l pl1ysiarl nddrt$$ ;s gnrmtt~ in 8086 l
1J. Draw tilt' bit pcttttnr for flng rtgisln- of 8086 and explain tire signiflcanc:t of tach bit.
12. List lilt rum for mmrory segmentation.
J.t Wllot tua~ th( n.1m11111gt'$ of ushr,l( mt'fnory ~mmtation ?
14. Wlral do Y""' m~"'m by imkx n-shifl"rs ?
15. Wlftlt llrt tM fimt1ions of 51 and Dl rt:giSlt'TS ?

ODD

Copyrighted material
3
8086 Instruction Set and
Assembly Language Programming

3.1 Introduction
The 8086 instn1<:tion set includes .._--quivaJents of the 8085 instructions plus many fl('W
ones. Tht:' 1tew in$tructions cont.lin operations such as signed/unsigned multipli01ti0n and
division, bit manipulation instruction"i, string instructions, and interrupt instruction....
11\e 8086 has approximately 117 different instructions with about 300 opct:x:les. The
8086 inst.ruction set oont.1ins no operand, single operand, and two operand in.o::;tructions.
Except for string instructions which involve array operations, the 8086 instructh'ms do not
permit memory to memory operations.
In this chapter we study the addrt>$$ing modes, instruction S(!t of 8086 and assembler
directives.
3.2 Addressing Modes
We have seen how the 8086 fetcht-'S code bytes from memory by generating 2().bit
physical addr~ with thE;> help o f IP ;mel CS. We hiiVe also St'-'11 how the 8086 a<..'\..'{_'8..""-~ lhc
stack u~ing SS and SP. In this St.Ytion we will sec the- di/fet'l-'lll ways that an 8086 can
access the dam. The different ways thnt a processor can access data are reft!m.:.d to as
addressing modes.
The addn."SSing modes o( any processor can be broodly classified as :
Data add.n.ssing modes.
.
Program memory addressing modes.
Stade ~"mory addn...~sing modes.

3.2.1 Data Addressing Modes


1'he data addressing modL"S can hl further cla."-~lfiN as
I. Addressing modes for accessing immediate and register data (n.-gistcr and
iouru!diate modes).
2. Addressing modeti for acces.o;ing data in mt..omory (memory modes).
3. Addn.,.sing mock., for ocn.-ssing l/0 ports (1/0 mndos).

(3 1)

Copyrighted material
Microprocessors and Interfacing
. " . . '
32 80861nstruction Set and ALP

Addressing Modes for Accessing immediate and Register Data


1. Regi)OI~r Addre~sing Mode
This rnude !ipCdfi ~;.'S the ~u rcc ()perand, d t~ti nati on opcromd, or both lo be COJt taincd
in an 8086 register.

Direction ol data flow

MOV AL. Bl

.; . Destination register Source register

Note : Both source and destination operands are in 8086 register

ExamPles :
M O V BX, CX ; Copies the 16-bit oontents of CX i nto BX
M OV CL, BL ; CopiL.os a.-bit contents o ( BL into CL.
2.. Immediate Addressing Mode
In an immedial' mode, 8 or 16-bit d ata c.an be s pecified as a J>4.Ut of ins truction.

7 0

~---------20H
j I '
_ . MOV AL. 20 H

Destination operand lnmediate data


is a 8086 register as a source operand

15 0

MOll AX. 1234 H IL _ _ _ _ _AX


_ ___.I--1234 H

Oeslination operand Immediate data


is a 8086 register as a source opetand
Note : Anew Indicates diredion of data ftaw

Examples :
MOV BL, 26H ; Copies the 3-bit data 26H into BL
MOV CX. 4567H ; Copk'S the 16-bit data 4561H into ex.

Copyrighted material
Microprocessors and Interfacing 3 -3 8086.1notructlon Set and ALP

Addressing Mode s f or Accessing Data in MemorY


As n'lentionOO before, the Execution Unit (EU) has direct acceSs to all registers nnd
data fo r regi">t,~r .md immt-xii.lh.-' optr.: mds. Hmnvtr, lht Et: connot dir~.-'<'t ly ,\CO.::.:; lht'
memory operands. It must usc the BIU segment registt-rs to actt.'SS mcn1ory operands. For
example, wh~ the EU needs to access a memory loca tion, it sends an offset valu..: to lhe
BIU. This offset is also called the Effective Address (EA). Note that EA is displacement of
the desired location from the segment base. As mcntiotK..~ before, the BIU generates a
2D-bit physical addrt..:>SS after s hifting the contents of the desired segment register four bits
to the left and then adding the l6 bit EA to it
11\.ere are six ways to specify effective addres.'i (EA) in the instruction.
a. Dir<.-*Ct addressing mode b. Register indin.--ct addr~sing mode
c. Based addressing mode d. lndext.>d addrc!->sing mode
c. Based indexed addressing mode f. String addrcs!>ing mode.

1. Direct' Addressing Mode :


In this mode, the 16bit effective address (EA) is taken directly from the displacemt.:.nt
field of the instruction. The displa~cmcnt (unsignt.>d 16bit or sign.-cxt.:."-dcd Sbit number)
is stored in the location fo llowing the instruction opcodc.
Memof)'

AL

[~~~~-----t~~O~H~
13001
MOV AL. (3000HI
SOH L SOH : 13000H J
H

OS [==~~==}!~1
1000 OS ~~~~H~+i3000~~Hr----------__j
(10H)+3000H
x

10 13001H

MOV t3000HJ. ex 1 10 1 20 20 13000H


eH Cl 12ffl'H
ex
1-c...- -1

OS [==~~==}!~1~DOCO~HH~JOOO~~H~
1000
0Sx(10 H)+3000 H
_ __ _ :___j

- : 1.AaoJmoOS= 1000
:. Physical address = OS (10H)+ 3000H
1ooolQJ 3000H = 13000H
2. Atrow indicales direcCion of data flow.

Copyrighted material
Mlcroprouss'?rs and Interfacing 3-4 8086 Instruction Set and ALP

Example :
MOV CL, [9323HI ; This ins truction will copy the C01ltcnts oi the
; memory locatio1\, at a displacement of 9823H from the
; data S<>gment baS<>, into tt.> CL register. Here, 9823H is
; the effective address (EA) which is written
; dire<"tly in the instruction.

2. Register Indirect Addressing Mode


In this mode, the EA is spedfied in either a pointer register or rm index register. Tile
pointer registecr can be either ba~ register BX or base pointer n.?gistcr BP and index
r~gisler can be (ithcr Source lndL'x (51) register or ~tlnalion Index (01) register. The
20-bit physical address is computed using OS and EA.

Memory

M0V8X. (CX)

- 8X

OS 1000H

2000H
ex 2000H
address

Example:
1. MOV [01], BX ; The imnruction copies the 16-bit contents of BX into a
; memory location offset by t'-' value of EA specified in 01
; from t'-' current contents in OS. Now, if [DSJ e 7205H,
; [DIJ OOOOH, and (BX] 8765H, then afll1r MOV [01), BX.
; content of BX (8765H) is copied to memory locations
; 72080H and 72081 H.

Copyrighted material
Microprocessors ond Interfacing 3-5 8088' instiucllori 'S et and ALP

2. MOV DL. (BPI ; This instruction copies the 8-bit


; contents in DL from the memory location offset by the
; value of EA spccilied ln BP from Ulc contents of SS.
; Because data add ressed by BP a re by default located in
; stack segment (SS).
3. Base-Plus-Index-Addressi ng :
Base-plus-index addressing is similar to indirect addressing because it indirectly
addresses memory data. This addressing uses one ba.se register (6P or BX), and one index
regl-;ter (01 or 51) to indirectJy address mcrnory. The base registe r often holds the
begirming location of a memory array, while the inde>< rq;istcr holds the relative position
of an element in the array. Remember that w henever BP addresses the memory data, the
cont~ ls of stack segment., BP and index register arc used to generate physical add ress.

Locating Data with Base-Pulse-Index Addressing :

Memory
MOV CX. (BXOI)

. -- - - - - - - - t-;;
, O;H;-1 12031H

I 10H I 40H 40H 12030H


CH
ex
CL
--
OS I IOOOH
IOOOK!iH
DS > ( IOH) + 12000H
+
12030H

BX I 2000H
2000H

01 I 2000H

Locating Arry Data Using Ba.se..Piu.s-lndex Addressing :


A main usc o( the ba_sc..plus-index addressing mode is to addn..~o; elemen t~ ln .1
memory army. Suppose that the array is located in the data ::;egment tx.:.ginnil\g (rom
memory )(>Cation ARRAY. To access a p.uticular element within the array we have to load
the BX register (base) with the bL>ginning address of the array, and the 0 1 registl>r (index)
with the element number to be acc~d . This is illustrated in Fig. 3.1.

Copyrighted material
Mlcroprocuoors and Interfacing . 3-6 8086 Instruction Set and ALP
-
MO\ CX. ~UX C i)

CH
'
I 3001 IOt<
CL
-
40H ARRAY+&
AARAY+5
ARRAY+4
ex ARRAY +01

ARRAV+3 0 11 Element I,...,


ARRAY+2
ARRAY+1
ARRAY

OS ~:m9nt ba58
- ARRAY

ax ; ARRAYI>ase I I
Fig. 3.1
4. Regis ter Relative Addressing :
Register relative addressing is similar to b.1se--plus-index addressing. Here, the data in
a segment of memo?' are addn..-ssed by adding the displacement to the contents or a b.,se
or on index register {BP, BX, 01 or Sl). Rerru=ber that displa=ent should be added to
the register within the I ]. This is illustrated in the Fig. 3.2. Displacement can be any 8-bit
or 16-bit number.
MOV CX. (BX 0003HI or MOV CX. (BX 31

I-1;.;0;.;H-1 61004H
IOH I 20H 20H 61003H

-
CH CL 6t002H

ex

OS I 6000H
6000imH
DS {IOH)

IOOOH 1003H
ax I
.....
IOOOH +
Olsp&accmont
03H

Fig. 3.2

Copyrighted material
" ..>
Microprocessors and Interfacing 3-7 8086 lo'i'atriictiori Set and ALP
Note :

Di~oplaccment can be subtract4;..-d from the register : MOV AL (01-2(.


Displacement can be an offset address appc>nded to the fron t of , the [ j
MOV AL, OFF_ADD JDI + 4).

Example : MOV AL, LAST [SI + 2) ; Thi< mstruction copios the contents of the 20-bil
address computed from the displacement LAST, SI + 2 and OS into AL.

Addressing Array Data with Register Relative :

The Fig. 3.3 shows how to address d<tta elemE"Ot within the array with register relative
addressing.

MOV CX. ARRAY (01) ........

30H A~FtAY+6

130HIoH 1 40H ARRAYS-- - ,


CH CL A~FtAY4

ex ARRAY3 01 Index
'--....--"
ARRAY+2 .. 1

OS Segmenl base +

ARRAY

Displacement in the
tegment register

Fig . 3,3
S. B~ Relative Plus Index Addressing :
nw base relative plus index addressing mode is simi1ar to. ,.the ba~e plus index
addressing mode, but it adds a displacement, besides using a base register and an index
register to generate a physical address of the memory. This addressin~ mode is suitable to
address data within the two dimensional array.

Copyrighted material
Microprocessors and Interfacing 3 8 8086 Instruction Set nd ALP

Addressing Data with Base Relative Plus Index :


Ttl( Fi~ ..'l.-1 ..;.hu\\'._ hm , d ~ll,l c.m be .-.(_"CL'S$4._--.d with base rd.l ti v~.. plu:, indt:'x addrt.--ssing
mode.
MOV Al,(8X Sl 1OHJ
........
20310H
Al I 50 5ClH

-
ex 0100H 0300H '+\ 03tOH
T
So
: 0200H
I 1
10M

20000H
OS
I 2000M
OS x (11J1)

Fig. 3.4
Addressing Arrays with Base Re lative-Pius~ndex :
As mentioned earlier this addressing mode is useful in addressing two dimensional
array. Two dimensional array usually stores records. For example, student record ~-uch as
its name, roll no etc. Thcndorc, each n>eord _c ontains number of data elements. To access
data element from a particular record we use base regjster to hold the beginning address
of the array of records, index register to point a particular record in the array of records
and displac-ement to point a partictllar element in the record. This is iUustrated in Fig. 3.5.

........,
I

~ ~~
,. .._ ....... !! ___,
; I

........
I

;- , I 51

-
2
1

OS I

I
Fig. 3.5

Copyrighted material
3-9 808e lnatruc:tlon Set nd ALP

6. String Addrft&ing MQ<Ie :


This mode uses index registers. The string instructions automatially assume SJ to
point to the first byte or word or the source operand and OJ to point to the first byte or
word of the destination operand. The contents of Sl and OJ are automatically incremented
(by c.learing OF to 0 by ClD instruction) or decremented (by setting OF to I by SI'D
instruction ) to point to the next byte or word. The segment register (or the sou~ is OS.
The segment register for the destination must be ES.
Example :
MOVS BYrE ; IJ [OF( = 0, [OS) = 3000H, (SIJ = 0600H, (ESJ =5000H,
; [OIJ = 0400H, [30600H( = 38H, and [50400Hj = 45H, then
; after execution of the MOVS BYrE, (50400Hj = 38H,
; (Sij 060lH, and [Oij 040lH.
Addressing Modes for Accessing 110 Ports (110 Modes)

StaJ,dard 1/0 devin.'S uses port addressing modt."S. For memory..mapped 1/0, n\emory

addressing mod~ are used. T~re are two types of port addressing modes : dirt"CI ,md
indirect.
In direct port mode, th e port number is an 8-bit immediate ope.rand. This allows fixed
acxess to ports numbered 0 to 255.
Ex.mple :
01.11'05H, AI. ; Sends the contents of AL to 8-bit port 05H.
IN AX, SOH ; Copies 16-bil contents of port SOH
In indirect port mode, the port number is taken (rom OX allowing 64K 8-bit ports or
32K 16-bit po<ts.
ex....ple :
IN AL, OX ; If (OX( = 7890H, then it copies lH>il coolent or port 7890H
1
; into AL.
IN AX, OX ; Copies the 8-bit contents or ports 7890H and 7891 H into AL
; .md AH, r<"$pcorlivcly.
Note : Titc &bit and 16--bit 1/0 trc\nsfers must take place via AL and AX. rest'III..'Ctively.

3.2.2 Program Memory Addressing Modes


JMP Oump) and CALL instructions use program memory addressing modes. These
instruction have three distinct forms : direct, relative and indirect. Let us see these forms
and corresponding addressing modes.

Copyrighted material
Mictoprocessors and Interfacing 3 -10 80861nstruction Set and ALP

Direct program memory addres.sing :

In lhi~ addrcssinh mode addn...s;s whtn to lrnn.'ifer program cuntrc:JI is s pt.--cifiOO within
the instruction alongwith the opcode. The Fig. 3.6 shows the direct intersegment JMP
instruction and the four bytes required to store the address 20Xl0H. This JMP instruction
loads CS with 2<KX>H and ll' with OOOOH to jump to memory location 20000H for the next
instn1ction. An intersegment jump is a jump where destination location is from a different
St.--gment; it can be any memory location within the entire memory locations. Therefore,
intel'S4.-ction jump is also known a.s far jump.

Ofl..t (lOw) Oflset (t;gh) Segmont (lOw) Segment (high)

JMP2000H EA 00 00 00 00

Fig. 3.6
Like JMP instruction, CALL ins truction also lk~ direct PI"'h7am addressing with
inte&--gmt-"'1\t or far CALL in.;tnlction. U:maiJy. in both instructions OMP or CALL) th'-'
name of a memory addrt"SS, called a label is spedfiai in the instruction instead of addn_--ss.

Relative program memory addressing :

In this addressing mOOc, the t'e rm rcl'-'tive is restricted to instruction poinh~.r (IP). For
example, if n JMP instruction skip~ the next 5 bytes of memory, tht- address in relation to
the instructjon pointer is <1 5 that adds to the instnadion pointer. ThLo; generates the
addrcs.<~ of the next progr<-1m in..:;l'ruction. ThLo; is illustrated in Fig. 3.7.

Opoode

20000H
20001H
~JMP(OS)
20002 H
20003 H
-'--Oflset
20004 H
20005 H
20006 H
20007 H
20008 H
Fig. 3.7
It is importilnt to note thc1t in JMP instruction, oprode takes ont> byte and di.splacem(.nt
may take one or h\'l) byt~. Wlwn displacement i~ onl.' byte (8--bit), it is called short jump.
\Vht>n displacement is two byte ( 16--bit), it is called near jump. ln both (short and near)
case::> onJy ronten~ of IP register are modified; contents of CS register are not modified.
Such jumps are called intra.segment jumps ba.."Causc jumps ore within the current code
segmtnt.
Tht. rclativl' JMP and CALL ins tructions can have either an S~bit or a l6bit signed
displacement that allows a forwfltd memory reference or a reverse memory referenC('.

Copyrighted material
MicroproceMors and Interfacing 3 -11 80861nstruction Set and ALP

Indirect program memory addressing :

Thl 80.% nUow:-; :o~oevcrnl (orm..o; ~,( program indin,-'CI mt!mnry addre-.-sing (or the JMP
and CALL ins tructions. ln this addressing mode, it ls possible to use any 16-bit register
(AX, BX, CX, OX, SP, BP, 01 or 51); any relative register ((BP(, (BX], (01(, or (51]); and any
reliltive register with displacement to specify the jtmlp address. This is illustrated in
Table 3.1. /

lnstruetion Operation
JMP ex Jumps 10 tnell'!Of)' lOcation adcttcssed by ex <Mthin current COde
&<>gment.
tP +- ex
JMP NEAR PTR (BX) Jumps to memcwy location addressed by the COntents ot the dat<t
segment memory location addressed by 8X Witfin the CUIT8nl code
segment
tP <- ( (8X + t1 (6Xl)
High byte low bylo
JMP NEAR PTR (0 1 21 J umps to memory location addtessed by the contents 04 the data
segment memory tocation addressed by 0 1 plus 2 within the current
cooe segment.
IP +- ((Dt 3), (Dt 21)
Hlon byte Low byte
JMP ARRAY [BX) Jumps to memory location OO<lfessed by the contents of the data
segment memory location addressed by ARRAY plus ex with the
curTent oodo segment
IP ~ ((ARRAY + ex 1], [ARRAY eXI)
High byte Low byte

Table 3.1
3.2.3 Stack Memory Addressing Modes
The stack is a portion of read/ write mt>mory set asidr by the user fo r t~ purpose of
s toring infonnation temporarily. When the informatic)n is written on the stack. the
Opt."fation is c..lJicd PUSH. When the hl(onnation is read from stack, the operation is called
a POP.
t he :njcro prucl-"S.-<OOT :oton.>S the infonna t10n, mud1 like stackmb p l ate~. Using thi ...
analogy of s tacking: plah.>s . il is (>asy to illu.o;trilte th e stack operation.
Fig. 3.8 shows the stacked plates. Here, we rl'a Hzc
3
that if it is desired to take out the fi rst st.1cked plate we
2 will h ow~ It) rcmove all plate-s a.bovc the firs t plate in the
t reverse order. TI1is me.a ns that to remove first p late we
will have to rem<we the third plate, then the second
Fig. 3.8 Stacked plates plato and finall y lhe first plote. This means tha~ tho first
information pushed o n to the stack is the last
information popped off from the sta.ck. This type o f opcrJtion is known as a first in, last
out (fl LO). This stack is implemented with the help of special me mory pointer register.

Copyrighted material
Microprocessors and Interfacing 3 12 8086 Instruction Set and ALP

The special pointer register is called the stack pointer. During PUSH and POP operation,
stack pointer regil.iter giv~ the address of memory where the information is to be stored
or to be read. The stack pointer's contents arc automatically manipulated to point to stack
top. 1be memory location currently pointed by stack pointer is called top of stack.

Stack Structure of 8086188


The 8086/88 h..1S a spt-'Cinl 16-bit T('gistcr, SP to work as a stack pointer. The stack
pointer (SP) register contains the 16-bit offset from the start of the segment to the top of
stack. for stack oper('tion, physical address is produced by adding the contents of stack
pointer register to the segment base address in SS. To do this the contents of the stack
segment rcgistN arc shifted four bits lt>ft and the contents of SP a.t<' added to the s hifted
n:.-sult. If the contents of SP a.re 9F20H and SS are 4000H lhen the physical address ls
cakulatcd as follows. (Refer Fig. 3.9)
SS ~ 4000H after shifting follr bits left SS ~ 40000H
Now
ss 40000H
+ SP 9F20H
Physical address 49F20H

- End of s.tadt segment 4FFFFH

- Top of stack 49F2011

SP 9F20H 1
-
SS =4000H - Start of stack segment 40000H

Fig. 3.9 Staclt and alack pointer


PUSH and POP Operations
Temporarily stores the contents of 16-bit register or memory location or progr<"~m status
word, and rctril'Vt-':lo whl-n rl'quir~.-.d . Whtn rrog.mmmcr realiu.-s the s hortage of the
l't-"'gi~ lcr~. he :o lurl~ lhe pr~.."Sc.'Jll rontcnb of tiw n~i,:.tcr.: in thl :otJck with thl help of PUSH
instruction and then Ust"S the registers for other function. After completion of other
function programmer loads the previl,US contents of the regis ter from the s tack with the
help of POP instruction.
PUSH Operation :
The PUSH instruction decrements stack pointer by two and copies a word from some
source to the location in the stack where the stack pointer points. Here the source must be
a word (16 bit). The source of the word can be a general purpose register, a segment
register or memory. The Fig. 3.10 shows the map of the stack before and after execution of
PUSH AX and PUSH CX instructions.

Copyrighted material
Microprocessors and I-cing 3 -13 80861nstructlon Set and ALP

End of slatk ~
- 4FFFFH
4FFFEH
4FFfOH
t FFFCH
<tff'FBH - Topol slack
4FFFAH

ssi401Xlt1 1-
=
S -= - sladl segment

(b) After ..c"'lion of PUSH AX en6 PUSH CX


Fig. 3.10
POP Operation :
The I'OP instruction oopk'S a word from the stack location pointed by the stack pointer
to the destina tio n. TI'U'! dt.'Stination can be a general p u rp<.>Se regis ter, a segml"tlt n.--gister_, o r
a memory location. After the word is copied to the specified destination, the stack pointer
is automaticaUy increme~"'ted by 2. 1he Fig. 3.11 shows the m('p of the stack before and
after execution of POP OX and POP BX instructions.

exI I ox! exI4455H I oxl 1234HI

.... . ...
nd ciNe* segmM End of stack segmenl 4Ff"FFH
- 4FFFFH $P )FFFFH)- - Top ol slad;
4 I'f'1'f'H 4 FR'EH


-
FFFOH 56 H - FOH
12H FFFCH 12 H
FFFCH

"'" 4 .......
4fFF8H- Topol sUet 34H

''"'"'"
"""""
""""'"
ss(AOOOH)- """''"
-

-
Sbr'l of---~ SS(-4000H

Fig. 3.11
I-

CALL Operation
The CALL instruction is used to transfer execution to a subprogmm or procedure.
There ..., lwo basic typ<'S of CALL, near and fur. A neor CALL is a call to a procedure
which is in the same code St."gl1'lml as the CALL ino;;ttuction. When the 8086 t.."Xu~ a

Copyrighted material
Microprocessors and Interfaci ng 3-14 8086 Instruction Set and ALP

near CALL in~ITuctin n it d(.ocrement~ the stack pointer by two and copies the offset of the
next ins tructiOil ~lfl~r the CALL 011 the stack. It loads IP with the offset of the first
instruction of tht pn:>~.X'\i urt in ..:,\11\(~ scg1nent
A fa r CALL is <1 call to .1 pnx.-c.~ure which is in a d ifferent segment from that which
contains thl' CALL instructio' When the 8086 executes a far CAll U decrements the stack
pointer by two and copies the contents of the CS register t'O the stack. It then d ecrements
the stack pointer by two again and copies the offset of the instruction afte r the CALL to
the stack. r.1naUy, it loads CS with the segment base of the segment w hich contains the
prQc:\.-'dure and IP with the offset of the fi rst instruction of the procedure in that segment.

RET Operation
The RET instruction wilt retum executi(m from a procedure to the next instruction
after the CALL inl'truction in the calling p rogram. If the pn..lCl.'<.iure is , neilr p rocedure (in
the :;ame code segment as the CALL instruction), then the return will be done by replacing
the instn1ction pointer with a ''"Ord from the top of the ~tack.
I( tht> pn:x.:edtlrC is ,, far pn>et>dure (in a diffen.."Tlt code segment from the CALL
instruction which calls it), then tht..> instrtction pointer will be replac;ed by the word at the
top of the stack. The stack pointer w ill then be incremented by nvo. The code segment
rcooister i.s then replaa.."CC \vith a word from the new top of the stack. After the code
segm~.m t word i!i: poppt.'rl off the s t:tck, tht:' stack pointer is nga in incremented by two.
Thl'S<> words/word art' the offset of th<' next instmction after the CALL. So 8086 wiU fetch
th'- next iru;tn.a<.tiou nflcr th\.' CALL.-

Overflow anJj Underflow of Stack

We hl.'lve se-!'n thl PUSH opcmtion. During this operatio n st.., ck pointer i~ dccrementt..~
by two. Wl' know that maximum length of stnck segment is 64K. lf we go on performing
PUSH UJX'fl.llions s ut.'Ce':'Sivcly, 41t ,_me time tht;> contents of SP will be OOOOH. Any further
attempt to PUSH data on the stack will l'\.Sull in stack overflow.
On the other hand, if we go on perfonning POP operation:-; succes...-ivdy. ill 00(' time
the contents ,,f SP will be FFFFH. Any furtbcr a ttempt to POP data from the stack will
result in stack underflow.

3.3 Instruction Set of 808618088


The instn1ction set of the 8086 is divided into Eight major groups as follows :
Dat.1 Mon.-'lllt.-'111 Instruction."
Arithmetic and logic Instructions
String Instruction."> and
Program Control Transfer ln~tructions
Iteration Control Ins tructions
rroet....~r Control lalStructions

Copyrighled malerial
M i~roprocessors and Interfacing 3. 15 8086 lnstructio ~JcSet and ALP

Externa l J-lard wnre Synchronization Jnst-ructim\.<;


lnterrupt Instructions

3.4 Data Movement Instructions


The data movement ins tructions cr~n be classified as
MOV ins tructions to transfer byte or word.
PUSH I POP instructions.
load effective address instmctions.
String data transfer instructions.
M.isllan<.-'Ous data transfer instructions.

3.4.1 MOV Instruction


1t is a general purpose in.~truction
to tra 1lsfer byte or word from reg-ister to register,
register to memory or from memory to register.
MOV destination, source

The MOV instruction copies a word or a byt(' of data from some source to a
destitaalion. The destination can be n register or a rnemory location. The.> source can be a
register.. a memory location, or an immediate number. The source and destination in an
instruction can't both be memory locations. The source and destination in a MOV
instna.:tion must be of same type i.e. either both must be byte or word.
MOV instruction does not affect any fla~.

Examples:
MOV BX. 592FH ; l..ood th i mmediate number 592FH in BX
MOV CL. (357AH( ; Copy the conh>nts.. of memory l oca tion~ at a
; displacement of 357AH from data segment base,
; into the CL register.
MOV [734AHI, BX ; Copy the contents of BX register to two memory
; Locations in the data segtru..."nl. Copy the contents
; of BL register to memory location a t a
; displacement of 734AH and BH register
; to memory location at a displacement of
; 734BH.
MOV DS, CX ; Copy word from ex register to data
; segment register.
MOV TOTAL (BPL AX ; Copy AX to two memory locations. AL to
; first location., AH to s.t."CCnd. Efftoctive
; address, EA, is the sum of displacement

Copyrighted material
Microprocessors and Interfacing 3-16 8086 Instruction Set and AU'

; represented by TOTAl and content'> o( BP.


; Phy!>ical address a: EA + SS.
MOV CS : TOTAL (BP), AX ; s.,mc a:-; above instruction, but physical
; addn:.-ss a EA+CS. Because the SL-:.gment
; overidc prefix is CS.

3.4.2 PUSH/POP Instructions


These instruct:'"~ns are used to IOitd or rt.--ceive data from the stack memory.

PUSH source

The PUSH instntction decrements sto.1ck pointer by two and copies a word from some
source to the location in the stack whe re the stack pointer puints. Here the source must be
a word (16 bit). The source o( the word can be a general purpose register, a segment
register or memory.
It is important to note that wht.>never data is pushed onto the stack, the first (most
s ignificant) data byte moves into the stack segment memory location addres._.;;ed by SP-1.
The second (least s ignificant) data byh. moves into the stack segment memory location
addressed by SP-2.

Examples :
I. PUSH ex ; DecrcmL'fllS SP by 2. copy ex to s tack
The Fig. 3.12 shows the execution o! PUSH CX instruction.

30036H

3003511
ex
CH Cl 30034H

[ 20 (30 30 30033H
l 20 300J2H

30031H

30030H

1 oo34
30000H
30000/"
ss 1 3000
ss )l 10H
Fig. 3.12
Copyrighted material
Microprocessors and lntMfacing 3 11 8086 Instruction Set and ALP

Note : After execution ol instaHation SP = 0032 H and it is indicated by doH.xt


arrow.
/
2. PUSH OS ; Decrement SP by 2, copy OS to stack
3. PUSH NEXT [BX) ; Dec:rcme:nt SP by 2, copy a word from memory in
; 05 (i.e . I'A = EA + OS) to staek with
; EA = NEXT + [BX]
PUSHF
Puts the flag register contents on the stack. Whenever this instruction is executed, the
most significant byte of flag register movt"S into the stack segment memory location
addressed by SP-1. The least significant byte of flag f('gister moves into the stack SL--gment
memory location add r~ by SP-2.

POP destination
11le POP instruction copies a word from the s tack location pointed by the stack pointer
to the destination. The destination can be a general purpose register, a segment rebrister, or
a memory I0<'41t'ion. Afte r the word L<> copied to the s pecified destination.. the s tack pointer
is automatically incrementt.'Cl by 2. Whenever data L-; removed from the stack, the byte
from the stack segment memory location addressed by SP moves into the most significant
byte of the destination register and the byte from the stack segment memory )()('.{ttion
addressed by SP + 1 moves into the least significant byte of the destination register.
Examples :
1. POP CX ; Copy a word from top of stack
; to CX n.nd increment SP by 2.
The Fig. 3.13 shows the execution o POP CX instruction.

30045H

30044H - - - - 1
'
40 30043H '
)40150
''
50 30042H
CH Cl..
3000 1H
ex 30040H

SP 1 0042

~
30000H
30000
ss I 3000
SS a 10H
Fig. 3.13

Copyrighted material
Mlcroproce~ors !'!! Interfacing 3 - 18 8086 lnstTuc11on Sat and ALP

N ote : After execution of instnction SP =- 0044H and it is indicated by dotted arrow.


2. POP OS ; Copy a word from top of stack
; to OS and increment SP by 2.
3. I'OP NEXT [BX) ; Copy a word from top of stack to memory in OS
; (i.e. PA = EA + OS) with EA = NEXT+ [BX), and
... ; increment SP by 2.
Note : POP CS is illegal.

POf'F

Remove:; the \yor<:J. from top of stack to the flag register. Whenever this instnlction is
cxecutt.:>Cl, the byte from the stack ~ent memory location addressed by SP moves into
the most s ignificant byte of the flag n.~ister and the byte from the stack segment memory
location addressed by SP+ 1 moves into the least significant byte of the flag register.

Initializing the stack



Before goinj; to lL':i<.' any in.~truction which uses s tack for its operation we have
initialize stack segment, and we have reverse the memory a~ n.--quired for the stack. The
s tack am be initialized by including foUowing sequence of instructions in the program.

METHOD 1 :

ASSUME CS : CODE, OS : DATA, SS: STACK

STACK SEGMENT

S_DATA DB 100 DUP (?}

STACK ENDS

Note : ., (\!latter typed in Bold letters is included to initialize s tack. This program
sequence ....,.,.,.. 100 byt"" fa< the stack operation.
METHOD 2 :

Syntax : Stack [size I


Example : Stack 100
The s tack is a directive, w hich provides sho<lcut in definition of the stack ""8J'J"'''l
The default size is 1024 bytes. The instruction stack 100 reserves 100 by1es for the stack
operatitm.

3.4.3 Load Effective Address


11le lo.'ld effectin! address group includes following instructions.
UA

Copyrighted material
Microprocessors and Interfacing 3-19 8086 lhstructlon S.l and ALP

LOS
LES

LEA lnslructlon : Load Effective Address : LEA register, SOUJ'Ce

nus instruction determines the offset of the variable or memory location named as the
source and loads this address in the specified IG-bit "'1,-ister. Flags are not aff<!Ctt.>d by lEA
instruction.
Examples:
LEA ex, TOTAL ; Load ex with offset of TOTAL in OS.
LEA BP, SS: STAeK_TOP ; Load BP w ith offset of STACK_TOP
. in SS.
LEA AX, [BX] [01] ; Load AX with EA = [BX] + [Dl]
LOS Instruction : Load register and OS with words from memory. LOS register,
memory address of first word.
This instruction copies a word from two memory locations into the register specified in
the instTuction. It then copies a word from the next two memory locations into the OS
register.
Examples :
LOS CX, [391AH) ; Copy contents of memory at displacement of
; 391AH and 391BH to CX. Then ropy contents at
; displacement of 391CH and 391 Ofi in OS.
L5 Instruction : Load register and llS w ith words from memory. LES n.'gister, memory
address of first word.
Thi.~ instruction loads new values into the specified register and' intO the ES register
from four successive memory locations. 1lle word fTom the fir5t two memory Jocation is
copk!d into the ~pecilied register and the word (rom the nexl two memory locations is
copied into the llS register. ., .
Example :
LES ex, [3483H] ; Copy contents of memory at displacement of 3483HO
; in OS to eL, oontents of 3484H in OS to CH and
; ropy the rontents of memo<y at displacement of
; 3485H and 3486H in OS to ES register.

3.4.4 String Data Transfer Instructions

These instructions ropy a byte or word from a location in the data segment to a
location in the extra segment. The of&et of the source byle or word in the data segment
must be in the SI register. The offoet of the destination in the exlr;\ segment must be
rontained in the 01 register. For multiple byte or multiple word moves the number of
elemenlll to be moved is put in the ex register so that it can function as a counter. After
the byte or word is moved SI and 01 are automatically adju$led to point to the next source
.
Copyrighted material
Microprocessors and Interfacing 3 - 20 80861notructlon Set and ALP

and the next destination. If the direction flag is 0, then SI and 0 1 wi_ll be incremented by 1
after a byte move a1ld they wi11 i.ncreme.r1ted by 2 after a word move. 1( the OF is a 1, then
Sl .md Dl will be dt>Cremcntcd by 1 after a byte move al\f.i they will be dercremented by 2
after a word move. MOVS aff<.-'CIS no flags.
The way to tell the assembler whether to code the instmction for a byte or word move
is to ndd a "'8 " or a "W" to the MOVS mnemonic. MOVSB, for example, says move a
string as bytes. MOVSW says move a s tring as words.

Examples :
eLO ; Clear Direction Flag to autoincrement SJ and 0 1
MOV AX, OOJOH
MOV DS, AX ; Initialize dnta segment register to 0
MOVES, AX ; lnitiali:te extra segment register to 0
MOV 51, ZOOOH ; l..ood offset of start of source string into 51
MOV 01, 2400H ; load offset of start of destination into Dl
MOV ex, 04H ; l..ood length of string in ex as counter
REP MOVSB ; Decn>ment ex and MOVSB until ex will be 0.
After move SJ will be one greater than offset of last byte in sourct:! s tring. OJ will be
one greater than offset of last byte of destination string. ex will be 0.
REP is a prefix which is written before MOVSB to repeat execution of It until ex 0.
REPIREPEIREP2/REPNE/REPNZ Prefix

REP is a prefix whlch i.~ writte1\ before one of the s tring instructions. These
instructions repeat until specified condition exists.

lna.tructlon Code Condition lor Exit


REP ex= o
REPEJREPZ CX OorZF=O
REPNEJREPNZ CX =OorZI'=I

Examples :
REPZCMP 58 ; Compare string bytes until CX 0
; or until string bytes not equal.
LODS/LODSB/LODSW

This instnoction copies a byte from a string location pointed to by 51 to AI.,, or a word
from a string location pointed to by 51 to AX. LODS does not affect any fL1gs. LODSB
copies byte and lODSW copies a word.

Copyrighted material
3-21 8086 IMtruc:tion Set and ALP

Examples :
CLD ; Clear di.rcction flag so SI isautoincremented
MOV 51, OFFSET S_SI'R!NG ; Point Sl at s tring
LODS S_STRING.
STOSISTOSBISTOSW
The STOS instruction copies a byte from AL or a word from AX to a memory l(.)oCation
in the extra segment. 01 is US4.."CC to hold the offset of the memory location in the extra
segment. After the copy, 01 is automa tically incremented or decremented to point to the
I'K'xt string clement in memory. If the direction flag. OF. is cleared, then 01 will
automatically be incremented by on<.' fo r a byte string or incremented by two for a word
string. lf the direction Aag is set, 01 will be automatically dt.>Cremented by one for a byte
string or decremented by two for a word string. STOS does not affect any flags. STOSB
copies byte and srosw oopies a word.
Examples:
MOV Dl, OFFSET D_STR!NG ; Point 0 1 at destination string
STOS D_STRING ; Asscmbk.~ uses string name to deterntine
; whether string is of type byte or' type word.
; l( byte string, tht."'f'' string byte replaced
; w ith contents of Al... lf word string, then
; string word replact.'<i with contents of AX.
MOV Dl, OFFSET D_STRING ; Point Dl a t destination string
STOSB ; s added to STOS mnemonic directly
; tells assembler to replace byte in string with byte from
; AL. STOSW would tell assembler directly to repla<e a
; word in the string with a word from AX.

3 .4.5 Miscellaneous Data Transfer Instructions


This group consists of foUowing instructions.
XCHG
LAHF
SAHP
XLAT
IN and OUT

Copyrighted material
Microprocessors and Interfacing 3-22 8086 Instruction Set and ALP

XCHG lnotruction : XCHG destination, solll'Ce.


1he XCHG instfuCtion exchanges the contents of a register with the contents of another
register or the content<; of a register with the contents of a memory location(s). 1be
instruction c-annot exchange the contents of two memory locations.. The source and
destination both must be words or bytes. The segment registers can't be used in these
instructions.
Exampln:
XCHG BX.CX ; Exchange word in BX with word in CX.
XCHG AL, CL ; Exchange byte in AL with byte in CL.
XCHG AL, SUM (BX] ; Exchange byte in AL with byte in m~ory at
; EA =SUM + [BX]. PA = EA + OS.
LAHF Instruction : Lo.,d lower byte of Rag register in AH.
TIUs instruction copies the contents of lower byte of 8086 flag register to AH register.
1
SAHF lnstructiori Copy AH register to low byte of flag "'b>ister.
:
. .
The contents of the AH register are copied into the lower byte of the 8086 flag "'b>ister.
XLAT lnotruction : Translate byte in AL.
The XLAT instruction replaces a byte in the AL register with a byte from a lookup
table in ML"n\\ty. BX reg-ister s ton.:os the offSL>t of the starting addres.o; of the lookup table
and AL register stores the byte number from the lookup table. TIUs instruction copies byte
from address pointed by [BX + All back into Al.
IN and OUT Instructions

IN Instruction : Input a byte or word from port.


The IN instruction will copy data from a port to the accumulator. If an 8-bit port is
read, the data will go to ALand if an 16-bit port is read the data will goto AX.
The IN instruc-tion c-an be executed in two different add.ressing modes,
1. Direct : ln d irect addressing mode 8-bit address of the port is a part of the
instruction.
Examples :
IN AL, OFSH ; Copy a byte from port OFSH to AL.
IN AX, 95H ; Copy a word from port 95H to AX.
2. Indirect : In indirect addressing. the address of the port is referred from OX
register. Since OX is a 16bit register, the port address can be any number between
OOOOH to FFFFH. Therefore it is possible address to upto 65,536 ports in this mode.

Copyrighted material
Microprocessors and Interfacing 3 -23 80861ns'ittctlon:S~and ALP
Examples :
MOV OX. 30F8H ; Load 16-bit address of the port inf>X.
IN AL, OX ; Copy a byte from 8-bit port 30F8H to AL.
IN AX, OX ; Copy a word from 16-bit port 30P8H to AX.
OUT Instruction : Send a byte or word to a port.
The OUT instruction copies a byte from AL or a word from AX to the specified port.
1he OUT instruction can be executed in two different addressing modes.
I. DirL~ : In direct addressing mode 8-bit address of the port is a part of the
in.~truction.

Examples :
OUT OFSH, Al ; Copy cont""ts of AL to 8 bit port OF8H.
OUTOFBH, AX ; Copy contents of AX to 16-bit port OFBH.
.
2. lnditect : In indirect addressing. the address of the port ~ ref~~ from OX
rf:b"ister. It has advantage of accessing 216 i.e. 65536 ports as mentioned earJier.
Examples :
MOV OX. 30P8H ; Load H)-bit address of the port in OX.
OUT OX. AL ; Copy the contents of AL to port 30P8H.
OUT OX, AX ; Copy the contents of AX to port 30F8H.

3.5 Arithmetic and Logic Instructions


The arithmetic and logic group of instructions include
Addition in.<oitructions
Subtraction instructions
Multiplication instructions
Division
BCD and ASCll arithmetic instructions
Comparison
Basic logic Instructions AND, OR NOT, XOR
Shift and rotate instructions

3.5.1 Addition
This group of instructions consist of following instroctions
ADD : Addition
ADC : Addition with carry
INC : Increment (Add l)

Copyrighted material
Microprocessors and Interfacing 3. 24 8086 Instruction Set and ALP

ADD/AOC Instruction : ADD dcst:in.atjon, source I AOC destination_. source.

These instruction~ add a number from source to a number from destination and put
the result in the destination. The ADC, instruction also adds the status of carry flag into
the result. The source may be an im.mt.dhHe number, a register, or a memory location. The
~urce and the destination in an instruction cannot both be memory locations. 1he source
and destinltion both must be a word or byte. [{ you want to add a byte to a word, you
must copy the byte to a word location and fill the upper byte of the word with zeroes
before adding.
Flags affected : Af, CF, OF, PF, SF, ZF.
Examples :
ADD AL, OFOH ; Add immedi<lle number OFOH to contents of AL.
ADC DL, CL ; Add contents o( CL to contents of DL w ith carry
; and s tore result in DL i.e. DL ~ DL + CL + CY
ADC DX. BX ; Add contents of BX to contents of OX with carry
; and s tore resuh in OX i.e. OX ~ OX + BX + CY
ADD CL, TOTAL (BX) ; Add byte from effective oddrcss
; TOTAL [BX] to contents of CL
ADD CX. TOTAL [BX] ; Add word from effective address
; TOTAL [BX] to contents of CX.
INC Instruction : Increment destination.
The INC instruction add 1 to the speciAed destination. The destina tion may be a
register or memory location. The Af, OF, Pf, SF and ZF flags ore affected.
Examples :
lNC AL ; Add I to contents of AL.
lNC BX ; Add I to contents of BX.
NOTE : The carry flag CF is not affected.
If contents of 8-bit register are FFH and !~it register are FFFFH, after INC instruction
contents of registers will be z.ero without affecting carry flag.
INC BYTE PTR [BXI ; Increment byte at offset of BX in DS.
; BYTE PTR directive indicates to the assembler
; that the byte from memory is to be Incremented.
INC WORD PTR [BX) ; Increment word a t offfiet of BX in DS.
; WORD PTR directive indicates to the assembler
; that the word from memory is to be incremented.

Copyrighted material
3-25 8086 Instruction Set and ALP

3.5.2 Subtraction
This group of instructions consist of following group of instructions.
SUB : Subtraction
SBB :Subtraction with borrow
DEC : o.crem..>nt (subtract I)
NEG : 2's complement of a number
SUBISBB Instruction : SUB destination, Source.

SBB destination, Source.


These instructions subtract the number in the source from the number in tllt"
destination and put resuJt in the destination. The SBB, instruction also s ubtracts the stat'US
of carry flag from the result. The source may be an immediate nu.mber, a regis ter, or a
memory location. The destination may be a register or a memory location. 1be source and
the destination both cannot be memory locations. The source and destination both must be
word or byte. If you want to subtract a byte from a word, you must copy the byte to a
word location and fill the upper byte of the word with zeroes before subtracting.
Flags allect<d : AF, CF, OF, PF, SF, and ZF.
Examples :
SUB AL. OFOH ; Subtract immediate number OFOH
; from contt!llts of AL store result in AL
SBB DL, CL ; Subtract contents of CL and status of carry flag
; from the contents of DL and store result in DL.
; i.e. DL +- DL - CL - CY
SBB OX, BX ; Subtract contcnl of BX and status of carry
; Oag from the OX and store result in OX.
;i.e. OX+- DX - BX - CY
SUB CL, TOTAL [BX] ; Subtract byte from effective address TOTAL [BX]
; from the contents of CL and store result in CL
SUB CX, TOTAL [BXJ ; Subtract word from effective address TOTAL [BXJ
; from the contents of ex and s tore result in ex.
DEC lnatruetlon : Dt'CI'ement destination.

The DEC instruction subtract I from the specified destination. The destination may be
a register or a memory location. The AF, OF, PP, SF and ZF flags are affectt-d.

Copyrighted material
M~on and lnteffacing 3 26 8088 Instruction Set and ALP

ElUimples:
DECAL ; Subtracts I from the contents of AL.
DEC BX ; Subtracts I from the contents of BX.
Note : The carry flag CF is not affected.
If the contents of 8-bit register are OOH and 16-bit register are OOOOH, after DEC
instruction contents of registers will be FFH and FFFFH respectively without affecting
carry flag.
DEC BYTE PTR (BX( ; Decrement byte at offset of BX in DS.
; BYTE PTR directive indicates to the assembler
; that the byte from memory is to be decremented.
DEC WORD PTR (BX) ; Decrement word at offset of BX in DS.
; WORD PTR directive indicates to the ns."K"mbler
; that the wOfd from memory is to be decremented.
NEG Instruction : Form 2's complement.

This instntction repi<K:eS the number in a destination with the 2's complement of that
number. Tile dcstin.'\tion can be a register or a memory location. This instruction can ~
implemented by inverting each bit and adding 1 to it.
The OL>gate instruction updates the AF, CF, SF, PF, ZF and OF flags.

Examples:
; AL 0011 0101 35H
NECAL ; RepL'Ice number in AL with its 2's complement
; AL = 1100 1011 = CBH

3.5.3 Comparison
The comparison Instruction (CMP) compares a byte/word from the specified source
with a byte/word from the specified destination. The source and destination both must be
byte or word. ihe source may be an immediate number, a register, or a memory location..
The destination may be a register or a memory location. However the source and
destination both can't be memory locations. The comparison is done by subtracting the
source byte or word from the destination byte or word. But the result is not stored in the
destination. Soun:e and destination remain unchanged, only flags are updated.
Flags : The AF, OF, SF, ZF, PF and CF are updated by the CMP instruction.

ExompiH:
CMP BL, OJH ; Compare immediate number OIH with byte in BL.
CMPCX, BX ; Compare word In BX with word in ex.
CMP CX, TOTAL ; Compare wot<l at displacement
; TOTAL in DS with word in CX.
Note : It is not possible to compare segment registers.

Copyrighled malerial
I
3. 27 aoa& lrmructlon s.t nd ALP

The result of comparison is checked by conditional jump, conditional call and


conditional return instructions. We discu.ss these instructions Later in this chapter.

3.5.4 Multiplication
This group of instructions consist of following group of instructions.
MUL : Unsigned multiplication
IMUL : Signed multiplication
MUL Instruction : MUL source.
This in..-;truction multiplies an unsigned byte from source and unsigned byte in AL
register or unsigned word from source and un..;;.igned word in AX regi.stM. 'The source can
be a register or a memory location. When the byte is multiplied by tile contents o AL, the
result is stored in AX. 1he mos.t significant byte is s torOO in AH and least significant byte
is stored in At.. When a word is multiplied by the contents of AX~ the most significant
word of result is s tored in OX and least significant word of result is stored in AX.
Flags : MUL inslruction affect AF, PP, SF, and ZP Oags.
Examples :
MULBL ; AL x BL, result in AX.
MUL BX ; AX x BX, result high word in OX low word in AX.
MUL WORD PTR IBX] ; AX tiOK'S word in OS pointed by IBX]
; result high word in OX low word in AX.
IMUL IMtruction :
This instruction multiplies a signed byte from some source and a sigru.>d byte in AL. or
a signed word from so~ soum! and a s igned word in AX. 1'he source can be register or
memory location. Wilen a signed byte is multiplied by AL a signed result will be put in
AX. Wilen a sigN!<! word is m ultiplied by AX. the high-order word o the signed result is
put in OX and the low-<>rder word of the signed result is put in AX.
If the upper byte of a Hi-bit result or the upper word of 32-bit result contains only
copies o the sign bit (aU O's or all J's), then tile CF and the OF Hags will both be O's. The
AF, PF, SF, and ZP lags are undefined after IMUL
To multiply a signed byte by a signed word it L< """""sary to move the byte into a
word location and fill the upper byte of the word with copies of the sign bit. This can be
done using CBW instruction.
Exampleo:
IMUL BL ; AL < BL, result in AX
IMULCX ; AX X ex, high-order word of result in, ox and
; low-order word of result in AX.

Copyrighted material
Mleroproc:esiiOf'S and Interfacing 3-28 8086 Instruction Set- ALP

3.5.5 Division
This group of instructions consists of following group of instructions
orv
IDIV

DIV Instruction : DIV source

This instruction L.:; used to d ivide an unsigned word by a byte or to d iv ide an


unsigned double word by a word.
When dividing a word by a byte, th! word must be in AX register. After the division
AL will contain an 8-bit quotient and AH will contain an 8-bit remainder. tl an attempt is
mad~ to divide by 0 or the quotient is too large to fit in AL (greater than FFH), the 8086
will automatically execute a type 0 interrupt.
When a double word is divided by a word, the most significant word of the double
word must be in OX and the lcastooSignificant word must be in AX. After the division AX
will contain a l(K)it quotient and OX will oontain a 16--bit remainder. Again, if an attempt
is made to divide by 0 or the quotient is too large to fit in AX regislff (grealff than
FFFFH). the 8086 will do a type 0 interrupt. For ON instruction source may be a register
or memory k>cation.
To divide a byte by a byte, it is necessary to put the dividend byte in AL and fill AH
with all O's. Similarly, to divide a word by a word, it is necessary to put the dividend
word in AX and fiU OX with aJJ O's.
Flags : All flags ar~ undefinro after a DIY instruction.
Examples ;
DIVCL ; Word in AX/byte in CL,
; Quotient in AL, remainder in AH.
DIV CX ; Double word in OX and AX/ word in CX,
; Quotient in AX. remainder in OX.
IDIV Instruction : IDIV source

This lntitruction is used to divide a b;gncd word by a signed byte, or to divide a


signro double word (32-bits) by a signed word. Rest all is similar 1o DIV instruction.

3.5.8 BCD and ASCII Arithmetic


The 8086 allows arithmetic manipulation of both BCD (Binary coded decimal) and
ASCU (American Standa.rd Code for Information Interchange) data. This is accomplished
by instructions that adju.<t the numbers for BCD and ASCII arithmetic. Let us sre
instructions used for BCD and ASCJJ arithmetic.

Copyrighted material
Mlcropn>cessors and Interfacing 3 - 29 8086 Instruction Set and ALP

3.5.6.1 BCD Arithmetic


The 8086 provides two instructions to support BCD arithmetic. They correct result of a
BCD addition and a BCD subtraction. 11le OAA (decimal adjust after addition) inJ:;truction
follows BCD addition. and the DAS (decimal adjust after subtraction) follows BCD
subtraction. Both instructions correct the result of the addition or subtraction so that 1t is a
BCD number.
DAA Instruction : Decimal Adjust Accumulator.
This instruction is used to make sure the result of adding two packed BCD numbers is
adjusted to be a legal BCD number.
Instruction works as follows :

1. If the value of the low-order four bits (03-Do) in the Al is greater than 9 or if AF
is set, the instruction adds 6 (06) to the low-order four bits.
2. U the value of the high-order four bits (O,.D,) in tl>e Al is greater than 9 or if
carry flag is set, the instruction adds 6 (60) to the high-order four bits.
Examples :
I. ; AL = 0011 1001 = 39 BCD
; Cl = 0001 0010 = 12 BCD
Add AL, CL ; AL = 0100 1011 = 4BH
DAA ; Add 0110 Because 1011 > 9
; Al = 0101 0001 = 51 BCD
2. = =
; Al 1001 0 110 96 BCD
; BL = 0000 Olll = 07 BCD
ADD Al, BL ; Al = 1001 1101 9DH
DAA ; Add 0110 Because 1101 > 9
; AL 1010 0011 A3H
; 1010 > 9 so add 0110 0000
; AL 0000 0011 = 03 BCD, CF = I. The result is 103.
The instruction updoHes the AF, CF. PF1 and ZF. The OF is undefined after DAA
instruction.
No le : only work... for AL.

DAS Instruction : Dc>cimal Adjust After Subtraction.


This instruction is used after subtracting two packed BCD numbers to make sure the
rc!t"Uit is correct packed BCD. Instruction works as fo11ows :

I. If the value of the low-order four bits (03-Do) in the AL is greater than 9 or if AF
is set; the instruction subtracts 6 (06) from the low-order four bits.
2. If the value of the high-order four bits (O,.D,) in the Al is greater than 9 or if
carry flag is set, the instruction subtracts 6 (60) from the high-order four bits.

Copyrighted material
Microprocessors and Interfacing 3-30 8086 Instruction Set and ALP

Examples:
I. ; AL 0011 0010 a 32 BCD
; CL = 0001 0111 = 17 BCD
SUB AL, cL ; AL = 00011011 = 1BH
; Subtract 0110 Because 1011 > 9
; AL = 0001 0101 = 15 BCD
2. ; AL 0010 0011 23 BCD
CL = 0101 1000 = 58 BCD
SUB AL, CL ; AL = 1100 1011 = CBH CF = I
; Subtract 0110 (6) Because 1011 > 9
; AL 1100 0101 = CSH
; Subtract 0110 0000 Beca""" I 100 > 9
; AL = 0110 0101 = 65 BCD CF = I,
; CF 1 means borrow
; is Meded means numb<!r is ru>gative (- 65).
The OAS instruction updates the AF, CF, PF, and ZF. The OF flag is undefined a.fter
DAS instruction.
Note : DAS only works for AL

3.5.6.2 ASCII Arithmetic


ASCD numb<!rs range in value from 30H to 39H for the numbers o-9. The 8086
provick's four instructions for ASCll arithmetic.
AAA:ASCII adjust afte< addition
AAS :ASCII adjust after subtraction
AAM:ASCD adjust afte< multiplication
AAO :ASCll adjust before division
AM Instruction : ASCU Adjust for Addition.

1be number,; from 0-9 are rep"'"""ted "" 30H-39H in ASCD oode. When you want to
add two dimal digilll whidt are represerued in ASCD oode, it is necessary to mas1c upper
nibble (3) from the <Ode before addition. 1be 8086 allows you to add the ASCD oodes for
two decimal digits without ma.'lking off the :r in the upper nibble of each digiL 1be AAA
instruction can b<! used afte< addition to get the current result in unpacked BCD form.

~ =
; AL = 0011 0100 ASCII 4
; CL = 0011 1000 ASCII 8
ADO AL,CL ; AL = 0110 1100
; 6CH a lncom!ct temporary result
; AL = 0000 0010 Unpacked BCD for 2.

Copyrighted material
Microprocessors and Interfacing 3. 31 8086 l(latruction Set and ALP

; Carry 1 to indicate correct answer ls 12


=
dt'Clmal.
The AAA instruction updates the AF and the CF, but the OF, PF, SF, and ZF are left
undefined.
Note : The AAA instruction only works on the AL register.

AAS Instruction : ASCD Adjust After Subtraction.


The numbers from 0-9 are represented as 30-39 in ASCD code. When you want to
subtTact two decimal digits which are represented in ASCD code. it is ne>SSary to mask
upper nibble (3) from the code before subtraction. The 8086 allows you to subtract the
ASCJJ codes for two decimal <figits without mnsking off the "3" in the upper rubble of
each digit. 'The AAS instruction can be used after subtraction to get the current result in
unpac.ked BCD form.
ExampiH:
L ; AL = 0011 1000 ASCII 8
; CL = 0011 0010 ASCJJ 2
SUB Al. Cl ; AL = 0000 0110 BCD 06
; CF 0
'' AAS ; AL = 0000 0010 = BCD 06
; CF c 0 no borrow required
2. ; AL = 00 II 0010 ASCII 2
; CL = 0011 1000 ASCII 8
SUB AL. CL ; AL 1111 1010 a FAH
; CP = I
AAS ; AL = 0000 0110 BCD 6
; CF = I borrow na'<led means (- 6)
AAM 1..-on : ASCD Adjust After Multiplication.
After the two unpacked BCD digits are multiplied, the AAM instruction is used to
adjust the product to two unpad<ed BCD <figits in AX.
Eumples :
; Al = 0000 0100 Unpacked BCD 4
; Cl = 0000 0110 = Unpacked BCD 6
MULCL ; AL x Cl Result in AX.
; AX = 0000 0000 0001 1000 = 0018H
AAM ; AX = 0000 0010 0000 0100 = 0204H
; Which is unpacked BCD for 24.
Now by ad<fing 3030H in AX register we get the result in ASCD fonn.

Copyrighted material
Microprocessors and:fntiOI'facing 3 -32 8086 Instruction Set and ALP

AAD Instruction : ASCII Adjust Before DivL<ion.


AAD converts two unpacked BCD digits in AH and Al to the equivalent binary
number in AL This adju~tment must be made before dividing the two unpacked BCD
digits in AX by an unpac.ked BCD byte. After the division Al will contain the unpacked
BCD quotient and AH will contain the unpacked BCD remainder. The PF, SF and ZF are
updated. The AF, CF and OF are undefined after AAD.

Eumples :
; AX = 0400 unpacked BCD for 43 decimaL CL = 07H
AAD ; Adjust to biruuy before divi;on,
; AX 002BH a 2BH c 43 decimal.
DIV Cl ; Divide AX by unpacked BCD in CL.
; AL = quotient = 06 unpacked BCD
; = =
AH remainder 01 unpacked BCD
Now by adding 3030H in AX register we get the quotient and remainder in ASCfl
form.

3.5.7 Basic Logic Instructions


The basic logic instructions inc.lude AND, Oft Exdusive-OR, and NOT. This group
also includes TEST instruction which is a special form of the AND ins truction.
AND Instructio n : AND destination, source.

We know th.'\t, AND operntion with two inputs produCt..)$ res ult logic 1 only when both
the inputs are logic 1. i.e. Y = A B.

A 8 y

0 0 0

0 1 0

1 0 0

1 1 ,
Table 3.2 : Truth table for AND gate
This instruction logically ANDs each bit of the source byte or word with the
corTcsponding bit ln the destin.,tion and stores result in the destination. 'The source may be
an immediate number, a register or a memory location. The destination may be a register

Copyrighted material
Microproe<~saora and ll!lerfacing 3 - 33 8086 Instruction S.t and ALP

or a memory location. ~ source and destination both cannot be memory locations in the
same instruction. The CF and OF are both 0 <liter AND. The PF, SF and ZF are affected.
Af is undefined.
Eumpleo :
I. ; AL = 1001 0011 = 93H
; BL = 011 1 0101 = 75H
AND BL, AL ; AND byte in AL with byte in BL
; BL 000 1 0001 = llH
2. ; ex = OliO lOll 1001 lllO
AND CX, OOFOH ; ex oooo oooo
= 1001 oooo
11\e AND operation dears bits of a binary number. The task of dearing a bit in il
binary number is rolled masking. The Fis. 3.14 s hows the prore;s of mnsking.

xxxx xxxx Unknown 8-bit binaty number


1 1 1 1 0000 Masking pattem

X X X X

Fig. 3.14 Masking using AND operation

OR Instruction : OR destination, source.


We know that, OR ope-ration w ith two }nputs produC('S result logic 1 when any oate or
both inputs are logic 1 i.e. Y = A + B.
1

A 8 y

0 0 0
0 1 1

1 0 1

1 1 1

Tabl 3.3 Truth tablo for OR gate


This instruction log.ic.ally ORs e:.lch bit of the source byte or word with the
corresponding bit in the destination and stores result in the destination. The soul'O! may be
an immediate number, a register or a memory location. The destination may be a register

Copyrighted material
Microprocessors and Interfacing 3'- 34 8088 Instruction Set and ALP

or a memory location. The source and destination both can not be memory locations in the
some instruction. The CF and OF are both 0 after OR. The PF, SF and ZF are affected. AF
is Ul'ldefin('<f.

Examples :
I. ;
AL = 1001 0011 = 93H
Bl 0111 0101 75H
;
OR BL, AL ;
OR byte in AL with byte in BL.
;
BL = 1111 0111 = F7H
2. :ex = 0110 1011 10011110
OR CX. OOf()H :ex= 0110 1011 nn 1110
The OR instruction is used to ..,t (make one) any bit in the binary number. This is
illustrated in Fig. 3.15.

xxx x xxxx Unknown 8bit binary number

c:= ,, ,,
1 1 1 1
0000
xxxx
S8111ng pattem

Result

' Set bits

Fig. 3.15 Setting bills using OR operation

XOR Instruction : XOR dt.-stin.:1tion, source.


We know thnt, XOR operation produces result logic 1 when odd number ol inputs are
logic I i.e. Y = AB+AB.
A 8 y

0 0 0

0 , 1

1 0 ,
, , 0

Table 3.4 : Truth table for XOR gate


This instruction logically XORs enclt bit of the source byte or word with lhe
corresponding bit in the destination and s tores result in the destination. Ttu! sourot may be

Copyrighted material
Microprocessors and Interfacing 3 - 35 8086 ins~ucuOn Set and ALP

an immed.iatc number, J. register or a memory locatio'' Tile d~tination may be a register


or a memory location. '; he soure<> and destina tion both cannot be 1nernory loc;;.tion~ in the
same instru<:tion. The Cf and OF are both 0 ;1fh.r XOR. Th<' PF, SF md ZF a~ a fft'Ct<:'d. AF
is und"'f'int."<<.
Examples :
I. ; AL ~ 1010 l lll AFH
; BL = 1 111 0000 = FOH
XOR BL, AL ; XOR b)te in AL with byte in BL
;BL= 0101 ll ll =SFH
The XOR instruction is used if some bits of a register or ffi(mory Jomtion must be
inverted. This instruction allows part of a number to be inverted or' cOi.hplt>mentc.d . This is
illustrated in Fig. 3.16. ' '

~n~ry number
c=c0 xxxx
0 0 0 0
xxxx
xxxx
1 1 1 1

x x xxl
Unknown e.-bi1

Pattern for invening lower 4-bils

Resutl

' lnVQrtOO bit&

Fig. 3.16 Inversion of part of a number using XOR operation


~ ~J '
NOT Instruction : NOT dcstinaHon.
The NOT in.::truction inverts each bit of a byte or a word. 1ht- destination can IX'
register or a memory location.
Flags : NOT instruction affecb no flag.

Eumpleo :
; AL e 0110 liOO
NOTAL ; AL = 1001 0011
; ex 1010 11 11 0010 OliO
NOT ex ; ex= 0101 oooo 1101 1001
Test and bit test instructions :
The TEST in.o;truction performs the AND oper.ltion. The difference is that the AND
ll\.o;truction changes the destination operand, while the TEST instruction does not. A TEST
only affects the condition of the flag register, which indkates the result of the test.
PF, SF and ZF will be updated to s how the rt>Sults of the ANDing. PF has meaning
only fo r the lower 8 bits of the destination. AF wi.U be undefined.

Copyrighted material
Microprocessors and Interfacing 3 . 36 80861nstruction Set and ALP

Examples :
TEST AL, Cl ; AND eL with Al.
; Update flogs, resttlt is not stored.
TEST BX, ex ; AND ex with BX.
; Update flags, result is not ston.od.
Th.: TEST instruction functions in the similar manner as a CMP instruction. The
di((crcnre is that the TEST instruction normally tt.-sts a s ingle bit (or occasionally multiple
bits), while the CMP instruction tests the (.'1\tirc byte or word. The Fig. 3.17 shows the bit
pattern and h.>St operation fo r t~ting of bit 0. lf zero nag is set (Z = 1) after this operation,
the bit under test bit..O is zero ; oth~rwise bit 0 is 1.
4

The cro flag is usually tc'Sted by JZ or JNZ instmctions. Therefore, the TEST
instruction is usually followed by either the JZ or JNZ instruction.

xxxx xxx x UnknOwn &..bit binary numbet

0 0 0 0 0 0 0 1 Bit pattem 10 test bit 0

0 0 0 0 0 0

Fig. 3.17 TEST operation


3.5.8 Shift and Rotate

3.5.8.1 Shlft
Shift instructions positjon or move binary data to the left or right by shifting them
within the register or memory location. They also pe:rfonn multiplication by powers of 2"
Oeft shift) and division by powers of 2 (right shift). The shift operations can be classified
as logical shifts and arithmetic shifts. The logical shifts move a 0 into the rightmost bit
pooition lor a logical left shift (SHL) and a 0 into the leftmost bit pooition lor a logical
right shift (SHR). The arithmetic left shift (SAL) and logical left shift operations are
identical. However, arithmetic and logical right shifts arc different because the arithmetic
right shift (SAR) copies the sign bit through the number, while the logical right shift
copi<!s a 0 through the number. This is illus!Tated in Fig. 3.18. logical shift operations are
used with unsigned numbers; they perform multiplication or division of unsigned
numbers. On the otherhand, arithmetic shift operations are used with signed numbers;
they perform multiplications or division of signed numbers.

Copyrighted material
Mlcroproceuora and lmerfac:lng 3 - 37 8086111Siruc1ion.Set and ALP

CY Target register or memol)'

SHL Of--(==~==~~- 0

CY

SAL D-
-{1== ==:=JI- 0

CY
SHR
o -IC:::=:::=::=J---0
Ltt,I :::=:::=::=J--- 0
Sign blt(MSB)

Fig . 3.18 Shift operations

SAUSHL Instruction : SAL/ SHL destination, count


SAL and SHL arc two mnemonics for the same instruction. This instruction shifts each
bit in the specified destination to the left and 0 L stored a t LSB position. The MSB is
shifted into the carry flag. The destination can be a byte or a word. It can be in a register
or in a memory location. The number of s hifts ar~ indicated by oount. But if t~ number of
shifts required is one, you can place 1 in the CO\mt position. If number of shifts are greater
than 1 then s hift count must be loaded in CL register and Cl must be placed in the count
position of the instruction.
Diagram shows SAL instruction for byte operation.

After Execution [J
Flags : All flags are affected.

Copyrighted material
Mlcroproeest,Gtf.andlnterfaclng 6086 Instruction Sot end ALP

Examples :
SAl. CX. I ; S hift Wt)rd in ex 1 bit pt_')!tition Jdt. 0 in LC)B
M OV CL, OSH ; Lvad desired number of shifts in CL
SAL AX, CL ; Shift word in AX left 5 times
; Os in 5 least-significant bits.
SHR Instruction : SHR destiniltion. count

This instnaction shift~ each bit in the specified destination to the right and 0 is s tored
a t MSB position. The LSB is shifted into the carry flag. The destination can be a byte or a
word. U can be in a register or in i-'1 memory location. The number of shifts a re indicated
by count. If number of shifts required is one, you can place 1 in the count position. But if
the number of :ohifts are bl'ft'aler than l then shift count must be loaded in Cl regis ter and
CL must tx p la cl'<'l in the count p<'~ition of the instm ction.
Di.t))r;:un 1-ohows SH R instru ction fo r byte uperatlon.

After Execution

.
Flags : AU flags an.o affected .

Examples :
SHR CX, 1 ; Shift word in CX 1 bit position right, 0 in MSB.
MOV CL, OSH ; load desired number of shifts in CL
SHR AX, CL ; Shift word in AX right 5 limes
; O's in 5 most significant bits.
SAR Instruction : SAR dt.~ti na tion~ count.
This instruction ~hifts t>ach bit in the spedfied destination somt~ number of bit
po:-iti~~n~ to lh l: ri):.ht. r\ :- a hit i!'l- ~hiflt.-d o ut l'lf the ~lSI~ po~ilic)rt, a t:t'PY of the old MS B is
put in tiw ~tSB positil)J\. The LSO \\'ill l.x ~hift..:d into CF. In th~ case or mu1tipl" shifts, CF
will ctmt41in the bit most n."Ccntly ~hift(.od in from the LSB. Bits shifted into CF previously
w ill be lost.
Tht' ~..-t estiau1 tion (an t;>e a byte or a word. It can bot in a register or in a memory
h.K.ltion. The number of shi fts are indicated by count. If number of shifts required is one,
you can place 1 in the count position. J( numb<-r of shifts are greater than 1 then shift
count must be loaded in CL rt.~iS IN and Cl must be pla'd in the count position of the
instruction.

Copyrighted material
Mlc:tJ>prOCHSors end lnterfeclng 3. 39 8088 lnllnic:tion set and ALP

Diagram shows SAR instruction for byte operation.

~CY
~ 1-G

Flags : All flags are affc>cted.

Examples:
SAR BL, I ; Shift byte in BL one bil position right.
MOV CL, ()IH ; Load dl>sired number of shifts in Ct.
SAR DX, CL ; Shift word ston..'Cl in OX 4 bit posilions right.

3.5.8.2 Rotate
Rotate instruction." position or move binary data by rotating the infonnation in a
register or memory lorntion,. either from one end to another or through the carry flag. This
is illustrated in Fig. 3.19.

CY Target register or memofY


RCL
( R01ale left through cany )
cO h
CY
ROI.
{ RDtale left }

CY
h
RCR
( Rotate right through carry )
I D-J
ROR
( Rotate right )

Fig. 3.19 Rotate operations

Copyrighted material
Micn>processors and Interfacing 3-40 8088 Instruction Set and ALP

ROL Instruction : ROL destination. count.


This instruction rot~,tcs aU bits in a specified byte or word to the left some number of
bit positions. MSB is p laced as a new LSB and a new CF.
Diagram shows ROL ins truction for byte rotation.

The destination can be a byte or a word. It can be in A register or in a memory


locat-ion. TI\c number o( s hifts a.tc indicated by count. lf number of s hifts f'\_"'qUired is one
you can place 1 in the count position. lf number of shifts are greater than 1 then shift
<:ounl must be loaded in CL regi$ler and Cl must be placed in the count position of the
instruction.

Examples :
ROL ex, I ; Word in ex one bit position left, MSB to LSB and eF
MOV eL. 03H ; Load desired number of bits to rotate in eL.
ROL BL, CL i Rotate BL thrt.--e positions.
ROR Instruction : ROR destination, count.
This instruction rotates all bits in a specified byte or word to the right some number of
bit positions. LSB is placed as a new MSB and a new eF.
The destination can be a byte or a word. It can be in a register or in a memory
location. The number of shifts arc indicated by count. if number of shifts required is one,
you can place 1 in the count position. JJ number of shifts are greater than 1 then shift
count must be loaded in eL register and eL must be placed in the count position of the
instruction.
Diagram shows ROR instruction for byte rotation.

Copyrighted material
Mlcropn>ceQO,. and Interfacing 3-41 8086 lna1ructlon Set and ALP

Examples :
RORex, I ; Rotated word in CX one bit position right.
; lSB to MSB and CF.
MOV CL, OOH ; Load number of bits to rotate in CL.
ROR BL, CL ; Rotate BL three positions.
RCL Instruction : RCL destination, count.
11\is instruction rotates a ll of the bits in a specified word or byte some number of bit
positions to the left along with the carry flag. MSB is placed as a new carry and previous
carry is p laced as a new LSB.
The destination can be a byte or a word. It can be in a regL~ter o.r in a memory
location. The number of shifts are indicated by count. lf number of shifts required is one,
you can place 1 in the count position. If number of s hifts are greater than 1 then shift
count must be loaded in CL reglstcr and CL must be placed in the count position of the
instruction.
Diagram shows RCL instruction for byte rotation.

Examples :
RCL ex, I ; Rotated word in CX I bit left, MSB to CF, CF to lSB.
MOV CL, 04H ; Load number of bit pooiHons to rotate in CL.
RCL AL, CL ; Rotate A L 4 bits loft.
RCR Instruction : RCR destinatiot,, count.
This instruction rotates all of the bits in a spt>cified word or byte some number of bit
positions to the right along with the carry flag. lSB is placed as a new carry and previous
carry is placed as a new MSB.
The destination can be a byte or a word. It can be in a register or in a memory
location. The number of shifts a re indicated by count. If number of shifts ri.>quired is oale
you can p lace I in the count position. If number of shlfts are greater than I then shift
count must be loaded in CL register and CL must be placed in the count position in the
instruction.

Copyrighted material
110M 1nstruc:t1on Set and ALP

Diagram shows RCR instruction for byte rotation.

8~
r ~KJJ
CY

Eumples :
RCR ex, I ; Word in ex I bit righ~ LS8 to CF, CF to MSB.
MOV CL, 04H ; Load number of bit positions to rotate in CL.
RCR AL, CL ; Rotate AL 4 bits right.

3.6 String Instructions


11le 8086 instruction set provides following string instructions.
REP/ REPE/REPZ/REPNE/REPNZ
MOVS/MOVSB/MOVSW
LODS/LODSB/LODSW
STOS/STOSB/STOSW
CMPS/CMPSB/CMPSW
SCAS/SCASB/SCASW
from the ab<we six ~tructions we have already studied first four instTuctions in
section 3.4. the remaining two in~tructions arc string compare instructions. The string
romparic;on instructions allow the progr-ammer to test a section of memory against cl
constant or against another section of memory.
CMPS/CMPSBICMPSW Instruction :

A string is a series of the same type of data items in sequential memory locations. The
CMPS instruction can be used to compare a byte in one string with a byte in another
string or to compare a word in one string with a word in another string. SI is used to hold
the offset of a byte or word in the source string and Dl is used to hold the offset of a byte
or a \\'Ord in the other string. The comparison is done by subtracting the byte or word
pointed to by Dl from the byte or word pointed to by 51. The AF, CF, OF, PF, SF, and ZF
nags are affected by the comparison., but neither operand is aifected.

Copyrighted material
Microprocessors and lntlffaclng 3 43 8086 Instruction Set and ALP

Examples :
; Point St at source string. Point Dl at
; destination string
MOV 51, OFFSET F_STRING
MOV Dl, OFFSET S_STRING
CLD ; OF dcart.'<l so 51 and Dl will
; autoincrement after compare
eMPS F_STRING, S_STRING ; The assembler uses names to determine whether
; strings were declared as type byte or us type
; word.
MOV e x, 100 ; Put number of string elements in CX, Point 51 at
; source of string and 0 1 at destination of string
MOV 51, OFFSET F_STRING
MOV DL OFFSET S_STRING
STD ; OF set so SJ and 01 will autodecremcnt after
;compare
REPE CMPSB ; Repeat the comparison of string bytes until end
; of string or until comparro bytes are not equal.
After the comparison 51 and Dl wilJ be a utomatically incrc:mcnted or decremented
according to direction flag to point to the next element in the two strings (if OF = 0, 51
and OJ t otherwise l ) CX functions as a counter which is decre.ll'llented after each
comparison. This will go on until ex = 0.
SCAS/SCASBISCASW Instruction :

SCAS compares a string byte with a byte in AL or a s tring word with word in AX.
The instruction affects the flags, but it doc'S not change either the operand in AL (AX) or
the operand in the string. The string to be scanned must be in the extra ~~lent and 01
must contain the offset of the byte or the word to be compared.
After the comparison OJ will be automaticaUy incremented or decremented according
to direction flag to point to the next clement in the two s trings (if OF = 0, 51 and 01 t
otherwise J. ) CX functions as a counter w hich is dC'Crcmentcd after each comparison. This
will go on until ex = 0. SCAS affects the AF, eF, OF, PF, SF and ZF flags.

Examples :
; Scan a text string of 80 charnciC'r.:l
; for a carriage return
MOV AL, OOH ; Byte to be scanned for into AL
MOV 01, OFFSET TEXT_STRING ; Offset of string to 01
MOV ex, 80 ; ex used as element c<mnter
CLD ; Clear OF; so 01 autoincremcnts

Copyrighted material
Microprocessors and Interfacing 3--44 8086 Instruction Set and ALP

REPNE SCAS TEXT_STRING ; ComP"re byte in string with byte in


i AL.
SCASB says comP"re strings as bytes and SCASW says compare s trings as words.

3.7 Program Control Transfer Instructions


l1lcsc in..o;t-ruction.<oj, arc da.ssificd as
Unconditional transfer instructions -CALL. RET. JMP
Conditional transfer instructions - J cond
3.7.1 CALL and RET Instructions
Wheru..'"Ver we na."CC to use a group of instructions several times throughout a program
there are two ways we can avoid having to write the group of instructions each time we
want to use them. One way is to write the group of instructions as a separate procedure.
We can then just CALL the proa.>dure whenever we need to execute that group of
instructions. For calling t.he procedure we have to store the return address onto the stack.
This process takes some time. If the group of instructions is big enough then this overhead
time is negligible with respect to execution time. But if the group of instructions is too
t"hort. the overhead time and execution time are comparable. In such cases; it is not
desirable to write prOC'edures. For these cases, we can use macros. Macro is also a group of
in.'trucUons. Each time we NCA LL.. a macro in our program, the assembler will insert the
defined group of instructions in place of the "CALL'". An important point here is that the
assembler generates machine codes for the group of instructions each time macro ls called.
So there is not overhead time involved in calling and returning from a procedure. The
disadvantage of macro is that it generates inline code each time when the macro is called
which tal= more memory. In this section we discuss the procedures.
From the above discussions; we know that the procedure is a group of instructions
s tored as a separate program in the memory and it is caned from the main program
whenever required. The type of proredure depends on where the proredure is stored in
the memory. U it is In the same code segment where the main program is s tored then It is
called neou procedure: otherwise it is referred to as far procedure. For near procedure
CALL instruction pushes only the IP register contents on the stack, since CS register
contents remains unchanged lor main program and procedure. But for far procedures
CALL instruction pushes both IP and CS on the stack. Let us see the detail description and
examples of CALL instruction to enter the pnx:edure and RET instruction to return from
the procedure.

Copyrighled malerial
MICfoprocesson and Interfacing 80861nstruction Set and ALP

CALL Instruction :
The CALL instmction is used to transfer execution to a subprogram or p rocedure.
11tere are two basic types of CALLs, near and far. A near CALL is a call to a proc:edure
which is in the same code segment as the CALL instruction. When the 8086 executes a
near CALL instruction it decrements the stack pointer b)' two and copies the offset of the
next instmct:ion after the CALL on the stack. It lo<lds IP with the offset of the first
instruction of the procedure in same segment
A far CALL is a call to a procedure which is in a different segment from that which
contains the CALL instruction. When the 8086 executes a far CALL it decrements Ule stack
pointer by two and copies the oontenlo:; of the CS n..~ister to the stack. It then dccrcmetlts
the stack pointer by two again and copies the offset of the instruction alter the CALL to
the stack. Finally, it loads CS with the segment base of the segment which contains the
procedure and JP with the offset of the first instmction of the proct->dure in that segment.

Examples :
Direct within segment (near)
CALL PRO ; PRO is the name of the proo.>dure.
; The assembler determines displacement of pro
; from the ins truc:tion after the CALL and codes
; this displacement in as part of the instruction.
Indirect within.-$egment (neu)
CALL CX ; CX contain., the offset of the ftrst instruction
; of the procedure. RepiMes contents of IP with
; contents of register ex.
Indirect to another segment (fad
CALL DWORD PTR (BXJ ; New values for CS and IP are fetched from four
; memory locations in OS. n.e new value for CS
; is fetched from (BXJ and (BX + I], the new IP
; is fetched from (BX + 2] and [BX + 3).
RET Instruction :

The RET instruction will return execution from a procedure to the next instruction
after the CALL instruction in the calling program. 1f the procedure is a near procedure ( in
the same code segment as the CALL instruction), then the return will be done by reptoclng
the instruction pointer with a word from the top of the stack.
If the procedure is a far procedure (in a different code segment from the CALL
instruction which calls it), then the instruction pointer will be replaced by the word at the
top of the stack. The stack pointer will then be incremented by two. The code segment
n>gister is then replaced with a word from the new top of the stack. After the code
segment word is popped off the stack, the s tack pointer is again incremented by two.
These words/ word are the offset of the next instruction after the CALL. So 8086 will fetch
the next instruction after the CALL

Copyrighted material
MICI'oproeessors and Interfaci ng 3-46 80861nstruclion Set ond ALP

A RET instruction can be followed. by :1 number, for example. RET 4. ln this case the
stack pointer will be incremented by an additi.o na) four addresses after the lP or the lP
and CS are popped off the ~tack. This form is used to increment the s tack pointer up over
parameters passed to the procedure on the s tack.
Flags :The RET instn1ction affects no flags.

3.7.2 JMP Instruction


This grou~ of in.o;tructions will always cause the 8086 to fetch its next instruction from
the location specified or indicated by instnlction rather than from the next location after
the JMP instruction. The JMP instructions are basically classified as unconditional jump
(JMP) and conditional jump ins tructions.. A conditional jump instruction allows the
programmer to make decision.~ based upon numerical tests. The results of numerical tests
an held in the fiag bits; which arc then tcslOO by condition..1.l jump instructions .
The jump instruction.<; arc further dassified as s hort, near and far jump irn;truc:tions. A
short jump is a twobytc instruction that allows jumps or branches to memory locations
within +127 and -128 bytes from the address following the jump. A thr.., byte near jump
a iJows a branch or jump within 32 Kbytes (or anywhere in the current code segment)
from the instruction in the current code segment. The segments arc cyclic in nature. This
mcan.'l that, one locatit1n above oFfset address FFFFH is offset address (XXX)H, two Jocations
above offset address FFFFH is offset address OOOtH and so on. Thus, a dlsplaccment of
32 kbytes allow a jump to any location within the current code segment. In ncar jump
only IP is changed, the contents of CS remains same. A five byte far jump allows a jump
to 01.ny memory location within tht! real memory hJ'Siem. A far jump i,s a jump where
destination location L-; from a diffel'l."ftt SI..1)DlCllt. hl this case both IP and CS Me changed
as spedfit.>d in the destination. The short and near jump arc often called intrasegment
jumps, and the far jumps a re often called intersegment jumps.. Tile short jumps are also
called relative jumps because in such instructions the destination location i<J spt."Cified
relative to the current location. The Fig. 3.20 show s instnK:tion formats for short, near and
far jump instruction.-;..
Near and far jumps are further described as either direct or indirect. lf the destination
add r~ for the rump is specified directly within the instruction, then the jump is described
as direct. II the destination addn.~s for the jump is contained in a regh;Wr or memory
location, the jump is referred as indirect, bt.'>cause the 8086 has to access the specified
r~ister or rnemory h.x:ation to get the required destination address.

Copyrighted material
Microprocessors and Interfacing 3 47 808G Instruction Set and ALP

~
....,.,
I I
EB Dlsp

opcode

near
I I I
E9
Oisp
Low
Disp
Hilt!

opcode

'"' I I
EA
IP
Low
IP
Higll
I cs
Low
cs
High

Fig. 3.20 Instruction fonnats for short, near and far jumps

Eump4es : (Unconditional jump)


JMP NEXT ; Fetch next instruction from address at label NEXT.
; 1t label is in same SL--gment, an offset coded. as part of
; the instruction will be added to the instntction pointer
; to produce the new fetch address. If the label L in
; another segment then IP and CS will be replaced with
; values C\xled in as part of the instruction.
; This type of jump is refc.rred to as direct
; because the displacement of the destination or the
; destination ifl;elf is specified directly in the instruction.
JMP BX ; Replace the contents of IP with the content of BX.
; BX must fir.;t be loaded with the offset of the
; destination instruction in CS. Thi.o; is a near jump. It is
; referred to as an indirect jump because the new value
; for IP oomes from a n.~ter rather than from the
; instruction i~lf as in a d irect~type jump.
JMP WORD PTR [BX] ; Replace IP with a word from a memory location
; pointed to by BX in OS. This is an indirect near jump.
JMP DWORD PTR (SI) ; Replace IP with w ord pointed to by Sl in OS.
; Replace CS with word pointed 10 by Sl + 2 in OS.
; Ths is an indirect far jump.

Copyrighted material
lllicroproc:esoors and lntarfaeing 3 - 48 8086 lnslruclion Set and ALP

As explained earlier, a near type jump instruction can cause the next instruction to be
fe tched from anywhere in the current code segment. To prodtK:e thE' new instntction fe tch
address, thi-; instruction adds a 16bit signed db'Piacetnmt ront.l incd in the in.,010truction to
U'e contents of the instruction pointer register. A 16 bit signed displacement means that
the jump can be to a location anY""here from +32.767 to -32,768 bytes from the current
instruction pointer location. A positive displacen\ent usually means jump is ...ahead" in the
program, and a negative displacement usually means jump is "'backwa rd" in the p rogram.
A special ca:,;. of the direct near jump instrudion is direct short jump. If the
destination for the jump is within a displacement range of +127 to -128 bytes from the
current instruction pointer loation, the destination can be r~acht."'Cl with just an 8 bit
dispL1cernent.
3.7.3 Cond - Conditional Jump
Conditional jumps are always short jumps in the 8086. These in.o;tructions will cause a
jump to a label given in the instruction if the desired oondition(s) occurs in the program
before the execution of the instruction. The destination must be in the range of -128 bytes
to +127 bytes from the address of the instruction after the CQnditional transfer in.o;truction.
H the jump is not taken, execution simply goes on to the ~xt instruction.

Instruction Code Des<:ription Condition for jump

JAIJNBE Jump if above/Jump if nol below or equal. CF=OandZF=-0


JAEIJNB Jump if above or equai/JlmP if not below. CF=OOildZF = 1
JBIJNAEIJC Jump if below/Jump if not above or equ~. CF=1andZF=O
JBEIJNA Jump ff below or equal/Jump if not above. CF=1andZF=1
JEIJZ Jt.mp if equ:aVJump if zero ftag. ZF = 1
JGIJNLE J~..mp if greater/JOOIJ) if noc less than nor equal. ZF=OandCF=O
JGEIJNL Jump if greater than or equal/Jump if not tess than. SF= 0
JUJNGE Jump if tess tha~Jump if not greater than or equal. SF * 0
JLE/JNG JlJIT'C) If tess than or equal/Jump if not gruter ZFe. 1 orSFO
JNC Jump if no cany CF 0
.N"<EIJNZ Jump if noc equal/Jump if not zero ZF 0
JNO .kJmp if no overflow OF= 0
JNP/JPQ Jump W,... parity/Jump K parity odd PF =0
JNS Jump if not sign or jump if positive SF= 0
JO Jvmp K over&w ftag = 1. OF= 1
JP/JF'tO Jv""4> W parity/Jv""4> K parity even PF = 1
JS Jump if sign nag = 1 01' jul"f'C) if negative SF 1
JCXZ Jumo K ex is zero e x= o

Note : The terms greater and less are used to refer to the relationship of two signed
numbers.

Copyrighled material
Microprocess ors and Interfacing 3. 49 8086 1nstruc:11on Set and ALP

3.8 Iteration Control Instructions


These instnctions are used to execute a series of instt:uctions some number of times.
The number is spt..:>Ci fk>d in the CX n..e,ristcr. The CX rt'gist~r b automatic<1lly J~;."Cn;rna:ntOO
by one, each time after execution of LOOP instruction. Until CX = 0, execution w iiJ jump
to a destination sp..--cified by a label in the instruction.
The destination address fo r the jump must be in the range of - 128 bytes to + 127
bytes from the address of the instruction after the iteration w ntrol instruction. For
LOOPE/lOOPZ and LOOPNE/ LOOPNZ instructions there is one more condition for exit
from loop, whkh is given below. If the loop is not taken, execution s imply goes on to the
next instruction after the iteration control instruction.

Instruction Code Description Condition for Exit


1. LOOP Loop through a seQUence of instructions ex =o
2. LOOPEILOOPZ LOop thrOugh a sequence of if\Struetions CX =OO<Zf=O
3. LOOPNEILOOPNZ Loop through a sequence of instructions CX= Oor ZF= 1

3.9 Processor Control Instructions


src
CLC
CMC
sro
CLD
STI
CLI
STC lnstruc:11on :
This instruction sets the carry Rag, STC does not a/feet any other Rag.
CLCinllnJcllon :
11\is instruction resets the carry Rag to zero. CLC does not affect any other Rag.
CMC ln.tructlon :
11\is instruction complements the carry Rag. CMC does not affect any other flag.
STO lnstruc:11on :
This instruction is used to set the din.'Ciion Rag to om' so that 51 and/ or 0 1 can be
deaemented automatically af~ execution o( string in.~tructions. STO does not afft my
other Oag.

Copyrighled malerial
Microprocessors and Interfacing 3 . 50 80861notruction Set and ALP

CLO Instruction :

TI\is instruction is used to reset the d in..>etion flag to zero, so t.hat Sl al'td/or 0 1 can be
incren\L'I'Ilcd automatically a fl t:or CxL-cutinn of string in$tructiOI\S. CLD dOl'S not a ffect any
other flng.

STI Ins truction :

This instruction St'ts the interrupt flag to one. This enables lNTR interrupt of the 8086.
STI does not affect any other flag.

CLI Instruct ion :

This instruction reoets the internpt flag to zero. Due to this 8086 will no t respond to
an interrupt signal o n its INTR inpul Cll does not affect any o ther flag.

3.10 External Hardware Synchronization Instructions


HLT

~VA IT

ESC
LOCK
NOP
HLT Instruction :

Tl\\ H LT in!"tructinn will cause th<! 8086 to stop (f.'tchinJ:; .md t>.xccuting ins tructions.
l1'\c 8086 will m ter a halt s tate. The only w ays to get the proet'Ssor out of the halt s late
are with an interrupt signal on the INTR pin, an interrupt signal on the N MI pin.. or a
n.-"Set ~is'al on the RESFT input.

WAIT Instruction :

When this ins truction executes, the 8086 enters an idle condition w here it is doing no
proc.:'e:'Sing. The 8086 wiiJ s1.1y in thjs idle sta te until a signal is asserted on the 8086 TEST
input pin, or until a valid interrupt signal is receivt.>d on the INTR or the NMI interrupt
input pins.. If a valid interrupt occurs while the 8086 is in this idle st.Ue, the 8086 will
r~tutO JO the idJe s tate after the execution of interrupt service procedure. WAIT affects no
flag.-;. 11tc WAET instnction is used to synchronize the 8086 with external hardware such
<\S the 8087 math ropNCl'SSOr.
ESC Instructi on :

This instruction i.s lL'"C'd to pass instmctions to a coprocessor such as the 8087 math
copmo..~~r '''hich ~httrcs the addn-s.c; and data bus with an ~. Instructions for the
copn ll-\.>S~r arc rcpn.~!ntl:.d hy ,, 6-bit C'o dc cmlxodd~..>d in the ~1pe in~ITu ction.. Wl'l(.'l"' the
8086 fete~ an ESC instn1ction, the ooprocX'SSOr decodes the instructio n and carries o ut the

Copyrighted material
Microprocessors and Interfacing 3 - 51 80861nstructlon' Set and ALP

action specified by the 6-bit code specified in the instruction. In m ost cftses the 8086 tre.1ts
tlw ESC ins truction as :. NOP. In ~nne. c,tstos tht> 80S(; will iiC'C'e$:-> a c.lnta item in rnt"mol'y
for the coprocessor.
LOCK Instruction :
In a multiprocessor system each microprocessor has i t~ own local bus...--s and memory.
The individual microprocessors are connccte d together by a system bus so that each can
access system resources s uch as disk drives or memory. Each microproc:essor onJy takes
controJ of the system btL-; when il needs to access some system resources. The LOCK pr.:-fix
allows a microprocessor to make sure that another processor docs not take control o( the
system bus while it is in the middle or a critical instruction which uses the system bus.
The LOCK prefix is put ln front of the critical instruction. When an instnu; ti(m with a
LOCK prefix CX('Cutcs, the 8086 w ill assert its bus Joc-k s ign.1l output. TI\iS signa l is
connected to <1n external bus controller device w hich tht!n prevents .my other processor
from taking over the syste m bus. LOCK affects no flags.

Examples :
LOCK XCHG SEMAPHORE, AL ; lllo XCHG instn tction rcquiros two bus ocC'<.'SS<'S.
; Tht:! LOCK prefix prevent$ another p rocessor
; from taking control of the system bus bctw("("n
; the h\'0 accesses.
NOP Instruction :
At the time of execution of NOP inst:n.rction, no operation is perfonned eXcept fl'tch
and dt'C'Od,~. It ta k~ thn:-"C dod: cycle~ to t'Xt'('ulc the inslruc:tic-m. NOP in~lnu.ti t)fl dtx"l" n.t, t
affect any flag. This instruction is uSL~ to fill in time delays or to delete and insert
instructions in the program while trouble s hooting.

3.11 Interrupt Instructions


INT Instruction : !NT Type

This instruction causes the 8086 to caJI a far p~~ure. The term type in the
instruction reJers to a number between 0-255 which identifies the interrupt. The address of
the procedure is taken from the memory whose address is four tim~-s the type numbc.>r.

INTO Instruction :
1( the o v<.>rflow nag i~
set. this instntction will cause thc 8086 to do an indin.'Ct (.,r .:all
to a procedure you write to handle overflllW condition. To do call the 8086 will read a
. . OOOIOH and a new value of CS from address CXXJ12H.
new value for W from addn:>ss

Copyrighted material
Mlcroproe:euors and Interfacing 8086 Instruction S.t and ALP

IRET Instruction :

The fRET in~lmC't-icn'l is used at lhe end of the interrupl 5'<.'rvicc routine to return
execution to lhe lntcrrupt'Cli program. The 8086 copies return address from stack into IP
and CS r(."'gisters and thE" stored vaJue of Hags back to the flag rt"gister.
Note : Tiu~ RET instruction dOL~ not copy the lings from the stack back to the Ht1g
register.

3.12 Assembler Directives


ThCre are SCime instructions in the assembly languagE" program which arc not a part of
proc::e;~or instruction set. These instructions are instructions to tiw- assembler, linker, and
lo.1der. The8e are referred to as pseudo-oper~tions or as assembler d_irectives. Tile
nssembl ~r dir.tCtives enable us to control the way in which a program as.._o;embles and lists.
They act during the asS<>mbly of a program and do not generate any executable machine
code.
There are many specialized a.-;.._.:;emble-r d irectives. U!t us St.>e the commonly used
assembler directive in 8086 assembly Language programming.
ALIGN : The align directive forces the assembler to align the next ""b>ment a t an
addrcs...; divisible by specified di\'lsor. 'J"he general fonnat for thi."' directive is as shown
below.
ALIGN number
whc.--rc number can be 2, 4, 8 or l6.
Example : ALIGN 8 ; This for""' the assembler to align the next segment
; at an address that is divisible by 8. The as..-.embJer fills
; the unused bytes with 0 for data and NOP in.~tructions
; for code.
Usually ALIGN 2 directive is used to start the data segment on a word boundary and
ALIGN 4 directive is used to ~tart the data segm.mt on a double word boundary.
ASSUME : The 8086, at any time, can din!ctly address four physical segm.mts which
include a code segment, a data segment, a stack segm.mt and an extra segment. The 8086
may contain a number of logical segments. The ASSUME directive assigns a logkal
segm.mt to a ph)'l'ical S<.'gmetll at any given time. That is, the ASSUME directive tells the
assembler what addresses will be in the segment register.o at execution time.
Example : ASSUME CS : code, OS : Data, SS : stack.
.CODE : This directive provides shortcut in definition of the code segment. General
I format for this directive is as shown below.
II code (name)
I The name is optional. It is basically specified to distinguish differ<'tlt code segments
when there are multiple code segments in the program.

Copyrighted material
Mleroproc:easors and Interfacing 3-53 80861natructlon Set and ALP

.DATA : This din.-"Ctive provides shortcut in defutition of the dat.1 segment.


DB, DW, DD, DQ, nd DT : These directives a re used to define different ty!""' of
variables, or to set aside one or more storage locations of corresponding data type in
memory. Their definitions are M foUows :
DB - Define Byte
OW - Define Word
DD - Define Doubleword
DQ Define Quadword
DT - Do>fine Ten Bytes
Example :
AMOUNT DB I OH, 20H, JOH, 40H ; Dedare array of 4 bytes named
; AMOUNT
MES DB 'WELCOME' ; Declare array of 7 bytes and
; initialize with ASCil COdE'S for letters in
; WELCOME.
DUP : 11\C DUP directive can be USt_"'<f to initialize seveml locations and to assign
values to these locations.
Forrruat : Name Data_Type Num DUP (value}

Example :
TABLE OW I 0 DUP (0) ; Reserve an array of 10
; words of memory and iniHaliu all tO
; words with 0. AlTay is named TABLE.
END : The END directive is put after the last statement of a program to tell the
assembler that this is the end of the program module. 'The as.o;emblt.--r ignores :my
statement after an END din."'Ctive.
EQU : The EQU directive is u......_~ to redefine a do'lla namt' or vari.lblc with an'-llh~r
dat.., name, variable, or immediate value. 1lle directive should be dlfirw..od in a pn'J~ra m
beJorr it i~ referenced.
Fonnats :
Numeric Equate : name EQU expression
String Equate : nnmc EQU <:String>
Example : PORT EQU 80 ; Numeric value
NUM E.QU <'Enter the first number :'>
MES DB NUM ; Replace with string
EVEN : EVEN t~Us the assembler to advance its location oounter if neccss..,ry so that
the next defined data item or label is aligned on an even storage boundary. This feature
makes processing more efficient on processors that access 16 or 32 bits a t a time.

Copyrighted material
Microprocessors and Interfacing 3. 54 8086 Instruction Set and ALP

Example :
EVEN LOOKUP DW 10 DUP (0) ; Ot."CI."Ir-es the array of ten words
; starting from even address..
EXTR.N : The EXTRN directive is used to inform assembler that the names or labels
foUowing the dir\.>ctivc are in some other as....;embly mOOule. for exrunple; if you want to
a
c.1U a procedure which is in a program mOOule assembled at different time, you must
teU the assembler that the procedure is EXTRN. The assembler will then put information in
the object rode file so that the linker can connect the two modules together. For a
reference it is neo..:.S..'M'ltY to specify whether the label is near or fa r.
NOTE : Names and labels referred to as e.xtem.'ll in one module must be declared
public:.

Exampie :
CALLING PROGRAM CALLED PK(X;RAM
DATA SEGMENT EXTRN VAR : FAR
I'UDLIC VAR DATA SEGMENT
VARDW
MOV AX, VAL
DATA ENDS
DATA ENDS
GROUP : A program ""'Y contain several segments of the same type (code, data, or
stack). The purpose of lhe GROUP is to collect them all under one name, so that lhey
reside within one segment., usually a data segment.
Formal : Name GROUP Scgn>mc, .. . , Scg name.
Example :
SEG G ROUP SEG!, SEG2
SEGl SEGMENT PARA 'DATA'
ASSUME DS : SEG

~E\. 1 1"'11 ~
:'lot.: ~EG~IfNT I'ARA 'D.-\TA'
ASSUME DS : SEG
.'
SEG2 ENDS
LABEL : Assembler uses a location counter to keep track of how many bytes it is
from the start of a ~gment at any time. The LABEL directive is used to give a name to
the curre-nt value in the location counter. The labd directive can be used to specify
destination for jump or call instruction or to specify refe-rence to a data item. When labe.l
is lL"'-.'<i r.s dt.-stination for a jump or a call, then the label must be specified as type nea.r or

Copyrighted material
Microprocessors and Interfacing 3. 55 8086 Instruction Set and ALP

as type far. When label is uSL"'CJ to refe-r a dnt..l item it mu:-:t tx- SJ>l-"'Cificd a.s type by te,
type word. or type double word.

Example:
NEXT LABEL FAR ; Can jump to NEXT from
; another segment
NEXT: MOV AX, BX ; Cannot do far jump directly to a label
; with a colon.
; lnitialization of s tack pointer using
; label directive
LENGTH : II is an operator which tells the asS<"mblcr to dclemtine tht.~ number of
elements in some named data item such as a string or array.

Example :
MOV BX, LENGTH STRING! ; Loods the Length of string in llX
MACRO and ENOM : Tht macro~ in the programs can bt.~ ddim-d by MACRO
'
directive. ENDM directive L~ uSL-d along with the MACRO directive. ENDM defines th~
end of the macro .
.MODEL : It is available in MASM version 5.0 and above. This din.""Ctivc provides
short-cuts in defining segments. h is initializes memory model before defining any
segment. The me mory model can be SMALL, MEDIUM, COMPACT or LARGE. We can
choose the memory model based on our requirement by referring foiJowi!'S Wble.

Model Code segments Data s.egments


Small Cl<lc Ooe
Medium Multiple Ooe
Compact Cl<le Multiple
Large Multiple M ultiple

Table 3.5
NAME : The name d irec-tive is used at th(> star t of a :o'I'Ur(l' progr,1m to ~i v(' !'pl>c:ific
n..'mcs to c\lch a~sembly modull'.
OFFSET : It is an operator which tells the ilS..~mbkr to determine the offset ur
displacement of a named dahl item (variable) from the start of the ~gmtnt which cnnt.1in..
it.

Example :
MOV AX, OFFSET MESI ; Loads the of6;el of variable, MESI in
; AX regi.<iter

Copyrighted material
Microprocessors and Interfacing 3-56 8086 Instruction Set and ALP

ORG : The as.~mbler uses a location counte.r to account for its relative position in a
dat.l or code scgm~nl.
format : ORG !!Xptt...-ssion

Example : ORG IOOOH, Set the location counter to lOOOH

PTR : PTR is used to ossig:n a sp<cilic type to a variable or to a label. It is alo;o used to
override the decJared type of n variable.

Example : WORD_LEN DW

MOV BL. DYTE PTR WORD_LEN ; Byto nccess..'S byte from word
PAGE : The PAGE din.--ctive helps to control tho: forma t of a listing of an assembled
program. At the !'~tart of a program the PAGE directive specifies the maximum number of
lin'l"S to list on a pagl." and the n.aximum number of characters on a line.
Format : PAGE [length), )width)

Example : PAGE 52, 132; 52 linos per page and 132 ch.1mcters per line
PROC and ENDP :
PROC : 1be procedures in the prog.rams can be defined by PROC d.in.ctivc. 1hc
procedure name must be p~nt, must be unique, and must follow naming conventions
lor the language. Alter the PROC directive the tenn NEAR or FAR are L'"ued to sp<cify
the type of the procedure.

Example : FACT PROC FAR ; Identifies the start of a procedure named FACT and tells
the assembler that the procedure is far (in a segment with a different name from that
which contains lhe in.o;;tructicm which calls the procedure)
ENDP : ENDP dirt!Ciive is used a long with the PROC directive. ENOP defines the end
of the pron>dure.

PUBLIC : Large probrrams are u::oually written as several separate modules. Each
mod1~e is individuilll) assembled, testro and debugged. When all the modules are
working et')rrc<:tly, their object code files are linked together to fonn the complete program.
In order for the modules to link together correctly, any variable name or k1bel referred to
in other modules must be declared public in the module where it is defined. The PUBLIC
directive is used to tell the assembler tha t a specified name or label will be accessed from
other moduJes.
Format : PUBLIC Symbol I . . .. I

Copyrighted material
3-57 8086 Instruction Set and ALP

Example : PUBLIC SETPT ; M,>kes SETPT available for other modules.


SEGMENT and ENDS : An assembly program in .EXE format consists of one or more
segments. The start of these segments arc defined by SEGMENT directive and the ENDS
statement indicates the end of the segment.
Format : name SEGMENT (option.( ; ll<>gin segment

name ENDS
Example : CODE SEGMENT

CODE ENDS
SHORT : A s hort is a operator. It is us..>d to tell the as.~mbler that only 1-byte
di.:,1>la~ment is la'ded to codt: a jump instruction. If the jump destination is after the
jump in.o;truction in the program. the assembler will automatic..'llly reserve 2.-bytcs for the
displacement. Using the short opt>rator s.1vcs 1-bytc of memory by telling the assembler
that it only needs to reserve 1-byte fo r thl~ particular jump. The short operator should be
used only when the destination is in the ronge of - 128 bytes to +127 bytes from the
address of the instructions after the jump.

Example : j'MP SHORT NEAR_LABEL

.STACK : This directive provides shortcut in definition of the stack segment. General
fonnat for this directive ls as shown below.
.stack (si7,e)
The default siz.c is 1024 bytes.
Example : .STACK 100 ;This reserves 100 bytes for the stack operation.

When stack is not used in the program .stack command can be omitted. This will
reserve in the waming message "no stack segment"' after linking the program. This
warning may be ignored.
TITLE : The TITLE directive help to control the fomlat of il listing of an a!'sembl t~
program. TmE directive causes a title for a progrclm to print on line 2 of e.,"'ch page of the
program listing. Maximum 60 characters are allowed as title.
Format : TITLE text
Example : TITLE Program to find maximum number
TYPE : Tt is an operator which tells assembler to determine t~ type of specified
variable. Assembler determines the type of specified variable in number of bytes. For byte
type variable the assembler gives a value of 1. For word type variable the assembler gives
a value of 2 and for double word type variable the assembler gives a value of 4.

Copyrighted material
Microprocessors and Interfacing 3 . 58 8086 Instruction Set and ALP

3.12.1 Summary of Assembler Directives


Directive Acnon

ALIGN aligns next variable 01 instruction to bvte which Is multiple of operand


ASSUME selects t reQister(sl to be the default for all s.vmbof in t(s)
COMMENT indicates a comment
DB allocates and optionatlv inltiaizes bYtes ol s10raoe
ow allocates and optionally Initializes words of storaQe
DO allocates and optionally initiaizes doublewords of storage
DO allocates and optionally initializes quachNords of storage
DT allocates and optionally initialzes 10.0vte.fono storeae units
END terminates a5semblv: oplionallv indicates entrv oolnt
ENOM tenninates a m&erO definition
ENOP martcs end ol_procedure ctetini.tion
ENOS marks end of $E!Oment or structure
EOU assiMs expression to name
EVEN allons neX1 variable or instruction to even bVIe
EXITM teonlnates macro e~_!lsion
EXTRN Indicates extemally def'f'led symbOls
LABEl creates a new label v.ith specified type and current location counter
lOCAl. dedares local variables in macro definition
MACRO starts maao defini1ion
.MODEl specifies mode for assembling the program .
ORG sets location counter to argument
PAGE sets Jength And width of program listing.; generates page break
PROC starts procedure definition
PTR assigns a specific type to a variable or to a label
PUBliC identifies symbots to be visible outside module
TITLE defines tt'le program listing title

Table 3.6

3.12.2 Variables, Suffix and Operators


Variable : A variable is an identifier that is associated with the first b yt~ of data item. In
assembly la nguage s tatement : COUNT DB 20H, COUNT is a variable.
Example : Array DB 10, 20, 30, 40, 50
Here, array is the variable which is associated with the first byt" of the
data item, i.e. to.

Copyrighted material
Microprocessors and Interfacing 3-59 8086 Instruction Set and ALP

Suffix : In nssembly language programming base of th'-' number of indic.ah.trd by a suffix


as follows :
6- Binary
D - Decimal
0 - Octal
H - Hexadecimal
The default is decimal. The first digH in a hexadecimal number must be 0 through
9; therefore, if the most significant digit is a letter (A-F), then it must be prefixed
with a 0.

Examples : 1010 B 5 1010,


2967 D = 2967 5 29671
3F2AH = 2F2A .,
08129H = 8129"
Operators : Arithmetic operators :"'+",''- ","*'', Mki "/".

Logical Operators: .. AND"', "'OR", "'NOT, and ~xoR".

Logical operators arc s pecially uS<.>d for binary operands.

3.12.3 Accessing a Procedure and Data from another Assembly Module


As mentioned earlie-r, usually a large program is divided into a series of modules.
Each module is individually written, assembled, and tested. The object code files for the
modules are then linked together to gCt~eratc a linked CiJc or executable file.
In order fCJr a linke.r to be able to access data or a procedure in another assembly
module correctly we have to usc two a....scmbl) lang-uage directives : PUBUC and EXTRN.
In the module where a varii.'lble or procedure is declared we must u84!' the PUBLIC
directive to let the linker know that the variable or .procedure can be accessed from other
modult.'S.
In a module which calls a procedure or acccsscs t1 variable in another module, we
must ust thl~ EXTRN directivl to Jet the as.scmbler know thnt thr. procedure or vnriablc is
not in this mudulc but it ha~ to olC("\.'5:0. from another mOOul~. 1'hf.' E.XTRN St..ltcment olL"'
gives the linker some needed information about the procOO.uro. For example : EXTRN
ROUTINE : FAR, TOKEN : BYTE h:lls the linker that ROUTINE is a FAR pron>dure and
TOKEN is o variable of type byte.

,... Example 1 : "FUt1.asm"' coutains a program segmtnt wllidr calls a subrouNtu (procedurt)
;, '"FUt 2 .asm'". Give tile ntef'.SSIIry declarations in FU~1.nsm nud HFife2 asm " (to maY
the subrouliut! of file2.asm availnblr to filt!1.asm which is uot /QC.n/Jy tr.Jailable) aud tile
as~mbliug n11d li11king to obtain the r xtculnblt' Jilt.

Copyrighted material
8086 Instruction Set and ALP

Solution : Filel.asm File2.asm


EXTRN ROUTINE : FAR PUBUC ROUTINE PROC FAR

ROUTINE ENDP

3.13 Assembly Language Programming


A program is a set of instructions arranged in the specific sequence to do the specific
task. It tells the microprocessor what it has to do. The process of writing the set of
instructions which tells the microprocessor what to do is called "Progrilllll1,ling". In other
words, we on say thnt programming i.~ the proc:es..~ of telling the processor ex<\ctly how to
solve a problem. To do this, the programmer must "speAk" to the processor in a language
which proces.sc.lr can understand.

Steps lnvoiWd In Programming

Specifying the problem : The first step in the programming is to find out which
tas k is to be perfonned. This is called specifying the problem. II the programmer
does not understand wMt i~ to be done, the programming proces.o; cannot begin.
Designing the problem-solution : During thi< proccs.<, the exact step by s tep
process that is to be followed (program logjc) is developed and written down.
Codi_ng : Once the program is specified and designed. it can be lmpl.eme:nt<.-d.
Implementation begins with the process of coding the program. Coding the
program means to tell the pro<:es-<Or the exact step by step process in its
language. Each processor has a set of instructions. Programmer has to choose
appropriate instructions from the instruction set to build the program.
Debugging : Once the program or a part of program is coded, the next step is
debuggjng the code. Debugging is the process of testing the code to see if it does
the givon task. If program L< not working properly, debugging process helps in
finding and correcting errors.
To write a program, programmer should know :

How to develop program logic?


How to tell the program to the pmces..wr?
How to code the p rogram?
How to test the program?

Copyrighted material
Mlcrop<ocessors and Interfacing 3-61 8036 Instruction Set and ALP

Flow Chart
To develop the p rogramming logic programmer has to write down various actions
which are t<) ~ performed in proper ~uence. The flow ('hart is a graphical tool that
allows programmer to "'J'reserlt various actions which are to be p<!rformed. The graphical
"'Presentation is very useful for clear understanding of the progranuning logic.
The Fig. 3.21 shows the graphic symbols used in
(..._____.) the flow chart.
Oval : It indicates start or s top operation.
Anow: Jt indicates flow w ith direction.

0 Parallelogram : It indicates input/ output


operation.

c:J Rectangle : It indicates process operation.


Diamond : It indicates decision making

<>
CJ
operation.
Double sided rectangle : It indicates exec:ution of
pre-defined process (subroutine).

Circle with alphabet : It indicates continuation.


0
Fig. 3.21 Graphic symbols
A: Any alphabet

used In now chart The Fig. 3.22 shows sample flow chart.

Start

Cal subroutine

Sic!>
Fig. 3.22 S.mple flowchart

Copyrighted material
Microprocessors and Interfacing 3. 62 8086 Instruction Set and ALP

3.13.1 A&sembly Language Programs


A program which has simply a sequence of the binary codes for the instructions is
C.lllt>d machint' level language program. 11-ljs bin.ny fo rm of the pro~;ram is reft>rred to as
machine language lx.->cause it is the form required by the machine. However, to write a
program in machine language, programmer has to memorize the thousands of binary
instruction codes for a proces."llr. This task is d ifficult and error prone.
To make programming easier, usually programmers write programs in assembly
language. They then translate the assembly language program to machine language so that
it can be loaded into . nemory and executed. Assembly language uses two, three or four
letter words to represent each instruction types. These words are referred to as
mnemonics. The letters in an assembly language mnemonic a re usually initials or a
shortened form of the English word(s) for the operation performed by the instruction. For
example, the mnemonic for addition is ADD, the mnemonic for logic AND operation is
AND, and the mnemonic for the instruction for ropy data from one location to another is
MOV. Therefore, the meaning expres..'ied by mnemoni~ help us to remember the operation
pedormed by the in!ltruction.
Assembly language statements are usually written in a standard fonn and a~embly
lanb"Uage has its own unique syntactical structure~ such as n..~uiring upper case or lower
case, or ro..1uiring colons after Label definitions. Here we discuss the common features that
assembler s han>s.
The assembly text is usually divided into fields, separated by spaces and robs. A
fo rmat fo r a typical line from asstmbly limguo.1gc pmgr;.tm din be given n.s
Label : Mnemonic Operandi, Opernnd2 ; Commt'flt
The firs t field, which is optional, is the label field, used to specify symbolic labels. A
label is an identifier that is assigned to the addri'$S of the first byte of the instruction in
which it appears. As m('fltioncd rorlier, the pi'CSC1lCC of a label is optional, but if present,
the label provides a symbolic name that can be used in branch lnstructions to branch to
the instruction.
The SL:.cond fie.ld is ~monic, which is compulsory. All in.~tru.ctions must contain a
mnemonic. The third and following fields are operands. The prest..-~ of the opemnds
depends on tN! instruction. Som~ in.-;truction.~ have no operands, S4.)me have one, 0\nd sc,)me
have two. If there are two operands, they are separated by a comma.
The t..tst field L~ a comment field. It begins with a delimiter such as the semicolon and
continues to the end of the line. The comments are for our bcnt!.fits, they tell us what the
program is trying to accomplish. Fig. 3.23 shows a typic.1l B086 assembly language
instruction.

Copyrighted material
Microprocessors and Interfacing 3. 63 8086 Instruction Set and ALP

M
\ /oo= o~nd
AGAIN : ADO AX. price (BX) ; Add prke of item to AX

'\
Sr. No.
Label

" Oes.tinalion operand


Fig. 3.23 Typical assembly language instruction
The Table 3.7 shows the comparison between machine level and assembly languages.

Machine Language
""'
Assembly Language
Comment

I. LMguage consists of binary COd&& Language consists of mnemonics whk::h


which specify the operation. speCify the operation.
2. Processor dependent and henoe Processor de9ef!ctenl henoe requires
reQuires knOwtedge of internal knowledge of intornal de-tails or
details of processor to write a processor lO write a program.
program.
3. Programs require less memory Progratn$ require less memory.

Programs have less execution


time.
Programs have aess execution time .

5. Program development is dlfficutL Program development Is simpler than


machine language.
6. h is not user friendty. II i:s tess user friendty.

Table 3.7 Comparison between various microcomputer languages

3.13.2 Assembly Language Programming Tips


We know that a program is a set of instructions arrnnged in the specific sequence to
perform the s pecific task. For writing a program for specific task, p rogrammer may find a
number of solution..:; (in.~truction St.'querlC\."S). A skillt-"<i progmmmer ha.s to dlOOSe an
optimum solution out of them for that specific tnsk. The technique of choosing an
optimum solution L'i an a ct and we can name this as an art of nssc-mbly language
programming. ln this section we will see some tips regarding this w ith tlu;! help of
examples.
What is an optimum solution 1 : The optimum solution is the solution which
takes minimwn memory space for the program and minimum time for the
execution of a task. When we say memory space for the program we consider
space for program storage (program l1."11gth), space for data s torage and space
used by the s tack.
Use of proper instructions : Many times we come across the &;tuation where
more than one set of instntctions are available to perform particular functjon. For
examp le, if the function is add 01 in tht! BX register of 8086 we have two
options : ADD BX~ 0001 H or INC BX. ln such ~ituations we mtLo;t check the space
and tim(' for both the options and then seled the option which requires less

Copyrighted material
Microprocessors a nd lnteffaclng 3-64 8086 lns tructlon Set and ALP

space and time. let us see the space and time requin..>d for ~ two
instmctions. The ins truction ADD BX, 0001H is 4 byte in."ilruction and requires 4
dock cydes to execute. On the other hand, INC BX Lot a single byte instruction
and requires 2 cyc.les for the execution. Tha t is instruction INC BX requires less
memory space and exccutlon thne than instruction ADD BX, OOOl H. Therefore,
programmer must use INC BX instrnctio(l in such situation.
Use of advanced instructions : We must optimally utilize the pl"()C(!S_o;or
capabilities. For example, when it is necessary to write a program to move a
block of data from the source to destination location, a programmer may
initialize a p""'inte.r to indicate source location, a pointer to indicate destination
location, a counter to count tht' number of data elements to be transf('rred. Aftt>r
transfer of one data clement from source to destination location programml'!r
may use INC, DEC and JNZ instructions to increment source and destination
pointers, decrement cmmter and to check whether all data elements are
transerred or not, respectively.
The same task can be implemented by MOVS instruction supported by 8086. Let us sc.>e
the p<'lrt listing of the program with both the approaches and then we compare them.
1. Part listing of program with general approach
MOV SI, lOOOH ; Initialise source pointer
MOV 01 ,2000H Initialise destination pointer
MOV ex, 0020H ; Initialise counter
BACK MOV AX, I S II ; Get data element from souroe
MOV (Oil, AX ; Store it at destination
INC sr ; Incre-ment source pointer
INC OI ; Increment destination pointer
DEC ex ; Decrement counter
JNZ BACK If count is not zero, repeat
2. Patt listing of program wtttl MOVS lnslruetlon
MOV SI~ 1000H ; Initialise source pointer
MOV OJ, 2000H Initialise destination pointer
MOV CX, 0020H ; Init ial ise counter
CLD ; Cl ear direction flag
REP MOVS8 ; Move the entire block
Looking at the lwo programs we can ily notice lhat the MOVSB instructlon needs
neilher counter decrement and jump back nor pointer up<fute instructions. All these
functions are done automatically. S.Causc MOVSB instruction copies multiple bytes fTOm
source to destination. After each byh! transfe< it automatically incremmts SJ and 01
pointers by I (since OF is 0) and decrements count in CX n:gister and il repeats this
process until ex = o.
In the second approach, we require less numbe< of instructions and memory space. As
numbe< of instructions are less, fetching time required for the instructions is also wed
and hence we can say lhat the ...,i>nd approach requi""' less memory space and less time
to exute the same task. So skill programmer ......,. second approach.

Copyrighted material
Mlcroprocosoors and Interfacing 3-65 8086 Instruction Set and ALP

Use of prope.r addressing modes : We know that the diffe rent ways th3t a
p~r can ac:.cess data a re n>ferred to as addl"\.:.ssing modes. If we compare the
variOlL"J addrcs..~ing mod~ n><1grding acces...o; time required for acce!>~ing ope-rands,
we can easily make out that the register addressing takes less time to access
operand than the index and ind irect addressing modes. lt is obvious that when
operands arc available in CPU registers they a rc immediately available for
operation; however when they are in memory we have to fetch them from
memory. Fetching operands takes more time. So it is advisible to store most of
the operands in the CPU registers. We know that CPU registers arc limited in
numbers. Therefore, when they are not enough then only we should use memory
space for storing the operands.
Prepare documentation : Program mus t provide enough information so tha t
other tL<;CtS can utilize thl" program moduJe without having to examine its
internal s tructure. So along with program it is ad\rised to give the following
information.
1. Description of the purpose of the pr<)gram module.
2. In case of subroutine program IL<il ()f passing parameters and retun\ value.
3. Register and memory locations used.
4. Proper c::ommc:nts for e-ach inslruction uSL"'<i.
3.13.3 Programming with an Assembler
let us see what arc the steps involved in developing and executing assembly language
programs. Fig. 3.24 s hows these steps. The left side of the figure shows t~ time pl--*fiOd, a t
which each step in the overall pn~ takl'S place.

Assembty WJnguage
nme period program tel!l wrlnen
~ -------------------I
in 3tY'f text edltot
Program li5ting I I
I

I Etrot messages
I
I

J.- ~
( Assembler
'
Olofect code Other object code
module In binary modules from library

I
Link time ( linker y

I Lil'lked module$ I
..---:-::..

~
.....
"''- ~~' Pro<:o5$01'
...... -
~ - "'...
~
~~
memo<y

Loade< } ""
CPU I
Exoeucion lime
Fig. 3.2.. Steps in program development and execution
Copyrighted material
Microprocessors and Interfacing 3-66 8086 Instruction Set and ALP

The first s tCp in the development process is to writ~ an assembly language program.
The assembly language prog-r am can be written with an ordinary text editor s uch as word
star. edit and so on. The assembly language program text is an input to th~ assembler. The
assembler tran.slat<.-'S assembly language statements to their binary equiva l enL~, usually
known as object rode. Time required to trans la te assembly code to object code is caUed
assemble time. During assembling process assembler checks for syntax errors and displays
them before giving object rode module.
The object code module contains the information about where the progr;,m or module
to bl.> loaded in memory. If the obj\.>ct code module is to be linked with other separately
assembled modules then it cont<tins additional linkage information. At link time, separately
assembled moduk--s ;.\r(' combint.'Cl into one s-ingle load moduJe, by the linker. The linker
also adds any required initialization or finalization code to allow the operating system to
s tart the program nanning an d to return control to the operating system ilfter the program
has completed. Mo~t linker$ allow assembly language modules to be Linked w ith object
code modules compiled (roan highlevcl l:mguagcs as well. lltis allows the programmer to
insert a time-critical assembly language routines, library modules into a program.

.' .
At load time, the program loader copies the program into the computer's main
memory, and at exution time:, program l"XOCution begins.

.
3.13.3.1 Assembling Process
As mCI\tioned ~ rlier. as.<;embler translates a sourc:e file that was created using the
editor into machine Lmguage such as binary or obj1.."C't rode. TI\C' asst."lllbler reads the
SOlli'Ce fil~ o( our program from the disk where we saved it afte:t' editing. An as:.wmbler
usually reJds our sout'C(' file more than once.
The assembler generates two files on the Ooppy or hard during th<>se two P"-''"""' 1lle
first file is calkd the object lilt. The object file contains the binary rodes for the
instructions and information about the addresses of the instructions. The second file
generated by the as..o;cmblcr is called assembler list file. This file contains the assembly
language s tatements, the binary code for each instruction. and the offset for each
instmction.
ln the first pass, the assembler performs the following operation" :
l. Reading the sc.lun:e pn.wam instructions.
2. Creating a symbol table in which ali symbols used in the progmm, together with
their attributes, are ston.---d.
3. Replacing ali mnemonic rodos by thc,;r binary oodes.
4. CNtecting any syntax errors in the source program.
5. Assigning relative addres..-;es to instructions and data.
On a second p.us thnlugh the source program, the assembler extracts the symbol from
the operand field and searches for it in the symbol !able. If the symbol does not appear in

Copyrighted material
Microprocessors and lnterfaclng 3 -67 " Set and ALP
80861nstructlon
.
the tl'lble, the corresponding statement i$ obviously erroneous. I( the symbol docs appcnr in
the table, th~ symbol is rep laced by its addrt'S~ or value.
We can use 0'1 s uitable Editor to type .asm flit.-.. We can runvcrt object (iJc from .asm (if('
using popular assemblers MASM (Microsoft mac-ro assembler) or TASM (Turbo as~mb l cr).
The command on command prompt pcrfom1ing this operation is as given below
C:\ MASM\ BIN\> MASM myprog.asm;
where myprog.asm is name of the .asm file w hich is to be converted to .obj file.

3.13.3.2 Linking Process


A linker is a program used to join together several object files into one l..."'rge object file.
Wht.~ writing large programs, it is usually much more efficient to divide tht: larse
program into smaller modules. Each module can be individually written. tested and
debugged. When all the modules work. they can be linked together to form ,, Iorge
functioning program. . .
Tile linker produces a link file which contains the binary codes for all the combined
modules. The linker also produces a link map which contains the addrt.">S$ infonnation
about lh~ link fik'il. The linker, howevl!r, does not assign absolUte addn.~ to the
program, it only assign'5 relative addn..-sses $tarting: from z.ero. This fbf.m of the program is
SC\id to be rclocatable, because it can be put anywhere in memory t;o ~ run.
The command on' command prompt for ronverting .obj file to .EXE file i~ as given
below :
C : \ MASM \ BIN \ > LINK myprog.obj;

3.13.3.3 Debugging Process


.. .
A debugger is a pn">gr.lm which a llows us to load our ubje:.'Ct rode p rogra m into system
memory, execute the program. and dt.--bug H.
How does a debugger help in d<.-bugging a program ?
I. The debugger allows us to look a t the contents of registers and memory lqcations
after our program runs.
2. It allows us to change the contents of register and memory locations a nd rerun the
program.
3. Some debugger allows us to stop execution after each instntction so we can check
or alter me-mory and register contents.
4. A debugger also allows us to set n breakout at any point in our program. When we
run a program, the system will execute instructions up to this breakpoinl and stop.
We can then examine register and memory contents to see if the results are correct
at that point. U the n.-sults a re correct, we can move the break point to a latl'1"
point ln our program. U results il1'e not COITl"Ct, we can check the prot-,'Tam up to
that point to tlnd out why they are not correct.
In short, debugger tools can help us to isol;tte probll">lns in our program.

Copyrighted material
MleroP<OCessors and Interfacing 3-68 8086 lnsb'uctlon Set and ALP

Debug Commands

Command Command Syntax and Description


Ass&mbter - A (address]
A command allows you to enter the mnomorWc, or humar\-rcadable, lnstrlJCI)orns
dicedly.
Com901e - C range address
C command comparH two m blod<S-
Dump - D (range]
0 command displays a pardon of memory in hex and ASCII.
Enlet - E address (list)
E oonvnand plooes Individual bYtes In memorv.
Fill - F range 1st
F command fills a range of memory With a single value or a list ot valUeS.
GO - G 1= address) (adci'esses)
G oommand execute the program in

~ I
- H value 1 value 2
H command performs addition and subb'action on two hexadecimal nurnbetl.
load - l (add<ess) (drive) (fitst sectO<] (number]
L command loads a fie (or disk sectors) into memory.
M<MI - M range address
M command oooies a block of data from one k>cation to another.
Name N (pathname) (etglist)
N command initializes a fitell3me (and file control blodt) in memory before using
load or write commands.
PIOC$e(l - P ( address)(nlmber)
P command traces the program without entering the subroutine or intet'T\4)t. If
SUCh instruction appears in the program it executes entire subroutine or ~terrupt
routrle and immediately pnxeeds to next instruciton in the sequence.
Quit - a
a ~ Quito rrom debug.
Register - R (register)
R command diOD!ays the
. r conhmt:s on the screen.
Searcn - S range list
S command seardl a ranoe of add<esses lor a list or bvtes or a otrino.
Traoe - T (= address) (value)
T oomm81nd execute one Ot mont lnsVuc:tionl from the current CS : IP location or
1 address, if
.
Unassemble - u (nlnge)
U command translates memorv into Ia """""""ics-
Write - w (address) (dr1vel (flr1l sector! (n...-,
W oonvnand wrlle a bkldt of memory 10 a file or to indMdual disk aedors.

See detail description of debug command in Appendix C.

Copyrighted material
lllcropi'ClCHSon nd lnterfc:lng 3 - 69 8088 Instruction S.t and ALP

3.14 Assembly Language Example Programs : :rh


Program 1 : (Softcopy of this program. PLas m is avai1able at www.vtubooks.com)
NAME Addition
PAGE 52 ,80
TITLE 8086 assembly language program to add two numbers .
. model small
. stack 100
.data
Nol DB 63H ; First number storage
No2 DB 2 EH ; Second numbe r sto r age
Result OW ? ; Double byte reserved for result
. code
START ' MOV AX, @data ; I I nitialises
MOV OS, AX ; data segment J
HOV AL, NOl ; Get fi rst number in AL
ADD AL,N02 ; Add second to it
AOC AH , OOH ; Put carry in AH
HOV Result , AX ; copy result to memory
END START
Program 2 : (Softcopy of this program_ P2.osm is available at www.-vrubooks.com)
NAME Average
PAGE 52, 80
TITLE 8086 ALP to find average of two numbers .
. model small
.stack 100
.data
Nol DB 63H : First number storage
No2 DB 2EH : Second number storage
Avg oa ? ; Aver age of two numbers
. code
START ' MOV AX , @data ; ( Initiali ses
NOV DS ,AX ; data segment
t-10V AL,NOl ; Get first number ln AL
ADD AL, N02 : Add second to it
AOC AH,OOH ; Put carry in A.H
SAR AX, 1 Divide surn by 2
MOV Avg , AL ; Copy result to memory
END START
Program 3 : (Softcopy of thL~ program# P3.asm is available a t www.vtubooks.com)
NAME r1a x imum number
PAGE 52 , 80
TITLE 8086 ALP to find maximum i n the array .
. model small
. stack 100
.data

Copyrighted material
Miuoproeesao~ and Interfacing 3. 70 8086 Instruction Set ond ALP

ARRAY DB 63H , 32H,4 S H, 7SH,l 2 H,4 2 H,09H, l 4H,56H,38H


' ; Array o f ten numbers
Hf,X DB G Max i mum number
.code
START : MOV AX., @data { Initialises
lo10V OS , AX data segment
XOR DI , DI Initialise pointer
ov CL, 10 Initialise counter
LEA BX , ARRAY In itialise base pointer for array
MOV AL, MAX Get maxi mum number
BACK: CMP AL, {BX+DI I Compare number with maximum
JNC SKIP
10V DL, {BX+DI] ( If numbe r > MAX
MOV AL, DL !-tAX n umbe r J
S KI P : INC OT Increment pointe r
D<~CCI. Occre~en t counter
JNZ BACK IF count a 0 stop
o therwise go BACK
MOV MAX, AL Sto re maximum number
NO S'!"AR'l'

Program 4 : (Softcopy of this program, P4.a..""m is available a t www.vtubooks..com)


NAME Fi nd number
PAGE 5 2 , 80
TITLE 8086 ALP to search a number in t he array .
. model small
. stack 100
.data
ARRAY DB 63H,32H,45H,75H,l2H,42H , 09H,l4H,56H , 38H
Array of ten numbers
SER NO DB 09H Numboc to be S@arched
SER POS DB ? Posit i on of th~ s~arch&d number
.code
ST.!>RT : MOV AX , @data ( I nitia lises
I!OV DS , I<X data s~g:ment

ov
>!OV
ES , J!..X
CX. OOOAH tni t ial i se counter
LEA Ol , AFO.AY !nitiall5e ba3e point~ r for a rra y
i'10V AL, SEK_t:J Gel the n\:mber to be searched in AL
CLD Clear direction flag
REPNE SCAS ARRAY Repeat until match occurs or ex 0
MOV AL, 10 { F i nd the searc hed number position
sua At.,CL in the array i f SER_POS is 0
t-10 V SER POS, AL numbQr is not in array; othe rwise
SER_POS gives the position of
number in t he array J
END START
Program 5 : (Soitcopy o( this program, PS.asm i~ avo1ilabl~ at www.vtubooks.oom)
NAME Array sum
PAGE 52 , 90

Copyrighted material
llllcroproceuors and lnterfac:ing 3. 71 8086 InstrUction Set and AlP

TITLE 8086 ALP t o fi nd sum of numbers in t he array.


.model small
. data
ARRAY DB 12H, 24H, 26H, 63H , 25H, 86H , 2FH, 33H ,I OH, 35H
S UM DW 0
. code
START : MDV AX, @data ; ( I nitialise
MOV OS ,AX data segment
MOV CL, IO Initialise counter
XDR 01, DI Initial ise pointer
LEA BX,ARRAY Initi alise array base pointer
BACK: MDV AL, ( BX+DI) ; Get the number
MOV AH,OOH Make higher byte OOh
ADD SUM, AX SUM = SUM + number
INC DI Increment pointer
DEC CL Dec reme nt counter
JNZ BACK If not 0 go to bac k
END START
Program 6 : (Softcopy of this program. P6.;,sm is available at www.vtuboc..lks.a.lm)
NAME separate even- odd
PAGE 52 , 80
TITLE Separate even and odd numbers in t he a rray .
. model small
.STACK 1 00
.data
ARRAY DB 12H,23H, 26H , 63H , 25H, 86H,2FH, 33H,IOH,35H
ARR ODD DB 10 DUP (? )
ARR EVEN DB 10 DUP (? )
.code
START : MOV AX,@data ; { Initialise
MOV DS , AX ; data segment
MDV CL, 10 ; In itialise counter
XDR DI, DI ; Initialise odd_pointer
XDR S I, SI Ini tia lise even_pointer
LEA BP, ARRAY ; Initialise a r ray base_pointer
BACK : !OV AL, OS : (B P) ; Get the number
AND AL,OlH ; f-lask all bi ts except LSB
JZ NEXT : [f LSB 0 go to nex t
LEA BX , ARR_OOD ; f Otherwise
MOV AH, (BX+OJJ ; tni.tiAli$C pointer to o dd t~rr~y

NOV ARR_OOD, AH ; a nd save number in odd array )


IN:: 01 ; Increment odd_pointer
J MP SKIP
N ~XT : LEA 6 X, ARR_EVEN ; ( Initialise pointer
MOV AH, (BX+S l ] ; to even a rray and save number
MOV AH, ARR_EVEN ; in avan array )
INC SI ; Increment even_pointer
SKIP : INC BP ; Increment array base_pointe r
DEC CL ; Decrement counter

Copyrighted material
Microprocessors and Interfacing 3-72 80861notruction Set and ALP

J NZ MCK ; If not 0 go t o back


END START
Jt is important to note that programs discussed so far do not accept any input from
keyboord nd d o not display any result on the video .creen. This is done purposely to
maintain simpUcity. To nccept input in various formats from keyboard nnd to display data
on the video screen we have to use routines provided by Disk Operating System (DOS).
These routines arc discussed in Chapter 9. The programs givctl in the subsequent sections
use routines provided by f.X)S, Therefore, students are suggested to refer these routines
before further r~ading the remaining p..\rt of this text.

3.15 Timings and Delays


ln the n>al time applications, s uch as traffic light control, digital dock, process control,
:"Cri<ll communic..1tion, it is imporlrtnl to keep a track with time. For examp lt~ in traffic light
control application, it is neces.sary to ghe time delays between two transitions. These time
ddays ate in few seconds and can be generated with the help of executing group of
instruction:o: numbc_r of times. This sofhvnre timers are also called time delays or software
delays. l..ct us St...--e how to implement these time dclays or software delays.
As you know r~iCroprucc..:.s.-.or system cOJ\.~ists of two bask components, hardware and
softwarf.'. Tile software component controls and operates the hardware to get the desired
output with the help of instructions. To execute these instructions. microprocessor takes fix
time as per the instruction, s ince it is driven by ~tant frequency dock. This makes it
possible to introduce delay for SJX-'Cific time between two events.. In the followi.ng section
we wiU see d ifferent de1ay implementation techniques.

3.15.1 Timer Delay using NOP Instruction


NOP instruction does nothing but t.'lkes 3 dock cycles of processor time to execute. So
by executing NOP instruction in between two instructions we can get delay of 3 dock
eyeI.,..

3.15.2 Timer Delay using Counters


Countjng can cr~atc tjmc ddays. Since tJw execution times of the ins tructions used in a
counting routine are known. the initial value of the counter, required to gt!t specific time
delay can be determined.
Cloc k cycles required
MOV CX, COUNT ; Load count 4
BACK : DEC ex ; Decrement count 2
JNZ BhCK ; If count ~ 0 , repeat 16/ 4
In this progrnm. the instructions DEC CX and JNZ BACK exf..~ te number of times
~l \lal to count stored in the ex register. The time taken by this program for execution can
~ cnlculatcd with the help or cloc.k cycles. The w lumn to the right of the oomments
indicates the number of clock cyciL"S required for the execution of each in.o;truction. Two
valttes a re Spt'Cifi ed for the number of dock cycles for the JNZ instruction. The smaller

Copyrighled malerial
llillcroprocessOO'S and lnlllffllclng 3 . 73

value is applied when the condition is not met, and the larger value is applied when it iS
met. The first instruction MOV CX, count is executed only once and it requires 4 clock
cyclc.-s.. There are cmmt-1 passes through the loop where the condition is 11'let and control
is transferred back to the first instruction in the loop (DEC CX). The number of dock
cycles that elapse While CX register is not zero 3n! (COunt-J) X (2 + 16). Qn the last pass
through the loop the condition is not met and the loop is terminated. The number of dock
cycles th3t e.Lapse in this pass are 2 + 4.
:. Total dock cycles required to execute the given program

= 4 +(Count - l) x(2+ 16)+(2+4)


MOY ex. Count Loop ~

For count = 100, the numbe-r of dock cycles required are


= 4 + (100- I) X (2 X 16) + (2 + 4)
= 1792
Assuming operating frequency of 8086 system 10 MHz,

fime requin...>d for 1 dod:-<:ycle =


10
~Hz = 0.1 J.15e'C

:. Total time required for execution o( a given progrnm with count equal to 100 is
1?9.2 "sec (1?92 x 0.1).
In the above example, we have calculated the time required for the execution of
program or delay introduced by the program when count value ls given. However, in
most of the situations we know the waiting time or delay time and it is neces...~ry to
detennine what count should be loaded in the ex register to get the specified delay. Let
us consider that we have to generate a deJay of 50 ms using an 8086 system that runs at
10 MHz frequency. Then using same program we can calculate the count value as follows :

St.p 1 : Calculate the number of "'qulred clock cycles


Required delay time
Number of required dock cycles =: Time for 1 _clock cycle

1: 50 m.c; ::3. 5(X} 000


0.1 ...
Step 2 : Find the required count
Number of required clock cycles - 4 - (2 + 4)
Count = 1
Execution Time lor one loop +

500000 - 4- 6
= (16 +2) +
1

~ 27778 = 6CS2H

Copyrighted material
Microprocessors and lntert.clng 3. 74 8016 Instruction Sat nd ALP

3.15.3 Timer Delay using Nested Loops


In this program one more cxtC11\ll.l loop is added to execute the internal loop multiple
times. So that we can get larger delays. The inner loop is nothing but the program we
have seen in the las t St.."Ction.
MOV ex , Multip lier count ; Load multiplier count
REP MOV CX, COUNT ; Load coun t
BACK DEC ex ; Decremen t count
JNZ BACK ; If count ~ 0 , repeat
DEC BX ; Decrement multiplier count
JNZ REPE : If not zero repeat
In the delay calculations of nested loop$, the delay introduced by inner loop is very
large in comparison with the delay provided by MOV BX, COUNT, DEC BX and JNZ
in!iltructions. Therefore, il is not ~~cuy to consider the last loop for the external loop
delay calculations separately. The inner loop delay calculations will remain as it is.
:. Total dock cycles required to execute the given program
= I 4 +(count-l)x(2+16)+ (2+4) ] x multiplier count
MOV CX. Cuut~l LoJop
.............
Ueit loop

For count = 100 and multiplier count 50, the number of dock
cycles required are
= [ 4 + (100 - I) X (2 + 16) + (2 + 4)) X 50

Assuming operating fr<'quency of 8086 system 10 MHz,


Total time required for execution of a given program
= 89600 x 0.1 ~sec = 8.96 rns
l... Examp'- 2 : Writ; "'' 8086 ALP to g~utrntt a dl'fny of 100 ms, if 8086 ~,-ystem frl!tJurm:y
is 10 M.Hz..
Solution :
Program :
MOV CX,. COUNT ; 4
BI'.CK DEC CX 2
JNZ BACK ; 16/ 4
Ste p 1 : Calculate the number of required clock cycles

Required delay time


Number or required dock cyd ~ =
'rime lor1 clOCk cycle
:I; 100 ms 1000 000
0.1,..

Copyrighted material
Mlcropr...,....,... and lnterfaelng 3-75 8086 Instruction Set and ALP

S tep 2 : Find the n.'quired count


Number of required clock cycles-4-(2 + 4)
Count = Execution time for one loop +
1

1000000-4-6
1
(16 + 2) +

G 55556 D904H

,. . Example 3 : Write arr 8086 ALP to gf!m7alt 11 delay of 1 mimtle if 8086 systt-nl freque,cy
is 10 MHZ.
S olution :
Program
MOV ax, mu l tiplier count
RE PE MOV CX, Count ; 4
BACK ' DEC CX ; 2
JNZ BACK ; 16/4
DEC BX
JNZ REPE
S tep 1 : Ca lct~ate the delay generated by iiUl<'r loop with maximum ootmt (FFFFH)
Delay generated by inner loop for count (FFFFH ~ 65535)
= (4 + (65535 - 1) X (2 + 16) + (2 + 4}) X 0.1 flS

= 118.1422 msec
Step 2 : Calculate the multiplier oount to get delay o( I minute
Rt.'quin.>d delay
multipHer count =
Delay provided by inner loop
1 x 60sec
= 118.1422 m sec

~ 509 = IPDH

3.16 Data Conversions


Before going to wTite and execute any assembly lnnguage program on a computer we
must understand which type of data proccs..~r u.nd('tslands and which type of data user
understands, and how they communicate with et1ch other. User com municah..~ with
computer using input de-vices and computer gives outcome of process or result on the
disp lay devices or hardcopy devices suc:h as printer or plotter. Most commonly used input
device is keyboard and most commonly used output device is a display device, video
monitor. The8e devices understand the information in ASCD format. Keyboard gives the
pn...'Sscd key 1'u1nber or character in its ASCII equlvaJent and for dL">play certain number or
character we have to send the ASCII equivalent of the number or character to the display

Copyrighted material
Microprocessors and Interfacing 3. 76 8086 Instruction Set and ALP

device. On the other hand, processor docs not und erstand the ASCll format. It uses binary
numbers. Therefore, it is necess.ny to convert input from keyboard to its binary equivalent
(ASCJJ to bin..1ry conversion) and convert processed data by processor into ASCII forma t
for the dis play (binary to ASCD conversion). Let us see how we can perform these
conversions. ln this St.--ction we s tudy the routines for these conversions. Once we
underst;md these routines we can use these routines to accept input using keyboard and to
display dat:'l on video monitor.

3.16.1 Routines to Convert Binary to ASCII


There are two ways to convert binary number into its ASCU equivalent :
By the AAM instruction if the number is less than 100.
By a series of deci_m a_l divis ions (divide by 10).

3.16.1.1 By AAM Instruction {For number less than 100)


The AAM ins tn1ction converts the value in AX into a two-digit unpacked BCD number
in AX. For example, if number in AX is 0059H (89 decimal) before execution of AAM
instruction, AX contains 0809H after execution of AAM instruction. Now we can get A5CD
equivalent by adding 3030H to AX.
Algorithm :

AXjoo Jssj
AH Al
. AAM--EB
AH Al

Nolo : 59H - 89 Oedmal

AXI08 1091 ADO AX. 3030H-- ~


AH Al

Now : 38H and 39H are the ASCU equivalents ~ 8 and 9 resp6Clivel'y

1. Save contents of a ll registers whk:h are used in the routine.


2. Get the data in AL register and rru~ke AH equal to 00.
3. Use AAM instruction to convert number in its decimal equivalent in the unpacked
format.
4. Add JOH in cad\ digit to g~t its ASCU equivalent.
5. Display digit one by one using function 2 of !NT 21 H.
6. Restore contents of registers.

Copyrighted material
Mlcroptocessor:s and Interfacing 3-n 8086 Instruction Set and ALP
Flow Chart

l Start
I
I Save registers 1
I
Get me hex nl.II'I'Oer

I
Convert it into Its
decimal (BCD) equlvolenl
I
Unpack the BCD digits

I
Add 30H in each BCD
dlgh to get its ASCII equlvcdent

I
Display eoch dlgil

I
Remre registers

I
( End )

Routine : Convert Binary to ASCIJ for number less than 100


Passing Parameter : Hex number in AL register.
Routine to convert binary number into its
: deci mal and then ASCII equivalent , and then display the number
BTA PROC NEAR

PUSH OX ; S3ve reqisters


PUSH BX
PUSH AX

MOV AH, OOH ; Clear AH


AAM ; Convert to BCD
ADO AX, 3030H : Convert to ASCII
MOV BX,AX ; Save result
MOV OL, BH : Load first digit (MSD)
MOV AH, 02 ; Load function number
INT 21H ; Display first digit (MSD)

Copyrighted material
Microprocessors and Interfacing 3. 78 80881nolructlon Sat and ALP

MOV OL , BL ; Load second diqit (LSD)


INT 21H ; Disp la y second digit (LSD)

POP AX Restore reqistecs


POP BX
POP OX
RET
ENDP
S..mple Progr,,m
; Sample p rog r c'l:m t.o convert b ina ry number i nt.o its
; decimal and then ASCII e quivalent, and then display the number

.MODEL SMALL ; Select SMALL mode


.STACK 100 ; Initiali zation of stack
.CODE

MOV AL,59H ; Load number in AL


CALL BTA Call couti ne
t-tOV AU I 4Ctl [Exi t
I NT 21H ; to DOS)

B'l'A l'ROC NEAR

PUSH ox Sava rec;p.St~rs

P\)SH BX
PUSH AX

MOV ARI OOH ; C!eac AR


AA>l ; Conve"rl to JICL'
ADD AX, J030H convert- to ASCII
I'IOV SX,AX ; Save .rcsul t.
MOV OL, BH ; Loctd !irst digit (MSDI
MDV l\H, ~2 ; Load function number
nrr 2l.R .
Oi~play ficst cHgit (MSO)
MDV DL, BL Load second Q:igit ( LSD)
! NT 21H Display .second di<)it ( LSD)

POP AX ; Restore cvgistecs


POP BX
I'OP ox
RET
EHDP
E!IO

C:\ tasm\tasm s_ b t a. asm


Turbo Assembler version 3.0 Copyright_ {c 1988 , 1991 Borland
lnternat. i o nal
As s emblin9 file: s bta.a.sm
Error messages ~ None

p n hr 1 n
Microp<ocessors and Interfacing 3-79 8086 Instruction Set and ALP

Warning messages: None


Passes : 1
Remaining memory: 410k

C:\tasm\tlink s_bta . obj


Turbo Link Version 5 . 0 Copyri9ht (c l992 Borland International
C:\ tasm\s bta
89

3.16.1.2 By Series of Decimal Division


lf number is greater than 99 we can not use AAM inslruct:ion to convert given number
in the BCD format. ln such case we use scheme of dividing by 10 to ronvert a'Y whole
number from binary to an ASCO coded ch.arader string that can be displayed on tht? video
monitor.

Assume : Hex number is 7BH

12 c - 01
10) 123 A J 7BH
- 120 - 78H 02 l\
3 03 03 ~)
1 1 :--,/
~
10) 12 A) c -\
- 10 - A
30H - 31H
2 2
0 0 ' 02. 30H- 32H
10) 1 A) 1 03+ 30H - 33H
- 0 - 0
1 1

Let us see the algorithm for converting number from binary to ASCII rode.

I. Save contents of all registers which are used in the routine.


2. Divide the number by 10 and ,;ave the remainder on the stack as a signilicant BCD
digit.
3. Save the quotient as a number.
4. Rcp<>at s tep I and 2 until quotient is 0.
5. Retrieve each remaind<T from stack and add 30 H "to convert to ASCII before
displaying or printing.
6. Restore contents of registers.

Copyrighted material
Microp<ocessors and Interfacing 8086 Instruction Set and ALP

Flowchart

( Start
I
Save~

I
Get the hex nl.W'I'Ibe:r

Divide the runber by 10


and save remainder on the stack
I
Save ltle quotient as a oomber

J.
No Check W
~uotient is 0

v..
Gellhe remainder

I
Convert 10 ASCU and dl$play

No Check W
11 remai'lclers a
""'' v..
Retrive reglaler contents

I
( Stop )

Routine : Convert Binary to ASCII

P.,..lng parameter: +digit hex number in AX register.


; Routine to convert 4- digi t hex into its decimal
; and then to ASCII equi valent , a nd display i t

BTA4 0 PRDC NEAR

PUSH OX ; Save r egisters


PUSH CX

Copyrighted material
Microprocessors and Interfacing 3-81 8086 Instruction Set and ALP

PUSH BX
PUSH AX
MOV ex, 0 ; Clear diglt counter
HOV BX, 10 ; Load 10 decimal in BX
BACK: MOV ox, 0 ; Clear ox
OJV BX .
Divide ox : AX by 10
PUSH ox ; Save rema.indar-
INC CX Counter remainder:
OR AX, AX ; Test i f quotient equal to zero
J NZ BACK ; I f not zero divide again
MOV AH , 02H ; Load !unction numbeJ:
OISP: POP ox ; Get remainder
ADD DL, 30H ; Conve-rt to ASCI I
INT 21H ; Display digit
LOOP DTSP
POP AX ; Restore .ccgisters
POP BX
POP ex
POP ox
RT
ENDP
END
Sample Program
; Sample proqr._m to convert 4diglt hex into its decimal
; and then to ASCII equivalen t, and displdy it

.HODEL SMALL ; Select SMALL mode 1


.STACK 100 .11\lti;,lise stack sagmont
.CODE
MOV AX, 21\BCH
CALL BTMD ; Call routine
MOV AH, 4CH ; I EXit
HIT 21H ; to DOS)
STMO l'ftOC NEAA
P\fSH DX .
Save reqi,.,~Ot"it

I'IJ~ cl<
PIISII Ill<
l'tlSH AX
MDV ex, u I Clriar digit countec
>tOY ax, 10 ; Load ~o deci.nl~l >.n BY.
,BACK~ MOV !>X, a ; C!'lea& OX
DIV ax ; ctivida DX : AX by 13
I'llSA Q)<. ; Save r.main dl>r
INC C'X I ..:'nun tee re.mainde~
0~ 1\1., Ml ; Te*'t" H qu"'tlen.t eqtl~l o "Zero
J1'!ll l!ACII ; :! 1\C!l zero dlvl-Mo a.;a.ln
OOV AN, o:m .
Lo~ct tunction numher
Ol$t': I?OP DX ; Get .rema.lru:i.er
ADD t>L, :()B ; Cortvc: r:L to 1\SCI.I

i y11 Itt
Micr oprocessors and Interfacing 3. 82 8086 lnstruclio n Set a nd ALP

nrr 2Ja Oi splay d.lqit"


t.QOP D!SE
1'01' AX
Pt.? SX
t'OP ex
1'\'!P nx
PE'T
END.P
S>ll>

C: \ttiSil)\tasm s_bta4d . asm


Turbo Assembler- Vet~ion 3.0 Copyright (c) 1.986 , 1991 Borla11d
International
Assembling file : -s bta4d . asm
E:rror messages: None
Warning mcss11ge.s : None
Passes : 1
R~ma in i ng memor-y : 4l0 k

C: \tasm\tlink s bta4d.ObJ
Turbo Lin k Ver-~n on 5 .0 Copyrigh t I C) 1992 Borland International
C: \tasm\s bt.a4d
10940

3.16.2 Routine to Convert ASCII to Binary


Wl'k.">n we accept d ecimal number from keyboard w~
get ASCII code o( each decimal
digit This information from the keyboard mtL~t be converted from ASCU to binary. When
a single key i:o; pressed conven;ion can be <~chjev<."CC by subtracting 30H. However, when
more th.1n orw key i$ t}'IX"d rotwl'rsion from ASCil to binary requires 30H to be
s ubtracted, but lher i$ additional s tep. After subtracting 30H, the number is dded tO the
result after the prior 1\."'S uH is first mulliplit.od by 10.
:. 256 Oecimol -> I00 H

-
Key~. t<.ylnput SUBlCII't ~
2 - 32H - 32H-30H
~OA
02
Multiply by 10
14H

,
s- 35H
- 35H-30H
-

xOAH
05H
19H
- """' digit

MUltiply by 10
FAH

s- 36H
- 361i-30H
- +
06H Md next digit
100H - Resull

2560edmal - 100H

Y'lt ,fr.'t_'''
Microprocessors and Interfacing 3-83 8086 Instruction Set and ALP

Let us see the algorithm for converting number from ASCII to binary code
Algorithm
1. Save contents of all registers which a.rc used in the routine.
2. Make binary n.">Su1t s=: 0.
3. SubtTact 30H from the character typed on the keyboard to convert it to BCD.
4. Mt~tiply the result by 10, and then add the new BCD d igit.
5. Repeat steps 2 and 3 until the character typed is not an ASCII coded number.
6. Restore register contents.

Flowchart

l Start )
I
Save register oonlent5

I
Result= 0

Gee the key input

No

().9

Yes
-
Convtwt it to 8CO
( Sub 30H ) d;g;c Save result

I t
Result = Result 10 + BCD digit Reskn reglsler contents

I ~ 5J.
l Slot> ) '

..\
-
. ~


Copyrighted material
MletOprocessors and Interfacing 3 84 8086 Instruction Set and ALP

Routi'ne : Convert BCD num~r from keyboard to its Hex equfvak:.ni.


; Routine to conve-rt ASCII coded decimal t rom kcyboa.cd 1nto Jt& HEX
equivalent
ATfl PROC N~AR

PUSH CX Save .registers


PUSR BX
PUSH AX
MOV ex, 10 ; Load 10 decimal in ex
MOV BX, 0 ; Clear result
BACK: MOV AH,OlH ; I Read key
INT 21H ; with echo)
CMP AL, I 0'
JB SKIP ; Jump i f below o
CMP AL, I 9'
JA SKU ; Jump .if above ' 9 '
SUB AL, "30H Convert to BCD
PUSH AX ; Save digit
MOV AX, SX
MUL CX : Multiply previous result by 10
MOV BX, A.)( ; Get tlle result- in BX
POP AX Ret-rieve digit
MOV 1\H, OOH
ADD BX, AX Add diqit v~lue to result
JMP BACK Repeat.
SKIP: MDV NOMBER,BX Save the result in NUMBER
POP AX Restor e reqisters
POP BX
POP ex
RET
ENDP
Sample Program
: Siimple program to convct:t ASCJ I coded de.clmal hom keyboard into
its HX oqulvtll~ er t-
.OODEL SMALL
.DATA
NUMB.ER OW '? ; Oof i n~ number
.CODE
START: HOV AX; @DATA ; ( [nitia lize
HOV OS , AX : dat-a segement)
CALL ATB conve r t ASCII coded decimal !~om
; keyboard into its: HEX equivalent
MOV AH, 4CH ; !Exit to
INT 218 ; DOS!
ATB PROC l'll';l\R
PUSU CX ,- Save reqi.n.er.s
PUSJl BX
PUSll AX
oov ex, ~o ; L04d 10 ae~i~l in ~
llV JlX1 0 ; Clear-- re.sul t
BAj:K: ~ AH,Ol > [R~ad l<tly
!NT 2!H ; Wlth t:!t:ho)
CMP ~L 1 ' 0 '
J9 SY,IP I J\Pilp h M 1OW ' 0'
CMP AL,' 9'
Microprocessors and Interfacing 3 85 8086 Instruction Set and ALP

JA 3lUP r .Jnmp l f ~bove , ~ ...


su~ H, 30~ ; ~on'-rort t.o 9CCJ
P:JSH I\X ; S.;t.V<! d.l-~.1 t:.
MOV AX, !l1( Molup.l.Y pre vi ouc. "t:eBtli r: t,"ly 10
MUt, :A
IIO'' RY, I\X ; Ge-t en~ t &~l-ull 1n. tlx
FOP .'<X ; B;etr.iE:.'\'t1 d..1gLt
ww AJ.!-, 0(1R
l<DL' BXI Juft;: di o l t v-al UP.: .r.n

~lP:
l.T!dP eAt~;
rdOV NltMBER, BX
"" ; ReptMt
..- 54\t~ tne .t .;;ul t.
1-a51.1 H

l.n NOMP.EP.

~"
POf
E'()P GX
I'OP ox
P.E.tt'
NDP
tll!l

C: \tasm\tasm .s_atb.ascn
Turbo Asse-mblet Ver$lOn "'3.0 copyriqht {C} 1 988 , 1991 socland
International
Assembling tile : s atb . asm
Erro.r messages: None
Wurn ing messages: None
Passes: 1
Remaining memory: 410k

C:\t.asm\tlink s_atb . obj


1'urbo Link Version 5 . 0 Copyri9ht (c) 1992 Borland I nte rnational
C: \tasm\s_a:tb
1234

3.16.3 Routine to Read Hexadecimal Data


We know that hexadecimal numbers range rom 0 to 9 and rom A to F. The keyboard
gives ASCII codes for these hexadecimal numbers. It gives 30H to 39H for numbers 0 to 9
and gives 41H to 46H for A to F letters or gives 61H to 66H for a to f letters H..,c:e, to
eonvert ASCU Input rom keyboard to eorrespondizlg hexadecimal number we have to first
check whelher it is a number or letter and then if letter whether It Is a small letter or
capita! letter and aordingJy CQnvert lt into hexadecimal number.
Microprocessors a.nd Interfacing 3-86 8086 Instruction Set a.nd ALP
BX
BH Bl
15 1211 57 43 0
1o o o I oI
Key
o iHI AL Input
1

0 I 0 I 0 I HI
Shifllefl4-bi1al o I o I HI o 1- o
Key
o i HIAL '"""t
2
0 0 I HI HI
Slllftleftbo1ol o I HI HI o 1-o
Key
oiHIAL ii\I)Ul
3

I HI HI HI
Shiflleft4-bi1al HI HI HI o 1- o
Key
loiHIAL ii\I)Ul

I HI HI HI HI
Not ; H represents any heJCadeeimat digit (Q-;F).

Algorithm

I. Sow~! rcgistc~
2. Make res~t =0
3. Get the ASCII code of character from keyboard and
S-ubtract 30H from it i( du1racter is 0 - 9
Subtract 37H fl'om it if character is A - F

Subtract 57H from it if character a - f


4. Shift the result by 4-bits and add digit to pack binary digits.
5. Rcpcoat s teps 2 and 3 four times to get 4..d igit hex number.
6. Restore reJ;,r:istcrs.

Copyrighted material
3-87
Flowchart

Get the ke)'OCidt


-


'

~

Mk:roproceuors and lnterfloclng 3 &088 lnotructlon Set ond ALP

Routine : Reading hexadecimal d ata


Return.-c; : Hex number in variable number
Routine to read 4-diqit H ~ x number from the keyboard

R HEX PROC NEAR

PUSH ex Save re9is ters


PUSH ax
PUSH AX
PUSH sr
MOV CL, 04 ; Load shift count
MOY sr, 04 ; Load iteration count
MOY ex, 0 ; Clear result
BACK: MOY Atll 01
INT 21 H ;
(Read key
with echo]
CALL CONV convert to bi nary
SHL ex, CL ; (pack four
ADD BL, AL ; binary digits
DEC SI ; as 16-bit
JNZ BAC ; number)
HOY NUMBER, ex ; Save result at NUMBER
POP SI ; Restore registers
POP AX
POP BX
POP ex
RET
ENOP

; Th~ procedure to convert contents of AL into hexadecimal


equivalent

CONY PROC NEAR


CMP AL, ' 9 '
JB SUBTRA30 ; If number is between 0 through 9
CMP AL, ' a'
JB SUBTRA37 ; If letter is uppercase
SUB AL, 57H ; Subtract 57H i f letter is lowercase
JMP LAST!
SU8TRA30: sua At., 30H ; Convert number
JMP LAST!
SUBTRA37 : SUB AL, 37H . Convert
'
uppercase letter
LAST!: RET
CONY ENOP
Sample Program
; Sampl e example t o r ead 4-digit He x number from the keyboard

. !lODEL SMl\LL Select small model


.STACK 100 ; I nitialise stack

Copyrighted material
MlaoptocHaors ond lnt.rfaclng 3 . 88 8086 Instruction s.t and AlP
.DATA ; Strt data acgment
NUMBER OM? : Do tine NUMBER
.COO& : StJrt code ae~nt
START,HOV AX, @DATA ; I tnit ialize
MOV OS, AX ; dlolta seqmont1
CALL o< 11: K ; F n 4-jl~ ~ hex nu1 L r
,.,. . Ali, 4~t ; lO
H~ 2l.H~-----------
PMI:' 11: .
IUSH CX ; '~'I req.!.sto
JtSH X
1'\JHA.l(
~H s
MOV Ct, 4
II V ol, 1
MI)'V ~,. ;
MOl .:..s, I
rt
A L VNV n::~ry

HL BY,
lll'D Bl., Al. :
$!
5 ;
"
MOll NI.IH B.~ :
I'OP SI :
f AA
'
p(p
f BX
...
F:uor
. T ov t f AI. l
quh

'OKV l Jl:('ll NEMA


< MP AL,, :.,
UBTRA .,.,. 1 9
l"M ~
Je S !lTP>. 31 ettoer- 1 .Jp.poc,..a e
S'J!I AL, >7!1

MP LAS!
I
I
rr))ct 5111
,. ... f HL H

SUS AL, 3 8 : v r.
H LA!TI
f118T~T, ~1. :.;;us AL, 37t : (" ez=-t r.l.fo' ca&"' t"V"r
... ;srt.

yrr 11 m
Mlcn>processors and Interfacing 3 - 90 8088 Instruction Set ond ALP
C: \ta sm\tasm s r dhex . asm
Turbo Assemble r Ver sion 3 . 0 Copyr i gh t (c ) 1988, 1 991 Borl a nd
Interna tio nal
Assembling f ile : s _ rdhe x . a s m
Err o r mes sages : None
Wa r ni ng messages : None
Passes : 1
Re ma ini n g memory : 410 k

C: \tasm\tlink s_rdhex .obj


Turbo Link version 5 . 0 copyright (C ) 1 992 Bo rland International
C: \tasm\s_ rdhex
12AB

3.16.4 Routine to Display Hexadecimal Data


To display hexadecimal data we have to first unpack each digit (nibble) in the given
number. Thon by adding 30H to digit having number between 0 to 9 and by adding 37H
to digit having lettt'r bctwetn A to F we can get the ASCU equivalent of given
hexadecimal number. This can be achieved by rotating number left (nibble by nibble) and
adding 30H or 37H into it. By rotating left we can display left moot digit (MSD) firsl

16 bH
,-------A~------~
<1s 12 11 s a o)
I

l)tqllay

130H .. 37HI :::::::::> [l;git 1 (Mso)

130H .. 37HI :::::::::> Oigil3

I
130H .. 37H :::::::::> Digit (LSD)

Nibble

Copyrighted material
Microprocessors and Interfacing 3-91 8086 lna1ruc:tlon s.t and ALP

Algorfltlm
1. S.we registers.
2. Get the number and unpack digit from it.
3. Add 30H if d igit is 0 - 9 or add 37H if digit is A - F to got the ASCII code of
digit.
4. Display digit.
5. Repeat steps 2, 3 and 4.
6. Restore regt.o;ters.
Flowchart

Get the number

InitialiZe ~it oounc

Unpack nibble

Add 37H

Display digit

No

Re:sw-e registers

Stop

Copyrighted material
Microprocessors and Interfacing 3-92 8088 Instruction Set end ALP

Routine
; Routine to displ ay 4-digit hex number in AX

D HEX PROC NEAR

PUSH OX Siwe registers


PUSH CX
PUSH AX
MOV CL, 0 4H Load rotate count
MOV CH, 0 4H Load digit count
BACK : ROL AX, CL Rotote digits
PUSH AX Save contents of AX
AND AL, OFH {Convert
CMP AL, 9 number
JBE ADD30 to
1\DD AL, 37H its
JMP DISP ASCII
ADD30 :
ADD AL, 30H ; equivalent]
DISP : MOV AH, 02H
f-10V DL,AL ; ( Display the
IN'f 2:11 number I
POP AX Restore contents of AX
DEC CH ; Decrement digit count
J NZ BACK ; 1 f . not z.ero repeat

PCP AX Restore registers


POP ex
POP ox
RET
ENDP
Sample Program
; Sample pro9ram displays 4-digit hex number in AX

MODEL SMALL
STACK 100
. CODE

MOV AX , l2ABH ; Load AX with test data

CALL D HEX Call procedure

MOV AH , 4CH [Exit


!NT 21H ; to DOS )

Copyrighted material
Mjcroprocessors and Interfacing 3. 93 8086 Instruction Set and ALP
0 _RE:< ~ROC NEAP

PlJBR DX
PUE'H CX
PVljR A.'(

NOV Ct., J~H LO.ld !\.lLa t; eiJUnL


MQV <:H, ~4R ; J,.O.'ld d ic;i t CuLm\.
BJiCKt BOL AA 1 CL ; P:oU\te d..tg.1- s
PUSH AX ; Save ~ont:ents o! U
A}JO A.L, OFH ; (Cunvert
CMP AL ,.9 J O\W~er
JBE ht>D30 ; to
ADD AL, 31H ns
JMP OJSP : ~~Ci-:
1\D!1'0 : ~.DO
AL, 30H i equ1.v.alentl
DIS~; Mt'V All , 02H
MOV DL,AL ; t 01..&play t.ll.E-
fNT Zl8 ; nunb~r]
PO? AX ; H~srotc col\tN!tJ>- of AX
o~c cu i o~crcrtlctlt oiqll: cow't
JN.Z B"C.K ; : l not .:<'ro tl'..p-.3<.~1

t-'\)P ril-!
POl ex
E'"'~'P DX
RET
&I!DP
ENP
C:\tasm\tasm s d hex.asm
Turbo Assembl er -version 3 . 0 Copyri9ht fc) 1988, 1991 Borland
International
Assembling file: s d hex . asm
Error messages: NOne
Warning messages: None
Passes: 1
Remaining memory : HOk

C:\tasm\tlink s d hex.obj
Tur bo Link VerS.iOn 5.0 Copyright. (c) 1992 Borland Inc.ernar.iona l
C: \tasm\s d he<
12A8 - -

3.16.5 Lookup Tables ,for Data Conversions


For certain data conve~on, wlu...>Jl number of possible data conv~ions are small ln
numbers then lookup tables are often u.o;.ed to convert data from one fonn to another. for
example, lor conversion of BCD to 7-<~Cgment code there are only 10 possible conversions.
A lookup table is nothing but a array form in th metnory as a list of data that is
refcn>necd by a procedure to perform convCl'Sions.
Mlcrop<ocessors and Interfacing 3 - 94 8086 Instruction Set and ALP

Converting from BCD to 7-segment code


Let us see how to perform BCD to 7.o5c.'gmcnt code conversion. for BCD to 7-sc..:-g:mcnt
rode COJwcrsiotl a lookup table cuntdins the 7-:K.'"gment codes for the numbers 0 to 9. Tilesc
codes are determined from Fig. 3.25. The 7-segment display s hown in Fig. 3.25 uses active
high (logic I) input to light a segment. The code is formed by placing the a segment in the
bit position 0 and the g scgmrot in the bit position 6. It position 7 is kept 0.


g
Code forrno1ion byte

c 0 g
I
Fig. 3.25 7-segment code formation
A look-up table can be stored in the program memory (code segment) or in the dabl
memory (data segment). Let us see the program which uses lookup table stored in the
data memory to convert BCD code into its 7--scgment equivalent code.

Program statement ; Wrltc an assembly Janguage program to convert BCD to 7-segment


code.
Program
.MODEL SMALL
. DATA
TABLE DB )FII ; 0
DB 0611 ; 1
DB 5BII ; 2
DB 4FII ; 3
DB 6611 ; 4
DB 6011 ; 5
DB 7011 ; 6
DB 07H ; 7
DB 7FH ; 8
OB 6FH ; 9
. CODE
START : MOV AX, @DATA ( Initialize
MDV OS, AX Data segment)
MDV AL, 0811 ; Loads AL with any BCO digit,
; for exampl e 8, to be converted to
; 1 - seqment code
MDV BX,OFFS&T TABLE ; Load BX wi t h the offset o f
; starting address of loo kup tabl e

Copyrighted material
Microprocessors and Interfacing 3-95 8086 Instruction Set and ALP

XLAT TABLE ; copy byte from address pointed by


; { BX + AL) back into AL
HOV AH, 4CH ; (Exit
I N1' 2 1H ; to OOS J
END START
END
Note : When Jookup table is s tored in the code segment we have to include a segment
override prefix in the XLAT instruction because XLAT instruction by default access. byte
from d:.ta segment. To access byte from code segment we have modify XLAT instruction
as XLAT CS: TABLE.

Look-up table to access ASCII data


Many program require that numeric codes to be converted to ASCU character strings.
For example, if we need to display month in the text format we should use lookup table to
reference the ASCII coded months of the year. Let us see program to a<XeSS ASCii s tring
corresponding to given month of the year using lookup table stored in the data segment.
Program statement : Write an assembly language program to a<XeSS ASCII string
corresponding to given month of the year.
Program:
.MODEL SMALL
. DATA
DPOINTER DW J AN, FEB, MAR, APR, MAY, J UN, JUL , AUG, SEP,
DW OCT, NOV, DI C
JAN DB 'JANUARY $'
fEB DB 'FEBRUARY S'
MAR DB 'MARCH $'
APR DB 'APRIL $'
MAY OB ' MAY $'
JUN DB 'JUNE $ '
JUL DB 'JULY $'
AUG DB 'AUGUST $'
SEP DB ' SEPTEMBER $ '
OCT DB 'OCTOBER S'
NOV DB 'NOVEMBER $'
DIC DB 'DECEMBER S'
.CODE
START: MOV AX, @ DATA i tini ti.,li:te
MOV DS, AX : Data segment)
MOV AL, 07H : Loads AL with any month in its
nu.rnerical va lue
MDV SI, OFFSET DPOINTER : Address table find month of year

'
HOV AH, OOH : [Multiply the AL by 2
ADD AX, AX : to point to correct
ADD SI , AX : month of the year ]
HOV ox, [SI ) ; Get month of year
MOV AH, 09H : (Display month

l Copyrighted material
Microproces sors and Interfacing 3-96 8086 Instruction Set and ALP

I NT 21 H ; o f ye a r s tring)
MOV AH, 4CH ; (Exit
I NT 2 1H ; t o DOS )
END ST>.RT
END

3.17 Procedures
Whenever we net.~ to use a group o ( instructions several times throughout a program
there are two ways we can avoid having to write the group of instructions each time we
want to usc them. One way is to write the group of instructions as a separate pn:x:edure.
We can then just CALL the pr<>c.."t..">dure whenever we need to execu te that group of
instructions. For c.:11Hng the procedure w e have to store the reh1m address onto the s tack.
This process takes some timc. Jl the gro up ol instructions is big enough then this overhead
time L.;; nt..:.gligiblc with respect to execution time. But if the group of instructions is too
short, the overhead time and execution time are comparable. In s uch cases, it is not
dc..>sirable to write procedures. For these cases, we can use macros. Macro is also a group of
ins truc;tions. Ench time we "'CAL'L" a macro in our program, t~ assembler will insert the
defined group o ( instruction-; in place of the .. CALL"'. An important point here is that the
assembler generates machine codes fo r the group of imtnctions each time macro is called.
So there is not overhead time involved in calling and returning frum a procedure. The
d isadvantage of rnacro is tha t it generates inline rode each time when the macro is called
which takes more memory. ln this section we discuss the procedures.
From the above dL~ussions, we know Ulat the procedure is a group of instructions
s tored as n scpnrnte prog:ram in the memory and it ls called from the main program
wheJ\L""Ver required. 11\c type of procedure depends on where the procedure is s tored in
the memory. If it is in the same code segment where the main program is stored then it is.
rnlk'CI neilr procedure otherwise it is referred to n.o; far procedure. For near procedure
CALL instruction pushes only the fP register contents on the stack, since CS register
contents remains unchanged fo r main program and p rocedure. But for fa r procedures
CA LL instruction pushes both II' and CS on the stack. Let us see the detail description and
example'S of CALL instmction to enter the p rocedure and RET instruction to return from
the p r<K:edu re.

CALL Instruction :
The CALL instruction is used to transfer execution to a subprogram or procedure.
There are two basic typt."S of CALL<~, near and far. A near CALL is a call to a procedure
which is in the same code segment as the CALL in..ttru<:tlon. When the 8086 executes a
near CALL instruction it decrements the s tack pointer by two and copies the o ffset of the
1\ext ino;tructiot'l a fter the CALL on the s tack. It loads r.P with the offset of the first
instruction of the procedure in s ;\me ~en t.
A far CALL is a call to a procedure which is in a different segment from that which
contains the CALL instruction. When the 8086 executes a far CALL it decrements the s tack

Copyrighted material
Microprocessors and Interfacing 3 . 97 80861ns truction Set and ALP

pointer by two and oopies the contents of the CS register to the stack. It then decrements
the stack pointer by two again and copies the offset of the instruction after the CALL to
the stack. Finally, it loads CS with the segment base of the SL>gment which contains the
procedure and JP with the offset of the first instruction of the procedure in that segment

Examples :
Direct within segment (near)
CALL PRO ; PRO is the name of the procedure.
; ThC' assembiC'r determines displacement of pro
; from the instruction after the C ALL and codes
; this dis placement in as part of the instruction.
Indirect within~segment (near)
CALL CX ; CX contains, the offset of the first instruction
; of the procedure. Replaces contents of IP with
; contenl") of register ex.
Indirect to another ~gmen t (far)
CALL DWORD PTR fBX) ; New values for CS and TP are fetched from four
; m~mory locations in DS. nu~ new value for CS
; is fetched from fBXJ and [BX + 11. the new IP
; is fetched from [BX + 2[ and (BX + 3].
RET Ins truction :

The RET instruction will retun\ cxocuti01\ from a procedure to the 1\CXt instruction
after the CALL instruction in the calling program. H the procedurt> is a near procedure (in
the same code seJ,oment as the CALL instruction), then the return will be done by replacing
th(! instmction pointer with a word from the top of the stack.
If the procedure L-; a fa r pr<X'edure (in a different rode segment from the CALL
instruction which calls it), then the instruction pointer will be r~ l accd by the word a t the
top of the s tack The s tack pointer will tht.'l\ be incremc1\ted by two. The code segment
register is then replaced with a word from the new top of the stack. After the code
8e!,'l'nCnt word is popped off the stack. the s tack pointer is again incremented by hYO.
These words/word arc the offset of the next instruction after the CALL So 8086 will fetch
the next instruction after the CALL.
A RET instruction can be follow~.---<! by a number. for example, RET 4. ln this case the
stack pointer will be incremented by an additional four addres..CO(.>s after the IP or the lP
and C:S are popped off the stack. This foml is used to increment the stack pointer up over
parameters passed to the p rocedure on the stack
Flags : The RET instruction affects no flags.

Copyrighted material
.,
Mic.roprocessors and Interfacing 3 . 98 8086 Instruction Set and ALP

3.17.1 Reentrant Procedure


In some situations it may happen that procedure) is called from main program,
procedure2 is called from procedure! and procedure} is again called from proccdut1.'2. In
this situation program execution flow reenters in the procedurel. This type of procedures
are called reentr-ant procedures. The flow of program execution for reentrant p rocedure is
shoonrn in fig. 3.26.

PROCEDURE 2

CALL
PROCEDURE 1

NEXT MAINUNE
INSTA.UCllON
AFTERCAI.L

RElVRNrO
UAIN PROGRAM , '

Fig. 3.26 Flow of program e xecution for reentrant procedure

3.17 .2 Recursive Procedure


A recursive procedure is a procedure which calls itself. Recursive procedures are used
to work with compll'x data :l-h'uctures called trees. II the procedures is called with N
(recursion depth) ;:; 3. Tilen the n is decremented b) one alter each procedure CALL and
the procedure is called until n = 0. Fig. 3.27 shows the flow diagram and pseudo-rode for
recursive prOCt.."Clure.

MAINliNE

PRO~EO.,..; RECURSIVE Fl:l

lfN>I(I

OCR!MH1' N
CALL Rt.OUI:tSIVE

ElSE
R<TURN

Fig. 3.27 Flow diagram and pseudo-code for recursive procedure

Copyrighted material
Mlcroprocessol$ and Interfacing 3 . 99 8086 Instruction Set and ALP
.,
3.18 Macro
Macro is a group of instructions. The mac-ro assembler generates the code in the
program each time where the macro is 'caUed'. Macros can be defined by MACRO and
ENDM assembler directives. Creating macro is very similar to creating a new opcode that
can be used in the program, as shown below.

Example : Mac-ro definition for initializntion of segment regtsters.


I NIT MACRO ; Defin~ mac ro
'MeV AX, @data }
MOV OS ; Body of macro definition
MOV ES, AX ;
ENDM ; End macro
It is important to note that macro sequences execute faster than procedures because
there are no CALL and RET instructions to execute. The assembler places the macro
instruc-tions in the program each time when it is invoked. This procedure is known as
Macro exp ansion.
Comparison of Procedure and Macro

Sr. No. Procedure Macro


1. Accessed by CALL and RET instruction Accessed during assembly w ith name
during program execution. given to m&cro when defined.
. 2. Machine code for ins.tn,JCtions Is put onty M&chfne code is generateq for insttvctions
onoe In lhe memorv. eaCh time wnen macro is called.
3. With proce<tures k!ss memory Is requlre<t. W'dtl m&eros more memory Is requtre<t.
4. Paramelers can be passed in registers, Parameters passed as part of statement
memory locations, or stack. which calls macro.

Table 3.8
Passing Parameters in Macro
l.n Macro, parameters are passed as a part of statemc:nt which calls Macro.
Example:
PROMPT MACRO MgssAGE ;Defi ne macro with MESSAGE as a parameter
MOV AH, 09H
LEA MESSAGE
INT 2 1H
ENDM ;End macro
DATA
ME$1 DB 10, 13, 'Student Name : $'
MES2 DB 10, 13, 'Student Address : $ " .'
. CODE
START : NOV AX, @data Initialize
MOV OS, AX
;

' data segment .

Copyrighted material .
Microprocessors and Interfacing 3-100 80861nstruction Set and ALP

PROMPT MESl ; Display MESl


PROMPT HES2 ; Disp la.y MES2
NOV AH , 4CH ; Return to DOS
!NT 21H
END START
The above example shows th;,t parameters Ccln be passed in macro with the help of
dummy argument. Argument tell.; the assembler to match its name with any occurrence of
the S<lm e name in the macro body. For example the dummy a rgument MESSAGE also
occurs in the LEA in~truction. The macro instructiOI'l "'PROMPT MES1" passes the MESl as
a parameter and macro acccpl"' that as an argument.
Local Variables in a Macro

Body of the Macro can use local variables. A local variable defined in the Macro is
available in the Macro, howcv~r ll is not available outside the Macro. To define a local
varit~blc, LOCAL dir~tivc is u:o:ed. Example shows how local variable is used as a jump
address. If this jump address is not defined as a local, the assembler give an error mess.1ge
on the second and subsequent attempts to use the Macro.

Example
DISPLAY MACRO A Displ ays ASCII character i n uppercase
LOCAL J LABEL ; Defines J LABEL as local
PUSH OX
C.MP J.L , ' Z '
JB J l l\JleL Check if uppercase
SUB AL , 20H Convert to uppercase
J LABEL: MOV DL, hL
MOV 1\H, 0 2H
tNT 21 H
POP OX
ENDM
The above Macro aoccpt~ ASCII code for character. (AZ or az). H it is (or lowercase
character, Macro conv(.rts it to uppercase character and displays the uppercase character
on video screen.
H is important to note tho.l l local variable or variables must be defined using LOCAL
d irec-tive immediately after MACRO directive.

3.19 Instruction Formats


The instructions of 8086 vary from I to 6 bytes in length. Fig. 3.28 shows the
instruction formats for I h) 6 byh:.os instruction for each instruction format first field is the
operation code field, commonly known as opcodc field. Opcodc field indicates the type of
operation Ia be performed by the proce<;SOr. The olher field in lhe instruction format is
o~and fie.ld. The operand fieJd may consists of source/destination operand, source
operand addn..>ss, destination operand address or next instruction address. The operand
and the relative nddn."SS of the operand (dis placement) may be either S.bit or 16-bit long
depend on the instruction and its addressing mode.

Copyrighted material
Microprocessors and Interfacing 3 101 8086 Instruction Set and ALP

One b y1e tn s u uc lio n ltnp llce.l upt'fand~

Qooode

Ont' byte lns tru c liOII rrgis t ~ r node

IOooodl Rog I

Opoode

..
Re It is 1u 1o I from m c m o ry w It h :. u dIS p ill c e 111 e n t

Ke ~ is t u to I fru m m e m o ry ,., II h d Is p I a c e m t n t ( IS bIt )

Oisp

Re gis t u to /from ntemo r y with d h pl a ccmcot ( 1 6blt)

lm lnc d l a t c opera nd to res is t e r (tlbil'


Operand

lo1 mcdit tc op t' rand t o regis t e r ( 16-bit)

lm ncd i a ..- operand t n men or)' a ith 16bit disp l:attmtnt

Qooode II ModjOpcode IRIM I !Oow-oroe< Olsij IHigh.orde< Oispl E<'d"OP8i@ (igl><le< "*'"'4
Fig. 3.28 Sample 8086 Instruction fonnats
The opcode and the addressing mode js specified us ing first h.,ro bytes of an
inslnoction. The opc()(le/addressing mode by te(s).
The opc()(le/addressing mode byte(s) may be follow<'<~ by :
No additional byte
Two byte EA (For direct addressing only).
One or two byte displacement
~ or two byt~ immOOiatl! operand
One or two byte displacement followed by a one or two byte imml...:iiate operand

Copyrighted material
Microprocessors and Interfaci ng 3 102 8086 Instruction Set and ALP

Two b)tc d isp l ac~mcn t and a n ..o byt~ segment address (for direct intersegment
Jddrc:;sing only).
Most o( t-he opcodcs in 8086 has a spcc:ial 1--bit indicotors. They arc :
W-bit : Some instructions of 8086 can operate on byte or a word. The W~bit in the
oprode of s uch instruction specify whether instruction is a byte instruction
(W = 0) or a word instruction (W = 1).

D-blt : TI1e O-bit in the opcode of the instruction indicates that the register specified
within the instruction is a source n..~ste r (D 0) or destination regis ter (D 1).
S-bit: : An 8-bit 2's complement number can be extended to a 16~bit 2's complement
number by mn.king all of the bits in the Wgher..order byte equal the most
significant bit in the low order byte. This is known as s ign extension.. The S--bit
along with the W-bit indicate :

5 w Operation
0 0 S.bfl operation
0 1 16-bit operation with 16-bit immed~te operand
1 0 -
1 1 16-bit operation with a sign extended 8-bit immediate operand
Table 3.9
V-bit : Vbit d-.'Cides the number of shifts for rotate and shift instructions. lf V = 0. then
count = 1; if V I, the count is in Cl register. For eXt"tmple, if V = 1 and CL = 2
th(''' shift or rota te in~truction shifts or rotates 2bits.
Z-blt : It i~ \tSt.>d for s tring: primitives :o:uch as REP for comparison with ZF Flag. If it is
I, the instruction with REP prefix is executed until th~ zero nag matcht.'S the
Zbil.
(Refer Appc1\dix A for instruction formats)
As seen fro~ the Fig. 3.28 if an instruction hn.<> two opcode/addn:..-ssing mode bytes,
then the second byte is of one of the following two forms :

I MOD Opoode

or

I MOD Reg
I

Copyrighted material
Microprocnaora ond Interfaci ng 3 103 8086 lnatructlon Set and ALP

where Mod, R4'g ond R/ M Aclds -pecify operand as dl-scrib<'<i ll\ the following tables.

Modo Otsplac:et~Mnl

0 0 Ollp 0 LOw Otdtf and H'itt't order di:sj:~.. . . . . . . .


0 1 ~ LOw order chplacemenl is preMnt ~ sign Uindld to 1~
t 0 Bocll ~r 11\d Hogt>.onler- ore-~
1 1 rim 1\etd II treated as a 'Reg' held.
Table 3.10 'Mod' field assignment

Word Operand (W 1} Byte Operand (W 0) Segmnt


000 AX 000 Al 00 ES
001 ex 001 ct. 0 1 cs
0 10 ox 0 10 01. 10 ss
0 1 1 BX 0 11 Bl 1 1 OS
10 0 SP 10 0 AH
10 1 BP 10 1 CH
110 Sl 110 OH

11 1 01 1 I 1 BH

Table 3.11 ' Reg' field assignment

RIM Operand Addreu


000 EA {BXl {SI] + Dlsl)lac"""'m (oc>Uont)
0 0 1 EA [BX] + {01] Oltpl"""m""l (OpCion.l)
0 10 EA = [BPJ + (SI) + Di$pla.,_nt (oe>tlonOI)
0 1 1 EA = jBPJ + {DIJ + ~mont (OI)Iionolj
10 0 EA lSI) Oitpl~ (opllonef)
10 I EA.=(Of)
~~-~
1 10 EA =[BPI
~ ~-~
1 1 1 EA = [BX) + ~ Qpdonel)

Tobie 3.12 'RIM' field anlgnmont



Copynghted matenal
Microprocessors and Interfacing 3 - 104 8086 Instruction Set and ALP

n. . Examplo 4 : Writ. tlr~ instruction format for PUSH BX iustruction.

Solution : This instruction will put BX register


contents o n s t<1ck. Referring the table in
I Bytet I
Appt.:.ndh: A \ Ve find that the S..bit opcodc or
this instruction is 01010. We put 0 11 in the
REG field to reprt'sent the BX register. The
llflill
Opcode for REG = ex
PUSH
cock-'S for each rt:gisters an: shown in table
3.11. The r<'Sultant code for PUSH BX will be Fig 3.29 Instruction format
for PUSH BX
01010011.
II. . Example 5 : Writt tl!t instruction format for MOV AX, CX itrstruction.

Solution : This instructjon will copy a word from the CX register to the AX register.
Refer-ring the table in Ap~ndix A we find the 6-bit opcodc for this in.~truction is 100010.
Because we are moving a word, W=1. The 0 bit for this instruction may be somewhat
confusi'S . Sinc~ two regi.o;tcrs M C involved, we can think of the move as eitMr to AX o r
from CX. It actually does not matter which we assume as long as we are consistent in
coding the rt.-'S t of the instruction. If we think of the instruction as moving a word to AX.
then moke D=l and put 000 in the REG Aeld to repr...,.,t the AX register. The MOD field
will be 11 to represent register addressing mode. We make the R/ M field 001 to represent
the othe r register CX. The rcsultont code for the instruction MQV AX, CX w ill be 10001011
11000001. The Fig 3.30 shows the meaning of all these bits.

I Byto1 I Byte2 I
I'iololol +1111t!ol+lol+l
~,
~
RIM CX

To REG

MOVword - - '
L REG =AX

Fig. 3.30 Instruction format for MOV AX, CX

I( we chang'-' D field. to a 0 and swap the codes in the REG and R/ M field, we will get
10001001 11001000, which is another equally valid code for the instruction.

Copyrighted material
Microprocessors and lnbtrfaclng 3-105 80861nstructlon Set and ALP

Fig. 3.31 Albtmatlve instruction format for MOV AX, CS

,,... Example 6 : Write l11e ;ustmt tiorr ftmnnt for MOV 56H(SI), BH

Solution : This instruction will copy a byte from the BH register to a memory location.
The BIU will compute the effective address of the memory location by adding the
indicated displacement of 56H to the contents of Sl register. The BIU then produ tM
physical address by adding the effective address with the base represented by H)bit
contents of OS register. The 6-bit opoode for this instruction is again 100010. We put Ill in
the REG field to represent the BH register. D = 0 because we are moving data from BH
register. W = 0 !><.'Cause we are moving a byte. The R/M field will be 100 because 51
contains part or the effective address.. The MOD field wiiJ be 01 because the displacement
cont-ained in the instruction_, 56H, wiiJ fit in J byte. The S.bit displacement forms the third
byte of the instruction. The resultant sequence of code bytes will be 10001000 01111100
01010110.

I Byte 1 I Byte 2 I Byte 3 I

+
I+ 1o1 lol olol oll111 +lol + Iol 11 +I +
OPQOde latMOV~ =ISIJ
FromREG_ I L ~/M
~EG BH
Olsptaccmetll e: 56 H

MOV 6yte L.__ MOO'IOI"J. ooc byte displacement

Fig. 3.32 Instruction format for MOV 56H (SIJ, BH

II... E.xample 7 : Write tl1e ;nstruC'tfou fomrnt for MOV DL; {8X}.

Solution : This instruction will copy a byte to DL from the memory loctttion whose
effective address is contained in BX. The effective address will be added to the data
segmon t base in OS to produce tho physical address. Referring the table in Appendix A,

Copyrighted material
Microprocessors and Interfacing 3 -106 8086 Instruction Set and ALP

we find opcode for this instruction is 100010. We make 0 = 1 because data is being moved
to register OL. We make W = 0 bt..>cause the insln.lction is moving a bytl" into Dl. We put
010 in REG field t(l represent Dl. register. We make MOD field 00 to represent memory
with no displacement. For this instruction R/ M field will be 111. The resultant sequence of
rode bytes will be 100010 1000010111 .
I Byte 1 I Byte2 I

I+lol o! +l lolololol+I 111


OpcodetorM-;;~
t ~ LLRIM= tBxJ
ToREG:=._j REG=Dt.
MOVByte
Memory, no displacemenl

Fig. 3.33 Instruction fonnat for MOV DL, (BX)

,,... Example 8 : Writ< the iustructio11 fommt for MOV BX, 11234 HI

Solution : This instn1ction copies thl" contents of two memory locations into the BX
regis ter. The direct address or displacement of the first memory location from the sta rt of
the data segment is 1234H. The BIU will produce the physical memory address by adding
this displacement to the data segment base represented by the 16-bit number in the OS
register.
The 6bit opcodc for this instruction is again 100010. We make D = 1 because we are
moving data to the BX register, and we make W = 1 because the data being moved is a
word. We put 011 in the REC field to reprcst.-nt the BX register. Referring tables 3.11 and
3.12 we get MOD = 00 and R/ M field = 110. Then the fi rst two bytes of instrucrion code
will be 10001011 0001 1110. Tiocse two bytes will be followed by the low byte of the d imct
address, 34H (00 1I 0100 binary), and the high byte of the d irect address, 12H (0001 0010
binary). n~ i nstruc~ion will be coded into four s ua:essive memory addresses as 8BH, I EH.
:WH and 12H.

I Byte I I Byte2 I Byte3 I By"' I

I I+lo!ol+1 1 'iolololll I +1+11+I +loJoloJol olo!ol +I


I
L
J
REGBX

D1rec1
Orract addross
lowetbyte
Direct address
H igher byte

addressing

Fig. 3.34 Instruction format for MOV BX, (1234H)

Copyrighted material
Microprocessors and Interfacing 3-107 80361nstructlon Set and ALP

II... Example 9 : Write tire inslmction formnt for MOV CS : !BX}, CL.

Solution : This instruction copies a byte from the Cl register to a memory location. The
effective address for the memory location is contained in the BX register. Usually an
effective address in BX will be added to the data segment base in OS to produce the
physical memory address. ln this instruction, the CS in fron t of [BXJ indicates that we
want the BIU to add the effective address to the code segment base in CS to produce the
physical e1ddress. The CS : is called segment override prefix.
Whel\ an instruction containing a 5eb'Tnent override p refix is coded, an 8-bit code fo r
the segment override prefix is put in memory before the code for the instruction. The rode
byte fo r the segment override prefix has the format 001 XX 110. We can be replace XX
with : the segment code. The segment codes ore : ES = 00, CS =01. SS =10 and OS = II.
The s~men t override prefix byte for CS, then, i1:> 00101 11 0.
The opc<x:le for this instruction is 100010. 0 = 0 because we are moving data from the
CL register. W = 0 because we arc moving a byte. We put 001 in REG field to !\.>present
Cl reboister. We make MOD field 00 to represent memory with no displacement. For this
instruction R/ M field will be 111. The resultant sequence of code bytes will be 00101110
10001000 00001111.

I Byte1 I Byre2 I Byte3 I


lol 11111 +I Ioio Iol +lol oio lol ololtl 11
0
+
6
Register
OpcodefotMOV , , ~LLRIM=(BXJ
From REG REG = Cl
MOVByte
Memory, no disptacoment

Fig. 3.35 Instruction format !Of MOV CS : [BX], CL

Review Questions
1. xplsi11 vsrious datil addrt$sing m"'les of 8086 witl1lite help of t'Xt:Jnrples.
2. E.xpl.ni11 tht diffi.wn ~lfUtfll direct and iudir.t addrt':,-sing modt.
J. E.xplni.11 boS<plusil1dtx nddmsi11g mode.
4. xplsi11 lunu bast>-plus-iudt'x addressing mode am bt tr51'4 to loet:Jtt' array data.
5. E.xpl!lit1 rtgis.t.er rdnting nddre$$h!g.
6. Explain bast n'.tatiw-plus-indt'x addressing.
7. E.xpiJtin IJOW ba~ l't'lalit~plu~oind.u Nidmsbrg can bt usN to ltllt dAta from two dimensionAl
army.
8. fxplni11 tht> string addressing moM.
9. E.xplniu IKI,;OIJ$ 1/0 nddrt'SSing modes supportrtl by 8086.

Copyrighted material
Microprocessors and Interfaci ng 3 108 8086 Instruction Sot and ALP

W. r..tf.'t'' .lm'lf prosmm mcmory dddmsi11g UJifh llrtlr.-.lp of ~xnmplt'.


11. 1'\' lllf! ~ ::1w1, Jtt'l1r 1111rl for /limps?
1!. 1..\JI/.u. ffl, ~~~({m"'tr:t' hltwn.n inttrs..ogmml attd illfrllSt'S"'~"' jump iuslructions.
7l. i tt/.. :. ~~J,,t.:'r! wngrrmr llh.>mory IUIJressin,~.
I 1 i tl': M.41rt'\t prosram me-mory addrt"SSing.
75. I\'I >( ... t,;,.\ ?

16 lW~~ .: ;It~ (miCttOII of S:llltk pointer !


J;'. W,'J,. '' ...m ''"'~m l'.V top of stMk ?
II;. ['JII""' t/r. l::t:full/1!$$ of lih' folltXuiug instmctions in 8086
t. I ~ K;.:, t. II ~ 1' c. XLAT d. LES
tQ. IVir1 i. .!il_r;.,.,.,(t' J"1U\"t'" t.ltt' folltNIJing instntclions
' Aft~l' C'< .fJ;"AJI ami MOV CX, 1437AHI
to. ,\lit W, .f,l 7A H fmd MOV BL. DS:BYT' PTR [437/tH]
?tl. [-,.,. .. 1''1', follot/lt''~ iustrurtions for rniCt'OfJrt'$...~r 8086 ?
Jr \f1 .,, C X, A I. 11. AIOV DS, 437AH
, ,\It) . < '. WX! tl. MOV 43/i(SII. DH
,. MOV C!<:I~X/. DL
:!I WitJ: Jl,, lldJ' (?{ an (Xmnplt dtseri~ lire tk'li<m p<tformtd by mkroprtJCtSsor 8086 for
" ' "' t11,. _tl'"'"t'ltiS mstl'uctions :
n. AA.\1 I. CM PSB c. /MltL d. ROL
1!. L\J/wr l"t' W4.' of tht following pn.fix"--s
'' Rll 1 !. RFP
2'3. fJt..,aE1\ tft r;~I)()IIIo.' of 81)86 to tilt' folltJUr;,rg jhte primitiw Slri11g operRikms.
MOVS C\>11'$. SCAS. LOOS and STOS
2~ . DiKII$."' ,,/lllfllf~ of JUmp iuslructio11s uSt'd in S(JS6 mkroproussor.
! i tVri! oJyW<-l:i.m..{ lvrfomrt'd by thf 8086 microprtX't$$0r CALL instruction.
16 rx,~o:J I: m clt-tml lire diffiri'11Ct bdTI'I'i"'ll tlt'QT CALL nnd fiAT CAU..
27. For tJ/,_t.P/m.m,'( hr$lruclioll compu~ tire address of memory opemnd for 8086:
" MOV AX. lllXI b. MOV AI. IBP + Sl/
As:mtm:
CS = 0/llOH DS = 021XJH 55 = IHIXJH 1:5 = IXJ3QH
HP tJfl1011 OX 0020N Sl OOJON SP 0030H
Clt'11rl 11 ...Jtmt' t'OriiJ'ltlotiour..
U. ~~~:~ 1/:, tliffi'Tt'ltrt l~t-'tTI.~''" a jump nrrd a coli instruction l Wlrat dOtS tlw processor do in
t':m:utmg it ? You uwy use 8Q8S, 8086 iustntcU01fS to explain.
29. f.xpilf-11 wiMt tlfll.'flrtN>u l'$ ptrformrd by thr follt:nuing inslfllctions :
a. '<Ill HYI'r PTR /0400 HI, Cl.
b. MIW /BXI I0/1 + 4, AX
c.'<t r .t. XTHL ' PCHL

Copyrighted material
Microprocessors and Interfacing 3-109 8086 Instruction Set and ALP

30. xplnin tlr ~~~ of PUSH and POP inSlnrctions in 8086.


JJ. E.xplni11 lht function of thr following inSiruetions of 8086;
XLAT, CWO tmd CMPSB.
32. Wllnt is th~ function of assembler directives ?
33. fxpl.nin t~ follmui11g assembler dirt>dit't's
a. DB b. EXTRN c. .MODEL SMALL d. PROC ' PUBLIC
34. F;.xplaitJ rmrh?bles. siffix (lrJd operatOr$ usM i11 as..~bly lnugwgl' pro[~rnmmilt,\i
35. Wll11 do you mnm by rmrclri~re ln11gmrgf! progrnrtl ?
J6. Wlmt do you llft'llll by ns'S<'mWy lnnguRgt' program J
37. Civt tl1r diflmnc4' bt'hrom machine langmrgc and ass..mbly lnngungr.
38. Ex,taiu lht' aSSfmbJ.v lnng~tngr prQgramming lips.
39. What do yo11 m1vm by optimum solulhm ?
40. Explmn tht' steps tlml nsstmbler follqws to ronwrt .ASM filt' to .08} jilt.
41. .\'tJiam lire> fuuctiou of linkt>r.
42. Wlurt Is 4ldmggtr ? E.xplain its adrNmtng_l'1.
43. xplni11 Vt1rW11s drbug.'?tT rommmrds.
44. Wlurt is timl delny ? Wrilt tm ffS'S(>m[Jiy lmrgttQgf I"<IR'''"' lo gt'uernk 11 dduv fJl .'i~.~ Ill'>.
45. :rplnbr Ore hco ledmiqucs to crmlll.'rt binttry to ASCII.
46. El1J/tJi1r tire protc$$ of tcllvt'rlr'lrg ASCJI to bimrry.
47. E..'q)fni11 tl1r ptl'SS of displ.ny;rrg lltxnde>r:imnl dntn.
48. :rplni11 how look up 111blto.s ctm bt uSt"(f to cont\"rt BCD to 7-~~"'111
,_ nltlt'.
49. Wlutt is mliCI'() ? Wlrfn it should be. used ? Wlmt nrt' its Jtdtltmtng,._~ ?
50. E.xplnin llr~ stmdurt' of macro with 1/r, lr~lp of ~xamplt>.
51. Cit lltt romp1risou hfht't't'" proct'drm aud marro.
52. Ho.w art' 11aromutrrs pas54!d to 11 mnao ?

O QQ

Copyrighted material
(3 . 110)

(; y ned Male
Assembly Language Programs

In this chapter, we S4...lC the programs lnvolving logical, branch and caJI inslTuctions,
sorting, evaluation of arithmetic expressions and string manipulation. Most of the
programs usc DOS function calls. The details of DOS function caUs are given in chapter 9.

Program 1 : Read keyboard input and display it on monitor


TITLE Read Keyboa r d Input a nd Displ a y it on Mon itor
. model smal l
. code
start : mov a x, @data ; (loads t.h e add r ess o f data
mov ds , ax ; segment i n OS )
back : mov ah, 0 1
i nt 2lh
cmp al, ' 0 '
j z Las~
jmp back
Last : mov ah, 4ch ; ( Ex 1t
int 2lh ; t o DOS
end s t art
end

Program 2 : Addition of two 32-bit numbers


; This program adds t wo n umbers
TITLE Addi t ion of t wo 32-bit numbers
.model small
.d a t a
nol dd 8 111FFFFh
no2 dd 922244 44h
result dd ?
carry db 0
.code
sta rt : mo v ax, @da t a ( loads the a ddress of data
mov d s , ax segment in OS J
mov ax,word pt r nol Get the LS word of f irst
numbe r in AX a dd ax,word
; p tr no2 Add t h e LS wo rd ot
; second number to it
(4 - 1)

Copyrighted material

Microprocessors and lnterfacJng 42 Assembly Language Programs

mov word ptr result,Qx; Save LS word of result


mov bx, offset (noll
mov a x,~ord ptr ibx21 ; Get the MS word of first
num.be r in AX
mov bx, offset (no2l
adc ax ,word pt r [bx+21 ; Add the 115 word of second
; number to i t with carry
mov bx, offset result
mov (bx+2l , ax ; Save ~lS word of result
adc carry, O ; save any carry after
; MS word addition
mov ah , 4ch ; I Exit.
i nt 2 lh ; to DOS I
end start
end

Program 3 : Addition of 3 x 3 matrix


; Thi s program adds 3 x 3 matrix , The matrices are stored in
; t'orm of lists (row wise) .
TITLE Addition of 3 x 3 Matrix
. model small
.data
ml db 10h, 20h,30h,qOh, SOh, 60h, 70h , 80h,90h
m2 db 10h,20h,30h,40h, 50h,60h , 70h , 80h,90h
result dw 9 dup(O)
. code
start : mov ax,@data (loads the address of data
;
mov ds, a x se9mcnt in OS)
;
mov cx ,9 ; Initialise the COUJ'Iter
mov di, offset ml ; Initialise the pointer to
; matrixl
mov bx, offset m2 ; Initia lise the pointer to
; matri x2
tr.OV si, offset result ; Initialise the poit~ter to
; resultant matri x
back: rr:ov ah,OO ; Make MSB of result zero
mov al. ldi ) ; Get the number from rr.atrixl
add al. lbx) ; Get the number from m.atrix2
; and add it in corresponding
.
number of matrix!
a de ah,OO .
Save the carry of addition
; in MSB
mov {si).ax ; Store the result in
; corresponding position of
; resultant matrix
inc di ; increment pointer to matri x!
inc bx ; increment pointer to "fna.trix2
inc si I increment pointer
inc si ; to resultant matrix I
loop back Repeat the process for all
; matrix elements

Copyrighted material
MIC>Oprocnoors and Interfacing 4-3 Assembly Language Programs

mov ah , 4ch ; Exit


int 2lh ; to DOS
end start
end
Flowchart
S<art

tnitilliZt COunttt

Initialize POOter to Matrix 1

Initialize Pointer to Mattix 2

lniCialile Poinler to resultant Matrix.

(",et the number from Matrix 1

Get the numbet rrom Matrb 2

Petform adcilion of two numbers

Increment pointer to Matrix 1

Increment poin1er to Matrix. 2

l ncremen4 pointer to Resut1anc Matrix

Oecremen1 Counter

Copyrighted material
Microprocnsors and ~nterfllcing Aasembly Lln&U-u Programs

Program 4 : Program to read a password and validate user


. MODEL SMALL
. DATA
. STACK 100
PASS DB ' MBS12 3 4 '
~!E$1 DB 10 , 13 , ' ENTER 7 CHARACTER PASSWORD S '
MES2 DB 10 , 13 , ' PASSWORD IS CORRECT $'
MES) DB 10,13, ' INVALID PASSWORDS '
. CODE
STAAT: MOV AX,@DA'!A ; ( Initial i se
~!OV OS ,AX ; data segment )
[>10V AH , 09H
L EA OX, MESl
INT 21H ; Display message
MOV CL , 00 : Clear count
MOV DH , OOH ; Clear number of match
XOR 0 1, DI : Intialise pointer
. WHILE CL ! 7 ; Check if count = 1 i f not
; Continue
MOV AH , 01H
INT 21 H ; Read character
PUSH AX ; save character
~!OV AH , 02H ; ( Display
MOV DL, : ' *' instead of
INT 21H ; character )
POP AX : Re:storc character
LEA BX,PASS ; [ Set pointer
MOV AH , (BX+DI) ; to password l
. r r ALAH ; Compare read character with
; pa.ss aord
ADD DH , 01 ; Increament match count if match
; occurs
. ENDir
!NC Dl ; Increment pointer
!NC CL ; Incremen t counter
. ENOW
rr DH
--
MOV AH , 09H
LEA DX,MES2
7 ; ( if match count 7
; display message
: password is correct
!NT 2 11i
.ELSE : t if match count <> 1
MOV AH, 09H ; display message
LEA DX,MES3 ; password is wrong 1
!NT 21H
. ENDlr
MOV ;..H, 4CH t Exit to
JN'l' 21H DOS l
END S'fART
END

Copyrighted material
.
Microprocessors and Interfacing 4-5 Assembly Language Programs

Program 5 : Program to calculate factorial of a number " '


(Softcopy of this program, P16.asm is available at www.vtubooks.com)

Flowchar1 :

.MODEL SMALL
. STACK 100
. DATA
MS1 08 10 , 13 , 'ENTER THE NO.: $ '
MS2 DB 10,13, ' THE FACTORIAL IS S'
NUM ow 0
AN$ ow 0
.CODE
START : MOV DX, @data ; I Initialise
MOV OS, OX ; data seqrnent
ERROR : LEA DX, MSl
MOV AH,09H ; Display message MS1
! NT 21H
MOV AH,OlH ; I nput number with echo
!NT 21H
CMP AL, 30H ; It zero display I
JE DISPLY2
CMP AL,JOH ; I f ( 30 then input

Copyrighted material
Microprocessors and Interfacing 4-6 Assembly Language Programs

JB ERROR Next no
CMP AL, 39H If >39 then input
JA ERROR Next no
SUB AL, JOH ; Convert to HX
MOV AH , OOH
SUB SP, 0004H ; Space in stack for
PUSH AX , Factorial
CALL FACTO
ADD SP, 0002 ; After execution
POP AX ; Of facto space for
POP ox ; Result
NOV BX,OO!O ; Convert HEX to BCD
MOV CX,0006 ; Max input no is 9
BACK: DIV BX ; To get remainder
OR DX , OOJOH ; Conver t to ASCII
PUSH ox
XOR ox , ox ; Clear ox
LOOP BACK
L1\ OX , MS2 ; Output MS2
l10V AH , 09
INT 21H
MOV CX, 0006
DISPLYl : POP ox
t10V AM,02M Output factorial
INT 21M
LOOP DI SPLYl
JMP LAST
DISPLY2 : ~lOV AH, 09
LEA OX,M$2 Display factorial ot
INT 21 11 ze ro 1
MOV AH, 02H
MDV DL, 31M
INT 21H
LAST : MOV AH,4CH ; Terminate and
!NT 21M ; Exi t to DOS l
FACTO PROC
PUSHF
PUSH AX
PUSH ox
PUSH BP
NOV BP, SP ; Point BP at TOS
MOV AX, (BP + 10) ; Copy no from stack to
. CMP AX , OOOlH ; AX & if no not 1 then
; GO ON
JNE GO ON ; To compute fac torial
MOV WORD PTR(BP+l2) , 0001M
; Else l oad FFACT
MOV WORD PTR (6P+l4),0000H
; 0 and 1 in stack
JMP EXIT

Copyrighted material
MiCTOprocn oors and lhtei'foclng 4-7 Assembly Language Program

GO ON' SUB SP , 0004H ; Space for preliminary


DEC 1\)( ; Factorial
PUSH AX
CALL FACTO
MOV BP,SP
MOV AX, (BP+2) ;
;
Last
stack
(N-
to AX
1) ! from

MUL WORD PTR [BP+l6} ; Multiply by previous N


MOV (BP+lB!.AX ; Copy new facto to stack
MOV (BP+20 I . ox
ADD SP, 0006H ; Point SP .at pushed REGR
EXIT ' POP BP
POP OX
POP AX
POPF
RET
FACTO ENDP
END START

Program 6 : Reverse the words in string


(Softcopy of this program, 1'19.asm is available at www.vtubooks.com)
. MODEL SMALL
.STACK 100
. DATA
TITLE REVERSE THE WORDS IN STRZNG
Ml DB 10 ,1 3 , 'ENTER THE STRING, $ '
M2 DB 10,13, ' THE REVERSE STRING : $ '
BUFF DB 80
DB 0
DB 80 DUP(0)
COUNTER! ow 0
COUNTER2 ow 0
.CODE
START ' MOV AX, @data ; { Initialise
MOV DS ,AX ; da ta segment J
MOV AH, 09H Display message Ml.
MOV DX, OFFSET Ml
INT 21H
MOV AH,OAH
LEA OX, BUFF ; I/P ehc string .
lNT 21H
MOV AH, 09H
MOV DX, O FFSET M2 ; Display message M2
INT 21H
LEA SX , BUFF
INC BX
MOV CH, OOH Take charact~r
MOV CL, BUFF + 1 ; count in
MOV OI , CX DI I

Copyrighted material
~

Microprocess~! ~ anll lntorfaeing 4 8 Assembly Language Progra~M

BACK : MOV DL, (BX+_DI) Point to the end


character and read i t
MOV AH,02H
INT 21H Display the character
DEC DI Decrement count
JNZ BACK Repeat until count isO
EXIT: MOV AH, 4CH ; ( Terminate
INT 21H ; Exit to DOS I
END START
Flowchart :

Set poin&er IO
End of the stri~

Display poin1Dd c:hore<::ter

Pointer =Pointer -1
Count = Couot - 1

Copyrighted material
Itn vJ:
Mlcroprocesoors and Interfacing 49 Assembly l.itnguage Programs

Program 7 : Search numbers, alphabets, special characters


(Softcopy of this program, P20.asm is available at www.vtubooks.com)

Flowchart :

c.... )
l
/ Ge<lhe sblng /
l
Sec alphabet counter 0
$4tt numbof tounler 0
Set s0Eteia1CI'Waeter counter ... 0
l
I Count length of,. Stmg I
I
Set pointer to irs!
owa~er In the siting

J.
< "
CharacMr = H001bef
YH
I
I lnQ"emenl number COt.lnttr I
Is
"" Yes
< cnaracw = AJphabe
I
I No 1h::rement alphabet oo~er J
IS Yes
< Character = Special chcw'aelot
(lncromtnl special dlantt* coUnter(
No
l
1Pon.,. = Pointer .. t I
l
I Count Count t I e

J..
7
No

~ Display
Oi&:play number eountef'
alph~ counter
play apedal Character counter
I
If

( .... )
j_

Copyrighted material
Microprocessors and Interfaci ng 4 - 10 Assembly Language Programs

. HODEL SMAt.t.
.STACK 100
TITLE TOTAL
(THIS ~ROGRht1 GIVES THE TOTAl. NUMBERS, ALPHABETS, SPECIAL
; CHARACTERS I N THE GIVEN STRINGI
. DATA
sur DB 80 ; (MAX LENGTH OF ARRAY I
DB 00 ; (ACTUAL LENGTH OF ARRAY I
DB 80 DUP <01 ; (STARTING OF ARRAY}
STRl DB 10 , 13, 'ENTER THE STRING:$'
STR2 DB 10,13, 'TOTAL NO:$ '
STR3 DB 10 , 13 , 'TOTAL ALPHABETS:$'
STR4 DB 10,13, 'TOTAL SPECIAL CHAR:$ '
NUM DB 0
SPC DB 0
At. PH!\ DB 0

. CODE
START: AX,@data. Initialise
t10V
MOV DS,AX .
;

'
data segment
110V AH,09H
MOV OX, OFFSET STRl ; Address of STRl
INT 21H ; Display message STRl
t10V AH,OAH
110V DX,OFFSET BUf' ; Get address of the buffer
!NT 21H ; Input the string
MOV BX,OFFSET BUF ; Get address of the buffer
I NC BX ; I nCrement address of buffer
MOV DL, I BX) ; Get the length of string
INC BX ; Get the starting of array
NEXT: MOV AL, (BX) Read the character
CMP AL,30H Check for special character
JB INCSPC ; If yes qoto INCSPC
CMP AL, 3AH Check for number
JB INCNliM If number goto INCNUI1
CMP AL, 41H Check for special character
JB INCS PC I f yes goto INCSPC
CMP AL, 5BH Check for a lphabet
JB I NALP If yes goto INALP
CMP AL, 61H Check for special character
JB INCSPC I f yes goto INCSPC
CMP AL, 7BH .
Check for alphabet
JB I NALP ; If yes goto INALP
I NCSPC : MOV AL, SPC
ADO AL,OlH ; INCR special character
; counter and
OAA ; adjust it to decimal
MOV SPC,AL
INC BX ; Increment pointer to point
; the next character

Copyrighted material
Mlc:roprocenon ond lnt.rfaclng 4-11 Assembly Lang.._ Programs

DEC OL ; Decrement counter


JNZ NEXT
JMP DIS PLY ; Otherwise go to OISPLY
INCNUM : MOV AL, NUM
ADO AL,OlH ; I Increment number counter
DAA ; and adjust it to decimal
MOV NUM, AL
INC ax ; Incremen t pointer to point
; the next character
DEC DL Decrement counter
JNZ
JMP
NEXT
OISPLY
;
;
;
If count not -o. repeat
Otherwi se qoto DISPLY
INALP : MOV AL,ALPHA
ADO A.L, Ol H ; t Increment alphabet counter
OM ; and adjust it to decimal I
MOV A.LPHA ,hl..
INC BX ; Increment pointer to point
; the next character
DEC OL ; Decrement counter
JNZ NEXT ; If count not = 0 , repeat
J >IP DISPLY Otherwise go to DISPLY
OISPLY : MOV OX, OFFSET STR2 ; Get the address of STR2
MOV AH, 09H
!NT ::1H Display message STR2
MOV 1\L,NUM ; Read the number count
AND AL, OFOH Get ~IS diqi t in AL rotate AL
MOV CL, 04H ; Four times
ROR AL,CL
ADD Al , 30H Convert to ASCII
MOV DL,AL
f<iOV AH,02H ; Display the MS digit
!NT 21H
MOV AL,NUM Read the number count
AND AL, OFH Get LS digit i n AL
ADD AL, 30H Convert to ASCII!
MOV DL,AL
!NT 21H Display the LS digit
MOV DX, OFFSET STR3 Get address of STR3
MOV AHI 09H
!NT 21H Display message STR3
MOV AL, ALPHA ; Read the alphabet count
AND AL 1 Of OH Get ~15 d i git in AL rotate AL
MOV CL, 04H Fou r times
ROR AL, CL
ADD AL, 30H Convert to ASCII
MOV DLI AL
MOV AH, 02H
!NT 21H ; Display the MS digit
MOV AL,ALPHA ; Read the alphabet count.
ANO AL, OFH Get LS digit in AL

Copyrighted material
Mi~roprocessors and Interfacing 4 - 12 Assembly Language Programs

ADD AL,30H ; Convert to ASCII


I~OV DL,AL
MOV AH, 02H
INT 21H ; Display the LS digit
MOV OX, Of!'SET STR4 : Get the address of STR4
MOV AH, 09H
INT 21H Display message SfR4
MOV AL,SPC ; Read the special character
; c oun t
AND AL, OF OH Get MS digit in AL rotate AL
MOV CL, 04 ; Four times
ROR AL, CL
ADD AL, 30H Convert to ASCII
MOV DL,AL
MOV AH, 02H
!NT 21H Display the MS digit
MOV AL, SPC Read the spe cial cha rac~er count
AND AL, OFH Get LS digit in AL
1\DD AL, 30H Convert to ASCII
MOV DL,AL
MOV AH , 02H
INT 21H Display the LS d i g it
MOV AH , 4CH ; ( Termina te and
INT 2 1H ; Exit to DOS )
END START

Program 8 : Prog ram to find whether string is palindrome or not


(Softcopy of this program, P2l.asm is available at www.vtubooks.com)
. MODEL SMALL
. DATA
M-1 DB 10 , 13 , Enter the string : S '
M2 DB 10 . 13, ' String is palindrome S'
M3 DB 10 , 13, ' String is not pal indrome $ '
BUFF DB 80
DB 0
DB 80 OUP (0)
.CODE
START : MOV AX, @data ; Initia lise
MOV OS,AX ; data segment
MOV AH, 09H
t-tOV OX, OfFSET 1-il
INT 21H ; Disp l ay message Ml
MOV AH, OAH ; Input the string
LEA OX, BUFF
INT 21 H
LEA BX, BOFF+2 ; Get starting address of string
MOV CH , OOH
MOV CL, BUFF+l
MOV DI , CX

Copyrighted material
MICtOprocessors and Interfaci ng 4-13 Assembly Language Programs

DEC OI
SAR CL, l
MOV SI,OOH
BACK: MOV AL, {BX + Oi l ; Get the riqht most character
HOV AH, {BX + SI I ; Get the left most character
CMP AL,AH ; Check for palindrome
JNZ LAST ; If not exit
DEC DI ; Decrement end pointer
INC SI ; Increment starting pointer
DEC CL ; Decrement counter
JNZ 3ACK ; If count not 0 , repeat
#

MOV AH,09H ; Display message 2


t-10V OX , OFFSE't M2
!NT 21H
J~IP TER
LAST: MOV AH,09H
MOV OX , OFFSET M3 ; Display message 3
INT 21H
TER: MOV AH,4CH { Te rminate and
INT 21H Exit to DOS I
END START

Program 9 : Program to display string in lowercase


(Soflcopy of this program, P22.asm is available at www.vtubooks.com)
.MODEL SMALL
.DATA
Ml DB 10 , 13 , 'ENTER THE STRING : S '
M2 DB 10 , 13 , 'THE LOt-lERCAS E STRING : $'
BUFF DB 80
DB 0
DB 80 OUP ( 0)
.CODE
START MOV AX, @data ; ( Initialise
MOV OS, AX ; data segment
MOV AH, 09H ; Display message!
MOV OX, OFFSET Ml
I NT 21H
HOV AH, 09H
HOV OX, OFFSET H2 ; Display message M2
INT 21H
MOV AH,OAH ; Input the string
LEA OX, BUFF
INT 21H
HOV CH, OOH

Copyrighted material
Microprocessors and Interfacing 4 14 Assembly Language Programs
MOV CL, BUFF+ I ; Take character count in CX
LEA BX , BUFF+2
MOV OI , OOH
BAC.:K MOV DL, {BX+OI) point to the first cha r acter
ADD OL, 20H convert to lowercase
MOV AH, 02H
!NT 2 1H Display the character
INC or
DEC ex Dec rement character counter
JNZ BACK ; If not 0 , repeat
MOV AH,4CH ; [ Terminate and
!NT 21H ; Exit to DOS )
END START

Program 10: Write an 8086 assembly language program (ALP) to add


array of N number stored in the memory.
Flowchort :

Start

lnitialle counter
array pointer and sum = 0

Gee array etement

Sum sum array element

Increment array pointer


Decrement counter

Stop

Copyrighled malerial
MlctOprocesoors and Interfacing 4 15 Auembly Langua~ Program
Algorithm :

l . Initialize counter N
2. Initialize array pointer.
3. Sum 0
4. Get the a rray element pointed by array pointer.
5. Add array clement in the sum.
6. Increment array pointer decrement counter.
7. R~at steps 4, S and 6 until counter equal to zero.
8. Display sum.
9. Stop.

Sum of array having HEX numbers


PAGE 52,80
TITLE 8086 ALP to find sum of numbers in the array.
MODEL SMALL
. DATA
ARRAY DB 10H,20H, 30H,4 0H, 50H,60H, 10H,8 0H,90H, OOH
SUl-1 ow 0
ME$ DB 10 , 13 , 'Sum of a rray elements is : $'
.CODE
START ' MOV AX , @data Initialise
MOV OS,AX data segment
MOV CL, lO ; Initiali$e counte r
XOR OI , DI ; Initialise pointer
LEA BX, ARRAY Initialise array base pointer
SAC : MOV AL, (BX+DI I , Get the number
MDV AH , OOH ; Make higher byte DOh
ADD SUM, AX ; SUM .., + number
SUM
INC OI ; Increment pointer
DEC CL ; Decrement counter
JNZ BAC ; i f not 0 go to back
t-10V AX, SUM ; Get sum in AX
CALL 0 HEX ; Display sum of array
t40V AH, 4CH
INT 21 H

Copyrighted material
M~811d lnterfllclng 4-11 Auembly U.ngu-se Prognms

D HEX PROC NEAR

PUSH ox Save reqis ters


PUSH ex
PUSH AX

MOV CL, 0 4H Load rotate count


MV"J' CH , 0 4H Load di git count
BACK: ROL AX, CL rotate digits
PUSH AX save contents of AX
AND Al., OFH (Convert
CMP AL, 9 ; number
JBE ADD30 to
ADD AL, 37H its
JMP DISP ; ASCII
ADD30:
ADD AL, 30H ; equivalent. )
DISP: 1'/:)V AH, 02H

MOV DL,AL ; (Display the


INT 21H ; number )
POP AX ; restor e contents of AX
DEC CH decrement digit count
JNZ BACK i f not zero repeat

POP AX ; Rescore registers


POP ex
POP ox

RET
1 ENDP
I END

II Sum of array having decimal numbars


PAGE 52 , 80
l TITLE 8086 ALP to find sum of numbers in the array .
. HODEL SMALL
. DATA

Copyrighted material
Mlcroproceaora encllnwrfllclng 4-17 Aanmbly Lenguege PYognoma
1\RRI\Y DB 12 , 24 , 26, 63 , 25 , 86 , 20, 33, 10 , 35
SUM IY" 0
MES DB 10 , 13, ' Sum of array elements is $ .
.CODE
S TART : MOV AX, @data. ( Initialise
MOV DS,AX data seqrr.ent
MOV CL, 10 Initialise counter
XOR Dl , DI Initiali$e pointer
LEA BX, .~RRAY Initialise array base pointer
91\C : MOV AL, IBX+DII Get the number
MOV AH, OOH ; Make higher byte OOh
ADD SUM, AX ; SUM = SUM + number
INC DI ; Increment pointer
DEC CL ; Decrement counter
JNZ BAC ; if not 0 90 to back
MOV AX , SUM ; Get. the result
CALL ATB40 ; Display sum of array
MOV AH, 4CH
INT 21H

ATB4 0 PROC NEAR

PUSH ox ; Save registers


PUSH ex
PUSH BX
PUSH AX

MOV ex, 0 ; Clear digit counter


MDV BX, 10 ; Load 10 decimal i n BX
BACK : MOV ox , 0 ; Clear OX
DIV ax ; d i vide DX : AX by 10
PUSH ox ; Sove remoinc:lar
INC ex ; Counter re ma i nde r
OR AX , AX ; test if quotient equ6l to zero
JNZ BACK ; if not zero divide again
MOV AH, 02H load function number

Copyrighted material
Mlcroproceaaora and lnt-clng 4-18 Aaaambly Language Programa
OISP ' POP ox get rema i nder
ADD DL, 30H Convert to ASCII
!NT 21H display digit
LOOP DISP

POP AX ; Restore regi ste r s


POP BX
POP ex
POP ox

RET
ENDP
END

Program 11 : Write 8086 ALP to perform non-overlapped block


transfer.
In non overlapped block transfer, source block and destination blocks are different.
Here, we can tran.<fer byte-by-byte or word-by-word data from one block to another bloc.k.
Algorithm :
t. lnltializc counter.
2. Initialize source block pointer.
3. Initialize destination block pointer.
4. G.>t the byu, from souroo block.
5. Store the byte in the destination block.
6. lncrement source, destination pointers and decrement counter.
7. Repeat steps 4, 5 and 6 unit counter equal to zero.
8. Stop.

I
Copyrighted material
MlcroprocesOO<S and lnterfaclng 4 19 Assembly Language Programs

Flowchart :

Start

Initialize counter
Initialize SOU'ce block pointer
lni1iali2e destination block pointer

Get byte (rom


SOUrc$ blOCk

Store byte in the


destination block

Increment soutee block pointer


lncremeot destination block pointer
decrement counter

No

Non overlapped block transfer


PAGE 52, SO
TITLE Non o verlapped block trans fe r .
. MODEL S~ll< LL

. STACK 100
DA.TA
ARRAY DB 12H , 2 3H,26 H,63 H,25H, 86H,2FH , 33H, l0H , 35H
NEW ARR DB 10 DUP (?)
.CODE
START : >'.OV AX ,@data ; ( Initialise
!',OV OS, AX ; data segment and
>'.OV ES,AX ; e xtra seqment 1
MOV ex, 10 Ini t i a lise co\lnter
LEA SI,ARRAY I nitial ise s ou.rce_pointer

Copyrighted material
Microprocessors and Interfacing 4. 20 Assembly Language Programs

LEA DLNEW_ARR ; Initialise destina.tion_pointer


CLO ; Clear direction flag to
; autoincrement SI and DI
MOV AL , { 51) {Get the number
/lo10V ( Dl) , A L and save number in new array
REP t-!OVSB Decrement CX and MOVSB until Cx
will be 0

LEA OI , NEW_ARR Ini tialise destination_pointer


MOV CX, I O I nitia lize counter
BACK! : MOV AH, I Oil Get number
CALL 0 HEX2 Display number
CALL SPACE Di s play space
l NC Dl Increment dostinatiotl_poi J\ ter
LOOP SACK! if counter not zero. repeat
MOV AH , 4CH Return to DOS
lNT 21H

D HEX2 PROC NEAR


PUSH ex
I'.OV CL, 04H ; Load rotate count
HOV CH , 02H ; Load digit count
3AC : RtlL AX , CL ; rotate digits
PUSH AX ; save contents of AX
AND AL , OFH ; (Convert
CM? AL , 9 ; number
JBE Add30 ; to
ADD AL, 31H ; its
JMP DIS!' ; ASCII
Add30 : l\00 AL , 30H ; equ-ivalent ]
DIS~ : ~10V AH , 02H
MOV OL,AL ; fDJ.splay the
INT 21H ; number)
POP AX ; restore contents oC AX
DEC CH ; decreree-nt digit count
JNZ SAC if not z.ero -repeat
POP ex
-
Rl:"'~"

ENDP
Microprocessors and Interlacing 4. 21 Assembly Language Programs

SPACE PROC NEAR


PUSH AX : Save registers
PUSH ox
MOV AH,02 ; Display space
HOV DL, '
INT 21H
POP ox ; res~ore registers
POP AX
RET ; return to main program
ENDP
END
Overtopped block transfer

We caU two blocb are overlapped when some portion of source and destination
blocks are common. As shown in the Fig. 4.1. source and destination blocks can be
overlapped in two ways. In first case Fig. 4.1 (a) we can begin transfer from starting
location of source block to the s tarting location of destination block, i.e.
(20000H( <- (20005H)

2000EH . - - - - - - - , end

20009 H ------- end


20009 H i - - - - --lend
20005 H - - - - - l start
!
, -

20005 H --------- - start

IDe=~..,1- - i ~-
'' '
20000H .. ......................' stan 20000 H ' -- - - - ' stan

(a) (b)

Fig. 4 .1
We can then increment source and destination block pointers and carry on byte
transfer until the pointers reach the end of two blocks, i.e. upto
(20009H) <- (2000EH].
In second case Fig. 4.1 (b) we cannot use the same block transfer procedure, because
there will be over writing of data within the source block, i.e. a t first byte transfer contents
of 2(XK)()H will be over writh..~ in the location 2000SH and data at 2000SH in the source
block get lost. To avoid over writing in such cases we have to transfer data from source
block to destination block from the end of the block, i.e. we have to begin with the

Copyrighted material
Microprocessors and lnt.rfacJng 4-22 Assembly Language Programs

transfer I2000EH) .-. 120009Hj, decrement the source and dct>tination pointers and carry on
the byte transier untiJ the pointct reach the start of the blocks, i.e. upto
I20005HI+- I20000H)
PAGE 52 , 80
TITLE Overlapped block transfer .
MODEL SMALL
STACK 100
. D~.T.,
AAR!>.Y DB, 12H , 23H , 26H , 63H , 25H ,86K, 2FH, 33H, l0H, 35H , ? , ? , ? , ? , ?
.coos
START : MOV AX , @data ; ( Initialise
MOV DS , AX ; data segment and
MOV ES , AX ; extra segment J
MOV CX , IO ; Initialise counter
LEA SI. ARAAY+9 ; Inic.ialise source_pointcr
LEA Dl,ARRAY+l4 ; !ni tial ise destination_pointer
STD ; SET direction flag to
autodecrement SI and or
MOV AL, [$!) ; Get the number
MOV I 01) ' AL and save number in new array
REP MOVSB ; Decrement e x and f.jOVSB until
Cx will be 0

L EA D!, ARRAYt-5 Initialise destination_pointcr


NOV CX, lO ; initialize counter
BACK! : MOV AH , (Dl) Get number
CALL O_HRX2 Display number
CALL SPACE Display .space
INC 01 ; Increment distination_pointer
LOOP BACK! ; If counter not zero repeat
MOV AH , 4CH , Re tu rn to DOS
!NT 21H

Copyrighted material
Mieroproeeasora and lnl erfac1ng 4 . 23 Assembly Language Programs

D HEX2 PROC ~ t;AR

PUSH CX
I~ I CL, 04H ; Load r ot..s-:.e eour.t
H, o;.H ; !.oad d!.g 1 t ccunt
BI.C : 110~ AX , CL ; r-ota-::e d i'9~ta

PUSII AX : s ave con ter.ta of AX


J.I,O AL 1 OrH ; (Convrt
CH~ AL9 mwbe r

~ Aid30 to
ADO AL , 3'?H ; i ts
JMP Ol.;P ; ASCII
Aod)O : AO~ AL , 30fl i eqi.iiva'ent)
O!SP : tV AH . 02H
:v Dl . AI
It ~ II nu:nber}
i'l.)f AX restorr- C'""ntenta of .\X
E<; '"H ; oecre~e>nt dtg:.lt cour.t
J'Z : 1 f nc-:: :eco repeat
POP
PET
" ~f

S PACE PR'X: NEAP


PUS H AX .save registers
PUSH OX
MOV A!-1 , 02 display space
I-10V OLI I

!NT 21H
POP c.x rest o re regieter:s
POP AX
RET ; r t1.n:n t o ll'8ln proq r am
!lOP
EfJt'

Program 12: Write 8086 ALP to find and count negative numbers from
the array of signed numbers stored In memory.
In sign number n.oprt.osent.ltion.. number is C4llled negati\'e when it! most s1gnificant bit
(MSB) L< l. Thi< bit can be ch<'<:ked by masking all other biL with tl><: help ol logical AND
instruction.
Mlcroproc<~ssoro and Interfacing 4. 24 AsMmbly Language Programs
Algorithm : '
t . Initialize counte r.
2. Initialize array pointer.
3. Initialize negative number count.
4. Get the number.
5. Check sign of number by checking its MSB. If negative increment negative number
count and display the number.
6. Decrement counter and increment array pointer.
7. Repeat steps 4. 5 and 6 until count.,. equal to zero.
8. Display negative number count.
9. Stop.
Flowchart

lnitialze counter, array


pointer and negative number count

Get the number

Yeo

Display number

No

Increment array pointer


Oeaemenl counter

No

Oisptay ~tive
nu-count

Copyrighted material
Mlctoprocessors and Interfacing 4-25 Assembly ~~~guage Programs

PAGE 52 ,80
TITLE Find and count the negative numbers in the array .
. MODEL SMALL
. STACK 100
.DATA
ARRAY DB 92H , 23H , 96H,OA3H,25H, 86H , 2FH , 33H,l0H,35H
MES DB 10, 1 3 , 'Negativ e nu.mbers are $'
M51 DB 10 , 13 , 'Total Negative number count is s.
. CODE
MOll AX, @data ; ( initialise
~1011 OS, AX ; data segment
MOll ex, 10 ; Init.l.alise counter
t"'OV BH, O ; Initialise negative number count
equal to 0
LF.:A BP, ARRAY ; Initi alise array base_pointer
LEA OX , MES
11011 AH; 09H
!NT 21H
MOll AL, OS ' [BPI ; Get the number
11011 AH , AL ; Save number in AH
AND AL, 80H ; Mask all bits e xcept l1SB
JZ NEXT ; If MSB 0 go to next
CALL O_HEX2 ; Othenfise display number
CALL SPACE
INC BH Increment negat.ive number count
NEXT INC BP ; Increment array base_pointar
LOOP BACK ; Decrement counter
; if not 0 qo to back
LEA OX, MES l
MOll AH , 09H
!NT 21H
MOll AH , 02H
ADD BH , 30H
MDV DL,BH
!NT 21H
MOll AH , 4CH ; Exit
INT 21H ; to DOS

Copyrighted material
Mlcroproe9ssors and Interfacing 4-26 Aseembly Language Programs

0 ~-~l P~OC NEAP


~l0V CL, 04H Load rotat.e counc
f.1f.)' CH , 02H ; Load digit count
oAC: ROL AY. . CL rotate di--gits
~OSR AX .
f>ave content-~ of AX
AND l\L OFlt ; rcor.ve-rt
c~<r ;,L, 9 I number
JBE Add30 I LO
AD~ .u, 3lH ; its
JT~P O!SP ASCii
Add~o,
'
ADD i\L , 30Jt ; equivalont.]
DfSP : MOV 0211
o\li 1
!'>10V DL, AL I I Display the
tNT 21H ; uumbet:]
POP 1\.~ restore con~;ents<>f AX
DEC cu
'
I d~o-rement. diqit cou.n c
.mz 61\C ; if n<>t zero repeat
NDP
SPACE PROC NEAR
PUSH AX ; save AX
MOV AH,02H ; I Call DOS routine
MOV OL, ; to leave space 1
!NT 2 1R ; restor e AX
PDP A.~ ; return to main program
R&T
ENOP

END

Program 13 : Convert BCD to HEX and HEX to BCD


Write 8086 ALP to convert +digit HEX number into its equivalent BCD number and
5digit BCD numht!r into its l.'<Juivalent HEX number. Make your program user friendly to
aepl. th( chukc:- frtun usct (or :
a . HEX to BCD
b. BCD to H EX
<. EXIT
Displ:.y pr"~r :-.ttinb"S to protnpl tl1c user whHe :.ccepHng ttl input and displaying the
r('Sldt
4. 27

In this program we use the standard routines explained in the chapter 3 to convert
data from one form to other. However, to ~lect the conversion we di!iplay menu on the
Kreen and display proper messages on the scre...--n to guide user. Therefore. in this
program separate macro named PROMPT is written for display the message. After
accepting the option from the user, the option is checked and proper routine is called to
perform desired operation.
Algorithm :
1
Oisplav menu
a. HEX To BCD
b. BCD To HEX
c. EXJT
ENTER THE CHOICE :
2. Read Ule option
It option is ~x i t

I Do HEX to BCD conversion


2 - Do BCD to HEX conversion
3. Stop
Flowchart :

Display menu
1. HEX to BCD
2.. BCOtoHEX
3. EXIT

React opCioo

Yes

Yos
CAI.L HT8

Yes
CAI.L BTH

Copyrighted material
Mlcroprocenors and Interfacing 428 Anembly Language Programs

PROlPT MACRO t<ESSAGE ; Define macro with NESSAGE as a


; parameter
PUSH AX Save AX r egister
lOV AH, 09H di splay message
LEA OX, MESSAGE
!NT 21H
POP AX restore register
ENOM

. MODEL SMALL select small model


.STACK 100

. DATA ; start data segment


MESl DB 10 , 13, ' 1. HEX TO BCD $'
MES2 DB 10, 13, ' 2 . BCD TO HEX $'
MES3 DB 10, 13, ' 3. EXIT S '
MES4 08 10, 13, ' ENTER 'EHE CHOICE ; $'
MESS DB 10 , 13, ' ENTER CORRECT CHOICE $'
MES6 DB 10, 13, . s .
ME.S7 DB 10, 13' ' ENTER THE FOUR DIGIT HEX NUMBER $'
MESS DB 10, 13 ' ' EQUIVALENT BCD NUMBER IS ; s'
MES9 DB 10, 13' ' ENTER THE BCD NUMBER ; $ '
MES10 DB 10, 13 ' ' EQUIVALENT HEX NUMBER IS : $ '

NUMBER DW ? define NUMBER


.CODE start code segment
START : t<OV AX, @OAT.~ (Initiali ze
110V OS, AX ; data seqment)

PROMPT MESl ; Display MESl


PROMPT MS2 i Display MES2
PROMPT 1ES3 ; Display MES3
PROMPT 1ES4 ; Display MES4

Copyrighted material
Microprocessors and Interfacing 4-29 Asoembly Language Programo

AGAIN: MOV AH,Ol ; READ


!NT 21H ; OPTION

PROMPT ~IES6 i Display MES6

CMP AL, '3' i If choice is 3


JZ LAST ; exit )

CMP AL, '1' ; If choice is 1


JNZ NEXT!
CALL HTB Do HEX to BCD conversion
JMP LAST ; exit )

NEXT! : CMP AL, '2 ' I If choice is 2


JNZ NEXT2
CALL BTH Do BCD to HEX conversion
JMP LAST exit )

NEXT2: PROMPT MESS Di$play NESS


JMP AGAIN

LAST: MOV AH, 4CH Return to DOS


!NT 21H

HTB PROC NEAR

PROMPT MES7
CALL R HEX
PROMPT MESS
CALL D BCD
RET
ENDP

Copyrighted material
Microprocessors and Interfacing 4-30 Assembly Language Programs

BTH PROC NEAR


PROMPT MES9
r~ov ex, 10 : load 10 decimal in ex
MOV BX, 0 : clear result
MOV Ali, OlH : ( Re ad key
INT ZlH : with echo)
CMP AL , 0 I

JB SKIP : jump i f below ' 0'


CMP At , ' 9 '
JA SKIP : jump if above ' 9'
SUB AL, 30H : convet't to B(;D
PUSH AX : save digit
MOV AX, BX mul t i ply previous result by to
MUL ex
MDV ax, 1\X : get the resu l t in BX
POP AX : retrieve digit
MDV AH, OOH
ADD BX, AX Add dig .it value"' .to r.esult
JMP BACK2 ; Repeat
.
SKIP : MOV AX,BX save ~ the re;ult in AX
PROMPT MESIO
,, ;i ~

CALL D HEX
RET
ENDP

R HEX PROC NEAR


MOV CL, 04 load shi ft count
MOV Sl, 04 ; load iteration count
MOV BX, 0 : clear result
SAC : MDV AH , 01 {Read a key
INT 21H : with echo )

CALL CONV : convert to binary

SHL BX, CL ; (pack four


AD.D BL, AL : binary diqits
DEC SI : as 16 - bit
JNZ SAC : number}
MDV NUMBER, BX : save result at NUMBER
ENDP

Copynghted matenal
MlcroPfOCeaaotS 111<1 lnart.c:lng 4. 31 Aseembly Lang..-ge Program

'The procedure ~o convttrt contents of AL into


: hPxa1Pcir..a! equivJ~!ent

cmr.; PnOC N'tAJ\

CMP At., ' j '


JBE SCil':'AAJa
CHP AL,'A'
;e SUSTR/,31 ; if letter 13 upperca.ae
SUB AL, 57H ; subtract 5'7H tf letter 11 lowercase
JMP LASTl
SUBTRAlO:SUB AL, JOH convert nu:r.ber
JMP LAST!
SUBTRA3'1 :SUB 1\L, J711 convert upporcase letter
LP.STl ! RET
CONV Et;op

0 BCD PROC NEAR

WJV AX, h11K9R


HOV ex, 0 ; Clear dic;it counter
MOV BX, 10 ; Load 10 decl..al In llX
BACK:HOV ox, 0 ; Clear DX
DIV BX ; divide OX : AX by 1 0
PUSH DX ; Save remainder
INC ex ; Counter temainder
OR AX , AX ; test if quotient equal to zero
JNt M CK ; i t not z~ro divide again
MOV AH, 02H , load function number
DISP: POP OX ; get. remainder
ADD DL , JOH ; convert to ASCII
!NT 21H ; display digit
LOOP DISP
RET
ENDP

DHEX PROC NEAl\


HOV CL, 04H ; LOad rotate cou.nt
.
MOV CH, 0 4H ; Load c:ii9it count
SAC I: ROL AX, CL rotate digits
PUSH AX ; save content of AX
Microprocessors and Interfacing 4- 32 Assembly Language Program

AND AL, Of'H [Convert.


CMP At..,::; numher-
JBE Add30 t<>
ADC AL, 37H ito
-IMP DISPl ;,.seer
Ada30 :
l!.DO AL, 3011 ; equlval.enc)
O!SPl : NOV AB,02H
('!!(IV 0.&-., AL ; (DiovlY tllo
lNT :11H ; number]
~0~ AX .rest ore con-,:ent_s- of AX
DEC CA ; decrement dig.tt. count
JNZ BACt ; i rtot z.e.r<> n !p4:!at
RET
END~

END

Program 14 : Multiplication of two 8-blt numbers


Algorithm :
1. Read 2-dlgH hex number as tl muJtlplicand.
2. Read 2-digit hl'x numbt?r as a mu1tiplic.r.
3. Initialize iteration count = 8 since multiplier is 8-bit.
4. Make result = 0.
5. Shift result left by !-bit.
6. Rotate multiplier t ..bit to check c:urrent MSB if bit is t, Add multiplicand in the
result
7. Decrement iteration rount and repeat steps 5 and 6 fiU iteration count is zero.
8. Display rest~t.
9. Stop.
.M icroprocessors and Interfacing 4-33 Assembly ~nguage Prognoms

Flowchart :

( Sian )

-- I l
I Read multiplicand I Decrement iteration
counle<
J
( Read multiplier

I "
Coun t-= 1
No

Make result = 0
Iteration count = 8

I [);splay ' " "" I


Shift r esult loeft
by 1-bil
I
l Stop )

I
Rotate multiplier
an d check currenl
MSB of multiplier

Yes H
M$8 1
I
I Add multiplicand in the resun J
No
I

Multiplication of HEX numbers


PROMPT M..h.CRO MESSAGE ; Define mac ro with t-1ESSAG as a
: parameter
PUSii AX ; save register
MOV AH, 09H ; display message
LEA ox. MESSAGE
INT 21H
POP AX ; restore register
ENOM

.0100EL SMALL ; select s mall model


STACK 100

Copyrighted material
Microprocessors and lntarfaclng 4-34 Assembly Language Prog....,.

.DATA ; start data segment


MUL ER 08 ? ; define NUMBER
MOL AND 08 ? : define NUMBER
MESl DB 10, 13 , 'Enter 2- digit heY. number as a multiplicand : $ '
MES2 DB 10, 13 , 'Enter 2-digit hex number as a multiplier : $ '
ME$3 DB 10, 13, 'The result of multiplication is : $ '
.CODE ; start code segment
ST.'\RT: HOV AX, @DATA ; [Initialize
MOV OS1 AX ; data seqment)

PROMPT >1ES1
CALL REAO HEX2
HOV MUL_AND, BL

PROMPT MES2
CALL REAO HEX2
MDV MUL_ER, BL

MDV DH , OO
MDV DL, MUL_AND
MOV cx,oooa
MDV AX , OOOO
REP1 : SHL AX,l
ROL BL, 1
JIJC SKIP
ADD AX, OX
SKIP : LOOP REP1
PROMPT ME$3
CALL D HEX
>JOV AH,02H
MOV OL, ' H'
INT 21H
MOV AH , 4CH ; !Exit to
INT 21H ; DOS)

READ HEX2 PROC NEAR

t10V CL, 04 load shift count


t10V SI , 02 load iteration count
HOV BL, 0 clear result
BACK MOV AH, 01 (Read a key

Copyrighted material
Mlcroproceaao111 and Interfacing 4-35 Assembly Language Programs

INT 21H ; with echo]


CALL CONV ; convert to binary
SHL BL, CL ; [pack t wo
ADO BL, AL ; binary digits
DEC sr ; as 8- bit
JNZ SP.CK ; nulf.ber)
RET
ENOP

; The procedure to convert contents of AL into


; hexadecimal equivalent
CONV PROC NEAR
CMP AL, ' 9'
JBE SUBTRA30 if number is between 0 through 9
CMP AL, ' a '
JB SUBTRA37 if letter is uppercase
SUB AL, 57H subtract 57H if letter is lowercase
JMP LAST
SUBTRA30 : SUB AL, 30H convert number
JMP LAST
SUBTRA37 : SUB AL, 37H convert uppercase letter
RET
ENOP

0 HEX PROC NEAR


NOV CL, 04H ; LOad rotatQ count
t-!OV CH , 0 4H ; Load digit count
BACl : ROL AX , CL ; ro tate diqits
PUSH AX ; save contents of AX
AND AL, OFH ; (Convert
CMP AL, 9 ; number
JBE Add30 ; to
ADO AL, 37H ; its
JMP DISPl ; ASCII
Add30:
ADO AL,30H ; equiva l ent}
OISPl: MOV AH,02H
MOV OL,AL ; [Display the
INT 21H ; number)
POP A.X .
'
restore contents of AX

Copyrighted material
Microprocessors and Interfacing 4 36 -'*mbly Language Prognoms
DEC CH decre ment digi t count
JNZ BACI ; if not zero repeat
RET
ENDP
END
Muttlplication of BCD numbers
PROMPT MACRO NESSAGE: ; Define macro with MESSAGE as a parameter
PUSH AX
MOV AH , C9H
LEA ox, r~ESSAGE
!NT 21H
POP AX
ENDM

. MODEL SMALL select small model


. STACK 100

. DATA start data segment


MUL_ER DB ? deflne NUf-1BER
MUL AND DB ? define NUMBER
tlES 1 OB 10, 13, E:1ter 2-digit BCD number (<256) as a
multiplicand $'
M52 OB 10, 13,
'
' Enter 2-dig it BCD number (<256) as a
multiplier $'
MES3 DB 10, 13,
'
' The result of multiplication is $'
.CODE ; start code- segment
START o NOV AX, @DATA ; [Initialize
MOV OS , AX ; data segmentj

PROMPT MESl
CALL llTH
MDV MUL_ANO, AL

PROMPT r<52
CALL BTH
r10v MUL_ER, AL
fo!OV BL, AL

Copyrighted material
Mlcroprocosson and Interfacing 4-37 Assembly Language Programs

MOV OH , OO
MOV DL, MUL_ AND
MOV cx.ooos
MOV AX , OOOO
REP!: SHL AX , l
ROL BL,l
JNC SKIP I
ADD AX, OX
SKI PI : LOOP REP!
PROMPT M8S3
CALL D BCD

MOV AH, 4CH ( Exit to


INT 21 H DOS)

BTH PROC NEAR


MOV ex, 10 load 10 decima l in ex
MOV ax, 0 clear r esult
BACK2 : MOV liH , OlH : (Read key
!NT 21H with echo!
CMP AL, '0'
JB SKIP jump i t bel o'A ' 0'
CMP AL, ' 9 '
JA SKIP jump i f above ' 9 .
SUB AL, 30H convert to BCD
PUSH AX save digit
t-10V AX, BX multiply previous result by 10
~lUL ex
f-10V BX, AX get the result in BX
POP AX retrieve digit
MOV AH, OOH
liDO BX, 1\X Md dig it val ue to result
~!P BACK2 Repeat
SKIP: MOV AX,BX save the result in AX
RET
ENDP

Copyrighted material
Microprocessors and Interfacing 4 . 38 Assembly Language Programs

D BCD PROC NEAR

l-IDV ex , c Clear digit countet


MOV BX, 10 ; i..oad 10 decimal in BX
B.~CKI' MOV ox, 0 Clear ox
O!V BX ; divide DX : AX by 10
PUSH OX ; S&ve remainder
INC ex ; Counter rema.ind.er
OR AX , AX ; tOSt i f quotient equal to tero
JNZ BACK! ; i f noc zero divide ag;;lin
MOV AH , 02H ; load function no.mbet
OISP : POP ox ; get z:e.mainder
ADO OL, JOH ; Convert to ASCti
INT 2lll ; display di'9it
LOOP D!SP
RET
ENDP

SND

Program 15 : Divide 4 digit BCD number by 2 digit BCD number.


PROMPT MACRO MESSAGE ; Define macro wi th MESSAGE as a parameter
PUSH AX
MOV AH, 09H
LEA ox, MESSAGE
INT 21H
POP AX
ENDM

.MODEL SMALL ; select sma ll model


. STACK 100

DATA start data segment


O!V!SOR DB ? ; de t ine NUMBER
DIVIDEND ow ? ; define NUMBER
MES l
MES2
DB
DB
10 , 13 ,
0 . 1) ,
' En tar 4- diq i t BCD number
dividend:$'
' Ente r 2-digit BCD number as a divisor:$'
HES3 DB 10 , 13 , ' The Quotient of Division is $'
!1ES4 DB 10 , 13, ' The Remainder o! Division is s'
Mlcroproceasora and lnterlKing 4 - 39 AaMmbly Language Prog.....,.

.CODE ; start code seqfl'!ent


START' MOV AX, @DATA ; {Initia l ize
MOV OS, AX : data seg:eent.)

PROMPT HSI
CA~~ ATB

PROMPT MES2
CA~L 8TH
MOV DIVISOR, AL

~10V AX, DIVIDEND


DIV DIVISOR

MOV BX,AX
PROMPT ME$3
MOV AH, 00
CALL D_BCD

PROMPT 1'.53

MOV AH, OO
MOV AL, BH
CALL D BCD
-
MOV AH , 4CH ; (Exit t o
I NT 21H ; DOSJ

BTH PROC NEAR


MOV ex, 10 ; !oad 10 docimal in ex
MOV BX, 0 ; cle~:r reaulc
BAC'K2: HOV ; (Read key
"" 0111
lNT 21H ; W1th echo}
CMP AL,O
JB s~: :P! ; JU"-P lf be.!ov '0'
CMP AL, '9'
JA SY-.!Pl : j=p H above 9.
SUB AL, JOH ; convert to BCD
PUSH AX ; save diqit
MOV AX, BX ; r.ultiply previoua result by 10
Mlcroproc:easors and Interfaci ng 4 40 Assembly language Programs
~:+~
. ,,....Mot' BX,
ex
in. ax
MOV AX ;
POP AX ;
MOV AH, OOH
ADD ax. ;,x i to result
., JMP BACK2

;
'
SKIEl": tlOV AX,BX ; iJ' AX
RET
ENDP

[!)lCD PROC NEAR

'
PUSH BX
r~ov CXi
. 0 .
Clear
~..
cligi~. coUnter-
.
MOV BX, 10 ; Load 10 decimal . in ..BX
~KI : MOV OX, 0 ; Clear OX 'it'I ,
DIV BX ; d i vide ox : x AX by 10
fOSH OX ; save r~ma.i:nder t
INC ex ; Counter : remainder
... ... .:;
OR AX, AX ; te$t if quotient equal to 'zer:o "'
JNZ BACKl I if not 2.erp di_-vide a_q ain
MOV J\H, 02H .
load fun <;;i9D ~ numb~ ;r
DISP : I'P ox .
q:et r emainder '
ADO OL, 30H ; Convert to ASCI I
INT aH ; display digit
LOOP OISP /
I'OP BX
RT
ENDP

ATS PROe NEAA

PUSH ex I Save registers


'
PUSH BX
PUSH AX
""
/

ijACK :
~IOV

MOV
~lOV
ex.
BX,
AH , OlH
10
0
l oad10 decimal ln ex
clear r esult
; [Read
- '
key

!NT 21H I wi th echo)
C~lP AL., 0 '

Copy nghteo r 1tenal


Mk:toproc:enort and lnwrfacing 4-41 Alt..,.bly I.Ainguege Programs
JB SKIP ; jUl<'p t! No low o
Cl<P AL, '9'
JA SK:P ; j u:>tp
..
1L aOOve .
~
SUB AL, 30H .
conver"t tc BCD
PUSH AY. .
sav~ C.i.9it
MOV AX, BX ; multiply prevto~ result by 10
"UL ex
HOV BX, AX ; get t.ne result BX
POP AX ; retrieve diqtt '"
MOV 1\H , OOH
ADO BX, AX ; Add digit value to result
JMP BAC~ ; Repeat
SKIP: MOV 01\11 DNO, BX ; eave thP re~ult in NUMBER

reP AX Res-=.ore req1.sters


POP BX
POP ex
PET
[NOP

EIID

Program 16 : To perform conversion of temperature from f to c.


PROMPT MACRO MESSAGE ; Define mc.1cro ._.ith MESSAGE as .!1 parameter
PUSH AX
MOll AH , 09H
LEA ox I MESSAGE
INT 21H
POP AX
ENDM

MODEL SMALL ; St!lQct. sr.:al l l:lOdel


. STAC~ 100

. DATA ; start data seqr.:ent


NUMBER 011 1 ; define NUMBER
MESl DB 10,13, Ente:- Temperature in De:9reeFAHRNtT : $
MES2 DB 10 , 1J , ' The Temperature in Degree Celaiua is : $'
Microprocessors and Interfacing 4-42 Auembly Language Programs

.CODE start code seqment


START : MOV AX, @DATA {Initialize
MOll DS, ~. X data se9ment J

PROMPT MESl

CALL ATB Get the Temperature in F

MOV AX , NUMBER
SUB AX , 20H ; Subtract 32
MOV NUMBER, AX

t-10V BX,05
MOV CX , 09
MUL BX ; Multiply by 5
DIV ex ; Divide by 9

MOV NUMBER, DX ; Save remainde r


PROt<PT ~1ES2

CALL D_ BCD : Displ a y result in decimal


CMP NU~IBER, 0 ; If remainder is zero e xit
JZ LAST
MOV DL, ; Display decimal point
MOV AH, 02H
!NT 2!H

MOll AX, 0064H ; Multiply remainder by 100


t<UL NUfo1BER Di v ide resul t by 9
DIV ex
CALL D BCD display f ractions

LAST: MOV AH , 4CH (Exit to


!NT 21H ; DOS )

Copyrighted material
Mlcroproceooora and lnt.rfaclng 4 43

,-
~.'Ito
--
..: ....

MOV ; clear diqit , c;Oiu i.ter
Load 1 0 de<;.l:ma 1
., .
Clea..c DX .. ~
'

i
AX, ,. AX lc f:
BACKl ;" .it )'lO:t zero
"' ~'
t' '
MOV J\lj, 02H ~ ;
DfS.I' : P.OP Ox " -
30H

~.'

; Save

with echo1

'
lf

,.
jUmp if' above 9'
.
. '
cOnvert t'O ~!'- .
; save tligl ~ .
1
..
lri~itip>y .pt1!V~~ result by 10

"
qet the resulj; _in BX i f .,
;. r~ t,r4.eve %<,J dfg1 t ' '
r
.
'4'

Copyrighted material
Microprocessors and Interfacing 4 44 Assembly Language Programs
ADC BX, AX : Add d!qit value to result
.JMF 8ACII : Rep~at
SKIP: HOV t~UMBER1 B.X save tbe- re3U 1t in lWMBr:R

POP AX
POP sx
POP ex
RET
Ellll.P
END

Program 17 : String operations


Program S-meni : Write 8086 ALP for the following operations on the string entered
by the U$4/r.
a. Calculate Jength of the string.
b. Reven;.e the string.
c. Cht.--ck whether the string. is palindrome or not.
Make your pro~:;ram """r friendly by providing MENU llke :
Enter tl\e string.
b. Ca.lculate length of siTing.
C~ Revets(' s tring.

d . Cht.>ck p,1Jindrome.
c.-. Exit.
Here we usc PROMPT macro to display the mess.1ge on the screen, accept choice from
the u...er and call _proper prvcedure to perform desired tolsk. To enter a string we use
function OAH of INT2!. This function accepts a string and stores it in tl\e buffer along
with its length. Let us see the algorithm and flow chart.

II
Microprocessors and Interfacing Anembly Langu- Programs

Algorithm :

1. Display Menu
a. Enter the string.
b. Calculate length of the string.
c. Reverse the string.
d . Check whether the string is palindrome or not.
-. Exit.
Enter the option : -
2. Read the option
If option is
a. Read the string.
b. Read the string length and display it.
c. Initialize pointer at the end of the string and display the string from end to
start.
d. i) lnitializ.e two pointers one at s tart and other at the end.
ii) Compare two bytes; if not t..:.qual s top and display string is not palindrome.
ii.i) Increment start pointer and decrement end pointer.
iv) Repeat s tep ii) and iii) until two pointers overlap i.e. until sta_rt pointer
reach the half the string.
e. Exit to DOS.
3. Stop.

Copyrighted material
Microprocessors and Interfacing 4. 46 Assembly Language Programs

Flowchart :

Read option

I
Yes

Check palindrome
No
OispJ.ay meuage
enter OOtre<:l option

Stop

Copyrighted material
Mlcroproc:esoors ond lnt.rfaclng 4. 47 Aoumbly Language Progroms

Flowchart : String Reverse

Set poln1er 10
End ot me $1r1ng

Oisplay pointed character

POinter Poln'ler - 1
Count Count - 1

No

Flowchart : String Palindrome


Start
t
Initialize pointer at
the s.tal"'. of the siting

I
lnltlallze pointer at
the end of the string

I
J1nitia1ite counter= lcngMI

Compare charaetets
pointed by two strings
Are
characters
No
equal
I Oecremenl oounter I
Yos

No
1,.
oountet = 0 Display message
sbing is not palindrome
Tves
OISf)l&y meuage
string is palindrome

I
( St<>p)

Copyrighted material
Mlcroproceaaors and Interfacing 4 48 Assembly unguage Programs

PRO~lPT ~lliCRO

PUSH
MESSAGE : Define macro with MESSAGE as
AX ; save AX register
parameter
t~OV AH, 091! ; disp lay message
LEA ox, ~!ES SAGE
!NT 21H
POP AX ; restore AX re9ister
NOM

.MODEL St1ALL ; select small model


. STACK 100

. DA"l'JI. .
start data segment

MESl DB 10 , 13, 'L ENTER THE STRING s .
MES2 DB 10, 13 , 2' CALCULATE THE LENGTH OF STRING $ '
MES3 DB 10, 13 . 3 . REVERSE THE STRING s.
H.ES4 DB 10, 13 . q PALINDROME $ '
><ESS DB 10, 13 . 5 . EXIT $.
MES6 DB 10 . 13. 'ENTER THE CHOICE : $.
MES7 DB 10, 13. 'ENTER CORRECT CHOICE : $.
MESS DB 10, 13 , $.
MES9 DB 10, 13, ' FAILED : STRING IS MISSING - PLEASE
ENTER THE STRING$'
~1ESI 0 DB 10, l3, ' STRING LENGTH IN DECHlliL IS $'
MESll DB 10 . 13, ' STRING IS NOT PALINDROME $.
MESI2 DB 10 , 13, ' STRING IS PALINDROME $.

fLAG DB 0
MES13 DB 10, 13, ' ENTER THE STRING : $'
>IES14 DB 10 , 13 , ' THE STRING IS : $ '

BUfF DB 80
DB 0
DB 80 DUP(O)
COUNTER! ow 0
COUNTER2 ow 0

Copyrighted material
lollcroprocen ors and Interfacing 4-49 Anembly Language Programs

NUMBER ow ? ; define NUt~BER

. CODE ; start code segment


START : ~ovAX, @DATA ( !nitialize
MOV OS, AX data seqmcnt)

BEGIN: PROMPT MESS Display MESS


PROI<PT MESS Display MESS
PROMPT MES1 Display MESI
PROMPT MES2 ; Display MES2
PROMPT M$3 ; Display MES3
PROMPT MES~ ; Display MES4
PROMPT MESS ; Display MESS
PROMPT MES6 ; Display MES6

AGAIN : ~!OV AH, Ol ; READ


INT 21H ; OPTION

PROMPT MESS ; Display MESS

CNP AL, ' 5' ; If choic~ is 5


JZ LAST ; exit I

CMP AL, ' 1 ' ; { I f choice is 1


JNZ NEXT!
CALL E STR ; Enter the string
PROMPT MESS
PROtiPT MES14
CALL D STR Display the s tring
JMP BEGIN exit l

NEXTl: CMP AL, ' 2 ' It choice 1 2


JN Z NEXT2 ..-
CALL L STR Calculate the length of the string
JMP BEGIN e xit I

NEXT2: CMP AL, ' 3 ' ; It choice i s 3


JNZ NEXT3
CALL R STR Reverse the strin9

Copyrighted material
Microprocessors and Interfacing 4-50 Assembly Langug Programs

JMP BEGIN exit J

NEXT3: c r~P AL, '4' ; I f choice is 4


JNZ NEXT4
CALL P_STR ; Palindrome of the st.ring
JMP BEGIN ; exit

NEXT4 : PROMPT '1ES7 ; Display MES7


JMP AGAIN

LAST : MOV AH , 4CH ; Return to DOS


!NT 21H

E STR PROC NEAR


PROMPT MES13 Display message MES13
NOV AH , OAH
LE/1. OX, BUFF 1/P the string .
INT 21H
t>'IOV ~LAG . I
RET
ENDP

L STR PROC NE~.R


CMP fLAG, O
JNZ SKI P
PROMPT MES9
RET
SKI P: MOV AL, BUFF+!
PROMPT ME$10
CALL D HEX
RET
ENDP

R STR PROC NEAR


CMP fLAG, O
JNZ SKIP!
PROMPT MES9
RET

Copyrighted material
Mlc:roproceaaora and l nt.rfllc:lng ... 51 Assembly Langu- Programs

SKIP1: CALL DR STR


RET
ENDP

P STR PROC NEAR


LEA BX , BUFF+2 ; Get starting address of string
MOV CH,OOH
MOV CL, BUFF+l
tov DI,CX
DEC DI
SAR CL,l
MOV SI,OOH
BACK4: MOV AL, (BX + DI) ; Get the right most character
MOV AH, (BX + SI) ; Get the left most character
CMP AL,AH ; Check for palindrome
JNZ LAST2 ; I f not exit
DEC DI ; Decrement end pointer
INC SI Increment starting pointer
DEC CL ; Decrement counter
JNZ BACK4 I f count not 0 , repeat
PROMPT ME$12 ; Display message 12
RET
LAST2: PROMPT ME$11 Display message l l
RET
ENDP

0 STR PROC NE.AR


LEA BX, BUFF
MOV CH,OOH I 'Take character
MOV CL,BUFF +1 count in
liOV OI , OO DI 1
BACK: MOV DL, (BX+OI+2) Point to the start
character and read it
.!OV AH, 02H
INT 21H ; Display the character
INC DI Decrement count
LOOP BACK Repeat until count is 0
RET
ENOP

Copyrighted material
Microprocessors and l ntarfltc:l ng . 452 Assembly Language Programs

DR STR PROC NEAR


LEA BX,BUFF
MOV CH,OOH ; Take character
MOV CL , BUFF+l ; coun t in
MOV Dl , CX ; DI )
!10V DL, IBX+DI+l I ; Point to the start
; character and r ead i t
MOV ll.H, 02H
!NT 21 H ; Display the character
DEC 01 ; Decrement count
JNZ BACK3 ; Repeat until count is 0
RET
ENDP

0 HEX PROC NEAR


MOV AH, OOH Clear AH
AAM convert to BCD
ADD AX, 3030H ; Convert to ASCII
MOV SX , AX Save result
MOV DL, BH Load f'irst digit (MSD)
NOV AH , 02 ; Load f unction number
lNT 21H ; Display f irst digit (MSO)
f.lOV DL. BL ; Load second digit (LSD)
!NT 21 H ; Display second digit (LSD)
RET
ENDP
END

Program 18 : String Manipulations


Program Statement :

Write 8086 ALP to perfonn string manipulation. The strings to be accepted from the
user L' to be stored in code segment Module_! and write FAR PROCEDURES in code
St..:.gment Mlxiule_2 fo r following operations on the string.
a. Concntenation of lw o strings.
b. Compare two strings.
c. Number of occurrences of a sub-string in the given string.
d. Find number of wo rd~, characters and apitaJ letters from the given text in the
data St."'gment
i'

Copyrighted material
Mlcroprocenora and Interfacing Anembly Langu19e Prog,.ms

Note : Use PUliLIC and EXTERN directive. Create . QB) files of both the modules and
link them to create an EXE file. Command : Tlink Ml.OB) M2.0BJ
In this experiment we have to write two . asm programs one for accepting strings and
one for procedures.

Algorithm : Module_1
1. OispJar Menu
a. Enter the strings.
b. C.oncatcnation of two strings.
<:. Compare two strings.
d. Find number of occurrences of a substring.
e. Find words, characters and capital letters.
f. Exit.
2. Read option
It's option is
1. Read two strings.
2. Concatenate two strings.
3. Compare two strings.
4. Find number of occurrences of a substring.
5. Find words, characters and capital letlers.
6. Exit.
3. Stop
M1 : String operations
PROMPT MACRO 1<1ESSAGE ; Define macro '.iith t1SSAG as a parameter
'PUSH AX save registers
PUSH ox
MOV
LEA
AH,
OX,
09H
MESSAGE
d isplay message
. ..
..

!NT 21H
POP OX restore registers
POP AX
ENOM

MODEL SMALL ; select small model


.STACK 100

Copyrighted material
Mlcroproc:nsors and I..Wrfaclng

.DATA ; start data segment


PUBLIC BUFFl
PUBLIC BUFf"2
PUBLIC BUFF3
MESl CB 10 , 13, 1
1. ENTER THE STRING $'
t1ES2 CB 10 . 13 , '2. CONCATENATION OF TWO STRINGS S '
MES3 DB 10 , 13 , '3 . COMPARE TtlO STRINGS $ '
MES4 CB 10 , 13, '4. NUMBER OF OCCURENCES OF A
SUBSTRING S'
MESS CB 10, 13, '5. FINO WORDS, CHARl\CTERS AND CAPITAL
LETTERS s I

MES6 DB 10, 13 , '6 . EXIT $ '


MES7 DB 10, 13, ' ENTER THE CHOICE : S '
MESS DB 10, 13 , 'ENTER CORRECT CHOICE S'
MES9 08 10, 13 , 's'
MESlO DB 10 , 13, ' STRING IS MISSING - PLEASE ENTER
THE STRINGS '
MESll DB 10, 13 , ' CONCATENATED STRING IS : S'
MES12 DB 10, 13 , ' TWO STRINGS ARE S AME S'
MES13 DB 10 , 13, 'TWO STRINGS ARE NOT SAME S'

FLAG 08 0
MES14 DB 10, 13 , ' ENTER THE STRING : S '
MES15 OB 10, 13, ' THE STRING IS : S '

BUFF! oB so
DB 0
DB 80 OUP(0)
BUFF2 DB 80
oB o
DB 80 DUP!Ot
BOFF3 DB SO
DB 0
DB SO DUP (0)
. CODE ; start. code segment

EXTRN CON STR: FAR


EXTRN COM_STR : FAR
EXTRN SUB STR: FAR
EXTRN FWCC_ STR : FAR

Copyrighted material
Mlcroprocouorsnd l~ng <1 55 Assembly~ Proarw

START : MOV AX, @DATA {Initialize


MOV OS, AX ; data aegment)
MOV ES, AX
BEGIN : PROMPT MES9 ; Display MESS
PRO~!PT t4ES9 ; Disp!Q.y MESS
PROMPT MESl ; Di$play MESl
PROr"'PT MES2 ; Display MESZ
PR0t4PT t!ES3 ; Displa.y MES3
PROMPT lo!ES4 ; Display MES4
PROMPT MESS Display MESS
PROMPT MES6 ; Display MES6
PROMPT MES7 ; 01splay MES7

AGAIN : MOV AH , Ol ; READ


! NT 21H ; OPTION

CI"'P AL, ' 6 ' ; If choice is 6


JZ LAST ; exit 1

MOV BL, FLAG ; Check for f irst occurrence


CMP BL, O
JNZ SKIP ; i f not skip
CMP AL, ' 1 ' ; check i f choice is 1
JE: SKIP ; if yes skip
~ROMPT HESlO ; otherwise qive error message
JMP BEGIN ; and enter the strings

SKIP : PROMPT HES9 ; Display >!ES9

CM? AL, ' 1 ' ; I l f choice is l


JNZ NEXT!

LE:A ox, BUfFl


CALL E STR ; Enter. the stringl

LE:A ox. 8Uff2


CALL E STR ; Enter the st["inq2
MOV FLAG, !
JMP BEGIN ; exit

Copyrighted material

Microprocessors and Interfacing 4. 56

NEXT!: CMP AL, '2 ; If choice is 2


JNZ NEXT2
CALL CON STR ; Concatenate two strings
JMP LAST ; exit I

NEXT2: CMP AL, ' 3' ; If choice is 3


J NZ NEXT3
CALL COH_STR ; Compare two string
J~1P BEGIN ; exit I

NEXT 3: CI1P AL, ' 4 ' ; I I f choice is 4


JNZ NEXT4
CALL SUB_STR rind number of occurences of a
; sub- string i n the given str ing
J I<P BEGIN ; exit I
NEXT4: CMP AL, ' 5 ' ( If choice is 4
JNZ NEXTS
CALL F'riCC STR Find word, character and capital
letters in the string
JMP BEGIN ; exit

>IEXTS: PROI<PT MESS ; Display t<ES8


JMP AGAIN

LAST : HOV AH, 4CH Return to DOS


! NT 21H

E STR PROC NEAR


PROMPT MESl ; Display messaqe MESl
~10V AH, OAH ; I /P the string .
!NT 21H
RET
ENDP

END

Copyrighted material
Microprocessors and Interfacing 4. 57 Assembly Language Programs

M2 : For string operations


.I!OOEL S~!ALL

.STACK 100
. DATA
EXTRN BUFFl : BYT
EXTRN BUFF2 : BYTE
EXTRN BUFF3 : BYTE
MESS1 DB 10 , 13, 'STRINGS .~ RE
SAME $ '
MESS2 DB 10 , 13 , 'STRINGS ARE NOT SAMES'
MESS3 DB 10 , 13, 'NUMBER OF ALPHABETS TN THE STRING
ARE:$'
MESS4 DB 10 , 13 , ' NUMBER OF CAP!T~. L LETTERS IN THE STRING
ARE:$'
HESS5 DB 10,13 , ' NUiiBER OF WORDS I N TH STRING AR : S'
M556 DB 10 , 13 , ' NUMBER OF OCCURRENCES OF SUBSTRING IN
T HE STRING IIR : S'
l'ifLAG DB 0
ACOUNT DB 0
CCOUNT DB 0
WCOUNT 0~ 1
C ADDR Dl~ ? current address of pointer
E_ ADDR Dt< ? End address of string

. CODE

PUBLIC CON STR


PUBLIC COH STR
PUBLIC SUB_ STR
PUBLIC F"riCC S TR

-
CON STR PROC FAR

CLO
MOV CH, 00 ; copy string l
NOV CL , BUfF l+l
LEA SI, BUFE'l +2
LEA DI, BUFF3+2
REPZ MOVSB

MOV CH, 00 ; copy string 2


MOV CL , BUFF2+1

Copyrighted material
Microprocessors and Interfacing 458 Assembly Langu- Prognoms
LEA SI , BUFF2+2
REPZ HOVSB

t-1CN CL, BUFtl+l calculate and store length of


concatenated stri ng
ADD CL, BUFE"2+ 1
t-10V BUFF)+ 1, CL

~lOV CH , OO . Di splay conca tenated string


LEA SI,BUFF3+2
DI SNEXT: MOV AH , 02H
r<OV OL , [SI l
INT 21H
INC SI
LOOP DISNEXT
RET
CON_STR ENOP

COM STR PROC FAR

MOV CH, BUFFl+l ; check t wo string character by chara c~ er

MOV CL, BUFF2+ 1


CMP CH , CL

' JNZ NOTEQ


CLD
MDV CH, OO
LEI'< $! ,BUFF1+2
LEA DI , BUFF2+2
REPE C.lPSB
JNZ NOTEQ

MOV AH, 09H ; i f equal displa y message accordingly


LEA OX, MESSl
INT 2 1H
JMP RE
! NOTEQ: MCV AH, 09H i if not equal display message
I according ly
I LEA OX, MESS2
I INT 2 1H

Copyrighted material
Microprocessors and Interfacing 4. 59 Assembly Language Programs

RE: RET
COM_ STR ENDP

SUB_STR PROC FAR

MOV BL, 00
LEA SI , BUFF!+~

t-10V c _ ADDR, 51 ; Load cu rrent address


NOV 01.., BUFf"l + 1
.,OV DH, 00
MOV AX , SI
J\00 AX, OX
MOV E_AOOR,AX ; load end address
NOV CH, 0
MOV CLIBUFF2+1 ; load lenqth of substrin9
LEA DI . BUf'f'2+2 ; initiali ze pointer to substring
t10V BH, (SI)
CMP BH, B'i'l'E PTR (01 1 ; compare substring characters
JNZ NNNEXT ; if not equal 90 to NNNEXT
INC SI ; otherwi se increment character pointers
INC 01 ; and conf ine
LOOP BBB
INC BL ; if subst r ing occurs inc.rement count
C~!P S! , E AODR ; check for end of string
JNZ STl ; if not zero qo t o check more
occurrences
JMP LLLAST ; i t end of string go to displ ay number
of occurrences
NNNEXT : MOV SI , C_ADDR
I NC Sl
MOV C_AOOR, SI ; mod ify current address
CMP SI, E_AOOR
JNZ STl

MOV AH, 09H ; display nu.mber ot occur.rences of strinq


LEA OX, MESS6
INT 2 1H
MOV AL, BL
CALL DIS HEX
RET

Copyrighted material
Mic~oooro and Interfaci ng 4-60 Assembly Language Prog111ma

SUB STR ENDP

fWCC STR PROC FAR

MOV CH, 00
HOV CL, BUFFl +1
LEA SI , BUFF1+2
BB : MOV AL, (SI) ; check of space
CMP AL, '
J NZ NNEXT
MOV AL , WFLAG if space occur s increment word count
CMP AL, 0
JZ LLAST
MOV WFLAG, 0
INC WCOUNT
JMP LLAST
NNEXT: MOV WFLAG, 1
; . IF AL > ' A. && At < I z I

CMP AL, 'A '


JB LLAST ;
check if a lphabet
CMP AL, I~ I ; if yes increment a l phabet count
JA NNEXTl
INC ACOUNT
INC CCOUNT
; . ENDIF

NNE:XTl : ;.IF AL > ' a' && AL < 'z'


Cf-JP AL, 'a'
JB LLAST ; check if alphabet
CMP AL, ' z ' ; i f yes i ncrement a l phabet count
JA LLAST
INC ACOUNT
; E NDIF
LLAST : INC SI
LOOP BB

MOV AH, 09H display a lphabe t count


L EA OX, ME:SS3
INT 2 1H
MOV AL, ACOUNT

Copyrighted material
4-61 Asaombly Lllnguage Prog..ms
CALL DIS_ HEX

HOY AH,09H display character count


LEA DX,MESS4
!NT 21H
MOV AI., CCCXJNT
CALL DIS_HEX

MO\' AH, 09H display word count


LEA OX, MESSS
!NT 2 1H
MOV AL, WCOUNT
CALL DIS_HEX

MOV ACOUNT, 0
MOV CCOUNT, 0
MOV WCOVIIT. I

RT
fWCC_ STR ENDP

DIS HEX PP.OC IIEAP


MOV All, OOH ; Clear AH
AAII
; Convert to BCD
ADD AX, J OJOH Convert to ASCII
HOV BX,AX ; Save result
MOV DL, BH Load fiut digi~ (MSD)
HOV AH , 02 Load function number
!NT 2lH ; Display Cirat digit (HSDI
MOV DL, BL Load second digit (LSD)
!NT 21H ; Display aeeond diglt (LSDI
RET
ENDP
END
._1

Micr oprocessors and Interfacing 4. 62

Program 19 : Sorting of Array


Program Statement : Write 8086 ALP to arrange the numbers stored in the array in
a~nding as well as descending order. Assume that the first location in the array hold~
the number of elements in the array and successive memory locations will be actual array
elements. Write separate s ubroutine to arrange the numbers in ascending and descending
order. Accept key from the user.
U user enters 1 : Arrange in a<~~Ce:nding order
If user enters 2 : Arrange in descending order
Sorting of Amy
PROMPT MACRO MESSAGE ; Deline macro with MESSAGE as a
PUSH AX parameter save reg ister
MOV AH, 09H ; display message
L EA ox, MESSAGE
INT 21H
POP AX ; restore register
ENOM

MODEL SMALL
. STACK 100
.DATA
ARRAY DB 10 , 53H, 20H, 30H, 25H , 50H, 09H, 10H, 13H, 90H, OOH
MES 1 DB 10 , 13 , 'I. SORT ARRAY IN THE ASCENDING ORDER $'

MES2 DB 10, 13 , 2. SORT ARRAY I N THE DESCENDING ORDER s


ME$3 DB 10, 13 , 3. EXIT $'
P.1ES4 DB 10, 13, ' ENTER THE CHO I CE s.
MS5 OB 10, 13, ' SORTED ARRAY IS : $ '
MES6 DB 10, 13, ' ENTER CORRECT CHOICE : s
MES7 DB 10, 13, '$'
.COO
START: MOV AX,@data : Initialise
ti()V OS , AX data segment

PROMPT MES 1
PROMPT MS2
PROMPT MES3
PROMPT MES4

Copyrighted material
Mlaoprocesoon nd -clng -4 - 63 ...._,y Lan{IU8118 p.._,
STl: HOV AH,OlH
!NT 21H

CMP AL# ' 3 '


JZ LAST

CMP AL, I 1'


JNZ NEXT
PROMPT MES7
CALL ASC
JMP LAST
NEXT : CMP AL, 2 I
JNZ NEXT!
PROMPT MES7
CALL osc
JMP LAST
NF.XTl : PROMPT MES6
JMP STl
LAST : MOV AH , 4CH
HIT 21H
l\SC PROC NEAR
!-10V CL,ARRAY ; Init iali se countorl
8881 : r~ov CH , ARMY ; Initiil li se counter2
DEC CH
XOR DI , DI Initialise poi nter
LEA BX,ARRAY ; Initia li se a rray base pointer
BACK! : r~ov DL, [8X+Dl+l] ; Get the number
CMP OL, [BX+DI+2) ; Compare i t with next number
J8 SKIP!

MOV AH , [8X+DI +2] ; Other.,.ise


mv {BX+DI+2] , DL ; exc hange
MOV [8X+DI+l I ' AH ; two number s

SKIP! : INC DI
DEC CH
JNZ BACK!
DEC CL
JNZ 8881

Copyrighted material
MlctOproeessors and Interfacing 4-64 Auembly Ulnguage Programs

PROMPT MESS
MOV CH, OO
MOV CL, ARRAY
LEA DI , ARRAY
INC DI
AGl ' INC DI
MOV AL, (OI (
CALL D HEX2 ; Display sorted a rray
PUSH AX
PUSH t,,;
t-10V AH,02H
MOV DL,
!NT 21H
POP ox
POP AX
LOOP AGl
RET
ENOP

osc PROC NEAR


MOV CL,ARRAY ; Initialise counterl
BBB ' MOV CH, ARAAY ; Initia lise counter2
DEC CH
XOR 01.01 Initialise pointer
LEA BX, ARRAY Initia lise arra y base pointer
BACK ' MOV OL , (BX+OI+ l) Get the numbe r
CMP OL, (BX+OI+2 ) Compare it with next number
JAE SKIP

MOV AH, ( BX+DI+2 ) Ot he rwise


MOV (8X+OI+2 ) , DL exchange
MOV (BX+DI+l) , AH ; t wo numbers

SKIP ' I NC DI
DEC CH
JNZ BACK
DEC CL
JNZ BBB

Copyrighted material
Mlcropi'OCeDOI'S and lntarfacing 465 Assembly LAnguage Programs ..
PROMPT M$5
MDV CH, OO
MDV CL,ARRAY
LEA OI ,ARRAY
I NC OI
AG: INC OI
MOV AL, [Oil
CALL () HEX2 Display sorted array
PUSH AX
PUSH OX
MOV AH, 02H
~IOV OL,
INT 21 H
POP OX
POP AX
LOOP AG
RET
ENDP

D HEX2 PROC NEAR


PUSH ex
HOV CL, 04H ; Load rotate count
MOV CH, 02 H ; Load digit count
SAC: ROL AX , CL ; rotate digits
PUSH AX save contents of AX
AND AL, OfH (Convert
CMP AL,9 number
JBE Add30 to
ADD AL, 37H its
J MP DISP ASCII
Add30:
ADD AL,JOH equiva lent)

Copyrighted material
Microprocessors and Interfacing 4 111 AsHmbly Langwoge Programs
DISP: MOV AH , 02H
MDV DL,AL ; (Displ ay the
!NT 21H ; number)
PDP AX ; restore contents of AX
DEC CH : decrement digi t count
JNZ BAC ; if not zero repea t
PDP ex
RET
ENOl-
END

Program 20 : Program to search a given byte In the string


MODEL SMALL
. DATA
M1 DB 10, 13, 'ENTER THE STRING : $ '
M2 DB 10, 13, ' GIVEN BYTE IS NOT HI T HE STRING $'
CHAR DB 0
ADDR DB 0
BUFF DB 80
DB 0
DB 80 OUP (0)
.CODE
START MOV AX, @data ; I I nitialise
MOV OS, AX ; data segment. )
MOV AH, 09H : Display messagel
MOV OX, OFFSET M1
!NT 2 1H
MOV AH, OAH ; Input the st ring
LEA DX, BUFF
!NT 21H
MOV AH, 0 1 ; [ Read character
INT 21H ; from keyboard]
MOV CHAR,AL ; save character
MOV CH , OOH
NOV CL, BUFF+l ; Take character count i n ex
LEA BX, BUFF+2
~!OV DI , OOH
BACK MOV DL , ( BX+DI ) ; poi nt to the f i r st character
CNP DL, CHAR ; compare str ing character with
; given character
JZ NEXT : if match occurs go to next
I NC OI
DEC CX ; Decrement character counter
JNZ BACK : If not 0 , r epeat
MOV AH, 09H : (Di splay message M2
LEA DX , M2 ; on the
INT 21H ; monitor)

Copyrighted material
Microprocessors al\d lnteffaclng 4 -67 AoMmbly lianguege Programs
JMP LAST
NEXT : MOV ADDR, OI ; save rel ative address of the
; byte from the starting
; l ocation of the stri ng
LAST : MOV AH, 4CH ; ( Terminate and
!NT 21H ; exit to DOS I
END START

Program 21 : Program to find LCM of two 16-bit unsigned numbers


(Softcopy of this program, P24.asm is available at www.vtubooks.com)
lf we divide the first number by the second number and th~r~ is no rem,\in4c:r, then
the first number is the LCM. In case of remainder, it is necessary to add first number to it
to get the new first nu.mber. Afte.r addition we have to divide the new fi rst number by the
second number to check if the remai..ndcr is zero. [( remainder is not zero "gain add the
original first number to nt>w one and repeat the process.
For cxamplc, if two numbers arc 20 and 15 then we get LCM as foiJows :
20 + '15 = I Remainder 5 i.e. * 0
20 + 20 = 40 + 15 = 2 Remainder 10 i.e. *0
40 + 20 = 60 + 15 = 4 Remainder 0
LCM = 60
NANE LCH
PAGE 60,80
TITLE program to find LCM of t wo 16- bit unsigned numbecs
. MODEL SMALL
. STACK 64
. DATA
NUMBERS ow 0020, 0015
LCH OW 2 DUP (?)
. CODE
START : MOV AX, @DATA (Initialize
t10V DS,AX da ta segment]
MOV OX, 0
MOV AX, NUMBERS Ge t t he first number
I~V BX, NUNBERS+2 Get the second number
BAt.h : PUSH AX { Save the
PUSH OX first number)
OIV BX Divide if by second number
CMF OX , 0 Check if remainder 0
JE EXIT : if remainder & 0 then e xi t
POP OX
POP AX
ADD AX,t\UMBERS First number + first number
JNC SKJP
I NC OX

Copyrighted material
Microprocessors and Interfacing 4. 68 Ass embly Language Progrems

SKIP: J MP BACK ; Go to BACK


EXIT : POP LCM+2 ; I Get
POP LCM ; the LCM
l-10V AH,4CH ; I Terminate i!.nd
. INT 21H ; Exit to DOS I
END START

Program 22 : Program to find HCF of two numbers.


(Softcopy of this program, P2S.asm is available at www.vtubooks.com)
To find the HCF of two numbers we have to divide greater number by smaller
number, i( remainder is zero, divisor is a HCF. If remainder is not zero, remainder
becomes new divisor and previous divisor becomes dividend and this process is re~atcd
until we get remainder 0.
For example, if numbers are 20 and 15 we can find HCF as follows :

20 + 15 = I Remainder 5 i.e. - 0
15 + 5 = 3 Remainder 0
HCF = 5
.model small
. stack 100
.data
CR EQU 0AH
LF EQU ODH
MES 1
MES 2- DB
DB
CR,LF, 'ENTER 4-0IGIT FIRST HEX NO ', CR, LF, '$ '
CR,LF, 'ENTER 4-0IGIT SECOND HEX NO ' ,CR,LF, ' $ '
MES 3 DB CR,LF, 'INPUT IS INVALID BCD S'
MES_4 DB CR,LF, ' THE HCF IS : $'
MULTI DW 1,10,100 ,1000
RESULT ow (00)
DIVISOR ow (00)
DIVIDEND ow (00)
INPl DB OS
DB 00
DB 05 DUP (O)
INP2 DB 05
DB 00
DB 05 DUP(O)
.code
MAIN: MOV AX,@data ; Initia lise
MOV OS,AX ; data segment
MOV AH,09H Di spl ay
MOV DX,OFFSET MES_l ME$ 1
!NT 21H on video screen
LEA OX, INPl ; Get the
MOV AH,OAH Firsc

Copyrighted material
Microprocessors and Interfacing 469 A...mbly Lllnguqe Piogt111
!NT 21H ; HEX number
MOV AH, 09H ; Display
MOV OX,OffSET MES 2 ; MES 2
!NT 21H ; on video screen l
LEA OX, INP2 ; (Get the
MOV AH,"OAH ; Second
!NT 21H ; HEX number
MOV CH, 02H ; Initialize buffer counter
LEA BX , INPl ; Get the address of buffer
AGAIN : INC BX ; ( Ad j ust buffer
INC BX ; pointer )
XOR OI , OI ; Clear pointer
~!OV CL, 04 ; Initialize counter for digits
BACK : MOV AL, [BX+OI) ; Get the digit from buffer
CMP AL,39H [ Convert
JG NEXT the ASCII
SUB AL,30H code of
JMP SKIP the actual number
NEXT : SUB AL,37H and store it in the same
SKI P : t<!QV ( SX+OI),AL position l
INC DI Increment pointer
DEC CL Decrement diqit counter
JNZ BACK If not zero qoto BACK
LEA BX, INP2 Point to second buffe r
DEC CH Decrement buffer coun ter
JNZ AGAIN ; 1f not zero go to AGAIN
MOV CL, 4 ; In itia li ze r otation counter
LEA BX, INPl ; Po1nt to first buffer
INC BX ; (Adjust buffer
INC BX ; pointer 1
MOV AH, [BX+O) ; [Forms the
SAL AH , CL ; packed BCD
AND AH , OfOH ; Hiqher
MOV AL, [BX+ l) ; Byte J
OR AH, AL
MOV AL, (8X+2 ) : (Forms the
SAL AL, CL ; packed BCD
AND AL, OFOH ; LOwer
MOV OH, (BX+3) ; byte )
OR AL. OH
r1ov RESULT, AX : Save packed wor d as a RESULT
MOV CL, 4 ; Initialize rotation counter
LEA BX, INP2 ; Point to second buffer
INC BX : ( Adjust buffer
I NC BX pointer l
MOV AH , (BX+O) ; (Forms t.he
SAL AH,CL : packed BCD
AND AH, OFOH ; Hi9her
MOV AL, (BX+l) ; byte)
OR AH, AL
MOV AL, (8X+2) ; I forms the

Copyrighted material
_,,Mj~~~~ '"~ lntorf~cing Assembly Language Programs

SAL AL, CL ; packed BCD


AND AL, OFOH ; lower
M()V DH, I BX+3) byte J
OR AL, DH
CMP AX, RESULT ; Compare two packed words
JNC tiiEXTl
MOV DIVISOR , AX ; A.$Sign smaller wo rd D.s a
MOV CX, RESULT ; DIVISOR ond
MOV OIVIDEND,CX ; greater word as a DIVIDEND
JMP SKIPl
NEXTl ' 1-'.0V DIV I DEND, AX ; Assign greater word as a
HOV CX,RESULT ; DIVIDEND and
MOV DIVISOR , CX : smaller word as a DIVISOR
SKI P! ' MOV ox, o
MOV AX, DIVIDEND
OI V DIVISOR ; Perform division
CMP DX, O Check remainder fo r zero
MOV CX, DIVISOR
MOV DIVISOR, DX Load remainder as a new
DIVISOR
NOV DIVIDEND, CX Load previous DIVISOR as a
new DIVIDEND
JNZ SKIPl If remainder is not zero
goto SKIP!
MOV AH, 09H (Display
LEA DX, MES - 4 l-IES 4
INT 21H on video screen )
ADO CL, 30H (Display the DIVISOR
tIOV DL, CL ..then remainder
f.10V AH, 02H is zer o
I NT 21H , i .e . HCF J
MOV AH , 4CH (Term inate and
!NT 21H ; Exit to DOS
EN D MA IN
END

Program 23 : Program to find LCM of two given numbers.


(Softcopy of this program, P26.asm is available at W\\"ov.vtubooks.com)

There is a one more method to find LCM of two number if HCF is known. We can
find L.CM a:o: (cdlows :

LCM = (numberl x number 21 + HCF

11l i~
progr.tm accepts two four digil numbers from keyboard, finds HCF ftrst and
us ing above equ.:.tion it then finds LCM ol the hvo numbers.

Copyrighted material
I
M lcroproceuora and Interfacing 4 . 71

.model small
.stac k 100
.dlU.a
CR &OU OAH
LF EOU ODII
~s
M5_2- I 08
08
CR,Lf,'ENTER 4-0IGIT FIRST HEX NO' , CR,LF, ' S'
CR, LF,' Et-iTER 4 - DIGIT SECOND HEX NO' , CR, LF, '$'
MES .3 DB CR, LF, ' INPu:' IS INVALID BCD $ '
HES 4 DB CR, LF, ''THE HCF IS : $ '
HVLT! OW 1, 10 , 100 , 1000
RESULT D'rl {00)
DIVISOR ow {00)
DIVIDEND OW {00 )

INPl DB 05
DB 00
DB 05 DUP(O)
INP2 DB 05
DB 00
DB 05 DUPIOI
. code
MJ.tN: HOV 1\X,@data ;
HOV OS, AX : dat aeqment. J
HOV AH, 09H ; ( Display
HOV OX, OFFSET O<ES_ l l!o'.!S_l
!NT 2 1H on v1deo screen J
LEA OX , I NPI I Get the
MOV AH, OAH First
!NT 21H HEX number
MOV AH , 09H Display
MOV OX, OFFSET MES 2 ~ es 2
!NT 21H on video screen J
LEA OX, 1NP2 [ Get the
HOV AH, OAH Second
!NT 21M ; HEX number
HOV CH,02H : Initialize butter counte r
LEA BX, INPl : Get the butter pointer
AGAIN: INC BX .
( Ad)USt buff er
INC BX : pointer )
XOR 01,01 ; Clear pointer
HOV CL,04 ; Initi Uze counter fo r digits
BACK: HOV AL, (BX+DI] : Get the di9it ft om bu ffe r
CHP AL,39H : ( Convert
JG N&XT ; the ASCII

Copynghted materio1l
MlcroproceMora and Interfacing 4-72 Asoembly Language Programs

SUB AL, 30H code


Jt~P SKIP ; the actUal number
NEXT: SUB AL, 37H ; and s t ore ic in the same
SKIP : MOV {BX+DI I . AL position I
INC DI ; I ncreme nt poi n ter
DEC CL ; Decrement digit counter
JNZ BACK ; If not zero go to BACK
LEA SX , INP2 ; Point to second buffer
OEC CH ; Decrement buffer counter
JNZ AGAIN ; If not -z.ero go to AGAIN
MOV CL, 4 Initialize rotation counter
LEA BX , IN PI ; Point to first buffer
INC BX ; r Adj ust buf fe r
INC BX ; poi nter I
MOV AH, {BX+O I ; f'orms the
SAL AH, CL ; packed BCD
AND AH, OFOH ; Higher
MOV 1\L, {BX+l l ; Byte I
OR AH,AL ;
MOV AL, [BX+2 1 ; ( forms the
SAL AL,CL ; packed BCD
AND AL,OFOH ; Lower
MOV DH, [BX+31 byte l
OR AL, OH
MOV RESULT,AX Save
RESULT
t he packed word
HOV CL,4 Ini tialize rotation counter
LEA BX, INP2 Point to second buffer
I NC BX Adj ust buffer
INC BX ; pointer I
MOV AH, (BX+O) Forms the
SAL AH,CL ; packed BCD
AND AH, OFOH ; Higher
MOV AL, ( BX+l) byte I
OR AH,AL
10V AL, (SX+21 ; Forms the
SAL AL, CL ; packed BCD
AND AL, OFOH ; lower
MOV DH , (BX+31 ; byte I
OR AL,OH
MOV RESULTl, AX ;
;
Save second pac k word
a RESULT2

CMP AX , RESULT ; Compare t wo packed words
JNC NEXT!

Copyrighted material
Microprocessors and lnterfllclng 4-73

MOV DIVISOR, AX ; Assign smaller word as a


MOV CX, RESULT DIVISOR and
MOV O!V! OEND, CX ; greater word as a DIVI DEND
J MP SK!Pl
NEXT!:
MOV OIVIbEND,AX Assi9n greater word as a
MOV CX, RESULT OIVIOENO and
MOV DI VISOR, ex smaller word as a DIVISOR
SKIP! : MOV OX , 0
r<OV AX, DIVIDEND
D! V DIVISOR Perform division
CI1P OX, 0 Check remainder for zero
MOV e x , DIVISOR
110V DIVISOR, OX Load remainder as a new
DIVISOR
110V DIVIDEND, C X Load p r evious DIVISOR a s et
new DIVI DEND
JNZ SKIPl If r emainder is not zero
; goto SKlPl
110V AH , 09H ( Display
LEA OX , OFFSET MES 3 ; MES 3
INT 21H ; on video screen J
Number! x Number2 = HCF x LCM . . LCM (Number! x Number2) /HCF
MOV Her, ex
~,OVOX, 0
MOV AX, RESULT ; Get the fi r st number
MUL RESULT! ; Multiply number! and number2
OIV HC F ; Divide multiplication by HCF
MOV CL, q ; Initi a li ze rotation counter
MOV BX, AX ; Save the quotient (LCM)
AND ~.H, OF OH ; ( Display the LCM
SAR AH, CL ; on the v ideo screen )
CMP AH, 09H
JNC SKIP2
ADD AH, 30H
J MP NEXT2
SK ! P2 : ADD AH , 37H
NEXT2: MOV DL, A.H
MOV AH, 02H
! NT 21H
MOV AX, BX
AND AH, OFH
CMP AH, 09H
J NC SKIP3

Copyrighted material
Microprocessors and Interfacing 4,. 74 Assembly Language Programs

ADD AH , JOH
J MP NEXTJ
SKIPJ: ADD AH , J7H
NEXT3 : MOV OL, AH
NOV AH, 02H
INT 2 1H
MOV AX,BX
AND AL, OFOH
SAR AL, CL
CMP AL, 09H
JNC SKIP4
ADD AL,30H
JMP NEXT4
SKI P4: ADD AL, 37H
NEXT4: MOV OL ,AL
MOV AH,02H
! NT 21 H
MOV AX,BX
AND AL, OFH
CHP A.L,09H
JNC SKIP5
ADD AL , 30H
JHP NEXT5
SKI P5 : ADD AL,37 H
NEXT5 : MOV OL,AL
MOV AH, 02H
!NT 21H
MOV AH, 4CH ( Terminate and
!NT 21H Exi t to DOS I
END MAIN
END

DOD

Copyrighted material
8086 System Configuration

5.1 Introduction
Unlike 8085. 8086 and 8088 can be operated in two modes : Minimum mode and
Maximum mode. ln this chapter we study the topics rcl~ted to Minimum mode and
Maximum mode operation of 8086. Topics include clock generation, bus buffering, bus
latching. timings. minimum mode operation <~nd maximum mode operation. let us begin
w ith signal description of 8086.

5.2 Signal Description of 8086


In order to implement many situations in the microcomputer system the 8086 and 8088
has been designed to work in two operating modes :
1. Minimurri Mod!!
2. Maximum Mode
The minimum mode is ust-d for a sm;all !'ystcms with a single processor and
maxi mum mod~ is for medium ~iZC" to large systems, which orten include tv~,o or more
pr()('('ssors. Fig. 5.1 s hows tht> pin diagram ol 8086 and 8088 in minimurn as well as
maximum mode. As a close comparison reveals, there is no much difference between two
microprocessors both are packaged in 40-pin dual-inHne package (DIPs). A~ mentioned
in section 2.1, the 8086 is a 16-bil microprocessor with a 16-bit data bus, and the 8088 is a
16-bit microprocessor \o\'i.th an 8-bit data bus. The pin-<>ut shows, the 8086 has pin
connections A00-AD 1 ~ and the 8088 has pin connections AD0AO,. There is one more
mil\or diJfe:rcncc in OJ'\C of the control signals. Th(' 8086 has an M/ 10 pin, a.nd the 8088 has
an 10 / M pin. n,e only hardware difference otppcars on pin 34 of both chips : on the 8086
it is a BHE/~ pin, while on the 8068 it is a SS, pin.
The 8086 signats can be categorised in three groups.
Signals having common functions in both minimum and maximum modes.
Signals having special func:tions fo r minimum mode.
Signals having s-pedal functions (or maximum mod('.

(5 1)

Copyrighted material
Microprocessors and Interfacing 5-2 8086 System Configuration

...,
,..... .....,
(Mift

00<0

..."". 2
O

,." ..... ....


Vee
......
GNO
2
O

",. ...
vee

......"""..
3
A.,fS,
,." ....... ...... 3
,.
31
A.,tJSl

......
14. 111S,

...
5

, .. ....... .....
,. "''A

....., ...,
As, S$o !HIGH)
" ' "
"" " t.tN..iii
. 33 . ..;;x
.....,
-
(M>n (Mn

...
loD,
'oo .... "
"
Ri)
RQIG'io ()tOlD)

...... 10 "
"
Ri)

.....
HOW <R016Tot

...
CPU
loD, II 30
,. RCW'io t><L""> II """ ,.
30 cHOtGT,,

.., ",,
..
<OCK

s,
l~ih
..,.., ,,.." ,.
;;;;; (LOCK)
loD,
""
..

(J4i:i)
tDTifi)
,, ""'
OT~
,." 00<
<$,1
(il )

...""'
AD,
"
"
"
" 00,
t6ENI
(ALE)
(iifTAJ
.......


17
,. ....
,. .;:;n
<S,i
t<>O,I
(0$,1
INTR
17
18 "
23
OS,
TEST INTR
23 TUT
CLK

ONO
19
20 ,," Rt;ADY
RESET
CUt
GHO ,." ,," REAOV
RESET

{a) Pin d iagram of 8086 (b) Pin dlogram ol8088

Fig. 5.1

5.2.1 Signals with Common Functions in Both Modes


1. AD 15AD0 : Ac-ts as nddrcss bus during the first pa rt of machine cycle and data bus
for the remaining part of the machine cycle.
2. A 11/S6A 16/S3 : During the first part of machine cycle these arc used to output
upper 4-~bi ts of address. During remaining part of the machine cycle these are used
to output status~ which indicates the type of operation to be performed in that
cycle. S, and 54 indicate the segment register being used as follows :
s. s, R~later

0 0 es
0 1 ss
1 0 CS or none
1 1 OS

55 gives the current setting of the interrupt flag (IF) and 56 is always zero.
3. BHEIS7 : BHE (Bus High Enable) : Low on this pin during firs! part of the
machine cycle~ indicates that at least one byte of the current transfer is to be made

Copyrighted material
Microprocessors and Interfacing 5-3 8086 System Configuration

on higher order byte ADwAD~ othen..,ise the transfer is made on lower order byte
AD,.-AD..
BHE Ao Data acceaa.H
0 0 Word
0 1 Upper byte from Odd addrH*

1 0 Lowet byte from even address

1 1 None

Status S, is output during the later part of the machine cycle, but, presently, S, has
not been as..\igned a meaning.
4. NMI : It is a p05itive edge triggered nonmaskablc interrupt request.
5. INTR : ft is a level triggered maskable interrupt request. It js sampled during the
last dock cycle of each instruction to determine if the processor should enter into
an interrupt scrvke routine.
6. CLK : 8086 requires clock signal (with 33 % duty cycle) from some external, crystal
controlled generator to synchronize internal oper01tions. Clock frequency depends
on the version of 8086.
.
Procusor Required clock signal

80~ 5MHZ
8086-2 8MHZ
80861 10 MHZ

7. RESET : lt dears PSW, lP, OS, SS, ES, and the instruction queue. It then sets CS to
FFFFH. This signal must be high for at least 4 clock cycles. 1'\lh<."' RFSET is
removed, 8086 will fetch its next ir'lstruction fronl physical address FFFFOH.
8. READY : lf this signal is low the 8086 enters into wait stt~te . This signal is used
primarily to synchronize slower peripherals with the microprocessor.
9. TEST !Input) : This signal is only used by the WAIT instruction. The 8086 enters
into a wait state after exect1tio n of the WAIT instruction until a LOW signill on the
TEST pin. TEST signal is synchror,i7Ald inte n,nlly durh\g C('~ Ch dock cyde on the
leading edge of the dock cycle.
10. RD (Output) : RD ls low whenever the 8086 is reading data from memory or an
T/ 0 device.
11. MN / MX Clnput) : The 8086 can be configured in either rrummum mode or
maximum mode ushlg this pin. This pin is lied high for minimum mode.

Copyrighted material
Microprocessors and Interfacing 5-4 8086 System Configuration

5.2.2 Signal Defi nitions (24 to 31) for Minimum Mode


INTA (Interrupt Acknowledge) Output : This indicates recognition of an interrupt
request It COJ\Sists of two neg-Mive going pulses in two consecutive bus cyck-s. ll1e fi rst
pulse inform.:; t! ~ i!llcdacc th<'lt its request ha.s been recognized and upon receipt ol the
second pulse, the interfae<> is to send the interrupt type to the processor over the data bus.
ALE (Address Latch Enable) Output : This signal is p rovided by 8086 to demultiplex
the ADrtA D 15 into A0..A15 and 0 0"'0 15 usi1'S external latches.

DEN (Data Enable) Output : This s ignal in(onns the transceivers that the CPU is ready
to SC1'd or receive data.
OT/R (Data transmit/Receive) Output : 1'his signal is used to control data Oow
direction. High on this pin indica tes that the 8086 is tro1nsmitting the data and low
indic<ttt..-,. that the 8086 is receiving the data.
MilO Output : It is used to distinguish memory dotn transfer, (M / 10 G HIGH) and 1/0
dam transfer (M/10 = LOW).

WR : Write Output : WR is low whenever the 8086 is writing data into memory or an
l/0 device.
HOLD input, HLOA Output : A HIGH on HOLD pin indicates that another master
(DMA) is requesting to take ovN the system bus. On receiving HOLD s ignal p rocessor
outputs HLDA signal HlCH as an acknowledgment. At the same tim(', pnxC'SSOr tristates
the system bus. A low on HOLD givt.>s the system bus control back to the processor.
ProcesSt')r then outputs low signal on HLDA.

5.2.3 Signal Definitions (24 to 31) for Maximum Mode


1. QS 1, QS0 (output) : These two output s ignals reflect the s ta tus o( the ins truction
queue. This status indicates the activity in the queue during the previous clock
cycle.
os, os, Status

0 0 No operation (queue is Idle)

0 1 First byte of an opcode

1 0 Queue is empty
I 1 1 Subsequent byte of an opc:ode
I
I 2. 5 2 , 5 1, 5 0 (output) : These three status s ignals indicate the type of transfer to be
take place d uring the current bus cycle.
II
I

Copyrighted material
Microprocessors and Interfacing 5 5 8086 System Configuration

s, s, s, Machine cycle
-s. -s, -s, Maehlne cycle

0 0 0 lntO<rupt ~ I 0 0 l'lstruclion fetcta

0 0 1 V0 ReOCI I 0 I Memory read

0 1 0 110 w.tt. I I 0 Mernocy wrile


0 1 1 Holt I I I Inactive-Passive
. . .
J. LOCK : Tius sagn-11 and!C.lt"" th.lt on onstruchon wath a LOCK prefix IS lx>ing
. .
executed and the bus ;. not to be usa! by another processor.
4. RQ/CT 1 ~d RQICT1 : In the ""''imum mode, HOLD and HLDA pins are
<q>lad by RQ (Bus Nqu<St)/ CT1 (Bus Cr.nt). nd RQ/ GT1 sign.1ls. By using bus
request Sign.ll nother m.lSter can r<qUl'St for the system bus and processor
communicate th.lt tlw t\'quest lS gnntcd to the rcque-.tiog master by u..o;ing bm
grant sigN!. Both signab are mo;.r \Cq)l the RQ/ CT0 has higher priority than
RQ/ CT1

5.3 Physical Memory Organisation


Mo<t of the memory
IC~ are b)rte oriented i.e.
Oa!abus
(Do-ll,,J
o,.Ho. o,H o0 each memory location
c<\n stor<' only one bytt>
-SHE of data. The 8086 is a
cs .... cs 16-bit microprocessor, it
Bank 1 BankO can trallSfcr 16-bit data.
(512 byiOI) (512 bj1ol) So in addition to byte.
Addre:u word (16-bit) h.,g to be
bus Ao i?A 10 A, i Ao$
s tored in the memorY.
(Odd addreued memory b9tlk) (E\Itn oddre11ecl meiTIOI)' benk) Thi.s is slt)n.'Cl by using
two consecutive memory
fig. 5.2 Memory Interfacing toc.,tions, one for le.:a~t
si ~;nificant byt~ and
other for most si~;rtiflc.u-'11 b yt\!. The iu..ldn..~ of word ls the address o( )('ast s ignificant byte.
To implement this. the tontire memory Is dlvldl'Ci lnto two memory banks : banko and
bank,. Fig. 5.2 shows tho intorfndng d1Agr3m to th"'"' memory banks. Ban~ is selected
only when Ao is zcru and n..,nk 1 is ~koc:ttxl only when OHE i-. 1.cm . A.,, i.:; zert, for all cvt~l
addn.-'5.._...-s. So Ban."'
Is t~u.ll l y rcfcrn.-d .1s even addr~jJed memory bank. UHE i:.3. lL~-d to
access higher otdt.'f memory banlo., rderrtod hJ il:J odd addrttsed memory b.,nk.
Togclh-..or BHE .mel Ao tl'll the intl"''f.Kc how d-. d.1ta applaro: on bus. Four J>O!bible
rombinatiQn:, arc shown in tht- to1b~.

Co 1Q edIT' ale a
Microprocessors and Interlacing 5 -6 8086 System Configuration

No. Operation -BHE Ao Data Lines Used


1. Read/Write a byte at an even address 1 0 0, Do
2. ReactJWrlte a byte at an odd address 0 , D1s Oa

3. Read/Write a word at an even address 0 0 o,5. Do


4. Rea<i!Wrlte a word at an Odd address 0 1 D1sD0 In first opera.tiOn byte
from odd bank is transferred.
1 0
..,.,;.,
DrOo In sf)C(N')(I operatkln
byte from eve~ bank is
;,;,
Note : To access odd addressed word two bus cycles are roquired.
Every microprocessor based system has a memory system. Almost all systems contain
two basic typos of memory, read-only memory (ROM) and random access memory (RAM)
or read/ write tnemory. Read only memory contains system soltware and permanent
sy~tem da~ such a s lookup tables, while Random Access Memory contains temporary data
and application sofh-vare. ROM~/ PROMs/EPROMs are mapped to cover the CPU's reset .
address. s ince these are .,on-vo1atil~.?. When the 8086 is re.~t. the next ln.struction is fetched
fl'()m memory location FFFFOH. So in the 8086 systems, the location FFFFOH mus t be ROM
location.
The Fig. 5.3 shows memory map for 8086. Certain locations in 1 Mbyte memory are
reserved and some a re dedicated for s pecific CPU operations. t...ocations from FFFFOH to
1M~s

FFFFFH
FFfFOH
"
~.

0
1

Fl'FFEH} -
FfFFCH
I
I
Ft:f:rnH 0
FFFF9H FFFFN<}
FfFF8H l $ byiH
FFFF7H 0
FfFF6H Declicfltecl
FFFFSK FfFF.tH
FFFF3H FfFF1H
FFFF1 H 0 FFFFOH
0
0
0
0
003FFH OO>FH
OC13F[)Oj 0 OOOFCH
0
0
0
0
ooomo
000100i 0

0
0
0001EH}
000700
........
128
1
b'Jies
0001510
000131"1
0

0
00014H

00011 H 00012t<
OOOUIH }
0

0000010
0
"""""""'
00000H
Odd Bat*
0
Evtn Bet*
"""""
OOOOOH

Fig. 5.3 Mitmory map for 8086

Copyrighted material
Mlcroprocenora end lnterfaci"ll 5 7 8086 Syotem Configuration

FFFFSH are dedicated to the initiali'!ation procedure of the 8086, while locations FFFF6H to
FFFFBH arc dedicated to the initialiMtion prcxedure of the 8089 input/output processor.
Locations OOOOOH to 00013H are dedicahld to store the v~tor addresses of the dedicated
interrupts. The dedicated locations are used for processing of specific system initialis.1tion,
inte_rrupt and reset hmction.
Intel has also reserved several locations for future hardware and software products.
Locations from OOOJ4H to 0007FH and locations from FFFFCH to FFFFFH are reserved
IOL"ations. nw locntions from OOOOOH to 003FFH are u.o;.ed for interrupt vector table (1V1).
The interrupt ve<:tor t:.ble provides the starting location/address of the interrupt service
routh\12' fo r the interrupt s upported by 8086. The detail description of interrupt vector table
i$ given i.n sections 8.2 and 8.3.

5.4 110 Addressing Capability


The 8086 can generate 16-bit of 1/0 address. Thus it can address upto 64 kbyte l/0
locations or 32 K word 1/0 location.<. The 16-bit 1/0 address appears on A 0 to A 1; address
lines; A 16 to A19 lines are at logic 0 during the 1/0 operations. The 16-bit OX register is
uSt--'<1 as 16--bit l/0 address pointer to address upto 64 K devices in in-direct addressing
mode. The J/0 in.cctructlons with direct addressing mode can directly address one or t\vo
of the 256 1/0 byte locations in page 0 of the l/0 address space. See Fig. 5.4.

7 0
FFFFH
FFFEH

OOFFH 64K
OOFEH liO space
Reserved

OOF8H
PagoO
OOF7H "'

0001H
OOOOH
1 - l
t==:::j
Fig. 5.4 l/0 map for 8086

Copyrighted material
Microprocessors and Interfacing 58 8086 System Configuration

1/0 ports arc addr6Scd in the same manner as memory locations. Even addressed
bytes are transferrt:'d on the D;-00 bus lines and odd addressed bytes on Dw 0 8. Care
must be taken to assure that e~ch res:bt~r w ithin an 8-bit peripheral located on the lower
portion of tht- bus be addressed as tven. In the 1/0 space. Intel has reserved OOF8H to
OOFP locations.

5.5 General 8086 System Bus Structure and Operation


The 8086 has a commOI'l address and data bus. TM address and data arc time
muJtiplcxed, i.c. a<'rlrc-ss and data appear on common bus a t different timi.:' intervals. Titus
bus is commonly known as multiplexed address and d..1ta bus. The multiplexed address
:.nd data bus provides the m0$1 efficumt use of pins on the prc:w:~r while permitting the
tLW of a standard 40-l~ad p.>ckage. This multiplexed address and data bus has to be
domultiplcxed cxtom.tlly with the usc of latches and the ALE signal provided by 8086, as
shown in Fig. 5.5.

ALE STB

Adctress
A00 Lotch bus
AOro,"- ~ (2)

Data
~ 1 ransoetver bus
(2)

DEN
-OE
OT/R T

Fig. 5.5 Oemultiplexing of address and data bus


Each prOC<.>Ssor b us cycle consists o f at least four clock cycles. These are referred to as
T1, T 2, T~ and T,. Refer Fig. 5.5. Dmin~ T1, proct'SSOr sends address on the addr..s bus
<lnd ~'cli va h..-s
ALE sigrul. T1w ALE ::tjg;nal is uSt-d tlctiv.lt(" latches and thus to l1t'=h the
(lddress. 1be data transfer occurs Ol\ lht? bu~ during T, and T4. The tim~ int('r val T 2 is uSt..~
primarily fo r changjng the dirt"Ction of the bus during t'C<ld operations. Ready signal is
s.amplt>d during T 3. TI\e lOiower p!!riphcral devices use this signa l to indicate that the
device is not ready to send th~ dt:'Sin..>d data within specified time. In the event that a
''NOT Re;,dyH indiC<1tion is giv(n b\ the ~lmvcr I"'Cripht!r.ll d~..vk~.-. 'WAIT' stat<'s (Tw> a r.._~
illscrtcd betwt-'1..'1) T2 and T3 to g iv-.: enough ,1\.'Cl-"SS time for the siO\\'er peripheral devi\ie.

Copyrighted material 1
Ml<:roproc:esso~ a.rid lnterflclog 8088 Syitem Configuration

Each WAIT s tate is of the :1<1 mc durarion"" n clock cycle. During a WAIT s tate, the signals
on the bus..'S remain the s.1mc as thl'Y were at the start of the WAIT state. (( the Ready
input is made high during wait s tate, then ofter WAIT state the 8086 wiU go on with the
regular T, of tlw! machioo cycle. Howll"cr, if the 8086 Ready input is still low at the end of
a WAIT state, then the 8066 will inseft another WAIT state. The 8086 will continue
insefting WAIT states until the Ready input is made high again.
TN! status bib S,. S1 and S, arc uJ<d, in ma.>dmum mode, by the bus controller to
identify the type of bus transaction according to tho table given below.
-s, -s, -s,
--
s, Mochlne cyclo s, s. lbd\lne cyclo

0 0 0 ........,. "'*""""<'g I 0 0

0 0 1 110- I 0 1 Meuoy read

-
0 1 0 IIOWo'lt I I 0 Memory Wl'ke

0 1 1 I 1 I ~PassiYe

Status bib S, through S. are multipl<!xed with high-onder address bib and the BHE
signal. Tl1ese bib are also demultlplexed using latch and the ALE signal during T 1
Therefore, the status bits S, through S. arc valid during T2 through T4 Status bits S, and
S, indicate which segment register was used lor this bus cycle in forming the address,
aceo<ding to the following Table.

s, s, Char-otico
0 0 AJ-ooe OliO (t><lnl _ . )
0 I SIOck
I 0 Cod<> 01 None

I I Oata

Out of rcmai.nJ.ng stat\ts bit'l, S, ~ a rcOcclion o lhc Interrupt enable bit o the flag
register, $6 is always 0 and S, is a Spt'IN StatuS bit.
If a systom is large enough to "''''<!
dllta bus buffers, then the 8086 OT/R signal
connech.d tn ~~~ bufferS wUI 8Ct lhcm for in~during a read operation or set them for
output durong o -write op<rotion. The I1Ql6 DEN slgnol will enable the buffers at the
appropriat< time in the m.'lchlne cycle, "" hown In the Fig. 5.6.

Co 1Q edIT' ale a
Microprocessors an~ Interfacing 5 - 10 8086 System Configuratton
r - -Momo<y .... cycle- r - - - -Momo<ywrite cycle -j
I r, I r, I r, p,.,l r, I r, I r, I r, p,.,l r, I
CLK
Goes inactive in the &tate
just priQt to T4

=;'..___.~~~.tlhWJ'//JhWJ~
ALE

AOORI
;;j \
STATUS

AOORI Datil OUI


DATA

Ready

orlfi

Fig. 5.6 Basic system timing


.:-F-

,.., 8086 System and Timings


5.6 Minimum Mode
5.6 .1 Minimum Mixle Configuration
Latching
Fig. 5.7 shows the typical minimum mode configuration. As shown in the figure~
AD0 -AD 1, A16 /S,A 19/S., and BHE/S, signals are multiplexed. These signals are
demultiplexed by external latches and ALE signal generated by the p""""""r. This is
accomplished by using three latch !Cs (Intel 8282/82113), two of them are required for a
li>-bit addrt.'$.< and three are needed il a full 2<H>it address is used. In case of 8088, only
twv external latches are required. One for demulliplexing AD0-AD7 and other for
demultiplexing A 16/S, and AD 19 /S6. Fig. 5.8 shows the internal block diagram of
8".lj2/82ll3 latches. The 8282 provides noninverting outputs while the 8283 version inverts
the input data. In addition to their demultirlexing function, these chips also buffer the
.h.i dn-ss lines, providing increased output c:riving capability. The output low !.e vel is
"f"'O:iiied as 0.45 V maximum with a sink cuirent of 32 rnA maximum. The high ltvel is
Sf"-'Cifkod as 2.4 V minimum while supplying a 5 mA maximum hjgh level load cuneut.

Copyrighted material
Microprocessors and Interfacing 5 -11
''".6 t"
11086 'System Configuration

ro~ Vee
I
.
+Vee \
'--
CO.K """'-"' .
.
R 8284A ALE STB
Clod< READY 8H
8Hf

-
82112
-Generator 1\ESET ...,
c
I-
RES
"r't6
> Address
Iateil
(3)
-
;>sus
ss

AD, ..."o OE
-----I
1 " -v
~
'
WAIT
I STATE
I 8086 CPU
I GENE.AATOR I
.r... . ta
L----I 8288
Transceiver ;>~
-DEN (lit (2)

DTIR T

(Optional fOf increased


-
Data bus drive)
wi6
..
""RD ..
COntrol
HOLD
><.OA
-a..s
.-...
INTR
._,
Fig. 5.7 Typlcal minimum mode configuration

8282

''

..

Fig. 5.8 Internal diagram of 8282 and 8283 Copyrighted material


.lt9M <
M icroprocessOrs a'nCIInterfacing . 5 - 12 8086 System Configuration
--

A"o ... i'--


Buffering
AD0
.,
A,
.,., . II a system indudcs several
AO,
AO,
...,
....."" .,
A>
8

-
~

Data Bus
interfaces then to increase current
sourcing/sinking C(lpaciti4."S it is
t
AD,
2
.,,
A.D. necessary to use drivers and

""'
oo;
A,

OE
8
6
= rcceive:rs (t'r ansceiver) for data bus
also. The Intel 8286 device is used to
DTIR T implement the transceive r block

... .. -
81H16 shown in Fig. 5.7 The 8286 contah'S
.,, 16 tristate elements, eight recl'ivers,
.,,.
ADo
.,.. .,.. =
and eight drivers. Therefore two
8286s are n.~ui red to service 16 data
.,,
A011

.,,
.,,.
1
.....,"" .... ==-.
a
2
a

} Data Bus
lines of 8086 . Fig. 5.9 shows the
detailed col'moctions of 8286.
-

-
AD, 6

oe
T
"' DT/ R signal is connected to the
T input, which controls the direction
of the data flow. When this signal is
..J
' low, receivers are t.'flabled, so that
Fig . 5:11 Connection details of 11286 8086 can read data from memory or
input device. To write data into
memory or output device, the 8086's DT/R signal goes high. Due to this drivers are
enabled to transfer data from 8086 to the memo!l.. or the output device. At the thne of
data trnnsfer, to enable output of transceiver its OE should be low. This is acromplisht.od
by connecting DEN signal of 8086 to the OE pin.of 8286, since DEN signal goes low when
CPU is ready to send or receive d:.ta.
;If.
Clock genenotor
.
The third comeonent, other than the processor that appears in Fig. 5.7 is an 8284 clock
generator. The 8284 clock generator does the following functions :
Clock generation
RESET synChronb..ation
. Jl
READY synchronization
Peripheral clock generation.
The Fig~ 5. ro'sl\'ows the internal logic diagram of 8284.
The top half of 'the logic diagram represents the clock and reset synchronization section
of the 8284 clock generator. As shown in the logic diagram, the crystal oscillator has two
inputs : x ; and x,. If a cryStal is atladled to x, and x, the oscillator generates a
square-wove signal at the same frequency u the crys'tal The output of oocilioto )s fed to
an _!>NO gate and also to an inverter buffer that provides the oscillator output sognal The
F/C signal selects one of the osciUator inputs. When F/C input is 1, the EFI input

Copyrighted material
Microprocessors. and lnletfacing 5 13 8084! System CQnfiguratio~

[}:>
R'ES

x,
0

CLK
0
I - RSET

XTAL
x, Oscilt.a!Ot
. osc

FJC
,..._ , -

J 3 .
SYNC SYNC
2

I
- PCU<

EFI ~

CSYNC
ROY 1
I I
AEN 1 -{:::
v .' CLK

J
ROY0

AEN
2
1'-
v
I ~
._ 0
CLK

FFI
a ::n- o
CU<

FF2
a - READY

ASYNC
[=L >
Fig. 5.10 The internal logic diagram of 8284 .
determines the frequency; otherwise oscillator determines the frequency. When EFI input is
used, CSYNC signal is u.""<' for multiple processo~ system synchronitation. If the internal
crystal oscillator is used, CSYNC signal is grounded. In both the cases the output clock
frequency is one third of the input frequency. llje CLK signal is also buffered before it
leaves the clock generator. As shown in tM Fig. 5.10, the output of the divide~by3 counter
generates the timing for ready synchronization, a signal for another couriter (divide-by-2),
and the CLK signal to the 8086/8088 microprooessors. The two ~ caScaded counters
(div ide--by.J and dividc--by2) provide the di vide~by--6 output at PCLK, which c.-.n be used
to provide clock input for peripherals. The address enable pins, J).EN 1 and AEN2 are
provided tu qualify the bus ready signals, R()Y 1 and ROY,, respectively.
The reset circuit of 8284 consists of a schmitt trigger buffer and' a' sing.lc D nipCiop
circuit The D flip-flop ensures that the timing n.'quirements of the 8086/8088 RESET input
are met. This circuit applies the RESET signal to the microprocessor.o.n. the negative edge
(1 to 0 transition) of each clock. The 8086/8088 microprocessors ~~ljlpl e RESET at the
positive edge (0 to 1 transition) of the docks; therefore, this drcuit meets the timing
requiremonts of the 8086/8088. ' .,

j.

Copyrighted material
Mle~nora and)nllltfaclng 5 14 8086 Syatem Configuration

The Fig. 5.11 shows the drcuit connection for 8284 clock generator. The RC circuit
provides a logic 0 to the RES input pin when power is first applied to the system. After a
short time, the RES lnput becomes a logic 1 because the capacitor charges toward + 5.0 V
through the regL<ter. A push button switch a llows the microprocessor to be reset by the
operator.

nmf-
x, X,

- EFI

F/ C RESET
a.K CU<

RESET

"'" READY READY


"'"
CSYNC
>SV ~-~

10t<i
-
>
8284
Clock Qeneqtor
8086
or
8086
w
' ~

RES

I :o,,F
. PCU< f--
ROY 1 ROY:

1 1
Fig. 5.-11 Interfacing of 8284 clock genenotor with 8086 or 8086
Other signals e
The statt1s on the M/10, RD, and WR lines decides the type of data transfer, as listed
in the Table 5.!.
MilO RD -WR Ope..Uon
0 0 1 110 read
0 1 0 110-
1 0 1 MonlOiy read

1 1 0 Mtmoty write

Table 5.1
HOLD and HLDA signals a re used to interface other bus masters like DMA controller.
Interrupt request (INTR) and interrupt acknowledge (INTA) are used to extend the
interrupt handling capacity of the 8086 with the help of interrupt controller.

Copyrighted material
1 tos 21e..
Mleroproceaaors and Interfacing 5 15 8088 System Configuration
5.6.2 Minimum Mode 8086 System
"
The Fig. 5.12 shows the typical minimum mode 8086 system. , He!'\', interfacing of
memory and 1/0 d evices arc shown with the ba.liic minimum mode 8086 configuration.

~hll ~~ fi d'J
of- ~
.h
I
>

~
~

I f
.rJ !
I
,.
Lr-
~ ~ ~
I (
.u

~

;>-'"
~
I ~
.
-!I w
~
,:
b
~ I
~

~I ~
,... - ,.
~-
~
.
----


EIS li : I
. '
'
: ~1!1"'
&
'
4 -
>ij1 ! II II
I II
ii l i
'j
.
'In lilt ~ ~ }11 ~~ I 'if-
dfJ
I ~ v .~.J
..
'

lf.....'if .
~ ~

{
1
!l :f n(
H
.
.
I ':~'
IJ r
,, .

Copyrighted material
Microprocessors and lnte~lng 5 - 16 8086. SY)Sl..., c;:onflguratlon

For interfacing memory module to 8086~ it is necessary to have odd ' and ,e;ven memory
banks. Tilis is implemented by uslng two EPROMs and two RAMs. Data lines 0 150 8 arc
connected to odd bank of EPROM and RAM, and data lines D,.-00 are connected to even
bank of EPROM and RAM. Address lines are connected to EPROM and RAM as per their
capacities. RD signal is connected to the output enable (OE) s ignals of EPROMs and
RAMs. WR signal is connected to WR signal of RAMs. Two separate decoders are used to
generate chip select signals for memory and 1/0 devices. These chip select signals are
logically ORed with either BHE .or A, to generate final chip select signals. For generating
final chip select s ignals for odd bank decoder outpuiS are logically ORed with BHE signal.
On the otl'ler hand to generate fin.1l chip select signals for even bank decoder outputs are
logically ORed with A0 signal.
The 16-bit 1/ 0 interface is s hown in the Fig. 5.12. RD and WR signals are connected to
the RD and WR signal~ of 1/0 device. Oatn lines 0 15-00 arc connected to the data lines of
1/0 device. The chip select signal for 1/0 device is generated using separate decoder
whose output is enabled on1y when M/10 signal is low.
'
5.6.3 Bus Timings lor Minimum Mode

5.6.3.1 Timings for Read and Wrila Operations


TI\e til'l"'ing diagrams of input and output transfers for 8086 minimum mode are shown
in the Fig. 5.13 (a) and (b) respectively.

11------- One Sus Cycle


T' , - - - \ T2 I T>,---\
CLK
/ Address. BHE OUT
, ,...__,,-....,X
A,s'S.-A,o's, _ __,)>---!cfc s~atus OUT )>-- -
and BHE.ts7 s==~
~ TAVDV !
AD1s-A00 ------<< 'I )>-----!CK'"::-
o.-,.'"'tN
- ..)>----- -
,----.."" Address OUT ;
ALE

RD

DTIR .......... _______


..........: .. ____
..............- - - " ' -
..
_______ .i--'---+-----'
_;_
TRLOV -i
_;_ :
.. ........
..........
.... ....
Fig. 5.13 (aj Input (read 01)41ratlon)

Copyrighted material
~!c;(pp~~rs.ancllnterfaclng 5-17 808fl System C<!nflguratlon

I' OneBusCyole ------1


1
T' r---\ T2 3
T,r ---\ T''r---\
CU< - - '
--,~C-... Address. BHE OUT
A,sfS.-A,,jS, _ _.... >>---<< I _x: StaiUO OUT
>>---
ond BHEIS,

10
AD -AD
0
------<<.-.s.ou~.._~;;;o;ata:-:o:ur=:r--""'>
:--- TDVWl-1
A L E - - -- . /

_,X..__ __;;.LOW
MilO _ _ .;__
_IIO.;_WR
_IT.;;;
E;..H
_IGH
.;__
_M"'EMORY
....;.._,R
w;-_ITE
....;...._.,x..___
WR --------!--- ~~------
TWLWH

OT/R

.. - - -.....
...............
..... ...
Fig. 5.13 (b) OU1pU1 (write operation)
These are explained in steps.
1. When processor is ready to initiate the bus cycle, it applies a pulse to ALE during
T1 Before the falling edge of ALE. the address, BHE, M/10, DEN and DT/R must
be stable i.e. DEN = high and DT/R 0 for input or DT / R a 1 lor outpul
2. At the trailing edge of ALE, ICs 74LS373 or 8282 latches the address.
3. During T2 the address signals are disabled and S,S, arc available on
AD 16/S,AD,. /S6 and BHE/S,. Also DEN is lowered to enable transceiver.
4. In case of input operation, RD is activated during T2 and A00 to A0 15 go in high
impedance preparing for input.
5. If memory or 1/ 0 interface can perform the transfer immediately; there a~ no wait
states and data is output on the bus during T3.
6. After the data is accepted by the processor, RO is raised high at the beginning of
T,.
7. Upon detecting this transition during T,, the memory or 1/0 device will disable its
data signals.
8. for an output operation, processor applies WR = 0 and then the data on the data
bus during T,.
9. InT., WR is raised high and data signals are disabled. \.

Copyrighted material
Hidden page
Micropr.oc:.n 10n1 and Interfacing 5- 19 8081 System Conflgur811on

- - ..
v.,., [ ~ [ I
...... _...,
LOCM.8USES

CLOCK
. . . . . .tOR
CU<
,._
I, .. CL'
r-
Mlll5l!
r-
iiWiC

- """" r-
i, i,
::;m
..,
liD
r- ..,.
-
i, J,

.... ""'T C I'U


DEN Cl10U>

OTM
iQWC
:o;owc
f- oo
r-
r- .... r-
ii1A
iOi5< - H.c.
""'
tlA1'1
.,"""""'
GHO
'- ...
ill
"
Ao.,IIO,$
~ ....., 'r
.... -
AOIt.o.J.TA
. "''
'-"""
C:tOU)

-t>= ' lit .....


"" .
TIW<scv.1!R
~TA lUS

"'
Fig. 5.15 Typ ical maximum mode conftguration

I
~

I If there is no
STB
"""'"'
.,.,. (3)

a25&A. !his il
~~ I 8fl i'IYet*

I ';:1 .r oe Tran~
828612)

r T

CLK ALE
CEN DEN
5V Control

IOMI
AEN
oOB
Con'""
l ogic f= Signal
Generator
OTIR
MCEIP""'DEH
8011 '
BUS i,i;oC
"_;:.
ro;:::er IIWTC

$!)
... Command
s-gnal
;c;;;c
ii5WC

s,
Status
Decode<
Generator ;;:;;;;.:
s,
iNiA
Po1011ty lniO<nlj)t
conb'oller8259A

Fig. 5.16 8266 bus controller


Copyrighted material
Hidden page
Microprocessors and Interlacing 5. 21 8086 Syatam Configuo'allon

.
~
13
}it
~
;
'.
Ill

~~~
I I

Ill
I (
}H
I

il
~.~I
1!1
~

~I
}If
1!1

IU~ IP
,- :; ui
.., ...... n~ 13
::a"'
as~
. 18
~~a
I

,
i "" . . .. i"
~
i 71
j}ll
,..-,: ,..~ .

di
I I
u
LJ:t t
r
a..d. i t-- i~
.r
L.... wli 8
,s

Copyrighted material
Mlcroproc:eaors and Interfacing 5 - 22 8086 System Conflguratl~

5.7.3 Bus Timings for Maximum Mode

5.7.3.1 Timings fOf Read and Write Operations


The timing diagrams ot input and output transfers are shown in the Fig. 5.18 (a) and
(b) ""f'e<:tively.

One Bus Cycle ------lj


T2 T' , - - - \ T' ' , - - - \
CLK - - - '

- - --.,.'----_-_-_-..;:...!:..&1.........-_-_-_-_-_-_-_,-;-r--s:,. -.live
~s.~,- -~-..:: :::

r
- ..~.,. : ---!c'k_:,.-""1::.....,x;.=='-s,...,...,.s-,--- --..> F~oe~
BHe, A1 gA16

ANOBHEIS1 - - - - - - - -
!
! ~--.. cDataiND11~-0o
.......,.......- - - - -l<:< A,.... ) >------;.::<_ I >-----
(AD,AOoJ TAVOV - ---i
1

" ALE - - - -. /
!--TRLOV -i
"MRDC ----------~ :
ortORC
" DT~ ----- ,;------

" DEN - -- -- - - --'

Fig. 5.18 (a) Input (rud operation)

These are explained i~ steps.


I. S,. 5 1, S, are set at the begiMing of bus cycle. On detecting the change on passive
state S, = S1 =S, = 1, the 8288 bus controller will output a pulse on its ALE and
apply a required signal to its DT/R pin during T 1
2. In T,. 82BS will set DEN = I thus enabling transceiver. For an input, 8288 it will
activates MROC or IORC. These signals are activated until T,. For an output the
AMWC or AIOWC i.s activated from T2 to T, and MWTC or IOWC i.s activated
from T3 toT,.
3. The status bits So to ~ remain active until T,; a:nd become passive during T3 and
T,.
4. If ready input i.s not activated before T,_ wait state wlll be inserted betwc""' T, and
T,.

Copyrighted material
Hidden page
Hidden page
Microproc:easort and Interfaci ng 5 -25

Word length M bit

8 bit

Example 2 : If memory has 8192 memory locations, then it has 13 addn.>ss lines.

The Table 5.2 summarizes the memory capacily and addrus lines Nquired for memory
interlacing.

Memory Capacity AddrHa Linea RequfM

1 K 1024 memcwy locations 10


2 K 2048 memory locations 11
4 I( 4098 memory locations 12
8 K 8182 memory lOCations 13
16 K 18384 memory locations 14
32K 3 2 7 1 1 8 - - 15
64K 6$538 IMmOII y localions 16

Table 5.2
As shown in the Fig. 5.20 (a) memory chip has 11 addl'l'S5 lines Ao-A 1., """chip sclect
(CS), and two control lines, read (~ to enable output buffer and write (WR) to '""'blc the
input bufk>r. TI>e intcrnol decoder is used to doox!e the add"'"" li~... Fig. 5.20 (b) shows
the logic diagram of a typical EPROM (Erasable Programmable Read-Only Memory) with
4096 (4 K) registe,... It has 12 address lines A0-A 11, one chip select (~, ono Read control
signal. Since EPRO M i.s a rc{ld only memory. it does not require the (\VR) sign.1l.

5.9 Basic Concepts In Memory Interfacing


For int~rfadng memory d\!vin>S to micropl'()('{._-'S:iar 8086 followln.,; lmpurt.11ll pouil't~ i'ln'
to be kept in mind.
I. Microprocessor 8066 can access 1 Mbytes memory sinoe address bus is 20-bil But it
is not always neceotary to use lull I Mbytes address spa'. The total memory size
depends upon the application.
2. Cenerally EPROM (or EPROMs) is used as progr.tm memory nJ I:AM (ur
RAMs) as a dat.> memory. When both. EPROM and RAM ere used, the total
addre55 spxe IMbytes is shared by them.
3. The individual capodties of program rru.mory and dalll "'->rnory d,pend on the
application.
4. H IS oot ,, lh'.l) ~ n~-u.~"-t f) lv !'ICI\.'t-1 1 EPROM .md I RAM. w,. '"~m 1"1 \ ,. tlluflil !'-
EI'ROMs and multiple RAMs as per the Nquirement of application.

Lopynghted materio~l
Hidden page
Microprocessors and Interfacing 5. 27 8086:'9Ystem Configuration

memory interface with absolute decoding. Two 8 K EPROMs (2764) a~ used to provide
even and odd memory banks. Control signals BHE and Ao are used to enable outputs of
odd and even memory banks respectively. As each memory chip has . 8 K memory
locations. thirteen address lines are required to address each locations~ independently. All
rc.-maining address lines are used to generate an unique chip select 1signal. This addressing
tedutique is normally used in large memory systems.
2) Linear Decoding :
In small systems, hardware for the decoding logic can be elif!linated by using only
required number of addressing lines (not all). Other lines are simply ignored. This
technique is referred as line.ar decoding or partial decoding. Pig 5.22 shows the addressing
of 16 K RAM (6264) with linear decoding. Control signals BHE and Ao are used to enable
odd and even memory banks, respectively. The address line A19 is used to select the RAM
chips. When A1t is low, chip is selected, otherwise it is d isabled. The status of A 14 to A18
does not affect the chip selection logic. This gives you multiple addresses (shadow
addresses). This technique reduces the cost of decoding circuit, but it has drawback of
multiple addresses.

DATA
BUS
o,. .L).o. o,.L).o.
07 DO Do o,
A, LA A, A,~ A,
A;-" ... A;-" Ao 1 ~

-I> '> liRO Rii


6264

RAM
RD :-)
./
LRO
RO RAM
6264

SHE
~ HWR
- (8K)
IA&i. i.WR
'
' (8 K)

WR WR WR - ViR
./ ./
Cs Cs

A" .

Fig. 5.22 Linear decoding


3) Block Decoding :
In <'1. microcomputer system the memory array is often consists or seve-ral block.' or
memory chips. Each block of memory requires dcroding circuit. To 3\'0id separate
decoding for each memory block special decoder IC is used to generate dup select signal
for each block. Fig. 5.23 shows the block decocling technique using 74138, 3:8. decoder.

Copyrighted material
Microprocessors and lniiHfaclng 5 28 8086.Syatem Con~

... ~
o,, ll Ot .. .. o,5 {}o, ..u ..
... ....
D

:::; .....
0,0, 0,0,
""" I ~ ...... ....... I~ . =:: ...
3 "" ...,
r.-/ ii;li
~
,..
~
,,..
......
..., ;o;o
5E ...... (Rlj .........
--q y... '""
151
~"
Of
""'
~ iiR ~ w;;
a a a a

....,- A
r
Yeo

v,
~
EPROt.ICS
.... - e 1
~
A" - ,...___
'

-
G, >
.f 0~
lS
~
~
~AAMCS
3_ }- 0 . 9 NO
_._
Fig. 5.23 Block decoding

5.10 Interfacing Examples

,..., Example 1 : Ot":'i~...,, au 8086 based system tuitll tilt> jollutuing sptcificntious.
i) 8086 iu miuimwn modt.
iil 6-1 KByte EPROM
iiiJ WI KHyk RAI\rl
Drtrw lite complete :;clttmntic of tilt' desigu iudicating addrtSS map.
Solution : The 8066 L a 16 bit microprocessor. It can access 16 bit data simultaneously.
hr inh'rfacin14 nu. non mudule to 8086 CPU, it ls ''ecessary to have odd and even
mem ory ban~. This Cr.'m be achieved by using two 32 Kbyt~ EPROMs and two 32 byte
RAMs, one for odd bank and anothe r for even bank.
As 32 Kbytc RAM and EPROM need 15 address lines, A 1 to A15 lines are used. A, and
BHE a rc used to select even and odd memory banks respectively. Fig. 5.24 shows the
intt-rf,:~~. !'IWt.'' '" ~lRl .1nd lwo nll'mory chips.

Copyrighted material
Vee
J
""""' I
..it~
74LS373(2)

.,.
""" r-
leu< ~
7A
T
.....
-
AlE

--
7"LS138
Vee
f
o,
o,, I
.&
. Ro A
D G,
E
c
MEMR
MEM\ii
w.
..00
c 0
D

R ""
OW I uo
CU< Reset Ready
o, o, . ::!
I I I .... OE o8-o,& A, -A,$ Of 0,0, A,-A,s 0E o,.o,5 ~A,, WR OE 0.,~ A1~$ WR
O.OCK 17256 (EMOt.4) 27256 (EPAOM) 62256 {J\AM) 6:2256 (RAM}
?vee
"'""
I ~
......
Cs Cs Cs Cs

~ ....- L ~ A
Vee o G,
E
c
A1. - A ~ .
T
D
D ,..._ ,..._ .- i

A., - C ~
H ~
c
q,
v,
R
I -1>- AO -L>- -L>- ., -L>- "' '
-r-
iiiiE o; GNOv, .
74lS313
.. f
0 L....;r74LS138 . I '
0
"0
'<
~

<0'
j
::r
~
3
Fig. 5.24 Interfacing 64 K RAM and 64 K EPROM with 8086 In minimum mode

i
*"'
"'
Mlcropr~essors and Interfacing 5 . 30 8086 System Configuration

Memory Map :

BHE A,, A11 Au A,, A, A,. Au Au Au A" At A. A, A. A, A.


1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0
" ' A,
0 0
A,

0
.. Acklress
0 FO<lOOti
Memory
EYO<l
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 FFFFFH EPROM1
0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 F0001H Odd
0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 FFFFHH EPROM2
1 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 30000H Even
1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 3FFFEH RAM1
, , 0 1 30001H
0
0
0
0
0
0
0
0 , 1 , 0, 0
1
0
1
0
1
0 0 0 0 0 0
1 1 1 1 1 1
0
1
0
1
0
1 1 3FFFFH
Odd
RAM2

,,.. Example 2 : Design an 8086 based system witll tile fa/tawing specifirotians.

i) 8086 in maximum mode ii) 64 KByte EPROM iii) 64 KBytr RAM

Draw the complete schematic of the design indicating address map.


Solution : The 8086 is a 16 bit microprocessor. It can ace<>Ss 16 bit data simultaneously.
For interfacing memory module to 8086 CPU, it is necessary to have odd and even
memory banks. This can be achieved by using two 32 Kbyte EPROMs and two 32 Kby1e
RAMs, one for odd bank and another for even bank.
In tho maximum mode, memory and l/ 0 read/write, address latch enable (ALE), Data
Enable (DEN), Data transmit/receive (DT/ R) signals must be decoded externally using bus
controller 8288. f ig 5.25 shows the memory interface with 8086 in the maximum mode. As
32 Kbyte RAM and EPROM need 15 address lines, A1 to A15 lines are used. A, and BHE
a r~ used to select even and odd memory banks respectively.
Memory Map :

-BHE A.,, A" Au A,, Au Au Au Au Au A,. A.

, 0
.. A, At At ... A, AJ At .. AddrHS

FOOOOH
Address

Even
1
1
1
1
1
1
I
1 1
0
1
0
1

1
0
1
0
1
0
1
0
1
0
1
0 0
1 1
0
1
0
1
0 0 0 0
1 1 0 , FFFFEH EPROM1

1 , , FOOOIH Odd
0
0 1
1
1 1
1
1
0
1
0
1
0
1
0
1 ,
0 0 0
1 1 , 0,
0 0 0
1 1
0
1
0
1
0 0
1 1 1 FFFFFH EPROM2

-o 0 0 0 0 0 e...
1
1
0
0
0
0
1
1 ,
I 0
1
0
1 1
0
1
0
1 ,
0 0
1
0
1 1 1
0
1 , 0
1
0
1 1 0
30<lOOti
3FFFEH RAM1

0 0 0 0 0
0
0
0
0
0
0
1
1
1
1
0
I
0
1
0
1
0
1
0
1
0
1
0
1
0
1 1 1 , 1
0 0
1 1 1 ,
1 30001H
3FFFFH
Odd
RAM2

Copyrighted material
!I:
n~
0

"
MN/Mx
11- '"'"~"'"'''~ l
.. ..~
0

"""
Do r- T )
... Ii
"o

r- -
c
L.!!..
TRANSCEIVER

.... .. Q.

- r- CU<
ot.ii
oao
MRDC
T (i o,

i.iiDC
li~
!l
loll

"'
I,
i, t.... ~
;u;;;;c
iOiii!
iOwi!
iiNTc
:;;;;;we
iOiiC
;owe

-...
CU( Reset R..oy AiOWC AiOWC
...
-- --
I ':"
I I

......
ClOCK
I
"""""""'
f Vco;
OE o..o,,
212'!111 Cf~j
~
A,..A" 0 Do.O, A1--A1~

mso(fl'IIC)WJ
cs
Oi GrOts

cs
A'"''' Wit oe 1
a
At""ts Wft
-
I ,,..... I ..... Vee o G,

...,_ . i--
..... - l ~A ~

J---r
0
0

--t?.f-
Ate
.. ~ I-< H
f- C

-
E Y7

v,
.<o-L>- ...J.>- "o ~ >-- i..
ru3n G2 Gte>

0
~~~- . 1 n

~c:
0
-o
'<
~
Fig. 5.25 Interfacing 64 K RAM and 64 K EPROM with 8086 In maximum mode
-
<3

~
3
t
~
"""
Ol
Hidden page
Micr oprocessors ,a nd Interfacing 5 - 33 8086 System Configuration

clear input, CLR, of the shift register. The outputs of the shift register will then all be low.
One of th~ lows will be coupled through a jumper (jumper 4 in the Fig. 5.26), wiU cause
the RDYI input of the 8284 to be pulled low. However, WAIT states will not be inserted
unless ROY! remruns low long enough. Now, when RD. WR. or INTA goes low in the
machine cycle, the CLR input of the 74t.S164 shift register will go hjgh_ and th(> shift
register will function normally. The highs on the INA and INB inputs will be loaded on to
the Q A outp\lt on the next positive edge of the clock. lf the \.YAJT s tate jumper is ln the fo
position., then this high on the Q A output will cause the RDYl input of the 8284 to go
high again. For this Ctl.SC, the ROYJ input gOL"S high soon enough that no W AJT states are
inserted.
The high lood-.."'<1 into the 74L5164 shift rcgist('r is shifted one stage to the right by ('ach
successive dock pulse. When the high reaches tht> jumper connected to the RDY1 input, it
will cau::.e the RDY1 input of the 8284 to go high, as shown in the Fig. 5.27. n ,e 808b will
then exit (rom a WAJT st:~te on the next dock pulse. The number o( WAIT stales il\scrtcd
in a r11.achine cycle is determined by how many s tates the high has to be shifted before it
reaches the insta11ed jumper.

ern ~,
'
o. ~~----~vr--~:----~--+---~----------

o. ~~--------":; :
~ ~~--------~vr-+--~------
oo ~'---------------lJvr'-t-------
o.
(RDY 1) ___2:~---------------------"

READY
Fig. 5.27 Timing diagram for wait state generator

Review Questions
l. Explain ll~: fm~etioll offo/IMl.Jin,r{ pins in S086.
-- ---
il NMI ii) MN/MX iii) TEST
--
iu) BHE vi OT/R vi! DEN vii! QS(}"QS,.
2. EJ.plai11 11~ mnxlmum mode s-ig11nl$ f1/ 8086.
J. EJ:pl11itt lilt mhtlmum modt slgn11ls 8()86.
4. Wilh tl1t' lklp of b/()(k diagram explain memory iutrrfocing WitiJ 8086 mrd e.rplnin rl.llly two bus
cycle'S art> ri'qr.tirM to ltC4'SS odd mldrffS iLI()rd ?
5. DmtU mtd r:rplni11 tiN' nh"1t10ty mnp for 8086.

Copyrighted matenai
Microprocessors and Interfacing 8086 System Configuration
6. E.xplairl lllt 1/0 rtddrming copabilitit-5 of 8086.
7. Drnw and n:plnin 1111" 1/0 mnp of 8086.
S. Explain tllt grruml bus op~rnlion of 8086 ruWr the lld.p of timing diagram.
- -
9. E.xp/1;,, th ,mrpose of RMdy, OE..N nnd DT/R sigtutls.
lO. Witlr llw lttP of block sclkmatic diagmms ~xplnin tlr~ optndion of 8284 dock g~11trator ttnd 8286
transaivcr.
11. Sketclr block diagram sJunvilrg bask 8086 minimum mode sysltm. E.xplain ftmctions of 8282 /ntcll!t'S
(md 8286 lrtmsrrivtr.
12. O.:fint be~s ryde, nnd ~xpltrbr tire minimum nrodt- rmd n11d writt- bus cycle wilh proper Uming
diagram.
13. Explnin Ill( HOLD rt'5ponse ~UI'11U in tlr~ minimum mode of 8086 witlr lht lretp of timing
dingrnm.
14. Dmw and exploiu a block diagram showirfg 8086 in mn.ximum nwdt cotifiguraliQn.
15. Drnrv and (:tp/nin llrl" timing dingmm.s of brp1d and 011tput trtmsfrrs of 8086 in nruinrum mcxk
16. IndicaJe tilt signals wllich art dif/c!n!fll wlum 8086 iu minimum mode 1md in mtJ:rimum mcde.
17. Explain the operation of bus rrqurslaud b11s gmnt Sif1ull wWr the l~tlp of liming dingmm.
18. Explain tlw ftmction of wait stntt gm~rntor.
19. D ..osign the u\'.lit state gt~ltTiltor to in$Ul ~1it stntes from uro to set'Cn.

QQQ

Copyrighted material
6
Direct Memory Access
(DMA) - 8237/8257

In microprocessor based systems data transfer can be controlled by either software or


hardware. Upto this point we have used program instructions to transfer data from l/ 0
device to memory or rom memory to 1/0 devke. To transfer data by this method
microprocessor has to do following tasks :
1. To fetch the instruction
2. To decode the instruction and
3. To cxec\lte the ins truction.
To carryout these tasks microprocessor requires considerable time, so this method of
data transfer is not suitable fo r large data transfers S\JCh as data transfer from magnetic
disk or optical disk co memory. In such situations hardware oontn>lk>d dato transfer
technique is \ISL~ .
Software Controlled Data Transfer
In this methl'X! programmet e:Xt."Cutes a series of ins tructiOJ'\S to carry oul data transfer.
The sample flow chart and program required to transfer data from memory to l/ 0 device
is shown in Fig. 6.1. (Refer Fig. 6.1 on next poge.)
Program :
Trans fer Subroutlnt
MOV CX, COUNT I n itializ~ counter
MOV ox, PORT addt Load port address in ox
B.:.CK MOV AL, lSI) Get byte from memory
OUT ox, AL Send byte to output port
I NC ox I ncrement port address
TNC SI Increment memory pointer
LOOP BACK Repeat until ex = 0
RET
Hardware Controlled Data Transfer
ln this technique external device is used to control dam transfer. External device
generates address and control sigmds tLliJuircd to control data tn\ns(er and allows
(6 1)

Copynghted r" atenal


Mle<oproeessors and Interfaci ng 6-2 Dlreet Memory Aeeess (DMA) - 8237/8257

&ni!ializ:e counter
Initialize &OtKCe pointer

Fig. 6.1 Flowchart


peripheral device to directly access the memory. Hence this technique is referred to as
O'itect Memory Access (OMA) and external device which controls the data transfer is
referred to as DMA controller. Fig. 6.2 shows that how DMA controJier operates in a

-
microprocessor system.

r--1
ADo -AD,s
.... -
--""'~ -
-
"""" " ' lO
~
HRO

HI.OA

Fig. 6.2 OMA controller operating In microprocessor system

Copyrighted material
6 -3 Direct Memc.ry Acceu (DMA)-1237111257

DMA Idle Cycle


When the system is turned on, the switches are in the A position, so the buses are
co.mect'ed from tlw microprocessor to the system memory and periphe-raL..;. Microproces..c:or
then ext."C'\Ites the p rogram until it needs to read a block of data from the disk. To read a
block of d.atn from the disk micnlproa.~r sends a series of commands to the disk
controller device telling it to '"'arch and read the desired block of data from the disk.
When disk controller is ready to transfer first byte of data from disk, it sends DMA
n..-qucst DRQ signa l to the DMA controller. Then DMA controller send~ a hold request
HRQ signal to the microprocessor HOLD input The microprocessor responds this HOLD
si~'Tlal by floa ting its buses and ..,nding out a hold a<:knowledge signa.! HLDA. to the
OMA controller. When the OMA rontro11er receives the HLDA signal, it sends a control
sign..1l to change switch position from A to B. This disconnects the microprocessor from the
b u$CS and connects OMA contrullcr to the bu~.

DMA Active Cycle


When DMA controller gets oontrol.o( the buses, it sends the memory address where
the fir.;t byte of data from the disk is to be written. It also sends a DMA acknowledge,
DACK signal to the disk controller device telling it to get ready for data transfer. Finally
(in case o( DMA write operation), it a..,_o;crts both the lO R and MEMW sjgnals OJ\ the
control bus. Asserting the lOR signal enabi<'S the disk controller to output the byte of data
from the disk on the data bus and asserting the MEMW signal enables the addressed
memory to aCC<!pt d:tta from the data bus. In this technique data is transferred d irectly
from the disk controller to the memory location without pi.l.S:Sing through the CPU or the
DMA contn>ller.
When the data transfer L-. complete, the DMA controller unasscr ts the HOLD request
signal to the microprocessor nnd releases the bus by chan ging switch position from 8 to A.
Aftt..:.r getting the control of all buses the m icroprocessor executes the remaining pr~~a m.

6.1 Features of 8257


1. II i:.o ;, programmable, 4-chn.nncl, d irect mt:mory acre:,-:; controller. Each channel can
be programmed individually. Therefore, we can interface 4 input/output devices
with 8257.
2. Ench channel indudes a 16.bit DMA addres.c; register and a 14-bit counter. DMA
address register gives the address of the memory location and counter specifies the
number of DMA cych.--s to be pcrfonnl-d. As rounh:.r is 14-bit, ('.:\Ch d\annc! c.m
transfer 2 1-' (16 kbrtcs) without intc rvJ.">fttio n of mjcrupn.,t."t.~wr.
3. It maintains the DMA cycle count or L"a.Ch channl!l and activates :t control s ignal
TC (T\. nninal count) In indicate the pcriphlral th.lt the pnlgrammL'<I number of
DMA cydl'S art> complt.<tc.
4.. it provid('S another control ~ igna l MARK to lndic:~tc pc!riphcral that the current
IJMA cydt i~ thl.! I:!M'" \'yC'lc siilt.:L! the prC\1ious MARK o u tput

Copyrighted material
-
Microprocessors and Interfacing 8-4 Direct Memory Access (DMA) - 8237/8257

5. It has priority logic that re:soJvt"S the peripherals requests. The priority logic c:an be
programmed. to work in two modes, either in fixed mode or rotating priority
mode.
6. It provides inhibit logic which can be used to inhibit individual channels.
1. It allows data transfer in two modes : burst mode and cycle steal (single byte
transfer) mode.
8. It can execute three DMA cycles : DMA read, DMA write and DMA verify.
9. Auto load featur. of 8257 p<lnnits repeat block o r block chaining operations.
10. It operates in two modes : slave and master.
11. When DMA is in master mode, AEN signal provided by 8257 allows to isolate
CPU buffe rs~ latches and other devices from the system bus.
12. Extended write mode of 8257 prevents the unneccssa;ry occurrence of wait states in
the 8257, increasing the system throughput.
13. It op.<rates on single TIL clock and it is completely TIL compatible.
14. lt can be interfaced with all Intel microprocessor.
15. H transfers one byte of data in four doc.k cydes. Thus giving high transfer rate
s uch as 500 Kbytes/second at 2
MHz dock input.
16. Like 8085, 8257 alw has READY
.,
input which allows 8257 to interface
slower memory or l/ 0 devices that
can .,ot mt.>el bus setup f:'>les
required by the 8257.
REAOY ....
TC

6.2 Pin Diagram of 8257


Pig. 6.3 shows pin diagram of 8257.
HLOA
AOSTB
.....
.,
Data Bus (00-07) : These are bi-directional
HRO vee
tristate signals connected to the system
data bus. When CPU is having control of Oo
system bus it can acces.-. contents of address CU< o,
register, stat\tS register, mode set register, RESET o,
and a tennin:d count register and it can o,
also program, control registers of DMA o,
controller, through the data bus.
During DMA cycles th<>se lines are used
to send the most significant bytes of the
memory address from one of the DMA
address registers.
.
"""
..,.
GHD o,

Fig. 8.3 Pin diagram of 8257

Copyrighted material
Microprocessors and Inte rfacing 6-5 Direct Memory Access (DMA) 823718257

Address Bus (Ao-A3 and A4-A 7) : The four leasl significanl tines Ao-A3 are
bi - directional tri - state signals. In the idle cycle they are inputs and used by the CPU to
address the register to be loaded or read. In the active cycle they output the lower 4 bits
of the address for DMA operation. A4 A 7 are unidirectional lines, provide 4bits of address
during OMA service.
Address Strobe (ADSTB) : This signal is used to demultiplex higher byte address and
data using external latch.
Address Enable (AEN) : This active high signal enables the 8-bit latch containing the
upper 8-address bits onto the system address bus. AEN can also be used to disable other
system bus d rivers during DMA transfers.
Memory Read and Memory Wrtt, ( MEMR, MEMW ) :
These are active low tri-state signals. The MEMR signal used to access data from the
add res._~ memory location during a OMA read or memory-to-memory transfer and
MEMW signal is lLc;cd to write data to the addressed memory location d uring DMA write
or memory to mentory transfer.
VO Re ad and 110 Wrlte ( lOR AND iOW ) : These are active low bi-directional s ignals.
In idle cycle, these are an input control signals used by CPU to read/ write the control
regis tcrs. In the active cyc-le lOR s ignal is used to access data from a periphera l and lOW
signal is used to send data to the peripheral.
Chip Select (CS) : This is an active low input, used to select the 8257 as an 1/0 device
during the idle cyde. This allows CPU to communicate with 8257.
Reset : This active high s ignal dears the command, s tatus, request and temporary
registers. [t also dears the first/last flip-flop tt.nd sets the Mastc.r Register. After reset the
device is in the idle cyde.

Ready : This input is used to extend the mem ory read and write s ignals from the 8257
to interface s low memories or 1/ 0 deviet.~.
Hold Roqueot (HRQ) : Any valid DREQ causes 8257 to issue the HRQ. II is used for
requesting CPU to get the control of system bus.
Hold Acknowledge (HLDA) : The octive high Hold Acknowledge from the CPU
indkatcs that it hM rolinguishcd control of the system bus.

DREQ,-DREQ3 : These a re DMA request lines, which are activated to obtain DMA
service, until the corresponding DACK signal goes active.
DACK,-DACK3 : These are used to indicate peripheral devices that the DMA request is
granted.
Terminal Count (TC) : This is active high Sib'l\al concem with the compiNion of OMA
service. The TC output signal is activated at the end of DMA service, i.e. when present
cycle is a last cycle for the current data block.

Copyrighted material
Mlcroprocusors and Interfacing 6 -6 Direct t.'e .. oory Access (DMA) 823718:257
MARK : Tilis output notifies the selected peripheral that Lhe current DMA cycle is the
128 " cycle since the previous MARK output. MARK always occurs ot 126 (all multiplies of
126) cycles from the end of the dat., block.

6.3 Block Diagram of 8257


Fig. 6.4 shows the functional block diagram of IC 8257.

.. r-
Data I '"' 16 ORQ0
o,.oo ( bl1
' bus
buffer
- addr
CNTR

; :
... 16
DRQ 1
RlR bit
RlW
CLK
RESET
Readl
write
j
..
- addr
C>ITR DAllR,

.,.,_
Ao

logic
.... 16
_,
bit

'i f-. CNm


cs I
,._
READY-
.,_
~- Cootrol
logic
and
I "" 16
b<t
addr
CNm
HRO - I
roode

'
H LDA-
ggm1--< set

.~
register Priotity
lm!WY--< resolver
AEN-
.~
ST8- I
Internal bus
MARK
TC ....

Fig. 6.4 Functional block diagram of 8257

Data Bus Buffer


It is n trist:;Hc. bi-din.--c-tional. dJ;ht bit buff\~r which intl'rfaccs the R"'-57 to the .s\'Slcm
data bu~. In ~he s lavt! mode, it is u:oo~.d to l r~m~fcr data bdwwn micropn..lC\.-'tl!t\.1r and

Copyrighted material
Mlci'Oflrocesf!Prs and Interfacing 6-7 Dire<:! Memory Access (DMA) 8237/8257

internal "'b>isters of 8257. In master mode, it is used to send higher byte address 1As-A1s)
on the data bus.
Road/Write logic
When the CPU is p rogramming or reading one of the internal registers of 8257 (i.e.
when the 8257 is in the slave mode), .t he Read/Write logic accepts the 1/0 Read (lOR) or
1/ 0 Write (lOW) signal, decodes the the least significant four addre$S bits (Ao - As) and
~ithcr wrltcs the contents of the data. bus lnto th~ addres..t;Cd regio;ter (if iOW is low) or
places the ('(_mtents of the addressed register onto the data bus (if lOR is low).
During OMA cycles (i.e. when the 8257 is in the master mode) the Read/Write logic
g(..onerates the 1/0 read and memory write (DMA write cycle ) or 1/0 write and memory
read (DMA read <::yde) sign.1ls which control the data transfer bel\v(!Cn pcriphcr:ll and
memory device.
DMA Channels
The 8257 provides four identical channels, labeled CH, to CH3. Each channcl has tw"
sixteen bit registers : i) A DMA address register. and ii) A tcrmin31 count r(-gis ter.
DMA Addnoss Register :
Fig. 0.5 shows the format of OMA addn-:,s n..ogi.stcr. It ~pt...odfit...os tht! .1ddn......_... u ( lh( fi,..,.t
memory location to be accessed. 1t is necessary to load valid memory address in the DMA
address register before channel is enabled.

Fig. 6.5 Fonnat of DMA address register


Terminal Count Registef' : Fig. 6.6 shows the format of terminal count rcgi~tcr.

14 bit binary count (N-1) ....,


Fig. 6.6

T, To Type of openUon

0 0 OMA Verify cycle


0 1 OMA Wti'le cycle

1 0 OMA READ cycle


1 1 Illegal

N ote- : N i..; 11umb4_ uf by tt:.. "' h.: tr.m..ftrn.(.L

Copyrighted material
Mlcroproeessor&iand Interfacing 6-8 Direct Memory Access (DMA) 8237/8257

The value loaded into the low order 14 bits (C 13 -Co) of the terminal count register
specifies the number of DMA cycles minus one before the terminal count (TC) output is
activ,1ted. Therefore, for N number of desired DMA cycles it is necessary to load the value
N-1 into the low order 14bits of the terminal count register. The most significant 2 bits of
the termina l count regi~lcr specifies the type of DMA operation to be performed. It is
ncces..;;ary to load count fo r DMA cycles and operational code for valid DMA cycle in the
terminal count register before channel is enabled.

Control logic
It controls the sequence of operatiOJ\S during 0'1.11 DMA cycles (DMA read, DMA write,
DMA verify) by generating the appropriate control signals and the H>bit address that
specifies the memory location to be accessed. It consists of mode set register and status
register. Mode set register is programmed by the CPU to configure 8257 whereas the status
register is read by CPU to check which channels have reached a terminal count cond ition
and status of update nag.

Mode Set Register


Fig. 6.7 gives the format of mode set register. least significant four bits of mode set
register, when set, enable each of the four OMA channels. Most significant four bits allow
four different options for the 8257.

e7 B6 B5 e, 83 e., e, B0

Enables AUTOLOAO _ j L _ Enables DMA channel 0


Enabtes TC stop Enables OMA channel 1
Enabtes EXTENDED WRITE Enables OMA Channel 2
Enables ROTATINGPRIORtTY Enables OMA channel3

Fig. 6.7 Mode set register

lt is nonnally programmed by the CPU after initializing the DMA address registers
and terminal count registers. It is cleared by the RESET input, thus disabling all options,
inhibiting all chaMcls, and preventing bus conflicts on power-up.
Status Register
Fig. 6$ shows the status register format. As said earlier, it indicates which channels
have reached a terminal count condition and includes the update f'lag described
prev ious ly.
The TC status bit, if one~ indkates terminal count has been reached for that channel.
TC bit remains S<'l until the status register is read or the 8257 is reset. The up!ate flag,
h.._1wevcr, i:o:; not a ffech.:.d by a status read Optration.

Copyrighted material
Microprocessors and Interfacing 6-9 Direct Memory Acce(DMA) 823711257

0 0 0
L _ TC status 101' Channel 0
Update flag
TC status for Channel 1
TC statu-s fOf c::tlannel 2
TC status for channel 3

Fig. 6.8 Status register

The update Aag bi~ if one, indicates CPU that 8257 is executing update t)'de. In
update cycle 8257 loads parameters in channel 3 to channel 2.
Priority Resolver
It resolves the peripherals requests. It can be programmed to work in two modes,
either in fixed mode or rotating priority mode.

6.4 Operating Modes of 8257


The 8257 can be programmed to operate in following modes :
1. Rotating Priority Mode
ln rotating priority mode, the priority of the
channels has a circular sequence. ln this, channel
being serviced gets the lowest priority and the
channel next to it gets the highest priority as
s hown in fig. 6.9.
Thus, w ith rotating priority in a single chip Fig. 6.9 Rotating priority
DMA system, any device requesting service is
guaranteed to be recognized after no more than three highe.r priority services have
occurred. This prevents any one channel from monopolizing the system. The rotating
priority mode can be set by writing logic '1' in the bit 4 of the mode scl register.
Fixed Priority Modo
In the fixed priority, channel 0 has the highest priorHy and channel 3 has the lowe.">l
priority. Table 6.1 shows the priority ratings.

Priority Chlnnel
Highesl 1 0
2 1
3 2
4 3
Table 6.1 Priority ratings

Copyrighted material
Hidden page
Hidden page
MlcroproeessOrc-'~nd Interfacing 6 - 12 Direct Memory Access (DMA)- 823718257

~ ..
Q ..
Q '
Q
Q 0

tf o 8 o
0 -8 0' N
"
8 0'

J I~ I~ A A j
~~~ ~ ~~ I~ I~

I I I I I
I
~ ~ <!-2

"~
-.
11~
OQ
a' <
~~
. g"
c o
f
~
~


,(

i%

~ d~

-.. I~ I~
!l
I~ ~~ 0
Q
g ~
~
~
w
lfl ~ 18
tf ~ .
I

~~
-' < ~uz:S
ld

owuOowu-
10
u
-' <~U :Z: ~ E
1
fO I~ I~ I~ { I~ H f-
<
~
~
o-lj o
IC
N


hi
I I

Fig. 6.10
Copyrighted material
Hidden page
Hidden page
Microprocessors and Interfacing 6 - 15 Direct Memory Access (DMA) 823718257

EOP
RESET
cs
READY
......
-
ct.OCK
AEN
AOS'lll
MEMR
MEMW
lOR
lOW

Fig. 6.1 2 Internal block diagram of 8237A

2. Program Command Control Block : It decodes various commands given to the


8237A by the m icroprocessor lx!fore scrvic:iJ\8 a DMA request. It also decodes l:hc Mode
Control Word, which is u.sed to select the type of DMA during the servicing.

3. Priority Encoder Block : ll resolves the priority bctwa""f'' DMA d"-'.ru\CJs


requesling service simultaneously.
Internal Registers ; TI\c 8237A contlins 344 bits internal memory in the form of
registers. Table 6.2 gives the nam e, size and number of each register.
Name Size Number
Base Address Registers 16 bits 4
Base Word Count Registers 16 bits 4
Current Addre.~ RegisterS 16 bits 4
Current Word Count Registers 16 bits 4
Temporary Address Regis ters 16 bits 1
Temporary Word Count Registers 16 bits t
Status Regis ters 8 bits 1
Command Registers 8 bits 1
Tempor-ary Registers 8 blts 1
Mode Registers 4
6 "'"
Mask Registers 4bils t
ReQuest R('oJ.{isters 4 bits 1

Table 6.2

Copyrighted material
Hidden page
Hidden page
MlcroprocenOJS and Interfacing 6 - 18 Direct Memory Access (DMA) 823718257

7. The word/byte transfer counf is decremented and the memory address is


incremented.
8. The DMAC continues to execute transfer cycles until the l / 0 device deas."'lerts DRQ
indicatir~ its inability to continu~ delivering data. The DMAC deasserts HOLD
signal. giving the buses back to microprocessor. It also deasserts DACK.
9. 1/0 device can re-initiate demand transfer by reasserting DRQ signal.
10. Transfer continues in thi..; way until tM transfer count has been exhausted.
The flowcharts in the Fig. 6.13 s ummarized the three data transfer modes of DMA
(St.'<> Fig. 6.13 on next page).

Cascade Mode
DMA ch;mnels can be expanded using this mode. Fig. 6.14 shows thnt two addition:.l
devices are cascaded to the mas ter device us ing two channels of the master device. This is
two level DMA system. In this the HRQ and HLDA signals from the additional 8237A are
conn<.'Cted to the DREQ and DACK signals of a channel of the master 8237A. This allows
the DMA requests of the additional devices to communicate through the priority network
circuitry of the preceding device.

2ND LEVEL

o:I:ITA
1ST LEVEL
M1CROPROCSSOR
HRO DREO HRO
>I.OA DACI( HlOA

W7A

OREO HRO
DACI(
>I.CA

&237A

ADOinONAL
DEVICES

Fig. 6.14 Caocade 8237s


Note : More 8237As can be added by adding more lovels in the DMA system.
Fig. 6.15 (See Fig. on page 6-20) shows the detail ronnections for master and slave
DMAC's.

Copyrighted material
Start Sllrt Start

No /
__..... ,..... .... ' ...
~

5.
i,. j
..;
w
v..
OMA acquires ~
"'"
OMA .cqulres DMA acQUires the control of
the control of the oontrd of buses from DI'008'SSOf
i buNt from PfOCtltol' buses from processor

I Tron>f~ one by<e I


i Transfers ont I I~
I
bytl

0
DW.rtllngulohts
;
!l

I
oonttol of buses 1o
processor 1:
YH 3
!i. ~
i No
f-
DMA relinguishes
control of buses to

IV" processo< 0

~
0
0
"0
I ptO<:eiiOt
~
'< 0
~
cO~ lop Slop Slop tl
-
::r
~
(1) atnglt tronofe< (b) Block trandw (c) Demand transt.r
.........ill
3.
"'"'
10

"'
Microprocessors and Interfacing 6 - 20 Direct Memory Access (OMA) 8237/8257

HOLD

HL()A

I
Master
DMA
Controller

Slave
DMA
Control'-r

Fig. 6.15 Cascaded DMA controllers


6.10 Transfer Types

6.10.1 Memory-to-Memory Transfer


In this mode block of data from one memory address is moved to another memory
address. ln this mode current address register of chaMel 0 is used to point the source
address and the current address register of channel 1 is USL~ to point the destination
address in the fi rst transfer <:yde~ data byte from the soUrce address is loaded in the
temporary register of the 8237A and in the next tran.';ofcr cycle the data from the temporary
register is stored in the memory pointed by destination address. After each data transfer
current address registers are decremented or incremented according to current settings.
The channel 1 current word count register is also decremented by 1 after each data
transfer. When the word coun t of channel 1 goes to FFFFH, a TC is generated which
activates EOP output terminating the DMA service.

Copyrighted material
MICI'Oprocessors and Interfacing 6. 21 Dlrec1 Memory Access (DMA) 823718257

6.10.2 Autoinitialize
In this mode, during the initialization the base address and word count registers are
loaded ~;mu1taneously with the current address and word count registers by the
microprocessor. ~ address and the count in the base registers remain unchanged
throughout the DMA service.
After the first block transfer i.e. after the activation o( the EOP signal, the original
values of the current address and current word count registers are automatically restored
from the base address and base word count register of that channel. After autoinitialization
the channel is rea.dy to perform ;:mother DMA servk~. without CPU intervention.

6.11 Priority
In the 8237A there are two priority scl(>('tion options.
1. Fixed Priority
2. Rotating Priority.

6.1 1.1 Fixed Priority


In the fixed priority channel 0 has the highest priority and the channel 3 has the
lowest priority. Table 6.3 shows the priority ratings.
Prtorlty Channel
Highest 1 0
2 1
3 2
lowest 4 3
Table 6.3
ln the fixed priority, aJter recognition of any one channel for service, the other
channe-Ls arc prevented from interfering with that service until it is completed.

6.11.2 Rotating Priority


[n this, channel being serviced gets tlu~ lowest priority and the channel next to it gets
the highest priority as shown in Fig. 6.16.
1st 2nd 3rd
Servk:e Service Service
Hlgnest 0 2 + Service ' \ 3 + Service
1 + Service """- 3 + ~est o
2 "'0 1
lowest 3 1 2
Fig. 6.16 Rotating priority
With rotating priority in a ~ ingle chip DMA system, any device requesting service is
guaranteed to be recognized after no more than three higher priority services have
occurred. This prevents any one channel from monopolizing the system.

Copyrighted material
Mlcrop<ocessors and Interfacing 6 22 Direct Memory Access (DMA) 1,&23718257

6.12 Register Description
1. Current Address Registe r : Each dlt.1.lllle1 has 16-bit current address register. This
rt.--gister stores the value of the address used during DMA transfers. The address in the
current address regis ter is automatic::al1y incremented or decremented after each transfer.
This register is loaded or read by th~ mkropl"'CeSS()r and it a.Lso be re-initiaHzcd back to
its original value after EOP in the autoinitialization mode.

2. Current Word Register : Each channel has a 16-bit current word count regisrer.
This register determines the number of transfers to be perfonncd. Tile actual number of
transfers will be one more than the number stored in the current word count register.
After e<'lch transfer the contents of word count register is decremented by 1. Wht"'l the
value in the register goes from zero to FFFFH, a TC wHJ be geru.'"Tated. ThLo; register is
loaded or read by the microprocessor and it also be relnitialized back to its original value
after EOP in the autoinitialize mode.

3. Base Address and Base Word Count !Wglot."' : Each channel has base
address and base word count registers. TI\CSC 16--bit registers s tore lhe original V<lluc of
their associated current registers. During autoinitialization these values are used to restore
the current regist~ to their originctl values. 1he base n.-gisters are storE..od simultaneous ly
with their corresponding curl't-"'flt registers.

4. Request Register : 'The 8237A can respond to requests for DMA service which
are initiated by software as well as by a DREQ. Each channel has a req....st bit associated
with it in the 4-bit request register. Each bit in the reqlK'St register is set or reset separately
undc..)J' software control and is nu tQmatkaJJy dcan.>d upon generation of a TC or t.xtemal
EOP.

Request Register
7 6 5 4 3 2 1 0 .-sitNumber

Don't Care
I { 00 St:locl """""' 0
0 1 Select channel 1
10 Select chaooel 2
11 Select channel 3

L - - --{ 0 RAlset requost ba


t Set request bil

F'og. 6.17 Request regiola<

5. Command Register : Fig. 6.18 shows the bit patlem of the oommand rq;i:,ter. It
is a.bit n:.og:ister wh ich ('Olltrols the opc..--r.1tiun o( 8237A.

Copyrighted material
~lcropn>cuson and Interfacing 6 23 Direct Memory Accuo {DMA) 823718257

Commend Register
7 6 5 4 3 2 1 O ~ SitNumber

I I I I I JIJ I
1 ro Memory-to-memory diseble
l 1 Memo<y-to-memo<y enoble
0 Channel o address hOkl disable
1 Chan.wtl o a<khss hOld enable
X lfbftO=O

0 Controler enable
1 Controller diS8ble
0 Normal timing
1 Compreosed timing
tfbit 01

0 Fixed ptfority
1 ROialing prlor11y

o Late wme selection


1 Exlonded- Hledlon
X lfbit31

0 DREQ ...,.. oelive h;gh


1 DREO ...,.. odlve low

0 DACK sense active low


1 DACK sense active high

Fig. 6.18 Command register

6. Mask Register : E.1ch channel request can be individually maoked by setting the
proper bit pattem in the mask register. Fig. 6.19 sh<>ws the bit patterns of the mask
register.

7 6 5 4 3 2 1 0 +--BitN~Mnber

I I I I I I I I
00 Select channel 0 mask bit
Don't Care 01 Select channel 1 mask bil
10 Select channel 2 mask bil
11 Select channel 3 mosl< bft

L - ---< 01 Clear mask bit


Set mask bit

Fig. 6.19 Mask register

Copyrighted material
Mlci'.OI)I'oces~ and Interfacing 6- 24 Qlrect Memory Acces, (DMA,) - 8237/8257
'~ ...
:)
Note : All fou r-bits of the mas k register can be written with a single command.
Fig. 6 .20.

7 6 5 4 3 2 1 O.....,_BiiNumber

l l J l J illJ
~ IL ----lr o Clear Cllannel o mask bll
Don't care l 1 Set chaMel 0 mask bit

... '"' L - - - - j f 0 Clear Channel 1mask bit


l t Set dlannel1 mask bit

I '

0 Clear channel 2 mask bit


1 Set channel 2 mask bit

0 Clear channel 3 mask bit


1 Set channat 3 mask bit

Fig. 6.20 Mask register using single command

7. Mode Re.gister, : Each channel has n 6-bit mode reg-i.i tcr associatL)(J with it. The bit
I' 11 h ru ,,f tl'k 1m~o~.ic ':t-,.;i~h.. r is '-'~ shown in the Fig. 6.21 .
Mode Register
7 65432

'- I I I I II I

~,,
00 Channel 0 select
01 Channel 1 seleC:t
o
1 Channel 2 se1ec1
11 Charnel 3 se.4ect

00 Verify transfer
01 Write transfer
,
I 0 Read ltansfer
1 Illegal
\ ' tfbits 6 and 7 = 11
10t

I
\
!
I 0 Adcl'eSII: inct'el'nenf setec:t
1 Addte!IS cSeaernenl 9eled

,.

Copyrighted material
Microprocessors and Interfacing 6 25 Direct Memory Access (DMA) 823718257

8. Status Register : The status register contains the infonnation about the status of
the OMA channels. It includes which channels have reached a terminnl count and which
ch<~ nnels have pending DMA requests. The bit pattern for s tatus r:c~istt..--r i!J shown in
Fig. 6.22.

7 6 5 4 3 2 1 0 4--- BI! Numbet

ll JllL il l
1 Chamel 0 has reached TC
1 Channel 1 has reached TC
1 Channel 2 has read~<><l TC
1 Channel 3 has reaChed TC
1 Channel 0 request
1 Channel 1 request

1 Channel 2 request
1 Channel 3 request

Fig. 6.22 Status regis ter ~

Tempontry Register: It is tiS4..."<! to hold d:tta during memory lt)nll:moT)' traru.f(-rs.


' ....'
9. Register Addresses : Table 6.4 gin.--s th~ addtt.s~-s (o~ di((cn.nt n~i:-<kr!O tJi th..
8237A.

Channel Register Operation S!gnals


cs lOR lOW A, A2 A, Ao
0 Base and Current Addre:s-s Write 0 1 0 0 0 0 0
0 1 0 0 0 0 0
Current Address Read 0 0 1 0 0 0 0
0 0 1 , (>

Base and Currem Word Wrile 0 1 0 0 0 0 1


COunt
0 1 0 0 0 0 1
CoA'ent WOtd ~~ Read 0 0 1 0 0 0 1


--
'
0 0 1 ~ ,")

Copyrighted material
Hidden page
Mlcroprocnoora nd lnletfacl119 8 27 Dlfect Memory Acc:.aa (OMA) 823718257

Softwore Comm.tndo : The 8237A respond 10 the splal software commands in the
progmm mode. Each software command hruo the spociflc code. The Table 6.5 lists the code
fO< spocial software comtru~nda provided by 8237A.

a..- Open~Uon

... .., .... ... -lOR -


lOW
t 0 0 0 0 I RMdSIIURoglolor
I 0 0 0 I 0 Wrilil COmmend Register
I 0 0 I 0 I llogol
I 0 0 I I 0 -~RegiSior
I 0 I 0 0 I llogol
0 1 0
~- Rogi&IM e.t
I I 0
-
1 0 1 1 0 1 tlogol
1 0 , 1 1 0 --Roglolor
1 , 0 0 0 I tlogol
0 0
1
1
1
, 0 , 1
0
0
, C.. ~ - Ftlp/l'ql
RMd Tlfi'CIOIOIY fllsliltor
1 1 0 , , 0 ....... c.....
1 1 I 0 0 , lllegll
1 1 1 0 1 0 Clelr Motlc Roglole<
I 1 I 1 0 1 Mlogll
1 1 I 1 I 0 Wl1le M Mool< Regls1<1r BIIS
Tble 8.5

6.13 Interfacing
Fig. 6.23 shows that a typical method for configuring a DMA sy>tem with the 8237A
controller and an 8088 microproces!!Or sy>tem. The multlmode DMA controller issues a
HRQ signal to the microproces.10r whenever there is a t leilSt one valid DMA request from
a peripheral device. When p""""'""r responds with a HLDA signal, the 8237A tokes
control of the addr('ti..S bus, data but' and control bU!.. Tile 8237A sends lower byte of the
address on the AoA 7 bus and higher byte on the data bus. The contents of the data bus
are then latched Into the extemol latch to complete the full 16-bits of the address bus.
Microprocessors and Interfacing 6- 28 Direct Memory Access (DMA) - 8237/8257

~~ -A, ADDRESS BUS

~ ' ~ ' ~

~ ~"
...
oe
.
. _, ...o. A,Ao A7 ~ AEN
AOST8
_r LATCH

~ t-"'9
- - ClK
'
~

~
0:
8:Z37A5

,~ .
~~ ~ ~~~~ li li
oao
ce,
A



...

.. . ! 4 4

CI.K - ,,.,, .
RESET
MROC
MWRC
lOA
lOW

Or- 0o OATA eus

Fig. 6.23 Interfacing of 8237 and 8088

Review Questions
J. WIMt i~ lite' lli'f'<f ofi)M!l iu mi,rartrot:"!l~r nJrliclrtious?
~. 1:\JJ/,riu tilt' (lf(,/rilt'(lllft', organiSIItiou and vmio11s modr$ of Optration of a programmable DMA
~-ontrollr.'f' 8257.
J. Expl.rin hr bri<f tltr difft'mll (VP.~ of DMA data trrmsfrr.
.J. W1111t do you rmtltrSlnmJ by tiN.' following lt'TmS ?
Rotann,f! l'riority mode.
TC STOI, r~wd
S. Giw tltt' int<'rfacitrg sdrt>mc of 8257/81J7 ;md 8086.
6. List lilt' featuns of 8237 A DMA controll~r.
7. Draw a11d t'Xplaitr tl1t> ardtitt'Cillrt of 8237 A .
8. Explnirr till" optroting modes of 8237 ..4.
9. xp!ni11 tlw datil tnwsjt'r f.VIH'$ SllpfiOI'IM b.v 8237 A.
JO. Cxpl(1in "'" wiorily option: ntuilnlllc in 81J7 A
'I J . Draw ttud t'.l' plniJl 1.11.. iuterfilciu.~ of 8137 A nnd 8088.

CICICI

Copyrighted material
. u' ,.

8255 PPI (Programmable


Peripheral Ir1terface) I

Tile 8255 is a general purpose programmable 1/0 device u...;cd (or poralld J.1to
transfer. It has 24 l/ 0 pins whkh can be grouped in three 8-bit parallel ports : Port A,
Port B and J'ort C. The eight bits of port C c-an be used as individual bits or be grouped in
two 4-bit ports : C,,., (C") a nd C ..... (Cc>
The 8255, primarily, can be progra mmed in two basic modes : Bit Set/Reset (BSR)
mode and 1/0 mode. The BSR mode is used to set .or reset the bits in port C. The 1/0
mode is Further divided into three modes :
Mode 0 : Simple Input/ Output
Mode I : Input/Output with handshake
Mode 2 : Bi-directional 1/ 0 data transfer
The function of 1/ 0 pins (input or output) and modes of operntidn of 1/0 ports can be
programmed by writing proper control word in the control word register: Each bit in the
control word has a specific meaning and the s tatus of tht.-ose bits dt"CideS th~~ Function cmd
operating mode of the 1/0 ports.

7.1 Features of 8255A


1. The 825SA ls a w idely used, programmable, paraUd 1/ 0 d .'vic<..
2. It can be programmed to transfer data under various conditions, from simple 1/0
to interrupt 1/0.
3. It is compatible with aU lntel and mos t other microprocessors.
4. It is completely TIL compatible.
5. It has three 8-bit ports : Port A, Port B, and Port C. which are arranged in two
groups of 12 pins. Each port has an unique address, and data can be read from or
written to a port. In addition to the address as.'ligned to the thtcc ports. anoth('r
address is assignt."Cl to the control register into which cOntrol words arc written fur
progr-amming the 8255 to operate in various modes.
6. Its bit set/n...._-..et mode allow:; setting and rt."Setting of inrlividunl bit~ o( r\1t1 C.
(7 - 1)

Copyrighted material
Mlcroproceooonl and Interfacing 7 - 2 8255 PPI (Programmable Peripheral interface)

7. The 8255 can operate in 3 I/ 0 modes : (i) Mode 0, (ii) Mode I, and (iii) Mode 2.
a) In Mode 0, Port A and Port B can be configured as simple 8-bit input or output
ports without handshaking. The two halves of Port C can be progtammed
separately as 4bit input or output ports.
b) In. Mode I, two groups each of 12 pins are formed. Group A consists of Port A
and the upper half of Port C while Group B consists of Port B and the lower half
of Port C. Ports A and B can be programmed as 8-bit Input or Output ports with
thtee lines of Port C in each group used for handshaking.
c) In Mode 2, only Port A can be used as a bidirectional port. The handshaking
si!lMis are provided on Ave lines of Port C (PC, PC, ). Port B can be used in
Mode 0 or in Mode I.
8. All l /0 pins of 8255 has 2.5 mA DC driving capacity (i.e. sourcing current of
2.5 mA).

7.2 Pin Diagram


Fig. 7.1 shows the pin diagram of 8255.

P.Ao 40 PA,
PA, 39 PA,
PA1 38 PAo

PAo 37 PA,
R5 36 \VR
Cs 35 RESET
GNO 34 Do
A, 33 o,
Ao 32 02
PC7 31 o,
USSA
PC6 30 o,
PC5 29 Ds
PC4 28 o.
PC0 27 0,
PC 1 26 Vcc(+5 V)
PC2 25 PB7
PC3 24 PB8
Pao 23 PB5
PB 1 22 Pa,
PB2 21 PB3

Fig. 7.1 Pin diagram of 825SA


Copyrighted material
Microprocessors and Interfacing 7 .. 3 8255 PPI (Programmable Peripheral Interface)

Pin Symbols Function

D0.0, (Dala B<Js) These bi-directional, tri-state data bus tines are connected to tho system
data bus. They ere used to transfer data and control word frcm
mlcroPf'QCe$sor (8065) to 8255 or 10 receive data or status word from 8255
to the 8085.
PAo-PA7 (Port A) These 8-bit bi-directional liO pins are used to send data lo output device
end to receive daca from ilput <fErolioe. It ~~ et an 8--bit data output
latch/buffer, when used In outpll'l mode and an 8-blt data Input buffer, when
used in input mode. .
PB0-PB7 (Port B) These S.bit bi-directional liO pins are used to send data to output device
and to recefve data from k'lput dcwloe. It fi.rlctlons as an 8bft date, ovtpU'I
latchlbutfer when used in output mode and an 6-bit data I~ buffer. when
used in input mode.

J>Co.PC, These &.-bi1 bl-dlrecdonal lfO pins are divided Into two groups PCt.
(~.PC.0) and I:.Cu (PCrPC4). These groups indMdualy can transfer data
., or out when programmed for simpae l/0, and used as handshake signals
when programmOd for hancbtlab or bi-directiOnal modes.

RD (Read) When this pin Is tow. the CPU can read the data In lhe ports or the saatus
word, through the data buffer.
-WR {Write) VYhen this input pin i s tow, the CPU can write data on the pot'IS 0t in the
control regGter through the data bus buffer.
-
CS (ChiP 5elect) This is an active kJw input Which can be enabled for data transfec' opetatlon
between lhe CPU and the 8255.

RESET This Is an activo high i"Put used to reset 8255. When RESET k'lput Is high,
the control register i s cleared and al lhe ports are set to the input mode.
U$U811y RESET OUT signal ffom 8085 Is used to reset 8255.
Ao and A 1 These Input signals along wftll RD and WR Inputs oonVol the selection ol
the controlfstalus w01d regislers Of 2!2! q!_lhe th~. Tabie. 7.1.
summarizes the status of Ao ,
A 1, CS, RD and WR to acceu the con1Jol
wordfporls. Ao and A 1 are generally connected~A 1 pins of the
addreu bvs: the 8255 therefore occupies four locations in the

110 "'"""

Ao
" RD WR cs Operation

Input (Rta<f) ~radon


0 0 0 1 0 Por1 A to Data Bus
0 1 0 I 0 Pori 6 to Data Bus
I 0 0 1 0 Pon C to Oa1a -Bus
Output (Write) Operation
0 0 I 0 0 Data Bus to Port A

0 I I 0 0 Data Sus to Port B

I 0 I 0 0 Data Bus to Port C

I I I 0 0 Data Bus to COntrol Register

Copyrighted material
Microprocessors and Interfacing 7 4 8255 PPI (Programmable PerlpMral...-rface)

DI!Nble Function
X X X X 1 Data Bus TI'IStated
1 1 0 1 0 Illegal Cond-

' X 1 1 0 Dati Bus Trt-stated


Table 7.1 Port and register saleC1 signals summary

7.3 B lock Diagram


Fig. 7.2 shows the internal block diagram of 8255A. It consists of data bus buffer.
oontrol logic and Group A and Group 8 controls.

I I
,_J P.

POWER{-
suPP\.IES -
5V
GNO
- GROUP
A
CONTROL
GROUP A
PORTA
(8)
r
I
GROUP A
PORTC
Upper
BIOtRECTIONAL (4)
DATA BUS
o,..o, r
DATA
BUS
BUfFER 8BIT
INTERNAL GROUPB PCL
DATA BUS PORT O
Lower
.
(4)
I-
_I
Rll
WR READ/ GROUP GROUP S PB
WRITE PORTS
S

RESET
""A, CONTROl.
LOGIC -
CONTROl. (8)
I-
p
L...r.__
I I
t:1; l

Fig. 7.2 Block diagram of 8255A

Copyrighted material
Hidden page
Mluoproc. .sors and Interfacing 7 6 8255 PPI (Programmllble Pertphenlln...,_)

I. Outputs are latched. 2. Inputs are buffered, not latched.


3. Ports do not have handshake or interrupt capability.
Mode 1 : tn puiiOutput with handshake
In this mode, input or output data
transfer is controlled by handshaking
Do1a Bus signals. Handshaking signals are used to
transfer data between devices whose data
STll
Computer Printer transfer speeds a re not same. For exampleJ-
:ll:R compute:r can send data to the printer wflh
'"'~v large speed but printer can't accq>t data
and print data with this rate. So computer
Fig. 7.3 Data transfer betwe&n computer has to send data with the speed with which
and printer us ing handshaking signals printer can accq>t. This type of data !<ansfer
is achieved by using handshaking signals
alongwith data signals. Fig. 7.3 shows data transfer between computer and printe.r using
handshaking signals.
These handshaking signals are used to teU computer whether printer is ready to accept
the data or not. If printer ls ready to accept the data then alter sending data on data bus,
computer uses another handshaking signal (STB) to tell printer that valid data s available
on the data bus.
The 8255 mode 1 which supports handshaking has following fea tures.
J. Two ports (A and 8) function as 8-bit 1/0 ports. They can be configured either as
input or output ports.
2. Each port uses three lines from Port C as handshake signals. The remaining two
lines of Port C can be used lor simple 1/0 functions.
3. Inp ut and output data are latched.
4. Interrupt logic is supported.
Mode 2 : BI-directional 110 dato transfer
This mode allows bi.-dircctional data transfer (transmi~ion and reception) over a single
8-bit data bus using handshaking signals. This feature is available only in Group A with
Port A as the &-bit bi-directional data bus; and PC,- PC, are used for handshaking
purpose. In this mode, both inputs and outputs are latched. Due to use of a single &-bit
data bus for bi-directional data transfer, the data sent out by the CPU through Port A
appears on the bus connecting it to the peripheral, only when the peripheral requ ests it.
The remaining lines of Port C i.e. f'CoPC2 can be used for simple 1/0 functions. The Port
B can be programmed in mode 0 or in mode 1. When Port B is programmed in mode 1,
f'CoPC2 lines of Port C are used as handshaking signals.

Copyrighted material
MlcloprocH oora ond lnt.rfacing 7 7 8255 PPI (Prograrnm- P..-lpherll lnt.rt.ce)

7.5 Control Word Formats


A high on the RESET pin cauS<S all 24 lint.'S of the three 8-bit ports to be in the input
mode. All flip-Oops are cleared and the interrupts are reset. This condition is maintained
even after the RESET goes low. The ports of the 8255 can then be programmed for any
other mode by writing a single control word into the contnll register, when required.
For Bit Set/Reset Mode
Fig. 7.4 shows bit set/reset controJ word forma t.

l o l ~l~l~ l ~l~lo, l ~ l
L L L I SIT SET/RESET
1 SET
~ ORESET
Don't c:are

SIT SELECT

0 I 2 3 4 5
1
0 I 0 I 0 I 0 I Bo
0 0 I I 0 0 1 I a,
0 0 0 0 1 1 1 1 a,

BIT SET/RESET FlAG


0 AC11VE

Fig. 7 A Bit set/reset control word fonnat

The cight pos.<tibte combination.~ of the s tates of bits 0 3 -B1 B1 8 0 ) in the Bit
01 (
Set-Reset formllt (BSR) determine particular bit in I'C. . PC1 being set or reset as per the
5tatus of bit 0 0. A SSR word is to be written for each bit that is to be set or r~t. For
example, if bit PC, is to be set a..nd bit PC,. is to be reset, the appropriate BSR words that
will h.tve to be lo.,ded into the control register will be, OXXXOIII and OXXXIOOO,
respectively, where X is don't care.
.
The BSR word can also be used for enabling or disabling interrupt signals generated
by Port C when the 8255 is programmed for Mode 1 or 2 OJX><ation. This is done by
setting or resetting the associatt."<i bits of the interrupts. This is described in detail in nex-t
section.
For I / O -
The mode definition format for 1/0 mode is s hown in Fig. 7.5. The control words for
both. r.oode dcli.nition and Bit SctR~t arc loodcd into the s.une control register, with bit
0 1 used for spt.'Cifying whether the word loaded into the control register is a .._mode

Copyrighted material
Microprocessors' and Interfacing 7 8 8255 PPI (PrOgrammable Perlpherallntofface)

1 o. o, o, o, 02 01 Do

I I GROUPS
PORT C (LOWER)
1 INPUT
O=OUTPUT

PORTS
1 INPUT
OOUTPUT
MODE SElECTION
O MOOEO
1 MOOE1

GROUP A
PORT C (UPPER)
1 INPUT
O=OUTPUT

PORTA
I= INPUT
O=OUTPUT

' MOOE SELECTION


OOMODEO
01 = MODE I
I X= MODE 2

MOOE SET FLAG


11ACTIVE

Fig. 7.5 8255 Mode definition format

definition word or Bit Set-Reset word. lf 0 1 is high. the word is taken as a mode
definition word~ and if it is low, it is taken as a Bit Set-Reset word. The appropriate bits
arc set or reset dt:"pCnding on the type of operation desired, and loaded into the control
regisler.

1. Port A : Simplt i11p111


2. f>ort 8 : Simp/" output
3. Port CL : Output
4. Port Ct... : lupttl
Assume aJdreso; of tilt control twrd rt-yi:>ltr of 8255 is dJH

Copyrighted material
-
Micropi"OC4!Uors and lnt-clng 7-9

Solution :
8255 PPI (Programmabl P ..lpMral lnltlrf-)

1 0 0 1 1 0 0 0
l l L Port cl - Output
Pott 8- Output
ModeOPart 8 - Simpk! l/0
Port Cu input
Port A - Simple input
MOdeOPonA-Sim 110

Source proqr.a : MOV AL, 98H : t..oad control word


OUT 83H , AL ; send contro l word
,,... Example 2 : Wrilt a program to ir~itinUu 8255 in tlte cotJfigurati.OII j(iVt'" below :

1. Port A : Output tvitlr lzatrdslwkt'


2. Port 8 : Juput roillr Jwudsllakt'
3. Port CL : 011tp11t
4. Port Cu : I11p111
Assume addr,ss of tl1e coutrol word register of 8255 is 23H.
Solution :

1 0 1 0 1 1 1 0 =AEH

I I

PonA
Pon<;,
- -
L Pon c, Output
8
1 Pon B - HandShake

Mode 1 Port A - Handshake


I/O Mode

Source proqraa : MOV AL, O.Z\EH : Loa d conc~:ol word


OUT 2JH, AL ; Send control word
Program : Blink port C bit 0 of 8255.

Program S-ment :
Write a pn.lgmm to blink Port C bil 0 of the 8255. A~umc addn..---ss o( control word
r.'gisk>t ol 8255 L 83H. U:<e Bit Sell R..-..t mod<.

Copyrighted material
Hidden page
Mk:roproceooors and Interfacing 7 - 11 8255 PPI (Programmable Peripheral Interface)

7.6 8255 Programming and Operation

7.6.1 Programming In Mode 0


lhc Ports A, B and C can ~ configured llS simple input or output ports by writing the
appropriate control word in the control word register. In the control word~ 0 7 is set to '1
(lo define a mode set operation) and o,, o, and o, are all set to '0' lo configure aU the
ports in Mode 0 OJX"foltion. The slalus ol bits 0, , o,, 0 1 and 0 0 then detennine (refer 10
Fig. 7.5) whe~'l' the ro"""J'Jflding pori> are 1o be configur<-d as Input or Outpul.
For example in mode 0, II Port A and Port B are 10 operate ns outpul ports with Port
C lower as inpu~ and Port C upper oulpul. lhe conlrol word thai will ha lo be
loaded into lhe conlrol "'S"'""' will be folio""

81H

As mentioned earlier, this mode provide sinlple input and output operations for each
ol the tl\r.,., ports. No handshaking 1$ ""!lllrood, daln is samply writlen 10 or read from a
specified pori.
Input Mode : rig. 7.6 shows lhe liming diogram for mode 0 inpul mode.

Rll - - - - - - - 1
I
Input
---~

CS, A,.I\o _ __ _.

Fig. 7.6 Timing diagram for mode 0 Input mode

Afler initializnlion ol 8255 in the inpul mode 0, CPU can read dala through lhe in~
port by initiating read command with propct port address. Read command tti:tivates RD
signal. Upon activalion of RD sign.,l CPU reods lhe dnm from lhe sell'<:ted input port into
the CPU register.

0
Microprocessors and Interfacing 7 12 8255 PPI (Programmable Peripherallnterfece)

Output Mode : Fig. 7.7 shows th~ tinting di.-gram for mode 0 output mode.

WR- - - - - - " " ' 1 .

OrDo _ _____ _,X. . ._ ___,X..____


cs.,.,."" _ ___,X.._________,X..__
OU'Iput
- - - - - - - ->C
Fig. 7.7 Timing diagram for mode 0 output mode
After initialization of 8255 in the output mode 0, CPU can write data into the output
port by initiating write command with p roper port address. CPU sends data on the data
bus and upon activation of WR signal, data on the data bus gets latched on the selected
output port.
Mode 0 Configurations :

A B GROUP A GROUP B

o, o, o, Do PORT A PORT C
(Upper) PORT B PORT C
(Low.r)
0 0 0 0 OUTPUT OUTPUT 0 OUTPUT OUll'UT
0 0 0 1 OUTPUT OUTPUT 1 OUTPUT INPUT
0 0 1 0 OUTPUT OUll'UT 2 INPUT OUTPUT
0 0 1 1 OUTPUT OUll'UT 3 INPUT INPUT
0 1 0 0 OUTPUT INPUT 4 OUTPUT OUll'UT
0 1 0 1 OUTPUT INPUT 5 OUTPUT INPUT
0 1 1 0 OUTPUT INPUT 8 INPUT OUll'UT
0 1 1 1 OUTPUT INPUT 7 INPUT INPUT
1 0 0 0 INPUT OUll'UT 8 OUTPUT OUll'UT
1 0 0 1 INPUT OUll'UT 9 OUll'UT INPUT
1 0 1 0 INPUT OUll'UT 10 INPUT OUTPUT
1 0 1 1 INPUT OUll'UT 11 INP\IT INPUT
1 1 0 0 INPUT INPUT 12 OUll'UT OUTPUT
1 1 0 1 INPUT INPUT 13 OUTPUT INPUT
1 1 1 0 INPUT INPUT 14 INPUT OUTPUT
1 1 1 1 INPUT INPUT 15 INPUT INPUT

Copyrighted material
Mlcroproceuors and Interfacing 7 13 8255 PPI (Programmable Peripheral Interface)

7.6.2 Programming in Mode 1 (Input I Output with Handshake)


Both Group A and Group B can operate in Mode I, either together, or individually,
with each port containing an 3-bit latched Input or Output data port, and a 4-bit port
which is used lor control and status of the 8-bit port.
When Port A is to be programmed as an input port, PC, , PC, and PC, are used for
control. PC,. and PC7 ane not used and can be Input or Output, as programmed by bit o,
of the control word. When Port A is programmed as an output port, PC, , PC,, and Pc,
are used for control and PC, and PCs can be Input or Output, as programmed by bit O,,
of the control word.
When port 8 is to be programmed as an input or output port, PC.. PC1 and PC, ane
used for control.
Mode 1 Input Control Signals :

1. STB (Strobe Input) :


nus is an active low input signal for 8255 and output signal for the input device. The
input device activates this signal to ind_icate CPU that the data to be read is already sent
on the port lines of 8255 port. Upon activation of this signal 8255 loads the data from the
input port lines into the input bufler of that port.
2. IBF (Input Buffer Full) :
This is an active high output signal for 8255 and an input signal for input device. This
signal is generated by 82.55 in response to STB signal as an acknowledgment to input
device~ It also indicates to the input device that the input buffer is fuU and it is not ready
to accept next byte from the input device. Therefore input device sends data on the port
liMS only when IBF signal is not active. Tite IBF signal is deactivated when CPU neads the
data from input buffer of the respective port by activation of RD signal
3. INTR (Interrupt Request) :
This is a_n active high output signal generated by 8255. A 'high' on this output can be
used to interrupt the CPU when an input device is requesting service. The 8255 sets the
lNTR when STB signal is 'one. ffif signaJ is 'one' a_n d JNTE is 'one', indicating CPU that
the data from the input device is avaHablc in the input bulle-r. This signal is reset by the
falHng edge of the RD signal i.e. immediately after reading the data from the input buffer.
INTE (Interrupt Enable) flipflop is uS<.-'d to enable or disable INTR (lnterntpt request)
signal. H INTE Oipflop is set, the interrupt request is generated depending on the status of
STB and !BF signals. If !NTE flipflop is neset, the interrupt request is not generated,
a1lowing masking facility for the lntcrrupt.
Mode 1 : Port A Input Operation
Fig. 7.8 (n) s hows Port A as an input port along with the control word and control
signals (for handshaking with a peripheral). When the control word (as in Fig. 7.8 (a) is
loaded into the control register, Group A is configured in Mode 1 with Port A as an input

Copyrighted material
Microprocessors and Interfacing 7 - 14 8255 PPI (Programmable Peripheral Interface)

port. Port A can ilccept parallel d(lta from a peripheral (like a keyboard) and this datd can
be read by the CPU. The peripheral first loads data into Port by maldng the STB, input
low. This latches the data placed by the peripheral on the common data bus into Port A.
Port A acknowledges reception of data by making IBF, (Input Buffer Full) high. IBFA is
set when the STB"' input is made low, as shown in f ig. 7.8 (b).
MOOE ! (PORT A)

Conttol word
r----
' INTE r"'----
' PC
A o

'- - -- PCs

1 = INPUT
0 c OliTPUT

Fig. 7.8 (a) Port A In mode 1

m,,--,
'---____,J/
I

I~R --------J/'
Rn -------+--,." ) /'r/ _ _

o:-;:~ -<________,>---------------------
Fig. 7.8 ( b) Timing diagram for port A In mode 1

INTR, is an octive high output signal which can be used to interrupt the CPU so that
the CPU can suspend its current operation and read the data written into Port A by the
peripheraL INTRA can be enabled or disabled by the INTE, flip-flop which is controlled
by Bit Set-Reset operation of PC,. INTR, is set (if enabled by setting the INTEA flip-flop)
after the STBA has gone high again. and if !BFA is high.
On receipt of the interrupt, the CPU can be forced to read Port A. The falling edge of
the RD input resets !BFA and it goes low. This can be used to indicate to the peripheral
that the input buffer is empty and that data can again be loaded into it.

Copyrighted material
Microprocessors and Interfacing 7 - 15 8255 PPI (Programmable Perlpherallntorface)

Mode 1 : Port B Input operation


Fig. 7.9 shows Port B as an input por-t (when in Mode 1). The timing diagram and
operation of Port B is similar to that of Port A e-xcept that it uses d.iflt.lrent bits of Port C
for control. INTE6 is controUed by Bit Set/ Reset of PC,.
MODE 1(PORT B)

Control wo<
r----.,
PB,.PB0
~
I' INTE 'r---- PC2 1--1
0
~ s
t_,.,,_,___,!
I PC 1 f--t

~
PCo r- INTR6

Fig. 7.9 Port B in mode 1

If the CPU is busy with other system operations, it can rend data from the input port
when it is interrupted. Titis is often called interrupt driven l/0. However, if t1w CPU is
otherwise not busy with other jobs, il c-an continuously poiJ (read) the status word to
check fo r an IBF . This l< often caUed Program ControUed 1/0. The status word is
aca:ssed by reading Port C (A 1 A0 must be 10, RO and CS must be low). The s tatus word
fonnat when Ports A and B arc input ports in Mode 1, is shown in Fig. 7.10.
INPUT CONFIGURATION

o, o8 o5 04 o3 o2 o, o0
1/0 1/0 j1sFA I INTE.jiNTRAjiNTE6 j lsF6 j tNTRel

-L~----~----~' I I
GROUP A GROUP 8
Fig. 7.10 Mode 1 status word (Input)

Mode 1 : Output control signals

1. OBF (Output Buffer Full) :


This is an active low output signal for 8255 and input signal for the output device. The-
8255 activates this signal to indicate output device that data is available on the output
port. Upon <~cti vation of 06F sib"11al, ~ut device reads data from the output port ~
acknowledges it by ACK signal. The OBF signal is activated at the rising edge of the WR
signal and de-activated al the falling edge of the ACK signal.

Copyrighted material
Microprocessors and Interfacing 7 -16 8255 PPI (Programmable Peripheral Interface)

2. ACK (Acknowledge Input) :


This is an active low input slgna1 {or 8255 and output signal for the output device. The
output device generates this signal to indicate 8255 that the data from port A or Port B has
h<N>n accepted.
3. INTR (Interrupt Request) :
This is an active high output signal generated by 8255. A 'high' on this output can be
used to inte.rrupt the CPU when an output device has accepted data transmitted by the
CPU. The 8255 sets the INTR when ACK signal is 'one', OBF is 'one' and lNTE is 'one',
indicating that the output device is ready to accept next data byte This signal is reset by
the falling edge of the WR sign.1l i.e. immediately after sending the data to the output
port.
INTE (Interrupt Enable) Oip-Aop is used to enable or disable INTR (Interrupt Request)
signal. If INTE fli?"Aop is set. the interrupt request is generated depending on the statu.~ of
ACK and OBF signals. If INTE flip-flop is reset, the interrupt request is not generated,
allowing masking facility for the interrupt.

Mode 1 : Port A output operation


Fig. 7.11 (a) shows Port A configured as an output port (When in Mode I) along with
the control word and contro1 signals (for handshaking with a peripheraJ). When the control
word (as in Fig. 7.11 (a)) is loaded into the control register, Group A is configured in
Mode 1 with Port A as an output porl Tile CPU ca.n send data to a peripheraJ (like a
di>l'lay device) through Port A of the 8255.

MODE 1jPORT A)

Control word
, - - - - - I PC7

1 0 1 0 t/0 -----..
INTE j PCs
Il.....A
_ _j
r'--;
PC 5, PC4
' - - - 1 = INPUT
0 OUTPUT

Fig. 7.11 (a) Port A In mode 1

Copyrighted material
Microprocessors and Interfacing 7 - 17 8255 PPI (Programmable Peripheral Interlace)
vm -----._

l.rrR:r-----""""

~.~------------~~

DATA:- - - - - - - - - - - -
OUTP~~ PAEv1ous DATA X..____N_e._v_o_r__ _ __
PAoPA7

FJg. 7.11 (b) Port A In mode 1 (Output)


The OBFA output (Output Buffer full) goes low on U,., rising edge of the WR signal
(when U,., CPU writes data into the 8255). The OBFA cutput from 8255 can be used as a
strobe input to the peripheral 10 latch the contents of Port A. The peripheral responds to
the receipt of data by making the ACK, input of the 8255 low, thus acknowledging that it
has """'ived the data sent by the CPU through Port A. The ACK, low sets the OBF
signal, which can be polled by the CPU through OBFA of the status word to load the next
data when it is high again.
INTRA is an active high~ut of the 8255 whkh is made high (if the associated
INTE, nip-flop is set) when ACK, is made high again by the peripheral, and when OBFA
goes high again (see timing diagram in Fig. 7.11 (b)). It can be used t~terrupt the CPU
whenever the output buffer is empty. It is T<'Set by the falling edge of WR when the CPU
writes data onto Port A. It can be enabled or disabled by writing a ' 1' or a '0' re.'lpectively
to PC6 in the BSR mode.

Modo 1 : Port B ou1put operation


Fig. 7.12 s hows Port B as an output port when in Mode 1. The operatjon of Port B is
similar to that o( Port A. lNTRA is controlled by writing a t or a '0' to PC~ in the BSR
mode.
MODE 1(PORT 8)

Control WOtc:t

o,. De o, D4 o1 ot 01
I c><lXI><JXJ I lXl I 0

INTR8

Fig. 7.12 Port BIn mode 1 (Outpu1)


Copyrighted materia<
Microprocessors and Interfacing 7 - 18 8255 PPI (Programmable Peripheral Interface)

Th" s t.11us word is acccsstd by issuing a Read to Pon C. The forma t of the s tatus
word when Port$ A <~n d B are Output ports in Mode 1 is shown in Fig. 7.1 3.

o, o, o,

I I L-~~~1
I I
GRD\JP A GRD\JP B

Fig. 7.13 Mode 1 status word (Output)

7.6.3 Programming in Mode 2 (Strobes Bi-directional Bus 1/0)


When the 8255 is operated in Mode 2 (by loading the appropriate control word), Port
A can be used as ., b1 d ircctional 8-bit 1/0 bus using for handshaking. Port 8 can be
4

pn..') grammed i l''l Mode 0 o r it\ Mode 1. \--vhen Port B is programmed in mode 1, PC0 - PC 2
lines of Port C are used as handsh..'lking signals.
Fig. 7. 14 s hows the control word that should be loaded into the control port to
config u re 8255 i l''l Mode 2.

1 1
X IX X 110 110 110

PC,.-f'Co
1 = INPUT
0 OUTPUT

PORTS
1 = INPUT
0 0\JTPUT

GRD\JP B MODE
O MODEO
1MODE 1

j Fig. 7.14 Mode 2 control word

Mode 2 : Control signals


INTR (Interrupt Request) : A 'high' on this output can be used to interrupt the CPU
I (or input or output opcratior,s.
II

Copyrighted material
Mlcroprocenors and Interfacing 7 -19 8255 PPI (Programi1UIIJM Periphefallnterfeee)

Output Control Signals :

OBFA (Output Buffer Full)


This is an active low output which indicates that the CPU has written data into
Port A.

ACKA (Acknowledge)
This is an active low input signal (generated by the peripheral) which enables the
tri-state output buffer of Port A and makes Port A data available to the peripheral. In
Mc:x:J(! "" : Jrt A outputs are in tri-state until enabled.
INTE 1
This L< the Rip-flop associated with Output Buffl?r Full. INTE I ean be used to enable
or disable the interrupt by setting or resetting PC in the BSR Mode.
Input Control Signals :

STB (Strobe Input)


This is an active low input signal which enables Port A to latch the data available! at
its input.
IBF (Input Buffer Full Flip-Flop)
This is an active high output which indicates that data has been loaded into the input
latch of Port A.
INTE 2
This is an Intemtpt enable flip-flop associated with Input Buffer Full. It can be
controlled by setting or resetting PC, in the BSR Mode.
Mode 2 : Port A operation.
Fig. 7.15 shows rort A and assodotcd
control signals when 8255 is in Mode 2.

)-
J >-E f--tHTF(A Interrupts are generated for both output and
input operations on the same INTRA (PC,)
PA,-PAo
,., r--
PC,
line.

Status Word In Mode 2


1--Cll!l'.
( - IHTE f- The status word for Mode 2 (t'l cccs.~d
r- Pet '--Xl:R, q
' by reading Port is shown in Fig. 7.16.
IHTE
2
~
- f-
PC, -m. 07 OJ of the status word carry informa tion

about OBF,, INTE1 ,IBF, . JNTE2 , INTR, .
The status of the bits 0 1 0 0 depend on the
!---< ""' + o
._ f---IBf"A
PCrPCo
3
mode setting of Group B.
progrt'lmmed in Mode 0, 0 2 0 0 are the
JJ B is

same as PC, - PCo (simple 1/0 ); however if


Fig. 7.15 Mocle 2 operation

Copyrighted material
Microprocess ors and Interfacing 7 - 20 8255 PPI (Programmable Peripheral Interlace}

B is in MOOc 1, 0 2 - 0 0 carry information about the control signals for Port 8 (as in
Fig. 7.10, or Fig. 7.13), deptmding upon whether Port B is an Input port or Output port
respectively.

Dz D,
Imil' I
A ltH E 1 I
I
GROUP A GROUP B
(DEfiNED BY MODE 0
OR MODE 1 SELECTION)

Fig. 7.16 Status word for mode 2

Mode Definition Summary

MODE 0 MODE 1 MODE 2

IN OUT IN OUT GROUP A

-..
ONLY
PA, IN OUT IN OUT
PA, IN OUT IN OUT ++
PAz IN OUT IN OUT ++
PA3 IN OUT IN OUT
PA,
PAs
IN
IN
OUT
OUT
IN
IN
OUT
OUT ...
++

~~
IN OVT IN OUT ++
IN OVT IN OUT ++
MODE 0 MODE 1 MODE 2

IN OUT IN OUT GROUP A ONLY

--
IN OUT
~~
IN OUT
IN OUT IN OUT
p~
P63
IN
IN
OUT
OUT
IN
IN
OUT
OUT
-- ModeO
Ot

---
PB, IN OUT IN OUT Mode1
PB5 IN OUT IN OUT Only
PB6 IN OUT IN OUT
PB, IN OUT IN OUT -
~
IN OUT INTR, INTR8 110
IN OUT IBF8 08F8 1/0
~ IN OUT STS, ACKS 1/0

~
IN OUT INTRA INTRA INTRA
IN OUT STB 110 STBA
PC5 IN OVT 18fA 1/0 IB~
PC8 IN OUT 110 AC~ AC
PC7 IN OVT 1/0 08 . oB?.

Copyrighted material
Mlcrop<ocesaors and l nterfaclrig 7 21 8255 PPI (Programmable Peripheral Interface)

7.7 Interfacing 8255 to 8086 In 1/0 Mapped 1/0 Mode


The 8086 has four special ins tructions IN. INS. OUT, tm.d OUTS to tramofer data
through ~~e input/output ports in 1/0 mapped l/ 0 sy>tem. M/ 10 signal is always low
wlwn 8086 is executing these instructions. So M/ 10 signal is used to generate separate
addresses for, memory and input/ output. Only 256 (2 8 ) l/0 addresses can be generated
when direct addressing method is used. By using indirect address method this range can
be extended upto 65536 (2") addresses.
"'" 7.17 sho"" the interfacing of 8255 with 8086 in l/0 mapped l/0 technique. Here,
RD and WR signals are activated when M/ 10 signal is low, indicating l/0 bus cycle. Only
lower data bus (D0 - D1 ) is used as 8255 is 8-bit device. Reset out signal from clock
generator is connected to the Reset signal of the 8255. In case of interrup t driven l/ 0
JNTR signal (PC, or PCo) from 8255 is connected to INTR input of 8088.

Do
~~<
o, o,
A PA, "-

A, Ao " PAr v
>
... A,
A PBo
Milt!
Ri5
Ao
' RO

8255
, PBr

.... PCo ....


-1 VIR
WR " PCr v
Reset
Reset cs
,___ T

Fig. 7.17 UO mapped 110


UO Map :

Port I control Register Addren nnea Add., ....

A, At As At "' "' "' .Ao


Port A 0 0 0 0 0 0 0 0 OOH
Port B 0 0 0 0 0 0 1 0 02H
Pone 0 0 0 0 0 1 0 0 04H
Con1rol tegi1ster 0 0 0 0 0 1 1 0 06H
Note : It is assumed that the direct addressing is used.

Copyrighted material
Microprocessors and Interfacing 7 22 8255 PPI (Programmable Peripheral Interface)

7.8 Interfacing 8255 to 8086 in Memory Mapped 1/0


In this type of 1/0 interfacing. the 8086 uses 20 addres.~ linL'S to identify an I/0
device; an l/0 device is connected as if it is a memory register. The 8086 uses same
control signals and ins tructions to <~ ccess 1/0 as those of memory. Fig. 7.18 shows the
interfacing o( 8255 with 8086 in memory rnapp..-:.d 1/0 tech1\iquc. Here RD and WR signals
arc activated when M/10 signal is high. indicating memory bus cycle. Address lines
A 0 A 1 are used by 8255 for inlemal decoding. To get absolute address, all remaining
address lines (A3 A 19) a re used to decode the address for 8255. Other signal connections
are same as in l /0 mapped 1/0.

Do Do

.,., ....,
0, D,
Ap...

I'-. ..., >


~ -r """
PB, . >

....., WR
..
A15

--1
RO

I'IR
8255
~

APC0

"~' PC
7
>
.... .. Reset CUI
R...,
cs
.., 5

....,,
A,

A, ' )
.......'
..
...."'
..
...
Fig. 7.18 Memory mapped 1/0

.. .. ... .. ... ... ... ... ....


1/0 Map :

Rtglat ..... .... .... .... .... Au .... .... .... AM .. ddres

P<>ttA 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 OOOOOH
P<>tt B 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 00002H
Po"C 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 00004H
Control rcg;s.ter 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 00006H

Copyrighted material
Hidden page
Mlcroproeosson and Interfacing 7 24 8255 PPI (Programmable Peripheral interface)

The IC 1408 cons i<IS of reference curreot amplifier, an R/2R ladder and eight high
speed current sw itches. It has eight input dato lines A1 (MSB) through As (lSB) which
control the positions of current switches.
It requires 2 mA reference current for full scale input and two power supplies
Vee = + 5 V and Vee a=- 15 V (Vu can range from - 5 V to- 15 V).
The voltage Vro:f and resistor R14 determines the total reference current source and Ru
is generally equal to R1.- to match the input impcda\CC ol the reference current amplifier.
Fig. 7.20 shows ' typical circuit for IC 1408.

'The output cu.rrent 10 can be given as

I = V~r (~ + A2 + A l + A +A, + A, + A , + A 11 ) ( 1)
R 14 2 4 8 16 32 64 128 2.16 ...

Note : lnput At through As can be either 0 or 1. lherefore.. fo r typical circuit full scale
ciJ.ITf!Jlt can be given as,

= 2mAx255 = A
256 1992
. m

Copyrighted material
Microproc.Uol'8 and Interfacing 7 25 8255 PPI (Programmable Perlpherlllnterface)

It shows that the full scale output current is always I lSB less than the reference
current sour o( 2 rnA. This output current is converted into voltage by I to V converter.
The output voltage for full scale input can be given as
V0 = 1.992x 2.5 K

4.98 v
Note : The arrow on the pin 4 shows the output current direction. It is inward. This
means that lC 1408 sinks current. At (0000 0000), binary input it sinks zero current and at
(11111111)2 binary input it sinks 1.992 mA.
The circuit shown in the Fig. 7.20 gives output in the unipolar range. When digital
input is OOH, the output voltage is 0 V and when digital input is FFH (11111111)2, the
output voltage L~ + 5 V. This drcuit can be modified to give bipolar output.
Fig. 7.21 sho\~o's the circuit for giving output in the bipolar range. Here, resistor R8
(5 K) is connected between V"' and the output terminal of IC 1408. This gives a constant
current source of 1 mA.

Vee
+5V

5 13 R,.
A, +5V
6
14 v,.,
A2 2.5 K

8-bit
d igital
1
8
9
A3
~
A$ JC 1<108
1 mA
'l 5K
RB - R,
SK

- .
input
4
10 A
Ao
11
~
Ar
12
Ao . ..1.
15 -:;:"
163 1 2 Ros
15 pF 2.5K


v "
Fig. 7.21 Interfacing DAC in tho bipolar range
The circuit operation can be observed for three conditions ;
Condition 1 : For binary input (OOH)
Whet. binary input is OOH. the output current fo ttt pin 4 is zero. Due to this current
flowing through R6 (I mAl flows through R1 giving V0 = - 5 V.

Copyrighted material
Microprocessors and Interfacing 7 26 6255 PPI (Programmable Peripheral Interface)

Condition 2 : For binary input SOH


Wh!!n birutry input is 80H, the output current 10 at pin 4 is 1 mA. By applying KCL a t
node A we get,
- l u + l~> +l r = 0

Substituting va lues o f 18 and 10 we get,


-{1 mA) + (I mA) + 11 0

11 0

and therefore the output voltage is zero.


Condition 3 : For binary input FFH
When binary input L< FFH. the output current 10 at pin 4 is 2 mA. By applying KCL at
node A we get,
- 10 + 1u + lr 0
Substituting values of 18 and 10 we get,
- (1 mA) + (2 mA) + 11 = 0

1, = -lmA

Therefore, the output voltage is + 5 V. In this way, circuit shown in the Fig. 7.21 gives
output in the bipolar range.
Important Electrical Characteristics for IC 1408
Re ference current : 2 mA
Supply voltage : + 5 V Vee and - 15 V VEE
Setting time : 300 ns
FuJI scale output current : 1.992 mA
Accuracy : 0.19%

7.9.2 DA C0830
The DAC0830 is an advanced CMOS 8-bit DAC designed to interface directly with the
8080, 8048, 8085, 280, and other popular microprocessors. A deposited silicon-<:hromium
R-2R resistor ladder network divides the reference current and provides the circuit with
excellent temperature tracking characteristics (0.05% of Full Scale RaJl.b~ maximum linearity
error over temperature). The circuit uses CMOS current switches and control logic to
achieve low power consumption and low output leakage current errors. Special circuitry
provides TTL logic input voltage level compatibility.

Copyrighted material
Mlctoprocessors end lnterfaclng 7 - 27 8255 PPI (Progrsrnmll>le PeripherallnterfKe)

Double buffering feature allows this OAC to output a voltage corresponding to one
digitnl word while holding the nex t digital word. This permits the simultaneous updating
of any number of DACs.
The DAC0830 series (0AC0830/DACOB3 1/ DAC0832) ore the 8-bit members of o fomily
of microprocessor-mmpatible DACs. For applications demanding higher resolution, the
OACl OOO series (!O-bits) and the 0AC1208 and OAC1230 (12-bits) are available
alternatives.
Features
Doubl.,.buffcrecl, singl.,.buffured Or flow-through digital data inputs.
Easy interchange and pin-compatible w ith 12-bit DAC1230 series.
Direct interface to all popular microprocessors.
Built-in fadJity fo r zero adjustment.
Works with l: 10 V reference voltage.
Can be used in the voltage switching mode.
Logic inputs whkh meet Til voltage 1eve1 specifications..
Operates ..STAND ALONE.. (without up) if desired.
Available in 20-pin smaJl-outline or molded chip carrier package.
Pin Diagrams
Fig. 7.22 shows ll~ pin diagram of DAC0830. The function of each pin Lo; explained in
Tobie 7.2.

- 1. 20 Vee
WR, - 2 19 ILE(BYTE11BVTE2)

GND 3 18 WR2

DC, - 4 17 XFER
0'2 - 5 16 01,
0 11 - 6 15 ot,
D'<I(LSB) 7 14 ot6
v., - 8 13 Dt 7 (MSB)

RF8 - 9 12 1oun

GND 10 11 loun

DAC0830

Fig. 7.22

Copyrighted material
Microprocessors and Interfacing 7 - 28 8255 PPI (Programmable Peripheral Interface)
- .
Controt Signals (All contrm slgn l level .c:tuated)

cs ; Chip Select (adi\'e low).. The Bin combination with ILE Y"ill enable WR1.
ILE : lnpu1 Latch Enable (acttve high), The ILE In combination with CS enables WR1. -
WR 1 : Write 1. The octM! low WRJ is used to load the digjtal .!!i!Ut data bita (01) into the
loput latch. The data In the oput latCh Is latChed when WRo Is high. To update the
input latch- ~ and WR. must be lOw while ILE is high.

WR~ : Write 2 (active low}. This $lgnal, in combination with XFER, causes the a.bit data
which ts aw!labfe In the i~ut latch to transfer to the OAC reg.lster.
XFER: Transfet control signal (active low). The XFER will enable WR, .

Table 7.2 Pin description

Other Pin Functions

D \)017 : Digital Inputs. 0 10 Is the least significant bit (LSB) and 0 17 Is the mos1 slgnlllcant bit
(M SB).

101/TI : DAC Current Output 1. lour 1 is a maximum for a digital code of all 1's In the OAC
register, and is zeto 101 all Its in OAC register.
lOUT> : OAC Cw rent Output 2. Ioun lour2 constant (I full scale for a fixed reference
'""tage).

R., : Feedback ReslstOt. The feedback resistor is provtded on the IC chip few use as the
Shunt feedbaCk resJstor tcw the extemal op-amp which is used to provide an output
voltage for the DAC. This on-chip resistcw should ahvays be used (not an external
resistor) since it matches the resistors Which are used in the orw;hl p R2R ladcter
and tracks these reslstcn over tet'J1)etlture.

VREF : Reference Voltage Input This input connects an external preds.Jon voltage SQt.II"'e
to the internal R2R ladder. VR~t can be selected over the range ot +10 v to
-1 0 v . This is also the analog voltage Input for a ~uadrant multiplying OAC
application.

Vee: Digital Supply Voftage. Thi s is the power supply pin for the part v cc can be from
+5 Voc to +15 Voc. Operation is optfmum fof + 15 Voc.

GNO: The pin 10 'o'oltage must be at the same ground poten tial as loun and Iou12 for
c...-rent swftchlng appllcaUon$. Any dltference of potential (V08 pin 10) will result in
a linearity chaoge ot

Vo;: ,
1
For example. if VRF a 10 v and pin 10 ls 9 mv offset from lovT1 and
1~. the linearity change wil be 0.03%. Pin 3 can be offset t 100 mv with no
linea ty Change. but tne logic loput ll'<eshotd wiM slllft.

Functional Block Diagram


A most unique characteristic of this DAC is that the 8-bit digital input byte is
double-buffered. This means that the data must transfer through two independently
controlled 8-bit latching regLtcrs h<!forc bt!ing applied to the R-2R ladder network to
change the analog output. The addition of a second regL.~ter allows two useful control

Copyrighted material
Hidden page
Microprocessors a.n d Interfacing 7. 30 8255 PPI (Programmable Peripheral Interface)

ne TO l.OGIC 1 IF NOT NEEOEO


Fig. 7.24 Controlling muUiple DACs

DATA

!:S 1
\ I
WIIT & Wll2 1

~
ll.E LOGIC ~1
\
--
~n.PIA'-Ich .............

Fig. 7.25 Timing diagram


The ILE pin is .tn active high chip select which can be decoded from the oddrcss bus
as a qualifier fo r the norma l CS signal generated during a write operation. This can be
used to provide a higher degree of decoding unique control signals for a particular DAC,
and thereby cre~te a more efficient addressing scheme.

Copyrighted material
Hidden page
Hidden page
1:

,
.c
...
tl Vee
f
~
a
'
'
:10K
"S'
;. Do Do
PA, 4
PA, 3 ILE ~
!!.
.,"
D,
g;D,
D,
D, ~~ 1
"""
oe,
oo,
oe, ~
o; PA, oe, ~
WID
RD ~
~ Ao
D,
D,
D,
D,
D,
D,
PAo
~~ ...
oe,
oe, + 12V
...
~
VRF +V1e4 (10 V)
WR
0, P8o
P81 XFER "'"'
0
g
R6
ViR ~ ""
loo; ~
AI PB, "'"'
:::
3
;;- ..... A2
RESET
cs
PS.
PS.
PB,
--,.
cs
w., Dri>glon
pair "
:l!
-:;;
c;
" .. 8 A

I!
2 OGNO A.GNO
A, -i>-f
~
2
DAC 0830 "Analog
5
..., Ground
~
- o;gital
c: .. Gr""""
:;
... "
0
0
"0
'<
N
g: I
l
~
cO.
::r
~
3

*"'
"'
Hidden page
Hidden page
Microprocessors and Interfacing 7 - 36 8255 PPI (Programmable Peripheral Interface)

CLKOUT _ CLK IN
RO
RO
ViiR -WR
IN+
Microprocesaor AOC ANALOG
Address INP\IT
Address OOOOdor Cs 01031
System 01041 ~
0805
INT ii'fl'R
~
080
DATA BUS
087

Fig. 7.32 Interfacing of ADC 08031080410805 with microprocessor system

Interfacing the ADC 08031080410805 to 8088 Microprocessor


Fig. 7.33 shows the interfacing of AOC 0803/0804/0805 to the 8086 microprocessor.
Here, converted digital data is read through data bus. The address ts decoded using 1/0
mapped 1/0 technique. As shown in the Fig. 7.33, adpress for AOC is SOH. The Fig. 7.34
shows the timing diagram of ADC operation. The conversion starts when CS and WR
signals go low. The end of conversion is indicated by INTR output of the AOC. The iNi'R
output goes low after conversion is over. Therefore~ INTR signa] is polled through data
bus by enabling a buffer to detect the end or conversion. Once the conversion is over, the
digital data is read by activating l/0 read command. This is illustrated in the following
procedure.
(S..>e Fig. 7.33 and 7.34 on next page)

; Procedure to read data from AOC 0803/0804/0805

READ PROC NEAR


OUT BOH ,AL ; Start convers i on
AGAIN : IN AL, 82H Read INTR
AND AL,80H Check INTR
JNZ AGAIN Repeat until INTR 0
IN AL, SOH Read digital data i n AL
RET
READ ENDP

Copyrighted material
Microprocessors and Interfacing 7 37 8255 PPI (Programmable Peripheral Interface)

A IN Analog input
Do Dllo
Dr To DSr
IN-
Dr -!-
. Rii

-
iOR ClKR
R(10 K)
iO ClK
C{150 pF)
:f.
.,.
~ MR
REF/2 VREF
Ao- A Yo 1>-
A, - B D v. Cs AGNO
A,- c E
c
0 />DC0804
.!-
A,- G, D
E
=I / G2 R

Ar - G
'
741 38

Fig. 7.33 Interfacing of ADC 0803/0B<WOBOS to 8086

\\.....;__.J/
INTR ---...;J~ Busy \'----+- - - -
~ ----~------~\~~!
Start of conversiOn - .
'
Read data

Fig. 7.34 Timing diagram

Interfacing ADC 08031080410805 to 8086 using 8255


Fig. 7.35 shows the interfacing of ADC 0803/0804/0805 to 8086 using 8255. Here,
port ~of 8255 is used to read digital datll !Tom 8255. The start of conversion signal (WR
and CS = low) generated using port 8, PO, pin. The end of conversion is detected by
polling JNTR pin through !'Co The procedure given below illustrates the operation.

Copyrighted material
Microprocessors and Interfacing 7 - 38 8255 PPI (Programmable Peripheral Interface)

PAo 4
go o, PA, 3 00.
IN+
Analog onput
o' o, PA2 00,

o' o, PA3 00.


oo,
o' o, PA IN-
LRO
o'
o'
~
o,
Ds
o,
....
PAs
PA,
' 00,
oe.
DB,
00, CLKR
.,.
0, PBo R{10 Kl
PB 1 WFi CLK
RD Ri'i
..
WR

RESET
A,
Wii
AI
A2
REseT
cs
PB2
PB3
PB,
PBs
PB6
cs
Ri5 REF/2
qtso pFJI

VAEF
.,.

PB7
PC, iN'fR
8 PC 1
1
AGNO
2 PC2
.,.
2 ~ ADC 081)4
5 PC,
PC5
PC.
PC,

Fig. 7.35 lnterfecing of AOC 0803/080410805 to 8088 using 8255


READ PROC NEAR
MOV AL , 99H { Initial ize 8255 as port A and
OUT 06H,AL ; port C i npu t and por t B output )
MDV AL , OF<H ( Ma ke WR
OUT 02H,AL high]
MDV AL , OFCH ; (Send sta rt of
OUT 02 H, AL ; conversion )
NOP ; wai t
MOV AL, OFFH ; (Ha k e WR
OUT 0 2H,AL ; higt ]
BACK: IN AL, 0 4H ; Read INTR
AND AL, OlH ; Check INTR
J NZ BACK ; Repeat until INTR = 0
IN AL, OOH ; Read diqital data in a l
RET
READ ENDP

Application
This section illustrates the application of ADC/ DAC to store and reproduce audio
signal or speech. Refer Fig. 7.36. Here, speech data is converted to digital dta using
AOC0804. This data is stored in the array at the sampling rate of 1/2048 of second. Then
this sampled data ls sent to DAC0830 with same rate to reduce the speech signal This is
illustrated in the following program.

Copyrighted material
II
~~
Hidden page
Microprocessors and Interfacing 7 40 8255 PPI (Programmable Peripheral Interface)

MODEL S~IALL
. DATA
SAMPLES DB 2048 DUP (?) ; Space for speech samples
. CODE
START ' MOV AX, @DATA ; (Initialize
MOV OS, AX ; data seqment J
CALL READ ; Read speech
CALl.. >lRlTE ; Reproduce speech
PROC NEAR
MOV ex, 2048 ; Init ialize counter
MOV Dl,Of'FSET SA~1PLES Ini tialize pointer to array
OUT 94H,AL : Send start of conversion
IN 1\L, 80H ; Read INTR
AND AL, 80H Check INTR
JNZ BACK Repeat until INTR ~ 0
IN AL, 84H Read samplo
MDV { DI J,AL : Store sample in array
INC DI Increment array pointer
CALL DELAY Wait for 1/2048 seconds
LOOP AGAIN Repeat 2048 times
RET
READ ENDP
WIHT PROC NEAR
MOV CX, 2048 Initialize counter
MOV DI, OFFSET S AMPLES ; Initialize array pointer
BACKl ' MOV 1\L, ( Dl) Read sample from array
OUT 82H,AL Send it to OAC
INC DI ; Increment array pointer
CALL DELAY Wait for 1/2048 second
LOOP BliCKl Repeat 20 48 times
RET
WRITE ENDP
DELAY PROC NEAR
; This procedure generates a pproximately 1/2048 second delay
; assuming 8MHz Clock frequency of 8086.
PUSH ex ; save ex register
AGAINl ' MDV CX,0255 ; Initialize counter
LOOP AGAINl ; Repeat until count 0
POP ex ; Restore CX register
RET
DELAY ENDP
END START

Copyrighted material
Microprocessors and Interfacing 7 - 41 8255 PPI (Programmable Perlplleralln1er1ace)

7.10.2 ADC 0808/0809


The ADC 0808 and ADC 0809 are monolithic CMOS devices with an 8-<:hannel
multiplexer. These devices are also designed to operate from common microprocessor
control buses, with tri-state output latches driving the data bus. The main features of these
devices are :
Features
8-bit successive approximation ADC.
S.Channel multiplexer with address logic.
Conversion time 100 p.s.
It eliminates the need for cxtcrn..l l zero and full-scale adjustments.
Easy to interface to all microprOC\..-ssors.
It operates on single 5 V power supply.
Output meet TIL voltage level s pecifications.
Pin Diagram
Fig. 7.37 shows pin diagram of 0608/0809 ADC.

.......
Analo\l

5
:
2}
Arnllog
~~

~}-~
6
7
soc

OUTPUT CONTROL
EOC
083 ....
AOC
01011
A LE
097
096
CLK DBS
Vee o..
REF 080
GNO REF
09 1 082

Fig. 7.37 Pin diagram of 080810809


Operation
ADC 0808/0809 has eight input channels, so lo select desired input channel, it is
necessary to send 3-bit address on A, B and C inputs. Tho address of the desired ch>nnel
is sent to the multiplexer address inputs through port pins. N ter at least SO ns, this
address must be latched. This can be achieved by sending ALE signal. After another 2.5 I'S,
the start of conversion (SOC) signa) must ~ sent high and then low to start the convers-ion
process. To indicate end of conversion ADC 0808/0809 activates EOC signal. The
microprocessor system can read converted dlgital word through data bus by enabling the
output enable signal after EOC is activated. This is iJJustrated in Fig. 7.38.

Copyrighted material
I
Microprocessors and Interfacing 7 - 42 8255 PPI (Programmable Perlpllerallnlerface)

A
e ~ Address X
c - 50nsl-
ALE
~25JJs-C "----1 j

soc ~ (
)
EOC

~~ -~----------------------------)( V&lld data >-


oe--------------------------./
Fig. 7.38 Timing waveforms for ADC 0808
Interfacing
fig. ?.39 shows typical interfacing circuit for AOC 0808 with microprocessor S)'Stem.
The zener diode and LM 308 amplifier circuitry i.<Cl: u.c;ed to produce a \(_"C an +VRfJ' of
5.12 V for the A/D converter. Will\ this reference voltage the A/D converter will have 256
steps of 20 m V each.

060 INO
091 IN1
082 IN2
INPUT 093 IN3
PORT/ 064 A IN4 1K
PORTS 065 D INS
09& c IN6
067 0 IN7
eoc 0

-
CLK

OUTPUT
A
6
Output
+5V
0.01 1-1F

PORT c 74t4
soc Vee
ALE +REf 12 v
-"EF GND

2K

-
"""
,......... 10 K

=
Fig. 7.39 Typical Interface for 080810809 -
Copyrighted material
Microprocessors and Interfacing 7 - 43 8255 PPI (Programmable Peripheral Interface)

7.11 Stepper Motor Interfacing


A stepper motor is a digital motor. It can be driven by digital s ignal. Fig. 7.40 shows
the typical 2 phase motor interfaced using 8255. Motor shown in the drcuit has two
phases~ with center-tap winding. The center taps of these windings are connected to the
12 V supply. Due to thio;, motor can be exdted by grounding four terminals of the two
windings. Motor can be rotated in steps by giving proper excitation sequence to these
windings. The lower nibble of port A of the 8255 is used to generate excitation signals in
the proper sequence.
+ 12 V

.....
Stepper

.. x, motor

~ Ov
~
X, 0~

v, v,

~ 0
A, +1
;::::
~
A,

~ rj v--
r bt

~ v)
">
~CQ '' ~ 2~ ' ~ 2~
. '-
Fig. 7.40 Stepper motor Interface
The Tnblc 7.3 s hows typical excitation sequence. The given excitation sequence rotaK-s
thl~ motor in dockwi~ d irection. To rotate motor in antidockwi.~ direction we hnv(' co
("xcilt motor in a reverse sequence. The excitation sequence for stepper motor may changt
due to dtaJ'SC in winding ronn:tions. However, it is not desirable to excite both the ~omds

Copyrighted material
Microprocessors and Interfacing 7 - 44 8255 PPI (Programmable Peripheral Interface)

of the same \'o'inding simultaneously. This cancels the flux and motor windjng may
damage. To avoid this, digital locking system must be designed. Fig. 7.41 shows a sjmple
d igital locking system. Only one output is activated (made low) when properly excited;
otherwise output is disabled (made high).

x, _-.-1 ~o--1--.,
X'1
X2 - r--1.....:..- -L...-

x;

Fig. 7.41 Digital locking system

Step x1 x, v, v,
1 0 1 0 1

2 1 0 0 1

3 1 0 1 0
4 0 1 1 0
I 0 I 0 I

Table 7.3 Full step excitation sequence


1lh ~\ n l.l t i ou !'l('qul'I\Ct> ,.;ivt"tl in Table 7.3 is called full step sequence in which
..xcitaliun ~.nd :. v( the pho.tSe arc dlnngOO in one step. The excitation sequence given in
Tahl~ 7.-l tokes two s teps to change the excitation ends of the phase. Such a sequence is
\.~,l !h..,1 half step ~rquence and in (ach s tep the motor is rotated by 0.9.

Stop x1 x, y1 v,
I 0 I 0 I

2 0 0 0 I

3 I 0 0 I

I 0 0 0
5 I 0 I 0
6 0 0 I 0
7 0 I I 0
6 0 1 0 0
1 0 1 0 1
.
Table 7.4 Half stp excitation sequence

Copyrighted material
Microprocessors and Interfacing 1 45 8255 PPI (Programmable Peripheral Interface)

We know that stepper motor is stepped (rorn one position to the ne1Ct by changing the
currents through the llelds in the motor. n,. winding inducta""" opposes the change in
current and this puts Umil on th(t tot\.-pping rAte. For higher stepping rate s and more
torque, it is necessary to use " higher voltage source and ('WT(>Ilt limiting resistors as
shown in Fig. 7.4.2. By adding seri"" resistance, we decrease L/R time constant, which
allows the """""' to change more rapidly in the wlndinS$- ll>ere is a power loss across
series resistor, but designer has to compromise between power and speed.

Fig. 7.42 Excitation circuit with aertea reaiatance

)... Example 3 : hlltrfnce sttft/)('r motor to tl1e 8086 microproc.C"Ssor s.vstem and wri te mr
8086 assembly lmrgmrg,. pf08ram to control IIIC' II'PP.'' motor.
Solution : Hardware : Fig. 7.43 shOW8 the typical 2 phnsc 1'1\0h ll' t<~h.:d 12 V/ .67A/ph
interfaced with the 8086 micropl'()((>tlsor system using 8255. Motor shown in the circuit has
two phases, with centertap winding. Tile center taps ol these windings are connected to
the 12 V supply. Due to this, motor om be cxdted by 6rounding four terminals of the two
windings. Motor can be rotatoo In steps by Siving proper excitution sequence to these
windings. 1ne lower nibble o( pori A of tt-K. 8255 i ~ w:....-d to gentratc 4!.Acit.liun ,j~,,, in
the proper sequence. llte--.A." excitation s igm.l11 aN bulk-red usi.ng driver transistors.. 11-.
transistors are selected such that they can souroc rotoo current for the windings. Motor is
rotaloo by 1.8" per excitation.
Hidden page
Hidden page
Microprocessors and Interfacing 1 - 48 8255 PPI (Programmable Peripheral Interface)

7.12.2 Transistor Buffers


The Fig. 7.44 s hows some buffer circuits using transistors. In these circuits, transistor is
used as a switch. It ct~n be switch ON or OFF with logic 0 or logic 1 on port pin
depc'nding on the .-.pplictltion. To make transistor ON with logic 0 at port pin we have to
use pnp transistor otherwise we h.:we to use npn transistor. When transistor is ON, its
collector cutrent drives the Joad. To determine component values and transistor we have
to check maximum collector current of the transistor Clcm...J, maximum hr~ that transistor
can provide (h_,.m11 ~), maximum collector to emitter breakdown voltage (Vacro)and a
m~ximum power dissipation (Pdma,) allowc.-d by the transistor.

+SV

From
porto--'Ww--H
pin

(a) npn transistor (b) pnp tranlstor

Fig. 7.44 Transistor buffer circuits

Let us aj;~u mc tha t the Joad cunent is 200 rnA and maximum sourcing current of port
pin is 1 mA. Then transis tor should have
> 200 mA

> l
I Bm.liX
200mA
>
1 mA
hf-c min > 200
pdfl\ol:c > vCE:Io1t lcm.a:c
X

> 0.2 200 mA


> 40mW
Assuming output h.igh voltage or port pin equal to 4.5 V we have
4.5 - 0 .8
Re l mA

= 3.7 kQ

Copyrighted material
Hidden page
Hidden page
Microprocessors and Interfacing 7 51 8255 P.PI (Programmoble Peripherollnterfac:e)

The mechanical relays or oontactors, however, have several serious problems. When
the contacts are opened and closed, arcing takes place between the contact, which causes
the cot1tacts to oxidize and pit A~ the contacts a re oxidiz.t:d, they become higher resistance
.contact and mfly get hot enough to melt. Another disadvantage of mechanical relays Ls that
when they switch ON or OFF at high-voltage point, they produce la_rge amount of
electrical noise, called tlec.trom.agnetic interference (EMI).

7.12.3.2 Solid Slale Relays


+SV +12V
To ;woid the problems of mechanical
relays, solid state rela)rs are u."l'd. In this
1000 1.2 K
triac is used as a switching eJcment and
isolation is pro\ided by optoisolators or
pulse transformer. The Fig. 7.48 shows the
typicaJ oploLsolator circuitry. It consists of
LED and a phototransistor. LED glows
when d igital input is high, making
phototransistor ON. Thus digital input
From d;gilal 2K
circuit o--'\M'V--[ controls the voltage at the collector of
- Power
phototransistor without any physical
ground connection between them, providing
Digital isolation. When digital lnput is low, LED
ground -::- and hence phototrali.sistor is OFF.
Fig. 7A8 Optolsolator circuitry The Fig. 7.49 shows the typical pulse
transformer circuit. The pulse transformer
v ac
220_.,__ magnetically couples the control and
power circuitry avoiding electrical contact
between them.
Triac - c . ':1.
Tile optoisolator circuits giv~ better

~;;-]
I Load I perfonnance a t relatively low switching
speed. Because it has switching speed
limitations. On the other hand, at high
""' switching speeds pulse transfonner
\Pulse transformer
provides better performance. At low
switching spet.1(j pulse trnnsformer may get
Fig . 7.49 Isolation using pulse tr~msformer saturated to deteriorate its performance.

7.13 Keyboard and Display Interfacing


In this s~tion we disctass the keyboard and display interfadng using 8255.
,..,. Exampla 4 : Interface 4 x 4 ke.vbonrd witlt 8086 microprocessor.

Solution : Hardware : Fig. 7.50 shows a matrix keyboard with 16 ke)~ connected to the
8086 microproct..'Ssor u~ing 8255. A matrix keyboard reduces the number of connections,
thus H'lc J)uJnbcr of h\tctlae:iJlg lines.. Jn this: example th~ keyboard with 16 keys, is

Copyrighted mat~rial
Mluoprocessors and Interfacing 7 52 8255 PPI (Programmable Perlpherallntert.ce)

arranged in 4 x 4 (4 rows and 4 columns) matrix. This requires eight lines from the
microprocessor to make aU the connections instead of 16 lines if the keys are connected
individually. The interfacing of matrix keyboard requires two ports : one input port and
one output p<i ri. Rows are connected to the Input Port (return lines) and columns are
connected to the Output Port (scan lines). When aU keys are open row and column do not
have nny connection. Wh~n any key is pressed, it sho ts corresponding row and column. II
the output line of thico column is low, it makes corresponding row line low; otherwise the
status of row line is high. The key is identified by data sent on the output port and input
code rettived from the input port. The following section explains the steps required to
identify pressed key.

0,
o, z-; ~
~ Jt-
Rl! ~

::
MIKJ
-l ""'
; lOW 8
:-
2
""
t:S
5
5 rv
:::jit::
A,
. , I I
>- ...

Fig. 7.50 Interfacing of 4 x 4 keyboard with 8088

Check 1 : Whether any key is pressed or not


1. Make aU column lines zero by sending low on all output lines. This activates all
keys in the keyboard matrix. (Note : When scan lines are logic high, the status on
the return lines do not change, it will remain logic high.)
2. Read the status of return lines. If the status of all lines is logic high, key is not
pressed; otherwise key is pressed.

Copyrighted material
Microprocessors and Interfacing 7 - 53 8255 PPI (Progra'!'mable Peripherallnterfoc.)

Check 2 :
1. Activate keys from any one colwnn by mal<Y'tg any one column line zero.
2. Read the status of return lines. The zero on any return line indicates key is pressed
from the corresponding row and selected column. U the status of alJ lines is logic
high, key is not pressed from that column.
3. Activate the keys from the next column and repeat 2 and 3 for aU columns.
In Fig. 7.50 the scan lines are connected to the port CL of 8255 and return.~ Jines are
connected to the port C u of 8255.
Flowchart
(See flowchart on next page).

Source program
PORTA EQU 0000
PORTC EQU 0004
CR EQU 0006
PROC KEY NEAR
START: t10V AL, 81H Initialize Port C 1 as input and Port Cu
as output
MOV OX, CR I nitialise
OUT DX, AL 8255 J
MOV t\L, OOH
t10V OX , PORTC
OUT DX, AL !<1aka all scan lines zero
BACK : IN AL, DX
AND AL , OfH
Ct1P AL, OFH Check for key release
JNZ BACK If not, wai t for key release
BACK! : IN AL , DX
AND AL, DfH
CMP AL,OFH ; Check for key press
JZ BACK! ; If not, wait fo r key press
CALL DELAY ; wait for key debounce
MOV BL , ODH ; I nitialize key coun t er
NOV CL,04H
NOV Bli , FE!i ; t-1a ke one column l ow
NEXTCOL : t-10V AL , BH
OUT OX, A.L
MOV CH , 04H ; Initialize row counter
NOV OX, PORT A
IN .AL , DX ; Road return line status

Copyrighted material
Microprocessors and Interfacing 7 ~ S4 8255 PPI (Programmable Peripheral Interface)

lnlllalft key counter

Call display

-1
Yeo

Fig. 7.51 Flowchart

Copyrighted material
Mlcroprocesson and lnterhocing 7 55 8255 PPI (Progrwnm- Periphenol lnt.rt.ca)
NEXTROW : RCR AL, 1 ; Check fo r one Row
JNC DISPLAY ; I f zero, go to d i splay
; other"<fise continue
INC BL ; I nc rement key counter
DEC CH ; Decremen t row counter
JNZ NEXTROK ; Chec k for next r ow
NOV AL, BH
RCL AL 1 1 Select the next column
MOV BH , AL
DEC c Decrement column count
JNZ NEXTCOL Chec k for last colurnn if not repeat
J MP START Go to start
RET
KEY ENDP
END START
Ex.ample 5 : lnterfrtct' au 8-digit 7 5egmt:nt LED display u.si''S 8255 to tile 8086 microprocessor
sys.li!m and rvrite tm 8086 aS..'it'1nbly larrguase routhr~ to display messag~ on llr~
displny.
Solution : Hardware : Fig. 7.52 shows dw multiplcx<'<l eight digit 7-scgment display
connected in the 8086 system using 8255. In this drcuit port A and port B are used as
simple Jatchf..'CI output ports. Port A provides the segment data inputs to the display and
port B provides a means or selecting a display position at a time for multiplexing ttw
disp~1ys. The 8255 is addressed using di"-"'t nddn!Ssing mode, so only AaA7 lines are used
to dec:ode the addr<.'SSL'S for 8255.
For this circuit different addresses are :
PA OOH PC s 04H
PB 02H CR 06H
TI'le register values are chosen in Fig. 7.52 so the segment current is 80 mA. This
current is required to produce an average of 10 mA per segment ns the d isplays arc
multiplexed. In this type of display system, only one of d1c eight display position is ON at
any given Instant. Only one digit is sel:ted at a time by giving low sigMI on the
corresponding control line. Maximum anode current is 560 mA (7-~<rJnents"' 80 mA =
560 rnA), but d1c average anode current is 7D mA.
Software : Before going to write the software we must know the control word to Pr'Ob"?fam
8255 according to hardware connections. For 8255 Port A and 8 are used as output ports.
Comrol word format f 8255

~R--+-__M_~,__A__~----:-A----+-~-
0 0 X~+---M-~___B__~_PB___~_PC_X~L-41 ~
0 0

Copyrighted material
Hidden page
Mlcroproceoaors and lnwrtaci ng 7 - 57 8255 PPI (Programmable Perlpherallnwrtace)

Program :
MODEL SMALL
. DATA
PA EQU SOH
PB EQU 82H
CR EQU 86H
MES DB 41H,4 2H,4 3H,4 4H, 45H , 46H,4?H,48H
. CODE
; Procedure t o display message o n multiplexed LED displ ay
DISP PROC NEAR
MOV AX,@OATA ( I nitialise
M()VOS, AX data s egment
MOV AL, 80H Load control word in Al,
OUT CR, AL Load cont rol word in CR
PUSH F Save registers
PUSH AX
PUSH BX
PUSH ox
PUSH SI
; set up registers f or display
MOV BX, OSH ; load count
NOV AH , 7FH ; load select pattern
LEA SI , MES ; starting address ot messaq~

display mC:$Saqe
DISPl : MOV AL,AH : selec t diqit
OUT PB, AL
MOV AL , (BXSIJ ; get data
OUT PA, AL display data
Ct..LL DELA'f wait for some time
RDR AH, OlH ; adjust selection pattern
DEC BX ; adj ust count
JN Z DISPl ; r f!p.ea t 8 times
POP SI restore registers
POP OX
POP BX
POP AX
POPF
R1'
OISP ENDP
Note : This procedure must be called C'tmtinuously to display the 7-segment coded
mlossage in the memory.

Copyrighted material
Microprocessors and Interfacing 7 58 8255 PPI (Programmable Perlpherallntertaca)

7.15 Centronics Printer Interface


As explained earlier.. ha nds haking signals are required to transfer data brh-vet.:.n two
devices whose speeds are not same. This cc:ntronics protocol is a printer protocol. gives
standards for printer intcrfacc.
It has 36 pins. The Fig. 7.53 shows the pin definitions for ccntronics interface. The
ASCU characters are sent to the printer through eight data lines. Each data line has
individual ground to reduce the change of picking up electrical noi~ in the lines.

Signal Return Signal Direction Description


Pin Pin No.
No.
1 19 STROBE IN STROBE pulSe 10 read data in. Pulse width must be mcwe
than 0 .5 ms at receiving terminal. The signal levet is normally
,igh: read-In ol data Is performed at the "low" ~vel of this
signal.
2 2() DATA 1 IN
3 21 DATA 2 IN
4 22 DATA3 IN
5 23 OATA 4 IN
6 24 OATAS IN
7 25 DATA6 IN The.se signats represent 8-bit parallel data Each sional is at
Ngh" ~...ef when Cf3ta Is k;lglcal .. ,. and ~ v.tten logical
8 26 DATA 7 IN "0".
9 27 DATA6 IN
10 26 ACKNt.G OUT Ap.:;roximately 5 ms pulse; "1ow"' Indicates tha1 data has been
r~ed and the printer Is ready to accept other data.
11 29 BUSY OUT A "high" signal indicates lhat the pMter cannot receive data.
Tha signal becomes '"high" in the following cases.:
1. During data entry. 3. In "olfice" stale.
2. During printing operation. 4. During printer error &latus.
12 30 PE OUT A "high" signal indicates t~t the printer is out of paper.

13 - SLCT OUT This signal Indicates that the printer is in lhe selected state.
14 - -AUTO IN When 1his signal beflg 01 "low" level. the paper is
FEED XT automa~lly fed one IW'Ie after printing, (The signal le~ e&n
bo fix.ed to "lOW" with orP sw pin 2-3 provkfe<f on the oonb'OI
circui1 board).
15 - NC Not used.

16 - OV logic GND level.


17 - CHASIS.
GND - Printer chasi$ GNO. In the printer, the chasis GND and the
lOgic GND are iSOlated from each other.
16 - NC - Not used.

19-30 - GND - '"Twisted-Pair Return" signal; GNO level.

Copyrighted material ,
Mleroprocessors and lnterfaelng 7 -59 8255 PPI (Programmable Peripherallnterfaee)

31 .. iNiT IN When the tevel of this si~at becOmes ~ the


controler is reset to its initial state and the print -~utier.- ls
cleared. This signal Is noonaMy at "high" tevet and lis pulse
wi1h mU$1 be more lhen 50 al lhe leoninal.
32 - ~ OUT
The 1";1::. :~~s .";:;( wfl~:~po~llot i& in
33 .. GND - Same as wi1h p;n numbe10 19 10 30.
34 .. NC - Not used.

35 Pulled up IO + 5 Vd< 4.7 K-ohms reslstanoe.


36 .. SLC T IN IN Da~
this
..:::::1'is; 10'1ow".
lhe pllnler Is posoible only wflen lhe 1"""1 at

Notes :
1. "Oif\.'(tiM'' ~(e~ to the d irection (l(f signal I'!Qw 115 vitwt'd from the p rinter.

2. ..Rerum" de~ ..TwistedPair Rl"h.lm"' and is to be COIVM.'C'tt'd at 5igml--gru~md ":vel.


When making the interface, be surt> to use a tw istcd.,..ir C<\bk lew 4:~h &igrgl :a.nd neves fail to
c,mp lctc C\lf\1\l.' (tion Qn the.: retum ~de to prt\'f'n t nOitlc effecthely, these eab lcs shou ld be sh.lelded .md
rorH't.<d~ to the chassis olthe system unit.

). All intcrfllOc conditJons art ba..~d o n m. leYel. Both the rise and fait times ol each signal must be les&
th.ln 0.2 IJS.

4. Data trilnsk:r must nol 00 c;~ rried o ut by i&noring the ACKNLC or BUSY sfgrol. ~Ia tra.n..;er to this
printer can b.: rarried ou t only afh!r oonfl.rmlng the ACKNLG signal o r when the level of tht BUSY
signal is '1ow"'.
Fig. 7.53 Pin definitions for contronlcil Interface
The other sign.al.s fall into two categories, signals sent to the printer to ten it which
operation to do a nd signals from the printer that ind icate its status. These signal~ ar~ as
follows :
Input slgnal.s for printer :
1. INIT : This signal whe n activated tells the printer to perform its internal
initialization sequence.
2. STROBE (STB) : This signal when activated tells lhe printer that valid data is
available on the d a hl b us.

Status signals output from printer :


1. ACK : This signal when low indicates that lhe data character has been accepted
l'lnd the printer is ready for the next data.
2. BUSY : Thi. is active high s ignal. It goes high when printer is not ready to receive
a character.

Copyrighted material
Microprocessors and Interfacing 7 ' 44! .82" PPI (Programmable Periphe ral Inte rface)
3. PE : This activo high signal goe5 high when printer is out of paper.
4. SLCT : This signal goes high If the printer is selected for rC<"Oiving data.
5. ERROR : This active low signal goes low for variety of problem condi tion.~ in the
printer.
Fig. 7.54 shows the timing waveforms for transfer of data characters to an JBM printer
using the basic handshake signals.

BUSY

1- APPROXJMATELY 5 ...
ACKNLG

1- 0.5 ,,. (MINIMUM)


STROBE

-1 1- 0.5 (MINIMUM)

Fig. 7.54 Timing waveforms for transfer of data characters to an IBM printer

Communicatio n between Computer and Printer


Cmnputcr sends the TNIT pulse for at least 50 IJS, to initialize the printer. Computer
then checks for BUSY low to confinn whether the printer is ready to rcccive data or not. lf
BUSY :~~ ignal is low (not busy). computer sends an ASCD code on eight parallel data lines
and ,1fter <lt least 0.5 J.tS, it also sends Srn signal to indicate, valid datn is available on the
dnta bus. Computer activates this STB signal for at least 0.5 ).lS c1nd it also ensures that
vntid datn is pres<.'flt on the data bus for at least 0.5 ps after the STB $ignal is di<;abled.
When the printer is ready to receive the next character, it as~rts its ACK signal low for
.1bout 5 ).lS. TM ris ing edge of the ACK si~;nal tells the computer that it can send the next
character. The rising edge of the ACK s ignal also n.--sets the BUSY sig'"lal from the printer.
When computer finds busy low. it sends the next character along with strobe and the
~equc1lCC is repeated ti11 the last character transfer.

Centronics Printer Interface using 8255


Fig. 7.55 shows the drcu.it for interfacing centronics type paraJlel input printer ta
82SSA. Port A is uS<;d to send 8-bit data to the p rinter. It is wed in mode 1 so PC6 (OBF
signal) is used as STB signal to tc-1.1 the printer that valid data is available on the data bus
,md PC, i:; used ,15 an ACK signal. BUSY, PE and ERROR signals are connected to tho PS.
l \ 1 r~ port lines.

Copyrighted material
. Microprocessors and Interfacing 7 61 6255 PPI (Programmable Perlpherallnterfacel

Do
Hardware

Do
.... Do
0,
A,
0,
... 2 PC6 w- 0,
iii

R
I
A, 5 N
PC, AcK
""
iOR
i5W
Ro
\iVR
5
PCo
PB,
I NIT
ERROR
T
E

Ro,.. RoSOl P8 1 PE
from8284 PBo
r-' cs BUSY

D >-
Fig. 7.55 Interfacing cen1ronlcs printer to 8255A
ln the next section we will see flowchart and program required to print a message.
Flowchart : Fig. 7.56 Flowchart for printer interface.

No

No

Yes

Fig. 7.56 Flowchart for ~rinter Interface


Copyrighted material
MIC!Oi>~uoni>and Interfacing 7 62 112~ PPl (Programmable Peripheral Interface)

ln the program it is necessary to initialize .6255. as follows

Port Input/output Mode

Port A
. .
Output 1
.
Port 8 Input ! 0

Pon C Upper - " -


.
Port CLower Ou1put -
Control word :
Mode A

0 1 A2H

110 map :

A,, A,. A,, A1 2 A t1 ... ,. ... ... A, ... ... .... .... A, A, ... Address Port

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 OOOOH Port A
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0002H Port B
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0004H Port C
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0006H CR

Program:
. ~fODE L SHALL
Por~A ~QO 0000
PortB EQU 0002
Porte EQU 0004
CR EQU 0006
. DATA
Mesl DB ' Printer Paper Out' , 10 , 13 , ' S'
.. Mes2
Mes3
08 ' Printer Offline' , 10, 1 3 , ' $ '
08 ' Printing Over, ' S'
Mes4 DB ' This is to be print '
COUNT DB 15
.CODE
START : MOV AX , @DATA Initialize da t a se<;ment
MOV OS , AX
LEA BX, ~lE S 4 In itia lize po i nter to string
MOV OX, CR CR i s control register address
MOV AL, OA2H Load control ""'Or d
OUT OX, AL
MOV AL, 07 Ma k e INTE, h igh to e nable INTRA

Copyrighted material
Microprocessors and Interfacing 7 - 63 8255 PPI (Programmabl.e Peripheral Interface)

OUT DX ,AL
~10V AL, OO
OUT DX,AL Make PC0 ~ (BSR mode)
to give ! NIT low
l10V CX, OFFf'H
BACK : or.:c ex Wa it for mo r e than 50 ~
LOOP BACK
MOV AL,Ol
OUT DX,AL Make INIT HIGH
NEXT : t<QV ox, Porta
IN AL,OX
MDV AH,AL ; Save status information
AND AL, Ol H
J NZ CHECK Check for BUSY if high goto
; check
MOV AL, (BXJ
MOV ox, PortA
OUT DX,AL ; Send the character
MDV DX, PortC
AG-'IN : IN AL, OX ; Check for ACK by
AND AL, 08 ; checking I NTR,.. line high
JZ AGAIN
INC BX ; Increment st ring pointe r
t-1CV AL,COUNT
DEC AL
f-iOV COUNT, AL ; Decrement counter
JNZ NEXT Check for counter 0
JMP LAST
CHECK: MOV AL, AH
AND AL , 02
MOV AL,AH Save printer status
JZ CHECK!
LEA DX,>lESl
MDV AH, 09H Call for DOS interrupt
!NT ?!H to display MSl
CHECK! : AND AL, 04
JNZ NEXT
LEA OX, MES2
~10V AH , 09H ; Call for DOS interrupt to
INT 21H ; display MES2
JMP NEXT
LAST LEA DX , MES 3 ; Call for DOS interrupt to
><OV AH , 09H ; display MES3
! NT 2!H
MDV AH , 4CH ; Terminate program
!NT 21H
END START
END

Copyrighted material
Hidden page
8086 Interrupts

8.1 Introduction
Sometimes it is necessary to ha\'e the computer automaticaUy execute one of a
collection of s pecia l routin~ whcnevt>r cert.tin conditions exists within d program or in the
microcomputer system. For example, H is necessary that microcomp uter sytitem should
give response to devices s uch ns keyboard, ~!ilor and other components whc1\ they
reque:;t fo r service.
The most commOt\ method of servking such device is the polled approach. ll'ai~ is
where the proccs..;tu m us t test each device in sequence :.nd in effect "ask.. each one if it
needs communication w ith the pruces.~r. It is easy to sec that a large portion of the main
program is Looping through this continuous polling cycle. Such a me thod would h.wc n
serious and dt..'CTCmental effect on system th roughput, thus limiting the tasks that rovld be
assumed by the microcomputer and n.--ducing the cost e(fect:iveJ''ICSS of us ing su ch deviccs.
A more de.~irablc method would be the one thn t allows the microprOCl.-.ssor to exL>cutc
its main program and only stop to service peripheral devices when it is told to do so by
the device itself. l.n effect. the method, would provide an external asynchronous input that
would inform the pn.>c~-..or tha t it s hould complete whatever instruction that is cUrrently
being executed and fetch a new routine that will service the requesting device. Once this
servicing is completed, the processor would resume exactly w~ it left off. This met:hOtl
is c.-11led interrupt m ethod. It is easy to see that system throughput would d rastically
increase, and thus enhance its cost {>(fcctivern.'SS. Most microprocessors a llow execution of
special routines by in terrupting normal program execution. When a microprocessor is
intcrrupttod. it stops executing its current program cmd ca.Jls a special routine w hidl
NscniccsN the il\tcrrupt. The event that cnu.~-.s the interruption is called interrupt l)nd the
special routine ext.'Cuted to service the interrupt is called interrupt service
routine/procedure. Normal program can be interrupted by three ways :
1. By external s ignal
2. By a special instruction in the pro~'Tam or
3. By the occurrence of some cond ition.
(8 1)

Copyrighted material
Mlcroproussors and Interfacing 8-2 8086 Interrupts

An interrupt caused by an external signal is referred as a hardware in terrupt.


Conclitional interrupts or interruptS caused by specia1 instructiom are called softwue
interrup ts.

8.2 Interrupt Cycle of 8086/88


An 8086 interrupt can come from any one the three sources :
External signa l
Special Instruction in the program
Condition produced by instruction . '.
8.2.1 External Signal (Hardware Interrupt)
An 8086 can get interrupt from an external signal applied to the nonmaskable interrupt
(NMI) input pin, or the interrupt (INTR) input pin .

8.2.2 Special Instruction


8086 supports a spedal in.o;truction, INT to execute special program. At the end of the
interTupt service routine, execution is usually returned to the intem1pted program.

8.2.3 Condition Produced by Instruction


An 8086 i..~ interrupted by some condition produced in the 8086 by the execution of an
Lnstruction. For example divide by zero : Program execution will automaticaUy be
.. interrupted if you attempt to divide an operand by zero.
At the end of each instruction cycle 8086 checks to see if there is any interrupt request.
If so. 8086 responds to the interrupt by ~ rform.in.g scri(..o$ of actions (Refer Fig. 8.1).
J. It dccreml'nts stac.k pointer by 2 and pushes the flag regis ter on the stnck .
2. It disables the lNTR interrupt input by clearing tht.' interrupt flag in the flag
n.-gister.
3. It n..."!'oets the trap flag in the fl.1g register.
4. lt decrements stack pointer by 2 and pushes the current code segment register
contents on the stack.
5. It dtocrcments stack pointer by 2 i\nd pushc."S the current instruction pointer
content.-; un the stru:k.
6. It doc,; an indirect for jump a t the slilrt of the proo.>dure by loading the CS and IP
values fo r the start of the interrupt service routine (ISR).
An IRET in~truction at the end of the intem1pt service prOCt.>dure returns execution lo
the main program.

Copyrighted material
Microprocessors and Interfacing 83 8086 Interrupts

INTERRUPT
SERVICE
PROCEDURE

PUSH REGISTERS
MAINLINE PUSH Ft.AGS
PROGRAM CLEAR IF
CLEARTF
PUSHCS
PUSHIP
FETCH ISR ADORES$

POPIP
POPCS
POPFI.AGS
PDP REGISTERS
IRET

Fig. 8.1 8086 interrupt response

Now the qut..~tion is " How to get the values of CS and LP register ?" The 8086 gets the
new values o( CS and lP register from four memory 3ddrcsscs. When it responds to an
inte-rrupt, the 8086 goes to memory locations to get the CS and u> values for the start of
the internlpt service routine. In an 8086 system the first 1 Kbyte of memory from CXXlOOH
to 003FFH is reserved for storing the s tarting addresst.~ of interrupt service routines. This
block of memory is oftC'n called the interrupt vector table or the interrupt pointer table.
Since 4 bytes are required to store the CS and LP values for each intern1pt service
procedure, the table can hold the starting addresses for 256 interrupt !o'Oervi mutine!-'0.
Fig. 8.2 shows how the 256 intcrn1pt poiniCI'S ore arranged in the memory table'.
Each intl'rrupt ty~ is given a number bdwt..'Cn 0 to 255 and the addrC"SS of each
interrupt is found by multiplying the type by 4 e.g. for type 11, interrupt addn..-oss is
11 x 4 = ~~ ~o~ 0002CH
Only fin; t five types Juwe explicit defini tions s uch as divide by zero anct non mas kabJe
interrupt. The next 27 inter-rupt types, from 5 to 31, are reserved by lntcl for u!ie in fu ture
microproctssors. The upper 224 interrupt typl~. from 32 to 255, ar'! available for user fvr
hardware or s.oftware interrupts.
When the 8086 responds to an interrupt, it ilutomntic.llly SOt..'S to the SJX->ci(ied location
in the interrupt vector table to get the starting address o( interrupt serviC\" roul\n(', So \bel'
has to l0c1d these starting addresses for different routines at the s tart of the p rogram

Copyrighted material
Microprocessors and Interfacing 8-4 sols Interrupts

ADDRESS

f-- TYPE 255 POlNTER : _


{AVAILABLE)

f-
TYPE 33 POINTER:
(AVAltA&.E) -
r- TYPE 32 POI""ER :
( AVAllABl) -
r- TYPE 31 POINTER:
(RESERVED) -

TYPE 5 PQ(NTER :
f- (RESERVED) -
f- TYPE 4 POlNTEA :
OVERFLOW
-
f-,1BYTE
TYJ>E 3 POlNTR :'leN
INT INSTRUCTI

r- TYPE 2 POINTER :
NON-~SKABl.E -
TYPE 1 POINTER :
r- SINOLESTEP -
CS BASE ADDRESS
r- TYPE 0 POINTER :
OMOE ERROR
- IPOFFSET

'' 16 BITS
I
Fig. 8.2 8086 interrupt vector table

8.3 8086 Interrupt Types

8.3.1 Divide by Zero Interrupt (Type 0)


Wht>n the quotient from either a OIV or JDJV instruction is too large to fit in the result
register; 8086 will automatically execute type 0 interrupt

8.3.2 Single Step Interrupt (Type 1)


The type 1 interrupt is the single s tep trap. En the single step mode, system will
execute one instruction and wait for further direction from user. Then user can examine
the contents of registers and memory locations and if they are correct, user can tell the
system to execute the next instruction. This feature is useful fo r debugging assembly
language programs.

Copyrighted material
Hidden page
Mi~roprocessors and Interfacing 8-6 8086 Interrupts

executes the INTO ins truction, the instruction will simply function as ar. NOP (no
opt>rqtion). However, if the ov~rfl0\'1: flag is set, indjcating an overflow ('rTOr, th~ 8086 wiiJ
cx~J<Cute a type 4 interrupt after executing the INTO .i nstruction.

Another way to detect and respond to an overflow error in a program is to put the
jump if ovcrfJow instruction, (JO) immed_iateJy after the arithmetic inStr\lction. J.f the
overnow flag is set as n resuJt of nrithmetic operation~ execution will jump to tht: addr('SS
s pecified in the jO instruction. At th.is address you can put an error routiN~ which
responds in the way you want to the overflow.

8.3.6 Software Interrupts


Type 0 255 :
The 8086 INT in$truction can be used to cause the 8086 to do one of the 256 possible
interrupt types. TI'lc interrupt type is specified by the number as a part of the instruction.
You can use an (NT2 instruction to send execution to an NM I int~rrupt ~rv ice routine.
This allows you to test the NMI routine without needing to apply an extcmal signal to the
NMI input of the 8086.
With the softwnr(' int~rrupL;;you cnn call the desired routine...:; from many d ifferent
progra.ms in a system e.g. BIOS in IBM PC. The IBM PC has in its ROM collection of
routint..>s, each performing some speci.fk function !t"Uch as reading character from keyboard,
writing character to C RT. This collection of routines refern--d to as Bas ic Input O utput
System or BIOS.
The BIOS ro utjncs are e<-11led with INT instructions. We ,..,.UJ summarize interrupt
response and how it is serviced by going through following step~
I. 8086 push~ the flag ree,.,stcr on the $!;td; .
2. It disables the single step and the lNTR input by clearing the trap Rag and
interrupt flag in the flag ngister.
3. It ~nv~ the cummt CS and IP rcgi-l'tcr contt-nb; by pus hing them on the stack.
4. It dOL'!': an indirect fr.r jump to tht s tart of the routine by loading the new values
of CS and IP regi.'iltcr from the memory whose address caJculated by multiplying 4
to the interrupt type, For example, if interrupt type is 4 then memory address is
4 x 4 = lOHl = l OH. So 8086 wiJI read new value of lP from OOOlOH and CS frol"n
00012H.
5. Once these values <:~re loadc<'d in the CS and IP~ 8086 will fetch the ins truction from
the 1"1<-'W addrCss which is the s tnrtjng address of il'ltcrrupt service routine.
6. An IRET ins truction a t the end of the interrupt service routine gets the previous
valuC'S of CS nnd IP by popping the C5 a 1'ld IP from the stack.
7. At the end the nag register contents are copied back into flag register by popping
the n.,g
register form s tack.

Copyrighted material
Microprocessors and Interfacing 8-7 80861nterrupts

8.3.7 Maskable Interrupt (INTR)


The 8086 INTR input ('an be used to interrupt a program execution. The 8086 is
provided with a maskablc h.w1dShl'lke i1\terrupl. This interrupt is implemented by us ing
two pins- INTR a nd INTA. Thi> interrupt can be enabled or disabled by STI (lf=l) or CLI
(IF=O), respectively. When the 8086 is reset, the interrupt flag is automatically deared
(IF=O). So a fter rc>set INTR is disabl"d. User has to execute STI instruction to enable lNTR
internapt.
The 8086 responds to an INTR interrupt .:s: follows :
l. The 8086 first d ocs two interrupt acknowledge machine cycles as shown in the
Fig. 8.3 to get th e inte rrupt type from the external device. In the first interrupt
<h.:knowlt."'Clge machine cycle the 8086 Aoats the Jata bus lines ADcrAD1s and sends
out an INTA pulse on its lNfA output pin. This indicates an interrupt
acknowledge cycle in progress and the system is ready to a<Xept the intern.1pt type
from the external device. During the second interrupt acknowk>dgl;! machine cycle
the 8086 sends out another puJse on its INTA output pin. In response to this
St..'CQnd INTA pulse the external device puts the interrupt type on lower 8 bits of
the data bus.

r, 1 T2 1 r 3 1 T4 1 r, 1 r, 1 r, 1 r 2 ) r, 1 T4 1

ADO-A015 --=====~~_!F~L~O~A~J------~---------------2~~~~)
tntetnJpl
type

Fig. 8.3 Interrupt acknowledge machine cycle

2. Once the 8086 receives the interrupt type. it pushes the flag register on the s tack,
dear!-1 TF and IF, and pushes the CS l'!nd lP values of the next instruction on the
stack.
3. The 8086 then gets the new value of lP from the memory address equal to 4 times
the interntpl type (number), and CS value fmm memory address equal to 4 times
u,e intt'rrupt number plus 2.

Copyrighted material
Microproces.sors and Interfacing 88 80881nterrupts

8.4 Interrupt Priorities


As far as the 8086 interrupt priorities are concerned, software interrupts (All interrupts
except single s tep. NMI and INTR interrupts) have the highest priority, followed by NMI
followed by INTR. Single step has the least priority.

lnterTUpt Prlonty
OMde Enor. 1n1 n, lnt 0 HIGHEST
N~.1 ~
INTR J.
SINGlE STEP WWEST

l MAIN PROGRAM
The interrupt Rag is al!tomatically
cleared as pnrt of the response of an 8086 to
NMI J
I DIV I an interrupt. This prevents a signal on the
JNTR input from interrupting a higher
I DIVIDE ERROR
priority interrupt service routine. The 8086
PUSH FLAGS, CS. IP allows NMJ input to interrupt hig:.t,er
CLEAR TF & IF priority interrupt, (or example supp~ that
TRANSFER CONTROl
a rising edge signal arrives at the NMJ input
J IF=O TF = 0 while the 8086 is executing a OIV
instruction. and that the division operation
PUSH FLAGS. CS. IP produces a d ivide error. Since the 8086
CLEAR TF & IF
TRANSFER CONTROL check. for intc.rnol interrupts before It checks
for an NMI interrupt, the 8086 will push the
I flags on the st.lck, clear TF and IF, push the
I EXECUTE NMI I rehtm address on the stack, and go to the
start of the divide error service routine. The
! RETURN IF = 0 IF=O 8086 will then do a n NMI interrupt response
EXECUTE ONIOE and execute non-maskable interrupt service
ERROR ROI.ITINE ~utine. After completion of NMl service

I RETURN T0 MAIN PROGRAM


routine an 8086 will rctum to the divide
error routine. lt wiiJ execute divide error
Fig. 8.4 Flow-chart for divide error routine and then it will retum to the mnin
routine program (Refer Fig. 8.4).

8.5 Expanding Interrupt Structure using PIC 8259


hHcrn~pt.s C;:tn ~ used for a variety of applic<ltions. Each of these interrupt applications
rt."'quires a sepa rati.~ interTupt lnput. lf we a re working with an 8086~ we get only two
interrupt inputs INTR and NMI. For applications where we have muJiiplc interrupt
sources, we use external device <'llled a priority interrupt controller (PIC). Fig. 8.5 shows
the oonncction between 8086 and 8259.

Copyrighled material
Microprocessors and Interfacing 89 80861nlerrupts

ADo Do
'Ro
AD 7 0., ,.., f--
IR 1

IR3
84U 8259
IR;
lm'A lm'A
'"
IR6
INTR INT IR7

Fig. 8.5 Connection between 8086 and 8259

8.5.1 Features of 8259


1. It can manage eight prjority interrupts . Ttlis is t."'(]Uivttlent to provide eight
interrupt pins on the processvr in place of 11\ifl{ pin.
2. lt i!; po$.-;iblc to l oc~~ ~~ ve<;tor table for thest additional intcrn.1 pts any w here in the
memory map. Howev~r. ~II eight il''l terrupts a r~ spac.~d dl the int~rval of either fou r
or eight loca tion~.
3. By cascading &259s it is ~i blt> to get 64 priority interrupts.
4. Interrupt ma~k rcgistN makc5t it !'O!'Sibl(' to mask individual interrupt request.
5. The 8159A can be prog-r.\mmi!d to act-ept either the level triggered or the edge
triggNed interrupt reqw..'St.
6. With the hdp o( 8259A user can get the informa tion of pending interrupts,
in-service interrupts and masked interrupts.
7. The 8259A i.s designed to minin'li.ZC the software and real lime overhead in
h..1ndHng multi 1evel priority internpts.
4

8.5.2 Blcx:k Diagram of 82~9A


Fig. 8.6 l'l.hows the internnl block d iagram of the 8259A. It includes eight blocks : data
bus buHer, read/write logic, <OT\trol lugk, thro;_'(' r'--gistN S (IRR. lSR nnd IMR). priority
resolver, and c<'!:Salde buffer.

Data Bus Buffer


lllc data btL'> a llows the 8086 to !'end control words to the 8259A and read a s tatus
wotd from the 8259A and read a st~tus word fm1n the 8259A. The Sbit data bus also
allows the 8259A to send interrupt types to the 8086.

Copyrighted material
Hidden page
Mlcropi'OC4Issora and Interfacing 8 11 80861n1errupts

Priority Resolver
The priorily resolver detennlnes the priorities of the bits set in the IRR. The bit
rorresponding to the highest priorily interrupt input is set in the ISR during the (]','TA
input.

Cascade Buffer Compara1or


This section generates control signals necessary for cascade operations. It also generates
Buffel'EMble sign,ls. As stated earlier, the 8259 can be CJ>scaded with other 82.59s in ord.,.
to expand the interrupt handling capacity to sixty-four levels. ln such a case, the former is
called a master, and the latter are called slaves. The 8259 can be set up as a master or a
s lave by the SP I ENpin.
CAS 0 2
For a master 8259, the CA5o.CAS, pins are outputs, and for slave 82595, these are
inputs. When the 8259 is a master (that is, when it accepts interrupt requests from other
8259s), the CALL opcode is generated by the Master in response to the first iNTA. The
vectoring address must be released by the slave 8259. The master sends an identification
code of three-bits (to '"''ectone out of the eight possible slave 8259s) on the CAS,.CAs,
lim.>S. The slave 8259s accept these three sib"'als as Inputs (on their CAS,.CAS, pins) and
compare the rode sent by the master with the codes assigned to them during initialisation.
The s lave th us selected (which had originally placed an interrupt request to the master
8259) then pulo; out the address of the interrupt service routine during the second and
third INTA pulses from the CPU.

SP I EN (Sieve Program /Enable Buffer)


The SP I EN s ignal is tied high for the master. However, it is grounded for the slave.
In large systems where buffers arc used to drive the data bus, the data sent by the
8259 in response to INTA cannot be accessed by the CPU (due to the data bus buffer
being disabled).
If an 8259 is used in the buffered mode (buffered or non-buffered modes of operation
cnn be specified a t the time of initialising the 8259), the SP I EN pin is used as an output
which can be used to ~ble the systeM data bu." buffer whenever the 8259's data bus
outputs are enabled (when it is ready to send data).
Means, in non-buffered mode, the SP/EN pin of an 8259 is used to specify whether
the 8259 is to operate as a master or as a slave, and in the buffered mode, the SP/EN pm
is used as an output to enable the data bus buffer of the system.

8.5.3 Interrupt Sequence


The evE..nts occur as follows in an 8086 system :
l. One or more of the INTERRUPT REQUEST lines (IRO-IR7) are raised high, setting
the corresponding (RR bit(s).

Copyrighted material
Microprocessors and Interfacing 8- 12 8086 Interrupts

2. The priority resolver checks three registers : The IRR (or interrupt requests, the
IMR for masking bits, and the ISR for the intermpt request being served. It
resolves the priority and sets the lN1' ~gtl when appropriate.
3. The CPU acknowledges the !NT and responds with an iNi'A pulse.
4. Upon rea>iving an INTA from the CP U, the highest priority ISR bit is set and the
corresponding IRR bit is reset. The 8259A does not drive data bus during this
cycle.
5. A selection of priority modes is available to the progranuner so that the manner in
w h ich the requests are p rocessed by the 82.S9A can be configured to match his
system requirements. The priority modes can be changed or reconfigured
dynamici'llly a t any time during the main program. This means that the complete
interrupt service structure can be defined as required, based on the total system
environment.
6. The 8086 will initiate a second INTA pulse. During this pulse. the 8259A releases a
8-bit pointer (interrupt type) onto the Data Bus where it is read by the CPU.
7. This completes the interrupt cycle. In the A01 mode the ISR bit is reset at the end
of the second !NTA pulse. Otherwise, the ISR bit remains set until an appropriate
EOI command is issued at the end of the interrupt subroutine.

8.5.4 Priority Modes and Other Features


The various modes of operi'tion of the 8259 are :
(J Fully NesiL'<l Mode,
(b) Rotating Priority Mode.
(c) Special Masked Mode, and
(d) Polled Mode.
a) Fully Nested Mode :
'""-4fter initialization, the 8259A operates in fully nested mode so it is caUed as default
mode. The 8259 continues to OJX><ate in the Fully Nested Mode until the mode is changed
through Operation Command Wc.')rds. In this mode, IRO has highest priority and 1R7 has
lowest priority. When the interrupt is acknowledged, it sets the corresponding bit in ISR.
This bit wiU prevent aU interrupts of the s.1me or lower level, however it will accept
higher priority interrupt requests. The vector address corresponding to this interrupt is
then sent. The bit in the ISR will remai n set until an EOI command is issued by the
microprOC'essor at the end of interrupt service routine.
But if AEOI (Automatic End of I.nterrupt) bit is set, the bit in the ISR rest!ts at the
trailing edge of the last !NTA.

II
Copyrighted material
,,
Hidden page
,Miti'OI!(OC. .IPrs and lnt&rfaelng 8 14 80861nterrupts

(II Automatic Rotation


In this mode, a device.. after being serviced, receives the lowest priority. Assuming that
I R ~ has just been servid, it will re<:eive the seventh priority.

IR0 IR0 IR, IR3 Ill. JRs IR1 IR,


4 5 6 7 0 1 2 3

(Ill Sp&elfle Rotation


In the Automatic Rotation mode, the interrupt request last serviced is assigned the
lowest priority, whereas in the Specific Rotation mode, the lowest priority can be assigned
to any interrupt input ORo to IR, I thus fixes all other priorities.
For example iJ the IOW!$t priority is assigned to I'R2, other priorities are as s hown
below.

IR0 IR0 IR, IR, Ill. IR IRo IR,


5 6 7 0 1 2 3 4

dl Special Mask Mode :


If any interrupt is in seorvice then the corresponding bit is set in ISR and the lower
priority interrupts are inhibited. Some applications may require an interrupt service routine
to dynamically alter the system priority s tructure d uring its execution u.nder software
oontrot for example, th<l routin<' may wish to inhibit lower priority requests for a portion
of its execution but enable some of them for another portion. fn these eases we have to go
for special mask mode.
ln the s pecial mil.Sk mode it inhibits further interrupts at tha t level and enable$
i.ntemtpts from all other levels (lower as \\eiJ as higher) that are not masked. Thus any
interrupt may b~ selectively enabled by loading the mask regjster.
I Poll Mode :
In this mode the lNT output is not used. The microprocessor checks the s tntus of
intern.rpf requests by issuing poll command. The microprocessor reads contents of &259A
after lssulng poll command. During this read operation the 8259A p rovides polled word
and sets ISR bit of highest priority active interrupt request FORMA T.

l r lx lx l x l xlw. l w, jw, j
I = 1 4 One or more interrupt requests activated.
I =0 -+ No interrupt request activated.
Binary code of h.lghcsl priority active interrupt roqucst.

Copyrighted material
Microprocessors and Interfacing 8-15 8086 ln1errupls

8.5.5 Programming the 8259A


The 8259A n.~u_ires two types of command words. lnitializ.ation Command Words
(JCWs) ond Operational Command Words (OCWs).
The 8259A can be initialized wlth four JCWs; the first two arc compulsory, and the
other hvo are optional based on lhe modes being used. These words must be issued in a
given sequence. After initia1i~1ti on., the 8259A can be set up to operate in various modes
by using three different OCWs; however, they no longc.r need to be issued in a specjfic
sequence.
Flow chart :

ICW1

NO {SNGL 1)

READY TO ACCEPT
IN'TERRIJPT REQUESTS

Fig. 8.7 8259 A Initialization flowchart

lnitlall.z.alion Command Word 1 (ICW1 )


Fig. 8.8 shows the lniliali.zalion Command Word I (ICWI).
A write command issued to th<' 8259 with Ao = 0 and 0 4 ;:; 1 is interpreted as JCW1,
which s tarts the initiali7,ation S<!quenc::e.
It specifies
I. Single or multiple 8259As in the system.
2. 4 or 8 bit interval ~tween the interrupt vector locations.
3. The address bits A1 As of the CALL instruction.
4. Edge hiS!,tered or Jevel higgered int.:rrupts.
S. ICW4 is needed or not

Copyrighted material
..I I , I .. I .. I
Microprocessors and Interfacing

0
o, o, o, o,
1
o, 0,
8 -16
o, 0,

ILnu l ""' ISHG'I "" I


8086 Interrupts

I I

- 1 rcw NEEDED
0 NO ICW4 NEEOEO

1SINGLE
0 ,. CASCADE MOOE

CALl ADDRESS INTERVAL


1 INTERVAl C>' 4
0 INTERVAl OF 8

1 = LEVa. TRIGGERED MODE


0 EDGE TRtGGEREO MODE

._,...,o,..,.._.,.,
VECTOR ADDRESS
{MCS 80f85 MODE ONLY}

Fig. 8.8 Initialization command word 1 (ICW1)


Initialization Command Word 2 (ICW2)
Fig 8.9 shows the lnltializ.,tion Command Word 2 (ICW2).

~ ~ ~ ~ ~ ~ ~ D, ~

I IA~,,A"f. l"'~sl"~.l"%, 1
I I I I
"o I At "o
A1s-Ao OF INTERRUPT
VECTOR ADDRESS
(MCS80185 MODE)
T rTs OF INTERRUPT
VECTOR ADDRESS
(808618()88 MODE)

Fig. 8.9 lnltlallzatiCM'I command word 2 (ICW2)

A write corrunand following ICWI, with AO = I is interpreted as ICW2. This Is used to


load the high order byte of the interrupt vector address of all the interrupts.
l nltiallzatlon Command Word 3 (ICW3)
ICW3 is required oniy if there is more than one 8259 in the system and if they are
cascaded. An ICW3 operation loads a slave register in the 82.59. The format of the byte to
be loaded as an ICW3 for a master 82.59 or a slave is shown in the Pig. 8.!0. For master,
each bit In ICW3 is used to specify whether it has a slave 82.59 attached to it on its
corresponrling IR (Interrupt Request) inpul For slave, bits 0 0-0 2 of ICW3 are used to
assign a slave identification code (slave 10) to the 8259.

Copyrighted material
Mlc:roprocosson and Interfaci ng 8-17 8086 Interrupts

ICW3(MASTER DEVICE)
Ao D, De Ds D, D, D, D, Do

I 1 s, So s.
I
s,
I
s, s, s,
I
So
I
1 = IR INPUT HAS A SLAVE
0 :~; IR INPUT DOES NOT
HAVE A SLAVE
ICW3(SLAVE DEVICE)
Ao D, D. D. D, D, o, D, Do

I I I I I I I I I I
1 0 0 0 0 0 10 2 10 1 IDo

I
0 1
SLAVE ID
2 3 4 5 6 7
I 0
0
1 0 1 0
0 1 1 0
1 0 1
0 1 1
0 0 0 0 1 1 1 1

Fig. 8.10 ln~lallzation command word 3 (ICW3)


lnitlallzatlon Command Word 4 (ICW4)
It is loaded only if the 0 0 bit of ICW1 (!C 4) is sel The fo rmat of !CW4 is shown in
Fig_ 8.11.
Ao D, o. D. D, o, D, o, Do
1 0 0 0 SFNM BUF MIS AEOI PM

1 808618088 MODE
0 MCS 801'85 MODE

1 AUTO EOI
0 NOR....-L EOI

NON 8\JFFERED MODE


BUFFERED MODE/SLAVE
BUFFERED MODE/MASTER

1 SPECW.. f'VlLY
NESTEOMOOE
0 NOT SPECIAL FUllY
NESTEOMODE

Fig. 8.11 Initialization command word 4 (ICW4)

It specifics.
1) Whelher lo use special fully nested mode or non spedal fully nested mode.
2) Whether to use buffered mode or non buffered mode.
3) Whclhcr to usc Automatic EO! or Normal EO!
4) cru used. 8086/8088 or 80810.

Copyrighted material
Microprocessors and Interfacing 8 1 8 80861nterrupts

After initialisation, the 8259 is read~ to process interrupt requests. However, during
operation. it might be necessary to change the mode of processing the intemapts.
Ot>erabon Command Words (OCWs) are used for this purpose. They may be loaded
:.nytime n(tcr the 8259's initialisation to dynamically alter the priority mocles.
Operation Command Word 1 (OCW1)
A Write command to the 8259 with A0 = 1 (after ICW2) is intorpreted as OCWI.
OCWl is used for enabling or d isabling the recognition of specific interrupt requests by
programming the IMR.
M = 1 indicates tha t the interrupt is to be masked, and M a 0 indicates that it is to be
unmasked as shown in Fig. 8.12.

1 , Mo .... ....
... ..., M3
"' Mo

I I I I I INlERRUPT MASK
1 =MASK SET
0 : MASK RESET

Fig. 8.12 Operation command word 1 (OCW1)


Operation Comrnond Word 2 (OCW2)
A Write command with At1 = 1 and 0 4 o, = 00 is interpreted as OCW2. 1he
R(Rotntc), SL (Sck-ct-Lcvcl), EOI bits control the Rotate and End Of Interrupt Modes and
combinations of the two. fig. 8.13 shows the Operation Command Word format. L2 - Lo
are used to SJ'I.'Cify the interrupt level to be acted upon when the SL bit is active.


I I I I ~" I I I ... I ... I ... I
0 Sl 0 0

I I
0 I 2 '
' ' '
.
IR lEVEL TO 81! ACT:0 UPON
5 ' 7

' ' '' '''


0 0 I 0

..., r
0 0 0 0
0 0 0 0 '

0
' NON-SPE:CIFIC EOI COtoaAANO
SPECIFJC EOI OClUMA.ND
} END Of INTEARUPT

'' ' ''


0
0 ROTATE OH ~IC ( COtAWfO }
0 ROTATE JN AUTOtAA.TIC EOI MODE (SET) AlJTOJMTIC ROTATlOH
0 0 0 ROTATE IN AUTOW.TIC ECM MOD (CLEAR)
' ROTAT'E OH SPECIAC fCM eot.tMN)

'' ' 0'


I
' SET PRJORITY COlAW) ' } SPf:CIFICROTAnoN
NO OPERATION
' ' L.O-t.2 AA USED

Fig. 8.13 Operation command word 2 (OCW2)

Copyrighted material
Hidden page
Microprocessors and Interfacing 8 . 20 8086 lntaiTUpls

IMR Status Read


A Read command issued to the 8259 with A<o = I (with RD , CS 0 ) causes the 8259
to put out the conte1'ltS of the Interrupt Mask RegLo;ter. OCW3 is not required for a status
read of the IMR.
A.~ described earlier, the sequence shown in flowchart (Fig. 8.4) mlLc;t be followed to
initialize 8259A. According to this flow chart an JCWl and an IOV2 must be sent to any
8259A in the system. If the system has any slave 8259As (cascade mode) then an ICW3
mus t ~ !lAmt to the mas ter? and n difference 1CW3 must be sent to the s lave. If the system
is an 8086. or if you want to specify certain special conditions? then you have to send an
JCW4 to the master and to each slave. To hriVe better understanding the initiation
SL--qucnccs for different specification arc given in the next section.
Note : It is assumed that A1 of thi! system bus is connected to the Ao of the 8259A. So
the intcmal addresses correspond to 0 and 2. It is aLso assumed that the base addr~C\ of
the device is 40H. So the two system addresses for the 8259A are 40H and 42H.
,...,. Example 1 : Write tht' inilinHzation instructions for 8259A int~rrupt controlltr to nu.'tt
tfu~ follawiug specifiCiltiotts :
a) /utarupt lyP<' 32. bi Edge triggmd, siuglt a11d /CW4 m'C'drd.
d Mnsk iuttrrupts IR1 and IR3.
Solution :

ICW1
1 AOI
0 1 0 13H

Note : When used with an 8086. bit 0 11 0 51 0 4 and 0, a re don't care, so we make
them O's for simplicity.
ICW2
In an 8086 system ICW2 is used to tell the 8259A the type number to send in response
to an interrupt s ignal on the IRI) input.

I ~ I : I ~ I : I :: I : I : I ~ I.
2
20H 32 Decimal

!CW2 for sending interrupt type 32 to the 8086 in response to an IRQ interrupt is 20H
Note : For an IRI input the 8259A will send 00!0000! binary (33 decimal ) and so on
(or the other lR inputs.

ICW3
Since we are not using a stnve in our example, we don't need to send an JCW3.

Copyrighted material
Mlcr_.,cessors and Interfacing 8. 21 80861nterrupls

ICW4
For our example, the only reason we need to send an ICW4 is to let the 8259A know
that it is operating in an 8086 system. We do this by making bit 0 0 of the 1CW4 one.
OCW1
An OCWl must be sent to an 8259A to unmask any IR inputs. For our example we
wnnt to mask IR1 and IR3, so we put l''s in these two bits and O's in the rest of the bits.

I : ! : I : I : I ~ I : I ~ I : I
7

= OAH

Program:
t>IOV AL, l3H ; edge triggered , s ingle , ICW4 n eeded
OUT 40H,AL Send ICWl
l-lOV AL, 20 H .
;
t ype 32 i s first 8359A t.ype
OUT 41H, AL ; s end ICW2
MOV AL, Ol H ; ICW4, 8086 mode .
OUT HH, AL ; s end ICW4
MOV AL, OAH ; OCWl to mask IRl and I R3
OUT 41H, AL ; send OCWl

J... Example 2 :
"ri~l
Write th~ it~itialization instructions for master nud SIIJvt' coufigurntiou to
tlre Jolluwiug spedficntions :
11 Tilt INTR of slnve is rout<d through IR2 of the mnslff 8259A to the 8086.
2J Master and slllvt nrt! both /n~el triggt>rffl.
3) First interrupt types for master and slnt't! are 32 and 64 respectively.
4) Modes : automatic rotation aud aJito tnd of inltrrrtpl.
5) Addrm<S of th mnsltr are #JH nnd 41H and lite slavt are SOH and 8lH.
6) Buffers are not used.
lnitializntion command words for Masft'T JCW1 (Mastn)

ICW1 (master)

SNGL

0 IOH

ICW2 (master)

1 ~1: 1 ~ 1 0 I; I; I ~ I~ I = 20H

ICW3 (master)

1~1~ 1 : 1
s.
0 = 04H

Copyrighted material
Microprocessors and Interfacing 8 - 22 8086 lnterTUpts

Program :
MOV AL, 19H ; level triggered, cascaded, ICW4 needed
OUT 41 OH , AL ; send ICWl {ma ster)
M()V AL, 20H ; type 32 is first 8259A type
OUT 41H , AL ; send I CW2 Imaster}
MOV AL, 04 slave at IR2
OUT 42H, AL send !CW3 (master)
10v AL, 0311 ; 1CW4 , SOS6 mode , and set AEOI
OUT 4 1H , AL send 1CW4 {mastt!' r}
MOV AL, 19H l eve l triggered, cascaded, ICW4 needed
OUT SOH , AL send ICWl (slave)
MOV AL, 40H ; type 64 is fi rst 8259A type
OUT SlH , AL ; send ICW3 {slave}
MOV AL, 02H I D fo r slave connected to IR2
OUT 81H , AL ; send ICW2 tslave)
MOV AL, OlH ICW4, 8086 modo
OUT 81 H, AL ; send 1CW4
MOV AL, SOH OCW2 <rotate in auto EO! mode set command)
OUT SOH , AL send OCY12 {s l ave}

8.5.6 8259A Int erfacing


Fig. 8.15 shows that how an 8259A can ~ interfaced with the 8086 microprocessor
system in minimum mode. ln case of 8088 microprocessor same jnterfacing diagram can be
used except M/ 10 signal. In 8088, M/ 10 signal is represented by 10/M signaL therefore
this s ignal is connected to G (active high) signal of decoder to interface 8259A in 1/ 0
mapped 1/ 0 mode.
AddrHsing of 8259A :

A,. A,. Au A,, Au A,o A, A, A, A, A, A. A, Az A, Ao Addreu

1 1 1 1 1 1 1 1 1 1 1 1 0 0 X 0 FFFOH
F F F 0/2 FFF2H

The 74LS138 address decoder w ill assert the C5 input of the 8259A when an 1/0 base
address is FFFOH or FFF2H on the address bus. The Ao input of the 8259A is used to
Sl:'lect one of the two internal addresses in the device. Ao of the 8259A is connected to
system line Al. So the system addresses for the two internal addresses are FFR)H and
FFF2H. The data lines of an 8259A a re connected to . the lower half of the system data bus,
because the 8086 eXJX'CIS to receive interrupt types OJ\ these lowe.r eight data lines. RD and
WR signals are connected h,., the system RD and WR Jines. ~ interrupt req u~t s ignal

Copyrighted material
Microprocessors and Interfacing 8-23 8088 Interrupts

+5V

A,o - v<X G

Address
bus ~ - "
/ 0:, Yo

A, c
...
A,
B
741.5138

Ao A T +5V
~~1 0 <i, GNO
I I
... SPiEN v<X
Control
L-.. cs IRe, --
bus
RO
AO
R5
IR 1
IR, --
WR
INTR
WFi
-INT
IR3
IR4
--
INTA
Do
o,
INTA
Oo 8259A
IRs
IRe,
IR7
--
02
o,
02 CASo
--
o...
bus
o,
o,
o,
o.
o,
o,
o,
o.
CAS 1
CAS2
-
o, o, GNO

...
Fig. 8.15 8259A interface to 8086 s yste m bus

It-IT from O>c 8259A is connected to the INTR input of the 8086 and INTA from 01e 8086 is
connected to INTA on the 8259A. As we are using single l'259A in the system SP/EN pin
is tied high and CAS.,.CAS, lines a re left open. The eight IR inputs are available for
interrupt signals.

Note :
1. Unused IJ< inputs should be tied to ground so that a noise pulse cannot
accidentally cau.<soe an interrupt
2. ln rna.x:imum mode RD and INTA signals of 8259A ar~ connected to the IORC,
IOWC and !NTA lines of 8288 bus controller.

Copyrighted material
Microprocessors and Interfaci ng 8. 24 8086 Interrupts

Cascading :
The 8259A cnn be- ~asily interconncctOO to get' multiple interrupts. Fig. 8.16 shows how
8259A can be conn<.-*<:'ted in the cast(lde mode. In cascade mode one 8259A is configured in
Moster mod~ <\nd other should be configured in the Slave mode. In thio; figure 8259Al is
in the master mode and others are in slave mode. Each slave 8259A is identified by the
number which is assigned as a part of its initiaUzation. Since- th(' 8086 has only one lNTR
input, only one of the 8259A fNT pins is connected to the 8086 INTR pin. The 8259A
connected directly into the 8086 INTR pin is referred as the master. The lNT pins from
other 8259A are connected to the lR inputs of the masrer 8259A. These cascaded 8259As
are referred as sla\ :. The INTA signal is connected to both master and slave 8259A.
(S<e Fig. 8.16 on next page.)
The C..'lscadc pins CASo to CAS2 are connected from the master to the corresponding
pins of thl! slave. For the master these pins function as outputs. and for the slave these
pin,'it function as inputs. The SP/EN signal is tied high for the mas ter. However it is
grounded for the s lowe.
Each 8259A ha.o; iL'j own addres.o;c~ so that command words can be written to il and
status bytes read from it.
Addresses for 8259As :

No A,, A14 A u A,, A, A,o A, Ao Ar Ao As A A, A, A, Ao Address


8259A-1 I 1 1 1 1 1 1 1 1 1 1 1 0 0 X 0 FFFOH
F F F 012 FFF2H

8259A-2 1 1 1 1 1 1 1 1 1 1 1 1 0 1 X 0 FFF4H
F F F 4/6 FFFSH

82S9A3 1 1 1 1 1 1 1 1 1 1 1 1 1 0 X 0 FFF8H
F F F 8/A FFFAH

Master and slave operation :


When the slave receives an interrupt signal on one of its IR inputs. it checks mask
condition and priority of the inte rrupt request. lf the interrupt is unmasked and its priority
is higher than any other interrupt level being serviced in the slave, then the slave will
send an fNT sign'al to the IR input of a master. If that IR input of the master is unmasked
and if that input is a higher priority than any other I_R inputs currently being serviced~
then the master will send an INT signal to the 8086 INTR input. If the INTR interrupt is
enabled, the 8086 will go through its rNTR interrupt pi"'CL:'<fure and sends out two lNTA
pulses to both the master and the slave. The slave ignores the first interrupt acknowledge
pulse but th~ rnasteT outputs a 3-bit sla.ve identification number on the CASo-CA~ lines.
Sending the 3--bit 10 number en(lblcs the slave. When the slave receives the second JNTA
pul> from the 8086, the slave will send the desired type number to the 8086 on the eight
data lines.
If an interrupt signaJ is applied directly to one of the IR inputs of the maste:r, the
mas ter will send the desired interrupt type to the 8086 when it receives the second iNTA
pulse from the 8086.

Copyrighted material
Hidden page
Mlc:roprocessors and lnterfac:ing 8. 26 8086 Interrupts

8.6 Interrupt Example


Tllere arc several reasons for writing interrupt service routine. However, to write such
a interrupt service routine we have set the address of our interrupt service routine in the
interrupt vector table. To set an interrupt vector to a specified address, (starting address of
interrupt service routine) the re are two ways :
1. Using function 25H of !NT 21H
2. Without using any IX)S function.

1. INT21H, Function 25H : Sc lnterrup1 Address


To set a new interrupt address... lo.ld the required interrupt number in the AL and the
new address in the OX :
MOV AH, 2 5H Reque s t inte rru p t address
MOV AL, i nt i Inte r rup t numbe r
LEA ox, newaddr New address fo r in t er r upt
! NT 2 1H
The above program replaces the present address of the interrupt with the new address..
ln eflect, then, when the specified interrupt occurs... processing links to resident program,
rather than to the normal interrupt address.
2. Without using any DOS Function
The DOS fu nction discussed above do nothing more than getting address of interrupt
vector COI'Tespond ing to an interrupt number and IOclding two words (segment address and
offset address of the interrupt service routine) into it. The address of interrupt vector can
be obtained by multiplying the intern1pt number by 4. Once we get the address of the
interrupt vector roblc we have load the segment address and offset address of the
interrupt service routine.
,.... Example 3 : Ce,emte a rtr~l time clot.k by gmemting a p.oriodic intt*rrupt requtsl signal
011 tile NMI input of 8086.

Solution : Hardware : The Fig. 8.17 shows simple circuit that generates intem1pt request
after every 0.5 sec.

39pF 330K
.r~-'WIIr~-lo
15M 4060

Fig. 8.17 Interrupt ~ne,.tlon circuit

Copyrighted material.
Hidden page
' ; 1;
Microprocessors and Interfacing 8-28 80861nterrupts

JNZ DONE
MOV HR, OOH ; Reset HR - 00
DONE : POP SI ; restore register s
MOV AH , 00
I {lET
TIMES ENDP
END START
l.ENf
Review Questions
1. Wlrat do you mevJn by fntt>rmpt ?
2. Wltnt is intemrpl ~rola routiu~ '!
3. Wl111l arr 11~ sourm of h1trrrupt5 ;, 8086 ?
4. Wllat il_iult'rmpt Vt1"tor fllblt> ?
5. Orotuaud explnltl fht IVT for 8086.
6. Brt.'fty. t4-'SCJ'i~ ihe conditions wllicll CIJII~ tile sas6 to pt'rform mch of the following 'YIN'S of
iuttrmpts : Typt 0, Type L Type 2. Typt 3 and Typt 4.
7. Explain itiUhitpl' structure of 8086.
8. Wlrat are sojt'roJ~,. inf("rmpt ? How 8086 ll'Sponds to 5Qftwn intuntpts ?
9. Draw and c).rltliu tf11! internrpt ncknowlc>.dgt cycle of 8086.
10. Dt'S(Tibc. tlrt' rtSporr~ of 8b86 to 111~ int~rrupl coming em pi~.
l 1. WJtal do you memr by i11terrupt priorities ?
12. Stolt" tltC' intNTupt priorities for 8086 inturupts.
13. Wllat On! advmttogN of 1Lii11g 8259 ?
14. LiM tl1e footures of 8159.
15. Expl!liJI l.fle operating modes of 8259.
16. Draw amJ I*Xplm'n til~ itrlt'rfndng of 8259 tvilh 8086.
17. Drnw nnd rxplniu llu hrt~rftm'~tg of cttscndtod 8259s with 8086.
18. E.xplsdn lht pro.:wlurt of lutt'rrupt programming.

ODD

...
'

Copyrighted material
Introduction to DOS and
BIOS Interrupts

In IBM PC. part of the operating system is located in the permanent memory (ROM)
and part is loaded during power up. The part located in ROM is referred to as
ROM-BIOS (B-sic Input/Output System). The other part which is loaded in RAM during
power-up from harddisk or Ooppy disk is known as DOS (Dis k Operating Systom).
BIOS is located in an 8Kbyte ROM at the top of memory, the address range being
from FEOOOH tO FFFFFH. The progra.m s within ROM-BIOS provide the 1110St direct. lowest
level intcrttction with the various devices in the system. Tile ROMBIOS contains routiru.~
for
1. Power~on self test
2. System configuration analysis
3. Time-of-day
4. Print screen
S. Bootstrap loader
6. l/0 support prog'"m for
a. Asynchronous communication ...
b. Keyboard
c. Diskette
d. Printer
e. Display
Most of t~ progr<lms are accessible to the assemblylang,uage programmer through
the software interrupt instruction (!NT). The d<'Sign goal for the ROM-BIOS programs is tO
provide a device-independent interface to the various physkal devices in the system.

(9 1)

Copyrighted material
Mieroprocessors.~,nd Interfacing 92 Introduction to DDS and BIOS Interrupts

It is seen that ROM-BIOS provides basic low-level services. Using ROM-BIOS one can
output characters tp_ various physical deviet.'S lik(> the printer or the d isplay monitor, one
can read characters from keyboard, one can read or write sectors o( data to the diskette.
But still (ew things we can't do with ROM-BIOS.
1. It is not possible to provide ability to load and execute programs directly.
2. It is not pos$ible to store data on the diskeHe organized as logical files.
3. ROM-BiOS h.(I.S no command-interpreter to allow us to copy fllcs, print files, delete
files.
It is DOS tha t provides these services. When we tum our computer ON, we exp~t to
SL->e a mcssoige or a prompt. We except to be able to look a t ~ diskette directory to see
what data files or programs the diskette contains. We expect to run a program by typing
its name. We want to copy programs from one diskette to another, print programs, and
delete progra~1s. All tl1esc scrviees are provided by group of programs "''lied DOS. The
service:; provided by DOS can be grouped into following categories.
1. Character Davie" .UO : This group indudes routineti that input or output characters
to character oriented devices such as th(' printer, the display monitor, and the keyboard.
2. File Management : This group includes routines thai manage logical Iiles, allowing
you to create, read~ write a nd delete rues.
3. Memory Management : Thi,. group includes routines that alJow us to change..
a llocate, and deallocate memory.
4. Directory Management ; This group includes routines tha t permit us to create,
change search.. and delete d irectories.
5. Executive Functions : This group includes routines that aUow us to load and execute
programs, to ov('rlay programs, to retrieve error codes from completed programs, and to
execute commands.
6. Command Interpreter : This routine is in action whenever a prompt is present on lh e
screen. It intcrpre!f. commands and executes DOS functions, utility programs, application
programs.. depending upon the command.
7. Utility Programs : These programs facility to copy, delete provides lhe DISKCOPY,
DIR and m(lny other DOS commands.

Copyrighted material
Hidden page
MlCtOprocusors'ih!fjnterfaclng 9-4 Introduction to DOS and BIOS Interrupts

In! 21H Direct console UO Function 06H

Used by program that need to read and wrire all p<l5Sible characters and control codes
without any interference from the operating system.
Reads a character from the standard input device or writes a character to the standard
output device. 1/ 0 may be redirected.
Calling parameters
AH 06H
DL = fu nction requested
OOH-FEH if output request
OFFH if input request
Returns : Nothing, i f called with DL c OOH OfEH
If called with OL Ff'H and a character is ready returns
Zero fla g = clear
AL '"' 8-bit input data
If cal led with OL = FFH and no character is ready
Zero _ {lag set
! jj.

lnt 21H - - Unfiltered character Input without echo Function 07H

Reads a charac~r"'from the standard input device without echoing it to the standard
output device. If no character is ready, waits until one is available.
Calling Parameter
J\H 07H

Returns
AL 8-bit input data

Example : Read a character from the standard input without echoing it to the display,
and store it in the variable char.
char db 0 ; input character

mov ah, 7 ; function number


int 2lh transfer to MS- OOS
mov char, al save character

Copyrighted material
Hidden page
Microprocessors and Interfacing 9-6 Introduction to DOS and BIOS Interrupti

If the buffer fills to one fewer than the maximum number of characters it can hold,
subsequent input is ignored and the bell is sounded until a carriage return is detected.
Example : Read a string that is maximum of 80 characters long from the standard
input device, placing it in the buffer named buffer
buffer db 81 ; maximum length of input
db 0 ; actual length of input
db 81 dup (0) ; actual input placed here

mov ah,Oah ; function number


mov dx,seg buffer ; input buffer address
mov ds,dx
mov dx.offset buffer
int 21h transfer co MS-OOS

In! 21H Check Input status Function OBH (11)

Checks wheth<'r a character is available from the standard input device.


Calling Parameter
AH = OBH
Retums
AL = OOH if no character is available
FFH if at least one character is available
Example : Test whether a character is available from the standard input.

mov ah,Obh ; function on number


int 21h transfer to MS- OOS
or al,al ; character waiting?
jnz avail jump it char available

Copyrighted material
Microprocessors and Interfacing 9-7 Introduction to DOS and BIOS Interrupts

lnt 21H Flush Input buffer and then Input Function OCH (12)

Clears the standard input buffer and then invokes one of the character input functions.
Input can be redirected.
Calling parameters
AH = OCH
AL = number of input fu nction to be invoked
after resetting buffer (must be OlH , 06H ,
07H, OSH, o OAH)
(i f AL OAH)
DS : DX = segment :offset of input buffe

Returns : (if called with AL = OlH, 06H, 07H, or OSH)


AL 8-bi~ inpu~ data
(if called with AL OAH)
Nothing (dato placed in buller)

9.2 Character Display Functions

lnt 21H Character output Function 02H

Outputs the character to the standard output device.


Calling Parameters
AH 02H
DL 8-bit data tor output
Returns : Nothing
Example: Send the character ...,. to the standard output device.

mov ah, 2 ; function number


mov dl , ' ' ; character to out.put
int 2lh ; transfer to MS - 005

lnt 21H Display string Function 09H

Sends a string of characters to the standard output device. End of string is indicated
by character $ (24H).

Copyrighted material
Microprocessors and lntarfacjng 9 -8 Introduction to DOS and BIOS Interrupts

Calling Parameters
1\H 09H '
OS = segment : offset o f string
Returns : Nothing

Example : Send the s tring, followed by n carriage return and line feed, to the st."lndard
output device.
cr equ Odh
l E equ Oah
msq db ' MICROPROCESSOR', cr , l!,' $'

mov ah , 09h ; f unction number


mov dx . seg msg : address of string
mov ds , dx
mov dx , offsot msg
i nt 2lh ; transfer to MS -OOS

9.3 File Control Block Functions

lnt21H Open file Function OFH (15)

Opens a file and ma kes it available for subst.~uent read/write operations.


Calling Parameters
AH OF'H
OS:OX = se9ment : offset of fi l e control block
Returns :
If function ~uccessful (file found)
AL OOH
and FCB filled in by M5-DOS as follows :
drive fie ld (offset OOH) c 1 fo r drive A, 2 for drive B, etc.
current block field (offset OCH) = OOH
record size field (offset OEH) ~ OOSOH
(2.0+) size field (offset !OH) = file size from direc:tory
(2.0+ 1 date field (offset 14H) date s tamp from directory
(2.0+] time field (offset J6H) = time stamp from directory
If function unsuccessful (file not found)
AL = FFH

Copyrighted material
Hidden page
Microprocessors and Interfacing 9-10 Introduction to DOS and BIOS Interrupts
mov ds, dx
mov d x,. offset myfcb
i nt 21h trans fer to MS-OOS
o r al. al ; check status
jnz error ; jump if close failed

lnt 21H Delete file Function 13H (19)

Dclcles all matching mes from the current directory on the default or specified disk
drive.
Calling parameters
AH = l3H
DS : DX s egment : offset o f fi le control b lock

Returns:
If function successful (file or files deleted)
AL ' = OO H
If function unsuccessful (no matching files were found, or at least one matching file
was read-onJy)
AL ~ FFH
Example :
Delete the file TEST.DAT from the current dL<k drive and directory.
myfcb db 0 drive default
db ' TEST' f ilena me , 8 characters
db ' OA'l" e x tension , 3 characters
db 25 dup ( OJ remainder of FCB

mov ah, 13h function number


mov d x, seg my feb ; a ddress of FCB
mov ds , d x
mov dx,. off sct my feb
i nt 2lh ; trans f e r to MS-OOS
or aLal ; c h eck s t a tus
j nz e r ror ; jump i f close failed

Copyrighted material
Microprocessors and, Interfacing 9 -11 Introduction to DOS and BIOS Interrupts

lnt 21H Sequential read Function 14H (20)

Re\lds the next sequential block of data from a file, then increments the file pointer
appr<>priately.
Calling parameters
AH 14H
DS : DX = segment : offset of previously opened file
control block

Returns
AL = OOH if read successfu l
OIH if end of file
02H if segment. -,.rap
03H i f partial record read at end of fi l e

Example .: Read 512 byt.,. of data from the file spe<:ified by the previous ly opened file
control block myfcb.
myfcb db 0 drive = defau lt
db ' TEST' filename , 8
characte rs
d.b ' OAT' extension , 3
characters
db 25 dup (0 ) remainder of FCB

mov ah,14h function number


mov dx, seg my feb address o f FCB
mov ds, d x
mov dx, offset my feb ; set record size
mov wo r d ptr myfcb+Oeh , Sl2
int 2 lh ; transfer to t~ S - DOS

or al , al ; check status
)n error ; j ump if read fa iled

lnt 21H Sequential write Function 15H (21)

Writet the next sequential block of data from a file, then increments the file pointer
appropriately.

Copyrighted material
Hidden page
Microprocessors and Interfacing 9 13 Introduction to DOS and BIOS lntetTUpls

and FCB ftlled in by ~-IS-DOS as follows :


drive field (offset OOH) I for drive A. 2 for drive B. etc.
curm1t block field (offset OCH) OOH
record size field (offset OEH) OOSOH
(2.0+(size field (offset lOH) file size from dir<-ctory
(2.0+1<'ote field (offset l4H) date s tamp from d irectory
(2.0+1 time field (offs<Jt 'l 6H) lime s tamp from directory
If function WlSUccessful (directory full)
AL = FFH

Exampt. : Create a file in the current directory using the name in the file control block
myfcb.
ay!cb db 0 ; drive default
db ~TE ST' ' ; H lcnA.t:li&, 8 characters
db ' OAT' ; e x tens ion, 3 charact.rs
db 25 dup 101 I remainder of res

mov ah , l6h ; function number


mov dx,seg my!cb address of res
mov ds,dx
mov dx, offset my feb
inc 2lh transfer to MS-cos
or al, a! ; check status
jn z er::or ; Jump i f create failed

lnt 21 H Rename file Function 17H (23)

Allers the name o( all matching files in the current d.irectory on the disk in the
specified drive.
Calling parameters
AH = l7H
os : ox = seqment:offset of '"'specia l .. file control
block
Retums : If function successful (one or moc files arc renamed)
IlL = OOH
II function wtsuccessful (no matching files, or new filename matdu.od rm cxbting fiJe)
AL = FFH
Microprocessors and Interfacing 9-14 Introduction to DOS and BIOS Interrupts

Example : Rename the We .OAT to NEWNAME.DAT.


mytcb db 0 drive default
~

db ' OLONAM' old file name, s characters


db ' OAT ' old extension , 3 cha racters
db 6 dup ( 0) reserved area
db ' NEWNAME' new file name, s characters
db ' OAT ' new extension, 3 characters
db 14 dup ( 0) ; reserved area

mov ah, l?h function number


mov dx,seg my feb ; address of FCB
mov ds, dx
mov dx , offset my feb
int 2 1h transfer to MS-OOS
or a 1, <3: 1 chec k status
jnz error ; jump i f close failed

lnt 21 H Get file size Function 23H (35)

Searches for a matching fLJe in the current directory; if one is found~ updates the FCB
with the file's size in terms of number of records.

Calling Parameters :
!\H 23H
DS:OX segment : offset of unopened fi l e control
block
Returns : If function suocessh~ (matching file found)
!\L = OOH
a"d FCB relative-record field (offset 21 H) set to the number of records in the file.
If function unsuccessful (no matching file found)
AL = FFH

Example : Determine the size in bytes of the file MICRO.DAT


myfcb db 0 drive : default
db 'MICRO' filename, 8 chars
db 'OAT' extension , 3 chars
db 25 dup (0) remainder of FCB

Copyrighted material
Hidden page
Microprocessors and Interfacing 9 - 16 Introduction to DOS and BIOS lnterru~

Ir function.
fa iled
Carry flag = set
AX = error code
Example : Crea te and open,or truncate to zero length a1\d open, the file
C : \ 1-JBS\PROl.ASM and $3ve the handle for ~ubsequent
access to the file.
fname db 'C: \M.BS\PROl.ASH', 0
handle dw ?

mov ah, 3ch ; function number


xor cx , cx ; no_rmal attribute
!t'IOV dx , seg !name ; address of path name
mov ds , dx
mov dx , offset fname
.t.IW 2 lh transfer to HS-DOS
jc e r ror jump i f create failed
mov fhandlo , ax . ; save file handle

lnt 21H Open file Function 3DH (81)

Op..n:.\ th'l" ~pl'<'Hied fill


in the dcsignah:.od or default d irectory on the designated or
defa ult d isk drive. A handle is returned which can be u..~ by the program for subsequent
ac."C('S.c; tc) tht! file.

Calling ParametO<S
1\H 3DH

Bit (S} Siqnitica.nce


0-2 access mode
000 = r ead access
001 = write access
LlJ""' !"e-<:HJ/wdte access
3 r eserved (0)
: .. 4-o sharinq mode (MS- DOS versions 3. 0
and later J
000 compatibili t y mod e
00, = der!l/ a ll
Olil - deny write

Copyrighted material
:: 2',(,
Mi.CI;OP<Q~:easors a!)d lnlllrfaclng 9-17 lnlroductlon to DOS-andBIOS Interrupts

011 ,.. d~ny read


100 deny none
7 inheritance flaq (MS - OOS versio ns 3 . 0
' later)
0 = child process
inherits handle
1 ch ild does not inherit handle
OS : OX segment :o ffset of ASCII path name

Returns : If function s uccessful

Carry flag clear


AX = handle
If function unsuccessful
Carry flag = set
AX error code

Example : Open the file C:\ \ PROI.ASM for both reading and writing, and save the
handle for subsequent ac:ccss to the file.
fname db ' C o \~IBS \ PROl.ASM',O

fhandl e dw ?

mov ah,3dh function numher - -


mov al,02h mode -
read1~-~ i te
mov
mov
dx , seq t nau\e
ds,dx
a.ddress of .. , nAme
pa.th

mov dx , offset fname


int 21H transfer to MS-tiOS
jc e rro r j ump if open
.failed
rr.ov fhand le, al< :J11,(~ !ill! ~dn(flc

lnt 21H Close file Function 3EH (62)

Given a handle that was obtninl' \1 by ~' previous succLossful open or create operatiun,
flushc."S all internal buffers associated with the file to disk.. doses the file, and releases the
handle for rcu~. If the file was modiik-d. the time and date stamp and flit> :o>izt .ur
upd.ltt.od in the filt.'s d irectory entry.

Copyrighted material
9 18
.
Introduction to.DOS and BIOS Interrupts

Calling Parameters
AH = 3EH
BX handle

Returns : If function successful


Carry flag -= clear
If function unsuccessful
Carry flag = set.
AX error code
Example : Clnse the fi1e whose handle is saved in tf'w varia:bJe fhandle.
fhand l e dw 0

mov ah,Jeh ; function number-


mov bx , handle ; f ile handle
int 2lh ; transfer to MSDOS
....J c error ; jump i f c l ose fai led

<1 ' I'


lnt 21H Read file or device Funct ion 3FH (63)

C ivcn a valid file handle from a previous open or create operation. a buffer address,
and a length in bytes, transfers data at the current file-'pointer position from the file into
the buffer and then updates the file pointer position.
Calling Parameten
AH 3FH
BX = h andle
ex number of bytes to read
OS:DX = segment : offset of buffer
Rotu<ns : If function successful
Carry fla g = c lear
AX bytes transferred
lf function unsuccessful
Carry fla g set
AX = error code
Examp&e : Using the fill' handle from ~ previous open or create operation, read 512
bytes at the current file pointer into thll! buffer named buff.

Copyrighted material
Introduction to DOS- B IO&Inlerrupls

buff db 512 dup (?) buffer lor read


fbandle dw ? ; contains file handle

-
mov ah , Jfh ; f unction number
mov dx, seq buff ; buffer address
mov ds , dx
mov dx, offset buff
mov bx, fhandle ; file hand le
i ~
mov ex , 51 2 ; length to read
int 21h ; t ransfer to MS-OOS
jc error ; jump, read fai l ed
cmp ax , e x ; check length of read
jl done ; jump, end of file

lnt 21H Write file or device Function 40H (64)

Given a valid file handle from a previous open or cre01tc opc:rtttui"n, i'l buffer address,
and a length in bytes, transfers data from the buffer into the file an!! then updates the file
pcJinter posi lion.
Calling parameters
AH = 40H .,.
BX handle ..
ex .. number of bytes to write
DS:DX = segment:offset of buffer

R.tums : If function suC<>!SSful


Carry flag clear
AX = bytes transferred
"
If function unsuccessful
Ca rry fla9 = set
AX error code
Example : Using the handle from a previous open or create operation, write 512 bytes to
disk at the current file pointer from the buffur named buff.

' .

Copyrighted material
Mlcroprocess~m .':>.d Interfacing 9-20 Introduction to DOS and BIOS Interrupts

buff - db 512 dup (?) ; buffer f or write


fhandlc .,::d.,.. ? ; contt!lins file handle

.... .
mov ah, 40h ; function number
mov dx, seg buff ; butter address
mov ds , dx
mov dx, offset buff
mov bx, f handle file handle
mov ex, 512 ; l ength to write
int 2lh ; transfer to MS- OOS
jc erro r jump, failed
write
cmp ax, 512 entire record writ t en?
jne error no , jump

lnt 21H Delete fila Function 41H (65)

Deletes a file lrorri 'flie specified or default disk and directory.


Calling Parameters .a<>
AH 4 1H
DS : DX = segment : offset of ASCIIZ pathname

Returns : If function success(uJ


Cetrry flag clear
If function tm.SUCCCssful
Carry _f' f aq_
"- = set
. .AX e r ror code
Example : Delete'lhe' file named MICRO. OAT from the directory \ MYDIR on drive C.
fname db ' C : \ r<YDIR\MICRO . DAT' , 0

mov ah , 4lh function number


mov dx , seg f name f ile name address
mov ds, dl<
mov dx, offset fname
int 2lh transfer to MS - OOS
jc error jump it de l ete failed

Copyrighted material
.,, .
M_lcroproc:eosors"anel.lnterfaclng 9 21 Introduction to ooaanc'I.Bios lntenupts


INT21H Move file pointer Function 42H (66)

DOS maintains a file pointer. The open file operation initialize file pointer to 0 and
subsequent sequential reads and writes incr~ment file pointer by record.
Calling pararMtors
1\.H 42H
AL = method code
OOH absolute offset from start of file
Ol H siqned offset from current file poi nter
02H signed o ffset from end of fi l e
BX handle
e x = most sign ificant half of offset
OX l east signficant hal f of offset

Returns : If function successful


Ca rry flag
-
clear
OX = most sig nificant half of res.ul,ting file
pointer
AX = l e ast significant ha lf of resulting file
pointer
[('function unsuccessful
Carry tlag ~ set'
AX =- error code It

.... ,~

lnt 21 H Rename file Function 56H (86)


..
Renames a fiJe and/or moves its directory entry to a different directory on the SC~mc
disk. ln MS-DOS version 3.0 and later, this function can also be used torename directories.
Calling parameters
1\.H = 56H
OS: - segment:o ffs et of current ASCIIZ pathname
5:01 - segment:offset of new pathname
Returns : If function successful
Carry flag = c lear
If function unsuccessful
Carry flag set
AX error code

Copyrighted material
I Z2 ;.. -.ction to DOS end BIOS lnlerrupta
Example : Change the name of the 61e.~~.DAT in the directory \MYDIR on drive
C to MYTFXT.OAT. At the same time. n\oYi! .11\e 6Je to the directory \SYSTEM on the
same drive.
oldname db 'C: \ MYDIR\ MYFILE.OAT' ,0 ; drive defau l t
newname db ' C: \SYSTEM\ MYTEXT.DAT' ,0

mov ah ,
56h function number
mov . '
dx , seq oldname old filename address
mov ds , dx
mov dx, oft set oldname
mov di, seq newname ; new fi lename address
mov es , di
mov di, offset newname
int 2 lh ; transfer to MSOOS
jc error ; jump i f rename
; fai l ed

9 .5 Memory Management Functions

lnt 21H Allocate memory block Function 48H (72)

Allocates a block of memory and retums a poinrer to the beginning of the allocated
an.--a.
Calling paramete rs :
AH 4811
BX ~ number of paragraphs of memory needed

Returns : If function successfu!


Carry f l ag clear
AX = base segment address of alloca ted block
If function u.nsucressful
Carr y flag = set:.
AX &;e r r o r code
= size of largest available block
{paragraphs}

Example : Request 64 KB block of memory for use as buffer.


bufseq dw ? ; seqment base of new block

Copyrighted material
t 23 tntroduc:tion to DOS UKI BIOSint.nupa

mov ah,48h ; f unction number


mov bx, lOOOh ; block si:te (pa ragraphs!
int 2l h ; transfer to MSDOS
jc err o r ; j ump i f alloca tion t ailed
mov bufseg, ax ; save segment of new block

lnt 21H Release memory block Function 49H (73)

ReleOS<!S a memory block and makes it availilble for use by other programs.
Calli"ll parameters :
AH = 49H
es segment of b loc k t o be released
Returns : If function succes..~ful

Carry flag clea=


If function unsucces...;fuJ
Carry flag .. set
AX = error code

Example_: Releose the memory block tl>at was previously allocated in the example for
21H Function ~SH.
bufseg dw ? ; segment base of block

mov ah , 49h ; function number


mov es , bufseg ; base segment o f block
int 2lh ; transfer to MS-DOS
jc error ; j ump i f release fa i led

lnt 21H Resize memory block Function 4AH (74)

Dynamically shrink.o; or extends a memory block, according to the needs of an


application program.
Calling paramot.rs :
AH 4AH
desired new b l oc k s i ze i n paragra phs
ES segment of block to be modified

Copyrighted material
Hidden page
Microprocessors and 'Interfacing 9 - 25 Introduction to DOS and BIOS Interrupts

lnt 15H Get extended memory size Function 88H{136)

Returns the amount of extended memory installed in the system


Calling parameters :
AH a 88H

Returns :
AX = amount of e x tended memory {in KB)

9.6 Display Functions Provided by ROM BIOS

lnt 10H Set video mode Function OOH

Selects thl' current video dis play mode. Also sele<:ts the active vidoo controller, if more
than one vidro controller is present.
Calling Parameters
AH = OOH
AL '"' video modes

Returns Nothing

Differ ent Video Modes

Mode Resolution Colors Text/graphics


0011 40-by-25 16 text

ook>rburstoff

Ot H 40-by-25 16 text

02H 80-by-25 16 text

color bUI'$1 otf

03H 80-by-25 16 text

04H 320-by-200 4 groplllcs


OSH 320-by-200 4 graplllco
color burst off

06H 640-by-200 2 graphics

07H 80-by-25 2' text

08H 160-by-200 16 graphics

Copyrighted material
Introduction to DOS and BIOS Interrupts
Mic:,roprocessors and lnterfac;,,lg
-9-26
09H 320-by-2(;0 I 16 gralll1k:O
OAH 640-by-200 4 ~ralll1ico

OBH reserved

OCH esorved
ODH 320-by-200 16 graphics

OEH 640-by-200 16 graphics

OFH 640-by-350 2' graphics

10H 640-by-350 4 graphics

10H 640-by-350 16 gralll11cs


11H 640-by-480 2 graphics

12H 640-by480 16 graphics

13H 320-by-200 256 gmlll11cs

lnt 10H Set cursor type Function 01H

Selec-ts the starting and ending lines for the bUnking hardware cursor in text display
modes.
Calling Parameters :
AH OlH
CH bits 0 - 4 = starting l ine for cursor
CL bits 0 .. 4 endi ng l ine for cursor
Note : Cursor om be disabled by se1ting CH = 20H

Retumo : Nothing

lnt 10H Sat cursor position Function 02H

Positions the cursor on the display, using text coordinates.


Calling Parametero :
AH 02H
BH page
DH = row (y coordinate)
DL column (x coordinate)

Returns : Nothing
Mlcroprocesaors end tnt.rfaclng 9-27 Introduction to DOS and BIOS lnttrrupts

lnt 10H Get cursor po&ition Function 03H

Obtains the C\Jrrertt position of the cursor on the display, in text coordinates.
Catling Parameters :
AH = ' 03H
BH page

Returns :
CH starting l ine for cursor
CL = e ndin9 line for curso r
OH row (y coordina te }
DL = co l umn (x coordinate)

lnt 10H Reed character end attribute et cursor Function 08H

Writes an ASCR character and its a ttribut~ to the display at the current cursor
position.
C.lllng P.ameters :
AH = 08h
AL = character
BH page
BL attribute (text modes) or color
{graphics modes)
e x = count of characters to write
(replication f a ctor)
Return& : Nothing

lnt 10H Write character at cursor Function OAH (10)

Writes an ASCU character to the display at the current cursor position. The character
receives the attribute of the previous character displayed at the same po5ition.
Cdlng Parameters :
AH = OAH
A.L character
BH = page
BL = color
ex = count of characters to write
(repl i cati on factor}
Retumo : Nolhillg

Copyrighted material
Hidden page
Mlcropr.ocessors and Interfacing 9. 29 Introduction to DOS and BIOS Interrupts

mov ah,S : function number


mov dl,' ' ; chara cte r to outp ut
int 2lh ; transfer to MS - 005

lnt 17H Write character to printer Function OOH

Sends a character to the specified parallel printer interface port and retum~ the current
status of the port.
Calling parameters :
AH = OOH
AL character
OX = pri nter number (0 LPTl, 1 ... LPT2,
2 = LPT3)

Returns :
AH status
Bit Significance (if s et)
0 printer timed- out
1 unused
2 unused
3 I/0 error
4 printer selected
5 out of paper
6 printer acknowledge
7 pr inter not busy

lnt 17H Initialize printer port Function 01 H

initializes the specified parallel printer i_nterface port and returns its status.
Calling parameters :
AH = O! H
OX printer number (0 ~ LPTl, 1 LPT2 ,
2 = L PT3 )

Retums :
AH status (see lot 11H Fu nction OOH)

Copyrighted material
Microprocessors and Interfacing 9-30 Introduction to DOS- BIOS Interrupts

lnt 17H Get printer status Function 02H

Retun't~ the current status of the specified p;1rclllel pri_n tcr interface port.
Calling parameters :
l\H 02H
DX ""' printer number (0 LPT l , 1 = LPT2 ,
2 ~ LPT3)

Ratums :
AH = sta t us (see Int 17 H Function OOH)

(J(J(J

Copyrighted material
10~----------------~

Serial Communication

Most of the microprocessors are designed for parallel communication. In parallel


communication number or lines required to transfer data depend on the number of bits to
be tr<~nsferred . For example, to transfer a byte of data, 8 lines are required and all 8 bits
are transferred s imultaneously. Thus for transmitting data over a long distance, us ing
paraUel communication is impractical due to the increase in cost of cabling. Par4Hel
communication is also not practical for devices such as cassette tapes or a CRT terminal. In
such situations, serial communication is used. In serial communication one bit is
transferred a t a time over a single Une.
To implement serial communication in the microcomputer system, it is necessary to
ul\dcrstand the basic ronct.."1'ts of serial communication. The following se<tion describes the
basic concepts involved in serial com.municatlon.
Basic concepts :
1. Classification
2. Transmis.-.ion forma t51
3. Data communication over telephone lint.."S
4. Error detection
5. lntt>rfacing requirements
6. SctiaJ conununicntion standards.

10.1 Classification
Serial dntn transmission can be classified on the basis of how transmission occurs.
l. Simplex
2. Half duplex
3. Full d~plex

10.1.1 Simplex
ln simplex, the hardware exists such that data transfer tak.L--s plact' only in om.
direction. There is no possibility of data transfer in the other direction. A typical cxampl(
is transmission from a computer to the printer.
(1 0 1)

Copyrighted material
Microprocessors and Interfacing 10.2 Serial Communicatior

10.1.2 Half Duplex


Th(' half dupl('X trtu\smi.s.....-ion allows the datn transfer in both directions, but no
s imultaneous ly. A typical example is a walkicHalkj(',

10.1 .3 Full Duplex


The full duplex ITaOSmission allows the data transfer in both d irection s imultaneously
The typical example is transmission through telephone lines.

10.2 Transmission Formats


11\e data in the serial communiation may be sent in two fo rmats :
a) Asynchronous b) Synchronous

10.2.1 Asynchronous
Fig. 10.1 shows the trnnsmission format for asynchronous transmiss ion. Asynchronou:
formats oH\' ch.u.lctc-r oric.-ntcd. In this, the bits of a character or data word are sent at
constant rate, but characters can come at any rotc (asynchronously) as !ong as they do no
overlap. Wh~n no"characters are being sent. a line stays high at Jogic 1 called mark, logic (
is ~1II L'tl space. Tilt.> beb..Jnning of a character is indicated by a start bit which is alway:
lu\\'. This i~ used tu synchro1\ize the tran.~mith!r and receiver. After the s tart bit, the dat.:
bit:~ nn. stJH with INst significant bit first, followed by one or more s top bits (active high)
Tht:. !\top l>it:-o indicate the end o( character. Different systems use 1, 1 1/2 or 2 stop blts
Th~o. ~,... mN n.ltion v( s tart bit. character and s top bits is known as frame. The start and s tar
bib co.1rry n o inforn1Z1tkm, but are required because of the asynchronous nature of data.
Fig. 10.2 illustrates how the data byte CAH would look when transmitted in t~
asynch runnu~ SCrii-11 format.

Tronsmittt~t Reoeiller

CLK CU<
rome
Fig. 10.1 Transmission format for asynchronous transmission

1 $101) bll

Transmittet Receivec

Tome - --

Fig. 10.2 Asynchronous format w ith data byte CAH


Copyrighted material
Microprocessors and Interfacing 10-3 Serial Communication

11\e data rate can be expressed as bits/sec. or charactcrs/St.-:>e. tne


tCrn\ bits/sec is also
called the baud rate. The asynchronous format is generally used in l dW-speed transmission
(less U>an 20 Kbits/sec).

10.2.2 Synchronous
The start and s top bits in each
I - I
"""' frame of asynchronous format
represents wasted ove rhead bttes
s,...l-1 I I I I I tha t reduce the overall character
T~l!lllr
"""'H
-
o... rate. Th~ .~tart and s top bits can
Tlnut -
be climinated by synchronizing
receiver and trAnsmitte r. They can
Fig. 10.3 Synchronous transmission format be synchronized by having "
common dock signal. Such a
commul'tication is called synchronous serial communication. :rhe Fig. 10.3 shows the
tran~m ission format of synchronous sc-rial commw'lication. . ln th is transmission
synchr01'10US bits are inserted ins tead of start and s top bits.

Sr. No. Asynchronous Serial Communication Synchronou.s S.rial Communication


1. Transmltters and
$ynchronizod by clock.
receive.., ... not Transmitter and reoeivers are synchronized by
Clock.
'
2. Bits of d ata are tr~nsmiltd at con$tant rale . Oala bils are transmitted with synchronisation
of"""" '
3. Chatader may an1ve at any t,.t.e at receiver. Character is received at conslant rate.

4. Data ttanSfer is Character orien ted. Oats tmnsler takes pface tn block.$.

5. Start and stop bits are required to establiSh


communication of each character.
&art and $top bit$
establish communk:&11on
.,.ot not r&Quired lO
e3ch Cha(a(ter,
however. sync::hronlsatlon bils are reqtired 10
transfer the data blOCk.

6. u...s In IOwspeod transmissM:ms at aboul Used in high-speed transmissions


speed less than 20 kbiiSisec.

Table 10.1 Comparison between asynchronous and synchronous serial data transfer

10.3 Interfacing Requirements


To impl("ment serial communica tion in microproa.:.ssnr sy;o;tcm \'!'C ne..."<i ha ~icall v two
devices :
1) Parallel to serial converter 2) Scrinl to parnllel converter.
To tral\S1nit byte data it is necessary to oonvert byte into eight serial birs. Thi' cnn b(.
done by using the parallel to serial converte-r. Similarly at the reception th~se serial bits
must be converted into parallei 8 bit data. The serial to parallel convqrter is u~l"'i h'
convert serial data bits into the parallel datJ.

Copyrighted material
Mlc:toproc....,... andilnterfacl ng 10-4 Serial Communication

'The devices are designed for his purpose are called universal asynchronous
receiver-transmitter (UART). The devices which provides synchronous as weU as
asynchronous transmission and reception are called as universal synchronous
asynchronous receiver-transmitter. A good example of UART is 8250 and USART is 8251.
'These devices are software programmable for number of data bits$ parity and number of
stop bits. In the next sections, we discuss the 8251 (USART).

10.4 USART 825~

To implement serial communic..,tion in microprocessor system we need basically two


devices : 1) ParaiJel to serial converter
2) Serial to parallel converter.
To transmit byte data it is necess.uy to convert byte into eight serial bjts. This can be
done. by using the parallel to serial converter. Similarly a t the reception these ~rial bits
must be converted into parallel 8 bit data. The serial to parallel converter is used to
convert serial data bits into the parallel data.
Tile devices are d(!Signed for this purpose are called un iversal asynchronous
receiver-transmitter (UART). The devices which provides synchronous as well as
asynchronous transmis.o;ion and reception are called universal synchronous asynchronous
recei,er-transmitter. A good example of UART is 8250 and USART is 8251. 1hese devices
are software prot,rrammable for number of data bits, parity and number of stop bits. In the
ne.xt section we d iscuss IC 8251 (USAR1).

10.4.1 Features
1. The lntcl 8251A is an universal synchronous and asynchronous communication
controUer.
2. It supports standard asynchronous protocol with :
a) 5 to 8 Bit character format
b) odd, even or no parity generation and detection
c) Baud rate from DC to 19.2 Kbaud
d) False start bit detection
e) Automatic break detect and handling
f) Break character generation.
3. It ha..i built in baud rate 8'--nerator.
4. It supports standard synchronous protocol with :
a) 5 to 8 Bit character format
b) Internal or external character synchronization
c) Autom..'llic sync insertion
d) Baud rate from DC to 64 Kbaud

Copyrighted material
Microprocessors and Interfacing 10.5 serial Communication

5. It allows full duplex transmission and reception.


6. It provides double buffering of data both in the transniission section and in the
receiver sectio n.
7. It provides error detection logic, which ddects parity, overrun and framing errors.
8. ll has Modem Control Logic, which supports basic data set control signals.
9. (t provides separnte dock inputs for roo..:.ivcr and transmitt<:r sections, thus
providing an option of fixing different baud rates for the transmitter and receiver
section.
10. It Lc; compatible with an extended range of Intel microprocessors.
11. It is fabricated in 28 pin DIP package and its all inputs and outputs are TIL
compatible.
12. It is available in standard as well as ~tended temperature range.

10.4.2 Pin Diagram of 8251A


Fig. 10.4 shows the pin diagram of 8251 A.

o, o,
o, Do

""' Vee
;;;c
o, OrR
o, RTS
o, DsR
RESET
CLK

TICE:mpty
CTs
SYN OET 180
T11ROY

Fig. 10.4 Pin diagram of 8251A

Data Bus : Bi-directional, tri-state, 8-bit Data Bus. Thlc; pin aJiow transfer of bytes
between the CPU nnd the 825LA.
RO (Read) : A low on this input allows the O'U to read data or status bytes from
8251A
WR (Write) : A low on this input allows the CPU to write data or command word to the
8251A.

Copyrighted material
Hidden page
Microprocessors and Interfacing 10.7 Serial Communication

TxC (Transmitter Clock) : This dock input controls the rate at which thE: character is to
be transmitted.
Receiver Signals

RxD (Receiver Data) : This input receives a composite serial st:reilm of data on the
rising edge ol RxC.
RxRDY (Receiver Ready) : This output ir'ldicatcs that the 8251A contains a charact..,r
that is redy to be input to the CPU.
RxC (Receiver Clock) : This clock input controls the r.th: at which the character is to be
received.
SYNDET (Sync Detect)/ BRKDET (Break Detect)
This pin is used in synchronous mode for detection of synchronous characters and
may be u!'Cd as either input or ou tput.
In asynchronous mode this pin gtX'S high if receiver line stay~ low for more than 2
character times. It then indicates a break in the data s tream.
When used as an input (external sync detect mode) a positive ~ignal will cause the
8251A to s tart receiving data characters on the rising edge of the next RXC.

1 0.4.3 Block Diagram


Fig. 10.5 shows the block diasrarn ol IC 8251A. It includes : Data bus buffer,
Read/ Writ.:! control logic* modern cont'rOI. Tral'lStnit buffer, Transmit Control, Receiver
Buffer and Receiver control.

....
Dal
bufter
L -"
~
Transmit
buffer
(P- S) - r.o

l
RESET -
c
Cl~
;;-
~::::
R-
"""""'
logic
Transml' -- TxROY
TE
w
ccntrol
- fie
cs
'
_., -
SR -

- -
Rooeive
TR --< Modem buffer
(S-P)
S --<

In~ - -
data bus

"-
- ReoeNe

"""''"' -.__ RtROY


RiC
SYNOET

Fig. 10.5 Block diagram

Copyrighted material

Hidden page
Mlcroproceaors and Interfacing 10 10 Serial Communleallon

I. Mode instruction 2. Command instruction


Mode lnstruchon : Fig. 10.6 shows the mode instruction forma t.

,o,,o. ,o. , o. o3 I o, o, Do Baud rat factor


---.......--.-' ---.......--.-'
~~ oo- svNmOdo
01 - ASYNw1
10- ASYN1d6
11 -ASYNI(64

Character r.ngth
00- Sbits
01-6bits
10-7 bits
11-8 bits

Framing control Parity control


00 -Not valid XO-No parity
0 1-1 stop bit 01-0dd patity
10- 1 1/z$top bitS 11 -even parity
11 - 2 ~op bi1S

Fig. 10.6 Mode instruction format


The instmction can be considered as four 2-bit fields. The first 2-bit field (0 1'00)
determines whether the USART is to operate in the synchronous (00) or asynchronous
mode. In the asychronous mode, this field determines the division factor for dock to
dedde the baud rate. For example, if 0 1 and 0 0 are both ones, the RxC and TXC: will be
d ivided by 64 to cstabli~h the baud rate.
The :;(..'CQnd 2bit field ( Dr D 2) determinet> number of data bits in one character. With
this 2blt field we can set character length from Sbits to 8 bits.
The third 2-bit field, (0 , -0,), controls the parity generation. The parity bit is added to
the data bits only if parity is enabled.
. ..
The last .field, (0,-06 ), has two meanings depending on whether operation is to be in
the synchronous or asynchronous mode. F-or asynchronous mode, (i.e. 0 1 0 0 ;t 00), it
controls the number of STOP bits to be transmitted with the ch..v acter. In synchronous
mode, (i.e. 0 10,) = 00) this field controls the synchronizing process. It decides whether to
operate with exteinal synchroniza~ion or internal synchronization and whether to transmit
single synchronizing character or two synchronizing characters.
Command Instruction
After the mode in...;truction, command character should be issued to the USART. It
controls the operation of the USARl within the basic frame work established by the mode
instruction. Fig. 10.7 shows command instruction format.
It does function such as : Enable Transmit/Receive, Error Reset and modem control.

Copyrighted material
Mlcroproce..on and Interfacing 10 - 11 Serlal CommunicatiOn

--
IEHIIRJRTSl<R lbiO l<>lli1T<Hj
&let* """' ft!IOIOit.
1

--
"'*' ....,.,.. lOr
~~
I I
-
- 12$1 IOmodle

A~t10Mnd
1~RTS
---
t EtM1t1it DTR

Ft.ot~.... 4INible
I ENIH
0 """"'
Error~tel Sind br"ll ~let
1 RtMI tff'1)f A.-gt 1 fi':oroes T')O 'LOW"
PE.OE,F 0 Norm,. Cperllion
'(Hat no elf.a inAsync: li"'Ide)
Ho4e :Error re&et must be perlorme<l-'!enev.r
RX et~ebfe a~ en1e.r N.lnt are l)fDgfammecl

Fig. 10.7 Command instruction format


10.4.5 8251A Statu Word
In the data communication systems it ts often necessary to examine the ...status"' of the
lransmitter and recclver. It I also necessary for CPU to """"' 1f any error has ocrured
du.ring communication. 'The 8251A alJO'\,. the programmer to read above mentioned
informahon from ct., ""t""
rq;isrer any time during lhe func11onal operation. Fig. 10.8
shows the format of soaous register.
o, o o1 o,. o, o, ol o.,
IOSR ~~~=I e IDE IPE ITEMPTY IRxRDYITxROY
L flklte 1
Slime Mtinltlons 110 pins

P111rity Eri'Of'
The PE ftag It a.ec ~on a1)anty error Is
dlOI;Iod, II ._ roto~ by lhe ER bit of the
command ll\l.lruclion, PE duel not inhibit
operaUOI'I of lht 8215 1A

Overrun IIN'or
TM oe ftllg le ... .,........ the CPU doos
1'101 read chereetef befor. the Mlll or-.
beComH av...ble II t. , .... bV the ER
bllottn.~ ~ oe: ~
nollnhlbic ~Of h 82151 A. fto.eYef,
--~~~-bit.

,.,..mlfto Ctf'Ot (MyftC only)


~ FE. fttt lie Mt whM valid e.t100 bil is 1'10(
eMU =*I .. .,_ end Of .-..ry~.lt is
,.... by l'le ER bit Of tM canrnrod Nln.o
lien FE ~ not lntlibl\ the CIPM'tion olah41
82S1A

_I Dt.IJ , ,.My:
ln<JiCatn IMt ,,. DSR l t e :.t~ levet.

Fig. 10.8 Status register formal


Lopyrighted ma eri.JI
Microprocessors and Interfacing 10 12 Serial Communl~tlon

Error Definitions

Partty Error : At the tjme of trc1.nsmission of data an even or odd parity bit is inserted in
the data s tream. At the receiver end, if parity of the character does not match with the
pre-defined parity oarity error occurs.
Overrun Error : ln the receiver section received character is s tored in the receiver buffer.
The CPU is supposed to read this character before r~ption of the next character. But if
CPU fails in re:1ding the character loodcd in the receiver buffer, the next the received
chamcter repl:lccs the previous one and the OVERRRUN Error occurs.
Framing ErTor : lf valid stop bit is not detected at the end eac-h character framming
error occurs.
All these errors, when occur, set the corrosponding bits in the s tatus register. These
error bits are reset by setting ER bit in the command instruction.

10.4.6 Data Communication Types


We know that, 8251 A is Universal Synchronous, Asynchronous, Receiver, and
Transmitter. Therefore commun.ication can. take place with four different ways.
1. Asyrw;hronous transmission
2. Asynchronous reception
3. Synchronous transmission.
4. Synchronous reception
These communication modes can be enabled by writing proper mode and comnumd
instructions. The mode instn tction defines the baud rate (in case of asynchronous mode),
character length, number of s top bil(s) and parity type. Alter writing proper mode
instruction it is necessary to write appropriate command ins truction depending on the
communication type.
Asynchronous Transmission

Transmission can be C"nabled by setting transmission enable bit (bit 0) ln the command
instruction. When transmitter is enabled and ffi = 0 the transmitter is ready to transfer
data on TxD Hne.
Operation : When transmitter is ready to transfer data on TxD line, CPU sends data
character and it L~ Jo:1ded in the transmit buffer register. The 8251A then automatically
adds a start bit (low level) foUowed by the data bits (least significant bit first), and the
programmed number of STOP bil(s) to each character. It also adds parity information prior
to STOP bil(s), as defined by the mode instruction. The character is then transmitted os a
serial data stream on the TxO ou~ at the falling edge of TxC. The rate of transmission is
equal to I, }{6 or y64 that of the Tl<C, as defined by the mode instruction. Fig. \0.9 shows
the transmitter output in the asynchronous mode.

Copyrighted material
Mlcroprocenors and lnterfadng 10 - 13 Serial Communication

"
TxO Matklng Slart
Oata bits Parily s
bil bl< bll(
((

Fig. 10.9 Transmitter output In asynchonous mode


Asynchronous Reception
Reception can be enabled by setting receive enable bit (bit 2) in the command
instruction..
Operation :
The RxD Line is normally high. 8251A looks for a low level on the RxD Line. When it
receives the low level, it assumes that it is a START bit and enables an internal counter. At
a count equivalent to one~half of n bit time, the RxD line is sampled again . lf the line is
still low, a valid START bit is detected and the 8251A proceeds to assemble the character.
After succesful reception of a START bi( the 8251 A receives data, parity, and STOP bits
and then transfers the data on the receiver input register. The data is then transferred into
the receiver buffer register. Fig. 10.10 shows the roo.--iver input in thC asynchronous mode.

RxO

Fig. 10.10 Receiver Input In asynchronous mode

Sync:hronous Transmission
Ttansmlc;sion can be enabled by setting tran.o;mission enable bit (bit 0) in the command
instruction. When transmitter is en.."lbled and crs = 0, the transmitter is ready to transft-r
data on TxD line.

Open~tion : When transmitter is ready to transfer data on TxD line, 8251A transfers
characters serially out on the TxD line a t the falling edge of the TxC. The first character
usually is the SYNC d1aracter.
Once transmis.'tion has startect the data stream at the TxD output mlL">l continue ~t the
TXC rate. II Cl'U does not provide 8251A with a da"' character before transmitter buffers
become empty, the SYNC characters will be automatically inserted in the TxD da"' stream,
as shown in the Fig. 10.11. In this case, the TxEMP'IY p in is raiS<.od high to indicate CPU
that transmilter buffers are empty. The TxE.MPTY pin is internally reset w he:n CPU writ<.>S
data character in the transmitter buffer.

TxEMPTY ------'~ \ \ \ \ \ \\

Fig. 10.11 lnoer1lon of SYNC characters

Copyrighted ma!;:rial
Microprocessors and Interfacing 10 -14 Serial Communication

Synchronous Reception : Rcccption can be enabled by setting receive enable bit (bit 2) in
the command instruction.
Operation : In this mode chMiKier synchronization can be achieved internally or
externa lly.
Internal SYNC To detect the SYNC character 8251A should be programmed in the 'Enter
H UNT mode by setting bit 7 in the commrmd insturction. Once 8251A enters in the ' Enter
HUNT' mode it s tarts snmp ling data on the RxD pin on the rising edge of the RxC. The
con ~ent of the receiver btlffer is compared at every bit boundary with the first SYNC
char:<cter until a ma tch occurS. If the 8251A has bet..:.n programmed for two SYNC
characters, the :mbsequent SYNC characters are compared until the match occurs. Once
8251 A det.;.'CIS SYNC character(s) it enters from 'HUNT' mode to character synchroniz,-, tion
mode, and s tarts receiving the data characters on the rising edge of the next RxC. To
indicate that the synchr<mi~a tion is achieved 8251 A sets the SYNDET pin high. It is reset
<lUtomatically when CPU reads the s tatus register.
External SYNC
In the extem<1l S.YNC mode, synchronization is achieved by applying a high level on
the SYNDET pin, thlL< forcing the 8251A out of the HUNT mode.

10.4.7 Interfacing 8251A to 8086 in 110 Mapped 1/0 Mode


fi!L.!0.12 shows the interlacing of 8251A with 8086 in l/ 0 mapped l/0 technique.
Here, RD and WR signals are activated when M/10 signal is low, indic-ating 1/ 0 bus
cycle. Only lower data bus (0 0 0 1) i:; used as 8251A is 8bit device. R'"set out signal from
d ock generator L~ connected to the rt$et signal of the 8251A.

0
DoO,
o, TO
Reset oot Reset FbO
Clock out CtK
MilO
Ro ::> RO
Ao 8251A
ViR
WR

-
FbC From...,.
A, cii5 generator 01
- TxC
cs

CTs GNO

T I

Fig. 10.12 Interfacing of 8251A with 8086 in 1/0 mapped 1/0

Copyrighted material
Microprocessors and Interfacing 10- 15 Serial Communication

110 Map :

Register Address lines Address

A, A, A A, A2 A, Ao
Data Register 0 ""
0 0 0 0 0 0 0 OOH

Control Register 0 0 0 0 0 0 1 0 02H

10.4.8 Interfacing 8251A to 8086 In Memory Mapped 110


In this type of 1/0 interfacing, the 8086 u~ 20 address lines to identify an 1/0
device; an l/0 device is connected as if it is a memory register. The 8086 uses same
control signals and instructions to acxess 1/ 0 as those of memory. Fig. 10.13 shows the
interfacing o( 8251A with 8086 in memory mapped l/ 0 technique. Here, RD and WR
signals are activated when M/i5 signal is high, indicating memory bus cycle. Address line
A 1 is used to select either data register or control register. The remaining address lines
A.,-A 19 are \lsOO to decoder the addresses fo r 82SIA.

.
Do-07
rxo
RxO
Reset out Reset
Ck>ck out CLK

Ml iO ...
VRO Ro
Ao ......, 8251A
WR
WR
RiC From pulse
'; A, Clii generator or
TxC timet

cs

..
~
CiS GNO

l I
- c.
Fig. 10.13 Interfacing of 8251A with 8086 In memory mapped 1/0

Copyrighted material
Microprocessors and Interfacing 10 16 Serial Communication
110 Map :

Regis.1et ..... A,. A,, A,. A,, ..... Au A,. Au ... .. ... ... ... ...
A, .... A, .... A, Ao Addrus
Oala 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 OOOOOH
Register

COntrol 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 00002H
Rogisler

10.4.9 Programming Examples


To implement sctial communication the CPU must infornl the 8251 A a11 detail~ such as
mode, baud rate (in case of asynchronous mode), stop bits, parity etc. Therefore$ prior to
data transfer, a set of control words must be loaded into the mode ins truction and control
instruction registers of 8251 A.
Example 1 : Write the sequence of instructions required to initialize 8251A at address
SOH and 81 H for the configuration given lx!low
i) Choracter length 6 bit> v) DTR and RTS asserted
ii) Pnrity even v i) Error flag r~t
iii) St<>p bit 1 vii) Transmitter enable
iv) Saud rate 64 X
Sot : In the example, number of stop bits and baud rate is s pcc:itlOO, therefore, it is
r\t...-.cessary to Initialize 8251 A in the asychronous mode.
Mode word for given specification ~s 3$ foUows.

0111 1 0111 1o77H

'---v---' '---v---' '---v---' '---v---'


1 Sk!p bit Even Prity C'--cter lrtflll'h ASYN 8at.d rale
6blls 6AX

Fig. 10.14
Command word for given specification is as follows.

I I I I J
..,....
No~ . . .
_ II
I
I I
I
llH

'-
iffii- 0
.,.._
,.,._
RTSo
....... ...._
Fig. 10.15

Copyrighted material
Mlcroproceoooro and lnterfoclng 10 17 Serial Communication

Program :
t<!OV IlL, OOH
OUT 81H , IlL
OUT 81H , AL
OUT 81H, AL Dummy mode "'ord
MOV AL, 40H Reset command word
OUT 81H, AL ; Reset 82$1A
MVI AL, 71H ; Mode word incilization
OUT 8 1A, AL
MOV AL, JJH : Command vord initialization
OUT 81H, AL
Note : Before initialization of the 82SIA. the dummy mode word and the reset
command are sent to the control register. lnihally control n.~tcr m.y have any random
word; therefore. it is a good pl'liCtlc< to~ the 82SIA. However, it eocp1s lhe instruction
as a mode word followed by lhe command word. Therefore, lhe """'t command is sont
afler sending three dummy mode word. which are recommended lo avoid problems
when it is turned on.

10.5 Serial Communication Protocol (RS232C)


In response to lhe nrt'<l for slgnls and h.ondshab standards belw<""' DTE and OCE,
lhe Electronic lndustri"" A.<SOciotion (EIA) introduced EIA sl.lndard ~232 in 1962. II was
re-.'ised and named as RS-232C, in 1969 by EIA. II is widely aq>ted lor single ended data
transmission over short di.stano..--s with low datn rntes.
This standard deiCri~ the function.<~~ of 25 sit;M I and handshake pins for serial data
transfer. It also describes the voltage levels, im~dance levels, rise and (aU times,
maximum bit r(lte, and maximum ca~dmncc for thcst sigr'ldl lines. R$.232C specifics 25
signal pins and it ~pccifi~ that the DTE oonm.'Ctor should be male, and the OCE ooM.ector
should be a female. The most commonly li.Sf..'Cl roru1ector ~hould be a female. The most
commonly used connector, 0 13-lSP i~ shown In the Fig. 10. 16.
Slgl\llt .... SISJnela

PtotoetiY ground
'
SecondWy Trentmllt< <lfll.f
" 2 Tren1mlfttcl <IRa (T X 0) - 00E
Tti11111T115Sion 1lgnN t41mtnllltning (OCE ~~
Secondlry ,~ Clal.f ,,
1$ ) Rt041Md dltt (R X D)
Rtqunt to Mnd (Itt$)
OlE
OCE
R~ aiOnal element timing (DCE aource)

u~-
"

$ QNr to lend (CTS)
Oat , ,..dy (D~)
OlE
OlE

- -
s.cono.ry fi!QUtlt to Mncl 18 7 Slgf\11 GrOUnd
OCE -o.ta lerminll I'Ndy {OTR) 20 6 R.cllved IN~ deteaof
59'wl Qu*y <*ICIOf 21
... ...
T----(OTE-)
(-
Rlne-
Deta .gnM ma 1e11ctor (DTE.OCE ICIUI"Oe)
22
n
10
...._,..
(~lot dMIIel testing)

24 "
12 Sec. ~'ed IN t9- dHec:Jof
"""'- H I) S.C. . .to Mnd

Fig . 10.16 RS 232C 25 pin conntc1or


M icroprocessor'-
.. and Interfacing 10 -18 Serial Communication

Pin CommoJ~ RS-232C Oeur lptlon Signal


Number Name Name Direction
On DEC
1 A4 ProtecliWl' ground

2 TXD BA Transmitted data IN

3 RXO BB ReceiVed data OUT


4 RTS CA Requesl to send IN

5 CTS CB Ctear to send Olff


-~

6 DSR ' cc Data set ready Olff



7 GND AB Slg.nat ground (oommon return) I

8 CD CF Reoefved line signal detector Ol/T


9 (Reserved for data &et tosting)

10 (Reserved tor data set testing)

11 .. unsigned

12 j SCF Secondary reed. line sig. detector Olff


13 SCB Secondary c!ea.r to send Olff
14 SBA Secondary ltansmltted da1a IN

15 DB Transmission signal ek!ment timing OUT


(DCE source)
16 SBB Secondary received data Ol/T
17 DD Receiver signal e1emen1 timing Ol/T
(DCE SO<ffce)
18 Unassigned

19 SCA Secondary re~uesl to send IN


20 DTR co Data terminal ready IN
21 CG Signal quality doteelor Ol/T
22 CE Ring tndicatOt Ol/T
23 CHICI Data ~lgr.at rotc sotector {OTEIOCE IN/OUT
source)

24 OA Transmit sigl\31 element tlmlng (OTE IN


source)
25 Unassigned

Table 10.2

Copyrighted material
Microprocessors and Interfacing 10-19 serial Communication

11\C Table 10.2 s hows pins and s ignals de&ription for RS-232C fo~ datn l ine~, The
voltage level + 3V to + 15V ls defined as logic 0; from -3 V to - 15 V is de:fiN!d as logic 1.
The control and timing s ignals are compatible with the TfL level. BecmtSe of the
incompatibility of the data lines with the TTL logic, voltage ITans la ton;, called line d rivers
and line receivers, art' n:."quired to interface lTL logic with the 1~232 s ignals. Fig. 10. 17
shows the inter facing behveen TTL and RS-232 s ignals. 1ne line driver, MC1488, converts
logic 1 into approxilnatel)r 9 V. TI\CSe levels a t the receiving end :\Te aAain oorwertcd by
the line receiver, MC1489, into TIL-.compatible logic.
RS 232C
cable

! '"2"' Receive
(""1
MC 1483 MC t~9
"\_TIL
Ot~la
t~at
TIL '- 2 Oa1a
Comm~lcatlon
/ /
equipment + 3.4 v -- 9v -9V-+3.4V e quipment
0.2V -+9V +9V - 0.2V -
J 3 3 J . -
\. Transmil\.
MC t ~9 MC 1488
OTE oG:e
GNO GNO
7 7

'-' '-'
Fig. 10.17 Line drivers and receivers

10.6 Sample Programs of Serial Data Transfer


Jn this section, we are going to s~ thr<.oe progrnms which transfer data ~ riaHy through
the COM port of one PC to another PC.

10.6.1 Program to Transmit One Character


CODE SEGNENT
A.SSUt"'E CODE, OS ' COOE
CS :
ORG OIOOH
START ' HOV AH, OOH ; Initialize serial port COf12 '"'ith
I<OV AL,03H 8-data b its , 1 stop b:it , par ity
MOV OX,OlH ; none and baud raee 110 bps .
!NT 14H
MOV AH, 08H ; Read character from keyboard
! NT 21H

HOV Ali, Ol H ; Transmit character in AL to


MOV DX, Ol H ; COM2 ~erial port
!NT :4H
MOV AH, 4CH ; Terminate program and
!NT 21H ; retut'n to DOS
CODE ENOS
END START

Copyrighted material
Hidden page
Microprocessors and Interfacing 10.21 Serial Communication
--
MOV AL, 02
fr.10V BX, FILE HANDLE
the end ana

end address to get


use
r1ov ex, o - the tile size
MOV OX , 0
INT 21H
MOV S!Z, AX

MOV All, 42H SET fil<> POINTER AT


MOV AL, 00 STARTING POSITION
MOV BX,F!LE HANDLE
MOV CX, 0 -
MOV OX, 0
INT 21H

BACK MOV AH, 3FH ; Rend file one chacactcr


MOV BX, FILE HANDLE at a time
MOV ex, 1 -
MOV OX, OFFSET BUFF
!NT 21H
MOV $ 1 , OFFSET BUFF

MOV AH, OOH ; Initialize COM 1


MOV l\L, OJH
MOV OX , 0
!NT 14H

MOV l\H , OlH ; Transmit character r ead


MOV AL, [S!J ; from file to COMl
MOV OX, 0 ; Display the same
!NT 14H ; Character on the monitor
MOV AH , 02H
MOV DL, [SIJ

INT 2 1 H
.,: -,
DEC WORD P'I'R S I Z ; Decrement size poir.ter
CMP SlZ , 0 ; Check if end of f ile
JNZ BACK
MOV AH, 4CH ; Terminate pro9ram and
INT 21 H ; ret\lrn to DOS
CODE ENDS
END START

Program to Receive file


CODE SEGMENT
ASSU~IE CS : CODE, OS : CODE
DRG OlOOH
START : MOV AH , OO INITIALIZE COMl PORT
fr.tOV l\L, 03
MOV ox, oo
INT 14H
AGAIN MOV AH , 03 ; Read status of COMl
MOV DX, OO
INT 14H

Copyrighted material
Microprocessors and Interfacing 10 - 22 Serial Communication

AND AH, 01 Chec~ COMl, i f it is ready


; to r ece ive
CMP AH, Ol data
JNE AG.; !N i f not chec k status again

NEXT MOV AH , 02 Rece 1 ve data f r om ser ial


to!OV ox, oo Port COM I
INT l4H

CMP AL, lAH Check for e nd o f


J STOP file charactec if yes stop
HOV OL, AL Display the r eceived
NOV AH , 02 character
!NT 21H
NEX'i
J r-!P : Goto receive ne xt cha racter

STOP MQV AH , 4CH ; TER!<!I NATI ON

COD ENOS
!NT 21 H .
END START

10.7 Introduction to High-Speed Serial Communication Standards, USB


The Universal Serial Bus (USB) was bom out of the frustration of PC users experience
trying to connect an incredibly wide range of peripherals to their computers. This was not
possible with the exis ting centronks parallel interface and the RS-232 serial port interface.
These inter faces could not hand le increasing computer power and the number of
peripherals. They have becflme bottle-neck of slow communication. with limited options
for expan:-ion. This is the s ituation that prompted the development of USB. The result is
versntil~ interface that ca1' replace existing interfaces to tow to moderat.:! spet.:.d standard
and custom peripheral types on computers of all types. USB gives fa.st and flexible
interface for connecting all kinds of peripherals.
USB is playing a key role in fast growing consumer areas like digital imaging, PC
telephony. and multimedia games, etc. The presence of USB in most new PCs and its
plugn-play capab!lity, moans tha t I'Cs and peripherals (s uch as CD ROM drives, tape and
floppy drives, scanners, printers, video devices, digital cameras, digital speakers,
telephones, modemsf key boards, mice$ digital joysticks and others) will automatically
configure and work together. with high degr~ of reliability. in this exciting new
application areas. USB opens the door to new levels of innovation and its usc for input
I
devices. There are also brand new opportunities of all types of peripherals from printers to
scanners to high speed connection su ch as Ethernet OSL, cable and satellite
Cllmmunications.

Copyrighted materia!
Microprocessors and Interfaci ng 10.25 Serial Communication

reduce power consumption, this feature is especially useful on battery powered computers
where every milliampere counts.
12. Flexiblli1y
usos four transfer types and two speed (3 with version 2.0) make it feasible for many
types of peripherals. The.re arc tr-.11\Sfcr types suited for exchanging large and small blocks
of data, with and without time constraints. For data that cannot tolerate delays. USB can
guarantee a tran~fer rate or maximum ti.me between transfers .
.... .J ike otl-.cr interfaces, the USB does not assign specific functions to signals or make
other assumptions about how the interface wiU be use. For example, the status and control
linl'S on the PC's parallel port were defined with the intention o f communicating with line
priJ\t('rs,
For c.:ommunicating with common device types such as printers and mode.ITl.S, USB
s upports dasscs with defined devi~ requiremc:nts and protocols. This saves developers
from having to reinvent these for each peripheral.
13. Operating system support
Windows 98 was the fi rs t Windows operating system to reHably support USB? and its
successors such as Windows 2(XX') support USB as well. Other computers : nd operating
systems also have USB support. ON apples iMac, the only peripherals conn<ctors are USB.
Other Madntoshes also supp(lrt USB, and s upport is in progress fo r Linux, NetBSD, and
FrceBSO.
14. Peripheral support
O n the pcriphcrnl s ide, each USB dcvi<..'e's hardware mus t include a controller chip that
ho1ndJes the details of USB communkations. Some controiJers are complete m.icrocomputcrs
lhal include a CPU and memory thai stores the code that runs inside the peripheral.
Others handle only USB-specific tasks, with a data bus that connects to another
mk rocontrollcr thnt perfo rm~ non USB related functions and communicates with the USB
controller as needed.
ThC! peripheral is responsible for ret>pond ing to requests to send and receive
configuration data, and for reading and writing ot~r data when requested. In some chjps,
some of the functions are microcoded in ha rdwa re and don't need to be programmed.
Mnny USB controllers arc bo.s<.-d on popular architectures .!Ouch as Intel's 8051, with
added circuits and machine codes to support USB.
Most peripheral manufuctun."S provide sample code for their chips.

10.7.2 Limitation of USB


All of USB's advantages mean that it's a good candidate for use with many
peripher<als. But one interface can't do it al l.
From the t.Lscr's perceptive, the downside to USB includes lack of support on order
hardware and operating systCJl'IS, speed and distance Limits that make USB impractical for

Copyrighted material
Microprocesors and Interfacing 10-27 Serial Communication

The controller
just about any new PC will have a USB controller and at least tw':l port col'mcctors. l(
a computer doesn't have a USB controller built into its motherboard, you co.n add one on
an expansion card tha t plugs into a s lot on the PCI bus.
The operating system
The other side of USB support is in the op-erating system. Windows 95 had some USB
support, but the support was greatJy improved and enh..1nced in Windows 98. WindO\\"S 95
and Windows 98 (;an't use the same devite drivers. Windows NT 4 dc~n' t s upport USB.
How('\tct, if you're deve:lopil\g a peripheral that needs to run under NT. there arc third
party products that you can use to create a device driver that enables the peripheral to be
used under NT. DOS and Windows 3.x also have no USB support, though again, third
party products may be available.
The components
The physical component~ of the Universal Serial Bus consist of the circuits. connectors.
and cables between a host and one or more devices.
The host is a PC or other computer that contains two components; a host controller
and a root hub. Th~e work together to enable the operating system to communicate with
the dcviCl'S on the bus. The host controller forma ts datn for transmitting on the bus and
translates received dal.c1 to a fo rmat th.itt operating system components can understand. The
host controller also perfonns other functions related to ma.naglng communications on the
bus. The root hub has one or more connectors for attuching devices. The root hub detects
the attachment and removal of devices, carries out requests from the host controUcr. and
passes data between devices and the host controller.
The dev~res arc the pc.riphernls and additional hubs that connect to the btL<:o. A hub has
one or more por1s for connecting devices. Each device must contain circuits and rode that
know how to oommunicate with the host.

10.7.4 USB "tiered star" Topology


As shown in Fig. 10.18 at the center of each ~ta r is a hub. Each point on a s tar is a
device that connect to one of the hub's ports. The devices may be additional hubs or otJwr
peripherals . The number of points on each star can vary~ with a typical hub hon-ing two,
four. or seven ports. When there are multiple hub in series you c..1n think of then\ as
connecting in a tier, or series, one above the next. (Refer Fig. on next page.).
All of the devices on a bus share one data path to the host computer. Only one device
can communicate with the host at a time. If you need more bandwidth , you can add a
second data path to the host by instaJiing an expansion card with another host controller
and root hub.
fig. 10.19 s hows a few of the possible configurations for a PC with n root hub that hM
to USB connectors.

Copyrighted material
Microprocessors and Interfacing 10-28 Serial Communication

Peripheral Peripheral

Peripheral

Periph~traJ Peripheral

Peripheral Peripheral

Peripheral Peripheral

Fig. 10.18 USB tired star topology

oq ~

Peripheral
Peripheral
\
0
Host PC Host PC Peripheral

Host PC with 2 peripherat:s Peripheral + 1-por'l HUB

Peripheral
Hosl PC with 6 peripherats
Fig. 10.19 Different configurations for connecting USB devices to a host PC

10.7.5 Terminology used in USB


Hos t
The host is a PC or other computer that contains two components : a host controUe.r
and a root hub.

Copyrighted material
Microprocessors and Interfacing 10.32 Serial Communication

connect to the bus detect the absence of bus activity for three miUi seconds,. they must
enter the suspend stntc and limit the current they dmw from the bus .
5. Exchange data with the host
Aftl'r the device is configured, it must respond to request to send and receive data.
The hos t may pole device at regular intervals or only when an application requests It)
comm unica t~ with it. TI\e device must respm\d to each poiJ by sending an
acknowledgment (ACK) thnt indicates that it receiver! the data, or a negative
acknO~'I:k>dg:men t (NAK) to ind icate that it is busy to handle the dali.'l.

10.7.8 USB Communication


USB communication is divided into h'IO types.. depending on whether they're used in
initial ronfig1.uation or in applications. In configuration communications.. the host learns
about the device and prepares h for e.xch.1nging data. Most of these communications take
place when the host en umerah..-'S the device on power up or attachment. Application
communications occ:ur when applications oJ'l the host exchange data with an ~numerated
devic~. These are the communications that carry out the device's purpose. For e.xampJe,. for
a keybo.ucl the application communic.-1tions are the sending of keypress data to the host.
to tell <'l.n <"~pplicatim\ to dis.play a charac-ter or perform othe.r action...;.
1. Configuration communications
During enumeration, the device's finnware responds to a series of standard requests
from the host. The device mlL'~l identify each ra1uesl, return the n'quesh.>d information,
and take other actions sp('('ificd by the requests.
On l~s. Windows pcrfonns the CJ\umeration, so there's 1\0 user programming
involved. However, to complete the enumeration, Windows must have two files available
an INF file that identifies the filename and loc-ation of the device's driver, and the device
driver itself.
2. Application communications
After the host has exchanged enumeration information with the device and a device
driver has been assigned and loaded, the application phase can be fairJy s traightforward.
At the host, applications can use s tandard Windows API functions to read a nd write to the
device. At the device~ transferring data typically requires placing data to send in the USB
controller's transmit buffer,. reading received data from the receive buffer when a hardware
interrupt signals that data has arrived, a 1\d on completing a transfer~ e.nsuring the device is
ready for the next transfer. Most devices also require some additional support for handling
errors and other events.

10.7.9 Elements of Transfer


1. Device endpoints
AU ttan.smi!'sions travel to or from a device endpoint. The endpoint is a buffer that
stores multiple bytes. Typically it's a block of data memory or a regis ter in the controller

Copyrighted material
Microprocessors ~n~ Interfacing 10 -3-4 S.rlal Communication

10.7.10 Data Transfer Types


1 ., ,,.. '
Th~
USB is designed to handl(' many types of peripherals with varying requirements
for transfer ra te, R'l"ronse time, <lnd error correcting. Th~re are four typl.~ of data transfers
each hond lc different needs~ and ,\ peripheral can support the transfer types that are best
suited for its purpose.

.....
1. Control transfer
Control transfer~ a re the only type with functions defined by the USB specification.
These tTiln~fer~ em1~~c the h~t to read and select configurations and other settings on the
devices being cnul'l\cr<ltcd. Control t ransfc~ may also send custom requests that send and
re<"eive blocks of dil til fo r any purpose. All USB devices must support contml transfers.
Ti'lis data t~r;!'(cr
' t, ,,
exchanges configuration, setup, and command information between
tht> device and host, CRC~ check the data and initiate retrafl..'tmissions when needed to

guarantee the correctneN uf these packets.
I .
Control Trans fers Use Message Pipe':'. In a message pipe, each transfer begins with a
Sch.Lp tran......,ction containing a request. To complete the transfer, the ho:->1 and device may
exch;mge data An<Jl~"~t~lu$ il'tformatior'l, or the devi<..~ may just St."'t"'d s tatus infonnation.
Th('re is alw<.\fs M leaSt one trar\So.'lCtion thnt sends information in cnch direction.
' ..,: . '
If th<. n ..>qy;.:;t JJ. qne that the device supports, it takes the requested action. A d evi~
may also respond with n code th.lt indicatl.'S that it doesn't support the rt.oquest.
2. Bulk transf'r _
Bulk trans.fers .,~ intended for s ituations where the rate of transfer is n't critical~ such
as send ing a file nr a printer or receiving data from a scanner. In these cases quick
IMnsfl!rS are nice, but the data can wait if necessary. If the bus is very busy with other
lransfl!rS that have guaranteed lran$fer rate$, bulk transfers must wait, bt.rt if the bus is
idle, bulk transfe~ ~rc very fast . Only fullspa~ devices can do bulk transfers. Devices
aren't required to support bulk transfers, but a specific device class might require it.
11liS datn tra.n:dcr moves large nmounts of data when timely delivery is not critical
Typical applications indude printers and scanners. Bulk transfers rare fiBers; claiming
unu.sc USB b~:~.ndw i dth when nothing more important is going on. CRCs protect these
packets.
3. Interrupt transfer

lnternlpt ITtmsfers arc for devices that must receive the host's or device's nttention
qukkJy. Other thiin co'nlrol transfers, interrupt transfers are the only way that low speed
devices can transfer- data. A keyboard or mouse can use interrupt transfers to send
keypress or mouse Jl!OVement dat-a. Both full and low speed devices can do interrupt
transfers. Devices aren't required to support interrupt transfers, but a specific device class
might require it.IL"'s ..,.
This data transfcr~r though nl>t interrupt in the CPU d iverting sense, poll devices to
see if they m..-ed service. Peripherals exchanging s mall amounts of data that need

Copyrighted material
Microprocessors and Interfaci ng 10.37 Serial Communication

susJX!"fld state, error checking information, and other information about how the chip will
be used and the current status of transmitted or received data. "'
, .,.. r-.r
5. USB port
A USB peripheral controller must of course have USB port and supporting circuits.
6. USB buffers
A USB controller must have transmit and receive buffers for storil)g 1,1SB data.

Review Questions
7. Comp.1re parnlld rmd Sf'Yial ty~
of tlattr trnnsfer.
2. Classify nnd expl1dn Sfrinl communicolion systems. ttl

3. E.xplgin dat~o~ nmummicntio11 formttts irr seri.:ll conummiattion. ."


4. Diff~rrntiate betumr Sy,duonous r.ud Asynchrono1l$ dntn transftr.
5. Lisllh< '"''""'of
825JA.
6. Ojsc1d$ llu org.1nizntion nnd "rcltithtrr uf 82SJA (liSART) with Q fimttf!t!Jnl blk diagram .
7. Draw and aplabr command and mode word formAts of 82SJA.
8. Draw tmd rxplain tJw status word .format of 82S JA.
9. With a nMI diagram, explain how 8251 i$ i_n tufnwl tuith 8086 11nd usaf for StriDI communicDticn.
10. Writ~ a shorl not~ on RS232C prototol.
11. Exptni11 the fenhtrr.s of USB.
12. Give> tl1e dttnits of USB cotmn:tor will/ tiN' htlp of dfagmm.
13. How USB dsfto is grnemted ? Explain tlk' t'tu:oding mt'lhod u~ by thi USB.
14. Wlu11 is bit SlU/fi1'8 ?
15. Dmtv til~ flow clmrt ~xp/nini11g til~ prot;r!SS of grnn-ating USB d11t11 from. tilt raw digitnl stritrl
data.
16. Write a $/J()rl nott on USB commiJnds.
17. Wlurt do you lltc'iltl by slop lind u!'(fit fltm' rot~trol ?
'.
... '
DOD
' .

.. : ''

Copyrighted material
8051 Microcontroller

11.1 Introduction
To makt a complete m icrocomputer sys-tem, only microprocessor is not :n1ffident. Jt is
nt.-'Ces..c;cuy to add o ther peripherab su ch as rei'td o n ly memory (ROM). read/write m(>mo ry
(RAM), dC!COders, drivers, number of input/output devices to make n complete
microcomputer system. In addition, special purpooc devices, such as intcJ'rupt controller,
programmable timers, program.mable 1/0 de\'ic.es, DMA controllers may be added to
improve the capability and performance and ncxibility of a microcomputer sy~ tcm .
The key fcahuc of micropr<X'CSsor based computer system is that it is possible to
dt'!'Sign a system with a great flexibility. lt is possible to oonfigure a system as Large sy:::tcm
or small system by adding suitable pe.riphe.rnls.
On the othN hartd, the mkrocontn)llcr incorpor.-.tcs a ll the featun.'!'l tha t M(' found in
microprocessor. However, it has a lso add4..--d fe~l tures to make a compl~te 1nicrocomputer
system un it'S uwn. The mkrt'>eOniTOllt!r ha ~ built-in ROM, RAM, parallel l/ 0. ~erial l/ 0,
COlu\t'c rs alld a dock circuit.
The microcontro11er hns on<hip (bui l t~ in) peripheral devices. The~
o n < hiy peripherals
make it possible to have sing.le-chip microcomputer system . There are (ew more
advantages o f built-in pe-ripherals : I
BuiltiJ\ peripherals have s maller acet.--ss times he:r'lce speed is more.
Hardware n..:.duces due to s ingle chip microcomputer system.
Less h..'lrdware. reduces PCB s ize and increases reliability of the system.

(1 1 1)

Copyrighted material
Microprocessors and Interfacing 11 -2 8051 Microcontrolle<

Comparisoo between Microprocessor and Microcontroller


We have dicuS-.'it.~ whttt is a microprocessor and a m icrocontroller. Let us see the
points of differencos between them.

No. Microprocessor Microcontroller


'
1. Microprocessor conta~s Al.U, 001\1101 unit Mlcrocontrotler contains microprocesscw.
(elodc and dmlng circuit). ctlfferent register and memory (ROM a nd RAM). 1/0 interfacing
intetrupt circuit. c*euit and peripheral devices SUCh as NO
converter, serial I/O, timer etc.
2. It has many instructions to move data between It has one or two lnstrvctlOf'ls to move data
memory ilnd CPU. b etween memory and CPU.

3. ll nas one or two bit handling instructions. It has many bit handling instrucOOns.
4. Access times for memory and 1/0 devices are Less aCC8:S$ times for buift.in memory and 110
more. devices.
5. Microprocessor b35ed system requires more Miorocontroller based syotem requires less
hardware. hardware reduci'lg PCB size and increasing
tne rellablltty.
6. Microprooessor based system is more flexible l ess nexille in design point of view.
in design point of view.
7. It has single memory map for data and code. It has separate memory map for data and
COde.
8. Less numbet of pins are multifunclioned. t.1ore number pins are multifunctiooed.

The 805 1 is i'ln 8~bit microcontroller designed by Intel It was optimized for S~bit math
and single bit l3oolean operations. Its family-MCS-51 include5 8031, 8051 and 8751
microcontrollers. The Table 11.1 gives the summary of MCS.Sl micnxontrollers.

N Internal Memory Timer I


Dovlce . Program Dahl Event Counters Interrupts

8052AH 8K x 8 ROM 256 8 RAM 3 x 16-Bit 6

8051AH 4K x 8 ROM 128 x 8 RAM 2 X 16-Bit 5

8051 4K x 8 ROM 128 x8 RAM 2 X 1S.Bit 5

8032AH none 256 x 8 RAM 2 )I 1S.Bit 8

8031AH nona 128 x 8 RAM 2 )I; 1S.Bit 5

8031 none 128 x8 RAM 2 X 16-Bit 5

8751H 4 K )I 8 EPROM 128 x 8 RAM 2 X 1S.Bit 5

87Sttf.12 4. K x 8 EPROM 128 x 8 RAM 2 X 10.8i'l 5


Table 11.1 MCS-51 family

Copynghted matenal
Microprocessors and Interfacing 11 - 3 8051 Microcontrolle r

In this chapter we are going to sec features nnd the int'e nla) hardware details
(architechue) of 8051 microcontroller.

11.2 Features of 8051


The features of the 8051 family are as follows :
1) 4096 bytes on - chip program memory.
2) 128 bytes on chip data memory.
3) Four register banks.
4) 128 User-~efined softwa re flags.
5) 64 Kilobytes each program and external RAM addressability.
6) One microsecond instruction cycle with 12 MHz crystal.
7) 32 bid irection.1li/O lines organiwd as four 8-bit ports (16 lines on 8031).
8) Multiple mooe, high-speed programmable serial port.
9) Two multiple mode, 16-bit Timers/Counters.
10) Two--level prioritized interrupt structure.
11) Fun depth stack for subroutine return linkage and data storage.
12) Direct Byte and Bit addressability.
13) Binary or Decimal arithmetic.
14) SignOO-overflow detection and parity computation.
15) Hardware Multiple and Divide in 4 .,asec.
16) Intebl'fl'lted Boolean Processor for rontro! applications.
17) Upwardly compatible with exis ting 8084 software.

11.3 8051 Mlcrocontroller Hardware


The Fig. 11 .1 shows tht! intern..'\.1 block d ingram of 8051. It consi.,ts of a CPU, two kinds
of memory sections (dota memory - RAM and program .nemory EPROM/ ROM),
input/ output ports, special function registers and control logic needed for a variety of
peripheral functions. These elements communicate through an eight bit data bus which
nms throughout the chip referred as internal data bus. This bus is buffered to the outside
world through an 1/ 0 port when memory or 1/ 0 expansion is desired.

Copyrighted material
3:
;;
a
r-------------

-- ----------------
'--------- - -: Port~
D .
------------------------------------;
]
J~.II
laiOIIo
A
Register I Slack I: - "'" n~- r =
0
POinter
Program
1
f

'
Bullur 0

,
:

:
..
Ol
~
c.
Temp Temp eot11ter
': :

....
.o
~
~
Register Reg.ttcr

-I
I DPTR H-~
PC
lnc:rementer
: I-
'
LatCh 1

Blflter i
:

;;

~
~
!!.
.,"
~

'
Ill

,..g

'------
_________ ___:' Buitftt' 2 ~ ~

.l
I
..
~
c. ' ~
;;;
~r- RAM P'rogra111 t-- latch 3 ' '
"';:3 Adc;lr(:fl!i
Register
Address
Regisoeo 1-- Buffr 3 ,
r"

-. .
!l. -................. -----------
. . ... _....,

.
...
0
~
PSE:N-!--1 11rni<Jg
-EA -+-I
ALE
. an<~ I I I RAM EPROI.V
16 bll add~S$

ROM
CO<IIIQI
: I
tnwntPt
...
c:
RST
''
'' I !'CON SOON I TMOO TCON
,...,., pen,
ilrne1 afiO
tuetnory road/ ..
0

-
~. ~

I OS<: I
hl11truc00n
1l40 Tl11 l l1 write <::onl.tot 3:
L- Regis:ler '!1.0
;;-
.-=r D.L :, '
g
~ ~I
~ S8lJf' IE IP
~
.~

i ' Special Function Rsglslers ------------------------' g


~--
' ------ - - - ----------------~ ------------
------------ [
'
{
"'
~
Microprocessors and Interfacing 11 6 8051 Microcontroller

Port 0 (Pins 32 39)


Port 0 pins can be used as l/0 pins. The ouput drives and input buffers of port 0 are
used to access exte.m al memory. Port 0 outputs the low order byte of the external memory
address. time multiplexed with the data being written or read. Thus, port 0 can be used <tS
a multiplexed address/ data bus.
Port 1 (Pins 1 8)
Port I pins can be used only as 1/ 0 pins.
Port 2 (Pins 21 28)
The output drives of port 2 t'lre used to access external memory. Port 2 outputs the
high order byte of the external memory address when the address is 16 bits wide.
OthenYise, port 2 is used as an l/0 port.

Port 3 (Pins 10 17)


All port pins of port 3 are multifunctional. They Mve specinl functions.
Po-rsupply pins Vee (Pin 40) and V55 (Pin 20)
8051 operates on d.c. power s upply o! +5 V with respect to ground. The +5 V is to be
connected to pins Vex and grotmd to pin Vex with rated power supply current o! 125 rnA.
Oscillator pins XTAL2 (Pin 18) and XTAL 1 (Pin 19)
For generating an internal clock s ignal. the external oscillator is connected a t these two
pins.
ALE (Address Latch Enable, Pin 30)
AD0 to AD7 lines nre multiplexed. To demultiplex these Jines and for obtaining lower
half of an address. an external latd' and ALE signal of 8051 is used.
RST (Reset, Pin 9)
Thi.s pin is used to reset 8051. For proper reset operation, reset signal must be held
high at least fo r two machine cycles, while oscillator is running.
PSEN (Program Store Enable, Pin 29)
It is the active low output control signal used to ac-tivate the enable signal of the
external ROM/EPROM. It is activated every six oscillator periods while reading the
external memory. Thus. this signal acts as the read strobe to exte.mal program memory.

EA (External Access, Pin 31 )


When the EA pin is high (connected to Vex), program !etches to addresses OOOOH
through OFFFH are directed to the internal ROM and program !etches to addresses IOOOH
through FFFFH are directed to cxtemal ROM/EPROM. When EA is low (gorunded), all
addres-"'8 (OOOOH to FFFFH) !etched by program are directed to the external
ROM/EPROM.

Copyrighted material
Microprocessors and lnlerfaclng 11 7 8051 Mlcrocontroller

11.3.2 Central Processing Unit (CPU)


The CPU of ilffil ronsisls of eightbit Arithmetic ami Logic unit with associated
registers Uke A, B. PSW, SP. the sixteen bit program rounl<!r and " Dilta poinlet" (DI'TR)
registers. Alongwith these rcgi>t= it has a set of spocial function rcgi>tus. Along with
these rq;istetS 11 has set of spocial function rq;isters.
The 8051' Al.U an perfonn arithmetic ami logk fwlction5 on eight bit variables. The
arithmetic unit con perform addition, subiTaclion, multiplication and division. The logk
unit can pcrfonn logical operatlons such as AND, OR. and Exdusiv~R., M well as rotate,
dear, ttnd complement. The ALU also looks aftt...>r the branching decisions. An important
and unique feature of the 8051 archit('(ture ls that the ALU c.m abo manlpuliUe one bit as
well as clghthlt dtltn typ<.'8. Individual bits may be set, dc.ucd, romplemenh..od, moved,
tL>stcd, and used in Jog:ic computation.

11.3.3 Internal RAM


The ilffil has 123-byte intern.,! RAM. It is access<.'<! using RAM oddr""" rc'giSier. The
fig. 11.3 shows the organls.,tlon of internal RAM. Aa shown in the Fig. 11.3, internal RAM
of ilffil is organlsc'<l Into three distinct areas :
Working .-.gist.,..
Bit Add..,....ble
~.1 Pu'J'O"<
I. first tlurty two bytes from oddress OOH to I FH of .ntemal RAM constitute
32 worl<ing registers. They re organised into four bonl:o of eight rq;isl<!rS each.
The four rogist<'l' bonks are numbered 0 to 3 and ore consists of eight rcgistors
nomed Ro to R,. Each rcgi.tcr can be addressed by name or by its RAM address.
On1y one n:.ogister b.\ok is in US<' at a time. Bit$ RSo nnd RS 1 In the I>SW dct~?nnine
which bl.lnk uf rc."Sistcrs is currcntJy in use. Rl>glstc.r bonks when not sclccttd can
be u~d as gt.nrrnl purpose RAM. On reset, tht: Bom k 0 i.J( ~ck-ctcd.
2. The 805 1 provides 16 bytes of a bitaddi'CSS!Ible area. It occupies RAM byte
addrc'SS<.'$ from 20H to 2FH, forming a tol<ll of 128 ( 16 8) oddr<,...,ble bits. An
addr""s.'blc bit may be specified by its bit addrc,.. of OOH to 7FH, or 8 bits may
fonn any byte address from 20H to 2FH. For example, bit address 4EH refers bit 6
of the byte add,.... 29H.
3. The RAM area above bit addressable area from JOH to 7FH b called gmeral
purpooe RAM. It i' add...,....ble as byte
See F1g. 11 .3 on ncM page.

11.3.4 lntemal ROM


The 8051 has 4 Kbyte of internal ROM with addless space from OOOOH to OffFH. It is
programmL'<i by nmufKturcr when the chip is built. This part Ct'Mc.lt be C"rased or altered
after fabric."ltlon. This h used to store final version of the program.

Gopynghted matenal
Microprocessors and Interfacing 11 - 8 8051 Mlcroeon1roll"

Byte
Addre-u Byte
Address , - - - - - - - ,
1F R, 7F
1E Ro
10 Rs
1C R,
Bank3
18 R,
1A R2
19 R,
18 Ro
17 R,
16 Ro
15 R,.
14 R,
Bank2
13 R,
12 R,
11 R, Byte
address Blt Addres'"
10 Ro
OF R, 2F 7F 78
OE Ro 2E 77 70
00 Rs 20 6F 68
oc R, 2C 67 60
Bank1
OB R, 28 SF 58
OA R2 2A 57 50
09 R, 29 4F 48
08 Ro 28 47 40
07 R, 27 3F 38
06 Ro 28 37 30
05 Ro 25 2F 28
04 R, 24 27 20
BankO
00 R, 23 1F 18
02 R, 22 17 10
01 R, 21 OF 08
00 Ro 20 07 00
30 L - -- ---J
Woo1dng Bit S it
Re-gister 7 5

Fig. 11.3 Organisation of Internal RAM of 8051

Copyrighted material
Microprocessors and Interfacing 11 9 8051 Mk:roconlroller

It is aca:.>Ssed u..o;:ing program addr~


register. The
program addresses higher than OFFFH, which exceed PC Program
Address
the intem<ll ROM capacity wi11 cause the 8051 to Registec-
OPTR
automatically fetch code bytes from external program
memory. However, rode bytes can nlso be fetched
exclusively from an external memory addn.>Sses OOOOH
to FFFFH, by connecting the external acct.>SS pin (EA) to OFFFH
4K
ground. EPROM
ROM
000OH
11.3.5 Input/Output Ports
The 8051 has 32 1/ 0 pins oonfigured as four eightbit parallel porl< ( 1'0, Pl, 1'2,
and P3 ). AIJ four pnrts arc bidirectional. i.e. each pin wilJ be configured as input or
output (or both) under software control. Each port consists of a latch. an output driver,
and an input buffer.
The output d rives of Ports 0 and 2 i.1nd the input buffers of Port 0, are used to accL-s.~
external memory. As mentioned earlier, Port 0 outputs the low order byte cf the externlll
memory address, time multiplexed with the data being written or read. and Port 2 outputs
the high order byte of the external memory addn..:.ss when the addrcs~ is 16 bit~ wide.
Otherwise Port 2 gives the contents o( special function register P2.

0
Latch 0
PortO
' .. 110
o!p Driver .. AoAt
Buffer 0
'
. 1o,.o,

0
Latch 1
Port 1 ' .
.
o/p Driver . ..
Suffer 1
'
Latch 2
Port 2 '' ....
o/p Driver
Buffer 2 .
'
Latch 3

Sutler 3
Port 3
o/p Driver
'' ..
..
.
'I"'""'"
110

"""""'
Seriol 00o1a
RQ.wA
'
Fig. 11.4 1/0 Ports

Copyrighted material
Microprocessors and Interfacing 11 -10 8051 Microcontroller

All port pins of Port 3 arc multifunctional. They have spcd'-'.l functions as shown
below including two external interrupts, two counter inputs, two special data lines and
two timjng control strobes.
'
Symbol Position N1me and Signtfic:anee

RD P3.7 Read dala oonttd output. Adive aow pulse generated bY hatdware when
external data memory_ is react.
-WR P3.6 Write data control output. Active tow pulse generated by hardware when
e),,"'maJ data memory is written.
T1 P3.5 Ttmetlcountet 1 extetN11 lnout or test cln.
TO P3.4 Timer/oounter 0 external Input or test pin .
INT1 P3.3 lnte~pt 1 in_pu_t ~. l ow-level or faling:_e9g_e trjggered.
INTO P3.2 lnterruot (J fnout '*' lowlevel or fallln ttlooe<ed.
TXD P3.1 Transmit Data pin for serial port in UART mode. Ckx:t output In shift register
mode.
RXD P3.0 Receive Data pin for serial pon in UART mode. Data 1/0 pin in shift register
mode.
Table 11.2
11.3.6 Register Set of 8051
11.3.6.1 Register A (AcctJmulator)
It is an 8-bit register. It holds a source operand and rece.ives the rest1lt of the
arithmetic instructions (addition, subtraction, multiplication. and d ivision). 11le accumulator
cnn be the source or destina tion for logical operations <11\d a number of special data
movement instn1ctions, including look-up tables and external RAM expansion. Several
functions apply exclusively to the accumulator : rotatei parity computation , testing for
zero , and so on.

11.3.6.2 Roglster B
In addition to accumulator, an 3-bit &-register is available as a general purpose register
when ..... not being used for the hard ware multiply/divide operation.
it ~

11.3.6.3 I'Togram S1atus Word (Flag Register)


Many instructions implicitly or explicitly affect (or are affected by) several status flags,
which are grouped together to form the Program Status Word. Fig. 11 .5 shows the bit
pattern of the program s tatus word. It is an 8-bit word, containing the information as
foUows.

Copyrighted material
.
Mlcrop>cessors and Interfacing 11 11 8051 Microcontroller

B, 0, o, B,
CY AC FO RS t RSO OV p

CY Bit 7 Carry flag


AC Bit 6 Auxiliary carry !lag ror BCD operations
FO Bit 5 User d efined fl.ag (Flag zero)
R.~ J. RSO Hit 4-3 Selef:t the working register ba nks as follows :

RS1 RSO Bank Selection

0 0 OOH 07H Bank 0


0 1 081< OFH Bank 1

1 0 10H - 17H Bank 2

1 1 181< 1FH Bank 3

ov 6it 2 OverAow Oag


Bit I Reserved
r Bit 0 Parity flag (1 a Even parity)

Fig. 11.5 Program status word

11.3.6.4 Stack and Stack Pointer


The stack refers to an area of internal RAM that is used in conjunction with certain
opcodes data to store and retrieve data quickly. The stack poin ter register is used by the
8051 to hold an internal RAM address that is called top of stack. The stack pointer register
is 8-bit wide. Jt is incn.--ased before data is stored d uring PUSH and CALL instruction.~ and
decremented after data is restored d uring POP and RET ins tructions. n,us stack array can
reside anywhere in on-chip RAM. The s tack pointer is initialized to 07H after a r~t. This
cmtSCs the st<tck to bcgill at location OSH. TI\c operation of s tack a nd stack pointer is
illustrated in Fig. 11 .6.
Pl~a$<.' ref~r Fig. 11.6 on next page.

11.3.6.5 Data Pointer (DPT!I)


Tho data pointer (DPTR) consists of a high byte (DI'H) and a low byte (DI'L). Its
function is to hold a 16 bit nddress. It mny be manipulated as a 16 bit data register or as
two indc.opende:nt 8 bit registers. It serves as a ba...coe register in indirect jumps, lookup table
instructions and external data transfer. Tile OPTR does not have a single internal address;
DPH (83H) and DPL (82H) have separate internal addresses.
16-bit DPTR

I OPH"'"' I OPL"'"' ~-1 -:>~'/"-~ Memory


Address

~~
6-bi1 8-bil.

Copyrighted material
Microprocessors al)d Interfacing 11 12 8051 Microcontroller
On-c::hip RAM Qn.chlp RAM On-chtpRAM

[}'E)-
l===l 08
07
l===l
1-----1 08
09
r- ,.,.
09
06
Stack pckller 06 SP -
07
SP - SP 1 ..J --~:::::~~=1 07

(;~) Status of tack and (b} Store oper~tion


stack pointer of reset

I 09
08
07

SP - SP-1 _ _ ~~~ E
(c) Read operation

Fig. 11.6
11.3.6.6 Program Counter
11te 8051 has n 16-bil program cou.nt~r. Jl is used to hold lhe address of memory
location from which the next instmction is to be fetched. Due to this the width of the
program counter dcddt."S the maxil'num program length in bytes. For example, 8051 is
16-bit hence it can addrt..--ss upto 2',. bytes (64 I<) of mcntory.
The PC is automatkally incremented to point the ne_x t instruction in the program
St-:.quence after execution of the current instruction. It may also be altered by certain
instructions. The PC is the only rt.'g:istcr thl'lt docs not have an internal address.

11.3.6.7 Special Funcllon Registers


UniH(;e other microprocessors in the lntel family. 8051 uses memory mapped 1/0
through n !Oet of special function registers that nre implemented in the addrL'SS space
immediately above the 128 bytes of RAM. Fig. 11.7 shows special function bit addresses.
All acce8S to the four 1/0 ports, the CPU registers, interrupt-control registers, the
timer/counter, UA.RT, and power oonhol nre performed through registers between SOH
and FFH.

Copyrighted material
Mic:n>procnoo,.. and lnt.rfacl ng 11 13 8051 Mlcrocontroller

ones
llylo
- ( M S B)
(l68)
OffH

nl H I FS I IF31 f2 1fl I Fo II

OEOH E71 ee l es I el Ell E2 1eo Ieo


OOOH 01 I 061osl e<l o31021 oo Ioo PSW

088H - I - I- I scJ. ell_[ BAj ell_[ BB IP

OBOH 111 I ssl es I a. IB31B21eo Ieo P3

AFI - 1-IACIABIMIMIAII
A71 Alii AS 1... 1All A2 1AI IAO P2

OF I!1EI9019CI96J SAj eej ee

91196 196194 193192 191190 PI

88H 8F I ae Iso lee Is~ SAJ a9j88 TCON

,, 188 185 184 183 112 1eo 1eo PO

Fig. 11.7 SFR bit addrua

Copynghted materio1l
Microprocessors and Interfacing 11 -14 8051 Mlcroeontroller

Table 11.3 contnins a list oi nil the SFRs and their addresses and their value in binary.
COLnparing Table 11.3 and T.1ble 11.4 shows that all of the SFRs that are byte and bit
addres..,.lble nrc locate-d on th<' first column of the Table 11.4.

Symbol Name Address Value In Binary

"ACC Accumulator OEOH 0000 0000


e B Reolster OFOH 0000 0000
psw Program Status WOld OOOH 0000 0000
SP Stadl. Pointer 8tH 0000 0 1 1 1
DPTR Data Pointer 2 Bytos
DPL low Byte 82H 0000 0000
OPH Hioh Byte 83ti 0000 0000
po Port 0 80H 1 1 1 1 1 1 1 1

"PI
"P2
Port 1
Port 2
80H
OAOH
'I I' II II 1 1 1 1

11 1 1

"P3 Port 3 OBOH 1 1 1 1 1 1 1 1

068H 8051 xxxo 0000


"IP Interrupt PriOtity Control
8052 xxoo 0000
OA8H 8051 oxxo 0000
"IE Interrupt Enable Control
8052 oxoo 0000

TMOO TlmeriCounter Mode Control 89H 0000 0000

"TCON Tlmef'I'Counter Control 88H 0000 0000


T2CON TimerlCounter 2 Com~ OC8H 0000 0000
THO Timer/Counter 0 High Byte 8CH 0 0 0 0 0000
no Timer/Counter 0 Low Byte 8AH 0 0 0 0 0000

THI Timer/Counter 1 High Byte SOH 0000 0000


Ttl Timer/Counter t l owByte 88H 0000 0000
+ TH2 Timer/Counter 2 High Byte OCOH 0000 0000
Tt2 Timer/Counter 2 Low BYie OCCH 0000 0000
+ RCAP2H TIC 2 Copture Reg, High Byte OCBH 0000 0000
+ RCAP2L TIC 2 Cop!Ure Reg. Low Byte OCAH 0000 0000
SCON Serial Control 98H 0000 0000
SSUF SaricH Data Buffer 99H lntermlnate

87H HMOS ox xx xxxx


PCON Power ContrOl
CHMOS oxxx 0000
Table 11.3 List of all SFRs ( =Bit addressable. + =8052 only )

Copyrighted material
Microprocessors and Interfacing 11 - 15 8051 Microcontroller

Bit 8 Bytes
Addressable
F8 FF
FO 8 F7
ea EF
eo ACC E7
08 OF
DO PSW 07
cs T2CON RCAP2t RCAP2H 71.2 1>12 CF.
co C7
B8 IP SF
BO P3 67
A8 IE Af
AO P2 AT
98 SCON SBUF 9F

90 PI 97
88 TCON TMOO TLO TL1 THO 1>11 SF
80 PO SP DPL OPH PCON 87
Table 11.4 SFR memory map

11.4 Memory Organization In 8051


Fig. 11.8 shuws the basic memory structure for 8051. H can access upto 64 K program
memory and 6-l K dtttil memory. The 8051 has 4 Kbytes of internal program memory and
256 bytes of illtcn,al data memory.
Program Memory (Read Only) Data MemOty (Read1Writ9)
................................................. ...................................................
~

FFFFH ...i FFFFH


.!.
. .. ...
"' :. :. :: External-+ .:
External !

J't
' OFFFH
-
~
EA= 0
Extemat
4
0000

. 0000
L........................... J .....J .....i .

RD WR

Fig. 11.8 Memory structure


Copyrighted material
!
Mi~.~fPJEf~~.sors and Interfacing 11 -17 8051 Microcontroller
Vex;

RAO
LATCH
IHTERHAL
PUUUP

!NT BUS
P1.X
0 .) PIN
P I .X
WAJTE I.ATCH
TO -;~t---~CI.
LATCH
~ __;Ci!J------~~

Fig. 11.9 (b) Port 1 bit

Vee
-"""" OV$
REAO
I,.ATCH .. ~-~ t CONTR<>.
~


!NT SUS

P2.X
PitI

: ______ ___
.,_.,_ .
...
REAO

Fig. 11.9 (c) Port 2 bit

At.lE.RNAT'E
Ol/TPUT
RfAO FUNCTION' INTERNAl
LATCH P!A.t.UP

PlX
IN T OVS PON
0 0
P3X
!li'RITE I.AlCH
TO -;ll'---t<~L:.._~O~
t.ArCH

READ
ALTERNATE

""""
FUNCTION

Fig. 11.9 (d) Port 3 bit


Fig. 11.9 8051 port bit latches and UO buffers

Copyrighted material
Microprocessors and Interfacing 11 -1 8 8051 Microcontroller

As ~hown in the Fig. 11.9, for Port 0 and Port 2 drivers arc swHchable to internal
ADDR/ DATA and ADDR bus. respectively, by internal CONTROL signal. The switching is
required to access external memory. During external memory accesses, the P2 SFR
rema ins unchanged, but PO SFR ge~ ls written to it.
As m<.'nt-ioncd earlier, Port 3 htt.' muJtifunction pins. Therefore, each pin of Port 3 can
be programmed to usc as 1/0 or as one of the alternate function. This is achieved by the
another control input, "alternate output fu nction"', as s hown in the Fig. 11.9. When latch
bit of Port 3 conta ins I. the output level is controlled by control input, "alternate output
function."
The port pi_n can be configured as an input by writing 1 in the la tch bit of the
corl'L~punding pin. It turrL., OFF the output driver FET. Then for, Ports 1, 2 and 3, the pin
is pulled high by the internal pullup, but can be pulled low by an external source. There
is no internal pull-up for port 0. Therefore, its output pin floats when 1 is written in the
latch bit, and pin can be used as a high impedance input. The port 0 is said to be true
b idirectional"', bec..'lusc when configured as an input it floats..
On the otherhand, the output of Ports I, 2 and 3 arc pulled high with pull-up
registers, when configured as an input Thus they are sometimes called "'quasi
b id irectional" ports.
The Table 11 .5 summarize!; the functions of four ports.
Port Functiona
Pott 0
Used as an 1/0 port

Used as a bi-directional k:lw~er address


and deta bus for extern&! memory.

Pott 1
Used as an input/output por1

Pott 2
Used as an inpuVol.rtput port

Used as a rMgher-ordet a<tess bus for


external memory.

Pott 3
Used as an inpuVoutput port or u$0d for
alternate function as shown be.low.
P3.0.RXD Serial data input
P3.1TXD Serial data output
P3.21NTO Extem&t Interrupt 0
P3.31NT1 Extemel lntefTUpt 1
P3.-r o Extem$1 timer 0 input
P3.5-T1 External tmer 1 Input
P3.&-WR External memory write signal
P3.7-RO Extemal memory read signal

Table 11.5 Port func11ons

Copyrighted material
Microprocessors and lntertacing 11 -19 8051 Microcontroller

11.6 External Data Memory and Program Memory


We have St.--en thnt 8051 has internal data and t.'Ode memory with limited memory
capacity. This memory cap~city may not be sufficient fo r some applications. ln such
situations, we have to connect external ROM/EPROM and RAM to 8051 microcontroUer to
increase the memory C<"pacity. We also know that ROM is used as a program memory and
RAM is used as a data memory. ~ t us see how 8051 accesses these memories.

11.6.1 External P rogram Memory


Fig. 11.10 shows a map of the 8051 program memory.

FFFF H FFFFH

60 Kbytes
External
64 Kb)"'e$
OR External
1000H
OFFFH
4 Kbytes
tntetnal 0000
0000 )

Fig. 11.10 The 8051 program memory


In 805'1 w hen the EA pin is connec:ted to \t:c. proSram fetches to addresses OOOOH
1

through OFFFH a re d irected to the internal ROM and progTam fe tches to addres..<OCS IOOOH
through FFFFH arc directed to external ROM/ EPROM. On the other hand when EA pin is
grounded, all addresses (OOOOH to FFFFH) fetched by program are dire<:t<'<l to the extcrn.,l
ROM/EPROM. The PSEN s it,ona l is usc..>d to activate output enable ~ignal of the external
ROM/EPROM, os shown in the Fig. 11.11.

A
P, Po Do
' v 0,
EA
~
ROM/EPROM

8051
l
A
T
c
"v ...A,
ALE
Cl.K H MrJr.
"--"
P, Aa
p2 "v Al5
PSEN 5E
.
Fig. 11.11 Accessing external program memory

Copyrighted material
Microprocessors and Interfacing 11 -21 8051 Microcontroller

Instructions to Access External ROM I Program Memory


The table 11.6 explains the instructions to access external ROM/program memory.

Mnemonic Operation

MOVC A. @ A + OPTR Copy the contents or the external ROM 81dcfre1-S


formed by adding A and the OPTR. to A.

MOVCA, @A+PC Copy the contents of the external ROM address


f(l(l"l'led by aOddlng A and the PC, to A.
Table 11.6

11.6.2 External Data Memory


Fig. 11.14 shows a map of the 8051 data memory

Internal Memory
~ FFFF H

FFH
..................... ISFRs) .

Accessible by
Aoce&sible by
Indirect
Uppe< Addressing
Direct
128 Ad0re:$$1ng 64 Kbytes
Only
Extemal
SOH Memo<y
+-AND-+
7FH
Aocenible by
lowe< Oirec:l & Indirect
128 Addrt$$ing

OOOOH
0 I

Fig. 11.14 A map of the 8051 data memory

The 8051 ca n address upto 64 Kbytes of externa l data memory. The "MOVX"
instruction is uSL~ to access the external data 1\'lcmory. The inten1al data memory space for
8051 is d ivided into three blocks : Lower 128 byte'S, Upper 128 bytes and SFRs. The upper
addrt"SSeS and SFRs occupy the same bloc-k of address space.. SOH through FFH, although
they a re physicaJJy separate entities. As shown in the Fig. 11 .14, the upper address s pace is
ao:~siblc by indirect addressing onJy and SFRs are accessible by direct addressing only.
On the other hand, lower address s pace can be ac~ either by din."Ct addrcs.o;ing or by
indirec-t addressing.

Copyrighted material
Microprocessors and Interfacing 11 - 23 8051 Mlcroeontroller

ALE
_/ \'--- ------'/ \..__-----'!
PSEN

WR

PORT O DATA INSTR


OUT IN

PORT 2 ----'x'----P-2.1_H'_2._7 o
_R_ A_o-_ ~x... -A 1, FROM PCH
A _,,_r_R_O_M_o_P_H_ _

Fig . 11.16 (b) Timing waveforms for external data memory write cycle
Instructions to Access External Data Memory
The tabll.' 11.7 explains the instruction to access extem.d data memory.

Mnemonic Operatio n

MOVX A, @Rp Copy the contents of the extemat address in Rp to A.

MOVX A, @OPTR Copy the contents of lhe external address in OPTR to A

MOVX @ R.p, A Copy <lata from A to the eJCternat 8d<fress in Rp.

MOVX @OPTR, A Copy data from A to the eJCternal address in OPTR

Table 11.7
11.6.3 Important Points to Remember In Accessing External Memory
AU external datil moves with external ROM or externa l RAM involve the A
register.
While accessing external memory, Rr can address 256 bytes and DPTH can
address 64 Kbyte;;.
MOVX instruction is used to access external RAM or 1/0 add resses.
\P\' hen PC is ust>d to acccs5 externa l ROM, it is incremented by 1 (to point to the next
instr\ICtion) before it is addc.>d to A to form lh~ physical address o r external ROM.

Copyrighted material
Microprocessors and Interfacing 11 -25 8051 Microcontroner

11.7.2 Timer 0 and Timer 1


Ln thi5 timers, "Timer;' or Cou., ter" mnde is sclectoo by control bits c;T in the Special
Function Register TMOD (Fig. ll.IS). These two Timer/ Counters tmve four Op<Omting
modt'S, whieS. are sciC<ted by bilpoirs (Ml , MO) fn TMOO. Modes 0, I ond 2 a re .. me for
both Timer / Counter'S. Mode 3 IS differe.n~ The four O'f"erating modes At~ d<!$Cribcd as
foUows ::

(MSB) (lS B)

MOl GATE C/Td M1 MO


;;>
I
Timer 1 TlmerO
GATE Gaung co~ ..,on_!!!. r~r/CQufl60r tl' 1s tA l Mrt Opm~U~g IAodn
onllbled o!1ttWhll 1NTK" pin ~ .;~nd no t1 D ~!lit ll'nerK;ounter ~Hlt"' W4l\ rl.X"& ~bll
~ brt If Ml Whorl deatOO Thner "li" '-
.nablod ~WW~r 1'Rx conlml ~Is set
i ""''""
Hi-t>~! TI!Nir!Cot.lnw 1l-l;< ""li" "TT.~e Me
r.tr llrner ot CWMtlf ~r de..-.6 tor 1lm0t'" ~; ~ISI'IDII"tt&CIIit'
90!kltl \_,P\Il tromlf!Wimal sys:1ern ctocll). Se1
fOt Q)ull((lor ODetttlfon (Jn:Mtn:rm ,_.lnpul ptr.), 0 a.bir ulo.rlllrcl3d1111'11!1'/Counll!r 'THII" I'IO!tte:
ll vatu& \llhlen Is to be tiiOedllld IMo "TLJ("
eadi~!IOOA!rli!Ms.

rn"* O) llO .s n 8-o~1 r~x;o...,~er


OOn!!ollt!d bY the Slal)(la:cl T 1'1~ 0 COtltJdi
bits. ll10 Is 11n 8-bit llml!l' ~ C!Cinii'OIIt!cl rJt
li~tWJ I CO!\t!OI bt.~.

~TII'IIO 1} litni;'I'ICOuruel, sb:11)9ad.

Fig. 11,18 TMOD : Timer/counter mode canirol register


MODE 0

r
I
- l
'I
' -
ctr=O
'I
I
TU Ttt1
TF I ,. lnterrupl
II Bl"l ~ llll)
C'T:t 'I
n PIN - - - - - - . . . . J
'
I
TR1 I
I
I
' G/ITE C"'llf(ll
I
1 INT1 PIN _ _/-,.- - '
----.. --__. . --.. ----- -4co.--------
~mr I counter conltof log9c

Fig. 11.1c9 Tlmar/countar 1 mode 0 : 13-bit counter

I 1 I lh t I II I
Microprocessors and Interfacing 11 -26 8051 Mlcrocontrolle r

Both Timers in Mode 0 is an S~b it Counter with a divide-by-32 prescaJer. This 13-bit
timer is MCS-48 compatible. Fig. 11.19 shows the Mode 0 opera tion as it applies to Timer
L In this mode. the Timcr register is configured as a 1J..bit register. As the count rolls over
from all ls to all Os, it SC'ts the Timer interrupt flag TFl. nu~ COW'Ited input is enabled to
the Timer when TRI = I and either GATE= 0 or INTI =1. (Setting GATE = 1 allows the
Timer to be o.)ntrol1ed by externa l input INTI, to fad litate pulse width measurements..)
TRI is n control bit in the Spial Function Register TCON (fig. 11.20) GATE is in TMOD.
(MSB) (LSB)

[7F, I TR I I TFO I TRO I lEt I ITt I lEO I ITO I


Symbol Position Name and Significance

TFt TCON.7 Timet 1 Overftow f lag. Set by hatdwate on timer/counter overllow. Cieared when
lnterrupc processed.

TR1 TCON.6 Timer t Run control bit SeVcteared by software to tum timer/counter on/off.

TFO TCON.S Tll'flef' 0 Ovetftow Flag. Set by Ml'<twate on timerlcoun~er 0\'erflow, Cle3red when
lnterrupc processed.

TRO TCON.-4 Tlmet 0 Run eorttrot til. SeVdeared by software to tum tlmer.'counter onfolf.

IE1 TCON.3 lmcrrvpt 1 Edgo Flag. Sol by hardWare when external W'lterrupt cdgo delectod.
Cleared when intonupl procflMd,

ITt TCON.2 lnterrupl 1 Type control olt. SeVcleared by software to speeity ramng edgeiiOw
leVel triggered external interrupls.

lEO TCON.1 huertupt 0 Edge R&g. $et by hllrdw,re when extemal iOtettt.JI)t edge delbCted.
Cle81ed when Interrupt processed.

ITO TCONO lnten'IJS)t 0 Type conlrOf bll. $eVCie3rod by sottw&re to specify telling edgollow
level triggered e:xt.ernat imerrupts.

Fig 11.20 TCONtlmer/counter control/status register


The 13-bit register consists of all 8 bits of THI and the lower 5 bits of TU. The upper
3 bits of TLI are indeterminate and should be ignored. Setting the run flag (TRI) does not
d ear the register s.
_ _Mode 0 operation i~ the sam~ for Timer 0 as for Timer 1. Substitute TRO, TFO and
INTl) for the corresponding Timer 1 signaJs in Fig. 11.19. There are two different GATE
bits, one for Timer 1 (TMOD.7) and one for Timer 0 (TMOD.3).

Copyrighted material
Microprocessors and Interfacing 11 28 8051 Mlcrocontroller

MOOE 3
Timer l in Mode 3 simply holds its count. The effecr is [he same afol setting "ffi.1 = 0.
1'imer 0 in Mode 3 \.-"St.lblishes TLO and THO >lS two scpar,1te count.ers. The logic for
Modt!3 nn Timer 0 is ,shl)wn in Fi)). 11 .21. n.o uses th(;! T iml!r 0 amtrol bits : C/ 'f, GATE.
TRO, iNTO, ond lFO. THu is locked into a tim<.'! mode (counting machine cycles) and lakes
over the use llf TRI and TFl from 'Timer J. Thus, THO now control$ lh~ : Timer 1
intcr:rupt.

'tOF11~-------'

1f12 I OSC
T>iO
(8 81~1 r--1 EJ-- inlerruot

CONtROL

Fig . 11.23 Timer/counter 0 mode 3 '"'- ~ two 8-blt counters


~ l ~c 3 15 providt~d for applicatiQtt$ r~mnr\g An ~xtra Sbil tin'llt or cuunte:r. Wlth
firm::.r 0 ln Mode 3, <Hl 8051 Jook like it has three Timer /Counters1 and nn 805~ like it
c:t1'1
h11s four. When timf..:ar 0 is in t-.lode 3, Timer Lcan be tum1..>d on and oft by switchfng it out
of lmd fnto 11~ own Mode 3, or !:t~n ~tiiJ be uSl.:l(j by the seri.-.1 port as ~ baud ratl'
gcJ\crator, or i 1'1 (act, 1n any application not requiring an interrupt.
nw Table 11.8 summnriY.cs the mndl~ uf titners.
Mode Brief Description

Mode o 131>11 umer (Tt5 bll$ ond TH8 blls)


Courtier overllow ls Indicated by 11me Interrupt 1\ag,

Mod<! 1 16-bil bmet (Tt.-5 bi1s and TH-8 bits),


Rest ~ same u modct 0.
M-2 Automatic relOAd mode. 8-bit counter (TL-8 bit) QYEtrflotftt from
TL not onty sets Tf. but also rcMo&ds TL with the coments or 111.
Mocle 3 Establlstles TL and TH as two separate counters.
Table 11.8 Summary of timer modes

II I
Microprocessors and Interfacing 11-30 8051 Microcontrolter

Rl SCON.O Receive lnterrupl flag.


Sot by hafCiw9rc when t>y\0 received. caearcd by sottw;)re arter serviCing

Not-1 : The slate of { SMO. SM 1) selects ;


Mode SMO SM1

0 0 0 . Shift regisrer : baud ~ f/12


1 0 1 . 3blt UART, vrlable <lala ra1e.
2 1 0 . 9bl! UART, tilted dSI.a rale : baud U32 or tt64
3 1 1 . 9b1t UART, veriable data rate.

Fig. 11.24 {a) SCONserial port control/stat us register


(MS8) (LS6)
7 6 s 4 3 2 1 0
I SMOO I GF1 GFO PO IOL

Symbol Position N ame and Significance

SMOO PCON.7 Serial boaud rnto modify bit, 11 is 0 at ~. It is &el to 1 by progrom to doul *
the baud rate.

-
GF1
PCON.&-4 Not defined

PCON.3 G&neral purpose user tlag bit 1. SeVCieared by program.


GFO PCON.2 GenE!fal purpose use:r rtag bit o. Sei!Cieared by prOgram.
PO PCON 1 Power down bit. 11 is set lo t by p rogram to enter power dcwln configuration
for CHMOS microcontrollers.
IOL PCON.O ldte mode b it. I! is set to 1 by progra-m to enter Idle mode configuration for
CHMOS microconttollers.
No te : PCON i s nor bil aodressable

Fig. 11.24 (b) PCON register

11.8.1 Operating Modes for Serial Port


MODE 0
In this mode, serial data ~1\ters i'lnd ~xits through RXD. TXD outputs the shift dock. 8
bits are transmittOO/ reccivt..'CI : 8 d<.\ta bits (LSB firs-t). The baud rate is fixed at 1/ 12 the
oscillator frequency.
MODE 1
In this mode, 10 bits are tra nsmitted (through TXD) or re<:cived (through RXD) : a stMt
bit {0), 8 dala bits (1.$6 first), and a stop bit (l ). On receive, the stop bit goes into RB8 in
Special Function Regis ter SCON. The baud rate is variable.

Copyrighted material
M icropr~ssors and Interfacing 11 - 31 8051 Microcontroller

MODE 2
ln this mod~. 11 bils a re tr<Ul$mitted (thorug h TXD) or r<.>eeived (through RXD) : a start
bit (0), 8 data bits (lSB first), n programmable 9th data bit, and a stop bit (1). On
Tran~mil, the 9 th data bit (1138 in SCON) can be assigned the value of 0 o r 1. Or, fo r
example, the parity bit (1', in the PSW) could be moved i11to TBS. On receive, the 9th datn
bit goes into R BS in Special Function Rcgsitcr SCON. while the stop bit is ignored. The
baud r.lte is prosmmmable to either Y~ or y64 the oscillator frequency.

MODE 3
In thi~ Mt)de, 1 J bits are tr<~nsmitted (through TXO) or rt;.-ceivtod (through RXD) : n start
bil (0), S data bits (lSB first), a progmmmnblc 9th data bit o.nd a s top bit ( 1). In fact,
MOOe ? is the s.1mt> as Mode 2 in aU respeocts except the bc1ud r.ite. The baud rate in Mode
3 is v,uinble.
In ,,n fo ur mOO..-s, tnmsmis!'ion ~ initiated by any ins tn.1ction that uses SBUF as a
destination n:.-gislcr. Rcccpti()J"' i~ initia ted in Mode 0 by the condition Rl 0 and REN =; 1.
R(orrccption is initintcd in t h~ o thLr mt1d~ by th(' incoming start bit if REN :: 1.
TI\C Table 11.9 Stunm~riL-'S the four serinl port modes provided by 8051.

M-0 8-<:iela bas


Transmission Format Baud Rate
;1 osciiSatOC' frequency
1 10btt (start b!l + 8odata bits $lOP bit) Vorloble
2 1~bit (start bh + 8..0ata bits programmabte Programmable to elti'I.Cr i2
9 data bit stop bit) or ;_. oscilfator frequency

3 1\bil (star1 bit 8 data bit programmable g1h Variable


cau. b't stop bit)
Table 11.9 Summary of serial port modes

11.8.2 Serial Port Control Register


The sericll port control a nd ~ta lus n:ghtt:-r is the Specinl Function R~giste r SCON,
shown in Fig. l \.25. TI1is r~.-g istcr (_'Ontain.-; not o nly the mode selection bits, but <llso Ulc
9th datcl blt for transmit and n..>ceivC" (TBS rmd RBS). and the serial port intemtpt bits
(TI and Rl).
11.8.3 Generating Baud Rates
Serial Port In Mode 0 :
Mode 0 h.1s a fix(.-'(! baud rate w hich is 1/ 12 of the oscHJator frequency. To nm the
serial pt)rt in this mode no ne of the Timer/Cowltcrs need to be set up. Only the SCON
rcgis tC'r nC'eds to be defined.
Osc Frt..'1
Baud Rote =
12

Copyrighted material
Microprocessors and Interfacing 11 32 8051 Microcontroller
Serial port in Mode 1
Mode 1 has a variable baud rate. The baud rate can be generated by either Timer 1 or
Timer 2 (8052 only).
Using Timer/Counter 1 to Generate Baud Rates
For this purpose, Timer 1 is usai in mode 2 (Auto-Reload).
k x Osdlliltor Freq.
Baud Rate = 32x12x[256 - THI)J

If SMOD = 0, then k = 1.
If SMOD = l , then k 7 2. (SMOD is the PCON register)
Most of the time the user knows the baud rate and needs to know the reload value for
THl. Therefore, the equation t'o calculate THl can be written as :
TH J = 256 _ kx Osc Freq.
384xbaud rate

THl must be an integer value. Rounding off 11-:11 to the nearest integer may not
produre the desired baud rate. In this case, the u~r may have to choose another crystal
frequency.
Since the PCON register ls not bit addressable, one way to set the bit is logical QR.ing
the PCON register. (i.e. ORL PCON, #SOH). The address of PCON is 87H.
Using Timer/Counter 2 to Genrate Baud Rates
For this purpose, Timer 2 must be used in the baud rate generating mode. If Timer 2
is being clocked through p in T2 (1'1.0) the baud rate is :
a. d R Timer 2 Overflow Rate
uau n1c =
16
And if it is being clocked internally the baud rate is :
Osc Freq.
Bau d Rote = 32x[65536 - (RCAP2H,RCAP2L))

To obtain the reload value for RCAP2H and RECAP2L the above equation can be
rewritten as :
Osc Freq.
Rc P2H Rc P2L
A ' A = 65536 - 3'h6audrate

Serial Port in Mode 2


Tile baud rate is fixed in this mode and is y32 or y~ of the o~U.ator freq uency
depending on the value of the SMOD bit in the PCON register. In this mode none of the
Timers arc used and the clock comes from the internal phase 2 clock.
SMOD 1, Baud R.1te = y, 0sc Freq.

Copyrighted material
Microprocessors and Interfaci ng 11 33 8051 Mlcrocontroller

SMOD ~ 0, 6aud Rate = Y.. Osc Freq.


To set the SMOD bit : ORL PCON,NSOH. The address of PCON is 871-1.
Serial Port In Mode 3
The baud rate ln mode 3 is variable and sets up exactly the s.;1me as in mode 1.

11.9 Interrupt Structure


The 8051 provides 5 interrupt :o;ources. The 8052 provides 6. These a re shown in
Fig. 11.25. The external lntt>rrupts INTO and lNTl can e.1ch be either It-vel-activated or
transition-activated, depending on bits ITO and IT! in Register TCON. The flags that
actually gcncr<\te these interrupts an~ bits lEO and fE1 in TCON. Whe1\ an external
interrupt is generated, the nag tha t ge:ncr<.\ted it is cleared by the hnrdware when the
service routine is Vt'Ctored to only if the interrupt was tmnsitionactivated. If the interntpt
was level-activated, then the external requesting source is what controls the request Aag,
rathC'r that the on--chip hilrdwarc.

TPO - - - - - - - - -

0 Interrupt
sources
1

TF1

Tt
Rl - D>----
Fig. 11.25 MCS 51 Interrupt structure
The Time-r 0 and Timer 1 Interrupts are generated by TFO and TF1, \vhich a re ::>et by a
rollover in U\eir rcspt..-ctivc Timer/ Counter registers (except sec Timer 0 in Mode 3). 11lc
timer flag set upon generation of interrupt is cleared by the on-chip hardware when
micnxontroller starts ext.-cution of particular interrupt service routine.
The Serial port Inte rrupt is generated by the logical OR o f Rl and Tl. Neither of these
fli'lgs is clearOO by hardware when the service routine is vectored to. ln ftlct, the service

Copyrighted material
Microproceoaors and Interfacing 11-35 8051 Mlcrocontroller

(MSB) (lSB)

I I PS PT1 PXI

Symbol Position Name and Slgnlflc.anc.

- IP.7 IRese<Ve<lt

- IP.6 (Reserved)

- IP.S (ResOM>d)

IP.4 Serial poc1 Priority control b it.


SeVdeared by software to spectfy higMow priority interrupts for Serial port.
PTI IP.3 Timer 1 Prlotlty contrOl bit
SeVdeared by softwate 10 specify high/low ln1erruD1S for timer/counter 1.
PXI IP.2 EX1emat interrupt 1 Priority control bit.
SeVdeared by software to ~ high/low priority interrupts for INT1.
1>1'0 IP.t Timer o Priority control bit
SeVdeared by software 10 spedfy high/low
. Interrupts for timer/counter 0.
PXO IP.O Extet"nal intertupt 0 Priority control bit. SeUcleared by software to specify
high/low prlotlty intorruplS for INTO.

Fig. 11.27 IP - Interrupt priority control register


If t\vo requests of different priority levels are received simultaneous ly, t~ n.:.quest of
higher priority levc1 is servidOO. If requests of the same priority level are received
s imultaneously, an internal polling sequence dctennines which request is serviced. Thus
within each priority level there is a second priority s tructure determined by the pomng
sequence, as follows :

No. Source Priority within Level

1. lEO (Nghe$1)

2. TFO

3. lEI

4. TFI

s. Rl Tl (IOW0$1)

Note tha t the "priority within level" structure is only used to resolve s imultaneous
requests of the same priority level.
The U' register ront..1.ins a number of unimplemented bits. 11'. 7 and IP.6 arc vacant in
the 8052s, and in the 8051s these and IP.S are vacant. User software should not write l s to
these bit positions, since they may be used in future MCs-51 products.

Copyrighted material
Microprocessors and Interfacing 11.37 8051 Mlcrocontroller

11 .10 Interfacing 8255 for 1/0 Expansion


As seen earlier, for interfacing external memory to the 8051. port 0 and port 2 are used
as multiplexed address/data bus and a higher order address bus respectively. lf the c;ircuit
needs the on chip peripherals (e.g. serial 1/0 and Interrupts) then only I port is available
for 1/0. In such situations, 1/0 expansion ls necessary and it is achieved by using 8255.
The Fig. 11.28 shows the expanded l/0 ports using 8255. Data bus of 8255 is connected to
the Port 0. Address lines AO and AI, after latches are coMected to AO and AI of the 8255 .

M .....'
...
"-
XTAL1
......
l
XTAL2

......
...
....,,"' '*
"'
.!..
..,, .,.
RST "'
'

.!!. .........'" "


EJ:/VC<:
'
" ... .... .....,... "
........' Ift
m

~
RXD
TXO
........, ' ,...
"
...
.""' . .....,1.~
~
"'" """
-H
~"
..,
.. '


82SS

2
1
~
t.SU
'* ~
f-2 " fL

.
...
.
.... "
.~.
1

"'
" "
,.
..,
......... '
2 '''"
cl ~ [: '
"
1"
Fig. 11.28 110 expansion using 8255

Copyrighted material
Microprocessors and Interfacing A-4 Appendix A

M,.._nlcncl
OMcrlpdon I ....lnllott Codt

"""'--
. - . Unuonc!IU-..1 AIIOIP

o;,<tts ..iiiWI ~
Jfi<IISI10
! u t01001

! tt 10 1 0 11 -...
tfUU 1 f ?f$ 1
:1310
ol~h

ll'dr.ct.,.... ~
Ol!ea lnlll~".,..enl

1nctto.c11n...,.._1
1 11101010

l t t111 1 11
--
1 111 1 111 1 moOIOOdm

........
IIIOd tO 1 Ntf>
_,.,.
Oll'wtf'i'i

llltT Jbtuon ,_CALL.:


.,..

-
,...~

Wil'm $eg ~ '"'"'"II)$,.


ltt000 011

I UOOOIO
ltt0010 11 ---- -- .......,.
~ AOclonlll"'"*'-leiiD $P

JfJJl ~111'1 ~t!O


111001010

I ott 10 1 00
,
.....
JUJNGIE J~~mp 0t1 LH$/NOt a-t lott1t100
orf(ll.;81
JUIJNO Jun'oll on '-"t 01 ECIU'it
Gto
Mol;
J.,JNM Nolp hlow.M:II
01> ~
lo t tttllo

l ot~tOoto
......
Mf -
.........
JlfJJH.A Jump "" 8alcwrt 01 f(Wati

JI"UPe AriP on P~tytWtl


01 110 l10 ll.p

01111010
""'
....
JO JUMP Cl!l 0...,_.

Jl Jut!IP on SII;J'I
01110000
011 11 0 00
-""
JNEJ.INZ .Aifl'lll MHCil C)ullllttll

JHV.ICC "~
Nqt on Nol tM~~o'G~aler

~-
011 U101

0111tl01

JNLEI.IG NIP!p 111'1 HOI~~ 01 EQII... 011111H --...


-...
"'-
Jlf&IJAI! J..-.010 tfOI ~ 011t0011

~-
Jlllll/JA Jlrp Ql! Nol hlo- Of 01110,1

--...
EQI.IIIi'A bo.,..
JHI'fJf'O ~on Nol P,<P OciCI 0111 1011

JHO -"'"P on Hl;ll o..trow 01110001

JNI ~on NO! SiQn OUIIOOI

...
---
LOOI" LOOP X Tmn 11100010

LOOPZ/l.OOPe LOOP Whit Z~

LOOI'NlA.OOHif: LOOCIWNt Not

JIQCZ ""'*"P on ex z-
1 11 00001

1 l1000 00
1 1100011 -...
,._
INT I' * " " "
,..
,., 1 1100110 1 1
1 1 1001100 1
INTO 1flllon\.4ll ot1 o..rtll)w l t 10011tO !
tftiT "*""" ltiMunot l tt 0 0 1 11 t l

Copyrighted material
A l

.. .........
MOCQICIIR CC*I AOi. JI U U U nu n u
CLC C...CM\o tt tttuo i
Cllt Col~~ Ceny ttt to t ot!
lTC Soli CltiY tt t noo 1)
CUIC...~ IUt!UO J

ITO SII~ tl 11 11 0,j

CU O.er ln'-'P! tl 1 11010

ITI k~ l!1t 1 0n

Hl.T Hill 1tti0\00

WNT -W * 100 ttO;t

eiC E~IIOblorNf~l 1 1011 MOdl(l( -1


U)C:I( . . . l* ...... " 11 0000

l:ll:ll:l

Copyrighted material
.Mlaropi'G-Ion end ~ a.fKing Bl r>
'
- ... ~ , Appendix a
-
ma llllc Oee u lptlcM ~cyctee Number of Page No.
byiH

ON . 2,. .. .
Unligned-
8-bil,...,
18-l>llrogi~W
80-90
1-162 2 '
"'
8-l>ii"*""'Y (8&-96) + EA .;2-4
1 - motnOIY (150-168) + EA -2-4
<"

uc Eocljle 203
Regioter 2 )1 -~ ~ . .'
. ~ 8 + EA
..
2-4
Hl.T ...... 2 '- - 202

IDlY Integer divilion


.. ' v
189
&-bit regiaktf 101-112 l')fl
16-blt.,_r
8--bit memory
16~ 184
(107-118) + EA
2
" 2-4 .
'
18-bll """""'Y (171-190) + EA 2-4
IIIUL lnleglr multiplicatjon '
,, 188
&-bi1 rogls1or 80-98 2
16-bil rog- 128-154 2 . ,.
(8&-104) + EA 2~ ., ..
- ...mory

.. 18-tMt memory
lnpu1 from 110 pori
FII<Od pori
(IU-180) + EA

10 .
""'
2
1
2-4
180

V.:l- pori 8
IIIC incremetllb'( 1
16-bit registlf 2
----
..1...
181
'
8-bll rog;oler . 3 2
Memory
- 15 + EA 24 ,.
MY lntenupt
- ' 20(
Type3 52 1
Type.l 51 2
*YO ln'-'Up< W - 1 . 20(
lnterrupl io taken
. 53 . --- -
lnWNPC il not taken 4
": ...
ltET Retum from interrupt 24
"
20(

..
-
JN Jump if aboYW 16/4 2 200

Jump if not below or equal 200

Copyrighted material
Microprocessors and Interfacing B -4

Mnemonic: , Desc:ttption Cloek,.c:yels Number P age Not!


of bytes

JA1 Jump If 3b0ve or eQv&V 16/4 2 200


JNBI Jump if nol below/ 200
JNC Jump if nol cany 200

JB/ Jump if belowi 16/4 2 200


JNAE/ Jump if not above or equaU 200

JC Jump if carry 200

JBEI Jt,~mp if below or equafl 16/4 2 200


JNA Jump if not above 200

JCXZ Jump if ex is zero 1816 2 200.


~
JE/ Jump if equal! 16/4 2 201
.
JZ Jump if zero 200
JG/ Jump If gteater/ 16/4 2 200

JNLE Jump if not I&M 01' ectual 200


JGE/ Jump tf greater or equaif 16/4 2 200
JNL Jump if no! Jess 200

JL/ Jump if 5essl 16/4 2 200
JNGE Jump if no! greater or eQual 200
.
JLEI Jump if less or equaV 16/4 2 200
JNG Jump if no1 greater

200
JMP Jump . 199
lntrasegmenl direct shOrt
rnvasegmen1 direct
15
15
2 .....
3
lnterscgmenl direct 15 5
lnttasegmcnl _..direct through memory 18 + EA 2-4

lntrasegment
lnlersegment
indirect through register
indirect
II
24 + EA
' 2
2-4
JNE/ Jump if not equal/ 16/4 2 2op
JNZ Jump f not zero - - - 200-

Copyrighted material

........
lllcnopnlceMors ancllm.rtKiftt
_.,.... ..
-
Appendix

lllnemonlc . Do_...... 1'8pNo.

IIIOV Move
of """ 171
Accumulator to memory 10 3
~"to aoc~.mUIItor 10 3
RogitiO< 10 rogiiiO< 2 2
Mti\'Q'YIOregl- 8 EA 2-4
Regis& to memory D + EA 24
Immediate to regia.ter 4 2-3
lmmedi.... 10 memory 10 + EA :HI
Roglslet 10 SS. DS. "' ES 2 2
Momc.y 10 SS. OS. 0t ES 8 EA 2-4 -
S!!!troen ~ oo rog~,.., 2 2
Segment tegiltlf to memory D EA 2-4

IIOVII Maw'Cttrif9 1 205


-
IIIOVIIII ;: byle otringr
. Maw 205

MOYSW ~ . 11ring
205
Not~ 18

9 + 11Jtep
11M. ~- mulliplieallon 117
8-bll regil1er 7().77 2
16-bit;~ilter
8-bii"~!QVY
118-133
(76-83) EA
2
2-4
.
16-bh ""'mory (124-138) EA 2-4
NEG Negale
i ..
115
Reg-.r 3 2
Mem~>iY'" 16 + EA 24
NOf' No operation 3 1 :104
NOT Logicol NpT 1t1
Roglolo< 3 2
Mtmo<y
: .
Logiall OR
. 18 + EA 2-4
OR 1t1
~ilti, regllllr 3 2
Mlmoty .to register 9 EA 2-4
Regi&W' to rnerr101Y 16 + EA 2-4
Immediate to IICCI.WftUIIIor 4 2-3
lmmedWe to register 4 3-4
lmmedi8tit to memory .. . . '
17 + EA . :HI

~-

Copyrighted material

I

MICrupNIIIIIDI'S Mil '"llrfiiCI. . .. ,. _.,.... ......


Applftlll
., .........
.
' ,.....c DMDriJMIR
........ .

- .
~.og~eo~.-OR
Roglllotwllh . . . . .
Memory wllh ,.ai.. IJ'
RegisW wtlh nwmory
3
8 + EA
18 + EA
2
2-<1
'2-<1
.
-
lnllnedt...... IIC:C:UrftUIMDr
2-3
,, lmmtdillllt wilh ~-.,
lniR'..ctl wtlh ,.,.,..'1 17 + EA
3-<1
3-e
.- I 1
tliJtl

Copyrighted material
Microprocessors and Interfacing C-2 Appendix- C

If address is not spt.-x-ified, the IOGltion begins whe.re the last D command efrot: or ,lt
locati(~n DS:O if the oon"'mnn.d us being typed for the first time. An address m'ons1st of
a segment-offset address or JUSt a n offset :
D 6000:() (segment-offset)
.;.t
c .
-,,<"
),.,
!li tlr> >; ES:2001
. -
.1' (segment register-offset)
"" ~ ,W\L- ~ ,.. ,.,;=,.(offse t)
The defauJt segment is OS. so it is not nect-'SSary to specify segment
dump an offset from another 5eb'1l1ent location.
A range m.1y be given. tehing DEBUG to dump all bytes ~ithin the range :
D 100 200 ; Dump 0 5:0100 through 0200
Other segment regis ters or absolute addresses may be used, as shown in the fo llowing
examples.
Examples

I. D Dump 1~8 bytes fTOm the last referenced location.


2. 0 SS:OA Dump the byt<"S at offsets ~A from SS.
3. D 300:0 Dump 128 bytes at offset :z.ero from segment 0300h.
..., .. .... ,_.
4. D 0 200 Dump offset 0-200 from OS.
5. 0 100 L 20 Dump 20th bytes, s tarting at offset lOOh from OS.

E (Etter)
The E command places indivictual bytes in memory. We must supply a starting
memory locat1on where the values will be stored. U only an o((set value is entered, the
oHset is as..~umed to be from OS. Otherwise, a 32-bit address may be entered, or another
segment register may be used. The syntax is :
E address Enter new byte value at address

E address (list) Replace the contents of memory storting at
,, ..the,' ...
specified address with the values contained
..
in the list.
\J.
To begin entering hexadecimal or choracter data a t 05:200, type, Ji.200. Press the space
bar to advance to the neXt byte, and press ENTER to s top. To enter a string into memory
starling at location CS:200, type E CS:200 "This is a string". r~lttl.-1 ~

' ~ I" ..,


! .

Copyrighted material
Microprocessors and.Interfaci ng C-3 .
F (Fill) :..1~.~ , '
The F command fills a range of memory with a single value or a list of values. The
range must be spcd.fied as two offset addns.~cos or segme:ntoffset addresses: The syntax is :
F range list

Examples
1. F 100-200, ' ' Fill with spaces.
2. F CS:0100 CS:0200, FF Fill with hex OFF.
3.F200L30'A' Fill 30 hex bytos with the letter
'A', starting at location 200.

'
G (hecate)
The G command executes the program in the memory. We can specify a starting
address and a breakpoint. causing the program to sto~ at a given add!'e55. The syntax is :
G [= startaddress) brkptaddress [brkptaddress ... )
JJ no breakpoint is specified, the program runs until it stops by itself and returns to
DEBUG. Up to 10 breakpoints m"y be specified.

Examples
t.G Execute from IP to the end of. the program.
2. G tOO Exe<Ute from the lP to CS:1 OOh and stop.
3. G = 100 500 Begin execution at offset 1001\ and stop before
the instruction at offset 5001\

H (Henrithmetlc) ,, -; ._
The H cqmmand perfonns addition and subtraction on two hexadecimal numbers,
entered in the following syntax :
H valuel valuc2
\
Example
I ' ..
H 10 20 Hexadecimal values 10 and 20 are added and subtTacted
I
0030 0010 <- displayed by Debugger
I
I
I
Copyrighted material
Hidden page
Mlcroprocnso,.. and Interfacing C-6 Appendix C

T (Tract )
The T command executes one or more instruc~ons from the current CS:IP location or
an optional address, if specified. The contents of the registers are shown after each
instn1ction is exect1ted. The syntax is : -..v.- N.

T (= address) (, value) -'.

Examples

I. T
.
Trace one instruction from the current location
2. T 5 T race five ins tructions.
3. T = 5, 10 Start tracing at eS:5, and trace the next 16 s teps.
This command traces individual loop i!erations, so we can use it to debug statements
within a loop. Also, the T command traces into procedure calls, whereas the P command
executes a procedure caU in its entirely withotlt tracing.

U (Uausemble)
The U command translates memory into assembly language mnemonics. This is called
unasscmbling or disassembHng memory. If we don't specify an address, debugger
disassembles from the location where the last U command is left off. If the command is
used fo r the first time aJter loading debugger, memory is disassembled from location CS :
100. The syntax is :
Syntax I : U (address)
Syntax 2 : U (range)

Eumples
i. U Unassemble the next 32 bytes from the current location.
2. u0 Unassemble 32 bytes from location 0.
3. u 100, 200 Unassemble all bytos from offset 100h200h.

W (Write)
The W command writes a block of memory to a file or to individua l d is k sectors. If we
want to write to a file, it must first be initialized with the N command . (If the file was just
loaded either on the DOS command line or with the Load command, we do not need to
repeat the Name command.)
Place the number of bytes to be written in BX and ex (BX contains the high 16 bits,
.tnd CX cont3ins the tow 16 bits). If a fi le is 256 bytes long, for example, the BX and CX
registers will contain the following :
ax = oooo e x = 0100

Copyrighted material
MicroprocHsors and Interfacing C7 Appendix C

Exmples
I. N MYFILE.COM lnitiali1.e the filen.am~ MYFILE.COM
on the default drive.
2. RCX 20 Set the ex register to 20h, the length of the file.
3. w Write 20h bytes to the file, s tarting at CS : 100.
4. wo Write from location CS : 0 to the file.
aaa

Copyrighted material
Microprocessors
& Interfacing

~ Chapterwise University Questions with Answers

(P - 1)

Copyrighted material
8086 Instruction Set and
Assembly Language Programminl

Q.l DiS<:u:;s l~1rious brnuch i11Stmctiou of 8086 micrtJprqce$:i(Jr, thnt are u.;.eful for
re/ocntio11. 1Aprii!May-21Y.J5, Sel-l, 8 Marks; Aprii/May-2006, Set-1, 8 Marksf
Ans. : Refer section 3.7.
Q.2 It is 11eressary to cherk w/ret/r.r the word >tdrcd in location 4(}()()H: A(}()()H is posiliVt'
mm1btr of not. Sholl/ all p()SSible Wily$ of lestiug the above condition aud store 001-1 if
lhe condition is ::atisfied ;, location 3000: 2002. Otl1erwi~ store OFFH.
IAprii/May-2005, Set-2, 16 Marksl
Ans. : Rcit"'r program 12 in chapte r 4.
Q .3 Distinguish l~tween iuter~segmeut aud iutra ~stgmmt CALL instructions smd explain
willl txnmplc'S !tow they an~ executed. (Aprii/May2005, Set2, 8 Mark.i )
Ans. : Rdc.r st"Ction 3.7.1.
Q .-l Gi;tr. d umt flow chart mul lht corrtsJ'cmdiug 80d6 assembly lauguagt' program for
J'l'fformiug bubble sort ;, m; array of N tltmmts of 4--digit Htx number.
[Aprii/May-2005, Set-2, Set-3, 8 Ma rks]
Ans. : R(f..:r p rograr.1 l 9 :n ch aprer 4. '
Q.S What is a procedure ? Hqzv is a procedure idt!ntified as nmr or Jar ?
IAprii/May-2005, Set_., 8 Marksf
Ans.: Keicr St.-<:tion 3.17.
Q.6 D1scus.s the importanu of proc.,"'tfures in assembly language programming.
(NovJDec.-2005, Set-!. 8 Marks!
Ans. : Rek>r section 3.17
Q.7 Wl~t~l l:i- ,, rtrur:;ir't' pr(J(t'dur~ ? Writf' a recursive procedure to calulalf the factorial of
tmmbtr N, when N is 11 two-digit Hex rrumber.
(NovJDec.-2005, Set-2, Set-4, 8 Marks]
Ans. : Rd..-r prog:r.lm 5 of chapter 4.

(P 4)

Copyrighted material
Microprocessors and Interfacing f P-5
' .
8086 Instruction Set and ALP

Q.8 Wlrat are tire loop instructions of8086 ? Explllin tire u& of DF flag in tlr. execution
of string instmctions. (NovJOec.-2005, Set-2, 8 Marks)
Ans. : Refer se.-tions 3.8 and 3.6.
Q. 9 What ;nstruction set support is providtd in 8086 ? {NovJOec.-2005, Set-2,. 4 Marks)
Ans. : Refer section 3.3.
Q.lO Ot'Vt!lop a far procedure declared as PUBLIC to convert a 4-digit BCD mtml>r to its
equivalent ht'x nllmber. [Nov./0.-2005, Set-3, 8 Marks)
Ans. : Rcfe.r program 13 of chapter 13.
Q .ll Giw tlrPassembly lmrguage implementation of tire following.
i) DO WHILE ii) FOR (NovJOec.-2005, Set-4, 8 Marks)
Ans. : i) DO WHILE

DO WHILE

Statementfs label :
::::::: } lnsttuc:tiOns
...... .
.......
Compare instruction
Yes J conditional instruction
if condition is tr\le goc.o Label
OthervMe exit loop

Fig. 1

'

Copyrighted material
Microprocessors and Interfacing P-6 8086 Instruction Set and ALP
iil FOR

FOR
Assembly Implementation
Initialization or
variable with initial count
Initialize Register with
Jnlt1al value. FOt example,
MOV CX. 0020H
Label : Compare registor value
with final vatoe. For example,
CMP CX,OG40H

tf ex = 0040H exit
For example, JE exrr
OU\etwi&e continue

Update variable :.< }~cl~s


Update register value
For example, INC ex

GO BACK. For example,


JMP label

Fig. 2
Q.12 Explaitr /row !RET instruction is executed ? (NovJ Dec.-2005, Set-4, 8 Marks )
Ans. : Refer section 3.1 1.
Q.13 Using a do-while construct, develop a sequence of 8086 inslntelions tl111t reads a
cllnrncler string from tht kcybonrd and after prtsSing the enter key tire charactn- string
is to be displayed again. [April/May-2006, Set-1, 8 Marks]
Ans.:
model small
stack 100
dat a
msl db 10 , 13 , ' Enter tho st r ing S
buff db 80 dupl$ )

cod e

s t ar t : mov ax , @da t a ; ! l oads the address of


mov ds , a x ; data segment in OS )
lea b x, b uff ; get t he address of buffer
leo dx, msl d ispla y the message

Copyrighted material
Microprocessors and Interfacing P-7 8086 Instruction Set and ALP
mov ah , 09H
i n t 21 H
back mov ah , 0 1 ; Read character
i n t 21 H
mov ( BX) , AL ; Save the chatilcter
inc BX Increment pointer
cmp AL, 13 ; Chec k i f i t >S ente r
jnz back I f not read next character
lea d x, bu ff Display the strinq
mov ah, 09H
int 2lh
mov a h , 4c h; (Ex i t to
i nt 2 l h ; DOS)

end s t.a r t.
/ e nd
Q.14 Discuss tilt' addressing modes prDVidt~ by 8086 and txplain tuitlr examples.
[ApriiiMay-2006, Set-2, 8 Marks)
Ans. : Refer se<:tion 3.2.
Q.lS It is neC<'ssary to define a block of data in 8086 assemble languagr program. The
lmgth of the block is 80,(}()(} Bytes. Ciw the initialization of data segment for the
abow data. It is nec=ry to excla11ge second element and 7001JCi element in the
abcrve. Glue the sequence of instructions to perform the above operation.
[ApriliMay-2006, Set-2, 16 Marks)
Ans.:
mode l l a rge
da ta s e gment
bu f f db 65535 dupo
data ends

da tal segment
buf f! db 14465 dup 0
dat al ends

code segment
assume cs code, ds data

Copyrighted material
Microprocessors and lnterfaclr/9_.~1_
' _ ___,Pc...::.-,8_ __ ____,80~86~1:!!n.!.st,r,u~etl,;o!!n~Se~t!!an,_,d"-'=ALP=

StaTt : mov e~x , data ; (Initialize


mov ds , a x ; data segment l
lea bx , buff ; get the addr ess of buff
m<>v CL , (bx + l I ; get data

mov a x, datal ; {In itialize


mov ds , ax ; datal segment }
lea bx, buff! ; get the address of boffl
mov si , 446~ ; load offset
rnov ch, { b x Ysi} ; get data
mov !b x ~ si) , cl ; store data
mov a x, data ; (Initialize
rnov ds, ax ; data segrr.ent 1
lea b x, buff ; get the address of buff
mov ( b x +l) , ch ; s tore data

mov ah, 4CH ; [Terminate to


int 2 t H ; COS)
cede ends
end sta rt
Q.t6 Explain tire u~ of nddrc.ssing mode. It is ucct>Ssary to move a byte from location
4000H : 2()()()H to 4000H : 2005H. Givt all possiblr methods llSing 8086 addressing
modes. (April/May-2006, Set-3, 8 Marks]
Ans. : Refer section 3.2.
Q.17 Explain in detail the coding template for 8086 MOV instructiun.
(April/May-2006, Set-3, 8 Marks]
Ans. : Refer section 3.19.
Q.18 It is necessary to declare a program as a public procedurt to be accessible by other
programs. Giw tlze sequ~nce of assembly lnngunge statemmts. An external program
called 'facr is to used in this program. Show the req11irtd statements.
(April/May-2006, Set-3, 8 Marks]
Ans. : Refer section 3.12.3.

Copyrighted material
Micr oprocessors and Interfacing p.g 8086 Instruction Set and ALP

Q .19 It is "'-'CtsSllry to check whttlrer the rvord stored ;n location 3000H : 2000H ;s uro or
not. Shotv all po$$ible Wb)!S of trsting the abo"" condition using different addmsing
modes and stort> OFFH if tJre condiUou is sntisfied hr location 3000H : 2002H.
Otllmvise store OOH. [Aprii/May-2006, Set-4, 16 Marks)
Ans. : Refer section 3.2.
[J[J[J

Copyrighted material
Assembly Language Programs

Q .l Detelop n11 8086 t1SSembly language program Orat will determine if a given SllfJ..Siriug
i$ prt!Sent or not i11 t1 mnin string of characters. Place tire result as 'P' if present else
plnct 'N' iu memory loc.atio11 'rt!Su/1'. (ApriUMay200S, Set-4, 8 Marks)
Ans. : Refer prog:ram 18.
Q.2 Using OF flag and string instrucfi(mS, write mr u$S('mbly langungt program to moue
n block of data of length N from source to dt'Siirration. Assumt' all possible conditions.
INovJOec.-2005, Set-1, 8 Mark.<I
Ans. : Refer program 1L
Q.J Dnoelop a near procedure lo find lite CCD of two numbers of 2-digil Hex. Use litis
proadnre to finci lite GCD of IIITt'e 1111mbers. INovJOec.-2005, set-3, 8 Marks I
Ans. : Re fer program 22.
DDCJ

(P -10)
Copyrighted material
Microprocessors and Interfacing p -12 8086 System Config.,ration

110 Map :

SHe .... A,, ":l .... A,, .... Ag Ao A, ... ... A, A, A, ... Ao HEX
&ddress
VO O~Ice

1 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 OFOOH 1-<lata

1 0 0 0 0 1 1 1 1 0 0 0 0 0 0 1 0 OF02H 1status

0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 1 OF01H 2-data

0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 1 1 OF03H 2-smtus
1 0 0 0 0 1 1 1 1 0 0 0 0 0 1 0 0 OF04H 3-<fa1a
1 0 0 0 0 1 1 1 1 0 0 0 0 0 1 1 0 OF06H 3status
0 0 0 0 0 1 1 I 1 0 0 0 0 0 1 0 1 OF05H 4-data

0 0 0 0 0 1 1 1 1 0 0 0 0 0 1 1 1 OF07H 4status
'
1 0 0 0 0 1 1 1 1 0 0 0 0 1 0 0 0 OF06H 5-data

1 0 0 0 0 1 1 1 1 0 0 0 0 1 0 1 0 OFOAH ~status

Instruction sequence to read and store status of each l/0 device


MOV OX, OF02 il
IN AL. OX Read status 1
MOV LOCI , AL ; Store it
MOV ox, 0 F03H
IN A[., ox Read status 2
MOV LOC2, AL Store it
MOV ox. OF06H
t N Jo.L, ox Read status 3
MOV t.OC3, AL Stote it
MOV ox. OF07H
IN i\L , ox ; Read status 4
MOV LOC4 , A[. ; Stote it
mv ox. O>' OAII
IN AL, ox ; R&ad sta tus 5
MOV LOCS , AL ; Store it
Q. 3 /11 a homt PC ruith 8088 processor, SRAM is 1rom OOOOOH an. EPROM
providtt~
mds tvith the address af FFFFFH. 171t capacity of SRAM is 256 KB ,md thnt of
EPROM is 32 KB. All tirP chips art of siu 32 KB. Civt tl" address map for
individual t.l1ip and design 'tlze complet~ mtmory intt"rjac~. 11

(Aprii/May-2005, Set-2, 16 Marks]


Ans. : Refe.r section 5.10.

Copyrighted material
MlcroproceHora and Interfacing p -13 10116 Systam Confil!llration

Q. 4 Describe the function of the fo//()wing pins and their use in 8086 bastd system.
a) NMI b) WCK c) TEST d) RESET. (April/May-2005, Set-4, 16 Marks)
Ans. : Refer section 5.2.
Q. 5 ~be the futrclion of tire following pins in 8086 maximum modo of operation.
(a) TEST

(b) RQ,cT0 and RQ,CT1


(c) QS0 and QS 1
(d) s. s,,s, [NovJDec.-2005, Set-1, 16 Marks)
Ans. : Refer Stion 5.2.
Q. 6 Witlt a sk<lclt explam 74LSI38 decoder am/ its 11~. (NovJOec.-2005, Setl, 8 Marks)
Ans.:

r Ya
Ao v,
3 inputS { A,
3:8
v,
"' Decoder
7US1$8
v,
v,
v,
Acelve hiGh enable e,
~.
v,
Ac!M>IOw {
enabht $lgn8IS E, v,
GNO
. j_

Fig. 2
The IC 74LSJ38 is a 3 : 8 decoder. It ru.s 3 input lines (select lines), 8 output lines
(Active low) and three enable signals : E1 , E2 and E3 To make decoder
active 3 should be high, and E1 and E2 should be low. Once 74LSI38 is enabled,
according to the inputs A 0 , A 1 and A 2 one of the output pin is activated.

Copyrighted material
Microprocessors and Interfacing p -14 8086 System Configuration

Function Table of 74LS138 :

INPUTS OUTPUTS

E, e. e, Ao A, A, 0 1 2 3 4 5 6 7

H X X X X X H H H H H H H H
X H X X X X H H H H H H H H
X X L X X X H H H H H H H H
L L H L L L L H H H H H H H
L L H H L L H L H H H H H H
L L H L H L H H L H H H H H
L L H H H L H H H L H H H H
L L H L L H H H H H L H H H
L L H H L H H H H H H L H H
L L H L H H H H H H H H L H
L L H H H H H H H H H H H L

The 74LS138 decoder is used fo r generating chip select signals by decoding the
address.
Q. 7 C~nerate chip sdL>ct siguals wit11 tile llrlp of 74LS138 to six memory cl1ips of siu
16 kB, witlr II" addms map from OOOOOH to 17FFFH.
INo vJ Dcc.-2005, S<t-1, 8 Mark&)
Ans. : The 16 kB memory requires 2a address lines, i.e. A 0 - A 13 The remaining
address lines are used as a~decoder input.

Yo
Ao CSotochipO
v, cs, to <hlp 1
A,
3 :8
v. CS to <hlp 2
A,
Oecodtf v, cs,2 to <hlp 3
74LS138 v, cs,. to chip 4
-t>- ,E3 Ys
CSs to chip s

E,

Fig. 3

Copyrighted material
Mic,roprocessors and Interfacing p -16 8086 System Configuration

Q. 10 A lnrgd systrm based on 8086 processor uses less amount of SRAM. Tire programs
art' stomf in EPROM tllat stnrls from F()()()()H ends witll f),. a.tdress of FFFFFH.
Tire capacity of SRAM is 8 KB int"fnwt nddress OOQOOH. Tl.r cllip siu is 8 KB for
PROM nnd St~AM. Sllow tile compiete memory interface.
INovJDcc.2005, Set-2. 16 Marks)
Ans. : KcfL"r section 5.10.
Q. 11 Wlmt is fJ~e purpose of ALE, BHE. DTiR nnd DEN pins of 8086 ? Show their timing
in tile system bus cycle of8086 . )NovJDec.-2005, Set-3, 8 Marks)
Ans. : Refer section 5.2.
Q. 12 Wiry 8086 mtmory is mapped into 2 byte wide banks ? Wllnt losic h.,..ls are found
with BH and AO tvht>ll 8C86 rrods n word fro, the> addrt.'SS OAOAH ?
)NovJDec.-2005, SetJ, 8 Marks ; ApriUMay-2006, Set-1, Set-4, 8 Marks)
Ans. : Refer se<:tion 5.3.
Q. 13 DistinguisJr bt'tnJt'e11 a memory read and write maclliue c-ycle. Draw tire timing
dingrams i11 minimum ;md maximum modes of Opt.'T'ntion.
(Nov./Dec.-2005, Set-4, 16 Marks)
Ans. : Refer S<.><:tion 5.6.3.
Q. 14 /11 an SDK-86 kit !28 KB SRAM and 64 KB F.PROM is prm>ioied on system aud
provisiou for t>xpausiou of anol-hlr 128 KB SRAM is siveu. Tire 011 system SRAM
address starts from OOOOOH mrd flint of EPROM mds with FFFFFH. Tlrt expansion
slot address map is from 8()()001-1 to 9PFFFH. Tl~t siu of SRAM cltip is 64 KB.
EPROM chip siu is 16 KB. Give til~ cvmplrtf mt!mory iuterfirce nud also tile addn!-SS
map for individual clrip:;. (NovJDec.-2005, Set-4, 16 Marks)
Ans. : Please ref!![ Fig. 5 on next page.
Memory map:

-- .... ............ .... .... .... .... A., "'' "' A, A,


1
1
1
1
1
1
.I
r
I

I
1
1
0
I
0
I
0
I
0
I
0
I
0
1
0
1
0
1
0
1
.. ... ... .., ... ... ......... .........
0
1
0
1
0
1
0
1
0
r
"''
0 f8000H
-
0 FFFFEH EAAOMr
0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 F8001H O<ld
0 1 1 r 1 1 0 0 0 r 1 1 1 1 1 1 . 1 1 1 1 1 FaFFFH EPROM2
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 OOOOClli e....
1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 OFFFEH RAM1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 00001H O<ld
0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 OFFFFH IW.I2
1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 llOOOIIH .....
1 I 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 8FFFEH IW.I2
0
0
1
1
0
0
0
0
0
0
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
r
0
1
0
I
0
1
0
1
0
1
1 80001H
1 8FFFFH RAM2"""
Copyrighted material
Microprocessors and Interfacing p 11 808E System Configuration

'

I~
i
~~ro
.! A
11! ,....,
~
~
I~ ~<

'~~ro
'l. A
~

~
Ill
Q

I~ ,...., ,....,
L
:
~
'<
$ ~ ltl
Ill
A !
~
,...., 8

~

15
{
< '-
,....,
}w~ 1!1
L

I~
A
,...,
~ >.

,Jlo- .;
i
,,. ~ ,l!o. ~~
UJ u l ow
a ..-
<m<>
<I(GIOO

-y,,
II I
~
I
-1<1-0% I
iO I~ Ill~ I I-,.- ' ~ ~ ~ ,~
<<<< ID

.. II J1- U1-1 1~
~ I- ._
Fig. 5
Copyrighted material
Direct Memory Access
(DMA)- 8237/8257

Q. 1 Explain demand trnlisfer mode and block trnnsfer mode of 8237.


[Nov./Dec.-2005, Set-1, Set-3, Set-4, 6 Marks!
Ans. : Refer section 6.9.
Q. 2 Slunu how 8237's are cascaded to provide mort number of DRQ's and explai11 the
operation. [NovJDe<:.-2005, Set-1, Set-J,Set-4, 6 Marks!
Ans. : Refer section 6.9.
Q. 3 Explain how mellll)ry to memory transfer is performed with 8237.
[Nov./Dec.-2005, Set1, Set-3, Set-4, 4 Marks!
Ans. : Refer section 6.10.
Q. 4 Explai11 with a nl'llt sketch nil registers of 8237 and their use in DMA tr.,rsfer.
[Nov./Dec.-2005, Set-2. 16 Marks!
Ans. : Refer section 6.12.
Q. 5 Explain single trmrsfer mode and block transfer mode of 8237.
[April/May-2006, Set-2. 16 Marks!
Ans. : Refer section 6.9.
Q. 6 With a tl(tl/ sketch explain 8237 DMA controller a11d its applfcatjqn.
[Aprii/May-2006, Set-4, 8 Marks!
Ans. : Refer sections 6.9 and 6.1.
DOO

(P 19)

Copyrighted material
8255 PPI (Programmable
Peripheral Interface)
. .
Q. 1 Explain how to interfn~ a stepptr mQtor with 4 step input stquen~ to 8086 bastd
system witl1 the lwlp of hardware design. Write the instruction sequen~ to move the
stepper motor 10 steps i11 clockwise tmd 12 steps in anti-clockwise direction.
[ApriiiM;oy-2005, Set-1, 16 Marks]
And. : Refer section 7.12.
Q. 2 Explain why 8255 ports are divided inl<> two groups. Discuss how these groups are
controlled in different modes of operation. Explain diffrrent control signals and their
associated pins for ui-directional 110 mode of operation.
(April/Moy-2005, Set-2, 16 Marks; NovJDec.-2005, Set..J, 16 Marks ;
April/May-2006, SetI, Set:Z. 8 Marks]
And. : Refer section 7.4.
Q. 3 lnterfnet :. 12-bit DAC to 8255 with an address map of OCOOH to OC03H. Tht DAC
provide-s output in th~ range of+ 5 V to - 5 V. Write the instruction sequence.
(a) For generating a square wave with a peak to peak voltage of 4V and the frequency
will be stltv:ted from memory location 'F'.
(b) For generating c triangulnr wave with a maximum voltage of + 3V and n
minimum of- 2 V. [Nov.!Oec. 2005, Set-1, 16 Marks)
Ans. :
Interface :
Please refer Fig. 1 on next page.
JOV
Resolution =
2 12 - I
= 2.442 mV

(P 20)

Copyrighted material
Mlcooprocesoors - ~lllorfacina P 21 1255 PPI (PfO!!!'!!I!INible P!!'!p!!!nll lntofface)

IIOo
AD
7
(
ADo
AD,
IPAo
PA7 -
MEMR - PBo

-
RD
I
MEMW ViR 2 DAC v.,..
5 P83
Reset Out Reset
5
PC0 Latch
Ao Ao
A, A,
cs

~
4/
")
.

Fig. 1

Dlgltol d.,. Equlvolont Anolog Output Voltage

OOOH - 5V

FFFH +5V

7FFH ov -
4CCH -2V
..
CCCH 3V

E65H 4V
19AH - 4V

a) Generating square wave :


LXI SP,27FFH ; Initialize s t a c k pointer
MVI A, SOH ; I nitial i ze 8255 to configure
STA OC03H ; PA, PB and PC as output

Loop MVI A, 9AH ; Load and send diqital data


STA OCOOH 1 corre~ponds t o -4V

Copyrighted material
Mleroproceyors and Interfacing P- 22 8a55 P~ (f!!oJ!rsmmable Perlptl!rallnterlaee)
MVI
" OIH --~ -- -
STA OCOlH
MV! A, OIH ; Enab l~ latch signal
S'l'A OC02H
NOP '
MVIA, OOH
STA 0C02H
CAl.L Delay wait for OFF period
MVI A, 65 H Load and send digital data
STA OCOOH corresponds to + 4 V
MVI A, OEH
STA OCOl H
HV! A, OIH ; Enable latch siqnal
STA 0C02H
NOP

MVI A, DOH
STA OC02H
CALL Delay ; Wait f o r ON p~riod

JMPLOOP : 'Repeat

Delay LOA 'F' ; Read the delay count wh ich i s


.. i nvers ely proportional to frequency
BACK OCR A ; Decrement count
JNZ BACK ; Chec k i f count = 0; otheno'ise repeat
RET ; Return to ma i n p rogram
b) Generating T riangular Wave :
LXI SP , 27 FFH ; Initial ize stac k pointer
MVI A, 80 H I nitialize 8255 to configure
STA OC03H ; PA, PB and PC as output

BACK : LXI H, 04CCH Load and send digital data


C,,."
LOOP! : SHLD OCOOH ; correspond to - 2v
CALL LATCH
INX H ; Increment diqital data

Copyrighted material
Mlcroprocnaon nd lnt.rfac:lng P 23 8255 PPI (P!'Oj!'!!!!!!!!blliPerifil'!rl lntert.c:e)
MOV A, L ; Check digital data foi pos itive
CP! CCH peak output (+3)
' JNZ LOOP!
MOV A, H
CP! OCH
JNZ LOOP!
LOOP2 : SHLD OCOOH ; Send digital data
CALL LATCH
DCX H Decrement di9ital data
MOV A, L ; Check digital data for negative
CP! CCH peak output (-2>
JNZ LOOP2
MOV A, H
CPI 04H
JNZ LOOP2
JMP BACK Repeat
LATCH : MVI A, OlH Enable l atch siqnal
STA 0C02H
NOP
MVI A, OOH
STA 0C02H
Q. 4 Write tile rzect'SSnry instruction sequrnce to inililllize 8255 rvitlt address OCOOH to
OC03H for flU! follmuing combinations.
a) Pori A as input port in mode 1 and port B as input port in mo,ie 1 without tire
interntpt driven 1/0.
b) Port A in modt 2 as output port and port B as iuput port iu mode 0 with
iuterrupt driven 1/0.
c) Port A in mode 0, port C upper lwlf as input ports and port 8 as input port in
m.ode 1 witiJ interrupt driven 1/0.
d) Port A as output port in mode I witlt activt intn-ntpt, port 8 as irrp11t port in
mode 0 and port C lowt'T lrnlf as output port in mode 0.
(Nov./Dec.-2005, Set-4, 16 Marks!
Ans. : Refer section 7.5.

Copyrighted material
MlcroprocHaors and Interfacing P 24 8255 PPI (Programmable Peripheral Interface)

Q. 5 It is Ut..'Cessnry to inilinliu interrupt for mode 1 operation of port -A as input and


port-8 as output in the same mode with tire 8255 address map of 04COH to 0700H.
Give t}u! compl('tc hnrd-ware dt"Sigu to interface 8255 to 8086 proct'SS<Jr witlt tltis
address map. Write lite iuslmclion sequence for lilt> iuitia/izntion of 8255 itt the above
modes. Give lite instruction sequence to change t11t operation modes of port A, port B,
pori C IC1ver-hnlf and port 8 to mode 0 input ports.
[ApriUMay-2006, Se t-4, 16 Marks)
Ans. : Refer sections 7.7 and 7.5.
- ot
000

".

'.

' ..
,-

Copyrighted material
Microprocessors-and Interfacing p - 26 8086 Interrupts

Q. 7 Addr.ss OOOEOH in the interrupt l'eclor table contains 4132H and address OOOE2H
cot~tains 0040H.

i) To wltnt interrupt type do these locntions correspond ?


ii) Whnl is the starting address for the interrupt service routine ?
[April/May - 2005, Set-3, Set-4, 4 Muk$)
Ans. : Interrupt vector Table :

,-_.
l ... l
OOOE3H OOH CS (High)

OOOE2H 40H CS (low)

aooe1H 41H 1P (High)

OOOEOH 32H IP (low)


0 L
"'f 'J
Fig. 1
i} lnterntpt type = E 0 H/4 = 224/4 = 56 in decimal
ii} CS = 0040H IP = 4132 H
oo4oUD
+ 4 13 2

Starting address of ISR = 0 4 5 3 2 H


Q. 8 What is tl~< purpose of operntional commtmd t<J()rd$ of 8259
? Explain their format
and the nsr. [Nov./Dec.-2005, Set-1, 8 Mark$)
Ans. : Refer section 8.5.5.
' :::(Hu
Q. 9 Wltat detailed ltardware and tltr associated algorithm, explain /tow a rMI time clock
tui/1 be implemented in an 8086 based system ? [Nov./Dec.-2005, Set-2, 16 Morksl
Ans. : Please refer Fig. 2 on next page.
t ~..
Algorithm (Initialization) :
I. Initialize clock i.e. HoutS, Minutes and Seconds.
,, ...
2. Load the address of ISR in interrupt vector table a t OOOSH.
. ''

Copyrighted material
MiC(Oprocessor:s and Interfacing p -27 ...,,..80861nterrupts

T '
39,pF 16 hi .. .
r
330K

"
10 ..
"
. ;[=
rJ '
32768 Hz 15MO
4060
3
a ,. Output frequency
2HZ
.' .
r-

'
n- "' ~F 11
8

J. Divide
by I-To NMI
2

Fig . 2
Algorithm (lntem.tpt service routine) :
1. Save registers.
2. Increment seconds.
3. If seconds = 60 , ake seconds = 0 and increment minutes.
4. If minutes :;; 60, ake minutes = 0 and increment hours.
5. If hours = 13, ake hours = 1.
6. Return to main program.
Q. 10 Write a11 initia/izntion S<'qllf.nce for an 8259 that is lilt 011/y 8259 in a11 8086 based
s_vstem, with n11 even addrrss of OFOH that wilt cauu.
a) Request to tire edge triggered motle
b) IR 0 r.,uest to a11 i11terrupt typo 30
c) SP/I?.N to output a disable signal to the data-bus trmtsceir,.rs "
d) The IMR to be cleared
t) Tht highest priority interrupt will be IR6. [NovJOec.-2005, Set-3, 16 Marks)
An$. : Refer section 8.5.5.
Q . 11 Draw the block diagram of 8259 and explai11 I'Jlch block ?
(Nov./Dec.-2005, Set-4. 8 Marks)
. .:.
Ans. : Refer section 8.5.2.
Q. 12 Under wlrat conditions type 0 interrupt is initiattd ? L1sl out the instructiOJJS that
may CllliSt type 0 intt rrupt. (April/May 2006, Set-1, Set-2.,Set-3, 6 Marks]
Ans. : Refer section 8.3.1.
Copyrighted material
Microprocessors and Interlacing p 28 8086 Interrupts

Q. 13 Explain tht foi/()U)ing tmns with refrmet to 8259.


(a) END of interrupt
(b) Automatic rotation
(C) Poll command
(d) Rend rttSisltr command [Aprii/May-2006, Set-4, 16 Marks!
Ans. : Refer section 8.5.4.
000

Copyrighted material
Serial Communication

Q. 1 Discuss the CQmmornl instruction ond Stotus register format of 8251.


(Aprii/May-2005, Sel-l , Set2, 8 Morksl
Ans. : Refer sections 10.4.4 and 10.4.5.
Q. 2 Drow the block diagram of 8251 and erplain each block.
(Aprii/May2005, Set3, 8 Marks!
Ans. : Refer section 10.4.3.
Q. 3 Draw th~ jlotuchart showing how synchronous serial data can be ~nt from a port line
11sing software routine. (Aprii/May-2005, Set3, 8 Marks!
Ans. : Refer section 10.4.6.
Q. 4 Discuss tltt st!rlal dnta transmission standnrds and tlJeir specifJCntions.
[Aprii/May-2005, Set-4, 8 Marks)
Ans. : Refer section I 0.5.
Q. 5 A lt>mlhral is transmitting asynchronous serial dntn nt 2400 bd. What is the bit time?
Assuming 7 data bits, a pnn'ty bit and 1 stop bit lrOtv long does it taU to transmit
one clmracttr ? (Aprii/Ma y-2005, Set-4, 8 Marks)
Ans. : Refer section 10.5.
Q. 6 Write tm initialization sequence to operntt 8251 in asynchronous mode with B~bil
chnmcter size, baud rate factor 64, tw() stop bits nnd odd parity tnnble. The 8251 is
interfoc<-d with 8086 nt address 082H. [Aprii/May-2006, Set-1, 8 Marks!
Ans. : Mode word for given specifica~on is as follows.

I I I o I 1 I 1 I 1 I 1 I 1 I =DFH
'-v-' ~....__.,_....., Baud rate
2 saop Odd Char&Cter factor 64
bils parity ltllglh
8 . bils

Fig. 1

(P- 29)

Copyrighted material
Mlcroprocessors and Interfacing p. 31 Serial Communication

Q. 10 Hotu do ""' """"'"t RS-232C equipm.,rt


i) To dntn ftrmiunl type dtuicts ?

ii) To serial port of SDK - 86, RS232C con/Jection ?


(Aprii/May-2006, Set-3, 10 Morks, Set-4, 8 Marks(
Ans. : Refer section 10.5.
Q. 11 Give tht specifications of RS-232C. [Aprii/May-2006, Set..J, 6 Marks)
Ans. : Refer se<:tion 10.5.
CICICI

'

Copyrighted material
8051 Microcontroller

Q. 1 Discuss t.he jollawing signal descriptions


i) INToflNTt ii) TXD

ii) T0 and T1 iii! RD [Aprii!May-2005, Set-1, 8 Marks]
Ans. : Refer section 11 .3. I.
Q. 2 Draw and discuss the fommts and bit dtfinitions of the following SFRs in 8051
micron trolltr.
iJ TMOD ii) PSW [Aprii!May-2005, Set-1, 8 Marks]
Ans. : Refer sections 11.7.2 and 1 1.3.6.3.
Q. 3 Draw and discuss tl~e formats and bit definitions of tire following SFR's in 8051
mlcrocontroller.
a) PSW b) IE c) SCON d) TMOD
[Aprii!May-2005, Set-2, 8 Muks ; Aprii!May-2006, Set-3, 8 Marks]
Ans.: Refer sections 11 .3.6.3, 11.9, 11.8 and 11.7.2.
Q. 4 Discuss the interrupt structure of 8051. Mention tire priority. Explain ltOtu least
priority is mad~ as JrighPSI priority. (Aprii/May2005, Set-3, 8 Marks ;
Nov.!Dec.-2005, Set-1, 8 Marks, ApriUMay-2006, Set-2, 8 Marks)
Ans. : Refer section 11.9.
.
Q. 5 Dnnu and discuss tire formals and bit definitions of the following SFR's in 8051
microcontroller.
a) IP b) TMOD cJ TCON d) SCON
(Aprii1May2005, Set-4, 16 Marks ; NovJDec.-2005, Set-2, 8 Marks]
Ans.: Refer sections 11.9.1, 11 .7.2 and 11.8.
Q. 6 Explain the alternate functions of Port 0, Port 2 and Port 3.
(NovJDec.-2005, Setl, 8 Marks ;
Nov./De<.-2005, Set3, 8 Marks ; Apr!UMay-2006, Set2, 8 Marks]
Ans. : Refer section 11.3.1.

(P 32)
Copyrighted material
Mlcroproceoso111 and lnterfaclng p 33 8051 Mlcroconlroller

Q. 7 Discuss tire following signal descriptions.


iJ ALf/PROC iii fA/V PP iii) PSN iv) RXD [Nov./Dec.-2005, SetZ, 8 Marks)
Ans. : Refer section 11.3.1 .
Q. 8 Discuss tlrt register set of MCS-51 family of microcontrollers.
[NovJDec.-2005, Set-3, 8 Marks)
Ans. : Refer section 11.3.6.
Q. 9 Discuss the following signal descriptions.
In) A LE/PROC (b) A/Vrr lcJ PSEN (d) RXD
(e) INT0/INT1 If) TXD lgJ T0 and T1 (lz) RD
[Aprii/May2006, Setl, 16 Marks]
Ans. : Refer section ll.3.1.
(J(J(J

Copyrighted material
Contents I
tv.OWS'\.... --~- ~ ~80616. Mlu"4*\)CiS'Q. Spec.1i~d,...... ~ ~ fDibllg
- ond ......... d,.,., . .
Add~llQ onortrt. oii'QHb ~ wt ~ AOS6 ~ dddlws llmpW ~' fl'nxerdum.. .net MIDot
~ ~ proq,llml lnYOII.ng liJglc:N ~and c.l ~,.. ~J ~iOn ot arrthmetlc
AJ)rtlt'aun,, 'Kring n'lciMII)UWtQn
P\t\ dla(Jri)M ~ ~Mu11mum tt'l~ af'd triMlffl'.ml rnodll ~ C'lpllftldon. Timing <hlli'.J"'" Memotv nt~dltCinQ co
W)661$ttJC" RAM Met EPROM., ~lid for DMA. DMA dolt;) trnnsfet mnhod. ln.,trl"n"''l ~llh ~7'8257

825tt PPt VMifA mcxW ol ()f'lf'TNinn '"ld i~r,cmg to 8086. lnww f<KIWJ "~ 01~. Stepper motor &nd
~te~\lolkltt. OA. m'ld AD tofMir1it intertac:tng.

lrtrrvP' ,trt,lt'llnit ofHON>, V11m int.mupt k1b1,t._ !Norupr .,.,_'k:~ tW.fM' lntn)(iu&-:-n m I~ lind BIOS in'bmuph
~ PK: Cllthl~ .nd ,.,iet~M'tng ~ng ol intlm'ui'lt tanlmlk!f Mid Mllmpol'llbfi(.O!

sm...t d.6t.t ...~ ..;Nmt_, M;"ndwoncus and Sl,ndu:oncJul cl.t;a ....... ~.,...,.,_ KlSl U'Wn' atdl-.lfrrft -
~nMt.:mg. m ~o A::; 2J2C and RS232C., T1_ coo.'ft'Sion. ~ PfUIItN'rl "' MW ct.. rrcn.kr. ll"'trcduC!on 10
~--~USB-
~~~~adl4a:w ....... wti1051 Nodttal~~l80ft..~t1Ul~~
~ol.,l ~aondlOinlilf.-:'19t;O)l

Fi rst Edition : 2009


Price I'iR 185/-
1\H\ 81-SHI-125- 7

---.- ...
I>H\ V l S-~1-8431-115-9

Technical Publications Pu ne
111, Amlt Rea,d e ncy, 412 Shaniwa r Peth, Pune 411030, M.S., India.
Te,efa.x t +91 (020) 24495496/97. Email: tchnlcai@Y1ubooke.com
V1sil us al www.vt.u books.com 4

Das könnte Ihnen auch gefallen