0% found this document useful (0 votes)
16 views

Microprocessor & interfacing

The document is a textbook titled 'Microprocessors and Interfacing: Programming and Hardware' by Douglas V. Hall, published by McGraw-Hill in 1986. It covers various aspects of microprocessors, including programming, interfacing, and hardware design, focusing primarily on the Intel 8086 family of microprocessors. The book is intended for students in electrical and electronic engineering programs, as well as industry professionals seeking to enhance their knowledge of microprocessor technology.

Uploaded by

shahriarabid54
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Microprocessor & interfacing

The document is a textbook titled 'Microprocessors and Interfacing: Programming and Hardware' by Douglas V. Hall, published by McGraw-Hill in 1986. It covers various aspects of microprocessors, including programming, interfacing, and hardware design, focusing primarily on the Intel 8086 family of microprocessors. The book is intended for students in electrical and electronic engineering programs, as well as industry professionals seeking to enhance their knowledge of microprocessor technology.

Uploaded by

shahriarabid54
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 568

DouglasV.

Hall
MICROPROCESSOR.
ANDINTERFACING
programming
andHardware

\ m

m2222*2222222 22-2-2."
Digitized by the Internet Archive
in 2010

http://www.archive.org/details/microprocessorsiOOhall
MICROPROCESSORS
AND INTERFACING
Programming and Hardware

Douglas V. Hall

Gregg Division
McGRAW-HILL BOOK COMPANY
New York Atlanta Dallas St. Louis San Francisco
Auckland Bogota Guatemala Hamburg Lisbon
London Madrid Mexico Montreal New Delhi Panama Paris
San )uan Sao Paulo Singapore Sydney Tokyo Toronto
Sponsoring Editor: Paul Berk
Editing Supervisor: James Fields
Design and Art Supervisor/Cover Designer: Frances Conte Saraeco
Production Supervisor: Priscilla Taguer
Text Designer: Susan Brorein

Library of Congress Cataloging-in-Publication


Data
Hall, Douglas V., date.
Microprocessors and interfacing.
Includes index.
1. Microprocessors — Programming. 2. Micro-
processors.
Computer 3. interfaces. I. Title.
QA76.6.H2994 1986 005.26 86-156
ISBN 0-07-025526-1

The manuscript for this book was prepared elec-


tronically.

Microprocessors and Interfacing:


Programming and Hardware
Copyright C 1986 by McGraw-Hill. Inc. All rights
reserved. Printed in the United States of America.
Except as permitted under the United States
Copyright Act of 1976. no part of this publication
may be reproduced or distributed in any form or
by any means, or stored in a data base or retrieval
system, without the prior written permission of
the publisher.

5 6 7 8 9 0 SEMBKP 8 9 3 2 10 9
ISBN Q-07-0255Eb-l
CONTENTS
Preface v More Practice with Simple Sequence Pro-
grams 72
Flags, .Jumps, and WHILE-DO Implementa-
CHAPTER tion 77
REPEAT- UNTIL Implementation and Exam-
Computer Number Systems, Codes, and Digital ples 87
Debugging Assembly Language Programs l 00
Devices 1
Review Questions and Problems 102
Objectives 1
Computer Number Systems and Codes 1
Adding and Subtracting Binary. Oetal, Hex, and
BCD Numbers 10 CHAPTER
Basic Logic Gates 15
Review Questions and Problems 22 IF-THEN -ELSE Structures, Procedures, and
Macros 104
Objectives 104
CHAPTER IF-THEN, IF-THEN-ELSE. and Multiple IF-
THEN - ELSE Programs 104
Computers, Microcomputers, and Micro- Writing and Using Procedures 1 10
processors—
An Introduction 24 Writing and Using Assembler Macros 139
Review Questions and Problems 141
Objectives 24
Computers 24
The 8086. 8088. 80186. 80188, 80286 Micro-
processors—
Introduction 33 C H A P T E " 6
8086 Internal Architecture 33
Introduction to Programming the 8086 37 8086 Instruction Descriptions and Assembler Di-
Review Questions and Problems 41 rectives 144
Instruction Descriptions 144
Assembler Directives 174
CHAPTER

8086 Family Assembly Language Programming CHAP TER 7


— Introduction 43
Objectives 43 8086 System Connections, Timing, and Trouble-
Program Development Steps 43 shooting 179
Constructing the Machine Codes for 8086 In- Objectives 179
structions 54 8086 Hardware Review 179
Writing Programs for Use With an As- Addressing Memory and Ports in Microcomputer
sembler 60 Systems 196
Assembly Language Program Development 8086 Timing Parameters 209
Tools 65 Troubleshooting a Simple 8086-based Microcom-
Review Questions and Problems 69 puter 213
Review Questions and Problems 219

CHAPTER

CHAP T ER 8
8086 Assembly Language Programming Tech-
niques—
Part 1 72 Interrupts and Interrupt Service Proce-
Objectives 72 dures 221
Objectives 221
8086 Interrupts and Interrupt Responses 221 CHAPTER 12
Hardware Interrupt Applications 232
Review Questions and Problems 258 Microcomputer System Peripherals 406

Objectives 406
Microcomputer Displays 406
CHAPTER .7 Raster Scan CRT Graphics Displays 413

CRT Terminals 414


Digital Interfacing 261 Raster Scan Color Graphics 415
Objectives 261 Vector Scan CRT Displays 4 18
Alphanumeric/Graphics LCD Displays 419
Programmable Parallel Ports and Handshake
Input/Output 261 Computer Vision 4 19
Interfacing a Microprocessor to Keyboards 280 Mass Data Storage Systems 422
Interfacing to Alphanumeric Displays 287 Floppy Disk Data Storage 422
Interfacing Microcomputer Ports to High-Power Magnetic Hard Disk Data Storage 431
Devices 298 Optical Disk Data Storage 432
Optical Motor Shaft Encoders 304 Printer Mechanisms 434
Review Questions and Problems 307 Speech Synthesis and Recognition With a Com-
puter 437
Review Questions and Problems 440

CHAPTER 10
Analog Interfacing and Industrial Control 311 CHAPTER 13
Objectives 311
Data Communication and Networks 442
Review of Operational-Amplifier Characteristics
and Circuits 311 Objectives 442
Sensors and Transducers 316 Asynchronous Serial Data Communication 442
D/A Converter Operation, Interfacing, and Appli- Serial Data Transmission Methods and Stan-
cations 321 dards 448
A/D Converter Types, Specifications, and Inter- Asynchronous Communication Software on the
facing 324 IBM PC 461
A Microcomputer-Based Scale 328 Synchronous Serial Data Communication and
A Microcomputer-Based Industrial Process-Con- Protocols 477
trol System 340 Local Area Networks 481
An 8086-Based Process-Control System 342 Review Questions and Problems 487
Developing the Prototype of a Microcomputer-
Based Instrument 355
Digital Filters
Review Questions
357
and Problems 359
CHAPTER 14
Operating Systems, the 80286 Microprocessor,
and the Future 490
CHAPTER 11 Objectives 490
Multiple Microprocessor Systems and Operating System Concepts and Terms 490
The Unix Operating System 496
Buses 361 The INTEL RMX 86™ Operating System 499
Objectives 361 The INTEL 80286 Microprocessor 502
The 8086 Maximum Mode 361 New Directions 513
Direct Memory Access (DMA) Data Transfer 363 Epilogue 516
Interfacing and Refreshing Dynamic RAM 370 Review Questions and Problems 5 17
Processors With Integrated Peripherals — The
80186 and 80188 374
A Coprocessor — The 8087 Math Coproces- Bibliography 519
sor 377 Appendix A 521
Multiple Bus Microcomputer Systems 397 Appendix B 533
Review Questions and Problems 404 Index 547
CONTENTS
PREFACE
For the most part. Microprocessors and Interfac write, lest . ;ind debug. Experience hasshownthat
tng: Programming and Hardware is based on a the most successful approach to writing a pro
throe-quarter series of microprocessor courses gram is to solve the problem fust . and then simply
that my colleagues and I teach. The book is in- implement the solution in the desired program-
tended
students
tor in electrical engineering pro- ming language.
grams, students
in electronic engineering techni- The 8086 instructions are introduced in Chap
cian trainingprograms, and people working in ters 2 through 5, as they are needed to solve sim-
industry who want to upgrade their knowledge of ple programming problems. Chapter 6 contains a
microprocessors. dictionary of all the 8086 and 80 186 instructions.
Before reading this book, you should have some You can refer to this chapter to find further details
basic knowledge of diodes, transistors, and digital about an instruction you want to use to do a par-
circuitry. One of its aims is to teach you how to ticular operation
in a program.
decipher and use manufacturer's literature; ac- Chapter 7 discusses the hardware signals, tim-
cordingly,
relevant
many parts of data sheets are ing, and
system connections of a simple micro-
shown. Because of the large number of actual de- computer. Chapter
7 also teaches a systematic
vices discussedhere, it was impossible to put the approach to troubleshooting a malfunctioning
complete data sheets for all these devices in the 8086-based system. The remaining chapters
appendixes. Therefore, I strongly suggest that you show how the hardware and the programs work
acquire or gain access to the latest edition of the together. Troubleshooting a microprocessor-
Intel Microsystem Components Handbook so based system, for example, usually requires
that, as you work your way through this book, you knowledge of both its hardware and program-
can refer to it if you need further information ming,I discuss
so here how diagnostic routines
about a particular device. The bibliography lists are written and used to find a problem.
other materials I have found useful. Chapter 8 discusses how the 8086 responds to
I have chosen here to teach the programming, interrupts and how interrupt service procedures
system connections, and interfacing of 16-bit mi- are written and used. Chapters 9 through 13 de-
croprocessors,
function
which as the "brains" of scribe
detail
in how a microcomputer is interfaced
microcomputers such as the IBM PC. My experi- with a wide variety of devices and systems. Also
encean as engineer and as a teacher indicates these chapters describe how the hardware and
that it is more productive to learn one micropro- programs for microprocessor-based products are
cessor familyvery thoroughly, and from that developed. Finally, Chapter 14 discusses operat-
strong base learn other families as needed. There- ing systemprograms, and the 80286 and 80386
fore, thisbook concentrates on the Intel microprocessors that are designed to be used as
8086/8088/80 186/80 188/80286/80386 family the brains of multiuser microcomputer systems.
of microprocessors, rather than superficially cov- Program development for 16-bit microproces-
eringmicroprocessor
the families of several man- sorssomewhat
is tedious on hex-keypad-type de-
ufacturers. velopmentsuchboardsas we used for 8-bit pro-
I came into the world of electronics through the cessors. Furthermore, industry does not usually
route of vacuum tubes. Therefore, my first tend- develop microprocessor-based products in this
ency was to approach microprocessors from a manner. Therefore, for working with 16-bit pro-
hardware orientation. However, the more I de- cessors
recommend
I a systems approach. A mi-
signed with
microprocessors and taught micro- croprocessor development
system, an IBM PC, or
processor classes,
the more I became aware that IBM PC-compatible computer, can be used to edit,
the real essence of a microprocessor is what you assemble, link/locate, run, and debug 8086 as-
can program it to do. For this reason the book sembly language programs. For programs that re-
begins with just a brief overview of the hardware quire external hardware, the object code for these
of a computer. The next five chapters show how a programs can be downloaded to some prototype
microprocessor-based microcomputer can be pro- hardware such as an Intel SDK-86 development
grammed
do someto real tasks. board. Chapter 13 contains a program that allows
The emphasis throughout is on writing assem- you to download object code programs from an
bly languageprograms in a top-down structured IBM or IBM-compatible computer to an SDK-86
manner. The idea is to make programs easy to board. An available laboratory manual, written to
accompany this book, shows you how to use the merous
mention.
to Thanks to Lee Campbell of
SDK-86 board and an IBM PC-compatible com- Spokane Community College in Spokane, Wash-
puterassembly
for language programming and ington,meticulously
who worked his way through
interfacing. the manuscript and made many valuable sugges-
In the interfacing sections of this book I have tions. Thanks
to Wayne J. Vyrostek of Westark
tried to show as many circuits as possible that you College in Fort Smith, Arkansas, who reviewed
can build, add to your microcomputer, and exper- the manuscript and contributed several valuable
iment with.
Building and experimenting with real suggestions. Thanks to Intel Corporation for let-
circuits will help you become fluent with micro- ting use
me many drawings from their data books,
processors.
circuits
The in this book are intended so that this book could lead readers into the mate-
just as starters. Hopefully you will grow far rial they
can use to continue their learning. Fi-
beyond what is shown here, if you have sugges- nally, thanks
to my family and friends for their
tionsimproving
for this book or ideas that might patience and support during the long effort of
clarify a point for someone else, please communi- writing this book.
cate with
me.
I wish to express my profound thanks to the Douglas V. Hall
people who helped make this book a reality.
Thanks to Pat Hunter, without whose cheerful en-
couragement
might not I have made it through the
book. She proofread and coded the manuscript, DEDICATION

worked out the answers to the end-of-chapter


problems to verify that they are solvable, and To my students — Who grow beyond what I give
made many suggestions and contributions too nu- and return to pull me into the future with them.
CHAPTER

Computer Number Systems,


Codes, and Digital Devices

Before starting our discussion ol microprocessors and The number ol symbols needed in any base numbei sys
microcomputers we need to make sure that some key tern is equal to the base number. In the decimal numbei
concepts ol the number systems, codes, and digital de- system then, there are 10 symbols, 0 through 9. When
vires used in microcomputers are fresh in your mind. If the count in any digit position passes that ol the highest
the short summaries of these concepts in this chapter value symbol, a carry of 1 is added to the next digit posi-
are not enough to refresh your memory, then it is a good tion and
the other digit rolls back to zero. A car odome-
idea to review them in a current digital text before going ter ais good example of this.
on in this book. A number system can be built using powers of any
number as place holders or digits, but some bases are
more useful than others. It is difficult to build electronic
OBJECTIVES circuits which can store and manipulate 10 different
voltage levels but relatively easy to build circuits which
At the conclusion of this chapter you should be able to:
can handle two levels. Therefore, a binary or base -2
number system is used.
1. Convert numbers between the following codes: bi-
nary, octal,
hexadecimal, and BCD.

2. Define the terms bit. nibble, byte, word, most signif- The Binary Number System
icant bit.
and least significant bit. Figure lib shows the value of each digit in a binary
number. Each binary digit represents a power of 2. A
3. Use a table to find the ASCII or EBCDIC code for a
binary digit is often called a bit. Note that digits to the
given alphanumeric character.
right of the binary point represent fractions used for
4. Perform addition and subtraction of binary, octal, numbers less than one. The binary system uses only two
hexadecimal, and BCD numbers. symbols, zero (0) and one (1). Therefore, in binary you
count as follows: 0, 1, 10. 11. 100. 101. 110. Ill, 1000.
5. Describe the operation of gates, nip-flops, latches,
ri(
registers, ROMs, dynamic RAMs, static RAMs. and Binary numbers are often called binary words or just
buses. ifords. Binary words of certain numbers of bits have
6. Describe how an arithemtic logic unit can be in- also acquired special names. A 4-bit binary word is
structed
perform
to arithmetic or logical operations
on binary words.
5 3 4 6 7 2
103 102 10' 10° 10 ' 10 2
COMPUTER NUMBER SYSTEMS AND
CODES

Review of Decimal System 10 110 1 1


To understand the structure of the binary number sys- 2' 26 2" 24 23222'2° 2~'2~;
tem, the
first step is to review the familiar decimal or
base- 10 number system. Figure 1-la shows a decimal 1286432 16 8 4 2 1 i j
number with the value of each place holder or digit ex-
pressed
a power
as of 10. The digits in the decimal num-
ber 5346.72 then tell you that you have 5 thousands, 3 FIGURE 1-1 Digit values in decimal and binary.
hundreds. 4 tens, 6 ones. 7 tenths, and 2 hundredths. fa) Decimal, (b) Binary.
25 2" 23 22 21 2° reverse of the binary-to-decimal method above. For ex-
32 16 8 4 2 1 ample,
convert
to the decimal number 21 (sometimes
written as 21,,,) to binary, first subtract the largest
0 1 0 1 0 1n
power of 2 that will fit in the number. For 21 10 the larg-
est power of 2 that will fit is 16 or 24. Subtracting 16
from 21 gives a remainder of 5. Put a one in the 24 digit
227,0 = position and see if the next lower power of 2 will fit in
the remainder. Since 2A is 8 and 8 will not fit in the
Least Significant
remainder of 5. put a zero in the 2 ' digit position. Then
Binary Digit
try the next lower power of 2. In this case the next is 22
1
or 4. which will lit in the remainder of 5. A 1 is, there-
R] x 1 1 fore, put
in the 22 digit position. When 22 or 4 is sub-
R\ x 2 2
tracted from
the old remainder of 5 a new remainder of 1
is left. Since 21 or 2 will not fit into this remainder, a
no x 4 0 zero is put in that position. A 1 is put in the 2" position
because 2° is equal to 1 and this fits exactly into the
RQ x 8 0
remainder of 1. The result shows that 21,0 is equal to
RQ x 16 0 10101 in binary. The conversion process is somewhat
messy to describe, but easy to do. Try converting 46 10 to
R) x 32 32
binary. You should get 101 1 10.
R] x 64 64 Another method of converting a decimal number to
binary is shown in Figure l-2b. Divide the decimal
R] x 128 128
number by 2 and write the quotient and remainder as
1 227 Check shown. Divide this quotient and following quotients by
Most Significant 2 until the quotient reaches zero. The column of re-
Binary Digit mainders
be will
the binary equivalent of the given deci-
mal number. Note that the MSD is on the bottom of the
227,
column and the LSD is on the top of the column if you
perform the divisions in order from the top to the bot-
tomthe
of page. You can demonstrate that the binary
MSD Check
number is correct by reconverting from binary to deci-
2 • 625 = ^25 1 x .5 mal as
shown in the right-hand side of Figure l-2b.

2 ' 25^^ ^cj.50 0 • 25


You can convert decimal numbers
narysuccessive
by multiplication
less than 1 to bi-
by 2, and recording
2 x
.50 *"^ i!oo 1 %
125 carries until the quantity to the right of the decimal
625 point becomes zero, as shown in Figure l-2c. The car-
LSD ries representthe binary equivalent of the decimal num-
(c) ber, with
the most-significant bit at the top of the col-
umn. Decimal 0.625 equals 0.101 in binary. For
FIGURE 1-2 Converting decimal to binary, (a) Digit value decimal values that do not convert exactly the way this
method. (6.) Divide by 2 method, (c) Decimal fraction one did (quantity to the right of the decimal never be-
conversion. comes zero),
you can continue the conversion process
until you get the number of binary digits desired.
called a nibble, and an 8-bit binary word is called a byte. At this point it is interesting to compare the number
A 16-bit binary word is often referred to just as a word. of digits required to express numbers in decimal with
and a 32-bit binary word is referred to as a doubleword. the number required to express them in binary. In deci-
The rightmost or least-significant l)it of abinary word is mal, one
digit can represent 101 numbers. 0—9; two dig-
usually referred to as the LSB. The left most or most-sig- its canrepresent 102 or 100 numbers. 0-99; and three
nificant
of bit
a binary word is usually called the MSB. dibits can represent 10* or 1000 numbers. 0-999. In
To convert a binary number to its equivalent decimal binary, a similar pattern exists. One binary digit can
number multiply each digit times the decimal value of represent two numbers. 0—1; two binary digits can rep-
the digit and just add these up. The binary number 101, resent
or 224 numbers. 0—11; and three binary digits
for example, represents: (1 • 22) + (0 • 21 ) + ( 1 % 2°) can represent 2 4 or 8 numbers. The pattern then is that
or 4 + 0 + 1 = decimal 5. For the binary number N decimal digits can represent 10N numbers and N bi-
101 10. 1 1 you have: nary digits
can represent 2N numbers. Eight binary dig-
its canrepresent the 2H or 256 numbers. 0—255.
(1 •- 24) + (0 % 23) + (1 < 22) + (1 % 2'1
+ (0 • 2"] Ml -2 '1 + (1 • 2 '-')
= 16 + 0 + 4 + 2 + 0 + 0.5 + 0.25 Octal
= decimal 22.75
Binary is not a very compact code. This means that it
To convert a decimal number to binary there are two requires many more digits to express a number than
common methods. The first (Figure l-2a) is simply a does, for example, decimal. Twelve binary digits can only

CHAPTER ONE
4096 512 64 8 1 which groups the binary digits in groups ol four rathei
than three Hexadecimal oi base 16 code does this. Fig-
ureIdI shows the digil values foi hexadecimal, which
Is often | ust called lt<-\ Sim e hex is base M>. you have to
have 16 possible symbols for each digit. The tabli of 1 '
in i' I l/) shows the symbols foi hex code. Aftei the deci
327
J*- ' Decimal = "> 327D = 5078 111.11 symbols 0 through 9 air used up. you use the let! cis
A through F foi values l<> through 15.
As mentioned above, each hex digit is equal to foui
8J327 = 40 binary digits. To convert the binary number 1 10101 10

8j~40 = 5
16' 16-' 16' 16°. 16 ' 16 ' 16 '
8j 5 = 0
4096 256 16 1 ,'„ ,,',

(a)

Dec Hex
Binary 101 011 111 .
0 0
Octal
Binary Point
1
1 1

2 = 2
FIGURE 1-3 Octal numbers, (a) Value of place holders. 3 = 3
(b) Conversion of decimal to octal, (c) Conversion of
binary to o( tal. 4 = 4

5 = 5

describe a number up to 4095,,,. Computers require 6 = 6

binary data, but people working with computers have 7 = 7


trouble remembering the long binary words produced by
the noncompact code. One solution to the problem is to 8 = 8

use the octal or base-8 code. As you can see in Figure 9 = 9


l-3a, the digits in this code represent powers of 8. The
symbols then are 0 through 7. You can convert a decimal 10 = A

number to the octal equivalent number with the same


11 = B
trick you used in convert decimal to binary. Figure l-3b
shows the technique for decimal-to-octal conversion. 12 = C
Decimal 327 is equal to 507,s. Verification of this is
13 = D
shown by reconverting the octal to decimal in the sec-
ond half
of Figure l-3b. 14 = E
Since 8 is an integral power of 2. conversions from
15 F
binary to octal, and octal to binary, are quite simple. If
you have a binary number such as 10101 1111. then, ib)
starting from the binary point and moving to the left,
1101 1D1102
mark off the binary digits in groups of three, as shown
in Figure 1-3c. Each group of three binary digits is equal D 6 HEX
to one octal digit. For the example above. Ill is a 7. 01 1
(c)
is a 3, and 101 is a 5. Therefore. 101011111 binary is
equal to 537,s.
22710 = ? H6;
You convert from octal to binary by replacing each
octal digit with its 3-bit binary equivalent. 16J227" = 14 R3 x 1 = 3

16pc4 = 0 RE x 16 = 224
Hexadecimal 22 7

Some once-popular minicomputers, such as the PDP-8,


have 12 parallel data lines. Four octal digits are an easy 227, E3,6
way to represent the binary data word on these 12 paral-
lel lines. For example. 100001010111 binary is easily
remembered or written as 4127 octal. Most microproc- FIGURE 1-4 Hexadecimal numbers, (a) Value of place
essors have
4-bit. 8-bit. 16-bit. or 32-bit data words. For holders, (b) Symbols, (c) Binary to hexadecimal
these microprocessors, it is more logical to use a code conversion, (d) Decimal to hexadecimal conversion.

COMPUTER NUMBER SYSTEMS, CODES, AND DICITAt DEVICES


z 5
o _l
a. o -- w n rr in to r^ oo o) < co O Q LU LL
II
CO
5

O
-1
a
(0 u. i- o o o t- t- i- o ,- t- O r- O O t- r-
5
i- UJ T- O T- O O O t- o ,- o t- i-
z
UJ
Q r- O t- i- O i- t- o ,- O *- t- T- T- T- O
S
o
LU O t- O o
CO u
z
LU CO T- O O T- ,- ,- t- O O r- r- O
>
UJ
CO ,- O T- 1- O T- T- T" T- T- T- O O O t- i-

REFLECTED
CODE
GRAY
O
O
o
o

i-
T-
O
o
o

O
T~
t-
o
o

T-
O
i-
o
o

O
O
*-

o
T-
t-

o
T-
o

o
O
o

o
O
O
i-
O
*-
T-
o
T-
O
1-
o
i-
T-
o
i-
O
o
p
P
o

CO
CO
CO
T-
O
o
O
T-
o
O
T-
o
T-
T-
o
1000
0111 1010
1001 1100
1011 )0100
)0011 1000
0100
0100
0110
0100
0111
0100
0101
UJ
u
X o o o o
UJ
o o o o p p t- t-
o o o o o o o o o o o o

O 1- O T" O O t- o

CO
CM
O
o
o
O
o
o
T"
o
o
T-
o
o
o
i-
o
o
o
o
i-
o 1100
1011 0000 1000
0001
0010
0001
000110001
0100
0001
001
0001
UJ
a in
o
o
-i
< O i- O 1-
s
o CM
o
o
o
p
o
o
t-
o
o
i-
o
o
0010
OOLL
LLOL 1110
LOLL1111 0010
0001
0000
0001
00010100
0001
0011
0001
1011
0001
UJ
t
Q CM

O i- O i- O t- O i-
a
o
m
O
o
o
O
o
o
i-
o
o
T-
o
o
O

o
O

o
T-

o
T~

o
10000000
0001
1001
00010100
0001
0010
0001
0101
0001
0011
0001
CM

CO

<1
X s O «- CM CO t 111 (O N co a> < cd O O LU LI-
UJ u
X UJ
a

_i
LU O f- CM CO 'S- id co r^
Q O t- CM CO « K) (O s

0 o
o
u
LU >
CO E O i- O 1- O i- O T- Q i- O i- O i- O i-
< O O t- t- O O t- •>- S p i- r- O O i- i-
o o o o o o o o
z o o o o
Zj o o o o
CD

r- Z
r-0
uuS is O f- CM CO m- lo to r~- CO en O r- CM CO %* LO

II 3 «

CHAPTER ONE
id hex, mark off groups ol four, moving to the left from r I 1/

the binary point, .is shown In Figure l 4c. Then write


the hex symbol foi the value ol each group ol four The
ol 10 uk nip Is equal to 6 and the 1 101 group Is equal to
13. Since 13 is Din hex. 110101 10 binary is equal to D6 / /
y. y.
U1AJ
in hex. II is usually used after a numbei to indicate
that It is a hexadecimal number. For example, I >«i hex is
usually written D6H. Eighl bits require only two hex
(limits id represenl them
11 you want to convert from decimal to hexadecimal,
Figure I 4d shows .i familiar trick to do this. The resull
shows that 227i0 is equal to E3H. As you can sec. hex is
an even more compact code than decimal. Two hexadec
unal digits can indicate a number up to 255. Only four
hex ilii^iis ,uc needed to represenl a 16-bit binary num
her.
To Illustrate how hexadecimal numbers are used in
digital logic, a service manual tells yon that the 8-bit-
wide data bus of an 8088A microprocessor should con- HGURt l-d Seven-segment LLD display. (a) Segmenl
tain 3FHduring a certain operation. Converting 3FH to labels, (b) Schematic of common-cathode type.
binary' gives the pattern ol Is and O's (001 1 11111 yon (c) Schematic of common-anode type.
would expect to find with your oscilloscope or logic ana-
lyzerthe
on parallel lines. The 3FH is simply a short-
hand whichis easier to remember and less prone to er- binary digit changes at a time as you count up in this
rors. code.
To convert from octal code to hex code, the easiest way If yon need to construct a Gray-code table larger than
is to write the binary equivalent of the octal and then that in Table 1 - 1. a handy way to do so is to observe the
convert the binary dibits, four at a time, into the appro- pattern of Is and O's and just extend it. The least-signif-
priatedigits.
hex Reverse the procedure to get from hex icant digit
column starts with one 0 and then has alter-
to octal. nating groups
of two 1 s and two O's as you go down the
column. The second-most-significant digit column
starts with two O's and then has alternating groups of
four Is and four O's. The third column starts with four
BCD Codes
O's, then has alternating groups of eight Is and eight
O's. By now you should see the pattern. Try to figure out
STANDARD BCD
the Gray code for the decimal number 16. You should
In applications such as frequency counters, digital volt- get 11000.
meters,
calculators,
or where the output is a decimal
display, a binary-coded decimal or BCD code is often
used. The advantage of BCD for these applications is
that information for each decimal digit is contained in a Seven-Segment Display Code
separate 4-bit binary word. As yon can see in Tabic 1-1, Since seven-segment displays such as that shown in
the simplest BCD code uses the first 10 numbers of Figure 1-6 are now so common in everything from calcu-
standard binary code for the BCD number 0 through 9. lators
gasoline
to pumps, the segment code for these has
The hex codes A through F are invalid BCD codes. Each been included in Table 1-1. Some single seven-segment
decimal digit then is individually represented by its displays will display the last six numbers ( 10—15) of this
4-bit binary equivalent. Figure 1-5 illustrates this. code as the hexadecimal digits A-F. In Table 1-1, a 1
indicates that the segment is lit. which is true for dis-
GRAY CODE plays such
as the common-cathode light-emitting diode
(LED) display in Figure l-6b. For some displays, such as
Gray code is another important binary code which is
often used for encoding shaft position data from ma- the common-anode LED display shown in Figure l-6c, a
low actually lights the segment, so you have to invert all
chines such
as computer-controlled lathes. This code
has the same possible combinations as standard binary, the values.
but as you can see in the 4-bit example in Table 1- 1. they
are arranged in a different order. Notice that only one
Alphanumeric Codes
When communicating with or between computers you
5 2 9 Decimal
need a binary-based code which can represent letters ol
the alphabet as well as numbers. Common codes used
0101 0010 1001 BCD
for this have from 5 to 12 bits per word and are referred
FIGURE 1-5 Decimal to BCD conversion. to as alphanumeric codes. To detect possible errors in

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES


TABLE 1-2
COMMON ALPHANUMERIC CODES

HEX
HEX HEX HEX CODE
CODE CODE CODE SELEC- FOR HOL- HOLES
ASCII FOR 7-BIT BCDIC FOR EP EBCDIC FOR TRIC SELEC- LERITH PUNCHED CODE
SYMBOL ASCII SYMBOL BCDIC SYMBOL EBCDIC SYMBOL TRIC SYMBOL FOR HOLLERITH

N U L 0 0 N U L 0 0 N U L 12 0 9 8 1
S 0 H 0 1 S 0 H 0 1 S C H 12 9 1
S T X 0 2 S T X 0 2 S T X 12 9 2
E T X 0 3 E T X 0 3 E T X 12 9 3

EOT 0 4 EOT 3 7 E C T 9 7
E N Q 0 5 E N Q 2 D E N Q 0 9 8 5
A C K 0 6 A C K 2 E A C K 0 9 8 6
BEL 0 7 BEL 2 F BEL 0 9 8 7

B S 0 8 B S 1 6 B S 119 6
H T 0 9 H T 0 5 H T 12 9 5
L F 0 A L F 2 5 L F 0 9 5
V T 0 B X 9 A V T 0 B V T 12 9 8 3

F F 0 C F F 0 C F F 12 9 8 4
C R 0 D * F F C R 0 D C R 12 9 8 5
S 0 0 E S 0 0 E S 0 12 9 8 6
S 1 0 F S 1 0 F S 1 12 9 8 7

D L E 1 0 D L E 1 0 D L E 12 119 8 1
D C 1 1 1 D C 1 1 1 D C 1 11 9 1
D C 2 1 2 D C 2 1 2 D C 2 11 9 2
D C 3 1 3 D C 3 1 3 D C 3 119 3

D C 4 1 4 D C 4 3 5 D C 4 9 8 4
N A K 1 5 N A K 3 D N A K 9 8 5
S Y N 1 6 S Y N 3 2 S Y N 9 2
E T B 1 7 E 0 B 2 6 E T B 0 9 6

CAN 1 8 CAN 1 8 CAN 119 8


E M 1 9 E M 1 9 E M 119 8 1
SUB 1 A SUB 3 F SUB 9 8 7
ESC 1 B B Y P 2 4 ESC 0 9 7

F S 1 C F L S 1 C F S 119 8 4
G S 1 D G S 1 D G S 119 8 5
R S 1 E R D S 1 E R S 119 8 6
U S 1 F U S 1 F U S 119 8 7
S P 2 0 S P 0 0 S P 4 0 S P NO PNCH

I 2 1 1 6 A i 5 A \\ 2 7 i 12 8 7
2 2 4+f 5 F 7 F 2 D 8 7
# 2 3 # 4 B # 7 B # 7 E # 8 3
$ 2 4 $ 2 B $ 5 B $ 7 9 $ 11 8 3
% 2 5 % 5 C % 6 C % 3 D % 0 8 4

& 2 6 & 3 0 & 5 0 & 7 D 12


2 7 V 1 D 7 D 2 5 8 5
( 2 8 Blank 5 0 ( 4 D ( 3 8 ( 12 8 5

) 2 9 6 F ) 5 D ) 3 9 ) 11 8 5
2 A 6 C 5 C 7 C 118 4

(c ontinued)

CHAPTFK ONI
TABLE 1-2
COMMON ALPHANUMERIC CODES (CONTINUED)

HEX
HEX HEX HEX CODE
CODE CODE CODE SELEC FOR HOL- HOLES
ASCII FOR 7-BIT BCDIC FOR EP EBCDIC FOR TRIC SELEC LERITH PUNCHED CODE
SYMBOL ASCII SYMBOL BCDIC SYMBOL EBCDIC SYMBOL TRIC SYMBOL FOR HOLLERITH

t 2 B I 4 E i 0 E i 12 8 6
2 C 1 B 6 B 4 4 0 8 3
2 D 6 0 0 0 11
2 E 7 B 4 B 2 6 12 8 3
1 2 F 1 1 6 1 / 4 1 / 0 1

0 3 0 0 0 A 0 F 0 0 3 1 0 0
1 3 1 1 4 1 1 F 1 1 7 7 1 1
2 3 2 2 4 2 2 F 2 2 3 6 2 2
3 3 3 3 0 3 3 F 3 3 7 6 3 3
4 3 4 4 4 4 4 F 4 4 7 1 4 4

5 3 5 5 0 5 5 F 5 5 3 5 5 r)
6 3 6 6 0 6 6 F 6 6 3 4 6 6
7 3 7 7 4 7 7 F 7 7 7 5 7 7
8 3 8 8 4 8 8 F 8 8 7 4 8 8
9 3 9 9 0 9 9 F 9 9 3 0 9 9

3 A 4 D 7 A 4 D 8 2
3 B 2 E 5 E 4 5 118 6
< 3 C < 7 E < 4 C < 12 8 4
= 3 D V 0 F = 7 E = 0 6 = 8 6
> 3 E > 4 E > 6 E > 0 8 6
? 3 F ? 3 A ? 6 F ? 4 9 ? 0 8 7
,, 4 0 @ 0 C (a 7 C @ 3 E (1 8 4

A 4 1 A 7 1 A C 1 A 6 C A 12 1
B 4 2 B 7 2 B C 2 B 1 8 B 12 2
C 4 3 C 3 3 C C 3 C 5 C C 12 3
D 4 4 D 7 4 D C 4 D 5 D D 12 4

E 4 5 E 3 5 E C 5 E 1 D E 12 5
F 4 6 F 3 6 F C 6 F 4 E F 12 6
G 4 7 G 7 7 G C 7 G 4 F G 12 7
H 4 8 H 7 8 H C 8 H 1 9 H 12 8

I 4 9 I 3 9 I C 9 I 2 C 1 12 9
J 4 A J 2 1 J D 1 J 0 7 J 11 1
K 4 B K 2 2 K D 2 K 1 C K 11 2
L 4 C L 6 3 L D 3 L 5 9 L 11 3

M 4 D M 2 4 M D 4 M 6 F M 11 4
N 4 E N 6 5 N D 5 N 1 E N 11 5
0 4 F 0 6 6 0 D 6 0 6 9 0 11 6
P 5 0 P 2 7 P D 7 P 0 D P 11 7

Q 5 1 Q 2 8 Q D 8 Q 0 C Q 11 8
R 5 2 R 6 9 R D 9 R 6 D R 11 9
S 5 3 S 1 2 S E 2 S 2 9 S 0 2
T 5 4 T 5 3 T E 3 T 1 F T 0 3

[continued)

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES


TABLE 1-2
COMMON ALPHANUMERIC CODES (CONTINUED)

HEX
HEX HEX HEX CODE
CODE CODE CODE SELEC- FOR HOL- HOLES
ASCII FOR 7 BIT BCDIC FOR EP EBCDIC FOR TRIC SELEC- LERITH PUNCHED CODE
SYMBOL ASCII SYMBOL BCDIC SYMBOL EBCDIC SYMBOL TRIC SYMBOL FOR HOLLERITH

U 5 5 U 1 4 U E 4 U 5 E U 0 4
V 5 6 V 5 5 V E 5 V 6 E V 0 5
w 5 7 w 5 6 w E 6 w 2 8 w 0 6
X 5 8 X 1 7 X E 7 X 5 F X 0 7
Y 5 9 Y 1 8 Y E 8 Y 0 9 Y 0 8
z 5 A z 5 9 z E 9 z 3 F z 0 9

[ 5 B [ 7 D I A D [ 7 F I 12 8 2

\ 5 C \ 1 E N L 1 5 \ 0 8 2

I 5 D ] 2 D ] D D ] 11 8 2
A 5 E D 3 C "I 5 F A 11 8 7
5 F 6 0 6 D 0 8 0 8 5
6 0 RES 1 4 8 1

a 6 1 a 8 1 a 6 4 a 12 0 1
b 6 2 b 8 2 b 1 0 I. 12 0 2
t: 6 3 c 8 3 c 5 4 c 12 0 3
d 6 4 d 8 4 d 5 5 d 12 0 4

e 6 5 e 8 5 e 1 5 e 12 0 5
f 6 6 f 8 6 f 4 6 f 12 0 6

<J 6 7 g 8 7 g 4 7 g 12 0 7
h 6 8 h 8 8 h 1 1 h 12 0 8

i 6 9 i 8 9 i 2 4 i 12 0 9
I 6 A 1 9 1 i 0 7 1 12 111
k 6 B k 9 2 k 1 4 k 12 112
I 6 C 1 9 3 I 5 1 1 12 113

in 6 D m 9 4 m 6 7 m 12 11 4
n 6 E n 9 5 n 1 6 n 12 115
(i 6 F o 9 6 o 6 1 o 12 116
P 7 0 P 9 7 P 0 5 P 12 117

q 7 1 q 9 8 q 0 4 9 12 118
r 7 2 r 9 9 r 6 5 r 12 119
s 7 3 S A 2 s 2 1 s 11 0 2
t 7 4 t A 3 t 1 7 t 11 0 3

u 7 5 u A 4 u 5 6 u 110 4
V 7 6 V A 5 V 6 6 V 11 0 5
w 7 7 w A 6 w 2 0 w 110 6
X 7 8 X A 7 X 5 7 X 11 0 7

y 7 9 y A 8 y 0 1 y 110 8
z 7 A z A 9 z 3 7 z 110 9

1 7 B { 8 B ( 12 0
1 7 C 4 F 1 12 11
} 7 D } 9 B 1 11 0
~
7 E c 4 A - 11 0 1
DEL 7 F DEL 0 7 DEL 12 9 7

BCDIC SELECTRIC
HEX DIGIT HEX DIGIT R,,T,T, SR,4R,R,
PCBA 2 ' 2 • 2 ' 2° HEX DIGIT HEX DIGIT

( HAN Ik ONI
these codes, an additional bit. called a parity bit. is often TABLE 1-3
added as the mosl significanl bit. DEFINITIONS OF CONTROL CHARACTERS
/'(irin/ is a term used i<> Identifj whethei .1 data word
has .111 odd or even number of l's. II .1 data word con NUL NULL DC2 DIRECT CONTROL 2
tains an odd number ol l's. the word is said to have odd SOH START OF HEADING DC3 DIRECT CONTROL 3
parity rhe binary woi d 01 l 0 I l I with five l's has odd STX START TEXT DC4 DIRECT CONTROL 4

parity. The binary word 01 10000 has an even number ol ETX END TEXT NAK NEGATIVE

l's (two) so 11 has even parity EOT END OF TRANSMIS- ACKNOWLEDGE


SION SYN SYNCHRONOUS
In practice the pai ity bil may function as follows. The
ENQ ENQUIRY IDLE
system thai is sending a data word checks the parity ol
ACK ACKNOWLEDGE ETB END TRANSMIS-
the word. II the parity ol the da 1.1 word is odd. the sys
BEL BELL SION BLOCK
tern will set (he parity bil to a I - This makes the parity ol
BS BACKSPACE CAN CANCEL
the data word plus parity bil even. 11 the parity of the
HT HORIZONTAL TAB EM END OF MEDIUM
data \\ ord is even, the sending system will resel the par-
IF LINE FEED SUB SUBSTITUTE
ity bilto a 0. This again makes the parity of the data
VT VERTICAL TAB ESC ESCAPE
word plus parity even. The receiving system checks 1in-
FF FORM FEED FS FORM SEPARATOR
parity of the data word plus parity bil thai it receives. II
CB CARRIAGE RETURN GS GROUP SEPARATOR
the receiving system detects odd parity in the received
SO SHIFT OUT RS RECORD
data word plus parity, it can assume an error occurred
SI SHIFT IN SEPARATOR
and tells the sending system to send the data again. The
DLE DATA LINK ESCAPE US UNIT SEPARATOR
system is then said to be using even parity. The system
DC1 DIRECT CONTROL 1
could have been scl up to use (maintain) odd parity in a
similar manner.
The difficulty with this method of detecting errors in-
troduced during
transmission is that two errors intro-
duced into
a data word may keep the correct parity and, Interchange Code or EBCDIC. This is an 8-bit code
therefore, the parity checker won't indicate an error. without parity. A ninth bit can be added for parity. To
Other, more complex methods, such as CRC and "Ham- save space in Table 1-2, the eight binary digits ol
ming codes"can be used to detect multiple errors in EBCDIC are represented with their 2-digit hex equiva-
transmitted data, and even to correct errors. Some of lent.
these will be described in Chapters 12 and 13.
SELECTRIC
ASCII
Selectric is a 7-bit code used in the familiar IBM spin-
Table 1-2 shows several alphanumeric codes. The first of ning ball
typewriters and printers. Table 1-2 shows this
these is ASCII, or American Standard Code for Informa- code for reference also. Each bit position in the code
tion Interchange. This is shown in the lable as a 7-bit controls an operation of the spinning ball.
code. With seven bits you can code up to 128 characters, From most-significant to least-significant bit, the
which is enough for the full upper- and lower-case al- meaning of the seven bits are: ROTATE 5. TILT 1, TILT
phabet, numbers, punctuation marks, and control 2, SHIFT. ROTATE 2A, ROTATE 2. and ROTATE 1. In
characters. The code is arranged so that if only upper- addition to this 7-bit code. Selectrics have separate
case letters, numbers, and a few control characters are machine commands for space, return, backspace, tabs,
needed, the lower six bits are all that is required. If a bell, and index.
parity check is wanted, a parity bit is added to the basic
7-bit code in the MSB position. The binary word 1 100 HOLLERITH
0100. for example, is the ASCII code for upper-case D
Hollerith is a 12-bit code used to encode data from those
with odd parity. Table 1-3 gives the meanings of the con-
computer cards which threaten you with a fate worse
trol character symbols used in the ASCII code table.
than death if you "fold, spindle, or mutilate" them. Fig-
ure l-7b shows a standard 12-row by 80-column card.
BCDIC
The 12 data rows are referenced as. starting from the
BCDIC code is the Binary Coded Decimal Interchange top. 12. 11,0, 1.2.3.4,5,6,7,8.9. The top three rows
Code used with some computers. It uses seven bits plus are called zone punches and the bottom 10 rows are
a parity bit. The lower four bits are referred to as the called digit punches. Note that the zero row is included
numeric bits. The upper four bits contain a parity bit in both categories. A punched hole represents a 1 and a
and three zone bits. The arrangement of these bits is data word is described by the 12 bits in a vertical col-
shown at the bottom of Table 1-2. To save space in Table umn. The
card in Figure l-7b shows the Hollerith code
1-2. the hex equivalent of the binary digits is used for for the numbers and letters printed across the top of the
the BCDIC code expressed with even parity. card. Table 1-3 shows the entire code and the punched-
hole equivalent for each character. Since Hollerith code
EBCDIC uses very few of the possible combinations for 12 bits, it
Another alphanumeric code commonly encountered in is not very efficient. Therefore, it is usually converted to
IBM equipment is the Extended Binary Coded Decimal ASCII or EBCDIC for use.

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES


• •••

• •• • • • • ••••
•••• • • • • • • ••••• • ••••••

• •••
• •••• • • • • ••• • • ••
•••• •• •• • •• • ••••••• • ••

0 1 23456 789 ABCDEFGHIJKLMNOPQP.STUVWXYZ

ZONE
PUNCHES
iiiiiiiii i

0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 II IJ 0 '.
docoooooooooooggooooIIIIIIIIooooooIIooooooooogoooooooo OGC

1 I I II I I I I I I l| I I I Ill i 11 n ii i 1 1 11 1 i i i i i i i i i i i i n i i i i i ii i i i i i i i i i i i i i i i i i i i i I I 1

2222222 22 2 22 2|22 >222|22222222|2222222|22222222222222222222222222222222? 22 2


222;

I 3 ] 3 31 3 3 3 1 3 3 3 3 1 3 3 3 3 3 3 3 1 3 3 3 3 3 3 3 3 3 3 3 1 1 3 1 1 3 3 3 3 3 3 3 3 3 3 3 1 3 3 3 3 3 3 3
33 33 3 3 3 3 3 33 3 3 3|3 3 3 3:

4 4 4 4 4 4 4 4 4 4 4 4 4 4 4| 1 4 4 I 144444|4444444<|4444444|4444444444444444444444444444444 4 l 4

DIGIT
555555555555555 5|555 i 55
5 5 51 5 5 5 51 5 5 5 5 5 5 5 5| 5 5 5 5 5 5 51 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 PUNCHES

6 E G 6 6 6 G 6 6 6 6 6 E 6 6 6 E | B 6 6 6 6 I,56b666|86666666|6666666|6666666S68666|666666666666666

j j ) 7 7 j 7 7 7 ; 7 7 7 7 7 7 7 7 1 J J; 7 7 7 7 7 7 7 J 7 1 7 7 7 7 7 7 7 7 1 7 7 7 7 7 7 7 1 7 ) 7 7 7 7 J 7 7 1 1 7 7 7 7 7 7 7 7 7 7 J 7 7 7 7 7 J

! 8 8 8 » 3 E ! 3 t 3 3 S 8 8 8 S 8 6 | 8 8 8 3 8 8 8 8 8 ' 3 1 1 8 8 8 8 8 I S 8 1 8 ! 8 1 8 8 ! | J 8 8 I 8 8 1 1 1 1 1 1 ! M I ! ! ! 6 5 8 I 8 It I

9 9 9 'i 9 9 9 9 9 9 5 9 9 5 9 9 9 31 9 9 I 9 9 9 9 9 5 9 9 9 9 9 9 | 9 9 9 9 9 9 3 9 1 9 9 9 3 9 3 3 I « 1 " 3 1 1 3 9 1 1 i 1 "%'I 9 5 9 9 i « 9 i C M ?

FIGURE 1-7 (a) ASCII punched paper tape; (b) Hollerith punched card.

ADDING AND SUBTRACTING BINARY, INPUTS OUTPUTS


OCTAL, HEX, AND BCD NUMBERS
A B CIN ^ CoUT
The previous section of this chapter reviewed common
number systems and codes used with computers. This 0 0 0 0 0
section reviews how to do computations in the previ-
0 0 1 1 0
ously describednumber systems.
0 1 0 1 0
Binary
0 1 1 0 1
ADDITION 1 0
1 0 0
Figure l-8a shows the truth table for addition of two
1 0 1 0 1
binary digits and carry in (C!N| from addition of previous
digits. Figure l-8b shows the result of adding two 8-bit 1 1 0 0 1
binary numbers together using these rules. Assuming
1 1 1 1 1
that Cim =1,1+0 + C|N = a sum of 0 and a carry into
the next digit, and 1 + 1 + C,N = a sum of 1 and a carry
S - A © B © Cm
into the next digit because the result in any digit posi-
tion can
only be a one or a zero. Cut = A %B + C,N [A © B)

2's COMPLEMENT BINARY

2's complement binary is a way of representing negative 10011010


numbers in binary. When you handwrite a number
11011100
which represents some physical quantity such as tem-
perature,
canyousimply put a + sign in front of the m 01110110
number when you wish to indicate that the number is t_, Carry
positive. You can write a - sign when you wish to indi-
cate that
the number is negative. If however, you want
to store values such as temperatures, which can be posi-
tive negative
or in a computer memory, there is a prob- FIGURE 1-8 Binary addition, (a) Truth table for 2 bits
lem. Sincethe computer memory can only store Is or plus carry, (b) Addition of two 8-bit words.

10 CHAPTER ONE
lis. some way must be established to represenl the sign %13 00001101
ol the number with .1 1 oi a 0 + 9 00001001
I he waj to 1In 1Ins is to reserve the mosl significant t22 00010110
bit oi the data word .is ,1 sign bit and to use the resl ol
Sign bit is 0
the bits ol the data word to represenl the size (magni so result is positive
tude) ot the quantity. A computer thai works with 8 bil
(a)
words will use the MSB tbit 7) as the siiju hit and the
lowei seven bits to represenl the magnitude for the t 13 00001101
numbers. The usual convention is to represenl a posi-
- 9 11110111 2's complement for 9 with sign bit
tive number with a o sign bil and a negative number
with a 1 sign bit.
f 4 1J 00000100
1 Sign bit is 0
To make computations with signed numbers easier,
so result is positive
tin- magnitude ol negative numbers is represented m a
Ignore carry
special form called 2's complement. The 2's complement
(b)
ol a binary number is formed by inverting each bit ol the
data word and adding one to (he result. Some examples
+ 9 00001001
should help clarify all of this.
-13 11110011 2's complement lor 13 with sign bit
The number ' 7,,, is represented 1118-bil sign-and-
magnitude form as 0000 0111. The sign bit is zero, - 4 11111100 Sign bit is 1

which indicates a positive number. The magnitude of 0000001 1 So invert each bit

positive numbers is represented in straight binary, so 1 Add 1


equals
0000 01 1 1 in the least-significant bits represents 7,,,. 00000100 Prefix with minus sign
1
To represent -7K, in 8-bit 2's complement sign-and-
(C)
magnitude form, start with the 8-bit code for +7. 0000
0111. Invert each bit to get 1111 1000. Then add 1 to
get 1111 1001. This result is the correct representation
- 9 11110111 I 2's complement,
-13 11110011 | sign-and-magnitude form
of -7i0. Figure 1-9 shows some more examples of posi-
tive andnegative numbers expressed in 8-bit sign-and- 22 11101010 Sign bit is 1
magnitude form. For practice, try generating each of 00010101 So invert each bit
these yourself to see if you get the same result as shown. 1 Add 1
equals
To reverse the above procedure and find the magni- -00010110 Prefix with minus sign
tudeaof number expressed in sign-and-magnitude (cO
form, proceed as follows. 11 the number is positive, as
indicated by the sign bit being a 0. then the least-signif- FIGURE 1-10 Addition of signed binary numbers

icant
bits7 represent the magnitude directly in binary. (a) +() and 1 I % !.(b) 9 and ' I 1. (t 1 +9 and I I

If the number is negative, as indicated by the sign bit id) -') and -13.

being a 1. then the magnitude is expressed in 2's com-


plement.
get the
To magnitude of this negative number
expressed in standard binary, invert each bit of the data Figure 1-10 shows some examples of addition of
word, including the sign bit and add one to the result. signed binary numbers of this type. Sign bits are added
For example, given the word 1110 1011, invert each bit together just as the other bits are. Figure 1 -10a shows
to get 0001 0100. Then add 1 to get 0001 0101. This the results of adding two positive numbers. The sign bit
equals 21 ,0 so you know that the original numbers rep- of the result is zero, so the result is positive. The second
resent10.-21Again, try reconverting a few of the num- example, in Figure 1 - 1Ob, adds a -9 to a +13 or, in
bersFigure
in 1-9 for practice. effect, subtracts 9 from 13. As indicated by the zero sign
bit, the result of this. 4. is positive and in true binary
form.
Sign bit Figure l-10c shows the result of adding a -13 to a
1 : smaller positive number. +9. The sign bit of the result is
+ 7 0 0000111
a 1. This indicates that the result is negative and the
+ 46 0 0101110 magnitude is in 2's complement form. To reconvert a 2's
complement result to a signed number in true binary
+ 105 0 1101001
form :
- 12 1 1110100
1. Invert each bit. to produce l's complement.
- 54 1 100 10 1(J > Sign and
2. Add one.
two's complement
-117 1 0001011
of magnitude 3. Put a minus sign in front to indicate that the result
- 46 1 1010010 is negative.

FIGURE 1-9 Positive and negative numbers represented The final example in Figure l-10d shows the results of
with a sign bit and 2's complement. adding two negative numbers. The sign bit of the result

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES 11


01111111 +127 you like number patterns, you might notice that this
scheme shifts the normal codes for 128 to 255 down-
wardrepresent
to -128 to -1.
If a computer is storing signed numbers as 16-bit
00000001 +1 words, then a much larger range of numbers can be rep-
00000000 ZERO resented.16
Since
bits gives 2lb or 65.536 possible val-
11111111 -1 ues, the
range for 16-bit sign-and-magnitude numbers
is -32,768 to +32,767. Operations with 16-bit sign-
and-magnitude numbers are done the same as was
demonstrated above for 8-bit sign-and-magnitude num-
10000001 -127
bers.
10000000 -128

FIGURE 1-11 Range of signed numbers that can be BINARY SUBTRACTION

represented with 8 binary bits. There are two common methods for doing binary sub-
traction. These
are the pencil method and the 2's com-
plementmethod.
add Figure l-12a shows the truth
is a 1. and the result is negative and in 2's complement table for binary subtraction of two binary digits A and B.
form. Again, inverting each bit. adding 1. and prefixing Also included in the truth table is the effect of a borrow
a minus sign will put the result in a more recognizable in, B|N. from subtracting previous digits. Figure l-12b
form. shows an example of the "pencil" method of subtracting
Now let's consider the range of numbers that can be two 8-bit numbers. Using the truth table, this method is
represented with eight bits in sign-and-magnitude done the same way that you do decimal subtraction.
form. Eight bits can represent a maximum of 2s or 256 A second method of performing binary subtraction is
numbers. Since we are representing both positive and by adding the 2's complement representation of the bot-
negative numbers, half of this range will be positive and tom number(subtrahend) to the top number (minu-
half negative. Therefore, the range then is () to • 127 end). Figurel-12c shows how this is done. First repre-
and from 1 to 128. Figure 1-1 1 shows the sign-and- sent the
top number in sign-and-magnitude form. Then
magnitude binary representations for these values. It form the 2's complement sign-and-magnitude represen-

INPUTS OUTPUTS

A B BIN D B0ut 10101010


01100100
0 0 0 0 0
01000110
0 0 1 1 1

0 1 0 1 1

91,0 01011011 01011011


0 1 1 0 1

-46,0 —00101 110 -^ -> +11010010


1 0 0 1 0 Invert /
45,0 each bit | [Jj 00101101 =45,
1 0 1 0 0
One's comp V,. 11010001 . >, A
1— Indicates
1 1 0 0 0
result positive
Add 1 + ' and in true
1 1 1 1 1
Two's comp
11010010 -'
binary form
Different = A ® B ® Bm Carry
Borrow A %8 + (A © B) %B..

01001101 01001101
38,o 01011000 Complement + 10101000 Complement
00001010
^. 10100111
Qj] 11110101
Add one v 1
Indicates
1011
result negative
Two's comp 10101000 and in two's
Carry complement form

FIGURE 1-12 Binary subtraction, (a) Truth table for 1 bits and borrow, (b) Pencil
method. (C) 2's complement positive result, id) 2's complement negative result.

12 ( MAI' 1 1 K ONI
tation for the negative ol the bottom number. Flnallj 01100 Quotient
.hUI the two parts formed For the example In Figure
I- 12c, the sign of the result Is a zero which Indicates the
Divisor 110)1001000 Dividend 1.'
6)72
resull is posihvt' and in true form. The final carry pro 110
(lined by the addition can be ignored. Figure I 12d 110

shows another example ol ibis method ol subtraction 110

In this ease the bottom number is larger than the top


number. Again, represenl the top number in si^n and
magnitude form, produce the 2's complement sign and
magnitude form for the negative ol the bottom number,
and add the two together. The sign l>ii of the resull is a 110.01 6 25
I for tins example. This indicates that the result is neg-
(III) 11001 00 4)25 00
ative and Ms magnitude is represented in 2's comple-
ineiii form, lb o<i the resull into a form thai is more -100
recognizable to you, invert each bit ol the result, add I
100
to it. and put a minus sii;n in lionl ol it as shown in
Figure l-12d. 100
The examples shown use eight bits, hut the process
01 00
works for any number ol hits. This method may seem
awkward, but it is easy to do in a computer or micro- (b)
processor because
it requires only the simple operations
of inverting and adding. FIGURE I-I4 Binary division.

BINARY MULTIPLICATION

There are several methods of doing binary multiplica- nets arc added as they are produced and the sum ol the
tion. Figure1-13 shows what is called the pencil method partial products is shifted right rather than each partial
because it is the same as the way you learned to multiply product being shifted left.
decimal numbers. The top number or multiplicand is A point to note about multiplying numbers is the
multiplied by the least-significant digit of the bottom number of bits the product requires. For example, mul-
number or multiplier. The partial product is written tiplying
4-bit
two numbers can give a product with as
down. The top number is multiplied by the next disj.il ol many as 8 bits, and two 8-bit numbers can give a 16-bit
the multiplier. The resultant partial product is written product.
down under the last, but shifted one place to the left.
Adding all the partial products gives the total product. BINARY DIVISION
This method works well when doing multiplication by
Binary division can also be performed in several ways
hand, but it is not practical lor a computer because the
Figure 1-14 shows two examples of the pencil method.
type of shifts required make it awkward to implement.
This is the same process as decimal long division. How-
One of the multiplication methods used by computers
ever,
is itmuch simpler than decimal long division be-
is repeated addition. To multiply 7 %55. for example,
causedibits
the of the result (quotient) can only be 0 or
the computer can just add up seven 55's. For large num-
1. A division is attempted on part of the dividend. If this
bers, however,this method is slow. To multiply 786 x
is not possible because the divisor is larger than that
253. for example, requires 252 add operations
part of the dividend, a 0 is entered into the quotient.
Most computers use an add-and-shift-right method.
Another attempt is then made to divide using one more
This method takes advantage of the fact that, for binary
digit of the dividend. When a division is possible, a 1 is
multiplication, the partial product can only be either the
entered in the quotient. The divisor is then subtracted
top number exactly if the multiplier digit is a 1. or a 0 if
from the portion of the dividend used. The process is
the multiplier digit is a 0. The method does tin same
continued as with standard long division until all the
thing as the pencil method except that the partial prod-
dividend is used. As shown in Figure l-14b. O's can be
added to the right of the binary point and division con-
tinued
convert
to a remainder to a binary equivalent.
11 1011 Multiplicand Another method of division that is easier for com-

x 9 1001 puters and


microprocessors to perform uses successive
Multiplier
subtractions. The divisor is subtracted from the divi-
99 1011 '
dend and
from each successive remainder until a bor-
0000 rowproduced.
is The desired quotient is I less than the
% Partial produ number of subtractions needed to produce a borrow.
0000
This method is simple, but lor large numbers it is slow
1011 For faster division of large numbers, computers use a
subtract-and-shift-left method that is essentially the
1100011 Product
same process you go through with a pencil Ion;; divi
FIGURE 1-13 Binary multiplication. sion.

COMPUTER NUMBER SYSTEMS, CODES, AND DICITAl DEVK Is 13


Carry the sum is 16 or greater. An A in hex is a 10 in decimal
1 and an F is 15 in decimal. These add to give 25, which is

100 111 '4/ a carry with a remainder of 9. The 9 is written down and
47e
the carry is added to the next digit column. Then 7 plus
t3G:; + 011 110 + 368 3 plus a carry gives a decimal 1 1 , or B in hex.
1 000 101 8,o 13K, You may use whichever method seems easier to you
and gives you consistently right answers. If you are
1 0 58 1 0 5„
doing a great deal of octal or hexadecimal arithmetic you
(a) (b) might buy an electronic calculator specifically designed
to do decimal, octal, and hexadecimal arithmetic.
FIGURE 1-15 Octal addition, (a) Adding binary
equivalents, (b) Direct octal addition. OCTAL SUBTRACTION

Octal subtraction is shown in Figure 1-17. Since the


least-significant digit of the top number is smaller than
Octal and Hexadecimal Addition and
the least-significant digit of the bottom number, a bor-
Subtraction
row must be done. In octal subtraction. 8 is borrowed
People working with computers or microprocessors from the next digit position and added to the top num-
often use octal or hexadecimal as a shorthand way of ber. Thebottom number is then subtracted and the
representing long binary numbers such as memory ad- remainder written down. The process is continued until
dresses.
is therefore
It useful to be able to add and sub- all digits are subtracted. If you are uncomfortable "bor-
tract octal
and hexadecimal numbers. rowing B's.'you
can just convert the number to decimal,
subtract, and convert the result back to octal.
OCTAL ADDITION

Figure 1-15 shows two ways of adding the octal num-


34
bersand
47 36. The first way is to convert both numbers
to their binary equivalents. Remember, each octal digit -17.
represents three binary digits. These binary numbers 15
are then added using the rules for binary addition from
Figure l-8a. The resultant binary sum is then converted FIGURE 1-17 Octal subtraction.
back to octal.
The second method works directly with the octal form:
7 added to 6 gives 13. which is a carry to the next digit HEXADECIMAL SUBTRACTION
and a remainder of 5. The 5 is written down and the Hexadecimal subtraction is similar to octal subtraction
carry added to the next digit column. Then 4 plus 3 plus except that, when a borrow is needed, 16 is borrowed
a carry gives 8. which is a carry with no remainder. The from the next-most-significant digit. Figure 1-18 shows
0 is written down and the carry is added to the next digit this. It may help you to follow the example if you do par-
column. This is the same process you use for decimal tial conversions to decimal in your head. For example. 7
addition but a carry is produced any time the sum is 8 plus a borrowed 16 is 23. Subtracting B or 1 1 leaves 12
or greater, rather than 10. or C in hexadecimal. Then 3 from the 6 left after a bor-
row leaves3. so the result is 3CH.
HEXADECIMAL ADDITION

As shown in Figure 1-16 the same approaches can be


used to add two hexadecimal numbers. For converting
7716 119,o
to binary, remember that each hex digit represents four -3B„ 5910
binary digits. The binary numbers are added and the
3C,6 60,0
result is converted back to hexadecimal.
The second method works directly with the hex num- FIGURE 1-18 Hexadecimal subtraction.
bers. With
hex addition, a carry is produced whenever

BCD Addition and Subtraction


Carry
| In systems where the final result of a calculation is to be
displayed, such as a calculator, it may be easier to work
1A 0111 1010 7 ' A,t
with numbers in a BCD format. These codes, as shown
+ 3F + 0011 1111 t 3 f,fi in Table 1-1. represent each decimal digit. 0 through 9,
69 1011 1001 with a 4-bit binary word. The BCD words are the same
11,0 25„,
as the binary equivalents for 0 through 9.
5,6 9,6
BCD ADDITION

BCD can have no digit-word with a value greater than 9.


IIGUKI I-I6 Hexadecimal addition. Therefore, a cany must be generated if the result of a

!4 CHAPTER ONE
BCD addition is greatei than loni or 9. Figure l 19 17 1 0111
shows three examples ol BCD addition. The first, In Fig
0 1001
urc l-19a, is very straightforward because the sum is
less than 9. rhe resull is the same as il would be foi 8 i HID Illegal BCD
si. inil. ii d Inn. ii \ 110 Subtract 6
leu the second example, In Figure I 19b, adding BCD
1000 8,,
7 in BCD 5 produces I 100. This is ,i correcl binary re
suli nl 12 bin il is an Illegal BCD code. Io converl Ihe IGURI I .Ml IK 1) m 11111, 11 (ion
resull io BCD format, .i correction factor ol 6 is added.
The rcsuli ol adding 6 is 0001 0010, which is the legal
BCD rude for 12.
BCD SUBTRACTION
Figure l-19c shows anothei case where .i correction
factoi must be added The initial addition ol 9 and 8 Figure 1 20 shows a subtraction <>i B< Dli (0001 01 1 1)
produces 0001 0001. Even though the lower lour digits minus BCD 9 (0000 1001). The initial result, 1 0
are less than 9, this is an incorrecl BOD resull because a 1110. is not a legal BCD number. Whenever this occurs
carry out of bit 3 of the BCD digit-word was produced. ill BCD sill ill, id ion. 0 must he subtracted from Ihe ini-
Tins carry out ol hit 3 is often called an auxiliary cany. tial resull Io produce Ihe correct BCD result. For the
Adding the correction factor of 6 gives the correct BCD example shown in Figure 1-20, subtracting 0 gives a
result of 0001 0111 or 17. correct BCD resull ol 0000 100(1 or 8.
To summarize, a correction factor of 6 must be added The correction factor of 0 must he subtracted from
to the result if the resull in the lower 4 bits is greatei any BCD digit-word il that digit-word is greater than
than 9 or if the initial addition produces a carry out of IO0I . or if a borrow from the next higher digil occurred
bit 3 of any BCD digit-word. This correction is some- during the subtraction.
times called
,i decimal adjust operation.
The reason lor the correction factor of 6 is that in BCD
we want a carry into the next digit after 1001 or 9. but in
binary a cany out of the lower four bits does not occur BASIC LOGIC GATES
until after 1111 or 15. which is 6 more than 9.
Microcomputers such as those we discuss throughoul
this book often contain basic logic gates as "glue" be-
BCD
tween(large
LSI scale integration) devices. For trouble-
35 0011 0101
shootingsystems
these it is important to be able to pre-
+ 23 -t 0010 0011 dict logic
levels at any point directly from Ihe schematic,
rather than having to work your way through a truth
58 0101 1000
table for each gate. This section should help refresh
( a) your memory of basic logic functions and help you re-
memberto how
quickly analyze logic gale circuits.
BCD
7 0111
Inverting and Non-inverting Buffers
+ 5 t 0101
Figure 1-21 shows the schematic symbols and truth
12 1100 Incorrect BCD tables for simple buffers and logic gates. The first tiling
to remember about these symbols is that the shape of
+ 110 Add 6
the symbol indicates the logic function performed by the
0U0 100 If) Correct BCD 12 device. The second thing Io remember about these sym-
bolsthat
is a bubble or no bubble indicates the asser-
(6)
tion level
for an input or output signal. Let's review how
modern logic designers use these symbols.
BCD The first symbol lor a buffer in Figure l-21a has no
1001 bubbles on the input or output. Therefore, the input is
+ 8
active high and the output is active high. We read this
+ 1000
symbol as follows. If the input. A. is asserted high, then
17 00010001 Incorrect BCD the output. Y, will be asserted high. The rest of the truth
110 Add 6 table is covered by the assumption that if the A input is
not asserted high, then the Y output will not be asserted
00010111 Correct BCD 17 high.
The next two symbols lor a hi i Her each contain a huh
(c)
ble. the bubble on the output of the first of these indi-
FIGURE 1-19 BCD addition, la) No correction needed. cates thatthe output is active low. The input has no
(b) Correction needed because of illegal BCD result. bubble so it is active high. You can read the function of
(c) Correction needed because of carry out of BCD the device directly from the schematic symbol as follows.
digit. If the A input is asserted high, then the Y output will be

COMPUTER NUMBER SYSTEMS, CODES, AND DICITAf 1)1 VI i is 15


Again bubbles or no bubbles are used to indicate the
assertion level of each input and output. The first AND
A X Y
symbol in Figure 1-2 lb has no bubbles so the inputs
0 0 1
and the output are active high. The output then will be
1 1 0
asserted high if the A input is asserted high AND the B
input is asserted high. The bubble on the output of the
second AND symbol in Figure 1-2 lb indicates that this
device, commonly called a NAND gate, has an active low
output. If the A input is asserted high and the B input is
asserted high, then the Y output will be asserted low.
4 e \ i

;=0* :=x> 1) i) ii 1
Look at the truth table in Figure 1-2 lb to see if you agree
with this.
1) i ii 1
Figure l-21c shows the other two possible cases for
Y = A %B Y = A +B 1 0 0 1
the AND symbol. The first of these has bubbles on the

:=C>' %:n>-< 1 i 1 II
inputs
schematic,
and on the outputs.
you should
If you see this symbol
immediately see that the output
in a

will be asserted low if the A input is asserted low AND


the B input is asserted low. The second AND symbol in
Figure l-21c has no bubble on the output, so the output
4 B V Y will be asserted high if the A AND B inputs are both
(i 0 II i asserted low.
0 1 1 ii A logic symbol with a curved back indicates that the
1 0 1 0 output of the device will be asserted if the A input is
1 1 1 n
asserted OR the B input of the device is asserted. Again
bubbles or no bubbles are used to indicate the assertion
level for inputs and outputs. Note in Figure 1-2 lb and
Figure l-21c that each of the AND symbol forms has an
equivalent OR symbol form. An AND symbol with active
4 fi \ 1 high inputs and an active high output, for example, rep-
II II 1) 1 resents
same
the device la 74LS08 perhaps) as an OR
symbol with active low inputs and an active low output.
3C^* :=E> II

1
I

II
1

1
II

II Use the truth table in Figure 1-2 lb to convince yourself


I I II 1
of this. The bubbled-OR representation tells you that if
one input is asserted low, the output will be low, regard-
lessthe
of state on the other input. As we will show later
in this chapter, this is often a useful way to think of the
FIGURE 1-21 Buffers and logic gates, (a) Buffers.
(b) AND— NAND. (c) OR— NOR. (d) Exclusive OR. operation of an AND gate.
Figure 1-2 Id shows the symbol and truth table for an
exclusive OR gate. The output of this device will be as-
asserted low. This device then simply changes the asser- serted
theif A input is asserted OR if the B input is
tion level
of a signal. The output, Y. will always have a asserted, but the output will not be asserted if both A
logic state which is the complement or inverse of that on AND B are asserted.
the input, so the device is usually referred to as an in- You need to be able to read all of these symbols, be-
verter. cause most
logic designers will use the symbol that best
The second schematic symbol for an inverter in Figure describes the function they want a device to perform in a
1-2 la has the bubble on the input. We draw the symbol particular circuit.
this way when we want to indicate that we are using the
device to change an asserted-low signal to an asserted-
high signal. For example, if we pass the signal CS Latches, Flip-flops, Registers, and Counters
through this device it becomes CS. The symbol tells you
directly that if the input is asserted low. then the output THE D LATCH
will be asserted high. Now let's review how you express A latch is a digital device that stores a one or a zero on
the functions of logic gates using this approach. its output. Figure l-22a shows the schematic symbol
and truth table for a D latch. The device functions as
follows. If the enable input. E. is low, any data present
Logic Gates on the D input will have no effect on the Q or Q outputs.
Figure 1-2 lb shows the symbols and truth tables for This is indicated in the truth table by an A" in the D
simple logic gates. A symbol with a flat back and a round column. If the enable input is high, a high or a low on
front indicates that the device performs the logical AND the D input will be passed to the Q output. In other
function. This means that the output will be asserted if words, the Q output will follow the D input as long as
the A input is asserted AND the B input is asserted. the enable input is high. The Q output will contain the

16 CHAPTER ONE
complement ol the logic state on (.). When the enable The I) Hip nop in Figure I 22b also has direct set IS|
Inpul is made low again, the state on Q al that time will ami reset (R) inputs a ihp Hup is considered set ii its (}
be latched there Anj changes on D will have no effecl on output is :. It is reset if its Q output is a zero. I In
Q until the enable Input is made high again. When the bubbles on the set and reset inputs tell you that these
enable inpui Lines low, then, the state present on I) insi inputs are active low. The truth table I or the I ) nip Hop
before the enable goes low will be stored on the Q out in Figure l 221) Indicates that the set and reset inputs
put. Keep ilus operation In mind as you read about the are asynchoriOUS. This means thai if the set input is
I) flip Hop In the next section. asserted low, the output will be set. regardless ol the
stale on the I) and the clock inputs. Likewise. II the
THI I) imp-hop reset input is asserted low. the Q output Will be reset,
regardless of the state of the D and clock inputs rheXs
The first type o\Jlip-lh>i> to review is the I) type. Figure
in the /' and CK columns ol the truth table remind you
l-22fa shows the schematic symbol and the truth table
that these inputs are "don't cares' it set Ol reset is ,is-
for ,i typical I) flip-flop. Note that this device has a clock
sei led. The condition indicated by the asterisks (*) is a
input. CK, in place of the enable input on the I) latch.
nonstable condition; that is. it will not persist when
Also note the up arrows in the clock column of the truth
reset or clear inputs return to their inacl ive (high) level.
table. These arrows are used to indicate that a one or
zero on the D input will be copied to the Q output at the
instant the clock input goes from low to high. In other THE )K FLIP-FLOP
words, the D flip-Hop takes a snapshot of whatever state Figure l-22c shows the schematic symbol and the truth
is on the D input when the clock goes high, and displays table for a common Ik Hip-Hop such as the 74LS76. The
the photo on the Q output. If the clock input is low, a two data inputs. ) and K make this device more versatile
change on D will have no effect on the output. Likewise. than a D Hip-Hop. The bubble on the clock input of the
if the clock input is high, a change on D will have no symbol and the downward arrows in the truth table in-
effect on the Q output. Contrast this operation with dicate that
the Q and Q outputs will only change when
that of the D latch to make sure you understand the the clock inpul goes from a high to a low. Changes on )
difference between the two devices. or K will have no effect on the output if the clock input is
low or if the clock input is high.
D t Q 0
If | and K are both low when the CK input goes low. the
outputs will remain the same as they were before the
X u QN On
clock edge. This is indicated by QN and QN in the truth
0 i 0 i
table. If ) is low and K is high at the time of the clock
1 l 1 0
edge. Q will become a zero. If | is high and K is low at the
time of the clock edge, Q will become a one. If | and K are
both high at the time of the clock edge, the Q output will
toggle. This means that it will change to the opposite
s R u CK a Q
state of what it was before the clock edge. The Ik Hip-Hop
1 1 1 t 1 0
also has asynchronous set and reset inputs which func-
D Q
1 0 1 n 1
1
tion the
same as those of the D Hip-Hop described previ-
>CK I 1 X II 0N (.',. ously.
1 1 X 1 oN On
II 1 X X t 0 REGISTERS
1 ii X X i) i
Flip-Hops can be used individually or in groups to store
0 v X binary data. A register is a group of D Hip-Hops con-
nected
parallel
in as shown in Figure l-23a. A binary
word applied to the data inputs of this register will be
transferred to the Q outputs when the clock input is
A fl CK Q Q made high. The binary word will remain stored on the Q
1) II 1 1 1 °N °N outputs until a new binary word is applied to the D in-
I.I 1 1 1 0 1 puts and
a low-to-high signal applied to the clock input.
1 0 1 1 1 0 Other circuitry can read the stored binary word from the
1 1 1 1 TOGGLE
Q outputs at any time without changing its value
'CK ,

If the Q output of each Hip-Hop in the register is con-


K _ Q
'
X 1 1 0 0N Qn
nected
the to D input of the next as shown in Figure
\ X 1 1 1 °N 0N
l-23b. then the register will function as a shift registei
X \ II 1 X 1 0
A one applied to the first D input will be shifted to the
1 1 11 X 0 1
%%
first Q output by a clock pulse. The next clock pulse will
shift this one to the output of the second Hip-Hop. Each
additional clock pulse will shift the one to the next Hip-
FIGURE 1-22 Latches and flip-flops, (a) D latch, (b) D Hop in the register. Some shift registers allow you to
flip-flop, (c) |-K flip-flop. load a binary word into the register and shift the loaded

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES 17


— n.
D,
a, — I
0,
iJ ij J

CK> *-

DATA
OUT

FIGURE 1-23 Registers, (a) Simple data storage, (b) Shift register.

word left or right when the register is clocked. As we will table counter functions, so there is no need to go into
show later in this chapter, the ability to shift binary the internal circuitry of the device. If the reset input is
numbers is very useful. asserted, the Q outputs will all be made zeros. After the
reset signal is unasserted, each clock pulse will cause
COUNTERS the binary count on the outputs to be incremented by
one. As shown in Figure l-24b. the count sequence will
Flip-Hops can also be connected in parallel to make
go from 0000 to 1111. If the outputs are at 1111, then
counters. Figure 1-24 shows a schematic symbol and
the next clock pulse will cause the outputs to "roll over"
count sequence for a presettablc 4-bit binary counter.
to 0000 and a carry pulse to be sent out the carry out-
The main point we want to review here is how a preset-
put. This
carry pulse can be used as the clock input tor
another counter.
Now. suppose that we want the counter to start count-
O, O, O, Q„ ing fromsome number other than 0000. We can do this
0 0 0 0 by applying the desired number to the four data inputs
and asserting the load input. For example if we apply a
binary 6, 01 10, to the data inputs and assert the load
> CLOCK input, this value will be transferred to the Q outputs.
D0 After the load signal is unasserted, the next clock signal
will increment the Q outputs to 0111 or 7. Counters
D,
such as this can be connected in series (cascaded! to
D-, 0.
produce counters of any desired number of bits.
D 0

LOAD

RESET ROMs, RAMs, and Buses


CARRY
flic next topics we need to review are the devices which
store large numbers of binary words and how combina-
tionsthese
of devices can be connected together.

ROMs

The term ROM stands for read-only memory. There are


several types of ROM that can be written to. read,
FIGURL 1-24 Four-bit, presettable binary counter. erased, and written to with new data, but the main fea-
1,1)Schematic symbol, (b) Count sequence. ture ROMs
of is that they are nonvolatile. This means

18 CHAPTFK ONt
,\ i mm ss ii

NCI l is

3DRESS
BUS

A ,

1, ",,i 4Q ^M

l< De «,, Dtt D, I), /J, l)„ D, Dh Db DA D3 D-, D, Dn

D0

DATA
BUS

O, i < %º

FIGURE 1-25 ROMs, (a) Schematic symbol, (fa; Connection in parallel.

that the information stored in them is not lost when the lines connect to each device to allow us to address one of
power is removed from them. the 32,768 words in each. A set of parallel lines used to
Figure l-25a shows the schematic symbol of a com- send addresses or data to several devices in this way is
mon ROM. As indicated by the eight data outputs. DO- called a bus. The data outputs of the ROMs are likewise
D7. this ROM stores 8-bit data words. The data outputs connected in parallel so that any one of the ROMs can
are three-state outputs. This means that each output output data on the common data bus. If these ROMs
can be at a logic low state, a logic high state, or a high- had standard two state outputs, a serious problem
impedance, floating state. In the high-impedance state would occur because each device would be trying to out-
an output is essentially disconnected from anything put an
addressed word onto the data bus. The resulting
connected to it. If the CE input of the ROM is not as- argument between data outputs would probably destroy
serted, all
thenof the outputs will be in the high-imped- some of the outputs and give meaningless information
ance state.
Also, most ROMs switch to a lower-power- on the data bus. Since the ROMs have three-state out-
consumption condition if CE is not asserted. If the CE puts, however,we can use external circuitry to make
input is asserted, the device will be powered up. and the sure that only one ROM at a time has its outputs en-
output buffers will be enabled. Therefore, the outputs abled. very
The important principle here is that when-
will be at a normal logic low or logic high state. You will ever several
outputs are connected on a bus. the outputs
soon see why this is important if you don't happen to should all be three-state, and only one set of outputs
remember. should be enabled at a time.
You can think of the binary words stored in the ROM At the beginning of this section we mentioned that
as being in a long, numbered list. The number that cor- some ROMs can be erased and rewritten or repro-
responds
each to stored word is called its address. In grammed with new data. Here's a summary of the differ-
order to get a particular word onto the outputs of the ent types of ROM.
ROM you have to do two things. You have to apply the
Mask-programmed ROM — Programmed during
address of that word to the address inputs, A0-A14, and
manufacture; cannot be altered.
you have to assert the CE input to turn on the outputs.
Incidentally, you can tell the number of binary words PROM — User programs by blowing fuses: cannot be
stored in the ROM by the number of address inputs. The altered except to blow additional fuses.
number of words is equal to 2N where N is the number of
EPROM — Electrically programmable by user: erased
address lines. The device in Figure l-25a has 15 ad-
by shining ultraviolet light on quartz window in
dress lines,A0-A14. so the number of words is 215 or
package.
32.768. In a data sheet this device would be referred to
as a 32K x 8 ROM. This means 32K addresses by 8 bits EEPROM — Electrically programmable by user; erased
per address.
with electrical signals instead of ultraviolet light.
Now. let's see why we want three-state outputs on this
STATIC AND DYNAMIC RAMs
ROM. Suppose that we want to store more than 32K
data words. We can do this by connecting two or more The name RAM stands for random-access memory, but
ROMs in parallel as shown in Figure l-25b. The address since ROMs are also random access, the name probably

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES 19


be refreshed every two milliseconds or so. A device called
a dynamic RAM refresh controller can be used to refresh
a large number of dynamic RAMs in a system. Some
newer dynamic RAM devices contain built-in refresh cir-
cuitry
they
so appear static to external circuitry.

Arithmetic Logic Units


Previous sections of this chapter reviewed ANDing.
ORlng, exclusive ORing. adding, and subtracting of bi-
nary numbers.A device which can perform any of these
functions and others on binary words is an arithmetic
logic unit or ALU. Figure l-27a shows a block diagram
for the 74LS181 which is a 4-bit ALU. This device can
perform any one of 16 logic functions or any one of 16
arithmetic functions on two 4-bit binary words. The
READ/WRITE
function performed on the two words is determined by
CHIP ENABLE the logic level applied to the mode input, M. and by the
4-bit binary code applied to the select inputs, S0-S3.
FIGURE 1-26 RAM schematic symbol.
Figure l-27b shows the truth table for the 74LS181.
In this truth table A represents the 4-bit binary word
applied to the A0-A3 inputs and B represents the 4-bit
should be read-write memory. RAMs are also used to binary word applied to the B0-B3 inputs. F represents
store binary words. A static RAM is essentially a matrix the 4-bit binary word that will be produced on the F0-F3
of nip-flops. Therefore, we can write a new data word in outputs. If the mode input. M. is high, the device will
a RAM location at any time by applying the word to the perform one of 16 logic functions on the two words ap-
flip-flop data inputs and clocking the flip-flops. The pliedtheto A and B inputs. For example, if M is high
stored data word will remain on the flip-flop outputs as and we make S3 high. S2 low. SI high, and SO high, the
long as the power is left on. This type of memory is vola- 4-bit word on the A inputs will be ANDed with the 4-bit
tile because data is lost when the power is turned off. word on the B inputs. The result of this ANDing will ap-
Figure 1-26 shows the schematic symbol for a com- pear the
on F outputs. Each bit of the A word is ANDed
mon RAM.
This RAM has 12 address lines. AO-Atl, so it with the corresponding bit of the B word to produce the
stores 212 14096) binary words. The eight data lines tell result on F. Figure l-27c shows an example of ANDing
you that the RAM stores 8-bit words. When we are read- two words with this device. As you can see in this exam-
ingword
a from the RAM these lines function as out- ple, output
an bit is high only if the corresponding bit is
puts. Whenwe are writing a word to the RAM. these high in both the A word AND in the B word.
lines function as inputs. The chip enable input, CE, is For another example of the operation of the 74LS 181,
used to enable the device for a read or for a write. The suppose that the M input is high. S3 is high, S2 is high,
R/W input will be asserted high if we want to read from S2 is high, and SO is low. According to the truth table the
the RAM or it will be asserted low if we want to write a device will now OR each bit in the A word with the corre-
word to the RAM. Here's how all these lines work for sponding
in the
bit B word and give the result on the
reading from and writing to the device. corresponding F output. Figure l-27c shows the result
To write to the RAM we applyjhe desired address to that will be produced by ORing two 4-bit words. Figure
the address inputs, assert the CE input low to turn on l-27c also shows for your reference the result that would
the device, and assert the R/W input low to tell the RAM be produced by exclusive ORing these two 4-bit words
we want to write to it. We then apply the data word we together.
want to store to the data lines of the RAM for a specified If the M input of the 74LS181 is low, then the device
time. To read a word from the RAM we address the de- will perform one of 16 arithmetic functions on the A and
sired word,assert CE low to turn on the device, and as- B words. Again the result of the operation will be put on
sert R/Whigh to tell the RAM we want to read from it. the F outputs. Several 74LS181s can be cascaded to op-
For a read operation the output buffers on the data lines erate words
on longer than 4 bits. The ripple-carry
will be enabled and the addressed data word will be pres- input. Cn. allows a carry from an operation on previous
ent onthe outputs. words to be included in the current operation. If the Cn
The static RAMs we have just reviewed store binary input is asserted low. then a carry will be added to the
words in a matrix of flip-flops. In dynamic RAMs results of the operation on A and B. For example if the M
(DRAMs). binary l's and 0's are stored as an electrical input is low, S3 is high, S2 is low, SI is low, SO is high,
charge or no charge on a tiny capacitor. Since these tiny and Cn is low, the F outputs will have the sum of A plus B
capacitors take up less space on a chip than a flip-flop plus a carry.
would, a dynamic RAM chip can store many more bits The real importance of an ALU such as the 74LS 18 1 is
than the same size static RAM chip. The disadvantage of that it can be programmed with a binary instruction
dynamic RAMs is that the charge leaks off the tiny ca- applied to its mode and select inputs to perform many
pacitors.
logic
The state stored in each capacitor must different functions on two binary words applied to its

20 CHAPTER ONE
ACTIVE-HIGH DATA
SELECTION
M H M 1 , AMI 1 lir.1l III i >l'l H "%
LOGIC
S3 S2 SI SO FUNCTIONS H (no carry) ( rj 1 (with carry)

L L L L / A F = A F = A PLUS 1
1 L L H ' A i B F = A * B F ~ (4 ) S) PLUS 1
L 1 H L I At; F = A i li Z7 WiS] PLUS 1
1 L II H I (1 F MINUS 1 (2'sCOMPLI F - ZERO
1 H 1 L F = AB F - A PLUS AB f = 4 PLUS4« PLUS 1
L M 1 H F = B F • {A + B) PLUS4S F = (4 + S) PLUS 40 PLUS 1
1 H H L F = A®B F = A MINUSff MINUS 1 f = 4 MINUSS
1 M H H F = AB F - AB MINUS 1 f = AB
M 1 L L r a i /; F = A PLUS AB F = 4 PLUS4S PLUS 1
H L 1 H F = 4©B F = A PLUSS F = 4 PLUS ff PLUS 1
M L M L F = B F= [A +fi) PLUSES F= (4 +B) PLUS 4S PLUS 1
H 1 H H F = AB F = 4flMINUS 1 F = 4S

H M I L F = 1 F = /1 PLUS4 F= 4 PLUS4 PLUS 1


M II 1 II F = A + B f= W +S) PLUS A f = (4 +fi) PLUS 4 PLUS 1
H H H 1 F = A + B F = {A i B) PLUS A F = (4 + S) PLUS 4 PLUS 1
H H H H F = A F = A MINUS 1 f = 4

n I 1 0

^ / F F0
n II 1 0

^3 / F, F0
1 1 1 0

4©e

FIGURE 1-27 Arithmetic logic unit (ALU), (a) Schematic symbol, (fa) Truth table.
(c) Sample AND, OR, XOR operations.

data inpLits. In other words, instead of having to build a Seven-segment display code
different circuit to perform each of these functions, we
Alphanumeric codes: ASCII, BCDIC, EBCDIC.
have one programmable device. We can perform any of
Selectric, Hollerith
the operations that we want in a computer with a se-
quence
simple
of operations such as those of the Parity bit, odd parity, even parity
74LS181. Therefore, an ALU is a very important part of
the microprocessors and microcomputers which we dis- Converting between binary, octal, hexadecimal, BCD
cussthe
in next chapter. Arithmetic with binary, octal, hexadecimal. BCD

BCD decimal adjust operation


CHECKLIST OF IMPORTANT TERMS AND Signed numbers, sign bit
CONCEPTS IN THIS CHAPTER
2's complement sign-and-magnitude form
If you do not remember any of the terms or concepts in
Signal assertion level
this list, use the index to find them in the chapter.
Inverting and noninverting buffers
Binary, bit, nibble, byte, word, double word
Symbols and truth tables for AND, NAND. OR. NOR.
LSB, MSB, LSD, MSD XOR logic gates.
Octal, hexadecimal, standard BCD, Gray code D latch. D flip-flop, Ik nip-flop

COMPUTER NUMBER SYSTEMS,CODES, AND DIGITALDEVICES 21


Register, shift register, binary counter PROM. EPROM, EEPROM

ROM: address lines, data lines, bus lines RAM: static, dynamic
nonvolatile volatile
three-state READ/WRITE input
cascaded outputs ALU
enable input

REVIEW QUESTIONS AND PROBLEMS


1. Convert the following decimal numbers to binary: 11. Express the following decimal numbers in 8-bit
a. 22 sign-and-magnitude form:
b. 76 a. +26

c. 500 b. -7
c. -26
2. Convert the following binary numbers to decimal: d. -125
a. 1011
b. 11010001 12. Show the subtraction, in binary, of the following
c. 1110111001011001 decimal numbers using both the pencil method
and the 2's complement addition method:
3. ('(invert to following numbers to octal:
a. 7-4
a. 110101001 binary b. 37 - 26
b. 1 1 decimal
c. 1 25 - 93
c. 111011101100 binary
13. Show the multiplication of 1001 and 011 by the
4. Convert the following octal numbers to decimal:
pencil method. Do the same for 11010 and 101.
a. 314
b. 74 14. Show the division of 1 100100 by 1010 using the
c. 43 pencil method.

5. Convert to hexadecimal: 15. Perform the indicated operations on the following


a. 53 decimal numbers:
b. 756 decimal a. The octal numbers 27+16

c. 01101100010 binary b. The octal numbers 132-45

d. 1 10000101 1 1 binary c. 3AH + 94H


d. 17AH - 4CH
6. Convert to decimal:
e. 0101 1001 BCD
a. 1)311
+ 0100 0010 BCD
b. 3FEH
c. 44H

7. Convert the following decimal numbers to BCD: 0111 1001 BCD

a. 86 + 0100 1001 BCD

b. 62
c 33
0101 1001 BCD
S. The L key is depressed on an ASCII-encoded key- 0010 0110 BCD
board. What
pattern of 1 's and 0's would you expect
to find on the seven parallel data lines coming from
the keyboard? What pattern would a carriage re- 0110 01 11 BCD
turn, CR,
give? 001 1 1001 BCD

9. Define parity and describe how it is used to detect


.in ii i in ni I ransmitted data.

10. Show addil inn of: 16. For the circuit in Figure 1-28

a. 1001 I , and 101 I , m binary a. Is the Y output active high or active low?
I). 37|0 and 2510 in BCD b. Is the C signal active high or active low?
c. 37H and 25R in octal c. What input conditions on A. B. and C will

(/. 4A1I and 77H cause the Y output to be asserted?

22 CHAPT1K ONI
19. Why do most ROMs and RAMs have three stale out
puts?
20. Using Figure I 27, show the programming "I th<
select and modi- Inputs the 74181 requires to pi i
form the following arithmeti< functions:
a. A i B
I). A MINUS li MINUS I
c. A PLUS li

21. show the output word produced when the follow


ing binary words arc ANDed with each other and
when they aic ORed with each other:
FIGURE 1-28 Circuit for Problem 1-16.
a. 1010 and 01 I I
b. Kill and I 100
17. What is the main difference between .i I) latch and C I 10101 I 1 and 1 1 1000

a I) nip-flop? d. ANDing an 8-bit binary number with 1111


0000 is sometimes referred to as "masking"
IS. I lie National Semiconductor INS8298 is a 65.536-
the lower 4 bits. Why':'
hii l\( )M organized as 8 192 words or bytes "I 8 bits
How many address lines arc required to address
one oi the 8192 bytes?

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES 23


CHAPTER

Computers, Microcomputers,
and Microprocessors —An
Introduction
We live in a computer oriented society and we are con- parallel lines called buses. The three buses are the ad-
stantly bombardedwith a multitude of terms relating to dress bus.the data bus. and the control bus.
computers. Before getting started with the main flow of
the book we will t ry to clarify some of these terms and to MEMORY
give an overview of computers and computer systems.
The memory section usually consists of a mixture of
RAM and ROM. It may also have magnetic floppy disks,
OBJECTIVES magnetic hard disks, or laser optical disks. Memory has
two purposes. The first purpose is to store the binary
At the conclusion of this chapter you should be able to: codes for the sequence of instructions you want the
computer to carry out. When you write a computer pro-
1. Define the terms: microcomputer, microprocessor, gram, what
you are really doing is just writing a sequen-
hardware, software, firmware, time share, multi- tial list
of instructions for the computer. The second
tasking, distributed
processing, and multiprocess- purpose of the memory is to store the binary-coded data
ing. with which the computer is going to be working. This
2. Describe how a microcomputer fetches and executes data might be the inventory records of a supermarket,
an instruction.
for example.

3. List the registers and other parts in the 8086/8088 INPUT/OUTPUT


execution unit and bus interface unit.
The input/output or I/O section allows the computer to
4. Describe the function of the 8086/8088 queue. take in data from the outside world or send data to the
outside world. Peripherals such as keyboards, video dis-
5. Demonstrate the way in which the 8086/8088 calcu-
play terminals, printers, and modems are connected to
lates memory addresses.
the I/O section. These allow the user and the computer
to communicate with each other. The actual physical
COMPUTERS devices used to interface the computer buses to external
systems are often called ports. Ports in a computer func-
What is a Computer? tion justas shipping ports do for a country. An input
Figure 2-1 shows a block diagram for a simple com- port allows data from a keyboard, an analog-to-digital
puter. The
major parts are the central processing unit (ADI converter, or some other source to be read into the
or CPU. memory, and the input and output circuitry or computer under control of the CPU. An output port is
I O. Connecting these parts together are three sets of used to send data from the computer to some peripheral

INPUT
DEVICE
I
CONTROL CENTRAL CONTROL
1 0 BUS BUS MEMORY
PROCESSING
PORTS UNIT
(RAM AND
ROM)
(CPUI
OUTPUT
DEVICE '

ADDRESS BUS

I K ,1 IR[ J- 1 Bloi k diagrams ol a simple computer or microcomputer.

24
such as a video display terminal, a printer, 01 .1 digital HARDWARE, SOFTWARE, AND FIRMWARI
to-analog il ' A) 1onvertei Physically, an input 01 outpul When working around computers you hear the terms
port is often just .1 set ol parallel l> Hip Hops which let hardware, software, and firmware almost constantly.
data pass through when they arc enabled or clocked by a Hardware is the name given to the physical devices and
control signal from the CPU. * in iiiiiv ol the computer. Software refers 10 the pro-
grams written
foi the computer. Firmware is the term
CENTRAL PROCESSING UNIT
given i<> programs stored in ROMs or in oilier devices
riic central processing unit or CPU controls the opera which keep theii stored Information when the power is
tion of (lie computer, li fetches binary coded instruc- turned nil
tions from
memory, decodes the instructions into a se
1 irs 0! simple actions, and carries out these actions. The Execution of a Three-Instruction Program
CPU contains an arithmetic logic unit, or ALU. which
can perform add, subtract. OR, AND. invert, or exclu EXECUTION SEQUENCE
sue t )R operations on binary words when instructed to
do so. The CPU also contains an address countei which To line you a better idea ol how the pai is 1ii .; i omputer
function together, we will now describe the aiiions .1
is used to hold the address ol the next instruction or
data to be fetched from memory, general-purpose regis- simple computer might go through to tarn- out [exe
ters whichare used for temporary storage of binary data, cute) .1 simple program. The three instructions of the
and circuitry which generates the control bus signals. program are:

ADDRESS BUS 1. Input a value from a keyboard connected to tin- port


at address 051 1.
The address bus consists of 16. 20. 24. or more parallel
signal lines. On these lines the CPU sends out the ad- 2. Add 7 to the value read in.
dressthe
of memory location that is to be written to or
3. Output the result to a display connected to the port
read from. The number of memory locations that the
at address 02H.
CPU can address is determined by the number of ad-
dress lines.If the CPU has N address lines then it can
Figure 2-2a shows in diagram form the actions that the
directly address 2 to the N power memory locations. For
computer will perform to execute these three instruc-
example, a CPU with 16 address lines can address 2"' or
tions.
65.536 memory locations, a CPU with 20 address lines
For this example assume that the CPU fetches in-
can address 220 or 1.048.576 locations, and a CPU with
structions
dataand from memory one byte at a lime.
24 address lines can address 224 or 16.777,216 loca-
Also assume that the binary codes for the instructions
tions. When
the CPU reads data from or writes data to a
are in sequential memory locations starting at address
port, the port address is also sent out on the address
00100H. Figure 2-2b shows the binary codes that would
bus.
be required in successive memory locations to execute
DATA BUS this program on an 8086- or 8088-based microcom-
puter.
The data bus consists of 8. 16. 32 or more parallel sig- The first action a computer will do is to fetch the first
nal lines. As indicated by the double-ended arrows on instruction byte from memory. To do this the CPU sends
the data bus line in Figure 2-1. the data bus lines are out the address of trie first instruction byte, in this case
bidirectional. This means that the CPU can read data in 00100H, to memory. This action is represented by line
on these lines from memory or from a port as well as 1A in Figure 2-2a. The CPU then sends out a memory'
send data out on these lines to a memory location or to a read signal on the control bus (line IB in the figure).
port. Many devices in a system will have their outputs This causes the memory to output the first instruction
connected to the data bus. but the outputs of only one byte (E4HI on the data bus as represented by line 1C.
device at a time will be enabled. Any device outputs con- The CPU reads in the byte from the data bus and de-
nected
theon data bus must be three-state so that they codesByit. decode we mean that the CPU determines
can be floated when the device is not in use. from the binary code read in what actions it is supposed
to take. In this case the CPU determines that the code
CONTROL BUS read in represents an input instruction. Also from de-
The control bus consists of 4-10 parallel signal lines. coding instruction
this byte, the CPU determines that it
The CPU sends out signals on the control bus to enable needs more information before it can carry out the in-
the outputs of addressed memory devices or port de- struction.
CPUThe must fetch from memory the input
vices. Typical
control bus signals are memory read, port address. To do this the CPU sends out the next se-
memory write. I/O read, and I/O write. To read a byte of quential address
(00101H) to memory as indicated by
data from a memory location, for example, the CPU line 2A in the figure. The CPU also sends out another
sends out the address of the desired byte on the address memory read signal on the control bus (line 2B). This
bus and then sends out a memory read signal on the enables the memory' to put the addressed byte on the
control bus. The memory read signal enables the ad- data bus (line 2C). When the CPU reads in this second
dressed memory
device to output the byte of data onto byte. 05H in this case, it has all the information it needs
the data bus where it is read by the CPU. to execute the instruction.

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS— AN INTRODUCTION 25


FIGURE 2-2 (a) Execution of a three-step computer
program, (b) Memory addresses and memory contents
for a three-step program.

6A 5A 4A 3A 2A 1A IB 2B 3B 4B 5B 1C 2C 3C 4C 5C 6C
i i i i i i
L CONTROL BUS J
3 on
m 3

£ CPU <
s <
<

r CONTROL

1
BUS

1 n
6D 2D 2E 6F

\ I
L
I/O

PORT 05

PROGRAM '

: 6
1. Input a value from port 05. •

2. Add 7 to this value.


3. Output the result to port 01

SEQUENCE

1A CPU sends out address of first instruction to memory.


IB CPU sends out memory read control signal to enable memory.
1C Instruction byte sent from memory to CPU on data bus.
2A Address next memory location to get rest of instruction.
2B Send memory read control signal to enable memory.
2C Port address byte sent from memory to CPU on data bus.
2D CPU sends out port address on address bus.
2E CPU sends out input read control signal to enable port.
2F Data from port sent to CPU on data bus.
3A CPU sends address of next instruction to memory.
3B CPU sends memory read control signal to enable memory.
3C Instruction byte from memory sent to CPU on data bus.
4A CPU sends next address to memory to get rest of instruction.
4B CPU sends memory read control signal to enable memory.
4C Number 07H sent from memory to CPU on data bus.
5A CPU sends address of next instruction to memory.
5B CPU sends memory read control signal to enable memory.
5C Instruction byte from memory sent to CPU on data bus.
6A CPU sends out next address to get rest of instruction.
6B CPU sends out memory read control signal to enable memory.
6C Port address byte sent from memory to CPU on data bus.
6D CPU sends out port address on address bus.
6E CPU sends out data to port on data bus.
6F CPU sends out output write signal to enable port.

26 CHAPTER TWO
AEMi >R> CONTENTS CONTENTS ( )PI RATION
\DDRESS (BINARY) illl X)

001001 I 1 1 10(1100 L4 INPU1 FROM


00101H ooooolol 0r) POR1 05H
00102H 0000010(1 04 Al )l )
00103H 000(101 11 0 0711

00104H 1 1 100 MO E6 outpui ro


0010 -1 1 000000 10 02 P( )KI 02

To execute the inpul instruction the ('I'll sends oul vice so


the dala from the data bus lines can pass
the pent address (05H) on (he address bus (line 2D\ and through i(. When the CPU removes the I/O write signal
sends oul an 1 ( ) read si una 1 on (lie eon I ml bus Mine 2EI. to proceed with the next instruction, the data output
The addressed port device (hen puis a byte of data on will remain latched on the output pins of the porl de-
the data bus (line 2F). The CPU reads in the byte of data vice. Therefore,the computer does not have to keep oul
and stores it in an internal register called the accumu- putting a value in order for it to remain there.
lator. This
completes the first instruction. All of the steps described above may seem like a great
Having completed the first instruction, the CPU must deal of work just to input a value from a keyboard, add 7
now fetch its next instruction from memory. To do this to it. and output the result to a display. Even a simple
it sends out the next sequential address (00102H) on computer, however, can run through all these steps in a
the address bus (line 3A). The CPU then sends out a few microseconds.
memory read signal on the control bus (line 3B). This
allows the memory to put the addressed byte (04H) on SUMMARY OF SIMPLE COMPUTER OPERATION
the data bus (line 3C). The CPU reads in the instruction 1. A simple computer CPU fetches instructions or
byte from the data bus and decodes it. From the instruc- reads data from memory (reads memory) by sending
tion byte
the CPU determines that it is supposed to add out an address on the address bus and a memory
some number to the number stored in the accumulator. read signal on the control bus. The addressed in-
The CPU also determines from this instruction byte that struction
data oris sent from memory to the CPU on
it must go to memory again to get the number that it is
the data bus.
supposed to add. To get the required byte, the CPU will
send out the next sequential address (00103H1 on the 2. The CPU can write data in RAM by sending out an
address bus (line 4A] and a memory read signal on the address on the address bus, sending out the data to

control bus (line 4B). The memory will then put the con- be written on the data bus. and sending out a mem-
tentsthe
of addressed byte (in this case the number ory write signal on the control bus.
07H) on the data bus (line 4C). The CPU will read in the
3. To read data from a port, the CPU sends the port
byte on the data bus and add it to the contents of
address out on the address bus and sends an I/O
the accumulator as instructed. Assume the result of the read signal on the control bus. Data from the port
addition is left in the accumulator. This completes the
comes into the CPU on the data bus.
second instruction.
The CPU must now fetch its next instruction. To do 4. To write data to a port, the CPU sends out the port
this it sends out the next sequential address (00104H) address on the address bus, sends the data to be
on the address bus (line 5A). sends out a memory read written to the port out on the data bus, and sends
signal on the control bus (line 5B). and reads in the ad- an I/O write signal out on the control bus.
dressed (E6H)
byte from the data bus (line 5C). From
5. A microcomputer fetches each program instruction
this byte the CPU determines that it is now supposed to
in sequence, decodes the instruction, and executes
do an output operation to a port. The CPU also deter-
mines that
it must go to memory again to get the ad- it.
dress
theof port that it is supposed to output to. To do
this it sends out the next sequential address (00105H)
Types of Computers
on the address bus (line 6A), sends out a memory read
signal on the control bus (line 6B). and reads in the byte
MAINFRAMES
(02HI put on the data bus by the memory (line 6C\. The
CPU now has all the information that it needs to execute Computers come in a wide variety of sizes and capabili-
the instruction. To output a data byte to a port, the CPU ties. The
largest and most powerful are often called
first sends out the address of the desired port on the mainframes. Mainframe computers may fill an entire
address bus (line 6D), Next it puts the data byte from the room. They are designed to work at very high speeds
accumulator onto the data bus (line 6E). The CPU then with large data words, typically 64 bits or greater, and
sends out an I/O write signal on the control bus (line they have massive amounts of memory. Computers of
6F1. This signal enables the addressed output port de- this type are used for military defense control, business

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS— AN INTRODUCTION 27


business data processing, industrial control (an oil re-
finery,
example),
for and scientific research. Examples
of this type of computer are the Digital Equipment Corp.
VAX 1 1/730 and the Data General MV/8000II. Figure
2-35 shows a photograph of a Digital Equipment Corp.
VAX 1 1/730 minicomputer.
MICROCOMPUTERS

As the name implies, microcomputers are small com-


puters. They
range from small controllers that work di-
rectly with
4-bit words and can address a few thousand
bytes of memory to larger units that work directly with
32-bit words and can address millions or billions of
bytes of memory. Some of the more powerful microcom-
puters have
all or most of the features of earlier mini-
computers. Therefore,
it has become very hard to draw a
sharp line between these two types. One distinguishing
feature of a microcomputer is that the CPU is usually a
single integrated circuit called a microprocessor. Older
books often used the terms microprocessor and micro-
computer interchangeably, but actually the micropro-
cessor
the isCPU to which you add ROM. RAM. and ports
to make a microcomputer. A later section in this chapter
discusses the evolution of different types of micropro-
cessors. Microcomputers are used in everything from
smart sewing machines to computer-aided design sys-
tems. Examples of microcomputers are the Intel 8051
single-chip controller; the SDK-86. a single-board com-
puter designkit: the IBM Personal Computer (PC); and
the Apple Macintosh computer. Figure 2-4a shows a
block diagram of the Intel 8051 single-chip microcon-
troller. Figure
2-4b shows the SDK-86 board, and Figure
2-4c shows the IBM PC. The purpose of this book is to
teach you how microprocessors are connected with other
components to build microcomputers, how the micro-
computers
interfaced
are with peripheral components to
build microcomputer systems, and how these systems
are programmed. We use the IBM PC and the SDK-86
as example systems throughout this book. An available
laboratory manual, written to accompany this book,
shows you how to get started using the SDK-86 board
and the IBM PC for assembly language programming.

SUMMARY OF IMPORTANT POINTS SO FAR


FIGURE 2-3 (a) Photograph of IBM mainframe computer. 1. A computer or microcomputer consists of memory, a
(IBM Corp.) (b) Photograph of DEC minicomputer. CPU. and some input/output circuitry.
(Digital Equipment Corp.)
2. These three parts are connected together by the ad-
data processing (an insurance company, for example), dress bus.
the data bus. and the control bus.
and for creating computer graphics displays for science
3. The sequence of instructions, or program, for a
fiction movies. Examples of this type of computer are
computer is stored as binary numbers in successive
the IBM 438 1. the Honeywell DPS8. and the CRAY X-MP/
48. Figure 2-3a shows a photograph of an IBM 4381 memory locations.
mainframe. 4. The CPU fetches an instruction from memory, de-
codes the
instruction to determine what actions
MINICOMPUTERS must be done for the instruction, and carries out

Scaled-down versions of mainframe computers are often these actions.


called minicomputers. The main unit of a minicomputer
5. Three types of computer are mainframes, minicom-
usually fits in a single rack or box. A minicomputer runs
puters,microcomputers.
and
more slowly, works directly with smaller data words
(often :'»2-bit words), and does not have as much mem- 6. The CPU in a microcomputer is called a microproc-
ory aas mainframe. Computers of this type are used for essor

2H CHAPTER TWO
f±± ±±ri


i[ ii
i i i II

wn

COMPUTERIZING AN ELECTRONICS FACTORY-


PROBLEM

Now. suppose that we want to "computerize" an elec-


tronics company.By this we mean that we want to make
computer use available to as many people in the com-
panypossible
as as cheaply as possible. We want the
engineers to have access to a computer which can help
them design circuits. People in the drafting department
should have access to a computer which can be used for
computer-aided drafting. The accounting department
should have access to a computer for doing all of the
financial bookkeeping. The warehouse should have ac-
cessa tocomputer to help with inventory control. The
manufacturing department should have access to a
computer for controlling machines and testing finished
products. The president, vice presidents, and supervi-
sors should have access to a computer to help them with
long range planning. Secretaries should have access to a
computer for word processing. Sales people should have
access to a computer to help them keep track of current
pricing, product availability, and commissions. There
are several ways to provide all the needed computer
power. The next sections discuss some of the ways that
are used to give people access to a computer.
FIGURE 2-4 (a) Block diagram of Intel 8051 single chip
microcomputer. (Intel Corp.) (b) Photograph ot Intel BATCH PROCESSING
SDK-86 board. (Intel Corp.) (c) Photograph ot IBM PC.
(IBM Corp.) In the 1960s the available computers were very large and
were kept in separate air-conditioned rooms. When pro-
grammers wanted
to run their programs, they brought
How Computers and Microcomputers are them to the computer room. Usually the program was in
Used — An Example the form of a batch of punched cards. A computer opera-
The following sections are intended to give you an over- tor wouldthen run the program. A new programming
viewhow
of computers are interfaced with users to do job could not be started until the last one finished.
useful work. These sections should help you understand Therefore, if a large job was being run. there might be a
many of the features designed into current microproces- considerable wait before a programmer could get his or
sors and
where this book is heading her job run. Also, if an error was found when the pro-

COMPUTERS, MICROCOMPUTERS, AND Ml( KOPRl )( ISSORS— AN INTRODUCTION 29


gram ran. the programmer had to punch new cards, and computer can serve many users by dividing its time
either bribe the computer operator or put the corrected among them in small increments. In other words, the
program cards on the bottom of the jobs-to-be-done pile. computer works on user #l's program for perhaps 20
Needless to say. a system of this sort is not acceptable milliseconds, works on user #2's program for 20 milli-
for computerizing our electronics company, because it seconds,works
then on user #3's program for 20 milli-
only serves one user at a time and does not allow easy seconds,so andon until all all the users have had a
back-and-forth interaction between the computer and turn. In a few milliseconds the computer will get back to
the user. user #1 again and repeat the cycle. To each user it will
appear as if he or she has exclusive use of the computer
MULTIPROGRAMMING because the computer processes data as fast as the user
enters it. A time-share system such as this allows sev-
An improvement over the basic batch system is a multi-
eral usersto interact with the computer at the same
programming In system.
this type of system several pro-
time. Each user can get information from or store infor-
gramsputare in the computer's memory at the same mation
the in large memory attached to the computer.
time. The computer runs one programming job until it
Each user can have an inexpensive printer attached to
reaches a point where it needs access to some slow pe-
the terminal or can direct program or data output to a
ripheral device
such as a printer. If the printer is not
high-speed printer attached directly to the computer.
busy, the computer will print out the produced results.
An airline ticket reservation computer might use a
If the printer is busy, the data to be printed is stored on
time-share system such as this to allow users from all
a magnetic disk. The computer can then start another
over the country to access flight information and make
programming job while it waits for the printer to be-
reservations. A time-multiplexed or time-sliced system
come available.When the printer becomes available, the
such as this can also allow a computer to control many
computer can print out the results from the first pro-
machines or processes in a factory. A computer is much
gram, and
then return to the second program. To fur-
faster than the machines or processes. Therefore, it can
ther reducethe burden on the computer, some com-
check and adjust many pressures, temperatures, motor
puters have
separate circuitry that takes care of copying
speeds, etc. before it needs to get back and recheck the
output data from magnetic disks to the printer. Multi-
first one. A system such as this is often called a multi-
programming the
improves
efficiency of the computer
tasking system
because it appears to be doing many
by keeping it busy more of the time, but it still does not
tasks at the same time.
allow the user to easily interact with the computer.
Now let's take another look at our problem of comput-
erizingelectronics
the company. A time-share system
TIME-SHARE AND MULTITASKING SYSTEMS
seems to be a better idea than a batch system or even a
A further improvement in computer access is timeshar- multiprogramming system. We could put a powerful
ing. Figure2-5 shows a block diagram of one type of computer in some central location and run wires from it
time-share system. Several video terminals are con- to video display terminals on users' desks. Each user
nected
the tocomputer through direct wires or through could then run the program needed to do a particular
telephone lines. The terminal can be on the user's desk task. The accountant can run a ledger program, the sec-
or even in the user's home. The rate at which a user retaryrun
can a word processor program, etc. Each user
usually enters data is very slow as compared to the rate can access the computer's large data memory. Inciden-
that a computer can process the data. Therefore, the tally,
large
a collection of data stored in a computer's

MASS COMPUTER
DATA (MAINFRAME
STORAGE OR MINI)

VIDEO VIDEO
PRINTER LOW-COST
VIDEO TERMINAL TERMINAL
VIDEO PRINTER
ERMINAL TERMINAL

FIGURE 2-5 Block diagram of a computer time-share system.

30 CHAPTFR TWO
MA If: I RAMI Hll ,11 Mi I :
STORAGE COMPUTER PRINTER

CONNI l 1 ION II!


PHONE LINE

FLOPPY DISK
DRIVE

%¡ \Q_\Q
PRINTER MICROCOMPUTER

VIDEO TERMINAL VIDEO TERMINAL VIDEO TERMINAL

FIGURE 2-6 Block diagram of distributed processing computer system.

memory is often referred to as a data base. For a small means that a person can do many tasks locally on the
company a system such as this might be adequate. microcomputer without having to use the large com-
However, there are at least two potential problems. puter
all.at Since the microcomputers are connected to
The first potential problem is "What happens if the the large computer with a network, however, a user can
computer is not working?" The answer to this question access the computing power, memory, or other re-
is that everything grinds to a halt. In a situation where sources
the oflarge computer when needed.
people have become dependent upon the computer, not Distributing the processing around to multiple com-
much gets done until the computer is up and running puters
processors
or in a system has several advantages.
again. The old saying about putting all your eggs in one First, if the large computer goes down, the local micro-
basket comes to mind here. computers
continue
can working until they need to ac-
The second potential problem of the simple time cess the
large computer for something. Second, the bur-
share system is saturation. As the number of users in- den on
the large computer is reduced greatly, because
creases,
timetheit takes the computer to do each user's much of the computing is done by the local microcom-
task increases also. Eventually the computer's response puters. Finally,
the distributed processor approach al-
time to each user becomes unreasonably long. People lows system
the designer to use a local microcomputer
get very upset about the time they have to wait. best suited to the task it has to do.

DISTRIBUTED PROCESSING OR COMPUTERIZED ELECTRONICS COMPANY


MULTIPROCESSING OVERVIEW

A partial solution for the two potential problems of a Distributed processing seems to be the best way to go
simple time-share system is to use a distributed proces- about computerizing our electronics factory. Engineers
sor system.Figure 2-6 shows a block diagram for such a can each have a personal computer on their desk. With
system. The system has a powerful central computer this they can use available programs to design and test
with a large memory and a high-speed printer as does circuits. They can access the large computer if they need
the simple time-share system decribed previously. How- data from its memory. Through the telephone lines, the
ever,this
in system each user or group of users has a engineer with a personal computer can access data in
microcomputer instead of simply a video display termi- the memory of other computers all over the world. The
nal.other
In words, each user station is an independent drafting people can have personal computers for simple
functioning microcomputer with a CPU, ROM, RAM, work, or large computer-aided design systems for more
and probably magnetic or optical disk memory'. This complex work. Completed work can be stored in the

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS— AN INTRODUCTION 31


large computer memory. The accounting department quentialdevices.
logic Also, the ability to change the
can use personal computers with spread sheet pro- function of a system by just changing the programming,
grams
workto with financial data kept in the memory of rather than redesigning the hardware, is very appeal-
the large computer. The warehouse supervisor can like- ing.was
It these factors that pushed the evolution of
wise use
a personal computer with an inventory pro- microprocessors.
gramkeep
to personal records and those in the large In 1972 Intel came out with the 8008 which was capa-
computer's memory updated. Corporate officers can ble ofworking with 8-bit words. The 8008, however,

have personal computers tied into the network. They required 20 or more additional devices to form a func-

then can interact with any of the other systems on the tional CPU.
In 1974 Intel announced the 8080, which

network. Sales people can have portable personal com- had a much larger instruction set than the 8008 and
puters they
that can carry with them in the field. They only required two additional devices to form a functional

can communicate with the main computer over the tele- CPU. Also, the 8080 used NMOS transistors, so it oper-
phone lines
using a modem. Secretaries doing word pro- ated muchfaster than the 8008. The 8080 is referred to

cessing
usecanindividual word processing units or per- as a second-generation microprocessor.
sonal computers.Since word processing is not a high Soon after Intel produced the 8080. Motorola came
intensity use for a computer, several video display ter- out with the MC6800, another 8-bit general-purpose
minals
wordfor processing can be connected to a local CPU. The 6800 had the advantage that it required only a
microcomputer, and this local microcomputer can be + 5 V supply rather than the -5 V, +5 V, and +12 V
connected to the large computer through the network. supplies required by the 8080. For several years the
Users can also send messages to each other over the net- 8080 and the 6800 were the top-selling 8-bit microproc-
work. specifics
The of a computer system such as this essors. Some
of their competitors were the MOS Tech-
will obviously depend on the needs of the individual nology 6502
used as the CPU in the Apple II microcom-
company for which the system is designed. puter, and
the Zilog Z80 used as the CPU in the Radio
Shack TRS-80 microcomputer.
SUMMARY AND DIRECTION FROM HERE As designers found more and more applications for
microprocessors, they pressured microprocessor manu-
The main concepts that you should take with you from
facturers
develop
to devices with architectures and fea-
this section are multiprogramming, time-sharing or
tures optimizedfor doing certain types of tasks. In re-
multitasking, and distributed processing or multiproc-
sponse
the toexpressed needs, microprocessors have
essing.
youAswork your way through the rest of this
evolved in three major directions during the last 10
book, keep an overview of the computerized electronics
company in the back of your mind. The goal of this book years.
is to teach you how all the parts of a system such as this
DEDICATED CONTROLLERS
work, how the parts are connected together, and how
the system is programmed at different levels. One direction has been dedicated controllers. These
The first step toward this goal will be a quick look at devices are used to control "smart" machines such as
the different types of microprocessors available. We then microwave ovens, clothes washers, sewing machines,
discuss a specific microprocessor, the Intel 8086. and auto ignition systems, and metal lathes. Texas Instru-
the programming of a microcomputer built around a ments producedmillions of their TMS-1000 family of
member of this microprocessor family, the IBM PC. Next 4-bit microprocessors for this type of application. In
we discuss the hardware connections and timing of this 1976 Intel introduced the 8048. which contains an 8-bit
microcomputer. From there we show how the micro- CPU, RAM. ROM, and some I/O ports all in one 40-pin
computer
interfaced
is to a wide variety of peripheral package. Other manufacturers have followed with simi-
devices. And finally we cycle back to our computerized lar products. These devices are often referred to as
electronics company, the networks it uses, and the sys- microcontrollers. Some currently available devices in
tem programs it requires. this category, the Intel 8051 and the Motorola MC6801.
for example, contain programmable counters, a serial
port (UART) as well as a CPU, ROM, RAM, and parallel
I/O ports. A more recently introduced single-chip
Common Microprocessor Types
microcontroller, the Intel 8096, contains a 16-bit CPU.
MICROPROCESSOR EVOLUTION
ROM, RAM, a UART, ports, timers, and a 10-bit analog-
to-digital converter.
A common way of categorizing microprocessors is by the
number of bits that their ALU can work with at a time.
BIT-SLICE PROCESSORS
In other words, a microprocessor with a 4-bit ALU will
be referred to as a 4-bit microprocessor, regardless of A second direction of microprocessor evolution has been
the number of address lines or the number of data bus bit-slice processors. For some applications general-
lines that it has. The first microprocessor was the Intel purpose CPUs such as the 8080 and 6800 are not fast
4004 produced in 1971. It contained 2300 PMOS tran- enough or their instruction sets are not suitable. For
sistors. The 4004 was a 4-bit device intended to be used these applications several manufacturers produce de-
with some other devices in making a calculator. Some vices which
can be used to build a custom CPU. An ex-
logic designers, however, saw that this device could be ample
theis Advanced Micro Devices 2900 family of
used to replace PC boards full of combinational and se- devices. This family includes 4-bit ALUs, multiplexers.

32 CHAPTER TWO
sequencers, and other parts needed foi custom building M. I hi I hi i. ii v wind'. I in 8086 has ,1 16-bit data bus, so
.1 CPU. The term slice comes from the fact that these ii ran i en I (1. 11, i iii Mi, mi m hi i lata io memory and ports
pails can be connected in parallel u> work with 8 bil either 16 bits or 8 bits at a time The 8086 lias ., '.'n bil
winds. 16 Imi words, or 32 bit words. In other words, a aililnss bus, so il ran address any one ol
designei can add as many slices as needed for a particu- 1,048,576 memory locations. Each ol the 1,048,576
lar application. the designer not only custom designs i .nlilirsscs ol i he 8086 represents a byte wide
ilic hardware oi the CPU, but also custom makes the location. Words will be stored in two conse< utive mem
instruction sel for it using "microcode." orv locations. II (he lirst byte ol a word is ,il an even
address, the 8086 can read the entire wind in one opera
CENERAL-PURPOSI ( PUs lion. II I he I list byte of the word is at an odd address, the
8086 will read the first byte in one operation, and the
The third major direction ol microprocessor evolution
second byte 111 another operation, hater we will discuss
has been toward general-purpose CPUs which give a
this in del ail. the main point here is that if the In si byte
microcomputer most or all of the computing power ol
ol a 16-bit word is at an even address, the 8086 i an read
earlier minicomputers. After Motorola came out with
the word in one opei it Ion
the MC6N00. Intel produced the 8085. an upgrade of the
The Intel 8088 has the same arithmetic logic unit, the
8080 requiring only a +5 V supply. Motorola then pro-
same registers, and the same instruction set as the
ducedMC6809
the which has a few 16-bit instructions,
8086. The 8088 also has a 20-bit address bus so it can
but is still basically an 8-bit processor. In 1978 Intel
address any one of 1,048,576 bytes in memory. The
came out with the 8086 which is a full 16-bit processor.
8088, however, has an 8-bit data bus so it can only read
Some 16-bit microprocessors, such as the National
data from or write data to memory and ports 8 bits at a
PACE and the Texas Instruments 9900 family of devices,
time. The 8086, remember, can read or write either 8 or
were available previously, but the market apparently
16 bits at a time. To read a 16-bit word from two succes-
wasn't ready. Soon after Intel came out with the 8086.
sive memory locations, the 8088 will always have to do
Motorola came out with the 16-bit MC68000, and the
two read operations. Since the 8086 and the 8088 are
16-bit race was off and running. The 8086 and the
almost identical, any reference we make to the 8086 in
68000 work directly with 16-bit words instead of with
the rest of the book will also pertain to the 808K unless
8-bit words, they can address a million or more bytes of
we specifically indicate otherwise. This is done to make
memory instead of the 64 Kbytes addressable by the
reading easier. The Intel 8088. incidentally, is used as
8-bit processors, and they execute instructions much
the CPU in the IBM Personal Computer and several com-
faster than the 8-bit processors. Also these 16-bit proc-
patible personalcomputers.
essors have
single instructions for functions that re-
The Intel 80186 is an improved version of the 8086.
quired
lengthy
a sequence of instructions on the 8-bit
and the 80188 is an improved version of the 8088. In
processors. addition to a 16-bit CPU the 80186 and 80188 each have
The evolution along this last path has continued on to programmable peripheral devices integrated in the
32-bit processors that work with giga ( 109) bytes or tera
same package. In a later chapter we will discuss these
(1012) bytes of memory. Examples of these devices are
integrated peripherals. The instruction set of the 80186
the Intel 80386. the Motorola MC68020, and the Na-
and the 80188 is a superset of the instruction set of the
tional 32032. 8086. The term superset means that all of the 8086 and
Since we could not possibly describe in this book the
8088 instructions will execute properly on an 80186 or
operation and programming of even a few of the avail-
on an 80188. but the 80186 and the 80188 have a few
able processors,we confine our discussions to primarily
additional instructions. In other words, a program writ-
one group of related microprocessors. The family we
ten loran 8086 or for an 8088 is upward-compatible to
have chosen is the Intel 8086. 8088, 80186. 80188,
an 80186 or to an 80188, but a program written for an
80286 family. Members of this family are very widely
80186 or for an 80188 may not execute correctly on an
used in personal computers, business computer sys-
8086 or an 8088. In the instruction set descriptions in
tems, and
industrial control systems. Our experience
Chapter 6. we specifically indicate which instructions
has shown that learning the programming and opera-
only work with the 80186 or 80188. The 80186 is used
tionone
of family of microcomputers very thoroughly is
as the CPU in several personal computers.
much more useful than looking at many processors su-
The Intel 80286 is an advanced version of the 8086
perficially.
you learnIf one processor family well, you will
specifically designed for use as the CPU in a multiuser or
most likely find it quite easy to learn another when you
multitasking microcomputer. Programs written for an
have to.
8086 can be run on an 80286 operating in its real ad-
dress mode.
We discuss in Chapter 14 the operation
THE 8086, 8088, 80186, 80188, AND and use of the 80286. The 80286 is the CPU used in the
80286 MICROPROCESSORS- IBM PC/AT personal computer.

INTRODUCTION
The Intel 8086 is a 16-bit microprocessor intended to be 8086 INTERNAL ARCHITECTURE
used as the CPU in a microcomputer. The term "16-bit"
means that its arithmetic logic unit, internal registers. The three-instruction program section of this chapter
and most of its instructions are designed to work with describes how a CPU sends out addresses, sends out

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS— AN INTRODUCTION 33


FIGURE 2-7 8086 internal block diagram. (Intel Corp.)

control signals, reads in instructions and data to inter- which does not require use of the buses. When the EU is
nal registers, and sends out data to ports or memory. ready for its next instruction, it simply reads the in-
Before we can talk about how to write programs for the struction
thefrom
queue in the BIU. This is much faster
8086. we need to discuss its specific internal features than sending out an address to the system memory and
such as registers, instruction byte queue, and flags. waiting for memory to send back the next instruction
As shown by the block diagram in Figure 2-7, the 8086 byte or bytes. The process is analogous to the way a
CPU is divided into two independent functional parts, bricklayer's assistant fetches bricks ahead of time and
the bus interface unit or BIU. and the execution unit or keeps a queue of bricks lined up so that the bricklayer
EU. Dividing the work between these two units speeds can just reach out and grab a brick when necessary.
up processing. Except in the cases of |UMP and CALL instructions
where the queue must be dumped and then reloaded
starting from a new address, this prefetch-and-queue
The Bus Interface Unit scheme greatly speeds up processing. Fetching the next
The BIU sends out addresses, fetches instructions from instruction while the current instruction executes is
memory, reads data from ports and memory, and writes called pipelining.
data to ports and memory. In other words the BIU han-
dles all
transfers of data and addresses on the buses for SEGMENT REGISTERS
the execution unit. The following sections describe the The BIU contains four 16-bit segment registers. They
functional parts of the BIU. are: the code segment (CS) register, the stack segment
(SS) register, the extra segment (ES) register, and the
data segment IDS) register. These segment registers are
THE QUEUE used to hold the upper 16 bits of the starting addresses
To speed up program execution, the BIU fetches as many of four memory segments that the 8086 is working with
as six instruction bytes ahead of time from memory. The at a particular time. The 8086 BIU sends out 20-bit ad-
prefetched instruction bytes are held for the EU in a dresses,
it can
so address any of 220 or 1.048.576 bytes
first-in-first-out group of registers called a queue. The in memory. However, at any given time the 8086 only
BIU can be fetching instruction bytes while the EU is works with four. 65.536-byte (64 Kbyte) segments
decoding an instruction or executing an instruction within this 1.048,576-byte II Mbyte) range. Figure 2-8

a CHAPTER TWO
PHYSICAL A stack is .i scci urn n! memor) i el aside in sti
ADDRESS
dresses and data while .i subprogram executi
FFFFFH si.uk segment register is used for the upper 16 bits <>i
I II 1 M the starting address foi the program stack. We will dis-
cuss the use ,ind operation ol ,i si, irk in detail later.
1 he extra segment ir^isin and tin data
istei in- used in hold the uppei l<> bits ol the st.uim^
addresses nl two memory segments thai an- used lor
data.
EXTRA SEGMFNT BASE
ES - 7000H
INSTRUCTION POINTER
5FFFFH — TOPOF STACK i
The nexl lea tore lo look a i in i he I ill i is i he instruction
pointei III'] register. As discussed previously, the code
segment register holds the upper 16 bits ol the starting
address ol the segment from which the BIW is fetching
instruction code bytes. The instruction pointer registei
STACK SEGMENT BASE
holds the 16-bit address of Hie next code byte within
SS - 5000H
this code segment. The value con lamed in the IP is often
me i K i. hi i m 'in referred lo as an offset, because iliis value musl be offset
from (added to) the segment base address in CS to pro-
duce therequired 20-bit physical address. Figure 2-9a
shows in diagram form how this works. The CS register
points to the base or start of the current code segment
The IP contains the distance or offset from this base
CODE SEGMENT BASE
CS = 348AH address to the next instruction byte to be fetched. Fig-
ure 2-9bshows how the 16-bit offset in IP is added to the
TOPOF DATA SEGMENT
16-bit segment base address in CS to produce the 20-bit
physical address. Notice that the two 16-bit numbers
are not added directly in line. One way to describe this
process is to say that the contents of the CS register are
shifted left four bit positions before the contents of the
BOTTOM OF DATA SEGMENT IP are added to it. CS contains 348AH. When shifted left
by four bit positions this produces 348A0H as the start-
FIGURE 2-8 One way that four 64 Kbyte segments ing address of the code segment. The offset of 4214H in
might be positioned within 1 Mbyte address space of the IP is added to this base to give a 20-bit physical ad-
808b. dress 38AB4H.
of

shows how these four segments might be positioned in


memory at a given time. The lour segments can be sepa- PHYSICAL ADDRESSES

ratedshown,
as or. lor small programs which do not TOPOF CODE SEGMENT
need all 64 Kbytes in each segment, they can overlap. A 1J89F II

minimum system, for example, might start all four seg-


ments
address
at 00000H.
To repeat then, a segment register is used to hold the
upper 16 bits of the starting address for each of the seg-
ments. code
The segment register, for example, holds CODE B i il
the upper 16 bits of the starting address for the segment 38AB4H
IP 4214H
from which the BIU is currently fetching instruction
code bytes. The BIU always inserts zeros for the lowest CS - 348AH — *— START OF CODE SEGMENT
348A0H
four bits (nibble) of the 20-bit starting address for a seg-
ment.
the If code segment register contains 348AH. lor
example, then the code segment will start at address
348A0H. In other words, a 64 Kbyte segment can be lo-
cated anywherewithin the 1 Mbyte address space, but
the segment will always start at an address with zeros in
I3 4 8 A 0 IMPLIED ZERO

1 .' 1 1
the lowest 4 bits. This constraint was put on the loca-
PH .Ml AL AHURFSS 3 8 A R 1
tionsegments
of so that it is only necessary to store and
manipulate 16-bit numbers when working with the
starting address of a segment. The part of a segment
starting address stored in a segment register is often FIGURE 2-1) Addition of IP to CS to produce physical
called the segment base. address of code byte, (a) Diagram, (b) Computation.

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS— AN INTRODUCTION 35


The 8086 20-bit physical addresses are often repre- nine Hags are used to indicate some condition produced
sented
a segment
in base: offset form rather than in the by an instruction. For example, a flip-flop called the
single number form. For the address of a code byte the carry flag will be set to a one if the addition of two 16-bit
alternative form will be CS:IP. For example, the address binary numbers produces a carry out of the most signif-
constructed in the preceding paragraph. 38AB4H, can icantposition.
bit If no carry out of the MSB is produced
also be represented as 348A:4214. by the addition, then the carry flag will be a zero. The EU
To summarize, then, the CS register contains the then effectively runs up a "flag" to tell you that a carry
upper 16 bits of the starting address of the code seg- was produced.
mentthein 1 Mbyte address range of the 8086. The in- The six conditional Hags in this group are: the carry
struction pointer
register contains a 16-bit offset which flag (CF), the parity flag (PF), the auxiliary carry flag
tells where in that 64 Kbyte code segment the next in- IAF), the zero flag (ZF), the sign flag (SF1. and the over-
struction
willbyte
be fetched from. The actual physical flow fag(OF). The names of these flags should give you
address sent to memory is produced by shifting the con- hints as to what conditions affect them. Certain 8086
tents
theof CS register four bit positions left and adding instructions check these flags to determine which of two
the offset contained in IP. alternative actions should be done in executing the in-
As you will see in later sections, any time the 8086 struction.
accesses memory, the BIU produces the required 20-bit The three remaining Hags in the flag register are used
physical address by shifting the contents of one of the to control certain operations of the processor. These
segment registers left four bit positions and adding to it flags are different from the six conditional flags de-
a displacement or offset. scribed above
in the way they get set or reset. The six
conditional flags are set or reset by the EU on the basis
of the results of some arithmetic or logic operation. The
The Execution Unit control fags are deliberately set or reset with specific
The execution unit of the 8086 tells the BIU where to instructions you put in the program. The three control
fetch instructions or data from, decodes instructions, flags are the trap flag (TF1, which is used for single step-
and executes instructions. The following sections de- ping through a program; the interruptjlag (IF), which is
scribe functional
the parts of the execution unit. used to allow/prohibit the interruption of a program,
and the direction fag (DF). which is used with string
CONTROL CIRCUITRY, INSTRUCTION instructions.
DECODER, AND ALU Later we will discuss in detail the operation and use of
the nine flags.
Now take another look at the 8086 block diagram in Fig-
ure 2-7to see what is contained in the execution unit.
GENERAL-PURPOSE REGISTERS
The EU contains control circuitry which directs internal
operations. A decoder in the EU translates instructions Observe in Figure 2-7 that the EU has eight general pur-
fetched from memory into a series of actions which the pose registerslabeled AH. AL, BH, BL. CH, CL. DH, and
EU carries out. The EU has a 16-bit arithmetic logic unit DL. These registers can be used individually for tempo-
which can add. subtract, AND, OR, XOR, increment, rary storageof 8-bit data. The AL register is also called
decrement, complement, or shift binary numbers. the accumulator. It has some features that the other
general-purpose registers do not have.
FLAG REGISTER
Certain pairs of these general-purpose registers can
A fag is a flip-Hop which indicates some condition pro- be used together to store 16-bit data words. The accept-
ducedtheby execution of an instruction, or controls able registerpairs are AH and AL. BH and BL, CH and
certain operations of the EU. A 16-bit flag register in the CL. and DH and DL. The AH-AL pair is referred to as the
EU contains nine active flags. Figure 2-10 shows the lo- AX register, the BH-BL pair is referred to as the BX reg-
cation
theof nine flags in the flag register. Six of the ister, the
CH-CL pair is referred to as the CX register.

3085 COMPATIBLE FLAGS

15 14 1! 12 11 10 9 ;-; 7 6 5 4 3 2 1 0

U U U OF DF IF TF SF ZF U AF U PF U CF

U= UNDEFINED
L CARRY FLAG - SET BY CARRY OUT OF MSB
PARITY FLAG - SET IF RESULT HAS EVEN PARITY
AUXILIARY CARRY FLAG FOR BCD
ZERO FLAG - SET IF RESULT = 0
SIGN FLAG = MSB OF RESULT
SINGLE STEP TRAP FLAG
INTERRUPT ENABLE FLAG
STRING DIRECTION FLAG
OVERFLOW FLAG

I IGURE 1- Id 8086 tlag register format. (Intel Corp.)

(6 CHAPTER TWO
and the DI1 DL pair is referred to .is the DX regtstei Foi rhe operation and use of the stack will be discussed in
16-bit operations, AX is called the accumulator. detail lain as need arises
lh, 8086 reglstei set is very similai to those ol the
earlier generation 8080 and 8085 microprocessors. Ii OTHER POINTER AND INDEX REGISTERS
was designed tins way so thai the many programs wrl I In addll Km in the stack p tei registei . SP, the EI i con
ten for the 8080 and 8085 could easily be translated to la ins a 16-bil base polntei (BP) register It also contains
run on the 8086 oi the 8088. The advantage ol using a 16-bil source index (SI) registei and a 16-bit destina-
Internal registers for the temporary storage "i data Is tion indexIDli register. These three registers can be
that, since the data is already In the EU, n can be ac used for temporary storage ol data jusl as the gi neral
cessed much more quickly than it could be accessed in purpose registers described above I lowevei . theii mam
external memory. use is to hold the 16 bit offset ol a data word in one ol
the segments. SI. foi example, can be used to hold the
STACK POINTER REGISTER
offset ol a daia word in the data segment The physical
A stack, remember, is a section ol memory set aside In address ol die data in memory will be generated in this
store addresses and data while a subprogram is execut- case by shilling the contents of the data segment regis-
ing. The
8086 allows you to set aside an entire 64 Kbyte ter fourlui positions to the lefl and adding the contents
segment as a stack. The upper 16 bits of the starting of SI to the result. A later section on addressing modes
address for this segment is kept in the stack segment will discuss and show mam- examples of the use ol these
register. The stack pointer (SP) register contains the base and index registers.
16-bit offset from the start of the segment to the mem-
ory location where a word was most recently stored on
the stack. The memory location where a word was most INTRODUCTION TO PROGRAMMING
recently stored is called the top of stack. Figure 2-1 la THE 8086
shows this in diagram form.
The physical address for a stack read or for a stack Programming Languages
write is produced by adding the contents of the stack Now that you have an overview of the 8086 CPU. it is time
pointer register to the segment base address in SS. To to start you thinking about how it is programmed. To
do this the contents of the stack segment register are run a program, a microcomputer must have the pro-
shifted four bit positions left and the contents of SP are gram stored
in binary form in successive memory loca-
added to the shifted result. Figure 2-1 lb shows an ex- tions. There
are three language levels that can be used
ample.5000H
The in SS is shifted left four bit positions to write a program for a microcomputer.
to give 50000H. When FFE0H in the SP is added to this.
the resultant physical address for the top of the stack MACHINE LANGUAGE
will be 5FFE0H. The physical address can be repre- You can write programs as simply a sequence ot the bi-
sented either
as a single number, 5FFE0H, or it can be nary codes
for the instructions you want the microcom-
represented in SS:SP form as 5000:FFE0H. puter
execute.
to The three-instruction program in Fig-
ure 2-2b
is an example. This binary form of the program
is referred to as machine language because it is the
PHYSICAL ADDRESSES form required by the machine. However, it is difficult, if
END OF STACK 5FFFFH not impossible, for a programmer to memorize the thou-
SEGMENT TOP OF STACK sands
binary
of instruction codes for a CPU such as the
5FFE0H 8086. Also, it is very easy for an error to occur when
working with long series of Is and 0's. Using hexadeci-
mal representation lor the binary codes might help
some, but there are still thousands of instruction codes
to cope with.

ASSEMBLY LANGUAGE
START OF STACK SEGMENT
To make programming easier many programmers write
50000 H
programs in assembly language. They then translate
the assembly language program to machine language so
it can be loaded into memory and run. Assembly lan-
guage uses
two-, three-, or four-letter mnemotiics to
h ii 0 ii ii
represent each instruction type. A mnemonic is just a
F t t 0 device to help you remember something. The letters in
PHYSICAL ADDRESS h F r E u an assembly language mnemonic are usually initials or
(TOP OF STACK) a shortened form of the English word(s) for the opera-
tion performedby the instruction. For example, the
mnemonic for subtract is SUB, the mnemonic for exclu-
FIGURE 2-11 Addition of SS and SP to produce physical sive OR
is XOR, and the mnemonic lor the instruction to
address ot top of stack, (a) Diagram, tbi Computation. copy data from one location to another is MOV.

COMPUTERS. MICROCOMPUTERS, AND MICROPROCESSORS— AN INTRODUCTION 37


the destination, however, cannot both be memory loca-
LABEL OP CODE OPERAND COMMENT
FIELD FIELD FIELD FIELD tionsan
in instruction.

ADD AL. 07H ADD CORRECTION FACTOR A later section on 8086 addressing modes will show all
NEXT:
of the ways in which the source of an operand and the
destination of the result can be specified. The point here
FIGURE 2-12 Assembly language program statement
is that the single mnemonic. ADD. together with a spec-
format.
ified source
and a specified destination can represent a
great many 8086 instructions in an easily understanda-
Assembly language statements are usually written in ble form.
a standard form having four fields. Figure 2-12 shows The question that may occur to you at this point is. "If
an assembly language statement with the four fields I write a program in assembly language, how do I get it
indicated. The first field in an assembly language state- translated into machine language which can be loaded
ment
theis label field. A label is a symbol or group of into the microcomputer and executed?" There are two
symbols used to represent an address which is not spe- answers to this question. The first method of doing the
cifically known
at the time the statement is written. translation is by working out the binary- code for each
Labels are usually followed by a colon. Labels are not instruction a bit at a time using the templates given in
required in a statement, they are just inserted where the manufacturer's data books. We will show you how to
they are needed. We will show later many uses of labels. do this in the next chapter. It is a tedious and error-
The opcode field of the instruction contains the mne- prone task. The second method of doing the translation
monicthe
for instruction to be performed. Instruction is with an assembler. An assembler is a program which
mnemonics are sometimes called operation codes or op- can be run on a personal computer or microcomputer
codes. ADD
The mnemonic in the example statement in development system. It reads the assembly language
Figure 2-12 indicates that we want the instruction to do instructions and generates the correct binary code for
an addition. Chapter 6 describes the function of each each. For developing all but the simplest assembly lan-
8086 instruction type and gives the opcodes for each. guage programs,an assembler and other program devel-
The operandfield of the statement contains the data, opment are
tools essential. We will introduce you to
the memory address, the port address, or the name of these program development tools in the next chapter
the register on which the instruction is to be performed. and describe their use throughout the rest of this book.
Operand is just another name for the data item(s) acted
on by an instruction. In the example instruction in Fig- HIGH LEVEL LANGUAGES
ure 2-12there are two operands. AL and 07H. specified Another way of writing a program for a microcomputer
in the operand field. AL represents the AL register, and is with a high level language such as BASIC, FOR-
07H represents the number 07H. This assembly lan- TFiAN. or Pascal. These languages use program state-
guage statementthen says add the number 07H to the ments which are even more English-like than those of
contents of the AL register. By Intel convention the re- assembly language. Each high level statement may rep-
sult the
of addition will be put in the register or the resent many
machine code instructions. An interpreter
memory location specified before the comma in the op- program or a compiler program is used to translate
erand field.
For the example statement in Figure 2-12 higher level language statements to machine codes
then, the result will be left in the AL register. As another which can be loaded into memory and executed. Pro-
example, the assembly language statement. ADD BH. gramsusually
can be written faster in high level lan-
AL, when converted to machine language and run. will guages than
in assembly language because the high
add the contents of the AL register to the contents of the level language works with bigger building blocks. How-
BH register. The results will be left in the BH register. ever, programs written in a high level language and in-
Looking back at the example assembly language state- terpreted
compiled
or execute slower than the same pro-
ment Figure
in 2-12. observe the comment field which grams written in assembly language. Programs that
starts with a semicolon. This field is very important. involve a lot of hardware control, such as robots and
Comments do not become part of the machine language factory control systems, or programs that must run as
program. You write comments in a program to remind quickly as possible are usually best written in assembly
you of the function that this instruction or group of in- language. Programs that manipulate massive amounts
structions performs
in the program. of data, such as insurance company records, are usually
To summarize why we use assembly language, let's best written in a high level language. The decision of
look a little more closely at the assembly language ADD which language to use has recently been made more dif-
statement. The general format of the 8086 ADD instruc- ficult
theby fact that current assemblers allow the use of
tion is: manv high level language features, and the fact that
some current high level languages provide assembly lan-
ADD destination, source
guage features.

The source can be a number written in the instruction,


OUR CHOICE
the contents of a specified register, or the contents of a
memory location. The destination can be a specified Throughout this book we will use mostly assembly lan-
register or a specified memory location. The source and guage because
we will be working very closely with hard-

W CHAP 11
ware Interfacing. Before we start teaching you assembly her that the destination location is spe< Ified In the In
language programming in the nexl chapter, however, struction before the source Also note that the contents
we wanl to give you an introduction to how the 8086 ol AX are |iist i opied In CX, not actually moved. In oilier
.in esses data. words, the previous contents ol < x are written over, hut
the contents of AX are not changed. Foi example, If CX
contains 2A84H and AX contains 4971H before the
How the HOW) Accesses Immediate and Register MOV CX, AX instruction executes, then alter the in-
Data struction executes
CX will contain 4971H and AX will
hi a previous discussion ol the 8086 Bin we described si ill coi i lam 197 1H. You can MOV any 16-bil registei to
how the 8086 ai cesses code bytes using CS and IP. We any l «> bit register, or sou can MOV any 8 hn register to
also described how the 8086 accesses the stack using any 8 hit register. However, you cannot use an instruc-
ss ami SP. Before we can teach you assembly language tion suchas \H)V ( X, AI because this is an attempt to
copy a byte-type operand (Al.l into a word-type destina
programming techniques, we need to discuss some ol
the different ways that an 8086 can access tin- data that
tion (CX). The' byte in AI. would fit in CX. hut the 8086

ii operates on. The different ways that a processor can


would not know which hall ofCX to put it in. II yon try to
access data are referred to as its addressing modes In write an instruction like this and you are using a good
assembly language statements the addressing mode is assembler, the assemblei will tell you that the instruc-
indicated in the instruction. We will use the ,K086 MOV
tion contains a type error. To copy the byte from AL to
instruction to illustrate some ol the 8086 addressing
the high byte ol CX you can use the instruction MOV
CH, AL. The instruction MOV CL, AL will copy the byte
modes.
The MOV instruction has the format: from AL to CL. the low byte of CX.

MOV destination, source How the 8086 Accesses Data in Memory

When executed, this instruction copies a word or a byte OVERVIEW OF MEMORY ADDRESSING MODES
from the specified source location to the specified desti-
The addressing modes described in the following sec-
nation location.
The source can be a number written
tions used
are to specify the location of an operand in
direi tlv in the instruction, a specified register, or a
memory location specified in one of 24 different ways.
memory. A previous section described how the 8086
produces the physical address for instruction codes by
The destination can be a specified register or a memory
location specified in any one of 24 different ways. The
adding an offset in the instruction pointer to the code
source and the destination cannot both be memory loca-
segment base in the CS register. Remember that the
contents of CS are shifted four bit positions left before
tionsanin instruction.
the contents of IP are added. Another previous section
IMMEDIATE ADDRESSING MODE
described how the 8086 accesses stack locations by add-
ing anoffset in the stack pointer register to the stack
Suppose that in a program you need to put the number segment base in the stack segment register. Here again
437BH in the CX register. The MOV CX, 437BH instruc- the contents of the stack segment register are shifted
tion can
be used to do this. WLien it executes, this in- four bit positions left before the contents of the stack
struction
putwall
the immediate hexadecimal number pointer are added.
437BH in the 16-bit CX register. This is referred to as To access data in memory the 8086 must also produce
immediate addressing mode because the number to be a 20-bit physical address. It does this by adding a 16-bit
loaded into the CX register will be put in two memory value called the effective address to one of the four seg-
locations immediately following the code for the MOV ment bases.
The effective address (EA) represents the
instruction. This is similar to the way the port address displacement or offset of the desired operand from the
was put in memory immediately after the code for the segment base. In most cases, any of the segment bases
input instruction in the three-instruction program in can be specified, but the data segment is the one most
Figure 2-2b. often used. Figure 2- 13a shows in graphic form how the
A similar instruction, MOV CL, 48H could be used to
EA is added to the data segment base to point to an
load the 8-bit immediate number 48H into the 8-bit CL operand in memory. Figure 2- 13b shows how the 20-bit
register. You can also write instructions to load an 8-bit
physical address is generated by the BIU. The starting
immediate number into an 8-bit memory location or to
address for the data segment in Figure 2-135 is 20000H
load a 16-bit number into two consecutive memory loca-
so the data segment register will contain 2000H. The
tions, but
we are not yet ready to show you how to spec- BIU shifts the 2000H four bit positions left and adds the
ify these. effective address. 437AH. to the result. The 20-bit physi-
cal addresssent out to memory by the BIU will then be
REGISTER ADDRESSING MODE 2437AH. The physical address can be represented either
Register addressing mode means that a register is the as a single number. 2437AH, or in the segment base:
source of an operand for an instruction. The instruction offset form as 2000:437AH.
MOV CX, AX. for example, copies the contents of the The execution unit calculates the effective address for
16-bit AX register into the 16-bit CX register. Remem- an operand using information you specify in the in-

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS— AN INTRODUCTION 39


struction acopies
word from memory into the BX regis-
PHYSICAL ADDRESSES
ter. Sinceeach memory address of the 8086 represents a
END OF DATA SEGMENT byte of storage, the word must come from two memory
2FFFFH locations. The byte at a displacement of 437AH from the
data segment base will be copied into BL. The contents
of the next higher address, displacement 437BH. will be
copied into the BH register. The 8086 will automatically
access the required number of bytes in memory for a
DATA BYTE given instruction.
2437AH
The previous two examples showed how the direct
EA = 437AH
addressing mode i an be used to specify the soun e ol an
DS 2000H !— START OF DATA SEGMENT
operand. It can also be used to specify the destination of
20000H
an operand. The instruction MOV [437AH], BX. for ex-
ample,copy
will the contents of the BX register to two
memory locations in the data segment. The contents of
BL will be copied to the memory location at a displace-
!% %
0 n ) ii
ment437AH.
of The contents of BH will be copied to the
1 3 / A memory location at a displacement of 437BH.
PHYSICAL ADDRESS 2 4 1 / /\
'.< ill When you are hand-coding progams using direct ad-
dressing
the ni
form shown above, make Mire to put in the
square brai kets to remind you hov\ to code the instrui tion II
FIGURE 2-13 Addition of data segment register and you leave the brackets out of an instruction such as
effective address to produce physical address of data MOVCX, [437AH], you will < ode it as il it were the instru< turn
byte, la) Diagram, lb) Computation. MOV CX, 4J7AH. This will load the immediate number
437AH into ( Y rathei than load a word from memory at a
struct ion. You can tell the EU to use a number in the displacement ol 437AH, Also note thai if you are writing an
instruction as the effective address, to use the contents instrui tion using direc i addressing sue h as this for ,\n assem-
of a specified register as the effective address, or to com- bler, you
must use a form such as MOV BL, DS:BYTE
pute the
effective address by adding a number in the PTR|437AH| to give the assembler all the information it needs.
instruction to the contents of one or two specified regis- As will be shown in the next chapter, when using an assem-
ters. Thefollowing section describes one way you can bler, we
usually use a name to represent the direct address
tell the execution unit to calculate an effective address. rather than the actual numerical offset
In later chapters we show other ways of specifying the
effective address. We also show how the addressing A FEW WORDS ABOUT SEGMENTATION
modes this provides are used to solve some common At this point you may be wondering why Intel designed
programming problems. the 8086 family devices to use memory segmentation.
At least two reasons come to mind. First, by working
DIRECT ADDRESSING MODE with only 64 Kbyte segments of memory at a time, the
For the simplest memory addressing mode the effective 8086 only has to work with 16-bit effective addresses to
address is just an 8- or 16-bit number written directly in access any location in the segment. In other words, be-
the instruction. The instruction MOV CL, [437AH] is an cause
theof segmentation scheme the 8086 only has to
example. The square brackets around the 437AH are manipulate and store 16-bit address components. The
shorthand for "the contents of the memory locationlsl at second reason has to do with the type of microcomputer
a displacement from the segment base of." When exe- in which an 8086 family CPU is likely to be used. A pre-
cuted, this
instruction will copy the contents of the vious section
of this chapter described briefly the opera-
memory location, at a displacement of 437AH from the tionaoftime-share microcomputer system. In a time-
data segment base, into the CL register. The actual 20- share system several users share a CPU. The CPU works
bit physical memory address will be produced by shift- on one user's program for perhaps 20 milliseconds, then
ing the
data segment base in DS four bits left and add- works on the next user's program for 20 milliseconds.
ing theeffective address 437AH to the result. Figure After working 20 milliseconds for each of the other
2- 13b shows how the operation is done. This addressing users, the CPU comes back to working on the first user's
mode is called direct because the displacement of the program again. Each time the CPU switches from one
operand from the segment base is specified directly m user's program to the next it must access a new section
the instruction. The displacement in the instruction of code and new sections of data. Segmentation makes
will be added t<>the data segment base in DS unless you this switching quite easy. Each user's program can be
use a seqment override prefix to tell the BIU to add it to assigned a separate set of logical segments for its code
some other segment base. We will discuss the segment and data. The user's program will contain offsets or dis-
overide prefix later. placements
thesefromsegment bases. To change from
Another example of this addressing mode is the in- one user's program to a second user's program all that
struction BX,
MOV [437AH], When executed, this in- has to be done is to reload the four segment registers

40 I MAIM IK TWO
wiih the segment base addresses assigned u> the set ond Addi ess. data, and I ontrol buses
user's program. In othei words, segmentation makes II
i ontrol bus signals
easy to keep users' programs and data separate from
each other, and segmentation makes ii easy to switch ALU
from one user's program to anothei user's program
Segmentation

Mill
IMPORTANT TERMS AND CONCEPTS Instruction byte queue, pipelining
EROM THIS CHAPTER ES, CS, SS. DS registers, IP register

EU
II yon do noi remember any ol the terms oi concepts in
AX, MX, CX, D.\ registers, flag register
the following list, use the index to find them In the
ALU. SI'. MP. SI. 1)1 registers
chaptei
Machine language
Microcomputer, mici oprocessoi
Assembly language
Hardware, software, firmware Mnemonic, opcode, operand, label, comment,
Time-share Assembler

Multitasking computer system High level language


Distributed processing system Compiler

Multiprocessing Immediate address mode, register address mode.


direct address mode
CPU
Effective address
Memory, RAM. ROM
I/O ports

REVIEW QUESTIONS AND PROBLEMS


Describe the sequence of signals that occurs on the physical address will a code byte be fetched
address bus. the control bus, and the data bus from if the instruction pointer contains
when a computer fetches an instruction. 539CH?

Describe the main advantages of a distributed pro- 8. What physical address is represented by:
cessing computer
system over a simple time-share a. 4370:561EH
system. b. 7A32:0028H

What determines whether a microprocessor is con-


9. What is the advantage of using a CPU register for
sidered
8-bit.
an 16-bit. or 32-bit device?
temporary data storage over using a memory loca-
a. How many address lines does an 8086 have?
b. How many memory addresses does this num-
10. II the stack segment register contains 3000H and
ber of
address lines allow the 8086 to access
the stack pointer register contains 8434H. what is
directly?
the physical address of the top of the stack?
c. At any given time, the 8086 works with four
segments in this address space. How many 11. a. What is the advantage of using assembly lan-
bytes are contained in each segment? guage instead
of writing a program directly in
d. Why was the 8086 designed with this segmen- machine language?
tal ionol the address space? b. Describe the operation an 8086 will perform
What is the main difference between the 8086 and when it executes ADD AX, BX.
the 8088?
12. What types of programs are usually written in as-
a. Describe the function of the 8086 queue. sembly language?
b. How does the queue speed up process opera-
13. Describe the operation that an 8086 will perform
tion?
when it executes each of the following instructions:
a. II the code segment for an 8086 program starts a. MOV BX, 03FFH
at address 70400H. what number will be in the b. MOV AL, ODBH
CS register? c. MOV DH, CL
b. Assuming this same code segment base, what d. MOV BX, AX

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS— AN INTRODUCTION 41


Write the 8086 assembly language statement 16. If the data segment register, DS, contains 4000H.
which will perform the following operations: what physical address will the instruction MOV AL,
a. Load the number 7986H into the BP register. [234BH] read?
b. Copv the BP register contents to the SP regis- ,_ rp , „„„„ ,
17. II the 8086 data segment register contains 7000H.
ter. ° °
„ ., . . r.. .v „. . . ., r.c write the instruction that will copv the contents of
c. Copv the contents ol the AX register to the DS ^r ,, „ „„„„
DL to address 74B2CH.
register.
d. Load the number F3H into the AL register. 18. Describe the difference between the instructions
„. f. Q„„c .. .. , ,. ,, t. MOV AX, 2437H and MOV AX, [2437H].
II the 8086 execution unit calculates an eftective
address of 14A3H and DS contains 7000H. what
physical address will the Bill produce?

42 CHAPTERTWO
CHAPTER

8086 Family Assembly


Language Programming-
Introduction
The last chapter showed you the format for 8086 assem solve. In oilier words, ask yoursell many times, "What do
bly language programs and introduced you to a few 1 really want this program to do?" If you don't do this,
8086 instructions. Developing a program, however, re- you may write a great program that works, but does not
quires more
than just writing down a series of instruc- do what you need it to do. As you think about the prob-
tions. When
you want to build a house, it is a good idea lemisita good idea to write down exactly what you want
to first develop a complete set of plans for the house. the program to do and the order in which you want the
With the plans you can see if the house has the rooms program to do it. At this point you do not write down
you need, if the rooms are efficiently placed, and if the program statements, you just write the operations you
house is structured so that you can easily add on to it if want in general terms. An example for a simple pro-
you have more kids. We have all probably seen examples gramming problem
might be:
of what happens when someone attempts to build a
house by just putting pieces together without a plan. 1. Read temperature from sensor
Likewise, when you write computer programs it is a
2. Add correction factor of +7
good idea to start by developing a detailed plan or out-
line.
good
A outline helps you to break a large and seem- 3. Save result in a memory location
ingly overwhelmingprogramming job down into small
modules which can easily be written, tested, and de- For a program as simple as this, the three actions de-
bugged.more
The time you spend organizing your pro- sired are
very close to the eventual assembly language
gramsless
the time it will take you to write and debug statements. For more complex problems, however, we
them. You should never start writing an assembly lan- develop a more extensive outline before writing the as-
guage program by just writing down instructions! In sembly language
statements. The next section shows
this chapter we show you how to develop assembly lan- you some of the common ways of representing program
guage programs in a systematic way. operations in a program outline.

OBJECTIVES Representing Program Operations


At the conclusion of this chapter you should be able to: The formula or sequence of operations used to solve a
programming problem is often called the algorithm of
1. Write a task list, flowchart, or pseudocode for a sim- the program. The following sections show you several
ple programming problem. ways of representing the algorithm for a program or pro-
gram segment.
2. Write, code or assemble, and run a very simple as-
sembly language
program. SEQUENTIAL TASK LISTS
3. Describe the use of program development tools such Some programmers use just a sequential list of the
as editors, assemblers, linkers, locators, debuggers, tasks such as that in the preceding section to show the
and emulators. algorithm for their programs. To give you a better idea of
this form, we will show another slightly different exam-
4. Properly document assembly language programs.
ple. Suppose that, instead of taking in one data sample
from the temperature sensor, we want to take in a data
PROGRAM DEVELOPMENT STEPS sample every hour for 24 hours, add 7 to each sample,
and put each corrected value in a memory location We
Defining the Problem could write a task list for this problem as:
The first step in writing a program is to think very care-
fully about
the problem that you want the program to I. Read data sample from temperature sensor.

43
2. Add 7 to value read in. FLOWCHARTS

3. Store eorrected value in memory location. If you have done any previous programming in BASIC or
in FORTRAN, you are probably familiar with flowcharts.
4. Wait one hour.
Flowcharts use graphic shapes to represent different
5. Read next sample from temperature sensor. types of program operations. The specific operation de-
sired
written
is in the graphic symbol. Figure 3-1 shows
6. Add 7 to value read in.
some of the common flowchart symbols. Plastic tem-
7. Store eorrected value in next memory location. platesavailable
are to help you draw these symbols if vou
decide to use them for your programs.
Figure 3-2 shows a flowchart for a program to read in
24 data samples from a temperature sensor at 1-hour
intervals, add 7 to each, and store each result in a mem-
ory location. A racetrack-shaped symbol labeled START
97. Read last data sample from temperature sensor. is used to indicate the beginning of the program. A par-
allelogram
used to is represent input or output opera-
98. Add 7 to value read in. tions.
theIn example we use it to indicate reading data
99. Store corrected value in next memory location.
from the temperature sensor. A rectangular box symbol
is used to represent simple operations other than input
and output operations. The box containing "add 7" in
As you can see. this direct form is not a very compact or
Figure 3-2 is an example.
efficient way of representing the operation of the pro-
A rectangular box with double lines at each end is
gram.
more
A efficient way of writing the sequential task
often used to represent a subroutine or procedure that
list for this program is:
will be written separately from the main program. When
a set of operations must be done several times through-
Read a data sample from temperature sensor.
outprogram,
a it is usually more efficient to write the
Add 7 to the value read in. series of operations once as a separate subprogram and
then just use or "call" this subprogram as it is needed.
Store corrected value in memory location. For example, suppose that there are several times in a
Wait one hour. program where you need to compute the square root of a
number. Instead of writing the series of instructions for
24 samples yet? computing a square root each time you need it in the
No, read next sample and process.
program, you can write the instruction sequence once
Yes. done.
as a subprogram and set it aside in some location in
memory. Vou can then call this subprogram each time
The last three lines indicate that we want the program you need to compute a square root. In the flowchart in
to do the read. add. store, and wait operations 24 times. Figure 3-2 we use the double-ended box to indicate that
Carefully written sequential task lists are often quite the "wait 1 hour" operation will be programmed as a
close to the assembly language statements that will im- subroutine. Incidentally, the terms subprogram, sub-
plement them,
so you may find them useful. As you de- routine,procedure
and all have the same meaning.
termine hardware
details, such as port addresses for the Chapter 5 shows how procedures are written and used.
system on which the program is to run. you can add this A diamond-shaped box is used in flowcharts to repre-
information to the appropriate task statement. The next sentdecision
a point or crossroad. Usually it indicates
section show-, you a more graphic way of representing that some condition is to be checked at this point in the
ilu algorithm of a program or program segment. program and. if the condition is found to be true, one set

OFF PAGE CONNECTOR


CONNECTOR
SUB
ROUTINE
| ) /^~\ Q
FIGURE 5-1 Flow, h.iit symbols

44 ( HAPTER lllkl t
f STAR! J however, have several disadvantages First, yo
write much Informal in the little boxes Second,
flowcharts do nol present information In a verj <ompai i
form. For mine complex problems, flowcharts lend to
become spread out over many pages I hej are verj hard
in follow back and forth between pages Ftiird and most
important, with flowcharts the overall structure ol the
program tends to get losl in the details. The following
section describes a more clearly structured and compact
method ol representing the algorithm of a program or
pi ogi .mi segment.

MRU RJRED PROGRAMMING AND


PSEUDOCODE OVERVIEW

In the early days ol computers a single brilliant person


might write even a large program single-handedly. The
main concerns in this case were. "Does the program
work?" and "Whal do we do if this person leaves the
company?" As the number of computers increased and
the complexity of the programs being written increased,
large programming jobs were usually turned over to a
team of programmers. In this case the compatibility of
parts written by different programmers became an im-
portant concern.
During the 1970s it became obvious to
many professional programmers that, in order for team
C STOP J programming to work, a systematic approach and
standardized tools were absolutely necessary.
FIGURE 3-2 Flowchart for program lo read in 24 data One suggested systematic approach is called top-
samples from a port, correct each value, and store each down design. In this approach a large programming
in a memory location. problem is first broken down into major modules. The
top level of the outline shows the relationship and func-
tionthese
of modules. This top level then presents a
of actions is to be done. If the condition is found to be one-page overview of the entire program. Each of the
false, then another set of actions is to be done. In the major modules is broken down into still smaller mod-
example flowchart in Figure 3-2 the condition to be ules following
on pages. The division is continued until
cheeked is whether 24 samples have been read in and the steps in each module are clearly understandable.
processed. If 24 samples have not been read in and proc- Each programmer can then be assigned a module or set
essed, arrow
the labeled NO in the flowchart indicates of modules to write for the program. Also, those who
that we want the computer to jump back and execute want to learn about the program later can start with the
the read. add. store, and wait steps again. If 24 samples overview and work their way down to the level of detail
have been read in. the arrow labeled YES in the flow- they need. This approach is the same as drawing the
chartFigure
of 3-2 indicates that all the desired opera- complete plans for a house before starting to build it.
tions have
been done. The racetrack-shaped symbol at The opposite of top-down design is bottom-up design.
the bottom of the flowchart indicates the end of the pro- In this approach each programmer starts writing low-
gram. level modules and hopes that all the pieces will eventu-
The two additional flowchart symbols in Figure 3-1 ally together.
fit When completed, the result should be
are connectors. If a flowchart column gets to the bottom similar to that produced by the top-down design. Many
of the paper, but all of the program has not been repre- modern programming teams use a combination of the
sented,can
you put a small circle with a letter in it at the two techniques. They do the top-down design and then
bottom of the column. You then start the next column at build, test, and link modules starting from the smallest
the top of the same paper with a small circle containing and working upward.
the same letter. If you need to continue a flowchart to The development of standard programming tools was
another page, you can end the flowchart on the first helped by the discovery that any desired program opera-
page with the five-sided off-page connector symbol con- tion couldbe represented by three basic types of opera-
taining
lettera or number. You then start the flowchart tion. The
first type of operation is sequence which
on the next page with an off-page connector symbol con- means simply doing a series of actions. The second
tainingsame
the letter or number. basic type of operation is decision or selection, which
For
simple programs and program sections, flow- means choosing between two alternative actions. The
charts
a are
graphic way of showing the operational flow third basic type of operation is repetition or iteration.
of the program. We will show flowcharts for many of the which means repeating a series of actions until some
program examples throughout this book. Flowcharts. condition is or is not present.

808b FAMILY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION 45


On the basis of this observation, the suggestion was The WHILE-DO structure in Figure 3-3d is one form
made that all programmers use a set of three to seven of repetition. It is used to indicate that you want to do
standard structures to represent all of the operations in some action or sequence of actions as long as some con-
their programs. Actually, only three structures. dition
present.
is This structure represents a program
SEQUENCE. IF-THEN-ELSE, and WHILE-DO. are loop. The example in Figure 3-3d is:
required to represent any desired program action, but
three or four more structures derived from these often WHILE money lasts DO

make programs clearer. If you have previously written Eat supper out.

programs in a structured language such as Pascal, then Go to movie.

these structures are probably already familiar to you. Take a taxi home.

Figure 3-3 uses flowchart symbols to represent the com-


monly used
structures so you can more easily visualize This example shows a sequence of actions you might do
their operations. In actual program documentation, each evening until you ran out of money. Note that, in
however. English-like statements called pseudocode are this structure, the condition is checked before the
used rather than the space-consuming flowchart sym- action is done the first time. You certainly would want to
bols. Figure
3-3 also shows the pseudocode format and check how much money you have before eating out.
an example for each structure. Another useful structure, derived from the WHILE-
Each structure has only one entry point and one exit DO structure, is the REPEAT-UNTIL structure shown
point. The output of one structure is connected to the in Figure 3-3e. You use this structure to indicate that
input of the next structure. Program execution then you want the program to repeat some action or series of
proceeds through a series of these structures. actions until some condition is present. A good example
Any structure can be used within another. An IF- of the use of this structure is the programming problem
THEN-ELSE structure, for example, can contain a se- we used in the discussion of flowcharts. The example is:
quence
statements.
of Any place that the term state-
ments) appears
in Figure 3-3. one of the other REPEAT
structures could be substituted for it. The term "state- Get data sample from sensor.
ment(s)" can also represent a subprogram or procedure Add correction of +7.
that is called to do a series of actions. Store result in a memory location.
Wait one hour.
STANDARD PROGRAMMING STRUCTURES UNTIL 24 samples taken.

The structure shown in Figure 3-3n is an example of a


simple sequence. In this structure the actions are sim-
Compare the space required by the pseudocode repre-
ply written down in the desired order. An example is:
sentation
the desired
for action with the space required
by the flowchart representation shown in Figure 3-2.
Read temperature from sensor. The space advantage of pseudocode should be obvious.
As indicated previously, the REPEAT-UNTIL struc-
Add correction factor of t-7.
turederived
is from the WHILE-DO. In other words, any
Store corrected value in memory. problem that can be represented by a REPEAT-UNTIL
can also be represented by a properly written WHILE-
Figure 3-3b shows an IF-THEN-ELSE example of the DO. The example in Figure 3-3e could be written as:
decision operation. This structure is used to direct op-
eration
oneto of two different actions based on some WHILE NOT 24 samples DO
condition. An example is: Read data sample from temperature sensor.
Add correction factor of +7.
IF temperature less than 70 degrees THEN Store result in memory location.
Turn on heater Wait one hour.
ELSE
Turn nil heater Note that the REPEAT-UNTIL structure indicates that
the condition is first checked after the statement(s) is
The example says that it the temperature is below the performed. In other words, a REPEAT— UNTIL structure
thermostat setting, we want to turn the heater on. II the indicates that the action or series of actions will always
temperature is equal to or above the lhermcist<it setting, be done at least once. If you don't want this to happen,
we want to turn the heater oil. then use the WHILE— DO which indicates that the con-
The IF-THEN structure shown in Figure 3-3c is the dition
checked
is before any action is taken. As we will
same as the IF-THEN-ELSE except that one of the show later, the structure you use makes a difference in
paths contains no action. An example ol this is: the actual assembly language program you write to im-
plement it.
IF hungry THEN The WHILE-DO and REPEAT-UNTIL structures con-
Get food tainsimple
a IF—THEN-ELSE decision operation. How-
ever, since
this decision is an implied part of these two
I he assumpt ion tor tins example is thai if you are not structures, we don't indicate the decision separately in
hungry, you will just continue on with your next task. them.

46 i M 'NIK THRFt
-r
1 %:
u /

>% -'

-
,' 5 * :% m
I „ ^ (- O O
< tn O * 5-
:. LI.

<

2 -

5>o
- <

z <
LU (J

g 2
5 —- 1
< < --' ~
-
1
Q L_

T
TO

§
C Z
•a 0
X
s
h-
-,-
/

:

OS C
_ i
"5
u
— E

8086 FAMILYASSEMBLY
LANGUAGEPROGRAMMING- INTRODUCTION 47
Another form of the repetition operation that you more complex programming problems, a sequential list
might see in high level language programs is the FOR- may become very messy because it has little real struc-
DO loop.
This structure has the form: ture standardization.
or Another way of representing
program operations is with flowcharts. Flowcharts are a
FOR count = 1 TO n DO very graphic representation, and they are useful for
statement short program segments, especially those that deal di-
statement rectly with
hardware. However, flowcharts use a great
deal of space. Consequently, the flowchart for even a
moderately complex program may take up several pages.
In assembly language we usually implement this type of
It often becomes difficult to follow program flow back
operation with a REPEAT-UNTIL structure, so we have
and forth between pages. Also, since there are no
not included a sample of it.
agreed-upon structures, a poor programmer can write a
The CASE structure shown in Figure 3-3/ is a com-
flowchart which jumps all over the place and is even
pact way
of representing a choice among several alterna-
more difficult to follow. The term "logical spaghetti"
tive actions.The choice is determined by testing some
comes to mind here.
quantity. The example in Figure 3-3/ best shows how
A third way of representing the operations you want
this is used. This everyday example describes the de-
in a program is with a top-down design approach and
sired actions
for a cook in a restaurant. The pseudocode
standard program structures. The overall program
is just a summary of the thinking the cook might go
problem is first broken down into major functional
through. The cook or the computer checks the value of
modules. Each of these modules is broken down into
the variable called "day" and selects the appropriate ac-
smaller and smaller modules until the steps in each
tionsthat
for day. Each of the indicated actions, such as
module are obvious. The algorithms for the whole pro-
"Make celery soup." is itself a sequence of actions which
gram andfor each module are each expressed with a
could be represented by the structures we have de-
standard structure. Only three basic structures.
scribed.
SEQUENCE, IF-THEN-ELSE. and WHILE-DO. are
The CASE structure is really just a compact way to
needed to represent any needed program action or series
represent a complex IF-THEN-ELSE structure. To il-
of actions. However, other useful structures such as IF-
lustrateFigure
this, 3-3g also shows how the soup cook
THEN, REPEAT-UNTIL. FOR-DO. and CASE can be
example can be represented as a series of IF-THEN-
derived from these basic three. A structure can contain
ELSE structures. Note that, in this example, the last
another structure of the same type or one of the other
IF-THEN has no ELSE after it because all of the possible
types. Each structure has only one entry point and one
days have been checked. You can, if you want, add the
exit point. These programing structures may seem re-
final ELSE to the IF-THEN-ELSE chain to send an
strictive,
using
but them usually results in program rep-
error message if the data does not match any of the
resentationsarewhich
easy to understand and for
choices. The CASE structure does contain the final
which it is easy to write the programs. A program writ-
ELSE, however. The CASE form is more compact for
ten ina structured manner is easier to debug and
documentation purposes and some high-level languages
much more understandable to someone else who has to
such as Pascal allow you to implement it directly. How-
work on it. Furthermore, a program representation de-
ever, the
IF-THEN-ELSE structure gives you a much
velopedstructured
with programming techniques can
better idea of how you write an assembly language pro-
be implemented easily in assembly language or in a
gram sectionto choose between several alternative ac-
high-level language such as Modula II or C.
tions.
Throughout the rest of this book we show you how to
use these structures to represent program actions and Finding the Right Instruction
how to implement these structures in assembly lan-
After you get the structure of a program worked out and
guage.
written down, the next step is to determine the instruc-
tion statements required to do each part of the program.
SUMMARY OF PROGRAM STRUCTURE
Since the examples in this book are based on the 8086
REPRESENTATION FORMS
family of microprocessors, now is a good time to give you
Writing a successful program does not consist of just an overview of the instructions the 8086 has for you to
writing down a series of instructions. You must first use.
think carefully about what you want the program to do You do not usually learn a new language by studying
and how you want the program to do it. Then you must its dictionary from cover to cover. It is more productive
represent the structure of the program in some way that to first learn a few very useful words and learn how to
is very clear to you and to anyone else who might have to put together simple sentences. You can then learn more
work on the program. If the structure is well developed, words as you need them to express more complex
it is usually not a difficult step to write the actual pro- thoughts. Chapter 6 contains a dictionary of all of the
gramming language
statements that implement it. 8086 instructions with detailed descriptions and exam-
One way of representing program operations is with a ples for
each. You can use this as a reference as you
sequential lask list. For initial thinking and simple pro- write programs. Here we simply list the 8086 instruc-
gramming problems
this technique works well. For tions
Junctional
in groups with single-sentence descrip-

48 CHAPTER IHKft
lions so thai you can see the types ol Instructions thai SAH1 Store (copy) All registei to low byte ol flag
are available to you. As you read through this set tlon, do registei .
not expect to understand all ol the Instructions. When
PUSHF Copy 11«iLi,register to top ol stack.
you si. u i writing programs, you will probably use ihis
section to determine the type of Instruction and Chapter POPF Copy word at top ol stack to flag registi i
6 to get the Instruction details .is you need them. Aftei
you have written a few programs, you will remember ARITHMI IK INSIRIK IIONS
most oi the basic Instruction types and will be able to
Addition instructions:
|ust look up an instruction in Chapter 6 to get any addl
tional del. ills you need. Chaptei I shows you in detail
ADD Add specified byte to byte, oi specified word
how to use the move, arithmetic, logical, jump, and to word.
string instructions. Chapter 5 shows how to use the call
Instructions and the stack. ADC Add byte * byte • carry flag oi word
As von skmi through the following overview ol the word • (airy flag.
8086 instructions, see II you can find the instructions
INC Increment specified byte or specified word by
needed to do the "read temperature sensor value from a
one.
port, add I 7. and store result in memory" example pro-
gram. AAA ASCII adjust alter addition

DATA TRANSFER INSTRUCTIONS DAA Decimal (BCD) adjust after addition.

General-purpose byte or word transfer instructions:


Subtraction instructions:
MNEMONIC DESCRIPTION
SUB Subtract byte from byte, or word from word.
MOV Copy byte or word from specified source to
specified destination. SBB Subtract byte and carry flag from byte, or
word and carry flag from word.
PUSH Copy specified word to top of stack.
DEC Decrement specified byte or specified word
POP Copy word from top of stack to specified
by one.
location.
NEC Negate— invert each bit of a specified byte or
PUSHA (80186/80188 ONLY) Copy all registers to
word and add 1 (form 2's complement).
stack.
CMP Compare two specified bytes or two specified
POPA (80186/80188 ONLY) Copy words from
words.
stack to all registers.
AAS ASCII adjust after subtraction.
XCHG Exchange bytes or exchange words.
DAS Decimal (BCD) adjust after subtraction.
XLAT Translate a byte in AL using a table in
memory.
Multiplication instructions:
Simple input and output port transfer instructions:
MUL Multiply unsigned byte by byte or unsigned
IN Copy a byte or word from specified port to word by word.
accumulator.
IMUL Multiply signed byte by byte or signed word
OUT Copy a byte or word from accumulator to by word.
specified port. AAM ASCII adjust after multiply.

Special address transfer instructions:


Division instructions:

LEA Load effective address of operand into


DIV Divide unsigned word by byte, or unsigned
specified register.
double word by word.
LDS Load DS register and other specified
IDIV Divide signed word by byte, or signed double
register from memory.
word by word.
LES Load ES register and other specified
AAD ASCII adjust before division.
register from memory.
CBW Fill upper byte of word with copies of sign
Flag transfer instructions: bit of lower byte.

LAHF Load (copy to) AH with the low byte of the CWD Fill upper word of double word with sign bit
of lower word.
flag register.

8086 FAMILY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION 4«)


BIT MANIPULATION INSTRUCTION'S REPNE REPNZ An instruction prefix.
Repeat until CX = 0 or
Logical instructions:
ZF = 1.
NOT Invert each bit of a byte or word. MOVS MOVSB MOVSW Move bvte or word from
one string to another.
AX I J AND each bit in byte or word with the
corresponding bit in another byte or COMPS COMPSB COMPSW Compare two string
word. bytes or two string
i >1< OR each bit in a byte or word with the words.
i orresponding bit in another byte or 1XS IXSB IXSW 180186 80188) Input
word. string byte or word from
XOR Exclusive OR each bit in a byte or word port.
with the corresponding bit in another OUTS OUTSB OUTSW (80186 80188) Output
byte or word. string byte or word to
AND operands to update flags, but don't port.
change operands. SCAS SCASB SCASW Scan a string. Compare
a string bvte with bvte
Shift instructions: in AL or a string word
with word in AX.
SHL SAL Shift bits of word or byte left, put zero(s|
LODS LODSB LODSW Load string byte into AL
in LSB(s).
or string word into AX.
SHR Shift bits of word or byte right, put
STOS STOSB STOSW Store byte from .AL or
zero(s) m MSI
word from AX into
SAR Shift bits of word or byte right, copy old string.
MSB into new MSB.
PROGRAM EXECUTION TRANSFER
Rotate instructions: INSTRUCTIONS

These instructions are used to tell the 8086 to start


ROL Rotate bits ol byte or word left. MSB to
fetching instructions from some new address, rather
LSB and to CF.
than continuing in sequence.
ROR Rotate bits of byte or word right. LSB to
MSB and to CF.' Unconditional transfer instructions:

RCL Rotate bits of byte or word left. MSB to


CALL Call a procedure (subprogram), save return
CF and CF to LSB.
address on stack.
RCR Rotate bits nt byte or word right. LSB to RET Return from procedure to calling program.
CF and CF to MSB.
JMP Go to specified address to get next
instruction.
STRING INSTRUCTIONS

NOTES A string is a series of bytes or a series of Conditional transfer instructions:


words in sequential memory locations. A strum often
\( )TE A " " is used to separate two mnemonics which
consists of ASCII character codes. In the list a " " is
represent the same instruction. Use the mnemonic
used to separate different mnemonics for the same
which most clearly describes the decision condition in a
instruction. Use the mnemonic which most clearlv
specific program. These instructions are often used
describes the function of the instruction in a spe-
after a compare instruction. The terms below and
cific application. A "B" in a mnemonic is used to
a/wre refer to unsigned binary numbers. Above means
specifically indicate that a string of bytes is to be
larger in magnitude. The terms greater than or less
acted upon. A "W" in the mnemonic is used to in-
than refer to signed binary numbers. Greater than
dii ate that a string of words is to be acted upon.
means more positive.
REP An instruction prefix.
JA JXBE Jump if above Jump if not below nor
Repeat following
equal.
instruction until CX =
(i
JAE JNB Jump if above or equal Jump if not
REPEREPZ
below.
An instruction prefix.
Repeat instruction until JB JNAE Jump if below Jump if not above nor
CX = 0 or ZF -%1 equal.

50 CHAPTER THRU
JBE JNA Jump il below or equal Jump il nol INTO Interrupt program execution it overflow
above. flag I.

,ic Jump il carry flag \CV) 1. [RET Return from interrupt service procedure
to main program
JE JZ Jump il equal Jump il zero flag (ZF) I

JG JNLE Jump il greater Jump it nol less than //n//i level language interface instructions
noi equal
ENTER (80186 80188 ( INLY) Enter procedure.
JGE JNL Jump il greater than or equal Jump il
noi less than. I 1. \\i (80186/80188 ONLY) Leave procedure.

HOUND (.sols), 80188 < INLY) cheek il effei tive


JL/JNGE Jump it less than/Jump it nol greater
address within specified array bounds.
i han nor equal.
JLE JNG Jump it less (han or equal Jump it nol PROCESSOR CONTROL INSTRUCTIONS
greatei than
Flag set/clear instructions:
JNC Jump it no carry (Jump il carry lla^
0). STC Set carry Hag (CF) to 1.

JNE.JNZ Jump il not equal/Jump il nol zero (zero CLC ( le.11 carry flag (CF) to 0.
flag = 0).
CMC Complement the state ol the earn' flag [< I
JNO Jump if no overflow (Jump if overflow
STD Set direct ion flag (DPI to 1 (decrement
flag = 0).
string pointers).
JNP/JPO Jump if not parity/Jump it parity odd
CLD Clear direction flati (DF) to 0.
(PF = 0).
STI Set interrupt enable flag to 1 (enable 1NTR
JNS Jump if not sign (Jump it sign flag = 0).
input I.
JO Jump if overflow flag = 1.
CL1 Clear interrupt enable flag to 0 (disable
JP/JPE Jump if parity/Jump if parity even (PF - INTR input).
1).
External hardware synchronization instructions:
JS Jump if sign flag = 1.

Iteration control instructions: HLT Halt (do nothing! until interrupt or reset.

WAIT Wait (do nothing) until signal on the TEST


These instructions can be used to execute a series of
pin is low.
instructions some number of times. Here mnemonics
separated by a "/" represent the same instruction. Use ESC Escape to external coprocessor such as

the one that best fits the specific application. 8087 or 8089.

LOCK An instruction prefix. Prevents another


LOOP Loop through a sequence of processor from taking bus while the
instructions until CX = 0. adjacent instruction executes.
LOOPE/LOOPZ Loop through a sequence of
instructions while zero flag = 1 No operation instruction:
and CX * 0.
NOP No action except fetch and decode.
LOOPNE/LOOPNZ Loop through a sequence of
instructions while zero flag = 0
and CX # 0. Now that you have glanced through an overview of the
JCXZ Jump to specified address if CX 8086 instruction set. let's see if you found the instruc-
tions neededto implement the "read sensor, add +7.
0.
and store result in memory'' example program. The IN
instruction can be used to read the temperature value
If you aren't tired of instructions, continue skimming
through the rest of the list. Don't worry if the explana- from an A/D converter connected to a port. The ADD in-
struction
be can
used to add the correction factor of +7
tionnot
is clear to you because we will explain these
to the value read in. Finally, the MOV instruction can be
instructions in detail in later chapters.
used to copy the result of the addition to a memory loca-
Interrupt instructions: tion.
major
A point here is that breaking the program-
ming problem down into a sequence of steps makes it
INT Interrupt program execution, call service easy to find the instruction or small group of instruc-
procedure. tions that
will perform each step. The next section

8086 FAMIlY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION ^)1


shows you how to write the actual program using these 8259A priority interrupt controller
instructions.
8254 programmable counter
8251 A programmable serial port
Writing a Program Initialize data variables

INITIALIZATION INSTRUCTIONS Reset/clear direction flag and interrupt enable flag


Alter finding the instructions needed to do the main As you can see, the list can become quite lengthy even
part of your program, there are a few additional instruc- though we have not included all of the devices a system
tions youneed to determine before you actually write might commonly have. Note that initializing the code
your program. The purpose of these additional instruc- segment register is absent from this list. The code seg-
tionsto isinitialize various parts of the system such as ment register
gets loaded with the correct starting value
segment registers, flags, and programmable port de- by the system command you use to run the program.
vices. Segment registers, for example, must be loaded Now let's see how you put all of these parts together to
with the upper 16 bits of the address in memory where make a program.
you want the segment to begin. For our "read tempera-
ture sensor,add +7, and store result in memory" exam- A STANDARD PROGRAM FORMAT
ple program, the only part we need to initialize is the
In this section we show you the form your programs
data segment register. The data segment register must
should have if you are going to construct the machine
be initialized so that we can copy the result of the addi-
codes for each instruction by hand. A later section of
tionatolocation in memory. If. for example, we want to
this chapter will show you the additional parts you need
store data in memory starting at address 00100H. then
to add to the program if you are going to use an assem-
we want the data segment register to contain the upper
bler produce
to the binary codes for the instructions.
16 bits of this address, 0010H. The 8086 does not have
To help you format your programs, assembly lan-
an instruction to move a number directly into a segment
guage coding
sheets such as that shown in Figure 3-4
register. Therefore, we move the desired number into
are available. The address column is used for the ad-
one of the 16-bit general-purpose registers, and then
dress
theor offset of a code byte or data byte. The actual
copy it to the desired segment register. Two MOV in-
code bytes or data bytes are put in the data/code col-
structions
do will
this.
umn.
label
A is a name which represents an address
If you are using the stack in your program, then you
referred to in a jump or call instruction. A label is put in
must include an instruction to load the stack pointer
the label column. It is followed by a colon (:| if it is used
register with the offset of the top of the stack. Most mi-
by a jump or call instruction in the same code segment.
crocomputer systems
contain several programmable
The opcode column contains the mnemonics for the
peripheral devices such as ports, timers, and control-
instructions. The operand column contains the regis-
lers. Youmust include instructions which send control
ters, memorylocations, or data acted upon by the in-
words to these devices to tell them the function you
structions.
comment A column gives you space to de-
want them to perform. Also, you usually want to include
scribe the
function of the instruction for future
instructions which set or clear the control flags such as
reference.
the interrupt enable flag and the direction flag.
Figure 3-4 shows how the instructions for the "read
The best way to approach the initialization task is to
temperature, add +7, store result in memory" program
make a checklist of all the registers, programmable de-
can be written in sequence on a coding sheet. We will
vices, flags
and in the system you are working on. Then
discuss here the operation of these instructions to the
you can mark the ones you need for a specific program
extent needed. If you want more information about any
and determine the instructions needed to initialize each
of these, detailed descriptions of the syntax (assembly
part. An initialization list for an 8086-based system,
language grammar) and operation of each of these in-
such as the SDK-86 prototyping board, might look like
structions
be can
found in Chapter 6.
the following.
The first line at the top of coding form in Figure 3-4
does not represent an instruction. It simply indicates
INITIALIZATION LIST that we want to set aside a memory location to store the

Data segment register result. This location must be in available RAM so that
we can write to it. Address 00100H is an available RAM
Stack segment register location on an SDK-86 prototyping board, for example.

Extra segment register Next, we decide where in memory we want to start put-
ting the
code bytes for the instructions of the program.
Stack pointer register Again, on an SDK-86 prototyping board, address
00200H and above is available RAM. so we chose to start
Base pointer register
the program at address 00200H.
Source index register The first operation we want to do in the program is to
initialize the data segment register. As discussed previ-
Destination index register
ously, MOV
two instructions are used to do this. The
8255 programmable ports MOV AX, 0010H instruction, when executed, will load

52 ( HAIMIR IHRU
PROGRAMMER 2> Mill I

PROGRAM TITLE &


,-, : a \oc ...% •:eadi ••: %t •>%%<\oLt %vain % i%ienion. connected %
[acton ol +7 to the value %I • ..... % eittlt ••%.
None coiled.
R£Q!)S7£t%'kSC^. A*
- ., . ,.-.:. utuui ..

1/tiei 05 aA-input pont


MCMOMj. 00/OOJl ^AHA; 00200J4 -0020GJ, G05>£

DATA
ADDRESS 1 ABI 1 S MNEM. OPERAND(S) COMMENTS
or
CODE

!, '•, 'ii XX Qeiemte memonu location to to <

" . :1 leAntt. 'llwi location- uull ae loaded


V utdk a data Lute oA-lead in

00/03 Z connected
luf Ike pnoanam.
00/04 XX meanA- dan t cane amid
00/05 contenti ol location.

00/06

00/07

00/08

00/09

00/OA

00/08

00)00.

00/OD

00/OE Code itanti kene

00/OF Note bleak in addneA-i

200 38 MOV AX. 00/OJf 9ndiaii'ie 2)£ to point to itaAt o[


0\ 10 memoMf,
iet aAide[on.itouna-data
02 00

Oi sS MOV 2>£, AX
04 2>8
OS .:'• M AI, 05Jl Readtempenatune
[nom
Ob 05 pont 05Jl
07 04 A2>2> AZ 07Jl Add connection
[acton
(98 07 o[ +07
09 A2 MOV [oooo], Alt Stale leinlt in leie-Mied

OA 00 .;/. •>:.. :,:

OB 00

OC gg Ml i Stop, utait [on command


00 [namu4en
OE

Of

FIGURE 3-4 Assembly language program on standard coding form.


53
the upper 16 bits of the address we chose for data stor- has shown that even a short program that you wrote a
age into the AX register. The MOV DS, AX instruction month ago and forgot to put comments on may not be at
will copy this number from the AX register to the data all understandable to you now.
segment register. Now we get to the instructions that do
what we started out to do. The IN AL, 05H instruction
will copy a data byte from port 05H to the AL register.
CONSTRUCTING THE MACHINE CODES
The ADD AL, 07 instruction will add 07H to the AL regis-
FOR 8086 INSTRUCTIONS
ter andleave the result in the AL register. The MOV
[0000], AL instruction will copy the byte in AL to a mem- This section shows you how to construct the binary
ory location at a displacement of 0000H from the data codes for 8086 instructions. Most of the time you will
segment base. In other words. AL will be copied to a probably use an assembler do this for you, but it is use-
physical address computed by shifting the data segment ful to
understand how the codes are constructed. If you
base in DS, 001 OH. four bit positions left and adding have an 8086-based prototyping board such as the Intel
the displacement. 0000H. contained in the instruction. SDK-86 available, knowing how to hand-code instruc-
The data will then be copied to physical address 00 100H tions will
enable you to code, enter, and run simple pro-
in memory. This is an example of the direct addressing grams
you
as work your way through the 8086 instruc-
mode described near the end of the previous chapter. tion set
examples in the next chapters.
The INT 3 instruction at the end of the program func-
tionsa asbreakpoint. In most 8086 systems, when the
8086 executes this instruction it will cause the 8086 to
stop executing the instructions of your program and Instruction Templates
return control to the monitor or system program. You To code the instructions for 8-bit processors such as the
can then use system commands to look at the contents 8085. all you have to do is look up the hexadecimal code
of registers and memory locations, or run another pro- for each instruction on a one-page chart. For the 8086
gram. Without an instruction such as this at the end of the process is not quite as simple. Here's why. There are
the program, the 8086 would fetch and execute the code 32 ways to specify the source of the operand in an in-
bytes for your program, and then it would go on fetching structionassuchMOV CX, source. The source of the
meaningless bytes from memory and trying to execute operand can be any one of eight 16-bit registers, or a
them as if they were code bytes. memory location specified by any one of 24 memory ad-
The next major section of this chapter will show you dressing modes.
Each of the 32 possible instructions
how to construct the binary codes for these and other requires a different binary code. If CX is made the
8086 instructions so that you can assemble and run the source rather than the destination then there are 32
programs on a development board such as the SDK-86. ways of specifying the destination. Each of these 32
First, however, we want to use Figure 3-4 to make an possible instructions requires a different binary code.
important point about writing assembly language pro- There are then 64 different codes for MOV instructions
grams. using CX as a source or as a destination. Likewise, an-
othercodes
64 are required to specify all of the possible
MOVs using CL as a source or a destination, and 64
DOCUMENTATION
more are required to specify all of the possible MOVs
In a previous section of this chapter we stressed the using CH as a source or a destination. The point here is
point that you should do a lot of thinking and carefully that, because there is such a large number of possible
write down the algorithm for a program before you start codes for the 8086 instructions, it is impractical to list
writing instruction statements. You should also docu- them all in a simple table. Instead, we use a template for
ment the
program itself so that its operation is clear to each basic instruction type and fill in bits within this
you and to anyone else who needs to understand it. template to indicate the desired addressing mode, data
Each page of the program should contain the name of type, etc. In other words, we build up the instruction
the program, the page number, the name of the pro- codes on a bit-by-bit basis.
grammer,
perhaps
and a version number. Each pro- Different Intel literature shows the code templates for
gramprocedure
or should have a heading block which the 8086 instructions in two slightly different formats.
contains an abstract describing what the program is One format is shown at the end of the 8086 data sheet in
supposed to do, which procedures it calls, which regis- Appendix A. The second format is shown along with the
tersuses,
it which ports it uses, which flags it affects, 8086 instruction timings in Appendix B. We will start by
the memory used, and any other information which will showing you how to use the templates shown in the
make it easier for another programmer to interface with 8086 data sheet. As a first example of how to use these
the program. templates we will build the code for the IN AL, 05H in-
Comments should be used generously to describe the structionourfromexample program. Figure 3-5a shows
specific function of an instruction or group of instruc- the template for this instruction. Note that two bytes are
tions Not
every statement needs an individual com- required for the instruction. The upper 7 bits of the first
iii iii ( omments should not just repeat the instruction byte tell the 8086 that this is an "input from a fixed
mnemonii port'' instruction. The bit labeled W in the template is
We cannot overemphasize the importance of clear. used to tell the 8086 whether you want to input a byte or
concise documentation in your programs. Experience input a word. If you want the 8086 to input a byte from

",4 ( HAI'TIK THREt


i kiii ici.i register. Note ili.ii a I leasl two code bytes are
1 1 I J i equlred for the Insl rui lion
I he uppei (> bils ol the liisi byte are an opcode which
OPCODE FOR "IN"
indicates the general type "I instruction. Look in the
v. n ic i i table in Appendix A i<> find the 6-bil opcode for tins
W 1 WORD M( )V reglstei memory in from register instruction. Win
should find il id In- 1000 10. The W bit in the In si word
is used to indicate whether a byte oi .i word is being
moved. II you are moving a byte, make this bit a 0. II you
1 1 0 0 1 0 0 0 i) 0 0 II 1 0 arc moving .i word, make this bil a I. In ibis instruc
i inn. inn- operand must always be a register, so 3 bits in
OPCODE FOR IN" POR1 05H the second byte are used in indicate which registei is
Involved. The .''>bit codes foi each register are shown at
- INPUT A BYTE
the end oi the table in Appendix A and in Figure 3 7a
Look in one ol these places in find the code for the CL
register. You should gel 001 . The I) bit in the first byte
ADDRESS CONTENTS of the instruction code is used to indicate whether the
nn w.n E4H
data is being moved to the register identified in the Rl C
00206 H IIMI field of the second byte or from that register. II you arc
moving dala to the register identified in the Kid field,
make the D bit a 1. If you are moving data from thai
FIGURI i-">Coding template for 80Kb IN (fixed-port) register, make the D bit a 0.
instruction, (a) Template, (b) Example, (c) Hex (odes in Now remember that in this instruction one operand
sequential memory locations. must be a register. The 2-bit field labeled MOD and the
3-bit field labeled R/M in the second byte of the instruc-
tion code
are used to specify the desired addressing
an 8-bit pint to AL, then make the W bit a 0. If you want mode for the other operand. Figure 3-8 shows the MOD
the 8086 to input a word from a 16-bit port to the AX and R/M bit patterns for each of the 32 possible address-
register, then make the W bit a 1. The 8-bit port ad- ing modes.
dress. 05H
or 00000101 binary, is put in the second If the other operand in the instruction is also one of
byte (if I he instruction. When the program is loaded into the eight registers, then put in 1 1 for the MOD bits in
memory to be run. the first instruction byte will be put the code template. Put the 3-bit code for that register in
in one memory location and the second instruction byte the R/M bits in the code template.
will be put in the next. Figure 3-5c shows this in hexa- For the case where the other operand is a memory lo-
decimalas
formE4H. 05H. cation there
are 24 ways of specifying how the execution
To further illustrate how these templates are used, we unit should compute the effective address of the oper-
will show here several examples with the simple MOV and in
memory. Remember from Chapter 2 that the ef-
instruction. We will then construct the codes for the fective address
can be specified directly in the instruc-
example program in Figure 3-4. Other examples will be tion,can
it be contained in a register, or it can be the
shown as needed in the following chapters. Figure 3-6 sum of one or two registers and a displacement. Figure
shows the coding template or format for 8086 instruc- 3-8 shows the MOD and R/M codes for each of the 24
tions which
MOV data from a register to a register, from ways of specifying an effective address. The MOD code
a register to a memory location, or from a memory loca- indicates whether the address specification in the in-

REGISTER SELECT (SEE FIGURE 3-7)

BYTE 3 BYTE 4

1 | 0 | 0 | 0 | 1| 0 1 1 LOWDISPLACEMENT
j HIGHDISPLACEMENT
OPCODE D w MOD REG R/M
I

DIRECT ADDRESS DIRECT ADDRESS


LOW BYTE HIGH BYTE

• (5 BITS! ADDRESSING MODE (SEE FIGURE 3-8)


BYTE/WORD DATA 0 = BYTE 1 = WORD
DIRECTION TO/FROM REG 0=FROM 1 = TO

OPERATION CODE

FIGURE 3-6 Coding template for 8086 instructions which MOV data between
registers or between a register and a memory location.

8086 FAMILY ASSEMBLY LANGUAGE PROGRAMMING — INTRODUCTION r>.->


REG FIELD BIT ASSIGNMENTS struction contains a displacement. The R/M code indi-
cates which register(s) contain part(s) of the effective
If- W = 1 16-BIT REGISTER address. Here's how it works:

REGISTER CODE I. [f the specified effective address contains no dis-


placement
in theas instruction MOV CX, |BX] or in
AX 000 the instruction MOV [BX][SI], DX. then make the
MOD bits 00. and chose the R/M bits which corre-
r %; 00 1 spond
theto registerls) containing the effective ad-
dress.example,
For if an instruction contains [BX],
the 3-bit R/M code is 111. For an instruction which
DX 0 10
contains [BX)[SI], the R/M code is 000. Note that for
direct addressing where the displacement of the
BX 011
operand from the segment base is specified directly
in the instruction, MOD is 00 and R/M is 110. For
SP 100 an instruction using direct addressing the low byte
of the direct address is put in as a third instruction
BP 101 code byte of the instruction, and the high byte of the
direct address is put in as a fourth instruction code
BI 1 10 byte.

2. II the effective address specified in the instruction


D I 111 contains a displacement less than 256 along with a
reference to the contents of a register, as in the in-
IF W = 0 S-BIT REGISTER struction MOV CX, 43H[BX], then code in MOD as
01, and chose the R/M bits which correspond to the
REG ISTER CODE registerls) which contain the part(s) for the effective
address. For the instruction MOV CX, 43H[BX],
AL 000 MOD will be 01 and R/M will be 111. Put the 8-bit
value of the displacement in as the third byte of the
p. (-)fj, 1 instruction.
3. If the expression for the effective address contains a
DL 010 displacement which is too large to fit in 8 bits, as in
the instruction MOV DX, 4527H[BX], then put in 10
oi 0 1 i for MOD. and chose the R/M bits which correspond
to the registerls! which contain the part(s) for the
effective address. For the instruction MOV DX,
AH 1 00
4527H[BX| the R/M bits are 111. The low byte of the
displacement is put in as a third byte of the instruc-
CH 101.
tion. The
high byte of the displacement is put in as a
fourth byte of the instruction. The examples which
DH 1 10 follow should help clarify all of this for you.

BH 1 1 1
MOV Instruction Coding Examples
All of the examples in this section use the MOV instruc-
..„„,- r-.,^ „„ tion template in Figure 3-6. As you read through these
SbbREG CODE , .. , „ , . . . , t , c .. ." . ,.t
examples, it is a good idea to keep track of the bit-by-bit
development on a separate paper for practice.
ES 00

CODING MOV SP, BX


CS 01
This instruction will copy a word from the BX register to
the SP register. Consulting the table in Appendix A, you
SS 10
find that the 6-bit opcode for this instruction is 100010.
Make the W bit a 1 because you are moving a word. The
DS 1 1
D bit for this instruction may be somewhat confusing,
however. Since two registers are involved, you can think
(ft)
of the move as to SP, or from BX. Actually, it does not
FIGURE 5-7 Instruction codes tor 8086 registers. matter which you assume as long as you are consistent
(a) General purpose, pointers, and index, (b) Segment in coding the rest of the instruction. If you think of the
registers. instruction as moving a word to SP, then make the D bit

56 ( HAPTER IMKII
R M 00 01 in 11

W i) U 1

000 BX ' I [BX] • [SI] • d8 |BX| + |SI| • ilhi

001 |BX| + |l)l| |BX| I |l >l| i d8 [BX] 1 il HI • di6 ( 1 ( X

010 [BP] + [SI] [BP] • [SI] • d8 IBP] I |SI| • d16 1)1 DX

nl 1 IBP] i [Oil |BP] t [01] • do [BP] I |DI] • d16 Bl BX

100 [SI] |SI| ' d8 [SI] • d16 All SP

101 11)11 nil . (I:; |DI| • (IK. (II BP

1 10 (IK. [BP1 d8 |BP| + (IK, DH SI


(d i re< t address)

111 |B\| [BX] i (!;% ! |BX| i (IK. BH Dl

Ml Ml IRY MODI: REGISTER MODE

d8 = O-lnt displacement dl 6 16-bit displacement


FIGURE 3-8 MOD and R/M bit patterns for 0006 instructions. The effective
address (EA) produced by these addressing modes will be added to the data-
segment base to form the physical address except for those cases where BP is
used as part of the EA. In that case the EA will be added to the stack-segment
base to form the physical address. You can use a segment-override prefix to
indicate that you want the EA to be added to some other segment base.

a 1. and put 100 in the REG field to represent SP. The the table. Read the required MOD-bit pattern from the
MOD field will be 11 to represent register addressing top of the column. In this case. MOD is 00. Then read
mode. Make the R/M field 01 1 to represent the other reg- the required R/M-bit pattern at the left of the box. For
ister, BX.
The resultant code for the instruction MOV this instruction you should find R/M to be 111. Assem-
SP,BX will be 10001011 11100011. Figure 3-9a shows blingofallthese bits together should give you 10001010
the meaning of all of these bits. 00001 1 1 1 as the binary code for the instruction MOV
If you change the D bit to a 0 and swap the codes in CL, [BX], Figure 3-9c summarizes the meaning of all the
the REG and R/M fields, you will get 10001001 bits in this result.
11011 100. which is another equally valid code for the
instruction. Figure 3-9b shows the meaning of the bits MOV 43H[SI], DH
in this form. This second form, incidentally, is the form
This instruction will copy a byte from the DH register to
that the Intel 8086 Macroassembler produces.
a memory location. The effective address of the memory
location will be computed by adding the indicated dis-
CODING MOV CL, [BX]
placement
43H toof the contents of the SI register. The
This instruction will copy a byte to CL from the memory actual physical address will be produced by shifting the
location whose effective address is contained in BX. The contents of the data segment base in DS 4 bits left and
effective address will be added to the data segment base adding this effective address to the result.
in DS to produce the physical address. The 6-bit opcode for this instruction is again 100010.
To find the 6-bit opcode for byte one of the instruc- Make the D bit a 0 because you are moving/rom a regis-
tion, consult the table in Appendix A. You should find ter. Makethe W bit a 0 because you are moving a byte.
that this code is 100010. Make the D bit a 1 because Put 110 in the REG field to represent the DH register.
data is being moved to register CL. Make the W bit a 0 The R/M field will be 100 because SI contains part of the
because the instruction is moving a byte into CL. Next effective address. Make the MOD field 01 because the
you need to put the 3-bit code which represents register displacement contained in the instruction. 43H, will fit
CL in the REG field of the second byte of the instruction in one bvte. If the specified displacement had been a
code. The codes for each register are shown in Figure number larger than FFH, then MOD would have been
3-7. In this figure you should find that the code for CL is 10. Putting all these pieces together gives 10001000
001. Now, all you need to determine is the bit patterns 01 1 10100 for the first two bytes of the instruction code.
for the MOD and R/M fields. Again use the table in Fig- The specified displacement, 43H or 0100001 1 binary is
ure 3-8to do this. To use the table, first find the box put after these two as a third instruction byte. Figure
containing the desired addressing mode. The box con- 3-9d shows this. If an instruction specifies a 16-bit dis-
taining |BX].
for example, is in the lower left corner of placement,
the then
low byte of the displacement is put

808b FAMILY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION 57


100010111 100011 MOV SP. BX 10001001 l|l|o|l|l|l|o|o| MOV
SP.BX

OPCODE FOR MOV R/M = BX OPCODE (MOV) '

'TO' REG -
L EG SP 'FROM' REG - REG BX

MOV WORD- REGISTER TO REGISTER MOV WORD- REGISTER TO REGISTER

BYTE 1 BYTE 2 1
|,|o 0 | 0 | 1| 0 ii 0 0 | 1 '!'!"! 1" 1
MOV CL, (BX] CODE
OPCOC R/M = [SI]
1 000101 000001 1 1
ROM' REG — I ;
'FROM' REG = DH
I IP I HI)!
VIOV RYTF
MOV BYTE 1 MEMORY, ONE BYTE
DISPLACEMENT
'TO' REG
1 BYTE 3
MOV BYTE MEMORY,
NO DISPLACEMENT n^ |o|o|o|o|i|i|

DISPLACEMENT = 43H

BYTE I BYTE 2
SEGMENT OVERRIDE PREFIX

H" li il 1 0| 1 1 0 0 0 | 0 | 1| 1| %
l"l I BYTE 1 I

001011
OPCODE
DIRECT
'TO' REG ' ADDRESSING
MOV WORD

BYTE 3
10001000000101 MOV CS [BX], DL
0 j 1| I | I | 1 | 0 | 1| II| 0 | I | " I '"'I n | II| I | I | MOV
CX,[437AH]
OP CODE
'
DIRECT ADDRESS DIRECT ADDRESS
'FROM' REG REG = DL
LOW BYTE HIGH BYTE
7AH 43H MOV BYTE MEMORY, NO DISPLACEMENT

(el

FIGURE 3-9 MOV instruction coding examples, la) MOV SP, BX. lb) MOV SP,
BX alternative. Id MOV CL, [BX]. Id) MOV 4?H [SI], DH. (e) MOV CX,
[437AH], If) MOV CS:[BX], DL.

in as byte three of the instruction code, and the high which is the mode specified by this instruction. For di-
byte of the displacement is put in as byte four of the rect addressing you should find MOD to be 00 and R/M
instruction code. to be 110. The first two code bytes for the instruction
then are 1000101 1 00001 1 10. These two bytes will be
CODING MOV CX, [437AH] followed by the low byte of the direct address, 7AH
(01 1 1 1010 binary) The high byte of the direct address
Tins instruction copies the contents of two memory lo-
43H (01000011 binary) will be put after that. The in-
cationsCX.
into The direct address or displacement of
struction
be willcoded into four successive memory
the first memory location from the start of the data seg-
addresses as 8BH, OEH. 7AH, and 43H. Figure 3-9e
ment
437AH.
is The physical memory address will be
spells this out in detail.
produced by shifting the contents of the data segment
register, DS, 4 bit positions left and adding this direct
CODING MOV CS:[BX], DL
address to the result.
The 6-bit opcode for this instruction is again lOOOlO. This instruction copies a byte from the DL register to a
Make the D bit a 1 and the W bit a 1 because you are memory location. The effective address for the memory
moving a word to CX. Put OOl in the REG field to repre- location is contained in the BX register. Normally an ef-
sent the
CX register, and then consult Figure 3-8 to find fective address
in BX will be added to the data segment
the MOD and R/M codes. In the first column of the fig- base in DS to produce the physical memory address. In
ure youshould find a b<>\ labeled "direct addressing." this instruction, CS: indicates that we want the BIU to

58 CHAPTER THREE
.idd the effective address to the code segmenl basi In < S \ni ) \i , on i
in produce the physical address ("he CS Is called a seg This instruction adds the immediate number 07H to the
ment ovei ride pn /i * AI. register and puts the resull in the Al. registi
When .in Instruction containing a segmenl override
simplest template to use foi coding this instruction is
prefix Is coded, an 8 bil code foi the segmenl override
found in the table in Appendix A undei the heading
prefix Is put in memorj before the code for the resl ol the
ADD Immediate to accumulator." the format is
Instruction. The code byte foi the segmenl ovei ride pre
10W, data byte, data byte. Since we are adding a
fix has the formal 001XX1 10. You Inserl a 2 bil code in
byte, the W hit should he a (I. the immediate data byte
pl.uc ol the X"s to Indicate which segment base you wanl
wi are adding will be put in the second code byte The
the effective address to be added to. I lie i tides for these
third code byte will not be needed because we are only
2 bus are .is follows 00 ES. 01 CS, 10 SS, and
adding a byte, the code then will be 00000100
I l DS. The segmenl override prefix byte foi CS then
00000111.
is 00101 l 10. For practice, code out the resl ol ihis in-
struction. Figure
3 9/ shows the result you should get
and how the code for the segment override prefix is put MOV [00001, AL
before the other code bytes for the Instruction.
This instruction copies the contents of the AL register to
a memory location. The direct address or displacement
ol the memory location fr the start of the data seg
ment is 0000H. The code template for this instruction is
Coding the Example Program
found in the table in Appendix A under the heading
Again, as you read through tins section follow the bit- "MOV — Accumulatoi to memory." The format ior the
by-bit development of the instruction codes on a sepa- instruction is 1010001W, address low byte, address
rate paper
for practice high bvte. Since the instruction moves a byte, the W bit
should be a 0. The low byte of the direct address is writ
MOV AX, 00 I OH ten in as the second instruction code byte, and the high
byte of the direct address is written in as the third in-
This instruction will move the immediate word 0010H
structionbyte.
code The codes for these 3 bytes then will
into the AX accumulator. The simplest code template to
be 10100010 00000000 00000000.
use for this instruction is listed in the table in Appendix
A under the MOV "immediate to register" heading. The
format for it is 1011 VV REG. data byte low. data byte INT 3
high. Make the W bit a 1 because you want to move a
word. Consult Figure 3-7 to find the code for the AX reg-
In most 8086 systems this instruction causes the 8086
to stop executing instructions and do nothing but wait
ister. You
should find this to be 000. Put this 3-bit code
for the user to tell it what to do next. According to the
in the REG field of the instruction code. The completed
format table in the appendix, the code for this instruc-
instruction code byte is 101 1 1000. Put the low byte of
the immediate number, 10H. in as the second code byte.
tionthe
is single byte 1 1001 100 or CCH.
Then put the high byte of the immediate data. 00H. in
as the third code byte. SUMMARY OF HAND CODING THE EXAMPLE
PROGRAM

MOV DS, AX Figure 3-4 shows the example program with all the in-
struction codes
in sequential order as you would write
This instruction copies the contents of the AX register
them so that you could load the program into memory
into the data segment register. The template to use for
and run it. Codes are in HEX to save space.
coding this instruction is found in the table in Appendix
A under the heading "Register/memory to segment reg-
ister." format
The for this template is 10001 1 10 MOD 0
segreg R/M . Segreg represents the 2-bit code for the de- A Look at Another Coding Template Format
sired segmentregister. These codes are also found in As we mentioned previously. Intel literature shows the
the table at the end of Appendix A. The segreg code for 8086 instruction coding templates in two different
the DS register is 1 1 . Since the other operand is a regis- forms. The preceeding sections have shown you how to
ter. MODshould be 11. Put the 3-bit code for the AX use the templates found in the 8086 data sheet in Ap-
register. 000, in the R/M field. The resultant codes for pendix
NowA. let's take a brief look at the second form
the two code bytes should then be 10001 110 1 101 1000. shown along with the instruction clock cycles in Appen-
dix B.
The only difference between the second form for the
IN AL, 05H templates and the form we discussed previously is that
This instruction copies a byte of data from port 05H to the D and W bits are not individually identified. Instead,
the AL register. The coding for this instruction was de- the complete opcode bytes are shown for each version of
scribed
a previous
in section. The code for the instruc- an instruction. For example, in Appendix B the opcode
tion11100100
Is 00000101. byte for the MOV memory, register 8 instruction is

8086 FAMILY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION 59


shown as 88H. and the opcode byte for the WOY mem- some features may be slightly different so consult the
ory, registerlb instruction is shown as 89H. The only manual for it.
difference between the two codes is that the W bit is a 0
for the 8-bit move and the VV bit is a 1 tor the 16-bit
move. One important point to make about using the Program Format
templates in Appendix B is that for operations which The best way to approach this section seems to be to
involve two registers, the 3-bit code for the source regis- show you a simple, but complete, program written for
ter is
put in the REG field of the MOD RM instruction an assembler and explain the function of the various
byte. The 3-bit code for the destination register is put in parts. By now you are probably tired of the "read tem-
the R M field of the MOD RM instruction byte. The in- perature,
-7. add
and store result in memory" program,
struction BX,
MOVCX, for example, is coded out as so we will use another example.
10001001 1 100101 1. or 89H CBH. You can use which- Figure 3-10 shows an 8086 assembly language pro-
ever set
of templates you find easier to use. gram whichmultiplies two 16-bit binary numbers to
give a 32-bit binary result. If you have a development
system or a computer with an 8086 assembler to work
A Few Words About Hand Coding
on. this is a good program for you to key in. assemble,
If you have to hand-code 8086 assembly language pro- and run to become familiar with the operation of your
grams,are
herea few tips to make your life easier. First, system. If you are working on a prototvping board such
check your algorithm very carefully to make sure thai it as the SDK-86. you can construct the binary codes for
really does what it is supposed to do. Second, initially each of the instructions, load the program into the on-
write down just the assembly language statements and board RAM.
and run it. In any case, you can use the
comments for your program. You can check the table in structure of this example program as a model for your
the appendix to determine how many bytes each in- own programs.
structionsotakes
you know how many blank lines to In addition to program instructions, the example pro-
leave between instruction statements. You may find it gramFigure
in 3-10 contains directions to the assem-
helpful to insert three or four NOP instructions after bler. These directions to the assembler are commonly
even' nine or ten instructions. The NOP instruction called assembler directives or pseudo operations. A sec-
doesn't do anything but kill time. However, if you acci- tion the
at end of Chapter 6 lists and describes for your

dentallyoutleavean instruction in your program, you reference a large number of the available assembler di-
can replace the NOPs with the needed instruction. This rectives. we
Herewill discuss the basic assembler direc-
way you don't have to rewrite the entire program after tives you
need to get started writing programs. We will
the missing instruction. introduce more of these directives as we need them in
After you have written down the instruction state- the next two chapters.
ments, recheck
very carefully to make sure you have the
right instructions to implement your algorithm. Then,
work out the binary codes for each instruction and write SEGMENT and ENDS Directives
them in the appropriate places on the coding form.
The SEGMENT and ENDS directives are used to identify
Hand coding is laborious for long programs. When
a group of data items or a group of instructions that you
writing long programs, it is much more efficient to use
want to be put together in a particular segment. These
an assembler. The next section of this chapter shows
directives are used in the same way that parentheses are
you how to write your programs so you can use an as-
used to group like terms in algebra. A group of data
sembler
produce
to the machine codes for the instruc-
tions. statements or a group of instruction statements con-
tained between
SEGMENT and ENDS directives is called
a logical segment. When you set up a logical segment.
you give it a name of your choosing. In the example
WRITING PROGRAMS FOR USE WITH program the statements DATA HERE SEGMENT and
AN ASSEMBLER DATA HERE ENDS set up a logical segment named
DATA HERE. There is nothing sacred about the name
If you have an 8086 assembler available, you should DATA HERE. We simply chose this name to help us re-
learn to use it as soon as possible. Besides doing the memberthis
that logical segment contains data state-
tedious task of producing the binary codes for vour in- ments. The
statements CODE HERE SEGMENT and
struction statements,an assembler also allows you to CODE HERE ENDS in the example program set up a logi-
refer to data items by name rather than by numerical cal segment named CODE HERE which contains in-
addresses. As you should soon see. this greatlv reduces struction statements.
The Intel and the IBM 8086 macro
the work you have to do and makes your programs assemblers, incidentally, allow you to use names and
much more readable. In this section we show you how to labels of up to 31 characters. You can't use spaces in a
write your programs so that you can use an assembler name, but you can use an underscore as shown to sepa-
on them. The assemblers used for the programs in this rate wordsin a name. Also, you can't use instruction
book were the Intel 8086 8088 80186 80188 M mnemonics as segment names or labels. Throughout
sembler and the Microsoft Macro Assembler for the IBM the rest of the program you will refer to a logical segment
Personal Computer. If you are using another assembler. bv the name that vou give it when vou define it.

60 CHAPTER THRFE
PAGI ,132 M ,i e listing file line! ' : ers w i do
18036 pi %¡g i .mi
; ABSTRACT I Ii I • I 'I i ii M 'Hi ffll I I. t 1 I %] 1 i " till' I W( ' 16 I'll t'i it il I
the memi <\ . Location: called Ml II (ill l CAI ID
MU1 TIPLIER. I In • resul 1 i • stored Ln thi n
i di at ion cal led PRODUCT
;P0R1 B USED : None
;PROCI DI IRI S IS! D: None
;ri listers u 3ED : CS , Di ;., DX and AX

DATA_HERE SEGMf N 1

MULT I PL ICAND DW 204AH fin I w< hi! here


MULTIPLIER DW 'H.Mll second wor d here
PRODUCT DW 2 DUP(0) i i •% iilt here

DATA HERE ENDS

CODE HERE SEGMENT


ASSUME CS CODE HERE DS : DATA._HERE

MOV AX, DATA HERE ; i n i t i a 1 i z e DS r eg i st er


MOV DS,AX

MOV AX, MULTIPLICAND get one word


MUL MULT IPLIER multiply by second word
MOV PRODUCT, AX store low word of result
MOV PRODUCT h-2, DX store high word of result
INT 3 wa i t -for com rn a n d f r o m u s e r

CODE HERE ENDS


END

FIGURE 3-10 Assembly language source program to multiply two 16-bit binary
numbers to give a 32-bit result.

A logical segment is not usually given a physical start- them by name rather than having to remember or calcu-
ing address when it is declared. After the program is late their value each time you refer to them in an in-
assembled, and perhaps linked with other assembled struction.
otherIn words, if you give names to con-
program modules, it is then assigned the physical ad- stants, variables, and addresses the assembler can use
dress where
it will be loaded in memory to be run. these names to find the desired data item or address
when you refer to it in an instruction. Specific directives
are used to give names to constants and variables in
Data and Addresses Naming Directives — EQU, your programs. Labels are used to give names to ad-
DB, DW, and DD dresses
yourin programs.

Programs work with three general categories of data:


constants, variables, and addresses. The value of a con-
THE EQU DIRECTIVE
stant does
not change during the execution of the pro- The EQU or equate directive is used to assign a name
gram. The
number 7 is an example of a constant you to constants used in your programs. The statement
might use in a program. A variable is the name given to CORRECTION FACTOR EQU 07H, in a program such as
a data item which can change during the execution of a our previous example, would tell the assembler to insert
program. The current temperature of an oven is an ex- the value 07H every time that it finds the name
ample
a variable.
of Addresses are referred to in many CORRECTION FACTOR in a program statement. In
instructions. You may. for example, load an address other words, when the assembler reads the statement
into a register or jump to an address. ADD AL, CORRECTION FACTOR, it will automatically
Constants, variables, and addresses used in your pro- code the instruction as if you had written it ADD AL,
grams can
be given names. This allows you to refer to 07H. Here's the advantage of using an EQU directive to

808b FAMItY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION 61


declare constants at the start of your program. Suppose MEMOF %

that you use the correction factor of -07H 23 times in


vour program. Now the company you work for changes
"iperature sensor and the new correction
factor is -09H. If you used the number 07H in the 23
:ons which contain this correction factor, then
HIGH WORD -
e to go through the entire program, find each
instruction that uses the correction factor, and update
_OWV = •
the value. Murphy's law being what it is. you are likely to
miss one or two of these, and the program won't work
correcdy. If you used an EQU at the start of your pro- . wu LT pL E.
gram and
then referred to CORRECTION TACTOR by
name in the 23 instructions, then all you do is change
START DF ML LT -- =AND
the value in the EQU statement from 07H to 09H and : -~- -e 2 e

reassemble the program. The assembler automatically


inserts the new value of 09H in all 23 instructions.
FIGURE 3-11 Data arrangement in memorv for multiplv
NOTE In large programs consisting of modules assem-
program.
bled separately, constants must be declared in each mod-
ule. The
assembler has no way to remember an EQU value
the name MULTIPLIER. When the program is loaded,
from one module when it assembles another module.
the first memory address will be initialized with 2AH.
and the second memory location with 3BH.
DB. DW. A\D DD DIRECTIVES
The third data declaration example in Figure 3-10.
The DB. DW. and DD directives are used to assign PRODUCT DW 2 DLPO . sets aside storage for two words
names to variables in your programs. The DB directive in memory and gives the starting address of the first
after a name specifies that the data is of type byte. The word the name PRODUCT. The DUPlO) part of the state-
program statement 0\ EN TEMPERATURE DB 2". for ex- ment tells
the assembler to initialize the two words to all
ample declaresa variable of type byte and gives it the zeros. When we multiply two 16-bit binary numbers, the
name OVEN". TEMPERATURE. D\V is used to specify product can be as large as 32 bits. Therefore, we must
that the data is of type trord (16 bits I. and DD is used to set aside this much space to store the product. We could
specify that the data is of type double word 132 bits). If have used the DD directive to declare PRODUCT as a
a number is written after the DB. D\V. or DD. the data double word. but. since in the program we move the re-
item will be initialized with that value when the pro- sult PRODUCT
to one word at a time, it is more conven-
gramloaded
is from disk into RAM. The statement ient to
declare PRODUCT as 2 words.
COW ERSIOV FACTORS DB 2~H.48H.32H.69H will de- Figure 3-1 1 shows how the data for MULTIPLICAND.
clare
data
a item of 4 bytes and initialize the 4 bytes with MULTIPLIER, and PRODUCT will actually be arranged
the specified 4 values. If we don't care what a data item in memory starting from the base of the DATAJTERE
is initialized to then we can indicate this with a segment. The first byte of MULTIPLICAND. 4AH. will be
in the statement TARE_\VEIGHT D\Y ?. Note that data at a displacement of zero from the segment base, be-
variables which are changed during the operation of a cause MULTIPLICAND is the first data item declared in
program should also be initialized with program in- the logical segment DATA_HERE. The displacement of
structions
that so the program can be rerun from the the second byte of MULTIPLICAND is 0001. The dis-
start without reloading it to initialize the variables. Fig- placement
the firstof byte of MULTIPLIER from the seg-
ure 3-10shows three more examples of naming and ini- ment base
is 0002H. and the displacement of the second
tializingitems.
data byte of MULTIPLIER is 0003H. These are the displace-
The first example. MULTIPLICAND DW 204AH. de- ments that
we would have to figure out for each data
clares
dataa word named MULTIPLICAND, and initial- item if we were not using names to refer to them.
izes thatdata word with the value 204AH. What this If the logical segment DATA_HERE is eventually put in
means is that the assembler will set aside two successive ROM or EPROM. then MULTIPLICAND will function as a
memory locations and assign the name MULTIPLICAND constant, because it cannot be changed during program
to the first location. As you will see. this allows us to execution. However, if DAT.A^HERE is eventually put in
access the data in these memory locations bv name. The RAM then MULTIPLICAND can function as a variable
MULTIPLICAND DW 204AH statement also indicates that because a new value could be written in those memory
when the final program is loaded into memory to be run. locations during program execution.
these memory locations will be loaded with I initialized
to) 204AH. Actually, since this is an Intel microproces-
sor, thefirst address in memory will contain the low T\pes of Numbers Used in Data Statements
byte of the word. 4AH. and the second memory address All of the previous examples of DB. DW. and DD declara-
will contain the high byte of the word. 20H. tions use
hexadecimal numbers as indicated by an "H"
The second data declaration example in Figure 3-10. after the number. You can. however, put in a number in
MULTIPLIER DW 3B2AH. sets aside storage for a word in any one of several other forms. For each form you must
memory and gives the starting address of this word tell the assembler which form vou are using.

hi CHAPTER THREE
bin \ka structions
the m CODE HERE section ol the 11
111 Figure 3 10, find the instruction MOV \\
Foi example, when you use a binary numbei In .1 state
VII I riPLK AND llns ins tion, when executed, will
ment, you put a B aftei the string oi 1'sandO's to let the
copy a word hum memory to the AX registei When the
assemble) know that you want the number to be treated
assemblei reads through this program the lust time, it
as a binary number. The statemenl 11 Ml' MAX DB
will automatically calculate the displacement ol -
01 1 1 1001 B is an example. II you want to put In a negative
the named data items from the segment base
binary number, write the number in its 2 s complement
DATA HERE. Referring to Figure 3 I I you can sec thai
si^ii and-magnitude form.
the displacemenl ol MULTIPLICAND from the segment
( X IAI base Is 0000. This is because MULTIPLICAND is the firsl
data Hem dec Tared in the segment. The assembler, then,
To Indicate that you want a number to be evaluated as
will find that the displacement ol MULTIPLICAND is
base 8 or octal, put a Q after the string oi octal dibits.
00001 1. When the assembler reads the program the sec
rhe statemenl OLD COMPUTER DW 7341 Q is an example.
ond lime to produce the binary codes tor the instruc
lions. 11 will insert Ibis displacement as part ol the bi
DECIMAL
nary code tor the instruction MOV AX, MUI Ill'l K AND.
ITie assemble! Heats a 111mil mi with no identifying lei Since we know that the displacement of MULTIPLK AM )
tei after it as a decimal number. In other words, if you is 0000. we could have written the instruction as MOV
forget to put an H alter a number that you want the AX, |0000|. However, there would be a problem if we latei
assembler to treat as hexadecimal, the assembler will changed the program by adding another data item be-
treat it as a decimal number. The assembler automati- fore MULTIPLICAND in DATA HERE. The displacemenl
cally converts a decimal number in a statement to bi- of MULTIPLICAND would be changed. Therefore, we
nary the
so value can be loaded into memory. The state- would have to remember to go through the entire pro-
ment TEMPERATURE MAX DB 49 is an example. If you gram and
correct the displacement in all instructions
indicate a negative number in a data declaration state- that access MULTIPLICAND. If you use a name to refer to
ment, the
assembler will convert the number to its 2's each data item as shown, the assembler will automati-
complement sign-and-magnitude form. For example, cally calculate the correct displacement of that data item
given the statement TEMP MIN DB -20. the assembler for you and insert this displacement each time you refer
will insert the value 11101 100. which is the 2's comple- to it in an instruction.
ment representation for -20 decimal. To summarize how this works, then, the instruction
NOTE You can put a D after decimal values if you want MOV AX, MULTIPLICAND is an example of direct ad-
to more clearly indicate that the value is decimal. dressing where
the direct address or displacement
within a segment is represented by a name. For instruc-
HEXADECIMAL tions such
as this, the assembler will automatically cal-
culatedisplacement
the of the named data item from the
As shown in several previous examples, a hexadecimal
start of the segment and insert this value as part of the
number is indicated by an H after the hexadecimal dig-
binary code for the instruction. When the instruction
its. The
statement MULTIPLIER DW 3B2AH is an example.
executes, the BIU will add the displacement contained
in the instruction to the data segment base in DS. (Re-
ASCII
member,
contents
the of DS are shifted 4 bit positions
ASCII characters can be put in data declaration state- left before the displacement is added.) This addition
mentsenclosing
by them in single quotation marks. produces the 20-bit physical address needed to address
The statement BOY 1 DB 'ALBERT, for example, tells the the data named MULTIPLICAND in memory.
assembler to set aside six memory locations named The next instruction in the program in Figure 3-10 is
BOY 1 . It also tells the assembler to put the ASCII code another example of direct addressing using a named
for A in the first memory location, the ASCII code for L in data item. The instruction MUL MULTIPLIER multiplies
the second, the ASCII code for B in the third, etc. The the word named MULTIPLIER in DATAJTERE times the
assembler will automatically determine the ASCII codes word in the AX register. The low word of the result is left
for the letters or numbers within the quotes. in the AX register, and the high word of the result is left

NOTE ASCII can only be used with the DB directive. in the DX register. When the assembler reads through
this program the first time, it will find the displacement
DECIMAL REAL AND HEXADECIMAL REAL of MULTIPLIER in DATA HERE is 0002H. When it reads
through the program the second time it inserts this dis-
These two types are used to represent noninteger num-
placement
part as of the binary code for the MUL in-
bers suchas 3.14159. We will discuss how these are
struction. When
the MUL MULTIPLIER instruction exe-
used in Chapter 11.
cutes, the
BIU will add the displacement contained in
the instruction to the data segment base in DS to ad-
Accessing Named Data with Program dress MULTIPLIER in memory.
Instructions The next instruction, MOV PRODUCT, AX. in the pro-
Now that we have shown you how the data structure is gramFigure
in 3-10 copies the low word of the result
set up, let's look at how program instructions access from AX to memory. The low bvte of AX will be copied to
this data. Temporarily skipping over the first two in- a memory location named PRODUCT. The high byte of

8(l8h FAMIIY ASSEMBLY LANGUAGE PROGRAMMING — INTRODUCTION 63


AX will be copied to the next higher address which we CS:CODE_HERE, DS:DATA_HERE tells the assembler that
can refer to as PRODUCT + 1. the logical segment CODE HERE contains the instruc-
The following instruction in the program, MOV tion statements for the program and should be treated
PRODUCT + 1, DX. copies the high word of the multipli- as a code segment. It also tells the assembler that it
cation result
from DX to memory. When the assembler should treat the logical segment DATA HERE as the
reads this instruction, it will add the indicated "2" to data segment for this program. In other words, the
the displacement it calculated for PRODUCT and insert DS:DATA HERE part of the statement tells the assembler
the result as part of the binary code for the instruction. that, for any instruction which refers to data in the data
Therefore, when the instruction executes, the low byte segment, that data will be found in the logical segment
of DX will be copied to memory at a displacement of DATA HERE. The ASSUME . . . DS:DATA HERE, for ex-
PRODUCT + 2. The high byte of DX will be copied to a ample, tells
the assembler that a named data item such
memory location which we can refer to as PRODUCT + as MULTIPLICAND is contained in the logical segment
3. Figure 3-1 1 shows how the two words of the product called DATA HERE. Given this information, the assem-
are put in memory. Note that the lower byte of a word is bler canconstruct the binary codes for the instruction.
always put in the lower memory address. The displacement of MULTIPLICAND from the start of
This example program should show you that if you are DATA HERE will be inserted as part of the instruction
using an assembler, names are a very convenient way of by the assembler.
specifying the direct address of data in memory. If you are using an assembler, you must use an
ASSUME statement in your program. Also, if you are
Naming Addresses — Labels using the stack segment and the extra segment in your
Names representing addresses are called labels. They program, you must include terms in the statement to
are written in the label field of an instruction statement tell the assembler the name of the logical segment to use
or a directive statement. One major use of labels is to for the stack and the name of the logical segment to use
represent the destination for jump and call instruc- for the extra segment. These additional terms might
tions. Suppose,
for example, we want the 8086 to jump look like: SS:STACK HERE, ES:EXTRA__HERE. As we will
back to some previous instruction over and over. In- show later, you can put another ASSUME directive later
stead
computing
of the numerical address that we want in the program to tell the assembler to use different logi-
to jump to. we put a label in front of the instruction we cal segments from that point on.
If the ASSUME directive is not completely clear to you
want to jump to and write the jump instruction as )MP
at this point, don't worry. We show many more examples
label. Here is a specific example.
of its use thoroughout the rest of the book. We intro-
NEXT: IN AL. 05H ; Get data sample form port 05H duced ASSUME
the directive here because you need to
put it in your programs for most 8086 assemblers. You
: Process data value read in.
can use the assume statement in Figure 3-10 as a model
of how to write this directive for your programs.

J MP NEXT ; Get next data value and process

Initializing Segment Registers


If you use a label to represent an address as shown in
The ASSUME directive tells the assembler the names of
this example, the assembler will automatically calculate
the logical segments to use as code segment, data seg-
the address that needs to be put in the code for the jump
ment, stack
segment, and extra segment. The assembler
instruction. The next two chapters show many exam-
uses displacements from the start of the specified logical
plesthe
of use of labels with jump and call instructions.
segment to code out instructions. When the instruc-
Another example of using a name to represent an ad-
tions are
executed, the displacements in the instruc-
dress
in isthe SEGMENT directive statement. The name
tions will
be added to segment registers to produce the
DATA HERE in the statement DATA HERE SEGMENT, for
actual physical addresses. The assembler, however, can-
example, represents the starting address of a segment
not directlyload the segment registers with the starting
named DATA HERE. Later we show you how we use this
physical addresses of the segments.
name to initialize the data segment register. We will now
The segment registers, other than the code segment
discuss some other parts of the example program that
register, must be initialized by program instructions
you will need to use in your programs.
before they are used to access data. The first two in-
structions
the example
of program in Figure 3-10 show
The ASSUME Directive
how this is done for the data segment register.
An 8086 program may have several logical segments DATA_HERE in the first instruction represents the
which contain code, several that contain data, and sev- upper 16 bits of the starting address you give the seg-
eral that
can serve as a stack. However, at any given time ment DATA HERE. Since the 8086 does not allow us to
the 8086 works directly with only four physical seg- move this immediate number directly into the data seg-
ments:
codea segment, a data segment, a stack .seg- ment register,
we must first load it into one of the gen-
ment, and
an extra segment. The ASSUME directive eral-purpose andregisters
then copy it into the data seg-
tells the assembler which logical segment to use for each ment register.MOV AX, DATATHERE loads the upper 16
of these physical segments at a given time. bits of the segment starting address into the AX regis-
In Figure 3-10, for example, the statement ASSUME ter. MOV DS, AX copies this value from AX to the data

64 ("HAI'UR IHKtl
segment reglstei rhis is the same operation we de
scribed for hand coding the example program In Figure
3 \. except that here we use the segment name instead
ol .1 number to refei to the segment base addi ess In this
example we used the AX registei to pass the value, but
an) 16 bit register othei than a segment register can be
used it you in hand coding youi programs, yi
just insert the uppei 16 bits ol the 20 bit segment stai t
Ing address in place ol DATA 1IERE in the instru< tion
For example, u in your pai t icular system you decide to
locate DATA HERE at address 00300H, DS should be
loaded with 0030H It you are using an assemble] . you
can use the segment name to refer to its base address as
shown in the example.
If you use the stack segment and the extra segment in
.i program, the stack segmenl register and the extra seg
ment register must also be initialized by program in-
structions
the same in way
\V1ifii the assembler reads through your assembly Ian
guage program, it calculates the displacement ol each
named variable from the start ol the logical segment
that contains it. The assembler also keeps track ol the FIGURE Mi Applied Microsystems is 1800 16-bit
displacement of each instruction code byte from the emulator. (Applied Microsystems ( orp.)
start of a logical segment. The CS:CODE HERE part of
the ASSUMED statement in Figure 3-10 tells the assem- ment tools to make your work easier These systems
blercalculate
to the displacements of the following in- usually contain several hundred Kbytes of RAM. a key-
structionsthe from start of the logical segment board video
and display, floppy and or hard disk drives,
CODE HERE. In other words, it tells the assembler a printer, and an emulator. Figure 3 12 shows an Ap-
that, when this program is run. the code segment regis- plied MicrosystemsES 1800 16-bit emulator which can
ter willcontain the upper 16-bits of the address where be added to an IBM PC/AT or compatible computer to
the logical segment CODE HERE was located in mem- produce a complete 8086/80186/80286 development
ory. Theinstruction byte displacements that the assem- system. The following sections give you an introduction
blerkeeping
is track of are the values that the 8086 will to several common program development tools which
put in the instruction pointer, IP. to fetch each instruc- you use with these systems. Most of these tools are pro-
tion byte. grams which
you run to perform some function on the
There are several ways that the CS register can be program you are writing. You will have to consult the
loaded with the code segment base address and the in- manuals foi your system to get the specific details for it.
struction pointer
can be loaded with the displacement of but this section should give you an overview of the steps
the instruction byte to be fetched next. The first way is involved in developing an assembly language microcom-
with the command you give your system to execute a puter programusing a system. An accompanying lab
program starting at a given address. A typical command manual steps you through the use of all these tools with
ol this sort is G = 0010:0000 <CR > . (<CR > means the SDK-86 board and the IBM Personal Computer.
"press the return key.") This command will load CS with
0010 and load IP with 0000. The 8086 will then fetch
Editor
and execute instructions starting from address 00100, An editor is a program which, when run on a system,
the address produced when the BIU shifts CS and adds lets you type in the assembly language statements for
IP. The other ways of loading CS and IP will be discussed your program. Examples of editors are ALTER which
in later sections. runs on Intel systems. EDLIN which runs on IBM PCs.
and Wordstar which runs on most systems. The main
The END Directive function of an editor is to help you construct your as-
sembly language
program in just the right format so
The END directive, as the name implies, tells the assem-
that the assembler will translate it correctly to machine
bler stop
to reading. Any instructions or statements
language. Figure 3-10 shows an example of the format
that you write after an END directive will be ignored
you should use when typing in your program. This form
of your program is called t he source program. The actual
ASSEMBLY LANGUAGE PROGRAM position of each field on a line is not important, but you
DEVELOPMENT TOOLS must put the fields of each statement in the correct
order, and you must leave at least one blank between
Introduction fields. Whenever possible, we like to line the fields up in
For all but the very simplest assembly language pro- columns so that it is easier to read the program.
gramswill
youprobably want to use some type of micro- As you type in your program, the editor stores the
computer development
system and program develop ASCII codes for the letters and numbers in successive

»()8b FAMILY ASSEMBLY LANGUAGE PR< x .KAMMING — INTRODUCTION 65


RAM locations. If you make a typing error the editor will The trailer section of the listing in Figure 3-13 gives
let you back up and correct it. If you leave out a program some additional information about the segments and
statement, the editor will let you move everything down names used in the program. The statement CODE HERE
and insert the line. This is much easier than working 0014 PARA NONE, for example, tells you that the segment
with pencil and paper, even if you type as slowly as I do. CODE_HERE is 14H bytes long and will be located at a
When you have typed in all of your program, you then physical address whose lower 4 bits are 0000. The state-
copy it from memory to a file on a floppy or hard mag- ment MULTIPLIER. . . . L WORD 0002 DATA HERE tells
netic disk.
This file, such as the one in Figure 3-10. is you that MULTIPLIER is a variable of type word and that
called a source file. If you later find that your program it is located at an offset of 0002 in the segment
contains errors, you can use the editor to load the DATA HERE.
source file back into RAM and make the needed correc-
tionsthe
in source program. Linker
A linker is a program used to join together several object
Assembler files into one large object file. When writing large pro-
An assembler program is used to translate assembly grams
is usually
it much more efficient to divide the
language mnemonics to the correct binary code for each large program into smaller modules. Each module can
instruction. The assembler will read the source file of be individually written, tested, and debugged. When all
your program from the disk where you saved it after ed- of the modules work they can be linked together to form
iting.assembler
An usually reads your source file more a large functioning program. Also, the object modules
than once. On the first pass through the source pro- for useful programs, a square root program, for exam-
gram,assembler
the finds everything. It determines the ple, can
be kept in a library file and linked into other
displacement of named data items and the offset of la- programs as needed.
bels, and
puts this information in a symbol table. On a The linker produces a link file which contains the
second pass through the source program, the assembler binary codes for all the combined modules. The linker
produces the binary code for each instruction and as- also produces a link map file which contains the ad-
signs addressesto each. dress information about the linked files. The linker,
The assembler generates two files on the floppy or however, does not assign absolute addresses to the pro-
hard disk. The first file is called the object file. The ob- gram,
only
it assigns relative addresses starting from
ject file
contains the binary codes for the instructions zero. This form of the program is said to be relocatable.
and information about the addresses of the instruc- because it can be put anywhere in memory to be run. If
tions. This
file contains the information that will even- you are going to run your program on a system such as
tuallyloaded
be into memory and executed. The second the IBM PC, you can just load the link file into memory
file generated by the assembler is called the assembler and run it. If you are going to run your program on a
list file. Figure 3-13 shows the assembler list file for the system such as the Intel Series IV. then you must use a
source program in Figure 3-10. This file contains the locator program to assign absolute addresses to the
assembly language statements, the binary codes for linker file.
each instruction, and the offset for each instruction.
You usually send this file to a printer so that you will Locator
have a printout of the entire program to work with when A locator is a program used to assign the specific ad-
you are testing and troubleshooting the program. The dresses
where
of the object code is to be loaded into
assembler listing will also indicate any typing or syntax memory. A locator program that comes with the IBM PC
(assembly language grammar) errors you made in typing Disk Operating System (DOS) is called EXE2BIN. Here's
in your source program. how you proceed if you want to produce a program with
absolute addresses that you can download to an SDK-86
NOTE The assembler will not tell you if you made a pro-
from an IBM PC. First build a source (.ASM| file using
grammingYou
error. usually have to run the program to
the EDLIN or perhaps the WORDSTAR editor. Assemble
find these. To correct the errors indicated on the listing,
the source file with the IBM PC Macroassembler (MASM)
you use the editor to reedit your source program and
to produce the .OBJ file. Use the LINK program to pro-
save the corrected source program on disk. You then
duce
relocatable
a .EXE file. Then use the EXE2BIN pro-
reassemble the corrected source program. It may take
gram
give
to your program an absolute starting address
several times through the edit-assemble loop before you
such as 0010:0000H. Finally, use the SDKDMP program
get all of the syntax errors out of your source program.
from Chapter 13 to download the .BIN file produced by
Now let's take a look at some of the information given
EXE2BIN and run it. In some systems a single program
on the assembler listing. The left-most column in the
performs both the link and the locate functions.
listing gives the offsets ol data items from the start of
the data segment and the offsets of code bytes from the
start of the code segment. Note that the assembler does Debugger
nol generate absolute physical addresses. A linker or If your program requires no external hardware or re-
lo( ator will do this later. Also note that the MOV AX, quires only
hardware accessible directly from your sys-
DATA HFRE statement is assembled with some blanks tem, then
you can use a debugger to run and debug
alter the basic instruction code because the start of DS your program. A debugger is a program which allows
is nol known at the time the program is assembled. you to load your object code program into system mem-

66 CHAPTER THREE
The IBM Personal Computer MACROAssembler 03-06-85 PA6E 1-1
PAGE ,132 ; Makes listing file lines 13? characters wide
;8086 program
".ABSTRACT : This program multiplies the two 16-bit words in
; the memory locations called MULTIPLICAND and
! MULTIPLIER. The result is stored in the memory
; location called PRODUCT
i PORTS USED : None
! PROCEDURES USED: None
REGISTERS USED : CS. DS, DX and AX

0000 DATAHERE SEGMENT

0000 2040 MULTIPLICAND DW 204AH first word here


0002 3B2A MULTIPLIER DW 3B2AH second word here
M04 02 l PRODUCT DW 2 DUP!0) result here
0000
ji

0008 DATA.HERE ENDS

0000 CODE.HERE SEGMENT


ASSUME
CS : CODE.HERE.DS : DATA.HERE

0000 B8 — - R MOVAX, DATA.HERE initialize DS register


0003 3E D8 MOVDS.AX

0005 Al 0009 R MOVAX, MULTIPLICAND get one word


0003 F7 26 0002 R MUL MULTIPLIER multiply by second word
000C A3 0004 R MOVPRODUCT, AX store low word of result
000F 89 16 0006 R MOVPRODUCT+2, DX store high word of result
0013 CC INT 3 wait for command from user

3014 CODE.HERE ENDS


END

The IBMPersonal Computer MACRO


Assembler 03-06-35 PAGE Symbols-1

Segments and groups:

Name Size al ion combine class

CODE.HERE. 0014 PARA NONE

DATAHERE. 1008 PARA NONE

Symbols:
Name Type Value Attr

MULTIPLICAND L WORD0000 DATA.HERE


MULTIPLIER . L WORD0002 DATA.HERE
PRODUCT. . . L WORD0004 DATAHERE Length =0002

Warning Severe
Errors Errors
0 0
FIGURE 3-13 Assembler listing lor example program in Figure 5-10

8086 FAMILY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION 67


ory. execute (he program, and troubleshoot or "debug"
it. The debugger allows you to look at the contents of
registers and memory locations after your program
runs. It allows you to change the contents of registers
and memory locations and rerun the program. Some
debuggers allow you stop execution after each instruc-
tionyou
so can check or alter memory and register con-
tents.
debugger
A also allows you to set a breakpoint at
any point in your program. When you run the program
the system will execute instructions up to this break-
point and stop. You can then examine register and
memory contents to see if the results are correct at that
point. If the results are correct, you can move the break-
point
a tolater point in the program. If the results are
not correct, you can check the program up to that point
to find out why they are not correct. The debugger tools
can help you isolate a problem in your program. Once
you find the problem, you can then cycle back and cor-
rect the
algorithm if necessary. You then use the editor
to correct your source program, reassemble the cor-
rected source program, relink, and run the program
again.
Microprocessor prototyping boards such as the SDK-
86 contain a debugger program in ROM. On boards
such as this the debugger is commonly called a monitor
program because it lets you monitor program activity.
The SDK-86 monitor program, for example, lets you
enter and run programs, single step through programs,
examine register and memory contents, and insert
breakpoints. The DEBUG program, used with the IBM
PC, allows you to do the same functions and also has a
trace function which shows you the contents of all the
registers after each instruction executes.

Emulator
Another way to run your program is with an emulator.
An emulator is a mixture of hardware and software. It is
usually used to test and debug the hardware and soft-
wareanof external system such as the prototype of a
microprocessor-based instrument. Part of the hardware
of an emulator is a multiwire cable which connects the
host system to the system being developed. A plug at the
end of the cable is plugged into the prototype in place of
its microprocessor. Through this connection the soft-
waretheof emulator allows you to download your object-
code program into RAM in the system being tested and
run it. As with a debugger, an emulator allows you to
load and run programs, examine and change the con-
tentsregisters,
of examine and change the contents of
memory locations, and insert breakpoints in the pro-
gram. emulator
The also takes a "snapshot" of the con-
1 registers, activity on the address and data bus.
and the state of the flags as each instruction executes. The
emulator stores this trace data, as it is called, in a large
RAM. You can do a printout of the trace data to see the re-
sults that
your program produced on a step by-step basis.
Another powerful feature of an emulator is the ability
to use either system memory or the memory on the pro-
totype lor the program you are debugging. In a later C STOP J
chapter we diseuss in detail the use ol an emulator in
developing a microprocessor-based producl FIGURE 3-14 Program development algorithm.

Mi < IIAI'ItR THKtF


Summary of the Use of Program Development flowcharts and flowcharl symbols
Tools Structured programming
Figure 3 I I shows In diagram form the order in which
1'seudocode
you will use the program development tools we have de
scribed. The first and most importanl step is to think lop down .ind hot torn up design
out very carefully what you want the program to do and
how you want the program to do it. Next, use an edltoi Sequence, repetition, and decision operations
in create the source lilt- for your program. Assemble the IF— THEN— ELSE. IF rHEN. WHILE DO,
source file with the assembler. II the assemble! lisl file REPEAT -UNTIL, and CASE structures
indicates any (inns m your program, use the editoi to
correct these errors. Cycle through the edil assemble 81 186 nisi i in t ion types

loop until the assembler uils you on the listing thai it Mnemonics
found nn errors, li your program consists oi several
modules, then use i he linker to join their object modules Initializal ion list

together Into one large object module.


standard program format
NOT! On some systems such as the IBM PC you must
Documentation
use the linker even if your program has only one mod-
ule. Instruction template: W-bit, MOD. R/M. D-bit
Now. if your system requires it. use the locate pro-
Segment-override prefix
gramspecify
to where in memory you want your pro-
grambetoput. Your program is now ready to be loaded Assembler
into memory and run. If your program does not interact
Assembler directives: SEGMENT, ENDS. END. DB.
with any external hardware other than that connected
DW. DD. EQU. ASSUME
directly to the system, then you can use the system
debugger to run and debus; your program. If your pro- Named data items
gramintended
is to work with external hardware such
as the prototype of a microprocessor-based instrument, Development tools
then you will probably use an emulator to run and Editor
debug your program. We will be discussing and showing
Linker: library file, link files, link map, relocatable
the use of these program development tools throughout
the rest of this book, but this section should give you an Locator
overview.
Debugger, monitor program
Emulator, trace data
CHECKLIST OF IMPORTANT TERMS AND
CONCEPTS IN THIS CHAPTER

If you do not remember any of the terms or concepts in


the following list, use the index to find them in the
chapter.

Algorithm

Sequential task list

REVIEW QUESTIONS AND PROBLEMS


1. List the major steps in developing an assembly lan- 5. A program is like a recipe. Use a flowchart or
guage program. pseudocode to show the algorithm for the following
recipe. The operations in it are sequence and rep-
2. What is the main advantage of a top-down design etition. Instead
of implementing the resulting
approach to solving a programming problem? algorithm in assembly language, implement it in
3. Why is it necessary to develop a detailed algorithm your microwave and use the result to help you get
lor a program before writing down any assembly through the rest of the book.
language instructions? Peanut Brittle:
4. a. What are the three basic structure types used
1 cup sugar 1 teaspoon butter
0.5 cup white corn syrup 1 teaspoon vanilla
when writing programs?
1 cup unsalted peanuts 1 teaspoon baking soda
b. What is the advantage of using only these
structures when writing the algorithm lor a i. Put sugar and syrup in 1.5 quart casserole
program? (with handle) and stir until thoroughly mixed.

8118b FAMItY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION i,<)


ii. Microwave at HIGH setting for 4 minutes. ES 6000 DATA SEGMENT
C5 4000 5000CH D7
iii. Add peanuts and stir until thoroughly mixed.
SS 7000 5000BH 9 A
iv. Microwave at HIGH setting for 4 minutes. Add
DS 5000 5000AH 7C
butter and vanilla, stir until well mixed and
IP 43E8 50009H DB
microwave at HIGH setting for 2 more min-
50008H C3
utes.
AH AL 50007H B2
v. Add baking soda and gently stir until light and
AX ^2 35 50006H 49
foamy. Pour mixture onto nonstick cookie
50005H 21
sheet and let cool for 1 hour. When cool, break
BH BL 50004H B9
into pieces. Makes 1 pound.
BX 07 5A 50003H 71
6. Use a flowchart or pseudocode to show the algo-
50002H 22
rithmaforprogram which gets a number from a
GH CL 50001H 4A
memory location, subtracts 20H from it, and out-
puts 01H
to port 3AH if the result of the subtrac- CX 00 04 50000H 3B

tiongreater
is than 25H.
DH DL
7. Given the register contents in Figure 3-15. answer
DX 33 02
the following questions:
a. What physical address will the next instruction
be fetched from?
b. What is the physical address for the top of the
stack?
SP 0000
8. Describe the operation and results of each of the
BP 2468
following instructions, given the register contents
SI 4C00
shown in Figure 3-15. Include in your answer the
DI 7D00
physical address or register that each instruction
will get its operands from and the physical address FIGURE 3-15 8086 register and memory contents tor
or register that each instruction will put the result. Problems 7, 8, and 10.
Use the instruction descriptions in Chapter 6 to
help you. Assume that the instructions below are
independent, not sequential unless listed together
under a letter. Write the 8086 instruction which will perform the
a. MOV AX, BX k. OR CL. BL
indicated operation. Use the instruction overview
b. MOV CL, 37H L NOT AH
in this chapter and the detailed descriptions in
c. INC BX m. ROL BX, 1
Chapter 6 to help you.
d. MOV CX, [246BH] n. AND AL. CH
MOV DS. AX
a. Copies AL to BL
e. MOV CX. 246BH a
b. Loads 43H into CL
/. ADD AL, DH P- ROR BX. CL
c. Increments the contents of CX by one
9- MUL BX <l AND AL. OFH
d. Copies SP to BP
h. DEC BP r. MOV AX, [BX]
e. Adds 07H to DL
i. DIV BL S. MOVIBX1ISI1. CL
f. Multiplies AL times BL
j- SUB AX. DX
g. Copies AX to a memory location at offset
See if you can spot the grammatical (SYNTAX) er- 245AH in the data segment
rorsthe
in following instructions (use Chapter 6 to h. Decrements SP by one
help you): i. Rotates the most significant bit of AL into the
a. MOV BH. AX d. MOV 7632H, CX least-significant bit position
b. MOV DX, CL e. IN BL, 04H j. Copies DL to a memory location whose offset is
c. ADD AL, 2073H in BX
k. Masks the lower 4 bits of BL
1(1. Show the results that will be in the affected regis- /. Sets the most significant bit of AX to a one but
ters memory
or locations after each of the following
does not affect the other bits
groups of instructions execute. Assume that each m. Inverts the lower 4 bits of BL but does not af-
group of instructions starts with the register and
fect theother bits.
memory contents shown in Figure 3-15. (Use
Chapter 6.) 2. Construct the binary code for each of the following
a. ADD BL. AL SUB AL, CL 8086
808R instructions.
instructions.
MOV [0004], BL INC BX a. MOV BL. AL J- ROR AX. 1
b. MOV CL. 04 MOV [BX], AL b. MOV [BX], CX 9- OUT DX. AL
ROR DI. CL d ADD AL. BH c. ADD BX. 59H[DI] h. AND AL. OFH
c. MOV BX, 000AH DAA d. SUB [2048], DH i. NOP

MOV AL, [BX] e. XCHG CH. ES:[BX] j- IN AL, DX

70 CHAPTER THREE
13. Describe the function of each assembler directive 1?. Write the pseudocode representation for tli<- flow
and Instruction statement in the shorl program chart In Figure 3-14,
shown below these review problems.

14. Describe how an assembly language program is


developed and debugged using system tools such
as editors, assemblers, linkers, locators, emula-
tors, and
debuggers.

i pressure read p r o 3 r a m
DATA.HERE SEGMENT
PRESSURE DB 0 istorase for pressure
DATA_HERE ENDS
PRESSURE-PORT EOU 04H ipressure sensor connected
; t o port 0 4 H
CDRRECTION_FACTDR EOU 07H icurrent correction factor. 07
C0DE_HERE SEGMENT
ASSUME CS:CODE_HERE i DS:DATA_HERE
MOO AX, DATA_HERE
MOO DS , AK
IN AL , PRESSURE_PORT
ADD AL . CORRECTION-FACTOR
MOO PRESSURE , AL
C0DE_HERE ENDS
END

808b FAMILYASSEMBLYLANGUAGE PROGRAMMING— INTRODUCTION 71


CHAPTER

8086 Assembly Language


Programming Techniques —
Parti
The purposes of this chapter are to show you how some Add maximum temperature and minimum
of the standard program structures described in the last temperature.
chapter are implemented in 8086 assembly language,
Divide sum by two to get average temperature.
how these structures are used to solve some common
programming problems, and how some of the 8086 in-
This sequence doesn't look much like an assembly lan-
structions work.
guage programand it shouldn't. The algorithm at this
point should be general enough that it could be imple-
mented
any inprogramming language, or on any ma-
OBJECTIVES chine. Once
you are reasonably sure of your algorithm,
then you can start thinking about the architecture and
At the conclusion of this chapter you should be able to: instructions of the specific microcomputer on which
you plan to run the program. Now let's show you how we
1. Write flowcharts or pseudocode for simple program- get from the algorithm to the assembly language pro-
ming problems. gramit.for

2. Implement WHILE— DO and REPEAT— UNTIL pro-


gram structuresin 8086 assembly language. SETTING UP THE DATA STRUCTURE

3. Describe the operation of selected data transfer, One of the first things for you to think about in this
arithmetic, logical, jump. loop, and string instruc- process is the data that the program will be working
tions. with. You need to ask yourself questions such as:

4. Use based and indexed addressing modes to access


1. Will the data be in memory or in registers?
data in your programs.
2. Is the data of type byte, type word, or perhaps type
5. Describe a systematic approach to debugging a sim- doubleword0
ple assembly language program using debugger.
monitor, or emulator tools. 3. How many data items are there?

4. Does the data represent only positive numbers, or


does it represent positive and negative Isigned!
numbers0
MORE PRACTICE WITH SIMPLE
SEQUENCE PROGRAMS 5. For more complex problems you might ask how the
data is structured. For example, is the data in an
Finding the Average of Two Numbers array or in a record?

DEFINING THE PROBLEM AND WRITING THE


Let's assume for this example that the data is all in
ALGORITHM
memory, the data is of type byte, and that the data rep-
A common need in programming is to find the average resents positive
only numbers in the range 0 to OFFH.
of two numbers. Suppose, for example, we know the The top part of Figure 4-1. between the DATA^HERE SEG-
maximum temperature of a day and the minimum tem- MENTtheand DATA HERE ENDS directives, shows how
perature
a day.of and we want to determine the average you might set up the data structure for this program. It
temperature. The sequence of step1- we go through to do is very similar to the data structure for the multiply ex-
this might look something like the following. ample
thein last chapter. In the logical segment called

72
: |i . PROGRAM
;ABSTF 11r o g r a n two
I MP and 1. 1
result ill the memory 1o H
REGISTERS ! ...
;PORTS USED : used
;PROCEDUF i

DATA_HERE SEGMENT

HI_TEMP r>H 92H temp storage


CO_TEMP DB 52H low temp storage
%v,.' fEMP ! 1B ?
put average here

DATA_HERE END S

CODE_HERE SEGMENT
ASSUME CS : CI
CODE HERE, DS DATA HERE

MOV AX , DATA_HERE initialize data i eg men t


MOV DS, AX
MOV AL, HI _TEMP get first temperature
ADD AC , CO TEMP add second to it
MOV AH, OOH clear all of AH register
ADC AH, OOH put carry in CSB of AH
MOV BC, 02H load divisor in BC register
DIV BC divide AX by BC
guo t i ent i n AC ,
remainder in AH
MOV AV TEMP, AC copy result to memory

CODE HERE ENDS


END

FIGURE 4-1 8086 program to average two temperatures.

DATAHERE. HI TEMP is declared as a variable of type to be initialized, but the presence of the list will remind
byte and initialized with a value of 92H. In an actual you that it has to be done. For this example program the
application, the value in HI TEMP would probably be only part you have to initialize is the data segment regis-
put there by another program which reads the output ter.
from a temperature sensor. The statement LO TEMP DB
52H declares a variable of type byte and initializes it with CHOOSING INSTRUCTIONS
the value 52H. The statement AV TEMP DB ? sets aside a
Next look at the major actions that you want the pro-
byte location to store the average temperature, but does
gram
perform
to other than moving data from one place
not initialize the location to any value. When the pro-
to another. You want the program to add two byte-type
gram executes, it will write a value to this location.
numbers together, so scan through the instruction
groups in Chapter 3 to determine which 8086 instruc-
INITIALIZATION CHECKLIST
tion will
do this for you. The ADD instruction is the ob-
Now that you have the data structure set up. let's start vious choice
in this case. Now find and read the detailed
thinking about the instructions that we can use to per- discussion of this instruction in Chapter 6. From this
form actions
the we want on this data. Although it does discussion you can determine how the instruction
not show in the algorithm, we know from a discussion works and see if it will do the necessary job. From the
in Chapter 3 that we should start the program with a list discussion of the ADD instruction you should find that
of initialization instructions. Start by putting this the ADD instruction has the format ADD destination,
checklist at the top of the paper. At this point you may source. A byte from the specified source is added to a
not know exactly which parts on the checklist will have byte in the specified destination, or a word from the

8086 \SSEMRLY LANGUAGE PROGRAMMING Tt( UNIQUES— PART 1 73


specified source is added to a word in the specified des- unsigned binary numbers, look up the DIV instruction
tination. (Note
that you cannot directly add a byte to a in Chapter 6 to find out how it works. The DIV instruc-
word.) The result in either case is put in the specified tion can
be used to divide a 16-bit number in AX by a
destination. The source can be an immediate number, a specified byte in a register or in a memory location. After
register, or a memory location. The destination can be a the division an 8-bit quotient is left in the AL register
register or a memory location. The source and the desti- and an 8-bit remainder is left in the AH register. The
nation cannot
both be memory locations in an instruc- DIV instruction can also be used to divide a 32-bit num-
tion. This
means that you have to move one of the oper- ber in
the DX and AX registers by a 16-bit number from
ands from
memory to a register before you can do the a specified register or memory location. In this case a
ADD. Another point to consider here is that if you add 16-bit quotient is left in the AX register, and a 16-bit
two 8-bit numbers, the sum can be larger than 8 bits. remainder is left in the DX register. In either case there
Adding FOH and 40H. for example, gives 130H. The 8-bit is a problem if the quotient is too large to fit in the indi-
destination will contain 30H, and the carry will be held cated destination. In a later chapter we discuss what to
in the carry Hag. What this means is that you must col- do about this problem. Fortunately, for the example
lect theparts of the result in a location large enough to here the data is such that the problem will not arise.
hold all 9 bits. A 16-bit register is a good choice. To sum- As you can see. we already have the sum of the two
marize then,
you need to move one of the numbers you temperatures already positioned in the AX register,
want to add into a register such as AL. add the other ready for the DIV operation. Before we can do the DIV
number from memory to it. and move any carry pro- operation, however, we have to get the divisor. 02H. into
ducedthe
by addition to the upper half of the 16-bit a register or memory location to satisfy the require-
register containing the result (which is in ALL ments
theof DIV instruction. A simple way to do this is
Now let's see how you can do this with program in- with the MOV BL, 02H instruction, which loads the
structions.
a look
Take now at the first six instruction immediate number 02H into the BL register. Now we
statements of the example program in Figure 4-1. As can do the divide operation with the instruction DIV BL.
explained in the last chapter, the first two instructions. The 8-bit quotient from the division will be left in the AL
MOV AX, DATA HERE and MOV DS, AX, are required to register. All we have left to do is to copy the quotient to
initialize the data segment register. These instructions the memory location we set aside for the average tem-
load the I)S register with the upper 16 bits of the start- perature.
instruction
The MOV AV TEMP, AL will copy
ing address for the data segment. If you are using an AL to this memory location. Take another look at Figure
assembler, you can use the name DATA_HERE in the 4-1 to see how these instructions are added on to the
instruction to refer to tins address. If you are not using previous instructions.
an assembler, then just put the hex for the upper 16 bits
NOTE: We could have used the remainder in AH to
of the address in the MOV AX, DATA HERE instruction
round off the average temperature, but that would have
in place of the name.
made the program more complex than desired for this
The next instruction in the example program in Fig-
example.
ure 4-1.MOV Af, HI TEMP, copies one of the tempera-
tures from
a memory location to the AL register. The
name HLTEMP in the instruction represents the direct SUMMARY OF CONVERTING AN ALGORITHM
address or displacement of the variable in the logical TO ASSEMBLY LANGUAGE
segment DATA HERE. The ADD Af, fO TEMP instruc-
A first step in converting an algorithm to assembly lan-
tion addsa byte from memory to the contents of the AL
guage
to set
is up and declare the data structure that the
register. The result of the addition (suml is left in the AL
algorithm will be working with. Then write down the
register
instructions required for initialization at the start of the
Now that we have done the addition, the next thing to
code section. Next determine the instructions required
do is get the carry bit where we want it. We would like to
to implement the major actions in the algorithm, and
get the contents of the earn' flag into the least signifi-
decide how the data must be positioned for these in-
cant bit
of the AH register. The MOV AH, 00H instruc-
structions. Finally,
insert the MOV or other instruc-
tion clearsall of the bits of AH to O's. The ADC AH, 00H
tions requiredto get the data in the correct position.
instruction adds the immediate number 00H plus the
contents of the carry flag to the contents of the AH regis-
ter. Theresult will be left in the AH register. Since we
i li ued AH to all O's before the add, what we are really A Few Comments about the 8086 Arithmetic
adding is 00H + 00H + CF. The result of all this is that Instructions
the carry bit ends up in the least-significant bit of AH. The 8086 has instructions to add. subtract, multiply,
which is what we set out to do. and divide. It can operate on signed or unsigned binary
The next major action in our algorithm is to divide the numbers. BCD numbers, or numbers represented in
sum of the two temperatures by two. Look at the in- ASCII. Rather than put a lot of arithmetic examples at
struction groups
in the last chapter to see if the 8086 this point in the book, we show arithmetic examples
has a divide instruction. You should find that it lias two with each arithmetic instruction description in Chapter
divide instructions. DIV and IDIV. DIV is for dividing 6. The description of the MUL instruction in Chapter 6.
unsigned numbers, and IDIV is used tor dividing signed for example, shows how unsigned binary numbers are
binary numbers Since m this example we are dividing multiplied. Also we show other arithmetic examples as

74 ( IIAPltK FOUR
needed throughout the rest of the book. If you need to do pa< ked form is obviously more effii ienl because n has
some .11 Ithmetic operations on the 8086 there are a few two Bt D digits in each byte memory location. I be 1nob
Instructions in addition to the basic add. subtract, mul- leiu we are going to work on here is how to converl two
tiply, .mil
divide Instructions that you need to look up in numbers from ASCII code form to unpacked BCD and
Chapter (>. then pack the two BCD digits into one byte. Figure 4 2
II you are adding BCD numbers, you need to also look shows the steps in numerical form.
up the Decimal Adjust for Addition (DAA) instruction. II fhe algorithm foi tins problem can be stated simply
you are subtracting BCD numbers, then you need to
look up the Decimal Adjust for Subtraction (DAS) in-
struction.
you are II working with ASCII numbers, then Convert lirsl ASCII number to unpacked BCD.
you need to look up the ASCII Adjusl after Addition
Convert second ASCII numbei to unpacked I '% <
D
(AAA) Instruction, the ASCII Adjust after Subtraction
l\\s| instruction, the ASCII Adjust after Multiply (AAM) Move first BCD nibble to upper nibble position 111
instruction, and the ASCII Adjust before Division (AAD) byte.
instruction.
Pack two BCD nibbles in one byte

Now let's see how you can implement this algorithm in


8086 assembly language.
Converting Two ASCII Number Codes to Packed
BCD
THE DATA STRUCTURE AND INITIALIZATION
LIST
DEFINING THE PROBLEM AND WRITING THE For this example program let's assume that the first
ALGORITHM ASCII code entered is in the BL register, and the second
II you tvpe a 9 on an ASCII-encoded computer terminal ASCII code entered is in the AL register. Since we arc not
keyboard, the 8-bit ASCII code sent to the computer will using memory for data in this program, we do not need
be 001 1 1001 binary, or 39H. If you type a 5 on the key- to declare a data segment. Also then we do not need to
board,code
the sent to the computer will be 001 10101 initialize the data segment register. In a real application
binary or 35H. the ASCII code for 5. The ASCII codes for this program would probably be a procedure or a part of
the numbers 0 through 9 are 30H through 39H. As you a larger program.
can see, the lower nibble of the ASCII codes contains the
4-bit BCD code for the number represented by the ASCII
code. For many applications we want to convert the
MASKING WITH THE AND INSTRUCTION
ASCII code coming in from the terminal to its simple
BCD equivalent. We can do this by simply replacing the The first operation in the algorithm is to convert a num-
3 in the upper nibble of the byte with four O's. For exam- ber in
ASCII form to its unpacked BCD equivalent. This
ple, suppose we read in 00111001 binary or 39H. the is done by replacing the upper 4 bits of the ASCII byte
ASCII code for 9. If we replace the upper 4 bits with 0's. with four O's. The 8086 AND instruction can be used to
we are left with 00001001 binary or 09H. The lower 4 do this operation. Remember from basic logic or from
bits contain 1001 binary, the BCD code for 9. Numbers the review in Chapter 1 that, when a 1 or a 0 is ANDed
represented as one BCD digit per byte are referred to as with a 0. the result is always a zero. ANDing a bit with a
unpacked BCD. If two BCD digits are put in a byte, this 0 is called masking that bit. because the previous state
form is referred to as packed BCD. Figure 4-2 shows of the bit is hidden or masked. To mask 4 bits in a word,
examples of ASCII, unpacked BCD, and packed BCD. then, all you do is AND each bit you want to mask with a
When we want to store BCD numbers in memory the 0. A bit ANDed with a 1, remember, is not changed.

ASCI I OOll 0101 = 35H


ASCI I 0011 1001 = 39H

UNPACKED BCD 0000 0101 = 05H


UNPACKED BCD 0000 1001 = 09H

UNPACKED BCD 0101 0000 = 50H


moved to upper nibble
PACKED BCD 59 0101 1001 = 59H

FIGURE 4-2 ASCII, UNPACKED BCD, and PACKED BCD examples.

808b ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES— PART 1 7.',


ASCII 5 0 0 11 0 10 1 The bit that was the MSB is rotated around into the LSB
MASK 0 0 0 0 1111 position. The old MSB is also copied to the carry flag.
RESULT 0 0 0 0 0 10 1 For the RCL instruction each bit of the specified register
or memory location is also rotated one bit position to the
FIGURE 4-3 Effects of ANDing with I's and O's. left. However, the bit that was in the MSB position is
moved to the carry flag, and the bit that was in the carry
flag is moved into the LSB position. As indicated by the
According to the description of the AND instruction in C in the middle of the mnemonic, the carry flag is in the
Chaptei 6, the instruction has the format AND destina-
rotated loop when the RCL instruction executes.
tion, source.The instruction ANDs each bit of the speci- In the example program we really don't want the con-
fied sourcewith the corresponding bit of the specified tentsthe
of earn- Hag rotated into our operand, so the
destination and puts the result in the specified destina- ROL instruction seems to be the one we want. If you
tion. The
source can be an immediate number, a regis- consult the ROL instruction description in Chapter 6.
ter, or
a memory location specified in one of those 24 you will find that the instruction has the format ROL
different ways. The destination can be a register or a destination, count. The destination can be a register or a
memory location. The source and the destination must memory location. It can be a byte location or a word loca-
both be bytes, or they must both be words. The source tion. The
count can be the immediate number 1 speci-
and the destination cannot both be memory locations in fied directly in the instruction, or the count can be a
an instruction. number previously loaded into the CL register. The in-
For this example the first ASCII number is in the BL structionAL,
ROL1 for example will rotate the contents
register, so we can just AND an immediate number with of AL one bit position to the left. We could repeat this
this register to mask the desired bits. The upper 4 bits instruction four times to produce the shift of four bit
of the immediate number should be O's because these positions we need for our BCD packing problem. How-
correspond to the bits we want to mask in BL. The lower ever, there
is an easier way to do it. We first load the CL
4 bits of the immediate number should be Is because
register with the number of times we want to rotate AL.
we want to leave these bits unchanged. The immediate The instruction MOV CL, 04H will do this. Then we use
number then should be 00001 1 1 1 binary or OFH. The the instruction ROL BL, CL to do the rotation. When it
instruction to convert the first ASCII number is AND BL,
executes, this instruction will automatically rotate BL
OFH. When this instruction executes, it will leave the the number of bit positions loaded into CL. Note that for
desired unpacked BCD in BL. Figure 4-3 shows how this the 80186 you can write the single instruction ROL BL,
will work for an ASCII number of 35H initially in BL. 04H to do this job.
For the next action in the algorithm we want to per- Now that we have determined the instructions needed
form the
same operation on a second ASCII number in to mask the upper nibbles and the instructions neces-
the AL register. The instruction AND AL, OFH will do this sary move
to the first BCD digit into position, the only
for us. Alter this instruction executes AL will contain thing left is to pack the upper nibble in BL and the lower
i he unpacked BCD for the second ASCII number.
nibble in AL into the same byte.

MOVING A NIBBLE WITH THE ROTATE


COMBINING BYTES OR WORDS WITH THE
INSTRUCTION ADD OR THE OR INSTRUCTION
The next action in the algorithm is to move the 4 BCD
Vim can't use a standard MOV instruction to combine
hits in the first unpacked BCD byte to the upper nibble two bytes into one as we need to do here. The reason is
position in the byte. We need to do this so that the 4 that the MOV instruction copies an operand from a
BCD bits an- m the correct position lor pat king with the specified source to a specified destination. The previous
second BCD nibble. Take another look at Figure 4-2 to
help you visualize tins. What we arc effectively doing
here is swapping or exchanging the top nibble with the
bottom nibble of the byte. It you check the instruction i 1! 11 11 11 11 11 11 1
groups in Chaptei 3 you will find that the 8086 has an
exchange n ist ruction, XCHG, which can be used In
swap two bytes or to swap two words. The 8086 does not
have a specific instruction to swap the nibbles in a byte.
1low .cr, if you think of the operation that we need to do
as shifting or rotating the BCD bits four bit positions to
the left, this will give you a good idea which instruction
1 11 11 11 11 11 11 11 1
will do the job for you. The 8086 has a wide variety of
rotate and shift instructions. For now let's look at the
ml, ite instructions. There arc (wo instructions. ROL
and RCL, which rotate the hits of a specified operand to
the left Figure 4-4 shows in diagram form how these
two work. For ROf each bit in the specified register or FIGURE 4-4 ROL instruction and RCL instruction
memory location is rotated one bit position to the left. operations tor byte operands.

76 ( HMMIK FOUR
contents ol the destination are lost. You can, howevei . p. 11 1 woi ks In this program we use the WD Instruction
use .111 \DD or an OR Instruction to pack the two BCD to zero (mask) unwanted bus in die AS< 11 bytes. Any bil
nibbles ANDed with a <) will bee %oi remain a zero
As described In the previous program example, the ANDed with a 1 will remain die same We use the KOI
ADD Instruction adds the contents ol a specified source instruction to rotate a nibble Iron I tin' lowei nibble posi
to die contents of .1 specified destination and leaves the lion to (be higher nibble position. In this case the R< >R
result in the specified destination. For the example pi o Instruction would also accomplish the same result. Fi-
gram here, the instruction ADD AL, BL can be used in nally, use
we the OR instruction to combine the two
combine the two BCD nibbles. Take a look al Figure 4-2 BCD nibbles in one byte. Any bit ORed with a I will be
to help you visualize (bis addition. come oi i en i.i in a l . Any bit ORed with a (i will remain
Ifyoulookup the OR instruction in Chapter 6. you will tin same
find (bai ii has the formal OR destination, source. This
Instruction ORs each bit in the specified source with the
corresponding bit in the specified destination I be re FLAGS, JUMPS, AND WHILE— DO
snlt of tbe ORing is left in the specified destination. IMPLEMENTATION
Remember from basic logic or the review in Chapter l
thai ORing a bit with a 1 always produces a result of I. Introduction
( (Ring a bit with a 0 leaves the bit unchanged. To set a The real power of a computer comes from its ability to
bit in a word to a 1 then, all you have to do is OR that bit repeat a sequence ol instructions as long us some con-
With a word which has a 1 in that bit posit ion and O's m dition exists,repeat a sequence of instructions until
all the other bit positions. This is similar to the way the some condition exists, or choose between two or more
AND instruction is used to clear bits in a word to O's. sequences of actions based on some condition. Flags
See the OR instruction description in Chapter 6 for ex- indicate whether some condition is present or not.
amples
this.of Jump instructions are used to tell the computer what
For the example program here we use the instruction sequence of actions to take based on the condition indi-
OR AL, BL to pack the two BCD nibbles. Bits ORed with catedthe
by Hags. In this section we first discuss the
O's will not be changed. Bits ORed with Is will become 8086 conditional Hags and the 8086 jump instructions.
or stay 1 's. Again look at Figure 4-2 to help you visualize Then we show with examples how the WHILE — DO
this operation. structure is implemented and used.

SUMMARY OF BCD PACKING PROGRAM

Figure 4-5 shows the complete program to produce a The 8086 Conditional Flags
packed BCD bvte from two ASCII bytes. Work your way The 8086 has six conditional flags. They are the carry
through this to make sure you understand how each flag, the parity flag, the auxiliary carry flag, the zero

;8086 PROGRAM
; ABSTRACT Program to produce a packed BCD byte from
two ASC I I -encoded digits.
The first ASCII digit (5) is located in AL
The second ASCII digit (9)is located in BL
The result (packed BCD) to be left in AL
REGISTERS USED CS, AL, BL, CL
5P0RTS USED : None
; PROCEDURES None used

CODE HERE SEGMENT


ASSUME CS C0DE_HERE
MOV AL, '5' ; 1 oad first ASCII digit into AL
MOV BL, '9' load second ASCII digit into BL
AND AL, OFH mask upper <4 bits of first digit
AND BL, OFH mask upper <+ bits of second digit
MOV CL, O^H load CL for <+ rotates required
ROL AL, CL rotate AL ^ bit positions
OR AL, BL combine nibbles, result in AL

CODE HERE ENDS


END

FIGURE 4-5 8086 assembly language program to produce packed BCD from
two ASCII characters.

808b ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES— PART I 77


flag, the sign flag, and the overflow flag. Chapter 1 THE AUXILIARY CARRY FLAG
shows numerical examples of the conditions indicated
This flag has significance in BCD addition or BCD sub-
by these flags. Here we review these conditions and
traction.
a carryIf is produced when the least-signifi-
show how some of the important 8086 instructions af-
cant nibbles
of 2 bytes are added, the auxiliary carry flag
fect these
flags.
will be set. In other words, a carry out of bit 3 sets the
auxiliary carry flag. Likewise, if the subtraction of the
THE CARRY FLAG WITH ADD, SUBTRACT, AND
least-significant nibbles requires a borrow, the auxiliary
COMPARE INSTRUCTIONS
carry borrow flag will be set. The auxiliary carry borrow
If the addition of two 8-bit numbers produces a sum flag is only used by the DAA and the DAS instructions.
greater than 8 bits, the cam- flag will be set to a 1 to Consult the DAA and the DAS instruction descriptions
indicate a earn- into the next bit position. Likewise, if in Chapter 6 and the BCD operation examples section of
the addition of two 16-bit numbers produces a sum Chapter 1 for further discussion of BCD operations.
greater than 16 bits then the carry- flag will be set to a 1
to indicate that a final earn- was produced by the addi- THE ZERO FLAG WITH INCREMENT,
tion. DECREMENT, AND COMPARE INSTRUCTIONS
During subtraction the carry flag functions as a bor- As the name implies, this flag will be set to a 1 if the
row flag.If the bottom number in a subtraction is larger result of an arithmetic or logic operation is zero. For
than the top number, then the carry/borrow flag will be example, if you subtract two numbers which are equal,
set to indicate that a borrow was needed to perform the the zero flag will be set to indicate that the result of the
subtraction. subtraction was zero. If you AND two words together
The 8086 compare instruction has the format CMP and the result contains no 1 s. the zero flag will be set to
destination, source. The source can be an immediate indicate that the result was all O's.
number, a register, or a memory location. The destina-
Besides the more obvious arithmetic and logic in-
tion canbe a register or a memory location. The compar- structions affect
which the zero flag, there are a few
isondone
is by subtracting the contents of the specified
other very useful instructions which also do. One of
source from the contents of the specified destination.
these is the compare instruction. CMP. which we dis-
Flags are updated to reflect the result of the comparison, cussed with
the carry flag previously. As shown there,
but neither the source nor the destination is changed. If
the zero flag will be set to a 1 if the two operands com-
the source operand is greater than the specified destina-
paredequal.
are
tion operand, then the carry borrow flag will be set to
Another important instruction which affects the zero
indicate that a borrow was needed to do the comparison
flag is the decrement instruction. DEC. This instruction
(subtraction). If the source operand is the same size as
will decrement or. in other words, subtract one from, a
or smaller than the specified destination operand, then
number in a specified register or memory location. If.
the carry/borrow flag will not be set after the compare. If after decrementing, the contents of the register or mem-
the two operands are equal, the zero flag will be set to a
ory location are zero, the zero flag will be set. Here's a
1 to indicate that the result of the compare (subtraction! preview of how this is used. Suppose that we want to
was all O's. Here's an example and summary of this for
repeat a sequence of actions nine times. To do this we
vour reference.
first load a register with the number 09H. and execute
the sequence of actions. We then decrement the register
CMP BX. CX
and look at the zero flag to see if the register is down to
condition CF ZF zero yet. If the zero flag is not set. then we know that the
CX - BX 1 0 register is not yet down to zero, so we tell the 8086. with
CX BX 0 0 a jump instruction, to go back and execute the sequence
CX = BX 0 1 of instructions again. The following sections will show
many specific examples of how this is done.
The compare instruction is very important because it The increment instruction. INC destination, also af-
allows you to easily determine whether one operand is fects the
zero flag. If an 8-bit destination containing
greater than, less than, or the same size as another op- FFH or a 16-bit destination containing FFFFH is incre-
erand. mented,
result
the in the destination will be all O's. The
zero flag will be set to indicate this.
THE PARITY FLAG

Parity is a term used to indicate whether a binarv word


THE SIGN FLAG— POSITIVE AND NEGATIVE
has an even number of Is or an odd number of Is. A NUMBERS
binary number with an even number of Is is said to When you need to represent both positive and negative
have even parity. The 8086 parity flag will be set to a 1 numbers for an 8086. you use 2's complement sign-and-
after an instruction if the lower 8 bits of the destination magnitude form as described in Chapter 1. In this form
operand has an even number of Is. Probablv the most the most significant bit of the byte or word is used as a
common use of the parity flag is to determine if ASCII sign bit. A 0 in this bit indicates that the number is
data sent to a computer over phone lines or some other positive. A 1 in this bit indicates that the number is
communications link contains any errors. A later chap- negative. The remaining 7 bits of a byte or the remain-
ter willdescribe this use of parity. ing 15
bits of a word are used to represent the magni-

78 CHAPTER FOUR
tude oi the number For .1 positive numbei the magni in the code segmenl base In CS Jump Instructions
tude will be In standard binary form. F01 .1 negative change the numbei In the Instruction pointer register.
number the magnitude will be in 2's complemenl form .iiul in some ' .isis they also load .1 new number Into the
Aftei .111arithmetic or logic Instruction executes, the code segment registei l"he 81 186 I Ml' instruction always
sign Flag will be ,1 copy ol the mosl significanl bil ol the causes a jump to occur. Tins is referred to as an u neon
destination byte 01 the destination word, In addition to dltional jump, the 8086 also has .1 large collection ol
lis use with signed arithmetit operations, the sign flag conditional jump Instructions which cause .1 jump
can be used to determine il .111operand has been dei re based on whethei some condition is present 01 not. In
mented beyond zero. Decrementing 00H, foi example, ilus section we discuss how the unconditional jump
will give IT II Since the MSB ol lit I is ,1 I. the sign flag msiiui tion operates. In .1 latei sei tion we dist uss the
u ill be sel operation ol the conditional jump instructions.

Illl o\i Know FLAG UNCONDITIONAF JUMP INSTRUC HON l~YPES


OVERVIEW
l'h is flag will be set ii the result ol a signed operation is
too large to lii In the number of bits available to repre- The 8086 unconditional jump instruction, IMP, has five
sentTo
ii. remind you ol what overflow means, here is different types. Figure -I 7 shows the names and in-
an example. Suppose you add the 8-bil signed number struction coding
templates lor these five types. We will
01 1 1D101 (+117 decimal) and the 8-bit signed number first summarize bow these live work to give von an over
00110111 1+55 decimal). Tin- result will be 10101100 view, and then we will describe in detail the tun types
I -i 172 decimal) which is the correct binary result in this you need lor your programs ai this point. The IMP in-
case, but is too large to lit in the 7 bits allowed for the struction description
in Chapter <>shows examples ol
magnitude in an 8-bit signed number. For an 8-bit each ol the live types.
signed number, a 1 in the most significant bit indicates
a negative number. The overflow Dan will be set after
this operation to indicate that the result of the addition IMP = lump
has overflowed into the sign bit.

Within segment or group, II' relative — near and short


The 8086 Unconditional Jump Instruction
< 'l If I 11 -1.1 lispH

INTRODUCTION
Opcode Clocks Operatic
Jump instructions can be used to tell the 8086 to start II' - II' ( Displ6
fetching its instructions from some new location. Figure IP % IP + I Hsp8
I )isp8 sign exli nded
4-6 shows in diagram form how a jump instruction af-
fects program
the execution flow. The 8086 remember,
computes the physical address to fetch the next code
Within segment or group. Indirect
byte from by adding the offset in the instruction pointer

Opcode Clock., Operation

Inter-segment or group. Direct


1 iih. 1,1,' offsel lov offset-high , seg-lo

Opcode Clocks Operatic

MAIN
PROGRAM Inter-segment or group. Indirect
SEQUENCE

Opcode I 101

JUMP TO
Opcode Clocks Operation
START

( stop) II 24 + EA

FIGURE 4-6 Change in program flow that can be caused FIGURE 4-7 8086 unconditional IMP instructions (Intel
by jump instructions. Corp.).

8086 ASSEMBLYLANGUAGE PROGRAMMING TECHNIQUES—PART 1 79


THE DIRECT WITHIN-SEGMENT NEAR JMP byte first, and the new value for CS will be written in the
INSTRUCTION next two memory locations, low byte first. Again, the
MOD — R/M byte in the second byte position of the in-
This instruction can cause the next instruction to be
struction
template
code indicates that the first memory
fetched from anywhere in the current code segment. A
address can be specified in any one of the 24 memory
jump to an address in the same segment as the jump
addressing modes shown in Figure 3-8.
instruction is commonly called an intrasegment or a
near jump. To produce the new instruction fetch ad-
DIRECT WITHIN-SEGMENT NEAR AND DIRECT
dress this
instruction adds a 16-bit signed displace-
WITHIN-SEGMENT SHORT JMP EXAMPLES
ment containedin the instruction to the contents of the
instruction pointer register. A signed 16-bit displace- Suppose that in a program you want to keep executing
ment means that the jump can be to a location any- an instruction or group of instructions over and over
where from
+32.767 to -32.768 bytes from the current again. Figure 4-8 shows how the JMP instruction can be
instruction pointer location. A positive displacement used to do this. In this program the label BACK followed
usually means you are jumping ahead in the program, by a colon is used to give a name to the address we want
and a negative displacement usually means you are to jump back to. When the assembler reads this label it
jumping "backward" in the program. will make an entry in its symbol table as to where it
found the label. Then when the assembler reads the JMP
THE DIRECT WITHIN-SEGMENT SHORT-TYPE JMP instruction and finds the name BACK, it will be able to
INSTRUCTION calculate the displacement from the jump instruction to
This instruction is a special case of a near jump. This the label. This displacement will be part of the code for
JMP instruction produces the new instruction fetch the instruction. Even if you are not using an assembler,
you should use labels to indicate jump destinations so
address by adding a signed 8-bit displacement, con-
tained
the ininstruction, to the contents of the instruc- that you can easily see them. The NOP instruction used
tion pointer
register. With an 8-bit signed displacement in the program in Figure 4-8 does nothing except fill
the jump can be to a location anywhere from + 127 to space. We used it in this example to represent the in-
-128 bytes from the current instruction pointer loca- structions
we that
want to loop through over and over.
We also use it to represent the instructions after the
tion.
JMP — BACK loop. Actually, the way this program is writ-
THE INDIRECT WITHIN-SEGMENT JMP ten the8086 will never get to the instructions after the
INSTRUCTION JMP instruction. Can you see why? The answer is that
once the 8086 gets into the IMP— BACK loop, the only
This instruction replaces the contents of the instruction
ways it can get out are if the power is turned off, an
pointer register with the contents of a specified 16-bit
interrupt occurs, or the system is reset. In most pro-
register or the contents of a specified memory location.
gramsof onethe instructions we have represented with
The MOD — R/M byte in the second byte position of the
a NOP would be a conditional jump instruction which
coding template for this instruction indicates that the
would get execution out of the loop when the specified
register or memory location can be specified in any of
condition occurred.
the 32 register and memory addressing modes shown in
Figure 3-8. Since this type JMP is to an address in the Now let's see how the binary code for the JMP instruc-
same code segment as the JMP instruction, it is another tionFigure
in 4-8 is constructed. The jump is to a label
example of a near jump. in the same segment so this narrows our choices down
to the first three types of JMP instruction shown in Fig-
THE DIRECT INTERSEGMENT-TYPE JMP ure 4-7.For several reasons it is best to use the direct-
type JMP instruction whenever possible. This narrows
This instruction causes a jump to another code seg-
our choices down to the first two types in Figure 4-7.
mentjumpA to another code segment is often referred
The choice between these two is determined by whether
to as an intersegment or Jar jump. In order to get to
you need a 1-byte displacement to reach the JMP desti-
another segment, you have to change the contents of
nation address,or whether you need a 2-byte displace-
both the instruction pointer and the code segment reg-
mentreach
to the IMP destination. Since for our exam-
isters.
shown
As in Figure 4-7, for this type instruction
ple program the destination address is within the range
the new value for the instruction pointer is written in as
of -128 to +127 bytes from the instruction after the
bytes 2 and 3 of the instruction code. The new value for
IMP instruction, we can use the direct within-segment
the code segment register is written in as bytes 4 and 5
short type of JMP. According to Figure 4-7 the instruc-
of the instruction code. Note that in each case, the low
tion template for this instruction is 11101011 (EBH)
byte is written before the high byte
followed by some displacement. Here's how you calculate
THE INDIRECT INTERSEGMENT JMP the displacement to put in the instruction.

This instruction also causes a far (to another code seg- NOTE: An assembler automatically does this for you,
ment
JMP.
I Therefore, both the instruction pointer reg- but you should still learn how it is done to help you in
ister and
the code segment register contents have to be troubleshooting.
changed. For this type instruction the new values are
taken from four memory locations. The new value for IP The numbers in the left column of Figure 4-8 repre-
will be written in the first two memory locations, low sent the
offset of each code byte from the code segment

HO CHAPTFR FOUR
The IBM Personal Computer MACRO Assembler 10-17-84 PAGE 1-1

page, 132
'•8086 program
'.ABSTRACT : This progra» illustrates a "backwards* ju«p
REGISTERS USED: CS, AL
JPORTS USED : None
;PROCEDURES : None used

OOuo CODE.HERE SEGMENT


ASSUME CS : CODE HERE

0000 04 03 BACK: ADD AL, 03H ; add 3 to total


0002 90 NOP ; duiny instructions
0003 90 NOP ! to represent those
0004 90 NOP ; instructions juiped
0005 90 NOP ; back over
0006 EB F8 JHP BACK ; loop back through
• series of instructions
0008 90 NOP ; duny instructions to
0009 90 NOP ; represent continuation
; after loop
OOOA IE
CODE.HERE ENDS
END

FIGURE 4-8 Program demonstrating "backward" IMP

base. These are the numbers that will be in the instruc- ple within
is the range of - 128 to +127 bytes from the
tion pointer as the program executes. After the 8086 address after the IMP instruction, the instruction can
fetches an instruction byte it automatically increments be coded as a direct within-segment short-type IMP. The
the instruction pointer to point to the next instruction displacement is calculated by counting the number of
byte. The displacement in the instruction then will be bytes from the next address after the IMP instruction to
added to the offset of the next in-line instruction after the destination. If the displacement is negative (back-
the IMP instruction. For the example program in Figure wardthein program I, then it must be expressed in 2's
4-8 the displacement in the JMP instruction will be complement form before it can be written in the instruc-
added to offset 0008H. which is in the instruction tion code template.
pointer after the IMP instruction executes. What this Now let's look at another simple example program, in
means is that when you are counting the number of Figure 4-9, to see how you can jump ahead over a group
bytes of displacement, you always start counting from of instructions in a program. Here again we use a label
the address of the instruction immediately after the JMP to give a name to the address that we want to JMP to. We
instruction. For the example program we want to jump also use NOP instructions to represent the instructions
from offset 0008H back to offset OOOOH. This is a dis- that we want to skip over and the instructions that con-
placement
-8H. of tinue after
the JMP. Now let's see how this JMP instruc-
You can't, however, write the displacement in the in- tioncoded.
is
struction
-8H. as Negative displacements must be ex- When the assembler reads through the source file for
pressed
2's in
complement, sign-and-magnitude form. this program it will find the label "THERE'' after the JMP
We showed how to do this in Chapter 1. First, write the mnemonic. At this point the assembler has no way ol
number as an 8-bit positive binary number. In this case knowing whether it will need 1 byte or 2 bytes to repre-
that is OOOOIOOO. Then, invert each bit of this, includ- sent the
displacement to the destination address. The
ing the
sign bit. to give 11110111. Finally, add 1 to that assembler plays it safe by reserving 2 bytes for the dis
result to give 1111 lOOO binary or F8H which is the cor- placement. Then the assembler reads on through the
rect 2's
complement representation for -8H. As shown rest of the program. When the assembler finds the speci-
in the assembler listing for the program in Figure 4-8. fied label,it calculates the displacement from the in-
the two code bytes for this JMP instruction then are EBH structiontheafterIMP instruction to the label. If the
and F8H. assembler finds the displacement to be outside the
To summarize this example then, a label is used to range of - 128 bytes to +127 bytes, then it will code the
give a name to the destination address for the jump. instruction as a direct within-segment near IMP with 2
This name is used to refer to the destination address in bytes of displacement. If the assembler finds the dis-
the IMP instruction. Since the destination in this exam- placement
be withinto the -128 to +127 byte range.

ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES— PART 1 81


The IBH Personal Coaputer HACRO Asseabler 10-17-8* PAGE 1-1

page, 132
;8086 progras
;ABSTRACT : This prograa illustrates a "forwards" ju«p
iREGISTERS USED : CS, AX
;PORTS USED : None
IPROCEDURESUSED: None

0000 CODE.HERE SEGMENT


ASSURE CS ;: CODE.HERE

0000 EB 05 90 JMP THERE j skip over a series


j of instructions
0003 90 MOP ; duaay instructions
000* 90 NOP i to represent those
0005 90 NOP i instructions skipped
0006 90 NOP ; over
0007 B8 0000 THERE: NOV AX, OOOOH ; zero accumulator before addition
000A 90 NOP ; duaay instructions to
OOOB 90 NOP ! represent continuation
; of execution
oooc CODE.HERE ENDS
END

FIGURE 4-9 Program demonstrating "forward" IMP.

then it will code the instruction as a direct within-seg- programs are the direct within-segment near and the
ment short-type IMP with a 1-byte displacement. In the direct within-segment short. A label followed by a colon
latter case the assembler will put the code for a NOP is used to give the destination address a name for both
instruction, 90H. in the third byte it had reserved for of these )MP types. For the direct within-segment near
the )MP instruction. The instruction codes for the IMP type, a 16-bit displacement contained in the instruction
THERE instruction in Figure 4-9 demonstrate this. As is added to the contents of the instruction pointer to
shown in the instruction template in Figure 4-7. EBH is produce the destination address. This type of jump can
the basic opcode for the direct within-segment short be to an address in the range of -32.768 bytes to
IMP. The 05H represents the displacement to the IMP + 32.767 bytes from the current IP contents. The direct
destination. Since we are jumping forward in this case, within-segment short IMP instruction adds an 8-bit dis-
the displacement is a positive number. The 90H in the placement contained
in the instruction to the IP to pro-
next memory byte is the code for a NOP instruction. The duce destination
the address. For this type IMP the des-
displacement is calculated from the offset of this in- tinationbe can
in the range of - 128 bytes to + 127 bytes
struction. 0002H.
to the offset of the destination label. from the current instruction pointer contents. The dis-
0007H. The difference of 05 between these two is the placement
both for of these JMP types is counted from
displacement you see coded in the instruction. the address of the instruction after the JMP instruction
It you are hand coding a program such as this, you to the address of the destination instruction. A jump
will probably know how far it is to the label and you can ahead in the program is usually represented by a posi-
leave just 1 byte for the displacement if that is enough. If tive displacement. A jump backward in the program is
you are using an assembler and you don't want to waste usually represented by a negative displacement which is
the byte of memory or the time it takes to fetch the exl ra coded in the instruction in its 2's complement sign-and-
NOP instruction, you can write the instruction as IMP magnitude form. Note that if you are making a )MP from
SHORT label. The SHORT operator is a promise to the an address near the start of a 64 Kbyte segment to an
assembler that the destination will not be outside the address near the end of the segment, you may not be
range of - 128 to +127 bytes. Trusting your promise, able to get there with a jump of +32.767. The way you
the assembler then only reserves 1 byte for the displace- get there is to JMP backwards around to the desired des-
ment. tination address.
An assembler will automatically do
this for you.
SUMMARY OF UNCONDITIONAL IMPS One advantage of the direct near- and short-type JMPs
The 8086 lias five types ol unconditional IMP instruc- is that the destination address is specified relative to
tions. The
types you will probably use most often in your the address of the instruction after the IMP instruction.

82 t HAF'TFK FOUR
Since the IMP Instruction In this case does nol i mi nun ten I is "greater" and "less" are used when you are work
an absolute address or offset, the program can be loaded Ing with signed binary numbers I lie 8-bit signed num
anywhere In memory and it will still run correctly. A pro bei 001 1 1001 is greatei (more positive) than the 8 bit
gram which can be loaded anywhere in memory to be signed number 1 loooi lo which repn a nts a rv
run is said to be relocatable. You should try to write number. Also shown in Figure 1 10 is an indication ol
your programs so thai ihev are relocatable the flag conditions thai will cause the 8086 to do the
The Indirect within segment type ol IMP instruction jump. II the specified flag conditions are nol present,
replaces the contents ol the instruction pointei with a i he 8086 will just continue on to the next instruction in
hi I hi value from a registei or memory location specified sequence. In other words, il the jump condition is not
in the instruction. The direct intersegment far type IMP met, tin- conditional jump instruction will effectivelj
loads IP with a new value contained in bytes 2 and :( of function as a NOP. Suppose, foi example, we have the
the instruction code, and n loads CS with a new value instruction |( SAVI , when- SAVE is the label at the des
from bytes 4 and 5 ol the instruction code. The interseg- tination address. II the carry flag is set. this instruction
ment indirect
far-type IMP loads IP and CS with new will cause the 8086 to jump to the instruction at the
values read from a memory location specified in the in- SAVI : label. II the carry flag is nol set, the insliiic lion
sl 1 Uc I I, ill will have no effect other than taking up a little proi essoi
time.
All conditional jumps are short-type jumps. This
The 8086 Conditional lump Instructions means that the destination label musi be in the same
As we slated previously, much ol the real power of a code segmenl as the jump instruction. Also, the desti-
computer comes from its ability to choose between two nation address
must be in the range ol 128 bytes to
courses of action depending on whether some condition + 127 bytes from the address ol the instruction alter the
is present or not. In the 8086 the six conditional flags jump instruction. As we show in later examples, tins
indicate the conditions that are present after an in- limit on the range of unconditional jumps is important
struction.
8086The conditional jump instructions look to be aware of as you write your programs
at the state of a specified flag(s) to determine whether a The conditional jump instructions are usually used
jump should be made or not. Figure 4-10 shows the after arithmetic or logic instructions. Very commonly
mnemonics for the 8086 conditional jump instructions. they are used after compare instructions. For this case
Next to each mnemonic is a brief explanation of the the compare instruction syntax and the conditional
mnemonic. Note that the terms "above" and "below" are jump instruction syntax are such that a little trick
used when you are working with unsigned binary num- makes it very easy to see what will cause a jump to
bers. The
8-bit unsigned number 1 10001 10 is above the occur. Here's the trick. Suppose that you see the in-
8-bit unsigned number 00111001. for example. The struction sequence

MNEMONIC CONDITION TESTED ")UMP IF . . ."

IA/JNBE i 1 or ZF) = 0 above/not below nor equal


IAE/JNB CF = 0 above or equal/not below
IB INAE CF=1 below not above nor equal
IBE/JNA (CF or ZF)=1 below or equal/not above
IC CF=1 carry
IEIZ ZF = I equal zero
IG/JNLE ((SF xor OF) or ZF) = 0 greater/not less nor equal
ICE/1 NL (SF xor OF) = 0 greatei oi equal/not less
IL/JNGE (SF xor OF) = 1 less not greater nor equal
ILE/JNG ((SF xor OF) or ZF)=1 less or equal nol greater
|NC CF = 0 not c am

INE/JNZ ZF = U not equal/not zero


|NO OF = 0 not overflow
INP/jPO PF = 0 not parity parity odd
INS SF = 0 not sign
IO OF=1 i iverflow
IP/JPE PF = 1 parity parity equal
IS SI 1 sign

Note: "above" and "below" refer to the relationship of two unsigned values;
"greater" and "less" refer to the relationship of two signed values.

FIGURE 4-10 8086 conditional JMP instructions lintel Corp.).

8086 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES— PART 1 83


CMP BL. DH

JAE HEATER_OFF

in a program, and you want to determine what these


instructions do. The CMP instruction compares the byte
in the DH register with the byte in the BL register and
sets flags according to the result. A previous section
showed you how the carry and zero flags are affected by
a compare instruction. According to Figure 4-10 the JAE
instruction says "Jump if above or equal" to the label
HEATER_OFF. The question now is. will it jump if BL is
above DH. or will it jump if DH is above BL. You could
determine how the flags will be affected by the compari-
son and use Figure 4-10 to answer the question. How-
ever,easier
an way is to mentally read parts of the com-
pare instruction between parts of the jump instruction.
If you read the example sequence as "Jump if BL is
above or equal to DH." the meaning of the sequence is
immediately clear. As you write your own programs,
thinking of a conditional sequence in this way should
help you to choose the right conditional jump instruc-
tion. The
next sections show you how we use condi-
tional and
unconditional jump instructions to imple-
ment some of the standard program structures and
solve some common programming problems.

WHILE— DO Implementation and Example


FLOWCHART
Remember from the discussion in Chapter 3 that the
WHILE— DO structure has the form:

READ TEMPERATURE
WHILE some condition is present DO
WHILE TEMPERATURE %
Action TURN HEATER ON
Action TURN HEATER OFF

PSEUDOCODE

An important point about this structure is that the con-


dition
checked
is before any action is done. In industrial
control applications of microprocessors there are many FIGURE 4-11 Flowchart and pseudocode tor heater
cases where we want to do this. The following very sim- control problem.
ple example will show you how to implement this struc-
ture8086
in assembly language. condition-checking part of the structure. If the tempera-
tureatis or above 100°, execution will exit the structure
DEFINING THE PROBLEM AND WRITING THE and do the next mainline action, turn off the heater. If
ALGORITHM the heater is already off. it will not do any harm to turn it
off again. If the temperature is less than 100°, the heater
Suppose that in controlling a chemical process we want
is turned on and the temperature rechecked. Execution
to bring the temperature of a solution up to 100C be-
will stay in this loop while the temperature is below
fore going
on to the next step in the process. If the solu-
100:. Incidentally, it will not do any harm to turn the
tion temperature is below 100\ we want to turn on a
heater on if it is already on. When the temperature
heater and wait for the temperature to reach 100:. If the
reaches 100:. execution will exit the structure and go on
solution temperature is at or above 100\ then we want
to the next mainline action, turn off the heater.
to go on with the next step in the process. The WHILE —
DO structure fits this problem because we want to
IMPLEMENTING THE ALGORITHM IN ASSEMBLY
check the condition (temperature) before we turn on the
LANGUAGE
heater. We don't want to turn on the heater if the tem-
perature
alreadyis high enough because we might over- Figure 4-12 shows one way to write the assembly lan-
heat the
solution. guagethis
for example. We have assumed for this exam-
Figure 4-1 1 shows a flowchart and the pseudocode of ple thatthe temperature sensor inputs an 8-bit binary
an algorithm for this problem. The first step in the algo- value for the Celsius temperature to port FFF8H. We
rithm
to isread in the temperature from a sensor con- have also assumed that the heater control output is con-
nected
a port.
to The temperature read in is then com- nected
the to most significant bit of port FFFAH. (Inci-
pared with 100 . These two parts represent the dentally, port
these addresses are two of the available

H4 CH-\PTf f
The IBM Personal Computer MACRO Assembler 02-16-85 PASS M

page* 132
8086 program
ABSTRACT program turns heater off if temperature equals
100 degrees or sore, and to turn the heater on
if the temperature is below 100 degrees.
REGISTERS USED: CS, DX, AL
PORTS USED : FFF8H - for temperature data input
FFFAH - MSB for heater control output
PROCEDURES None used

0000 CODE HERE SEGMENT


ASSUME CS CODE HERE

; initialize port FFFA as an output port


0000 BA FFFE MOV DX, OFFFEH ; point DXto port contol register
0003 BO 99 MOV AL, 99H ; control word to set up port FFFA as an output
0005 EE OUT DX, AL ; send control word to port

0006 BA FFF8 TEMP IN: MOV DX, 0FFF8H ; read in temperature data
0009 EC IN AL, DX
000A 3C 6* CMP AL, 100 ; if temp >= 100
000C 73 08 JAE HEATEROFF ; go turn heater off

000E BO 80 MOV AL, 80H load code for heater on


0010 BA FFFA MOV DX, OFFFAH point DXto output port
0013 EE OUT DX, AL turn heater on
001* EB FO JMP TEMPJN go & read temp again
0016 BO 00 HEATER OFF: MOV AL,0"0 load code for heater off
0018 BA FFFA MOV DX, OFFFAH point DXto output port
001B EE OUT DX, AL turn heater off

001C CODE HERE ENDS


END

The IBM Personal Computer MACROAssembler 02-16-85 PAGE 1-1

page, 132
8086 PROGRAM
ABSTRACT : program to turn heater off if temperature
equals 100 degrees or more, and to turn the
heater on if the temperature is below 100 degrees.
REGISTERS USED: CS, DX, AL
PORTSUSED : FFF8H - for temperature data input
FFFAH_ MSBfor heater control output
PROCEDURES : None used

0000 CODE HERE SEGMENT


ASSUME CS : CODE HERE

FIGURE 4-12 Assembly language program for heater control problem, (a) First
approach, (b) Improved version.

ASSEMBLYLANGUAGE PROGRAMMING TECHNIQUES—PART I 85


; initialize port FFFA as an output poi t
0000 BA FFFE MOV DX, OFFFEH ", point DXto port contol register
0003 BO 99 HOV AL, 99H i control word to set up port FFFA as an output
0005 EE OUT DX, AL ', send control word to port

0006 BA FFF8 TEMP.IH: HOV DX, 0FFF8H i point DXat input port
0009 EC IN AL, DX ; read in tesperature data
OOOA 3C 6* CMP AL, 100
OOOC 72 03 J6 HEATER_ON if tesp < 100 go
turn heater ON
OOOE EB 09 90 JHP HEATER_OFF te«p }- 100 go
turn heater OFF
0011 BO 80 HEATER.ON: MOV AL, SOH load code for heater ON
0013 BA FFFA HOV DX, OFFFAH point DXat output port
0016 EE OUT DX, AL turn heater ON
0017 EB ED JHP TEMP.IH read teap again

0019 BO 00 HEATEft.OFF: MOV AL, 00 load code for heater OFF


001B BA FFFA MOV DX, OFFFAH point DXat output port
001E EE OUT DX, AL turn heater OFF

OOiF CODE.HERE ENDS


END

FIGURE 4-12 (continued).

ports. P2A and F2B. on an SDK-86 board.) A 1 sent to 05H. For the variable port output instruction the 16-bit
the MSB of port FFFAH turns the heater on. port address is put in the DX register. The output in-
The 8086 lias two types of input instruction, fixed struction format
for this type is OUT DX, AL or OUT DX,
port and variable port. The fixed port instruction has AX. If you load DX with FFFAH and then do an OUT DX,
the format IN AL, port or IN AX, port. The term "port" in AL instruction as in Figure 4-12a. the 8086 will copy the
these represents an 8-bit port address to be put directly contents of the AL register to port FFFAH.
in the instruction. The instruction IN AX, 07H. for ex- Most common devices used as ports for microcomput-
ample,ropy
will a word from port 07H to the AX register. ers canbe used for input or output. When the power is
With an 8-bit port address you can address any one of first applied to these devices they are in the input mode.
256 possible ports. The port address is fixed, however. II you want to use any of these devices as output ports,
The program cannol change the port address as it exe- you must send the device a control word which switches
cutes. the device to output mode. Chapter 9 and later chapters
For the variable-port input instruction, the address of will describe in detail how you initialize programmable
the desired port is put in the DX register. The input port devices, but to give you an introduction we show
instruction foi this type then has the format IN AL, DX you here how to initialize one of the ports in an 8255
or IN AX, DX. If you load DX with FFF8H and then do an device on an SDK-86 microcomputer for use as an out-
IN AL, DX as in Figure 4-12a. the 8086 will copy a byte of put port. To specify the function of one of these pro-
data from port FFF8H to the AL register. The variable- grammable devices
you send a control word to a register
porl type instruction has two major advantages. First, inside the device. You can find the control word format
up to 65,536 different ports can be specified with the tot each type of device in the manufacturer's data book.
16-bit port address in DX. Second, the port address can For one of the 8255s on an SDK-86 board, the address of
be changed as a program executes by simply putting a the control register in the device is FFFEH. The instruc-
different number m I).\. This is handy in a case where tion MOVDX, OFFFEH points DX at this address. The
you want the computer to be able to input from 15 dif- control word needed to make port P2B of this 8255 an
ferent terminals, for example. Instead of writing 15 dif- output, and P2A and P2C inputs, is 99H. I In Chapter 9
ferent input
programs, you can write one input program we show how we determined this control word.) We load
which changes the contents ol DX to input from differ- this control word into AL with MOV AL, 99H and send it
ent terminals. to the 8255 control register with OUT DX, AL. Now we
The 8086 also has a fixed-port output instruction and can output a byte to port P2B of this device any time we
a variable-port output instruction. The fixed-port out- need to in the program. The actual address of this port
put instruction has the form OUT port, AL or OUT port, P2B on the SDK-86 board is FFFAH. It is to this address
AX. Here again the term port represents an 8-bit port that we will output a byte to turn the heater on or off.
address written in the instruction. OUT OS, AL, for ex- After we input the data from the temperature sensor
ample,copy
will the contents ol the AL register to port in Figure 4 -12a we compare the value read with 100

86 CHAPTER F( )HK
(64H). Tli<- |AI instruction after the compare can be read REPEAT— UNTIL IMPLEMENTATION AND
.is lump to the label HEATER OFF II AL in above 01 EXAMPLES
equal to 100." Note thai we used the Jump If Above 01
Equal instruction rather than a Jump il Equal instruc Remember from the discussion in Chaptei 3 that the

lion. Can you sec why? To see the answer, visualize REPEAT UNTIL structure has the form

whai would happen il we had used a II Instruction and


the temperature ol the solution were 101 '. On the firsl REPEAT
check the temperature would not be equal to 100 so the Action

sum. would turn on the heater. The heater would nol Action

gel turned off until meltdown.


It the heater temperature is below 100 . we turn on
the heater hv loading a I in the most significant bit ol
UNTIL some condition is present
AL and outputting this value to the most significant bit
ol port FFFAH. We then do an unconditional IMP hack to An important point about this structure is that the
check the temperature again. action or series of actions is done once before the condi
When the temperature is at or above 100 . we load a 0
tion is checked. Compare this with the WHILE: DO
in the most significant bit of AL and output this to port
structure.
FFFAH to turn off the heater. Note that the action of
The following examples will show you how you can
turning off the heater is outside the basic WHILE — DO
implement the REPEAT— UNTIL with 808(5 assemblv
structure. The WHILE-DO structure is shown by the
language and introduce you to some more assemblv lan-
dotted box in the flowchart in Figure 4-1 la and by the
guage programmingtechniques.
indentation in the pseudocode in Figure 4-1 lb.

SOLVING A POTENTIAL PROBLEM OF


CONDITIONAL JUMP INSTRUCTIONS Waiting for a Strobe Signal
In the example program in Figure 4- 12a we used the
DEFINING THE PROBLEM AND WRITING THE
conditional jump instruction )AE to help implement the
ALGORITHM
WHILE — DO structure. Conditional jump instructions
have a potential problem which you should become Many systems that interface with a microcomputer out-
aware of at this point. All the conditional jump instruc- put dataon parallel-signal lines and then output a sepa-
tions are
short-type jumps. This means that a condi- rate signalto indicate that valid data is on the parallel
tional jump
can only be to a location within the range of lines. The data-ready signal is often called a strobe. An
- 128 to +127 bytes from the instruction after the con- example of a strobed data system such as this is an
ditional instruction.
jump This limit on the range of the ASCII-encoded computer-type keyboard. Figure 4-13
jump posed no problem for the example program in Fig- shows how the parallel data lines and the strobe line
ure12a
4- because we were only jumping to a location 8 from such a keyboard are connected to ports of a micro-
bytes ahead in the program. Suppose, however, that the
instructions for turning on the heater required 220
DATA BUS TO 8086
bytes of memory. The HEATER_OFF label would then be
0„ D, 8255
outside the range of the )AE instruction.
D, D, P2A
Figure 4- 12b shows how you can change the instruc-
tions slightly
to solve the problem without changing the D, D .

basic WHILE — DO overall structure. In this example we D, D> PORT


read the temperature in as before and compare it to 100 °.i D FFF8H
(64H). We then use the Jump if Below instruction to D5 O,,
jump to the program section which turns on the heater. De D(,
This instruction, together with the CMP instruction, D, D,
says jump to the label HEATERON if AL is below 100. If ASCII
the temperature is at or above 100. the |B instruction will KEYBOARD

act like a NOP. and the 8086 will go on to the IMP STROBE D„ 8255
HEATER OFF instruction. Changing the conditional D, PIA
jump instruction and writing the program in this way D ,

means that the destination for the conditional jump D- PORT


instruction is always just two instructions away. There- D FFF9H
fore, you
know that the destination will always be reach-
D.,
able. Exceptfor very time-critical program sections, you
De
should always write conditional jump instruction se-
o7
quences
this in way so that you don't have to worry
about the potential problem. The disadvantages of this
approach are the time and memory space required by FIGURE 4-13 ASCII encoded keyboard with strobe
the extra IMP instruction. connected to microcomputer ports.

ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES— PART I 87


C START J computer. When a key is pressed on the keyboard, cir-
cuitry
theinkeyboard detects which key is pressed and
sends the ASCII code for that key out on the eight data
lines connected to port FFF8H. After the data has had
time to settle on these lines, the circuitry in the key-
board sends
out a key-pressed strobe which lets you
know that the data on the eight lines is valid. We have
connected this strobe line to the least-significant bit of
port FFF9H. A strobe can be an active high signal or an
active low signal. For the example here, assume that the
strobe signal goes high when a valid ASCII code is on the
parallel data lines.
If we want to read the data from this keyboard, we
can't do it at just any time. We must wait for the strobe
to go high so that we know that the data we read will be
valid. Basically what we have to do is look at the strobe
signal and test it over and over until it goes high. Figure
4- 14a shows how we can represent this operation with a
flowchart, and Figure 4- 14b shows the pseudocode. We
want to repeat the read-strobe-and-test loop until the
FLOWCHART
strobe is found to be high. Then we want to exit the loop
and read in the ASCII code byte. The basic REPEAT -
UNTIL structure is shown by the indentation in the
REPEAT pseudocode. Note that the read ASCII data action is not
READ KEYPRESSED STROBE
part of this structure and is therefore not indented.
UNTIL STROBE = 1
READ ASCII CODE FOR KEY PRESSED

PSEUDOCODE

The IB?! Personal Computer MACROAssembler 02-13-35 PAGE 1-!

page, 132
;3036 PROGRAM
; ABSTRACT : program to read ASCII code when a strobe
> signal is sent from a ke/board
% .REGISTERS
USED: CS. DX, AL
;PDRTS USED : FFF9H - strobe signal input port
! : FFF3H - ASCII data input port
; PROCEDURES : None used

':;V CODE HERE SEGMENT


ASSUME CS : C0DE_HERE

0000 BA FFF9 MOV DC, 0FFF9H point DX at strobe port


000:. EC LOOK again: IN AL, DX read keyboard strobe
0004 24 0! AND AL, 01 isask e>:tra bits and
set flags
0S0i Ti FB JZ LOOK AGAIN strobe low, keep looking
0003 BA FFF3 NOV DX, 0FFF3H point DX at data port
000B EC IN AL. DX read in ASCII code

CODE.HERE ENDS
END

FIGURE 4-14 Flowchart, pseudocode, and assembly language for reading ASCII
code when a strobe is present (a) Flowchart, (b) Pseudocode, (c) Assembly
language program.

88 ( HAPTER FOUR
IMPLEMIN1INC, lill MCI IRITHM Willi show you how you can use a conditional jump instrui
ASSEMBLE LANGUACI tiontomaketl PEAT a series of action
the Hags indicate thai some condition is pn senl i hi
Figure l l tc shows the 8086 assembly language to im
following section shows anothei example ol implemenl
plement this algorithm. To read in the key-pressed
ing the REPEAT UNTIL structure. This example alsi
strobe signal, we firsl load the address ol the porl to
shows you how a registei based addressing mode i;
which it is connected Into the DX register. Then we use
used to access data in me \
the variable port input instruction. IN AL, DX, to read
the strobe data to AL. Tins input instruction copies .1 Operating on a Series of Data Items in Memory
byte ol data from porl FFF9H to the AL register. How-
In main' programming situations we wanl to j
ever,only
we cue about the least significant bit ol the
some operation on a series ol data items stored in sue
byte, because that is the one the strobe is connected to.
cessive memory locations. We might, foi example, want
We would like 10 find oul il this l>ii is a 1 We will show
to read in a series of data values from a port and put the
you three ways to do il
values in successive memory locations. A series ol data
The first way, shown in Figure 4- 14c. is to AND the
values ol the same type stored in successive memory
byte in AL with the immediate number 0 1 1 1. Remember
locations is often called an array. Each value in the
that a bit ANDed with a 0 becomes a 0 (is masked). A hi!
array is referred to as an element ol the array Foi out
ANDed with a 1 is not changed. If the least-significant
example program here we want to add an inflation factoi
bit is a 0, then the result of the ANDing will be all 0's.
of 03H to each price in an 8-element array ol prices.
The zero flag, ZF, will be set to a 1 to indicate this. If the
Each price is stored in a byte location as packed BCD
hast significant bit is a 1 . the zero flag will not be set to
(two BCD digits per byte). The prices then are in the
a 1 because the result of the ANDing will still have a 1 in
range of 1 cent to 99 cents. Figure 4- 1 rui and /; shows a
the least-significant bit. The Jump if Zero instruction,
flowchart and the pseudocode for the operations that we
JZ. will check the state of the zero flag and, if it finds the
want to perform. Follow through whichever form you
zero nag set. will jump to the label LOOR AGAIN. If the
feel more comfortable with.
JZ instruction finds the zero flag not set (indicating
We read one of the BCD prices from memory, add the
that the LSB was a one), it passes execution on to the
inflation factor to it, and adjust the result to keep it in
instructions which read in the ASCII data.
BCD format. The new value is then copied back to the
Another way to check the least-significant bit of the
array, replacing the old value. Alter that, a check is
strobe word is with the TEST instruction instead of the
made to see if all of the prices have been operated on. II
AND instruction. The 8086 TEST instruction has the for-
they haven't, then we loop back and operate on the next
mat TEST
destination, source. The TEST instruction ANDs
price. The two questions that may occur to you at this
the contents of the specified source with the contents of
point are. "How are we going to indicate in the program
the specified destination and sets flags according to the
which price we want to operate on, and how are we
result. However, the TEST instruction does not change
going to know when we have operated on all ol the
the contents of either the source or the destination. The
prices?'' To indicate which price we are operating on at a
AND instruction, remember, puts the result of the
particular time, we use a register as a pointer. To keep
ANDing in the specified destination. The TEST instruc-
track of how many prices we have operated on we use
tionuseful
is if you want to set flags without changing
another register as a counter. The example program 111
the operands. In the example program in Figure 4 14c
Figure 4- 15c shows one way in which our algorithm for
the AND AL, 01 H instruction could be replaced with the
this problem can be implemented in assembly language
TEST AL, 01 H instruction.
The example program in Figure 4- 15c uses several
Still another way to check the least-significant bit of
assembler directives. Let's review the function of these
the strobe byte is with a rotate instruction. If we rotate
before describing the operation of the program in-
the least-significant bit into the carry flag, we can use a
structions.ARRAYS
The HERE SEGMENT and the
Jump if Carry or Jump if Not Carry instruct ion to control
ARRAYS HERE ENDS directives are used to set up a logi-
the loop. For this example program we can use either
cal segment containing the data definitions. The
the ROR instruction or the RCR instruction. Assuming
CODE HERE SEGMENT and the CODE HERE ENDS direc-
that we choose the ROR instruction, the check and jump
tives are
used to set up a logical segment which con-
instruction sequence would look like this:
tains the program instructions. The ASSUME
LOOK AGAIN: IN AL, DX CS:CODE HERE, DS: ARRAYS HERE directive tells the
ROR AL,l ; Rotate LSB into assembler to use CODE HERE as the code segment and
; carry use ARRAYS HERE for all references to the data seg-
INC LOOICAGAIN; If LSB = 0, keep ment. The
END directive lets the assembler know thai il
; looking has reached the end of the program. Now let's discuss
For your programs you can use the way of checking a bit the data structure for the program
that seems easiest in a particular situation. The statement. COST DB 20H,28H,15H,26H,19H,
To read the ASCII data we first have to load the port 27H,16H,29H, in the program tells the assembler to sel
address, FFF8H. into the DX register. We then use the aside successive memory locations for an 8-element
variable port input instruction IN AL, DX to copy the array of bytes. The array is given the name COST. When
ASCII data byte from the port to the AL register. the assembled program is loaded into memory to be run.
The main purpose of the preceding section was to the eight memory locations will be loaded with the eight

8086 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES— PART 1 H*>


FIGURE 4-15 Adding a constant to a series of values in memory, (a) Flowchart.
(6) Pseudocode, (c) Assembly language program, (d) Example program
showing array indexing.

REPEAT
GET A PRICE FROM ARRAY
ADD INFLATION FACTOR
ADJUST RESULT TO CORRECT BCD
PUT RESULT BACK IN ARRAY
UNTIL ALL PRICES ARE INFLATED

FLOWCHART PSEUDOCODE

page, 132
80S6 PROGRAM
ABSTRACT program adds an inflation factor to a series
of prices in memory. It copies the new price
over the old price
REGISTERS USED DS, CS, AX, BX, CX
PORTS USED : None
PROCEDURES None used
ARRAYS HERE SEGMENT
COST DB 20H, 28H , 15H, 26H, 19H, 27H, 16H, 29H
PRICES DB 36H, 55H , 27H, <t2H, 38H, <+lH, 29H, 59H
ARRAYS_HERE ENDS

CODE HERE SEGMENT


ASSUME CS CODE_HERE, DS : ARRAYS_HERE
MOV AX, ARRAYS_HERE
MOV DS, AX initialize data segment
LEA BX, PRICES initialize pointer
MOV CX, 0008H initialize counter
DO NEXT: MOV AL, cbx: copy a price to AL
ADD AL, 03H add inflation factor
DAA make sure result is BCD
MOV CBX] , AL copy result back to memory
INC BX point to next price
DEC Cx decrement counter
JNZ DO NEXT if not last, go get next
CODE HERE ENDS
END

90 CHAPTER FOUR
page , 1 32
8086 PROGRAM
ABSTRACT Program adds a profit factor to each element in
a COST array and puts the result in sr\ array
called PRICES
REGISTERS USED DS, CS, AX, BX, CX
PORTS USED None
PROCEDURES None used

ARRAYS_HERE SEGMENT
COST DB 20H, 88H, 15H. 26H, 19H, 87H, 1 6H , E9H
PRICES DB 8 DUP(O)
ARRAYS_HERE ENDS

PROFIT EQU 15H ; profit = 15 cents

CODE HERE SEGMENT


ASSUME CS:CODE HERE DS:ARRAYS_HERE

MOV AX , ARRAYS HERE ; initialize data segment


MOV DS, AX
MOV CX , 0008H initialize counter
MOV BX , OOOOH initialize pointer
DO NEXT MOV AL, COSTLBX] point to element in COST
ADD AL PROFIT add the profit to COST
DAA decimal adjust result
MOV PRICESCBX3, AL store result in PRICES
INC BX point to next element
in the ar r ays
DEC CX decrement the counter
JNZ DO NEXT if not last, do again
CODE HERE ENDS
END

FIGURE 4-15 (continued).

values specified in the DB statement. The statement.


PRICES DB 36H,55H,27H,42H,38H,41H,29H,59H, sets up
another 8-element array of bytes and gives it the name
PRICES. The eight memory locations will be loaded with
the specified values when the assembled program is
loaded into memory. Figure 4-16 shows how these two
arrays will be arranged in memory. Note that the name
BX = OFFSET OF DESIRED
of the array represents the displacement or offset of the ELEMENT IN PRICES
first element of the array from the start of the data seg-
ment. START OF ARRAY PRICES

The first two instructions. MOV AX, ARRAYS HERE


and MOV DS, AX initialize the data segment register as
was described for the example program in Figure 3-10.
The LEA mnemonic in the next instruction stands for DISPLACEMENT OF START
OF ARRAY PRICES
load effective address. An effective address, remember.
is the number of bytes from the start of a segment to the
desired data item. The instruction LEA BX, PRICES loads
the displacement of the first element of PRICES into the ARRAYS_HERE
SEGMENT BASE — START OF ARRAY COST
BX register. A displacement contained in a register is
DS = 3400H
usually referred to as an offset. If you take another look
at the data structure for this program in Figure 4- 16 you
should see that the offset of PRICES is 0008H. There- FIGURE 4-16 Data arrangement in memory for "inflate
fore, the
LEA BX, PRICES instruction will load BX with prices" program.

808b ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES— PART 1 91


0008H. We say that BX is a pointer to an element in will automatically make this adjustment for us. DAA will
PRICKS. We will soon show you how this pointer is used adjust the 2CH by adding six to the lower nibble and the
to indicate which price we want to operate on at a given carr\' produced to the upper nibble. The result of this in
time in the program. The next instruction, MOV CX, AL will be 32H which is the result we want from adding
0008H. loads the CX register with the number of prices 03 to 29. The DAA instruction only works on the AL reg-
in the array. We use this register as a counter to keep ister. For
further examples of DAA operation, consult
track of how many prices we have operated on. After we the DAA instruction description in Chapter 6.
operate on each price, we decrement the counter by one. The INC BX instruction adds 1 to the number in BX.
When the counter reaches zero, we know that we have BX now contains the effective address or offset of the
opei ated on all of the prices. next price in the array. We like to say that BX now points
The MOV AL, |BX] instruction copies one of the prices to the next element in the array. The DEC CX instruction
from memory to the AL register. Remember, the 8086 decrements the count we set up in the CX register by 1.
produces the physical address for accessing data in If CX contains 0 after this decrement, the zero flag will
memory by shifting the contents of a segment register be set to a 1 . The |NZ DO NEXT checks the zero flag. If it
four bit positions left and adding an effective address. finds the zero Hag set, it just passes execution out of the
EA. to the result. A section in Chapter 3 showed you structure to the next mainline instruction. If it finds the
how the effective address could be specified directly in zero Hag not set. the JNZ instruction will cause a jump to
the instruction with either a name or a number. The the label DO NEXT. Execution will repeat the sequence
instructions MOV AX, MULTIPLICAND and MOV AX, of instructions between the label and the |NZ instruc-
DS:WORD PTR [0000H] are examples of this addressing tion until CX is counted down to zero. Each time
mode. For the instruction MOV AL, [BX] the effective through the loop. BX will be incremented to point to the
address is contained in the BX register where we put it next price in the array.
with the fEA instruction above. The first time this in- Using a pointer to access data items in memory is a
struction executes.
BX will contain 0008H. the effective powerful technique that you will want to use in your
address or offset of the first price in the array. There- programs. Figure 4-15d shows another example. Here
fore, first
the price will be copied into AL. To produce the we want to add a profit of 15 cents to each element of an
physical memory address the 8086 will shift the con- array called COST and put the result in the correspond-
tentsthe
of data segment register four bit positions left ing element of an array called PRICES. We first initialize
and add this 0008H to the result. BX as a pointer to the first element of each array with
The next instruction ADD AL, 03H adds the immediate MOVBX. 000H. The instruction MOVAL. COST[BX] will
number 03H to the contents of the AL register. The bi- copy the first cost value into AL. The effective address
nary resultof the addition will be left in AL. We want the for this instruction will be produced by adding the dis-
prices in the array to be in BCD form, so we have to placement represented
by the name COST to the con-
make sure the result is adjusted to be a legal BCD num- tentsBX.
of Likewise, the instruction MOV PRICES1BX],
ber. For
example, if we add 03 to 29 the result in AL will AL copies the result of the addition to the first element
be 2C. Most people would not understand this as a price of PRICES. When BX is incremented. COST[BX] and
so we have to adjust the result to the desired BCD num- PRICESIBX] will each access the next element in the
ber. TheDecimal Adjust after Addition instruction DAA array. A programmer familiar with higher level lan-

SINGLE INDEX DOUBLE INDEX

1 Bv I
OR

ENCODED
1 BP [
IN THE -< OR
INSTRUCTION
1 s, I
0 R

1 o, h
EXPLICIT
IN THE
INSTRUCTION

ASSUMED
UNLESS
OVERRIDDEN
BY PREFIX

H PHYSICAL ADDR

FIGURE 4-17 Summary oi 8086 addressing modes.

92 c HAPTERFOUR
SEGMENT BASE

Name PATIENTS represents displacement of


start of array of records from segment base

PATIENTS ; array of patient records starts here

RECORD 1
TV N. BEER
132"+ Down Street
Portland, OR 97219
2/15/^5
2^t7 lb
S327.56

BX holds offset of - — > RECORD 2


desired record in array IN A. RUNNER
13733 S.W. Knaus Rd

Lake Oswego, OR 9730<+


6/30/^1
l<+5 lb
SI holds offset of > $0.00
desired field in record
RECORD 3

FIGURE 4-18 Use ot double indexed addressing mode.

guages would probably say that BX is being used as an effective address, the physical address will be produced
array index. The 8086 has several registers which can by adding the effective address to the data segment base
be used to index or to point to data in memory. in DS. When BP is used to contain all or part of the effec-
Figure 4-17 summarizes all the ways you can tell the tive address, the physical address will be produced by
8086 to calculate an effective address and a physical adding the effective address to the stack segment base
address for accessing data in memory. In all cases the in SS. For any of these four, you can use a segment over-
physical address is generated by adding an effective ride prefix
to tell the 8086 to add (he effective address to
address to one of the segment bases, CS. SS. DS, or ES. some other segment base. The instruction MOV AL,
The effective address can be a direct displacement speci- CS:[BX] tells the 8086 to produce a physical memory
fied directlyin the instruction as, for example. MOV AX, address by adding the offset in BX to the code segment
MULTIPLIER. The effective address or offset can be speci- base instead of to the data segment base. An exception
fiedbe
to in a register, as in the instruction MOV AL, to this is that with a special group of instructions called
[BX]. Also the effective address can be specified to be the siring instructions an offset in DI will always be added to
contents of a register plus a displacement in the in- the extra segment base in ES to produce the physical
struction.
instruction
The MOV AX, PRICES[BX] is an address.
example. For this example, PRICES represents the dis-
placement
the start
of of the array from the segment
base and BX represents the number of the element in Summary of REPEAT— UNTIL Implementation
the array that we want to access. The effective address of The preceding sections have shown two examples of
the desired element then is the sum of these two. implementing the REPEAT— UNTIL structure. In the
For working with more complex data structures such first example we repeated a series of actions until a con-
as records, you can tell the 8086 to compute an effective dition was
found to be present. Specifically, we kept
address by adding the contents of BX or BP plus the looking and testing until we found a strobe signal high.
contents of SI or DI plus an 8-bit or a 16-bit displace- In the second. We used a conditional jump instruction
ment contained in the instruction. The instruction to check the condition of a flag and make the decision
MOV AL, PATIENTS [BX]|SI] is an example of this address- whether to repeat the series of actions or not.
ing mode.Figure 4-18 shows an example of why you In the second REPEAT — UNTIL example we intro-
might want an addressing mode such as this to access ducedconcept
the of using a register as a pointer to a
the balance due field in some medical records in mem- data element in an array. We also showed in this exam-
ory. We
will illustrate the use of some of these more com- ple howto make a program repeat a sequence of instruc-
plex addressing modes in later chapters. tions
specific
a number of times. To do this we load the
When BX, SI, or DI is used to contain all or part of the desired number of repeats in a register or memory loca-

808b ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES— PART 1 93


tion. Each time we execute the series of instructions, we
LOOP Loop until CX = 0
decrement this counter by one. When the count in the
register is decremented to zero, the zero flag will be set.
LOOPE/LOOPZ Loop if zero flag set
and CX < > 0
Again we use a conditional jump instruction to check
this flag and to decide whether to repeat the instruction
LOOPNE/LOOPNZ Loop if zero flag not set
and CX < > 0
sequence in the loop again.
ICXZ lump it CX = 0
The need for performing a sequence of actions a speci-
fied number of times in a program is so common that
FIGURE 4-19 8086 LOOP instructions.
some programming languages use a specific structure
to express it. This structure, derived from the basic
WHILE— DO, is called the FOR— DO. It has the form tion, for example, to continue a sequence of operations
for a specified number of times or until compared values
FOR count 1 to count = n DO were no longer equal.
Action The LOOPNE/LOOPNZ label instruction decrements
Action the CX register by one. If CX is not zero and the zero flag
is not set. this instruction will cause a jump to the spec-
where n is the number of times we want to do the se- ified label.In other words, execution will exit from the
quence
actions.
of In assembly language you will usually loop if CX is equal to zero or the zero flag is set. This
implement this by loading n into a register and count- instruction is useful when you want to execute a se-
ingdown
it as shown in Figure 4-15c. quence
instructions
of a fixed number of times or until
The common need to repeat a sequence of actions a two values are equal. An example might be a program to
specified number of times also led the designers of the read data from a disk. We typically write this type of pro-
8086 to give it a group of instructions which make this gram that
so it attempts to read the data until the
easier for you. These instructions are the LOOP instruc- checksums are equal or until 10 unsuccessful attempts
tions whichwe discuss in the next section. have been made to read the disk.
Another instruction often listed with the LOOP in-
structions
the ]CXZis label instruction. This instruc-
The 8086 LOOP Instructions
tion does not affect the CX register. It simply does a
short jump to the specified label if the CX register is
INSTRUCTION OPERATION AND EXAMPLES
zero. The )CXZ instruction checks the CX register di-
The LOOP instructions have the format LOOP label. rectly,
doesit not check the zero flag.
These instructions combine two operations in each in- In summary then, the LOOP instructions are useful
struction.
first
The operation is to decrement the CX for implementing the REPEAT — UNTIL structure for
register by one. The second operation is to check the CX those special cases where we want to do a series of ac-
register and, in some cases, also the zero flag to decide tions
fixed
a number of times or until the zero flag
whether to do a jump to the specified label. As with the changes state. LOOP instructions incorporate two oper-
previously described conditional jump instructions, the ations
eachin instruction; therefore, they are somewhat
LOOP instructions can only do short jumps. This means more efficient than single instructions to do the same
that the destination label must be in the range of - 128 job. The 8086 string instructions, which we discuss in a
bytes to + 127 bytes from the instruction after the LOOP later section of this chapter, incorporate even more op-
instruction. Figure 4-19 summarizes the LOOP instruc- erations
single
in instructions. Some of the string in-
tions. Instruction mnemonics separated by a "/" repre- structions
implement
can an entire REPEAT — UNTIL
sent the
same instruction. NE in the mnemonics stands structure with a single instruction. In the next section,
for not equal, and NZ in the mnemonics stands for not we introduce you to instruction timing and show how
zero. Also shown in the figure is the conditionls) the LOOP instruction can be used to produce a delay
checked by each instruction to decide if it should do the between the execution of instructions.
jump.
The basic LOOP-label instruction will decrement the
INSTRUCTION TIMING AND DELAY LOOPS
CX register by 1 and jump to the specified label if the CX
register is not 0. The instruction LOOP DO NEXT, for The rate at which 8086 instructions are executed is de-
example, could be used in place of the DEC CX and the termined
a crystal-controlled
by clock with a frequency
JNZ DO NEXT instructions in the program in Figure of a few megahertz. Each instruction takes a certain
4- 15c. number of clock cycles to execute. The MOV register,
The LOOP instructions decrement the CX register, register instruction, for example, requires 2 clock cycles
but do not affect the zero flag. This leaves the zero flag to execute and the DAA instruction requires 4 clock cy-
available for other tests. The LOOPE/LOOPZ label in- cles. The
JNZ instruction requires 16 clock cycles if it
struction
decrement
will the CX register by one and does the jump and only 4 clock cycles if it doesn't do the
jump to the specified label if CX is not equal to zero and jump. A table in Appendix B shows the number of clock
if the zero flag is set to a one. In other words program cycles required by each instruction. Using the numbers
execution will exit from the repeat loop if CX has been in this table you can calculate how long it takes to exe-
decremented down to zero or the zero flag is not set. cute instruction
an or series of instructions. For exam-
This instruction might be used after a compare instruc- ple,
weif are running an 8086 with a 5-MHz clock, then

94 CHAPTER FOUR
each clock cycle lakes ' , Mil/ or <>2 us An instruction cycle then is ! , Mil/ oi 0 2 /us Now. suppose thai you
which lakes I clock cycles then will lake 4 clock cycles \ want io create a delay ol I ins oi 1000 /'s with a delay
0.2 ^is clock cycle or 0.8 (jls to execute loop ii you divide the mi to //-, desired by the ().'.'. //s pei
A common programming problem is the need to intro- elm k cycle, you gel the number ol clock cycles required
duce
(lel.i\
a between the execution ol two Instructions. io produce the desired delay. Foi this example then you
For example, we mighl want to read a data value from a need a total ol 5000 I 1000 0.2) clock cycles to produce
port, wail I ins. and then read the port again A latei ihc desired delaj
chapter will show how you can use interrupts to mark The nexl step is to write the number ol clock i yi les
off time Intervals. Here we show von how to use a pro required foi each instruction nexl to thai instru< tlon as
gram loop to do it. shown in Figure 1 20a. Then look at the program to de-
lhc basic principle is to execute an instruction or se- termine which
instructions get executed only once. The
riesinstructions
of over and over until the desired time number ol clock cycles for these instructions will only
has elapsed. Figure 4-20a shows a program we might contribute to lhc total once. Instructions which only
use to do this. The MOV CX, N instruction loads the ( X enter once in the calculation are often called overhead
register with the number of times we want to repeat the We will represent the number ol cycles ol overhead with
delay loop. Just ahead we show you how to calculate this the symbol (',,. In Figure 4 20a the only instruction
number lor a desired amount ol delay. The NOP instruc- which executes just once- is MOV CX, N. which takes 4
tions next in the program are not required. The clock cycles. For this example then. ('„ is 4.
KILL TIME label could be right in front of the LOOP in- Now determine how many clock cycles arc required lor
struction.
this case,
In only the LOOP instruction would the loop. The two NOPs in the loop require a total of 6
be repeated. We put the NOPs in to show you how you clock cycles. The LOOP instruction requires 17 clock
can get more delay by extending the time it takes to exe- cycles if it does the jump back to KILL TIME, but it re-
cute the
loop. The LOOP KILL TIME instruction will dec- quires only
5 clock cycles when it exits the loop. The
rement CXand. if it is not down to zero yet. do a jump to jump takes longer because the instruction byte queue
the label KILL TIME. The program then will execute the has to be reloaded starting from the new address For all
two NOP instructions and the LOOP instruction over but the very last time through the- loop it will require 17
and over until CX is counted down to zero. The number clock cycles for the LOOP instruction. Therefore, you
in CX will determine how long this takes. Here's how can use 17 as the number of cycles for the LOOP in-
you determine the value to put in CX for a given amount struction
compensate
and later for the fact that for the
of delay. last time it uses 12 cycles less. For the example program
First you calculate the number of clock cycles needed the number of cycles per loop, C,_, is 6 + 17 or 23. The
to produce the desired delay. If you are running your total number of clock cycles delayed by the loop is equal
8086 with a 5-MHz clock, then the time for each clock to the number of times the loop executes multiplied by

C 1 ock Cyc 1 es
MOV CX, N <+ = C
KILL_TIME: NOP 3
NOP 3 = Cl
LOOP KILL TIME 17/5

12
CQ + N(CL)

5000 - ^ + 12
CT " C0 + 1E?
218 = 0D9H
23

FIGURE 4-20 Delay loop program and calculations, (a) Program.


(b) Calculations.

8086 ASSEMBLYLANGUAGEPROGRAMMING TECHNIQUES—PART I 95


the time per loop. To be somewhat more accurate you ing for
a given word or phrase. The 8086 Compare
can subtract the 12 cycles that were not used when the String instruction, CMPS, allows you to do this easily.
last LOOP instruction executed. The total number of Let's see how these string instructions work.
clock cycles required for the example program to execute
is C0 N(CJ - 12. Set this equal to the number of clock
MOVING A STRING
cycles of delay you want. 5000 for this example, and
solve the result for N. Figure 4-20b shows how this is Suppose that we have a string of ASCII characters in
done. The resultant value for N is 218 decimal or 0D9H. successive memory locations starting at offset 2000H in
This is the number of times you want the loop to repeat, the data segment, and we want to move this string to an
so this is the value of N that you will load into CX before offset of 2400H in the data segment. Figure 4-2 la
entering the loop. shows the basic pseudocode for this operation. When we
With the simple relationship shown in Figure 4-20b. start thinking about how we can implement this algo-
you can determine the value of JV to put in a delay loop rithmassembly
in language, several points come to
you write, or you can determine the time a delay loop mind. We need a pointer to the source string to keep
written by someone else will take to execute. track of which string element we are moving at a given
If you can't get a long enough delay by counting down time. This is the same reason we needed a pointer in the
a single register or memory location, you can nest delay price-fixing program in Figure 4- 15c. We use the source
loops. An example of this nesting is: index register for this pointer. SI will hold the offset of
the byte that we are moving at a given time. We also need
jnunber of states a pointer to the location where we are moving string ele-
MOV BX.C0UHT1 J4 ments The
to. destination index register DI is used to
CNTDN1: HOV CX, C0UNT2 ;<t x COUNT1
hold the offset of the location where a byte is being
moved to at a given time. Another need is for a counter
CNTDN2: LOOP CNTDN2 ;< (17XC0UNT2)-12 (COUNT1
to keep track of how many string bytes have been
DEC ex ;2(C0UNT1)
moved so we can determine when we have moved all of
JNZ CNTDN1 ;16(C0UNT1)-12 the string. We use the CX register as a counter for
string operations. Having these pieces in mind we
The principle here is to load CX with COUNT2 and count can expand the pseudocode for the problem as shown
CX down COUNT 1 times. To determine the number of in Figure 4-2 lb. We often describe an algorithm
states that this program section will take to execute, in general terms at first and then expand sections
observe that the LOOP instruction will execute COUNT2 as needed to help us see how the algorithm is im-
times for each time CX is loaded with COUNT 1. The plemented
a specific
in language. In the expanded
total number of states then is COUNT 1 times the num- version in Figure 4-2 1 b. you can see that we need
ber of
states for the last four instructions plus 4. for the to initialize the two pointers and the counter. The
MOV BX, COUNT! instruction. The best way to ap- REPEAT — UNTIL loop consists of moving a byte, incre-
proach getting
values for the two unknowns. COUNT1 menting
pointers
the to point to the source and destina-
and COUNT2, is to choose a value such as FFFFH for tion for
the next byte, and decrementing the counter so
COUNT2 and then solve for the value of COUNT 1 . A cou- we can see if all of the bytes have been moved.
ple oftries should get reasonable values for both As it turns out, the single 8086 string instruction.
COUNT 1 and COUNT2. MOVSB. will perform all of the actions in the REPEAT —
Delay loops are a very common use of the REPEAT — UNTIL loop. In other words the MOVSB instruction will
UNTIL structure. The next section describes the 8086 copy a byte from the location pointed to by the SI regis-
string instructions which are often used in REPEAT — ter to
a location pointed to by the DI register. It will then
UNTIL structures. automatically increment SI to point to the next source
location, increment DI to point to the next destination
location. Actually, as we will show you soon, we can
specify whether we want SI and DI to increment or dec-
The 8086 String Instructions rement.
we addIf a special prefix called the repeat prefix
in front of the MOVSB instruction, the MOVSB instruc-
INTRODUCTION AND OPERATION
tion willbe repeated and CX decremented until CX is
A string is a series of bytes or words stored in successive counted down to zero. In other words it will repeat the
memory locations. Often a string consists of a series of MOVSB instruction until the entire string is copied to
ASCII character codes. When you use a word processor the destination location.
or text-editor program, you are actually creating a string Figure 4-2 lc shows the program instructions to move
of this sort as you type in characters. One important our string of bytes. The first three instructions in the
feature of a word processor is the ability to move a sen- program initialize the data segment register and the
tence
group
or of sentences from one place in the text to extra segment register. After that we load the SI register
another. Doing this involves moving a string of ASCII with 2000H so that it points to the start of the source
characters from one place in memory to another. The string. We then load the DI register with 2400H so that
8086 Move String instruction. MOVS. allows you to do it points to the first address of the desired destination.
this very easily. Another important feature of mosi word Actually, for string instructions, the offset in DI is added
processors is the ability to search through the text look- to the extra segment to produce the physical address.

96 CHAPTER FOUR
However, it DS and ES are Initialized with the iam< 1)1 However, with the repeal prefix, REP, In front ol the
value as we did with the first three instructions in the MOVSB instruction as shown, CX will be decremented
program, then si and Dl will both be added to the same and the instruction will execute ovei and ovei again
segment base Next we load the CX registei with the until the CX registei is counted down to zero. When the
number ol bytes In the string we are moving. CX will program is coded, the 8-bil code for the REP prefix,
tune i ion as a counter to keep track ol how many string 1 1 1 10010, is put in the memory location before the code
bytes have been moved at any given time. Finally, we for the M< )VSB Instruc l. 10100100. Alter the M< >VSB
make the direction flag a 0 with the Cleai Direction Flag instruction is finished, SI will be pointing to the loca-
instruction, ( IP l'his will cause both si and l>l to be tion alterthe lasi sou ice si i ing byte, Dl will be pointing
automatically incremented after a string byte is moved, to the location after the last destination address, and ( \
II the di reel ion flag is set with the Ml) Instruction, then will be /ei o
SI and Dl will be automatically decremented after each II ie M< )VSW instruction can be used to move a string
string byte is moved. Now when the Move String Byte ol winds Depend mt; on the state ol the direction flag, SI
instruction, MOVSB, executes, a byte pointed to bj si and Dl will automatically be incremented or decre-
will be copied to the location pointed to by 1)1. SI and 1)l mented
twoby alter each move. ( X will be decremented
will be automatically incremented to point to the next by one aftei each word move with the REP prefix so CX
source and to the next destination. The count register should be initialized with the number ol words in the
Will be automatically decremented. The MOVSB instruc- string.
tion itseli
by will just copy one byte and update SI and

REPEAT
MOVE BYTE FROM SOURCE STRING TO DESTINATION STRING
UNTIL ALL BYTES MOVED

(a)

INITIALIZE SOURCE POINTER, SI


INITIALIZE DESTINATION POINTER, DI
INITIALIZE COUNTER, CX

REPEAT
COPY BYTE FROM SOURCE TO DESTINATION
INCREMENT SOURCE POINTER, SI
INCREMENT DESTINATION POINTER, DI
DECREMENT COUNTER, CX
UNTIL CX = O

t/.i

CODE HERE SEGMENT


ASSUME CS:CODE HERE , DS: STRINGS .HERE, ES:
1 STRINGS HERE
MOV AX , 000' '%
MOV DS, AX ; initialize DS
MOV ES, AX ; initialize E S
MOV SI , E000H : initialize SI
MOV DI , 24-00H ; initialize D I
MOV CX , 0080H ; initialize counter
128 bytes in string
CLD : increment SI & DI
REP MOVSB ; move one byte

FIGURE 4-21 Program for moving a string from one location to another in
memory, (a) First-version pseudocode, (b) Expanded-version pseudocode.
(c) Assembly language.

808b ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES— PART 1 97


STRING INSTRUCTIONS OVERVIEW C START)
A section in Chapter 3 shows a list of the string instruc-
tions with
short descriptions of their operations. Take a
look at this list to give you an overview of this group of
instructions, and then go on to the second string in-
struction example
which follows. Consult the detailed
descriptions of the individual instructions in Chapter 6
for further information and short program examples for
each

USING THE COMPARE STRING BYTE TO CHECK


A PASSWORD

For this program example suppose that we want to com-


pare
password
a entered by a person who wants to use
the computer with the correct password stored in mem-
ory.
theII passwords do not match, we want to sound an
alarm. If the passwords match, we want to continue on
with the mainline program. Figure 4-22 shows how we
might represent the algorithm for this with a flowchart
and with pseudocode. Note that we want to terminate V. EQUAL S"
^S^ ? —
the REPEAT — UNTIL when either the compared bytes
do not match, or when we are at the end ol the string. Tno
We then use an IF — THEN structure to sound the alarm
SOUND
if the compared strings were not equal at any point. If ALARM
the strings match, the IF — THEN just directs execution
on to the main program. i
To implement this algorithm in assembly language. C STOP )
we probably would first expand the basic structures as
we did for the previous string example in Figure 4-21.
Figure 4-22c shows how we might do this expansion.
The first action in the expanded algorithm is to initial-
NEXT MAINLINE
ize the
port device for output. We need to have an output INSTRUCTION
port because we will turn on the alarm by outputting a 1
to the alarm control circuit. You can see that we need a
pointer to each siring and a counter to keep track of how
many string elements have been compared. If you use SI
REPEAT
and 1)1 for the pointers and CX for the counter, then the COMPARE SOURCE BYTE WITH DESTINATION BYTE
8086 Compare String Bytes instruction. CMPSB. will UNTIL (BYTES NOT EQUAL) OR (END OF STRING)
IF BYTES NOT EQUAL THEN
implement all of the actions between REPEAT and SOUND ALARM
UNTIL. If we put the correct repeat prefix in front of this STOP
instruction, the single instruction statement will imple- DO NEXT MAINLINE INSTRUCTION

ment entire
the REPEAT— UNTIL structure. lb)
Figure 4-23 reviews some old concepts, introduces a
few new ones, and shows how this program can be done
INITIALIZE PORT DEVICE FOR OUTPUT
in assembly language. First let's look at the data struc-
INITIALIZE SOURCE POINTER — SI
ture for
this program. The statement PASSWORD DB INITIALIZE DESTINATION POINTER — Dl
'FAILSAH scis aside 8 bytes of memory and gives the INITIALIZE COUNTER — CX
REPEAT
first memory location the name PASSWORD. This state- COMPARE SOURCE BYTE WITH DESTINATION BYTE
ment also
initializes (he eight memory locations with INCREMENT SOURCE POINTER

the ASCII (odes lor the letters FAILSAFE. The single INCREMENT DESTINATION POINTER
DECREMENT COUNTER
quotes around FAILSAFE tell the assembler to put the UNTIL (STRING BYTES NOT EQUAL) OR (CX = 0)
ASCII codes for the letters of this word in successive IF STRING BYTES NOT EQUAL THEN
SOUND ALARM
memory locations. For FAILSAFE the ASCII codes will be
STOP
46H, 41H, 49H, 4CH, 53H. 41H. 46H. 45H. The state- DO NEXT MAINLINE INSTRUCTION
ment INPUT
WORD DB 8 DUP(?) will set aside eight
(« I
memory locations and assign the name INPUT WORD to
the first location. The DUP(?) in the statement tells the
assembler not to initialize these eight locations. We as- FIGURE 4-22 Flowchart and pseudocode for comparing
sume that
another program section will load these loca- strings program, (a) Flowchart, (b) Initial pseudocode.
tions Willi ASCII codes read from the keyboard. (c) Expanded pseudocode.

<M (. IIAI'TIK FOUR


Now let's look at the code segmenl section ol the pro gramming problems
at the end ol the chapter Will give
gram, The ASSUME statement tells the assemblei that you pi, it tlce with these. The next section here gives you
the instructions will be In t in- segment COI >E 1 IERE. li some bints on how to debug the programs that you
also tells the assembler that any references to the data write.
segment or to the extra segment will mean the segment
DMA HERE. We have to tell the assembler what to as
Mime about the extra segment, because with string in- DEBUGGING ASSEMBLY LANGUAGE
,iiiii 11. His an offset in 1 >l is added to the extra segmenl
PROGRAMS
base to produce the physical address.
The next three VtO\ statements in the program ini- So i.u in this book we have tried to show you ilic tools
tializedata
the and extra segment registers. Since we and techniques used to write assembly language pro
initialize l)S and ES with the same values, both SI and grams By now you should be writing some progi ims ol
Dl will point to locations m the segment DATA HERE. your own. so we need to give Mill a lew hints on how to
The next three instructions initialize port P2B ol an debug your programs il they don't work correctly the
SDK 86 board as an output port. Inst tune you try to run them.
LEA SI, PASSWt )RD loads the effective address oi offsel I In lust technique you use when you hit a difficult
of the start ol the FAILSAFE string into the SI register, tO-find problem in either hardware or software is the
Since PASSWORD is the first data item in the segment Five Minnie Rule. This rule says "You gel 5 minutes to
DATA HERE. SI will be loaded with 0000H. LEA Dl, freak out and mumble about changing vocations, then
INPUT WORD loads the effective address or offset of the you have to cope with the problem in a systemat ic man
start of the INPUT' WORD string into the Dl register ner." What this means is step back from the problem,
Since the offset of INPUT WORD is 0008H, Dl will be collect your wits, and think out a systematic series ol
loaded with this value. The MOV CX, 08H statement ini- steps to find the solution. We have seen many techni-
tializes
with
CX the number of bytes in the string. The cians waste
a lot of valuable time randomly poking and
clear direction flat* instruction tells the 8086 to auto- probing to try to find the cause ol a problem. Here is a
matically increment
SI and Dl after two string bytes are list of additional techniques you may find useful in writ-
compared. ing anddebugging your programs.
The CMPSB instruction will compare the byte pointed
to by SI with the byte pointed to by Dl and set the flags 1. Very carefully define the problem you are trying to
according to the result. It will also increment the point- solve with the program and work out the best algo-
ers, and
SI Dl, to point to the next string elements, and rithm can.
you
decrement the counter. CX, to indicate that two string
elements have been compared. The REPE prefix in front 2. If the program consists of several parts, write, test
of this instruction tells the 8086 to repeat the CMPSB and debug each part individually then add parts one
instruction if the compared bytes were equal and CX is at a time.
not decremented down to zero yet. When the instruction
is coded, the code for this prefix. 1 1 1 1001 1. will be put 3. If a program or program section does not work, first
in memory before the code for the CMPSB instruction, recheck the algorithm to make sure it really does
10100110. what you want it to. You might have someone else
If the zero flag is not set when execution leaves look at it also. Another person may quickly spot an
the repeat loop then we know that the two strings are error you have overlooked 17 times.
not equal. This means that the password entered was
not valid so we want to sound an rlarm. The JNE 4. If the algorithm seems correct, check to make sure
SOUND J\LARM will check the zero flag and. if it is not that you have used the correct instructions to imple-
set. do a jump to the specified label. If the zero flag is ment algorithm.
the It is very easy to accidentally
set, indicating a valid password, then execution falls switch the operands in an instruction. You might,
through to the ]MP OK instruction. This IMP instruc- for example, write down the instruction MOV AX,
tion simply jumps over the instructions which sound the DX when the instruction you really want is MOV DX,
alarm and stops the computer. AX. Sometimes it helps to work out on paper the ef-
For this example we assume that the alarm control is fect that
a series of instructions will have on some
connected to the least-significant bit of port FFFAH and sample numbers. These predictions on paper can
that a 1 output to this bit turns on the alarm. The MOV later be compared with the actual results produced
AL, 01 instruction loads a 1 in the LSB of AL. The MOV when the program section runs.
DX, 0FFFAH instruction points DX at the port that the
alarm is connected to and the OUT DX, AL instruction 5. If you are hand coding your programs, this is the
copies this byte to port FFFAH. Finally, the HLT instruc- next place to check. It is very easy to get a bit wrong
tion stopsthe computer. An interrupt or reset will be when you construct the 8086 instruction codes.
required to get it started again. Also remember, when constructing instruction
As the preceding examples show, the string instruc- codes which contain addresses or displacements,
tions make
it very easy to implement some commonly that the low byte of the address or displacement is
needed REPEAT— UNTIL algorithms. Some of the pro- coded in before the high byte.

8086 ASSEMBLY LANGUAGE PROGRAMMING TECHNIQUES— PART 1 99


page , 1 32
;8086 PROGRAM
; ABSTRACT This program inputs a password and sounds an
! alarm if the password is incorrect
5REGISTERS USED: CS, DS, ES, AX, DX, CX, SI, DI
;PORTS USED FFFAH - alarm output port
PROCEDURES : None used

DATA_HERE SEGMENT
PASSWORD DB 'FAILSAFE'
INPUT_WORD DB S DUP ( ? ) ; space for user input
DATA HERE ENDS

CODE HERE SEGMENT


ASSUME CS-.CODE HERE, DS:DATA HERE, ES-.DATA HERE

MOV AX , DATA_HERE ; initialize data


MOV DS, AX ; extra segments
MOV ES, AX

MOV DX , OFFFEH set up port


MOV AL, 99H as an output port
OUT DX , AL

LEA SI , PASSWORD load source pointer


LEA DI , INPUT_WORD load destination pointer
MOV CX , 08H counter = password length
CLD increment DI &< SI
REPE CMPSB compare the two strings
JNE SOUND_ALARM not equal, sound alarm
JMP OK equal - continue
SOUND ALARM MOV AL, 01 to sound alarm, send
MOV DX , OFFFAH a 1 to the output
OUT DX , AL port whose address is
HLT in DX and HALT.
OK: NOP rest of program for user
whose password = FAILSAFE
CODE HERE ENDS
END

FIGURE 4-23 Assembly language program for comparing strings.

If you don't find a problem in the algorithm, instruc- executes one instruction and then stops execution.
tions,coding,
or now is the time to use debugger, You can then use the Examine Register and Exam-
monitor, or emulator tools to help you localize the ine Memorycommands to see if registers and mem-
problem. You could use these tools right from the ory contain the correct data at that point. If the re-
start, but by doing this it is easy to get lost in chas- sults are
correct at that point you can use the trace
ing lutsand not see the bigger picture of what is or single step command to execute the next instruc-
causing the program to fail. For short program sec- tion. Once
you have localized the problem to one or
tions,debugger
the or monitor trace and single-step two instructions, it is usually not too hard to find
functions may help you determine where the pro- out what is wrong. See the accompanying laboratory
gramnotis doing what you want it to do. The IBM manual instructions for using these functions.
PC Debugger Trace command displays the contents
of the registers after each instruction executes. After For longer programs, the single-step approach can
you run to a breakpoint then you can use the dump be somewhat tedious. Using breakpoints is often a
memory command to examine the contents ol the faster technique to narrow the source of a problem
memory. The SDK-86 board's Single Step command down to a small region. Most debuggers, monitors.

100 CHAPTER FOUR


and emulators allow you to specify both .1 starting the )NZ DO NEX1 instruction Perhaps you accidentally
address and an ending address In their "GO" com put the DO NEXT label nexl to the Mil ) \l , 03H instruc-
m. iiul. The SDK 86 monltoi GO command, for ex- tion insteadof next to the M( )V Al , [BX] instruction. Or.
ample,the
has formal GO .nidi ess. breakpoint ad- ii von are hand coding, perhaps you calculated the dis
dress rhe
GO command for the IBM PC debugger placemenl foi the IN/ Instruction incorrectlj
has the foi mal (I address address, When you give It helps youi frustration level ii you make ,1 game ol
these commands, execution will starl .11 die address thinking where to put breakpoints to track down tin
specified lust in the command and slop when it little bug that is messing up your program. With a little
reaches the address specified in the second position practice vou should soon develop an efficient debugging
in the roil in i.uid. Attn the program runs to a break algorithm ol your own using the specific tools a
point you can use the examine register and examine on your system
memory commands to check the results at that
point. Here's how we use breakpoints.
CHECKLIST OF IMPORTANT TERMS AND
CONCEPTS IN THIS CHAPTER
Instead of running the entire program, specify a
breakpoint so that execution stops some distance into II you do not remember any ol the terms or concepts in
the program. You can then check to see if the results are the following list, use the index to find them in the
correct at this point. II they are. you can run the pro- chapter.
gram againwith the breakpoint at a later address and
Defining a problem
check the results at that point. If the results are not cor-
rect, you
can move the breakpoint to an earlier point in Setting up a data structure
the program, run it again, and check if the results in
Making an initialization checklist
registers and memory are correct.
Suppose, tor example, you write a program such as Masking and moving nibbles using AND and OR
the price-fixing program in Figure 4-15c and it does not instructions
give the correct results. The first place to put a break-
Packed and unpacked BCD numbers
point might
be at the address of the ADD AL, 03 instruc-
tion. Incidentally, the instruction at the address where Conditional flags: CF. PF. AF. ZF. SF. OF
vou put the breakpoint does not get executed in most
systems. After the program runs to this breakpoint, you Jump instructions:
check to see if the data segment register, pointer regis- Unconditional
Direct and indirect within-segment near jumps
ter andcounter register were correctly initialized. You
can also see if the first price got copied into AL. If the Direct and indirect within-segment short jumps
Direct and indirect intersegment jumps
program works correctly to this point, you can run it
again with the breakpoint at the address of the JNZ Relocatable
DO_NEXT instruction. After the program executes to
this breakpoint you can check AL to see if the addition Conditional jumps
and decimal adjustment produced the results you pre- Fixed- and variable-port input/output
dicted.
the If8086 is working at all it will almost always
do operations such as this correctly, so recheck your Based and indexed addressing modes
predictions if you disagree with it. You can check the
Loop instruction
pointer in BX to see if it is pointing at the next price,
and you can check the count in CX to see if it has been Delay loop clock cycles
decremented as it should be. Also you can check to see if
String instructions
the adjusted price got put back in memory. If you have
not found the problem by now. the problem may be in Debugging — breakpoints, trace, single step

REVIEW QUESTIONS AND PROBLEMS


Describe the operation and results of each of the MOV AL, [BX]
following instructions, given the register contents Nl \l ADD AL, 02
shown in Figure 4-24. Include in your answer the DEC CL

physical address or register that each instruction |NZ NEXT


will get its operands from and the physical address MOV CX, 3FC2H
or register that each instruction will put the result COUNT DOWN: LOOP COUNT DOWN
in. Use the instruction descriptions in Chapter 6 to
help you. Assume that the instructions below are MOV CX, 100 ; length ot STRING 1
independent, not sequential unless listed together MOV SI, OFFSET STRING 1
under a letter. MOV Dl, OFFSET STRING J
a. ROL AX. CL d. ADD AX. [BX]|SI| CLD
b. IN AL. DX e. JMP 023AH REPMOVSB
c. MOV CX. [BX] ./'. JMP BX

8086 ASSEMBLY LANGUAGE PROCk, . '.MING TECHNIQUES— PART I 101


2. Construct the binary codes for the instructions of 6. Convert a packed BCD byte to two ASCII characters
Questions la through If. for the two BCD digits in the byte. For example,
given a BCD byte containing 57H (01010111 bi-
3. Predict the state of the six 8086 conditional flags
nary), produce
the two ASCII codes 35H and 37H.
after each of the following instructions or group of
instructions executes. Use the register contents 7. Compute the average of 4 bytes stored in an array
shown in Figure 4-24. Assume all flags are reset in memory.
before the instructions execute. Use the detailed
instruction descriptions in Chapter 6 to help you. 8. Compute the average of any number of bytes in an
a. MOV AL. AH c. ADD CL. DH array in memory. The number of bytes to be added
b. ADD BL. CL d. OR CX. BX is in the first byte of the array.

4. See if you can find any errors in the following in- 9. Add a 5-byte number in one array to a 5-byte num-
structions
groupsor of instructions. ber another
in array. Put the sum in another array.
a. CNTDOWN: MOV BL. 72H Put the state of the cam' flag in byte 6 of the array
DEC BL that contains the sum. The first value in each array
JNZ CNTDOWN is the least-significant byte of that number. HINT:
b. REP ADD AL. 07 d. ADD CX. AL See Figure 4-15d.
C. JMP BL e. DI\r AX. BX
10. An 8086-based process control system outputs a
measured Fahrenheit temperature to a display on
5. a. Write an algorithm for a program which adds a
its front panel. You need to write a short program
byte number from one memory location to a which converts the Fahrenheit temperature to Cel-
byte from the next memory location, puts the sius that
so the system can be sold in Europe. The
sum in a third memory location, and saves the relationship between Fahrenheit and Celsius is:
state of the carry flag in the least-significant bit C = (F - 32)5/9. The Fahrenheit temperature will
of a fourth memory location. Mask the upper 7 always be in the range of 50" to 250°. Round the
bits of the memory location where the cam' is Celsius value to the nearest degree.
stored.
b. Write an 8086 assembly language program for 11. An ASCII keyboard outputs parallel ASCII + parity
this algorithm. HINTS: Set up data declara- to port FFF8H of an SDK-86 board. The keyboard
tions similar
to those in Figure 3-10. Use a ro- also outputs a strobe to the least-significant bit
tate instruction to get the carry flag state into ID0) of port FFFAH. (See Figure 4-13.) When you
the LSB of a register or memory location. press a key. the keyboard outputs the ASCII code
c. What additional instructions would you have for the pressed key on the eight parallel lines and
to add to this program so that it correctly adds outputs a strobe pulse high for 1 ms. You want to
2 BCD bytes? poll the strobe over and over until you find it high.
Then you want to read in the ASCII code, mask the
For each of the following programming problems, draw parity bit (D7). and store the ASCII code in an array
a flowchart or write the pseudocode for an algorithm to in memory. Next you want to poll the strobe over
solve the problem. Then write an 8086 assembly lan- and over again until you find it low. When you find
guage programto implement the algorithm. If you have the strobe has gone low. check to see if you have
an 8086 system available, enter and assemble your read in 10 characters yet. If not. then go back and
source program, then load the object code for the pro- wait for the strobe to go high again. If 10 charac-
gram into
memory so you can run and test it. If the pro- ters have
been read in. stop.
gram does
not work correctly, use the approach de-
scribed
the inlast section of this chapter to help you 12. a. Write a delay loop which produces a delay of
debug it. 500 f±s on an 8086 with an 8-MHz clock.

AH AL BH BL
AX Ah 07 B> ^ B3

CH CL DH DL
C K 00 02 la FF FA

SP == FFFF CS = sooo
BP == 0009 DS = 3000
SI == <4200 SS =
DI == <+300 ES = 3000

FIGURE 4-24 Figure for Chapter 4 problems.

102 CHAPTERFOUR
Write a chilli program which outputs a I kHz b. Move the string containing youi name up four
square wave on DO ol porl 11 FAH rhe basic addresses In memory Considei whether the
principle here is to output a high, wail 500 fis pointers should he incremented 01 decre
(0.5 ms), output a low, wait 500 /us and output mented after each Inn is moved In order to
a high, etc Remembei that, before you can keep any needed byte from being written over.
output to a port device, you must first initialize HINT: Initialize Dl with die value ol SI • 4.
it as in Figure 1 12a It you connect .1 buffer
Scan a string ol so characters, looking foi a 1 ai
such as that shown in Figure 8-22 and a
riage return (0DH). II a carriage return is found,
speaker to DO ol the port, you will be able to
put the leniith ol the string up to the carriage re-
hear the lone produced,
turnAI..
in II no carriage return is found, put 50H
ISO decimal) In AL.
13. a. Move a string containing your name in the
form "Charlie T Tuna" from one string loca- Given a siring containing your name In the form
tionmemory
m to a new string location named "Charlie T. Tuna", put the characters in a second
NEW HOME which Is just above the initial lo- string called LAST FIRST in the order "Tuna Char-
cation. lie T".

8086 ASSEMBtY LANGUAGE PROGRAMMING TECHNIQUES— PART I 103


CHAPTER

IF—THEN— ELSE
STRUCTURES,
PROCEDURES, AND
MACROS

The last chapter showed you how quite a few of the 8086 This structure says that IF the stated condition is found
instructions work, and how jump instructions are used to be true, the series of actions following THEN will be
to implement WHILE— DO and REPEAT— UNTIL struc- executed. If the condition is false, then execution will
tures.
section
A of this chapter shows how IF — THEN — skip over the actions after the THEN and proceed on
ELSE structures are also implemented with jump in- with the next mainline instruction.
structions.
majorThe point of this chapter, however, is The simple IF — THEN is implemented with a condi-
to show you how to write and use subprograms called tional jumpinstruction. In some cases an instruction to
procedures. A final section of the chapter shows you set flags is needed before the conditional jump instruc-
how to write and use assembler MACROs. tion. Figure 5-la shows, with a program fragment, one
way to implement the simple IF — THEN structure. In
this program we first compare BX with AX to set the
OBJECTIVES required flags. If the zero flag is set after the compari-
son, indicating that AX is equal to BX. the |E instruction
At the conclusion of this chapter you should be able to:
will cause execution to jump to the MOV CL, 07H in-
struction labeled
THERE. If AX is not equal to BX. then
1. Write 8086 assembly language programs to solve the three NOP instructions after the )E instruction will
IF— THEN. IF— THEN — ELSE, and multiple IF- be executed before the MOV CL, 07H instruction.
THEN — ELSE type programming problems. The implementation in Figure 5-la will work well for a
2. Write an 8086 assembly language program which short sequence of instructions after the conditional
calls a near procedure. jump instruction. However, if the sequence of instruc-
tions
lengthy,
is there is a potential problem. Remember
3. Write an 8086 assembly language program which from the discussion of conditional jumps in the last
calls a far procedure chapter that a conditional jump can only be to a location
4. Describe how a stack is initialized and used in 8086 in the range of - 128 bytes to +127 bytes from the ad-
assembly language programs which call procedures. dress after
the conditional jump instruction. A long se-
quence
instructions
of after the conditional jump in-
5. Write and use an assembler MACRO. structionput
may the label out of range of the
conditional jump instruction. If you are absolutely sure
that the destination label will not be out of range, then
IF— THEN, IF— THEN— ELSE, AND use the instruction sequence shown in Figure 5-la to
MULTIPLE IF— THEN— ELSE PROGRAMS implement an IF — THEN structure. If you are not sure if
the destination will be in range. Figure 5-lb shows an
IF— THEN Programs instruction sequence that will always work. In this se-
Remember from ( lhapter 2 that the IF — THEN structure quenceconditional
the jump instruction only has to
has the format: jump over the JMP instruction. The )MP instruction
used to get to the label THERE can jump to anywhere in
IF condition THEN the code segment, or even to another code segment.
action Note that you have to change the conditional jump in-
action struction)Efrom
to JNE in this second version. The price

104
i MP AX, B> ; compare to set flags
.If THERE ; if equal then skip correction
NOP
NOP ; NOPs represent correction
NOP ; i ns true t i ons
1 HI i-'i MOV CL, 07H ; 1 oad count

CMP AX, BX ; compare to set flags


JNE FIX ; if not equal do correction
JMP THERE
FIX: NOP ; NOPs represent correction
NOP ; instructions
NOP
THERE: MOV CL , 07H ; load count

FIGURE 5-1 IF—THIN implementations, (a) Conditional jump destinations


closer than ± 128 bytes (b) Conditional jump destinations further than ! 128
bytes.

you pay for not having to worry whether the destination depending on the value of the temperature it reads in. If
is in range is an extra jump instruction. the temperature is be-low 30' C. we want to turn on a
By now you are probably thinking that this IF — THEN yellow lamp to tell the operator that the solution is not
structure looks very familiar. It should, because a sim- up to temperature If the temperature is greater than or
ple IF—
THEN is part of the WHILE— DO and REPEAT— equal to 30 C, we want to light a green lamp. With a
UNTIL structures. If you look back at the programs in system such as this the operator can visually scan all the
the last chapter, you should see several examples of sim- lamps on the control panel until all green lamps are lit.
ple—IFTHEN. One example is the instruction sequence When all the lamps are green, the operator can push the
in Figure 4-23 which turns on an alarm if two compared GO button to start making boards. The reason that we
strings are not equal. We cycled through the simple have the yellow lamp is to let the operator know that this
IF— THEN again here as a lead-in to the IF— THEN- part of the machine is working, but that the tempera-
ELSE discussed next. turenot
is yet up to 30°C.
Figure 5-2 shows with flowcharts and with pseudo-
code two
ways we can represent the algorithm for this
IF— THEN— ELSE Programs problem. The difference between the two is simply a
The IF— THEN— ELSE structure is used to indicate a matter of whether we make the decision based on the
choice between two alternative courses of action. Figure temperature being below 30 C, or we make the decision
3-3b shows the flowchart and pseudocode for this struc- based on the temperature being above or equal to 30°C.
ture. Basically the structure has the format: The two approaches are equally valid, but your choice
determines which conditional jump instruction you
IF condition THEN choose. Figure 5-3a shows the 8086 assembly language
action implementation of the algorithm in Figure 5-2a.
act ii hi For this program segment, assume that we read the
ELSE temperature in from an analog-to-digital converter con-
action nected
input
to port FFF8H. Also assume that the con-
action trol for
the yellow lamp is connected to bit 0 of port
FFFAH. and the control for the green lamp is connected
This is a different situation than the simple IF — THEN, to bit 1 of port FFEAH. A 1 sent to a bit position of port
because here either one series of actions or another se- FFFAH turns on the lamp connected to that line. After
ries actions
of is done before the program goes on with we read the data in from the port, we compare it with
the next mainline instruction. An example will show our set point value of 30 C. If the input value is below
how we implement this structure. 30 C. then we jump to the instructions which turn on
Suppose that in the computerized factory we dis- the yellow lamp. If the temperature is above or equal to
cussed
Chapter
in 2 we have an 8086 microcomputer 30 C. we jump to the instructions which turn on the
which controls a printed-circuit-board-making ma- green lamp. Note that we have implemented this algo-
chine. of
Partthe job of this 8086 is to check a tempera- rithmsuch
in a way that the IB instruction will always
ture sensorand turn on a green lamp or a yellow lamp be able to reach the label YELLOW.

IF I HLN — LLSF STRUCTURES, PROCEDURES, AND MACROS 105


READ
TEMPERATURE

^\. ? ^S^

LIGHT LIGHT LIGHT LIGHT


YELLOW GREEN GREEN YELLOW

1 «
1

READ pH READ pH
SENSOR SENSOR

READ TEMPERATURE READ TEMPERATURE


IF TEMPERATURE 30" THEN IF TEMPERATURE 30 THEN
LIGHT YELLOW LAMP LIGHT GREEN LAMP
ELSE ELSE
LIGHT GREEN LAMP LIGHT YELLOW LAMP
READ pH SENSOR READ pH SENSOR

(a) tb)

FIGURE 5-2 Flowcharts and pseudocode tor two ways of expressing algorithm
for printecl-circuit-board-making machine, (a) Temperature below 30 test, (b)
Temperature above <o test.

The IBM Personal Coaputer MACROAsseabler 02-19-85 PAGE 1-1

PAGE,132
8084 program section for PC board eakinq aachine

ABSTRACT: This prograa section reads the teaperature of a cleaning


bath solution and lights one of two laaps according to
the teaperature read. If the teap is belot* 30 degrees
Celsius, a yellow laap Mill be turned on. If the teap
is above or equal to 30 degrees, a green laap mi11be
turned on.
REGISTERS
USED:CS, AL, DX
PORTSUSED : FFF8H as a teaperature input
FFFAHas laap control output (yelloM=bit 0, green-bit 1)
PROCEDURES : None used

CODE HERE SEGMENT


ASSUME CS:C0DE HERE

Jintialire port FFFAHas an output port


BA FFFE MOVDX, 0FFFEH ; Point DX to port control register
B0 99 MOVAL, 99H i load control Mord to set up output port
EE OUTDH, AL ; send control Mord to control register
; initialization coaplete

BA FFF8 MOVDX, 0FFF8H ; point DXat input port


EC IN AL, DX ; read teap froa sensor on input port
3C IE CMPAL, 30 : coapare teap hi th 30 degrees C

FIGURE 5-3 Assembly language program segments lor printed-circuit-board-


making machine, (a) Below 50 version, (b) Above 30 version.

106 CHAPTER FIVE


mi 72 03 JB YELLOW if te»p < 30 go light yellow laap
mi. EB 0A 90 JMP GREEN else go light green laap
0011 B0 01 YELLOW: IIOVAL, 01H load code to light yellow laip
0013 BA FFFA MOVDX, 0FFFAH point DX at output port
0016 EE OUTOX, AL send code to light yelloM laip
0817 EB 07 90 JMP EXIT go to next aainline instruction
001A B0 02 green: NOVAL, 02H load code to light green laip
001C BA FFFA NOVDX, 0FFFAH point DX at output port
001F EE OUTDX, AL send code to light green laap
0020 BA FFFC exit: IIOVDX, 0FFFCH next aainline instruction

0023 CODE HERE ENDS


END

IBMPersonal Computer MACRO


Assembler Version S.00 Page 1-1 11-07-85

PAGE .132
8086 prograe section for PC board Baking aachine

ABSTRACT: This prograa section reads the teaperature of a cleaning


bath solution and lights one of two laaps according to
the teaperature read. If the teap is below 30 degrees
Celsius, a yellow laap will be turned on. If the teap
is above or equal to 30 degrees, a green laap will be
turned on.
REGISTERS USED: CS, AL. DX
PORTSUSED : FFFSH as a teaperature input
FFFAHas laap control output iyellow=bit 0, green=bit 1)
PROCEDURES : None used

0000 CODE HERE SEGMENT


ASSUME CS:C0DE HERE

iintialize port FFFAHas an output port


0000 BA FFFE MOVDX, OFFFEH ; Point DX to port control register
0003 BO 99 MOVAL, 99H ; load control word to set up output port
0005 EE OUTDX, AL ; send control word to control register
'.initialization coaplete
0006 BA FFF8 MOVDX, 0FFF8H point DXat input port
0009 EC IN AL. DX read teap froa sensor on input port
000A 3C IE CMP AL, 30 coepare teap with 30 degrees C
OOOC 73 03 JAE GREEN if teap >= 30. go light green laap
000E EB OA 90 JMP YELLOW else go light yellow laap
0011 BO 02 GREEN: MOVAL, 02H load code to light green laap
0013 BA FFFA MOVDX, OFFFAH point DXat output port
0016 EE OUT DX, AL send code to light green laap
0017 EB 07 90 JMP EXIT go to next aainline instruction
001 A BO 01 YELLOW: MOVAL, 01H load code to light yellow laap
OolC BA FFFA MOV DX, OFFFAH point DXat output port
00 IF EE OUT DX, AL send code to light yellow laap
ooao BA FFFC EXIT: MOVDX, OFFFCH next aainline instruction

o023 C0DE_HERE ENDS


END

FIGURE 5-3 (continued)

IF— THEN— ELSE STRUCTURES, PROCEDURES, AND MACROS 107


To actually turn on a lamp, we load a 1 in the appro- TEMPERATURE

priate
ofbit
the Al. register with a MOV instruction and 0
[yellow
send the byte to the lamp control port, FFFAH. For ex- ; f LAMP
1
ample,instruction
the sequence MOV AL, (IIH — OUT -I

30
DX, AL will light the yellow lamp by sending a 1 to bit 0 1 i,nti:n
f LAMP
ol port FFFAH. 39
Figure 5-3b shows another equally valid assembly lan- 40
\ RED
guage program segment to solve our problem. This one : 1 LAMP
uses a Jump if Above or Equal instruction. |AL. at the
decision point and switches the order of the actions.
This program more closely follows the second algorithm
statement in Figure 5-2b. Perhaps you can see from
READ
these examples why two programmers may write very
TEMPERATURE
different programs to solve even very simple program-
ming problems.

Multiple IF—THEN— ELSE Implementation


In the preceding section we showed how to implement
LIGHT
X^ 1
and use the IF — THEN — ELSE structure which chooses YELLOW
YES y^ T- 40^s NO
between two alternative courses of action. In many situ- LAMP

ationswant
we a computer to choose one of several al-
ternative actions
based on the value of some variable LIGHT
LIGHT RED
GREEN
lead in or on a command code entered by a user. To LAMP
LAMP
choose one alternative from several we can nest IF —
THEN — ELSE structures. The result has the form:

IF condition THEN READpH


SENSOR
action
action
ELSE IF condition THEN
action
READ TEMPERATURE
act ion
IF TEMPERATURE 30 THEN
ELSE LIGHT YELLOW LAMP
ELSE IF TEMPERATURE 40 THEN
action
LIGHT GREEN LAMP
action ELSE LIGHT RED LAMP
READ pH SENSOR

It is important to note in (his structure that the last (c)


ELSE is part of the IF— THEN just before it. Figure 3-3g
showed .i flowchart and pseudocode for a "soup cook"
FIGURE 5-4 Algorithm for 3-lamp printed-circuit-board-
example using this structure. The soup cook example,
making machine, (a) Condition list, (b) Flowchart, (c)
Pseudocode.
however, is too messy to implement here. Therefore,
while the printed-circuit-board machine from the last
se< tion is still fresh in your mind, we will expand that
example to show you how a multiple IF— THEN — ELSE
is implemented. chart or the pseudocode, it is best to start at one end of
Supposi that we want to have three lamps on our the overall range and work your way to the other. For
printed-circuil board-making machine. We want a yel- example, in the flowchart in Figure 5-4b we start by
low lampto indicate that the temperature is below 30'C, checking if the temperature is below 30°. If the tempera-
a green lamp to indicate that the temperature is above turenot
is below 30° then it must be above or equal to
or equal to 30°C but below 40°C, and a red lamp to indi- 30° and you do not have to do another test to determine
cate that
the temperature is al or above 40°C. Figure 5-4 this. You then check if the temperature is below 40°. If
shows three ways to indicate what we want to do here. the temperature is above or equal to 30°. beit below 40°,
The first way in Figure 5-4a simply indicates the desired (hen you know that the temperature is in the green
action nexl to each temperature range. You may find lamp range. If the temperature is not below 40°. then
this form very useful in visualizing problems where the you know that the temperature must be above or equal
alternatives are based on the range of a variable. Don't lo 40°. In other words, two carefully chosen tests will
miss the ASClI-to-hexadecimal problem at the end of the direct execution to one of the three alternatives.
chapter for some practice with ibis. Once von gel the Figure 5-5 shows how we can write a program for this
problem defined in this list form, you can easily convert algorithm in 8086 assembly language. In the program
it to a flowchart or pseudocode. When writing the How- we hist initialize port FFTAH as an output port. We then

108 < HAI'I I R IIVI


The IBM Personal Computer MACROAsseabler 02-19-85 PAGE 1-1

PAGE .132
8086 prograa section for PC board nahnq aachine

ABSTRACT: This prograa section reads the teaperature of a cleaning


bath solution and lights one of 3 laaps according to
the teaperature read. If the teap is below 30 degrees
Celsius, a yellow laap will be turned on. If the teap
is >= 30 and ( <»0degrees, a green laap will be turned on
Teaps >- <t0 degrees will turn on a red laap.
REGISTERS USED CS. AL. DX
PORTS USED : FFF8H as a teaperature input
FFFAHas laap control output (yellow = bit 0.
green = bit 1. red = bit 2)
;PROCEDURES None used

0000 CODE HERE SEGMENT


ASSUME CS:C0DE HERE

iintialize port FFFAHas an output port


oooo BA FFFE MOVDX. OFFFEH i Point DX to port control register
0003 BO 99 MOVAL, 99H ; load control word to set up output port
0005 EE OUT DX, AL » send control word to control register
; initialization coaplete

0006 BA FFF8 MOV DX, 0FFF8H point DXat input port


ooo> EC IN AL, DX read teap froa sensor on input port
000A BA FFFA MOV DX, OFFFAH point DXat output port
oooD 3C IE CMP AL, 1EH coapare teap with 30 degrees C
000F 72 OA 3B YELLOW if teap < 30 go light yellow laap
0011 3C 28 CMP AL, 28H coapare with <tOdegrees
0013 72 OC JB GREEN if teap \ <tOgo light green laap
0015 BO 0* RED: MOVAL, 0<tH teap >- <tOso load code to light red
0017 EE OUT DX, AL send code to light red laap
oo!8 EB OA 90 JMP EXIT go to next aainhne instruction
001B BO 01 YELLOW: MOVAL, 01H load code to light yellow laap
00 ID EE OUT DX, AL send code to light yellow laap
00 IE EB 0<t 90 JMP EXIT go to next aainhne instruction
0021 BO 02 GREEN: MOVAL, 02H load code to light green laap
0023 EE OUT DX, AL send code to light green laap
002^ BA FFFC EXIT: MOV DX, OFFFCH next aainhne instruction
0027 EC IN AL, DX ; read ph sensor
0028 CODE HERE ENDS
END

FIGURE 5-5 Assembly language program for 3-lamp printed-circuit-board-


making machine.

read inthe temperature from an A/D converter con- GREEN, if the temperature is less than 40° (28H). If the
nected
portto FFF8H. We compare the temperature read jump is not taken, we know that the temperature must
in with the first set point value. 30 ( 1EH). If the temper- be at or above 40°C so we just go ahead and turn on the
ature
below
is 30°. the jump if below. )B, instruction will red lamp.
cause a jump to the label YELLOW. If the jump is not For this program we assume that the lines which con-
taken, we know the temperature is above or equal to 30° trol the
three lamps are connected to port FFFAH. The
so we go on to the CMP AL, 28H instruction to see if the yellow lamp is connected to bit 0, the green is connected
temperature is below the second set point. 40 (28H). to bit 1 . and the red is connected to bit 2. We turn on a
The |B GREEN instruction will cause a jump to the label lamp by outputtinga 1 to the the appropriate bit of port

IF—THEN— ELSE STRUCTURES, PROCEDURES, AND MACROS 109


FFFAH. The instruction sequence MOV AL, 02H— OUT then CALL this subprogram each time we want to exe-
DX, AL. lor example, will turn on the green lamp by cute thatseries of instructions. This saves us from hav-

sending a 1 to bit 1 of port FFFAH. ing write


to the series of instructions over and over each
time we want it to execute in the program. This subpro-
SUMMARY OF IF— THEN— ELSE gram
usually
is called a subroutine or a procedure. To be
IMPLEMENTATION consistent with the Intel literature we will use the term
procedure when referring to called subprograms.
Conditional jump instructions and instructions which
There is another major reason for using procedures in
set flags for them are used to implement IF — THEN —
programs. Recall from Chapter 2 the top-down design
ELSE structures. A single IF— THEN— ELSE structure
approach to solving a programming problem. In this
is used to choose one of two alternative series of actions.
approach the problem is carefully defined, and then the
IF— THEN— ELSE structures can be linked to choose
overall job is broken down into modules. Each of these
one of three or more alternative series of actions. As
modules is broken down into smaller modules. The
shown in Figure 3-3g. linked IF— THEN— ELSE struc-
process is continued until the algorithm for each mod-
tures one
are way to implement the CASE structure. The
uleclearly
is obvious. Figure 5-6 shows how this hierar-
algorithm for the printed-circuit-board machine lamps
chymodules
of can be represented in diagram form. A
program in the preceding section example could have
diagram such as this is often called a hierarchial chart.
been expressed as:
The point of all this is to break a large problem down
into manageable-size pieces which can be individually
CASE temperature OF
written, tested, and debugged. The individual modules
< 30 light yellow lamp
are usually written as procedures and called from a
> 30 and light green lamp
mainline program which implements the highest level of
a 40 light red lamp
the hierarchy. This approach has the added advantage
that a person can read the mainline program to get an
This CASE structure would be implemented in the same
overview of what the program does, and then work down
way as the program in Figure 5-5. However, expressing
into the procedures to see the amount of detail needed
the algorithm for the problem as linked IF — THEN-
at a particular point. Now that you know what proce-
ELSE structures makes it much easier to see how to
duresusedare for. we will give you an overview of how
implement the algorithm in assembly language. Later
they work.
we show you another way to implement some CASE sit-
Figure 5-7a shows in diagram form how program exe-
uations using
a jump table.
cution goes
from the mainline to a procedure and back
In many programs where we want to choose between
to the mainline. A CALL instruction in the mainline
two or more alternative series of actions, each of the se-
loads the instruction pointer and in some cases also the
ries actions
of is quite lengthy. In this case we write
code segment register with the starting address of the
each series of actions as a subprogram and CALL this
procedure. The next instruction fetched then will be the
subprogram when it is needed. The next major section
first instruction of the procedure. At the end of the pro-
of this chapter shows you how to write and use subpro-
cedure
return
a instruction. RET. sends execution back
grams,
procedures,
or as they are often called.
to the next instruction after the CALL in the mainline
program. The RET instruction does this by loading the
WRITING AND USING PROCEDURES instruction pointer, and. if necessary, the code segment
register with the address of the next instruction after
Introduction the CALL instruction. As shown in Figure 5-7b, a proce-
Whenever we have a series of instructions that we want dure can
call another procedure. This is called nesting
to execute several times in a program, we write the se- procedures. Nested procedures are used to implement
ries of
instructions as a separate subprogram. We can the hierarchy of modules we described in the preceding

UPDATE
MAIN
INVENTORY

r~
UPDATE
READ SALES OUTPUT
LEVEL 1 PARTS
RECORDS RESULTS
TOTALS

1
PRINT PRINT
PRINT TOTAL PARTS TO
I 1 VI I. 2 DEPARTMENT
INVENTORY ORDER LIST
INVENTORIES

FIGURE 5-6 Hierarchical chart for inventory update program.

110 CHAPTERFIVE
MAINLINE OR starting address ol the procedure, i i shows
CALLING PROGRAM
the coding formats foi the Com forms of the 8086 ( All
PROCtliUHl instruction ["he differences between these lour forms
INSTRUCTIONS are in the way they tell the 8086 to gel the starting ad
dress for the procedure.

NEXT MAINLINE
INSTRUCTION
CALL = Call

Within segment or group. IP n lative

MAINLINE Opcode Clocks Operation


INSTRUCTIONS l I) I') IP % li' : I : r

LOWER LEVEL
PROCEDURE PROCEDURE

Within segment or group. Indirect

NEXT MAINLINE ( ipeode mod Oil) i m


INSTRUCTION
Opcode Clocks Operation

FIGURE 5-7 Program flow to and from procedures. Inter-segment or group. Direct
(a) Single procedures, (b) Nested procedures.
offset low

paragraph. In the case of nested procedures, a RET in-


struction
the end
at of the lower level procedure returns
execution to the higher level procedure. A second RET
instruction at the end of the higher level procedure re-
turns executionto the mainline program. Inter-segment or group. Indirect
The question that may occur to you at this point is. "If
a procedure can be called from anywhere in a program. ( i| le mod "I I i in mem-low m

how does the RET instruction know where to return exe-


cution to?"
The answer to this question is that when a
CALL instruction executes, it automatically stores the
return address in a special section of memory called the
stack. A later section will introduce you to how the 8086
stack works. For now let's take a closer look at the 8086
CALL and RET instructions.

RET = Return from Subroutine

The 8086 CALL and RET Instruction

THE CALL INSTRUCTION OVERVIEW

The 8086 CALL instruction performs two operations


when it executes. First, it stores the address of the in-
struction the
after CALL instruction on the stack. This
address is called the return address because it is the
Return and add constant to SP
address that execution will return to after the procedure
executes. If the CALL is to a procedure in the same code
segment, then only the instruction pointer contents will
be saved on the stack. If the CALL is to a procedure in
another code segment, both the instruction pointer and
the code segment register contents will be saved on the
stack.
The second operation of the CALL instruction is to
change the contents of the instruction pointer and. in FIGURE 5-8 8086 CALL and RET instruction formats (Intel
some cases, the code segment register to contain the Corp.). la) CALL, (b) RET.

IF— THEN— ELSE STRUCTURES, PROCEDURES, AND MACROS 111


DIRECT WITHIN-SEGMENT NEAR CALLS ter. The MOD — R/M byte in the instruction is used to
specify the addressing mode for the memory location
The first form, direct within-segment near call, tells the
where the 8086 goes to get the new values. The first
8086 to produce the starting address of the procedure
word from memory is put in the instruction pointer,
by adding a 16-bit signed displacement contained in the
and the second word from memory is put in the code
instruction to the contents of the instruction pointer.
segment register. The instruction CALL DWORD PTR
This is the same process as we described for the direct
[BX] will compute a new value for IP from [BX[ and
within-segment near JMP instruction in Chapter 4. With
[BX t- 1] and a new value for CS from [BX * 2] and
this instruction the starting address of the procedure
[BX + 31. In other words it does a far call to an address
can be anywhere in the range of 32.768 bytes to
contained in 4 bytes pointed to by BX in the data seg-
-<-32.767 bytes from the address of the instruction after
ment.
the CALL. If you are hand coding a program, you calcu-
late the
displacement by counting from the address of
THE 8086 RET INSTRUCTION
the instruction after the CALL to the starting address of
the procedure. If the procedure is in memory before the As we described in the previous section, when the 8086

CALL instruction, then the displacement will be nega- does a near CALL it saves the instruction pointer value

tive.this
In case you represent the displacement in for the instruction after the CALL on the stack. A return

16-bit. 2's complement sign-and-magnitude form just instruction. RET. at the end of the procedure copies this

as you do for backward JMP instructions. If you are value from the stack back to the instruction pointer.

using an assembler, the assembler will automatically This then returns execution to the mainline program.

calculate the displacement from the instruction after When the 8086 does a far CALL it saves the contents of

the CALL to a label at the start of the procedure. both the instruction pointer and the code segment reg-
ister on
the stack. An RET instruction at the end of the
THE INDIRECT WITHIN-SEGMENT CALL procedure copies these values from the stack back into
the IP and CS registers to return execution to the main-
The indirect within-segment CALL instruction is also a
line program. Obviously we need one form of the RET
near call. When this form of CALL executes, the instruc-
instruction to handle returns from near procedures,
tion pointeris replaced with a 16-bit value from a speci-
and another form of the instruction to handle returns
fied register or memory location. As indicated by the
from far procedures. Actually the 8086 has four forms of
MOD — R M byte in the coding template, the source of
the RET instruction. Figure 5-8b shows the coding tem-
the value can be any of the eight 16-bit registers or a
plates these
for four.
memory location specified by any one of the 24 address-
The simple within-segment form of RET copies a word
ing modesshown in Figure 3-8. This form of CALL in-
from the top of the stack to the instruction-pointer reg-
struction
be can
used to choose one of several proce-
ister. This
is the instruction form you will usually use to
dures based
on a computed value. The instruction CALL
return from a near procedure. The within-segment add-
BP. for example, will do a near call to the offset contained
ing immediate to SP form is also used to return from a
in BP. In other words the value in BP will be put in the
near procedure. When this form executes, however, it
instruction pointer. The instruction CALL WORD PTR
will copy the word at the top of the stack to the instruc-
[BX] will get the new value for the instruction pointer
tion pointer and also add an immediate number con-
from a memory location pointed to by BX.
tained
thein instruction to the contents of SP. Later, we
will show you what this form is used for.
THE DIRECT INTERSEGMENT FAR CALL The intersegment form of the RET instruction is used
The direi I intersegment far CALL is used when the pro- to return from far procedures. When this form of the RET
cedure
in is
.mi ithcr segment. If the procedure is in an- instruction executes, it will copy the word from the top
other segment,you have to change both the instruction of the stack to the instruction pointer. It will then incre-
pointer and the code segment register to get to it. For ment the
stack pointer by two and copy the next word
this form of the CALL instruction, the new value for the from the stack to the code segment register. The inter-
instruction pointer is written in as bytes 2 and 3 of the segment adding
immediate to SP form of the instruction
instruction code. Note that the low byte of the new IP also copies a new value for IP and a new value for CS
value is written before the high byte. The new value for from the stack. However, it also adds a 16-bit immediate
the code segment register is written in as bvtes 4 and 5 number contained in the instruction code to SP.
of the instruction code. Again the low byte is written Throughout the preceding discussions of the CALL
before the high byte. A program example later in this and RET instructions we have talked about writing
chapter shows you how to write your programs so that words to the stack and copying these words back to the
an assembler can find a procedure label in another seg- instruction pointer and/or code segment register. Now
ment. we will show you how to set up a stack in your programs.

THE INDIRECT INTERSEGMENT FAR CALL

This form of the CALL instruction replaces the instruc-


The 8086 Stack
tion pointer and the code segment register contents The stack is a section of memory you set aside for stor-
with two 16-bit values from memory. Since two 16-bit ing return addresses. The stack is also used to save the
values are needed, the values cannot come from a regis contents of registers for the mainline program while a

112 CHAI'ItK IT VI
procedure executes. A third use ol the stack is to hold We don't need .ill 111 Kbytes ol the logical segment in
data "i addresses thai will be acted upon by a proce- our programs so we tell the assemblei to sel aside 40
dure. decimal 01 28H words ol storage In this logical segment
the 8086 Ids you sel aside up to an entire 6 I Kbyte with the DW 40 DUP(O) statement By limiting the stack
segment of memory as .1 stack. Remember from Un- to near the si/e actually needed, this segment can be
block diagram
in Figure 2 7 thai the 8086 contains .1 overlapped with other logical segments to save on the
stack segment register and .1 stack pointei register. The ami >uni hi physical me y required tor a program. In
stack segment register is used to hold the upper Its bits other words, there is no use having a larger stack set
ol the starting address you give to the slack segment. II aside than Mm .11 e going to need
you decide to si. in the slack segment .11 70000H, foi Now. when we store addresses or data in these stack
example, the slack segment register will contain 7(>(i(il [. local ions, we siai I at the highest local and till toward
l'hc stack pointer register is used to hold the offset oi the bottom. 11ns is opposite to the way you put instruc
the last word written on the slack, the 8086 produces lion khU- bytes in memory. In the case ol instruction
the physical address for a slack location by shifting the codes you start at the lowesi address in a code segment
contents ol the stack segment register four bit positions and fill toward the top. Since we start writing to the
to the leli and adding the contents ol the slack pointer highest location in the stack first, we need a name at-
to the result. Figure 2- 1 1 shows a numerical example of tached
thisto location so we can access it by name. The

this. statement STACK TOP LABEL WORD in Figure 5-9 gives


II you are going to call procedures or use the stack in the name STACK TOP to the next even address after the
some other way in your program, then you need to ini- 40 words we set aside for the stack. We will explain later
tialize both
the stack segment register and the stack why we want the name at the address after the actual
pointer register. Figure 5-9 shows the pieces you need to stack. The WORD in this statement indicates that
add to vour programs to declare a stack segment, and writes to and reads from the stack will be done as words.
to initialize SS and SP. We have shown in Figure 5-9 Figure 5-10 shows in diagram form how this example
how you should format all this for an assembler. If you stack would be arranged in memory.
are not using an assembler, then you should use the We arbitrarily choose to start the stack segment at
same format, but put the desired numbers in place of address 70000H for this example, and we set a stack
the names we have used. length of 40 words with the DW 40 DUP(O) statement.
The STACK HERE SEGMENT STACK and STACK HERE Since each memory address represents a byte, these 40
ENDS statements in Figure 5-9 are used to declare a logi- words will occupy the 80 addresses 70000H to 7004FH
cal segment that will be used for the stack. The STACK as shown in Figure 5-10. The label STACKTOP is asso-
directive tells the assembler that this segment will be ciated with
address 70050H. the next address after the
used as a last-in. first-out stack. stack.
The next program addition you need to look at is in
NOTE: If you are going to use the IBM program the ASSUME statement. Note that we have added the
EXE2BIN on your programs so that you can download term SS: STACK HERE, to tell the assembler that any ref-
them to an SDK-86, omit the STACK directive here. The erence
thein program to the stack means the segment
linker will then give you an error message. WARNING — STACK HERE. This term tells the assembler that SS
NO STACK SEGMENT, which you can ignore. will contain the starting address of STACK HERE, but

;8086 Program fragment showing the i nt i a 1 i zat i on of the stack


; segment and the stack pointer

STACK_HERE SEGMENT STACK

DW ^O DUP(O)
STACK_T0P LABEL WORD
STACK HERE ENDS

CODE HERE SEGMENT


ASSUME CS-.CODE HERE, SS: STACK HERE

MOV AX, STACK_HERE initialize stack segment


MOV SS, AX reg i ster
LEA SP, STACK TOP intialize stack pointer
continue with program

CODE HERE ENDS


END

FIGURE 5-9 Required program additions when a stack is used.

IF— THEN— ELSE STRUCTURES, PROCEDURES, AND MACROS 113


DEFINING THE PROBLEM AND WRITING THE
ALGORITHM

INITIALTOPOF STACK
Delay loops such as that shown in Figure 4-20 are often
70050H
AND TOS AFTER RET written as procedures so that they can be called from
7004FH anywhere in a program. Suppose that we want to have a
7004EH — TOP OF STACK program which reads 100 data words from a port at
AFTER CALL 1-ms intervals, masks the upper 4 bits of each word,
and puts each result in an array in memory. Before you
read on. see if you can write a flowchart or pseudocode
for this problem. Now compare your results with those
in Figure 5-1 la or b. Hopefully you recognized this
>- STACK problem as a REPEAT — UNTIL situation.
The next step is to expand the algorithm to take into
account the specific architectural features of the 8086
that we will use to implement the algorithm. Figure
5- 1 lc shows one way to do this expansion. We know that

70000 H START OF STACK


SEGMENT

FIGURE 5-10 Stack diagram showing how the return


0
address is pushed on the stack bv CALL.

READ VALUE

it does not load this value in the SS register. Loading the FROM PORT

SS register must be done with program instructions,


just as we do with the data segment register and the
extra segment register. Again, we can't load an immedi-
ate number directly into a segment register, so we load MASK UPPER
ting address of the segment into a register and 4 BITS
then copy it into the stack segment register. The MOV
AX, STACK HERE and the VtO\ SS, \X instructions do
this Now all we have to do is initialize the stack pointer.
We want to initialize SP so that the first word written to PUT IN
the stack goes to the highest location in the memory we ARRAY
set aside for the stack. All of the instructions which di-
rectly write
a word to the stack decrement the stack
pointer by two before writing the word. Therefore, we
want the stack pointer to be initially loaded with the
next even address above the actual stack. We gave this
location the name STACKLTOP. Therefore, we can use
the LEA SP, STACK TOP instruction to initialize thi
pointer. We could also have used the instruction MOV
SP, OFFSET STACK TOP to initialize the stack pointer.
The next section shows how the pieces we have dis-
cussedput
are in an example program which calls a
near procedure We also use this example to show you
how the stack functions during a procedure call and re-
turn.

A Near Procedure Call and Return Example


Previous sections introduced you to the 8086 ( ALL and
RET instructions and showed you how to set up a stack.
Here we use a program example to show you how proce- FIGURE 5-11 Algorithm tor taking data samples at 1-ms
dures are written and to dig more deeply into how the intervals, (a) Flowchart, ib) Pseudocode, (c) Pseudocode
Stack operate-.. expanded.

114 ( HMTER FIVE


DATA SAMPLES PROGRAM some new ones from this chaptei The program is a little
REPEAT longei than oui previous examples, but don'l lei this
GET DATA SAMPLE FROM PORT overwhelm you. A large pari ol the program i %simply
MASK UPPER <* BITS
Initializ ; everything. Read through tins program and
sec how much ol ii you can remembei and oi figure out
PUT IN ARRAY
before you read oui explanations in the following para
WAIT 1 ms
graphs Deciphering a program written by someo
UNTIL 100 samples taken
is ,in impoi tanl skill to develop.
At the si. ii i ol the program we declare a logica
K>)
menl foi data with the DATA HERI SECMEN1
DATA HERI ENDS statements. The statement PRES-
DATA SAMPLES PROGRAM SURES Kill
DW DUP(O) in (his segment sets aside 100
winds dI memory to store the values read in from a pn s

INITIALIZE POINTER TO ARRAY [ S I 3 sine sensor. This statement also initializes these 100
words to .ill O's. Ii really doesn't matter what values are
INITIALIZE COUNTER, BX
initially in these locations, because the program is going
to write values in them. However, we like to initialize
REPEAT
arrays such .is ilus to all O's so that during debugging
READ PORT
we can tell il I he progi am wrote any values to these loca-
MASK UPPER <* BITS tions.
PUT IN ARRAY [SI] Next we declare a logical segment to be used for the
INCREMENT POINTER SI stack with the STAC k HERI SEGMEN1 STA( k and the
DECREMENT COUNTER BX STACK HERE ENDS statements. The statement DW 40
WAIT_1MS PROCEDURE DUP(O) sets up a stack length ol 40 words and initializes

UNTIL COUNTER = 0 these words to .ill o's. Again we really don'l care what
value these words have initially because we will be writ-
ing values there as we call procedures. The statement
WAIT_1MS PROC
STACK1TOP LABEL WORD gives a name to the next even
LOAD COUNT VALUE
address after the highest address in the stack we have
REPEAT
set up. As described in the previous section, we can then
DECREMENT COUNT VALUE access this location by name when we initialize the
UNTIL COUNT = 0 stack pointer.

!% % )
Now let's work our way through the main program
and the procedure in the code segment. We have to tell
FIGURE 5-11 (continued) the assembler which logical segments are being used for
code, data, and stack in the program. The ASSUME
CS:CODE HERE, DS:DATA HERE, SS:STACK HERE state-
ment does
this. The ASSUME statement, however, does
we need a pointer to the array and a counter to keep
not actually initialize the segment registers. We have
track of how many values we have put in the array.
to do this with program instructions. The MOV
Therefore we initialize these at the start. After we read
AX, DATA HERE and MOV DS,AX instructions initialize
in each value and put it in the array, we increment the the data segment register. The MOV AX, STACK HERE
pointer so that it points to the next location in the array.
and MOV SS,AX instructions initialize the stack
We then decrement the counter to indicate that we have
segment register. The stack pointer register must be
taken another sample, and call the WAIT IMS proce-
initialized to point to the next even address after the mem-
dure. Note
that the algorithm for the procedure is done
ory spacewe set aside for the stack. The MOV SP, OFFSET
separately from that for the main program. As we dis-
STACK_TOP statement will do this. The OFFSET
cussed
the inintroduction to procedures, the flow of the
operator, remember, tells the assembler to calculate the
mainline program is clearer if much of the detail is put
distance from the start of a segment to the specified
in separate procedures. Upon returning from the delay
name and put this number in the specified register. We
procedure we repeat the series of instructions if our
set aside 40 words for the stack so the offset of the label
sample counter is not yet down to zero.
STACK TOP will be 80 decimal or 0050H. This number
For the delay procedure we simply load a number in a is twice the number of words because each 8086 address
register or memory location and decrement the number represents a byte. The 0050H is the number that you
until it is down to zero. Note that even this expanded would put in the instruction, if you were hand coding
algorithm is general enough that it could be imple- the program.
mented
almost
on any microprocessor. Up to this point most of what we have done is essen-
tially housekeeping chores. Now we get started on the
THE 8086 ASSEMBLY LANGUAGE PROGRAM
actual algorithm for our initially stated problem. The
Figure 5-12 shows the assembly language program for statement LEA SI, PRESSURES initializes the SI register
our expanded algorithm. This program reviews some of as a pointer to the first location in the array PRES-
the concepts from previous chapters and demonstrates SURES.
loads Itthe effective address or offset of the first

IF— THEN— EfSE STRUCTURES, PROCEDURES, AND MACROS 115


IBH Personal Computer MACRO
Assembler Version 2.00 Page 1-1 11-07-85
PA6E ,132
;8086 Prograi
iABSTRACT: This progra» takes in data saiples fro« a port at 1 is
; intervals, tasks the upper 4 bits of each saaple, and
; puts each lasked sample in successive locations in an array.
;REGISTERSUSED:CS, SS, DS, AX, BX, CX, DX, SI, SP
iPORTSUSED: 0FFF8H- input port for data samples
iPROCEDURES: WAIT IMS

= FFF8 PRESSURE PORT ECU 0FFF8H

0000 DATA.HERE SEGMENT


0000 6H ( PRESSURESDU 100 DUP(O) ; set up array of 100 words
0000

00C8 DATA.HERE ENDS

0000 STACKHERE SEGMENT STACK


0000 28 [ DM 40 DUP(O) set stack length of 40 words
OOmO

0050 STACKTOP LABEL WORD


0050 STACK HERE ENDS

0000 CODE HERE SEGMENT


ASSUME CS:CODE HERE, DS:DATA HERE, SS: STACK HERE

0000 B8 — - R START: MOVAX, DATA.HERE ; initialize data segient register


0003 8E D8 MOVDS, AX
0005 B8 — - R MOVAX, STACK.HERE i initialize stack segment register
0008 8E DO MOVSS, AX
OOOA BC 0050 R MOVSP, OFFSETSTACK.TOP i intialize stack pointer to top of stack

OOOD 8D 36 0000 R LEA SI, PRESSURES ; point SI to start of array


0011 BB 0064 MOVBX, 100 ; load BX with nuiber of sasples
0014 BA FFF8 MOVDX, PRESSURE
.PORT ; Point DX at input port
0017 NEXT.VALUE:
0017 ED IN AX, DX ; read data froc port
0018 25 OFFF ANDAX, OFFFH ', task upper 4 bits
00 IB 89 04 MOV[SI], AX ; store data word in array
001D E8 0026 R CALLWAIT.IMS ; delay of 1 is
0020 46 INC SI ', point SI at next location in array
0021 46 INC SI
0022 4B DEC BX ; decreeent saeple counter
0023 75 F2 JNZ NEXT.VALUE ; repeat until 100 saiples done
0025 90 STOP: NOP

0026 WAIT.IMS PROCNEAR


0026 B9 23F2 MOVCX, 23F2H ; load delay constant into CX
0029 E2 FE HERE: LOOPHERE ; loop until CX = 0
002B C3 RET
002C WAIT.1MS
ENDP
002C CODE"HERE
ENDS
END

FIGURE 5-12 Assembly language program to read in IOOsamples of data at


1-ms intervals.

116 CHAPTER FIVE


IBMPersonal Coiputei MACRO
Assembler Version 2.00 Page Syibols-1 11-07-85

Segments and Groups:

N a i e Size Align Coabine Class

CODE.HERE. 002C PARA NONE

DATAHERE. 00C8 PARA NONE

STACKHERE 0050 PARA STACK

Syibols:

N a • e Type Value Attr

HERE L NEAR 0029 CODE HERE

NEXT_VALUE
. . L NEAR 0017 CODE HERE

PRESSURES.. . L WORD 0000 DATA HERE Length =006*


PRESSURE.PORT. Nuiber FFF8

STACK.TOP.. . L WORD 0050 STACK HERE


START L NEAR 0000 CODE HERE
STOP L NEAR 0025 CODE HERE
WAIT IMS . . . N PROC 0026 CODE.HERE Length =0006

50092 Bytes free

Warning Severe
Errors Errors
0 0
FIGURI VI 2 [continued)

word in PRESSURES into SI. For our example here bits from getting put in memory with our data, we mask
PRESSURES is the first data item in the segment so the these bits out by ANDing them with O's. The instruction
value loaded into SI will be OOOOH. We chose to use the MOV [SI], AX will copy the data word from the AX regis-
BX register as a sample counter, so we use the state- ter to
the memory location pointed to by SI in the data
ment MOV
BX, 100 to initialize BX with the number of segment.
samples we want to take and store. Finally, we are going To produce the desired delay between samples we
to get to some action. CALL the WAIT 1MS procedure. This is a direct within
As indicated by the PRESSURF PORT EQU 0FFF8H segment CALL because the procedure is contained in the
statement at the top of the program, the pressure sensor same code segment as the CALL instruction.
is connected to port FFF8H. Since this port address is We use the PROC and ENDP directives to "bracket" the
larger than FFH. we have to use the variable port input assembly language statements of the procedure. Putting
instruction. For this input instruction we first load the a name in front of these directives allows us to call the
port address in the DX register with the MOV DX, PRES- procedure by name. For the example in Figure 5-12 we
SURE PORT
instruction, and then read the data word in gave the procedure the name WAIT 1 MS to remind us of
with the IN AX, DX instruction. Notice how much more the function of the procedure. To produce the desired
understandable it makes a program when we use a delay we load a number into the CX register with the
name such as PRESSURE PORT in an instruction MOV CX, 25F2H instruction and count the number
rather than 0FFF8H. the numerical port address. If you down to 0 with the LOOP HERE instruction. The LOOP
are working with an assembler, use EQU statements to instruction, remember, decrements CX by 1 and jumps
give names to constants in your program. to the specified label if CX is not yet down to 0. Since we
When we get the pressure value into AX. we mask out put the label on the LOOP instruction, the LOOP in-
the upper 4 bits with the AND AX. OFFFH instruction. struction
simply
will execute over and over until CX

The reason why we want to do this is that the analog-to- reaches 0. The RET instruction at the end of the proce-
digital converter that the pressure sensor is connected dure will
return execution to the next instruction after
to is a 12-bit unit. The upper 4 bits of the 16-bit port are the CALL in the mainline of the program. Since this pro-
not connected to anything and may pick up random- cedure
in isthe same code segment as the mainline pro-
noise signals. To prevent noise signals on the upper 4 gram, only
the instruction pointer has to be changed to

IF—THEN— ELSE STRUCTURES, PROCEDURES, AND MACROS 117


get back to the mainline. The CALL instruction copied STACK IN MEMORY

the desired value for the instruction pointer to the stack


before going to the procedure. The RET instruction will
70050H SP INITIALIZED
copy this value from the stack back to the instruction TO HERE - SP = 0050H
7004 FH
pointer. If you are hand coding a program such as this,
7004EH SP POINTS HERE
make sure to use the correct form of the RET instruction.
AFTER NEAR CALL
7004DH
After we briefly discuss the rest of the mainline pro- SP = 004EH
gram,will
we show you what happens to the stack and 7004CH

stack pointer as the return address is copied to and


from the stack.
Now. back in the mainline we need to get ready for
reading the next data value. First we want If) get SI
pointed to the location where we want to put the next
data word. Since each address represents a byte, and we
are storing words, we have to increment the pointer by STACK SEGMENT
two to point to the next storage location. Two INC SI BASE 70000H
SS = 7000H
instructions do this. You could use the single instruc-
tion ADDSI, 02H to do the same job. After updating the
pointer we decrement the sample counter in BX with the
DEC BX instruction. If BX is not yet counted down to 0.
STACK IN MEMORY
the )NZ NEXT VALUE instruction will cause the 8086 to
read in and process another value from the port. If BX is 70050 H SP INITIALIZED
0, indicating that all 100 samples have been taken, exe- TO HERE - SP = 0050H
7004FH-
cution goes
on tn the next mainline instruction after
7004 EH
)NZ. Now let's see what happens to the stack and the
7004DH
stack pointer during all of this.
7004CH SP POINTS HERE
AFTER FAR CALL

More Stack Operation and Use

STACK OPERATION DURING A CALL AND RET

To show how the stack operates during a CALL and RET


we will use some specific numbers with the example
program in Figure 5-12. Suppose that for the program STACK SEGMENT
we start the stack at address 70000H. The stack seg- BASE - SS = 7000H

ment registerthen will be initialized with 7000H. We set


a stack length of 40 decimal or 28H words with the DW
40 DUP(O) statement. These 28H words will occupy the
50H memory locations from 70000H to 7004FH. Figure FIGURE 5-13 Stack diagram for program in Figure 5-10.
5- 13a shows this in diagram form. Now remember, la) For near CALL, (b) For far CALL.
when we write words to the stack, we put the first word
at the highest address. For our example here the first
word will be written at addresses 7004EH and 7004FH. in the instruction pointer to the memory location now
As we write other words to the stack they are written at pointed to by the stack pointer. If the stack pointer con-
lower addresses. In other words the stack fills from the tained 0050H before being decremented, then after
top down. We use the stack pointer to keep track of being decremented by two it contains 004EH. The phys-
where the last word was written to the stack. The loca- ical address pointed to by the stack pointer and the
tion pointed to by the stack pointer at any time is called stack segment register will be 7004EH. The low byte of
the top of the stack. In the program we initialized the the instruction pointer will be copied to address
stack pointer to offset 0050H. the next even address 7004EH and the high byte of the instruction pointer will
above our actual stack, with the MOV SP. OFFSET be copied to address 7004FH. This follows the Intel con-
TOP STACK instruction. vention
putting
of the lower byte of a word at the lower
After (he .S086 fetches the CALL instruction from the address in memory- Figure 5- 13a shows these two bytes
instruction-byte queue in the BILI it automatically incre- labeled as IP LOW and IP HIGH. After the CALL instruc-
mentsinstruction
the pointer to 0020H. the offset of the tion executes, the stack pointer is left pointing to offset
next instruction after the CALL. You can see this if you 004EH. This location is now the top of the stack or TOS.
look at the first column of the program listing in Figure When the RET instruction at the end of the procedure
5-12. The instruction pointer then contains the address in the example program executes, the 8086 copies the
we want execution to return to after the procedure is return address from the top of the stack to the instruc-
completed. When the near CALL instruction in our ex- tion pointer. Since the top of the stack was at offset
ample program
executes, the 8086 first decrements the 004EH. the word from addresses 7004EH and 7004FH
stack pointer by two Then it copies the return address will be copied to the instruction pointer. After it copies

118 (TIAP11R FIVE


the word from the top ol the stack to the instruction The POP registei memory instruction copies a word
pointer, the 8086 Increments the stack pointei by two. from the top ol the stack to the specified 16 bll registei
For our example here II will increment the stack pointei oi memory location and increments the stack pointer by
from 004EH to 0050H I lie stack pointer is now back two. The POP ( \ instrui tion, foi example, will copy a
where it was before i In- c ALI Instruction executed. Note word from the top ol the slack to the CX registei and
that the return address is siiii present in memory be mi lenient the stack pointei by two. Alter a POP the
cause the Kl I instruction simply copied it to the in stack pointer will point to the next word on tin stai I
struction pointei and incremented the slack pointer You can PUsl I any ol the lu bit general pin pose regis
ovei n leis, AX, BX, CX, and DX; any ol the base oi pointei
When the sum, executes a fai * \\ l instruction u dec registers, BP, SI'. SI, and 1)1; any ol the segment regis
rements the slack pointei by two and topics the con ters. CS, DS, ss, and KS; or even a woid from a memory
tents ol the code segment registei to the slack. It then location specified by one ol those 24 memory addressing
decrements the stack pointer by two again and copies modes in Figure 3-8. A separate instruction, PUSHF,
the offset ol the next mainline instruction from the in decrements the stack pointer by two and copies the Hag
struction pointer to the stack. To help you visualize this word to the slack. The 80186 and 80188 1'IISIIA in-
Figure 5-13b shows how these would be written to the struction copies
AX. CX, DX, BX, SI'. BP, SI and 1)1 to
stack assuming the same slack starting addresses that the stack.
we used for the previous example. As you can see from You can POP a word from the stack to any ol the regis-
this figure, aftei a far CALI the top ol the slack will be ters except CS. and you can POP a word from the stack
lour addresses lower than it w.is before the CALL. to a memory location specified in any one ol those 24
A far Kl I used at the end of a far procedure will copy a ways. The POPF instruction copies a word from the
word from the top of the stack to the instruction pointer stack to the flag register and increments the stai I.
and increment the stack pointer by two. It will then copy pointer by two. The 80186 and 80188 POPA instruction
the word from the new top of the stack to the code seg- copies words from the stack to the DI, SI. BP, BX. DX.
ment register and increment the slack pointer again CX, and AX registers. Note that the POPA instruction
by 2. The next instruction will then be fetched from the does not return a value to the SP register.
physical address alter the far CAI 1 instruction. The top When you PUSH several registers on the stack you
of the stack will be back to where it was before the ( \l I have to remember to POP them off in the reverse order
and RET. that you pushed them on. This is because the stack
As we mentioned previously the stack is also used to functions in a last-in— first-out manner. An everyday
save the contents of registers while a procedure executes example of this type of operation is the spring-loaded
and to hold data that the procedure is to act on. The plate stacks seen in some restaurants. The last plate
next section shows you how we do this. pushed on the stack is the first one popped off. Figure
5- 14a should help you visualize how this works for the
USING PUSH AND POP TO SAVE REGISTER
8086. It shows a sequence of PUSH instructions you
CONTENTS
might use to save registers and flags at the start of a
In the example program in Figure 5-12 we used the BX near procedure called MULTO. Figure 5- 14b shows how
register to keep track of how many data samples we had the PUSH instructions will put the contents of these reg-
taken in. After each data sample was taken in we decre- istersthe
on stack. The first entry in the stack is the
mentedBXtheregister and used the |NZ instruction to copy of the instruction pointer put there by the CALL
determine whether to take another sample or to exit. We instruction that called the procedure. Following this are
would like to have used the CX register to keep track of the flag word and the words from registers AX. BX, and
the number of samples taken so that we could have used CX. After all of these are pushed on the stack, the stack
a single LOOP instruction instead of the DEC BX and JNZ pointer is left pointing at the location in the stack where
label instructions. The reason that we couldn't use CX CX was pushed.
for this in the program is because CX is used in the When we want to restore the saved values to the regis-
procedure. Any value we put in CX in the mainline pro- ters and flags at the end of the procedure we first POP
gram would
be written over by the MOV CX, 23F2H in- CX because it was the last register pushed on the stack.
struction
the procedure.
in It is very common to want to After CX is popped the stack pointer will be left pointing
use registers both in the mainline program and in a pro- at the location where BX is stored. Therefore, we POP BX
cedure without
the two uses interfering with each other. next. We continue popping until all of the registers and
The PUSH and POP instructions make this easy to do. the Hags are restored. Trie RET instruction then copies
The PUSH register/memory instruction decrements the return address from the stack to the instruction
the stack pointer by two and copies the contents of the pointer to return execution to the main program. It is
specified 16-bit register or memory location to memory very important to keep the number of pushes equal to
at the new top of stack location. The PUSH CX instruc- the number of pops or in some other way keep the stack
tion, for
example, will decrement the stack pointer by balanced so that the RET instruction finds the correct
two and copy the contents of the CX register to the stack word to put in the instruction pointer.
where the stack pointer now points. This instruction Some programmers like to push and pop registers in
then can be used to save the contents of CX while a pro- the mainline or calling program rather than in the pro-
cedure executes.
The next question is, how do we get the cedure
we asdid in Figure 5-14a. This approach has the
saved value back when we want it? advantage that you can push only those registers that

IF— THEN — ELSE STRUCTURES, PROCEDURES, AND MACROS 119


MULTO PROC NEAR FIGURE 5-14 Using PUSH and POP instructions.
(a) Instruction sequence, (b) Effect on stack and stack
PUSHF pointer.
PUSH AX
PUSH BX
PUSH CX STACK IN MEMORY

SP

3EFORECALL 0050H AFTER RET 0050H

POP CX
AFTER CALL 004EH AFTER POPF 004EH
POP BX
POP AX
POPF AFTER PUSHF 004CH AFTER POP AX 004CH

RET
AFTER PUSH AX 004AH AFTER POP BX 004AH

MULTO ENDP
AFTER PUSH BX 0048H AFTER POPCX 0048H
(a)

AFTER PUSH CX 0046H BEFORE POPCX

you care about saving each time you call the procedure. Likewise we often want a procedure to make some proc-
The disadvantages of this approach are that the pushes essed data
values or addresses available to the main pro-
and pops clutter up the mainline program, and you may gram. These
address or data values passed back and
decide to use another register at some point in the pro- forth between the mainline and the procedure are com-
gram and
forget to add a push for it. We like to push the monly called
parameters. There are three major ways of
flags and any registers used in a procedure directly in passing parameters to and from a procedure. Parame-
the procedure. This way we always know that the proce- ters can
be passed in registers, they can be passed in
dure can
be called from anywhere in the program with- dedicated memory locations, or they can be passed in
out losingthe contents of any registers. Another advan- stack locations. In the following sections we use three
tagethis
of approach is that you only have to write the versions of a simple program to show you how each of
pushes and pops once. A disadvantage is that in a situa- these methods work.
tion whereall the pushes are not needed, the procedure
may take a little longer to run. DEFINING THE PROGRAMMING PROBLEM

A common programming need is to convert a packed


BCD number such as 4596 to its binary or hexadecimal
Passing Parameters to and from Procedures equivalent. The hexadecimal equivalent of BCD 4596 is
Often when we call a procedure we want to make some 1 1F4H. for example. There are several ways to do this
data values or addresses available to the procedure. conversion, but to us the easiest is based on using the

m-596 = (4 x 1000) + (5 x 100) + <9 x 10) +(6xl)

1000 = 03E8H therefore ^000 = <4 x 3E8H = OFAOH

100 = 006^+H therefore 500 = 5 x 06-+H = OIFh-H

10 = 000AH therefore 90 = 9 x OOAH = 005AH

1 = 00001H therefore 6 = 6 x 001 H = 0006H

"4596 = 11F<4H

FIGURE 5-15 BCD-to-HEX or -BINARY algorithm.

120 C HAPTERFIVI
value oi each placeholdei in the BCD number Figure low -ei nibble we saved ill BL to the result in Al. to gi I I
5 15 shows the names and values for each digil m a hex total. The desired result is left in AL. Before return
4-dlgit BCD numbei such as 1596 Winn we write a ing In the main program we pop the registers we pushed
number such as iins n means thai we have a total ol I al i he start ol t he p 'dui e
thousands • 5 hundreds • 9 tens i (i units. To deter
mine the value ol ilns numbei in hexadecimal we jusl USING GINI RAI MEMORV l<> PASS
multiply the numbei in each diuit position by the value PARAMI I IRS
ol thai diuii position in hexadecimal and add up the re
1 "i i a les where we only have to pass a few p
suits rhe righl hand side of Figure 5 15 shows how this
and from a proi edure, registers are a ( onvenienl way to
works. The units position has a value ol I in hex so
do n However, in cases where we need to pass a large
multiplying ilns by <i units gives 0006H, Ihe tens posi
number ol parameters to a procedure "i in cases where
i ii Mi lias a value ol <)AI I- Multiplying this value by 9, the
we don i w . in i lo use registers, we use memory I'his
number ol lens, gives 005AH. The hex value ol the hun
memory may be a dedicated section ol general memory
el reds posi lion is 64H. When we multiply this value bj 5
or pari ol ihe stack. The following example show; i er
the number of hundreds, we gel 01 I'll I When we multi-
simple ease usin^ dedicated memory locations.
pi) the hex value ol the thousands position, 03E81 1, by 4
Figure ri I In shows a fragment ol a program that uses
[the number of thousands), we gel 0FA0H. Adding up
another version of oui BCD TO HEX procedure. In this
the results foi the 4 digits gives I 1 I'll 1 which is the hex
version the numbei lo be converted is stored in a dedi
equivalent oi 4596 BCD. You can use this method to
cated memory location named BCD INPUT and the hex
convert a BCD number with any number ol digits to its
result is returned from ihe procedure to a dedicated
binary equivalent, but to conserve space hen we will do
memory location called HEX VALUE.
it for |ust a l2-dis;it BCD numbei.
In ihe procedure we first push the Hays and all ot the
The algorithm for this program then is the simple se-
registers used in the procedure. We then copy the IM D
quence
operations.
ol
number into AL with the MOV AL, BCD 1NPUI instruc-
tion. From
here on Ihe pi ocedure is the same as the pre
Separate nibbles
vious version until we reach the point where we want lo
Save lower nibble (don't need to multiply by one) pass the hex result back to the calling program. Here we
use the MOV HEX VALUE, AL instruction to copy the re-
Multiply upper nibble by OAH sult the
to dedicated memory location we set aside foi it.
Add lower nibble to result of multiplication To complete the procedure we pop the flags and regis-
ters, and
return to the main program.
We want to implement this program as a procedure The approach used in Figure 5- 17a works in this
which can be called from anywhere in a mainline pro- case, but il has a severe limitation. Can you see what it
gram.our
For first version we pass the BCD number to is? The limitation is that this procedure will always look
the procedure in a register. to the memory location named BCD INPUT to get its
data and always put its result in the memory location
PASSING PARAMETERS IN REGISTERS called HEX VALUE. In other words, the way it is written
we can't easily use this procedure to convert a L3CD
Figure 5-16 shows our first version of a procedure to
number in some other memory location.
convert a 2-digit packed BCD number to its hex (binary)
equivalent. The BCD number is passed to the procedure
PASSING PARAMETERS USING POINTERS
in the AL register and the hex equivalent is passed back
to the calling program in the AL register. We start the A parameter passing method which overcomes the dis-
procedure by pushing the flag register and the other advantage
using ofdata item names directly in a proce-
registers we use in the procedure. Notice that we don't duretois pass the procedure a pointer to the desired
need to push and pop the AX register because we are data. Figure 5- 17b shows one way to do this. In the
using it to pass a value to the procedure and expecting main program before we call the procedure we use
the procedure to pass a different value back to the call- the MOV SI, OFFSET BCD INPUT instruction to set up
ing programin it. the SI register as a pointer to the memory location
Hopefully the function of the rest of the instructions BCDJNPUT. We also use the MOV Dl, OFFSE1
in the procedure are reasonably clear from the com- HEX VALUE instruction to set up the DI register as a
ments with
them. We first make a copy of the BCD in AL pointer to the memory location named HEX VALUE. In
so we have two copies to work on. We then mask the the procedure the MOV AL, (SI) instruction will copy the
upper nibble of one and save it in BL. Since multiplying byte pointed to by SI into AL. Likewise, the instruction
this nibble by one would not change its value, we are MOV [Dl], AL instruction later in the procedure will
done with it for now. We mask the lower nibble oi the copy the byte from AL to the memory location pointed
other copy of the BCD and rotate this nibble into the to by DI.
lower nibble position of the byte so we can multiply it This second approach which actually uses a combina-
correctly. When we multiply this nibble by the digit tionregisters
of and memory is more versatile because
weight of OAH. the result is left in the AX register. How- you can pass the procedure pointers to data anywhere in
ever, sincethe result can never be greater than 8 bits, memory. You can pass pointers to individual values or
we can disregard the contents ol AH. Finally, we add the pointers to arrays or strings. If you don't want to use

IF— THEN— ELSE STRUCTURES, PROCEDURES, AND MA( Wis 121


S086 PROGRAM FRAGMENT BCD TO HEX CONVERSION
ABSTRACT Program fragment that uses a procedure to convert
BCD numbers to HEX (binary). It shows how to use
AL register to pass parameters to the procedure
Not shown SS contains segment base for STACK_HERE
Not shown Initialization of segment registers
PORTS USED none
PROCEDURES USED: BCD HEX

DATA_HERE SEGMENT
BCD_ INPUT DB storage for BCD value
HEX_VALUE DB storage for binary value
DATA_HERE ENDS

CODE HERE SEGMENT WORD


ASSUME CS:CODE HERE, DS:DATA HERE, SS : STACK_HERE

MOV AL, BCD_ INPUT


CALL BCD_HEX
MOV HEX VALUE, AL store the result

PROCEDURE: BCD_HEX
Converts BCD numbers to HEX (binary), uses
registers to pass parameters to the procedure
SAVES: All registers used except AH

BCD_HEX PROC NEAR


PUSHF ; save flags
PUSH BX : and registers
PUSH CX
jstart conversion
MOV AH, AL save copy of BCD in AH
AND AH, OFH separate and save lower
MOV BL , AH BCD digit
AND AL, OFOH separate upper nibble
MOV CL , 0<4 move upper BCD digit to low
ROR AL, CL nibble position for multiply
MOV BH, OAH load conversion factor in BH
MUL BH upper BCD digit in AL * OAH in BH
r esu It in AX
ADD AL, BL add lower BCD to result of MUL
final result in AL

; end conversion, restore registers


POP CX
POP BX
POPF

RET
BCD_HEX ENDP
CODE_HERE ENDS
END

FIGURE 5-16 Example program passing parameters in registers.

122 CHAPTER FIVE


;8086 PROGRAM FRAGMENT BCD to HEX CONVERSION
; ABSTRACT: Program fragment that uses a procedure to convert BCD
numbers to HEX (binary). It shows how to use dedicated
memory locations to pass parameters to a procedure.
; no t shown - SS contains segment base for STACKHERE
;not shown - Initialization of segment registers
;PORTS USED : None
-.PROCEDURES USED: BCD_HEX
DATA HERE SEGMENT
BCD_INPUT DB ? storage for BCD value
HEX_VALUE DB ? storage for binary value
DATA_HERE ENDS
CODE HERE SEGMENT
ASSUME CS:CODE HERE, DS-.DATA HERE, SS: STACK HERE

intitial ization
CALL BCD HEX

PROCEDURE BCD_HEX
ABSTRACT : Converts BCD numbers to HEX, uses dedicated

memory locations for data


SAVES: All registers used

BCD HEX PROC NEAR


PUSH AX
PUSHF save flags
PUSH BX and registers
PUSH CX
Jget BCD value from named memory location
MOV AL, BCD INPUT
»do conversion
MOV AH, AL save copy of BCD in AH
AND AH, OFH separate and save lower
MOV BL, AH BCD digit
AND AL, OFOH separate upper nibble
MOV CL, 0^+ move upper BCD digit to low
ROR AL, CL nibble position for multiply
MOV BH, OAH load conversion factor in BH
MUL BH upper BCD digit in AL * OAH in BH
resul t i n AX
ADD AL, BL add lower BCD to result of MUL
final result in AL
; end of conversion now store Hex value in named memory location
MOV HEX VALUE, AL
POP CX restore flags and
POP BX r eg i ster s
POPF
POP AX
RET
BCD_HEX ENDP
C0DE_HERE ENDS
END

FIGURE 5-17 Example program passing parameters in named memory


locations, (a) Named memory location only. (6) More versatile approach using
pointers to named memory locations.

IF— THEN— ELSE STRUCTURES, PROCEDURES, AND MACROS 123


5 8086 PROGRAM FRAGMENT BCD to HEX CONVERSION
JABSTRACT Program fragment that uses a procedure to convert BCD
numbers to HEX (binary) . It shows how to use pointers
to pass parameters to procedure.
; no t shown - SS contains segment base for STACK_HERE
Jnot shown - Initialization of segment registers
; PORTS USED : None
PROCEDURES USED: BCD HEX

DATA HERE SEGMENT

BCD_INPUT DB ? storage for BCD value


HEX_VALUE DB 7 storage for binary value
DATA_HERE ENDS
CODE HERE SEGMENT
ASSUME CS:C0DE HERE, DS:DATA HERE, SS:STACK HERE

»put pointer to BCD in SI and pointer to HEX storage in DI


MOV SI, OFFSET BCD_INPUT
MOV DI, OFFSET HEX_VALUE
CALL BCD HEX

PROCEDURE BCD_HEX
ABSTRACT : Conver t s BCD numbers to HEX. Uses pointers
to get data parameters
SAVES: All reg isters used
BCD HEX PROC NEAR
PUSH AX ; save registers and flags
PUSHF
PUSH BX
PUSH
Jbyte in DS pointed to by SI is moved to AL
MOV AL, csi:
;do conversion
MOV AH, AL save copy of BCD in AH
AND AH, OFH separate and save lower
MOV BL, AH BCD digit
AND AL , OFOH separate upper nibble
MOV l L 0^ move upper BCD digit to low
ROR AL CL nibble position for multiply
MOV BH OAH load conversion factor in BH
MUL BH upper digit * OAH, result in AX
ADD AL, BL add lower BCD to result of MUL
MOV CD I : , AL move HEX value result in AL
to DS location pointed to by DI
POP C X restore registers and flags
POP BX
POPF
POP AX

RET
BCD_HEX ENDP
CODE HERE ENDS
END

FIGURE 3-17 tcontmucd)

124 CHAPTER FIVE


registers to pass the pointers, you can use memorj loi a address. In othei winds the BP registei can act as a sec
(kins dedicated specifically to holding the pointers In ond pointer to a location in the stack. This is how we
thai case the procedure will liisi huh the pointer and use 11 in on i example program here. In the procedure we
then use n to access the desired data. copy tin i onti nts ol the stack pointer registei to the BP
Foi many ol youi programs you will probably use reg legist. a with tin' MOV BP, SP instruction. BP then
istcis hi .1 combination ol registers and general memory points to the same location as the siark pointer. Now we
to pass parameters to procedures. However, for more use tin- \U >V AX, [BP + IJ| Instruction to copy the de
complex programs, such as those which allow several surd wind from the slack to AX I he 8086 will produce
users to time share a system, we often use the stack to the effective address lor this instrui tion by adding the
p.iss parameters to and from procedures. displacement ol 12. specified in the Instruction, to the
contents ol the BP register. The 0042H in Id' gives an
effective address ol 004EH. As you can see m Figure
PASSING PARAMETERS USING 1 Mi STACK
5-18b the effective address produced will he thai ol the
To pass parameters to a procedure using the stack we desired parameter. Note that this insliui tion dues not
push them on the stack somewhere in the mainline pro- change the contents ol BP. BP can then he used to ac-
gram before
we call the procedure. Instructions in the cess other
parameters on the stack by simply specifying
procedure then read these parameters from the stack. a differenl displacement in the instruction used to ac-
Likewise, parameters to be passed back to the calling cess the
parameter.
program are written to the stack by instructions in the Once we have the BCD number copied from the stack
procedure and lead ott the stack by instructions in the into AL, the instructions which convert it to hex are the
mainline. A simple example will best show you how this same as those in the previous versions. When we want
works. to put the hex value hack in the stack to return it to the
Figure 5- 18a shows a version of our BCD-to-hex pro- calling program, we again use BP as a pointer to the
cedure which
uses the stack for passing the BCD num- stack. The instruction MOV [BP +12], AX will copy AX to
ber the
to procedure and for passing the hex value back a stack location 1 2 addresses higher than that where BP
to the calling program. To save space here we assume is pointing. This of course is the same location we used
that previous instructions in the mainline set up a stack to pass the BCD number to the procedure. After we pop
segment, initialized the stack segment register, and ini- the registers and return to the calling program, the reg-
tialized
stack
the pointer. We also assume that previous isters will
all have the values they had before the CALL
instructions in the mainline have left the BCD number instruction executed. AX will contain the original BCD
in AL. Now in the mainline fragment in Figure 5- 18a we number and the stack pointer will be pointing to the hex
copy AX to the stack with the PUSH AX instruction. In a value now at the top of the stack. In the mainline we can
more complex example the BCD number or a pointer to now pop this hex value into a register with an instruc-
it would probably be put on the stack by a different tion suchas POP CX.
mechanism, but the important point for now is that the Whenever you are using the stack to pass parameters
parameter is on the stack for the procedure to access. it is very important to keep track of what you have
The CALL instruction in the mainline decrements the pushed on the stack and where the stack pointer is at
stack pointer by two. copies the return address on the each point in a program. We have found that diagrams
stack, and loads the instruction pointer with the start- such as the one in Figure 5- 18b are very helpful in doing
ing address of the procedure. PUSH instructions at the this. One potential problem to watch for when using the
start of the procedure save the flags and all of the regis- stack to pass parameters is stack overfJoiu. Stack over-
ters usedin the procedure on the stack. Before discuss- flow meansthat the stack fills up and overflows the
ing anymore instructions, let's take a look at the con- memory space you set aside for it. To see how this can
tentsthe
of stack alter these pushes. easily happen if you don't watch for it. consider the fol-
Figure 5- 18b shows how the values pushed on the lowing. Suppose that we use the stack to pass four word
stack will be arranged. Note that the BCD value is in the parameters to a procedure, but that we only pass one
stack at a higher address than the return address. After word parameter back to the calling program on the
the registers are pushed on the stack the stack pointer stack. Figure 5-19 shows a stack diagram for this situa-
is left pointing to the stack location where BP is stored. tion. Beforea CALL instruction the four parameters to
Now, the question is, how can we easily access the pa- be passed to the procedure are pushed on the stack.
rameterseems
that buried in the stack? One way is to During the procedure the parameter to be returned is
add 12 to the stack pointer with an ADD SP, OCH in- put in the stack location previously occupied by the
struction
the so stack pointer points to the word we fourth input parameter. Alter the RET instruction at the
want from the stack. A POP AX instruction could then be end of the procedure executes, the stack pointer will be
used to copy the desired word from the stack to AX. left pointing at this value. Now assume we pop this value
However, for a variety of reasons which we will explain into a register. The POP instruction will copy the value
later, we would like to be able to access the parameter to a register and increment the stack pointer by two.
without changing the contents of the stack pointer. The stack pointer now points to the third word we
The design of the 8086 makes it very easy to use the pushed to pass to the procedure. In other words the
base pointer register to do this. Remember from Chap- stack pointer is six addresses lower than it was when we
terthat
2 an offset in the BP register will be added to the started this process. Now suppose that we call this pro-
stack segment register to produce a physical memory cedure many times in the course of the mainline pro-

IF— THEN— ELSE STRUCTURES, PROCEDURES, AND MACROS 125


;8086 PROGRAM
; ABSTRACT : Program fragment that uses a procedure to convert
; BCD numbers to HEX (binary) . It shows how to use
; the stack to pass parameters to procedure.
;not shown - SS contains segment base for STACK_HERE
; not shown - Initialization of segment registers
;PROCEDURES USED: BCD HEX

DATA HERE SEGMENT


BCD_INPUT DB storage for BCD value
HEX_VALUE DB storage for binary value
DATA_HERE ENDS

CODE HERE SEGMENT


ASSUME CS:CODE _HERE, DS:DATA_HERE, SS : STACK^HERE
; initialize segments
MOV AL, BCD_INPUT ; move BCD value into AL
PUSH AX ; put BCD value on stack
CALL BCD HEX ; convert to binary
iprogram continues here with result of conversion on the top of stack

PROCEDURE BCD_HEX
ABSTRACT : converts BCD numbers to HEX (binary)
Takes its parameters from stack
SAVES: All registers used and flags
BCD HEX PROC NEAP
PUSH A> save registers and flags
PUSHP
PUSH B>
PUSH CX
PUSH BP save BP
MOV BP, SP copy SP into BP
MOV AX , CBP+12] copy BCD « from stack ft)
;do conversion
MOV AH, AL save copy of BCD in AH
AND AH, OFH separate and save lower
MOV BL , AH BCD digit
AND AL, OFOH separate upper nibble
MOV CL, 04 move upper BCD digit to low
ROR AL, CL nibble position for multiply
MOV BH, OAH load conversion factor in BH
MUL BH upper d 1 g l t*0AH , resu 1 t in AX
ADD AL, EL add lower BCD to result of MUL
"final result in AL
? end of conver ion now move HEX value from AL to location onto the stack
MOV CBF +12] , AX
POP BP ; restore registers
POP CX ; and flags and return
POP BX
POPF
POP A>
RET
BCD_HEX ENDP
CODE HERE ENDS
END

126 ER FI\E
STACK IN MEMORY rhe cure foi ilns potential problem is to use youi
M' stack diagrams to help you keep the stack balanced. You
0050H
need to keep the number ol pops equal to the numbei ol
BEFORE PUSH ftX
pushes 01 in some othei way make sun the stack
polntei gets back to its Initial location.
AFTER PUSH AX
Foi iliis example we could use an ADD SP, 06H in
struction after the POP instruction to gel the stack
pointer back up the additional six addresses to where II
was before we pushed the luui parameters on thi stack
For othei cases such as i his the 8086 Kl 1 instruction
has two tonus which help you to keep the Stack bal
.mi ed Remember from a previous section ol this chap-
ter thatthe 8086 has lour lor ins ol the Kl I instruction
The regulai neai RET instruction copies the return ,n\
dress from the stack to the instruction pointer and in-
crements
stackthe pointer by 2. The regular far KIT in-
struction copies
the return II' and C'S values from the
stack to IP and CS, and increments the slack pointer by
AFTER PUSH BP 4. The other two Kl I instruction forms perform the
same functions respectively, bul they also .uM a number
specified in the instruction to the stack pointer. The
near RET b instruction, for example, will first copy a
STACK SEGMENT BASE SS 7000H word from the stack to the instruction pointer and in-
crement
stack
the pointer by 2. It will then add (i more to
the stack pointer. This is a quick way to skip the stack
pointer up over some old parameters on the stack.

SUMMARY OF PASSING PARAMETERS TO AND


FIGURE 5-18 Example program passing parameters on
FROM PROCEDURES
the stack, (a) Assembly- language program, to) Stack
diagram. You can pass parameters between a calling program and
a procedure using registers, dedicated memory loca-
tions,theor stack. The method you choose depends
gram. Each time we push four words on the stack but
largely on the specific program. There are no hard rules,
only pop one word off. the stack pointer will be left six
but here are a few guidelines. For simple programs with
addresses lower than it was before the process. The top
just a few parameters to pass, registers are usually the
of the stack will keep getting moved downward. When
easiest to use. For passing arrays or other data struc-
the stack pointer gets down to 0000H. the next push will
tures
andto from procedures you can use registers to
roll it around to FFFEH and write a word at the very top
pass pointers to the start of these data structures. As we
of the 64 Kbyte stack segment. If you overlapped seg-
explained previously, passing pointers to the procedure
ments
youas usually do in a small system, the word may
is a much more versatile method than having the proce-
get written in a memory location that you are using for
dure access the data structure directly by name.
data or your program code and your data or code will be
For procedures in a multiuser-system program, proce-
lost! This is what we mean bv the term stack overflow.
dures that
will be called from a high level language pro-
gram,procedures
or that call themselves, parameters
STACK IN MEMORY should be passed on the stack. When writing programs
which pass parameters on the stack you should use
stack diagrams such as the one in Figure 5- 18b to help
BEFORE PUSH 0050H
you keep track of where everything is in the stack at a
AFTER PUSH 1 004EH %
particular time. The following section will give you some
additional guidance as to when to use the stack to pass
AFTER PUSH 2 004CH parameters, and it will give you some additional practice
following the stack and stack pointer as a program exe-
AFTER PUSH 3 004AH - cutes.

AFTER PUSH 4 0048H Reentrant and Recursive Procedures


The terms reentrant and recursive are often used in
AFTER CALL 0046H
microprocessor manufacturers' literature, but seldom
illustrated with examples. Here we try to give these
terms some meaning for you. You should make almost
FIGURE 5-19 Stack diagram showing cause of stack all of the procedures you write reentrant, so read that
overflow. section carefully. You will seldom have to write a recur-

IF— THEN— EfSE STRUCTURES, PROCEDURES, AND MACROS 127


sive procedure so the main points to look for in that stack to hold parameters. To see why this second point
section are the definition of the term and the operation is necessary, let's take another look at the program
of the stack as a recursive procedure operates. in Figure 5- 17a. This program uses the named vari-
ables BCD_INPUT and HEX_VALUE. The procedure
REENTRANT PROCEDURES BCD TO HEX accesses these two directly by name.
Now. suppose that the 8086 is in the middle of execut-
The 8086 has a signal input which allows a signal from
ing theBCD TO HEX procedure and an interrupt oc-
some external device to interrupt the normal program
curs. Further suppose that the interrupt service proce-
execution sequence and call a specified procedure. In
dure loadssome new value in the memory location
our electronics factory, for example, a temperature sen-
named BCD INPUT, and calls the BCDTO HEX proce-
sor in
a flow-solder machine could be connected to the
dure again. The initial value in BCD INPUT has now
interrupt input. If the temperature gets too high, the
been written over. If the interrupt occurred before the
sensor sends an interrupting signal to the 8086. The
first execution of the procedure had a chance to read
8086 will then stop whatever it is doing and go to a pro-
this value in. the value will be lost forever. When execu-
cedure which takes whatever steps are necessary to cool
tion returns to BCD TO HEX after the interrupt service
down the solder bath. This procedure is called an inter-
procedure, the value used for BCD INPUT will be that
rupt serviceprocedure. Chapter 8 discusses 8086 inter-
put there by the interrupt service routine instead of the
rupts andinterrupt service procedures in great detail,
desired initial value. There are several ways we can han-
but it is appropriate to introduce the concept here.
dle theparameters so that the procedure BCD TO HEX
Now, suppose that the 8086 was in the middle of exe-
is reentrant.
cuting
multiply
a procedure when the interrupt signal
occurred, and that we also need to use the multiply pro-
The first is to simply pass the parameters in registers
cedurethe in interrupt service subroutine. Figure 5-20
as we did in the program in Figure 5-16. If this form of
shows the program execution flow we want for this situ- the procedure is called by an interrupt service proce-
dure,ofallthe variables will be saved by push instruc-
ation. When the interrupt occurs, execution goes to the
interrupt service procedure. The interrupt service pro-
tionsthe
at start of the procedure and they will be re-
cedure then
calls the multiply procedure when it needs
stored
popby instructions before returning to complete
it. The RET instruction at the end of the multiply proce-
the first execution.
A second method of making the BCD_TO_HEX proce-
dure returnsexecution to the interrupt service proce-
durespecial
A return instruction at the end of the in-
dure reentrantis to pass pointers to the data items in
terrupt service procedure returns execution to the registers as we did in the program in Figure 5- 17b.
Again, anything in registers will be saved by push in-
multiply procedure where it was executing when the in-
terrupt occurred. The multiply procedure must be writ-
structions
restored
and by pop instructions when the
ten suchthat it can be interrupted, used, and "reen- procedure is called by the interrupt service routine.
Usually at this point someone remembers that the
tered" withoutlosing or writing over anything. A
8086 allows you to push the contents of a memory loca-
procedure which can function in this way is said to be
tion on
the stack and asks. "Why can't I just save the
reentrant.
contents of BCD INPUT on the stack with a PUSH
To be reentrant a procedure must first of all push the
BCD INPUT instruction?" You can do this, but if an in-
flags and all registers used in the procedure. Also, to be
terrupt occurs
before this instruction occurs, you still
reentrant a program should use only registers or the
have the problem.
The third way to make the BCD TO HEX procedure
reentrant is by passing parameters on the stack as we
did in the version in Figure 5-18. In this version the
mainline pushes the BCD number on the stack and
then calls the procedure. The procedure pushes regis-
ters on
the stack and accesses the BCD number relative
to where the stack pointer ends up. If an interrupt oc-
curs, the
interrupt service procedure will push on the
stack the BCD number it wishes to convert and call
BCD TO HEX. This BCD number will be pushed on the
NEXT MAINLINE
stack at a different location from the first BCD number
INSTRUCTION that was pushed. Since everything is saved on the stack
AFTER CALL no matter where the interrupt occurs, the first execu-
tionthe
of procedure will produce correct results when
it is reentered.
If you are writing a procedure that you may want to
call from a program in a high-level language such as
Pascal, PL/M, or C, then you should definitely use the
stack for passing parameters because that is how these
languages do it. Check the manual for the high-level lan-
FIGURE 5-20 Program execution flow for reentrant guage
determine
to the parameter passing conventions
procedure. for that language.

128 CHAPTER FIVt


Kit URSIVI PRO( I Di Rl S RE( URSIVI PR( )( I Dl Rl I XAMPI I Alt, OKI I MM

A recursive procedure is a pro< edure which calls itself. The problem we have chosen to soke is to compute the
This seems simple enough, but the question you maj be factorial ol a given numbci In the range ol 1 to 9 The
thinking is. \\h\ would we wanl .1 procedure to call 11 factorial ol a number is the product ol the numbei and
self?" I he answer is thai certain types ol problems, such all ol the positive Integers less than the numbei F01
.is choosing the nexl move in .1 computer chess pro example, 5 factoi lal is equal to 5 I I. The
gram, can hesi be solved with .1 recursive procedure. word factorial is often represented with "!". v
Recursive procedures are used to work with complex ibei efore wi ite 5 factoi ial as r>!.
data structures called trees. Ii is unlikely thai you will Whal we wanl to do here is write a recursive procedure
have id write .1 recursive procedure because mosl <>lthe which will compute the factorial ol a number. N, which
programming problems thai you are likely to encounter we pass 10 ii on the stack, and pass the factorial ba< k to
can be solved with a simple WHILE DO 01 REPEA1 the calling program on the stack. The basic algorithm
UNTIL approach. You should, however, know what the can be expressed very Simply as: [F N 1 THEN
term means when you encounter it. For those "I you factorial 1, ELSE factorial M % (factorial ol N II.
who wish to know more about how a recursive proc< rhis says that if the numbei we pass to the pro< edure is
dure works, we have included an example in the follow- 1. the procedure should return the factorial of 1 which

ing set
lions. is 1. If the number we pass is not I, then the procedure
Most of the examples of recursive procedures thai we should multiply this number by the factorial of the
could think of are too complex to show here Therefore, number minus one. Now here's where the recursion
to show you how recursion works, we have chosen a comes in. Suppose we pass a 3 to the procedure. When
simple problem which could be solved without recur- the procedure is hist called it has the value of 3 for N,
but it does not have the value for the factorial of N - 1
sion

ROCEDURE
FACTO

CALL FACTO
( )

GET N

PROCEDURE PROCEDURE PROCEDURE


FACTO FACTO FACTO 1 i( FACTORIAL
- 1
DECREMENT
CALL FACTO N

NEXT MAINLINE f
INSTRUCTION RETURN

CALL
FACTO

MULTIPLY
PROCEDURE FACTO W-D!
IF N 1 THEN % PREVIOUS N
FACTORIAL = 1
RET
ELSE
REPEAT
DECREMENT N RETURN
CALL FACTO
UNTIL N = 1
MULTIPLY (N - 1)i % PREVIOUS N
RET

I. )

FIGURE 5-21 Algorithm for program to compute factorial for a number N


between 1 and 9. (a) Flow diagram for N = 1. (b) Flow diagram tor N = i. (c)
Pseudocode, (d) Flowchart.

IF— THEN— ELSE STRUCTURES, PROCEDURES, AND MACROS 129


that it needs to do the multiplication indicated in the structions
return to an error message if the number
algorithm. The procedure solves this problem by calling passed to the procedure is out of this range. Figure
itself to compute the needed factorial of N - 1. It calls 5-22b shows, with a stack diagram, how the stack will
itself over and over until the factorial of N - 1 that it has be affected if this procedure is called with an N of 3.
to compute is the factorial of 1. When working your way through a recursive procedure
Figure 5-2 1 shows in several ways how we can repre- or any procedure which uses the stack extensively, a
sent this
process. In the program flow diagram in Figure stack diagram such as this is absolutely necessary to
5-2 la you can see that if the value of N passed to the keep track of everything.
procedure is 1 then the procedure simply loads 1 in the The first parts of the program are housekeeping
stack location reserved for N! and returns to the calling chores we described in some previous examples. We
program. Figure 5-215 shows the program flow that will start the mainline program by declaring a stack seg-
occur when the number passed to the procedure is some ment and
setting aside a stack of 200 words with a label
number other than one. If we call the procedure with an at the top of the stack. The first three instructions in the
N of 3, the procedure will call itself to compute N - 1 ! or code segment of the mainline program initialize the
2! It will then call itself again to compute the value of the stack segment register and the stack pointer register.
nextN - 1 factorial or 1 !. Since 1 ! is 1 the procedure will The SUB SP,04 instruction after this will decrement the
return this value to the program that called it. In this stack pointer register by 4. In other words we skip the
case the program that called it was a previous execution stack pointer down over 2 words in the stack. These two
of the same procedure that needed this value to compute word locations will be used to pass the computed facto-
2! Given this value it will compute 2! and return the rial fromthe procedure back to the mainline program.
value to the program that called it. Here again the pro- Next we load the number whose factorial we want into
gram that
called it was a previous execution of the same AX and push the value on the stack where the procedure
procedure that needed 2! to compute the factorial of 3. will access it. Now we are ready to call the procedure. We
Given the factorial of 2 this call of the procedure can have given the procedure the name FACTO with the
now compute the factorial of 3 and return to the pro- FACTO PROC NEAR and FACTO ENDP directives. The
gram that
called it. For the example here the return now procedure is near because it is in the same code seg-
will be to the mainline program. menttheas instruction which calls it.
Figure 5-2 lc shows how we can represent this algo- At the start of the procedure we save the flags and all
rithmslightly
in expanded pseudocode. Use the pro- the registers used in the procedure on the stack. Take a
gram flow
diagram in Figure 5-2 lb to help you see how look at Figure 5-22b to see what is on the stack at this
execution continues after the return when N = 1 and point. Note that the value of N is buried 10 addresses up
N = 3. Can you see that if N is initially 1 the first return the stack from where the stack pointer was left after BP
will return execution to the instruction following CALL was pushed. To access this buried value we first copy SP
FACTO in the mainline':' If the initial N was 3, for exam- to BP with the MOV BP, SP instruction so that BP points
ple, this return will return execution back to the in- to the top of the stack. We can then use the expression
struction the
after call in the procedure. Likewise, the (BP + 10] to refer to the address where N was pushed.
return after the multiply can send execution back to the The MOV AX, (BP + 101 instruction will copy N from the
next instruction after the call or back to the mainline if stack to AX. If the value of N read in is 1 then the facto-
the final result has been computed. rial is1. We want to put 0000000 1H in the stack loca-
Figure 5-21d shows a flowchart for this algorithm tions reserved
we for the result, restore the registers and
Note that the flowchart shows the same ambiguity return to (he mainline program. Follow this path
about where the return operations send execution to. through the program in Figure 5-22a. Note how the
MOV WORD PTR [BP + 12], 0001H instruction is used to
load a value to a location buried in the stack. The WORD
ASSEMBLY LANGUAGE RECURSIVE FACTORIAL
PTR directives tell the assembler that you want to move
PROCEDURE
a word to the specified memory location. Without these
Figure 5-22a shows an 8086 assembly language proce- directives the assembler will not know whether to code
dure whichcomputes the factorial of a number in the the instruction for moving a byte or for moving a word.
range of 1 to 9. To save space we have not included in- The MOV WORD PTR [BP + 14], 0000H instruction is

5 8086 PROGRAM
;ABSTRACT : This program computes the factorial of a
number between 1 and 9
;PORTS USED : None
5 PROCEDURES USED: FACTO

STACK_HERE SEGMENT STACK


DW 200 DUP<0) set aside 200 words for stack
STACK_TOP LABEL WORD assign name to word above stack top
STACK HERE ENDS

130 CHAPTtK FIVh


NUMBER EQU 03

CODE_HERE SEGMENT
ASSUME CS:CODE_HERE, SS : STACKHERE
MOV AX, STACK_HERE ; initialize stack segment register
MOV SS, AX
MOV SP, OFFSET STACK_TOP ; initialize stack pointer

SUB SP, 000^+H ; make space in stack for factorial


; to be returned

MOV AX, NUMBER ; put number to be passed on stack


PUSH AX
CALL FACTO ; compute factorial of number
POP AX ; get result
NOP ; simulate next mainline instructions
NOP
NOP

PROCEDURE: FACTO
ABSTRACT : Recursive procedure that computes the factorial of
a number. It takes its parameter from the stack and
returns the result on the stack.
SAVES : all registers used

FACTO PROC NEAR


PUSHF save flags and registers on stack
PUSH AX
PUSH DX
PUSH BP
MOV BP, SP point BP at top of stack
MOV AX , cbp+io: copy number from stack to AX
CMP AX, 0001H if number not egual 1 then go on
JNE G0_0N and compute factorial
MOV WORD PTR CBP+123, 0001H ; else load factorial of one in
MOV WORD PTR CBP+1^3, 0000H ; stack and return to mainline
JMP EXIT
GO ON: SUB SP, OOO^tH make space in stack for preliminary
f ac tor i al
DEC AX decrement number now in AX
PUSH AX save number - 1 on stack
CALL FACTO compute factorial of number - 1
MOV BP, SP point BP at top of stack
MOV AX, CBP+2] last (N-l>! from stack to AX
MUL WORD PTR CBP+163 multiply by previous N
MOV CBP+1B3, AX copy new factorial to stack
MOV CBP+20 3, DX
ADD SP, 0006H point stack pointer at pushed register
EXIT POP BP restore registers
POP DX
POP AX
POPF
RET
FACTO ENDP
CODE_HERE ENDS
END
FIGURE 5-22 Recursive procedure to calculate factorial
of number between 1 and 9. (a) Assembly language, (b)
Stack diagram showing contents of stack for N = 3.

IF— THEN— ELSE STRUCTURES, PROCEDURES, AND MACROS 131


STACK IN MEMORY .V - 1 that we read in at this point is equal to 2. Since
NOTE EACH BOX IN THIS
SP STACK DIAGRAM this value is not 1 execution will again go to the label
REPRESENTS A WORD GO ON. The SUB SP, 04 instruction will again skip the
0080H
stack pointer down over four addresses to leave space for
007 EH \ HIGH :. R 3 4-BYTE SPACE RESERVED
(2 - 1)! to be returned by FACTO. We decrement N by 1
FOR FINAL FACTORIAL
007CH A/' LOW WORD
to get N — 1. which is now 1. We push this value on the
007AH — SP AFTER FINAL RET stack and call FACTO to compute the factorial of 1 .
0078H Alter pushing all the registers on the stack FACTO
0076H reads this 1 from the stack with the MOV AX, [BP + 10]
0074 H instruction. When the CMP AX, 0001 H instruction in

007 2 H
FACTO finds that the number passed to it is 1, FACTO
loads a factorial value of 1 in the four memory locations
0070H SP AFTER ^6 BALANCE
we most recently set aside for a returned factorial. The
006 EH
4-BYTE SPACE FOR (/V - l)i MOV WORD PTR [BP + 12], 0001 and the MOV WORD
006CH
PTR [BP + 14], 0000 instructions do this. Look at the
006 AH — SP AFTER SECOND RET
stack diagram in Figure 5-22b to see where these four
0068H
locations are in the stack. FACTO will then do a return
0066 H to the next instruction after the CALL instruction that
0064 H called it.
0062 H Now in this case FACTO was called from a previous
0060H — SP AFTER +6 BALANCE execution of FACTO so the return will be to the MOV
005 EH BP.SP instruction after CALL FACTO. The MOV BP, SP
4-BYTE SPACE FOR IN - 1)
005CH instruction points BP at the top of the stack so that we
can access data on the stack without affecting the stack
005AH — SP AFTER FIRST RET
pointer. The MOV AX, [BP + 2[ instruction after this
0058H
copies the low word of the last computed (N - 1)! from
0056 H
the stack to AX so that we can multiply it by N. We only
0054 H
need the lower word of the two we set aside for the facto-
0052 H rial, because for an .V of eight or less, only the lower word
0050 H SP AFTER LAST CALL will contain data. Restricting the allowed range of N for
AND PUSHES
004EH this example means that we only have to do a 16-bit by
16-bit multiply. We could increase the allowed range of N
by simply setting aside larger spaces in the stack for fac-
torials and
including instructions to multiply larger
numbers. In this example the MUL WORD PTR [BP + 161
FIGURE 5-22b Stack diagram showing contents ot stack instruction multiplies the (N - 1 )! in AX by the previous
for N = 3. N from the stack. The low word of the product is left in
AX and the Inuli word of the product is left in DX. The
MOV [BP + 18], AX and the MOV [BP + 20], DX instruc-
tions copy
these two words to the stack locations we re-
likewise used to move a word value to the other word served
thefor next factorial. Now take a look at the stack
loi ,iiiMn reserved in the stack for the factorial. diagram in Figure 5-22b to see where these two words
Now let's see what happens it the number passed to get put and where the stack pointer is at this time. The
FACTO is a 3. The CMP AX, 0001H instruction and the next operation we would like to do in the program is pop
JNE GOON instructions determine that N is not 1 and the registers and return. As you can see from Figure
send execution to the SUB SP, 04H instruction. Accord- 5-22b. however, the stack pointer is now pointing at
ing to
the algorithm we are going to find the value of N! some old data on the stack, not at the first register we
by multiplying N times the value of (A' - 1 1'. We will be want to pop. To get the stack pointer pointing where we
calling FACTO again to find the value of (IV - 1)!. TIS- want it. we add six to it with the ADD SP.06H instruc-
SUES04H
SP, instruction skips the stack pointer down tion. Then
we pop the registers and return.
over four addresses in the stack. The value of (3 - 1]! To see where we are returning to. take another look at
will be returned in these locations. We then decrement N Figure 5-22b. We are returning with 2! in the stack so
by one and push the value of JV - 1 on the stack where we still have one more computation to produce the de-
FACTO will access it. sired Therefore,
3!. the return is again to the MOV BP,
When we call FACTO now to compute the value of SP instruction after CALL in FACTO. The instructions
(N - 1)! the registers and flags will again be pushed on after this will multiply 2! times 3 to produce the desired
the stack. Take another look at Figure 5-22b to see what 3!. and copy 3! to the stack as described in the preceding
is on the stack at this point. The value of N - 1 that we paragraph. The ADD SP.06H instruction will again ad-
need is again buried 10 addresses up in the stack. This just thestack pointer so that we can pop the registers
is no problem because the MOV BP, SP and MOV \\ and return. Since we have done all the required compu-
[BP + 10] instructions will allow us to access the value. tations,time
this the return will be to the mainline pro-
We started with N 3 for this example, so the value of gram. The
desired result. 3!. will be in the memory loca-

132 ( HAPTtR FIVE


tions we reserved for n In the sta< k We t an access this sei i s shi iw you how to put these needed addltl
result with a BP addressing mode when we need the your programs the lnsi case we will describe is one
value In the mainline where the procedure is m the same assembly module,
It you work youi way through the How ol the stack and liui it is in a segmenl with a different name than the
the stack pointer in tins example program, you should segment thai contains the ( All Instruction.
have a good understanding ol how the stack is used
ACCESSING A PROCEDURI IN ANOTHER
SECMEN1
Writing and Calling FAR Procedures Suppose thai in a program we want to put all of the
mainline in one logical segment and we want to pul sev
INTRODUCTION AND OVERVIEW
ci. il procedures in another logical segmenl to keep them
A far procedure is one which is located in a different separate. Figure 5-23 shows some program fragments
segment from the CA1 1 instruction which calls it. To gel which Illustrate this situation. For this example our
to the starting address of a far procedure the 8086 must mainline instructions are in a segment named
change the contents of both the code segment register CODE HERE:. A procedure (ailed MULTIPLY 32 is in a
and the contents ol the instruction pointer. Therefore, it segment named PROCEDURES HERE. Since the proce
you are hand coding a program which calls a far proce- dure is in a different segment from the CALL instruction
dure, make
sure to use one of the intersegment forms of we must change the contents of the code segment regis-
the CALL instruction to do this. You might, for example, ter to
access it. Therefore, the procedure is far.
use the direct intersegment CALL instruction. II you We let the assembler know that the procedure is far by
look at the coding template for this instruction you will using the word FAR in the MULTIPI Y ?2 PROC FAR state-
see that the destination instruction pointer value is ment. When
the assembler finds that the procedure is
coded in as bytes 2 and 3 of the instruction, and the declared as far. it will automatically code the CAI I in-
destination code segment register value is coded in as struction
an asintersegment CALL.
bytes 4 and 5 of the instruction. Likewise, at the end of a Now the remaining thing we have to do, so that the
far procedure, both the contents of the code segment program gets assembled correctly, is to make sure that
register and the contents of the instruction pointer the assembler uses the right code segment for each part
must be popped off the stack to return to the calling of the program. We use the ASSUME statement to do
program. Make sure to use one of the intersegment this. At the start of the mainline we use the statement
forms of the RET instruction to do this. ASSUME CS:CODE HERE to tell the assembler to com-
If you are using an assembler to assemble a program pute the
offsets of the following instructions from the
containing a far procedure, there are a few additional segment base named CODE HERE. At the start of the
directives you have to give the assembler. The following procedure we use the ASSUME CS: PROCEDURES HERE

CODE_HERE SEGMENT

ASSUME CS:C0DE_HERE, DS : DATA_HERE , SS : STACK_HERE

CALL MULTIPLY_32

C0DE_HERE ENDS

PRQCEDURES_HERE SEGMENT

MULTIPLY_32 PROC FAR

ASSUME CS: PROCEDURES HERE

MULTIPLY 32 ENDP

PROCEDURES_HERE ENDS
FIGURE 5-23 Program additions needed for a far procedure.

IF—THEN— ELSE STRUCTURES, PROCEDURES, AND MACROS 133


statement to tell the assembler to compute the offsets the division, remember, is put in AX and the remainder
for the instructions in the procedure. The assembler will is put in DX. However, if the quotient is larger trian 16
then compute these offsets starting from the segment bits as it will be for our scaling, the quotient will not fit
base named PROCEDURES HERE. in AX. In this case the 8086 will automatically respond
When the assembler finally codes out the CALL in- in the same way that it would if you tried to divide a
struction,
will put
it the value of PROCEDURES. HERE number by zero. We will discuss the details of this re-
in for CS in the instruction. It will put the offset sponse
Chapter
in 8. For now it is enough to say that we
of the first instruction of the procedure in don't want the 8086 to make this response. The simple
PROCEDURES HERE as the IP value in the instruction. solution we came up with is to do the division in two
To summarize then, if a procedure is in another seg- steps in such a way that we get a 32-bit quotient and a
ment you
must declare it far with the FAR directive. Also 16-bit remainder.
you must put an ASSUME statement in the procedure to Our algorithm is a simple sequence of actions very
tell the assembler what segment base to use for the in- similar to the way we were taught to do long division. We
structions
the inprocedure. will first describe how this works with decimal numbers
and then we will show how it works with 32-bit and
ACCESSING A PROCEDURE AND DATA IN A 16-bit binary numbers. Figure 5-24a shows an example
SEPARATE ASSEMBLY MODULE of long division of the decimal number 433 by the deci-
mal number 9. The 9 won't divide into the 4. so we put a
As we have discussed previously, the best way to write a 0 or nothing in this digit position of the quotient. We
large program is as a series of modules. Each module then see if 9 divides into 43. It fits 4 times, so we put a
can be individually written, assembled, tested, and de- 4 in this digit position of the quotient and subtract 4 x
bugged. Working modules can then be linked together. 9 from the 43. The remainder of 7 now becomes the high
The previous section showed you how to access a proce- digit of the 73, the next number we try to divide the 9
durethein same assembly module, but in a different into. After we find that the 9 fits 8 times and subtract
segment from the CALL instruction. Here we show you 9x8 from the 73, we are left with a final remainder of 1 .
how to write your programs so that they can access data Now let's see how we do this with large binary numbers.
or procedures in another assembly module.
As shown in Figure 5-24b we first divide the 16-bit
In order for a linker to be able to access data or a pro-
divisor into a 32-bit number made up of a word of all O's
cedure
another
in assembly module correctly, there are
and the high word of the dividend. This division gives
four major types of information that you must give the
us the high word of the quotient and a remainder. The
assembler. We will give you an overview of these four and
remainder becomes the high word of the dividend for
then show with a program example how you actually
the next division, just as it did for the decimal division.
write them.
In the assembly module which contains the calling
program you must use the EXTRN directive to tell the 048 R1
assembler the names of any procedures or data items
that are in other assembly modules. Also, in the module
9) 433
36
that contains the calling program you must use the
PUBLIC directive to tell the assembler any labels or data 73

items that will be accessed from another assembly mod- 72


ule. 1

In the assembly module which contains the procedure


(a!
you must likewise use the EXTRN directive to tell the
assembler the names of any labels or data items that it
must look for in another assembly module. Also in the
QUOTIENT QUOTIENT
assembly module that contains the procedure you must
HIGH WORD LOW WORD
use the PUBLIC directive to tell the assembler that a
label or data item will be accessed from another assem-
bly module.
DIVISOR 16 BITS DIVIDEND DIVIDEND
16 BITS 0000 H HIGH WORD LOW WORD
PROBLEM DEFINITION AND ALGORITHM
DISCUSSION
REMAINDER DIVIDEND
The procedure in the following example program was
WORD LOW WORD
written to solve a small problem we encountered when
writing the program for a microprocessor-controlled
medical instrument. Here's the problem. REMAINDER
In the program we add up a series of values read in SECOND DIV WORD
(FINAL
from an A/D converter. The sum is an unsigned number
of between 24 and 32 bits. We needed to scale this value
by dividing it by 10. This seems easy because the 8086
DIV instruction will divide a 32-bit unsigned binary FIGURE 5-24 Algorithm for smart divide procedure, (a)
number by a 16-bit binary number. The quotient from Decimal analogy, (b) 8086 approach.

134 CHAPTER FIVE


We move the low word ol the original dividend In as 11it- is Identified as an external label ol type fai found In a
low word ol tins dividend and divide by the 16 bit divi si gmenl named PROCEDURES HERE
soi again Hie 16 bil quotienl from this division is the Now Ids see how we handle EXTRN and I'! BLIC in
low won I nt the 32 I >ii quotienl we want. The 16-bil final the procedure module The procedure at cesses the data
remaindei can be used to round off the quotienl oi be iii in named DIVISOR which is defined in the mainline
discarded, depending on the application. module Therefore, we musl use the statemenl IXIKN
DIVISOR:WORD to tell the assemblei thai DIVISOR, a
data item ol type word, will lie found in some othei mod
INI ASM \li;n I \NC.UAC.I PROGRAM ule. Furthermore we enclose the EXTRN statement with
Figure 5 25a shows the mainline ol a program which the DATA HERI SEGMENT PUBLK and DATA HERI I M >s
calls the procedure shown In Figure 5-25b winch imple- statements to tell the assembler that DIVISOR will he
mentsdivision
our algorithm. We wrote these two .is found in a segmenl named DATA HERE.
separate assembly modules so thai we could show you N( HI II we had needed to also access DIVIDEND we
whai you need to add to each module in order for the could have written the EXTRN statement as IXIKN
modules to be linkable. Let's look closely al these added DIVISOR:WORD, DIVIDEND:WORD. To add more
parts before we discuss the actual division procedure. terms, jusl separate them with a comma.
The first added part ol the program to look al is in the
statement DATA HERI sic, MINI WORD PUBLIC. The The procedure SMART DIVIDE must be accessible
woid PUBLIC in this statement tells the assembler thai from other modules so we declare it public with the
the contents of this segment will be added to the con- PUBLIC SMART DIVID1 statement in the procedure
tentsa olsegment with the same name m another as- module. If we needed to make other labels or data items
sembly module
when the two modules are linked. In public, we could have listed them separated by commas
other words, it two or more assembly modules have after PUBLIC SMART DIVIDE. An example is PUBLK
PUBLIC segments named DATA HKRE. their contents SMART DIVIDE, FXII
will be pulled together in successive memory locations Now that we have explained the use of PUBLIC and
when the program modules are linked. You should then EXTRN, let's work our way through the rest of the pro-
declare a segment PUBLIC anytime you want it to be gram. theAt start of the mainline the ASSUME state-
linked with other segments of the same name in other ment tells
the assembler which logical segments to use
modules. as code. data, and stack. We then initialize the data seg-
The next addition to look at is the statement PUBLIC ment, stack
segment, and stack pointer registers as de-
DIVISOR in the mainline module in Figure 5-25o. This scribed
previous
in example programs. Now before call-
statement is necessary to tell the assembler that the ing the
SMART DIVIDE procedure we copy the dividend
data item named DIVISOR will be accessed from some and divisor from memory to some registers. The divi-
other assembly module or modules. Essentially what we dend and the divisor are passed to the procedure in
are doing here is telling the assembler to put the offset of these registers. As we explained in a previous section, if
DIVISOR in a special table where it can be accessed we pass parameters to a procedure in registers, the pro-
when the program modules are linked. Whenever you cedure not
does have to refer to specific named memory
want a named data item or a label to be accessible from locations. The procedure is then more general and can
another assembly module you must declare it as PUBLIC. more easily be called from any place in the mainline.
Note in the table at the end of the assembler listing that However, in this example we referenced the named
DIVISOR is global. This is the assembler's way of telling memory location, DIVISOR, from the procedure to show
you that it can be accessed from other modules by the you how it can be done using the EXTRN and PUBLIC
linker. directives. The procedure is of type far so when we call
The other side of this coin is that, when you need to it. both the code segment register and the instruction
access a label or a named data item in another module, pointer contents will be changed.
you must use the EXTRN directive to tell the assembler In the procedure we first check to see if the divisor is
that the label or data item is not in the present mod- zero with a CMP DIVISOR, 0 instruction. If the divisor is
ule. Inthe example program the statement EXTRN zero the )E instruction will send execution to the label
SMART DIVIDErFAR tells the assembler that we will be ERROR EXIT. There we set the carry flag with STC as
accessing a label or procedure of type far in some other an error indicator and return to the mainline program. II
assembly module. For this example we will be accessing the divisor is not zero, then we go on with the division.
our procedure. SMART DIVIDE. We enclose the EXTRN To understand how we do the division, remember that
statement with the PROCEDURES HERE PUBLIC and the the 8086 DIV instruction divides the 32-bit number in
PROCEDURES HERE ENDS statements to tell the assem- DX and AX by the 16-bit number in a specified register
bler thatthe procedure SMART DIVIDE is located in the or memory location. It puts a 16-bit quotient in AX and
segment PROCEDURES HERE. There are some cases a 16-bit remainder in DX. Now. according to our algo-
where these statements are not needed, but we have rithmFigure
in 5-24b we want to put 0000H in DX and
found that bracketing the EXTRN statement with the high word of the dividend in AX for our first DIV
SEGMENT— ENDS directives in this way is the best way operation. MOV BX, AX saves a copy of the low word of
to make sure that the linker can find everything when it the dividend for future reference. MOV AX, DX copies
links modules. As you can see in the table at the end of the high word of the dividend into AX where we want it.
the assembler listing in Figure 5-25a. SMART DIVIDE and MOV DX, 0000H puts all O's in DX. After the first DIV

IF— THEN— ELSF STRUCTURES, PROCEDURES, AND MACROS 135


The IBM Persons! Cosputer MACROAssembler 02-19-85

;-GE ,132
Program
;ABSTRACT: Thi e prograji divides a 32-bit number bv a 16-bit nunbi
; to give a 32-bit quotient and a 16-bit resainder.
REGISTERS USED:CS. DS, 3S, AX. 5P. BX, Cx, BX
[PROCEDURES: Calls SHART_DIVIBE
^nich is e far procedure
;P0PTb USED: None

0000 DATA_HERE SEGMENTWORD


PUBLIC
0000 *03B 8C72 }] [BEND Dii *03BH, 3C~5H ; dividend SC72403BH
000=1 569S BIVISGR BU 5692H ; 16-bit divisor
DATfi HERE ENBE5

i10RE_BATA SEGMENTWORD
QUOTIENT DW I -

00 14 , ,(, REMAINDERDU
0006 MOREDATA ENDS

00( STAC* HERE SEGMENT STAG


0000 6: D« 100 DUP^O• stacl of 100 words

OOCfc TOP.STACK
LABEL wr-[ nase pointer to top of atac*
ooca STAC*here ends

FjBLIC DIVISOR

( ;j PRGCEDL!RES_HERE
SEGMENT
PUBLIC : let assembler know that SHART_DIVIBE
EXTRN SKARTJU'IBE: FhR ". is a label of type FAR and is located
I PROCEDURESHE^E ENDS ; m the sequent PROCEDURESHERE

CODE_HEPE
SEGMENT
WORD
PUBLIC
ASSUME CS:C0DE HERE. DS:DATA HERE, S3:STA[t HERE

0000 BB R START: MOVAX, DkTA_HSF; ; initialize data segment


0003 BE D8 MOV DE. AX
0005 PS R MOVAX, 3TACK_HERE : initialize atari segaent
0008 3E DO MOV SS, AJ
000A BC 0OC8 R MOV 3P, OFFSETTOPJTACK i initialize atari pointer
; load low word of dividend in AX, high word of di.idend in DXj divisor in CI
.; 0000 R MOV AX, DIVIDEND j load low word
0010 SB I. 0002 ;' MOV DX, DIVIDEND&f2 ; load high word
001* 8B OE 000* R MOV IS, DIVISOR ; load divisor
0018 9A 0000 CALL SHART.DIVIDE
; quotient returned in DX:AX«resainder returned in CX, carry set if result invalid
00 ID 7] 03 JNC SAVEmLL carry - U, result valid
001F EB 13 90 JMP STOP" carry set. don't save result
ASSUMEDS:MORE_BATA change data segment
0022 IE SAVEALL:PUSHDS save old DS

FIGURE 5-25 Assembly language program to divide a 32-bit number bv a 16-bit


number and return a 32-bit quotient, (ai Mainline program module, lb)
Procedure module.

136 I HAPTER FIVE


The IBM Personal Computer MACROAssenbler 02-19-85 PAhl 1 2

0023 BB — - R NOV BX. MORE_DATA ; load new data segtent


0026 8E DB NOV DS, BX
0028 A3 0000 R NOV QUOTIENT, AX ; store Ioh word of quotient
002B 89 16 0002 R NOV QUOTIENT t 2, DX ; store high word of quotient
002F 89 OE OOOn R NOV REMAINDER, CX ; store remainder

ASSUME
DS:DATA.HERE
0033 IF POP DS ; restoie initial DS
003h 90 STOP: NOP
0035 CODE.HERE ENDS
END

Segsents and groups:

N a • e Sl :p align coabine class

CODE.HERE 0035 WORD PUBLIC

DATA.HERE 0004 WORD PUBLIC

NORE.DATA 0006 WORD NONE

PROCEDURES.HERE 0000 PARA PUBLIC

STACK.HERE 00C8 PARA STACK

Symbols:

N a a e Type Value Attr

DIVIDEND L WORD 0000 data.here


DIVISOR . . . L UORD 0004 data_here Global
QUOTIENT , , , L WORD 0000 more_data Length =0002
REMAINDER L WORD OOOh more.data
SAVE ALL L NEAR 0022 code.here
SMART DIVIDE . . . L FAR 0000 prqce'dures.he
RE External
START ... L NEAR 0000 code.here
STOP . . . L NEAR 0034 code.here
TOP STACK ... L MORD 0OC8 stack.here

Warning Severe
Errors Errors
0 0

The IBM Personal Computer MACROAssembler 01-01-80 PAGE 1-1

PA6E ,132
8086 procedure called SHART.DIVIDE
ABSTRACT: This procedure divides a 32-bit nuaber by a 16-bit nutber
to give a 32-bit quotient and a 16-bit remainder. The
paraieters are passed to and frosi the procedure in the
following way:
Dividend : low word in AX, high word in DX
Divisor : word in CX
Quotient : low word in AX, high word in DX
Reiainder: in CX
Carry : carry set if try to divide by zero
USES: AX, BX. CX. DX, BP, FLAGS

IF— THEN— ELSE STRUCTURES, PROCEDURES, AND MACROS 137


; the following block tells the assembler that the divisor is a word
^variable found in the external segient nated DATAHERE
0000 DATA_HERE SEGHENTPUBLIC
EXTRN DIVIS0R:W0RD
0000 DATA.HERE ENDS

;the next stateaent Bakes SHARTDI VIDE available to other todules


PUBLIC SMART DIVIDE

0000 PROCEDURES_HERE
SEGHENT
PUBLIC
0000 SMART.DIVIDE PROC FAR
ASSUME CS:PROCEDURES .HERE,DS:DATA_HERE
0000 83 3E 0000 E 00 CMP DIVISOR, 0 check for illegal divide
0005 7* 17 JE ERROR.EXIT divisor = 0 so exit
0007 8B D8 MOV ex, ax save low order of dividend
0009 8B C2 MOV AX. DX position high word for 1st divide
000B BA 0000 MOV DX, OOOOH zero DX
000E F7 Fl DIV cx AX/CX, quotient in AX, remainder in DX
0010 8B E8 MOV BP, AX save high order of final result
0012 8B C3 MOV AX, BX get back low order of dividend
001*1 F7 Fl DIV CX AX/CX, quotient in AX, remainder in DX
0016 8B CA MOV CX, DX pass remainder back in CX
0018 8B D5 MOV DX,BP pass high order result back in DX
001 A F8 CLC dear carry to indicate valid result
001B EB 02 90 JMP EXIT finished
001E F9 ERROR.EXIT: STC set carry to indicate divide by zero
001F CB EXIT: RET
0020 SMART DIVIDE EHDP
0020 PROCEDURES HERE ENDS
END

The IBMPersonal Computer MACRO


Assembler 01-01-80 PAGE Sysbols-I

Segtents and groups:

Nate Size align coubine class

DATAHERE. . . . 0000 PARA PUBLIC


PROCEDURES HERE. 0020 PARA PUBLIC

Syibols:

Nate Type Value Attr

DIVISOR. . . . V WORD0000 DATA.HERE External


ERROR.EXIT . . L NEAR 001E PROCEDURES.HERE
EXIT L NEAR 001F PROCEDURES.HERE
SMART.DIVIDE
. F PROC 0000 PROCEDURES.HERE
Global Length =0020

Warning Severe
Errors Errors
0 0

FIGURE 5-25 (continued)

1 38 CHAPTER FIVE
Instruction executes, A.\ will contain the high word ol Writing and Debugging Programs Containing
the 32 in i quotient we want as our final answer. We save Pro< edures
iliis in HI' with the M( )\ BP, \\ Instruction so thai we
The most Importanl point in writing a program contain
can use AX for the second DIV operation,
ins; procedures is to approai h the overall job vc
The remainder from the first DIV operation was left In
tematically We carefully work out the overall structure
the DX register. As shown by the diagram in Figure
ol the program and break it down into modules which
5-24b, tins is right where we want it for the second DIV
can easily he written as procedures. We then write the
operation. All we have to do now, before we do the sec-
n i,i ii ill ne program so that we know whal each procedure
ond
)IVI operation, is to get the low word ol the original
has to do and how parameters can he most easily he
dividend back into AX with the MO\ \X, BX instruction
passed to each procedure. To test this mainline we sim-
Alter the second DIV instruction executes, the 16-bit
ulate each
procedure with a lew instructions whii
quotient will he in AX. This word is the low word ol our
pi) pass lest values hack to the mainline Some pro-
desired 32-bit quotient. We just leave this word in AX to
grammers to these
refei "dummy" procedures as stubs.
he passed hack to the mainline. The I )X register was left
Ii the structure of the mainline seems reasonable, we
with the final remainder We copy this remainder to CX
then develop each procedure and replace the dummy
with the MOV CX, 1)\ instruction to he passed back to
with it. The advantage ol tins approach is thai you have
the mainline program. Alter the first DIV operation we
a structure to hang the procedures on. 11 you write thi
saved the high word of our 32-bit quotient in BP. We
procedures first, you have the messv problem ol trying
now use the MOV DX, I5P instruction to copy this word
to write a mainline to connect all the pieces together.
back to DX where we want it to be when we return to the
Now, suppose that you have approached a program as
mainline. Yon really don't have to shuffle the results
we suggested, and the program doesn't work. Aftei you
around the way we did with these last three instruc-
have checked the algorithm and instructions, you
tions, hut
we like to pass parameters to and from proce-
should check I hat the number of PUSH and POP in-
dures
asin systematic a way as possible so that we can
structions
equalaretor each call and return operation.
more easily keep track of everything. After the shuffling
If none of the checks turns up anything, you can use tin
we clear the carry Hag with CLC before returning.
system debugging tools to track down the problem
Back in the mainline we check the carry Hag with the
Probably the best tools to help you localize a problem to a
|NC instruction. If the carry Hag is set we know that the
small area are breakpoints. Run the program to a break-
divisor was 0. no division was done, and there is no re-
point just
before a CALL instruction to see if the correct
sult put
to in memory. If the carry flag is not set then we
parameters are being passed to the procedure. Put a
know that a valid 32-bit quotient was returned in DX
breakpoint at the start of the procedure to see if execu-
and AX and a 16-bit remainder was returned in CX. We
tion ever
gets to the procedure. Move the breakpoint to a
now want to copy this quotient and this remainder to
later point in the procedure to determine ii the proce-
some named memory locations we set aside for them. If
dure found the parameters passed from the mainline.
you look at some earlier lines in the program, you will
Use a breakpoint just before the RET instruction to see if
see that the memory locations called QUOTIENT and
the procedure produced the correct results and put
REMAINDER are in a segment called MORE_DATA. At
these results in the correct locations to pass them back
the start of the mainline we tell the assembler to AS-
to the mainline program. Inserting breakpoints at key
SUME that
we will be using DATA HERE as the data
points in your program is much more effective in locat-
segment. Now. however, we want to access some data
ingproblem
a than random poking and experimenting.
items in MORE DATA using DS. To do this we have to
do two things. First we have to tell the assembler to AS-
SUME DS:MOREDATA. Second, we have to load the seg- WRITING AND USING ASSEMBLER
ment base
of MORE DATA into DS. In our program we MACROS
save the old value of DS by pushing it on the stack. We
do this so that we can easily reload DS with the base Macros and Procedures Compared
address of DATA HERE later in the program. The MOV Whenever we need to use a group of instructions sever, il
BX, MORE DATA and MOV DS,BX instructions load the times throughout a program there are two ways we can
base address of MORE DATA into DS. The three MOV avoid having to write the group of instructions each
instructions after this copy the quotient and the re- time we want to use it. One way is to write the group of
mainderthe
into named memory locations. instructions as a separate procedure. We can then just
Finally in the program we point DS back at CALL the procedure whenever we need to execute that
DATA HERE so that later instructions can access data group of instructions. A big advantage of using a proce-
items in the DATA HERE segment. To do this we first durethat
is the machine codes for the group of instruc-
tell the assembler to ASSUME DS:DATA HERE. We then tionsthe
in procedure only have to be put in memory
POP the base address of DATA HERE off the stack into once. Disadvantages of using a procedure are the need
DS. As you write more complex programs you will often for a stack, and the overhead time required to call t he-
want to access different segments at different times in procedure and return to the calling program.
the program. We wrote this example to show you how to When the repeated group of instructions is too short
do it. When you do change segments, make sure to or not appropriate to be written as a procedure, we use a
change both the ASSUME and the actual contents of the macro. A macro is a group of instructions we bracket
segment register. and give a name to at the start of our program. Each

IF— THEN— EtSE STRUCTURES, PROCEDURES, AND MACROS 139


time we "call" the macro in our program, the assembler Now, to call the macro in one of our procedures we
will insert the defined group of instructions in place of simply put in the name of the macro just as we would an
the "call." In other words the macro call is like a short- instruction mnemonic. The start of a procedure which
hand expression which tells the assembler, "Every time does this might look like this.
you see a macro name in the program, replace it with
the group of instructions defined as that macro at the BREATH RATE PROC FAR
start of the program." An important point here is that ASSUME CS:PROCEDURES HERE, DS:PATIENT_PARAMETERS
the assembler generates machine codes for the group of PUSH ALL ; macro call
instructions each time the macro is called. Replacing MOV AX, PATIENT PARAMETERS ; Initialize data
the macro with the instructions it represents is com- ; segment reg
monly called
"expanding" the macro. Since the gener- MOV DS, AX
ated machinecodes are right in-line with the rest of the
program, the processor does not have to go off to a pro-
cedurereturn.
and Therefore, using a macro avoids the
overhead time involved in calling and returning from a
procedure. A disadvantage of generating in-line code When the assembler assembles this program section it
each time a macro is called is that this may make the will replace PUSH ALL with the instructions that it rep-
program take up more memory. The examples which fol- resentsinsert
and the machine codes for these instruc-
low shouldhelp you see how to define and call macros. tionsthe
in object code version of the program. The as-
For these examples we use the syntax of the IBM PC sembler listing
tells you which lines were inserted by a
macro assembler, MASM, written by Microsoft Corpora- macro call by putting a + in each program line inserted
tion.
youIf are developing your programs on some other by a macro call. As you can see from the example here,
machine, consult the assembly language programming using a macro makes the source program much more
manual for your machine to find the macro definition readable because the source program does not have the
and calling formats for it. long series of push instructions cluttering it up.
The preceding example showed how a macro can be
used as simple shorthand for a series of instructions.
Defining and Calling a Macro Without
The real power of macros, however, comes from being
Parameters able to pass parameters to them when you call them.
For our first example suppose that we are writing an The next section shows you how and why this is done.
8086 program which has many complex procedures. At
the start of each procedure we want to save the flags and
all of the registers by pushing them on the stack. At the Passing Parameters to Macros
end of each procedure we want to restore the Hags and Most of us have received computer printed letters of the
all of the registers by popping them off the stack. Each form:
procedure would normally contain a long series of PUSH
instructions at the start and a long series of POP in- Dea r MR . HALL ,

structions
the end.
at Typing in these lists of push and We are pleased to inform you that you ma y
pop instructions is tedious and prone to errors. We h a " e won up to $ 1 >0 0 0 >0 0 0 in the Reader's
could write a procedure to do the pushing and another We e K 1 v sweepstakes. To find out if y o u
procedure to do the popping. However, this adds more are a winner MR. HALL, r e t u r n the gold
complexity to the program and is therefore not appro- card to Reader's We e H 1 % / in the enclosed
priate.simple
Two macros will solve the problem for us. e I", n e 1 o p e before OCTOBER 2 2 i 19 8 B . You can
Here's how we write a macro to save all the registers. take advantage of our special offer of
three -ears of Reader's We e H 1 •/ for only
PUSH ALL MACRO
$24.95 by putting a n X in the YES box o n
PUSHF
the Sold card. If you do not wish to take
PUSH AX
advantage of this offer, which is one
PUSH BX
third off the newstand price, mark the no
PUSH CX
box on the 9 o 1 d card.
PUSH DX
Than k y o u <
PUSH BP
PUSH SI
A letter such as this is an everyday example of the
PUSH DI
macro with parameters concept. The basic letter
PUSH DS
"macro" is written with dummy words in place of the
PUSH ES
addressee's name, the reply date, and the cost of a three-
PUSH SS
year subscription. Each time the macro which prints
ENDM the letter is called, new values for these parameters are
passed to the macro. The result is a "personal" looking
The PUSH ALL MACRO statement identifies the start of letter.
the macro and gives the macro a name. The ENDM iden- In assembly language programs we likewise can write
tifies the
end of the macro. a generalized macro with dummy parameters. Then

140 CHAI'Tf.R I IVt


when we call the macro we can p. ins n the actual param Machine code foi Instructions only put in memory
eters needed for the specific application i ii K e

Suppose, for example, we are wrll Inga word processoi


program. A frequeni need In .1 word processoi program
Parameters passed In registers, memorj loi ations, oi
stack.
is to move strings ol AS< II characters from one place in
memory to anothei I in 8086 M< As instruction is in-
MACRO
tended
do idihis. Remembei from the discussion oi the
stunt; Instructions in Chapter l. however, thai in order
for the MOVS instruction to work correctly, you firsl Accessed during assembly with name given to macro
have in lo. id SI uiih theoffsel ol the source start, DI with
when defined.
the offset of the destination start, and CX with the num Machine code generated for instructions each time
ber ol bytes or winds to be moved. We can define a macro called.
to do all of this as follows.
Parameters passed as part ol statement which calls
MOVI ASCII MAC RO NUMBER, souki I, macro.
DESTINATION
MOV CX, NUMBER Number ol c hara< ters
to be moved in CX IMPORTANT TERMS AND CONCEPTS
LEA SI, SOURCE Point SI at ASCII source FROM THIS CHAPTER
LEA DI, DESTINATION Point DI at ASCII
destination If you do not remember any of the terms in the following
REP MOVSB Copy ASCII string to list, use the index to help you find them in the chapter
new location for review.
ENDM
Procedure
The words NUMBER. SOURCE, and DESTINATION in
Subprogram
this macro are called dummy variables. When we call the
macro, values from the calling statement will be put in CALL. RET
the instructions in place of the dummies. If. for exam-
PUBLIC, EXTRN
ple, we
call this macro with the statement: MOVE ASCII
03DH, BLOCK START, BLOCK DEST. the assembler will Nested procedures
expand the macro as follows.
Direct intersegment far CALL
MOV CX, 03DH Number of characters to be
Indirect intersegment far CALL
moved in CX
LEA SI, BLOCK START Point SI at ASCII destination Direct intersegment near CALL
LEA DI, BLOCK DEST Point DI at ASCII destination
Indirect intersegment near CALL
REP MOVSB Copy ASCII string to new
location Stack: top of stack, stack pointer

PUSH. POP
We do not have space here to show you very much of
what you can do with macros. Read through the assem- Parameter, parameter passing
bly language programming manual for your system to
Near and far procedures
find more details about working with macros.
Stack overflow

Reentrant and recursive procedures


Summary of Procedures vs. Macros Interrupt

PROCEDURE Interrupt service procedure


Separate assembly modules
Accessed by CALL and RET mechanism during
program execution. Macro

REVIEW QUESTIONS AND PROBLEMS


In order to avoid hand keying programs into an had to convert each byte of the machine code pro-
SDK-86 board we wrote a program to send machine gramASCII
to codes for the two nibbles in the byte.
code programs from an IBM PC to an SDK-86 board In other words, a byte of 7AH has to be sent as 37H.
through a serial link. As part of this program we the ASCII code for 7. and 4 1 H. the ASCII code for A.

IF— THEN— ELSE STRUCTURES, PROCEDURES. AND MACROS 141


Once you separate the nibbles of the byte, this con- ASCI I
version
a simple
is IF — THEN — ELSE situation.
Write an algorithm and assembly language pro- OOH
gram section
which does the needed conversion.
A common problem when reading a series of ASCII ERROR
characters from a keyboard is the need to filter out
those codes which represent the hex digits 0-9 and 2FH
A-F. and convert these ASCII codes to the hex dig-
its they represent. For example, if we read in 34H.
the ASCII code for 4. we want to mask the upper 4
bits to leave 04. the 8-bit hex code for 4. If we read
30H
in 42H. the ASCII code for B. we want to add 09 and
mask the upper 4 bits to leave OB, the 8-bit code for
HEX 0-9
hex B. If we read in an ASCII code that is not in the
range of 30H-39H or 41H-46H. then we want to
load an error code of FFH instead of the hex value of 39H

the entered character. Figure 5-26 shows the de-


sired action next to each range of ASCII values.
Write an algorithm and an assembly language pro-
gram whichimplements these actions. HINT: a 3AH
nested IF — THEN — ELSE structure might be use-
ful. ERROR

Show the 8086 instruction or group of instructions


which will: ^+0H
a. Initialize the stack segment register to 4000H
and the stack pointer register to 8000H.
b. Call a near procedure named FIXIT.
c. Save BX and BP at the start of a procedure and
restore them at the end of the procedure. *+lH

d. Return from a procedure and automatically HEX A-F


increment the stack pointer by 8.
a. Use a stack map to show the effect of each of ^6H
the following instructions on the stack pointer
and on the contents of the stack.

MOV SP.4000H
^+7H
PUSH AX
CALL MULTO
POP AX ERROR
MULTO PROC NEAR
PUSHF 7FH
PUSH BX

FIGURE 5-26 ASCII chart tor Problem 5-2.

POP BX
POPF c. The instruction which will call a procedure
RET which is 97H addresses higher in memory
MULTO ENDP than the instruction after a call instruction.
d. An instruction which returns execution from a
b. What effect would it have on the execution of far procedure to a mainline program and incre-
this program if the POPF instruction in the mentsstack
the pointer by 4.
procedure was accidentally left out? Describe
the steps you would take in tracking down this 6. a. List three methods of passing parameters to a
problem if you did not notice it in the program procedure. Give the advantage and disadvan-
listing. tageeach
of method,
b. Define the term "reentrant" and explain how
5. Show the binary codes for the following instruc- you must pass parameters to a procedure so
tions. that it is reentrant.
a. CALL BX
b. CALL WORD PTR [BX! 7. a. Write a procedure which produces a delay of

142 CHAPTER FIVE


;(.;(;( ms when run on an 8086 with a i MHz
clock,
b. Write a mainline program whi< h uses this pro
cedure to output a square wave on bil DO ol
porl IITA1I.

Write a procedure which converts a 1 di^ii Ii('I)


W \ 12 BITS
number passed in AX to its binary equivalenl Use
the algorithm in Figure 5-15.
X 32 BITS

The 8086 \ 1L11 instruction allows you to multiply a


16-bit number by a 16-bit binary number to give a > • II 32 BITS

32 bil result. In some cases, however, you may


RESULT
need to multiply a 32 bil number by a .'S'2-bit num- 64 BITS
ber give
to a i;4 bit result. With the MUl instruc-
tion and
a little adding you can easily do this. Fig- I U .1 IRI 1-27 12 bil In (2-bit multiply method for

ure 5-27
shows in diagram form how to do it. Each Problem 5-9.

letter in the diagram represents a 16-bit number.


The principle is to use MUL to form partial prod-
ucts and
add these partial products together as
shown. Write an algorithm for this multiplication
and then write the 8086 assembly language pro-
gramthe
for algorithm.
Write an 8086 procedure which implements tins
Calculating the factorial of a number which we did algorithm for an JV between 1 and 8.
with a recursive procedure in Figure 5-22a can eas-
1 1. Write an assembler macro which will restore, in the
ily bedone with a simple REPEAT UNTIL structure
correct order, the registers saved by the macro
of the form:
PUSHALL in this chapter.
IF N = 1 THEN
FACTORIAL = 1 12. a. Show how you would tell the assembler to
ELSE make the label BINADD available to other as-
FACTORIAL = 1 sembly modules.
REPEAT b. Show how you would tell the assembler to look
FACTORIAL = FACTORIAL - N for a byte type data item named CONVERSION
DECREMENT N FACTOR in a segment named FIXUPS.
UNTIL N = 0

IF—THEN—ELSESTRUCTURES, PROCEDURES, AND MACROS 143


CHAPTER

8086 Instruction
Descriptions and Assembler
Directives

This chapter consists of two major sections. The first EXAMPLE:


section is a dictionary of all of the 8086 8088 80186
ADD AL. BL ; AL = 00110101, ASCIIS
80188 instructions. For each instruction we give a de-
BL = 00111001. ASCII 9
tailed description
of its operation, the correct syntax for
AL = 01101110.
the instruction, and the flags affected by the instruc-
6EH - Incorrect Temporary Result
tion. Also,
numerical examples are shown for those in-
AL = 00000101. Unpacked BCD for 4.
structionsthey
whereare appropriate. The binary cod-
Cany = 1 to indicate correct answer is
ing templates for the instructions are shown
14 decimal.
alphabetically in a table in the appendix. Putting the
codes together in a table makes it easier to find codes if NOTES: OR AL with 30H to get 34H. the ASCII code for
you are hand coding a program. 4. if you want to send the result back to a CRT terminal.
The second major section of this chapter is a diction- The one in the cam- can be rotated into the low nibble of
ary of
commonly used 8086 assembler directives. The a register. ORed with 30H to give the ASCII code for 1.
directives described here are those defined for the Intel and then sent to the terminal.
8086 macro assembler and the IBM macro assembler. The AAA instruction only works on the AL register.
MASM. If you are using some other assembler, it proba- The AAA instruction correctly updates the AF and the
bly hassimilar capabilities, but the names may be dif- CF. but the OF. PF. SF. and ZF are left undefined.
ferent.
You will probably use this chapter mostly as a refer-
AAD INSTRUCTION — BCD-to-Binar\ Convert
enceget
to the details of an instruction or directive as
before Division — AAD
you write programs of your own or decipher someone
else's programs. However, you should skim through the The mnemonic for this instruction might tempt you to
chapter at least once to give yourself an overview of the call it ASCII Adjust for Division. However, the instruc-
material contained here. You should not try to absorb all tion actually
works with unpacked BCD. You must mask
of this chapter at once. Most of the instructions de- out the 3 in the upper nibble of the ASCII codes for deci-
scribedare
here used and discussed in various example mal digits
before you can use AAD. AAD converts two
programs throughout the book. Therefore, we have in- unpacked BCD digits in .AH and AL to the equivalent
cluded referencesto the appropriate sections in the in- binary number in AL. This adjustment must be made
struction descriptions
here. before dividing the two unpacked BCD digits in AX by
an unpacked BCD byte. After the division AL will then
contain the unpacked BCD quotient and AH will contain
the unpacked BCD remainder. The PF. SF. and ZF are
INSTRUCTION DESCRIPTIONS
updated. The AF. CF. and OF are undefined after AAD.
AAA INSTRUCTION— ASCII Adjust for
Addition — AAA EXAMPLE:

Numerical data coming into a computer from a terminal AX = 0607 unpacked BCD for 67 decimal
is usually in ASCII code. In this code the numbers 0-9 CH = 09H
are represented by the ASCII codes 30H-39H. The 8086 AAD Adjust to binary before division
allows you to add the ASCII codes for two decimal digits AX = 0043 = 43H = 67 decimal
without masking off the "3" in the upper nibble of each. DfY CH Divide .AX by unpacked BCD in CH
The AAA instruction is then used to make sure the re- .AL = quotient = 07 unpacked BCD
sult the
is correct unpacked BCD. A simple numerical .AH = remainder = 04 unpacked BCD
example will show how this works. PF = 0 SF = 0 ZF = 0

144
Nl HI 11 an attempt is made to divide by 0, or if the lb)
quotient is greater than 09, the 8086 will do a type 0
Al. 001 I OKU ASCII 5
Interrupt. Interrupts are explained in Chaptei 8
BL 001 I 1001 ASCII 9
SCIi AL. BL ; (5 9) Results:
AL I 1 1 1 1 100 -1

AAM INSTRUCTION— BCD Adjust after in 2's complemenl


Multiply— AAM cv l
Results;
The mnemonic lor this Instruction may temp) you to Al. 0000 0100 BCD 04
call it ASCII Adjust for Multiply. In truth, however, the CF 1 borrow needed
8086 'Iocs not allow you to multiply the ASCII codes for
decimal digits directly. Before you can multiply two
ASCII digits, you must firsl mask the upper 1 hits ol The AAS Instruction leaves the c it unpacked BCD
result in the low nibble of AL and resets the upper nibble
each. This leaves unpacked BCD lone BCD digit per
byte) In each byte. Alter the two unpacked BCD dibits of AL to all (Vs. II you want to send the result back to a

are multiplied, the AAM instruction is used to adjust the CRT terminal, you can OK Al with 30H to produce the

product to two unpacked BCD digits in AX. correct ASCII code lor the result. If multiple-digit num-
bers are
being subtracted, the CF can be taken into ac-
AAM only works after the multiplication of two un-
countusing
by the SBB instruction when subtrai ting
packedbytes.
BCD It only works on an operand in AL.
The PF. SF, and ZF are updated by AAM. The AF. CF. and the next digits.

OF are undefined after AAM. N( )TES: The AAS instruction only works on the AL reg-
ister. The
AAS instruction correctly updates the AF and
EXAMPLE: the CF, but the OF, PF. SF. and the ZF are left undefined.

Al. (XMXHllOl unpacked BCD 5


BH = 00001001 = unpacked BCD 9
MUL BH AL x BH Result in AX
ADC INSTRUCTION— Add with carry— ADC
AX = 00000000 00101 101 = 002DH
destination, source
AAM AX = 00000100 00000101
which is unpacked BCD for 45.
If ASCII codes for the result are
ADD INSTRUCTION— Add— ADD destination,
desired.
source
use the next instruction.
These instructions add a number from some source to a
OR AX.3030H Put 3 in upper nibble of each byte.
number from some destination and put the result in the
AX = 00110100 00110101 = ASCII
specified destination. The add with carry instruction,
codes for 45.
ADC, also adds the status of the carry flag into the re-
sult. The
source may be an immediate number, a regis-
ter, aor memory location as specified by any of the 24
AAS INSTRUCTION— ASCII Adjust for addressing modes shown in Figure 3-8. The destination
Subtraction — AAS may be a register or a memory location specified by any
one of the 24 addressing modes in Figure 3-8. The
Numerical data coming into a computer from a terminal
source and the destination in an instruction cannot
is usually in ASCII code. In this code the numbers 0—9
both be memory locations. The source and the destina-
are represented by the ASCII codes 30H-39H. The 8086
tion must be of the same type. In other words, they must
allows you to subtract the ASCII codes for two decimal
both be byte locations, or they must both be word loca-
digits without masking the "3" in the upper nibble of
tions.
youIf want to add a byte to a word, you must copy
each. The AAS instruction is then used to make sure the
the byte to a word location and fill the upper byte of the
result is the correct unpacked BCD. Some simple nu-
word with zeroes before adding. Flags affected: AF, CF,
merical exampleswill show how this works.
OF. PF. SF. ZF.

EXAMPLE:
EXAMPLES (CODING1
(a) Add immediate number 74H
ADD AL. 74H
AL = 0011 1001 = ASCII 9 to contents of AL

BL = 0011 0101 = ASCII 5


ADC CL, BL Add contents of BL plus
SUB AL. BL (9 - 5) Results:
carry status to
AL = 0000 0100 = BCD 04
contents of CL.
CF = 0
Result in CL.
AAS Results:
AL = 0000 0100 = BCD 04 ADD DX. BX Add contents of BX to

CF = 0 no borrow required contents of DX

INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 145


ADD DX.[SI] Add word from memory at AND INSTRUCTION— AND corresponding bits
offset [SI] in DS of two operands — AND destination, source
to contents of DX
This instruction ANDs each bit in a source byte or word
ADC AL. PRICES[BX1 Add byte from Effective with the same number bit in a destination byte or word.
Address PRICESIBX] The result is put in the specified destination. The con-
plus carry status to tentsthe
of specified source will not be changed. The
contents of AL result for each bit position will follow the truth table for
a two-input AND gate. In other words, a bit in the speci-
ADD PRICESIBX]. AL Add contents of AL to fied destination will be a one only if that bit is a one in
contents of memory both the source and the destination operands. There-
location at Effective fore,
bita can be masked (reset) by ANDing it with 0.
Address PRICESIBX]
The source operand can be an immediate number, the
EXAMPLES (NUMERICAL): contents of a register, or the contents of a memory loca-
tion specifiedby one of the 24 addressing modes shown
Addition of Unsigned in Figure 3-8. The destination can be a register or a
numbers memory location. The source and the destination can-
ADD CL, BL CL = 01110011 = 115 not bothbe memory locations in the same instruction.
decimal The CF and OF are both 0 after AND. The PF, SF, and ZF
+ BL = 01001111 = are updated by AND. AF is undefined. Note that PF only
79 decimal has meaning for an 8-bit operand.
Result in CL
CL = 11000010 = 194 EXAMPLES (CODING):
decimal
AND BH. CL : AND byte in CL with byte in BH,
: result in BH
ADD CL. BL Addition of Signed numbers
CL = 011 1001 1 = +115
AND BX. 00FFH : AND word in BX with immediate
decimal
00FFH.
+ BL = 01001111 = + 79
decimal Mask upper byte, leave
Result in CL lower unchanged.
CL = 11000010 = -62
decimal.
AND CX. [SI] : AND word at offset [SI] in
data segment
; Incorrect because result too large to fit in 7 bits. with word in CX
register. Result in CX register.
FLAG RESULTS:
EXAMPLE (NUMERICAL)
CF = 0 No carry out of bit 7
; BX = 10110011 01011110
PF = 0 Result has odd parity AND BX. 00FFH : Mask out upper 8 bits of BX.
: Result BX = 00000000 01011110.
AF = 1 Carry was produced out of bit 3
: CF = 0 OF = 0 PF = 0 SF = 0 ZF = 0
ZF = 0 Result in destination was not zero

SF = 1 Copies most-significant bit of result: indi-


cates negative
result if you are adding signed
BOUND— 80186/80188 ONLY— Check if Array
numbers Operation Out of Bounds
When performing some operation on an array of data in
OF = 1 Set to indicate that the result of the addition
memory the BOUND instruction can be used to make
was too large to fit in the lower 7 bits of the
sure that data values outside the array are not being
destination used to represent the magnitude
operated on. To use this instruction the offset of the
of a signed number. In other words the result
lowest element in the array (lower bound) is loaded in
was greater than + 127 decimal so the result
two memory addresses. The offset of the highest ele-
overflows into the sign bit position and incor-
mentthe
in array (upper bound) is loaded into the next
rectly indicates that the result is negative. If
two memory addresses. The offset of the array element
you are adding two signed 16-bit values, the
currently being worked on is loaded into a general-
OF will be set if the magnitude of the result is
purpose register such as BX. When the BOUND instruc-
too large to fit in the lower 15 bits of the desti-
tion executes, it will compare the value in BX with the
nation.
lower and upper bounds in the two memory locations. If
NOTES: The PF is only meaningful for an 8-bit result. the offset in BX is less than the lower bound or greater
The AF is only set by a carry out of bit 3. Therefore, the than the upper bound, then the 80186/80188 will do a
DAA instruction cannot be used after word additions to type 5 interrupt. Refer to Chapter 8 for a thorough dis-
convert the result to correct BCD. cussion
interrupts.
of BOUND affects no flags.

146 CHAPTER SIX


EXAMPI I CALL SMART DIVIDE . SMART DIVIDE is the name
ol the procedure I he procedure must be declared
1. ARRAY! EQU 1T> ; Length of ARRAY! 15 bytes FAR with SMART DIVIDE PRO! FAR at its sin
MOV BOUND STORE, OFFSET AKKAVI ; Store offset section in Chaptei 5) ("he assemble! will determine
oi lowest element the code segment base for the segment which
: Now store offset ol highest element ol the arraj contains the procedure and the offsel ol the start ol
MOV HOUND STORE+2, OFFSE1 ARRAY) %\. AKKAVI the procedure In thai segment. It will put these
: Assume BX contains offset ol array element values In as pai t "I the instruction < ode
; currently being operated upon and then
; generate type 5 interrupt it trying to Indirect to anothei segment far or intersegment
; operate on an element which is out ol bounds
CALL DWORD PTR[BX] : New values loi CS and II1
BOUND BX, BOUND STORE
arc fetched from tour memory locations in DS. The
new value toi CS is fetched from [BX| and [BX * 1),
the new IP is fetched from [BX • 21 and [BJ
CALL INSTRUCTION— Call a procedure
The CALI instruction is used to transfer execution to a
subprogram or procedure. There are two basic types ol CBW INSTRUCTION -Convert signed Byte to
CALLs. near and Jar. A near CALL is a call to a procedure signed Word— CBW
which is in the same code segment as the CAl 1 instruc- This instruction copies the sign of a byte in AL to all the
tion. Whenthe 8086 executes a near CALL instruction it bits in AH. AH is then said to be the sign extension ol
decrements the slack pointer by two and copies the oft- AL. The CBW operation must be done before a signed
set of the next instruction after the CALI on the stack byte in AL can be divided by another signed byte with
This offset saved on the stack is referred to as the return the IDIV instruction. CBW affects no flags.
address, because this is the address that execution will
return to after the procedure executes. A near CALL in- EXAMPLE:
struction
also
will load the instruction pointer with the
; AX = 00000000 1001 1011 = - 155 decimal
offset of the first instruction in the procedure. A RET
CBW; Convert signed byte in AL to signed word in AX.
instruction at the end of the procedure will return exe-
; Result in AX = 11111111 1001 101 1
cution
theto instruction after the CALL by copying the
: = - 155 decimal.
offset saved on the stack back to IP.
A far CALL is a call to a procedure which is in a differ-
ent segment from that which contains the CALL instruc- For further examples of the use of CBW, see the IDIV
tion. Whenthe 8086 executes a far CALL it decrements instruction description.
the stack pointer by two and copies the contents of the
CS register to the stack. It then decrements the stack CLC INSTRUCTION— Clear the carry flag, CF—
pointer by two again and copies the offset of the instruc-
CLC
tion afterthe CALL to the stack. Finally, it loads CS with
This instruction resets the carry flag to zero. No other
the segment base of the segment which contains the
flags are affected.
procedure and IP with the offset of the first instruction
of the procedure in that segment. A RET instruction at
EXAMPLE:
the end of the procedure will return execution to the
next instruction after the CALL by restoring the saved CLC : Clear carry [lag
values of CS and IP from the stack.

CLD INSTRUCTION— Clear direction flag—


EXAMPLES
CLD
; Direct within-segment (near or intrasegment) This instruction resets the direction flag to zero. No
CALL MULTO ; MULTO is the name of the other flags are affected. If the direction flag is reset. SI
procedure. The assembler determines displacement of and DI will automatically be incremented when one of
MULTO from the instruction after the CALL and
the string instructions such as MOVS. CMPS. or SCAS
codes this displacement in as part of the instruction. executes. Consult the string instruction descriptions
for examples of the use of the direction flag.
: Indirect within-segment near or intrasegment
EXAMPLE:
CALL BX ; BX contains the offset of the first
instruction of the procedure. Replaces contents of IP CLD : Clear direction flag so that string pointers
with contents of register BX. ; autoincrement
CALL WORD PTR [BX] ; Offset of first instruction of
procedure is in two memory addresses in DS. CLI INSTRUCTION— Clear interrupt flag— CLI
Replaces contents of IP with contents of word memory
This instruction resets the interrupt flag to zero. No
location in DS pointed to by BX.
other flags are affected. If the interrupt flag is reset, the
; Direct to another segment-far or intersegment 8086 will not respond to an interrupt signal on its INTR

808b INSTRUCTION 1)1 S( RIP1IONS AND ASSEMBLER DIRECTIVES 147


input. The CLI instruction, however, has no effect on section. Having the compare instructions formatted the
the nonmaskable interrupt input. NMI. way they are makes this use very easy to understand.
For example, given the instruction sequence:

CMC INSTRUCTION— Complement the carry CMP BX. CX


flag— CMC JAE TARGET
If the earn,' flag. CF. is a zero before this instruction, it
will be set to a one after the instruction. If the carry' flag
you can mentally read it as jump to target if BX is above
is one before this instruction, it will be reset to a zero
or equal to CX. In other words, just mentally insert the
after the instruction executes. CMC affects no other
first operand after the J for jump and the second oper-
flags. and after
the condition.

EXAMPLE:
CMPS/CMPSB/CMPSW— Compare string bytes
CMC ; Invert the earn' flag or string words
A string is a series of the same type of data items in
CMP INSTRUCTION— Compare byte or word— sequential memory locations. The CMPS instruction can
CMP destination, source be used to compare a byte in one string with a byte in
This instruction compares a byte from the specified another string or to compare a word in one string with a
source with a byte from the specified destination, or a word in another string. SI is used to hold the offset of a
word from a specified source with a word from a speci- byte or word in the source string and DI is used hold the
fied destination. The source can be an immediate num- offset of a byte or a word in the other string. The com-
ber,register,
a or a memory location specified by one of parison
done is by subtracting the byte or word pointed
the 24 addressing modes shown in Figure 3-8. The des- to by DI from the byte or word pointed to by SI. The AF.
tination
also
canbe an immediate number, a register, or CF. OF. PF. SF. and ZF flags are affected by the compari-
a memory location. However, the source and the desti- son, but
neither operand is affected. After the compari-
nation cannot
both be memory locations in the same son and
SI DI will automatically be incremented or dec-
instruction. The comparison is actually done by sub- remented
point to to the next elements in the two
tracting
source
the byte or word from the destination strings. If the direction flag has previously been set to a
byte or word. The source and the destination are not one with an STD instruction, then SI and DI will auto-
changed, but the flags are set to indicate the results of matically
decremented
be by one for a byte string or by
the comparison. The AF, OF. SF. ZF. PF. and CF are up- two for a word string. If the direction flag has been pre-
datedtheby CMP instruction. For the instruction CMP viously to
reset
a zero with a CLD instruction, then SI
CX. BX the CF. ZF. and SF will be left as follows: and DI will automatically be incremented after the com-
pare. They
will be incremented by one for byte strings
CF ZF SF
and by two for word strings.
CX = BX ii 1 0 Result of subtraction is 0 The string pointed to by DI must be in the extra seg-
CX BX ii 0 0 No borrow required ment. The
string pointed to by SI is assumed to be in the
so CF = 0 data segment, but you can use a segment override prefix
CX BX 1 (i 1 Subtraction required
to tell the 8086 to add the offset in SI to CS. SS. or ES.
borrow so CF = 1
The CMPS instruction can be used with a REP. REPE. or
REPNE prefix to compare all of the elements of a string.
EXAMPLES: To see how this is done, read the discussion of strings in
Chapter 4 and the example program in Figure 4-23.
CMP AL. 01H Compare immediate number
01H with byte in AL
EXAMPLES:
CMP BH. CL Compare byte in CL with
: Point SI at source string
byte in BH
: Point DI at destination string
CMP CX. TEMP MIX Compare word at MOV SI. OFFSET FIRST STRING
displacement TEMP MIX MOV DI. OFFSET SECOND-STRING
in DS CLD : DF cleared so SI and DI will
with word in CX : autoinerement after compare
CMPS FIRST-STRING. SECOND_STRING
CMP TEMP MAX. CX Compare CX with word at
: The assembler uses names to determine whether
displacement TEMP MAX
: strings were declared as type byte or as type word.
in data segment
MOV CX. 100 : Put number of string
CMP PRICES1BXI.49H Compare immediate 49H
elements in CX
with byte at offset
Point SI at source of string
[BX] in array PRICES
and DI at destination of string
NOTE: The compare instructions are often used with MOV SI. OFFSET FIRST STRING
the conditional jump instructions described in a later MOV DI. OFFSET SECOND_STRING

148 t HAPTtR SIX


STD ; DF Mi so SI and 1)1 will auto- ADD AL, HI. Al 1101 0001. Al i
decrement after compare
REPE C'Ml'SH ; Repeat the comparison ol string ; add 01 10 Because AF I
bytes until end , Al. I 101 01 l l N7I1
of string or until compared ; l 101 li so add 01 10 oooo
bytes are not equal ; Al. 001 10111 37 BCD, CF 1

\i his i he DAA instruction updates the AF, CF, I'l'.


NOI I CX functions as a counter which the Kl I'l prefix
and ZF. The OF is undefined after a DAA instruction.
will cause to be decremented alter each compare. The B
A decimal UP counter can be Implemented using the
attached to CMPS tells the assembler that the strings are
DAA Instruction as follows:
ol type byte. With this addition you don't have to put in
the string names as we did in the previous example. It
MOV COUNT. 0011 Initialize count in memory
you want to tell the assembler that the strings are of type
location to 0
word, write the instruction as CMPSW.

CWD INSTRUCTION— Convert Signed Word to MOV AL. COUNT Bring count into AL to work on
Signed Doubleword — CWD ADD AL, 01H Can also count up by 2. by 3, or
CWD copies the sign bit of a word in AX to all the bits of by some other number using the
the DX register. In other words it extends the sign of AX ADD instruction
into all of DX. The CWD operation must be done before a DAA Decimal adjust the result
signed word in AX can be divided by another signed MOV COUNT. AL Put decimal result back in
word with the IDIV instruction. CWD affects no flags. memory store

EXAMPLE:
DAS INSTRUCTION— Decimal Adjust after
: DX = 00000000 00000000 Subtraction — DAS
: AX = 111 10000 1 10001 11 = -3897 decimal
This instruction is used after subtracting two packed
CWD : Convert signed word in AX to signed double
BCD numbers to make sure the result is correct packed
: word in DX:AX. BCD. DAS only works on the AL register. If the lower
: Result DX = 11111111 11111111 nibble in AL after a subtraction is greater than 9 or the
: AX = 111 10000 1 10001 11 = -3897 decimal
AF was set by the subtraction, then the DAS instruction
will subtract 6 from the lower nibble of AL. If the result
For a further example of the use of CWD see the IDIV
in the upper nibble is now greater than 9 or if the carry
instruction description. flag was set, the DAS instruction will subtract 60 from
AL. A couple of simple examples should clarify how this
DAA INSTRUCTION— Decimal Adjust works.
Accumulator — DAA
This instruction is used to make sure the result of add- EXAMPLES:

ing twopacked BCD numbers is adjusted to be a legal


BCD number. DAA only works on AL. If the lower nibble (al
in AL after an addition is greater than 9 or the AF was AL = 1000 0110 = 86 BCD
set by the addition, then the DAA instruction will add 6 BH = 0101 0111 =57 BCD
to the lower nibble in AL. If the result in the upper nib- SUB AL. BH AL = 0010 1 1 1 1 = 2FH. CF = 0
ble AL
of is now greater than 9 or if the carry flag was set DAS Subtract 0000 0110 (-06H).
by the addition or correction, then the DAA instruction Because 1111 in low nibble > 9
will add 60H to AL. A couple of simple examples should AL = 0010 1001 = 29 BCD
clarify how this works.

EXAMPLES: Ibl
AL = 0100 1001 = 49 BCD
(a) BH = 0111 0010 = 72 BCD

AL = 0101 1001 = 59 BCD SUB AL, BH : AL = 1 101 01 1 1 = D7H CF = 1

BL = 0011 0101 = 35 BCD DAS ; Subtract 01 10 0000 (-60H).

ADD AL. BL AL = 1000 1110 = 8EH Because 1101 in upper nibble > 9

DAA AL = 01 1 1 01 1 1 = 77 BCD CF = 1
add 01 10 Because 1 1 10 > 9 CF = 1 means borrow was needed
AL = 1001 0100 = 94 BCD
NOTES: The DAS instruction updates the AF, CF, SF,
PF, and ZF. The OF is undefined after DAS.
AL = 1000 1000 = 88 BCD A decimal down counter can be implemented using
BL = 0100 1001 = 49 BCD the DAS instruction as follows:

8086 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 149


MOV AL. COUNT Bring count into AL to work on When a double word is divided by a word, the most-
SUB AL. 01H Decrement. Can also count down significant word of the double word must be in DX and
by 2. 3. the least-significant word of the double word must be in
etc. using SUB instruction. AX. After the division AX will contain the 16-bit result
DAS Keep results in BCD format (quotient), and DX will contain a 16-bit remainder.
MOV COUNT, AL Put new count back in memory Again, if an attempt is made to divide by 0 or the quo-
tienttoo
is large to fit in AX (greater than FFFFH). the
DEC INSTRUCTION— Decrement destination 8086 will do a type 0 interrupt.
register or memory — DEC destination For a DIV the dividend (numerator) must always be in
AX or DX and AX, but the source of the divisor (denomi-
This instruction subtracts one from the destination
nator) can
be a register or a memory location specified
word or byte. The destination can be a register or a
by any one of the 24 addressing modes shown in Figure
memory location specified by any one of the 24 address-
3-8. If the divisor does not divide an integral number of
ing modes shown in Figure 3-8. The AF. OF. PF. SF. and
times into the dividend, the quotient is truncated, not
ZF are updated, but the CF is not affected. This means
rounded. The example below will illustrate this. All flags
that if an 8-bit destination containing 00H or a 16-bit
are undefined after a DIV instruction.
destination containing 0000H is decremented, the re-
If you want to divide a byte by a byte, you must first
sult will
be FFH or FFFFH with no carry (borrow].
put the dividend byte in AL and fill AH with all O's. The
EXAMPLES: SUB AH, AH instruction is a quick way to do this. Like-
wise,
youif want to divide a word by a word, put the
DEC CL ; Subtract one from contents of CL register
dividend word in AX. and fill DX with all O's. The SUB
DEC BP ; Subtract one from contents of BP register DX, DX instruction does this quickly.

DEC BYTE PTR [BX] ; Subtract one from byte at offset EXAMPLES (CODING):
[BX] in DS. The BYTE PTR directive is necessary to tell the
DIV BL ; Word in AX/byte in BL.
assembler to put in the correct code for decrementing a
: Quotient in AL, remainder in AH.
byte in memory, rather than decrementing a word. The
instruction essentially says "Decrement the byte in DIV CX : Double word in DX and AX word in CX.
memory pointed to by [BX)." : Quotient in AX. remainder in DX.

DEC WORD PTR [BP] ; Subtract one from a word at DIV SCALE[ BX] ; AXIbyte at effective address
offset [BP] in SS. The WORD PTR directive tells the as- SCALE[BX]) if SCALE1BX] is of type byte or IDX and
sembler
put to in the code for decrementing a word AX) (word at effective address SCALE[BX|) if
pointed to by the contents of BP. An offset in BP will be
SCALE[BX] is of type word.
added to the SS register contents to produce the physi-
cal address. EXAMPLE (NUMERICAL)

DEC TOMATO CAN COUNT ; Subtract one from byte AX = 37D7H = 14295 decimal

or word named TOMATO. CAN. COUNT in DS. If BH = 97H =151 decimal

TOMATO _CAN_COUNT was declared with a DB then the DIV BH : AXBH

assembler will code this instruction to decrement a byte. Quotient in AL = 5EH = 94 decimal.

If TOMATO CAN COUNT declared with DW. then the Remainder in AH = 65H = 101 decimal.

assembler will code this instruction to decrement a


word. Since the remainder is greater than half of the divisor,
the actual quotient is closer to 5FH than to the 5EH pro-
DEC HERD. COUNT [BX] : Decrement word or byte at duced. However,
as indicated above, the quotient is al-
offset [BX] in array HERD COUNT. Array is in DS Tins
ways truncated to the next lower integer rather than
instruction will decrement a byte if HERD -COUNT was rounded to the closest integer. If you want to round the
declared with a DB. It will decrement a word if
quotient, you can compare the remainder with (divisor
HERD COUNT was declared with a DVV directive. 2). and then add one to the quotient if the remainder is
greater than the (divisor 2).
DIV INSTRUCTION— Unsigned divide— DIV
source
ENTER— 80186/80188 ONLY— Enter Procedure
This instruction is used to divide an unsigned word by a
byte, or to divide an unsigned double word (32 bits) by a This instruction is used at the start of an assembly lan-
word. guage procedure which is intended to be called from a
When dividing a word by a byte, the word must be in high-level language program such as those written in
the AX register. After the division AL will contain an Pascal or C. Its main functions are to save space on the
8-bit result (quotient) and AH will contain an 8-bit re- stack for variables used in the procedure, and to deter-
mainder.
an attempt
If is made to divide by 0 or the mine pointers to data areas in the stack used by lower-
quotient is too large to fit in AL (greater than FFH). the level procedures (subprocedures). Refer to the Intel liter-
8086 will automatically do a type 0 interrupt. Interrupts ature for
further explanation of this instruction if you
are explained in Chapter 8. need it.

150 ( H \PTER SIX


ESC INSTRUCTION [Tie dividend foi IDIV musf alwaj s be In AX or DX and
Escape — ESC \\ but the source ol the divlsoi can be a register 01 .1
memory location specified by any one ol the 24 address
rhls Instruction Is used to pass Instructions to a
in" modes shown in Figure 3 8. II the divisor does not
coprocessoi such as the 8087 math coprocessor which
divide Into the dividend the quotienl will be truncated,
shares the address and data bus with an 8086 Instruc
nol rounded, rhe example below will illustrate this All
tions for the coprocessor are represented by .1 t> bil < mlr
flags are undefined after an II )IV.
Imbedded in the escape instruction. As the 8086 fetches
Instruction bytes, the coprocessoi .ils<> catches these It you want to divide .1 signed byte by a signed byte,
bytes from the data lius and puts them in lis queue you must lust put the dividend byte in AL and fill AH
with copies ol the sign bit from AL. In other words. 1I AL
However, the coprocessoi treats all ol the normal 8086
is positive (sign bil 01 then AH should be filled with
instructions as NOPs. When the 8086 fetches an ESC
Instruction, the coprocessor decodes the instruction O'S. II AL is negative (sign bit 1). the All should be
filled with Is, The 8086 Converl Byte to Word instruc-
and carries out the action specified by the (> l>ii code
tion,
BW,( does this by copying the sign I) it of AL to all
specified in the instruction. In most rases the 8086
treats the ESC instruction as a N( )l\ In some cases the the bits of AH. All is then said to contain the sign ex-
8086 will access a data item in memory for tin- coproces- tension
AL."ol Likewise, it you want to divide a signed
sor.section
A in Chapter I 1 describes the operation and word by a signed word, you must put the dividend word
in AX and extend the sign of AX to all the bits of DX. The
use of the ISC instruction.
8086 Convert Word to Doubleword instruction, CWD.
will copy the sign bil of AX to all the bits of DX.

EXAMPLES (CODING)
HLT INSTRUCTION
Halt processing — HLT ; Signed word in AX/signed byte
The HIT instruction will cause the 8086 to stop fetching ; in BL
and executing instructions. The 8086 will enter a halt
state. The only ways to get the processor out of the halt IDIV BP ; Signed double word in DX and
state are with an interrupt signal on the INTR pin. an : AX/signed word in BP
interrupt signal on the NMI pin. or a reset signal on the
RESET input. See Chapter 7 lor further details about the IDIV BYTE PTR [BX] ; AX/byte at offset |BX| in DS
halt state.
MOV AL. DIVIDEND : Position byte dividend
CBW : Extend sign of AL into AH
IDIV DIVISOR : Divide by byte divisor
IDIV INSTRUCTION
EXAMPLES (NUMERICAL)
Divide by signed byte or word — IDIV source
This instruction is used to divide a signed word by a : Example showing a signed word divided by a signed
signed byte, or to divide a signed double word (32 bitsl : byte
; AX = 00000011 10101011 = 03ABH = 939 decimal
by a signed word.
When dividing a signed word by a signed byte, the ; BL = 11010011 = D3H = -2DH = -45 decimal

word must be in the AX register. After the division. AL IDPV BL : Quotient in AL = 1 1 101 100
will contain the signed result (quotient), and AH will : AL = ECH = - 14H = -20 decimal
contain the signed remainder. The sign of the remain- : Remainder in AH = 001001 11
der will
be the same as the sign of the dividend. If an : AH = 27H = +39 decimal
attempt is made to divide by 0, the quotient is greater
than 127 (7FH). or the quotient is less than -127(81H). NOTE: Quotient is negative because positive was di-
the 8086 will automatically do a type 0 interrupt. Inter- vidednegative.
by Remainder has same sign as div-
rupts discussed
are in Chapter 8. For the 80186 this idend (positive).
range is -128 to +127.
; Example showing a signed byte divided by a signed
NOTE: When dividing a signed double word by a signed : byte
word, the most-significant word of the dividend (numer- : AL = 11001010 = -26H = -38 decimal
ator) must
be in the DX register and the least-signifi- ; CH = 0000001 1 = +3H = +3 decimal
cant wordof the dividend must be in the AX register. CBW : Extend sign of AL through AH,
After the division AX will contain a signed 16-bit quo- ; AX = 11111111 11001010
tient and
DX will contain a signed 16-bit remainder. IDIV CH ; Divide AX by CH
The sign of the remainder will be the same as the sign of ; AL = 111 10100 = -OCH = - 12 decimal
the dividend. Again, if an attempt is made to divide by 0, : AH = 11111110= -2H = -2 decimal
the quotient is greater than +32,767 (7FFFH). or the
Although the quotient is actually closer to 13
quotient is less than -32.767 (800 1H). the 8086 will
(12.666667) than to 12. the 8086 truncates it to 12
automatically do a type 0 interrupt.
rather than rounding it to 13. If you want to round the
NOTE: For the 80186 this range is -32.768 to quotient, you can compare the magnitude of the re-
+ 32,767. mainder the
with (dividend/2) and add one to the quo-

808b INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 151


tient if the remainder is greater than (dividend/2). Note EXAMPLES! NUMERICAL):
that the sign of the remainder is the same as the sign of
(«)
the dividend (negative). All flags are undefined after
AL = 01000101 = 69 decimal
IDIV.
BL = 00001 1 10=14 decimal
AX = +966 decimal
AX = 00000011 11000110
MSB = 0. positive result
IMUL INSTRUCTION— Multiply signed magnitude in true form.
number — IMUL source SF = 0. CF = 1, OF = 1
This instruction multiplies a signed byte from some
source times a signed byte in AL. or a signed word from (b)

some source times a signed word in AX. The source can AL = 11100100 = -28 decimal
be another register or a memory location specified by BL = 001 1 101 1 = +59 decimal

any one of the 24 addressing modes shown in Figure IMUL BL ; AX = - 1652 decimal
3-8. When a byte from some source is multiplied by AL. AX = 11111001 10001100
the signed result (product) will be put in AX. A 16-bit MSB = 1, negative result
destination is required because the result of multiplying magnitude in 2's complement.
two 8-bit numbers can be as large as 16 bits. When a SF = 1, CF = 1. OF = 1
word from some source is multiplied by AX, the result
can be as large as 32 bits. The high-order (most-signifi-
cant) wordof the signed result is put in DX and the IMUL— 80186/80188 ONLY— Integer (signed)
low-order (least-significant) word of the signed result is Multiply Immediate — IMUL destination register,
put in AX. If the magnitude of the product does not re- source, immediate byte or word
quireofallthe bits of the destination, the unused bits This version of the IMUL instruction functions the same
will be filled with copies of the sign bit. If the upper byte as the IMUL instruction described in the preceding sec-
of a 16-bit result or the upper word of a 32-bit result tion except
that this version allows you to multiply an
contains only copies of the sign bit (all O's or all Is), immediate byte or word by a byte or word in a specified
then the CF and the OF will both be O's. If the upper byte register and put the result in a specified general-
of a 16-bit result or the upper word of a 32-bit result purpose register. If the immediate number is a byte, it
contains part of the product, the CF and OF will both be will be automatically sign-extended to 16 bits. The
Is. You can use the status of these flags to determine source of the other operand for the multiplication can be
whether the upper byte or word of the product needs to a register or a memory location specified by any one of
be kept. The AF, PF. SF. and ZF are undefined after the addressing modes shown in Figure 3-8. Since the
IMUL. result is put in a 16-bit general-purpose register, only
If you want to multiply a signed byte by a signed word,
the lower 16 bits of the product are saved!
you must first move the byte into a word location and fill
the upper byte of the word with copies of the sign bit. If
EXAMPLE:
you move the byte into AL you can use the 8086 Convert
Byte to Word instruction, CBW. to do this. CBW extends IMUL CX. BX, 07H : Multiply contents of BX times
the sign bit from AL into all the bits of AH. Once you ; 07H and put
have converted the byte to a word, you can do word
: lower 16 bits of result in CX
times word IMUL. The result will be in DX and AX.

IN INSTRUCTION— IN accumulator, port


EXAMPLES! CODING ): The IN instruction will copy data from a port to the ac-
cumulator.
an 8-bitIf port is read, the data will go to AL.
IMUL BH Signed byte in AL times signed If a 16-bit port is read, the data read will go to AX. The IN
byte in BH, result in AX instruction has two possible formats, fixed port and var-
IMUL AX : AX times AX. result in DX and AX iable port.
For the fixed port type the 8-bit address of a port is
; Example showing a signed byte multiplied by a specified directly in the instruction.
: signed word
MOV CX. MULTIPLIER EXAMPLES:
Load signed word
multiplier in CX
IN AL. 0C8H : Input a byte from port 0C8H to AL
MOV AL. MULTIPLICAND Load byte multiplicand
into AL
IN AX. 34H : Input a word from port 34H to AX
CBW Extend sign of AL into AH
IMUL CX Word multiply: A TO_D EQU 4AH
result in DX and AX IN AX, A_TO D : Input a word from port 4AH to AX

152 CHAPTER SIX


For the variable porl type in Instruction, the port ad PRICES was defined .is an array <>! bytes with .1 DB dl
dress is contained In the 1).\ reglstei Since DX Is .1 re< tive
16 bii register, the port address can be any numbei be
\( HI rhe PTR operator is nol needed In die lasl two
tween 0000H and FFFFH. rherefore. up to 65,536 ports
examples because the assembler knows die type ol the
are addressable in 1Ins mode . rhe DX register, howevei
operand from the DM 01 DW used to dec late the named
must always be loaded with the porl address befon th<
IN Instruction. daia initially.

EXAMPLES:
INS/INSB/INSW— HO18<>80 188 ONLY— Input
MOV DX.0FF78H Initialize DX to point to porl String from Port — INS destination string, DX
IN AL, DX Input a byte from 8 bil porl ins copies a byte or a word from a porl to a memorj
0FF78H lo AI. location in the extra segmenl pointed to by Dl The ad
dress ol the port lo be copied from must be put 111 DX
IN AX. DX Input a word from 16-bil poll
before this instruction executes. 11 the direction Hag is
0FF78II to AX
cleared when this instruction executes. I )l will automal
leallv be incremented l>v one for a byte operation, and
rhe variable-port IN instruction has the advantage thai incremented by two for a word operation alter the data
the port address can be computed or dynamically deter is copied from the port. II the direction Hag is set, Dl will
mined 111 the program. Suppose, tor example, that an automatically be decremented by one for a byte opera
8086-based computer needs to input data from 10 ter- tion and decremented by two for a word operation after
minals, having
each its own port address. Instead of
data is copied from the porl. When used with the Kl P
having separate routines to input data from each port,
prefix or as part of a loop, the INS instruction can input
we can write one general input subroutine and simply a block of data directly to a scries of memory locations
pass the address of the desired port to the subroutine in
without having the data go through AL or AX as it does
DX. The IN instructions do not change any flags.
with the regular IN instruction.
When using the INS instruction you must in some waj
tell the assembler whether you want to input bytes or
INC INSTRUCTION— INCREMENT destination
input words. There are two ways to do this. The first is
The INC instruction adds 1 to the indicated destination. to use the name of the destination string in the instruc-
The destination can be a register or memory location tion statement as in the statement INS BUFFER, DX. The
specified by any one of the 24 ways shown in Figure 3-8. assembler will code the instruction for a byte input if
The AF. OF, PF, SF, and ZF are affected (updated) by this BUFFER was declared with a DB and it will code the
instruction. Note that the carry flag, CF. is not affected. instruction for a word input if BUFFER was declared
This means that if an 8-bit destination containing FFH with a DW. The second way to tell the assembler whether
or a 16-bit destination containing FFFFH is incre- to code the instruction for a byte or for a word input is to
mented,
result
the will be all O's with no carry. add a B or a W to the basic instruction mnemonic. For
example. INSB DX. tells the assembler to code the in-
EXAMPLES: struction
copying
for a byte from a port pointed to by DX
to a memory location pointed to by Dl in the extra seg-
INC BL ; Add 1 to contents of BL registei
ment. INS
affects no Hags.
INC CX : Add 1 to contents of CX register
EXAMPLE:
INC BYTE PTR [BX] ; Increment byte at offset of BX in
data segment. The BYTE PTR directive is necessary to CLD Clear direction flag to
tell the assembler to put in the right code to indicate autoincrement Dl
that a byte in memory, rather than a word, is to be in-
MOV Dl, OFFSET BUF ; Point Dl at input buffer
cremented.
instruction
The essentially says "increment
the byte pointed to by the contents of BX." MOV DX. 0FFF8H : Load DX with

INC WORD PTR IBX|: Increment the word at offset of : port address
|BX] and |BX + 1] in the data segment. In other words. MOV CX. LENGTH BUF : Load number of bytes
increment the word in memory pointed to by BX. : to be read in CX

INC MAX TEMPERATURE : Increment byte or word REP INSB DX Copy bytes from port
named MAX TEMPERATURE in data segment. Incre- until buffer full
ment byteif MAX TEMPERATURE declared with DB.
Increment word if MAX TEMPERATURE declared with
DW. INT INSTRUCTION— Interrupt program
INC PRICES [BX] : Increment element [BX] in array
execution — INT type
PRICES. Increment a word if PRICES was defined as an This instruction causes the 8086 to call a far procedure
array of words with a DW directive. Increment a byte if in a manner similar to the way in which the 8086 re-

8t)8b INSTRUCTION DESCRIPTIONS AND ASSEMBttR DIRECTIVES 153


sponds to an interrupt signal on its INTR or NMI inputs. EXAMPLE:
Part of the response is to do an indirect far call to a pro-
INTO ; Call interrupt procedure if OF = 1
cedure which
responds to that particular interrupt. The
term type in the instruction refers to a number between
0 and 255 which identifies the interrupt. When an 8086
executes an INT type instruction, it will: IRET INSTRUCTION— Interrupt return— IRET
When the 8086 responds to an interrupt signal or to an
1. Decrement the stack pointer by two and push the interrupt instruction, it pushes the flags, the current
nags on the stack. value of CS, and the current value of IP on the stack. It
2. Decrement the stack pointer by two and push the then loads CS and IP with the starting address of the
contents of CS on the stack. procedure which you write for the response to that in-
terrupt.IRET
The instruction is used at the end of the
3. Decrement the stack pointer by two and push the
interrupt service procedure to return execution to the
offset of the next instruction after the INT number
interrupted program. To do this return the 8086 copies
instruction on the stack.
the saved value of IP from the stack to IP, the stored
4. Get a new value for IP from an absolute memory ad- value of CS from the stack to CS, and the stored value of
dress
4 oftimes the type specified in the instruction. the flags back to the flag register. Flags will have the
For an INT 8 instruction, for example, the new IP will values they had before the interrupt, so any flag settings
be read from address 00020H. from the procedure will be lost unless they are specifi-
cally saved
in some way.
5. Get a new value for CS from an absolute memory
address of 4 times the type specified in the instruc- NOTE: The RET instruction should not normally be
tion plus2. For an INT 8 instruction, for example, used to return from interrupt procedures because it
the new value of CS will be read from address does not copy the flags from the stack back to the flag
00022H. register. See Chapter 8 for further discussion of inter-
rupts and
the use of IRET.
6. Reset both the IF and the TF. Other flags are not
affected.
EXAMPLE:

Chapter 8 further describes the use of this instruction. [RET

EXAMPLES:

INT 35 : New IP from 0008CH, new CS from 0008EH JA/JNBE INSTRUCTION— Jump if above/Jump if
INT 3 ; This is a special form which has the single
not below nor equal
byte code of CCH. Many systems use this as a break- These two mnemonics represent the same instruction.
point instruction. New IP from 0000CH. new CS from The terms "above" and "below" are used when referring
0000EH. to the magnitude of unsigned numbers. The number
0111 is above the number 0010. If, after a compare or
some other instruction which affects flags, the zero flag
INTO INSTRUCTION— Interrupt on overflow and the carry flag are both 0, this instruction will cause
execution to jump to a label given in the instruction. If
If the overflow flag. OF, is set. this instruction will cause
CF and ZF are not both 0. the instruction will have no
the 8086 to do an indirect far call to a procedure you
effect on program execution. The destination label for
wi ite to handle the overflow condition. Before doing the
the jump must be in the range of - 128 bytes to +127
call the 8086 will:
bytes from the address of the instruction after the JA.
(A/JNBE affects no flags. For further explanation of con-
1. Decrement the stack pointer by 2 and push the Hags
ditional jump
instructions, see Chapter 4.
on the stack.

2. Decrement the stack pointer by 2 and push CS <>n


the stack. EXAMPLES:

3. Decrement the stack pointer by 2 and push the off-


CMP AX. 437 1H Compare by subtracting 437 1H
set ofthe next instruction after the INTO instruc-
from AX
tion on
the stack
JA RUN PRESS Jump to label RUN PRESS if AX
4. Reset the TF and the IF. other flags are not affected. above 437 1H

To do the call the 8086 will read a new value for IP from CMP AX, 437 1H Compare by subtracting 437 1H
address 0001 OH and a new value of CS from address from AX
000 12H. JNBE RUN PRESS Jump to label RUN PRESS if A\
Chapter 8 further describes the 8086 interrupt sys- not below nor

tem. equal to 437 1H

154 ( HAPTERSIX
IAE/JNB/JNC INSTRUCTIONS ( Ml' AX. 4371H ( lompare by subl i
jump if above or equal lump if not below/Jump from AX
if no carry JNAE Rl IN I Jump in label RUN PRESS il
AX in ii above um
These three mnemonics repi esenl i lie same Instruction,
equal to 137 in
rhe terms "abov« and "below" arc used when referring
in the magnitude of unsigned numbers. The number
ol l l is above the numbei 0010. It. aftei a compare oi
some other instruction which affects flags, the carry flag
is 0. ihis instruction will cause execution to jump to a IBE/JNA INSTRUCTIONS
label given in the Instruction. If CF is 1, the Instruction Jump if below or equal/Jump if not above
will have n<> effect on program execution. The destina These two mnemonics represent the same instrui i
tion label tin the jump must be in the range of 128 The terms "above" and "below" are used when referring
bytes to • 127 bytes from the address ol the instruction to the magnitude ol unsigned numbers. The number
alter the |A. |AI INB/JNC affects no flags. For further 01 1 1 is above the number OOlO. If, alter a compare or
explanation ol conditional jump instructions, see ( hap some other instruction which affects flags, cither the
ter 4. zero flag or the carry flag is 1. (his instruction will cause
execution to jump to a label given in the instruction. If
CF and ZF are both 0, the instruction will have no effect
EXAMPLES: on program execution. The destination label for the
CMP AX. 437 111 jump must be in the range of - 128 bytes to +127 bytes
: Compare by subtracting 437 1H
from the address of the instruction after the J BE. |BE/|NA
: from AX
JAE RUN PRESS : Jump to label RUN PRESS if AX affects no Hags. For further explanation of conditional
; is above or equal to 437 1H jump instructions, see Chapter 4.

CMP AX. 437 1H ; Compare by subtracting 437 1H


: from AX
EXAMPLES:
JNB RUN PRESS : Jump to label RUN PRESS if AX
; not below 437 1H CMP AX, 437 1H ; Compare by subtracting 437 1H
: from AX
ADD AL. BL ; Add two bytes
JBE RUN PRESS : Jump to label RUN_PRESS if AX
JNC OK ; Result within acceptable range.
; is below or equal to 437 1H
; continue

CMP AX, 437 1H : Compare by subtracting 437 1H


: from AX
JNA RUN_PRESS ; Jump to label RUN PRESS if AX
JB/JC/JNAE INSTRUCTIONS : not above 437 1H
Jump if below/Jump if carry/Jump if not above
nor equal
These three mnemonics represent the same instruction. JCXZ INSTRUCTION
The terms "above" and "below" are used when referring
jump if the CX register is zero
to the magnitude of unsigned numbers. The number
This instruction will cause a jump to a label given in the
0111 is above the number 0010. If. after a compare or
instruction if the CX register contains all O's. If CX does
some other instruction which affects flags, the carry flag
not contain all O's, execution will simply proceed to the
is a 1 , this instruction will cause execution to jump to a
next instruction. Note that this instruction does not
label given in the instruction. If CF is 0. the instruction
look at the zero flag when it decides whether to jump or
will have no effect on program execution. The destina-
not. The destination label for this instruction must be
tion labelfor the jump must be in the range of -128
in the range of - 128 to +127 bytes from the address of
bytes to +127 bytes from the address of the instruction
the instruction after the JCXZ instruction. |CXZ affects
after the |B. |B/JC/]NAE affects no flags. For further ex-
no flags.
planation
conditional
of jump instructions, see Chap-
ter 4.
EXAMPLE:

EXAMPLES:
; If CX already 0 skip over the process
CMP AX. 4371H : Compare by subtracting 437 1H JCXZ SKIP LOOP
: from AX Subtract 7 from
LOOP SUB [BX1. 07H
JB RUN PRESS : Jump to label RUN PRESS if
data value
: AX below 437 1H
INC BX point to
ADD BX. CX : Add two words next value
JC ERROR FIX : Jump to label ERROR FIX if LOOP COUNT Loop until CX = 0
; CF = 1 SKIP LOOP: next instruction

8086 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 155


jE/JZ INSTRUCTIONS— Jump if equal/Jump if relationship of two signed numbers. Greater means
more positive. The number 00000111 is greater than
zero
the number 11101010. because the second number is
These two mnemonics represent the same instruction.
negative. This instruction is usually used after a com-
If the zero flag is set, then this instruction will cause
pare instruction. The instruction will cause a jump to a
execution to jump to a label given in the instruction. If
label given in the instruction if the sign flag is equal to
the zero flag is not 1 , then execution will simply go on to
the overflow Hag. The destination label must be in the
the next instruction after )E or JZ. The destination label
range of - 128 bytes to +127 bytes from the address of
for the JE/JZ instruction must be in the range of - 128 to
the instruction after the JGE/JNL instruction. If the jump
+ 127 bytes from the address of the instruction after the
is not taken, execution simply goes on to the next in-
JE/JZ instruction. JE/JZ affects no flags.
struction
theafter
JGE or JNL instruction. JGE/JNL affects
no flags.
EXAMPLES:
EXAMPLES:
AGAIN: CMP BX. DX Compare by subtracting DX
CMP BL, 39H Compare by subtracting 39H
from BX
from BL
JE DONE Jump to label DONE
JGE SHORT_LABEL Jump to label if BL more
if BX = DX
Else subtract AX
positive than 39H
SUB BX. AX
INC CX Increment counter or equal to 39H
JMP AGAIN Check again CMP BL. 39H Compare by subtracting 39H
DONE: MOV AX. CX Copy count to AX from BL
JNL SHORT LABEL Jump to label if BL not less
IN AL. 8FH Read data from port 8FH
than 39H
SUB AL, 30H Subtract minimum value
JZ START MACHINE Jump to label if result of
subtraction was 0

JL/JNGE INSTRUCTION— Jump if less than/jump


if not greater than nor equal
JG/JNLE INSTRUCTION— Jump if greater/jump These two mnemonics represent the same instruction.
if not less than nor equal The terms "greater" and "less" are used to refer to the
relationship of two signed numbers. Greater means
These two mnemonics represent the same instruction.
more positive. The number 00000111 is greater than
The terms "greater" and "less" are used to refer to the
the number 11101010, because the second number is
relationship of two signed numbers. Greater means
negative. This instruction is usually used after a com-
more positive. The number 00000111 is greater than
pare instruction. The instruction will cause a jump to a
the number 11101010, because the second number is
label given in the instruction if the sign flag is not equal
negative. This instruction is usually used after a com-
to the overflow flag. The destination label must be in the
pare instruction. The instruction will cause a jump to a
range of - 128 bvtes to +127 bytes from the address of
label given in the instruction if the zero flag is 0 and the
the instruction after the JL/JNGE instruction. If the jump
carry flag is the same as the overflow flag. The destina-
is not taken, execution simply goes on to the next in-
tion label
must be in the range of -128 bytes to + 127
struction
theafterJL or JNGE instruction. JL/JNGE affects
bytes from the address of the instruction after the JG/
no Hags.
JN LE instruction. If the jump is not taken, execution
simply goes on to the next instruction after the |G or EXAMPLES:
|NLE instruction. |G/|NLE affects no flags.
CMP BL, 39H Compare by subtracting 39H
EXAMPLES: from BL
JL SHORT LABEL Jump to label if BL more
CMP BL. 39H ; Compare by subtracting 39H
negative than 39H
: from BL
JG SHORT LABEL ; Jump to label if BL more CMP BL, 39H Compare by subtracting 39H
: positive than 39H from BL
JNGE SHORT LABEL Jump to label if BL not more
CMP BL, 39H : Compare by subtracting
positive than 39H
; 39H from BL
JNLE SHORT LABEL ; Jump to label if BL not less
or BL not equal to 39H
: than nor equal to 39H

JGE/JNL INSTRUCTION— Jump if greater than JLE/JNG INSTRUCTIONS— Jump if less than or
or equal/Jump if not less than equal/Jump if not greater
These two mnemonics represent the same instruction. These two mnemonics represent the same instruction.
I In terms "greater" and "less" are used to refer to the The terms "greater" and "less" are used to refer to the

156 ( HAPTER SIX


relationship ol two signed numbers. Greatei means . IMI' WORD PTR |BX] : Replace II" with a word from a
more positive. The number 0O0OOJ l l in greatei than memory location pointed to by MX In DS. llus is an
the numbei I l 101010, because the second numbei is induce 1 neai |ump.
negative, llus Instruction is usually used aftei a com
JMP l »W<>R1> PTR [SI] : Replace IP with word pointed
pan- instruction. The instruction will cause .1 jump to .1
in by si m DS. Replace CS with woid pointed to by SI •
label given m the instruction il the zero flag is set, 01 il
2 in DS. This is an Indirect far jump.
the sign flag is not equal to the overflow flag. The desti
nation label must be In the range ol 128 bytes to 12"!
bytes from the address oi the instruction aftei the II I
|NG instruction. It the jump is nol taken, execution
jNA/|BE INSTRUCTION— )ump if not above/
simply goes on to the next instruction after the ILE/JNG
Jump if below or equal
instruction. Ill INC. affects no flags Please refer to the discussion ol tins instruction under
ilu heading IBI -

I XAMPLES:
JNAE/JB INSTRUCTION— Jump if not above or
CMP BL, 39H ; Compare by subtracting 39H equal/Jump if below
; from BL
Please refer to the discussion of this instruction under
JLE SHORT LABEL : Jump to label if BL more
the heading IB.
; negative than 391 1 01
; equal to 39H
CMP BL. 39H ; Compare by subtracting 39H JNB/JNC/JAE INSTRUCTION— Jump if not
; from BL below/Jump if no carry/Jump if above or equal
JNG SHORT LABEL ; Jump to label if BL not more
Please refer to the discussion of this instruction under
: positive than 39H the heading |AF.

JMP INSTRUCTION— Unconditional jump to


specified destination JNBE/JA INSTRUCTION— Jump if not below or
equal/Jump if above
This instruction will always cause the 8086 to fetch its
Please refer to the discussion of this instruction under
next instruction from the location specified in the in-
the heading |A.
struction rather
than from the next location after the
IMP instruction. If the destination is in the same code
segment as the IMP instruction, then only the instruc-
tion pointer will be changed to get to the destination
JNC/JNB/JAE INSTRUCTION— Jump if not
location. This is referred to as a near jump. If the desti-
carry/Jump if not below/Jump if above or equal
nationthe
for jump instruction is in a segment w^h a Please refer to the discussion of this instruction under
name different from that containing the )MP instruc- the heading )AE.
tion, thenboth the instruction pointer and the code
segment register contents will be changed to get to the
destination location. This is referred to as a far jump. JNE/JNZ INSTRUCTION— Jump if not equal/
The IMP instruction affects no flags. Refer to a section in Jump if not zero
Chapter 4 for a detailed discussion of the different forms These two mnemonics represent the same instruction.
of the unconditional )MP instruction. If the zero flag is 0. then this instruction will cause exe-
cution
jumpto to a label given in the instruction. If the
EXAMPLES: zero flag is 1, then execution will simply go on to the
JMP CONTINUE : Fetch next instruction from address next instruction after |NE or JNZ. The destination label
at label CONTINUE. If label is in same segment, an offset for the )NE/)NZ instruction must be in the range of - 128
coded as part of the instruction will be added to the to +127 bytes from the address of the instruction after
instruction pointer to produce the new fetch address. If the JNE/JNZ instruction. JNE/JNZ affects no flags.
the label is in another segment then IP and CS will be
replaced with values coded in as part of the instruction.
This type of jump is referred to as direct because the EXAMPLES
displacement of the destination or the destination itself
AGAIN IN AL, 0F8H ; Read data value from port
is specified directly in the instruction.
CMP AL, 72 ; Compare by subtracting
JMP BX ; Replace the contents of IP with the contents : 72 from AL
of BX. BX must first be loaded with the offset of the JNE AGAIN : Jump to label AGAIN if
destination instruction in CS. This is a near jump. It is : AL not equal 72
also referred to as an indirect jump because the new IN AL, 0F9H : Read next port when
value for IP comes from a register rather than from the ; AL = 72
instruction itself as in a direct-type jump. MOV BX. 2734H ; Load BX as counter

8086 INSTRUCTION DESCRIPTIONSAND ASSEMBLERDIRECTIVES 1 57


NEXT 1 : ADD AX. 0002H Add count factor to AX instruction after the JNO/JPO instruction. The JNO JPO
DEC BX instruction affects no flags.
JNZ XEXT 1: Repeat until BX = 0

EXAMPLE:

JNG/JLE INSTRUCTION— lump it not greater IN AL. 0F8H Read ASCII character
Jump if less than or equal from UART

Please refer to the discussion of this instruction under OR AL. AL Set flags
the heading |LE.
JPO ERR MESSAGE Even parity expected, send
error message if parity
)NGE JL INSTRUCTION— Jump if not greater found odd
than nor equal Jump if less than
Please refer to the discussion of this instruction under
the heading JL. JNS INSTRUCTION— Jump if not signed (Jump
if positive)
This instruction will cause execution to jump to a speci-
JNL/JGE INSTRUCTION— lump if not less than fied destination if the sign flag is 0. Since a 0 in the sign
Jump if greater than or equal flag indicates a positive signed number, you can think
Please refer to the discussion of this instruction of this of this instruction as saying "jump if positive." If the
instruction under the heading |CE. sign flag is set. indicating a negative signed result, exe-
cutionsimply
will go on to the next instruction after
JNS. The destination for the jump must be in the range
JNLE JG INSTRUCTION— lump if not less than of -128 bytes to -127 bytes from the address of the
nor equal to/Jump if greater than instruction after the JNS. JNS affects no flags.
Please refer to the discussion of this instruct inn under
the heading )G. EXAMPLE:

DEC AL ; Decrement counter

JNO INSTRUCTION— Jump if no overflow JNS REDO : Jump to label REDO if counter has not

The overflow flag will be set if the result of some signed : decremented to FFH
arithmetic operation is too large to fit in the destination
register or memory location. The JNO instruction will
cause the 8086 to jump to a destination given in the
instruction if the overflow flag is not set. The destina- JNZ JNE INSTRUCTION— Jump if not zero Jump
tion mustbe in the range of - 128 bytes to - 127 bytes if not equal
from the address of the instruction after the JNO in- Please refer to the discussion of this instruction under
struction.
the overflow
If flaa is set. execution will sim- the heading JSE.
ply continue with the next instruction after ISO. |NO
affects no flags.

JO INSTRUCTION— Jump if overflow


EXAMPLE:
The overflow flag will be set if the result of some signed
ADD AL. BL Add signed bytes in AL and BL arithmetic operation is too large to fit in the destination
register or memory location. The JO instruction will
JNO DONE Process done if no overflow
cause the 8086 to jump to a destination given in the
MOV AL. 00H Else load error code in AL instruction if the overflow flag is set. The destination
must be in the range of - 128 bytes to - 127 bytes from
DONE: OUT 24H.AL Send result to display
the address of the instruction after the JO instruction. If
the overflow flag is not set. execution will simply con-
tinue with
the next instruction after JO. JO affects no
JNP JPO INSTRUCTION— Jump if no parity flags.
Jump if parity odd
If the number of Is left in a data byte after an instruc- EXAMPLE:
tion whichaffects the parity flag is odd. then the parity
flag will be 0. The JNP JPO instruction will cause execu- ADD AL. BL Add signed bytes in AL and BL
tionjump
to to a specified destination address if the Jump to label ERROR if overflow
JO ERROR
parity flag is 0. The destination address must be in the
from add
range of - 128 bytes to +127 bytes from the address of
the instruction after the JNP JNO instruction. If the par- MOV SUM. AL Else put result in memory location
ity flag is set. execution will simply continue on to the named SUM

158 CHAPTER SIX


|P/|PE INSTRUCTION — Jump if parity lump if I AMI INSTRUCTION— Copy low byte of flag
parity even register to AH
li the numbei ol L's left in a data word aftei an Instruc The lower byte ol the 8086 flag registei is the same as
Hon which affects the parity flag is even, then the pai Ity the flag byte foi the 8085 l \HI copies these 8085 equiv-
flag will be set. The II' H'l Instruction will cause exe< u alenl flags to the All register. They can then be pushed
don to |ump id a specified destination address il the on the stack along with AL by a PUSH AX instruction. An
parity lias; is set. II the parity flag is 0, execution will LAHI Instruction followed by a PUSH AX instruction has
simply continue on to the instruction after the |l' H'l the same effect as the 8085 PUSH PSW instruction n i-
Instruction. The destination address must be in the LAHI instruction was included in the 8086 Instruction
range ol 128 bytes to * 127 bytes from the address ol sel so thai the 8085 PUSH PSW instruction could easil;
the Instruction after the IP H'l instruction. The IP |PI be simulated on an 8086. LAHI changes no flags.
Instruction affects no flags
EXAMPLE: LAI IK
EXAMPLE:

IN AL. 0F8H Read ASCII charactei


LDS INSTRUCTION— Load register and DS with
from UART
words from memory — LDS register, memory
OR AL. AL Sel flags address of first word

JPE ERR MESSAGE Odd parity expected, send This instruction copies a word from two memory loca-
error message if parity tions into
the register specified in the instruction. It
found even then copies a word from the next two memory locations
into the DS register. IDS is useful for pointing SI and
DS at the start of a string before using one of the string
instructions. LDS affects no flags.
JPE/JP INSTRUCTION -lump if parity even/
Jump if parity EXAMPLES:
Please refer to the discussion of this instruction under
the heading IP. LDS BX. 14326] ; Copy contents of memory at
displacement 4326H in DS to BL, contents of 4327H
to BH. Copy contents at displacement of 4328H and
4329H in DS to DS register.
JPO/JNPINSTRUCTION-Jump if parity odd/
jump if no parity LDS SI. STRING POINTER ; Copy contents of
Please refer to the discussion of this instruction under memory at displacements STRING POINTER and
the heading |NP. STRING _POINTER + 1 in DS to SI register. Copy
contents of memory at displacements
STRING POINTER + 2 and STRING POINTER+3 in DS

JS INSTRUCTION— Jump if signed (Jump if to DS register. DS:SI now points at start of desired
negative) string.

This instruction will cause execution to jump to a speci-


fied destination if the sign flag is set. Since a 1 in the LEA INSTRUCTION— Load Effective Address—
sign (lag indicates a negative signed number, you can LEA register, source
think of this instruction as saying "jump if negative" or
"jump if minus." If the sign flag is 0, indicating a posi- This instruction determines the offset of the variable or
tive signed
result, execution will simply go on to the next memory location named as the source and puts this off-
instruction after )S. The destination for the jump must set inthe indicated 16-bit register. LEA changes no
be in the range of - 128 bytes to +127 bytes from the flags.
address of the instruction after the )S. )S affects no flags.
EXAMPLES:

EXAMPLE: LEA BX. PRICES Load BX with offset of


PRICES in DS
ADD BL, DH : Add signed byte in DH to signed
: byte in BL LEA BP. SS: STACK TOP Load BP with offset of

JS TOO COLD ; Jump to label TOO COLD if result STACK TOP in SS

: of addition is negative number


LEA CX. [BXHDII Load CX with
EA = (BX1 + (DII

JZ/JE INSTRUCTION— Jump if zero/Jump if A program example will better show the context in
equal which this instruction is used. If you look at the pro-
Please refer to the discussion of this instruction under gramFigure
in 4- 15c you will see that PRICES is an

the heading IE. array of bytes in a segment called ARRAYS JTERE. The

8086 INSTRUCTION DESCRIPTIONS AND ASSEMBtER DIRECTIVES 159


program gets a byte from this array with the instruction another processor does not take control of the system
LEA BX, PRICES. This will load the displacement of the bus while it is in the middle of a critical instruction
first element of PRICES directly into BX. The instruc- which uses the system bus. The LOCK prefix is put in
tion MOVAL, t BX] can then be used to bring an element front of the critical instruction. When an instruction
from the array into AL. After one element in the array is with a LOCK prefix executes, the 8086 will assert its bus
processed, BX is incremented to point to the next ele- lock signal output. This signal is connected to an exter-
ment. nal buscontroller device which then prevents any other
processor from taking over the system bus. LOCK affects
no flags.
LEAVE—80186/80188 ONLY— Leave procedure
EXAMPLE:
The LEAVE instruction is used at the end of an assem-
bly language procedure which is intended to be called LOCK XCHG SEMAPHORE. AL ; The XCHG
from a high level language program such as Pascal or C. instruction requires two bus accesses. The LOCK
An ENTER instruction at the start of such a procedure prefix prevents another processor from taking control
sets aside stack space for variables used in the proce- of the system bus between the two accesses.
dure andin subprocedures. The main function of the
LEAVE instruction is to increment SP and BP up over
this reserved space so they have the values they had be- LODS/LODSB/LODSW INSTRUCTION— Load
fore theENTER instruction. In other words. LEAVE re- string byte into AL or Load string word into AX
storesand
SP BP to the values they had at the start of This instruction copies a byte from a string location
the procedure. A RET instruction can then be used to pointed to by SI to AL, or a word from a string location
return execution to the calling program. Leave affects no pointed to by SI to AX. If the direction flag is cleared (0),
flags. Refer to the Intel literature for further explanation SI will automatically be incremented to point to the next
of this instruction if you need it. element of the string. For a string of bytes SI will be
incremented by one. For a string of words SI will be in-
cremented
two. Ifbythe direction flag. DF, is set ( 1). SI
LES INSTRUCTION— Load register and ES with will be automatically decremented to point to the next
words from memory — LES register, memory string element. For a byte string SI will be decremented
address of first word by one, and for a word string SI will be decremented by
This instruction loads new values into the specified reg- two. LODS affects no flags.
ister and into the ES register from four successive mem-
EXAMPLE:
ory locations. The word from the first two memory loca-
tions
copied
is into the specified register, and the word CLD : Clear direction flag so SI is autoincremented
from the next two memory locations is copied into the MOV SI, OFFSET SOURCE STRING ; Point SI at
ES register. LES can be used to point DI and ES at the : string
start of a string before a string instruction is executed. LODS SOURCE STRING
LES affects no flags.
NOTE: Assembler uses name of string to determine
whether string is of type byte or of type word. Instead of
EXAMPLES:
using the string name to do this, you can use the
LES BX. [789AH] ; Contents of memory at mnemonic LODSB to tell the assembler that the string is
displacements 789AH and 789BH in DS copied to BX. of type byte or the mnemonic LODSW to tell the
Contents of memory at displacements 789CH and assembler that the string is of type word.
789DH in DS copied to ES register.

LES DI, |BX) ; Copy contents of memory at LOOP INSTRUCTION— Loop to specified label
offset [BX] and offset [BX + 1] in DS to DI registei until CX = 0
copy contents of memory at offsets [BX + 21 and [BX +
This instruction is used to repeat a series of instruc-
3] to ES register.
tions some
number of times. The number of times the
instruction sequence is to be repeated is loaded into the
count register. Each time the LOOP instruction exe-
LOCK INSTRUCTION— Assert bus lock signal cutes. isCXautomatically decremented by one. If CX is
Many microcomputer systems contain several micro- not 0, execution will jump to a destination specified by a
processors.
microprocesor
Each has its own local buses label in the instruction. If CX = 0 after the
and memory. The individual microprocessors are con- autodecrement, execution will simply go on to the next
nected together
by a system bus so that each can access instruction after LOOP. The destination address for the
system resources such as disk drives or memory. Each jump must be in the range of - 128 bytes to +127 bytes
microprocessor only takes control of the system bus from the address of the instruction after the LOOP in-
when it needs to access some system resource. The struction. LOOP
affects no flags. See Chapter 4 for fur-
LOCK prefix allows a microprocessor to make sure that ther discussion and examples of the LOOP instruction.

160 t HAI'TtR SIX


EXAMP1 E ol instructions some number ol limes or mini the zero
flag becomes a I The number oi i imes the Instruction
MOV BX. OFFSE1 PRICES . Point BX at
sequence Is to be repeated Is loadi d Into the i ount regis
In si element In array
ler, CX. Each time the LOOPNI LOOPNZ Instruction
MOV C\. 40 Load i X wnli number ol executes, CX is automatically decremented bj one If ( X
elements In arraj is not 0 aiid the zero flag is not set . execution will jump
\L\l MOV AL, [BX] ( .el elemenl from arraj in ,i destination speed led by a label In i in In: inn tion II
ADD AL. 0711 Add coi rectlon factoi ( 'X is I aftei the autodecrement oi II the zero flag is set,
DAA I )c( imal ,id|iisl rt'sull execution will simply go on to the next instruction aftei
MOV [BX1.AL Put result back In ai i .i\ LOOPNE/LOOPNZ. In other wends, the two ways to exit
INC BX Repeat imiil .ill elements the loop are CX 0 or ZF I. rhe destination address
LOOP NEXT adjusted for the jump must be in the range ol 128bytesto I
bytes from the address of the instruction aftei the
LOOPNE/LOOPNZ instruction. LOOPNE/LOOPNZ al
LOOPE/LOOPZ INSTRUCTION— Loop while CX fects no flags, See chapter 1 for further discussion and
not = 0 and ZF = 1 examples ol the LOOPNE LOOPNZ instruction.
LOOPE and LOOPZ are two mnemonics for the same
instruction. This instruction is used to repeat a group EXAMPLE:

ol instructions some number of limes or until the zero


MOV BX, OFFSET ARRAY ; Point BX at start
flag heroines 0. The number of times the instruction
DEC BX : ol array
sequence is to be repeated is loaded into the count regis-
MOV CX, 100 : Put number ol
ter. Each lime the LOOP instruction executes. CX is
; array elements
automatically decremented by one. If CX is not 0 and the
: in CX
zero flan is set. execution will jump to a destination
NEXT: INC BX ; Point to next
specified by a label in the instruction. II CX is 0 after the
: element in array
autodecrement or if the zero flag is not set, execution
CMP [BX], 0DH . Compare array
will simply go on to the next instruction after LOOPE/
LOOPNE NEXT ; element with
LOOPZ. In other words, the two ways to exit the loop are
: ODH
CX = 0 or ZF = 0. The destination address for the jump
must be in the range of - 128 bytes to +127 bytes from
N< Ml The next element in the array is checked if the
the address of the instruction after the LOOPE/LOOPZ
element was not equal ODH and the element was not the
instruction. LOOPE/LOOPZ affects no flags. See Chapter
last one in array. If CX = 0 and ZF = 0 on exit, ODH was
4 for further discussion and examples of the LOOPE/
not found in the array. If CX does not equal 0 on exit
LOOPZ instruction.
from loop, then BX points to next element after the first
EXAMPLE: element containing ODH.

MOV BX. OFFSET ARRAY ; Point BX at start


DEC BX : of array
LOOPNZ/LOOPNE INSTRUCTION— Loop while
MOV CX. 100 : Put number of CX is not 0 and ZF = 0
; array elements Please see the discussion of this instruction under the
; in CX heading LOOPNE.

NEXT: INC BX : Point to next


: element in array
LOOPZ/LOOPE INSTRUCTION— Loop while CX
CMP [BX|, 0FFH : Compare array is not 0 and ZF = 1
: element with
Please see the discussion of this instruction under the
: FFH
heading LOOPE.
LOOPE NEXT

NOTE: The next element is checked if the element


equals FFH and the element was not the last one in the MOV INSTRUCTION— MOV destination, source
array. If CX = 0 and ZF = 1 on exit, all elements were The MOV instructions transfer a word or byte of data
equal to FFH. If CX is not equal to 0 on exit from loop,
from some source to a destination. The destination can
then BX points to next element after first byte that was
be a register or a memory location. The source can be a
not FFH. register, a memory location, or an immediate number.
The source and destination in an instruction cannot
LOOPNE/LOOPNZ INSTRUCTION— Loop while both be memory locations. The source and destination
CX is not 0 and ZF = 0 in a MOV instruction must both be of type byte, or they
LOOPNE and LOOPNZ are two mnemonics for the same must both be of type word. MOV instructions do not
instruction. This instruction is used to repeat a group affect any Hags.

808b INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 161


EXAMPLES: move a string as bytes. MOVSVV says move a string as
words.
MOV CX. 037AH Put the immediate number
037AH in CX
EXAMPLE:

MOV BL, [437AH] ; Copy byte from offset 437AH CLD Clear Direction Flag to autoincrement SI
: in DS to BL and DI
MOV AX. 00H
MOV AX, BX ; Copy contents of register BX
; to AX MOV DS. AX Initialize data segment
register to 0
MOV DL. [BX) ; Copy byte from memory address
: to DL MOV ES, AX Initialize extra segment
register to 0
: Offset of memory address
; in DS is in BX MOV SI. 2000H Load offset of start of source
string into SI
MOV DS. BX ; Copy word from BX to data
MOV DI. 2400H Load offset of start of
; segment register
destination into DI
MOV RESULTS [BP], AX ; Copy AX to two memory
locations. AL to first location, AH to second. EA of MOV CX, 04H Load length of string in CX
first memory location is the sum of displacement as counter
represented by RESULTS and contents of BP. Physical REP MOVSB Decrement CX and
address = EA + SS. MOVSB until CX = 0

MOV CS:RESULTS |BP], AX ; Same as the above


instruction, but Physical Address = EA + CS because After move SI will be one greater than offset of last byte
of segment override prefix. CS. in source string. DI will be one greater than offset of last
byte of destination string. CX will be 0.

MOVS/MOVSB/MOVSW INSTRUCTION— Move MUL INSTRUCTION— Multiply unsigned bytes


string byte or string word — MOVS destination,
or words — MUL source
source
This instruction multiplies an unsigned byte from some
This instruction copies a byte or word from a location in
source times an unsigned byte in the AL register, or an
the data segment to a location in the extra segment. The
unsigned word from some source times an unsigned
offset of the source byte or word in the data segment
word in the AX register. The source can be a register or a
must be in the SI register. The offset of the destination
memory location specified by any one of the 24 address-
in the extra segment must be contained in the DI regis-
ing modesshown in Figure 3-8. When a byte is multi-
ter. Formultiple byte or multiple word moves the num-
pliedtheby contents of AL, the result (product) is put in
ber of
elements to be moved is put in the CX register so
AX. A 16-bit destination is required because the result
that it can function as a counter. After the byte or word
of multiplying an 8-bit number by an 8-bit number can
is moved SI and DI are automatically adjusted to point to
be as large as 16 bits. The most-significant byte of the
the next source and the next destination. If the direc-
result is put in AH and the least-significant byte of the
tion flagis 0. then SI and DI will be incremented by 1
result is put in AL. When a word is multiplied by the
after a byte move and they will be incremented by 2 after
contents of AX. the product can be as large as 32 bits.
a word move. If the DF is a 1. then SI and DI will be
The most-significant word of the result is put in the DX
decremented by 1 after a byte move and they will be dec-
register, and the least-significant word of the result is
remented
2 after
by a word move. MOVS affects no Hags.
put in the AX register. If the most-significant byte of a
When using the MOVS instruction you must in some
16-bit result or the most-significant word of a 32-bit re-
way tell the assembler whether you want to move a
sult0.is the CF and the OF will both be 0's. Checking
string as bytes or as words. There are two ways to do
these flags then allows you to detect and perhaps dis-
this. The first way is to indicate the names of the source
card unnecessaryleading 0's in a result. The AF, PF, SF,
and the destination strings in the instruction as, for
and ZF are undefined after a MUL instruction.
example, MOVS STRING DUMP, STRING CREATE. The
If you want to multiply a byte by a word, you must first
assembler will code the instruction for a byte move if
move the byte to a word location such as an extended
STRING DUMP and STRING CREATE were declared
register and fill the upper byte of the word with all 0's.
with a DB. It will code the instruction for a word move if
they were declared with a DW. Note that this reference to NOTE: You cannot use the 8086 Convert Byte to Word
the source and destination strings does not load SI and instruction, CBW. to do this. The CBW instruction fills
DI. This must be done with separate instructions. The the upper byte of AX with copies of the MSB of AL. If the
second way to tell the assembler whether to code the number in AL is 80H or greater. CBW will fill the upper
instruction for a byte or word move is to add a "B" or a half of AX with 1 s instead of with 0's. Once you get the
"W" to the MOVS mnemonic. MOVSB. for example, says byte converted correctly to a word with 0's in the upper

162 t HAP7ER SIX


byte, you can then do .1 wind times word multiply 1 he NEC WORD PTR [BP| . Replace woul al offset [hl>] in
32 Imi resull will be in DX and AX ; SS with iis 2's ( omplemi in

I XAMPLES: Note thai the BYTE PTR and WORD PTR dire* tl
required in the lasl two examples to tell the assembler
Ml I l.l I : A I. times hi I. resull In AX
whether to code the Instruction foi .1 byte operation or a
MUL CX . AX times CX, resull high word in DX, word operation. The llil'l reference by itsell does not in-
: low word in AX dicatetype
the ol the operand

Ml I. BYTE PTR [BX] ; Al. times byte in DS pointed


. to by [BX] NOP INSTRUCTION— Perform no operation
Mil. CONVERSION FACTOR [BX] : Multiply AL This instruction simply uses up three clock cycles and
times byte at effective address CONVERSION FACTOR increments the instruction pointer to point to the next
[BX] it 11 was declared as type byte with DB. Multiply instruction. NOP affects no flags. The NOP instruction
AX times wind at effective address can be used to increase the delay of a delay loop as
CONVERSION FACTOR [BX]. if it was declared as shown in Figure -1 20 II can also be used to hold a pi, ice
type word with DW. in a program for instructions that will be added later.

; Example showing a byte multiplied by a word


MOV AX. MULTIPLICAND 16 : Load 16-bit NOT INSTRUCTION— Invert each bit of
; multiplicand in AX operand — NOT destination
MOV CL. MULTIPLIER 8 ; Load 8-bit multiplier The NOT instruction inverts each bit (forms the Is
: in CL complement of) the byte or word at the specified desti-
MOV CH, 00H : Set upper byte of CX nation.destination
The can be a register or a memory
: to all O's
location specified by any one of the addressing modes
MUL CX : AX times CX, 32-bit
shown in Figure 3-8. No flags are affected by the NOT
; result in DX and AX
instruction.

EXAMPLES:

NEG INSTRUCTION— Form 2's complement— NOT BX Complement contents of BX


NEG destination register
This instruction replaces the number in a destination NOT BYTE PTR [BXI Complement memory byte at
with the 2's complement of that number. The destina-
offset [BX] in
tion canbe a register or a memory location specified by data segment
any one of the addressing modes shown in Figure 3-8.
This instruction forms the 2's complement by subtract-
ing theoriginal word or byte in the indicated destina-
OR INSTRUCTION— Logically OR
tion from zero. You may want to try this with a couple of
corresponding bits of two operands — OR
numbers to convince yourself that it gives the same re-
destination, source
sult as
the invert each bit and add one algorithm. As
This instruction ORs each bit in a source byte or word
shown in some examples below, the NEG instruction is
with the corresponding bit in a destination byte or
useful for changing the sign of a signed word or byte. An
word. The result is put in the specified destination. The
attempt to NEG a byte location containing -128 or a
contents of the specified source will not be changed. The
word location containing -32,768 will produce no
result for each bit will follow the truth table for a two-
change in the destination contents because the maxi-
input OR gale. In other words, a bit in the destination
mum positive signed number in 8 bits is +127 and the
will become a one if that bit is a one in the source oper-
maximum positive signed number in 16 bits is
and OR
that bit is a one in the original destination oper-
+ 32,767. The OF will be set to indicate that the opera-
and. Therefore, a bit in the destination operand can be
tion could not be done. The NEG instruction updates the
set to a one by simply ORing that bit with a one in the
AF. CF. SF, PF, ZF. and OF.
same bit of the source operand. A bit ORed with zero is
not changed.
EXAMPLES (CODING)
The source operand can be an immediate number, the
NEG AL ; Replace number in AL with its contents of a register, or the contents of a memory loca-
: 2's complement tion specifiedby one of the 24 addressing modes shown
in Figure 3-8. The destination can be a register or a
NEG BX ; Replace word in BX with its
memory location. The source and the destination can-
: 2's complement
not bothbe memory locations in the same instruction.
NEG BYTE PTR [BX] : Replace byte at offset [BX] in The CF and OF are both zero after OR. The PF. SF. and
: DS with its 2's complement ZF are updated by the OR instruction. AF is undefined

8086 INSTRUCTION DESCRIPTIONS AND ASM MBI IK DIRECTIVES 163


after OR. Note that PF only has meaning for an 8-bit OUTS/OUTSB/OUTSW— 801 86/801 88 ONLY—
operand. Output String to Port — OUTS port, source
string
EXAMPLES (CODING):
OUTS copies a byte or a word from a string location
OR AH. CL CL ORed with AH, result in AH. pointed to by SI to a port whose address is contained in
CL not changed. DX. The address of the port to be copied to must be put
in DX before this instruction executes. If the direction
OR BP. SI SI ORed with BP. result in BP.
flag is cleared when this instruction executes, SI will
SI not changed.
automatically be incremented by one for a byte opera-
OR SI. BP BP ORed with SI. result in SI. tion, and
incremented by two for a word operation after
BP not changed. the data is copied to the port. If the direction flag is set,
SI will automatically be decremented by one for a byte
OR BL. 80H BL ORed with immediate 80H. operation and decremented by two for a word operation
Set MSB of BL to a 1. after data is copied to the port. When used with the REP
OR CX. TABLE[BX|[SI| ; CX ORed with word from prefix or as part of a loop the OUTS instruction can out-
effective address TABLE[BX||SI] in data segment. Word putblock
a of data directly from a series of memory loca-
in memory is not changed. tions
a port
to without having the data go through AL or
AX as it does with the regular OUT instruction.
When using the OUTS instruction you must in some
EXAMPLE (NUMERICAL):
way tell the assembler whether you want to output bytes
CX = 00111101 10100101 or output words. There are two ways to do this. The first
OR CX, OFFOOH OR CX with immediate FFOOH. is to use the name of the source string in the instruction
Result in CX = 11111111 10100101 statement as in the statement OUTS DX, BUFFER. The
note upper byte now all Is assembler will code the instruction for a byte output if
CF = 0 OF = 0 ZF = 1 SF = 1 BUFFER was declared with a DB and it will code the
PF UNDEFINED instruction for a word output if BUFFER was declared
with a DW. The second way to tell the assembler whether
to code the instruction for a byte or for a word input is to
OUT INSTRUCTION— Output a byte or word add a B or a W to the basic instruction mnemonic.
to a port — OUT port, accumulator AL or AX OUTSB DX, for example, tells the assembler to code the
The OUT instruction copies a byte from AL or a word instruction for copying a byte from a string location
from AX to the specified port. The OUT instruction has pointed to by SI to a port whose address is in DX. SI
two possible forms, fixed-port and variable port. normally points to a location in the data segment, but
For the fixed-port form the 8-bit port address is speci- you can use a segment override prefix to point it to a
fied directlyin the instruction. With this form anyone of location in some other segment. OUTS affects no flags.
256 possible ports can be addressed.
EXAMPLE:
EXAMPLES:
CLD ; Clear direction flag, autoincrement DI
OUT 3BH. AL : Copy the contents of AL to port 3BH
MOV DI. OFFSET BUFFER ; Point DI at
OUT 2CH. AX : Copy the contents of AX to port 2CH : output buffer

For the variable port form of the OUT instruction, the


MOV DX. 0FFF8H Load DX with
contents of AL or AX will be copied to the port at an port address
address contained in DX. Since DX is a 16 bit register, MOV CX. 100 Load number of
the port address contained there can be any number bytes to be output in CX
between 0000H and FFFFH. Therefore, up to 65,536
possible ports can be addressed in this mode. The DX REP OUTSB DX Copy bytes to port
register must always be loaded with the desired port until buffer empty
address before this form of the OUT instruction is used.
The advantage of the variable port form of addressing is
described within the discussion of the IN instruction.
POP INSTRUCTION— POP destination
EXAMPLES: The POP instruction copies a word from the stack loca-
MOV DX. 0FFF8H ; Load desired port address in DX tion pointedto by the stack pointer to a destination
specified in the instruction. The destination can be a
OUT DX. AL : Copy contents of AL to port FFF8H general-purpose register, a segment register, or a mem-
ory location.The data in the stack is not changed. After
OUT DX. AX : Copy contents of AX to port FFF8H
the word is copied to the specified destination, the stack
NOTE: The OUT instruction docs not affect any lings. pointer is automatically incremented by 2 to point to the

164 CHAPTER SIX


iic\i wind on the stack. No ilaus are affected by the P< )P PUSH INSTRUCTION — 8018b 80188 ONLY-
Instruction. PUSH Immediate

NOTE: POP CS is illegal. rhls version ol the PUSH instruction allows you to si ore
an miinrdi.il!' byte oi wind given In the Instruction on
EXAMPLES: the stack. II an Immediate byte Is specified, the b;
POP DX i opj .1 ui ii (I from 11>p ol stack to be sign extended to a word before the PI SI l is done. be
DX, SP SP I 2 cause all slack pushes are wind operations The si, irk
pointer will be decremented by two before the word is
POP DS Copy .1 wind from the top ol the pushed on the stack. PI ISI l affects no flag
si.uk hi DS.
Increment SP by 2 EXAMPLE:

POP TABLE [BX] ; Copy a word from the top ol the PUSH 437AH I )(( % lenient SP by 2 and Write
: slack to memory in I IS number 437A1 1 on stack
: wilh EA TABLE t [BX]

PUSHA INSTRUCTION— 80186/80188 ONLY—


POPA INSTRUCTION— 801 86/801 88 ONLY— Push all Registers on Stack
Pop all Registers from Slack PUSHA copies the contents of the lour general-purpose
POPA restores four pointer and index registers and four registers and the contents of four pointer and index reg
general-purpose registers that were saved on the stack isters to memory locations in the stack. The stack
with a PUSHA instruction. After the saved value is cop- pointer is decremented by two before each register is
ied fromthe stack to the appropriate register, the stack pushed on the stack. The registers are pushed in the
pointer is incremented by two. Register contents are following order: AX. CX. DX, BX, SP, BP. SI. DI. Tin-
popped off the stack in the following order: DI. SI. BP, value pushed for SP is the value that SP had before AX
SP. BX. DX. CX, AX. POPA affects no Hags. was pushed. PUSHA affects no Hags. PUSHA can be used
at the start of a procedure to save the contents of these
eight registers. A POPA instruction at the end of the pro-
POPF INSTRUCTION— Pop word from top of cedurebe
canused to restore the original contents of
stack to flag register the registers before returning to the program which
This instruction copies a word from the two memory called the procedure.
locations at the top of the stack to the flag register and
increments the stack pointer by two. The stack segment
register is not affected. All flags are affected. PUSHF INSTRUCTION -Push flag register on
the stack
This instruction decrements the stack pointer by two
PUSH INSTRUCTION— PUSH source
and copies the word in the Hag register to the memory
The PUSH instruction decrements the stack pointer by location! s) pointed to by the stack pointer. The stack
two and copies a word from some source to the location segment register is not affected. No flags are changed.
in the stack segment where the stack pointer then
points. The source of the word can be a general-purpose EXAMPLE: PUSHF

register, a segment register, or memory. The stack seg-


ment register
and the stack pointer must be initialized
before this instruction can be used. PUSH can be used to RCL INSTRUCTION— Rotate operand around to
save data on the stack so it will not be destroyed by a the left through CF — RCL destination, count
procedure. It can also be used to put data on the stack so This instruction rotates all of the bits in a specified
that a procedure can access it there as needed. No flags word or byte some number of bit positions to the left.
are affected by this instruction. Refer to Chapter 5 for The operation is circular because the MSB of the oper-
further discussion of the stack and the PUSH instruc- androtated
is into the carry flag and the bit in the carry
tion. flag is rotated around into the LSB of the operand. See
the diagram below.
EXAMPLES:

PUSH BX : Decrement SP by 2. copy BX to stack CF <- MSB LSB

PUSH DS ; Decrement SP by 2. copy DS to stack

PUSH AL : Illegal, must push a word


The "C" in the middle of the mnemonic should help you
PUSH TABLE [BX] : Decrement SP by 2. copy word remember that CF is in the rotated loop and it should
; from memory help distinguish this instruction from the ROL instruc-
: at EA = TABLE + [BX] tion. For
multibit rotates CF will contain the bit most
; in DS to stack recently rotated out of the MSB.

8086 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 165


The destination operand can be in a register or in a help distinguish this instruction from the ROR instruc-
memory location specified by any one of the 24 address- tion. For
multibit rotates CF will contain the bit most
ing modesshown in Figure 3-8. If you want to rotate the recently rotated out of the LSB.
operand one bii position, you can specify this by putting The destination operand can be in a register or in a
a 1 in the count position of the instruction. To rotate memory location specified by any one of the 24 address-
more than one bit position, load the desired number in ing modesshown in Figure 3-8. If you want to rotate the
the CL register and put "CL" in the count position of the operand one bit position, you can specify this by putting
instruction. a 1 in the count position of the instruction. To rotate
more than one bit position, load the desired number in
NOTE: The 80186 and the 80188 allow you to specify a
the CL register and put "CL" in the count position of the
rotate of up to 32 bit positions with either an immediate
instruction.
number in the instruction or with a number in CL.
RCL affects only the CF and OF. After RCL the CF will NOTE : The 80 1 86 and the 80 1 88 allow you to specify a
contain the bit most recently rotated out of the MSB. rotate of up to 32 bit positions with either an immediate
The OF will be a 1 after a single bit RCL if the MSB was number in the instruction or with a number in CL.
changed by the rotate. OF is undefined after a multibit RCR affects only the CF and OF. After RCR the CF will
rotate. contain the bit most recently rotated out of the MSB.
The RCL instruction is a handy way to move the CF The OF will be a 1 after a single bit RCR if the MSB was
into the LSB of a register or memory location to save it changed by the rotate. OF will be undefined after mul-
after addition. tibit rotates.

EXAMPLES (CODING1
EXAMPLES (CODING]
RCL DX. 1 Word in DX 1 bit left, MSB to CF
CF to LSB RCR BX. 1 Word in BX right 1 bit.
CF to MSB, LSB to CF

MOV CL. 4 Load number of bit positions to


MOV CL. 04H Load CL for rotating four bit
rotate in CL
positions
RCL SUMIBX], CL Rotate byte or word at effective RCR BYTE PTR (BX] Rotate byte at offset [BX] in
address SUM[BX] 4 bits left.
data segment four bit
Original bit 4 now in CF.
positions right.
original CF now in bit 3.
CF = original bit 3.
EXAMPLES ( NUMERICAL I
Bit 4 = original CF.
CF = 0 BH = 101 10011
EXAMPLES (NUMERICAL)
RCL BH. 1 Byte in BH 1 bit left. MSB to CF,
CF to LSB. CF = 1 BL = 00111000

CF = 1 BH = 01100110 RCR BL. 1 Byte in BL one bit position right.


OF = 1 because MSB changed LSB to CF.
CF = O.BL = 10011100
CF = 1 AX =00011111 10101001
OF = 1 because MSB changed to 1
MOV CL, 2 Load CL for rotating two bit positions.
RCL AX, CL Rotate AX two bit positions. CF = 0
CF = 0 AX = 01111110 10100110 WORD PTR [BX] = 0101 1 1 10 00001 111
OF undefined
MOV CL, 02H Load CL for rotate two
bit positions

RCR INSTRUCTION— Rotate operand around to RCR WORD PTR [BX], CL Rotate word at offset [BX]
the right through CF— RCR destination, count in data segment 2
This instruction rotates all of the bits in a specified bits right.
word or byte some number of bit positions to the right.
CF = original bit 1.
The operation is circular because the LSB of the oper-
Bit 14 = original CF
androtated
is into the carry Hag and the bit in the carry
flag is rotated around into the MSB of the operand. See WORD PTR [BX] =
the diagram below. 10010111 10000011

CF MSB LSB

REP/REPE/REPZ/REPNE/REPNZ— (Prefix) Repeat


string instruction until specified conditions exist
The "C" in the middle of the mnemonic should Iielp you REP is a prefix which is written before one of the string
remember that CF is in the rotated loop and it should instructions. It will cause the CX register to be decre-

166 CHAI'IIR SIX


merited and the string Instruction to be repeated until mi i In- slack as pari ol the operation ol Ihe ( Al I i list nil
CX 0. The Instruction REP MOVSB. lor example, will lion. The stack pointer will be incremented by two as the
continue to move string bytes until the length ol the return address is popped oil the stack.
string which was loaded Into CX is counted down to II ihe procedure is a far procedure I in a differenl code
zero. segment from the < Al I Instruction which calls It), then
REPI .u hI Kl IV .11c two mnemonics foi the same prefix the Instruction pointer will he replaced In ihe word al
They stand for Repeal II Equal and Repeat il Zero, re ihe lop ni iIk stai k. Tins word Is die offsel pari of the
spectively. You can use whichevei prefix makes the op- return address put there by the CALI Instruction Hie
eration clearer
to you in a given program. Kl I'l or Kl IV is slack pointer will then he Incremented by two I he code
often used with the Compare String Instruction or with segmenl register is then replaced with a word from the
the Scan Sinn;; instruction. Kl PI 01 Kl IV will cause the new lop ol ihe stack. This woid Is ihe segment pari ol
string instruction to be repealed as long as the nun the return address thai was pushed on Ihe slack by a I.a
pared bytes or words are equal (ZF I I. AND CX is nol ( .ill operation. Alter the code segmenl word is popped oil
yet counted down to zero. In other words (here are two 11ii stack the slack pointer is again incremented by two.
conditions that will slop the repel it ion CX 0 or string
bytes or winds NOT equal. A RET instruction can be followed by a number, for
example. Kl I (>. In this ease Ihe stack pointer will be
EXAMPLE: incremented by an additional six addresses after Ihe II'
or the IP and CS are popped off the stack. This form is
REPE CMPSB ; Compare string bytes until end ol used to increment the stack pointer up over parameters
string or until string bytes nol equal See ihe discussion passed to the procedure on the stack.
of the CMPS instruction for a more detailed example ol The RET instruction affects no flags.
the use of REPE. Please refer to Chapter 5 for further discussion of the
CALL and RET instructions.
REPNE and REPNZ are also two mnemonics for the same
prefix. They stand for Repeat if Not Equal and Repeat if
Not Zero, respectively. REPNE or REPNZ is often used ROL INSTRUCTION— Rotate all bits of operand
with the Scan String instruction. REPNE or REPNZ will left, MSB to LSB— ROL destination, count
cause the string instruction to be repealed as long as
This instruction rotates all the bits in a specified word
the compared bytes or words arc not equal (ZF = 01. or
or byte to the left some number of bit positions. The
until CX - 0 (end of string).
operation can be thought of as circular, because the
data bit rotated out of the MSB is circled back into the
EXAMPLE:
LSB. The data bit rotated out of the MSB is also copied
REPNE SCASW : Scan a string of words until a word in to the CF during ROL. In the case of multiple bit rotates,
the string matches the word in AX or until all of the CF will contain a copy of the bit most recently moved out
string has been scanned. See the discussion of SCAS for of the MSB. See the diagram below.
a more detailed example of the use of this prefix.
The string instruction used with the prefix determines CF ^- MSB LSB
which flags are affected. See the individual instructions
for this information. Also see Chapter 5 for further ex-
amples
the of REP instruction with string instructions.
The destination operand can be in a register or in a
NOTE: Interrupts should be disabled when multiple memory location specified by any one of the 24 address-
prefixes are used, such as LOCK, segment override, and ing modesshown in Figure 3-8. If you want to rotate the
REP with string instructions on the 8086/8088. This is operand one bit position, you can specify this by putting
because, during an interrupt response, the 8086 can a 1 in the count position of the instruction. To rotate
only remember the prefix just before the string instruc- more than one bit position, load the desired number in
tion. The
80186/80188 will correctly remember all of the the CL register and put "CL" in the count position of the
prefixes and start up correctly after an interrupt. instruction.

NOTE: The 80186 and the 80188 allow you to specify a


rotate of up to 32 bit positions with either an immediate
RET INSTRUCTION— Return execution from number in the instruction or with a number in CL.
procedure to calling program ROL affects only the CF and OF. After ROL the CF will
The RET instruction will return execution from a proce- contain the bit most recently rotated out of the MSB.
durethe
to next instruction after the CALL instruction The OF will be a 1 after ROL if the MSB was changed by
in the calling program. If the procedure is a near proce- the rotate.
dure (in
the same code segment as the CALL instruc- The ROL instruction can be used to swap the nibbles
tion), then
the return will be done by replacing the in- in a byte or to swap the bytes in a word. It can also be
struction pointer
with a word from the top of the stack. used to rotate a bit into CF where it can be checked and
The word from the top of the stack is the offset of the acted upon by the conditional jump instructions. |C
next instruction after the CALL. This offset was pushed (Jump if Carry) or JNC (Jump if No Carry).

S086 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 167


EXAMPLES (CODING) used to rotate a bit into the CF where it can be checked
and acted upon by the conditional jump instructions. )C
ROL AX. 1 Word in AX one bit position left,
(Jump if Carry) or JNC (Jump if No Carry).
MSB to LSB and CF

EXAMPLES (CODING)
MOV CL. 04H ; Load number of bits to rotate in CL
ROR BL. 1 Rotate all bits in BL right one bit
ROL BL. CL ; Rotate BL four bit positions
position
; (swap nibbles)
LSB to MSB and to CF
ROL FACTOR! BX), 1 ; MSB of word or byte at
MOV CL. 08H Load number of bit positions to be
; effective address
rotated in CL
; FACTOR! BX]
ROR WORD PTR [BX]. CL : Rotate word at offset
: in data segment one bit
: [BX] in data segment eight bit
; position left into CF
JC ERROR : Jump if CF = 1 to error routine ; positions right (swaps bytes in word)
EXAMPLES (NUMERICAL EXAMPLES [NUMERICAL)

CF 0 BH 10101110 CF = 0. BX = 00111011 01110101


i« u. mi. i CF 1 BH 01011101 OF 1 ROR BX. 1 Rotate all bits of BX one bit
position right
CL = 8 Set for 8-bit rotate
CF = 1. BX = 1001 1 101 101 1 1010
BX = 01011100 11010011
ROL BX, CL Rotate BX 8 times left (swap bytes)
CF = 0. BX = 11010011 0101 1100 CF = 0. AL = 10110011 OF = 1
OF = ? MOV CL. 04H Load CL for rotate four bit positions
ROR AL, CL Rotate all bits of AL around four
bit positions right
ROR INSTRUCTION— Rotate all bits of operand CF = 0 AL = 00111011 OF = ?
right, LSB to MSB— ROR destination, count
This instruction rotates all of the bits of the specified
word or byte some number of bit positions to the right.
The operation is described as a rotate rather than a shift SAHF INSTRUCTION— Copy AH register to low
because the bit moved out of the LSB is rotated around byte of flag register
into the MSB. To help visualize the operation, think of The lower byte of the 8086 flag register corresponds ex-
the operand as a loop with the LSB connected around to
actlythe
to 8085 flag byte. SAHF replaces this 8085
the MSB. The data bit moved out of the LSB is also cop-
equivalent flag byte with a byte from the AH register.
ied tothe CF during ROR. See diagram below. In the
SAHF is used with the POP AX instruction to simulate
case of multiple bit rotates the CF will contain a copy of the 8085 POP PSW instruction. As described under the
the bit most recently moved out of the LSB.
heading LAHF. an 8085 PUSH PSW instruction will be
translated to an LAHF— PUSH AX sequence to run on an
CF MSB LSB 8086. An 8085 POP PSW instruction will be translated
to a POP AX— SAHF sequence to run on an 8086. SAHF
changes the flags in the lower byte of the flag register.
The destination operand can be in a register or in a
EXAMPLE: SAHF
memory location specified by any one of the 24 address-
ing modesshown in Figure 3-8. If you want to rotate the
operand one bit position, you can specify this by putting
a 1 in the count position of the instruction. To rotate SAL/SHL INSTRUCTION— Shift operand bits
more than one bit position, load the desired number in left, put zero in LSB(s)— SAL/SHL destination,
the CL register, and put "CL" in the count position of
count
the instruction.
SAL and SHL are two mnemonics for the same instruc-
NOTE: The 80186 and the 80188 allow you to specify a tion. Thisinstruction shifts each bit in the specified
rotate of up to 32 bit positions with either an immediate destination some number of bit positions to the left. As
number or with a number in CL. a bit is shifted out of the LSB position, a 0 is put in the
ROR affects only the CF and the AF. After ROR the CF LSB position. The MSB will be shifted into the CF. In the
will contain the bit most recently rotated out of the LSB. case of multiple bit shifts. CF will contain the bit most
The OF will be a 1 after ROR if the MSB is changed by the recently shifted in from the MSB. Bits shifted into CF
rotate. previously will be lost. See diagram below.
The ROR instruction can be used to swap the nibbles
in a byte or to swap the bytes in a word. It can also be < F MSB LSB <- 0

168 CHAPTFR SIX


rhe destination operand can be a byte oi .1 word li can SAR INSTRUCTION— Shift operand hits right,
be in .1 registei hi in a memory location spe< Ifled bj anj new MSB = old MSB — SAR destination, count
one hi the 24 addressing modes shown In Figure 3 8. rhis Instruction shifts each bit in the specified destina
II ilic desired numbei oi shifts Is one, tins can be 11011some numbei ol bil positions to thi right As a bit
specified by putting .1 1 in the counl position of the in- Is shifted out ol the MSB position, .1 1 op) ol 1In- old MSB
struction.
shiftsI'm ol more than l bit position the <l<- Is put in the MSB position. In othei winds the sign bil is
sued numbei ol shifts is loaded into the CL registei and copied into the MSB. The LSB will be shifted into CF In
CL is put in the c (Mini position ol the instruction rhe the case ol multiple bil shifts, CF will contain the bil
advantage ol theCL way is thai the numbei of shifts can
niosi recently shifted in from the LSB. Biis shifted into
be dynamically calculated as the program executes CF previously will be lost, Sec diagram below,
NOTE: The 80186 and the 80188 allow you to specify a
shift of up to 32 bit positions with either an immediate MSB — MSB LSB • CF
number in the instruction or with a number in CL.
The flags are affected as follows: CF contains the Ini
The destination operand can be a byte or a word. Il ran
most recently shifted in from MSB. For .1 count ol one
be in a registei or in a memory location specified by any
OF will be l il the CF and the current MSB are not the
one "l the 24 addressing modes shown in Figure 3-8.
same. For multiple bit shifts, the OF is undefined. The
If the desired number ol shifts is one, tins ran be
SF and the ZF will be updated to reflect the condition of
specified by putting a 1 in the counl position of the in-
the destination. The PF will only have meaning il the
struction.
shutsFor ol more than one bit position the
destination is AL. AF is undefined.
desired numbei oi shifts is loaded into the CL register
The SAL or SHL instruction can also be used to multi- and CL is put in the count position of the instruction
ply an
unsigned binary number by a power of two. Shift-
ingbinary
a number one bit position to the left and put- NOTE: The 80186 and the 80188 allow you to specify a

ting
0 ain the LSB multiplies the number by 2. Shifting shift of up to 32 bit positions with either an immediate

the number two bit positions multiplies it by 4. Shifting number in the instruction or with a number in CL.
The flags are affected as follows: CF contains the bit
the number three bit positions multiplies it by 8. etc.
For this specific type of multiply the SAL method is most recently shifted in from the LSB. For a count of one
faster than using MUL. but you must make sure that the the OF will be a 1 if the two MSBs are not the same. After

result does not become too large for the destination. a multibit SAR the OF will be 0. The SF and the ZF will be
updated to show the condition of the destination. PF
will only have meaning for an 8-bit destination. AF will
EXAMPLES [CODING)
be undefined after SAR.
SAL BX. 1 : Shift word in BX 1 bit position left, The SAR instruction can be used to divide a signed
: 0 in LSB byte or word by a power of two. Shifting a binary num-
ber right
one bit position divides it by 2. Shifting a bi-
MOV CL, 02H : Load desired number of shifts in CL nary numberright two bit positions divides it by 4.
SAL BP, CL : Shift word in BP left (CL) bit Shifting it three positions divides it by 8. etc. For un-
: positions, O's in signed numbers
a 0 is put in the MSB after the old MSB
; 2 least-significant bits is shifted right. [See discussion of SHR instruction.) For
signed binary numbers the sign bit must be copied into
the new MSB as the old sign bit is shifted right. This is
SAL BYTE PTR [BX], 1 : Shift byte at offset [BX] in necessary to retain the correct sign in the result. SAR
: data segment one bit shifts the operand right and copies the sign bit into the
; position left. 0 in LSB MSB as required for this operation. Using SAR to do a
divide by 2. however, gives slightly different results than
: Example of SAL instruction's use to help pack BCD using the IDIV instruction to do the same job. IDIV al-
IN AL, COUNTER DIGIT : Unpacked BCD from
ways truncatesa signed result toward zero. For exam
pie. an IDIV of 7 by 2 gives 3 and an IDIV of -7 by 2 gives
: counter to AL
-3. SAR always truncates a result in a downward direc-
tion. Using
SAR to divide 7 by 2 gives 3, but using SAR to
MOV CL, 04H : Set count for four bit positions
divide -7 by 2 gives -3.

SAL AL. CL : Shift BCD to upper nibble, O's in


: lower nibble. Ready to OR another BCD digit into
EXAMPLES (CODING)
: lower nibble of AL.
SAR DI. 1 ; Shift word in DI one bit position right.
EXAMPLE (NUMERICAL! ; new MSB = old MSB

; CF = 0, BX = 11100101 11010011 MOV CL. 02H : Load desired number of shifts in CL


SAL BX. 1 ; Shift BX register contents one bit left SAR WORD PTR [BP], CL : Shift word at offset [BP]
: CF = 1. BX = 11001011 10100110 : in stack segment right two bit positions. Two MSBs
: OF = 0 PF = ? SF = 1 ZF = 0 ; are now copies of original MSB.

8086 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 169


EXAMPLES (NUMERICAL) SUB PRICES [BX], 04H : Subtract 04 from byte at
effective address PRICES! BX| if PRICES declared with
AL = 00011101 = +29 decimal CF = 0 DB. Subtract 04 from word at effective address
Shift signed byte in AL right PRICES[BX] if PRICES declared with DW.
to divide by 2.
SBB CX. TABLE! BX] Subtract word from effective
AL = 00001110 = +14 decimal. CF = 1
address TABLEIBX] and
OF = 0 PF = 0 SF = 0 ZF = 0 status of CF from CX

SBB TABLE! BX], CX Subtract CX and status of CF


BH = 1 1 1 1001 1 = - 13 decimal
SAR BH. 1 Shift signed byte in BH right to from word in memory at
effective address TABLE[BX]
divide by 2

BH = 11111001 = -7 decimal CF = 1 EXAMPLES! NUMERICAL):

OF = 0 PF = 1 SF = 1 ZF = 0 : Example subtracting unsigned numbers


CL = 10011100 = 156 decimal
BH = 001 10111 = 55 decimal
SBB INSTRUCTION— Subtract with borrow— SUB CL. BH Subtract BH from CL. Result:
SBB destination, source CL = 01100101 = 101 decimal
CF = 0. AF = 0, PF = 1, OF = 0.
SF = 0, ZF = 0

SUB INSTRUCTION— Subtract— SUB


destination, source Two examples subtracting Signed numbers
These instructions subtract the number in the indi- la)
cated source from the number in the indicated destina- CL = 00101 110= +46 decimal
tion andput the result in the indicated destination. For BH = 01001010 =+74 decimal
subtraction the carry flag. CF. functions as a borrow SUB CL, BH Results
flag. The carry flag will be set after a subtraction if the CL = 11100100 = -28 decimal
number in the specified source is larger than the num-
CF = 1, borrow required
ber inthe specified destination. In other words, the AF = 0 PF = 1 ZF = 0
carry/borrow flag will be set if a borrow was required to SF = 1, result negative
do the subtraction. The Subtract instruction, SUB. sub- OF = 0, magnitude of result
tracts just
the contents of the specified source from the fits in 7 bits
contents of the specified destination. The Subtract with
Borrow instruction, SBB. subtracts the contents of the (b)
source and the contents of the CF from the indicated CL = 10100010 = -95 decimal
destination. The source may be an immediate number, BH = 01001100 = +76 decimal
a register, or a memory location specified by any of the SUB CL, BH Results:
24 addressing modes shown in Figure 3-8. The destina- CL = 01010101 = +85 decimal
tion may
be a register or a memory location. The source CF = 1 . borrow required
and the destination cannot both be memory locations in AF = 0 PF = 1 ZF = 0
the same instruction. The source and the destination SF = 0. result positive !
must both be of type byte or they must both be of type OF = 1. invalid result
word. If you want to subtract a byte from a word, you
must first move the byte to a word location such as an The overflow flag being set indicates that the magnitude
extended register and fill the upper byte of the word with of the expected result. - 1 7 1 decimal, is too large to fit in
O's. The AF. CF. OF. PF. SF. and ZF are updated by the the 7 bits used for the magnitude in an 8-bit signed
SUB instruction. number. If the Interrupt on Overtlow instruction. INTO,
has been executed, this error will cause the 8086 to per-
EXAMPLES (CODING) form
software
a interrupt procedure. Part of this proce-

SUB CX. BX Subtract contents of BX from dureais user-written subroutine to handle the error.
contents of CX Leave result in CX
NOTES: The SBB instruction allows you to subtract two
SBB CH. AL Subtract contents of AL and multibyte numbers because any borrow produced by
contents of CF subtracting less-significant bytes is included in the re-
from contents of CH. Result in CH. sult whenthe SBB instruction executes. Although the
examples above were for 8-bit numbers to save space,
SUB AX, 3427H Subtract immediate number
the principles are the same for 16-bit numbers. For
3427H from AX
16-bit signed numbers, however, the SF is a copy of bit
SBB BX. [3427H] Subtract word at displacement 15, and the least-significant 15 bits of the number are
3427H in DS used to represent the magnitude. Also, the PF and the
and contents of CF from BX. AF only function for the lower 8 bits.

170 ( HAPTER SIX


SCAS/SCASB/SCASW INSTRUCTION— Stan The destinal ion operand can be a byte oi .1 word li can
string byte or a string word be in .1 registei 01 in a memor) location specified by any
one ol the 24 addressing modes shown in Figun !
S< VS« ompares .1 string byte with .1 byte In AL oi a --11 ing
II the desired numbei nl shifts is one. this can be
word with word in AX The instruction affei Is the flags
specified by putting a 1 in the counl position ol the in
bul II docs not change either the operand In AL(AX) or
struction. For shuts ol more ih. ne bil position the
the operand in the string. The string to be scanned
desired numbei ol shifts is loaded into the CL register,
must be in the extra segmenl and 1)1 musl contain the
and CL is put in the count position ol the Instruction
offset oi the byte or the word to be compared. Aftei S< \s
executes, I >1will be automatically incremented oi decre NOTI The 80 186 and 80188 allow you to specify a shifl
mented to poinl to the next element in the string. For ol up in 32 In I positions with either an immediate 111mi-
byte strings 1)1 will be incremented or decremented by llet inthe instruction or a numbei in CL.
one. ,u n I leu word strings I 'I will be incremented or dec The flags are affected by si IK as follows CF contains
remented by two. It the direction flag is cleared (0), then the bil most recently shifted In from the LSB. For a
1)1 will be incremented aftei si AS. II the direction flag is coin it ol one. ( )F will he a I if the two MSBs are not both
set (II. then 1)1 will be decremented after S< AS sc \s lis For multiple bit shifts, OF is meaningless. The SF
affects the AF. CF, OF, I'F. SI', and ZF. This instruction and ZF will be updated to show the condition ol the des-
is often used with a repeat prefix in find the first occur- tination.
will PFonly have meaning for the lower eight
rence
.1 ol
specified byte or word in .1 string. bits of destination. AF is undefined.
TheSHR instruction can be used to divide an un-
EXAMPLE: signed binary
number by a power of two. Shifting a hi
nary number one bit position to the right and put ting 0
: Scan .1 text string of 80 characters for .1 carriage
in the MSB divides the number by two. Shifting the
: return
number two bit positions divides it by 4. Shifting it
MOV AL. ODH ; Byte to be scanned for into AL
three bit positions divides it by 8. etc. When an odd
MOV 1)1. OFFSET TEXT STRING ; Offset of string
number is divided with this method, the result will be
: to DI
truncated. In other words, dividing 7 by 2 will give a
MOV CX. 80 ; CX used as element counter result of 3.
CLD ; Clear DF so DI autoincrements
REPNE SCAS TEXT STRING ; Compare byte in EXAMPLES (CODING)
; string with byte in AL
SHR BP. 1 ; Shift word in BP one bit position right.
NOTE: Scanning is repeated while the bytes are not ; 0 in MSB
equal and it is not end of the string. If a carriage return
MOV CL. 03H : Load desired number of shifts
ODH is found. ZF = 1 and DI will point at the next byte
: into CL
after the carriage return in string. If a carriage return is
not found then CX = 0 and ZF = 0. The assembler uses SHR BYTE PTR [BX] ; Shift byte at offset |BX| in
the name of the string to determine whether the string : data segment
is of type byte or type word. Instead of using the name ; 3 bits right.
you can tell the assembler directly the type of the string : O's in 3 MSBs.
by using the mnemonic SCASB for a byte string and
SCASW for a word string. ; Example of SHR Used to Help Unpack Two BCD
: Digits in AL to BH and BL

SHL/SAL INSTRUCTION— Shift operand bits MOV BL. AL ; Copy packed BCD to BL

left, put zero in LSB(s) — SHL/SAL destination, AND BL. OFH : Mask out upper nibble. Low BCD

count ; digit now in BL.

SAL and SHL are two mnemonics for the same instruc- MOV CL. 04H ; Load count for shift in CL
tion. Pleaserefer to the discussions of this instruction SHR AL. CL : Shift AL four bit positions right and
under the heading SAL/SHL. : put O's in upper 4 bits
MOV BH. AL : Copy upper BCD nibble to BH
SHR INSTRUCTION— Shift operand bits right, EXAMPLES (NUMERICAL)
put zero in MSB(s) — SHR destination, count
; SI = 10010011 10101 101 CF = 0
This instruction shifts each bit in the specified destina- SHR SI. 1 ; Shift contents of SI register right one bit
tion somenumber of bit positions to the right. As a bit : position. SI = 01001001 11010110
is shifted right out of the MSB position, a 0 is put in its
place. The bit shifted out of the LSB position goes to the : CF = 1 OF = 1 PF = ? SF = 0

CF. In the case of a multiple bit shift. CF will contain the : ZF = 0


bit most recently shifted in from the LSB. Bits shifted
into CF previously will be lost. See diagram below.
STC INSTRUCTION— Set the carry flag to a one
0 -» MSB LSB -» CF STC does not affect any other flags.

8086 INSTRUC TION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 171


STD INSTRUCTION— Set the direction flag to a MOV DI, OFFSET TARGET_STRING : Point DI at
: destination string
one
STD is used to set the direction flag to a one so that SI STOSB : "B" added to STOS
and/or DI will automatically be decremented to point to mnemonic directly tells assembler to replace byte in
the next string element when one of the string instruc- string with byte from AL. STOSW would tell assembler
tions executes.If the direction flag is set. SI and/or DI directly to replace a word in the string with a word
will be decremented by one for byte strings, and by two from AX.
lor word strings. STD affects no other flags. Please refer
to Chapter 5 and the discussion of the REP prefix in this
chapter for examples of the use of this instruction.
SUB INSTRUCTION— Subtract— SUB
destination, source
STI INSTRUCTION— Set interrupt flag (IF) Please refer to the discussion of this instruction under
the heading SBB.
Setting the interrupt flag to a one enables the INTR in-
terrupt
the of8086 after the next instruction after STI.
An interrupt signal on this input will then cause the
8086 to interrupt program execution, push the return TEST INSTRUCTION— AND operands to update
address and flags on the stack, and execute an interrupt flags — TEST destination, source
service procedure. An IRET instruction at the end of the This instruction ANDs the contents of a source byte or
interrupt service procedure will restore the flags which word with the contents of the specified destination
were pushed on the stack, and return execution to the word. Flags are updated, but neither operand is
interrupted program. Because STI does not allow the changed. The TEST instruction is often used to set flags
INTR input to be enabled until the instruction after STI before a conditional jump instruction.
executes, the instruction sequence STI— IRET will return The source operand can be an immediate number, the
execution to the interrupted program before another contents of a register, or the contents of a memory loca-
interrupt will be recognized. This is important to keep tion specifiedby one of the 24 addressing modes shown
the stack from filling up in systems which have many in Figure 3-8. The destination operand can be from a
different interrupts. STI does not affect any other flags. register or from a memory location. The source and the
Please refer to Chapter 8 for a thorough discussion of destination cannot both be memory locations in an in-
interrupts. struction.
CF The
and OF are both O's after TEST. The
PF. SF, and ZF will be updated to show the results of the
EXAMPLE: ANDing. AF will be undefined. PF only has meaning for
STI ; Enable interrupts after next instruction the lower eight bits of the destination.
IRET ; Return from interrupt service procedure.
; Interrupts enabled after return. EXAMPLES (CODING)

TEST AL, BH : AND BH with AL. no result.


Update PF. SF. ZF.
STOS/STOSB/STOSW INSTRUCTION— Store
byte or word in string TEST CX, 000 1H : AND CX with immediate number
000 1H no result stored.
The STOS instruction copies a byte from AL or a word
Update PF. SF. ZF.
from AX to a memory location in the extra segment. In
effect it replaces a string element with a byte from AL or TEST BP. [BXHDI] : AND word at offset [BX][DI] in
a word from AX. DI is used to hold the offset of the mem- data segment with word in BP,
orv location in the extra segment. After the copy. DI is no results stored.
automatically incremented or decremented to point to Update PF. SF. and ZF.
the next string element in memory. If the direction flag,
DF. is cleared, then DI will automatically be incremented ; Example of a Polling Sequence Using TEST
by one for a byte string or incremented by two for a word AGAIN: IN AL. 2AH Read port with strobe
string. If the direction flag is set, DI will be automatically connected to LSB
decremented by one for a byte string or decremented by TEST AL, 01 H AND immediate 01 H with AL
two for a word string. STOS does not affect any flags. to test if LSB of AL is 1 or 0.
ZF = 1 if LSB of result is 0.
EXAMPLES: No result stored.

MOV DI, OFFSET TARGET STRING : Point DI at JZ AGAIN Read port again if LSB = 0

: destination string EXAMPLES (NUMERICAL)


STOS TARGET STRING : Assembler uses string
AL = 01010001
name to determine whether string is of type byte or
TEST AL. 80H AND immediate 80H with AL to test
type word. If byte string, then string byte replaced
if MSB of AL is 1 or 0.
with contents of AL. If word string, then string word
ZF = 1 if MSB of AL =0.
replaced with contents of AX.

172 ( MAI1! Ik ' !'%


AL 0101000] (Unchanged] back into AL \l \l > hanges no Hags. The sei tioi
PF 0 SF 0 verting One Keyboard Code in Another" in Chaptei 9
should clarify the use ol the XLAT Instrui tion
ZF 1 because ANDing produced 00

EXAMPLE

WAIT INSTRUCTION— Wait for test signal or : ,so,s<; routine to ((invert ASCII code byte to EBCDIC
interrupt signal : equivalent
: ASCII code byte is in AL at start EBCDIC code m
When this instruction executes, the so.sti enters an idle
condition where it is doing no processing. The 8086 will ; AL .it end.
MOV BX. 2800H ; Point BX at starl ol EBCDIC
stay in this idle state until a signal is asserted (in the
8086 11 SI input pin, or until a valid interrupt signal is ; table in 1 )S

received on the IN1K or the NMI interrupt input puis, it XLAT Replace ASCII in AL will
a valid interrupt occurs while the 8086 is in this idle EBCDIC from table
state, the ,S(hSt> will return to the idle stale , liter the in-
terrupt service
procedure executes. It returns to the idle The XI AT instruction can be used to convert any code ol
state because the address of the WAIT instruction is the 8 bits or less to any other code of 8 bits or less.
address pushed on the stack when the 8086 responds to
the interrupt request. WAIT affects no flags. The WAIT
instruction is used to synchronize the 8086 with exter-
nal hardware such as the SON? math coprocessor. In XOR INSTRUCTION— Exclusive OR
Chapter 1 1 we describe how this works. corresponding bits of two operands — XOR
destination, source
This instruction exclusive ORs each bit in a source byte

XCHG INSTRUCTION— XCHG destination, or word with the same number bit in a destination byte
or word. The result replaces the contents of the specified
source destination. The contents of the specified source will
The XCHG instruction exchanges the contents of a reg-
not be changed. The result for each bit position will fol-
ister with the contents of another register or the con-
low thetruth table for a two-input exclusive OR gate. In
tentsa ofregister with the contents of a memory loca-
other words, a bit in the destination will be set to a 1 if
tion(s). The instruction cannot directly exchange the
that bit in the source and that bit in the original desti-
contents of two memory locations. A memory location
nation were
not the same. A bit exclusive-ORed with a 1
can be specified as the source or as the destination by
will be inverted. A bit exclusive-ORed with a 0 will not be
any of the 24 addressing modes summarized in Figure
changed. Because of this you can use the XOR instruc-
3-8. The source and destination must both be words, or
tion selectively
to invert or not invert bits in an operand.
they must both be bytes. The segment registers cannot
The source operand can be an immediate number, the
be used in this instruction. No flags are affected by this
contents of a register, or the contents of a memory loca-
instruction. tion specified by any one of the addressing modes
shown in Figure 3-8. The destination can be a register
EXAMPLES:
or a memory location. The source and destination can-
XCHG AX. DX Exchange word in AX not both be memory locations in the same instruction.
with word in DX The CF and OF are both 0 after XOR. The PF. SF, and ZF
are updated. AF is undefined after XOR.
XCHG BL. CH Exchange byte in BL
with byte in CH NOTE: PF only has meaning for an 8-bit operand
XCHG AL. PRICES [BX] Exchange byte in AL with
byte in memory at EXAMPLES (CODING):
EA = PRICES [BX] in DS
XOR CL. BH : Byte in BH exclusive ORed with byte
; in CL. Result in CL. BH not changed.
XOR BP. DI : Word in DI exclusive ORed with word
XLAT/XLATB INSTRUCTION— Translate a byte
: in BP. Result in BP. DI not changed.
in AL
The XLAT instruction replaces a byte in the AL register XOR WORD PTR [BX]. 00FFH ; Exclusive OR

with a byte from a lookup table in memory- Before the : immediate number 00FFH

XLAT instruction can be executed the lookup table con- ; with word at offset [BX] in data

taining
values
the for the new code must be put in mem- : segment. Result in memory

ory, and
the offset of the starting address of the lookup : location [BX].

table must be loaded in BX. To point to the desired byte


EXAMPLE (NUMERICAL)
in the lookup table the XLAT instruction adds the byte in
AL to the offset of the start of the table in BX. It then : BX = 00111101 01101001
copies the byte from the address pointed to by (BX + AL) : CX = 00000000 11111111

8086 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 173


XOR BX. CX ; Exclusive OR CX with BX. NAME HERE DB THOMAS' Declare array of
: result in BX 6 bytes and initialize
: BX = 00111101 10010110 with ASCII codes for
: Note bits in lower byte are inverted letters in THOMAS
: CF = 0 OF = 0 PF = 1 SF = 0
; ZF = 0 AF = ?
TEMPERATURE STORAGE DB 100 DUP(?) : Set
aside 100 bytes of storage in memory and give it the
name TEMPERATURE STORAGE, but leave the 100
bvtes uninitialized. Program instructions will load
ASSEMBLER DIRECTIVES
values into these locations.
The words defined in this section are directions to the
assembler, they are not instructions for the 8086. The PRESSURE- STORAGE DB 20H DUPI0I : Set aside
assembler directives described here are those for the 20H bvtes of storage in memory, give it the name
Intel 8086 macro assembler and the IBM macro assem- PRESSURE_STORAGE. and put 0 in all 20H
bler, MASM. If vou are using some other assembler, con- locations.
sult themanual for it to find the corresponding direc-
tives.
DD — Define Doubleword
The DD directive is used to declare a variable of type
ASSUME
doubleword or to reserve memory locations which
The ASSUME directive is used to tell the assembler the can be accessed as type doubleword. The statement
name of the logical segment it should use for a specified ARRAY POINTER DD 25629261 H. for example, will define
segment. The statement ASSUME CS:CODE HERE, for a doubleword named .ARRAY POINTER, and initialize
example tells the assembler that the instructions for a the doubleword with the specified value when the pro-
program are in a logical segment named CODE HERE. gramloaded
is into memory' to be run. The low word.
The statement ASSUME DS:DATA HERE, tells the assem- 926 1H. will be put in memory at a lower address than
bler thatfor any program instruction which refers to the the high word. A declaration of this type is often used
data segment it should use the logical segment called with the LES or LDS instruction. The instruction LES DI,
DATA HERE. If. for example, the assembler reads the ARRAY POINTER, for example, will copy the low word of
statement MOV AX, [BX] alter it reads this ASSUME, it this doubleword. 926 1H. into the DI register, and the
will know that the memory location referred to by (BX) is high word of the doubleword. 2562H. into the extra seg-
in the logical segment DATA HERE. You must tell the ment register.
assembler what to assume for any segment you use in a
program. If you use a stack in your program you must
tell the assembler the name of the logical segment you
DQ — Define Quadword
have set up as a stack with a statement such as ASsl Ml
This directive is used to tell the assembler to declare a
SS: STACIC_HERE. For a program with string instructions
variable 4 words in length, or to reserve 4 words of stor-
which use DI. the assembler must be told what to as-
age in memory. The statement BIG NUMBER DO
sume the
for extra segment with a statement such as
2435987401 92A92BH. for example, will declare a variable
\SSL ME ES:STRI\C DESTINATION. For further discus-
named BIG NUMBER, and initialize the 4 words set
sion the
of ASSUME directive refer to the appropriate
aside with the specified number when the program is
section of Chapter 3.
loaded into memory to be run. The statement STORAGE
DQ 100 DUP(O) reserves 100 quad words of storage and
initializes them all to 0 when the program is loaded into
DB— Define Byte
memory to be run.
The DB directive is used to define a byte-type variable, or
to set aside one or more storage locations of type byte in
memory. The statement CURRENT TEMPERATURE DB
42H. for example, tells the assembler to reserve 1 byte of
DT— Define Ten bytes
memory for a variable named CURRENT TEMPERAT- DT is used to tell the assembler to define a variable
URE and
to put the value 42H in that memory location which is 10 bytes in length, or to reserve 10 bytes of
when the program is loaded into memory to be run. storage in memory. The statement PACKED-BCD DT
Refer to Chapter 3 for further discussion of the DB di- 1234567890 will declare an array named PACKED BCD
rective to
andChapter 4 for a discussion of how you can which is 10 bvtes in length. It will initialize the 10 bytes
access variables named with a DB in your programs. with the values 1234567890 when the program is
Here are a few more examples of DB statements. loaded into memory to be run. This directive is often
used when declaring data arrays for the 8087 math
PRICES DB 49H. 98H. 29H Declare array of 3 coprocessor discussed in Chapter 11. The statement
bytes named PRICES RESULTS DT 20H DUP(O) will declare an array of 20H

and initialize 3 bytes blocks of 10 bvtes each and initialize all 320 bvtes to 00

as shown when the program is loaded into memory to be run.

174 CHAPTER SIX


DW— Define Word Insii u< lion slati menl
CODE HERE ENDS End ol segmenl nam< d
The DW directive Is used to tell the assembler to define a
CODE HERE
variable ol type word, or to reserve storage locations ol
type word In memorj rhe statemenl MULTIPLIER DW
437AH, lor example, declares .1 variable "l type word
named MULTIPLIER lh< statemenl also tells the .is
EQU— Equate
sembler thai the variable MULTIPLIER should be initial EQU is used to give a name to some value m symbol.
ized with the \aluc 437AH when the program is loaded Each time the assemble! finds the given name in the
into memory to be run. Refer to Chaptei 3 foi furthei program 11 will replace the name with the value 01 sym
discussion ol the DW directive and how you can access bol you equated with that name Suppose, foi example.
variables named with a DW in your pi ogi ams l lei e are a you write the statemenl CORREI HON FA( rOR EQU
few more examples ol DW statements. 03H at the start ol your program and later in the pro
gram you write the instruction statemenl ADD AI , ( OR-
rHREE LITTLE WORDS DW 1234H. 3456H. RE( Hon FA< rOR. When it codes this instruction state-
5678H ; Declare ai ray of three words and initialize ment,assembler
the will code il as il you had written the
with specified values instruction ADD AL, 03H. The advantage ol using EQU
in this manner is that if CORRECTION FACTOR is used
STORAGE DW 100 DUP(O) ; Reserve an array ol 100 27 times in a program, and you waul to change the
words of memory and initialize all 100 winds with value, all you have to do is change the EQU statement
0000. Array is named STORAGE. and reassemble the program. The assembler will auto-
matically
in put
the new value each time it finds the
STORAGE DW 100 DUP[?1 ; Reserve 100 words ol
name CORRECTION FACTOR. If you had used 03H in-
storage in memory and give 1! the name STORAGE,
bin leave die words uninitialized. stead
theof EQU approach, then you would have to try
to find and change all 27 instructions yourself. Here are
some more examples.

END — End Program DECIMAL ADJUST EQU DAA ; Create clearer


The END directive is put after the last statement of a ; mnemonic for DAA
program to tell the assembler that this is the end of the
STRING START EQU |BX] Give name to [BX]
program module. The assembler will ignore any state-
ments after
an END directive, so you should make sure
to only use one END directive at the very end of your
EVEN — Align on Even Memory Address
program module. A carriage return is required after the
As the assembler assembles a section of data declara-
END directive.
tions or
instruction statements, it uses a location
counter to keep track of how many bytes it is from the
start of a segment at any time. The EVEN directive tells
ENDP— End Procedure
the assembler to increment the location counter to the
This directive is used along with the name of the proce- next even address if it is not already at an even address.
dureindicate
to the end of a procedure to the assembler. The 8086 can read a word from memory in one bus cycle
This directive, together with the procedure directive. if the word is at an even address. If the word starts on an
PROC. is used to "bracket" a procedure. Here's an exam- odd address, the 8086 must do two bus cycles to get the
ple. 2 bytes of the word. Therefore, a series of words can be
much more quickly read if they are on even addresses.
SQUARE ROOT PROC Start of procedure When EVEN is used in a data segment, the location
Procedure instruction counter will simply be incremented to the next even ad-
statements
dress
necessary.
if When EVEN is used in a code seg-

SQUARE ROOT ENDP ; End of procedure ment, the


location counter will be incremented to the
next even address if necessary. A NOP instruction will

Chapter 5 shows more examples and describes how pro- be inserted in the location incremented over. Here's an

cedures
written
are and called. example which shows why you might want to use EVEN
in a data segment.

DATA-HERE SEGMENT
ENDS — End Segment ; Declare array of 9 bytes. Location
This directive is used with the name of a segment to ; counter will point to 0009 after

indicate the end of that logical segment. ENDS is used ; assembler reads next statement.
with the SEGMENT directive to "bracket" a logical seg- SALES AVERAGES DB 9 DUP(?)
ment containinginstructions or data. Here's an exam- EVEN ; Increment location counter to 000AH

ple. INVENTORY RECORDS DW 100 DUP(0)


: Array of 100 words starting
CODE HERE SEGMENT ; Start of logical segmenl : on even address for quicker read.
: containing code DATA HERE ENDS

8086 INSTRUCTION DESCRIPTIONS AND ASSEMBtER DIRECTIVES 175


EXTRN as type near or as type far. If the label is going to be used
to reference a data item, then the label must be specified
The EXTRN directive is used to tell the assembler that
as type byte, type word, or type double word. Here's how
the names or labels following the directive are in some
we use the LABEL directive for a jump address.
other assembly module. For example, if you want to call
a procedure which is in a program module assembled at
ENTRY POINT LABEL FAR Can jump to here from
a different time from that which contains the CALL in-
another segment
struction,
must
you tell the assembler that the proce-
dureexternal.
is The assembler will then put informa- NEXT: MOV AL. BL Cannot do a far jump
tion the
in object code file so that the linker can connect directly to a label
the two modules together. For a reference to an external with a colon
named variable you must specify the type of the variable
as in the statement EXTRN DIVISORAVORD. For a refer- Here's how we use the LABEL directive for a data refer-
encea tolabel you must specify whether the label is near ence.
(in a code segment with the same name), or far (in a
code segment with a different name). The statement STACK-HERE SEGMENT STACK
EXTRN SMART DIVIDE: FAR tells the assembler that
DW 100 DUP(O) Set aside 100 words
SMART DIVIDE is a label of type far in another assem-
for stack
bly module. Names or labels referred to as external in
one module must be declared public with the PUBLIC STACK TOP LABEL WORD Give name to next
directive in the module where they are defined. location after last
EXTRN statements should usually be bracketed with word in stack
SEGMENT— ENDS directives which identify the seg- STACK HERE ENDS
mentwhich
in the external name or label will be found.
Here's an example of how to do this. To initialize stack pointer then. MOV SP, OFFSET
STACIC.TOP.
PROCEDURES _HERE SEGMENT

EXTRN SMART DFV1DE:FAR : Found in segment


; PROCEDURES HERE LENGTH— Not implemented in IBM MASM
LENGTH is an operator which tells the assembler to de-
PROCEDURES HERE ENDS
terminenumber
the of elements in some named data
item such as a string or array. When the assembler
Refer to Chapter 5 for a thorough discussion of the use
reads the statement MOV CX, LENGTH STRING! . for ex-
of the EXTRN and the PUBLIC directives.
ample,
willit determine the number of elements in
STRING 1 and code this number in as part of the in-
struction. When
the instruction executes then, the
GROUP— Group-Related Segments length of the string will be loaded into CX. If the string
The GROUP directive is used to tell the assembler to was declared as a string of bytes. LENGTH will produce
group the logical segments named after the directive the number of bytes in the string. If the string was de-
into one logical group segment. This allows the contents clared
a as
word string. LENGTH will produce the num-
of all of the segments to be accessed from the same ber of
words in the string.
group segment base. The assembler sends a message to
the linker and or locator telling it to link the segments
so that the segments are physically in the same 64 Kbyte
NAME
segment. Here's an example of the GROUP directive:
SMALL SYSTEM GROUP CODE HERE, DATA_HERE, The NAME directive is used to give specific names to
STACK HERE each assembly module when programs consisting of
An appropriate ASSUME statement to follow this would several modules are written. The statement NAME
be: ASSUME CS:SMALL .SYSTEM. DS:SMALL SYSTEM, PC BOARD, for example, might be used to name an as-
SS:SMALL_SYSTEM sembly module
which contains the instructions for con-
trolling
printed-cireuit-board-making
a machine.

LABEL
As the assembler assembles a section of data declara-
OFFSET
tions or
instruction statements, it uses a location OFFSET is an operator which tells the assembler to de-
counter to keep track of how many bytes it is from the termine
offset
the or displacement of a named data item
start of a segment at any time. The LABEL directive is (variable) from the start of the segment which contains
used to give a name to the current value in the location it. This operator is usually used to load the offset of a
counter. The LABEL directive must be followed by a variable into a register so that the variable can be ac-
term which specifies the type you want associated with cessed with
one of the indexed addressing modes. When
thai name If the label is going to be used as the destina- the assembler reads the statement MOV BX. OFFSET
tion for
a jump or a call, then the label must be specified PRICES, for example, it will determine the offset of the

176 CHAPTER SIX


variable PRICES from the starl ol the segmenl In which assigns the type specified before PTR to Ihe variabli
PRICES Is defined and code this displacemenl In as pai i specified aftei PTR
oi the Instruction. When the Instruction executes, ihis The PTR operatoi can be used to ovei ride the declared
computed displacemenl will be loaded into BX An In- type ol a variable Suppose, foi i thai we have
strui tion such as \IM' M . |B\| can then be used to add declared an array ol words with the statemenl V
a value from PRICES to Al. DV\ 13 Ml , B9 Ml 7C41H. Normally we would access the
elements In this array as woi ds I lowevei il we wan I to
access a byte in the array, we c lo II with an Instruc-
ORG— Originate tion suchas MOV AL, BYT I PTR WORDS.

As the assembler assembles a section ol data declara- We also use the PTR operator to clarify our inti i
tions 01
Instruction statements, ii uses a location when we use indirect jump instructions. The statemenl
countei to Keep Hack of how many bytes il is from the IMP [BX], for example, docs not tell the assembler
start ol a segment at any tunc. The location counter is
whether to code the instruction for a neat jump 01 lot a
automatically set to 0000 when the assembler starts tai jump. II we want to do a iic.n jump we wi ite the in-
reading a segment. The ORG directive allows yon to set struction
IMP asWORD PTR [BX]. II we want to do a fai
the location countei to a desired value al any point in jump we write the instruction as |MP DWORD PI R [BX].
the program. The statement ORG 2000H tells the assem- Please refer to Chapter ;S for further discussion ol the
bler set
to the location counter to 200011. for example. 8086 jump instructions.
A "$" is often used to symbolically represent the cur-
rent valueof the location counter. The $ actually repre-
sents the
next available byte location where the assem- PUBLIC
bler can
put a data or code byte. The $ is often used in Large programs are usually written as several separate
ORG statements to tell the assembler to make some modules. Each module is individually assembled, tested
change in the location counter relative to its current and debugged. When all the modules are working cor-
value. The statement ORG $ + 100 tells the assembler to rectly, their
object code files are linked together to form
increment the value of the location counter by 100 from the complete program. In order for the modules to link
its current value. A statement such as this might be together correctly, any variable name or label referred to
used in a data segment to leave 100 bytes of space for in other modules must be declared public in the module
future use. where it is defined. The PUBLIC directive is used to tell
the assembler that a specified name or label will be ac-
cessed from
other modules. An example is the statement
PROC— Procedure PUBLIC DIVISOR, DIVIDEND which makes the two varia-
The PROC directive is used to identify the start of a pro- bles, DIVISOR
and DIVIDEND, available to other assem-
cedure. PROC
The directive follows a name you give the bly modules.
procedure. After the PROC directive the term NEAR or If an instruction in a module refers to a variable or
the term FAR is used to specify the type of the proce- label in another assembly module, the assembler must
dure. The
statement SMART_DIVIDE PROC FAR, lor ex- be told that it is external with the EXTRN directive.
ample, identifies the start of a procedure named Refer to the discussion of the EXTRN directive to see
SMART DIVIDE and tells the assembler that the proce- how this is done.
durefar
is (in a segment with a different name from that
which contains the instruction which calls the proce-
dure). The
PROC directive is used with the ENDP direc- SEGMENT
tive "bracket"
to a procedure. Refer to the ENDP discus-
The SEGMENT directive is used to indicate the start of a
sion for
an example of this. Also refer to Chapter 5 for a
logical segment. Preceding the SEGMENT directive is
thorough discussion of how procedures are written and
the name you want to give the segment. The statement
called.
CODE_HERE SEGMENT, for example, indicates to the
assembler the start of a logical segment called
CODE HERE. The SEGMENT and ENDS directives are
PTR— Pointer
used to "bracket" a logical segment containing code or
The PTR operator is used to assign a specific type to a data. Refer to the ENDS directive for an example of how
variable or to a label. It is necessary to do this in any this is done.
instruction where the type of the operand is not clear. Additional terms are often added to a SEGMENT di-
When the assembler reads the instruction INC [BX). for rective statement to indicate some special way in which
example, it will not know whether to increment the byte we want the assembler to treat the segment. The state-
pointed to by BX or increment the word pointed to by ment CODE_HERE SEGMENT WORD tells the assembler
BX. We use the PRT operator to clarify how we want the that we want this segment located on the next available
assembler to code the instruction. The statement INC word address when the segments are located and given
BYTE PRT [BX] tells the assembler that we want to incre- absolute addresses. Without this WORD addition the
ment the
byte pointed to by BX. The statement INC segment will be located on the next available paragraph
WORD PTR [BX] tells the assembler that we want to in- (16-byte) address which might waste as much as 15
crementword
the pointed to by BX. The PTR operator bytes of memory. The statement CODE HERE SEGMENT

8086 INSTRUCTION DESCRIPTIONS AND ASSEMBLER DIRECTIVES 177


PUBLIC tells the assembler that this segment will be put the address of the instruction after the jump. The state-
together with other segments named CODE HERE from ment (MP
SHORT NEARBY LABEL is an example of the
other assembly modules when the modules are linked use of SHORT.
together.

TYPE
SHORT The TYPE operator tells the assembler to determine the
The SHORT operator is used to tell the assembler that type of a specified variable. The assembler actually de-
only a 1-byte displacement is needed to code a jump in- termines
number
the of bytes in the type of the variable.
struction.
the jump If destination is after the jump in- For a byte-type variable the assembler will give a value of
struction
the program,
in the assembler will automati- 1 . For a word-type variable the assembler will give a
cally reserve
2 bytes for the displacement. Using the value of 2, and for a doubleword-type variable it will give
short operator saves 1 byte of memory by telling the as- a value of 4. The TYPE operator can be used in an in-
sembler it that
only needs to reserve 1 byte for this par- structionassuchADD BX, TYPE WORD. ARRAY, where
ticular jump.
In order for this to work the destination we want to increment BX to point to the next word in an
must be in the range of - 128 bytes to +127 bytes from array of words.

178 CHAPTER SIX


CHAPTER

8086 System Connections,


Timing, and Troubleshooting

In Chapter 2 we showed that a microcomputer consists be able to program the device. Now we will look at the
of a CPU, memory, and ports. We also showed in Chapter hardware model of the K()8b so that we can show how a
2 that these parts are connected together by three major microcomputer system is built around it. We will also
buses the address bus. the control bus. and the data discuss in this chapter the hardware connections for an
bus For Chapters 3 through 6. however, we made little 8088. A later chapter will show the hardware connec-
mention of the hardware of a microcomputer because tions for
the 80186 and 80286 microprocessors.
we were mostly concerned in these chapters with how a To get started, let's take a look at the pin diagram for
microcomputer is programmed. In this chapter we come the 8086 in Figure 7-1. Don't be overwhelmed by all ol
back to take a closer look at the hardware of a micro- those pins with strange mnemonics next to them. You
computer. don't need to learn the detailed functions of all of these
at once. We describe and show the use of these different
pins throughout the next few chapters as needed. When
you later need to refresh your memory of the function of
OBJECTIVES
a particular pin, consult the index to find the section
At the conclusion of this chapter you should be able to: where that particular pin or signal is described in detail.
For reference, the complete data sheet showing all of the
1. Draw a diagram showing how RAMs, ROMs, and pin descriptions is shown in the appendix.
ports are added to an 8086 CPU to make a simple
microcomputer.
3 v(l
2. Describe how addresses sent out on the 8086 data
J AD15
bus are demultiplexed.
3 A16/S3
3. Describe the signal sequence on the buses as a sim- 3 A17/S4
ple 8086-based microcomputer fetches and executes 3 A18/S5
an instruction. 3 A19/S6

4. Describe how address decoding circuitry gives a spe- 3 BHE/S7


cific address to each device in a system and makes 3 MN/MX
sure only one device is enabled at a time. 3 RD
3 RQ/GTO (HOLD)
5. Calculate the required access time for a memory
3 RQ/GTl (HLDA)
device or port to work correctly in an 8086 micro-
3 LOCK (WR)
computer system.
3 S2 (M/IO)
6. List a series of steps you might take to troubleshoot Hsl (DT/R)
a malfunctioning microcomputer system that once 3 so (DEN)
worked.
TJoso (ALE)

3 qsi (INT A)

3 TEST
8086 HARDWARE OVERVIEW 3 READY

In previous chapters we worked with what is often called 3 RESET


the programmer's model of the 8086. This model shows
40 LEAD
features, such as internal registers, number of address
lines, and number of data lines, that we need in order to FIGURE 7-1 8086 pin diagram. (Intel Corporation)

179
Note first in Figure 7-1 that Va is on pin 40 and 27, and 28. An external bus controller device decodes
ground on pins 1 and 20. Next find the clock input la- these signals to produce the control bus signals re-
beled CLK
on pin 19. An 8086 requires a clock signal quired
a for
system which has two or more microproces-
from some external, crystal-controlled clock generator to sors sharing the same buses. In Chapter 1 1 we discuss
synchronize internal operations in the processor. Dif- how a maximum mode 8086 system operates.
ferent versions
of the 8086 have maximum clock fre- Here's a brief introduction to the functions of a few
quencies ranging from 5 MHz to 10 MHz. more of the 8086 pins. First note pin 21. the RESET
Now look for the address and data bus lines. Remem- input. If this input is made high, the 8086 will, no mat-
ber fromprevious chapters that the 8086 has a 20-bit ter what it is doing, reset its DS, SS, ES, IP, and flag
address bus and a 16-bit data bus. A look at Figure 7-1, registers to all O's. It will set its CS register to FFFFH.
however, does not immediately reveal these 36 lines. When the RESET signal is removed from pin 21. the 8086
The reason is that the designers multiplexed the lower will then fetch its next instruction from physical ad-
16 address lines out on the data bus to minimize the dress FFFFOH.This address is produced in the 8086
number of pins needed. The 8086 could then be put in a Bus Interface Unit (BIU) by shifting the FFFFH in the CS
40-pin package. In other words, the data bus lines, la- register 4 bits left and adding the 0000H in the instruc-
beled ADO
through AD15 in Figure 7-1, are used at the tion pointer to it. The first instruction you want to exe-
start of a machine cycle to send out addresses, and later cute aftera reset is put at this address. FFFFOH. An ex-
in the machine cycle they are used to send or receive ample would
be the first instruction of a monitor pro-
data The 8086 sends out a signal called address latch gram such
as the one on the SDK-86.
enable, or ALE, on pin 25 to let external circuitry know Next notice that the 8086 has two interrupt inputs.
that an address is on the data bus. Later we will discuss nonmaskable interrupt (NMI) input on pin 17 and the
in detail how this works. The upper 4 bits of an address interrupt (INTRI input on 18. A signal can be applied to
are sent out on the lines labeled A16/S3 through A19/S6. one of these inputs to cause the 8086 to interrupt the
The double mnemonic on these pins indicates that ad- program it is executing and go execute a specified proce-
dress bits
A16 through A19 are sent out on these lines dure. might,
We for example, connect a temperature
during the first part of a machine cyle and status infor- sensor from a steam boiler to an interrupt input on an
mation, which
identifies the type of operation to be done 8086. If the boiler gets too hot, then it will assert the
in that cycle, is sent out on these lines during a later interrupt input. This will cause the 8086 to stop execut-
part of the cycle. ing its
current program and go execute a procedure to
Having found the address bus and the data bus, now turn off the fuel supply to the boiler. At the end of the
look for the control bus lines. Some of the control bus procedure we can return to executing the interrupted
lines on a microprocessor usually have mnemonics such program. Chapter 8 describes in detail the operation
as RD. WR, and M/IO. Fin 32 of the 8086 in Figure 7-1 is and uses of interrupts.
labeled RD. This signal will be asserted low when the Now that you have an overview of most of the major
8086 is reading data from memory or from a port. Pin 29 pins on an 8086, we will take a closer look at what is
has a label WR next to it. However, pin 29 also has a happening on the buses during a read operation and
label LOCK next to it. because this pin has two func- during a write operation.
tions. The
function of this pin and the functions of the
other pins between 24 and 31 depend on the mode in
which the 8086 is operating.
Basic Signal Flow on 8086 Buses
The operating mode of the 8086 is determined by the
logic level applied to the MN/MX input, pin 33. If pin 33 Figure 7-2 shows, in timing diagram form, the activities
is assserted high, then the 8086 will function in mini- on the 8086 buses during simple read and write opera-
mum mode, and pins 24 through 31 will have the func- tions. Don't
be overwhelmed by all of the lines on this
tions shown in parentheses next to the pins in Figure diagram. Their meaning should become clear to you as
7-1. Pin 29. for example, will function as WR which will we work our way through the diagram.
go low any time the 8086 writes to a port or to a memory
8086 BUS ACTIVITIES DURING A READ
location. Pin 28 will function as M/IO. The 8086 will
MACHINE CYCLE
assert this signal high if it is reading from or writing to
a memory location, and it will assert this signal low if it The first line to look at in Figure 7-2 is the clock wave-
is reading from or writing to a port. The RD, WR, and formthe
at top. This represents the crystal-controlled
M/IO signals form the heart of the control bus for a min- clock signal sent to the 8086 from an external clock gen-
imum mode8086 system. The 8086 is operated in mini- erator device
as shown in the top left of Figure 7-3. One
mum mode in systems where it is the only microproces- cycle of this clock is referred to as a state. A state is
sor onthe system buses. Later in this chapter we measured from the 50 percent point on the falling edge
discuss in detail the operation of a minimum mode sys- of one clock pulse to the 50 percent point on the falling
tem. edge of the next clock pulse. Tl in the figure is a state.
If the MN/MX pin is asserted low, then the 8086 is in Each basic bus operation such as reading a byte from
maximum mode. In this mode pins 24 through 31 will memory or writing a word to a port requires some num-
have the functions described by the mnemonics next to ber states.
of The group of states required for a basic
the pins in Figure 7- 1 . In this mode the control bus sig- bus operation is called a machine cycle. The total time
nals (SO.
S1, S2| are sent out in encoded form on pins 26. it takes the 8086 to fetch and execute an instruction is

180 CHAPTER SEVEN


OES INACTIVE IN DHI

r\^ UST PRIOR TO I,


j~v
w mm
X X X
"V BHE.V"
ADDR STATUS
X
RDATA)^^-^^^0^- (^yT 3ATA OUT ID,,, D,,l
xxz

m , r m_ r
"V v_

-MEMORY ACCESS TIME-

FIGURE 7-2 Basic 8086 system timing. (Intel Corporation)

called an instruction cycle. An instruction cycle consists can easily see the sequence of activities on the signal
of one or more machine cycles. To summarize this, lines as you move your imaginary time line across the
then, an instruction cycle is made up of machine cycles, waveforms.
and a machine cycle is made up of states. What we are After asserting M/IO, the 8086 sends out a high on
going to examine here are the activities that occur on the address latch enable signal. ALE. This signal is
the buses during a read machine cycle. connected to the enable input (STB) of the 8282 latches
During Tl_of a read machine cycle an 8086 first as- as shown in Figure 7-3. As you can also see in Figure
serts M/IO
the signal. It will assert this signal high if it 7-3, the data inputs of these latches are connected to the
is going to do a read from memory during this cycle, and 8086 AD0-AD15. A16-A19. and BHE (bus high enable)
it will assert M/IO low if it is going to do a read from a lines. After the 8086 asserts ALE high, it sends out on
port during this cycle. The timing diagram in Figure 7-2 these lines the address of the memory location that it
shows two waveforms for the M/IO signal, because the wants to read. Since the latches are enabled by ALE
signal may be going low or going high for a read cycle. being high, this address information passes through
The point where the two waveforms cross indicates the the latches to their outputs. The 8086 then makes the
time at which the signal becomes vaJid for this machine ALE output low. This disables the latches and holds the
cycle. Likewise, in the rest of the timing diagram, address information latched on the latch outputs. The
crossed lines are used to represent the time when infor- address information on the latch outputs can now be
mation
a line
on or group of lines is changed. Inciden- used to select the desired memory or port location.
tally,best
the way to analyze a timing diagram such as Observe in the timing diagram in Figure 7-2 how the
this one is to think of time as a vertical line moving from activity on the ADDR/DATA lines is represented. The
left to right across the diagram. With this technique you first point at which the two waveforms cross represents

8086 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 181


l7
w 8284A CLOCK
GENERATOR
CLK
READY

RESET
MN MX

M/IO
INTA
%

DT R

—]
•- -
WAIT 8086 CPU
STATE 8282
GENERATOR AD--AD,, ADDR DATA LATCH
2 OR 3
I I
I H— h-

UF= —\
L Ioe
| 8286
%TRANSCEIVER

77

L V 1^1 ..

OPTIONAL CSO„ CSOL WE OD


FOR INCREASED
DATA BUS DRIVE 2142 RAM 141 :7 1b J PROM <2l

FIGURE 7-3 Basic 8086 minimum mode system, lintel Corporation)

the time at which the 8086 has put a valid address on vice. They
are not usually used to indicate signal cause
these lines. These two waveforms DO NOT indicate that and effect within a device.
all 16 lines are going high or going low at this point. Now. referring to Figure 7-2 again, find the section of
Again, the crossed lines indicate the time at which a the ADO-AD 15 waveform marked off as memory access
valid address is on the bus. time near the bottom of the diagram. The addressed
Since the address information is now held on the memory location or port must put valid data on the data
latches, the 8086 does not need to send it out anymore. bus before the end of this indicated time interval. Sup-
Therefore, as shown by a dashed line in Figure 7-2. the pose, example,
for that we are addressing a ROM. ROMs
8086 floats the AD0-AD15 lines so that they can be used typically have an access time of a few hundred nanosec-
to input data from memory or from a port. At about the onds other
In words, after we apply an address to a
same time the 8086 also removes the BHE and A16-A19 ROM. it will be a few hundred nanoseconds before we
information from the upper lines and sends out some will see valid data on the outputs of the ROM. If the ac-
status information on those lines. cess timefor a ROM in a system is longer than the maxi-
The
8086 is now ready to read data from the ad- mum memory access time specified for the 8086, then
dressed memorylocation or port, so near the end of the 8086 will not get valid data when it addresses that
state T2 the 8086 asserts its RD signal low. As you will ROM. A later section of this chapter shows you how to
see in a later section of the chapter, this signal is used to calculate whether a particular ROM. RAM. or port device
enable the addressed memory device or port device. has a short enough access time to work properly in a
When enabled the addressed device will put a byte or given 8086 system. For now. however, we just need you
word of data on the data bus. In other words, asserting to understand the concept so we can show you one way
the RD signal low causes the addressed device to put that an 8086 can accommodate a slow device.
data on the data bus. This cause-and-effect relationship If you look at the pin diagram for the 8086 in Figure
is shown on the timing diagram in Figure 7-2 by an 7- 1. you should find an input labeled READY. If this pin
arrow going from the falling edge of RD to the "bus re- is high the 8086 is "ready" and operates normally. If the
serveddata
for in" section of the ADDR/DATA wave- READY input is made low at the right time in a machine
forms.bubble
The on the tail of the arrow always is put cycle, the 8086 will insert one or more WAIT states be-
on the signal transition or level that causes some action, tween
andT3 T4 in that machine cycle. The timing dia-
and the point of the arrow always indicates the action gramFigure
in 7-2 shows an example of this. An exter-
caused. Arrows of this sort are only used to indicate the nal hardware device is set up to pulse READY low before
effect a signal from one device will have on another de- the rising edge of the clock in T2. After the 8086 finishes

182 CHAPTER SEVEN


I 3 ol the machine cycle, it enters a WA11 state. During a III k isassei led high, the buffers will, 11 enabled by 1)1 N.
WA11 state the signals on the buses remain the same .is transmit data from the 8086 to ROM, RAM. 01 port:
they were al the start ol the WA11 state, The address <>i When 1)1 R is asseited low. the buffers, il enabled bj
the addressed memory location is held on the outpul ol I II N, Will allow da I, i lo eoiile in I nil n Rl ).M. RAM. in poi Is
the latches so ii does nol change. As von can sec from to the Mi 16
the timing diagram in Figure 7 2. the control bus sig Now let's look back at Figure 7 2 to see how 1)1 N and
11.iN. M K ) and Rl >. also do nol change during the WA11 1)1 R function during a read machine cycle. During Tl ol
state, l'w.ut. If the Kl \D\ inpul is made high again dur- the machine cycle the 8086 asseils 1)1 k low to put the
ing T3
in during the WA11 state .is shown in Figure 7-2, data buffers in the receive mode then, after the 80,s(,
then aftei one WA1I state the 8086 will go on with the liiiishes using the data bus to send out the lower 16
regulai IT of the machine cycle. What we have done by address bits, it asseils 1)1 N low lo enable the data bus
inserting the WAIT state is to freeze the action on the butlers. The data put on the dala bus by an addressed
buses tin one clock cycle. This gives the addressed de port or memory Will then be able to come in through the
vice an extra clock cy< le nine to put out valid data. II. for butler to the 8086
example, we want to use a slower (cheaper) ROM in a We can summarize the activities on the buses dining
system, we can add a simple circuit which pulses the an 8086 read machine cycle as follows. The 8086 asserts
Kl \D\ input low each tiinctli.it ROM is addressed. Note M/IO high if the read is to be from memory and asseils
in Figure 7-3 that a READY input signal is usually M/IO low if the read is going to be from a port. At about
passed through the 8284 clock generator IC so that the the same time, the 8086 asserts AIT high to enable some
Signal actually applied to the 8086 is synchronized with external latches. It then sends out BHL and. on the lines
tin system clock. Incidentally, a cross-hatched section AD0-A19. the desired address. The 8086 then pulls the
on a waveform indicates that the signal maybe changed ALE line low to latch the address information in the ex-
at any time during that time interval. ternal latches.Alter the 8086 is through using lines
If the 8086 READY input is still low at the end of a ADO-AD 15 for an address, it removes the address from
WAIT state, then the 8086 will insert another WAIT these lines and puts the lines in the input mode (floats
state. The 8086 will continue inserting WAIT states them). It then asserts its RD signal low. The RD signal
until the READY input is made high again. In later chap- going low turns on the addressed memory or port which
ters we
show more applications using the READY input then puts the desired data on the data bus. To complete
tu insert WAIT states in a machine cycle. the cycle the 8086 brings the RD line high again. This
Another look now at Figure 7-2 will show you that causes the addressed memory or port to turn off,
there are still two waveforms we haven't discussed yet. thereby floating the bus again. If the 8086 READY input
These two are the DEN signal and the DT/R signal. The is made low before or during T2 of a machine cycle, the
DEN signal is used to enable bidirectional buffers on the 8086 will insert WAIT states as long as the READY input
data bus. Figure 7-3 shows how buffers such as 8286s is low. When READY is made high the 8086 will continue
are connected on the data bus in a system. For a very on with T4 of the machine cycle. WAIT states can be
small system these buffers are not needed, but as more used to give slow devices additional time to put out valid
devices are added to a system they become necessary. data. If a system is large enough to need data bus buff-
Here's why. Most of the devices such as ROMs and RAMs ers, thenthe 8086 DEN signal will be asserted low to
used around microprocessors have MOS inputs, so on a enable the buffers, and the 8086 DT/R signal will be as-
dc basis they don't require much current. However, serted high
to set the buffers for output or asserted low
each input or output added to the system data bus, for to set the buffers for input.
example, acts like a capacitor of a few picofarads con
nected to ground. In order to change the logic state on
8086 BUS ACTIVITIES DURING A WRITE
these inputs from low to high, all of this added capaci-
MACHINE CYCLE
tance mustbe charged. To change the logic stale to a
low. the capacitance must be discharged. If we add more Now that we have analyzed the 8086 bus activities for a
than a lew devices on the data bus lines, the 8086 out- read machine cycle, let's take a look at the timing dia-
puts cannotsupply enough current drive to charge and grama for
write machine cycle in the right-hand half of
discharge the circuit capacitance rapidly. Therefore, we Figure 7-2. Most of this diagram should look very famil-
add high-current drive buffers to do the job. iar to
you because it is very similar to the read cycle.
We must be able to float the outputs of buffers used on During Tl of a write machine cycle the 8086 asserts
the data bus so that they do not interfere with other M/IO low if the write is going to be to a port and it as-
activities on these lines. For example, we certainly don't serts M/IO
high if the write is going to be to memory. At
want data bus buffer outputs enabled onto the data bus about the same time the 8086 raises ALE high to enable
while the 8086 is putting out the lower 16 bits of an the address latches. The 8086 then outputs BHE and the
address on these lines. The data enable signal, DEN, address that it will be writing to on AD0-A19. When
from the 8086 will enable the data bus buffers when it is reading from or writing to a port, lines A16-A19 will al-
asserted low. Buffers used on the data bus must also be wayslow,
be because the 8086 only sends out 16-bit
bidirectional, because we both send data out on the data port addresses. After this address has had time to pass
bus and read data in oji the data bus. The data trans- through the latches, the 8086 brings ALE low again to
mWreceive signal. DT/R, from the 8086 is used to spec- latch the address on the outputs of the latches. In addi-
ify thedirection in which the buffers are enabled. When tionholding
to the address, these latches also function

8086 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 183


as buffers lor the address lines. After the address infor- read and write machine cycles in Figure 7-2 until you
mation
latched,
is the 8086 removes the address infor- feel that you understand the sequence of activities that
mation from
AD0-AD15 and puts the desired data on the occur. Understanding this well will make later sections
data bus. It then asserts its WR signal low. The WR sig- easier to understand.
nal used
is to turn on the memory or port where the data
is to be written. After the addressed memory or port has
had time to accept the data from the data bus, the 8086 Analyzing a Minimum-Mode System, the SDK-86
raises the WR signal line high again and floats the data The previous sections showed how a clock generator,
bus. address latches, and data bus buffers are connected to
If the READY input is made low by external hardware an 8086 to form what we might call the minimum-mode
before or during T2 of the machine cycle, the 8086 will CPU group. As shown in Figure 7-3 this group of ICs
insert a WAIT state alter T3. If the READY input is made generates the address bus. data bus. and control bus
high before the end of the WAIT state, the 8086 will go signals needed for an 8086 minimum-mode system. In
on with state T4 as soon as it finishes the WAIT state. If this major section of the chapter we discuss how this
the READY input is still low just before the end of the CPU group is connected with ROM. RAM, ports, and
WAIT state, the 8086 will insert another WAIT state. It other devices to form a system. The system we use for
will continue to insert WAIT states until READY is made this discussion is the Intel SDK-86 system design kit. a
high. During a WAIT state the logic levels on the buses readily available 8086-based unit suitable for building
are held constant. Therefore, if we have a memory or the prototypes of small microcomputer-based instru-
port device which needs more time to absorb the data ments.
from the data bus, we can use some external hardware Figure 7-4 shows a photograph of an SDK-86 board.
to pulse the READY line low each time this device is ad- From the photograph you can see that, in addition to
dressed. Pulling
the READY line low will cause the K086 the microcomputer ICs, the board has a hexadecimal
to insert one or more WAIT states in the machine cycle, keypad, some seven-segment displays, and a large open
thus giving the addressed device more time to absorb area for adding more ROM, RAM, ports, or other cir-
the data. cuitry.
monitor
A program in ROM on the board allows
If the system is large enough to need buffers on the you to enter, execute, and debug machine code pro-
data bus. then DT/R will be connected to_the buffers. grams using
the on-board hex keypad or an external
During a write cycle the 8086 asserts DT/R high to put CRT terminal connected to the serial port on the board.
the buffers in the transmit mode. When the 8086 as- The board comes with 2 Kbytes of RAM and sockets
serts DEN
low to enable the buffers, data output from where you can add another 2 Kbytes. The board also has
the 8086 will pass through the buffers to the addressed six 8-bit parallel ports which you can program to be in-
port or memory location. putsoutputs.
or To get a better idea of the hardware
Work vour way across the timing diagrams for the functions on the board and the devices used to imple-
ment thesefunctions, let's look at the detailed block dia-
gramtheof SDK-86 in Figure 7-5.
Whenever you are approaching a system that is new to
you. it is a good idea to carefully study the detailed block
diagram of the system before you start digging into the
actual schematics. The schematics for even a small sys-
tem suchas this are often spread over many pages.
Without the overview that the block diagram gives, it is
very difficult for you to see how all of the schematic
pieces fit together.
The first parts to look at in Figure 7-5 are the 8086
CPU and the 8284 clock generator. Note that the 8284
has a 14.7456-MHz crystal connected to it. According to
the data sheet for the the 8284. the frequency of the
crystal connected to the 8284 will be divided by three to
produce the clock signal sent to the 8086. Therefore, the
actual 8086 clock frequency for this board will be 4.915
MHz. Another clock signal called PCLK is also produced
by the 8284. This signal is used as a general-purpose
clock signal throughout the system. The hardware RST
signal and the RDY signal are also passed through the
8284 to synchronize them with the clock signal before
they are sent to the 8086. As you can see in Figure 7-5,
considerable circuitry is connected to the RDY1 input so
that several conditions can cause a WAIT state to be in-
IH.UKI 7-4 Intel SDk-8d microprocessor development serted
a in
machine cycle. The structure labeled W27
In lard, (Intel ( orporation) through W34 above the WAIT state generator in Figure

184 ( HAPTERSEVEt
FIGURE 7-5 Detailed block diagram of SDK-86 board. (Intel Corporation)

7-5 represents wire wrap pins which can be jumpered to of schematics. Figure 7-6 shows the complete schematic
specify the number of WAIT states desired in a machine set for the SDK-86 board, so you can check this out if
cycle. We will discuss this in detail later. you wish.
By this time you may have noticed that the symbols The next parts to look for in the block diagram of the
for the 8284, 8086. and WAIT state generator each have SDK-86 are the address latches which you know are
a small box containing a 2 in their lower right corner. needed to grab address information during Tl of a ma-
This number tells you that the detailed schematic for chine cycle.
The box just below the 8086 in the diagram
these parts will be found on sheet number two of the set indicates that three 74S373s are used for address

8086 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 185


latches. AD0-AD15. A16-A19. and BHE are connected to tem can
be used individually to input or output parallel
the inputs of these latches. As expected, ALE is used to bytes. They can also be used together to input or output
enable the latches. The information held on the output words. For byte input or output operations, only one of
of the latches alter ALE goes low is A0-A19 and BHE. The the devices will be turned on by asserting its CS input
/20 after A0-A19 on the output of the latches indicates low. For word input or output operations, both 8255As
that there are 20 lines in this group. A heavy black line will be turned on by asserting their CS inputs low. The
is used to distinguish the demultiplexed address bus high byte of a word to be output, for example, will then
from the data bus. be sent to one of the ports in the PORT 1 device. The low
Next, follow the address lines to the right on the dia- byte of the word to be output will go to the correspond-
gramfind
to the ROM in the system. The box labeled ing port
in the PORT 2 device. To be more specific, if the
PROM indicates that four 23 1 6 or 27 1 6 devices are used high byte of an output word goes to port P1A, then the
for EPROM in the system. Each of these devices holds 2 low byte of that word will go to port P2A. In a later sec-
Kbytes of memory. Also indicated in the PROM box in tion address
on decoding, we show how the addresses
the diagram are the absolute addresses where these de- work out for these ports.
vices are
located. Two of the EPROMs occupy the ad- Most systems need a serial port so they can communi-
dress spacefrom FEOOOH-FEFFFH, and the other two cate withCRT terminals, modems, and other devices
occupy the address space from FF000H— FFFFFH. The which require data to be sent and received in serial
3625 PROM decoder connected to these EPROMs has form As shown in the lower left corner of Figure 7-5 the
two related purposes. The first is to produce a signal SDK-86 uses an 8251 A as a serial port. The letters
which turns on the desired EPROM when you send out USART on this device stand for universal synchronous/
an address in the range assigned to that device. The sec- asynchronous receiver transmitter, which is quite a
ond purpose is to make sure that only one device is out- mouthful. Chapter 13 discusses the initialization and
putting onto the data bus at a time. We discuss in detail use of the 825 1A. For now, just think of this device as
later how address decoders are connected to give a de- two back-to-back shift registers. One shift register ac-
sired address to a particular device in a system. Note cepts
parallel
a byte from the system data bus and shifts
that the enable input. CS2, of the decoder PROM is con- it out the TxD output in serial form. The other shift reg-
nected
theto RD signal from the 8086. The result of this ister shiftsin serial data from the RxD input and con-
is that the PROM decoder will only be enabled if the verts
toit parallel bytes which can be read by the 8086
8086 is doing a read operation. Can you see why you on the system data bus. The 825 1A has only eight data
would not want an EPROM to be turned on if you acci- inputs, so data can only be written to or read from the
dentallyout
sent an address in its range during a write 8251 A a byte at a time. Therefore, only the lower 8 bits
operation? The answer is that attempting to write to the of the data bus are connected to it. Each of the shift
outputs of an EPROM can burn out both the ROM and registers in the 8251 A requires a clock signal with a fre-
buffer outputs. The "A26" in the PROM decoder box of quency
16 ofor 64 times the rate at which you want to
the block diagram, incidentally, indicates that the 3625 shift data bits in or out. The clock for the transmit shift
IC will be numbered XA26 on the schematic sheet where register is called TxC and the clock for the receive shift
it is found. register is called RxC on the block diagram. These are
Follow the address bus to the upper right corner of the tied together because you usually want to send and re-
block diagram in Figure 7-5 to find how RAM is imple- ceive data
at the same rates. The clock for these inputs
mented
thisin system. The board comes with 2 Kbytes is produced by dividing down the 2.45-MHz PCLK signal
of static RAM contained in four 2142s. but there are from the 8284 clock generator. Wire wrap jumper pins.
sockets for another four 2142s. The initial lour devices W19-W25. allow you to select the desired TxC and RxC
occupy the address space from 00000H-007FFH. If four frequency from a divider chain in the 74LS393 baud
more 2142s are added, they will be in the address space rate generator. Baud rate is a way of specifying the rate
00800H-00FFFH. Another 3625 is used here as a RAM at which data bits are shifted in or out of a serial device.
decoder. As with the PROM decoder, the purposes of Baud rate for a device such as the 8251 A is defined as
this device are to turn on a memory device which corre- one over the time per bit. If the time per bit is 3.33 ms,
sponds
the to address sent out on the address bus, and for example, then the baud rate is 300 baud. Common
to make sure that only one device at a time is outputting baud rates for serial data transmission are 300. 600.
data on a data bus line. The 8086 can read or write a 1200. 2400, 9600. and 19,200.
byte, or it can read or write a word. Therefore, 16 data The final port to discuss here is the 8279 in the bot-
lines are connected to the RAM block. tom center
of the SDK-86 block diagram (Figure 7-5).
Now let's find the system ports in the block diagram in The 8279 is a specialized input/output device which
Figure 7-5. Two 8255As at the top of the page give the has two major functions. The first function is to scan
system programmable parallel ports. The term pro- the hex keypad, detect when a key is pressed, debounce
grammable
this case
in means that as part of your pro- the signal from a pressed key. and store the code for the
gram, you
send the 8255A a control byte. The control pressed key in an internal RAM where it can be read by
byte tells the 8255A whether you want a particular the 8086. The second major function of the 8279 is to
group of lines on the device to function as outputs or as refresh the multiplexed display on the eight 7-segment
inputs. In Chapter 9 we show you how to make up and LED displays. Seven-segment codes for the digits to be
send these control words. The two 8255As in this sys- displayed are sent to a RAM in the 8279. The 8279 then

186 CHAPTER SEVEN


D0-D7 2ZC3

D8-D15 2ZB3

1-5 V
IC GND
vcc

KIWI, 40 1, 20

8255A 26 7

8251A 26 4

8284 18 9

8279 40 20

2716 24 12

2142 20 10

3625 18 9

8286 20 10

74LS00 14

74LS04 14 7

74LS10 14

74LS14 14 7

74LS20 14 7

74S30 14 7

7 4LS74 14 7

74LS156 16 8

74LS164 14 7

74LS244 20 10

74LS393 14 7

7445 16 8

74S133 16 8

74S373 20 10

ULN20O3A 9 8

4. ALL DIODES 1N914B


3 ALL TRANSISTORS Q2T2905.
2 ALL CAPACITANCE VALUES ARE IN UF,
1. ALL RESISTANCE VALUES ARE IN OHMS
NOTES: UNLESSOTHERWISE SPECIFIED,

FIGURE 7-6 SDK-86 complete schematics, (sheet 1 of 9) {Intel Corporation)

mm SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 187


5ZA3 OFF BOARD

7ZCS 9ZC8 PCLf

5ZD8
7ZD8 RESET OUT
9ZD8

5ZA3 OFF BOARD BUFFER ON 4ZC6

DEN 4ZB6

FIGURE 7-6 'sheet 2 ol 9) {continued)


9
%1 1 1ZD7.6ZD7, 7ZC8
6
1, i, 1ZD7, 5ZD7. 6ZC7, 7ZC8. 9ZD8
12
8 1ZD7, 5ZD7, 6ZC7
lb
10 10
5 1ZD7, 6ZC7. 7ZC8
12 1.
2
] 1 1-1
M,
16 li, 1ZD7, 5ZC8, 6ZB8, 7ZC8 1 1
19
18 !!% :
3 i

'
5

/ /

9 9

1 1 11

% lu 20 20 1 i I 3
6
3Q 22 22 ZD7. 5ZB7.6ZB7, 7ZC8 IS 15
12
50 24 24 1/ 1-'
15
6Q 26 21, 1ZD7, 5ZB7, 6ZD7, 7ZB8 l'i 19
5
2u 28 .':% ; ..'1 21
2 1ZC7, 5ZB7, 6ZD7, 7ZB8
1Q (0 % 10 2 %: 23
19
8Q 32 '.2
2', 25
16 1ZC7, 5ZB7, 6ZC7, 7ZB8
7Q )4 11
'/ 27

:% % > ."i

-,i % il

i'i 33

v, :',

',/ -;% '


8Q J6 ;,,
16
,•;•! % :'i
7Q 38 «-;
15
60 40 4 1 II
40
12
5Q 42 42 1 i I i
9
4Q 2 2 45 % )•,

4/ 4/

49 49

FIGURE 7-6 (sheet 3 of 9) (continued)

8086 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 189


22A3 BUFFER ON

'-"

.'

•>

I i

1 1 %

15 - <

i . ' c

19

21

2 ;

."..

27

29

i1 - '

%I; '

16 — •

% ;/ - •
S9 - 4
•11

13
HLDA 2ZA8
i1 •

17 i
ri t

2ZC3 INTA

A16/S3

, .', 1/ ',1

A18/S5

FIGURE 7-6 (sheet 4 of ')) [continued)

190 CHAPTER SEVEN


RESET OUT

2ZA3

7ZD2 HIGH PORT!

3ZC3

7ZD2 LOW PORTSEL

H> OFF BOARD 2ZA8, 2ZD8

FIGURE 7-6 (sheet 5 of 9) (continued)

8086 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 191


I RP5
3ZC2 ••0 | 22 K
3ZA2 BHI .J
r A11
A12

A13

A14

3ZB?< A15

A16

AI7

IT

B 2ZA3
CS2

poo o o o o o o o o o o o o

D11
D I0

D15
D14
D ! %:
D12

FIGURE 7-6 (sheel 6 of 9 i ontinued)

192 CHAPTER SEVEN


•i ,., N
J J
h h 1
h- i t ' 1

J J -3 j ' < /J i

a; Q 1 a a 1 1 <i Q I
o

0
i
-: <
a
o
i
Hi'

ouooaaua

% •' '.'i % :.i H %D '•)


>d o
Q Q O %¡ Q Q Q Q

194 CHAPTERSEVEN
=00000 0 ^0 0

• * I I I II

I | § i Ulllllll
t/> ~* < '-'-•-
Q '
Z . o
< J tN 9 ID » -


5f Ls 5l^r

FIGURE 7-6 (sheet 9 of 9) (continued)

automatically sends out the code for one digit and turns takes care of scanning a keyboard and refreshing a dis-
on that digit. After a millisecond or so the 8279 sends playthat
so you don't have to do these operations as part
out the seven-segment code for the next digit and turns of your program.
on that digit. The process is continued until all digits Now that you have an overview of the ports in this
have been lit, and then the 8279 cycles back to the first system, see if you can find in the block diagram the de-
digit again. In Chapter 9 we discuss in detail how you coder which
selects an addressed port. You should find
use an 8279. The main point for now is that this device the 3625 labeled A22 about in the center of the block

8086 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 195


diagram. We discuss later how this device produces the screened on the board next to the corresponding IC.
port select signals from a port address sent out by the Usually IC numbers are sequential and start from the
8086. upper left corner of the component side of a board.
The final part of the SDK-86 block diagram to take a There may be several 2716s on the board, but only one
look at is the buffers along the right-hand edge. The will be labeled XA36.
purpose of these devices is to buffer the data and control Other devices often found on microprocessor boards
bus lines so that they can drive additional ROM. RAM. are resistor packs. You can find an example in zone C5
or ports that you might add to the expansion area of the of schematic sheet 1. As you can see from the schematic,
board. Note that the address lines are already buffered this device contains four 2.2-k$l resistors. Resistor
by the 74S373 address latches. packs may physically be thin, vertical, rectangular wa-
fers,they
or may be in packages similar to small ICs.
The advantages of resistor packs are that they take up
A First Look at the SDK-86 Schematics
less printed circuit board space and that they are easier
Now that you have seen an overview of the SDK-86. the to install than individual resistors.
next step is to take a first look at Figure 7-6. which Some other symbols to look at in the schematics are
shows the actual schematics for the board. At first these the structures with labels such as )2 and PI. You can
many pages of schematics may seem overwhelming to find examples of these in zones C7 and B7 of schematic
you. but if you use the 5-minute freak-out rule and then sheet 1. These symbols are used to indicate connectors.
approach the schematics one part at a time, you should The number in the rectangular box specifies the pin
have no trouble understanding them. The schematics number on the connector that a signal goes to. The let-
simply show greater detail for each of the parts of the terstands
P for plug. A connector is considered a plug if
block diagram that we discussed in the preceding sec- it plugs into something else. In the case of the SDK-86,
tionsthe
of chapter. the connector labeled P1 is the printed circuit board
At this point we want to make clear that it is not the edge connector. The letter ) next to a connector stands
purpose of this chapter to make you an expert on the for jack. A connector is considered a jack if something
circuit connections of an SDK-86 board. We use parts of else plugs into it. On the SDK-86 board the jacks J1-I6
these schematics to demonstrate some major concepts are 50-pin connectors that you can plug ribbon cable
such as address decoding and to show how the parts are connectors into. These jacks allow the address bus. data
connected together to form a small but real system. bus, control bus, and parallel ports to be connected to
Even if you do not have an SDK-86 board, you can learn additional circuitry.
a great deal from these schematics about how an 8086 One more point to notice on the SDK-86 schematics is
system functions. Multipage schematics such as these the capacitors on the power supply inputs shown in
are typical for any microprocessor-based board or prod- zone B6 of sheet 1. As you can see there, the schematic
uct, you
so need to get used to working with them. shows a large number of 0.1 -/nF capacitors in parallel
Before getting started on the next major concept, we with a 22-^iF capacitor. Most systems have filtering such
will discuss some of the symbols used on most micro- as this on their power lines. You may wonder what is the
processor system
schematics. The first thing that we use of putting all of these small capacitors in parallel
want to look at in the schematics are the numbers with one which is obviously many times larger. The
across the top and bottom of each and the letters along point of this is that the large capacitor filters out or by-
the sides of each. These are called zone coordinates. You passes low-frequency
noise on the power lines, and the
use these coordinates to identify the location of a part or small capacitors, spread around the board, bypass
connection on the schematic just as you might use simi- high-frequency noise on the power supply lines. Noise is
lar coordinates on a road map to help you locate Bowers produced on the power supply lines by devices switching
Avenue. For example, on sheet 1 of the schematics find from one logic state to another. If this noise is not fil-
the lines labeled A1-A7 in the upper left corner. Next to tered with
out bypass capacitors, it may become large
these lines you should see 3ZC2. This indicates that enough to disturb system operation.
these address lines come from zone C2 on sheet 3. To Glance through the SDK-86 schematics to get an idea
see what the lines actually connect to. first find sche- of where various parts are located and to see what addi-
matic sheet3. Then move across the row of the sche- tional informationyou can pick up from the notes on
matic labeledC until you come to the column labeled 2. them. In the next section of this chapter we discuss how
This zone is small enough that you should easily be able microcomputer systems address memory and ports. As
to find where these lines come from. The zone coordi- part of the discussion we cycle back to these schematics
nates next
to these lines on sheet 3 indicate the other to see how the SDK-86 does it.
schematic sheets and zones that these lines go to. For
practice, try finding where a few more lines connect
from and to. ADDRESSING MEMORY AND PORTS IN
The next points to look at on the schematics are the MICROCOMPUTER SYSTEMS
numbers on the ICs. In addition to a part number such
as 2716, each 1C has a number of the form XA36. This Address Decoder Concept
second number is used to help locate the IC on the While discussing the block diagram of the SDK-86 board
printed circuit board. The number is usually silk- earlier in this chapter, we mentioned that the 3625 de-

196 CHAPTER sFVtN


vices on ttie board serve .is <j<Mrc.s.s decoders. One func Note thai each 2732 in Figure 7-7 has a Chip Select
tion of an address decoder is to produce a signal which ((S| input. When this input is asserted low the ad
enables the ROM. RAM, or port device thai you want dressed byte in .1 devi« e will be outpul on tin- data bus
enabled foi .1 particulai address. A second, related tunc To get meaningful data from the EPROMs we need to
tion of an address decoder is to make sure that only one make sure that the ( S inpul ol only one device at .1 tunc
device at a time is enabled to put data on 1in- data bus is low. In the circuit in Figure 7 7 this is done by tin
lines. 74LS138. If the 74LS138 is enabled by making Us G2A
It seems that every microcomputer system does ad- and G2B inputs low and its (i I input high, then only one
dress decoding
in a different way from every other sys- outpul of the device will be low at a time. The output
tem. Therefore,instead ol memorizing the method used that will be low is determined by the 3-bit address ap
in one particular system, it is important thai you undo plied to the ( . B, and A select inputs For example, 11
stand the concept ol address decoding. You can then CBA is 000, then the YO output will be low, and all the
figure out any system you have to work on. other outputs will be high. ROM 0 will be selected. If CBA
is 001 . the Y1 output will be low and the ROM 1 will be
selected. If CBA is 111, then Y7 will be low, and only
A SYSTEM ROM DECODER ROM 7 will be enabled. Now let's see what address range
To start, look at Figure 7-7. This figure shows how eight each of these ROMs will have in the system.
EPROMs can be connected in parallel on a common ad- To determine the addresses of ROMs. RAMs, and ports
dress bus
and common data bus. From just looking at in a system, a good approach in many cases is to use a
the schematic you can see that these EPROMs output worksheet such as that in Figure 7-8. To make one of
bytes of data because each has eight outputs connected these worksheets you start by writing the address bits
to the system data bus. The number of address lines and the binary weight of each address bit across the top
connected to each device gives you an indication of how of the paper as shown in the figure. To make it easier to
many bytes are stored in it. Each EPROM has 12 ad- convert binary addresses to hex, it helps if you mark off
dress lines(A0-A11) connected to it. Therefore, the the address lines in groups of four as shown. Next, draw
number of bytes stored in the device is 212 or 4096. II vertical lines which mark off the three address lines that
you have trouble with this, think of how many bits a connect to the decoder select inputs (C, B, and A). For
counter has to have to count the 4096 states from 0 to the decoder in Figure 7-7 address lines A14, A13. and A12
4095 decimal, or 0000H to OFFFFH. are connected to the C, B, and A inputs of the decoder.

ADDRESS
BUS

ROM 0 ROM 1 ROM 7


2732 2732 2732

DATA
BUS

74LS138

FIGURE 7-7 Parallel ROMs with decoder.

SYSTEMCONNECTIONS,TIMING,AND TROUBLESHOOTING 1 97
HEX
2'-' 214 2" 2" 2" 2"' 29 28 23 22 EQUIVALENT
A15 A14 A13 A12 A11 A10 A9 A3 A7 A6 A5 A4 A3 A2 ADDRI •:.'.,

(START 0000
[END = 0FFF

SLOCK I SI AH I = 1000
2 I END = 1FFF

3L0CK | START 2000


3 Iend = 2FFF

(START = 3000
I END = 3FFF

|SI AH I = 4000
|END if i-r

5L0CK I START 5000


6 I END = 5FFF

I START = 6000
I END = 6FFF

I ST A R I = 7000
I END = 7FFF

DECODER
ADDRESS
INPUTS

FIGURE 7-8 Address decoder worksheet showing address decoding for eight
2732s in Figure 7-7.

respectively- Then write under each address bit the logic look at the worksheet in Figure 7-8 you should see that
level that must be on that line to address the first loca- the address ranges for the other six EPROMs in the sys-
tion the
in first EPROM. To address the first location in tem are2000H to 2FFFH. 3000H to 3FFFH, 4000H to
any of the EPROMs, the A0 through All address lines 4FFFH, 5000H to 5FFFH. 6000H to 6FFFH, and 7000H
must all be low, so put a 0 under each of these address to 7FFFH. In this system then we use address lines A14,
bits on the worksheet. To enable EPROM 0, the select A13, and A12 to select one of eight EPROMs in the overall
inputs of the decoder must be all O's. Since address lines address range of 0000H to 7FFFH. Some people like to
A14, A13, and A12 are connected to these select inputs, think of address lines A14. A13, and A12 as "counting
they must then all be O's to enable EPROM 0. Write a 0 off 4096-byte blocks of memory. If you think of the ad-
under each of these address bits on the worksheet. dress lines
as the outputs of a 16-bit counter, you can
Since address line A15 is connected to the C2A enable see how this works. The end address for each EPROM
input of the decoder, it must be asserted low in order for has all l's in address bits A0-A11 . When you increment
the decoder to work at all. Writeji 0 under the A15 bit on the address to access the next byte in memory, these
your worksheet. Note that the RD signal from the micro- bits all go to 0, and a 1 rolls over into bits A14, A13, and
processor control
bus is connected to the G2B enable A 12. This increments the count in these 3 bits by one
input of the decoder. The decoder then will only be en- and enables the next highest 4096-byte EPROM. The
abled duringa read operation. This is done to make sure count in these bits goes from binary 000 to 111.
that data cannot accidentally be written to ROM. The G1
enable input of the decoder is permanently asserted by
A SYSTEM RAM DECODER
tying it to +5 V because we don't need it for anything
else in this circuit. The system in Figure 7-7 contains only ROM. In most
You can now read the starting address of EPROM 0 systems we want to have ROM, RAM, and ports. To give
directly from the worksheet as 0000H. The highest ad- you more practice with basic address decoding we will
dressEPROM
in 0 is that address where A0-A11 are all show you now how we can add a decoder for FtAM to the
Is. If you put a 1 under each of these bits as shown on system.
the worksheet, you can see that the ending address for Suppose that we want to add eight 2K x 8 FlAMs to
EPROM 0 is OFFFH. Remember that A12-A14 have to be the system, and we want the first FIAM to start at ad-
low to select EPROM 0. A15 has to be low to enable the dress 8000H. just above the EPROMs which end at ad-
decoder. The address range of EPROM 0 is said to be dress 7FFFH.
0000H to OFFFH, a 4 Kbyte block. To start, make another worksheet such as the one in
Now let's use the worksheet to determine the address Figure 7-8. Addressing one of the 2048 bytes (2") in
range for EPROM i. EPROM 1 is enabled when A15 is 0, each RAM requires 1 1 address lines, A0-A10. These
A 14 is 0, A13 is 0. and A12 is 1. For the first address in lines will be connected directly to each RAM. so draw a
EPROM f address lines A0-A11 must all be low. There- vertical line on the worksheet to indicate this. Since we
lore, the starting address of EPROM 1 is 1000H. Its end- want to select one of eight RAM devices, we can use an-
ing address, when A0-A11 are all I's, is 1FFFF1. If you other 74LS138 such as we used for the EPROMs. We

198 CHAPTER SEVEN


mi '• DIGH HEX DIGIT Ml • DIGI HEX DIGIT
HI

A vl I •\u •
Al 1 All) AM - A/ A 1 A3 A2 Al AO ADDI

11 0 0 (1 11 [1 (1 0 1 11 n 0 0 0 8000H 1

0 0 0 1 0 0 0 0 II II II 0 0 0 II 8800H 2
0 0 I 0 0 0 0 0 11 11 0 0 0 0 0 9000H 3
0 0 I 1 0 0 11 (1 0 0 1) 0 0 0 0 9800H 4
0 1 0 0 0 0 0 0 0 0 II 0 0 0 0 AOOOH
0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 A800H 6
0 1 I 0 0 0 II 0 0 0 n 0 0 0 0 BOOOH /
ii I 1 1 0 0 0 0 0 0 0 0 0 0 II B800H 8

IK CODI R
ADDRESS
INPUTS

FIGURE 7-9 Address din odor workshoot tor eight 2 Kbyte RAMs Starting at
address 8000H.

want to select 2048-byte blocks of memory, so address 0 under A14. you will be able to quickly determine the
line A 1 1 will be connected to the A input of the decoder, address range for each of the RAMs. The first RAM will
A12 will be connected to the B input of the decoder, and start at address 8000H. The ending address for this
A13 will be connected to the C input of the decoder. RAM will be at the address where bits A0-A10 are all Is.
Under these 3 address bits on the worksheet list the If you put I's under these bits on your worksheet, you
3-bit binary count sequence from 000 to 1 1 1 as we did should see that the ending address for the first RAM is
in Figure 7-8. All we have left to decide is what to con- 87FFH. For practice, work out the hexadecimal ad-
nect the
to enable inputs of the decoder. We want the dresses
each
for of the other seven RAMs. When you fin-
block of RAM selected by the outputs of this decoder to ish, compare your results with those in Figure 7-9. The
start at address 8000H. For this, address A15 is high eight RAMs occupy the address space from 8000H to
and A14 is low. The G1 enable input of the decoder is BFFFH.
active high so we connect it to the A'15 address line. This
input will then be asserted when A15 is high. We con-
A SYSTEM PORT DECODER
nect A14
to G2A of the decoder so that this input will be
asserted when A14 is low. Because we don't need to use Figure 7- 10a shows how another 74LS138 can be con-
it in this circuit, we simply tie the G2B input of the de- nected
ourin system to produce chip select signals for
coder
ground
to so that it will be asserted all the time. some port devices. Make another address decoder work-
Note that we don't connect the RD signal to an enable sheet and
see if you can figure out the system address
input on a RAM decoder, because we want to enable the that corresponds to each of these decoder outputs.
RAMs for both read and write operations. Figure 7-9 Check your results with those in Figure 7- 10b. First
shows tbe address decoder worksheet for the 74LS138 note that A15 and A14 must be high to enable the de-
connections that we have just described. coder, and
write l's under these bits on your worksheet.
Now, ifyouputa 1 under A1 5 on your worksheet and a Then notice that A'13 and A12 must be low to enable the

HEX HEX HEX HEX HEX


DIGIT DIGIT DIGIT DIGIT PORT DEVICE
j 74LS08 A15A14 A13A12 A11 A10 A9 A8 A7 A6 A5 A i A3 A2 Al AO ADDRESS

110 0 0 0 0 Q 0 0 0 0 ii 0 0 II C 0 0 0

0 0 1 C 0 0 8

0 1 0 C 0 1 0

0 1 1 C 0 1 8

1 0 0 C 0 2 0

1 0 1 C 0 2 8

1 1 II C 0 3 0

1 1 0 0 0 0 0 0 II 8 1 1 1 C 0 3 8

DECODER
SELECT
INPUTS

FIGURE 7-10 Adding a port device decoder, (a) Schematic for 74LS138
connections, (b) Address decoder worksheet.

8086 SYSTEM CONNECTIONS, TIMING, AND TROUBiESHOOTINC 199


decoder, and write a 0 under each of these bits on your tagedirect
of I/O is that none of the system memory
worksheet. Finally determine which three address lines space is used for ports. The disadvantage is that only
are connected to the select inputs of the decoder, and the specialized IN and OUT instructions can be used to
write the binary count sequence from 000 to 1 1 1 under input or output data.
these bits. For this port decoder, address lines A3. A4, In a later section of this chapter we show how direct
and A5 will be connected to the decoder select inputs. I/O is done with the 8086, but first we will discuss how
Address lines AO, A'l . and A2 will be connected directly to the 8086 addresses memory.
the port devices to address individual ports and control
registers in the devices. This is the same idea as con-
necting
lower
the address lines directly to a ROM so that
we can address one of the bytes stored there.
8086 and 8088 Addressing and Address
Address lines A6-A11 are not connected to the port
Decoding
devices or to the decoder, so they have no effect on se-
8086 MEMORY BANKS
lecting
port.a We don't care then whether these bits are
l's or 0's. As you will see, these "don't care" bits mean The 8086 has a 20-bit address bus. so it can address 220
that there are many addresses which will turn on one of or 1.048.576 addresses. Each address represents a
the port devices. To give the simplest address for each stored byte. As you know from previous chapters, when
device, however, we assume that each of these don't care you write a word to memory with an instruction such as
bits is 0. Write 0's under each of these bits on your work- MOV DS:WORD PTR[437AH], BX, the word is actually
sheet. You
should now see that the address C000H will written into two consecutive memory addresses. As-
cause the YO output of the decoder to be asserted. The sumingDSthatcontains 0000. the low byte of the word
address C008H will cause the Y1 output of the decoder is written into the specified memory address. 0437AH.
to be asserted. Using address lines A3, A4. and A5 on the and the high byte of the word is written into the next
decoder select inputs then leaves eight address spaces higher address. 0437BH. To make it possible to read or
for each port device. write a word with one machine cycle, the memory for an
To see that any one of several different addresses can 8086 is set up as two "banks" of up to 524,288 bytes
select one of these port devices, replace the 0 you put each. Figure 7-1 la shows this in diagram form.
under A6 on the first line of your worksheet with a 1. One memory bank contains all the bytes which have
This represents a system address of C040H. A15 and A14 even addresses such as 00000. 00002, and 00004. The
are l's and A13, A12. A5. A4, and A3 are 0's, for this ad- data lines of this bank are connected to the lower eight
dress. Therefore, this address will also cause the YO out- data lines, D0-D7. of the 8086. The other memory bank
put of
the decoder to be asserted. You can try other com- contains all of the bytes which have odd addresses such
binations
l's and
of 0's on Ab-All if you need to further as 00001. 00003. and 00005. The data lines of this
convince yourself that these bits don't matter when ad- bank are connected to the upper eight data lines, D8-
dressing ports.
Again, we usually use 0's for these bits to D15. of the 8086. Address line AO is used as part of the
give the simplest address. enabling for memory devices in the lower bank. An ad-
Using a decoder which translates memory addresses dressed memory
device in this bank will be enabled
to chip select signals for port devices is called memory- when address line AO is low, as it will be for any even
mapped I/O. In this system a port will be written to or address. Address lines A1-A19 are used to select the de-
read from in the same way as any other memory loca- sired memorydevice in the bank and to address the de-
tion.other
In words, if this were an 8088 system, you sired byte
in that device.
would use an instruction such as MOV AL, DS:BYTE PTR Address lines A1-A19 are also used to select a desired
0C000H to read a byte of data from the first port to the AL memory device in the upper bank and to address the
register, instead of using the MOV DX, 0C000H and IN desired byte in that bank. An additional part of the ena-
AL, DX instructions. The advantage of memory-mapped blingmemory
for devices in the upper bank is a separate
I/O is that any instruction which references memory can signal called bus high enable, or BHE. BHE is sent out
be used to input data from or output data to ports. In a from the 8086 at the same time as an address is sent
system such as this, for example, the single instruction out. An external latch, strobed by ALE, grabs the BHE
ADD AL, DS:BYTE PTR [0C000HI could be used to input a signal and holds it stable for the rest of the machine
byte of data from the port at address C000H and add the cycle. The BHE signal will be asserted low if a byte is
byte to the AL register. The disadvantage of memory- being accessed at an odd address, or if a word at an even
mapped I/O is that some of the system memory address address is being accessed. Figure 7-1 lb shows you what
space is used up for ports and is therefore not available will be on the BHE and AO lines for different types of
for memory. memory accesses.
You can use memory-mapped I/O with any microproc- If you read a byte from or write a byte to an even ad-
essor, some
but microprocessors such as those of the dress such as 00000H. AO will be asserted low and BHE
8086 family allow you to set up separate address spaces will be high. The lower bank will be enabled and the
for input ports and for output ports. You access ports in upper bank will be disabled. A byte will be transferred to
these separate address spaces directly with the IN and or from the addressed location in the low bank on D0-
OUT instructions. Having separate address spaces for D7. For an instruction such as MOV AH, DS:BYTE PTR
input and output ports is called direct I/O. The advan- [0000], the 8086 will automatically transfer the byte of

200 ("HAPTFR SFVFN


UPPI R HANK R HANK
ODD AIM-
BYTES B I' .

DATA BUS
AO ADDRESS BHE AO
i mi in. 1 TYPE CYCLES
m 11hk

00003 00002 0000 B Y II 1 0 ) II

hi mm 0O00OH 0000 WuUIJ 0 0 ONE


At !
0001 BYTE 0 1 ONE

0001 WORD 0 1 FIRST


D15
1 0 SECOND

FIGURE 7-11 8086 memory banks, (a) Block diagram, (b) Signals tor byte and
word operations.

data from the lower data bus lines to AH. the upper byte from memory. During the first machine cycle the 8086
of the AX register. You just write the instruction and the will output address 0000 1H and assert BHE low. AO will
8086 takes care of getting the data in the right place. be high. The byte from address 0000 1H will be read into
Now. if the DS register contains OOOOH and you use the 8086 on lines D8-D15 and put in AL. During the
an instruction such as MOV AX, PS: WORD PTR [OOOOI to second machine cycle the 8086 will send out address
read a word from memory into AX. both A0 and BHE will 00002H. AO will be low, but BHE will be high. The second
be asserted low. Therefore, both banks will be enabled. byte will be read into the 8086 on lines D0-D7 and put in
The low byte of the word will be transferred from address AH. Note that the 8086 automatically takes care of get-
00000H to the 8086 on D0-D7. The high byte of the tingbyte
a to the correct register regardless of which
word will be transferred from address 0000 1H to the data lines the byte comes in on.
8086 on D8-D15. The 8086 memory, remember, is set The main reason that the AO and BHE signals function
up in banks so that words, which have their low byte at the way they do is to prevent the writing of an unwanted
an even address, can be transferred to or from the 8086 byte into an adjacent memory location when the 8086
in one bus cycle. When programming an 8086. then, it writes a byte. To understand this, think what would
is important to start an array of words on an even ad- happen if both memory banks were turned on for all
dress for
most efficient operation. If you are using an write operations, and you wrote a byte to address 00002
assembler, the EVEN directive is used to do this. with the instruction MOV DS:BYTE PTR [0002], AL. The
When you use an instruction such as MOV AL, data from AL would be written to address 00002 as de-
DS:BYTE PTR [0001] to access just a byte at an odd ad- sired. However,
since the upper bank is also enabled,
dress.will
A0 be high and BHE will be asserted low. the random data on D8-D15 would be written into ad-
Therefore, the low bank will be disabled, and the high dress 00003. The 8086 then is designed so that BHE is
bank will be enabled. The byte will be transferred from high during this byte write. This disables the upper
memory address 0000 1H in the high bank to the 8086 bank of memory and prevents the random data on D8-
on lines D8-D15. The 8086 will automatically transfer D15 from being written to address 00003.
tin- bvlc nl data I mm tin- high r eight data lines to AL. Now that you have an overview of address decoding
the low byte of the AX register. Note that address and of the 8086 memory banks, let's look at some exam-
0000 1H is actually the first location in the upper bank. pleshow
of all of this is put together in a small system.
The final case in Figure 7-1 lb is that where you want
to read a word from or write a word to an odd address.
ROM ADDRESS DECODING ON THE SDK-86
The instruction MOV AX, DS:WORD PTR [0001 H] copies
the low byte of a word from address 00001 to AL and the Sheet 1 of the SDK-86 schematics in Figure 7-6 shows
high byte from address 00002H to AH. In this case the the circuit connections for the EPROMs and EPROM
8086 requires two machine cycles to copy the two bytes decoder. The 2716 EPROMs there are 2K % 8 devices.

808b SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 201


Two of the EPROMs have their eight data outputs con- Now, to analyze any decoder circuit, first determine
nected
parallel
in to system data lines DO— D7. These two what signals are required to enable the decoder. The CS1
EPROMs then give 4 Kbytes of storage in the lower mem- enable input of the 3625 EPROM decoder is tied to
ory bank. The other two EPROMs have their data out- ground so it is permanently enabled. The CS2 enable
puts connected in parallel on system data lines D8-D15 input is tied to the RD signal from the 8086, so that the
to give 4 Kbytes of storage in the upper bank of ROM. decoder will only be enabled if the 8086 is doing a read
Eleven address lines are needed to address the 2 Kbytes operation. As explained previously, you don't want to
in each device. Therefore, system address lines A1-AT1 accidentally enable a ROM if you send out a wrong ad-
are connected to each EPROM. Remember that we can't dress during
a write operation.
use AO for this because, as we described in the last sec- The next step in analyzing a decoder circuit using a
tion,isit used in enabling the lower bank. PROM is to consult the manufacturer's manual for the
A 2716 has two enable inputs. CE and OE. In order for system. You need to do this because, for a PROM, the
the 2716 to output an addressed byte, both of these en- relationship between the inputs and the outputs can-
able inputs must be asserted low. The CE inputs of the not be
determined directly from the schematic.
two devices in the lower bank are connected to system Figure 7- 1 2 shows the truth table for the PROM from
address line AO, so the CE inputs of these devices will be the SDK-86 manual. This truth table is very similar to
asserted if AO is a 0. The CE inputs of the two 2716s in the address decoder worksheet that we used in previous
the upper bank are connected to the BHE line. The CE sections of the chapter. From the truth table you can see
inputs of these devices then will be asserted whenever that in order for the 01 output to be asserted low. M/IO
BHE is asserted low. To summarize, then, the two de- has to be high. This is reasonable since this decoder is
vices labeledXA27 and XA36 form the lower bank of enabling memory devices. Address lines A12-A19 also
EPROM and the two devices labeled XA30 and XA37 have to be high in order for the 01 output of the PROM
form the_upper bank of EPROM in this system. To see to be asserted low. Since the upper eight address bits
how the OE enable input of each of these devices gets must all be Is for the 01 output to be asserted, the low-
asserted and to determine the address that each device est address which will cause this is FF000H. Refer to
will have in the system you need to look next at the 3625 sheet 1 of the SDK-86 schematics in Figure 7-6 to see
address decoder labeled XA26. that the 01 output of the decoder PROM connects to the
A 3625 is a IK % 4 bipolar PROM which performs the OE enable inputs of two of the 2716 EPROMs. XA27 and
same function that a 74LS138 performs in Figures 7-7 XA30. Note also on the schematic, or remember from a
and 7-10. Since a 3625 has open collector outputs, a previous_ discussion, that the other enable input of
pull-up resistor to +5 V is required on each output. The XA27, CE. is connected to system address line AO. The
dotted box around the four resistors on the schematic XA27 EPROM then will be enabled whenever the 8086
indicates the four are all contained in one package, re- does a memory read from an even address (AO = 01 in the
sistor pack
5 (RP5). The 3625 translates an address to a range FF000H to FFFFFH. Now let's look at the XA30
signal which is used as part of the enabling of the EPROM_
desired device. Using a PROM as an address decoder, The CE enable input of X430 is connected to the sys-
however, is for several reasons much more powerful tem BHE
line. As shown in Figure 7-11, BHE will be as-
than using a simple decoder such as the 74LS138. In serted whenever
low the 8086 accesses a byte at an odd
the first place, the 3625 is programmable, which means address or a word at an even address. TheXA30 EPROM
that you can move the memory devices to new addresses then will be enabled when the 8086 reads a byte from an
in memory by simply programming a new PROM. Sec- odd address in the range FF000H to FFFFFH. XA30 will
ondly,large
the number of inputs on the PROM allow also be enabled when the 8086 asserts both AO and BHE
you to select a specific area of memory without using low to read a word that starts on an even address in the
external gates. If. for example, you wanted the G2A range FF000H to FFFFFH.
input of a 74LS138 to be asserted if A11-A15 were all These EPROMs are put at this high address in mem-
high, you would have to use an external NAND gate to ory onthe SDK-86 board because, after a RESET, the
detect this condition. With a PROM you can just make 8086 goes to address FFFF0H to get its first instruction.
this condition part of the truth table you use to burn Since we want the SDK-86 to execute its monitor pro-
the PROM. gram afterwe press the RESET button, we locate the

PROM INPUTS PROM OUTPUTS


PROM ADDRESS
BLOCK SELECTED
M/IO A14-A19 A13 A12 04 03 02 01

1 1 1 1 1 1 1 II FFOOOH-FFFFFH
1 1 1 0 1 1 0 1 FEOOOH-FEFFFH
1 1 0 1 1 0 1 1 FDOOOH-FDFFFH (CSX)
1 1 0 0 0 1 1 1 FCOOOH-FCFFFH (CSY)

ALL OTHER STATES 1 1 1 1 NONE

FIGURE 7-12 Truth table tor an SDK-86 (A26) ROM decoder PROM.

202 CHAPTFR SEVEN


HIGH LOW First lake a look al the input and output lines on the
BANK BANK
2 142 sialic RAM devices. From the fact ihat each device
FFFFF FFFFEH
has lour daia I () lines you can conclude that the devil es
XA30 XA27
FE001 I I OOOH store I bit words. The fact that each device has 10 ad
FEFFF dress Inputs, A0-A9, indicates that each one sto
XA37 XA36
oi 1024 of these 4-bit wends. To si ore bytes, two 2 142s
F i 00 1 I i 000
an- enabled in parallel. Devices A38 and A4 1 , foi exam
FICURI 7-13 ROM memory map for SDK-86 board. pie, are enabled together to store bytes from the lower
eight dala hues. and devices A43 and A45 are enabled
together to store bytes from the upper eight data lines.
EPROM containing the monitor program such that (his Note next that the control bus signals RD, VVK. and M lo
address is in it. The lour SDK-86 EPROMs actually con- are connected toallol the 2142s. RD is connected to the
tain twomonitor programs. One monitor in devices output disable, OD, pin on the 2142s. When the RD sig
XA27 and XA30 allows you to use the hex keypad for nal is high or when the device is not enabled, the output
entering and running programs. The oilier monitor in buffers will be disabled. During a read operation the RD
devices XA36 and XA37 allows you to use an external signal is asserted low. If a 2142 is enabled and its OI)
CRT terminal to enter and run programs. Using sheet I input is low, the output buffers will be turned on so that
of the schematic and the PROM truth table in Figure an addressed word is output onto the data bus.
7-12, see if you can determine the address range lor the WR from the 8086 is connected to the write enable,
XA36 and XA37 EPROMS. WE. input of the 2142s. Ifa2142 is enabled, dala on the
The OE enable inputs of the XA36 and XA37 devices data bus will be written into the addressed local ion in
are connected to the 02 output of the address decoder the RAM when the 8086 asserts WR low.
PROM. According to the truth tablejor the PROM, the The 2142s have two enable inputs. CS1 and CS2. The
02 output will be asserted low if M/IO is high. A14-AI9 M/IO signal from the 8086 is connected to the CS2 input
are high. A 13 is high, and A12 is low. The lowest address of all of the 2142s. Since the CS2 input is active high, it
that will assert the 02 output of the PROM then is will be asserted whenever the 8086 is doing a memory
FE000H. and the highest address that will assert the 02 operation. The CS1 inputs of the 2142s are connected in
output low is FEFFFH. Therefore the address range for pairs to the outputs of a 3625 PROM which functions as
XA36 and XA37 is FE000H— FEFFFH. Since AD must an address decoder.
also be low to enable the XA36 EPROM. this device con- In order to assert any of its outputs and enable some
tains the even-addressed bytes in this range. Since BHE RAM. the 3625 must itself be enabled. Since the CS2
must also be low to enable the XA37 EPROM. this device enable input of the PROM is tied to ground, it is perma-
contains the odd-addressed bytes in the range FE000H — nently enabled.The CS1 enable input will be asserted
FEFFFH. A memory map such as the one in Figure 7-13 when system address line A19 is low. To determine any
is a convenient way to summarize where each device is more information about this PROM you need to look at
located in the system address space. Note that the 3625 the truth table for the device. Before we go on to that,
ROM decoder has two unused outputs which can be however, note that AO and BHE are connected to two of
used as part of the enabling for EPROMs you add to the the address inputs on the 3625 PROM. Knowing what
prototyping section of the board. you do about 8086 memory banks, why do you think we
want A0 and BHE to be part of what determines the out-
RAM ADDRESS DECODING ON THE SDK-86
puts for
this decoder? If you don't have the answer to
To give you another example of memory address decod- this question, a look at the truth table for the device in
ing in
a real system, we now discuss the RAM decoding Figure 7-14 should help you.
of the SDK-86 board. Sheet 6 of the SDK-86 schematics According to the third line of the truth table/address
in Figure 7-6 shows the circuit for the system RAM and decoder worksheet in Figure 7-14, the O'l output of the
RAM decoder. Let's look at this schematic to see what we PROM will be asserted low if A12-A18 are low, A 11 is low,
can learn from it. BHE is high, and AO is low. The Ol output then will be

PROM INPUTS PROM OUTPUTS


BYTE(S) SELECTED
04 01
(ADDRESS BLOCK)
A12-A18 A11 BHE A0 03 02

0 i 0 0 1 1 0 0 BOTH BYTES (OH I17FFH)

0 0 0 1 1 1 0 1 HIGH BYTE (0H-07FFH)

0 0 1 0 1 1 1 0 LOW BYTE (0H-07FFH)

0 1 0 0 0 0 1 1 BOTH BYTES (0800H-0FFFH)


0 1 0 1 0 1 1 1 HIGH BYTE (0800H-0F F FH)
0 1 1 0 1 0 1 1 LOW BYTE (0800H-0FFFH)
ALL OTHER STATES 1 1 1 1 NONE

FIGURE 7-14 Truth table for an SDK-86 (A29) RAM decoder PROM.

8086 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 203


asserted for even system addresses starting with port address is written as part of the instruction. The
00000H. A low on the 0 1 output will enable the A38 and instruction IN AL, 38H. for example, copies a byte from
A4 1 RAMs which are connected to the lower hall of the port 38H to the AL register. For variable-port input or
data bus. These two devices are part of the lower bank of output operations, the 16-bit port address is first loaded
RAM. into the DX register with an instruction such as MOV
Next look at the second line of the PROM truth table in DX, 0FFF8H. The instruction IN AL, DX is then used to
Figure 7-14. From this line you should see that the 02 copy a byte from port FFF8H to the AL register. MOV DX,
output of the PROM will be asserted low if A12-A18 are 0038H followed by IN AL, DX has the same effect as IN AL,
low. Al 1 is low, BHE is low. and AO is high. The 02 out- 38H.
put willthen be asserted for odd system addresses start- Whenever the 8086 uses the IN or OUT instructions to
ing with 000 1H. A low on the 02 output will enable the access a port, the port address is sent out directly from
A43 and A45 RAMs which are connected on the upper the 8086 on lines AD0-AD15. None of the segment regis-
half of the data bus. These two devices are part of the ters hasany effect on the address for an IN or OUT in-
upper bank of RAM. struction.
8086TheaJways outputs O's on lines A16-A19
Now. suppose we want to write a 16-bit word to RAM during an IN or OUT instruction. Since the 8086 out-
at an even address. To do this we want both Ol and 02 puts16-bit
a address for direct I/O operations, it can
to be asserted low so that both the lower bank RAMs and address any one of 2"J or 65,536 input ports, and any
the upper bank RAMs are enabled. According to the first one of 65,536 output ports. An 8086 system which uses
line of the PROM truth table in Figure 7-14. 01 and 02 direct I/O is designed so that the separate address space
will both be asserted low if BHE and AO are both low. for ports is enabled when the M/IO signal from the 8086
Remember from Figure 7-1 1 that BHE and AO will both is low. Remember that the M/IO signal being high was
be low whenever you write a word to an even address or one of the enabling conditions for the SDK-86 ROM and
read a word from an even address. This last case gives RAM decoders we discussed in previous sections. The
the answer to the question we asked earlier about why M/IO signal will be low during any direct input or output
AO and BHE are connected to the address decoder PROM operation. The RD signal from the 8086 will also be low
inputs. The two inputs are required to tell the PROM during an IN operation, so this signal is used to enable
decoder to assert both Ol and 02 for a word read or an addressed port device for input. The WR signal from
write operation. the 8086 will be low along with M/IO during an OUT
The address range for the XA38. XA41, XA43. and operation, so this signal is used to enable an addressed
XA45 RAMs is 00000H to 007FFH. Another look at the port for output.
PROM truth table in Figure 7-14 should show you that For an example of how direct I/O ports are addressed
RAMS XA39, XA42, XA44, and XA46 contain 2K more and selected in a real system, we will again look at the
bytes in the range 00800H to OOFFFH. Again, both SDK-86 schematics in Figure 7-6. sheet 7. Here another
banks of this additional F-iAM will be enabled if AO and 3625 PROM IXA22) is used to produce the chip select
BHE are both low, as they are for reading or writing a signals for four I/O devices. The 01 output of the PROM
word to an even address. is used to enable the 8279 keyboard/display interface
device. A section of Chapter 9 discusses in detail the
operation of this device. The 02 output of the PROM is
SDK-86 PORT ADDRESSING AND PORT
used to enable the 8251 A USART shown on sheet 9 of
DECODING
the schematics. The 8251 A allows communication with
In a previous section of this chapter we described other systems in serial form. A section in Chapter 13
memory-mapped input/output. In a system with discusses the operation of this device. The 03 and 04
memory-mapped I/O, port devices are addressed and se- outputs are connected to two 8255A parallel port devices
lected
decoders
by as if they were memory devices. The shown on sheet 5 of the schematics. These devices can
main advantage of memory-mapped I/O is that any in- be enabled individually to input or output bytes. They
struction which
refers to memory can theoretically be can also be enabled together to input or output words. A
used to read from or write to a port. The single instruc- section in Chapter 9 shows you how to tell each port in
tion ADDBH, DS:BYTE PTR [437AH] could be used to read these devices whether you want it to be an input or an
a byte from a port and add the byte read in to the BH output.
register. The disadvantage of memory-mapped I/O is Take a look now at the 3625 decoder PROM to see if
that the ports occupy part of the system memory space. you can determine what conditions enable it. You
This space is then not available for storing data or in- should find that theJ^S2 enable input of the PROM will
structions. be asserted when M/IO is low as it is during an input or
To avoid having to use part of the system memory output operation. Furthermore, you should see that the
space for ports, the 8086 family microprocessors have a CS1 input will be asserted when A11-A15 are all high.
separate address space for ports. Having a separate ad- Now. to see what addresses cause each of the PROM out-
dress space
for ports is called direct I/O. because this puts be
to asserted, refer to the address decoder work-
separate address space is accessed directly with the IN sheet for
the PROM in Figure 7- 15a. From this figure
and the OUT instructions. you can see that to assert the Ol output low. A5-A15
Remember from previous chapters that the 8086 IN have to be high, A4 has to be low. and A3 has to be high
and OUT instructions each have two forms, fixed port and AO has to be low. BHE can be either a high or a low.
and variable port. For fixed-port instructions an 8-bit Note, however, that only the lower eight data lines. DO-

204 CHAI'TLR SEVEN


PROM INPUTS I'Hi >M i 'i 1 1 imi I :.,•

04 02
Ml A 15 0,5 MO A 1 BHI AO
% .i i i i I Mil. I t DSI 1

0 1 0 0 1 1 1 0

0 1 1 0 1 1 1 II

0 0 0 1 1 0

0 1 0 1 1 0

1 0 0 0 0 1

1 0 1 0 1 1

1 1 1 0 1

ALL OTHER STATES 1 1 1

PORT ADDRESS PORT FUNCTION

0000
to OPEN
FFDF

FFE8 READ/WRITE 8279 DISPLAY RAM OR READ 8279 FIFO


E9
EA READ 8279 STATUS OR WRITE 8279 COMMAND
EB
EC RESERVED
ED
EE RESERVED
FFEF

FFFO READ/WRITE 8251 A DATA


Fl
F2 READ 8251 A STATUS OR WRITE 8251 A CONTROL
F3
F4 RESERVED
F5
F6 RESERVED
FFF7
FFF8 READ/WRITE 8255A PORT P2A
F9 READ/WRITE 8255 A PORT PI A
FA READ/WRITE 8255A PORT P2B
FB READ/WRITE 8255A PORT P1B
FC READ/WRITE 8255A PORT P2C
FD READ/WRITE 8255A PORT P1C
FE WRITE 8255A P2 CONTROL
FFFF WRITE 8255A PI CONTROL

FIGURE 7-15 Truth table and map for SDK-8b port decoder, (a) Truth table, (b) Map.

D7, are connected to the 8279. Therefore, data must be select one of two internal addresses in the 825 1A I Figure
sent to or read from the 8279 at an even byte address. In 7-6, sheet 9). A1 low selects one internal address and A1
other words data must be sent as a byte to an even ad- high selects the other internal address. The two system
dressasor the lower byte of a word to an even address. addresses for this device then are FFFOH and FFF2H.
The system base address for this device then is Now. before discussing the 03 and 04 outpLits of the
FFE8H. System address line A1 is connected to the 8279 decoder PROM, we will take a brief look at the two 8255
to select one of two internal addresses in the device. A1 parallel port devices they enable. These devices are
low selects one internal address and Al high selects the shown on sheet 5 of the schematics in Figure 7-6. Each
other internal address. A1 low gives system address of these devices contains three 8-bit parallel ports and a
FFE8H. and A1 high gives system address FFEAH. These control register. System address lines A1 and A2 are
are then the two addresses for the 8279 in this system. used to address the desired port or register in the device
According to the worksheet in Figure 7- 15a, the 02 just as lower address lines are used to address the de-
output of the decoder PROM will be asserted low when sired internal location in a memory device. Note that the
A4-A15 are high, and A3 and AO are low. BHE can be lower eight data lines. D0-D7. are connected to the
either a low or a high. but. since only the lower eight XA40 device, and the upper eight data lines are con-
data lines are connected to the 8251 A USART, data nected
the to XA35 device. This is done so that you have
must be sent to or read from the device as bytes at an several input or output possibilities. You can read a byte
even address. Again system address line A1 is used to from or write a byte to an even-addressed port in device

8086 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOf HIM 205


XA40. You can read a byte from or write a byte to an 86 schematics. The purpose of this circuitry is to pro-
odd-addressed port in device XA35. You can read a word duce the
signal OFF BOARD whenever the 8086 sends
from or write a word to a 16-bit port made up from an out a memory or port address which does not corre-
8-bit port from device XA40 and an 8-bit port from de- spond to a device decoded on the board. The OFF BOARD
vice XA35.To input or output a word both devices have signal will be asserted low if pin 4 of the A3 NAND gate is
to be enabled. Now let's look at the decoder truth table to low or if pin 5 of the A3 NAND gate is low. According to
determine what addresses enable the various ports in the truth table for the XA12 PROM in Figure 7-16. the
these devices. 01 output will be low if the the 8086 is doing a memory
The .YA40 device will be enabled by the 03 output of operation and the address sent out is not in one of the
the decoder PROM if address lines A3-A15 are high and ranges decoded for the on-board RAM or ROM.
AO is low. A1 and A2 are used to select internal ports of In order for pin 4 of the A3 NAND gate to be low. both
the 8255A. Let's assume that these two bits are 0 for the pin 9 and pm 10 of the A3 NAND uate must be high. Pin
first address in the device. To select the A port in the 10 will be high_if the 8086 is doing an input or output
XA40 8255A. address lines A1 and A2 have to be low. operation IIO'M from the 8286 inverting buffer equals
The system address that will enable this device and se- 1 1. Pin 9 of the A3 NAND gate will be high if any one of
lect the
A port within it is FFF8H. Other values of A2 and the A 19 NAND gate inputs is low. Since system address
A I will select one of the other ports or the control regis- lines A5-A15 are connected to the inputs of the 74LS133
ter inthis device. Figure 7- 15b shows the system ad- NAND gate, the signal to pin 9 of A3 will be high for any
dresses
thefor ports and control register in this 8255. address less than FFE0H. In other words, pin 4 of the A3
Note that the ports in this device (XA40) are identified NAND gate will be asserted low for any I/O operation in
as port 2A. port 2B. and port 2C. These all have even an address range not selected by the.Y.422 port decoder.
addresses because AO must be low for this device to be The OFF BOARD signal produced by the previously
selected. discussed PROM and logic gates is connected to an
The XA35 8255A which contains port 1 A. port 1 B. and input of a NAND gate labeled A2 on sheet 2 of the sche-
port 1C will be enabled by the 04 output of the decoder matics.
OFFIf BOARD is asserted low. or INTA is as-
PROM if A3-A15 are high and the BHE line is low. If this serted low.
or HLDA is asserted low. the output of this
8255A is being enabled for a byte read or write, then the gate will be high. For now all we are interested in is the
AO line will also be high. A2 and A1 are again used to fact that if OFF BOARD is asserted low, a high will be
address one of the ports or the control register within applied to pin 1 of the A3 NAND gate in zone A4 of the
the 8255A. A2 = 0 and A1 = 1 will select port 1A in this schematic. If the DEN signal from the 8086 is also as-
8255A. As shown in Figure 7- 15b. then, the system ad- serted low.
the signal labeled BUFFER ON will be as-
dress port
for 1A is FFF9H. Port 1B will be accessed with serted low.
The DEN signal from the 8086 will be as-
a system address of FFFBH. port 1C will be accessed serted whenever the 8086 reads in data from a memory
with a system address of FFFDH. and the internal con- location or a port, or when it writes data to a memory
trol register will be accessed with a system address of location or port. The BUFFER ON signal produced here is
FFFFH. used to enable the 8286 data bus buffers (XA6 and XA7)
Note in the truth table in Figure 7- 15a that the 3625 shown on sheet 4 of the schematics. Now here's the
PROM decoder will enable a port device only when the point of all this.
specific address assigned to that device is sent out by In the next chapter we show you how to add another
the 8086. This is sometimes called complete decoding LO decoder and some other devices to the prototyping
because all of the address lines play a part in selecting a area of an SDK-86 board. To drive these additional de-
device and one of its internal ports or registers. As we vices, address,
the data and control buses must all be be
show in a later section, adding another decoder to pro- buffered. The address bus on the SDK-86 board is buf-
duce enable
signals for more port devices is very' easy in feredthe
by 74S373 address latches shown on sheet 3 of
a system which uses this complete decoding. the schematics. Data bus and control bus buffers are
not needed to drive the ROM, RAM. and port devices
THE SDK-86 "OFF-BOARD" DECODER that come with the SDK-86 board. To read data from or
Before we show you how another port decoder ran In- write data to external devices, however, the data bus is
added to the SDK-86. we need to briefly discuss the op- buffered by two 8286s shown as XA7 and XA6 on sheet 4
eration
the ofoff-board circuitry on sheet 5 of the SDK- of the SDK-86 schematics. These two buffers are turned

PROM INPUTS
PROM OUTPUT CORRESPONDING
(01) ADDRESS BLOCK
A19 A18 A17 A16 A15 A14 A13 A12

1 0 0 0 0 0 0 0 0 1 (INACTIVE) OH-OFFFH (ON-BOARD RAMi

1 1 1 1 1 1 1 1 0 1 (INACTIVE) FEOOOH-FEFFFH (ON-BOARD PROM)

1 1 1 1 1 1 1 1 1 1 (INACTIVE) FFOOOH-FFFFFH (ON-BOARD PROM)

ALL OTHER STATES 0 (ACTIVE) 01000H-FDFFFH (OFF-BOARDl

FIGURE 7-16 SDK-86 "off-board" decoder PROM truth table.

206 CHAPTER SEVEN


on when the BUI 1 1 K ON signal, described in the pieced matic.
a jumpei
II is installed m the W27 position, Idi
ing paragraph, is asserted low. The 8286 buffers are example, no WAIT slates will be Inserted. II a jumper is
bidirectional. When these buffers are enabled, the Data installed ill the W2H position, one WAIT state will be in
Transmit Receive signal, Dl R, from the 8086 will deter- sei led I hi' pattern continues to jumpei W !4 which will
minewhich
in direction the buffers are pointed. II DT/R cause seven WAI I' states to be inserted in each machine
is high, the buffers will be enabled to write data to some cycle I lere's how ihe WAIT state generator Itsell woi ks.
external device. II I) I K is low, the buffers will be enabled The 74LS164 WAI'F state generatoi is an 8 bit shifl
to read data in from some external device. registei At the start of a machine cycle the Rl). WR, and
The control bus signals are buffered by an 8286 la INTA signals from the 8086 are all high. These three sig
beledXAl 1 and a 74LS244 labeled XA8 on sheet 4 ol the rials being high will cause the NAND gate in zone < I to
SDK 86 schematics. These buffers are permanently en- assei i the clear input, CLR, of the shift register. The out-
abled
send
to out the control bus signals except during a putsthe
of shift register will then all he low. One of these
HOLD stale which we will explain later. lows will be coupled through a jumper and an invei tei in
pin 9 ot Ihe A15 NAND gate we discussed previously.
THE SDK-86 WAIT STATE GENERATOR CIRCUITRY
This high on pm !) together with a high on pin 1 1 will
Now that you know how the OFF BOARD signal is pro- cause Ihe RDY I input ol the 8284 to he pulled low. I low-
ducedthe
on SDK-86 board, we can explain the opera- ever, wait states will not be inserted unless RDY1 re-
tion ot
the WAIT state generator circuitry shown on mainslong
low enough. Now. when RD, WR. or IN IA
sheet 2 of the schematics. goes low in the machine cycle, the CFR input of the
In a previous section of the chapter we mentioned that 74LS164 shift register will go high, and the shift regis-
if the RDY input of the 8086 is asserted low. the 8086 ter will
function normally. The highs on the INA and INB
will insert one or more WAIT states in the machine cycle inputs will be loaded onto the QA output on the next
it is currently executing. Figure 7-2 shows how a WAIT positive edge of the clock. If the wait state jumper is in
state is inserted in an 8086 machine cycle. During a the W27 position, then this high on the QA output will,
WAIT state the information on the buses is held con- through the inverter and NAND gate, cause the RDY I
stant. Whatever was on the buses at the start of the input of the 8284 to go high again. For this case the
WAIT state remains throughout the WAIT state. The RDY1 input goes high soon enough that no WAIT states
main purpose of inserting one or more WAIT states in a are inserted.
machine cycle is to give an addressed memory device or The high loaded into the 74LS164 shift register is
I/O device more time to accept or output data. In the shifted one stage to the right by each successive clock
next major section of the chapter we show you how to pulse. When the high reaches the jumper connected to
determine whether a WAIT state is needed for a given the A25 inverter, it will cause the RDY1 input of the
device with a given 8086 clock frequency. For now, how- 8284 to go high. The 8086 will then exit from a WAIT
ever, let's
just see how the circuitry on the SDK-86 board state on the next clock pulse. The number of WAIT
causes the 8086 to insert a selected number of WAIT states inserted in a machine cycle is determined by how
states. many stages the high has to be shifted before it reaches
WAIT states are inserted by pulling the RDY1 input of the installed jumper.
the 8284 clock generator IC low (Figure 7-6. sheet 2. To summarize all of this, the 8086 will insert the se-
zone C6). The 8284 internally synchronizes the RDY1 lected number of WAIT states in any machine cycle
input signal with the clock signal and sends the resul- which accesses any device not addressed on the board,
tant signalto the RDY input of the 8086. For the SDK-86 or any I/O device on the board. If jumper W39 is inserted,
the RDY1 input will be asserted low if all three inputs of the selected number of WAIT states will be inserted for
the A 15 NAND gate shown in zone D5 of the schematic any on-board or off-board access. The purpose of insert-
are high. Pin 10 of this device is tied to +5 V. so it is ing waitstates is to give the addressed device more time
permanently high. Pin 1 1 of A15 will be high if any of to accept or output data.
the inputs of the NAND gate in zone D7 are asserted low.
Pin 1 of this gate will be low whenever the 8086 does an
input or output operation. Pin 2 of this gate will be low How the 8088 Microprocessor Accesses
whenever the 8086 accesses a port or memory location Memory and Ports
which is not decoded on the board. In other words, with Now that we have shown in detail how the 8086 accesses
these connections the selected number of WAIT states memory and port devices, we can show you how the
will be inserted in each machine cycle when the 8086 8088 does it.
does a read from or a write to an on-board I/O device, or In Chapter 2 we mentioned that the 8088 is the CPU
when the 8086 does a read from or a write to any device used in the IBM PC and the IBM PC/XT. The instruction
not decoded on the board. If jumper W39 is installed on set of the 8088 is identical to that of the 8086. and the
pin 13 of A15. pin 11 of A15 will always be high. The registers of the two are the same. There are two major
selected number of WAIT states selected by the W27-W34 differences between the two devices. First, the 8088 in-
jumpers will be inserted for all read and write opera- structionqueue
byte is only 4 bytes long instead of 6.
tions. Second, and more important, the 8088 memory is not
The desired number of wait states to be inserted is divided into two banks as the 8086 memory is. The
selected by putting a jumper between two pins in the 8088 only has an 8-bit data bus. AD0-AD7. All of the
W27-W34 matrix shown in zone D3 (sheet 2) of the sche- memory devices and ports in an 8088 system are con-

808b SYSTEM CONNECTIONS, TIMING, AND TROUBtESHOOTING 207


nected onto these eight lines The 8088 memory then
: - 5 ~5 bytes. Fig-
ru ture This single bank struc-
ture means that ai - - - tnnot read a word from or
- e a -"to memory in one machine cycle as the
""

3086 ca - - - -iad or write bytes, so the


- - tys do 2 -.achine cycles to read or write a
rord. ^ re used with some decod-
select a desired byte in memory. The 8088 does
not produce the BHE signal, because it is not needed.
-

emory devices and LO devices


were designe I r 8-bit microprocessors which have
- - - ;s designed with an 8-bit
- .r."-r:ace more easily with 8-bit
and LO devices. For example, in an
% '-'.: -uctun
- - - "4-LS13S can be used for a port
decoder as we showed in Figure 7- 10a. An 8086
more complex decoder such as the
sheet 7 -,-?cause the decoder
.nto account the states of AO and BHE.

y z
X y. X
/—

J v /

f
J V

y y--^< y^-y
y
-. y
r
-. Read

208
8086 TIMING PARAMETERS

In previous sections ralized


timing. - in Figure 7-2. Th The edg
grams are sufficient to show the sequence of a<
on the 8086 buses. However, they are not
enough to determine, lor example, whether a memory
device is fast enough to work ii stem. To M IO. addre-~ -
allow you to make precise timing calculations, m; -

.detailed tin:
s for each mieroprc ss As we mentioned earlier, one
Complete timing information for the 8086 is contained
in the data sheet in the appendix Fig whether a particular memon
some of these for the 80S6 operating in minimum mode. rk a sys
. look at F:_ - remember the 5-minuie quern % .pie of how
freak-out rule. Most of the time there are only a very few . look in zone C5
se parameters that you need to worry about. In s. = is ins lied, the
- syst( - example, you don't need to worry
about the clock signal parameters, because an 3284 If jumper VV40 is installed e 8086
clock generator and a crystal will be used to produce the 2.43-MHz PCLK sig 3284
clock signal. The frequency of the cl - _ rom an you want to determine .

3284 is - %-third the resonant frequent- the SDK-S6 boaro

crystal connected to it. 7. - sig td to guaran- - .: you install jump - -


tee thecorrect clock period, clock time low. clock time
g as the correct suffix number part is - ou look uj

X X
BHE 5-
X X X
/

J V /

SE£ NOTE -

X /
J V
X X %c
X
-

- V
X
FICLRE 7-18 [continued)

209
EPROM in the appropriate data book. According to an address is already present on the address inputs of the
Intel data book, the 2716 has a maximum address to 2716, and the output buffers are already enabled, the
output access time, tAcc. of 450 ns. This means that if 2716 will put valid data on its outputs no later than 450
the 2716 is already enabled and its output buffers ns after the CE input is asserted low. A third parameter
turned on, it will put valid data on its outputs no more given for the 2716 in the data book is an output enable
than 450 ns after an address is applied to the address to output time, t0E, of 120 ns maximum. This means
inputs. The 2716 data sheet also gives a chip enable to that if the device already has an address on its address
output access time, t( f %of 450 ns. This means that if an inputs, and its CE input is already asserted, valid data

MINIMUM MODE (CONTINUED)

TCH1CH2 TCL2CL1

CLK (8284A OUTPUT)


nu?X_A^^rA

3HE/S7, A,9/S6 A,6 S,

WRITE CYCLE
(I. nil 1)
(RD. INTA,
DT R V0H)

AD1,,-AD1J

INTA CYCLE
(NOTES 1 & 3)

RD, WR - VOH)
BHE V ,, )

SOFTWARE HALT
RD, WR, INTA V0H
DT/R INDETERMINATE

NOTES:
1 All signals switch between V, IH and V, JL unless otherwise specified
RDY is sampled
2, RDY sampled near
near the
the end
end ofof T,.
T,. T3,
T3, Tw
Tw to determine
d if Tw machines states are to be inserted.
3, Two INTA cycles run back -to-back The 8086 LOCAL ADDR/DATA BUS is floating during both INTA cycles Control signals shown for second
INTA
INTA cycle,
cycle.
4. Signals at 8284A are shown for reference only
5 All liming measurements are made at 1,5 V unless otherwise noted

FIGURE 7-18 (continued)

210 CHAPTER SIVIN


MINIMUM COMPLEXITY SYSTEM TIMING REQUIREMENTS

8086 8086-1 (Pre nary) 8086-2 ii .


SYMBOL PARAMETER UNITS
! IONS
MIN. M A -. MIN. MAX. MIN MAX.

TCLCL CLK Cycle Period 200 Mill 100 500 1." 500 ns

TCLCH CLK Low Time 118 53 68 ns

TCHCL CLK High Time 69 39 44 ns

TCH1CH2 CLK Rise Time 10 10 10 ns From 1.0 V to 3.5 V

TCL2CL1 CLK Fall Time 10 10 10 ns From 3.5 V to 1.0 V

TDVCL Data hi Setup 1 ime 30 5 .'II ns

TCLDX Data in Hold Time 10 10 10 ns

RDY Setup Time into 8284A 35 35


TR1VCL 35 ns
(See Notes 1, 2)

RDY Hold Time into 8284A


TCLR1X 0 0 0 ns
(See Notes 1, 2)

TRYHCH READY Setup Time into 8086 118 53 68 ns

TCHRYX READY Hold Time into 8086 30 20 20 ns

READY Inactive lo CLK


TRYLCL -8 -10 -8 ns
(See Note 31

THVCH HOLD Setup Time 35 20 20 ns

INTR, NMI, TEST Setup Time


TINVCH 30 15 15 ns
(See Note 2)

TILIH Input Rise Time (Except CLK) 20 20 20 ns From 0.8 V to 2.0 V

TIHIL Input Fall Time (Except CLK) 12 12 12 ns From 2.0 V to 0.8 V

TCLAV Address Valid Delay 10 1 10 10 50 10 ill) ns

TCLAX Address Hold Time 10 10 111 ns

TCLAZ Address Float Delay TCLAX :-:u 10 40 TCLAX 50 ns

TLHLL ALE Width TCLCH-20 TCLCH-10 TCLCH-10 ns

TCLLH ALE Active Delay 80 40 50 ns

TCHLL ALE Inactive Delay 85 45 55 ns

TLLAX Address Hold Time to ALE Inactive TCHCL-10 TCHCL-10 TCHCL-10 ns

TCLD\ Data Valid Delay 10 110 10 50 10 60 ns

TCHDX Data Hold Time 10 in 10 ns

TWHDX Data Hold Time After WR TCLCH-30 FCLI H 25 TCLCH-30 ns


•CL=20 -100 pF
TCVCTV Control Active Delay 1 10 1 10 10 50 10 70 ns for all 8086 Outputs
(In addition to
TCHCTV Control Active Delay 2 10 110 10 45 10 60 ns
8086 self load)
TCVCTX Control Inactive Delay 10 110 10 50 10 70 ns

TAZRL Address Float to READ Active 0 0 0 ns

TCLRL RD Active Delay 10 165 10 70 10 100 ns

TCLRH RD Inactive Delay 10 150 10 60 10 80 ns

TRHAV RD Inactive to Next Address Active TCLCL-45 TCLCL 35 TCLCL-40 ns

TCLHAV HLDA Valid Delay 10 160 10 60 10 li ill ns

TRLRH RD Width 2TCLCL-75 2TCLCL-40 2TCLCL-50 ns

TWLWH WR Width Mi. i.( i i.n 2TCLCL-35 2TCLCL-40 ns

TAVAL Address Valid to ALE Low TCLCH 60 TCLCH-35 TCLCH 40 ns

TOLOH Output Rise Time 20 20 20 ns From 0.8 V to 2.0 V

TOHOL Output Fall Time 12 12 12 ns From 2 0 V to 0.8 V

NOTES.
1 . Signal at 8284A shown for reference only
2. Setup requirement for asynchronous signal only to guarantee recognition at next CLK.
3. Applies only to T2 state. (8 ns into T3)

(.)

FIGURE 7-18 (continued)

8086 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 211


will appear on the output pins at most 120 ns after the T, T2 T3
204 ns 204" ns 204 ns
OE pin is asserted low.
Now that you have these three parameters for the
2716. the next step is to check if each one of these times — — HH H-
is short enough for the device to work with a 4.9-MHz
8086. In other words, does the 2716 put out valid data
I 1 r
soon enough after it is addressed and enabled to satisfy TCLAV = 110 ns TDVCL = 30 ns
TPD74S373= 12 ns
the requirements of the 8086? To determine this you TIME AVAILABLE FOR 2716
need to look at both the 8086 timing parameters and ADDRESS ACCESS TIME =
612 ns- 152 ns = 460 ns
how the 2716 is addressed and enabled on the SDK-86
board.
To make it easier for you to find the important param-
eters for
these calculation, we show in Figure 7- 18b
a simplified version of the timing diagram in Figure T. T3
204" ns 204 ns
7- 18a. You should try to mentally do this simplification
whenever you are faced with a timing diagram. As
shown by the timing diagram in Figure 7- 18b the 8086
sends
machine
out M/IO. BHE, and an
cycle. Note on the AD15-AD0
address during Tl of the
line of the timing
i V1 1
t

165 n TPD3625 - 30 ns TDVCL =


diagram that the 8086 outputs this information within
a time labeled TCLAV after the falling edge of the clock at TIME AVAILA BLE FOR 2716
the start of Tl. TCLAV stands for time from clock low to toe = 408 ns - 225 ns= 183 ns

address valid. According to the data sheet shown in


lb)
Figure 7- 18c in the 8086 column, the maximum value of
this time is 1 10 ns. Now look further to the right on the FIGURE 7-19 Calculations of 8086 times available for
AD15-AD0 lines. You should see that valid data must 2716 EPROM access, (a) Time for rACC and tKD. (b) Time
arrive at the 8086 from memory a time TDVCL before for t, „
the falling edge of the clock at the end of T3. TDVCL
stands for time data must be valid before clock goes
low. The data sheet gives a value of 30 ns for this pa- ing section. As shown in Figure 7- 19a the time available
rameter. for tCE of the 2716 will be 460 ns. Since the maximum
The time between the end of the TCLAV interval (time (ce of the 2716 is 450 ns. you know that this parameter
clock low to address valid) and the start of the TDVCL is also acceptable for an SDK-86 operating with a 4.9-
interval is the time available for getting the address to MHz clock.
the memory, and for the tACC of the memory device. You The final parameter to check is £0e of the 2716. Ac-
can determine this time by subtracting TCLAV and cording
sheet
to 1 of the SDK-86 schematics, the OE
TDVCL from the time tor 3 clock cycles. With a 4.9-MHz signals for the 2716s are produced by the 3625 decoder.
clock each clock cycle will be 204 ns. Three clock cycles The signals coming to this decoder are A12-A19, M/IO,
then total 612 ns. Subtracting a TCLAV of 1 10 ns and a and RD. Look at the 8086 timing diagram in Figure
TDVCL of 30 ns leaves 472 ns available for getting the 7- 18b to see if you can determine which of these signals
address to the 2716 and for its tACC. To help you visual- arrives Jast at the 3625. You should fincHhat addresses
ize these times. Figure 7- 19a shows this operation in and M/IO are sent out during Tl, but RD is not sent out
simplified diagram form. until T2. As indicated by the arrow from the falling edge
If you look at sheets 1 and 3 of the SDK-86 schematics of the RD signal, RD going low causes the address de-
you should see that the BHE signal and the A0-A11 ad- coder
send
to an OE signal to the 2716 EROMs. Since
dress information goes from the 8086 through the RD is sent out so much later than addresses, it will be
74S373 latches to get to the 2716s. The propagation the limiting factor for timing. RD going low and the
delay of the 74S373s then must be subtracted from the EPROM returning valid data must occur within the time
472 ns to determine how much time is actually available of states T2 and T3. Now, according to the timing dia-
for the tAcc of the 2716. The maximum delay of a gram.isRDsent out from the 8086 within a time TCLRL
74S373 is 12 ns. As shown in Figure 7-19a, subtracting after the falling edge of the clock at the start of T2. From
this from the 472 ns leaves 460 ns for the t M , of the the data sheet the maximum value of TCLRL is 165 ns.
2716. Now, as we told you in a previous paragraph, the As we discussed before, the 8086 requires that valid
2716 has a maximum tACC of 450 ns. Since this 450 ns data arrive on AD0-AD15 from memory a time TDVCL
is less than the 460 ns available, you know that the tA( ( before the falling edge of the clock at the end of T3. The
of the 2716 is acceptable for the SDK-86 operating with minimum value of TDVCL from the data sheet is 30 ns.
a 4.9-MHz clock. You still, however, must check if the The time between the end of the TCLRL interval and the
values of tCE and tOE for the 2716 are acceptable. start of the TDVCL interval is the time available for the
If you look at sheet_l_of the SDK-86 schematics, you OE signal to get produced and for the OE signal to turn
should see that the CE inputs of the 2716s are con- on the memory. To determine the actual time available
nected
either
to AO or to BHE. The timing for these sig- for these operations, first compute the time for states T2
nalsthe
is same as that for the addresses in the preced- and T3. For a 4.9-MHz clock each clock cycle or state will

212 CHAPTER SEVEN


be 204 us. so the two together total 408 ns. Then sub ibis book will describe bow the prototype ol a
tract the TCLRL of 165 us and the TDVCL of 30 ns As microproccssoi based instrument is developed.
shown by the simple diagram in Figure 7- 19b. this The following sections describe a series ol steps thai
leaves 213 ns available lor the decoder delay and the f,i> we have found effective in troubleshooting various mi
ol the 271b. (.'becking a data sheet lor the 3625 would crocomputer systems. The first point to impress on youi
show you that it has a maximum CS2 to output delay oi mind about troubleshooting a microcomputer is that a
30 ns. Subtract this from the available 213 ns to see systematic approach is almost always more effective
bow much time is left lor the (,n ol the 2716. The result than random poking, probing, and hoping. You don't,
of this subtraction is 1H3 ns As we indicated in a previ- for example, want to spend 2 hours troubleshooting a
ous paragraph, the 2716 has a maximum t()K of 120 ns. system and finally find thai the only problem is thai tin-
Since this time is considerably less than the 183 ns power supply is putting out only 3 V instead of 5 V. Use
available, the 2716 has an acceptable (,,,. value for oper- the list of steps below or a list ol your own each time you
ating the
on SDK-86 board with a 4.9-MHz clock. have to troubleshoot a microcomputer.
You have now checked all three 2716 parameters and
found that all three are acceptable for an SDK-86 operat-
ing ona 4.9-MHz clock. No wait states need to be in- 1. Identifying the Symptoms
serted when
these devices are accessed, so jumper VV39
Make a list of the symptoms that you find or those that a
in zone D7 on sheet 2 of the schematics can be left out.
customer describes to you. Find out, for example,
As discussed in a previous section, installing jumper
whether the symptom is present immediately or
W39 will cause the selected number of WAIT states to be
whether the system must operate for a while before it
inserted for all memory or I/O operations.
shows up. If someone else describes the symptoms to
Here's a final point about calculating the time avail- you, check them yourself, or have that person demon-
able for
tACC. £CE. and tOE of some device in a system. stratesymptoms
the to you. This allows you to check if
Suppose that you want to add another pair of 2716 the problem is with the machine or with how the person
EPROMs in the prototyping area of the SDK-86 board,
is attempting to use the machine.
and you want to enable the outputs of these added de-
vices with
the 03 output of the 3625 ROM decoder on
sheet 1 of the schematics. The timing for these added
2. Making a Careful Visual and Tactile
devices will be the same as for the previously discussed
Inspection
2716s except that the data from the added devices must
This step is good for preventive maintenance as well for
come back through the 8286 buffers shown on sheet 4
finding a current problem. Check for components that
of the SDK-86 schematics. According to an 8286 data
sheet, these buffers have a maximum delay of 30 ns.
have been or are excesively hot. When touching compo-
nents
seetoif any are too hot, do it gently, because a bad
This 30 ns must be subtracted from the times available
IC can get hot enough to give a nasty burn if you keep
for rACC. tCE. and ton- If you look back at our calculations
of the time available for tACc in Figure 7- 19a, for exam-
your finger on it too long.
ple, youwill see that we ended up with 460 ns available
Check to see that all ICs are firmly seated in their

for rACC. Subtracting the 30 ns of buffer delay from this sockets and that the ICs have no bent pins. Vibration

leaves only 430 ns. which is considerably less than the can cause ICs to work loose in their sockets. A bent pin

maximum tACC of 450 ns for the 2716. This tells you may make contact for a while, but after heating, cooling,

that, because of the buffer delay, the added 2716s are and vibration, it may no longer make contact. Also, in-

not fast enough to operate on an SDK-86 board with a expensive


socketsIC may oxidize with age and no longer

4.9-MHz clock and no WAIT states. To take care of this make good contact.

problem, the SDK-86 is designed so that any access to a Check for broken wires and loose connectors. A thin
memory or I/O device "off board'' will cause the selected film of dust. etc. may form on printed circuit board edge
number of WAIT states to be inserted in the machine connectors and prevent them from making dependable
cycle. For our example here, selecting one WAIT state contact. The film can be removed by gently rubbing the
with jumper W28 on sheet 2 will give another 204 ns for edge connector fingers with a clean, nonabrasive pencil
the data to get from the 27 16s to the 8086. This is more eraser. If the microcomputer has ribbon cables, check to
than enough time to compensate for the buffer delay, so see if they have been moved around or stressed. Ribbon
the added 2716s will work correctly. cables usually have small wires that are easily broken. If
you suspect a broken conductor in a ribbon cable, you
can later make an electrical check to verify your suspi-
TROUBLESHOOTING A SIMPLE 8086- cions.
BASED MICROCOMPUTER

Now that you have some knowledge of the software and 3. Checking the Power Supply
the hardware of a microcomputer system, we can start From the manual for the microcomputer determine the
teaching you how to troubleshoot a simple microcom- power supply voltages. Check the supply voltage(s) di-
puter system
such as an SDK-86 board. For this section rectly
theon appropriate pins of some ICs to make sure
assume that the microcomputer or microprocessor- the voltage is actually getting there. Check with a scope
based instrument previously worked. Later sections of to make sure the power supplies do not have excessive

SYSTEM CONNECTIONS, TIMING, AND TROUBEESHOOTING 213


noise or ripple. One microcomputer that we were called the CPU from the bad system, then the CPU is probably
on to troubleshoot had very strange symptoms caused bad. Remove it from the good system and bend the pins
by 2-V peak-to-peak ripple on the 5-V supply. so that you know it is bad. If the CPU seems bad. you
can try replacing it with the CPU you removed from the
good system. If you do this, however, it is important to
4. Signal Roll Call keep track of which IC came from where. To do this we
like to mark each IC from the good system with a wide-
The next step is to make a quick check of some key sig-
tip, water-soluble marking pen. We can then rebuild the
nals aroundthe CPU of the microcomputer. If the prob-
good system by simply putting back all the marked ICs.
lemaisbad IC, this can help point you toward the one
The marks on the ICs can easily be removed with a damp
that is bad. First, check if the clock signal is present and
cloth.
at the right frequency. If not. perhaps the clock genera-
The procedure from here on is to keep testing ICs from
tor ICis bad. If the microcomputer has a clock, but
the bad system until you find all of the bad ICs. Make
doesn't seem to be doing anything, use an oscilloscope
sure to turn the power off before you remove or insert
to check if the CPU is putting out control signals such as
any ICs. Be aware that more than one IC may be bad. It
RD, WR. and ALE. Also, check the least-significant data
is not unusual, for example, that an AC power-line surge
bus line to see if there is any activity on the buses. If
will wipe out several devices in a system. We usually
there is no activity on these lines, a common cause is
work our way out from the CPU to address latches, buff-
that the CPU is stuck in a wait, hold, halt, or reset con-
ers, decoders, and memory devices. Often the specific
dition
theby failure of some TTL devices. To check this
symptoms point you to the problem group of ICs with-
out, use the manual to help you predict what logic level
out yourhaving to test every IC in the system. If, for
should be on each of the CPU input control signals for
example, the system accesses ROM, but doesn't access
normal operation. The RDY input of the 8086, for exam-
FtAM, suspect the FtAM decoder. If a system uses buffers
ple, shouldbe high for normal operation. If an external
on the buses, suspect these devices. Buffers are high-
logic gate fails and holds RDY low. the 8086 will go on
current devices and thev often fail.
inserting WAIT states forever, and the buses will be held
constant. If the 8086 HOLD input is held high or the RST
input is held high, the 8086 buses will be floating. Con-
necting
scopea probe to these lines will pull them to 6. Troubleshooting a System with Soldered-in
ground, so you will see them as lows. ICs
If there is activity on the buses, use an oscilloscope to
The approach described in the preceding paragraphs
see if the CPU is putting out control signals such as RD
works well if the system ICs are all in sockets and you
and WR. Also check with your oscilloscope to see if select
have two identical systems. However, since sockets add
signals are being generated on the outputs of the ROM.
to the cost and unreliability of a system, many small sys-
RAM, and port decoders as the system attempts to run
tems put only the CPU and ROMs in sockets. This
its monitor or basic program. If no select signals are
makes your troubleshooting work harder, but not im-
being produced, then the address decoder may be bad or
possible.
the CPU may not be sending out the correct addresses.
Again, if you have two identical systems, one that
After a little practice you should be able to work
works and one that doesn't work, you can attempt to
through the previously described steps quite quickly. If
run the monitor or basic system program on each and
you have not located the problem at this point, the next
compare signals on the two. A missing or wrong signal
step for a system with its ICs in sockets is to systemati-
may point you to the bad IC or ICs.
cally substituteknown good ICs for those in the non-
If the system works enough to read some instructions
working system.
from ROM and execute them, you can replace the moni-
tor orbasic system ROM with one that contains diag-
nostic programswhich test FIAM and I/O devices. A ¥U\M
5. Systematically Substituting ICs test routine, for example, might attempt to write all l's
The rosiest case of substitution is that where you have to each FIAM location, and then read the memory loca-
two identical microcomputers, one that works and one tionsee
to if the the data was written correctly to that
that doesn't, and the ICs of both units are in sockets. location. If the data read back is not correct, the diag-
For this case you can use the working system to test the nostic programcan stop and in some way indicate the
ICs from the nonworking system. The trick here is to do address that it could not write to. If a write of all l's is
this in such a way that you don't end up with two sys- successful, then the test routine will try to write all O's to
tems that
do not work! Here's how you do it. each memory location. A port test routine might initial-
First of all. DO NOT REMOVE OR INSERT ANY ICs izeport
a for output, and then write alternating l's and
WITH THE POWER ON! Now. with the power off. remove O's to the port over and over again. With an oscilloscope
the CPU from the good system and put it in a piece of you can then see if the port device is getting enabled and
conductive foam. Plug the CPU from the bad system into if the data is getting to the output of the port device.
the now empty socket on the good board and turn on the Another port test routine might try to read a byte of data
power. If the good system still works, then probably the in from a port over and over so that you can again see if
CP1 1 is good. Turn off the power and put the CPU back in the device is getting enabled and if the data is getting
the bad system. If the good system does not work with through the device to the system data bus. The tech-

214 CHAPTER SFVtN


nique ol using program routines to test hardware is a
very Important one thai you will use many tunes when
you .uc working with microcomputer systems.
Now. suppose thai you have localized the problem to a
few K's that are soldered in. II the problem is one thai
occurs when the unit gets hot, you might hv spraying
some IT eon (-old spray on the ICs, one at a time, to see il
you can determine which one has a problem. II ihis does
not find the bad [C or the problem is not heal related,
what you do next Is to replace these K's one ai a time
until the system works correctly. The point we want to
stress here is that cost of these few K's is probably much
less thai the cost of the time ii would take you to deter
mine just which IC is bad. il you do not have specialized
test equipment.
To remove an IC from a printed circuit board. DO NOT
attempt to desolder pins with a handheld solder
"sharper." Modern multilayer printed circuit boards are
quite fragile, and these tools can slip and knock a trace
FIGURE 7-20 Tektronix 518 logic analyzer. (Copyright
right off the board. Instead, use cutters with narrow tips
1983, Tektronix Inc.)
to cut all the leads of the IC next to the body. Since you
are going to throw it out anyway, you don't care if you
destroy the IC. With the body of the IC out of the way.
you can then gently heat each pin individually and use internal EvAM. Different analyzers store between 256
needle nose pliers to remove it from the PC board. If the and 1024 samples for each input channel. A clock signal
hole fills with solder, heat it gently and insert a small tells the analyzer how often to take samples. As shown
wooden toothpick until the solder cools. After you re- by the block diagram in Figure 7-21. an internally pro-
place each
IC, power up the system and see if it now duced signal
or some external signal can be used to
works. clock the analyzer. If you are using an analyzer to look at
The techniques described in the preceding sections 8086 address and data lines, for example, you could use
will enable you to troubleshoot many microcomputer ALE as a clock signal. The analyzer will then take a sam-
systems with a minimum of test equipment. However, ple eachtime the 8086 puts out an address and pulses
specialized test equipment is available to speed up the ALE. The samples stored in the analyzer memory will
process and help find complex problems. The following then represent the sequence of addresses output by the
sections describe two of these instruments. 8086 after some specified trigger. As another example,
you could clock the analyzer on RD from an 8086. After a
specified trigger the analyzer will take a sample each
time the 8086 does a read operation. In this case the
7. Using a Logic Analyzer to Troubleshoot a samples stored in the analyzer memory will represent
Microcomputer System the sequence of data words read in from memory or from
A logic analyzer is an instrument which allows you to ports.
see the signals on 16 to 64 signal lines at once. With a To make precise timing measurements with an ana-
logic analyzer you can. for example, see the signals on lyzer
clock
a signal from an internal, crystal-controlled
the address bus, data bus, and control bus of a micro- oscillator is used. In this case the analyzer will take a
computer.7-20
Figureshows a picture of a relatively sample each time a pulse from the internal clock oscilla-
low-cost logic analyzer, the Tektronix 318. Instruments tor occurs.If, for example, you choose an internal clock
such as this are themselves controlled by internal mi- frequency of 50 MHz, the analyzer will take a sample
croprocessors.
clipleads
Smallplug into a pod shown at every 20 ns.
the bottom of the drawing to get parallel data signals If the analyzer is receiving either an internal or an ex-
into the analyzer. The model shown only has 16 parallel ternal clock,
it will be continuously taking samples of
data inputs. In addition, a scope-type probe can be used the input data and storing these samples in the internal
to send in serial data such as that sent out from a UART E^AM. A trigger signal tells the analyzer when to display
to a modem. the samples stored in the EiAM. As shown by the block
Figure 7-21 shows a functional block diagram of a diagram in Figure 7-21 some external signal can be used
simple logic analyzer. Since logic analyzers are used to to trigger the analyzer, or the trigger signal can come
detect and display only Is and 0's, a comparator is put from a word recognizer in the analyzer. A word recog-
on each input. The reference input of the comparator is nizer comparesthe binary word on the input signal
set for the logic threshold of the devices in the system. lines with a word you set with switches or a keyboard.
The signals out of the comparators to the rest of the When the two words match, the word recognizer sends
analyzer are then clear-cut Is or 0's. out a trigger signal.
The analyzer takes "snapshots" of the logic levels on Since the analyzer is continuously taking samples,
each of the data inputs and stores these samples in an you can set the analyzer for a pretrigger display, a center

8086 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 215


INTERNAL ASYNCHRONOUS CLOCK INPUT

EXTERNAL CLOCK INPUT


L>
ADJUSTABLE
DISPLAY
THRESHOLD CRT
SCAN
COMPARATORS DISPLAY
, CIRCUIT

6
WORD
COMPARATOR
AND
TRIGGER WORD TRIGGER
SELECTION CIRCUITRY
SWITCHES

EXTERNAL TRIGGER INPUT

FIGURE 7-21 Logic analyzer block diagram.

trigger display, or a posttrigger display. For an analyzer clock source. In this case the analyzer is said to be oper-
that displays 256 samples, pretrigger means that the atingsynchronous
in mode. For precise timing meas-
display will show the 256 samples that were taken |iist urements
internal,
an crystal controlled clock source is
before the trigger occurred. For center trigger mode, 128 used. The group of samples that are actually displayed
samples taken before the trigger and 128 samples taken on the screen is determined by a trigger signal. The trig-
after the trigger will be displayed. Posttrigger mode ger signalmay come from some external source, or it
means that the analyzer will take 256 more samples may be produced by a word recognizer when it finds a
after the trigger and display them. specified data word on the parallel signal lines. Now that
Figure 7-22 shows some of the formats in which a you have an overview of how a logic analyzer works,
logic analyzer can display the samples stored in its RAM. here's a few hints on how to use one for troubleshooting
The series of displayed data samples is often called a an 8086 microcomputer.
trace. The timing diagram format in Figure 7-22a is Connect the analyzer data inputs to the address and
most useful when making time measurements with an data bus lines from the CPU. For an 8086, connect the
internal clock. A binary listing such as that in Figure external clock input of the analyzer to the 8086 ALE pin.
7-22b is useful for seeing the actual pattern of l's and Look at an 8086 timing diagram such as the one in Fig-
O's on signal lines, but a hexadecimal listing such as ure 7-2
to see at which edge of the ALE signal valid ad-
that in Figure 7-22c makes it easier to recognize if a dresses
present
are on the buses. Set the analyzer to
microcomputer is putting out addresses in the right clock on this edge. Set the analyzer to trigger on address
sequence. FFFFOH. the first address output by the 8086 after a
Some analyzers, such as the Tektronix 318, allow you reset. Set the analyzer display format for posttrigger dis-
take a series of samples from a functioning system, play. Tell
the analyzer to do a trace and press the 8086
store these samples in a second memory in the analyzer, system reset button. The display on the analyzer should
and then compare these samples with a series of sam- show you the sequence of addresses output after a reset.
ples takenfrom a nonfunctioning system. We have If you have one. use the system monitor listing to see if
found this feature quite helpful in troubleshooting mal- the displayed sequence is correct. If the sequence is not
functioning instruments
which have poor documenta- correct, look for address bits that should change, but
tion. don't. The cause of this problem may be the CPU or an
As we mentioned previously, the 318 can also be used address buffer. A common failure mode for buffers is
to display a sequence of serial data as shown in Figure that an input or an output will short to V,( or to ground.
7-22c. Note that in this format the analyzer shows the This prevents that line from changing.
binary, hexadecimal, and the equivalent ASCII code for If the address sequence seems reasonable, connect
each of the data bytes taken in. the analyzer external clock input to the 8086 RD pin. Set
To summarize then, a logic analyzer takes samples of the analyzer to clock on the positive edge of this signal.
the signals present on its data inputs each time a clock Set the format for posttrigger display. Tell the analyzer
pulse occurs and stores these samples in an internal to do a trace and push the system reset button. The dis-
RAM. A system signal such as ALE may be used as a play the
on analyzer should show the data transferred

216 ( HAI'IIK SEVEN


.

| il w rana clk> i«-."^ !•• I


hfl.-MSI LGC =

[% H3
ai G2 C3 G4
03 a SI IB
i^Hr 1 1 1 1 001 10- -033- -FF- 663
1 1 1 1 DOM 1 033 ^F 127
£ 1 1 1001 1 1 033 3F 127
3 1110 0 110 0 33 3F 063
4 1 1 1 00 1 10 033 3F 063
5 1 1 10O1O1 0 23 FF 255
£ 1110 0 1 0 1 023 FF 255
T 7 111001 00 02 3 FF 191
& 1 1 1 00 100 023 FF 191
Si 1 1 1 O 0 1 0 1 023 3F 255
1 0 11100101 023 3F 255
1 1 11100100 ©23 3F 191
1 2 1 1 100100 623 3F 191
cuR-e <T -7M>

We obviously can't describe here all of the ways to use


a logic analyzer. If you have one, consult the manual for
it to learn some of the finer points of its use. Also, the
lab manual that is available for use with this book has
20--00 l 00000-- some exercises to help you gain more skill with an ana-
lyzer. The
point here was to show you how to use the
***V&# 0123456789O*
THIS SERIAL ANALYZER analyzer as a "window'' into what's going on in a system.
FUNCTION ENABLES YOIL By carefully choosing what signals you look at. what sig-
TO ShMPLE I'ATA ASYNC7 nal you
clock on. and what word you trigger on, you can
OR SYNC UP TO 19200 often solve difficult problems. For this reason, a logic
1 O© BITS-SEC. I'ATA INPUT
12 0 CAN EE 5 TO 8 BITS/ analyzer is a valuable tool when developing a new
1 40 CHARACTER TRIGGERS microcomputer-based product. However, it is important
160 CAN BE INTERNAL OR for you to have a perspective of when to use an analyzer
1 30 EXTERNAL THRESHOLDS
200 ARE SELECTABLE FROM in troubleshooting simple systems that previously
220 &f TO -10.GU AND TTL. worked. Most of the time you can use the techniques
240 *>< 98765432 10#»*
CUR-6
described in previous sections to find and fix a problem
in less time than it would take you to connect up the
logic analyzer and figure out the trace display. If you
have an analyzer, however, don't hesitate to use it when
FIGURE 7-22 Logic analyzer display formats, (a) Parallel
the simple techniques don't seem to be getting you any-
timing display, (b) Parallel state display, (c) Serial data
where.
display. (Tektronix Inc.)

on ADO-AD 15. Again, use the monitor program listing to


see if instruction bytes are coming in correctly. To help 8. Other Microcomputer Troubleshooting
with this, some analyzers allow you to display the in- Equipment
struction mnemonic
that corresponds to the bytes read A logic analyzer is a very powerful troubleshooting tool,
in. If the data sequence is not correct, again check for but to use it effectively you need some detailed knowl-
stuck bits. edge and
a program listing for the system that you are
Another important logic analyzer feature you should trying to troubleshoot. If you are working as a repair
learn to use is the clock qualifier input. If you switch on technician and have to repair several different types of
this input, the analyzer will only accept clock signals microcomputer systems with poor documentation to
when a specified logic level is present on it. You can use work from, most analyzers then are not too useful. To
the clock qualifier input to, for example, do a trace of make your life easier in this case, "smart" instruments
only data read from ports. To do this in an 8086 mini- such as the Fluke 9010A microsystem troubleshooter
mum modesystem, you connect the data inputs to the have been created.
data bus. the RD signal to the analyzer clock input, and As you can see from the picture of the 90 1 OA in Figure
the 8086 M/IO signal to the anafyzer clock qualifier 7-23, it has a keyboard, a display, and an "umbilical
input. You set the clock qualifier input to respond to a cable with an IC plug on the end The unit also contains
low. The analyzer will then take samples only when RD a minicasette tape recorder. For troubleshooting, the
pulses and M/IO are low, as they will be during reads 9010A is used as follows.
from ports. The microprocessor in a fully functioning unit is re-

8086 SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 217


i 11 n' II l till t. V-U«-4t
i H i [ II H II i t4t
I II I Slfiil'lB

FIGURE 7-23 Fluke 9010A microsystem troubleshooter. ( h>hn Fluke Mfg Co . Ini )

moved, and the plug at the end of the cable is inserted in Pin functions of 8086: _
its place. The learn function of the 9010A is then exe- V,,. RD. WR, CLK, ALE. M/IO, LOCK. MN/MX,
cuted. This
function finds and maps ROM. RAM. and RESET. NMI, 1NTR, BHE, DEN, DT/R
I/O registers that can be written into and read from. It 8086 RESET response
also computes signatures (checksums) for blocks of
Maximum and minimum mode of 8086
ROM. All of these parameters are stored in the 9010A's
RAM and/or on a minicassette tape. The microprocessor 8086 timing diagram interpretation
on a malfunctioning unit is then removed and the plug State, instruction cycle, machine cycle, wait state,
at the end of the umbilical cable inserted in its place. An READY signal
automatic test function is then executed. In this mode
Bus activities during read/write
the 9010A tests the buses, RAM, ROM. ports, power
Bidirectional buffer
supply, and clock on the malfunctioning system. Any
problem found, such as stuck nodes or adjacent trace General functions: 3625. 8284, 8255A, 825 1A, 8279.
short-circuits, is indicated on the display. The results of 2716, 2142
this test give some good hints as to the source of the SDK-86 schematic: zones, plugs, jacks, wire wraps,
problem. Because of its built-in intelligence, the 9010A
resistor packs
can be programmed to do other tests as well.
Address decoding: ROM decoding. RAM decoding.
The point of an instrument such as the 9010A is that
port decoding
with it you do not have to be intimately familiar with the
programming language and hardware details of a simple Memory-mapped I/O
microcomputer system in order to troubleshoot it. Direct I/O

8086, 8088 memory banks


Timing parameters: tACC, tCL, tOE, t(F. TCLAV, TCLRL,
IMPORTANT TERMS AND CONCEPTS TDVCL
FROM THIS CHAPTER
8086 typical clock frequencies
II you do not remember any of the terms or concepts in Troubleshooting steps for a simple 8086-based
the following list, use the index to find them in the microcomputer
chapter. Logic analyzer: clock signal, trigger, trace

218 l HAPTER S| VfN


REVIEW QUESTIONS AND PROBLEMS
1. From what point on the clock waveform is the start 19. Describe the purpose ol the many small capacitors
ol .in 8086 state measured? connected between V, , and ground on microcom-
puter
inted
pi circuit hoards.
2. Why are latches required on the ADO AD15 bus in
an 8086 system? 20. A 74LS138 decodei has its three SELECT inputs
connected to A12, A13. and Ah) ol the system ad
3. What is the purpose of the ALE signal in .in 8086 dress bus. It has G2A connected to A15, ( .".'.I', con
system? nected to RD. and Gl connected to t 5 V. Use an
address decoder worksheet to determine what
4. Describe the sequence ol events on the 8086 data
eight ROM address blocks the decoder outputs will
address bus. the AI.K line, the M/IO line, and the
select. Whv is RD used as one of the enables on a
RD line as the 8086 fetches an instruction word.
ROM decoder?
5. What logic levels will be on the 8086 RD. WR, and
21. Show a memory map for the ROMs in Problem 20.
M/IO lines when the 8086 is doing a write to a
memory' location? A read from a port? 22. Use an address decoder worksheet to help you draw
6. What is the major difference between an 8086 oper- a circuit to show how another 74LS138 can be con-
atingminimum
in mode and an 8086 operating in nected
select
to one ol eight 1 Kbyte RAMs starting
maximum mode? at address 8000H.

7. Describe the response an 8086 will make when its 23. Why are there actually many addresses that will se-
RESET (RST) input is asserted high. lect one
of the port devices connected to the port
decoder in Figure 7- 10a.
8. Why are buffers often needed on the address, data,
24. Describe memory-mapped I/O and direct I/O. Give
and control buses in a microcomputer system?
the main advantage and main disadvantage of
9. a. How is an 8086 entered into a WAIT state? each.
b. At what point in a machine cycle does an 8086
25. a. Why is the 8086 memory set up as two byte-
enter a WAIT state?
wide banks?
c. What information is on the buses during a
b. What logic levels would you find on BHE and
WAIT state?
A0 when an 8086 is writing a byte to address
d. How long is a WAIT state?
04274H? Writing a word to 04274H?
e. How many WAIT states can be inserted?
c. Describe the 8086 bus operations required to
/. Why would you want the 8086 to insert a WAIT
write a word to address 04373H.
state?
26. How does the circuitry on the SDK-86 make sure
10. What are the functions of the 8086 DT/R and DEN
that you cannot accidentally write a byte or word to
signals?
ROM?
11. What does an arrow going from a transition on one
27. Why is some ROM put at the top of the address
signal waveform to a transition on another tell
space in an 8086 system?
you?
28. a. Show the truth table you would use for a 3625
12. How are wire wrap jumpers indicated on a sche-
PROM decoder to produce CS1 signals for
matic?
4K > 8 RAMs in an 8086 system. Assume the
13. What is the meaning of /8 on a signal line on a sche- first RAM starts at address 00000H. Don't for-
matic? get A0and BHE.
b. Draw the circuit connections for the 3625 de-
14. Describe the two purposes of address decoders in
coder PROM
and for two of the 4K x 8 RAMs.
microcomputer systems.
29. Use sheets 5 and 7 of the SDK-86 schematics to
15. A memory device has 15 address lines connected to
help you determine for the SDK-86 what logic levels
it and 8 data outputs. What size words and how
will be on BHE. A0-A 19. M/IO. RD. and WR when a
many words does the device store?
word is read from ports FFF8H and FFF9H. Are
16. Briefly describe the function of the 8255. 8251 A, these ports memory-mapped or direct? What in-
and 8279 devices in the SDK-86 microcomputer struction(s) would you use to do this read opera-

system. tion'?

17. A group of signal lines on a schematic have the 30. a. How is the OFF BOARD signal produced on the
label 2ZB3 next to them. What is the meaning of SDK-86 board?
this label? b. Describe the purpose of the OFF BOARD sig-
nal
18. What is the difference between a connector identi-
fied with a "J" and a connector identified with a Describe how the 8088 memory is configured. Why
••p-? doesn't the 8088 need a BHE signal?

SYSTEM CONNECTIONS, TIMING, AND TROUBLESHOOTING 219


32. By referring to the 8086 timing diagrams in Figure 39. Describe the symptoms that an SDK-86 would
7-l.Sn and parameters in Figure 7- 18c determine show for each of the following problems.
for the 8086-2: a. Pin 8 of A 15 in zone D5 of schematic sheet 2 is

a. The maximum clock frequency. stuck low.

b. The time between CLOCK going low and RD b. The reset key is stuck on.

going low. c. None of the outputs of XA29 in zone D7 of


c. The time for which memory must hold data on schematic sheet 6 ever goes low.
the data bus after CLOCK goes low at the start d. Pin 6 of A3 in zone A5 of schematic sheet 5 is
of T4. stuck low.
d. The time that the lower 16 address bits remain
40. Draw a block diagram of a simple logic analyzer and
on the data bus after ALE goes low.
briefly describe how it operates. Include in your
33. The 27128-25 is a 16K % 8 EPROM with a tAI , of answer the function of the clock and the function
250 ns maximum, a (< K of 250 ns maximum, and a of the trigger.
tOE of 100 ns maximum. Will this device work cor-
41. What do you use for a logic analyzer clock when you
rectly withoutWAIT states in an 8-MHz 8086-2 sys-
want to make detailed timing measurements.
tem withcircuit connections such as those in the
SDK-86 schematics? Assume the address latches 42. On what signal and what edge of that signal would
have a propagation delay of 12 ns and the decoder you clock a logic analyzer and on what word would
has a delay of 30 ns. you trigger to see in an 8086 system:
a. The sequence of addresses output after a
34. List the major steps you would take to troubleshoot
RESET?
a microcomputer system such as the SDK-86
b. The sequence of instructions read in after a
which previously worked. Assume all ICs are in
RESET? (Assume the first instruction word is
sockets.
FALL)
35. Why is it important to check power supplies with c. Both the addresses sent out and the words

an oscilloscope? read in?


d. Most logic analyzers have a clock qualifier
36. Describe how you can keep from mixing up ICs
input. If this input is used, the logic analyzer
from a good system with those from a bad system
will not respond to a clock signal unless a spec-
when substituting.
ified logic
level is on the qualifier input. You
37. Write an 8086 routine to test the system RAM in might, for example, connect the M/IO to the
addresses 00200H-07FFH. clock qualifier input and set it for a high to see
a trace of data read from memory. What clock
38. Write a test routine to output alternating l's and qualifier would you use to see a trace of only
0's to port FFFAH over and over. With this routine data read in from ports?
running you could check with an oscilloscope to
see if the port device is getting enabled and is out- 43. How is it possible for a logic analyzer to display data
putting data. that occurred before the trigger?

220 CHAPTER SFVEN


CHAPTER

Interrupts and Interrupt


Service Procedures

Most microprocessors allow normal program execution The third source of an interrupt is from some condi-
to be interrupted by some external signal or by a special tion produced in the 8086 by the execution of an
instruction in the program. When a microprocessor is instruction. An example of this is the divide by zero
interrupted, it stops executing its current program and interrupt. Program execution will automatically be
calls a procedure which "services" the interrupt. At the interrupted if you attempt to divide an operand by zero.
end of the interrupt service procedure, execution is usu- Conditional interrupts such as this are also referred to
ally returnedto the interrupted program. This chapter as software interrupts.
shows you how the 8086 family members respond to At the end of each instruction cycle the 8086 checks to
interrupts, how to write interrupt service procedures, see if any interrupts have been requested. If an inter-
and how interrupts are used in a variety of applications. rupt has
been requested, the 8086 responds to the in-
terrupt
stepping
by through the following series of
major actions.
OBJECTIVES
1. It decrements the stack pointer by two and pushes
At the conclusion of this chapter you should be able to: the flag register on the stack.

2. It disables the INTR interrupt input by clearing the


1. Describe the interrupt response of an 8086 family
interrupt flag in the Hag register.
processor.
3. It resets the trap flag in the flag register.
2. Initialize an 8086 interrupt vector (pointer) table.
4. It decrements the stack pointer by two and pushes
3. Write interrupt service procedures. the current code segment register contents on the
4. Describe the operation of an 8254 programmable stack.

counter/timer and write the instructions necessary


5. It decrements the stack pointer again by two and
to initialize an 8254 for a specified application.
pushes the current instruction pointer contents on
5. Describe the operation of an 8259A priority inter- the stack.
rupt controller and write the instructions needed to
6. It does an indirect far jump to the start of the proce-
initialize an 8259A for a specified application.
dure you
wrote to respond to the interrupt.

To summarize these steps, then, the 8086 pushes the


8086 INTERRUPTS AND INTERRUPT flag register on the stack, disables the single step and
RESPONSES the INTR input, and does essentially an indirect far call
to the interrupt service procedure. Figure 8-1 shows
Overview
this in diagram form. Note that an IRET instruction at
An 8086 interrupt can come from any one of three the end of the interrupt service procedure returns exe-
sources. One source is from an external signal applied to cution
the to main program.
the nonmaskable interrupt (NMI) input pin, or the in- Now remember from Chapter 5 that when the 8086
terrupt
INTR)I input pin. An interrupt caused by a signal does a far call to a procedure, it puts a new value in the
applied to one of these inputs is referred to as a hard- code segment register and a new value in the instruc-
ware interrupt. tion pointer.For an indirect call the 8086 gets the new
A second source of an interrupt is execution of the values for CS and IP from four memory addresses. Like-
interrupt instruction. INT. This is referred to as a soft- wise, when
it responds to an interrupt the 8086 goes to
ware interrupt. memory locations to get the CS and IP values for the

221
MAINLINE INTERRUPT specified register or memory location. The 8-bit result
PRI II |R M SERVICE (quotient) from this division will be left in the AL regis-
PROCE DURE
PUSH FLAGS ter. The
8-bit remainder will be left in the AH register.
PUSH REGISTERS
CLEAR IF ^^" The DIV instruction also allows you to divide a 32-bit
CLEAR TF ^^^
PUSH CS unsigned binary number in DX and AX by a 16-bit num-
PUSH IP
ber in
a specified register or memory location. The
FETCH ISR ADDRESS
16-bit quotient from this division is left in the AX regis-
pi ter, and
the 16-bit remainder is left in the DX register.
^\ POP IP The 8086 IDIV instruction, in the same manner, allows
^ POPCS ,_

you to divide a 16-bit signed number in AX by an 8-bit


POP FLAGS
^\ POP REGISTERS
IRET signed number in a specified register, or a 32-bit signed
number in DX and AX by a 16-bit signed number from a
FIGURE 8-1 8086 interrupt response. specified register or memory location.
If the quotient from dividing a 16-bit number is too
start of the interrupt service procedure. In an 8086 sys- large to fit in AL or the quotient from dividing a 32-bit
tem thefirst 1 Kbyte of memory from 00000H to 003FFH number is too large to fit in AX, the result of the division
is set aside as a table for storing the starting addresses will be meaningless. A special case of this is where an
of interrupt service procedures. Since 4 bytes are re- attempt is made to divide a 32-bit number or a 16-bit
quired
store
to the CS and IP values for each interrupt number by zero. The result of dividing by zero is infinity
service procedure, the table can hold the starting ad- (actually undefined), which is somewhat too large to fit
dresses
up for
to 256 interrupt procedures. The starting in AX or AL. Whenever the quotient from a DIV or IDIV
address of an interrupt service procedure stored in this operation is too large to fit in the result register, the
table is often called the interrupt vector or the interrupt 8086 will do a type 0 interrupt.
pointer, and the table itself is then referred to as the The type 0 response proceeds as follows. The 8086
interrupt vector table or the interrupt pointer table. first decrements the stack pointer by two and copies the
Figure 8-2 shows how the 256 interrupt pointers are flag register to the stack. It then clears the IF and the TF.
arranged in the memory table. Each doubleword inter- Next it saves the return address on the stack. To do this
rupt pointeris identified by a number from 0 to 255. the 8086 decrements the stack pointer by two, pushes
Intel calls this number the type of the interrupt. The the CS value of the return address on the stack, decre-
lowest five types are dedicated to specific interrupts mentsstack
the pointer by two again, and pushes the IP
such as the divide by zero interrupt and the nonmask- value of the return address on the stack. The 8086 then
able interruptwhich we explain in detail later. The next gets the starting address of the interrupt service proce-
27 interrupt tvpes, from 5 to 31. are reserved by Intel for dure from
the type 0 locations in the interrupt pointer
use in future microprocessors. The upper 224 interrupt table. As you can see in Figure 8-2 it gets the new value
types, from 32 to 255, are available for you to use for for CS from addresses 00002H and 00003H. and the
hardware or software interrupts. new value for IP from addresses 00000H and 0000 1H.
When the 8086 responds to an interrupt, it automati- After the starting address of the procedure is loaded into
cally goes
to the specified location in the interrupt CS and IP, the 8086 then fetches and executes the first
pointer table to get the starting address of the interrupt instruction of the procedure.
service procedure. The 8086, however, does not auto- At the end of the interrupt service procedure an IRET
matically
the load
starting address in the pointer table. instruction will be used to return execution to the inter-
As we will show later, you have to do this with instruc- rupted program.The IRET instruction pops the stored
tionsthe
at start of your program. Note that the new value of IP off the stack and increments the stack
value for the instruction pointer is put in as the low pointer by two. It then pops the stored value of CS off the
word of the pointer, and the new value for the code seg- stack and increments the stack pointer again by two.
ment register is put in as the high word of the pointer. Finally it restores the flags by popping off the stack the
Now that you have an overview of how the 8086 re- values stored during the interrupt response and incre-
sponds
interrupts,
to we can show in detail how one of mentsstack
the pointer by two. Remember from the
these interrupts works. previous paragraph that during its interrupt response,
the 8086 disables the INTR and single-step interrupt by
clearing IF and TF. Now, if the INTR input and/or the
An 8086 Interrupt Response Example — Type 0 trap interrupt were enabled before the interrupt, they
Probably the easiest 8086 interrupt to understand is the will be enabled upon return to the interrupted program.
divide-by-zero interrupt, identified as type 0 in Figure The reason for this is that flags from the interrupted
8-2. We'll use a type 0 interrupt to show you in detail program were pushed on the stack before IF and TF were
how an 8086 interrupt works, and how to write a proce- cleared by the 8086 in its interrupt response. To sum-
dureservice
to an interrupt. marize, then,
IRET returns execution to the interrupted
First of all let's refresh your memory about how the program and restores the IF and the TF to the state they
8086 DIV and IDIV instructions work. The 8086 DIV were in before the interrupt. Now that we have described
instruction allows you to divide a 16-bit unsigned bi- the type 0 response, we can show you how to write a
nary number in AX by an 8-bit unsigned number from a program to handle this interrupt.

222 CHAPTfR IK, HI


3FFM TYPE 2b'j PulNII R
(AVAII All i I
3FCH

'-
AV All AB1 I INTERRUPT
POINTERS (224)
TYPE 33 POINTER
(AVAILAHl 1 1
084H
TYPE 32 POINTER
(AVAILAHl L1
080 H
07FH TYPE 31 POINTER
: HVED)

RESERVED INTERRUPT :
POINTERS (27)

TYPE 5 POINTER _
(RESERVED)
014H
TYPE 4 POINTER _
OVERFLOW
010H
TYPE 3 POINTER
1 BYTE INT INSTRUCTION
OOCH

DEDICATED INTERRUPT TYPE 2 POINTER _


POINTERS (5) NON-MASKABLE
008 H
TYPE 1 POINTER _
SINGLE-STEP
004 H
TYPEOPOINTER _ CS BASE ADDRESS_
DIVIDE ERROR IP OFFSET

1b Dl 1^

FIGURE 8-2 8086 interrupt pointer table.

An 8086 Interrupt Program Example in the 8086 flag register. The flag here is a bit in a mem-
ory location we set aside for this purpose. In the actual
DEFINING THE PROBLEM AND WRITING THE program we give this memory location the name
ALGORITHM BAD _DIV_FLAG. At the end of the interrupt service pro-
cedure
return
we to the interrupted mainline program.
In the last chapter we were mucking around mostly in
After the division in the mainline program we check to
hardware, so instead of jumping directly into the pro-
see if the result of the division is valid. If the result is
gram, use
let's this example to review how you go about
valid, we store it in the correct place in the scaled values
writing any program. array in memory. If the result is not valid, we leave zero
As described in Chapter 3. you start by carefully defin-
in that place in the scaled values array. The way we actu-
ing the
problem that you want the program to solve or
ally make the decision whether a result is valid or not is
the operations that you want it to perform. Part of this
to check the BAD DIV FLAG. If the result of the division
step is to determine the amount and types of data that
was too large, then the 8086 will have done a type zero
the program is to work with.
interrupt, and our interrupt service procedure will have
For the example program here we have four word-
set the BAD DIV FLAG to a one. If the result of the divi-
sized hexadecimal values stored in memory. We want to
sionvalid,
is then the 8086 will not do the interrupt,
divide each of these values by a byte-type scale factor to
and the BAD DIV FLAG will be zero.
give a byte-type scaled value. If the result of the division
The sequence of operations is repeated until all of the
is valid, we want to put the scaled value in an array in
memory. If the result of the division is invalid (too large values have been scaled. We use a register to keep track
to fit in the 8-bit result registei ). we want to put 0 in the
of which input value is being operated on at a particular
array for that scaled value. Figure 8-3 shows the algo- time.
rithmthis
for program in pseudocode. As shown in Fig-
WRITING THE INITIALIZATION LIST
ure 8-3a,the mainline part of this program gets each
16-bit value from memory in turn and divides that value After you have worked out the data structure and the
by the 8-bit scale factor. If the result of the division is too algorithm for a program, the next step is to make an
large to fit in the quotient register. AL, then the 8086 initialization list such as the one shown in Chapter 3.
will do a type 0 interrupt immediately after the divide Here is a list for this program.
instruction finishes.
Figure 8-3b shows the algorithm for our type 0 inter- I. Initialize the interrupt pointer table. In other words,
rupt service
procedure. The main function of this proce- the starting address of our type 0 interrupt service
dure
toisset a flag which will be checked by the main- routine must be put in locations 00000H and
line program.The flag in this case is not one of the Hags 00002H.

INTERRUPTS AND INTERRUPT SERVICE PROCEDURES 223


INITIALIZATION LIST

REPEAT
get INPUT_VALUE
divide by scale factor
IF result valid THEN
store result as scaled value
ELSE store zero
UNTIL all values scaled

Save registers
Set error flag
Restore registers
Return to mainline

FIGURE 8-3 Algorithm for divide by zero program example, (a) Mainline
program, (b) Interrupt service procedure.

2. Set up the data segment where the values to be available even address. The PUBLIC directive in this
scaled, the scale factor, the scaled values, and the statement identifies the segment name as public so it
BAD DIV FLAG will be put. can be referred to in other assembly modules. The input
values are words, so we use a DW directive to declare
3. Initialize the data segment register to point to the
these four values. The scaled values will be bytes, so we
base address of the data segment containing the val-
use the DB directive to set aside four locations for these.
ues be
to scaled.
The DUP(O) in the statement initializes the 4-byte loca-

4. Set up a stack to store the return address, since we tionsallto 0's. As the program executes, the results will

are essentially calling a procedure. be written into these locations. SCALE FACTOR DB 09H
sets aside a byte location for the number that we are
5. Initialize the stack segment and the stack pointer going to be dividing the input values by. The advantage
registers. of using a DB to declare the scale factor, rather than an
6. Initialize a pointer to the start of the data to be EQU directive, is that with a DB the value of scale factor

scaled, a counter to keep track of how many values can be held in RAM where it can be changed dynamically
we have scaled, and a pointer to the start of the array in the program as needed. If you use a statement such

where we want to put the scaled values. as SCALE FACTOR EQU 09H to set a value, you have to
reassemble the program to change the value.
Part of the 8086 interrupt response is essentially a far
Once you have the algorithm and the initialization list
call to the interrupt service procedure. In any program
for a program, the next step is to start writing the in-
that calls a procedure we have to set up a stack to store
structions
the for
program, so now let's look at the as-
sembly language
program for this problem. the return address and parameters passed to and from
the procedure. The next section of the program declares
a stack segment called STACKJIERE. It also establishes
ASSEMBLY LANGUAGE PROGRAM AND
a pointer to the next location above the stack with the
INTERRUPT PROCEDURE
statement TOPSTACK LABEL WORD. Remember from
Figure 8-4 shows our 8086 assembly language program the examples in Chapter 5 that this label is used to ini-
for the mainline and for the type 0 interrupt service pro- tializestack
the pointer to the next location after the top
cedure.can
Youuse many of the parts of these when you of the stack.
write your own interrupt programs. To help refresh your The next two parts of the program are necessary be-
memory of the PUBLIC and the EXTRN directives, we causewrote
we the main program and the interrupt
have written the mainline program and the interrupt service procedure as two separate assembly modules.
service procedure as two separate assembly modules. When the assembler reads through a source program, it
Remember, if you are not using an assembler, you can makes a symbol table which contains the segment and
just substitute the actual offsets or numbers for the offset of all of the names and labels used in the program.
names used in the example program. The statement PUBLIC BAD DIV FLAG tells the assem-
At the start of the mainline program in Figure 8-4a, bleridentify
to the name BAD_DiV_FLAG as public. This
we declare a segment named DATA HERE for the data means that when the object module for this program is
that the program will be working with. The WORD direc- linked with some other object module that declares
tive tellsthe locator to start this segment on the next BAD DIV FLAG as EXTRN. the linker will be allowed to

224 CHAITEK EIGHT


page ,132
8086 PROGRAM
ABSTRACT: Progras scales some data values by division.
PROCEDURES: Uses BADDIV, a type 0 interrupt service procedure
PORTS USED: None

DATA.HERE SEGMENT
WORD PUBLIC
INPUT_VALUESDW 0035H, 0B55H, 2011H, 1359H
SCALED.VALUESOB4 DUP10)
SCALE.FACTOR DB09H
BAD.dIv.FLAG DB0
DATA.HERE ENDS
STACK.HERE SEGMENT
STACK
DW 100 DUP (0) Set up stack of 100 words
TOP.STACK LABEL WORD Pointer to top of stack
STACK
HERE
" ENDS

PUBLIC BAD DIV FLAG Make flag available to other modules

INT_PROC_HERESEGMENT
WORD PUBLIC
EXTRNBAD_DIV:FAR Let asseabler know procedure BAD.DIVis
INT PROCHERE ENDS in another assembly aodule

CODE.HERE SEGMENTWORD PUBLIC


ASSUME
CS:C0DEHERE,DS:DATA
HERE,SSlSTACK.HERE
START: MOV AX, STACK.HERE Initialize stack segment register
MOV SS, AX
10V SP, OFFSETTOP.STACK ; Initialize stack pointer
NOV AX, DATA.HERE ; Initialize data segment register
MOV DS, AX
istore the address for the BAD.DIVroutine at address 0000:0000
laddress 00000-00003 is where type 0 interrupt gets interrupt
; service procedure address. CS at 00002 i 00003, IP at 00000 & 00001
MOV AX, 0000
MOV ES, AX
NOV WORD PTR ES:0002, SEGBAD.DIV
MOV WORD PTR ES:0000, OFFSETBADDIV
MOV SI, OFFSETINPUT.VALUES Initialize pointer for input values
MOV BX, OFFSET SCALED.VALUES Point BX at start of result array
MOV CX, 0004H Initialize data value counter
NEXT: MOV AX, [SI I Bring a value to AX for divide
DIV SCALE.FACTOR Divide by scale factor
CMP BAD.DIV.FLAG, 01H Check if divide produced invalid result
ONE OK" No, go save scaled value
MOV BYTEPTR [BX], 00 Yes, load 0 as scaled value
JHF SKIP
01.: MOV [BX], AL ; Save scaled value
SKIP MOV BAD.DIV.FLAG,
0 ; Reset BAD.DIV.FLAG
before doing nest
ADO SI,~02H~ ; Point at location of nest input value
INC BX ; Point at location for next result

LOOPNEXT ; Repeat until all values done


STOP: NOP
CODE.HERE ENDS
END START

FIGURE 8-4 8086 assembly language program for divide by zero example.
la) Mainline, lb) Interrupt service procedure.

INTERRUPTS AND INTERRUPT SERVICE PROCEDURES 225


age . 132

;8086 PROCEDURE TO SERVICE DIVIDE BY ZERO INTERRUPT (TVPE 0)

; This procedure sets the LS8 of a memory location called BADD1VFLAG,


; enables IHTR, and returns execution to the interrupted program with
; registers and flags unchanged.

DATA_HERE SEGMENT
WORD
PUBLIC
EXTRN BAD_DIV_FLA6:B¥TE ; Let assembler know BAD.DIVJLA6
DATAHERE ENDS ; is in another assembly nodule

PUBLIC BAD DIV I Hake procedure BADJIV available to


; other assembly modules

INTPROCHERE SEGMENTWORDPUBLIC ; Set up a segment for all


; interrupt service procedures
BADJIV PROCFAR ; Procedure for type 0 interrupt
ASSUMECS:INT PROC HERE, DS:DATA HERE

PUSH A): ; Save AX of interrupted program


PUSH DS i Save DS of interrupted program
MOV ftX, DATA_HERE ; Load DS value needed here
MOV DS, AH
MOV BAD.DIV_FLA6,
01 ; Set LSB of BAD_DIV_FLAG byte
POP DS ; Restore DS of interrupted program
POP AX ; Restore AX of interrupted program
I RE I ; Return to next instruction in
; interrupted program

BADDIV ENDP
INT PROC HERE ENDS

END

I |( ,1 IRI 8-4 (continual)

make the connection. Some programmers say that the CODE HERE SEGMENT WORD PUBLIC. The WORD in
PUBLIC directive "exports" a name or label. I his statement tells the linker/locator to locate this seg-
The other end of this export operation is to "import" ment the
on first available even address. The PUBLIC in
labels or names that are defined in other assembly mod- I Ins statement tells the linker that this segment can be
ules The
statement EXTRN BAD DIV: FAR in our example joined together (concatenated! with segments of the
program, for example, tells the assembler that BAD DIV same name from other assembly modules.
is a label of type FAR and that BAD DIV is defined As usual at the start of the code segment we use an
in some other assembly module. The INT PROC HERE ASSUME statement to tell the assembler what logical
SEGMENT WORD PUBLIC and INT PROC HERE ENDS segments to use for code, data, and stack. After this
statements tell the assembler that BAD DIV is defined (iimes the hopefully familiar instructions for initializing
in a segment named INT PROC HERE. When the as- the stack segment register, the stack pointer register,
sembler reads
these statements it will make an entry in and the data segment register.
its symbol table for BAD DIV, and identify it as external. The next four instructions are needed to place the
When the object module for this program is linked with address of the BAD DIV procedure in the type 0 location
iIk objeci module lor the program where BAD DIV is in the interrupt pointer table. The code segment ad-
ili fined, the linker will fill in the proper values for theCS dressBAD
for DIV is stored at 00002 and 00003 and the
and IP of BAD DIV. address of the offset of BAD DIV at OOOOO and 0000 lit
For the actual instructions of our mainline program is necessary to load the interrupt procedure addresses
we declare .i code segment with the statement in this way if you are using an SDK-86 board, or the

226 CHAPTER IK, HI


MASM and Link programs on an IBM PC type machine. dure here we save AX and l)S. Since we use the same
I his is because the linkei ovei rides any t >RG directives same data segment, DATA HERE, in the mainlii
winch makes it difficull to put programs .11 absolute in the procedure, you may wonder why we saved DS.
addresses The point is that an Interrupt service procedun
Next we initialize SI .is a pointer to the firsl be written so that n can he used ai any point in a pro
input value with the statement MOV SI, ( )l I SI I gram. By saving the DS value ol the interrupted pro
INPUT_ VALUES I he statement MOV BX, OFFSE1 gram, this interrupt service procedure can be used in a
sc MID \ \l HI s thru initializes BX as a pointer to the program section that docs not use DATA IIFCKIOas ils
first of the locations we set aside for the S hit scaled re- data segment.
sults. The ASSUME Statement tells the assembler the- name
To keep track of how many values have been scaled we ol the segment to use as a data segment, lint remembei
set up the ("X register as a counter. The statement M( )V that it does not load the DS register with a value foi the
CX, (H10-1H initializes the counter with the numbei ol val start ol that segment. The instructions MOV AX,
ues we want to scale. I his register will be decremented DAIA HfRI and MOV DS, AX do this in our procedure.
alter each input value is sealed. When CX 0. we know Finally, we get to the whole point ol this procedure
that all values have been scaled. with the MOV BAD DIV FLAG, 01 instruction. This in-
Finally everything is initialized, and we get to the op- struction simply
sets the least-significant bit ol the
erations
set weout to do. The statement MOV AX, |SI1 memory location we set aside with a DB directive at the
copies an input value from memory to the AX register start of the mainline program. Note that in order to ac-
where it has to be for the divide operation. The DIV cess this
variable by name you have to let the assembler
SCALE FACTOR instruction divides the number in AX by know that it is external, and you have to make sure that
09H. the value we assigned to SCALE FACTOR previ- the DS register contains the segment base for the seg-
ously with a DB directive. The 8-bit quotient from this mentwhich
in BAD DIV FLAG is located.
division will be put in AL and the 8-bit remainder will be To complete the procedure we pop the saved registers
put m AH. If the quotient is too large to fit in AL, then off the stack and return to the interrupted program. The
the 8086 will automatically do a type 0 interrupt. For IRET instruction, remember, is different from the regu-
our program here, the 8086 will push the flat's on the lar RET
instruction in that it pops the flag register and
stack, reset the IF and TF, and push the return address the return address off the stack. Note in the source pro-
on the stack. It will then go to addresses 0000H and gram
Figure
in 8-4b that if you are using an assembler,
0002H to get the IP and CS values for the start of the procedure must be "closed" with an ENDP directive,
BAD DIV. the procedure we wrote to service a type 0 and the segment must as usual be closed with an ENDS
interrupt. It will then execute the BAD DIV procedure. directive.
Now let's look at the procedure in Figure 8-4b and see Now let's look back in the mainline to see what it does
how it works. with this BAD DFV FLAG. Immediately after the DIV
The BAD DIV procedure starts by letting the assem- instruction, the mainline checks to see if the
bler knowthat the name BAD DIV FLAG represents a BAD DIV FLAG is set by comparing it with 01. If the
variable of type byte, and that this variable is defined in BAD DIV FLAG was not set by the type 0 interrupt
a segment called DATA-HERE in some other (EXTRN1 service procedure, then a jump is made to the MOV
assembly module. We also tell the assembler that the [BX], AL instruction. This instruction copies the result
label BAD DIV should be made available to other assem- of the division in AL to the memory location in
bly modules (PUBLIC I. SCALED VALUES pointed to by BX. If BAD DIV FLAG
Next we declare a logical segment called was set by a type 0 interrupt, then zero is put in the
INT PROC HERE. We could have put this procedure in memory location in SCALED-VALUES and a jump will
the segment CODE HERE with the mainline program. be made to the MOV BAD. DIV FLAG, 00 instruction
However, in system programs where there are many in- which resets the BAD DIV FLAG. Since this jump
terrupt service
procedures, a separate segment is usu- passes over the MOV [BX], AL instruction, the invalid
ally set
aside for them. What we are doing here, then, is result of the division will not be copied into one of the
to show you an overall structure that we will fill in as we locations in SCALED VALUES.
work our way through the rest of the book. After putting the scaled value or zero in the array and
The statement BAD DIV PROC FAR identifies the ac- resetting the flag, we get ready to operate on the next
tual start of the procedure, and tells the assembler that input value. The ADD SI, 02 instruction increments SI
both the CS and IP values for this procedure must be by two so that it points to the next 16-bit value in
saved. The ASSUME statement at the start of the proce- INPUT _VALUES. The INC BX instruction points BX at
dure thentells the assembler the names of the segments the next 8-bit location in SCALED VALUES. The LOOP
to use for code and data for this procedure. instruction after these automatically decrements the
Now. an important operation to do at the start of any CX register by one, and, if CX is not then zero, it causes
interrupt service procedure is to push on the stack any the 8086 to jump to the specified label, NEXT.
registers that you are going to use in the procedure. You The preceding section has shown you how to set up an
can then restore these registers by popping them off the interrupt pointer table, how to write an interrupt serv-
stack just before returning to the interrupted program. ice procedure, and how the 8086 responds to a type 0
The interrupted program will then resume with its reg- interrupt. Now we can discuss some of the other tvpes of
istersthey
as were before the interrupt. In our proce- 8086 interrupts.

INTERRUPTS AND INTERRUPT SERVICE PROCEDURES 227


8086 Interrupt Types each instruction, and wait for further direction from
you. The 8086 trap flag and type 1 interrupt response
The preceding sections used the type 0 interrupt as an
make it quite easy to implement a single-step feature in
example of how the 8086 interrupts function. In this
an 8086-based system.
section we discuss in detail the different ways an 8086
If the 8086 trap flag is set. the 8086 will automatically
can be interrupted, and how the 8086 responds to dif-
do a type 1 interrupt after each instruction executes.
ferent types
of interrupts. We discuss these in order,
When the 8086 does a type 1 interrupt it pushes the flag
starting with type 0. so that you can easily find a partic-
register on the stack, resets the TF and IF. and pushes
ular discussion when you need to refer back to it. How-
the CS and IP values for the next instruction on the
ever,you
as read though this section you should not
stack. It then gets the CS value for the start of the type 1
attempt to learn all of the details of all of the kinds of
interrupt service procedure from address 00006H. and
interrupts at once. Read through all of the kinds to gel
it gets the IP value for the start of the procedure from
an overview, and then focus on the details of the hard-
address 00004H.
ware-caused
interrupt,
NMI the software interrupts pro-
The tasks involved in implementing single step then
ducedtheby INT instruction, and the hardware inter-
are: set the trap flag, write an interrupt service proce-
rupt produced by applying a signal to the INTR input
dure which
saves all registers on the stack where they
pin.
can later be examined or perhaps displayed on the CRT.
DIVIDE-BY-ZERO INTERRUPT— TYPE 0 and load the starting address of the type 1 interrupt
service procedure into addresses 00004H and 00006H.
As we described in the preceding section, the 8086 will The actual single-step procedure will depend very much
automatically do a type 0 interrupt if the result of a DIV on the system that it is to be implemented on. We do not
operation or an IDIV operation is too large to fit in the have space here to show you the different ways to do
destination register. For a type 0 interrupt the 8086 this. We will, however, show you how the trap flag is set
pushes the flag register on the stack, resets the IF and or reset, because this is somewhat unusual.
TF. and pushes the return address ICS and IP) on the
The 8086 has no instructions to directly set or reset
stack. It then gets the CS value for the start of the inter-
the trap flag. These operations are done by pushing the
rupt serviceprocedure from address 00002H in the in-
flag register on the stack, changing the trap-flag bit to
terrupt pointer
table, and the IP value for the start of the
what you want it to be. and then popping the flag regis-
procedure from address 00000H in the interrupt
ter backoff the stack. Here is the instruction sequence
pointer table. to set the trap flag.
Since the 8086 type 0 response is automatic and can-
not be
disabled in any way. you have to account for it in PUSHF Push flags on stack
any programs where you use the DIV or IDIV instruc- MOV BP.SP Copy SP to BP for use as index

tions. One
way to do this is to in some way make sure OR [BP+01. 0100H Set TF bit

the result will never be too large for the result register. POPF Restore flag register
We showed one way to do this in the example program in
To reset the trap Hag. simply replace the OR instruction
Figure 5-25b. In that example you may remember we
in the above sequence with the instruction AND [BP+Oj,
first make sure the divisor is not zero, and then we do
OFEFFH.
the division in several steps so that the result of the divi-
sion will
never be too large. NOTE: We have to use [BP * 0] because BP cannot be
Another way to account for the 8086 type 0 response used as a pointer without a displacement. See Figure
is to simply write an interrupt service procedure which 3-8.
takes the desired action when an invalid division oc- The trap flag is reset when the 8086 does a type 1
curs. The
advantage of this approach is that you don't interrupt, so the single-step mode will be disabled dur-
have the overhead of a more complex division routine in ing the
interrupt service procedure.
your mainline program. The 8086 automatically does
the checking and only does the interrupt procedure if NONMASKABLE INTERRUPT— TYPE 2
there is a problem. Remember that when using any in- The 8086 will automatically do a type 2 interrupt re-
terruptsthe
with8086 you must in some way load the sponse when
it receives a low-to-high transition on its
starting address of the interrupt service procedure in NMI input pin. When it does a type 2 interrupt the 8086
the interrupt pointer table. will push the flags on the stack, reset TF and IF. and
push the CS value and the IP value for the next instruc-
SINGLE-STEP INTERRUPT— TYPE 1
tion on
the stack. It will then get the CS value for the
In a section of Chapter 3 on debugging assembly lan- start of the type 2 interrupt service procedure from ad-
guage programs
we discussed the use of the single-step dress 0000AH. and the IP value for the start of the proce-
feature present in some monitor programs and debug- dure fromaddress 00008H.
ger programs. When you tell a system to single-step, it The name nonmaskable given to this input pin on
will execute one instruction and stop. You can then ex- the 8086 means that the type 2 interrupt response can-
aminecontents
the of registers and memory locations. If not be
disabled (masked) by any program instructions.
they are correct, you can tell the system to go on and Because this input cannot be intentionally or acciden-
execute the next instruction. In other words, when in tally disabled,we use it to signal the 8086 that some
single-step mode, a system will stop after it executes condition in an external svstem must be taken care of.

228 R EIGHT
We could, lor example, have a pressure sensor on a large signed numbei til KM M)<> i ins decimal) and the 8 bit
sir. i in I Killer connected to the NMI input. II the prcsstu e signed number 01010001 (81 decimal), thi signed re-
lhh-s above some preset limit the sensoi Will send an in sull will be loillltil lis1.) decimal), rhis is the correct
terrupt s-ional to the 8086, The type 2 interrupt service result if we were adding unsigned binary numbei bu
procedure we write foi this case can turn oil the fuel to it is not the correct signed result. For si^nnl operations
the holler, open a pressure reliel valve, and sound an the l in the most significant bit ol the resull indicates
alai m. that the result is negative and in 2's complement form.
Another common use oi the type 2 interrupt is to save I he resuli then actually represents 67 decimal, which
program data in the case ol a system powei failure. is obviously not the correct result lor adding • 108 and
Some external circuitry detects when the ac power to the %89,
system I.tils and sends an interrupt signal to the NMI There are two major ways to detect and respond to an
input. Because ol the large filter capacitors in most overflow erroi in a program. One way is to put the Jump
power supplies, the (U- system power will remain lor per if Overflow instruction, IO, immediately aftei the arith-
haps 51) his alter the ac power is gone. This is more than metic instruction. II the overflow Hag is set as ,i result ol
enough time lor a type 2 interrupt service procedure to the arithmetic operation, execution will jump to the
copy program data to some RAM which has a battery address specified in the IO instruction. At this address
backup power supply. When the ac power returns, pro- you can put an error routine which responds in the way
gram data
can be restored from the battery-backed up you want to the overflow.
RAM and the program can resume execution where it The second way of detecting and responding to an
left off. A practice problem at the end of the chapter overflow error is to put the Interrupt on Overflow in-
gives you a chance to write a simple procedure for this struction, INTO,
immediately after the arithmetic in-
task. struction
the in program. If the overflow flag is not set
when the 8086 executes the INTO instruction, the in-
BREAKPOINT INTERRUPT— TYPE 3 struction
simply
will function as an NOP. However, if
the overflow flag is set. indicating an overflow error, the
The type 3 interrupt is produced by execution of the INT
8086 will do a type 4 interrupt after it executes the INTO
3 instruction. The main use of the type 3 interrupt is to
instruction.
implement a breakpoint function in a system. In (hap
When the 8086 does a type 4 interrupt, it pushes the
ter 4 we described the use of breakpoints in debugging
flag register on the stack, resets the TF and IF. and
assembly language programs. Hopefully you have been
pushes the CS and IP values for the next instruction on
using them in debugging your programs. When you in-
the stack. It then gets the CS value for the start of the
sertbreakpoint
a the system executes the instructions
interrupt service procedure from address 000 12H and
up to the breakpoint, and then goes to the breakpoint
the IP value for the procedure from address 0001 OH.
procedure. Unlike the single-step feature which stops
Instructions in the interrupt service procedure then
execution after each instruction, the breakpoint feature
perform the desired response to the error condition. The
executes all the instructions up to the inserted break-
procedure might, for example, set a "flag" in a memory
point and
then stops execution.
location as we did in the BAD DIV procedure in Figure
When you tell most 8086 systems to insert a break-
8-4b. The advantage of using the INTO and type 4 inter-
point
some
at point in your program, they actually do it
rupt approach is that the error routine is easily accessi-
by temporarily replacing the instruction byte at that
ble fromany program.
address with CCH. the 8086 code for the INT 3 instruc-
tion. When the 8086 executes this INT 3 instruction it
pushes the flag register on the stack, resets TF and IF. SOFTWARE INTERRUPTS— TYPE 0—255
and pushes the CS and IP values for the next mainline
The 8086 INT instruction can be used to cause the 8086
instruction on the stack. The 8086 then gets the CS
to do any one of the 256 possible interrupt types. The
value of the start of the type 3 interrupt service proce-
desired interrupt type is specified as part of the instruc-
dure fromaddress 0000EH and the IP value for the pro-
tion. The
instruction INT 32. for example, will cause the
cedure from
address 0000CH. A breakpoint interrupt
8086 to do a type 32 interrupt response. The 8086 will
service procedure usually saves all of the register con-
push the flag register on the stack, reset the TF and IF,
tents the
on stack. Depending on the system, it may
and push the CS and IP values of the next instruction on
then send the register contents to the CRT display and
the stack. It will then get the CS and IP values for the
wait for the next command from the user, or in a simple
start of the interrupt service procedure from the inter-
system it may just return control to the user. In this
rupt pointertable in memory. The IP value for any inter-
case an examine register command can be used to check
rupt type
is always at an address of 4 times the interrupt
if the register contents are correct at that point in the
type, and the CS value is at a location two addresses
program.
higher. For a type 32 interrupt, then, the IP value will be
put at 4 • 32 or 128 decimal (80H). and the CS value
OVERFLOW INTERRUPT— TYPE 4
will be put at address 82H in the interrupt pointer table.
The 8086 overflow Hag, OF, will be set if the signed re- Software interrupts produced by the INT instruction
sultan
of arithmetic operation on two signed numbers have many uses. In a previous section we discussed the
is too large to be represented in the destination register use of the INT 3 instruction to insert breakpoints in pro-
or memory location. For example, if you add the 8-bit gramsdebugging.
for Another use of software inter-

INTERRUPTS AND INTERRUPT SERVICE PROCEDURES 229


rupts is to test various interrupt service procedures. You an STI instruction. The 8086 was designed this way so
could, for example, use an INT 0 instruction to send exe- that ports, timers, registers, etc. can be initialized be-
cution
a to
divide-by-zero interrupt service procedure fore enablingthe INTR input. In other words this allows
without having to run the actual division program. As you to get the 8086 ready to handle an interrupt before
another example, you could use an INT 2 instruction to letting an interrupt in. just as you might want to get
send execution to an NMI interrupt service procedure. yourself ready in the morning with a cup of coffee before
This allows you to test the NMI procedure without need- turning on the telephone and having to cope with the
ing apply
to an external signal to the NMI input of the interrupts it produces.
8086. The interrupt flag is also automatically cleared as part
Another important use of software interrupts is to call of the response of an 8086 to an interrupt. This is done
desired procedures from many different programs in a for two reasons. First, it prevents a signal on the INTR
system. The BIOS in the IBM PC is a good example of input from interrupting a higher priority interrupt serv-
this. The IBM PC has in its ROMs a collection of proce- ice procedure in progress. You can. however, set the IF
dures. Each
procedure performs some specific function with an STI instruction at the start of the procedure if
such as reading a character from the keyboard, writing you want an INTR input signal to be able to interrupt a
some characters to the CRT, or reading some informa- procedure in progress.
tion froma disk. This collection of procedures is re- The second reason for automatically disabling the
ferred
as tothe Basic /nput Output System or BIOS. The INTR input at the start of an INTR interrupt service pro-
BIOS procedures are called with INT instructions. You cedure
to make
is sure that a signal on the INTR input
can read the BIOS section of the IBM PC technical refer- does not cause the 8086 to continuously interrupt itself.
ence manualto get all of the details of these if you need The INTR input is activated by a high level. In other
them, but here's an example of how you might use one words, whenever the INTR input is high and INTR is en-
of them. abled,8086
the will be interrupted. If INTR were not dis-
Suppose that, as part of an assembly language pro- abled during the first response, the 8086 would be con-
gram that
your are writing to run on an IBM PC, you tinuously interrupted, and never get to the actual
want to send some characters to the printer. Figure 8-5 interrupt service procedure. Since the INTR is level-
is a program which shows how to do this. activated, the interrupt signal must remain present
Note that the DX, AH. and AL registers are used to until it is recognized by the 8086.
pass parameters to the procedure. Also note that the The IRET instruction at the end of the interrupt serv-
procedure is used for two different operations: initializ- ice procedure restores the Hags to the condition they
ing theprinter port and sending a character to the were in before the procedure by popping the Hag register
printer. The operation performed by the procedure is off the stack. This will reenable the INTR input. If a high
determined by the number passed to the procedure in level signal is still present on the INTR input, it will
the AH register. AH = 1 means initialize the printer cause the 8086 to be interrupted again. If we do not
port, AH = 0 means print the character in AL, and AH = want the 8086 to be interrupted again by the same
2 means read the printer status and return it in AH. If input signal, we have to use external hardware to make
an attempt to print a character was not successful for sure the signal is made low again before we reenable
some reason such as the printer not being turned on, INTR with the STI instruction, or before the end of the
not being selected, or being busy. 01 is returned in AH. INTR service procedure.
The main advantage of calling procedures in this way When the 8086 responds to an INTR interrupt signal,
is that you don't need to worry about the absolute ad- its response is somewhat different from its response to
dress where
the procedure actually resides or about try- other interrupts. The main difference is that for an INTR
ing to
link the procedure into your program. All you interrupt, the interrupt type is sent to the 8086 from an
have to know is the interrupt type for the procedure and external hardware device such as the 8259A priority in-
the format for the parameters you need to pass to the terrupt controller which we discuss later in this chapter.
procedure. We show some other examples of using BIOS An 8086 INTR response proceeds as follows.
procedures in later chapters. The 8086 first does two interrupt acknowledge ma-
chine cycles,as shown in Figure 8-6. The purpose of
these two machine cycles is to get the interrupt type
INTR INTERRUPTS— TYPE 0—255
from the external device. At the start of the first inter-
The 8086 INTR input allows some external signal to in- rupt acknowledge machine cycle the 8086 floats the
terrupt execution
of a program. Unlike the NMI input. data bus lines, AD0-AD15. It then sends out an inter-
however. INTR can be masked (disabled) so that it can- rupt acknowledge pulse on its INTA output pin. This
not cause an interrupt. If the interrupt flag. IF. is pulse essentially tells the external device, "get ready.'
cleared, then the INTR input is disabled. The IF can be During the second interrupt acknowledge machine cycle
cleared at any time with the clear interrupt instruction. the 8086 sends out another pulse on its INTA output
CLI. If the interrupt flag is set, the INTR input will be pin. In response to this second INTA pulse the external
enabled. The IF can be set at any time with the set inter- device puts the interrupt type (number) on the lower
rupt instruction, STI. eight lines of the data bus where it is read by the 8086.
When the 8086 is reset, the interrupt flag is automati- Once the 8086 receives the interrupt type, it pushes
cally cleared.
Before the 8086 can respond to an inter- the flag register on the stack, clears TF and IF. and
rupt signal
on its IN fR input you have to set the IF with pushes the CS and IP values of the next instruction on

230 CHAPTER EIGHT


PAGE,132
;8086 PROGRAM
; ABSTRACT This program sends a string of characters to a
printer from the IBMPC
IREGISTERS USED CS, SS, DS, BX, AX, CX, DX
; PORTS USED printer port 0
;PROCEDURES USED:Calls BIOS printer 10 procedure INT 17

STACK.HERE SEGMENT STACK


DM 200 BUPI0) set aside 200 words for stack
STACK.TOP LABEL WORD assign name to word above stack top
STACK HERE ENDS

CHAR COUNT EQU 27

DATA.HERE SEGMENT
MESSAGE DB 'HELLOTHERE,HOWAREYOU"1-
MESSAGE.END DB 0DH, 0AH i return & line feed
DATA.HERE ENDS
CODE.HERE SEGMENT
ASSUME
CS:CODE.HERE,
SS:STACK.HERE,
DS:DATA_HERE

MOV AX, STACK


_HERE ; initialize stack segment register
MOV SS, AX
MOV SP, OFFSETSTACK.TOP
; initialize stack pointer

hov AX, DATA.HERE J initialize data segment


MOV DS, AX
MOV AH, 01 ; initialize printer port
MOV DX, 0 ; to use printer port 0
INT 17H ; call procedure to intitialize printer port
LEA BX, MESSAGE 1 get to start of tessage
MOV CX, CHAR.COUNTj set up a count variable
again:
MOV AH, 0 ; code to tell procedure to send character
MOV AL, [BX] ; load character to be sent into AL
1NT 17H ; send character to printer
CMP AH, 01H ; if character not printed then AH -1
JNE NEXT
not.rdy:stc set carry to indicate aessage not sent
JMP EXIT ; leave loop
NEXT: CLC dear carry flag to show character is sent
INC BX i address of next character
LOOP AGAIN ; send the next character
EXIT: NOP
CODE.HERE
ENDS
END

FIGURE 8-5 assembly language program for outputting characters to a


printer.

the stack. It then uses the type it read in from the exter- The advantage of having an external device insert the
nal deviceto get the CS and IP values for the interrupt desired interrupt type is that the external device can
service procedure from the interrupt pointer table in "funnel" interrupt signals from many sources into the
memory. The IP value for the procedure will be put at an INTR input pin on the 8086. When the 8086 responds
address equal to 4 times the type number, and the CS with 1NTA pulses, the external device can send to the
value will be put at an address equal to 4 times the type 8086 the interrupt type that corresponds to the source
number plus 2. just as is done for the other interrupts. of the interrupt signal. As you will see later the external

INTERRUPTS AND INTERRUPT SERVICE PROCEDURES 231


_r\. *J~\
a r
3 FLOAT Aype vector\— —

FIGURE 8-6 8086 interrupt acknowledge machine cycles.

device can also prevent an argument if two or more service procedure. However, because the NMI interrupt
sources send interrupt signals at the same time. request is not disabled, the 8086 will then do an NMI
(type 2) interrupt response. In other words, the 8086
PRIORITY OF 8086 INTERRUPTS will push the flags on the stack, clear TF and IF, push
the return address on the stack, and go execute the NMI
As you read through the preceding discussions of the
interrupt service procedure. When the 8086 finishes the
different interrupt types, the question may have oc-
NMI procedure, it will return to the divide error proce-
curred
you.to "What happens if two or more interrupts
dure, finish
executing that procedure, and then return
happen at the same time?" The answer to this question
to the mainline program.
is that the highest priority interrupt will be serviced
To finish our discussion of 8086 interrupt priorities,
first, and then the next highest priority interrupt will be
serviced. Figure 8-7 shows the priorities of the 8086 in-
let's see how the single step (TRAP or type 1) interrupt
fits in. If the trap Hag is set, the 8086 will do a type 1
terrupts
shownas in the Intel data book. Some exam-
ples will
show you what these priorities actually mean.
interrupt response after every mainline instruction.
As a first example, suppose that the INTR input is en- When the 8086 responds to any interrupt, however, part
of its response is to clear the trap flag. This disables the
abled,8086
the receives an INTR signal during execu-
single-step function, so the 8086 will not normally
tionaofdivide instruction, and the divide operation
single-step through the instructions of the interrupt
produces a divide-by-zero interrupt. Since the internal
service procedure. In actuality, if the 8086 is in single-
interrupts such as divide error. INT. and INTO have
step mode when it enters an interrupt service proce-
higher priority than INTR. the 8086 will do a divide error
dure,
willit execute the single-step procedure once be-
(type 0) interrupt response first. Part of the type 0 inter-
fore
executes
it the called interrupt procedure. The trap
rupt responseis to clear the IF. This disables the INTR
input and prevents the INTR signal from interrupting flag can be set again in the single-step procedure if sin-
gle stepping is desired in the interrupt service proce-
the higher priority type 0 interrupt service procedure.
dure.
An IRET instruction at the end of the type 0 procedure
Now that we have shown you the different types of
will restore the flags to what they were before the type 0
8086 interrupts and how the 8086 responds to each, we
response. This will reenable the INTR input and the
will show you a few examples of how the 8086 hardware
8086 will do an INTR interrupt response. A similar se-
interrupts are used. Other applications of interrupts
quence
operations
of will occur if the 8086 is executing
will be shown throughout the rest of the book.
an INT or INTO instruction and a high level signal ar-
rivesthe
at INTR input.
As a second example of how this priority works, sup- HARDWARE INTERRUPT APPLICATIONS
pose thata rising-edge signal arrives at the NMI input
while the 8086 is executing a DIV instruction, and that Hardware and Software Considerations When
the division operation produces a divide error. Since the Using Interrupts
8086 checks for internal interrupts before it checks for
HARDWARE
an NMI interrupt, the 8086 will push the flags on the
stack, clear TF and IF, push the return address on the Whenever you are going to do some task with an inter-
stack, and go to the start of the divide error (type 0) rupt, there
are some important hardware points for you
to consider. Among these are:

How many interrupt inputs does the microprocessor


INTERRUPT PRIORITY
have?
DIVIDE ERROR, INT n INTO HIGHEST
Do these inputs require active high, active low. or
NMI
edge-active signals to assert them?
INTR

SINGLE-STEP LOWEST
Do the interrupt inputs have priorities?
Is external hardware required to insert a restart in-
FIGURE 8-7 Priority of 8086 interrupts. (Intel struction
interrupt
or type, or is this done automati-
Corporation) cally whenthe CPU responds to the interrupt?

232 CHAPTER EIGHT


SOFTWARI ASCII PORT
KE > BOARI FFI IH

Among the software considerations when you an- going D D„


to use an Interrupt arc the following

1. What Instructions arc required to unmask/enabli P2A


the Interrupt input you want to use D,
2. How arc the stack and stack polntei Initialized? IT
KP
3. Docs the CPU automaticall) save flags and register
contents when it responds to the interrupt, or do 5

you have to use push instructions at the start ol the


routine to do this';' S2 <> R20
4. How can data required
cedure be accessed
by the interrupt
no matter
service
when- in the main
pro
pro
, r4 o „ i Hlv " NMI

% ±. INTR
gram the interrupt occurs?

5. What instructions are required at the end of the pro- FIGURE 8-8 Circuit modifications for SDK-86 NMI input.
cedure
restore
to main program flags and registers,
enable interrupts, and return to the interrupted When this key is pressed, the input of the 74LS14 in-
mainline program. verter be
will made low. and the output ol the invertei
will go high. The low-to-high transition on the NMI
SIMPLE INTERRUPT DATA INPUT
input causes the 8086 to automatically do an NMI (type
One of the most common uses of interrupts is to relieve 21 interrupt response.
a CPU of the burden of polling. Back in Chapter 4 we Figure 8-8 shows how we modified circuitry for our
showed you how ASCII characters can be read in from example here. We removed R22, a 1 10-12 resistor, and
an encoded keyboard on a polled basis. Figure 4-13 C33, a l-/uF capacitor, so the keypad switch can no
shows the circuit connections, and Figure 4-14 shows longer cause an interrupt. We then connected an active
the algorithm and program for this. To refresh your low strobe line from an ASCII-encoded keyboard directly
memory, polling works as follows. to the input of A21, the 74LS14 inverter. When a key on
The strobe or data ready signal from some external the ASCII keyboard is pressed, the keyboard circuitry
device is connected to an input port line on the micro- will send out the ASCII code for the pressed key on its
computer.
microcomputer
The uses a program loop to eight parallel data lines and it will assert the keypressed
read and test this port line over and over until the data strobe line low. The keypressed strobe going low will
ready signal is found to be asserted. The microcomputer cause the NMI input of the 8086 to be asserted high.
then exits the polling loop and reads in the data from This will cause the 8086 to do a type 2 interrupt. Now
the external device. Data can also be output on a polled let's look at the hardware and software considerations
basis. for this interrupt example.
The disadvantage of polled input or output is that The hardware considerations for this example are
while the microcomputer is polling the strobe or data quite simply answered. The NMI input requires a low-
ready signal, it can not easily be doing other tasks. In to-high transition, and, with the circuit connections
systems where the microcomputer must be doing many shown in Figure 8-8, this will be produced when a key
tasks, polling is a waste of time, so interrupt input and on the ASCII keyboard is pressed. Since we are only
output is used. In this case the data ready or strobe sig- using one interrupt here, we are not concerned about
nalconnected
is to an interrupt input on the microcom- priorities. In response to its NMI input being asserted,
puter. The
microcomputer then goes about doing its the 8086 automatically does a type 2 interrupt response.
other tasks until it is interrupted by a data ready signal No external hardware is needed for the interrupt type.
from the external device. An interrupt service procedure The software considerations require a little more
can read in or send out the desired data and, when fin- thought, but their answers are very similar to those for
ished, return
execution to the interrupted program. the divide by zero example in a previous section. At the
For our example here we will connect the keypressed start of the mainline we need to load address 00008H
strobe to the NMI interrupt input of the 8086 on an with the IP value for the start of the type 2 procedure,
SDK-86. The NMI input is usually reserved for respond- and address 0000AH with the CS value for the start of
ing ato power failure or some other catastropic condi- the procedure. Since any interrupt response uses the
tion. However, since we are not expecting any stack, we need to set up a stack. Assuming that we are
catastropic conditions to befall our SDK-86. we choose going to read in the ASCII characters from the keyboard
to use this input because it does not require an external and put them in an array in memory, we need to set up a
hardware device to insert the interrupt type as does the data segment for the array. In the actual code section of
1NTR input. the mainline we need to initialize the data segment reg-
Sheet 2 of the SDK-86 schematics in Figure 7-6 shows ister, stack
the segment register, and the stack pointer
the circuitry normally connected to the NMI input. This register. Figure 8-9a shows the instructions for doing
circuitry is designed so that you can cause an NMI inter- all this. Another important thing to do in the start of the
ruptpressing
by a key labeled INTR on the hex keypad. mainline program is to initialize a pointer to the start of

INTIRRUPTS AND INTERRUPT SERVICE PROC EDURts 233


page ,132
8086 PROGRAMTO READ CHARACTERSFROM A KEYBOARD
ABSTRACT: The aainline of this procedure initializes the interrupt
table with the address of the procedure that reads the
characters from a keyboard on an interrupt basis.
PROCEDURES: Uses KEYBOARD
PORTSUSED: None in aainline, FFF8H for keyboard input in KEYBOARD

DATA.HERE SEGMENTWORD PUBLIC


ASCII.STRIN6 DB 100 DUP!0) ; store for characters
ASCII.PQINTER DW OFFSET ASCII STRING
CHARCNT DB i read 100 characters
KEYDONE DB ; =1 if characters all read
DATA_HERE ENDS
STACK.HERE SEGMENT STACK
DW 100 DUP !0! ; Set up stack of 100 words
TOP.STACKLABEL WORD ; Pointer to top of stack
STACK
HERE
" ENDS

PUBLIC ASCII.POINTER,CHARCNT,
KEYDONE I Make available to other nodules
EXTRN KEYBOARDER ; Procedure in another assembly module

CODE.HERE SEGMENT
WORD PUBLIC
ASSUME
CS:CODE_HERE,
DS:DATA_HERE,
SS:STACK_HERE
START: MOVAX, STACK.HERE i Initialize stack segment register
MOV SS, AX
MOV SP, OFFSETTOP.STACK i Initialize stack pointer
MOV AX, DATA.HERE ; Initialize data segment register
MOV DS, AX
Jstore the address for the KEYBOARD routine at address 0000:3008
; address 0P008-0000E is where type 2 interrupt gets interrupt
; service procedure address. CS at 0000A h 0000B, IP at 00008 i 0000?
MOV AX, 0000
MOV ES, AX
MOV WORDPTR ES:000AH, SEG KEYBOARD
MOV WORD PTR ES:0008H, OFFSETKEYBOARD
(Simulate larger program.
HERE: JMP HERE

CODE HERE ENDS


en:

FIGURE 8-9 Reading characters from an ASCII keyboard on interrupt basis.


(a) Initialization and mainline, (h) Interrupt service procedure.

the array where the ASCII characters will be put as they gram that
the 8086 might be executing. The 8086 will
are read in. The statement ASCII POINTER DW OFFSET execute this instruction over and over until an interrupt
ASCILSTRING in the data segment in Figure 8-9a sets occurs. When an interrupt occurs the 8086 will service
aside a word location in memory and initializes that lo- the interrupt and then return to execute the HERE: JMP
ration with the offset ol the start of the array we de- HERE instruction over and over again until the next in-
dared to put the ASCII characters in. In the procedure terrupt. that
Note if we had connected the interrupt sig-
we get this pointer, use it to store a character, and in- nal to
the 8086 INTR interrupt input instead of the NMI
crement
to point
it to the next location in the array. input, we would have had to enable the INTR input with
Since this pointer is stored in a named memory loca- an STI instruction before the HERE: JMP HERE.
tion,
canit be accessed easily by the procedure, no mat- Figure 8-9b shows the interrupt service procedure for
ter when the interrupt occurs in the mainline program. this example. The comments for the procedure express
The HERE: JMP HERE instruction at the end of the its algorithm fairly clearly. After saving AX. BX. CX. and
mainline program simulates a complex mainline pro- DX on the stack, we check to see if all characters have

234 ( HAI'TER EIGHT


;3036 READ KEYBOARDON INTERRUPT BASIS PROCEDURE
; ABSTRACT : This procedure reads in ASCII characters from an
; : encoded keyboard on an interrupt basis and stores them
; : in a buffer in memory
iSAVES : all registers used
•.PORTSUSED: input port FFF8Hfor the keyboard input

DftTA_HERE SEGMENT
WORD PUBLIC
EXTRN ASCII_POINTER:W0RD, CHARCNT: BYTE. KEYDONE: BYTE
DATA_HERE ENDS
"

PUBLIC KEYBOARD

CODEHERE SEGMENT WORD PUBLIC


KEYBOARD PROC FAR
ASSUMECS:C0DE HERE, DS-.DATAHERE

ST1 enable 8096 INTRso higher priority


interrupts can be recognized
PUSH AX ! ave registers
save

PUSH BX
PUSH CX
PUSH DX
CMP CHARCNT, 00 ; see if all characters read in
j: EXIT ; leave if all done
MOV BX, ASCI] ;_POINTER; get pointer to buffer
MOV DX, 0FFF8H ; point at keyboard port
IN AL, DX ; Read ASCII code
AND AL, 7FH i Mask parity bit
MOV [BX], AL ; Write character to buffer
[NC ASCII.POINTER ; point to next buffer location
DEC CHARCNT ; Check if 100 characters yet
JNZ NOTDONE ; No. clear carry to indicate
MOV KEYDONE, 01H ', Yes, set flag to indicate done
JMP EXIT
N0TD0NE:MOV KEYDONE,OOH ; No, clear keydone flag
EXIT: POP DX ; restore registers
POP CX
POF BX
POP Ai
IRET
KEYBOARD ENDP

CODE.HERE ENDS
END

FIGURE 8-9 (continued)

been read. If CHARCNT is zero, then we do not read acter


theto memory location pointed to by BX. To get the
in any characters. If CHARCNT is not zero, we copy pointer ready for the read and store operation, we incre-
the array pointer from its named memory location. ment the
stored pointer with the INC ASCILPOINTER
ASCII POINTER, to BX. We then read in the ASCII instruction. Finally, our work done, we restore DX. CX.
character from the port that the keyboard is connected BX. and AX, and return to the mainline program.
to and mask the parity bit of the ASCII character. The Sitting in a HERE: IMP HERE loop waiting for an inter-
MOV [BX], AL instruction next copies the ASCII char- rupt signal
may not seem like much of an improvement

INTERRUPTS AND INTERRUPT SERVICE PROCEDURES 235


over polling the keypressed strobe. However, in a more high signal on its NMI input, it will automatically do a
realistic program the 8086 would be doing many other type 2 interrupt response. As we mentioned above, all
tasks between keyboard interrupts. With polling the the type 2 interrupt service procedure has to do in this
8086 would not easily be able to do this. case is increment the board count in a named memory-
location and return to running the machine. This same
technique can be used to count people going into a sta-
Using Interrupts for Counting and Timing dium, cows
coming in from the pasture, or just about
any thing else you might want to count.
COUNTING
USING AN INTERRUPT INPUT FOR TIMING
As a simple example of the use of an interrupt input for
APPLICATIONS
counting, suppose that we are using an 8086 to control
a printed-circuit-board-making machine in our com- In Chapter 4 we showed how a delay loop could be used
puterized electronics
factory. Further suppose that we to set the time between microcomputer operations. In
want to detect each finished board as it comes out of the the example there we used a delay loop to let us take in
machine and to keep a count of finished boards so that data samples at 1-ms intervals. The obvious disadvan-
we can compare this count with the number of boards tagea ofdelay loop is that while the microcomputer is
fed in. This way we can determine if any boards were stuck in the delay loop, it cannot easily be doing other
lost in the machine. useful work. In many cases a delay loop would be a waste
To do this count on an interrupt basis, all we have to of the microcomputer's valuable time. For most micro-
do is detect when a board passes out of the machine and computer timing,
an interrupt approach is much more
send an interrupt signal to an interrupt input on the efficient.
8086. The interrupt service procedure for that input can Suppose, for example, that in our 8086-controlled
simply increment the board count stored in a named printed circuit board machine we need to check the pH
memory location. of a solution approximately even' 4 minutes. If we used a
To detect a board coming out of the machine we use delay loop to count off the 4 minutes, either the 8086
an infrared LED. a phototransistor. and two condition- wouldn't be able to do much else, or we would have some
ing gates as shown in Figure 8-10. The LED is posi- difficult calculations to figure out at what points in the
tioned over
the track where the boards come out. and program to go check the pH.
the phototransistor is positioned below the track. When To solve this problem, all we have to do is connect a
no board is between the LED and the phototransistor. simple 1-Hz pulse source to an interrupt input as shown
the light from the LED will strike the phototransistor in Figure 8-11. This 555 timer circuit is not very accu-
and turn it on. The collector of the phototransistor will rate, but
it is inexpensive, and it is good enough for this
then be low. as will the NMI input on the 8086. When a application. We connect the timer output to the 8086
board passes between the LED and the phototransistor. NMI input as you might do to demonstrate this concept
the light will not reach the phototransistor. and it will on an SDK-86 board. The 555 timer will send an inter-
turn off. Its collector will go high, and so will the signal rupt signalto the 8086 NMI input approximately once
to the NMI input of the 8086. The 74LS14 Schmitt trig- even' second. If we simply count the number of NMI in-
ger inverters are necessary to turn the slow rise-time terruptsoccur,
that we will then know how many sec-
signal from the phototransistor collector into a signal onds have
passed.
which meets the rise-time requirements of the NMI Here's how the programming is done for this applica-
input on the 8086. When the 8086 receives the low-to- tion.the
In mainline we set aside a memon- location for

-5 V + 5 V

62 n

74LS14 6"74LS14

NMI

INFRARED LED

- PC
BOARD PHOTOTRANSISTOR

FIGURE 8-10 Circuit for optically detecting presence of an ob|ect.

236 CHAPTEREIGHT
.5V we reload the seconds count memorj loi atlon with F0I I
I- 5 V t 5 V and call the procedure which reads the pi I ol the solu
t ii >ti ,iihI takes appropriate action il the pi I in nol coi
IS 4 8 8086 rect. II the seconds count is nol zero, exe< ution simply
returns to the mainline program until the next inter-
/ Vcc rupt fromthe 555 or from some other source occurs Id
help you visualize how tins winks. Figure 8 12 show's
555 Hit- algorithm for this mainline and procedure. I he ad
470kS2\ 3 17 vantage ol this Interrupt approach is thai the interrupl
OUT NMI
service procedure only lakes a few microseconds ol the
6
8086's time once every second. The resi ol the time the
-1 8086 is free to run the mainline program

1/iF 7 .I5 1
USING AN INTERRUPT
TIME CLOCK
TO PRODUCE A RIAL-

0.01 a*F
X J Another application using a 1 -Hz interrupt input might
be to generate a real-time clock of seconds, minutes, and
hours The time from this clock can then be displayed
FIGURE 8-11 Inexpensive 1-Hz pulse source tor interrupt
and/or printed out on timecards, etc. To generate the
timing.
clock a 1-Hz signal is applied to an interrupt input. A
seconds count, a minutes count, and an hours count
the seconds count and initialize that location to the are kept in three successive memory locations. When an
number of seconds that we want to count off. In this interrupt occurs, the seconds count is incremented by
case we want 4 minutes, which is 240 decimal or FOH one. If the seconds count is not equal to 60. then execu-
seconds. Each time the 8086 receives an interrupt from tionsimply
is returned to the mainline program. If the
the 555 timer, it executes the interrupt service proce- seconds count is equal to 60 then the seconds count is
dure for
the NMI interrupt. In this procedure we decre- reset to zero, and the minutes count is incremented by
ment the
seconds count in the named memory location one. If the minutes count is not 60 then execution is
and test to see if the count is down to zero yet. If the simply returned to the mainline. If the minutes count is
count is zero, we know that 4 minutes have elapsed, so 60 then the minutes count is reset to zero, and the

INITIALIZE
INTERRUPT POINTER TABLE
STACK AND STACK SEGMENT POINTER
DATA SEGMENT
SECONDS COUNT TO 2^0 DECIMAL
WAIT FOR INTERRUPT

(a)

SAVE REGISTERS
DECREMENT SECONDS COUNT
IF SECONDS COUNT = 0 THEN
RELOAD SECONDS COUNT WITH 2^+0 DECIMAL
CALL pH READ PROCEDURE
RESTORE REGISTERS
RETURN TO MAINLINE
ELSE RESTORE REGISTERS
RETURN TO MAINLINE

FIGURE 8-12 Algorithm for pH read at 4-minute intervals, (a) Initialization and
mainline, (b) Interrupt service procedure.

INTERRUPTS AND INTERRUPT SERVICE PROCEDURES 237


hours count is incremented by one. If the hours count is the details of their operations. The discussions here are
not 13, then execution is simply returned to the main- intended to introduce you to the devices, show you what
line.theIf hours count is equal to 13 then it is reset to 1 they can be used for, and show you enough details about
and execution returned to the mainline. A problem at them that you can do some real jobs with them. After
the end of the chapter asks you to write the algorithm you become familiar with using a device in some simple
and program for this real-time clock. applications, you can read the data sheets to learn fur-
The interrupt service routine for the real-time clock ther "bells
and whistles" that the devices have.
can easily be modified to also keep track of other time
measurements such as the 4-minute timer shown in the
preceding example. In other words, the single interrupt Basic 8253 and 8254 Operation
service routine can be used to keep track of several dif- The Intel 8253 and 8254 each contain three 16-bit
ferent time
intervals. By counting a different number of counters which can be programmed to operate in sev-
interrupts or applying a different frequency signal to the eral differentmodes. The 8253 and 8254 devices are
interrupt input, this technique can be used to time pin-for-pin compatible, and they are nearly identical in
many different tasks in a microcomputer system. function. The major differences are:

GENERATING AN ACCURATE TIME BASE FOR 1. The maximum input clock frequency for the 8253 is
TIMING INTERRUPTS 2.6 MHz. the maximum clock frequency for the 8254
is 8 MHz ( 10 MHz for the 8254-2).
The 555 timer that we used for the 4-minute timer de-
scribed above
was accurate enough for that application, 2. The 8254 has a read-back feature which allows you
but for many applications, it is not. For more precise to latch the count in all of the counters and the sta-
timing we usually use a signal derived from a crystal- tus ofthe counter at any point. The 8253 does not
controlled oscillator such as the processor clock signal. have this read-back feature.
The processor clock signal is stable, but it is obviously
too high in frequency to drive a processor interrupt To simplify reading of this section we will refer only to
input directly. Therefore, it is divided down with an ex-
the 8254. However, you can assume that the discussion
ternal counter
device to an appropriate frequency for the
also applies to the 8253 except where we specifically
interrupt input. Most microcomputers have a counter
state otherwise.
device such as the Intel 8253 or 8254, which can be pro- As shown by the block diagram of the 8254 in Figure
grammed instructions
with to divide an input frequency 8-13, the device contains three 16-bit counters. In some
by any desired number. Besides acting as programma- ways these counters are similar to the TTL presettable
ble frequency dividers, these devices have many impor- counters we reviewed in Chapter 1 . The big advantage of
tant usesin microcomputer systems. Therefore, the these counters, however, is that you can load a count in
next section describes how an 8254 operates, how an them, start them, and stop them with instructions in
8524 can easily be added to an SDK-86 board, and how your program. The device is then said to be software
an 8254 is used in a variety of interrupt applications.
Also in the next section we use the 8254 discussion to
show you the general procedure for initializing any of
the programmable peripheral devices we discuss in later
chapters. CLK 0

D'D-<0 GATEO

OUTO
A Software-Programmable Timer/Counter, the
Intel 8253 and 8254
Because of the many tasks that they can be used for in
microcomputer systems, programmable timer/counters
are very important for you to learn about. As you read HI AH

through the following sections, pay particular attention


WRITE
O COUNTER GATE 1

to the applications of this device in systems and the gen-


LOGIC
1 OUT 1

eral procedure for initializing a programmable device


such as the 8254. Read lightly through the discussions
of the different counter modes to become aware of the
CLK 2
types of problems that the device can solve for you. You
can later dig into the details of these discussions when GATE 2

you have a specific problem to solve. OUT 2


Another important point to make to you here is that
the discussions of various devices throughout the rest
of this book are not intended to replace the manufactur-
ers" data
sheets for the devices. Many of the programma-
ble peripheral devices we discuss are so versatile that FIGURE 8-13 8254 internal block diagram.
they require almost a small book for each to describe all (Intel Corporation)

238 CHAPTER EIGHT


PIN NUMBER

I At h MUMBI R

1
, 14

SP I N : .;;

A14
-c| cs IRQ
A13
HI
A12 I
.'SI
.',,1
I
i
A11

A10
3^ Hi.'

IR3

.% ii ; i-; i
A9
%

.'.MS IR5
A8 I
20J3 IKi,

IR7
44J3

CAS0
r
3
18 13
A6 i CAS1
H,i !
CAS2
A - 5
14J3
3 %' 11-J I
AO
4 1 -I
A4
I2J3
A3

D0 IR2

D1 IR3

b.l I D2 IR4

SJI D3 IR5
1OJ 1 D4 |R6

12J1 % D5 IR7

14J1 - D6
CAS0
16J1 % D7
— CAS1
46J3 RD
CAS2
48J3 % WR
50J3 % INTA INT
38J1 • 8259Ai2
8J3-
SP/Fn GND
fh: n~i
36J1 %

CASCADED 8259A

CLKO

32J1 GATEO

30J1 OUTO
.% 'K.I1

26J1 CLK1

24J1 GATE1

22J1 OUT1

.'(ill

18J1 CLK2

GATE2

OUT2
8254

74LS30 AND 74LS27 ,N D


Vc| PIN 14
GND = PIN 7
T

FIGURE 8-14 Circuit showing how to add an 8254 and 8259A(s) to an SDK-86
board.

INTERRUPTS AND INTERRUPT SERVICE PROCEDURES 239


programmable. To program the device you send count major section of this chapter. Analyzing the circuit in
bytes and control bytes to the device just as you would Figure 8-14 should help refresh your memory on ad-
send data to a port device. dress decoding.
If you look along the left side of the block diagram in The 74LS138 in Figure 8-14 is used to produce chip
Figure 8- 1 3 you will see the signal lines used to interface select (CS) signals for the 8254, the 8259A, and any
the device to the system buses. A little later we show how other I/O devices we might want to add. We will look first
these are actually connected in a real system. The main at the circuitry around this device to determine the sys-
points for you to note about the 8254 at the moment are tem baseaddress which selects each device.
that it has an 8-bit interface to the data bus. it has a CS In order for any of the outputs of the 74LS138 to be
input which will be asserted by an address decoder asserted, the G1, G2A, and G2B enable inputs must all
when the device is addressed, and that it has two ad- be asserted. The G1 input will be asserted (high) if sys-
dress inputs. AO and A1, to allow you to address one of tem address lines A5, A6, and A7 are all low. The G2A
the three counters or the control word register in the input will be asserted (low) if system address lines A8-
device. A15 are all high. As shown by the truth table in Figure
The right side of the 8254 block diagram in Figure 8-15, these two inputs then will be asserted for a system
8-13 shows the counter inputs and outputs. You can base address of FFOOH. The G2B input of the 74LS138
apply a signal of any frequency from dc to 8 MHz (2.6 will be asserted (low) if the M/IO line is low. as it will be
MHz for the 82531 to the counter clock inputs, labeled for a port read or write operation.
CLK in the diagram. The GATE inputs on each counter Now. remember from Chapter 7. that only one of the Y
allow you to start or stop that counter with an external outputs of the 74LS138 will ever be asserted at a time.
hardware signal. If the GATE input of a counter is high The output asserted is determined by the 3-bit binary
( 1), then the counter is enabled for counting. If the GATE code applied to the A, B. and C select inputs. In the cir-
input is low, the counter is disabled. The resultant fre- cuit Figure
in 8-14 we connected system address line AO
quency
pulse
or from each counter appears on its OUT to the C input, address line A4 to the B input, and ad-
pin. Now let's see how a programmable peripheral device dress line
A3 to the A select input. The truth table in
such as the 8254 is connected in a system. Figure 8-15 shows the system base addresses that will
enable each of the 74LS138 Y outputs. As you will see a
little later, system address lines A1 and A2 are used to
SYSTEM CONNECTIONS FOR AN 8254 TIMER/
select internal parts of the 8254 and 8259.
COUNTER
We connected AO to the C input so that half of the Y
An 8254 is a very useful device to have in a microcom- outputs will be selected for even addresses and half of
puter system, but, in order to keep the cost down, the the Y outputs will be selected by odd addresses. We did
SDK-86 was not designed with one on the board. For a this so that we can equalize loading on the two halves of
real example of how an 8254 is connected in a system, the data bus as we add peripheral devices such as the
we show you here how to add one to an SE^K-86 board. If 8254 and 8259A. To see how this works, note that the
you use wire-wrap headers for connectors )1 and )3, the peripheral devices have only eight data lines. For an
circuitry shown can easily be wire-wrapped on the odd-addressed device we connect these data lines to the
prototyping area of the SDK-86 board. Install the WAIT upper eight system data lines, and for an even-
state jumper to insert one WAIT state, as explained in addressed device we connect these to the lower eight
Chapter 7. A WAIT state is needed because of the added system data lines. By alternating between odd and even
delay of the decoders and buffers. selected outputs as we add peripheral devices, we equal-
Figure 8-14 shows the circuit connections for adding ize loading on the bus as desired.
an 8254 and an 8259A to an SDK-86 board. We discuss As shown by the truth table in Figure 8-15, the system
the 8259A priority interrupt controller (PIC1 in the last base address of the added 8254 is FF01H. Other connec-

Y OUTPUT SYSTEM BASE


A8-A15 A5-A7 A4 A3 A2 A1 AO M/IO DEVICE
SELECTED ADDRESS

1 0 0 0 X X 0 0 0 F F 0 0 8259A =1

1 0 0 1 X X 0 0 1 F F 0 3 8259A =2

1 0 1 0 X X 0 0 2 F F 1 0

1 0 1 1 X X 0 0 3 F F 1 8

1 0 0 0 X X 1 0 4 F F 0 1 8254

1 0 0 1 X X 1 0 5 F F 0 9

1 0 1 0 X X 1 0 6 F F 1 1

1 0 1 1 X X 1 0 7 F F 1 9

ALL OTHER STATES NONE

FIGURE 8-15 Truth table tor 74LSI38 address decoder in Figure 8-14.

240 CHAPTER EIGHT


tlons i" the 8254 arc the system RD and WR lines used lore, we wanted to use system address line AO as an
to enable the 8254 for reading or writing; elghl data input to the address decode]
lines, used to send control bytes, status bytes, and
Add each ol the Internal addresses to the system
count values between the CPU and the 825 l. and system
base address to determine the system address ol
address lines Al and A2, used to select the control regis
each ol the parts ol the device You need to do this so
tei "i one ol the three counters in the 825 i Next we will
that you know to wh.it address to send control
show you how to initialize an 8254 to do some useful
wouls. timer values, etc. Figure 8 Id/j shows the
work foi you.
system add i esses lm the three timers and the con-
trol register ol the 8254 we added to the SDK-86
INITIALIZING A PROGRAMMABLI PERIPHERA1
board Note thai the addresses are all odd.
DEVICE— Till 8254
Look in the data sheet for the device to I the Ion i i.i I ol
When the power is firsl turned on, programmable pe
the control word(s) that you have to send to the de-
ripheral devices such as the 8254 are usually in unde-
vice initialize
in n Foi different devices, inciden-
fined states.
Before you can use them for anything you
tally, the
control word(s) may be referred to as com
have i" Initialize them in the mode you need for your
inand words or mode words. To initialize the 8254
specific application. Initializing these devices is not
you send a control word to the control registei lor
usually difficult, but it is very easy to make errors if you
each counter that you want to use. Figure 8 17
do not do it in a very systematic way. To initialize any
shows the format lor the 8254 control word.
programmable peripheral device you should work your
way through the following series of steps

Determine the system base address for the device.


You do this from the address decoder circuitry or the
SCI SCO RWl RWO
address decoder truth table. From the truth table in
Figure 8-15 the system base address of the 8254 in
our example here is FF01H. C - SELECT COUNTER

SCI SCO
Use the device data sheet to determine the internal
0 0 SELECT COUNTER 0
addresses for each of the control registers, ports,
timers, status registers, etc. in the device. Figure 0 1 SELECT COUNTER 1

8- 16a shows the internal addresses lor the three 1 0 SELECT COUNTER 2

counters and the control word register for the 8254. 1 1 READ BACK COMMAND (SEE READ OPERATIONS)

AO in this table represents the AO input of the device


and A1 represents the A1 input of the device. Note in RW - READ/WRITE
the schematic in Figure 8-14 that we connected sys- RWl RWO
tem address line Al to the AO input, and system ad-
COUNTER LATCH COMMAND (SEE READ
dress line
A2 to the A1 input of the 8254. Among 0 0
OPERATIONS)
other reasons, we did this because, as described be- 0 READ WRITE LEAST SIGNIFICANT BYTE ONLY
1

1 0 READ'WRITE MOST SIGNIFICANT BYTE ONLY

READ/WRITE LEAST SIGNIFICANT BYTE FIRST,


1 1
THEN MOST SIGNIFICANT BYTE

A, A0 SELECTS

0 '
COUNTER 0
M2 Ml MO
0 1 COUNTER 1
0 0 u MODE 0 - INTERRUPT ON TERMINAL COUNT
1 0 COUNTER 2
0 0 1 MODE I - - HARDWARE ONE-SHOT
1 1 CONTROLWORD REGISTER
X 1 0 MODE .! - PULSE GENERATOR

X 1 t MODE 3 - - SQUARE WAVE GENERATOR

t 0 0 MODE 4 - - SOFTWARE TRIGGERED STROBE

t 0 1 MODE 5 - - HARDWARE TRIGGERED STROBE

SYSTEM ADDRESS 8254 PART

F F 0 1 COUNTER 0 BCD

F F 0 3 COUNTER 1 0 BINARY COUNTER 16-BITS


F F 0 5 COUNTER 2 BINARY CODED DECIMAL (BCD) COUNTER (4 DECADESI
1

F F 0 7 CONTROL REG

NOTE: DON'T CARE BITS (X) SHOULD BE 0 TO INSURE


COMPATIBILITY WITH FUTURE INTEL PRODUCTS

FIGURE 8-16 8254 internal addresses and system FIGURE 8-17 8254 control word format. (Intel
addresses, (a) Internal, (b) System. Corporation)

INTERRUPTS AND INTERRUPT SERVICE PROCEDURES 241


5. Construct the control word required to initialize the will then be a square wave with a frequency equal to the
device for your specific application. You construct input clock frequency divided by the count you wrote to
this control word on a bit-by-bit basis. We have the counter. A little later we will discuss and show appli-
found it helpful to actually draw the eight little boxes cationssome
for of the six different modes. First let's
as shown at the top of Figure 8-17 so that we don't finish looking at the control word bits and see how you
miss any bits. (An easy way to draw the eight boxes send the control word and a count to the device.
is to draw a long rectangle, divide it in half, divide The RW1 and RWO bits of the control word are used to
each resulting half in two. and finally divide each specify how you want to write a count to a counter or to
resulting quarter in two.) To help keep track of the read the count from a counter. If you want to load a
meaning of each bit of a control word, write under 16-bit number into a counter, you put Is in both of
each bit the meaning of that bit. A little later we these bits in the control word you send for that counter.
show you how to do this for an 8254 control word. After you send the control word, you send the low byte of
Documentation of this sort is very valuable when the count to the counter address, and then send the
you are trying to debug a program or modify an old high byte of the count to the counter address. In a later
program for some new application. paragraph we show an example of the instruction se-
quence
do tothis. In cases where you only want to load a
6. Finally, send the control word(s) you have made up
new value in the low byte of a counter, you can send a
to the control register address for the device, and
control word with 01 in the RW bits, and then send the
send the starting count to the counter registers.
new low byte to the counter. Likewise, if you only want
Now. Let's take a closer look at the 8254 control
to load a new high bvte value in the counter, you can
word format now to see how you make up one of
send a control word with 10 in the RW bits, and then
these words.
send only the new high byte to the counter.
A separate control word must be sent for each counter You can read the number in one of the counters at any
that you want to use in the device. However, according time. The usual way to do this is to first latch the cur-
In Figure 8- 16a. the 8254 has only one control register rent count in some internal latches by sending a control
address. The trick here is that the control words for all word with 00 in the RW bits. Send another control word
three counters are sent to the same address in the de- with 01. 10 or 11 in the RWbits to specify how you want
vice. You
use the upper two bits of each control word to to read out the bytes of the latched count. Then read the
tell the 8254 which counter you want that control word count from the counter address.
to initialize. For example, if you are making up a control Now. for a specific example, suppose that we want to
word for counter 0 in the 8254 you make the SC1 bit of use counter 0 of the 8254 in Figure 8-14 to produce a
the control word a 0. and the SCO bit a 0. Later we will stable 78.6-kHz square-wave signal for a UART clock by
explain the meaning of the read-back command speci- dividing down the 2.45-MHz PCLK signal available on
fied by
a 1 in each of these bits. the SDK-86 board. To do this we first connect the
Next let's look at the bit labeled BCD in the control SDK-86 PCLK signal to the CLK input of counter 0 and
word. The 16-bit counters in the 8254 are down- tie the GATE input of counter high to enable it for count-
counters. This means that the number in a counter will ing. To
produce 78.6 kHz from 2.45 MHz we have to di-
be decremented by each clock pulse. You can program vide 32
by decimal, so this is the value that we will even-
the 8254 to count down a loaded number in BCD (deci- tually load
into counter 0. First, however, we have to
mal) in
or binary. If you make the DO bit of the control determine the system addresses for the device, make up
word a 0. then the counter will treat the loaded number the control word for counter 0. and send the control
as a pure binary number. For this case the largest num- word.
ber thatyou can load in is FFFFH. If you make the DO bit As shown in Figure 8- 16b the system address for the
of the control word a 1 . then the largest number you can control register of this 8254 is FF07H. This is where we
load in the counter is 9999H. and the counter will count will send the control word. For our control word we want
a loaded number down in decimal (BCD). Actually, be- to select counter 0. so we make the SC1 and SCO bits
cause
theof way the 8254 counts, the "largest" number both O's. We want the counter to operate in square-wave
you can load in for both cases is 0000. but thinking of mode. This is mode 3. so we make the mode bits of the
FFFFH and 9999H makes it easier to remember the dif- control word Oil. Since we want to divide by 32 deci-
ference between
the two modes. mal, we
tell the counter to count down in decimal by
Now let's take a brief look at the mode bits (M2. Ml. making the BCD bit of the control word a 1 . This makes
and MO) in the control word format in Figure 8-17. The our life easier, because we don't have to convert the 32
binary number you put in these bits specifies the effect to binary or hex. Finally we have to decide how we want
that the gate input will have on counting and the wave- to load the count into the counter. Since the count that
iorm that will be produced on the OUT pin. For example, we need to load in is less than 99. we only have to load
if you specify mode 3 for a counter by putting Oil in the lower byte of the counter. According to Figure 8-17,
these 3 bits, the counter will be put in a square-wave the RW1 bit should be a 0 and the RWO bit a 1 for a write
mode. In this mode the output will be high for the first to only the lower byte (LSB). The complete control word
half of the loaded count and low for the second half of then is 000101 1 1 in binary. Here are the instructions to
the loaded count. When the count reaches zero, the orig- send the control word and count to counter 0 of the
inal countis automatically reloaded and the countdown 8254 in Figure 8-14. Note how the bits of the control
repeated. The waveform on the OUT pin in this mode word are documented.

242 CHAPTER EIGHT


MO\ \i . (Million in Control word foi ( ountei 0
cw 1(1
ic. nl w rite I SB only,
mode 5, BCD UTJ
on in 011 I
I I I !__ BCD J\I\TLPJWJ\f\IU\f
! I I countdown
I l I Mode J
I I R/W
I LSB onK
I Select N N N N (J I 0 I I) I 0 I 0 I H I I I
•1 I 3 I 2 I l I 0 I FI I I I
i ountei o

CW 10 LSB - 3
MOV DX, 0FF07H Point at 8254 control registei
OUT DX, AL Send ( ontrol word
uu
MO\ A I , UN Load lower byte ol count
MOV DX, 0FF01H Point to counter 0 count registei JirLTlAAATLrUVir
OUT DX, AL Send count to count register
^ r
Note that since we set the RW bits of the control word for
read write LSB only, we do not have to include instruc-
tionsload
to the MSB of the counter. Programmed in
this way the 8254 will automatically load O's in the N N N N 0|0|0|0|0|0|FF
3 I 2 I 2 I 2 I 1 I 0 I FF
upper byte ol the counter.
If you need to load a count that is larger than 1 byte, CW 10 LSB 3 LSB 2

make the RW bits in the control word both Is. Send the i_ru — l_t
lower byte of the count as shown above. Then send the
high byte of the count to the count register by adding
the instructions:
jiAi^rLnjinrLTLTLr
MOV AL. HIGH BYTE OF COUNT; Load MSB of count
OUT DX. AL : Send MSB to count register

N N N N 0 I 0 I 0 I 0 I 0101 FF
Note that the high byte of the count is sent to the same 3 I 2 I 1 I 2 I 1 I 0 I FF
address that the low byte of the count was sent. For each
counter that you want to use in an 8254. you repeat the NOTE THE FOLLOWING CONVENTIONS APPLY TO ALL MODE

above series of six or eight instructions with the control TIMING DIAGRAMS
1 COUNTERS ARE PROGRAMMED FOR BINARY (NOT BCD)
word and count for the mode that you want. Before COUNTING AND FOR READING/WRITING LEAST
going on with this chapter, review the six initialization SIGNIFICANT BYTE (LSB) ONLY
2 THE COUNTER IS ALWAYS SELECTED (CS ALWAYS LOW).
steps shown at the start of this section to make sure
3. CW STANDS FOR "CONTROL WORD"; CW = 10 MEANS A
these are firmly fixed in your mind. In the next section CONTROL WORD OF 10, HEX IS WRITTEN TO THE COUNTER.
we discuss and show some applications of the different 4 LSB STANDS FOR "LEAST SIGN I FICANT BYTE" OF COUNT.
5. NUMBERS BELOW DIAGRAMS ARE COUNT VALUES.
modes that an 8254 counter can be operated in, but we
THE LOWER NUMBER ISTHE LEAST SIGNIF ICANT BYTE
do not have space there to show all of the steps for each THE UPPER NUMBER IS THE MOST SIGN I F ICANT BYTE

of the modes. SINCE THE COUNTER IS PROGRAMMED TO READ/WRITE


LSB ONLY, THE MOST SIGNIFICANT BYTE CANNOT BE READ.
N STANDS FOR AN UNDEFINED COUNT
VERTICAL LINES SHOW TRANSITIONS BETWEEN
COUNT VALUES
8254 Counter Modes and Applications
As we mentioned previously, an 8254 counter can be
programmed to operate in any one of six different
FIGURE 8-18 8254 MODE 0 example timing diagrams.
modes. The Intel data book uses timing diagrams such
(Intel Corporation)
as those in Figure 8-18 to show how a counter functions
in each of these modes. Since all of these waveforms may
not be totally obvious to you at first glance, we will work
counter is always enabled for counting. The first dip in
our way through some of these to show you how to inter-
the waveform labeled WR represents the control word
pret them. We will also show some uses of the different
being written to the counter. CW = 10 over this dip
counter modes.
indicates that the control word written is 10H. Accord-
ing to
the control word format in Figure 8-17, this
MODE 0— INTERRUPT ON TERMINAL COUNT
means that counter 0 is being initialized for binary
First read the Intel notes at the bottom of Figure 8-18, counting, mode 0. and a read/write of only the LSB.
then take a look at the top set of waveforms in the figure. After the control word is written to the control register.
For this first example the GATE input is held high so the the output pin of counter 0 will go low. The next dip in

INTERRUPTS AND INTERRUPT SERVICE PROCEDURES 243


the WR waveform represents a count of 4 being written The service procedure for this interrupt will contain
to the count register of counter 0. Before this count can instructions which turn on the parking-lot-full sign,
be counted down, it must be transferred from the count close off the main entrance, and return to the mainline
register to the actual counter. If you look at the count program. For this example we don't worry that the
values shown under the OUT waveform in the timing counter decrements from 0000 to FFFFH. because, after
diagram, you should see that the count of 4 is trans- we shut the gate, the counter will not receive any more
ferred into
the counter by the next clock pulse after WR interrupts.
goes high. Each clock pulse after this will decrement the
count by one. When the counter transitions to zero, the
MODE 1 — HARDWARE RETRICCERABLE ONE-
OUT pin will go high. If you write a count N to a counter
SHOT
in mode 0. the OUT pin will go high after JV + 1 clock
pulses have occurred. Note that the counter decrements The basic principle of a one-shot is that when a signal is
from 0000 to FFFFH on the next clock pulse unless you applied to the trigger input of the device, its output will
load some new count into the counter. If the OUT pin is be asserted. After a fixed amount of time the output will
connected to an active high interrupt input of the proc- automatically return to its unasserted state. For a TTL
essor, then
the processor will be interrupted when the one-shot such as the 74LS122. the time that the output
counter reaches zero (terminal count). is asserted is determined by the time constant of a resis-
The second set of waveforms in Figure 8-18 shows tor anda capacitor connected to the device. For an 8254
that if the GATE input is made low. the counter value will counter in one-shot mode the time that the output is
be held. When the GATE input is made high again, the
counter continues to decrement by one for each clock
pulse. The third set of waveforms in Figure 8-18 shows
that if a new count is written to a counter, the new
CW=12 LSB=3
count will be loaded into the counter on the next clock
pulse. Following clock pulses will decrement the new
~i_j~t_t
count until it reaches zero.
As an example of what you can use this mode for, sup- j\i\i\i\j\r\fuu\i\nr
pose that
as one of its jobs we want to use an available
8086 to control some parking lot signs around our elec- JX im
tronics factory.
The main parking lot can hold 1000
cars. \\ Tien it gets full, we want to turn on a sign which
directs people to another available lot. To detect when a
car enters the lot we can use an optical sensor such as N N N N N 0I0I0I 0|FF|0|0
3 I 2 M I 0 FF I 3 I 2
the one shown in Figure 8-10. Each time a car passes
through, this circuit will produce a pulse. We could con-
CW=12 LSB = 3
nect the
signal from this sensor to an interrupt input,
and have the processor count interrupts as we did for "LTLJ
the printed-circuit-board-making machine in a previous
example. However, the less we burden the processor juuwjuuuuumi
with trivial tasks such as this, the more it is available to
do complex work for us. Therefore, we let a counter in an in in
8254 count cars and only interrupt the 8086 when it
has counted 1000 cars.
We connect the output from the optical sensor circuit
r
to the CLK input of. say. counter 1 of an 8254. We tie the N N N N N 0|0|0|0|0|0|0
3I2I1I3I2I1IO
GATE input of counter 1 to +5 V so it will be enabled for
counting. We connect the OUT pin of counter 1 to an
CW=12 LSB = 2 LSB=4
interrupt input on the 8086.
In the mainline program we initialize counter 1 for "L_n_r i__r
mode 0. BCD counting, and read write LSB then MSB
with a control word of 01110011 binary. We want the J\J\fUUUUUU\fUW
counter to produce an interrupt after 1000 pulses from
the
counter.
sensor,
The
so we will
reason
send
that
a count
we want
of 999
to send
decimal
999 instead
to the
of
in JT
1000 is that, as shown in Figure 8-18. the OUT pin will
go high N + 1 clock pulses after the count value is writ-
ten to
the counter. Since we initialized the counter for 0 r FF j FF I 0 I 0
N N N N N
0 I FF I FE I 4 I 3
read write LSB then MSB. we send 99H and then 09H to
the address of counter 1. Note that we initialized the
counter for BCD counting, so we can just send the count
value as a BCD number instead of having to convert it to FIGURE 8-19 8254 MODE 1 example timing diagrams.
hex. (Intel Corporation)

244 CHAPTER EIGHT


asserted low is determined by t In- frequency ol an ap- The bottom set ol wavefoi ms In 1 Igure 8 19 show that
plied clock
and a count loaded Into the countei 111< it you write a new count to .1 count register while the
advantage ol the 8254 approach is thai the output pulse OUT pin is low. the new count will not be loaded into the
width can be changed under program control, and it .1 counter and counted down until the nexl trigger pulse
crystal-controlled clock is used, the output pulse width occurs.
can be very accurately specified. For an example ol the use ol mode 1 we will show you
Figure 8 19 shows some example timing waveforms how to make a circuit winch produces an Interrupt sig
for an 8254 counter In mode I. Let's take a look at the nal it the ac power fails. This circuit could be connei ted
top set ol waveforms. Again the first dip in the WW wave- to the NMI input ol an 8080 to vector to a procedure
form
('presents
1 the control word of 1211 being sent to which saves parameters in battery backed RAM when
the 8254. Use Figure 817 to help you determine how the ac power lails. Figure 8-20 shows a circuit which
this control word initializes the device. You should find uses an optical coupler (LED and a pholot 1ansisl 01
that a control word of 1211 programs countei 0 foi packaged together) to produce logic level pulses at
binary count, mode 1, read/write LSB only. When the power-line frequency. The 74LS14 Inverters sharpen
control word is written to the 8254. the (HO pin goes the edges of these pulses so that they can be applied to
high. the GATE/trigger input of an 8254. For a 00 11/ line fre
The second dip in the WR waveform represents writ- quency, a pulse will be produced every 16.66 ms. Now
ingcount
a to the counter. Note that, because the GATE what we want to do here is to load the counter with a
input is low. the counter does not start counting down value such that the counter will always be retriggered by
immediately when the count is written as it does in the power-line pulses before the countdown is com-
mode 0. For mode 1 the GATE input functions as a trig- pleted.
shown
As by the second set of waveforms in Fig-
ger input.When the GATE/trigger input is made high, ure 8-19.
the OUT pin will then stay low and not send an
the count will be transferred from the count register to interrupt signal to the NMI input of the 8086. If the ac
the actual counter on the next clock pulse. Each follow- power fails, no more pulses come in to the 8254 trigger
ing clockpulse will decrement the counter by one. When input. The trigger input will be left high, and the count-
the counter reaches zero, the OUT pin will go high downbewillcompleted. The 8254 OUT pin will then go
again. In other words, if we load a value of N in the high and interrupt the 8086.
counter, and we trigger the device by making the GATE To determine the counter value for this application,
input high, the OUT pin will go low for a time equal to N just calculate the number of input clock pulses required
clock cycles. The output pulse width is then N times the to produce a countdown time longer than 16.66 ms. for
period of the signal applied to the CEK input. Inciden- example, 20 ms. If we use the 2.4576-MHz PCLK signal
tally,dashed
the sections of the GATE waveforms in Fig- on an SDK-86 board. 20 ms requires 49,152 cycles of
ure 8-19mean that the GATE/trigger input signal can go PCLK. so this is the number we would load in the 8254
low again anytime during that time interval. counter. Since this number is too large to load in as a
The second set of waveforms in Figure 8-19 demon- BCD count, we load it in as C000H, and in the control
strate what
is meant by the term retriggerable. If an- word we tell the 8254 to count the number down in bi-
other trigger
pulse comes before the previously loaded nary.
count has been counted down to zero, the original count
will be reloaded on the next clock pulse. The countdown
MODE 2— TIMED INTERRUPT GENERATOR
will then start over and continue until another trigger
occurs or until the count reaches zero. If trigger pulses In a previous section we described how a real-time clock
continue to come before the count is decremented to of seconds, minutes, and hours could be kept in three
zero, the OUT pin will remain low. memory locations by counting interrupts from a 1-Hz

IN914
AAA

[>H]>>
POWER
TRANSFORMER

FIGURE 8-20 Circuit to produce logic level pulses at power-line frequency.

INTERRUPTS AND INTERRUPT SERVICE PROCEDURES 245


pulse source. We also described how the 1-Hz interrupts to the actual counter. Since the GATE input is high, suc-
could be used to measure off other time intervals. The ceedingpulses
clock will count down this value until it
difficulty with using a 1-Hz interrupt signal is that the reaches one. When the count reaches one, the OUT pin,
maximum resolution of any time measurement is 1 sec- which was previously high, will go low. The falling edge
ond.other
In words, if you use a 1-Hz signal, you can of the next clock pulse will cause the OUT pin to go high
only measure times to the nearest second. To improve again and the original count to be loaded into the
the resolution of time measurements, most microcom- counter again. Successive clock pulses will cause the
puter systemsuse a higher frequency signal such as countdown and load cycle to repeat over and over. If the
1 kHz for a real-time clock interrupt. With a 1-kHz inter- counter is loaded with a number JV. the OUT pin will go
rupt signalthe time resolution is then 1 ms. An 8254 low for one clock cycle every N input clock pulses. The
counter operating in mode 2 can be used to produce a frequency of the output waveform then will be equal to
stable 1 -kHz signal by dividing down the processor clock the input clock frequency divided by N.
signal. Now, for a specific example, suppose that we want to
Figure 8-2 1 shows the waveforms for an 8254 counter produce a 1-kHz signal for a real-time clock from an
operating in mode 2. Let's look at the top set of wave- 8-MHz processor clock signal. To do this we connect the
forms first.
The two dips in the WR waveform represent processor clock signal to the CLK input on one of the
a control word and the LSB of a count being written to 8254 counters and tie the GATE input of that counter
the count register. The next clock pulse after the count high. We initialize that counter for BCD counting, mode
is written will transfer the count from the count register 2, and read/write LSB then MSB. Since we want to di-
vide the
8 MHz by 8000 decimal to get 1 kHz. we then
write 00H to the counter as the LSB. and 80H to the
counter as the MSB.
A question that may occur to you at this point is "How
CW=14 LSB = 3
do I count seconds if the interrupts are coming in every
NP
millisecond?'' The answer to the question is that you set
aside a memory location as a milliseconds counter and
CLK J\IU\fU\fU\IWif\T initialize that location with 1000 decimal (3E8H). The
interrupt service procedure decrements this count each
GATE
time an interrupt occurs and checks to see if the count
OUT — u — u~ is down to zero yet. If the count is not zero, then execu-
tion simply
is returned to the mainline. If the count is
N N N N 0|0|0|0|0|0|0| down to zero, 1000 interrupts or 1 second has passed.
3|2|l [3l2ll l3|
Therefore, the milliseconds counter location is reloaded

CW=14 LSB = 3
with 3E8H. and the seconds-minutes-hours procedure
is called to update the count of seconds. In a similar way
the 1-kHz interrupt service procedure can measure off
several different time intervals that are multiples of
j\j\j\nj\ju\iu\i\r 1 ms.
The middle set of mode 2 waveforms in Figure 8-21
demonstrates that if the GATE input is made low while
the counter is counting, counting will stop. If the GATE
\j~ input is made high again, the original count will be re-
0|0|0|0|0|0|0 loaded the
into counter by the next clock pulse. Suc-
N N N N
ceeding pulses
clock will decrement the loaded count.
The bottom set of mode 2 waveforms in Figure 8-21
CW=14 LSB=4 LSB = 5 show that if a new count is written to the count register,
this new count will not be transferred to the counter
until the the previously loaded count has been decre-

J\J\fU\TUU\J\TLnd~ mented
one.to

MODE 3— SQUARE-WAVE MODE


If an 8254 counter is programmed for mode 3 and an
t_t even number is written to its count register, the wave-
N N N N
0|0|0|0|0|0|0 formthe
on OUT pin will be a square wave. The fre-
quency
the of
square wave will be eqLial to the frequency
of the input clock divided by the number written to the
NOTE A GATE TRANSITION SHOULD NOT OCCUR ONE CLOCK count register. If an odd number is written to a counter
PRIOR TO TERMINAL COUNT
programmed for mode 3. the output waveform will be
high for one more clock cycle than it is low. so the wave-
form will
not be quite symmetrical. Figure 8-22 shows
FIGURE 8-21 8254 MODI 2 example timing waveforms. some example waveforms for mode 3. By now these
(Intel Corporation) waveforms should look quite familiar to you.

246 CHAPTER EIGHT


The top sel ol waveforms show that aftei .1 control
word is written to the control registei and .1 count is
written to the counl registei . the count is transferred to
the counter on tin- next clock pulse. As shown by the
count sequence under the OU1 waveform, each addi
tional (lock pulse decrements the counter by 2. When
the count ts down to '.'. the OU1 pin goes low and the
original count is reloaded. The ( H> I pin stays low while
the loaded count is again counted down by twos When
the count is down to 2, the OU I pin goes high again and
the original count is again loaded into the counter. The
cycle then repeats.
The center set of waveforms in Figure 8-22 shows ITGUR1 H-H Audio speakei buffet foi 82r>4 timer output
what happens il an odd numbei is written to the count Or port.
registei . As you can see from this waveform, the number
of clock cycles for each waveform is still equal to the
number loaded into the count register. However, as we repetitive square-wave-type signal. In a previous section
mentioned above, the clock is high for one more clock we showed how an 8254 counter operating in mode 3
cycle than it is low. can be used to generate the hand rate clock for a USART
The bottom set of waveforms in Figure 8-22 shows such as the 8251A. Mode 3 could also be used to gener
that counting stops il the gate is made low at any time. ate interrupt pulses lor a real-time clock as we described
Alter the GATE input is made high again, the original tor mode 2.
count will be loaded by the next clock pulse. Another use of 8254 counters operating in mode 3 is
Mode 3 can be used lor any case where vou want a as programmable audio tone generators. For this appli-
cation
high-frequency
a clock such as the 2.4576-MHz
PCLK signal on an SDK-86 board is connected to the
counter CLk input, the GATE input is tied high, and the
CW-16 LSB-4
OUT pin is connected to an audio buffer such as that
wr "L_n_r shown in Figure 8-23. This simple buffer allows the out-
putsseveral
of counters to be added together if desired,
J^nJlJTnJTTlAJTnJTflAA
and supplies the current required to drive a small
speaker.
— 1 1— 1 /— L As an example of this application, suppose that you
want to produce a tone that is a musical A of 440 Hz
N N N N 0|0|0|0|0|0|0| 0I0I0I from the 2.4576-MHz PCLK signal. Dividing the PCLK
signal by 5585 will give the desired 440 Hz. Therefore,
CW-16 LSB-5
you simply send a control word which programs a
wr "i_n_r counter for mode 3, read/write LSB then MSB, and BCD
counting. You then write the LSB of 85H and the MSB of
ju\juumrLru\juu\ru\ 55H to the counter. If you want to change the frequency,
all you have to do is write a new count to the count regis-
ter. Witha few programmable counters and some rela-
~\ r ^ r
tively simple
programming you can play your favorite
0I0|0|0|0|0|0| 0I0I0
| N | N | N N 4I2I0I4I242I0I4I2 songs.

CW=16LSB=4 MODE 4— SOFTWARE-TRIGGERED STROBE


^ "\_n_r
This mode and mode 5 are often contused with mode 1.
juu\j\fuu\iuuuu\ru\ but there is an obvious difference. Mode 1 is used to
produce a low-going pulse that is JV clock pulses wide. If
^ r you look at the top set of waveforms for mode 4 in Figure
8-24. you should see that mode 4 produces a low-going
1 r pulse after N + 1 clock pulses. For mode 4 the output
N N N N 0|0|0|0|0|0|0|0|0|0 pulse is low for the time of one input clock pulse and
4I2I4I2I2I2I4I2I4I2
then returns high. In other words, in mode 4 a counter
produces a low-going strobe pulse N + 1 clock cycles
NOTE A GATE TRANSITION SHOULD NOT OCCUR ONE CLOCK
after a count is written to the count register. Mode 4 is
PRIOR TO TERMINAL COUNT
referred to as software-triggered because it is the writ-
ing of
the count to the count register that starts the
process. Note that after the loaded count is counted
FIGURE 8-22 8254 MODE 3 example timing waveforms. down, the counter decrements to FFFFH and then con-
(Intel Corporation) tinues
decrement
to from there.

INTERRUPTS AND INTERRUPT SERVICE PROCEDURES 247


CW=18 LSB = 3 CW=1A LSB=3

~l_tlj i_n_j

j\iu\iu\j\i\rj\i\r j\j\j\j\nj\juu\j\r
in in —
i_r
"U"
N N N N 0 I 0 I 0 I 0 I FF I FF I FF I
3 I 2 I ! I 0 I FF I FE I FD I N N N N N 0 I 0 I 0 I 0 I FF I 0
3 I 2 I 1 I 0 I FF I 3
CW=18 LSB = 3 CW=1A LSB=3

% L_ru "i_n_r

jmj\Fuuu\j\j\j\r juuuuuuuuuiruxr
,n__,n

v_r U~
0 I 0 0 I 0 I 0 I FF
N N N N O|0|O|O|O|0|FF N N N N N N 3 I 2
3l3l3l2l 1 lol FF
CW=1A LSB=3 LSB=5
CW=18 LSB-3 LSB = 2
"L_n_r "LJ"
i_n_r
J\nI\JU\nI^J\l\ru\f\^
j\rjuv\ju\j\rj\t

i_r "LT
N N N N
0 I 0 I 0 I FF N N N N N 0 I 0 I 0 I 0 I FF I FF I 0 I 0
2 I 1 I 0 I FF 3 I 2 I 1 I 0 I FF I FE I 5 I 4

FIGURE 8-24 8254 MODE 4 example timing waveforms. FIGURE 8-25 8254 MODE 5 example timing waveforms.
(Intel Corporation) (Intel Corporation)

Mode 4 can be used in a case where you want to send time. The OUT pin will go low N + 1 clock pulses after
out some parallel data on a port, and then after some the trigger input goes high.
delay send out a strobe signal to let the receiving system The second set of waveforms in Figure 8-25 shows
know that the data is available. that if another trigger pulse occurs during the count-
down time,
the original count will be reloaded on the
next clock pulse and the countdown will start over. The
MODE 5— HARDWARE-TRIGGERED STROBE OUT pin will remain high until the count is finally
counted down. If trigger pulses continue to come before
Mode 5 is used where we want to produce a low-going
the countdown is completed, the OUT pin will continue
strobe pulse some programmable time interval after a
to stay high. Therefore you can use a counter in mode 5
rising-edge trigger signal is applied to the GATE input.
to produce a power fail signal as we showed in the previ-
This mode is very useful when you want to delay a rising
ous discussion of mode 1. Note that for mode 5, how-
edge signal by some amount of time.
Figure 8-25 shows some example waveforms for a ever, OUT
the pin will be high if the power is on and go
low when the power fails.
counter operating in mode 5. For a start let's look at the
The bottom set of waveforms in Figure 8-25 shows
top set of waveforms. As usual we write a control word
that if a new count is written to a counter, the new
and the desired count to a counter. As shown by the
count will not be loaded into the counter until a new
count sequence under the OUT waveform, however, the
trigger pulse occurs.
count does not get transferred to the counter until the
the GATE (trigger) input is made high. When the trigger
USING A NONSYSTEM CLOCK WITH 8254 IN
input is made high the count will be transferred to the
MODES 2 AND 3
counter on the next clock pulse. Succeeding clock
pulses will decrement the counter. When the counter If you are applying a signal which is not derived from the
reaches zero, the OUT pin will go low for one clock pulse system clock to the CLK input of an 8254 (not 8253).

248 CHAPTER EIGHT


ilirn .1 small note In the Intel data sheet Indicates thai Mt A AL, 010000000B I ountei 1 latch command
the GATI Input ol .1 counter must be pulsed low |ust \l< IV DX HI |(i,ll . Point .11 825 l control registe
aftei the count is written to the countei An easy wa\ to OUT li\ AL : Send latch command
do this is to connect the GATE input of the counter loan MOV DX 0FF03H . Poinl al countei I address
otherwise unused output pun pin You can then pulse IN AL, DX . \<iai\ LSB ol I, ii< hed 1 ounl
the GATI by outputting a low and then outputting a MOV All Al . Sax e l.si 1 ol 1.iii hed counl
high to ili.ii pen 1 pin IN AL, DX : Read MSB ol latched count
XCH< All. AL ; I'm count 111 AX

READING 1HI COUN1 FROM AN 8254


COUNTER When ,1 counter latch command is sent, the lati hed
For many counter applications we want to be able to couni is held until it is re, id. When the count is read
read (he current count in the counter. Suppose, foi ex from the latches, the latch outputs return to following
ample, that we arc using an 8254 counter to count the the countei outputs.
cai s coming into a parking lot as we did in our example The third method of reading a stable counl from a
for modi' 0 above. In that case we used the counter to counter is to latch the count with a read-hack com
produce an interrupt when the parking lot was full, so mand. This method is available in the 8254, but not in
we could shut the gate. Now further suppose that as the 8253. It is essentially an enhanced version ol the
part of a traffic flow study we want to find out how many counter latch command approach described in the pre-
cars have come into the lot by 7:30 a.m. An interrupt- ceding paragraphs.
driven real-time clock procedure can. at 7:30 a.m.. call a Figure 8-26 shows the format for the 8254 counter
procedure which reads in the current count from the read-back command word. It is sent to the same address
counter. Since the counter was initially loaded with that other control words are for a particular 8254. The
1000 decimal and is being counted down as cars come Is in bits D7 and Db identify this as a read-back com-
in, we can simply subtract the current count from 1000 mand word.
To latch the count on a counter you put a 0
to determine how many cars have come in. in bit D5 of the control word and put a 1 in the bit posi-
The counters in an 8254 have latches on their out- tion thatcorresponds to that counter in the control
puts Whenyou read the count from a counter, what you word. The advantage of this control word is that you can
are actually reading is the data on the outputs of these latch one. two. or all three counters by putting 1 s in the
latches. These latches are normally enabled during appropriate bits. Once a counter is latched, the count is
counting so that the latch outputs just follow the read as shown in the example program above. Alter
counter outputs. If you try to read the count while the being read, the latch outputs return to following the
counter is counting, the count may change between counter outputs.
reading the LSB and the MSB. This may give you a If a read-back command word with bit D4 = 0 is sent

strange count. To read a correct count, then, you must to an 8254. the status of one or more counters will be
in some way stop the counting or latch the current latched on the output latches. Consult the Intel data

count on the output of the latches. There are three sheet for further information on this latched status.
major ways of doing this. The preceding sections have shown how 8254
The first is to stop counting by turning off the clock counters can be used to do a wide variety of tasks
signal or making the GATE input low with external hard- around microcomputers. Many of these applications
ware. This
method has the disadvantages that it re- produce an interrupt signal which must be connected to
quires external
hardware and that a clock pulse which an interrupt input on the microprocessor. In the next
occurs while the clock is disabled will obviously not be section we show how a priority interrupt controller de-
counted. vice, Intel
the 8259A, is used to service multiple inter-
The second way of reading a stable value from a rupts.
counter is to latch the current count with a counter
latch command, and then read the latched count. A
counter is latched by sending a control word to the con-
trol register address in the 8254. If you look at the for-
mat for
the 8254 control word in Figure 8-17 you should
see that a counter latch command is specified by mak- AO. Al = 11 CS 0 RD 1 WR 0

ing theRVV1 and RWO bits both 0. The SCI and SCO bits D7 D6 D5 D4
specify which counter we want to latch. The lower 4 bits
1 1 COUNT STATUS tin ;% CNT 1 CN1 n 0
of the control word are "don't cares" for a counter latch
command word so we usually make them O's for simplic-
D6: 0 - LATCH COUNT OF SELECTED COUNTERS(S)
ity. As
an example, here is the sequence of instructions
D4: 0 = LATCH STATUS OF SELECTED COUNTER(S)
you would use to latch and read the LSB and MSB from
D3: 1 = SELECT COUNTER 2
counter 1 of the 8254 in Figure 8-14. We assume that
D,: 1 = SELECT COUNTER 1
the counter was already programmed for read/write LSB
D,: 1 -- SELECT COUNTER 0
then MSB when the device was initialized. If the counter
D0 RESERVED FOR FUTURE EXPANSION, MUST BE 0
was programmed for only LSB or only MSB, then only
that bvte can be read. flGURE 8-26 8254 read-back control word format.

INTERRUPTS AND INTERRUPT SERVICE PROCEDURES 249


Multiple Interrupts and the 8259A Priority 5. Send out two interrupt acknowledge pulses on its
Interrupt Controller INTA pin. The INTA pulses tell some external hard-
ware device
such as an 8259A to send the desired
Previous sections of this chapter show how interrupts
interrupt type to the 8086.
can be used for a variety of applications. In a small sys-
tem, for
example, we might read ASCII characters in 6. When the 8086 receives the interrupt type from the
from a keyboard on an interrupt basis; count interrupts external device, it will multiply that interrupt type
from a timer to produce a real-time clock of seconds, by 4 to produce an address in the interrupt pointer
minutes, and hours; and detect several emergency or table.
job-done conditions on an interrupt basis. Each of these
7. From that address and the three following addresses
interrupt applications requires a separate interrupt
the 8086 gets the IP and CS values for the start of
input. If we are working with an 8086, we have a prob-
the interrupt service procedure. Once these values
lem here because the 8086 has only two interrupt in-
are loaded into CS and IP. the 8086 will then execute
puts. NMI
and 1NTR. If we save NMI for a power failure
the interrupt service procedure.
interrupt, this leaves only one interrupt input for all the
other applications. For applications where we have in-
terruptsmultiple
from sources such as this we use an Now if you look at the internal block diagram of the
external device called apriority interrupt controller (PIC) 8259A in Figure 8-27, I think you will be able to start
to "funnel" the interrupt signals into an interrupt input seeing how it fits into the INTR operation. First notice
on the processor. In this section we show how a com- the 8-bit data bus and control signal pins in the upper
mon PIC,the Intel 8259A. is connected in an 8086 sys- left corner of the diagram. The data bus allows the 8086
tem, how it is initialized, and how it is used to handle to send control words to the 8259A and read a status
interrupts from multiple sources. word from the 8259A. The RD and WR inputs control
these transfers when the device is selected by asserting
8259A OVERVIEW AND SYSTEM CONNECTIONS its chip select (CS) input low. The 8-bit data bus also
allows the 8259A to send interrupt types to the 8086.
To show you how an 8259A functions in an 8086 system
Next notice the eight interrupt inputs labeled IR0-IR7 on
we first need to review how the 8086 INTR input works.
the right side of the diagram. If the 8259A is properly
Remember from a discussion earlier in this chapter that
enabled, an interrupt signal applied to any one of these
if the 8086 interrupt flag is set and the INTR input re-
inputs will cause the 8259A to assert its INT output pin
ceives
higha signal, the 8086 will:
high. If this pin is connected to the INTR pin of an 8086
and if the 8086 interrupt flag is set, then this high sig-
1. Push the flags on the stack.
nal will
cause the previously described INTR response.
2. Clear the IF and TF. The INTA input of the 8259A is connected to the INTA
output of the 8086. The 8259A uses the first INTA pulse
3. Push the return address on the stack.
from the 8086 to do some activities which depend on the
4. Put the data bus in the input mode. mode that it is programmed in. When it receives the sec-

DATA

o BUS
BUFFER
o
CONTROL LOGIC

JUL H
READ/
WRITE
LOGIC
%IR2

IR3

• IR4

%IR5
% (Hi

%IR7
CASO-
CASCADE

CAS 1 % BUFFER;
COMPARATOR
CAS 2 % o INTERRUPT MASK
(MR)
REG

SP/EN %

FIGURE 8-27 8259A internal block diagram. (Intel Corporation)

250 CHAPTERI IGH1


ond INTA pulse from the 8086, the 8259A outputs an service procedure, an interrupl signal arrives al the IK.'
Interrupl type on the 8 bil data bus as shown In Figure input ol the 8259A Since we assumed foi this example
8 i. rhe Interrupl type thai II sends to the 8086 is de that IK.' was unmasked, hit 2 ol tin interrupl request
termlned by the IK inpul thai received an interrupt sit; i i ;ti i will be set. The priority resolvei will detei i th il
nal ami by a number you send the 8259A when you ini tins bit m the IKK is set .a hi mal i i di i i lion whethei to
tialize it. rhe poinl here is thai the 8259A funnels" si nd anothei interrupt signal to the 8086. To make the
Interrupt signals from up to eighl different sources into decision, the priority resolvei looks al the in service reg
the 8086 IN IK input, and il sends the sum, a spe< ified ister. 11 a highei priority bit in the 1SK is set. then a
interrupt type for e.ieh ol the eighl interrupl inputs. higher priority interrupt is being serviced, I he priority
At this point the question may occui to you, "What resolvei will wail until the highei priority bil in the isk
happens it interrupt signals appear at, for example. IK.? is icset before sending an interrupt signal to the 8086
and IR4 at the same time?" In the/ixed priority mode for the new interrupl input. II the priority resolvei hods
that the 8259A is usually operated iii. the answer to this that the new interrupt has a higher priority than the
question is quite simple. In tins mode the IKII input has highest priority interrupt currently being serviced, it
the highest priority (mosl important), the IKl input the will set the appropriate bil in the ISK and activate the
next highest, and so on down to IK~ which has the low- circuitry which sends a new INT signal to the 8086. Foi
est priority. What this means is that it two interrupt our example here. 1K2 has a highei priority than IR4 so
signals occur at the same time, the 8259A will service the priority resolver will set bit 2 of the ISK and acl ivate
the one with the highest priority first, assuming that the circuitry, which sends a new INT signal to the 8086.
both inputs are unmasked (enabled) in the 8259A. II the 8086 INTR input was reenabled with an Si I in-
Now let's look again at the block diagram of the 8259A struction
the atstart of the IK4 service procedure, as
m Figure 8-27 so we can explain in more detail how the shown in Figure 8 28a. then this new INI signal will
device will respond to multiple interrupt signals. In the interrupt the 8086 again. When the 8086 sends out a
block diagram note the lour boxes labeled interrupt re-
quest register (IRR), iuterrtipt mask register (1MR). in-
service register (ISR), and priority resolver. The opera- INITIALIZE 8259A
tionthese
of lour functional blocks is quite logical. UNMASK IR2, I R4
STI
The interrupt mask register is used to disable (mask) IR4 IR2
PROCEDURE PROCEDURE
or enable (unmask) individual interrupt inputs. Each
bit in this register corresponds to the interrupt input
with the same number. You unmask an interrupt input
bv sending a command word with a 0 in the bit position
that corresponds to that input. EOI
The interrupt request register keeps track of which COMMAND
IRET
interrupt inputs are asking for service. If an interrupt
input is unmasked, and has an interrupt signal on it.
then the corresponding bit in the interrupt request reg-
ister will
be set.
The in-service register keeps track of which interrupt
inputs are currently being serviced. For each input that INITIALIZE 8259A
UNMASK IR2, IR4
is currently being serviced, the corresponding bit will be STI
set in the in-service register. An example will show how PROCEDURE
the priority resolver acts as a judge in the middle of all
this.
Suppose that IR2 and IR4 are unmasked and that an
interrupt signal comes in on the IR4 input. Since IR4 is
EOI COMMAND
unmasked, bit 4 of the interrupt request register will be IRET
set. The priority resolver will detect that this bit is set
and see if any action needs to be taken. To do this it IR2
PROCEDURE
checks the bits in the in-service register (ISRI to see if a
higher priority input is being serviced. If a higher prior-
ity inputis being serviced as indicated by a bit being set
for that input in the ISR, then the priority resolver will
take no action. If no higher priority interrupt is being EOI COMMAND
serviced, then the priority resolver will activate the cir- IRET

cuitry which sends an interrupt signal to the 8086.


When the 8086 responds with INTA pulses, the 8259A
will send the interrupt type that we specified for the IR4
input when we initialized the device. The 8086 will use FIGURE 8-28 8259A and 8086 program flow for IR4
the tvpe number it receives to find and execute the in- interrupt followed by IR2 interrupt, (a) Response with
terrupt service
procedure we wrote for the 1R4 interrupt. INTR enabled in IR4 procedure, (b) Response with INTR
Now. suppose that while the 8086 is executing the IR4 not enabled in IR4 procedure.

INTERRUPTS AND INTERRUPT SERVICE PROCEDURES 251


second INTA pulse in response to this interrupt, the pin. The 8259A connected directly into the 8086 INTR
8259A will send it the type number lor the IR2 service pin is referred to as the master. The INT pin from the
procedure. The 8086 will use the received type number other 8259A connects into an IR input on the master.
to find and execute the IR2 service procedure. This secondary or cascaded device is referred to as a
At the end of the 1R2 procedure we send the 8259A a slave. Note that the INTA signal from the 8086 goes to
command word that resets bit 2 of the in-service register both the master and to the slave devices.
so that lower priority interrupts can be serviced. After Each 8259A has its own addresses so that command
that, an IRET instruction at the end of the IR2 procedure words can be written to it and status bytes read from it.
sends execution back to the interrupted IR4 procedure. For the cascaded 8259A in Figure 8-14, the two system
At the end of the IR4 procedure we send the 8259A a I/O addresses will be FF08H and FFOAH.
command word which resets bit 4 of the in-service regis- The cascade pins (CASO, CAS1, and CAS2) from the
ter so
that lower priority interrupts can be serviced. An master are connected to the corresponding pins of the
IRET instruction at the end of the IR4 procedure returns slave. For the master these pins function as outputs,
execution to the mainline program. This all sounds very and for the slave device they function as inputs. A fur-
messy, but it is really just a special case of nested proce- ther difference between the master and the slave is that
dures. Incidentally, if the IR4 procedure did not on the slave the SP/EN pin is tied low to let the device
reenable the INTR input with an STI instruction, as know that it is a slave.
shown in Figure 8-28b, the 8086 would not respond to Briefly, here is how the master and the slave work
the IR2-caused INT signal until it finished executing the when the slave receives an interrupt signal on one of its
IR4 procedure. We can't describe all of the possible IR inputs. If that IR input is unmasked on the slave and
cases, but the main point here is that the 8086 and the if that input is a higher priority than any other inter-
8259A can be programmed to respond to interrupt sig- rupt level
being serviced in the slave, then the slave will
nals frommultiple sources in almost any way you want send an INT signal to the IR input of the master. If that
them to. Now, before we show you how to initialize and IR input of the master is unmasked and if that input is a
write programs for an 8259A, we will show you more higher priority than any other IR inputs currently being
about how it is connected in microcomputer systems. serviced, then the master will send an INT signal to the
8086 INTR input. If the 8086 INTR is enabled, the 8086
will go through its INTR interrupt procedure and sends
8259A SYSTEM CONNECTIONS AND
out two INTA pulses to both the master and the slave.
CASCADING
The slave ignores the first interrupt acknowledge pulse.
Figure 8-14 shows how an 8259A can be added to an When the master receives the first INTA pulse, it outputs
SDK-86 board. As shown by the truth table in Figure a 3-bit slave identification number on the CASO, CAS1,
8-15. the 74LS138 address decoder will assert the CS and CAS2 lines. (Each slave in a system is assigned a
input of the 8259A when an I/O base address of FFOOH 3-bit ID as part of its initialization. ) Sending the 3-bit ID
is on the address bus. The AO input of the 8259A is used number enables the slave. When the slave receives the
to select one of two internal addresses in the device. second INTA pulse from the 8086, the slave will send the
This pin is connected to system address line A1, so the desired interrupt type number to the 8086 on the eight
system addresses for the two internal addresses are data lines.
FFOOH and FF02H. The eight data lines of the 8259A are If an interrupt signal is applied directly to one of the IR
always connected to the lower half of the 8086 data bus inputs on the master, the master will send the desired
because the 8086 expects to receive interrupt types on interrupt type to the 8086 when it receives the second
these lower eight data lines. RD and WR are connected to INTA pulse from the 8086.
the system RD and WR lines. INTA from the 8086 is con- Now that we have given you an overview of how an
nected
INTA
to on the 8259A. The interrupt request sig- 8259A operates and how 8259As can be cascaded, the
nal. INT,
from the 8259A is connectedjo the INTR input initialization command words for the 8259A should
of the 8086. The multipurpose SP/EN pin is just tied make some sense to you.
high because we are only using one 8259A in this sys-
tem. Since
we are not cascading any slave 8259As on the
INITIALIZING AN 8259A
IR inputs, the cascade lines (CASO. CAS1. and CAS2) can
be left open. The eight IR inputs are available for inter- Earlier in this chapter, when we showed you how to ini-
rupt signals. Unused IR inputs should be tied to ground tialize
8254,
an we listed a series of steps you should go
so that a noise pulse cannot accidentally cause an inter- through to initialize any programmable device. To re-
rupt.a Inlater section we will show you how to initialize fresh your
memory of these very important steps we will
this 8259A, but first we need to show you how more work quickly through them again for the 8259A.
than one 8259A can be added to a system The first step in initializing any device is to find the
The dashed box on the right side of Figure 8- 14 shows system base address for the device from the schematic
how another 8259A could be added to the SDK-86 sys- or from a memory map for the system. In order to have a
tem give
to 15 interrupt inputs. If needed, an 8259A specific example here, we will use the 8259A shown in
could be connected to each of the eight IR inputs of the Figure 8-14. The base address for the 8259A in this sys-
original 8259A to give a total of 64 interrupt inputs. temFFOOH.
is
Note that since the 8086 has only one INTR input, only The next step is to find the internal addresses for the
one ol the8259A INT pins is connected to the 8086 INTR device. For an 8259A the two internal addresses are se-

252 CHAPT1K IK, III


11,

0 A •\ •\ 1 LTIM ADI SNGL h 1

1 ICW4 NEEDI l)
ICW4 NEEDED

1 SINGLE
0 CASCADE MODE

CALL ADDRESS INTERVAL


1 INTERVAL OF 4
0 INTERVALOF8

1 LEVEL TRIGGERED MODE


0 EDGE TRIGGERED MODE

ArAb OF INTERRUPT
VECTOR ADDRESS
(MCS-80/85MODE ONLY)

1
V, V. Ax A'X V, A10 Ag A.
15-A8 OF INTERRUPT
VECTOR ADDRESS
(MCS80'85 MODE!
T. T, OF INTERRUPT
VECTOR ADDRESS
ICW3 (MASTER DEVICE) (8086,8088 MODE)

D. Dj Dj

1 | s SL, I s6 I s4 s3 I s I s. s0
IR INPUT HAS A SLAVE
IR INPUT DOES NOT HAVE
A SLAVE

ICW3 (SLAVE DEVICE)

1 0 0 0 0 11 ID, ID, ID„

OA 1
D4
1 ;
0 0 SFNM BUF M S AEOI MPM
8086/8088 MODE
MCS-80'85 MODE

AUTO EOI
NORMAL EOI

NON BUFFERED MODE

BUFFERED MODE/SLAVE

BUFFERED MODE/MASTER

NOTE 1: SLAVE ID IS 1 SPECIAL FULLY NESTED


EQUAL TO THE MODE
CORRESPONDING 0 NOT SPECIAL FULLY
MASTER IR INPUT NESTED MODE

FIGURE 8-29 8259A initialization command word formats and sending order, (a)
Formats, (b) Sending order and requirements. (Intel Corporation)

INTERRUPTS AND INTERRUPT SERVICE PROCEDURES 253


lected by a high or a low on the AO pin. In the circuit in 8259A will send 00100001 binary or 33 decimal and so
Figure 8-14 the AO pin is connected to system address on for the other IR inputs. In any ICW2 you send the
line A1 , so the internal addresses correspond to 0 and 2. 8259A, the lowest three bits must always be O's. because
Next you add the internal addresses to the base ad- the 8259A automatically supplies these bits to corre-
dress the
for device to get the system address for each spond
theto number of the IR input.
internal part of the device. The two system addresses for Since we are not using a slave in our example, we
this 8259A then are FFOOH and FF02H. don't need to send an ICW3. If you are using a slave
Now look at Figure 8-29a for the format of the com- 8259A in a system, you have to send an ICW3 to the
mand words
that must be sent to this device to initialize master to tell it which IR inputs have slaves. The master
it. The sight of all of these command words may seem has to be told this so that it knows for which IR input
overwhelming at first, but taken one at a time they are signals it has to send out a slave ID number on the
quite straightforward. To help you see which initializa- CASO. CAS1, and CAS2 lines. You have to send an ICW3
tion command words (ICWs) are needed for various to a slave 8259A to give it an ID number. The ID number
8259A applications. Figure 8-29b shows this in flow- you give a slave is equal to the IR input of the master
chart form.
According to this flowchart an 1CW1 and an that its INT output is connected to. When the master
ICW2 must be sent to any 8259A in the system. If the sys- sends out an ID number on the CAS lines, the slave will
tem hasany slave 8259As (cascade model then an 1CW3 recognize its ID number and output the desired type
must be sent to the master, and a different ICW3 must number to the 8086 when it receives an INTA pulse.
be sent to the slave. If the system is an 8086, or if you For our example here, the only reason we need to send
want to specify certain special conditions, then you have an ICW4 is to let the 8259A know that it is operating in
to send an ICW4 to the master and to each slave. Now an 8086 system. We do this by making bit DO of the word
let's look at the formats for the different ICWs. a 1. Another interesting bit in this command word is
The first thing to notice about the the ICW formats in D1, the automatic end-of-interrupt bit. If this bit is set
Figure 8-29a is that the bit labeled AO on the left end of in ICW4. the 8259A will automatically reset the in-serv-
each of these is not part of the actual command word. ice register bit for the interrupt input that is being re-
This bit tells you the internal address that the control sponded
whento the second interrupt acknowledge
word must be sent to. The AO = 0 next to ICW1. for ex- pulse is received. The effect of this is that the 8259A will
ample, tells
you that ICW1 must be sent to internal ad- then be able to respond to an interrupt signal on a lower
dresswhich
0, for our 8259A corresponds to system priority IR input. In other words, a lower priority inter-
address FFOOH. rupt input
could then interrupt a higher priority proce-
The next step in the initialization procedure is to dure. Since
we don't want automatic end of interrupt,
make up the control words. The least-significant bit of the ICW4 for our example here is 00000001.
ICW1 tells the 8259A whether it needs to look for an In addition to the initialization command words
ICW4 or not. Since we are using the device in an 8086 shown in Figure 8-29a, the 8259A has a second set of
system we need to send ICW4. Therefore we make bit DO command words called operation command words or
a 1. We only want to use one 8259A for now, so we make OCWs. These are shown in Figure 8-30. An OCW1 must
bit D1 a 1. When used with an 8086. bit D2 is a don't be sent to an 8259A to unmask any IR inputs that you
care, so we make it a 0. Bit D3 is used to specify level- want it to respond to. For our example here let's assume
triggered mode or edge-triggered mode. In level- that we only want to use IR2 and IR3. Since a 0 in a bit
triggered mode, service will be requested whenever a position of OCW1 unmasks the corresponding IR input.
high level is present on an IR input. In edge-triggered we put O's in these two bits and Is in the rest of the bits.
mode, a signal on an IR input must go from low to high Our OCW1 then is 111110011.
and stay high until serviced. We usually use the edge- OCW2 is mainly used to reset a bit in the in-service
triggered mode so that a signal such as a square wave register. This is usually done at the end of the interrupt
will not cause multiple interrupts. Making bit D3 a 0 service procedure, but it can be done at any time in the
does this. Bit D4 has to be a 1. For operation in an 8086 procedure. The effect of resetting the ISR bit for an inter-
system, bits D5, D6, and D7 are don't cares, so we make rupt levelis that once the bit is reset, the 8259A can
them O's for simplicity. The ICW1 for our example here then respond to interrupt signals of lower priority. In
then is 0001001 1. small systems we usually use the nonspecific end-of-
In an 8086 system ICW2 is used to tell the 8259A the interrupt command word. The OCW2 for this is
type number to send in response to an interrupt signal 00100000. When the 8259A receives this OCW it will
on the IRO input. In response to an interrupt signal on automatically reset the in-service register bit for the IR
some other IR input, the 8259A will automatically add input currently being serviced. If you want to reset a
the number of the IR input to this base number and specific ISR bit. you can send the 8259A an OCW2 with
send the result to the 8086 as the type number for that 011 in bits D7. D6. and D5, and the number of the ISR
input. Because 8086 interrupt types 0-31 are either bit you want to reset in the lowest 3 bits of the word. You
dedicated or reserved, type 32 (decimal) is the lowest can also use OCW2 to tell the 8259A to rotate the priori-
type number available for us to use. If we send the ties the
of IR inputs so that after an IR input is serviced,
8259A an ICW2 of 00100000 binary or 32 decimal, the it drops to the lowest priority. If you are interested, con-
8259A will send this number as the type to the 8086 in sult theIntel data sheet for more information on this
response to an IRO interrupt. For an IR 1 input the and on the use of OCW3.

254 CHAPTER EIGHT


Now that we have made up the required ICWs and Is to Initialize the SDK-86 system In Figure 8 14 for gen
OCWs the next step is to write the Instructions to send eratlng a real time clock of se< onds, minutes, and houi
these command words to the 8259A from a I kHz Interrupt signal, and foi reading ASCII
Figure 8-31 shows an 8086 assemblj language pro codes from .i keyboard on an interrupt basis. This pro
gram which shows how to Initialize an 8259A and com gram assumes thai the 2.4576-MHz PCLK signal on the
bines main' of the concepts ol tins chapter. You can use board is connected to the ( I K input % inter o.
this program .is .1 pattern for writing programs whii h the (.All input ol the 8254 countei 0 is tied high, and
service several interrupts. The purpose ol this program the ( >i I pin of countei 0 is connected to the IRO input ol

t M7 M6 M5 M4 M3 M2 M1 MO
INTERRUPT MASK
J L 1 MASK SET
0 - MASK RESET

A0 0 D6 Dh D„ D, U . D, D,

1% R SL EOI 0 0 L, L, t-o

NON-SPECIFIC EOI COMMAND


END OF INTERRUPT
SPECIFIC EOI COMMAND
ROTATE ON NON-SPECIFIC EOI COMMAND

ROTATE IN AUTOMATIC EOI MODE (SET) AUTOMATIC ROTATION

ROTATE IN AUTOMATIC EOI MODE (CLEAR)

"ROTATE ON SPECIFIC EOI COMMAND


SPECIFIC ROTATION
•SET PRIORITY COMMAND

NO OPERATION
•LO-L2 ARE USED

OCW3
D,

READ REGISTER COMMAND

READ IR REG ON READ IS REG ON


NEXT RD PULSE NEXT RD PULSE

1 -^POLL COMMAND 0 NO POLL COMMAND

SPECIAL MASK MODE

RESET SET
SPECIAL MASK SPECIAL MASK

FIGURE 8-30 8259A operational command words. (Intel Corporation)

INTERRUPTS
AND INTERRUPT
SERVICE
PROCEDURES 255
page .132
-.8086 PROGRAM
FRAGMENT
TO SHOWINITIALIZATION OF INTERRUPTJUMP TABLE,
; 8259A, AND COUNTER0 OF 8254.

AINT.TABLE WORD PUBLIC


SEGMENT
TYPE.64 OH 2 DUP(0 ",reserve space for clock proc addr
TYPE.65 DU 2 DUPfO '.not used in this prograa
TYPE~66 ow 2 DUPIO ".reserve space for keyboard proc addr
AINT.TABLE ENDS

DATA_HERE WORD
SEGMENT PUBLIC
SECONDS DB 0
MINUTES DB 0
HOURS DH 0
INTCOUNT DU 03E8H ;1 kHz interrupt counter
KEYJUF DB IOO DUP(O) -.Buffer for 100 ASCII chars
DATA_HERE ENDS

STACK_HERE SEGMENT no STACK directive, because


DU 100 DUP<0) Mill be using EXE2BIN
TQP.STACK LABEL UORD

STACK.HERE ENDS

CODE_HERE SEGMENTPUBLIC
ASSUME CS:CODE_HERE, DS:AINT.TABLE,SS:STACK_HERE
(initialize stack segaent register, stack pointer, data segaent
MOV AX, STACK_HERE
MOV SS, AX
MOV SP, OFFSETTOP_STACK
MOV AX, AINTTABLE
MOV DS, AX
idefine the addresses for the interrupt service procedures
MOV TYPE_64+2,SEGCLOCK put in clock proc addr
MOV TYPE_64, OFFSETCLOCK
MOV TYPE_66+2,SEGKEYBOARD put in keyboard proc addr
MOV TYPE.66, OFFSETKEYBOARD
; initial l ze data segaent
ASSUME DS:DATA_HERE
MOV AX, DATAHERE
MOV DS, AX
Unitialize 8259A
MOV AL, 00010011B edge triggered, single ICU4
MOV DX, OFFOOH point at 8259A control
OUT DX, AL send ICW1
MOV AL, 01000000B type 64 is first 8259A type
MOV DX, 0FF02H point at ICW2address
GUI DX, AL send ICW2
MOV AL, 0000000 IB I CHt, 8086 aode
OUT DX, AL send ICU4
MOV AL, 11111010B 0CU1 to unaask IRO and IR2
OUT DX, AL send 0CW1

(initialize 8254 counter 0 for 1 kHz output


; 8254 coemand word for counter 0, LSB then MSB, sguare wave, BCD
MOV AL, 001 101 1 IB
MOV DX, 0FF07H ; point at 8254 control addr

FIGURE 8-31 Assembly language program showing initialization of 8086, 8259A,


and 8254 for real-time clock and keyboard interrupt procedures.

256 CHAI'TFR tIGHT


oin DX, AL ; send counter 0 cottand word
NOV flL, 58H ; Load LSB of count
NOV DX, OFF01H ! point at counter 0 data addr
Uli! DX, AL ; send LSB of count
NOV AL, 2<>H ; load MSB of count
OUT DX, AL ; send MSB of count
lenable intern ipt input of 8086
STI
HERE: JMP HERE wait for interrupt
CLOCK PROC FAR
clock procedure intructions
NOV At . 00100000B 0CW2for non-specific E01
NOV DX, OFFOOH address for 0CW2
OUT DX, AL send 0CW2for end of interrupt
IRET
CLOCK ENDP

KEYBOARD PROC f AR

; keyboard proc intructions


MOV Al . 001000008 ; 0CW2for non-specific EOI
MOV DX, OFFOOH ; address for QCW2
OUT DX, AL i send 0CW2 for end of interrupt
IRET
KEYBOARDENDP

CODE_HERE
ENDS
END

FIGURE 8-3 I (continued)

the 8259A. The program further assumes that the The next thing we do in our program is to declare a
keypressed strobe from the ASCII keyboard is connected data segment and set aside some memory locations for
to the IR2 input of the 8259A. seconds count, minutes count, hours count, and 100
In the program we first declare a segment called characters read in from the keyboard. After the data seg-
AINT TABLE to reserve space for the pointers to the in- ment set
we up a stack segment.
terrupt procedures.The statement TYPE 64 DW 2 At the start of the mainline program we initialize the
DUP(O), for example, sets aside a word space for the off- stack segment register, the stack pointer register, and
set of
the the type 64 procedure and a word for the seg- the data segment register. We will be using interrupt
ment base
of the procedure. Because of the way the IBM type 64 for a real-time clock and type 66 will point at the
MASM, LINK, and EXE2BIN programs work, it is start of the procedure that reads ASCII codes from the
necesssary to do a little trick to get the AINT_TABLE seg- keyboard. We will not be using a type 65 interrupt in
ment locatedat absolute address 0000:0 lOOH where it this program. The next four instructions are needed to
must be for the program to work correctly. The trick is place the addresses of the clock and keyboard proce-
simply to give the segment which sets aside space for dures
thein type 64 and type 66 locations in the inter-
these pointers a name which alphabetically comes be- rupt pointertable. Later we initialize the 8259A so that
fore the
names of the other segments in your program, type 64 corresponds to its IRO input and type 66 corre-
just as we named our segment here AINT_TABLE. When spondsitsto IR2 interrupt. We then ASSUME
you MASM and LINK your program, the result is a relo- DS:DATA_HERE and initialize DATA HERE as the data
catable object
code (.EXE) program which the computer segment.
will load into any convenient location to run. The .EXE For the example here we have chosen type 64 to corre-
form of the program will not get put at the required ab- spond
anto IRO interrupt, so the needed ICW2 will be
solute locations.
To solve this problem you process your OlOOOOOO. We then initialize the 8259A with the com-
.EXE program with a program called EXE2BIN. When mand wordswe worked out above and this new ICW2.
run. this program prompts you to put in a segment Note that those command words shown with a 0 as the
fixup (absolute starting address) for your program. If AO bit in Figures 8-29 and 8-30 are sent to system ad-
you give a segment fixup value of OOIOH, EXE2BIN will dress FFOOH
and those command words shown with a 1
produce a .BIN file which will load at absolute address ;is Die AO bit are sent to system address FF02H.
0000:0100H. Since AINT TABLE is alphabetically first, The next section of the mainline program initializes
it will be located starting at this address, which is the counter O of the 8254 for mode 2. BCD countdown, and
correct absolute address for the 8086 type 64 interrupt. read'write LSB then MSB. To produce a 1-kHz signal

INTERRUPTS AND INTERRUPT SERVICE PROCEDURES 257


from the 2.4576-MHz PCLK we then write a count of Interrupt— INTR
2458 to counter 0. This will not give exactly 1 kHz. but it
Nonmaskable interrupt — NMI
is as close as we can get with this particular input clock
frequency. The PCLK frequency for this board was cho- Software interrupts — INT instruction
sen make
to baud rate clock frequencies come out exact .
not a 1-kHz real-time clock. Larger systems usually have Interrupt service procedure
two or more crystal-controlled oscillators to accommo- Interrupt vector, interrupt pointer
date both.
Finally, after the timer is initialized, we enable the Interrupt vector table, interrupt pointer table
8086 INTR input with the STI instruction so that the
Interrupt type
8086 can respond to INT signals from the 8259A, and
wait for an interrupt with the HtRE: IMP HERE instruc- Divide by zero interrupt — type 0
tion.
Single-step interrupt — type 1
For the two interrupt service procedures we show just
the skeletons and the end of interrupt instructions. We Nonmaskable interrupt — type 2
leave it to you to write the actual procedures. Note that
Breakpoint interrupt — type 3
the procedures must be declared as FAR so that the as-
sembler
load
willboth the IP and the CS in the interrupt Overflow interrupt — type 4
pointer table. Remember from a previous discussion
Software interrupts — type 0-255
that when the 8259A responds to an IR signal, it sets
the corresponding bit in the ISR. This bit must be reset INTR interrupts— tvpe 0-255
at some time during or at the end of the interrupt serv-
BIOS
ice procedure so that the priority resolver can respond to
future interrupts of the same or lower priority. At the Edge-activated interrupt input
end of our procedures here we do this by sending an
OCW2 to the 8259A. The OCW2 of 00100000 that we Level-activated interrupt input
send tells the 8259A to reset the ISR bit for the IR level
Interrupt priority
that is currently being serviced. This is a nonspecific
end of interrupt (EOI) instruction. Hardware interrupts
This chapter has introduced you to interrupts and
Software programmable
some interrupt applications. The following chapters will
show you more of this, because much of the interfacing Programmable timer/counter devices — 8253, 8254
discussed there is done on an interrupt basis.
Internal addresses

Control words, command words, mode words

IMPORTANT TERMS AND CONCEPTS 8259A priority interrupt controller


FROM THIS CHAPTER Fixed priority
In-service register — ISR
If you do not remember any of the terms in the following Priority resolver
list, use the index to help you find them in the chapter Interrupt request register — IRR
for review. Interrupt mask register — IMR

REVIEW QUESTIONS AND PROBLEMS


1. List and describe in general terms the steps an 0040H. To what interrupt type do these locations
8086 will take when it responds to an interrupt. correspond? What is the starting address for the
interrupt service procedure?
2. Describe the purpose of the 8086 interrupt pointer
table. 6. Briefly describe the condition(s) which cause the
8086 to perform each of the following types of inter-
3. What addresses in the interrupt pointer table are rupts: type
0. type 1, type 2. type 3, type 4.
used for a type 2 interrupt?
7. Why is it necessary at the start of an interrupt serv-
4. The starting address for a type 4 interrupt service ice procedure to PUSH all registers used in the pro-
procedure is 0010:0082. Show where and in what cedure and
to POP them at the end of the proce-
order this address should be placed in the inter- dure?
rupt jumptable.
8. Why must you use an IRET instruction rather than
5. Address 00080H in the interrupt jump table con- the regular RET instruction at the end of an inter-
tains 4A24H. and address 00082H contains rupt service procedure?

258 CHAPTER EIGHT


9. Show the assemblei directive and Instrut tlons you Ing the value is in range, add the byte to a
would use to Initialize the interrupt pointei table lo- running total kept in two successive memory loca
cations
.1 typeO
foi procedure called I >1V 0 ERROR lions. II the MSli ol data is I, showing that the
.iiid a type 2 procedure called POWER FAIL. value is mil ol range, Ignore the input. Aftei 100
samples have been idialed, divide by 100 to get the
10. Describe the main use of the 8086 type l interrupt average, store this average in anothei reserved
Show the assembly language instructions neces memory location, and reset the total to zero.
n.iiv (o set the 8086 trap flag
15. Write the algorithm and the program foi an intei
11. In a system which has battery backed RAM for sav rupt service procedure which turns on an LI
Ingdata in case of a power failure, the stack is often nected to bit DO ol port FFFAH on for 2.r) seconds
put in the battery-backed RAM. This makes n easy and oil foi 25 seconds. The procedure should also
to save registers and ci itical program data. Assume turn a second LED connected to bit Dl of port
that tin- battery backed RAM is in the address FFFAH on for 1 minute and oil for 1 minute. As-
range ol 08000H-08FFFH. Write an 8086 powei sume that
a l Hz interrupt signal is connected to
failure interrupt service procedure which: the NMI input ol an 8086. and that a high on a port

Sets .in external battery-backed flip-flop run bit turns on the LED connected to it.

nected to bit 0 of port 28H to indicate that a 16. Write the algorithms lor a mainline program and
power failure lias occurred. an interrupt service procedure which generate a
Saves all registers on the stack. real-time clock ol seconds, minutes, and hours m
three memory local ions using a 1 -Hz signal applied
Saves the stack pointer value for the last ent ry n to the NMI input ol an 8086. Then write the assem
location 8000H. bly language programs lor (he mainline and the
procedure. If you are woi king on an SDK-86 board,
Saves the contents of memory locations 001 00H-
there is a procedure in Figure 9-33 that you can
003FFH alter the saved stack pointer value at the
add to your program to display the t ime on the data
start of the batten- backed memory. (A string in-
and address field LEDs of the board. You can use
struction be
mightuseful for this.)
this procedure without needing to understand the
Halts. details of how it works. To display a word on the
data field, simply put the word in the CX register,
When the power comes back on. the start-up rou-
put 00H in AL, and call the procedure. To display a
tine can
check the power fail flip-flop. If the flip-Hop
word on the address field, put the word in CX, 01 H
is set. the start-up procedure can copy the saved
in AL, and call the procedure. HINT: Clear carry
data back into its operating locations, initialize the
before incrementing a count in AL so that DAA
stack segment register, and then get the saved SP
works correctly.
value from address 08000H. Using this value it can
restore the pushed registers and return execution 17. In Chapter 5 we discussed using breakpoints to
to where the power fail interrupt occurred. This is debug programs containing procedures. List the
called a "warm start." If we don't want it to do a sequence of locations where you would put break-
warm start, we can reset the flip-flop with an exter- points
thein example program in Figure 8-9 to
nal RESETkey so the system does a start from debug it if it did not work when you loaded it into
scratch or "cold start." memory.
12. Why is the 8086 INTR input automatically disabled 18. Suppose that we add another 8254 to the SDK-86
when the 8086 is RESET? How is the 8086 INTR add-on circuitry shown in Figure 8-14. and that
input enabled to respond to interrupts? What in- the CS input of the new 8254 is connected to the Y5
struction
be can
used to disable the INTR input? output of the 74LS138 decoder.
Why is the INTR input automatically disabled as
a. What will be the system base address for this
part of the response to an INTR interrupt? How
does the INTR input automatically get reenabled at added 8254?
b. To which half of the 8086 data bus should the
the end of an INTR interrupt service procedure?
eight data lines from this 8254 be connected?
13. Describe the response an 8086 will make if it re- c. What will be the system addresses for the three
ceivesNMI
an interrupt signal during a division counters and the control word register in this
operation which produces a divide by zero inter- 8254?
rupt. d. Show the control word you would use to initial-
ize counter 1 of this device for read/write LSB
14. The data outputs of an 8-bit analog-to-digital con-
verterconnected
are to bits D0-D7 of port FFF9H then MSB, mode 3. and BCD countdown.

and the end-of-conversion signal from the A/D con- e. Show the sequence of instructions you would
verter
connected
is to the NMI input of an 8086. use to write this control word and a count of

Write a simple mainline program and an interrupt 0356 to the counter.


service procedure which reads in a byte of data /. Assuming the GATE input is high, when does
from the converter. If the MSB of the data is a 0. the counter start counting down in mode 3?

INTERRUPTS AND INTERRUPT SERVICE PROCEDURES 259


g. Assuming initialization as in parts d and /. 22. Describe the use of the CAS0. CAS1. and CAS2
and that a 712-kHz signal is applied to the CLK lines in a system with a cascaded 8259A.
input of counter 1 in mode 3, describe the fre-
quency, period,
and duty cycle of the waveform 23. Describe the response that an 8259A will make if it
that will be on the OUT pin of the counter. receives an interrupt signal on its IR3 and IR5 in-
h. Describe the effect that a control word of putsthe
at same time. Assume fixed priority for the
10010000 sent to this 8254 will have. IR inputs. What response will the 8259A make if it
is servicing an IR5 interrupt and an IR3 interrupt
Show the instructions you would use to initialize
signal occurs
counter 2 of the 8254 in Figure 8-14 to produce a
1.2-ms-wide STROBE pulse on its OUT pin when it 24. Why is it necessary to send an end-of-interrupt
receives a trigger input on its GATE input. (EOI) command to an 8259A at some time in an
20. Show the instructions needed to latch and read a interrupt service routine?
16-bit count from counter 1 of the 8254 in Figure
25. Show the sequence of command words and in-
8-14.
structionsyou
that would use to initialize an
21. Describe the sequence of actions that an 8259A 8259A with a base address of FF10H as follows:
and an 8086. as connected in Figure 8-14. will take
when the 8259A receives an interrupt signal on its edge-triggered: only one 8259A: 8086 system:
1R2 input. Assume only IR2 is unmasked in the interrupt type 40 corresponds to IR0 input: nor-
8259A and that the 8086 INTR input has been en- mal EOI:
nonbuffered mode, not special fully
abled with
an STI instruction. nested mode: IR1 and IR3 unmasked.

260 ( HAPTFR EIGHT


CHAPTER

Digital Interfacing

I he majoi goal nl I Ills el i.i i i|i-i ,11nl I h«- iicx I is in show Describe the hardware and software needed to con-
you much of the Interface circuitry and software needed trolstepper
a motor.
to control a complex machine such as our printed-
circuit board-making machine or a medical instrument
with a microprocessor. We try to show enough detail in
PROGRAMMABLE PARALLEL PORTS AND
each topic so that you can build and experiment with
HANDSHAKE INPUT/OUTPUT
some real circuits and programs. Perhaps you can use
some of these to control appliances around your house Throughout the program examples in the preceding
or solve some problems at work. chapters, we have used port devices to input parallel
data to the microprocessor and to output parallel data
from the microprocessor. Most of the available port de-
vices such
as the 8255A on the SDK-86 board contain
OBJECTIVES two or three ports which can be programmed to operate
in one of several different modes. The different modes
At the conclusion of this chapter you should be able to:
allow you to use the device for many common types of
parallel data transfer. First we will discuss some of these
1. Describe simple input and output, strobed input common methods of transferring parallel data, and then
and output, and handshake input and output. we will show how the 8255A is initialized and used in a
2. Initialize a programmable parallel port device such variety of I/O operations.
as the 8255A for simple input or output and for
handshake input or output. Methods of Parallel Data Transfer
3. Interpret the timing waveforms for handshake SIMPLE INPUT AND OUTPUT
input and output operations.
When you need to get digital data from some simple
4. Describe how phonemes are sent to a speech syn-
switch such as a thermostat into a microprocessor, all
thesizer
a on
handshake basis.
you have to do is connect the switch to an input port line
5. Describe how parallel data is sent to a printer on a and read the port. The thermostat data is always pres-
handshake basis. ent andready, so you can read it at any time.
Likewise, when you need to output data to a simple
6. Show the hardware connections and the programs display device such as an LED, all you have to do is con-
that can be used to interface keyboards to a micro- nect the
input of the LED buffer on an output port pin
computer. and output the logic level required to turn on the light.
The LED is always there and ready, so you can send data
7. Show the hardware connections and the programs
that can be used to interface alphanumeric dis-
to it at any time. The timing waveform in Figure 9- la
represents this situation. The crossed lines on the wave-
plays
a tomicrocomputer.
form representthe time at which a new data byte be-
8. Describe how an 8279 can be used to refresh a mul- comes valid
on the output lines of the port. The absence
tiplexed display
LED and scan a matrix keyboard. of other waveforms indicates that this output operation
is not directly dependent on any other signals.
9. Initialize an 8279 for a given display and keyboard
format. SIMPLE STROBE I/O

10. Show the circuitry used to interface high-power In many applications valid data is only present on an
devices to microcomputer ports. external device at a certain time and it must be read in

261
other words the sending system might send data bytes
ZDC faster than the receiving system could read them. To
prevent this problem a handshake data transfer
scheme is used.

\ f SINGLE HANDSHAKE I/O

Figure 9- lc shows some example timing waveforms for a


^x: handshake
microprocessor.
data transfer from a peripheral
The peripheral outputs
device to a
some parallel
data and sends an STB signal to the microprocessor. The
microprocessor detects the asserted STB signal on a
polled or interrupt basis and reads in the byte of data.
v r The microprocessor then sends an acknowledge signal.
ACK, to the peripheral to indicate that the peripheral
can send the next byte of data. From the viewpoint of the
microprocessor, this operation is referred to as a hand-
shake
strobed
or input.
^>c These same waveforms
output from a microprocessor
might represent
to a parallel
a handshake
printer. In
this case the microprocessor outputs a character to the
printer and asserts an STB signal to the printer to tell
the printer, "Here is a character for you.'' When the
printer is ready, it answers back with the ACK signal to
tell the microprocessor, "I got that one. send me an-
other.
We will
" show you much more about printer inter-
facing
a later
in section.
The point of this handshake scheme is that the send-
X ing deviceor system cannot send the next data byte
until the receiving device or system indicates with an
ACK signal that it is ready to receive the next byte.
FIGURE 9-1 Parallel data transfer, (a) Simple output, (b)
Simple strobe I/O. (c) Single handshake I/O. (d) Double DOUBLE HANDSHAKE DATA TRANSFER
handshake I/O. For data transfers where even more coordination is re-
quired between
the sending system and the receiving
system, a double handshake is used. Figure 9- Id
at that time. An example of this is the ASCII-encoded shows some example waveforms for a double handshake
keyboard shown in Figure 4-13. When a key is pressed input from a peripheral to a microprocessor. Perhaps it
on the keyboard, circuitry on the keyboard sends out will help you to follow these waveforms by thinking of
the ASCII code for the pressed key on eight parallel data them as a conversation between two people. In these
lines. The keyboard circuitry then sends out a strobe waveforms each signal edge has meaning. The sending
signal on another line to indicate that valid data is pres- device asserts its STB line low to ask. "Are you ready?"
ent on
the eight data lines. As shown in Chapter 3. you The receiving system raises its ACK line high to say, "I'm
can connect this strobe line to an input port line and ready. " The peripheral device then sends the byte of data
poll it to determine when you can input valid data from and raises its STB line high to say, "Here is some valid
the keyboard. Another alternative, described in Chapter data for you." After it has read in the data the receiving
8, is to connect the strobe line to an interrupt input on system drops its ACK line low to say, "I have the data,
the processor and have an interrupt service routine read thank you, and I await your request to send the next
in the data when the processor receives an interrupt. byte of data."
The point here is that this transfer is time-dependent. For a handshake output of this type, from a micro-
You can only read in data when a strobe pulse tells you processor
a peripheral,
to the waveforms are the same
that the data is valid. but the microprocessor sends the STB signal and the
Figure 9- lb shows the timing waveforms which repre- data, and the peripheral sends the ACK signal. In a later
sent this
type of operation. The sending device, such as section we show how this type of handshake is used to
a keyboard, outputs parallel data on the data lines and transfer phoneme bytes from a microprocessor to a
then outputs an STB signal to let you know that valid speech-synthesizer device.
data is present. For handshake data transfer, a microprocessor can
For low rates of data transfer, such as from a keyboard determine when it is time to send the next data byte on a
to a microprocessor, a simple strobe transfer works well. polled or on an interrupt basis. We usually use the inter-
However, for high-speed data transfer this method does rupt approach because it makes better use of the proc-
not work because there is no signal which tells the send- essor's time.
The STB or ACK signals for these hand-
ing device when it is safe to send the next data byte. In shake transferscan be produced on a port pin by

262 ( HAPTEK NINE


Instructions In the program. This method, however, Likewise, port B can be used as an 8-bil Input port or as
tends in use too much processor time. Therefore, port an 8 bil outpul port. Porl C can be used as an 8 bil
devices such .is the 8255A have been designed so thai Inpul or outpul port, two l bil ports, oi to produce
they can be programmed to automatically manage the handshake signals for polls A and B. We will discuss the
handshake operation. Foi example, the 8255A can be different modes foi these lines in detail a liitle later.
programmed to automatically receive a STB signal from a Along the lefl side ol the diagram you see the usual
peripheral, send an interrupt signal to the processor, signal lines used to conned the device to the system
and send the A( K signal to the peripheral at the proper buses Eight data Inns allow you to write data bytes to a
times rhe following sections show you how to connect, port or the control register and to read bytes from a poi i
Initialize, and use an 8255A for a variety of applications oi the stains register undei the control ol the Rl » and
VYK lines. The address inputs, AO and Al, allow you to
selectively access one ol the three ports or the control
8255A Internal Block Diagram and System register The internal addresses tor the device are: port
Connections A 00, port B-01. porl (' 10, control-11. Asserting
Figure 9-2 shows the internal block diagram <>i the the CS inpul of the 8255A enables it for reading or writ-
8255A. Along the righi side of the diagram you can see ing. The
CS inpul will be connected to the output of the
that the device has 24 input/output lines. Port A can be address decoder circuitry to selecl the device when it is
used as an 8-bit input port or as an 8-bit output port. addressed.

POWER
SUPPLIES I/O
GRI IUP
r
: PA7-PA0
A
CONTROL

PORT
UPPER
C -; I/O
PC7-PC4

IDIRECTIONAL DATA BUS

Dl. DO <
A r\
, £
8-BIT
INTERNAL
DATA BUS
: PORT
LOWER
C

(4)

RD
READ/
WR GROUP GROUP
WRITE
B B
OONTRDI
LOGIC
CONTROL PORT
V

FIGURE 9-2 Internal block diagram of 8255A programmable parallel port


device. (Intel Corporation)

DIGITAt INTERFACING 263


The RESET input of" the 8255A is connected to the sys- 4DDRESSBUS

tem reset
line so that, when the system is reset, all of the
CONTROL BUS
port lines are initialized as input lines. This is done to
prevent destruction of circuitry connected to port lines.
If port lines were initialized as outputs after a power-up
or reset, the port might try to output into the output of a
device connected to the port. The possible argument
between the two outputs might destroy one or both of
them. Therefore all of the programmable port devices 8255A

initialize their port lines as inputs when reset.


We discussed in Chapter 7 how two 8255As can be
connected in an 8086 system. Take a look at Figure 7-6
(sheet
Note
51 to refresh
that one of the
your
8255As
memory of these
is connected
connections.
to the lower
if \f K- g«
half of the 8086 data bus. and the other 8255A is con- PB7-PB0 PC3 PCq PC7-PC4

nected
theto upper half of the data bus. This is done so
that
a word
a byte
can
can
be
be transferred
transferred by
by enabling
enabling
one
both
device,
devices
or
at
%^ PCq PC, PC2 PC3 PC4 PC5 PC6 PC7

the same time. According the truth table for the I/O port "

address decoder in Figure 7-15. the.\A40 8255A on the


lower half of the data bus will be enabled for a base ad- PB7 PB0 INTRB IBFB STBg INTRA STBA IBFA I/O I/O PA7-PA0
dressFFF8H.
of and the XA35 8255A will be enabled for OR OR_ OR OR OR OR
0"b'Fr ACKr I/O I/O ACKfl OBFa
a base address of FFF9H.
Another point to notice in Figure 7-6 is that system PORT A, PORT B CONTROL

address line A1 is connected to the 8255A AO inputs,


and system
inputs.
address line A2 is connected
With these connections
to the 8255A A1
the system addresses for
PC0 PC, PC2 PC3 PC4 PC5 PC6 PC7 J
the three ports and the control register in the XA40
8255A will be FFF8H, FFFAH, FFFCH. and FFFEH as
shown in Figure 7-15. Likewise, the system addresses INTRA IBFfl 0B>» pa?- PA0

for (he three ports and the control register of the XA35 PORT A CONTROL

8255A are FFF9H. FFFBH. FFFDH. and FFFFH.

FIGURE 9-3 Summary of 8255A operating modes.


8255A Modes and Initialization (Intel Corporation)
Figure 9-3 summarizes the different modes in which the
ports of the 8255A can be initialized.

11 input port, then pins PC3, PC4, and PC5 function as


MODE 0
handshake signals. Fins PC6 and PC7 are available for
When you want to use a port for simple input or output use as input lines or output lines. If port A is initialized
without handshaking, you initialize that port in MODE as a handshake output port, then port C pins PC3, PC6,
0. If both port A and port E3 are initialized in MODE 0. and PC7 function as handshake signals. Port C pins PC4
then the two halves of port C can be used together as an and PC5 are available for use as input or output lines.
additional 8-bit port, or they can be used individually as Since the 8255A is often used in this mode, we show
two 4-bit ports. When used as outputs the port C lines several examples in the following sections.
can be individually set or reset by sending a special con-
trol wordto the control register address. Later we will MODE 2
show you how to do this. The two halves of port C are Only port A can be initialized in MODE 2. In MODE 2,
independent, so one hall can be initialized as input, and port A can be used for bidirectional handshake data
the .ilher half initialized as output. transfer. This means that data can be output or input
on the same eight lines. The 8255A might be used in
MODE 1
this mode to extend the system bus to a slave microproc-
When you want to use port A or port B for a handshake essor
toortransfer data bytes to and from a floppy disk
(strobed) input or output operation such as we dis- controller board. If port A is initialized in MODE 2, then
cussed
previous
in sections, you initialize that port in pins PC3-PC7 are used as handshake lines for port A.
MODE 1 . In this mode some of the pins of port C func- The other three pins of port C can be used for I/O if port
tion as
handshake lines. Pins PCO, PCI, and PC2 func- B is in MODE 0. The three pins will be used for port B
tion as
handshake lines for port B if it is initialized in handshake lines if port B is initialized in MODE 1. After
MODE 1. If port A is initialized as a handshake (MODE you work your way through the MODE 1 examples in the

2C>4 CHAPTER NINE


following sections you should have little difficulty un-
derstanding
discussion
the o! MODf: 2 in the Intel data
D7 06 Db D4 D3 D2 Dl DO
sheel it you encounter it m a system

u
Constructing and Sending 8255A Control Words
Figure 9 I shows the formats for the two 8255A control
words. The MSB ol the control won! tells the
which control word you are sending il You use the
PORT C (LOWER)
mode definition control word formal in Figure 9 la to 1 INPUT
0 OUTPUT
ic 11 the device what modes you want the ports to operate
in. For the mode definition control word you put a l in PORT B
the MSB You use the bit set reset control word format 1 - INPUT
0 OUTPUT
in Figure 9 lb when you want to set oi reset the output
on a pin of port C, oi when you want to enable the inter MODE SELECTION
nipt output signals for handshake data transfers. The 0 MODE 0
1 MODE 1
MSB is 0 for this control word. Both control words are
sent to the control register address for the 8255A.
As usual, making up a control word consists ol figur-
ing out
what to put in the eight little boxes one bit .it a
time. As an example for this device, suppose that you
want to initialize the 8255A (XA40) in Figure 7-6 as fol PORT C (UPPER)
lows: Port B MODE 1 input, port A MODE 0 output, port 1 = INPUT
0 = OUTPUT
C upper as inputs, and bit 3 of port C as output. Figure
9-5a shows the control word which will program the PORTA
1 = INPUT
8255A in this way. The figure also shows how you
0 OUTPUT
should document any control words you make up for
MODE SELECTION
use in your programs. Using Figure 9-4a, work your way 00 MODE 0
through this word to make sure you see why each bit 01 = MODE 1
1X= MODE 2
has the value it does.
As we said previously, the control register address for
the XA40 8255A is FFFEH. To send a control word then
you load the control word in AL with a MOV AL,
MODE SET FLAG
10001 11 OB instruction, point DX at the port address with 1 ACTIVE
the MOV DX, OFFFEH instruction, and send the control
word to the 8255A control register with the OUT DX, AL
instruction.
As an example of how to use the bit set/reset control
word, suppose that you want to output a 1 to (set) bit 3
i ONTRi it KVI IRD
of port C. which was initialized as an output with the
mode set control word above. To set or reset a port C D7 06 D5 D4 D3 02 Dl DO
output pin you use the bit set/reset control word shown
in Figure 9-4b. Make bit D7 a 0 to identify this as a bit
set/reset control word and put a 1 in bit DO to specify BITSET RESET
1 ^SET
that you want to set a bit of port C. Bits D3, D2. and Dl 0 = RESET
are used to tell the 8255A which bit you want to act on. DON'T
CARE
For this example you want to set bit 3, so you put Oil in
BIT SELECT
these three bits. For simplicity and compatibility with
11 1 2 I
future products, make the other three bits of the control
0 1 0 1 0 1 0 1 B0
word O's. The result of 000001 1 IB. with proper docu- %¡0 1 10 0 1 1 Bl

mentation,
shown is in Figure 9-5b. 0 0 0 0 1 1 1 1 B.

To send this control word to the 8255A simply load it


into AL with the MOV AL, 00000111B instruction, point
DX at the control register address with the MOV DX, BITSET RESET FLAG

OFFFEH instruction if DX is not already pointing there, 0 ACTIVE

and send the control word with the OUT DX, AL instruc-
tion.part
As of the application examples in the following
sections, we will show you how you know which bit in
port C to set to enable the interrupt output signal for FIGURE 9-4 8255A control word formats, (a) Mode set
handshake data transfer. control word, lb) Port C bit set/reset control word.

DIGITAL INTERFACING 265


D7 D6 Jr- D4 D3 D2 D1 D0 ize the
8255A in the correct modes for this application.
i 0 0 0 1 1 1 0 To do this start by making a list showing how you want
each port pin or group of pins to function. Then put in
the control word bits that implement those pin func-
PORTC BIT 3 OUT
PORT B INPUT tions.our
For example here:
PORT B MODE 1
PORT C UPPER - IN Port A needs to be initialized for handshake input
PORT A OUTPUT (MODE 11. because instruction codes have to be read
PORT A MODE 0
in from the tape reader on a handshake basis.
MODE SET WORD

Port B needs to be initialized for simple output


(MODE 01. No handshaking is needed here because
this port is being used to output simple on or off
D7 D6 D5 DA in [j j 01 i'O control signals to the lathe.
0 0 0 0 0 i 1
Port C. bits PCO. PCI. and PC2 are used for simple
input of sensor signals from the lathe.

Port C. bits PC3. PC4. and PC5 function as the


handshake signals for the data transfer from the tape
reader connected to port A.
MUST BE 0
BIT SET RESET WORD Port C, bit PC6 is used for output of the STOP/CO
signal to the tape reader.

Port C, bit PC7 is not used for this example.


FIGURE 9-5 Control word examples for 825SA. (a) Mode
set control word, (b) Port C bit set/reset control word
Figure 9-7 shows the control word to initialize the
to set l)ll J. 8255A for these pin functions. This word will be sent to
the control register address as shown above. Now let's
talk about how the program for this machine might op-
8255A Handshake Application Examples erate, and
how the handshake data transfer actually
takes place.
INTERFACING TO A MICROCOMPUTER-
CONTROLLED LATHE

All of the machines in the machine shop of our


computer-controlled electronics factory operate under
microcomputer control. One example of the machines
here is a lathe which makes bolts from long rods of
stainless steel. The cutting instructions for each type of PC, '
R0
bolt that we need to make are stored on a %-in wide Ft,
paper or metal tape. Each instruction is represented by PA R, 8 LEVEL
PAPER
,i series of holes in the tape. A tape reader pulls the tape R, TAPE
R READER
through an optical or mechanical sensor to detect the PAr R.
MODE 1 _
hole patterns and convert these to an 8-bit parallel code. HNPUTI
PA6 R6
The microcomputer reads the instruction codes from
the tape reader on a handshake basis and sends the
pc„ "
STB

appropriate control instructions to the lathe. The mi- PC


crocomputeralsomustmonitor various conditions PC,

around the lathe. It must, for example, make sure the 8255A

lathe has cutting lubricant oil. is not out of material to PI START/STOP


MODE 0
work on. and is not jammed up in some way. Machines PC . LIMIT SENSOR IH/VI
(INPUT)
that operate in this way are often referred to as com- PC 2 OUT OF FLUID

puter numerical control or CNC machines.


Figure 9-6 shows in diagram form how an 8255A PB CHANGE TOOL

might be used to interface a microcomputer to the tape PB, -

LEFT RIGHT

reader and lathe. In the next chapter we will show you PB *


UP'DOWN

PB, HOR STEP STROBE


some of the actual circuitry needed to interface the port IOUTPUTI VERT STEP STROBE
PB,
pins of the 8255A to the sensors and the high-power SLEW/STEP

motors of the lathe. For now we want to talk about ini- PB6 FLUID ENABLE

EMERGENCY STOP
tializing
8255A
the for this application and analyze the
timing waveforms for the handshake input of data from
the tape reader. FIGURE 9-6 Interfacing a microprocessor to a tape
First you want to make up the control word to initial- reader and lathe.

266 ( HAI'IfR NINE


11 ;>.< M c ii. il will cause the iiitpul an intei rupl
0 1 1 0 0 0 requesl siynal to the inn ro| :ssoi <>n bit P< I
I he pi OCesSI us i espouse in ||ir mlci rupl lc(|U(sl will
I ii logo to an Interrupt service procedure which reads in
POR % LO
POR I B the byte ol data latched in port A. When the RD Signal
from the microprocessoi uocs low foi this read of port A,
PORT C UPI I i.\ will automatically resel lis interrupt requesl
POR1 A INPUT
signal on P( '.. I his is done so that a second interrupt
PORT A MODE 1
MODE SET WORD
cannot he caused by the same dala byte transfei Whin
the processor raises its RD signal high again at the end
FICURI 9-7 Control word to initialize 8255A for interface ol the read operation, the 8255A automatically drops its
with tape reader .uh) Lithe. IBI signal on PC5 low again. IBI going low .114,1111 is the
signal to the tape readei thai the data transfer is com
plete, and that it can send the next byte ol dala. The
Alter initializing everything, the system would proba lime between when the 8255A sends the interrupt re
bly read port C bits I't i). P( i. and PC2 to check if the quesl Signal and when the proi essoi leads the data byte
lathe was ready to operate. For any 8255A mode you from port A depends on when the procesSOl gets .110111id
read port C by simply doing an input from the port (' to servicing that interrupt. The point here is thai tins
address. Then the microprocessor would output a start time doesn't matter. The tape reader will not send the
command to the tape reader on bit PCb. This is done next byte of data until il detects thai the IBF signal has
with a hit set reset command. Assuming you want to gone low again. The transfer cycle will then repeal foi
reset bit PC6 to start the tape reader, the bit set/reset the next data byte.
control word for this is 00001 100. When the tape reader Alter the processor reads in the lathe control instruc-
receives the go command, it will start the handshake tion bytefrom the tape reader, it will decode this in-
data transfer to the 8255A. Let's work our way through struction,
output
and the appropriate control byte to
the timing waveforms in Figure 9-8 to see how the data the lathe on port B of the 8255A. The tape reader then
transfer takes place. sends the next instruction byte. If the instruction tape
The tape reader starts the process by sending out a is made into a continuous loop, the lathe will keep mak-
byte of data to port A on its eight data lines. The tape ing thespecified parts until it runs out of material. The
reader then asserts its STB line low to tell the 8255A that unused bit of port C, PC7. could be connected to a mech-
a new byte of data has been sent. In response the 8255A anism which
loads in more material so the lathe can
raises its input buffer full (IBF) signal on PC5 high to tell continue.
the tape reader that it is ready for the data. When it Before we go on there is one more point we have to
detects the IBF signal at a high level, the tape reader make about initializing the 8255A for this
raises its STB signal high again. The rising edge of the microcomputer-controlled lathe application. In order for
STB signal has two effects on the 8255A. It first latches the handshake input data transfer from the tape reader
the data byte in the input latches of the 8255A. Once the to work correctly the interrupt request signal from bit
data is latched, the tape reader can remove the data byte PC3 has to be enabled. This is done by sending a bit
in preparation for sending the next data byte. This is setVreset control word for the appropriate bit of port C.
shown by the dashed section on the right side of the Figure 9-9 shows the port C bit that must be set to en-
data waveform in Figure 9-8. Secondly, if the interrupt able the
interrupt output signal for each of the 8255A
signal output has been enabled, the rising edge of the handshake modes. For the example here port A is being

MODE 1 (STROBED INPUT)

MB
\ /

CT3
INPUT
PERIP
FROM
HERAL ' ~ \_
f >"
FIGURE 9-8 Timing waveforms for 8255 handshake data input from a tape mm, In

DIGITAL INTERFACING 267


PORT C TO ENABLE
INTERRUPT SIGNAL INTERRUPT REQUEST
FOR MODE 1 PIN NUMBER SET PORT C BIT

PORT A IN PC3

PORT B IN PCO PC2

PORT A OUT PC3 PC6

PORT B OUT PCO PC2

PORT C TO ENABLE
INTERRUPT SIGNAL INTERRUPT REQUEST
FOR NODE 2 PIN NUMBER SET PORT C BIT

PORT A IN PC3 PC^t

PORT A OUT PC3 PC6

FIGURE 9-9 Port C bits to set to enable interrupt request outputs for
handshake modes.

used for handshake input. According to Figure 9-9. port The circuit can be connected to one of the 8255As on an
C bit PC4 must be set to enable the interrupt output for SDK-86 board if you have one of these available.
this operation. The bit set/reset control word to do this
is 00001001. This bit set/reset control word will be sent SC-01A OPERATION AND CIRCUIT
to the control address of the 8255A. CONNECTIONS
Handshake data transfer from the tape reader to the Figure 9-lOa shows how an SC-01A speech synthesizer
8255A can be stopped by disabling the 8255A interrupt IC can be connected to an 8255A. The SCO 1A uses pho-
output on port C pin PC3. This is done by resetting bit nemes
produce
to speech. Phonemes are the individual
PC 4 with a bit set/reset control word of 00001000. You sounds in words. By linking phonemes, you can pro-
will later see another example of the use of this interrupt
duce any
word. To produce words, phrases, or even sen-
enable/disable process in Figure 9-17. tences,
microcomputer
the simply has to output a series
As another example of 8255A interrupt output ena- of phonemes to the SC-01A with the proper timing. A
bling, suppose
that you are using port B as a handshake 6-bit binary code sent to theP0-P5 inputs of the SC-01A
output port. According to Figure 9-9 you need to set port determines which of its 64 phonemes it will output. An
C bit PC2 to enable the 8255A interrupt output signal.
additional two bits sent to the SC-OlA's II and 12 inputs
The bit set/reset control word to do this is 00000101. determine the inflection of the sounded phoneme. A
The microcomputer-controlled lathe we have de- table in the appendix shows the 64 phoneme codes and
scribedishere
a small example of automated manufac- the phoneme sequence for some example words. To
turing.advantage
The of this approach is that it relieves sound a phoneme you send the phoneme and inflection
humans of the drudgery of standing in front of a ma- codes for that phoneme and then assert the STB input of
chine continuallymaking the same part, day after day. the SC-01 high. The SC-01A will then assert its
Hopefully society can find more productive use for the acknowledge/request (A/R) line low to tell you that it re-
human time made available. ceivedphoneme,
the and it will sound the phoneme. The
time required to sound a phoneme ranges from 47 to
A SPEECH SYNTHESIZER INTERFACE— 8255A
250 ms. When the SC-01 A finishes sounding the pho-
HANDSHAKE OUTPUT
neme,
will itraise its A/R line high again to indicate that
Many microprocessor-based products now recognize it is ready for the next phoneme. The variable time it
spoken commands and speak to you. In Chapter 12 we takes to sound a phoneme means that you have to send
discuss m detail several methods of producing human phonemes to the SC-01 A on a handshake basis. You
speech under microprocessor control. For our example could poll the A/R line to determine when the SC-01 A is
here we chose the Votrax SC-01A phoneme speech syn- ready for the next phoneme, but because of the relatively
thesizer because
it is relatively inexpensive, it is easy to long time between requests, it is much more reasonable
program, and it interfaces easily with a microprocessor to service the device on an interrupt basis. An 8255A
port on a handshake basis. You may want to build up port operating in MODE 1 easily manages the required
the tin nit shown here and give your programs a voice. STB, A/R, and interrupt signals, so these lines are con-

268 ( I I \IMIK MINI.


SYSTEM
DATA
BUS

74C906

Vcc - PIN 14
GND - PIN 7. 10

OBFFROM
8255A \
DELAYED
INVERTED
AND
OBF \
SC-01A
T0 8255A
A/R
\ J
8255A
TO
INTR
CPU \ r \
CPU WR
T0 8255A \LS \i
DATA OUT
FROM PORT

'- 500 ns MAX


450 ns MIN

FIGURE 9-10 (a) Connection of a Votrax SC-01A speech synthesizer to an 8255A


for handshake output of phonemes, (b) Timing waveforms for transfer of a
phoneme from 8255A to SC-01A on handshake basis. (Vofrax Incorporated)

DIGITAL INTERFACING 269


nected to the appropriate bits of port C for this mode. A/R line high again to say, "Send me the next phoneme."
Before we go on to the 8255A operation and timing When the 8255A ACK input receives the rising edge of
waveforms, here are a few more points about the circuit this A/R signal, it automatically raises the interrupt re-
connections. quest signal
on pin PC3 high if that signal has been en-
The LM380 in Figure 9- 10a is an audio amplifier abled.
the If8086 interrupt input being used is enabled,
which amplifies the signal from the SC-01A so that it the 8086 will go and execute the interrupt service rou-
tan drive a speaker. The resistors and capacitors con- tine that
writes a phoneme to port A of the 8255A. Writ-
nected
pinsto 15 and 16 of the SC-01A determine the ingphoneme
a to the 8255A will cause the 8255A inter-
internal clock frequency. This clock frequency deter- rupt requestoutput on PC3 to be automatically reset.
minespitch
the of the phoneme. Adjust the 10-kSl po- The handshake sequence then repeats for this pho-
tentiometer
get a frequency
to of about 680 kHz on pin neme.
16 or until you like the pitch of the sounded phonemes.
The 74C906 open drain CMOS buffers, between the 8255A INITIALIZATION FOR HANDSHAKE
8255A PA6-PA7 pins and the 11-12 pins, convert the 0-5 OUTPUT
V range signals from the 8255A to the 0-12 V range In order to have specific addresses let's assume the
signals required by the SC-01A inputs. Likewise, the SC-01 A is connected to the 8255A, XA40, on an
74C906 buffer on the A/R output of the SC-01 A converts SDK-86 board. As shown in Figure 7-15, the port ad-
the 0-12 V range signal from the SC-01 A to the 0-5 V dressesthis
for device are port P2A — FFF8H. port
range signal required by the 8255A. The STB signal to P2B— FFFAH. port P2C— FFFCH. and P2 control regis-
the SC-01 A must come at least 450 ns after the pho- ter—
FFFEH. Now let's make up the mode control word
neme andinflection codes arrive at the device. The to send to the 8255A.
20-kJl resistor and the 100-pF capacitor between the For the mode control word we make bit D7 a 1. We
two 74C906 buffers on the STB line produce the re- want to use port A as a handshake port, so we initialize
quired delay
for this signal. The transistor after the sec- it in MODE 1 by putting 0 in bit D6 and 1 in bit D5. To
ond bufferinverts the OBF signal from the 8255A so it initialize port A for output, we put a 0 in bit D4. The
has the correct polarity for the SC-01 A STB input. It is other bits in this control word would be determined by
often necessary to "massage" the handshake strobe sig- the use of port B and the remaining pins of port C. If you
nal so
that it meets the timing requirements of the re- are not using these, just make these bits O's. Figure
ceiving device.
In our next application example, a 9-1 la shows the resultant control word. We send this
printer interface, we show you another way to do this. mode control word to the control register at address
FFFEH.
PHONEME TRANSFER TIMING WAVEFORMS Since we want to do the handshake data transfer on
an interrupt basis, we have to send another control
Figure 9- 10b shows the timing waveforms for a hand-
word to enable the interrupt request signal on pin PC3.
shake outputdata transfer to the SC-01 A. Here's how
According to Figure 9-9 we enable this interrupt request
this works.
When the SC-01 is first powered up it raises its A/R
output high to indicate that it is ready for a phoneme.
D7 D6 D5 [U in D2 D1
This causes the 8255A to send an interrupt signal to the Ml

processor. In response to the interrupt request the proc- 1 0 1 0 0 0 0 II

essor does
an interrupt service procedure which writes a
phoneme and an inflection code to port A of the 8255A.
The left edge of the waveforms in Figure 9- 10b repre- NOT USED FOR THIS
sents start
the of the phoneme write operation. During APPLICATION

this write operation the WR from the 8086 will go low.


PORT A = OUT
When the 8255A detects this low, it will automatically
PORT A MODE 1
reset its interrupt request output on pin PC3. A little MODE SET WORD
later you will see how this was set. Now. when the WR
signal from the 8086 goes high, the phoneme and inflec-
tion codeswill be present on the output of the 8255A.
WR being at a high state causes the 8255A to automati-
cally assert
its output buffer full (OBF) signal low on bit II 0 0 0 1 1 0 1

PC7. This signal, inverted and delayed 450 ns by the


buffer circuit, arrives at the STB input of the SC-01 A. L SET BIT
This signal edge says to the SC-01 A, "Here is a phoneme BIT6P0RT C

for you." In response, the SC-01A drops its A/R output DON'T CARE
BIT SET/RESET CONTROL WORD
low to say. "I got the phoneme, thank you." When this
falling edge arrives at the 8255A ACK input on bit PC6,
the 8255A automatically raises its OBF signal high
again. This edge essentially asks the SC-01A, "May I FIGURE 9-11 8255A control words for Votrax SC-01A
send you another phoneme?" After the SC-01 A finishes interface, (a) Mode control word for port A, MODE 1.
sounding the phoneme (47—250 ms later) it raises its (b) Bit set/reset word to enable port A INTR.

270 CHAPTER NINE


l>\ setting 1)H P< 6 Figure 9 Lib shows the bil se) resel prints some out. A common standard tor Interfacing
control word to set bil P< 6 11ns control word is .ilso wiih parallel printers is (he Centronics Parallel Stan
output to the control registei .it address FFFEH. dard, named for tin- company thai developed n In the
following sections we show you how a Centronii
PROGRAM NOUS FOR SC-01A MAINLINE AND lei Interface works I how to implement it with an
INIIKKUIM PRO( LDURI 8255A.

The maioi tasks you have to do for the mainline line

Centronics Interface Pin Descriptions and


1. Set up a table containing the sequence ol phoneme Circuit Connections
codes you want lo scud. Make the last eode in the
( 'cut ionics type printers usually1 have a 36 pin interface
table the no sound phoneme. FFH, so that you can
connector. Figure 9 lii shows the pin assignments and
easily determine when .ill of the phoneme codes have
descriptions foi this connector as it is used in the IBM
been sent. As you read out the codes from the table
IV printei ->ut\ the Epson printers. Some manufactur-
vim can then compare each with this sentinel value
ers use
one or two pins differently so consult the manual
lo see if you have reached the end ol the table.
for your specific printer before connecting it up as we
2. Initialize, in a memory location, a pointer to the show here.
stari ol the phoneme table. Thirty-six pins may seem like a lot ol pins jusl to send
ASCII characters to a printer. The large number of lines
3. Initialize the interrupt pointer table lo point to the is caused by the fact that each data and signal line has
start ol the interrupt service procedure. its own individual ground return line. For example, as
4. Enable and unmask the interrupt input you are
shown in Figure 9-12. pin 2 is the LSB of the data chat
acter sent to the printer, and pin 20 is the ground re-
using.
turn forthis signal. The reason for the individual
5. Initialize the 8255A and enable the 8255A interrupt ground returns is to reduce the chance of picking up
request output. When the SC-01A is ready for the electrical noise in the lines. If you are making an inter-
next phoneme, the 8255A will send an interrupt sig- face cable for a parallel printer, these ground return
nal to
the 8086. lines should only be connected together and to ground
at the microcomputer end of the cable as shown in Fig-
The 8086 interrupt service procedure must get the table ure 9-14.While we are talking about grounds, note that
pointer from memory, use the pointer to get the next pin 16 is listed as logic ground and pin 17 is listed as
phoneme from the table, and send the phoneme to the chassis ground. In order to prevent large noise currents
8255A. The service procedure should then compare the from flowing in the logic ground wire, these wires
phoneme code to the sentinel value of FFH. If the pho- should only be connected together in the microcom-
neme code
is equal to FFH. then the procedure can sim- puter. (This
precaution is necessary whenever you con-
ply returnto the interrupted program. If the code is not nect anyexternal device or system to a microcomputer!
FFH. then the procedure should increment the table The rest of the pins on the 36-pin connector fall into
pointer to point to the next phoneme, store the pointer two categories, signals sent to the printer to tell it what
back in memory, and do an IRET. operation to do and signals from the printer that indi-
We leave the actual assembly language program for cate status.
its The major control signals to the printer
you to write as an exercise at the end of the chapter. are INIT on pin 31. which tells the printer to perform its
internal initialization sequence and STROBE on pin 1,
PARALLEL PRINTER INTERFACE— ANOTHER which tells the printer. "Here is a character for you."
HANDSHAKE OUTPUT EXAMPLE Two additional input pins, pin 14 and pin 36 are usually
For most common printers such as the IBM PC printer. taken care of inside the printer.
the Epson FX-80. and the NEC 8023. the data to be The major status signals output from the printer are:
printed is sent to the printer as ASCII characters on
eight parallel lines. The printer receives the characters 1. The ACKNLG signal on pin 10 which, when low. in-
to be printed and stores them in an internal FLAM buffer. dicates the
that data character has been accepted
When the printer detects a carriage return character and the printer is ready for the next character.
(ODH). it prints out the first row of characters from the 2. The BUSY signal on pin 11, which is high if, for
print buffer. When the printer detects a second carriage some reason such as being out of paper, the printer
return it prints out the second row of characters. The is not ready to receive a character.
process continues until all the desired characters have
been printed. 3. The PE signal on pin 12. which goes high if the
Transfer of the ASCII codes from a microcomputer to a out-of-paper switch in the printer is activated.
printer must be done on a handshake basis because the
4. The SLCT signal on pin 13 which goes high if the
microcomputer can send characters much faster than
printer is selected for receiving data.
the printer can print them. The printer must in some
way let the microcomputer know that its buffer is lull, 5. The ERROR signal on pin 32 which goes low for a
and that it cannot accept any more characters until it variety of problem conditions in the printer.

DIGITAL INTERFACING 271


SIGNAL RETURN
SIGNAL DIRECTION DESCRIPTION
PIN NO. PIN NO.

STROBE pulse to read data in. Pulse width must be more than 0 5fisat receiving terminal. The
1 19 STROBE IN
signal level is normally "high"; read-in of data Is performed at the "low" level of this signal.

2 20 DATA 1 IN

3 21 DATA 2 IN

4 22 DATA 3 IN

5 23 DATA 4 IN These signals represent information of the 1 st to 8th bits of parallel data respectively. Each
signal is at "high" level when data is logical "1" and "low" when logical "0."
6 24 DATA 5 IN

7 25 DATA 6 IN

8 26 DATA 7 IN

9 27 DATA 8 IN

Approximately 5 /as pulse; "low" indicates that data has been received and the printer is
10 28 ACKNLG OUT
ready to accept other data

A "high" signal indicates that the printer cannot receive data. The signal becomes "high"
in the following cases.
11 29 BUSY OUT
1. During data entry 3. In "offline" state.
2. During printing operation. 4 During printer error status.

12 30 PE OUT A "high" signal indicates that the printer is out of paper.

13 -
SLCT OUT This signal indicates that the printer is in the selected state.

AUTO With this signal being at "low" level, the paper is automatically fed one line after printing. (The
14 IN
F EEDXT signal level can be fixed to "low" with DIP SW pin 2-3 provided on the control circuit board.)

15 IC Not used.

16 ov Logic GND level

CHASIS- Printer chasis GND. In the printer, the chassis GND and the logic GND are isolated from
17 - -

GND each other.

18 NC Not used.

19-30 GND "Twisted-Pair Return" signal; GND level.


When the level of this signal becomes "low" the printer controller is reset to its initial state
31 -
INIT IN and the print buffer is cleared This signal is normally at "high" level, and its pulse width
must be more than 50 ms at the receiving terminal.

The level of this signal becomes "low" when the printer is in "Paper End" state, "Offline"
32 ERROR OUT
state and "Error" state

33 GND Same as with pin numbers 19 to 30.

34 NC Not used.

35 Pulled up to +5 Vdc through 4.7 k-ohms resistance

Data entry to the printer is possible only when the level of this signal is "low." (Internal
36 -
slcTTn IN fixing can be carried out with DIP SW 1-8. The condition at the time of shipment is set
"low" for this signal, )

1. "Direction" refers to the direction of signal flow as viewed from the printer.
2. "Return" denotes "Twisted-Pair Return" and is to be connected at signal-ground level.
When wiring the interface, be sure to use a twisted-pair cable for each signal and never fail to complete connection on the return side. To prevent
noise effectively, these cables should be shielded and connected to the chassis of the system unit
3 All interface conditions are based on TTL level. Both the rise and fall times of each signal must be less than 0.2 ms.
4. Data transfer must not be carried out by ignoring the ACKNLG or BUSY signal. (Data transfer to this printer can be carried out only after
confirming the ACKNLG signal or when the level of the BUSY signal is "low ")

FIGURE 9-12 Pin connections and descriptions for Centronix-type parallel


interface to IBM PC and EPSON FX-100 printers. (IBM Corporation)

Figure 9-13 shows the timing waveforms for transfer- lines for at least 0.5 ijls after the STROBE signal is made
ring data
characters to an IBM printer using the basic high.
handshake signals. Here's how this works. When the printer is ready to receive the next charac-
Assuming the printer has been initialized, you first ter,asserts
it its ACKNLG signal low for about 5 /us. The
check the BUSY signal pin to see if the printer is ready to rising edge of the ACKNLG signal tells the microcom-
receive data. If this signal is low. indicating the printer puter that
it can send the next character. The rising
is ready (not busy), you send an ASCII code on the eight edge of the ACKNLG signal also resets the BUSY signal
parallel data lines. After at least 0.5 jus you assert the from the printer. BUSY being low is another indication
STROBE signal low to tell the printer a character has that the printer is ready to accept the next character.
been sent. The STROBE signal going low causes the Some systems use the ACKNLG signal for the hand-
printer to assert its BUSY signal high. After a minimum shake,some
and systems use the BUSY signal. Now let's
time of 0.5 /us the STROBE signal can be raised high see how you can do this handshake printer interface
again. Note that the data must be held valid on the data with an 8255A.

272 ( HAPTER NINE


SDK 86 board so you can easily add this lnt< rfai
BUSY
U~ are woi king with i me
—j [—APPROXIMATELY
5 us Foi this Interface circuitry, 74LS07 open-collectoi
buffers are used mi the signal and data lines from the
ACKNLG
8255A. because the 8255A outputs do not have enough
—| I—0.5(is(MINIMUM) current drive to charge and discharge the capacitance ol
the connecting (able fast enough. Pull-up resistors foi
— 0 5 us (MINIMUM)
the open-collector outputs ol the 74LS07s are built into
the printer.
u Port H is used for the handshake output data lines.
—| h-0 .5 us (MINIMUM) I In refore, as shown in Figure 9 3, bil P< 0 functions as
the interrupt requesi output to the 8086. I he A( KM ( ,
FIGURI l>-l > riming waveforms for transfer of a data signal from the printer is c lected to the 8255A A( K
i hara< tei to a Centronix-type parallel printer sm h as input on bil PC2. The OBI signal from the 8255A does
the IBM-PC or Epson printer. (IBM Corporation) not have the right timing parameters lor this hand
shake, so PC I is left unconnected. For this the STROBl
8255A CONNECTIONS AND INITIALIZATION
input of the printer is connected to bit PC4. The S I K( Mil
Figure 9-14 shows the circuit for connecting the Cen- signal will be generated by a bit set reset of (his pin.
tronics parallel
printer signals to an 8255A. We show The tour printer status signals are connected to port A
here the pin connections for the |6 connector on the so the program can read them in, determine the condi

IBM 25-PIN PRINTER


INTR TO 8086 NMI OR 8259A IR INPUT CONNECTOR r- CONNECTOR

.16
PIN NUMBERS
1 1 3IN NUMBERS

36 32
12
PA) 40 12
13
11 13 M l.l ('111
PA2
11
PA3 48 11
PORT A «
PA4 50 1-1

PA5 46 15

PA6 42 18 NC

38 34
8255A
14
XA35 35 NC
^PCO 26
15
PCI 24 36 NC
16 10
PC2 22 10
17
PC3 20
PORTC -i
PC4
1i
28 5 IS6 1
1

12 Kc ahs. 8 16
31
PC5 30
1 1 ^2D
PC6 32

. PC7
10
34 6 74LS07
2
18
h>2
16
1<A 2
S Don

19
3fS 4 J
3
PB1
20
12

5ts 6
l^B^ 4
PB2
21
8
L^c 9h> 8
:
4

5
DATA 3

PB % : 4
PORT B i 22 KrT^ 6
PB4 6 11r^io 6

PB5
23
10
I^E 13f»v12 7 7 DATA 6
% "if
24
'IS 2 8
R
PB6
25
14
Ra 3fS4 9
9
_ PB7 18

1
f^r

IC 1 AND

GND = PIN
2 ARE

7
74LS07 V 3

J6
16

17
LOGIC GND

FICURE 9-14 Circuit for interfacing Centronix-type parallel input printer to


8255A on SDK-86 board.

DIGITAL INTERFAC INK, 273


D7 D6 D5 D4 D3 D2 D1 D0 example here assume that the interrupt request from
I 0 0 10 1 0 D PCO of the 8255A is connected to the IR6 interrupt input
of the 8259A shown in Figure 8-14 so that a clock inter-
C LOWER = X
rupt,
keyboard
a interrupt, and the printer interrupt
B = OUT can all be serviced in turn.
B = MODE 1 Figure 9- 16a shows the steps you need in the main-
C UPPER = OUT lineinitialize
to everything and "call" the printer driver
A INPUT
to send a string of ASCII characters to the printer.
A = MODE 0
At the start of the mainline some named memory loca-
MODE SET WORD
tions are
set aside to store parameters needed for trans-
fer of
data to the printer. The memory locations set aside
for passing information between the mainline and the

D7 D1 DO
driver procedure are often called a control block. In the
D6 1". D4 D 3 0?
control block a named location is set aside for a pointer
0 0 0 0 0 1 0
I to the address of the ASCII character that is currently
being sent. Another memory location is set aside to
~T~ ~1 ' ^- SETTO ENABLE store the number of characters to be sent. The number
BIT 2 CONTROLS INTR ON PC0
in this location will function as a counter so you know
DON'T CARES
when you have sent all of the characters in the buffer.
BIT SET/RESET CONTROL WORD
Instead of using this counter approach to keep track of
how many characters have been sent, the sentinel
method we described for handshake output to the
FIGURE 9-15 825I)A control words for printer interface.
SC-01A in Figure 9-10 could have been used. With the
(a) Mode control word, (b) Bit set/reset control word.
sentinel approach you put a sentinel character in mem-
ory after the last character to be sent out. MSDOS, for
example, uses a $ (24H) as a sentinel character for some
tion of the printer, and send the appropriate messages of its drivers. As you read each character in from mem-
to the CRT if the printer is not ready. ory, you compare it with the sentinel value. If it
Finally the INIT input of the printer is connected to bit matches, you know all of the characters have been sent.
PC5 so that the printer can be reinitialized under pro- The sentinel approach and the counter approach are
gram control.
Now let's look at the 8255A control words both widely used, so you should be familiar with both.
for this application. To get the hardware ready to go. you need to initialize
Figure 9- 15a shows the mode control word to initial- the 8259A and unmask the IR inputs of the 8259A that
ize portB in MODE 1 output, port A for MODE 0 input. are used. The 8086 INTR input must also be enabled.
and the upper 4 bits of port C as outputs. Figure 9- 15b Next the 8255A must be initialized by sending it the
shows the bit set/reset control word necessary to enable mode control word shown above. A bit set/reset control
the interrupt request signal on bit PCO for the hand- word is then sent to the 8255A to make the STROBE sig-
shake. The
addresses for the 8255A, XA35. on the nal tothe printer high because this is its unasserted
SDK-86 board are. as shown in Figure 7-15. port IMA — level. To make sure the printer is internally initialized,
FFF9H. port P1B— FFFBH. port PIC— FFFDH. and con- you pulse the INIT line to the printer low for a few micro-
trol —
PI FFFFH. For that system, then, both control seconds.
words are output to FFFFH.
When you are actually ready to print some characters
in a program, you first read the printer status from port
THE PRINTER DRIVER PROGRAM
A and check if the printer is selected, not out of paper,
Procedures which input data from or output data to pe- and not busy. In a more complete program you could
ripheral devices
such as disk drives, modems, and send a specific error message to the display indicating
printers are often called I/O drivers. Here we show you the type of error found. The program here just sends a
one way to write the driver procedure for our parallel general error message. If no printer error condition is
printer interface. found, you load the starting address of the string of
The first point to consider when writing any I/O driver ASCII characters into the control block location you set
is whether to do it on a polled or on an interrupt basis. aside for this, and load the number of characters to be
For the parallel Centronics interface here the maximum sent in the reserved location in the control block. Fi-
data transfer rate is about 1000 characters/second. This nally, you
enable the interrupt request pin on the
means that there is a little less than 1 ms between trans- 8255A. Note that you do not enable this interrupt until
fers.
characters
If are sent on an interrupt basis, many you are actually ready to send data. A high on the
oilier program instructions can be executed while wait- ACKNLG line from the printer causes the 8255A to out-
ing for
the interrupt request to send the next character. put an
interrupt request signal. This interrupt request
Also, when the printer buffer gets full, there will be an signal goes through the 8259A to the processor and
even longer time that the processor can be working on causes it to go to the interrupt service procedure.
some hi her job while waiting for the next interrupt This Figure 9- 16b shows the algorithm for the procedure
is another illustration of how interrupts allow the com- which services this interrupt and actually sends the
putei to do several tasks "at the same time." For our characters to the printer. After pushing some registers

274 CHAPTER NINE


the 8086 l\IK Input is enabled so thai highei priority Ing ol the charactei is now complete, so the next step is
Interrupts can interrupt this procedure. I'he string ad- to gel ready to send another i harai tei
dress pointei
is then read in from the control block and To do ilns tin buffei pointei is incremented by one,
used to read a i harai tei in from the memory buffer to and the Incremented value is placed hark in the i ontrol
Al. The charactei in Al. is then output to port li ol the block location. The charactei countei in the control
8255A. block is then (U( remented If the ch untei Is
From here on the program follows the timing diagram not down to zero thi re are more charai icis to si nd so
in Figure 9 13 Aftei sending the character the program the EOl command is simply sent to the
waits .ii least 0.5 /is, asserts the STROBI input low. thing popped oil the stack, and execution returned to
waits .n least anothei 0 5 (is and raises the STR( )BI line the interrupted program. 11 the character countei is
high again. The data byte will be latched on the pm i li down to zero, all of the characters have been sent, so the
output pins until the next charactei is sent, so the data interrupt request output ol the 8255A is disabled with a
hold parameter in the timing diagram is sat isfied. Scud bit set resel control word to prevent further interrupt

Mainline algorithm for printer driver

Initialization
set up control block

word tor storing pointer to ASCII string

word for number of characters in string

initialization control words to 3259A

unmask 8 2 59 A I.R6 and any other IR inputs used

unmask 8086 INTR input

mode set word to EI255A

send STROBE high to printer

initialise printer (pulse in it low)

To send ASCII string

read printer status from port

i f error then

send error message

ex i t

set print done status bit

load starting address of string into pointer store,

load length of string into character counter

enable 8255A INTR output

wa it f or i n terr up t
(a)

FIGURE 9-16 Algorithm for printer mainline and interrupt-based printer driver
procedure, (a) Mainline steps, (b) Printer driver procedure steps.

DIGITAL INTERFACING 275


Printer .Driver Procedure Algorithm

save registers

enable 8086 INTR -for higher priority interrupts

get. pointer to string

get ASCII char acter from butter

send character to printer

wait 1 usee

send STROBE low

wait 1 usee

send STROBE high

increment pointer to string

put pointer' back in pointer store

decrement character count

if character count = 0 then

disable E3255A interrupt request output

send EOI command to 8259A

restore registers

return from interrupt, procedure

i/, i

FIGURE 9-16 (continued)

requests from there. This interrupt source will remain larity requirements of the receiving device. Here we gen-
disabled until you want to send another buffer of char- erate the
strobe directly under software control.
acters
theto printer. Execution then exits from the pro- In the mainline we make the STROBE signal on PC4
cedure
sending
by an EOI command to the 8259A, pop- high by sending a bit set/reset control word of 00001001
ping registers,and doing an IRET. to the control register of the 8255A. In the printer driver
Figure 9- 17 shows the pertinent parts of the mainline procedure a character is sent to the printer with the
program and the printer driver procedure. The preced- OUT DX, AL instruction. According to the timing dia-
ing discussion of the algorithms and the comments gram Figure
in 9-13 we then want to wait at least 0.5 //s
with the instructions should make most of these rea- before asserting the STROBE signal low. This is automat-
sonably ifclear
you work your way through them one ically done
in the program because the instructions re-
step at a time. You have seen many of the pieces in previ- quired
assert
to the strobe low take longer than 0.5 us.
ous programs. One part of the program that we do want The MOV AL, 00001000B instruction requires 4 clock cy-
to expand and clarify is the generation of the STROBE cles, and
the OUT DX, AL instruction requires 8 clock
signal with bit PC3. cycles to execute. Assuming a 5-MHz clock (0.2-fis pe-
In the speech synthesizer example in a preceding sec- riod), these
two instructions take 2.4 /is to execute,
tion we
used external hardware to "massage" the OBF which is more than required.
signal from the 8255A so it matched the timing and po- Again referring to the timing diagram in Figure 9-13.

276 CHAPTtK NINE


page .132
8086 Printer -driver program
This program sets up the 8259A and the 8255A on an SDK-8t
board so that a message in a buffer can be sent to a
printer. The mainline sets up a control block and
initializes all variables
PORTS USED: SDk-86 ports P1A - FFF9H used to input status of printer
P1B - FFFBH used to output a character
PIC - for handshake signals for port B
PROCEDURES: PR1NTJT used to output characters

AJNT.TABLE SEGMENTWBR&
TYPE_6't_69 DW 12 DUP(O) ; reserved for IR0-IR6
TYPE.70 DW 2 DUP(O) ; IR6 interrupt
TYPE_71 DW 2 DUP(O) i IR7 interrupt - not used
A.INTJABLE
" ENDS
DATA HERE SEGMENT WORDPUBLIC
MESSAGE 'This is the message from the printer driver!'
ODH, OAH, ODH i return J, line-feed for printer
PRIMIDONE 0
POINTER 00 ; storage for pointer to MESSAGEJ
COUNTER 0 ; counter for length of MESSAGEJ
PRINTER.ERROR
DB 0
DATA.HERE
"ENDS
PUBLIC PRINTJJONE, POINTER,COUNTER.
MESSAGE 1
EXTRN PRINT.IT:FAR
MESSAGE.LENGTH EQU <t7 ; length of MESSAGE
1
STACK.HERE SEGMENT
DW 30 DUP(O)
STACK. TOP LABEL WORD
STACK HERE ENDS

CODE.HERE SEGMENT
WORDPUBLIC
ASSUME
CS:CODE_HERE,
DS:A_INT_TABLE,
SS:STACK.HERE
MOV AX, STACK.HERE ; initialize stack segenent
MOV SS, AX
MOV SP, OFFSETSTACK
.TOP
MOV AX,A.INTJABLE
"
MOV DS, AX
iset up interrupt table and put in address for printer interrupt subroutine
MOV TYPE.70+2,SEGPRINT.IT
MOV TYPEJO,OFFSET
PrFnTJT
ASSUME
DS:DATA.HERE
"
MOV AX, DATA.HERE ', set up data segment
MOV DS. AX
initialize 82 J9A and uneask IR6
MOV DX, 0FF00H i point at 8259A control address
NOV AL, 0001001 IB ; ICW1, edge triggered, single, 8086
GUT DX, AL ; send ICW1
NOV DX. 0FF02H ; point at ICW2address
MOV AL, 01000000B 5 type 64 is first 8259A type
OUT DX, AL ; send ICW2

FIGURE 9-17 8086 assembly language instructions for mainline and printer
driver procedure, (a) Mainline, (b) Procedure.

DIGITAL INTERFACING 277


MOV Ml 0000000 IB ICWt, 3036 node
GUI DX, AL send ICW4
MOV ML lOllilUB 0CW1 to unmask IR6
GbT DX, AL send 0CW1
<:e 3255A, PlA-model input. PlB-modeO output. Unused PIC bits-output
MOV DX, OFFFFH control address for 8255A
MOV HL 10010100B control word for above conditions
OUT DX, AL send control word
3TI ".unmask 808b INTR interrupt
isend STROBEhigh to printer with bit set o PC<t
MOV AL, 0000 i 00 IB
OUT DX, AL
; initialize printer - pulse INIT low for > 50 useconds (on PCS)
MOV AL, 000011 01 B bit set on PCS
OUT DX, AL send INIT high
MOV AL, 00001 100B bit reset on PCS,
OUT DX, AL send INIT low
MOV CX, 17H wait : 50 usee
PAUSE 1 LOOP PAUSE1
MOV AL, 00001 1016 bit set on PCS
OUT DX, AL send INIT high again
Iread printer status from port A, status Ok - AL XXXX0101
;PA3-BUSY'=0,PA2-SLCT=I, PAl-PE^O, PA0-ERR0R=1
MOV PRINTER.ERROR. ", printer OKso far
MOV DX, 0FFF9H ; point at port A
IN AL, DX ; get status of printer
AND AL, OFH I upper four bits are not used
CNF AL, 000001016 ; is status OK
j: SEND IT ; send it if OK
Sprinter not ready, try once more after waiting 20 ms
MOV CX, 16EAH load count for 20ms
PAUSE: LOOP PAUSE and wait
IN AL, DX repeat steps to read status
AND AL, OFH
CMP AL, 00000101 B

JZ SEND.IT is printer ready yet7


MOV PR1N~TER_ERR0R,
01 set error code
JMP FIN not read*? so terminate send

iset up pointer to message storage and say print not done yet
SEND_IT:MOV AX, OFFSETMESSAGE
J
MOV POINTER, AX
MOV PRINT.DONE, 00
MOV COUNTER, MESSA8E.LENGTH
ienable 8255A interrupt request output on PCOby setting PC2
MOV DX, OFFFFH i point at port control addr
MOV AL, 00000101B ; bit set word for PCO intr
OUT DX, AL
'.wait for an interrupt from the printer
WT: JMP UT
FIN: NOP

CODE HERE ENDS


END

FIGURI 9-17 (continued)

278 CHAPTLR NIN[


PAGE ,132
8036 Procedure for printer driver progran
ABSTRACT: This procedure outputs a character from a buffer to
a printer. If no characters are left in the buffer
then the interrupt to the 8086 on IRS of the 8259A
is disabled
PROCEDURES: None used
PORTS: Uses SDK-86 board Port P1B (FFFBH) to output characters
Port PIC bits for handshake signals and printer intr
REGISTERS USED:AX,BX, DX Flags, destroys no registers

PUBLIC PRINT.IT
DATA_HERE
" SEGMENT
PUBLIC
EXTRN C0UNTER:6YTE, P0INTER:W0RD
EXTRN MESSAGE
.1 :BVTE. PR I NTDQNE:BYTE
DATA HERE ENDS

C0DE_HERE SEGMENT
WORD
PUBLIC
PRINT.IT PROC FAR
ASSUME CS:C0DE HERE, DS:DATA HERE
PUSH save registers
PUSH
PUSH
STI ; enable higher interrupts
MOV DX, OFFFBH ; point at port B
MOV BX, POINTER : load pointer to message
MOV AL, [BX] ; get a character
OUT DX, AL ; send the character to printer
jsend printer strobe on PC1*low then high
MOV DX, OFFFFH ; point at port control addr
MOV AL, 00001000B j strobe low control word
OUT DX, AL
MOV AL, 00001001B ; strobe high control word
OUT DX, AL
! increment pointer and decrement counter
INC BX
MOV POINTER, BX
DEC COUNTER
JNZ NEXT i wait for next character?
ino more characters-disable 3255A int reguest on PCO by bit reset of PC2
MOV AL, 00000 100B
GUT DX, AL
MOV PRINT.DONE.1
NEXT: MOV AL, 00100000B ; 0CW2for non-specific EOI
MOV DX, OFFOOH ; point at 8259A control addr
OUT DX, AL
POP DX ", restore registers
PC^' BX
PGP AX
IRET
PRINT.IT ENDP
CODE.HERE ENDS
PNG

(/,)
FIGURE 9-17 (continued)

DIGITAL INTERFACING 279


the STROBE time low must also be at least 0.5 /us. The waveforms for this case are the same as those in Figure
MOV AL. 0000 100 IB instruction takes 4 clock cycles 9-9. except that you are not using the interrupt request
and the OUT DX, AL instruction takes 8 clock cycles. output from the 8255A.
With a 5-MHz clock this totals to 2.4 /us. which again is Port C bits not used for handshake signals and pro-
more than enough time for STROBE low. In this case cre- grammed
outputs
as can be written to by sending bit
ating the STROBE signal with software does not use set/reset control words to the control register. Techni-
much of the processor's time, so this is an efficient way cally, bits
PCO—PC3 can also be written to directly at the
In (In ll port C address, but we have found it safer to just use the
bit set/reset control word approach to write to all leftover
A FEW MORE POINTS ABOUT THE 8255A port C bits programmed as outputs.
Before leaving our discussion of the 8255A we want to
show you a little more about how port C is used.
INTERFACING A MICROPROCESSOR TO
Any bits of port C which are programmed as inputs
KEYBOARDS
can be read by simply doing a read from the port C ad-
dress.can
You mask out any unwanted bits of the word Keyboard Types
read in. If port A and/or port B is programmed in a
When you press a key on your computer you are activat-
handshake mode, then some of the bits of a byte read in
ingswitch.
a There are many different ways of making
from port C represent status information about the
these switches. Here's an overview of the construction
handshake signals. Figure 9-18 shows the meaning of
and operation of some of the most common types.
the bits read from port C for port A and/or port B in
MODE I. Here's how you read this diagram. If port B is
MECHANICAL KEYSWITCHES
initialized as a handshake (MODE 11 input port, then
bits DO, Dl. and D2 read from port C represent the sta- In mechanical switch keys, two pieces of metal are
tus the
of port B handshake signals. Bit D2 will be high pushed together when you press the key. The actual
if the port B interrupt request output has been enabled. switch elements are often made of a phosphor-bronze
Bit 1)1 is a copy of the level on the input buffer full (IBF) alloy with gold plating on the contact areas. The key-
pin. Bit DO is a copy of the interrupt request output, so switch usually contains a spring to return the key to the
it will be high if port B is requesting an interrupt. nonpressed position and perhaps a small piece of foam
In our previous application examples, we showed how to help damp out bouncing. Mechanical switches are
to do handshake data transfer on an interrupt basis to relatively inexpensive, but they have several disadvan-
make maximum use of the CPU time. However, in appli- tages. First,
they suffer from contact bounce. A pressed
cations where
the CPU has nothing else to do while wait- key may make and break contact several times before it
ing to.
for example, read in the next character from makes solid contact. Second, the contacts may become
some device, then you can save one interrupt input by oxidized or dirty with age so they no longer make a de-
reading data from the 8255A on a polled basis. To do pendable connection.
Higher-quality mechanical
this for a handshake input operation on port B you sim- switches typically have a rated lifetime of about 1 million
ply loopthrough reading port C and checking bit D1 keystrokes.
over and over until you find this bit high. The IBF pin
being high means that the input data byte has been MEMBRANE KEYSWITCHES
I.iii hed into the 8255A and can now be read. The timing These switches are really just a special type of mechani-
cal switch.They consist of a three-layer plastic or rubber
sandwich as shown in Figure 9- 19a. The top layer has a
conductive line of silver ink running under each row of
POUT C BITS
keys. The middle layer has a hole under each key posi-
D, ! D, Dt D, D, . D. . D„ tion. The
bottom layer has a conductive line of silver ink
running under each column of keys. When you press a
key you push the top ink line through the hole to con-
STATUS
tact the
bottom ink line. The advantage of membrane
INPl IT keyboards is that they can be made as very thin, sealed
p< »fl [
units. They are often used on cash registers in fast food
restaurants, on medical instruments, and in other
°7 °6 °5 D4 D3 °2 i,\ °0 messy applications. Lifetime of membrane keyboards
| „ »FA ,NTEfl;iWTRA| R7 IBFB ™.| varies over a wide range.
OUTPUT OUTPUT
PORT PORT CAPAC1TIVE KEYSWITCHES
I I
As shown in Figure 9-195. a capacitive keyswitch has
D7 D6 \ °4 D3 D2 ', Do two small metal plates on the printed-circuit board and
I °"^A INTE.
fll
"0
/'" l ra 6bfb H another metal plate on the bottom of a piece of foam.
When you press the key. the movable plate is pushed
FICURI 9-18 8255A status word format tor MODE 1 closer to the fixed plate. This changes the capacitance
input and output operations. between the fixed plates. Sense amplifier circuitry de-

280 < MM'IIR NINE


VITH ROW Keyboard ( ircuil Connections and Interfacing
CONLXu 1
In most keyboards the keyswili hes are i onnected in a
SHI ETWITH HOI I S
matrix ol rows and columns as shown in Figun 9-20
SHI I rWITH COLUMN We will use simple mechanical switches foi oui
CONDUCTORS
pics here, but the principle is the same I thei types ol
swiic lies. Getting meaningful data from a keyboard
such .is this requires doing three major tasks. They are

KEY CAP
1. Detecl .i Kc\ pi ess
RETURN SPRING

PLUNGER
2. Debounce the keypress.
FOAM PAD 3. Encode il (Produi e a standard code for the pressed
MOVABLE PLATE key).
FIXED PLATES

The three tasks can be done with hardware, software, oi


,i combination of the two, depending on the applii ation
We will first show you how they can be done with soft-
waremight
as be done in a microprocessor-based gro-
cery scale
where the microprocessor is not pressed for
time. Later we describe some hardware devices which do
KEY MOTION these tasks.
HALL
CRYSTAL VOLTAGE

REFERENCE
Software Keyboard Interfacing
CURRENT
CIRCUIT CONNECTIONS AND ALGORITHM

Figure 9-20a shows how a hexadecimal keypad can be


connected to a couple of microcomputer ports so our
three tasks can be done as part of a program. The rows
FIGURE 9-19 Key switch types, (a) Membrane. of the matrix are connected to four output port lines.
(b) Capacitive. (c) Hall effect. The column lines of the matrix are connected to four
input port lines. When no keys are pressed, the column
lines are held high by the pull-up resistors to +5 V. The
tects this change in capacitance and produces a logic- main principle here is that pressing a key connects a
level signal that indicates a key has been pressed. The row to a column. If a low is output on a row and a key in
big advantage of a capacitive switch is that it has no that row is pressed, then the low will appear on the col-
mechanical contacts to become oxidized or dirty. A umn which contains that key and can be detected on the
small disadvantage is the specialized circuitry needed to input port. If you know the row and the column of the
detect the change in capacitance. Capacitive key- pressed key, you then know which key was pressed, and
switches typically have a rated lifetime of about 20 mil- can make up any code you want to represent that key.
lion keystrokes. Figure 9-20b shows a flowchart for a procedure to de-
tect, debounce.and produce the hex code for a pressed
HALL EFFECT KEYSWITCHES
key.
This is another type of switch which has no mechanical The first step is to output O's to all of the rows. Next
contact. It takes advantage of the deflection of a moving the columns are read and and checked over and over
charge by a magnetic field. Figure 9- 19c shows you how until the columns are all high. This is done to make sure
this works. A reference current is passed through a a previous key has been released before looking for the
semiconductor crystal between two opposing faces. next one. In standard keyboard terminology this is
When a key is pressed, the crystal is moved through a called two-key lockout. Once the columns are found to
magnetic field which has its flux lines perpendicular to be all high the program enters another loop which waits
the direction of the current flow in the crystal. (Actually until a low appears on one of the columns, indicating a
it is easier to move a small magnet past the crystal. 1 kev has been pressed. This loop does the detect task for
Moving the crystal through the magnetic field causes a us. A simple 20-ms delay procedure then does the
small voltage to be developed between two of the other debounce task.
opposing faces of the crystal. This voltage is amplified After the debounce time another check is made to see
and used to indicate that a key is pressed. Hall effect if the key is still pressed. If the columns are all high.
keyboards are more expensive because of the more com- then no key is pressed and the initial detection was just
plex switch
mechanisms, but they are very dependable, a noise pulse or a light brushing past a key. If any of the
and have typical rated lifetimes of 100 million or more columns are still low. then the assumption is made that
keystrokes. it is a valid keypress.

DIGITAL INTERFACING 281


.:erii to
ALL ROWS

OUTPUT
PORT 01

READ
COLUMNS

NO s
/all\.
KEYS

YES

READ
COLUMNS

NO y. /key\

WAIT
20 ms

OUTPUT
ZERO TO
ONE ROW

READ

FIGURE 9-20 Detecting a matrix keyboard key-press, COLUMNS

debouncing it, and encoding it with a microcomputer.


(a) Port connections, (b) Flowchart for procedure.

The final task is to determine the row and column of


the pressed key. and convert this row and column infor-
mation
the to hex code for the pressed key. To get the
row and column information, a low is output to one row
and the columns are read. If none of the the columns are
low. the pressed key is not in that row. so the low is
HJRNJ
rotated to the next row and the columns are checked
again. The process is repeated until a low on a row pro-
duces
lowa on one of the columns. The pressed key is in
the row which is low at that time. The byte read in from down through these parts until you reach the ENCODE
the input port will contain a 4-bit code which represents label, then continue with the discussion here.
the row of the pressed key and a 4-bit code which repre-
sents the
column of the pressed key. As we show later,
CODE CONVERSION
this row-column code can easily be converted to hex
using a lookup table. There are two major ways of converting one code to an-
Figure 9-2 1 shows the assembly language program for othera inprogram. The ENCODE portion of this pro-
this procedure. The detect, debounce, and row-detect gram usesa compare technique, which is important for
parts ol the program follow the flowchart very closely you to learn, so we will discuss this portion in detail. In
and should be easy lor you to follow. Work your way a later section on keyboard interfacing with hardware

282 CHAPTfR NINE


paqe ,132
; 8086 Prograi to scan and decode a 16 switch keypad
; ABSTRACT : This proqra* initializes the ports below and then
'• calls a procedure to input an 8-bit value from
I a 16-switch keypad and encode it.
JPORTS : SDK-86 board Port Plft - FFF9H as output, P1B - FFFBH as input
IROUTINES : Calls KEYBRDto scan and decode 16-switch keypad
REGISTERS: Uses DS, SS. SP. AX, DX

DATA_HERE SEGMENT
WORD PUBLIC
TABLE DB 77H, 7BH. 7DH, 7EH, 0B7H, OBBH. OBDH, OBEH
i 0 12 3 4 5 6 7
DB 0D7H, OBBH, ODDH, ODEH. 0E7H, OEBH, OEDH, OEEH
8 9 A B C D. E F
DATAJERE ENDS
STACK.HERE SEGHENT
DU 30 DUP(0> i set up stack of 30 words

TOP.STACk LABEL WORD ; pointer to top of stack


STACKHERE ENDS

C0DE_HERE SEGHENT WORD PUBLIC


ASSUMECS:CODE_HERE. DS:DATA_HERE,
SS:STACK_HERE
; initialize segment registers
START: F10V AX, STACK_HERE
MOV SS, AX
MOV SP, OFFSETTOP.STACK
MOV AX, DATA_HERE
MOV DS. AX
I initialize ports, load DX with port control address
MOV DX, OFFFFH
Isode set word, port A as output, node 0, port B !. C input ports, node 0
MOV AL, 1000101 IB ; code 8BH
OUT DX. AL ; Send control word
CALL KEYBRD
NOP
NOP
iprogras will continue here with other tasks

JPROCEDUREKEYBRD
;ABSTRACT
: procedure gets a code froe a 16-switch keypad and decodes
; it. It returns the code for the keypress in AL and AH=00. If there
; is an error in the keypress then it returns AH=01 .
iPORTS : Uses SDK-86 ports PI A - FFF9H as output and P1B - FFFBHas input
; INPUTS : Keypress froi port
iOUTPUTS : Keypress code or error message in AX
ROUTINES : None used
REGISTERS: Destroys AX

KEYBRD PROC NEAR


PUSHF ; save registers used
PUSH BX
PUSH CX

FIGURE 9-21 Assembly language instructions for keyboard detect, debounce,


and encode procedure.

DIGITAL INTERFACING 283


PUSH DX
MOV AL, 00 ; send O's to all rows
MOV DX, 0FFF9H ', load output address
QUI DX. AL ; send O's
;Read columns
MOV DX, OFFFBH ; load l/p port address
HAITJ3PEN: IN AL, DX
AMD AL, OFH ', mask row bits

CUP AL, OFH ; wait until no keys pressed


JNE HAIT.OPEN
;Read columns for keypress
IN AL, DX ', read columns
HAIT.PRESS:
AND AL, OFH ; mask row bits

CHP AL, OFH ; see if keypressed

IE HAIT.PRESS
;Debounce key;iress
MOV CX, 16EAH i delay of 20 »s
DELAY: LOOP DELAY
IN AL, DX ; read columns

AND AL, OFH


CHP AL, OFH ; see if key still pressed
JE HAIT.PRESS
Unitialize a row sasl' with bit 0 low
MOV AL, OFEH
110V CL, AL ; save mask

NEXT ROM: MOV DX, 0FFF9H ; put a low on one row

OUT DX, AL
MOV DX, OFFFBH ; read columns & check for low

IN AL, DX
AND AL, OFH ; mask out row code

CMP AL, OFH ; check for low in a column

JNE ENCODE ', found column, now encode it


ROL CL, 01 ; rotate mask

MOV AL, CL ; move mask

IMP NEXTROH ; look at next row


;Encode the row/column information
ENCODE: MOV BX, OOOFH ; set up BX as a counter

IN AL, DX ; read row and column from port

CMP AL, TABLE!BX1 ; compare row/col code with table


TRY.NEXT:
JZ DONE
DEC BX ; point at next table entry
JNS TRY.NEXT
MOV AH, 01 ; pass an error code in AH
J MP EXIT
DONE: MOV AL, BL ; hex code for key in AL
MOV AH, 00 ; valid-code key in AH
EXIT: MOP
POP D(
POP ex
POP BX
POPF
REI

KEYBRD ENDP
CODE_HERE ENDS
END START
FIGURL ()-2l (continued)

284 CHAPTIR NINE


we will show vmi the other major code conversion lech cm i ii trap il two keys In thi s; ; row wei e pri
nlque which we call add and point. exactly the same time. A column codi with two lows in il
Alin the row which produces a low on one ol the col- would he produced. This would not match any ol th<
umns
found,
is execution jumps to the label ENCODE. row and coll ill il I codes in the table. Alter all ol the v, lines

The IN AL, DX instruction here reads the row and col m the table wen- checked, BX would in di( remented to
iimn codes in from the input port. This 8-bil code read FFFFI I and AL would then be compared with a value ofl
in represents the key pressed. All that has to be done m memory at offsel FFFFH The cycle would continue
now is to convert this .s-hii code to the simple hex code until, by chance, the value in a memory location
for the key pressed. Foi example il von press ihc D key, matched the row and column code in AL. The contents
you want to exit from the procedure with ODH in AL. ol HI. at that point would he passed back to the calling
The conversion is done with the lookup table declared routine. 1 he chances are I in 256 that this would be the
with DBs at the top ol Figure 9-21. This table contains correct value. Since these are not very good odds, it is
the 8 Imi keypressed codes for each ol the l<> keys. Note advisable to put error traps in your programs wherever
that the codes are put in the table in order for the hex there is a chance lot it to go oil to "never never land' in
code they represent. The principle ol the conversion this way. The error/no-error code can be passed back to
technique we use here is to compare the row and col- the calling program in a register as shown, in a dedi-
umn code
read in with each of the values in the table cated memorylocation, or on the stack.
mil tl a match is found. We use a counter to keep track of
how lai down (he table we have to go to find a match for
a particular input code. When a match is found, the Keyboard Interfacing With Hardware
counter will contain the hex code for the key pressed. The previous section described how you can connect a
In the program in Figure 9-21 we use the BX register keyboard matrix to a couple of microprocessor ports,
as the counter and as a pointer to one of the codes in the and perform the three interfacing tasks with program
table. To start we load a count of OOOFH in BX with the instructions. For systems where the CPU is too busy to
MOV BX, OOOFH instruction. The CMP AL, TABLE[BX| be bothered doing these tasks in software, an external
alter this compares the code at offset [BX] in the table device is used to do them. One example of an MOS de-
with the row and column code in AL. BX contains vice whichcan do this is the General Instruments
OOOFH and the code in the table at this offset is the row AY-5-2376. which can be connected to the rows and col-
and column code for the F key. If we get a match on this umns a keyboard
of switch matrix. The AY-5-2376 inde-
first compare, we know the F key was pressed, and BL pendently detects
a keypress by cycling a low down
contains the hex code for this key. The hex code in BL is through the rows and checking the columns just as we
copied to AL to pass it back to the calling program. AH is did in software. When it finds a key pressed, it waits a
loaded with 00H to tell the calling program this was a debounce time. II the key is still pressed after the
valid keypress, and a return made to the calling pro- debounce time, the AY-5-2376 produces the 8-bit code
gram. lor the pressed key and sends it out to. for example, a
If we don't get a match on the first compare, we decre- microcomputer port on eight parallel lines. To let the
ment BX
to point to the code for the E key in the table microcomputer know that a valid ASCII code is on the
and do another compare. If a match occurs this time, data lines, the AY-5-2376 outputs a strobe pulse. The
the E key was the key pressed, and the hex code for that microcomputer can detect this strobe pulse and read in
key, OEH, is in BL. If we don't get a match on this com- the ASCII code on a polled basis as we showed in Figure
pare, cycle
we through the loop until we get a match or 4-14. or it can detect the strobe pulse on an interrupt
until the row and column code for the pressed key has basis as we showed in Figure 8-9. With the interrupt
been compared with all of the values in the table. As long method the microcomputer doesn't have to pay any at-
as the value in BX is zero or above after the DEC BX in-
tention
the tokeyboard until it receives an interrupt sig-
struction,
Jump
the if Not Sign instruction, |NS nal, this
so method uses very little of the microcomput-
TRY NEXT, will cause execution to go back to the com-
er's time.
pare instruction. If no match is found in the (able. BX The AY-5-2376 has a feature called two-key rollover.
will decrement from 0 to FFFFH. Since the sign bit is a This means that if two keys are pressed at nearly the
copy of the MSB of the result after the DEC instruction, same time, each key will be detected, debounced. and
the sign bit will then be set. Execution will fall through converted to ASCII. The ASCII code for the first key and
to an instruction which loads an error code of 01H in a strobe signal for it will be sent out, then the ASCII code
AH. We then return to the calling program. The calling for the second key and a strobe signal for it will be sent
program will check AH on return to determine if the out. Compare this with two-key lockout which we de-
contents of AL represent the code for a valid keypress. scribed previously
in the software method of keyboard
interfacing.
ERROR TRAPPING
CONVERTING ONE KEYBOARD CODE TO
The concept of detecting some error condition such as
ANOTHER USING XLAT
"no match found" is called error trapping. Error trap-
ping
a isvery important part of real programs. Even in Suppose that you are building up a simple microcom-
this simple program, think what might happen with no putercontrol
to the heating, watering, lighting, and

DIGITAL INTERFACING 285


ventilation of your greenhouse. As part of the hardware, and do the XLAT instruction. When the 8086 executes
you buy a high-quality, fully encoded keyboard at the the XLAT instruction, it internally adds the EBCDIC
local electronics surplus store for a few dollars. When value in AL to the starting offset of the table in BX. Be-
you get the keyboard home you find that it works per- cause
theof way the table is made up. the result of this
fectly,that
but it outputs EBCDIC codes instead of the addition will be a pointer to the desired ASCII value in
ASCII codes that you want. Here's how you use the 8086 the table. The 8086 uses this pointer to copy the desired
XLAT instruction to easily solve this problem. ASCII character from the table to AL.
First look at Table 1-2 which shows the ASCII and The advantage of this technique is that, no matter
EBCDIC codes. The job you have to do here is convert where in the table the desired ASCII value is. the conver-
each input EBCDIC input code to the corresponding sion only
requires execution of two loads and one XLAT
ASCII code. One way to do this is the compare technique instruction. The question may occur to you at this
described previously for the hex-keyboard example. For point. "If this method is so fast, why didn't we use it for
that method you first put the EBCDIC codes in a table in the hex keypad conversion described earlier?'' The an-
memorv in the order shown in Table 1-2. and set up a swerthat
is since the row and column code from the hex
register as a counter and pointer to the end of the table. keypad is an 8-bit code, the lookup table for the XLAT
Then enter a loop which compares the EBCDIC charac- method would require 256 memory locations. Of these
ter inAL with each of the EBCDIC codes in the table 256 memory locations, only 16 would actually be used.
until a match is found. The counter is decremented This would be a waste of memory, so the compare
after each compare so that when a match is found, the method is a better choice. It is important for you to be-
count register contains the desired ASCII code. This come familiarwith both code conversion methods, so
compare technique works well, but for this conversion it that you can use the one that best fits a particular appli-
will, on the average, have to do 64 compares before a cation.
match is found. The compare technique then is often
too time-consuming for long tables. The XLAT method
DEDICATED MICROPROCESSOR KEYBOARD
is much faster.
ENCODERS
The first step in the XLAT method is to make up in
memory a table which contains all of the ASCII codes. Most computers and computer terminals now use de-
You can use the DB assembler directive to do this. Since tached keyboards with built-in encoders. Instead of
EBCDIC code is an 8-bit code, the table will require 256 using a hardware encoder device such as the AY-5-2376
memory locations. The trick here is to put each ASCII these keyboards use a dedicated microprocessor. Figure
code in the table at a displacement equal to the value of 9-23 shows the encoder circuitry for the IBM PC capaci-
the EBCDIC character from the start of the table. For tive-switch matrix keyboard. The 8048 microprocessor
example, the EBCDIC code for uppercase A is CI H, so at used here contains an 8-bit CPU. a ROM. some RAM.
offset C 1H in the table you put the ASCII code for upper- three ports, and a programmable timer/counter. A pro-
case 41H.
A. as shown in Figure 9-22. gram storedin the on-chip ROM performs the three key-
To do the actual conversion, you simply load the BX board tasks
and sends the code for a pressed key out to
register with the offset of the start of the table, load the the computer. To cut down the number of connecting
EBCDIC character to be converted in the AL register. wires, the key code is sent out in serial form rather than
in parallel form. Some keyboards send data to the com-
puterserial
in form using a beam of infrared light in-
TABLE CONTAINING
stead
a of
wire.
ASCII CODES Note in Figure 9-23 the sense amplifier to detect the
change in capacitance produced when a key is pressed.
Also note that the 8048 uses a tuned LC circuit rather
than a more expensive crystal to determine its operating
clock frequency.
One of the major advantages of using a dedicated mi-
croprocessor
do the three
to keyboard tasks is program-
mabilitv. Special function keys on the keyboard can be
programmed to send out any code desired for a particu-
lar application. By simply plugging in an 8048 with a
different lookup table in ROM. the keyboard can be
OFFSET C1H %<
changed from outputting ASCII characters to output-
ting some other character set.
The IBM keyboard, incidentally, does not send out
ASCII codes, but instead sends out a hex "scan'' code for
each key when it is pressed and a different scan code
START OF TABLE. BX when that key is released. This double-code approach
gives the system software maximum flexibility because a
FIGURE 9-22 Memory table setup tor using XLAT to program command can be implemented either when a
convert EBCDIC keycode to ASCII equivalent. key is pressed or when it is released.

286 CHAPTER NINF


CD 1 IA01I^-

'1

SI NSI A I /

SENSE B A9

SENSE C A7
C5 _L P12
20.7 pF % SENSE D A5
P13
SENSE E A3
P1 1
KEYBOARD SENSE F Al
i 15
CAPACITIVE
SENSE G C3
rn. MATRIX
SENSE H E1
CD 1 (A05)<-
1 * * - £A PW
P ' 1
SENSE
i/SS P25 AMPLIFIER

P26

P27

8048
MICROPROCESSOR

^ CD1(A09)

FIGURE 9-23 IBM PC keyboard scan circuitry using a dedicated


microprocessor. (IBM Corporation)

INTERFACING TO ALPHANUMERIC simply change the reflection of available light. There-


DISPLAYS fore, an
for instrument that is to be used in dim light
conditions you have to include a light source for the
Many microprocessor-controlled instruments and ma- LCDs, or use LEDs which emit their own light. Starting
chines toneed
display letters of the alphabet and num- with LEDs. the following sections show you how to in-
bersgive
to directions or data values to users. In sys- terface these
two types of displays to microcomputers.
tems where a large amount of data needs to be
displayed, a CRT is usually used to display the data. In a
later chapter we show you how to interface a microcom-
puter
a CRT.
to In systems where only a small amount of Interfacing LED Displays to Microcomputers
data needs to be displayed, simple digit-type displays are Alphanumeric LED displays are available in three com-
often utilized. There are several technologies used to mon formats.For displaying only numbers and hexa-
make these digit-oriented displays, but we only have decimal letters,
simple seven-segment displays such as
space here to discuss the two major types. These are that shown in Figure l-6a are used.
light-emitting diodes (LEDs) and liquid-crystal dis- To display numbers and the entire alphabet. 18-
plays (LCDs).
LCD displays use very low power, so they segment displays such as that shown in Figure 9-24a,
are often used in portable, battery-powered instru- or 5 by 7 dot-matrix displays such as that shown in Fig-
ments. LCDs
however, do not emit their own light, they ure 9-24bcan be used. The seven-segment type is the

DIGITAL INTERFACING 287


ries with each segment. Here's how you calculate the
w w
value of these resistors.
Each segment requires a current of between 5 and 30
mA to light. Let's assume you want a current of 20 mA.
a a a o d
D D n %¡ a
The voltage drop across the LED when it is lit is about
a a %¡ a a 1.5 V. The output low voltage for the 7447 is a maximum
a a d a a of 0.4 V at 40 mA. so assume that it is about 0.2 V at 20
%¡ D D d a mA. Subtracting these two voltage drops from the sup-
%¡ D D D D
ply voltageof 5 V leaves 3.3 V across the current-limiting
a a a a a
a resistor. Dividing 3.3 V by 20 mA gives a value of 168 SI
for the current-limiting resistor. The voltage drops
across the LED and the output of the 7447 are not ex-
r^ actly predictable and the exact current through the LED
is not critical as long as we don't exceed its maximum
rating. Therefore, a standard value of 150 fl is reason-
able.
COLUMN D.P 12 3 4 5 The circuit in Figure 9-25 works well for driving just
0 0 0®©© one or two LED digits. However, there are problems if
you want to drive, for example, eight digits. The first

££££1' problem is power consumption.


tions, assume
For worst-case
that all eight digits are displaying
digit 8 so all seven segments
calcula-

are lit. Seven segments


the

€££££ times 20 mA per segment gives a current of 140 mA per


digit. Multiplying this by 8 digits gives a total current of
I " I— " I ' I " 1120 mA or 1.12 A for the the eight digits! A second
i x. y. y. problem of the static approach is that each display digit
30- < • 1 requires a separate 7447 decoder, each of which uses,
perhaps, another 13 mA. The current required by the
€££££ decoders and the LED displays might be several times
the current required by the rest of the circuitry in the

&
£IIX instrument.
To solve the problems of the static display approach,
we use a multiplex method. A circuit example is the eas-
iest way
to explain to you how this multiplexing works.
Figure 9-26 shows a circuit you can add to a couple of

ES_£r microcomputer ports to drive some common-anode


displays in a multiplexed manner.
LED
Note that the circuit

TOP VIEW ORIENTATION


TIL 305

FIGURE 9-24 Eighteen-segment and 5 by 7 matrix LED


displays, (a) 18-segment. (b) 5 by 7 dot-matrix display
format, (c) 5 by 7 dot-matrix circuit connections.

least expensive, most commonly used, and easiest to


interface, so we will concentrate first on how to interface
this type. Later we will show the modifications needed to
interface to the other types.

STATIC AND MULTIPLEXED DISPLAY CIRCUITS

Figure 9-25 shows a circuit you might use to drive a


single, seven-segment, common-anode display. For a
common-anode display, a low is applied to a segment to
turn it on. When a BCD code is sent to the inputs of the
7447. it outputs lows on the segments required to dis-
play number
the represented by the BCD code. This cir- BCD INPUTS
cuit connectionis referred to as a static display because
current is being passed through the display at all times. FIGURE 9-25 Circuit for driving single seven-segment
Not< that current-limiting resistors are required in se- LED display with 7447.

288 CHAPTER NINE


COMMON ANODE
DISPLAYS = DL 707

Rl-7 = 1 k<>
Ql-7 = 2N3906

FIGURE 9-26 Circuit tor multiplexing seven-segment displays with a


microcomputer.

has only one 7447 and that the segment outputs of the until all of the digits have had a turn. Then digit 1 and
7447 are bused to the segment inputs of all of the digits. the following digits are lit again in turn. We leave it to
The question that may occur to you on first seeing this you as an exercise at the end of the chapter to write a
is, "Aren't all of the digits going to display the same procedure which is called on an interrupt basis every 2
number?" The answer is that they would if all of the ms to keep these displays refreshed with some values
digits were turned on at the same time. The trick of mul- stored in a table.
tiplexing displays
is that the segment information is With 8 digits and 2 ms per digit you get back to digit 1
sent out to all of the digits on the common bus, but only every 16 ms or about 60 times a second. This refresh
one display digit is turned on at a time. The PNP transis- rate is fast enough that, to your eye, the digits will each
tor in
series with the common-anode of each digit acts appear to be lit all of the time. Refresh rates of 40 to 200
as an on and off switch for that digit. Here's how the times a second are acceptable.
multiplexing process works. The immediately obvious advantages of multiplexing
The BCD code for digit 1 is first output from port B to the displays are that only one 7447 is required, and only
the 7447. The 7447 outputs the corresponding seven- one digit is lit at a time. We usually increase the current
segment code on the segment bus lines. The transistor per segment to between 40 and 60 mA for multiplexed
connected to digit 1 is then turned on by outputting a displays so that they will appear as bright as they would
low to that bit of port A. (Remember, a low turns on a if not multiplexed. Even with this increased segment
PNP transistor. 1All of the rest of the bits of port A should current, multiplexing gives a large saving in power and
be high to make sure no other digits are turned on. After parts.
1 or 2 ms, digit 1 is turned off by outputting all highs to
port A. The BCD code for digit 2 is then output to the NOTE: If you are calculating the current-limiting resis-
7447 on port B, and a word to turn on digit 2 is output tors for
multiplexed displays, make sure to check the
on port A. After 1 or 2 ms. digit 2 is turned off and the data sheet for the maximum current rating for the dis-
process repeated for digit 3. The process is continued plays are
you using.

DIGITAL INTERFACING 289


A disadvantage of the software multiplexing approach side the
8279. The 8279 then automatically cycles
shown here is that it puts an additional burden on the through the process we described previously for sending
CPU. Also, if the CPU gets involved in doing some these codes in sequence to the displays. Figure 9-27
lengthy task which cannot be interrupted to refresh the shows the operation in timing diagram form. The 8279
display, only one digit of the display will be left lit. An first outputs the binary number for the first digit to the
alternative approach to interfacing multiplexed displays 7445 on the SL0-SL3 lines (Figure 7-6. sheet 7) to turn
to a microcomputer is to use a dedicated display con- on the first one of the digit-driver transistors. The lines
troller such
as the Intel 8279. which independently SO and SI in Figure 9-27 represent the SLO and SL1 lines
keeps displays refreshed and scans a matrix keyboard. from the 8279. The 8279 then outputs the seven-
In the next section we show you how an 8279 is con- segment code for the first digit on the A3-A0 and B3-B0
nected
a circuit,
in discuss how the 8279 operates, and lines. This will light the first digit with the desired pat-
show you how to initialize an 8279. tern After
490 /is the 8279 outputs on the A and B lines
a code which turns off all of the segments. For the cir-
cuitFigure
in 7-6. sheet 7, this blanking code will be all
zeros (00H). The display is blanked here to prevent
Display and Keyboard Interfacing with the 8279 "ghosting" of information from one digit to the next
when the digit strobe is switched to the next digit. While
8279 CIRCUIT CONNECTIONS AND OPERATION
the displays are blanked, the 8279 sends out the BCD
OVERVIEW
code for the next digit to the 7445 to enable the digit-2
Sheets 7 ,iii(l 8 of the SDK-86 schematics in Figure 7-6 driver transistor. It then sends out the seven-segment
show the circuit connections for the keypad and the code for digit 2 on the A and B lines. This then lights the
multiplexed seven-segment displays. First let's look at desired pattern on digit 2. After 490 /j.s the 8279 blanks
the display circuitry on sheet 8. The displays here are the display again and goes on to digit 3. The 8279 steps
common-anode and each digit has a PNP transistor through all of the digits and then returns to digit 1 and
switch between its anode and the +5-V supply. A logic- repeats the cycle. Since each digit requires about 640
low is required to turn on one of these switches. Note /us. the 8279 gets back to digit 1 after about 5. 1 ms for
the 2'2-fxF capacitor between +5 V and ground at the top an 8-digit display and back to digit 1 after about 10.3
of the schematic. This is necessary to filter out tran- ms for a 16-digit display. The time it takes to get back to
sients caused
by switching the large currents to the a digit again is referred to as the scan time.
LEDs off and on. The segments of each digit are all con- The point is that once you load the seven-segment
necteda on
common bus. Since these are common- codes into the internal RAM in the 8279. it automati-
anode displays, a low is needed to turn on a segment. cally keeps
the displays refreshed without you having to
Now let's look at sheet 7 in Figure 7-6 to see how these do anything else in the program. As we will show later,
displays are driven. the 8279 can be connected and initialized to refresh a
The drive for the digit-switch transistors comes from wide variety of displays.
a 7445 BCD to decimal decoder. This device is also The 8279 can also automatically perform the three
known as a one-of-ten-low decoder. When a 4-bit BCD tasks for interfacing to a matrix keyboard. Remember
code is applied to the inputs of this device, the output from previous discussions that the three tasks involve
corresponding to that BCD number will go low. For ex- putting a low on a row of the keyboard matrix and
ample, when
the 8279 outputs 0100 or BCD 4, the 7445 checking the columns of the matrix. If any keys are
output labeled 04 will go low. In the mode used for this pressed in that row, a low will be present on the column
circuit the 8279 outputs a continuous count sequence which contains the key, because pressing a key shorts a
from 0000 to 1 1 1 1 over and over. This causes a low to be row to a column. If no low is found on the columns the
stepped from output to output of the 7445 in ring low is stepped to the next row and the columns checked
counter fashion, turning on each LED digit in turn again. If a low is found on a column, then, after a
Only one output of the 7445 will ever be low at a time, so debounce time, the column is checked again. If the
only one LED digit will be turned on at a time. keypress was valid, a compact code representing the key
The segment bus lines for the displays are connected is constructed. Take a look at the circuit on sheet 7 of
to the A3-A0 and B3-B0 outputs of the 8279 through Figure 7-6 to see how an 8279 can be connected to do
some high-current buffers in the ULN2003A. Note that this.
the 22-fl current-limiting resistors in series with the When connected as shown in Figure 7-6. sheet 7, the
segment lines are much smaller in value than those we 74LS156 functions as a one-of-eight-low decoder. In
calculated loi I he static circuit in Figure 9-25 There are other words, if you apply Oil, the binary code for 3, to
two reasons for this First, there is an additional few its inputs, the 74LS156 will output a low on its 2Y3 out-
tenths of a volt drop across the transistor switch on put. Now
remember from the discussion of 8279 display
each anode. Second, when multiplexing displays we refreshing, that the 8279 is outputting a continuous
pass a higher current through the displays so that they counting sequence from 0000 to 1111 on its SL0-SL3
appear as bright as they would if not multiplexed. Here's lines. This count sequence applied to the inputs of the
how the 8279 keeps these displays refreshed. 74LS156 will cause it to step a low along its outputs.
When you want to display some letters or numbers The 74LS156 then puts a low on one row of the key-
you write the seven-segment codes for the letters or board
a at
time.
numbers that you want displayed to a 16-byte RAM in- The column lines of the kevboard are connected to the

290 CHAPTER NINt


PRI S( MLR PROGRAMM1 D '
I t RNAI I Rl '.-'ii! N . 100 KHz SO
!c, 10/jS

ft ft Y BLANKY
:tive HIGH A CODE' A

A I 1IVI HIGH

RETURN LINES ARE SAMPLED ONE AT A TIME AS SHOWN


W-RLoSEL

NOTE SHOWN IS ENCODED SCAN LEFT ENTRY

S2 Sj ARE NOT SHOWN BUT THEY ARE SIMPLY S, DIVIDED BY 2 AND 1

FIGURE 9-27 8279 display refresh timing and keyboard scan timing. (Intel
Corporation)

return lines. RL0-RL7 of the 8279. As a low is put on output to an interrupt input and detect when the FIFO
each row by the scan-line count and the 74LS156. the has a character for you on an interrupt basis, or you can
8279 checks these return lines one at a time to see if any simply check the count in the status word to determine
of them are low. The bottom line of the timing wave- when the FIFO has a code ready to be read. The point
forms Figure
in 9-27 shows when the return lines are here is that, once the 8279 is initialized, you don't need
checked. If the 8279 finds any of the return lines low. to pay any attention to it until you want to send some
indicating a keypress, it waits a debounce time of about new characters to be displayed, or until it notifies you
10.3 ms and checks again. If the keypress is still pres- that it has a valid keypressed code for you in its FIFO.
ent, the
8279 produces an 8-bit code which represents Now that you have an overview of how the 8279 func-
the key pressed. Figure 9-28 shows the format for the tions,will
we show you how to initialize an 8279 to do all
code produced. Three bits of this code represent the of these wondrous things and more.
number of the row in which it found the pressed key.
and another 3 bits represent the column of the pressed INITIALIZING AND COMMUNICATING WITH AN
key. For interfacing to full typewriter keyboards the shift 8279
and control keys are connected to pins 36 and 37 re-
As we have shown before, the first step in initializing a
spectively
the 8279.
of The upper 2 bits of the code pro-
programmable device is to determine the system base
duced represent the status of these two keys.
address for the device, the internal addresses, and the
After the 8279 produces the 8-bit code for the pressed
system addresses for the internal parts. As an example
key it stores the word in an internal 8-byte FIFO RAM.
The term FIFO stands for first-in-first-out, which
means that when you start reading codes from the FIFO,
the first code you read out will be that for the first key
pressed. The FIFO can store the codes for up to eight
CNTL SHIFT SCAN
pressed keys before overflowing. J L
When the 8279 finds a valid keypress, it does two SCANNED KEYBOARD DATA FORMAT
things to let you know about it. It asserts its interrupt
request pin. IRQ, high, and it increments a FIFO count FIGURE 9-28 Format for data word produced by 8279
in an internal status register. You can connect the IRQ keyboard encoding.

DIGITAL INTERFACING 291


Keyboard/Display Mode Set Write Display RAM

MS 3 LSB Code | 1 | 0 0 Al %A A | A A |
Code 1" » ii " D ^
k|k| The CPU sets up the 8279 for a write to the Display RAM
by first writing this command After writing the com-
Where DD is ih %Display Mode and KKK is :' i mand with
A0= 1, all subsequent writes with A0= 0 will
Mode be to the Display RAM The addressing and Auto-
Increment functions are identical to those for the Read
Display RAM However, this command does not affect
0 0 8 8 I lisplay - Lett entry the source of subsequent Data Reads, the CPU will read
0 1 16 8-bit character display Left entr from whichever RAM (Display or FIFO/Sensor) which
was last specified If. indeed, the Display RAM was last
1 0 8 8-bit character display Right enti
specified, the Write Display RAM will, nevertheless,
1 1 16 8-bit character display - Right en change the next Read location

npti ett en Display Write Inhibit/Blanking


Consideral . Mote that when decoded si .in
keyboard mode the display is reduced to 4 ct
independent of display mode set
Code: | 1 | 0 | 1 | X| IW| IW| BL|BL|
KKK

0 u 0 Encoded Scan Keyboard 2 Key Lockout" The IW Bits can be used to mask nibble A and nibble B
in applications requiring separate 4 bit display ports By
0 0 1 Decoded Scan Keyboard 2-Key Lockout setting the IW flag (IW= 1) for one of the ports, the port
0 1 0 Encoded Scan Keyboard - N-Key Rollov becomes marked so that entries to the Display RAM
0 1 1 Decoded Scan Keyboard - N-Key Rollou from the CPU do not affect that porl Thus, if each nibble
is input to a BCD decoder, Ihe CPU may write a digit to
1 0 0 Encoded Scan Sensor Matn>
the Display RAM without affecting the other digit being
1 0 1 Decoded Scan Sensor Matin displayed It is important to note thai bil B0 corresponds
to bit Dn on Ihe CPU bus. and that bit A3 corresponds to
1 1 0 Strobed Input. Encoded Display Scan
bit D7
1 1 1 Strobed Input. Decoded Display Scan
If Ihe user wishes to blank the display, the BL Hags are
Program Clock available for each nibble The last Clear command issued
determines the code to be used as a blank " This code
Code 001PPPPP
defaults fo all zeros after a reset Note that both BL
flags must be set to blank a display formatted with a
All timing and multiplexing signals lor the 8279 are single 8 bit poll
generated by an internal prescaler This prescaler
divides the external clock (pin 3) by a programmable Cleai
integer Bits PPPPP determine the value ol this integer
which ranges from 2 to 31 Choosing a divisor that yields
100 kHz will give the specified scan and debounce
times For instance, if Pin 3 of the 8279 is being clocked The CD bits are available in this command to clear all
by a 2 MHz signal, PPPPP should be set to 10100 to rows of Ihe Display RAM to a selectable blanking code
divide Ihe clock by 20 to yield the proper 100 kHz operat- as follows
ing frequency

Read FIFO/Sensor RAM


I X All Zeros IX - Don't Carel

Code 0 AB = Hex 20 10010 0000'


010AIX|AAA X = Don't Care
1 All Ones
The CPU sets up the 8279 for a read of the FIFO/Sensor
RAM by first writing this command In the Scan Key- - Enable clear display when = 1 (or by CA = 1)

board Mode,
the Auto-Increment flag (Al) and the RAM During the time the Display RAM is being cleared (~160 fS),
address bits (AAA) are irrelevant The 8279 will automati- it may not be written to. The most significant bit of the
cally drive
the data bus for each subsequent read (A0 = 0) FIFO status word is sel during this time When Ihe Dis-
in the same sequence in which the data first entered the play RAM
becomes available again, it automatically
FIFO All subsequent reads will be from the FIFO untrl resets
another command is issued
II the CF bit is asserted (CF=1), the FIFO status is
In the Sensor Matrix Mode, the RAM address bits AAA cleared and the interrupt output line is reset Also, the
select one of the 8 rows of the Sensor RAM If the Al flag Sensor RAM pointer is sel to row 0
is sel (Al = 1), each successive read will be from the sub-
sequent
ofrow
the sensor RAM CA, the Clear All bit. has the combined effect of CD and
CF, it uses the CD clearing code on the Display RAM and
Read Display RAM
also clears FIFO status Furthermore, it resynchromzes
the internal timing chain
Code 1 1 , Al A A A A
End Interrupt/Error Mode Set
The CPU sets up the 8279 for a read of the Display RAM
by first writing this command The address bits AAAA
1 1 1 I E IX X IX ,X
select one of the 16 rows of the Display RAM If the Al
flag is set (Al = 1), this row address will be incremented
after each following read or write to the Display RAM For the sensor matrix modes this command lowers the
Since the same counter is used for both reading and IRQ line and enables further writing into RAM The IRQ
writing, this command sets Ihe next read or write line would have been raised upon the detection of a
address and the sense of the Auto-Increment mode for change in a sensor value This would have also inhibited
both operations further writing into the RAM until reset1

%the N-key i llpvei %E hit , progran i :

further details see Interface Conside

I ICURE 9-29 8279 command word formats and bit descriptions. (Intel Corporation)

292 < HAPTER NINE


here we will use the 8279 on sheet 7 ol Figure 7 6 Fig pattern ol stepping lows, in encoded mode th<
urc 7-15b shows thai the system base address for this puis oui a binary count sequence on its SLO M I si in
device is FFE8H. ["he 8279 has only two interna] ad hues, .mil an external decodei such as the 7445 I
dresses which are selected by the logic level on Its AO to produce Hie stepping lows, II you only have 1 digits to
input, pin 21. If the AO input is low when the 8279 Is refresh, you can program tin- 8279 in decoded mode in
selected, then the 8279 is enabled for reading data from this mode the 8279 directly outputs stepping lows on
ii oi writing data to ii. AO being high selects the internal the lour scan lines The second choice you have lo make
control status registers. For the circuit on sheet 7 of Fig- lor this control word is whether you want two key /<» l>
ure1/
the6, \0 input is connected to system address line out, or N-key rollovei In the two-key mode, one key
\l rherefore, the data address lor this S27>> is FFE8H must he released before anothei keypress will he de
and the control status address is FFEA1 1 tected and proi essed. In the N-key rollovei mode, ii two
Alter you have figured out the addresses lor a device, keys an- piessed at nearly the same time, both key
the next step is lo look at the lonnat for the control presses will be detected and debouneed and their codes
WOrd(s) you have to send to the device to make it operate put in the FIFO in the order the keys were pressed.
in the mode you want. Figure 9 29 shows the formal lor In addition to being used lo scan a keyboard, the 8279
the 8279 control words as they appear in (he Intel data can also be used to scan a matrix of switch sensors such
book. After you use up your 5-minute "freak-out" lime as the metal strips and magnetic sensors you see on
we will help you decipher these store windows and doors. In sensor matrix mode the
A question that may occur to you when you see all of 8279 scans all of the sensors and stores the condition of
these control words is. "II the 8279 only has one control up to 64 switches in the FIFO RAM. If the condition ol
register address, how am I going to send it all of these any of the switches changes, an IRQ signal is sent out to
different control words?" The answer to this is that all of the processor. An interrupt service procedure can then
the control words are sent to the same control register sound an alarm and turn the dogs loose. The return
address. FFEAH for this example. The upper three bits lines of the 8279 can also function as a strobed input
of each control word tell the 8279 which control word is port in much the same way as the 8255A.
being sent. A pattern of 010 in the upper three bits of a The SDK-86 initializes the 8279 lor eight-character
control word, for example, identifies that control word display, left entry, encoded scan, two-key lockout. See if
as a "Read FIFO/Sensor RAM" control word. you can determine the mode-set control word for these
The first control word you send to initialize the 8279 conditions. You should get 00000000.
is the keyboard/display mode set word. Keep Figure The next control word vou have to send the 8279 is

9-29 handy as we discuss this and the other control


words. The bits labeled DD in the control word specify RAM
first of all whether you have 8 digits or 16 digits to re- LOCATION

fresh.
youIf have eight or fewer displays, make sure to DISPLAY POSITION
(R)
initialize for 8 digits so the 8279 doesn't spend half of its
<b> RhCd
time refreshing nonexistent displays. The DD bits in
this control word also specify the order in which the <D
characters in the internal 16-byte display RAM will be (d>
sent out to the digits. In the left entry mode, the seven- (P) REPRESENTS

segment code in the first address of the internal display 7 SEGMENT


CODE FOR A
RAM will be sent to the leftmost digit of the display. If
you want to display the letters AbCd on the 4 leftmost
digits of an 8-digit display, then you put the seven-
segment codes for these letters in the first four locations
of the display RAM as shown in Figure 9-30a. Codes put
in higher addresses in the display RAM will be displayed
on following digits to the right. In the right entry mode, RAM
LOCATION
the first code sent to the display RAM is put in the lowest
address. This character will be displayed on the right- <n> DISPLAY POSITION

most digit
of the display. If a second character is written n h c d
to the display RAM it will be put in the second location
in the RAM as shown in Figure 9-30b. On the display,
<d>
however, the new character will be displayed on the
rightmost digit, and the previous character will be (H) REPRESENTS
7 SEGMENT
shifted over to the second position from the right. This CODE FOR A
is the way that the displays of most calculators function
as you enter numbers.
Now let's look at the KKK bits of the mode-set control
word. The first choice you have to make here if you are
using the 8279 with a keyboard is whether you want
encoded scan or decoded scan. You know that for scan- FIGURE 9-30 8279 RAM and display location relationships.
ning
keyboard
a or turning on digit drivers, you need a (a) Left entry, (b) Right entry.

DIGITAL INTERFACING 293


the program-clock word. The 8279 requires an internal the FIFO, and how to read the status word. In order to
clock frequency of about 100 kHz. A programmable di- read a code from the FIFO you first have to send a read
vider
thein 8279 allows you to apply some available fre- FIFO/sensor RAM control word to the 8279 control ad-
quency as
suchthe 2.45-MHz PCLK signal to its clock dress. Figure
9-29 shows the format for this word. For a
input and divide this frequency down to the needed 100 read of the FIFO RAM. the lower 5 bits of the control
kHz. The lower 5 bits of the program clock control word word are don't cares, so you can just make them zeros.
simply represent the binary number you want to divide You send the resultant control word. 01000000, to the
the applied clock by. For example, if you want to divide control register address and then do a read from the
the input clock frequency by 24. you send a control word data address. The bottom section of Figure 9-31 shows
with 001 in the upper 3 bits and 1 1000 in the lower 5 this.
bits. Now, suppose that the processor receives an interrupt
The final control word needed for basic initialization signal from the 8279 indicating that one or more valid
is the clear word. You need to send this word to tell the keypresses have occurred. The question then comes up,
8279 what code to send to the segments to turn them off "How do I know how many codes I should read from the
while the 8279 is switching from one digit to the next. FIFO?'' The answer to this question is that you read the
(Refer to Figure 9-27 and its discussion.) In addition to status register from the control register address before
telling the 8279 what blanking character to use during you read the FIFO. Figure 9-32 shows the format for this
refresh, this control word can be used to clear the dis- status word. The lowest 3 bits of the status word indi-
play RAM
and/or the FIFO at any time. For now we are cate the
number of valid characters in the FIFO. You can
only concerned with the first function. The lower two load this number into memory location and count it
bits labeled CD in the control word in Figure 9-29 specify down as you read in characters. Incidentally, if more
the desired blanking code. The required code will de- than 8 characters have been entered in the FIFO, only
pend the
on hardware connections in a particular sys- the last 8 will be kept. The error-overrun bit. labeled O in
tem. For
the SDK-86 a high from the 8279 turns on a the status word, will be set to tell you characters have
segment, so the required blanking code is all O's. There- been lost.
fore you
can put O's in the two Cn bits. The resultant Characters can be read from the 8279 on a polled
control word is 1 1000000. basis as well as on an interrupt basis. To do this you
The three control words described so far take care of simply read and test the status word over and over again
the basic initialization. However, before you can send until bit 0 of the status word becomes a 1. The SDK-86
codes to the internal display RAM, you have to send the uses this method to tell when the FIFO holds a
8279 a write-display-RAM control word. This word tells keypressed code.
the 8279 that data later sent to the data address should
be put in the display RAM. and it tells the 8279 where in
SDK-86 DISPLAY DRIVER PROCEDURE
the display RAM to put the data byte sent in. Refer to
Figure 9-29 for the format of this word. The 8279 has an Figure 9-33 shows an 8086 assembly language proce-
internal 4-bit pointer to the display RAM. You use the dure display
to the contents of the CX register on
lower 4 bits of this control word to initialize the pointer SDK-86 LED displays. This procedure assumes the
to the location where you want to write a data byte in the 8279 has already been initialized by the SDK-86 moni-
RAM. If you want to write a data byte to the firstlocation tor program, or as shown in the first part of Figure 9-31.
in the display RAM. you put 0000 in these bits. If you If AL is zero when this procedure is called, the contents
put a 1 in the auto increment bit. labeled Al in the fig- of CX will be displayed on the data field LEDs. If AL is
ure, theinternal pointer will be automatically incre- not zero then the contents of CX will be displayed on the
mented
pointto to the next RAM location after each data address field LEDs. There are two main points for you to
byte is written. To start loading characters in the first see in this procedure. The first is the sending of the
location in the RAM and select auto increment, then, write-display-RAM control word to the 8279 so we can
the control word is 10010000. write to the desired locations in the display RAM. Note
Figure 9-31 shows the sequence of instructions to that, for the data field, we write a control word of 90H
send the control words we have developed here to the which tells the 8279 to put the next data word sent into
8279 on the SDK-86 board. Also shown are some in- the first location in the display RAM. Since the 8279 is
structions
send to a seven-segment code to the first lo- initialized for left entry, the first location should corre-
cation
thein display RAM. Note that the control words spond
theto leftmost display digit. However, if you look
are all sent to the control address. FFEAH. and the char- at sheet 8 of the SDK-86 schematics you will see that
acter goingto the display RAM is sent to the data ad- digit 1 (leftmost as far as the 8279 is concernedl is actu-
dress, FFE8H.Also note from sheet 7 of Figure 7-6 that ally the
rightmost on the board. This means that, for the
the DO bit of the byte sent to the display RAM corre- SDK-86, the position of a seven-segment code in the dis-
sponds
segment
to output BO, and D7 of the byte sent to play RAMcorresponds to its position in the display
the display corresponds to segment output A3. This is starting from the right! All you have to do is send the
important to know when you are making up a table of seven-segment code for a number you want to display in
seven-segment codes to send to the 8279. a particular digit position to the corresponding location
You now know how to initialize an 8279 and send in the display RAM.
characters to its display RAM. Two additional points we The next part of the display procedure to take a close
need to show you are how to read keypressed codes from look at is the instructions which convert the four hex

294 CHAPTER NINE


INITIALIZATION

MOV DX, OFFEAH Point at 8279 control address


MOV AL , OOOOOOOOB Mode set word for left entry,
encoded scan, 2-key lockout
OUT DX, AL Send to 8279
MOV AL , OOlllOOOB Clock word for divide by 2^
OUT DX, AL
MOV AL, llOOOOOOB ; Clear display char is all zeros
OUT DX, AL

SEND SEVEN SEGMENT CODE TO DISPLAY RAM

MOV AL, lOOlOOOOB Write display RAM, first location,


auto increment
MOV DX , OFFEAH Point at 8279 control address
OUT DX , AL Send control word
MOV DX , 0FFE8H Point at 8279 data address
MOV AL, 6FH Seven segment code for 9
OUT DX , AL Send to display RAM
MOV AL, 5BH Seven segment code for 2
OUT DX , AL Send to display RAM

READ KEYBOARD CODE FROM FIFO

MOV AL, OlOOOOOOB Control word for read FIFO RAM


MOV DX , OFFEAH Point at 8279 control address
OUT DX , AL Send control word
MOV DX , 0FFE8H Point at 8279 data address
IN AL, DX Read FIFO RAM

FIGURE 9-31 8086 instructions to initialize SDK-86 8279, write to display RAM,
and read FIFO RAM.

nibbles in the CX register to the corresponding seven- a high turns on a segment, bit DO of a display FtAM byte
segment codes for sending to the display HAM. To do represents the "a" segment, bit D6 represents the "g"
this we first shuffle and mask to get each nibble into a segment, and bit D7 represents the decimal point. Work
byte by itself. We then use a lookup table and the XLAT your way through this section as a review of using XLAT.
instruction to do the actual conversion. Note that when
making up seven-segment codes for the SDK-86 board. INTERFACING TO 18-SEGMENT AND
DOT-MATRIX LED DISPLAYS

In the preceding examples we used an 8279 to refresh


some seven-segment displays. The seven-segment codes
FIFO STATUS WORD for each digit were stored in successive locations in the
display FtAM. To display ASCII codes on 18-segment
S/E ') U F N N I
LED displays you can store the ASCII codes for each
digit in the display RAM. (Remember that the A lines are
L driven from the upper nibble of the display RAM and the
NUMBER OF CHARACTERS IN FIFO
B lines are driven by the lower nibble). An external ROM
FIFO FULL
ERROR-UNDERRUN
is used to convert the ASCII codes to the required 18-
ERROR-OVERRUN segment codes and send them to the segment drivers.
SENSOR CLOSURE/ERROR FLAG Strobes for each digit driver are produced just as they
FOR MULTIPLE CLOSURES
are for the seven-segment displays in Figure 7-6. The
DISPLAY UNAVAILABLE
refreshing of each digit then proceeds just as it does for
FIGURE 9-32 8279 status word format. the seven-segment displays.

DIGITAL INTERFACING 295


PAGE ,132
8086 PROCEDURE TO DISPLAYDATAON SDK-86 LEDs
ABSTRACT:This procedure will display a 't-digit hex or BCDnun
passed in the CX register on LEDs of the SDK-86
INPUTS: Data in CX, control in AL.
AL = 00H data displayed in data-field of LEDs
AL 0 00H, data displayed in address field of LEDs.
PORTS: Uses none
PROCEDURES:Usesnone
REGISTERS:saves all registers and flags
PUBLIC DISPLAY
DATA HERE SEGMENT WORD PUBLIC
SEVEN SEG LIB 3FH, 06H, 5BH, <tFH, 66H, 6DH, 7DH, 07H
0 1 2 3 4 S 6 7
DB 7FH, 6FH, 77H, 7CH, 39H, 5EH, 79H, 71H
8 9 A b C d E F
DATAHEREENDS
CODE.HERE SEGMENT WORD PUBLIC

ASSUME CS:CODE_HERE,
DS:DATA_HERE
DISPLAY PROC FAR
PUSHF ', save flags
PUSH DS ; save caller's DS
PUSH AX i save registers
PUSH BX
PUSH CX
PUSH DX
MOV BX, DATAHERE mit DS as needed for procedure
HOV DS, BX
MOV DX, OFFEAH point at 8279 control address
CHP AL, OOH see if data field required
JZ DATFLD yes, load control word for data field
MOV AL, 94H no, load address-field control word
JHP SEND go send control word
DATFLD: HOV AL, 90H load control word for data field
SEND: OUT DX, AL send control word to 8279
MOV BX, OFFSET SEVENSE6 pointer to seven-segtent codes
MOV DX. 0FFE8H point at 8279 display RAM
MOV AL, CL get low byte to be displayed
AND AL, OFH % ask upper nibble
XLATB translate lower nibble to 7-seg code
GUI DX, AL send to 8279 display RAM
HOV AL, CL get low byte again
MOV CL, 0<t load rotate count
PGL AL, CL Move upper nibble into low position
AND AL, OFH Mask upper nibble
XLATB translate 2nd nibble to 7-seg code
OUT DX, AL send to 8279 display RAM
MOV AL. CH Get high byte to translate
AND AL, OFH Mask upper nibble
XLATB Translate to 7-seg code
OUT DX, AL send to 8279 display RAM
MOV AL, CH get high byte to fix upper nibble
ROL AL, CL •ove upper nibble into low position
AND AL, OFH •ask upper nibble

FIGURE 9-33 Procedure to display contents of CX register on SDK-86 LED


displays.

296 ( HAPTER NINE


XLATB ; translate to 7-seg code
OUT DX, AL ; 7-seq code to 8279 display RAH
POP DX ; restore all registers and flags
POP CX
POP BX
POP AX
POP DS
POPF
RET
DISPLAY ENDP
CODE.HERE
ENDS
END
FIGURI 9 13 [continued)

Refreshing 5 by 7 dot-matrix LED displays is a little transmission ol light through the region under the seo
more complex, because instead oi lighting an entire ment film.
digit, you have to refresh one row or one column at a There are two commonly available types of LCI): dy-
time in each digit. Think of how you might do this for namic scattering, and Jk-ld effect. The dynamic s< attei
one 5 by 7 matrix which has its row drivers connected to ing type scrambles the molecules where the field is pres-
one port and its column drivers connected to another ent. Thisproduces an etched-glass-looking light
port. To display a letter on this matrix you send out the character on a dark background. Field effect types use
code for the first column to the row drivers and send a polarization to absorb light where the electric field is
code to the column drivers to turn on that column. After present. This produces dark characters on a silvei graj
a millisecond or so you turn off the first column, send background.
out the code for the second column, and light the second Most LCDs require a voltage of 2 or 3 V between the
column. You repeat the process until all of the columns backplane and a segment to turn on the segment. You
have been refreshed and then cycle back to column 1 can't, however, just connect the backplane to ground
again. You could use additional ports to drive additional and drive the segments with the outputs of a TTL de-
digits, but the number of ports required soon gets too coderweas did the static LED display in Figure 9-25!
large. To reduce the number of ports required, inexpen- The reason for this is that LCDs rapidly and irreversibly
sive external latches can be used to hold the row codes deteriorate if a steady dc voltage of more than about 50
for each digit. You then write the row codes for the first mV is applied between a segment and the backplane. To
columns of all the digits to these latches. The columns of prevent a dc buildup on the segments, the segment-
all the digits are connected in parallel, so when you out- drive signals for LCDs must be square waves with a fre-
putcode
a to turn on the first column, the first column quency30-150of Hz. Even if you pulse the TTL de-
of each digit will be lit with the code stored in its row coder,
still it will not work because the output low volt-
latch. The process is repeated for each column until all ageTTL
of devices is greater than 50 mV. CMOS gates
columns are refreshed, and then started over again. are often used to drive LCDs.
To further simplify interfacing multidigit dot-matrix Figure 9-34a shows how two CMOS gate outputs can
LED displays to a microcomputer. Beckman Instru- be connected to drive an LCD segment and backplane.
ments. Hewlett-Packard,and several other companies Figure 9-34b shows typical drive waveforms for the
make large integrated display/driver devices which re- backplane and for the on and the off segments. The off
quire you
to send only a series of ASCII codes for the (in this case unused) segment receives the same drive
characters you want displayed and one or two strobe signal as the backplane. There is never any voltage be-
signals for each character sent. tween them, so no electric field is produced. The wave-
formthefor on segment is 180° out of phase with the
backplane signal, so the voltage between this segment
and the backplane will always be +V. The logic for this is
Liquid Crystal Display Operation and Interfacing quite simple, because you only have to produce two sig-
nals,
square
a wave and its complement. To the driving
LCD OPERATION
gates the segment-backplane sandwich appears as a
Liquid crystal displays are created by sandwiching a somewhat leaky capacitor. The CMOS gates can easily
thin (10- to 12-micron) layer of a liquid-crystal fluid be- supply the current required to charge and discharge
tweenglass
two plates. A transparent, electrically con- this small capacitance.
ductive
or film
backplane is put on the rear glass sheet. Older and/or inexpensive LCD displays turn on and off
Transparent sections of conductive film in the shape of too slowly to be multiplexed in the way we do with LED
the desired characters are coated on the front glass displays. At 0°C some LCDs may require as much as 0.5
plate. When a voltage is applied between a segment and seconds to turn on or off. To interface to these types we
the backplane, an electric field is created in the region use a nonmultiplexed driver device. Newer LCDs can
under the segment. This electric field changes the turn on and off faster. To reduce the number of connect-

DICITAL INTERFACING 297


UNUSED SEGMENT vdu LIQUID CRYSTAL input signal causes the seven-segment code to be
DIELECTRIC
latched in the output latches for the addressed digit.
An internal oscillator automatically generates the seg-

1 i-^p r^ t —i pL—i in 9-34b.


ment and
backplane drive waveforms shown in Figure

INTERFACING TO TRIPLEXED LCD DISPLAYS

For many microcomputer-based instruments we want


to display letters as well as numbers. To do this we usu-
ally use
18-segment digits such as the one shown in Fig-
ure 9-24a.For 18-segment LED digits we simply bus all
of the segment inputs and multiplex the displays as de-
ACTIVE SEGMENT scribed previously.
Current LCD digits, however, cannot
be multiplexed in the same way because of their slow
switching response time. To reduce the connections
required for a set of LCD digits, a compromise approach
called triplexing has been devised. For triplexing, each
OFF-SEGMENT
DRIVE ^^lJ digit is built as a matrix of six rows and three columns.
Each digit has a 6-bit latch to hold the 6-bit row code for
the segments in a column. The row codes are sent to all
BACKPLANE of the latches and the columns of each digit turned on.
DRIVE
After a period of time the row codes for the second col-
umn aresent out to the latches. The first column is
ON-SEGMENT turned off and the second column turned on. After a
DRIVE
period of time the row codes for the third columns are
sent out to digits and the third columns turned on. At
any given time one of the three columns in each display
FIGURE 9-34 LCD drive circuit and drive waveforms. is activated, which is where the term triplexing comes
la) CMOS drive circuits, lb) Segment and backplane from. Since only three columns ever need to be re-
drive waveforms. freshed,
matter
no how many digits are connected, the
switching rates are much lower than they are for the
LED multiplexing method. The Intersil ICM7233 is an
ing wires when interfacing to these, we use a triplex example of a device which contains all of the circuitry
technique. The following sections show you brief exam- needed to drive four triplexed, 18-segment LCD digits. It
pleseach
of of these. can be connected directly to a microcomputer bus as we
showed for the ICM721 1M in Figure 9-35. To display a
INTERFACING A MICROCOMPUTER TO series of characters all you have to do is output a 6-bit
NONMULTIPLEXED LCD DISPLAYS ASCII code for each character to the appropriate digit
address in the device. A demonstration kit containing
Figure 9-35 shows how an Intersil ICM7211M can be
two 7233s. eight 18-segment LCD displays and a PC
connected to drive a 4-digit. nonmultiplexed. seven- board is available from Intersil, if you want to add this
segment LCD display such as you might buy from your
type of display to something you are building.
local electronics surplus store. The 721 1M inputs can be
connected to port pins or directly to microcomputer
buses as shown. For our example here we have con-
nectedCSthe inputs to the Y2 output of the 74LS138 INTERFACING MICROCOMPUTER PORTS
port decoder that we showed you how to add to an TO HIGH-POWER DEVICES
SDK-86 board in Figure 8-14. According to the truth
As shown for the 8255A in Figure 9-36. the output pins
table in Figure 8-15. the device will then be addressable
on programmable port devices can typically source only
as ports with a base address of FF10H. SDK-86 system
a few tenths of a milliampere from the +5-V supply and
address line A2 is connected to the digit-select input
(DS2) and system address line A1 is connected to the DS I
sink only 1 or 2 mA to ground. If you want to control
some high-power devices such as lights, heaters, sole-
input. This gives digit 4 a system address of FF10H.
Digit 3 will be addressed at FF12H. digit 2 at FF14H.
noids,motors
and with your microcomputer, you need
to use interface devices between the port pins and the
and digit 1 at FF16H. The data inputs are connected to
high-power device. This section shows you a few of the
the lower four lines of the SDK-86 data bus. The oscilla-
commonly used devices and techniques.
tor input is left open.
To display a character on one of the digits, you simply
INTEGRATED CIRCUIT BUFFERS
put the 4-bit hex code for that digit in the lower 4 bits of
the AL register, and output it to the address of that One approach to buffering the outputs of port devices is
digit. The ICM 72 1 1M converts the 4-bit hex code to the with TTL buffers such as the 7406 hex inverting and
required seven segment code. The rising edge of the CS 7407 hex noninverting. In Figure 9-14 for example, we

298 I I I \ I'll K NINI


SEGMENT OUTPUTS i OUTPUTS II OUTPUTS

7 WIDE DRIVER / WIDI DRIVER ; wiDr

7 WIDE LATCH EN % 7 WIDE LATCH ENh 7 WIDE LATCH ENf

PROGRAMMABLE PROGRAMMABLE PROGRAMMABLE PRi IGRA


4 rO 7 DEC! IDER 4 TO 1 DECODER 1 In/1 1 r0 7 DECODER

Aim
4 BIT
AD1
LATCH
AIV
AD3

2 BIT
2 TO 4
LATCH
DECODER

CSJ___^ I ISl II LATOR BACK


ONE
16 KHZ PLANE
SHOT BACKPLANE
_TL FREE DRIVER
OUTPUT
RUNNING

OSC ENABLE

ENABLE DETECTOR

FIGURE 9-35 Circuit for interfacing four LCD digits to an SDK-86 bus using
Intersil ICM7211M.

show 74LS07 buffers on the lines from ports to a ground. You could then drive an LED with each output
printer. In an actual circuit the 8255A outputs to the by simply connecting the LED and a current-limiting
computer-controlled lathe in Figure 9-6 should also resistor in series between the buffer output and +5 V.
have buffers of this type. The 74LS06 and 74LS07 have Buffers of this type have the advantage that they come
open collector outputs, so you have to connect a pull-up six to a package, and they are easy to apply. For cases
resistor from each OLitput to +5 V. Each of the buffers in where you only need a buffer on one or two port pins,
a 74LS06 or 74LS07 can sink as much as 40 mA to you may use discrete transistors.

D C CHARACTERISTICS
T„ - 0 C to 70" C, V,%, t 5 V | 5%; GND - 0V

SYMBOL PARAMETER MIN MAX UNIT TEST CONDITIONS

VIL INPUT LOW VOLTAGE -0.5 08 V

V,H INPUT HIGH VOLTAGE 2.0 Vcc V

VUL(DB) OUTPUT LOW VOLTAGE (DATA BUS) 045 V lOL - 2.5 mA

VOL(PER) OUTPUT LOW VOLTAGE (PERIPHERAL PORT) 0 45 V l01 1 7 mA


VOH(DBI OUTPUT HIGH VOLTAGE (DATA BUS) 24 V l0H - 400 >jA

V0H(PER) OUTPUT HIGH VOLTAGE (PERIPHERAL PORT) 2 4 V lOH - - 200 pA

w DARLINGTON DRIVE CURRENT -1 0 -4.0 mA R, . , 750 SI, V,.., - 1.5 V

I, , POWER SUPPLY CURRENT 120 mA

l„ INPUT LOAD CURRENT * 10 ^A VIM V, , TO 0V

'OFL OUTPUT FLOAT LEAKAGE • 10 MA V0UT = Vcc TO0V


NOTE 1 AVAILABLE ON ANY 8 PINS FROM PORT B AND C

FIGURE 9-36 8255A dc operating characteristics.

DIGITAL INTERFACING 299


can only source 200 /LtA (0.2 mA) of current and still
maintain a legal TTL-compatible output voltage of 2.4 V!
When you see this specification, you may at first think
the port output will not be able to drive the transistor.
However, the fact is that the outputs can source more
than 0.2 mA. but if they source more than 0.2 mA, the
FROM OUTPUT output high voltage will drop below 2.4 V. You don't care
PORT PIN about the output high voltage dropping below 2.4 V ex-
ceptthe
in unlikely case that you are trying to drive a
logic gate input off the same port pin as the transistor.
The IDar specification in Figure 9-36 indicates that port
B and port C pins can source at least 1.0 mA, but when
doing so the output voltage may be as low as 1.5 V. Let's
assume an output voltage of 2.0 V for calculating the
value of our current-limiting resistor, Rb. The value of
FROM OUTPUT
PORT PIN
this resistor is not very critical as long as it lets through
8.2 K enough base current to drive the transistor. The base of
OR
io ^ the NPN transistor will be at about 0.7 V when the tran-
4 sistor
conducting,
is and the output port pin will be at
least 2.0 V. Dividing the 1.3 V across Rh by the desired
current of 0.4 mA gives an Rb value of 3.25 kft. A 2.7-kSl
or 3.3-kf2 resistor will work fine here.
For the PNP circuit in Figure 9-37b the output port
pin can easily supply the needed drive current. The
FIGURE 9-37 Transistor buffer circuits for driving LED VOI(PER) specification in Figure 9-36 shows that an
from 8255A port pin. (a) NPN. (b) PNP. output pin can sink at least 1.7 mA and still have an
output low voltage no greater than 0.45 V. Rb in Figure
9-37b has about 4 V across it. Dividing this voltage by
the required 0.4 mA gives an Rh value of 10 kft.
TRANSISTOR BUFFERS
When you need to switch currents larger than about
Figure 9-37 shows some transistor circuits you can con- 50 mA on and off with an output port line, a single tran-
nectmicroprocessor
to port lines to drive LEDs or small sistor does
not have enough current gain to do this de-
dc lamps. We will show you how to quickly determine the pendably.
solution
One to this problem is to connect two
parts values to put in these circuits for your particular transistors in a Darlington configuration. Figure 9-38
application. First determine how much current you shows how we might do this to drive a small solenoid-
need to flow through the LED. lamp, or other device. For controlled valve which controls the flow a chemical into
our example here, suppose that we want 20 mA to flow our printed-circuit-board-making machine, or a small
through an LED. Next determine whether you want a solenoid in the print heads of a dot-matrix printer. For
logic high on the output port pin to turn on the device or the case of the printer solenoid, when a current is
whether you want a logic low to turn on the device. If you passed through the coil of the solenoid, a print wire is
want a logic high to turn on the LED, then use the NPN
circuit. Now look through your transistor collection to
find an NPN transistor which can carry the required
current, has a collector-to-emitter breakdown voltage
(V'|,( i <>) greater than the applied supply voltage, and can
dissipate the power generated by the current flowing
through it. We usually keep some inexpensive 2N3904 1N4002
Ai
&f
3> OR
RELAY COIL
SOLENOID
NPNs and some 2N3906 PNPs on hand for low-current
switch applications such as this. Some alternatives are
the 2N2222 NPN and the 2N2907 PNP. When you decide
what transistor you are going to use. look up its current
gain, hFE. on a data sheet. If you don't have a data sheet, I- HUM B^bbA v
assume a value of 50 for the current gain of small-signal OUTPUT PIN /
transistors such is these. Remember, current gain, or
beta as it is commonly called, is the ratio of collector
current to the base current needed to produce that cur-
rent.produce
To a collector current of 20 mA in a tran-
^isim with a beta of 50 then requires a base current of
20 mA/50 or 0.4 mA. To drive this buffer transistor,
then, the output port pin only has to supply the 0.4 mA.
A look at the V()H(PER) specification of the 8255A in FIGURE 9-38 Darlington transistor used to drive relay coil
Figure 9-36 shows that an 8255A peripheral port pin or solenoid.

300 CHAPTER NINE


forced out. I'lic print wire hits the ribbon against the
paper and produces .1 dol on the papei
The dotted hues around the two transistors in Figure
WINDING
9-38 indicate that both devices arc contained in the OR SOI I
same package. Here's how ilns configuration works
The output port pin supplies base current to transistoi
Ql . This base current produces a collector current beta
times as large In Ql. ["he collector current ol Ql be-
comesbasethe current ol Q2 and is amplified by the
I- ROM \
current gain ol 1)2. The result ol all tins is that the de- Oil IIMIt /
vice acts like a single transistor with a current gain ol
(beta Ql - beta Q2) and a base emitter voltage ol about
1.4 V. I'lic internal resistors help turn oil the transis- ///
tors. I'bf
TIP] lo device we show here has a minimum
beta ot nit it) at l A. II we assume that we need 400 mA to FICURI 9-39 Power MOSFE1 circuil for driving solenoid
drive the solenoid, then the worst-case current that 01 motor winding.
must be supplied by the output port pin is about 400
mA 1000 or 0.4 mA. which it can easily do. If the drive
current required for the Darlington is too high for the path lor the induced current. The voltage across the
port output, you can add a resistor from the transistor inductor is clamped at 0.7 V. which saves the transistor.
base to +5 V to supply the added current. The output Figure 9-39 shows how a power MOSFET transistor
can easily sink the added current when the output is in can be used to drive a solenoid, relay, or motor winding.
the low state. Also another transistor could be added as Power MOSFETS are several times more expensive than
a buffer between the output pin and the Darlington bipolar Darlingtons, but they have the advantage that
input. Note that since the VBE of the Darlington is about they only require a voltage to drive them. The Motorola
2 Y. no Rb is needed here. Now let's check out the power IRF130 shown here, for example, only requires a maxi-
dissipation. mum gate
voltage of 4 V for a drain current of 8 A. Note
According to the data sheet for the TIP1 10. it comes in that a diode is required across the coil here also.
a TO-220 package which can dissipate up to 2 W at an
INTERFACING TO AC POWER DEVICES
ambient temperature of 25°C with no heat sink. With
400 mA (lowing through the device it will have a collec- To turn 110-V. 220-V, or 440-V ac devices on and off
tor-emitter saturation
voltage of about 2 V. Multiplying under microprocessor control we usually use mechani-
the current of 400 mA times the voltage drop of 2 V gives cal or
solid-state relays. The control circuitry for both
us a power dissipation of 0.8 W for our circuit here. This of these types of relay is electrically isolated from the
is well within the limits for the device. A rule of thumb actual switch. This is very important because if the
that we like to follow is. if the calculated power dissipa- 1 10 V ac line gets shorted to the I',, line of a micro-
tion for
a device such as this is more than half of its computer,
usually it bakes most of the microcomputer's
25°C no-heat-sink rating, mount the device on the chas- ICs. Figure 9-40a shows a picture of a mechanical relay.
sis ora heat sink to make sure it will work on a hot day. This relay has both normally open and normally closed
If mounted on the appropriate heat sink the device will contacts. When a current is passed through the coil of
dissipate 50 W at 25°C. the relay, the switch arm is pulled down, opening the
One more important point to mention about the cir- top contacts and closing the bottom set of contacts. The
cuitFigure
in 9-38 is the reverse-biased diode connected contacts are rated for a maximum current of 25 A. so
across the solenoid coil. You must remember to put in this relay could be used to turn on a 1 or 2-horsepower
this diode whenever you drive an inductive load such as motor or a large electric heater in one of the machines in
a solenoid, relay, or motor. Here's why. The basic princi- our electronics factory. When driven from a 12-V supply,
ple an
of inductor is that it fights against a change in the coil requires a current of about 170 mA. The circuit
the current through it. When you apply a voltage to the shown in Figure 9-38 could easily drive this relav cull
coil by turning on the transistor, it takes a while for the from a microcomputer port line.
current to start (lowing. This does not cause any major Mechanical relays, sometimes called contactors, are
problems. However, when you turn off the transistor, available to switch currents from milliamps up to sev-
the collapsing magnetic field in the inductor keeps the eral thousand amps. Mechanical relays, however, have
current flowing for a while. This current cannot flow several serious problems. When the contacts are opened
through the transistor because it is off. Instead this cur- and closed, arcing takes place between the contacts.
rent developsa voltage across the inductor with the po- This causes the contacts to oxidize and pit just as the
larity shownby the + and - signs on the coil in Figure ignition points in your car do with age. As the contacts
9-38. This induced voltage, sometimes called inductive become oxidized they make a higher-resistance contact
"kick.'' will usually be large enough to break down the and may get hot enough to melt. Another disadvantage
transistor if you forget to put in the diode. When the coil of mechanical relays is that they can switch on or off at
is conducting, the diode is reverse-biased so it doesn't any point in the ac cycle. Switching on or off at a high
conduct. However, as soon as the induced voltage voltage point in the ac cycle can cause a large amount of
reaches 0.7 V this diode turns on and supplies a return electrical noise called electromagnetic interference

DICITAt INTERFACING 301


focused on a phototransistor connected to the actual
output-control circuitry. Since the only connection be-
tweeninput
the and the output is a beam of light, there
is several thousand volts of isolation between the input
circuitry and the output circuitry.
The actual switch in a solid-state relay is a triae which
conducts in either direction when triggered. The zero-
voltage detector makes sure that the triac is only trig-
gered when
the ac line voltage is very close to one of its
zero voltage crossing points. If you output a signal to
turn on the relay, the relay will not actually turn on until
the next time the ac line voltage crosses zero. Triacs au-
tomatically
off turn
when the current through them
drops below a small value called the holding current. If
the control signal is on. the trigger circuitry will auto-
matically retrigger
the triac for each half cycle. If you
send a signal to turn off the relay, it will actually turn off
the next time the ac current drops to zero. Zero-point
switching eliminates most of the EMI that would be
caused by switching the triae on at high-voltage points
in the ac cycle.
Solid-state relays then have the advantages that they
produce less EMI. they have no mechanical contacts to
arc, and they are easily driven from microcomputer
ports. Their disadvantages are that they are more ex-
pensiveanthanequivalent mechanical relay and there
is a voltage drop of a couple of volts across the triae
when it is on. Another potential problem with solid-
state relays occurs when driving a large inductive load
such as a motor. Remember from basic ac theory that
the voltage waveform leads the current waveform in an
ac circuit with inductance. A triac turns off when the
current through it drops to near zero. In an inductive
circuit the voltage waveform may be at several tens of
volts when the current is at zero. When the triac is con-
ducting
has itperhaps 2 V across it. When the triac
turns off, the voltage across the triac will quickly jump
to several tens of volts. This large dV/dT may possibly
turn on the triac at a point you don't want it turned on.
To keep the voltage across the triac from changing too
rapidly, an RC snubber circuit is connected across the
A = PHOTOTRANSISTOR
B = ZERO CROSSING DETECTOR triac as shown in Figure 9-40c. A system in the next
C = TRIGGER CKT chapter uses a solid-state relay to control an electrical
D = SNUBBER CKT
heater.
(i )

INTERFACING A MICROCOMPUTER TO A
FIGURE 9-40 Relays for switching large currents, (a)
STEPPER MOTOR
Mechanical, lb) Solid-state. (Potter and Brumfield).
(c) Internal circuitry tor solid-state relay. A unique type of motor useful for moving things in small
increments is the stepper motor. If you have a dot-
matrix printer such as the Epson FX-80. look inside and
(EMI). The solid-state relays discussed next avoid these you will probably see one small stepper motor which is
problems to a large extent. used to advance the paper to the next line position, and
Figure 9-40b shows a picture of a solid-state relay another small stepper motor which is used to move the
which is rated for 25 A at 25C if mounted on a suitable print head to the next character position. While you are
heat sink. Figure 9-40c shows a block diagram of the in there, you might look for a small device containing an
circuitry in the device and its connection from an out- LED and a phototransistor which detects when the
put portto an ac load. print head is in the "home" position. Stepper motors are
The input circuit is essentially an LED and a current- also used to position the read/write head over the de-
limiting resistor. To turn the device on you simply turn sired track
of a hard or floppy disk, and to position the
on the buffer transistor which pulls the required 1 1 mA pen on X-Y plotters.
through the internal LED. The light from the LED is Instead of rotating smoothly around and around as

302 CHAPTER NINE


most motors do, stepper motors rotate 01 "step" from clockwise. Changing to SW4 and SW3 on will cause the
out' fixed position to the next. Common step sizes range motoi in rotate another 1.8 clockwise. Changing to
from i) 9 i" 30 A stepper motoi is stepped from one SV\ I and SW2 on will ca hei step After that.
posit to the next l>\ changing the currents through i 11.1in; in- to SW2 and s\\ i on .main will cause anothei
the fields in the motor. The two common field conni step clockwise. You can repeat the sequence until the
lions are referred to .is two phase and four phase. We motor has rot. lied .is many steps clockwise as you want
will discuss fow phase steppers here because theii In step the motor counterclockwise, you simply work
drive circuitry is much simpler. through the switch sequence in the reverse direction. In
Figure 9 -11 shows a circuit you can use to interface a either case the motor will be held in its lasl position by
small four-phase stepper such as the Superioi Electric the current through the coils Figure 9-41c shows the
MO61-FD302. IMC Magnetics Corp. Tormax 200, or a switch sequence thai can be used to rotate the motor
similar, nominal 5-V unit to lour microcomputer port half-steps "I 0.9 clockwise or counterclockwise
lines. If you build up this circuit, bolt some small heat A (lose look at the switch sequence in Figure 9 Ufa
sinks on the MJE2955 transistors and mount the 10-W shows an interesting pattern. To take the first step
resistors where you aren't likely to touch them. clockwise from SW2 and SW I being on, the pattern ol Is
Since the 7406 buffers are inverting, a high on an and 0's is simply rotated one bit position around to the
output-port pin turns on current to a winding. Figure right. The 1 Irom SWI is rotated around into bit 4. To
9-4 lb shows the switching sequence to step a motor take the next step the switch pattern is rotated one more
such as this clockwise, as you face the motor shaft, or bit position. To step counterclockwise the switch pat-
counterclockwise. Here's how this works. Suppose that ternrotated
is left one bit position for each step desired.
SW1 and SVV2 are turned on. Turning off SW2 and turn- Suppose that you initially load 00110011 into AL and
ing on
SW4 will cause the motor to rotate one step of 1 .8° output this to the switches. Duplicating the switch pal-

OPTIONAL LOW POWER


HOLD CIRCUIT.
CONNECT POINT A TO
+ 12 V IF SWITCH NOT USED

SWITCH
PORT BIT
OF SW4 SW3 SW2 SWI
MICROCOMPUTER
1 0 0 1 1

2 1 0 0
3 1 1 0 0
4 0 1 1 0
DO »
1 0 0 1 1

1 - SWITCH ON

D1 »

EIGHT-STEP INPUT SEQUENCE


(HALF-STEP MODE)

D2 » STEP SW4 SW3 SW2 SWI

1 OFF OFF ON ON

2 OFF OFF OFF ON

3 ON OFF OFF ON

D3-^> 1 ON OFF OFF 01 i

5 ON ON OFF OFF

6 OFF ON OFF OFF

7 OFF ON ON OFF

8 OFF OFF ON OFF

1 OFF OFF ON ON
D4^>>

FIGURE 9-41 Four-phase stepper motor interface circuit and stepping


waveforms, la) Circuit, (b) Full-step drive signal order. <c) Half-step drive
signal order.

DIGITAL INTERFACING 303


tern in the upper half of AL will make stepping easy. To rectly,
simple
a one-chip microcomputer or a device
step the motor clockwise, you just rotate this pattern such as the Cybernetic Microsystems CY525 stepper
right one bit position and output it to the switches. To controller is used.
step counterclockwise, you rotate the switch pattern left
one bit position and output it. After you output one step
code you must wait a few milliseconds before you output OPTICAL MOTOR SHAFT ENCODERS
another step command, because the motor can only step
so fast. Maximum stepping rates for different types of In order to control the machines in our electronics fac-
steppers vary from a few hundred steps per second to tory, the
microcomputers in these machines often need
several thousand steps per second. To achieve high information about the position, direction of rotation,
stepping rates the stepping rate is slowly increased to and speed of rotation of various motor shafts. The mi-
the maximum, then it is decreased as the desired num- crocomputer,
course, of needs this information in digi-
ber steps
of is approached. tal form. The circuitry which produces this digital infor-
As a stepper motor steps to a new position it tends to mation from
each motor for the microcomputer is called
oscillate around the new position before settling down. a shaft encoder. There are two basic types of shaft en-
A common software technique to damp out this oscilla- coder, absolute and incremental. Here's how these two
tiontois first send the pattern to step the motor toward types work.
the new position. When the motor has rotated part of
the way to the new position, a word to step the motor
backward is output for a short time. This is like putting Absolute Encoders
the brakes on. The step forward word is then sent again Absolute encoders attach a binary-coded disk such as
to complete the step to the next position. The timing for the one shown in Figure 9-42 on the rotating shaft.
the damping command must be determined experimen- Light sections of the disk are transparent, and dark sec-
tally each
for motor and load. tions are
opaque. An LED is mounted on one side of
Before we go on, here are a couple of additional points each track and a phototransistor is mounted on the
about the circuit in Figure 9-4 la, in case you want to other side, opposite the LED. Outputs from the four
add a stepper to your robot or some other project. First phototransistors will produce one of the binary codes
of all. don't forget the clamp diodes across each winding shown in Figure 9-42. The phototransistor outputs can
to save the transistors from inductive kick. Second, we be conditioned with Schmitt-trigger buffers and con-
need to explain the function of the current-limiting re- nected
a microcomputer
to port. Each code represents
sistors,
1 andR R2. The motor we used here has a nomi- an absolute angular position of the shaft in its rotation.
nal voltagerating of 5.5 V. This means that we could With a 4-bit disk. 360° is divided up into 16 parts, so the
have designed the circuit to operate with a voltage of position of the shaft can be determined to the nearest
about 6.5 V on the emitters of the driver transistors 22.5°. With an 8-bit disk the position of the disk can be
(5.5 V for the motor plus 1 V for the drop across the determined to the nearest 3607256, or 1.4°.
transistor). For low stepping rates, this would work fine. Observe that the codes in Figure 9-42 do not follow a
However, for higher stepping rates and more torque normal binary count sequence. The codes here follow a
while stepping, we use a higher supply voltage and cur- sequence called Gray code. Using Gray code reduces the
rent-limiting resistors
as shown. The point of this is size of the largest possible error in reading the shaft
that by adding series resistance, we decrease the LIR
time constant. This allows the current to change more
rapidly in the windings. For the motor we used, the cur-
rent per
winding is 0.88 A. Since only one winding on
each resistor is ever on at a time. 6.5 V/0.88 A gives a
resistor value of 6.25 fl. To be conservative we used 8-0,
10-W resistors. The optional transistor switch and diode
connection to the +5-V supply are used as follows. When
not stepping, the switch to + 12 V is off so the motor is
held in position by the current from the +5 V supply.
Before you send a step command, you turn on the tran-
sistor
+ to
12 V to give the motor more current for step-
ping. When stepping is done you turn off the switch to
+ 12 V. and drop back to the +5 V supply. This cuts the
power dissipation.
In small printers such as the IBM PC parallel printer, a
dedicated microprocessor is used to control the various
operations in the printer. In this case the microproces-
sor hasplenty of time to control the print-head and
line-feed stepper motors in software as we described
above. For applications where the main microcomputer FIGURE 9-42 Gray code optical-encoder disk used to
is too busy to be bothered with controlling a stepper di- determine angular position of a rotating shaft.

304 < MAI'HK NINH


position to tin value "i the leasl significanl bit. ll the
disk used straight binary code, the largest possible erroi
would be the value ol the most significant bit. Look .u
ihr parallel listings ol binary and Gray codes in fable
1-1 to help von sec why this is the case.
To start, assume we did have .1 binary disk and the
disk was rotating from position oil I (7) to position
1000 (8). Now suppose that the detectors pick up the
change to 000 on the least significant 3 bits, but don*t
pick up the change to l on the most-significant bit. l lie
output code would then be 000(1 instead ol the desired
1000. This is an erroi equal to the value of the MSB.
Now. while this is fresh in your mind, look across the
table at the same position change lor the dray code en-
coder. The Gray code lot position 7 is OHIO and the Gray
code lor position 8 is 1 100. Note that only one bit
changes lor this transition. If you look ai the Gray code FIGURE 9-4< Rhino XR robotics svsicm. (Rhino Robots
table closely, you will see that this is the case for all of ln< orporated)
the transitions. What this means is that if a detector
fails to pick up the new bit value during .1 transition, the
resulting code will always be the code for the preceding
position. This represents an error equal to the value of in the other direction will shift the phase of the wave
the LSB. forms 180° so that the B waveform leads the A waveform
If you need to construct a Gray code table for more by 90° instead of lagging it by 90:. Now the question is.
than 4 bits, a handy method is to observe the pattern of "How do you get position, speed, and direction informa-
Is and O's in Table 1-1. and just extend it. The least- tion from
these waveforms?"
significant-bit column starts with a 0. and then has al- You can determine the speed of rotation by simply
ternating groups
of two Is and two O's. The second- counting the number of pulses in the time between two
most-signilieant column starts with two O's and then interrupts as we described in Chapter 8. Each track has
has alternating groups of lour 1 s and four O's. The third six holes so six pulses will be produced for each revolu-
column starts with four O's and has alternating groups tion. Some
simple arithmetic will give you the speed in
of eight l's and eight O's. By now you should see the revolutions per minute (rpm).
pattern. Try to figure out the Gray code for the decimal You can determine the direction of rotation with hard-
number 16. You should get 11000. warewith
or software. For the hardware approach con-
Absolute encoding using a Gray code disk has the ad- nect the
A signal to the D input of a D flip-flop, and the B
vantage
each
that position is represented by a specific signal to the clock input of the flip-flop. The rising edge
code which can be directly read in by the microcom- of the B signal will clock the level of the A signal at that
puter. Disadvantagesare the multiple detectors needed,
the multiple lines required, and the difficulty keeping
track of position during multiple rotations.

Y i tr WINDOWS
j
1— '
P °U.TEF
r~ (A)
Incremental Encoders
An incremental encoder produces a pulse for each incre- LXJ t
t
INNER
(B)
mentshaft
of rotation. Figure 9-43 shows the Rhino
XR-2 robot arm. which uses incremental encoders to
determine the position and direction of rotation for each
of its motors. For this encoder, a metal disk with two
tracks of slotted holes is mounted on each motor shaft.
An LED is mounted on one side of each track of holes
and a phototransistor is mounted opposite the LED on
the other side of the disk. Each phototransistor pro-
duces
traina of pulses as the disk is rotated. The pulses 1 I ! I 1
are passed through Schmitt trigger buffers to sharpen 0 90' 1 270° 360 90 270 360J
I I
their edges. 01 I 00 i 10 I 11 I 01 I 00 I 10
00 I 10 I 11
The two tracks of slotted holes are 90° out of phase
with each other as shown at the top of Figure 9-44. 0.004 SEC.
"ONE CYCLE"
Therefore, as the disk is rotated, the waveforms shown
at the bottom of Figure 9-44 will be produced by the FIGURE 9-44 Optical-encoder disk slot pattern and
phototransistors for rotation in one direction. Rotation output waveforms.

DIGITAL INTERFACING 305


point through the flip-flop to its Q output. If you look at IMPORTANT TERMS AND CONCEPTS
the waveforms in Figure 9-44 you should see that the Q FROM THIS CHAPTER
output will he high for rotation in the direction shown.
You can convince yourself that the Q output will be low If you do not remember any of the terms in the following
for rotation in the other direction. To determine the di- list, use the index to help you find them in the chapter
rection
rotation
of more directly, you can detect the ris- for review.
ing edge
of the B signal on a polled or an interrupt basis,
and then read the A signal. As shown in the waveforms, Simple input and output
the A signal being high represents rotation in one direc-
tion, and
the A signal being low represents rotation in Simple strobe I/O
the opposite direction.
To determine the position of the motor shaft you sim- Single handshake I/O
ply keeptrack of how many holes the motor has moved
Double handshake data transfer
from some "home" position. On the Rhino robot arm a
small mechanical switch on each axis is activated when
8255A initialization of ports A. B. and C
the arm is in its starting or "home" position. When you
MODE 0. MODE 1. MODE 2
turn on the power, the motor controller/driver box auto-
Mode definition control word
matically moves
the arm to this home position. To move
Set/reset control word
the arm to some new position you calculate the number
of holes each motor must rotate to get the arm to that
Computer numerical control (CNC) machines
position. For each motor you then send the controller a
command which tells it which direction to rotate that
VOTRAX SC-01A speech synthesizer
motor and how many holes to rotate it. The controller
Phoneme
will drive the motor the specified number of holes in the
specified direction. If you then manually rotate the en- Centronix parallel standard
coder wheel
or some heavy load moves the arm and ro- I/O driver
tates the
encoder disk, the controller will detect the Control block
change in position of the disk and drive the motor back Counters and sentinels
to its specified position. This is an example of digital
feedback control, which is easily done with a microcom- Keyswitches — mechanical, capacitive. Hall effect
puter. The
Rhino controller uses an 8748 single-chip
microcomputer to interpret and carry out the com- Debounce keypress
mandssend
you it. Commands are sent to the controller
in the serial ASCII form described at the start of Chapter Two-key lockout, two-key rollover
13.
Incidentally, you may wonder at this point why the Code conversion
Compare
designers of the Rhino arm did not use stepper motors
Add and point. XLAT
such as those we described in a previous section. The
answers are: stepper motors are much more expensive
than the simple dc motors used; if a stepper motor is Error trapping
forced back a step there is no way to know about it and
LED interfacing
correct for it unless you have an external encoder. Also
Static display
the dc motor-encoder approach better demonstrates the
Multiplexed display
method used in large commercial robots.
In the Rhino robot arm each motor drives its section
Dedicated display controller
of the arm through a series of gears. Gearing the motor
Scan time
down reduces the force that the motor has to exert, and
8279
makes the exact position of the motor shaft less critical.
FIFO
Therefore, for the Rhino, six sets of slots in the encoder
Encoded and decoded scan
disk are sufficient. However, for applications where a Keyboard/display mode-set control word
much more accurate indication of shaft position is
Clear control word
needed, a self-contained shaft encoder such as the
Write-display control word
Hewlett-Packard HEDS-5000 is attached to the motor
shaft. These encoders have two track-encoder disks LCD interfacing
with 500 tiny radial slits per track. The waveforms pro- Dynamic scattering
duced the
are same as those shown for the Rhino en- Field effect
coder
Figure
in 9-44. but at a much higher frequency for Backplane
the same motor speed. Triplexing
Optical encoders in their many different forms are an
important part of a large number of microcomputer- Relays
controlled machines. Mechanical

306 ( IIM'HR NIN[


Solid state Foui phase stepper motor
Electromagnetic Intei ference
Shall encoders absolute and ini n mental
Zero point switching
RC snubber circuit i feedback control

REVIEW QUESTIONS AND PROBLEMS


1. Why must data be sent to a printer on a handshake 9. When connecting peripheral devices such as print-
basis? ers, terminals,etc. to a computer, why is it very
important to connect the logic ground and the
2. For the double handshake data transfer in Figure
chassis ground together only at the computer?
9- 1 d
(i. Indicate which signal is asserted by the sender It). Describe the function and direct ion ol the following
and which signal is asserted by the receiver. signals in a Centronics parallel-printer interface
b. Describe the meaning ol each oi the signal ,i. siKom

transitions. !>. ACkNL.C.


c. BUSY
3. Why are the port lines ol programmable port de- d. INH
vices automaticallyput in the input mode when the
device is first powered up or reset? 11. Modify the printer driver procedure in Figure 9-17
so that it stops sending characters to the printer
4. An 8255A has a system base address of FFF9H. when it finds a sentinel character of 03H. instead
What are the system addresses lor the three ports of using the counter approach.
and the control register for this 8255A?
12. Would the software method of generating the
5. a. Show the mode-set control word needed to ini-
STROBE signal to the printer in Figure 9-17 still
tialize8255A
an as follows:
work if you try to run the program with an 8-MHz
Port A — handshake input 8086?
Port B — handshake output
Port C— bits PC6 and PC7 as outputs 13. Show the instructions you would use to read the

b. Show the bit set/reset control word needed to status byte from the 8255A in Question 5.

initialize the port A interrupt request and the 14. Describe the three major tasks needed to get mean-
port B interrupt request. ingful information from a matrix keyboard.
c. Show the assembly language instructions you
would use to send these control words to the 15. Describe how the "compare" method of code con-
8255A in Question 4. version
Figure
in 9-21 works.
d. Show the additional instruction you need if
16. Why is "error trapping" necessary in real pro-
you want the handshake to be done on an in-
grams? Describe
how the error trap in the program
terrupt basis
through the IR3 input of the
in Figure 9-21 works.
8259A in Figure 8-14.
e. Show the instructions you would use to put a 17. Assume the rows of the circuit shown in Figure
high on port C bit PC6 of this device. 9-45 are connected to ports FFF8H and the 74148
is connected to port FFFAH of an SDK-86 board.
6. Describe the exchange of signals between the tape The 74148 will output a low on its GS output if a
reader, 8255A. and 8086 in Figure 9-6 as a byte of low is applied to any of its inputs. The way the key-
data is transferred from the tape reader to the mi- board
wired,
is the A2, A1, and AO outputs will have
croprocessor. a 3-bit binary code for the column in which a low
appears. Use the algorithm and discussion of Fig-
7. Why is it more efficient to send phonemes to the
ure 9-21to help you write a procedure which de-
SC-01A speech synthesizer in Figure 9-10a on an
tects
keypress,
a debounces the keypress, and de-
interrupt basis than on a polled basis?
termines
rowthenumber and column number of
8. If you have an SC-01A speech IC connected to your the pressed key. The procedure should then com-
system as shown in Figure 9- 10a. write the main- bine therow code, column code, shift bit and con-
line programand the interrupt procedure to send trol bit
into a single byte in the form: control, shift,
phonemes to the SC-01A. The mainline can termi- row code, column code. The XLAT instruction can
nate with
the HERE: JMP HERE instruction so then be used to convert this code byte to ASCII for
that it simply waits for interrupts from the 8255A. return to the calling program. HINT: Use DB direc-
Use the phoneme table in the appendix to help you tive make
to up table of ASCII codes.
make up the table of phonemes for the message Why is the XLAT approach more efficient than
"sell-test complete." the compare technique for this case?

DIGITAL INTERFACING 307


microcomputer to produce some interesting dis-
plays. The
principle here is to output a 1 to port B
for each LED you want turned on in the top row
and then output a 1 to the DO bit of port A to turn
on that row. After 2 ms. you output the pattern you
want in the row to port B and a 1 to bit 1 of port A
to turn on the second row. The process is repeated
until all rows are done and then started over.
The row patterns can be kept in a table in mem-
ory.
you11 want to display a sequence of letters, vou
can display the contents of one table for a few sec-
onds, then
switch to another table containing the
second letter. Using the rotate instruction, you can
produce some scrolled displays. HINT: The wiring
required to build the LED matrix can be reduced by
using an IC 5 by 7 dot-matrix LED display such as
the Texas Instruments TIL305.
Write the algorithm and program for an interrupt
procedure (called every 2 ms| to refresh these dis-
plays.
You are assigned the job of fixing several SDK-86
boards with display problems. For each of the prob-
lems listed
below, describe a possible cause of the
problem and tell where you would look with an os-
cilloscope
check toout your theory. Use the circuit
on sheet 7 of Figure 7-6 to help you.
a. The segment never lights.
b. The leftmost digit of the data field never lights.
c. All of the displays show dim "eights."
a. Show the command words and assembly lan-
FIGURE 9-45 Interface circuitry for unencoded matrix guage instructions necessary to initialize an
keyboard for Problem 9-17. 8279 at address 80H and 82H as follows:
16-character display, left entry-, encoded-scan
keyboard. /V-key rollover.
V )TE For test purposes, the keyboard matrix can 1-MHz input clock divided to 100 kHz.
be simulated by building the diodes, resistors, and Blanking character FFH.
74148 on a prototyping board and using a jumper b. Show the 8279 instructions necessary to write
wire to produce a "keypress." 99H to the first location in the display RAM
and autoincrement the display RAM pointer.
a. Calculate the value of the current-limitini; re- c. Show the assembly language instructions nec-
sistor needed
in series with each segment of a essary
readto the first byte from the 8279 FIFO
seven-segment display driven by a 7447. if you RAM.
want 40 mA per segment. d. Determine the seven-segment codes you would
b. Approximately how much current is being have to send to the SDK-86 8279 to display the
pulsed through each LED segment on the letters HELP on the data field display. Remem-
SDK-86 board? ber that DO of the byte sent = BO and D7 of the
byte sent = A3.
a. Write the algorithm for a procedure which re- e. Show the sequence of instructions you can
freshes
multiplexed
the LED displays shown in send to the 8279 of the SDK-86 board to blank
Figure 9-26. Assume the procedure will be the entire display.
called every 2 ms by an interrupt signal to IR4
of an 8259A. 23. Write a procedure which polls the LSB of the 8279
b. Write the assembly language instructions for status register on the SDK-86 board until it finds a
the display refresh procedure. Since this pro- key pressed, then reads the keypressed code from
cedure
called
is on an interrupt basis, all dis- the FIFO RAM to AL and returns.
play parameters should be kept in named Why must the backplane and segment-line signals
memory locations. If you have time, you can be pulsed for LCD displays?
add the circuitry shown in Figure 9-26 to your
Draw a circuit you could attach to an 8255A port B
microcomputer so you can test your program.
pin to drive a 1-A solenoid valve from a + 12-V sup-
20. Figure 9-46 shows a circuit for an 8 by 8 matrix of ply. You
want a high on the port pin to turn on the
LEDs that you can add to a couple of ports on vour solenoid.

308 CHAPTER NINE


-^
1 kS2 ^
W\r-pN2

sy /\ /y /s
^N ^N /N /ts /N /ts

D 7 D6 DE %¡4 DJ

PORT B

FIGURE 9-46 Eight by eight LED matrix circuitry for Problem 9-20.

26. Why must reverse-biased diodes always be placed 30. a. Why is Gray code, rather than straight binary
across inductive devices when you are driving them code, used on many absolute-position shaft
with a transistor? encoders?
b. If a Gray-code wheel has six tracks and each
27. What are the major advantages and disadvantages
track represents 1 binary bit. what is its angu-
of mechanical relays and solid-state relays.
lar resolution?
28. n. How is electrical isolation between the control
31. a. Look at the encoder disk on the Rhino arm in
input and the output circuitry achieved in a
Figure 9-43. Do the waveforms in Figure 9-44
solid-state relay?
represent clockwise or counterclockwise rota-
b. Describe the function of the zero-crossing de-
tion the
of motor shaft as seen from the gear
tector used
in better-quality solid-state relays.
end of the motor, which is what you care
c. Why is a "snubber circuit" required across the
about.
triac of a solid-state relay when you are driving
b. Assume the A signal shown in Figure 9-44 is
inductive loads?
connected to bit DO and the B signal is con-
29. Write the algorithm and the program for an 8086 nected
bit to D1 of port FFF8H. Write a proce-
procedure to drive the stepper motor shown in Fig- dure which determines the direction of rota-
ure 9-41.Assume the desired direction of rotation tion andpasses a 1 back in AL for clockwise
is passed to the procedure in AL (AL = 1 is clock- and a 0 back in AL for counterclockwise rota-
wise.=AL 0 is counterclockwise) and the number tion.
of steps is passed to the procedure in CX. Also as- c. The dc motors, such as those on the RHINO
sume full-stepmode as shown in Figure 9-4 lb. arms, are rotated clockwise by passing a cur-
Don't forget to delay 20 ms between step com- rent throughthem in one direction and rotated
mands! counterclockwise by passing a current through

DIGITAL INTERFACING 309


them in the opposite direction. Assume you dure to rotate a motor. The number of holes is
have a motor controller that responds to a 2-bit passed to the procedure in CX; the direction of
control word as follows: rotation is determined by the value in AL.
00 = hold 01 = rotate clockwise AL = 1 is clockwise, AL = 0 is counterclock-
11 = hold 10 = rotate counter-clockwise wise.
Write the algorithm and program for a proce-

310 CHAPTER NINE


CHAPTER

Analog Interfacing and


Industrial Control

In order l<> control the machines in our electronics fac- (>. Draw circuits showing how A/D converters ol vari-
tory, medicalinstruments, or automobiles with a micro- ous typescan be interlaced to a microcomputer.
computei we need to determine the values of variables
7. Write programs to control A/D and D/A converters.
such as pressure, temperature, and How. There are usu-
ally severalsteps in getting an electrical signal which 8. Describe how feedback is used to control variables
represents the values ol these variables, and converting such as pressure, temperature. How, motor speed.
the electrical signals to a digital form tint the micro- ck

computer understands.
The first step involves a sensor which converts the 9. Describe the operation of a "time slice" factory con-
physical pressure, temperature, or other variable to a trol system.
proportional voltage or current. The signals from most
sensors are quite small, so they must next be amplified,
REVIEW OF OPERATIONAL-AMPLIFIER
and perhaps filtered. This is usually done with some
CHARACTERISTICS AND CIRCUITS
type of operational-amplifier (op-ampl circuit. The final
step is to convert the signal to digital form with an Basic Operational Amplifier Characteristics
analog-to-digital (A/Dl converter. In this chapter we re-
Figure 10- la shows the schematic symbol for an op
view someop-amp circuits commonly used in these
amp. Here are the important points for you to remember
steps, show the interface circuitry for some common
about the basic op amp. First, the pins labeled +V and
sensors, and discuss the operation and interfacing of
-V represent the power supply connections. The volt-
A/D converters. We also discuss the interfacing of D/A
ages applied
to these pins will usually be +15 V and
converters and show how all of these pieces are put to-
- 15 V. or + 12 V and - 12 V. The op amp also has two
gether
a microcomputer-based
in scale and a machine-
signal inputs. The amplifier amplifies the difference in
control system.
voltage between these two inputs by 100,000 or more.
The input labeled with a - sign is called the inverting
input and the one labeled with the + sign is called the
OBJECTIVES
noninverting input. The + and - on these inputs has
At the conclusion of this chapter you should be able to: nothing to do with the power-supply voltages. These
signs indicate the phase relationship between a signal
1. Recognize several common op-amp circuits, de- applied to that input and the result that signal produces
scribe their
operation, and predict the voltages at on the output. If for example, the noninverting input is
key points in each. made more positive than the inverting input, the output
will move in a positive direction, which is in phase with
2. Describe the operation and interfacing of several the applied input signal. Now let's see how much the
common sensors used to measure temperature, output changes for a given input signal, and see how an
pressure, flow. etc. op amp is used as a comparator.
3. Draw circuits showing how to interface D/A convert-
ers with any number of bits to a microcomputer.
Op-amp Circuits and Applications
4. Define D/A data-sheet parameters such as resolu-
tion, settlingtime, accuracy, and linearity. OP AMPS AS COMPARATORS

5. Describe briefly the operation of flash, successive We said previously that the op amp amplifies the differ-
approximation, and ramp A/D converters. encevoltage
in between its inputs by 100,000 or more.

311
I .'AMP COMPARATOR COMPARATOR WITH HYSTERESIS

OUTPUT = +V -1 V
IF v1N% VBir

OUTPUT * -V + 1 V
R,
IF V,N V„„
R % R

NON INVERTING AMP INVERTING AMP ADDER (MIXER)

DIFFERENTIAL AMP INSTRUMENTATION AMP

Rl R2

R3 Rf

vou1(v, v^^Xll)

INTEGRATOR IRAMP GENERATOR! DIFFERENTIATOR

VIN
>_|(-

x_Fth

2ND ORDER LOW PASS F I LTER 2ND ORDER HIGH PASS FILTER

vi:j^H( J l( T "^^-

FIGURE 10-1 Overview of commonly used op-amp circuits, (a) Common op amp. (b) Comparator, (c) Comparator
with hysteresis, (d) Noninverting amp. (e) Inverting amp. it) Adder (mixer), (g) Differential amp. (h) Instrumentation
amp. (i) Integrator (ramp generator). (/) Differentiator. Ik) Second-order low-pass filter. (I) Second-order high-pass
filter.

312 CHAPTERTEN
(The number is variable with temperature and from de oscillate as the Input signal gets close to the reference
vice to device.) Suppose that you power an op amp with voltage.
I 15 V and 15 V, tie the inverting input oi the op amp In determine the amount ol hysteresis in a circuit
id ground, and apply .i signal ol i 0.01 V dc to Ihe non such as tli.it in Figure K) Ic, assume Viu , 0 V and
Invei ting input. The op amp will attempt to amplify this \ i, 13 V. A simple voltage-dividei calculation will tell
signal In 100.000 and produce the result on ns output. yon that the noninverting Inpul is at about 13 mV, The
An Input signal ol 0 01 V times a gain ol 100.000 pre voltage on the inverting inpul of the amplifiei will have
diets an output voltage ol 100 V. The op-amp output, to go more positive than ibis be lore the comparatoi will
however, ran only go positive to a voltage a volt or two Change slates. Likewise, il you assume \\,r\ is 13 V.
less than the positive supply voltage, perhaps 13 V. so the noninverting input will be al about 13 mV, so the
this is as far as II nuts. Now suppose llial von applj a voltage on the inverting input ol the amplifiei will have
signal ol 0.01 V to the noninverting input . The output to go below Ibis to change the stale ol the output. The
will now try to go to 100 V as fast as it tan. The output, hysteresis ol ilus comparatoi is • 13 mV and 13 mV.
however, ran only go to about Kf V, so it stops here.
In this circuit the op amp effectively compares the
NONINVERTINC. AMPLIFIER OP-AMP CIR( I HI
input voltage with the voltage on the inverting input
and gives a high or low output depending on the result When operating in open-loop mode (no feedback to the
ol the comparison. If the input is more than a few inverting input I. an op amp has a very high, but unpre-
microvolts above the reference voltage on the inverting dictable,This
gain. is acceptable for use as a compara
input, the output will be high (+13 V). If the input volt- tor, but not for use as a predictable amplifier. Figure
agea isfew microvolts more negative than the reference 10-lri shows one way negative feedback is added to an
voltage, the output will be low I 13 V). An op amp used op amp to produce an amplifier with stable, predictable
in this way is called a comparator. Figure 10- lb shows gain. First of all notice that the input signal in this cii
how a comparator is usually labeled. The reference volt- cuit is applied to the noninverting input, so the output
age appliedto the inverting input does not have to be will be in phase with the input. Second, note that a trac-
ground (0 V). An input voltage can be compared to any tionthe
of output signal is fed back to the inverting
voltage within the input range specified for the particu- input. Now. here's how tins works.
lar opamp. To start assume that VIN is 0 V. V(im is 0 V, and the
As you will see throughout this chapter, comparators voltage on the inverting input is 0. Now. suppose that
have many applications. We might, for example, connect you apply a +0.01-Vdc signal to the noninverting input
a comparator to a temperature sensor on the boiler in Since the 0. 1 -V difference between the two inputs will be
our electronics factory. When the voltage from the tem- amplified by 100,000. the output will head towards 100
perature sensor
goes above the voltage on the reference V as fast as it can. However, as the output goes positive,
input of the comparator, the output of the comparator some of the output voltage will be fed back to the invert-
will change state and send an interrupt signal to the ing inputthrough the resistor divider. This feedback to
microprocessor controlling the boiler. Commonly avail- the inverting input will decrease the difference in volt-
able comparators such as the LM319 have TTL-compali- age betweenthe two inputs. To make a long story short,
ble outputs which can be connected directly to micro- the circuit quickly reaches a predictable balance point
computer orports
interrupt inputs. where the voltage on the inverting input (VF) is very, veiy
Figure 10-lc shows another commonly used compara- close to the voltage on the noninverting input (Vin)- For
tor circuit. Note in this circuit that the reference signal a 1.0-V dc output this equilibrium voltage difference
is applied to the noninverting input, and the input volt- might be about 10 ^<V. If you assume that the voltages
ageapplied
is to the inverting input. This connection on the two inputs are equal, then predicting the output
simply inverts the output state from those in the previ- voltage for a given input voltage is simply a voltage di-
ous circuit.Note also in Figure 10-lc the positive-feed- vider problem.V0ut = VIN{R\ + R2)/R\. If R2 is 99 kil
back resistorsfrom the output to the noninverting and Rl is 1 ki», then V,,,,, = V,N % 100. For a 0.01-V
input. This feedback gives the comparator a character- input signal the output voltage will be 1.00 V. The
istic called
hysteresis. Hysteresis means that the output closed-loop gain. AVci., for this circuit is equal to the
voltage changes at a different input voltage when the simple resistor ratio. (Rl + R2)/Rl.
input is going in the positive direction than it does To see another advantage of feeding some of the out-
when the input voltage is going in a negative direction. put signalback to the inverting input, let's see what
If you have a thermostatically controlled furnace in your happens when the load connected to the output of the
house you have seen hysteresis in action. The furnace, op amp changes and draws more current from the out-
for example, may turn on when the room temperature put. The
output voltage will temporarily drop because ol
drops to 65°F, and then not turn off until the tempera- the increased load. Part of this drop will be fed back to
ture reaches68°F. Hysteresis is the difference between the inverting input, increasing the difference in voltage
the two temperatures. Without this hysteresis the fur- between the two inputs. This increased difference will
nace would rapidly be turning on and off if the room cause the op amp to drive its output to correct for the
temperature were near 68°F. Another situation where increased load. Feedback which causes an amplifier to
hysteresis saves the day is the case where you have a oppose a change on its output is called negative feed
slowly changing signal with noise on it. Hysteresis pre- back. Because of the negative feedback, then, the op
ventsnoise
the from causing the comparator output to amp will work day and night to keep its output stabi-

ANALOC INTERFACING AND INDUSTRIAL CONTROL 313


lized and its two inputs at nearly the same voltage! This
is probably the most important point you need to know 100,000
70,700 '"
to analyze or troubleshoot an op-amp circuit with nega- 1 > = -6dB/ 3CTAVE OR
tive feedback. Draw a box around this [joint in your
10,000
1 v\^ SLOPE
/-20dB DECADE
1
mind so you don't forget it. 1,000
1
The noninverting circuit we have |ust discussed is 1
used mostly as a buffer, because it has a very high input
100 u 1
1 UNITY GAIN
impedance (Zm), and will therefore not load down a sen- 10 1 FREQUENCY
sor orsome other device you connect to its input. 1
1 1 1 1 1 >o/
1
Bipolar-transistor-input op amps will have an input
10 100 1 10 100 1
impedance greater than 100 Mil. Some op amps such as KHZ MHZ
FREQUENCY

the National LF356 have a FET input stage so then


input impedance is 1012 !>.

INVERTING AMPLIFIER OP-AMP CIRCUIT

Figure 10-le shows a somewhat more versatile amplifier


OPEN LOOP
circuit using negative feedback. Note that in this cir-
cuit, the
noninverting input is tied to ground with a
resistor and the signal you want to amplify is sent to the
inverting input through a resistor. The output signal SLOPE =
20dB/DECADE
will therefore be 180° out of phase with the input signal
Resistor R, supplies the negative feedback which keeps
the two inputs at nearly the same voltage. Since the
noninverting input is tied to ground, the op amp will 1 10 100 1 10 100 1
sink or source current to hold the inverting input also at HZ KHZ MHZ

zero volts. In this circuit the inverting input point is f,- - BANDWIDTH
referred to as virtual ground because the op amp holds
it at ground. The voltage gain of this circuit is also de-
termined
the by ratio of two resistors. The AV( i. for this FIGURE 10-2 (a) Open-loop gain versus frequency
circuit at low frequencies is equal to -Rt/R\. You can response of 741 op amp. (b) Cain versus frequency
derive this lor yourself by just thinking of the two resis- response of 741 op-amp circuit with closed-loop gain of
tors aasvoltage divider with V!N at one end. zero volts in 100.
the middle, and VOI n- on the other end. The minus sign
in the gain expression simply indicates that the output Remember from the previous discussion that in an
is inverted from the input. The input impedance (ZIN) of inverting circuit, the op amp holds the inverting input
this circuit is approximately Rl because the op amp at virtual ground. For the circuit here the input voltage.
holds one end of this resistor at zero volts. V'|. produces a current through Rl to this point. The
One additional characteristic we need to refresh in input voltage, V2, causes a current through R'2 to this
your mind about op-amp circuits before going on to point. The two currents add together at the virtual
other op-amp circuits is gain-bandwidth product. As ground, which is commonly called the summing point
we indicated previously, an op amp may have an open- for this circuit. The sum of the two currents is pulled
loop dc gain of 100.000 or more. At higher frequencies through resistor R, by the op amp to hold the inverting
the gain decreases until, at some frequency, the open- input at zero volts. The output voltage is then equal to
loop gain drops to 1. Figure 10-2a shows an open loo]) the sum of the currents times the value of R,, or
voltage 14am versus frequency graph for a common op (V,/R1 + VVR2I % R,. A circuit such as this is used to
amp such as a 74 1. The frequency at which the gain is 1 "mix" audio signals and to sum binary-weighted cur-
is referred to on data sheets .is the unity-gain band- rentsa inD/A converter. An adder circuit can have sev-
width theor gain-bandwidth product. A common value eral inputs.
Ior this is 1 Mil/. The bandwidth of an amplifier circuit
with negative feedback times the low-frequency closed- SIMPLE DIFFERENTIAL-INPUT AMPLIFIER CIRCUIT
loop gain will be equal to this value. For example. 1I an
As we will show later, many sensors have two output
op amp with a gain-bandwidth product ol 1 MHz is used
signal lines with a dc voltage of several volts on each
to build an amplifier circuit with a closed-loop gain of
signal line. The dc voltage present on both signal leads
100. the bandwidth of the circuit ( /, I will be about
is referred to as a common-mode signal. The actual sig-
1 MHz/lOO or 10 kHz. as shown in Figure 10-2b.
nal you
need to amplify from these sensors is the few
millivolts difference between them. If you try to use a
OP-AMP ADDER CIRCUIT
standard inverting or noninverting amplifier circuit to
Figure 10-1J shows a commonly used variation ol the do this, the large dc voltage will be amplified along with
inverting amplifier described in the previous section. the small difference voltage you need to amplify. Figure
This circuit adds together or mixes two or more input 10- lc; shows a simple circuit which, for the most part,
signals. Here's how it works. solves this problem without using coupling capacitors

314 C HAPTtK I EN
to block the dc rhe analysis ol this circuit is beyond the simple R< filters, bul at live inters using op am|
space we have heir, bul basically the resistors on the much bettei control ovei filtei chai ai
noninverl ing input hold this input .it .1 voltage neai thi man) different filter configurations using op amps. The
common mode voltage I In- amplifier holds the invert- main points we want to refresh here are the meanings ol
ing input.11 the same voltage It the resistors are the terms low-pass filter, high-pass filter, and hand
matched carefully, the result is that only the differen< e pass filter; and how you identify the type when you find
in voltage between \ ,ukI \ will be amplified rhe out one in a circuit von are analyzing.
put will be >i single line which contains only the ampli A low pass filtei amplifies 01 passes through low fre
fied difference We say that the common-mode muh.i! quencies, but at some frequency determined by circuit
has been rejected. values, the output of the filtei starts to decrease. The
frequency at which the output is down to 0 707 ol the
AN INSTRUMENTATION AMPLIFIER ( IR( Mil
low frequency value is (ailed the critical frequency or
Figure 10 l'i shows .111op amp circuit used in applica- break point. Figure l0-3a shows ,1 graph ol gain versus
tions needing
a greater rejection ol the common mode frequenc) foi a low pass filtei with the critical frequency
signal than is provided bv the simple differential circuit ( /, ) labeled. Note that above the critical frequency th<
in Figure 10-lg. The first two op amps in tins circuit gain drops of! rapidly. For a first ordei filtei such as a
remove the common mode voltage and the lasi op amp single R and C, the gain decreases by a factor ol to for
converts the result from a differential signal to a signal each increase ol id times in frequency I 20 dB/decade).
referenced i<> ground. Instrumentation amplifier cir For a second order filter the gain decreases by a factoi ol
cuits such as this are available in single packages. 100 for each increase ol 10 times in frequenc)
Figure 10-lk shows a common circuit for a second-
AN OP-AMP INTEGRATOR CIRCUIT
order low-pass filter. The way you recognize this as a
Figure 10- li shows an op-amp circuit that can be used low-pass filter is to look for a dc path from the input to
to produce linear voltage ramps. A dc voltage applied to the noninverting input of the amplifier. II the dc path is
the input of this circuit will cause a constant current of present, as it is in Figure 10-lfc. you know that the am
V1N/R1 to flow into the virtual-ground point. This cur- plifier can amplify dc and low frequencies. Therefore, it
rent flows
onto one plate c>t Ihe capacitor. In order to is a low-pass filter with a response such as that shown
hold the inverting input at ground, the op-amp output in Figure 10-3a.
must pull the same current from the other plate of the For contrast look at the circuit for the second order
capacitor. The capacitor is then getting charged by the high-pass filter in Figure 10-1/. Note that in this circuit
constant current Vin/R1. Basic physics tells you that the the dc component of an input signal cannot reach the
voltage across a capacitor being charged by a constant noninverting input because of the two capacitors in se-
current is a linear ramp. Note that because of the in- ries withthat input. Therefore, this circuit will not
verting amplifier
connection, the output will ramp nega- amplify dc and low-frequency signals. Figure I0-3fa
tive aforpositive input voltage. Also note that some pro- shows the graph of gain versus frequency for a high-
vision must
be made to prevent the amplifier output pass filter such as this. Note that the gain-bandwidth
from ramping into saturation. product of the op amp limits the high-frequency re-
The circuit is called an integrator because it produces sponse
the ofcircuit.
an output voltage proportional to the integral or "sum" For the low-pass circuit in Figure 10-lk, the gam tor
of the current produced by an input voltage over a pe- the flat part of the response curve is 1 . or unity, her arise
riodtime.
of The waveforms in Figure 10-li show the the output is fed back directly to the inverting input. At
circuit response for a pulse-input signal. the critical frequency./,, the gain will be 0.707. and
above this frequency the gain will drop off. The critical
AN OP-AMP DIFFERENTIATOR CIRCUIT
frequency for the circuit is determined by the equation
Figure 10-1/ shows an op-amp circuit which produces next to the circuit. The equation assumes that Rl and
an output signal proportional to the rate of change of R2 are equal, and that the value of CI is twice the value
the input signal. With the input voltage to this circuit at of C2. R3 is simply a damping resistor. The positive
zero or some other steady dc voltage, the output will be feedback supplied by CI is the reason the gain is only
at zero. If a new voltage is applied to the input, the volt- down to 0.707 at the critical frequency rather than
age acrossthe capacitor cannot change instantly, so the down to 0.5 as it would be if we simply cascaded two
inverting input will be pulled away from zero volts. This simple RC circuits.
will cause the op amp to drive its output in a direction to For the high-pass filter, the gain for the flat section of
charge the capacitor and pull the inverting input back the response curve is also one. Assuming that the two
to zero. The waveforms in Figure 10-1/ show the circuit capacitors are equal and the value of R2 is twice the
response for a pulse-input signal. The time required for value of Rl. the critical frequency is determined by the
the output to return to zero is determined by the time formula shown next to Figure 10-li. Again. R3 is for
constant of Rl and C. damping.
A low-pass filter can be put in series with a high-pass
OP-AMP ACTIVE FILTERS
filter to produce a bandpass filter which lets through a
In many control applications we need to filter out un- desired range of frequencies. There are also many differ-
wanted low-frequency
or high-frequency noise from the ent singleamplifier circuits which will pass or reject a
signals read in from sensors. This could be done with band of frequencies.

ANALOG INTERFAC INC AND INDUSTRIAL CONTROL 315


pattern of cadmium sulfide or cadmium selenide whose
100.000
resistance depends on the amount of light present. The
10.000 l— resistance of the CL905 varies from about 15 Mi! when
\ OP AMP
1,000 >w /^ OPEN LOOP in the dark to about 15 kfl when in a bright light.
Photoresistors such as this do not have a very fast re-
100
sponse and
time are not siable with temperature, but
10 -

they are inexpensive, durable, and sensitive. For these


reasons they are usually used in applications where a
>
k 2ND \^ measurement of the amount of light need not be precise.
\ ORDER \ The devices on top of streetlights which turn them on
\^ LOW
PASS \
\ FILTER when it gets dark, for example, contain a photoresistor.
a transistor driver, and a mechanical relay as shown in
001

000 1
1
A , Figure
photoresistor
10-4b. As it gets dark,
goes up. This increases
the resistance of the
the voltage on the
10 100 1 10 100 1
KHZ MHZ base of the transistor until, at some point, it turns on.
This turns on the transistor driving the relay, which in
turn switches on the lamp.
Another device used to sense the amount of light pres-
ent ais photodiode. If light is allowed to fall on a spe-
cially constructedsilicon diode, the reverse leakage cur-
rent the
of diode increases linearly as the amount of
light falling on it increases. A circuit such as that shown
OP AMP
OPEN LOOP in Figure 10-5 can be used to convert this small leakage
current to a proportional voltage. Note that in this cir-
cuitnegative
a reference voltage is applied to the nonin-
verting input of the amplifier. The op amp will then pro-
duce thissame voltage on its inverting input, reverse
biasing the photodiode. The op amp will pull the photo-
diode leakage current through Rf to produce a propor-
tional voltage
on the output of the amplifier. For a typi-
cal photodiode such as the HP 5082-4203 shown, the
reverse leakage current varies from near 0 /^A to about
100 /uA. so with the 100-k.Q R,, an output voltage of
about 0 V to 10 V will be produced. The circuit will work

FIGURE 10-3 Gain versus frequency response for


second-order low-pass and high-pass filters. <j> tow
pass, (b) High pass.

Now that we have refreshed your memory of basic


op-amp circuits we will next discuss some of the differ-
ent types of sensors you can use to determine the values
of temperatures, pressures, position, etc.

SENSORS AND TRANSDUCERS

It would take a book many times the size of this one to


describe the operation and applications of all of the dif-
ferent types
of available sensors and transducers. What
we want to do here is introduce you to a lew of these and
show how they can be used to get data tor micro- PHOTORESISTOR

computer-based instruments
in. for example, our electron-
ics factory.

Light Sensors
One of the simplest light sensors is a light-dependent FIGURE 10-4 (a) Cadmium sulfide photocell. (Clairex
resistor such as the Clairex CL905 shown in Figure Electronics), (b) Light-controller relay circuit using a
10-4a. A ul.iss window allows light to fall on a zig-zag photocell.

316 CHAPTER TEN


cells. The current from the solar cell is a lineai function
ol the amount ol liulit tailing on the cell, A circuil such
as that in Figure 10-5 can be used to convert i be output
current to a proportional voltage Because ol the largei
output current we decrease R, to a much smaller value.
PHOTODIODE depending on the output current ol i be cell We also con
HP5082 4203
nect the noninverting Input ol the amplifiei in ground
because we don't use reverse biasing with solai cells
flic frequency response to light (spectral response) ol
IKiUKI 10-5 Photodiode circuil to measure infrared solai cells has been tailored to match the output of the
light intensity sun. Therefore, they an- ideal in photographic applica
tions where we want a signal proportional to the total
light from the sun or from an incandescent lamp.
without any reverse bias on the diode, but with the re-
verse bias,
the diode responds faster to changes in light.
An LM356 FET input amplifiei is used here because ii Temperature Sensors
does not require an input bias current. Again, there are many types of temperature sensors.
A photodiode circuit such as tins might be used to
The two types we discuss here are: semiconductor de
determine the amount ol smoke being emitted from a
vices, which are inexpensive and can be used to mea
smokestack. To do this a gallium arsenide infrared LED
sure temperatures over the range of -55 C to 100 C,
is put on one side of the smokestack, and the photode-
and thermocouples which can be used to measure very
tector circuit put on the other. Since smoke absorbs low temperatures and very high temperatures.
light, the amount ol light arriving at the photodetector
is a measure of the amount of smoke present. An infra-
SEMICONDUCTOR TEMPERATURE SENSORS
red LEDis used here because the photodiode is most
sensitive to 1iiO.lit wavelengths in the infrared region. The two main types of semiconductor temperature sen-
Still another useful light-sensitive device is a solar sors aretemperature-sensitive voltage sources and
cell. Common solar cells are simply large, very heavily- temperature-sensitive current sources. An example of
doped, silicon PN junctions. Light shining on the solar the first type is the National LM35 which we show the
cell causes a reverse current to (low. just as in the photo- circuit connections for in Figure 10-6a. The voltage out-
diode. Because
of the large area and the heavy doping in put fromthis cireirit increases by 10 mV for each degree
the solar cell, however, the current produced is milliam- Celsius that its temperature is increased. By connecting
peres rather than microamperes. The cell functions as a the output to a negative reference voltage (V.s) as shown,
light-powered battery. Solar cells can be connected in a the sensor will give a meaningful output for a tempera-
series-parallel array to produce a solar power supply. ture rangeof -55 to +150°C. You adjust the output to
Light meters in cameras, photographic enlargers, and zero volts for 0°C. The output voltage can be amplified to
our printed-circuit-board-making machine use solar give the voltage range you need for a particular applica-

OFFSET
REFERENCE

MEASURED TEMP
0TO 100°C P2 15 K
TRIM 100 C

-1500 mV AT 150'C

h250mV AT 25 C
550 mV AT -55:'C

REMOTE
TEMPERATURE-
TO CURRENT
TRANSDUCER,
1 mA/K 1 KS2 0.1' NSTRUMENTATION
LOW TCR AMPLIFIER,
AD590 IC IS METERING GAIN OF 10,
AVAILABLE IN RESISTOR. 0.00 V TO 1.00 FS
PROBE AS AC2626J dV/mA = ImV/K 10mV/°C

(a)

FIGURE 10-6 Semiconductor temperature-sensor circuits, (a) LM35


temperature-dependent voltage source, (b) AD590 temperature-dependent
current source. (Analog Devices Incorporated)

ANALOG INTERFACING AND INDUSTRIAL CONTROL 317


tion. In a later section of this chapter we show another
circuit using the LM35 temperature sensor. The accu- REFERENCE
JUNCTION
racy this
of device is about 10.
15C- T. 35'C
Another common semiconductor temperature sensor
is a temperature-dependent current source such as the
Analog Devices AD590. The AD590 produces a current VII .. IURII

of 1 /xA/ Kelvin. Figure 10-6h shows a circuit which con-


verts this
current to a proportional voltage. In this cir-
cuit the
current from the sensor (/7-( is passed through
an approximately l-kfi resistor to ground. This pro-
duces
voltage
a which changes by 1 mV/°Kelvin. The
RA
AD580 is a precision voltage reference used to produce a TYPE NOMINAL
...,;i
reference voltage of 273.2 mV. With this voltage applied J 52 3 n
to the inverting input of the amplifier, the amplifier out- K % II 2 I!
E 61 4fi
put will
be at zero volts for 0 C. The advantage of a T 40 2!2
S. R 5 76 n
current-source sensor is that voltage drops in long con-
necting do
wires
not have any effect on the output value.
If the gain and offset are carefully adjusted, the accuracy FIGURE 10-7 Circuit showing amplification and cold-
of the circuit in Figure 10-6b is ± 1 C using an AD590K junction compensation for thermocouple. (Analog
part. Devices Incorporated)

THERMOCOUPLES
temperature ranges. A thermocouple junction made of
Whenever two different metals are put in contact, a iron and constantan. commonly called a type J thermo-
small voltage is produced between them. The voltage couple,
a useful
has temperature range of about - 184 to
developed depends on the types of metals used and the + 760 C. A junction of platinum and an alloy of platinum
temperature. Depending on the metals, the developed and 13 percent rhodium has a useful range of 0°C to
voltage increases between 7 yuV and 75 /xV for each de- about 1600°C. Thermocouples can be made small, rug-
gree Celsius
increase in temperature. Different combi- ged, and
stable: however, they have three major prob-
nations
metals
of are useful for measuring different lems whichmust be overcome.

WIDE CHOICE OF
POWER SUPPLY
OPTIONS
WIDE VARIETY OF SENSOR AND
ANALOG SIGNAL INPUTS

THERMOCOUPLE COLD JUNCTION


COMPENSATION PROVIDED ON
RIBI
HIGH L EACH CHANNEL

INDUSTRIAL SCREW TERMINALS FOR


DIRECT SENSOR WIRING
COMPLETE SIGNAL CONDI
FUNCTION PER MODULE

FIGURE 10-8 Packaging of signal-conditioning circuitry for use in industrial


environments. (Analog Devices Incorporated)

318 ( HAI'TF.R TPN


First Hi these In the facl thai the output is very small has the advantages that the signal amplitude is then not
.md must be amplified a great deal to bring it up Into the affei ted bj resistance, Induced voltage noise, 01 voltage
range where il can. foi example, drive an A I >i onvei tei drops in .1 long connecting line. A common range of cui
Second, In ordei to make accurate measurements, .1 rents used to represent analog Signals in industrial en
second junction nude ol the same metals must In- in- vironments is 4 111Ato 20 111A.A current ol l mA repre
cluded
the incircuit .is .1 reference. Adding tins second senis a zero output, .1111I.1 current ol 20 mA represents
junction is referred to as cold-junction compensation the lull scale value. I'he reason that the cui rent 1
Figure in 7 shows a circuit to amplify the output ol a offsel from zero is so thai .1 currenl ol zero is lefl to rep
thermocouple and provide cold-junction compensation resent an open circuit. The currenl can be converted to
leu a type .1 thei mocouple. a proportional voltage .11 the receiving cud by simply
The first thing to notice in the circuit is that the refer passing it through .1 resistor.
ence junction is connected in the revei se direction from
the measuring junction. This is done so ilia 1 the output
connecting wires are both constantan. The thermocou Force and Pressure Transdu< crs
[iles formed by connecting these wires to the coppei To convert force or pressure (force/area) to .1 propor-
wires going t" the amplifier will then cancel out. The tional electrical
signal, the most common methods use
resultant output voltage will be the difference between strain gages and lineai variable differential transform
the voltages across the two thermocouples. ITwe simply crs (LVDTs). Both of these methods involve moving
amplify the output of the two thermocouples, however, something. This is why we refer to them as transducers
there is a problem it the temperature of both thermo- rather than as sensors. Here's how strain gages work.
couples
changing.
is The problem is that it is impossible
to tell which thermocouple caused a change in output
STRAIN GAGES AND LOAD CELLS
voltage. One cure for this is to put the reference junction
in an ice bath or a small oven to hold it at a constant A strain gage is a small resistor whose value changes
temperature. This solution is usually inconvenient, so when its length is changed. It may be made of thin wire.
instead a circuit such as that in Figure 10-7 is used to thin foil, or semiconductor material. Figure 10-9a
compensate electronically for changes in the tempera- shows a simple setup lor measuring force or weight with
turethe
of reference junction. strain gages. One end of a piece of spring steel is at-
As we discussed in a previous section the AD590 tached
a fixed
to surface. A strain gage is glued on the
shown here produces a current proportional to its tem- top of the flexible bar. The force or weight to be meas-
perature.
AD590
The is attached to the reference ther- uredapplied
is to the unattached end of the bar. As the
mocouple
that so they are both at the same tempera- applied force bends the bar. the strain gage is stretched,
ture. Thecurrent from the AD590, when passed increasing its resistance. Since the amount that the bar
through the resistor network, produces a voltage which is bent is directly proportional to the applied force, the
compensates for changes in the reference thermocouple change in resistance will be proportional to the applied
with temperature. The output amplifier lor this circuit force. If a current is passed through the strain gage
is a differential amplifier such as that shown in Figure then the change in voltage across the strain gage will be
10- lg or the instrumentation amplifier shown in Figure proportional to the applied force.
10- lh. Unfortunately, the resistance of the strain-gage ele-
The third problem with thermocouples is that their ments changes
also with temperature. To compensate
output voltages do not change linearly with tempera- for this problem two strain-gage elements mounted at
ture. This
can be corrected with analog circuitry which right angles as shown in Figure 10-9b are often used.
changes the gain of an amplifier according to the value Both of the elements will change resistance with tem-
of the signal. However, when a thermocouple is used perature,
onlybutelement A will change resistance ap-
with a microcomputer-based instrument, the correction preciablyapplied
with force. When these two elements
can be easily done using a lookup table in ROM. An A/D are connected in a balanced-bridge configuration as
converter converts the voltage from the thermocouple to shown in Figure 10-9c, any change in resistance of the
a digital value. The digital value is then used as a elements due to temperature will have no effect on the
pointer to a ROM location which contains the correct differential output of the bridge. However, as force is
temperature for that reading. applied, the resistance of the element under strain will
For use in industrial environments, circuitry such as change and produce a small differential output voltage.
that in Figure 10-7 is usually packaged in durable mod- The full-scale differential output voltage is typically 2 or
ules and mounted on racks in metal cabinets. Figure 3 mV per volt of applied voltage. For example if 10 V is
10-8 shows some of the Analog Devices 3B series signal- applied to the bridge, the full-load output voltage will
conditioning modules on a rack-mount panel. The only be 20 or 30 mV. This small signal can be amplified
3B37, for example, is a thermocouple-amplifier module with a differential amplifier or an instrumentation am-
with built in cold-junction compensation. The silver plifier.Analog
The Devices 3B16 module shown in Fig-
probe in front of the unit is a common type of thermo- ure 10-8
provides a 10-V excitation voltage and amplifi-
couple.rackThis unit is constructed so that you can cation
thefordifferential output signal for a strain-gage
plug in the modules you need for a given application. bridge.
Modules such as these usually have both a voltage out- Strain-gage bridges are used in many different forms
put and a current output. Sending a signal as a current to measure many different types of force and pressure. If

ANAtOC INTERFACING AND INDUSTRIAL CONTROL 319


STRAIN GAGESK SPRING STEEL STRIP

SSSfE
S3"*
n
WWMG8Z

STRAIN GAGESv. SPR ING STEEL STR IP

FIGURE 10-11 LX1804GBZ pressure transducer.


(Sensym, Inc.)

the strain-gage bridge is connected to a bendable beam


structure as shown in Figure 10-9a, the result is called a
load cell and is used to measure weight. Figure 10-10
shows a 10-lb load cell that might be used in a
microprocessor-controlled delicatessen scale or postal
scale. Larger versions can be used to weigh barrels being
filled, or even trucks.
If a strain-gage bridge is mounted on a movable dia-
phragm
a threaded
in housing, the output of the bridge
will lir proportional to 11u pressure applied lo the dia
phragm. If a vacuum is present on one side of the dia-
FICjURE 10-c) Strain gauges used to measure torce.
phragm,thethenvalue read out will be a measure of the
(a) Side view, (b) Top view (expanded), (c) Circuit
absolute pressure. If one side of the diaphragm is open
connections.
then the output will be a measure of the pressure rela-
tiveatmospheric
to pressure. If the two sides of the dia-
phragmconnected
are to two other pressure sources,
then the output will be a measure of the differential
pressure between the two sides. Figure 10-11 shows a
SFCNSYM LX1804GBZ pressure transducer which meas-
ures pressures in the range of 0 to 15 lb per square inch.
A transducer such as this might be used to measure
blood pressure in a microcomputer-based medical in-
strument.

LINEAR VARIABLE DIFFERENTIAL TRANSFORMERS

An LVDT is another type of transducer often used to


measure force, pressure or position. Figure 10-12 shows
the basic structure of an LVDT. It consists of three coils
of wire wound on the same form and a movable iron
core. An ac excitation signal of perhaps 20 kHz is ap-
pliedthe
to primary. The secondaries are connected so
that the voltage induced in one opposes the voltage in-
duced
thein other. If the core is centered then the in-
duced voltagesare equal and they cancel, so there is no
FIGURE 10-10 Photograph of load-cell transducer used net output voltage. If the coil is moved off center, cou-
to measure weight. (Transducers, Incorporated) pling will
be stronger to one secondary coil so that coil

320 < HAPItK II \


One method used is to put .i paddle wheel in the How
%is shown In Figure It) 13a ["he rate al which the paddle
wheel turns is proportional to the rate ol flow ol a liquid
or gas. An optical em odei i an be attai hed to the shafl ol
AC
i M'll AT ION the paddle whirl to | luce digital information as in
how last the paddle wheel is turning
20 KHZ
A second common method ol measuring How is with a
differential pressure transducer, as shown in Figure
lo i;;/i A wire mesh or screen is put in the pipe to
create some resistance. Mow through tins resistance
MOVEABL E [HON CORE
produces a difference in pressure between the two sides
FICURI 10-12 Linear variable differential transformei ol the resistance. The pressure transducer gives an out
(LVDT) stun ture put proportional to the difference in pressure between
the two sides ol the resistance. In the same way that the
voltage across an electrical resistoi is proportional to the
How ot (in lent through the resistor, the output of the
will produce a greater outpul voltage. The result will be a
pressure transducer is proportional to the How of a liq-
net outpul voltage. The phase relationship between the
uid or
gas through the pipe.
output signal and the input signal is an indication of
which direction the core moved from the center posi-
tion. The
amplitude of the output signal is linearly pro- Other Sensors
portional
how farto the core moves from the centei posi
tion. As we mentioned previously, the number of different
An LVDT can be used directly in this form to measure types of sensors is very large. In addition to the types we
displacement or position, [f you m\i\ a spring so that a have discussed, there are sensors to measure pH, con-
force is required to move the core, then the voltage out of centration
various of ibises, thickness of materials, and
the LVDT will be proportional to the force applied to the just about anything else you might want to measure.
core. In this form the LVDT can be used in a load cell for Often you can use commonly available transducers in
an electronic scale. Likewise, if a spring is added and creative ways to solve a particular application problem
the core of the LVDT attached to a diaphragm in a you have. Suppose, for example, thai you need to accu-
threaded housing, the output from the LVDT will be pro- rately determine the level of a liquid in a large tank. To
portional
the topressure exerted on the diaphragm. We do this you could install a pressure transducer at the
do not have space here to show the ac-interface circuitry bottom of the tank. The pressure in a liquid is propor-
required for an LVDT. tional
theto height of the liquid in the tank, so you can
easily convert a pressure reading to the desired liquid
height. The point here is to check out what is available
Flow Sensors and then be creative.
If we are going to control the flow rate of some material
in our electronics factory, we need to be able to measure
it. Depending on the material, flow rate, and tempera D/A CONVERTER OPERATION,
ture, we use different methods. INTERFACING, AND APPLICATIONS
In the previous sections of this chapter we have dis-
cussedwe howuse sensors to get electrical signals pro-
portional
pressure,
to temperature, etc. and how we use
op amps to amplify and filter these electrical signals.
The next logical step would be to show you how we use
an A/D converter to get these signals into digital form
that a microcomputer can work with. However, since
D/A converters are simpler and several types of A/D con-
verter have
D/As as part of their circuitry, we will dis-
DIFFERENTIAL
i PRESSURE cuss D/As
first.
TRANSDUCER

ft
D/A Converter Operation and Specifications

OPERATION
'RESISTANCE
The purpose of a digital-to-analog converter is to convert
a binary word to a proportional current or voltage. To
see how this is done let's look at the simple op-amp cir-
FIGURE 10-13 Flow sensors, (a) Paddle wheel. cuitFigure
in 10-14. This circuit functions as an adder.
(b) Differential pressure. Since the noninverting input of the op amp is grounded.

ANALOG INTERFACING AND INDUSTRIAL CONTROL 321


pressed
a percentage.
as The resolution of an 8-bit con-
verter then
is about 0.39 percent.
The next D/A characteristic to determine is the full-
scale output voltage. For the converter in Figure 10-15
voul the current for all of the switches is supplied by Vref
through R14. The current output from pin 4 of the D/A
is pulled through R0 to produce the output voltage. The
formula for the output voltage is shown under the cir-
cuit Figure
in 10-15. In the equation the term A\. for
FIGURE 10-14 Simple 4-bit digital-to-analog (D/A) example, represents the condition of the switch for that
bit. If a switch is closed, allowing a current to How, put a
converter.
1 in that bit. If a switch is open, put a 0 in that bit. As we
also show in Figure 10-15. if all of the switches are
the op amp will work day and night to hold the inverting
closed, the output will be (10 VK255/256I or 9.961 V.
input also at zero volts. This point, remember, is re-
Even though the output voltage can never actually get to
ferred
as toa virtual ground or summing point. When
10 V, this is referred to as a J0-V output converter. The
one of the switches is closed a current will flow from the
maximum output voltage of a converter will always have
-5-V (Vref) through that resistor to the summing point.
a value 1 least significant bit less than the named value.
The op amp will pull the current on through the feed-
As another example of this, suppose that you have a
back resistorto produce .1 proportional output voltage.
12-bit. 10-V converter. The value of 1 LSB will be (10
If you close switch DO, for example, a current of 0.05 mA
Vl/4096 or 2.44 mV. The highest voltage out of this con-
will flow into the summing point. In order to pull this
verter whenit is properly adjusted will then be
current through the feedback resistor, the op amp must
(10.0000 - 0.0024) V or 9.9976 V.
put a voltage of 0.05 mA % 10 kll or 0.5 V on its output.
Several different binary codes such as straight binary.
If you also close switch Dl, it will send another 0. 1 mA
B( ! ), and offset binary are commonly used as inputs to
into the summing point. In order to pull the sum of the
D/A converters. We will show examples of these codes in
currents through the feedback resistor, the op amp has
a later discussion of A/D converters.
to output a voltage of 0.15 mA • 10 kil or 1.5 V.
Fhe accuracy specification for a D/A converter is a
The point here is that the binary-weighted resistors
comparison between the actual output and the expected
produce binary-weighted currents which are summed
output. It is specified as a percentage of the full-scale
by the op amp to produce a proportional output voltage.
The binary word applied to the switches produces a pro-
portional output
voltage. Technically the output voltage VReF = 2.0 V dc
fl14 = /?15s I.Oka
is "digital" because it can only have certain fixed values
just as the display on a digital voltmeter can. However,
the output simulates an analog signal, so we refer to it
as analog Switch D3 in Figure 10-14 represents the
most significant bit, because closing it produces the
largest current. Note that since VRE] is negative, the out-
put will
go positive .is switches are closed.
As you see here, the heart of a D/A converter is a set of
binary-weighted current sources which can be switched
on or off according to a binary word applied to its in-
puts. Since
these current sources are usually inside an
IC. we don't need to discuss the different ways the
binary-weighted currents can be produced. As shown in
Figure 10-14, a simple op-amp circuit can be used to
convert the sum of the currents toa proportional voltage
if needed.

D/A CHARACTERISTICS AND SPECIFICATIONS

Figure I0-15shows (he circuit lor an inexpensive IC D/A


A2 A3 A4 A5 A6 A7 A8
converter with an op-amp circuit as a current-to-voltage 4 8 16 32 64 128 256
converter. We will use this circuit lor our discussion of
R\A OR Rn SO THAT Vn WITH ALL DIGITAL
D/A characteristics.
INPUTS AT HIGH LEVEL IS EQUAL TO 9 961 V
Ehe first characteristic ol a D/A converter to consider
is resolution. This is determined by the number of bits
,/ 2 V ,, ,n, / 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 1
Vo=lTn <5k™ { 2 + 4 + 8 + 16+ 32 + 64 + 128+ 256J
in the input binary word. A converter with eight binary
inputs such as the one in Figure 10-15 has 2* or 256
possible output levels, so its resolution is 1 part in 256.
As another example, a 12-bit converter has a resolution FIGURE 10-15 Motorola MC1408 »-bit D/A with current-to-
of I part in 212 or 4096. Resolution is sometimes ex- vi iltaee < onverter.

322 ( MAI' 11 R TEN


output voltage 01 current II .1 convertei has .1 full-scale some integrated-circuil amplilii connect the
output ol in V ,ui(l tO. 2 percent accuracy, then the output ol the 1) A convertei to the 1efei ene< inpi
maximum erroi for any output will be O.Ot unliable power supply, Ol Simply add tin
or 20 mV. Ideally 111*- maximum error foi .1 1 > A convertei current buffer circuit shown in Figure 10 I (Ho the out
should be no more than • l 2 ol the value ol the LSB put ol the I ) A, you have a powei supply whi< h you can
Another important specification foi .1 D/A convertei is \.n\ under program control fo determine the output
linearity. Linearity is a measure ol how much the out- voltage ol the IC under test as you vary its supply volt-
put rampdeviates from .1 straight line .is the convertei ige 1 onne< 1 the input ol an A I) converter to the IC out-
is stepped from 110 swit( Ins on to all switches on. Ideally put, -i\u\
connect the output ol the AD converter to an
the deviation ol the output from .1 straight line should input porl ol your microcomputer. You can then read in
be no greater than ! 1 2 ol the value ol the LSB to main- the value ol the output voltage on the IC.
tain overallaccuracy. Howevei . many 1> A converters are Another application you might use a D/A and a power
marketed which have linearit) errors greatei than that liultei loi is to vary the voltage supplied to a small rests
National Semiconductor, foi example, markets the tive healer under program control. Also, the speed of
DAC1020. DAC1021. DAC 1022 series ol 10 bit resolu- small dc 11lot 01s is piopoi tional to the aim 1111it ol I Lll Kill
tion converters. The linearity specification for the passed through them, so you could connect a small dc
DAC1020 is 0.05 percent, which is appropriate for a motor on the output ol the powei butter and control the
10-bit converter. The DAC 102 1 has a linearity specifica- speed ol the motor by the value you output to the 1) A.
tion0.10
ol percent and the I )A( 1022 has a specifica- Note that without feedback control the speed ol the
tion0.20
of percent. The question that may occur to you inoioi will vary it the load changes. Later we show you
at this point is. "What good is it to have a 10-bit con- how in add feedback control to maintain constant motor
verter
the iflineai ity is only equivalent to that ol an 8- or speed under changing loads
9-bit converter?" The answer to this question is that for So far we have talked about using an 8-bit 1) A with a
many applications the resolution given by a 10-bit con- microprocessor. Interfacing an 8-bit converter involves
verter
needed
is for small output signals, but it doesn't simply connect ing the inputs ol the converter to an out-
matter if the output value is somewhat nonlinear for put port,or for some D/As simply connecting the inputs
large signals. The price you pay for a D/A converter is to the buses as you would a porl device. Now, suppose
proportional not only to its resolution, but also to its that for some application you need 12 bits ol resolution,
linearity specification. so you need to interface a 12 bit converter. II you are
Still another D/A specification to look lor is settling working with a system which has an 8-bit data bus.
Lime. When you change the binary word applied to the your first thought might be to connect the lower eight
input of a converter, the output will change to the ap- inputs of the 12 bit converter to one output port and the
propriatevalue.
new The output, however, may over- upper four inputs to another port. You could send the
shootcorrect
the value and "ring" for a while before fi- lower 8 bits with one write operation, and the upper 4
nally settlingdown to the correct value. The time the bits with another write operation. However, there is a
output takes to get within ± 1/2 LSB of the final value is potential problem with this approach caused bv the
called settling time. As an example, the National time between the two writes. Suppose, for example, that
DAC1020 10-bit converter has a typical settling time of you want to change the output of a 12-bit converter from
500 ns for a full-scale change on the output. This speci- 0000 1111 11 1 1 to 0001 0000 0000. When you write the
fication
important,
is because if a converter is operated lower 8 bits, the output will go from 0000 1111 1 1 1 1 to
at too high a frequency, it may not have time to settle to 0000 0000 0000. When you write the upper 4 bits, the
one value before it is switched to the next. output will then go back up to the desired 0001 0000
0000. The point here is that for the tune between the
D/A Applications and Interfacing to two writes the output will go to an unwanted value. In
Microcomputers
D/A converters have many applications besides those I TO V
DEVICE
where they are used with a microcomputer. In a CONVERTER
UNDER
compact-disk audio player, lor example, a 13- or 14-bit TEST

D/A converter is used to convert the binary data read off


the disk by a laser to an analog audio signal. Most
speech-synthesizer ICs contain an D/A converter to con-
vert stored
binary data for words into analog audio sig-
nals. Here,
however, we are primarily interested in the ' VlUT

use of a D/A converter with a microcomputer.


The inputs of the D/A circuit IA1-A8) in Figure 10-15
can connected directly to a microcomputer output port.
As part of a program you can produce any desired volt-
age on
the output of the D/A. Here's some ideas as to
what you might use this circuit for.
As a first example, suppose that you want to build a
microcomputer-controlled tester which determines the
effect of power-supply voltage on the output voltage of FIGURE 10-16 High-power butter tor D/A output.

ANALOG INTtRF/U INC AND INDUSTRIAL CONTROL 323


many systems this could be disastrous. The cure lor this data bus. as shown in Figure 1017a. If. for example,
problem is to put latches on the input lines. The latches you want to connect up a DAC 1208 converter to an
can be loaded separately and then strobed together to SDK-86 board, you can simply connect the DAC 1208
pass all 12 bits to the D/A converter at the same time. data inputs to the lower 12 data bus lines, connect the
Many currently available D/A converters contain built- CS input to an address decoder output, connect the VVR1
in latches to make this easier. Figure 10-17a shows a input to the system WR line, and tie the VVR2 and XFER
block diagram of the National DAC1230- and DAC 1208- inputs to ground. The BYTE1/BYTE2 input is tied high.
type 12-bit converters. Note the internal latches and the You then write words to the converter just as if it were a
register. The DAC1230 series of parts has the upper 4 16-bit port. The timing parameters for the DAC 1208 are
input bits connected to the lower 4 bits so that the 12 acceptable for an 8086 operating with a clock frequency
bits can be written with two write operations from an of 5 MHz or less. For higher 8086 clock frequencies you
8-bit port or data bus such as that of the 8088 micro- would have to add a one-shot or other circuitry which
processor.
DAC1208
The series of parts has the upper inserts a WAIT state each time you write to the D/A.
four data inputs available separately so they can be con- Here's a few notes about the analog connections for
nected directly
to the bus in a system which has a 16-bit these devices.
These D/A converters require a precision voltage refer-
ence. The
circuit in Figure 10- 17b uses a - 10.000-V ref-
erence.D/AThe converters have a current output so we
DA I '<>:-: I i a: 09, DAC1210
use an op amp, as shown, to convert the output current
li U to a proportional voltage. A FET input amplifier is used,
D Q — because the input bias current of a bipolar input amp
D Q -~
might affect the accuracy of the output. The DAC 1208
D Q —
and DAC 1230 have built-in feedback resistors which
D Q H-
match the temperature characteristics of the internal
IJ Q —
current-divider resistors, so all you have to add exter-
D Q
nally
a 50-Si
is resistor for "tweaking" purposes. With a
D Q
-10.000-V reference as shown, the output voltage will
12-BIT
DAC be equal to (the digital input word/4096) > [+ 10.000 V).
REGISTER
Note that the D/A has both a digital ground and an ana-
D Q I
log ground. To avoid getting digital noise in the analog
D "-BIT q D Q
INPUT portions of the circuit, these two should be connected
D LATCH Q D Q
together only at the power supply.
D Q

A/D CONVERTER TYPES, SPECIFICATIONS,


SIGNA
:n BYTE
BYTE
1/
2 .
S" AND INTERFACING
FROM
A/D Converter Types
% '.NIiKLv
DECODER 3D-^ The function of an A/D converter is to produce a digital

^^-i-jizy word which represents


voltage or current.
the magnitude
The specifications
of some analog
for an A/D con-
verier are very similar to those for a D/A converter. The
resolution of an A/D converter refers to the number of
bits in the output binary word. An 8-bit converter, for
FULL-SCALE ADJUST
example, has a resolution of 1 part in 256. Accuracy and
linearity specifications have the same meanings for an
A/D converter as we described previously for a D/A con-
verter. Another
important specification for an A/D con-
verter
its isconversion time. This is simply the time it
takes the converter to produce a valid output binary
code for an applied input voltage. When we refer to a
converter as high-speed we mean it has a short conver-
sion time.
There are many different ways to do an A/D
conversion, but we only have space here to review three
commonly used methods, which represent a wide vari-
FORO I) 4095
ety conversion
of times.

PARALLEL COMPARATOR A/D CONVERTER

FIGURE 10-17 (a) National DAC1208 12-bit D/A input Figure 10-18 shows a circuit for a 2-bit A/D converter
block diagram showing internal latches, (b) Analog using parallel comparators. A voltage divider sets refer-
circuit connections ence voltages
on the inverting inputs of each of the com-

324 ( MAIM IK TIN


As soon as the output ol the Intcgratoi
mil i ovnlis below ground fh< i paratoi output will go
high, ["he comparatoi output being high enables the
AND gate aiid lets the I Mil/ clock into the countei
chain. After s e fixed numbei ol counts the control
circuiti") switches the input ol the integratoi to .i nega
I ive reference voltage a in I icscis the counters .ill to zero.
With a negative Inpul voltage the integratoi outpul will
ENCODING BINARY CODE ramp positive as shown in Figure 10 Hi/;. When the in-
GATES OUTPUT tegratoi outpul
crosses zero volts, tin comparator out
pol will (Imp low .mil shut oil the (link signal to the
counters. The number ol counts required foi tin- inte-
grator outpni
lo get back to zero is directly proportional
to the input voltage. For the circuil shown in Figure
Ki 19a, an input signal ol i 1 V, for example, produces a
count of l(i(i(i- Because the resistor and the capacitor on
the integrator arc used lor both the input voltage inte-
grate and
the reference integrate, small variations in
their value with temperature do not have any effect on
the accuracy ol Ihe conversion.

FIGURE 10-18 Parallel comparator A/D converter.


I MM

parators. The voltage at the top of the divider chain rep-


resents
full-scale
the value for the converter. The voltage
to be converted is applied to the noninverting inputs of
all of the comparators in parallel. If the input voltage on
a comparator is greater than the reference voltage on the
inverting input, the output of the comparator will go
high. The outputs of the comparators then give us a dig-
ital representation of the voltage level of the input sig-
nal. Withan input voltage of 2.6 V. for example, the out-
putscomparators
of A\ and A1 will be high.
The major advantage of a parallel, or flash, A/D is its
speed of conversion, which is simply the propagation
delay time of the comparators. The output code from the
comparators is not a standard binary' code, but it can be
converted with some simple logic The major disadvan-
tagea of
flash A/D is the number of comparators needed
to produce a result with a reasonable amount of resolu-
tion. The
2-bit converter in Figure 10-18 requires three
comparators. To produce a converter with N bits of reso-
lutionneed
you (2N - 1) comparators. In other words for
an 8-bit conversion you need 255 comparators, and for a
10-bit flash converter you need 1023 comparators.
Single-package flash converters are available from TRW
for applications where the high speed is required, but
they are relatively expensive. Devices are available which
can do an 8-bit conversion in 20 ns.

DUAL-SLOPE A/D CONVERTERS

Figure 10- 19a shows a functional block diagram of a


dual-slope A/D converter. This type of converter is often
used as the heart of a digital voltmeter because it can
io" n % o 1 'io °f
give a large number of bits of resolution at a low cost.
1 V/ms
Here's how the converter in Figure 10-19 works.
To start, the control circuitry resets all of the counters
to zero and connects the input of the integrator to the
input voltage to be converted. If you assume the input
voltage is positive, then this will cause the output of the FIGURE 10-19 Dual-slope A/D converter, (a) Circuit.
integrator to ramp negative as shown in Figure 10- 19b. (b) Integrator output waveform.

ANALOG INTERFACINGAND INDUSTRIALCONTROL 325


Complete slope-type A/D converters are readily avail- D/A converter is less than the input voltage, then the
ablesingle
in IC packages. One example is the Intersil comparator output will be high, which tells the SAR to
ICL7136 which contains all of the circuitry for a 3l/2- keep that bit on. When the next clock pulse occurs, the
digit A/D converter and all of the interface circuitry SAR will turn on the next-most-significant bit to the D/A
needed to drive a 3V2-digit LCD. Another example is the converter. Based on the answer this produces from the
Intersil ICL7135 which contains all of the circuitry for a comparator, the SAR will keep or reset this bit. The SAR
4'/2-digit A/D converter and has a multiplexed BCD out- proceeds in this way on down to the least-significant bit,
put. Note
that, because of the usual use of this type of adding each bit to the totai in turn and using the signal
converter, we often express its resolution in terms of a from the comparator to decide whether to keep that bit
number of digits. The full-scale reading for a 3 ' -digit in the result. Only 8 clock pulses are needed to do the
converter is 1999. so the resolution corresponds to actual conversion here. When the conversion is com-
about 1 part in 2000. A two-chip set, the Intersil plete binary
the result is on the parallel outputs of the
ICL8068 and ICL7 104-16, contains all of the circuitry SAR. The SAR sends out an end-of-conversion (EOC)
for a slope-type 16-bit binary output A/D converter. signal to indicate this. In the circuit in Figure 10-20 the
The main disadvantage of slope-type converters is EOC signal is used to strobe the binary result into some
their slow speed. A 41 -digit unit may take 300 ms to do latches where it can be read by a microcomputer. If the
a conversion. EOC signal is connected to the start-conversion (SO
input as shown, then the converter will do continuous
conversions. Note in the circuit in Figure 10-20 that the
SUCCESSIVE-APPROXIMATION A/D CONVERTERS
noninverting input of the op amp on the 1408 D/A con-
Figure 10-20 shows a circuit for an 8-bit successii>e- verter
connected
is to -5 V instead of to ground. This
approximation converter which uses readily available shifts the analog input range from -5 V to +5 V instead
parts. The heart of this converter is a successive- of 0 V to + 10 V so that sine-waves and other ac signals
approximation register (SAR) such as the MCI 4549 can be input directly to the converter to be digitized.
which functions as follows. The National ADC 1280 is a single-chip 12-bit succes-
On the first clock pulse at the start of a conversion sive-approximation
which
converterdoes a conversion
cycle the SAR outputs a high on its most-significant bit in about 22 /xs. Datel and Analog Devices have several
to the MC 1408 D/A converter. The D/A converter and the 12-bit converters with conversion times about 1 ^is.
amplifier convert this to a voltage and apply it to one Several commonly available successive-approximation
input of a comparator. If this voltage is higher than the A/D converters have analog multiplexers on their in-
input voltage on the other input of the comparator, the puts. The
National ADC0816, for example, has a 16-
comparator output will go low and tell the SAR to turn input multiplexer. This allows one converter to digitize
off that bit because it is too large. If the voltage from the any one of 16 input signals. You specify the input chan-

161 SERIAL
MR SC OUTPUT

QO MC'4549 Q7 END OF CONVERSION

MSB LSB
llS.i (141(131(12

LATCHES DATA
74LS374 OUTPUTS

MV-T-

moi [til

(161114)(15) (1)
,^)|J > > NC

50 pF j> (»2.5kJ2
2 5kn
6 4
+ 5 V -15 V

FIGURE 10-20 Successive-approximation A/D converter circuit.

326 CHAPTERTEN
ncl you wan! to digitize with a 1 bit addi ess you apply to Ing scheme has the advantage thai tin 2 complemenl
the address inputs oi the device. An A Dconvertei with a representation can he produced by simply inverting the
iiiultiplcxti on Ms inputs is often called .1 data acquisi most significant bit. Some bipolai converters output
tlon system or DAS Later In this chapter we show an the digital value directly in 2's complemenl form.
application ol .1 DAS in .1 factory control system.
Before we go on to discuss A 1) interfacing, we need to
make .1 few comments aboul common A D output codes.
Interfacing Different Types of A/D Converters to
Microcomputers
\ D OUTI'UI ( ODIS
INTERFACING IO PARALLEL-COMPARATOR A/D
F01 convenience in different applications, AD convert- ( ONVERTI RS
ers areavailable with several different, somewhat inn
In any application where a parallel comparator convertei
fusing, output codes. The best way to make sense out ol
is used, the converter is most likely going to be produc
these different codes is to see them .ill together with rep
Ing digital output values much faster than a micro< om
resentative values .is shown in Figure 10 21. The values
puter could possibly read them in. Therefore, separate
shown here are for an 8 bil converter, but you can ex-
Circuitry is used to bypass the microprocessor and load
tend themto any numbei ol bits
a set ol samples from (he converter directly into a series
F01 an A 1) converter with only a positive input range
of memory locations. The microprocessor can later pet
[unipolar) a straight binary code or inverted binary code
form the desired operation on the samples. Bypassing
is usually used. If the output oi an A D converter is going
Ihi' microprocessor in this way is called direct memory
to drive a display, then it is convenient to have the out-
access or DMA. The basic principle of DMA is that an
put codedin BCD. For applications where the input
external controller IC tells the microprocessor to float its
range of the converter has both a negative and a positive
buses When the microprocessor does this, the DMA
range [bipolar] we usually use offset-binary coding. As
controller takes control of the buses and allows data to
you can see in Figure 10-21 the values of 00000000 to
be transferred directly from the A/D converter to sui <es
11111111 are simply shifted downward so that
sive memory locations. We discuss DMA in detail in the
00000000 represents the most negative input value and
next chapter.
10000000 represents an input value of zero. This cod-
INTERFACING TO SLOPE-TYPE A/D CONVERTERS
UMIPOLAR BINARY CODES

111 INVERTED
Most of the commonly available slope-type converters
COMPLEMENTARY INVERTED
VALUE
VOLTS BINARY
BINARY BINARY
COMPLEMENTARY were designed to drive seven-segment displays in. for
FULL [BIN) BINARY
SCALE
(C6I (IB)
(ICBI example, a digital voltmeter. Therefore, they usually
•FS 1 LSB 99609 1111 1111 0000 0000
output data in a multiplexed BCD or seven-segment
1000 0000
5 0000
4 9609 0111 1111
0111 1111
form. Figure 10-23 shows how you can connect the mul-
+V4FS -1 LSB 1 000 0000
• 1 LSB 0 0391 0000 0001 1111 1110 tiplexedoutputs
BCD of an inexpensive 3'/ij-digit slope
ZERO 0 0000 0000 0000 1111 11 11 0000 0000 1111 1111 converter, the MC 14433. to a microprocessor port. In
1 LSB -0 0391 0000 0001 tin 1110 the section of the chapter where Figure 10-23 is located,
- . FS* 1 LSB -4 9609 01 11 1111 1000 0000
FS -5 0000 10000000 01 11 11 1 1
we use this converter as part of a microcomputer-based
-FS+1 LSB -9 9609 1111 1111 0000 0000 scale. The BCD data is output from the converter on
lines Q0-Q3. A logic high is output on one of the digit
UNIPOLAR BINARY CODED DECIMAL CODES
strobe lines. DS1-DS4, to indicate when the BCD code
COMPLEMENTARY INVERTED INVERTED
10 BINARY
BINARY BINARY COMPLEMENTARY
for the corresponding digit is on the Q outputs. The
VOLTS CODED
VALUE
FULL DECIMAL
CODED CODED BINARY CODED MC 14433 converter shown in Figure 10-23 outputs the
DECIMAL DECIMAL DECIMAL
SI AL! (BCD)
ICBC0) IIBCD) 1ICBCD1 BCD code for the most-significant digit, and then out-
* FS -1 LSB 99 1001 1001 0110 0110 putshigh
a on the DS1 pin. After a period of time it
+ ', FS 50
0 1
0101 0000 1010 11 11
1 1 1 1 1110
outputs the BCD code for the next-most-signilieant
&f1 LSB 0000 0001
digit and outputs a high on the DS2 pin. After all 4 digits
ZERO 00 0000 0000 1111 1 1 11 0000 0000 1 1 1 1 1111
have been put out, the cycle repeats.
-1 LSB -0 1 0000 0001 1111 1110
-•; FS -5 0 0101 0000 1010 till To read in the data from this converter, the principle
-FS+1 LSB -9 9 1001 1001 011001 10
is simply to poll the bit corresponding to a strobe line
until you find it high, read in the data for that digit, and
BIPOLAR BINARY CODES
put the data in a reserved memory location for future
COMPLEMENTARY
10 VOLTS OFFSET
OFFSET
TWO'S reference. After you have read the BCD code for one
VALUE FULLSCALE BINARY COMPLEMENT
RANGE I0B1
BINARY
(TO digit, you poll the bit which corresponds to the strobe
IC0B1
line lor the next digit until you find it high, read the
+ FS 50000
+ FS-1 LSB 4.9609 1111 1111 0000 0000 0111 1111 code for that digit, and put it in memory. Repeat the
+ 1 LSB 0 0391 nniuinni 01 1 1 1110 0000 0001
process until you have the data for all of the digits. The
ZERO 0.0000 11.11'i.i ni 0111 1 11 1 0000 0000
A/D converter in Figure 10-23 is connected to do contin-
-1 LSB -0 0391 01 11 1111 1000 0000 1111 1111
-FS+1 LSB -4 9609 0000 0001 1111 1110 1000 0001
uous conversions,so you can call the procedure to read
-FS -5.0000 0000 0000 1111 1111 1000 0000 in the value from the A/D converter at any time.
Frequency counters, digital voltmeters, and other test
FIGURE 10-21 Common A/D output codes. instruments often have multiplexed BCD outputs avail-

ANALOC INTERFACING AND INDUSTRIAL CONTROL 327


able on their back panel. With the connections and pro- first instrument we have chosen is a "smart" scale such
cedure
have
we just described you can use these instru- as you might see at the checkout stand in your local
ments
input
to data to your microcomputer. grocery store.

INTERFACING A SUCCESSIVE-APPROXIMATION
A/D CONVERTER Overview of Smart Scale Operation
Successive-approximation A/D converters usually have Figure 10-22 shows a block diagram of our smart scale.
outputs lor each bit. The code output on these lines is A load cell converts the applied weight of, for example, a
usually straight binary or offset binary. You can simply bunch of carrots to a proportional electrical signal. This
connect the parallel outputs of the the converter to the small signal is amplified and converted to a digital value
required number of input port pins and read the con- which can be read in by the microprocessor and sent to
verter output
in under program control. In addition to the attached display. The user then enters the price per
the data lines, there are two other successive approxi- pound with the keyboard and this price per pound is
mationconverter
A/D signal lines you need to interface shown on the display. When the user hits the compute
to the microcomputer for the data transfer. The first of key on the keyboard, the microprocessor multiplies the
these is a START CONVERT signal which you output from weight times the price per pound and shows the result
the microcomputer to the A/D to tell it to do a conversion on the display. After holding the price display long
for you. The second signal is a STATUS signal which the enough for the user to read it. the scale goes back to
A/D converter outputs to indicate that the conversion is reading in the weight value and displaying it. To save
complete and that the word on the outputs is valid. Here the user from having to type the computed price into the
are the program steps you use to get a data sample from cash register, an output from the scale could be con-
the converter. nected directly
into the cash register circuitry. A speech
First you pulse the START CONVERT high for a mini- synthesizer, such as the Votrax SC-01A we described in
mum100
of ns. You then detect the STROBE signal Chapter 9, could be attached to verbally tell the cus-
going low on a polled or interrupt basis. You then read tomerweight,
the price per pound, and total price.
in the digitized value from the parallel outputs of the Smart scales such as this have many applications
converter. In a later section of this chapter we show a other than weighing carrots. A modified version of this
detailed example of this for the ADC0808 converter. scale is used in company mail rooms to weigh packages
If you are working with a personal computer such as and calculate the postage required to send them to dif-
the IBM PC. there are available a wide variety of multi- ferent postal
zones. The output of the scale can be con-
channeland
A/D D/A converter boards which plug di- nected
a topostage meter which then automatically
rectly into
the bus connectors of these machines. prints out the required postage sticker. Another appli-
cationsmart
of scales is to count coins in a bank or
gambling casino. For this application the user simply
enters the type of coin being weighed. A conversion fac-
A MICROCOMPUTER-BASED SCALE tor in
the program then computes the total number of
coins and the total dollar amount. Still another applica-
So far in this book we have shown you how a lot of the tiona ofscale such as this is in packaging items for sale.
pieces of a microcomputer system function. Now it's Suppose, for example, that we are manufacturing
time to show you how some of these pieces are put to- woodscrews, and that we want to package 100 of them
gether
maketo a microcomputer-based instrument. The per box. We can pass the boxes over the load cell on a

MICROPROCESSOR

KEYBOARD

POWER
SUPPLY

FIGURE 10-22 Block diagram ot microcomputer-based smart scale

328 CHAPTERTEN
conveyor belt and fill them from .1 chute until the
weight, and therefore the count, reaches some entered
value II if pom! here is thai the combination ol Intelll
gence and some simple interface circuitry gives you an
Instrument with as many uses as youi Imagination can
come up with

LOADCELl |*15 V
BALANCE
Smart Stale Input Circuitry
Figure 1(> 10 shows .1 picture oi the [Yansducers, Inc.
Model C462 10#-10P1 strain-gage load cell we used
when we built this stale. We added a piece ol plywood to
the top of the load cell to keep the carrots from falling
off. This load cell has an accuracy ol about 1 pari in
1000 01 0.01 lb over the 0- to 10-lb range foi whii h it
was designed.
As shown in Figure 10-23. the load cell consists of
lour 350-fl resistors connected in a bridge configura-
tion.
stable
A 10.00-V excitation voltage is applied to the
top ol the bridge. With no load on the cell, the outputs
from the bridge are at about the same voltage, 5 V. When
a load is applied to the bridge, the resistance ol one of
the lower resistors will he changed. This produces a
small differential output voltage from the bridge. The
maximum differential output voltage for this 10-lb load
8255
cell is 2 mV per volt of excitation. With a 10.00 V excita- (24)
tionshown,
as the maximum differential-output voltage
03 (23) - PA3
is then 20 mV. RIO
470 KS2 Q2 (22) — PA2
To amplify this small differential signal we use a Na-
tional LM363 instrumentation amplifier. This device Q1 (21) — PA1

contains all of the circuitry shown for the instrumenta- Q0 (20) PAO
tion amplifierin Figure 10-lh. The closed-loop gain of CI 0 1 fiF
DS1 (19) — PA4
the amplifier is programmable for fixed values of 5, 100,
DS2 (18) — PA5
and 500 with jumpers on pins 2. 3. and 4. We have
jumpered it for a gain of 100 so that the 20-mV maxi- DS3 (17) PA6

mum signal from the load cell will give a maximum volt- C2xi0-' A-F
DS4 (16) — PA7
age 2.00
of V to the A/D converter input. A precision
MC14433
voltage divider on the output of the amplifier divides
this signal in half so that a weight of 10.00 lb produces
an output voltage of 1.000 V. This sealing simplifies the
display of the weight after it is read into the microproc-
essor. 0.1
The -/uF capacitor between pins 15 and 16 of
the amplifier reduces the bandwidth of the amplifier to
about 7.5 Hz. This removes 60 Hz and any high-
frequency noise that might have been induced in the FIGURE 10-23 Circuit diagram for load-cell interface
signal lines. circuitry and A/D converter for smart scale.
The MCI 4433 A/D converter used here is an inexpen-
sive dual-slopedevice intended for use in 3>/2-digil digi-
tal voltmeters, etc. Because the load cell changes slowly,
counts. As we described in a previous section, the out-
a fast converter isn't needed here. The voltage across an
put from this converter is in multiplexed BCD form.
LM329 6.9-V precision reference diode is amplified by
IC4 to produce the 10.00-V excitation voltage for the
load cell, and a 2.000-V reference for the A/D. With a
2.000-V reference voltage, the full-scale input voltage for An Algorithm for the Smart Scale
the A/D is 2.000 V. Conversion rate and multiplexing Figure 10-24 shows the flowchart for our smart scale.
frequency for the converter are determined by an inter- Note that, as indicated by the double-ended boxes in the
nal oscillator and Rl 1. An Rl 1 of 300 k£i gives a clock flowchart, most major parts of the program are written
frequency of 66 kHz, a multiplex frequency of 0.8 kHz. as procedures. The output of the A/D is in multiplexed BCD
and about four conversions per second. Accuracy of the form as we described in the section on slope-converter
converter is ±0.05 percent and ± 1 count, which is com- interfacing. Therefore, each strobe has to be polled until
parable
the toaccuracy of the load cell. In other words, it goes high, and then the BCD code lor that digit can be
the last digit of the displayed weight may be off by 1 or 2 read in.

ANALOG INTERFACING AND INDUSTRIAL CONTROL 329


it is assumed that the entered price per pound is cor-
rect, and
the program goes on to compute the total
price.
Computing the price involves multiplying the weight
in BCD form times the price per pound in BCD form. It
is not easy to do a BCD % BCD multiply directly, so we
took an alternate route to get there. Both the weight and
the price per pound are converted to binary. The two
binary numbers are then multiplied. The binary result
of the multiplication is then converted to BCD. rounded
off to the nearest cent, and displayed in the data field.
I i Hi VI lil
The letters "Pr" are displayed in the address field. After a
PRICE/LB
TO BINARY few seconds the program goes back to reading and dis-
playing weight
over and over, until a key is pressed.
DUMB
SCALE
MODULE CONVERT
WEIGHT
TO BINARY
The Microprocessor-based Scale Program
Figure 10-25 shows the complete program for our
MULTIPLY microprocessor-based scale. It is important for you not
WEIGHT %
PRICE/LB
to be overwhelmed by a mullipage program such as this.
If you use the 5-minute rule, and work your way through
DISPLAY "SP." this program one module at a time, you should pick up
FOR
CONVERT some more useful programming techniques and proce-
SELLING PRICE
TOTAL PRICE
duresyour
for "toolbox."
TO BCD
Three 4-byte buffers set up at the start of the program
are used to store the unpacked BCD values of the
DISPLAY KEY ROUND OFF weight, the price per pound, and the computed total
PRESSED TOTAL PRICE TO
price. These values will be used by the display proce-
NEAREST CENT
dure. Instead
of rising the display procedure we showed
you in Figure 9-33, we used here a more versatile proce-
dure which
can display a few letters as well as hex digits.
READ DISPLAY
GET KEYBOARD TOTAL PRICE The SEVEN SEG table in the data segment contains the
PRICE/LB seven-segment codes for hex digits and these letters. In
MODULE
the display procedure you will sec how these codes are
accessed.
WAIT
After initializing everything the program polls the
3 SECONDS
digit strobe for the most-significant digit from the A/D
converter. Since this A/D converter is a 3V2-digit unit,
the MSD can only be a 0 or a 1 . The value for this digit is
sent m the third bit (bit 2) of the 4-bit digit read in. If
this bit is a one. then 01 is loaded into the buffer loca-
tionthe
II bit is a 0. then the value which will access the
seven-segment code for a blank ( 14HI is loaded into the
buffer location. Each of the other digit strobes is then
polled in turn and the values for those digits read in.
FIGURE 10-24 Flowchart for smart-scale program. When all of the BCD digits for the weight are in the
WEIGHT BUFFER, the display procedure is called to
show the weight on the address field.
The BCD values read in from the converter are stored To use this display procedure you first load a 0 or a 1
in lour memory locations. A display procedure accesses into AL to specify data field or address field and a 1 or a
these values and sends them to the address field display 0 in AH to specify a decimal point in the middle of the
cil the SDK-86. The letters "Lb" are displayed in the data display, or no decimal point. You then load BX with the
field. Alter the weight is displayed, a check is made to offset of a buffer containing codes for the digits to be
see II any keys have been pressed by the user. If a key displayed. A program loop in the display procedure uses
has been pressed, the letters "SP," which represents the XLAT instruction and the SEVEN SEG table to con-
selling price, are displayed in the address field. Keycodes vi it ihese codes to the required seven-segment values
arc read from the 8279 as entered and displayed on the and send the values to the 8279 display RAM. Note how
data field display. Keys can be pressed until the desired a 1 is ORed into the seven-segment code for digit 3 when
price per pound shows on the display The price per a t is in AH passed to the procedure. For displaying the
pound entered by a user is assembled in a series of weight, BX is simply loaded with the offset of
memory locations. When a nonnumeric key is pressed. WEIGHT BUFFER, AL loaded with 01 to display the

330 CHAI'UR TF.N


Page ,132
8096 PROGRAMFOR SMART SCALE
PORTS: Uses input port P1A - FFF9H
[PROCEDURES:
READ.KEY, DISPLAY,PACK EXPAND,
CQNVERT26IN,
BINCVT

DATA HERE SEGMENT WORD PUBLIC

he1ght_buffer 4 DUP(0) Space Tor unpacked BCDweight


sell.price l [HjPUli Space lor unpacked price/pound
price'.total 4 DUP(0) Space tor total price to display
binary
jei6ht 0 Space for converted weight
LB 0BH, 10H, MH, 14H, b, L, blank, blank
S P 12H, 11H, 14H, 14H, P, S, blank, blank
Pfi 13H, 12H, 14H. 14H r, P, bblank, blank

SEVENSE6 DB 3FH, 06H, 5BH, 4FH, &6H,6DH, 7DH, 07H


; 0 12 3 4 5 6 7
DB 7FH, 6FH, 77H, 7CH, 39H, 5EH. 79H, 71H
; 8 ? A b C d E F
DB 38H, 6BH, 73H. 50H, 00H, 76H
: L S P r blank H

DATA HERE ENDS

STACK.HERE
SEGMENT
DH 40 BUPi0)
STACK.TOP LABEL WORD
STACK HERE ENDS

CODE.HERE SEGMENT WORD PUBLIC


ASSUMECS;CODE.HERE, DS:BATA.HERE,
SS:STACK_HERE
unitialize data & stack segments
START: MOV AX, DATA_HERE
MOV DS, AX
MOV AX, STACKHERE
MQV SS, AX
MOV SP, OFFSETBTACKJOP
;8279 initialized at power-up of BDK-86for 8 character display, left entry
jencoded scan, 2-key lockout,
MOV DX, 0FFEAH ; point at 8279 control address
MOV AL, 00H ; control word for above conditions
OUT DX, AL ; send control word
MOV AL, 00111000B ; clock word for divide by 24

OUT DX, AL
MOV AL, 11000W00B ; Clear display character is all 0's
OUT DX. AL

iDusb scale start


RBWT: MOV CX, 04H i Zero out weight buffer
MOV BX, OFFSETHEIGHT.BUFFER
NEXT!: MOV BYTEPTRCBX],00H
INC BX
LOOP NEXT!
MOV CX, 04H ; Zero out price/pound buffer

FIGURE 10-25 Assembly language program for smart scale.

ANALOG INTERFACING AND INDUSTRIAL CONTROL 331


MDV B!E,OFFSETSELL.PRICE
NEXT2: MOV BYTEPTRCBX3, 0t^H
INC BK
LOOP NEXT2
; Get we ight f -ois A/D converter and displa1
NOV BX, OFFSETWEIGHTBUFFER+3 ; MSB Position in weight buffer
Hi]'; DX, 0FFF9H Point at A/D port
03!: IN AL, DX ; Read byte from A/D
and AL, !?H ; Check for MSBstrobe high
n DS1 ; Loop till high
IN AL, DX ; P?ac MSD data froa A/D
AND AL, 0FH ; Mask strobe bits
CUP AL, 04H ; See if MSD in bit 3 is a one
JE L0AB1 ; Yes, go load 01H in buffer
MQV BYTEPTREBX],14H ; No, load code for blank:
JMP NXTCHR
LOAD!; MOV BYTEPTREBX],0!H
NXTCHR: DEC BX ; Point to next buffer location
BS2: IN AL, DX ; Poll for digit 2 strobe
AND AL, 20H
D32
[N AL, DX ; Read digit 2 from A/D
AND AL, FH ; Mask strobe bits
HOV [BX], AL j Digit 2 BCD to buffer
DEC &S ; Point at next buffer location
D33; IN AL, m ; Pol! for digit 3 from A/D
AND AL, 40H
% JZ 053
IN AL, DX ; Read digit 3 from A/D
AND AL, 0FH ; Mask strobe bits
HOV [BX],AL ; Digit 3 to buffer
;,F«- BX ; Point to next buffer location
D34; [N AL, BX ; Poll for digit 4 (LSDi
AND AL, 80H
33 DS4
IN AL, DX ; Read digit 4 froa A/D
AND AL, 0FH ; Mask strobe bits
Mf!1,' [BX], AL ; Digit 4 BCDto buffer
iDispla y wen ht on address field of SDK-8
MOV BX, OFFSET WEIGHTBUFFER j Point at stored weight
".[:. AL, 01H ; Specifies address field
MOV AH, ?1H ; Specifies decimal point
CALL DISPLAY
HOV BX, OFFSETLB ; Point at Lb string
MQV AL, 00 ; Specifies data field
HQ\J AH, 00 ; Specifies no deciaal point
CALL DISPLAY
; Check ifkey has been pressed
MOV DX, 0FPEAH ; Point at B279 status address
IN AL, DX ; Read 827? FIFO status
AND AL, 01H j See if F I FO has keycode
JN2 BETKEY ; Yes, go read it
JMP rdut ; No, go get weight and display
BETKEY: MOV AL, 01000000B ; Control word for read FIFO
OUT DX, AL ; Send to 327?

I ICURI 10-25 (continued)

332 C HAI'TER TEN


NQV DX, 0PFE8H Point at 8279 data address
IN ftL, DX Read code from FIFO
[KF AL, 09H Check if legal keycode(nunber)
J BE DK Go on if below or equal '
jflf RDW1 Else ignore, read Height again

;Read in and display price/pound

0!. : MOV BX, OFFSET SELL.PRICE Point at price per pound buffer
MOV [BX], AL Keycode to buffer
10 AL, ii Specify data field for display
»'% ', AH, 01 Specify decimal point
CALL DISPLAY
HQ\ BK, OFFSET B F Point at SP string
MOV AL; 01 Specify address field
MOV AH, 00 Specify no decimal point
CALL DISPLAY
NXTKEY: CALL READ.KEY Wait for next keypress
CMP AL, 0<?H See if more price or command
JA COMPUTE Go compute total price
hc!; BX, OFFSETSELL PRICE Point at price per pound buffer
MOV CL, [BX+2] Shift contents of buffer one
MOV [BX+3], CL position left and insert new
MOV CL, [BX+11 keycode
MOV EBX+2],CL
MOV CL, [BXl
Hh': CBX+1], CL
NOV [BX], AL
NOV AL, 00 Specify data field
MOV AH, 01 Specify decimal point
CALL DISPLAY
J MP NXTKEY Keep reading and shifting keys
until command key pressed
; compute total price

COMPUTE;
MQV BX, OFFSETHEIGHTJLIFFER ; Point at weight buffer for pack
CMF BYTEPTRCBX+33,14H See if MSDof weinht - 9
JNE NOTZER
M.J'J BYTEPTRCBX+33,
00 Yes, load 0 in place of blank code
NOTZER; CALL PACK Pack BCDweight into word
CALL CDNVERT2BIN Convert to 16 bit binary in A*
MOV BINARYJEIGHT,AX and save
MOV BX, OFFSETSELL.PRICE Point at price per pound for pack
CALL PACK Pack BCDprice into AX for convert
CALL C0NVERT2BIN Convert price to lfc-bit binary in AX
HUL BINARY
JIEIGHT Price per pound in AX » binary weight
total price result in DX:AX
MOV BX, A* Prepare for convert to BCD
CALL BINCVT Packed BCDprice result in DX: BX

jround off price to nearest cent and display

CMP BL, 49H ; Carry set if BL >49H


MOV AL, 00 ; Clear AL, keep carry

FIGURE 10-25 (continued)

ANALOG INTERFACINGAND INDUSTRIALCONTROL 333


ADC AL, BH Add any carry to next digit
DAA Keep in BCDformat
MOV BL, AL Save lower two digits of price
MOV AL, 00 Clear AL, save carry
ADC AL. PL Propagate carry to upper digits
DAA Keep in BCDform
MOV AH. AL Position upper digits lor EXPAND
HOV AL, BL Position lower digits for EXPAND
NOV BX, OFFSETPRICEJOTAL Point at buffer for expanded BCD
CALL EXPAND Unpack BCDfor DISPLAYprocedure
MOV AL, 00 Display total price on data field
MOV AH, 01 with decinal point
CALL DISPLAY
MOV BX, OFFSETPR Point at price/lb string
MOV AL, 0! Display in address field
MOV AH, 00 without decimal point
CALL DISPLAY
; del ay a few seconds
HOV CX.0FFFFH Delay a few seconds
CNTDNI:MOV BX, 0?«AH
CNTDN2: DEC B*
%M CNTDN2
LOOP CNTDNI
;go read next weight
JMP RDWT ; Jump back to dumb scale
;tIItl»iiMIIItilttitti«tIt|J»iHHmt mmmmmmmmmmt
liiiiiiiiiUi procedures used in smart scale prograis immmmttt

PROCEDUREREAD KEY
ABSTRACT reads the SDK-86 keyboard - procedure polls the status register
of the 8279 on the SDK-86 board until it finds a key pressed:
It then reads the keypressed code from the FIFO RAMto AL and exit;
^REGISTERS: Destroys AL - returns with character read in AL

READJiEY PRQC NEAR


PUSH DX
MOV DX, 0FFEAH j point at 8279 control address
NO.KEY:IN AL, DX ; get FIFO status
AND AL, 00000001B ; mask all but LSB, high if key in FIFO
JZ NO.KEY ; loop until a key is pressed
HOV AL, 01000000B ; control word for read FIFO
OUT DX, AL ; send control word
MOV DX. 0FFESH ; point at 8279 data address
IN AL, DX ; read character in PIFO ran
POF DX
RET
READ KEY ENDP

8086 PROCEDURE called DISPLAY


ABSTRACT;This procedure displays characters on the SDK-86 display
The data is sent to the procedure in the following Banner:
AL=0 for data field
AL-1 for address field
AH-0 for no decimal point
; AH-! for decimal point between second i third digit

FIGURE 10-25 {continued)

334 CHAPTER TEN


; BX=offset of buffer containing 7-seq codes of the 4 characters to be displayed

DISPLAY PROC NEAR


PUSHF save flags and registers
PUSH ;,»

PUSH BX
PUSH DJ
PUSH DX
PUSH SI
m DX, 0FFEAH point at 8279 control address
[MP AL, 0«H see if data field required
n DATFLD ves, load control word for data field
MOV AL. 94H no, load address-field control word
JHP SEND go send control word
DATFLD: MOV AL, 90H load control word for data field
SEND: OUT DX, AL send control word to 8279
MOV CL, 04H counter for number of characters
HOV si, bx Free BX for use with XLAT
HOV BX, OFFSETSEVENSEE pointer to seven-segment codes
MOV DX, 0FFE8H point at 8279 display RAM
AGAIN: MOV AL. [SI] Set character to be displayed
XLATB translate to 7-seg code
CMP CL, 02H see if digit that gets decimal point
JNE MORE no, go send digit
C«F AH, «1H yes, see if decimal point specified
JNE MORE no, go send character
OR AL, 80H yes, OR in decmal point
MORE: OUT DX, AL send seven seg codeto 8279 display RAM
INC SI Point to next character
LOOP ASAIN until all four characters sent
POP SI
POP DX restore all registers and flags
PDF [i
POP BX
POP „i

PQPF
RET
DISPLAY ENDP

;8«86 PROCEDURE
PACK
; ABSTRACT:
This procedure converts four unpacked BCDdigits pointed to by
; BXto four packed BCDdigits in AX
; DESTROYS; AX

PACK PROC NEAR


PUSHF save flags and registers
PUSH BX
PUSH cx
NOV AL, [BX] first BCDdigit to AL
NOV CL, 04H counter for rotate
SOL BYTE PTRIBX+1], CL position second BCDdigit
ADD AL, [BX+1] first 2 digits in AL
NOV AH, [BX+2] third digit to AH
POL BYTE PTREBX+3] n position fourth digit
ADD AH, [BX+3] second two digits now in AH

FIGURE 10-25 (continued)

ANALOG INTERFACING AND INDUSTRIAL CONTROL 335


PHP

POP
PQPF
RET
PACK ENDP

;80B6 PROCEDURE
EXPAND
; ABSTRACT: This procedure expands a packed BCDnumber in AX
; to 4 unpacked BCDdigits in a buffer pointed to by BX

EXPAND PROC NEAR


PUSHF
PUSH A<
PUSH BX
PUSH CX
NOV [8X],AL aove first 2 BCD digits to buffer
AND BYTEPTR[BX3,0FH eask off upper digit
MOV CL, 04H counter for rotates
ROR AL, CL position digit 2 in low nibble
AND AL, 0FH Bask upper nibble
m\ [BX+1], AL digit 2 to buffer
MOV [BX+2], AH second 2 BCDdigits to buffer
m BYTEFTR[BX+2],0FH iiask off upper digit
ROR AH, CL position digit 4 in low nibble
AND AH, 0FH mask upper nibble
H!;V tBX+3], AH digit 4 to buffer
PDF CX
pr,P B>
POP AX
POPF
RET
XPANDENDP

PROCEDUREC0NVERT2BIN
This procedure converts a 4 digit BCDnumber in
the AXregister into its BINARY(HEX) equivalent.
returns the result in the AXregister
;SAVES : FLAGregister, BX, DX, CX, Di
DESTROYS : AXregister
THOU EQ1 3EBH im - 3E8H
C0NVERT2BIN PROC NEAR
PUSHF save registers
PUSH B)
PUSH BJ
PUSH CX
PUSH DI
MOV BX, AX copy number into BX
nv- AL, AH place for upper 2 digits
MOV BH, BL place for lower 2 digits
split up numbers so that we have one digit in each register
MOV CL, «4 nibble count for rotate
POP AH, CL digit 1 in correct place
ROR BH, CL digit 3 in correct place
ftND AX, 0F0FH
AND BX, 0F0FH flask upper nibbles of each digit

FIGURI l()-Jr> (continued)

336 CHAIMIR TIN


; copy AX into CX so that can use AX for multiplication
MOV CX, AX
mov ax, mm
; now multiply each number by its place value
MOV AL, CH multiply byte in AL I word
NOV DI, THOU no immediate multiplication
MUL DI digit 1 t 1000
; result in DX and AX, because BCD digit will not be greater than 9
; the result will only be in AX
; zero DX and add BL because that digit needs no multiplication for
; place value. Then add the result in AX for digit 4
MOV DX, mm
ADD DL, BL ; add digit !
ADD DX, AX ; add digit 4
; continue with multiplications
MOV AX, M64H ; byte » byte result in AX
MUL CL ; digit 2 t \M
ADD DX, AX ; add digit 3
MQV ax, mm ; byte 1 byte result in AX
NUL BH
ADD DX, AX : add digit 2
MOV AX, DX ; put result in correct place
POP DI
POP CX
PDF DX ; restore registers
POP BX
POPF
RET
DNV
ERT2BIN ENDP

9986 PROCEDUREBINCVT
ABSTRACT: Converts a 24-bit binary number in DL and BX to
packed BCD equivalent in DX:BX
INPUTS: DL, BX - 24 BIT BINARY NUMBER
OUTPUTS: DX, BX - PACKEDBCD RESULT
CALLS: CNVT1
DESTROYS: DX and BX

BINCVT PROC NEAR


PUSHF i save registers and flags
PUSH AX
PUSH CX
MOV DH, 19H bit counter for 24 bits
CALL CNVT1 produce 2 LS BCD digits in CH
MOV CL, CH save in CL
MOV DH, 1<?H bit counter for 24 BITS
CALL CNVT1 produce next 2 BCDdigits in CH
PUSH CX save lower four BCDdigits on stack
MOV DH, !9H bit counter for 24 bits
CALL CNVT1 produce next two BCDdigits in CH
MOV CL, CH position in CL
MOV DH.19H set bit counter for 24 bits
CALL CNVT1 produce last two BCDdigits in CH
MOV DX, CX position 4 MS BCDDIGITS for return
POP BX ; 4 LS BCDdigits back from stack for RET

FIGURE 10-25 (continued)

ANALOG INTERFACING AND INDUSTRIAL CONTROL 337


POP CJ
pnp A:

pnpF
RE'
B1NCV- E'.::

; 3336 PROCEDL
CNv'Tl C-X NEAP
KOR ftL, ftL clear AL and carry as workspace
NOV ;H, Al clear CH
CNVT2: »!" ftL, ftL clear AL and CARRY
DEC DH decresent bit counter
JNZ do all bits
RET cone if DH down to zero
CONTINUE:
RCL BX, 1 BX left one bit, USB to carry
RCL DL; 1 USB froi BX to LSB of DL, *SB of DL to carry
NO ftL, CH aove BCD digit being built to AL
BDC ftL, ftL double AL and add carry froi DL shift
OAfl keen result in BCD fori
1:j. CH, ftL put back in CH for next tise through
JNC CNVT2 no carry frog DAA, continue
ADC BX, 00S3H if carry, propogate to BX and DL
ADC DL, MM for future tens
3HP CNVT2 continue conversion
ENDP

CODE.HERE
ENI5
END £ TART

FIGURE 10-25 (continued

weight in the address field, and AH loaded with 01 to the 8279 status register until another keypress is de-
insert a decimal point at the appropriate place. tected.
the If pressed key is a numeric key. then the
To display the letters Lb in the data field. BX is loaded code(s) for the previously entered number(s) will be
with the offset of the string named LB. and the display shifted one location in the buffer to make room for the
procedure is called. Again, the XLAT instruction loop new number. The new number is then put in the first
converts the codes from the LB string to the required location in the buffer so that is will be displayed in the
seven-segment codes and sends them out to the 8279 rightmost digit of the display. In other words, previously-
display RAM. The codes in the string named LB repre- entered numbers are continuously shifted to the left as
sent the
offsets from the start of the SEVEN SEG table new numbers are entered. If a mistake is made, the op-
for the desired seven segment codes. For example, the erator simply
can enter a 0 followed by the correct price
seven-segment code for a P is at offset 12H in the per pound.
SEVEN SEG table. Therefore, if you want to display a P. If the pressed key is not a numeric key. then this is the
you put 12H in the appropriate location in the the char- signal that the displayed price per pound is correct and
acter stringin memory. The XLAT instruction will then that the total price should now be computed. Before the
use the value 1 2H to access the seven-segment code for P weight and the price/pound can be multiplied, they
in the SEVEN SEG table. must each be put in packed BCD form and converted to
After displaying the weight, the program reads the binary. The PACK procedure converts four unpacked
8279 status register to see if the operator has pressed a BCD digits in a memory buffer pointed to by BX to a
start entering a price per pound. If no key has 4-digit packed result in AX. This procedure is simply
been pressed, or if a nonnumeric key has been pressed, some masking and moving nibbles. Note how the proc-
the program simply goes back and reads the weight esssimplified
is by the ability to rotate the contents of a
again. If a number key has been pressed, the weight is memory location. Conversion of the packed weight and
removed from the address field and the letters SP for the packed price per pound is done by the CON-
"selling price" displayed there. The number entered is VERT2BIN procedure. The algorithm for this procedure
pul in the SELL PRICE buffer and displayed on the is explained in detail in Chapter 5.
rightmost digit of the data field. The program then polls For the 8086 a single MUL instruction does the 16 x

338 CHAPTER TIN


ltj binary multiply to produce the total pine. Earlier
processors required a messy procedure to do ihis. Aftei
the multiplication the total price is m binary form,
which is mil the form needed foi the displa) procedure
['In- procedure B1NCV1 is used to converl the binary
total price to packed BCD form. Here's how this proce
dure woi ks
In .1 binary number, each l>i( position represents .1
powei nt 2. An 8-bit binary numbei . foi example, can be
represented as

b ' lit. 2' % l).r. < 25 + b4 x 2'1 b3


b2 % 2' i lil .'' I ho

This can be shuffled around and expressed

as binary number ((((((2b7 • b6)2 % b5)2 I b4)2 *


b3)2 t b'212 t bi)2 i bO

where b7 through bO are the values ol the binary bits. II


we start with a binary number and do each operation in
SHIFT BX LEFT 1 BIT
the nested parentheses in BCD with the aid ol the DAA
MSB TO CARRY
instruction, the result will be the BCD number equiva- SHIFT DL LEFT 1 BIT
lent the
to original binary number. CARRY TO LSB
MSB TO CARRY
The procedure in Figure 10-25 produces two BCD dig-
its ofthe result at a time by calling the subprocedure
CNVT1. Figure 10-26 shows a flowchart for the opera- < DIGIT BEING BUILT

tionCNVT1.
of The main principle here is to shift the AND ADD CARRY
FROM DLSHIFT
24-bit number left one bit position so the MSB goes into
the carrv flip-flop, then add this bit to twice the previous
result. We use the DAA instruction to keep the result of DECIMAL ADJUST TO
KEEP IN BCD FORMAT
the addition in BCD format. If the DAA produces a carry
we add this carry back into the shifted 24-bit number in
DL and BX so that it will be propagated into higher BCD
digits. After each run of CNVT1 (24 runs ol CNVT21, DL
and BX will be left with a binary number which is equal
to the original binary number minus the value of the
two BCD digits produced. You can adapt this procedure
to work with a different number of bits by simply calling
CNVT1 more or fewer times, and by adjusting the count ADD OVERFLOW
CARRY TO BX& DL
loaded into DH to be one more than the number of bi-
FOR NEXT BCD
nary bits
in the number to be converted. The count has BYTE CALCULATION
to be one greater because of the position of the decre-
ment thein loop. The temperature-controller procedure
in Figure 10-35 shows another example of this conver- FIGURE 10-26 Flowchart for CNVTl subprocedure.
sion.
The least-significant 2 digits of the BCD value for the
total price returned by B1NCVT in BL represent tenths play the total price on the data field. The DISPLAY proce-
and hundredths of a cent. If the value of these two BCD durecalled
is again to display the letters Pr in the ad-
digits is greater than 49H, then the carry produced by dress field.
the compare instruction and the next two higher BCD Finally, after delaying a few seconds to give the opera-
digits in BH are added to AL. This must be done in AL, tor time to read the price, execution returns to the
because the DAA instruction, used to keep the result in "dumb scale" portion of the program and starts over.
BCD format, only works on an operand in AL. Any carry A question (hat may occur to you when reading a long
from these two BCD digits is propagated on to the upper program such as this is, "How do you decide which
two digits of the result in DL. After this rounding off, the parts of the program to keep in the mainline, and which
packed BCD for the total price is left in AX. parts to write as procedures':'" There is no universal
In order for the display procedure to be able to display agreement on the answer to this question. The general
this price, it must be converted to unpacked BCD form guidelines we follow are to write a program section as a
and put in four successive memory locations. Another procedure if: it is going to be used more than once in the
"mask and move nibbles" procedure called EXPAND program: it is reusable (could be used in other pro-
does this. The DISPLAY procedure is then called to dis- grams):
is soit lengthy (more than 1 page) that it clut-

ANALOC INTERFACING AND INDUSTRIAL CONTROL 339


ters up the conceptual flow of the main program: or it is PEAK

an essentially independent section. The disadvantage of


ERROR
^ j ERROR
using too many procedures is the time and overhead NEW f BAND
SETPOINT
required for each procedure call. As you write more pro-
grams,
will
youarrive at a balance that feels comfortable % SETTLING TIME-

to you. The following section shows you another long


OLD
program example which was written in a highly modu- SETPOINT
lar manner so that it can easily be expanded. This exam-
ple shouldfurther help you see when and how to use
procedures.
RESIDUAL ERROR

A MICROCOMPUTER-BASED INDUSTRIAL
PROCESS-CONTROL SYSTEM — I BAND

Overview of Industrial Process Control


An area in which microprocessors and microcomputers
have had a major impact is industrial process control.
Process control involves first measuring system varia- % SETTLING TIME-

bles such
as motor speed, temperature, the flow of reac- (6)
tants. the level of a liquid in a tank, the thickness of a
material, etc. The system is then adjusted until the RESIDUAL ERROR
value of each variable is equal to a predetermined value
for that variable called a set point. The system controller SETPOINT
MOTOR SPEED
must maintain each variable as close as possible to its
set point value, and it must compensate as quickly and
accurately as possible for any change in the system such
as an increased load on a motor. A simple example will
show the traditional approach to control of a process INCREASED LOAD

variable and explain some of the terms used in control


systems.
The circuit in Figure 10-27 shows one approach to FIGURE 10-28 Overshoot and undershoot of system
controlling the speed of a dc motor. Attached to the when setpoint or load is changed, (a) Overshoot, (b)
shaft of the motor is a dc generator, or tachometer. Undershoot, (c) foad change.
which puts out a voltage proportional to the speed of the
motor. The output voltage is typically a few volts per
1000 rpm. A fraction of the output voltage from the ta-
chometer
fed backis to the inverting input of the power until the voltage fed back from the tachometer to the
amplifier driving the motor. A positive voltage is applied inverting input of the amplifier is nearly equal to the
to the noninverting input of the amplifier as a set point. set-point voltage. Using negative feedback to control a
When the power is turned on, the motor accelerates system such as this is often called servo control. A con-
trol loop
of this type keeps the motor speed quite con-
stantapplications
for where the load on the motor does
not change much. Some hard-disk drive motors and
high-quality phonograph turntables use this method of
speed control.
For applications in which the load and/or set point
changes drastically, there are several potential prob-
lems. The
first of these is overshoot when you change
the set point, as shown in Figure 10-28a. In this case
the variable, motor speed for example, overshoots the
new set point and bounces up and down for a while. The
time it takes the bouncing to settle within a specified
error range or error band is called the settling time. This
type of response is referred to as underdamped and is
similar to the response of a car with bad shock absorb-
ers whenit hits a bump. Figure 10-28b shows the oppo-
site situation where the system is overdamped so that it
takes a long time for the variable to reach the new set-
point.
FIGURE 10-27 Circuit tor controlling speed of dc motor Another problem of any real control system is residual
using feedback from tachometer. error. Figure 10-28c shows the response of a control sys-

340 CHAPTER TEN


icm such as the motor speed controller In Figure 10 21 from the tachometei is positive, there will be no net cui
when more load is added cm the motor. When the In reiii through the feedback resistoi ol the amplifiei il the
creased load is firsi added the motoi slows down so the iwo voltages are equal in magnitude. In othei words, il
voltage oul ol the tachometer decreases. This Increases the speed ol the molor is al Us sel point value, (he out-
the voltage difference between the amplifier Inputs and put amplifier
ol I will be zero, and amplifiers 2, 3, and I
causes the amplifier output to increase. Increased am will contribute no current to the summing junction ol
plifiei output increases the speed of the motoi and the powei amp.
thereby the output from the tachometer. When the sys Now. suppose that von add more load on the motoi.
tern reaches equilibrium, however, there is sonic notice slowing it down I he tachometer voltage is no longer
able difference between the sel poinl and the voltage fed equal to the set point voltage so amplifiei I now has
back from the tachometer, li is ihis difference or resid- some output. Ihis error signal on the output produces
ual cnoiwhich is amplified by the gam ol the amplifiei three types ol feedback to the summing junction of the
to produce the additional drive for the motoi Foi stabil power amp.
ity i easons, the gain of many control systems cannot be Amplifier 1 produces simple dc feedback proportional
too high. Therefore, even il you adjust the speed of a to the difference between the set point and the tachome-
motor, for example, to be exactly at a given speed for one ter output. This is exactly the same effect as the voltage
load, when you change the load there will always be divider on the tachometer output In Figure 10-27. Pro-
some residual error between the set point and the actual portional feedback,
as this is called, will correct foi
output. most of the effect of the increased load, but as we dis-
To help soke these problems, circuits with more com cussed before,
there will always be some residual error.
plex feedback are used. Figure 10-29 shows a circuit The cure for residual error is to use some integral
which represents the different types of feedback com- feedback. Amplifier 3 in Figure 10-29 provides this type
monly used.
First note in this circuit that the output of feedback. Remember from a previous discussion that
power amplifier is an adder with four inputs. The cur- this circuit produces a ramp on its output whenever a
rent suppliedto the summing point of the adder by the voltage is applied to its input. For the example here the
set-point input produces the basic output drive current integrator will ramp up or ramp down as long as there is
The other three inputs do not supply any current unless any error signal present on its input. By ramping up
there is a difference between the set point and the feed- and down just a tiny bit about the set point, the integra-
back voltage
from the tachometer. Amplifier 1 is another tor caneliminate most of the residual error. Too much
adder whose function is to compare the set-point voltage integral feedback, however, will cause the output to os-
with the feedback voltage from the tachometer. Let's cillate
and
up down.
assume the two input resistors, Rl and R2. are equal. A third type of feedback called derivative feedback is
Since the set-point voltage is negative and the voltage produced by amplifier 4 in Figure 10-29. Integral feed-

TACHOMETER

FIGURE 10-29 Circuit showing proportional, integral, and derivative feedback


control.
ANALOGINTERFACING
AND INDUSTRIAL
CONTROL 341
I
DISPLAY
RELAYS

TEMPERATURE SENSORS DAS

D/As
h-
cr
O
o MICRO-
Q-
COMPUTER
D
D

Z SOLENOID
O VALVES

DAS
1 N
KEYBOARD
CONTROL
- SIGNALS

t N TO DAS

FIGURE 10-30 Block diagram of microcomputer-based process control system.

back discussed in the previous paragraph is slow be- computer


to used
control an entire fractionating col-
causeerror
the signal must be present for some time umn an
in oil refinery. To show you how these
before the integrator has much output. Derivative feed- microcomputer-based control systems work, here's an
backa signal
is proportional to the rate of change of the example system you can build and experiment with.
error signal. If the load on the system is suddenly
changed, the derivative amplifier circuit will give a
quick shot of feedback to try and correct the error. When
the error signal is first applied to the differentiator cir- AN 8086-BASED PROCESS-CONTROL
cuit, the
capacitor in series with the input is not SYSTEM
charged, so it acts like a short circuit. This initially lets
a large current flow so the amplifier has a sizable out- Program Overview
put. the
As capacitor charges, the current decreases, so Figure 10-32 shows in flowchart form one way in which
the feedback from the differentiator decreases. Too the program for a microcomputer-based control system
much derivative feedback can cause the system to over- with eight PID loops can operate. After power is turned
shoot and
oscillate. on. a mainline or executive program initializes ports,
The point here is that by using a combination of some initializes the timer, and initializes process variables to
or all of these types of feedback, a given feedback-
controlled system can be adjusted for optimum response
to changes in load or set point. Process control loops
that use all three types of feedback are called propor-
tional integral-derivative or PID control loops. Because
process variables change much more slowly than the
microsecond operation of a microcomputer, a micro-
computersomewith simple input and output circuitry
can perform all of the functions of the analog circuitry in
Figure 10-29 for several PID loops.
Figure 10-30 shows a block diagram of a microcom-
puter-based process-control
system. Data acquisition
systems convert the analog signals from various sensors
to digital values that can be read in and processed by the
microcomputer. A keyboard and display in the system
allow the user to enter set point values and to read the
current values of process variables. Relays, D/A convert-
ers, solenoidvalves, and other actuators are used to
control process variables under program direction. A
programmable timer in the system determines the rate
at which control loops get serviced.
Microcomputer-based process-control systems range
from a small programmable controller such as the one
shown in Figure 10-31. which might be used to control FIGURE 10-31 Photograph of Texas Instruments'
one or two nun hines on a factory floor, to a large mini- programmable controller for up to eight PID loops.

342 ( MAIM IK UN
f START J MAINLINE OR ( INTH J HIHIUNCLOCK
TICK
INTERRUPT ( iP0 )
BACKGROUND
I'lUli HAM

DEI REM! N1
TICK
INITIALIZE COUNTER
Pi Hi is

INITIALIZE
TIMER

INITIALIZE
PROCESS
VARIABLES

LOOP lN YES
GET NEW
TEMPERATURE
UNMASK AND
READING
ENABLE
INTERRUPTS

CONVERT TO
LOOP? >, YES BCD FOR
DISPLAY

LOOK FOR
USER
COMMAND
h t ^ PRESS! (.1

COMPUTE
HEATER
DUTY CYCLE

TURN HEATER

SET DUTY
CYCLE FOR
OFF

(RETURN
~\
TO
INTR
J
RETURNTO "\
V1AINLINE
PROGRAM^/

FIGURE 10-32 Flowchart for microcomputer-based process control system, (a)


Mainline or executive, (b) Loop selector, (c) Temperature-control loop.

ANALOG INTERFACING AND INDUSTRIAL CONTROL 343


some starting values. The executive program then sits tion herewe only use the positive part of the output
in a loop waiting for a user command from the keyboard range, but we thought you might find this circuit useful
or a clock "tick" from the timer. Both the keyboard and for some of your other projects. An LM308 amplifies the
the clock are connected to interrupt inputs. signal from the sensor by 2 so that the signal uses a
When the microcomputer receives an interrupt from greater part of the input range of the A/D converter. This
the timer it goes to a procedure which determines improves the noise immunity and resolution.
whether it is time to service the next control loop. The The ADC0808 A/D converter used here is an eight-
interrupt procedure does this by counting interrupts in input data acquisition system. You tell the device which
the same way as the real-time clock we described in input signal you want digitized with a 3-bit address you
Chapter 8. For example if you program the timer to pro- send to the ADC, ADB, and ADA inputs. This eight-
duce
pulse
a every 1 ms, and you want the controller to input device was chosen so that other control loops
service another loop every 20 ms, you can simply have could be added later. Some Schmitt-trigger inverters in
the interrupt procedure count 20 interrupts before a 74C14 are connected as an oscillator to produce a
going on to update the next loop. Once you have counted 300-kHz clock for the DAS. The voltage drop across an
down 20 interrupts, the program then falls into a deci- LM329 low-drift zener is buffered by an LM308 amplifier
sion structure which determines which loop is to be to produce a V,, and a VR[f of 5.12 V for the A/D con-
updated next. Every 20 ms a new loop is updated in verter. With
this reference voltage the A/D converter will
turn, so with eight loops, each loop gets updated every have 256 steps of 20 mV each. Since the temperature
160 ms. Note that the microcomputer services each loop sensor signal is amplified by 2, each degree Celsius of
at a regular interval instead of simply updating all eight temperature change will produce an output change of
loops, one loop right after another. This is done so that 20 mV or one step on the A/D converter. This gives us a
the timing for each loop is independent of the timing for resolution of 1 C, which is about equal to the typical
the other loops. A change in the internal timing for one accuracy of the sensor. The advantage of using VRir as
loop then will not affect the timing in the other loops. the Vcc for the device is that this voltage will not have the
This system is one type of time-slice system, because switching noise that the digital Vcl line has. The control
each loop gets a 20-ms "slice" of time. inputs and data outputs of the A/D converter are simply
The procedures which actually update each control connected to SDK-86 ports as shown.
loop are independent of each other. For our example sys- Figure 10-34 shows the timing waveforms and param-
tem herewe only have space to show the implementa- etersthe
for ADC0808. Note the sequence in which con-
tionone
of loop, the control of the temperature of a tank trol signalsmust be sent to the device. The 3-bit address
of liquid in, perhaps, our printed-circuit-board-making of the desired input channel is first sent to the multi-
machine. You could write other similar control loop pro- plexer inputs.After at least 50 ns the ALE input is sent
cedures
control
to pH. flow, light exposure timing. high. ARer another 2.5 t±s the START CONVERSION
motor speed, etc. Figure 10-32c shows the flowchart for input is sent high and then low. Then the ALE input is
our temperature-controller loop. We will explain how brought low again. When you detect the END OF CON-
this works after we have a look at the hardware for the VERSION from
signalthe A/D converter going high, you
system. can then read in the 8-bit data value which represents
the temperature.
To control the power delivered to the heater we used a
25 A, 0-V turn on, solid-state relay such as the Potter-
Hardware for Control System and Temperature Brumfield unit described in Chapter 9. With this relay
Controller we can control a 120- or 240-V ac-powered hot plate or
To build the hardware for (his project we started with an immersion heater. The heater is pulsed on and off under
SDK-86 board and added an 8254 programmable timer program control. The duty cycle of the pulses deter-
and an 8259A priority interrupt controller as shown in minesamount
the of heat put out by the heater.
Figure 8-14. The timer is initialized to produce 1-kHz For very low power applications, a D/A converter and a
clock ticks. The 8259A provides interrupt inputs for the power amplifier could be used to drive the heater. How-
clock-tick interrupts and for keyboard interrupts. We ever,
high-power
in applications this is not very practi-
built the actual temperature sensing and detecting cir- cal, becausethe power amplifier dissipates as much or
cuitry
a on
separate prototyping board and connected it more power than the load. For example, when driving a
to some ports on the SDK-86 with a ribbon cable. Figure 5000-W heater, the amplifier will dissipate 5000 W or
10-33 shows the added circuitry. more. The D/A-converter approach has the added disad-
The temperature-sensing element in the circuit is an vantage it that
cannot directly use the available ac line
LM35 precision Centigrade-temperature sensor. The voltage.
voltage between the output pin and the ground pin of The driver transistor on the input of the solid-state
this device will be 0 V at 0°C, and will increase by 10 mV relay serves three purposes: it supplies the drive for the
for each increase of 1 "C above that. The 300 kii resistor relay, isolates the port pin from the relay, and holds the
connecting the output of the LM35 to - 15 V allows the relay in the off position when the power is first turned
output to go negative for temperatures below 0 C. (If you on. Port pins, remember, are in a floating state after a
are operating with ± 12-V supplies, use a 240-ki2 resis- reset. Now that you know how the hardware is con-
tor.) Thismakes the circuit able to measure tempera- nected
canwe explain how the program for this system
tures over
the range of -55 to + 150°C. For our applica- works.

344 CHAPTER TEN


•>;ERS FOR
CONNECTOR J5 OF

END OF
CONVERSION
START
CONVERSION
ALE
AH:
DAS

LM329^k

REFERENCE
FOR A/D

FIGURE 10-33 Temperature-sensing and heater-control circuitry for


microcomputer-based controller.

The Controller System Program SDK-86 monitor program is structured. Due to severe
space limitations, we do not show here the implementa-
THE MAINLINE OR EXECUTIVE SECTION tionthe
of keyboard interrupt procedure which allows
the user to change set points, stop a process, or examine
Figure 10-35 shows the assembly language program lor
the value of process variables at any time.
our controller system. Refer to the flowchart in Figure
10-32 as you work your way through this program. The
THE CLOCK-TICK INTERRUPT HANDLER
mainline or executive part of the program starts by ini-
tializing
FFFAH
port for output, the 8259A to receive The next part of the program to discuss is the interrupt
interrupt inputs from the timer and the keyboard, and procedure which counts clock ticks and decides which
the 8254 to produce a 1-kHz square wave from its process control loop to service. At the start of this proce-
counter 0. We have described all of these operations in dure we
simply decrement an interrupt counter kept in
detail previously, so we won't dwell on them here. We a memory location. In the initialization this counter was
also initialize here some process variables which we will set to 20 decimal or 14H. If the counter is not down to
explain later when they will have more meaning. After zero, execution is simply returned to the wait loop. If the
enabling the 8086 INTR input with an STI instruction, tick counter is now down to zero, the clock tick counter
the program then enters a loop and waits for an inter- is reset to 20. and one of the loop procedures is called to
rupt fromthe user via the keyboard, or from the timer. service the next loop. It is important that this clock tick
The keyboard-interrupt procedure would normally con- procedure be reentrant, because if one of the loop proce-
taincommand
a recognizer and subprocedures to im- dures takes
more than the time between clock ticks
plementofeach
the commands, similar to the way the (1 ms). the procedure will be reentered before its first

ANAtOC INTERFACING AND INDUSTRIAL CONTROL 345


rLTLTL

ADDRESS 50%

COMPARATOR
INPUT
(INTERNAL
NODE)

TRI-STATE
CONTROL

OUTPUTS —

FIGURE 10-34 Timing waveforms tor the ADC0808 data acquisition system.

use is completed. The procedure is made reentrant by Take a look at how the table of procedure addresses is
pushing all registers used in the procedure, and by set up with DD directives at the start of module 2 in
immediately resetting the clock tick counter to 20. If a Figure 10-35. The names LOOPO. LOOP1. LOOP2. etc.
loop procedure takes longer than 1 ms and the clock tick are the names of the procedures to service each of the
procedure is called again, it will just decrement the tick loops. When this program module is linked and loaded
counter and return to the interrupted loop procedure. into memory, the instruction pointer and code segment
The method used here to call the desired loop proce- addresses for each of the procedures will be loaded into
dureanis important programming technique. It uses a the table.
call table to efficiently implement the CASE or nested When execution returns from one of the loop proce-
IF — THEN — ELSE programming structure described in dures.
is 4added to LOOPNUM so that execution will go
Chapter 3. Here's how it works. to the next loop in sequence the next time the tick
To keep track of which loop should be serviced counter is counted down to zero. LOOPNUM must be
next, we use a variable called LOOPNUM in memory. incremented by four because each address in the call
During initialization LOOPNUM is loaded with OOH. table uses 4 bytes. If all loops have been serviced. LOOP-
When it is time to service the first loop, the value in NUM
setis back to 0 so LOOPO will be serviced again.
LOOPNUM is loaded into BX. The CALL DWORD PTR Now let's look at the actual temperature-control loop.
LOOP ADDR TABLE! BX] instruction then gets a far call
address from a table called LOOP ADDR TABLE in
THE TEMPERATURE-CONTROLLER PROCEDURE
memory. BX functions as a pointer to the desired ad-
dressthe
in table. For the first access BX is zero so the As we said previously, the amount of heat output by the
first address in the table is used. heater is controlled by the duty cycle of a pulse waveform

346 ( HAP1TR TEN


page ,132
8086 PROGRAMFOR CONTROLLERSYSTEM - MODULE1

ABSTRACT: This prograa services eight process rDntrcl loops on a


rotating basis. It i= written to run on an Intel SOK-86 board.
Timing t:r the control ioops is generated on an interrupt basis
by an on-board 8254 tiser. Control-loop $ in the program controls
the temperature of a water bath.
PORTS: Uses port C2B (FFFAH) as output
bits 7 - heater, bit 6,3 - not connected, bit 5 = start conversion
; bit 4 = ALE, bit 2,1,8 = channel address
; Uses port P2A (FFF8H) as data input
; Uses port F2C (FFFCH) as end-of-conversion input from A.'D
;PROCEDURES: Calls: CL0CK.T1CK - interrupt service procedure
; r EV&uAR[' - interrupt service procedure (empty!

INT_PROC_HERE
SEGMENT
WORD PUBLIC
EXTRN CLOCK_TICK:FAR,
KEYBOARD:FAR
!NT_PROC_HERE
ENDS
PUBLIC COUNTER.TIMEHI, TIMELO, LOOPNUM,CURTEMP,SETPOINT

AINTJABLE SEGMENT
WORD PUBLIC
TYPE.64 DW 2 DUP(0! jreserve space for dock-tick proc addr IR0
TYPE 65 DM 2 DUP(0! ; not used in this prograa - IR!
TYPE~6i [lit! 2 PUP(0) ;reserve space for keyboard proc addr - IR2
AINTJABLE ENDS

DATA_HERE HORD
SEGMENT PUBLIC
COUNTER DE M counter tor nuiber of interrupts
TIMEHI DB 0] heater relay - time on
TIMELO DE 31 heater relav - tifie off
LQQPHUH DB 00 temp storage for loop counter
CURTEHP DE M current temperature
SETPOINT PR 0^ setnoint temperature
DATA_HERE ENDS

STACK.HERE SEGMENT i no STACK directive because using EXE2SIN


DH 40 ; so can then download code to SBK-86
TOP.STACK LABEL wnsr:

STACK
HERE
" ENDS

CODE_HERE SEGMENT
WORD PUBLIC
ASSUME CS:CODEHERE, DSsAINTTABLE,SSsSTACKJOE
Unitialize stack segment register, stack pointer, data segment
MOV fix, STACfHERE
MOV 55, AS
MOV BP, OFFSETTOPSTACK
MOV AX, AINT TABLE
MOV DS, A»
idefine the addresses for the interrupt service procedures
MOV TYPE 64+2, SEG CLOCKTICK ; put in clock-tick proc addr
MOV TYPE_oi, OFFSETCLOCK
TIC*
MOV TYPE 66+2, SEG KEYBOARD ; put in keyboard proc addr
MOV TYPE 66. OFFSET KEYBOARD

FIGURE 10-35 8086 assembly language program for process control system (a)
Module 1— Mainline, (b) Module 2— interrupt service procedures, (c) Module
3— loop service procedures, (d) Module 4— utility procedures.

ANALOG INTERFACING AND INDUSTRIAL CONTROL 347


^initialize [lata s EQiisn *
-~:'.-*l CSsDATfi -^E:E
HG1, si, DATS ^::
HQ'J OS, A)
[initialize port P28 FFFA! : output - 'coe i, P2A !• P2C a? inputs - sods *
-:. [!>;, gFFFEH ; point BX at port control addr
HOV ! sods control -crc for above ccnoitiQ's
3UT BX, AL ; send control sord
initialize EI:3-
MOv »LS i I EdQE tri0QEr5d, 5i RQ16 , I CM4
MO', DX, :"rc^ ; soi nt it 3259A control
:J!jT OX, AL ; send !CHi
HQ'J AL, 01000000B ; type -A is *irst 3259A typE !IR«)
"".• :% - :";:- ; point at ICI2 address
but e : . »_ ; send ICN2
NOV --, {;e:s':?l: ; I CW4 , :
3u'T . ! . A- ; send ICM4
MOV fit, Li 111110E ; QCtil to unaask IR0 only ieavE IR2 lasked
\ UT ; bEcause not used % *send Qr y i
[initialize B254 counter i for 1-kHz output
S254 coiaand word lor counter i, LSB then MSB, sEjuars Nave, BCD
M fiL, 00U01HB
ffQV DX, 0FF?7H ; point at 6254 control acor
out r.;, at ; ser'd counter 0 comand ncd
MOV fiL, 5SH ! Load LSE of count
MO* [il BFF01H ! point at countEr 0 data addr
OUT [% :, fil. i send LSB of count
MOV AL, 24H ; load MSB0* count
OUT DX, -_ ; send MSB of count
;initia!izE variables
m\ SETPQINT,3CH ; initialize final teap at 60 deq
mov COUNTER, i4H ; intialize tise countEr
MQV LQOPNUH, 00H ; start at first loop
hhehi, 01H
MOV TIMELO, ?1H
KOV CURTEMP,00H
; e_;ab1e interrupt input of 8086
STI
JEC'E: J"" ^:E ; »ait for interrupt
NOP i if required, can put sere
KOF ; instructions here

NOP
C0DE_HERE
EMD5
END

FIGURt 10- 15 1 ontinued)

sent to the solid-stair relay The time on for the output have a temperature value to use for computing the duty
waveform to the solid-state relay is determined by cycle.
counting down a value called TIMEHI. The time off for The number of the A/D channel that we want to digi-
this waveform is determined by counting down a value tizepassed
is to the A/D conversion procedure in the BL
called TIMELO. At start-up the mainline program ini- register. The procedure then sends out this channel
tializes TIMEHI
and TIMELO to 01H. so that the first number to the A/D converter and generates the control
time the LOOPO procedure is called both of these are wave forms shown in Figure 10-34 under software con-
decremented to 0 and execution falls through to the A/D trol. The
binary- value for the temperature is returned in
conversion procedure. This needs to be done so that we AL.

348 ( HAPIf R TEN


PAGE ,13d
% . [N IE E SUI riNI

ncK, i

;ti t>ler loop addresses used ir. this modul


' ITA HERE SEGMENT WORD PUPI
addr rftBLt
t:> L )OF 1
DD LOOP2
DI L00P3
.[• LOOPs
DO L00P5
DD LGOPfe
DI LOOP?

EXTRN :BvTE,
COUNTER LOOPNUM:ByTE
'ATA HERE END;

itell asseabier wnere to find procedures used in this module


CODE.HERE SEGMENTWORD c' BLIC
E.J'TRN LDOPO:FAR, LOOFiiFAR, L00P2:FAR, LQ0P3:FAR
EXTRN LOOP^FAR, LOOF'iiFAR, LG0P6:FAR, L0QP7:FAR
CODE.HERE ENDS

INT_PROC
.HERE SEGMENT
WORDPUBLIC ;seqment for interrupt service procedures
ASSUME CS:INT_PRQC_HERE,
D5:DATA_HERE

!8086 INTERRUPT PROCEDURETO SERVICE PROCESS CONTROLLOOPS

; ABSTRACT: This procedure services calls 1 of 6 process control


i loops on a rotating basis.
; PORTS USED: none
PROCEDURES:calls L0OP0,L00Fl,L0OP2, LOOPS,LOOF'h
, LGOF'5
, LO0P6. LOOP?
iREGISTERS: saves ail

CLOCK_TICK PROC FAR


PUSH A' ; save registers
POSH BX
PUSH Da
PUSH DS '. save DS of interrupted program
STI i enable higher interrupts if any
MOV AL, 001000008 ! 0CW2 for nonspecific EOI
NOV Da. OFFOOH ! address for 0CW2
OUT DX, AL
MOV AX, DATA.HERE ; load DS needed here
MOV DS. AX
DEC COUNTER ; decrement interrupt counter
JNZ EXITS ; not zero yet , go wait
MOV COUNTER. 20 i if :ero, reset tic! counter to 20
MOV BH, 00 ! load BX with number of loop to
MOV BL, LOOPNUM I service
CALL DWORD
PTR L00P.ADDR.TABLE1BX] ! and service that loop
ADD LOOPNUM,04 i point at next loop address
CMP LOOPNUM. 20H . was this the last loop?
JNE EXITS ; no, exit

FIGURE 10-35 (continued)


ANALOG INTERFACINGAND INDUSTRIALCONTROL 349
MOV LQQPNUMj
00 l yes. get back to first loop
EXITBiPOP DS ! restore registers
POP DX
POP BX
POP A*
I RET
CLOCK TICK ENDP

{DUMMYINTERRUPT PROCEDURE TO SERVICE KEYBOARD


KEYBOARDPfiOC FAR
; keyboard proc instructions
MOV AL. 0O1OO0OOB ; 0CW2 for non-specific EOI
MOV DX, OFFOOH i address for QCWE
GUT DX. AL ; send 0CW2 for end of interrupt
IRET
KEYBOARDENDP

INT_PROC.HERE
ENDS
END
lb)

PA6E ,132
; MODULE3 - CONTAINS THE PROCEDURESTO SERVICE EACH LOOP

DATA_HERE SEGMENT
WORD PUBLIC
EXTRN TIMEH!:BYTE, TIMELO : BYTE ; iaported into this
EXTRN CURTEMPsBYTE,SETPDINT:BYTE ; nodule from the nainline
DATA_HERE ENDS

PUBLIC LOOP?,L0QP1, L00P2, L00P3, L00P4, LOOPS,L00P6, LOOP?

CODE.HERE
SE6MENT
WORD
PUBLIC
EXTRN DISPLAY : NEAR ; These procedures can be
EXTRN A_DREAD: NEAR ; found in another assenbly
EXTRN BINCVT : NEAR ; soduls which sill be linked
CODE HERE ENDS ; with this uodule & other aodules

C0DE_HERE SEGMENT
WORD PUBLIC
ASSUME
CS:CODE.HERE,
DS:DATA.HERE

;S086 PROCEDURE
TO SERVICE TEMPERATURE
CONTROLLER

; ABSTRACT: This procedure services the temperature controller


; REGISTERS: Destroys none
; PORTS: Uses F2B (FFFAH) as output port to turn heater with
; bit 7,
; CALLS: DISPLAY,AJ.READ, BINCVT
LQQP0 PROC FAR
PUSHF : save registers
PUSH AX
PUSH BX
PUSH CX
PUSH DX
DEC TIMEHI ; decrement tine 'or heater on

FIGURE 10-35 (continued)

350 CHAPTER TEN


JN2 EXIT ; return to interrupt procedure
NOV TIMEHI, 01 ; reset tiee high to fall through value
MOV DX, 0FFFAH ; point at o/p port P2B i
NOV AL, B0H ; turn off heater
DUT DX, Al
DEC TIMELO ; decrement tine tor heater off
JNZ EXIT i return to interrupt procedure
MOV BL, 00 ; load channel address 10)
CALL A.D.READ ; do A/D conversion
NOV CURTEHP,
AL ; save current temperature
CftLL BINCVT ; convert to BCD
NOV CL, AL ; put result in CX to display
MOV CH, 00
NOV AL, 00 ; temp in data field of SDK-86
CALL DISPLAY
MOV AL, SETPOINT get setpoint temperature
SUE AL, CURTEMP get temperature & subtract froi setpoint
j BE DONE heater off if above or equal setpoint
MOV DL, AL save temperature difference
ti.V AX, 0064H compute new TIMELO
DIV DL 0064/error, quotient is value
MOV TIMELO, AL for new time low
m TIMEHI,04 set time high for 4 loops on
m\ AL, 00
MOV DX, SFFFAH noint at output port
OUT DX,AL turn on heater
J MP EXIT
DONE: MOV TIMEHI, 01H fal! through value for time high
MOV TIMELO, 7FH long off value *or time low
EXIT: POP DX loop serviced - return to
POF [i interrupt service procedure
POP BX
POF AX
POPF
RET
LOOP0 ENDP

LOOPS HERE
; DUMMY
LOOP1 PROC FAR
instructions for this loop
RET
LOOPi ENDP

L00P2 PROC FAF


instructions for this loop
RET
L00P2 ENDP

LOOPS PROC FAR


instructions for this loop
RET
LOOP3 ENDP

L00P4 PROC FAR


instructions for this loop
RET
L00P4 ENDF

FIGURE 10-35 {continued)

ANALOG INTERFACING AND INDUSTRIAL CONTROL 351


LOOPS PROC FAR
i instructions tor this loop
RET
LOOPS ENDP

LQ0P6 PROC FAR


; instructions for this loop
RET
L00P6 ENDF

L00P7 PROC FhP

; instructions for this loop


RET
L00P7 ENDP

CODE.HERE l'<u?
END

PAGE ,131
; MODULE4 - CONTAINSTHE SERVICE PROCEDURESNEEDEDBY THE LOOP MODULES

PUBLIC DISPLAY,A_DREAD,BINCVT; make procedures available to other sodulss

DATA HERE SEGMENT WORD PUBLIC


SEVENSE5 DE 3FH, B£H, 5BH, *FH, 66H, bDH, 7DH, «7H
; 0 12 3 4 5 6 7
DB 7FH, 6FH, 77H, 7CH, 39H, 5EH, 79H, 71H
j 8 ? A b C d E F
DATfi_HERE
ENDS
CODE HERE SEGMENTWORD PUBLIC
ASSUME
CS:CODE.HERE,
DS:DATA_HERE
; 8086 PROCEDURETO DISPLAY DATAON SDL-86 LEDs
•ABSTRACT:This procedure will display a 4-digit hex or BCDnunber
: passed in the CX register on LEDs of the SDK-86
: INPUTS: Data in CX, control in AL.
; AL - 80H data displayed in data-held of LEDs
AL •' OOH, data displayed in address field of LEDs.
: PORTS: Uses none
; PROCEDURES:
Uses none
; REGISTERS: saves all registers and flags

DISPLAY PROC NEAR


PUSHF : save flags
PUSH DS ; save caller's DS
PUSHAX ; save registers
PUSH BX
PUSH CX
PUSH DX
MOV BX, DATAHERE ; init DS as needed for procedure
MOV DS, BX
MOV DX, 0FFEAH : point at 3279 control address
CMP AL, 0«H ; see if data field required
JZ DATFLD ; yes, load control word for data field

riGURE 10-35 (continued)

352 CHAPTERTEN
Al , 94H no, load address-field control word
JMP SEND go send control word
DftTFLD: MO'J AL, 90H load control word for data field
SEN?: DUT D) send control word to 8279
SEG
MOV BX, OFFSETSEVEN. pointer to seven-sequent codes
MOV DX, 0FFE8H point at 8279 display RAM
MOV AL. EL get low bvte to be displayed
AND AL. 0FH mast upper nibble
XLATB translate lower nibble to 7-seg code
OUT DX, AL send to 8279 display RAM
MOV AL. CL get low byte again

load rotate count
ROL AL, CL Move upper nibble into low position
AND AL. 0FH Mask upper nibble
XLATB translate 2nd nibble to 7-seg code
OUT DX, AL send to 8279 display RAM
MOVAL, CH Get high byte to translate
AND AL, 0FH Mask upper nibble
XLATB Translate to 7-seg code
OUT DX, AL send to 32?9 display RAM
MOVAL, CH get high bvte to fix upper nibble
ROL AL, CL move upper nibble into low position
AND Al., 0FH uasl upper nibble
XLATB translate to 7-seg code
OUT DK, AL 7-seg code to 8279 display RAM
PDF' DX restore all registers and flags
FOP CX
POP BX
FOP A«
POP DS
FOPF
RET
DISPLAY ENDP

; 8086 PROCEDURETO CONTROLA/D CONVERTER

j PORTS: Port P2A is input frorc A/D


Port P2B, bit 7 - heater, bit 5 - start conversion
bit 4 - ALE bits 2,1,0 = channel address
Port P2C bit § - end of conversion
: INPUTS: Channel address
; OUTPUTS: A/D data in AL
; REGISTERS: DESTROYS AL i BL

A D READ PROC NEAR


PUSHF
PUSH DX
NOV AL, 83H : control for heater off
m AL, BL ; combine with channel address
MQV DX, 0FFFAH ; point at P2B, output port
OUT DX, AL ; send
MQV AL, 90H ; send ALE, keep heater on
OS' AL, BL ; keep channel address on
hijT DX, AL
MOV AL, 0B0H ; send start of conversion

FIGURE 10-35 (continued)

ANALOG INTERFACING AND INDUSTRIAL CONTROL 353


fifv AL, BL ; keep channel address on
OUT DX, AL
MOV AL, 80H ; turn off ALE and start
OF AL, BL ; keep channel address
OUT DX, AL
NOV DX, 0FFFCH ; point at port P2C
EOCL: IN AL, DX ; wait for end of conversion
RCR AL, 01 ; to go low
JC EOCL
EOCH: IN AL, DX ; wait for end of conversion
RCR AL, 01 ! to go hi oh
EOCH
NOV DX, 0FFF9H : point at port P2A
IN al, dx ; read data fros A/d
POP DX
POPF
RET
A_D_READ r*,r,f

BINCVT - Converts an 8-bit binary nueber


to packed BCDequivalent in AL
INPUTS; AL - 8—bit binary number
OUTPUTS: AL - packed BCDresult

BINCVT PROC NEAF


PUSHF ; save registers and flags
PUSH CX
NQV AH,09H bit counter for 8 bits
NOV CL, AL save binary in CL
NOV CH, 00 clear CH for use as buffer
CNVT2: J OR AL, AL clear AL and carry
DEC AH decrement bit counter
JNZ 60_0N do all bits
HOME done if AH down to zero
80 ON; RCL CL,1 MSB froij CL to carry
MOV AL, CH uove BCD digit being built to AL
ABC AL, AL double AL and add carry frois CL shift
Oh., keep result in BCD form
m CH, AL put back in CH for next time through
JHF CNVT2 continue conversion
HOME: NOV AL, CH BCD in AL for return
POP r.i ; restore registers
POFF
sn

BINCVT ENDP

CODE HERE END:


END

FIGURt 10-35 {continued)

Upon return, the binary value of the temperature is To do this we convert the binary value for the tempera-
stored in a memory location called CURTEMP for future ture ato BCD value using a reduced version of the
reference. For testing purposes we wanted to display the binary to-BCD procedure from the scale program earlier
temperature on the address field of the SDK-86 display. in this chapter, and the display routine from Chapter 9.

354 CHAPTFR TEN


After displaying the current temperature, it is then i om
pared with the sel poinl temperature to see il the heater
needs to be turned (in 11 the temperature is .11 01 ibov<
the set point. TIMEHI is loaded with the fall-through
value, and HMELO with a large numbei .
II the temperature is below the sel point, we <ould call
.1 procedure, DUT\ CYCLE, which computes the coi MICROCOMPUTER CONTROL
THERMOSTAT CONTROL
i eei values foi I1MKII1 and HMELO based on the differ SETPOINT
enee be I ween I lie sel point and the current temperature.
A complex I'll) algorithm might be used for dns proce 1 1 I I
15 30 45
dure in a precision system. For oui example here, bow MIN MIN MIN TIME
ever, we have used simple propoi tional feedback. To fur-
ther simplifythe <ah ulations .1 fixed value ol I was used lURI 10- 16 temperature versus time responses for
for TIMEHI. The thinking for the value ol TIMELO then trmostat-controlled and mi< rocomputer-controlled
goes as follows. II the difference in temperature is large, lU'ls.

then TIMELO should be small so the healer is on for a


longei duty cycle. II the difference in temperature is
Robotics
small, then the value ol TIMELO should be large so the
heater has a short duty cycle. Experimentally we found in recent years the term robot has become a "buzzword'
that a good lust approximation for our system was in the media and in many people's minds. Science fic-
(difference in temperature) • TIMELO = 100 decimal tion movieshave helped us form an image ol robots as
(64H). For example, if the difference in temperature is mobile, rational companions. Robots, however, have
20 ( 1 HI), then 64H 14H gives a value ol 5 for TIMELO. many forms, and in operation they are simply a special
The values for TIMEHI and TIMELO are returned in case of feedback control systems such as we described in
their named memory locations. Upon return to the main the previous section. This is why we have not included a
loop procedure we send a control word which turns on chapter dedicated just to robotics. The Rhino robot arm
the heater. Execution then jumps to EXIT. shown in Figure 9-43, for example, uses optical encod-
When execution returns to loop 0 again alter 160 ms. ers to
detect the position of its different joints, motors
TIMEHI will be decremented. If TIMEHI did not decre- (actuators) to move each joint to a desired position, and
ment0.to then execution simply adjusts a few things a microcomputer to control the motors based on feed-
and returns. It TIMEHI is 0 alter the decrement, the back from
the sensors. In large industrial robots such as
heater is turned off, and TIMELO is decremented. those that weld or spray-paint cars, the sensors used
TIMELO is then decremented every time loop 0 is ser- may also include vision, and the actuators may be hy-
viced (every160 ms) until TIMELO reaches 0. When draulic
pneumatic,
or but the control principle is the
TIMELO gets counted down to 0. a new A/D conversion same. Feedback from the various sensors is used to con-
is done, and a new feedback value for TIMELO recalcu- trol the
output to the actuators.
lated. Most of von have probably used some simple robots
An important point here is that the part of the pro- around your home without realizing it. One example is
gram that
determines the feedback is separate from the an electric garage door opener which starts to open or
rest of the program so it can be easily altered without close when you tell it to. and then stops when a sensor
changing any of the rest of the program. All that needs indicates that it is closed or open as desired. Other ex-
to be changed in this procedure is the value of TIMEHI, amplesanare automatic clothes washer, a clothes
the value of TIMELO, and the rate at wlvch these change dryer, and a microwave oven with a temperature probe.
in response to a difference in temperature to produce The next major section of this chapter is a discussion
proportional, integral, and derivative feedback control. of how you develop the prototype of a microcomputer-
based instrument such as the smart scale or the control
system we discussed in the preceding sections.
TEMPERATURE CONTROLLER RESPONSE

The dotted line in Figure 10-36 shows the temperature


versus time response of our system with traditional DEVELOPING THE PROTOTYPE OF A
thermostat control, which is often called on-qff control MICROCOMPUTER-BASED INSTRUMENT
or "bang-bang" control. As you can see the temperature
overshoots the set point a great deal, and then oscillates The first step in developing a new instrument is to very
around the set-point temperature. The solid line in Fig- carefully define exactly what you want the instrument to
ure 10-36shows the response of the system operating do. The next step is to decide which parts of the instru-
with our temperature-controller program. The initial ment you
want to do in hardware, and which parts you
overshoot was caused by the large thermal inertia ol the want to do in software. You then can decide how you
hot plate we used. The overshoot and the residual error want to do each of these.
of about 1" could be eliminated by using a more complex For
the software, you will break the overall program-
feedback algorithm. This example should make you ming job
down into modules which can be individually
aware of the advantages of computer feedback control. tested and debugged as we have described previously.

ANALOG INTERFACING AND INDUSTRIAL CONTROL 355


For the hardware there are several different approaches some work to do when you get the prototype printed cir-
vou can take. cuit boardback.
After you stuff the board with the required parts vou
can power it up and check for hot or otherwise unhappy
Using a Microcomputer-Prototyping Board components. If there are no apparent problems you can
proceed to test the board. Probably the best tool to test
One approach is to use a commercially available micro-
the board with is an emulator.
computer-prototyping
such as board
the SDK-86 we
used for the examples in this chapter. An advantage of
this approach is that it gives you the basic CPU. RAM,
ROM. and ports already tested. You can then easily add Using an Emulator
any needed timers, priority interrupt controllers, and Figure 3-12 shows a picture of an Applied Microsystems
other interface circuitry. Some of the available prototyp- ES 1800 emulator which works with the IBM PC and
ing boards such as the SDK-86 have on-board monitor other compatible computers. Several other companies
programs which let you load and execute your pro- make similar emulators. The hardware of an emulator
grams.major
The advantage of this approach is that it consists of control circuitry, memory to store the trace
allows you to quickly get a prototype up and running to data after each instruction executes, and an "umbilical"
see if the instrument is feasible. If the instrument is cable with a plug at the end of it. To use the emulator
feasible you can then design a custom hardware board you remove the microprocessor from the prototype unit
which exactlv fits vour needs. and insert the plug at the end of the umbilical cable in
its place. The emulator contains a microprocessor
which will actually run your test programs under con-
Computer-Aided Design Approach trol the
of emulator. The emulator then gives you a win-
dow intothe operation of the circuitry on the prototype
Another approach to creating the needed hardware for
under control of a development system or PC.
the prototvpe is with a computer-aided design or CAD
The software of the emulator is similar to a powerful
system. This system may be a large and powerful engi-
monitor program or debugger program. You can use the
neering workstation
such as those made by Mentor
emulator commands and the system memory to test
Graphics, or simply an IBM PC-type computer with pro-
each part of the prototvpe. For example, you can write a
grams such
as the PCAD system from Personal CAD Sys-
short program to test the RAM in the prototvpe. load
tems. Inc..
Electronic Design Automation Division. The
this program into the system RAM. and run the pro-
programs on these systems allow you. first of all. to eas-
gram underemulator control. To help with debugging,
ily designand draw a schematic for your hardware. You
emulators allow you to set breakpoints, examine and
can just select the schematic symbol for a part you want
change the contents of registers and memory locations,
to use by number from a large library of common devices
and do a trace which shows the contents of registers
in a disk file and bring it on to your CRT screen. You use
after each instruction executes. Some emulators have
a "mouse" to move the symbol into position and to draw
an additional pod like those used on logic analyzers so
signal lines connecting it to other symbols. You can
that you can do a trace of the sequence of hardware sig-
move a device around as needed, and the connecting
nals on
a group of lines to check timing.
signal lines will follow.
An important point here is that, just as we stressed
When you get the schematic drawn up. you can then
with building programs, the fastest way to get a proto-
use another program in the CAD system to simulate the
tvpe debuggedand operating is one small part at a time.
operation of the circuit. By simulate we mean to "run"
the circuit in software. This helps you to find out if the
Because problems tend to interact, trying to debug too
large a section at a time can be frustrating and time-
signals are connected correctly, and il timing parame-
consuming. Therefore, remove all but the basic CPU
ters are
acceptable. If the circuit passes simulation, vou
group ICs for your first test then keep adding, testing
can make a printout of the schematic on a printer or
plotter.
and debugging one section at a time. As you get a hard-
ware section
working, you can if you want write and
The next step is to design a printed circuit board for
debug the software module which uses or drives that
your circuit. Another program in the CAD system will.
hardware module. To give you a better idea of how to do
with a little help from you. produce the artwork for the
this development process, we will briefly describe the
printed-circuit board. Some systems will even produce
steps we went through to develop the process-control
the control tape for the machine which automatically
drills the required holes in the printed circuit board.
system discussed earlier in this chapter.
The time is not too far away when the engineering work-
stationbecanconnected directly to the printed-circuit-
board-making machine, the machine that gets parts A Product Development Example
from the warehouse, the machine that stuffs the parts For our process-control demonstration system we
in the printed circuit board, and the machine that does started with an SDK-86 board because we only wanted
the initial functional tests on the board. This concept, to make one unit, and because we did not have CAD
incidentally, is called computer integrated manufactur- equipment and a printed-circuit-board-making ma-
ing or
CIM and seem> to be where the industry is head- chine. the
For controller we needed a timer to produce
ing, but
it isn't quite there yet. Therefore, you still have 1-kHz thick ticks and a priority interrupt controller to

356 CHAPTER TEN


handle keyboard and clock tick Interrupts We added binary t" li< I' conversion routine and run the resull
these two devices and some address decode] cii cuitry ii> with the emulator. This was a previously written and
the SDK 86 as shown In Figure 8 14, and proceeded to tested module, and when added, the result worked fine.
test this circuitry with an emulator, ro do this we wrote Next we added a couple ol instructions to turn the
a shorl program which wrote a byte to the starting ad heatei on during one execution ol loop 0 1 turn the
dress for the timer over and ovei again. We ran this pro- In alii off during the next time through loop 0 We then
gram with
the ciniil. inn .iiul with .i scope we checked to used an oscilloscope to check that the solid state relay
sec if the IS inpul ni the timer was getting asserted. It was getting turned on and oil correi tly
was, so we knew thai the . nidi ess decoding circuitry was Finally, we added the actual duty cycle and control
working correctly. We then connected the 2.45-MHz Instructions, and sal hack waiting foi the system to
P( ILK signal to the clock inputs ol all three timers in the heat us up a big container ol water lor lea
8254 and wrote the instructions needed to initialize the The actual development cycle will obviously he some
three timers foi l kHz square-wave output. Even what different lot every instrument developed. The main
though we only need one timer here, il was very little points hen- an- to develop and lest both the hardware
additional work to (heck the other two lor future refer- and software in small modules. To speed up the debug
ence. Hooray,the timers worked the first time, now on ging process, take the tunc to learn to use all or most ol
to the 8259A PIC. the power of the emulator and system von arc working
Testing the 8259A was a little more complex because with.
we had to provide an interrupt signal, initialize the
8259A. initialize the interrupt vector table in low RAM.
and provide a location for execution to go to when the DIGITAL FILTERS
I'K' received an interrupt. We used the 1-kHz clock tick
from the timer as the interrupt signal to the 8259A. For A section at the start of this chapter showed how op
8259A initialization and the interrupt jump table ini- amps can be used to build high-pass and low-pass filter
tialization
used we the instructions in the mainline pro- circuits. Filtering of a signal can also be done by taking
gramFigure
in 10-35. For the test-interrupt procedure samples of the signal with an A/D converter, performing
we actually used a real-time clock and display procedure mathematical operations on the samples from the A/D
that we developed lor examples in previous chapters. We converter, and outputting the result to a D/A converter.
used these so that we could see if the interrupt mecha- This approach, referred to as a digital filter, can easily
nism was
working correctly by watching the displays on produce a response curve which is difficult, if not im-
the SDK-86 count off seconds. This again shows the possible,
produce
to with analog circuitry. This digital
advantage of writing programs as separate reusable approach has the further advantage that the filter re-
modules. Note in the program in Figure 10-35 that we sponsebecanchanged under program control. Digital
initialize the 8259A before we initialize and start the filters are used in speech synthesizers, satellite image-
timer. When we first wrote a test program to test an enhancement systems, and many other applications.
8259A and an 8254. we did this in the reverse order. There are two basic types of digital filter, the Jmite
When we ran the test program with the emulator, the impulse response or FIR type and the infinite impulse
system would only accept one interrupt and hang up. response or IIR type. The basic principle of a digital filter
We did a trace with the emulator and found that execu- is to operate on the samples as a function of time rather
tion was
returning from the interrupt procedure to the than as a function of frequency as the analog filter does.
WAIT loop in the mainline program properly, but not Figure 10-37a shows a functional diagram of the op-
recognizing the next interrupt. Careful reading of the eration
an FIR-type
of filter. The box containing Z ' rep-
8259A data sheet showed us that we had to initialize the resents
delaya of one sample interval. Circles contain-
8259A before we started sending it interrupt signals, or ing anX represent a multiplication operation, and the
it would not respond correctly to the nonspecific EOl letters to the left of each circle represent the number
command that we used at the end of the interrupt pro- that the term will be multiplied by. Y0 represents the
cedure
resetto the 8259A's in-service register. value of the current sample from the A/D. Yt represents
After the interrupt mechanism was working correctly, the value of the previous sample from the A/D, and Y2
we wrote the interrupt procedure which implements the represents the value of the sample before that. Here's
decision structure shown in Figure 10-325. Initially we how this works. The output value, V, at any time is pro-
made all eight loops dummy loops to test the basic ducedsumming
by the (current sample x some coeffi-
structure. By inserting breakpoints with the emulator cient)
(the+ previous sample x some coefficient) * (the
we were able to see if execution was getting to each of sample before that • some coefficient), etc. To do all of
the eight loops. When all of this was working, we went this with a microprocessor involves simple operations of
on to build and test the temperature-control section. saving previous samples, multiplying, and adding. The
For the temperature-control section we first built the Intel 2920 microprocessor, which was specifically de-
analog circuitry and tested it. Then we wrote a small signedthis
for type of operation, contains an A/D con-
program to read the temperature from the A/D converter verter.converter,
D/A and an architecture and instruc-
and display the result on the SDK-86 displays. Initially tion set
which works with the 25-bit numbers required
then, the loop 0 procedure simply read in the tempera- for accurate filter response.
ture, displayedit in binary (hex) form and returned. Figure 10-37b shows a functional diagram for an IIR
This worked the first time, so we went on to add the digital filter. Here again the blocks containing Z ' rep-

ANALOC INTERFACING AND INDUSTRIAL CONTROL 357


Op amp

Comparator

•- 0 X ) A,-^ X Hysteresis

Noninverting amplifier
I— I
-4---H z' I— -*--- H z ' i— -*- Inverting amplifier
i i I 1
Virtual ground

Gain-bandwidth product

Unity-gain bandwidth
Adder circuit — summing point

Differential amplifier
Common-mode signal, common-mode rejection

Instrumentation amplifier

Op-amp integrator circuit


Linear ramp
Saturation

FIGURE 10-37 FIR and IIR digital filter principles, (a) FIR. Op-amp differentiator
lb) IIR. Op-amp active filters
Low-pass filter, high-pass filter, bandpass
filter
resent a delay of one sample time. The value of the cur-
Critical frequency or breakpoint
rent samplefrom the A/D converter is represented by the
Second-order low-pass filter, second-order high-pass
X at the left of the diagram. The Y0 point represents the filter
output from the microprocessor to the D/A converter.
Note that for an IIR filter it is this output value which is Light sensor
saved to be used in computing feedback terms for future Photodiode
samples. In the FIR type, remember, the samples from Solar cell
the A/D converter were saved directly for future use. The
Temperature-sensitive voltage sources
output for an IIR type is produced by summing Ithe cur-
rent sample* a calculated coefficient) + (the previous Temperature-sensitive current sources
output value x a calculated coefficient! + (the output
Thermocouples
value before that • a calculated coefficient), etc. The
Type J thermocouple
coefficients for both the FIR- and the IIR-type filters are
Cold-junction compensation
usually calculated using a computer program. FIR filters
are easier to design, but they may require many terms to Force and pressure transducers
produce a given filter response. IIR filters require fewer Strain gage, LVDT. load cell
stages, but they have to be carefully designed so that
Flow sensors
they do not become oscillators.
Paddle wheel, differential pressure transducer
A new type of filter called a switched capacitor filter
implements digital filtering for simple filter responses D/A converters
without the need for the A/D and D/A converter. An ex- Binary weighted
ample
the is National MF10. In this type of filter an Resolution
input signal is sampled on a capacitor. The signal is Full-scale output voltage
passed on to other capacitors and fractions of the out- Maximum error
puts from
these capacitors are summed to produce an Linearity
analog output signal directly. Switched capacitor filters Settling time
are less expensive, but they do not give the degree of
programmability that the microprocessor-based filters A/D converters
Conversion time
do.
Parallel-comparator A/D converter
Dual-slope A/D converter
IMPORTANT TERMS AND CONCEPTS Successive-approximation A/D converter
FROM THIS CHAPTER Data acquisition system

If you do not remember any of the terms in the following A/D output codes
list, use the index to help you find them in the chapter Unipolar binary code, unipolar BCD code, biopolar
for review. binarv code

358 CHAPTER TEN


Direct memory access Robotics

Sti point Digital filters


Finite impulse response [FIR), infinite impulse
Servo conti ol
response (IIR)
Settling time, underdamped, overdamped
Switched capacltoi filter
Residua] ei ror
( iiinpuici aided design
Proportional-integral-derivative control loop, I'll) Simulate

Time slice < omputei integrated manufacturing, C1M


On oil control Emulator

REVIEW QUESTIONS AND PROBLEMS


1. a. A comparator circuit such as the one In Figure 5. Why must thermocouples be cold-junction com
10- lb is powered by i 15 V, the inverting input pensated in order to make accurate measure-
is tied to + 5 V, and the noninverting input is at ments?can
Howthe nonlinearity of a thermocou-
+ 5.3 V. About what voltage will be on the out- ple be
compensated for?
put the
of comparatoi ?
6. Why are strain gages usually connected in a bridge
b. An amplifier circuit, such as the one in Figure
configuration? Why do you use a differential ampli-
10-ld. has an Kl of 10 kil and an R2 of 190
fieramplify
to the signal from a strain-gage bridge?
kil. Calculate the closed-loop voltage gain for
the circuit and the V,,,,, that will be produced by 7. Calculate the full-scale output voltage for the sim-
a Vm of 0.030 V. What voltage would you mea- ple D/A
converter in Figure 10-14.
sure on
the inverting input':' What would be
8. What is the resolution of a 13-bit D/A converter? If
the gain of the circuit if R2 = 0 SI.
the converter has a full-scale output of 10.000 V,
c. An amplifier circuit, such as the one in Figure
what is the size of each step? What will be the ac-
10- 1e, is built with an R 1 of 15 ki 1 and an R, of
tual maximum output voltage of this converter?
75 kfi. Calculate the closed-loop voltage gain
What accuracy should this converter have to be
for the circuit and the output voltage for an
consistent with its resolution.
input voltage of 0.73 V. What voltage will you
always measure on the inverting input of this 9. Why must a 1 2-bit D/A converter have latches on its
circuit? inputs if it is to be connected to 8-bit ports or an
d. A differential amplifier, such as the one in Fig- 8-bit data bus?
ure 10-
\g, is built with Rl = R2 = 100 kil and
R, = R3 = 1 Mil. V, is 4.9 V and V2 = 5.1 V. 10. Describe the operation of a "flash" type A/D con-
Calculate the output voltage and polarity. verter. What
are its main advantages and disadvan-
e. Describe the main advantage of the instru- tages?
mentation amplifier
in Figure 10- In over the
11. For the dual-slope A/D converter in Figure 10-19.
simple differential amplifier in Figure 10- lg.
what will be the displayed count for an input volt-
/. II the amplifier used in the circuit in Question
age2.372
of V? What is the resolution of a 4 '/i-digit
lb has a gain-bandwidth product of 1 MHz,
slope-type A/D converter expressed in bits?
what will be the closed-loop bandwidth of the
circuit? 12. How many clock cycles does a 12-bit successive-
approximation A/D converter take to do a conver-
2. Draw a circuit showing how a light-dependent re-
sion aon0. 1-V input signal? On a 5-V input sig-
sistor be
can connected to a comparator so the out-
nal? How
does this compare with the number of
put of
the comparator changes state when the re-
clock cycles required for a 12-bit dual-slope type?
sistance
the ofLDR is 10 kil.
13. n. Assume the inputs of the MC1408 D/A con-
3. For the photodiode amplifier circuit in Figure 10-5,
verter
Figure
in 10-20 are connected to an out-
what voltage will you measure on the inverting
put port
on your microcomputer board and the
input of the amplifier? Why is it important to use
output of the comparator is connected to bit DO
an FET input amplifier for this circuit? Which di-
of an input port. Write the algorithm for a pro-
rection
electrons
are flowing through the photodi-
cedure
do toan A/D conversion by outputting
ode?
an incrementing count to the output port,
4. In what application might you use a temperature- b. Write an algorithm for a procedure to do the
dependent current device such as the AD590 conversion by the successive approximation
rather than a temperature-dependent voltage de- method. Which method will produce a faster
vice such
as the LM35? result? If the hardware is available, write the

ANAtOC INTERFACING AND INDUSTRIA1 CONTROt 359


programs for these algorithms and compare 19. Describe how feedback helps hold the value of some
the times by watching the comparator output variable, such as a motor speed, constant. Refer to
with an oscilloscope. Figure 10-27 in your explanation.

Show the detailed algorithm for the procedure you 20. What problem in a control loop does integral feed-
would use to read in the data from a multiplexed back help
solve? Why is derivative feedback some-
BCD output A/D converter such as the MC 14433 in times added
to a control loop?
Figure 10-23 and assemble the value in a 16-bit
21. What is the major advantage of a microcomputer-
register for display.
controlled loop over the analog approach shown in
The data sheet for an A/D converter indicates that Figure 10-29?
its output is in offset-binary code. If the converter
22. Suppose that you want to control the speed of a
is set up for a range of -5 to +5 V and the output small dc motor, such as the one in Figure 10-27,
code is 01011011, what input voltage does this
with LOOP1 of our microcomputer-based process
represent? How could you convert this code to 2's
controller.
complement form after you read the code into your a. Show how you would connect the output from
microcomputer? the motor's tachometer to the system in Figure
!(,. Write a procedure to round a 32-bit BCD number in 10-33. Also show how you would connect an
DX:AX to a 16-bit BCD number in DX. 8-bit D/A to control the current to the motor.
fa. Write a flowchart for the LOOP1 procedure to
For the scale circuitry in Figure 10-23, what voltage control the speed of the motor.
should you measure on the inverting input of the c. Describe how a lookup table could be used to
LM308 amplifier? What voltages should you mea- determine the feedback value.
sure the
on two inputs of the LM363 amplifier with
no load on the scale? What voltage should you mea- 23. Describe the major difference in how the feedback
sure the
on output of the LM363 with no load on is produced in an FIR digital filter and how it is
the scale? produced in an IIR filter.

The section of the scale program following the label 24. When developing a prototype, why is it very impor-
NXTKEY in Figure 10-35 moves some bytes around tant build,
to test and debug both software and
in memory. Rewrite this section of the program hardware in small modules?
using an 8086 string instruction to do the move
operations. Which version seems more efficient in
this case?

360 CHAPTER TEN


CHAPTER

Multiple Microprocessor
Systems and Buses

The major point of the first six chapters ol this book was Use a inning diagram to describe how control ol the
to introduce you to structured programming and to bus is transferred from one ( TU board on the bus to
writing 8086 assembly language programs. Chapters 7 another.
through 10 introduced you to the hardware of an 8086
minimum-mode system, showed you how to interface a
microcomputer to a wide variety of input and output THE 8086 MAXIMUM MODE
devices, and finally demonstrated how all of these pieces
are [nit together to build a microcomputer-based instru- Many of the circuits shown in this chapter and the fol-
mentsimple
or control system. The major theme of lowing chapters
use the 8086 or 8088 in its maximum
Chapters 1 1 through 14 is to show you how larger mi- mode. Therefore, we start this chapter with a discussion
crocomputerare
systems
built and programmed. As of maximum-mode operation.
some of the parts of this we show you how large memory Figure 11-la shows the pin diagram of the 8086
banks are added to a system, how multiple processors again. You may remember from our discussion in Chap-
are used in a system, how you interface to more complex terthat
7 if pin 33. the MN/MX pin is tied high, the 8086
peripherals such as disk drives, and how systems com- operates in its minimum mode. In minimum mode the
municate
each
withother. We also discuss the system 8086 generates control-bus signals directly. Specifically,
programs used to coordinate all of (his. for pins 24—31, the 8086 in minimum mode generates
the signals identified in parentheses in Figure 1 1-1 n.
If the MN/MX pin is tied low. the 8086 operates in its
OBJECTIVES maximum mode and pins 24-31 generate the signals
named next to the pins in Figure 11-la. In maximum
At the end of this chapter you should be able to:
mode the control-bus signals are sent out in coded form
on the status lines. SO. S1, and S2. As shown in Figure
1. Show how an 8086 is connected with a controller
11-lb, an external controller device such as the Intel
device for operation in its maximum mode.
8288 is used to produce the required control-bus sig-
2. Show how a direct memory access (DMA) controller nals fromthese lines. Figure 11-lb shows the expanded
device can be connected in an 8086 system and de- names for each of the control-bus signals generated by
scribe how
a DMA data transfer takes place. the 8288. Note in Figure 11-lb that we use 8282 octal
latches to demultiplex the address signals and 8286 bi-
3. Describe how large banks of dynamic RAM can be directional to
drivers
buffer the data bus so that it can
connected in a system and how automatic error- drive a board full of devices. Figure 1 1-lc shows the sta-
correcting circuitry works with this memory. tus linecodes for each type of machine cycle.
4. Describe the added architectural features of the The request/grant pins. RQ/CTO and RQ/CT1. are used
80186 microprocessor.
by other devices to tell the 8086 that they want to use
the address, data, and control buses. These pins arc
5. Show how a coprocessor can be connected to an bidirectional. They operate in a similar way to that in
8086 or 8088 operating in maximum mode. which the HOLD and HLDA pins operate when some
other device wants to borrow the buses in an 8086
6. Describe the operation of the 8087 math coproces-
minimum-mode system. We will show you how these
sor, and
write simple programs for the 8087.
signals work in a later section on the 8087 coprocessor.
7. Show how several CPU boards can be connected to A signal can be sent out from the 8086 on the LOCK pin
share a common set of buses, and describe how data under program control (the LOCK prefix) to prevent
is transferred on this common bus. some other device from taking over the bus during exe-

361
GMDC 1 ^ 40 3
AD14C 39 J AD15

AD13C 38 J AD16S3

AD12 C : 37 3 AD 17 S4

AD1 1 C b 36 b A18/S5

AD10C 6 35, j A19/S6

AD9 C 7 34 j BHE/S7

AD8C 8 33 3 MN MX

AD7 n 9 32 3 RD s2 s, s0
AD6C 10 8086 ;:1 3 RQ GTO (HOLD)
O(LOW) 0 0 INTERRUPT ACKNOWLEDGE
AD5 C i ' CPU 30 3 RQ GTT(HLDA) 0 0 1 READ I/O PORT
AD4 Q 12 ,"i 1 LOCK (WR) 0 1 0 WRITE I/O PORT
0 1 1 HALT
AD3 C ' J 3 S2 (M/10) 1 (HIGH) 0 0 CODE ACCESS
AD2 C 14 .'/ 1 ST (DT/R) 1 0 1 READ MEMORY
1 1 0 WRITE MEMORY
adi n 15 26 3 SO (DEN) 1 1
1 PASSIVE
ADOC 16 ." -J QSO (ALE)

NMI C 17 3 QS1 (INTA)

INTR C 18 J J TEST

CLK ["" 19 .% J READY

GND C 20 'J RESET

j^L MRDC
LOCAL

MEMORY
BUSES

READ

CLOCK
MWTC MEMORY WRITE
GENERATOR

AMWC ADVANCED MW
8288
BUS IORC I/O READ
CTRLR
iowc I/O WRITE

AIowe ADVANCED I/O W

INTA INTERRUPT
ACKNOWLEDGE

1 MEGABYTE
ADDRESS BUS

FIGURE 11-1 8086 Revisited, la) 8086 pin diagrarn. (b) Circuit showing 8086
connections tor MAX mode operation, tc) S2, S1, and SO codes for 8086
machine cycles iIntel Corporation)

362 CHAPTER ELEVEN


cution of a critical Instruction. The queue status sig Circuit Connections and Operation of the Intel
nals. QS1 and QSO. Indicate the operation most recently 8237 DMA Controller
done to the Instruction-byte queue In the 8086 BIU.
W( chosi thi '% / DMA controllei as the example for
These signals allow an external device such .is the 8087
ihis section be< ause il is a < nonly used device, and
math coprocessor, which we discuss latei in this chap
because H is one ol the devices you will find il you starl
ter, to monitor the 8086 queue and read the same In
poking around inside an IBM PC oi PC AT. I lowever, be
struction bytes as the 8086 Now we will show you some
fore we dig into the actual < onnections and operation ol
ol the ways thai a micropi ocessoi can share lis buses m
.a i 8237 i Ircuit, let's take a look a i the bloi
iinmimiiii mode and m maximum mode.
figure I 1-2 to net an overview of how a DMA transfer
lakes place. The main poinl to keep in youi mind here is
simply thai the microprocessor and the DMA controller
DIRECT MEMORY ACCESS (DMA) DATA time-share the use ol the address, data, and control
TRANSFER buses. We have tried to indicate this with the three
switches in the middle ol the block diagram. I lere's how
DMA Overview a transfei lakes place.
Up to this point in the book we have used program in- When the system is first tinned on, the switches are
structions
transferto data from pons to memory, or in the position where the buses are connected from the
from memory to ports. For some applications, such as inn roprocessoi to system memory and peripherals. We
transferring data bytes to memory as they are read off a initialize all ol the programmable devices in the system
magnetic or optical disk, however, the data bytes are and go on executing our program until we need to. for
being sent from the disk taster than they can be read in example, read a file ofl a disk. To read a disk file we send
with program instructions. In a ease like this we use a a series oi commands to the smart disk-controller de
dedicated hardware device called a direct memory ac- vice, Idling it to go find and read the desired block of
cess controller. A DMA controller temporarily borrows data from the disk. When the disk controller has the
the address bus. data bus, and control bus from the first byte of data from the disk block ready, it scuds a
microprocessor and transfers the data bytes directly DMA request (DREQJ signal to the DMA controller. If that
from the port to a series of memory locations. Because input (channel) of the DMA controller is unmasked. tin-
the data transfer is handled totally in hardware, it is DMA controller will send a hold-request (HRQ) to the
much faster than it would be if done by program in- microprocessor HOfD input. The microprocessor will
structions.
DMA controller
A can also transfer data from respond to this input by floating its buses and sending
memory to a port. Some DMA devices can also do out an hold-acknowledge (HLDAI signal to the DMA
memory-to-memory transfers. Here's an example of how controller. When the DMA controller receives the HLDA
a common DMA controller is connected and used in an signal it will send out a control signal which throws the
8086 minimum-mode system. three bus switches to their DMA position, disconnecting

_ ., %%
I

ADDRESS
LATCHES

AD0-AD15 '

Al n (RE S lit '''•


ALE ^°~

^°-

CONTROL BUS
CONTROL BUS
IQR. IQW
HLDA HOLD MEMW, MEMR

HRQ
DMA CONTROL BUS
CONTROLLER
IQR. IQW SMART
PERIPHERAL
MEMW, MEMR
leg DISK
DEVICE
CONTROLLER)

DACKO

FIGURE 11-2 Block diagram showing how a DMA controller operates in a microcomputer system.

MULTIPLE MICROPROt I SS( )R s~i STEMS AND BUSES 363


the processor from the buses. The DMA controller then come from the 8086 bus. The 8237 directly outputs the
outputs on the address bus the memory address where lower 8 bits of the memory address for the DMA transfer.
we want the byte of data from the disk controller to go. Secondly. AEN. going high, switches the strobe multi-
Next the DMA controller sends a DMA-acknowledge plexer
that
so the strobe for device L72 comes from the
(DACK01 signal to the disk-controller device to tell it to address strobe output of the 8237. To save pins, the
get ready to output the byte. Finally . the DMA controller 8237 outputs the upper 8 bits of the memory address for
asserts both the MEMW and the IOR lines on the control the DMA transfer on its data-bus pins and asserts its
bus. Asserting MEMW enables the addressed memory ADSTB output high to let you know that this address is
for writing data to it. Asserting IOR enables the disk present there. At the start of a DMA transfer, then,
controller to output the byte of data from the disk on the memory address bits A1 5-A8 will be sent out by the 8237
data bus. The byte of data will then be written to the and latched on the outputs of L72.
addressed memory location. Still another effect of AEN going high is to switch the
source of address bits A19-A16 from device UA to device
NOTE: For this type of transfer the disk controller
U3. The DMA controller does not send out these address
chip-select input does not have to be enabled by the port
bits during a DMA transfer, so you have to produce
address decoding circuitry as it does for normal reading
them in some other way. You can either hard-wire the
from and writing to registers in the device. In fact, the
inputs of L73 to ground or +5 V to produce a fixed value
normal port-decoding circuitry is disabled during DMA
for these bits, or you can connect these inputs to an
operations to prevent the combination of IOR and the
output port so you can specify these address bits under
output memory address from turning on unwanted
program control.
ports. Finally. AEN, going high, switches the source of the
When the data transfer is complete the DMA controller control-bus signals from the outputs of the control-bus
unasserts its hold-request signal to the processor, and decoder circuitry to the control-bus signal outputs of
lets the processor take over the buses again until an- the DMA controller. This is necessary because, during a
other DMAtransfer is needed. The processor then con- DMA transfer, the 8237 generates the required control-
tinues executingfrom where it left off. A DMA transfer bus signals such as MEMW and IOR. Incidentally, the
from memory to the disk controller would proceed in a NOR gate decoder circuitry in the upper right corner of
similar manner except that the DMA controller would the schematic is necessary to produce processor
assert the memory-read control signal (MEMR). and the control-bus signals compatible with those from the
output-write control signal (IOW). DMA transfers may 8237.
be done a byte at a time or in blocks. The final part of the circuit in Figure 1 1-3 to analyze is
Now, to give you more practice working your way the two 8286 octal bus transceivers. The disk controller
through actual microprocessor circuits, let's look at Fig- has only an 8-bit data bus output. If we connected these
ure
1 -3
1 to see some of the circuitry we might add to an eight lines on the lower eight data bus lines of the 8086
8086 system so that we can do DMA transfers to and system, the DMA controller could only transfer bytes to
from a disk controller. This circuitry is simply a more even addresses. Likewise, if we connected the disk-
detailed version of the block diagram in Figure 11-2. controller data outputs on the upper eight data lines of
The first thing to do in analyzing this schematic is to the 8086 system, the DMA controller could only transfer
identify the major devices and relate their function. bytes to odd addresses in memory. To solve this prob-
where possible, to the block diagram. The 8086 and lem, we
connect the two 8286s as a switch which can
8284 should be old friends from your exploration of the route data to/from the disk controller from/to either odd
SDK-86. The 8237 is. of course, the DMA controller, and or even addresses in memory. AO determines which half
the 8272 is the floppy-disk controller. We will discuss of the data bus is connected to the eight data pins of the
the operation of the disk controller in the next chapter, disk controller. Now let's look at the signal flow and tim-
but for now all we need to know about it is an overview of ing forthis circuit.
how it interacts with the 8237 as we described above.
The 8282s in this circuit are octal latches with three-
state outputs. They are used here to latch addresses A DMA Transfer Timing Diagram
output from either the 8086 or from the DMA controller. Figure 1 1-4 shows the sequence of signals that will take
These devices are controlled by ALE from the 8086 and place for a DMA transfer in a system such as that in
by AEN and ADSTB from the DMA controller. Figure 11-3. Keep a copy of the circuit handy as you
When the power is first turned on. the address- work your way down through these waveforms. The la-
enable signal (AEN) from the DMA controller is low. De- bels we
have added to each signal should help you. We
vices Ul,
VI. and UA are then enabled, and the ALE sig- will pick up where the 8237 asserts AEN high and gains
nal from the 8086 gets to the strobe inputs of all three control of the buses. After the 8237 gains control of the
devices. When the 8086 sends out an address and an bus it sends out the lower 8 bits of the memory address
ALE signal, these three devices will grab the address and on its A7-A0 pins, and the upper 8 bits of the memory-
send it out on the address-bus lines. A19-A0. This is just address on its DB0-DB7 pins. The 8237 pulses ADSTB
as would be done in a simpler 8086 system. Now. when high to latch these address bits in the 8282. and then
tin DMA controller wants to take over the bus. it asserts removes these address bits from the data bus. At about
its AEN output high. This does several things. First, it the same time the 8237 sends a DACK signal to the disk
disables device L71 so that address lines A7-A0 no longer controller to tell it to get ready for a data transfer. Now

364 CHAPTER ELEVEN


A19 A16

_J+h HHI

.'.
READY
M 10
CLK

RESET
AD15 AD8
-0° - IN do

.T3_| t>
A07 ADO
UPPER
Oil U3
DMA
D12 8282
0C1 M
D'3 LATCH

8286
BIDIRECTIONAL
BUFFER
B282
OCTAL
'

LATCH
^>T>
%• U6
8286
ADDRESS c RECTIONAL MEMORY
BUFFER AND
STROBE
pi m rs

-/- D0 D7
1 .
-/- A8 A15

>— L i Lt ADSTB
MEMW

MEMR
RESET A[ I;

DB7-0 HREQ
HLDA A 7-0
DREQ0 [OR
8272
DREQ1 DISK
DISK DRIVE
IOW
CONTROL
CONTROL AND
DREQ2 mTmw CHIP
DATA SIGNALS

DREQ3 MEMR

FROM
PORTDECODER>- <:% DACK0 DACK

DACK1 I I l

READY DACK2

EOP DACK 3

FIGURE 11-3 Schematic for 8086 system with 8237 DMA controller and 8272
tloppy-disk controller.

that everything is ready the 8237 asserts two control- a second transfer is done, unless those bits have to be
bus signals to enable the actual transfer. For a transfer changed. This saves time during multiple-byte trans-
from memory to the disk controller, it will assert MEMR fers.
and IOW. For a transfer from the disk controller to When the programmed number of bytes have been
memory, it will assert MEMW and IOR. Note that the transferred, the DMA controller pulses its end-of-proc-
8237 does not have to put out an I/O address to enable ess (EOP) pin low. unasserts its hold request to the
the disk controller for this transfer. When programmed 8086. and drops its AEN signal low to release the buses
in DMA mode, the disk controller needs only IOR or IOW back to the 8086. Now that you have an idea how an
to be asserted to enable it for the transfer. Also note that 8237 is connected and operates in a system, we will give
the 8237 will not output a new address on A8-A15 when vou an overview of what is involved in initializing it.

MULTIPLfc MICROPROCESSOR SYSTEMS AND BUSES 365


DREQ
FROM 8272 zz T ssx
HRQ8237
TO 8086 /h A
HLDA
FROM 8086 mr v S2 X
AEN
823/ f V
ADSTB
8237 y~\
DB0-DB7
YA8-A15V
FROM 8237

-( ADDRESSVALID^ ADDRESSVALID
)-

/ V
\ y— v 7^
j-
\^r
INT EOP \ r
FIGURE 11-4 Timing diagram for 8237 DMA transfer. (Intel Corporation)

8237 Initialization Overview


1 l-5c shows the internal addresses you use when you
Initializing an 8237 is not difficult, but it does require a send or read addresses and counts to/from the 8237.
fairly large number of bytes. Therefore, we do not have Note that the low byte and the high byte of. for example,
space here to show you a complete initialization. What the base memory address are written to the same inter-
we can do is give you an overview so that, hopefully, the nal address in the 8237. The 8237 keeps track of which
data sheet will make more sense to you if you do have to byte is being sent or read with an internal first-last flip-
initialize one. flop. If the flip-Hop is reset then the 8237 assumes that
As shown by the pin labels on the 8237 in Figure 1 1 -3. the byte being sent or read is the least-significant byte.
the 8237 has four DMA request inputs or channels, as If the first-last flip-flop is set. the 8237 assumes the byte
they are commonly called. To initialize an 8237 you need being sent or read is the most significant byte. The first-
to send it a command word which specifies the general last flip-flop is automatically toggled after each write to a
operation. You also need to send it mode words, starting particular address so you can just write to an internal
transfer addresses, and the number of bytes to be trans- address twice to send a full 16-bit count. It is important
ferredeach
for channel you are using. Figure 11 -5a to understand this mechanism so that you remember to
shows the names of the different types of registers used keep track of the state of the first-last flip-flop as you
to hold this data in the 8237. the number of bits in each send counts and addresses to the device. Also, at the
type of register, and how many registers of that type the start of the initialization before you read or write any
device has. Register names with a 4 next to them have a words, it is a good idea to send the device a command
register of that type for each channel. Now that you which resets the first-last flip-flop. You do this by writ-
know about all of these registers, the next question is ingbyte
a to internal address 1 100 as shown in Figure
how do you write to or read from all of them. 1 l-5b. The contents of the byte written don't matter, it
The 8237 is connected in a system as a port device, so is the act of writing to the particular address which re-
you write initialization words to it just as you would to sets theflip-flop. Here's the order in which you might
any other port device. The lower four address bits. A3- send initialization words to an 8237. Consult the data
A0, together with the inputVoutput read signal. IOR, and sheet in an Intel data book to get the details of each
the input/output write signal, IOW. determine which command word.
internal register you write to or read from. Figure 1 l-5b
shows the internal addresses that you use when send- I. Output a master reset command word to internal
ing commands to and reading the status byte. etc. from address 1101. The actual word written doesn't mat-
an 8237. We'll come back to these in a minute. Figure ter: thecommand resets the first-last flip-flop.

366 CHAPTER ELEVEN


I ION
A i A2 A1 AO IOR IOW

0 II 0 HI ..i- MA I ir, HI i .r II I-:

NAME SIZE NUMBER


0 0 ii 0 WRI II l IIMM.V, HIM H f-

RAM .\imni :,: HI nIM i M. 16 BITS I 0 0 0 ILLEGAL

BASE WORD COUNT REGISTERS li, 111 :: 1 0 0 0 WRI II HI Ml! SI HI MM! H

CURRENT ADDRESS REGISTERS iii m r. 4 0 1 0 0 ILLEGAL

CURRENT WORD COUNT REGISTERS 16 BITS 4 0 1 0 0 ..

TEMPORARY ADDRESS REGISTER 16 BITS 1 0 1 0 ILLEGAL

TEMPORARY WORD COUNT REGISTER 16 m rs 1 0 1 0 WRITE MODE REGISTER

STATUS REGISTER 8 BITS 1 u 0 ILLEGAL

COMMAND REGISTER H H 11S 1 li 0 CLEAR BYTE POINTER FLIP/FLOP

TEMPORARY REGISTER 8 BITS 1 ii 0 READ TEMPORARY REGISTER

MODE REGISTERS 6 BITS 4 n 0 MASTER CLEAR

MASK REGISTER 4 BITS 1 1 0 0 ILLEGAL

REQUEST REGISTER 4 Hill. 1 1 II 0 CLEAR MASK REGISTER

1 0 ILLEGAL

1 0 WRITE ALL MASK REGISTER BITS

SIGNALS
INTERNAL DATA BUS
CHANNEL REGISTER OPERATION FLIP-FLOP DB0-DB7
cs IOR IOW A3 A.' A1 AO

BASE AND CURRENT ADDRESS WRITE 0 0 0 0 0 0 0 A0-A7


0
0 1) II II I.I II A8-A15

CURRENT ADDRESS READ 0 0 0 II II 1) 0 A0-A7


0 u 0 1) 0 II A8-A15

BASE AND CURRENT WORD COUNT WRITE 0 0 0 II II 1 0 W0-W7


0 0 (I %¡ 1 W8-W15

CURRENT WORD COUNT READ 0 0 1.1 n I.) I 0 W0-W7


II 0 0 0 0 1 W8-W15

BASE AND CURRENT ADDRESS WRITE 0 0 0 0 0 A0-A7


1
0 0 0 0 0 A8-A15

READ 0 0 0 0 A0-A7
CURRENT ADDRESS
0 0 II 0 A8-A15

BASE AND CURRENT WORD COUNT WRITE 0 0 I.I 1 W0-W7


0 0 0 1 W8-W15

CURRENT WORD COUNT READ 0 0 0 1 W0-W7


0 0 11 1 W8-W15

2 BASE AND CURRENT ADDRESS WRITE 0 0 0 0 A0-A7


0 u II 0 A8-A15

READ 0 0 0 0 0 A0-A7
CURRENT ADDRESS
0 0 0 II 0 A8-A15

BASE AND CURRENT WORD COUNT WRITE ll 1.1 0 0 1 W0-W7


II 0 0 II 1 W8-W15

READ 0 LI I.I II 1 0 W0-W7


CURRENT WORD COUNT
II 0 0 0 1 W8-W15

BASE AND CURRENT ADDRESS WRITE 0 0 II 0 0 A0-A7


3
II 0 0 I! A8-A15

CURRENT ADDRESS READ 0 II 0 0 0 A0-A7


0 0 0 II A8-A15

BASE AND CURRENT WORD COUNT WRITE 0 0 0 1 0 W0-W7


0 0 0 1 W8-W15

CURRENT WORD COUNT READ 0 II 0 1 0 W0-W7


0 0 0 1 W8-W15

FIGURE 11-5 8237 registers and internal addresses, (a) Internal registers, (b)
Internal addresses for writing commands and reading status, fc) Internal
addresses for writing transfer addresses and counts. (Intel Corporation)

MULTIPLE MICROPROCESSOR SYSTEMS AND BUSES 367


2. Output a master command word to internal address The IBM PC Expansion Bus and DMA
1000.
To continue our evolution toward larger and larger mi-
3. Output a mode word for each channel you are using crocomputerwe systems
will now take a brief look at the
to internal address 1011. IBM PC. which is a multiboard system. Figure 11-6
shows a view of the component side of the main micro-
4. Output the starting memory address for the trans- processor board,
often called a motherboard, for the
fer, one
byte at a time, to the base register internal IBM PC. After you find the ROM. RAM. and microproces-
address for each channel you are using. sor onthis board, note the system expansion slots in the
5. Output the number of bytes you want to transfer to upper left corner. These slots allow you to add the spe-
the base word count internal address for each chan- cific functionboards you need in your system in addi-
nel youare using. tionthe
to basic CPU board. For example, you may want
to add a disk-controller board, a serial-port board, a
6. Output clear mask command word(s) to unmask the monochrome- or color-CRT board, a board with addi-
channel(s) you are using. tional memory',
an ADD/A board, or a board which al-
lows your
PC to function as a logic analyzer. This "open
Each channel of the 8237 can be programmed to trans- system" approach lets you easily customize the system
fer single
a byte for each request, a block of bytes for for your application and your financial state. Now let's
each request, or to keep transferring bytes until it re- see how these slots connect into the basic system.
ceives
wait a signal on the EOP input/output. 8237s can Figure 11-7 shows a block diagram for the mother-
be cascaded in a master-slave arrangement to give more board
theof IBM PC. Start on the left side of the diagram
input channels. As we said before, the main concept and work your way across it from the 8088 CPU and the
here is that the microprocessor and the DMA controller 8259A priority-interrupt controller. The next vertical
share the use of the address, data, and control buses. line of devices to the right consists of the address bus
As another DMA example we will now show you how buffers, the data bus buffers, and the 8288 bus-control-
the IBM PC is designed to allow peripheral boards to in- ler chip. The bus-controller chip is required because the
terface
a DMA
on basis. is operated in maximum mode. The buses from

CASSETTEI 0 KEYBOARD I 0

SYSTEM EXPANSION SLOTS \


IBM MATH
COPROCESSOR

SYSTEM BOARD
POWER CONNECTIONS

.CLOCK CHIP
TRIMMER
READ ONLY
MEMORY INTEL 8088
PROCESSOR

DIP SWITCH
BLOCK 2

DIP SWITCH
BLOCK 1

16 TO 64 K OR
64 TO 256 K
READ WRITE
MEMORY

CASSETTE MICROPHONE
OR AUXILIARY SELECT

FIGURE 11-6 Component layout diagram tor IBM PC motherboard.

368 ( HAPTERELEVEN
;

il^7

f * »

O-

3! T

<:
5Z

< ffl
v% /v
IT 3! 3! 31 311!

tH

TT ^t 7T 7?

1£ ai

TT

MULTIPLEMICROPROCESSORSYSTEMSAND BUSES 369


these devices go across the drawing and connect to the nectors should be easily recognizable to you. A + in
62-pin peripheral board connectors. The CPU then can front of a signal indicates that the signal is active high,
use these buses to communicate directly with the and a - indicates that the signal is active low. A0-A19
boards in the peripheral expansion slots. Now find the on the connectors are the 20 demultiplexed address
ROM in the lower right, the keyboard logic etc in the lines, and D0-D7are the eight data lines. IRQ2-IRQ7are
middle right, and the dynamic RAM in the upper right. interrupt request lines which go to the 8259A priority-
We will discuss this dynamic RAM later. Finally, take a interrupt controller so that peripheral boards can inter-
look at the column of devices which contains the 8237A- rupt the
8088 if necessary. Some other simple signals
5 DMA controller. Starting at the bottom of this column on the connectors are the power supply voltages: the
you see an 8253-5 programmable timer which is nearly standard ALE. MEMW, MEMR, IOW, and TOR control-bus
identical to the 8254 we described in Chapter 8. Just signals: and some clock signals.
above this is a familiar 8255A-5 programmable port de- Finally, we are down to the DMA signals on the expan-
vice. Nowyou are left with just the three devices with sion connectors. The DMA request pins DRQ1-DRQ3
DMA in their labels to ponder. The 8237A-5 is. of allow peripheral boards to request use of the buses. A
course, the DMA controller. The 74LS373 just under it disk controller board, for example, might request a DMA
is used to grab the upper 8 bits of the DMA address sent transfer of a block of data from system memory. When
out on the data bus by the 8237A-5 during a transfer. the DMA controller gains control of the system buses, it
This device has the same function as device U1 in Fig- lets the peripheral device or board know by asserting the
ure
1-3.
1 The 74LS670 just below this is used to output appropriate DACK0-DACK3 signal. The AEN signal on
bits A16-A19 of the DMA transfer address, the same the connectors is used to gate the DMA address on the
function performed by 1/3 in the circuit in Figure 1 1-3. bus as we described earlier. When the programmed
When you have worked your way around the diagram in number of bytes has been transferred, the T/C pin on the
Figure 1 1-7 and feel reasonably comfortable with it. take connector goes high to let the peripheral know that the
a look at the pin descriptions for the peripheral connec- transfer is complete. A peripheral board can assert the
tors Figure
in 1 1-8. I/O CH RDY pin on the connector low to cause the 8088
The signals shown in Figure 1 1-8 are bused to all six to insert WAIT states until it is ready.
peripheral connectors. Most of the signals on these cod- Later you will see many more examples of bus sharing.
For our next example we show how dynamic RAM is con-
nectedrefreshed
and in a microcomputer.
signal REAR PANEL SIGNAL
NAME NAME
INTERFACING AND REFRESHING
GND
PRESET DRV
DYNAMIC RAM
i5V %Hi.
Review of Dynamic RAM Characteristics
+ IRQ2
-5VDC For small systems such as the SDK-86 where we only
%DRQ2 need a lew kilobytes of RAM we usually use static RAM
12V devices. For larger systems where we want several hun-
RESERVED
dred kilobytesor megabytes of memory we use dynamic
+ t2V
RAMs, often called DRAMs. Here's why.
GND •I/O CH RDY
-MEMW I AEN
Static RAMs store each bit in an internal nip-flop
-MEMR A19 which requires six or so transistors. DRAMs store bits
IOW as a charge or no charge on a tiny capacitor, so they
- IOR
need only one transistor to access the capacitor when
DACK3 —
you write a bit to it or read a bit from it. The result of
\ DRQ3 — I-A15
DACK1 — A 14
this is that DRAMs require much less power per bit. and
+DRQ1 — I A13 many more bits can be stored in a given-size chip. The
DACKO — \f\\7 cost per bit of storage is then much less. The disadvan-
CLOCK — — B20 A20- tageDRAMs
of is that each bit must be refreshed every 2
t IRQ7 —
ms or so because the charge stored on those tiny capaci-
4-IRQ6 —
IRQ5 —
tors tendsto change due to leakage. The internal refresh
I IRQ4 — circuitry has to check the voltage level in each storage
HRQ3 — location; if the voltage is greater than Vcc/2 then that
DACK2 — location is charged to Vcc, if the voltage is less than V,, II
IT/C — then that location is discharged to zero volts. Let's take
IALE —
a look at the pin diagram and timing waveforms for a
45V
MM.
typical DRAM to see how we read, write, and refresh it.
I-GND Figure 11-9 shows the pin diagram for an Intel
51C256H CHMOS DRAM. This device is a 256K by 1
. COMPONENT device, so it stores 262.144 words of 1 bit each in its
^SIDE
16-pin package. You can connect eight of these in paral-
FIGURE 11-8 Pin names and numbers for peripheral slots lel to
store bytes, or 16 in parallel to store 16-bit words.
on IBM PC motherboard. Now, according to the basic rules of address decoding.

370 CHAPTiK HEVT.N


A„ C 1
"r. C % '
WE WHIM 1 MAUI 1
WE d 3
RAS C -I A„ AB ADDRf SS INPI ITS

A [ '• DATA INPUT


A, [6 1
A, C) POWER
:
GROUND

\ J
"XY ^ f V
J X
dcedsk X
HIGH IMPEDANCE

\
<x.

FIGURE 11-9 51C256H CHMOS dynamic RAW. (a) Pin diagram, (b) Read-
operation timing diagram. C/nfe/ Corporation)

18 address lines should be required to address one of burst mode all 512 rows are addressed and pulsed one
the 21S words stored in this device. The pin diagram in right after the other every 4 ms. In the distributed mode
Figure 1 l-9a. however, shows only nine address inputs. another row is addressed and pulsed after every 4/512
A0-A8. The trick here is that to save pins. DRAMs usu- ms or 7.8 /j.s. In a particular system you use the mode
ally send
in the address one-hall at a time. A look at the which will least interfere with the operation of the sys-
timing diagram for a read operation in Figure ll-9b tem. Now
that the operation of dynamic RAMs is fresh in
should help you to see how this works. your mind, we will show you how you interface banks of
To read a word from a bank of dynamic RAMs. a DRAMs to an 8086.
DRAM-controller device or other circuitry asserts the
write-enable (WE) pin of the DRAMs high to enable them
Interfacing DRAMs to an 8086
for a read operation. It then sends the lower half of the
As perhaps you can see from the preceding discussion,
address, called the row address, to the address inputs of
the main tasks you have to do to interface a bank of
the DRAMs. The controller then asserts the roiu-
DRAMs to a microprocessor are:
address-strobe (RAS) input of the DRAM low to indicate
a row address is present. After the proper timing inter-
1. To refresh each location at the proper interval.
val, the
controller removes the row address and outputs
the upper half of the address, called the column address, 2. To "funnel" the two halves of the address into the
to the address inputs of the DRAM. The controller then each device with the appropriate RAS and CAS
asserts the column-address-strobe (CAS) inputs of the strobes.
DRAMs low to indicate that the column address is pres-
3. To assure that a read or write operation and a re-
ent. Aftera propagation delay, the data word from the
fresh operation do not take place at the same time.
addressed memory cells will appear on the data outputs
of the DRAMs. 4. To provide a read/write control signal to enable data
The timing diagram for a write cycle is nearly the into or out of the devices.
same except that after it sends out the column address
and CAS. the controller asserts the write-enable (WE) There are several ways to do these tasks.
input low to enable the DRAMs for writing, and asserts a
signal which gates the data to be written onto the data
inputs of the DRAMs. DRAM Refreshing and Error Checking in the
The DRAM controller refreshes the cells in the DRAMs IBM PC
by sending out each of the 512 row addresses and puls- As you can see in Figure 1 1-7. the IBM PC 256K version
ing RAS
low at least every 4 ms. The refresh can be done has four banks of DRAMs which are 64K by 1 devices.
in either a burst mode or in a distributed mode. In the The PC uses a dummy DMA read approach to refresh its

MUtTIPfE MICROPRO( ESSOR SYSTEMS AND RUSES 371


DRAM. Here's how it works. An 8253 timer is pro- dresses from
the 8086 for read and write operations as
grammed
produce
to a pulse every 15 pis. This pulse is we described previously. One important point to observe
connected into one of the DMA request inputs (DREQOI here is that the status signals. S0-S3. from the 8086
of an 8237 DMA controller which has been programmed are connected directly to the control inputs of the 8208.
to read from memory and write to a nonexistent port. The 8208 decodes these status signals to produce the
When the 8237 DMA controller receives this pulse, it read and write signals it needs. This means that most of
sends a hold request to the 8088 microprocessor. After the time the 8086 will be able to read a byte or word from
the 8088 responds with a HLDA signal, the 8237 takes the DRAMs without any WAIT states being required. If
over the buses, sends out a memory address, sends out the 8208 happens to be in the middle ol a refresh cycle
a memory read signal, and sends out a DMA acknowl- when the 8086 tries to read a DRAM location, the 8208
edge (DACKO)signal. The lower 8 bits of the memory will hold its AACK high and cause the 8086 to insert a
address it sends out goes to the address inputs of all of WAIT state. The 8086 will then have to wait 1 clock cycle
the DRAMs. The DACKO signal is used to pulse the RAS while the 8208 finishes its refresh cycle before it can
lines of all of the DRAM banks low at this time. After access the DRAMs. The occasional access conflict here is
each DMA operation the current address register in the arbitrated by the controller, and slows the 8086 up less
DMA controller will be automatically incremented or than the DMA approach shown in the previous section.
decremented, depending on how the device was pro- Another interesting point about the 8208 is that, in
grammed.
either In case, the next DMA operation will order to save pins, it does not connect to the data bus to
refresh the next row in the DRAMs. If the 8237 is pro- allow command words to be sent to it for initialization. If
grammed
transfer
for of 64 Kbytes, start at address 0. the PDI pin is tied to ground, the 8208 will initialize
increment count after DMA. and autoinitialize. the se- itself in a mode suitable for many applications. For ap-
quence
addresses
of sent out will refresh all 256 rows in plications where
the default mode will not work, the out-
the DRAMs over and over. One row in each of the banks put of
a parallel-in— serial-out shift register is connected
is then refreshed every 15 yus. With the 4.77-MHz clock to the PDI input of the 8208. After a reset the WE/PCLK
used in the IBM PC. a refresh DMA cycle takes about 820 pin outputs a series of pulses. These pulses are used to
ns every 15 jus. or about 5 percent of the processor's clock the desired command word from the shift register
time. into the 8208. The desired mode word is simply hard-
Another point about the DRAM memory banks in the wiredthe
on parallel inputs of the shift register.
IBM PC is that each bank is 9 bits wide. Eight of these
bits make up the data byte being stored, and the ninth
bit is a parity bit which is used to detect errors in the Battery Backup of Dynamic RAMs
stored data. A 74LS280 parily generator/checker circuit In Chapter 8 we discussed the use of an 8086 NMI inter-
generates a parity bit lor each byte and stores it in the rupt procedure to save program data in the case of a
ninth location as each byte is written to memory. When power failure. In the few milliseconds between the time
the 9 bits are read out, the parity is checked by the par- the ac power goes off and the time the dc power drops
ity generator checker circuit. If the parity is not correct, below operating levels, the interrupt procedure copies
an error signal is sent to an 8255 port pin where it can program data to a block of static RAM which has a bat-
be read by the 8088 microprocessor. When you first turn tery backup power supply. When the system is
on the power to an IBM PC or warm boot it by pressing repowered, the saved data is copied back into the main
the Ctrl, Alt, and Del keys at the same time, one of the RAM. and processing takes up where it left off. In larger
self tests that it performs is to write byte patterns to all systems such as the one in Figure 1 1-10, there may not
of the RAM locations and check if the byte read back and be time enough to copy all of the important data etc. to
the parity of that byte are correct. If any error is found, another RAM. In this case we simply use a battery
an error message is displayed on the screen so you don't backup for the entire RAM array as shown in Figure
try to load and run programs in defective RAM. 11-10.
In this circuit we used CHMOS DRAMs because when
these devices are not being accessed for reading, writ-
A DRAM Controller IC— The Intel 8208
ing,refreshing,
or they take only microwatts of power.
In high-performance systems where we want DRAM re- During battery backup of the DRAMs they must still be
freshing
take to up a minimum amount of the proces- refreshed, so the 8208 DRAM controller is also con-
sor's time,
we usually use a dedicated device which han- nected
the tobattery power. The 8208 normally receives
dles of
all the refreshing chores without tying up the its required clock signal from the 8284 clock generator,
microprocessor or its buses as the DMA approach does. but since that is a high-current device, we added a
An example of this type of device is the Intel 8208. Fig- CMOS clock generator which will be switched in when
ure 11-10shows, in block diagram form, how an 8208 the power fails. We use a nickel-cadmium or some other
can be connected with an 8086 in maximum mode to type of battery which can stand the continuous recharg-
refresh and control 1 Mbyte of dynamic RAM. The mem- ing and supply the needed current. The diodes in the
ories here
are 256K by 1 devices. As usual for an 8086. circuit prevent the power supply output and the batten1
the memory array is set up as two banks. Each bank has from fighting with each other.
two blocks containing 8 RAM chips, or 256 Kbytes. In applications where the entire system must be kept run-
In the system in Figure 11-10 the 8208 takes care of ning duringan ac power outage, we use an uninterrupt-
all of the refresh tasks in addition to tunneling in ad- ible powersupply. UPS. which contains a large battery

372 CHAPTER ELEVEN


%ºt

O
t>
H J_ N p^
CLK \

_L
RASO 1 L -A
CASO 1
8208
1
__/ Wl

CTL vv[ PCI K

F BS PDI
AHO 1 Alt) I
v. H^ 7\
B284A
CLOCK
CI K MW 1 1
GENERATOR
READY AMWC

RESET s. ii ISi
DEN iowi ".JlO
DT:R A IOWC

AI I NIA

AD„-AD,, B282 | A0-A19 BANK SELECT CIRCUIT


ADDR.DATA
A,6-A,, LATCH
i
(2 OR 3)

4>-
TRANSCEIVER

FIGURE 11-10 Circuit tor refreshing dynamic RAMs with the 8208 dynamic RAM
controller.

and the circuitry needed to convert the battery voltage to this, depending on the amount of detection and correc-
the voltage needed by the microcomputer. tion needed.
The simplest method for detecting an error is with a
parity bit. As we described previously for the IBM PC. we
do this by first determining the parity of, say, an 8-bit
Error Detecting and Correcting in RAM Arrays data word as it is being written to a memory location. We
Data read from RAMs is subject to two types of errors. then generate a parity bit such that the overall parity of
hard errors and soft errors. Hard errors are caused by the 8 data bits plus the parity bit is. for example, always
permanent device failure. This may be caused by a man- odd. The generated parity bit for each byte is written
ufacturingordefect
simply random breakdown in the into a separate memory device in parallel with the de-
chip. Soft errors are one-time errors caused by a noise vices containingthe data byte. When the data byte and
pulse in the system or. in the case of dynamic RAMs. the parity bit are read from memory, we check the parity
perhaps an alpha particle or some other radiation caus- of the 9 bits together. If the overall parity of these nine is
ing the
charge to change on the tiny capacitor on which not odd as it should be. then we know that somewhere
a data bit is stored. As we add larger and larger arrays of in the read/write process an error was introduced. If ex-
RAMs to a system, the chance of a hard or a soft error ternal hardware
is being used to generate/check parity,
occurring increases sharply. This then increases the then an output from this circuitry can be used to tell the
chance that the entire system will fail. It seems unrea- processor that an error occurred, and that the data is
sonableone
that fleeting alpha particle could possibly not valid. The processor can then respond appropri-
cause an entire system to fail. To prevent or at least re- ately.
duce chances
the of this kind of failure, we add circuitry One difficulty with a simple parity check is that two
which detects and in some cases corrects errors in the errors in a data word may cancel each other. A second
data read out from RAMs. There are several ways to do problem with simple parity is that it does not tell you

MULTIPLE MICROPROCESSOR SYSTEMS AND BUSES 373


correction, consult the manual for it if you need the spe-
cific coding. Several available ICs such as the Intel 8206
will automatically detect/correct single bit errors and
detect two bit errors in 16-bit data words. The devices
can be cascaded to work with up to 80-bit data words.
Now that we have shown you the operation of a DMA
controller and the operation of the 8086 in maximum
mode, we can introduce you to the 80186 and 80188
SINGLE CORRECT/ SINGLE CORRECT/ microprocessors which have DMA controllers and other
SINGLE DETECT DOUBLE DETECT
peripherals built in.
% M < •- M '

4 11 1 3
12 26 4 10
27 57
PROCESSORS WITH INTEGRATED
11 25
58 1 20 26 56 PERIPHERALS— THE 80186 AND 80188
121 245 57 119
Overview
Figure 11- 12a shows a block diagram of the internal
FIGURE 11-11 Error detecting/correcting codes, (a) architecture of the Intel 80186 microprocessor. The ar-
Encoding bits, (bi Number of encoding bits for chitecture
instruction
and set of the 80188 are identical
detecting/correcting. to those of the 80 1 86 except that the 80 1 88 has only an
8-bit data bus instead of the 16-bit data bus that the
which bit in a word is wrong so that you can correct the 80186 has. With this in mind, we will use 80186 to rep-
error. More complex error detecting/correcting codes resent both
the 80 1 86 and the 80 1 88 in our discussions
(ECCs), often called Hamming codes after the man who here.
did some of the original work in this area, permit you to The 80186 has the same bus-interface unit and exe-
detect multiple-bit errors in a word and to correct at cution unit
as the 8086 which we discussed previously,
least one bit error. Here's how they work. so there is nothing new there for you. Unlike the 8086.
As the data word is read in. several encoding bits are however, the 80186 has the clock generator built in so
generated and stored in memory along with the data that all you have to add is an external crystal. Also note
word. Figure 11-1 la shows this in diagram form. The that the 80186 does not have a pin labeled MN/MX. The
number of encoding bits, k. required is determined by 80186 is packaged in a 68-pin leadless package as
the size of the data word.m. and the degree of detection/ shown in Figure 1 l-12b. so it has enough pins to send
correction required. The total number of bits required out both the minimum-mode type signals RD and WR
for a data word. n. is equal to m + k. Figure 1 1-1 lb and the S0-S3 status signals which can be connected to
shows the mimber of encoding bits needed for different external bus-controller ICs for maximum-mode systems.
numbers of data bits and different degrees of detection/ Now let's look at the four peripheral chip function blocks
correction. According to these values. 5 encoding bits in the 80186.
are required to detect and correct a single-bit error in a First is a priority interrupt controller which has up to
16-bit data word, so the total number of bits that have to four interrupt inputs, INTO. INT1. 1NT2/INTA0. and INT3/
be stored for each word in this case is 21. To give you INTA1 as well as an NMI interrupt input. If the four INT
enough information to correct one error and detect 2 inputs are programmed in their internal mode, then a
wrong bits in a 16-bit word would require 6 encoding signal applied to one of them will cause the 80186 to
bits. push the return address on the stack and vector directly
When you write a word to memory the error detecting/ to the start of the interrupt service procedure for that
correcting circuitry generates the required encoding interrupt. Figure 11-14 shows the interrupt type which
bits and writes them to memory along with the data corresponds to each of these inputs. The INT2/INTA0.
word. The encoding bits, incidentally, are not just and INT3/INTA1 pins can be programmed to be used as
tacked on to one end of the data word as a parity bit is. interrupt inputs as we have just described, or they can
They are interspersed in the data word. When you read a be programmed to function as interrupt acknowledge
data word from memory, the error detecting/correcting outputs. This mode is used to interface with external
circuitry recalculates the encoding bits for the data 8259As. The interrupt request line from an external
word read out. It then exclusive-NORs these encoding 8259A is connected to. for example, the 80186 INTO
bits with the encoding bits that were stored in memory input, and the 80186 INT2/INTA0 pin is connected to the
for that data word. The word produced by this operation interrupt acknowledge input of the 8259A. When the
is known as a syndrome word. The encoding bits are 8259A receives an interrupt request, it asserts the INTO
generated in such a way that the value of this syndrome input of the 80186. When the 8259A receives interrupt
word indicates which bit, if any. is wrong in the total acknowledge signals from the INT2/INTA0 pin, it sends
word of data word plus encoding bits. The erroneous bit the desired interrupt type to the 80186 on the data bus.
can then be corrected by simply inverting it. Because of This second mode is commonly referred to in the litera-
hardware implementation tradeoffs, there are actually ture as
iRMX mode, because an 80186 system must
several different schemes for determining the encoding have an external 8259A and 8254 if the iRMX operating
bits, so if you are working with a RAM system with error system is going to be run on it.

374 ( HAPTFK ELEVEN


CLKOUT \ GND IMII
INT1
TMR IN i

U_L
I %I i i ; I . P %MMABLE
I IMI RS

16 Bl I MA X COUNT kVV1
ALU PU< H.MAMMABLE 3ISTERB k\V
RRUPT
CI OCK CONTROLLER
Gi Nl RA I OR
16 BIT
CONTROL REGISTf RS
PURPOSE CONTROL
16 BIT
R| GISTI RS REGISTERS
J
J[ ITI R IAI BUS
ft
-hliijn
% DR01

PROGRAMMABLE
DMA UNIT
S0-S2

CHIP SELECT 20-BIT


SRDY- UNIT SOURCE POINTERS
ARDY- 20-BIT
BUS INTERFACE 16-BIT
TEST- DESTINATION
UNIT SEGMENT
HOLD- Pi UN I ERS
REGISTERS
HLDA- PROGRAMMABLE 16-BIT
6-BYTE CONTROL
RES- TRANSFER COUNT
PREFETCH REGISTERS
RESET- QUEUE CONTROL
REGISTERS

UCS f w PCS6/A2
i DEN
| LOCK LCS PCS5/A1
V V
MCS0-3 PCSO -4

JJUUUUUUUUUUUUUULH UCS
SO
M 3 1 LCS
S2 n 1 PCS6/A2
ARDY 5 1 PCS5/A1
CLKOUT ,j I PCS4
RESET ^ 1 PC S3
X2 h ! PCS2
XI =i 1 PCS1
VSE n 1 V

ALE/QSO ] 1 PCSO
RD/QSMD ] ( RES
WR/QS1 l I TMR OUT 1

BHE h [:: TMR OUTO

A19/S6 7i i TMR IN 1

A18/S5 j i TMR IN 0

A17/S4 3 r DRQ1
A16/S3
ftinnnnnnnnnnnnnnr rf DRQO

FIGURE 11-12 80186. (a) Internal block diagram, (b) Pin diagram. (Intel Corporation)

MULTIPLE MICROPROCESSOR SYSTEMS AND BUSES 375


Next to look at in the block diagram is the built-in OFFSET

address decoder, referred to in the drawing as the chip- RELOCATION REGISTER FEH
select unit. This unit can be programmed to produce an
active low chip-select signal when a memory address in
the specified range or a port address in a specified range
D- H
is sent out. Six memory address chip-select signals are DMA DESCRIPTORS CHANNEL 1
DOH
available: LCS, UCS, and MCSO-3. The lower-chip-select
signal, LCS, will be asserted by addresses between
00000H and some address which you specify in a con- CAH
trol word.The specified ending address can be any- DMA DESCRIPTORS CHANNEL 0
I OH
where between IK and 256K. The highest address that
will assert the upper-chip-select signal. UCS. is fixed at
FFFFFH. The lowest address for this block of memory is A8H
CHIP-SELECT CONTROL REGISTERS
again programmable by some bits you put in a control .'.ijH

word. The size of the upper memory block can be any-


where between IK and 256K. Finally, there are four
middle-chip-select lines, MCSO-3. Each of these four is TIMER 2 CONTROL REGISTERS
asserted by an address in a block of memory in the mid- BOH
5EH
dle rangeof memory. Both the starting address and the TIMER 1 CONTROL REGISTERS
58H
size of the four blocks can be specified for this middle-
56 H
range block. The specified size of blocks can be any- TIMER 0 CONTROL REGISTERS

where from
2K to 128K. The memory areas assigned to
different chip selects cannot overlap, or two chip-select
outputs will be asserted at the same time, possibly dam-
INTERRUPT CONTROLLER REGISTERS
aging somememory devices. The point of this built-in
decoder is to select major blocks of memory. External
decoders can then be used to select specific groups of
memory devices. At the rate memory devices are growing
15 14 13 12 11 10 9
in size, external decoders may soon not be needed.
FEH ET RMX X M/IO RE LOCATION ADDRESS BITS R 19-R8
In addition to producing memory chip-select signals,
the 80186 can be programmed to produce up to seven
ET = ESC TRAP/NO ESC TRAP (1/0)
peripheral chip-select signals on its PCSO—PCS4, PCS5/ M/IO = REGISTER BLOCK LOCATED IN MEMORY / I/O SPACE (1/0)
A1, and PCS6/A2 pins. You program a base address for RMX = MASTER INTERRUPT CONTROLLER MODE / IRMX COMPATIBLE
INTERRUPT CONTROLLER MODE (0/1)
these I/O addresses in a control word. PCSO will be as-
serted when
this base address is output during an IN or (M
an OUT instruction. The other PCS outputs will be as-
serted
addresses
by at intervals of 128 bytes above. FIGURE 11-13 80186 Peripheral control block, (a) Control
Now let's look at the programmable DMA unit in the block format, lb) Relocation word format. (Intel
80186. As you can see from the block diagram in Figure Corporation)
11-12. the DMA unit has two DMA request inputs,
DRQO and DRQ1. These inputs allow external devices every 4 processor clocks. By setting or clearing the ap-
such as disk controllers. CRT controllers, etc. to request propriate
in bits
a control word, you can direct the out-
use of one of the DMA channels as we described earlier put counter
of 2 to a DMA input, an interrupt input, or
in this chapter. For each DMA channel the 80186 has a the input of counter 1 and/or counter 0.
full 20-bit register to hold the address of the source of As you can see from the preceding discussion, the
the DMA transfer, a 20-bit register to hold the destina- 80186 contains many of the peripheral chip functions
tion address, and a 16-bit counter to keep track of how needed in a medium-complexity microcomputer system.
many words or bytes have been transferred. DMA trans- In order to use these integrated peripherals, you have to
fers canbe from memory to memory, I/O to I/O, or be- initialize them just as you do external peripherals. Note
tweenand
I/O memory. in Figure 11-12 that control registers are shown as part
Finally, let's look at the three 16-bit programmable of each of the integrated peripherals. These 16-bit con-
counter/timers in the 80186. The inputs and outputs of trol registers are all contained in an internal 256-byte
counters 0 and 1 are available on pins of the 80816. block, as shown in Figure ll-13a. After a reset this
These two counters can be used to divide down the fre- block will be located at I/O address FF00H. Control and
quency
external
of signals, produce programmed-width status registers in this block can then be accessed with
pulses, etc. just as you do with the counters in an 8254. IN and OUT instructions. This peripheral control block
You can also internally direct the processor clock to the can be relocated to some other address in the I/O space,
input of one of these counter inputs by clearing the ap- or to an address in memory by writing the appropriate
propriate
in abitcontrol word. The input of the third word to the relocation register in the control block. Fig-
counter in the 80186 is internally connected to the proc- ure
l-13b
1 shows the format for the word you send to
essor clock.Because of the way the counters in the the relocation register. We do not have space here to
80186 are decremented, counter 2 will be decremented show and explain all of the control word formats for the

376 CHAPTER FfEVEN


80186. Ii you have to woi k with an 80186, you can find
INTERRUPT
the formats foi these words in the 80186 data sheet,
.uhI work mi I the control words you need foi youi partii
DIVIDE II %1
ul. u application on a bil by bil basis, jusl as you d<> for EXCI 1
the separate peripherals You may also find Intel appli SINGLI 1

cation note 1M(>.Introduction to the 80186 Microproces IMMI 1


sor, helpful BREAKPOINT 3 •1 INT

The final pi 'ii n s we want to make about the 80186 are


INTO DETECTED 4 %1
the additional instructions and Interrupts i( has beyond OVi HI I ow
those nl the 8086. Hie 10 additional instructions thai EXCEPTION
ARRAY BOUNDS %1
the 80186 has are:
EXCEPTION
UNUSED OPCODI 6 %1 INED
ENTER I ntei a procedure EXCEPTION iDES
1 1 \\ 1 — I eave a procedure ESC OPCODE / T"
EXCEPTION
BOUND i he< k ii .in array index in a register
TIMER 0 INTERRUPT 8 2A
is in range ol arra} TIMER 1 INTERRUPT 18 2H
INS —Input string byte oi string word TIMER 2 INTERRUPT 19
RESERVED 9 3
OUTS — Output string byte or string wind DMAO INTERRUPT 10 4
PI M I \ — Push all registers on slac k DMA 1 INTERRUPT 11 5
INTO INTERRUPT 1? 6
POPA — Pop all registers oil stack
INT1 INTERRUPT 13 7
PUSH immediate — Push immediate number on stac k 14 8
INT2 INTERRUPT
IMUL destination register, source, immediate INT3 INTERRUPT 1b 9

— Immediate % source to destination


SHIFT/ROTATE destination, immediate ' 1 These are generated as the result of an instruction exe
— Shift register or memory contents specified ••2. This is handled as in the 8086
' • ' "3 All three timers constitute one source of request to the interrupt
immediate number ot times
controller. The Timer interrupts all have the same default priority
level with respect to all other interrupt sources. However, they have
These instructions are explained in greater detail in a define, I priority older inq amonqst themselves. (Priority 2 A is
Chapter 6 for your reference. Now let's look at the addi- hiqhei priority than 28.) Each Timer interrupt has a separate vector
type number.
tional built-ininterrupt types the 80186 has.
4. Default priorities tor the interrupt sources are used only if the user
Figure 11-14 shows the names, type numbers, and does not program each source into a unique priority level.
default priorities lor the 80186 internal interrupts. The * **5. An escape opcode will cause a trap only if the proper bit is set in
the peripheral control block relocation register.
first five of these should be familiar to you from our dis-
cussions
the 8086of internal interrupts. The 80186 will
FIGURE 11-14 80186 internal interrupt types. (Intel
do a type 5 interrupt if an array index number in a regis-
Corporation)
ter is
outside of the specified range for the array when
the BOUND instruction executes. It will do a type 6 in- cessing. Therefore, specialized coprocessors have been
terrupt
it finds
if an undefined opcode in the instruc- developed for these applications. These coprocessors
tions fetched from memory by the BIU. If this interrupt operate in parallel with an 8086-type processor on the
is unmasked, and if the 80186 finds an ESC opcode in same buses and with the same instruction-byte stream.
the instructions it fetches from memory, the 80186 will To show you how a coprocessor works, we will use a spe-
do a type 7 interrupt. The additional interrupt tvpes are cific example,
the 8087 math coprocessor. If you have an
dedicated to the integrated peripherals as shown. IBM PC type of computer, you can plug an 8087 chip in
Now that you have an overview of the relatively sophis- it directly and run 8087 programs. You can then run the
ticated 80186microprocessor, our next step is to show example programs, and write some of your own as you
you how two or more microprocessors are used in a sys- work your way through this chapter.
tem Earlierin this chapter we showed you how a DMA In many microcomputer programs such as those used
controller, a floppy-disk controller, and a dynamic FMM for scientific research, engineering, business, and
controller can share the buses of a microprocessor. graphics, you need to make mathematical calculations
These devices have some "intelligence," but they are not such as computing the square root of a number, the
comparable to the microprocessor in power. In the next tangent of a number, or the log of a number. Another
section we show you how two or more processors can common need is to do arithmetic operations on very
directly share the address, data, and control buses. large and very small numbers. There are several ways to
Processors which share the local buses in this way are do all of this. One way is to write the number-crunching
referred to as coprocessors. part of the program in a high-level language such as
FORTRAN, compile this part of the program, and link in
A COPROCESSOR— THE 8087 MATH I/O modules written in assembly language. The difficulty
COPROCESSOR with this approach is that programs written in high
level languages tend to run considerably slower than
Overview
programs written in assembly language.
The instruction set of general-purpose processors such Another way is for you to write an assembly language
as the 8086 is not optimized to do complex numerical program which uses the normal instruction set of the
calculations, CRT graphics manipulations, or word pro- processor to do the arithmetic functions. Reference

MULTIPLE MICROPROCESSOR SYSTEMS AND BUSES 377


books which contain the algorithms for these are readily First note that the multiplexed address-data bus
available. Our experience has shown that it is often lines. AD0-AD7. go directly from the 8088 to the 8087.

time-consuminsj, to get from the algorithm to a working The 8088. remember, has the same instruction set as

assembly language program. the 8086, but it only has an 8-bit data bus, so all read
Still another approach is to buy a library of floating- and writes are byte operations. The upper address lines.
point arithmetic object modules from the manufacturer A8-A19. also connect directly from the 8088 to the 8087.
of the microprocessor you are working with or from an If you look a little closer at the schematic, you should see

independent software house. In your program you just that the status lines, S2, SI, and SO, from the 8088 and

declare a procedure needed from the library as external, the queue status lines, QS1 and QSO, from the 8088 also

call the procedure as required, and link the library to the connect directly to the 8087. The 8087 receives the
object code for your program. This approach spares you same clock and reset signals as the 8088. Three more

the labor of writing all the procedures. connections to the 8087 that you need to pay close at-
In an application where you need a calculation to be tention
are:to
done as quickly as possible, however, all of the previous First, the request/grant signal, RQ/CTO. from the 8087
approaches have a problem. The architecture and in- is connected to the request/grant pin, RQ/CT1, of the
struction
of general-purpose
sets microprocessors such 8088. The way you figure this out from the schematic is
as the 8086 are not designed to work efficiently with to notice that the signal from the 8087 RQ/CTO pin is
mathematical manipulation. Therefore, even highly op- labeled just RQ/CT where it enters the erosshatched
timized number-crunching programs run slowly on bus. Likewise, the label on the signal coming from the
these general-purpose machines. To solve this problem, erosshatched bus to the RQ/CT1 pin of the 8088 is also
special processors, which have architectures and in- just labeled RQ/CT. You know from the fact that the two
struction
optimized
sets for number crunching, have lines have the same label, they are connected together.
been developed. An example of this type of number- Second, the BUSY signal from the 8087 is connected
crunching processor is the Intel 8087 math processor. to the TEST input of the 8088. If the 8088 must have the
An 8087 is used in parallel with the main microproces- result of some computation that the 8087 is doing be-
sor ainsystem, rather than serving as a main processor forecan
it go on with its instructions, you tell the 8088
itself. Therefore it is referred to as a coprocessor. The with a WAIT instruction to keep looking at its TEST pin
major principle here is that the main microprocessor, until it finds the pin low. A low on the 8087 BUSY output
an 8088 for example, handles the general program exe- indicates that the 8087 has completed the computation.
cution,the
and 8087 coprocessor handles specialized Third, the interrupt output, INT. of the 8087 is con-
math computations. First we will show you how an 8087 nected
the to nonmaskable interrupt. NMI, input of the
is connected and functions in a system, then we will 8088. This connection is made so that an error condi-
show you how to program it. tion the
in 8087 can interrupt the 8088 to let it know
about the error condition. The signal from the 8087 INT
output actually goes through some circuitry on sheet 2
Circuit Connection for an 8087 of the schematics and returns to the input labeled NMI
Figure 11-15 shows the first sheet of the schematics for on the left edge of Figure 11-15. We do not have room
the 256K version of the IBM PC. We chose this sche- here to show and explain all of the circuitry on sheet 2.
matic'only
not to show you how an 8087 is connected in The main purposes of the circuitry between the INT out-
a system with an 8088 microprocessor, but also to show put of
the 8087 and the NMI input of the 8088 is to
you another way in which schematics for microcomput- make sure that an NMI signal is not present upon reset,
ers arecommonly drawn. The more schematics you to make it possible to mask the NMI input, and to make
work your way around, the easier it will get for you. it possible for other devices to cause an NMI interrupt.
First in Figure 11-15. note the numbers along the left A couple of pins on the 8087 that we aren't concerned
and right edges ol the schematic. These numbers indi- with here are the bus-high-enable IBHEI and request/
cate the
other sheet! s) that the signal goes to. This is an grant 1 (RQ/CT 11 pins. When the 8087 is used with an
alternative approach to the zone coordinates used in the 8086. the BHE pin is connected to the system BHE line to
schematics in Figure 7-6. In the schematic here the enable the upper bank of memory. The RQ/CT1 input is
zone coordinates are not needed because all of the input available so that another coprocessor such as the 8089
signal lines are extended to the left edge of the sche- I/O processor can be connected and function in parallel
matic, all
and of the output signal lines are run to the with the 8087.
right edge of the schematic. If you see that an output As you can see from the preceding discussion, the
signal goes to sheet 10. then it is a simple task to scan 8087 is connected very tightly with the 8088. Now let's
down the left edge of sheet 10 to find that signal. The talk about how the two devices work together.
wide erosshatched strips in Figure 11-15 represent the
;s, data, and control buses. From the pin descrip-
t ions tor the major ICs you know where these signals are 8087-8088 Cooperation
produced. You can then scan along the bus to see where The point that we need to make about the 8087 is that it
various signals get dropped off at other devices. On this is an actual processor with its own, specialized instruc-
type of schematic the buses are always expanded to indi- tion set.Instructions for the 8087 are written in a pro-
vidual lines
where they enter or leave a schematic. Now gramneeded,
as interspersed with the 8088/8086 in-
let's look at how the 8087 is connected. structions.
you, Tothe programmer, adding an 8087 to

378 CHAPTER ELEVEN


FIGURE 11-15 8088 and 8(187 section of IBM PC schematic.

the system simply makes it appear that you have sud- The fact that the status lines and the queue status lines
denly been
given a whole new set of powerful math in- from the 8086 are connected directly to the 8087 allows
structions
use intowriting your programs. The opcodes the 8087 to track the 8086 or 8088 queue in this way.
for the 8087 instructions are put in memory right along The 8087 decodes each instruction that comes into its
with the codes for the 8086 or 8088 instructions. As the queue. When it decodes an instruction from its queue
8086 or 8088 fetches instruction bytes from memory and finds that it is an 8086 instruction, the 8087 simply
and puts them in its queue, the 8087 also reads these treats the instruction as an NOP. Likewise, when the
instruction bytes and puts them in its internal queue. 8086 or 8088 decodes an instruction from its queue and

MULTIPLE MICROPRO! IssoR SYSTEMS AND BUSES 379


finds that it is an 8087 instruction, the 8086 simply quired
theby instruction to/from memory. When the
treats the instruction as an NOP. or in some cases reads 8087 is through using the buses for its data transfer, it
one additional word from memory for the 8087. The sends another low-going pulse out on its RQ/CTO pin to
point here is that each processor decodes all of the in- let the 8086 or 8088 know it can have the buses back
structions
the fetched
in instruction byte stream, but again. This bus sharing is another example of a DMA-
only executes its own instructions. The first question type operation. The RQ'CTO line is used in a bidirec-
that may occur to you is. "How do the two processors tional mode
here to save pins. The key point here then is
recognize 8087 instructions?" The answer is that all of that the coprocessor, by pulsing the RQ/GTO input of the
the 8087 instruction codes have 11011 as the most- host processor, can take over the buses from the host or
significant bits of their first code byte. Later we show bus master processor to transfer data when it needs to.
you how to code 8087 instructions. The synchronous This is another example of a DMA operation.
operation of these two processors is an example of a The next type of synchronization between the host
lightly coupled multiprocessor system. Now. before we processor and the coprocessor that you need to know
get into the 8087 data types, architecture, and instruc- about is that required to make sure the 8086 or 8088
tion set.
let's dig a little more into how the two proces- host does not attempt to execute the next instruction
sors are
synchronized during various operations. before the 8087 has completed an instruction. There are
One type of cooperation between the two processors two possible problem situations here.
that you need to know about is how the 8087 transfers One problem situation is the case where the 8086
data between memory and its internal registers. When needs the data produced by execution of an 8087 in-
the 8086 or 8088 reads an 8087 instruction that needs struction
carryto out its next instruction. In the in-
data from memory or wants to send data to memory, the struction sequence
in Figure ll-17a for example, the
8086 sends out the memory address coded in the in- 8087 must complete the FSTSW STATUS instruction be-
struction
sends
and out the appropriate memory read or fore the
8086 will have the data it needs to execute the
memory write signals to transfer a word of data. In the MOV AX, STATUS instruction. Without some mecha-
case of a memory read, the addressed word will be put nismmake
to the 8086 wait until the 8087 completes
on the data bus by the memory. The 8087 then simply the FSTSW instruction, the 8086 will go on and execute
reads in this word off the data bus. The 8086 or 8088 the MOV AX, STATUS instruction with erroneous data.
ignores this word. If the 8087 only needs this one word We solve this problem by connecting the 8087 BUSY out-
of data, it can then go on and execute its instruction. put to
the TEST pin of the 8086 or 8088. and putting an
However, some 8087 instructions need to read in or 8086 WAIT instruction in the program. Here's how it
write out up to 80-bit words. For these cases the 8086 works.
outputs the address of the first data word on the ad- While the 8087 is executing an instruction it asserts
dress bus
and outputs the appropriate control signal. its BUSY pin high. When it is finished with an instruc-
The 8087 reads the data word put on the data bus by tion, the
8087 will drop its BUSY pin low. Since the
memory or writes a data word to memory on the data BUSY pin from the 8087 is connected to the TEST pin of
bus. The 8087 then grabs the 20-bit physical address the 8086 or 8088. the host can check this pin to see if
that was output by the 8086 or 8088. To transfer addi- the 8087 is done with an instruction. The 8086 instruc-
tional words
it needs to/from memory, the 8087 then tion usedto check the TEST pin is the WAIT instruction.
takes over the buses from the 8086. To take over the bus You put the 8086 WAIT instruction in your program
the 8087 sends out a low-going pulse on its RQ/CTO pin after the 8087 FSTSW instruction, as shown in Figure
as shown in Figure 1 1-16. The 8086 or 8088 responds 11- 17b. (Actually, for reasons we explain later, you
to this by sending another low-going pulse back to the should use the 8087 FWAIT instruction which does the
RQ/CTO pin of the 8087 and by floating its buses. The same thing.) When the 8086 or 8088 executes the WAIT
8087 then increments the address it grabbed during the instruction, it enters an internal loop where it repeat-
first transfer and outputs the incremented address on edly checks the logic level on the TEST input. The 8086
the address bus. When the 8087 outputs a memory read will stay in this loop until it finds the TEST input as-
or memory write signal, another data word will be trans- serted low.
indicating the 8087 has completed its in-
ferredorto from the 8087. The 8087 continues the struction.8086
The will then exit the internal loop,
process until it has transferred all of the data words re- fetch and execute its next instruction.

- 1 CLK OCLK. ANY CI K i, 1 CLK.


CYCLE CYCLE CYCLE CYCLE

/V-^u \ v^v^v
\_ZiS
AD:. AD. — TCLAZ

>^c j —%
— (El
FIGURE 11-16 Signals on 8087 to 8088 RQ/GT line during bus takeover by 8087
instruction coding formats. (Intel Corporation)

380 CHAPTER EtEVEN


FSTSW STATUS copy 8087 status word to memory
MOV AX, STATUS copy status word to AX to check bit'

FSTSW S I AIUS copy 8087 status word to memory


FWAIT wait for 8087 to finish before doing
next 8086 instruction
MOV AX, STATUS copy status word to AX to check bits

I ICl 'Kl 11-17 S} in hronizing 8086 and »(NS7 instrin tion exe< ution. (a) ( ode
sci lion without needed synchronization. (D) ( ode section with needed FWAIT
ins li in lion

Another execution case where you need synchroniza- and real. We will discuss and show examples of each type
tionthe
ol host and the coprocessor is the case where a individually
program has several 8087 instructions in sequence. The
8087 can obviously execute only one instruction at a BINARY INTEGERS
time, so you have to make sure that the 8087 has com- The first three formats in Figure 1 1-18 show differenl
pleted instruction
one before you allow the 8086 to fetch length binary integer numbers. These all have the same
the next 8087 instruction from memory. Here again you basic format that we have been using to represent
use the BUSY-TEST connection and the FWAIT instruc- signed binary numbers throughout the rest of the book.
tion solve
to the problem. If you are hand coding, you The most-significant bit is a sign bit which is 0 for posi-
can just put the 8086 WAIT (FWAIT) instruction after tive numbers and 1 for negative numbers. The other
each 8087 instruction to make sure that instruction is 15—63 bits of the data word in these formats represent
completed before going on to the next. If you are using the magnitude of the number. If the number is negative,
an assembler which accepts 8087 mnemonics, the as- the magnitude of the number is represented in 2's com-
sembler
automatically
will insert the 8-bit code for the plement Zero,
form. remember, is considered a positive
WAIT instruction. 10011011 binary (9BH), as the first number in this format, because it has a sign bit of 0.
byte of the code for the 8087 instruction. You can see an Note also in Figure 11-18 the range of values that can be
example of this in the code column of the sample pro- represented by each of the three integer lengths. When
gramFigure
in 1 1-24 which we discuss later. When the you put numbers in this format in memory for the 8087
8086 or 8088 fetches and decodes this code byte, it will to access, you put the least-significant byte in the lowest
enter the internal loop and wait for the TEST input to go address.
low before fetching and decoding the 8087 instruction
following this byte. The point here is that by putting the PACKED DECIMAL NUMBERS
FWAIT instruction after an 8087 instruction in some
The second type of 8087 data format to look at in Figure
way. you make sure that one instruction is finished be-
1 1-18 is the packed decimal. In this format a number is
fore the
next is started.
represented as a string of 18 BCD digits, packed two per
In the preceding sections we have shown you how two
byte. The most-significant bit is a sign bit which is 0 for
tightly coupled processors can operate essentially as one
positive numbers and 1 for negative numbers. The bits
unit, sharing the same buses, memory, and instruction
indicated with an X are don't cares. This format is
stream. Because the 8087 math coprocessor which we
handy for working with financial programs. Using this
used as an example in the preceding sections is such a
format you can represent a dollar amount as large as
useful and common device, we now want to go on and
$9,999,999,999,999,999.99. which is probably about
show you how you can use one. We can't show you all
what the national debt will be by the year 2000. Again,
there is to know about the 8087, because it is a fairly
when you are putting numbers of this type in memory
complex device. However we can show you enough that
locations for the 8087 to access, the least-significant
if you have an 8087 in your system, you can write a few
byte goes in the lowest address.
simple programs for it. We will start with a discussion of
the types of numbers that the 8087 is designed to work
REAL NUMBERS
with.
Before we discuss the 8087 real number formats, we
need to talk a little about real numbers in general.
So far the computations we have shown in this book
8087 Data Types have used signed integer numbers or BCD numbers.
Figure 1 1-18 shows the formats for the different types of These numbers are referred to as fixed-point numbers
numbers that the 8087 is designed to work with. The because they contain no information as to the location
three general types are binary integer, packed decimal. of the decimal point or binary point in the number. The

MULTIPLE MICROPROCESSOR SYSTEMS AND BUSES 381


Approximate Range (Decimal)

INCREASING SIGNIFICANCE

WORD INTEGER MAi, Nil HDL 32768 % % ' -32767

SHORT INTEGEF MAGNITUDE 2 % 109 - • -- 2 % 109

MAGNITUDE 9 • 10 's - % •- t 9 • 10 ' s


LONG INTEGER

MAGNITUDE
PACKED DECIMAL -99 99 % %s +99 99 (18 digit

BIASED
SHORT REAL SIGNIFICAND 0 12-10"- - 14 10
EXPONENT

BIASED
SIGNIFICAND
EXPONENT

~!*cr>
TEMPORARY REAL
E SIGNIFICAND 0.3 4 x 10 4932 % - 1 1 % 104932

NOTES
S = Sign bit (0-positive, 1 negative)
d„ - Decimal digil [Iwo per byte)
X - Bits have no signilicance. 8087 ignores when loading, zeros when storing
A - Posihon of imphcil binary poinl
I = Integer bit ot signiticand, stored in lemporary real, implicit in short and long r
Exponent Bias (normalized values)
Short Real 127 (7FH)
Long Real 1023 (3FFH)
Temporary Real 16383 (3FFFH)

FIGURE 11-18 8087 data formats. (Intel Corporation)

decimal or binary point is always assumed to be to the There are several different formats for representing
right of the least-significant digit, so all numbers are real numbers in binary form. The basic principle of all of
represented in this form as whole numbers with no frac- these, however, is to use one group of bits to represent
tional part.
A weight of 9.4 lb. for example, is stored in a the digits of the number, and another group of bits to
memory location simply as 10010100 BCD or 0101 1 1 10 represent the position of the binary point with respect
binary. A price of SO. 29 per pound is stored in a memory to these digits. This is very similar to the way numbers
location as 00101001 in BCD or 0001 1 101 in binary. are represented in scientific notation, so as a lead-in we
When the binary representation of the weight is multi- will refresh your memory about scientific notation.
pliedthe
by price per pound to give the total price, the To convert the number 27.934 to scientific notation
result is 101010100110 binary, or 2726 decimal. To you move the decimal point four digit positions to the
give the desired display of $2.73, the programmer must left and multiply the number by lO4. The result.
round off the result and keep track of where to put the 2.7934 x 104. is said to be in scientific notation. As
decimal point in the result. For simple numbers such as another example, you convert 0.00857 to scientific no-
these from the scale program in Chapter 10, it is not too tation
moving
by the decimal point three digit positions
difficult to do this. However, for a great many applica- to the right and multiplying by 10 l to give 8. 57 x 10~3.
tionsneed
we a representation that automatically keeps The process of moving the decimal point to a position
track of the position of the decimal or binary point for just to the right of the most-significant, nonzero digit is
us. In other words we need to be able to represent num- called normalizing the number. In these examples you
bers which have both an integer part and a fractional can see the digit part, sometimes called the significand
part. Such numbers are called real numbers, or float- or the mantissa, and the exponent part of the represen-
ing-point numbers. tation. When
you are working with a calculator or com-

382 CHAPTER ELEVEN


puter, the numbei ol digits you can store foi the sig 127 (7FI [) to the exponent ol i you gel die biased expo
nificand pari <il the number determines the accuracy 01 1lent value ol H(il I (hat you need lor the si 1011 real repre
precision ol the representation. In most cases the real sentatlon. The final lini In F Igui ell 1' • .hows the com
numbers you work with in your computer will be ap- plete short real result Foi the significand you put in the
proximations,
to because
"accurately" represent a num- binary bits to the right ol the binary point. Remember,
ber suchas rr would require an Infinite number ol dig the 1 to the lefl ol the binary point is assumed. I he in
iis. The point here is that more digits give mon ased exponent value ol «<ill or 100001 10 binary is put
precision, or In other words a better approximation. in as bits 23 through 30. Finally, since the number is
The numbei ol iIilmis you can store for the exponent ol pi isi inc. ,1 o is pui in bit 31 as the sign bit. The complete
a number determines the range of magnitudes ol num result is then 0100001 1001 100101 010000000000000
licis you can store in your computer or calculator. The or 4332A000H, which is lengthy, but not difficult to
sign ol the exponent indicates whethei the magnitude produce.
of the number is greater than one or less than one The The long-real format shown in Figure 1 1 - 1 h uses 64
sign ol the significand or mantissa indicates whether bits to represent each number Ibis format is often re-
the number itself is positive 01 negative. Now let's sec ferred
as todouble-precision representation. This for-
how you represent real numbers in binary form so the matbasically
is the same as thai of the short -real, except
8087 can digest them. that it allows greater range and accuracy because more
First let's look at the short-real format shown in Fig- bits are used for each number. For long-real, 52 bits are
ure
1-18.
1 This format, which uses 32 bits to represent used to represent the magnitude Ol the number. Again
a number, is sometimes referred to as single precision the number is normalized so that only a single 1 is to the
representation. In this format 23 bits are used to repre- left of the binary point. You can think of the binary point
sent the
magnitude of the number. 8 bits to represent as being between the bits numbered 5 1 and 52. The one
the magnitude of the exponent, and 1 bit to indicate to the left of the binary point is not actually put in as one
whether the number is negative or positive. The magni- of the 64 bits. For this format. 1 1 bits are used for the
tudethe
of number is normalized so th.U there is only a exponent, so the offset added to each exponent value is
single one to the left of the binary point. The one to the 1023 decimal or 3FFH. The most significant bit is the
left of the binary point is not actually present in the rep- sign bit. Our example number of 178.625 will be repre-
resentation,
is simplyit assumed to be there. This sented
thisin long-real or double-precision format as
leaves more bits for representing the magnitude of the 4066540000000000H. Note in Figure 1 1-18 the range of
number. You can think of the binary point as being be- numbers that can be represented with this format. This
tweenbits
the numbered 22 and 23. The exponent for range should be large enough for most of the problems
this format is put in an offset form, which means that you want to solve with an 8087.
an offset of 127 (7FH) is added to the 2's complement The final format in Figure 11-18 to discuss is the
value of the exponent. This is done so that the magni- temporary-real format which uses 80 bits to represent
tudetwo
of numbers can be compared without having to each number. This is the format that all numbers are
do arithmetic on the exponents first. The sign bit is 0 converted to by the 8087 as it reads them in, and it is
for positive numbers, and 1 for negative numbers. To the format in which the 8087 works with numbers in-
help make this clear to you. we will show you how to ternally.large
The number of bits used in this format
convert a decimal number to this format. reduces rounding errors in long chain calculations. To
We chose the number 178.625 for this example be- understand what this means, think of multiplying
causefractional
the part converts exactly, and therefore 1234 x 4567 in a machine that can only store the upper
we don't have to cope with rounding at this point. The 4 digits of the result. The actual result of 5.635,678 will
first step is to convert the decimal number to binary to be truncated to 5.635,000. If you then divide this by
give 101 10010.101 as shown in Figure 11-19. Next nor- 1234 to get back to the original 4567, you get instead
malizebinary
the number so that only a single one is to 4566 because of the limited precision of the intermedi-
the left of the binary point and represent the number of ate number.
bit positions you had to move the binary point as an As you can see in Figure 1 1-18, the temporary-real for-
exponent as shown in Figure 11-19. The result at this mat hasa sign bit, 15 bits for a biased exponent, and 64
point is 1.01 10010101E7. If you now add the bias of bits for the significand. The offset or bias added to the
exponent here is 16.383 decimal or 3FFFH. A major dif-
178.625 DECIMAL ference
the insignificand for this format from that for
10110010.101 BINARY
short-reals and long-reals is that the 1 to the left of the
1.0110010101 E7
binary point after normalization is included as bit 63 in
01000011001100101010000000000000 the significand. To express our example number of
"

BINARY POINT 178.625 in this form, then, we convert it to binary and


normalize it as before to give 1.01 10010101E7. This
BIASED SIGNIFICAND
gives us the upper bits of the significand directly as
EXPONENT
10110010101. We simply add enough O's on the right of
-SIGN this to fill up the rest of the 64 bits reserved for the sig-
nificand.
produce
To the required exponent, we add the
FIGURE 11-19 Converting a decimal number to short-real bias value of 3FFFH to our determined value
format. of 7. This gives 4006H or 100000000000110

MUITIPLE MICROPROCESSOR SYSTEMS AND BUSES 383


binary as the value for the exponent. The sign bit is a stack pointer in the 8087 is loaded with 000. so register
0 because the number is positive. Putting all of these 0 is then the TOS. When the 8087 reads in the first
pieces together gives4006B2A0000000000000H number that it is going to work on from memory, it con-
as the temporary-real representation of 178.625. This verts number
the to 80-bit temporary-real format if nec-
concludes our initial discussion of the way numbers essary.
then It decrements the stack pointer to 111, and
are represented for the 8087. writes the temporary-real representation of the number
in register number 111 (71. Figure 1 l-22a shows this in
diagram form. As shown by the arrow in the figure, you
can think of the stack as being wrapped around in a
The 8087 Internal Architecture circle so that if you decrement 000 you get 111. Also
Figure 1 1-20 shows a block diagram of the 8087. As we from this diagram you can see that if you push more
described before, the 8087 connects directly on the ad- than 8 numbers on the stack they wrap around and
dress, data,
and status lines of the 8086 or 8088 so that write over previous numbers. After this write-to-stack
it can track and decode instructions fetched by the 8086 operation, register 7 is now the TOS.
or 8088 host. The 8087 has a control-word register and In the 8087 instructions the register that is currently
a status register. Control words are sent to the 8087 by the TOS is referred to as ST(0), or simply ST. The regis-
writing them to a memory location and having the 8087 ter justbelow this in the stack is referred to as ST( 1 ). By
execute an instruction which reads in the control word the register "just below." we mean the register that the
from memory. Likewise, to read the status word from an stack pointer would be pointing to if we popped one
8087 you have it execute an instruction which writes number off the stack. For the example in Figure 1 l-22a,
the status word to memory where you can read or check register 000 would be ST( 1 ) after the first push.
it with an 8086 instruction. Figure 11-21 shows the for- To help you understand this concept. Figure 1 l-22b
mats for
the 8087 control and status words. Take a look shows another example. In this example we have
at these now so you have an overview of the meaning of pushed three numbers on the stack after initializing.
the various bits of these words. We will discuss the Register 101 is now the TOS, so it is referred to as ST(0)
meaning of most of these bits as we work our way or just ST. The preceding number pushed on the stack
through the following sections. is in register 1 10, so it is referred to as ST| 1 ). Likewise,
The 8087 works internally with all numbers in the the location below this in the stack is referred to as
80-bit temporary-real format which we discussed in the ST(2). If you draw a diagram such as that in Figure
preceding paragraphs. To hold numbers being worked 1 l-22b, it is relatively easy to keep track of where every-
on, the 8087 has a register stack of eight, 80-bit regis- thingin isthe stack as instructions execute. In a pro-
ters labeled101-17) in Figure 1 1-20. These registers are gram youcan determine which register is currently the
used as a last-in-first-out stack in the same way the ST by simply transferring the status word to memory
8086 uses a stack. The 8087 has a 3-bit stack pointer and checking the bits labeled ST in the status-word for-
which holds the number of the register which is the cur- matFigure
in 1 1-2 lb. Now let's have a look at the 8087
rent top-of-stack. When the 8087 is initialized, the 3-bit instruction set.

TNu^mcT. ec~ ,o~N,r ~1

I 4-*-4
&

11

L J
FIGURE 11-20 8087 internal block diagram. (Intel Corporation)

384 ( HAPTERELEVEN
1 . % I I "% I' '% I "I h'h'H % -•'hi"I

Li INVALID mi

UNO! m 1 i IW

INTERRUP1

'. % l iNTRl il

ROUNDINl,'

(RrSERVEOi

1 I InU'lIUpl I N.lhlr M.I .h


0 Inlerfupls Enabled
t Interrupts Disabled (Masked)'
(2) Precision Control
00 24ijits
01 (reserved!
10 53 bits
11 64 bits

(3) Rounding Control


00 Round to Nearest or Even-
01 Round Down (toward %)
10 Round Updoward
11 - Chop (Truncate Toward Zero!
(4) Infinity Control
0 - Protective*
i Atfine
% DEFAULT AFTER FINIT

EXCEPTION FLAGS (1 EXCEPTION HAS OCCURRED)

Li INVALID

DENORMALIZED
OPERATION

OPERAND

ZERODIVIDE

OVERFLOW

UNDERFLOW

PRECISION

(RESERVED)
INTERRUPT REOUEST
CONDITION CODE1"

STACK TOP POINTER121

BUS I

(1) See descriptions ot compare, le Li. :n.. onS 7tor


condition code interpretation
(2) ST values
000 = register 0 is slack top
001 = register 1 is stack lop

FIGURE 11-21 8087 control and status word formats, (a) Control, (b) Status.
(Intel Corporation)

8087 Instruction Set be written as 8086 ESCAPE (ESC) instructions followed


by a number as, for example. ESC 28, or they can be writ-
ten using specific 8087 mnemonics. For the following
8087 INSTRUCTION FORMATS discussion we will use the 8087 mnemonics. Later we
Before we work our way through the list of 8087 instruc- will show you how to code the instructions as ESC in-
tions will
we use one simple instruction to show you structions
you don't
if have an assembler which accepts
how 8087 instructions are written, how they operate, 8087 mnemonics. The instruction we have chosen to
and how they are coded. Instructions for the 8087 can use as an example here is the FADD instruction.

MUtTIPtE MICROPROCESSOR SYSTEMS AND BUSES 385


REGISTER with the DT directive. If you want to add an integer
NUMBER number from memory to ST. you use an instruction such
111 — ST(0) AFTER as FIADD CORRECTION FACTOR. The I in the mnemonic
1 10 FIRST PUSH tells the assembler to code the instruction so that the
101 REG 000 NOW 8087 treats the number read in as an integer.
100 ST(1)
01 1
NOTE: The FIADD instruction only works for a source
010
operand in memory.
00 1
The /destination, source in the representation of the
000 - ST(0)
FADD instruction means that you can write the instruc-
AFTER RESET
tion withboth a specified source and a specified desti-
8087 STACK REGISTERS nation. source
The can be one of the stack elements, or a
number from memory. The destination has to be one of
the stack elements. The instruction FADD ST(2), ST(1).
REGISTER
for example, will add the number one location down
NUMBER
from ST to the number two locations down from ST. and
111 ST(2)
leave the result in STI2). The instruction FADD ST(3),
110 ST(1)
CORRECTION FACTOR will add the real number from
101 — TOS ST((
the memory location named CORRECTION FACTOR to
100 ST(7)
the contents of the ST(3) stack element.
011 ST(6)
Another form of the 8087 FADD instruction shown in
0 10 ST(5)
the data book is FADDP. The P at the end of this mne-
001 ST(4)
monic means
to POP. When the 8087 executes this form
000 ST(3)
of the FADD instruction, it will increment the stack
pointer by one after it does the add operation. This is
8087 STACK REGISTERS referred to as "popping the stack." The instruction
lb) FADDP ST(1), ST(4), for example, will add the number at

FIGURE 11-22 8087 stack operation, (a) Condition of ST(4) to the number at ST(ll. and put the result in
stack after reset and one push, (b) Condition of stack ST|1). It will then "pop the stack" or. in other words,

after reset and three pushes. increment the stack pointer so that what was ST(1) is
now ST. This form of the instruction leaves the result at
ST where it can easily be transferred to memory. Now
All ill the 8087 mnemonics start with an F. which
let's see how the different forms of this instruction are
stands for floating point, the form in which the 8087
coded.
works with numbers internally. If you look in the Intel
data book, you will see this instruction represented as
CODING 8087 INSTRUCTIONS
FADD //source/destination, source. This cryptic repre-
sentation means
that the instruction can be written in The coding templates for all of the 8087 instructions are
three different ways. in the appendix for your reference. You use these tem-
The // at the start indicates that the instruction can be plates
thein same manner as you do those for the 8086
written without any specified operands as simply FADD. instructions. For closer reference. Figure 11-23 shows
In this case, when the 8087 executes the instruction it the coding templates for the 8087 FADD instructions in
will automatically add the number at the top of the stack the form shown in the appendix and in expanded form
(ST) to the number in the next location under it in the so you can see the individual bits. Note that the figure
stack. STI 1 ). The 8087 stack pointer will be incre- shows coding for "8087" encoding and for "emulator"
mented
oneby so that the register containing the result encoding. The 8087 encoding represents the codes re-
will be ST. quiredthebyactual device. The emulator encoding rep-
The word "source" by itself in the expression means resentscodes
the needed to call an FADD procedure
that the instruction can be written as FADD source. The from an available Intel library of 8086 procedures which
source specified here can be one of the stack elements, perform the same functions as the 8087 instructions.
or a memory location. For example, the instruction The procedures in this library, written in 8086 code,
FADD ST(2) will add the number from two locations run much slower, but they allow you to test an 8087
below ST to the number in ST. and leave the result in program without having an actual 8087 in the system.
ST. As another example, the instruction FADD We will concentrate here on the codes for the actual
CORRECTION FACTOR will add a real number from the 8087 device.
memory location named CORRECTION FACTOR to First let's look at the coding for the FADD instruction
the number in ST and leave the result in ST. The assem- with no specified operands. This instruction, remem-
bler willbe able to determine whether the number in ber, will
add the contents of ST to the contents of ST( 1 ).
memory is a short-real, long-real, or temporary-real by the put the results in STI 1 ). and then pop the stack so that
way that CORRECTION FACTOR was declared. Short- the result is at ST. The first bvte of the instruction code.
reals, for example, are declared with the DD directive, 10011011. is the code for the 8086 WAIT instruction.
long-reals with the DQ directive, and temporary-reals Remember from our previous discussion that this in-

386 CHAPTER EEFVEN


FADD

Stack top • Slack Element

type I Slack top and stack element


| WAIT OP1 |
Execution
Clocks

8087 Emulator Typical


10011011 11011 d 00 11000(1)
Encoding Encoding Range Operation

11001101 00011 dOO 11000(1) 9B D8 CO • i CD 18 CO 85


70 11)0

9B DC CO t CD 1CC0t 85 ST(i). ST • ST(1)


70-100

type 2 si. nk top and niemor) operand


Slack top i memor) operand

10011011 11011 m 00 mod 000 r m WAN upl ID r addr2 I

11001101 00011 mOO mod 000 r m

8087 Emulator Typical


in - tl lor short real operand; I lor long real operand Encoding Encoding Range Operation

9B D8 mOrm CD18m0rm 105 -EA ST- ST • mem-op


(90-120) - EA (short-real)
9B DC mOrm CD 1C mOrm 110 • EA ST- ST t mem-op
type 3: Pop slack (95-125) - EA (long-real)

10011011 11011110 11000(1) FADDP = Add Real and Pop

Slack top + Slack Element


11001101 00011110 11000(1)

I WAIT opl op2. i |


Execution
8087 Timing (clocks) TYPICAL RANGE
Clocks

8087 Emulator Typical


stack element and stack top 85 70-100
stack element, stack top + pop 90 75-105 Encoding Encoding Range Operation
short real memory and stack top 105 + EA 90-120- EA
9BDEC1 CD 1EC1 90 ST(1). ST • ST(
long real memory and stack top 1 10 + EA 95-125- EA
75-105 pop stack

9BDEC0-I CD 1 ECO- 90 ST(i). ST + ST(i)


75-105 pop slack

FIGURE 11-23 8087 FADD coding templates. (Intel Corporation)

st ruction code is put here to make the 8086 and 8087 struction
nowith
specified source or destination gives
wait until it has completed a previous instruction before 10011011 11011100 11000001 binary or 9BH DCH
starting this one. The second byte shown is actually the C1H as the code bytes.
first byte of the 8087 FADD instruction. The 5 most- For a little more practice with this see if you can code
significant bits. 11011, identify this as an 8087 instruc- the 8087 instruction FADD ST, ST(2). Most of the coding
tion. The
lower 3 bits of the first code byte and the mid- for this instruction is the same as that for the previous
dlebits
3 of the second code byte are the opcode for the instruction. For this one. however, the d bit is a 0 be-
particular 8087 instruction. The bit labeled d at the causeisST the specified destination. Also, the R/M bits
start of these 6 is a 0 if the destination for an FADD are 010. because the other register involved in the addi-
ST(N), ST(N) type instruction is ST. The d bit is a 1 if the tionST(2).
is The answer is 9BD8C2H. Now let's try an
destination stack element is one other than ST. as it is example which uses memory as the source of an oper-
for the FADD instruction with no specified operands. and for
FADD.
For the FADD instruction with no specified operands For an FADD instruction such as FADD COR-
these 6 bits will be 100 000. The two most significant RECTION FACTOR,
which brings in one operand from
(MODI bits in the second code byte are ones, because memory and adds it to ST, the memory address can be
this form of the FADD instruction does not read a num- specified in any of the 24 ways shown in Figure 3-8. For
ber frommemory. The least-significant 3 bits of the sec- the memory reference form of the FADD instruction the
ond instruction byte, represented by an i in the tem- MOD and R/M bits in the second code byte are used to
plate, indicatewhich stack element other than ST is specify the desired addressing mode. FADD COR-
specified in the instruction. Since the simple FADD in- RECTION FACTOR
represents direct addressing, so the
structionST(1)
uses as a destination. 001 will be put in MOD bits will be 00 and the R/M bits will be 1 10 as
these bits. Putting all of this together for the FADD in- shown in Figure 3-8. Two additional code bytes will be

MULTIPLE MICROPROCESSOR SYSTEMS AND BUSES 387


used to put in the direct address, low byte first. Since we our examples in a previous section. According to the
are not using any of the other stack elements other than templates in the appendix, the code for this instruction
ST for this instruction, we don't need the d bit to specify is 10011011 11011000 llOOOi. The 10011011 at the
the other stack element. Instead, as shown in Figure start is the code for the WAIT instruction. The 6 under-
1 1-23. this bit is labeled m. A 0 in this bit is used to lined bits
from this code that you use for the immediate
specify a short-real, and a 1 in this bit is used for a number in the ESC instruction are 000 000. The ones
long-real. Assuming CORRECTION FACTOR is declared in the MOD position of the last code byte indicate that
as a long-real, the code bytes for our FADD COR- only registers are involved in the operation. The three i
RECTION FACTOR
instruction will then be 10011011 bits in this byte must contain the number of the other
1 101 1 100 000001 10 followed by the two bytes of the stack element besides ST that is used in the instruction.
direct address. For our example here we want the assembler to put in
So far in this section we have shown you examples of 010 or 2 for these bits, because we are using ST(2). To
how some 8087 instructions will be coded out if they are get the assembler to put in 1 1 for the MOD bits in the
written with 8087 mnemonics and assembled with an ESC instruction code, you simply put an 8086 register
assembler that recognizes 8087 mnemonics. If you don't name after the immediate number in the ESC instruc-
have an assembler with 8087 capability, you can code tion. The
register name you use tells the assembler what
8087 instructions as 8086 ESCAPE (ESC) instructions to put in the 3-bit i field of the instruction. Look at Fig-
with the help of the 8087 instruction templates in the ure 3-8to determine the 3-bit codes for each of the 8086
appendix. Your 8086 assembler should then produce registers. The code of 010 which you need here corre-
the correct code for them. Here's how you do it. sponds
thatto for the DX register. If you put all of these
The 8086 ESC instruction has two basic forms. The pieces together, the 8087 FADD ST, ST(2) can be written
first of these. ESC immediate, memory, is used to pro- as the 8086 ESC 00H, DX instruction. Once you see the
duce 8087instructions which bring an operand in from correspondence here, it is not too difficult to get the
memory or send an operand out to memory. The second 8086 assembler to produce a desired 8087 instruction
form of the escape instruction is ESC immediate, regis- code. Now that you have an overview of how 8087 in-
ter. Thissecond form is used to produce 8087 instruc- structions
written
are and coded, we will briefly discuss
tions whichoperate only on registers. We'll start with the operation of the available 8087 instructions.
the ESC immediate, memory form.
8087 INSTRUCTION DESCRIPTIONS
The coding template for the ESC immediate, memory
instruction is 1101 lxxx MODxxxR/M. The 6 x's in the The 8087 instruction mnemonics all begin with the let-
template represent a 6-bit binary opcode for the desired terwhich
F stands for floating point and distinguishes
8087 instruction. You specify these 6 bits in the ESC the 8087 instructions from 8086 instructions. We have
instruction as an immediate number. You determine found that if we mentally remove the F as we read the
the value for this immediate number by looking at the mnemonic, it makes it easier to connect the mnemonic
coding template for the 8087 instructions in the appen- and the operation performed by the instruction. Here we
dix. Forexample, suppose that you want to use the briefly describe the operation of each of the 8087 in-
ESC instruction to produce the FADD CORREC- structions
that soyou can use some of them to write
TION FACTORinstruction. In our discussion of the simple programs. As you read through these instruc-
coding lor this instruction above, we determined that tions first
the time, don't try to absorb them all, or you
if CORRECTION FACTOR is a long-real, then the bi- probably won't remember any of them. Concentrate first
nary codefor the instruction is 10011011 11011100 on the instructions you need to get operands from mem-
0000001 1 followed by the direct address in the next 2 ory intothe 8087. simple arithmetic instructions, and
bytes. The first byte of this is the WAIT instruction. The the instructions you need to get results copied back
values for the 6 bits that we are interested in are 1 00000. from the 8087 to memory where you can use them. Then
Converting this to hex gives 20H, the immediate num- work your way through the first example program in the
ber youneed to put in the ESC instruction. You write next section. After that, read through the instructions
the 8086 ESC instruction then as ESC 20H, CORREC- again and pay special attention to the transcendental
TION FACTOR.When the assembler reads this in- instructions and the load constant instructions. Fi-
struction statement,it will automatically determine the nally, work
your way through the second example pro-
values for the MOD and the R/M bits of the instruction gramthein next section. We hope that you will find, as
from the reference to the memory location COR- we have, that the 8087 is fun to work with. After you
RECTION^ FACTOR.
You can put an 8086 WAIT instruc- play around with some simple programs such as those
tion before the ESC instruction if necessary. here, you can go to the Intel literature to get more infor-
Now we will show you how to write an ESC instruction mation about
error handling and more complex pro-
to produce an 8087 instruction which operates only on gram examples.
internal registers of the 8087. The coding template for The instructions are grouped here in four functional
this ESC instruction is also 1101 lxxx MODxxxR/M. The groups so that you can more easily find the instruction
(> x's again represent the desired 8087 opcode. You get which performs a desired operation. A section in the
the values for these bits from the 8087 code templates in appendix shows the coding templates and clock cycles
the appendix. As an example, suppose that you want to for each instruction.
get the 8086 assembler to produce the correct code for If the 8087 detects an error condition, usually called
the 8087 instruction FADD ST, ST(2), which was one of ,ni exi cption, while it is executing an instruction, it will

:*88 ( IIAI'HR ELEVEN


sci the appropriate bil In its status register. After the lls| destination Integer store Convert numbei from
Instruction finishes executing, the status registei con ST to integer form, and copy to memory. Exceptions: I.
tents can be transferred to memory with anothei 8087 P. Example:
Instruction. You ran then use 8086 Instructions to FIST LONG INT : ST to memory locations
check the status bits and decide whal action to take , named LONG INT
.hi error has occurred. Figure I I -2 1 /) shows the formal
ol the 8087 status word I he lowest 6 in is are the excep FISTP destination Integei store and pop. Identical to
t ion status hits. These hits will all he o's il no errors have MSI except that stack pointei is incremented aftei
occurred. In the instruction descriptions following, we copy.
use the first lettei ol each exception type to Indicate the
status hits affected by each instruction.
II yon send the 8087 a control word which unmasks Packed Decimal Transfers
the exception interrupts as shown in Figure 1 1-2 lu. t Ik- FBLD source Packed decimal(BCD) load Convert num-
SOS? will also send a hardware interrupt signal to the
bei from
memory to temporary real format and push on
808t>. when an error occurs. II the 8086 interrupt input top ol 8087 stack. Exception: I. Example:
is enabled, this allows the 8086 to go directly to an ex
FBLD MONEY DUE ; ten byte BCD number from
ception handling procedure. : memory to SI

DATA TRANSFER INSTRUCTIONS FBSTP destination — BCD store in memory and pop ,so<s7
stack. Pops temporary-real from stack, converts to
10-byte BCD, and writes result to memory. Exception: I.
Real Transfers Example:
FBSTP TAX : ST converted to BCD, sent to memory
FLD source — Decrements the stack pointer by one and
copies a real number from a stack element or memory
ARITHMETIC INSTRUCTIONS
location to the new ST. A short-real or long-real number
from memory is automatically converted to temporary-
real format by the 8087 before it is put in ST. Excep-
Addition
tions:
D. I.Examples:
FLD ST(3| : Copies ST|3| to ST FADD //source/destination, source — Add real from speci-
FLD LONG REAL(BX] ; Number from memory copied fied source to real at specified destination. Source can
: to ST be stack element or memory location. Destination must
be a stack element. If no source or destination is speci-
FST destination — Copies ST to a specified stack position fied, thenST is added to ST( 1 ) and the stack pointer is
or to a specified memory location. If a number is trans- incremented so that the result of the addition is at ST.
ferred
a memory
to location, the number and its expo- Exceptions: I. D. O. U, P. Examples:
nent will
be rounded to fit in the destination memory FADD STI3), ST ; Add ST to ST13), result in STI3)
location. Exceptions: I. O, U. P. Examples: FADD ST.ST14) : Add STI4I to ST. result in ST
FST STI21 ; Copy ST to STI2). and FADD INTEREST : Real num from mem + ST
: increment stack pointer FADD : ST + ST( 1). pop stack-result at ST
FST SHORT_REAL[BX] : Copy ST to memory
: at SHORT REAL[BX| FADDP destination, source — Add ST to specified stack
element and increment stack pointer by one. Excep-
FSTP destination — Copies ST to a specified stack element tions:
D, I,O, U. P. Example:
or memory location and increments the stack pointer by FADDP ST| 1] : Add ST( 1 ] to ST. Increment stack

one to point to the next element on the stack. This is a : pointer so ST(1) becomes ST

stack POP operation. It is identical to FST except for the


effect on the stack pointer. FIADD source — Add integer from memory to ST. result
in ST. Exceptions: I. D. O. P. Example:
FXCH //destination — Exchanges the contents of ST with FIADD CARS SOLD ; Integer number from
the contents of a specified stack element. If no destina- : memory + ST
tionspecified,
is then ST(1) used. Exception: I. Exam-
ple:
FXCH ST(5) : Swap ST and ST(5) Subtraction
FSUB //source/destination, source— Subtract the real
number at the specified source from the real number at
Integer Transfers the specified destination and put the result in the speci-
F1LD source — Integer load. Convert integer number from fied destination. Exceptions: I. D. O. U. P. Examples:
memory to temporary-real format and push on 8087
stack. Exception: I. Example: FSUB STI2). ST : STI2] becomes ST(2) - ST
FILD DWORD PTR [BX] : Short integer from memory FSUB CHARGE ; ST becomes ST - real from memory
: at [BX] FSUB ; ST becomes (ST( 1 ) - ST)

MUtTIPfE MICROPROCESSOR SYSTEMS AND BUSES 389


FSUBP destination, source — Subtract ST from specified Reversed Division
stack element and put result in specified stack element. FDIVR source/destination, source
Then increment stack pointer by one. Exceptions: I, D. FDIVP destination, source
O. U. P. Examples: FIDIVR source
FSUBP ST( 1 ) ; ST( 1) - ST. ST( 1 ) becomes new ST.
These three instructions are identical in format to the
FDrv. FDIVP. and FIDrV instructions above except that
FISUB source — Integer from memory subtracted from they divide the source operand by the destination oper-
ST. result in ST. Exceptions: I, D. 6. P. Example:
and and
put the result in the destination.
FISUB CARS- SOLD : ST becomes ST - integer
; from memory
Other Arithmetic Operations
FSQRT — Contents of ST are replaced with its square
Reversed Subtraction root. Exceptions: I. D. P. Example: FSQRT
FSUBR source destination, source FSCALE— Scale the number in ST by adding an integer
FSUBRP /destination, source value in ST( 1 ) to the exponent of the number in ST. Fast
FISUBR source way of multiplying by integral powers of two. Excep-
tions:
O. I,U.
These instructions operate the same as the FSUB in-
FPREM — Partial remainder. The contents of ST( 1 ) are
structions described
above except that these instruc-
subtracted from the contents of ST over and over again
tions subtract the contents of the specified destination
until the contents of ST are smaller than the contents of
from the contents of the specified source and put the
ST( 1 ). In an 8087 program example later in this chapter
difference in the specified destination. Normal FSUB
we show how FPREM is used to reduce a large angle to
instructions, remember, subtract source from destina-
less than ~/4 so that we can use the 8087 trig functions
tion.
on it. Exceptions: I. D. U. Example: FPREM

FRNDINT — Round number in ST to an integer. The


Multiplication round-control (RC) bits in the control word determine
how the number will be rounded. If the RC bits are set
FMUL source destination, source — Multiply real num-
for down or chop, a number such as 205.73 will be
ber fromsource by real number from specified destina-
rounded to 205. If the RC bits are set for up or nearest.
tion, and
put result in specified stack element. See
205.73 will be rounded to 206. Exceptions: I. P.
FADD instruction description for examples of specifying
operands. Exceptions: 1. D. O. U. P.
FXTRACT— Separates the exponent and the significand
parts of a temporary-real number in ST. After the in-
FMULP destination, source — Multiply real number from struction executes.
ST contains a temporary-real repre-
specified source by real number from specified destina- sentation
the significand
of of the number and ST(1)
tion, put
result in specified stack element, and incre- contains a temporary-real representation of the expo-
ment stack
pointer by one. See FADDP instruction for nentthe
of number. These two could then be written
examples of how to specify operands for this instruc- separately out to memory locations. Exception: I.
tion. With
no specified operands FMULP multiplies
ST| 1 1by ST and pops stack to leave result at ST. Excep- FABS— Number in ST is replaced by its absolute value.
tions:
D. I.O. U. P. Instruction simply makes sign positive. Exception: I.

FIMUL source — Multiply integer from memory times ST FCHS — Complements the sign of the number in ST.
and put result in ST. Exceptions: I. D. O. P. Example: Exception: I.

COMPARE INSTRUCTIONS
FIMUL DWORD PTR [BX1
The compare instructions with COM in their mnemonic
compare contents of ST with contents of specified or
default source. The source may be another stack ele-
Division
ment real
or number in memory. These compare in-
FDIV //source destination, source — Divide destination structions
the setcondition code bits C3. C2. and CO of
real bv source real, result goes in destination. See FADD the status word shown in Figure 1 1-2 lb as follows:
formats. Exceptions: I. D. Z. O. U. P.
C3 C2 CO

FDIVP destination, source— Same as FDIV. but also in-


0 0 0 ST > source
crement stack
pointer by one after DIV. See FADDP for-
mats. Exceptions: I. D. Z. O, U. P. 0 0 0 ST < source

1 0 0 ST = source
FIDIV source — Divide ST by integer from memory, result
1 1 1 numbers cannot be compared
in ST. Exceptions: I, D. Z. O. U. P.

390 CHAPTER ELEVEN


You can transfei the status word to memory with the F2XM1 Computes the function ) .' ' l foi an X
8087 FSTSW instruction and then use 8086 instruc value in ST. The result. Y. replaces X In ST. X must be in
lions to determine the results ol the comparison. Here the range 0 X 0.5 lo produce 2X, you can simply
.in the differenl compai es. add one lo i he resuli from this instruction Usin
common equalities you can produce values often needed
11 i )M source Compares ST with real number in an- in engineering and scientific calculations. Here are
other stack
element or memory Exceptions: I. D. Exam some examples.
pics: 10* 2xtLOC"101
FCOM ( (Hiip.ii is si wil li si 111
[COM ST(3) Compares ST with ST(3) (.\ ., %
FCOM MINIMUM PAYMEN1 Compares ST with real
y\ ., All I II. .1 |
from memoi \

FYL2X Calculates Y times the LOG to the base 2ofXoi


FCOMP source Identical to FCOM except that the
Y(LOG2X). X must be in the range ol 0 X < and V
slack pointer is incremented by one alter the compare
must be in the range % V • c. X must initially be in
operation. Old ST| 1 ) becomes new ST.
ST and Y must be in Sill I. The result replaces Y and
then the stack is popped so that the result is then al ST.
I (.OMIT ( ompare ST with ST( 1) and increment stack This instruction can be used to compute the lor; ol a
pointer by 2 after compare. This puts the new ST above number in am base. n. using the identity LOGnX
the two numbers compared. Exceptions: 1, D. LOG„2(LOG2X). For a given n, LOG„2 is a constant
which can easily be calculated and used as the Y value

FICOM source — Compares ST to a short or long integer for the instruction. Exceptions: P.

from memory. Exceptions: 1. D. Example:


FICOM MAX ALTITUDE FYL2XP1— Computes the function Y times the LOG to
the base 2 of (X + 1 ) or Y(LOG2(X + 1 )). This instruction
is almost identical to FYL2X except that it gives more
FICOMP source— Identical to FICOM except stack
accurate results when computing the LOG of a number
pointer is incremented by one after compare.
very close to one. Consult the Intel manual for further
detail.
FTST — Compares ST with zero. Condition code bits C3.
C2. and CO in the stains word are set as shown above if
INSTRUCTIONS WHICH LOAD CONSTANTS
you assume the source in this case is zero. Exceptions:
1. D. The following instructions simply push the indicated
constant on the stack. Having these commonly used
FXAM — Tests ST to see if it is zero, infinity, unnormal- constants available reduces programming effort.
ized. or empty. Sets bits C3. C2, CI. and CO to indicate
FLDZ —Push 0.0 on stack
result. See Intel data book for coding. Exceptions: None.
FLD1 —Push +1.0 on stack
FLDP1 — Push the value of -n on stack
TRANSCENDENTAL (TRIGONOMETRIC AND
FLD2T —Push LOG of 10 to the base 2 on stack
EXPONENTIAL) INSTRUCTIONS
(LOG210)
FPTAN — Computes the values for a ratio of Y/X for an FLDL2E —Push LOG of e to the base 2 on stack (LOG2e)
angle in ST. The angle must be expressed in radians. FLDLC2— Push LOG of 2 to the base 10 on stack
and the angle must be in the range of 0 < angle < n/4. (LOG|„2)

NOTE: FPTAN does not work correctly for angles of ex-


PROCESSOR CONTROL INSTRUCTIONS
actly
and0 7r/4. You can convert an angle from degrees to
radians by dividing it by 57.295779. An angle greater These instructions do not perform computations. They
than 7t/4 can be brought into range with the 8087 are used to do tasks such as initializing the 8087, ena-
FPREM instruction. The Y value replaces the angle on bling interrupts,writing the status word to memory,
the stack, and the X value is pushed on the stack to etc.
become the new ST. The values for X and Y are created Instruction mnemonics with an N as the second char-
separately so you can use them to calculate other trig acter havethe same function as those without the N,
functions for the given angle as we show in an example but they put a NOP in front of the instruction instead of
program later in this chapter. Exceptions: 1. P. putting a WAIT instruction there.

FPATAN— Computes the angle whose tangent is Y/X. The FINIT/FNINT— Initializes 8087. Disables interrupt out-
X value must be in ST, and the Y value must be in ST( 1 ). put, sets
stack pointer to register 7, sets default status.
Also, X and Y must satisfy the inequality 0 < Y < X < *-.
The resulting angle expressed in radians replaces Y*in FDISI/FNDISI— Disables the 8087 interrupt output pin
the stack. After the operation the stack pointer is incre- so that it cannot cause an interrupt when an exception
mented
the soresult is then ST. Exceptions: U, P. (error) occurs.

MULTIPLE MICROPROCESSOR SYSTEMS AND BUSES 391


FENI/FNENI— Enables 8087 interrupt output so it can 8087 Example Programs
cause an interrupt when an exception occurs.
PYTHAGORAS REVISITED
FLDCW source — Loads a status word from a named
memory location into the 8087 status register. This in- As you may remember from back there somewhere in
struction should
be preceded by the FCLEX instruction geometry, the pythagorean theorem states that the hy-
to prevent a possible exception response if an exception potenuse (longest
side) of a right triangle squared is
bit in the status word is set. equal to the square of one of the other sides plus the
square of the remaining side. This is commonly written
FSTCW/FNSTCW destination— Copies the 8087 control as C2 =A2 + B2. For this example program we want to
word to a named memory location where you can deter- solve this for the hypotenuse, C, so we take the square
mine current
its value with 8086 instructions. root of both sides of the equation to give C = \ A2+B2.
Figure 1 1-24 shows a simple 8087 program you can use
FSTSW/FNSTSW destination— Copies the 8087 status to compute the value of C forgiven values of A and B. We
word to a named memory location. You can check vari- have shown the assembler listing for the program so you
ous status bits with 8086 instructions and base further can see the actual codes that are generated for the 8087
action on the state of these bits. instructions. Note, for example, that each of the codes
for the 8087 instructions here starts with 9BH. the code
FCLEX/FNCLEX—Clears all of the 8087 exception Hag bits for the WAIT instruction whose function we explained
in the status register. Unasserts BUSY and INT outputs. before.
At the start of the program we set aside some named
FSAVE/FNSAVE destination— Copies the 8087 control memory locations to store the values of the three sides of

word, status word, pointers, and entire register stack to our triangle, the control word we want to send the 8087,
a named. 94-byte area of memory. After copying all of and the status word we will read from the 8087 to check
this the FSAVE/FNSAVE instruction initializes the 8087 for error conditions. Remember, the only way you can
as if the FINIT/FNINIT instruction had been executed. pass numbers to and from the 8087 is by using 8087
instructions to read the numbers from memory loca-

FRSTOR source — Copies a 94-byte named area of mem- tionswrite


or the numbers to memory locations. In this

ory intothe 8087 control register, status register, section of the example program the statement SIDE A

pointer registers, and stack registers. DD 3.0 tells the assembler to set aside two words in
memory to store the value of one of the sides of the tri-
angle. The
decimal point in 3.0 tells the assembler that
FSTENV/FNSTENV destination— Copies the 8087 control
this is a real number. The assembler then produces the
register, status register, tag words, and exception point-
short-real representation of 3.0 (40400000) and puts it
ers atonamed series of memory locations. This instruc-
in the reserved memory locations. Likewise the state-
tion does
not copy the 8087 register stack to memory as
ment SIDE
B DD 4.0 tells the assembler to set aside two
the FSAVE/FNSAVE instruction does.
word locations and put the short-real representation of
4.0 in them. The statement HYPOTENUSE DD 0 reserves
FLDENV source— Loads the 8087 control register, status
a double word space for the result of our computation.
register, tag word, and exception pointers from a named
When the program is finished, these locations will con-
area in memory.
tain 40A00000. the short-real representation for 5.0.
The actual code section of this program you would
FINCSTP— Increment the 8087 stack pointer by one. If
normally write as a procedure so that you could call it as
the stack pointer contains 1 1 1 and it is incremented, it
needed. To make it simple here we have written it as a
will point to 000.
stand-alone program. We start by initializing the data
segment register to point to our data in memory. We
FDECSTP— Decrement stack pointer by one. If the stack
then initialize the 8087 with the FINIT instruction. The
pointer contains 000 and it is decremented, it will con-
notations for the control word in Figure ll-21a show
tain 111.
the default values for each part of the control word after

FFREE destination — Changes the tag for the specified FINIT executes. For most computations these values

destination register to empty. See the Intel manual for a give the best results. However, just in case you might
discussion of the tag word which you usually don't need want to change some of these settings from their default

to know about. values, we have included the instructions needed to


send a new control word to the 8087. You first load the
FNOP — Performs no operation. Actually copies ST to ST. desired control word in a reserved memory location with
the MOV CONTROL WORD, 03FFH instruction, and
FWAIT — This instruction is actually an 8086 instruc- then load this word into the 8087 with the FLDCW
tion which makes the 8086 wait until it receives a not CONTROL WORD instruction.
busy signal from the 8087 to its TEST pin. This is done to To perform the actual computation, we start in the
make sure that neither the 8086 nor the 8087 starts the inside of the equation and work our way outward. FLD
next instruction before the preceding 8087 instruction SIDE A brings in the value of the first side and pushes it
is completed. on the 8087 stack. FMUL ST, ST(0) multiplies ST by ST

392 < HAPTER ELEVEN


IBMPersonal Coaputer MACRO
Asseabler Version 2.00 Page 1-1
05-21-85
page ,132
;80B7 NUMERIC DATA PROCESSOR EXAMPLEPROGRAM

(ABSTRACT: This program calculates the hypotenuse of a right


triangle, given SIDE A and SIDE B
NAME PVTHAG

O'AM DATA.HERE SEGMENT


WORD PUBI
0000 00 00 *0 *0 SIDE_A DD 3.0 ; set aside space for Side A, short real
000* 00 00 80 *0 SIDE.B DD H.U i set aside space for Side B, short real
0008 00 00 00 00 HYPOTENUSE DD 0 ; set aside space for result, short real
; 5.0 normalized = *0AOOOO0
oooc 0000 CGNTROL.WORDDw 0 ; space for control word
OOOE 0000 STATUS.WORD DW 0 ', space for status word
0010 DATA_HERE ENDS

On 00 CODE.HERE SEGMENT
WORD PUBLIC
ASSUMECS:C0DE HERE, DSiDATAHERE
ESCAPE CODES
0000 B8 — - R START: MOV AX, DATA_HERE ; initialize data segment
0003 8E D8 MOV DS, AX
0005 9B DB E3 F1N1T ; initialize 8087 ESC 1CH, BX

0008 C7 06 OOOC R 03FF I1UV CONTROLWORD,03FFH put control word in meaorv


so 8087 can access it, round
to even, aask interrupts
OOOE 9B D9 2E OOOC R FLDCU CONTROL.WORD load control to 8087 ESC 0DH,C0NTR0L_U0RD
0013 9B D9 06 0000 R FLD SIDE A put value of SIDE_Aon
stack top ESC 08H, SIDE.A
0018 9B D3 C8 FMUL ST, ST(O) square SIDE.A ESCOIH, AX
00 IB 9B D9 06 000* R FLD SIDEJ get SIDE.B stack top ESC 08H. SIDEJ
0020 9B D8 C8 FMUL ST, STiO) square SIDE.B ESCOIH, AX
0023 9B D8 CI FADD ST. STU) add A squared + & squared ESC 00H, CX
result at top of stack
0026 ?s D9 FA FSQRT take square root of ST
result m ST ESC OFH, DX
0029 98 DD 3E OOOE R FSTSW STATUS.UORD copy status word to aemory
where 8086 can access it ESC 2FH, STATUS.yORD
002E 9B FWAIT wait until status store done
002F A! OOOE R HOV AX, STATUS_WORD bring status to AX to check
for errors
0032 2* BF AND AL, OBFH aask unneeded bit
003* 75 05 JN2 STOP handle error if found
0036 9B D9 IE 0008 R FSTP HYPOTENUSE no error, copy result fros
8087 to aeaory ESC OBH.HYPOTENU
00 3 & JO STOP: NOP
003C CODE.HERE
ENDS
END START

FIGURE 11-24 8087 program to compute the hypotenuse of a right triangle.

and puts the result in ST. so ST now has A2. Next we contains A2. We add these together and leave the result
bring in SIDE B and push it on the 8087 stack with the in ST with the FADD instruction. FSQRT takes the
FLD SIDE B instruction, and square it with the MUL ST, square root of the contents of ST and leaves the results
STIO) instruction. ST now contains B2 and ST| 1 ) now in ST. To see i! the result is valid, we copy the 8087

MULTIPLE MICROPROCESSOR SYSTEMS AND BUSES 393


status word to the memory location we reserved for it tangent based on this triangle. The 8087 FPTAN in-
with the FSTSW STATUS WORD instruction. We then struction
notdoes
produce the tangent of a given angle
use 8086 instructions to check the six exception status directly, it produces two proportional values which rep-
bits to see if anything went wrong in the square root resent
and Y X. You then divide the Y value by the X
computation. If there were no exceptions (errors), these value to produce the actual tangent value. To produce
status bits will all be O's. and the program will copy the the sine and cosine values for the given angle, you can
result from ST to the memory location named HYPOTE- use these values of X and Y in the relationships shown
NUSE using
the FSTP HYPOTENUSE instruction. We in Figure 11 -25a. Here are a few more general com-
used the POP form of this instruction so that after this ments before
we get into the actual program example.
instruction the stack pointer is back at the same regis- To simplify the internal design of the 8087, the FPTAN
ter asit was when we started. This makes it easier to instruction was designed to work only with an angle in
keep track of which register is ST if necessary. the range 0 < angle < -rr/4 radians (0 to 45°). Figure
For the case where our test found an error had oc- 1 1 -25b shows graphically the values for the sine, cosine,
curred,
could
we have program execution go to an error and tangent for angles from 0 to 360°. As you can see
handling routine instead of simply to the STOP label as there, the values for each function are repetitive. If you
we did for this simple example. We have shown the ESC compute the values for these functions for the first oc-
form for each of the instructions to give you more exam- tant (0—
45 or 0--/4 radians), you can determine their
ples these.
of values for any other octant by using various simple trig-
When you feel comfortable with the preceding exam- onometric equations.
The values for the sine of an angle
ple, read
through the 8087 instruction descriptions in octant 4 ( 180 to 225), for example, are the same as
again, and then work your way through the next exam- those in octant 0 except that their sign is changed. As
ple whichshows you how to use the 8087 for working another example, the tangent of an angle in octant 1 is
with trig functions. equal to l/(tan (90° - the angle)). The point of all of this
is that before you can use the FPTAN instruction to find
the Y and X values for an angle, you have to reduce the
AN 8087 TRIG FUNCTION EXAMPLE
angle to within the range of 0-7r/4 radians. The 8087
As our second example of an 8087 program we have cho- FPREM instruction is used to do this.
sen show
to you how to compute the tangent of a given The FPREM instruction subtracts 7i/4 from ST over
angle using the 8087 FPTAN instruction. Figure 1 l-25a and over until the result in ST is less than 77/4. After
shows the standard reference triangle we will be using FPREM executes, ST contains the remainder from these
for this example, and the definitions of sine, cosine, and subtractions, and bits CO, C3. and C 1 of the status word
contain a 3-bit binary number which indicates the
number of times rr/4 had to be subtracted from the origi-
SINE ANGLE - R nal angle. The number in these status bits then tells you
what octant the original angle was in. You use this oc-
COSINE
ANGLE ''R tant information to tell you which formula you use to
compute the desired value for the angle. For example,
TANGENT
ANGLE

suppose that you are computing the sine of an angle,
and the status bits tell you that the angle is in octant 4.
You then know that you have to change the sign of the
result produced by Y/\ X2 + Y2 to get the correct sine for
the angle, because as shown in Figure 1 l-25b, sines in
octant 4 are negative.
Finally, you have to check if the remainder left in ST
after the FPREM instruction is zero. You need to do this
because the FPTAN instruction will not work for a value
of exactly 0 in ST. Now, let's look at our example pro-
gramFigure
in 11-26.
In order to keep this example short so you don't get
lost in trigonometric manipulations, we require that the
input angle be in the range of 0 to 7r/2 radians (0-90). If
you need to expand t"his example to work with other
angles, use the identities from a standard trig text to
help you.
In the data segment of the program in Figure 1 1-26 we
set aside memory spaces for the status word and for the
values we want to calculate. Since we set aside double
word spaces with the DD directive, the 8087 assembler
16)
will convert results to short-real format before writing
FIGURE 11-25 (a) Reference triangle for trigonometry them to these spaces. We also declare here the value of
examples, <b) Definitions of basic trigonometric - 4 which will be used by the FPREM instruction. We
functions. could have calculated this value with the 8087. but we

394 CHAPTER ELEVEN


IBM Persofial Computer MACRO
Assembler Version 2.00 Page 1-1
05-21-85
page ,132
;a087 PROGRAMSECTION
;ABSTRACT : This program section uses an 8087 to compute the tangent
of an angle in the range of O^angle<pi/2 radians.
The angle, expressed in radians, is assumed to be in a
memory location named ANGLE.
The program also produces values for Y and X,
the opposite and adjacent sides of a right
triangle with the given angle. These Y and X values can
be used to compute the SINE and COSINEof the given angle.

0000 DATA_HERESEGMENTWORD
0000 0000 STATUS DW 0 ! Reserve space for status woid
0002 35 C2 68 21 A2 DA PI OVER 4 DT 3FFEC90FDAA22168C235R ; Temporary real form for Pi/4
OF C9 FE 3F
000C 00 00 00 3F ANGLE DD 0 ; Angle to be processed, 0.5 Radians
0010 00 00 00 00 X DD 0 ; Space for X value for angle
0014 00 00 00 00 Y DD 0 ; Space for Y value for angle
; Normalized results X=3FBC7A43 Y=3F4DEE7A
0018 00 00 00 00 TANGENT DD 0 ; Space for Tangent of angle 0.5 radians
! Tan 0.5r = 0.546; normalized = 3F0B0A7B
00 1C 00 00 00 00 SINE DD 0 ; Space for SINE of angle
0020 00 00 00 00 COSINE DD 0 ; Space for COSINEof angle
0024 DATA_HERE
ENDS

OOuO C0DE_HERE
SEGMENT
WORD
ASSUMECS:C0DE HERE, DS:DATA HERE

0000 B8 — - R START: MOVAX, DATA HERE ; Initialize data segment register


0003 8E D8 MOVDS, AX
0005 9B DB E3 FINIT ; Initialize 8087
0008 9B DB 2E 0002 R FLD PI_0VER_4 ; PI/4 to ST from memory
00OD 9B D9 06 000C R FLD ANGLE ; ANGLE to ST, PI/4 in ST(1)
0012 9B D9 F8 FPREM ; Reduce angle to range 0 to pi/4,
! result in ST
0015 9B DD 3E 0000 R FSTSH STATUS j Check status to determine octant
001A 9B FWAIT
00 IB Al 0000 R MOV AX STATUS ; Bring to register to check
00 IE F6 C4 02 TEST AH 0000001 OB ; Bit 1=0 if octant 0 (0 - pi/4)
; Bit 1 = 1 if octant 1 (pi/4-pi/2>
0021 74 2A IZ OCTANT.O ; If octant 0, go check for 0, do Tangent
0023 9B D9 E4 FTST ; Else. Test for result from FREM - 0.
; FPTAN Hill not work with value of 0
0026 9B DD 3E 0000 R FSTSH STATUS ; Status word to memory
002B 9B FWAIT
002C Al 0000 R MOV AX, STATUS ; Copy to register to check
002F F6 C4 40 TEST AH 01000000B ; Bit 6=1 if result from FTST = 0
0032 75 5B JNZ ANGLE_45 ; Go load values for ANGLE= 45 degrees
0034 9B DE E9 FSUB ; Else subtract angle from pi/4 for octant 1
0037 9B D9 F2 FPTAN ; X value put in ST, Y value put in STil)
003A 9B D9 16 0010 R FST X ', Copy X value to memory for SIN and COS

MULTIPLE MICROPROCESSOR SYSTEMS AND BUSES 395


003F 9B D9 C9 FXCH ; Swap ST and STil) to get Y in ST
0042 9B D9 16 0014 ft FST Y ; Copy Y value to aeaory for SIN and COS
00<t7 9B DE F9 FDIV i Divide X value in ST(1) by Y value in ST
i To give Tangent for octant 1 angle in ST
00<tA EB 67 90 JHP STORE
JAM
00<iD OCTANT_0:
004D 9B D9 E4 FTST ; Test for result froa FREH = 0. FPTAN
; will not work with value of 0

0050 9B DD 3E 0000 ft FSTSW STATUS ; Status word to aeaory

0055 9B FHA1T
0056 Al 0000 R MOV AX, STATUS i Copy to register to check
0059 F6 C4 40 TEST AH, 01000000B ; Bit 6 = 1 if result froi FTST = 0

005C 75 19 JMZ ANGLE


.0 ; So load values for ANGLE - 0

005E 9B D9 F2 FPTAN i X value put in ST. Y value put in ST(1)


0061 9B D9 16 0010 R FST X i Copy X value to aeaory for SIN and COS
0066 9B D9 C9 FXCH ; Swap ST and STU) to get Y in ST
O069 9B D9 16 001<i R FST Y i Copy Y value to aeaory for SIN and COS
OO&E 9B D9 C9 FXCH ; Put X back in ST and Y in ST(l)

0071 9B OE F9 FDIV ! Divide Y value in ST!1) by X value in ST


; to give Tangent for octant 0 angle in ST
0074 EB 3D 90 JHP STORE.TAN
0077 0:
ANGLE_
0071 9B D9 E8 FLD1 ; Load one in ST
007A 9B D9 IE 0020 R FSTP COSINE ; Copy to aeaory reserved for COSINE
007f 9B D9 EE FLDZ ; Load :ero in ST
-082 9B D9 16 001C R FST SINE i Copy to aeaory reserved for SINE

0087 9B D9 16 0018 R FST TANGENT ; Copy to aeaory reserved for TANGENT


008C EB 2A 90 JHP DONE
008F W:
ANGLE.
008F 9B D9 EB FLDl ; Load 1 in ST
0092 9B D9 16 0018 R FST TANGENT ; Tangent of 45 degrees is 1
0097 9B D9 E8 FLDl ; ST and STil) now 1
Q09A 9B OE C! FADD ; ST now = 2
009D 9B DD Dl FST STil) ; ST(l) now = 2
OOAO 9B 09 FA FSQRT ". ST now = sguare root of 2

0OA3 9B D8 Fl FDIV ST, ST(1) ; ST now = (square root 2)/2 = sin 45

00A6 9B D9 16 001C R FST SINE ; Copy to aeaory reserved for SINE


00A8 9B D9 16 0020 R FST COSINE ', Copy to aeaory reserved for COSINE
OOBO EB 06 90 JHP DONE
0OB3 TAN:
STORE.
00B3 9B C9 16 0018 R FST TANGENT i Copy computed Tangent value to aeaory
00B8 DONE:
0OB8 9'! HOP

0OB9 90 NOP
OOBA 90 NOP
OOBB HERE ENDS
CODE_
END START

FIGURE 11-26 8087 program to compute the tangent of an angle.

did it this way to show you how temporary-real numbers struction


described
as before, and check the status
can be declared with a DT directive. word to determine what octant the angle is in. Remem-
In the code segment of the program we first initialize ber fromour previous example program that you check
the data segment register and the 8087. We then load the 8087 status word by first having the 8087 write the
it/4 and the angle we want to compute the values for, status word to a memory location with the FSTSW STA-
reduce the angle to within range with the FPREM in- TUS instruction. You then read this status word and

396 CHAPTER ELEVEN


check u with 8086 Instructions Since we have limited cause
theol way the 8087 works Since it this point in
the Inpul angle to be in either octant 0 or octanl l . we our calculations R Is in ST and 7r/4 is in ST( 1 1, we can do
only have to check oil CI ol the status word. In do this the needed subtraction with the FSUB instruction. The
we i opy the status word to .1 register with the M( IV \\ result ol this subtraction will be in ST. We then use the
STATUS instruction, and check bit CI with the ll M Ml, ll'IAN Instruction to find the V and .\ values for this
000000108 Instruction. The 8086 IT'.si instruction, result . Aftei slot nit; the A and V values .is we do tor oc-
remember, ANDs the specified source and destination. i.ini o. we leave out the final IXC II Instruction thai we
Flags itc affected, but the operands are not. use there. This leaves the .\ value in ST(1) and the V
If the result of the IKS rwas 0, we know the angle is in value in ST. Therefore, when we do the FDIV instrui
octant 0, so we jump to the program section which deals lion, we really are dividing the \ value by the \ value
with octanl 0 .mules, ll the result ol the TEST was no! 0, This gives the reciprocal we need to satisfy oui equa-
then we know the angle is in octant l. and process n tion. The
tangent value for the octant 1 angle will then
accordingly. Let's start with how we handle an angle in be left in ST where we can copy it to memory with an I s I
octant 0. IANGINI instruction. For voui reference we have
For an octant 0 angle we first use the 8087 FTST in- shown the short-real values produced by this program
struction
checkto it the result left in ST by the FPREM for an angle ol 0.5 radians.
instruction is zero. FTST will not change the contents ol Hopefully, by now you have some understanding of
ST. but it will affect the flags in the 8087 status register. how the 8087 works and can write some programs ol
With the ISTSVV STATUS instruction we then copy the your own. To debug 8087 programs, you may find it
8087 status register out to memory where we can get at helpful to insert extra store instructions to copy inter-
it. Bit 6 of the upper byte of the status word will be a 1 mediate results
out to reserved memory locations where
alter FTST if the value in ST is 0. If we find that ST is you can get at them to see if they are correct. The extra
zero for an octant 0 angle, we know that the angle is store instructions can be removed when the program
zero. The sine, cosine, and tangent values for 0 are works. If you are going to be writing programs where
known constants. Therefore, for this case we simply you need extensive 8087 sections, there are several com-
load these values one at a time into the 8087 ST register, mercially available
8087 software packages. These pack-
and copy them to the appropriate memory locations. ages contain8087 routines which you can simply link
The cosine of 0, for example, is 1. so we simply load 1 into your assembly or higher level language programs
into ST with the FLD 1 instruction and copy this value to
memory with the FST COSINE instruction. If we find that
the result of FPREM in ST is not 0. we go and compute MULTIPLE BUS MICROCOMPUTER
its tangent ratio with FPTAN. SYSTEMS
FPTAN. remember, does not give the value for tangent
directly, it gives two numbers whose ratio is equal to the In a previous section of this chapter we discussed how a
tangent of the angle. We call these two values Y and X as coprocessor can be connected on the local buses of a
shown in Figure 1 l-25a. This form of result is actually microcomputer to increase its computing power. In
more useful than having just a tangent result, because another section of this chapter we discussed how sev-
you can use the A' and Y values to compute the sine and eral different function boards can be connected on the
cosine of the angle as shown. To save the X and Y values local bus of the IBM PC to customize and extend its ca-
for these computations, we first copy X from ST to mem- pabilities.
amount
The that you can add to a system
ory withthe FST X instruction. We then exchange ST and using this approach, however, is limited. In both of
ST(1) with the FXCH instruction. The V value is now at these cases the coprocessor or peripheral boards borrow
ST. We copy Y to memory with the FST Y instruction, and the local buses from the main microprocessor on a DMA
then put X and Y back in their original position with basis as needed. When the coprocessor or peripheral
another FXCH instruction. To get the actual tangent board is using the buses, the main microprocessor is
value we divide the Y in ST( 1 ) by the X in ST with the just sitting in a hold state doing nothing. Therefore, if
FDIV instruction. The result of the division is left in ST you add too many DMA operations, you soon start to
where we can copy it to memory with an FST TANGENT slow down the main processor. The thought might
instruction. Now let's look at how we handle an octant 1 occur to you to simply add another main processor, an-
angle. other 8086for example, on the local buses to increase
Again for octant 1, the first thing we have to do is to the computing power. Since only one main processor on
check if the result left in ST by the FPREM instruction is the local buses could be active at a time, this does not
0. If it is. we know that the angle is 77/2 or 45°. Again, the gain anything for you. There are several ways, however,
sine, cosine, and tangent for this angle are known con- that two or more standard microprocessors can be used
stants which
we can just calculate and load into the re- in a system.
served memory
locations. If the value left in ST by One major approach is to set up each microprocessor
FPREM is not 0. we go on and compute the tangent as essentially a stand-alone microcomputer with its own
ratio. The computation in this case is a little less direct. RAM. ROM, ports, and local buses. These separate mi-
The formula we use to compute the tangent of an crocomputer then
boards
communicate with each other
angle in octant 1 is: tangent angle = l/( tangent ((77/4) - and with shared resources such as a hard disk drive
R). where R is the remainder left in ST after FPREM exe- using a separate system bus. Figure 11-27 shows a
cutes. This
looks messy, but it is really quite simple be- block diagram of this type of multiprocessor system.

MUfTIPtE MICROPROCESSOR SYSTEMS AND BUSES 397


r„— E

J-U rar I I
I I

FIGURE 11-27 Multiprocessor bused system. (Intel Corporation)

The principle here is that each processor board can op- recognizable groups of signal lines and work your way
erate independently, fetching and executing its own in- down to the toughies. For the Multibus 86-pin P1 con-
structions
itsfrom
on-board memory, until it needs to nector, start
with the power supply and ground connec-
access some shared resource such as the system mem- tionspins
on 1-12 and 75-86. This knocks off 24 pins.
ory, printer, or I/O board. This type of system is often Next check out the 16 data lines labeled DATA*-DAT1*
referred to as a loosely coupled system. Each board on pins 59—74. The * after each of these signal names
which can take over and use the bus is called a bus mas- indicates that these signals are active low (inverted) on
ter.board
A which can only be written to or read from is the Multibus. Note in Figure 1 1-29 that there are three
called a bus slave. sets of buffers on the data lines. Device A44, on the left
A question that may occur to you at this point is, side, buffers the local data bus for the 8-bit peripheral
"What happens if two or more masters on the system devices. Buffers A60 and A61 in the right center of the
bus try to use the bus at the same time?" The answer to diagram buffer the local data bus for the dual-port RAM.
this question is that the system must contain logic Two bidirectional inverting buffers. A69 and A89, are
which in some way "arbitrates" the dispute and makes used to interface these local RAM data lines to the Mul-
sure only one master at a time asserts its control signals tibus. Due
to a lack of space, the on-board ROM, ROM
on the bus. Later we will show you in detail some ways data-bus buffers, and ROM decoder are not shown in
in which this is done. For now we will start with an over- Figure 11-29.
view
a of
commonly used system bus so you have an idea Next look for the address lines on the Multibus con-
about how it operates. nectors. Sixteen
address lines. ADRE*-ADR1*. are on
pins 43-58 of the P1 connector. Four more address
lines. AD10*-AD13\ are on pins 28. 30, 32. and 34.
Four more address lines, ADR14*-ADR17*. are bused on
The Intel Multibus— IEEE 796 Bus Standard pins 55-58 of the P2 connector. These 24 address lines
There are many different microcomputer system buses make it possible for the bus to address up to 16 Mbytes
currently in use. Almost every microprocessor and mi- of memory. For many systems we use simple inverting
crocomputer manufacturer
has its own bus standard, buffers to interface the on-board local bus to these ad-
so it is not possible here to give even a survey of the dress lines.In some systems, however, we want both the
different ones. We have chosen to discuss the Intel Mul- on-board CPU and another master on the bus to be able
tibus becauseseveral hundred companies make several to access on-board RAM. In this case we use bidirec-
thousand different boards using this standard, and be- tional bufferson the address lines so that addresses for
cause
fitsit in with the devices and systems we are RAM can be sent from the board to the Multibus, or
working with in the rest of this book. This bus standard come from the Multibus to the on-board memory. RAM
was developed and evolved by Intel and later adopted by which is accessible from two directions in this way is
IEEE as Bus Standard 796. called dual-port RAM. Note in Figure 1 1-29 that devices
The basic IEEE 796 standard defines the signals for A42 and A58 are used to buffer the local address bus to
two printed circuit board edge connectors, an 86-pin the RAM. Bidirectional devices A86, A87. and A88 are
connector referred to as PI and a 60-pin connector re- used to buffer address lines to and from the Multibus.
ferred
as toP2. Figure 11-28 shows the signal names Next observe the eight interrupt request lines. INTO* —
and numbers for these connectors. Figure 1 1-29 shows INT7*. on pins 35-42 of the P1 connector. These lines
a block diagram for part of a single-board computer that can be routed to the inputs of a processor or an 8259A
might be used as a master on the Multibus. Keep copies on one of the master boards so that a slave board or
of these two figures handy to refer to as we discuss how another master board down the bus can interrupt that
all of this works. master when it needs attention. This is indicated by the
Whenever you are confronted with a long list of pin wirewrap interrupt jumper matrix in the lower right
names such as that in Figure 1 1-28, start with the easily corner of Figure 1 1-29.

398 CHAPTER ELEVEN


TJTDTOTOTDTOT3T3T3T3T3TDT-JTJT3TDT3T3TT1T3
CJCDCDCDCDCDCDlDCDCDCDCDCDCDCDCDCDCDCDCD

Reserved,
bussed
a

Bussed
Bussed
Bussed
Bussed
BussedBussed
Bussed
c c 33333333333333333333 CD
o o mcocommcomcomaacQcommmtDcotticQco
oooooooooooooooooooo 3

GND
Signal
a. Q

Signal
GND
zzzzzzzzzzzzzzzzzzzz m
3
u o m td'

12Vdc
T]T)T)X)OTJT)T3T3T3T]Dt)T)T)OUT3T3T: "O "O TD TO T3 T3 TD
in W

-5Vdc
*5Vdc
CO CDCDCDCDCDCDCDCDCDCDCDCDCDCDCDCDCDCDCDCD CD CD CD CD CO CD OJ CD
to 01 CD >
>>>>>>>>>>>>>>>>>>>> > > >
a Q 0
ojcdcdcdcdcdcdcdcdcdcdcdcdcdcdojcdcdcdcd CD CD CD CD CD CD CD CD
3
u
%5
cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd CD CD CD CD CD CD CD TD CD
rrrrrrarrrrrccrrccrrccrrrrQirxrxrrrrrrrr < cr
u o
o u

c r- in
c
o o
E
Q Si > > Q
E DC£
CD Z -- m m z 0) QQ
c CO I + + O c < <
£ :•

«^ CDCOO W 1 to CO o
c CO CO O CM T ID c CM'JlOCOOCM'JlDCOOCM^lOCOOCJ^COCOO
% 3- ^t •*! tt in in in m in CD
a.
N N CO CO CO CO b.
"OT3*D'DT3"D"0"0"D"DTD"D*0'D"0"0"0"D"0*D
CDCDCOCDCJCDCDCDCDCDCDCDCDCDCDCDCDCDCDCD

TO

Bussed
Bussed
Bussed
BussedBussed
Bussed
Bussed
33333333333333333333

Bussed
Reserved,
c c
o mcomcDCDmmcQcDaDmcDcncDcacDCQCDCDCD
o

Q.
oooooooooooooooooooo
a TO CQ
%a zzzzzzzzzzzzzzzzzzzz 3

GNDSignal
GND
Signal
to to m
u TD"O"O"O"0"0T3'O"O'OTD"0X3'0'O"0"O"O"O"O "O td td "o td "o td td
(A CDCDCDCDCOCDCDCDCDCDCDCDCDCDCDCDCDCDCDCD CD CD CD CD CD CD CD
c
c ai

-12Vdc
CD >>>>>>>>>>>>>>>>>>>> >>>>>>>
9)

5Vdc
i
CI a

-5Vdc
a CD
CDCDCDCDCDCDCDCDCDCDCDCDCDCDCDCDCDCDCDCD CD CD CD CD CD CD CD
c c "O
o o CDCDCDCDCDCDOJCDCDCDCDCDCDCDCDCDCDCDCDCD CD CD CD CD CD CD CD CD
a td
a. rrrrrxairrrxcirrrrnrrrDrrrrrrrccrrrrcra: rr rr rr tx rr rr rr < cc
E E
o o
o o
E c to T

o o
E Q cm > > Q E rr en
Z *- in in Z a a
0) ai
c c < <
S £

c c T-COlONOl'-COLOSOlr-oiONCD^COlONCD *- co in r~ en *- co in r- OJ
LO N C3J t- CO lO
^t ^ ^ t 't in in m in
a. S S N CO CO CO a.

CO

II TD
<
O 3
Q.tO
n
i' CD CD "=•

F TD ' 1
JLJ U r a.
Q Q
Q. 5 0) a i O "O O
Z Z O 3
CD
•D CD CJ CD CD CT CM 5 CL
5
to
0>

c
TC
> >
TD
>
CM
>

ca
c
5
Z
LL
CD
LT

CD
5 if a
O
rr
J'
ca
3
3
:
cc

Ul U) : - ) c tE n -
C|i i- '% i"

o CO + + + H en —
CJ llj > —
< aj 0. —
LL < LD a UJ

6
o

n o %

* .
* S LL a cd CTi h- in Ol r-
LL n m m _

E i
.'
i
m z
CC Ui
5 -> I T
n 1 n
I- h-
ir
n
cc
a
cc
a
11
1 1 I 1 i
II il
i 1 l i < < <
H
< %3 d < <
o z Z Z
c
<n' • + + CT in ca > < < < <r < < < < < < %I < LJ CJ LJ U CJ LJ LJ LJ

£
.-., ,-,, ^. to m n -"J ,^- CO Xi nj T in CO <~' CM -T to CO O CM T LD Xi O CM -J-
'" "" CJ OJ CM CM CM CO ''' CO CJ CO 1 rf T <Ct -T " m
cL ^ "-
-

CD
CD
CO
TD O
"O Hi CD
o CD
TD n a T3
F T3 3
u t O
Q
JJ
LJ
o
UJ
LL) O
I
to c a O
t> Z z
CO
ca a c c 2
O CD to a.
0)
CD 1 E CD
o O il
C
TD TD > £ ro Q_ CD
n
DC
^ < s 3
CO
c > > '.-'% 1 E UJ CD F ;
o CC -
i ) i ' o 1 TD J
a. + DC to i> U u 0. LL u CD
to %
' CD co lij X -1 CD < CD
E — —

o o
o

z > U :*: V ? o V < * LU o < aj ID -T CM o <) ni O


o
E 1 1 Q 11 il cc cc II II 11 II II 1- K- h- h- H h- K
cc 1 h- h-
z m in y LL en > ) n Q LJ 1 ! ! 1 1 1 1 1 < < < < < < < <
CD o o z z u: z z
i i

C n + n m CQ CD > X m () ( ) < < < < < < < < a lJ Q CJ LJ CJ CJ CJ


E 5
- %

£
c: m ,_ CO m r^ i-Ti ^ CO Lf) 1- iTi ,_ m m r- en r- CO in r-. Ol ,- CO CO —
r_ "1 CM CM CM r 1 <-.> CO CO C'J C) 'cr •J- T T T in U"l iji UJ U) in UJ
(L

CO CO UI in
Q-
a'
(>

•: 11 TD
o 3 1 1 n TD
D. -/i CO O CD U ca < -
•I
^j-Lu ;

,T

tm
if 5;;
!t dp

U
q %

C)

L"

7*rr
>~

^J
a
« s„
^^
r!

u ill J

;:

A i\ §
A
400 CHAPTER ELEVEN
Now that we have found the address and data bus nectedthe
lor serial priority arbitration scheme. The
connections, let's sec how the control-bus read and kej here is ihat , In ok In foi a mastei board to take over
write signals are produced, ["he 8086 here is operating the bus. its bus p 11v input. BPRN , must be asserted

in M.\\ mode so device A8 1. .in 8288 controller, is used low rhe highest priority master has it; BPRN/ input tied
to produce the control bus signals foi on board opera to ground, so it can take ovei the Multibu
iious Anothei 8288 device A83 on the right side of the needs to. It the highest priority mastei does nol need (o
diagram, is used to produce the control-bus signals use i he bus. it will assert its bus priority output, BPR( ) ,
needed when this board wi lies to oi re. ids from .mother low. This will assert the BPRN of the next lowei priority
board on the Multibus, rhe control signals produced by mastei so it can lake over the bus it it needs to II the
tins device conned to Multibus puis l!» 22 and 33. The second priority master does not need to use I he bus. it
transfei ol data from, for example, a memory board on asserts Us BPRO output low. This enables the lowest
the bus to a mastei is nearly identical to a transfei I priority master to use the bus it it needs to. II a low
local memory to the CPU. The master outputs the de priority master is using the bus and a higher priority
sued address on the Multibus, and the controller out- master needs to use the bus. the lower priority mastei
putsmemory-read
a command. MRDC*. The addressed will be allowed to finish transferring its current byte oi
location on the memory board is enabled, and puts its word, and then the higher priority master will take con-
data on the Multibus to be returned to the CPU on the trol.
master board which has control of the bus. Figure ll-30b shows the connections lor a parallel
The last major group of signals on the Multibus are priority scheme. This scheme uses the bus request sii^
those which transfer control of the Multibus from one nals. BREQ/. from each master, and the BPRN/ signals to
master to another. The signals in this group are BCLK*. each master. Here again, the BPRN/ input of a master
BPRN*. BPRO*. BUSY4. BREQ*. and CBRQ*. In our exam- must be asserted low in order for that master to be able
ple system in Figure 11-29. these signals are for the to take control of the Multibus. Here's how this scheme
most part produced and interpreted by an 8289 bus ar- works. When a master needs to use the bus to transfer
biter, device
A82. in the upper right corner. In a later some data, it asserts its BREQ/ signal. This signal, along
section we show you how these signals interact when with bus-request signals from other masters, goes into
two masters exchange control of the bus. For now we the inputs of a priority encoder. The priority encoder
will make some comments about the few remaining sig- will output a 3-bit code which represents the highest
nals on
the bus. numbered input that is asserted low. The 3-bit code
The IN1T* signal on pin 14 can be used to reset all of from the 74LS148 is connected to the select inputs of a
the master and slave boards on the bus. It is usually 74LS138 one-of-eight-low decoder. The result of all of
driven by circuitry on the highest priority master. The this is that the 74LS138 will assert the BPRN/ input of
INTA* signal is produced by the 8288 bus-controller de- the highest priority master requesting service. When
viceresponse
in to an interrupt request. An I/O board on this master finishes its data transfer, it raises its BREQ/
the bus, for example, might send an interrupt request signal high. The 74LS138 will then assert the BPRN/
on the bus to our master board in Figure 11-29. The input of the next highest priority master requesting use
master board, when ready, might assert INTA* on the of the bus. Now we will show you how bus control gets
bus to tell an 8259A on the I/O board to send back the transferred from one master to another in an orderly
desired interrupt type to the master board on the system manner.
data bus. The inhibit signals. INH1 * and INH2*. on pins Figure 11-31 shows the signal waveforms for transfer
24 and 26. can be used to disable a block of memory in of control of the Multibus from a lower priority master
the system. You might, for example, want to have ROM |A| to a higher priority master (B). Keep a copy of Figure
in a particular address space when the system is first 1 1-29 handy as we work through these waveforms with
turned on, and later have RAM in that address space. you.
These signals can be used to do this. Finally, note the The bus-control transfer process starts when the CPU
transfer-acknowledge signal, XACK*. on pin 23 of the on the higher priority master. B, outputs an address
Multibus. In our example system in Figure 11-29 this which is not decoded on that board. This off-board ad-
signal is connected to the READY input logic of the 8284 dress causesa signal labeled ON BD ADDR/ to be sent to
in the upper left corner. This connection allows an ad- the system-bus-request input of the 8289 bus arbiter,
dressed memory
or peripheral on the bus to make the telling it to attempt to take over the bus. Refer to the top
8086 insert WAIT states until it has accepted or output right corner of Figure 1 1 -29 to see how these signals are
valid data. Now. we will show you how a master can gain connected. On the waveforms in Figure 11-31 this sig-
control of the bus. nal referred
is to as TRANSFER REQUEST/. In response to
this request, the 8289 asserts its BREQ/ output low. As-
suming
areweusing a parallel priority scheme as de-
Arbitrating and Transferring Bus Control scribed before,
the priority encoder-decoder will then
When two or more masters share a bus such as the Mul- unassert the BPRN/ input of master A and assert the
tibus, some
mechanism must be used to settle the argu- BPRN/ input of mastei B as shown in the waveforms.
ment whentwo masters want to use the bus at the same While master A is using the bus for a data transfer, it
time. The Multibus can use either a serial priority holds the BUSY/ line on the Multibus low. The BUSY/ line
scheme or a parallel priority scheme to do this. is an open-collector line which any master can pull low
Figure 11 -30a shows how three masters are con- when it is using the bus. No other master can actually

MULTIPLE MICROPROCESSOR SYSTEMS AND BUSES 401


HIGH! '•!
PRIORITY
MASTER

OTHER
MASTER
IiTHI R
INPUTS
, MASTER
OUTPUTS

FIGURE 11-30 Serial and parallel priority resolution circuitry tor Multibus
systems (a) Serial, (b) Parallel. (Intel Corporation)

take over the bus until the master currently using the struction without
interleaving with other masters. The
bus releases the BUSY/ line. After master A finishes way this is done is with a bus-lock mechanism. Observe
transferring data it disables its address, data, and con- in Figure 1 1-29 that the bus arbiter device has an input
trol buffers connected to the Multibus, and releases the labeled LOCK. If a master has control of the bus. the bus
BUSY/ line. Master B then pulls the BUSY/ line low to let arbiter will hold the BUSY/ line on the Multibus low as
other masters know that the bus is in use. Master B long as the LOCK input is asserted. As we described
next enables its buffers to output address and control above, this prevents any other masters from taking a
signals on the Multibus for its data transfer. In normal turn on the bus. The LOCK signal for the 8289 bus arbi-
operation a master releases the bus after each byte or ter can come from one of several sources on the board,
word data transfer so that a high priority master cannot but the main source we are concerned with here is the
prevent lower priority masters from ever having a turn. LOCK output of the 8086.
In some eases, however, we want a master to be able to Note in Figure 1 1-29 that, when the 8086 is set to
transfer several bytes or words of data needed for an in- operate in maximum mode, pin 29 outputs a signal

402 ( IIAPILR ELEVEN


MASTER B

COMMAND ACTIVE

FIGURE 11-31 Signal waveforms for transfer of control of Multibus from a


lower priority master to a higher priority master. (Intel Corporation)

called LOCK. The 8086 will assert this signal when it ter onthe Multibus might take over the bus between the
executes an instruction which has a LOCK prefix in two operations and read the old value of FLAG, rather
front of it. An example of this type of instruction is than the new value that you are trying to put there with
LOCK XCHC AL, FLAG. When this instruction is assem- the XCHG AL, FLAG instruction.
bled, the
code for the LOCK prefix. 1 1 1000, will be put This section has shown you how several processor
in before the code for the XCHG instruction. The XCHG boards can share a common bus in a harmonious man-
instruction takes two bus cycles, one to read in the byte ner. Chapter
In 13 we show you how several complete
from the memory location named FLAG on a shared computers can be networked together to communicate
memory board, and another to copy AL to the memory- and share a common data base.
location. Without the LOCK mechanism, another mas-

MULTIPLE MICROPROCESSOR SYSIFMS AND BUSES 403


IMPORTANT TERMS AND CONCEPTS Tightly coupled multiprocessor system
FROM THIS CHAPTER 8087 math coprocessor
data types and terms
8086 maximum mode Word, short, and long integers
Packed decimals
DMA
DMA channel
Short-, long-, and temporary-reals
8237 DMA controller
Fixed-point numbers
Floating-point numbers
Motherboard and system expansion slots Normalizing
Significand, mantissa, exponent
DRAM
Single- and double-precision representation
Refresh — burst and distributed modes
Offset form
RAS and CAS strobes
8087 control and status words
8208 DRAM controller IC
Multiple bus microprocessor systems
Error detecting and correcting
loosely coupled system
Hard and soft errors
Intel Multibus — 796 bus standard
Parity check
Bus master and bus slave
Hamming codes
Syndrome word Dual-port RAM

80 186/80 188— integrated peripherals Serial and parallel bus arbitration schemes

REVIEW QUESTIONS AND PROBLEMS


1. Describe how the control-bus signals are produced 11. When using a Hamming code error detection/
for an 8086 system operating in maximum mode. correction scheme for DRAMs. how many encoding
bits must be added to detect and correct a single-
2. Why is DMA data transfer faster than doing the
bit error in a 32-bit data word?
same data transfer with program instructions?
12. List the peripheral functions integrated into the
3. Describe the series of actions that a DMA controller
will do after it receives a request from a peripheral
Intel 80186 microprocessor.
device to transfer data from the peripheral device to 13. Describe the function of the relocation register in
memory. the 80186 peripheral control block.

4. Describe how the 20-bit memory address for a DMA 14. How can you tell from the schematic that the 8088
transfer is produced by the circuit in Figure 1 1-3. in Figure 11-15 is configured in maximum mode?
5. Describe the function and operation of devices U5
15. Device t/7 in Figure 1 1-15 has a signal named AEN
and U6 in Figure 1 1-3.
connected to its OE input. If, in troubleshooting
6. Why are microcomputers such as the IBM PC de- this system, you find that this signal is not getting
signed with
peripheral expansion slots instead of asserted, on which schematic sheet would you first
having functions such as a CRT controller de- look to see how this signal is produced?
signed the
into motherboard?
16. In what ways are a standard microprocessor and a
7. List the series of signals that must occur to read a coprocessor different from each other?
data word from a dynamic RAM such as the
17. a. When a coprocessor and a standard processor
51C256H.
are connected together in a system such as
8. List the major tasks that must be done when using that in Figure 1 1-15. why are the S2-S0 status
dynamic RAM in a microcomputer system. lines, the QS1-QS0 lines, the address, and the
data lines of the two devices connected directly
9. How does a dynamic RAM controller, in a system
together?
such as that in Figure 11-10. arbitrate the dispute
b. Where does the 8087 coprocessor in Figure
that occurs when you attempt to read from or write
11-15 get its instructions from?
to a bank of dynamic RAMs while the controller is
c. How does the main processor distinguish its
doing a refresh cycle?
instructions from those for the 8087 as it
10. Describe how parity is used to check for RAM data fetches instructions from memory?
errors in microcomputers such as the IBM PC. d. Describe how the 8087 and 8088 work to-
What is a major shortcoming of the parity method gether
load
to a long-real data item from mem-
(il error detection? ory to
the 8087 ST.

404 ( MAPI I R I if YIN


e How does the 8087 In Figure 11 15 signal the c. Show the 8086 ESC instructions required to
8088 thai II needs to use the buses? get an 8086 assemblei to produce thi
t. How can you prevent the 8088 in Figure ii 15 codes for the Instructions In question 20.
from going on with its next Instruction before
22. In the example program in Figure l i '.;.I. why did
the 8087 lias completed an Instruction? What
we pul ,i WAN Instruction aftei the FSTSW STATUS
hardware connection In Figure 11 l r> is pari ol
instruct Ion?
ilus mechanism?
23. Using the example program In Figure 1 1-24, write
18. a. Given the decimal number 2435.5625. converl
an 8087 program winch computes the volume ol a
this [lumber to binary, normalized binary,
sphere. The formula is V ' \ttR .
long real, and temporary-real format.
b. Whv are mosl floating-poinl numbers actually 24. Describe the function ol the FPREM Instruction In
approximations? the example program In Figure I 1-20.
19. a. Which 8087 stack register is ST after a reset? 25. Extend the example program in Figure 11-26 to
b. Which 8087 stack register will be ST alter one calculate the sine and the cosine ol the given angle
data Item is read into the 8087? in the range 0 : ANGLE • 90 (tt/2).
c. Describe the operation that will be done by the
8087 FADD ST(2), ST(3) instruction.
26. What are the advantages of having several micro-
d. How does the operation of the instruction
processors connected
on a common system bus
FADDP ST(2), ST(3) differ from the operation of such as the Multibus? What is the major problem
the instruction in 19c?
that has to be worked out in order for these multi-
ple processors to exist peacefully on the common
20. Describe the operation performed by each of the bus?
following 8087 instructions.
27. Name the two schemes used to determine which
a. FLD TAX-RATE
master on the Multibus gets control when two or
b. FMUL INFLATION FACTOR
more masters request use of the bus at the same
c. FSQRT
time.
d. FLDPI
e. FSTSW CHECK ANSWER 28. On board a master, how is the signal produced
/. FPTAN which tells the bus controller to take over the bus?

21. a. Show the binary codes required for each of the 29. How can a master keep control of the bus for more
instructions in question 20. than 1 byte or word access if that master is in the
b. Why is 9BH. the code for the 8086 WAIT in- middle of some critical program section?
struction,
in put
before most of the 8087 in-
structions?

MULTIPLE
MICROPROCESSOR
SYSTEMS
ANDBUSES 405
CHAPTER

Microcomputer System
Peripherals

In the preceding chapters we discussed basic microcom- Chapter 9 we discussed the operation of alphanumeric
puter systems
and some of the programmable periph- LCD displays and a little later in this chapter we will
eral devices
used in these systems. In this chapter we show how large LCD screens are interfaced to a micro-
expand outward to discuss the hardware and software computer.
now.Forhowever, we want to discuss the
of system peripherals such as CRT displays, computer operation and interfacing of CRT-type displays.
vision devices, disk drives, and printers.

Basic CRT Operation


A CRT is a large, bottle-shaped vacuum tube. The pic-
OBJECTIVES ture tubeused in a TV set is an example of a CRT. An
electron gun at the rear of the tube produces a beam of
1. Describe how characters are produced on a CRT or
electrons which is directed towards the front of the
an LCD screen.
tube. The inside surface of the front of the tube is coated
2. Use BIOS calls to display a message on the CRT dis- with a phosphor substance which gives off light when it
playanof IBM PC-compatible computer. is struck by electrons. The color of the light given off is
determined by the particular phosphor used. To pro-
3. Describe how bit-mapped and vector graphic dis- duce color
displays as in a color TV set, dots of red-,
playsproduced
are on a CRT. blue-, and green-producing phosphors are put on the
inside of the screen in triangle patterns. Separate elec-
4. Describe how computer vision systems produce an
tron beamsare focused on the dots for each color phos-
image that can be stored in a digital memory.
phor.altering
By the intensity ratio of the three beams
5. Show in general terms the formats in which digital we can make the three-dot triangle appear any desired
data is stored on magnetic and optical disks. color.
The most common method of producing images on
6. Describe the operation of disk controller circuitry.
the CRT screen is to sweep the electron beam(s) back
7. Use DOS calls to open, read or write, and close disk and forth across the screen. When the beam reaches the
files. right side of the screen, it is turned off (blanked) and
retraced rapidly back to the left side of the screen to
8. Describe the mechanism used in several common
start over. If the beam is slowly swept from the top of the
types of computer printers.
screen to the bottom of the screen as it is swept back
9. Describe how phoneme, formant filters, and linear and forth horizontally, the entire screen appears
predictive coding synthesizers produce human- lighted. When the beam reaches the bottom of the
sounding speech from a computer. screen, it is blanked and rapidly retraced back to the top
to start over. A display produced in this way is referred
10. Describe the basic principle used in speech recogni- to as a raster display. To produce an image we turn the
tion systems. electron beam on or off as it sweeps across the screen.
The trick here is to get the beam intensity or video infor-
mation synchronized with the horizontal and vertical
MICROCOMPUTER DISPLAYS sweeping so that we get a stable display.
Black-and-white TVs in the United States use a hori-
Currently there are several different technologies used zontal sweep
frequency of 15.750 Hz and a vertical
to display numbers, letters, and graphics for a micro- sweep frequency of 60 Hz. One sweep of the beam from
computer.
mostThecommon types are cathode-ray the top of the screen to the bottom is called afield. Sixty
tubes (CRTs) and liquid-crystal displays (LCDs). In fields per second are then swept out. To get better pic-

406
STARTOF FIELD2 line resolution and avoid flicker, TVs use interlaced
/ scanning. As shown In Figure 12 la, this means the
scan lines i Held ,uc iillsci and interleaved with
i In isc ill ill the nexl field Aftei evei \ othei field the scan
lines repeal rherefore, two fields an required to make a
complete picture or frame. The frame rate is then 30
frames/second. The beam sweeps 262.5 times horizon-
tally
ii f(
each vei i leal sweep.
CRT units used for computer readouts usually have
noninterlaced scanning, as shown in Figure 12-lb. In
this case a horizontal sweep rate ol 15,600 11/ and a
vertical sweep rate ol 60 11/ gives 260 sweep lines field.
The held rale and the frame rate arc both 60 11/ in this
case

Whether the CRT' you are using to display your pro-


grams
in isa TV set, a video monitor, or a terminal,
there arc certain basic circuits required to drive the
END OF FIELD 1 I Nil HI Mill).' CRT. These are: the vertical oscillator to produce the
vertical sweep signal for the beam, the horizontal oscil
262% LINES FIELD
lator to produce the horizontal sweep signal lor the
2 FIELDS FRAME
525 LINES/FRAME FOR 15.750 Hz beam, and the video amplifier to control the intensity of
HORIZONTAL AND 60 Hz VERTICAL
the electron beam. A unit which contains only this basic-
drive circuitry is referred to as a video monitor. A TV set
contains the basic monitor functions plus RF and audio
START OF FIELD
decoding circuitry. A CRT terminal contains a key-
board, memory,
communication circuitry, and usually a
microprocessor to control all of these parts.
The basic CRT drive circuitry for a one-color, or mono-
chrome, display
requires three input signals to operate
properly. It must have horizontal sync pulses to keep the
horizontal oscillator synchronized, and vertical sync
pulses to keep the vertical oscillator synchronized. Also
it must have the video information for each point as the
beam sweeps across the screen. All of this must be syn-
chronized
that soa particular dot of video information
gets displayed at the same point on the screen during
each frame. If you have seen a TV picture rolling, or a TV
picture with jagged horizontal lines in it. you have seen
what happens if the horizontal, vertical, and video infor-
mation
notare synchronized.
END OF FIELD When transmitted to a TV set or to a video monitor,
260 LINES/FIELD the two svnc signals and the video information are usu-
1 FIELD/FRAME ally combined into a single signal called composite
260 LINES/FRAME FOR
video. Figure 12-2 shows a typical TV-type composite
15,600 Hz HORIZONTAL AND
60Hz VERTICAL video signal waveform. It is hard to show in a figure, but
there is one vertical sync pulse for each 262.5 horizontal
sync pulses. The video information is represented by the
FIGURE 12-1 CRT scan patterns, (a) Interlaced. waveform sections between horizontal sync pulses. For
(b) Noni nterlaced.

VERTICAL SYNC PULSE 60 Hz

HORIZONTAL SYNC PULSES 15,750 Hz

JL JL JL JUTJl-T-LT-Lrnr-lJlJUlj-L

~a| {/^
BLANKING ONE VERTICAL SYNC PULSE
(BLACK) FOR EACH 262-5 HORIZONTAL
LEVEL PULSES

\NOTCHES TO KEEP HORIZONTAL


OSCILLATOR SYNCHRONIZED
I VIDEO |
INFORMATION

FIGURE 12-2 Composite video waveforms.


MICROCOMPUTER SYSTEM PERIPHERALS 407
DOT ROW
these waveforms, a more positive voltage turns the beam
0 0 0 0 0 0 0 0 0 0 0 0 0 II 1) n 1.1 1.1
off. Therefore, the beam will be blanked during the hor-
izontal retrace
time represented by the pulse that the 0 0 0 1 O o o o o o 0 0 0 II 0 0 0 0

horizontal sync pulse sits on top of. The beam will also 0 0 10 O 0 0 0 0 0 o 0 0 0 0 0 0 0

be blanked during the vertical retrace time. Now let's see 0 0 11 O 0 0 0 0 0 o 0 0 0 0 0 0 0


how we generate these three signals to display charac-
0 10 0 O 0 0 0 0 0 o o 0 o o o 0 0
ters on
a CRT screen.
0 10 1 © © o o © o 0 © o 0 0 0 o 0

0 110 o 0 0 0 0 0 0 o 0 0 0 0 o 0
Creating a Page of Monochrome Characters on
0 111 o 0 0 0 0 0 0 o 0 0 0 0 o 0
a CRT
10 0 0 o 0 0 0 0 0 0 o o 0 0 0 o 0
Characters or graphics are generated on a CRT screen
as a pattern of light and dark dots. To do this we turn 10 0 1 o 0 0 0 0 0 0 o 0 o o o 0 0

the electron beam on and off as it sweeps across the 11.111) 0 0 0 0 0 0 0 o 0 0 0 0 0 0

screen. Figure 12-3 shows how this works. The round 10 11 0 0 0 0 0 0 0 o 0 0 0 0 0 0


dots in the figure represent the beam on, and the empty,
110 0 0 0 0 0 0 0 0 o 0 0 0 0 0 0
square boxes represent the beam off. With this dot ma-
110 1 0 0 0 0 0 0 0
trix we
can produce a reasonable approximation to any 0 0 0 0 0 0 0

letter or symbol. The more dots used for each character, 1110 0 0 0 0 0 0 0 0 II 0 0 0 0 '1

the better the representation. Common dot-matrix sizes 1111 0 0 0 0 0 0 0 0 0 0


0 0 0 0
for a character are 5 by 7. 7 by 9. and 7 by 12. The dot
CAPITAL OR UPPERCASE SMALL OR LOWERCASE
patterns for each character we want to display are stored
in a ROM called a character generator ROM. Figure 12-4 FIGURE 12-4 Dot format for Motorola MC6571 character
shows the matrix for a Motorola MC6571 character gen-
generator ROM.
erator.MC6571
The uses a 7 by 9 matrix for the actual
character, but it has extra dot rows to leave space be-
tween rows
of characters and so that lowercase letters the ASCII code for the first character is addressed in the
can be dropped in the matrix to show descenders cor- display RAM. The addressed code will be output from
ectly. Each dot row in Figure 12-4 represents the pat- the IiAM to the data inputs of the character generator
terndots
of for a horizontal scan line of the character. ROM. The outputs of a dot row counter are also applied
Figure 12-5 shows how the character generator is con- to the character generator. With these two inputs the
nected with
some RAM. a shift register, and some character generator will output the 7-bit dot pattern for
counters to produce the signals required to display one dot row in the character. For the first scan across
characters on a CRT. Here's how it works. the screen the counter will output 0000 so the dot pat-
The ASCII or EBCDIC codes for the characters to be tern output will be that for dot row 0000 of the charac-
displayed on the screen are stored in a RAM so that they ter. Theoutput from the character generator is in paral-
can be changed when you want to display something lel form. In order to turn the beam on and off at the
new on the screen. This RAM is often referred to as the correct time as it sweeps across the screen, this dot pat-
display RAM or the display refresh RAM. The RAM tern must be in serial form. A simple parallel-to-serial
must contain at least one byte location for each charac- shift register is used to do this conversion. Note that the
ter tobe displayed. A common display size is 25 rows of eighth data input of the shift register is tied to ground
characters with 80 characters in each row. This display so that there is always one dark dot or undot between
then requires about 2 Kbytes of display RAM. A charac- characters. The high-frequency clock used to clock this
ter counter and a row counter are used to address the shift register is called the dot clock because it controls
ASCII codes in this RAM. the rate at which dot information is sent out to the video
To start the display in the upper left corner, the char- amplifier.
acter counter and the row counter outputs are all O's so After the dots for the first scan line of the first charac-
ter areshifted out. the character counter is incremented
by one. It then points to the ASCII code for the second
-B-B- d o • a SCAN LINE character in the top row of characters in the display
SCAN LINE RAM. Therefore the ASCII code for this second character
will be output to the character generator ROM. Since the
dot line counter inputs to the ROM are still 0000. the
ROM will output the dot pattern for the top scan line of
•aaaa»an
the second character in the top row of characters on the
d a d a a a • a
screen. When all of the dots for the top scan line of this
• a d d a d a • a
character are all shifted out, the character counter will
be incremented by one again, and the process repeated
ONE CHAR ONE CHAR
for the third character in the top row of characters. The
(PI (H)
process continues until the first scan line for all 80
FIGURE 12- i Producing characters on a CRT screen with characters in the top row of characters is traced out.
dots. A horizontal sync pulse is then produced to cause the

408 ( MAIM Ik TWEfVt


MC6571 74165
CHARACTER SHIFT
GENERATOR REGISTER

SERIAL VIDEO ADDER


DOT PATTERN
RAM
OUT
512 X 7
COMPOSITE VIDEO OUT

DOT
CLOCK
VERTICAL
HORIZONTAL SYNC
SYNC 15, 600 Hz 60 Hz

OSCILLATOR
6 MHz

A0 I A2 I A4 A5 I A7 I
A1 A3 fll /?3 A6 A8
CHARACTER DOT LINE
COUNTER COUNTER
32/ROW f HORIZONTAL 13 LINES/
BLANKING/RETRACE CHARACTER
TIME

FIGURE 12-5 Block diagram of circuitry to produce dot-matrix character display


on CRT.

beam to sweep back to the left side of the screen. After CRT Display Timing and Frequencies
the beam retraces to the left, the character counter is
rolled back to zero to point to the ASCII code for the first There are many different horizontal, vertical, and dot
character in the row again. The dot line counter is incre- clock frequencies commonly used in raster-scan CRT
mented
0001to so that the character generator will now displays. The horizontal sweep frequency is usually in
output the dot patterns for the second scan line of each the range of 15-30 kHz, the vertical sweep frequency is
character. After the dot pattern for the second scan line usually 50 or 60 Hz, and the dot clock frequency is usu-
of the first character in the row is shifted out to the ally 5-25
MHz. For our first specific example, we will use
video amplifier, the character counter is incremented to the frequencies used in the IBM PC monochrome dis-
point to the ASCII code for the second character in the play adapter,which we use as a circuit example in a
display RAM. The process repeats until all of the scan later section.
lines for one row of characters have been scanned. The IBM monochrome display adapter produces a dis-
The character row counter is then incremented by play25of rows of 80 characters/row. Each character is
one. The outputs of the character counter and the char- produced as a 7 by 9 matrix of dots in a 9 by 14 dot
acter row
counter now point to the display RAM address space. This means that because clear space is left
where the ASCII code for the first character of the sec- around each actual character, each character actually
ond rowof characters is stored. The process we de- uses 9 dot spaces horizontally, and 14 scan lines verti-
scribed
thefor first row will be repeated for the second cally. The
active horizontal display area then is 9
row of characters. After the second row of characters is dots/character x 80 characters/line or 720 dots per line.
swept out. the process will go on to the third row of The active vertical display area is 25 rows > 14 scan
characters, and then on to the fourth, and so on until all lines/row or 350 scan lines.
16 rows of characters have been swept out. Now. according to the IBM Technical Reference Man-
When all of the character rows have been swept out. ual, the
monochrome adapter uses a dot clock frequency
the beam is at the lower right corner of the screen. The of 16.257 MHz. This means that the video shift register
counter circuitry then sends out a horizontal sync pulse is shifting out 16.257,000 dots/second. The manual
to retrace the beam to the left side of the screen, and a also indicates that the board uses a horizontal sweep
vertical sync pulse to retrace the beam to the top of the frequency of 18.432 lines/second. Multiplying
screen. When the beam reaches the top left corner of the 16,257.000 dots per second by 1/18.432 seconds per
screen, the whole screen-refresh process that we have line tells you that the board is shifting out 882 dots/line.
described will repeat. As we mentioned before, the entire Just above we showed you that the active display area of
screen must be scanned (refreshed) 30 to 60 times a sec- a line is only 720 dots. The extra 162 dot times actually
ond avoid
to a blinking display. Now let's see what fre- present are required to give the beam time to get from
quencies
involved
are in each major part of the circuitry. the right edge of the active display to the right edge of

MICROCOMPUTER SYSTEM PERIPHERALS 409


the screen, retrace to the left edge of the screen, and mal TV
sets connected to computers cannot display
sweep to the left edge of the active display area. This high-resolution 80-character lines for word processing,
large number of extra dot times is necessary because etc. In order to filter out the sound subcarrier and the
most monitors have a large amount of overscan. This color subcarrier, the bandwidth of TV video amplifiers is
means that the beam is actually swept far off the left and limited to about 3 MHz. When using a TV as a readout
right sides of the screen so that the portion of the sweep device for a microcomputer, then, we usually limit the
actually displayed is linear. display to a smaller number of dots per character, and to
The manual for the display adapter indicates that the 40 characters/line. A CRT monitor used for displaying
frame rate is 50 Hz. In other words the beam sweeps characters or graphics should have a bandwidth greater
from the top of the screen to the bottom and back again than one-half the dot clock frequency.
50 times/second. To see how many horizontal lines are A final point we want to make about CRT timing is
in each frame, you can divide the 18.432 lines/second by how often the display-refresh RAM has to be accessed.
50 frames/second to give 369 scan lines/frame. As we As the circuitry scans one line of the display, it has to
showed above, the active vertical display area is 350 access a new character in RAM after each 9 dots are
lines, so this gives 19 extra scan line times for the beam shifted out, assuming 9 dots horizontally per character.
to get to the bottom of the screen, retrace to the top of Dividing the dot clock frequency of 16.257 MHz by 9
the screen, and get to the start of the active display area dots/character tells you that characters are read from
again Note that the dot clock, horizontal sweep fre- RAM at a rate of 1.806.333 characters/second, or one
quency,vertical
and sweep frequency must all be related character every 553 ns! Next we will show you how pro-
to each other so that the display is synchronized. grammable
display
CRT controllers are used to produce
Another point we need to make here concerns the a desired display-
bandwidth required by a video amplifier or monitor to
clearly display a given number of dots per line. For our CRT Controller ICs and Circuits
example here, the dot clock frequency is 16.257 MHz.
In addition to the chain of counters shown in Figure
This means that the dot shift register is shifting out
12-5, considerable other circuitry is needed to produce
16.257,000 dots/second. If we are shifting out alternat-
horizontal blanking pulses, vertical blanking pulses, a
ing dotsand undots. then the waveform on the serial
cursor, scrolling, and highlighting for a CRT display.
output pin of the shift register will be a square wave
Several manufacturers offer CRT controller ICs that
with a frequency of half that of the dot clock or 8. 1285
contain different amounts of the required circuitry. The
MHz. In order to produce a clear display with this many
two devices we discuss here are the Intel 8275 and the
dots per line, then, the video amplifier in the monitor
Motorola 6845.
connected to the display adapter must have a band-
width
at of
least 8 MHz. In other words, the circuitry in
THE INTEL 8275 CRT CONTROLLER
the monitor must be able to turn on and off fast enough
so that dots and undots don't smear together. Figure 12-6 shows, in block diagram form, how an 8275
This bandwidth requirement is the reason that nor- controller is connected with other circuitry to produce

SYSTEM BUS

DBO-7
WR

HRQ
HACK
^>

8257 VIDEOSIGNAL
CHARACTER
DMA
GENERATOR
CONTROLLER
8?/ 5 DOT HORIZONTAL SYNC
CRT TIMING
corn mn i i h AND
VERTICAL SYNC
INTERFACE

VIDEO CONTROLS

FIGURE 12-f) Block diagram showing connections of Intel 8275 CRT controller
in .i microcomputer system.

410 CHAPTER TWELVE


1

MUI 1 IPI 1 m R J 110)


2 K MEMORY

A 1 11

(8)
IM1 A >

GATING
R
(8)
S3DO ;

MA
—1— 'i 1 A|
LATCH A I'M

1 1
\
RA CHARACTER BUI E
•\n (4) i,l Nl HATOR DECODE

null LK 1
SHIFT
REGISTER
i
VIDEO
TIMING PROCESS
LOGIC
HSYNC. V SYNC, C URSOR. DISPI

CHARACTER CLOCK

MONITOR DIRECT
DRIVE OUTPUTS

FIGURE li-- IBM monochrome display adapter board blink diagram.

the drive signals for a CRT monitor. The 8275 contains THE MOTOROLA 6845 CRT CONTROLLER
a row counter which can be programmed for a display of
1 to 64 rows, a character counter which can be pro- The 6845 CRT controller chip performs most of the
grammed
a display
for of 1 to 80 characters/row, and a 8275 functions discussed in the previous section, but it
scan line counter which can be programmed for 1 to 16 interfaces with the display refresh RAM in a very differ-
scan lines/character. The 8275 also has an 80-byte ent way.The 6845 is used in both the monochrome dis-
buffer to hold the ASCII characters for the row currently play adapter board and the color/graphics monitor
being displayed and an 80-byte buffer to hold the ASCII adapter boards for the IBM PC. so we will use some cir-
characters for the next row of characters to be displayed. cuitry from
these boards to show you how it works.
For the system in Figure 12-6 the page of characters to Figure 12-7 shows a block diagram for the IBM PC
be displayed is stored in a buffer in the main microproc- monochrome display adapter board. Take a look at this
essor memory. While the 8275 is using the contents of figure and see what parts you recognize from our previ-
one of its 80-byte buffers to refresh a row of characters ous discussions. You should quickly find the CRT con-
on the screen, it fills the other 80-byte buffer from the troller, character
generator, and dot shift register. Next,
main memory on a DMA basis. To do this it sends a DMA find the 2 Kbyte memory where the ASCII codes for the
request signal |C)REQ) to the 8257 DMA controller. The characters to be displayed are stored. To the right of this
DMA controller sends a DMA request signal to. for exam- memory is another 2 Kbyte memory used to store an
ple, the
HOLD input of an 8086. When the 8086 sees the attribute code for each character. An attribute code
request signal, it floats its buses and sends a hold ac- specifies how the character is to be displayed. For exam-
knowledgeAs signal.
we described in Chapter 1 1 , the ple, withan underline or with increased or decreased
DMA controller then sends out the memory address and intensity. As you may have observed, it is common prac-
control signals needed to transfer the characters from ticedisplay
to a menu at reduced intensity so it does not
memory to the 8275 buffer. The DMA approach uses distract from the main text on the screen.
only a small percentage of the microprocessor's time Now observe that there is a multiplexer in series with
and. since the display page is located in the main mem- the address lines going to the character and attribute
ory', newcharacters are easily written to it. memories. This is done so that either the CPU or the
The character generator is left out of the controller so CRT controller can access the display-refresh RAM. The
that a ROM for any desired character set can be used. 6845 has 14 address outputs, so it can address up to 16
The dot clock and the dot shift register are also external Kbyte display and attribute locations. To keep the dis-
because of the high frequencies involved in that part of play refreshed, the 6845 sends out the memory address
the circuit. The 8275 produces vertical and horizontal for a character code and an attribute code. The charac-
sync signals, but external circuitry is used to massage ter clock signal latches the code from memory for the
the timing of these signals to correspond with the video character generator and the attribute code for the attri-
information from the dot shift register. Now we will bute decode circuitry. The character clock also incre-
show you another CRT controller approach. ments address
the counter in the 6845 to point to the

Ml( K< (COMPUTER SYSTEM PERIPHERALS 411


next character code in memory. The next character The Cursor output pin will be asserted high when the
clock transfers the next codes to the character generator controller is displaying the cursor. This signal can be
and attribute decoder. The process cycles through all of combined with signals from the attribute decoder to
the characters on the page and then repeats. Now, when cause the cursor to blink or to be highlighted, depend-
you want to display some new characters on the screen, ing onattributes stored for the cursor location.
you simply have the CPU execute some instructions The Display Enable output pin will be asserted when
which write the ASCII codes for the new characters to the 6845 is scanning the active display area of the
the appropriate address in the display RAM. When the screen. This signal can be used to produce blanking
address decoding circuitry detects a display RAM ad- pulses during horizontal and vertical retrace times. In a
dress,
produces
it a signal which toggles the multiplex- system that accesses the display RAM during retrace
ers so
that the CPU has access to the display RAM. The times, this signal can be used to tell the CPU when it can
question that probably occurs to you at this point is. access the display RAM.
"What happens if the 6845 and the CPU both want to When the light pen strobe input, LPSTB. is made to go
access the display RAM at the same time?" There are from low to high, the current refresh address will be
several solutions to this problem. One solution is to latched in two registers inside the 6845.
allow the CPU to access the RAM only during horizontal The 6845 has a register bank of 19 registers which are
and/or vertical retrace times. Another solution is to used to set and to keep track of display counts during
interleave 6845 accesses and CPU accesses. This is how display refreshing. Figure 12-9 shows the function of
it is done in the IBM board. The character clock signal each of these registers. Even if you are not going to be
going to the 6845 and the multiplexers allows the CPU programming a 6845. it is worth taking a look at this
to access the RAM during one half of the clock signal figure so you have an idea of the types of parameters you
and the 6845 to access the RAM during the other half of specify for a CRT controller chip such as the 6845.
the clock signal. If the CPU tries to access the display The 6845 has only two internal I/O addresses which
RAM during the controller's half of the character clock are selected by the RS input. When the RS input is low,
cycle, a not-ready signal from the CRT controller board the internal address register is selected. When the RS
will cause the processor to insert WAIT states until the input is high, one of the 18 internal data registers is
hall of the character clock signal when it can access the selected. In order to access one of the internal data reg-
display refresh RAM. isters, you
first have to write the number (address) of
that register to the address register with RS low, and
then write the data to the 6845 with RS high. RS is usu-
6845 INTERNAL REGISTERS AND INITIALIZATION
ally tied
to a system address line so that you just write
Figure 12-8 shows the pin diagram and labels for the the address word to one address, perhaps 3B4H, and
6845. We will take a brief look at these pin functions, the data word to another address, perhaps 3B5H.
and then discuss the internal registers so we can show The standard way to initialize all of these parameters
you how the device is initialized. for a 6845 in a system is to use a program loop of the
The function of most of the pins should be easily rec- form:
ognizable
you from
to the block diagram in Figure 12-7.
Ground is on pin 1 . +5 V is on pin 20. and a reset input
is on pin 2. The 6845 sends out the display RAM address
of the character currently being scanned on the MAO-
MAI 3 lines. On the RA0-RA4 pins the 6845 sends out the
number of the character scan line currently being
scanned to the character generator. A character clock
signal which changes state when it is time for the con-
troller
access
to the next character in memory is con-
nected
the to 6845 CLK input. The horizontal and verti-
cal syncoutput signals on pins 39 and 40 are produced
by dividing down this CLK input signal. The 6845 has
eight data inputs, D0-D7, which connect to the system
data bus so that initialization words can be written to
the device and status words read from the device, just as
with any of the other peripheral devices we have dis-
cussed.6845
The will be enabled for a read or write on
its data bus when its CS input is asserted low. The RAV
is asserted high for a read and low for a write. The proc-
essor clock,
or a signal derived from it. is applied to the E
input of the 6845 to synchronize data transfers in or out
on the data lines. As seen from the processor, the 6845
has two internal addresses, a control address selected
when RS is low and a data address selected when the RS
input is high. We will tell you more about this alter we FIGURE 12-8 Motorola MC6845 CRT controller pin
talk briefly about the few remaining pins. names.

412 CHAPTER TWELVE


RS Register Func t i on
number

X Holds number of data register to write to.


o Total number of horizontal character times +1 ,

including retrace.
1 Number of horizontal characters displayed.
c Character number when hor i zonta 1 -sync pulse is
produced. Determines horizontal display position.
3 Width of hor i zonta 1 -sync pulse in character times.
Total number of vertical character rows-l» including
vertical retrace.
5 Adjusts vertical timing to get exactly 50 or 60 Hz.
to Number of vertical character rows displayed.
7 Vertical row number when ver t i ca 1 -sync pulse produced.
Controls vertical position on screen.
H Sets controller for interlaced or non-interlaced scanning
9 Number of horizontal scan lines-1 per character row.
LO Starting scan line for the cursor and cursor blink rate.
1 1 Ending scan line for the cursor.
IB Starting address (high byte) for character to be put
out after vertical retrace. Determines which character
row from buffer appears at top of screen. Change this
value to scroll display.
1 13 Low byte of first row starting address.
1 1<+ High byte of current cursor address.
1 15 Low byte of current cursor address in display RAM.
1 16 High byte of display RAM address when LPSTR occurs.
1 17 Low byte of display RAM address when LPSTR occurs.

FIGURE 12-9 MC6845 internal register functions.

REPEAT page up. scroll page down, set color palette, write dot.
Output a data register number to the 6845 internal and write character to screen. You specify the function
address register (RS = 0). you want by loading the number for that function in the
Output parameter byte for that register to data AH register before executing the INT 10H instruction.
register address (RS = 1). To write a character to the screen you simply load AH
with 14 decimal, load AL with the character you want to
UNTIL all required registers of the 18 are initialized.
display, and then execute the INT 10H instruction. An-
Before we start the next section on computer graphics, other BIOS
procedure that you might want to use with
let's take a brief look at how you can use the IBM PC this one is the INT 16H procedure which you can use to
BIOS procedures to display characters on the CRT read characters from the keyboard. If you load AH with 0
and execute the INT 16H instruction, the ASCII code for
screen.
the next key pressed on the keyboard will be left in the
AL register after the procedure executes. Coupling the
Using the IBM PC INT 10H to Display two INT procedures lets you read in characters from the
Characters on the CRT keyboard and display them on the CRT.
If you are working on an IBM PC it is quite easy to dis-
play characters on the CRT as part of your program by
using the BIOS routines in ROM. In Chapter 8 we RASTER SCAN CRT GRAPHICS DISPLAYS
showed you how to use the BIOS INT 17H procedure to
send characters to a printer. To use the BIOS proce- The previous section of this chapter showed you how a
dures you
load the parameters required by the proce- monochrome display of alphanumeric characters can be
dure into
registers specified for that procedure in the produced on a CRT screen. In this section we show you
IBM Technical Reference Manual, and then execute the how we produce a picture or graphics display. The two
INT # instruction that accesses that procedure. You can major methods of producing a graphics display are the
use the BIOS INT 10H procedure for 15 different func- bit-mapped raster scan approach, and the vector
tions related
to the CRT display. Some of these func- graphics approach. We'll explore the raster approach
tions are:
set display mode, set cursor position, scroll first.

MICROCOMPUTER SYSTEM PERIPHERALS 413


Figure 12-5 shows a block diagram of some simple cir- sor the
to point on the screen where you want one end of
cuitry that
can be used to create a display of characters the line and press a button on the mouse. You then
on a CRT screen by turning the electron beam on and off move the cursor to the point on the screen where you
as it is scanned across the screen. Characters are pro- want the other end of the line, and press a button on the
duced
a as
series of dots and undots on the screen. The mouse again. The graphics program then computes the
ASCII codes for the page of characters to be displayed coordinates for the other points on the line and puts Is
are stored in a display-refresh RAM. The dot patterns for in the appropriate locations in the display RAM to draw
each scan line of each character are stored in a charac- in the line. By moving the cursor around on the screen
ter generator ROM. Now, suppose that we leave the and pressing buttons on the mouse at the appropriate
character generator out of this circuit and connect the times, you can quickly create some elaborate graphics
outputs of the RAM directly to the inputs of the dot shift displays. If you have not had a chance to play with a
register. And further suppose that instead of storing the computer that has these graphics capabilities, do not
ASCII codes for characters in the RAM, we store the dot pass go, proceed directly to your nearest computer store
patterns we want for each eight dots of a scan line in and experiment with a graphics program on the Apple
successive memory locations. When a byte is read from Macintosh or IBM PC.
the RAM and loaded into the shift register, the stored
dot pattern will be shifted out to the CRT beam to pro-
duce the
desired pattern of dots for that section of a CRT TERMINALS
scan line on the screen. The next RAM byte will hold the
dot pattern for the next 8 dots on a scan line, etc. Oper- Several times previously in this book we have used the
atingthis
in mode, each bit location in memory corre- term CRT terminal. You may have used a CRT terminal
sponds
a dot
to location on the screen. The entire screen to communicate with a minicomputer or mainframe
then can be thought ol as a matrix of dots. Each dot can computer. In addition to the basic CRT drive circuitry, a
be programmed to be on or off by putting a one or a zero terminal contains a keyboard so you can talk to it. the
in the corresponding bit location in RAM. A graphics CRT-refresh RAM and controller to keep the display re-
display produced in this way is known as a bit-mapped freshed,a and
UART to communicate to and from a
raster scan display. Each dot or in some cases block of computer. Most CRT terminals now have one or more
dots is called a picture element. Most people shorten built-in microprocessors to coordinate keyboard, dis-
this to pixel or pel. For our first example let's assume a play, and
communications functions. A major advan-
pixel is 1 dot. tageusing
of a microprocessor instead of dedicated logic
Now. suppose that we want a graphics display of 640 here is that key functions and communications parame-
pels horizontally by 200 pels vertically. This gives a total ters canbe changed to match a given computer by
of 200 x 640 or 128.000 dots on the screen. Since each simply typing a few keystrokes. A device from National
dot corresponds to a bit location in memory, this means Semiconductor, the NS456, contains a microprocessor-
that we have to have at least 128.000 bits or 16 Kbytes of based CRT controller, a keyboard interface, a UART, and
RAM to hold the pel information for just one display most of the other functions needed for a graphics/
screen. Compare this with the 2 Kbytes needed for each character CRT terminal.
page of an 80 by 24 character display. As we will show
you a little later, producing a color graphics display with
a large number of pels increases the memory require-
BLUE ELECTRON
ments even
further. 'GUNS
Now that you have a picture of a raster graphics
screen as a large matrix of dots, the question that may
occur to you is, "How do 1 draw a rocket ship or other
picture on the screen?" One method is to program each
of the 128.000 dots to be on or off as required to produce
the desired display. This method works, but it is some-
what analogousto handprinting copies of the Bible, a
very tedious process. To make your life easier, many
graphics programs are now available. These programs
allow you to create a complex graphics display, dump
the display to a printer, store the display on a disk, or METAI
MASK
include the display in another program you are writing.
These graphics programs contain graphics routines or
primitives which allow you to draw lines, draw arcs,
draw three-dimentional figures, shade in areas, set up
"windows," etc. Often these programs work with a
mouse. A mouse in this case is a device which moves a
cursor around the CRT screen when you move it around
on the desk next to your computer. To draw a straight FIGURE 12-10 Three-color phosphor dot pattern used to
line between two points, for example, you move the cur- produce color on a CRT screen.

414 CHAPTER TWELVE


trlangulai pattern as shown in Figure 12 10. The dots
CO! OR
are close enough togethei so thai to your eye they appear
BLACK as ,i single dot. By changing the Intensity ratio ol tin
BLUE (luce beams we ran make the three pari dol appeal any
COloi we waul, including black and while, li all three
CYAN beams are off, the dol is ol course black. It the beams are
HI D turned on in the ratio ol 0.30 RED, <>..r>9 GREEN, and
MAGENTA
0. 1 1 BLUE, then the dol will appear white. The overall
Intensity ol the three beams, often represented with the
BROWN
letter I or the letter Y determines whether the dol will be
WHITE
a lighl 01 a dark shade ol the color Figure 12-1 1 shows
GRAY
16 colors thai can be produced by simply turning on or
LIGHT BLUE
off different combinations of the red, blue, and green
LIGHI GREEN
beams A 1 in the I bit means that the overall intensity ol
LIGHT CYAN the beam is increased to lighten the color as shown. 11
LIGHT RED we drive the color guns and the intensity with the oul
LIGHT MAGENTA put of a D/A converter instead ol simply on or off signals.
YELLOW we can produce a much wider variety of colors. A 2-bit
HIGH INTENSITY WHITE D/A converter on each of the color signals and the inten-
sity signal, for example, gives 256 color variations In
order to produce a display with a large number of pixels
FIGURE .2-11 Sixteen colors produced by different
and a large number of colors, a large memory is needed.
combina ions of red, blue, and green beams at normal
and at increased intensity. As we discuss a common color graphics adapter in the
next section, we will show you some of the tradeoffs in-
volved
this.in
RASTER SCAN COLOR GRAPHICS

Monochrome graphics displays get boring after a while, The IBM PC Color/Graphics Adapter Board
so let's see how you can get some color in the picture. As a real system example here we will use the IBM PC
To produce a monochrome display we coat the inside color/graphics adapter board whose block diagram is
of the tube with a single phosphor which produces the shown in Figure 12-12.
desired color light when bombarded with electrons from This board again uses the Motorola MC6845 CRT
a single electron gun at the rear of the tube. To produce controller device to do the overall display control. It
a color CRT display we apply red. green, and blue phos- produces the sequential addresses required for the
phors
thetoinside of the tube, and bombard these three display-refresh RAM. the horizontal sync pulses, and
different phosphors with three separate electron beams. the vertical sync pulses as we described in a previous
One approach is to have dots of the three phosphors in a section. The 16 Kbyte display-refresh RAM is dual-

PROCESSOR INPUT
DISPLAY
ADDRESS ADDRESS BUFFER DATA
BUFFER
LATCH (16 K BYTESI

OUTPUT
[ 1 LATCH

ADDRESS DATA DATA


PROCESSOR
6845 LATCH LATCH LATCH
DATA
CRT
CONTROLLER I GRAPHICS
SERIALIZER ~|
-

CHARACTER -
ALPHA COLOR
GENERATOR
SERIALIZER ENCODER %º
ROM

PALETTE/
OVERSCAN HORIZONTAl
VERTICAL

COMPOSITE
TIMING COLOR —

MODE
GENERATOR GENERATOR
CONTROL
'

FIGURE 12-12 IBM PC color graphics adapter board block diagram.

MICROCOMPUTER SYSTEM PERIPHERALS 415


ported. This means that it can be accessed by either the 7 6 5 4 3 2 1 0

system processor or the CRT controller on a time-share CI CO CI CO C1 CO C1 CO


basis as we also described previously. A little later we
FIRST SECOND THIRD FOURTH
will show you how display information is stored in RAM DISPLAY DISPLAY
DISPLAY DISPLAY
for various display modes. PEL PEL PEL PEL

This adapter board can operate in either a character


mode or a graphics mode. In the character mode it uses
a character generator ROM and a single shift register
CI CO FUNCTION
(alpha serializer) to produce the serial dot information
for display scan lines. When operating in a color graph- DOT TAKES ON THE COLOR OF 1 of 16
0 0
ics mode,the board uses separate shift registers (graph- PRESELECTED BACKGROUND COLORS

ics serializer) to produce the dot information for each of SELECTS FIRST COLOR OF PRESELECTED
0 1
the color guns and for the overall intensity. COLOR SET 1 OR COLOR SET 2

As you can see by the signals shown in the lower right SELECTS SECOND COLOR OF PRESELECTED
1 0
corner of Figure 12-12. the adapter board is designed to COLOR SET 1 OR COLOR SET 2

drive either of the two common types of color monitor. SELECTS THIRD COLOR OF PRESELECTED
1 1
One type, commonly called an RGB monitor, has sepa- COLOR SET 1 OR COLOR SET 2

rate inputsfor each of the required signals, red. green,


blue, intensity, horizontal sync, and vertical sync. The
other type of color monitor is called a composite color
COLOR SET 1 COLOR SET 2
monitor because all of the required signals are combined
on a single line. Color TV sets used as color monitors for COLOR 1 ISGREEN COLOR 1 IS CYAN
computers require a composite video signal if they have COLOR 2 IS RED COLOR 2 IS MAGENTA
COLOR 3 IS BROWN COLOR 3 ISWHITE
a direct video input, or they require a radio-frequency
signal modulated with the composite video signal if they
do not have a direct video input. Later we will show you FIGURE 12-14 Data storage format for medium-resolution
how we produce a composite color video signal from the graphics mode of IBM PC color adapter board.
separate signals. Now let's look at how the display infor-
mation
stored
is in the display-refresh RAM for various
display modes. The intensity bit. I. in the attribute byte allows you to
In the character or alphanumeric mode each charac- specify normal intensity or increased intensity for a
ter is
represented by two bytes in the display-refresh character. The bit patterns used to produce different
RAM in the format shown in Figure 12- 13a. This is the colors with the RGB and I bits are shown in Figure
same format as the monochrome adapter board. The 12- 13b. The B bit in the attribute byte allows you to
upper byte contains the 8-bit ASCII code for the charac- specify that a character will be blinked. Only 4 Kbytes of
ter be
to displayed. The lower byte contains an attribute the display RAM are needed to hold the character and
code which you use to specify the character color (fore- attribute codes for an 80 character by 25 row display.
ground) theandbackground color for the character. For displaying graphics, the adapter board can be
operated in three different modes: low resolution, me-
dium resolution,and high resolution. Higher resolution
DISPLAY-CHARACTER CODE BYTE ATTRIBUTE BYTE means more pixels in the display. We will use these three
7 6 5 4 3 2 10 7 6 5 4 3 2 10
modes to show you the tradeoffs between number of col-
ors, resolution, and memory requirements.
We often use the low-resolution mode when we are
using a color TV set or a composite video monitor as a
ATTRIBUTE BYTE
display device, because this mode requires less video
ATTRIBUTE FUNCTION
amplifier bandwidth than high-resolution modes. In
,' 6 5 4 ; 2 1 0
this low-resolution mode each pel is 2 dot times hori-
B RGB i RGB
zontally
2 dot
and times vertically, so the picture is actu-
FG BACKGROUND FOREGROUND ally being
made with larger blocks. The display consists
of 100 rows of pels with 160 pels in each row. The total
NORMAL B 0 0 0 1 1 1 1
REVERSE VIDEO B 1 1 1 1 0 0 0 number of pels is then 16.000. The color and intensity
NONDISPLAY (BLACK) B 0 0 0 1 0 0 0 for each pixel is specified by the I, R. G. and B bits in the
NONDISPLAY (WHITE) B 1 1 1 1 1 1 1
lower half of a byte in the display RAM. Since 4 bits are
= HIGHLIGHTED FOREGROUND (CHARACTER) being used to specify color and intensity, a pel can be
= BLINKING FOREGROUND (CHARACTER) any one of 16 colors. Since a byte is used to store the
information for each pel. all 16 Kbytes of the display
RAM are used to display the 100 by 160 pel display.
FICURI 12-13 Data storage formats lor IBM color In the medium-resolution mode each pel is a single
graphics board operating in alphanumeric mode, (a) dot. The display consists of 200 rows of pels with 320
Character byte and attribute byte, lb) Attribute byte pels in each row, or a total of 64.000 pels. The 16 Kbytes
format. of display refresh RAM corresponds to 16 Kbits * 8 or

416 CHAPTER TWELVE


the cotnmen lall - ill tble graphli These
6 b •1 3 , .
progi ims allow you to product th< figures you want
with a mouse oi with drawing instructions rather than
t li.,IHH DISPLAY PEL specifying the bit values foi each pixel.
As you should see by now. the limiting factoi foi coloi
SIXTH DISPLAY PEL graphics displays is the amount ol memory you are will-
FIFTH DISPLAY PEL
ing devote
to to the display. Sonic high resolution dis
I OURTH DISPLAY PEL
plays used in engineering work stations have a display
I HI HI.) DISPLAY PEL
ol 1000 by 1000 pels with 16 colors. A display such as
ID DISPLAY PEL
FIRST DISPLAY PEL
this requires about 500 Kbytes ol high-speed-refresh
RAM
FIGURI 12-15 Data storage format for high-resolution For each ol the graphics formats above, data for a pel
graphics mode o( IBM PC color graphics adaptei board. is read from the display RAM and converted to separate
R, (,. B, .ind I signals. These signals, along with the hori-
zon!.il
and vertical sync signals, can be sent directly to
L28 Kbits. Dividing the number of pels iulo the number an RGB-type monitor. Before they can be senl toai om
of bits available for storage tells you that in this mode posite video-type monitor these signals must be put to-
(here are only 2 bits per pel available to store color Infor- gether
a single
in Signal. Here's how we do it.
mation.'2With
bits we ran specify only one ol four colors
for each pel. As yon can see. increasing the resolution of
the display lias reduced the number of colors that can be
Producing a Composite Color Video Signal
specified with a given amount of memory. Figure 12-14 In order to produce a composite color signal from the R.
shows the format in which the pel information is stored G, B. and sync signals, we can't just add all the signals
in RAM bytes and the meaning of the bits in these bytes. together. Instead, the approach we use is based on the
The background color is selected by outputting a control NTSC standards for color television signals. Figure
byte through port 3D9H to the palette circuit shown on 12-16 shows in diagram form the somewhat complex
the left edge of Figure 12-12. Consult the IBM Technical method used to put the pieces together
Reference Manual for more details if you need them. As a first step, the red, the green, and the blue signals
In the high-resolution graphics mode the IBM color are combined in the ratios shown to produce a signal
graphics adapter board displays 200 rows of pels with proportional to the overall intensity or luminance. If
640 pels in each row. or a total of 128.000 pels. Since horizontal and vertical sync pulses are added to this sig-
the 16 Kbyte refresh RAM contains 128,000 bits, this nal, the
result is a monochrome composite video signal
corresponds to 1 bit per pel. Therefore, you can only identical to that we described earlier in this chapter.
specify for each bit whether it is on or off. In other This signal will produce a monochrome display on ei-
words, in this high-resolution mode you are limited to a thermonochrome
a monitor or a color monitor.
black-and-white display, because there are no bits left to To develop the correct color signals we pass the lumi-
specify colors. Figure 12-15 shows the format in which nance signal
through a 1.5-MHz low-pass filter and then
pel data is stored in display RAM bytes for high-resolu- an inverter. The filter is required to comply with FCC
tion displays.Here again we want to point out that if you bandwidth rules if this signal is going to be sent out as
want to produce color graphics displays as part of your part of a TV signal modulation. The inverted luminance
programs, the best approach is probably to buy one of signal. -Y. is then added to the red signal to produce

COMPOSITE
COLOR
Y. R-Y * VIDEO
FROM
COLOR
Q
CAMERA
{OR
MEMORY)

HORIZONTAL, VERTICAL
AND BLANKING PULSES

FIGURE 12-16 Block diagram of circuitry used to produce composite color


video signal.

MICROCOMPUTERSYSTEMPERIPHERALS 41 7
R - Y. and it is added to the blue signal to produce B- width of a composite color monitor or a color TV is lim-
Y. The reason we do this is probably not obvious to the itedless
to than 3 MHz. As we explained in the section of
casual observer, but this scheme reduces the number of the chapter on monochrome displays, this limits the
separate signals which have to be sent. Here's how it resolution, and makes it difficult to display 80-character
works. The Y. R - Y, and B - Y signals are sent as part of lines or detailed graphics on standard TV displays. Now
the color TV signal or as part of the composite video sig- that we have beat raster scan displays into the ground,
nal. the
In receiver the Y signal is added to the R - Y we will show you how vector scan displays work.
signal to reconstruct the red signal. The Y signal is
added to the B - Y signal to reconstruct the blue signal.
Since the Y signal is composed of red. green, and blue, VECTOR SCAN CRT DISPLAYS
the red signal and the blue signal are subtracted from
the Y signal to reconstruct the green signal. Because of A raster scan CRT display scans the electron beam over
all this we don't have to send a separate green signal. the entire screen and turns the beam on and off to pro-
Now that you have an idea why we do all of this, let's duce
light
a or dark spot at each point in the scan. For
continue the story of a composite color video signal. certain CRT display applications such as computer-
The key to the next step is a stable 3.579545-MHz sig- aided design workstations where the display consists
nal produced by a crystal oscillator. The B - Y signal is mostly of background and an array of straight lines, it
used to modulate this signal, and the R - Y signal is seems wasteful to sweep the beam back and forth over
used to modulate a portion of this 3-MHz signal whose the entire screen. Also diagonal lines drawn on a raster
phase has been shifted by 90°. The two modulated scan display look like stair steps if you look closely at
3.579545-MHz signals are then added together. The re- them, because of the rigid placement of the pixels on the
sultsometimes
is called the chroma signal, because it screen.
contains the color information. A vector graphics scheme solves both of these prob-
Now, to produce the color composite video signal we lemsdirectly
by tracing out only the desired lines on the
simplv add the horizontal sync pulses, the vertical sync CRT. In other words, if we want a line connecting point
pulses, the Y signal, and this chroma signal together as A with point B on a vector graphics display, we simply
shown in Figure 12-16. When the composite video mon- drive the beam-deflection circuitry with a signal which
itor receivesthis signal, it will separate all of the pieces causes the beam to go directly from point A to point B. If
again. we want to move the beam from point A to point B with-
To produce a composite signal which can be fed into out showinga line between the points, we can blank the
the antenna input of a color TV set. we usually use a beam as we move it. To draw a line on the CRT. then, we
chroma modulator device such as the Motorola MC 1372 simply tell the beam how far to move and in what direc-
shown in Figure 12-17. This device produces the tionmove
to across the CRT. The name vector graphics
3.579545-MHz color carrier frequency, and it produces comes from the fact that in physics a quantity which
the chroma signal from the R - Y and B - Y signals. The has magnitude and direction is called a vector.
device also produces a radio-frequency carrier at the fre- The question that may occur to you at this point is.
quencystandard
lor TV channel 3 or 4 and modulates "How do vou tell the beam where to move on the
this carrier signal with the Y. R - Y. B - Y, and sync in- s( reen?" One way to direct the beam is by connecting a
formation.
a When
color TV set receives this modulated DA converter to the horizontal deflection circuitry and
signal, it demodulates the signal and separates the vari- another D/A converter to the vertical deflection circuitry.
ous parts. Because it has to filter out the remnants of The values input to the two D/A converters then deter-
the 3.579545-MHz color carrier frequency, the band- mine position
the of the beam on the screen. If we use
10-bit DA converters, we can direct the beam to one of
1024 positions horizontally and one of 1024 positions
vertically. This is equivalent in resolution to a IK by IK
raster display. Color displays can be produced by using a
three-beam, three-phosphor CRT and moving the three
beams together as we described for the raster scan color
display.
The next question that may occur to you is, "If this
scheme is so simple, why don't we use it for all CRT
graphics displays?" The answer is that a vector display
works well where the information we want to display is
mostlv straight lines, but it does not work well for dis-
plays that
have many curves and large shaded areas.
When using a vector graphics system, we draw, for ex-
ample,
circlea by drawing many short vectors around in
a circle. The circle is then made up of short line seg-
TANK CIRCUIT TUNED TO
mentspoints.
or The number of vectors you can draw on
CHANNEL3 OR 4
the screen is limited by the fact that you have to go back
FIGURE 12-17 Motorola MC1372 used to produce color and redraw each vector 60 times a second to keep the
video signal compatible with a standard TV channel. display refreshed. Some current vector graphics sys-

418 CHAPTER TWELVE


terns can draw 150,000 short vectors 60 times a second, from obstacles. Some Polaroid cameras use thi

but 11>i complex images you soon run oul ol ve< tors rhe I i.ii iism ii i detei nunc the di i i ibjecl being
point here is that no one display technique 01 techno! photographed. I he camera then uses the dl

ogy has .ill nt the marbles al this poinl in time, Heres mation to automatically locus the camei
another display technology that has some advantages rhe majoi parts ol the range findei circuitry used in
lor portable Instruments and computers. these cameras, including a printed circuil board, is
available as a kit Irom Texas Instruments. With one oi
these kits and some simple t ircuitry you can ,uU\ this
type ol vision to your microcomputer. Figure 12-I8a
ALPHANUMERIC GRAPHICS LCD shows a block diagram foi the cin uitry on the experi-
DISPLAYS mental board,
and Figure 12 18b shows the major wave-
formsonefor cycle of operation. A cycle starts when the
InChaptei 9 we discussed how LCDs work and how they
VSW input is pulsed high. I he transmitter section then
can be used in display numbers and letters as individual
sends nut a "chirp" ol 56 pulses through the transducer.
digits In make a screen type display the liquid crystal
The output is called a (hup because the T><ipulses step
elements are constructed in a large X-Y matrix oi dots.
through lour frequencies, (>() kHz, 57 kH/.. r>.'5kHz, and
The elements in each row are connected togethei . and
50 kHz to avoid absorption problems that mighl occur
the elements in each column arc connected together, An
with just one frequency. This transmission is repre-
individual clement is activated by driving both the row
sentedthebyXLG signal in Figure L2-18b.
and the column thai contain that clement. LCD ele-
Alter the pulses arc sent out. the circuitry is switched
ments cannotbe tinned on and oil last enough to be
so i hat the transducer functions as a receiver. When the
scanned one dot at a time in the way thai we scan a CRT
echo of the sound waves returns to the transducer it
display. Therefore, we apply the data lor one dot line of
produces an analog electrical signal out ol the trans-
one character, or for an entire line, to the X axis of the
ducer.
programmable-gain
A amplifier amplifies this
matrix, and activate that dot row of the matrix. For a
echo and convei ts it to a digital pulse shown as the FfG
graphics display we wail a short time, then we deacti-
signal in Figure 12- 18b. The time it took the ultrasonic
vate that
dot row. apply the data for the next dot row to
signal to go out to the target and return then is the time
the X axis, and activate that dot row. We continue the
between the first rising edge of XLG and the rising edge
process until we get to the bottom of the display and
ol the PLC. signal.
then start over at the top of the screen. For large LCDs
the matrix may be divided into several blocks of perhaps
40 dot lines each. Since each block of dot rows cm l»
TRANSDUCER
refreshed individually, this reduces the speed at which
each liquid crystal element must be switched in order to
keep the entire display refreshed. Large LCDs usually
come with the multiplexing circuitry built in so that all
vou have to do is send the display data to the unit in the
format specified by the manufacturer for that unit. We
should soon see color LCDs for use with computers.

COMPUTER VISION

For many applications we need a microcomputer to be


able to "see" its environment or perhaps a part that the
machine it controls is working on. As part of a
microcomputer-controlled security system, for example.
we might want the microcomputer to "look" down a cor-
ridorsee
to if any intruders are present. In an auto-
mated factory
application we might want a micro- _l NOT
ACCURATELY
REPEATABLE
| |
FROM CYCLE TO CYCLE 0FF
computer-controlled
to "look" robot
in a bin of parts, ,.
recognize a specified part, pick up the part, and mount
the part on an engine being assembled. There are sev- TRANSMISSION
(XLG)
eral mechanisms we can use to allow a computer to see.
The first one we will discuss uses sound waves.
DETECTED
ECHO (FLG)
Ultrasonic Vision
Bats "see" in the dark by emitting sound waves that are
above the human hearing range or ultrasonic. A bat FIGURE 12-18 Polaroid ultrasonic range finder, (a) Block
sends out ultrasonic pulses, and on the basis of the time diagram ot interlace circuitry. (I)) Major signal
it takes for echoes to return, determines how far it is waveforms.

MICROCOMPUTER SYSTEM PERIPHEKAfs 41 9


You can measure this time in any one of several ways. GATE ISOLATION

One way is to start a counter with the rising edge of XLG.


and stop the counter with the rising edge of FLG. the
OXIDE
number left in the counter then is the number of clock % W, .^7>. ,°^», .^b7r—?^P ./LAYER
pulses required for the signal to go out to the target and
P SUBSTRATE
back. To get the total time for the trip, you can multiply
the number of clock pulses counted by the period of the
FIGURE 12-19 Basic structure of charge-coupled device
clock pulses. Divide this time by 2 to get the actual time
used in CCD video cameras.
to the target. Since sound travels at about 1 foot in
0.888 ms, you can easily convert the transit time to an
equivalent distance. An exercise in the laboratory man-
ual written to accompany this book shows you more "potential well" is created under that gate. What this
about all of this. means is that, if a charge of electrons is injected into the
A simple ultrasonic range finder such as we have de- region under the gate, the charge will be held there. By
scribed could
here be mounted in a mobile robot. By applying a sequence of clock signals to the gates, this
scanning the rangefinder back and forth the robot could stored charge can be shifted along to the region under
determine a clear path through a series of obstacles, or the next gate. In this way a CCD can function as an
detect when someone intrudes into its space. The range analog or a digital shift register.
finder we described has a range of about 35 feet, and a To make an image sensor, several hundred CCD shift
resolution of about '/« inch when looking at a flat surface registers are built in parallel on the same chip. A photo-
perpendicular to the sound waves. For applications diode is doped in under every other gate. When all of the
where we need greater resolution or to recognize the gates with photodiodes under them are made positive,
shapes of objects, we use optical vision devices with our potential wells are created. A camera lens is used to
microcomputer. focus an image on the surface of the chip. Light shining
on the photodiodes causes a charge proportional to the
light intensity to be put in each well which has a diode.
Video Cameras and Computers These charges can be shifted out to produce the dot-by-
Cameras used in TV stations and for video recorders use dot values for the scan lines of a picture. Improved per-
a special vacuum tube called a vidicon. A light-sensitive formance
be gained
can by alternating nonlighted shift
coating on the inside of the face of the vidicon is swept registers with the lighted ones. Information for a scan
horizontally and vertically by a beam of electrons. The line is shifted in parallel from the lighted register to the
beam is swept in the same way as the beam in a TV set dark, and then shifted out serially.
displaying the picture will be swept. The amount of The video information shifted out from a CCD register
beam current that flows when the beam is at a particu- is in discrete samples, but these samples are analog be-
lar spoton the vidicon is proportional to the intensity of causecharge
the put in a well is simply a function of the
the light that falls on that spot. The output signal from light shining on the photodiode. To get the video infor-
the vidicon for each scan line then is an analog signal mationa into
form that can be stored in memory and
proportional to the amount of light falling on the points processed by a microcomputer, it must be passed
along that scan line. This signal is represented by the through an A/D converter, or in some way converted to
waveform between the horizontal sync pulses in Figure digital. For many robot applications and surveillance
12-2. In order to get this analog video information into a applications, a black-and-white image with no gray
digital form that a computer can store and process, we tones is all we need. In this case the video information
have to pass it through an A/D converter. For a color from the CCD registers can simply be passed through a
camera we need an A/D converter on each of the three comparator to produce a 1 or a 0 for each dot of the
color signals. Each output value from an A/D converter image. CCD cameras have the advantages that they are
then represents a dot of the picture. The number of bits smaller in size, more rugged, less expensive, and easier
of resolution in the A/D converter will determine the to interface to computer circuitry than vidicon-based
number of intensity levels stored for each dot. cameras. Next we describe an inexpensive type of cam-
Standard video cameras and the associated digitizing era whichproduces digital video information directly.
circuitry are relatively expensive, so they are not cost-
effective for many applications. In cases where we don't
need the resolution available from a standard video OPTICRAM Cameras
camera we often use a CCD camera. Figure 12-20 shows a picture of the Micron Eye camera
produced by Micron Technology in Boise. Idaho. This
camera is relatively inexpensive, interfaces easily to
CCD Cameras
common microcomputers, and has enough resolution
Charge-coupled devices or CCDs are constructed as for simple robot-type applications.
long shift registers on semiconductor material. Figure The heart of this camera is a 64 Kbit dynamic RAM
12-19 shows the structure for a CCD shift register sec- with a glass cover instead of the usual metal lid. A lens
tion.you
As can see. the structure consists of simply a on the front of the camera is used to focus the image
P-type substrate, an insulating layer, and isolated gates. directly onto the surface of the dynamic RAM. Here's
If a gate is made positive with respect to the substrate, a how it works.

420 CHAPTER TWELVE


puter memory foi processing. The sensitivity ol the
camera to lighl can be adjusted bj < hanging the time
between when you charge up .ill the <ells and whin you
read oul the logic levels <ni the cells For brighter lii^lif
conditions, use a shoi tei time et<
Available with the Micron Eye are printed circull
boards which contain circuitry to interface the camera
to comm nlcrocomputers such .is the IBM PC, the
APPLE, and the Commodore 64 With these boards in-
stalledcan
youdisplay images on 111«- CRT screen, adjust
display parameters undei program control, and save
images on a disk. Once you gel the bit pattern foi an
image into memory, sou can then experiment with pro-
grams whichattempt to recognize the image of, foi ex
ample. ,i square in the image.
Figure 12-21 shows an example ol what a lit fie vision
can do for a robot. The Sumitomo Electric Company
robot shown here can play an organ using both hands
mi the keys and both feet on fhe pedals. II can puss up
(o 15 keys per second. The robot can play selections
from memory when verbally told to do so. Using its vi-
sioncan
it read and play songs from standard sheet
music. The robot uses seventeen 16-bit microprocessors
and fifty 8-bit controllers to control all of its activities.
If you think some about what is involved in recogniz-
ing complexvisual shapes, in all of their possible orien-
tations,awith
computer program, it should give you a

FIGURE 12-20 Micron Eye optic RAM video camera with


interface board for IBM PC. (Micron Technology Inc.)

The 65,536 storage cells of dynamic RAM are arranged


in two arrays of 128 by 256 cells each. Each cell func-
tionsaas pel. There is a dead zone of about 25 cell
widths between the two arrays. If the two arrays are
used together, this dead zone has to be taken into ac-
count.
Remember now that data is stored in dynamic RAMs
as a charge on a tiny capacitor. Dynamic RAMs have to
be refreshed because the charge gradually changes due
to leakage. If you shine a light on a dynamic RAM cell,
the charge changes faster than it would without the
light. To use the dynamic RAM as an image sensor,
then, we start by charging up all of the cells to a logic 1
level. After some amount of time we read the logic level
on each cell. A cell which still contains a logic 1 repre-
sents
darka spot, and a cell which has dropped to a logic
0 represents a light spot. The logic levels can be read out FIGURE 12-21 Organ-playing robot developed by
of the OPTICRAM and stored directly in a microcom- Sumitomo Electric Company.

MICROCOMPUTER SYSTEM PERIPHERALS 421


new appreciation for the pattern recognition capabili- RECORD HEAD GAP

tiesthe
of human eye-brain system.
Another area where the human brain excels is in that
of data storage. Only very recently have the devices used
to store computer data approached the capacity of the
human brain. In the next section we look at how some of
these mass data storage systems operate, and how they
are interfaced to microcomputers.

MASS DATA STORAGE SYSTEMS

Since the ROM and RAM in a computer cannot possibly


hold all of the programs that we might want to run and
all of the data that we might want to analyze, a computer
system needs some other form of data storage which can
hold massive amounts of data, is nonvolatile, can be FIGURE 12-23 Magnetic disk read/write head.
updated, and has relatively low cost per bit of storage.
The most common devices used for mass data storage
are magnetic tape, floppy magnetic disks, hard mag-
spins the disk at a constant speed of perhaps 300 or 360
netic disks,
and optical disks. Magnetic tapes are used
mostly for backup storage, because the access time to rpm.
Data is stored on the disk in concentric, circular
get to data stored in the middle of the tape is usually too
tracks, rather than in a spiral track as it is on a phono-
long to be acceptable. Therefore, in our limited space
graph record.A read/write head contacts the disk
here we will concentrate on the three types of disk stor-
through the racetrack-shaped slot to read from or write
age. to the disk. Figure 12-23 shows a diagram of a read/
write head. In the write mode a current passing through
the coil in the head creates a magnetic flux in the iron
FLOPPY DISK DATA STORAGE core of the head. A gap in the iron core allows the mag-
netic flux
to spill out and magnetize the magnetic mate-
Floppy Disk Overview rial on
the disk. Once a region on the disk is magnetized
Figure 12-22 shows a picture of a typical floppy disk in a particular direction, it retains that magnetism. The
enclosed in its protective envelope. The common sizes polarity of the magnetized region is determined by the
for disks are 8. 5.25, and 3.5 inches. The disk itself is direction of the current through the coil. We will say
made of Mylar and coated with a magnetic material. The more about this later.
Mylar disk is only a few thousanths of an inch thick, Data can be read from the disk with the same head.
thus the name floppy. When the disk is inserted in a Whenever the polarity of the magnetism changes as the
drive unit, a spindle clamps in the large center hole and track passes over the gap in the read/write head, a small
voltage, typically a few millivolts, is induced in the coil.
An amplifier and comparator are used to convert this
PERMANENT LABEL TEMPORARY ID LABEL small signal to standard logic levels.
The write-protect notch in a floppy disk envelope can
be used to protect stored data from being written over.
as the knock-out plastic tabs on audiotape cassettes are.
An LED and a phototransistor can indicate whether the
notch is present and disable the write circuits if it is.
NDEX HOLES
An index hole punched in the disk indicates the start
of the recorded tracks. An LED and a phototransistor
= E are used to detect when the index hole passes.
o o

Disk Drive and Head Positioning


The motor used to spin the floppy disk is usually a dc
WRITE motor whose speed is precisely controlled by negative
PROTECT
feedback as we described in Chapter 10. In most sys-
NOTCH
tems this
speed will be held constant at all times. Typi-
cally
takes
it about 250 ms for the motor to start up after
-6.25 in (159 mm)- a start motor command.
The most common method of positioning the read/
write head over a desired track is with a stepper motor.
FIGURf 12-22 Floppy disk in protective envelope. A lead screw or a let-out— take-in steel band, such as that

422 CHAPTERTWELVE
DOUBLE-SIDED The actual digital data is stored on floppy disks In
STEPPING MOTOR HEAD ASSEMBLY
many different foi mats, so we can't begin to show you .ill
ni them In give you a general Idea, we will use an old
Mini. ml, the IBM 3740 format, which is the basis ol
most currenl formats Figure 12 2.r> shows how bytes
MAGNETIC
HEADS are written to a track in this formal
In the 3740 format a track has three types of fields. An
index field Identifies the start of the track. ID fields
coni. mi the track and sector identification numbers for
each ol the 26 data sectors on the track Each ol the 26
sectors also contains a datajield which consists ol 128
bytes of data plus two bytes foi an ei rot chei king i odi
As you can see. In addition to the bytes used to store
RRIAGE WAY DOUBLE-SIDED data, many bytes are used for identification, synchroni
DISKETTE
RIAGE zation, error checking, and buffering between sectors.
One type of separator used here is called a gap. A gap is
BASE CASTING simply a region which contains no data Caps .in- pro
MOUNTING PLATE
vided to separate fields, so that the information stored
FIGURL 12-24 Head positioning mechanism for floppy in one field can be changed without altering an adjacent
disk drive unit. (Shui^drt Corporation) field.
Address marfcs shown at several places in this format
are special bytes which have an extra clock pulse re-
shown in Figure 12-24. converts the rotary motion of corded along
with their D2 data bit. Address marks are
the stepper motor to the linear motion needed to posi- used to identify the start of a field. The four types of
tion the
head over the desired track on the disk. As the address mark are: index, ID, data, and deleted data.
stepper motor in Figure 12-24 rotates, the steel band is Two bytes at the end of each ID field and 2 bytes at the
let out on one side of the motor pulley, and pulled in on end of each data field are used to store checksums or
the other side. This slides the head along its carriage. cyclic redundancy characters. These are used to check
To find a given track, the motor is usually stepped to for errors when the ID and the data are read out. A data
move the head to track zero near the outer edge of the checksum, for example, is produced by adding up all of
disk. The motor is then stepped the number of steps the data bytes and keeping only the least-significant 2
required to move the head to the desired track. Typically bytes of the result. These 2 bytes are then recorded after
it takes a few hundred milliseconds to position the head the data bytes. When the data is read, it is readded and
over a desired track. the sum is compared with the recorded checksum bytes.
Once the desired track is found, the head must be If the two sums are equal, then the data was probably
pressed against the disk or loaded. Typically it takes read out correctly. If the sums do not agree, then an-
about 50 ms to load the head and allow it time to settle other attemptcan be made to read the data. If. after sev-
against the disk. eral tries,the sums still do not compare, then a disk
read error can be sent out to the CRT.
Instead of using a checksum, most disk systems use a
Floppy Disk Data Formats and Error Detection cyclic redundancy character or CRC method. There are
As we said previously, floppy disks come in several stan- actually several similar techniques using CRC. Here's
dard sizes.Larger disks tend to have more data tracks one way to give you the idea. To produce the 2 CRC bytes
than smaller disks, but there is no one standard num- the 128 data bytes are treated as a single large binary
ber of
tracks for any size disk; 8-in disks typically have number and are divided by a constant number. The
about 77 tracks/side. 5.25-in disks about 40 tracks/ 16-bit remainder from this division is written in after
side, and the new 3.5-in disks in hard plastic envelopes the data bytes as the CRC bytes. When the data bytes
about 80 tracks/side. Single-sided drives record data and the CRC bytes are read out. the CRC bytes are sub-
tracks on only one side of the disk. Double-sided drives tracted the
from data string. The result is divided by the
use two read/write heads to store data on both sides of original constant. Since the original remainder has al-
the disk. The data tracks on floppy disks are divided ready beensubtracted, the remainder of the division
into sectors. There are two different methods of indicat- should be zero if the data was read out correctly. Higher-
ing thestart of sectors: hard sectoring and soft sector- quality systems usually write data to a disk and immedi-
ing. Hard-sectored 8-in disks typically have 32 addi- ately read
it back to see if it was written correctly. If an
tional index
holes spaced equally around the disk. Each error is detected, then another attempt can be made. If
hole signals the start of a sector. The index hole photo- 10 write attempts are unsuccessful, then the operator
detector is used to detect these sector holes. can be prompted to throw out the disk, or the write can
Soft-sectored disks have only the one index hole be directed to another sector on the disk.
which indicates the start of all of the tracks. The sector The IBM 3740 format we have been describing is re-
format is established by bytes stored on the track. Most ferred
as to single density. An 8-in disk in this format
newer systems use soft sectoring because it is more reli- has one index track and 76 data tracks. Since each
able thanhard sectoring. track has 26 sectors with 128 data bytes in each sector.

MICROCOMPUTER SYSTEM PERIPHERALS 423


ONE TRACK

INDEX
POST SECTOR SECTOR SECTOR SECTOR SECTOR SECTOR SECTOR
PREAMBLE ADDRESS POSTAMBLE
INDEX GAP 1 2 3 4 24 25 26
VASf

NDEX 46 1 33 ^ ^
HOLE BYTES BYTE BYTES BYTES] ^^

ID ADDRESS TRACK SECTOR DATA ADDRESS NEXT ID


MARK ID MARK ADDRESS MARK

33
byti r BYTES BYTES

/
/
/
/

TRACK SECTOR
0 0 CHECKSUM DATA CHECKSUM
NUMBER N JM8ER

128 BYTES - — 2 BYTES —

FIGURE 12-25 IBM 3740 floppy disk soft-sectored track format (single density).

the total is about 250 Kbytes. If we use both sides of the through the next section, keep in mind that what we
disk we get about 500 Kbytes. To increase the storage show in the waveforms as a pulse simply represents a
capacity even further, most systems use double-density change in magnetic polarity on the disk.
recording. Double-density recording uses a different Figure 12-26 shows how bits are stored on a disk
clock and data bit pattern to pack twice as many sectors track in single-density format. This format is often
in a track. Now let's look at how data bits are actually called frequency modulation. FM. or F2F recording.
recorded on floppy disks. Note that there is a clock pulse. C. at the start of each bit
cell in this format. These pulses represent the basic fre-
quency.
1 is written
A in a bit cell by putting in a pulse.
Recorded Bit Formats - FM and MFM D. between the clock pulses; a 0 is represented by no
A "one'' bit is represented on magnetic disks as a change pulse between the clock pulses. Flitting in the data
in the polarity of the magnetism on the track. A "zero" pulses modifies the frequency, thus the name frequency
bit is represented as no change in the polarity of the modulation.
magnetism. This form of recording is often called non- The recorded clock pulses are required to synchronize
return-to-zero
NRZ recording,
or because the magnetic the readout circuits. The actual distance, and therefore
field is never zero on a recorded track. Each point on the time, between data bits read from an outer track is
track is always magnetized in one direction or the other. longer than it is for data bits read from an inner track. A
The read head produces a signal when a region where circuit called a phase-locked loop adjusts its frequency
the magnetic field changes passes over it. As you read to that of the clock pulses and produces a signal which

ji_jL_rL_n_n_n_Ji n n n n n n_rL_
D C

R __n n tl_

FIGURE 12-26 FM and MFM recording formats for magnetic disks.

424 CHAPTERTWELVE
tells the read circuit when to check foi a data bit. Re DMA basis NOW we w.ml to lake .1 (loser look at the
cording clock information along with data information controller itsell to show you the types ol signals it pro
not only makes it possible to accurate!) read dat duces and how il is pi Ogl i ed
different tracks, bui It also reduces the chances ol To start, take .1 look at the block diagram 0
error caused l>\ small changes In disk speed in figure 12-27. The signals along the left side ol the
A disadvantage ol standard F2F recording is that a diagram should be readily recognizable to you. The data
clock pulse and the data bit are required to represent bus lines, Kl). VVK. All. KIM I. and ( S are the standard
each data bit. Since bits can only be packed just so close peripheral interlace signals. The l)k(,). DA( k. and INT
together on a disk track without interfering with each signals aic used itn DMA transfei ol data to and from
other, this limits the amount ol data that can be stored the controller. To refresh your memory from < hapter I l.
on a track in this format. To double the amount of data hi i' 1 review ol how the DMA works. When .1 micro-
that we can store on a track we use the modified fre computer program
needs some data oil the disk, it
quency modulation or MI'M recording format shown as sends a series of command words to registers inside the
the second waveform in Figure 1 2-26. I he basic princi controller. The controller then proceeds to read the data
pie of this formal is that both clock pulses and "one" from the spec ifled track and sector on the disk. When
data pulses ale used to keep the phase locked loop and the controller reads the first byte ol data from a sectoi . it
read 1 ircuitry synchronized. A clock pulse is not put in sends a DMA request. DKQ. signal to the DMA control
unless data pulses do not happen to come often enough ler. The DMA controller sends a hold request signal to
in the data bytes to keep the phase-locked loop locked. the HOLD input of the CPU. The CPU floats its buses
Clock bits are put at the start of the bit cell and data bits and sends a hold acknowledge signal to the DMA con-
are put in the middle of the bit cell time. A clock bit will troller. The
DMA controller then sends out the first
only be put in. however, if the data bit in the previous transfer address on the bus and asserts the DACK input
cell was a 0, and the data bit in the current bit cell is also of the 8272 to tell it that the DMA transfer is underway.
a 0. Since this format has in all cases only one pulse per When the number of bytes specified in the DMA initiali-
bit cell, a bit cell can be hall as long, or in other words. zation been
has transferred, the DMA controller asserts
twice as many of them can be packed into a track. This the TERMINAL COUNT input of the 8272. This causes
is the way that double-density recording is achieved in the 8272 to assert its interrupt output signal, INT. The
the IBM PC and other common microcomputers. For a INT signal can be connected to a CPU or 8259A interrupt
5.25-in double-density recorded disk, data bits will be input to tell the CPU that the requested block of data has
read out at about 250.000 btts/s. Incidentally, a new been read in from the disk to a buffer in memory. The
disk recording technology called perpendicular or verti- process would proceed in a similar manner for a DMA
cal recording should allow 4 to 8 times as much data to write-to-disk operation.
be put on a given-size disk. With perpendicular record- Now let's work our way through the drive control sig-
ing the
tiny magnetic regions are oriented perpendicu- nals shownin the lower right corner of the 8272 block
lar to
the disk surface instead of parallel to it as they are diagram in Figure 12-27. Reading through our brief
for standard disks. descriptions of these signals should give you a better
Now that we have shown you how digital data is stored idea of what is involved in the interfacing to the disk
on floppy disks, we will show you the circuitry required drive hardware. Note the direction of the arrow on each
to interface a floppy disk drive to a microcomputer. of these signals.
The READY input signal from the disk drive will be
high if the drive is powered and ready to go. If, for exam-
A Floppy Disk Controller - the Intel 8272A ple, you
forget to close the disk drive door, the READY
signal will not be asserted.
As you can probably tell from the preceding discussion, The WRITE PROTECT/TWO SIDE signal indicates wheth-
writing data to a floppy disk and reading the data back er the write protect notch is covered when the drive is in
requires coordination at several levels. One level is the the read or write mode. When the drive is operating in
motor and head drive signals. Another level is the actual track-seek mode, this signal indicates whether the drive
writing and reading at the bit level. Still another level is is two-sided or one-sided.
interfacing with the rest of the circuitry of a microcom- The INDEX signal will be pulsed when the index hole
puter. Doing
all of this coordination is a full-time job, so
in the disk passes between the LED and phototransistor
we use a specially designed floppy disk controller to do
detector.
it. As our example device here we will use the Intel The FAULT/TRACK 0 signal indicates some disk drive
8272A controller, which is equivalent to the NEC problem condition during a read/write operation. Dur-
MPD765A controller used in the IBM PC. It is easier to ingtrack-seek
a operation this signal will be asserted
find data sheets and application notes for the 8272A. if when the head is over track 0, the outermost track on
you need further information. the disk.
The DRIVE SELECT output signals, DSO and DS1. from
8272 SIGNALS AND CIRCUIT CONNECTIONS
the controller are sent to an external decoder which uses
Figure 1 1 -3 showed you how an 8272A controller cm In- these signals to produce an enable signal for one to four
connected in an 8086-based microcomputer system. drives.
Also in Chapter 1 1 we discussed in detail how data can The MFM output signal will be asserted high if the
be transferred to and from a floppy disk controller on a controller is programmed for modified frequency modu-

MICROCOMPUTER SYSTEM PERIPHERALS 425


a DATA
BUS
/L-N REGISTERS

BUFFER
W
WR CLOCK
WR DATA
WR ENABLE
SERIAL PRE-SHIFTO

o INTERFACE
CONTROLLER
PRE-SHIFT 1

READ DATA
DATA WINDOW
VrriSYNC

%READY
%WRITE PROTECT/TWO SIDE
% INDEX
%FAULT/TRACK 0

DRIVE DRIVE SELECTO


a INTERFACE
CONTROLLER
DRIVE
MFM
SELECT
MODE
1

OUTPUT RW/SEEK
Wl PORT HEAD LOAD
HEAD SELECT
LOW CURRENT/DIRECTION
FAULT RESET/STEP

FIGURE 12-27 INTEL 8272A floppy disk controller block diagram.

lation. and low if the controller is programmed lor stan- cordingclock


that information is recorded on the track
dard frequency
modulation (FM). with the data information. We use the clock bits to tell
The RW/SEEK signal is used to tell the drive to operate us when to read the data bits. The Vc 0 SYNC signal from
in read-write mode or in traek-seek mode. Remember, the controller tells an external phase-locked loop circuit
some of the other controller signals have different mean- to synchronize its frequency with that of the clock
ings in
the read-write mode than they do in the seek pulses being read off the disk. I In the case of MFM re-
mode. cording,
datathe bits are also part of the signal the PLL
The HEAD LOAD signal is asserted by the controller to locks on). The output from the phase-locked loop cir-
tell the drive hardware to put the read/write head in eon- cuitry
a DATA
is WINDOW signal. This signal is sent to
tact with the disk. When interfacing to a double-sided the controller to tell it where to find the data pulses in
drive, the HEAD SELECT from the controller is used along the data stream coming in on the READ DATA input.
with this signal to indicate which of the two heads For writing pulses to the disk, the story is a little more
should be loaded. complex. External circuitry supplies a basic WR CLOCK
During write operations on inner tracks of the disk signal at a frequency of 500 kHz for FM and 1 MHz for
the LOW CURRENT/DIRECTION signal is asserted by the
controller. Because the bits are closer together on the
inner tracks, the write current must be reduced to pre-
vent recorded bits from splattering over each other. CLOCK AND WRITE
TIMING CIRCUIT WRITE
When executing a seek-track command this signal pin is PRECOMPENSATE
used to tell the drive whether to step outward toward the CIRCUIT
edge of the disk or inward toward the center.
The FAULT RESET/STEP output signal is used to reset
the fault Hip-flop after a fault has been corrected when
doing a read or write command. When the controller is WRITE DATA

carrying out a track-seek command, this pin is used to PRE-SHIFT0


output the pulses which step the head from track to PRE-SHIFT 1 DATA READ DATA
track. 8272A
SEPARATOR
VCOSYNC
Now that we have led you quickly through the drive
MO DATA
interface signals, let's take a look ai the H272A signals
DATA WINDOW
used to read and write the actual clock and data bits on
a track. To help with this. Figure 12-28 shows a block
diagram of the circuitry between these pins and the FIGURE 12-28 Block diagram of external circuitry used
read/write head. with Intel 8272A floppy disk controller for reading and
Remember from our discussion of FM and MFM re- writing serial data.

426 CHAPTER rWELVI


MFM recording. II u- 8272 outputs the serial strea III.in 111equal to data
dock bits and data bits that are to be written to the disk string from (l'1 01
mi us WR DATA pin. Dm inn •> vvrite operation the 8272 contn illei
asserts its WR EN \BI I signal to turn on the extei nal i ii s( AN It >\Y ( IR EQUAI Set flag it data string
cuitrj which actually sends this serial data to the read from disk sc< lor is less
write head. Now, data bits written in MEM on .1 disk will than or equal to data
tend to shift in position as they are readout A "one" bit, string from ( PI I or DMA
Ini example, will tend to shut inward an adjacent "zero" controller.
Int. This slnii could cause errors in readoul unless 11
were compensated for. Tin- PRI Mill I (land PRE-SHII I I Work mi; on 1 a sci us oi commands tor a disk controllei
signals iiiini the controller go to external circuitry which such as the 8272 on a bit by bit basis is quite tedious
shitts hits forward oi backward as they arc being wril and time-consuming. Fortunately, you usually don't
ten. The bits will then he in the correct position when have to do this, because in most systems, von can use
1 ead dill higher level procedures to tt.u\ from and write to a disk.
In the next section we show you some of the software
8272 COMMANDS used lo Interface to disk drives.
I he 8272 can execute 15 different commands. Each of
these commands is sent in the data register m the con-
Disk Drive Interface Software
troller
a as
series Ol bytes. Consult an 8272 data sheet to
find the formats lor these commands il you need them. There are several different software levels at which you
Aftei a command has been sent lo the 8272. it carries can interact with a disk drive. One level is directly at the
out the command, and returns the results to status reg- controller level. The next level up is at the BIOS level. A
isicrs in the 8272, and or to the data register in the still higher and easier-to-use level is at the disk operat-
8272. To give you an overview ol the commands you get ing system (DOS] level. Using the IBM PC as an example
to send to an 8272. we list them here with a short de- we will show you in the following sections how to inter-
scription
each.
for face yourprograms with a disk drive using the BIOS
approach and the DOS approach.
SPECIFY — Initialize head load time,
head step time, DMA/
non-DMA. BIOS Level Floppy Disk Interfacing
SENSE DRIVE STATUS — Return drive status
In previous discussions we have shown you how to use
information.
IBM BIOS procedures to interface with the keyboard,
SENSE INTERRUPT STATUS — Poll the 8272 interrupt the CRT. and a printer. BIOS procedures, remember,
signal. are called with the INT I type] instruction. Figure 12-29
SEEK — Position read/write head
shows the header for the BIOS INT 13H procedure
over specified track.
which allows you to interact with disk drives. To give
RECALIBRATE — Position head over track
you an idea of what is involved in using this procedure,
0.
read through the list of parameters you must pass to it
FORMAT TRACK — Write ID field, gaps, and
for different operations. As you can see from the header,
address marks on track.
when using this procedure, you have to specify the par-
Kl \l) DM \ — Load head, read
ticular track
and sector(s) that you want to read or
specified amount of data
write You have to set up a buffer in memory and pass a
from se< tor.
pointer to the start of the buffer. Also, you have to set up
READ DELETED DATA — Read data from sectors
a table in memory that contains the numbers of tracks
marked as deleted.
and sectors you have recorded data on. The point here is
WRITE DATA — Load head, write data to
that, yes, you can use this BIOS procedure to interact
specified sector. with a disk by loading registers with the indicated pa-
WRITE DELETED DATA —Write deleted data rametersexecuting
and the INT 13H instruction. How-
address mark in sector.
ever,use
to an old cliche, it is not a very user friendly
READ TRACK — Load head, read all
way to do it. An easier way to interface your programs
sectors on track.
with the disk drive is to use DOS procedures. Here's how
READ ID —Return first ID field
you do this.
found on track.
SCAN EQUAL — Compare sector of data
bytes read from disk Disk Operating System (DOS) Interfacing
with data bytes sent
from CPU or DMA
DISK OPERATING SYSTEM OVERVIEW
controller until strings
match. Set bit in status First of all. let's clarify some terms for you. An operating
register if match. system is simply a program or collection of programs
SCAN HIGH OR EQUAL — Set flag if data string which allows you to format disks, execute programs,
from disk sector greater create disk files, write data to files, read data from files,

MICROCOMPUTER SYSTEM PERIPHERALS 427


in ' IMZ K65 DO ANOTHER CYCLE
2408 Pi IP AX I'll i IVER CONTROL
2409 OUT KB_CTL AL l IUTPU1 III! ( ( INTROL
2410 IMP K27
2411
PI is I Mil I'M M M I'.RI 'I II'. I

Rl IS_( MM KSUM I'K'i II HEAR '.I - I.k'i IS-MI IDI II


Mm CX.8192 NUMBER i il B1 II % li i Mm
R( IS_I MM KSUM-CNT ENTR\ FOR OPTIONAL ROS TEST
XDR AL.AL
i 26
ADD Al I IS B>
INI PI H'.l li i NEXT BYTE
H if IP ADD ALL BYTES IN Rl IS Ml 'I" LI
i ik' M \l SLIM = U'
Rl
Rl ISJ MM KSUM ENDP

INT II
DISKETTE I/O
THIS INTERFAI I PRI IVIDES V I ESS U I IML 5 1/4" DISKETTE DRIVES
INPUT
IAHI - II RLSET DISKETTE SY5TEM
HARD REM I TO NEC, PREPARI I I IMMAND, RECALL REQUIRED
ON ALL DRIVES
IAHI = 1 READ THE STATUS Ol rHE SYSTEM INTO IALI
DISKETTE-STATUS FR< IM I AST OPERATION IS USED

REGISTERS FOR READAA'RITE/VERIFVFOk'MAI


(DL1— DRIVE NUMBER 10-3 ALLOWED VALUE CHECKED)
l 18 IDH1 -HEAD NUMBER (0-1 ALLOWED NOT VALUE CHECKEDl
24 19 ii Hi IKAl. k NUMBER (0-39, NOT VALUE CHECKEDl
2440 ICLI— SECTOR NUMBER (1-8, Nol \ \l I I i MM H I i
2441 NOT nslli li ik M IRMATI
'II IALI— NUMBER OF SEI H IRS MAX 8, NOT VALUE CHECKED, NOT USED
1443 li ik M IRMAT)
111 IES BX)— ADDRES5 OF BUFFER ( NOT REQUIRED Fl IR VERIFY

(AHl 2 RE \M Mil I IESIRI I ' SEI H IRS INK ' MEM( IR\
(AH) ', WRITE THE DESIRED SECTORS FROM MEMORY
'l 18 IAHI = 4 VERIFY THE DESIRET) SEI U IRS
%; 19 (AHl - ". Fl IRMAT I Ml DESIRED FRA( k
'I ,n FOR TFII M IRMAT I IPERATION, THE BUFFER POINTER IES BXI
24 r, I MUST POINI in nil l oil M 111 IN I IF DESIRED ADDRESS FIELDS
' I , ' FOR THE TRA( k I Al H FIELD IS COMPOSED OF 4 BYTES,
I . I tCH.R.Nl, Wlllk'l i TRAI k NUMBER, H = HEAD NUMBER,
1,1 R - SE( Ti )R NUMBER, N = NUMBER OF BYTES PER SEI Tl IR
I , [00 128 "I 256,02 512,03 1024) THERE MUST BE ONE
' I 16 ENTRY Fl IR EVERY SE( 11 IR ON Flit TRAI k THIS INK IRMATION
2457 IS USED Id I INI l nil REQUESTED SM Ink DURING READ/WRITE
\i i l SS

DATA Y XJ.I Xl'.l I 1 HSK_PI UNTER


in IUBLI Wl IRD POINTER TO THE CURRENT SI 1 Ol Ml H I II PARAMETERS
i ii rpi i
AM = STATUS OF OPERATII >'.
si VTI S BITS \RI DEFINED IN llll EQI Ml '• M IR
DISKETTE-STATUS VARIABLI IN II II DATA SEGMENT OF THIS
h, i, Ml il lUI I
2467 i i n sui i. ESSFI I i 'I'l K XI H IN \M hi IN Rl II I",
li,:. CY = 1 FAILED I 'I'l K \IH IN (AH HAS ERROR Rl I ON
.'If,'' FOR READ/WRITI VERII i
'I i DS.BX DX.I H.I I PRESERVED
24"] AL = NUMBIP i 'I SEI li IRS \l TUALLY READ
AL MAY NOT FtL I ORREI 1 IF TIME ( IUT ERROR I II I MRS
Noll IF AN ERROR IS REPORTED BY THE DISKETTE CODI llll
M'PRi IPRIATE \l TION IS |i i RESET llll DISKETTE, IlltN RETRY
Flit i IPERATION, ON READ Al CESSES, NO Ml ITOR START DELA1
IS lAkEN, SO THAT THREE RETRII KRE REQUIRED ON READ5
TO ENSURE THAI llll PRI 'HUM IS Ni H DUE H I Ml ITI Ik
SI \kl UP

A'.SMMI I s I I II It, I is DMA tS DATA


i IRS ''II
MISMIIIJO PROC FAR
STI , INTERRUPTS BA( k I II

FIGURE 12-29 Header lor IBM BIOS INT I3H procedure for interfacing with
floppy disk drives.

communicate with system peripherals such as modems principle is the same as having a named file folder in an
and printers, etc. As we will discuss in Chapter 14, some office file cabinet.
operating systems allow several users to share a CPU on Using DOS to format disks, write files, and read files
a time-share basis. The term disk operating system or relieves you of the burden of keeping track of the indi-
DOS means that the operating system resides on a disk vidual tracks
and sectors. DOS does all of this for you.
and is loaded into memory and executed when you turn Now, before we show you how to use DOS procedure
nil or reset the system. The term file in this ease refers calls, we will briefly show you how DOS keeps track of
In .1 collection of related data accessible by name. The where it puts everything.

428 CHAPTER TWELVE


directory can contain the names ol program 01 dal
Bool rec ord variable size
tiles 1he root directory can .1K0 have the names ol
I nst copy el file allot ation subdlrei torles ol files Each subdirectory can also refei
table variable size directly to program <>i data files, oi it can refei to lower
subdirectories. I he point here is that tins structure al-
Sec ond t op\ cii iilf alloc ation lows you
10 group similar files together, and in avoid
table variable size going through a long list of filenames to find a particular
Knot direi ton variable size tile you need. To gel to a tile in .1 lower level direi tory
von simply specify the path to that file. 1he path is the
Data .in'. i series ol directory names that von go through to tin to
f- .... -I
that hie.
FIGURI 12-50 IBM PC DOS format tor floppy disks.
USING IBM PC DOS (AILS IN YOUR
PROGRAMS

Figure 12 -:u> shows the "housekeeping" Information As we said previously, DOS is largely a collection ol pro
that IBM PC DOS puis on the first track ol a disk to do cedures which von can call from your programs, similar
this, l'hc basic structure for these parts is put on a disk to the way you call BIOS procedures. Many disk operal
when it is formatted with a DOS format command. As ing systems and earlier versions ol PC Dos require you
tiles are created and written to the disk, the relevant to construct a.file control blockor FCB in order to access
information for each file is put in the directory and ta- disk files from your programs. The format of a file con
bles. trol block differs from system to system, but basically
The boot record in the first sector of the first track the FCB must contain among other things, the name ol
indicates whether the disk contains the DOS files the file, the length of the file, the file attribute, and in-
needed to load DOS into RAM and run it. Loading DOS formationthe
aboutblocks in the file. Version 2.0 and
and running it is commonly referred to as "booting" the later versions of PC DOS simplify calling DOS file proce-
system. duresletting
by you refer to a file with a single 16-bit
The directory on the disk contains a 32-byte entry for number. This number is called the file handle or token.
each file. Let's take a quick look at the use of these bytes You simply put the file handle for a file you want to ac-
to get an overview of the information stored for each file. cessainregister, and call the DOS procedure. DOS then
constructs the FCB needed to access the file. The ques-
Byte number tion thatmay occur to you at this point is. "How do I
(dec 1111.1l
know what the file handle is for a file I want to access on
0-7 Filename
a disk?" The answer is that to get the file handle for a
8-10 Filename extension
disk file you simply call a DOS procedure which returns
11 File attribute
the file handle in a register. You can then pass the file
01H - read only handle to the procedure that you want to call to access
02H - hidden file
the file. PC DOS treats external devices such as printers,
04H - system tile
the keyboard, and the CRT as files for read and write
08H - volume label in first II bytes, not
operations. These devices are assigned fixed file handles
filename
by DOS as follows: 0000 - keyboard. 0001 - CRT.
10H - tile is a subdirectory of files in lower
0002 - error output to CRT. 0003 - serial port.
level of hierarchical file tree
0004 - printer. The point here is that file handles make
20H - file has been written to and closed
it easy for you to access files. There are more examples of
12-21 Reserved
calling DOS procedures in Figure 13-24. but here are a
22-23 Time the file was created or last updated
few to get you started.
24-25 Date the file was created or last updated
Each DOS function (procedure) has an identification
26-27 Starting cluster number - DOS allocates space
number. To call a DOS function you put the function
for files in clusters of one or more adjacent
number in the AH register, put any parameters required
sectors in size.
by the procedure in other registers, and then execute
28-31 Size of the file in bytes
the I NT 21 H instruction. For example, DOS function call
DOS uses the first/He allocation table or FAT to keep 40H can be used to print a string. To use this procedure
track of which clusters on a disk are currently being set up the registers as follows:
used for each file, and which clusters are still available.
1. Load the function number, 40H, into the AH regis-
The FAT is part of the link between a filename and the
ter.
actual track and sector numbers where that file is
stored. The second FAT is simply a copy of the first, in- 2. Load the DS register with the segment base of the
cluded
backup
lor purposes. segment which contains the string.
Most current microcomputer operating systems. IBM
3. Load the DX register with the offset of the start of
PC DOS 2. 1 and later versions for example, allow you to
the string.
set up a hierarchical/He structure. In this structure you
have one main or root directory which resides in the di- 4. Load the CX register with the number of bytes to
rectory
the ofdisk as shown in Figure 12-30. This root write.

MICROCOMPUTER SYSTEM PERIPHERAtS 429


5. Load the BX register with the fixed file handle for 3DH. For this call DS:DX must point to the start of an
the printer. 0004H. ASC1IZ string which contains the disk drive number,
the path, and the filename. An ASCIIZ string is a string
Then, to call the DOS procedure, execute the INT 21 H of ASCII characters which has a byte of of all O's as its
instruction. Note that the DOS function allows you to last byte. Also AL must contain an access code which
send an entire string to the printer, rather than just a indicates the type of operation that you want to perform
single character at a time as the BIOS INT 17H does. on the file. Use an access code of 00 for read only. 01 for
As another example, the DOS OAH function will read write only, and 02 for read and write. Again, to actually
in a string from the keyboard and put the string in a call the function, you load 3DH into AH and execute the
buffer pointed to by DS:DX. Characters will also be dis- INT 21 H instruction. The handle for the opened file is
played
theon CRT as they are entered on the keyboard. returned in the AX register. The first part of Figure
The function terminates when a carriage return is en- 12-31 shows how these pieces are put together.
tered.use
To this function, first set up a buffer in the To read a file we use function call 3FH. For this call BX
data segment with the DB directive. The first byte of the must contain the file handle and CX the number of
buffer must contain the maximum number of bytes the bytes to read from the file. DS:DX must point to the
buffer can hold. The OAH call will return the actual buffer location in RAM that the data from the file will be
number of characters read in the second byte. The func- read into. To do the actual call we load 3FH into AH and
tion does
not require you to pass it a file handle, because do an INT 21 H instruction. After the file is read, AX con-
the file handle is implied in the function. tains the
number of bytes actually read from the file.
To leave a program and return to the DOS command To close the file we load function number 3EH into
level, you can use the DOS 4AH call. Load AL with 00. AH. load the file handle into BX, and execute the I NT 21 H
AH with 4CH, and execute the INT 21 H instruction. instruction. The last half of Figure 12-31 shows the in-
As a final example here, we will show you how DOS structions
canyouuse to read and close a file. Watch for
calls can be used to open a file, read data from a file into some more examples in Figure 13-24. Consult the IBM
a buffer in memory, and close the file. Opening a file DOS Technical Reference Manual for the details of all of
means copying the file parameters from the directory to the available function calls.
a file control block in memory and marking the file as
RAM DISKS
open. Closing a file means updating the directory infor-
mation
thefor file and marking the file closed. To open a Currently available for most microcomputers are pro-
file and get the file handle we use DOS function call grams which
allow you to set aside an area of RAM in

8086 Program fragment


ABSTRACT: This code shows how to use DOS functions to
open a file, read the file contents into a buffer
in memory, and close the file

point at start of buffer containing file name


MOV DX , OFFSET FILE_NAME and move pointer over
ADD DX , 02H string length bytes
MOV AL, 00 open file for read
MOV AH, 3DH and get file handle
INT 21H
MOV BX , AX save file handle in BX
PUSH BX and push for future use
MOV CX, 20^+8 set up maximum read
point at memory buffer reserved for disk file contents
MOV DX, OFFSET FILE_BUF
MOV AH, 3FH read disk file
INT 21H
POP BX get back file handle for close
PUSH AX save file length returned by
3FH func t ion call
MOV AH, 3EH c lose disk file
INT 21H
use the file now stored in memory

FIGURE 12-31 Instruction sequence to open a disk file and get file handle,
read file contents to a buffer in memory, and close file using IBM PC DOS
function calls.

430 CHAPTER TWELVE


sik'Ii a way that II appears to Dos as stmplj another Mbytes pei 8 in disk. 30 to 50 Mbytes per 10 In disk.
disk drive. In an 1HM PC tti.it has two actual drives. A ,i\u\ 1 100 Mbytes pei 14 in disk.
and B:, the i iisi ailed RAM disk becomes C:. You can cop) Rigid disks are rotated at 1000 to 3600 rpm I Ins
iiles id and from this RAM disk by name |us1 as you high speed not only makes il possible to lead and write
would for any other drive. Here's the poinl ol this. Sup data faster, it also creates a thin cushion ol ail thai
pose von are using Wordstai to edil program tiles Musi floats the read-write head 10/xin oft i he disk. Unless the
of the tune when you execute a Wordstai command the ii< ad i rashes, it never touches the recorded area ol the
system must go and gel the code for thai command from disk, so wear is minimized. When data is not her
the Wordstar system disk and load II Into memory before or written, the head is retracted to a parking zone where
it can execute the command. This makes \iiu spend a lot no data is recorded. Hard disks musl be kepi in a dust-
of time waiting. It yon load all ot the Wordstai tiles into free environment, because the diameter of dust and
the RAM disk, they can then be accessed much faster smoke particles may be 10 limes the distance the he, id
because there is no mechanical access time. The advan floats oil the disk. Il dust does get into a hard disk sys
tage ol configuring the RAM as a disk drive is thai the tem, the result will be the same as that which occurs
software can be accessed just as it it were on a disk when a plane does not fly high enough to get over some
mountains. The head will crash and perhaps destroy the
data stored on the disk
MAGNETIC HARD DISK DATA STORAGE
Hard disk drives are often referred to as Winchesters.
The floppy disks that we discussed in the previous sec- Legend has it that the name came from an early IBM
tion have
the advantage that they are relatively inexpen- dual-drive unit with a planned storage of 30 Mbytes
sive and
removable. The distance between tracks, and drive. The 30-30 configuration apparently reminded
therefore the amount of data that can be stored on someone ol the famous rifle, and the name stuck.
floppy disks, is limited to a large extent by the flexibility In some hard disk drives the read-write heads are po-
ut the disks. The rate at which data can be read oft a sitionedthe
over desired track by a stepper motor and a
disk is limited by the fact that a floppy disk can only be band actuator as we described for the floppy disk drive.
rotated at 300 or 360 rpm. To solve these problems, we Other hard disk drives use a linear voice coil mecha-
use a hard disk system like the one in Figure 12-32. nismposition
to the read-write heads. This mechanism
The disks in a hard disk system are made of a metal uses feedback control, such as that we described in
alloy, coated on both sides with a magnetic material. Chapter 10, to control the position of what is essentially
Hard disks are more dimensionally stable. This means a linear motor. The feedback system adjusts the posi-
that they can be spun at higher speed, and that tracks tionthe
of head over the desired track until the strength
and the bits on the tracks can be put closer together. In of the read signal is a maximum.
most cases the hard disks are permanently fastened in Most hard disk drives record data bits on a disk track
the drive mechanism and sealed in a dust-free package, using the MFM method we described in the floppy disk
but some systems do have removable enclosed disks. section of this chapter. As with floppy disks, there is no
Common hard disk sizes are 3.5. 5.25. 8. 10.5. 14. and real standard for the format in which the data is re-
20 in. To increase the amount of storage per drive, sev- corded. Most
systems format a track in a manner simi-
eral disksmay be stacked with spacers between. A read- lar tothat shown for floppy disks in Figure 12-25. The
write head is used for each disk surface. Current tech- hard disk drive unit used in the IBM PC XT. for example,
nology allows
3 to 10 Mbytes per 5.25-in disk. 5 to 20 uses two double-sided hard disks with 306 tracks on
each disk surface. On disk drives with more than one
recording surface, tracks are often referred to as cylin-
ders, because if you mentally connect same numbered
tracks on the two sides of a disk or on different disks.
the result is a cylinder. The cylinder number then is the
same as the track number. On the PC XT hard disk.
each track has 17 sectors with 512 bytes in each sector.
This adds up to about 10 Mbytes of data storage. Data is
read out at 5 Mbits/s, which is about 10 times faster
than the readout rate for double-density floppy disks.
To interface a hard disk drive to a microcomputer sys-
tem we
use a dedicated controller device such as the
Intel 82064. which operates similarly to the 8272 floppy-
disk controller we described previously in this chapter.
An added feature of this controller is the ability to record
either CRC words or error-correcting code words with
each data sector.
From a software standpoint, writing files to and read-
ing filesfrom a hard disk is very similar to the same
operations for a floppy disk. To DOS the hard disk ap-
pears for
the most part as simply another drive. One
FIGURE 12-32 Multiple-platter hard disk memory system. difference is that a hard disk is often divided into parti-

M1CROCOMPUTER SYSTEM PERIPHERAfS 431


tions so that groups of programs can be separated from some other systems record data on a single spiral track
each other. Partitions function essentially as separate as a phonograph record does. A linear voice coil mecha-
disks. An operating system loaded from one partition, nism with
feedback control is used to precisely position
for example, cannot accidentally destruct another oper- the read head over a desired track or section of the
ating system
stored in another partition. The only way track. The head positioning must be very precise, be-
to get to the other partition in many systems is to reboot causetracks
the on an optical disk are so close together.
the system into that partition. The 24-/Liin-wide tracks on the Optimem 1000 disks, for
Another term encountered in connection with hard example, are only 70 juin between centers. This spacing
disks is file server. A file server is a hard disk system allows 40,000 tracks to be put on the disk. For the Op-
which has its own CPU and operating system. The unit timem 1000
the average access time to a track is 150
is usually a major part of a computer network. The func- ms. and data is read out at 5 Mbits/s. The disk sizes
tionthe
of file server is to manage the access to and use currently available in different systems are 4.72 (the
of files stored on the disk by other systems on the net- compact audio disk size), 5.25. 12, and 14 in. Optical
work. disk systems are available in three basic types: read
To prevent data loss in the event of a head crash, hard only, write once/read, and read/write.
disk files are backed up on some other medium such as Read only systems allow only prerecorded disks to be
floppy disks or magnetic tape. The difficulty with using read out. A disk which can only be read from is often
floppy disks for backup is the number of disks required. referred to as an optical ROM or OROM. Examples of
Backing up a 10 Mbyte hard disk with 360 Kbyte this type are the 4.7-in audio compact disks.
floppies requires 30 disks and considerable time shov- Write-once/read systems allow you to write data to a

ing disksin and out. Many systems now use a high- disk, but once the data is written, it cannot be erased or

speed magnetictape system for backup. A typical changed. Once data is written, you can read it out as

streaming tape system, as these high-speed systems are many times as you want. Write-once systems are some-

often called, can dump or load the entire contents of a times referred to by the name DRAW, which stands for

10 Mbyte hard disk to a single tape in a few minutes. direct read after write.

The next technology we discuss here, optical disks, can Read/write optical disk systems, as the name implies,
store even larger amounts of data on a single drive unit allow you to erase recorded data and write new data on a
than magnetic hard disks can. disk. The recording materials and the recording meth-
ods are
different for these different types of systems.
Disks used for read-only and write-once/read systems
OPTICAL DISK DATA STORAGE are coated with a substance which will be altered when a
high-intensity laser beam is focused on it with a lens.
Optical disks are probably familiar to you from their use The principle here is similar to using a magnifying glass
as laser video disks and compact audio disks. Higher to burn holes in paper as you may have done in your
quality versions of the same type of disk can be used to earlier days. In some systems the focused laser light ac-
store very large quantities of digital data for computers. tually produces tiny pits along a track to represent l's.
One currently available unit, the Shugart Optimem In other systems a special metal coating is applied to the
1000. for example, stores up to a total of 1 gigabyte disk over a plastic polymer layer. When the laser beam is
( 1000 Mbytes! of data on one side of a single t2-in disk. focused on a spot on the metal, heat is transferred to the
This amount of storage corresponds to about 400.000 polymer, causing it to give off a gas. The gas given off
pages of text. In addition to their ability to store large produces a microscopic bubble at that spot on the thin
amounts of data, optical disks have the advantages that metal coating to represent a stored 1. Both of these re-
they are relatively inexpensive, immune to dust, and in cording mechanisms are irreversible, so once written,
most cases, removable. Also, since data is written on the the data can only be read. Data can be read from this
disk and read off the disk with the light from a tiny laser type of disk using the same laser diode used for record-
diode, the read/write head does not have to touch the ing, but
at reduced power (a system might, for example,
disk. The laser head is held in position above the disk, use 25 mW for writing, but only 5 mW for reading). In
so there is no disk wear, and the head cannot crash and some systems, such as the one in Figure 12-33. a sepa-
destroy the recorded data as it can with magnetic hard rate laser
is used for reading. The laser beam is focused
disks. on the track and a photodiode used to detect the beam
The actual drive and head positioning mechanisms reflected from the data track. A pit or bubble on the
for optical disk drives are very similar to those for mag- track will spread the laser beam light out so that very
netic hard
disk drives. A feedback system is used to pre- little of it reaches the photodiode. A spot on the track
cisely controlthe speed of the motor which rotates the with no pit or bubble will reflect light to the photodiode.
disk. Some units spin the disk at a constant speed of Read-only and write-once systems are less expensive
700 to 1200 rpm. Other systems such as those based on than read/write systems, and for many data storage ap-
the compact disk (CD) audio format adjust the rota- plications
inability
the to erase and rerecord is not a
tional speed
of the disk so that the track passes under major disadvantage.
the head with a constant linear velocity. In this case the For the most common read/write optical disk system
disk is rotated more slowly when outer tracks are read. the disks are coated with an exotic metal alloy which has
Some optical disk systems record data in concentric the required magnetic properties. The read/write head
tracks as magnetic disks do. The CD disk systems and in this type of system has a laser diode and a coil of wire.

432 CHAPTFR TWEtVE


DIODI
WRI 1 1 PROPRIETARY
LASER OPTICS

OBJI CTIVE I I NS

f
HELIUM NEON
READ LASER

FIGURE 12-33 Read/write mechanism for optical disks.

BLOCK BLOCK ADDRESS AREA

A current is passed through the coil to produce a mag- FIRST BLOCK 00 MIN, 00 SEC,
00 BLOCK PRE-
netic field
perpendicular to the disk. At room tempera-
GAP
ture the
applied vertical magnetic field is not strong 00 MIN. 01 SEC, AREA
enough to change the horizontal magnetization present 74 BLOCK

on the disk. To record a 1 at a spot in a data track, a USER'S FIRST 00 MIN, 02 SEC,
BLOCK 00 BLOCK
pulse of light from the laser diode is used to heat up that USER
AREA
spot. Heating the spot makes it possible for the applied USER'S LAST 60 MIN. 01 SEC.
magnetic field to flip the magnetic domains around at BLOCK (MAX ) 74 BLOCK

that spot and create a tiny vertical magnet. To read data 60 MIN, 02 SEC,
00 BLOCK POST-
from the disk, polarized laser light is focused on the
iAP
track. When the polarized light reflects from one of the LAST BLOCK 60 MIN, 03 SEC, AREA

tiny vertical magnets representing a 1, its plane of polar- (MAX) n hi och

ization
rotated
is a few degrees. Special optical circuitry
can detect this shift and convert the reflections from a
data track to a data stream of l's and O's. A bit is erased HEADER ERROR
by turning off the vertical magnetic field and heating the BLOCK
CORRECTION CODE
ERROR
(ECO
spot corresponding to that bit with the laser. When ADDRESS USER DETECTION
SYNC %¡ SPACE
heated with no field present, the magnetism of the spot Q DATA CODE
o
5 s (EDCI
will flip around in line with the horizontal field on the z
u
5 P-PARITY Q-PARITY

disk. Other techniques for producing read/write disks 5


are now being researched intensely because of the
promise this form of data storage has.
ONE BLOCK (TOTAL) 2352 BYTES
Data is stored on optical disks in several different for-
SYNC 12 BYTES
mats. Figure12-34 shows the format in which digital
HEADER 4 BYTES
data is stored on the 4.7-in audio compact disks. USER DATA 2 KBYTES (2048 BYTES)
EDC, 4 BYTES
As shown in Figure 12-34a. data is stored serially in
SPACE 8 BYTES
one long spiral track, starting near the center of the i C

disk. The track is divided into blocks, each containing 2 P-PARITY 172 BYTES (REED SOLOMON CODE)
Q-PARITY 104 BYTES (REED SOLOMON CODE)
Kbytes of actual data. Figure 12-34b shows the format
USER DATA
for each block. Note that a considerable number of bytes
1 BLOCK = 2 KBYTES (2048 BYTES)
in each block are used for header, synchronization, and
1 SECOND = 75 BLOCKS = 150 KBYTES
error-detecting/correcting codes. Extensive error detec- 1 MINUTE = 60 SECONDS = 4500 BLOCKS

tion/correction
necessary is to bring the error rate down 1 DISK 1 HOUR - 60 MINUTES = 270 K BLOCKS

to that of magnetic disks. The position of each block on AVERAGE DATA TRANSFER RATE (SEQUENTIAL) - 150 KBYTES/SEC

the track is identified with coordinates of minutes, sec-


onds, and
block number. As shown in Figure 12-34a, a
second represents 75 blocks numbered 0-74. A minute FIGURE 12-34 Industry-wide data structure for audio
represents 60 seconds, or a total of 4500 blocks. The compact disk (CD) optical disks, (a) Disk format, (b)
entire disk represents one hour or 270K blocks. Note Track format. {Electronic Engineering Times, March 25,
that although data can be read out from the disk at 150 1985)

MICROCOMPUTER SYSTEM PERIPHERALS 433


Kbytes/s (about 3 times the rate for floppy disks), the
PAPER
disk contains so much data that it takes an hour to read
out all of the data on the disk. Also note that a large area
RIBBON
at the start of the track and a large area at the end of the
track are used as gaps. In all. about half of the total area CHARACTERS
EMBOSSED
on an optical disk is used for synchronization, identifi-
ON TIP OF ARM
cation, error
and correction. This is not a big drawback
because of the immense amount of data that can be
stored on the disk.
There are currently available several "jukebox" optical
disk systems, which contain up to 256 disks. Typically
it takes only a lew seconds to access a disk. The potenti-
ally low
cost of a few cents per megabyte and the hun-
PRINTER
dreds
gigabytes
of of data storage possible for optical MECHANISM
disk systems may change the whole way our society MOVEMENT

transfers and processes information. The contents of a


sizable library, for example, can be stored on a few
disks. Likewise, the entire financial records of a large-
TOTAL OF 96
company may be able to be kept on a single disk. "Ex- CHARACTER
pert" systems
for medical diagnosis or legal defense de- ARMS

velopment
use acanmassive data base stored on disk to
do a more thorough analysis. Engineering workstations
can use optical disks to store drawings, graphics, or FIGURE 12-36 Daisy-wheel printer mechanism. (Data
IC-mask layouts. The point here is that optical disks Products Corporation)
bring directly to your desktop computer a massive data
base that previously was only available through a link to
the operation and tradeoffs of some of the common
large mainframe computers, or in many cases was not
printer mechanisms. We start with those that mechani-
available at all. Perhaps the distribution of data made
cally hit
the paper in some way.
possible by optical disks will reduce the need for print-
ers whichwe discuss in the next section.
Formed Character Impact Printers
PRINTER MECHANISMS This category of printers function in the same way as a
typewriter. In fact the unofficial standard of comparison
Manv different mechanisms and techniques are used to for print quality is the print produced by the "spinning
produce printouts or "hard" copies of programs and golf ball" IBM Selectric typewriter.
data. This section is intended to give you an overview of
IBM SELECTRIC MECHANISM

To refresh your memory. Figure 12-35 shows how this


works. The entire character set is present as raised type
around a sphere. The bottom of the sphere is connected
to the drive mechanism. By shifting the ball up or down,
rotating it. and tilting it. the character to be printed can
be precisely positioned over the desired spot on the
paper. When the ball is hit against the ribbon, the letter
is printed on the paper. The head is moved across the
paper to print a string of characters. Selectric typewrit-
ers canbe interfaced to computers to do printouts.
The advantages of the Selectric mechanism are the
excellent print quality and the fact that the font can be
changed by simply changing the sphere. Font is the
name used to refer to the character set of a printer. The
disadvantages of this mechanism are: it is mechanically
SPHERICAL complicated, noisy, and can only print about 14 charac-
"GOLF-BALL' ters per
second (cps).
ELEMENT
DAISY-WHEEL PRINTERS
EMBOSSED
CHARACTERS Figure 12-36 shows a drawing of a daisy-wheel printer
mechanism. Here the raised letters are attached at the
ends of spokes of a wheel. To print a letter the wheel is
PRINTER MECHANISM MOVEMENT rotated until the desired letter is in position over the
FIGURE 12-55 IBM Selectrk printer mechanism. (Data paper. A solenoid-driven hammer then hits the "petal"
Products ( orporation) against the ribbon to print the letter.

434 CHAPTER TWELVE


I In- advantages ol the daisy-wheel mechanism are
high prinl quality, Interchangeable fonts, and prinl
speed up to 55 cps Prinl quality is nol quite .is good .is
thai produced l>v the spinning goll ball

DRUM, BAND, AND CHAIN PRINTERS


A daisy wheel produc es good quality print, but for mas-
sive data
output from large mini and mainframe rum
puters. 55 cps is nol nearly fasl enough. For these sys-
tems drum,
band, or chain type line printers are used
Figure 12 37 shows a diagram ol how .i drum type is
constructed A rapidly spinning drum has ,i complete
raised charactei sel constructed around the drum for
each eh. u, icici position across the paper, lb prinl char
acters, magnetically driven hammers in each charactei
position hit the paper and ribbon againsl the spinning
drum. An entire line of characters can be printed during
each rotation "I the drum. Some drum printers ran
print 2000 Inns min. It you assume 80 characters per
DUAL COLUMN BIDIRECTIONAL
line, tins corresponds to 2700 cps. I lowevei . pi ml lines MATRIX PRINTING HEAD
may be wavy, fonts are not easily changed, and the noise
level is high. FIGURE 12-38 Impact dot-matrix printer mechanism.
In a band pi intei several raised character sets are con- (Data Products Corporation)
structed
a metal
on hand which is rapidly pulled across
a line position behind the paper. Each character posi-
font is changeable, but they are noisy and the prinl
tion has
a magnetically driven hammer such as those
shown for the drum printer. When the desired character mechanism tends to wear out.
is under a hammer, the hammer is tired. This hits the
ribbon and paper against the letter on the band and Dot-Matrix Impact Print Mechanisms
prints the character. Some band printers can print up Figure 12-38 shows an impact-type dot-matrix print
to 2000 lines/min. Print quality is acceptable, louts are head. Characters are printed as a matrix of dots. Thin
easily changed, and the noise level is high. print wires driven by solenoids at the rear of the print
Chain printers operate like band printers, except that
head hit the ribbon against the paper to produce dots.
the character sets are held in a metal or rubber chain
The print wires are arranged in a vertical column so that
and rotated across the paper along a print line. Another
characters are printed out one dot column at a time as
variation of this type of printer is the lidin printer the print head is moved across a line. Early dot-matrix
which rotates metal slugs with characters on them
print heads had only seven print wires, so print quality
around in a track across the paper. These mechanisms
of these units was not too good. Currently available
also produce print speeds up to 2000 lines/min and the
dot-matrix printers use 9, 14. 18, or even 24 print wires
in the print head. Using a large number of print wires
64 CHARACTERS AROUND
and/or printing a line twice with the dots lor the second
PERIMETER OF DRUM
printing offset slightly from those- of the first, produces
CHARACTERS
ACROSS DRUM
print that is difficult to tell from that of a Selectric or
daisy wheel.
Unlike the formed character printers, dot-matrix
printers can also print graphics. To do this the dot pat-
tern for
each column of dots is sent out to the print head
solenoids as the print head is moved across the paper.
The principle is similar to the way we produce bit-
mapped raster
graphics on a CRT screen. By using dif-
^CHARACTER ferent color
ribbons and making several passes across a
DRUM
line, some dot-matrix impact printers allow you to print
color graphics. Most dot-matrix printers now contain
one or more microprocessors to control all of this.
Print speeds for dot-matrix impact printers range up
to 350 cps. Some units allow you to use a low-resolution
mode of 200 cps for rough drafts, a medium resolution
mode of 100 cps lor finish copy, or 50 cps for near-letter-
quality printing. A big advantage of dot-matrix impact
FIGURE 12-37 Drum printer mechanism. (Data Products printers is their ability to change fonts or print graphics
Corporation) under program control.

MICROCOMPUTER SYSTEM PERIPHERALS 435


Dot-Matrix Thermal Print Mechanisms
Most thermal printers require paper which has a special
heat-sensitive coating. When a spot on this special
paper is heated, the spot turns dark. Characters or CLEANING UNIT

graphics are printed with a matrix of dots. There are two


PRE-CHARGING
main print head shapes for producing the dots. For one ELECTRODE
of these the print head consists of a 5 by 7 or 7 by 9
SCAN PATH OF
matrix of tiny heating elements. To print a character the
LIGHT BEAM ON
head is moved to a character position and the dot-sized INTERMEDIATE
heating elements for the desired character turned on. SURFACE

After a short time the heating elements are turned off DEVELOPER UNIT

and the head is moved to the next character position.


Printing then is done one complete character at a time.
The second print head configuration for thermal
MULTIPLE MIRRORS
dot-matrix printers has the heating elements along a MOUNTED ON
ROTATING DRUM
metal bar which extends across the entire width of the
paper. There is a heating element for each dot position LIGHT BEAM MODULATOR
(CONTROLLED BY
on a print line, so this type can print an entire line of
CHARACTER GENERATOR
dots at a time. The metal bar removes excess heat. Char-
PATH OF LIGHT
acters graphics
and are printed by stepping the paper
BEAM FROM LASER
through the printer one dot line at a time. A few thermal
printers can print up to 400 lines/min. FIGURE 12-39 Laser printer mechanism. (Data Products
Some of the newer thermal printers have the heat- Corporation)
sensitive material on a ribbon instead of on the paper.
When a spot on the ribbon is heated, a dot of ink is
transferred to the paper. This approach makes it possi- producing an image on the photosensitive drum is with
ble to
use standard paper, and by switching ribbons, to a laser. Turning a laser on and off as it is swept back and
print color graphics as well as text. forth across the drum produces an image in about the
The main advantage of thermal printers is their low same way that an image is produced on a raster scan
noise. Their main disadvantages are: the special paper CRT. Figure 12-39 shows a diagram of how this is done.
or ribbon is expensive, printing carbon copies is not The rotating mirror sweeps the laser beam across the
possible, and most thermal printers with good print rotating drum. A modulator controlled by a microcom-
quality are slow. puter turns
the laser beam on or off to produce dots.
Alter the image is inked and transferred to the paper,
the drum is cleaned and is ready for the next page.
Spark Gap Printers An alternative to the photosensitive drum is a mag-
netically sensitive
drum used in some units. An image is
These printers use a special paper that looks and feels
written on this magnetic drum in the same way that
somewhat like aluminum foil. When a spot on the paper
data is recorded on magnetic disks. Magnetized ink par-
is "zapped" with a high voltage, the outer coating at that
ticles then
are applied to the drum, transferred to the
point is burned off. exposing a dark layer underneath.
paper, and fused.
Characters are printed as a matrix of dots. These print-
Laser and other xerographic printers have the advan-
ers are
often used to print out movie theater tickets be-
tages
very
of high print quality (text and graphics can
cause they
can print out as many as 2000 cps. Most of
easily be printed on the same page), very high print
the disadvantages relate to the paper which is expen-
speeds (up to 20,000 lines/mini, ability to use standard
sive, difficult
to handle, not very durable, and does not
paper, and relatively quiet operation. They have the dis-
produce very good print quality.
advantages
the copies
that "look like Xerox copies." the
machines are very expensive, and the machines require
a lot of maintenance.
Laser and Other Xerographic Printers
These printers operate on the same principle as most
office copy machines, such as Xerox machines. The
basic approach is to first form an image of the page that Ink-Jet Printers
is to be printed on a photosensitive drum in the ma- Still another type of printer that uses a dot-matrix ap-
chine. Powdered
ink, or "toner," is then applied to the proach
produce
to text and graphics is the ink jet. Early
image on the drum. Next the image is electrostatically ink-jet printers used a pump and a tiny nozzle to send
transferred from the drum to a sheet of paper. Finally out a continuous stream of tiny ink globules. These ink
the inked image on the paper is "fused," usually with globules were passed though an electric field which left
heat. them with an electrical charge. The stream of charged
In a Xerox machine the image on the photosensitive ink globules was then electrostatically deflected to pro-
drum is simply a copy of an "original" produced with a duce characterson the paper in the same way that the
camera lens. A more computer-compatible method of electron beam is deflected to produce an image on a CRT

436 CHAPTER TWELVE


screen. Excess Ink was deflected to a guttei and re reel diuii i/. ii ion In ordei to explain how the waveform
turned to the ink reservoir. Ink jet printers are relatively modification approaches work we need to talk brieflj
quiet, ami some of these electrostatically deflected Ink- about how humans produce si iuni I
jet printers ran prinl up to 15,000 lines/min. Several
disadvantages, however, prevented them from being
WAVEFORM MODIFICATION sl'IIUI SYNTHESIS
used more widely. They lend to be messy and difficult to
keep working well Prinl quality at high speeds Is poor Some sounds, (ailed voiced sounds, an- produced by
and multiple copies are not possible. vibration ol the vocal cords as air passes from the lungs.
Newei ink jel printers use a variety oi approaches to I he frequency ol vibration or pitch, the position ol the
solve these problems. Some, such as the III' Thinkjet, tongue, the shape ol the mouth, and the position ol the
use ink cartridges which contain a column ol liny heal lips delei mine the actual sound produced, the vowels A
ers when one ol these tiny heaters is pulsed on. ii and E are examples of voiced sounds. Anoihei type ol
caused a drop ol ink lo explode onto the paper. Others. sound, tailed unvoiced sounds, m speech aie piodui ed
Such as the IBM Quietwriter, lor example, use an elei by modifying the position ol the tongue and the shape ol
trie current lo explode microscopic ink hubbies from a the mouth as a constant stream ol an (nines from the
special ribbon directly onto the paper. These lasl two lungs. The letter S is an example of this type of sound. A
approaches are really hybrids of thermal and ink-jet third type ol sound, the nasal sounds called Jri< atives,
technologies. They can produce very near letter-quality consist of a mixture ol voiced and unvoiced sounds. In
print at speeds comparable to those of slower dot-matrix electronic terms then the human vocal system consists
impact printers. A disadvantage of some ink-jet printers of a variable-frequency signal generator as the source for
is that they require special paper lor best results. voiced sounds, a "white" noise signal source for un-
voiced sounds, and a series of filters which modify the
outputs from the two signal sources to produce the de-
SPEECH SYNTHESIS AND RECOGNITION sired sounds.Figure 12-40 shows this in block diagram
WITH A COMPUTER form.
The three main approaches to implementing this
In a great many cases it is very convenient for a com- model electronically are linear predictive coding or LPC.
puter
communicate
to verbally with a user. Some exam formant. and phoneme. These methods differ mostly in
pies of the use of computer-created speech are talking the type of filter used, and in how often the filter charac-
games, talking cash registers, and text-to-speech ma- teristics
updated.
are
chines by usedblind people. Other examples are medical LPC synthesizers, such as that in the Texas Instru-
monitor systems that give verbal warnings and direc- ments "Speak and Spell." use a digital filter such as we
tions when some emergency condition exists. This use described in Chapter 10 to modify the signals from a
demonstrates some of the major advantages of speech pulse and a white noise source. For this type of filter the
readout. The verbal signal attracts more attention than parameters that must be sent from the microcomputer
a simple alarm, and the user does not have to search are the coefficients for the filter and the pitch for the
through a series of readouts to determine the problem. pulse source. Remember from the discussion in Chapter
Adding speech recognition circuitry to a computer so 10 that for a digital filter, the current output value is
that it can interpret verbal commands from a user also computed or "predicted" as the sum of the current input
makes the computer much easier to use. The pilot of a value and portions of previous input values. A high-
rocket ship or space shuttle, for example, can operate quality LPC synthesizer may require as many as 16
some controls verbally while operating other controls Kbits/s. One difficulty with most LPC devices has been
manually, lit probably won't be too long before we elimi- that complex computer equipment and programs had to
nate the
verbal/manual link and control the whole ship be used to analyze a spoken word and determine the
directly from the brain, but that is another story, per- series of coefficients required to produce that word.
hapsthein next book. ) Voice entry systems are also use- Usually the IC manufacturer did this for a fee, and pro-
ful for
handicapped programmers and other computer ducedROM a with the parameters for a particular vo-
users. We will first describe for you the different meth- cabulary.
General
The Instruments SP1000. however,
ods usedto create speech with a computer, and then has now simplified this process somewhat.
describe speech recognition methods.

V0ICED
Speech Synthesis Methods SIGNAL

There are several common methods of producing speech VARIABLE

from a computer. The tradeoffs between the different


FREQUENCY %^ SPEAKE
GENERATOR
methods are speech quality and the number of bits that PROGRAMMABLE
FILTER(S)
must be stored/sent for each word. In other words, the UNVOICED
SIGNAL
higher the speech quality you want, the more bits you
WHITE
have to store in memory to represent each word, and the NOISE
faster you have to send bits to the synthesizer circuitry. SOURCE

All of the common methods of speech synthesis fall into


two general categories: waveform modification, and di- FIGURE 12-40 Electronic model of human vocal tract.

MICROCOMPUTER SYSTEM PERIPHERAtS 437


The SIM 000 can function as an LPC speech processor. sound quality. A phoneme synthesizer has a mechanical
an LPC speech recognizer, and an LPC speech synthe- sound. One big advantage of phoneme synthesizers is
sizer underthe control of a microcomputer. In learn that you can make up any message you want by simply
mode the device generates LPC coefficients for spoken putting together a sequence of phoneme codes. Another
words. The microcomputer reads these coefficients from example of a phoneme synthesizer is the SSI263 from
the SP1000. and stores them in memory. To operate in Silicon Systems, Inc.
recognition mode the SP1000 is used to generate the
coefficients for the unknown word. These coefficients DIRECT DIGITIZATION SPEECH SYNTHESIS
are then compared with those of known words in mem-
This method produces the highest-quality speech, be-
ory identify
to the unknown word. For use as a speech
causeis itessentially just a playback of digitally re-
synthesizer the SP1000 is switched to talk mode and the
corded speech.To start, the word you want the com-
coefficients for the desired word are sent to it by the
puter
speak
to is spoken clearly into a microphone. The
microcomputer. Consult the General Instruments data
output voltage from the microphone is amplified and
sheet for more information about this interesting de-
applied to the input of perhaps a 12-bit A/D converter.
vice. One approach at this point might be to simply store the
The formant approach uses several resonant or form- A/D samples for the word in a ROM and read the values
ant filters to massage the signals from a variable- out to a D/A converter when you want the computer to
frequency signal source and a white-noise source. Fig- speak the word. The difficulty with this approach is
ure 12-41 shows how the frequencies of these formant that, if the samples are taken often enough to produce
filters might be arranged for a male and for a female good speech quality, a lot of memory is required to store
voice. For this type of system the parameters that must the samples for a word. To reduce the amount of mem-
be sent from the computer are the pitch of the variable- ory required,several speech compression algorithms are
frequency signal, the center frequency for each formant used. These algorithms are too complex to discuss here,
filter, and the bandwidth of each formant filter. The but the basic principles involve storing repeated wave-
data rate for direct formant synthesis is only about 1 forms once,
only taking advantage of symmetry in wave-
Kbit/s, but the parameters must again be determined forms,not and storing values for silent periods. To fur-
with complex equipment. It is then not easy to develop a ther reducethe memory required for direct digital
custom vocabulary for a specific application. A phoneme speech, some systems use differential or delta modula-
approach solves this problem and requires a still lower tion.these
In systems only a 3-bit or 4-bit code, repre-
data rate, at the expense of lower speech quality sentingmuch
how a sample has changed from the last
Phonemes are fragments of words. An example of a sample, is stored in memory instead of storing the com-
phoneme speech synthesizer is the Votrax SC-01 which plete 12-bitvalue. Since audio signals change slowly.
we described in Chapter 9. In the case of the SC-01 you this is very acceptable. Even with compression, how-
get it to sound one of its 64 phonemes by sending it a ever, direct
digital speech requires considerable memory
6-bit binary code from a computer port. When the SC-0 1 and a bit rate as high as 64 Kbits/s. The OKI Semicon-
finishes sending the phoneme, it asserts a REQUEST sig- ductor MSM5218RS is an example of a device which
nal whichindicates that it is ready for the next pho- functions in this way. In record mode it can be used
neme. Wordsare produced by sending a series of pho- with an A/D converter to produce the differential codes
neme codes.
In addition to the 6-bit phoneme code, an for a spoken word. In play mode the device produces
additional 2 bits can be sent to specify rising, falling, or speech from applied codes using an internal 10-bit D/A
flat inflection for each phoneme. Inside the SC-01 A. the converter. Another example of a direct digital system is
6-bit phoneme code is used to control the characteris- the National Semiconductor Digitalker. For further in-
ticssome
of formant filters as described in the previous formation, the
consult
data sheets for these devices.
paragraph. Since only one code is sent out for a rela-
tively long
period of speech, the required bit rate is only
about 70 bits/s. However, the long period between codes
gives less control over waveform details, and therefore Speech Recognition
Speech recognition is considerably more difficult than
speech synthesis. The process is similar to trying to rec-
ognize human
faces with a computer vision system. The
MALE FEMALE 4 KHz
first step in speech recognition is to train the system, or
\ 1

ft \ /*
/ \i
6 / \
/ 1\
/ 1> 6 4) /\
i \ >
in other words produce

plates
memory.
in
templates
that the system needs to recognize,
for each of the words
and store these tem-
To produce a template for a word, the
\ >*->^
V
intended user speaks the word several times into a mi-
i 1 i
...1 i 1 1 crophone connected
to the system. The system then de-
IFREQUENCY termines several
parameters or features for each repeti-
FIRST SECOND THIRD FOURTH I
tion the
of word and averages them to produce the
FORMANT FORMANT FORMANT FORMANT
actual template.
FIGURE 12-41 Filter responses for formant speech Different systems extract different parameters to form
synthesizer. the template. Figure 12-42 shows a block diagram for

438 ( HAPTER TWELVE


BAND PASS FILTERS

1 1

MICROPHONE 3 3

A
V ^> -< ANALOG A/D
in roMP
MULTIPLEXER CONVERII H — V y POUT
INPUT
1
START
N N CONVERT

Z f H 0 CROSSING
ETECTOR
MP
OUTPUT
\ F TO V

/^
y
CONVERTER INPUT
SELECT

FIGURE 12-42 Block diagram ot one type o( speech recognition system.

one of the most common methods. This method uses a IMPORTANT TERMS AND CONCEPTS
set of formant filters with their center frequencies ad- FROM THIS CHAPTER
justed
match
to those of the average speaker. The out-
put amplitudes of these formant filters are averaged to CRT operation
produce a signal proportional to the energy in each of raster display
the frequency bands. Also used are one or more zero- field
crossing detectors to give basic frequency information. interlaced scanning
The pulse train from the zero-crossing detector is con- frame
verted
a proportional
to voltage, so it can be digitized
Video monitor
along with the outputs from the formant averagers.
Now. when a word is spoken, samples of each of the CRT terminal
features are taken and digitized at evenly spaced inter
vals of 10-20 ms during the duration of the word. The Horizontal and vertical svnc pulses
features are stored in memory. If this is a training run,
Composite video
this set of samples will be averaged with others to form
the template for the word. If this is a recognition run, Character generator
this set of features will be compared with the templates
Display refresh RAM
stored in memory. The best match is assumed to be the
Dot. undot
correct word. Currently none of the available voice rec-
dot clock
ognition systems
is 100 percent accurate. The most ac-
curate systemsare those that only work with the overscan

speaker who trained them and those that only work Display page
with isolated words. However, considerable progress is
being made in this area. The VPC 2000 from VOTAN Attribute code
Inc.. for example, is a speech recognition unit which
Bit-mapped raster scan CRT graphics display
plugs into IBM PC-compatible computers and can recog-
picture element — pixel — pel
nize continuous phrases. It also has a built in voice-
activated telephone dialing and answering service. An- Mouse
other PC-compatible unit, the VocaLink from Interstate
Voice Products, permits the programming of up to 240 Composite color monitor
spoken commands to control standard PC software such
Luminance signal
as word processors and business programs. Perhaps the
HAL 9000 is not too far away. Chroma signal

MICROCOMPUTER SYSTEM PERIPHERALS 439


Vector-scan CRT displays ASCIIZ

Alphanumeric/graphics liquid crystal displays ILC'Ds) RAM disk

Computer vision Hard disk systems


ultrasonic vision cylinders
video cameras — vidicon partitions
CCD cameras
OPTICRAM cameras Optical disk systems
OROM
Floppy disks DRAW
hard and soft sectoring
index holes
Printer mechanisms
index. ID. and data fields, gaps, address marks
IBM Selectric
daisy wheel
Checksums drum. band, and chain
dot-matrix impact and dot-matrix thermal
Cyclic redundency character
spark gap
Single and double density laser and xerographic
ink jet
FM and MFM recording
Speech synthesis
File allocation table
pitch, unvoiced sounds, and fricatives
Hierarchical file structure linear predictive coding, formant. phoneme
direct digitization
Root directory and subdirectory
Speech recognition
File control block

File handle

REVIEW QUESTIONS AND PROBLEMS


1. With the help of a simple drawing explain how a a. Total number of character times/row
noninterlaced raster is produced on a CRT. b. Total number of scan lines/frame
c. Horizontal frequency (number of lines/second)
2. Use a simple drawing to help you describe how a
d. Dot-clock frequency (dots/second)
display of the letter X is produced on a noninter-
e. Minimum bandwidth required for video ampli-
laced raster-scanCRT display.
fier
3. Refer to Figure 12-5 to help you answer the follow- /. Time between RAM accesses
ing questions. The IBM PC color adapter board uses a 14-MHz dot
a. What is the purpose of the RAM in this circuit?
clock frequency, a 15.750-kHz horizontal scan
b. At what point(s) in displaying a frame do the
rate, and a 60-Hz frame rate. Characters are pro-
address inputs of this RAM get changed?
duced
an in 8 by 8 dot matrix. There are 80 charac-
c. At what poinds I in displaying a frame do the ters/row25
and rows/frame.
R0-R3 address inputs of the character genera-
a. What is the total number of dot times per scan
tor ROMget changed?
line?
d. What is the purpose of the shift register on the
b. How many dot times then are left for horizontal
output of the character generator ROM?
overscan?
e. Why is one input of the shift register tied to c. What is the total number of scan lines per
ground? frame including overscan?
f. At what pointlsl in displaying a frame are hori- d. How many scan lines then are left for vertical
zontal sync
pulses produced? overscan?
g. At what pointls) in displaying a frame are verti-
cal sync
pulses produced? Describe how a DMA controller is used with a CRT
h. List the three components of a composite video controller such as the 8275 to keep a CRT display
signal. refreshed.

4. A CRT display is designed to display 24 character How does the CRT display system in Figure 12-7
rows with 72 characters in each row. The system arbitrate the dispute that occurs when the 6845
uses a 7 by 9 character generator in a 9 by 12 dot CRT controller and the microprocessor both want
matrix. Assuming a 60-Hz noninterlaced frame to access the display RAM at the same time.
rate, three additional character times for horizon-
Write a program which uses the IBM BIOS proce-
tal overscan, and 120 additional scan lines for ver-
duresread
to a string of characters entered from
tical overscan, answer the following questions.

440 CHAPTER TWEtVE


the keyboard, put the key codes In .1 buffei In mem 21. What is inc. ml l>\ llie term rlieran hi) al file StrtlC

ory, and display the characters foi the pressed keys iiac'' What is a majoi advantage ol this type nl file
on the CRT. structun

9. 1low much memorj is required to store the pel data 22. Wi in ,1 program which uses the IBM PC Dos func-
l(u a lni mapped display of 640 bj 180? tion callsto ie.ul 111 a string containing your name
from the keyboard to a butler In memory, and
1(1. What is the difference between .1 CRT monitoi and
sends the string to a pi inter. Reineinbei in use the
.1 CRT terminal?
DOS4CH function call to return to DOS at the end
1 1. Describe how three electron beams are used to pro- ol the program.
duce possible
.ill colors on .1 color CRT screen.
23. Explain why magnetic bard disks can store much
12. I low much memory is required to store the pel data 11101e d.ita than floppy disks, and why data can I"
lor a 5 12 by 5 12 display where each pel can be any written 01 read out much faster from hard disks
one ol 16 colors?
24. Why must hard disks be perated in a dust-free
13. Describe how a composite color video signal is pro-
environment?
duced from
the red. blue, green, and sync signals.
Include in your answei the function ol the 25. Two terms often encountered in hard disk system
3.579545-MH/ signal. manuals aie cylinder and pen lit ion. Del me and tell
the difference between these two terms.
14. Describe how a vector graphics CRT display system
produces a display of a triangle on the screen. What 26. Describe how stored data is read from optical
is the major problem with the vector approach to disks. What advantages does this readout method
CRT graphics? have over that used for hard magnetic disks?
15. The inputs of an 8-bit D/A converter are connected
to port FFF8H of a microcomputer and the output 27. Describe how data bits are recorded in magneto
of the D/A converter is connected to the A" axis of .111 optic read/write optical disk systems and in DRAW
oscilloscope. The inputs of another 8-bit D/A con- optical disk systems.
verterconnected
are to port FFFAH of a microcom-
28. A human brain can store about 10'" bits of data
puter, and
the output ol this D/A is connected to
and has an access time in the order of about a sec-
the V axis of the oscilloscope. Write a program
ond. Comparethese parameters with those of an
which uses these D/A converters to display a square
optical disk system such as the Optimem 1000.
on the screen of the oscilloscope. Then modify the
program so that the square enlarges after each 100 29. Describe the operation of the print mechanism for
refreshes. each of the following types of printer. Also give an
16. Describe the methods used by CCD and OPTK RAM advantage and a disadvantage for each tvpe.
cameras to produce visual images which can be a. Spinning golf ball
stored in computer memory. b. Daisy wheel
c. Drum
17. How is the read/write head for a disk drive moved d. Chain or band
into position over a specified track?
e. Dot matrix
18. What additional information besides the actual /. Thermal
data is recorded on each track of a soft-sectored g. Laser
floppv disk? Describe the purpose of the CRC bytes h. Ink jet
included with each block of data recorded on the
30. Draw a block diagram of a waveform modification
disk.
type of speech systhesizer. Describe the operation
19. Why must clock bits be recorded along with data of the LPC. formant, and phoneme types of speech
bits on floppy disks? Under what conditions will a synthesizer that use this model.
clock pulse be inserted in a bit cell when recording
data on a disk in MFM format? 31. What are the major differences between an LPC
speech synthesizer and a formant speech synthe-
20. List the major types of information contained in sizer?
the directory of a magnetic disk formatted by a
DOS. If a data file requires several clusters on a 32. Describe the operation of a direct digitization
disk, how does a DOS keep track of where the speech synthesizer. What is the major advantage
pieces of the file are located. and the major disadvantage of this type':'

MICROCOMPUTER SYSTEM PERIPHERALS 441


CHAPTER

Data Communication and


Networks

In Chapter 2 we discussed "computerizing" an electron- 10. Describe how data is transmitted on an Ethernet
ics factory. What this means is that computers are inte- system.
grated all
into of the operations of the factor.-, and that
each person in the company has access to a computer. 11. Describe how data is transmitted in a token-passing
The company may have a large centrally located main- ring system.
frame computer, several supermicrocomputers that 12. Show the major signal groups for the GPIB (IEEE
serve groups of users, individual computer engineering 488) bus. describe how bus control is managed, and
workstations, and portable computers spread around how data is transferred on a handshake basis for the
the world with the salespeople. In order for all of these GPIB.
computers to work together, they must be able to com-
municate each
with other in an organized manner. In
this chapter we show you some of the devices, signal
ASYNCHRONOUS SERIAL DATA
standards, and systems used for communication with
COMMUNICATION
and between computers.
Introduction and Overview
Serial data communication is a somewhat difficult sub-
OBJECTIVES jectapproach,
to because you need pieces of information
from several different topics in order for each part of the
At the end of this chapter you should be able to:
subject to really make sense. To make this approach eas-
ier, we
will first give an overview of how all the pieces fit
1. Show and describe the meaning of the bits in the
together and then describe the details of each piece later
format used for sending asynchronous serial data.
in specific sections. A problem with this subject is that
2. Describe the use of the major signals in the RS-232C it contains a great many terms and acronyms. To help
standard. you absorb all of these, you may want to make a glossary
of terms as you work your way through the chapter.
3. Show how to connect RS-232C equipment directly Within a microcomputer data is transferred in paral-
or with a "null-modem" connection. lel, because that is the fastest way to do it. For transfer-
4. Initialize a common UART for transmitting serial ring data over long distances, however, parallel data
data in a specified format. transmission requires too many wires. Therefore, data
to be sent long distances is usually converted from par-
5. Use the IBM PC BIOS and DOS procedures to send
allel form
to serial form so that it can be sent on a single
and receive serial data. wire or pair of wires. Serial data received from a distant
6. Describe several voltage, current, and light (fiber- source is converted to parallel form so that it can easily
optic
signal
I methods used to transmit data. be transferred on the microcomputer buses. Three
terms often encountered in literature on serial data sys-
7. Describe the three types of modulation commonly tems simplex,
are half-duplex, and full-duplex. A sim-
used by modems. plex data
line can transmit data only in one direction.
An earthquake sensor sending data back from Mount
8. Show the formats for a byte-oriented protocol and
St. Helens or a commercial radio station are examples of
for a bit-oriented protocol used in svnchronous se-
simplex transmission. Half-duplex transmission means
rial data
transmission.
that communication can take place in either direction
9. Draw diagrams to show the common computer net- between two systems, but can only occur in one direc-
work configurations. tionaattime. An example of half-duplex transmission

442
Is a two-way radio system, where one usci always listens pai allel out shift register can lis Also
while the othei talks because the receive! circuitry is needed, for somi case; 'i ' 1 i. data transfei
turned ofl during transmit I lie term lull duplex means shaking circuitry to make sun- that a transmits 1 doi
thai each system can send and receive data al the same not send data fastei lhan it 1 an be read In by the recelv
time. A normal phone conversation is an example ol a iny system. There are available several programmable
full duplex operation. LSI devices which contain most ol the circuitry 1
Serial data can be senl synchronously 01 asyn 11 communication. A device such as the
chronously. Foi synchronous transmission, data is senl it I, which can only do asyni fironous 1 ommi inii .1
in blocks at a constanl rate. Hie starl and end of a block 1 ion, is often n ferred to as a universal a
are identified with specific bytes or bil patterns We dis • 1 < eivei transmittei 01 ( 'ART. A device such as the Intel
cuss synchronous data formats in a latei section of tins 8251A. which can be programmed lo do eithei asyn
chaptei Foi asynchronous transmission, each data chronous 01 synchronous communication, is often
charactei has a bit which identifies its st.ut and 1 01 2 ( ailed a universal synchronous asynchronous n
bits which identify its end. Since each character is indi transmittei or f 'SART.
vidually identified, characters can be sent al am tune Once the data is converted to serial form it must in
(asynchronously), in the same way that a person types some way be sent from the transmitting (JAR1 to the
un a keyboard at different rates. receiving WART. There are several ways in which serial
Figure 13- 1 shows the bit format often used foi trans- data is commonly sent. One method is to use a current
mitting asynchronous serial data. When no data is to represent a 1 in the signal line and no current to rep-
being sent, the signal line is in a constant high or mark- resenl a 0. We discuss this current loop approach in a
ing state. The beginning of a data charactei is indicated later seel ion. Another approach is to add line drivers on
by the line going low forifl bit time. This bit is called a the output ol the HART to produce a sturdy voltage sig
start bit. The data hits are then sent out on the line one nal The range ol each ol these methods, however, is
after the oilier. Note that the least-significant hit is sent limited to a few thousand feet
out hrst. Depending on the system, the data word may For sending serial data ovei long distances the si ,11id
consist of 5, 6, 7. or 8 hits. Following the data hits is a ard telephone system is a convenient path, because the
parity bit which, as we explained in Chapter 1 1 . is used Wiring and connections arc already in place. Standard
to check for errors in received data. Some systems do phone lines, often referred to as switched lines because
not insert or look for a parity bit. After the data bits and any two points can be connected togethei through a se-
the parity bit. the signal line is returned high for at least riesswi
of lelics. have a bandwidth of only about 300 to
1 bit time to identify the end of the character. This al- 3000 Hz. Therefore, for several reasons, digital signals
ways-high bit is referred to as a stop bit. Some systems of the form shown in Figure 13-1 cannot be sent directly
use 2 stop bits. For future reference note that the effi- over standard phone lines. (NO If: Phone lines capable
ciency
thisof format is low, because It) or 1 1 bit times of carrying digital dala directly can be leased, but these
are required to transmit a 7-bit data word such as an are somewhat costly, and limited to the specific destina-
ASCII character. tionthe
of line. )
The term baud rate is used to indicate the rate at The solution to this problem is to convert the digital
which serial data is being transferred Baud rate is de- signals to audio-frequency tones, which arc in the fre-
finedl/(the
as time for a bit cell). If a bit time is 3.33 ms, quency range
that the phone lines can transmit. The
for example, the baud rate is 1/(3.33 ms), or 300 Bd. device used to do this conversion and to convert trans-
There is an almost unavoidable, but incorrect, tendency mitted tones
hack to digital information is called a
to refer to this as 300 bits/s. In some cases, the two do modem. The term is a contraction of modulator-demod-
correspond, but in other cases 2 to 4 actual data hits are ulator.
a Inlater section of this chapter we discuss the
encoded within one transmitted bit time, so data bits operation ol some common types of modems. For now.
per second and baud do not correspond. Commonly take a look at Figure 13-2 which shows bow two mo-
used baud rates are 1 10. 300. 1200, 2400, 4800. 9600. dems can
be connected to allow a remote terminal to
and 19.200 Bd. communicate with a distant mainframe computer over
To interface a microcomputer with serial data lines a phone line. Modems and other equipment used to
the data must be converted to and from serial form. A send serial data over lonu distances are known as data
parallel-in-serial-out shift register and a serial-in- communication equipment 01 DCE. 'The terminals and

ALWAYS ALWAYS HIGH


LOW

, *- • » • f 1
START DO D2 ' D3 ' 04 ' D5 D6 PARITY STOP ! STOP

ONE CHARACTER

TICURE 13-1 Bit format used tor sending asynchronous serial data.

DATA ( OMMUNKAIION AND NETWORKS 443


MICROCOMPUTER MODEM
LARGE A Serial Interface Device — The Intel 8251 A
CONTROLLED
TERMINAL COMPUTER Since the 8251 A is used as the serial port on SDK-86
TELEPHONE boards, on the IBM PC synchronous communication
TxD TxD
board, and on many other boards, we will use it as an
RxD RxD
example here.
rTs RTS

CTS cfs
SIGNALS AND SYSTEM CONNECTIONS
CD CD
Figure 13-3 shows a block diagram and the pin descrip-
0TR DTR
tionsthe
for 8251 A. Figure 7-6, sheet 9. shows how an
DSR DSR
8251 A is connected on the SDK-86 board. Keep copies of
DCE these two handy as you work your way through the fol-
lowing discussion.
As shown in the SDK-86 schematic, the eight parallel
DTE DATA TERMINAL EQUIPMENT lines, D7-D0, connect to the system data bus so that
DCE - DATA COMMUNICATION EQUIPMENT data words and control/status words can be transferred
to and from the device. The chip-select (CS) input is
FIGURE 13-2 Digital data transmission using modems connected to an address decoder so the device is enabled
and standard phone lines. when addressed. The 8251 A has two internal addresses.
a eontrol address which is selected when the C/D input
is high, and a data address which is selected when the
computers that are sending or receiving the serial data C/D input is low. For the SDK-86 the control/status ad-
are referred to as data terminal equipment or DTE. The dressFFF2H
is and the data read/write address is
signal names shown in Figure 13-2 are part of a serial FFFOH. The RESET, RD, and WR lines are connected to
data communications standard called RS-232C. which the system signals with the same names. The clock
we discuss in detail in a later section. For now you just input of the 8251 A is usually connected to the system
need enough of an overview so that the signals and ini- clock to synchronize internal operations with system
tialization
the of825 1A described in the next section operations. In the ease of the SDK-86 the clock input is
make sense to you. Note the direction arrowheads on connected to the 2.45-MHz PCLK signal because it is re-
each of these signals. 1 lere is a sequence of signals that latedthe
to system clock, but at a frequency the 825 1A
might occur when a user at a terminal wants to send can handle.
some data to the computer. The signal labeled TxD on the upper right corner of the
After the terminal power is turned on and the termi- 8251 A block diagram is the actual serial-data output.
nal runsany self-checks, it asserts the data-terminal- The pin labeled RxD is the serial-data input. The addi-
ready (DTR) signal to tell the modem it is ready. When it tional circuitry
connected to the TxD pin on the SDK-86
is powered up and ready to transmit or receive data, the board is needed to convert the TTL logic levels from the
modem will assert the data-set-ready (DSRI signal to 825 1A to current loop or RS-232C signals. The circuitry
the terminal. Under manual control or terminal control connected to the RxD pin performs the opposite conver-
the modem then dials up the computer. sion. will
We discuss current loop and RS-232C signal
If the computer is available, it will send back a speci- standards a little later.
fied tone.Now. when the terminal has a character actu- The shift registers in the UART require clocks to shift
ally readyto send, it will assert a request-to-send (RTS I the serial data in and out. TxC is the transmit shift-
signal to the modem. The modem will then assert its register clock input, and RxC is the receive shift-register
carrier detect (CD) signal to the terminal to indicate clock input. Usually these two inputs are tied together
that it has established contact with the computer. When so they are driven by the same clock frequency. Look at
the modem is fully ready to transmit data, it asserts the Figure 7-6, sheet 9, to see how a variety of clock signals
clear-to-send (CTS) signal back to the terminal. The ter- are produced from a 74LS393 counter. A wirewrap
minal then
sends serial data characters to the modem. jumper is installed to select the desired TxC and RxC.
When the terminal has sent all the characters it needs The frequency of the applied clock signal must be 1 . 16.
to. it makes its RTS signal high. This causes the modem or 64 times the transmit and receive baud rate, depend-
to unassert its CTS signal and stop transmitting. As we ing on
the mode in which the 825 1A is initialized. Using
show later, a similar handshake occurs between the a clock frequency higher than the baud rate allows the
modem and the computer at the other end of the data receive shift register to be clocked at the center of a bit
link. The important point at this time is that a set of time rather than at a transition. This reduces the
handshake signals are defined for transferring serial chance of noise at a transition causing a read error.
data to and from a modem. The 8251 A is double-buffered. This means that one
Now that you have an overview of asynchronous serial character can be loaded into a holding buffer while an-
data, modems, and handshaking, we will describe the other characteris being shifted out of the actual trans-
operation of a typical device used to interface a micro- mit shift
register. The TxRDY output from the 8251 A will
computei lo a modem or other device which requires go high when the holding buffer is empty and another
serial data. ( haracter can be sent from the CPU. The TxEMPTY pin

444 ( HAPTER THIRHIN


m2 5 1 Pin Functions

Pin Name Pin Function

D7-D0 lata bus (8 bits)

C D Control - ii

! HAT.', Ml !
BUS Bl IFFER RD Read data - nmmand
BUFFI h
D/ DO WR Write data or i ontrol i ommand

*
cs ( hip selei 1

RESET CLK . pulse <! U i


HE AD - T.H[!\
, I -
WRIT! 1 RANSMI 1 HI SI 1 Reset
1 -1,1 Ml' 1 i
CONT Hill
TxC 1 ransmittei clock
- - I.I
WR
TxD niter data

RxC Rei eivei clod

RxD Receiver data


DSR -c

DTR a RECEIVE RxRDY Rei eivei ready (has character for CPU)
MODEM
BUFFER
CTS -a
CONTROL TxRDY Transmitter ready (ready for cha from CPU)

RTS- ' DSR Data set ready

DTR Data terminal ready

'.1 : ii'.A - RxRDY SYNDET BD Sync detect break detect


DATA BUS RECEIVE
- H.(
RTS Request to send data
CONTROL
i_#_SYNDET
CTS Clear to send data
BRKDET
TxEMPTY Transmitter empty

V, t 5-V supply

GND Ground

FIGURE 13-3 Block diagram and pin descriptions for the Intel 8251A USART.
(a) Block diagram, (b) Pin descriptions. (Intel Corp.)

on the 8251 A will go high when both the holding buffer dress the
for device. Figure 13-4 shows the formats for
and the transmit shift register are empty. The RxRDY these words and for the 8251 A status word which is
pin of the 825 1A will go high when a character has been read from the same address. Baud rate factor, specified
shifted into the receiver buffer and is ready to be read by the two least-significant bits of the mode word, is the
out by the CPU. Incidentally, if a character is not read ratio between the clock signal applied to the TxC-RxC
out before another character is shifted in, the first char- inputs and the desired baud rate. For example, if you
acter will
be overwritten and lost. want to use a TxC of 19,200 Hz and transmit data at
The sync-dererL/brea/c-derecr (SYNDET/BD) pin has 1 200 Bd, the baud rate factor is 19, 200/ 1200 or 16 • If
two uses. When the device is operating in asynchronous bits DO and Dl are both made O's, the 8251 A is pro-
mode, which we are interested in here, this pin will go grammed
synchronous
for data transfer. In this case the
high if the serial data input line, RxD, stays low for more baud rate will be the same as the applied TxC and RxC.
than 2 character times. This signal then indicates an The other three combinations for these 2 bits represent
intentional break in data transmission, or a break in asynchronous transfer. A baud rate factor of one can
the signal line. When programmed for synchronous data only be used for asynchronous transfer if the transmit-
transmission this pin will go high when the 825 1A finds ting system and the receiving system both use the same
a specified sync characters] in the incoming string of TxC and RxC. The character length specified by bits D2
data bits. and D3 in the mode word includes only the actual data
The four signals connected to the box labeled MODEM bits, not the start bit, parity bit or stop bit(s). If parity is
CONTROL in the 8251 A block diagram are handshake disabled, no parity bit is inserted in the transmitted bit
signals which we described in a previous section. string. If the 8251 A is programmed for 5. 6, or 7 data
bits, the extra bits in the data character byte read from
INITIALIZING AN 8251 A
the device will be O's.
To initialize an 8251 A you must send first a mode word After you send a mode word to an 8251 A. you must
and then a command word to the control register ad- then send it a command word. A 1 in the least-signifi-

DATA COMMUNICATION AND NETWORKS 445


D7 D6 D5 D4 D3 D2 D1 DO
D7 D6 D5 D4 D ; D2 hi DO
EH IR RTS ER 5BRK RiEOTR T«EN
1 S2 S1 EP t'[ !% ! u B2
Bl|
L TRANSMIT ENABLE

L BAUD

0
RATE

1
FACTOR

0 1
0
1 ENABLE
DISABLE

0 0 1 1
DATA TERMINAL READY
-:% ,nc HIGH WILL FORCE
(1X1 (I6X) (64X)
MODE DTR OUTPUT TO ZERO

CHARACTER LENGTH RECEIVE ENABLE


1 ENABLE R %RDY
0 1 0 1
6 DISABLE R -RDY
0 I) 1 1

5 6 7 8 SEND BREAK CHARACTER


BITS BITS BITS BITS 1 = FORCES T %D LOW
0 - NORMAL OPERATION

PARITY ENABLE
1 = ENABLE 0 DISABLE ERROR RESET
1 = RESET ALL ERROR
EVEN PARITY
FLAGS (PE.OE, FE)
GENERATION/CHECK
1 = EVEN 0 - ODD
REQUEST TO SEND
NUMBER OF STOP BITS HIGH WILL FORCE
1
RTS OUTPUT TO ZERO
0 1 0

0 0 1 1
NTERNAL RESET
1 1' HIGH RETURNS 8251
INVALID
BITS BITS BITS TO MODE INSTRUCTION
FORMAT
(ONLY EFFECTS Tx; Rx
NEVER REQUIRESMORE
ENTER HUNT MODE
THAN ONE STOP BIT)
I ENABLE SEARCH FOR
SYN CHARACTERS

DATA SET READY TRANSMITTER READY


DSR is general purpose. Norn- Indicates USART is ready to accept
used to test modem condition -"
Data Set Ready.

RECEIVER READY
Indicates USART has received a
character on its serial input and
SYNC DETECT is ready to transfer it to the CPU.
When set for internal sync detect
indicates that character sync has been
achieved and 8251 is ready for data TRANSMITTER EMPTY
Indicates that parallel to serial
OVERRUN ERROR converter in transmitter is empty.
The OE flag is set when the CPU doe
not read a character before the next
FRAMING ERROR (ASYNC ONLY) nes available. It is reset by PARITY ERROR
FE flag is set when a valid stop bit is nc the ER bit of the Command instruct! PE flag is set when a parity er
detected at end of every character It is OE does not inhibit operation of the detected It is leset by ER bil
reset by ER bit of Command instruct io 8251 , however, the previously Command instruction PE do
FE does not inhibit operation of 8251. h.ii . ImSI inhibit operation of 8251

FIGURE 13-4 Format ot 8251 A mode, command, and status words, (a) Mode
word, (b) Command word, (c) Status word. (Intel Corp.)

cant bit of the command word enables the transmitter data address, the TxRDY signal will go low and remain
section of the 8251 A and the TxRDY output. When en- low until the holding buffer is again ready for another
abled. the 8251 A TxRDY output will be asserted high if character. Putting a 1 in bit D1 of the command word
the CTS input has been asserted low. and the transmit- will cause the DTR output of the 8251 A to be asserted
ter holding buffer is ready for another character from low. As we explained before, this signal is used to tell a
the CPU. The TxRDY signal can be connected to an inter- modem that a terminal or computer is operational. A 1
rupt input on the CPU or an 8259A, so that characters in bit D2 of the command word enables the RxRDY out-
to be transmitted can be sent to the 8251 A on an inter- put pinof the 8251 A. If enabled, the RxRDY pin will go
rupt basis. When a character is written to the 8251 A high when the 8251 A has a character in its receiver

446 CHAPTER THIRTEEN


buffei ready to be read. This signal can be connected in Putting a l in I >ii l id 111 the command word causes the
an Interrupt Input so that characters can be read In on i \ in be internally resel when the command word is
.in Interrupt basis. The KxKIA output is resel when a sent. After a software resel command is sen i in i Ins waj .
rli. u actei is read from thi a new mode word must be sent. Latei we will show you
Putting a l In bit D3 of the command word causes the how lliis is used.
8251A to output .1 charactei ol .ill O's, which is called a The 1)7 bil In the command word is only used when
break chai acter. A break charactei is sometimes used to the device is operating In synchronous mode A com
Indicate the end ol a block of transmitted data. Sending in.iiid word wiili a 1 in this bil position tells the M2T>1A
a com m. i ml word with a 1 in bit D4 causes the 8251 A to in look loi specified sync character(s) in a sin. mi ofbits
reset the parity, overrun, and framing error flags in the being shifted in. II the 8251A finds the spei ified sync
825 1A status register, ["he meanings ol these flags are character(s), h will assen its SNX'DI I hi) pin high. We
explained in Figure 13 4c. A 1 in bit l)r> ol the command will discuss ilns more in the synchronous data commu
word will cause ilic 8251A to asserl Us request i<> send nication section ol this chaptei
(Risi output low. This signal, remember, is sent to a Figure 13-5 shows an example ol the instruction se
modem to ask whether the modem and the receiving quence yon can use to initialize an K251A. This se-
system are ready for a data character in be sent. quence
somewhat
is lengthy lor two reasons. First, the

; 8086 Instructions to initialize the 8251A on an SDK-86 board


MOV DX , 0FFF2H point at command register address
MOV AL, OOH send O's to guarantee device is in
OUT DX , AL the command instruction format before
MOV CX , 2 the RESET command is issued
DO: LOOP
LOOP DO
DO ; and delay after sending each command
OUT DX , AL instruc t i on .
MOV CX, ,
CX 2
Dl LOOP Dl
OUT DX , AL
MOV CX , 2
D2: LOOP D2
MOV AL, ^+0H Send internal reset command to
OUT DX , AL return device to idle state
MOV CX , 2 Load delay constant
D3: LOOP D3 and delay
MOV AL, 11001 1101 Load mode control word and send it

110 0 1110 Mode Word


\ \ \ \ \ \ \_\__ baud rate factor of 16x
\ \ \ \ \_\ character length of 8 bits
\ \ \_\_ __parity disabled
\_\_ __2 stop bits

OUT DX, AL
MOV CX, 2 ; and delay
DU: LOOP D<+
MOV AL, 00110111B ; Load command word and send it
OUT DX, AL

0 0 110 111 Command Word


\\\\\\\\ Transmit enable
\ \ \ \ \ \ \__ Data terminal ready, DTR will output 0
\ \ \ \ \ \ Receive enable
\ \ \ \ \ Normal operation
\ \ \ \ Reset all error flags
\ \ \ RST output 0, request to send
\ \ Do not return to mode instruction form
\ Disable hunt mode

FIGURE 13-5 Instruction sequence for 8251 A initialization.

DATA COMMUNICATION AND NETWORKS 447


8251 A does not always respond correctly to a hardware the 8251 A to reset its TxRDY output until the buffer is
reset on power-up. Therefore, a series of software com- again ready to receive a character. A counter can be used
mands must
be sent to the device to make sure it is reset to keep track of how many characters have been sent.
properly before the desired mode and command words In a similar manner characters can be read from an
are sent. The device is put into a known state by writing 825 1A on an interrupt basis. In this case the RxRDY out-
3 bvtes of all O's to the 8251 A control register address, put of
the 8251 A is connected to an interrupt input of
and then it is reset by sending a control word with a 1 in the processor or an 8259A, and this output is enabled
bit D6. After this reset sequence the desired mode and by putting a 1 in bit D2 of the command word sent dur-
control words can be sent to the 8251 A. The 825 1A dis- ing initialization. When a character has been shifted
tinguishes
command a word from a mode word by the into the 8251 A. and the character is in the receiver
order they are sent to the device. After reset, a mode buffer ready to be read, the RxRDY pin will go high. If the
word must be sent to the command address. Any words interrupt chain through the 8259A and the processor is
sent to the command address after the mode word will enabled, the processor will go to an interrupt procedure
be treated as command words until the device is reset. which reads in the data character. Reading a data char-
The second factor which lengthens this initialization acter from
the 8251 A causes it to reset the RxRDY out-
is the write-recovenj time 7"kv of the 825 1A. According put signal. This signal will stay low until another char-
to the data sheet the 825 1A requires a worst case recov- acterready
is to be read.
erv time of 16 cycles of the clock signal connected to the To send characters to an 8251 A on a polled basis, the
Cf K input. On the SDK-86 board the PCLk signal, which 8251 A status register is read and checked over and over
is the same as the processor clock frequency, is con- until the TxRDY bit ID0I is found to be a 1. In some sys-
nected
the toCLK input of the 8251 A. Therefore, for the tems you
also want to check bit D7 of the status register
SDK-86 board, the required write-recovery time corre- to make sure the DSR input of the 8251 A has been as-
sponds
16 toprocessor clock cycles. What all this means serted
a by
signal from, for example, a modem. When the
is that you have to delay this many clock cycles between required bitls) of the status register are all high, a data
successive initialization byte writes to the 8251 A. A character is then written to the 8251A. Figure 13-6a
simple way to produce the required delay and some shows the instruction sequence needed to do this. Note
extra is to load CX with 0002 and count it down with the that the status register has the same internal address as
LOOP instruction. The MOV CX, 0002 instruction lakes the control register. Also note that both an AND and a
4 clock cycles, the first execution of the LOOP instruc- CMP operation must be done to determine when the two
tion takes 17 clock cycles, and the last execution of the desired bits are both high. Writing a data character to
LOOP instruction takes 5 cycles. The 8 cycles required the 8251 A resets the TxRDY bit in the status register.
for the OUT instruction, which writes the control words, Reading a character from the 8251 A on a polled basis
also count as part of the time between writes, so the is a similar process, except that the RxRDY bit (Dl) of the
sum of all these is more than enough. When writing status register is polled to determine when a character
data characters to an 8251 A you don't have to worry is ready to be read. When bit D1 is found high, a charac-
about this recovery time, because a new character will ter is
read in from the 8251 A data address. Figure 13-6b
not be written to the 8251 A until the previous character shows the instruction sequence for this. Status register
has been shifted out. This shifting, of course, requires bits D3, D4, and D5 can be checked to see if a parity
much more time than TR\ . error, overrun error, or framing error has occurred. If an
The comments in Figure 13-5 explain the meanings of error has occurred, a message to retransmit the data
the bits in the mode and control words used in this ex- can be sent to the transmitting system.
ample. Once
the 825 1A is initialized as shown, new con- The next step in our journey into serial data commu-
trol words can be sent at any time to. for example, reset nications
to discuss
is the signal standards used to con-
the error flags. Now let's look at how characters are sent nect the
serial inputs and outputs of UARTS to modems
to and read from an 8251 A. and other serial devices.

SERIAL DATA TRANSMISSION METHODS


SENDING AND RECEIVING CHARACTERS WITH
AN 8251 A
AND STANDARDS

Data characters can be sent to and read from the 825 1A Aside from drum beats in the jungle, one of the earliest
on an interrupt basis or on a polled basis. To send char- forms of serial data communication was the telegraph.
actersanon interrupt basis the TxRDY pin of the 825 1A In a telegraph pressing a key at one end of a signal line
is connected to an interrupt input on the processor or causes a current to flow through the line. When this
an 8259A priority interrupt controller. The transmitter current reaches the receiving end of the line, it activates
and the TxRDY output are enabled by putting a 1 in bit a solenoid (sounder) which produces a sound. Letters
DO of the control word sent to the 8251A during initiali- and numbers are sent using the familiar Morse code or
zation. When
the CTS input of the 825 1A is asserted low. some other convenient code. After a hundred years or so
and the 825 1A buffer is ready for a character, the TxRDY the telegraph key and sounder evolved into the teletype-
pin will go high. If the processor and 8259A interrupt writer.
teletypewriter
A terminal has a typewriter-style
path is enabled, the processor will go to an interrupt keyboard so that the user can simply press a key to send
service procedure which writes a data character to the a desired letter or number. A teletype terminal also has a
8251 A data address. Writing the data character causes print mechanism which prints out characters as they

448 ( HM'IEK THIRTEEN


Instructions for transmitting data using an SDK-86 8251A
using polling method

MOV DX, 0FFF2H ; point at control register address


TEST1 IN AL, DX ; read status
AND AL, 10000001B ; and check status of
\ \ . data set ready & transmit ready
CMP AL, 10000001B ; is it ready?
JNK TEST1 ; continue to poll if not ready
MOV DX, OFFFOH ; otherwise point at data address
MOV AL, DATA_TO_SEND ; load data to send
OUT DX, AL ; and send it

Instructions for receiving data with an SDK-86 8251A


using polling method

MOV DX, 0FFF2H point at control register address


TEST2 IN AL, DX read status
AND AL, 00000010B and check status of RxRdy
JZ TEST2 continue to poll if not ready
MOV DX, OFFFOH otherwise point at data address
IN AL, DX get data

FIGURE 13-6 Instruction sequences for transmitting and receiving with an


825 IA on a polled basis, (a) Transmit, (b) Receive.

are received. Most teletypes use a current to represent a RX RET line. Think of the key mechanism of the teletype-
1 and no current to represent a 0. We start this section writer
a as
simple switch connected between pins 24
by briefly describing the old current-loop standards, and and 12 of |7 on the circuit. When the switch is closed the
then go on to newer methods. current flows back on the TTY RX line and through R3 to
- 12 V. The current flowing through R3 will produce a
legal TTL high logic level on the input of the 74LS14
20- and 60-mA Current Loops inverter. This high signal passes through two inverters
In teletypewriters or other current signal systems some and produces a high on the RxD input of the 8251A.
manufacturers use a nominal current of 20 mA to repre- The circuit as shown in Figure 7-6 is set up for full-
sent1 a. or mark, and no current to represent a 0. Other duplex operation because the transmit circuit and the
manufacturers use a nominal current of 60 mA to repre- receive circuit are independent of each other In this
sent1a and no current to represent a 0. case, a character sent to the SDK-86 will not be printed
out on the teletypewriter until it is echoed back from the
NOTE: The actual current in a specific system may be SDK-86. This is sometimes referred to as echoplex
considerably different from the nominal value. mode. If jumper VV17 is installed, the system will operate
Sheet 9 of Figure 7-6 shows circuitry which can be in half-duplex mode. In this mode a character will be
used to interlace current type signals with the TTL printed out directly as it is typed on the keyboard. How-
input and output of an 8251 A USART on the SDK-86 ever, data
cannot be sent and received at the same time
board. With the jumpers in place as shown, a high on because typed characters will be interspersed with char-
the TxD output of the 8251A will produce a low on the acters sent
from the SDK-86. We will leave it to you to
PNP transistor. This will turn the transistor on and trace the current paths lor this half duplex mode. Now
cause a positive current to flow out the TTY TX line In- we will go on to a more common signal standard which
side
teletypewriter
a this current flows through an elec- uses voltages.
tromagnet
backandto the TTY TX RET. To help you visu-
alize this,
think of a coil of wire connected between puis
RS-232C Serial Data Standard
13 and 25 of )7 in the drawing. The current then flows
on to - 12 V through R2 to complete the path. To send a
OVERVIEW
data bit. the teletypewriter opens or closes a switch in a
current path. The current for this path in the SDK-86 In the 1960s as the use of time-share computer termi-
circuitry is supplied from +5 V through RIO to the TTY nals becamemore widespread, modems were developed

DATA COMMUNICAUON AND NETWORKS 449


so that terminals could use phone lines to communicate
with distant computers. As we stated earlier, modems
and other
ferred
devices
asto data
used
communication
to send serial
equipment
data are often
or DCE.
re-
£> 330 pF
>vo Fl %D

The terminals or computers that are sending or receiv-


ing thedata are referred to as data terminal equipment
or DTE. In response to the need for signal and hand
I x-p. 330 pF
K> A
'
%1
r.T<
shake standards between DTE and DCE. the Electronic
Industries Association (EIAI developed EIA standard
RS-232C. This standard describes the functions of 25 yf^O^ xio
' DSR

signal and handshake pins for serial data transfer. It


also describes the voltage levels, impedance levels, rise
and fall times, maximum bit rate, and maximum capac- >H>
itance these
for signal lines. Before we work our way . I
PIN M 12 V
through the 25 pin functions, we will take a brief look at
PIN 1 12 V
some of the other hardware aspects of RS-232C. PIN 7 GND

RS-232C specifies 25 signal pins and it specifies that


the DTE connector should be a male, and the DCE con-
nector should
be a female. A specific connector is not FIGURE 13-8 TTL to RS-232C and RS-232C to TTL signal
given, but the most commonly used connectors are the conversion, (a) MC1488 used to convert TTL to RS-232C.
DB-25P male and the DB-25S female shown in Figure (b) MC1489 used to convert RS-232C to TTL.
13-7. When you are wiring up these connectors, it is
important to note the order in which the pins are num-
bered. Another, more standard way to interface between
The voltage levels for all RS-232C signals are as fol- RS-232C and TTL levels is with MC1488 quad TTL-to-
lows.
logic
A high, or mark, is a voltage between -3 V RS-232C drivers and MCI 489 quad RS-232C-to-TTL
and -15 V under load (-25 V no load). A logic low or receivers shown in Figure 13-8. The MC 1488s require +
space is a voltage between +3 V and + 15 V under load and - supplies, but the MC1489s require only +5 V.
I + 25 V no load). Voltages such as ± 12 V are commonly Note the capacitor to ground on the outputs of the
used. MC 1488 drivers. To reduce cross talk between adjacent
wires the rise and fall times for RS-232C signals are lim-
ited30
to V//xs. Also note that the RS-232C handshake
RS-232C TO TTL INTERFACING
signals such as RTS are active low. Therefore, if one of
Obviously a USART such as the 8251 A is not directly these signals is asserted, you will find a positive voltage
compatible with these signal levels. Sheet 9 of the SDK- on the actual RS-232C signal line when you check it
86 schematics in Figure 7-6 shows one way to interface during troubleshooting. Now let's look at the RS-232C
TTL signals of the 825 1A to RS-232C signal levels. 11 the pin descriptions.
jumpers shown are removed and the jumpers shown in
the jumper table under CRT are inserted, the circuil will
RS-232C SIGNAL PINS
produce and accept RS-232C signals. (N( >TE; This is
the jumpering needed to prepare the SDK-86 board for Figure 13-9 shows the signal names, signal direction,
downloading programs from an IBM PC or other i om and a brief description for each of the 25 pins defined
puter.) Here's an example of how it works. for RS-232C. For most applications only a few of these
With a jumper between the points numbered 7 and 8, pins are used, so don't get overwhelmed. Here are a few
a high on the TxD output of the 8251 A produces a high additional notes about these signals.
on the base of the transistor, which turns it off. With First note that the signal direction is specified with
points numbered 9 and 10 jumpered, the CR TX line will respect to the DCE. This convention is part of the stand-
then be pulled to - 12 V which is a legal high or marking ard. We
have found it very helpful to put arrowheads on
condition for RS-232C. A low on the TxD output of the all signal lines as shown in Figure 13-2 when we are
8251 A will turn on the transistor and pull the CR TX line drawing circuits for connecting RS-232C equipment.
to +5 V, which is a legal low or space condition for Next observe that there is both a chassis ground (pin
RS-232C. 1) and a signal ground (pin 7). To prevent large ac-
induced ground currents in the signal ground these two
should be connected together only at the power supply
in the terminal or the computer.
The TxD. RxD, and handshake signals shown with
1 2 3 4 5 6 7 8 910111213)) common names in Figure 13-9 are the ones most often
>oooooooooooo
used for simple systems. We gave an overview of their
oooooooooooc
14 15 16 17 18 19 20 21 22 23 24 25 1— J use in the introduction to this section of the chapter,
and will discuss them further in a later section of the
FIGURE 13-7 DB-25P connector often used tor RS-J S2C chapter on modems. These signals control what is called
connections. the primary or forward communications channel of the

450 CHAPTER THIRTEEN


PIN COMMON
NUMBER NAME NAME
iN DCI

1 AA PHOl I C1IVI i.H


TXD BA IN
3 RXD BB RE CI
%1 CA REQUI I
5 CTS CB ,1 ND OUT

h DSR CC DATA SET READY OUT


7 AB SIGNAL GROUND (COMMON RE 1UHN)
CD CF REC! IVf D 1 INI mi, MAI HI Hi rOR OUT
9 ING)
10 (RESERVI D i OR DAI a mi it :,i

11 UNASSIGNED
12 SCf 11 CO LINE SIG DETECTOR Ml il
13 SCB SECONDARY CLEAR TO SEND H! 1

14 SBA SECONDARY TRANSMITTED DATA IN


lb DB TRANSMISSION SIGNAL ELEMENT TIMING IliCI '.( n Hi 1 i

16 SBB SECONDARY RECEIVED DATA OUT


17 DD RECEIVER SIGNAL ELEMENT TIMING (DCE SOURCE) our
18 UNASSIGNED
19 SCA SECONDARY REQUEST TO SEND IN
20 DTR CD DATA TERMINAL READY IN

21 CG SIGNAL QUALITY DETECTOR OUT


22 CE RING INDICATOR OUT
23 CH CI DATA SIGNAL RATE SELECTOR (DTE DCE SOURCE) IN/OUT
24 DA TRANSMIT SIGNAL ELEMENT TIMING (DTE SOURCE) IN
25 UNASSIGNED

FIGURI 15-') RS-iiiC pin names and signal descriptions.

modem. Some modems allow communication over a anything, but connecting outputs together is not a pro-
secondani or backward channel which operates in the ductive relationship.A solution to this problem is to
reverse direction from the forward channel and at a make an adapter with two connectors so that the signals
much lower baud rate. Pins 12. 13. 14. 16, and 19 are cross over as shown in Figure 13- 10a. This crossover
the data and handshake lines for this backward chan- connection is often called a null modem. We have again
nel put arrowheads on the signals in Figure 13- 10a to help
Pins 15, 17, 21, and 24 are used for synchronous data you keep track of the direction for each. As you can see
communication. We will tell you a little more about these in the figure, the TxD from the terminal now sends data
in the section of the chapter on modems. Next we want to the RxD input of the computer. Likewise, the TxD
to show you some of the tricks in connecting up RS- from the computer now sends data to the RxD input of
232C "compatible" equipment. the computer as desired. The handshake signals also
are crossed over so that each handshake output signal
is connected to the corresponding input signal
CONNECTING UP RS-232C EQUIPMENT A second reason that you can't just plug RS-232C
A major point we need to make right now is that you can compatible equipment together and expect it to work is
seldom just connect together two pieces of equipment, that a partial implementation of RS-232C is often used
described by their manufacturers as RS-232C compati- to communicate with printers, plotters, and other com-
ble, and
expect them to work the first time. There are puter peripheralsbesides modems. These other periph-
several reasons for this. To give you an idea of one of the erals may
be configured as DCE or as DTE. Also, they
reasons, suppose that you want to connect the terminal may use all. some, or none of the handshake signals. As
in Figure 13-2 directly to the computer rather than an example of this, suppose that we want to connect the
through the modem-modem link. The terminal and the RS-232C port on the IBM PC asynchronous communi-
computer probably both have DB-25 type connectors so cation board
to the serial port on the SDK-86 so that we
that, other than a possible male-female mismatch, you can download object-code programs.
might think you could just plug the terminal cable di- The IBM PC asynchronous board is configured as
rectly into
the computer. To see why this doesn't work, DTE, so TxD is on pin 2, RxD on pin 3. RTS on pin 4. CTS
hold your fingers over the modems in Figure 13-2 and on pin 5. DTR on pin 20. DSR on pin 6. and carrier detect
refer to the pin mimbers for the RS-232C signals in Fig- (CD) on pin 8. In order for the IBM board to be able to
ure 13-9.As you should see, both the terminal and the transmit and receive, its CTS. DSR. and CD inputs must
computer are trying to outpLit data (TxD) from their be asserted. The BIOS software asserts the DTR and RTS
number 2 pins to the same line. Likewise, they are both outputs. Now take another look at sheet 9 of the SDK-86
trying to input data (RxD) from the same line on their schematics in Figure 7-6 to see how the data and hand-
number 3 pins. The same problem exists with the hand- shake signalsare connected there.
shake signals.
RS-232C drivers are designed so that For communicating with RS-232C tvpe equipment,
connecting the lines together in this way will not destroy the SDK-86 board is jumpered as shown in the jumper

DATA COMMUNICATION AND NETWORKS 451


when RTS is asserted. Pins 6, 8. and 20 are also
jumpered together on the connector so that when the PC
asserts its DTR output on pin 20. the DSR input and the
CD input will automatically be asserted. These connec-
tionsnot
do provide for any hardware handshaking
They are necessary just to get the PC and the SDK-86 to
talk to each other.
The point here is that whenever you have to connect
RS-232C "compatible" devices such as terminals, serial
printers, etc., get the schematic for each and work your
way through the connections one pin at a time. Make
sure that an output on one device goes to the appropri-
ate input on the other device. Sometimes you have to
look at the actual drivers and receivers on the schematic
to determine which pins on the connector are outputs
and which are inputs. This is necessary because some
IBM SDi 86 manufacturers label an output pin connected to pin 3 as
PC RS-232C
PIN # PIN # RxD, indicating that this signal goes to the RxD input of
the receiving system.
1 1
GND
2 2
T*D - r r R %
3 3
R*D CRT TX
4
RS-422A, RS-423A, and RS-449
RfS
5 A major problem with RS-232C is that it can only trans-
CTS
6
mit datareliably about 50 ft [16.4 m] at its maximum
DSR
rate of 20,000 Bd. If longer lines are used, the transmis-
CD
,8 , sion rate
has to be drastically reduced. This limitation is
20
DTR caused by the open signal lines with a single common
7
ground that are used for RS-232C.
A newer standard, RS-422A specifies that each signal
will be sent differentially over two adjacent wires in a
ribbon cable or a twisted pair of wires as shown in Fig-
FIGURE 13-10 Nonmodem RS-232C connections, (a) Null ure 13-1la. Differential signals are produced by differ-
modem tor connecting two RS-232C data-terminal-type ential line
drivers such as the MC3487 and translated
devices, (b) IBM PC serial port to SDK-86 RS-232C back to TTL levels by differential line receivers such as
connection. the MC3486. Data rates for this standard are 10 MBd for
a distance of 50 ft [16.4 ml or 100,000 Bd for a distance
of 4000 ft [1220 m). The higher transmission rate of
table column labeled "stand alone CRT." The output RS-422A is possible because the differential lines are
data on CRT TX then connects to pin 3 of connector \7 . a terminated by resistors so they act as transmission lines
DB-25S-type connector. This corresponds to the RxD instead of simply open wires. A further advantage of dif-
on the IBM connector, so no crossover is needed. Like- ferential signals
is that any common-mode electrical
wise, the
CRT RX of the SDK corresponds to the TxD of noise induced in the two lines will be rejected by the
the IBM board, so this is also a straight-through con- differential line receiver. For RS-422A a logic high or
nection.handshake
The signals here are another story. mark is indicated by the B signal line being more posi-
The RTS of the SDK-86 is simply looped into the CTS tive thanthe A signal line. A logic low or space is indi-
so CTS will automatically be asserted when RTS is as- catedtheby A signal line being more positive than the B
sertedthe
by 8251 A. Therefore, neither of these signals signal line. The voltage difference between the two lines
is available for external handshaking. The DTR output of must be greater than 0.4 V. but not greater than 12 V.
the 8251 A on the SDK board is used for a teletypewriter The common-mode voltage on the signal lines must be
function, and does not connect to the normal RS-232C in the range of -7 V to +7 V.
DTR pin number, so it is not available either. The DSR Another EIA standard intended to solve the speed and
input of the 825 1A is connected to the RxD input so that distance problems of RS-232C is RS-423A. This stand-
it will be asserted when a start bit comes in on the serial ard specifiesa low impedance single-ended signal in-
data line, but this line is also not available for hand- steadtheof differential signal of RS-422A. The low-
shaking with
external devices. The problem here then is impedance signal can be sent over 50-12 coaxial cable
that the SDK-86 is not set up to supply the handshake and terminated at the receiving end to prevent reflec-
signals needed by the IBM PC serial board. Figure tions. Figure
13-1 lb shows how an MC3487 driver and
13- 10b shows the connections we make to solve this MC3486 receiver can be connected to produce the re-
problem so the PC can talk to the SDK-86. The PC RTS quired signals.
A logic high in this standard is repre-
line on pin 4 is jumpered on the connector to its CTS line sented
thebyA line being between 4 and 6 V negative
on pin 5, so that CTS will automatically be asserted with respect to the B line (ground), and a logic low is

452 CHAPTER THIRTEEN


where digital data needs to be transferred in man} dil
ferenl local s, oi where the amount ol data in be
transferred dors not warrant the cost ol a leased line,
standard (switched) phone lines are used As we indi
i .iii (I in ,i previous section, the bandwidth ol si
phone lines is limited i<> «><) it/ :', kHz, so modems
iniisl be used In convei t digital data In tones lb,it it can
I ii (in ovei standard telephone lines, and to convert the
tones back tn digiial data at the receiving end ol the
phone line Before we can explain how modems interact
with phone lines, we need in look at some telepho
cuitry.
Figure 13 12 shows some generic circuitry lor plain
old telephone set rue or POTS, that many ol us are si ill
stuck with. A POTS system uses a rotary dial and elec
tromechanical ringer. Newer systems use dual-tone
multifrequency (I)TMF or touch-tone) dialing and elec
tronic ringers, but the line connections we are inter-
ested here
in are the same.
The circuitry to the left of the first vertical line in lit;
ure 13-12 is contained in the telephone. The circuitry
between the two dotted vertical lines may be located in a
private branch exchange, or PBX, il the phone is part ol
a multiphone system in a large building. It may be lo-
cated a in
centralized building if the phone is that of a
single subscriber connected directly to the phone lines.
(b)
Note that for a simple system such as this, only two
FIGURE 13-11 RS-422A and RS-423A drivers and wires are required to connect the phone to the PBX or
receivers. u> MC 5487 driver and MC3486 receiver used local exchange. To send and receive the signals over long
tor RS-422A differential signals, (bi MC3487 driver and distances, however, the two-wire signal must be con-
MC3486 receiver used for RS-423A signal on coax cable. vertedseparate
into send and receive signals. This must
be done so that amplifiers or repeaters can be put in
each signal path. The conversions back and forth be-
represented by the A line being 4-6 V positive with re- tween two-wire signals and four-wire signals is done by
spect
ground.
to a device called a hybrid coil. Now let's see how this
The RS-422A and RS-423A standards do not specify works and pick up some more terminology.
connector pin numbers or handshake signals the way Let's assume that the phone handset is in its cradle,
that RS-232C does. An additional EIA standard called or on-hook. to start. At this point, then, switches 51 and
RS-449 does this for the two. RS-449 specifies 37 signal S2 are open, and S3 is closed. To ring up the phone, an
pins on a main connector and 9 additional pins on an ac voltage of 48 V or 96 V rms is sent from the local
optional connector. The signals on these connectors are exchange or PBX to the phone. This voltage activates the
a superset of the RS-232C signals so adapters can be ringer mechanism. When the phone handset is lifted
used to interface RS-232C equipment with RS-449 off-hook, switches S1 and S2 close, and switch S3 opens.
equipment. Still another EIA standard, RS-366. incor- Closing 51 and S2 causes a direct current to flow from
porates signals
for automatic telephone dialing with the 48-V dc supply. Circuitry in the PBX or in the local
modems. exchange detects this direct current and turns off the
ringing signal within about 200 ms. The process is re-
ferredas toa ring trip. Incidentally, the ring and tip
Telephone Circuits and Systems names on the signal lines in Figure 13-12 refer to the
A large amount of the communication between users parts of the old-fashioned phone plug connected to that
and computers and between different computers takes signal line. Closing S1 and S2 also allows the voice sig-
place over telephone lines in some form. In this section nalsget
to in and out of the phone. As you talk into the
we give you an introduction to the terminology and op- phone, the induction coil feeds back part of the trans-
eration
phone
of lines, and then discuss how different mitted voice
signal to the receiver so you can tell how
types of modems send and receive data over telephone loud you are talking. Now let's see what happens when
lines. you make a call.
In the case where digital data needs to be transferred Again when the handset is lifted off-hook a direct cur-
only between two fixed points, broadband lines can be rent produced
is in the wires to the PBX or local ex-

leased from telephone or other companies. Depending change.PBX


The or local exchange returns a dial tone to
on the type of line leased, digital data can be directly let you know that it is alive and ready to serve you. As

sent and received at rates from 10 Kbits/s to several you turn the rotary dial to dial a number, switches S4

megabits per second on these lines. However, in cases and S5 open and close as the dial passes each number.

DATA COMMUNICATION AND NFTWORKS 453


LOCAL (2-WIRE) TOLL (4 WIRE)
EXCHANGE

BALANCING
HYBRID NETWORK

S1 S2and S3 are me I
coupled together to sw l<hhoo^
S4 and S5 are mechanically i oup ed
together to dial
% 4WIRE CIRCUIT
TO FROM S> STEM

FIGURE B-12 Circuitry and line connections for standard rotary-dial


telephone. (Texas Instruments, Inc.)

This produces a series of pulses equal to the desired application is usually called a coder and the D/A con-
number. Switching circuitry in the local exchange uses verter that
reconstructs the analog signal from the pulse
the series of pulses to start finding a path to the dialed codes is referred to as a decoder. Since both a coder and
phone. Dual-tone frequency-modulation or DTFM tele- a decoder are needed for two-way communication, they
phones produce
a mixture of two tones for each number are often packaged in the same IC. This combined coder
button pushed. Circuitry in the FBX or the local ex- and decoder is called a codec. Common examples of
change decodes
these tones to get the required number codecs are the Intel 2910Aand the Intel 291 1A- 1. These
information. In either case when all the desired num- devices each contain a sample-and-hold circuit on the
bers have
been entered, the local exchange attempts to analog input, an 8-bit A/D converter, an 8-bit D/A con-
complete the connection. If the dialed unit is unavaila- verter, appropriate
and control circuitry.
ble, the
local exchange returns a busy signal to your Normal A/D converters are linear, which means that
phone. the steps are the same size over the full range of the
An important point here is that any circuit or system converters. The A/D converters used in codecs are non-
that is going to be connected to standard phone lines linear. They
have small steps for small signals and large
must be approved by the FCC. This regulation is in- steps for large signals. In other words, for signals near
tended
prevent
to untested devices from damaging the the zero point of the A/D converter, it only takes a small
phone system or creating a shock hazard. change in the signal to change the code on the output of
The next topic we want to discuss here is one way that the A/D. For a signal near the full scale of the converter,
analog phone signals are converted to digital form so a large change in the input signal is required to produce
that they can be more efficiently sent over long dis- a change in the output binary code. This nonlinearity of
tances. the A/D converter is said to compress the signal, be-
cause
reduces
it the dynamic range of the signal. Com-
pression
this inway greatly improves the accuracy for
CODECS, TDM, and PCM small signals where it is needed, without going to a con-
Because digital signals have much better noise immu- verter with
more bits of resolution. The D/A in the codec
nity than
analog signals, analog signals are often con- is nonlinear in the reverse manner, so that when the
verted
digital
to signals with an A/D converter for trans- binary pulse codes are converted to analog, the result is
missionlong
over distances. A D/A converter at the expanded to duplicate the original waveform. A codec
destination uses the received binary codes to recon- which has this intentional nonlinearity is often referred
struct
replica
a of the originaJ analog signal. Sending to as a compander or a companding codec. The two
analog signals such as phone signals as a series of bi- most common ways of changing the size of the steps as
nary codes
is called pulse-code modulation or PCM. The the signal gets larger are called the /x LAW. and the A
A'D converter that produces the binary codes in this LAW. Consult the Intel 2910A data sheet for more infor-

454 ( HAPTER THIRftfN


quency ol the tones is within the bandpass ol the lines
The three majoi forms ol modulation used are iinijili
19 E—(24 I HANNELSI-
tu.de, frequency-shift keying (FSK), and phase-shift
1 BIT ADDI keying (PSK).
To produce amplitude modulation, a single frequency
CH2 CH3 CH4 CH tone ol perhaps 387 11/ is turned on to represent a I and
turned oil to represent a 0 as shown in figure 13 14a.
1 1( ,i iri i ; i ; I rame ionn.it for time-domain-multiplexed
Amplitude modulation is only used for very low speed
data it. im < ode<
reverse channel transmission because ol its pooi noise
rejection characteristics A temporary change in line
resistance, foi example, might drop the amplitude ol the
inatioii about a /i LAW device, and the Intel 291 IA I 1 signal below the threshold of the detector, and the
data sheet for more information about an A LAW device. data would appear to be all O's.
In most systems the output of the codec A/D is not Frequency si nil keying uses one tone to represenl a 0
simply sen i on a wire by itself, it is multiplexed with the and another tone to represenl a I as shown in Figure
outputs of many other codecs in a manner known as 13-14/). In order to allow lull-duplex communication,
time division multiplexing. TDM. Then- are several dif- four different frequencies are often used. An old stand
ferent formats
used. A simple one will give you the idea ard. the Bell 103A, 300-Bd FSK modem, for example,

Ol how it's done. uses 2025 Hz for a 0 and 2225 11/ for a 1 in one direc-
( )ne ol the first I'l >\1 systems was the Tl or DS-1 sys- tion, and1070 Hz for a 0 and 1270 Hz for a 1 in the
tem which multiplexes 24 PCM voice channels onto a other direction. Another standard, the Bell 202 modem,
single wire. For this system an 8-bit codec on each chan- permits hall-duplex communication at 1200 Bd. The
nel samples and digitizes the input signal at an 8-kHz 202 uses 1 200 Hz to represent a 0 and 1 700 Hz to repre-
rate. The 8-bit codes from the codecs are sent to a multi- sent1a for the mam channel. Different versions of the
plexer which
sends them out serially, one after the 202 may also have either a 5 bit/s amplitude-modulated
other One set of bits from each of the 24 codecs plus a back channel, or a 150 bit/s FSK back channel which
framing bit is referred to as a frame. Figure 13-13 shows uses 387 Hz for a 0 and 487 Hz for a 1.
the formal of a frame for this system. The framing bit at LSI has made it possible to build an FSK modem with
the start of each frame toggles after each frame is sent. It very few parts. Figure 13-15 shows a circuit diagram for
is used to keep the receiver and the transmitter syn- a modem which uses the Advanced Micro Devices Am
chronized and for keeping track of how many frames 7910 device. The 7910 can be programmed to operate in
have been sent. After it sends the framing bit, the multi- a Bell 103 compatible mode, Bell 202 compatible mode,
plexer sends
out the 8-bit code from the first codec, then or in a mode compatible with one of several other stand-
sends out the 8-bit code from the next codec, and so on ards.
uses
It A/Ds, D/As. and the digital filter techniques
until the codes for all 24 have been sent out. At specified we described in Chapter 10 to synthesize and filter all of
intervals the multiplexer sends out a frame which con- the data signals. The circuit in Figure 13-15 is con-
tains synchronization information and signaling infor- nected
a terminal
to or microcomputer through a stand-
mation. does
This not seriously affect the quality of the
transmitted data.
Since the multiplexer is sending out 193-bit frames at
a rate of 8000 per second, the data rate on the wire is
193 8000. or 1.544 Mbits/s. A newer system, known n_
as T4M or DS-4 multiplexes 4032 channels onto a single
coaxial cable or optic fiber. The bit rate for this system is
274.176 Mbits/s.
Telephone companies transmit long-distance phone
signals over high-speed digital Hires, and all local phone
service may eventually be converted to a wideband digi-
tal systemknown as the integrated services digital net-
workISDN.
or For now, however, the bandwidth of each
standard user channel is still only about 4 kHz. Until 0 10 0 0 10
this "weak link" is removed we still have to use modems
to communicate with computers over standard phone J^
lines. The next section shows how modems operate.

Modems

MODULATION METHODS

As we described in a previous section, a modulator-


demodulator, or modem, sends digital Is and O's over FIGURE 13-14 Modem modulation methods.
standard phone lines as modulated tones. The fre- (a) Amplitude, (b) Frequency-shift keying (FSK).

DATA COMMUNICATION AND NETWORKS 455


vBB

^ 'Value as recommended
AGND b\ crystal manufacturer
±

RCAP = IOOnforAm79IO
= 91012 tor Am7s>ll

FIGURE 13-15 FSK modem circuit using AM7910 modem chip. (Advanced Micro Devices)

ard RS-232C interface. Signal names on the 79 10 which sophisticated DAA circuitry. One of these is the CH1810
start with a B are the back channel signals. The 7910 from Cermetek Microelectronics. Inc. Note in Figure
inputs labeled MC0-MC4 are used to program the oper- 13-15 that the DAA circuitry provides a RINGING signal
ating modefor the device. These can be connected to to the 7910 when the modem is being called.
manual switches as shown, or in a microcomputer sys- Two important features of the modem circuit in Fig-
tem where the data and handshake signals are con- ure 13-15
are the analog loopback (ALBI and the digital
nected directlyto the UART. these lines could be con- loopback (DLB) which are used for testing. The analog
nected
a toport so that the operating mode could be loop mode is used to test the modem locally. When the
changed under program control. ALB switch in the middle of Figure 13-15 is in the up
FSK-modulated data is sent out from the 7910 on the position, the FSK-modulated data will be routed back
pin labeled TC and received on the pin labeled RC. The into the FSK input. A software test procedure can then
duplexer puts the transmitted signal on the common compare the incoming data with the transmitted data to
signal line and taps off the received signal from the com- see if the modem is a 7910 and the connecting circuitry
mon signalline. Remember from a previous discussion is working correctly. The digital loopback is used to
that data is sent and received on the same wire for a check the operation of the modem from some remote
standard two-wire phone service. The box labeled DAA location. When the DLB switch in Figure 13-15 is in the
in Figure 13-15 is the data access arrangement cir- down position, data received from the phone line will be
cuitry whichactually interfaces the signals with the retransmitted back to the sending system. The sending
phone lines. It is this circuitry that must conform to the system can then compare the sent and returned data to
provisions of FCC rules section 68. Several integrated see if the data link is operating correctly.
packages are available which contain a duplexer and On a standard two-wire phone line FSK modulation is

456 CHAPTER THIRTEEN


limited id hall duplex operation al L20<i I Id (With a stream is treated togethi i and referred to as a dibit,
four line service, lull duplex operation al 1200 bits s is I he value ol these I wo hi is determines ihc amount that
possible I Foi highei bit rates and full-duplex operation iiic phase oi (he ( .ii i ni will be shifted. Figure 13 I6fa
on standard phone service, phase-shifl modulation is shows the angle that the phase ol the carrfei will be
used shifted loi the lour possible values ol a dibit If, foi ex
ample, the value of 2 bits taken together is 01 . the phase
ni the i ,n i H i will be shifted 90 to represenl thai dibit
PHASE-SHIF1 MODULATION VARIATIONS
the trick here is that the phase ol the carrier only has to
In the simplest form ol phase-shift modulation, the slnii once for each two transmitted hits. Remember
phase ol a constant frequency sine-wave (.unci ol pei from a previous discussion that band rate is the rate at
haps 1700 Hz is shifted by 180° to represenl a change in which the carrier is changing. In this case it is not the
the data from a l to a 0 or from a () to a 1. Finnic 13 l 6a same as the number ol bits per second. Bell 212A type
shows an example ol this. As the digital data changes modems use this scheme to transmit 1200 bits s at a
from a o to a I . near the lefi edge ol the figure, the phase baud rate ol only 600 I id. Two carriei frequencies, 1200
ol the signal is shifted by 180 . When the data changes 11/ and 24(10 11/. are used to permit lull-duplex opera-
from a l to a 0, the phase ol the carrier is again shifted tion.
by 180 . For the next section ol the digital data where For tribii encoding, the data stream is divided into
the data stays t) for 3 bit times, the phase oi the carrier groups ol three bits each, called tribits. Figure 13 I6(
is not changed. Likewise, in a later section ol the wave- shows one possible set ol angles that the phase ol the
form where
the data remains at a one level for 2 bit carrier might be shifted to represent the eight different
times, the phase of the carrier is not changed. The values that the tribit can have. The Bell 208 modem
phase ni the carrier then is only shitted by 180° when uses this tribit scheme to transmit data at 4800 bits s
the data line changes from a 1 to a 0 or from a 0 to a 1. Another similar scheme which makes it possible to
The simple phase-shift modulation shown in Figure transmit data at 9600 bits/s over conditioned standard
13- 16a has no real advantage over FSK as far as maxi- phone lines encodes 4 bits in each baud time and is
mum rate
hit etc. are concerned. However, by using ad- called quaternary amplitude modulation (QAM). This
ditional phase
angles besides 180°. 2 or 3 bits can be scheme uses eight different angles to represent three of
sent in 1 baud time. Two bits sent in 1 band time are the bits in each group of four, and two different ampli-
called dibits, and 3 bits sent in 1 baud time are called tudesrepresent
to the fourth bit in each quadbit. A
tribits. Here's how dibits and tribits are encoded. baud rate of 2400 Bd and 4 bits/Bd produces a data rate
For dibit encoding, each pair of bits in the data of 9600 bits/s.
Dibit and tribit phase-shift modulation permits
higher data rates on phone lines, but detecting this type
of phase-encoded data presents some unique problems.
We will use a dibit example to describe these problems
and how they are solved. Remember from our previous
discussion that, in a dibit system, the value of a dibit is
represented by shifting the phase of a carrier signal
some specified number of degrees from a reference
phase. In order to detect the amount of phase shift, the
receiver and the transmitter must be using the same
reference phase. This would be easy if we could just run
another wire to carry a synchronizing clock signal.
GRAY CODE DEGREES OF
DIBIT VALUE
Since this is not easily done, the synchronizing signal
PHASE SHIFT
GRAY DEGREES must in some way be included with the data. The carrier
00 1 22.5
CODE OF signal itself cannot be used directly, because we want to
DIBIT PHASE 000 67.5
VALUE SHIF 1
measure the phase of that signal.
0 1 0 112.5
0
The solution to this problem is to use transitions in
00
0 1 1 157.5 the transmitted signal to synchronize a phase-locked
0 1 90
1 1 1 202.5 loop oscillator in the receiver. In order for this to work,
1 1 180
1 1 i) 247.5 two factors must be included in the transmitted data.
1 0 270
1 llll 292.5 First of all. the system must be operated synchronously
1 0 1 3.i/ ' rather than asynchronously, so that data, sync, or null
characters are always being received by the receiver.
Secondly, the transmitted data must have enough tran-
sitions
regular
at intervals to keep the phase-locked loop
HGURI I Mli Phase-shift modulation (PSK). (a) Wave- locked in the desired phase. The transmitted data from
forms
simple
for phase-shift modulation. (/>) One the USART may not have enough transitions in it to sat-
common set oi phase shifts used to represent four isfy this
second condition, so a special circuit called a
possible dibit combinations, (c) One common set of scrambler in the transmitter puts any required extra
phase shifts used to represent the eight possible tribit transitions in the signal. The scrambler usually consists
combinations. of a shift register with feedback. The output from the

DATA COMMUNICATION AND NETWORKS 457


scrambler is then used to modulate the phase of the car- warethe
in system connected to the modem. The hand-
rier. Whenthe carrier signal reaches the receiver, the shake sequence is similar for most of the Bell compati-
signal is demodulated to produce a signal of Is and O's. ble modems, so we will use the Bell 202 as an example.
This signal is then passed through a descrambler which Figure 13-17 shows the data and handshake wave-
reverses the scrambling process and outputs the origi- formsa for
202 modem as produced by the AM7910
nal data. single-chip modem described in the FSK section previ-
ously. Keep
a copy of the circuit diagram in Figure 13-15
handy as you work your way through the waveforms
MODEM HANDSHAKING
here.
Many of the currently available modems, such as the The modem which makes a call is usually referred to
Hayes Smartmodem 1200 that we use with our IBM PC. as the originate modem, and the modem which receives
contain a dedicated microprocessor. The built-in intelli- the call is usually referred to as the answer modem. In
gence allows
these units to automatically dial a specified the following discussion we will use the terms calling
number with either tones or pulses, and redial the num- modem and called modem, respectively, to agree with
ber itif is found busy or doesn't answer. When a smart the labels on the waveforms in Figure 13-17.
modem makes contact with another modem, it will au- At the left side of the waveforms, a call is being made
tomatically
to settry its transmit circuitry to match the from one modem to another. Assuming that the DTR
baud rate of the other modem. It can be set to automati- of the called modem is asserted, the ringing signal on
cally answer a call after a programmed number of rings the line will cause the DAA circuitry to assert the ringing
so that you can access your computer from a remote lo- input (Rl| of the 7910. In response to this the 7910 will
cation. Some
CRT terminals now come with a smart send out a silent period of about 2 seconds to accommo-
modem which allows the user to establish voice contact date billingsignals, and then it will send out an answer
and then switch over to digital data communication. tone of 2025 Hz to the calling modem for 2 seconds. If
After a modem dials up another modem, a series of the DTR and the RTS of the calling modem are asserted
handshake signals takes place. The handshake signals indicating that data is ready to be sent, the calling
may be generated by hardware in the modem or by soft- modem then puts a tone of 2225 Hz (mark! on the line

/ / / / / /'/ -;-a ////// \ / / / /

i % % -% ^^E3J—
% H4 I
—fvwrf— —k/v\rM• % •-' ,% 4;%%
%. :,
"—^ p
~~L '
i

—1- % r
1r
i- F~
/ / I / h / / I\ KTKS ^ 1 / / / / / / / ; /

IKS I °""'li"
in

FIGURE H-I7 Handshake signal sequence for Bell type 202 FSK modem using
AM7910 modem <hip.

458 CHAPTER II UK 1 1 IN
for 8 ins t<> lei the called modem know thai contact is types 103 202 106 ind 112A whi< h we have used as
complete. In response to this mark the called modem examples in this section. Throughout much ol tin rest
asserts its carriei detect output it I'l to enable the re ot the world modems follow one ot the standards ol the
celvlng UAR l rhe calling modem then sends data until (ninth- Consultatif Internationale Telephonlque el
us RTS input is released by the computer 01 terminal Telegraphtque l( (TIT), which is part ol tin Interna
sending the data. While it is receiving data on the main tional Telecommunications Union (MM standards
i h. mm I. the called modem can send data to the calling which relate to modems si, nt with a V Examples are the
modem on the 5 bits back channel. Releasing RTS V 26, w hi< li is a 2 100 bit s modem, and the V.27, which
causes the modem to release ( Is to the sending com is a 4800 bit s modem. In the next section we discuss a
puter, . mil remove the carrier from the line. The called means til data communication that may make modems
modem sense-, the loss oi the carrier and unasserts its obsolete.
can hi detect, ( I) signal.
Now. if (he called system is to send sonic data back to
the calling system on the main channel, it asserts the Hiber-Oplic Data Communication
KIS input to its modem. The (ailed modem sends a
marking tone to the calling modem for 8 ms. The calling INTRODUCTION
modem asset is its CD output to its HART. The called
All of the data communication methods we have dis-
modem then sends data to the calling modem on the
cussed
far souse metallic conductors. The systems we
mam channel until its RTS input is unasserted by the
describe here transfer data through very thin glass ot
called system, indicating no more (lata to send. While
plastic fibers with a beam of light and have no conduct
the called modem is transmitting on the main channel,
ing electrical path. Therefore, they arc called/iber-optic
the calling modem can transmit over the back channel it
systems. Figure 13-18 shows the connections for a basic
necessary. For a full-duplex system the handshake is
fiber-optic data link you can build and experiment with.
similar, but the data rates are equal in both directions.
The light source here is a simple infrared LED. Higher
MODEM STANDARDS performance systems use an infrared injection laser
diode (ILD] or some other laser driven by a high-speed,
Two organizations are responsible tor most of the cur- high-current driver.
renl standards regarding modems. In the United States
most modems follow one of the Bell Telephone stand- NOTE: If you are working on a fiber-optic system you
ards. Examples of these de facto standards are the Bell should never look directly into the end of the fiber to see

MOUNTING
HOLE

W I \
A P

FIGURE 13-18 Diagram oi simple fiber-optic data link.

DATACOMMUNICATION AND NETWORKS 459


if the light source is working, because the light beam
from some laser diodes is powerful enough to cause per-
manent damage.
eye Use a light meter, or point the cable
at a nonreflecting surface to see if the light source is
working.
Digital data is sent over the fiber by turning the light
beam on for a 1 and off for a 0. Data rates for some
currently available systems are as high as a gigabit per
second. Current systems use one of three light wave- AI
LIGHT

lengths.(im,
0.85 1.3 nm. or 1.500 /im. These wave-
LIGHT BEAM '
BEAM NORMAL
lengthsused
are because the absorption of light by the
optical fibers is minimum at these wavelengths.
The fibers used are made of special plastic or glass.
Depending on the desired operating mode, bandwidth.
and transmitting distance, different diameter fibers are
used. Fiber diameters used range from 2-1000 /urn. As
shown in Figure 13-19e. the fiber-optic cable consists of
three parts. The optical-fiber core is surrounded by a
cladding material which is also transparent to light. We
will explain the function of this cladding later. The cable
is enclosed in a sheath which protects the cladding and
does not allow external light to enter.
To convert the light signal back into an electrical sig-
nal atthe receiving end. Darlington photodetectors
such as the MFOD73 shown in Figure 13-18. p-i-n FET
devices, or avalanche photodiodes (APDs) are used.
APDs are more sensitive and operate at higher frequen-
cies, but the circuitry for them is more complex. A
Schmitt trigger is usually used on the output of the de-
tector"square
to up" the output pulses. Now that you
have an overview of an optical-fiber link, we will briefly
discuss some of the optics involved.
THE OPTICS OF FIBERS

The path of a beam of light going from a material with


one optical density to a material of different optical den- FIGURE 13-19 Light-beam paths for different angles of
sity dependson the angle at which the beam hits the incidence with boundary of material leaving a lower
boundary between the two materials. Figure 13-19 optical density, (a) Right angle. (6) Angle less than
shows the path that will be taken by beams of light at critical angle, (c) At critical angle, (d) Angle greater than
various angles going from an optically dense material critical angle, (e) Angle greater than critical angle in
such as glass to a less dense material such as a vacuum optical fiber.
or air. If the beam hits the boundary at a right angle, it
will go straight through as shown in Figure 13- 19a. A still more interesting situation is shown in Figure
When a beam hits the boundary at a small angle away 13-19d. If the beam hits the boundary at an angle
from the perpendicular or normal, it will be bent away greater than the critical angle, it will be totally reflected
from the normal when it goes from the more dense to from the boundary at the same angle on the other side of
the less dense, as shown in Figure 13- 19b. A light beam the normal. This is somewhat like skipping stones
going in the other direction would follow the same path. across water. In this case the light beam will not leave
A quantity called the index of refraction is used to de- the more dense material.
scribeamount
the that the light beam will be bent. To see how all of this relates to optical fibers, take a
Using the angle identifications shown in Figure 13-19b, look at the cross-sectional drawing of an optical fiber in
the index of refraction, n, is defined as the (sine of angle Figure 13-19e. If a beam of light enters the fiber parallel
B)/(sine of angle A). A typical value for the index of re- to the axis of the fiber, it will simply travel through the
fraction
glassof is 1.5. The larger the index of refrac- fiber. If the beam enters the fiber so that it hits the
tion, more
the the beam will be bent when it goes from glass-cladding layer boundary at the critical angle, it will
one material to another. travel through the fiber optic cable in the cladding layer
Figure 1319c shows a unique situation that occurs as shown for beam Y in Figure 13-19e. However, if the
when a beam going from a dense material to a less dense beam enters the cable so that it hits the glass-cladding
material hits the boundary at a special angle called the layer boundary at an angle greater than the critical
critical angle. The beam will be bent so that it travels angle, it will bounce back and forth between the walls of
parallel to the boundary after it enters the less dense the fiber as shown for beam X in Figure 13-19e. The
material. glass or plastic used for fiber-optic cables has very low

460 CHAPTER THIRTFHN


absorption, so the beam can bounce back and forth cal noise,and signals can be sen I linn h |i ingei distances
along the fiber foi several feel 01 miles without excessive without repeater amplifiers A large number ol fibers
.11tenuatlon. carl be put In a single cable. One lit the lirst major uses
ol fiber-optic transmiss systems has been foi carrj
MULTIMODE AND SINGLE-MODI FIBERS nig large numbers of phone conversations across oceans
and throughout cities. The specifications ol currently
[fan optical fiber has a diametei many times largei than
available fiber-optic systems are Impressive, bul rela
the wavelength ol the light being used, then beams
tively primitive as com pa ted to the possiblities shown by
which enter the fiber at different angles will arrive .h the
laboratory research. In the future it is possible that the
other end ol the fibei at slightly different times. The <lii
high data rate of fibei optic transmission maj makepii
ferent angles of entry for the beams are referred to as
ture phones a household reality, replace IV cables, re
modes. A fibei with a diameter large enough to allow
place satellite commuiiicai ion for many applications,
beams with several different entry angles to propagate
replace modems, and provide extensive computer net-
through ii is called a multimode liber. Since multimode
W01kmg
fibers are largei . they are easiei to manufacture, areeas
ier to manually work with, and can use inexpensive I.ED
diners However, the phase difference between the out-
ASYNCHRONOUS COMMUNICATION
pui beams in multimode libers causes problems at high
data rates One partial solution to this problem is to SOFTWARE ON THE IBM PC
dope the "lass of the fiber so that the index of refraction
In a previous section of this chapter we discussed how
decreases toward the outside of the fiber. Light beams
asynchronous serial data can be sent or received with an
travel faster in the region where the index of refraction
8251 A on a polled or an interrupt basis. Any serial cum
is lower, so beams which take a longer path back and
munication at some point has to get down to that level ol
forth through the faster outer regions tend to arrive at
hardware interaction. However, when you are working
the end of the fiber at the same time as those that take a
in a microcomputer system which has a DOS and BIOS
shorter path through the slower center region.
available, you can often add serial communication capa-
A better solution to the phase problems of the multi-
bility
a toprogram without getting down to this hard-
mode fiber is to use a fiber that has a diameter only a few
ware level.
To help you see how to decide which software
times the wavelength of the light being transmitted.
level to use for a given application, we will show you how
Only beams very nearly parallel to the axis of the fiber
we developed a simple terminal emulator program and a
can be transmitted then. This is referred to as single-
program which downloads object code files from the IBM
mode operation. Single-mode systems currently avail-
PC to an SDK-86 board.
able can
transmit data a distance of over 30 km at a rate
of nearly 1 Gbit/s. An experimental system developed by
AT&T multiplexes 10 slightly different wavelength laser A Terminal Emulator Using DOS Function Calls
beams onto one single-mode fiber. The system can and BIOS Calls
transmit data at an effective rate of 20 GbitVs over a dis- As a first step in developing the SDK download program
tance
68ofkm without amplification. we decided to write a simple terminal emulator pro-
One of the main problems with single-mode fibers is gram.
terminal
A emulator program, when run. makes
the difficulty in making low-loss connections with the the PC act like a dumb CRT terminal. Characters typed
tiny fibers. Another difficulty is that in order to get on the keyboard are sent out on an RS-232C line to a
enough light energy into the tiny fiber, relatively expen- modem or some other RS-232C compatible equipment,
sive laser
diodes or other lasers rather than inexpensive and characters coming into the PC on an RS-232C line
LEDs must be used. are displayed on the CRT.
Whenever you want to write a system program such as
FIBER-OPTIC CABLE USES
this, you should first see what DOS function calls are
Fiber-optic transmission has the advantages that the available to do all or part of the job for you. There are
signal lines are much smaller than the equivalent elec- several reasons for this approach. First, DOS function
trical signal
lines, the signal lines are immune to electri- calls are usually very easy to use because they do not

IN IT C0M1
REPEAT
IF CHARACTER READY IN UART THEN
READ CHARACTER
SEND TO CRT
IF KEYPRESSED ON IBM KEYBOARD THEN
READ KEY
SEND TO SERIAL PORT
UNTIL FOREVER

FIGURE 13-20 Algorithm for simple terminal emulator program.

DATA COMMUNICATION AND NETWORKS 461


require you to have extensive knowledge of the hardware
rHIS ROUTINI PRI IVIDES HUE STREAM I/O TO THE COMMUNK Mil INS
details. Second, programs written at the DOS level are l'i IRT M I i IRI IINC 11 I IMF PARAMETERS
(AHi - II INITIALIZI HIE I i IMMUNISATIONS PORT
much more likely to run correctly on another "compati- (AEl HAS PARAMETERS FOR INITIALIZATION
ble" system.If you are going to be writing system pro-
"
gramstheforIBM PC, you should get a copy of the DOS - HAl ID RATI -PARITY-- STI IPBI1 --WORD LENGTH-
Technical Reference Manual. "in X0-NONE 1! 1 in " BITS
i 'ii in ODD 1-2 11-8 BITS
If you need some operation that is not provided by a
DOS function call, then the next step is to check the
available BIOS procedures in the IBM PC Technical Ref- mi j 4i n i
110 1800
erence Manual.
Finally, if neither DOS or BIOS has the
111 '
functions you need, you invoke the 5-minute rule, and
IN Rl ll RN ( ' IN NS '-.I I V5 IN i M.I TO CI IMMI I SI VTUS i Ml
then dig into the Technical Reference Manual to find the %\lli I SEND 111! i HARAC TLR IN (ALi OVER THE I I IMMI i LINI
pieces you need to write the functions yourself. First, we \l 1,1 1 ,1.11 R 15 PRESERVED
i IN I KIT BIT ' i IE AH IS SET IF THE ROUTINE WAS UNABLE
will show you an example using DOS and BIOS calls, Ii i TRANSMIT THE BYTE OF DATA OVER THE LINE
and then an example which manipulates the hardware II BIT "i If -Ml IS Nl IT SET. THE REMAINDER OF AH
IS SLI AS IN -\ STATUS REQUEST, REFLEl EING 111!
directly to obtain greater performance. i I IRRENT STATUS OF THE LINE
(AHl 2 REl EIVE -\ l HARACTER IN IALI FROM COMMO LINE BEFORE
Figure 13-20 shows the algorithm for our terminal
RETURNING TO CALLER
emulator program. Let's see which parts of the algo- < IN EXIT, AH HAS THE CURRENT LINE STATUS As SI 1 BY
THE STATUS ROUTINE, EXCEPT THAT THE ONLY HITS
rithm be
can done with DOS, and which must be done LEFT ON \PI nil ERR( IR HITS (7 J. 1,2,11
with BIOS. II Ml HAS BIT - ON I TIME OUT) THE REMAINING
lllls \R| NOT PREDICTABLE
The relevant DOS function calls are: Mil . MH IS NON ZERO ONLY WHEN AN ERROR
i ii i URRED
IAH i RETURN THE COMMO PORT STATUS IN (AXI
Function Call 2 — The character in DL is sent to the \IMi INTAINS HIE LINE si Ml s
BIT " = TIM! ' il I
CRT and the cursor is advanced one
BIT Ii = TRANS sllll l REGISTER EMPTY
position. BIT i IP \-.- Hi ILDINC REGISTER EMPTY
BIT 4 = BREAK DETEI 1
Bll I FRAMING ERRI IR
Function Call 3 — Waits for a character to be received
BIT 2 PARITY ERRI IR
in the serial port, then returns Ull I I IWPPI '. I RKI >P
BIT ii DAT \ PI Mi\
character in AL.
M i i i'. I MNS IHI Ml HUM STATUS
BIT ' REl EIVED LINI Sll INAI DETEI I
Function Call 4 — The character in DL is output to the P.ll 6 RING P.I H< ATOR
BIT , DATA SI I PI MM
serial port. nil I i LEAR 11 i SEND
Bll l DELTA REl EIVE LINE SIGNAL DETECT
Function Call 8 — Waits for a key to be pressed on the nil 1 IP Ml P.i , [in ,1 RING DETECTOR
Bll I DELTA DAI \ SET READY
keyboard, and then returns the BIT ll -- DELTA CLEAR Ii ) SEND

ASCII code for the key in AL.


(DXI PARAMI IIP INI Hi All'. i, HI Hi II RS232 I \P KLLOWED1

I IA1 '% mm \ RS2 I2.BASE CONTAINS THf BASI YDDRESS Ol III! 8250 I IN I III
Function call 2 looks useful for sending a character to i \K CATION 4 I CONTAINS UP TO 4 RS232 \DDRESSES POSSIBLE
DATA AREA 1 Mill RS232-TIM-OI I BYTI CONTAINS Ol III UNI
the CRT. and function call 4 looks useful for sending a
\ mi I n .p i I'm i H i in i \i 11 = n
character to the serial port. However, the keyboard call OUTPUT
\\ Ml H HI II I i -V i i IRD1NI . Ii i PARMS Ol I Ml
and the serial-read call will not work because they both Ml i ITHERS UNI HANI ,ED
sit in loops waiting for input. In other words, if you call
function 8, execution will not return from that function
until a key is pressed on the keyboard. If execution is in
the function 8 loop, characters coming into the serial
port will not be read. What is needed here are proce-
dures which
allow polling to go back and forth between
I I VBI OKI 1 L'I I
the keyboard and the serial port receiver. Also needed is llllsl ROUTINES PROVIDE KEYBOARD SUPPORT

the least painful way to initialize the serial port. Let's see INPUT
Alii 0 READ THE NEX1 \SCII CHARACTER STRUCK I Rl IM 11 II KEYBOARD
what BIOS has to offer. II 11 RN 1IIL Rlsuil IN i \[ SI v. i i H i| IN (AHI
% III! I s|| nil Z FLAG TO INDICATE IF AN A5CII CHARACTER 15
Figure 13-21a shows the header for the IBM PC BIOS,
V. Ml Mill EO Bl Rl \\ <
INT 14H procedure. This procedure will do one of four IZFl = 1— NO CODE AVAILABLE
IZF1 ii CODI is w ULABLE
functions, depending on the value passed to it in the AH
IF Zl ii THE NEXT CHARACTER IN THE BUFFER TO BE READ
register. If AH = 0 when the procedure is called, the byte is in \\ \NU HIE ENTRY REMAINS IN nil Bl HU-
MPRETURN
2 THE CURRENT SHIFT STATUS IN U, REGISTER
in AL is used to initialize the serial port device as shown. THE Bll s| l I l\i ,S u IP 11 lis i ODE ARE INDICATED IN
If AH = 1 . then the character in AL will be sent out from THE IOI Mis H ip KB_FI M
I H MPI I
the serial port. Likewise, if AH = 2, then a character will v. -.< nil i M)i IVI i INLY \\ v.u FLAGS CW II
\ll REGISTERS PRESERVED
be read in from the serial port and left in AL. Finally, if
AH = 3 when the procedure is called, the status of the
(b)
serial port will be returned in AH and AL. The first of
these four options solves the initialization problem. The FIGURE 13-21 Header for IBM PC BIOS calls, (a) INT 14
last (AH = 31 supplies most of the solution for the prob- serial communication procedure, (b) INT 16 keyboard
lem of
determining when the UART has a character access procedure.

462 CHAPTER THIRTEEN


; TERMINAL EMULATOR PROGRAM FOR SDK-86
; This program sends characters entered on the IBM PC to the C0M1
; serial port at 600 baud, and displays characters received from the
; C0M1 serial port on the CRT.
PAGE ,132

STACK_HERE SEGMENT STACK


DW 100 DUP(O)
STACKTOP LABEL WORD
STACK HERE ENDS

CODE HERE SEGMENT


ASSUME CSrCODE HERE, SS : STACK HERE

START: MOV AX , STACK_HERE ; Initialize stack segment


MOV SS, AX
MOV SP, OFFSET STACK_TOP
TOP; Initialize stack pointer
MOV AH, 00 ; Initialize C0M1
MOV DX , 0000 ; Point at C0M1
MOV AL, 01 1001 1 IB ; 600 Bd , no parity, 2 stop, 8-bit
INT 1<+H via BIOS INT 1<+H
STI Enable interrupts
CHKAGN: MOV DX , 0000 ; Point at C0M1
MOV AH, 03 i Check for character from SDK
INT l^H
TEST AH, 01H ; See if char waiting in UART
JN2 RDCHAR ; I f char , read i t
JMP KYBD ; else, go look for keypress
RDCHAR: MOV AH, 02 ; Read character
INT 1<^H from UART to AL
MOV DL, AL ; Character to DL for DOS call
MOV AH, 02H ; DOS call number for CRT display
INT 21H Do DOS call
KYBD:
MOV AH, l ; Check if key has been pressed
INT 16H using BIOS call
JNZ RDKY ; If keypress, read key code
JMP CHKAGN ; else look for more from SDK
RDKY: MOV AH, 0 ; Read key code
INT 16H usi ng BIOS call
MOV DX , OOOOH ; Point at C0M1 serial port
MOV AH, 01
INT 14H Send character to UART with BIOS
JMP CHKAGN ; Go look for another char from UART
or from keyboard

C0DE_HERE ENDS
END START
FIGURE 13-22 Simple 300/600-Bd terminal emulator program.

ready to be read. Bit 0 of the status byte returned in AH INT 16H procedure which accesses the keyboard. As you
will be set if the UART contains a character ready to be can see in the figure, this procedure supplies three dif-
read. If a character is ready, it can be read in and sent to ferent functions,
depending on the value passed to it in
the CRT. If no character is present, the program can go AH. AH = 0 returns the code for a pressed key in AL.
check to see if a key on the keyboard has been pressed. AH = 1 returns the zero flag = 0 if a key has been
Figure 13-2 lb shows the header for the IBM PC BIOS. pressed and the code is available to be read. AH 2

DATA COMMUNICATION AND NETWORKS 463


INITIALIZE EVERYTHING
REPEAT
IF KEY PRESSED THEN
READ KEY
IF KEY = 0 THEN
QUIT
ELSE IF KEY = L THEN
DOWNLOAD BINARY FILE FRON DISK 10 SDK-H6
ELSE SEND CHARACTER FOR PRESSED KEY TO SDK-86
IF UART BUFFER HAS CHARACTER THEN
SE ND CHARACTER TO CRT
UNTIL QUIT

FIGURE 1 3-23 Algorithm for download program.


(a) Pseudocode, (d) Flowi hart

causes the procedure to return the shift status in AL.


Bit D6 of this byte will be set if the shift key is depressed.
Calling the INT 16 procedure with AH = 1 solves the
problem of polling the keyboard without sitting in a loop
the way the DOS function call does. The zero flag can
simply be checked upon return from the INT 16 proce-
dure, and
if no key is ready, execution can go check the
UART again. If a key code is ready, it can be read in with
a DOS call or another INT 16 call and sent to the UART.
Figure 13-22 shows a simple terminal emulator pro-
gram whichuses the procedures we have described. The
program follows the algorithm almost line by line. Re-
member previous
from chapter examples that BIOS pro-
cedures
called
are directly by an INT (number) instruc-
tion, and
DOS calls are done by putting the function
number in AH and doing an INT 21 H instruction.
The program in Figure 13-22 works well at 300 Bd or
600 Bd. You can connect the serial port on an IBM-
compatible computer to the serial port of an SDK-86
board as shown in Figure 13-10b and use this program
to communicate with the board. However, if you try to
use the program at 1200 or 2400 Bd. the first character
of each line of characters received from the SDK-86 or
other source will be lost. It took some work to figure out
why this is the case, because with a processor as fast as
the 8088 in the IBM PC. even 4800-Bd communication
should be no problem. The problem is in the procedure
which sends a character to the CRT. After a carriage re-
turn sent
is to the CRT. the display on the screen is
scrolled up one line. To avoid flicker, however, the
screen is not scrolled until the next frame update. Since
the frame rate for the monochrome display is 50 Hz, the
return from the display procedure may take as long as
20 ms. One or more characters that come in during this
time will be lost. The next section shows how we solved
this problem in a high-speed download program.

IBM PC to SDK-86 Download Program


The main purpose of the program described in this sec-
tiontois allow the binary codes for programs developed
on an IBM PC compatible computer to be downloaded
through an RS-232C link to an SDK-86 board. The pro-
gram alsofunctions as a dumb terminal so that down-
loaded programscan be run. memory contents dis-
played, registers
and examined by typing the

464 CHAPTER THIRTEEN


appropriate keys on the computei keyboard Figure around to the (UK N DISPLA\ procedure again, the
13 23 shows the overall algorithm for the program. The i harai tei will then be read from ihc buffer and sent to
in. mi difference between tins algorithm and the one foi the display rhe XMI1 | edure is used al several places
the dumb terminal In Figure 13-20 is the addition of the In the program to send characters to the UART for
actions when the letter Q or the letter I is typed. How transmission to the SDK.
evei . we Implemented the algorithm in a different waj In The LOAD II procedure, which is railed when the
ordei iu solve the speed problem described in the previ uset pusses the I key on the PC, prompts the user to
mis section and to show you some very Important pro enter the name of a binary file, converts the binary file to
gramming techniques. a form the SDK can digest, and sends the result to the
Figure 13 24 shows the complete program. The data SDK through the UART. Now let s look at the details ol
segment declared at the start oi the program contains the initialization and the lour procedures
buffers, flags, and the messages used in the program.
INITIALIZATION
We will refer to these as needed throughout the discus-
sion. The
mainline pari ol the program which follows The UART used on the IBM asynchronous communica
ilus is only a little over a page long and consists mostly tions adaplei hoard is an INS8250. II the board is con
ol various initializations. Four procedures, si RIAL IN. figured as system serial port COM1, the interrupt out-
(UK N DISPLAY, XMIT, and LOAD IT, are used to do put fromI his device is connected to the IR4 inpul ol an
most of the work. Alter we give an overview, we will ex- 8259A priority interrupt controller on the main PC
plaindetail
in how each of these five parts work. board oft lie IBM computer. The major part oi the initial-
ization here
involves gelling the 8250 initialized and
OVERVIEW
setting up the interrupt mechanism. Remembei from
The procedure SERIAL IN reads in characters received previous discussions that when an 8259A receives an
from the SDK-86 by the IBM serial board on an interrupt interrupt on an IK input th.it is unmasked, it sends a
basis and puts the characters in a buffer. The procedure specified interrupt type to the processor. The 8259A is
CHK N DISPLAY, when called, cheeks the buffer to see if initialized by the BIOS so that type 8 will be sent In an
it contains any characters. If the buffer contains a char- IRO input. Therefore, for an IR4 signal from the LJART.
acter,procedure
the sends it to the CRT. If the buffer is the 8259A will send type OCH to the processor. The
empty, the procedure simply returns. Now. take a look processor multiplies the type number by 4 and noes to
at the mainline section of the program starting at the that address to get the starting address of the service
label THERE, to see how these two procedures. together procedure for that interrupt. The recommended way of
with XMIT and LOAD IT implement trie algorithm in putting the IP and CS values for the procedure in these
Figure 13-23. absolute memory locations is with the DOS function call
After interrupts are enabled, the BIOS INT 16 proce- 25H. To use this call, the interrupt type number is put
dureused
is to see if a key on the PC has been pressed. If in AL, the CS value in the DS register, and the IP value
a key has been pressed, then the BIOS INT 16 procedure in the DX register as shown in Figure 13-24.
is called again to read in the code for the pressed key. An The 8259A itself is mostly initialized by the BIOS
IF — THEN — ELSE decision structure is then used to when the system is turned on. However, since the UART
quit the program and return to DOS, go download a bi- is connected to IR4 of the 8259A, that input has to be
nary file,
or simply send the character to the SDK-86. unmasked. To do this the current contents of the 8259A
If the first call of the BIOS INT 16 procedure does not interrupt mask register are read in from address 21H.
indicate that a key has been pressed, then the The bit corresponding to IR4 is then ANDed with a 0 to
CHKLN DISPLAY procedure is called. If the UART inter- unmask the interrupt, and the result sent back to the
rupt procedure. SERIAL IN. has read in a character interrupt mask register. Using this approach saves the
from the SDK and put it in the buffer, this procedure system environment. It is important to do this rather
will send the character to the CRT and return to the than just sending out a control word directly, so that
mainline. If there is no character in the buffer, you don't disable other system functions. In this sys-
CHK N DISPLAY will simply return to the mainline. tem, for
example, the system clock tick is connected to
Once back in the mainline, execution loops back to IRO and the keyboard is connected to IR1. so these would
again see if a key on the PC has been pressed. The inter- be disabled if you accidentally put is in these bits of the
rupt andbuffer approach used to read and hold the control word.
characters coming in from the SDK solves the timing Initializing the 8250 UART is next. Figure 13-25
problem we described for the program in Figure 13-22. shows the internal addresses and the bit formats for the
Here's how. control words we need here. The first part of the initiali-
The problem with operating the program in Figure zation
theis baud rate, parity, and stop bits. Since this
13-22 at over 600 Bd is that characters which come into step requires several words to be sent, we simply used
the UART while the INT 10H procedure is scrolling the the BIOS INT 14H procedure to do it. (NOTE: Wc initial-
CRT display are missed. The program in Figure 13-24 ize the8250 here for 4800 Bd. so the baud-rate jumper
reads characters from the UART on an interrupt basis. on the SDK-86 must be set for this baud rate.)
Even if the PC is in the middle of the INT 10H procedure The next task we need to do here is enable the desired
or some other procedure when the UART has a character interrupt circuitry in the 8250. In order to do this, the
ready, the interrupt procedure will read the character DLAB bit of the line control word must first be made a 0.
and put it in the buffer. When execution loops back Note that this is done by reading in the line control

DATA COMMUNICATION AND NETWORKS 465


; TERMINAL EMULATORAND DOWNLOAD
PROGRAMFOR SDK-86
;Thi5 program allows an IBM PC compatible computer to opei ate as a 4800-Bd
; dumb terminal for use with an SDK-86 board. The program also allows
; binary files to be downloaded from a disk in the PC to RAM in the SDK-86
i through the COH1serial port on the PC.
PAGE ,132

DATA HERE SEGMENT


SIGN ON DB 'SDKDMP PROGRAM
'.ODH.OAH
DB ' BY DOUGLAS V. HALL' ,0DH,0AH
DB 'COPYRIGHT - McGraw-Hill Book Co., 1986' .ODH.OAH
DB ODH.OAH
DB 'Press RESETkey on SDK-86 to get Monitor prompt.'
DB ODH,OAH,ODH,OAH.21H
QUEUE DB 1000 DUP(O) ; Circular buffer

HEAD_POINTER DW 0 ! Next character to read out of queue

TAIL.POINTER DW0 j Next location to put char in queue


CHARCOUNTER DB 0 i Used to count number of char sent to CRT

TIHE_OUT_HESS DB ' Transmit Timeout - Check Hardware ', ODH, OAH


PROMPT DB ' Please type in binary filename', ODH, OAH
DB ' Filename format is d:path filename.bin', ODH, OAH
DB 21H ; String terminator

FILE NAME DB 10 DUP!0) ; Space for user entered filename

ERR_MESS_PQINTERS
DM 0 i Dummy,no ERR_NESS0
DH OFFSETERRJESS1
DM OFFSET ERRMESS2
DU OFFSETERRJ1ESS3

ERR_MESSi DB 'INVALID FUNCTIONNUMBER',ODH, OAH, 21H


ERR.MESS2 DB 'FILE NOT FOUND', ODH, OAH, 21H
ERRJ1ESS3 DB 'PATH NOT FOUND', ODH, OAH, 21H

FILEJUF DB 2018 DUP(O) ; Buffer for bin file read from disk

HEADER DB 53H,20H,30H,3OH,30H,30H.3AH,30H
DB 31H,30H,30H,2CH i SDK-86 Substitute Command

DATA_HERE
ENDS

STACK_HERE
SEGMENTSTACK
DH10OHDUPiO)
STACK.TOPLABELWORD
STACK_HERE
ENDS

CODE_HERE
SEGMENT
ASSUME
CS:CODE.HERE,
DS:DATA_HERE,
SS:STACK_HERE

START: MOV AX, STACK_HERE ; Initialize stack segment


MOV SS, AX
MOV SP. OFFSETSTACKJOPi Initialize stack pointer
MOV AL. OCH ; Initialize interrupt vector for UART
MOV BX. SEGSERIALJN ; using DOSfunction call 25H

FIGURE 1 5-24 Program to download object code programs from IBM PC to


SDK-86 and allow PC to function as a "dumb" terminal for the SDK-86.

466 ( HAPTER THIRTEEN


HOV DS. BX
MOV DX, OFFSETSERIALJN
MOV AH. 25H
INI 21H
MOV AX, DATA_HERE ; Initialize DS reqistei
MOV DS, A*
MOV HEADPOIMTER, 0 ; Initialise circular buffer pointers
MOV TAIL POIN1ER, 0
lunmask 8P59A IR4
IN ftL, 21H ; Read 8259A I MR
AMD AL, OECH i Unmask IR<t
OUT 21H. AL
; initialize 8250 UART baud rate, etc.
MOV AH. 00 ; Initialize C0M1
MOV DX, 0000 ; Point at COfli
MOV AL, 1100011IB i H800 Bd.No parity. 2 stop,8-bit
INT IhH ; via BIOS INT 1W
ienable 8250 RxRDY interrupt
MOV DX, 03FBH I Point at 8250 line control port
IN AL, DX i Read in line control word
AND AL, 7FH i Set DLAB= 0
OUT DX, AL ! Send line control word back out
MOV AL. 01H i Value to enable RxRDY interrupt
MOV DX, 03F9H ; Point at interrupt enable register
OUT DX. AL i Enable RxRDYinterrupt
MOV AL, OBH i Assert 8250 0UT2, RTS, DTR byte
MOV DX, 03FCH ', Point at modem control reg in 8250
OUT DX, AL ! Send to 8250
STI '. Enable 8086 interrupts
{main program starts here
MOV DX. OFFSETSIGNJJN ; Send sign on message to CRT
MOV AH. 09H ; with DOS call
HOV BH, 0
INT 21H
,look for response from SDK
THERE: MOV AH, 1 ! Check if key has been pressed
INT 16H
JNZ RDKY ; If keypress, go read key code
CALL CHK_N DISPLAY ; See if char in circular buffer from
; UART and send it to CRT if there
JMP THERE ! Go look for keypress or char from UART
RDKY: MOV AH, 0 , Read key code
INT 16H
CMP AL. 5IH ; See if quit costmnad
JNE NXCHK ! No, go check if load command
JMP QUIT i Yes. go exit to DOS
NXCHK: CMP AL, 4CH ; Check if load command
JNE SENDIT ". Ho, go send char to SDK
CALL LOADIT ; Yes. go load file
JMP THERE ; Go wait for next command
SENDIT: CALL XMIT ! Char not Q or L. send char to SDK-86
JMP THERE i Go wait for next command
SUIT: IN AL, 21H
OR AL, 10H i Mask UART interrupt
OUT 21H, AL ! to prevent it from disrupting DOS

Figure 13-24 (continued)

DATACOMMUNICATION AND NETWORKS 467


MOV AL, 0 Exit to DOS using DOS function call <tCH
HOV AH, <iCH
INT 21H
HOP

SERIAL.IN PROC PAR


STI Interrupts back on for keyboard, etc
PUSH AX
PUSH BX
PUSH DX
PUSH DI
PUSH DS ; Save DS of interrupted ptograffi
HOV AX, DATA_HERE ! Install DS needed here
HOV DS, AX
HOV DX, 03F8H ; Receiver buffer address for 9250
IN AL, DX ; Read character
HOV DI. TAIL POINTER ; Get current tail pointer value
INC Dl ; Point to next storage location
CflP DI. 1000 ; Coepare with queue length to see if tine
; to wrap around
INE FULCHK ; No, go check if queue full
HOV DI, 00 ; Yes, set DI for wraparound to start
FULCHK:
; CUP DI, HEAD_POINTER; Check for full queue
IE NO_HORE ; Full, return without writing char
HOV BX. TAIL_POINTER ! Not full, point at location to put char
MOV OUEUEIBX], AL i Character to circular buffer
HOV TAIL.POINTER,DI ', Tail pointer to next location
NO_riORE:
HOV AL, 20H ; Non-specific End Of Intenupt cosiiand
00 T 20H, AL ; to 8259A
POP DS
&0P DI
POP DX
POP BX
POP AX
IRET
SERIAL.
.IN ENDP

5ISPLAY
CHK.NJ PROC NEAR
PUSH BX
IN AL, 21H
OP AL. 10H ". Disable 8259A IR<t during critical region
00 T 21H, AL ; by sasking bit k of int iask register
MOV DI, HEAD.POINTER
CUP DI, TAIL.POINTER ; Is queue empty 7
JE NOCHAR ; Yes, just return
HOV AL, 8UEUEIDI] ; No, get char fron gueue to AL
INC DI ; Point DI at next byte in queue
OOP DI, 1000 ', See if ti»e to wrap pointer around
JNE OK ! No, go on
MOV DI, 00 ; Yes, wrap pointer around
Ok: HOV HEAD,POINTER,
DI ; Store new pointer value
PUSH AX ', Save character in AL on stack
IN AL, 21H
AND AL, OECH ; Enable IR't interrupt so new char in 8250

Figure 13-24 (continued)

468 CHAPTER THIRTEEN


OUT E1H. AL can interrupt INT 10H
POP AX Get character back fron stack
MOV AH, \h Use BIOS INT 1OH procedure to send to CRT
MOV BH, 0
INT 10H Send char to CRT
DEC CHARCOUNTER Decrement count of char to be sent to CRT
NOCHAR: IN AL. 21 H
AND AL, OECH End of critical region. Enable IR*t by
unmasking bit <r in I MRof 8259A so new
OUT 21H. AL ; char in UARTcan interrupt
POP BX
RET
CHK N DISPLAY ENDP

iSend character in AL to C0M1serial port after checking if


; handshake signals asserted
! INPUTS: character in AL
; OUTPUTS:character in AL, CY flag set if xmitter not ready

XHIT PROC HEAR


PUSH BX
PUSH CX
PUSH DX
PUSH AX ; Save char
MOV CX,0
RECHK: MOV DX, 03FEH ; Check CTS and DSR asserted
IN AL, DX
AND AL, 30H
CMP AL, 30H
JNE NOT.READY
MOV DX, 03FDH ', Check if transmitter buffer ready
IN AL, DX
AND AL, 20H
JZ NOT READY
POP AX i Get character back
MOV DX, 03F8H ; Send to UART
OUT DX, AL
CLC ; Clear carrv to indicate char sent
JMP DONE
NOT READY:
LOOP RECHK i Check for status ready CX times
MOV DX, OFFSETTIME_OUT_MESS; If still not ready
MOV AH. 09H ; send error message
MOV BH, 0
INT 21H
STC Set carry to indicate xmtter not ready
POP AX Restore registers
DONE: POP DX
POP CX
POP BX
RET
XMIT ENDP

SLOADIT - Down-load procedure

Figure 13-24 (continued)

D\l \ ( ( >\l\U Ml MK IN \M> M l\V( IKKS 469


; Prcapts user to enter naae of binary file, then reads file froa disk
; to a buffer in aeaory. The file is converted to the ASCII character fors
! required by the SDK-86, and sent to an SDK-86 board via the C0M1 serial
; port. Replies froa the SDK-86 are displayed on the CRTas received.

LOAD,IT PROCHEAR
PUSHBX
NOV DX. OFFSET PROflPT Send aessage to CRT telling user
110V AH, 09H to enter filenaae with DOS function
NOV BH. 0 call 09H
INT 21H
NOV DX, OFFSETFILE.NAHEPoint at filenaae buffer
NOV FILENAME,40 Hake first byte of buffer = max chars
NOV AH, OAH DOS function call nuaber to
\nr 21H read in filenaae froa keyboard
NOV BL. FILEJIAHE+i Set length of file naae froa buffer
ADD BL, 02 Add 2 to reach carriage return at end
NOV BH. 00 BX now has offset of CR at end of file tiaae
NOV FILEJ4AMEIBX3,00 Replace ODH at end of file naae with 00H
NOV DX. OFFSETFILE.NAMEPoint at start of file naae buffer
DX, 02H Move pointer over string length bytes
NOV AL, 0 Open file for read
NOV AH, 3DH and get file handle with DOS 3DH call
[NT 21H
Check for file error
JNC FILEOK No carry, file opened properly
ROL AX, 1 Multiply error code in AXby 2
MOV BX, AX ; Copy to BX for use as pointer
NOV DX, ERR_HESS_PQINTERS[8XJGet pointer to desired error
Hoy BH. 0 ; aessage froa table to DX
NOV AH, 09H Use DOS function call 09 to send
[NT 21H error aessage to CRT
NOV DL, ODH Send carriage return to CRT
NOV AH, 02H with DOS function call 02H
I'll 21H
JMP EXIT1 Return to look for next coanand fro* user
Read binary file froa disk to buffer in aeaory
FILEOK: MOV BX. AX File handle to BX
PUSH BX Save file handle for file close
NOV CX. 2048 ! Set aaxiaua nuabei of char to read

NOV DX, OFFSETFILEJUF Point at buffer to store char read in


NOV AH, 3FH : Read disk file
INT 21H
POP BX : Set back file handle for close
PUSH AX Save length of file returned by 3FH
NOV AH, 3EH : Close disk file with DOS 3EH call
INT 2!H
iSEND SUBSTITUTE COMMAND
TO SDK86
NOV BX, OFFSET HEADER Point at string buffer
MOV CX. 000CH ! Nuaber of characteis to send to SDK
NEXT1: MOV AL, IBXJ Set a character to be sent
TR/2: CALL XMIT : Character to C0M1
JC EXIT1
INC BX i Pointer to next location in buffer
LOOP NEXT1 Loop until all sent
MOV CHAR_COUNTER,
11H Nuaber of characters to send to CRT
Figure 13-24 ^continued)

470 CHAPTER THIRTEEN


M0RE1: Cftl I CHK N DISPLAY ; Characters to CRT
DEI CHAR COUNTER ', See if all sent
.in: MORE
T
;SEND FIRS CODE BY1E TO SDK86
pup AX ; Get back length of f i le
MOV CX, AX i Use CX as counter
III IV BX. OFFSETFILE.BUF ! Point at start of object code file
NXTCHR NOV DL, [BX] J Set a character froa file buffer
AMD DL, OFOH i Mask lower nibble
PUP DL, 1 ; Move to lower nibble position
POP DL, 1
pop DL, I
ROR DL, 1
IMP DL, OAH ; Convert to ASCII
JAE ADD37
ADD DL, 30H
IMP SEND1
ADD37: ADD DL, 37H
SEND1: HOV AL, DL ; Position character for send
CALL XMIT ; Send upper nibble of byte to SDK
JC EXIT!
HOY DL, [BX] ; Get char again and sake ASCII for
AND DL, OFH ; Ioh nibble
LlIP DL, OAH
JAE ADDHI
ADD DL, 30H
JtIP SEND2
ADDHI: ADD DL, 37H
SEND2: MOV AL, DL ; Position for send
CALL XHIT ; Send ASCII for low nibble to SDK
JC EXIT1
DEC CX ; Check if all bytes sent
JZ EXIT ; Yes, done, send carnage return
MOV AL, 2CH < Else load consa
CALL XMIT ; Send to SDK
JC EXIT1
HOV CHARCOUNTER,OEH ; Nuaber of characters to send to CRT
H0RE2: CALLCHK_N_DISPLAY i SDKecho aessage to CRT
CUP CHAR.COUNTER,
0 ; See if all of aessage sent to CRT
JNE HORE2
INC BX ; Point to next byte in binary file
J IIP NXTCHR ; Send next code byte
EXIT: HOV AL. ODH ; Load carriage return
CALL XMIT ; Send to SDK
EXIT! : POP BX
RET i Go look for SDK answer and next cowand

LOAD
J 1 ENDP

CODE.HERE
ENDS
END START

Figure 13-24 (continued)

word, resetting the desired bit. and sending the word the interrupt enable register at address 03F9H. As
out again. This preserves the previous state of the rest of shown in Figure 13-25b. the 8250 has four different
the bits in the line control register. As shown in Figure conditions which can be enabled to assert the interrupt
13-25b. with DLAB = 0. a control word which enables output when true. In cases where multiple interrupts
the enable-receive line status interrupt can be sent to are used, the interrupt identification register can be

DATA COMMUNICATION AND NETWORKS 471


I/O DECODE (IN HEX)
REGISTER SELECTED DLAB STATE
PRIMARY ALTERNATE
ADAPTER ADAPTER

3F8 2F8 TX BUFFER DLAB 0 (WRITE)


3F8 2F3 RX BUFFER DLAB=0(READ)
3F8 2F8 DIVISOR LATCH LSB DLAB 1
3F9 2F9 DIVISOR LATCH MSB DLAB 1
3F9 2F9 INTERRUPT ENABLE REGISTER DLAB-X

3FA 2FA INTERRUPT IDENTIFICATION REGISTERS DLAB X


*B 2FB LINE CONTROL REGISTER DLAB=X
3FC 2FC MODEM CONTROL REGISTER DLAB X
3FD 2FD LINE STATUS REGISTER DLAB=X
3FE 2FE MODEM STATUS REGISTER DLAB X

INTERRUPT ENABLE REGISTER (IER) MODEM CONTROL REGISTER (MCR)

HEX ADDRESS 3F9 DLAB HEX ADDRESS 3FC

BIT 7 6 5 4 3 2 BIT 7 6 5 4 : 0

1 ENABLE DATA I— DATATERMINALREADY(DTR)


AVAILABLE INTERRUPT
REQUEST TO SEND (RTS)
1 ENABLE TX HOLDING REGISTER
EMPTY INTERRUPT
- OUT 1
1 ENABLE RECEIVE LINE
STATUS INTERRUPT - OUT 2
1 ENABLE MODEM STATUS
.. Ll i, ,p
INTERRUPT

- 0

LINE STATUS REGISTER (LSR) MODEM STATUS REGISTER (MSR)

HEX ADDRESS 3FD HEX ADDRESS 3FE


5 4 3 2 10

DATA READY (DR) - DELTA CLEAR TO SEND (DCTS)

- DELTA DATA SET READY (DDSR)


OVERRUN (OR)
- TRAILING EDGE RING
PARITY ERROR (PE)
INDICATOR (TERI)
FRAMING ERROR (FE) - DELTA RX LINE SIGNAL
DETECT (DRLSD)
BREAK INTERRUPT IBI)
- CLEAR TO SEND (CTS)
TRANSMITTER HOLDING REGISTER
- DATA SET READY (DSR)
EMPTY (THRE)
- RING INDICATOR (Rl)
TX SHIFT REGISTER EMPTY (TSRE)
- RECEIVE LINE SIGNAL
DETECT (RLSD)

(e)

FIGURE 15-25 8250 internal addresses, registers, and control words, (a) System
addresses, (b) Interrupt enable register, (c) Modem control register, (d) Line
status register, (e) Modem status register.

read to determine the source of an interrupt. For this CD inputs of the UART. The OUT2 signal from the 8250
application we are only using the enable receive line sta- must be asserted in order to enable a three-state buffer
tus interrupt, so a 1 is put in that bit. The final step in which is in series with the interrupt signal from the
the 8250 initialization is to assert the RTS, DTR, and 8250 to the 8259A.
OUT2 output signals. As shown by the circuit connec- When you are working out an initialization sequence
tionsFigure
in 13-10a, asserting RTS is necessary to such as this, read the data sheet carefully, and check
assert the CTS input so the UART can transmit. Like- out the actual hardware circuitry for the system you are
wise. asserting DTR is necessary to assert the DSR and working on. We missed the OUT2 connection the first

472 CHAPTER TEllKTttN


time through. Inn .1 second look .11 the schematii The buffei empty condition is Indicated when th
communications board showed thai 11 was necessary to pointei is equal to tin tail pointer It the buffer is not
assert ibis signal. Now let's sec how the procedure lull, the charactei read in from i lie UAR1 is written to
which reads characters from the UAR1 woi ks. ihi' but lei . .mil iIh pointer to the next available 1
In the buffei is transferred from thi registei lolhemem
Illl si RIA1 IN PROCEDURI or> lo« ation called TAIL POINTER. Finally, bi
turning, an end-of-interrupl command must bi sent to
The purpose oi this Interrupl procedure is to read chai
the 8259A in resel bit 1 of the Intel rupl m
acters in from the UART and put them in .1 buffei Note
In summarize the op< ration ol a circulai buffer, then,
thai since this is ,111 interrupl procedure which can
bytes are put iii ai the i. ul pointei location ami read out
occui .1! .my time, it is important to save the DS registei
from the head pointei location. The bullet is considered
of the interrupted program and load the DS registei
lull when i he I ail pom let reaches one less than the head
wiib DATA HERE, the value needed for ibis procedure.
pointer. An empty buffer is indicated by head pointei
The buffer used here is .1 special type ol queue called a
equal in tail pointer.
circular buffer. Figure 13 26 .111cm pis to show how this
works One pointer, tailed the TAIL POINTER, is used
to keep track oi where the nexl byte is to be written to THI: CHK N DISPLAY PRO( EDURE
the buffer. Another pointer called the HEAD POINTER
The main purpose ol this procedure is In lead a i hai.u
is used to keep track oi where the nexl character i<> be
ler from the Circular buffei and send it lo the CRT with
read from the buffer is located. The buffer is circulai
the BIOS INT I0H procedure. In order to make sure the
because, when the tail pointer reaches the highest loca-
procedure operates correctly under all conditions, how
tion the
in memory space set aside for the butler, it is
ever, we mask the IR4 interrupl in the 8259A righl at
"wrapped around" to the beginning of the buffei again,
the starl so thai a 11 interrupt from the UART eat mot call
The head pointer follows the tail pointer around the cir-
the SERIAL IN procedure while CHK N DISPLAY is using
cle ascharacters are read from the butler. Two checks
the head and tail pointers. This is necessary to prevent
are made on the tail pointer before a character is written
the SERIAL IN procedure from altering the values ol the
to the butter.
pointers in the middle of CHK N DISPLAY'S use ol them
First the tail pointer is brought into a register and
and causing the CEIK N DISPLAY procedure to make the
incremented. This incremented value is then compared
wrong decisions about whether the buffer is empty, for
with the maximum number of bytes the buffer can hold.
example. The group of instructions which you need to
II the values are equal, the pointer is at the highest ad-
protect from interruption is called a critical region. It is
dressthe
in buffer, so the register is reset to zero. After
important to keep critical regions as short as possible so
the current character is put in the buffer, this value will
that interrupts need not be masked for unnecessarily
be loaded into TAIL POINTER to wrap around to the
long times. Note that we masked the IR4 interrupt input
lowest address in the buffer again.
of the 8259A rather than disable the processor inter-
Second, a check is made to see if the incremented
rupt. This
was done so that the keyboard and the timer
value of the tail pointer is equal to the head pointer. If
interrupts, which have nothing to do with the critical
the two are equal, it means that the current byte can be
region in this procedure, can keep running
written, but that the next byte would be written over the
Once the critical region is safe, a check is made to see
byte at the head of the queue. In this case we simply if there are any characters in the buffer. If not, the
return to the interrupted program without writing the 8259A IR4 input is unmasked, and execution returned
current character into the buffer. Actually this wastes a to the calling program. If a character is available in the
byte of buffer space, but it is necessary to do this so that
buffer, the character is read out and the head pointer
the pointers have different values for this buffer-full updated to point to the next available character. If the
condition than they do for the buffer-empty condition. pointer is at the top of the space allotted for the buffer,
the pointer will be wrapped around to the start of the
buffer again. As soon as the character is read out from
the buffer and the pointers updated, an interrupt from
the UART cannot do any damage, so we unmask IR4.
The BIOS INT I0H procedure is then used to send the
character to the CRT. If a UART interrupt occurs during
the INT 10H procedure, the SERIAL IN procedure will
read the character from the UART and return execution
to the INT I OH procedure. This short interruption pro-
ducesnoticeable
no effect on the operation of the INT
I0H procedure, and it makes sure no characters from
the UART are missed. After the INT 10H procedure fin-
ishes,
character-sent
a counter is decremented and exe-
cution
returned
is to the calling program. This counter
FIGURE 13-26 Diagram showing how circular buffer counts the number of characters actually sent to the
pointers wrap around at the top of allocated buffer CRT rather than just the number of times the
CHK N DISPLAY procedure is called. This allows the
space.

DATA COMMUNICATION AND NETWORKS 473


procedure to be called over and over again until a given through how the pointer gets to DX for the 09H function
number of characters are sent to the CRT. call which is used to display the error message. If the file
was opened correctly, then the binary file is read in from
THE XMIT PROCEDURE a disk with the DOS function call 3FH. and the file is
closed with the DOS function call 3EH as we described
After first checking to see if the handshake signals and
in Chapter 12.
the transmitter buffer are ready, this procedure sends a
The next section of the procedure sends the substi-
character to the 8250 UART. The status of the DSR input
tute command to the SDK-86 to get it ready to receive
and the CTS input are available as bits 5 and 4 respec-
the binary file. The SERIAL IN interrupt procedure will
tively,
theof modem status word of the 8250. For an IBM
read the echo of the command sent back from the SDK
PC with the serial board configured as COM1. the ad-
and put it in the circular buffer. To display this echo on
dressthis
of register will be 03FEH. The transmitter-
the CRT. we load CX with the number of characters in
buffer-ready status bit of the 8250 is available as bit 5 of
the echo message, and enter a loop which calls the
the line status register at address 03FDH. This bit will
CHK N DISPLAY procedure over and over until all of the
be high when a character can be sent to the internal
SDK response is sent to the CRT. Now comes the bit-
buffer for transmission. Rather than having the pro-
fiddling section of the procedure.
gram hang
in a loop checking the status signals forever,
The SDK-86 requires that each nibble of a program
if any one of them is not ready, we send an error mes-
code byte be sent in as the corresponding ASCII charac-
sage andexit after a specified number of tries. The CX
ter. The
code byte 3AH for example must be sent as 33H
register is loaded with the desired number of tries, and
(ASCII 31, followed by 41H (ASCII A). You can work your
counted down after each loop through the status check.
way through this section to see how the conversion is
After the error message is sent to the CRT with the DOS
done if you need to use it in some other program. After
09H function call, the carry flag is set to indicate that a
the ASCII characters for each code byte are sent, the
character could not be sent. Execution is then returned
ASCII code for a comma is sent as required by the
to the section of the program from which XMIT was
SDK-86. The SERIAL IN procedure reads in the SDK
called. After each call of XMIT in the program, a JC in-
reply and puts it in the circular buffer. A loop containing
struction
used is to send execution back to look for the
a call to the CHK N DISPLAY procedure is used to send
next user command if the transmitter was not ready for
the SDK reply to the CRT. After the ASCII codes for the
some reason.
final byte are sent to the SDK, a carriage return is sent
to the SDK to terminate the substitute command. Exe-
THE LOAD IT PROCEDURE
cution then
returns to the mainline program and then
In response to a filename entered by the user, this pro- to the section of the program which waits for the user to
cedure reads
a binary file from disk to a buffer in mem- enter another command.
ory, converts each byte to the form needed for sending to
the SDK, and sends the result to the SDK-86. SDK re- CONCLUSION
sponses
displayed
are on the CRT.
At the start of the procedure. DOS function call 09H is
This program was written to do a specific job and to
used to send a prompt message to the user on the CRT.
demonstrate some important programming concepts.
DOS function call OAH is then used to read in the file-
Space limitation prevented us from making the program
as "friendly" as we would have liked it to be. Instructions
name enteredby the user on the computer keyboard. To
use this call the DX register must point to the start of a
could be added, for example, to allow the desired baud
rate to be entered by the user from the keyboard. Hope-
buffer in memory where the characters are to be put.
The first byte of the buffer must contain the maximum
fully you
can use some of the techniques shown here in
your own programs. In the next section we show you
number of characters that you want to be read in. The
function call terminates when the user enters a carriage
how to call assembly language procedures from higher
return. The second byte of the buffer then holds the
level language programs.
number of characters actually read in. not including the
carriage return.
The next task in the procedure is to open the named Calling Assembly Language Procedures from
binary file for reading with the DOS 3DH function call. High Level Language Programs
Before this can be done, however, the carriage return at Programs which need to do a lot of bit-fiddling and
1he end of the filename in the buffer must be changed to hardware manipulation are usually written in assembly
00H. To do this we get the number of characters read language because this level gives direct hardware con-
from the second byte in the buffer, and use it to con- trol. However, business, scientific, and other programs
struct
pointer
a to the carriage return in the buffer. which involve mostly manipulating large amounts of
That location is then loaded with 0's. data are usually written in a higher level language such
11 an error is detected while trying to open the file, the as BASIC, Pascal, or C. For programs such as communi-
DOS 3DH function call will return the carry flag set, and cations programs,
which involve both types of opera-
an error number in AX. We multiply the error number by tion, main
the program is usually written in a high level
2 and use it as a pointer to a table which contains the language, and assembly language procedures are called
offsets of the error messages for some of the errors. As a to do the bit fiddling as needed. The intent of this sec-
refresher on the use of address tables, work your way tiontois give you an overview of how to write and call

474 CHAPTER THIRTEEN


these procedures However, we firs I have to briefly dis Interpretei each statement must be translated to ma
cuss the two ways thai luuh level language programs are chine code every nine the program is run. In other
converted Into machine code and executed, interpreting il t ime is p.n i ol the execut Ion
time.
,ni(l compiling.
Figure 13 27a % -howsin flowchart form how an Inter- Figure 13-27b shi iws how a compilei his into the
preter program
executes a high level language p ram translatlon-execul process. A compilei program
I lie Interpreter reads a high level language statement ol reads through the entire high-level language source pro
the source program, translates that statement to ma :-1 tiii and in two oi re passes through it. translates
chine code and, it ii doesn't need information from an It all to a relocatable machine code version. Before the
othei Instruction, executes the code for that statement program can he run, however, this relocatable object
Immediately, li then reads the next high level language code version iniisi he linked with any other required ob-
source statement, translates it, and executes it BASIC ject modulesfrom the system library, a user library, or
programs are often executed in tins way assembly language procedures. The output file from the
The advantage ol using an interpretei is that it an linker is then located, which means that it is given abso
error is found, von can just correct the source program lute addresses so that n cm be loaded into memory. Fi-
and immediately renin it. The majoi disadvantage ol the nally located
the program is loaded into memory. Some
Interpreter approach is that an interpreted program systems, incidentally, combine two or more ol the link.
inns 5 to 25 times slower than the same program will locate, and load functions in a single program. Once the
run alter being compiled. The reason is that with an loeated program is loaded into memory, the entire pro-
-am can
be run without any further translation. There-
fore,
will
it run much laster than it would it executed by
an interpreter, 'file major disadvantage ol the compiler
approach is that when an error is found, it usually must
be corrected in the source program and the entire com
pile-load sequence repeated.
Calling assembly language procedures from an inter-
preted level
hiu.li language is quite messy, especially in
CREATE
the case of multiple procedures, because of the way the
SOURCE interpreter uses memory. If you are working with IBM
PROGRAM
PC Microsoft BASIC, consult Appendix C of the IBM
BASIC Reference Manual to see how to do it for that
language. We recommend the compiler approach for
most hybrid programs, because of the obvious execu-
COMPILE TO
READ A
RELOCATABLE
tion speed advantage and the ease with which assembly
SOURCE
STATEMENT MACHINE language modules can be called.
CODE Calling assembly language procedures in compiled
programs is much simpler, because the object modules
produced by the assembler can be simply linked with
object modules produced by the compiler and object
TRANSLATE
STATEMENT modules from libraries. The major task when using as-
TO MACHINE sembler-created
withmodules
compiler-created mod-
CODE
ulestois make sure the modules can find and commu-
nicate with
each other. Since common Pascal. C, and
BASIC compilers use similar conventions to do this, we
will use the Microsoft BASIC compiler conventions as an
EXECUTE example here.
STATEMENT
The BASIC call statement has the format CALL numvar
(varl, var2, var3, . . ., varN). For compiled BASIC pro-
grams numvar is the name of the assembly language
procedure being called. When the BASIC program and
the assembly language module are linked, the linker will
EXECUTE
establish the required connection between the call and
ENTIRE
PROGRAM the named procedure. Varl. var2. var3. etc. represent
the names of variables which are being passed to or
from the assembly language procedure. Numeric varia-
blesstring
or variables can be passed to or from an as-
(stop) sembly language procedure.
Figure 13-28a shows a simple BASIC program which
inputs a line of characters from the keyboard, calls an
assembly language procedure to make sure all letters in
FIGURE 13-27 Comparison of compiler and interpreter the string are upper case, and then outputs the resul-
operation, (a) Interpreter, (b) Compiler. tant stringto the CRT. The program terminates when

DATA COMMUNICATION AND NETWORKS 475


10 REM This program inputs a string of characters from the keyboard
11 REM converts any lowercase letters to upper case, and outputs
12 REM the resulting string to the CRT
13 REM Procedures called: UCASE
14
100 LINE INPUT Q$
1 10 CALL UCASE < Q* )
120 PRINT QS
130 IF Q*<>"EMD" THEN 100
140 END

[a)

; This procedure is intended to be called from an interpreted


; or compiled BASIC program.
; The procedure converts any lower case ASCII characters in an
; input string to upper case and returns the result as the same string

PUBLIC UCASE
;Segment name 'CODE' required for compiler compatibility
CODE SEGMENT PUBLIC 'CODE'
UCASE PROC FAR
ASSUME CS CODE
PUSH HP Save old BP
MOV BP SP Set up second stack pointer
MOV BX CBP+6] Pointer to string descriptor from stack
add 2 to displacement for each word
pushed on stack in addition to BP
MOV CX , CBX3 Length of string from memory to CX as counter
MOV CL, CBX3 For IBM interpreted BASIC string length Ibyte
MOV BX , CBX+2] Offset of start of string from descriptor
displacement in l ns t r uc t i on= 1 for

IBM interpreted BASIC


NEXT MOV al, cbx: Get byte from string
CMP AL,61H Check if lower case
JB OK
CMP AL,7AH
J A OK No , 1 eave as i s
SUB AL,20H Yes* convert to upper case
01- : MOV CBX3 ,AL Put back in string
INC BX Increment pointer to next char
LOOP NEXT Repeat until all string done
POP BP Restore old BP
RET Return and increment stack pointer over
string descriptor passed on stack
UCASE ENDP
CODE ENDS
END

FIGURE 13-28 Integration of high-level language and assembly language


programs, (a) BASIC calling program, (b) Assembly language procedure called.

END followed by a carriage return is entered. The CALL BASIC passes these parameters to the procedure on the
instruction here calls a procedure called UCASE and stack.
passes the "hooks" needed for the procedure to access The left side of Figure 1 3-29 shows the contents of the
the string named Q$. Before we can discuss the actual top few locations of the stack after the CALL executes.
assembly language procedure, we need to show you how The top 2 words on the stack contain the IP and the CS

476 CHAPTER THIRTEEN


registers and flags an- restored upon return i! the <<>i
SI MINI,
% 1 ;i RIP rOR reel number is used with the RET instruction. II you are
i Mm i not sure they are pushed by the call statement in a par-
-I ill 1 %
ticular high
level language, ii won't hurl anything to
[STRING IN
push and pop them In the procedure.
J DS Combining assembly language procedures with high
SP • 4
DESCRIPTOR IN DS
[_1ENGTH level language programs is a powerful programming
SP + 2 RETURN CS
f OF SI RING technique. Hopefully, this section has shown you that it
SI' AF H R „ is not a difficult one il done in a compiler environment.
RETURN IP
CALL t
SYNCHRONOUS SERIAL DATA
11(,i Rl l i-J() stac k after assembly language pro* edure
call showing pointer to string variable des< riptoi table COMMUNICATION AND PROTOCOLS
passed In calling program. Introduction
Most ol the discussion ol serial data transfer up to this
of the return address The next word in the stack con- point in the chapter has been about asynchronous
tains offset
the (in the data segment) of a 4-byte descrip transmission. For asynchronous serial transmission a
tor for the string passed to the procedure. As shown in start bit is used to identify the beginning of each data
the right side of Figure 13-29 the lower 2 bytes of the character, and at least one stop bit is used to identify
descriptor contain the length of the string. The upper 2 the end of each data character. The transmitter and the
bytes of the descriptor contain the offset of the actual receiver are effectively synchronized on a character by-
string m the data segment. In other words, the offset character basis. Since a total of 10 bits must be sent foi
passed on the stack for the string is a pointer to a table each 8-bit data character, 20 percent of the transmis-
which contains the length of the string and the actual sion time is wasted. A more efficient method of transfer-
location of the string. When a simple nonstring variable ring serialdata is to synchronize the transmitter and
is passed to a procedure, the offset in the stack points the receiver, and then send a large block of data charac-
directly to a word location which contains the offset of ters one after the other. No start or stop bits are then
the actual variable in the data segment. Once you know needed for individual data characters, because the re-
where the offset for a variable or a descriptor is stored in ceiver automatically knows that every 8 bits received
the stack, it is a simple matter to access the variable in after synchronization represents a data character.
your assembly language program. When a block of data is not being sent through a syn-
Figure 13-28b shows how this is done. The BP regis- chronous
link,
data the line is held in a marking condi-
ter first
is saved on the stack, and then the value in the tion. indicate
To the start of a transmission the trans-
stack pointer copied to it. Since a value in the BP regis- mitter sends
out one or more unique characters called
ter isadded to the stack segment base to produce a sync characters, or a unique bit pattern called a flag,
physical address. BP can now function as a second depending on the system being used. The receiver uses
pointer into the stack. After BP is pushed on the stack. the sync characters or the flag to synchronize its inter-
the offset of the string descriptor that we need will be 6 na] clockwith that of the receiver. The receiver then
bytes up in the stack. The instruction MOV BX, [BP + 6] shifts in the data characters following and converts
then brings the string descriptor offset from the stack to them to parallel form so they can be read in by a com-
BX. The MOV CX, (BX] instruction then uses this offset puter. Higher-speeddata links or digital communica-
to bring the length of the string into CX lor use as a tion channels usually use synchronous transmission.
counter. The MOV BX, [BX + 21 instruction then brings Now, remember from a previous section that a hard-
the offset of the start of the string from the descriptor ware levelset of handshake signals is required to trans-
table to BX where it can be used to access the elements mit asynchronous or synchronous digital data over
in the string. The next section of the program runs phone lines with modems. In addition to this hand-
through a simple check and fix-if-necessary loop until shaking,
highera level of coordination, or protocol, is
all of the string elements have been processed. In this required between transmitter and receiver to assure the
case, the results of the processing are passed back to the orderly transfer of data. A protocol in this case is an
calling program in the same string as the data was agreed set of rules concerning the form in which the
passed in. Finally, the initial BP is restored and execu- data is to be sent. There are many different serial data
tion returned to the calling program. Note that the RET 2 protocols. The two most common that we discuss here
instruction is used to increment the stack pointer after are the IBM binary synchronous communications pro-
the return. This is done to move the stack pointer over tocol,
BISYNC,
or and the high-level data link control
the variable offset that was passed to the procedure on protocol, or HDLC.
the stack. If this is not done to balance the stack, the
stack may grow downward in memory over the program.
For each variable passed to the procedure, add 2 to the
Binary Synchronous Communication Protocol —
return number. It is not necessary to push the flags and BISYNC
the general-purpose registers used in the procedure, BISYNC is a referred to as a byte-controlled protocol
because this is done as part of the call statement. The (BCP). because specified ASCII or EBCDIC characters

DATA COMMUNICATION AND NETWORKS 477


(bytes) are used to indicate the start of a message and to to receive data, it sends back a text message containing
handshake between the transmitter and the receiver. the single character for negative acknowledge, NAK
Incidentally, even in a full-duplex system. BISYNC only (ASCII 15H). If the receiver is ready, it sends a message
allows data transfer in one direction at a time. containing the affirmative acknowledge, ACK. charac-
Figure 13-30 shows the general message format for ter (ASCII 06H). In either case, the computer then
BISYNC. For our first cycle through this we will assume switches to receive mode to await the next message from
that the transmitter has received a message from the the terminal. If the terminal received a NAK. it may give
receiver that it is ready to receive a transmission. If no up, or it may wait a while and try again. If the terminal
message is being sent, the line is in an "idle" condition received an ACK, it will send a message containing a
with a continuous high on the line. To indicate the start block of text and ending with a BCC character(s). After
of a message, the transmitting system sends 2 or more sending the message, the terminal switches to receive
previously agreed upon sync characters. For example, a mode and awaits a reply from the computer as to
svnc character might be the ASCII 16H. As we said be- whether the message was received correctly. The com-
fore, the
receiver uses these sync characters to synchro- puter meanwhile computes the BCC for the received
nize clock
its with that of the transmitter. A header may block of data and compares it with the BCC sent with
then be sent if desired. The header contents are usually the message. If the two BCCs are not equal, the com-
defined for a specific system and may include informa- puter sends
a NAK message to the terminal. This tells
tion aboutthe type, priority, and destination of the mes- the terminal to send the message again, because it was
sage thatfollows. The start of the header is indicated not received correctly. If the two BCCs are equal, then
with a special character called start-of-header (SOH1. the computer sends an ACK message to the terminal,
which in ASCII is represented by 01H. which tells it to send the next message or block of text.
After the header, if present, the beginning of the text In a system where multiple blocks of data are being
portion of the message is indicated by another special transferred, an ACK 0 message is usually sent for one
character called start-of-text (STX), which in ASCII is block, an ACK 1 message sent for the next, and an ACK 0
represented by 02H. To indicate the end of (he text por- again sent for the next. The alternating ACK messages
tionthe
of message, an end-of-text (ETX) character or an are a further help in error checking. In either case, after
end-of-block (ETB) character is sent. The text portion the message is sent the computer switches to receive
may contain 128 or 256 characters (different systems mode to await a response from the terminal.
use different-size blocks of text). Immediately following One major problem with this protocol is that the
the ETX character. 1 or 2 block check characters (BCC) transmitter must stop after each block of data is trans-
are sent. For systems using ASCII, the BCC is a single ferred, and
wait for an ACK or NAK signal from the re-
byte which represents complex parity information com- ceiver. Due
to the wait and line turnaround times, the
putedthe
for text of the message. For systems using actual data transfer rate may be only half of the theoreti-
EBCDIC a 16-bit cyclic redundancy check is performed cal rate predicted by the physical bit rate of the data
on the text part of the message and the 16-bit result sent link. The HDLC protocol discussed in a later section
as 2 BCCs. The point of these BCCs is that the receiving greatly reduces this problem. Next we want to return to
system can recompute the value for them from the re- the Intel 825 1A USART and give you a brief look at how
ceived data
and compare the results with the BCCs sent it is used for BISYNC communication.
from the transmitter. If the BCCs are not equal, the re-
ceiversend
can a message to the transmitter, telling it to
Using the Intel 8251 A USART for BISYNC
send the message again. Now let's look at how messages
are used for data transfer handshaking between the
Communication
transmitter and the receiver. As shown in Figure 13-5, we initialize an 8251 A by first
To start let's assume that we have a remote "smart" getting its attention, sending it a mode word, and then
terminal connected to a computer with a half-duplex sending it a command word. To initialize the 8251 A for
connection. Further, let's assume that the computer is synchronous communication. O's are put in the least-
in the receive mode. Now, when the brain in the termi- significant 2 bits of the mode word. The rest of the bits
nal determines that it has a block of data to send to the in the mode word then have the meanings shown in Fig-
computer, it first sends a message with the text contain- ure 13-31. Most of the bit functions should be reasona-
ing onlythe single character ENQ (ASCII 05H). which bly clearfrom the descriptions in the figure, but a cou-
stands for enquiry. The terminal then switches to re- ple need a little more explanation.
ceive mode
to await the reply from the computer. The Bit 6 of the mode word specifies the SYNDET pin on
computer reads the ENQ message, and, if it is not ready the 8251 A to be an input or an output. The pin is pro-
grammed
function
to as an input if external circuitry is
used to detect the sync character in the data bit stream.
When programmed as an output, this pin will go high
SYN when the 8251 A has found one or more sync characters
in the data bit stream.
Bit 7 of the mode word is used to specify whether 1
DIRECTION OF SERIAL DATA FLOW
sync character, or a sequence of 2 different sync charac-
riGURE 1 1-30 General message format for BISYNC. ters to
is be looked for at the start of a message.

478 CHAPTER THIRTEEN


I ill
%¡7 D6 D5 u 1)3 1).' D 1 acter, I l\ character, and B( ( byte to the 8251A. one
scs ESD EP PEN 1 , 1 0 0 aftei i In- (it hi] I in 82 . 1A si i ids the charactei
synchronous serial formal (no start and stop bits). II. for
.mi ir reason such as a high priority Interrupt, the CPU
1 I) 1 stops sending characters while a message is being sent,
0 0 1 the 8251A will automatically Insert sync characters
6 7 8 until the flow ol data characters from the CPU resumes.
BITS BITS bus After the I NQ message has linn sent, the CPU in the
terminal awaits a reply from the computer through the
PARI I Y ENABLE
il l-NABLE)
RxD input ol the 8251A. II the 8251A has been pro
(0 - DISABLE) grammed to enter hunt mode by sending it a control
word with a l in bit 7. it will continuously shifl in bits
EVEN PARITY GENERATION CHECK
1 EVEN from the RxD Inn- and check after each shift it the char
0 ODD acter in the receive buffer is ,i sync charactei When it
EXTERNAL SYNC DETECT finds a syne character, the 8251A asserts the SYNDET
1 SYNDET IS AN INPUT pin high, exits the bunt mode, and starts the normal
0 = SYNDET IS AN OUTPUT
data read operation. When the 825 l A has a valid data
SINGLE CHARACTER SYNC character in its receiver butler, the RxRDY pin will be
1 = SINGLE SYNC CHARACTER
asserted, and the RxRDY bit in the status register will be
0 DOUBLE SYNC CHARACTER
set. Characters can then be read in by the CPU on a
NOTE IN EXTERNAL SYNC MODE, PROGRAMMING DOUBLE
polled or an interrupt basis.
CHARACTER SYNC WILL AFFECT ONLY THE Tx
When the CPU has read in the entire message, it can
FIGURL 1 Ml 8251A mode word for synchronous determine whether the message was a NAK or an ACK. If
communication. the message was an ACK, the CPU can then send the
actual data message sequence of characters to the
8251 A. Handshake and data messages will be sent back
To initialize an 825 1A for synchronous operation: and forth until all of the desired block of data has been

1. Send a series of nulls and a software reset command


to the control address as shown at the start of Figure
D7 Dl. ncj HI Dj D2 Dl DO
13-5.

2. Send a mode word based on the format in Figure


|EH IK RTS 1 R sbrkIrxE IdtrItxEnI

13-31 to the control address.


L TRANSMIT
1 ENABLE
ENABLE

3. Send the desired sync character for that particular 0 DISABLE

system to the control address of the 8251 A.


DATA TERMINAL RtADv
"HIGH" WILL FORCE DTR
4. If a second sync character is needed, send it to the OUTPUT TO ZERO
control address.
RECEIVE ENABLE
5. Finally, send a command word to the control ad- 1 = ENABLE
0 = DISABLE
dressenable
to the transmitter, enable the receiver,
and enable the device to look for sync characters in SEND BREAK CHARACTER
1 = FORCES T- D "LOW
the data bit stream coming in on the RxD input.
0 - NORMAL OPERATION

The format for the command word is shown in Figure ERROR RESET
1 RESET ERROR FLAGS
13-32. Now, let's examine how the 8251 A participates in PE, OE. FE
a synchronous data transfer. As you work your way
through this section, try to keep separate in your mind REQUEST TOSEND
"HIGH'-WILL FORCE RTS
the parts of the process that are done by the 825 1A and OUTPUT TO ZERO

the parts that are done by software at one end of the link
INTERNAL RESET
or the other. "HIGH" RETURNS 8251 A TO
To start, let's assume the 825 1A is in a terminal which MODE INSTRUCTION FORMAT

has blocks of data to send to a computer as we described


ENTER HUNT MODE'
earlier in this section. Further assume that the com-
1 -- ENABLE SEARCH FOR
puter
in is receive mode waiting for a transmission from SYNC CHARACTERS

the terminal, and that the 8251 A in the terminal has


been initialized and is sending out a continuous high
on the TxD line.
An I/O driver routine in the terminal will start the
transfer process by sending a sync character(s). SOH FIGURE 13-32 8251A command-word format for
character, header characters. STX character. EIMQ char- synchronous operation.

DATA COMMUNICATION AND NETWORKS 479


sent to the computer. In the next section we discuss scheme allows any type of characters or data to be sent
another protocol used for synchronous serial data without the problems BISYNC has in this area.
transfer. The next field in a frame is the 16-bit frame check
sequence (FCS). This is a cyclic redundancy word de-
rived from
all of the bits between the beginning and end
flags, but not including 0's inserted to prevent false flag
High-level Data Link Control (HDLC) and bytes. This CRC value can be recomputed by the receiv-
Synchronous Data Link Control (SDLC) ing systemto check for errors.
Protocols Finally, a frame is terminated by another flag byte.
The BISYNC protocol, which we discussed in the previ- The ending flag for one frame may be the starting flag
ous sectiononly works in half-duplex mode, has diffi- for another frame.
culty accurately
transmitting pure binary data such as In order to describe the HDLC data-transfer process,
object code for programs, and is not easily adapted to we first need to define a couple of terms. HDLC is used
serving multiple units sharing a common data link. In for communication between two or more systems on a
an attempt to solve these problems, the International data link. One of the systems or stations on the link will
Standards Organization (ISO) proposed the high level always be set up as a controller for the link. This station
data link control protocol (HDLC) and IBM developed is called the primary station. Other stations on the link
the synchronous data link control protocol (SDLC). The are referred to as secondary stations.
standards are so nearly identical that, for the discussion Now, suppose that a primary station, a computer for
here, we will treat them together under the name HDLC example, wants to send several frames of information to
and indicate any significant differences as needed. a secondary station such as another computer or termi-
As we said previously. BISYNC is referred to as a byte- nal Here's
how a transfer might take place.
controlled protocol because character codes or bytes The primary station starts by sending an S frame con-
such as SOH, STX. and ETX are used to mark off parts of taining
address
the of the desired secondary station and
a transmitted message or act as control messages. a control word which inquires if the receiver is ready.
HDLC is referred to as a bit-oriented protocol (BOP) be- The secondary station then sends an S frame which
cause messagesare treated simply as a string of bits, contains the address of the primary station and a con-
rather than a string of characters. The group of bits
which make up a message is referred to as a frame. The
three types of frames used are: information or I frames.
supervisory control sequences or S frames, and com-
mand/response
U frames. or The three types of frames
1EGINNING ENDING
INFORMATION FRAME
all have the same basic format. FLAG ADDRESS CONTROL FLAG
ANY NUMBER CHECK
Figure 13-33a shows the format of an HDLC frame. 01111110 8 BITS 8BITS 01111110
OF BITS 16 BITS
8 BITS 8 BITS
Each part of the frame is referred to as a. field. A frame
starts and ends with a specific bit pattern. 01111110.
called ajlag or Jlagjield. When no data is being sent,
the line idles with all Is, or continuous flags. Immedi-
ately after
the flag field is an 8-bit address field which BITS IN CONTROL FIELD
contains the address of the destination unit for a con-
HDLC FRAME FORMAT 7 6 5 4 3 2 1
trol orinformation frame, and the source of the re-
sponse
a for
response frame. l-FRAME (INFORMATION
TRANSFER
Figure 13-33b shows the meaning of the bits in the
COMMANDS/RESPONSES) Nr Nr Nr P.'F Ns Ns Ns
8-bit control field for each of the three types of frames.
S FRAME (SUPERVISORY
We don't have the space or the desire to explain here the
COMMANDS/RESPONSES! Nr Nr Nr P/F S S 0 1
meaning of all of these. A little later we will, however,
U-FRAME (UNNUMBERED
explain the use of the Ns and Nr bits in the control byte
COMMANDS/RESPONSES! M M M P/F M M 1 1
for an information frame.
SENDINGORDER-BITOFIRST, BIT7 LAST
The information field, which is only present in infor-
NS THE TRANSMITTING STATION SEND SEQUENCE NUMBER, BIT 2 IS THE
mation frames,
can have any number of bits in HDLC LOW -ORDER BIT

protocol, but in SDLC the number of bits has to be a


P/F THE POLL BIT FOR PRIMARY STATION TRANSMISSIONS, AND THE
multiple of 8. In some systems as many as 10.000 or FINAL BIT FOR SECONDARY STATION TRANSMISSIONS

20,000 information bits may be sent per frame. Now,


Ni THE TRANSMITTING STATION RECEIVE SEQUENCE NUMBER, BIT 6 IS
the question may occur to you, "What happens if the THE LOW-ORDER BIT

data contains the flag bit pattern, 011111 10?" The an-
S THE SUPERVISORY FUNCTION BITS
swerthis
to question is that a special hardware circuit
M THE MODIFIER FUNCTION BITS
modifies the bit stream between flags so that there are
never more than 5 ones in sequence. To do this the cir-
cuit monitors the data stream and automatically stuffs
in a zero alter any series of 5 ones. A complementary FIGURE 13-33 (a) Format of HDLC frame, (b) Meaning of
circuit in I he receiver removes the extra zeros. This bits in 8-bit control field for a frame.

480 ( HAITI R THIRTEEN


trol word which indicates its ready status. II tin- second LOCAL AREA NETWORKS
ary station receivei was ready, the primary station then
sends a sequence ol Information frames. The informa Introduction
tion frames contain the address <>i the secondary sta The objective "I tins section is to show you how several
t K hi. ,1 control wind, a block of information, and the FCS computers can l»- connected togethei in communicate
winds For .ill bul the lasl frame ol .1 sequence oi Infor with each othei and to share common peripherals such
mation frames, the I' I bit in the control byte will be .1 0. as printers and large disk drives. We will start with sim-
The 3 Ns bits in the control byte will contain the number ple casesand progress to the type ol network that might
(it the frame In the sequence. be used in the computerized electronics fa< tor) we de-
Now as the secondary station receives each Informa scribed
.111in
eai liei chapter.
tion frame, it reads the data into memory and computes To communicate between a single terminal and .1
ih< frame check sequence for the frame. Fur each frame nearby computer, a simple RS 232C connection is suffi
in a sequence that the secondary station receives coi Cient. It the computer is distant, then a modem and
rectly, it increments an internal counter. When the pri phone line 01 .1 leased phone line is used, depending on
marv station sends the last frame 111a sequence ol up to the required baud rate. Now. lor a nunc difficult case,
seven frames, it makes the P I bit in the control byte a 1, suppose tint we have m a university building I do ter-
This is a signal to the secondary station that the pri- minals need
that to communicate with a distant com-
mary stationwants a response as to how many frames puter.could
We use 100 phone lines with modems, but
were received correctly. The secondary station responds this seems quite inefficient. One solution to this prob
with an S frame. The Nr bits in the control word of this S lem is to run wires from all of the terminals to a central
frame contain the sequence number of the last frame point in the building, and then use a multiplexer or
that was received correctly plus 1. In other words, Ns data concentrator of some type to send all of the com-
represents the number of the next expected frame. The munications
one overwideband line. Either time-
primary station compares Ns - 1 with the number of domain multiplexing or frequency-division multiplexing
frames sent in the sequence. If the two numbers do not can be used. A demultiplexer at the other end of the line
agree, the primary station knows that it must reconstructs the original signals.
retransmit some frames, because they were not all re- As another example of computer communication,
ceived correctly.The Nr number tells the primary sta- suppose that we have several computers in one building
tion which frame number to start the retransmission or a complex of buildings that need to communicate
from. For example, if Nr is 3. the primary station will with each other. Our computerized electronics factory is
retransmit the sequence of frames starting with frame an example of this situation. What is needed in this case
3. If the sequence of frames was received correctly, an- is a high-speed network, commonly called a local area
other seriesof frames can be sent if desired. Actually. network or LAN, connecting the computers together. We
since HDLC operates in full duplex, the receiving station start our discussion of LANs by showing you some of the
can be queried after each frame is sent to see if the pre- basic connection configurations.
vious frame
was received correctly. A similar series of
actions takes place when a secondary station transmits
to a primary station or to another secondary station. LAN Connection Configurations
One advantage of this HDLC scheme is that the trans- The different ways of physically connecting devices on a
mitter does
not have to stop after every short message network with each other are commonly referred to as
for an acknowledge as it does in BISYNC protocol. True, topologies. Figure 13-34 shows the five most common
several frames may have to be resent in case of an error, topologies and some other pertinent data about each,
but in low error rate systems, this is the exception. As such as examples of commercially available systems
we will show in the next section. HDLC is used along which use each type.
with some higher level protocols to allow communica- In a star topology network, a central controller coordi-
tion between a wide variety of systems. natescommunication
all between devices on the net-
One final point to make here is how HDLC protocol is work. The
most familiar example of how this works is
implemented with a microcomputer. At the basic hard- probably a private automatic branch exchange, or
ware level,
a standard USART cannot be used because of PABX. phone system. In a PABX all calls from one phone
the need to stuff and strip 0 bits. Instead, specially de- on the system to another or to an outside phone are
signed parts
such as the Intel 8273 HDLC/SDLC proto- routed through a central switchboard. The new digital
col controller are used. Devices such as this automati- PABX systems allow direct communication between
cally stuff
and strip the required 0 bits, generate and computers within a building at baud rates up to per-
check frame-check sequence words, and produce the haps 100
kBd.
interface signals for RS-232C. The devices interface di- In the loop topology, one device acts as a controller II
rectly
microcomputer
to buses. a device wants to communicate with one or more other
The actual control of which station uses the data link devices on the loop, it sends a request to the controller.
at a particular time and the formatting of frames is done If the loop is not in use, the controller enables the one
by the system software. The next section discusses how device to output, and the other device(s) to receive. The
several systems can be connected together or "net- GPIB or IEEE488 bus described in the last section of
worked"
theyso can communicate with each other. this chapter is an example of this topology.

DATA COMMUNICATION AND NETWORKS 481


TYPICAL TYPICAL TYPICAL to introduce you to a couple of terms commonly used
TOPOLOGY
PROTOCOLS NO OF NODES SYSTEMS
with networks. In some networks such as Ethernet,

5k r .-. n
RS-232C
COMPUTER
OR
TENS
PABX,
COMPUTER
pC CLUSTERS
data
10M
transmit
is transmitted
bits/s.
at
With
a time.
this
directly
type
This
as digital
of signal,
form of data
signals
only one
at a rate
device
transmission
of
can
is
often referred to as baseband transmission, because
IBM 3600/3700, onlv one basic frequency is used. The other common
SDLC TENS
uC CLUSTERS
form of data transmission on a network is referred to as
LOOP broadband transmission. Broadband transmission is
ETHERNET,

w CSMA/CD
CSMAWITH
ACKNOWLEDGMENT
OR TENS
HUNDREDSPER
SEGMENT
TO NET/ONE,
OMNINET,
Z-NET
(JC CLUSTERS
based
such
(CATVI
as
on
that
systems.
a frequency-division
used
The
for community
radio-frequency
multiplexing
antenna
spectrum
scheme
television
is di-
COMMON BUS
videdinto
up 6-MHz-bandwidth channels.

^
PRIMENET.
SDLC TENS TO
DOMAIN. A single device or group of devices can be assigned one
HDLC HUNDREDSPER
OMNILINK
(TOKEN PASSING) CHANNEL
pC CLUSTERS channel for transmitting and another for receiving.
Each channel or pair of channels is considered a branch
CSMA/CD
on the tree. Special modems are used to convert digital
TWO TO WANGNET
RS-2321 --.
HUNDREDSPER LOCALNET signals to and from the modulated radio-frequency sig-
OTHERS PER
M/A-COM
OTHER SERVICES CHANNEL
CHANNEL
nals required. The multiple channels arid the 6-MHz
BROADBAND BUS bandwidth of the channels in a broadband network
allow voice, data, and video signals to be transmitted at
the same time throughout the network. This is an ad-
(cT) LOCAL
CONTROLLER vantage
baseband
over systems which can only transmit
(fc)) MULTINETWORK
CONTROLLER one digital data signal at a time, but the broadband sys-
temmuch
is more expensive.
(H3M)
FREQUENCY
DIVISION
MULTIPLEX
FIGURE 1 5-34 Summary of common computer network Network Protocols
topologies.
In order for different systems on a network to communi-
cate effectively
with each other, a series of rules or proto-
In the common-bus topology, control of the bus is cols mustbe agreed upon and followed by all of the de-
spread among all of the devices on the bus. The connec- vices the
on network. The International Standards
tionthis
in type of system is simply a wire (usually but Organization, in an attempt to bring some order to the
not always a coaxial cablel which any number of devices chaos of network communication, has developed a stan-
can be tapped into. Any device can take over the bus to dard calledthe open systems interconnection (OSI)
transmit data. Data is transmitted in fixed-length model. This model is not a rigid standard. It is a seven-
blocks called packets. Two devices are prevented from layer hierarchy of protocols as shown in Figure 13-35.
transmitting at the same time by a scheme called carrier This layered approach structures the design tasks and
sense, multiple access with collision detection, or makes it possible to change, for example, the actual
CSMA/CD. This is discussed in detail in a later section hardware used to transmit the data without changing
on Ethernet. the other layers. We will use a common network opera-
In a ring network, the control is also distributed tion, electronicmail, to explain to you the function of
among all of the devices on the network. Each device on the upper-layers model.
the ring functions as a repeater, which means that it Electronic mail allows a user on one system on a net-
simply takes in the data stream and passes the data worksend
to a message to another user on the same
stream on to the next device on the ring if it is not the system or on another system. The message is actually
intended receiver for the data. Data always circulates sent to a "mailbox" in a hard-disk file. Each user on the
around the ring in one direction. Any device can trans- network periodically checks a personal mailbox to see if
mit onthe ring. A token is one common way used to it contains any messages. If any messages are present,
prevent two or more devices from transmitting at the they can be read out and then deleted from the mailbox.
same time. A token is a specific lone byte such as The application layer of the OSI protocol specifies the
01111111 which is circulated around the ring when no general operation of network services such as electronic
device is transmitting. A device must possess the token mail, access to common data bases, and access to com-
in order to transmit. When a device needs to transmit, it mon peripherals.For our example, this layer of the pro-
removes the token from the bus, thus preventing any tocol dictates
how you go about invoking the electronic
other devices from transmitting. After transmitting one mail function of the network.
or more packets of data, the transmitting device puts The presentation layer of the OSI protocol governs
the token back on the ring so another device can grab it the programs which convert messages to the code and
and transmit. We discuss this more in a later section. format that will be understood by the receiver. For our
The final topology we want to discuss here is the tree electronic mail message this layer might involve trans-
structured network which often uses broadband trans- lating
message
a from ASCII to EBCDIC, or perhaps
mission. Before
we can really explain this one. we need from English to French.

482 CHAPTER THIRTEEN


IIk physical layei ol the i )S1 model is the i
NUMBER
level. This layer is used to specif) the connectors, cables,
levels, bil rates, modulation methods eti
-

RS-232C is an exampli ol a standard which falls in ihis

PRESENTATION 6
PROVIDI layei ol the model.
Now we will lake a more detailed look ,ii the operation
COORDir: ol a very widespread "common bus network, Ethernet.
SESSI
END APPLICATION PRi
Ethernel is a trademark of Xerox Corporation.
PROVIDI
TRANSP 4
AND 01 * l\ l( I

NETWORK 3 AND R0U1 ! :% INI ORMATION Ethernet

TRANSFH: lATIONTO The Ethernet network standard was originally devel-


DATA LINK 2
.1 LINK opedXerox
by <lot poration. Later Xerox. DE( '. and Intel
worked on defining the standard sufficiently so that
PHYSICAL 1 TRANSMITS Bl I Ml DIUM
commercial products for implementing the standard
were possible. II has now been adopled. with slight
FICURI 13-35 ISO open system interconnect model for changes, as the IEEE802 3 standard.
network i ommunk ations. Physically, Ethernet is implemented in a common-bus
topology with a single 50-fl coaxial cable. Data is sent
over the cable using baseband transmission at 10
The session layei ol the OS! protocol establishes and Mbits/s. Data bits are encoded using Manchestei coding
terminates logical connections on the network. This as shown in Figure 13-36. The advantage oi this coding
layei is responsible for opening and closing named files. is that each bit cell contains a signal transition. A sys-
and for translating a user name into a physical network tem thatwants to transmit data on the network first
address. Electronic mail allows you to specify the in- checks for these transitions to see if the network is cur-
tended receiver
of a message by name. It is the responsi- rently busy.
II the system detects no transitions, then it
bility
thisof layer of the protocol to make the connection can go ahead and transmit on the network.
between the name and the network address of the Figure 13-37 shows how a very simple Ethernet is set
named receiver. up. The backbone of the system is the coaxial cable. Ter-
The transport layer of the protocol is responsible for minations
put areon each end of the cable to prevent
making sure a message is transmitted and received cor- signal reflections. Each unit is connected into the cable
rectly.
example
An of the operation of this protocol layer with a simple tee-type tap. A transmitter-receiver, or
is the ACK or NAK handshake used in BISYNC transmis- transceiver, sends out data on the coax, receives data
sion after
the receiver has checked to see if the data was from the coax, and detects any attempt to transmit
received correctly. For electronic mail, the message can while the coax is already in use. The transceiver is con-
be written to the addressed mailbox and then read back nected
an to interface board with a 15-pin connector
to make sure it was sent correctly. and four twisted-wire pairs. The transceiver cable can
The network layer of the protocol is only used in mul- be as long as 15 m. The interface board, as the name
tichannel systems.
It is responsible for finding a path implies, performs most of the work ol getting data on
through the network to the desired receiver by switch- and off the network in the correct form. The interface
ing betweenchannels. The function of this layer is simi- board assembles and disassembles data frames, sends
lar to
the function of postal mail routing which finds a out source and destination addresses, detects transmis-
route to get a letter from your house to the addressed sion errors, and prevents transmission while some
destination. other unit on the network is transmitting.
The data link layer of the OSI model includes the The method used by a unit to gain access to the net-
framing of the data in terms of packet size and address work
CSMA/CD.
is Before a unit attempts to transmit on
information, the means used to check errors (parity or the network, it looks at the coax to see if a carrier (Man-
CRC). the handshake signals between the transmitter chester code
transitions! is present. If a carrier is pres-
and the receiver, etc. The HDLC protocol described ear ent, theunit waits some random length of time and
lier in this chapter is an example of the type of transmis- then tries again. When the unit finds no carrier on the
sion factorsinvolved in this layer. line, it starts transmitting. While it is transmitting, it

ACTUAL DATA J \
I "0" I "1"
—I v ' r
(MANCHESTER-ENCODED DATA] "V^ V y~
FIGURE 13-36 Manchester encoding used for Ethernet data bit stream. Note
that encoded data has a transition at center of each data bit cell time.

DATA COMMUNICATION AND NETWORKS 483


COMPUTER FILE SERVER

\onH
TERMINATOR TERMINATOR

FIGURE 13-37 Very simple Ethernet system.

also monitors the line to make sure no other unit is approach described for Ethernet. As the name implies,
transmitting at the same time. The question may occur systems are connected in series around a ring. Data al-
to you at this point. "If a unit cannot start transmitting ways travelsin one direction around the ring. Unlike the
until it finds no carrier on the coax, how can another passive taps used in an Ethernet system, however, each
unit be transmitting at the same time?" The answer to active station on a token ring receives data, examines it
this question involves propagation delay. Since trans- to see if the data is addressed to it. and retransmits the
ceiversbe
can as much as 2500 m apart, it may take as data to the next station on the ring. A bypass relay is
long as 23 ,us for data transmitted from one unit to used to shunt data around defective or inactive units.
reach another unit. In other words, one unit may start Data is sent around the ring at perhaps 4-5Mbits/s in
transmitting before the signal from a transmitter that HDLC or SDLC frames which we described in an earlier
started earlier reaches it. Two units transmitting at the section of the chapter on synchronous transmission.
same time is referred to as a collision. When a unit de- Any station on the network can use the network.
tects
collision,
a it will keep transmitting long enough A token is a byte of data with an agreed-upon, unique
that all transmitting stations detect that a collision has bit pattern such as 0 1 1 1 1 1 1 1 . If no station is transmit-
occurred. All of the units then stop transmitting and try ting, this
token is circulated continuously around the
again after a random period of time. The term "multiple ring. When a station needs to transmit, it withdraws the
access" in the CSMA/CD name means that any unit on not-busy token, changes it to a busy token of perhaps
the network can attempt to transmit. No central control- 01111110. and sends the busy token on around the
ler decides which unit has use of the network at a par- ring. The transmitting unit then sends a frame of data
ticular time.
Access is gained by any unit using the around the ring to the intended receiver(s). When the
mechanism we have just described. The maximum transmitting station receives the busy token back
number of units that can be connected on a single again, it reads it in, and sends out the not-busy token
Ethernet is 1024. For further information about how an again. The transmitting station also pulls the transmit-
interface board is built, consult the data sheets for the ted dataoff the ring as it returns, so it can't circulate
Intel 82586 LAN coprocessor, and the data sheet for the around again. As soon as a transmitting station releases
Intel 82501 Ethernet serial interface. the not-busy token again, the next station on the loop
Incidentally, a file server such as the one shown in can grab the token and transmit on the network. The
Figure 13-37 is a "smart" hard-disk system which man- first station that transmitted cannot transmit again
ages file
access requests by other systems on the net- until the not-busy token works its way around the ring.
work.
print
A server is a "smart" printer which queues This gives all units on the network a chance to transmit
up print requests from other systems on the network. in a "round-robin" manner. (NOTE: Some token ring
networks use tokens with priority bits so that one sta-
tion cantransmit again if necessary before a lower-
Token-Passing Rings priority station gets a turn.]
Token- passing ring networks solve the multiple access Two questions occurred to us the first time we read
problem in an entirely different way from the CSMA/CD about token-passing rings: perhaps these same two

484 CHAPTER THIRTEEN


questions may have occurred to you. Hie firsl question %i k i Actually, each end of the cable has both a male con-
is. "How docs a station on the network tell the bll pal ii . toi ai ul a female connectoi . so thai cables can daisy
tern for a token from the same bil pattern In Ihe data chain from one unit to the next on the bus Instruments
frame?" f*he answei to this question is bll stuffing, the Intended for use on a GPIB usuall) hav< some switches
same technique that is used to prevenl the flag bil pal which allow you in selecl the 1 bil address thai the in-
tern from being present in ihc data section ol an HDLC strument
have
will on the bus Standard 111. signal
frame. A hardware circuit in the transmitter alters i in- voltage levels an used
data stream so that certain bil patterns are nol present. As shown in Figure 13 38b. the dl'HJ has eighl bidi-

Anothei hardware circuit in the receive] reconstructs rectional lines.


data These lines are used to tianslet
the original data data, add i esses, com ma i ids. and status bytes among as
l'hc second question is. "What happens ii the nol main- as 8 or It) instruments.
busy token somehow gets lost going around the i ing?" A The GPIB also has live bus management lines which
couple ol different approaches are used to solve ilns function basically .is follows. The interface cleat line
problem. One approach uses a timer in each station I IK ). when asserted by the controller, resets all devii i
When a station lias a frame to transmit, it starts a timer. on the bus to a starting state, h is essentially a system
It the station does not detect a token in the data stream reset. The attention IAIN) line, when asserted (low), in-
before the timer counts down, it assumes that the token dicates the
thai controller is putting a universal com
was lost, and sends out a new token. Another approach mand or an address command such as "listen" on the
used by IBM sets tip one station as a network monitor. II data bus. When the AI N line is high, the data lines inn
tins station does not deteet a token within a prescribed tain data or a status byte. Seruice request (SRC,)) is simi-
time, it clears any leftover data from the ring and sends lar toan interrupt. Any device that needs to transfer
out a new not-busy token. data on the bus asserts the SRQ line low. The controller
Token-passing ring networks have Ihe disadvantage then polls all the devices to determine which one needs
that more complex hardware is required where each sta- service. When asserted by the system controller, the re-
tion connectsto the network. The receive and transmit mote enable(REN I signal allows an instrument to be
circuitry at the connection, however, acts as a repeater controlled directly by the controller rather than by its
which maintains signal quality throughout the net- front panel switches. The end or identify (EOI) signal is
work. Since
signals only travel in one direction around usually asserted by a talker to indicate that the transfer
the ring, this topology is ideally suited lor fiber-optic of a block of d.tta is complete.
transmission, which allows high data rates and long Finally, the bus has three handshake
lines that coor-
distances between repeaters. IEEE802.5 standard de- dinatetransfer
the of data bytes on the data bus. These
scribes
token-passing
a ring network. Texas Instru- are data valid (DAV). not ready for data (NRFD). and
ments
currently
is offering the TI TMS380 chip set not data accepted (NDACI. These handshake signals
which implements a token-passing ring microcomputer allow devices with very different data rates to be con-
interface. nected together
in a system. A little later we will show
In the next section we discuss a somewhat different you how this handshake works. First we will give you an
type of network which is used to connect instruments overview of general bus operation.
with a computer to form an integrated test and meas- Upon power-up the controller takes control of the bus

urement system. and sends out an IFC signal to set all instruments on the
bus to a known state. The controller then proceeds to
use the bus to perform the desired series of measure-
The GPIB, HPIB, IEEE488 Bus ments
tests.
or To do this the controller sends out a se-
The general-purpose interface bus (GPIB). also known ries commands
of with the ATN line asserted low. Figure
as the Hewlett-Packard interface bus and the IEEE488 13-38c shows the formats for the combination com-
bus is not intended for use as a computer network in the mand-address
that codes
a controller can send to talkers
same way that the Ethernet and token rings are used. It and listeners. Bit 8 of these words is a don't-care, bits 7
was developed by Hewlett-Packard to interface smart and 6 specify which command is being sent, and bits 5
test instruments with a computer. through 1 give the address of the talker or listener to
The standard describes three types of devices that can which the command is being sent. For example, to en-
be connected on the GPIB. First is a listener, which can able (address) a device at address 04 as a talker, the con-
receive data from other instruments or from the control- troller simply
asserts the ATN line low and sends out a
ler. Examples of listeners are printers, display devices, command-address byte of XI 000 100 on the data bus. A
programmable power supplies, and programmable sig- listener is enabled by sending out a command-address
nal generators. The second type of device defined is a byte of X0 1 A^A tA.>A , , where the lower 5 bits contain
talker, which can send data to other instruments. Ex- the address that the listener has been given in the sys-
amples
talkers
of are tape readers, digital voltmeters, tem. Whena data transfer is complete, all listeners are
frequency counters, and other measuring equipment. A turned off by the controller sending an unlisten com-
device can be both a talker and a listener. The third type mand. X01
1 1 1 1 1. The controller turns off the talker by

of device on the bus is a controller, which determines sending an untalk command, X1011111. Universal

who talks and who listens on the bus. commands sent by the controller with bits 7, 6, and 5 all
Physically the bus consists of a 24-wire cable with a 0's will go to all listeners and talkers. The lower 4 bits of

connector such as that shown in Figure 13-38a on each these words specify one of 16 universal commands.

DATA COMMUNICATION AND NETWORKS 485


IE G , CALCULATOR!
'(8SIGNAL LINES)

(E. G., DIGITAL VOLTMETER)

(3 SIGNAL LINES)

DEVICE C

ONLY ABLE TO LISTEN

(E G , SIGNAL GENERATOR)

(5 SIGNAI I INI S)

DEVICE D

ONLY ABLE TO TALK

MEANING

UNIVERSAL COMMANDS
LISTEN ADDRESSES
IE G . TAPE READER]
UNL'STEN COMMAND
TALK ADDRESSES
UNTALK COMMAND NRFD
SECONDARY COMMANDS NDAC
IGNORED

CODE FOR TYPE OF COMMAND


SRQ
-REN

FIGURE 13-38 CPIB pins, signal lines, and waveforms, (a) Connector, (b) Bus
structure, (c) Command formats, (d) Data transfer handshake waveforms.

Periodically while it is using the bus. the controller pleted


series
a of conversions and has some data to send
checks the SRQ line for a service request. If the SRQ line to a listener such as a chart recorder. When the control-
is low, the controller polls each device on the bus one ler determines the source of the SRQ. it asserts the ATN
after another (serial), or all at once (parallel), until it line low and sends listener address commands to each
finds the device requesting service. A talker such as a listener that is to receive the data and a talk address
DVM, for example, might be indicating that it has com- command to the talker that requested service. The con-

486 CHAPTER THIRTEEN


(roller then raises the ATN line high, .mil data is nans II , Us 122A, RS 423A, RS 449 serial data
ferred directl) from the talker to the listeners using .1 standards
double handshake signal sequence
Figure 13 38d shows the sequence ol signals on the telephone circuits and systems
leased and switched lines
handshake hues for a transfei ol data from a talker to
POTS. DTMF, I'HX
several listeners. The DA\ . NRFD, and NDA< lim
open-collectoi rherefore. any listenei can hold NKII)
repeatei . hybi id coil, ring trip
low to Indicate thai il is noi ready for data, or hold CODECS, TDM, and PCM
\[ ) u low to indicate thai it has not yel accepted a data
b) te l he sequence proceeds as follows. When all listen Modems
ers have released the NRFD line (5 in Figure 13-38d). FSK, I'SK

indicating thai they are ready (not not-ready), the talker analog and digital loopback (ALB and DLB)
asserts the DAV line low to indicate that a valid data byte dibit, tribit
is on the hi is. The addressed listeners then all pull NRFD quaternary amplitude 1 lulation (QAM)
low and stall accepting the data. When the slowest lis-
Fiber-optic data communication
tener has
accepted the data, the NDAC line will he ic index ol refraction, critical angle
leased high (9 in Figure l3-38d). The talker senses Multimode and single-mode fibers
\l ) \i becoming high and unasserts its DAV signal. The
listeners all pull NDA< low again, and the sequence is Circular buffer
repeated until the talker has sent all ol the data bytes it Critical time hi
has to semi. The rate of data transfer is determined by
the rate at which the slowest listener tan accept the Compiler and interpreter
data.
Descriptor
When the data transfer is complete, the talker pulls
the EOI line in the management group low to tell the Binary synchronous communications protocol
controller that the transfer is complete. The controller (BISYNC)
then takes control again and sends an untalk command byte-controlled protocol (BCPI
to the talker. It also sends an unlisten command to turn cyclic redundancy check
off the listeners, and continues to use the bus according
HDLC.SDLC protocols
to its internal program.
A standard microprocessor bus can be interfaced to
bit-oriented protocol (BOPI
the GPIB with dedicated devices such as the Intel 8291
frame, field, flag
GPIB talker-listener, and 8292 GPIB controller. The
frame check sequence IFCS]
importance of the GPIB is that it allows a microcom- Local area network (LAN I
puterbeto connected with several test instruments to
form an integrated test system. Star, loop. ring, common-bus. broadband-bus (tree)
topologies
token
baseband and broadband transmission

Electronic mail
IMPORTANT TERMS AND CONCEPTS
Open system interconnection model (OSI)
FROM THIS CHAPTER
presentation, session, transport, network, data
link, physical layers
Serial data communication
simplex, half-duplex, full-duplex Ethernet

synchronous, asynchronous transceiver


marking state, spacing state collision

start bit, stop bit CSMA/CD

baud rate
Token-passing rings
UART, USART. DTE, DCE
GPIB. HPIB. IEEE 488 bus standard
20- and 60-mA current loops listener, talker, controller

REVIEW QUESTIONS AND PROBLEMS


1. Draw a diagram showing the bit format used for A terminal is transmitting asynchronous serial
asynchronous serial data. Label the start, stop, and data at 1200 Bd. What is the bit time? Assuming 7
parity bits. Use numbers to indicate the order of data bits, a parity bit, and 1 stop bit, how long does
the data bits. it take to transmit one character?

DATA COMMUNICATION AND NETWORKS 487


3. What is the main difference between a UART and a 16. How does an FSK modem represent digital l's and
US ART? 0's in the signal it sends out on a phone line? How
does an FSK modem perform full-duplex communi-
4. Define the term modem and explain why a modem
cation standard
over phone lines?
is required to send digital data over standard
switched phone lines. 17. Draw a waveform to show the signal that a simple
phase-shift keying (PSK) modem will send out to
5. Describe the functions of the DSR. DTR. RTS. CTS.
represent the binary data 01 1010100.
TxD, and RxD signals exchanged between a termi-
nal and a modem. 18. a. Draw a diagram which shows the construction
of a fiber-optic cable, and label each part.
6. What frequency transmit clock (TxC) is required by
b. Identify two types of devices which are used to
an 8251 A in order for it to transmit data at 4800
produce the light beam for a fiber-optic cable
Bd with a baud rate factor of 16.
and two devices which are commonly used to
7. a. Show the bit pattern for the mode word and detect the light at the receiving end of the fiber.
the command word that must be sent to an c. Why should you never look into the end of a
8251 A to initialize the device as follows: baud fiber optic cable to see if light is getting
rate factor of 64, 7 bits/character, even parity, through?
1 stop bit. transmit interrupt enabled, receive d. Describe the difference between a multimode
interrupt enabled. DTR and RTS asserted, error fiber and a single-mode fiber. Give a major ad-
flags reset, no hunt mode, no break character. vantage
a major
and disadvantage of each type.
b. Show the sequence of instructions required to e. What are the major advantages of fiber-optic
initialize an 8251 A at addresses 80H and 81H cables over metallic conductors?
with the mode and command words you
19. Using IBM PC BIOS and DOS calls, write an assem-
worked out in part a.
bly language program which reads characters from
c. Show the sequence of instructions that can be
the keyboard and puts them in a buffer until a car-
used to poll this 8251 A to determine when the
riage return is entered. The characters should be
receiver buffer has a character ready to be read.
displayed on the CRT as entered. When a carriage
d. How can you determine whether a character return is entered, the contents of the buffer should
received by an 8251 A contains a parity error? be sent out the COM1 serial port.
e. What frequency transmit and receive clock will
this 8251 A require in order to send data at 20. The SDK-86 will only accept uppercase letters as
2400 Bd? commands. The SDK-86 download program in Fig-
/. What other way besides polling does the 825 1A ure 13-24 would be friendlier if you did not have to
provide for determining when a character can remember to press the caps lock key on the IBM.
be sent to the device for transmission? De- Write an assembly language routine that will con-
scribe the
additional hardware connections vert
letter
a entered in lowercase to uppercase with-
required for this method. out affectingentered uppercase letters or numbers.
Show where you would insert this section of code
8. Draw a flowchart showing how asynchronous se-
in the program in Figure 13-24.
rial data
can be sent from a port line using a soft-
ware routine. 21. Describe the operation of a circular buffer. Include
in your answer the function of the tail pointer, the
9. Give the signal voltage ranges for a logic high and head pointer, and how the buffer-full and buffer-
for a logic low in the RS-232C standard. empty conditions are detected.
10. Describe the problem that occurs when you at-
22. Why is it necessary to disable the UART interrupt
tempt
connect
to together two RS-232C devices
input of the 8259A during part of the
that are both configured as DTE. Draw a diagram
CHK N DISPLAY procedure in Figure 13-24?
which shows how this problem can be solved.
23. Why. when changing a bit in a control word or in-
11. Why are the two ground pins on an RS-232C con-
terrupt mask
word, should you not alter the other
nectorjust
not jumpered together?
bits in the word? Show the assembly language in-
12. What symptom will you observe if the wire con- structions
would
you use to unmask IR5 of an
nected
pinto 5 of an RS-232C terminal is broken? 8259A at base address 80H without changing the
interrupt status of any other bits.
13. Explain why systems which use the RS-422A or
RS-423A signal standards can transmit data over 24. Describe the major difference between the way that
longer distances and at higher baud rates than an interpreter translates a high level language pro-
RS-232C systems. gram the
and way that a compiler does the transla-
14. Describe the function of the hybrid coil in Figure tion. Give
a major advantage and a major disadvan-
13-12. tageeach
of approach.

15. Describe the operation of a codec. Why are codecs 25. Show how the CALL statement in Figure 13-28a

designed with nonlinear response? would be modified to pass two additional parame-

488 CHAPTER THIRTttN


ins. A2 and B3. to the assembly language proce sembling messages into frames oi packets? WhU h
dure show the assembly language Instructions layer is responsible t<n making sun- the message
thai you would add to the procedure to bring the was transmitted and received correctly?
actual value ol A2 Into the (\ registei Assume the
M. a. Describe the topology, physical connections,
ordei ol the passed parameters is qs. A2, B3 De
scribe the function ol the string descriptor table and signal type used in Ethei net
b. Describe the method used by a unit on an
during a procedui e call.
Ethernel to gain access to the network for
26. Why is synchronous serial data communication i ransmitting a message.
much more efficient than asynchronous communi- ( What response will a transmitting
cation? make II it finds that another station starts
transmitting alter u starts? Whal is the term
27. If an H25 1A is being used in synchronous mode foi
used in refer to Uns condition?
a BISYNC data link, wlial additional initialization
word(s) must be sent to the device. How does the 33. Describe the method used by a unii on a token
8251 A detect the start of a message? I low dors the passing ring to take control ol the network foi
8251A indicate that is has found the start ol a mes- transmitting a message frame. Whal is the advan-
sage? How
does the receiving station in a BISYNC tageihis
ol scheme over the method used in Ether-
link indicate that it found an error in the received nel ?
data?
34. How can a token ring network recover if the token
28. How is the start of a message frame indicated in a is lost while being passed around the ring?
bit-oriented protocol such as HDLC? How does an
35. a. For what purpose was the GPIB designed?
HDLC system prevent the flag bit pattern from ap-
b. Give the names for the three types of devices
pearing
the indata part of the message? How does
which the GFIB defines.
the receiver in an HDLC system tell the transmitter
c. List and briefly describe the function of the
that an error was found in a transmitted frame?
three signal groups of the GPIB.
29. Draw simple diagrams which show the five com- d. Describe the sequence of handshake signals
mon network
topologies. For each topology identify that take place when a talker on a GPIB trans-
one commercially available system which uses it. fers data to several listeners. How does this
handshake scheme make it possible for talkers
30. What is the difference between a baseband network
and listeners with very different data rates to
and a broadband network?
operate correctly on the bus?
31. List the seven layers of the ISO open systems
model. Which of these layers is responsible for as-

DATA COMMUNICATION AND NETWORKS 489


CHAPTER

Operating Systems, the


80286 Microprocessor, and
the Future

As we told you in an earlier chapter, a general-purpose 8. Describe the mechanism used to schedule tasks in
operating system in its simplest form is a program RMX 86.
which allows a user to create, print, copy, delete, dis-
9. List some of the differences between UNIX and
play, and
in other ways work with files. It also allows a
RMX 86.
user to load and execute other programs. The operating
system insulates the user from needing to know the in- 10. Draw a block diagram of the internal structure of
tricate hardwaredetails of the system in order to use it. the 80286.
Up to this point in the book we have only referred to
1 1. List the major hardware and software features that
single-user operating systems such as the IBM PC DOS.
the 80286 microprocessor has beyond those of the
To round out the book we now want to give you an over-
8086.
viewmultiuser/multitasking
of operating systems, and
an introduction to the 80286 microprocessor. The 12. Show how the 80286 constructs physical ad-
80286 (used in the IBM PC/AT and its clones) has ad- dresses
its in real address mode and in its pro-
vanced features
which make it suitable as the CPU in a tected virtualaddress mode.
multitasking system. Finally, in this chapter we discuss
13. Describe how the 80286 uses descriptor tables and
a few directions in which microcomputer evolution
call gates to control memory access.
seems to be heading.
14. Define the term "demand-paged virtual memory"
and describe briefly how the 80386 produces a
physical address in paged mode.
OBJECTIVES
At the conclusion of this chapter you should be able to:

OPERATING SYSTEM CONCEPTS AND


1. Describe the difference between time-slice schedul- TERMS
ing andpreemptive priority-based scheduling.
Multiuser/Multitasking Operating System
2. Define the terms blocked, task queue, deadlock,
Overview
deadlv embrace, critical region, semaphore, kernel,
Newer 16-bit and 32-bit microprocessors are designed
memory management unit, and virtual memory.
to be used as the CPU in multiuser/multitasking micro-
3. I (escribe two methods that can be used to protect a computer systems.
Therefore, to understand how these
critical region of code. processors operate, you need to understand some of the
terms and concepts of operating systems.
4. Show with assembly language instructions how a
In Chapter 2 we discussed how several terminals can
semaphore can be used to accomplish mutual ex-
be connected to a single CPU and operated on a time-
clusion.
share basis. An operating system which coordinates the
5. Describe the major features of the UNIX operating actions of a time-share system such as this is referred to
system and define the terms kernel, pipe, and shell. as a multiuser operating system. The basic principle of a
time-share system is that the CPU services one terminal
6. List and describe the types of "objects" used in the
for a few milliseconds, then services the next for a few
RMX 86 operating system. milliseconds, and so on until all of the terminals have
7. List and describe the states that an RMX task can had a turn. It cycles through all of the terminals over
be in. and over, fast enough that each user seems to have the

490
complete attention of the ( PU rhe program or section be restarted correctly. The usual way ol preserving the
of a program which sei vices each usei is referred to as a environment is to keep il on a stack ( )ften the opi
task or process A multiusei operating system Ihen, can system keeps a separate stack foi each task < urrenl
also be referred to as multitasking, bul iliis term Is processors such as the 8011 1 186 have the
more often unci I when referring to real time indi ENTER and I.1..W I instru< tions 1 ake il easy to save
control operating systems. With the addition ol .1 usei and restore the environment Any procedures used in a
interface, the factory controllei program in Figure 10 35 multitasking system have to be reentrant.
would be .ui example ol .1 verj simple real time mul
1itasking operating system.
A( ( I SSING RESOURCES
The multiple tasks thai are to be executed by a CPU
must in some waj be scheduled so that they execute The second problem encountered in a multitasking sys-
properly. This part ul the operating system is called the tem assuring
is that tasks have orderlj
scheduler, dispatcher, or superoisor. There arc several sources such as printers, disk drives, etc. As one exam
different methods ol scheduling tasks, but we are pie oi tins, suppose thai a usei al a terminal needs to
mainly interested in two of them. read a file from a hard disk and print it on the system
The first method is the time-slice method which we printer. Obviously the file cannot be re. id in from the
discussed previously. In this approach the CPU executes disk and printed in one of the 20-ms time slices allotted
one task for perhaps 20 ms, then switches to the nexl to the terminal service, so several provisions must he
task. .Alter all tasks have had their turn, execution re- made to gam access to the resources and hang on to
turns
theto lust. The UNIX operating system, winch we them long enough to get the job done propel ly. A flag or
discuss in detail later, uses this scheduling approach semaphore 111 memory is used to indicate whether the
for a multiple-user system. The advantage of the time- disk drive is in use by another task or not. Likewise,
slue approach in a multiuser system is that all users are another semaphore is used to indicate whethei the
serviced at approximately equal time intervals. As more printer is in use. II a task cannot access a resource be
users are added, however, each user gets serviced less cause it is busy, the task is said to be blocked. Now.
often, so each user's program takes longer to execute. rather than making the user type in a print command
This is referred to as system degradation. In industrial- over and over until the disk drive and the printer are
control operating systems this variable time between available, most operating systems of this type set up
services is often not acceptable, so a different schedul- queues of tasks waiting for each resource. When one
ing method is used. task finishes with a resource, it resets the semaphore
The second scheduling method we are interested in is for that resource. The next task in the queue can then
preemptive priority-based scheduling. In this approach set the semaphore, to indicate the resource is busy and
an executing low priority task can be interrupted by a use the resource.
higher priority task. When the high priority task fin- In order to keep track of the state of a task, a block ol
ishes executing,execution returns to the low priority data called a process control block, process header, or
task. This approach is well suited to some control appli- process descriptor is set up by the operating system for
cations becauseit allows the most important tasks to be each task. Part of the information contained in the proc-
done first. Priority interrupt controllers such as the ess control block is the progress of the read disk and
8259A are often used to set up and manage the task print job. To simplify the disk and printer queues, ill
service requests. The Intel RMX 86 operating system, that needs to be put in these queues are pointers to the
which we discuss later, uses priority-based scheduling. process control blocks of tasks that are waiting for ac-
In addition to scheduling, multitasking operating sys- cess. This
is similar to the way a pointer to a string de-
tems have
several other considerations which have to be scriptor table
is passed to a procedure, rather than
taken into account. The next section discusses some of passing the string itself, as shown in Figure 13-29. Inci-
these. dentally,systems
most use a separate I/O processor to
actually handle disks, printers, and other slow re-
sources,
that sothese do not load down the main proc-
Problems Encountered in Building Multitasking essor.
Operating Systems Another problem situation in a multitasking system
can occur when two tasks need the same two resources,
There are a great many operating system variations, and
many different ways of solving various problems in an for example, a disk drive and a printer. Suppose that
operating system. What we have tried to do in this sec- one task gains access to the disk drive and sets its sema-
tionuse
is simple enough examples to illustrate the phore
indicate
to that the disk drive is busy at the end of
basic problems without getting lost in all of the possible its time slice. The next task finds the disk busy, so its
request goes on the queue. However, suppose that the
variations.
second task finds the printer not busy, so it sets the
printer semaphore to indicate it has control of the
PRESERVING THE ENVIRONMENT
printer, and goes on about its business. When execution
The first problem to be solved in a multitasking system returns to the first task, it will try to access the printer
is to preserve the registers, data, and return address so it has both the disk drive and the printer it needs.
(environment! of each task when execution is switched However, it finds the printer busy, so its request is put
to another task. This is necessary so that the task can on the printer queue. The situation here is that each

OPERATING SYSTEMS. THE 8028b MICROPROCESSOR, AND THE FUTURE 491


task controls a resource that the other needs in order to The section of code which must be protected is called a
proceed. Therefore, neither can proceed. This condition critical region. A technique called mutual exclusion is
is called deadlock or deadly embrace. The problem can used to prevent two tasks from accessing a critical re-
be solved in a number of ways. One way is to link the gionthe
at same time. In the CHICN DISPLAY procedure
printer and the disk drive together under one sema- in Figure 13-24 we showed one way in which a critical
phore
that
so the two resources are accessed with a sin- region can be protected from an interrupt procedure by
gle action. Another more practical approach is to set up simply masking the interrupt. In a time-slice system,
a hierarchy among the tasks, so that if deadlock occurs, however, a semaphore is used to provide mutual exclu-
the higher priority task can gain access to all of the re- sion.
sources
needs.
it Figure 14-1 shows how this can be done with 8086
Still another interesting problem can occur in a mul- assembly language instructions. The instruction se-
titasking operating
system when two or more users at- quence
the issame for each task. If task 1 needs to enter
tempt
read
to and change the contents of some memory a critical section of code, it first loads the semaphore
locations at the same time. As an example, suppose that value for critical-region-busy into AL. The single in-
an airline ticket reservation system is operating on a struction. AL.
XCHC SEMAPHORE, then swaps the byte
time-slice basis. Now. further suppose that one user in AL with the byte in the memory location named SEM-
examines the memory location which represents a seat APHORE.
is important
It to do this in one instruction so
on a plane and finds the seat empty, just before the end that the time-slice mechanism cannot switch to another
of its time slice. Another user on the system can then, in task halfway through the exchange and cause our air-
its time slice, examine the same memory location, find it line problem.
empty, mark it full, and print out a reservation confir- Alter the semaphore is read in Figure 14-1. it is com-
mation
theon CRT. When execution returns to the first pared with
the busy value. If the critical region is busy,
user, it has already checked the seat during its previous execution will remain in a wait loop for as many time
time slice, so it marks the seat full, and prints out a slices as are required for the critical region to become
reservation confirmation on the CRT. The two people free. If the semaphore value is a 0. indicating not busy.
assigned to the same seat may make nasty remarks then execution enters the critical region. The XCHG in-
about computers unless this problem is solved. struction
already
has set the semaphore to indicate the
The section of a program where the value of a variable critical region is busy. After execution of the critical re-
is being examined and changed must be protected from gion finishes,the MOV SEMAPHORE, 00 instruction re-
ai i ess by other tasks until the operation is complete. sets the
semaphore to indicate that the critical region is

; Instruct ions for accessing critical region of code protected by


; semaphore - User 1

MOV AL , 01 Load semaphore value for region busy


HOLD: XCHG AL , SEMAPHORE Swap and set semaphore
CMP AL , 01 Check if c egion busy
JE HOLD Yes, loop until not busy
No » enter critical region of code
instructions which access c itical region inserted here.
MOV SEMAPHORE , OO ; Reset semaphore to make critical
region available to other users.

; Instruction for accessing critical region of code protected b;


; semaphore User E

MOV AL, 01 Load semaphore value for region bu=


HOLD: XCHG AL , SEMAPHORE ; swap and set semaphore
CMP At , 01 ; Check if region b u s v
JE HOLD ; Yes, loop until not busy
No, enter critical region of code
i Instructions which access critical region inserted here.
MOV SEMAPHORE, 00 ; Reset semaphore to make critical
region available to other users.

FIGURE 14-1 8086 assembly language instruction sequences showing how a


semaphore can be used to provide mutual exclusion tor a critical region.

492 CHAPTER FOURTEEN


no longer bus} rask 2 can then swap the semaphore
and access the critical region when needed. The sema
phore functions in the same way as the "occupied" sign
on .1 restroom ol a plane or train. If you mentall} n\
interrupting each sequence "I Instructions .n differenl
points, you should sec thai there is no condition where
both tasks ran get into the critical region at the same
tune
In an Intel multibus system a problem could still re-
sulttin'
it semaphore were located on a differenl board
from the CPU. rheXCHG instruction takes 2 bus cycles,
so a task mi anothei master could take over the bus and
access the semaphore between the 2 bus cycles. This
problem is sohcd by putting the LOCK prefix in fronl of
theXCHG instruction. The LOCK prefix causes the 8086
to assert a hardware signal which can be used to mam
tain control ol the bus as we described in Chapter 1 1. In
the next section we look at some other ways that an op-
erating system
must protect various data and code areas
that it uses

The Need for Protection


Most single-user operating systems do little to prevent
user programs from "tromping on" the code or data
areas of the operating system. The usual results ol tbis
and Murphy's law are that an incorrect address in a user
program will cause it to write over critical sections of the
operating system. The system then "locks up." and the
only way to get control again is to reboot the system In a
multitasking system this is intolerable, so several meth-
ods areused to protect the operating system.
The major method is to construct the operating sys-
temtwo
in or more layers. Figure 14-2a shows an "on-
ionskin" diagramlor a two-layer operating system. The
basic principle here is that the inner circle represents
the code and data areas used by the operating system.
The outer layer represents the code and data areas of
user programs or tasks that are being run under control
of the operating system. The inner layer is protected
because user prggrams can only access operating sys-
tem resourcesthrough very specific mechanisms rather
than a simple, accidental call or jump. The Motorola
MC68000 family of microprocessors is designed to ac-
commodate
two-levela structure such as this. The
MC68000 has two modes of operation, user and super- FIGURE 14-2 "Onionskin" diagrams fey multitasking
visory. Certain
privileged instructions which affect the operating systems, (a) Operating system with two levels
operating system can only be executed when the proces- of protection, (b) Operating system with three levels,,
sor in
is supervisory mode. e.g., UNIX.
The AT&T UNIX"' operating system, which we discuss
in the next major section of the chapter, is an example of Other systems use even more levels of protection. The
a three-layer operating system. Figure 14-2b shows the Intel 80286 processor has designed into its hardware a
three layers for UNIX. The innermost layer, or kernel. mechanism which allows up to four levels of protection
contains the major operating system functions such as to be built into an operating system running on it.
the scheduler. The middle layer or shell contains the In addition to protecting itself from being tromped on
command line interpreter, which translates user- by executing tasks, an operating system should provide
entered commands to a sequence of kernel operations. some way of protecting tasks from each other. Through-
The shell level is the user-interface level. The outer layer out the
rest of this chapter we will be showing you how
contains application programs such as data base man- protection layers are actually implemented, and bow
agement programs. It also contains utilities such as edi- tasks can be protected from each other. To start this, we
tors, compilers, etc. which programmers can use to need to introduce you to the concepts of memory man-
write more application programs. agement.

OPERATING SYSTEMS, THE 80286 MICROPROCESSOR, AND THE FUTURE 493


FROM MICROPROCESSOR
Memory Management ADDRESS BUS

There are two major reasons why memory must be spe-


cifically managed
in a multitasking operating system.
The first reason is that the physical memory' is usually LOGICAL IpagE ADDRESS! PAGE OFFSET I
ADDRESS I _, -I ,—, 1
not large enough to hold all of the operating system and
all of the application programs that are being executed
by the multiple users. The second reason is to make
PHYSICAL CONTROL
sure that executing tasks do not access protected areas PAGE PROTECTION
of memory. Memory management can be done totally by ADDRESSES BITS

the operating system or with the aid of hardware called a M-M Y 0

memory management unit or MMU. Before we get into


the operation of an MMU. we want to give you a little
background on methods used to solve the limited mem-
DESCRIPTOR TABLES ::
ory problem.
A common problem, especially in older, single-user
systems, is that the physical memory is not large
enough to hold, for example, an assembler and the pro-
gram being
assembled. The traditional solution to this
problem is to write the assembler in modules, and use
an overlay scheme. When the assembler is invoked, the N \/7 M-1 M
executive module of the assembler is loaded into mem- PHYSICAL
ADDRESS
|PA'_-.-
-..% %
l -%
--%
| .-.%
---; EOFFSET
"
ory, and
reserves an additional memory space called the
overlay area. The assembler then reads through the TO MEMORY ADDRESS BUS

source program. When it reaches a point where it needs


a particular module, it reads that module, referred to as FIGURE 14-4 Block diagram showing operation of a
an overlay, from the disk into the overlay area reserved memory management unit.
in memory'. When the assembler reaches a point where
it needs another overlay, it reads the overlay from the
disk, and loads it into the same overlay area in memory. sarv to get execution smoothly from one bank to an-
The overlay approach is commonly used and works well other,the
but approach does help overcome the memory
for specific cases such as the assembler example we limits designed into the processor.
used here, but it is not flexible enough for multitasking To use bank switching in a multiuser system, each
systems. user's program might be assigned to a bank. The diffi-
Another approach traditionally used to expand the culty with
this is that a copy of the operating system
available memory in a microcomputer is bank switch- kernel must be kept in each bank, the actual memory
ing.system
A which has only 16 address lines can di- available for each user is still limited to 64 Kbytes, and
rectly address
only 64 Kbytes of memory. As shown in users cannot easily share code or data. Thus memory is
Figure 14-3. however, the addition of some simple selec- not very efficiently used. Also, protection is not as easily
tion hardware allows the system to access up to eight implemented as it is in the MMU approaches we discuss
memory "banks" of 64 Kbytes each. The hardware is next.
configured so that when the power is turned on. the sys-
temusing
is bank 0. To switch to bank 1. a byte which MMUs
turns off bank 0 and turns on bank 1 is output to the
To reduce the burden of memory management on the
selection port. Execution then proceeds in bank 1. In
operating system, most microprocessor manufacturers
practice, some system-dependent tricks are often neces-
now have hardware memory management devices avail-
able. The
device may be built into the processor as it is
in the 80286. or be available separately. In either case
the MMU is functionally positioned between the proces-
sor andthe actual memory as shown in Figure 14-4. The
major function of the MMU is to translate logical pro-
gram addressesto physical memory addresses. We will
explain how it does this, but first let's clarify what is
meant, in this case, by logical address and physical ad-
dress.
When you write an assembly language program, you
usually refer to addresses by name. The addresses you
work with in a program are called logical addresses.
because they indicate the logical positions of code and
data. An example of this is the 8086 instruction. JNZ
FIGURE 14-3 Block diagram showing how microcomputer NEXT. The label NEXT represents a logical address that
memory can be expanded with bank switching. execution will go to if the zero flag is not set. When an

494 CHAPTER FOURTEEN


8086 program is assembled, ea< h logical address is rep In tins type ol system is usually called the virtual ad-
resented with a 16 bil offset and a 16 bil segmenl base. he term vii lual n ippears
I In- 8086 BIU then produces the actual physical mem- to be pi esenl but actually isn't
ory addressby simply adding these two parts togethei as When the CPU or smart MMU wants to load a segmenl
explained many times previously. secondarj storage Into ph\ sii .'1 memory, it must
When .1 program is assembled or compiled to run on .1 first make space for it in the physical memory. Depend
system with an MMl I, each logical address is also repre ingon the system, it may do tins by compacting the seg
sented by two components, bin the components func ments already present and changing the descriptors to
tion differently In .1 segment-oriented system the upper point to the new physical locations. 01 by swapping the
component is referred to as a segment selector, and the segment being brought in with one currently 111physical
lowei component is referred to as the offset. In .1 page- memory. To help in deciding which segmenl to swap
oriented system the upper component is referred to .is back to memory, most systems use some bits in the de-
the page address, and the lowei component is referred scriptor
keep to track ol bow many limes the sectOl lias
to .is the page offset. been used. A low use segmenl is the must likely candi-
In the segment case the MMl I uses the upper compo- dateswap
to back to memory. Most systems alsi
nent,
segment
.1 selector for example, to access a de dirty bit in each descriptor. This bit will be set il the
scriptoi in a table ol descriptors in memory, rathei than contents oi a segment have been changed. II the dirty bil
just adding it to the offset in the lower component. A is set. a segmenl must be swapped back to secondary
descriptor is a series of memory locations that contains storage il its space is needed. It the dirty bit is not set.
the physical base address for a segment, the privilege then the segment has not been altered. The copy of the
level of the segment, and some control bits. As an exam segment in secondary storage is si ill correct, so the seg-
pie, let's assume the selector has 14 address bits and 2 mentjust
can be overwritten. This eliminates one write-
privilege-level bits. The 14 address bits in the selector to-disk operation.
can select any one of 16,384 descriptors in the descrip- Another term often found in MMU data sheets is the
tor table.If the offset component of the logical address term hit rate. Hit rate refers to the percentage ol the
has 16 bits, then each segment can contain 64 Kbytes. time that the segment required at a particular time is
Since each descriptor points to a segment, the logical present in the physical memory. In a well-strut lured
address space for our example system here is 65.536 system the hit rate may be 85-90 percent.
bytes/segment < 16.384 segments, or about 1 gigabyte. The use of a descriptor table to translate logical ad-
What this means is that the operating system can func- dresses
physical
to addresses has another major advan
tionifasa gigabyte of memory were available. Now let's tage besides making virtual memory possible. The selec-
see how this relates to the actual semiconductor mem- tor component of each address contains 1 or 2 bits
ory. which represent the privilege level of the program sec-
Physically the MMU may have perhaps 24 address tion requestingaccess to a segment. The descriptor for
lines so it can only address 16 Mbytes of physical mem- each segment also contains 1 or 2 bits which represent
ory. The question that may immediately come to mind the privilege level of that segment. When an executing
here is, "How can the operating system function as if program attempts to access a segment, the MMU can
there were a gigabyte of memory, when the maximum compare the privilege level in the selector with the privi-
physical memory that the system can have is 16 lege level
in the descriptor. If the selector has the same
Mbytes?" The answer to this question is that the physi- or greater privilege, then the MMU allows the access. If
cal memory,whatever its actual size, is simply a holding the selector privilege is lower, the MMU can send an in-
place for the segments currently being used by the oper- terrupt signal
to the CPU indicating a privilege-level vio-
ating system or user programs. lation. indirect
The method of producing physical ad-
When the MMU receives a logical address from the dressesgives
then a method of providing privilege levels
CPU, it checks to see if that segment is currently in the and protecting program sections such as the operating
physical memory. If the segment is present in physical system kernel.
memory, the MMU adds the offset component of the In most segment-oriented systems the segments
address to the segment base component of the address swapped in and out of physical memory are quite large.
from the segment descriptor to form the physical ad- The disadvantages of these large segments are the time
dress.
thenIt outputs the physical address to memory required to load them and the compaction that often
on the memory address bus. If the MMU finds that the must be done to make space for a segment in physical
segment specified by the logical address is not in mem- memory. The method described next helps solve this
ory,sends
it an interrupt signal to the CPU. In response problem.
to the interrupt, the CPU reads the desired code or data The second major memory management approach
segment from a disk or other secondary storage, and currently used is called demand-paged virtual mem-
loads it into the physical memory. The MMU then com- ory.this
In approach the virtual memory is mapped as
putes andoutputs the physical address as described fixed-length pages of perhaps 4 Kbytes in length. The
above. The operation is semiautomatic, so other than a two components of the virtual address are called the
slight delay, the operating system or other program is page address and the page offset. The page offset, as the
not aware that the segment had to be loaded. The name implies, contains the offset of a desired byte
gigabyte of logical address space that is available to pro- within a page. The page address is used as a pointer to a
grams
called
is virtual memory and the logical address descriptor table just as the selector is in the segmenta-

OPERATING SYSTEMS, THE 8028b MICROPROCESSOR, AND THE FUTURE 495


tion approach. The descriptors function in about the inghigh
a level language program to run on a different
same way here that they do in the segmentation machine involves rewriting the I/O sections as needed by
scheme. When a demanded page is found to be not pres- the hardware of the new machine, and compiling the
ent the
in physical memory, the MMU or the CPU swaps high level language program to the machine code for the
it in. The typically smaller and fixed length of the pages new machine. By 1972 a version of UNIX written in C
makes the swapping operation much easier. was operating successfully on the DEC PDP-11 com-
Before we summarize and go on to the next topic, we puter.
need to explain one more term commonly used with In the following years Western Electric, a parent com-
MMUs. For some MMUs the descriptor table is stored in panyBell
of Laboratories, licensed the source code of
a part of the main physical memory. Other MMUs have a UNIX to several universities where it underwent further

built-in, high-speed memory called a cache (pro- evolution. A commonly available enhanced version was
nounced "cash").
The descriptors for the currently used developed at the University of California at Berkeley. The

segments or pages are kept in the cache memory so that evolution also continued at Bell Labs. In 1979 version 7

they can be accessed much more quickly than they was released, and later versions III and V were released

could if they were in the main memory. The descriptors by Western Electric.
for pages not currently being used are kept in a table in Unfortunately, the basic structure of UNIX is easy to
main memory. If the descriptor for a required page is understand and alter. Therefore, each group using
not present in the cache, then it is read in from the de- UNIX tended to extend and modify it to fit its specific
scriptorintable
main memory. The descriptor is then needs or prejudices. Furthermore, due to licensing diffi-
used to read in the required page. culties with
Western Electric, commercial companies
To summarize then. MMUs translate logical program developing UNIX-like operating systems developed their
addresses to physical addresses with an indirect own proprietary versions. The result of all of this is that
method through a descriptor table. This indirect ap- there are many different versions of UNlX-tvpe operating
proach makespossible a virtual address space much systems in use. Hopefully, the current efforts to work
larger than the physical address space. The indirect out a standard will be successful.
approach also makes it possible to protect a memory
segment or page from access by a program section with
a lower privilege level. You will meet all of these concepts UNIX Operating System Structure
again in a later section which describes the operation of As shown in Figure 14-2b. the UNIX operating system
the 80286 microprocessor. First, however, we want to consists of three layers. The innermost, most privileged
give you overviews of UNIX, a common multiuser operat- layer, or kernel, contains a process scheduler, a hierar-
ing system, and RMX 86. a common real-time mul- chal file structure, and mechanisms for processes to
titasking operating
system. communicate with each other. The middle layer of the
operating system, called the shell, is the layer that a user
interlaces with. This layer contains the command inter-
THE UNIX OPERATING SYSTEM preter which
decodes and carries out user-entered com-
mands. outermost
The layer contains programming
The purpose of this section is to show you the structure,
tools such as editors, assemblers, compilers, debuggers,
terminology, and overall operation of the UNIX operat-
etc.. and application programs such as an accounting
ing system, so you can see how it relates to multiuser
package. Let's take a closer look at how each of these
microcomputer systems. If you are going to be working
layers function, and how they operate together.
with UNIX, there are available several books which show
with step-by-step examples how to use it.
OPERATIONS OF THE KERNEL

History The UNIX operating system was designed to allow sev-


In 1969 Ken Thompson, a researcher at Bell Laborato- eral users to share a CPU on a time-slice basis. Each
ries, decidedto write some system programs that would user program is referred to as a process. One of the

make it easier to develop other programs. Over the next major functions of the kernel is to schedule and service
few years, with the help of another researcher. Dennis the needs of processes. To do this the kernel keeps two
Richie, these programs evolved into a powerful mul- tables in memory.
tiuser operatingsystem. The original versions were One of these, the process table, contains information
written in assembly language for a DEC PDP-7 mini- about the state of each process. Among other things the
computer,
whenbut the value of the operating system entry in the process table contains the location of the
became obvious, there was a strong desire to write ver- process in memory, the length of the process, the identi-
sionsother
for machines. Adapting an assembly lan- fication number
of the process, the identification of the
guage programto run on another machine with a diiter- user, and whether the process is active or blocked.
ent CPU means rewriting the whole thing. To help solve The second type of table maintained by the kernel is
this portability problem. Dennis Richie developed a high called a user table, or a per-process segment. The user
level language called C. This language has much of the table contains pointers to the data, files, and directories
i apability ol assembly language to work with hardware currently being used by the process.
and twiddle bits, but it also allows a programmer to When a user or process is added to the system, the
write high level language structured programs. Adapt- kernel creates a process table entry and a user table for

496 CHAP1FR FOUkTUN


thai process the length ol the process table in fixed for A second factoi used to determine which ai live pro<
each system, so only ilns number ol processes can be ess should be serviced next is how recently each
presenl In the system at one time A process can create a has been serviced An active process which has re< entry
subprocess, called a child process, When a child process had a turn will have a lower priority than an actl
is i reated, an entry Is made in the process table for it. ess which has not recently had a turn because II just
and a usei table created for It. When any process Is re unblocked oi was jusl swapped in from disk.
moved from the system, Its process table entry and user Because [here is usually not room enough in memory to
table are removed to make room for another process. store .ill ol the suspended processes, some ol them are
At any given instant in time, only one process i an a< swapped out to secondary storage such as a di
tually be running since there is only one CPU to run schedule) decides which processes to swap so thai all
processes <>n. All <>!the other processes are suspended. processes get serviced as needed
Pro< esses essentiallj compete with each other for serv A second majoi function ol the UNIX kernel is to
u r l he schedulei in the kernel determines which proc maintain the system file structure. Unix uses a hier
ess is to be run at a given time. The scheduling mecha archical file structure as shown in Figure l i
nism works as follows. structure is sometimes called a tree structure because it
An externa] clock signal interrupts the CPU 50 or 60 looks like an inverted tree. The highest level in the hier-
nines a second to produce the basic time slues. The in archy
theis root directory. This directory contains the
terrupl procedure which services this clock interrupt names ol system files and the names oi subdirectories A
checks the process table entries for each process to de- directory in UNIX is simply a file which contains the
termine which
process should be run next. The decision name of the directory above it in the hierarchy, and
as to which process to run is based on several factors. names of files or directories below it in the hierarchy.
The first factor is whether the process is ready to run or The directory above a file or directory is often refei red to
blocked. A process may be blocked or put to sleep il it as the parent directoi v.
has to wait for: an input or output operation to com- A user logged on to the system is given a directory,
plete,
child
a process to complete, a signal from some under a directory labeled usr in Figure 14-5. under the
other process, an external interrupt signal, or some parent directory. The user can then create subdirec
fixed amount of time before continuing. A sleeping proc- tories or files under this directory. To refer to other hies
ess will
not he given a turn until the waited-for event or directories in the system, a user specifies the direc-
occurs and the process is marked as active (ready to tory path
to it. For example, a user whose directory is at
run). point 2 in Figure 14-5 can refer to the file at point 8 as

ROOT DIRECTORY

OPERATING
SYSTEM CODE

D = DIRECTORY
F = FILE
T = DEVICE

CAN BE REFERENCED AS

FILE AT 1 UNIX UNIX


DIRECTORY AT 2 ,USR'D0UG . . .DOUG
DIRECTORY AT 3 /USR/PAT
DEVICE AT 4 ,'DEV/MEM /DEV/MEM
DEVICE AT 5 DEV/C0M3 0EV/C0M3
FILE AT 6 /USR/PAT/A

You might also like