100%(1)100% found this document useful (1 vote) 569 views609 pagesDouglas
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
re eae ll pe
‘eae i
and Interfacing
DOUGLAS V HALL
For Sale in India, Pakistan, Nepal, Bangladesh, Sri Lanka and Bhutan only|Tata McGraw-Hill
Special Indian Edition 2006
Adapted in India by arrangement with The McGraw-Hill Companies, Inc.,
New York
Sales territories : Indi
Pakistan, Nepal, Bangladesh, Sri Lanka and Bhutan only
MICROPROCESSORS AND INTERFACING: Programming & Hardware,
Revised Second Edition
Eighth reprint
DZXACDDXRVQCY
Copyright © 1992 by the Glencoe Division of Macmillan/McGraw-Hill School
Publishing Company. Copyright © 1986 by McGraw-Hill, Inc. All rights reserved.
‘No part of this publication may be repreduced or distributed in any form
or by any means, or stored in a database or retrieval system, without the
‘riot written permission of the publisher.
IBM PC, 1BM PC/XT, IBM PC/AT, PS/2, and MicroChannel Architecture are registered
trademarks of IBM Comporation. The followingare registered trademarks of Intel Corporation:
i486™, i860™, ICE, RMX. Borlané, Sidekick, Turbo Assembler, TASM, Turbo Debugger,
and Turbo C+ are registered trademarks of Borland Intemational, inc, Microsoft, MS,
MS DOS, Windows 3.0, Codeview, and MASM are registered trademarks of Microsoft
‘Corporation. Other product names are registered trademarks of the companies associated
‘with the product aame reference in the text of figure.
ISBN-13: 978-0-07-060167-3
ISBN-10: 0-07-060167-4
Published by Tata McGraw-Hill Publishing Company Limited,
7 West Patel Nagar, New Delhi 110 008, and printed at
Pashupati Printers (P) Ltd, 1/429/16, Gali No. 1,
Friends Colony, GT Road Shahdara, Delhi 110 095
Cover : SDR Printers
eeeContents
Prefice xi
Acknowledgements xiv
1. Computer Number Systems, Codes, and Digital Devices 1.1-1.20
Computer Number Systems and Codes 1.1
Arithmetic Operations on Binary, [Link] BCD Numbers _/.7
Basic Digital Devices _/./2
Review Questic
2. Computers, Microcomputers, and Microprocessors 2.1-2.21
‘=An Introduction
TypesofComputers 2.7
How Computers and Microcomputers are Used—AnExample__ 2.2
Overview of Microcomputer Structure and Operation 2.6
Execution ofa Three-instructionProgram 2.7
Microprocessor Evolution and Types 2.9
The8086 Microprocessor Family—-Overview _2.1/
8086 Internal Architecture 212
Intoductionto Programming the 8086 2.76
Review Questions and Problems 2.20
8. 8086 Family Assembly Language Programming—Introduction _3.1-8.32
Program Development Steps _3./
Constructing the Machine Codes for 8086 Instructions 3.2
Writing Programs for Use with an Assembler__3./9
Assembly Language Program Development Tools _ 3.26
Review Questions and Problems 3.29
4. Implementing Standard Program Structures in 8086 4.1-4.36
‘Assembly Language
Simple Sequence Programs 4.)
[Link] Multiple If-Then-Else Programs 4.15
While-Do Programs 4.20
Repeat-Until Programs 4.22
Instruction Timing and DelayLoops 4.34
Review Questions and Problems 4.viii Contents
5. Strings, Procedures, and Macros
The 8086 String Instructions _ 5.1
‘Writing and Using Procedures 5.6
and mbler Macro!
Review Questions and Problems 5.39
6. 8086 Instruction Descriptions and Assembler Directives
InstructionDescriptions 6.1
Agsemblir Directive 430
snd Program 6.32
ENDP—End Procedure 6.
EVEN—Alignon Even Memory Address 6.37
EXTRN 633
GLOBAL—-Declare Symbols as Public or Extm 6.33
GROUP—-Group-elated Segments 6.33
LABEL 6.34
LENGTH—Not hnplementedinIBMMASM _ 6.34
NAME 6.34
OFFSET 6.34
ORG-—Originate 6.34
PROC—Procedure 6.35
PTR—Pointer 6.35
Segment 6.35
Shoxt 4.35
Type 6.36
7. 8086 System Connections Timing, and Troubleshooting
‘A Basic 8086 Microcomputer System 7.
Usinga Logic Analyzer to Observe Microprocessor Bus Signals 7.7
An Example Minimum-mode System, The SDK-86_ 7/2
Troubleshooting a Simple 8086-based Microcomputer 7.42
Review Questions and Problems 7.47
8. 8086 Interrupts and Interrupt Applications
5.1-5.40
6.1-6.36
7.14.48
8.1-8.44
8086 Interrupts and Interrupt Responses 8.1
‘Hardware Interrupt Applications 8./2
8254 Software-Programmable Timer/Counter 8.17Contents ix
8259A Priority Intenupt Controller 8.30
Sofiware Interrupt Applications 8.39
Review Questions and Problems 3.41
9. Digital Interfacing 9.1-9.50
Programmable Parallel Portsand Handshake Input/Output 9.
interfacing a Microprocessorto Keyboards 9.17
Interfacing to Alphanumeric Displays 25
8279 CircuitComnections and Operation Overview 9.28
Interficing to 18-segment and Dot-matrix Led Displays 9.35
interfacing aMicrocomputerto Nonmultiplexed Led Displays _ 9.36
interfacing Microcomputer Ports to High-powerDevices 9.37 ,
Optical Motor ShaftEncoders 9.44
Review Questions and Problems 9.47
10. Analog Interfacing and Industrial Control 10.1-10.60
Review of Operational-amplifier Characteristics and Circuits 10.2
Sensorsand Transducers 10.7
D/AConverter Operation, Interfacing, and Applications 10.13
A/D Converter Specifications, Types, and Interfacing /0./77
A Microcomputer-based Seale 10.21
A Microcomputer-based Industrial Process-control System 10.31
An 8086-based Proc: ontrol System 10.35
Developingthe Prototype of Microcomputer-based instrument 10.46
Robotics and Embedded Control 70.47.
Digital Signal Processing and Digital Filters 10.52
Review Questions and Problems 10.59
11. Dma, Drams, Cache Memories, Coprocessors, and Eda Tools 11.1-11.49
Introduction 11.2
The 8086 MaximumMode 1/.4
Direct Memory Access (DMA) Data Transfer 11.5
Interfacing and Refreshing DynamicRAMs 17.10
A Coprocessor—The 8087 Math Coprocessor 11.23
Computer-based DesignandDevelopment Tools 11.39
Review Questions and Problems 11.48
12. C, a High-level Language for System Programming 12,1-12.52
Introduction—A SimpleC Program Example 12.2
Program Development Tools forC 12.3
Programming in@ 12.7
Review Questions and Problems 12.50
13. Microcomputer System Peripherals 13. 59
System-level Keyboard Interfacing _/3.1
Microcomputer Displays 13.5
Computer Mice and Trackballs 13.34 .disk Data-storage Systems 13.34
Optical Disk Data Storage 13.49
Printer Mechanisms and Interfacing 13.50
and Recognition with aComputer 13.853
Digital Video Interactive 13.55
Review Questions and Problems 13.57
14. Data Communication and Networks
Introduction to Asynchronous Serial Data Communication 14.1
erial-d
Transmission MethodsandStandants [44.8
20-and 60-ma Current Loops 14.9
Asynchronous Communication Software on the BM PC_ 14.23
Synchronous Serial-data Communication and Protocols 14.35
ica Area NWO 7]
The GPIB. HPIB.IEEE488 Bus _/4.44
Review Questions and Problems 14.50
15. The 80286, 80386 and 80486 Microprocessors
Multiuser’Multitasking Operating System Concepts _ 15.2
The Intel 80286 Microprocessor 15.11
The Inte] 80386 32-bitMicroprocessor 15.16
The Intel $0486 Microprocessor 15.41
Review Questions and Problems 15.44
16, An Introduction to the Pentium Processors
Epilogue 16.18
Review Questions and Problems 16.19
Appendix A
Appendix B
Appendix C
Bibliography
Index
14.1-14.52
15.1-15.45
16.1-16.19
Bib, t-Bib.3
LinkPreface
‘This book is written for a wide variety of introductory microprocessor courses. The only prerequisite for this book is
some knowledge of diodes, transistors, and simple digital devices.
My experience as an engineer and as a teacher indicates that it is much more productive to first learn one
microprocessor family very thoroughly and from that strong base learn others as needed. For this book I chose the
Intel 8086/80 186/80286/80386/80486 and Pentiuin family of microprocessors, Deviecs inthis family arc uscd in millions
and millions of personel computers, including the IBM PC/AT, the IBM PS/2 models. and many “clones.” The 8086
was the first member of this family, and although it has been superseded by newer processors, the 8086 is still an
excellent entry point for leaming about microprocessors. You don’t need to know about the advanced features of the
newer processors until you leam about multiuser/multitasking systems, Therefore, the 8086 is used for most of the
hardware and programming examples until Chapter 15, which discusses the features of the higher processors and
hhow these features are used in multiuser/multitasking systems. Chapter 16 further discusses Pentium Processors and
their architecture.
CONTENT AND ORGANIZATION
All chapters begin with furdamental objectives and conclude with a review of important terms and concepts. Each
chapter also concludes with a generous supply of questions and problems that reinforce both the theory and applications
presented in the chapters.
To help refresh your memory, Chapter | contains a brief review of the digital concepts neoded for the rest of the
book. It also includes an overview of basic computer mathematics and arithmetic operations on binary, HEX, and BCD
numbers.
Chapters 2-10
Chapters 2-10 provide you with a comprehensive introduction to microprocessors, including interrupt applications.
digital and analog interfacing, and industrial controls. These chapters include an overview of the 8086 microprocessor
family and its architecture, programming language, and systems connections and troublestooting.
Because I came into the world of electronics through the route of vacuum tubes, my first tendency in teacking
microprocessors was to approach them from a hardware direction. However, the more I designed with microprocessors
and taught microprocessor classes, the more I became aware that the real essence of a microprocessor is what you
can program it to do. Therefore, Chapters 2-5 introduce you to writing structured assembly language programs for
‘the 8086 microprocessor. The approach taken in this programming section is to solve the problem, write an algorithm
for the solution, and then simply transtate the algorithm toassembly language. Experience has shown that this approach
is much more likely to produce a working program than just writing down assembly language instructions. The 8086
instruction set is introduced in Chapter 2-5 asneeded to solve simple programming problems, but for reference Chapter
6 contains a dictionary of all 8086 instructions with examples for each.
Chapter 7 discusses the signals, timing, and system connections for 2 simple 8086-based microcomputer. Also
discussed in Chapter 7 is a systematic method for troubleshooting a malfunctioning 8086-based microcomputer system
and the use of a logic analyzer to observe microcomputer bus signals. Chapter 8 discusses how the 8086 responds to
interrupts, how interrupt-service procedures are written, and the operation of a peripheral device called a priority-
interrupt controller,
Chapters 9 and 10 show how a microprocessor is interfaced with a wide variety of low-level input and output
devices. Chapter 9 shows how a microprocessor is interfaced with digital devices such as keyboards, displays, and
relays, Chapter 10 shows how a microprocessor is interfaced with analog input/output devices such as A/Ds,xi 2 Preface
D/As, and a variety of sensors. Italso shows how all the “pieces” are put together to produce a microprocessor-based
seale and a simple microprocessor-based process contro} system, Chapter 10 concludes with a discussion of how
‘microprocessors can be used to implement digital filters,
Chapters 11-16
Chapters 11-15 are devoted to the hardware, software, and peripheral interfacing for a microcomputer such as those
in the IBM PC and the IBM PS/2 families. Chapter 11 discusses motherboard circuitry, including DRAM systems,
‘caches, math coprocessors, and peripheral interface buses. It also shows how to use a schematic capture program to
draw the schematic, a simulator program to verify the logic and timing of the desig, and a layout program to design
4 printed-circuit board for the system. Knowledge of these electronic design automation tocls is essential for anyone
developing high-speed microprocessor systems.
At the request of many advisors from industry, Chapter 12 introduces you to the C programming language, which
is used to write a lange number of system-level programs. This chapter takes advantage of the fact that itis very easy
to learn if youare already familiar with 8086-type assembly language. A section in this chapter also shows you how
to write simple programs which contain both C and assembly language modules
Chapter 13 describes the operation and interfacing of common peripherals such as CRT displays, magnetic disks,
and printers. Chapter 14 shows how a microcomputer is interfaced with communication systems such as modems
and networks.
Chapter 15 starts with a discussion of the needs that must be met by a multinser/multitasking operating system and
then describes how the protected-mode features of the 80286, 80386, and 80486 processors meet these needs. This
section of the book also includes discussions of kow to develop programs for the 386 in a variety of environments.
‘The chapter concludes with introductions to parallel processors, neural networks, and fuzzy logic. [think you will ind
these newly developing areas as fascinating as 1 have
Finally, Chapter 16 is about the Pentium processors and their architecture. Data transfer between processor and
memory or /O is also discussed. The chapter ends with a brief description of the Hyper Thread or HT Technology.
SUGGESTIONS FOR ASSIGNMENTS
Flexible Organization
The text is comprehensive, yet flexible in its organization, Chapter | could be easily omitted if students have a solid
background in basic binary mathematics and digital fundamentals,
Chapters 2-10
1 suggest following Chapters 2-10 as an instructional block as each chapter builds on the preceding chapter. These
nine chapters represent ideal coverage for a “short course” in microprocessors. The remaining chapters represent an
‘opportunity for the instructor to tailor assignments for the students’ needs or perhaps to give an individual student
added study in recent developments in the architecture of microprocessors.
Chapter 11
Individual topics from Chapter 11 could be selected for study as students gain knowledge of the “tools” available for
designing computer-based systems. The DRAM section is very important.
Chapter 12
‘You may wish to assign or leave for outside reading Chapter 12 on programming in C,, a new chapter. At the very least
you should take a careful look at the simple programming examples and the development of tools for C. If class time
‘does not permit assigning this chapter, youmnay wish to use selected examples and programs in your lecture presentations.
This chapter should be included in any course sequence which does not have a separate class in C programming.Preface: xiit
Chapter 13
Portions of the peripherals chapter may be assigned as required, depending upon the course syllabus, The CRT, disk,
and printer sections are highly recommended
Chapter 14
This is an important chapter, given the ever-expanding use of data communications. It should be assigned, if at all
possible, ualess the curriculum includes a separate course in data communications. Of primary importance are the
sections on modems and LANS.
Chapters 15 and 16
The last two chapters discuss the cutting edge of the development of higher microprocessors up to 8046 and the
Pentium Processors,
SALIENT FEATURES OF THIS EDITION
In response to feedback from a variely of electronics instructors. and fiom the industry, the revised second edition of
Microprocessors and Interfacing: Programming and Hardware contains the following salient features.
Focused coverage of 8086 microprocessor.
Examples of programs with C and assembly language modules.
Interfacing illustrated via real life systems.
Introduction to Neural Networks and Fuzzy Logic.
Inclusion of a new chapter on Pentium Processors.
Focused discussion on Software Keyboard Interfacing
Multimedia Technologies: MMX, SSE, SSE2 and SSE3 are also discussed.
SPECIAL FEATURES AND SUPPLEMENTS
This book contains many hardware and software exercises students can do to solidify their knowledge of
microprocessors. A dedicated website now supports the book. This website contains the lustructor’s Manual and
Experiments Manual for instructors and students,
The Experiments Manual contains 40 laboratory exercises that are directly coordinated to the text. Fach experiment
includes chapter references. required equipment. objectives. and experimental procedures. An IBM PC or IBM PC-
compatible computer can be used to edit, assemble, link/locate, run, and debug many of the 8086 assembly language
programs.
‘The Instructor's Manual contains answers to the review questions. It also includes experimental notes and answers
to selected questions for the Experiments Manual.
ADDITIONAL GOALS
One of the main goals of this book isto teach you how to decipher manufacturers” data sheets for microprocessor and
peripheral devices, so the book contains relevant parts of mary data sheets. Because of the large number of devices
discussed, however, it was not possible to include complete datasheets. I you are doing anin-cepthstudy, itis suggested
that you acquire oF gain access to the latest editions of Intel Microprocessors and Peripherals handbooks. These are
available free of charge to colleges and universities from the Academic Relations Department of Intel. The bibliography
at the end of the book contains a list of other bocks and periodicals you can refer to for further details on the topies
discussed in the book.
If you have suggestions for improving the book or ideas that might clarify @ point for someone else, please
communicate with me through the publisher.
Douglas V. KallAcknowledgements
1 wish to express my profound thanks to the people around me who helped make this book a reality. Firsily, 1 would
like to thank Dr. K.M. Hebbar, Director, Computer Engineering, NMAM Institue of Technology, NITTE, Kamataka,
for the effort put into adapting this edition of the book. His efforts have indeed updated the book to current standards,
‘Thanks to Pat Hunter, whose cheerful encouragement helped me through seemingly endless details. She proofread and
coded the manuscript, worked out the answers to the end-of-chapter to verify that they are solvable, and made
suggestions and contributions toonumerous to mention, Thanks to Richard Cihkey of New England Technical Institute
in New Britain, Connecticut, who meticulously worked his way through the manuscript and made many valuable
suggestions. Thanks to Mike Olisewski of Instant Information, Inc,, who helped me “C the light” in Chapter 12 and
contributed his industry perspective on the topics that should be included in the book. Thanks to Dr. Michael A. Driscoll
of Portland State University, who helped me fine-tune Chapter 15. Thanks to Intel Corporation forletting me use many
drawings from their data books so that this book could lead readers into the real world of data books. Finally, thanks
to my wife, Rosemary, my children Linda, Brad, Mark, Lee, and Kathryn, and to the rest of my family for their patience
and support during the long effort of rewriting this book.
Douglas V. HaltComputer Number
Systems, Codes, and
Digital Devices
fore starting our discussion of microprocessors
B and microcomputers, we need to make sure that
some key concepts of the number ystems, codes,
and digital devices used in microcomputers are fresh in
your mind. If the short summaries of these concepts in
this chapter are not enough to refresh your memory, then
you may want to consult some of the chapters in Digital
Cirewits and Systems, McGraw-Hill, 1989, before going
‘on in this book.
Aithe conclusion of this chapteryou should beable to:
1. Convert numbers between the folowing codes: binary.
‘hexadecimal, and BCD.
2. Define he terms bis, nibble, byte, word, most sgnificane
bit, and leas significane bit.
3. Use atableto find the ASCII or EBCDIC code fora given
elphanuomerc character
4. Perform addition and subractionofbinarg hecadecimal, and
BCDnumbers.
5. Describe theopertionof aes flip-flops aces regen, ROMS,
PALs dynamic RAM, static RAMs, and buses
6 Describe bow an arithmetic logic unit can be instructed 0
perform arithmetic ological operations on binary words,
COMPUTER NUMBER SYSTEMS
AND CODES
Review of Decimal System
‘To understand the structure of the binary number system,
the first step is to review the familiar decimal or base-10
number system, Here is a decimal number with the value
of each place holder or digit expressed as a power of 10.
5 3 4 6 7 2
10 = 10? tok 10 t0"! 10?
‘The digits in the decimal number 5346.72 thus tell you
that you have 5 thousands, 3 hundreds, 4 tens, 6 ones,
7 tenths, and 2 hundredths. The number of symbols
needed inany number system isequal tothe base number.
Inthedecimal number system, then, there are 10 symbols,
Othrough 9. When the count in any digit position passes
that of the highest-value symbol, the digit rolls back to 0
and the next higher digit is incremented by 1. A car
‘odometer is a good example of this.
‘A number system ean be built using powers of any
number as place holders or digits, but some bases are more
useful than others. Its difficult to build electronic circuits
which can store and manipulate 10 different voltage levels,
but relatively easy to build circuits which can handle two
levels. Therefore, a binary, or base-2, number system is,
used to represent numbers in digital systems.1.2
Microprocessor and Interfacing: Programmntng and Hardware
‘The Binary Number System
Figure Ila, shows the value of each digit in a binary
number. Each binary digit represents a power of 2, A
binary digitis often called a bit. Note that digitsto the right
of the binary point represent fractions used for numbers
less than 1. The binary system uses only two symbols,
zero (0} and one (1), so in binary you count as follows
0,1, 10, 11, 100, 101, 110, 111, 1000, ete. For reference
Fig. |.1h shows the powers of 2 from 2! to 2”.
Binary numbers are often called binary words or just
words. Binary words with certain numbers of bits have
also acquired special names. A 4-bit binary word is called
a nibble, and an 8-bit binary word is called a byte. A
[Link] binary word is often referred to just asa word, and
32-bit binary word is referred to as a doubleword. The
rightmost or least significant bit of a binary word i
usually referred to as the LSB. The leftmost or most
significant bit of a binary word is usually called the MSB.
To convert a binary number to its equivalent decimal
‘number, maltiply each cigittimes the decimal value ofthe
digit and just add these up. The binary number 101, for
example, represents: (1 x 2) + (0 x 2!) + x 2%),
,ortrord
PPP Ae Be ae
mez iwe 421 t 4
(a)
oe
g8
%
pie aio = s3.808a82
4.004 26144 2% = 67,108,864
208 2% = stan a = 134,217,728
4096 2 = 1008576 2 = 258,435,458
e122 = 2.007.152 2 = 536,870,912
16,386 = 41943042” = 1.073,741,824
32.768 = aaeaeoe 2 = 2.147.403,648
2 = 85596 2 = 16.77.2162 = 4,204,967,298,
()
Fig. L1 (a) Digit values in binary, (6) Powers of 2.
or4+0+1
‘you have:
x 4 OXF) 41x 2741 x29 + Ox 2
4x2) + (1X2) =
16+ 044424 0+ 05 + 0.25 = decimal 22.75
{mal 5. For the binary number 10110. 11,
To convert a decimal number to binary, there are two
‘common methods. The first (Fig. |.2a) is simply a reverse
of the binary-to-decimal method. For example, to convert
the decimal number 21 (sometimes written a5 219) to
binary, first subtract the largest power of 2 that will fit in
the number, For 21 the largest power of 2 that will fitis
16 or 2*. Subtracting 16 from 21 gives a remainder of 5.
Puta 1 in the 2 digit position and see if the next lower
power of 2 will fit in the remainder, Since 2 is 8 and 8
will not fit in the remainder of 5, put a 0 in the 2° digit
position. Then try the next lower power of 2. In this case
the next is 2 or 4, which will fit in the remainder of 5. A
1 is therefore put in the 2° digit position. When 2* or 4is,
subtracted from the old remainder of 5, anew remainder
of | is left. Since 2' or 2 will not fit into this remainder, a
Oiisputin that position. A 1 is putin the 2° position because
2" is equal to 1 and this fits exactly into the remainder of
1. The result shows that 21 9 is equal to 10101 in binary.
This conversion process is somewhat messy 10 describe
but easy todo. Try converting 4649 10 binary. You should
get 101110.
Another method of converting a decimal number to
binary is shown in Fig, 1.26. Divide the decimal number
bby 2 and waite the quotient and remainder as shown. Divide
this quotient and following quotients by 2 until the quotient
reaches 0, The column of remainders will be the binary
cequivalentof the given decimal number. Note that the MSD
ison the bottom of the column and the LSD is on the top
of the column if you perform the divisions in order from
the Cop to the bottom of the page, You can demonstrate
that the binary number is correct by reconverting from
binary to decimal, as shown in the right-hand side of
Fig. 1.26.
You can convert decimal numbers less than I to binary
by successive multiplication by 2, recording carries until
the quantity to the right of the decimal point becomes zero,
as shown in Fig. 2c. The carries represent the binary
equivalentof the decimal number, with the most significant
bit at the top of the column, Decimal 0.625 equals 0.101
in binary. For decimal values that do not convert exactly
the way this one did (the quantity to the right of the
decimal never becomes zero), you can continue the
conversion process unl you get the number of binary
digits desired.Computer Number Systems, Codes, and Digital Devices 1.3
At this point itis interesting to compare the number of
digits required to express numbers in decimal with the
‘number required to express them in binary. In decimal,
one digit can represent 10! numbers, 0 through 9; two
digits can represent 10° or 100 numbers, 0 through 99;
and three digits can represent 10° or 1000 numbers, 0
through 999. Inbinary, asimilar pattem exists. Onebinary
digit can represent 2 numbers, Oand 1; two binary digits
can represent 2° or 4 numbers, 0 through 11; and three
binary digits can represent 2° or 8 numbers, 0 through
111. The pattern, then, is that N decimal digits can
represent 10" numbers and N binary digits can represent
2" mumbers. Eight binary digits can represent 2¥ or 256
numbers, 0 through 255 in decimal.
BA 222
smo 42
so1o10
@)
Least Signtteant
Bnary Digit
RI x18 = 128
t 227 Chock
Most Sgnificant
Binary Digit
00011
@
sa.
625 Be
Fig. 1.2 Converting decimat to binary. (a) Digit
value method, (b) Divide by 2 method,
(¢) Decimal fraction conversion.
Hexadecimal
Binary is not a very compact code. This means that it
requires many more digits to express a number than does,
for example, decimal, Twelve binary digits can only
describe anumber up 104095 , Computers require binary
data, but people working with computers have trouble
remembering long binary words. One solution to the
problem is to use the hexadecimal or base-16 number
system.
Figure |.3a shows the digit valves for hexadecimal,
‘which is often just called ex. Since hex is base 16, you
have to have 16 possible symbols. one for each digit. The
table of Fig. 1.3b shows the symbols for hex code.
{WW 1610" 16-1167 1697 \
cae
acs 266 16 1
Dec Hex |
20 6:8 |
te1 929 |
222 A
223 8
4n4 eo
| een)
| 626 Wee
| Te? BsF
| re)
|
22 y= Ee
\ @
Fig.1.3° Hexadecmalnumbers, (q) Value of place
holders, (b) Symbols, (c) Decimat-to-
hexadecimalconversion.
After the decimal symbols 0 through 9 are used up.
you use the letters A through F for values 10 through 15.
‘As mentioned above, each hex digit is equal to four
binary digits. To convert the binary number 11010110 to
hex, mark off the binary bits in groups of 4, moving to
the Jeft from the ‘ nary point, Then write the hex symbol
for the value of each group of 41a Microprocessor and Interfacing: Programming and Hardware
Binary 1101 0110
Hx oD 6
‘The 0110 group isequal to 6 and the 1101 group isequal
Since 13 is D in hex, 11010110 binary is equal to
hex. “H” is usually used after a number to indicate
that it is a hexadecimal number. For example, D6 hex is
usually written DOH. As you can see, 8 bits can be
represented with only 2 hex
If you want to convert a number from decimal to
hexadecimal, Fig. |.3c shows familiartrick fordoing this.
‘The result shows that 227, is equal to E3H. As you can
see, hex is an even more compact code than decimal. Two
hexadecimal digits can represent a decimal number up to
255. Four hex digits can represent a decimal number up
10 65,535.
To illustrate how hexadecimal numbers are used in
digital logic, a service manual tells you that the 8-bitwide
data bus of an 8088 microprocessor should contain 3FH
during acertain operation. Converting 3FHto binary gives
the pattern of I's and 0's (QOI1 1111) you would expect
to find with your oscilloscope or logic analyzer on the
parallel lines. The 3FH is simply a shorthand which iseasier
to remember and less prone to errors than the binary
equivalent.
BCD Codes
STANDARD BCD
In applications such as frequency counters, digital volt-
meiers, or calculators, where the output is a decimal
Table 1.1 Cormunon Number Codes
display, a binary-coded decimal or BCD code is often used.
BCDusesa4-bit binary codeto individually representeach
decimal digit in a number. As you can see in Table 1.1,
the simplest BCD code uses the first 10 numbers of
standard binary code for the BCD numbers 0 through 9.
‘The hex codes A through F are invalid BCD codes. To
convert a decimal number to its BCD equivalent, just
represent each decimal digitby its 4-bit binary equivalent,
as shown here.
Decimal 5 2 9
BCD 0101 101001
To convert a BCD number to its decimal equivalent,
reverse the process.
GRAY CODE
Gray code is another important binary code; it is often
used for encoding shaft position data from machines such
as computer-controlled lathes. This code has the same
possible combinations as standard binary, but as you can
see in the 4-bit example in Table 1.1, they are arranged
in a different order. Notice that only one binary digit
changes at a time as you count up in this code,
If you need to construct a Gray-code table larger than
that in Table 1.1, a handy way to do so is to observe the
pattern of I'sand0’sand just extend [Link] least significant
digit column starts with one and then has alternating
gToups of two I's and two 0's as you go down the column,
‘The second most significant digit column starts with two
0's and then has alternating groups of four |"s and four
Binary-Coded Decimal Reflected _7-Segment Display (l= on)
Decimal Binary Octal Hex 8421 BCD EXCES: Gry " abedefg Display
Code
ii 0000=~«~S*=<“<«S~C O11 OO1} 0000 mt
oor O11 0100 0001-01 10000 1
0102 OO 0101 = O01 1oroL 2
ool 3 O11 O10 00101111001 3
01004 OO OT O10 “OT EDOAT 4
ol 5 O11 1009 O11 1o1t011 2
oo 6 0011 1001 o101 lori 6
our 7 O11 1019 01001110000 7
8 100010 Co 1001111111 8
9 tor on 9 oti 1100 1101 tito011 9
10 1010 «AL 0100 OO 1111 HLAL1OL A
n tol BB (000d 100 1001110 O ETAT B
2 10 ~« | C~«(OOOT 0010-0100 O101~—«1010.~=«~ OT AOF €
B Hor 15 D0} ool! = 0100 1101011 orii0t D
4 110 16 E000 Qi 0100 O11 1001 ont E
15 ui ___000t 10! 0100 10001000 ODI LL FEComputer Number Systems, Codes, and Digital Devices 1.5
O's. The third column starts with four 0's, then has
alternating groups of eight 1's and eight 0's. By now you
should see the pattern. Try to Fig. out the Gray code for
the decimal number 16. You should get 11000.
7-Segment Display Code
Figure 4a shows the segment identifiers fora 7-segment
display such as those commonly used in digital
instruments. Table 1.1 shows the logic levels required to
display 0 to 9 and A to F on a common-cathode LED
display such as that shown in Fig. 4b. For a common-
anode LED display such as that in Fig. 14c, simply invert
the segment codes shown in Table 1.1
Alphanumeric Codes
‘When communicating with or between computers, you
need a binary-based code which can represent letters of
the alphabet as well as numbers. Common codes used for
this have 7 or 8 bits per word and are referred to as
alphanumeric codes. To detect possible errors in these
codes, an additional bit, called a parity bit is often added
as the most significant bit.
Parity is a term used to identify whether a data word
has an odd or even number of I's. Ifa data word contains
an odd number of ls, the word is said to have odd parity.
‘The binary word 0110111 with fivel’s has odd parity. The
binary word 0110000 has an even number of I's (two),
so it has even parity.
In practice the parity bitis used as follows. The system
that is sending a data word checks the parity of the word.
If the parity of the data word is odd, the system will set
the parity bit toa 1. This makes the parity of the data word
plus parity biteven. Ifthe parity of the data word is even,
the sending system will reset the parity bit to a 0. This
Table 1.2 Common AlphanumericCodes
again makes the parity of the data word plus parity even.
The receiving system checks the parity of the data word
plus parity bit that it receives. If the receiving system
detects odd parity in the received data word plus parity, it
assumesan error has occurred and tells the sending system
to send the data azain, The systems then said to be using
even parity. The system could have been set up to use
(maintain) odd parity in a similar manner.
Fig. 1.4 7-segment LED display, (a) Segment
labels, (b) Schematic of common-cathode
type, (c) Schematic of common-anode
type.
ASCIL
Table 1.2 shows several alphanumeric codes. The first
of these is ASCH, or American Standard Code for Infor-
‘mation Interchange. This is shown in the table as a 7- bit
code. With 7 bits you can code up to 128 characters,
‘which isenovgh for the full upper- and lowercase alphabet,
ASC HEX EBCDIC HEX ASC) HEX EBG@DIG HEX ASCH HEX EBCDIC HEX
Symbol Code Symbol Code Symbol Code ‘Symbol. Code Symbol Code Symbol Code
for 7-Bit for for 7-Bit for for 7-Bit for
ASCIL EBCDIC ASCIL EBCDIC EBCDIC
NUL 00 | NUL * 2A * 5 5
SOH 01 SOH_ ool . 2B + 4E u
STX 02 SIX @ 2 8 ES
EX 03 FIX : w rs
FOT 0: | BOT 37 4B n
BENQ 05) ENQ. 2D 1 i ol B
ACK 06 ACK 0 0 FO B
BA? BL 1 1 Fl AD
(Contd)1.6
-Microprocessorand interfacing: Programming and Hardware
(Contd.)
ASG HEX EBCDIC HEX ASCIN HEX EBCDIG HEX | ASC HEX EBCDIG HEX
Symbol Code Symbol Code Symbcl__Code Symbol_ Code Symbol Code Symbol Coe
foe 7-Bit for for 7-Bit for for 7-Bit for
ASCIL EBCDIC ASCUL EBCDIC ASCIL EBCDIC
BOS BS 1G 2 z Fr oe xc NE 5
HT HT OS 3 3 F3 ics 9D ( pp
LF OA Th 4 4 Fa “ = 7 e
VI (OB week 5 5 5B fa + = ©
FF OC ee) OC leg 6 F6 : © RES ut
Roop ce o ie 7 F7 a 1 a a
SO OF SO. 0c | 8 8 FR b @ b 2
Si OF Si OF 9 9 Fo © 6 © 8
DE 0 DE 0 : : 7A a a 4 4
pe ls eee SE © 6 © s
oo 2 fee pl xc Re 4c f « f %6
he, 3 fos 2B aD 7E ® a ® a
i es \ 3, \ oF b 6 h %
INAK 1S NAK 3D? F 1 oF i © i ®
SYN 16 SIN 2 @ 4 e 7c iy (6A i 1
EB O70 OB. HA A a k @ k 2
CAN 18 (CAN 18 = B 2 <8 i 1 «© 1 g
mM 19 ™ » (|e 3 re G. mo oO m 4
See) 1A Poe oF Tepe 44 D ce o « a 6
rey (BeBe es E 5 oF 0 %
sy ee Re eg F co io P 9
cs wD oS wo Men o G 7 4 1 4 8
7 Er Boe © ae « H cs r r »
US oF us oF 1) 2 1 9 s s a2
sp sP 0 Ti 4A J DI t t a3
ei 5A ee 48 K D2 u a Ad
1 2 a fey ac L D3 v Vv a3
i 2 * 3 eM) 3 fem D4 w w 6
3. 4 s 5s lay a N Ds x x a7
% 2 * c O| ° bo zi y a8
& % Be) 0 Bae P D7 z x a9
a2 7D Mowe st Q DS ( { B
C 2 oe > mee 2 R be 1 1 F
) 2 2 > ao Ss s E2 } } B
: é 4A
Da DEL o
numbers, punctuation marks, and control characters. The EBCDIC
code is arranged so that if only uppercase letters,
numbers, and a few control characters are needed, the
lower 6 bits are all that are required. If parity check is
‘wanted, a parity bit is added to the basic 7-bit code in the
MSB position. The binary word 1100 0100, for example,
is the ASCII code for uppercase D with odd parity.
‘Table 1.3 gives the meanings of the control character
symbols used in the ASCII code table.
Another alphanumeric code commonly encountered in
IBM equipment is the Extended Binary-Coded Decimal
Interchange Code or EBCDIC. This is an 8-bit code
without parity. A ninth bitcan be added for parity. To save
space in Table 1.2, the eight binary digits of EBCDIC are
represented by their 2-digit hex equivalent.Computer Number Systems, Codes, aitd Digital Devices LZ
Table 1.3 Definitions of Control Characters
ROE) Nat DEI Direct contrat T
SOH Star of heading DEZ__ Direct control 2
SUX Start ext DE Direct control 3
ETX End text DE Direct contra 4
OT End of AK Negative
transmission acknowledge
ENO Enquiry SYN. Synchronous idie
ACK Acknowledge ETB End transmission
BEL 0S block
BS Backspace CAN: Cancel
HT > Horizontal tab EM End of medium
IF Line feed SUB Substitute
ME Vertical tab FSC Escape
TF Formfced FS Form separator
RH Carrisge ow GS Group separator
SO Shift out RS Record separator
St Shift in US = Unit separator
DLE link escape
ARITHMETIC OPERATIONS ON
BINARY, HEX. AND BCD NUMBERS
Binary Arithmetic
ADDITION
Figure|.Sashows the wuth table for addition of two binary
digits end acarry in (C,) from addition of previous digits
Fig. 1.5b shows the result of adding two 8-bit binary
S=A@BOCy
Cour =A" B+ Gn (ASB)
@
s0011010
+ nomn00
@ orono
cary
C)
¥ig.1.5. Binary addition, (a) Truthtable for 2 bits
plus carry. (6) Addition of two 8-bit
words.
‘numbers together using these rales. Assuming that Cy
1, 1+0+Cyy=asum of Oanda carry into the next digit
and 1 +14 Gy =a sum of 1 and a carry into the next
digit because the result in any digit position can only be a
For 20.
2/S-COMPLEMENT SIGNS-AND-MAGNITUDE
BINARY
When you handwrite a number that represents some
physical quantity suchas temperature, you can simply put
a+ sign in front of the number to indicate that the number
is positive, or you can write a sign to indicate that the
number is negative. However, if you want to store values
such as temperatures, which can be positive or negative,
in a computer memory, there is a problem. Since the
computer memory can store only I's and 0's, some way
must be established to represent the sign of the number
with a 1 or a0.
‘A common way to represent signed numbers is to
reserve the most significant bit of the data word as a sign
bit and to use the rest of the bits of the data word to
represent the size (magnitude) of the quantity. A computer
that works with 8-bit words will use the MSB (bit 7) as
the sign bitand the lower 7 bits to represent the magnitude
‘of the numbers, The usual convention is to represent a
positive number with a 0 sign bit and anegative number
with aT
‘Tomake computations with signed numbers easier, the
magnitude of negative numbersis represented in special
form called 2's complement. The 2's complement of a
binary number is formed by inverting each bit of the data
word and adding | to the result. Some examples should
help clarify all ofthis.
The number +749 is represented in 8-bit sign-an
‘magnitude form as 000001111. The sign bit is 0, which
indicates a positive number. The magnitude of positive
‘numbers is represented in straight binary, so 00000 111
in the least significant bits represents 7,0,
To represent ~7, in 8-bit 2's-complement sign- and-
magnitude form, start with the 8-bit code for + 7,
(00000111. Invert each bit, neluding the MSB, toget 1111
1000, Then add 1 to get 11111001. This resultis the correct
representation of ~7,9. Fig. 1.6 shows some more
‘examples of positive and negative numbers expressed in
8-bit sign-and-magnitude form. For practice, try
generating each ofthese yourself to see if you get the same
result.
To reverse this procedure and find the magnitude of a
number expressed in sign-and-magnitude form, proceed
as follows, If the number is positive, as indicated by the1.8 Microprocessor and interfacing: Programming and Hardware
2! oo00114
0} 101110,
0! 1401001,
41 1110100
11 7001010
1 0007014
4} 1010010
‘Sign and
‘two's complement
‘of magnitude
Fig.1.6 Positive and negative numbers repre-
sented with a sign bit and 2's comple-
ment.
sign bit being a0, then the least significant 7 bits represent
the magnitude directly ia binary. If the numbers negative,
as indicated by the sign bit being a 1, then the magnitude
is expressed in 2's complement. To get the magnitude of
is negative number expressed in standard binary, invert
ach bit of the data word, including the sign bit, and add
1 to the result. For exemple, given the word 11101011,
invert each bit to get 00010100. Then add 1 to get
(00010101. This equals 21 o.s0 you know that the original
numbers represent ~219. Again, try reconverting a few
of the numbers in Fig. 1.6 for practice.
Figure 1.7 shows some examples of addition of signed
binary numbers of this type. Sign bits are added together
just as the other bits are. Fig. 7a shows the results of
‘adding two positive numbers. The sign bit ofthe result is,
zero, so the result is positive. The second example, in Fig.
1.76, adds a-9 to a+13 or, in effect, subsracts 9 from 13.
As indicated by the zero sign bit, the result of 4 is positive
and in true binary form.
Figure .7c shows the result of adding a—13 to asmaller
positive number, +9. The sign bit of the resut is 2 1. This,
indicates that the result is negative and the magnitude
in 2's-complement form. To reconvert a 2’s complement
result to a signed namber in true binary form:
1, Invert each bit to produce the 1’s complement.
2. Addi.
3. Put a minus sign in front to indicate that the result
is negative.
The final example, in Fig. 1.7d, shows the result of
adding two negative numbers. The sign bit of the result is,
a, so theresult is negative and in 2's-complement form.
‘Again, inverting each bit, adding 1, und prefisinga minus
sign will put the result in a more recognizable farm.
‘Now let's consider the range of numbers that can be
represented with 8 bits in sign-and-magnitude form. Eight
bits can represent a maximum of 2* or 256 numbers. Since
‘we are representing both positive and negative numbers,
half of this range will be positive and half negative
‘Therefore, the range is -128 to +127. Here are the sign-
and-magnitude binary representations for these values:
OLLLtdat 4127
00000001 41
00000000 zero
didiidit
10000001 -127
10000000 -128
413° _0o00t107
+9 90001001
422 soo10T10,
‘son bitis 0
20 recut le positive
a)
+13 oooott01
= 3, ANT10111_2's complement for ~9 with sign bit
‘90000100
{Sign bitis 0
‘50 resut is positive
Ignore carry
»
0001001
{1110011 2's complement for —13 with sign tt
11111100. Sign bitis 1
190000011 0 Invert each bit
1 Add 1
40000400 Prefix with minus sign —
eed
@
‘41110111 2's complement for
41110014 Sign-and-magnitude fon
11101010 Signbitis 1
‘30 invert each Bi
ae 4 Add t
90010110 Prefix wit minus sign
_ i
Fig. 1.7 Addition of signed binary numbers,
(lq) +9 and +13. (a) -9 and +13. (d +9
and -13. (d)-9 and -13.
Ifyou like number patterns, you might notice that this
scheme shifts the normal codes for 128 to 255 downward
to represent ~128 to ~1Computer Number Systems, Codes, and Digital Devices
If a computer is storing signed numbers as 16-bit
words, then a much larger range of numbers can be
represented. Since 16 bits gives 2'° or 65,536 possible
values, the range for 16-bit sign-and-magnitude numbers
is ~32,768 to +32,767. Operations with 16-bit sign-and-
magnitude numbers are done the same way as operations.
with 8-bitsign-and-magnitude numbers
SUBTRACTION
There are two common methods for doing binary sub-
traction, These are the pencil method and the 2°s-
‘complement add method. Fig. L8a shows the truth table
for binary subtraction of two binary digits A and B. Also
included in the truth table is the effect of a borrow.
from subtracting previous digits. Fig. 1.8 shows an
‘example of the “pencil” method of subtracting two 8-bit
numbers. Using the truth table, this method is done the
same way that you do decimal subtraction,
A second method of performing binary subtraction is
bby adding the 2's-complement representation of the bottom
umber (Sabtrahend) to the top number (minuend). Fig,
1 8eshowshow thisis done. Firstrepresent the top number
in sign-and-magnitude form. Then form the 2’s-
complement sign-and-inagnitude representation for the
negative of the bottom number. Finally, dd the two parts
formed. For the example in Fig. 8c, the sign of the result
Bays
19
is @ 0, which indicates that the result is positive and in
true form. The final carry produced by the addition can
be ignored. Fig. 1.84 shows another example of this
‘method of subtraction. In this ease the bottom number is
larger than the top number, Again, represent the top
number in sign-and-magnitude form, produce the 2's
complement sign-and-magnitude form for the negative of
the bottom number, and add the two together. The sign
bit of the result isa I for this example. This indicates that
the result is negative and its magnitude is represented in
2’s-complement form. To get the result into a form that
is more recognizable to you, invert each bit of the result,
add 1 to it, and put a minus sign in front of it as shown in
Fig. 18d.
Problems that may occur when doing signed addition
or subtraction are overflow and underflow. If the
magnitude of the nomber produced by adding wo signed
numbers is larger than the number of bits available to
represent the magnitude, the result will “overflow” into
_the sign bit position and give an incorrect result. For
‘example if the signed positive number 01001001 is added
lo the signed positive number OLO1I01, the result is
10110110. The | in the MSB of this result indicates that it
is negative, which is obviously incorrect for the sum of
two positive numbers. In asimilar manrer, doing an 8-bit
signed subtraction that produces a magnitude greaterthan
soror010
INPUTS BUTPUT 03100100
A [B [Bal D] Bou i
ofo|o] oo
o}ofa]s| 4 ”
ois fol a] 4
afal tf Ste orort011 orono11
tfolo}t| o s +11070010
AR =A6y 00101119 avert
i|$]ojel 6 Be leach bit | JOOTOHIOT = 45,5
abilstat$ ‘i
One'scome \- 1101001 | + + nace
DIFFERENCE =A© By, ‘aa ys i) Pees.
BORROW =4-B + (A8B)-8yy Jwo'scome ——notoato/ | andintrue
@ ‘Cay. ary frm
°
Tie 91001101 exo0r01
rors ane ee coplanar
10100811 Be pe one ory
Two'scomp 19101000 Bnd in o's
carry! Somploment )
a m /
Fig.1.8 Binary subtraction, (a) Truth table for 2 bits and borrow, (b) Pencil method, (c} 2's-complement
positive result, (d) 2’s-complement negative result.1.10
=128 will cause an “underflow” into the sign bit and
produce an incorrect result.
For simplicity the examples showa use 8 bits, but the
method works for any number of bits. This method may
seem awkward, but it is easy to do ina computer or
microprocessor because it requires only the simple
operations of inverting and adding
MULTIPLICATION
‘There are several methods of doing binary multiplication.
Fig. 1.9 shows what is called the pencil method because
it is the same way you learned to multiply decimal
‘numbers. The top number, or multiplicand, is multiplied
by the least significant digit of the bottom number, or
multiplier. The partial product is written down, The top
numberis then multiplied by the next digit of the mukiplier.
‘The resultant partial product is written down under the
last, but shifted one place to the left. Adding all the partial
products gives the total product. This method works well
‘when doing mukiplication by hand, but itis not practical
fora computer because the type of shifts required makes
it awkward to implement.
(1 4011 MULTIPLICAND
|< 9 x 4001 MULTIPLIER
| tor
‘0000
Bago | PARTIAL PRODUCTS
son
{oooH PRODUCT
Fig. 1.9 Binary multiplication.
One of the multiplication methods used by computers,
is repeated addition. To multiply 7 x 55, for example, the
‘computer can just add up seven $5's. For large numbers,
however, this method is slow. To multiply 786 x 253, for
example, requires 252 add operations.
Most computers use an add-and-shift-right method.
This method takes advantage of the fact that for binary
multiplication, the partial product can only be either the
topnumber exactly if the mukiplier digit isa | ora0 if te
multiplier digit isa 0. The method does the same thing as
the pencil method, except that the partial products are
added as they are produced and the sum of the partial
products is shified right rather than each partial product
being shifted left.
‘A point to note about multiplying numbers isthe number
‘of bits the product requires. For example, multiplying two
4-bit numbers can give a product with as many as 8-bits,
and two 8-bit numbers can give a 16-bit product.
Microprocessor and Interfacing: Programming and Hardware
DIVISION
Binary division can also be performed in several ways
Fig. 1.10 shows two examples of the pencil method.
is the same process as decimal long division. However, it
is much simpler than decimal long division because the
digits ofthe result (quotient) canonly be 0or I. A division
is attempted on par of the dividend. If this isnot possible
because the divisors larger than that part of the dividend,
a Qisentered inthe quotient. Anotherattempt is then made
to divide using one more digit of the dividend. When a
divisien is possible, a 1 isenteredin the quotient. The divisor
is then subtracted from the portion of the dividend used.
‘As with standard long division, the process is continued
until all the dividerd is used. As shown in Fig. L10b,0°s
can be added to the right of the binary point and division
continued to convert a remainder to a binary equivalent.
04109 quotient
| pimsor 110)7901000 DIVIDEND 12
0.
2
10
a
| 0
| (a)
|
| ost ez
| sof 1005.00 yas
cs
©)
Fig. 1.10 Binary division.
Another method of division that is easier for com-
puters and microprocessors to perform uses successive
subtractions. The divisor is subtracted from the dividend
and from each successive remainder until a borrow is
produced. The desired quotient is 1 less than the number
of subtractions needed 10 produce a borrow. This method
is simple, but lor large numbers it is slow.
For faster division of large numbers, computers use @
subtract-and-shift-left method that is essentially the same
process you go through with a pencil long di
Hexadecimal Addition
and Subtraction
People working with computers or microprocessors often
use hexadecimal as a shorthand way of representing long
binary numbers such as memory addresses. ILis therefore
useful to be able to add and subtract hexadecimal
numbers.Computer Number Systems, Codes, and Digital Devices
1
ADDITION
As shown in Fig. I.11a, one way to add two hexadeci-
‘mal numbers is to convert each hexadecimal number to
its binary equivalent, add the two binary numbers, and
convert the binary result back to its hex equivalent. For
converting to binary, remember that each hex digit
represents 4 binary digits
‘A second method, shown in Fig. 1.116, works directly
with the hex numbers. When adding hex digits, a carry is
produced whenever the sum is 16 decimal or greater.
Another way of saying this is thet the value of a carry in
hex is 16 decimal. For the least significant digits in Fig.
1.116, 4n A inhex is 10 indecimal and an Fis Sin decir.
These add to give 25 decimal, This is greater than 16, 50
mentally subtract 16 from the 25 to give a carry and a
remainder of 9. The 9 is written down and the carry is
added to the next digit column. In this column 7 plus 3
plus a carry gives a decimal 11, or B in bex.
cary
‘
7A ont 1010 1) Ae
+3f | Soom ttt sa Fe
Be 1011 1007 tthe 25:0
8 8 Be 86
@ @)
Wig. 1.11 Hexadecimal addition.
You may use whichever method seems easier to you
and gives you consistently right answers. If you are doing
a great deal of hexadecimal arithmetic, you might buy an
electronic calculator specifically designed to do decimal,
binary, and hexadecimal arithmetic.
SUBTRACTION
Hexadecimal subtraction is similar to decimal subtraction
except that when a borrow is needed, 16 isborrowed from
the next most significantdigit Fig. 1-12 showsan example
of this. It may help you to follow the example if you do
partial conversions o decimal in yourhead. For example,
7 plus a borrowed 16 is 23. Subtracting B or II leaves 12
oF C inhexadecimal. Then 3 from the 6 left after a borrow
leaves 3, so the result is 3CH
Wig. 1.12 Hexadecimal subtraction.
BCD Addition and Subtraction
In systems where the final result of a calculation is to be
displayed, such as a calculator, it may be easier to work
with numbers in a BCD format. These codes, as shown
in Table 1.1, represent each decimal digit, D through 9,
by its 4-bit binary equivalent.
ADDITION
BCD can have no digit-word with a valve greater than 9.
‘Therefore, a carry mustbe generatedif the result ofa BCD
addition is greater than 1001 or 9. Fig. 1.13 shows three
examples of BCD addition. The first, in Fig. 1.134, is very
straightforward because the sum for each BCD digit is
less than 9, The result isthe same asit would be for adding
standard binary,
For the second example, in Fig. 1.13b, adding BCD 7
to BCD 5 produces 1100. This is a correct binary result
of 12, butit isan illegal BCD code. To convert the result
to BCD format, a correction factor of 6 is added. The
result of adding 6 is 0001 0010, which is the legal BCD
code for 12.
Figure |.13c shows another case where a correction
factor must be added. The initial addition of 9 and 8
cD
oot! O101
+23 +0010 0071
‘0107 1000
@
co
ont
+0101
2 1100 INCORRECT BCD
+0110 ADDS
|
| 0001 0010 CORRECT BCD 12
®
aco
° ior
+8 + 4oco
17 0001 0001 INCORRECT BCD.
0000 0119 ADD 6
000 O11 CORRECT BCD 17
©
a )
Fig. 1.13 BCD addition, (a) Nocorrection needed.
(b) Correction needed because of illegal
BCD result, ( Correction needed because
of carry-out of BCD digit.
produces 0001 0001. Even though the lower four digits
are less than 9, tis is an incorrect BCD result because a
carry out of bit 3 of the BCD digit-word was produced.112
‘This carry out of bit 3 is often called an auxiliary carry.
Adding the correction factor of 6 gives the correct BCD
result of 0001 OL1! of 17.
To summarize, a correction factor of 6 must be added
ifthe result in the lower 4 bits is greater than 9 or if the
jl addition produces a carry out of bit 3 of any BCD
i-word. Thiscorrection issometimes called a decimal
adjust operation.
‘The reason for 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 cary out of the lower 4 bits does not occur until
after 1111 or 15. The difference between the two carry
points is 6, s0 you have to add 6 to produce the desired
carry ifthe result of an addition in any BCD digit is more
than 1001.
SUBTRACTION
Figure 1.14 shows a subtraction, BCD 17 (0001 0111)
minus BCD 9 (0000 1001). The initial result, 0000 1110,
is nota legal BCD number. Whenever this occurs in BCD
subtraction, 6 must be subtracted trom the inital resultto
produce the correct BCD result. For the example shown
in Fig. 1.14, subtracting 6 gives a correct BCD result of
(0000 1000 or 8,
17 ooor ont )
9 0000 1001
9000 1110 ILLEGAL BCD
=0110 SUBTRACTS
000 160 CORRECT BCO
Fig. 1.14 BCD subtraction.
The correction factor of 6 must be subtracted from
any BCD digit-wordit that digit-wordis greaterthan 1001,
or if'a borrow from the next higher digit was required to
do the subtraction.
BASIC DIGITAL DEVICES
Microcomputers such as those we discuss throughout this
book often contain basic logic gates as “glue” between
LSI (large-scale integration) devices. For troublshooting
these systems, itis important to be able to predict logic
levels at any point directly from the schematic rather than
having to work your way through a truth table for each
gate. This section should help refresh your memory of
basic logic functions and help you remember how to
quickly analyze logic gate circuits
Microprocessor and interfacing: Programming and Hardware
Inverting and Noninverting Buffers
Figure 1.15 shows the schematic symbols and truth tables
for simple buffers and logic gates. The first thing to
remember about these symbols is that the shape of the
symbol indicates the logic function performed by the
device. The second thing to remember about these
symbols is that a bubble or no bubble indicates the
assertion level for an input or output signal. Let's review
how modern logic designers use these symbols.
1.154 has no
bubbles on the input or output. Therefore, the input is
active high and the output is active high. We read thi
symbol as follows: Ifthe input A is asserted high, then
the output Y will be asserted high. The rest of the truth
table is covered by the assumption that if the A input is,
not asserted high, then the Y output will not be asserted
high,
The next two symbols for a buffer each contain a
bubble. The bubble on the output of the first of these
indicates that the output is active low. The input has no
eal!
ls wal |
SaSee]
loso-l-<|
Kb
[)-
@
Saaen]
noo-<
Y=AB HRB
si’ }
@ J
Fig. 1.18 Buffers and logie gates. (a) Buffers. (b)
AND-NAND, (c) OR-NOR, (d) Exclusive
OR.Computer Number Systems, Codes, and Digital Devices
bubble, so it is active high. You can read the function of
the device directly from the schematic symbol as follows.
If the A input is asserted high, then the Y ontput will be
asserted low. This device simply changes the assertion
level of a signal. The output Y will always have a logic
state which is the complement or inverse of that on the
input, so the device is usually referred to as an inverter.
The second schematic symbo! for an inverter in
Fig. 1.15a has the bubble on the input. We draw the
symbol this way when we want to indicate that we are
using the device to change an asserted-low signal to an
asserted-high signal, For example, if we pass the signal
GS through this device, itbecomes CS. The symbol tells
you directly that ifthe inputis asserted low. then the output
will be asserted high. Now let's review how you express
the functions of logic gates using this approach,
Logic Gates
Figure 1.15b showsthe symbols and truth tables for simple
logic gates. A symbol with a flat back and a round front
indicates that the device performs the logical AND function,
‘This means that the output will be asserted if the A input
is asserted ad the B inputis asserted. Again, bubbles or
‘no bubbles are used to indicate the assertion level of each
input and output. The first AND symbol in Fig. 1.15b has
‘no bubbles, so the inputs and the output are active high.
‘The output then will be asserted high if the A input is
asserted high and the B input is asserted high. The bubble
‘on the output of the second AND symbol in Fig, 1.155
indicates that this device, commonly called 2 NAND gate,
has an active low output. If the A input is asserted high
and the B input is asserted high, then the ¥ output will be
asserted low. Look at the truth table in Fig. 1.15b to see if
you agree with this.
Figure 1.1Se shows the other two possible cases for the
AND symbol. The first of these has bubbles on the inputs
and on the output. [f you see this symbol in a schematic,
‘you should immediately see that the output will be asserted
low ifthe input is asserted low and the B input is asserted
ow. The second AND symbol in Fig. 1.15c has no bubble
‘on the output. so the output will be asserted high if the A
and B inputs are both asserted low.
‘A logic symbo! with a curved back indicates that the
‘output of the device will be asserted if the A input is
asserted or the B input of the device is asserted. Again,
bubbles or no bubbles are used to indicate the assertion
level for inputs and outputs. Note in Fig. 1.15 and cthat
each of the AND symbol forms has an equivalent OR
symbol form. An AND symbol withactive high inputs and
an active high output, for example, represents the same
1.13
device (a 74LS08 perhaps) as an OR symbol with active
Tow inputs and an active low output. Use the truth table in
Fig. 1.15b to convince yourself of this. The bubbled-OR
representation tells you that if one input is asserted low,
the output will be low, regardless of the state of the other
input. As we will show later in this chapter, this is often a
usefull way to think of the operation of an AND gate.
Figure 1.15d shows the symbol and truth table for an
exclusive OR gate and for an exclusive NOR gate. The
output of an exclusive OR gete will be high if the logic
levels on the two inputs are different. The output of an
exclusive NOR gate will be high if the logic levels on the
two inputs are the same.
‘You need o be familiar with all these symbols, because
most logic designers will use the symbol that best describes
the function they want a device to perform in a particular
circuit.
Programmable Logic Devices
Instead of using discrete gates. modem microcomputer
systems usually use programmable logic devices such 2s
PLAs, PROMS, or PALS to implement the “glue” logic
between LSI devices. To refresh your memory.
Figure 1.16 shows the internal structure of each of these
devices. As you can see, they all consist ofa programmable
AND- OR matrix, so they can asily implement any sum-
of products logic expression. Each AND gate in these
figures has up to four inputs, but to simplify the drawing
only a single input line is shown, Likewise, the OR gates
have several inputs, but are shown with a single input line
to simplify the drawing. These devices are programmed
by blowing out fuses, which are represented in the figure
by Xs. An X im the figure indicates that the fuse is intact
and makes a connection between, for example, the output
of an AND gate and one of the inputs of an OR gate. A
‘dot atthe intersection of two wires indicates a hard-wired
connection implemented during manufacture.
Inaprogrammable logic array (PLA) or field program
‘mable logic array (FPLA), both the AND matrix and the
OR matrix are progammable by leaving in fuses or
blowing them out. The two programmable matrixes make
FPLAs very flexible, but difficult to program.
In a programmable read-only memory or PROM, the
AND matrix is fixed and just the OR matrix is
programmable by leaving in fuses or blowing them out.
PROMS implement all the possible product terms for the
input variables, so they are useful as code converters
In a programmable array logic device or PAL, the
‘connections in the OR matrix are fixed and the AND matrix
connections are programmable. PALs are often used to14
implement combinational logic and address decoders in
microcomputer systems.
Heer
rusiaeavo J
AB PAL
HARDWIRED
OR
A
oe
AB
=
a
PROGRAMMABLE,
"AND
Fig.1.16 FPLA, PROM, and PAL programmed to
implement some simple logie functions,
(a) FPLA, (a) PROM, (c) PAL
A computer program is usually used to develop the fuse
map for an FPLA, PROM, or PAL. Once developed, the
fise-map file is downloaded toe programmer which blows
fuses or stores charges to actually program the device.
‘Microprocessorand Interfacing: Programming and Hardware
Latches, Flip-Flops, Registers, and
Counters
THE D LATCH
A latchisadigital device tat stores.a | ora onits output.
Fig. 1.17 shows the schematic symbol and truth table
for a D latch. The device functions as follows. If the
enable input CK is low, the logic level present on the D
input will have no effect on the Q and Q outputs.
Fig. 1.17 Latches and flip-flops, (a) D latch. (b) D
Slipflop.
This is indicated in the truth table by an X in the D
column. If the enable input is high, a high or alow on the
D input will be passed to the Q output. In other words,
the Q output will follow the D inpat as long as the enable
input is high. The Q output will contain the complement
of the logic state on Q. When the enable input is made
low again, the state on Q at that time will be latched there.
Any changes on D will have no effect on Quntilthe enable
input is made high again, When the enable input goes low,
then, the state present on D just before the enable goes
Tow will be stored onthe Q output. Keep this operation in
‘mind as you read about the D flip-flop in the next section,
THE D FLIP-FLOP
Figure 1.170 shows the schematic symbol and the truth
table for atypical D flip-flop. The small triangle next to
the CK input of this device tells you that the Q and Q
‘outputs are updated when a rising signal edge is applied
to the CK input. The up arrows in the clock column of
the truth table also indicate that a 1 or 0 on the D input
will be copied to the Q output when the clock input goes
from low tohigh. In other words, the D flip-flop takes aComputer Number Systems, Codes, and Digttal Devices
1.15
snapshot of whatever state is on the D input when the
clock goes high, and displays the “photo” on the Q output.
If the clock inputis low, achange on D willhave noeffect
‘onthe output. Likewise, ifthe clock input ishigh, a change
on D will have no effect on the Q output. Contrast this
‘operation with that of the D latch to make sure you
understand the difference between the two devices.
‘The D flip-flop in Fig. 1.17b also has direct set (S) and
reset(R) inputs. A flip-flop is considered setif ts Q output
isa 1. Itis reset if its Q output is a0. The bubbles on the
set and reset inputs tell you that these inputs are active
low. The truth table for the D flip-flop in
Fig. 1.17b indicates that the set and reset inputs are
asynchronous. This means that ifthe set input is asserted
tow, the output will be set, regardless of the states on the
D and the clock inputs. Likewise, if the reset input is
asserted low, the Q output will be reset, regardless of the
state of the D and clock inputs. The Xs in the D and CK
‘columns of the truth table remind you that these inputs
are “don't cares” if set or reset is asserted. The condition
indicated by the asterisks (*) isa nonstable condition; that
. it will not persist when reset or clear inputs return t0
their inactive (high) level.
REGISTERS
Flip-flops can be used individually or in groups to store
binary data. A registeris a group of D flip-flopsconnected
in parallel, as shownin Fig. 1.18a, A binary word applied
to the data inputs of this register will be transferred to the
‘Q outputs when the clock input is made high. The binary
‘word will remainstored on theQ outputs until anew binary
‘word is applied to the D inputs and a low-te-high signal is
applied to the clock input. Other circuitry can read the
stored binary word from the Q outputsat any time without
changing its value.
If the Q output of each flip-flop in the register is
connected to the D input of the next as shown in
Fig. 1.185, then the register will function asa shift register
‘A 1 applied to the first D input will be shifted to the first
Qoutput bya clock pulse, The next clock pulse will shift
this I tothe outpat of the second flip-flop. Each additional
clock pulse will shift the I to the next flip-flop in the
register. Some shift registers allow you to load a binary
‘word into the register and shift the loaded word left or
right when the register is clocked, As we will show later,
the ability to shift binary numbers is very useful.
COUNTERS
Flip-flops can also be connected to make devices whose
outputs step through a binary or other count sequence
‘when they are clocked. Fig. 1.19a shows a schematic
symbol and count sequence for a presettable 4-bit binary
Counter. The main point we want to review here is how a
presettable counter functions, so there is no need to go
into the internal circuitry of the device. Ifthe reset input
is asserted, the Q outputs will al be made O's. After the
reset signal is unasserted, each clock pulse will cause the
Fig. 1.18 Registers, (a) Simple data storage, (b)
Shiftregister.
i
3
aoassaasessesseap|
|
Fig. 1.19 Four-bit. presettable binary counter, (a)
‘Schematic symbol, (fa) Count sequence.
binary count on the outputs to be incremented by 1. As
shownin Fig. 1.198, the count sequence will go from 0000
to 1111, Hf the outputs are at 1111, then the next clock1.16
pulse will cause the outputs to “roll over” to 0000 and a
carry pulse to be sent out the carry output. This carry
pulse can be used as the elock input for another counter.
Counters can be cascaded to produce as large a count
sequence asi needed fora parila appliaion, The
‘maximum count for a binary counter is 2° — 1, where
is the number of flip-flops.
Now, suppose that we want the counter to start
counting from some number other than 0000. We can do
this by applying the desired number to the four data inputs
and asserting the load input. For example, if we apply a
binary 6, 0110, to the data inputs and assert the load input,
this value will be transferred to the Q outputs. After the
load signal is unasserted, the next clock signal will
increment the Q outputs to 0111 or 7.
ROMs, RAMs, and Buses
The next topics we need to review are the devices that
store large numbers of binary words and how several of
these devices can be connected on common data lines.
ROMS
‘The term ROM stands for read-only memory. There are
several types of ROM that can be written to, read, erased,
and written to with new data, but the main feature of ROMS
is that they are nonvolatile. This means that the
information stored in them is not lost when the power is
removed from them.
Microprocessor and Interfacing: Programming and Hardware
Figure 1.20a shows the schematic symbol of a com-
mon ROM. As indicated by the eight dara outputs, DO to
D7, this ROM stores bit data words. The data outputs
are three-state outputs. This means that each output can
be at a logic low state, a logic high state, or a high-
impedance floating state. In the high-impedance state an
‘ontputis essentially disconnected from anything connected
toit. If the CE input of the ROM is not asserted, then all
the outputs will be in the high-impedance state. Most
ROMs also switch to a lowerpower consumption standby
mode if CE is not asserted. If the CE input is asserted,
the device will be powered up, and the output buffers will
beenabled. Therefore, the outputs will beat a normal logic
ow or logic high state. If you don’t happen to remember.
you will soon see why this is important
You can think of the binary words stored in the ROM
asbeing ina long, numberedlist. The number that identifies
the location of each stored word in the list is called its
‘address. You can tell the nuniber of binary words stored
inthe ROM by the aumber of address inputs. The aumber
of words is equal to 28, where N is the number of address.
lines. The device in Fig. 1.20a has 15 address lines, AO to
A14, so the number of words is 2'* or 32,768, Ina data
sheet this device would be referred to as a 32K x
8ROM. This means it has 32K addresses with 8 bits per
address.
In order to get a particular word onto the outputs of
the ROM, you have to do two things. You have to apply
‘ADDRESS: DATA
INPUTS ouTeuTs
ar)
s 8 ADDRESS
ze BUS
A303
Ad
AS OS Ate
Aste
ayo
— {a8
fe ROM ,
— ato
an 5
= ce
—ais
ae DATA
ce BUS
oe
®
D706 D§ D4 D3 D2D100
0
ce
97.065 D403 02 D1 0
()
Fig. 1.20 ROMs, (a) Schematic symbol. (b) Connection in paraitel.Computer Number Systems, Codes, and Digital Devices
1.17
the address of that word to the address inputs, AO to A14,
‘and you have to assert the CE input to power up the
device and to enable the three-state outputs.
Now, le’s see why we want three-state outputs on this,
ROM. Suppose that we want to store more than 32K data
‘words. We can do this by connecting two or more ROMs
in parallel, as shown in Fig. 1.20b. The address lines
connect to each device in parallel so we can address one
of the 32.768 words ineach. A set of parallel lines used to
send addresses or data to several devices in this way is
called a bus. The data outputs of the ROMS are likewise
connected in parallel so that any one of the ROMs can
‘output data on the common data bus. If these ROMs had
standard two-state outputs, a serious problem would
‘occur when both ROMS wied (0 output data words on
the bus. The resulting argument between data outputs
would probably destroy some of the outputs and give
meaningless information on the data bus. Since the ROMS
have three-state outputs, however, we ean use external
circuitry to make sure that only ore ROM at a time has
its outputs enabled. The very important principle here is
that whenever several outputs are connecied on a bus,
the outputs should all be three- state, and only one set of
outputs should be enabled at a time.
ithe beginning ofthis section we mentioned that some
ROMs can beerased and rewritten or reprogrammed with
new data, Here’s a summary of the different types of
ROMs.
Mask-programmed ROM—Programmed during
manufacture; cannot be altered
PROM User programs by blowing fuses; cannot be
altered except to blow additional fuses.
EPROM Electrically programmableby user: erased by
shining ultraviolet light on quartz. window in package.
EEPROM—Electrically programmable by user; erased
with electrical signals, so it can be reprogrammed in
circuit.
Flash EPROM—Electrically programmable by user,
erased electrically, so it can be reprogrammed in circuit,
STATIC AND DYNAMIC RAMS.
‘The name RAM stands for random-access memory, but
ce ROMS are also random access, the name probably
should be read-write memory. RAMS are also used to store
binary words. A static RAM is essentially a matrix of flip:
flops. Therefore, we can write a new data word in a RAM
locatior at any time by applying the word to the flip-flop
data inputs and clocking the flip-flops. The stored date
‘wont will remain on the flip-flop outputs as long as the
power is Ieft on. This type of memory is volatile because
data is lost when the power is tumed off.
Figure 1.21 shows the schematic symbol for a
common RAM. This RAM has 12 address lines, AOto AU1,
so it stores 2'? (4096) binary words. The eight data lines
tell you that the RAM stores 8-bit words. When we are
reading a word from the RAM, these lines function as
‘outputs. When we are writing a word to the RAM, these
lines function as inpats. The chip enable input, CE,, is
used to enable the device for a read or for a write. The
R/W input will be asserted high if we want toread from
the RAM or asserted low if we want to write a word fo
the RAM. Here’show all these lines work for reading from
and writing to the device
To write to the RAM, we apply the desired address 10
the address inputs, assert the CE input low to turn on
the device, and assertthe R/W input low to tell the RAM
‘we want (o write to it. We then apply the dats word we
want to store to the data lines of the RAM for a specified
time. To read a word from the RAM, we address the
desired word, assert GE low to tum on the device, and
assert R/W high to tell the RAM we want to read from
it. For aread operation the output buffers on the data fines
willbe enabled and the addressed data word willbe present
oon the cutputs.
‘The static RAMs we have just reviewed store binary
words in a matrix of flip-flops. In dynamic RAMs
(DRAMS), binary I's and 0's are stored as an electric
charge or no charge on a tiny capacitor. Since these tiny
capacitors take up less space on a chip than a flip-flop
ADDRESS
INPUTS
Fig. 1.21 RAM schematie symbol.1.18
would, a dynamic RAM chip can store many more bits
than the same size static RAM chip. The disadvantage of
dynamic RAMS is that the charge leaks off the tiny
capacitors. The logic state stored in each capacitor must
be refreshed evesy 2 milliseconds (ms) ot so. A device
called a dynamic RAM refresh controller can be used to
refresh a large number of dynamic RAMS in a system,
Some newer dynamic RAM devices contain built-in
refresh circuitry, so they appear static to external circuitry.
Arithmetic Logic Units
An arithmetic logic unit, ot ALU, is a device that can
AND, OR, add, subtract, and perform a variety of other
operations on binary words. Fig. 1.22a shows a block
diagram for the 7418181, which is a 4-bit ALU. This
device can perform any one of 16 logic functions er any
ne of 16 arithmetic functions on two 4-bitbinary words.
The function performed on the two words is determined
by the logic level applied to the mode input M and by the
bit binary code applied to the select inputs $0 to $3.
Figure 1.22b shows the truth table for the 74LS181.
In this truth table, A represents the 4-bit binary word
applied to the AOto A3 inputs, and B represents the 4-bit
Microprocessor and Interfacing: Progranuning and Hardware
binary word applied to the BO to B3 inputs. F represents
the 4-bit binary word that will be produced on the FO to
F3 outputs. If the mode input M is high, the device will
perform one of 16 logic functions on the two words
applied to the A and B inputs. For example, if M is high
and we make $3 high, S? low, SI high, and SO high, the
4-bit word on the A inputs will be ANDed with the 4-bit
word on the B inputs, The result of this ANDing will
appear on the F outputs. Each bit of the A word is ANDed
with the corresponding bit of the B word to produce the
result on F. Fig. 1.22c showsan example of ANDing two
‘words with this device. As you can see in this example,
aan output bit is high only if the corresponding bit is high
in both the A word and the B word.
For another example of the operation of the 74LS181,
suppose that the M input is high, S3 is high, S2 is high,
Slis high, end $0 istow. According to the truth table, the
device will now OR each bit in the A word with the
corresponding bit in the B word and give the result on the
corresponding F output. Fig. 1.22c shows the result that
will be produced by ORing two 4-bit words. Fig. 1.22c
also shows for your reference the result that would be
produced by exclusive ORing these two 4-bit words
together.
7418181 TETVE-AIGADATA
‘SELECTION
alg MEL;ARITHMETICOPERATIONS
jay so sz st so GEHINOGARRY) [Gy =LQWTHOARRYD
ey
ie ib be & Fea Pus
Loud =(A+@)pLUs 1
bo aera | Estate yptusi
Bt tou HH F=MINUS 1(2's COMPL)
Ex LHe FEAPLUSAB [Link] PLUS
BS CoH LOH ES(AsB)PLUSAB | F=(A+B) PLUSABPLUS 1
ee Chae MNUSE MINUS MNSe
he tL oH HOH ‘AB MINUS 1 FeAB
esveat fied Hee F=APUUSAB =APLUSABPLUS 1
Huu d -APLUS* PLUSBPLUS 1
Tl) lace eae [Ep mmuns
HLH A AB INOS FAB
6 hate ‘APLUS PLUS APLUS 1
HHL H F=(A+B)PLUSA F=(A+B)PLUSAPLUS1
HoH HL (A+B )PLUSA —«E=(A+ B)LUSAPLUS
HAA OA Aig Fra ®
“EAGHBITISSHIFTEDTO THENEXT MORE SIGNIFICANT BIT POSTION
A= AS AZ AI AO A=1010 A
B= 83 B2 61 BO B=o110 B=o110 8
Fam RF PO sesiit6 F=axe-0070 F=Aee
©
Fig. 1.22 Arithmetic logic unit (ALU). (a) Schematic
XOR operations.
‘symbol, (b) Truth table, (c) Sample AND, OR, andComputer Number Systems, Codes, and Digital Devices
If the M input of the 74LS181 is low, then the device
will perform one of 16 arithmetic functions on the A and
B words. Again, the result of the operation will be put on
the F outputs. Several 74LS 181s can be cascaded to
operate on words longer than 4 bits. The ripple-carry input,
Cy allows a carry from an operation on previous words
to be included in the current operation. If the Cyy input is
asserted low, then a carry will be added to the results of
the operation on A and B. For example, if the M input is
ow, $3 is high, S2 is low, $1 is low, SO ishigh, and Cy is
Jow, the F outputs will have the sum of A plus B plus a
carry.
The real importance of an ALU such as the 74LS181
is that it can be programmed with a binary instruction
applied to its mode and select inputs to perform many
different functions on two binary words applied to its data
inputs. In other words, instead of having to build
different circuit to perform each of these functions, we
have one programmable device. We can perform any of
the operations that we want in a computer witha sequence
of simple operations such as those of the 74LS181
Therefore, an ALU is a very important part of the
microprocessors and microcomputers that we discuss in
the next chapter.
1.19
CHECKLIST OF IMPORTANT TERMS AND
CONCEPTS IN THIS CHAPTER
{you do notremamberanyof the terms or conceps in his lit, use the
indo find chen the captor
Binary bit, nibble by, word, doubleword
ISB, MSB, LSD, MSD
Hexadecimal, sendard BCD, Gray cede
regent diplaycode
Alphanumeric codes: ASCU,EBCDIC
Parity bit, odd perity even parity
Canuerting beeen binary. decinal, hexadecimal, BCD
Arichmeve wich binary hexadecimal, BCD
BCD decimal adst operation
Signed numbers ign bit
2icomplementsign-ard-magnitudeform
Signataserion level
Inverting and noninverting bufers
‘Symbols and trash cables for AND, NAND, OB, NOR, XORogic
‘PLA, PROM, PAL
Ditch, D fip-fep
Register shiftrgiter, binary counter
ROM addres ine, daa lines, bu ines hreesate outputs andenable
input
PROM EPROM, EEPROM, lah EPROM
RAM: static dynamic
ALU.
—___________ Review Questions AND PROBLEMS =
1, Write the decimal equivalent foreach integral power
of 2 from 2° to 2”
2. Convert the following decimal numbers to binary:
a2
6.16
©. 500
3. Convert the following binary numbers to decimal:
a. 10H
&. 11010001
¢. 110111001011001
4, Convert to hexadecimal:
a, 53 decimal
b. 756 decimal
¢. 01101100010 binary
4. 11000010111 binary
5. Convert to decimal:
a, D3H
6. 3FEH
4H
6. Convert the following decimal numbers to BCD:
a. 86
b. 62
3
7. The L key is depressed on an ASCII-encoded key-
board. What pattern of 1’sand 0's would you expect
to find on the seven parallel data lines coming from
the keyboard? What pattern would a carriage return,
CR. give?
8. Define parity and describe how it is used to detect
an error in transmitted data.
9. Show addition of:
4. 10011, and 10113 in binary
b. 37 and 25,yin BCD
cc. 4AHand 7H
10. Express the following decimal nurnbersin 8-bit sign-
and-magnitude form:
a. #26
b-7
c. 26
d, 125
1, Show the subtraction, in binary, of the following.
decimal numbers using both the pencil method and
the 2’s-complement addition method:
a 7-4
b. 37-26
c. 125-931.20
12,
13.
14.
16.
1.
Show the multiplicationof 1001 and 01 by thepencil
method. Do the same for 11010 and 101
Show the division of 1100100 by 1010 using the
pencil method.
Perform the indicated operations on the following
numbers:
a, 3AH+94H
b, YTAH-4CH
01011001 BCD
+ 91000010 BCD
4. 01111001 BCD
+ 0100.1001 BCD
e. 0101 1001 BCD
~ 90100110 BCD
Jf. - 91100111 BCD
— 0011 1001 BCD
For the circuit in Fig. 1.23:
a. Isthe Y output active high or active low?
. Isthe C signal active high or active low?
<¢. What input conditions oa A.B, and C will eause
the Y output tobe asserted?
Describe how a D latch responds to a postive pulse
‘on its CK input and how a D flip-flop responds to a
positive pulse on its CK input.
‘The Nawonal Semiconductor INS8298 is a 65,536-
bit ROM organized as 8192 words orbytes of 8 bits.
How many address lines are required to address one
of the 8192 bytes? .
Why do most ROMs and RAMs have three-state
output.
Mlcroprocessor and Interfacing: Programming and Hardware
Fig.
9.
oe
1.23 Circuit for problem 15
Using Fig. 1.22h, show the programming of the
select and mode inputs the 74181 requires to
perform the following arithmetic functions
AGB
A-B-1
ABLA
Show the output word produced when the following
binary words are ANDed with each other and when
they are ORed with each other:
a. 1010and 0111
>. 1011 and 1100
¢. 1010111 and 111000
4. ANDing an 8-bit binary number with 1111 0000
is sometimes referred to as “masking” the lower
4 bits. Why?Computers,
Microcomputers, and
Microprocessors—An
Introduction
live in a compater-oriented society, and we
‘are constantly bombarded with a multitude of
terms relating to computers, Before getting
started with the main flow of the book, we will try to
clarify some of these terms and to give an overview of
computers and computer systems.
‘OBJECTIVES
Aithe conclesion ofthis chapter, you should be able to:
1. Define the terms microcomputer. microprocesar, hardieare
nftware, firmare timeharing, multitasking, disributed
procesing,and multiprocesing.
Describe how a microcemputer fetches and executes an
instruction.
3. List the registers and other part inthe BO8G/ 8088 execution
nit and busincerfave unit
4. Describe the function ofthe 808618088, queve.
5. Demonstrate how the 808618088 cakulates memory address
TYPES OF COMPUTERS
Mainframes
Computers come ina wide variety of sizes and capabilities.
‘The largest and the most powerful ones are ofien called
‘mainframes. Mainframe computers may fill an entire room,
They are designed to work at very high speeds with large
data words. typically 64 bits or greater. and they have
massive amounts of memory. Computers of this type are
used for military defence control, for business data
processing (in an insurance company, for example), and
for creating computer graphics displays for science fiction
movies. Examples of this type of computer are the [BM
438.1, the Honeywell DPS8, and the Cray Y-MP/832, The
fastest and the most powerful mainframes are called
supercomputers. Fig. 2.1a, shows a photograph of a Cray
‘Y-MP/832 supercomputer, which comtains eight central
processors and 32 million 64-bit words of memory.
Minicomputers
Scaled-down versions of mainframe computers are often
called minicomputers. The main unit of a minicomputer
usually fits ina single rack or box. A minicomputer runs
more slowly, works directly with smaller data words2.2 Microprocessor and Interfacing: Programming and Hardware
(ofien 32-bit words), and does not have as much memory
as a mainframe. Computers of this type are used for
business data processing, industrial control (for an oil
refinery, for example), and scientific research. Examples
of this type of computer are the Digital Equipment
‘Corporation VAX 6360 and the Data General MV/S0001I.
Fig. 2.1 shows a photograph of a Digital Equipment
Corporation's VAX 6360 minicomputer.
Microcomputers
Asthe nameimplies, microcomputers are small computers,
‘They range from small controllers that work directly with
4-bit words and can address a few thousand bytes of
memory to larger units that work directly with 32-bit
‘words and can address billions of bytes of memory. Some
of the more powerful microcomputers have all or most
of the features of earlier minicomputers. Therefore it has
become very hard to draw a sharp line between these two
types. One distinguishing feature of a microcomputer is
that the CPU is usually a single integrated circuit called a
microprocessor. Older books often used the terms
microprocessor and microcomputer interchangeably, but
actually the microprocessor is the CPU to which you add
ROM, RAM, and ports to make a microcomputer. A later
section in this chapter discusses the evolution of different
types of microprocessors. Microcomputers are used in
everything from smart sewing machines to computer-
aided design systems. Examples of microcomputers are
theIntel 8051 single-chipcontroller, the SDK-86, asingle-
‘board computer design kit; the [BM Personal Computer
(PC); and the Apple Macintosh compater. The Intel 8051
microcontroller is contained in a single 40-pin chip.
Fig. 2.2a, shows the SDK-86 board, and Fig. 2.2b shows
the Compag 386/25 system.
HOW COMPUTERS AND
MICROCOMPUTERS ARE
USED—AN EXAMPLE
‘The following sections are intended to give you an
overview of how computers are interfaced with users to
do useful work, These sections should help you
understand many of the features designed into current
‘microprocessors and where this book is heading.
Computerizing an Electronics
Factory—Problem
‘Now, suppose that we wnt to “computerize” an electron-
ies company. By this we mean that we want to make
computer-use available to as many people in the company
Fig. 2.1 (a) Photograph of Cray Y-MP/832
‘computer. (Courtesy Cray Research, Inc.,
‘and photographer, Paul Shambroom.)
(b) Photograph of VAX 6360
minicomputer. (Courtesy Digital
Equipment Corp.)
as cheaply as possible, We want the engineers to have
accesso acomputer which can help them design circuits.
People in the drafting department should have access to a
computer which can be used for computer-aided drafting.
The accounting department should have access to a
computer for doing all the financial book-keeping. The
‘warehouse should have access to a computer to help with
inventory control. The manufacturing department should
have access to a computer for controlling machines and
testing finished products. The president, vice-presidents,
and supervisors should have access to a computer to helpComputers, Microcomputers, and Microporcessors—An Introduction
agai
Fig. 2.2 (a) Photograph oj Intel SDK-86 board.
Gntel Corp.) (b) Photograph of Compaq
386/25. (Compag Corp.)
them with long-range planning. Secretaries should have
access to a computer for word processing. Salespeople
should have access 10 a computer to help them keep track
ofcurrent pricing, product availability, and commissions.
There are several ways to provide all the needed computer
power. One solution is to simply give everyone an
individual personal computer. The problem with this
approach is that it makes it difficult for different people
to access commonly needed data. In the next sections,
we show you two ways to provide computer power and
‘common data to many users.
TIMESHARING AND MULTITASKING SYSTEMS
One common method of providing computer access is a
timesharing system such as shown in Fig. 2.3. Several
video terminals are connected to the compater through
direct wires or through telephone lines. The terminal can
be on the user’s desk or even in the user’s home. The
rate at which a user usually enters data is very slow
compared with the rate at which a computer can process
the data. Therefore, the computer can serve many users
by dividing its time among them in small increments. In
other words, the computer works on user I's program for
perhaps 20 milliseconds (ms), then works on user 2°s
program for 20 ms, then works on user 3’s program for
20 ms, and soon, until all the users have had a turn. In a
‘few milliseconds the computer will get back to user | again
and repeat the eycle. To each user it will appear as if he
or she has exclusive use of the computer because the
‘computer processes data as fast as the user enters it. A
timesharing system such as this allows several users to
interact with the computer at the same time. Each user
‘can get information from or store information in the large
memory attached to the computer. Each user can have
‘an inexpensive printer attached tothe terminal or can direct
program or data output to a high-speed printer attached
directly to the computer.BASS + computer
pata | (MAINERAME |
{ STORAGE orn |
VIDEO
TERMINAL
PRINTER VIDEO
TERMINAL
ds
tteroprocessor and Interfacing: Programming andl Hardware
./ High-sPEED /
PRINTER /
vIDEO
TERMINAL
Low cost
PRINTER
VIDEO
TERMINAL
Fig. 2.3. Block diagramofacomputer timesharing system.
An airline ticket reservation computer might use a
timesharing system such as this to allow users from all
over the country to access flight information and make
reservations. A time-multiplexed or time-sliced system
such as this can also allow a computer to control many
machines or processes in a factory. A computer is much
faster than the machines or processes. Therefore. it can
check and adjust many pressures, temperatures, motor
speeds. etc. before ii needs to get back and recheck the
first one. A system such as this is often called a
‘multitasking system because it appears to be doing many
tasks at the same time.
Now let's take another look at our problem of
computerizing the electronics company. We could put a
powerful computer in some central location and run wires
from it 10 video display terminals on users’ desks. Each
user could then sun the program needed todo a particular
task. The accountant could run a ledger program, the
secretary could tun a word processing program, etc. Each
user could access the computer's large data memory.
Incidentally, a large collection of data stored ina
computer's memory 1s atten referred to as a database.
For a smail company. a system such as this might be
adequate. However, there are at least nwo potential
problems,
‘The first potential problem is, “What happens if the
computer is not working?” The answer to this question
is that everything grinds to a halt. In a situation where
people have become dependent onthe computer, not much
gets done until the computer is upand running again, The
‘ld saying about puttingall your eggsin one basketcomes
to mind here
‘The second potential problem of the simple timeshar-
ing system ation. AS the number of users in-
‘creases, the time it takes the computer to do each user's
task increases also. Eventually, the computer's response
time to each user becomes unreasonably Tong. People get
very upset about the time they have to w:
DISTRIBUTED PROCESSING OR
MULTIPROCESSING.
A partial solution for the two potential problems of a simple
timesharing system is to use a disiributed processing
system, Fig, 2.4 shows a block diagram for such a
system, The system has a powerful central computer with
large memory and a high-speed printer a does the simple
timesharing system described previously. However. in this
system each user has a microcomputer instead of simply
a Video display terminal, In other words, each user station
is an independently functioning microcomputer with a
CPU, ROM, RAM, and probably magnetic or optical disk
‘memory. This means that a petson can do many tasks
locally on the microcomputer without having to use the
large computer at all. Since the microcomputers are
connected to the large computer through a network, a
user can access the computing power, memory, or other
resources of the large computer when needed.
Distributing the processing to multiple computers or
processors in a system has several advantages. First if
the large computer goes down. the local microcomputersComputers, Microcomputers, and Microporcessors—an Introduction 2.5
f 1
mass / MAINFRAME
SOMPUTER | 7
DATA
(STORAGE
CONNECTION To
PHONE LINE
RY
\Y
MICROCOMPUTER
MINICOMPUTER,
/wicH-sPeeD/
PRINTER /
MICROCOMPUTER
FLOPPY DISK
DRIVE
HARD.
DISK DRIVE |
AK \ |
MN \
=
MICROCOMPUTER
PRINTER
VIDEO TERMINAL VIDEO TERMINAL VIDEO TERMINAL
Wig. 2.4 Block diagram ofa distributed processing computer system.
can continue working until they need to access the large
‘compater for something. Second, the burden on the large
computer is reduced greatly, because much of the
‘computing is done by the local microcomputers. Finally,
the distributed processing approach allows the system
designer to use a local microcomputer that is best suited
to the task it has to do.
COMPUTERIZED ELECTRONICS COMPANY
OVERVIEW
Distributed processing seems to be the best way to go
aboutcomputerizing our electronics factory. Engincerscan
have personal computers or engineering works-stations
‘ontheir desks. With these they can use available programs
to design and test circuits. They can access the large
‘computer if they need data from its memory. Through the
telephone lines, the engineer with a personal computer can
access data in the memory of other computers all over
the world. The drafting people can have personal
computers for simple work, or large computer-aided
design systems formore complex work. Completed work
ccan be stored in the memory of the large computer. The
production department can have networked computers to
keep track of product flow and to contol the machines
which actually mount components on cireuit boards, etc
‘The accounting department can use personal computers
with spreadsheet programs to work with financial data
kept in the memory of the large computer. The warehouse
supervisor can likewise, use a personal computer with an
inventory program to keep personal records and the
records the large computer's memory updated. Corporate
officers can have personal computers tied into the
network. They then can interact with any of the other
systems on the network, Salespeople can have portable
personal computers that they can carry with them in the
field. They can communicate with the main computerover
the telephone lines using a modem. Secretaries doing word
processing can use individual word processing units or
personal computers. Users can also send messages to one
another over the network, The specifics of a computer
system such as this will obviously depend on the needs
of the individual company for which the system is
designed.
SUMMARY AND DIRECTION FROM HERE
The main concepts that you should take with you from
this section are timesharing or multitasking and distributed
processing or multiprocessing. As yon work your way
through the rest of this book, keep an overview of the‘computerized electronics company in the back of your
mind. The gool of this book is to teach you how the
microcomputers and other parts of a system such as this
work, how the parts are connected together, and how the
system is programmed at different levels.
OVERVIEW OF MICROCOMPUTER
STRUCTURE AND OPERATION
Figure 2.5 shows a block diagram for a simple
microcomuter. The major parts are the central processing
unit or CPU, memory, and the input and output circuitry
or 1/0, Connecting these parts are three sets of parallel
lines called buses. The three buses are the address bus,
the daia bus, and the control bus. Let’s take a brief took
at each of these parts
Memory
‘The memory section usually consists of a mixture of RAM
and ROM, It may also have magnetic floppy disks,
‘magnetic hard disks, or optical disks. Memory has two
purposes. The first purpose is to store the binary codes
for the sequences of instructions you want the computer
to carry out. When you write a computer program, what
yon are really doing is writing a sequential list of
instructions for the computer. The second purpose of the
‘memory isto store the binary-coded data with which the
computer is going to be working. This data might be, for
example, the inventory records of a supermarket.
Input/Output
The input/output or VO section allows the computer to
take in data from the outside world or send data to the
outside world. Peripherals such as keyboards, video
display terminals, printers, and modems are connected to
the /O section, These allow the user and the computer
Microprocessar and Interfacing: Programming and Hardware
to communicate with each other. The actual physical
devices used to interface the computer buses to external,
systems are often called ports. Ports in a computer,
function just as shipping ports do for a country. An input
port allows data from a keyboard, an A/D converter, or
some other source to be read into the computer under
control of the CPU. An ouput port is used to send data
from the computer to some peripheral, such as a video
display terminal, aprinter, or a D/A converter. Physically,
the simplest type of input or output port is just a set of
parallel D flip-flops. they are being used as an input port,
the D inputs are connected to the external device, and the
Q outputs are connected to the data bus which runs to
the CPU, Data will then be transferred through the latches
when they are enabled by a control signal from the CPU.
In a system where they are being used 2s an output port,
the D inputs of the latches are connected to the data bus,
and the Q outputs are connected to some external device.
Data sent out on the data bus by the CPU will be transferred
to the external device when the latches are enabled by a
control signal from the CPU.
Central Processing Unit
‘The central processing unit or CPU controls the operation
of the computer. Ina microcomputer the CPU is a
‘microprocessor, as we discussed in an earlier section of
the chapter. The CPU fetches binary-coded instructions
from memory, decodes the instructions into a series of
simple actions, and carries out these actions ina sequence
of steps.
The CPU also contains an address counter or
instruction pointer register, which holds the address of
the next instruction or data item to be fetched from
memory; general-purpose registers, which are used for
temporary storage of binary data; and circuitry, which
generates the control bus signals.
—
Fig.2.5. Block dtagram ofa simple microcomputer.
paragus
[side }—§_
DEVICE CONTROL [ CENTRAL | CONTROL
vo BUS | processmie | “ous | MEMORY
Ports NT A A
fourrur]|___—4 (cru)
| DEVICE
‘ADDRESS BUSComputers, Microcomputers, and Mlcroparcessors—An Introduction 2.7
Address Bus
‘Theaddress bus consists of 16, 20.24, or 32 parallel signal
lines. On these lines the CPU sends out the address of the
‘memory location that is to be written to orread from. The
number of memory locations that the CPU can address is
determined by the number of address lines. If the CPU
has Naddress lines, then itcandirectly address 2" memory
locations. For example, a CPU with 16 address lines can
address 2'® or 65,536 memory locations, a CPU with 20
address lines can address 2” or 1,048,576 locations, and.
aCPU with 24 address lines can address 2* or 16,777,216
locations. When the CPU reads data from or writes data
to pon, it sends the port address out on the address bus.
Data Bus
‘The data bus consists of 8, 16, or 32 parallel signal lines.
As indicated by the double-ended arrows on the data bus
line in Fig. 2.5, the data bus lines are bidirectional. This
means that the CPU can read data in from memory or
from a port on these lines, or it can send data out to
memory or to a port on these lines. Many devices in a
system will have their outputs connected to the data bus.
butonly onedevice ata time will have its outputs enabled.
Any device connected on the data bus must have three-
“Sate outputs so that its outputs can be disabled when itis
not being used to put data on the bus,
Control Bus
The control bus cor
The CPU sends out signals on the control bus to enable
the outputs of addressed memory devices or port devices.
‘Typical control bus signals are Memory Read, Memory
Write, WO Read, and 1/0 Write. To read a byte of data
from a memory location, for example, the CPU sends out
the memory address of the desired byte on the address
bus and then sends out a Memory Read signal on the
control bus. The Memory Read signal enables the
addressed memory device to output a data word onto the
data bus. The data word from memory travels along the
data bus to the CPU.
Hardware, Software, and Firmware
‘When working around computers, you hear the terms
hardware, software, and firmware almost constantly.
Hardware is the name given to the physical devices and
circuitry of the computer. Sofiware refers to the programs
written for the computer, Firmware is the term given to
programs stored in ROMS or in other devices which
permanently keep their stored information.
Summary of Important Points So Far
‘+ [Link] or microcomputer consists of memory.
a CPU, and some input/output circuitry.
‘© These three parts are connected by the address bus,
the data bus, and the control bus.
‘ The sequence of instructions or program for a
computer is stored as binary numbers in successive
memory locations
«The CPU fetches an instruction from memory.
decodes the instruction to determine what actions,
must be done for the instruction, and carries out
these actions
EXECUTION OF A
THREE-INSTRUCTION PROGRAM
To give you a better idea of how the parts of a microcom-
puter function together, we will now describe the actions
a simple microcomputer might go through to carry out
(execute) a simple program. The three instructions of the
rogram are
1. Inputa value froma keyboard connected to the port
at address 05H.
2. Add 7 to the value.
3. Output the result to a display connected to the port
at address 02H.
Figure 2.6 shows in diagram form and sequential list
form the actions that the computer will perform to execute
these three instruetions.
Forthis example, assume that the CPU fetches instruc-
tions and data from memory 1 byte at a time, as is done
in the original IBM PC and its clones. Also assume that
the binary codes for the instructions are in sequential
memory locations starting at address OOIOOH. Fig. 2.65
shows the actual binary codes that would be required in
successive memory locations to execute this program on
an IBM PC-type microcomputer.
‘The CPU needs an instruction before itcan do anything,
so its first action is to fetch an instruction byte from
memory. To do this, the CPU sends out the address of
the first instruction byte, in this case 00100H, to memory
on the address bus, This action is represented by line 1A
in Fig. 2.62, The CPU then sends out ¢ Memory Read
signal on the control bus (line 1B in the figure). The
Memory Read signal enables the memory to output the
addressed byte on the data bas, This action is represented
by line 1C in the figure. The CPU reads in this first
instruction byte (E4H) from the data bus and decodes it.
By decode we mean that the CPU determines from the2.8 ‘Microprocessor and interfacing: Programming and Hardware
PROGRAM
1. INPUT AVALUE FROM PORT 05
2. A007 70 THI VALUE.
3. OUTPUTTHERESULT TOPORT 02
i ‘SEQUENCE
‘W CRU SENDS OUT ADDRESS OF FIRST INSTRUCTION TO MEMORY.
18 CAU SENOS OUT NEMORY READ CONTROL SIGNAL TOENABLE MEMORY.
{C INSTRUCTION BYTE SENT FROM NEMCRY TO GPU ON OATABUS.
{2 ADDRESS NEXT MEMORY LOCATION TO GETREST OF INSTRUCTION.
B SEND MEMORY READ CONTROL SIGNAL TO ENABLE MEMORY.
2& PORT ADDRESS BYTE SENT FRON MENORY TO CPU ON DATA BUS.
{2D CPU SENOS OUT PORT ADDRESS ON ADDRESS BUS,
CPU SENDS OUT NPUTREAD CONTROL SIGNAL TO ENABLE PORT.
DATAF ROM PORTSENT TO CPU ON OATA BUS.
{A CAU SENDS ADDRESS OF NEXT INSTRUCTION TO MEMORY.
Maamnin beet citer
SONTROLBUS. }—
coi 3 Sr seuss evo reabeaninor owt TOBUAS tenors
SG LL Siemtorevesmmuaion serocy axaunacs
potty i Suse tsraonee vowshens roatinda OP eStascron,
“4 CPU SENDS MEMORY READ CONTROL SIGNAL TO ENABLE MEMORY,
Hw 4G NUMBER O7H SENT FROM MEMORY TO CPU ON DATA BUS.
58 CPU SENDS ADDRESS OF NEXT INSTRUCTION TOMENORY.
53 CAL SENDS MEMORY READ CONTROL SIGNAL TO ENABLE MEMORY.
EC INSTRUCTION BYTE FROM MEMORY SENT TO CPU ON DATABUS,
aoe ae. {®\ CBU SENDS OUT NEXT ADDRESS TO GET REST OF INSTRUCTION,
{ CRU SENDS OUT NEMORY READ CONTROL SIGNAL TOENABLE WEMORY.
TO TOO {© PORT ADDRESS BYTE SENT FRON MENORY TO CPU ON DATA BUS,
OEE {6D CRU SENDS OUT PORT ADDRESS ON ADDRESS BUS,
a[5| 67 ag {CRU SENDS OUT CATA 10 PORT ONDATA BUS,
alsteir {F CPU SENDS OUT OUTPUT WRITE SIGNAL TOENABLE PORT.
KEYBOARD DISPLAY ®
MEMORY CONTENTS CONTENTS OPERATION
ADDRESS (BINARY) (HEX,
ox00H | ‘widow = _INPUT FROM.
coon expe @ —— PoRTosn
ovat co00%00 o& = A00
ooo ‘10010 &% — ouPuTtO
coos coo PTR
o
Fig.2.6 (a) Execution of three-step computer program. (b) Memory addresses and memory contents for
three-step program.
binary code read in, what actions it is supposed to take. _Readsignal on the control bus (line 2B). The memory then
Ifthe CPU is a microprocessor, it selects the sequence of
microinstructions needed to carry out the instruction read
from memory. For the example instruction here, the CPU
determines that the code read in represents an Input
instruction, From decoding this instruction byte, the CPU
also determines that it needs more information before it
‘can carry out the instruction, The additional information
the CPU needsis the address of the port that the data is to
be input from. This port address part of the instruction is
stored in the next memory location after the code for the
Input instruction.
To fetch this second byte of the instruction, the CPU
sends out the next sequential address (00101H) to memory,
asshown by line 2A in the figure. Toenable the addressed
memory device, the CPU also sends out enother Memory
outputs the addressed byte on the data bus (line 2C). When
the CPU has read in this second byte, OSH in this ease, it
has all the information it needs to execute the instruction,
‘To execute the Input instruction, the CPU sends out
the port address (OSH) on the address bus (line 2D) and
sends outan 1/0 Read signal on the control bus (line 2B).
‘The VO Read signal enables the addressed port device to
puta byte of data on the data bus (line 2F). The CPU reads
in the byte of data and stores it in an internal register. This
completes the fetching and execution of the first
instruction.
Having completed the first instruction, the CPU must
now fetch its next instruction from memory. To do this,
it sends out the next sequential address (00102H) on the
address bus (line 3A) and sends out a Memory Read signalComputers, Mecrocomputers, and Microporcessors—An Introduction 2.9
on the control bus (line 3B). The Memory Read signal
enables the memory device to putthe addressed byte (O4H)
onthe data bus (line 3C). The CPU reads inthis instruction
byte from the data bus and decodes it. From this instruction
byte the CPU determines that its supposed to add some
number to the number stored in the internal register. The
CPU also determines from decoding this instruction byte
that it must go to memory again to get the next byte of
the instruction, which contains the number that it is
supposed to add. To get the required byte, the CPU will
send out the next sequential address (00103H) on the
address bus (line 4) and another Memory Read signal
onthe control bus (line 4B). The memory will then output
the contents of the addressed byte (the number 07H) on
the data bus (line 4C). When the CPU receives this number,
it will add it to the contents of the internal register. The
result of the addition will be left in the internal register.
This completes the fetching and executing of the second
instruction.
‘The CPU must now fetch the third instruction, To do
this, itsends out the next sequential address (00104H) on
the address bus (line 5A) and sends out a Memory Read
signal on the control bus (line SB). The memory then
outputs the addressed byte (EGH) on the data bus (line
‘5C). From decoding this byte, the CPU determines that it
is now supposed todo an Output operation to a port. The
CPU also determines from decoding this byte thatit must
{go to memory again to get the address of the output port.
To do this, it sends out the next sequential address
(0010SH) on the address bus (line 6A), sends out a
Memory Read signal onthe control bus (line 6B), and reads
the byte (02H) put on the data bus by the memory (line
‘6C). The CPU now has all the information that it needs to
execute the Output instruction.
To outpat a data byte to a por, the CPU first sends out
the address of the desired port on the address bus (line
6D). Next it ouputs the data byte from the internal register
on the data bus (line GE). The CPU then sends out an VO
Write signal on the control bus (line 6F). This signal
enables the addressed cutput port device so that the data
from the data bus lines can pass through it to the LED
displays. When the CPU removes the /0 Write signal to
proceed with the next instuetion, the data will remain
latched on the output pins of the port device. The data
will remain latched on the port until the power is turned
off or until a new data word is output to the port. This is
important because it means that the computer does not
have to keep outputting a value over and overin order for
itto remain on the output.
Allthesteps described abovemay seem like a great deal
of work just to input a value from a keyboard, add 7 to,
and output the result to a display. Even a simple
‘microcomputer, however, can run through all these steps
in a few microseconds.
Summary of Simple Microcomputer
Bus Operation
1. A microcomputer fetches each program instruction
sequence, decodes the instruction, and executes
it
2. The CPU ina microcomputer fetches instructions
reads data rom memory by sending out an address
on the address bus and a Memory Read signal on
the control bus. The memory outputs the addressed
instruction or data word to the CPU onthe data bus.
3. The CPU writes a data word to memory by sending
out an address on the address bus, sending out the
data word on the data bus, and sending a Memory
Write signal to memory on the control bus.
To read data from a port, the CPU sends out the port,
address on the address bus and sends an VO Read
signal to the port device on the control bus. Data
from the port comes into the CPU on the data bus.
5. To write data to a port, the CPU sends out the port
address on the address bus, sends out the data to
be written to the port on the data bus, and send an
/O Write signal to the port device on the control
bus.
MICROPROCESSOR EVOLUTION:
AND TYPES
[Link] told you in the preceding section, microprocessor
is used as the CPU in a microcomputer. There are now
many different microprocessors available, so before we
dig into the details of « specific device, we will give you
a short microprocessor history lesson [Link] overview
of the different types.
Microprocessor Evolution
‘Acommon way of categorizing microprocessorsis by the
‘number of bits that their ALU can work with at a time. In
‘other words, a microprocessor with a d-bit ALU will he
referred to as a 4-bit microprocessor, regardless of the
number of address lines or the number of data bus
lines that it has. The first commercially available
microprocessor was the Intel 4004, produced in 1971. It
contained 2300 PMOS transistors. The 4004 was a 4-bit2.10
Microprocessor and Interjacing: Programming and Hardware
device intended to be used with some other devices in
making a calculator. Some logic designers, however, saw
that this device could be used to replace PC boards full of
combinational and sequential logic devices. Also, the ability
to change the function of a system by just changing the
programming, rather than redesigning the hardware, is
very appealing. It was these factors that pushed the
evolution of microprocessors.
In 1972 Intel came out with the 8008, which was
capable of working with 8-bit words. The 8008, however,
required 20 or more, additional devices to form a
functional CPU. in 1974, Intel announcedthe 8080, which
had a much larger instruction set than the 8008 and
required only two additional devices to form a functional
CPU. Also,the 8080 used NMOS transistors, soit operated
much faster than the 8008. The 8080 is referred to as a
second-generation microprocessor.
Soon after Intel produced the 8080, Motorola came out
‘with the MC6800, another 8-bit general-purpose CPU. The
‘6800 had the advantage that it required only a + 5- V
supply rather than the -5-V, +5 ~ V, and +12-V supplies
required by the 8080, For several years, the 8080 and the
6800 were the top-selling 8-bit microprocessors. Some
oftheir competitors were the MOS Technology 6502, used
asthe CPU in the Apple II microcomputer, and the Zilog
Z80, used as the CPU in the Radio Shack TRS-80
microcomputer
As designers found more and more applications for
microprocessors, they pressured microprocessor
manufacturers to develop devices with architectures and
features optimized for doing certain types of tasks. In
response to the expressed needs, microprocessors have
evolved in three major directions during the last 15 years.
Dedicated or Embedded Controllers
One direction in the dedicated or embedded controllers.
These devices are used to control “smart” machines, such
as microwave ovens, clothes washers, sewing machines,
auto ignition systems, and metal lathes. Texas Instruments
has produced millions of their TMS-1000 family of 4-bit
microprocessors for this type of application. In 1976 Intel
introduced the 8048, which contains an 8-bit CPU, RAM,
ROM, and some VO portsallinone 40-pin package, Other
‘manufacturers have followed with similar products. These
devices are often referred to as microcontrollers, Some
currently available devices inthiscatezory—the Intel 8051
and the Motorola MC6801. for example—contain
programmable counters and a serial port (UART) as well
as a CPU, ROM, RAM, and parallel /O ports. A more
recently introduced single-chip microcontroller, the Intel
8096, contains a 16-bit CPU, ROM, RAM, a UART, ports,
timers, and a 10-bit analog-to-digital converter.
Bit-Slice Processors
A second direction of microprocessor evolution has been
bit-slice processors, For some applications, general-
purpose CPUs such as the 8080 and 6800 are not fast
‘enough ordo not have suitable instruction sets. For these
applications, several manufacturers produce devices which
can be used to build a custom CPU. An example is the
Advanced Micro Devices 2900 family of devices. This
family includes 4-bit ALUs, multiplexers, sequencers,and
‘other parts needed for custom-building a CPU. The term
slice comes from the fact that these parts can be connected
in parallel o work with 8-bit words, 16-bit words, or 32-
bit words, In other words, a designer can add as many
slices as needed for a particular application, The designer
not only custom-designs the hardware of the CPU, but
also custom-makes the instruction set for it, using
“microcode.”
General-Purpose CPUs
‘The third major direction of microprocessor evolutionhas
been towards general-purpose CPUs which give a
microcomputer most or all of the computing power of
earlier minicomputers. After Motorola came out with the
MC6800, Intel produced the 8085, an upgrade of the 8080
that required only a +5-V supply. Motorola then produced
the MC6809, which has a few 16-bit instructions, but is
still basically an 8-bit processor. In 1978 Intel came out
with the 8086, which is a full 16-bit processor. Some 16-
bit microprocessors, such as the National PACE and the
‘Texas Instruments 9900 family of devices, had been
available previously, but the market apparently wasn’t
ready, Soon after Intel came out with the 8086, Motorola
‘came out with the 16-bit MC68000, and the 16-bit race
was off and running. The 8086 and the 68000 work
directly with 16-bit words instead of with 8-bit words.
they can address.a million or mote bytes of memory instead
of the 64 Kbytes addressable by the 8-bit processors, and
they execute instructions much faster than the &-bi
processors. Also, these 16-bit processors have single
instructions for functions such as mudtiply and divide,
which required a lengthy sequence of instructions on the
B-bit processors.
The evolution along this last path has continued on to
32-bit processors that work with gigabytes (10? bytes)
or terabytes (10" bytes) of memory. Examples of these
devices are the Intel 80386, the Motorola MC68020, and
the National 32032.
Since we could not possibly deseribe in this book the
‘operation and programming of evena few of the available
processors, we confine our discussions primarily to oneComputers. Microcomputers, andl Microporcessors—An Introduction
group of related microprocessors. The family we have
chosen is the Intel 8086, 8088, 80186, 80188, 80286,
80386, 80486 family. Members of this family are very
widely used in personal computers, business computer
systems, and industrial control systems. Our experience
has shown that learning the programming and operation
fone family of microcomputers very thoroughly is much
more useful than looking at many processors superficially
Ifyou learn one processor family well, you will most likely
find it quite easy to lear another when you have to.
THE 8086 MICROPROCESSOR
FAMILY—OVERVIEW
‘The Intel 8086iis « 16-bit microprocessor tha is intended
tobe used as the CPU in a microcomputer. The term 76-
‘bit means that its arithmetic logicunit, its internal registers,
‘and most of its instructions are designed to work with
16-bit binary words. The 8086 has a 16-bit data bus, so it
can read data from or write data to memory and ports
cither 16 bits or 8 bits at a time, The 8086 has a 20-bit
address bus, so it can address any one of 2”°, or
1,048,576, memory locations.
Each of the 1,048,576 memory aildresses of the 8086
represents a by‘e-wide location. Sixteen-bit words will be
stored in two consecutive memory locations. Ifthe first
byte of a word is at an even address, the 8086 can read
the entire word in one operation. Ifthe first byte of the
‘word is at an odd address, the 8086 will read the first byte
with one bus operation and the second byte with another
‘bus operation. Later we will discuss this indeteil. The main
point here is that if the first byte of a 16-bit word is at an
even address, the 8086 can read the entire word in one
operation.
‘The Intel 8088 has the same ALU, the same registers,
land the same instruction set as the 8086, The 8088 also
hhas a 20-bit address bus. so it can address any one of
1,048,576 bytes in memory. The 8088, however, has an
8-bit data bus, so itcan only read data from or write data
to memory and ports, 8 bits at a time. The 8086.
remember, can read or write either § or 16 bits at a time
To read a 16-bit Word from two successive memory
locations. the 8088 will always have to do two read
operations. Since the 8086 and the 8088 are almost
identical, any reference we make to the 8086 in the rest
of the book will also pertain to the 8088 unless we
specifically indicate otherwise. This is done to make
reading easier. The Intel 8088, incidentally, s used as the
CPU in theoriginal IBM Personal Computer, the IBM PC/
XT, and several compatible personal computers,
DAL
The Intel 80186 is an improved version of the 8086,
and the $0188 is an improved version of the 8088. In
addition to a 16-bit CPU, the 80186 and 80188 each have
programmable peripheral devices integrated in the same
package. In a laterchapter we will discuss these integrated
peripherals. The instruction set of the 80186 and 80188
is a superset of the instruction set of the 8086. The term
superset means that allthe 8086and 8088 instructions will
execute properly on an 80186 or an 80188, but the 80186
and the 80188 have a few additional instructions. In other
Words, a program written for an 8086 or an 8088 is
upward-compatible to an 80186 or an 80188, but 2
program written for an 80186 or an 80188 may not
execute correctly on an 8086 oran 8088. Inthe instruction
cet descriptions in Chapter 6, we specifically indicate
which instructions work only with the 80186 or 80188.
‘The Intel 80286 isa 16 bit, advanced version of the
8086 which was specifically designed for use asthe CPU
in a multiuser or multitasking microcomputer. When
‘operating in its real address mode, the 80286 functions
mostly ava fast 8086, Most programs written for an 8086
can be run on an 80286 operating inits real address mode.
‘When operating in its virtual address mode, an 80286 has
features which make it easy to keep users’ programs
separate from one another and to protect the system
program from destruction by users’ programs. In
‘Chapter 15, we discuss the operation and use of the
80286. The 80286 is the CPU used in the IBM PC/AT
personal computer.
With the 80386 processor, Intel started the 32-bit
processor architecture, known as the I-32 architecture.
This architecture extended all the address and general
purpose registers to 32-bits, which gave the processor
‘he capability to handle 32-bit address (4 GB of memory
addressing), with 32-bit data, and yet accommodating ail
the software designed for the earlier 16-bit processors,
80¥6,8088, 80186, 80188 and 80286. It contains more
sophisticated features for use in multiuserand mukitasking
environments,
Intel 80486 is the next member of the IA
architecture. This processor has the floating poi
processor (80387) integrated into the CPU chip itself.
These processors are then followed by different versions
of the Pentium Processors, with different additional
capabilities such as multimedia (MMX, SSE, SSE2 etc.
system power saving modes, hyper thread technology etc.
InChapter 15, we will discuss the 80286, 386..and 486
processors, and in Chapter 16, we shall take up some
rnajor versions of the Pentiun processors for discussion.2.12
Microprocessor and Interfacing: Programming and Hardware
8086 INTERNAL ARCHITECTURE
Before we can talk about how to write programs for the
8086, we need todiscuss its specific internal features, such
as its ALU, flags, registers, instruction byte queue, and
segment registers
‘As shown by the block diagram in Fig. 2.7, the 8086
CPU is divided into two independent functional parts, the
bus interface unit or BIU, and the execution unit or EU.
Dividing the work between these two units speeds up
processing,
‘The BIU sends outaddresses, fetches instructions from
memory, reads data from ports and memory. and writes
data to ports and memory. In other words, the BIU handles
all transfers of data and addresses on the buses for the
execution uri
The execution unit of the 8086 tells the BIU where to
fetch instructions or data from, decodes instructions, and
executes instructions, Let's take a lookat some ofthe parts
The Execution Unit
CONTROL CIRCUITRY, INSTRUCTION
DECODER, AND ALU
As shown in Fig. 2.7, the EU contains control circuitry
which directs internal operations. A decoder in the EU
translates instructions fetched from memory into a series
of actions which the EU carries out. The EU has & 16-bit
arithmetic iogic unit which can add, subtract, AND, OR,
XOR, increment, decrement, complement, or shiftbinary
numbers.
FLAG RECISTER
A flag isa flip-flop that indicates some condition produced
by the execution cf an instruction or controls certain
operations of the EU. A 16-bit flag register in the EU
contains nine active flags. Fig. 28 shows the location of
the nine flags in the flag register. Six ofthe nine flags are
used to indicate some condition produced by an
instruction, Forexample, a flip-flop ealled the carry flag
will be set to a 1 if the addition of two 16-bit
STREAM
agirumanc
toa unit
Fig. 2.7 8086 internal block diagram. (Intel Corp.)Computers, Microcomputers. and Micropercossors—An Introduction
2.13
er sw 2 on 10 pasaaa
—)
oF [or sF]ze| u [ar] u [Pr
Blo
v
|
‘CARRY FLAG - SET BY CARRY OUT OF MSE
PARITY FLAG — SET IF RESULT HAS EVEN PARITY
[AUXILIARY CARRY FLAG FOR BCD
ZERO FLAG™ SET IF RESULT =0
‘SGN FLAG = MSH OF RESULT
SINGLE STEP TRAP FLAG
INTERRUPT ENABLE RAG.
STRING DIRECTION FLAG.
OVERFLOWFLAG
Fig. 2.8 8086 flag register format. (Intel Corp.)
numbers produces a carry out of the most significant bit
position. If no carry out of the MSB is produced by the
addition, then the carry flag will be a 0. The EU, thus
effectively runs up 2 “flag” to tell you that a carry was
produced.
‘The six conditional flags inthisgroup are the carry flag
(CB), the parity flag (PF), the auziliary carry flag (AP),
the zero flag (ZF), the sign flag (SF), and the overflow
‘flag (OF). The names of these flags should give you hints,
‘as to what conditions affect them. Certuin 8086
instructions check these flags to determine which of two
alternative actions should be done in executing the
instruction.
‘The three remaining flags in the flag register are used
to control certain operations of the processor. These flags
are different from thesix conditional flags described above
in the way they are set or reset. The six conditional flags
are set or reset by the EU on the basis of the results of
some arithmetic or logic operation. The control flags are
deliberately set or reset with specific instructions you put
in your program. The three control flags are the trap flag
(TR), whichis used for single stepping through a program;
the interrupi flag (IF), which is used to allow ot prohibit
the interruption of a program; and the direction flag (DF),
which is used with string instructions.
Later we will discuss in detail the operation and use of
the nine flags.
GENERAL-PURPOSE REGISTERS,
Observe in Fig. 2.7 thatthe EU haseight general- purpose
registers, labeled AH. AL, BH, BL, CH, CL, DH, and DL.
These registers can be used individually for temporary
storage of 8-bit data. The AL register is also called the
accumulator. It has some features that the other general-
purpose registers do not have.
Certain pairs of these general-purpose registers can be
used together to store 16-bit data words. The acceptable
register pairs are AH and AL, BHandBL,CH and CL, and
DH and DL. The AH-AL pair is referred to as the AX
register, the BH-BL pair is referred to as the BX register,
the CH-CL pair is referred to as the CX register, and the
DH-DL pair is referred to as the DX register.
The 8086 general-purpose register set is very similar
to those of the earlier generation 8080 and 8085
‘microprocessors. It was designed this way so that the
‘many programs written for the 8080 and 8085 could easily
betranslated to run on the 8086 or the 8088. The advantage
of using internal registers for the temporary storage of
data is that, since the deta is already in the EU, itcan be
accessed much more quickly than it could be accessed in
external memory. Now let’s look at the features of the BIU.
The BIU
THE QUEUE
‘While the EU is decoding an instruction or executing an
instruction which does not require use of the buses, the
BIU fetches up to six instruction bytes for the following
instructions. The BIU stores these prefeiched bytes in a
first-in-first-out register set called a quewe. When the EU
is ready for its next instruction, it simply reads the
instruction byte(s) for the instruction from the queue in
the BIU. This is much faster than sending out an address
to the system memory and waiting for memory to send
back the next instruction byte or bytes. The process is
analogous to the way a bricklayer’s assistant fetches
bricks ahead of time and keeps a queue of bricks lined up
so that the bricklayer can just reach out and grab a brick
when necessary. Except in the cases of JMP and CALL2.14 Microprocessor and Interfacing: Programmning and Hardware
instructions, where the queue must be dumped and then
reloaded starting from a new address, this prefetch-and-
queue scheme greatly speeds up processing. Fetching the
next instruction while the current instruction executes is
called pipelining.
SEGMENT REGISTERS
‘The 8086 BIU sends out 20-bit addresses, so itcan address
any of 2*° or 1,048,576 bytes in memory. However, at
any given time the 8086 works with only foar 65,536-
byte (64-Kbyte) seaments within this 1,048,576-byte
(-Mbyte) range. Four segment registers in the BIU are
used tohold the upper 16 bits of the starting addresses of
four memory segments that the 8086 is working with at
4 particular time. The four segment registers are the code
segment (CS) register, the stack segment (SS) register, the
extra segment (ES) register, and the data segment (DS)
register.
Figure 2.9 shows how these four segments might be
positioned in memory at given time. The four segments
can be separated as shown, or, for small programs which
do not need all 64 Kbytes in each segment, they can
overlap.
To repeat, then, a segment register is used to hold the
upper 16 bits of the starting address for each of the
segments. The code segment register, for example, holds
the upper 16 bits of the starting address for the segment
from which the BIUis currently fetching instruction code
bytes. The BIU always inserts zeros for the lowest 4 bits
(nibble) of the 20-bit starting address for a segment. If
the code segment register contains 348AH, for example,
then the code segment will start at address 348A0H. In
other words, a 64-Kbyte segment can be located anywhere
within the I-Mbyte address space, but the segment will
always star at an address with zeros in the lowest 4 bits.
This constraint was put on the location of segments 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 called the segment base.
A stack is a section of memory set aside to store
adresses and data while a subprogramexecutes. The stack
segmer* register is used to hold the upper 16 bits of the
starting address for the program stack. We will discuss
the use and operation of a stack in detail later
The extra segment register and the data segment
register are used to hold the upper 16 bits of the starting
addresses of two memory segments that are used for data.
INSTRUCTION POINTER
‘The next feature to look at in the BIU is the instruction
pointer (IP) register. As discussed previously, the code
PHYSICAL
‘ADDRESS:
FEFFFH HIGHEST ADDRESS.
TOP OF EXTRA SEGMENT
EXTRASEGMENT BASE
ES 70008)
Serres TOP OF STACK SEGMENT
STACK SEGMENT BASE
SS= s000r
‘TOP OF CODE SEGMENT
‘348A0H (CODE SEGMENT BASE
FFF ‘TOP OF DATA SEGMENT
BOTTOM OF DATA SEGMENT
Wig. 2.9 One way four 64-Kbyte segments might
be positioned within the I- Mbyte address
space of an 8086.
segment register holds the upper 16 bits of the starting
address of the segment from which the BIU is currently
fetching instruction code bytes. The instruction pointer
register holds the 16-bitaddress,or offset, of the next code
byte within this code segment, The value contained in the
IP is referred to as an offset because this value must be
offset from (added to) the segment base address in CS to
produce the required 20-bit physical address sent out by
the BIU. Fig. 2.10a 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 address to the next instruction byte
to be fetched. Fig. 2.10b shows how the 16-bit offset in
IP is added to the 16-bit segment base address in CS to
produce the 20-bit physical address, Notice that the twoComputers, Microcomputers, and Mlcroporeessors—An Intreduction
2.15
ADDRESS = MEMORY
ABH —coveevie
peau
sean “+ START OF CODE SEGMENT
Cs =348aH
@
es [3] 4]@]A] o--naromnen 26R0
we [alatifa
prvsicacaconess [3[e]alels
Fig. 2.10 Addition of IP to CS to produce the
physical address of the code byte, (a)
Diagram, (b) Computation.
16-bit numbers are not added directly in line, because the
€S register contains only the upper 16 bits of the base
address for the code segment. As we said before, the BIU
automatically inserts zeros for the lowest 4 bits of the
segment base address.
Ifthe CS register, for example, contains 348AH, you
know that the starting address for the code segment is
348A0H. When the BIU adds the offset of 4214H in the
IP to this segment base address, the result is a 20-bit
physical eddress of 38AB4H.
‘An alternative way of representing 20-bit physical
address is the segment base:offsetform. For the address
‘ofa code byte, the format for this alternative form will be
CS:IP. As an example of this, the address constructed in
the preceding paragraph, 38AB4H, can also be represented
a5 348A:4214,
‘Tosummarize, then, the CS register contains the upper
16 bits of the starting address of the code segment in the
I-Mbyte address range of the 8086. The instruction pointer
register contains a 16-bit offset which tells, where in that
64-Kbyte code segment the next instruction byte is to be
fetched from. The actual physical address sent tomemory
is produced by adding the offset contained in the IP
register to the segment base represented by the upper
16 bits in the CS register.
‘Any time the 8086accesses memory, the BIU produces
the required 20-bit physical address by adding an offset
to a segment base value represented by the contents of
cone of the segment registers. As another example of this,
let’s look at how the 8086 uses the contents of the stack
segment register and the contents of the stack pointer
register to produce a physical address.
STACK SEGMENT REGISTER AND STACK
POINTER REGISTER
A stack, remember, is a section of memory set aside to
store addresses and data whilea subprogram is executing.
The 8086 allows you to set aside an entire 64-Kbyte
segment as a stack. The upper 16 bits of the starting
address for this segment are kept in the stack segment
register. The stack pointer (SP) register in the execution
unit holds the 16-bit offset from the start of the segment
to the memory location where a word was most recently
stored on the stack. The memory location where a word
‘was most revently stored is called the top of stack. Fig.
2.1]a shows this in diagram form.
‘The physical address for a stack read or a stack write
is produced by adding the contents of the stack pointer
register to the segment hase address represented by the
upper 16 bits of the base address in SS. Fig. 2.116 shows
PHYSICAL
ADDRESS,
‘perry
SFFEDH
<— Tor oF stack
“+— START OF STACK SEGMENT
SS = 500tH
ss
spt
PHYSICAL s00RESS
(TOP OF STACK).
Fig, 2.11 Addition of SS and SP to produce the
physical address of the top of the stack,
(a) Diagram, (b) Computation.2.16
Microprocessor and Interfaciag: Programming and Hardware
an example. The 5000H in SS represents a segment base
address of SOO00H. When the FFEQH in the SP is added
to this, the resultant physical address for the top of the
stack will be SPFEOH. The physical address can be
represented either as a singlenumber, SFFEOH, or in SS:SP
form 28 5000:FFEOH.
‘The operation and use ofthe stack will be discussed in
detail later as need arises.
POINTER AND INDEX REGISTERS IN THE
EXECUTION UNIT
In addition to the stack pointer register (SP), the EU
contains a 16-bit base pointer (BP) cegister. It also
contains a 16-bit source index (SI) register and a 16-bit
destination index (DV) register. These three registers can
be used for temporary storage of data just as the general-
purpose registers described above. However, their main
use is to hold the 16-bit offset of a data word in one of
the segments. SI, for example, can be used to hold the
offset of a data word in the data segment. The physical
address of the data in memory will be generated in this
‘case by adding the contents of SI to the segment base
address represented by the 16-bit number in the DS
register. After we give you an overview of the different
levelsof languages used to program a microcomputer, we
‘will show you some examples of how we tell the 8086 to
read data from or write data to a desired memory location,
INTRODUCTION TO PROGRAMMING
THE 8086
Programming Languages
‘Now that you have an overview of the 8085 CPU, it is
time to start thinking about how itis programmed. Torun
a program, a microcomputer must have the program
stored in binary form in successive memory locations, as
shown in Fig. 2.12. There are three language levels that
can be used to write a program for a microcomputer.
MACHINE LANGUAGE
‘You can write programsas simply a sequence of the binary
codes for the instructions you want the microcomputer
to execute. The three-instruction program in Fig. 2.6b is
an example. This binary form of the program is referred
to as machine language because itis the form required
by the machine. However, itis difficalt, if not impossible,
for a programmer to memorize the thousands of binary
instruction codes for a CPU such as the 8086. Also, itis
very easy for an error to occur when working with long
series of I's and 0's, Using hexadecimal representation for
the binary codes might help some, but there are still
thousands of instruction codes to cope with.
TABEL | OPCODE
FRED | FELD
NEXT: | ADD
CPERAND) COMMENT
FELD FED
‘AL, O7H_| |ADD CORRECTION FACTOR]
Fig. 2.12 Assembly language program statement
format.
ASSEMBLY LANGUAGE
To make programming easier, many programmers write
programs in assembly language. They then translate the
assembly language program to machine language so that
itcan be loaded into memory and run. Assembly language
uses two-, three-, or four-letter mnemonics to represent
each instruction type. A mnemonicis just a device tohelp
you remember something. The letters in an assembly
janguage mnemonic arc usvallyinitials ora shortened form
of the English word(s) for the operation performed by the
instruction. For example, the mnemonic for subtract is
SUB, the mnemonic for Exclusive OR is XOR, and the
mnemonic for the instruction to copy data from one
location to another is MOV.
Assembly language statements are usually written in
standard form that has four fields, as shown in Fig. 2.12,
‘The first field in an assembly language statement is the
label field. A label is a symbol or group of symbols used
to represent an address which is not specifically known
at the time the statement is written, Labels are usually
followed by acolon. Labels arenot required in a statement,
they are jast inserted where they are needed. We will show
later many uses of labels.
‘The opcode field of the instruction contains the
mnemonic for the instruction to be performed. Instruction
mnemonics are sometimes called operation codes, of
‘epcodes, The ADD mnemonic in the example statement
in Fig, 2.12 indicates that we want the instruction to do
anaddition.
The operand field of the statement contains the data,
the memory address, the port address, of the name of the
register on which the instruction is to be performed.
Operand is just another name for the data item(s) acted
on by an instruction. In the example instruction in
Fig. 2.12, there are two operands, AL and 07H, specified
inthe operand field. AL represents the AL register, and 07H
represents the number 07H. This assembly language
statement thus says, “Add the number 07H to the contentsComputers, Microcomputers, and Microporcessors—~An Introduction
of the AL register.” By Intel convention, the result of the
addition will be put in the register othe memory location
specified before the comma in the operand field. For the
example statementin Fig. 2.12, then, the result will be left
in the AL register. As another example, the assembly
longuage statement ADD BH, AL, when converted (0
machine language and run, will add the conients of the
AL register to the contents of the BH register. The results
will be left in the BH register.
‘The final field in an assembly language statement such
as that in Fig, 2.12is the commentfield, which starts with
a semicolon. Comments do not become part of the
‘machine language program, but they are very important.
You write comments in a program to remind you of the
function that an instruction er group of instructions
performs in the program.
‘To summarize why assembly language is easier to use
than machine language, let's look a little more closely at
the assembly language ADD statement. The general format
of the 8086 ADD instruction is
ADD Destination, Source
‘The source can be a number written in the instruction, the
contents of a specified register, or the contents of
memory location. The destination can be a specified
register or a specified memory location. However, the
source and the destination in aa instruction cannot both
bbe memory locations.
A later section on 8086 addressing modes will show
all the ways in which the source of an operand and the
destination of the result can be specified. The point here
isthatthe single mnemonic ADD. together witha specified
source and a specified destination, can represent a great
many 8086 instructions in an easily understandable form
The question that may occurto you at this point is, “If
I write a program in assembly language, how do I get it
translated into machine language which can be load into
the microcomputerandexecuted?” There aretwoanswers
to this question, The first method of doing the translation
is to work out the binary code for each instruction, 2 bit
ata time using the templates given in the manufacturer's
data books. We will show you how to do this in the next
chapter, but it isa tedious and error-prone task. The second
method of doing the translation is with an assembler. An
assembler is a program which can be run on a personal
computer or microcomputer development system. It reads
the file of assembly language instructions you write and
generates the correct binary code foreach. For developing
all but the simplest assembly language programs, an
assembler and other program development tools are
essential. We will introduce you to these program
development tools in the next chapter and describe their
use throughout the rest of this book
247
HIGH-LEVEL LANGUAGES
Another way of writing a program for a microcomputer
is with a high-level language, such as BASIC, Pascal, ot
C. These languages use program statements which are
even more English-like than those of assembly language.
Each high-level statement may represent many machine
code instructions. An interpreter program or a compiler
program is used to translate higher- level language
statements to machine codes which can be loaded into
memory and executed. Programs can usually be written
faster in high-level languages than in assembly language
because a high-level language works with bigger building
blocks. However, programs written in a high-level language
and interpreted or compiled almost always execute more
slowly and require more memory than the same programs
‘written in assembly language. Programs that involve a lot
of hardware control, such as robots and factory control
systems, or programs that must runas quickly as possible
are usually best written in assembly language. Complex
data processing programs that manipulate massive
amounts of data, such as insurance company records, are
asually best written ina high-level language. The decision
concerning which language to ase has recently been made
more difficult by the fact that current assemblers allow
the use of many high-level language fectures, and the fact
that some current high-level languages provide assembly
language features.
OUR CHOICE
For most of this book we work very closely with
hardware, so assembly language isthe best choice, Inlater
chapters, however, we do show you how to write
programs which contain modules written in assembly
Janguage and modules written in the high-level language
C. In the next chapter we inwoduce you to assembly
language programming techniques. Before we go on to
that, however, we will usea few simple 8086 instructions
to show you more about accessing data in registers and
memory locations,
How the 8086 Accesses Immediate
and Register Data
Ina previous discussion of the 8086 BIU, we described
how the BOS6 accesses code bytes using the contents oF
the CS and TP registers. We also described how the 8OR6
accesses the stack using the contents of the SS and SP
registers. Before we can teach you assembly language
programming techniques, we need to discuss some of the
different ways in which an 8086 can access the data that
it operates on. The different ways in which a processor
can access data are referred to as its addressing modes2.18
‘Microprocessor and Interfacing: Programming and Hardware
In assembly language statements, the addressing mode is
indicated in the instruction, We will use the 8086 MOV
instruction to illustrate some of the 8086 addressing modes.
‘The MOV instruction has the format
MOV Destination, Source
When executed, this instruction copies a word or a byte
from the specified source location to the specified
destination location, The source can bea number written
directly in theinstruction. aspecified register, or amemory
location specified in 1 of 24 different ways. The destination
can be a specified register or a memory location specified
in any 1 of 24 different ways. The source and the
destination cannot both be memory locations in an
instruction.
IMMEDIATE ADDRESSING MODE
Suppose that in a program you need to put the number
437BH in the CX register. The MOV CX, 437BH
instruction can be used to do this. When it executes, this
instruction will put the immediate hexadecimal number
437BH in the 16-bit CX register. This is referred to as
immediate addressing mode because the number 10 be
Toaded into the CX register will be put in thetwomemory
locations immediately following the code for the MOV
instruction. This is similar to the way the port address was
put in memory immediately after the code for the input
instruction in the three-instruction program in Fig. 2.66.
similar instruction, MOV CL, 48H, could be used to
load the 8-bit immediate number 48H into the 8-bit CL
register. You can also write instructions to load an 8-bit
immediate number into an 8-bit memory location or toload
2 16-bit number into two consecutive memory locations,
but we are not yet ready to show you how to specify these.
REGISTER ADDRESSING MODE
Register addressing mode means that a register is the
source of an operand for an instruction. The instruction
MOV CX, AX, for example, copies the contents of the
16- bit AX register into the 16-bit CX register. Remember
that the destination location is specified in the instruction
before the comma, and the source is specified after the
comma. Also note that the contents of AX are just copied
to CX, not actually moved. In other words, the previous
contents of CX are written over, but the contents of AX
are not changed. For example, if‘ CX contains 2A84H and
AX contains 4971H before the MOV CX, AX instruction
executes, then afier the instruction executes. CX will
contain 4971H and AX will still contain 49711. You can
MOV any 16-bit register to any 16-bit register, or you can
MOV any 8-bit registerto any &-bit register. However, you
‘cannot use an instruction such as MOV CX. AL because
this is an attempt to copy a byte-fype operand (AL) intoa
word-type destination (CX). The byte in AL would fit in
CX, but the 8086 would not know which half of CX to
put it in. If you try to write an instruction like this and
youare using a good assembler, theassembler will tell you
that the instruction contains a type error: To copy the byte
from AL to the high byte of CX, you can use the
instruction MOV CH, AL. To copy the byte from AL to
the low byte of CX, you can use the instruction MOV CL,
AL.
Accessing Data in Memory
OVERVIEW OF MEMORY ADDRESSING MODES
‘Theaddressing modes described in the following sections
are used to specify the location of an operand in memory.
To access data in memory, the 8086 must also produce a
20-bit paysical address. It does this by adding a 16-bit
value called the effective address to a segment base
address represented by the 16-bit number in one of the
four segment registers. The effective address (EA)
represents the displacement or offset of the desired
operand from the segment base. In most cases, any of
the segment bases can be specified, but the data segment
ADDRESS MEMORY
OFF
+ END OF DATA SEGMENT
axpeaisrer
paren J
Baran
OV 8x, [87 AH
se 20004
«
os [2]o] [0] 0
mA
PHYSICAL ADORESS
Fig. 2.13 Addition of data segment register and
effective address toproduce the phystcal
address of the data byte. (a) Diagram,
() Computation.Computers, Microcomputers, and Microporcessors—An introduction
is the one most often used. Fig. 2.134 shows in graphic
form how the EA is added to the data segment base to
point to an operand in memory. Fig. 2.136 shows how
the 20-bit physical address is generated by the BIU. The
starting address for the data segment in Fig. 2.13b is
20000H, so the data segment register will contain 2000H.
‘The BIU adds the effective address, 437AH, to the data
segment base address of 20000H to produce the physical
address sent out to memory. The 20-bit physical address
sent out to memory by the BIU will then be 2437 AK. The
physical address can be represented either as a single
number 2437AH or in the segment base:offset form as
2000:437AH.
The execution unit calculates the effective address for
an operand using information you specify in the
instruction. You can tell the EU to use a number in the
instruction as the effective address, to use the contents
of a specified regisler as the effective address, or to
compute the effective address by adding a number in the
instruction to the contents of one or two specified
registers. The following section describes one way you
caniell the execution unit to calculate an effective address
In Iter chapters we show other ways of specifying the
effective adress. Later we also show how the addressing
modes this provides, are used to solve some common
programming problems.
DIRECT ADDRESSING MODE
For the simplest memory addressing mode, the effective
address is just a 16-bit number written directly in the
instruction. The instruction MOV BL, [437AH] is an
example, The square brackets around the 437AH are
shorthand for “the contents of the memory locs
a displacement from the segment base of.
executed, this instruction will copy “the contents of the
‘memory location at adisplacement from the data segment
base of” 437AH into the BL register, as shown by the
rightmost arrow in Fig. 2.134. The BIU calculates the 20-
bit physical memory address by adding the effective
address 437AH to the date segment base, as shown in Fig.
2.136. This addressing mode is called direct because the
displacement of the operand from the segment base is
specified directly in the instruction. The displacement in
the instruction will be added to the data segment base in
DS unless you tell the BIU to add itto some other segment
base. Later we will show you how to do this.
Another example of the direct addressing mode is the
instruction MOV BX, [437AH]. When executed, this
instruction copies a 16-bit word from memory into the
2.19
BX register. Since each memory address of the 8086
represents a byle of storage, the word must come from
two memory locations. The byte at a displacement of
437AH from the data segment base will be copied into BL,
as shown by the right arrow in Fig, 2.13a, The contents
of the next higher address, displacement 437BH, will be
copied into the BH register, as shown by the left arrow in
Fig. 2.13a. From the instruction coding, the 8086 will
automatically determine the number of bytes that it must
access in memory.
‘An important point here is that an 8086 always stores,
the low byte of a word in the lower of the two addresses
and stores the high byte of a word in the higher address.
To stick this in your mind, remember:
Low byte—Low address, High byte—High address
The previous two examples showed how the direct
addressing mode can be used to specify the source of an
operand, Direct addressing can also be used to specify
the destination of an operand in memory. The instruction
MOV (437AH], BX, for example, will copy the contents
of the BX register to two memory locations in the data
segment. The contents of BL will be copied to the memory
location ata displacement of 437AH. The contents of BH
will be copied to the memory location at a displacement
of 437BH. This operationis represented by simply reversing
the direction of the arrows in Fig. 2.13a.
NOTE: When you are hand-coding prograns using
direct addressing of the form shown above, make sure
to put in the square brackets to remind you how to
code the instruction. If you leave the brackets out of
an instruction such as MOV BX, [437AH], you will
code it as if it were the instruction MOV BX, 437AH.
This second instruction will load the immediate
umber 437AH into BX, rather than loading a word
frommemory atadisplacement of 437AH into BX. Also
note that if you are writingan instruction using direct
addressing such asthis or an assembler, you must write
n the form MOV BL, DS:BYTE PTR
[437AH] to give the assembler all the information it
needs. As we will show you in the next chapter, when
you are using an assembler, you usually use aname 10
represent the direct address rather than the actual
numerical value.
‘A FEW WORDS ABOUT SEGMENTATION
Atthis point you may be wondering why Intel designed
the 8086 family devices to access memory using the
segment:offset approach rather than accessing memory
directly with 20-bit addresses. The segment:offset scheme
requires only a 16-bit numberto represent the base address
the instruction2.20
for a segment, and only a 16-bit offset to access any
location in a segment, This means that the 8086 has to
manipulate and store only 16-bit quantities instead of
20-bit quantities. This makes for an easier interface with
8- and 16-bit-wide memory boards and with the 16-bit
registers in the 8086.
"The second reason for segmentation hasto do with the
type of microcomputer in which an 8086-family CPU is
likely to be used. A previous section of this chapter
described briefly the operation of a timesharing
microcomputer system. In a timesharing system, several
users share a CPU, The CPU workson one user's program
for perhaps 20 ms, then workson the next user's program
for 20 ms. After working 20 ms for each of the other
users, the CPU comes back to the first user’s program
again, Each time the CPU switches from one user's
program to the next, it must access a new section of code
and new sections of data. Segmentation makes this
switching quite easy. Eachuser's program can be assigned
aa separate set of logical segments for its code and data.
The user's program will contain offsets or displacements
from these segment bases. To change from one user's
program to asecond user's program, all that the CPU has
to do is to reload the four segment registers with the
segment base addresses assigned to the second user's
program. In other words, segmentation makes it easy to
keep users’ programsand data separate from one another,
and segmentation makes it easy to switch from one user's
program to another user's program. In Chapter 15 we tell
Microprocessor and Interfacing: Programming and Hardware
‘you much more about the use of segmentation in multiuser
systems.
CHECKLIST OF IMPORTANT TERMS AND
CONCEPTS IN THIS CHAPTER
Uf yeu donot remember any ofthe termsor conceps in she following
is, use the index find them inthe chapter.
Miceacompuser micoprecesor
Hardware, oftware, firmware
Timesharing eompusersstem
Maliitasing computer stem
Dinribueed procesingsatem
Mulliprocesing
cpu
‘Memory RAM, ROM
WOpors
Adéres, data,and control buses
Control bus signals
ALU
Segmentation
Businterface unit (BIU)
Insracton bye queue, pipelining, ES, CS, SS, DSregsts, [Preiser
Execution unie (EU) AX. BX. CX. DX reste, flag register, ALU, SP.
BRSI Diregisters
Machine language, assembly language, high-evellan- guage
Mnemonic, [Link], label comment Auembler compiler
Immediate address mode register addressmede direct addressmode
Effesive address
Review Questions ND PROBLEMS
1. Deseribe the main advantages of a
processing computer system over a
timesharing system
2, Deseribe the sequence of signals that occurs on the
address bus, the control bus, and the data bus when
a simple microcomputer fetches an instruction.
3. What determines whether a microprocessor is
considered an §-bit, a 16-bit, or a 32-bit device?
4, a. How many address lines does an 8086 have?
b, How many memory addresses does this number
of address lines allow the 8086 to access
Girectly?
¢. Atany given time, the 8086 works with four
segments inthis address space. How many bytes
are contained in each segment?
5. What is the main difference between the 8086 and
the 8088?
6. a. Describe the function of the 8086 queue.
b, How does the queue speed up processing?
7. a. Ifthe code segment for an 8086 program stars
at address 70400H, what number will be in the
CS register?
b, Assuming this same code segment base, what
physical address will a code byte be fetched from
if the instrection pointer contains 539CH?
8, What physical address is represented by:
@. 4370:561EH
. 7A32:0028H
9, What is the advantage of using a CPU register for
temporary data storege over using a memory
location?
10, If the stack segment register contains 3000H and
the stack poinicr register contains 8434H1, what is
the physical address of the top of the stack?(Computers, Microcomputers, and Microporcessors—An introduction 2.21
11. a. What is the advantage of using assembly
language instead of writing a program directly
in machine language?
b, Describe the operation an 8086 will perform
when it executes ADD AX, BX.
12, What types of programs are usually written in
assembly language?
13. Describe the operation that an 8086 will perform
when itexecutes each of the following instructions:
a. MOV BX, 03FFH
b. MOV [Link]
ce. MOV DH, CL
d. MOVBX,AX
14, Write the 8086 assembly language statement which
will perform the following operations:
15,
16,
1.
18,
1. Load the number 7986H into the BP register.
. Copy the BP register contents to the SP register.
Copy the contents of the AX register to the DS
register
d, Load the number F3H into the AL register.
If the 8086 execution unit calculates an effective
address of 1443H and DS contains 7000H, what
physical address will the BIU produce?
If the data segment register (DS) contains 4000H,
what physical address will the instruction MOV AL,
(234BH] read?
If the 8086 data segment register contains 7000H,
write the instruction that will copy the contents of
DL toaddress 74B2CH.
Describe the difference between the instructions
MOV AX, 2437H and MOV AX, (2437H].
>8086 Family Assembly
Language Programming—
Introduction
he last chapter showed you the format for
I assembly language instructions and introduced you
toa few 8086 instructions. Developinga program,
however, requires more than just writing down a series
of instructions. When you want to build a house, itis a
good idea to first develop a complete set of plans for the
house. From the plans you can see whether the house has
the rooms you need, whether the rooms are efficiently
placed, and whether the house is structured so that you
‘can easily add on to it if you have more kids. You have
probably seen examples of what happens when someone
attempis to build a house by just putting pieces together
without a plan.
Likewise, when you write a computer program, it is a
‘g00d idea to start by developing a detailed plan or outline
forthe entire program. A good outline helps you to break
down alarge and seemingly overwhelming programming
{jobinto small modules whichcan easily be written, tested,
‘and debugged. The more time you spend organizing your
programs, the less time it will take you to write and debug
them. You should never start writing an assembly language
program by just writing down instructions! In this chapter
we show you how to develop assembly language pro-
grams in a systematic way.
OBJECTIVES
Atte conclusion of thischapter, you sheuld be able to:
1. Write a tak lis, flaochart, or pseudocode for a simple
programming problem.
2. White codeorasemble and rama ver simple asembl language
program,
3. Describe the useofprogram derelopment oolssuchaseditors,
asiemblers linkers locators debuggers and emulator
4. Properlydecument asembly language programs.
Defining the Problem
‘The first step in writing a program is to think very
carefully about the problem that you want the program to
solve. In other words, ask yourself many times, “What
do I really want this program to do?” If you don’ tdo this,
you may write a program that works great but does not
{do what you need itto do. As you think about the problem,
it is a good idea to write down exactly what you want the
program to do and the order in which you want the
program to do it. At this point you do not write down
program statements, you just write the operations you want
in general terms. An example for a simple programming
problem might be
1, Read temperature from sensor.
2. Add correction factor of + 7
Save result in a memory location
For a program as simple as this, the three actions desired
are very close to the eventual assembly language3.2
statements. For more complex problems, however, we
develop a more extensive outline before writing the
assembly language statements. The next section shows
you some of the common ways of representing program
‘operations in a program outline.
Representing Program Operations
‘The formula or sequence of operations used to solve a
programming problem is often called the atgorittm of the
program. The following sections show you two common
‘ways of representing the algorithm for a program or
rogram segment.
FLOWCHARTS
If you have done any previous programming in BASIC or
inFORTRAN, you are probably familiar with flowchars
Flowcharts use graphic shapes to represent different
types of program operations. The specific operation
desired is written in the graphic symbol. Fig. 3.1 shows
some of the common flowchart symbols. Plastic templates
areavailable to help you draw these symbols if you decide
to use them for your programs.
Figure 3.2, shows a flowchart for a program wo read
in 24 data samples from a temperature sensor at |-hour
intervals, add 7 to each, and store each result ina memory
location. A racetrack- or circular-shaped symbol labeled
START is used to indicate the beginning of the program.
A parallelogram is used to represent an input or an output
operation. In the example, we use it to indicate reading
data from the temperature sensor. A rectangular box
symbol is used to represent simple operations other than
inpat and output operations. The box containing “add 7”
in Fig. 3.2 is an example.
mrocess| Se] Gon)
OFF-PAGE CONNECTOR|
OMNESTOR
—
|
sua
ROUTINE
Fig. 3.1. Flowchart symbols.
A rectangular box with double lines at each end is often
used to represent a subroutine or procedure that will be
‘written seperately from the main program. When a set of
operations must be done several times during a program,
itisusually more efficient to write the series of operations
Microprocessor and Interfacing: Programming and Hardware
once as a separate subprogram, then just “call” this
subprogram each time itis needed. For example, suppose
that there are several places in a program where you need
tocompute the square root of a number. Instead of writing
the series of instructions for computing a square root each
time you need it in the program, you can write the
instruction sequence once as a separate procedure and put
itin memory after the main program. A special instruction
allows you to call this procedure each time you need to
‘compute a square root. Another special instruction at the
end of the procedure program returns execution to the
main program. In the flowchart in Fig. 3.2, we use the
double-ended box to indicate that the “wait 1 hour”
operation will be programmed as a procedure. Inciden-
tally, the tems subprogram, subroutine, and procedure all
have the same meaning. Chapter 5 showshow procedures
are written and used.
{Cea
fevo vue
[RRB
[STORE RESULT]
INMENORY
WAST 4 HOUR
28
LNO_—“SantpLes
2
ves
\ Csr)
J
Flowchart for program to read in 24 data
samples from a port, correct each value,
and store each ina memory location.
Fig. 3.2
A diamond-shaped box is used in flowcharts to repre-
sent a decision point or crossroad. Usually it indicates that
some condition is to be checked at this point in the8086 Famty Assembly Language Prograruning—Introduction 3.3
program. If the condition is found to be true, one set of
actions is to be done; if the condition is found to be fase,
another set of actions is to be done. In the example
flowchart in Fig. 3.2, the condition to be checked is
whether 24 samples have been read in and processed. If
24 samples have not been read in and processed, the
arrow labeled NO in the flowchart indicates that we want
the computer to jump back and execute the read, add,
store, and wait steps again, If 24 samples have been read
in, the arrow labeled YES in the flowchart of Fig. 3.2
indicates that all the desired operations have been done.
The racetrack-shaped symbol at the bottom of the
flowchart indicates the end of the program.
The two additional flowchart symbols in Fig. 3.1 are
connectors. If a flowchart column gets to the bottom of
the paper, but not all the program has been represented,
you can puta small circle with g letter in it at the bottom
of the column. You then start the next column at the top
of the samme paper with a sinall circle containing the same
letter. If you need to continue a flowchartto another page,
you can end the flowchart on the first page with the five-
sided off-page connector symbol containing a letter or
‘number. You then start the flowchart on the next page with
an off-page connector symbol containing the same letter
or number.
Forsimple programs and program sections, flowcharts
are a graphic way of showing the operational flow of the
program. We will show flowcharts for many of the
program examples throughout this book. Flowcharts,
however, have several disadvantages. First, you can’t write
‘mach information in the little boxes. Second, flowcharts
do not present information in a very compact form. For
more complex problems, flowcharts tend to spread out
over many pages. They are very hard to follow back and
forth between pages. Third, and most important, with
flowcharts the overall structure of the program tends to
get lost in the details. The following section describes a
more clearly structured and compact method of
representing the algorithm of a program or program
segment.
STRUCTURED PROGRAMMING AND
PSEUDOCODE OVERVIEW
In the early days of computers, a single brilliant person
might write even a large program single-handedly. The
main concerns in this case were, “Does the program
work?” and “What do we do if this person leaves the
company?” As the number of computers increased and
the complexity of the programs being written increased,
large programming jobs were usually turned over to &
team of programmers. In this case the compatibility of
parts written by different programmers became an
important concern. During the 1970s it became obvious
to many professional programmers that in order for team
programming to work, a systematic approach and
standardized tools were absolutely necessary.
‘One suggested systematic approzch is called top-down
design. Inthis approach, a large programming problem is
first divided into major modules. Thetop levelof the outline
shows therelationship and function of these modules. This
top level then presents a one-page overview of the entire
program. Bach of the major modules is broken down into
still smaller modules on following pages. The division is
continued until the steps in each module are clearly
understandable, Each programmer can then be assigned
a module or set of modules to write for the program.
Another advantage of this approach is that people who
later want to learn about the program can start with the
overview and work their way down to the level of detail
they need. This approach is the same as drawing the
complete plans for a house before starting to build it.
‘The opposite of top-down design is dosrom-up design.
In this approach. each programmer starts writing low-
level modulesand hopes that all the pieces will eventually
fit together. When completed, the result should be similar
to that produced by the top-down design. Most modern
programming teams use a combination of the two
techniques. They do the top-down design first, then build,
test, and link modules starting from the smallest and
working upward,
The development of standard programming methods
was helped by the discovery that any desired program
operation could be represented by three basic types of
operation. The first type of operation is sequence, which
means simply doing a series of actions. The second basic
type of operation is decision, or selection, which means
‘choosing between two altemative actions. The third basic
lype of operation is repetition, or iteration, which means
repeating a series of actions until some condition is or is
not present,
On the basis of this observation, the suggestion was
made thet programmers use a set of three to seven
standard structures to represent all the operations in their
programs, Actually, only three structures, SEQUENCE,
IF-THEN-ELSE, and WHILE-DO, are required to
represent any desired program action, but three or four
more structures derived from these often make programs
clearer. If you have previously written programs in a
structured language such as Pascal, then these structures
are probably already familiar to you. Fig. 3.3, uses34 Microprocessor and Interfacing: Programming and Hardware
flowchart symbols to represent the commonly used
structures so that you can more easily visualize their
operation. In actual program documentation, however,
English-like statements called pseudocode are used rather
than the space-consuming flowchart symbols. Fig. 3.3
also shows the pseudocode format and an example for
each structure.
Each structure has only one entry point and one exit
point. As you will see later, this feature makes debugging
the final program much easier. The output of one structure
is connected to the input of the next structure, Program
execution then proceeds through a series of these
structures,
Any structure can be used within another. An IF-
THEN-ELSE structure, for example, can contain a se-
quence of statements. Any place that the term state-
‘ment(s) appears in Fig. 3.3, one of the other structures
could be substituted for it. The term starement{s) can also
represent a subprogram or procedure that is called to do
a series of actions. Now, let’s look more closely at these
structures.
STANDARD PROGRAMMING STRUCTURES
The structure shown in Fig. 3.34 isan example of a simple
sequence. In this structure, the actions are simply written
down in the desired order. An example is.
Read temperature from sensor.
‘Add correction factor of + 7.
Store corrected value in memory.
Figure 3.2b shows an IF-THEN-ELSE example of the
decision operation. This structure is used to direct
operation to one of two different actions based on some
condition. An example is
IF temperature less than 70 degrees THEN
Turn on heater
ELSE
‘Tur off heater
The example says that if the temperature is below the
thermostat setting, we want to tum the heater on. If the
temperature is equal to or above the thermostat setting,
‘we want to turn the heater off.
‘The IF-THEN structure shown in Fig. 3.3c is the same
as the IF-THEN-ELSE except that one of the paths
contains no action. An example of this is
IF hungry THEN
Get food
The assumption for this example is that if you are not
hungry, you will just continue on with your next task.
To represent a situation in which you want to select
Cone of several actions based on some condition, you can
use a nested [F-THEN.-EL SE structure such as that shown
in Fig. 3.34. This everyday example describes the thinking
4 soup cook might go through. Note that in this example
the last IF-THEN has no ELSE after it because all the
possible days have been checked. You can, if you want,
add the final ELSE to the IF-THEN- ELSE chain to send
an error message if the data does not match any of the
choices.
‘The CASE structure shown in Fig. 3.3¢ is really just a
compact way to represent a complex IF-THEN- ELSE
structure. The choice of action is determined by testing
some quantity. The cook or the computer checks the value
of the variable called “day” and selects the appropriate
actions for that day. Each of the indicated actions, such
as “Make celery soup,” is itself a sequence of actions
which could be represented by the structures we have
described. Note that the CASE structure does not contain
the final ELSE for an error.
The CASE form is more compact for documentation
purposes, and some high-level languages such as Pascal
allow you to implement it directly. However, the nested
IF-THEN-ELSE structure gives you a much better idea
of how you write an assembly language program section
to choose between several alternative actions.
The WHILE-DO structure in Fig. 3.3 is one form of
repetition. Itis used to indicate that you want to do some
action or sequence of actions as long as some condition
is present. This structure represents a program loop. The
example in Fig. 3.3fis
WHILE money lasts DO
Eat supper out.
Go to movie.
Take a texi home,
This example shows a sequence of actions you might do
‘each evening until you ran out of money. Note that in this
structure, the condition ischecked before the action is done
the first time. You certainly want to check how much
money you have before eating out.
Another useful repetition structure is the REPEAT-
UNTIL structure shown in Fig. 3.3g. You use this structure
to indicate that you want the program to repeat some
action or series of actions until some condition is preseat.
‘A good example of the use of this structure is the
programming problem we used in the discussion of
flowcharts. The example is5086 Family Assembly Language Programming—intreduction
/ \
IF-THEN-ELSE FLOWCHART
3.5
/ SIMPLE SEQUENCE RLOWCHART
[STATEMENT(S)1
he
IF-THEN FLONCHART \
‘CASE EXPRESSED AS MULTIPLE IF-THEN ELSE FLOWCHART
frarewenrsd [pareve] rarenewiod renew
seupocone rseyngcone Pseunocone
en PES ERfon men if en
SIAEMENTISE Saar STENENTO
5‘ Earenewrse ge
BEA NES: IF ROOM TEMPERATURE LESS THAN SET POINTTHEN ——'F HUNGRY THEN
Seer 3
SBF mnenorrvocanon —_ gygum ONFUIACE sere
un or FuRgce
(a) oy to
CASE FLOWCHART
1
SELECTING EXPRESSION |
es Kea
fect s Fmaena [armend.-fraeuenie
"ee
£8. Ginom) —_—|
“
E
eee or
SESS)
Ps EXAMPLE en
IRECILEY oop acct
SE LIRRE LED cour TUE esto
cst ONESDAY THER wellQhEMINESTRONE soUP
GION MAKE ONION SOUP
see shown! aug
SEEN cour eee
fs es
\wive.00 Loe owesanr FPEATUNTLOWENART
Gones> YO 'STATENENT
SZ }
es wo |
[STATENENT(S) se EXAMPLE |
fase) Else |
ves Bomnswune
Beeneaurnncsors |
oye rsrypocene ae
TRE onoyso Me none aereo0 wntaE eines ween
SIN mest
\
TAKE TARIHOME
o
REPSTATEMENT(S
unt CONSIGN
@
Ke
Fig.3.3. Standard program structures. (a) Sequence,
(b)IF THEN ELSE, (¢) IF THEN, (d) CASE expressed
as nested IF- THEN-ELSE, (e) CASE, (f) WHILE-DO, (q) REPEAT-UNTIL.3.6 ‘Microprocessor and Interfacing: Programming and Hardware
REPEAT
Get data sample from sensor.
‘Add correction of +7.
Store result in a memory location.
Wait 1 hour.
UNTIL 24 samples taken.
Notethatin aREPEAT-UNTIL structure, the action(s)
is done once before the condition is checked. If you want
thecondition to be checked before any action isdone, then
‘you can write the algorithm with a WHILE-DO structure
as follows:
WHILE NOT 24 samples DO
Read data sample from temperature sensor.
Add correction factor of + 7.
Store result in memory location.
Wait 1 hour.
Remember, aREPEAT-UNTIL structure indicates that
the condition is first checked after the statement(s) is
performed, so the action or series of actions will always
be done at least once. If you don’t want this to happen,
then use the WHILE-DO, which indicates that the condi-
tion is checked before any action is taken. As we will show
later, the structure you use makes a difference in theactwal
assembly language program you write to implement it.
‘The WHILE-DO and REPEAT-UNTIL structures con-
tain a simple IF-THEN-ELSE decision operation. How-
ever, since this decision is an implied part of these two
structures, we don’t indicate the decision separately in
them.
‘Another form of the repetition operation that you might
seein high-level language programs is the FOR- DO loop.
This structure has the form
FOR count = 1 TOn DO
statement
statement
This FOR DO loop. as it is often called, simply repeats
the sequence of actions n times, so for assembly language
algorithms we usually implement this type of operation
with a REPEAT-UNTIL structure.
Incidentally, if you compare the space required by the
pseudocode representation for a program structure with
the space required by the flowchart representation for the
same structure, the spaceadvantage of pseudocode should
be obvious.
‘Throughout the rest of this book, we show you how
to use these structures to represent program actions and
how to implement these structures in assembly language.
SUMMARY OF PROGRAM STRUCTURE
REPRESENTATION FORMS
Writing a successful program does not consist of just
writing down a series of instructions. You must first think
carefully about what you want the program to do and how
you want the program to do it. Then you must represent
the structure of the program in some way thatis very clear
both to you and to anyone else who might have to work
on the program,
‘One way of representing program operations is with
flowcharts. Flowcharts are a very graphic representation,
and they are useful for short program segments, espe-
cially those that deal directly with hardware. However,
flowcharts use a great deal of space. Consequently, the
flowchart for even a moderately complex program may
take up several pages. It often becomes difficult to follow
program flow back and forth between pages. Also, since
there are no agreed-upon structures, a poor programmer
can write a flowchart which jumps all over the place and
is even more difficult to follow. The term “logical
spaghetti” comes to mind here.
A second way of representing the operations you want
in a program is with a top-down cesign approach and
standard program structures, The overall program problem
is first broken down into major functional modules. Each
ofthese modules is broken down into smaller and smaller
‘modules until the steps in each module are obvious. The
algorithms for the whole program and for each module
are expressed with a standard structure, Only three basic
structures. SEQUENCE, IF-THEN-ELSE, and WHILE-
DO, are needed to represent any needed program action
or series of actions. However, other useful structures such
asIF-THEN, REPEAT- UNTIL, FOR-DO, and CASEcan
bbe derived from these basic three. A structure can contain
another structure of the same type or one of the other
types. Each structure has only one entry point and one
exit point. These programming structures may seem
restrictive, but using them usually results in algorithms
which are easy to follow. Also, as we will show you soon,
if you write the algorithm for a program carefully with
these standard structures, it is relatively easy to translate
the algorithm to the equivalent assembly language
instructions.
Finding the Right Instruction
After you get the structure of a program worked out and
‘written down, the next step is todetermine the instruction
statements required to do each part of the program. Since
the examples in this book are based on the 8086 family of8036 Family Assembly Language Programming—introduction 3.7
microprocessors, row is a good time to give you an
overview of the instructions the 8086 has for you to use.
First, however, is « hint about how to approach these
instructions.
You do not usually learn a new language by memoriz~
ing an entire dictionary of the language. A better way isto
lear afew useful words and practice putting these words
together in simple sentences, You can then learn more
words as you need them to express more complex
thoughts. Likewise, you should not try to memorize all
the instructions for a microprocessor at once.
For future reference, Chapter 6 contains a dictionary
of all the 8086 instructions with detailed descriptions and
‘examples of cach. As an introduction, however, the few
pages here contain a list of all the 8086 instructions with
‘a short explanation of each. Skimthrough the list and pick
‘out a dozen or so instructions that seem useful and
understandable. AS a start, look for move, input, output,
logical, andarithmetic instructions. Then look through the
list again to see if you can find the instructions that you
might use to do the “read temperature sensor value from
a port, add + 7, and store resuit in memory” example
program.
You can use Chapter 6 as a reference as you write
programs. Here we simply list the 8086 instructions in
functional groups with single-sentence descriptions so that,
‘you can see the types of instructions that are evailable to
You. As you read through this section, do not expect to
understand all the instructions, When you start writing
programs, you will probably use this section to determine
the type of instruction and Chapter 6 to get the instruction
details as you need them. After you have written a few
programs, you will remember most ofthe basic instruction
types and will be able to simply lock up an instruction
in Chapter 6 to get any additional details you need,
Chapter 4 shows you in detail how to use the move,
arithmetic, logical, jump, and string instructions. Chapter 5
shows how to use the call instructions and the stack,
DATA TRANSFER INSTRUCTIONS
General-purpose byte or word transfer instructions:
MNEMONIC DESCRIPTION
Mov Copy byte or word from specified
source to specified destination.
PUSH Copy specified word to top of stack
POP Copy word from top of stack to
specified location.
PUSHA (801 86/801 88 only) Copy all registers
to stack.
POPA (60186/80188 only) Copy words from
stack to all registers.
XCHG Exchange bytes or exchange words.
XLAT Translate a byte in AL using a table in
memory.
Simple input end output port transfer instructions:
IN Copy a byte or word from specified
port to accumulator.
ouT Copy a byte or ward from accumulator
to specified port.
Special address transier instructions:
Lea Load effective address of operand into
specified regisier.
Los Load DS register and other specified
register from memory.
LES Load ES register and other specified
register irom memory.
Flag twanster instructions:
LAHF Load (copy to) AH with the low byte
of the flag register.
SAHF Store (copy) AH register to low byte
of flag register.
PUSHF Copy flag register to top of stack.
POPF Copy word at top of stack to flag
register.
ARITHMETIC INSTRUCTIONS
Addition instructions:
ADD Add specified byte to byte or specified
word to word.
Apc Add byte+ byte + carry flag or word +
word + carry flag
INC Increment specified byte or specified
word by 1.
AMA ASCH adjust after addition
DAA Decimal (BCD) adjust after addition.
Subtraction instructions:
sua Subtract byte from byte of word from
word.
sBB Subtract byte and cary flag from byte
or word and carry flag irom word.
DEC Decrement specified byteor specified
word by 1
NEG Negate — invert each bit of a
specified byte or word and add 1
(orm 2's complement
op Compare two specified bytes or two
specified words.
AAS ASCII agjust after subtraction.
DAS Decimal (BCD) adjust ater
subtraction,
Multiplication instructions:
MUL Multiply unsigned byte by byte or
unsigned word by word.IMUL Multiply signed byte by byte or signed
word by word.
‘AM ASCII adjust after multiplication.
Division instructions:
Div Divide unsigned word by byte or
unsigned double word by word
ID Divide signed word by byte or signed
double word by word.
AAD, ASCII adjust before division
cBw Fill upper byte of word with copies of
sign bit of lower byte.
cwo Fill upper word of double word with
sign bit of lower word.
BIT MANIPULATION INSTRUCTIONS
Logical instructions
NOT Invert each
AND AND each bitin a byte or word with
the corresponding bitin another byte
orword
OR OR each bit ina byte or word with the
corresponding bit in another byte or
word.
XOR Exclusive OR each bit ina byte or
word with the corresponding bit in
another byte or word.
TEST AND operands to update flags, but
dor't change operands.
Shit instructions:
SHUSAL Shift bits oi word orbyte left, put zero(s)
in LSB).
SHR Shift bits of word or byte right, put
zero\s) in MSB(S).
SAR Shift bits of word or byte right, copy
old MSB into new MSB.
Rotate instructions:
ROL Rotate bits of byte or word left, MSB
to LSB and 10 CF,
ROR Rotate bits of byte or word right, LSB
to MSB and to CF.
ReL Rotate bits of byte or word lefi, MSB
to CF and CF to LSB.
RCR Rotate bits of byte or word right, LSB
to CF and CF to MSB.
STRING INSTRUCTIONS.
A string is a series of bytes ot a series of words in
sequential memory locations. A string often consists of
ASCII charsctercodes. Inthelist,a“/” is asedto separate
ferent mnemonics for the same instruction, Use the
‘mnemonic which most clearly describes the function of
theinstruction ina specific application. A“B” in amnemonic
Microprocessor and Interfacing: Programming and Hardware
is used to specifically indicate that a string of bytes is to
beacted upon. A “W" in the mnemonic is used to indicate
that a string of words is to be acted upon.
REP An instruction prefix.
Repeat following
instruction until
x=0.
An instruction prefix.
Repeat instruction until
€X = 0 or zero flag ZF
1.
An instruction prefix.
Repeat until CX = Cor
ZF=1.
Move byte or word from
one string to another.
Comparetwo string bytes
ortwo string words.
(80186/80188) Input
string byte or word
from port,
(0186/8018) Output
string byte or word to
port.
Scana string, Compare a
sting byte with a byte
in AL or a string word
with a word in AX.
Load string byte into AL
orstring word into AX.
Store byte irom AL or
word from AX into
string
REPE/REPZ
REPNE/REPNZ
MOVSIMOVSB/MOVSW
COMPS/COMPSB/COMPSW
INS/INSB/INSW
OUTS/OUTSBIOUTSW
SCAS/SCASB/SCASW
LODSLODSBLODSW
STOS/STOSB/STOSW
PROGRAM EXECUTION TRANSFER
INSTRUCTIONS:
‘These instructions are used to tell the 8086 to start fetching
instructions from some new address, rather than
continuing in sequence.
Unconditional transfer instructions:
CALL Call a procedure (subprogram), save
return address on stack.
RET Return from procedure to calling
program,
IMP Go to specified address to get next
instruction.
Conditional transfer instructions:
A“7”’is used to separate two mnemonics which represent
the same instruction. Use the mnemonic whichmost clearly
describes the decision condition in a specific program.
These instructions are often used after a compare
instruction. The terms below and above refer to unsigned8086 Family Assembly Language Programming—Introduction| 3.9
binary aumbers. Above means larger in magnitude. The
terms greater than or less than refer to signed binary
numbers. Greater than means more positive.
JAINBE Jump if above/lumpif not below or
equal.
JABIIN Jump if above or equal/ump if not
below.
JB/INAE Jump iibelow/Jumpiifnot above or
equal.
JBE/INA lump if below or equal/iump if not
above,
1c jump if carry flag CF =1
JEN. Jump if equal/fump if zero flag
2
JG/INLE Jump if greater/lump if not less
than or equal
JGEJNL Jump if greater thanor equal! jump
if not less than.
JLINGE Jump if less than/lump if not
greater than or equal
JLEJING Jump if less than or equal/Jump if
not greater than.
INC Jump if no carry (CF = 0).
JNEJNZ Jump if not equal/Jump if not
2et0 (ZF = 0)
JNO Jump if no overflow (overflow
flag OF = 0}
INFAPO Jump if not parity/jump if parity
odd (PF = 0).
JNS Jump if not sign (sign flag SF = 0).
Jo Jump if overflow flag OF = 1
IPAPE Jump if parity/Jump if parity even
(PF = 1).
Js Jump if sign «SF = 1)
eration control instructions
These instructions can be used to execute @ series of
instructions some number of times. Here mnemonics
separated by a “Y" represent the same instruction. Use the
‘one that best fits the specific application,
Loop Loop through a sequence of
instructions until CX = 0.
LOOPELOOPZ Loop through a sequence of
instructions while ZF = 1 and
Cx #0.
LOOPNE/LOOPNZ Loop through a sequence of
instructions while ZF = 0 and
cx #0,
Jump to specified address if
Cx =0.
If you aren't tired of instructions, continue skimming
through the rest ofthe list. Don’t worry if the explanation
JOXZ
is not clear to you because we will explain these instruc~
tions in detail in later chapters.
Interrupt instructions:
INT Interrupt program execution, call
service procedure
INTO Interrupt program execution if
OF=1
RET Return from interrupt service
procedure to main program.
High-level language imerface instructions:
ENTER (80186/80188 only) Enter pro-
cedure.
LEAVE (80186/80188 only) Leave pro-
cedure,
BOUND (80186/80188 only} Check if
ffective address within spec-
ified array bounds
PROCESSOR CONTROL INSTRUCTIONS
Flag set/elear instructions
ste Set carry flag CF t0 1
cic Clear carry flag CF to 0.
cmc Complement the state of the carry
flag CF
sto Set direction tlag DF to 1 (decre-
ment string pointers!
co Clear direction flag DF to 0.
stl Set interrupt enable flag to 1
(enable INTR input
cu Clear interrupt enable flag to 0
(disable INTR input)
External hardware synchronization instructions:
HUT Halt (do nothing) until intesrupi or
reset.
‘Wait (do nothing) until signal on
the TEST pin is low.
Esc Escape to external coprocessor
such as 8087 oF 8089.
‘An instruction prefix. Prevents
another processor from taking
the bus while the adjacent
instruction executes.
No operation instruction
NoP. No action except fetch and
decode.
WAIT
Lock
Now that you have skimmed through an overview of the
8086 instruction set, let's see whether you found the
instructions needed to implement the "read sensor, add
+7, and store result in memory” example program. The
IN instruction can be used to read the temperature value3.10
Microprocessor and Interfacing: Programming andl Hardware
from an A/D converter connected to a port. The ADD
instruction can be used to add the correction factor of
£7 to the value read in, Finally, the MOV instruction can
be used to copy the result of the addition to a memory
location, A major point here is that breaking down the
programming problem into a sequence of steps makes it
easy to fiid the instruction or small group of instructions
that will perform each step. The next section shows you
how to write the actual program using the 8086
instructions.
Writing a Program
INITIALIZATION INSTRUCTIONS,
After finding the instructions you need to do the main part
of your program, there ere a few additional instructions
that you need to determine before you actually write your
program. The purpose of these additional instructions is
10 initialize various parts of the system, such as segment
registers. flags, and programmable port devices. Seement
registers, for example, must be loaded with the upper 16
bitsof the address in memory where you want the segment
to begin. For our “read temperature sensor, add +7, and
store result in memory” example program, the only part
‘we need to initialize is the data segment register. The data
seginent register must be initialized so that we can copy
the result of the addition to a location in memory. If, for
example, we want to store data in memory starting at
address 00100H, then we want the data segment register
to contain the upper 16 bits of this address, ODLOH. The
8086 does not have an instruction to movea number directly
into a segment register. Therefore, we move the desired
‘number into one of the 16-bit general-puspose registers,
then copy it to the desired segment register. Two MOV
instructions will do this.
If you are using the stack in your program, then you
‘must include instructionsto load the stack segment register
and an instruction to load the stack pointer register with
the offset of the top of the stack. Most microcomputer
systems contain several programmable peripheral devices,
such as ports, timers, and controiters. You must include
instructions which send control words to these devices
to tell them the function you want them to perform. Also,
you usually want to include instructions which set or clear
the control flags, such as the interrupt enable flag and the
direction flag.
‘The best way to approach the initialization task is to
‘make achecklistof all theregisters, programmable devices.
and flags in the system you are working on. Then you can
mark the ones you need fer a specific program and
determine the instructions needed to initialize each part.
‘An initialization listfor an 8086-based system, such as the
SDK-86 prototyping board, might lock like the following.
INITIALIZATION LIST
Data segment register DS
Stack segment register SS
Entra segment register ES
Stack pointer register SP
8255 programmable parallel por
8259A priority interrupt controller
£8254 programmable counter
8251 A programmable serial port
Initialize data variables
‘Sct interrupt enable flag
‘As you can sce, the list can become quite lengthy even
though we havenot included all the devices a system might
coinmonly have, Note that initializing the code segment
register CS is absent from this list. The code segment
register is loaded with the correct starting value by the
system command you use to run the program, Now let’s
see how you putall these parts together to makea program.
STANDARD PROGRAM FORMAT
Inthis section we show you howto format your programs
if you are going to construct the machine codes for each
instruction by hand, A later section of this chapier will
show you the additional parts you need to add to the
program if you are goingto use a computer program called
fan assembler to produce the binary codes for the
instructions.
‘Totelp you write your programs in the correct format,
assembly language coding sheets such as that shown in
Fig. 3.4 areavailable. The ADDRESS column is used for
the address or the offset of a code byte or data byte. The
actual code bytes ordatabytes are putin the DATA/CODE
column. A label is a name which represents an address
referred to in jump or cal instruction; labels are put in
the LABELS column. A label is followed by a
colon (:) if it is used by a jump or cal instruction in the
same code segment. The MNEM column contains the
opcode mnemonics for the instructions, The
OPERAND(S) column contains the registers, memory
locations, or data acted upon by the instructions. A
COMMENTS column gives you space to describe the
function of the instruction for future reference.
Figure 3.4, shows how instructions for the “read
temperature, add +7, store result in memory” program can
be written in sequence on a coding sheet. We will discuss8086 Family Assembly Language Programming —Introduction, 3.11
PROGRAMMER 3.0 JAAP SHEET 7 FT
PROGRAM TITLE 10> TucCinTiA AND CORECT Bae ak
AESRACT "Bis pas a Ia oles os UIST ies fk CAA oe a cod fader of #7
a ad anton Hanes th etal i ota saan heaton
enoccanies ‘we colle
ALQLSTRS HSE re
FUAGSAGHCED, — All cditnal
ARTs. to 08a pel pant
ecuony 201008 Wa 02200..002001, CES
ADDRESS | DATA | LABELS MNEM. | OPERANDS) COMMENTS
cope
O10 ca Mast may heal To
ooror overtake ston
0102 tl eld wth a data bie
0103 at sadn E cova by th pga
0108 TH means Hatch” boat
00/08 cnlansoflcolon
00106
oor07
00108
00109
oor |
ooree | _
wore |
20103 t
007 t Cees os
010% t Tie ah naa
200 te Wet Ak cored ‘iil DS to paintl ant
27 a | iy a ie aig da
a 0 i
a z WD asf
oe Be T
05 o w Al On Bad omc fm
06 © pond Ot
oF o BD Ab oH Ald esr flr 107
os or
oe az Wow [e000 Sos sal wed
af @ arp
of wo
26. az W7, z Sip, wad promod
oD famuter
a
oF
Fig. 3.4 Assembly language programon standard coding form.12 Microprocessor and Interfacing: Programming and Hareware
here the operation of these instructions to the extent
needed. If you want more information, detailed
descriptions of the syrttax (assembly language grammar)
and operation of each of these instructions can be found
Chapter 6.
‘The first line at the top of the coding form in Fig. 34
does not represent an instruction. It simply indicates that
‘we want to set aside memory location to store the result
This location must be in available RAM so that we can
write to it. Address OOL00H isan available RAM location
on an SDK-86 prototyping board, so we chose it for this
example. Next, we decide where in memory we want 10
start puiting the code bytes for the instructions of the
program. Again, on an SDK-86 prototyping board, address
(00200H and aboye isavailable RAM, so we chose to start
the program at address. 00200H.
‘The first operation we want to do in the program is to
initialize the data segment register. As discussed previously,
two MOV instructions are used todo this. The MOV AX,
OOIDH instruction, when executed, will load the upper
16 bits of the address we chose for data storage into the
AX register. The MOV DS, AX instruction will copy this
‘number from the AX register fo the data segment register
Now we get to the instructions that dothe input, add, and
store operations. The IN AL, 05H instruetion will copy a
data byte from the port OSH to the AL register. The ADD
AL, 07 instruction will add O7H tothe AL register and leave
the result in the AL register. The MOV [0000], AL
instruction will copy the byte in AL toa memory location
at a displacement of 0000H from the data segment base
In other words, AL will be copied to a physical address
computed by adding 0000 to the segment base address
represented by the 0010H in the DS register. The result of
thisadditionis a physical address of OC/100H, so theresult
in AL will becopied to physical address 0100H in memory
Thisis an example of the direct addressing mode described
near the end of the previous chapter.
The INT 3 instruction at the end of the program
Functions as breakpoint. When the 8086 on an SDK- 86
board executes this instruction, it will cause the 8086 to
stop executing the instructions of your programand return
control to the monitor or system program. You can then
use system commands to look at the contents of registers
and memory locations, or you can run another program,
Without an instruction such as this at the end of the
program, the 8086 would fetch and execute the code bytes
for your program, then go on fetching meaningless bytes
from memory and trying to execute them as if they were
code bytes
‘The next major section of this chapter will show you
how to constructthe binary codes for these and other 8086
instructionsso that you can assemble and ran the programs
on a development board such as the SDK-86. First,
however, we want to use Fig. 3.4 to make an important
point about writing assembly language program
DOCUMENTATION
Ina previous section of this chapter, we stressed the point
that you should do a lot of thinking and carefully write
down the algorithm for aprogram before you start writing
instruction statements. You should also document the
program itself so that its operation is clear to you and to
anyone else who needs to understand it
Each page of the program should contain the name of
the program, the page number, the name of the
programmer, and perhaps a version number. Each program
Or procedure should have a heading block containing an
abstract describing what the program is supposed to do,
which procedures it calls, which registers it uses, which
ports ituses, which flags it affects, the memory used, and
any other information which will make it easier for another
programmer to interface with the program.
Comments should be used generously to describe the
specific function of an instruction or group of instructions
in this particular program, Comments should not be just
aan expansion of the instruction mnemonic. A comment of
‘ald 7 to AL" after the instruction ADD AL, 07H, for
example, would not tell you much about the function of
theinstruction ina particular program, A more enlightening
comment might be “Add altitude correction factor to
temperature.” Incidentally, not every statement needs an
individual comment. It is often more useful to write a
comment which explains the function of a group of
instructions.
We cannot overemphasize the importance of clear,
concise documentation in your programs. Experience has
shown that even a short program you wrote without
comments a month ago may not be at all understandable
to you now.
CONSTRUCTING: THE MACHINE
CODES FOR 8086 INSTRUCTIONS
This section shows you how to construct the binary codes
for 8086 instructions. Most of the time you will probably
uusean assembler program to do this for you, but itis useful
to understand how the codes are constructed. If you have
‘an 8086-based prototyping board such as the Intel SDK-
86 available. knowing how to hand code instructions will
enable you to code, enter, and run simple programs.8086 Family Assembly Language Programming — Introduction
Instruction Templates
To code the instructions for 8-bit processors such as the
8085, all you have to do is look up the hexadecimal code
for each instruction on a one-page chart, For the 8086,
the process is not quite as simple. Here’s why. There are
32 ways to specify the source of the operand in an
instruction such as MOV CX, source. The source of the
‘operand can be any one of eight 16-bit registers, or a
memory location specified by any one of 24 memory
addressing modes. Each of the 32 possible instructions
requires a different binary cove. IF CX is made the source
rather than the destination, then there are 32 ways of
specifying the destination. Each of these 32 possible
instructions requires a different binary code. There are
thus 64 different codes for MOV insiructions using CX
as asource or asa destination, Likewise, another 64codes
are required to specify all the possible MOVs using CL as
a source or a destination, and 64 more are required to
specify all the possible MOVs using CH as a source or a
destination, The point here is that, because there is such
alarge number of possible codes for the 8086 instructions,
it is impractical to list them all ina simple table. Instead,
‘we use a template for each basic instruction type and fill
in bits within this template to indicate the desired
addressing mode, data type, etc. In other words, we build
up the instruction codes on a bit- by-bit basi
Different Intel literature sows two slightly differeat
formats for coding 8086 instructions. One format is
shown at the end of the 8086 data sheet in Appendix A.
‘The second format is shown along with the 8086
instruction timings in Appendix B. We will start by
showing you how touse the templates shown in the 8086
data sheet.
BYTE 1 I
oleae
\G
aa o1e]e] oToloys els
es
e008 FoR WT t pont sn
INPUTABYTE
o
ADDRESS CONTENTS
oaz05H eH
cuz oon
\ ©
Fig. 3.5. Coding template for 8086 IN (fixed
port) instruction. (a) Template. (b)
Example] (o) Hex codes in sequential
memory locations.
As a first example of how to use these templates, we
will build the code for the IN AL, 05H instruction from
our example program. To start, look at the template for
this instruction in Fig. 3.5a. Note that two bytes are
required for the instruction, The upper 7 bits of the first
byte tell the 8086 that this is an “input from a fixed port”
instruction. The bit labeled “W" inthe template is used to
tell the 8086 whether it should input abyteto AL ora word
to AX. If you want the 8086 0 inputa byte from an 8-bit
port to AL, then make the W bit a0. If you want the 8086
to input a word from a 16-bit port to the AX register, then
make the W bit a 1. The 8-bit port address, OSH or
=n ON
——- REGISTER SELECT (SEE FIGURE 3.7)
On
‘OP CODE
[
NOD] REG | RA
+
|
L
|
Le
DIRECTADORESS |
LOW BYTE,
(6 BITS) ADDRESSING NODE (SEE FIGURE 3.8)
BYTEMWORD DATA 0 = BYTE 1= WORD
DIRECTION TO/FROM REG 0=FROM 1 =TO
OPERATION CODE
DIREST ADDRESS
HIGH BYTE
2
Fg.3.6 Coding template for 8086 instructions which MOV data between registers or between a register
and a memory tocation.









