The 8051 Microcontroller and Embedded Systems Second Edition Muhammad Ali Mazidi Janice Gillispie Mazidi Rolin D Mckinlay

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 136

élE 805£ MICBOCONTROLLEO

AND EMBkDDED SYSTElvlS

Muhammad Ali Mazidi


Janice Giilispie Mazidi

Prentice Hall
Upper Saddle River, New Jerse y Columbus, Ol-io
man's gIor'y lieth in his kncwledge,
his upri@t conduct, his praiseworthy character,
his wisdom, and not in his nationality o¿ rank.

Baha’u'llah
CONTfiHTS AT A GLANCE

CHAPTERS
: ›:itroduction to Computing l
1: ‘‹ne 8051 Microcontrollers 23
2' *.*)51 Assembly Language Programming 35
3i J!›mp, Loop, and Call Instructions 65
4' I *â Port Programming 83
5: i*I5l Addressing Modes 95
6: 'rithmetic Instructions and Programs 109
7. 1-r›gic Instructions and Programs 127
Single-bit Instructions and Programming 143
- timer/Counter Programming in the 6051 157
lG: *.*151 Serial Communication 183
11 Jnterrupts Programmirg 209
12! J’.cal-world Interfacing I: LCD, ADC, and Sensors 235
13: P.cal-wor!d Interfacing II: Stepped Motor, Keyboard, DAC 255
14: *› 151/31 Interfacing to External lvlemory 273
*.t)31/51 Interfacing to the 8255 303

APPENDICES

!•!I S I Instructions, Timing, and Registers 325


’*. IS 1-Based Systems: fi*re-Wrapping ana Testi•s 365
I "I'echnology and System Design Issues 375
D. ! l‹iwcharts and Pse'adocod• “55
'*›tL51 Primer for X86 Programmers 400
F. /\ SCH Codes 401
/\ssemb1ers, Development Resources, and Suppliers 402
H: I data Sheets 404
CONTENTS

CHAPTER 0: INTRODUCTION TO COMPUTING 1


Section 0.1: Numbering and Coding Systems 2
Section 0.2: Digital Primer 9
Section 0.3: Inside the Computer 13

CHAPTER 1: THr. 8051 MICROCONTROLLERS 23


Section 1.1: Microcontrollers and Embedded Processors 24
Section 1.2: Over•ziew of the 8051 Family 28

CHAPTER 2: 8051 ASSEMBLY L.4NGUAGE PROGRAMMING 35


Section 2.1: inside the 8051 36
Section 2.2: Introduction to 8051 Asscmbly Programming 39
Section 2.3: Assembling and Running an 8051 Program 42
Section 2.4: The Program Counter and ROM Space in the 8051 44
Section 2.5: Data Types and Directives 47
Section 2.6: 8fi5 . Flag Bits and the PSW Register 50
Section 2.7: 8051 Register BanKs and Stack 53

CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS 65


Section 3.1: Loop and Jump Instructions 66
Section 3.2: Call Instuctiuns 71
Section 3.3: Time Delay Generation and Calculation 7fi

CHAPTER 4: I/O PORT PROGRAMMING 83


Section 4.1: Pin Description of the 8051 84
Section 4.2: t/O Programming; Bit Manipulation 91

CHAPTER 5: 8051 ADDRESSING MODES 95


Section 5.1: Immediate and Register Addressing Modes 96
Section 5.2: Accessing Memory Using Various Addressing Modes 98

CHAPTER 6: ARITHMETIC INSTRUCTIONS AND PROGM.ivIS 109


Section 6.1: Unsigned Addition and Subtraction 110
Section 6.2: Unsigned Multiplication and Division 117
Section 6.3: Signed Number Concepts and Arithmetic Operations 119
CHAPTER 7: LOGIC INSTRUCTIONS AND PROGRAMS 127
Section 7.1: Logic and Compare Instructions 128
Section 7.2: Rotate and Swap Instructions 134
Section 7.3: BCD and ASCII Application Programs 137

CHAPTER 8: SINGLE-BIT INSTRUCTIONS AND PROGRAMMING 143


Section 8.1: Single-Bit Instruction Programming 144
Section 8.2: Single-Bit Operations with CY 150
Section 8.3: Reading Input Pins vs. Port Latch 152

CHAPTER 9: TIMER/COL'NTER PROGRAh4MING IN THE 8fl51 157


Section 9.1: Programming 8051 Timers 158
Section 9.2: Counter Programming 173

CHAPTER 10: 8051 SERIAL COMMUNICATION 183


Section 10.1: Basics of Serial Communication 184
Section 10.2: 8051 Connection to RS232 191
Section 10.3: 8051 Serial Communication Programming ! 93

CHAPTER 11: INTERRUPTS PROGRAMMING 2fi9


Section 11.1: 5051 Interrupts 21G
Section 11.2: Programming Timer Interrupts 2 i2
Section 11.3: Programming External Hardware Interrupts 215
Section 11.4: Programming the Serial Communication Interrupt 2z3
Section 11.5: Intemipt Priority in the 6051 227

CHAPTER 12: REAL-UfORLD INTERFACING I: LCD, ADC,


AND SENSORS 235
S•etion 12.1: Interfacing an LCD to the 8051 236
Section 12.2: 8051 Interfacing to ADC, Sensors 243

CHAPTER 13: REAL-WORLD IN x ERFACING II: STEEPER MOTOR,


KEYBOARD, DAC 255
Section 13.1: Interfacing a Stepper Motor 256
Section 13.2: 8051 Interfacing to the Keyboard 261
Section 13.3: Interfacing a DAC to the 8051 266
CII A!"I’ER 14: 8051/31 INTERFACING TO EXTERNAL iYIEMOItY 2?3
Section 14.1: Semiconductor *.'cmory 274
Sect.ion 14.2: Memory Address Decoding 284
Section 14.3: 8031/5) iiiiiiffacinh Wlth External ROM 287
Section 14.4: Data Memory Space 292

CHAPTER 15: 8031/51 INTERFACING TO TH “ 8255


Section 15.1: Programming the 8255 304
303
Section 15.2: 5255 Interfacing 312
Section 15.3: Other Modes of the 8255 316

APPENDIX A: 8051 INSTRUCTIONS, TIM1NO, AND REGISTERS 325

APPENDIX B: 8051-BASED SYSTEMS: WIRE-WRAPPIN'G AND TESTING 365

APPENDIX C: IC TECHNOLOCuY AND SYSTEM DESIGN ISSUES375

APPENDIX D: FLOWCHARTS AND PSEUDOCODE 395

APPENDIX E: 8051 PRIMER FOR X86 PROGRAMMERS 400

APPE”NDIX F: ASCI i CODES 401

APPENDIX G: ASSEMHLRS, DEVELOPMENT RESOURCES, AND SUPPLIERS 402

APPENDIX H: D.ATA SHEETS 404


INTRODUCTION
Products using microprocessors generally fall into two categorics. The first
category uses high-performance microprocessors such as the Pentium in
applica- tions where system performance is critical. -We have an entire book
dedicated to this topic, The 80x86 ID.H PC and Compatible Coiiiputei's. Volumes !
and II, froiii Pre:itice Hall. In the second category of applications, perforinarce
is secondary; issues of space, power, and rapid development are more critical thai't
raw process- ing power. The microprocessor for this category is often called a
niicrocontrollei.
This book is for the second category of applications. The 8051 is a
widely used iuicrocontioller. There are many reasons for this, including the
existence of multiple producers and its simple architecture. This book is intended
for use in col- lege-level courses teaching microcontrollers and embedded
systems. It not only establishes a foui‹dation of assembly language programming,
but also provides a
i - comprehensive treatment of 8051 interfacing for engineering students. From this
background, the design and interfacing of microcontroller-based embedded sys-
tems can be explored. This book can be atso used by practicing technicians,
hard- ware engineers, computer scientists, and b.obbyists. It is an ideal source
for those building stand-alone projects, or projects in which data is collected and
fed into a PC for distribution on a network.
Prerequisites
Readers should have had an introductory digital course. Kncwledge of a
programming language u ould be helpful but is not necessary. Although the book
is written for those with no background in assembly language programming, stu-
den.ts with prior assembly language experience •.vill b• able° tO 8alfl a mastery of
8051 architecture very rapidly and start on their projects right away.
Overview
A systematic, step-by-step app:oach is used tu cover vai ious aspects of
505 l Assembly language pi ogramming and interfacing. Many examples and
sam- ple. programs arc given. in clarify the conc•pts and provide students with an
oppoi - trinity to !earn by doing. P.evie questions are provided at the end of each
section to reinforce the main points of the section.
Chapter 0 coveis number sy stems (binary, decimal, and hex), and
provides an introduction to basic logic gates and co:oputer tenninology. This is
designed especially for 5tudent5, Such as mechanical engineering students, who
have not taken a digital logic course or those who need to refresh their memory
‘on these 'opics.
Chapter 1 discusses 8051 history and features of other 805 ! family mem-
bers such as the 8751, 89C51, DS5000, and 8031. It also provides a list of
various producers of 8051 chips.
Chapter 2 discusses the inter nal architecture of the 805! and explains the
use of an 8051 assembler to create ready-to-run programs. It also explores the
stack and the flag register.
tn Chapter 3 the topics of iooj›, junp, and call instructi ›ns are discussed,
* ith many programming examples.
Chapter 4 is dedicated to the discussion nd l/O ports. This allows
students who aro working on a project to start experimenting with 805 I l/O
::1tcrfacing and start the project as soon as possible.
Chapter 3 covers the 905.1 addressing mode.s and explains how to use tlzc
code space of the 805.1 to stole data, as well as ho» to access data.
Chapter 5 is dedicated to aritl inctic ins uctioiis and prograi»s.
Logic instructions and programs are covered in Chapter 7.
In Chapter 8 we discuss one of the most important features of’the 8051,
bit manipulation, as well as stngle-bit instructions of t!:e 8051.
Chapter 9 describes the 5051 timers and how to use theln as event-counters.
Chapter 10 is dedicated to set ial data coniiiiunication of the 805.1 and its
inter facing to the RS232. It also shows 8051 coniiiiunication with COM ports of
the IBM PC and compatible computers.
Chapter 11 provides a detailed discussion of 8051 inter i tipts with many
examples on how to write interrupt handler progi ams.
Chapter 1? shows 8051 inter facing with real- world devices such as
LnDs, ADCs, and sensors.
Chapter 13 shows 8051 interfacing with real world devices such as the
key- board, stepper motors, and DAC devices.
In Chapter 1<. we cover 5031/51 interfacing north external inemoi ics,
both RO*E and RAM.
Finally, in Chapter 15 the issue of adding more ports to the 5031/51 is dis-
cussed, and the interfacing of an 8255 chip with thee microcontroller is co vered in
‹retail.
The appendices have been tlesigned tc pro•'ide al I reference material
required for the topics covered in the book. Appendix A describes each. 8051
instruction in detail, with eKainples. Appendix A also provides the clock count
for insti fictions, 8051 register diagraiiis, and R XM memory maps. Appendix B
describes wire ›vt-apping, and how to design your own 5051 tra'nei boar d based
on 89C51 or DS5tl00 chips. Aopendix C covers IC teclinolo* an«J logic families,
as w'ell as 8G5 ! I/O po:4 intct facing and. lan-out. Fiat e sure you study this before
c‹›n- necting the 8051 to an external device. In Appendix D, the use of tlowcliarts
and psriedocode is explored. Appendix E is for students farri‹liar with x86
arc!.:‹ecture w•ho need to make a re.pid transition to 8051 architecture. Xppcndix
F provides the table for ASCII characters. Appendix G lists resources for’
assembler shareware, and electronics parts. Appendix H cont‹iins data sheets for
the 8051 and other IC chips.
Diskette contents
The disxette attached te the book contain.s the lab iiianual, which has
many experiments for software progratuining and liai'd are interfacing of the
8051 . ’. ! use are in Microsoft Word 97 format. In add:!’ on, the disketle contaiiis
the source code for all the programs in the book fin ASGIi t‹les). Also on the
diskette at c two guides for using 8051 assemblers a.nd simulators from Franklin
Software and Keil Corporation.
Acknowledgments
This book is the result of the dedication and encouragement of many
indi- viduals. Our sincere and heartfelt appreciation goes to all of them.
First, we would like to thank Professor Danny Morse, the most knowl-
edgeable and eKperienced person on the 8051 that we know. He felt a strong
need for a book such as this, and due to his la*k of time he encouraged us to
write it. He is the one who introduced us to this microcontroller and was always
there, ready to discuss issues related'to 8051 architecture.
Also we wou!ci like to express our sincere thanks to Professor Clyde
Knight of Devry Institute of Technology *or his helpful suggestions on the
organ- ization of the book.
In addition, tire following professors and students found errors while using
the book in its pre-publication form in their microcontroller course, and we
thank them sincerely: Professor Phil Golden and John Berry of DeVry Institute
of Technology, Robert Wrightson, Priscilla Martinez, Benjamin Fombon, David
Bergman, John Higgins, Scot Robinson, Jerry Chrane, James Piott, Daniel
Rusert, Michael Beard, Landon Hull, Jose Lopez, Larry Hill, David Johnson,
Jerry Kelso, Michael Marshall, Marc Hoang, Trevor Isra.
Mr. Roiin McKinlay, an eKcellent student of the 8051, made many valuable
suggestions, found many errors, and helped to produce the solution manual for
the end-of-chapter problems. '’é sincerely appreciate his enthusiasm for this
book.
Finally, we would like to thank the people at Prentice Hall, in pai‘ticular our
publisher, Mr. Charles Stewart, who Gontinues to support and encourage our
writ- ing, and our prodiiction editor Alex Wolf who mad• the book a reality.
We enjoyed writing this boot:, and hope you enjoy reading it and using
i1 for your courses and projects. P1•ase !ct us know if’ you have any
suggestions Or find any errors.
Assemblers
The following gives two sites i â‹er•. you can download assemblers:

www.fsinc.com for Franklin Software, Inc.


www.keil.com for Keil Corporation

Another interesting web site is www.5052.com for more discussion on


the iiicrocontroller. Finally, the follo ring site provides useful Intel manuals:

http://developer.intel.com/design/auto/mcs51/manuals
ABOUTTHSAUTHORS
Muhammad Ali Mazidi holds Master's degrees from both Southern
Methodist University and the University of Texas at Dallas, and currcntly is com-
pleting his Ph.D. in the Electrical Engineering Departmcni of Southern Methodist
University. He is a co-foundcr and chief researcliér of Microprocessor Education Group,
a company dedicated to bringing kr.owi•dge of microprocessors to the widest possible
audience. lie also teaches microprocessor-based system dcsign at DeVry Institute of’
4fichnology in Dallas, Texas.
Janice Giilispie Mazidi has a Master of Science degree in Computer
Science from the University of North Texas. After several years experiefice as a software
engineer in Dallas, she co-founded Microprocessor Education Group, where she is the
chief technical writer and production manager, and is responsible (or software develop-
ment and testing.
The Mazidis have been married since 1985 and have two sons, Robert
Nabil and Michael iamal.

The authcrs can be cor‹tacted at the following address if you have any com-
ments or suggestions, or if you find any errors.

Microprocessor Education Group


P.O. Box 381970
Duncanville, TX 75138
U.S.A.

mm.azidi@Tal.‹âevry.edu
This volume is dedicated to the memory of Dr. A. Davoodi, Professor of
p‹ hran L'niversity, who in the tumultuous yea'rs of my youth taught me th.e
importanceof an independent semi ch for truth.. -- Muhammad Ali Mazidi
CHAPTER 0

BNVRODUC&QON TO

OBJECTIVES

*Upon completion of this chapter, you wilt ii• able to:

HH Convert any number from base 2, base 10, or base 16 to any of the
other two bases
Add and subtract hex numbers
Add binary numbers
Represent any binary number in 2’s complement
Represent an alphanumeric string in ASCII code
» Describe logical operations AND, OR, NOT, XOR, NAND, NOPR
Use logic =qates to diagram simple circuits
Explain the difference between a bit, a nibble, a iiyte, and a word
Give precise mathematical definitions of the terms kilobyte, megabyte,
terabyte, and gigabyfe
Explain the difference between RAM and ROM and describe their use
Describe the purpose of the major components of a computer system
List the three types of buses found in computers and describe the
purpose of each ty pe of bus
Describe the role of the CPU in computer systems
List the major components of the CPU and describe the purpose of each
To understanci the soft•ware and hardware of a microcontroller-based sys-
tem, one must first master some yep' bas.c concepts underlying computer
design. Jp {his chapter (which in the tradition of digital computers can be cal/ed
Chapter
0), the fundamentals of numbering and coding systems are presented. After an
introduction to logic gates, an overview of the workings inside the computer is
given. Finally, in the ›asi section we give a brief history of CPU architecture.
Although some reader may .have an adequate background in many of the
topics of this chapter, it is recommended that :h-• material be scanned, however
briefly.

SECTION 0.1: NUMBERING ANO CODING SYSTE74S


Whereas human beings use base 10 (decimal) arithmetic, computers use
the base 2 {binary) system. In this section we explain how to convert from the dec-
imal sys:em to the binay system, and vice versa. The convenient representation of
t . binact numbers, called hex‹!clecimal, also is covered. Finally, the binary format of
the alphanumeric code, called ASCII, is explored.
Decimal and binary number systems
Although there has bed.n speculation that the origin of the base 10
system is tne fact that human beings have 10 fingers, there is absolutely no
speculation about the reascn behind the use of the binary system in computers.
The binary sys- tem is used in computers because l and 0 represent the two
voltage levels of on and off. Whereas in base | Q there are 10 distinct symbols,
S, 1, 2, ..., 9, in base 2 there are only two, 0 and i , with wh.ich to generate
nurrbers. Base 10 contains dig- its 0 through 3; b'nary contain3 digits 0 and 1
on!y. These two binary digits, 0 and
1, are commonly referred t‹a as bits.
Converting from decii11aI to binary
One method of converting from decimal to binary is to divide the decimal
number by 2 repeated I y, kecping track of the remainders. This process continues
unti! the quotient becomes xero. The remainders are then written in reverse order
to obtain the binay’ number i lits is demonstrated in example 0-1.
Example 0-1
Convert 25 0 to binary.

Solution:
Quotient Remainder
25/2 = 12 1 LAB (least significant bit)
12/2 = 6 o
6/2 = 3 o
3/2 = 1 1
1/2 = 0 l MSB (most significant bit)

Therefore, 2510 = I I Gli 1 2.


2
Converting from binary to decimal 4
06831D
To con.vert from binary to decimal, it
1 00
is i:nportani o understand the concept of •xeight 3x 101
- 3
8 = 80
associated with each digit position. First, as an 1 02 =
x - 600
analogy, recall the weight of numbers in the base
6 x i03 - 0 0 00
10 sj stem, as shown in the diagram. By the same
o x lO* = 40000
tokcn, each digit position in a number in base 2
4 x 10* 700000
has a weight associatcd with it: 740683
7 x

1101012 = Decimal Binary


lx20 — 1x1 - 1 1
l
0x2 = 0x2 = 0 00
2
1x2 = lx = 4 100
3
0x2 = 0x% - 0 0000
4
lx2 = lXl6 - 16 10000
1x2* = lx32 = 100000
53 110101

Knowing the weight of each bit in a binary number makes it simple to


add them together to get its decimal equival•nt, as shown in Example 0-2.

Example 0-2
Convcrt 110012 to decimal.

Weight: 16 8 4 2 1
Digits: 1 1 0 0 1
Sum: l6+ 8+ 0+ 0+ l=25l0

Knowing ihe weight associateci with cach binary bit position all ws one
to convert a decimal number to binary directly instead of going through the
process of repeated division. This is shown in Example 0-3.

Example 0-3
Use the concept of weight :o convert 3910 to binary. Solution:

Weight: 32 16 8 4 2 1
1 0 0 1 1 1
32 + 0 + 0- 4+ 2 r I = 39
Therefore, 39;0 = 1001112.

CHAPTER 0: INTRODUCTION TO COMPUTING 3


Hexadecimal system Table 0-1:Base l6
Base 16, the hexadecimal system as it is called in Number Systems
computer literature, is used as a convenient Decimal, Binary
representation of binary numbers. For’ example, it is H 0 0000 0
much easier for a human being to represent a string of 0s 1 0001 1
and ls" such as 100010010110 as its hexadecimal 2 0010 2
equivalent of 896H. The binary system lfas 2 digits, 0 and 3 0011 3
1. The base 10 system has 4 0100 4
10 digits, 0 through 9. The hexadecimal (base 16) system 5 01G1 $
has 16 digits. In base 16, the first 10 digits, 0 to 9, are the 6 0110 6
same as in decimal, and for the remaining six digits, the 7 0111 7
let- ters A, B, C, D, E, and F are used. Table 0-1 shows the 8 1000 8
equip. alent binai'y, decimal, and hexadecimal representa- 9 1001 9
tions *or 0 to 15. 10 1010 A
11 1011 B
. Converting between binary and hex
12 1 00 C
To represent a i›inary number as its equivalent hexa- 13 1 i01 D
decimal number, start from the right and group 4 bits at a 14 1110 E
time, replacing each 4-bit binary number with its hex 15 1111 F
equiv- alent shown in Table 0-1. To convert from hex to
binary, each hex digit is replaced with its 4-bit binary
equivalent. See Examples 0-4 and 0-5.
Example 0-4
Represent binaq• 1001 i1110101 in hGx.

Solution: ' , .. ''


First the number is grouped into sets of 4’ bits: 1001 1111 0101.
Then each group of 4 bits is replaced with its hex
equivalent: 1001 1111 0101
9 F 5
Thcrefore, 100111110 1012 — 9F5 hexadecimal.

Example 0-5
C .ivert hex 29B to biI1'ury.
So!•.ition:
2 9 B
— 0010 1001 1011
Dropping the leading zeros gives 1010011011.
Converting from decimal to hex
Converting from decimal to hex could be approached in two ways:
1. Conven to binaw târst and then convert to hex. Example 0-fi shows this
method of cor.vening decimal to hex.
2. Convert directly from decimal to hex by repeated di ision, keeping track of
the remainders. Experimenting with this method is left to the reader.
Example 0-6 ,
(a) Convert 45 ;0 to hex.

@ 8 4 2 l First, convert to binary.


1 0 1 1 0 1 3 + 8 + 4 + 1 = 45

4S t0 - 0010 I !012 = 2D hcx

(b) Convert 629, to hex.

512 256 128 32 8 4 2 1


1 0 0 1 1 I G 1 0 l

629 _ (512 + 64 + 32 -j- 1.6 + 4 + I) = 0010 0111 01012 — 275 hex

(c) Convert 171410 to hex.

1024 512 256 128 6›4 6 8 4 2 1


1 1 0 1 0 1 1 0 0 1 0

171410 - (1024 + 512 + 128 + 32 + 16 + 2) = 0110 1011 00102 = 6B2 hex

Converting frooi héx to decimal


Ccnversion. from hex to decima! can a!sn b.• approaeh•d in ›wG ways:
1. Convert from Sex to binary and then to decimal. Example 0-7 demonstrates
this method of converting from b.ex to decimal.
2. Convert directly from hex to decimal by summing the weight of all digits.

Example 0-7
Convert the following hexadecimal numbers to decimal.

(a) 6B216 = 0110 1011 00102


1024 512 256 128 64 32 6 8 4 2 1
1 1 0 1 0 1 1 0 0 -1 0

1024 + 512 + 128 + 32 + 16 + 2 = 1714 0

fb) 9F2D = 1001 1111 0010 11012


32768 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1
1 0 0 1 1 1 1 1 0 0 1 0 11 0 l

32765 + 4096 + 2048 + 1024 + 512 + 256 + 32 + 8 + 4 + 1 = 40,749 0

CHAPTER 0: INTRODUCTION TO COMPUTING 5


Table 0-2: Counting in Bases Counting in boses 10, 2, and 16
Decimal Binarv Hex To show the relationship between all
0 00000 0 three bases, in Table 0-2 we s!.cry the sequence
1 00001 1 of numbers from 0 to 31 in decimal, along with
2 00010 2 the equiva- Table 0 - 3: Bina A d tfon
3 00011 3 cnt binary
4 00100 4 and hex A + B Carry Sum
5 00101 5 n u m be rs . 0 + G 0
6 00110 6 cy
Notice i 0 + 1 0
7 00lll 7 each base + 0 0
8 01000 8 that when +1 1 0
9 01001 9 onc wore is
10 01010 added to
11 A
G1011 B the highest digit, that digit becomes zero and a
!2 0110G C 1 is carried to the next-highest digit position.
13 0110 l D For example, in decimal, S + l — 0 with a
14 0! 110 E carry to the r.ext-highest position. In binaty, l
15 01111 F + 1 — 0 with a catry; similarly, in. hex, F + 1
16 10000 10 = 0 with a carry.
!7 10 1 11
18 10010 12 Addition of bi«ary and hex numb•rs
19 10011 i3
20 10100 14 The addition of binary numbers is a
21 l0101 15 very straightforward process. Table 0-3
22 I G110 16 shows the addition of two bits. Ttie discussion
23 10111 17 of sub- traction of binary number s is bypass•d
24 11000 18 since all computers use the addition process to
25 11001 19 imple- ment subtraction. Although computers
26 11010 IA have add•r circuitry, there is no separate
27 110 l l lB circuitry for subtractors. Instead, adders are
28 11100 IC used in con- ju ‹ction with z 's complem .nt
29 1! ! 0i lD circuitry to pel‘- form subtraction. in othe:
0 11110 lE wotds, tO '!npleinent ". - ”, the computer
o1 11 l l l lF takcs the 2’s complement of y and adds it to x.
The concept of 2’s com- plement s reviewed
next. Example 0-8 shows the addition of
binary numbers.
Example 0-8
Add the following binary numbers. Check against their decimal equivalents.

Solution:

Binary Decit ml
! 101 lo 9
+ 1001 22
10110
6
2’s compien1ent
To get the 2’s complement ot’ a binary nuiiiber, invert ali the bits and
then add l to the result. inv•Hing the bits is simply a matter of’ changing all 0s
to 1s and 1s to 0s. Ti:is is catled the 'r complement. See Example 0-9.
Example 0-9
Take thc 2’s complement of l00lll0l.

SOtutiOit:
1001-1101 binary number
01100010 l's complement

01100011 2’s complement

Addition and subtraction of hex numbers


In studying issues related to software and hardware ot’ computers, it is
often necessary to add or subtract hex numbers. Mastery of these techniques is
essential. Hex addition and subtra.ction are discussed separately below.
Addition of hex numbers
This section describes the process of adding hex nun.bers. Starting with
the least significant digits, tlie digits are added together. If the result is less than
16, write that digit as the sum for that position. lf it is greater than 16, si:btract
16 from it to get the digit an‹i carry 1 to the next digit. the best way to explain
this is by
•xaiiip!e. as shC-Nr 'n Examp!e 0-10.

Example 0-10
Perform hex addition.: 23D9 + 94BE.

TO ltltlo11:
23D9 LSD: 9 + 14 = 23 2 - i 6 — 7 witi: a carry
+ 94BE 1 + 13 + 1i — 25 23 - 16 = 9 with a case
B897 1+3+4—8
MSD: 2 + 9 = B

Subtraction of hex numbers


In subtracting two hex numbers, if the second digit is greater than the first,
borrow 16 from the preceding digit. See Example 0-11.
ASCII code
The discussion so far has revolved around the represents.ion of number
ystems. Sir.ce all information in the compiitei i!i ust be represented by 0s and 1s,
binary patterns must be assigned to letters ance ‹other charactcrs. ln the 1960s a
standard representation called ASCII (American Standard Code for Information
Interchange) was established. The ASCII (pronounced “ask-E”) code assigns

U'?APTER 0: INTRODUCTION TO COMPUTING 7


binary patterns for numbers 0 to 9, all the y> ‘szm»i n•x s+-•icéc
letters of the Eng!ish alphabet, both 41 A Gl a
uppercase (capital) and lowercase, and 42 R 62 b
many control codes and punctuation 43 C 63 G
marks. The great advantage of this sys- 44 D 64 d
ten is that it is used by most corr.puters,
so that information can be shared aiiior‹g 59 7V y
computers. The ASCli system uses a 7A z
Y
5A Z
to'al of 7 bits to represent each code. For
Figure 0-1. Selected ASCII Codes
example, 100 0001 is assigned to the
uppercase letter “A” and 110 0001 is for
the lowercase “a”. Often, a zero is placed in the most significant b'i position to
make it an 8-bit code. Figure 0-1 shows selected ASCII codes. A complete list of
ASCII codes is given in Appendix F. The use of ASCII is not only standard for
keyboards used in the United States and many other countries but also provides a
standard for printing ana displaying characters by output devices such as printers
and monitors.
Notice that the pattern of ASCII codes was designed to allow for easy
manipulation of ASCII data. For example, ‹Jigits 0 through 9 are represented by
ASCII codes 30 through 39. This enables a prograln to easily convert ASCII to
decimal by masking off the “3” in. the upper nibble. Also notice th.at tilere is a
rela- tionship between the uppercase and lowercase letters. The uppercase letters
are represented by ASCII codes 41 through 5.4 while lowercase letters are
represent- ed by codes 61 through 7A. Looking at the binary code, the only bit
that is differ- en.I bemeen the uppercas• “A” and lowercase “a” is bit 5.
Therefore, conversion b tween uppercase of 1ow•rcase is as simple as changing
bit 5 ct the /iSCII code.
Example 0-11
Perform hex subtraction: 59F - 2B8.

So!:ition:

59F LSD: 8 from 15 = 7


- 2B8 11 from 25 (9 + 16) = 14 (E)
2E7 2 from 4 (5 - l) = 2

Review Questions
1. Why do computers use the binary number system instead of the decimal sys-
tem?
2. Convert 3410 to binary and hex.
. Convert 1101012 to hex and decimal.
4. Perform binary addition: ! 01100 + 101.
5 Convert 1011002 to its 2’s complement repres‹:ntation.
6. Add 36BH + F6H.
7. Subtract 36BH - F6H.
8. Write “80x86 CPUs” in its ASCII code (in hex form).
8
SECTiON 6.2: GiG!TAL PRliv1ER

This section giv•as an overview of digital logic and design. First, we


cover binary logic operations, tiien we show gates that perform these fiinctions.
Next, logic gates are put together to form simple ‹J}*ital circuits. Finally, we
cover somc logic devices commonly found in microcontroller interfacing.
Binary logic
s -
As mentioned earlier, computers use the 4Logic 1
binary number system because the two voltage lev-
els can be represented as the two digits 0 and 1. 3 —
Signals in digital electronics have two distinct volt- z—
age levels. FGr example, a system may define 0 V
as logic 0 and +5 V as logic l. Figure 0-2 shows this
system with the built-in. tolerances for variations in
the voltagc. A valid digital signal in this example Logic 0
0
should be within either of the two shaded areas.
Fi«qiire 0-2. Binary Signals
Logic gates
Logical AND Function
dinar'y logic gates are simp!• circuits that
take one or more input signals and send out one out- Inputs Out t
put signal. Several of these gates a.re defined below. Xy x AND Y
00 0
A.ND gnte 01 ñ
The AND gat- takes two or more inputs and 10 0
performs a logic AND on them. See the truth table 11 1
and diagram of the AND gate. Notice that if both X AND Y

