Microprocessor & interfacing
Microprocessor & interfacing
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
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
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
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
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
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
16pc4 = 0 RE x 16 = 224
Hexadecimal 22 7
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/
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
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 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)
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
• •• • • • • ••••
•••• • • • • • • ••••• • ••••••
• •••
• •••• • • • • ••• • • ••
•••• •• •• • •• • ••••••• • ••
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
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
FIGURE 1-7 (a) ASCII punched paper tape; (b) Hollerith punched card.
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
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.
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
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
0 1 0 1 1
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
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-
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
!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
;=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
1
I
II
1
1
II
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 ,
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
ROMs
18 CHAPTFK ONt
,\ i mm ss ii
NCI l is
3DRESS
BUS
A ,
1, ",,i 4Q ^M
D0
•
DATA
BUS
O, i < %º
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
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
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
ROM: address lines, data lines, bus lines RAM: static, dynamic
nonvolatile volatile
three-state READ/WRITE input
cascaded outputs ALU
enable input
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.
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
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
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
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.
INPUT
DEVICE
I
CONTROL CENTRAL CONTROL
1 0 BUS BUS MEMORY
PROCESSING
PORTS UNIT
(RAM AND
ROM)
(CPUI
OUTPUT
DEVICE '
ADDRESS BUS
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:
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. •
SEQUENCE
26 CHAPTER TWO
AEMi >R> CONTENTS CONTENTS ( )PI RATION
\DDRESS (BINARY) illl X)
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
2H CHAPTER TWO
f±± ±±ri
%¡
i[ ii
i i i II
wn
MASS COMPUTER
DATA (MAINFRAME
STORAGE OR MINI)
VIDEO VIDEO
PRINTER LOW-COST
VIDEO TERMINAL TERMINAL
VIDEO PRINTER
ERMINAL TERMINAL
30 CHAPTFR TWO
MA If: I RAMI Hll ,11 Mi I :
STORAGE COMPUTER PRINTER
FLOPPY DISK
DRIVE
%¡ \Q_\Q
PRINTER MICROCOMPUTER
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.
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
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
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
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
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.
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
(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.
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.
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
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-
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
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
42 CHAPTERTWO
CHAPTER
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
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.
make programs clearer. If you have previously written Eat supper out.
these structures are probably already familiar to you. Take a taxi home.
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
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.
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.
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.
the one that best fits the specific application. 8087 or 8089.
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
DATA
ADDRESS 1 ABI 1 S MNEM. OPERAND(S) COMMENTS
or
CODE
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
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
OB 00
Of
BYTE 3 BYTE 4
1 | 0 | 0 | 0 | 1| 0 1 1 LOWDISPLACEMENT
j HIGHDISPLACEMENT
OPCODE D w MOD REG R/M
I
OPERATION CODE
FIGURE 3-6 Coding template for 8086 instructions which MOV data between
registers or between a register and a memory location.
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
56 ( HAPTER IMKII
R M 00 01 in 11
W i) U 1
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
'TO' REG -
L EG SP 'FROM' REG - REG BX
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
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
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.
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
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
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
Symbols:
Name Type Value Attr
Warning Severe
Errors Errors
0 0
FIGURE 3-13 Assembler listing lor example program in Figure 5-10
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.
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
Algorithm
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
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.
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
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:
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
DATA_HERE END S
CODE_HERE SEGMENT
ASSUME CS : CI
CODE HERE, DS DATA HERE
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
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
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.
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
FIGURE 4-5 8086 assembly language program to produce packed BCD from
two ASCII characters.
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.
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
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.).
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
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.
page, 132
;8086 progras
;ABSTRACT : This prograa illustrates a "forwards" ju«p
iREGISTERS USED : CS, AX
;PORTS USED : None
IPROCEDURESUSED: None
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
Note: "above" and "below" refer to the relationship of two unsigned values;
"greater" and "less" refer to the relationship of two signed values.
JAE HEATER_OFF
READ TEMPERATURE
WHILE some condition is present DO
WHILE TEMPERATURE %
Action TURN HEATER ON
Action TURN HEATER OFF
PSEUDOCODE
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
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
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
FIGURE 4-12 Assembly language program for heater control problem, (a) First
approach, (b) Improved version.
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
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
sum. would turn on the heater. The heater would nol Action
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 ,
PSEUDOCODE
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
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
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
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
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
92 c HAPTERFOUR
SEGMENT BASE
RECORD 1
TV N. BEER
132"+ Down Street
Portland, OR 97219
2/15/^5
2^t7 lb
S327.56
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-
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
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)
REPEAT
COPY BYTE FROM SOURCE TO DESTINATION
INCREMENT SOURCE POINTER, SI
INCREMENT DESTINATION POINTER, DI
DECREMENT COUNTER, CX
UNTIL CX = O
t/.i
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.
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.
DATA_HERE SEGMENT
PASSWORD DB 'FAILSAFE'
INPUT_WORD DB S DUP ( ? ) ; space for user input
DATA HERE ENDS
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.
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
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".
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
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.
^\. ? ^S^
1 «
1
READ pH READ pH
SENSOR 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.
PAGE,132
8084 program section for PC board eakinq aachine
PAGE .132
8086 prograe section for PC board Baking aachine
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.
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:
PAGE .132
8086 prograa section for PC board nahnq aachine
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
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
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
LOWER LEVEL
PROCEDURE PROCEDURE
FIGURE 5-7 Program flow to and from procedures. Inter-segment or group. Direct
(a) Single procedures, (b) Nested procedures.
offset low
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.
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
DW ^O DUP(O)
STACK_T0P LABEL WORD
STACK HERE ENDS
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
READ VALUE
it does not load this value in the SS register. Loading the FROM PORT
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
Syibols:
NEXT_VALUE
. . L NEAR 0017 CODE HERE
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
SP
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)
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
"4596 = 11F<4H
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
DATA_HERE SEGMENT
BCD_ INPUT DB storage for BCD value
HEX_VALUE DB storage for binary value
DATA_HERE ENDS
PROCEDURE: BCD_HEX
Converts BCD numbers to HEX (binary), uses
registers to pass parameters to the procedure
SAVES: All registers used except AH
RET
BCD_HEX ENDP
CODE_HERE ENDS
END
intitial ization
CALL BCD HEX
PROCEDURE BCD_HEX
ABSTRACT : Converts BCD numbers to HEX, uses dedicated
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
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.
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
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. )
5 8086 PROGRAM
;ABSTRACT : This program computes the factorial of a
number between 1 and 9
;PORTS USED : None
5 PROCEDURES USED: FACTO
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
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
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-
CODE_HERE SEGMENT
CALL MULTIPLY_32
C0DE_HERE ENDS
PRQCEDURES_HERE SEGMENT
MULTIPLY 32 ENDP
PROCEDURES_HERE ENDS
FIGURE 5-23 Program additions needed for a far procedure.
;-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
i10RE_BATA SEGMENTWORD
QUOTIENT DW I -
00 14 , ,(, REMAINDERDU
0006 MOREDATA ENDS
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
ASSUME
DS:DATA.HERE
0033 IF POP DS ; restoie initial DS
003h 90 STOP: NOP
0035 CODE.HERE ENDS
END
Symbols:
Warning Severe
Errors Errors
0 0
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
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
Syibols:
Warning Severe
Errors Errors
0 0
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
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
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
MOV SP.4000H
^+7H
PUSH AX
CALL MULTO
POP AX ERROR
MULTO PROC NEAR
PUSHF 7FH
PUSH BX
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
ure 5-27
shows in diagram form how to do it. Each Problem 5-9.
8086 Instruction
Descriptions and Assembler
Directives
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
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.
EXAMPLE:
EXAMPLES (CODING1
(a) Add immediate number 74H
ADD AL. 74H
AL = 0011 1001 = ASCII 9 to contents of AL
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
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:
EXAMPLES: Ibl
AL = 0100 1001 = 49 BCD
(a) BH = 0111 0010 = 72 BCD
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:
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
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.
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-
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.
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-
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.
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
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.
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
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
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.
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:
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.
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.
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
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.
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
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
EXAMPLES:
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]
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
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
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)
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.
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.
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
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
MOV DI, OFFSET TARGET STRING : Point DI at JZ AGAIN Read port again if LSB = 0
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].
and initialize 3 bytes blocks of 10 bvtes each and initialize all 320 bvtes to 00
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
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
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
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.
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
3 qsi (INT A)
3 TEST
8086 HARDWARE OVERVIEW 3 READY
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
m , r m_ r
"V v_
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
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 ..
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
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
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
5ZD8
7ZD8 RESET OUT
9ZD8
DEN 4ZB6
'
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, :',
4/ 4/
49 49
'-"
.'
•>
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
2ZA3
3ZC3
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
J J -3 j ' < /J i
a; Q 1 a a 1 1 <i Q I
o
0
i
-: <
a
o
i
Hi'
ouooaaua
194 CHAPTERSEVEN
=00000 0 ^0 0
• * I I I II
I | § i Ulllllll
t/> ~* < '-'-•-
Q '
Z . o
< J tN 9 ID » -
J±
5f Ls 5l^r
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
ADDRESS
BUS
DATA
BUS
74LS138
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
(START = 3000
I END = 3FFF
|SI AH I = 4000
|END if i-r
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
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
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.
DATA BUS
AO ADDRESS BHE AO
i mi in. 1 TYPE CYCLES
m 11hk
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.
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)
FIGURE 7-12 Truth table tor an SDK-86 (A26) ROM decoder PROM.
FIGURE 7-14 Truth table for an SDK-86 (A29) RAM decoder PROM.
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
0000
to OPEN
FFDF
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
PROM INPUTS
PROM OUTPUT CORRESPONDING
(01) ADDRESS BLOCK
A19 A18 A17 A16 A15 A14 A13 A12
y z
X y. X
/—
J v /
f
J V
y y--^< y^-y
y
-. y
r
-. Read
208
8086 TIMING PARAMETERS
.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 .
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
TCH1CH2 TCL2CL1
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
TCLCL CLK Cycle Period 200 Mill 100 500 1." 500 ns
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)
(.)
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-
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
6
WORD
COMPARATOR
AND
TRIGGER WORD TRIGGER
SELECTION CIRCUITRY
SWITCHES
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
[% 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>
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
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?
b. The time between CLOCK going low and RD b. The reset key is stuck on.
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.
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 ,_
'-
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
1b Dl 1^
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.
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
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
INT_PROC_HERESEGMENT
WORD PUBLIC
EXTRNBAD_DIV:FAR Let asseabler know procedure BAD.DIVis
INT PROCHERE ENDS in another assembly aodule
FIGURE 8-4 8086 assembly language program for divide by zero example.
la) Mainline, lb) Interrupt service procedure.
DATA_HERE SEGMENT
WORD
PUBLIC
EXTRN BAD_DIV_FLA6:B¥TE ; Let assembler know BAD.DIVJLA6
DATAHERE ENDS ; is in another assembly nodule
BADDIV ENDP
INT PROC HERE ENDS
END
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
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-
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
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
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:
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?
% ±. 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
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
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
DftTA_HERE SEGMENT
WORD PUBLIC
EXTRN ASCII_POINTER:W0RD, CHARCNT: BYTE. KEYDONE: BYTE
DATA_HERE ENDS
"
PUBLIC KEYBOARD
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
-5 V + 5 V
62 n
74LS14 6"74LS14
NMI
INFRARED LED
- PC
BOARD PHOTOTRANSISTOR
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.
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
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
FIGURE 8-14 Circuit showing how to add an 8254 and 8259A(s) to an SDK-86
board.
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
FIGURE 8-15 Truth table tor 74LSI38 address decoder in Figure 8-14.
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)
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
F F 0 1 COUNTER 0 BCD
F F 0 7 CONTROL REG
FIGURE 8-16 8254 internal addresses and system FIGURE 8-17 8254 control word format. (Intel
addresses, (a) Internal, (b) System. Corporation)
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
IN914
AAA
[>H]>>
POWER
TRANSFORMER
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
~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).
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.
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 %
1 ICW4 NEEDI l)
ICW4 NEEDED
1 SINGLE
0 CASCADE 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
OA 1
D4
1 ;
0 0 SFNM BUF M S AEOI MPM
8086/8088 MODE
MCS-80'85 MODE
AUTO EOI
NORMAL EOI
BUFFERED MODE/SLAVE
BUFFERED MODE/MASTER
FIGURE 8-29 8259A initialization command word formats and sending order, (a)
Formats, (b) Sending order and requirements. (Intel Corporation)
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
NO OPERATION
•LO-L2 ARE USED
OCW3
D,
RESET SET
SPECIAL MASK SPECIAL MASK
INTERRUPTS
AND INTERRUPT
SERVICE
PROCEDURES 255
page .132
-.8086 PROGRAM
FRAGMENT
TO SHOWINITIALIZATION OF INTERRUPTJUMP TABLE,
; 8259A, AND COUNTER0 OF 8254.
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 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
KEYBOARD PROC f AR
CODE_HERE
ENDS
END
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
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
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.
POWER
SUPPLIES I/O
GRI IUP
r
: PA7-PA0
A
CONTROL
PORT
UPPER
C -; I/O
PC7-PC4
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
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
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 "
for (he three ports and the control register of the XA35 PORT A CONTROL
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.
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.
around the lathe. It must, for example, make sure the 8255A
LEFT RIGHT
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.
MB
\ /
CT3
INPUT
PERIP
FROM
HERAL ' ~ \_
f >"
FIGURE 9-8 Timing waveforms for 8255 handshake data input from a tape mm, In
PORT A IN PC3
PORT C TO ENABLE
INTERRUPT SIGNAL INTERRUPT REQUEST
FOR NODE 2 PIN NUMBER SET PORT C BIT
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-
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
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
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.
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.
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.
CHASIS- Printer chasis GND. In the printer, the chassis GND and the logic GND are isolated from
17 - -
18 NC Not used.
The level of this signal becomes "low" when the printer is in "Paper End" state, "Offline"
32 ERROR OUT
state and "Error" state
34 NC Not used.
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-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.
.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
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
Initialization
set up control block
i f error then
ex i t
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.
save registers
wait 1 usee
wait 1 usee
restore registers
i/, i
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.
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.
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
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)
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
REFERENCE
Software Keyboard Interfacing
CURRENT
CIRCUIT CONNECTIONS AND ALGORITHM
OUTPUT
PORT 01
READ
COLUMNS
NO s
/all\.
KEYS
YES
READ
COLUMNS
NO y. /key\
WAIT
20 ms
OUTPUT
ZERO TO
ONE ROW
READ
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
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
IE HAIT.PRESS
;Debounce key;iress
MOV CX, 16EAH i delay of 20 »s
DELAY: LOOP DELAY
IN AL, DX ; read columns
OUT DX, AL
MOV DX, OFFFBH ; read columns & check for low
IN AL, DX
AND AL, OFH ; mask out row code
KEYBRD ENDP
CODE_HERE ENDS
END START
FIGURL ()-2l (continued)
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
'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)
&
£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
Rl-7 = 1 k<>
Ql-7 = 2N3906
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.
ft ft Y BLANKY
:tive HIGH A CODE' A
A I 1IVI HIGH
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.
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
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
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
I ICURE 9-29 8279 command word formats and bit descriptions. (Intel Corporation)
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
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.
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
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
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-
Aim
4 BIT
AD1
LATCH
AIV
AD3
2 BIT
2 TO 4
LATCH
DECODER
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
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
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 »
1 OFF OFF ON ON
3 ON OFF OFF ON
5 ON ON OFF OFF
7 OFF ON ON OFF
1 OFF OFF ON ON
D4^>>
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.
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?
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
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
Rl R2
R3 Rf
vou1(v, v^^Xll)
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-
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.
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
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.
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)
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
SSSfE
S3"*
n
WWMG8Z
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.
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-
161 SERIAL
MR SC OUTPUT
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
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-
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
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.
STACK.HERE
SEGMENT
DH 40 BUPi0)
STACK.TOP LABEL WORD
STACK HERE ENDS
OUT DX, AL
MOV AL, 11000W00B ; Clear display character is all 0's
OUT DX. AL
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
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
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
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
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
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
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
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
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-
A MICROCOMPUTER-BASED INDUSTRIAL
PROCESS-CONTROL SYSTEM — I BAND
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
TACHOMETER
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
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^/
END OF
CONVERSION
START
CONVERSION
ALE
AH:
DAS
LM329^k
REFERENCE
FOR A/D
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
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
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
" 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.
NOP
C0DE_HERE
EMD5
END
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.
ncK, i
EXTRN :BvTE,
COUNTER LOOPNUM:ByTE
'ATA HERE END;
INT_PROC
.HERE SEGMENT
WORDPUBLIC ;seqment for interrupt service procedures
ASSUME CS:INT_PRQC_HERE,
D5:DATA_HERE
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
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
LOOPS HERE
; DUMMY
LOOP1 PROC FAR
instructions for this loop
RET
LOOPi ENDP
CODE.HERE l'<u?
END
PAGE ,131
; MODULE4 - CONTAINSTHE SERVICE PROCEDURESNEEDEDBY THE LOOP MODULES
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
BINCVT ENDP
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.
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
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
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?
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
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)
INTR C 18 J J TEST
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
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)
_ ., %%
I
ADDRESS
LATCHES
AD0-AD15 '
^°-
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.
_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.
-( ADDRESSVALID^ ADDRESSVALID
)-
/ V
\ y— v 7^
j-
\^r
INT EOP \ r
FIGURE 11-4 Timing diagram for 8237 DMA transfer. (Intel Corporation)
1 0 ILLEGAL
SIGNALS
INTERNAL DATA BUS
CHANNEL REGISTER OPERATION FLIP-FLOP DB0-DB7
cs IOR IOW A3 A.' A1 AO
READ 0 0 0 0 A0-A7
CURRENT ADDRESS
0 0 II 0 A8-A15
READ 0 0 0 0 0 A0-A7
CURRENT ADDRESS
0 0 0 II 0 A8-A15
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)
CASSETTEI 0 KEYBOARD I 0
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
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
\ 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
O
t>
H J_ N p^
CLK \
_L
RASO 1 L -A
CASO 1
8208
1
__/ Wl
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
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
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.
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
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
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)
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
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
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
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
/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)
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
INCREASING SIGNIFICANCE
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)
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-
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
Li INVALID
DENORMALIZED
OPERATION
OPERAND
ZERODIVIDE
OVERFLOW
UNDERFLOW
PRECISION
(RESERVED)
INTERRUPT REOUEST
CONDITION CODE1"
BUS I
FIGURE 11-21 8087 control and status word formats, (a) Control, (b) Status.
(Intel Corporation)
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-
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
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
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
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.
FICOM source — Compares ST to a short or long integer for the instruction. Exceptions: P.
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.
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-
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
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
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
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
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
0OB9 90 NOP
OOBA 90 NOP
OOBB HERE ENDS
CODE_
END START
J-U rar I I
I I
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.
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
—
£
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
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
COMMAND ACTIVE
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-
80 186/80 188— integrated peripherals Serial and parallel bus arbitration schemes
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.
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.
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
JL JL JL JUTJl-T-LT-Lrnr-lJlJUlj-L
~a| {/^
BLANKING ONE VERTICAL SYNC PULSE
(BLACK) FOR EACH 262-5 HORIZONTAL
LEVEL PULSES
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
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
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
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
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
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.
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
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
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.
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.
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
CHARACTER -
ALPHA COLOR
GENERATOR
SERIALIZER ENCODER %º
ROM
PALETTE/
OVERSCAN HORIZONTAl
VERTICAL
COMPOSITE
TIMING COLOR —
MODE
GENERATOR GENERATOR
CONTROL
'
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
COMPOSITE
COLOR
Y. R-Y * VIDEO
FROM
COLOR
Q
CAMERA
{OR
MEMORY)
HORIZONTAL, VERTICAL
AND BLANKING PULSES
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-
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
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.
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.
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] ^^
33
byti r BYTES BYTES
/
/
/
/
TRACK SECTOR
0 0 CHECKSUM DATA CHECKSUM
NUMBER N JM8ER
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_
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-
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
OUTPUT RW/SEEK
Wl PORT HEAD LOAD
HEAD SELECT
LOW CURRENT/DIRECTION
FAULT RESET/STEP
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
(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
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.
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.
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.
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.
OBJI CTIVE I I NS
f
HELIUM NEON
READ LASER
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
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. 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
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
After a short time the heating elements are turned off DEVELOPER UNIT
V0ICED
Speech Synthesis Methods SIGNAL
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
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
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
File handle
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.
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':'
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
, *- • » • 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.
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
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
DTR a RECEIVE RxRDY Rei eivei ready (has character for CPU)
MODEM
BUFFER
CTS -a
CONTROL TxRDY Transmitter ready (ready for cha from CPU)
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-
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
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
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
OUT DX, AL
MOV CX, 2 ; and delay
DU: LOOP D<+
MOV AL, 00110111B ; Load command word and send it
OUT DX, AL
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
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
11 UNASSIGNED
12 SCf 11 CO LINE SIG DETECTOR Ml il
13 SCB SECONDARY CLEAR TO SEND H! 1
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
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.
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
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-
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
^ '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
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
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
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
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.
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
ERR_MESS_PQINTERS
DM 0 i Dummy,no ERR_NESS0
DH OFFSETERRJESS1
DM OFFSET ERRMESS2
DU OFFSETERRJ1ESS3
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
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
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
LOAD
J 1 ENDP
CODE.HERE
ENDS
END START
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
BIT 7 6 5 4 3 2 BIT 7 6 5 4 : 0
- 0
(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
[a)
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
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
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
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.
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.
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
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.
\onH
TERMINATOR TERMINATOR
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
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.
(3 SIGNAL LINES)
DEVICE C
(E G , SIGNAL GENERATOR)
(5 SIGNAI I INI S)
DEVICE D
MEANING
UNIVERSAL COMMANDS
LISTEN ADDRESSES
IE G . TAPE READER]
UNL'STEN COMMAND
TALK ADDRESSES
UNTALK COMMAND NRFD
SECONDARY COMMANDS NDAC
IGNORED
FIGURE 13-38 CPIB pins, signal lines, and waveforms, (a) Connector, (b) Bus
structure, (c) Command formats, (d) Data transfer handshake waveforms.
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
baud rate
Token-passing rings
UART, USART. DTE, DCE
GPIB. HPIB. IEEE 488 bus standard
20- and 60-mA current loops listener, talker, controller
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-
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:
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
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
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
ROOT DIRECTORY
OPERATING
SYSTEM CODE
D = DIRECTORY
F = FILE
T = DEVICE
CAN BE REFERENCED AS