X inputs to the AND gate are 1, the output will be 1.


Any other combination of inputs will give a 0 output.
The example shows two inputs, x and y. Multiple Logical OR Function

of AND, if all inputs are 1, tne output is 1. If any


input is 0, the output is zero. XY X OR Y
00 0
OR gate
01 1
The OR !ogic function wil! output a 1 if one 10 1
or more inputs is 1. If all inputs are 0, then and only 11 1
then will the output be 0.
— X OR Y
Y
Tri-etc te butter
B‘'ff‘''’
A i>'!ffer gate does not cb.ange the logic level
of t!•.- inpn:. It iS used to isolate or amplify the sig- ity y
na1.
C

CHAPTER 0: INTRODUCTION TO COMPUTING 9


Inverter
The inveHer, also called NOT, outputs the
value opposite to that input to thc gate. That is, a 1
input will give a 0 output, while a 0 input will give
a l output.

FOR gate 0
1 0
The XOR gate performs an exclusive-OF
operation on th• inputs. Exclusive-OR produces a 1 X — NOT X
output if one (but only one) input is ! . lf both
operands are 0, the output is zero. Likewise, if both
Logical XOR Function
operands are 1, the output is also zero. Notice from
the XOR truth table, that whenever the two inputs Inputs Out ut
acre the same, the output is zero. Th.is function can be
used to compare two bits to see if they are the sane. XY X XOR
Y00 0
01 1
NAND and NOR gales 10 1
The NAND gate functions like an AND gate 1 1 0
with an inverter on the output. It produces a zero out- X
X XOR Y
put when all ir.puts are 1; otherwise, it produces a 1 Y
output. The NOR gate functions like an OR gate with
an inverter on the outpvt. It produces a l If all inputs
are 0. Gtherwise, it produces a 0. NAMED and L'OR Logical NAND £ unction
gates are used extensively in digital design because Ji;pu:s
they ar- easy and inexpensive to fabricate. Any cir-
_ fi«'.Pt
cuit that can be designed with .AND, OR, XOR, and X Y X NAND Y
INVERTER gates can be implemented using only 0 0 “i
NAND and FOR gates. A simple example of this is 0 1 1
given below. Notice ir. LAND, that if any input is 1 0 1
zero, the output is one. Notice in FOR, that if any 1 1 0
input is one, the output is zero.
X NAND Y

Logic design using gates


Next we will show a simple logic design to
add two binary dlgits. If we add two binary digits
there are four possible outcomes:
X Y................X. Y. . .
NO.. R.
00 1
Carry Sum 01 0
0+0= 0 0 10 0
0+! = 0 1 i 1 0
! + 0 = 0 1 x X NOR Y
1+ I = 1 0 Y

10 "
Notice that when we add 1 I we get 0 w'ith a car ry io the next higher
place. We wil! i ‹ced to determine the sum and the carty for t!iis design. Notice that
th.e sum column above matches the. output tor the XOR function, and that the carry
column iiiatehes the output for the AND function. Figure 0-3 (a) shows a simple
adder ilnplenienteci witi‹ XOR and AND gates. Figure 0-3 (b) shows the same
logic circuit iliiplemented with .6ñ!D and OR gates.

X Sum

— Cargo
X Carry

(a) Half-Adder *Using XOR and AND (a) Flalf-iidder Using AND, OR, I nvertei s

Figure 0-3. Two Implementations of a Half-Aader

Figure 0-4 shows a block dia-


gram of a half-adder. Two half—adders
x Sum
can be coriibined to form are adder that
Half
can adci three input digits. This is ca!led Adder
a full-adder. Figure 0-5 shows the logic
Carry
diagram of a full adder, along with a out
block diagrams which inasks the details
of the eiicriit. Figure 0-6 sho ws a 3-bit
adder using 3 fit!!-«dders. Figure 0-•!. Brock Diagram of:i iIalf-Arlder

x Half— Carry
r Sum .Adder
r inal
Carry
Sum

— C OUt
Adde “
C Jp. ' Carry

C in
Final Sum

giire 0-5. Full-Adder Built From a Half-Adder

CHAPTER 0: INTRODUCTION TO CONFPIIT NU• 11


Decoders
Another example of the application
of logic gates is the decoder. Decoders are
widely used for address decoding in com- X0 S0
Fuil
puter design. Figure 0-7 shows decoders for Adder
9 (100 I binary), and 5 (0101) using invt•.rt- Y0 c p
ers and AN D gates.

Flip-fIO|gS X1 S1
y1 Full
A widely used component in digital Addei
systems is the flip-flop. frequently, flip- Carry
flops are used to store data. F!gure 0-8
shows the logic diagram, block diagram,
and truth tabie for a flip-flop.
The D flip-flop is widely used to X2 S2
Full
latch data. Notice from the truth table that AdderCarn/
Y2 S3
a D-FF grabs the data at the input as the
clock is activated. A D-FF holds the data
as long as the power is on.
Figure 0-6. 3-Bit ii‹ider Using 3 Full-Adders

LSB LSB

(a) Address decoder for 9 (binary 1001) (b) Address decoder for 5 (binary 0101)
The output of the AND gate will be 1 Tne output of the AND gate will be 1
if and on1Y if the input is binary I 0c"1. if and only if the input is binary 010 I .

Fig:me 0-7. Address Decoders C!U

D Q
No x no change
T 0 0
Clk
Clk 1 1 1
x = don't care

(a) Circuit diagram (b) B!ock diagram (c) ‘1’! utii table

Figure 0-8. D Flip-Flops


Review Questions
1. The logical operation gives a l output when all inputs are 1.
2. The logical opsration gives a 1 output when 1 or iiiore ot its inputs is 1.
3. The logical operation is often used to compare if two inputs have the
same value.
4. A gate does not change thc logic lcvcl of the input.
5. Namc a com mon use loI tlip-flops.
6. An address is uscd to identify a pre-dstennined binary addrcss.

SECTION 0.3: INSIDE THE CO@PUTER

In this section we provide an introduction to the organization and


internal working of computers. The model used is generic, but the concepts
discussed are applicable to all computers, including the IBM PC, PS/2, and
compatibles. Befoi• ernbai king on this subject, it »•ill be helpful to review
definitions of some of the most widely used terminology in computer literature,
such as K, mega, giga, hyte, ROM, MM, and so on.
Some important terminology
One of the most important features of a computer is how much memory it
has. Next we review terms used to describe amounts of memory in IBM PCs and
compatibles. Recall from the discussion above that a Air is a binary digit that can
have the value 0 or 1. A byte is defined as
0
S bits. A nibble is half a byte, or 4 bits. A Bit Nibblc Byte
0000
“r OTC ' S tWO .es, or 16 bits. The display is
0000 0000
intended tc› show the relative size of tb.ese Word 0000 0000 0000 0000
units. If course, they could all be com-
posed of any combination of zeros and
ones.
A kilobyt• is 210 bytes, which is 1024 bytes. The abbreviation K is often
used. For example, some iioppy disks hold 356K bytes of data. A n› gabyte. c‹‘
meg as some call it, is 22 bytes. That is a liitle over 1 million bytes; it is exactiy
1,048,0 76 bytes. Moving rapidly up the scale in size, a gigabyte is 2*0 bytes
(over 1 billion), and a terabyte 1s 24 bytes (over 1 trillion). As an example of
how some of these terms are used, suppose that a given computer has 16
megabytes of mem- ory. That would be 16 x 22 , or 24 x 220, which is 224.
Therefore 16 megabytes is
224 bytes.
Two types of memory commonly used in microcomputers are RAM,
which stands for “random access memory” (sometimes called reafwrite memory},
and ROM, which stands for “read-only mem.ory.” ‘RAM is used by the ccmputer
for temporary storagc of programs that it is running. That data is lost when the
com- puter is turned off. For this reason, RAM is sometimes called volatile
memory'. ROM contains programs and ir,'formation essential to operation of the
computer’. The information in ROM is permanent, cannot be changed by the user,
and is not lost when the power is turned off. Therefore, it is called nonvolatile
memory.
CHAPTER 0: INTRODUCTION TO COMPUTING 13
Internal organization of computers
The internal working of every computer can be‘ broken down into three
parts: CPU (central prccessing unit), memory , and I/O (:•nput/output) devices (see
Figure 0-9). The function of the CPU is to eKecute (process) information stored in
memory. The function of I/O devices such as thc keyboard an‹i video monitor is
to provid- a means of communicating with tF‹ CPU. The CPU is connected to
memory and I/O through strips of› 'ire called a bus. The bus inside a computer
car- ries information from place to place just as a street bus carries pecple from
place to place. In every computer there are three types of buses: address bus,
data bus, and control ous.
For a device (memory or I/O) to be recognized by the CPU, it iiiust be
assigned an address. The address assigned to a given device must be uiiique; no
twc devices are allowed to hav• the same address. The CPU pt:ts the address (of
course, n binary) on the address bus, and the decoding circuitry finds the de ice.
Then the CPU uses the data bus either to get data from that device or to send
daia to it. The control buses are used to provide read or write signals to the
device to indicate if the CPU is asking for information or sending it information.
Of the three buses, the address bus and data bus determine the capability of a
given CPU.
Address Bus

Peripherals
Memory
(monitor, printer, etc.

Figure 0-9: Inside tb.e Computer

More about the Jata bus


Since data buses are used to carry information in and out of a CPU, the
more data buses available, the bener the CPU. If one thinks of data buses as
high- way lanes, it is clear that more lanes provide a better pathway between th'e
CPU and its external devices (such a› printers, RAM, ROM, etc.; see Figure 0-
10). By the same token, that increase in the number of lanes increases the cost of
con struction. More data buses mean a more expensivq-CPU and computer. The
aver age size of data buses in CPU s aries between 8 and 64. Early computers
such < Apple 2 used an 8-bit data bus. while supercomputers such as Cray use a
64-bi data bus. Data buses are .directional, since the CPU must use thera
either t‹ receive or to send data. The l›ocessing power of a computer is related
to the c›izi
of its buses, since an 8-bit bus can send out 1 byte a time, but a 16-bit bus can sen(
out 2 bytes at a time, which is wvice as fast.
14
More about the address bus
Since the address bus is used to identify the devices and meiiiory
connect- ed to the CPU, the more address buses available, the larger the number
of devices that can be addressed. I n other words, the number of address buses
for a CPU determines the number oi’ locations with which.ât can commui:icate.
The nuliibci
of locations is always equal to 2*, wlierc x is the nuintirr of address lincs, lcga b-
less of the size of the data bus. For exaiiiple, a CPU with 16 address lines can
pro- vide a‘total of 65,536 (2 ' ) o:‘ 64K bytes of addr essable ineiiiory. Each
location can have a maximum of 1 byte of data. This is due to the fact thal all
general-pm‘- pose microprocessor CPUs are what is called byte addr essable. As
another exam-
ple, the IBM PC AT uses a CPU with 24 a.ddress lines and 16 data lines. 1 n this
case th• total accessible memory is ! 6 megabytes (224 = 16 megabytes). In this
example there would be 2 4 locations, and since each location is one byte, there
would be 16 megabytes of iiieinory. The address bus is a tiniclii ectional bus,
which means that the CPU uses the address bus on.ly to send out a‹idresses. To
summarize: The total number of ineluory locations addressable by a gi men CPU
is
always equal io 2x where z is the iir:iiiber of address bits, regai'diess of the size of
the data bus.
Address Bus

M ROM Printer Disk Monitor Keyboard


CPU

Data Bus

Read/write
Control Sus

Figure 0-10: Internal Or•qanization of Computers

CPU and its relation to RAl¥i and ROM


For the CPU to process infoi ination, the data must be stor.ed iii RAM or
ROM. The function of ROM in computers is to provide information that is fixed
and permanent. This is information such as tables for character patterns to be dis-
played on the video monitor, or programs that are essential to the working of the
computer, such as programs for testing and finding the total amount ef RA1v1
installed on the system, or programs to display infonration on the video monitor.
in contrast, RAM is used to s:ore info.nation that is not permanent and can change
with time, such as various versions of the ti berating system and application pack-
ages such as '•zord processing or tax calculation packages. These programs are
loaded into RAM to be processed by the CPU. The CPU cannot get the informa-
CHAPTER 0: INTRODUCTION TO COMPUTING 15
tion from J• disk directly since the disk is too stow. In other words, the CPU
gets IN :'-nforrnation to be processed, first from RAi'vt (or ROlvi). Only if it is not
there da, * g CPU seek it from a mass storage device such as a disk, and then it
trans-
*era ‘be information to RAM. For this reason, RAM and ROM are sometimes
refe, r V› us primary memory and disks are called secondary memory. Figure 0-
i I ›hov.. a block diagram of the internal organization of the PC.
Insid° C. Lis
/- program stored in memory provides instructions to the CPU io
perform J›• o. The action can simply be adoring data such as payroll data
or control-
ling a rrivhine such as a robot. It is the function of the CPU to fetch tiiese instruc-
*irons frrim memory and eKecute them. To perform the actions of fetch and
execute, od CPf/s are equipped with resources such as the following:

foremost among the resources at the disposal of the CP'J are a number of reg-
i. l‹.•rs. The C.*U uses registers to store information temporarily. The
informa- tion could be two values to be processed, or the address of the value
needed to be fetched from memory. Registers ins'de the CPU can be 8-bit,
16-bit, 32-bit, '›t c’ en 64-bit registers, depending on the CPU. In general, the
more and big- Dyer the registers, the better the CPU. The disadvantage of more
and bigger reg- i.sk:re is the increased cost of such a CPU.
‘the CPU also has wb.at is called the ALU (arithmetic/logic unit). The ALU
cation of the CPU is responsible fr›r performing arithmetic functions such as
id, subtract, multiply, and divide, and logic functions su*h as AND, OR,
and

J(Very CPU has what is called a program counter. The function of the
program c‹iunter is to point to the address of the n•xt instruction to be executed.
As each instruction is executed, the program counter is incremented to
point to the
•!! âtess of the next instruction to be executed. I: is the contents of the
program c• Hunter that arc placed on the address bus to find and fetch the
desired instruc-
/i.›n. In the IBM PC, the program counter is a register called iP, or the
insir.ic- 1.ion pointer.
4.
’l'he function of the instruction decoc!er is to interpret the instruction fetched
into the CPU. On• can think of the instruction decoder as a kind of
dictionary,
'storing the meaning of each instruction and what steps the CPU should take
upon receiving a given instruction. Just as a dictionary requires more pages
the more words it defines, a C.°U capable of understanding more instructions
requires more transistors to design.
Internal working of computers
To demonstrate some of the concepts discus“sed above, a step-by-step
"analysis of the process a CPU would go through to add three numbers is given
next. Assume that an imaginary CPU has repl sters called A, B, C, and D. It has
an
$-bit data bus and a l6-bit address bus. Therefore, the CPU can access memory
ffom addresses 0000 to FFFFH (for a total of 10000H locations). The action to be
QCrfprmed by the CPU is to put heKadecimal va!ue 21 into register A, and then add
to register A values 42H and 12H. Assume that the code for the CPU to move a
x'alue to register A is IN 11 0000 (BOH) and the code for adding a vaiue to
register A is 0000 0100 (04H). The necessary step• and code to perform them are
as UI- lOwS.

Action o‹fe Oa£a


Move value 2lH into register A BOH 2lH
Add value 42H t register A 04M 42H
Add value 12H to register A 04H l2H

It the program to perform the actions !isted above is stoled in memory


locations starting at 1400H, the following would represent the contents for rach
memory address location:

Meadow” adoess Co.-ztezzt:s o:€ zae»ao:z:-y add:z:eaa


140G ( O)code for moving a value to register A
1401 (2l)value to bc moved
1402 (O4)code for adding a value to register A
1403 (42)value to be added
1404 (04)code for adding a value to register A
1405 (12)value to be added
1405 (F4)code for halt

The actions perfonned by the CPU to run the program above would be as
follows:
1. The UPU's program count•r can have a value between 0000 and FFFFH. The
program counter must oe set io the value 1400i-I, indicating the address of
the tirst instruction cGde to be executed. After the pt ogram counter has been
loaded wi.h the address of the first instruction, the CPU is ready to execute.
2. The CPU puts l400H on the address bus and semis it out. The memory cir-
cuitry finds the location while tne CPU activates the READ signal, indicating
to memory that it wants the byte at location 1400H. This causes the contents
of memory location 14G0H, which is BG, to be put on the data bus and
brought into the CPU.
3. The CFU decodes i:le instt uction B0 with the help of its instruction decoder
dictionary. When it finds the definition for that instruction it knows it must
bring into register A of the CPU the byte in the next memory location.
Therefore, it commands its control!er circuitry to do exactly that. When it
brings in value 21H from memory location 1401, it makes sure that the doors
of all registers are closed except register A. Therefore, when value 21H comes
into the CPU it wiil go directly into register A. After completing one instruc-
tion, the program counter points to the address of the next in.struction to be
exe- cuted, which in this case is i 402H. Address 1402 is sent out on the
address bus to fetch the next instruction.
4. From memory location 1402H it fetches code 04H. After decoding, the CPU
kno that it must add to the contents of register A t!i byte sitting at the nex:
address (1403). After it brings the value (in this case 42!I) into the CPU, it
pro- vides the contents of register A along with this value to the ALU to
perform the addition. It then takes the result of the addition front the ALU's
output and

CHAPTER 0: INTRODUCTION TO COMPUTING 17


puts it in register A. Meanwhile the prograip counter becomcs 1404, the
address of the next instruction.
5. Address 1404H is put on the address bus and the code is fetched into the CPU,
decoded, and executed. This code is again adding a value to register A.
The program counter is updated to 1406H. _
5. Finally, the contents of address 1406 are fetched in and executed. This
HALT instruction tells the CPU to stop increnientiiig the program counter
and asking for the next instruction. In the absence of the HALT, the CPU
would continue updating th.e prcgram counter and fetching instructions.
How suppose that address l403N contained value 04 instead of 42H.
How would the C.°'J distinguish between data 04 to be added and code 04?
Reiueinber that code 04 for this CPU means move tire next value into register
A. Therefore, fi.e CPU will not try to decode the next value. It simp!y moves
the contents of the followin3 memory location into register A, regardless of its
value.

Program Counter

Flags Instniction Register


ALU Instruction decoder. t:rr.ing, and control

Internal buses

Contr
Pip•ure 0-11: Internal Block Diagram: of a CPU
Wu

Review Questions
How many bytes is 24 kilobytes?
s

2 What does “RAM” stand for? HOw !s it used in computer systems?


*. \Vhot does “ROM” stand for? How is it used in co!^n outer systems?
- Win› is RAM called volatile memory?
a. List the three major components of a computer system.
6. What does “CPU” stand for? Explain its function in a computer.

18
7. h ist :he tlwee types of‘ btises found in computer systems atid state briefly the
purpose of each type of btis.
8. State which of” the following is unidi› cctional and which is bidirectional.
(a) data bus (b) address bus
9. If an addr ess btis for a gi'zen computer has 16 lines, what is the inaximuiii
fl1T1Oli!*.t ot’ r.ienaory it can access ?
10. What docs “A CU” stand for'? What is its purpose’?
1.1. !4ow ai e registers used in eoiiiputer systems?
1.2.What is the ptli pose of the prograiii counter?
1 u. What is the pu1 pose of the instruction decoder?

SUMh1ARY

The binary number system represents all nuiiibers with a coiiibination of


the two binai‘y digits, 0 and 1. Tire use of binary systems is nccessaiy in digital
coinptiteis because only two states can be represented: on or off. Any binary num-
ber can be coded directly into its hexadecimal equivalent for the convenience of
humans. Converting from binary/hex to decimal, and vice hers*., !s a straightfor-
ward process that becomes easy with practice. The ASCI I code is a dinary code
used to represent alphanumeric data internally in the computer. it is frequently
used in periphera! devices for input and/or eutput.
The loSiC gates AND, OR, and Inverter are the basic building blocks of
simple circuits. NAND, NOR, and XOR gates are also used to implement circuit
design. Diagrams of half-adders and full-adders were given as examples of the
use of logic gates for circuit design. Decoders are tised to detect certain
addresses. Flip-fiops are used to !a(ch iri data unt!1 Gthei circuits are ready for
it.
The major components of any computer system are ihe CP'N, memory,
and I/O crevices. “Memory” refers to temporary or permanent storage of data. In
most systems; memory can be accessed as bytes or words. The tends kilobyte,
megabyte, pigabv/c, and terabyte are used to refer to large numbers of bytes.
There are two main types of memory in computer system.s: RAM and ROM.
RAlv! (i‘an- dom access nieluol'y) is usea for temporary storage of pro3:’ams and
data. ROM (read-only ic•.!J.O!’y) ‹s used for permanent storage of programs and
data that the coinptttet system. must have in order to function. All components c›
tire computer system are under the control of the CPU. Peripiheral devices such
as I/O (input/out- put) devices allow the CPU to conimrir icate with humans or
othet‘ computei sys- tems. There ate three types of buses in computers: address,
control, and data. Control btises are used by the CPU to direct other devices. The
address bus is used by the CPU to locate a device or a memory location. Data
buses are used to subnet infonration back and forth between the CPU and other
devices.
Finally, this chapter gave an overview of digital logic.
CHAPTER 0: INTRGDUCTION TO COMPUTING 19
PROBLEl¥iS
SECTION 0.1: NUMBERING AND CODING SYSTEMS

1. Convert the following decimal numbers to binary.


(a) 12 (b) 123 (C) 63 (d) 128 fe› 1000
2. Convert the following binary numbers to decimal.
(a) 100100 (b) l G00001 (c) 11101 (d) 1010 (e) 001000!0
3. Convert the values in Problem 2 to hexadecimal.
4. Con.vert the following hex numbers to binary and decimal.
(a) 2B9H (b) F44H (c) 912H (d) 2Bd (e) FFFFH
5. Convert the values in Problem l to
6. Find the 2’s complement of the follows.g• binary numbers.
(a) 1001010 (b) 111001 (c) 1000WJl0 (d) 11111000 1
7. Add the following hex valucs.
(a) 2CH+3 FH (b) F34H+5D6Fi (c› ?0000H+ 12FFH (d) FFFFH+2222H
S. Perform hex subtraction for the folio •ânp.
(a) 24FH- l 29H (b) FE9H-5CCH (c) 2FFFFII-FFFFFH (d) 9FF25
H- 4DD99H
9. Show the ASCII codes for numbers 0. I. 2, 3, ..., 9 in both hex and binary.
10. Show the ASCiI code (in hex) for ter following string:
“U.S.A. is a country” CR,LF
“in worth Am•rica” CR,LF
CR is carriage return
LF is line feed

SECTION 0.2: DIGITAL PRIIvIER

11. Draw a 3-input OR gate using a 2-input OR gate.


! 2. Show the truth table for a 3-input OR rate.
13. Draw a -input .AND gate using a 2-:nput AND gate
14. Show tire truth table for a 3-input .AND gate.
15. Design a -input XOR gate with a 2-input XOR gate. She ' $ .D i’U h (able
for a 3-input XOR.
16. List the truth table for a 3-input fi.ID.
17. List the truth table for a 3-input NOT.
18. Show the decoder for binary 1100.
19. Show the decoder for binary 11011.
20. List the truth table for a D-FF.

SECTION 0.3: INSIDE THE

COFJPUTER

21. .Answer the following:


(a) How ma: i; nibbles are 16 bits?
(b) Ho many bytes are 32 bits?
(c) If a word is defined as 16 bits, how many words s a 64-bit data item?
(d) What is the exact value (in decimal) of l meg?

20
(e) flow many K is 1 inc3?
(f) What is the exact value (in decimal) of i s'ga?
(g1 How many K is 1 giga?
(h) How many meg is 1 giga?
(i) If a given computer has a total of 8 megabytes of in•1uory, how many
bytes (in deciiiial) is this?• How iTlany kilobytes is this?
22. A givcn mass storaSC devic• such as a hat d disk can stoi e 2 Sigabytcs o I in.for-
mation. Assuiiiing heat each page of text has 25 rows and each low has 80
columns of ASCI I characters (each character = I bytc), approximately how
many pages of information can this disk store?
23. In a given byte-addressable computer, memory locations 10000i-i to
9FFFFH are available for user programs. The first location is l0000H and
the last loca- tioils 9FFFFH. Calculate the followiiig:
(a) The total number of bytes available (in decimal)
(b) Thc total number of kilobytes (in decimal)
?4. A given computer has a 32-bit data bus. What is the largest number that can
be carried into the CPU at a time?
25. Oe[ow are listed several computers with their data bus widths. For each com-
puter, list the maximum value that can be brought into the CPU at a tilue (in
both hex and decimal).
(a) Apple 2 with an 8-bit data bus
(b) IBh4 PS/2 with a 16-bit data bus
(c) IBM PS/2 model 80 with a 32-bit data bus
(d) CRAY supercomputer with a 64-bit data bus
26. Find the total amount of memory, in the •anits requested. for ach of th• fol-
1c›wing CPUs, given the size of the address buses.
(a) 16-bit addi‘ess bus (in Yr}
(b) 24-bit address bus (in meg)
(c) 32-bit address bus (in megabytes and giga.bytes)
(d) 48-bit address bus (in megabytes, gigabytes, and terabytes)
27. Regarding the data bus and address bus, '+h'c!i is unioirectional and which is
bidirectional?
2+. ’Vhich register of the CP'N holds the address of the instt uction to be fetched?
2<. Whicn section of the Ci'U is responsible for performing addition?
30. List the three bus types present in every CPU.

ANSWERS TO REVIEW QUESTIQNS


SECTION 0.1: NU.\’.BERING AND CODING SYSTEMS
1. Computers use the binary systeln because each bit can have one of’ two voltage levels: on and
off.
2. 34 } (j 1000 l0z' 2/ } §
3. 1101012 ' J516' 5J i o
4. 1110001
5. 010100
6. 461
7. 275
8. 38 30 78 38 36 2fi 43 50 55 73

CHAPTER 0: INTRODUCTION TO COMPUTING 21


SECTION 0.2: DIGITA U PRI M EP.
1. AND 2. OR
3. XOR 4. l3ulTcr
5. Storing data
6. Decoder

SECTION 0.3: INSIDE THE CO11PUTEIt


I . 24,576
2. Itandom access memory; it is uscd for temporary storage of programs that the. CPU is i
un- ning, such as the operating systcm, word processing programs, etc.
3. Read-only mumory; it is used for permarcr‹t programs such as those that control thc kcyhoerd,
ctc.
4. Tb.e contents or PAhfi are lost ivhei: the computer is powered off.
5. The CPU, memory, and l/O devices
6. Central processing unit; it can be considered the “brain” of the computer; it executes the pro-
grams and controls aI1 other devices in the computer.
7. The address bus carries the location (address) needed by the CPU; the data bus carries infor-
mation in and out of the CPU; the control bus is used by the CPt to send signals controlling
I/O devices.
S. (a) bidirectional (b) unidirectional
9. 64K, or o5,536 bytes
10. Arithmetic/logic unit; it performs all arithmetic and logic operations.
11 . It is for temporary storage of infomiation.
! 2. It holds the address of the next instruction to be executed.
13. It tells the CPU what steps to perform for each instruction.

22
CH.4PTER 1

THE
RICRO6OHTRObLERS

OBJECTIVE 23
S

Upon completion of this ci:apter, yoti wiil be able to:

Compare and contrast micr‹iprocessors and microcontroiicrs


Describe the advantages of microcontrollers for some applications
Explain the concept of embedded systems
Discuss criteria to consider in choosing a microcontroller
Expla:•n the variations of speed, packaging, memory, and
cost per unit and how these affect choosing a
microcontroller
Compare and contrast the various members of the 8051 family
Compare 8051 microcontrollers offered by various manufacturers
This chapter begin.s witfi a discussio:i of the role and iiriportance of micro-
controllers in everyday life. In Section 1.1 we atso discuss criteria to consider in
choosing a microcontroller, as well as the use of microcontrollers in the embed-
ded market. Section 1.2 covers various members of the 8051 family such as the
8052 and 8031, and their features. In addition, we discuss varior›s versions of
the 5051 such as the 8751, AT69C5 1, and DS5000.

SECTION 1.1: MICROCON I ROLLERS ANO EMBEDDEG


PROCESSORS

I n this section. we discuss the need for microcontrollers and contrast


them with general-purpose microprocessors such as the Pentium and other x86
micro- processors. We also look at the role of microcontrollers in the embedded
market. In addition, we provide some critc•ria on how to choose a
microcontroller.
Microcontroller versus general-purpose microprocessor
What is the difference between a lnicroprocessor and microcontroller?
By microprocessor is meant the general-purpose microproc•ssors such as Intel's
x86 family (5086, 80286, 80386, 80456, and the Pentium) or Motorola's 680x0
fami-
ly (6800G, 68010, 68020, 68030, 68040, etc.). These microprocessors contain
no RAM, no ROM, and no I/O ports Gn the chip itself. For this reason, they are
com- monly referr•d to as general-purpose microprocessors.

data bus
c.»u ROM
Figure 1-1. Microprocessor System
I Contrasted With Microcontroller System
General- Purpose h4icro- processor Serial
A system designerRC›M using a general-purpose
I/O Timer microprocessor such as the
COM
Pentium or the 68040 must add RAM, °ort ROI›4, I/O ports,
Port and tin.ers
I/Oexternally
Timer toSerial
make them functional. Although the addition of external RAM, ROM, and UOCOM
ports makes these systems bulkier and much more expCnsive, they have thePort
Address be..
advan- tage of versatility such that the designer can decide on the amount of
RAM, ROM, and I/O Microprocessor
(a} General-Purpose Syst•ln
ports needed to fit the task at hand. This is not the case
(b) filicrucontroller
with microcon- trollers. A microcon'rolier has a CPU (a microprocessor) in
addition to a fixed amount of RAM, ROM, I/O ports, and a timer all on a single
chip. In other words, the processor, the RAM, ROM, I/O pori and timer are all
embedded together on one chip; therefore, the designer cannot add any external
memory, I/C›", or timer to it. The fixed amount of on-chip ROM, RAM, and
number of I/O ports in micro- controllers makes them ideal for many
applications in which cost and space are

21
critical. In rivalry app!ications, for exaiiiple a I V retinoic control,
Home there is no need for the computing power of a 486 or cvcn an 5086
in icroprocessor.
Appliances In.tercom 7elepficrics Security systemsln man.y applications, the space it takes, the
garage door openers 9o› 'ei it consumes, and the price per unit are liiuch more critical
^.nswci ing machines Fax machines
consideratioiis than the computing power. These applications
Jomc computcrs most often require some I/O operations to 1 ead sisnals and turn on
rv and olT cci tail hits. Foi this rcasoi sowc call thcsc processoi's
Cable "IV tuner I Fi P. “itty-bitty processors” (see “Good Things in Siua!1
VCR
Packages
Caiizcorder
.AiCellt!1ar
R-smote controls Video games e Generating
phonesBig Product
ivlusical Opportunities”
instruments by MickLighting
Se ’ing machines Gi ehan,
control Paging
Camera B5 TE iiiagazine, September 1994; www.byte.coin, loi an excel-
Pinball machines Toys lent discussion of !*iicrocoi‘itrollers).
Exercise equipment lt is interesting to note that solne liiicl ocontroller rrianu-
' factuiers have gone as far as i›ritegrating an A DU (analog-to-digi-
tal co‹ivei ter) and other per iphe:als ilito the microcontroller‘.
Microcontrollers for emb dded systems
In the literature ‹discussing iiiicroprocessors, we often
see the term embedded syster.i. Microprocessors and
microcontrollers ate « idely used in embedded system products.
An embedded pioduct uses a microprocessor (or microcontroller)
to do one task and one task only. A printer is an example of
•mbedded system since the pi'ocessor inside it perforiiis one ta'sk
office only; namely, get- ting the data and printing it. Contrast this with
Telephones Computers a Pentium-based PC (or any x86 IBM-compatible PC). A PC can
Seeul itj‘ s3'stems be used for any number of applications such as woitl proc•ssor,
Fax i.iochine Microwave Cop‹er print-server, bank teller t•rminal, video game player, networx
Laser printer Color print•: Paging
! scrver, or internet ter- normal. Software for a variety of
applications can be loadcd and run Of coursc (he reason a PCB
can perform myriad tasks is that it has PROM memory and an
operating system that loads the appli- cation software into RAM
and lets the C.*U run it. In an eibed- cued s;•sterr., there is Gr.1y
oxic application software that is *ypical- ly burned into ROM. .In
Auto
xS6 PC contains or is connected to c.r- iots er.ibedded products
i rip computer Engine control Air bag
ABS such as the keyboard, printei‘, modem, disk controller, sour.d
Instrumentation Security system card, CD-ROMcontrol
Transmission driver, mouse, and
Entertainment so on.
Climate Each
control one phone
Cellular of these
Keyless entry
peripherals has a inicrocontro! er inside it that performs only one
task. For example, inside every mouse there is a inicrocontroiler
to perform the task of finding the mouse posi- tion and sending ii
to the PC. Table l -1 lists some embedded products.

X86 PC embedded applications


Although microcontroller‘s are the preferred choice for
Table 1-1: S‹::ue many embedded systems, there are times that a microcontroller is
Embedded P i’t›ducts inadequate for the task. ror this : Mason, in recent years many
Usi g i‹ianufacturers of general-purpose iiiicropiocessors such as lntel,
Microcontrollers Motorola, AMD (Advanced Micro Devices, Inc.), and Cyrix
(now a division of National Semiconductor, Inc.) have targeted

CHAPTER 1: THE 8051 MICROCONT OLLERS 25


their microprocessor !or the high end of the embedded market. While Intel,
A1€G, and Cyrix push their x86 processors for both the embedded and desk-top
PC mar- kets, Motorola is determined to keep the C›8000 family alive by
targeting it main- ly for the high end of embedded systcms now that Apple no
longer uses the 680x0 in their Macintosh, In the early 1990s Apple computer
began using Power PC naici oprocessors (604, 603, 620, etc.) in place of the
680x0 for the Macintosh. The Power PC microprocessor is a ioint venture
between 1 BM and Motorola., and is targeted for the high end of the embedded
iiiarket as well as the PC market. lt must be noted that when a coiiipany targets a
general-purpose mici oprocessor for the eni bedded market it optiinixes th‹•
processor used *or embedded systems. For this reason these processors are often
called high-end eofbeddedprocessors. Very often the ter ins embedded firocessor
and microcontroller are used interchangeably.
One of the most critical needs of an eiiibedded system is to decrease
power consumption and space. 3“his can be ach•eved by integrating more
functions into the CP U chip. All the eiiibedded processor s based on the x86 and
680x0 have low power consumption in addition to some for us of [/O, COM
port, and ROM all on a single chip. In high-performance embedded processor s,
the trend is to intesrate
inoi e and more functions on the CPU chip and let the designer decide which fea-
tures he/she wants to use. This trend is invading PC system design as well.
Nor really, in designing the PC motherboard we need a CPU plus a *hip-set con-
tai!iing I/O, a cache controller, a flash RO41 containing BIOS, and finally s sec-
ondary cache memory. New designs are en‹ei‘g. rig in industry. For example,
Cyrix has ana.ounced that it is working on a chip that contains the entire PC,
except for DRAM. In other words, we are about to see an entire computer on a
chip.
Currently, because of MS-DOS and fi'indows standardization many
embedded systems are using xS6 PCs. In litany cases using x8ñ .*Cs for the high-
end embedded applications nGt orily saves money but a!so shortens development
time since there is a vast Library of sotiware already written for the DOS and
Windows platforms. The fact that Windows is a widely used and well understood
platfoi in means that developing a Windows-based embedded product reduces the
cost and shortens the de‘ve[opircnt time cG:is idciably.

Choosing a microcontroller
The:’e- are four major 8-bit nici‘ocontt’olleis. They are: Motorola's 6811,
Intel’s 8051, Zilog's ZS, and PIC l 6X front Microchip Technology. Each of the
abovc iriicrocontiollers has a unique inst1‘uction set and register set; therefore,
they are not compatible with each other. Programs written for one will not run on
the other s. There are also 16-bit and 2-bit microcontrollers made by various chip
makers. With all these differ ent na ict'oconti ollers, what criteria do designers
con- sider in choosing one? Thi'ee criteria in choosing m ici otontrollers are as
follows: l ) meeting the computing needs ot the task at hand efficiently and cost
effective- ly, (2) availability of software development tools such as compilers,
asseiiible.rs, and ‹!ebuggei s, and (3) wide availability ‹ilJd relial › c sources of
the inicrocon- trol lci Next we elabot ate fair ther on each o1 the abo c critei ia.
26
Criteria for choosing a microcontro!Ier
I. 1"hc fiist and rorcnzost ct itcrioiz in choosing a mici oconti ollcr is that it must
mcct thc task at hand efficiently and cost cftfictivcly. In analyzing the nccds of
a microcoi trullcr-based projcct, we must fiist sce wlzcthci ai› g-bit, 16-bit, or
32-hit microcontt ollci can bcst handle the computing nccds of tl c task most
(just j'y |y. A i11rH1 otl1CI Col1SIdCratIOilS Il1 tl1I S CatCL',OI y alC:
(a) Speed. Wh:•t is the highest speed tizat the n iciocoiztrollci sup/ooi Is?
(b) Packaging. Docs it conzc its 40-pin DIP (drtt‹l ii linc package) or a QFP
(qtiad 11a: pac!:i1Je), or sonic other packaging for iiiat? This 's ilTlportant in
ter:iis of” spc‹ce, asseiTlbling, and prototyping the child p'odticl.
(c) Power consumption. This is especially critical for battery-powered plod-
ucts.
The aiiiount of‘ RAM and ROM on chip.
3“1ie nun er of i/O pins and the tinier on tlic chip.
How casy it is to upgrade to higher-per for mance Gr lower power -con-
sriiiiption versions.
(g) Cost per’ unit. This is important in terms of the final cost of the product in
which a lnicrocontrollei is used. For example, there are ir icrocontrollers
that cost 50 cents per unit when purchased 100,000 units at a tiiiie.

2. The second criterion in choosing a microcontroller’ is how easy it is to ‹devel-


op products ai ound it. Key considerations include the availability of an assem-
bler, debug3er, a code-efficient’C language compiler, emulator, iechnical sup-
por, and both. in-house and outside expertise. In many cases, third-party ' ei-
der (that is. a supplier other th.an th. chip manufacturer) support for the chip is
as 3ood as, if not bett•r than, .support from the. c.hip ir'anufacturer.

3. The third critel ion in choosing a microcontroller is its ready availability in


needed qrlaniities both now and in the future. For sortie des gners this is even
moi e iirponant than the first two criteria. Cui iently, of the leadin* *-bit micro-
coin: oller s, the 8051 family has the largest number of diversified (multiple
sotii'cc) stippliets. By supplier is rn.ean: a produce! besides the oi iginatoi of
the
Table 1-2: Some Coii•. panies Producing a Member of Inlci oconti oller. In the
case the 8051 Family O C 5051, which was oi'ig-
inated by Intel, several com-
Company _ Web Site __ panies also cuti“ently pro-
Intel www.intel.com.'design/mcs51 duce (or have produced in
Atmel www.atinel.com the past) the 8051. These
Philips/Signetics www.semiconductors.philips.coin cont.panies include: Intel,
Siemens www.sci.sieinens.com Atiiiel, Philips/Signetics,
Dallas Semiconductor www.dalsemi.com AMD, Si0!iiens, lvlati a, and
Dallas Semiconductor.
lt she:!!d be noted that Motorola, Zilog, and Mici oc! i i Technol sy have
‹•l i ded lcater: massive resources to ensui‘e wide and t.1tiiely .c. ailability of their
pt oduct since their product is stable, mature, and single so:!rced. In rec•nt years
they also have begun to sell the ASIC library cell of the inici oconti oller.

CHAPTER 1: THE 8051 MICROCONTROLLERS 27


Review questions
l. True or false. Microcontrollers are i1ui’mally less expensive than microproces-
SOBS.
2. When comparing a syst•m board based on a microconti uller and a general-pur-
pose microprocessor, which one is cheaper? -
› A ir icrocontroller nominally !•.*.s which of the following devices on-chip?
(a) kAM (b) ROM (c) l/O (d) all of the above
4. A general-purpose microprocessor noonio I I y needs which of the following
devices to be attached to it?
(a) FtAM (b) RGM (c) l/O (d) all of the above
5. An embedded system is also called a dedicated systems. Why?
6. fi*1iat does the term embedded system mean?
7. \Vhy does having multiple sources of a given product matter?

SECTION 1.2: OVERVIEW OF THE 8051 FAMILY

In this s•.ction we first look at the various members of the 805 i family of
microcontrollers and their internal features. Plus w'e see who are the different
man- ufacturers of the 8051 and what kind of products they offer.
.4 brief history of the 8051
In l fi81, Intel Corporation introduced an 8-Sit microcontroller called the
8051. This microcontroller had 128 bytes of RAM, 4K bytes of on-chip ROM,
two timers, one s@ ial port, and four ports (eash S-bits wide) all on a single chip. At
thee i'm• it v.as a!so referred to ms a “system on a chip.” The 8051 is an 8-oit
proces- scr. meaning that the CPU can work on only 8 bits of data at a time. Data
larger than 8 bits has to be broken into S-bit pieces to be processed by the CPU.
The 8051 has a total of four I/O ports, each 8 bits wide. See Figure 1-2. Although
the 805 l can laave a maximum of 64K bytes of on-chip ROM, many
manufacturers have put o!‘.ly 4K by*es on th• chip. This will be discrissed in
more detail later.
TU.e 8051 became widely popular after Intel allowed other manufacturers
to make and ir.at ket any fiiavor of the 5051 they piease with the condition that
they reinaln code-compatible with. the 8051. This has led to :iiany vei'sions of
the 8051 with different speeds and amounts of on-chip ROM marketed by more
than half a dozen manufacturers. Next we review some of them. It is important
tO ilote that
although there are different flavors of the 8051 in terms Table 1-3: Features of the 8051
ot speed and amount of on-cfiip ROM, they are all com-
patible with the or iginal 8051 as far as the instructions Feature Quantity
are concerned. This means that if you write your ROM 4K bytes
program for one, it will run on any one of them RAM 128 bytes
regardless of the man- ufactui er. Timer 2
I/O pins 32
8051 microcontroller Serial port l
Tire 80 1 is the original member of the 8051 Ir‹ic! rupt sources 6
Note. ROM amount indicates on-chip
fam- ily. Intel refers to it as MCS-51. i able 1-3 shows program space.
the main features of the 8051.

28
EXTERNAL INTERRUPT S

ON-CHIP ROM
Y Y for program code
INTERRUPT ——— ON—CHIP RAM ETC.
CONTROL ” TIMER 0
TIIV!ER 1 -<

CPU “

BUS 4 IO SERIAL
OSC CONTROL PORTS . ORT

COUNTE
TXD RXD
P0 P1 P2 P3

ADDRESS/DATA

Figure 1-2. Inside the 8051 iYIicrocontroller Block Diagram

Other mem!aers oT the 8051 family


i h•re are two other numbers in the 8051 lamiiy o »tcrocontiG1! s.
They are the 8052 and the 80.1.

INPU
8052 microcontroller
The .°.052 is another irembei of the 805 i family. Thc 8052 has all the
s:an- dard featui'es of the 8051 in addition to an extra 12° bytes of RAM c.nd an
extra timer. In otfiei‘ words, the 8052 has 256 bytes of RAT* and 3 tii-crs. It a!so
has 8K bytes of on-chip progi'am RO›Vi instead of oK bytes. See t aS!c 1-4.
Ta'ole 1-4.: Com arison of 8051 FamilMembers

at! prograiiis ’ritten to’ the 8051 will run on the 8052, but the i ever se is not true.

CHAPTER 1: THE 8051 MICROCONTROLLERS 29


8031 microcontroller
Another iiiember of the 6051 tâmily is the 8031 chip. This chip is often
referred to as a ROW.4-less 801.1 since it has 0K bytes of on.-chip ROM. To use this
ch!p you must add external ROM to it. This external ROM must contain the
pro- gi am that t!ie 8031 will 1“etcli and execute. Contrast that to the 8051 in
which the on-chip COM contains the program to be leached and executed but is
limited to only 4K bytes ot‘cude. The FtOM containing the proSrai:l attached to
the 8031 can be as large as 64K bytes. In the process of adding external ROM to
the 8031, you lose two ports. That leaves only 2 poris (of‘the 4 poi ts) for l/O
operations. To solve this problem, yoti can adJ external l/O to the 5031. Intei
facing the 8031 with memory and l/O ports such as the 8255 chip is discussed in
Chapter i4. There are also various sped.d versions of the 803.1 available from
different companies.
Var!›ous 80S1 microcontrollers
Although the 8051 is the liiost popu!at member of the 8051 family, you
will not see “805 l” in the part numoer. This is because the 8051 is available in
differ- ent inemoi y types, such as UV-EPROM, fiash, and NV-RAM, all of
which have different part numbers. A discussion of the variou5 types Of ROM
will be given in Chapter 14. The UV-EPROM version of the 8051 is the 8751.
The flash RGNi ver- sion is marketed by iiiany companies including Atmel Corp.
The Atniel Flash 8051 is called AT89 51. The NV-RASH version of the 8051
made by Da.lias Semiconductor is ea11e‹J DS5000. There is also the OTP (one-time
programmable) version of the 8051 made by various manuIacturers. Next we
discuss t›riefly each of the above chips an.d cSGribe applications where they are
used.
9751 microcontroller
This 8751 chip has only 4K bytes of on-chip UV-EPROM. To use this
chip for development requires acccss to a PROM burner, as well as a UV-
EPROM eras- er to erase the contents of UV-EPROM inside the 875.1 chip
before you can pro- grams :t again. Due to the fact that the on-chip ROM for the
8751 is UV-EPROM, it takes around 20 rnin'!!es to crase th.• 5751 before it can
be programmed again. This has led many :ranufacturers to 'nttoduce flash and
NV-RAT' versions of the 505 ! as we will discuss iiext. There are also various
speed versions of tb.e 8751 available fi‘oiii different companies.
AT89C51 from bfr e/ Corporation
This popular 5051 chip has on-chip ROM in the form of flash memory.
This is ideal for fast development since flash meiiiory can be erased in séconds
compared to the twenty minutes or moral needed for the 8751. Foi’ this reason the
ATS9C51 s used in place of the 875.1 to eliminate the waiting ttme necded to
erase the chip and thereby speed up the development time. Tc use the AT89C5 1
to devel- op a Nictncontio\\et-based sts'.em i•.quines a FOR butnet that supports
flash memory; however, a Rf3M eraser is not needed. Notice that in flash memory
you must erase the elitire c tents or ROM in order to program it again. TI, i
erasing ot” flash is done by the l'liOM but net itself and this is why a separate
eraser is not needed. To eliminate the need for a PROM but net Atmel is working
on a version of the AT89C51 that can be programmed via the serial COM port of
an IBM PC.
30
l‹iilc I -5: Verxions of 8051 from Atmel (All ROM £’Iasli)
l•.irt Number ROM RnlYI I/O ›ins Timer Interrupt Yp, Packaging
4T89C51 4K ! 28 32 2 6 SV 40
T89LV51 4K 128 32 2 6 3V 40
4T89C 1051 1K 64 !5 1 3 3V 20
1f89C205 I 2K 125 l5 2 6 3V 20
4T89C52 8K 128 32 .3 8 5V 40
,iT89LV 52 8K 128 32 3 8 3V 40
i\‹›ic. “C” in the part number indicates CMOS.
There are various speed anci packaging versions of the abovc products.
See Table 1-6. For exairiple, notice ATS9c5 l - l2PC where “c” before the 5.1 is
for CHAOS, which has a low pow'er consumption, “12” indicates 12 lvi I-iz, “P”
is for plastic DI P package, and “C” is for eolnliiercial Avs. “M” for iT1ilitai’y).
Often, the Ai 89CS 1 - I2PC is ideal for many studelit projects.

Tabie 1—6: Varioiu Speeds of 8051 From Atmel


Part Num ber S ced Pins Packaging Liser
AT89C51-12PC 12 MHz 40 DIP plastic commercial
AT89C5 l- I6PC 16 lviHz 40 DIP plastic commercial
AT89C5 I-2GPC 20 k4Hz 4G DIP plastic commercial

DS5000 from Dallas Sem.iconductor


Another popular versicn of the 5051 is the DSS 300 chip frorri Dallas
Semiconductor. The on-chip ROM for the DS5000 is in tb.e form of h'V-RAID.
The lead/write capability of IV-RAM allows the program to b• loaded into the
on-chip ROM while it is in the system. This can be done even via the set ia! port
of an IBM PC. This in-system program loading of DS5000 via a PC serial port
makes it an icleal home development system. Another advantage of NV-RAM is
the ability to changc tne ROM ccntents one byte at a time. Conti ast this witia
UV- EPROivl and tflasla mClTlGry in willCh the entire ROM i‹aust be erased before
ii is profi ammed again.
Table 1-7: Versions of 8051 From Dallas Semiconductor's Soft Microcontroller
P ai t Number RO
- -- R I/O i i mers I n ter ru p ts V P ac k ag ing
.- . . .. . - ... .. . . .. . . - . ..- .
M
..-
DS5000-8 8K AM 128 pin s 32 C. B2 .... . 6 5V 40
.. .
DS5000-32 32K 128 32 2 6 54’ *.0
DS5000T-8 8K 125 32 2 6 5V 40
DS5000T-8 32K 125 32 2 6 5V 40

iVoi¿s.‘ AU ROM are NV-RAM.


F” means it has a i eal-time clock.

Notice that the real-tilTle clock (PTC) is dit?erent from the iiirer. The
real- tiie clock generates and keeps the time of day (hr-min-sec) and date (yr-
mon-day) even when the power is off.
CHAPTER 1: THE 8051 MICROCONTROLLERS Sl
There are various speed and packaging versions of the DS5000 US S(1OWi1
in Table 1-8. For example, DS5000-8-8 has 8K NV-RAM and a speed of 8MHz.
Often the DS5000-8-12 (or DS5000T-8-12) is ideal for many student projects.

Table 1-8: Versions of 8051 From Dallas Semiconductor


Part Number NV-RAM S
DS5000-8-8 8K 8 MHz
DS5000-8—12 8K 12 MHz
DS5000-32-8 8 MFiz
DS5000T-32-8 32K 8 MHz with RTC
DS5000-32-12 32K 12 MHz
DS5000T-8-12 with RTC

OTP version of the 8051


There are also OTP (one-time-programmable) versions of the 8051 avail-
able from different sources. Flash and NV-RAM versions are typically used for
product development. fifften a product is designed and absolutely finalize‹i, the
OTP version of the 8051 is used for mass production since it is much cheaper in
terms of price per unit.
8051 family from Philips
Another major producer or :he 5051 family is Philips Corporation.
Indeed, they how one of the !argest se!ccticns of 805 i microcontrollers. many of
their products include features s•ach as A-to-D converters, D-to-A converters.
extended I/O, and both OTP and trash.

Review Questions
1. Name three features of the 5051.
2. \fhat is the major difference between the 8051 and 8052 inierocontro!!ers?
3. Give the size of RAM in each of the following.
(a) 8051 (b) 8052 (c) 8031
4. Give tire size of the on-chip ROM in each"of the following.
(a) 8051 (b) 8052 (c) °03 l
5. The 8051 is a(n) -bit inicroprocCssor.
6. State a major difference between the 8751, the AT89C51 and the DS5000.
7. List additional features introduced in the DS5000T that are not present in the
DS5000.
8. Ti‘rie or false. The AT89C5 l-12PC rhip has a DIP”package.
9. The AT89C5 l- l2PC chip can handle a maximum frequency of MHz.
10. The DS5000-3a has K b acs of on-chip NV-RAM for programs.

S2
SUMMARY
This chapter discussed the role and importance of microcontrollers in
everyday life. Microprocessors and microcontrollers were contrasted and com-
pared. We discussed the tise of iiiicioccntrollers in the embedded market. We
also discussed criteria to consider in choosing a microcontroller such as speed,
ieio- ry, I/O, packagins. and cost per unit. The second section of this chapter
described
various family numbers of’the 8051, such as the 8052 and 8031, and their features.
In addition. we discussed vai iotis versions ot’ the 5051 such as the AT89C5 I
and DS5000, which are marketed by suppliers other than lntel.

PROBLEMS

SECTION 1. l: NIILROCONTROLLERS AND EMBEDDED PROCESSORS

1. True or False. A general-purpose microprocessor has on-chip ROM.


2. True or False. A microcontroller has on-chip ROM.
3. True or False. A microcontroller has on-chip I/O ports.
4. True or False. A microcontroller has a fixed amount of RAM on the chip.
5. What components are normally put together with the microcontroller into a
single chip?
6. Intel's Pentium chips used in \Vindows Cs need external and
ChipS to store data ai.d cGde.
7. List three embedded products attached to a PC.
s. V›'hy would someone want to use ari x66 as an embedded processor?
9. Give the name and the manufacturer of some of the most widely used 8-bit
microcontrollers
In Qu•stion 9, wliiich one !ias the most m.anufacture sources?
11. In a battery-based embedded product, what is t!.e most important factor in
choosin.g a microcontroller?
12. In an embedded controller with on-chip ROM, why does the size of the ROM
matter?
In choosing a microcontroller, how important is it to have a multiple source for
that chip?
i4. What does the term "third-party support" mean?
15. If a microcontroller architecture has both S-bit and l 6-bit versions, which of
the following statements is true.
(a) i he 8-bit software will run on the 16-bif system.
(b) The 16-bit sott’ware will i un on the 8-bit system.

SECTION 1.2: OVERVIEW OF THE 605 i F. 'IILY

16. The 8751 has bytes of on-chip ROM.


17. The AT89C51 has bytes of on-chip RAM.
18. The 8051 has on-chip timer(s).
CHAPTER 1: THE 8051 MICROCONTROLLERS 33
19. The 8052 has bytes of on-chip RANL
20. The RO. Hess version of the 8051 uses as the part number.
21. The 8051 family has pins for l/O.
22. The 80?* 1 famity has circuitry to support serial ports.
23. The S. 51 on-chip ROM is of type
24. The ATR 95 I on-chip ROM is of type
25. The DS5000 on-chip ROM is of’ type
2‘6. Give the speed and package type for the following chips.
(a) AT6"9C5 1- I6PC (b) DS5000-8- 12
27. In Quest.on 26, give the amount and type of”on-chip ROM.
28. Of the 5051 family, which version is the most cost effective if you .i
million of t.hem in an embedded product?
29. What is the difference between the 8031 and 8051?
30. Of t!:e 5051 microcontrollers, which one is the best for a honsc rlc
, ,cnvir< nment? (You do not have access to a ROM burner).

ANSWERS TO REVlE\ñ/ QUESTIONS

SECTION 1.1: MICROCONTROLLERS AND EMBEDDED PROCESSORS

1. True 2. A microcontroller based system 3. (d)


5. It is d icatea since it is dedicated to doing one type ofjob.
6. Emitted system means the processor is embedded into that application.
7. Hat 'n_• multiple sources for a 3iveii part meams ycu are not hostage to one s« ,
impo-*ntly competition amoo.3 supplier s brings about low'er cost for that prod r!c

SECTION 1.2: OVERVIEW OF THE 8051 FAMILY

1. 125 b acs of RAM, 4K bytes of on-chip ROM, four 8-hit I/O ports.
2. The ?•L52 has everything that the 8051 has, plus an extra tim.er, and the on -c!:. :
byte› :n›tead of 4K bvtes. The RAM in the 8052 is 236 by:•s instead of ! 28 ! ,
3. Boti•. :.-.e 605 l and the S03 1 Isa 'e 1 28 bJ'tes of RAM and the S†52 has 25fi l›;
4. (a) - K oytes (0) c8 K bytes (c) OK bytes
5. 8
6. The fiiñ'erence is the type of on-chip ROM. In the 575 [ it is UV-EPRGM: in i!
is l“. : . and in the DS5000 it is N \'-RARI.
7. DS5fi *OT hat a read-time clock (RTC).
S. True

34
CHAPTER 2

8051 &SSEMBL9
L&HGUAGE
PROGRAMMING
OBJECTIVES

Upon completion o1 this chapter, you will b able to:

List the registers of tbe 8051 microcontroller


Manipulate data usin=q the regist•rs and MOV instructions
Code simple 8i):S1 Assembly languiige instructions
Assemble and run an 80s1 program
Describe the sequence of events that occtir upon 8051 r•wer-up
Examine programs in RONI code of the 8051
Explain the ROM memory map o* the 8051
Detail the execution of 8051 Assembly language instructions
Describe 8051 data types
Explain the purpose of the PSW (program status word) regisJer
Discuss RAT'I m.emory space allocation in the 8tl5l
Diagram the rise of the stack in the 8051
ivlanipulate the register banks of the 805I

35
In Section 2.1 we look at the inside of the 805 I . We dciiionstratc some of
the widely uscd registers of the 8051 with simpie instructions such as MOV and
ADD. In Section 2.2 we examine Assembly lar.guage and machine language pro-
gramming and define terms such as mnemonics, opcode, operand, etc. The
process of assembling and creating a ready-to-run program for the 8051 is
discus.«ed in Section 2.3. Step-by-step execution of an 8051 program and the role
of the pro- gramcounter are examined in Section 2.4. In Section 2.5 we look at
some widely uscd Assembly language directives, pseudocode, and data types
related to the 5051. In Section 2.6 we discuss the flag bits and horn’ they are
atâ'ected by arith- metic instructions. Allocation of RAM memory inside the 8051
plus the stack and register banks of the 8051 are discussed in Section 2.7.

SECTION 2.1: INJgIDE THE 8051


In this section we examine the iuajor registers of the 8051 and show their
use with the simple instructions MOV and ADD.
«r
Registers *
G7 D5 D4 D3 D2 Dl D0 “
In the CPU, reg-
isters are used to store
infoi ination temporarily. That information could be a byte of data to be
processed, or an address pointing to the data to be *etched. The vast majority or
8051 regis- ters are 8-bit registers. In the 8051 there is only one data type: 8 bits.
The S bits cf a register a.re snoun. in the diagram from the. MTB (most significant
bit) D7 to the LSB (least significant bjt.) D0. With an 6-bit data type, any data
larger than 8 bits must be broken into 8-bit chunks oefore it is prGcesse‹i. Since
there are a laiS<
number of registers in the 8011, we will concentrate on some of the widely us•d
general-purpose registers and cover special registers in future chapters. See
Appendix A.3 for a complete list of 8051 registers.

DPH DPL

PC
PC (program counter)

Figure 2-1 (b): Some 8051 16-bit Registers

The most wiciely used registers of the 8051


are A (acctiiiitilatoi), B, RR, R 1, R2, R3, R4, R5, R6,
k7, DPTR (data pointei’), anal PC (program counter).
All o* the abo ve registers ar S-bits, except DPTR
and the programs counter. The accr!mulator, register
A, is used for all arithmetic and logic instructions. To
Figurc 2-1 (a): Some 8-bit understand the use of these registets, we will show
Registers of the 805) them in the context of two simple instructions, MOV
and ADD.
36
. . ‹*
MO*7 instruction
$imply stated, thc MOV ii\structioia copics data iron onc location to
anoth- er. It has the following format:

MOV destination,source ;copy source to dest.

This instruction tells the CPU to move ( reality, copy) the sour cs operand
to the destination operand. For exaliipie, the insti‘uction “MOV A, R0” copies the
contents of register R0 to register A. After this instruction is executed, register A
will have the same value as register R0. The MOV instruction does not affect the
suui ce operand. The following program first loads register A with•valiie 55H (that
is 55 in hex), t:men moves this value around to various registers inside the CPU.
Notice the “#” in the instruction. This signifies that it is a value. The importance
of this will be discussed soon.

MOV ;load value SSH into reg. A


A,#55H ;copy contents of A into R0
MOV R0,A ;(now A=R0—SSH)
;copy contents of A into Rl
MOV Rl,A ;(ncw A=R0=Rl=SSH)
;copy contents of A into R2
MOV R2,A ;now A=R0=Rl=R2-SSH)
MOV R3,#95H ;load value 95H into R3
;(now Ro-95H)
;copy contents of R3 i.to A

V'hen programme ng the 8051 microcontroller, the following points


should be noted:
1. Values can be loaded dii ectly into any of ie isters A, B, or R0 - R7. However,
to indicate t!iat it is an iiiiinediate value it must be preccded with a pound si•_!
â ( . This is shov•ri next.

MOV 0,#23H ;load 23H into A (A=23H)


MOV R0, #l2H ;load 12H nto R0 (R0-12H)
MOV Rl,#lFH ;load lFH into Rl (Rl=lFH)
MOV R2,#2BH ;load 2BH into R2 (R2=2BH).
MOV B,#3CH ;load 3CH into B {B=3CH)
MO R7,#9DH ;load 9DH into R7 (R7=9DH)
MOV R5,#0F9H ;load F9H inCo R5 (R5=F9H)
MOV R6,#l2 ;load 12 decimal (= OCH)
rlnto reD. R6 (R6=0CH)

Notice in instruction “MOV R5, 10 fi9H” that thele is a need for U


between the # and F to indicate that F is a hex number and not a letter. ln other
woyds “MOV R5, I C9H” will cause an error.

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMINO“


2. If values 0 to F are liioved into an 8-bit register, the rest of tlie biis are
assuiiied to be all zeros. For example, in “ O v A, 8 S” the result will he A
= 05; that is, A = 00000101 in binary.

3. Moving a value that is to large into a register will cause an error.


MOV A,#7F H;ILLEGAL: 7F2H > 8 bits (FFH)
MOV R2,456 ;ILLEGAL: 456 > 255 decimal (FFH)

4. To load a value into a register it must be preceded with. a pound sign (#).
Otherwise it means to load from a memory location. For example “MQV
A, 17 H” means to move into A the value he!d in memory location 17 Fi,
which cculd have any value. In order to load tf:e value l7H iiito the
accumulator we must write “MOV A, 117 H” with the # preceding the
number. Notice that the absence of the potind sign will not cause an error by
the assembler since it is a va!'d instruction. However, the result would not be
what the programmer intended. This is a common error for beginning
programmers in the 8051.
ADD instruction
The ADD instruction has the following format:

ADD A,source ;ADD the source operand


; O the accumulator

The ADD instruction felts the CPL to add the source byte to register‘ A
and" put the rest.ilt In rcgister A. To add two numbers such as 25H and 34H, each
can be moved to a ‹cgi.:•r and then °*ded together:

MOV A,#25H ;load 25H into A


MOV R2,#34H ;load 34H into R2
ADD A,R2 ;add R2 to accumulator
:(A = A + R2)

Executing the program above results in A — 59Fi (25H + 34H = 59H) and
R2 — 34H. Notice that the content of R2 does not change. The program above
can be wi ittcn in many ways, depending on the registers used. Another way
might be:

MOV R5,#25H ;load 25H into R5 (R5=25H)


MOV R7,#34H ;load 34H into R7 (R7=34H)
MOV A,#0 ;load 0 into A (A=0,clear A)
ADD A,R5 ;add to A content of R5
;where A = A + R5
ADD A,R7 ;add tc A content of R7
;where A - A + R7

The program above i'esults in A = 59H. There are always many ways to
write the same program. One question that might come to mind after looking at
the program above, is whether it is necessary to move both data items into
registets
38
before adding them together. T'hc ans ver is no, it is not neccss*! y. Look at the
Al- lowing variation of the saiiic progralii:

MOV A,#25H ;load one operand into A (A=25H)


ADD p#34 radd the second operand 34H to A

In the above case, while one register contained one value, the second
value followed the instruction as an operand. This is called an iniii.•e‹fiafc•
operand. Fhe examples shown so far for the ADD instruction indicate that the
source operand can be either a register or iiniiiediate data, but the destination irtist
at ways be reg- ister A, the accriinttlator. In o:her words, an instruction such as
“ADD P 2, # 12 H” is invalid since register .4 (aGcuiiiulator) must be involved
in any arithmetic oper- ation. Notice that “ADD R4, A” is also invalid tor the
reason that A must be the destination ot any ai ithiiietic operation. T put it simply:
In. the 8051, l cgistci A must be involved and be the destination for a!1 arithmetic
operations. The forego- ing discussion explains the reason that register A is
referred to as the accumulator. The format for Assembly language instructions,
descriptions of their use, arid a listing of legal operand types are provided in
Appendix A.1.
There are two 16-bit registers in the 8051: PC (program counter) and
DPTR (data pointer). The importance and use of the program counter are covered
in Section 2.3. Fhe D!*TR register is used in accessing data and is discussed in
Chapter 5 when addressing mod•s are co 'ered.
Reviev\• Questions
1. Writ• time ins*uctions to move va!ue 34H 'mo register A and value 3FH into
register B, then add tiierii together.
2. Write the instructions to add the values 16H and CDH. Place the :esult in reg-
ister R2.
3. True or false. No value can be moved directly into registers R0 - R7.
4. What :s :he largest hex value that can be moved into an 8-bit re•qister? W'hat
is the decimal •.qtiivalent of the hex value?
5. Tree vas' rna.jority cf ies'S›els in 5051 ai e bits.

SECTION 2.2: INTRODUC1ON TO 8051 ASSG’¥BLY PROGRAMMI!‘1G

In this section we discuss Assembly language format and detine some


widely used terminology associated witli Asseiiibly language pro3ran?iiiing.
While the CPU can work only in binary, it can do so at a vei'y hi•pli speed.
However, it is quite tedious and slow for hu:nans to ñ.•. with 0s and l s in order
to program the computer. A program that consists of 0s and ] s is calle‹i iiirici'iine
language. In thc early days of the computer, programmer s coded prop•prams in
machine language. Although the hexadecimal system was used as a iiioi'e efficient
way to represcnt bina: numbers, the process of woi king in :uachine c c was still
cumbersome for human,. Eventually, Assembly languages were dcvclo;›ed which
provided iiineinonics for the machine code instructions, pltis other f'eattii es which
made programming faster and less prone to error. The term mnemonic is frequent-
ly used in computer science and engineering literature to refer to codes and abbre-

CHAPTER 2: 8051 ASSEMBLY LANC•U ALL PHHt Ivnviii 39


viations that are relatively easy to remember. Assembly language programs must
be translated into machine code by a program calle.d an assembler. Assembly
lan- guage is referred to as a low-level langtiage because it deals directly with the
int•r- na1 structure of the CPU. To program in Assembly language, the program.iner
must know all the registers of the CPU and the size of each, as well as other
details.
Today, one can use many different programinin.g languages, such as
BASIC, Pas*al, C, C++, Java, and numerous others. These languages are called
/7iy6-/evef languages because the progralnmer does not have to be concerned
with the internal details of the CPU . Whereas an cssembler is used to translate an
Assembly language program iiito machine code (soinetimes also called object
code or opcode for operation code), high-level languages are translated into
machine code by a program called a compiler. For instance, to write a program in
C, one must use a C compiler to translate the program into machine language.
Now we look at 5051 Assembly language torlrat and use an 5051 assembler to
create a ready-to-run program.

Structure of Assembly language


An Ass•mbly language program consists of, among other things, a series
of !ines of Assembly language instructions. An Assembly language instruction
consists of a mnemonic, optionally followed by one or two operands. The
operands are the data items being manipulated, and the mnemonics are the com-
mands to the CPU, telling it what to do with those items.

ORG cH ;s art (origin) at location 0


MOV R5,#2SH ;load 25H into R5
MOV R7,#34H ;load 34H into R7
MOV A,#0 ;load 0 into A
ADD A,R5 ;add contents of R5 to A
;now A - A + R5
AND A,R7 ;add contents of R7 to A
;now A = A + R7
ADD A,#l2H ;add to A value 12H
;-ow A = A + l2H
HE RE : S HCP i-iERE ;stay in this loop
END ;end of Msm source file

F'rogram 2-1: Sample of an Assen:bly Language Pro•qram

A given #.sscrrlbly language program (see Program 2-1) is a sei'ies


of'state- ments, or lines, wh' are either Assembly language instructions sue' as
ADD and MOV, or statements called directives. While instructions tell the Cf'k
what to do, directives (also called pseudo-instructions) give directions to the
assembler. For example, in the above program while the MOV and ADD
instructions are com- mands to the CPU, ORG and END are directives to the
assembler. ORG tells the
40
assembler to place the opcode at memory location 0 while END indicatcs to the
assembler the end of t •. source code. In other words, one is for the start of the
pro- gram and the other one for the end of the program.

An A mbly. language instruction consists of four fields:

[label:) mnemonic (operands) (;comment)


Brackets indicate that a field is opticnal and not all lines havu theiii.
Brackets should not be typed in. Regarding the above format, the followins P '
should be noted.

1. The label field allows the program to refer to a line of code by name. T!ic
label field cannot exceed a certain number of characters. Check your
assembler for the rule.

2. The Assembly language mnemonic (instruction) and operand(s) fields top•eth-


er perform the real work of the program and accomplish the tasks for which
the program was written. In Assembly language statements such as

ADD A,B
MOV A,#67

ADD and MOV are the mnemonics which produce opco cs; “A,B” and
“A,#67” are the operands. Instead of a rr.nemonic and operand, these- two
fields would contain assembler pseudo-instructions, or fire tivcs. $errember
that directives do not generate any machine code (opcode) arid are used or!y
by the assembler, as opposed to instructions that are translated into machine
code (opcode) for the CPU to execute. In Program 2-1 the commands ORG
(origin) a*d END are examples of directive.› (some 5051 assemblers use
.ORG and
.END). Check you:r assembler for the rules. More of these pseudo-instructions
are discussed in detail in Section 2.5.

3 The comment field begins with a semicolon comment indicator “ ’.


Comments may be at the end of a line or on a line by themselves. The assem-
bler ignores comments, but they are indispensable to programmers. Although
ccmments are optional, it is recommended that they be used to describe the
program in order to make it easier for someone else to read and ndeistand.

4. Notice the label “HERE” in the label field in Program 2-1. Any label referring
to an instruction must be followed by a colon symbol, “:”. In the SIM P (short
jump instructi Fl‘), the .805 l is told to stay in this loop indefinitely. If your sys-
temhas a monitor pre 3ram you do not need thls llne and it should b deleted
from your program. i .. the next section we will see l•.ow :o create a idy-to-
run progiam.
‹i
R»view Questions
1. What is the purpose of pseudo-instructions?
2. are translated by the assembler into machine code, whereas
are not.
3. Ti ue or false. Assembly language is a high-level language.
4. Which of the following produces opcode?
(a) At)D A,R2 (b) MOV A,#12 (c) Oft 2000H (d) SJMP HERE
5. Pseudo-instructions are also called
6. Tt ue or false. Assembler directives are not used by the CPU itself. They are
simply a guide to the assembler.
7. I n question 4, » hich one is an assembler directive?

SECTION 2.3: ASSEMBLING AND RUNNING AN 8051


PROGRAM

°How that the basic form of an Assembly language program has been
given, tne next question is: How it is created, assembled and made ‘ready to run?
The steps to create an executable Assembly language program are outlined as
follows.
EGITOR
PRocRAM
1. Fiist we use an editor to type in a 4
myfile.asiu
pt cgra.m similar to Pi ogram 2-1. 2
k4any excelleirt editors or word
processors are a ailable that can be ASSEMBLER PROGRANI
used to create and/or edit the pro-
gram. A widely used -ditor is the
n›yfi Ie.1st
MS-DOS EDIT program (or
Notepad in \Vindows), which comes my file.obj
other obj files
w ith all M lcrosoft operatin_•
systems. Notice that the editor mus: LINKER
be able to produce an SCl I fi le. For .°ROGRAM
many assemblers, the file names
follow the usual DOS conventions,
but the source fi le has thee ext•nsion my file.abs
“asm” or “src”, depending on which
assem- bler you are- us ing. Check your
assembler tor the convention. The OH PROGRAM
“asiii” extension for the source file is
used by an assembler in the next
Siep.
my file.hex
2. The “asiii” son: cc file con.ta.ining the
program code ci cated in step l is fed
to an 8051 fl5SClnbler. The assembler
converts the instructions into
Figure 2-2. Steps to Create a Program
izJaclJinc ccdc. 1"hc assembler \yi|! produce an (.icct filc ::nd a list liIe. The
cxtcnsion l1r the object fjlc is "ob]" while thc cxtci Sion lor tlzc list tllc is "lst".

3. Assemblers require a thiid step called linking. The iink program takes one or
more object files and produces an absolute object file with the extension
"abs". This abs fi ie is tised by 8051 trainers that have a monitor progra:n.

4. Next the "abs" fiic is lcd into a program called "OH" (object to hex convei t-
er) wli Fch ci eates a II le with extension "hex" that is ready to b.irn. into
ROM. This program cones with all 8051 assemblers. Recent Windows-based
assem- blers combine steps 2 ill otigli 4 iiito one step.

More about "asm" and "obj" files


The "asir" fi!e is also called the source file an‹i for this reason some
assem- blers require that this tlc l.ave the "src" extension. Check your’ 8051
assembler to see which one it requires. As iiientioned earlier, this file is created
with an editor such as DOS EDIT or Window's Notepad. The 8051 assembler
converts the asm file's .Xssemb!y language instructions into machine language
and provides the obj (object) file. !n addition to creating the object file, the
assembler also produces the 1st file (list file).

Ist file
The 1st (i ist) l3le which is optional, is every useful to the programmer
because it lists all t'ne opeodes ana addresses as well as •rrors that the- asserrlb!er
dctectco. Many assemblers assume that the list file is not wanted crless you indi-
cate that you want to produce it. This file can be accessed by an editor such as
DOS *DIT and displayed on the monitor or sent to the printer to get a hard copy.
The pi'ograiuiuel uses the list file to fir.d syntax errors. It is only after fixing all
the ei rois indicated in that 1st file that the obj file is ready to be inprit to the
linker pro- grams.
I SOOO ORG OH ;start (origin) at 0
2 0000 7D25 MOV R5,#25H ;load 25H into R5
0002 7F34 MOV R7,#3dH ;load odH into R7
4 0004 7400 MOV A,#0 ;load 0 into A
S 0006 2D ADD A,R5 ;add contents of R5 o A
;now A = A * R5
E 0007 2F ADD L, R7 ;add contents of R7 to A
;now A = A + R7
0008 2412 ADD A,#l2H ;add to-A value 12H
;row A = A + l2H
OOOA 80FE HERE: SJMP HERE ;stay in this loop
OOOC END ;end of asm source file

Program 2-1: List File ”’

CHAP'£E11 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 43


Review Questions
l. True or false. The DOS program GDIT produces an ASCII file.
2. True or false. Generally, the extension of the source file is “.a•‹o” or “.src”.
3. Which of the following tiles can be produced by the DOS EDIT program?
(a) myprog.asm (b) myprog.obj (c) myprog.exe (d) myprog.1st
4. Which of the following files is produced by an 8051 assembler?
(a) myprog.asm fb) myprog.obj (c) myprog.hex (d) inyprog.1st
5. Which of the following files lists syntax errors?
(a) inyprog.asrn (b) myprog.obj (c) myprog.hex (d) myprog.1st

SECTION 2.4: TI-!E PROGRAM COUNTER AND ROM


SPACE IN THE 8051

In this section we examine the role of the program counter (PC) register in
executing an 8051 program. We also discuss ROM memory space for various
8051 family members.
Program counter in the 8051
Another important register in the 8051 is the PC (program counter). The
' sram counter points to the address of the neKt instruction to be executed. As the
CPU fetches the opcod- front the program ROM, the program counter is incre-
mented *o point to the next instruction. The program counter in the 6051 is 16
Sits wide. i b.is means that the SG51 can acces.s program addresses 0000 to FFr
FH, a total of 64*? bytes of*o‹i•. Howev'er, not al! mernb•rs of the 805'. has.e the
entire 6*.K bytes ot on-chip ROh4 installed, as we wil see socn firbere do•s the
805 i wake up when it is powered? We will discuss this important topic next.
Where the 8051 wakes up wilen it is powered up
O.ne question that we must ask about any microcontroller (or microproces-
sor) is: At what addi'ess does the CPU wake tip upcn applying power to it? Each
mic› oprocessor is ‹liiTerent. ln t!ie casc of the 8051 family. that is, all members
regardless of the maker and variation, the microcontroller wakes up at memory
addiess 0000 when it is powered up. By powering up eve mean applying V CC to
the RESET pin as discussed in Chapter 4. In other words, when the 8051 is pow-
ered tip, the PC (program counter) has tb.e value of 0000 in it. This means th.at it
expects thee first opcode to be stored at ROM address OOOOH. For this reason in the
8051 system, the first opcode must be burned into memory location OOOOH of
pro- grams ROM since this is where it looks for the first instruction when it is
booted. We achieve this by the ORG statement in the source program as shown
earlier. Next we discuss the step-by-step action of the progfim counter in fetching
and executing a sample program.
Placing code in program. ROM
To get a better understanding of the role of the program counter in fetch-
in.g end executing a program, we examine the action of the program counter as
each instruction is fetched and executed. First, we examine once more the list file
of thc sample program and how the code is placed in the llON^. of’ : n 8051 chi;:.
As we can see, thc opcode and operand for cach instruction arc listed on the lcft
side of the list file.

ORG OH ;start at location 0


7125 NOV R5,#25H ;lOad 25H iCtO R5
MOV R7,#34H ;load 34H into B7
" 90 MOV A,f0 ;load 0 into A
’ADD A,R5 ;add contents of R5 to A
;now A = .A + R5
ADD A,R7 ;aad contents of R7 to A
;now A = A + R7 ,
%.DD A,#12H ;add to A value l2h
;now A = A + 1 H
”?- 80FE HERE: SJMP HERE ;stay in this loop
END ;end of asm source file

RAM Address Machine Lan aqe_ Assembl _Lanquage


OOOO 7D25 MOV R5,#25H
0002 7F34 MOV R7,#34H
0004 7400 MIV A,#0
’0006 2D ADD A,R5
0007 2F ADD A,R7
0008 24i2 ADu A,#12H
0OuA 80FE JURE: SNMP HERE

After the program is burned into ROM of an 8051 family rr.ember such as
875 l or AT895! or DS5000, tne opcode and operand are placed in ROM memory
locations starting at 0000 as shown in the list below.
The list shows that addiess 0000 con-
tains 7D which is *he opcode for iriovin3 a Program 2-1: I'.OM Contents
value into register R5, and address OOG l con-
taiiâs the operand (in this case 25H) to be
moved to R5. Therefore, the instruction “MOV
R5, # 25H” has a machine code of “7D25”,
where 7D is the opcode and 25 is the operand.
Similarly, the machine code “7F34” is located
in memory locations 0002 and 0003 and rep-
resents the opcode and the opeiand for the
instruction “MOV R7, # 34 H”. In the same
way, machine code “7400” is located in mem-
ory locations 0004 and 0005 and repress ,
the opcode and the operand for the instruction
“MOV A, 10”. The memory location 0006 has
the opcode of 2D which is the opcode for the'

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMIh’G 45


instruction “ADD A, R5” and memory location 0007 h.as thc content 2F, which
is opcode for the “ADD A, R7” instruction. The opcode for instruction
“HDD h, # 12 H” is located at addi ess 0008 and the operand 12H at address
0009. The memory location OOOA has the opcode for t!1e SJMP instruction and
its target address is !ocated in location OGOB. Thy reason the target address is
FE is explained in the next chapter.
Executing a program byt:e by byte
Assuming that t!ie above program is burned into the ROM of an 8051
chip (or 5751, ATS951, or DS5000), tlJC fOllowing is a step-by-step description
of the action of the 8051 upon applying power to it.

1. When the 5051 is powered up, the PC (program counter) has 0000 and starts
to fetch the first opcoae from location 0000 c›f the program ROM. In the case
of the above program the first opcode is 7D, which is the code for moving an
operand to R5. Upon executing the opcode, the C. U fetches the value 25 and
places it in R5. Now one instruction is Finished. Then the program counter is
incrementefi to point to 0002 (PC = 0002), •xhich contains opcocie 7F, the
opcode for the instruction “NOV R7, ”.
2. Upon executing the opcode 7F, the value 34H is moved into R7. Then the
pro- gram counter is incremented to 0004.
3. ROM location 0004 has the opcode for instruction “MOV A, 10”. This
instruction is executed and now PC=0006. Notice that all th• above instruc-
tions are 2-byte instructions; that is, ea*.n one ta.kes two memory locations.
4. h'ow PC = 0006 points to the next instruction which iS “ADD Ps r R5”• Th @
a I-byte instruction.. A*er th.e execution of this instruction, PC — 0007.
5. The location 0007 has the opcode 2F which belon-gs to the instruction “ADD
A, R7”. This is also a l -byte instruction. L'pon execution of this instruction,
PC is in.cremented to 0008. This process goes on until all the instructions are
fetch.ed and executed. The fact the program counter points at the next instruc-
tion to be executed explains why some microprocessors (notably the x86) call
the program counter the in.sfrncf/on pointer.
ROM. memory map in the 6051 family
As we saw in the last chapter, some family members have only 4K byte›
of on-Gllip ROM (e.g., 8751, AT8951) and some, such as the AT89C52, have 8k
bytes of. ROM. Dallas Semiconductor’s DS5000-32 has 32K bytes ot’ on-chip
ROM. Dallas Semiconductoi’ also has an 5051 with 64K bytes of on-chip ROM.
The pcint to remember is that no ineiiiber of the 5051 famiiy can access more
than 64K bytes of opcode since the program counter in the 8051 is a 16-bit
register (0000 to FFFF address range). lt must be noted that while the first
location of pro- gram ROM inside the 8051 has the a‹idress of 0000, the last
location can be dif- ferent depending on the size of the ROkl on the chip. Among
the 8051 faluily members, the 8751 and AT8951 have 4k tiytes of on-chip ROM.
This 4K bytes ROM memory has memory addresses of 0000 to 0FFFi-I.
Therefore, the first local tion of on-chip ROM of this 8051 has an address of 0000
and the last location ha the address of OFFFH. Look at Example 2-1 to see how
this is computed.
46
rxamp!c 2-1
Find thc ROM memory address c each of the following 805.1 chips.
(a) AT89C51 (or 8751) with 4KB (b) DS5000-32 with 32KB

Solution:

(a) With 4K bytes of on-chip ROM iiieinory space, we have 4096 bytes, which is I OOOH
in hex (4 x 1024 = 4096 or 1000 in hex). This iuuch me1iioi‘y maps to address
loca- tions of 0000 to 0FFF1-1. Notice that 0 is always the first location.

(b) Witli 32K bytes we have 32,768 (32 x 1024 — 32,768) bytes. ConveHii:g 32,768 to
hex, we get 8000H; therefore, the memory space is 0000 to 7FFFH.
b3 te byte
0000
00 00

OF
8751
ATS9C 8752
AT89C

7F

Pigii re 2-3. 8051 On-Chip COM Address Ranp•e DS5000-


Rev‹ew Questions
1. lit the 8051, the program counter is bits wide.
2. Ti die or’ false. Every iiiember of the 8051 family, regardless of the maker,
wakes up at memory OOOOH when it is powered up.
3. At what ROM location do we store the first opcode of an 8051 progt ant?
4. The instruction “MOV A, # 4.4 H” is a -by'e iiJStFUCtiOFl.
5. What is the Rk^Nl address space for the 8052 chip?

SECTION 2.5: 8051 DATA TYPES AND DIRECTIVES

In this section we look at some widely used data types and directives sup-
poi't ri by the 8051 assenibier.

805 data type and directives


The 8051 mlcrocontroller has only one data type. It is 8 bits, a.nd the sixe
of each register is also 8 bits. It is the job of the programmer to break. down data

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 47


larger than 8 bits (00 to FFH, or 0 to 255 in decimal) to be processed by the CPU.
For examples of how to process data larger than 8 bits, see Chapter 6. The data
types used by the 8051 can be positive or negative. A discussion of signed num-
bers is given in Chapter 6.
DB (define byte)
The DB directive is the most widely used data directive in the asseiiibler.
lt is used to define the 8-bit data. When DB is used to define data, the n.umbeis
can be in decimal, binary, hex, or ASCII formats. For decimal, the “D” after the
deci- mal nuiiiber is optional, but using “B” (binary) and “H” (hexadecimal) for
the oth- ers is required. Regardless of which is used, the assembler will convert
the num- bers into hex. To indicate ASCII, simply place it in quotation marks
(‘like this’). The assembler will assign the ASCII code for the numbers or
characters at!tomat- ically. The DB directive is the only directive that can be used
to define ASCII strings larger than two characters; therefore, it shou!d be used for
all AS“Cll data definitions. Following are some DB examples:

ORG 500H
DATAl: DB 28 ;DECIMAL(lC in hex)
DATA2: DB 00l10l01B ;BINARY (35 in hex)
DATA3: DB 39H ;HEX
ORG 5l0H
DATAS: DB “2591” ;ASCII NUMBERS
ORG 5l9H
DATm6: DB “My name is Joe”;ASC I CHARACTERS

Either single or double quotes can be used around ASCII strings. This can
be useful for strings, which contain a single quote such as “O'Leary”. DB is also
used to allocatc memory in byte-sized chunks.
Assembler directives
The following are some more wide!y used directives of the 8051.

ORG (origin)
The ORG directive is used to indicate the beginning of the address. The
nuinbe: that comes after GRG can be either in hex or in decimal. If the number is
not followed by H, it is decimal and the assembler will convert it to hex. Some
assemblers use “ . oRG” (notice the dot) instead of “ORG” for the origin directive.
Check your assembler.
EQU (equate)
This is used to define a constant without occupying a memGry location.
The ")U directive does not set aside storage for a de!a item but assoclates a con-
stant aiue with a data labei so that when the label appears in the program, its con-
stant value will be substituted for the label. The following uses EQU for the
count- er constant and then the constant is used to load the R3 register.

48
COUNT EQU 25

MOV R3,#COUNT

When executins the instruction “NOV R3 r k COUNT”, the register R3


will be loaded with the value 25 (notice the # sign). What is tlic advantage of
using EQU°- Assume that there is a constant (a fixed va!iie) uscd in hiany
difl'ercnt places in the program, and the prograiiiiner wants to change its valtie
throughout. By the
use of EQU, one can change it once and the assembler wilt chanse all of its
occur- i ences, ratliei than search the entire progtam trying to find every occur
ience.

END directive
Another important pseudocode is the END directive. This indicates to the
assembler the end of the source (asin) file. The END directive is the last line of an
8051 program, meaning that in the source code anything after the END directive
is ignored by th.e assembler. Sortie assemblers use “ . EN D” (notice tne dot) instead
O L “EN D”.

Rules for labels in Assembly language


By choosi.rig label names that are meaningful, a progratnmer can make a
program mrich easier to read and maintain. There are several ru!es that names
must fo1lo•x. First, each lai:el name must be unique. The names used for
labels in A ssembl•,• language programming consist of alphabetie letteis in both
upper and lower case, *he digits G though 9, and the special charactei's question
mark (?), pericd (.), at (@), underline (_), and dollar sign ($). The first character of
the label must be an alphabetie character. In other words it cannot be a number.
Every assembler has some reserved words which must not be used as labels in the
pro- gram. Foremost among the reserved words are the mnemonics for the
instructions. FOR C2iiilTlQle, “MOV" and “ADD" are reserved since. !hey are
instruction mnemon- ics. As.dc from the mnemonics there arc some othei resei‘ved
words. Check your asscn°.bler for the list of reserved words.

Review Questions
l. The directive is always used for ASCII stt in3s.
2. How man.y bytes are used by the following?
DATA l DB "AMERICA"
o. What is the advantage in using the EQU directive to define a constant value?
4. Fiow many bytes are set aside by each of the following directl yes?
(a) TSC DATA DB ” 1.2.3.4 ” (b) MY DATA DB "ABC 1.2.3.4 ”
5. State tl.e ntents of memory locations 2 0fi - -295H tj!’ ' followin,q
ORG 200H
MYDATA: DB "ABCl23"
CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 49
SECTION 2.6: 8051 F* AG BITS ANO THE PSW REGISTER

Like any oilier microprocessor. tic 805 lfas a hag regi‘star to ii›ñicaie
ai itIin›etic conditions such as the carp bit. TJ›e flag rogistei ir. '.1e 80a) is
called the piogram status word (PSW) register. In this scction wc discuss various
bits ot“ this i cgistei and provide some examples of loo a it is altci cdi

PSW (program status word) register


i he program status wold (PSW} rcgistci is an S-hit rcgister. It is also
refer i ed to as the bag regifi/er. Although the PSW register is 8 bits wide, only 6
sits of it are used by the 8051. The two unused bits are user-definable flags. Four
* * +^6 o oa?eñ conditioned hogs, meaning t\ at tfizy indicate sore condi-
tions tha' resulted after an instruction was executed. These tour are CY (carry), AC
(auxiliary carry), P (parity), and OV (over flo'.v).
As seen from Figure 2-4, the bits PS \i’3 and PS tV4 are designated as RS0
and RS 1, and are used to change the bank registers. Tiiey’ ai e explained in the next
section. The PSW.5 and PSW. 1 bits are general-purpose status flag bits aiid can be
used by the pi ogrammer for any purpose. In other woi ds, they are user definable.
See Figure 2-4 for the bits of the PSW register.

CY I AC F0 RS1 RS0 OV - P

CY PSW.7 Carry flag.


AC PSI'.ti Auxiliary carry flag.
PSW.5 Available to the user for general purpose.
RSI PSW.4 Regis:er Bank selector bit 1.
RS0 PSW.3 Register Bank selector bit 0.
OV PSW.2 O‘/erflow flag.
PSW.I User definable bit.
P PSW.0 Parity flag. Set/clear cd by hardware each instuction cycie
to to.dicate an odd/es en numbe:‘ of 1 bi's in the accumulator.

_ Register Bank s
0 AOH' 7H’ " *”
I 08H -
OFH l0H -
l7H l8H -
l FH

Figii re 2-4. Hits of the PSW Register

The following is a brief eKplanation Of four of the flag bits of the PSW reg-
ister. The impact of instructions on these registers is then discussed.
CY, the carry flag
This flag is set whenevcr there is a carry out morn tl c d7 bit. This flag bit
is affected after an 8-bit addition or subtraction. It can also be set to ! or 0 direct-
ly by an instruction such as “SETB C” and “CLR C” 'there “SETB C” stands
Not “set bit carry” and “CLR C” for “clear carry”. More about these and other
bit- addressable instructions will be givers in Chapter 8.
AC, fhe auxiliary carry I/ag
If there is a carry front D3 to D4 during an ADD or SU E operation, this
hit is set; otherwise, it is cleared. 3“his flag is used by ilisti uctioas that perform
i3CD (binary coded decimal) arithmetic. See Chapter 6 for iiiore tutor mation.
P, the parity flag
The parity flag reflects the number of 1s in the A t accumulator) register
only. If the A register contains an odd number of 1s, risen P = 1. Fhei efore, P —
0 if A has an eveti number of 1s.
OV, the overf/ow flag
This flag is set whenever the resu!t of a signed nriiiiber opera(ion is too
large, causing the high-order bit ’to overflow into the sign bit. In general, the carry
flag is used to detect errcrs in unsigned arithmetic operations. Fhe overflow flag
is only used to detect ert‘ors in signed arith:netic operations and is discussed in
detail in Chapter 6.

ADD instruction and PSW


Liexi we examine the impact Tabl• 2-1: Instructions That Affect
of the AND instruction on the flag bits *lat Bits
CY, AC, and .* of the PSW register. Instrntion CY GV AC
Some exampl•as should clarify their ADD X X X
status. Although the flag bits affected ADDC X X X
by the ADD instl uction are CY (car iy SUBB X X X
fiag), P (pari'y flag), AC (auxiliary MUL 0 X
carry flag), and OV (overflow flag) MIV 0 X
we will focus on flags CY, AC, and P DA X
for now. A discussion of the overflow RRC X
flag is given in Chapter 6, since it RLC X
relates only to signed number arith- SETB C i
metic. How the vat ious flag bits are CLR C 0
uscd in programming is discussed in CPL C X
future chapters in the context of many ANL C,bit X
applications. ANL G;/bit ñI
See Examples 2-2 through 2-4 ORL C,bit X
for the impact on selccted flag bits as ORL C,/bit X
a result of the ADD i'istruction. MOV C,bit X
CJNE X
Note: X can be 0 or 1.

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PP.OC P * ?^ < 51


Example 2-2
Shov. .he status of the Câ, AC, and l• flags after the aJdition of 38H and 2FH in the fol-
lowing instructions.
MOV A,#38H
ADD A,#2FH ;after the addition A=67H, CY=0

SO IU tlO R'
38 00111000
+ 2F_ 00101111
67 01100111

CY = 0 since there is r.o carry beyond the D7 bit


AC = 1 since there is a carry from t!ie D3 to the D4 bit
P = 1 since the accumulator has an odd number of 1s (it has tve 1s).

Example 2-3
Show the status of the CY, AC, and P flags after the addition of 9CH and 64H in the fol-
lowing instructions.
MOV A,#9CH
ADD A,#64H ;after addition A=00 and CY=l

Solution:
.*C 10011100
+ 64 01100100
100 OOOGOOOO

CY=1 since there is a carry beyond the D7 bit


AC=1 since there is a carry from the D3 to the D4 bit
P=0 since the accumulator has an even number of 1s (it has zero 1s).

Examp}e 2-4 ,
Show the status of the CY, AC, and P flags after the addition of 88H and 93H in the fol-
lowing ir.strueiions.
MOV A,#88H
ADD A,#93H ;after the addition A=1BH,CY-1

Solution:
86 10001000
+ 100l00'1
llB 00011011

CY=1 since there is a carry beyond the D7 bit.


AC=0 since there /s no carry from the D3 to the D4 bit.
P=G since the accumulator has an even nulnber of 1s (it has four 1s).
Review Questions
1. The flag register in the 8051 is calleu
2. Wliot is the size of the flag register 'n the 805 l?
3. Which bits of the PS"N register are user-defi nable?
4. Find the CY and AC flag bits for thc following code.
MOV A , 1 0 fi fi!!
RDD A, # 0 l
5. Find the CY and AC flag hits lor the following code.
NOV A, # 0C2 H
I\D D A, # 8 DH

SECTION 2.7: 8051 REGISTER BAI\1I?S A¥!O STACK

The 8051 microcontroller has a total of 128 bytcs of R.PM. I n this section
we discuss the allocation of these 128 bytes of RAM am examine their us ge as
registers and stack.
RAM memory space allocation in the 8051
There are 128 bytes of RAM in the 8051 (Some members, notably the
8052, have 256 bytes of RAM). The 128 bytes of RAM inside the 8051 are
assigned addresses 00 to 7FH. As we will see in Chapter 5, they can be accessed
directly as rr‹emory locations. These 128 bytes are divided into three different
groups as follows.
1. A totai of 32 bytes from locations 7f
0G to IF b.ex arc se: aside for reg- ,
Scratch pad RAM
ister banks arid the stack.
2. A total of 16 bytes from locations 30
20H to 2FH are set aside for bit- 2F "
addressable read/write memory. A Bit-.^.ddressrble RAM
detailed discussion of‘bit-address-
20
able memory and instructions is IF
given in Chapter . Re•_ister Bank 3
A total of 80 bytes from locations i8
30H to 7FH are used for read and 17 Re•_ister Bank 2
10
write storage, or what is normally
0F
cal!ed a scratch pad. These 80 Register 6ank I (stack)
locations of RAM are widely used 08
for the purpose of stoi ing data 07
and parameters by 8051 Register Bank_0
programmers. We will use them in
00 ”
future chap- ters to store data
brougb.t into the
CPU via I/O ports. Figure 2-5. RAM .Allocation in the 8051

Register banks in the 805*.


AS ITlCntioned earlier, a total of 32 bytes of RAM are set aside for the reg-
ister banks and stack. These 32 bytes are divided into 4 banks of registers in which

CHAPTER 2: 8051 ASSEMBLY * ^.N *'* GW T•Hftf2W A MING 53


inch l›.ank has 8 re•*isters, R0 - R7. RAM locations front 0 to 7 are set aside for
bank 0 Of K0 - R7 where R0 is RAM location 0, RI is RAM location l, R2 is
loca- titan 2. and so on, until mets.tory location 7 which belongs to R7 of bank 0.
The sec-
Pitt hank of registers R0 - R7 starts at RAM location 08 and goes to location OFH.
TI› ti ird bank of R0 - R7 starts at iTlemory location l0H and goes to location l7H;
›l1:3 1„ r.AM locations l8H tc I FH are set aside for the fourth bank of R0 - R7.
T!ic following shows how the 32 bytes are allocated into 4 baliks:
Bank 0 Bank I Bank 2 Bank 3
17R7 R7 R6
16R6 1F
15
D 15 RQ l D IC I B
R5 R4 R3
C| ) 14R4 13 R4
BI I R3
A 12 lA
9 Rel 11 Rel 19 1
0 R0 8 R0 10 R0 18 R0

Fi•piirc 2-6. 8051 Register Banks and their RAM Addresses

As we can see from Figure. 2-5, Sank 1 uses the same PPM space as the
stack. This is a majoi‘ problem in programming the 8051. We must either not use
re•_ister bank 1, or we must allocate another area of RAlvi for the stack. This
wiil be discussed be-low.
Example 2-5
Smite tl°.e contents of RAM locations after the following program:

MOV RO,#99H MOV


;load R0 with
Rl,#85H MOV R2,#3FH
value 99HMOV R7,#63H MOV
;load Rl with value 85H
;load R2 with value 3FH
;load R7 with vaiue 63H
;load R5 with value l2H

.At‹ei the execution of the above program we have the following: 14M location 0 b.as value .°

Default register bank


If RAM locations G0 - IF are set aside for the four register banks, which
register bank cf RO - R7 ñ we have access to when the 8051 is powered ii ? The
a.••.› ver is register bank 0; that is, kAM locations 0, 1, 2, 3, 4, 5, 6, anti 7 are
:iccessed with the names R0, Rl, R2, R3, R4, R5, R6, and R7 when programming
‹i:e 8051. It is much easier to refer to these RAM !ocations with names such as
R0, RI, and so on, than by their memory locations. Example 2-6 clarifies this
concep'.
Example 2-6
Repeat Examplc 2-5 using RAM addresses instead of register names.

0 It tlOR •

This is callcd direct addressing mode and uses the RAM address location for the ‹desti-
nation addless. See Chapter 5 for a more detailed discussion of add!cssing modes.

MOV 00,#99H ;load R0 with value 99H


MGV 0l,#85H ;load Rl with value 85H
MOV 02,#3FH ;load Rz with value 3FH
MOV 07,#63H ;load R7 with value 63H
MOV 05,#l2H ;load R5 with value l2W

No\x' !o »v7itch register banks


As stated above, register bank 0 is the default when the 8051 is powered
up. We can s itch to otliei banks by use of the PSW (programs status word) regis-
ter. Bits D4 and D Gf the PSW are used to select the dcsii ed register bank as
Table 2.2: PSYt' Bits Bank Selection Shown in Table 2-2.
RSI (PSW.4) RS0 (rsw.s) The D3 and D4 bits of register
S£fnk 0 0 Q PSW are often reFerr•d to as PSW.4
Bank 1 0 i and PSW.3 since th5y can be accessed
Bank 2 1 0 by the bit-addressable instructions
Bank 3 1 ' SETB and LR. For exarrple, “SETB
PSW.3” will makc PSW.3—1 and select
bank register 1. See Example 2-7.
Example 2-7
State the contents of the RAM locations after the following pi'ogram:

SET2 PSW.4 ;select bank 2


MOV R0.#99H ;load R0 with value 99H
MOV Rl,#85H r'l td Rl with value 85H
MOV R2,#3in ;ioad Rz with value 3FH
MOV R7,#6oH ;load R7 with value 63H
MOV R5,#12H ;load R5 with value 12H

Solution:

By default, PSW.3=0 and PSW.4=0; therefore, the instruction “SETB J7 4” sets


RS1=1 and RS0=0, thereby selecting re•qistei Bank 2. Register bank 2 uses RAM loca-
tions 10H - 17H. After the execution of the above program we have the following:

RAM location l GH has vaiue 99H RAM location HH has value 85H
RAM location 12H has value 3FH RAM location 17H has value 63H
HAM location 15H has value 12H

“•“• • • •• . ?? “• ASSEMBLY LANGUAGE PROGRAMMING 55


Stack in the 8051
The stack is a section of RAM used by the CFU to store information
tem- porarily. This information could be data or an address. The CPU needs
this stor- age area since there are only a limited number of registers.
How stacks are accessed in the 8051
lf the stack is a section of RAM, there must be registers inside the CPU to
point to it. The register used to access the stack is called the SP (stack pointer)
reg- ister. The stack pointer in the 8051 is only 6 bits wide, which means that it
can take values offi0 to FFH. When the 8051 is powered up, the SP register
contains value
07. This means that RAM location 05 is the first location being used for the stack
by the 8051. The storing of a CPU register in 'he stack is called a PUSH, and
load- ing the contents of the stack back into a CPU reg:ster is called a PO-*. In
other words, a register is pushed onto the stack to save it and popped off the stack
to retrieve it. The job of the SP is very critical when push and pop actions are per-
forriied. To see how the stock works, let’s look at the PUSH and POP
instrrictions.
Pushing o»to the stack
In the 8051 the stack pointer (SP) is pointing to the last used location of the
stack. As we push aata onto the stack, the stack pointer(SP) is incremented by one.
Notice that this is different from many microprocessors, notably x86 processors in
which the SP is decremented when data is pushed onto th.e stacK. Examining
Example 2-8, we see that as each PUSH is executed, the contents of the
register are say.red on the stack an‹i SP is incremented by 1. Notice that for
even' oyte of data saved on the stack, SP is incremented only once. Not•ce also
that to push the registers onto the stack we must use their RAM addresses. ’Eor
example, the instruction “PUSH 1" pushes register R1 onto the stack.
Example 2-8
Show the stack and stack pointer for the following. Assume the default stack are
MOV R6,#25H MOV Rl,#l2H MOV R4,#0F3H PUSH’ 6
PUSH 1
PUSH 4-

After PUSH 6After PUSH 1 After PUSH 4


Solution:
OB 0B OB OB

OA 0A 0A “ 0A F3

09 09 09 i2 09 12

08 08 25 08 25 08 25

Start SP = 07 SP = 08 SP = 09 SP = 0A
56
Popping from the stack
Popping the contents of the stack back into a given register is the opposite
process of pushing. With every pop, the top byte of the stack is copied to the reg-
ister specifie‹i by the instruction and the stack pointer is dscrementcd once.
Examp!e 2-9 demonstrates the POP instruction.
Th.e upper limit of the stack
As mentioned earlier, in the 8051 RAM locations 08 to l F can be used for
the stack. This is due to the fact that locations,20 - 2FH of RAh4 are rcserved
for bit-addressable memory and must not be used by the stack. If in a given
program we need more than 24 bytes (08 to IFH = 24 bytes) of stack, we can
chanse the SP to point to RAM locations 30 - 7FH. This is done with the
instruction “NOV
so, sxx•.
Example 2-9
Examining the stack, show the contents of the registers and SP after execution of the
following instructions. All values are in hex.

POP 3 ;POP stack into R3


POP 5 rPOP stack into R5
POP 2 ;POP stack into R2

After POP 3 After POP 5 After POP 2


0B 54 OB OB 0B

0A F9 OA L'A

09 75 09 76 09 76 09

08 6C 08 6C 08 6C 08 6C

Start SP = 0B SP — 0A SP = 09 SP - 08

CAL! instruction and the stack


In addition to using the stack to save registers, the CPU also uses the stack
to save the address of the instruction just below the CALL instruction. This is how
i CPU knows where to resume when it returns ‘. ›m the called subroutine. More
iitiwfliiauon on this wiii be given iii Cihapter 3 wnLi i ›x'e :sciiss .!ie CA I.L instri!c-
tion.
CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 57
Example 2-10
Show the stack and stack pointer for the to!lowing instructiOflS.
MOV SP,#5FH ;make RAM location
60H
;first stack location
MOV R2,#25H
MOV Rl,#l2H
MOV R4,#0F3H
PUSH 2
PUSH 1
PUSH 4

SOlUtlO R:

After PUSH 2 After PUSH l After PUSH 4


'636363

62 62 62F3

61 6112

,60 6025

Stack and Dank 1 conflict


Recall from our earlier discussion that the stack pointer register points to
the current RAbt location available for the stack. As data is pushed onto the
stack, SP is incremented. COilversely, it is decremented as data is popped off the
stack into the registers. The reason that the SP is inciemented after the push is to
make sure that the stacx is grow'ing toward RAivI location 7FH, from !ower
o.ddr•sscs to upper addresses. If the stack pointer were d•cremented after push
instructions, we would be using RAM locations 7, 6, 5, etc. which belong to R7
to R0 of bank 0. the default register bank. This incrementing of the stack pointer
for push instruc- tiGns also ensures that the stack will not reach location 0 at the
bottom of RAM, and consequently run out of space for the stack. However, there
is a problem with the default setting of the stack. Since SP = 07 when the
8051 is powered up, the first location of the stack is RAM location 08 W ii(ih
also belongs to register R0 of register bank 1. In other words, register bank 1
and the stack are using tne same memory space. If in a given program we need
to use register banks I and 2, we can reallocate anothCr section of RAM to the
stack. For example, we can allocate R.’ 4 locations 60H and higher to the
stack as sh n in Example 2-10.
58 '
Review Questions
1. What is the size o1” the SP rcgistcl’’?
2. V'itli cach PUSH instruction, the stack pointer registcr, SP, is
(incremented, decreiTiented) by 1.
3. With each POP instruction, the SP is (incieil cntcd, rlccicnaciatcd)
by 1.
On power-up, the 805.1 uses RAM location as they lii‘st loc‹itioo. of the
stack.
5. On power up, the 8051 uses bank for registers Ft0 - lt7.
6. On power’ r!p, the 8051 uses RAM locations to for i egisters R0
- R7 (register bank 0).
?. Which register bank is used if we alter P S0 and RS I of the PS W by the UI -
!owing two instructions?
S ITS PSU . 3
SETB PSW . 4
8. In Question 7, what R.PM locations are used for register R0 - R7?

SUMMARY

This chapter began with an •xploration of the major i egisteis n•f the 8051,
including A, S, R0, R1, R2, R3, R4, R5, R6, R7, DPTR, and PC. The use of these
registers was d•mor:strated in the context of programming examples. This process
of cieat np an Assembly language program was described from writing the source
file, to asscn.bling it, linking, and executing the program. The PC (program count-
cr) register always points tc the next in.struction to be execute‹i. 4 he way the
805.1 uses program ROM space- was explored because 8G51 Assembly language
pro- grammers must be aware of where programs are placed in ROM, and how
much memory is available.
An Asseiiibly !anguage p!Ogram is compose‹i of a series of statements
that ai e either irish uctions or pseudo-instructions. also called âirc•ctives. lnstl
uctions are tran.slated uy the assembler into machine code. PseudG-instructions
are not translated into machine code: They direct the assembler in how to translate
instruc- tions into machine code. Some pseudo-instructions, called dota directives,
ai‘e used to define data. Data is allocated in byte-size increments. T!ie data can be
in bina- ry, hex, decimal, or ASCII formats.
Flags are useful to programmers since they indicate certain conditions,
such as carry or overflow, that result from execution of instructions. The stack is
used to store data temporarily dtii‘ing execution of a program. The stack resides in
the RAM space of the 8051, which was diagrarptned and explained. Manipulation
of the stack via POP and PUSH instructions was also explored.

CHAPTER 2: 8051 ASSEMBKi iJ uAGr. MMING 59


PROBLEMS
SECTION .l: INSIDE THE 8051

l. Most registers in the 8051 are bits wide.


2. Registers R0 - R7 are all bits wide
3. Ftegisters ACT“ and B are bits wide.
4. Name a 16-bit register in the 8051.
5. To load R4 with the value 65H, the pound sign is (necessary,
optional) in the instruction ”MOV R4 , # 65H".
6 \Vliat is the result of the following code and where is it kept?
MOV A,#l5H
MOV R2,#l3H
ADD A,R2
7. Which of 'he following is (are) illegal?
(a) MOV R3,#5OO (b)MOV Rl,#50 (c)MOV R7,#O0
(d)MOV A,#255H (e)MOV A,#50H (Q MOV A,#F5H
(g)MOV R9,#5OH
8. *.Vhich of the following is (are) illegal?
(a) ADD R3,#50H (b)ADD A,#50H (c) ADD R7,R4
(d) ADD A,#255H (e)ADD A,R5 ( ADD A,#F5H
(g) ADD R3,A
9. What is the result of the following code and where is it kept?
MOV R4,#25H
MOV A,#lFH
ADD 4,R4
10. What is the result of the following code and where is it kept?
MOV A,#l5
MOV R5,#l5
ADD A,R5

SECTION 2.2: INTRODUCTION TO 5051 ASSEMBI.Y PRGGRANIMING and

SECTION 2.3: .ASSEMBLING AND RUNNING AN 8051 PROGRAM

11. Assembly language is a (low, high) level language while C is a


(!ow, high) level language.
Of C and Assembly language, which is more efficient in terms of code gen.er-
ation (i.e., the amount of ROM spase it uses)?
1 . Which program produces the "obj" file?
14.
Trust or false. The source file has the extensioir "src" or "asm".
15.
Which file pro ’ides the listing of error messages?
16.
True or fi!lse. The source code file can be a non-ASCII fi!c.
17.
TFUC OF ill lse. Every source file must have ORG and ENl' directives.
18.
Do the ORG and END directives produce opcodes?
19.
Why are the ORG and END directives also called pseudocode?
20.
True or false. The ORG and END directives appear in the ".lst" file.

60
SECTION 2.4: THE PROGRAM COUNTER AND ROM SPACE IN ’HSE 5051

2 i. Every 8051 family member wakes up at address when it is powered up.


22. A grammer puts the first opcode at address l OOH. What happens siren
the microcontroller is powered up?
23. Find tb.e number ot bytes each of the following instructions
take. (a)MOV A,#55H (b) MOV R3,#3 (C)INC R2
(d)ADD A,#0 (e)MOV A,Rl (f)MOV R3,A
(g) ADD ñ,R2
24. Pick up a programs listing of your choice, and show the ROM inenioi‘y address-
es and their contents.
25. Find the address of the last location of on-chip ROM for each of the follow-
ing.
(a) DS5000-l 6 (b) DS5000-8 (c) DS5000-32
(d) AT89C52 (e) 8751 (f) AT89C5 l
(g) DS5000-64
26. Show the lowest and highest values (in hex) that the 5051 program counter can
take.
27. A gix'en 8051 has 7FFFH as the address of its last loc'ation of on-chip
RO›Xi. What is the size of on-chip ROM for this 8051?
28. Repeat Question 27 for 3FFH.

SECTION 2.5: 8051 DATA T”fPES AND DIRECTIVES

29. Compile and state the contents of each COM location for the following data.
OR? 200?
MYDAT 1: Db “Earth”
MYDAT 2: DB “987-65”
MYDAT 3: DB “GABEH 98”
30. Compile and state the contents of each ROM location *or the following data.
ORG 340H
DAT 1: D0 22,56H,10011001R, 32,0F6H, l1I1lp¿¿p

SECTION 2.6: 8051 FLAG BITS AND THE PSW REGISTER

31. The PSW is a(n) -bit register.


32. Which bits of PSW are used for the Uâ" and AC flag bits, respectively?
33. Which bits of PSW are used for the OV and P flag bits, respectively?
34. In the ADD instruction, hen 1s CY raised?
35. In the ADD instruction, is°1ien is AC raised?
36. What is the value of the CY flag after the fdllowing code?
CLR C ;CY = 0
CPL C ;complement carry
37. Find the CY flap ' attic Tter each of the following codes.
{u, MO. A #°>B (b)MOV A,#00 (c) MOV A,tz50
ADD A,#0C4H ADD A,#0FFH IDP A,fO5
38. Write a simple program in which the value 55a is added 5 times.

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 61


SECTION' 2.7: 8051 REGISTER BANKS AND STACK

39. Which bits of the PS'N are responsible for selection of the register banks?
40. On power up, what is the location of t1< first stack?
41. In the 8051, which register bank conflicts with the stac!:?
42. ln the 8051, what is the size of the stack pointer (SP) register?
43. On power up, which of the register banks is used ?
44. Give :he address locations of RAM assigned :o various banks.
45. Assuiiiing the t!se of bank 0, find at what R.PM location each ot’ the following
lines stoi cd the data.
(a) MOV R4 , # 32 H (b) MOV RO , # 12 H
(c)MO\ R7,#3FH (d)MOV E5,#55H
46. RepeotProbem45 forbank 2.
47.ARerpowcrupshowl:owtose)ectbank2whhasngeinsWucton
48. Showthesackandsackp
onerforeachWneofthefolowingpog am. ORG 0
MOV RO,#66H
MOV R3,#7FH
MOV R7,#5DH
PUSH 0
.USM u
PUSH 7
CLR A
14OV .3,L
MOV R7,A
PGP 3
PG P 7
POP 0
49. In Problem 45, does :he sequence of POP instructions restore the original
val- ues of registers R0, R3, and R7? If not, show the correct sequence of
ins'ruc- tiois.
50. Sho the stack and stack pointer for each iine of the following profi tin.
ORG 0
MOV SP,#70H
MOV R5,€66n
MOV R2,#7FH
MOV R7,#5DH
PUSH 5
PUSH 2
PUSH 7
CLR A
MOV R2,A
MOV R7,A
POP 7
POP 2
AñiSWERS TO REVIEW Qi?ESTIOfidS
SECTION 2.\: INSIDE 1”NE 803t

I. MOV A,#34H
MOV B#3FH
ADD A,B
2. MOV A,#I GH
ADD A.//0CDI I
MOV R2,A

4., Fl° hex an.d 255 in dcciiiial


5. 8

SECTI ON 2.2: INTPxODUCTlON TO 8051 / SSEiHBLY PROGRAf•4!›4 ING

1. The real work is performe‹i by instructions such as MOV and ADD. Pseudo-instructions, also
called assembly directives, instruct the assembler in doing its job.
2. The instruction mnemonics, pseudo-instructions
3. False
4. All except (c)
5. Assembler directive
6. True
7. (c)

SECTION 2.3: ASSEMBLING AND RUNNING AN 8051 PROGR.4N'

I . Ti”ue 2. True S.(a) 4. (b) and (d) 5. (d)

SECTION 2.4: THE PROGRAM COUNTER #.ND ROM SPACE IN THE 8051

l. 16 2. True 3. OOOOH 4. 2
5. With SK bytes. we have S192 (8 x 1024 = 8192) bytes, and the RO4I space is 0000 to I FFFH.

S ECTION! .5: **51 D.4T.4 T\ P E?s AND Ci I RECT!

VES 1. DB 2. 7
3. If the value is to be changed tater, it can be done once in one place instcad of at every occur-
rence.
4. (a) 4 bytes (b) 7 bytes
5. This places the ASCII values for each character in memory locations starting at 200H. Notice
that at l values are in hex.
200 = (4! )
20 l = (42)
202 = (43)
203 = (3 I)
204 = (32)
205 = (33)

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 63


SECTION 2.6: 805 I FL.^.G BITS AND THE f•SW REGISTER

1. PSW (program status register) 2. 8 bits


3. D I and D5 which are referred to as PS¥V.1 and PSW.3, respectively.
4.
Hex binary
rr llll llll
+ 1
UO 100 00 0000 This leads to CY= I and .'\C= I
5.
Hex binary
C2 1100 0010
+ 3D + 0011 llll
FF llll llll
Tiiis leads to CY = 0 and .DC = 0.

-SECTION 2.7: 8051 REGISTER BANKS AND STACK

1. 8-bit 2. Incremented 3. Decremented


4. 08 5. 0 6. 0 - 7
7. P.egister bank 3
8. RAM locations 18H to lFH
Y°HAPTER 3

&ND C&kL
INSTRUCTIONS

OBJECTIVES

Upon completion of this chapter, you will be aole to:

»> Code 8051 Assembly language instructions using loops


code 8051 Assembly language conditional jump instructions Explain conditions that
Code short jump instructions for unconditional shoi4 jumps Calculate target addresses
Code 8051 subroutines
Describe precautions in using the stack in subroutines Discuss crystal frequency versus
Code 8051 programs to generate a time delay

65
In the sequence of instructions to be executed, it is often nec-•ssary to trans-
fer program control to a different location. Thetc are niany instructions in the
8051 to achieve this. This chapter covers the control transfer instructions
available in 805 Assembly language. In the first section we discuss instructions
used for loop- ing, as well as instructions ror conditional and unconditional
jumps. In the second section we examine CALL instructions and their uses. In
the third section. time
delay subroutines are described.

SE(?TION 3.1: LOOP ANO JUMP INSTRUCTIONS

!n this section we first discuss huw to performs a looping action in the 8051
and then talk about jump instruction is, both conditional and unconditional.
Looping in the 8051
Rcpeating a sequence of instructions a certain number of times is called a
looD. The loop is one of most widely used actions that any microprocessor per-
forms. In the 5051, the loop action is performed by the instruction “DJNZ req,
l aLe1”.In this instruction, the register is decreniented; if it is not zero, it jumps
to the target address referred to by the label. Prior to the start of the loop the reg-
ister is loaded with the counter for the number of repetitions. Notice that in this
instrtiction both the register decrement an‹i the decision to jump are combined
into a single instruction.
Example 3-1
Wi ‹te a program to
(a) clear ACC, then
(b) add 3 to the accumulator ten times.

Soliition:

;This program adds value 3 to the ACC ten times

;A=0, c3ear ACC


MOV R2,#10 ;load counter R2=l0
AGAIN: ADD A,#03 ;add 03 to ACC
DJNZ R2,AGAIN ;repeat until R2=0(10 times)
MOV R5,A ;save A in R5

In the program in Example 3-1, the R2 register is used as a counter. The


counter i5 first set to 10. In. each iteration the instruction DJNZ decrements R2
and cheeks its value. If R2 is not zero, it jumps to the target address associated
with labc-1 “AGAIN”. This looping action continues until R2 becomes zero.
After R2 be. ones zero, it falls through the loop and execril.: tire instruction
immediately below it, in this case the “NOV R5, A” instruction.
Notice in the DJNZ instruction that the registers can be any of R0 - R7.
The counter can also be a RAM location as we will see in Chapter 5.

66
Example 3-2
What is the maximum number of times that the !oop in Example 3-1 can be repeated?

Solution:

Sincc R2 holds the count and R2 is an 8-bi‹ •s'slei, it can hold a rnaximuni of FFU
(255 decimal); therefore, the loop can be repeated a iiiaxiirtiin of” 256 times.

Loop inside a locp


As shown in Example 3-2, the inaxiivtiiTl count is 256. What happens if’we
want (o repeat an action more :ilues than 256? To do that, we use a loop inside a
loop, which is called a neste.^l loop. I n a nested loop, we use two registers to hold
the count. See Example 3-3.

Example 3-3
Write a program to (a) load the accumulator with the value 55H, and (b) complement
the ACC 700 times.

solution:

Sauce 700 is larger than 255 (th.e maximum capacitv of any register), we use two
regis- ters to hold the count. The tollow'ing code shows how to us•- Rz and R3 for the
count.

51OV L,#.9 ñ ;A=5SH


MOV R3,#l0 ;R3=10, the outer loop count
NEXT: MOV R2,#70 ;R2—70, the inner count
AGAIN: CPL A ;complement A register
DJNZ R2,AGAIN ;repeat it 70 times (inner loop)
DJNZ no,NEXT

In this program, R2 is used to keep the inner loop count. In the insti’UG(iOlI "DJl9 Z
R2 , ACA I N”, whenever R2 becomes 0 it falls through and “DIN Z R , NEXT” is exe-
cuted. This, instruction forces the CPU to load R2 with the count 70 and the inner loop
starts again. This process will continue until R3 becomes zero and the outer loop is fiil-
ished.

Other conditional jumps


Conditional jumps for the 8051 are sulnniai'ized in T.ibie 3-1. More details
of each ir 'i uction arc provided in Appendix A. In Table “ , notice that solne of
the instructions, such as JZ (juirip if A = zero) and .IC (jrn ii if cariy‘j, jump only
i• a cci main coiiuiiion is met. iNex: w e..a*•.'Fi* SO!3*U r'nny it renal jiinip
instructions with examples.

CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS 67


JZ (jump if A -- 0)
In this instruction the content of register A is checked. If it is zero, it
jumps to the target address. For example, look at the following code.

NO*/ A, R0 ; h=R0
JZ OVER ;jump if A = 0
MOV A,Rl ;A=Rl
JZ . OVER ;jump if A = 0

OVER:
Table 3-1: 8051 Conditional Jump Instructions
In this program, if either Instruction
Action' .....
R0 or R1 is zero, it jumps to the JZ
Jump if A = 0
label OVER. Notice that the IZ JNZ Jump if A 0
instruction can be used only for Decrement and jump if A z
DJNZ
é Jump if A byte
register A. It can only check to CJNE A,byte
Jump if byte #data
see whether the accumulator is CJNE
Jump if CY = 1
reg,#data zero, and it does nct apply to any JC
Jump if CY = 0
other register. More importantly, INC
Jump if bit = 1
you don't have to perform ;jjj JB
Jump if bit = 0
arithmetic instructions such as
Jumo if bit — i and clear bit
JNB decrement to use the JNZ instruc-
ABC tion. See Example 3-4.

Example 3-4
\Vrite a program to determine if n5 contains the value 0. If so, put 55H in ii.

Solution:
MOV A,R5 ;copy R5 to A
JNZ NEXT ;jump if is not zero
MOV R5,#55H
NEXT:

JNC (jump if no carry, jMJ7?R^ if CY -- 0)


In this instruction, the carry flag bit in the flag (PSI*.*) register is used to
make the decision whether to jump. In executing “JNC l abe l”, the processor
lOGks at the carry flag to see if it is raised (CY = 1). If it is not, the CPU starts to
fetch and execute instructions from the address of the label. If CY = 1, it will not
jum.p but will execute the next instruction below ›WC.
It needs to be noted that there is also a “JC la be l” instruction. In the JC
instruction, if CY = 1 it jumps to the target address. We will give more examples
of tb.ec•e inst u ons in the context of applications in future chs! :-rs.
There is .ilso a JB (jump if bit is high) and JNB (jump if bit is low). These
are discussed !n C*.aptars 4 arid fi wiien bit manipulation instructions are dis-
cussed.

68
Example 3-5
Find the sum of the values 79H, F5H, and E2H. Put the sum in registers R0 (low byte)
and R5 (high byte).

Solution:

MOV A,#0 ;clear %(A=O)


MOV R5,A ;clear R5
ADD A,#79H ;A-0+79H=79H
JNC N i :if no carry, add next numbwr
INC R5 ;if CY=l, increment R5
11 l: ADD A,#0F5H ;A=79+F5=6E and
CY=l JHC N_2 ;jump if CY=0
INC R5 ;If CY=l then increment
R5(R5=l) N 2: ADB A,#0E2H ;A=6E+E2=50 and CY=1
JNC OVER ;jump if CY=0
INC R5 ;if CY=l, increment 5
OVER:MOV R0,A ;Now R0=50H, and
R5=02

All conditiona! jumps are short jumps


It must be notcd that all conditional jumps are short jumps, meaning that
:he addiess of the target must bc within —128 to 127 bytes of the contents of the
program counter (PC). This very important concept is discussed at the end of this
section.
Linconditional jump instructions
The unconditional jump is a jump in which control is transferred
uncondi- tionally to the target location. In the 803 l there are two unconditional
jumps: LJMP (long jump) and SJMP (short jump). Each is d:scussed below.
LJMP (lo. g jump)
LIMP is an unccnditional long jump. It is a 3-byte insti'tiction in which
the fitst byte is the opcode, and the second and.third bytes represent the l 6-bit
address of the target location. The 2-byte target address allows a jump to any
memory loca- tion fioin 0000 to FFF FH.
Remember tnat although the program counter in the 8051 is l 6-bit, there-
by giving a ROM address space of 64K bytes, not all 8051 fam.ily members have
that much on-chip program ROM. The orig na1 8051 had only 4K bytes of on-
chip ROM for program space; consequently, every byte was precious. For this
reason there is also a SJMP (short jump) instruction whicii is a 2-byte instruction
as opposed to Hoc 3-byte LJMP instruction. This can save some bytes of memory
in iiiany appllcations where m‹ :.cry space is in short supply. SJMP .s discussed
xt.
SJIfiP (short jump)
In this 2-byte instruction, the first byte is the opcode and the second byte
is the relative address of the target location. The relative address range of 0(l -
FFH
CHAPTER 3: .HAMP, LOOP, AND CALL INSTRUCTIONS 69
is diviJed into for.:ard and backward jumps; that is, within — l 2ii to +127 bytes
of memory relative to the address of the *'irrent PC (progralii counter). If the
jump is forward, the target address can be within a space of 127 bytcs from the
current PC. If the target address is backward, the targct address can be within —128
bytes front the current PC. This is explained in detail nexl
Calculating tile short jump address
In addition to the SJfvlP insti u*tion, all conditional jumps such as INC, JZ,
and DJNZ are also short jumps due to the fact that they ai e all two-byle instruc-
tions. In these instructions the first byt* is the opcode and the second byte is the
i‘elative address. The target address is relative to the value of the program. cot!nter.
To calculate the target address, the second byte is added :o the PC of the instruc-
tion immediately below the jump. To un‹ierstand this, look at Example 3-6.

Example 3-6
Using the following list file, verify the jump forward address calculation.

Zlzze *C Xcode
01 0000
02 00 0 0 7800 MOV R0,#0
03 0 0 02 7455 MOV A,#55H
04 0004 60 03 JZ NEXT
05 0006 06 INC R0
06 0007 04 AGAIN: INC A
07 0006 04 IKC A
08 0009 2477 NEXT: AND A,#77h
09 OOOA 5005 JNC OVER
10 OOOD E4 CLR A
11 OOOE F8 MOv R0,A
12 OOOF F9 MOV Rl,A
13 0010 FA MOV R2,A
14 0011 FB MOV R3,A
5 0 01 2 2B OVER: ADD A,R3
16 0013 50F2 JN AGAIN
17 0015 80FE hERE: SJMP HERE
END

SOlutiOR°

First notice that the JZ and INC instructions both jump forward. The target address
a forward jump is calculated by adding the PC of the following instruction to the si
ond byte of the short jump instruc:ion, which is called the relative address. In line 4 i
instruction “JZ NEXT” has opcode of 60 and operand of 03 at the addresses of 0004 i
0005. The 03 is the relative address, relative to the address of the n•xt instruction P
R0, which is 0006. By adding 0006 to 3, the target address of the label NEXT, w,lHcl
0009, is generated. In the same way for line 9, the “INC OVER” instruction has oper
and operand of 50 and /15 where 50 is the opcode and 05 the relative adc!' ass.
Therefi 05 IS ñ€lded to i)00D, I!. aadress of instruction “CLR A”, giving l2H, ilie
address label OVER.

70
Example 3-7
Verify the calculation of backward jumps in Example 3-6.

S0llltlO£l l

In that program list, “JNC AGAIN” has opcode 50 and relative address F2H. When
the relative address of F2H is added to l 5H, the address of the instruction below the
jump, we have 15H + F2H = 07 (tlie carry is di opped). Notice that 07 is the address
o* label AGAIN. Lcok also at “S AMP HERE”, which has 80 and FT for the opcode
and rela- tive address, respectivcly. The PC of the following instruction, 0017H, is
added to FEH, the relative address, to get 0015H, address of the HERE label (l7H +
FEH = l 5H). Notice that FñH is —2 and 17Fi + (—2) = 15Fi. For further discussion
of the addition of negative numbers, see Chapter 6.

Jump backwarJ target address calculation


While in the case of a forward jump, the displacement value is a positive
number between 0 to 12/ (00 to 7F in hex), for the backward jump the displace-
ment is a negative value of 0 to —128 as explained in Example 3-7.
It must be emphasized that regardless of whether the SJMP is a forward
or backw'ard jump, for any shcrt jtiinp the address of the target address can never
be more than —128 to +127 bytes mom tb.e address associated with the
instruction below the SJMP. If any attempt is made to violate this rule, the
assembler will gen- erate an error stating the jump is out of range.
Review Qaestlons
1. The mnemonic DJNZ stands for
2. True or false. “DJNZ R5, B.ACK” combines a decrement and a jump in a
sin- gle instruction.
3. “J<.0 HERE” is a -byte instruction.
4. In “AZ NEXT”, which register's content is checked to see if it is zero? I
5. LIMP is a -byte instruction.

SECTION 3.2: CALL INSTRUCTIONS

Another control transfer instruction is the CALL instruction, which is


used to call a subroutine. Subroutines are often used to perform tasks :hac need to
be performed frequently. This makes a program more structured n addition to
saving memory space. In the 8001 thei'e aie two instructions for call: LCALL
(long call) and ACALL (absolute call). Deciding which one to use depends on the
target address. Each instruction is explained next.
LCALL (long call)
In this 3-byte instruction, the fii‘st byte. is the opcode and the second and
thiid bytes are used for the address of the target subroutine. Therefore, LCALL
can be used to call subroutines located anywhere wlthiii the 64K byte address
space of

CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS 71


the 805 l. To make sure that afier execut!on of the called subroutine the 8051
knows where to come back to, it automatically saves on the stack the address of
the instruction immediately below the LCALL. When a subroutine is called,
con- trol is transferred to that subroutine, and the processor saves the PC
(program counter) on the stack and iiegins to fetch instructions from the new
1oca(ion. After finishing execution of the subicutine, the instruction RET (retui
n) transfers con- trol back to the caller. Every subroutine needs RET as tlic last
instruction. See Example 3-8.
The following points should be noted for the program in Example 3-8.
1. Notice the DELAY subroutine. Upon eKecuting the first “LCALL DE
LRY”, the a‹idress of the instruction right below it, “ IOV A, I OAAH”, is
pushed onto the stack, and the 8051 starts to execute insiructions at address
300H.
2. In the DELAY subroutine, first the counter R5 is set to 255 (R5 = FFH);
there- fore, the loop is repeated 256 times. When R5 becomes 0, control falls
to the RET instruction which pops the address from the stack into the program
count- er and resumes executing the instructions after the CALL.
Example 3-8
Write a program to toggle all the bits of port l by sending to it the x'alues 55H and
AAH continuously. Put a time delay in between each issuing of data to port 1. This
program will be used to test the ports of the 8051 in the next chapter.

Solution:

OPG 0
bACK: MOV A,#55H ;load A with SSH
MOV Pl,A ,send SSH to port 1
LCALL DELAY ;time delay
MOV A,#JAAH ;load A 'with AA (in hex)
MOV, Pi,A ;send AAH to port 1
LCALL DELAY
SJMP BACK ;keep doing this indefinitely
; his is the delay subroutine
ORG 300H ;put time delay at address 300H
DELAY: i£OV R5,#0EFH :R5=255(FF in hex), he counter
AGAIN: DJNZ R5,AGAIN ;stay here until R5 becomes 0
RET ;return to caller (when R5 = 0)
END ;end o'f asm file

The amount of time delay in Example 3-8 d.•pends on the frequency of


the 8051. How to calculate the exact time will be explained in detail in Chapter 4.
However you can incr•ase the time delay by using a nested loop as shown below.

DELAY: rnested loQp delay


MOV R4,f255 rR4'255(FF in hex)
NEXT: MOV R5,#255 ;R5=255(FF in hex)
114: DJ''? R5,AGP. ’ ;stay here until R5 becomes C
DJNZ R4,NEXi ;decrement R4
;keep loading R5 until R4=0
RET ;return (when R4 = 0)

72
CALL instruction and the role of the stack
The s: ck and stack pointer were covered in the last chapter. To
understand the importance of the stack in microcontrollers, we now examine the
contents of the stack and stack pointer for Example 3-8. This is shown in
Example 3-9.
example 3-9
Analyze the stack contents after the execution of the first ICC.4LL in the fol1cw'ing.

Sslutior:

001 0000 ORG 0


02 0000 7455 bACK: MOV A,#55H ;load A with SSH
03 0002 F590 MOV P1,A ;send SSH to port l
004 0004 120300 LCALL DELAY ;time delay
005 0007 74AA MOV A,#0AAH;load A with AAH
005 OOOS F590 MOV Pl,A ;send AAH to port 1
’007 OOOB 120300 LCALL DELAY
008 OOOE 80F0 SJMP BACK ;keep doing
this 009 0010
010 0010 ; this is the delay subroutine
011 0300 ORG 300H
012 0300 DELAY:
013 0300 7DFF MOV R5,#0BFH ;R5=255
14 0302 DDFE AGAIN: DJNZ R5,AGAIN ;stay here
15 0304 22 RET ;return to caller
16 0305 END ;end of asm file
When the rirst *ACALL is executed, the address of the instruction.
“MOV R, # ORAH” is saved on the stack. Notice that the low byte 0A
*res first and the !iigh byte is last. The last instruction of the cal!ed
subroutine must be a RET instruc:ion which directs the CPU to ()9
00
POP the top bytes of the stack into the PC and resume executing
08 07
at address 07. The diagram shows the stack frame after the
first LCALL.
SP = 09
iJse o? PUSH and POP instructions in subroutines
Upon calling a subroutine, the stack keeps track of where the CPU should
return after completing the suoroutine. For this reason, we must be. very careful
ia any manipulation of stack contents. The rule is that the number of PUSH and
POP instructions must always match in any called subroutine. In other words, for
every PUSH there must be a POP. See Example 3-10.
Calling subroutines
In Assembly language programming it is common to have one main pro-
gram and many subroutines that are called from the iriain program. This allows
you to make each subroutine into a separatc module. Each module can be tested
seyn.--*ct grid tin, kr .¿** 'oae‹ho• *•• *h the :.a.in program. More importantly,
in a large program the modules can be assigned to different programmers in order
tu shorten development time.
CHAPTER 3: JUMP, LOOP, AND CALL INSTRUC IONS 73
Example 3-10
Analyze the stack for the first LCALL instruction in the following program.

01 0000 ORG 0
02 0000 7455 BACK: MOV A,#55H ;load A with SSH
03 0002 F5S0 MOV P1,A ;send SSH to port 1
04 0004 7C99 MOV R4,#99H
05 0006 7D67 MOV’ R5,#67H
06 0008 120300 LCALL DKLAY ;time delay
07 OOOB 74AA MOV A,#OAAH ;Load A with AA
08 OOOD F590 MOV P1,A ;send AAH to port l
09 OOOF 120300 LCALI DELAY
10 0012 80EC SJMP BACK ;keep doing this
11 0014 ; this is the delay subroutine
12 0300 ORG 300H
13 0300 C004 DELAY:PUSH 4 ;PUSH R4
14 0302 C005 PUSH 5 ;PUSH R5
15 0304 7CFF MOV R4,#0FFH ;R4=FFH
16 0306 7DFF NEXT: MOV R5,#0FFH ;R5=255
17 0308 DDFE AGAIN:DJNZ R5,AGAIN
18 030A DCFA DTNZ R4,NEXT
19 030C D005 POP 5 ;POP INTO R5
20 030E D004 POP 4 ;POP INTO R4
21 0310 22 RET ;return to caller
22 0311 END ;end of asm file

Solution:

First notice that for the PUSH and POP instructions we must specify the direct address
of the register being pushed or popped. Here is the stack frame.

After the first LCAI.L After PUSH 4 After’ PUSH 5

0B OB 0B 67 R5

0A OA 99 R4 0A Qq *

09 00 PCI I 09 00 PCH 09 oo PCH

08 0B 08 0B PCL 0B PCL
PCL

It needs to be emphasized tbyt in. i!Sir! I.CALL, the target addi‘•ss of ine
subroutine can be anywhere within the 64K bytes lnemory space of the 8051. This
is not the case for the other call instruction, ACALL, which is explained next.

74
;MAIN program calling subroutines
0
ORG TCALL LCALL
MAIN: SUBR_1 SUBR_2
*UBR 3
LCALL

H EP.E : SJMP HERE


and of MAIN

SUBR l:

RET
end of subroutine l

SLBR 2:

RET
end of subroutine 2

RET
end of subroutine 3
END ;end of the asm file
Figure 3-1. 8051 .Assembly Main rogram Tiiat Cal!s Subroutines
ACAL! (absolute call)
ACALL is a 2-byte instruction in contrast to LCALL, which is 3 bytes.
Since ACALL is a 2-byt• instruction, the target address of the subroutine must be
within 2K bytes address becat‹se only 11 bits of the 2 bytes are used ior the
address. There is no difference between .ficALL and LCALL in terms of
saving the progiam cGunter on the stack or the Function of tne RET instruction.
l'he oniy difference is that the target address for LCALL can be anywhere within
the 64K byte address space of the 8051 while the target address of A TALL
must be with- in a 2K-byte range. In many variations of the 8051 marketed by
different compa- nies, on-chip ROM is as low as lK bytes. In such cases, the use
of ACALL instead of LCALL can save a number of bytes of program ROM
space.
Example 3-11
A developer is using the Atmel AT89C1051 microcqntroller chip for a product. This chip has only lK b

Solution:
The ACALL instruction is more useful since it is a 2-byte instruction. It saves one byte each ilme the c
CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS 75
Of course in addition to us.ng compact instructions, we can program
effe- ciently by having a detailed knowledge of all the instructions supported by
a given microprocessor, and usi•s them. » isely. look at E.xample 3-12.

Example 3-12
Rewrite Example 3-8 as efficiently as you can.
TO111 tlO fI•
OR0
MOV A,#55H
;load A with SSH
BACK. :MOVPl,A ACALL RELAY CPL value
;issue A in reg A to port 1
SJMP BACK ;time delay
;complement reg A
;keep doing this indefinitely
, this is the delay subroutine
DELAY:
AGAIN: ;R5'2/5(FF
MOV R5,#0FFH DJNZ R BAG INinRET
hex),the counter
END ;Stay here until R5 becomes 0
;return to caller
;end of asm file
h!otice in this program that register A is set to 55H. By complementing 55H, we havl AAH; a

Rex•iew questions
1. \\*hat do the mnemonics “LCALL.” and “ACALL” stand for?
2. True or false. In the 8051, control can be transferred anywhere within the
64K bytes of code space if using the LCALL ihstruction.
3. How does the C.>U know where to return to after execr:ting the RET instruc-
tion?
4. Describe briefly the function of the RET instruction.
5. The LCALL instruction is a -byte instruction.

SECTION 3.3: TIME DELAY GENERATION AND CALCULATION

In the last section we used the DELAY subroutine. How to generate vari-
ous time ‹relays and calculate exact delays is discussed in this section.
Machine cycle
FO!’ the CPU to execute an instruction takes a certain number of clock
cycles. I :1ie 805! family, tb.ese clock cyc1•s are referi‹ ‹! to as niac.hine cycles.
Appendix .fi.2 provides the list of 8051 instructions and iiicir machine cycles.
To calculate a time delay, we use this list. In the 8051 family, the length of the
machine cycle depends on the frequency of the crystal oscillator connected to the

76
505 I systeiii. The crystal oscillator, a!o1ig with on-chip circuitry, iii'oi !dc the clock
source for the 8051 CPU (see Chapter 4). The frequency of the crystal connected
to the 8051 family can vary from 4 MHz to 30 MI Iz, depending on the chip
rating and manufacturer. Very often the I 1.0592 MHz crystal oscillator is used to
wake the 8051-based system compatible with the serial port of the I BM PC (see
Chapter 10). In the 8051, one inachin• cycle !asts 12 oscillato pericds. Therefore,
to cal- culate the machine cycle, we take 1/1 2 of the ci)'sta! freqiic-iicy, tlicn
take its inverse, as shown its Example 3-13.

The following shows crystal frequency for three different 8051-based systems. Find the
p.eriod of the machine cycle in each case.
(a) i l .0592 MHz (h) 16 MHz (c) 20 MHz

SOIUtIOR •

(aJ11.0592/12 = 921.6 kHz; machine cycle is 1/921.6 kHz = 1.085 ps (rriicrosecor.d)


(b) 16 MHn'l2 — l.33c MHz; mach.ine cycle (MC) = 1/.1.333 MNz — 0.75
p.s (c1 20 ñ.4Hz/12 = 1.66 MHz; LIC = 1/1.66 MHz = 0.60 us

Example 3-14
For an 8051 system of i 1.0592 MFz, find how long it takes to execct•. ea*h of the fol- lowing instructio

) V R3,#55 (b) DEC R3 (c)DJNZ R2,target


(a) LJMP () SJMP (f) NOP (no operation)
(g) 'UL AB

Solution:

the machine cycle for a system of 11.0592 MHz is 1.085 qs as shown in Example 3-
13. Table A-1 in AppCndix A sho›''s machine cycles for eacn of the above instructions. Therefore, we h

Rme to execute

(a) MOV R3,#55 lxl.085 ps =


1.085 ps
(b) DEC R3 l lxl.085 ps -
1.085 ps
(c) DJNZ R2,targec 2 2 1.085 ps =
2.17 ps
d) LJMP 2 2x1.085 ps =
2.17 ps
(e) SJMP 2 2^l.0"? ?.I- ‹.
(Q MOP 1 lxl.08s ps =
1. ps
85
(g) MUX AB 4 4x1.085 ps = 4.34 ps

CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS 77


Delay calculation
As seen in the last section, a delay subroutine consists of two parts: (1) set-
ting a counter, and (2) a loop. Most of the time delay is performea oy the body
of the loop, as shown in example 3-15.

Example 3-15
Find the size of the delay in the following program, if the crystal frequency is 11.0592
MHz.

MOV A,#55H
AGAIN: MOV Pl,A
ACALL DELAY
CPL A
SJMP AGAIN
r --Time delay
DELAY: MOV R3,#200
HERE : DJNZ R3, i-tERE
RET

Solution:

From Table A-1 in Appendix A, we have the following machine cycles for ea.ch instruc-
tion of the DELAY subroutine.
WacIn:Lne gcse
DZLA'f: MOV R3,#200 l
HERE: DJNZ R8,HLRE 2
RET

Therefore, we have a time delay of [(200 2) + 1 + 1] x 1.085 qs = 436.17 gs.

Very often we calculate the time delay based on the instructions inside the
loop and ignore the clock cycles associated with the insu uctions outside the loop.
In Example 3-15, the largest value the R3 register can take is 255; there-
fore, one way to increase the de!ay is to use NOP instructions in the
loop..NCiP, which stands for “no operation,” simply wastes time. This is shown in
Example 3- i6.

Low p \‹nside loop delay


Another » y to get a large delay is to use a loop inside a lo ›,-. which is
also called a nested /ooy›. See Example 3-17.

78
Example 3-16
Find the time deiay for the following subroutine, assuiiiiiig a crystal frequency of
11.0592 MHz.

DEIAY: MOV R3,#250

HERE: ?TO°
NOP 1
NOP 1
NOP 1
DJNZ R3,HERE 2

RET 1

SOlutiOn:

The time d•1ay inside the HERE loop is [250 (1+ l + l +1+2)] 1.065 gs = 1500 x
1.085 gs = 1627.5 gs. Adding the two instructions outside the loop we ha've 1627.5 qs
+2x
1.085 g s = 1629.67 qs.

Example 3-17
For a m chine cycle. of 1.085 is, find the time delay in the following subroutine.

DELAY: Mach:ine C e
MOV R2,#200 1
AGAIN: MOV R3,#250
HERE: NOP 1
NOP
DJNZ R3,HERE 2
. DJNZ R2,AGAIN 2
RET 1

For the HERE loop, we have (4 250) 1.085 is = 1085 gs. The AGAIN ‘loop repeats
the HERE loop 200 times; therefore, we have 200 1085 qs — 217000, if we do not
include the overhead. However, the- instructions "MO*/ R3, 4 2 50" and "DJNZ
R2 , AGA.I N" at the beginning and end of the AGAIN-loop add (3 . 200 1.085 qs) —
651 qs to the time delay. As a result we have 217000 + 65 l = 21765 l t‹s = 217.651
mil- liseconds for total time delay associated with the above DELAY subroutine.
Notice that in the case n a •st•d !oo* +s in nil other tame delay !oops, th time is
since we have ignored the first and last instructions in t1 c sufiroa:i.,c.
approximate

CHAPTER 3: JUMP, LOOP, AND CALL INSTRUUTIU?'* 79


Review Questions
1. True o‹ false. In the 805 l, the machi.oe cycle lasts 12 clock rycles of the crys-
ta1 frequency.
2. The minimum number oâ rn.achine cycles needed to execute an 8051 instruc-
tl OD IS .
3. tor Question 2, what is the maximum number of cycles needed, and for
which instructions?
4. Finer the machine cycle for a crystal frequency of 12 MHz.
5. Assuming a crystal frequency of 12 MHz, find the time delay associated
with the loop section of th following DELAY subroutine.
DELAY:
MOV R3,#l00
HERE: NOP
NOP
NOP
DJNZ R3,MERE
RET

SLiMMARY
The flow of a program proceeds sequentially, from instruction. to instruc-
tion, unless a control transfer instruction is executed. The various types of
control transfer instructions in Assembly language include conditional and
unconditional j•arnps, and call instructions.
The looping a*tion in 8051 Asseir.bly language is performed using a spe-
cial :n•'ruciion wb.ich decr•ments a counter and jumps to the top of the loop if
the counter is not zero. Other jump instructions jump conditionally, bassd on the.
value of tb.e carry flag, the accumulator, or bits of the I/O port. Ur.conditional
jumps can be long or short, depending on the relative value of the target address.
Special attention must be given to the effect of LCALL and ACALL instructions
on the stack.

PROBLEMS

SECTION 3.1: LOOP AND JUMP INSTRUCTIONS


1.
In the 8051, looping action with instruction “DJNZ Rx, re l
addr ess” is limited to iterations.
2.
If a conditic>nal jamp is not taken, what is the next instruction to be executed?
In calculating the target address for a jump, a displacement is added to the
con- tents of register
4. The mnemonic SJMP stands for arid it is a -byte instruction.
5. The :,inemonic LIMP stands for and it is a -byte instruction.
6.
What is the advantage of using 3U.*i' cyber LJlviP?
7. ’l'ruc or false. The target of a short jump is within -128 to +127 bytes of the
current PC.
8.
True or false. All 8051 jumps are short jumps.

80
9.
Which of t!-.e f‹•liowing instructions is (are) not a short juin p?
(a) JZ (b) JNC (c) Di MP (d) D NZ
10.
A short jump is a -byte instruction. Why?
II. True or false. All conditional juiiips are °hort julnps.
12. Show code for a nested loop to perfomi an action 1000 times.
|3.ShowcodcFraneod1oopto pdf manacGonl00,000Gncs.
1% Findthonuuborofthnesthcfoñuwingloopisperfonned
MOV R6,#200
BACK: MOV R5,#l00
HERE: DJNZ R5,HERE
DJNZ R6,BACK
15. Thee target address of a jump backward is a maximum of bytes from
the current PC.
16. The target address of a jump forward is a maximuin of bytes from
the current PC.

SECTION 3.2: CALL INSTRUCTIONS

17. LCALL is a -byte instruction.


18. ACALL is a -byte instruction.
19. The ACA* L target address is limited to bytes from the present PC.
20. The LCALL target address is limited to bytes from the present PC.
21. When LCALL is executed, how many bytes of the stack are used?
22. When AC.ALL is eKecuted, how many bytes of the stack are used?
2 . Why do the r‹umser of PUSH and POP instructions in a subroutine need to be
equal?
24. Describe the acticr. associated v.'ith the PCP instruction.
25 Show the stack for the following code.
OOOB 120300 LCALL DELAY
OOOE 80F0 SJMP BACK ;keep doing this
0010
0010 this is the delay subroutine
H3H0 OPG 300H
0300 RELAY:
0300 7DFF MOV R5,#0FFH ;R5=255
0302 DDFE AGAIN: DJNZ R5,AGAIN ;stay here
0304 22 RET ;return
26. Reassemble Example 3-10 at ORG 200 (instead of ORG 0) and show the
stack frame for the first LCALL instruction.

SECTION 3.3:TI1v1E DELAY GENERATION AND CALCULATION

27. Find the systei» frequency if the machine cycle = 1.2 gs.
28. Find the macl. '.e cycle if crystal frequency is 18 MHz.
29. Find the mac!iiiie cycl• if crystal frequency is 12 MHz.
30. Find the machine cj.!-z if crystal frequency is 25 MHz.

CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS «1


31. Ti ue or false. LAMP and SJ MP instructions take the same amount of time to
execute even though one is a 3-byte instruction and the other one is a 2-bytc
instruction.
32. Pind the time delay for the
delay subroutine shown to DELAY: MOV R3,#150
HERE: NOP
the i ight, if the system fre- NOP
quency is I 1.0592 MHz. NOP
DJN R3,HERE
RET
DELAY: MOV R3,#200
33. Find the time delay for the I!ERE : NO P
delay subroutine shown to NOP
the right, if the system fre- NOP
quency is l6 MHz. DJNZ
P3,HERE RET

DELAY: BACK:
MOV AGAIN:
MOV
R5,#l00
MOVHKRE:
R2,#200
NOP NOP DJNZ
R3,#250
DJNZ DJNZ RET

34. Find the time delay for the


delay subroutine shown to
the right, if the system fre- R3,HERE R2,AGAIN R5,BACK
quency is 11.0592 MHz.

MOV R2,#15C MOV P.3,#2b0 NGP


NOP
Find the time delay fGr tL‹e NLP.°
delay subroutine shown to DJNZ R3,HERE DJNZ R2,AGAIN RET
the right, ii‘ the syst-mm
fre- quency is 16 MI4z.

ANSWERS TC RE"JIE'W QUESTIONS

SECTION 3.1: LOOP AND JUMP INSTRUCT'ONS


1. Decrement and jump if not zero 2. True 3. 2 4. A S. 3

SECTION 3.2: CALL INSTRUCTIONS


I . Long CALL. and Absolute CALL 2. True
3. The address of where to return is in ilie stack.
4. Upon executing the RET instruction, the CPU pops off the top two bytes of the stack into the
program counter (PC) register and starts to execute from this New location.
5. 3

SEC 1“1ON 3.3: TI THE 13 I-.LAY GENERATION AND CALC ULATIGN


1. Truc 2. i 3. MUL and DIV each take 4 machine cycic...
4. 12 MHz / 12 = l M Hz, and MC = l/l MHz = l is.
5. [100 (l + l + l +2)] x 1 is = 500 ps = 0.5 milliseconds.

82
CHAPTER 4

PBOGRAMM4NG

Upon completion of this chapter, you will be able to:

Explain the purpose of each pin tif the ii051 microcontroller L:st the 4 ports of the 8051
Describe the dual role of port 0 :•n providing both data ard addresses Cod• Assembly language to use th
Code 8051 instructions for l/O handling
Code bit-manipulation instructions in the 8G51
83
This chapter describes 'he 8051 pins and then shows l/O port
programming cf the 8051 witii many examples.

SECTION 4.1: PIN DESCRIPTION OF THE 6051

Although 8051 family members (e.g., 8751, 89C51, DS5000) come in


dif- ferent packages, such as DiP (dual in-line package), QFP (quad flat
package), and PLC (leadlcss chip carrier), they all have 40 pins that are dedicated
for various l'anctions such as !/O, RD, WR, address, data, and interrupts. It must
be noted that some companies provide a 20-pin version of the 8051 yith a
reduced number of I/O ports for less demanding applications. However, since the
vast majority of developers use the 40-pin DIP package chip, we will concentrate
on that.

PDIP/Cerdip

P1.0 1 40 Vcc
P1.1 2 39 P0.0 (ADO)
P1.2 3 38 P0.1 (AD1)
P1 3 4 8051 37 PO.2 (AD2)
P1.4 5 (8031) 36 P0.3 (AD3)
P1.5 6 35 P0.4 (AD4)
P1.6 7 34 PO.5 (ADS)
PI.7 8 33 PO.6 (AD6)
RST |9 32 PO.7 (AD7)
(RXD) P3.0 10 31 EA/VPP
(TXD) P3.1 11 30 ALE/PROG
(lNT0j P3.2 12 29 PSEN
(INT1) P3.3 13 28 P2.7 (A15)
(TOO P3.4 14 27 P2.6 (A14)
(T1) P3.5 15 26 P2.5 (A13)
(WR) P3.o 16 25 P2.4 (A12)
{RD) P3.7 17 2^. P2.3 (AII)
XTAL2 18 23 P2.2 (A10)
XTAL1 19 22 P2.1 (A9)
GND 20 21 P2.0 (A8)

Figure 4-1. 8051 Pin Diagram

Examining Figrne 4-1, note that of the 40 pins, a total of o2 pins are set
aside fcr the four ports PO, Pl. P2, and P3, where each port takes 8 pins. The rest
of’ the pins ai e desigFli!!v’d £fS VCC G1fiD9 XTAL 1, XTAL2, RS’F3 EA, !â›Ei9›
Of these 8 pins, six of them (VCt , GND, XTAL 1, XTAL2, RST, and EA) are used
by all members of the 8051 and 8031 families. In other words, they must be
connect- ed in order for the system to work, regardless of whether the
microcontroller is of
14
the 805 I or 8031 Tamil . The other two pins, PSEN and ALE, are uscd mainly
in 5031-based systems. We first describe the function of each pin. Ports *re
discussed separately.
Vcc
Pin 40 provides supply voltage C2
XTAL2
tO ihe chip. The v oltage soui‘cc is 5V.

CI
Pin 20 is the ground.
XTAL1
XTAL! and XTAL2 30 pF
The 8051 has an on-chip oscil-
lator but requires an extei nai clock to GND
run it. Most often a quartz crystal
oscillator is connected to inputs
XTAL l (pin 19) and XTAL2 (pin 18).
The quartz crystal oscillator connected
to XTAL1 and XTAL2 also needs two Figure 4-2 (a). XTAL Connection to 8051
capacitors of 30 pF value. One side of
each capacitor is connected to the
ground as shown in Figure 4-2 (a).
It must be noted that there arc NC XTAL2
various speeds of the 8051 family.
Speed refers to the maximum oscilla-
tor frequency connected to XT.AL.
For example, a i 2-R"Hz chip m'ast be EXTERNAI. OSL"ILLATOR. SIGNAL
con- nect•fi to a crysta! with 12 k4Flz XTAL1
fre- quency or less. Likewise, a 20-
MHz microcontroller requires a
crystal fre- quency of no more than 20 GND
MHz. When the 5051 is connected to
a cq's- tal oscillator and is powered up,
we can observe the frequency on tlic Figure 4-2 (b). XTAL Connection. to an
XTAL2 pin using the oscilloscope.
External Clock Source
If you decide to use a frequen-
cy source other than a crystal oscilla-
Table 4-1: RESET Value of Some
tor, such as a TTL oscillator, it will be
8051 Registers
connected to XTAL1; XTAL2 is left
unconnected, as shown in Figure 4-2 (b). Register Reset Values
PC 0000
RST ACC.”‘ 0000
s 0000
Pin 9 is the RESET pin. It is an Psw m*†
input and is active high (norina! I !ow). $p 0007
Upon applying a high puise to tu..; pin, DPTR 0000
the microcontroller will reset and termi-
nate all activities. This is often referred to

CHAPTER 4: FO PORT PiiOGRAMMING 85


as a power-on reset. Activating «
power-on reset will cause a!1 values in
the registers to be lost. Table 4- I
pro- vides a partial list of 8051
registers and their valucs after power-
on reset. Notice that the value of the 40 uF 31
PC (program counter) is 0 upon EA/VPP
reset, forcing the CPU to fetch the 19 X1
11.0592 MHz
first opcode front ROM memory 8.2 K
location 0000. This means that we X2
30 pF 18
must place tire first line of source RST
code iii ROM location 0 because
that is where the CPU v.makes up
and expects to find the first
instruction. Figure 4-3 shows two
ways of connecting the RST pin
to the power-on reset circuitry.
In order for the RESET“ input
to be effective, it must have a mini- Figure 4-3 (a). Power-On RESET Circuit
mum duration of 2 machine cycles. In
oth.er words, the high pulse must be
high for a minimum of 2 machine
cycles before it is allowed to go low.
In the 5051, a machine cycle
is defined as 12 oscillator periods, as
discussed in Chapter 3, as shown
again in Example 4- i.

The 8051 family members,


such as the 8751, 89C51, or DS5000,
all come with on-chip ROM to store
programs. In such cases, the EA pin
is connected to VCC. FCiR family mem-
bers such as the 8031 arid 8032 in
which there is no on-cnip RO4i, code
is stored on an external ROM and is
fetched by the 8031/32. Therefore,
for the 8031 the EA pin must bu con-
nected to GND to indicate that the
Vcc

31
EA/VPP
10 ur
30 pF

X2
RST

9.2E

Figure 4-3 (b). Power-On RESET with Debounce


code is stored externally. EA, which stands for “external access,” is pin number
31 in the DIP packages. It is an input pin and must be connected to either dcc or
GND. In other words, it cannot be left unconnected.
In Chapter 14, we will show how the 8031 uses this pin along witn PSEN
to access programs stored in P.O' ! memory located outside the 8031. In 805 l
chips with on-chip ROM, such as me 8751, 89C51, or DS5000, EA is connected
to Vcc• as we will see in the next section.

86
Example 4-1
Find the machine cycle for (a) XTAL = 11.0592 Mhz (b) XTAL = 16 MHz.

Solution:
(a)11 .0592 MHz / 12 = 921.6 kHz;
lrachine cycle = 1 / 921.6 kHz = 1.055 gs
(b)16 MHz / 12 — 1.333 MHz;
machine cycle = ! / 1.333 MHz = 0.75 his

The pins discussed so far must bc connected no matter which family


mem- ber is used. The next two pins are used mainly in 80 I -based systems and
are dis- cussed in wore detail in Chapter 14. ‘the fol!owing is a brief
‹Description of each.
PSEN
This is an output pin. PSEN stands fot “program store enable.” In an
8031 - based system in which an external ROM holds the program code, this pin
is con- nected to the OE pin of the ROM. See Chapter 14 to see how' this is
used.
ALE
ALE (address batch enable) is -‹in output pin and is active high. When
con- necting an 5031 to external memory, port G provides both aadress and data.
In other words, the 8031 multiplexes address and data through port 0 to save
pins. The ALE pin is used for demultiplexing the address and data by connecting
to the G pin of the 74LS373 cfiip. This is aiscussed in detail in Chapter 14.
1/0 port gins and their functions
The four ports P0, P1, P2, and P3 each us• 8 pins, making them 8-bit
pcbs. All the ports upon RESET are configur•d as output, ready to be used as
output ports. To use any of these ports as an input pori, it must be prcgrammed,
as iv'- w'ill explain throughout this sect‹on. First, we describe each port.
Oft 0
.°ort 0 occupies a total of S pins (pins 32 - 39). It can be used fci input or
output. To use the pins of port 0 as both input and output ports, each pin must be
connected externally to a 10K ohm pull-up resistor. This is due to the fact that P0
is an open drain, unlike P1, P2, and P3, as we will soon see. Open drain is a term
used for MOS chips in the same way that open collector is used for TTL chips.
In any system using the 8751, 89C51, or DS5000 chips, we normally connect P0
to pull-up resistors. See Figure 4-4. In. this way we take advantage of port 0 for
both input and output. With external pull-up resistors connected upon reset, port 0
is configuled as an output port. Fo: example, the following code will continuously
send out to port 0 the alternating values 55H and AAH.
MOV A,#55f:

ACALL DELAY
CPL A
SJMP BACK
* TER 4: FO PORT PROGRAMMING 87
Port 0 as input
Vcc
10 K
With resistors
connected to port 0, in
order to make it a.* input,
the port must be pro- P0.0
P0.1
grammed by writing 1 to DS5000
PO.2
all the bits. In the 9751 PO.3
follow- ing code, port 0 8951 P0.4 —
P0.5
is con- figured first as P0.6
an input port by writing P0.7
1s to it, and then data is
received from tb.at port
and sent to P1. Figure 4-4. Port 0 with Pull-Up
Resistors

MOV A,#0FFH ;A = FF hex


MOV P0,A ;make P0 an input port
;by writing all 1s to it
BACK: MOV A,P0 ;get data from P0
MOV Pl,A ;send it to port 1
STEP BACK ;keep doing it

Dual role of part 0


As sho•xn in Figure 4-1, port 0 is also aesignated as ADD - AD7. allowing
it to be used for both address and data. When connecting an 8051/31 to an
exter- nal memoq•, port 0 provides both address and data. The 8051 multiplexes
address and data through port 0 to save pins. ALE indicates if P0 has
address or data. When AI.E = 0. it provides data DC - D7, but wh•n ALE = l it
has address A0 - A7. Therefore, ALE is used for demuliplexing address and
data with the help of a 74/ S373 latch, as we will see in k“hapter 14.

Port 1
Port 1 occupies a total of 8 pin.s (pins l through 8). It can be used as
input or output. In, contrast to port 0, this port does not need any pull-up
resistors since it already has pull-up resistors internally. Upon res•t, port 1 is
configured as an output port. For example, the follcwing code will continuously
send out to port l the alternating values 55H and AAH.

MOV A,f55H
BACK: MOV Pl,A
ACALL DELAY
CrL A
SJMP BACK

88
Port 1 as input
To make port l an input port, it must programmed as Stich by i• riting I to
all its bits. The reason for this is discussed in Appendix C.2. In the foliowiiig
code, port l iS configured first as an input port by writing 1s to it, then data is
received from that port and saved in R7, R6, and R5.

MOV A,#0FFH ;A=FF hex


NOV P1,A ;make Pl an input port
;by writing all 1s to it
MOV A,Pl ;get data from Pl
MOV R7,A ;save it in reg R7
ACALL DEALY ;wait
MOV A,P1 ;get another data from Pl
MOV R6,A ;save it in reg R6
ACALL DELAY :wait
MOV A,Pl ;get another data from P1
MOV R5,A ;save it in reg J5
Port 2
Port 2 occupies a total of 8 pins (pins 21 through 28). It can be used as
input or output. Just like Pl, port 2 does not need any pull-up resistors since it
already has pull-up resistors internally. Upon reset, port 2 is configured as an
out- put port. For example, the following code will send out continuously to port
z the alternating values 5ñH and AAH. That is, all the bits Of P2 toggle
continuously.

MOV A,#,55H
BACK: MOV P2,A
ACALL DELAY
CPL A
SJMP BACK
Port 2 as input
To make port 2 an input, it must programmed as such by writii.g 1 to all
its bits. In the following code, port 2 is configured first as an input port by
writing 1s to it. Then data is received from that port and is sent to Pl
continuously.

’MOV A,#0FFH ;A=FF hex


MOV P2,A ;make P2 an input port by
;writing all 1s to it
BACK: MOV A,P2 ;get data from P2
MOV Pl,A ;send it to Port 1
SJMP BACK ;keep doing that
Oc!z-.I roie of port z
In systems based on the 8751, 89C51, and DS5000, P2 is used as simple
I/O. However, in 8031-based systems, port 2 must be used along with P0 to pro-
CHAPTER 4: FO PORT PROGRAMMING 89
vide the I 6-bit address for the external memury. As shown in Figure 4-1, Port 2
is also designated as A8 - A 15, indicating its dual function. Since an 8031 is
capable of“ accessing 64K bytes of external memory, it iiecds a path for the l6
bits of thc address. While P(I provides the lower 8 bits via A0 - A7, it is the job
of P2 to pro- vide bits A8 - A15 of the address. In other words, when the 803! is
connected to external memory, P2 is used for the upper 8 bits ot’ the I 6-bit
address, and it can- rot be used for 1/L°. This is diseusse‹i in de(ai1 in Chapter
14.
Prom the discussion so far, we conclude that in systems based on 8751,
89C51, or DS5000 microcontrollers, we have three ports, P0, P1, and P2, fi›r
!/O operations. This should be enough for most microcontroller applications.
That lca es port 3 for in.ter rupts as well as other signals, as we will see next.
Port 3 Table 4-x: Port 3 Alternate
Port 3 occupies a total of 3 piiis, pins 10 Functions
through 17. It can be uscd as input or output. P3
does not need any pull-up resistors, the same as
P l and P2 did not. Although port 3 is
configured as an output port upon reset, this is
not the way it is most commonly used. Pot 3
has the addi- tional function of providing some
extremely important signals such as interrupts.
Table 4-2 provides these alternate functions of
P3. This information appllGS tO both 8051 and
8031 chips.
P3.0 RxD 10
P3.1 TxD’ 11
P3.2 INT0 12
P3.3 INTl 13
P3.4 T0 lv
P3.5 T1 15
P3.6 WR 16
P3.7 RD 17
P3.0 and P3.1 are used for the RxD and
TxD serial corr municatioiis signals. See CL‹aptcr
10 to see how they are connected. Bits F3.2 and Pñ.3 are set aslde for exterr.al
inierrupts, and are discussed in Chapter 11. Bits P3.4 and P3.5 are used for
timers 0 and 1, and are discussed in Chapter 9 where timers are discussed.
Finally, P3.6 and P3.7 are used to provide the WR and RD signa!s of external
memories con- nected in 8031-based systems. Chapter 14 discusses how they are
used in 8031- based systems. In systems based on the 8751, 89C 51, er DS5000,
pins 3.6 and 3.7 are used for I/O n'hile the rest of that pins in Port ar• nonnally
used in the alter- nate function role.
R=view Questions
1. A given 8051 ch p has a speed of 16 MHz. What is the range of frequency
that can be applied to the XTAL l and XTAL2 pins?
2. A 16-MHz 8051 system has a machine cycle of
3. Which pin is used to inform the 8051 that the on-chip ROM contains the
pro- gram?
!. There are total of ports in the 805 I and each has bits.
5. True or false. All of the 8051 ports can be used for both input and output.
Upon po:ver up, the nrogre.m eount•r (PC) h a value of
/. Upon power up, the 8051 fctciies the first opcode from ROM address locaticn

8. Which of the 8051 ports need pull-up resistots to function as an I/O port?

9b
SECTION 4.2: IiO PROGRA?IMING; BIT MANIPULATION

1 n this section we further examine 8051 l/O instructions. We pay special


attention to I/O bit manipulation since it is a powerful and widely tired 8051 fea-
Um e. A detailed discussion of l/O ports of the 8051 is given in Appcndix C.2.
different ways of accessing the entire 6 bits
In the. following code, as in many prcvious I/O cxarn|ilcs, t!ic entire 8 bits
ot” Port l ai e accessed.

BACK: Nov r,#55a


DAOV P1,
ACALL DELAY
MOV A,#0AAH
MOV Pl,A
ACALL DELAY
SJMP BACK

The above code toggles every bit of P1 continuously. We have seen a


vari- ation of the above program before. Now vie can rewrite the above code in a
more efficient manner by accessing the port directly without goin•q through the
accumu- lator. This is shown next.

BACK: MOV P1,#55H


ACALL DELAY
MOV P1,#O AH
ACALL DccAY
SJMP BACK

We can write another variation of the above code by using a technique


called read-modify-write. This is shown next.
Read-modify-write feature
The ports in the 8051 can be accessed by the read-modify-write technique.
This feature saves many lines of code by combining in a single instruction air
three actions of l) reading the port, (2) modifying it, and (3) «'riting to the port.
The following code first places 0i010101 (binary) into port 1. Next, the
instruction “XLR PI, 4 0 OFH” performs an XOR logic operation on P l with
1111 1111 (bina- ry), and then n'rites the result back into PI.

MOV Pl,#55H rel=0l0l01Ol


AGAIN: WLR Pl,#0FFH ;EX-OR Pl with 1111 1111
ACALL DELAY
SJMP AGAIN

Notice that the XOR of 55H and FFH gives AAH. Likewise, tlie this of
AAH and FFH gives 55H. Logic instructions are di.scussed in Chapter 7.

CHAPTER 4: UO PORT PROGRAMMING 91


Single-bit addressability of ports
There are times that we necd to access only 1 or 2 btis Of the port instead
of the entire 8 bits. A powerful feature of 8051 l/O ports is their capability to
access individual bits of the port without altering the rest of the bits in that port.
For example, the following code toggles the bit P1.2 continuously.

BACK: CPL Pl.2


ACALL ,complement P1.2 only
DELAY SJMP
BACK

;another variation oi the above program follows


AGAIN: SETB Pl.2 ;change only P1.2=high
ACALL DELAY
CLR P1.2 ;change only Pl.2-low
ACALL
DKLAY SJMP
AGAIN
Table 4-3: Single-Bit Addres abili f o ts
Notice that PI 2 is the third bit
of P1, since the first bit is PI.0, the sec- P0 PI P2 P3 Po t Bit
ond bit is PI.1, and so on. Table 4-3 PO.0” ”P1.0 ’P2.0 *P3.0 D0
shows the bits cf 8051 I/O ports. See P0.l P1.1 P2.1 P3.1 Dl
Example 4-2 for an example of bit P0.2 P1.2 P2.2 P3.2 D2
manipulation of 1/O bits. Notice in P0.3 PI.3 P2.3 P3.3 D3
Example 4-2 that unused portions of Ph.4 Pl.4 P2.4 P3.4 D4
Ports l and < are undisturbed. This sin- P0.5 PI.5 P2.5 P3.5 D5
gle-bit *.ddressability of I/O ports is one P0.6 P1.6 P2.6 P3.6 D6
of most powerful features of the 805 l P0.7 P1.7 P2.7 P3.7 D7
microcontroller.
Example 4-2

Write a program to perform the following.


Keep monitoring the PI.2 bit until it becom•s high,
When P1.2 becomcs high, write value 45H to port 0, and
Send a high-to-low (H-to-L) pulse to P2.3.

Solution:

SETB Pl . 2 ;make Pl.2 an input


MOV A,#45M r‘ A= 4 S H
AGAIN: JNB pl.2,AGAIN ;get out when Pl.2=l
MOV P0,A ;issue A to P0
SETB P2.3 ;make P2.3 high
CLR P2.3 ;make P2.3 low for H-to-L

In thi: Program, instruction “JNB P1 . 2, AGA I N” (iU'° means jump if no bit) stays in the loop as long as P1

92
Review Ques’.ions
l . Upon reset, thc 8051 ports are configured as
(a) input (b) output (c) both input and output.
2. Trike or false. The instruction “S ET B P2 . 1” makes pin PM.. I high while
leav- ing other bits of P2 unchanged.
3. Why do we use 55 H and AAH to test the bits of the poi t’?
4. As the following a valid insti uction: “MOV P l , 19 S H”? Exp!ain your answer.
5. Using the instruction “JNB P 2 . 5, HEf-IE” ‹issuiiies that bit P2.5 iS fllâ
(in ptit, outp ut).

SUMMARY
This chapter began by describing the function of each pin of the 805 t.
The four ports of the 8051, PO, P1, P2, and P3, each use 8 pins, leaking them 8-
bit ports. These ports cae. be used for input or output. Port 0 can be used for
either address or data. Port 3 can be used to provide interrupt and serial
communication signals. Then I/O instructions of the 8051 were explained, and
numerous exam- ples were given.

PROBLEMS
SECTION 4.1: PIN DESCRIPTION OF THE 8051

1. Tne 5051 DIP package is a -pin package.


2. fi'hicb. pm.s are assigned to VCC and AND?
3. In th- 8051, how many pins are d•sigrated as I/O port pins?
4. The crystal oscillator is connected to pins and
5. If an 8051 is rated as 25 MHz, what is the maximum frequency that can be
connectcd to it?
6. Indicate the pin number assigned to RST in the DIP package.
7. RST is an (input, outp›at) pin.
S. The RST pin is rornially (low, high) and ne•ds a (low, !ii3h)
signal to be activated.
9. What me th• contents of .he PC (program counter) upon RESET of the 8051?
10. What are the contents of:he SP register upon RESET of the 8051?
11. What are the contents of the A register upon RESET of the 8051?
12. Find the machine cycle for the following crystal frequencies connected to X l
acid X2.
(a) 12 MHz (b2 20 MHz (c) 25 MH4 (d) 0 h4Hz
1 o. EA stands for and is an (input, output) pin.
14. For 8051 family members with on-chip ROM stich as the 8751 and the 89C
51, pin EA is connected to (VCC, GND).
1 5. PSEN is an (inptil. .›ut}3t!() }3tF1.
IN. ALE is an (input, output) pin.
17. ALE is used mainly in systems based on the (8G5 i, SQ* !).
18. How many pins are designated as P0 and what are those in the DIP package?

CHAPTER 4: FT PART PROCRAMMIN.G 93


19. now marry pins are de='snated as P I and what are those in the 191 P package?
20. How many pins are designated as P*, ñiiu wliat e.re thosC in the Dl P package?
21. How many pins are designated as P3 and what are those in the DlP package?
22. Upon RESET, all the bits of ports are conFlgured as (IR Ut, OUt Ut).
23. In the 8051, which port nee s a pull-up resistor to be used as I/O?
24. Which port of the 8051 does not have any alternate function and can be Used
solely for I.'O?
25. fi*rite a program to get 8-bit data from PI and selid it to ports P0, P2, and P3.
26. Write a programs to get an 8-bit data from P2 and send it to ports P0 and P1.
27. In P3, which pins are for RxD and TxD?
28. At what memory location does the 8051 wake up upon RESET? What is the
i:np[ication of that?
29. Write a program to toggle all the bits of P1 and P2 continuously
(a) using AAH and 55H (b) rising the CPL instruction.
30. What is the address of the last location of on-chip ROM for the 8751?

SECTION 4.2: I/O PROGRAJ'VilvIING; BIT NIA”NIPULATION

31. Which ports of the 8051 are bit-addressable?


32. What is the advantage of bit-addressability for 8051 ports\*
33. When P1 is accessed as a single bit port, it is desibflated as
34. Is the instruction "CPL 01" a valid instruction?
35. Write a program to toggle PI.2 and PI.5 continuously without disturbing the
rest of the bits.
36. Write a program to toggle PI.3, P1.7, and P2.5 continuously without disturb-
ing the rest o* the bits.
37. Write a program to monitor bit P1.3. When it is high, send 55H to P2.
38. Write a program to monitor the P2.7 bit. V'hen it is low, send 55H and AAH
to P0 continuously.
39. Write a program to monitor the P2.0 bit. When it is high, send 99H to P1.
40. Write piograni to monitor the P1.5 bit. When it is high, make a low-to-
high- to-low pulse on PI.o.

ANSWERS TO REVIEW QUESTIONS


SECTION 4.1: PIN DESCRIPTION Or THE 8051
1. From 0 to 16 MHz, but no more than 16 MHz.
2. l/l2th of 16 MHz is 1.33 MHz. and the machine cyclc is — 0.75 qs
3. EA 4. 4, 8 5. True
6. PC = 0000 7. 0000 8. Port 0

SECTI ON 4.2: i/O PP OGRAMM LNG; BIT MANIPUL:^.TI ON


1. (b) 2. True 3. they are the complement of each other.
4. Yes. This is ca1le‹i immediate ad‹l i cssing mode (discusscd in Chapter 5).
5. input

94

You might also like