You are on page 1of 542

THE 8051 MICROCONTROLLER

AND EMBEDDED SYSTEMS

,,1; , 0 Using Assembly and C

SECOND EDITION
~ L;r ,<:>
o:,~
o>-"'
'' ' \}.._~M '-"' t'\ '<"' S V\ '-. cl
:Ir
~o-<
~e_ E_ ~ \\ - C ~ ~ -
$ 1:\... t.f!...""" ~~c- .
Muhammad Ali Mazidi
Janice Gillisp~~ Mazidi
Rolin D. McKinlay

~ l:1 .f ')..fl- /J~



Cj I () 'tJ ~ (!.A.{e.y ~ #"">


CONTENTS
1
CHAPTER O: INTRODUCTION TO COMPUTIN G 2
Section 0.1: Numbering and coding systems 8
Section 0.2: Digital primer 12
Section 0.3: Inside the computer
19
CHAPTER 1: THE 8051 MlCROCONTROLLERS 20
Section 1.1: Microcontrollers and embedded processors 23
Section 1.2: Overview of the 8051 family

29
CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING
30
Section 2.1: Inside the 8051
32
Section 2.2: Introduction to 8051 Assembly programming
34
Section 2.3: Assembling and running an 8051 program
Section 2.4: The program counter and ROM space in the 8051 35
Section 2.5: 8051 data types and directives 38
Section 2.6: 8051 flag bits and the PSW register 40
Section 2.7: 8051 register banks and stack 43

CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS 55


Section 3.1: Loop and jump instructions 56
Section 3.2: Call instructions 60
Section 3.3: TUl1e delay for various 8051 chips 65

CHAPTER 4: 1/0 PORT PROGRAMMING 75
Section 4.1: 8051 I/0 programming
76
Section 4.2: I/0 bit manipulation programming
80

CHAPTER 5: 8051 ADDRESSING MODES


Section 5.1: Irruned iate and register addressing modes 89
Section 5.2: Accessing m em ory using various addressing modes 90
Section 5.3: Bit addresses for I/ 0 and RAM 91
Section 5.4: Extra 128-byte on-chip RAM in 8052 100
107

CHAP'I ER 6: ARITHMETIC, LOGIC INSTR UCTIONS, AN D PROG RAMS


Section 6.1: Arithmetic instructions 115
Section 6.2: Signed number concepts and arithmetic operations 116
Section 6.3: Logic and compare instructions 124
Section 6.4: Rotate instruction and data serialization 129
Section 6.5: BCD, A.Sell, and other application programs 135
141
CHAP'I'ER 7: 8051 PROG RAMMI NG IN C
Section 7.1: Data types and time delay in 8051 C 153
Section 7.2: l/ 0 programming in 8051 C
154
Section 7.3: Logic operations in 8051 C
160
Section 7.4: Data conversion programs in 8051 C
165
Section 7 5; Accessing code ROM space in 8051 C
169
St.>ction 7.6: Data serialization using 8051 C
173
178

V
183
D INTEL }JEX FILE
184
188
CHAPTEK 8: 8051 HARDWAR~ CONNECTION AN 195
Se tion 8 1. Pin description o f the 8051 .
S:tion : ; Design and test o f D589C~x0 tramer
82
Section 8.3: Explainin g the Intel hex file 201
202
CHAPTER 9: 8051 TIMER PROGRAMMING IN ASSEMBLY AN D C 217
Section 9.1: Programming 8051 timers 222
Section 92: Counter programming
Section 9.3: Programming timers Oand 1 in 8051 C
237
CHAPTER 10: 8051 SERIAL PORT PROGRAMMING IN ASSEMBLY AND C
238
242
Section 10.1: Basics of serial comm unication
244
Section 10.2: 8051 connection to RS232
Section 10.3: 8051 serial p ort programming in Assembly 255
Section 10.4: Program.ming the second serial port 261
Section 10.5: Serial port programming in C
271
CHAPTER 11: INTERRUPTS PROGRAMMIN G IN ASSEMBLY AND C 272
Section 11.1: 8051 interrupts 275
Section 11.2: Programming timer interr upts 279
Section 11.3: Programming external h ard ware interrupts 284
Section 11.4: Programming the serial communication interrupt
288
Section 11.5: Interrupt p riority in the 8051 /52
290
Section 11.6: Interrupt programming in C

CHAPTER 12: LCD AND KEYBOARD INTERFACING 299


Section 12.1: LCD interfacing 300
Section 12.2: Keyboard interfacing 311

CHAPTER 13: ADC, DAC, AND SENSOR INTERFAC ING 321


Section 13.1: Parallel and serial ADC 322
Section 13.2: DAC interfacing 344
Section 13.3: Sensor interfacing and signal conditioning 348

CHAPTER ~4: 8051 INT~RFACING TO EXTERNAL MEMORY


35S
Sect~on 14.1: Serruconductor memory
Sec~on 14.2: Memory address decoding 356
Sect~on 14.3: 8031 / 51 interfacing with external RO M 364
Sect~on 14.4: 8051 data memory space '361
Section 14.5: Accessing external data me mory .m8051 c 371
381
CHAPTER ~5: 8051 INTERFACING WlTH THE 8255
Section 15.1: Programming the 8255
Sec~on 15.2: 8255 interfacing
Section 15.3: 8051 C programming for the 8255

CHAPTER 16: DS12887 RTC INTERFACING


Section 16.1: DS12887 RTC interfacin AND PROGRAMMING
Section 16.2: DS12887 RTC program!in .
Section 16.3: Alarm, SQ.W, and IRQ t g m C
eatures of the DS12887 .
ch1p

vi
427
CHAPTER 17: MOTOR CONTROL: RELAY, PWM, DC, AND STEPPER MOTORS 428
Section 17.1 Rclav~ tlnd optoisolators 432
Sc-:tion l7.2: Stepper motor intcrfacmg 441
Section 17.3 DC motor interfaang and PWM
453
\ PPE.'.\01'< A 8051 INSTRUCTIONS, TlMING, AND REGISTERS
487
\ PPf DIX 8: BASlCS OF WIRE WRAPPING
49]
APPE DIX C: TC TEC}INOLOGY AND SYSTEM DESIGN ISSUES
509
APPf\.DlX D: FLO\.VCHARTS AND PSEUDOCODE
513
APPFNDIX E: 8051 PRIMER FOR X86 PROGRAMMERS
514
,-\PPEXDIX F: ASCil CODES
Ci17
APPENDIX G: ASSEMBLERS, DEVELOPMENT RESOURCES, AND SUPPLIERS

,\PPL'\DIX H: DATA SHEETS 519

l:'l:DEX 545

7 C t I '.
1n Chapter 14 \Ve cover 8031/5 1 interfacing with external memories, both R?M and RAM:
Chapter 15 addresses the it>Sue of adding additional ports to the 8031/51 using an 8255 chip.
Chapter 16 shO\\'S ho\v to connect and program the DS12887 real-time clock chip.
Final!}, Chapter 17 shows basic interfacing to relays, optoisolators, and motors. . .
The appendice5 have been designed to provide aJJ reference material required for the topics covered m the book.
Appendix A describes each 8051 instruction in detail, with exan1ples. Appendix A also provides the clock count for
instructions, 8051 register diagrams, and RAM memory maps. Appendix B describes basics of wire wrapping. Appendix
C covers IC technology and logic families, as well as 8051 J/0 port interfacing and fan-out. Make sure you study this
before c~nne~ting the 8051 to an external device. Jn Appendix D, the use of flow charts and psuedocode is explored.
Append'.x E ts fo.r students familiar with x86 architecture who need to make a rapid transition to 8051 architecture.
Appendix F pr~v1des the table of ASCII characters. Appendix G lists resources for assembler shareware, and electronics
parts. Appendix H contains data sheets for the 8051 and other IC chips.

What is new in the second edition


hrThe ~ggest change in this ne~v edition is the addition of 8051 C programmmg throughout the book. W11ile Chapters
1 t oug f6 us; Assem~ly l.anguage exclusively, starting with Chapter 7, we have both Assembly and C language
programs or a the topics discussed. The second edition includes the following new features
1
:
new cha~ter on 8051 C programming (Chapter 7)
new se~on on the 8051 C progran1ming of timers (Section 9.3)

A new sec~on on the second serial port of the DS89C4x0 chip (Section 10 4)
A . on the 8051 c progranun1ng
A new section of the second serial port (Section
10 5)
p new sec~on on the 8051 C programming of interrupts (Section 11.6) .
Arogramm~g of the J KB SRAM of the DS89C4x0 chip (Section 14 4)
ne~v section on the 8051 C programmtng
A new h
. of external memory (Section
. 14.5)
A chapter on the DS12887 RTC (real-time clock) chip (Chapter 16)
new c apter on motors, relays, and optoisolators (Chapter 17)

~ab manual
The lab Inanual and support mat . ls f .
M.icroDigita!Ed.com Web site. er1a or this and other books by the authors can be f d
otm at the www.

Solutions manualleQ.werPoinie slides


The solutions manual was produced with th
and Po~erPoint' sUdec. for the drawin are , ~ help of ~ rdeshir Eslamj (of Sharif U . .
Education representative or visit wwwgs
pea a, a1dlabl~ onhnc for instructors only Instrruvers1ty). The solu tions manua l
. rsone .co.1n/muhammadaJ.1maz1d1 . . . uctors can contact the1r p earson

Acknowledgments
This book is thl' result of the ded .
ciation goes to all of them icahon and encouragement of man . . .
p Y t.nd1v1duaJs Ou .
that ~;t~ :.w~ul~ l; ke to thank Professor Danny Morse th . r sincere and heartfelt appre-
He is the one wh~
architecture
i;! a strong need f~r a book such as ;hise :,ost knowledgeable and e ri
oduced us to this microcontroller and' d due to his lack of timexpeh enced person on the 8051
was always th e encouraged .
Also we wouJd l"k to ere, ready to d ' . us to wnte it.
suo- . t e express our sincere ti.. __ ,_ _ lSCUss issues related t 805
or..~..tio":' on the organization of the book 'IGJ WI to Professor Cl d . o 1
. In addition, the follow Y e Knight of DeV u .
their nlicrocontroller mg professors and students found ry ruvers1ty for his helpful
course, and we thank them . errors while us
sincerely: Prot . 1ng the book in .
....._ essor Phil Golden and J hn its pre-publication form in
"" 0DUCl"ION Berry of DeVry University,

ix
I
ABOUT THE AUTHORS
Muhammad Ali Mazidi went to Tabriz University and holds M.aster's degrees from both Southern Methodist
University and the University of Texas at DaJJas. He is currently a.b.d. on his Ph.D. in the Electrical Engineering
Department of Southern Methodist University. He is co-author of a widely used textbook, The 80x86 IBM PC and
Compatible Computers, also available from Prentice Hall. He teaches microprocessor-based system design at DeVry
University in Dallas, Texas.
Janice Gillispie Mazidi has a Master of Science degree in Computer Science from the University of North Texas.
She has several years of experience as a software engineer in Dallas. She has been chief technical writer and production
n1anage'.' and was responsible for software development and testing of a widely used textbook, The 80x86 IBM PC and
Compatible Computers, also available from Prentice Hall.
. Rolin McKinlay has a BSEET from DeVry University. He is currently working on his Master's degree and PE license
m_the s~a!e of Texas. He is currently self-employed as a programmer and circuit board designer, and is a partner in
M 1cr0D1gitalEd .com.
The authors can be contacted at the following e-mail addresses if you have any comments or suggestions or if you
find any errors. '

mdebooks@yahoo.com
mmazidi@microdigitaled.com
rmckinlay@microdigitaled.com
CHAPTERO

INTRODUCTION TO
COMPUTING

OBJECTIVES

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

>
> Convert any number from base 2, base 10, or base 16 to either of the other h-vo 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, NANO, NOR
> Use logic gates to diagram simple circuits
> Explain the difference between a bit, a nibble, a byte, and a ivord
> Give precise mathematical definitions of the terms kilobyte, megabyte, gigabyte, and terabl(te
> Explain the difference between RAM and ROM and describe their use
> Describe the purpose of the major components of a computer svstem
>
> Uot dw thn!e
Describe typos
the role the"-found
of of CPU in computer systemsand describe the pu<poee of each type of bus
in computers

> List the major components of the CPU and describe the purpose of each

I
one mu st first master some very b .
. trollerbased systemf,d' tal computers can be called Chap~
f microcon ~:fon o agi I 'Cf

~
To u.nderstand the software and hard ware o a hich in the traw I . troduction to og1c gates, an overvi
concepts underlving computer design. ln this chapter (ware presented- After an a brief history of CPU archit-~
' - L., d coding systems we gave . . -.......
o), the fundamentals of num= ing an. . . in the (ast section . f this chapter, 1t 1s recommended that
11
of the workings inside the computer as given. Frna y, din .lllany of the topics o
Although some readers may have an .adequate backgroun
the material be scanned, however briefly.

. SYSTEMS
SECTION 0.1: NUMBERING AND CODING . rs use the base 2 (b'111ary) system. In this section we
\\lhereas human beings use base 10 (decimal} anthmetic, compu te d , ce versa. The convenJent representation
explain how to convert from the decimal system to the binary sys~emll anth' ~inary format of the alphanumeric code
of binary numbers in base 16, called hexadecimal, also is covered. Frna Y, e
called ASCII, is explored.

Decimal and binary number systems


Although there has been speculation that the origin of the base JO system is the fact th~t human beings have 10 fin.
gers,. there ~ absolutely no speculation about the reason behind the use of the binary system Ul com,i:iuters. The bmary sys
~m.'s used in computers because 1 and Orepresent the two voltage levels of on and off. Where, s m base 10 there are JO
distinct symbols,_O, 1, 2,..., 9'. in base 2 there are only hvo, Oand 1, with which to genera te numbers. Base 10 contains dig
,tsO through 9; binary contains digits Oand 1 only. These two binary digits, 0 and l, are commonly referred to as bits.

Converting from decimal to binary
of thOne m~thdod ofThic~nverting from _decimal to binary is to divide the decima I number by 2 repeatedly keeping track
remain
ordere to obtainers.
the b' s processbcontinues
Thi . until the q uoti:"t beeomes zero. TI,e remainders
'
are then written in revene
mary num er. s 1s demonstrated ,n Example 0-1.

Example0-1
Convert the following deci mal numbe rs to binary
. fonn: (a) 27 and (b} 125.

Solution:
(a) 27
Quot1 eiit Jl...,indar
27/2 = 13 l LSB (least aignificant bit)
13/2 6 l
6/2 = 3 0
3/2 1 l
l/2 0 l MSB (moat significant bit )
The binary equhalent of 2710 : l lOl l z
(b) 125
Quot .I. et
125/2 ~ indft-
62
62/2 = 31 l LSB
31/2 15 0
15/2 7 l
7 /2 3 l
3/2 l l
1/2 O l
The . lMSB
binary equivalent of 125,. l llllOl:r

2
THE 80St MlCROC:o _.
NTROLLER
ANO EMBEDDED 5'1ff
must first master some very b .
stem, one b ll Ilic
. r ontroller-based ~.Y di jtal computers can e ca ed Cha 1
To understand the software and h:""dware _of a m:r~hich in the tradition of iJl!oduction to logic gates, an over,};"
concepts underlying computer design. In this chap! ~
are presented. After an . a brief histor y of CPU architecture\\,
0), the fundamentals of numbering an~ c~ing 5F~s ell in the last section we _givef thiS chapter, it is recommended ,L~
of the "'orkings inside the computer IS given. rna Y . ny of the topics o u14t
Although some readers may have an.adequate background ,n ma
the material be scanned, however bnefly.

SECTION 0.1 : NUMBERING AND CODING SYSTEMS


. rs use the base 2 (b.11111,Y) system ln this =~
~Qtion we
Whereas human beings use base 10 (decimal) arithmetic, compute d vce versa The con venient representation
. system an 1
. th b.
explain how to convert from the decimal system to e rnary .all
th binary format of the alphanumeric code
of binary numbers in base 16, called hexadecimal, also is covered. Pin Y, e '
called ASCJJ, is explored.

Decimal and binary number systems


Although there has been speculation that the origin of the base 10 system is the fact that human beings ha~e 10 fin.
gers, there is absolutely no speculation about the reason behind the use of the binary system m computers. The binary sys
tern is used in computers because 1 and Orepresent the two voltage levels of on and off. Where,.s m base 10 there are 10
~stinct symbols, 0, 1, 2, ..., 9, in base 2 there are only hvo, oand 1, with which to generate numbers. Base 10 contains dig
its Othrough 9; binary contains digits Oand 1 only. These hvo binary digits, 0 and 1, are commonly referred to as bits.

Converting from decimal to binary


One method of c~11verting from _decimal to binary is to divide the decimal number by 2 repeatedly, keeping track
of ~he rema,~ders. ~s process contiflues until the quotient becomes zero. The remainders are then w ritten in reverse
or er to obtain the binary number. This is demonstrated in Example 0-1.

Example 0-1
Convert the following decimal numbers to binary form: (a) 27 and (b) 125.

Solution:
(a) 27
Quotient Rmui nder
27/ 2 13 l LSB (least aigni!icant bit)
13/2 6 l
6 /2 = 3 0
3/2 = l 1
l /2 0 1
MSB (moat significant bi t)
The binary equivalent of 27 IC> = 11011 2

(b) 125
Quo t i ent R-..1.nder
125 / 2 62 l LSB
6 2/2 = 31 0
31/ 2 = 15 1
1 5/2 7 1
7/ 2 3 1
3/2 e 1 1
l/2 0 1 MSB
The bJJ1ary equivalent of 125,. 111110~.

2
THE 8051 MICRocoNTR.ott --
ER. AND EMBEDDED 5yS'llld
Converting from binary to decimal
740683 0 -
To con, ert from binary to dec1n,al. it ts important to unders tand the con~ept of 3 X 10 - 3
11eight as~oci.ited 1vith each Jigit position. First, as an analogy, recall the weight of 8 X 10
1
- 80
numbers in the base 10 system, as shown in the diagram. By the same token, each 6 X 10
1 - 600
digit position in a nun1ber in ba!>e 2 has a weight associated with it: 0 X 10 - 0000
4 X 10 - 40000
1101012 = Decimal Binary 7 X 10s - 700000
lx2 - lxl - 1 1 740683
Ox2 =
lx2 =
Ox2 = 0 00
lx4 - 4 100
Ox2 - Ox8 - 0 0000
lx2' = lxl6 - 16 10000
lx2 5 = lx32 = 32 1 00000
-
53 110101

Kno""ing the ,veight of each bit in a binary number makes it simple to add them together to get its decimal equiva-
lent, as sho1-vn in Example 0-2.
Kno,ving the 1veight associated with each binary bit position allows 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-2

Convert the binary numbers to decimal (a) 1011, (b) 1100101, and (c) 10111.
Solution:
(a) 1011
Weight: 8 4 2 ]
Digit~ 1 0 1 1
Sum: 8+ O+ 2+ 1 = 11 10
(b) 1100101
\.\'eight: 64 32 16 8 4 2 1
Digits: l 1 0 0 I 0
Sum: 64+ 32 + 1
O+ 0+ 4+ O+ 1 = 101,0
(c)lOill
Weight: 16 8 4 2 1
Digits: 1 0 1 I I
Sum: 16 + O+ 4+ 2+ 1 = 2310

Eumple0-3

Use the concept of weight to convert 39 to binary.


19

Solution:
Weight: 32 16 8 4 2
1 0 0 1
1 1
32+ O+ O+ 1
'1?1.mefowe,39.. 100111r 4+ 2+ l 39

INTRooucnoN TO COMPUTING

I
Table o-1: Base 16 Number Systelt\s
oecintal Binary H;;
Hexadecimal system . . lied in computer
- 0000 o-
Base 16 ' or the hexatfecimnl system as it 1s caf b inary num bers
10 0001 i-
literature is used as a convenient
. rep resentation
o .
resent a s trlllg
f 0010 2-
0011 3-
For example, it is much easier for a h un,an belllg to rep . of
of Os and ls such as J00010010110 as its hexadecin1nl eqiuvalent 3 0100 4 -
S96H. The binarv system has 2 d igits, 0 and l. The base 10 syste m
10 digits, O thro~gh 9. The hexadecimal (base 16) system ~,as 16. d ig
has s4 0101 5 -
- 0110 6 -
its. ln base 16, the fi rst 10 d igits, 0 to 9, are the same as u1 decima l, ; 0111 7-
and for the remait1irlg six digits, the le tters A, B, C, D, E, and F a re 8 1000 8 -
used. Table 0-1 shows the equivalent b inary, deci mal, and h exad ecimal 9 1001 9 -
representations for Oto 15. To 1010 A
11 1011 B
Converting between binary and hex i2 1100 C
To represent a binary number as its equivalent hexadecimal nwnbe r, 13 1101 D
start from ~he.right and iroup 4 bits at a time, re placing each 4-bit binary 14 1110 E
nun1ber with its hex cqmvalent s hown in Table 0-1. To convert from hex 15 1111 F
to binary, each hex d igit is replaced with its 4-bit binary equivalent. See
Examples 0-4 and 0-5.

Example 0-4
Represent binary 100111110101 in hex. """,\le.

Solution:
;r,;t the number i.s grouped into sets of 4 bits: 1001 ll 11 0101
en each group of 4 bits is replaced with its hex equivalent:.
1001 1111 0101
9 F 5
Therefore, 100111110101, = 9F5 hexadecimal.

Example 0-5

. the hexadecimal numbers to b ,nary (a) F035, (b) AOl, and (c) 2E
Convert

Solution:
(a) F035
Hex: F 0
Bina rv: 11 ll 0000 3 5
The b' 0011 0101
m.uy representation is 1111000000110
Cb) AOI lOI
Hex: A 0
Binary: 1010 0000 I
The btnary repl"l.'9elltation is 10100000000~1
(c)2E
Hex: 2 E
Binary: 0010 1110
Th, binary ~ttNntation 111 101110 on
dropping the leeding Zffll9.

4
THt 80St MICROC
ONTROLLER -
AND EMBEDDED Sffl ...
Converting from decimal to hex
Converting from decimal to hex could be approached in two ,vays:

l. Convert to binary first and then convert to hex. Example 0-6 shows this method of converting deci,nal to hex.
2. Convert directly from decimal to hex by repeated division, keeping track of the remainders. Experimenting with
this method is left to the reader.

Converting from hex to decimal


Conversion fron1 hex to decimal can also be approached in two ,vays:

l. Convert from hex to binary and then to decimal. Example 0-7 demonstrates this method of con verting from hex to
decimal.
2. Convert directly from hex to decimal by summing the weight of all digits.

E,cample 0-6

(a) Con\'ert 451d to hex.

-l
32 16
-
0
-8
l - 4
1
2
-0 -ll 'First, convert to binary.
321-8+4+1=45
- ,_--
7)..
.,__ ~
~
.
i
45111 = 0010 1101 2 = 20 hex
2. ,, - <:)

(b) Convert 629 1 to hex. , T ..


512
-
256
-0128 -64 - -
~

l 0 l
12
-1 -16
J -08 -14 - 2
0
-1 1 ":>.. ).
~-
- ' (:)
629,o =(512 + 64 + 32 + 16 + 4 + 1) = 0010 0111 0101 = 275 hex
2
(c) Con\'ert 1714 hl to hex t~~~~.S,' \ C \J L
1024 512
-I 256 128
',3J:,
-0 -1 -064 -132 -116 -8 4
I
0 -
0 -12 -1
0
171 4,,, =(1024 + 512 + 128 + 32 + 16 + 2) =011 010110010 -
, - 6B2 hex

Convert the following hexadecimal numbers to decimal.


(a) 68210 =0110 101I 0010 \
2 ( (
1024 512 256
1 t o -I
128
-064 -132 16
- -08 -04
1024 + 512 + 128 + 32 + 16 + 2 = 1714
I -21 -
1
0
10

Cb) 9F20" =1001 1111 0010 1101l


32768 16384 8192 Allft. ""'"a 1
l "IU7V ""1'90 02, 512
0 0 1 t 1 l ~ 128 64 ~ 16 8
32168 + 4096 + 20M + 1024 + Sl2 + 256 + 32 8
+ +4+1 . _
0 0 1 -
o r 1 -0 -1
4 2
]
10

INTRODUCTION TO COMPUTING

5
I
0-3: Bin carry
~~~~~a~!A~d~d~i~ri~on~~==========~~=--
Table Sum
Table 0-2: Counting in Bases
!- 0 -
Hex
Decimal
Bina!}' [+O
~Ai+iB==============~Ot::::=============tl====~
O L -
-
0
0
1 QOi+!1:::=:::::::=::=::=::::oc=:::::::::=:::::::::::::::::::::::::::::Jot==::-
I
00()()1
()()()10 2 I+o 1
2 3 l+l
00011
3 4
4
00100 . n bases 1O, 2, and 16
5
00101 5 Counting 1 . . between all tluee base~, in Table 0-2 we
00110 6 To show the relationship frorn o to 31 in d ecima l, along with
6 7
7
00111 show the sequence of nu~b:C! numbers. Notice in each base that
8
9
01000
01001
8
9 the equivalent ~,nary;"to
when one more ,s add
th: highest digit, that digit becomes zero
I-highest digit position. For example, in
01010 A
10 and a 1 is earned toththe nerrxy to the next-highest position. ln binary,
11 01011 B
. al9+1-0w1 aca .h
12 01100 C d ec,m . - . . iady in hex, p + 1 = 0 w1t a carry.
D 1 + 1 : 0 with a carry, s1m1 '
13 01101
1-l 01110 E
15 01111 F Addition of binary and hex numbers
16 10000 10
11 The addition or binary numbers is a very straightforward pro-
17 10001
10010 12 cess. Table 0-3 shows the addition of two bits. The discussion or
18
19 10011 13 subtraction of binary numbers is bypassed s.i nce all computers use
20 10100 14 the addHion process to implement subtraction . Although computers
21 10101 15 have adder circuitry, there is no separate circuitry or subtractors.
22 10110 16 Ins tead, adders are used in conjunction with 2's co111pleme11t circuitry
23 10111 17 to perform subtraction. In other words, to implement "x - y", the
24 11000 18 computer takes the 2's complement of y and adds it to x. The con
25 11001 19 cept of 2's complement is reviewed next. Example 0-8 shows the
26 11010 lA addition or binary numbers.
27 11011 18
28 11100 lC
29 11101 10 2's complement
30 11110 lE To get the 2'scomplementof a binary number invert all the bits
31 11111 lF
and then add 1 to the result. Inverting the bits is ;imply a matter of
chSeanEging all Os to ls and ls to Os. This is called the J's complement.
e xample 0-9.

Exampleo-8

Add the binary numbers (a) 1011 + 111 and (b) 11010011 + 11011
11.
Solution:
(a) 1011 + 111
Decimal Equivalent
IO 1 I
0111 11
10010 +7
(b) 11010011 + 1101111 18
Dttima/ Eq1livaltnt
110100 11
01 1 0111 1 211
101000010 + 111
322

6
THE 8051 MlCROC -
ONTROL . .....-.d
LER AND EMBEDDED SD.....-

....
Example 0-9
Take the 2's complement of 10011101.

Solution:
10011101 binary number
01100010 l's complement
+ 1
01100011 2's complement

Addition and subtraction of hex numbers


ln studying issues related to software and hardware of computers, it is often necessary to add or subtract hex num-
bers. Mastery of these techniques is essential. Hex addition and subtraction are discussed separately below.

Addition of hex numbers


This section describes the process of addmg hex numbers. Starting with the least significant digits, the digits are added
together. If the result is less than 16, write that digit as the sum for that position. If it is greater than 16, subtract 16 from it
to get the digit and carry 1 to the next digit. The best way to explain this is by example, as shown in Example 0-10.

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.

..

Example 0-10
Perform hex addition: 2309 + 94BE. ;l, ~ ~
I /-1
Solution: (:) I
2309 / LSD: 9 + 14 =23 23 - 16 = 7 with a carry
+ 94BE 1+ 13+11 = 25 25 - 16 = 9 with a carry
8897 ,. 1 +3 +4=8
MSO: 2+9:sB

Exmple 0-11
Perforna hex subtraction: 59F - 288.

Solidion:
I.SD: 8 from 15 s 7
11 from 25 (9 + 16) 14 (B)
;g1roa, fl-t>a;J

-
Dn'RoDUC110N TO COMPUTING
7
Ha Sy,,.bol Ha sy,,,i,.1
41 A 61 a
ASCII code tation of number 8 62 b
The discussion so far has re-olved around the r:rese;esented by Os and ,2 c 63 c
svstems Sll\Ce all 1nformation ln. the computer must oi:: characters. 1n the 43 D 64 d
Is bmary pattems must be as.ggned to letters and . tandard Code iot 44
1%05 a <t.anda.rd representation called ASC/fj/\mencan 5 eel "askE") - -
Information Interchange} was established. The ASCIJ (pronoun~ the English S9 Y 79 y
code as.1gns buwy patterns for numbers O to 9, au the letters :ol codes and SA z 7A z
alphabet, both upperca5e (capital) and lowercase, and m~y con . is used by
punctuabon marlc.s The great advantage of this system IS that I1 t The Figure 0-1. Selected ASOI Codts
mO!,t computers, so that information can be shared among compu ~rs.
ASCII sy.tem uses a total of 7 bits to revresent each code. For example, 00 0001
,. ,.
is ~signL'<l to the uppercase letter "A" and 110 0001 is for the Jowerca~ ~ Fgure 0-1 sho1vs selected ASCil codES
Often, a ll!ro 1s laced in the most si cant bit ition to make n g. ~ 1 c e. ni' tandard for keyboards used in the
complete list of ASCll codes is given in Appendix F. The use of ASCII IS ~ot .0 Y s d dis la in characters b ou u
United States and many other countries but also provides a standard for prmting an P Y g Y tp t
devices <uch a. printers and monitors. . .
Notice that the pattern of ASCII rodes was designed to allow for easy n1an1pulat1on of ASC~ data. For example,
d1g11s O through 9 are represented by ASCIJ rodes 30 through 39. This enables a program to castly convert ASCU to
_decimal by maski,.f; off the "3" in the upper nibble. Also notice that there c; a relationship between the uppercase and
lowercase letters. e uppercase letters are represented by ASCII codes 41 through SA while lowercase letters are rep-
resented by codes 61 through 7A. Looking at the binary code, the only bit that i!. different between the uppercase "A"
and lowercase a is bit 5. Therefore, conversion between uppl.'rcase and lowercase is as simple as changing bit S of the
ASCII code.

Review Questions
l. CWhy do computers use the binary number system instead of the decimal system1
2. onvert 3-1 10 to bmary and hex.
3. Convert 110101, to hex and decimal.
4. Perform binary addition: 101100 + 101.
5. Convert 101100, to its 2's complement representation
6. Add 368H + F6H. .
7. Subtract 36BH - F6H.
8. ~Vrite "80x86 CPUs" in its ASCII rode (in hex form).

SECTION 0.2: DIGITAL PRIMER


This stion gives an overview of digital I .
gate:, tha! perform these functions. Next I . og1c and design. First, we cover b' .
some logic devices commonly found . , .ogic gates are put together to fo . mary logic operations then we show
in microcontroUer interfacing. rm sunple digital circuits. F~lly, we CO\'ff

Binary logic
As mentioned earlier, computers use th . 5 r -~-~
l~~ls can be represented as the two di 1:,e binary number system beca
distinct voltage levels. For example a gi Oand I. Signals in digital IUSe the hvo voltage
Figure 0-2 ,how~ tlus system wth' system _may define OVas I . e CCtrorucs have tw
val.id digital signal in tlus examp~e ~~~du:-m. to(erances for va?~i an~ +S Vas logic
w1thm either of the tw nsha in the voltage A
t 3 J._~i,lfj
05
ded are 2
Logic gates as.
I
Bmary logic gates are sunple circu
one output signal Several of,.___ t ,ts that take one or mo .
u..,,,., ga es are defined h re input si&nals 0
ere. lnd send out
8
Fla- ~2- lh7ZJ'
THE 80St MICR
OCoNTROLLER C
.\ND EMBEDDED 9'1QS
logical AND function
AND gate Output
1 AND on them. See Inputs
The AND gate takes two or more inputs and per o~ a ~gicf AND ate
the truth table and diagram of the AND gate. Notice that 1f both ~p~ts tote tp t ~e XY XANDY
are 1 the output wiU be l. Any other combination of inputs will give a 0 ~ ut. In 00 0
ex~ple shows two inputs, x and y. Multiple outputs are also possible for logic ?a es.
.
the case of AND, 1 all .Inputs are 1, the output 1s
. f . t o the output IS zero.
1. l any mpu IS , 01 0

10 0

11 1
OR gate
The OR logic function will output a 1 if one or more inputs is 1. If all inputs are 0, X XANDY
y
then and only then will the output be 0.

Logical OR Function
?, Tri-state buffer .
Output
A buffer gate does not change the logic level of the input. It is used to 1so1ate or inputs
amplify the signal. XY XORY
00 0
Inverter 01 1
The inverter, also called NOT, outputs the value opposite to that input to the gate. 10 1
That is, a 1 input will give a O output, while a O input will give a l output. 11 1

XORY
XOR gate
The XOR gate performs an exclusive-OR operation on the inputs. Exclusive-OR
produces a 1 output if one (but only one) input is 1. lf both operands are 0, the output Buffer
is zero. Likewise, if both operands are 1, the output is also zero. Notice from the XOR
truth table, that whenever the two inputs are the same, the output is zero. This function
can be used to compare two bits to see if they are the same.
ContTol

NANO and NOR gates


Logical Inverter
The NAND gate functions like an AND gate with an inverter on the output. It pro-
duces a zero output when all inputs are 1; otherwise, it produces a 1 output. The NOR gate Input Output
functions like an OR gate with an inverter on the output. It produces a 1 if all inputs are O;
othenvise, it produces a 0. NAND and NOR gates are used extensively in digital design X NOTX
because they are easy and inexpensive to fabricate. Any circuit that can be designed with 0 1
AND, OR, XOR, and INVERTER gates can be implemented using only NANO and NOR 1 0
gates. A simple example of this is given below. Notice in NAND, that if any input is zero
the output is one. Notice in NOR, that if any input is one, the output is zero. '
X --{)o- NOTX
Logic design using gates _ d. ts If we add two bina.tY digits there are four J)Ossib!t
Next we wiU show a sitrtple logic design to add two bmary igi .

outcomes;
Carry S11m
O+O= 0 0
O+l= 0 1
]+0= 0 1
J+I= 1 0
Notice that when we add 1 + 1 we get O\vith a carry to the next higher place. We will need to de!enni.ne the sum
and the carry for this design. Notice that the sum column above matches the output for the X~R function, and that the
carry column mat.ches the output for the AND function. figure 0-3 (a} shows a simple adder unplemented with XOR
and AND gates. Figure 0-3 (b) shows the same logic circuit implemented with AND an~ OR gates.
Figure 0-4 shows a block diagram of a half-adder. Two half-add ers can be comb med to form an adder that can
add three input digits. This is called a full-adder. Figure 0-5 shows the logic diagram of a full-adder, along with
a block diagram that masks the details of the circuit. Figure 0-6 shows a 3-bit adder using 3 full-adders.

Decoders
com~:~:~::;mri1;:: t~~ai;;lka~on of logic gates is the decoder. Decoders are widely used for address decoding in
e s ows ecoders for 9 (1001 binary) and 5 (0101} using invert ers and AND gates.

Flip-flops
A widely ~sed component in digital systen'IS is the fli . fl .
sho,;. the l~gic diagram, block diagram, and truth table For o~. Fr~uently, Oip-flops are used to store data. Figure 0-8

as the clock is activated. A 0-FF holds the d:: r;~:a~::


e D flip-flop (D-FF) is widely used tot h d
as ~:e~: ~~~ table that a 0-FF grabs the data at the input
a ,p- op.

X
y

~ -...Jol------- Carry
(a) Half-Adder Using XOR and AND
Cb) Half-Adder using
. ANO, OR, Inverters
Figure 0-3. Two Implement Ii ons of a Half-Adder

X
Sum
Half-
Adder
y
Carry
out

f',gun 11-4. Block Dia


gri:n of HlfAdder

10
TJiE 8051 MlCROC
ONTROLLER
AND EMBEDDED sw- --
Carry
X Half-
\..---Sum Adder Final
y
Carry
____,sum

Cou t Half-
Adder Carry
Cin

Cm-----~
Final Sum

figure 0-5. FuJI-Adde r Built from a Half- Adder

lJ --
)
,.. I ct> i I XO -
i
so
~ 1)
) Full-
\ ' Adder
YO
~ Carry

10
). f d- -) t I
> -4' Xl
Full-
SJ

Adder
Yl Carry

I
X2 52
Pull-
Adder Carry
y2
S3

Figure 0-6. 3-Bit Adder Using 3 Full-Adders /'O, V'


- t,\s)
>'~
.J
lP b''

I LS
p 1 - - -- 'o
0
I
(a) Address decoder for 9 (b11u1ry ~001 )
The output of tM AND gate y.1U be 1 Cb) Addre"s decoder for 5 Cbinary 0101)
if and only If the input ill bmary 100I. The output of the AND gate " 'ill be 1
If and only if the input ill binary 0101.

....
IN'raooucr10N ro coMPUnNG
lt
Carry
>. HaJf.
X
y
', ''} " Su m y Adder Final
/ Carry
~-_.JSum

~ '
. ",, ' - Cout HaU- 1---1
.
- Cm
Adder Carry

Final Sum

Figure 0-5. Full-A dder Built from a H alf-Adder

-
~
,. It, b I
'( . , XO -~ ' so
) Full-
0 'O ' \ Adder
YO
~ Carry

~ -) ' r,
>I ;, ..f"
1 I
XI 51
Full
Adder
Yl Carry

I
X2 52
Full-
Adder Carry
Y2 53

Figure ~ . 3-Bit Adder Using 3 Full-Adders /'~ "'


- ~ .)I~
l (/c,, b; {

I
p
LS
..__ ___,,
p
I
(a} Addl'l'Ss d ecoder for q (bina ry 1001)
The output of the AND gai. 'l\'ill be 1 (b) Add ~ decod.r for 5 (binary 0101)
iJ and only If the input is bane,y 1001. The output of the A'.\10 gai. will be 1
If md only ti the input is binary 0101.

lless M . Addn 11 Decod


.,,

11
I
Q
Clk D
-No X
no chan2e
Q 0
- - D -1, 0
D ,., ,., Q
1 1
.- , 1,
- - Cl.k

ak -Q -Q x == don't care

4>
- '
/
'
,
J.)

(c) Truth table


(b) Block diagram
(a) Circuit diagram
- ) I
Figure 0-8. D Flip-Flops v~it ~d C. C..."'

Review Questions hen all inputs are 1..


t . 1
. ,. ~t) gives a 1 outpu w re of its mputs ts .
l. The logical operation r. gives a 1 output when 1 o~ : : inputs have the same value.
2. The logical opera~on JV I is often used to comp~e t
3. The logical operationd :,< t change the logic level of the mpu .
A gate oesn?
4. Name a common use for ~p-flops. 'd tify a predetermined binary address.
5.
6. An address is used to i en

SECTION 0.3: INSIDE THE COMPUTER . . .


al workin of computers. The model.used
. 'de an introduction to the orgaruzahon and ~teclmdin the M PC PS/2, and compatibles.
In this section we provt Li bl to all computers in u g ' d t ology
is generic, but the conc:pts d~scu~sed_are a~~ ~It~ review definitio~ of some of the most wfely use ermm
Before embarking on thlS subject, it will ~e b ~e ROM RAM and so on. c*-'{ ?-,'-:_ ~
in computer literature, such as K, n1ega, g1ga, y ' ' ' ~ ~
a I
<\ ('. <vA. \o- A:.
Some important terminology ......_ _ _ :_
::, _ __ __ _ _ _ _ _ _
One of the n,ost important features of a computer is h?w
much memory it has. Here we review terms. used to describe / 1
Bit 0
amounts of memory in IBM PCs and comp~tibles. Recall from
Nibble 4 0000
the discussion above that a bit is a binary d1g1t that can have the \
Byte r 0000 0000
value Oor 1. A byte is defined as 8 bits. A ni~ble is ~a~ a byte, or
4 bits. A word is two bytes, or 16 bits. The display IS intended to
Word 0000 '()000 0000 0000
show the relative size of these units. Of course, they could all be
composed of any combination of zeros and ones. . Id
10
A kilobyte is 2 bytes, which is 1024 bytes. The abbreviation K is often used. For example, some flopp~ ~sks ho
356K bytes of data. A megabyte, or meg as some call it, is 220 bytes. That is a little over 1 million bytes; 1t LS exactly
1,048,576 bytes. Moving rapidly up the scale in size, a gigabyte is 230 bytes (over 1 billion), and a terabyte is 2 bytes (over
40
1 trillion). As an example of how 20 some
4
of
20
these terms are used, suppose that a given compu ter has 16 megabytes of
memory. That would be 16 x 2 , or 2 x 2 , "."hie~ is 224. Therefore, 16 megabytes is 2 24 bytes. ,,
Two types of memory commonly used in ffilcrocomputers are RAM, which stands for " random access memory
(sometimes called read/write rnemory), ~d.ROM, ~hich stands for "read-only memory." RAM is u sed by the computer
for temporary ~torage of progr~ that 1t 1s runn.mg. ~at data is lost when the computer is turned off. For this reason,
RAM is sometimes called volat1/e niemory. ROM contams programs and informati a1 ti' o f the corn
puter. The .mformation m ROM is permanent, cannot be changed by the use d on
. essenti to th on is turned
h opera
off. Therefore, it is called nonvolatile memory. r, an 1s not 1ost w en e power

Internal organization of computers

The internal working of every computer can be broken down int thr . . . ) mem
ory, and I/0 (input/output) devices (see Figure 0-9). The function of~ ee P~rts: CPU (cen tral p rocessmg ~ t 'stored
in memory. The function of I IO devices such as the keyboard and v. d e CP ~ is. to execu te (process) informabo~,-.dd'Ul
1
eo monitor LS to provid e a means of commwuu-...,.
12

THE
8051
MICRocoNTR.otLER AND EMBEDDED~
-
Address Bus

Peripherall>
Memory

CPU
(monitor,
(RAM, ROM) printer, etc.)

Data Bus
,

figure 0-9. Inside the Computer

f all d bus The bus carries information


~,'ith the CPU. The CPU is connected to memory and I/0 through strips o Wll'e c e a . t there are
from place to place ~ e a computer just as a street bus carries people from place to place. In every compu er
three types of buses: address bus, data bus, and control bus. dr d
For a device (memory or I/0) to be recognized by the CPU, it must be assigned an address. The ad ess assign~
to a given device must be unique; no two devices are allowed to have the same address. The CPU puts the addre~s (m
binary, of course) on the address bus, and the decoding circuitry finds the device. Then the CPU ~ses_ the data bus et~er
to get data from that device or to send data 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.

More about the data bus


Since data lines are used to carry information in and out of a CPU, the more data lines available, the better the CPU.
Uone thinks of data lines as highway lanes, it is clear that more lanes provide a better pathway between the CPU and its
external devices (such as printers, RAM, ROM, etc.; see Figure 0-10). By the same token, that increase in the number of
lanes increases the cost of construction. More data buses mean a more expensive CPU and computer. The grouping of data
lines is called data bus. The average size of data buses in CPUs varies between 8 and 64. Early computers such as Apple 2
used an 8-bit data bus, while supercomputers such as Cray use a 64-bit data bus. Data buses are bidirectional, since the
CPU must use them either to receive or to send data. The processing power of a computer is related to the size of its buses,
since an 8-bit bus can send out 1 byte a time, but a 16-bit bus can send out 2 bytes at a time, which is twice as fast.

More about the address bus


_Since the address bus is used to id~ntify the devices and memory connected to the CPU, the more address buses
available, the larger the number of devices that can be addressed. In other words, the number of address buses for a

Address Bus

RAM ROM Printer Disk Monitor Keyboard


CPU

Data Bus

Read/write
Control Bus

F'
gure 0.10. Jntemal Organization of Computers

-
1NnooucnoN TO COMPUTING

13
. Th umber of locations j5 al,vays equal to 2
. I ations """ith \.vhich it can commurucatebus e :Or
example, a CPU \Vith 16 address lin~
CPU dt!t~ri:~~~;ru:r!rd~!:iines, regardless of the size of the:a taEach. location can l1ave a maximum of 1 byte of
~;er::v~de a total of 65,536 (2'") or 64K bytes of addr~ssable ;;:r &us
are what is called byte addressabl:. As another
dat:. This is due to the fact that all general-purpose m1c~opr~nd 16 data lines. [n this case the total acc~ss1~le memory
example, the IBM PC AT uses a CPU with 24 address Lines would be 224 locations, and since each location is one byte,
is 16 megabytes (22 = 16 megabytes). In this example there is a unidirectional bus, which ~eans that the CPU uses the
there '"ould be 16 megabytes of memory. The address bus al ber of memory locations addressable by a given
ze Toe tot num b
T
address bus only to send out addresses. o sum.man . dless of the size of the data us.
CPU is always equal to 2 where xis the number of address b1<S, regar

CPU and its relation to RAM and ROM n A ROM The function of ROM in compute
1'A
O
For the CPU to process information, the data must be stored in
1
r
J.V'UY. r~
is to provide information that is fixed and permanent. This is informabon ~uch as tables for character patterns to be
displayed on the video monitor, or programs that are essential to the working of the ~ompu~er, SltCh _as progra~ for
testing and finding the total amount of RAM installed on the system, or programs to dtSplay nlformation on the video
monitor. In contrast, RAM is used to store information that is not permanent and can change with time, such as various
versions of the operating system and application packages such as word processing or tax calculation packages. These
programs are loaded into RAM to be processed by the CPU. The CPU cannot get the information directly from the disk
since ~h: disk is too slow. In other words, the CPU first seeks the informatio11 to be processed from RAM (or ROM).
<?r''Y lf it 1s not the~e does the CPU seek it from a 1nass storage device such as a disk, and then it transfers the informa-
tion to~- For this reason, RAM and ROM are sometimes referred to as pri1nary 111emory a11d disks are called seco 11 dary
111en1ory. Figure 0-11 shows a block diagram of the internal organization of the PC.

Inside CPUs
~ program stored in memory provides instructions to the CPU t f . .
adding ?ata such as payroll data or control ling a machine such o per o~m an actt~n. T11e action can simply be
tnstructions from memory and execute them. To perform th _as a r~~ot. lt is the function of the CPU to fetch these
resources such as the following: e actions o etch and execute, aJJ CPUs are equipped ,vith

1. ~;;mos~ among the r:source~ at the disposal of the CPU are a numb .
t b ";'atlon temporarily. The information could be two v 1 t b er of registers. The CPU uses registers to store
:om
0
: ;ee~t~d

~~::s;~~:::t
registers is ~he
m:rory. Registers inside the CPU can ~:;~bi~ 1~~~c;;s~~' o r the address of the value needed
an; biCPgger the registers, the bett~r the1CPU ; or~vedn 64-bit registers, depending
su a U. e sa vantage of more and bigger

:i,.
I a.
a.
I [ Program Counter
I a
(/)
c:,
C:
(/)
Flags
ALU lnstruction Register
Q
Instruction ::,
I decoder, liming
and control '
a-
c:,
lniemal
~
buses

Register A
..or
0

a,
~
Register B
Regil.ter C
Register D
F"gure 0-11. Internal Block Diagram of a CPU

14
THE 8051 MICRocoNn
OLLER AND EMBEDDED S -
. . . . e ALU section of the CPU is resp onsible fo r
., The CPU also has what is called the ALU (ar1thmetic/logi~ urut). !1'd 'd d logic function s such as AND, O R,
performing arithmetic functions such as add, subtract, multiply, an ivt e, an
and NOT.
. unter is to point to the address of the next
3. Every CPU has what is called a progra1n counter. The function of the program ~o is incremented to point to the address of
instruction to be executed. As each instruction is executed, the program coun er ed th address bus to find and fetch
~ truction pointer.
0
the next instruction to be executed. The contents of the progr~ co~ter are plac ~
the desired instruction . In the IBM PC, the program counter is a register called IP, or e lJ1S
. f h d . t0 the CPU One can think of the
4. The function of the instruction decoder is to interpret the in~truction e.tc e 11.' d h t teps the CPU should
instruction decoder as a kind of dictionary, storing the meaning of each instruction an w a s ds 1.t defines a CPU
take upon receiving a given instruction. Just as a dictionary requires more p~ges the more wor '
capable of understanding more instructions requires more transistors to design.

Internal working of computers


To demonstrate some of the concepts discussed above, a step-by-step analysis of the p rocess a CPU would go ~ough
to add three numbers is given next. Assume that an imaginary CPU has registers called A, B, C, and D. It has an 8-b1t data
bus and a 16-bit address bus. Therefore, the CPU can access memory from addresses 0000 to FFFFH (for a total of lOO?OH
locations). The action to be performed by the CPU is to put hexadecimal value 21 into register A, and then add to register
A values 42H and 12H. Assume that the code for the CPU to move a value to register A is 1011 0000 (BOH) and the code
for adding a value to register A is 0000 0100 (04H). The necessary steps and code to perform them are as follows.

Action Code Data


Move value 21H i nto register A BOH 21H
Add value 42H t o regis t er A 04H 42H
Add va l ue 12H t o register A 04H 12H

If the program to perform the actions listed above is stored in memory locations starting at 1400H, the following
\vould represent the contents for each memory address location:
Memory address Contents of memory address
1400 (BO)code for moving a value to register A
1401 (21 ) value to be moved
1402 (04 )code for adding a value to register A
1403 (42) value to be added
1404 (04 )code f or adding a val ue to register A
1405 (12)va l ue to be added
1406 (F4 ) c ode for halt

The actions performed by the CPU to run the program above would be as follows:
1. The CPU's program counter can have a value between 0000 and FFFFH Th
value 1400H, indicating the address of the first instruction code to be ex t ; ~gram counter must be set to the
loaded with the address of the first instruction, the CPU is ready to exe:~~e~ ter the program counter has been
2. The CPU puts 1400H on the address bus and sends it out. The memo . . .
activates the READ signal, indicating to memory that it wants the b /Y c~cui~ finds the location while the CPU
of memory location 1400H, which is BO, to be put on the data bus yd ebat ocati~n l400H. This causes the contents
. . . an rought into the CPU.
3. The ~ d~':5 the ms~ction ~ wt~ the help of its instruction decoder di . . .
that instruction 1t knows 1t must bnng mto register A of the CPU th b . ctionary. When it finds the definition for
commands its controller circuitry to do exactly that. When it brings . e alyte m the next memory location Therefore it
closed m v ue 21H from ,
s~ that the d oors ofall registers are except register A. Ther f memory location 1401, it makes
directly into register A. After completing one instruction, the progr.;ore, when ~alue 21H comes into the CPU it will go
to be executed, which in this case is 1402H. Address 1402 is sent O t cothunter pomts to the address of the next instruction
4 u on e address bus to fetch th
From ~emory location 1402H it fetches code 04H. After decodin th e next mstruetion.
of reg15ter A the byte sitting at the next address (1403). After 't bg~ e CPU knows that it must add to the contents
- , nngs the value (in this case 42H) into the CPU, it
1Nnoouc1 ION TO COMPUTING

IS
dd.ition lt then takes the resui 1
. perform the a co~ter becomes 1404, the
Jue to the A L.U to hile the program
A along \'\-ith this va . ter A. Meanw
'd thecontentsofregister Ip tandputsitinregts
prov, es the ALU's OU u cru deeoded, and executed. ThiscCJde
of the addition fro~instruction. . fetched in!O the I-{.
addre:.s of the nex n the address bus and the coden~er is updated to 1406 . truction tells the CPU to stap
5. Address 1404diH ,s,;.~~; to register A. The program cou d ecuted This HALbTenlll:e of the HALT, the CPU Would
is again ad ng a ched in an ex . . [n the a s
. ntents of address 1406 are ~et the next instrucbon. . .
6. F,nally, th_e cothe program counter and asking fo~. instructions. d the CPU distmguish between
inc~entin~ating the program counter and fetc tng . d f 42H. How woul th next value into register A.
continue up 1 04 ,nstea o n ove e I
1
ddress 1403H contained va ue f thiS CPU means f tie following memory OCation
Now suppose that~ code 04? Remember that code 04_ o\ moves the contents o ,
data 04 to be added an d ode the next value. It s1mp y
Th efore the CPU will not try to ec
t'er A, regardless of its value.
.intoerregts

Review Questions
J. How many bytes is 24 kilobytes? . . sed n computer systems?
2. What does "RAM" stand for? How ,sa t u ~ rs stems?
3. What does "ROM" stand for? How ~ ,t used ,n compute y
4 Why is RAM called volatile memory
s . componen ts of a computer. system.
List the three ma1or . t
6. What does "CPU" stand for? Explain its htnction in a compdu ~\ briefly the purpose of each type of bus.
. . s of buses found in computer systems an s a e
7.
8. List the three type . as uru'd'rectional
State which of the fo LIowing 1 and which is bidirectional. .

9. (a)
[fandata bus (b)
address busaddress bus compu_t~ has 1O; rin~, w ha I is the maxinlum amount of memory 1t can access.1
for a given
10. What does" ALU" stan~ for? What 1s ,ts pur~ose.
11. How a,e registers used in computer systems;
12. What is the purpose of the program counter.
13. What is the purpose of the instruction decoder?

SUMMARY

The binary number system represents all numbers with a combination of the two binary digits, 0 and 1. Th~ use
of binary systems is necessary in digital computers because only two states can be represented: on or off. Any bi!W}'
number c~ be coded directly into its h~xadecimal equivalent for the convenience of humans. Converting from b~ary/
hex to decunaJ, and vice versa, as a str&ghtforward process that becomes easy with practice. The ASCII code is a bi!W}'
code
input used to output.
and/or represent alphanumeric data internally in the computer. It is frequently used in peripheral devices for

The logic gates ANO, OR, and ln~erte~ are t~e basic building blocks of simple circuits. NANO, NOR, and XOR
gates fare also used to unplement c,rcu,t design. Diagrams of half-adders and full add les of lhe
I gi
use o o c gates cor c1rcwt
des,gn.
n=.cod ers are used to detect certain address- FLi ers flwere given as examptch data
until other circuits are ready for it. es. P ops are used to a di
I
The major components of any computer system are the CPU, memory, and l/O . ,, " telll"
porary or permanent storage of data. In most systems, memory can be acce devices. Memory refen ~
megabyte, gigabyte, and tembyte are used to refer to large numbers of bytes Thssed as bytes o~ words. The terms ~obyW,
puter systems: RAM and ROM. RAM (random access memory) is used f r ere are two main types of memory m C(lllt"
ROM (read-only memory) is used for pem,anent storage of programs dod temporary storage of programs and data.
order to function. All co~ponents of the computer system are under~ ata that the computer system must haft ill
//0 (input/output) devices allow the CPU to communicate With h control of the CPU. Peripheral devices such
types of buses in computers: address, control, and data. Control bu:'ans or other computer systems. There are tfu'II
address bus is used by the CPU to locate a device or a memory loc . are USed by the CPU to direct other device& 1111
and forth between the CPU and other devices. ation. Data buses are used to send Information a.ck
FinaUy, this chapter gave an overview of digital logic.

16
THE 8051 MICROC()........ ..:.---a
F
... "'OLLBa AND IIIDEDDBD.........-:-
pROBLEMS
SECTION 0.1: NlJMBERING AND CODING SYSTEMS
1. Convert the following decimal numbers to binary.
(a) 37 (b) 77 (c) 96 (d) 1050
2. Convert the following binary numbers to decimal.
(a) 100100 (b) 1000001 (c) 11101 (d) 1010 (e) 00100010
3. Convert the following decimal numbers to hexadecimal.
(a) 67 (b) 123 (c) 99 (d) 1100 ".>
4. Convert the following hex numbers to binary and decim al. "
(a) 2B9H (b) F44H (c) 912H (d) 2BH (e) FFFFH ::::>I..o
5. Convert the values in Problem 1 to hex. o
6. Find the 2's complement of the following binary numbers.
(a) 1001010 (b) 111001 (c) 10000010 (d) 111110001 ~ c1
7. Add the following hex values. o" J ~e
(a) 2CH + 3FH (b) F34H + SD6H (c) 20000H + 12FFH (d) FFFFH + 2222H cl'
8. Subtract the following hex numbers.
(a)56-3E (b) 456F-OECF (c) F089EE - 897DEF (d) 76F-2AD J
, 9. Show the ASCII codes for numbers 0, 1, 2, 3, ... , 9 in both hex and binary .
v~
_J,(l4!- ~

tftY'
~~

b 10. Show the ASCII code (in hex) for the following string:
"U.S.A. is a cow1try" CR, LF, "in North America" C R, LF,
CR is carriage return, LF is line feed

SECTION 0.2: DIGITAL PRIMER ~ ~~


11. Draw the logic diagram for Y =AB+ CD. ' ~~ -rf,
"'-.... '
12. Show the truth table for a 3-input OR gate. ,..)If
13. Realize the logic equation of Problem 11 using NANO gates only.
14. Sho\.v the truth table for a 3-input AND gate.
(15. Design a 3-input XOR gate w ith a 2-input XOR gate. Show the tr uth table for a 3-input XOR.
" 16. List the truth table for a 3-input NANO. 1
17. List the truth table for a 3-input NOR. \ __:::;- --
? 18. Show the d ecoder for binary 1100.$ .b-~ I
0 t>
" 4.9. Draw the d ecoder for'binary 01110}!4 o--t;r- - I - tp.
20. List the truth table 'for a D-Ff._.., 1v-J' -\ t{, ') IA 1,,f
~ iol!t
-~ -
,o--
1~

')... -
lo -
SECTION 0.3: INSIDE THE COMPUTER , \;,!Gr ~ i ~
21. Answer the following: ,,.
\ "'\:) ~ )
) 0
-
-

(a) How many nibbles are 16 bits?


(b) How many bytes are 32 bits? '1
(c) If a word is defined as 16 bits, how many words is a 64-bit data item? ~
i ,,Q. (d) What is the exact value (in d~al) of 1 meg? ~J.():::. to'4 ~ S?b
~\ i(e)....How many K is 1 meg? IoV 1 ~ ~ .,.. ) I.( ' vJi t \I
~ What is the exact value (in decimal) <1f 1 giga? 0 , o ,o
(g) How many K is 1 giga? {1 c. ) < ' ~ v l. v l.
1
(h) How many meg is 1 giga? f f "I
(i) If a given computer has a total of 8 megabytes of memory how man b ; ' (' .
kilobytes is this? ' Y Yes m decunal) is this? How many
"- 22. A given mass storage device such as a hard disk can store 2 gigabytes of informa . .
text has 25 rows and ea~ row h~ 8~ columns of ASCD characters (each char tio~ Asswrung that ~ch page of
many pages of information can this disk store? acter - 1 byte), approxunately how
~ 23. In a given byte-addressable computer, memory locations 10000H to 9Pf . .
first location is 10000H and the last location is 9FFFFH. Calculate th f FF1: are available for user programs. The
(a) The total number of bytes available (in decimal) e O11owing:
(b) The total number of kilobytes (in decimal)
...
lknlooucr ION TO COMPUTING
1'1
, ing capability? ,d_mum value that can
- address list the ma
l What is its memory each computer, .----=
S
ssor has a 20--bit addres~ b:~ir data bus widths- for
24. A micropr::ed several comp~ters(~1~~th hex and decimal).
25 Below areh toth e cr1t
ru
1 at a tune m

be broug t m .th S-bit data bus


A le 2 w1 an b
? (a) 1J
PC with a 16-bit data us PU given the size of the
c- icj ~:M PC with a 32~:: ~ : ~:-bit data bus ted for each of the following C s,

26.
c.
(d) Cray supercompu f
Find the total amount o m
address buses. . K)
emory, in the units reques '
n- .._ ,.
,
., " !:;,, i
to (

- "t! r1
c
'

./ (a) 16-bit address bus(~ e ab tes) '"


(b) 24-bit address bus(~ m g aby tes and gigabytes) ?
(c) 32-bit address bus(~ meg bytes gigabytes, and terabytes) . unidirectional. Why.
(d) 48-bit address bus (m mega. yb"directiona1 and the address bus is
mputer, the data bus lS 1 omputer?
~~e ~
.

~;: ~;'~ function of the_ progra:;:i:;~~rp:r;~;~g addition? 4r.


29. WhichsectionoftheCPU1sres~o CPU. 1t1,tl''"' t I"/' re,1 Rt..
30. List the three bus types present in every

ANSWERS TO REVIEW QUESTIONS


SECTION 0.1: NUMBERING AND CODING SYSTEMS h f two voltage levels: on and off.
1. Computers use the binary system b ecause e ach bit can ave
,.. one o
2. 3410 =1000102= 2216 C'""' ') ~ by
3. 1101012 = 3516 = 5310 {) ' "" k{
4. 1110001
5. 010100
6. 461 I
7. 275
8. 38 30 78 38 36 20 43 50 55 73
,.
SECTION 0.2: DIGIT AL PRIMER
1. AND l._ ~ I -,.( I Y- J'
2. OR
3. XOR
4. Buffer
5. Storing data
6. Decoder

SECTION 0.3: INSIDE THE COMPUTER


1. 24,576
2. Random access memory; it is used for temporary storage of programs that the CPU is running, such as the operat-
ing system, word processing programs, etc.
3. Read-only memory; it is used for permanent programs such as those that control the keyboard, etc.
4. The contents of RAM are lost when the computer is powered off.
5. The CPU, memory, and 1/0 devices
6. Central processing unit; it can be considered the "brain" of the computer; it executes the programs and controla all
other devices in the computer.
7. The address bus carries the location (address) needed by the CPU; the data bus carries information in and out of the
CPU; the control bus is used by the CPU to send signals controlling 1/0 devices.
8. (a) bidirectional (b) unidirectional
9. 641(, or 65,536 bytes
10. Arithmetic/ logic unit; it performs all arithmetic and logic operations.
11. It is for temporary storage of information.
12. It holds the address of the next irtstruction to be executed.
13. It tells the CPU what steps to perform for each irtstruction.

18
THE 8051 MICROCONTROLLBR AND BMDDDID _- I .. ,
CHAPTERl

THE 8051
MICROCONTROLLERS

OBJECTIVES

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

),, Con1pare and contrast microprocessors and microcontrollers


> Describe the advantages of microcontrollers for some applications
> Explain the concept of embedded systems
> Discuss criteria for considering a microcontroller
),, Explain 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

,. > , , . \ ,. a-,,

19
. ,veryday life. In Section 1 1
Uers in e . th . 1t
Ce of microcontro f .....,1
crocontrollers in e em~dl>,l
d mportan
I h use o "' f I -~
. d. sion ofthe rolean IL as \-vellas t e d 8031 andthe1r eatures. naddition
This chapter begins with a .iscu~ choosing a microcontro. er, uch as the 8052 an ' '
als~ discuss criteria to consid:us members of the 8051 f ~~;C51 and D55000.
n,art..et. Section 1.2 cove:s vanf the 8051 such as the 8751, A ,
ve d~ uss various versions o
' ) EDDED PROCESSORS .
. MICROCONTROLLERS AND EMB with g_eneral-pupose rrucroerocessors
SECTION 1.1. . tr Uers and contrast them . ontrollers in the embedded ~
In this section \Ve iliscuss the ne~d for oucroconW~ also look at the role of nucroc
such as the Pentium and other~ 86 n~cr?p!.oc~ssors. choose a microcontroller.
kef.To acldition, we provide some cr1ter1a on how to

1 e microprocessor
,J Microcontroller versus genera -purpos
.
What is the difference between a microprocessor an
7
B micropro!;._essor is meant the general.
d microcontroller ~ . ) M t l ~ Q/\.,J\
80386 80486 and the Penh um o r o oro as vvvAv
286 ' t . n' 0 RAM no ROM, and no I/ 0 ports on
Purpose microprocessors such as Intel's x86 fanuly
) Th
(8086, 80 ,
onrocessors con am '. =
family (68000 68010, 68020, 68030, 68040, etc.. _ ese rrucr -'~ l ose ,nicroprocessors.
the chip itself'. For this reason, they are common!~ referred to as genera ~u~ tium or the 68040 m ust add RAM, ROM.

1/ 0 ports, and timers extem~y to make them funcho_nal. Althoug


;s
A-system designer usin& a general-purpose rmc~oprocessor su~ a:di:n of ext~al RAM, ROM, and 1/ 0 ports"
e d a e of versatility such tl1at the designer
makes these systems bulkier and much more expensive, they have the a vant g d Thi . t th .th .
can decide on the amount of RAM, ROM, and I/ 0 ports needed to fit the task at han s 15 no e case WI rrucro-
controllers. A microcontroller has a CPU (a microprocessor} in addition to a fixed amo~t of.RA.M, ROM, l /0 '1orts, ~
a timer all ona smg1e chip:Tn other words, the processor, RAM, ROM, I/ 0 por~, and t~er ar~ all eml:2.edde .togei_L..
on ~ chh>; therefore, the designer cannot add any external memory, 1/ 0 , or tuner to 1t. Th_e fi~ed ~mo~t of on-chip
ROM, RAM, and number of l / 0 ports in microcontrollers makes them ideal for many applications m which cost and
space are critical. Jp mans applicatiQns, for examp!g_a JV remote control, there is no need for the computing power of
a 486 or even an 8086 microprocessor. In many applications, the space it takes, the power it consumes, and the price
per unit are much more critical consTclerations than the computing power. These applications most o ften require some
1/ 0 operations to read signals and tum on and off certain bits. For this reason some call these processors IBP, "itty-bitty
proces~ors" (see "9ood Thing_s in Sma!] Packag_es Are Generati~g Big Product OePor_tunities" by Rick Grehan, BYTE
maga~~e, Sept~mber 1994; www.byte.com, for an excellent discussion of microcontrollers).
. _It 1s interesting to note that some microcontroiler manufacturers have gone as far as integrating an AOC (analog-to-
d1gital converter) and other peripherals into the microcontroller.

V M1crocontrollers for embedded systems


ln the lit~ature discussing microprocessors, we often see the te . .
trollers are \v1dely used in embedded system products An b dd nn embedded systcn,. Microprocessors and rrucrocon-
. _em e ed product uses a n\icroprocessor .{_or microcontroller)

Data bus
CPU

General- CPU
Purpose RAM ROM
RAM ROM 1/0 Serial
Micro- Timer
processor
Port COM
Port 1/ 0 limer Serial
COM
Address bus Port
(a) General-Purpose Microprn.-~- S
~~'"""r ystem

Figure 1-1. M icroprocessor System Contruted With Mi {b) Microcontroller


crocontroUer Syste m
20
THE 80St MICR.<>c
ONTROLLER AND EMBEDDED S~
le of embedded system since
Table 1-1: Some
to do one task and on~sk only_.[!. printer i~'.111 exa~pgetting the data and printing Embedded Products
me processor inside it perf~rms only one tas , nam~ IBM-compatible PC). 1 PC can Using Microcontrollers
it)Contrast this with a Penbum-based PC (or any x rocessor print server, bank
~ used for any number of applications such as wor~ P t te~al. Software for Home
:..:;....-.-:~- la
teller terminal, video game p yer, ne Of
twork server or inteme
se the reason a PC can per- Appliances
avanety of applications can be loaded and run. cour . tin system that loads Intercom
form myria~ tasks is tha_t it has RAM memory and an Ft~: angembedded system, Telephones
the application software mto RAM and lets_the ~PU run ed into ROM. An x86 PC Security systems
there is only one application software that IS typically b ~ the keyboard, printer, Garage door opei:ers
contains or is connected to various embedded products sue as d Each one Answering machines
modem, disk controller, sound card, CD-~OM ~ver, mouse, an ~ ~~~ task. For
0
Fax machines
of these peripherals has a microcontroller ms1de it that performs 0 Y th t k f
. tr u that performs e as o Home computers ~
example inside every n1ouse there ts a microcon o er b dd d TVs _.
finding the mouse position and sending it to the PC. Table 1-1 lists some em e e
Cable TV tuner
products. ~ ft.A "tt:> ~ 4 ~\ "--
...~.J p, odJ.J.d t - ( c._
VCR
Camcorder
C>""'~ . Remote controls
'
X86 PC embedded applications Video games
Although microcontrollers are the preferred choice for many embedded sy~- Cellular phones '
tems there are times that a microcontroller is inadequate for the task. For this Musical instruments v
I

reason, in recent years many manufacturers of general-purpose microprocessors Sewing machines


such as Intel, Freescale Semiconductor Inc. (formerly Motorola), AMD (Advanced Lighting control
Micro Devices, Inc.), and Cyrix (now a division of National Semiconductor, Inc.) Paging
have targeted their microprocessor for the high end of the embedded market. Camera '
While Intel and AMD push their x86 processors for both the embedded and desk- Pinball machines
top PC markets, Freescale is determined to keep the 68000 family alive by target- Toys
ing it mainly for the high end of embedded systems now that Apple no longer Exercise equipment
uses the 680x0 in their Macintosh. In the early 1990s Apple computer began
using Power PC microprocessors (604,603, 620, etc.) in place of the 680x0 for the Office
Macintosh. The Power PC microprocessor is a joint venture between IBM and
Telephones
Freescale, and is targeted for the high end of the embedded market as well as the
Computers
PC market. It must be noted that when a company targets a general-purpose micro-
Security systems
processor for the embedded market it optimizes the processor used for embed-
Fax machine
ded systems. For this reason these processors are often called high-end embedded
processors. Very often the terms embedded processor and rnicrocontroller are used Microwave
interchangeably. Copiet/
One of the most critical needs of an embedded system is to decrease power con- Laser printer,/
sumption and space. This can be achieved by integrating more functions into the Color printer""
CPU chip. All the embedded processors based on the x86 and 680x0 have low power Paging
co'.15ump~on in addition to some forms of I/0, COM port, and ROM all on a single
Auto
chip. In high-performance embedded processors, the trend is to integrate more and
more functions ~n the C~~ chip_and let the designer decide which features he/she Trip computer
~ants to use. This trend 1s mvadmg PC system design as well. Normally, in design- Engine control./
ing the PC motherboard we need a CPU plus a chip-set containing 1/0 a ch Airbag ....,
controller, a flash ROM containing BIOS, and finally a secondary cache ' ca e ABS
N . . . . d F memory.
. ew d es1gns are emerging in m ustry. or example, Cyrix has announ d th . Instrumentation .
. th t th
IS working on a ch1p a contains e entire
PC, except for DRAM. In other
ce w atd 1t
Security system _,,,
we are about to see an entire computer on a chip. or s,
Transmission control
Currently, because ofMS-[X)S and Windows standardization m
systems are using x86 PCs. In many cases using x86 PCs for the high- an~ em~edded Entertainment
?PPlications not only saves money but also shortens development
1s a vast library of software already written for the DOS and w d
i:
e~ edded
e since there
Climate control
Cellular phone
The fact that Windows is a widely used and well understood ~ ows platforms.
1
!o
developing a Windows-based embedded product reduces the ~ or;; hmeans that
development time considerably. 5
an s ortens the
Keyless entry

-
Tl-IE 8051 MICROCONTROLLERS
21
/ , Zilog's Z8, and PIC 16~ from
051
V Choosing a microcontroller h are: Freescale's 6811, ~tels ~d'r;gister set; theref~re, they are
a
f
The~e are_1. 0
:r
M' ochip Teuu,o1ogy. .
aor a-bit rn.icrocontroJlers. T ey h s unique instrucnon set
writti>n .ct on WJ.1..1
There are also 16-bit and 32-bit
m J Each of these microco~troUefr!L-ae ... :11,Jtot run on lll.e other__s.U_
contro er6 ,
what criteria do designers
.
Jcr m atib'j; with each oth~r. P_rgg_:a.ll5 With aJl these different rrucro . Q1 meeting the computing neects
:~~~:o~trollers made by~ous .~hip 7:t1:sing microcontrollers are as foll~;:~lopment tools such as compilers,
1
consid~in choosing o~~? e: ~ c:~: effectively, _w avajlability of softwa~ethe mi_crocontroller. Next we elaborate
0
of the task at hand efficiently d (~\ wide avaHability and reliable sources o
assemblers, and debuggers, a1: .*'-
further on each of the above criteria.

/ criteria for choosing a microcontroller . . t eet the task at ~nd efficiently and
ontroller is that it mus m h 8 b't 16--b't
1. The first and foremost criteriohn in chdoosfmg ~:c;~~~oller-based project, we must first see whet e r than - ;;side I ,
cost effecti.veb'-In analyzing t e nee so a nu . needs of the task most effectively. Among o e r c ra-
or 32-bit microcontrolJer can best handle the computmg , P. 7. r
tions in this category are:
. h hi h t ed that the microcontroller supports.
, t, P
(a) Speed.. What 1st ~ g es. spe . . . "'"'"v"aP) or a QFP (quad Q_at packag~, or some other
(b) fackag_i!lg. Does 1t come in a 40-pm_J?IP (du~ mlm_e_~bling ana prototyping the end product.
packaging format? T_his is important m term~ o space:, assem ,
(c) .Power consumption. This is especially critical for battery-powered products.
(d) The amount of RAM and ROM on chip.
(e) The number of 1/0 pins and the timer on the chip. . .
(f) How easy it is to upgrade to higher-performance or lower power-consumption vers1ons. .
,- (g) Cost per urut. This is important in terms of the final cost of ~e product in which a microc~ntroller_ IB used. For
example, there are microcontrollers that cost 50 cents per urut when purchased 100,000 uruts at a time.
2. The second criterion in c.h_oosing a microcontroller is how easy it is to develop products around it. Key consid~a-
tions include the ~ailability of an assembler, de__!?ugger, a code-efficient C language compileF, emulator, techru~
support, and both in-house and outside expertise. In many cases, tl:urd-party vendor (that is, a supplier other than
the chip manufacturer) support for the chip is as good as, if not better than, support from the crup manufacturer.
3. The third criterion in choosing a microcontroller is its ready availability in needed quantities both now and in the
future. For some designers this is even more important than the first two criteria. Currently, of the leading 8-bit
~crocontrollers, the 80~1 family h.a~ the largest number of diversified (multiple source) suppliers. By supp~r
IS meant a producer besides the ongmator of the microcontroller. In the case of the 8051, which was originaled
by Intel, several companies also currently
produce (or have produced in the past) the
80~1: The~eco1:1panies include: Intel, Atmel, Table 1-2: Some of the Companies Producing a
P~lips/S1gnet1cs, AMO, Infineon (formerly Member of the 8051 Family
Siemens), Matra, and Danas Semiconductor.
See Table 1-2. Company Web Site
Intel
It should be noted that Freescale, Zilog 1 www.intel.com/ design/ mcs51
and Microchip Technology have all dedicated Atmel
www.atmel.com
ma~siv~. resource~ to ensure wide and timely Philips /Signetics
availab1lity of their product since their product www.serniconductors.philips.com
Infineon
is stable, mature, and single sourced. In recent www.infineon.com
years they also have begun to sell the ASIC Dallas Semi/Maxim
www.maxim-ic.com
-
library celJ of the microcontrolJer.
~,~t"'
Review Questions
V
1. True or false. Microcontro!Jers are normally less ex ensiv .
2. When comparing a system board based on a microcp tr ell than microprocessors.
? on o erandagen l
chea per. ,,, era -purpose microprocessor, which one iS

22
THE 8051 MICROC
ONTROLLER AND EMBEDDED s\'ffllMS
. h O f th f llowing devices on-chip?
. A microcontroller normally has "vhlc ( )~/~ v(d) all of the above
3 (a) RAM (b) ROM c hi h f the following devices to be attached to it?
4. A general-purpose microprocessor normally needs w c o ""(d) 11 of the above
(a) RAM (b) ROM (c) I/0 a
s. An embedded system is also <;.a~d a dedicat~ systetn- Why?
6. What does the term etnbedded system mean? ?
7. Why does having multiple sources of a given product matter

SECTION 1.2: OVERVIEW OF THE 8051 FAMILV


f ontrollers and their internal features.
1 f il
In this section we first look at the various members of the 805 am Yo nucroc
Plus we see who are the different manufacturers of the 8051 and what kind of products they offer.

A brief history of the 8051


In 1981, Intel Corporation introduced an 8-bit microcontroller called the 8051. This microcontroller had 128 bytes
of RAM, 4K bytes of on-chip ROM, two timers, one serial port, and four ports (each 8-bits wide) all on a single chip.
At the time it was also referred to as a "system on a chip." The 8051 is an 8-bit processor, 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 8-bit pieces to be processed by the
CPU. The 8051 has a total of four I/0 ports, each 8 bits wide. See Figure 1-2. Although the 8051 can have a maximum
of 64K bytes of on-chip ROM, many manufacturers have put only 4K bytes on the chip. This will be discussed in more
detail later.
The 8051 became widely popular after Intel allowed other manufacturers to make and market any flavors of the
8051 they ~leas~ with the condition that they remain code-compatible with the 8051. This has led to many versions of
the 805~ 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 note that although there are different flavors of the 8051 in terms of speed
gos-'
--,./ I ~
S c:i0tS5 '

s g
ON-CHIP t,,/
~'f
ROM
"(7

INTERRUPT -- for
program ON-CHIP
ETC.
CONTROL TlMERO
- code RAM
TIMER1 ,c

I,. :::.. L"'~


"' -
rJ.; I/
CPU
I\
~ '<- ./.,. ~/ '<:'.._ 7

osc BUS 41/0

" -
CONTROL PORTS
SERIAL
PORT

"' -+
~

...+ tttt
PO
TXD RXD
w .( . -t
Figure 1-2. Inside the 8051 Mlcrocontroller Block Diagram
' ~
-THE IOSl MICllOCONTROLLEllS

23
ble 1-3: Features of the 8051
. iJ1al soSl
.th the orig ol.11' -
ra Quantify
all compatible w1 if you write y feature 4K bytes'
d O
unt of on-chip ROM, they ared This means thatth manufacturer jzoM
an am . e concerne di s of e 128 bytes
as far as the instructions ar of them regar es
~~-----2;--::...:.::--
program for one, 1t
. will run on any
Tl~iIJl~e~r----~~~~~~;-----
t as _:: 32
8051 mlcrocontroller
. . b f the 8051 fauwY
The 8051 is the original me~ ~:a':ures of the 8051.
~-:1 Intel refers to i
0
-
I/0 pin.S
t-- ~ r i al port
1 --
MCS-51. Table 1-3 shows the mrun - terrupt sources 6. -
~ M !Jlount indicates on-chip program
Note: RO a
Other members of the 8051 family . of microcontrollers. space.
There are two other members in the 8051 family
They are the 8052 and the 8031.

8052 microcontroller d d features of the 8051 as well as an extra


. b f th 8051 familv. The 8052 has all the stan arf RAM and 3 timers. It also has BK bytes
The 8052 IS another mem er o e ~ d the 8052 has 256 bytes o
128-bytes of RAM and an extra timer. In other wor s, .
of on-chip program ROM instead of 4K byt~s. See Table 1-4. 8052 therefore, all programs written for the 8051 will run
As can be seen from Table 1-4, the 8051 is a subset of the '
on the 8052, but the reverse is not true.

8031 microcontroller
Another member of the 8051 family is the 8031 chip. 'l]\is chip is often referred to as a ROM-less 8051_ since it has OK
bytes of on-chip ROM. To use this-chip you musTadd external ROM to it. This external ROM must con tam the program
that the 8031 will fetch and execute. Contrast that to the 8051 in which the on-chip ROM contains the program to be
fetched and executed but is limHed to only 4K bytes of code. The ROM containing the program 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 ports
(o~ the 4 ports) for I/0 operations. To solve this problem, you can add external I/0 to the 8031. Interfaciru! the 8031
with memory and l/0 ports such as the 8255 chip is discussed in Chapter 14 There a l d- -v f
the 8031 available from different companies. re a so vanous spee versions o

Various 8051 microcontrollers


. ~though the 8051 is the most popular member of the f . .
8051
This IS because the 8051 is available in different memo typ amily, you will not see "80Sl,, in th art umber
have different part numbers. A discussion of th . ry es, such as W-EPROM fl.a h e p n .
version of the 8051 is the 875l The flash ROM e vai:ious types of ROM will be . ' . s I and NV-RAM, all of which
Dallas Semiconductor. The A~el Flash 8051 . ve~1on is marketed by many c given~ C~apter 14. The UV-EPROM
(DS89C420/430/440). The NV-RAM version of!Sthc ed AT89C51, while Dallas omp~es including Atmel Corp. and
an OTP (on~time programmable) version of the 8~:f51 made by Dallas Semico:nuco~ductor calls theirs DS89C4x0
the above chips and describe applications where th made by various man:ut ductor lS called DSsooO There is also
ey are used acturers Ne t .
x we discuss briefly each of
Table 1-4: Comparison of 8051 F .
Feature atnily Members
ROM (on-chip program space in b 8051
8052
8031
81(
01(

128
'l') Serial port 3
Interrupt sources 2
1
32
32
6 l
24 l
8
6
,,
8751 mlcrocontroller
This 8751 chlp has only 4K bytes of on-chip UV-EPROMi

u::r
this chi for development reqwres
. access to a
UV-EPR~M inside the 8751 chip before you can
PROM burner, as well as a UV-EPROM eraser to erase ~e. c~PROM it takes around 20 minutes to erase the 8751
program it again. Because the on-chip ROM for the 87:,l IS - t '. tr d ce flash and NV-RAM versions of the

8051, as we will discuss next. There are also various speed versions o e
d:
before it can be programmed again. This has le~ many manufa~er; ~ ~ :vailable from different companies.
7
OS89C4x0 from Dallas Semiconductor (Maxim) Th AT89C51 from Atmel Corp. is one
Many popular 8051 chips have on-chlp ROM in the fonn of flash me~ory. e b a ed in seconds
example of an 8051 with flash ROM. This is ideal for fast developm_ent since flash memo~ caned ~r l:ce of the 8751
9 5
compared to the twenty minutes or more needed for the 8751. For this reason the AT8 C l is ~s U ? h AT89 51 c
to eliminate the waiting time needed to erase the chip and thereby speed up the development time. sing t . e
to develop a microcontroller-based system requires a ROM burner that supports flash ~emory; however, a_ RO~ eras~r
is not needed. Notice that in flash memory you must erase the entire contents of R~M JJ'\ order to progr_a~ it agam. This
erasing of flash is done by the PROM burner itself, which is why a separate eraser 1s not needed. To elurunate the need
for a PROM burner, Dallas Semiconductor, now part of the Maxim Corp., has a version of the 8051/52 called D589C4x0
(DS89C420/ 430/ .. .) that can be programmed via the serial COM port of an IBM PC.
Notice that the on-chip ROM for the DS89C4x0 is in the form of flash. The DS89C4x0 (420/430/440/450) comes
with an on-chlp loader, which allows the program to be loaded into the on-chip flash ROM while it is in the system.
This can be done via the serial COM port of an IBM PC. This in-system program loading of the D589C4x0 via a PC
serial COM port makes it an ideal home development system. Dallas Semiconductor also has an NV-RAM version of
the 8051 called DS5000. The advantage of NV-RAM is the ability to change the ROM contents one byte at a time. The
DSSOOO also comes with a loader, allowing it to be programmed via the PC's COM port. See Table 1-5. From Table 1-5,
notice that the DS89C4x0 is a really an 8052 chlp since it has 256 bytes of RAM and 3 timers. M ore details of this chip
are given throughout the book.

DS89C4x0 Trainer
. In C:1~pter 8, we dis~uss ~e design of DS89C4x0 Trainer extensively. The MDE8051 Trainer is available from www.
~croDigitalEd.com. This Trainer allows you to program the DS89C4x0 chip from the COM port of the x86 IBM PC
with no need for a ROM burner. '

For a D5B9C4x0-based trainer see www.MlcroDlgltalEd.com.

AT89C51 from Atmel Corporation


The Atmel Corp. has a wide selection of 8051 chips as shown T
a popular and inexpensive chlp used in many small pr~ects Ith ~ ables 1-6 and 1-7. For example, the AT89C51 is
where "C" before the 51 stands for CMOS which has a low as byt~s of flash ROM. Notice the AT89C51-12PC
pac ge, "C" .
1s for commercial. ' power consumption , . dicates 12 MHz, "P" is for plastic'
"12" in
DIP ka

Table 1-5: Versions of 8051/52 Microcontroller From Dall .


Part Number ROM as Semiconductor (Maxim)
- RAM UO Timers Interrupts
DS89C420/30 16K (Flash) 256 pins
32 3
DS89C440 321< (Flash) 256
6 sv
32 3 6 5V
\tbS89C450 64K (Flash) 256 32 3
DSsooo 6 5V
- 8K(NVRAM) 128 32 2 6 sv
-DS8oo20 oK 256 32
DS87520 16K (UVROM) 256 3 6 sv
Sourct. www .maxim-,ccom/products/microcontrollers/8051 32 3
.
_d rop_m.cfrn
. 6 sv
-
TliE 80S1 MICROCONTROLLERS
25
OM flash) V Pac
JnterruPt
. 051 From Atmel (All R Timer SV
Table 1-6: Versions of 8 I/0 pins 6 40
Part Number ROM RAM 2 3V 40
32 6
4K 128 2 3V
AT89CS1 20
128 32 3
AT89LV51 4K 1 3V
15 6 20
AT89C1051 1K 64 2
15 SV 40
AT89C2051 2K 128 8
3 3V 40-
BK 128 32 8
AT89C52 3
AT89LV52 BK 128 32 '
Nolt: "C" in the part number indicates CMOS.

Table 1-7: Various Speeds of SO51 Fr om Atmel . Use


Part Number Speed Pins Packaging
DIP plastic commercial
AT89C51-12PC 12MHz 40
40 DIP plastic commercial
AT89C51-16PC 16MHz
AT89C51-20PC 20MHz 40 DIP plastic commercial

OTP version of the 8051

There are also OTP (one-time-programmable) versions of the 8051 available from different sources. Flash and NV-
RAM versions are typically used for product development. When a product is designed and absolutely finalized, 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 ofthe 8051 family is Philips Corporatio Ind d
8051 m.icrocontrollers. Many of their products include featur ch n. ee , they have one of the largest selections ol
1/0, and both OTP and flash. For the list of companies prod:~;u thas A-to-D ~onverters, D-to-A converters, extended
g e 8051 family see the Web sites in the box below.

See the following Web sites f 8


their features from va I or 051 products and
r ous companies.
www.aos2.com/chipa.phtm1
WWW.MicroDlgitalEd
.com

Review Questions
v 1.- Nam.e three features of the 8051.
2. What is the major difference between th
3. Give the size of RAM in each of the f e 8_o51 anct 8052 rn ~

5. The 8051 is a(n) (/-, -bit microp


11
4. Give the size of the on-chip ROM in :ac~wing: (a) 805] {b) ~~f
0 ntroUers?
of the following 2 (c) 8031
6. State a major difference between ther;~~s; (a) 8051 {b) 80si ( )
7. True or false. The DS89C420/JO is r " ' e AT89c:5 c 8031
1
ea y an 8052 chi , anct the Qssar,
u p. J'-420/30.
Uminating the need for ROM burner.
dded to the chip, therefore e
mb
30 has a loader e e
8 True or false. Th e DS89C42o/ chi ROM.
9: The DS89C420/30 chip has bytes o on- p
10. The DS89C420/30 chjp has bytes of RAM.

SUMMARY . d !if Microprocessors and rrucro-


. f
ntrollers m every ay e. k W als
This chapter discussed the role and importance o rrucroco f . ocontrollers in the embedded mar et. e . o
controllers were contrasted and compared. We discussed the us:
o rrue:d memory I/0, packaging, and cost per wu.t.
discussed criteria to consider in choosing a microcontroller s ue ~ sp f the 8051 s~ch as the 8052 and 8031, and their
The second section of this chapter described various family mem echrs o th AT89C51 and DS89C4x0, which are mar-
. f the 8051 su as e
features. In addition, we discussed various versions o
keted by suppliers other than Intel.

Vj>ROBLEMS ~
~ SECTION 1.1: MICROCONTROLLERS AND EMBEDDED PROCESSORS ..._
1. True or False. 8-bit microcontrollers are the most widely used microcontroller~ th:w~d o ~ ~ J vv,. ts\ 0 t f\ \o..)
2. True or False. The 8051 is manufactured by more than o~ manufacturer. l f>-. ~ 1
J
3. True or False. A microcontroller has on-chip 1/0 ports. I
4. Trtie or False. A microcontroUer has a fixed amount of RAM on the chi.P . . ? e..c,rr, Q ,._ -M. -\ 'fV' ' l ,. c_~u._., ,, C)
If 5. What components are normally put together with the microcontroller into a single.chip. ,
6. Intel's Pentium chips used in Windows PCs need external f..A ('("I and ,f_ c; 1't') chips to s tore data and cod e.
\,)/. List three embedded products attached to a PC. ,.,.., <> u. se I IJ. e..t;t Le-<'\. rel 1 {'c r. "'"' ~ "' ' )

Jo. Why would someone want to use an x86 as an embedded processor?


9. Name two 16-bit microcon trollers. .S LC.. I ~ 1 b <?- ' 2., 1-o
1
~
( , , (-A ) -{ t cc;,,.. CftG.. c... ( M ~ <:f"'~O...

10. True or False. The 8051 has on-chip ADC. 7- c ,.. (" "' "('.. r ~
11. Which operating mode of a microcontroller is useful in battery-based embedd ed products?POL-" <IY\ (?... ~
12. 1n an embedded controller w ith on-chip ROM, why does the size of the ROM ma tter?? .o-'- 1:,.... , .. -.
6
13. 1n choosing a microcontroUer, how important is it to have multiple sources for that chip ?
14. What does the term "third-party s uppo rt" mean?
15. lf a microcontroller architecture h as both 8-bit and 16-bit versions, w hlch of the following s ta tements is true?
(a) The 8-bit software will run on the 16-bit system. 1
(b) The 16-bit software will run on the 8-bit system .

SECTION 1.2: OVERVIEW OF THE 8051 FAMILY \


L -:::,~ 1t..\1Y\I<" '"''-
16. The 8751 has !li3). bytes of on-chip ROM.
17. The 89C51ED2 has :2- l& bytes of on-chip ROM.
18. Which timer of the 80ql can be used as a counter as well? .:t:.,\'V'\~ , o,. "\ 'y,.,.""'~ < ,
19. The 8052 has z
S: b bytes of on-chip RAM.
20. The ROM-less version of the 8051 uses t,o 5I as the part number.
21. The 8051 family has ~').... pins for 1/ 0 .
22. How many pa rallel and serial port lines the 8051 has? ~ Sc,A..je.R. H'"'d YlO
23. The 8751 on-chip RO M is of typ e f>.u..
S":i
24. The AT89C51 on-chip ROM is of type ot P.
25. The DSSOOO on-chip ROM is of type f...f.A f.t /"J" l /.I n"\
26. The DS89C420/30 on-chip ROM is of type fl ~~ ~ .,,. (_
27. Give the amo unt of ROM and RAM for the following chips {) I p
(a) AT89C51 ~'-~~ (b? DS89C420/ 30'!?, "'t (c) DS89C440 . JJ. "-
28. Of the 8051 family, which memory type is the most cost eff ~) 6. ~
product? ( c-r P) .Jc t'f, o" ective if you are using a m illion o f the m in an embedded
29. Which vers io~ of the 8051 does not have on-chip ROM? ~O!. I
30. Of the 8051 m1crocontrollers, which one is the best for h
to a ROM burner.) a ome d evelo pment e nv ironment? (Yo u d o not have access

-
THE 8051 MlCJlOCONTROLLBRS '
27
ANSWERS TO REVIEW QUESTIONS ED pROCESS0R5
ANDEMBEDD
SECTION 1.1: MlCROCONTROLLERS
1. True
2. A m.icrocontroller-based system
3. (d)
4. (d) . type of job. . d into a single system.
5. It is dedicated since it is dedicated to d?m~ one d processor are comblCle plier. More importantly, competili...
6. Embedded system means that the application an ot hostage to one sup oq
7. Having multiple sources for a given part means you ~e nt
among suppliers brings about lower cost for that pro uc

SECTION 1.2: OVERVIEW OF THE 8051 FAMILY


l. 128 bytes of RAM, 4K bytes of on-chip ROM, four 8-bit I(O ports. th on-chip ROM is 8K bytes instead of 4J( 1..-......
2. The 8052 has everything that the 8051 has, plus an extra tuner, and e "11Q
The RAM in the 8052 is 256 bytes instead of 128 bytes.
3. Both the 8051 and the 8031 have 128 bytes of RAM and the 8052 has 256 bytes.
4. (a) 4.K bytes (b) 8K bytes (c) OK bytes
5. 8
6. The main difference is the type of on-chip ROM. In the 8751 it is UV-EPROM; in the AT89C51 it is flash; and in~
DS89C420/30 it is flash with a loader on the chip.
7. True
8. True
9. 16K
10. 256

28
CHAPTER2

8051 ASSEMBLY
LANGUAGE PROGRAMMING

OBJECTIVES

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

List the registers of the 8051 microcontroller


Manip~ate data using the registers and MOV instructions
Code sunple 8051 Assembly language instructions
Assemble and run an 8051 program
Describe the sequence of events that occur u on 805
Exam~e programs in ROM code of the 8051 p 1 power-up
Explain the ROM memory map of the 8051
Detail the execution of 8051 Assembly langu . .
Describe 8051 data types age instructions
E~plain the purpose of the PSW (program status wor .
~scuss RAM memory space allocation in the 8051 d) register
Dia~am the use of the stack in the 805l
Marupulate the register ban.ks of the 8051

1,

Ir

.
--
.'
-

29
d gisters of tl1e 8051 with
f the widely use r; and rnachine language
trate soJ'lle O A ernblY laflgufag se""'bling and creating a
051 We delllons ine ss s o as ".
111 Section 2.1 we look at the inside of the 8 . 5eetion 2.2 we eXatfl etc. 'fhe proces 8051 program and the ro~e of
simple iJ1Structions such as MOY and ADD. In . opcode, operand, execution of an d A5sernbly language direc-
programming and define terms su.ch ~s rnne;.0 ~~tion 2.3. Step-by-~e~ sorne widely us~ and hoW tlley are affected
ready-to-run program for the 8051 ts d1scu.sse in In 5eetion 2.5 we Loo a . cuss the f)ag bits . ban.ks of tile 8051 are
the program counter are examined in Section 24 In 5eetion 2.6 v,e dis 5 tack and register
rives, pseudocode, and data types.related to the 80Sl. inside the 8051 plus the
by arithmetic iJ1Structions. Allocation of RAM memory
discussed in Section 2.7.

SECTION 2.1 : INSIDE THE 8051 . with the siJllple instructions MOY
. d show thelI use
6
~~ ~
Ln this section we examine the major registers of the 805l an
andADD. ;;

Registers
Th inf tion could be a byte of data to be
1n the CPU, registers are used to store information temporarily. at orma . . .
Y processed, or an address pointing to the data to be fetched. The vast !;_'ajority of 8051 registers ar 8-b1t regist~rs. -~ the
8051 there is only one data type: 8 bits. The 8 bits of a register areshown in the diagram from the Mfil3 (most :1gnif1cant
~) 07 to the LSB (least significant bit) DO. With an 8-bit data type, any data larger than 8 bits must be broken into 8-bit
~unks before it is processed. Since there are a large number of registers in the 8051, we will concentrate on some of the
widely used g~neral-purpose registers and cover special registers in future chapters. See Appendix A.2 for a complete
list of 8051 reg1Sters. gJ, ,# f,, ~

GGGGGGGG
. The most widely used registers of the 8051 are A (accumula
pointerlla,and PC .<program counter). All of the above re<>isters ar to8-rb),_ B, RO, Rl, R2, R3, R4, RS, R6, R7, 12.PTR (data
accumu tor, register A, is used for all arithm . o. . e its, except DPTR and the
will show them in the context of twostmp Ie instructions,
. ellc ~d logic
MOY and ADD.To understand th e useprfogram
instructions. counter. The
O these registers, we

MOV instruction
Simply stated, the MOV i . i
A ~ I has the following format
MOV dest .
nstruction copies data from one 1 ti'
oca on to another. It
)( \~I B I 1nat1on , 60 urce c
This tru
destinati ms ction tells the CPU t
' opy sour
ce to dest.
,., rl ==R0=~11 on operand F
of register ROto re i o move (' .
or example, the . m reality, copy) th
I Rl I same value as regi~t!!e;~- After this ins~~~tio~ " Mov A, : 0~?urc~ op erand to the

I j~
The following program f. The MOY inst ~on ts executed . copies the contents
R2 moves this value ust loads re . ruction does , register A will h th
instructi Th' around to v . gtster A wth not affect th ave e
I R3i0- I soon. on~ IS
signifies that registers ~ i;alue SSH (that ~ siu~ce operand.
~~1fus
5 a value. The. e the CPU N ~ 5 m hex), then
I R4 q,v> I
t rf, 1
unportan . Otice the ,, #" . th
ce of th' . m e
I R5 .,;,I 'I fJ lS W 1ll be discussed

~PTR [
_
-;;-
,r
DPH J g '7
-..:.:_-JL-
I R7 ~'<> j PC
-

Figure 2-1 (a). Some 8-bit


Registers of the 8051
-
30
d.d r uee..
/ .:>I so
_,,-, value SSH into reg. A
MOV A,#SSH ;load contents of A into RO
MOV RO,A ;copy )
; {now A=RO=SSH
MOV Rl,A ;copy contents o f A into Rl
. (now A=RO=Rl=SSH)
MOV R2,A ;copy contents of A into R2
;now A=RO=Rl=R2=5SH)
MOV R3,#95H ,load value 95H into R3
; (now R3=9SH)
MOV A,R3 ;copy contents o f R3 into A
now A=R3=95H)
' . oints should be noted:
When programming the 8051 microcontroller, the following P . .
. . th t t is an unmed1a te
. or RO - R7. However, to indicate a l
Valu es can be loaded directly into any of registers A, B, t
. (#)Thi'
1. value it must be preceded with a pound sign sis shwnnex.
0

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


MOV R0,#12H ;load 12H into RO {RO=l2H)
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)
MOV R7,#9DH ;load 9DH into R7 (R7=9DH)
MOV RS,#OF9H ;load F9H into RS (RS=F9H)
MOV R6,#12 ;load 12 decimal (OCH)
;into reg. R6 (R6=0CH)
Notice in instruction "MOV RS, #OF9H" that a Ois used between the# and F to indicate that Fis a hex number and
not a letter. In other words "MOV RS, #F9H" will cause an error.
2. If values oto fare moved into an 8-bit register, the rest of the bits are assumed to be all zeros. For example, in "MOV
A, #5" the result will be A= 05; that is, A= 00000101 in binary.

3. Moving a value that is too large into a register will cause an error.
- -
MOV A,#7F2H ;ILLEGAL: 7F2H > 8 bits {FFH)
MOV R2,#456 ;ILLEGAL: 456 > 255 decimal {FFH)

4. A value to be loaded into a register must be preceded with a pound sign (#). Otherwise it means to load from a
memory location. For example ''MOVA, l 7H" means to move into A the value held in memory location 17H, which
coiila have any value. In order to load the value 17H into the accumulator we must write "MOV A, #1 7H" with the
# preceding the number. Notice that the absence of the pound sign will not cause an error by the assembler since it
is a alid instruction. However, the result would not be what the programmer intended. This is a common error for
beginning programmers in the 8051.

ADD instruction
{ ov.n: ~ ...,~ b~ ~ dJ ~4.
The ADD instruction has the following format:
,,..,J .! -I-arc_ of. ..f-t> ('A > ~
ADD A,source ;ADD the source operand
;to the accumulator

The ADD instruction telJs the CPU to add the source byte to register A and ut th . .
numbers such as 25H and 34H each can be moved to a recnst d h P e resu1t in register A. To add two
, o er an t en added together:
HOV A,#25H ;load 25H into A

l MOV R2, #34H


ADD A, R2
; load 34H into R2
; add R2 to accumulator
; (A A + R2)
r~ , ;..,, ~~ 't
{
~ It\ p_.) ~ u.~,~
' '

8051 ASSEMBLY LANGUAGB PROGRAMMING


31
. e that the content of R2
~,u Nobe
. d R2 == .;'tl gisters used. Another way
34fl == 591-{) an ding on the re
ults in A :: 59H (25B + ways, depeJl
Executing the program above res ..,,.;tten in Jllal\Y
bove can be ....
does not change. The program a
might be: (RS:2SH)
;load 25H into RS :34Hl
MOV RS,#2SH
;load 34H into R7 (R71ear A)
MOV R7, #34H load o into A {A=o,c
MOV A,#0 '.add to A content of RS
ADD A,RS
where A= A+ RS
' f R7
ADD A,R7 ;add to A content O ram One q uestion
;where A = A + R7 write the same prog . .
. are always manY way~ ~o to move both data items into
The program abo~e results m ': "' 59H. There bove is whether it 1s necess31Oll0 wing variation of the same
that might come to mlI\d after looking at the pro~am a.tis ~ot necessary. Look at the
1
registers before adding them together. The answer 1s no,
program:
MOV A,#25H ;load one operand into A {A=25H)
ADD A,#34H ;add the second operand 34H to A .
th d alue followed the instruction as an o p er-
ln the above case, while one register contained one val ue, e secon v . di te that the so rce
and. This is called an immediate operand. The examples shown so far for the ADD instructlo~ in ca u
operand can be either a register or immediate data, but the destination mus~ always be register A, the acc~ulator.
In other words, an instruction such as "ADD R2, #12H" is invalid since register A (accumulator) must be involved
in any arithmetic operation. Notice that "ADD R4, A" is also invalid for the reason that A must be the destination
of any arithmetic operation. To put it simply: In the 8051, register A must be involved and be the destination for all
arithmetic operations. The foregoing discussion explains why register A is referred to as the accumulator. The format
for Assembly language II\Structions, descriptions of their use, and a listing of legal operand types are provid ed in
AppendlX A.l.
There are two 16-bit registers in the 8051: PC (program counter) and DPTR
use of the program counter are covered in Section 2.3. The DPTR . . .(data p~mter). The imp o rtance and
Chapter 5 \vhere addressing modes are covered. register IS used Lil accessing data and is d iscussed in

Review Questions
1. Write the instructions to move value 34H. t .
2.
3.
4.
True ~r false. No value can be moved direct! an
What IS the largest hex value that c b y mt~ registers RO - R7.
r
Write the instructions to add the values 16~ o r~g~;r A and value 3FH into re st
~- Place the result in rel>'i
oS er
R2er 8, then add them together.
.
value? an e moved into an 8-bt .
5 Th . t regISter? What .
e vast majority of registers in 8051 are IS the decimal
bits. eqw. valent of the h ex

SECTION 2.2: INTRODUCTION TO 8


. 051 ASSEM
In this section we discuss Assembl BLY PROG
Assembly language progr~=='-
Whit the - =u.ug.
y language format a d
n defin
RAMMING
e CPU can work only in binar . e some Wide(
ous ~d slow to deal with Os and ls . Y, it can do so at Y USed ter
n111ch1ne ~anguage. In the early days of~horder to program thea very high speed F llUnology associated with
hexadeC1mal system was used as am e co.~puter, pro computer. A . or hUJna.ns
code was still cumbersome for ore efficient wa t &ranuners CO<led program th , how ever i . . . .
for the machine code instructi humans. EventuallyyAo represent bin programs in at consists of O , t ts q wte ted1-

relatively easy to remember.::mpb~ter science and : a~


mnemonic is frequently used . ons, plus other featur;s ssemb)y langu ary nllrnbers t machine lan s and l s is called
made Prograges Were d~v~e Precess of guag~. Althou gh the
an assembler. Assembly language ~~efy language pro &Ineerlng liter~ing faste e oped that w o~k.ing in machine
of!e CPU. To program in Assembly 1:ged to as a ~ =11'1\ust be tr~le to refer t~ and less pri;ov1ded mne m onics
ea , as well as other details. uage, the progr anguage b atect int0 COd.es and e to erro r. The tenn
atnrne ecause ll\acl.:_ abbre
r ll'lust kn It deals clire" llle COd b Vta tio ns that are
32 ow all the re . ctly Withethy _a Program called
Sisters of th e internal structure
ecru and the size of
l such as BASIC Pascal, C, C++, Java, and numerous
Today, one can use many different progranurung anguages, 'does not have to be concerned with
others. These languages are called high-level languages because the rrogra~er bl language program into machine
the internal details of the CPU. Whereas an assembler is use~ to trans at~ anl ss1e:n y s are translated into machine
code (sometimes also called object code or opcode for operation code), ~gh- eve an~age C com iler to translate the
code by a program called a con1piler. For instance, to write a program in C, one mus ;se a 805iassembler to create
program into machine language. Now we look at 8051 Assembly language format an use an
a ready-to-run program.

Structure of Assembly language


An Assembly language program consists of, among other things, a series of lines of Assembly language instruc-
tions. An Assembly language instruction consists of a mnemonic, optionally followed by one or two ~per~nds. The
operands are the data items being manipulated, and the mnemonics are the commands to the CPU, telling it what to
do with those items.
A given Assembly language program (see Program 2-1) is a series of statements, or lines, which are either
Assembly language instructions such as ADD and MOV, or statements called directives. While instructions tell the
CPU what to do, directives (also called pseudo-instructions) give directions to the assembler. For example, in the
above program while the MOY and ADD instructions are commands to the CPU, ORG and END are directives to the
assembler. ORG tells the assembler to place the opcode at memory location O while END indicates to the assembler
the end of the source code. In other words, one is for the start of the program and the other one for the end of the
program.
_ ... ~ / ;u..., fi~ .

V
An Assembly language instruction consists of four fields:
09~~ e.
"'- ~"'--,~ ~ ~
V\I\V\U. ~ ~ "''\ c..
[label:) mnemonic [operands] [;comment)

Brafckets indicate that a fiel~ is optional, and not all lines have them. Brackets should not be typed in. Regarding the
abo ve ormat, the following points should be noted.

l. The label field allows the program to refer to a line of code by name. The label field ca t d .
of characters. Check your assembler for the rule. nno excee a certain number
~OU>~
2. The Assembly language mnemonic (~truction~ and operand( ) fi ld
gram and accomplish the tasks for ~vfuch the program w . .: eln s together perform the real work of the pro-
as wn en. Assembly language statements such as
ADD A BI C -+ ,., . I h( M...,...;_,, (., v- d")' o,{ )
MOV A,#67 r vO'>

ORG OH ;start (origin) at location 0


MOV RS,#2SH ;load 2SH into RS
MOV R7,#34H ;load 34H into R7
MOV A,#0 ;load O into A
ADD A,RS ;add contents of RS to A
;now A= A+ RS
ADD A,R7 ;add contents of R? to A
;now A= A+ R7
ADD A,#12H ;add to A value 12 H
;now A= A+ 12H
HERE:SJMP HERE ;stay in this loop
ENO ;end of asm source file

Prog,am 2-1: Sample of an A111mbly Langu1g1 Program

-
8051 ASSEMBLY LANGUAGE PROGRAMMING
# ,, are the operands. Instead of a
,,
. and" A, B'' and .A, 67ctions or directives. Remember
ch od ce opcodes, do-i.flStru , bl
ADD ,nd MDV"' the mn,moni<', whi P' u t . as1'bl,t ps,u Onl bY th ass,,rn er, as opposed lo
mnemonieand ,n ope,and, these two field,; .,,uld 'f ""de) .,,d are used Y fl, program Z-1 the commands
that dire<ti"' do not gene<ate .ny '"''""'' ,ode 0 ~ ) for the CJ'U to e,ecu~ d END). Check your assem-
0
'"'""'"""' that are t,'"''a ted into ,n,chln ':""e (P' ' 1 ,sembl'" use .OR . an
ORG (origbtl and END are ,,..,nple, of d""'" (s0nt 805 a ed in detail in 5e,non Z,5.
bier for the rules. More of these pseudo-instructions are. discuss
. ,, " cointnents rna y be at the end of a line or on a
3. Thee'"'""'' field begins with a ,emicolon "''""'"'' ,nd"ato< ' :111d. nsable 1o programmers. Although com-
tine by themselves. The assembler ignores comments, but they ar~ th!Spe ogracn and rnake it easier for someone
ments are optional it is recommended that they be used to descnbe e pr
ebe to read and ..,'d,~tand, or fo, the p,og,a,nme< to-mbe< whal they wrote, .

4
'""'" has a monitor prog,am you do not need this
~
Notire the label "HERE" mthe label field in P>g,a,n 2-1. Any label ,efenirt8 to "'.' inS.truchO~ must .be followed
by a colon symbol, "c". mthe SjMP (short juntp m,trodion), the 8051 told l<> ,tay ,n t]us loop tndefirti tely. If your
line and it should be del-1 from your program. In the next
section \~e will see how to create a ready-to-run program.

Review Questions
1. What is the purpose of pseudo-instructions?
23.. re translated by the .assembl
True or false.aAssembl . machine code, whereas
. er into are not.
4. Which of the foll . y 1anguage is a high-level language.
(a) ADD A R2 O\vmg produces opcode?
s. p . ' (b) MOVA #12
seudo-mstructions are also called
( ) ORG
c 2000H (d) SjMP HERE
6.
7. True or false.4, Assembler
In question which one directiv
is an as::;~e:o~i~v~. the CPU itself. They are simply a guide to the assembler.

SECTION 2 3 ASSE
AN 8051 PROGRAMMBLING AND RUNNING

. Now that the basic form EDITOR


to run? The steps to ~;e:;
given, the next questi . of an Assembly Ian a
How it is created, ass:b~:Jro~am has been
l;
PROGRAM
are outlined
. as follows. e an executable Assembly nguage
an made ready
program J myfile.asm

1. Fust we use an editor to type


M
' any excellent editors m a program similar ~ rrcf'J r.-=1:___-
~~cr;;ri' and/or e~~t~:~r;;essors are avail~~l:r~gram 2-1. 1
ASSEMBLER

:'w~ ~
PROGRAM
all Microsoft prog_ram (or Notepad
operating syst
widely used ediatt
mdows)
be
or IS th
m~~,,,:.='._J
b=
pro uce an ASCil fil ems. Notice th t ' which co e
- dal -- e. For a the ed' 0 mes With

:~'sr~e~:~::ons, ~~i:l~s, e f ~! ~a%'!t~able t~


~~ 1
/ myfile.obj
:,:,::,::, fo, the oon':en"::':."'~ble<
y an assembler in
;ou~,lli' e,ten,i.:. ~:"
e asm" exte .e using. Ch asm
~ r-:-::-1..l.- ~
other obj files
LlNl<ER
2. The "asm" the next step. ns1on for the eek your PROGRAM \.
is fed t source file contain. source file
. o an 8051 assembl mg the progr
er. The assembler am
I'intofiJmachine cod e. The asse c code created
ist e. The extens f mbler will onverts th . in step 1 rnyfiJe.abs
IS obj" an ob~
for the list file is ,,~;~ or the object fi le~r~~uce mstructio
Ject fil ns
3. Assemblers require a thi While the ex~ and a
one or more object fiJ rd step called link. ension
~
extension "abs" Th' es and produces a r11g. The link
monitor progra~ is abs file is used Y absolute
8051 tr ob file . takes
progra.rn
. Ject
ainers th Wtth th
34 at h ave ae
rnyfile.he)(
2
Esosl ~ Clt "' -2. s~Ptto c
OcoNl'Q. ~ate a ..____
OttEa ugl'UJI
.\Nt)
~BEoonr..
twuSYSTEMS
ORG OH ;start (origin} at 0
1 0000 load 25H into RS
2 0000 7025 MOV RS,#25H I

MOV R7,#34H load 34H into R7


3 0002 7F34 'load o into A
4 0004 7400 MOV A,#0 I
to A ;now A= A+ RS
5 0006 20 ADD A,RS ,add contents of RS now A = A+ R7
;add contents of R7 to A I

6 0007 2F ADD A,R7 12H


0008 2412 ADD A,#12H add to A value 12H now A = A +
I
7 '
OOOA 80FE HERE: SJMP HERE ;stay in this loop
8
9 oooc END I
end of asm source file

Program 2-1: List File .


,, . h nverter) which creates a file with extension
4. Next, the "abs" file is fed into a program called "OH (ob1ec! to exO~~ bl s Recent Windows-based assem-
"hex" that is ready to burn into ROM. This program comes with a 118 assem er
biers combine steps 2 through 4 into one step. e,,v.,.(' ,. YJ ~ c v !' e ~
t,vv; 5rc ~e - t
More about " asm" and " obj" files ~ """ .,,t ,.C, e.
The "asm" file is also called the source file and for this reason some assemblers require th. at thi. s fil
. e.h ave the "src"
.
extension. Check your 8051 assembler to see which extension it requires. As mentioned earlier, this file LS created with
an editor such as DOS EDIT or Windows Notepad. The 8051 assembler converts the_ a~m file'~ A~embly language
instructions into machine langu_ag_e and provides the obj (object) file. In addition to creating the obJect file, the assembler
also produces the 1st file (list file).
,._vr(e \ Ait.11,11?\ 1> fto1,!?l ob J. J' 'e .
1st file ~ fl ,_ 1 \ L ' _:_2_!__J
The 1st (list) file, which is optional, is very useful to the programmer because it Jists all the opcodes and addresses

-
as well as errors that the assembler detected. Many assemblers assume that the list file is not wanted unless you indicate
1nat you want to produce it. This file can be accessed by an editor such as DOS EDIT and displayed on the monitor or
sent to the printer to produce a hard copy. The programmer uses the list file to find syntax errors. It is only after fixing
all the errors indicated in the 1st file that the obj file is ready to be input to the linker program.

Review Questions
1. True or false. The DOS program EDIT produces an ASCU file.
2. True or false. Generally, the extension of the source file is "asm" or "src".
3. Which of the following files can be produced by the DOS EDIT program?
(a) myprog.asm (b) myprog.obj (c) myprog.exe (d) myprog.lst
4. Which of the follow~files is produced by an 8051_assernbler?-) ~rot;fu , " -i C b~ f1f , A
..,.J
(a) myp rog.asrn t>J'myprog.obj (c) myprog.hex (d) myprog.lst
5. Which of the following files lists syntax errors?
(a) myprog.asm (b) myprog.obj (c) myprog.hex {dj:myprog.lst
v
SECTION 2.4: THE PROGRAM COUNTER AND ROM SPACE IN THE 8051
In this section we examine the role of the program counter (PC) re t
discuss ROM memory space for various 8051 family members. gis er in executing an 8051 program. We also

Program counter In the 8051


An other important register in the 8051 is the PC (program count ) Th
the next instruction to be executed. As the CPU fetches the opcod % e program counter points to the address of
lllcremented to point to the next instruction. ~pro_gram counter; thorn the _progr~m R_O M, the program counter is
can access program addresses 0000 to FFFFH, a total of 64'R 6 f- e S05l i ~ 16 bits wide. This means that the 8051
t~ entire 64K bytes of on-chip ROM installed, as we will see ::,S
0
~~ae. liowever, not al11nembers of the 8051 have
We will d iscuss this important topic next. n. ere does the 8051 wake up when it is powered?
-
8051 ASSEMBLY LANGUAGE PROGRAMMING
35
/ . ered up . . t what address does the CPU
15
Where the 8051 wakes up when it 15 pow ( rnicroprocessor) 8A051 fa]llilY (that is, all members
ocontroller or e of the
an. qu"tion ""t w, must ,sk ,bout any nucr . different. fp th"" ddte5S 0000 when ti ts powered up.
w,ke up upon applying Po"" to ;t? Earh nu,rop"""';: wal<es up at memo')' a 4 In other words, when the 8051 ;,
"'""I"' of the """'' and ,.n,oon). th nucrorontro. d'SCUSS"d in Chpt: t th f[rSt opcode to be stored
By powering up we mean applying Vcc to the RESET Pl1l ~~ \ T)us rneans that it expe~~ t memory location OOOOH
0
powered up, the pC (program counter) has the value of 00 Ul ~ de must be burne in .
h. b
otROM ,ddre,s OOOOH. FOJ u,;, reason u, the S05lsystom, th n~iopco h ;t is booted. We acttleve t JS Y the ORG
of progJam ROM'"'".,,;,;, whe" ;t looks fOJ th fu>t """"'"'": ,:; -by-s"J' action of the program counter in
statement in the source program as shown earlier. Next, we discuss th P
fetching and executing a sample program.

Placing code in program ROM


To.get a bett<J und,~t.tnding of the rol, of th P'<>s'"" rountoJ in r,tdtlng and executing a program, we ex~min'
the action of the program counter as each instruction is fetched and executed. First, we exarrune once more the list file
;f "'' ""'pie prog,am and how tt,, rode a pl~OO rn the ROM of an SOS! ,hip. As we ran see, the oprode and ope,and

and~;' ::,~;:"f"' b=ed rnto ROM of an 8051 f~ily membeJ surh as 8751 o, AT8951 o, D55000, the opcode
or each mstruction are listed on the left side of the list file (Program 2-1).
e P aced Ul ROM memory locations starting at 0000 as shown in the list below.

Machine Language Assembly Language


ROM Address
0000 7025 MOV RS, #2SH
0002 7F34 MOV R7, #34H
0004 7400 MOVA, #0
0006 20 ADD A, RS
0007 2F ADD A, R7
0008 2412
OOOA
80FE ADD A, #12H

0001The I.is! shows that address 0000 . HERE: SJMP HERE \


con tams the operand (in . contains 7D, which is th
machine code of "7D25" h 1h15 case 25H) to be mo d e opcode for movin
ln me
in th mory Iocations 0002' wandere0003
7D is th veis th
d e opcode and 25 to RS. Th erefore, theginstr
a value. m
. to register R5 and dd
e "me way ma hln an "'"""" th """"'' S;mit urtion .. MOV , a '"'
the operand for tile . c e ~ode "7400" is located . e opcode and the . arly, the mach.in RS, #2 SH" has a
for the instruction ..::iction "Mov A, #o". Thtn memory locationsoOpOerand for the inst e. code "7F34" is located
A R ,, . A, Rs" and
' 7 mstruetion. The opcode for the. ~o~ e memo l 04 and 000 ruction "MO
location ;o;:tion 0006 has th 5 and represent thv R7, #34H".
lllS etion "ADD A #1 s the content 2Fe opcode of 20 his e opcode and
2H" IS located at ' w,uch
L .
is the , W ch LS the opcode
address 0008 an~pcode for the "ADD
1 0000
ORG OH the operand 12H at
2 0000 702S ;start at l
MOV RS #2SH
; load ocat1
MOV R7 ' #34H
3 0002 7p3 4 0
25H n o
MOVA ' #o
4 0004 7400 ;load 34H :nto Rs
S 0006 20 ' ;load o . into R7
ADD A RS
' ;add into A
6 0007 2F Conte
ADD A, R7 ;now A - nts of R
,-add - A+ Rs s to A
7 0008 2412 ;now Acontent 8
ADD A, #12H " - A of R7
'. -add t~ A + R7 to A
8 OOOA 80FE HERE ,now A "va1
SJ'Mp HERE
9 oooc . "' - A Ue l
END
;end n this H
Program 2-1: List File of asrn loop

;;-~~~~~~~~~~~~~~~-:;:::~~=
36 .__ ce file
sour

TfiE sos1 ~rcaoc ------


oN"raotta
-'Nt>~
Et>t>Et> SYSTEMS
th ode for the SJMP instruc-
Program 2-1: ROM Contents
address 0009. The memory !?cation OO?A has . e
on and its target address 1s located 1n locabon
o6o~B
The reason the target
Address Cod e
!
1
ddress is FE is explained in the next chapter. 0000
70
25
0001
executing a program byte by byte
7F
. burned mto
. th e ROM of an 0002
Assunung that the above program 1s . .8051 chip
f the
(or 8751, AT8951, or D55000), the following is a step-by-step descnption 0003
34
action of the 8051 upon applying power to it. 74
0004
0005
00
1. When the 8051 is powered up, the PC (program counter) haRsOOMOOOinan!:::r::
to fetch the first opcode from location 0000 of the program .
0006 20
of the above program the first opcode is 70, which is the code for movmg
an operand to RS. Upon executing the opcode, the CPU fetches the value 0007 2F
25 and places it in RS. Now one instruction is finished. Then th: program 0008 24
counter is incremented to point to 0002 (PC = 0002), which contai.ns opcode
0009 12
7F, the opcode for the instruction "MOV R7, .. ".
OOOA 80
2. Upon executing the opcode 7F, the value 34H is moved into R7. Then the
program counter is incremented to 0004. OOOB FE
3. ROM location 0004 has the opcode for the instruction "MOV A, #0". This
instruction is executed and now PC= 0006. Notice that all the above instruc-
tions are 2-byte instructions; that is, each one takes two memory locations.
4. Now PC= 0006 points to the next instruction, which is "ADD A, RS". This is a 1-byte instruction. After the execution
of this instruction, PC = 0007.
5. The location 0007 has the opcode 2F, which belongs to the instruction "ADD A, R7". This also is a I-byte instruction.
Upon execution of this instruction, PC is incremented to 0008. This process goes on until all the instructions ,1re
fetched and executed. The fact that the program counter points at the next instruction to be executed explains \-vhy
some microprocessors (notably the x86) call the program counter the instruction pointer.

/ ROM memory map in the 8051 family


As we sa,v in the Last chapter, some family members have only 4K bytes of on-chip ROM (e.g., 8751, AT8951) and
some, such as the AT89C52, have 8K bytes of ROM. Dallas Semiconductor's DSS000-32 has 32K bytes of on-chip ROM.
Dallas Semiconductor also has an 8051 ,vith 64K bytes of on-chip ROM. The point to remember is that no member of the
8051 family can access more than 64K bytes of ~pcode ~ince the_ program counter in the 8051 is a 16-bit register (0000 to
FFFF address ran~c). It must ~e noted that w~le the firs~ locahon of program ROM inside the 8051 has the add ress of
0000, the Last locahon can be different depend!ng on the s1~e of the ROM on the chip. A m ong the 8051 family members,
the 8751 and AT8951 hav~ 4K byt~s of on-chi~ ROM. This 4K bytes of ROM memory has memory addresses of 0000
to OFFFH. Therefore, the firs t location of on-chip ROM of this 8051 has an address of 0000 and the last I ti h h
address of OFFFH. Look at Example 2-1 to see how this is computed. oca o n as t e

Example 21

Find the ROM memory address of each of the following 8051 chips.
(a) AT89C51 w ith 4KB (b) DS89C420 with 16KB (c) DSS000-32 with 32KB

Solution:
(a) With 4K bytes of on-chip ROM memory space, we have 4096 bytes (
4 1024
locations of 0000 to OFFPH. Notice that O is always the first ti x(b . = 4096). This maps to address
1
memory spa, we have 16,384 bytes (16 ,c 1024 = 16,384) .oca _on. ) With 161< bytes of on-chip ROM
have 32.768 bytel (32 x 1024 32,768). Converting 32 768 "tow:!.ch gives 0000 - 3FFFH. (c) With 321( bytes ~
ia 0000 to 7FFPH. ' ' we get 8000H; therebe, the menaory ~

-
!IOS~l~A~S;S~EM;;B~l~Y~LA~N~ciu~A~G~E~PR~OG~RA~M;M~IN;G~------------------~~~~~~---------
37
byte ..
byte ,..
byte
oOOo
()(JOO
0000

OFFF
8051 3FFF
AT89C51

[)589C420/30

7FFF
DS5000-32

Figure 2-3. 8051 On-Chip ROM Address Range

Review Questions . . .

;: ~ru~eo~~~~!~~t;~:;~~::~r :e
bits wide.
8051 family, regardless of the maker, wakes up at memory
OOOOH w h en 1t lS

3 ~~:~:;1R6M location do we store the first opcode of 3:" 8051 ~rogram?


4. The .ins truc11,on "MOV A , # 44H" is a . ?-byte instruction.
5 _ What is the ROM address space for the 8052 chip.
,/
SECTION 2.5: 8051 DATA TYPES AND DIRECTIVES
in this section we look at some \videly used data types and directives supported by the 8051 assembler.

8051 data type and directives

The 8051 rnicrocontroller has only one data type. It is 8 bits, and the size of each . . . . .
of the programmer to break down data larger than 8 bits (00 to FFH, or to . . register 1s also 8 bt ts . It 1s the JOb
O 255
For examples of how to process data larger than 8 bits, see Chapter . Tu d tn deoma1) to be p rocessed by the CPU.
or negative. A discussion of signed numbers is given in Chapter 6. 6 e ata types used by the 8051 can be positive
DB (define byte)
The DB directive is the most widely used da ta djrective th
DB is used to define data, the numbers can be in decimal b" 111 e assembler. It is used t .
decimal number is optional, but using "B" (binary) and "~'~ry, hex, o'. AScn forrnat O defin~ the 8-bit data. When
which is used, the assembler will convert the numbers int h (he~adeatnal) for th s. For deorna1, the " D" after the
tion marks ('like this'). The assembler will assign the A~n ex. To indicate A.SCn _e others is required. Regardless of
directive is the only di rective that can be used to define A.SC~od~ for the numbe 'sunpJy Place the chara t . ta-
5
used for all ASCII data definitions. Following are sorne DB hings larger tha rs or characters autorn ti~ ersll mThquoDB
exarnples n tw0 chara a ca y. e
DATAl: ORG
DB soott
28 . DEcr cters; therefore, it should be
DATA2, os 001101010 ' MAL (1c
DATA3: DB 39H ;BlNARy (35
ORG 510H ;HE}(

38
-~~'"o..~, . a:,!'
r~
~"
DATA4:
rfa 7 0
'-'a.
"2591" ;ASCII NUMBERS
ORG 518H . " ASCII cHA.RACTERS
DATA6: DB "My name 1s Joe 1
b ful for strings, which contain a
d ASCII strings. This can e use
Either single or double quotes can be used aroun . byte-sized chunks.
single quote such as "O'Leary". DB is also used to allocate memory in
E..<). v (_e.~ v..~)
Assembler directives ~"v-e I'
~ ' e c. ""'
The following are some more widely used directives of the 8051.

ORG (origin) .
. Th m ber that comes after ORG can be either
The ORG directive is used to indicate the beginning of~~ add~ess. ~ ~e assembler will convert it to h ex. Some
in hex or in decimal. If the number is not followed by H, tt 1s dec~al a_n . mbler
assemblers use ". ORG" (notice the dot) instead of "ORG" for the origin directive. Check your asse

EQU (equate)
1 ti' The EQU directive d oes n ot set aside stor -
This 1s used to define a constant withou t occupying a memory oca on. . .
age for a data item but associates a constant value with a data label so that when the label app ears in the program, its
constant value will be substituted for the label. The following uses EQU for the counter constant and then the constant
is used to load the R3 register.
COUNT v--..1,.E
t QU 2
... .... '
MOV R3,#COUNT
When executing the instruction "MOV R3, #COUNT", the register R3 will be load ed with the valu e 25 (notice the
# sign). What is the advantage of using EQU? Assume that there is a constant (a fixed valu e) used in many different
places in the program, and the programmer wants to ch ange its value throughout. By the use of EQU, the programmer
can change it once and the assembler will change all of its occurrences, rather than search the en tire program trying to
find every occurrence.

END directive
Anothe_r im~oi:ant pseud?code is the END directive. ~ s indicates to the assembler the end o f the source (asm ) file.
The END directive 1s the last !me of an 8051 program, meaning that in the source code anything after the END dir ti
is ignored by the assemb ler. Some assemblers use 11 END" (notice the dot) instead of " END" . ec ve

'V
Rules for labels In Assembly language
By choosing label names that are meaningful, a program.mer can make a pro am ch
~ain. There are several rules that names must follow. First, each label name must fe _m u easter to read and main-
m Assembly language programming consist of alphabetic letters in both u ercase ::;iue. The names ~~ed for labels
9, and the special characters question mark (?), period (.), at (@}, under~!(_), and doll: ;e~case, the di~ts Othrough
of the label must be an alphabetic character. In other words it cannot be a b E sign ($). The first character
words that must not be used as labels in the program. Foremost among thnum er. dvery assembler has some reserved
instructions. For example, "MOV" and "ADD" are reserved since the e ~eserve . words are the mnemonics for the
mnemonics there are some other reserved words. Check your assemblr ~re mthstruli ction mnemonics. In addition to the
r or e st of reserved words.

Review Questions
l. The directive is always used for ASCll strings.
2. How many bytes are used by the following?
DATA_l : DB AMERICA#
3. What is the advantage in using the EQU directive to define
a constant value?
-
8051 ASSEMBLY LANGUAGE PROGllAMMING
. &ectives?
. b ch of the foUoWJilS ,,
4-. How many bytes are set aside y) ea DATA. DB .-p.BC1234 ll ing
(a) ASC_OATA: DB 1234" (b ~-
5. State the contents of memory locations ZOO
8
.zostfforthefo ow

ORG 200H
MYDATA: DB ABC123"

/secTION 2.6: 8051 FLAG BITS AND THE PSW REGISTER ..i..... tic conditions such as theb1carry
clicate anu.,,,e
bit.
t f this
Like any other microprocessor the 8051 has a flag register to Ul . In ti.;~ section we discuss various so
' d (PSW) reer1c;ter. "'"
The flag register in the 8051 is called the program status wcr o-
register and provide some examples of how it is altered.

PSW (program status word) register


Jb~ogram status word (.PSW) register is an 8-bit register. It is also referred to .as the fiag regis.ter. Although the
PSW register lsl! bits wide, only 6 bits of it are used by the 8051. The two unused bits are user-definab~e flags. Four
of the flags are called conditional flags, meaning that they indicate some conditions that result after an mstruction is
executed. These four are CY (carry), AC (auxiliary carry), P (parity), and OV (overflow).
As seen from Figure 2-4, the bits PSW.3 and PSW.4 are designated as RSO and RSl, respectively, and are used to
:an~i: tt;:~ r:f~ters. They are explained in the next section. The PSW.5 and PSW.l bits are general-purpose status
forgthe bits of the PS~Jt!e programmer for any purpose. In other words, they are user definable. See Figure 2-4

theseThe following
registers t.extdiscussed.
is then is a brief explanation of our of the fl ag bits
. of the PSW register. The impact of instru ctions on

-
3 ~ I
CY AC FO m C
..._~~~~;.~~:
9 ,i.:!"'-;~~~--;:---~~1-~~J__~RSO~~L_~o~v~~~=--~~~P
~~
V CY
AC PSW.7 Carry flag. 05~ <'.!.'-J (I)' A c..

c ~
't - IL (;l
L
FO
RS1
PSW.6
l'SW.5
PSW.4
Auxiliary carry flag.
Available to the user f
Re . or general p
\ ~ \t)\\\o
"" RSO PSW.3 ~ler Bank selector bit 1 U!pOSe. _\ o I b I I o \
- OV PSW.2 RegJSter Bank selector bit o
Overflow flag. I t>
!'SW.I User..,,.efinable
..., bit.
p PSW.O p .
t ~ty flag. Set/cleared b
o indicate an odd/ y h.udware each.
even nu.inL- 11\Stuctj
vu of 1 bits . on cycle
In the ac
Ctunu!ator

I' l~======~======~=R:e&:sjte0tr~Banl(====== Addl'l!ss


I

~======f=====~==~I~===~
;_ 2
3
~
~
Figure 2-4. Bits of the PSW Register -
40
-
/
Table 2-1: Instructions That
CY. the carry flag . fl b't Affect Flag Bits
' . fr the 07 bit. This ag 1 15
This flag is set whenever there 1s a ~ out om be set to 1 or odirectly by 1.lin~s~tru
~ c~ti:,:
ov ~-;--
CY ---:;;---
o::":.--:~
AC
ffected after an 8-bit addition or subtraction. It can also ,, t ds for "set bit
- X X
:n instruction such as "SETB c" and "CLR C" where "SETB c s ~t-addressable ~A~D~D~---~---:---~-
X
X X X
carry" and "CLR C" for "clear carry". More about these and other b ~\...c,.fi~ ::;A~D~DC~--~--:----::;---~-
instructions will be given in Chapter 8. .....i SUBB X X X
~~-.:.:__--::--
MUL 0 X
AC, the auxiliary carry flag X
0
. .
lf there 1s a carry from D3 to D4 during an
ADD
or
SUB operation this bitD
'
1.,'.:IV~-----=-------
BCD -
is set; otherwise, it is cleared. This flag is used by instructi?ns that ~erform X _ _ _ _ __
::D'.:A:___ _ _......:...:__
(binary coded decimal) arithmetic. See Chapter 6 for more info~ation. " RRC X
v v'" ~=-----=--------
"l"' OT-' ~ p X
~RL~C:___ ___:_.:.__--:----
P, the parity flag ~ ' SETS C 1
The parity flag reflects the number of ls in the A (accumulator) regist~r only. :::C:.
L.:.R:.C-=---- - - - - - - -
0
=
lf the A register contains an odd number of ls, then P 1. Therefore, P - 0 if A has
an even number of ls. .::C:.P.=L:....:C:__ _ _X_ _ _ _ _ __
l l'J r 0 //14.f ANLC, bit X
Ci (l I 1 7) /'). ~ ," 'J v-
ov, the overflow flag > ANLC, /bit X
This flag is set whenever tne result of a signed number operation is too larg~, ORLC, bit X
causing the high-order bit to overflow into the sign bit. ln general, the carry. flag is
ORLC, /bit X
used to detect errors in unsigned arithmetic operations. The overflow flag 1s onJy
used to detect errors in signed arithmetic operations and is discussed in detail in MOV C, bit X
Chapter 6. CJNE X
Note: Xcan be Oor J.
ADD instruction and PSW
Next we examine the imp act of the ADD instruction on the flag bits CY, AC, and P of the PSW register. Som e exam -
ples should clarify their sta tus. Although the flag bits affected by the ADD instruction are CY (carry flag), P (parity
nag), AC (auxiliary carry flag), and OV (overflow flag) we will focus on flags CY, AC, and P for now. A d iscu ssion of
the overflow flag is given in Chapter 6, since it relates only to signed number arithmetic. How the various flag b its a re
used in programming is d iscu ssed in future chapters in the context of many applications.
See Examples 2-2 thro ugh 2-4 for the impact on selected flag bits as a resul t of the ADD instruction .

Example 2-2

a) Use assembler directives to place constants OFCH, OSH, 76H, 28D and character s tring "SAM" .
10
program memory locations beginning from location OOSOH. consecutive
b) Add the numbers 56H and 95H , and show how the CY, AC, and p flags are affected.
Solution:
a) ORG OSOH
DB OFCH, OSH, 76H, 28
DB "SAM"
The program memory location will contain data as follows.
Addre11 Data
0 050 PC
0051 01
0052 7fS
0053 l:C ;Hex equivalent of 28D

. . . .
-
80s1 ASSEMBLY LANGUAGE PROGRAMMING
' .

41
of S
ivalent
53 ASCII equ nt of P.
0054 '. ASCI r equi vale f M "SAM" would have to be
41
oo5S 4D ;ASCII equivalent ~en here. In that case'
0056 AS(il string as g1\
Some assemblers do not allow the use of an
written as 'S',' A','M'.
b) MOV A,#56H
ADD A, #95H
56H 01010110
+ 95H 10010101
EBH 11101011
In this calculation, CY = 0, since there is no carry beyond D7.
AC= 0, since there is no carry from the 03 to the 04.
P = 0, since the accumulator has an even number of bits.

Example 2-3
Show the status of the CY, AC, and P flags after the addition of 9CH and 64H in the following instructions.
MOVA, !l9CH
ADD A, #64H ;after addition A=OO and CY=l

Solution:
9C 100\1100
+ 64 01 l (JllOO
100 I 00000000
CY = 1 s~ce there~ a carry beyond the D7 bit.
AC = 1. since there is a carry from the D3 to the D4 bit.
p - 0 suice the accumulator has an even number of ls ('th
1 as zero ls).

Example 2-4
Show the contents of the PSW r .
MOV A, #OBFH egister after the execution of the foll . .
ADD A, #lBH owmg tnstructtons.
Solution:
BF 10111111
+~ 00011011 c,,
DA 11011010
The bits of the PSW are now as foll
PSW.7: CY= !).since there is ows.
PSW.6: AC =1 since there . no carry beyond the D7 b'
PS W5: FO: unused, hence o.is a carry from th e 03 to theit.04 b'
PSW.4: Register bank select b' RS it.
PSW 3 R .
. : eg15ter bank selector bit RSO
PSW.2: OV =0 since there is
=
or it 1 - 0 .
since by default
- 0 since by d f ' Bank Ois I
PSW.l: Not used, hence 0. no carry from D6 to D7e(:t.Bank Ois selected.
PSW.O: P =l since there is an odd signed bit .se ~ed.
The contents of the PSW is thus 01 ~ber_of '1 'sin th IJ\ signed oPer
1, i.e. 41H. e accurnulator. ,.._.).

42
Review Questions I ~\ I I I
Toe flag register in the 8051 is called _ _ __ I
(I c,1) I
r
~: What is the size of the flag register in the 8051 ?bl , r.., v' 0
Which bits o f the PSW register are user-defina e . r ' OO O
3. d
-1. Find the CY and AC flag bits for the fo llowing co e. - - - - - - } ,

s.
MOVA , #OFFH
ADD A, #01
Find the CY and AC flag bits for the following code.

- , \
MOV A, #OC2H
ADD A, #3DH
<.
'
1'\
,
(. :::,
\

SECTION 2.7: 8051 REGISTER BANKS AND STACK


128
The 8051 microcontroller has a total of 128 bytes of RAM. 1n this section we discuss the allocation of these bytes
of RAM an d examine their usage 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 ~28 bytes
of RAM inside the 8051 are assigned addresses 00 to 7FH. As we will see in Chapter 5, they can be accessed d1rectJy as
memory locations. These 128 bytes are divided into three different groups as follows.

1. A total of 32 bytes from locations 00 to lF hex are set aside for regis ter banks and the stack.
2. A total of 16 bytes from locations 20H to 2FH are set aside for bit-addressable read/write memory. A detailed dis-
cussion of bit-addressable memory and instructions is given in Chapter 8.
3. A total of 80 bytes from locations 30H to 7FH are used for read and write storage, or what is normally called a
scratch pad. These 80 locations of RAM are widely used for the purpose of storing data and parameters by 8051
programmers. We will use them in future chapters to store data brought into the CPU via [/0 ports.

Register banks in the 8051


As mentioned earlier, a total of 32 bytes of RAM are set aside 7F
for the register banks and stack. These 32 bytes are divided into 4
banks of registers in which each bank has 8 registers, RO - R7. RAM
locations from O to 7 are set aside for bank O of RO - R7 where RO is Scratch Pad RAM
RAM location 0, Rl is RAM location 1, R2 is location 2, and so on, 30
until memory location 7, which belongs to R7 of bank 0. The second
~ank of registers RO - R7 s tarts at RAM location 08 and goes to loca- 2F
tion OFH. The third bank of RO - R7 starts at memory location lOH Bit-Addressable RAM
20
and goes to location 17H. Finally, RAM locations 18H to lFH are set
aside for the fourth bank of RO - R7. Figure 2-6 shows how the 32 IF
bytes are allocated into 4 banks. Register Bank 3
18
As we can see from Figure 2-5, bank 1 uses the same RAM space
as the stack. This is a major problem in program.ming the 8051. We 17
must either not use register bank 1, or allocate another area of RAM Register Bank 2
10
for the stack. This will be discussed in Example 2-5.
OF
Register Bank 1 (Stack)
Default register bank 08
07
. URAM locations 00 - l F are set aside for the four register banks
Which register bank of RO- R7 do we have access to when the 8051 ' Register Bank O
00
powered up? The answer is register bank 0; that is, RAM locations;
l, 2, 3, 4, 5, 6, and 7 are accessed with the names RO, Rl, R2, R3, R4 '.

-
8051 ASSEMBLY LANGUAGE PROGRAMMING
Figure 2-5. RAM Allocation in the 8051

43
Bark I lf [ R7 J
J [ R6 J
1 F[ R7 ] 6
Rb
ID [ R5 J
1 E[ Rn ] I~ [
}:, - R5 ]
J tC [ R4 J
J o[
C[
' J
R4 ]
14 [ R-1 ] tB [ R3 J
8[ RJ J 13 [ R3 ] lA [ R2 J
A[ R2 ] 12 [ ~ ] 19 [ Rl J
'J [ RI ] n [ RO ] 18 [ RO 1
IO L[_;.:.._.--
0 RlJ 8[ RO ]

figure 2-6. 805 I R~giJler Banka and th etr RAM AddresK5 -

Exi mpl~ 2-5 am


~tJtc thl' conrenl!> of RAM loca tion, afttrt ,thl'value
folloY. ing
99Hpn-.gr .
H load RO Wl 1
MOV R0,#99 '.load Rl with value 85H
MOV Rl,#BSH , ith value JFlf
H load R2 w
MOV R2.#3F . 1 d R7 with value 63H
MOV
MOV R7,N63H
RS,#12H oa RS with valu~ 12H
;; load

Solution;

A ftxr the l"(l'Cuhon of the ,1bu, c pro~r,1m Wl' h.i,~he f~llo;1~g:


RAl\1 locahon Ohi!~ value 9911 RAI\I k1cat1,n l ~ \a ue
~1 location 2 hJ~ , ,1luc 3f'I I RAM lol'illiln 7 ha~ \'alue 6311
RAlvl loc.itton 5 hi!,\ ,llUl' 12H

Rcpt>at Ex.imple 2-5 using RAM addresses tlll>tead of register names.


Solution:

1,
Thl, called dtrl'Ct addressing mode and uses the RAM address locatton f h . .
5fo,, more detailed discus,,.,., of add"""'S modo,
1".0V 00, #99H
' 1 de,tinahon d<fn.ss. Se. Chapler
MOV 01 ,IIBSH ;load RO with value 99H
MOV 02, #3FH ;load Rl With Value BSH
MOV 07,1163H ;load R2 with value 3F'ii
MOV 05, 1112H ;load R7 With value 6JH
;load RS with value llH

RS, R6, .inu R7 "'hrn progran1m1ng the 8051, It i~ much e .


b h .
RI, and l><I on, than } l cir memory locations Example a51er
-6 to. re,er
, to these RAl
2 1
How to switch register banks c anfies this co ncept. ,vi l0cations With
. nam es such as RO,
~ stilted ,1bo, t.', reg1Ster bank O1s the default When
o( the PS\.V (progr.im st.itus ,,ord) rt.>gi~ter. B1ts D4 and ~ 8051 is Powered
'"""'" m r ,bte 2-2 of the Ps\y , ,. p. Iv, <an '"'tct,
44 U5e(f to &elect the t? other banks by use
des,red register bank as
Tabl e 2-2: PSW Bits Bank Selection
The D3 and D-l bits of register PSW are often referred .to
rsW.4 and PSW.3 since they can be accessed by the bit- RS1 (PSW.4) RSO (PSW .3)
:~dressable instructions SETB and CLR. For example, "SETB Bank O O 0
pSW, 3" will make PSW.3 = 1 and select bank register 1. See
1- - - -
~~~--~-------:;--
Example 2-7. ~~r~e:.. ~~ ~ -\-,~e. ~Bank~~l~--O~------;:O;-----
i;1L-D u Bank 2 1
v stack in the 8051 I" )... 1-o ~~--..:.----------
~"".\-~~ ?. . il This information could be data or
.
The stack is a section of RAM used by the CPU to store information temporar Y .
15
an address. The CPU needs this storage area since there are only a limited number of reg ters.

How stacks are accessed in the 8051


CPU t to 1t The register used to access the
lf the stack is a section of RAM there must be registers inside the
' . . to porn
l 8 b't

ide which means
tha t 1t can
stack is called the SP (stack pointer) register. The stack pomter m the 8051 is on Y I s w ' th RAM 1 ti 0
take values of 00 to FFH. When the 8051 is powered up, the SP register contains value 07. This me~ns at oca ~
08 is the first location used for the stack by the 8051. The storing of a CPU register in the stac~ is c~lled a PUSH, a n
pulling the contents off the s tack back into a CPU register is called a POP. 1n other words, a register 1s pushed ? nto 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
performed. To see how the stack works, let's look at the PUSH and POP instructions.

Pushing onto the stack


In the 8051 the stack pointer (SP) points to the last used location of the stack. As we push d ata onto the stack, the
stack pointer (SP) is incremented by one. Notice that this is different from many microprocessors, notably x86 proces-
sors in \Vhich the SP is decremented when data is pushed onto the stack. Examining Example 2-8, we see that as each
PUSH is executed, the contents of the register are saved on the stack and SP is incremented by 1. N o tice that for every
byte of data saved on the stack, SP is incremented only once. Notice also that to push the registers onto the stack we
must use their RAM addresses. For example, the instruction "PUSH 1" pushes register Rl onto the s tack.

Example 2-7

Write instructions to use the registers of bank 3, and load the same vaJue 05H in the registers RO to R3.

Solution:
SETB PSW.4 ;make RS1=1 for selecting bank 3
SETB PSW.3 ;make RS0=1 for selecting bank 3
MOV RO,#OSH ;load RO with value OSH
MOV Rl,#OSH ;load Rl with value OSH
MOV R2,#0SH ;load R2 with value OSH
MOV R3,#0SH ;load R3 with va lue OSH
After execution, the four registers ROto R4 of bank 3 (RAM locations 18H to 1BH) will .
program can be rewri tten as contam the value OSH . The

SETB PSW.4 ;make


RS1=1 for selecting bank 3
SETB PSW.3 ;make
RSO=l for selecting bank 3
MOV A,#OSH ;load
A with OSH
MOV RO,A ;move
the contents of A to RO
MOV Rl,A ;move
the contents of A to Rl
MOV R2,A ;move
the contents o f A to R2
MOV R3,A ;move
t he contents of A to R3
We_will see later that it will be more economical to use the above set 0 f . .
fer IS a shorter instruction and thus saves program memory space. instructions, as a register to register trans-

-
Bost ASSEMBLY LANGUAGE PROGRAMMING
45

' ...., .. ~ .. ..".: ,, -~,,


.
. or.,.
. :a\"'
'-,
'
< .' ~ .. ..
. ter Ois selected.
a and regJS
stack are
h default
Example 2-8 . Assume t e
. t for the fotlowing.
Show the stack and stack porn er

R6, 1i25H
MOV
MOV Rl, lil2H - \ ~p j
MOV R4, ltOF3H
p,.; \.. I
PUSH
PUSH
6
l tJ1 -
"~ PUSH 4
~ After pUSH4
Solution: After PUSH 1
After PUSH 6 OB
OB
OB OB F3
OA
OA OA OA -
12
09
09 12
09 09
08 25
08 25 08 25
08
SP =OA ; 1"
Start SP =07
- SP =08
- -
SP : 09

~opejng 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 register specified by the instruction and the stack pointer is decremented once.
Example 2-9 demonstrates the POP instruction.

The upper limit of the stack


As mentioned earlier, locations 08 to lF in the 8051 RAM can be used for the sta k Th'1 . .
of RAM are reserved for bit-addressable memory and must not be used b the c s_1s bec.ause locations 20 - 2FH
Y stack. If m a gtven program we need
Example 2-9 ( I i__ f)

Examining the stack, show the contents of the registers and SP


values are in hex. after execution of the foll . .
,... , t_ 1 owing II\Structions. All
~P 3 ; POP stack into R3 -
POP 5 \ ;POP stack into RS ,
POP 2 ;POP stack into R2
'
. ({5 /
Solution: \...._ ~
---,:. R. l.
AfterPOP3
After PQp 5
OB 54 OB AfterPQp2
OA F9
- - -
OA F9
OA - 08
09 76 09 76 -09 0A I
-
08

StartSP zOB
6C 08 6C -
08
76 -
-
SP OA
6C-
t t t RAM locations 30 - 7FH. This is done
th Sp
,ore than 24 bytes (08 to 1FH = 24 bytes) of stack, we can change e o pom o
n .
with the 1nstruc a. on "MOV SP, #xx'' .

CALL instruction and the stack


th k tO the address of the instruction just
In add1t:1on to usmg the
stack to save recnc:.ters
o- t tur s from the ca11e d sub rou tin'e.
' the CPU also uses e stac h save
belo\V the CALL mstru chon. This is how the CPU knows where to resume w en t re n
More information on this will be given in Chapter 3 when we discuss the CALL instruction.

Stack and bank 1 conflict


Recall from our earlier discussion that the stack pointer register points to the current RAM location_ available
for the stack. As data is push ed onto the stack, SP is incremented. Conversely, it is decremented as data 1s p opp e d
off the stack into the registers . The reason that the SP is incremented after the push is to make sure that the stack
is growing toward RAM location 7FH, from lower addresses to upper addresses. If the stack pointer were decre-
mented after push instru ctions, we would be using RAM locations 7, 6, 5, etc., which belong to R7 to RO of b ank 0,
the default register bank. This incrementing of the stack pointer for push instructions also en s u res that the sta ck
\\lill not reac~ location Oat 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 lo~ation 08, which also belongs to register RO of register bank 1. In other words, register bank 1 and
the stack are using the same memory s pace. If in a given program we need to use register banks 1 an d 2, we can
reallocate another section of RAM to the stack. For example, we can allocate RAM locations 60H and higher to the
stack as shown in Example 2-10.

Example 2-10

~rite P~SH instructions to push the contents of the registers on stack afte r the execution of the following set of
instructions.

MOV SP ,#4FH
SETB PSW.3
MOV R0 ,#25H
MOV Rl ,#OCH
MOV R2,#0SH
MOV A, #OCEH

Solution :
The first instruction defines the stack to be from 50H onwards Th d
bank 1. Since the register bank 1 has been selected, the address~s ofe se~otn : truction defines the use of register
address of the A register is OEOH. Hence the PUSH instructions areregts ers ' Rl, and R2 are 8, 9, and OAH . The

PUSH 8
PUSH 9
PUSH OAH
PUSH OEOH

After the four PUSH instructions, the conten t of the RAM select d
e as the stack locations will be
Address Data
50 25H
51 OCH
52 05H
53 CEH

-
. (

80S1 ASSEMBLY LANGUAGE P R O G R A M M I N G G : ~ - - - - - - - - - - - - - - - - - - - -


47
. 1ator ew the contents of registers
Viewing registers and memory with a s,mu . uiators aUoW us to vdi that you use a simulator to
I .
Many assemblers and C comp_ilers co~e w~th a 51
mulator. 5itJ1 I eeoJll.Tllen th I t
in ). We strong Y r . a rograrn w1 . a sin:iu a or gtv~s
and memory after executing each instruction (smgle-5teppchg pters. Sirlgle-stepplJ\t we can use 1t to fmd errors m r
single-step some of the programs in this chapter an~ future : addition to the fact t a ovieW 32 and Keil. See www.
us a deeper understanding of microcontroller architecture, f 8051 simulators from Pr
our programs. Figures 2-7 through 2-10 shov, screen-shots or
MicroDigitalEd.com for tutorials on how to use the sunulators.

Cl
. :IIPit. f _,~ IJfJ .
~p; , ' . I
Ha1dware
8""~ Data -
CP PO FF
PC J0003 RB 00
@RO 00
P1 00
ACC Joo RO 00 @R1 00
PS\11 (oolA1 00 @DPTR FF P2 FF
P3 FF
SP ~ IR2 00 ~@RO FF TCON 00
DPT 0000 R3 00 X@Al FF
SP>< >< THU 0000
B loo A 00
THLl 0000
C 10 R5 00 XAAEA ><
EA ro R6 00 Taik >< THI r... .\A
PCON 00
I,_
~

IE
~- fro R7 00 Ta\kP ><

'====~~~~~-----~
I

Figure 2-7. Register's Screen from Pr0 v,ew


. 32 Simulator
.

00: I I 00 00 00 00 00 00
2SJ
08: 00 00 00 00 00
00 00 00 00
1O: 00 00 00 00 00 00 00
. ..
18: DO OD DO 00 00
00 00 00 00


20: DO 00 00 00 00
28: DO 00 00 00 00
00 00 00 00
30: OD DO 00 00 00 00

38: OD 00 DO DO
DO 00 00 00 00 . . .
40: OD 00 00 DO oo
00 00 OD 00
48: DO 00 OD 00 00 00
00 00
50: DO 00 00 00 00
00 oo ..
58: OD OD 00 00 00
00 oo oo

60: 00 00

68: DO
00
00
00 00 00 DO
00 oo

00 00 00 00 00
70: DO 00 00 00
00 oo oo
78: 00 DO 00 00
00 oo oo oo


00 00 oo

oo


Figure 2-8. 128-Byte Memory S PilCe from Prov


ew 32 s
48 nnutiltor
- r "l'!
Pro1ect Work~pc1ce
-

Reos VM
e Regs
rO 0><00
rl O,d)()
r2 OxOO
r3 OlCOO
-- ,4 OxOO
r5 OxOO
16 OxOO
- 17 OxOO
r '
El - Sys
pc>'"'~ t a~ OxOO
~~ I'-~ b ... OxOO
~p; . $p Ox07
sp_max Ox07
',.. dpt1 OxOOOO
- PC$ C:OxOOOO
$tates 0
sec O00000000
'
11 psw OxOO

Figure 29. Register's Screen from Keil Simulator

,w - - - - - - - . . .. ~ -,,

C:OxOOOO 00 00 00 00 00 00 00 00 - 00 00 00 00 00 00 00 . .
00 . . . . . . . . . . . . . .
C:OxODlO 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 . ..
00 . . . . . . . . . . . . .
C:OxOD2D 00 00 00 00 00 00 00 00 - 00 00 00 00 00 00 00 00 . . ... .
. .. . .. ... .
C:OxOD3D 00 00 00 00 00 00 00 00 - 00 00 00 00 00 00 00 . .
00 . . . . . . . . . . . . . .
C:Ox0040
C:OxOOSO
C:Ox0060
00
00
00
00
00
00
00
00
00
DO
00
00
00
00
00
00
00
00
00
00
DO
00
00
00
-
-
-
00
00
00
00
00
00
00
00
00
00
00
00
00
00
00
00
00
00
00
00
00
00 . . ....
..
00 . . . . . . . . . . . . . .
.. . ... .. . .
.
00 . - . . . . . . . . . . . . .
.
C:Ox0070 00 00 00 00 00 00 00 00 - 00 00 00 00 00 00 00 .
00 . - . . . . . . . . . . . . .

..........- - . . ~ ~ ~............~~~~~- ~
J$
iJ L_"'.J:Cc

Figure 2-10. US-Byte Memory Space from Keil Simulator

Review Questions
1. What is the size of the SP register?
2. With each PUSH instruction, the s~ck pointer regi~ter, SP, is (incremented, decremented) by 1.
3. With each POP instruction, the SP is (mcremented, decremented) by 1.
4. On power-up, the 8051 uses RAM location as the first location of the stack.
5. On power-up, the 8051 uses bank . for registers RO - R7.
6. On power~up, the 8~1 uses ~ locations to for registers RO - R7 (register bank 0).
7. Which register bank 1s used if we alter RSO and RSI of the PSW by the following two instructions?
SETB PSW.3
SETB PSW .4
8. In Question 7, what RAM locations are used for register RO - R7?

-
80S1 ASSEMBLY LANGUAGE PROGRAMMING
49
SUMMARY .
. I
th 8051 inc uuu I I
..1:"g A
I
B RO Rl, R2, R3, R4, RS, R6
I

This chapter began with an exploration of the major registers of e ' t of programnung examples. The process
the contex blin t linkin'
R7, DPTR, and PC. The use of these registers was demonstra ted IIl . . the source file, to assem g', g, and
of creating an Assembly language program was described from wn~g th ext instruction to be execu ted. The
executing the program. Th.e PC (program counter) register always points Ito egunage programmers must be aware of
1
way the 8051 uses program ROM space was explored because 8051 Assemb Y an
where programs are placed in ROM, and how much memory is available. 'ther instructions or pseudo-
An Assembly language program is composed of a series of statements ~at are e~ de Pseudo-instructio
instructions, also called directives. Instructions are translated by the assembler into ma~e c~ . t hin dns
are not translated into machine code: They direct the assembler in how to translate U1S1:'uctions .m ~ mac e co e.
Some pseudo-instructions, called data directives, are used to define data. Data is allocated in byte-size increments. The
data can be in binary, hex, decimal, or ASCII formats.
Fl~gs are. useful to programmers since they indicate certain conditions, such as carry or overflow, that result from
~xecution of mstructions. The stack is used to store data temporarily during execution of a program. The stack resides
m the ~ space of the 8051, which was diagrammed and explained. Manipulation of the stack via POP and PUSH
mstructions was also explored.

PROBLEMS
'1 SECTION 2.1: INSIDE THE 8051
1. The program counterof_aos;J. is (~ b'ts 'd
2. Registers RO - R7 are all b't .d I w1 e.
3. Registers ACC and B are <t> b1 .st w1 'de
1 s w1 e.
4 N b. .
. ame a 16- 1t register in the 8051. p p'fl e r
5. It is necessary to add 45H to SSH. Are . .
MOV A, 45H the followrng two instructions correct?..(
ADO A, SSH
I) t '
6. What is the result of the followin 0 10 I
Mov A, #lSH Kc. g code and where is it kept?
MOV R2, #13H pi 1 "' ,ti ~ ~ ~ o' o
ADO A, R2
7t ~).ch of the following is (are) illegal? fl'
:.,MOV R3 #500 (W MOV Rl .
(oJ. MOV A, #25~, (er'MOV A ' #50 (t) MOV R7, #00
h ~
')
,(g) MOV R9) #SOH ' #~OH Xf) MOV A, /tFSH
8. l~oofthefollowingis(are)illegal? ~or[f/ .1cJ_/'{~r-1 i.t~-f
R3, #SOH (b)ADD W ct r...J}.. (\) C'.J.'
~(d) ADD A, #255H te) ADD~ ii.sSOH (CJ ADD R7 R4 ~ (,~ ~
1
( ,4 I
(g)ADDR3,A- '- .;f}ADDA, #FSH JfrrrC.. '"'
9. What is the result of th e foll owing
. code d o.
MoV R4, #25R an where is it kept?
MOV A, #lFH .
ADD A, R4
10. The contents of RO and A 2
:~ex~1ti~r,J each line :~:~1: : ;~1;~~rectiveJ~. What Will be th
.S p k- MOY tl'b A instructions? e content of the de tin . .
ADD .., A, ~o (' -,B ~ ) : /. s ation reg15ter after
ADD R0,#07 ~ !I {;) \ ,b lo
r ' sP ; ,o ,.. ' - ~
s P. ~ fl ;;.,-- 0- I.J
J I
,'
so
THE 8051 MICRoc
ONTROLLER AND
EMBEDDED SYSTEMS
sECflON 2.2: CNTRODUCTION TO 8051 ASSEMBLY PROGRAMMING

AND
SECTION 2.3: ASSEMBLING AND RUNNING AN 8051 PROGRAM tf,d l
I el language while C is a r. (low, high) -level
11. Assembly language is a Ie (low, hi g h) - ev
language. . . . f d ti (i e. the amount of ROM space it
12. Of C and Assembly language, which is more eff,aent m terms o co e genera on '
uses)? I f ~ r rr qr . . ' ' ' b "' f'
13. Which program produces the "obl'' file? t f .(,,...
14. True or false. The source file has- the extension "src" or "asm".(
15. Which file provides the listing of error messages? l t-t ~' 'l
16. True or false. The source code file can be a non-ASCJI file.
17. True or false. Every source file must have ORG and END directives. ~
18. How does an instruction differ from a directive? '\ \e..)(
19. Why are the ORG and END directives also called pseudocode? e.Y C..
20. True or false. The ORG and END directives appear in the" .1st" file. wr~c t:> I ('(' C ,t- .at_
11
SECTION 2.4: THE PROGRAM COUNTER AND ROM SPACE IN THE 8051 \ ,1,r<>- t .,

21. Why do we always write programs starting with ORG 0000? 'io f ,:~ ,..,.- & m 1"
22. A programmer puts the first opcode at address 100H. What happens when the microcontroller is powered up?
23. Find the number of bytes each of the following instructions takes
(a) MOV A, #SSH (b) MOV R3, #3 (c) INC R2
(d) ADD A, #0 (e) MOV A, Rl (f) MOV R3, A
(g) ADD A, R2
24. After the following program is burned into ROM, show the contents of each ROM location.
ORG OOOOH
MOV RO, #26H
MOV Rl, #36H
MOV A, #0
ADD A, RO
MOV R2, A _
25. Find the address of the last location of on-chip ROM for each of the following
(a) DSS000-16 (b) DS5000-8 (c) DS5000-32 .
(d) AT89C52 (e) 8751 (f) AT89C51
(g) DSS000-64

27. A given 8051 has 7FFFH as the address of its las/location of on-chip
8051?
RO:;
26. 89C51ED-2 has a program memory space of 64K What are its first and l t

d
~m?rytha ~resses?
at 15 e size of on-chip ROM for this
28. How many bytes space does the instruction MOV A, #4 o occupy?

SECTION 2.5: 8051 DATA TYPES AND DIRECTIVES


29. Compile and state the contents of each ROM location for the fOll .
ORG 200H owing data.
MYDAT_l: DB "Earth"
MYDAT_2: DB "987-65"
MYDAT 3 : DB "GABEH 98"
30. List thicontents of the locations that change with these ct .
ORG OSOOH 1rectives.
DB "MANGO"

SEcnoN 2.6: 8051 FLAG BITS AND TI-IE PSW REGISTER


!~. Wh~t
Which
is ~e function of the bits PSW. 3 and PSW.4? / ,,-
bits of PSW are used for the CY and AC fla b. '
_ g its, respectively?

8ost ASSEMBLY LANGUAGE PROGRAMMING


51
b1ts respecti \:el}'?
31 Which bit,, of PSW are u:,ed for the OV a.nd P flag . ' ( the Ul5t:r\Jct1ons
3,i. find the value or the rsw regt:,te"r after the executton O
HOV A, 1195
ADD A, 1il20
35 In thr ADD tmtr\lctlon, when IS AC raised? ,
36 Whal 1> the value of the CY flag after the following code
CLR C ;CY =0
CPL C ;complement carry
37. find the CY flag value after each of the following codes.
2 50
(a) MOV A, #54H (b) MOV A, #00 (c) MOV A, #
ADD A, #OC4H ADD A, #OFFH ADD A, #OS
38. Add 25H and 70H and find the contents of the AC, CY, and P flags.

SECTION 2.7: 8051 REClSTER BANKS AND STACK


39. Which bit~ of the PSW are responsible for selection of the register banks?
40. On powerup, what is the location of the first stack? . d Wh ?
41 If bank 1 regi~ters are being used, the default value of the stack pomter cannot be use Y
42. In the 8051, what is the size of the stack pointer (SP) register?
43. On power-up. which of the register banks is used?
44. Does the stack of 8051 grow upwards or downwards?
45. Assuming the use of bank 0, find at what RAM location each of the following tines stored the data.
(a) MOV R4,#32H (b) MOV R0,#12H
(c) MOV R7,#3FH (d) MOV RS,#SSH
46. Repeat Problem 45 for bank 2.
47. After p~wer-up, show how to select bank 2 with a single instruction.
48. What 1v11J be performed by the (ollowing set of in.'ilructions?
MOV
MOV
SP, #52H
A, #04 .,
MOV RO, #OSH I
ADD A, RO 41
PUSH OEOH
PUSH O
SET PSW. 4
POP lOH
POP OBOH
49. In Problem 48, does the sequence of POP . .
')
show the correct sequence of instructions instructions restore the original values of r .
SO. Show the stack and stack pointer for each r . eg1sters RO, R3, and R7? lf not,
ORG o me of the followmg program.
MOV SP, #70H
MOV RS, #66H
MOV R2, #7FH
MOV R7, #SDH
POSH 5
PUSH 2
PUSH 7
CLR
MOV
MOV
A
R2,A
R7 ,A
~-\.
~ltt
POP
POP
POP 5
7
2 -\''1 \-
:~~~
52
THE 80s1 MICROC
\'
ON'fROttER AN
D EMBEDDED SYSTEMS
ANSWERS TO REVIEW QUESTIONS

SECTION 2.1: lNSIDE THE 8051


]. MOV A,#34H
MOV B,#3FH
ADDA,B
2. MOY A,#16H
ADDA,#OCDH
MOV R2,A
3. False
4. FF hex and 255 in decimal
5. 8

SECTION 2.2: INTRODUCTION TO 8051 ASSEMBLY PROGRAMMING d . tr ctions also called assembler
. ch MOV and ADD. Pseu o-ms u ,
The real work is performed by instru~noi:is ~u as
1. directives, instruct the assembler in doing it~ 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 PROGRAM


1. True
2. True
3. (a)
4. (b) and (d)
5. (d)

SECTION 2.4: THE PROGRAM COUNTER AND ROM SP ACE IN THE 8051
1. 16
2. True
3. OOOOH
4. 2
5. With 8K bytes, we have 8192 (8 x 1024 = 8192) bytes, and the ROM space is 0000 to lFFFH.

SECTION 2.5: 8051 DATA TYPES AND DIRECTIVES


1. DB
2. 7
3. Uthe value is to be changed later, it can be done once in one place instead of at every occurrence.
4. (a) 4 bytes (b) 7 bytes
5. This places the ASCII values for each character in memory locations starting at 200H. Notice that all values are in
hex.
200 = (41)
201 = (42)
202 = (43)
203 = (31)
204 = (32)
205 = (33)

-
80s1 ASSEMBLY LANGUAGE PROGRAMMING

1
SECTION 2.6: 8051 FLAG BITS AND THE PSW REGISTER
1. PSW (program status register)
2. 8 bits
3. Dl and OS, which are referred to as PSW.1 and PSW.5, resp
ectively.
I
4.
Hex binary
FF 1111 1111
1
+
-1001 +
10000 0000
This leads to CY =1 and AC =1.
/
5.
Hex binary
C2 1100 0010
+ 30 + 0011 1101
FF 1111 1111

SECTION 2.7: 8051 REGISTER BANKS AND STACK


1. 8-bit
2. Incremented
3. Decremented
4. 08
5. 0
6. 07
7. Register bank 3
8. RAM locations 18H to 1FH
JUMP, LOOP, AND CALL
INSTRUCTIONS

OBJECTIVES

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

> Code 8051 Assembly language instructions using loops


> Code 8051 Assembly language conditional jump instructions
> Explain conditions that determine each conditional jump instruction
> Code long jump instructions for unconditional jumps
> Code short jump instructions for unconditional short jumps
> Calculate target addresses for jump instructions
> Code 8051 subroutines
> Describe precautions in using the stack in subroutines
> Discuss crystal frequency versus machine cycle
> Code 8051 programs to generate a time delay

55
. m control to a different IOcation
fer progra . . .
sary to trans trol transfer mstructions available
. d t 1s often neCes rs the con U .
ln the sequence of instruchons to be execute , . . This chapter cove 1Ooping, as we as instructions for
There are many instructions in the 8051 to achieve tht~- nstrUction5 used ~or tions and their uses. In the third
in 8051 Assembly language. In the first section we discuss examine CALL in5trUC eneration.
conditional and unconditional jumps. In the second secbon ::tionaJ
1 8051 and its newer g
section, time delay subroutines are described for both the tra

SECTION 3.1: LOOP AND JUMP INSTRUCTIONS d th n talk about jwnp instructions

11
in the 8051 an e ,
ln this section we first discuss how to perform a looping acho
both conditional and unconditional.

Looping in the 8051


. all d loop The loop is one of most widely
Repeating a sequence of instructions a certain number of tunes c _e a 15 ed b the instruction "DJNZ r
used actions that any microprocessor performs. In the 8051, the loop a~ti~n ts perform Y eg,
label" In this instruction, the register is decremented; if it is not zero, 1t Jumps to the target addr~~ referre~ to by t~e
label. Prior to the start of the loop the register is loaded with the counter for the n~ber ~f rep:tttions .. Notice that 1n
this instruction both the register decrement and the decision to jump are combined mto a single instruction.
. In ~e program in Example 3-1, the R2 register is used as a counter. The counter is first set to 10. ln eac~ iteration the
instruction DJNZ decrements R2 and checks its value. If R2 is not zero, it jumps to the target address assoetated with the
label "AGAIN". This loopin~ action continues until R2 becomes zero. After R2 becomes zero, it falls through the loop
and execut~s the 111struction immediately below it, in this case the "MOV RS, A" instruction.
~otice ~ the DJNZ instruction that the registers can be any of RO - R7. The counter can also be a RAM location as
we \Vlll see 111 Chapter 5.

Loop inside a loop


As shown in Exan1ple 3-2, the maximum count is 256. What ha if
256? To do that, we use a loop inside a loop which is II d ~~ens we want to repeat an acbon more times than
the count. See Example 3-3 () ' D ca e _ a ne_;te oop. In a nested loop, we use two registers to hold
. ~<"'-~
rl -"1~
., t/J r , , .
Example 3-1
! co
.p y y 10 using the technique of repeated addition. J
So Iution:
')
Multiplication can be achieved b add in t . .
e.g., 25 x 10 = 250 (FAH) y g he multiplicand repeatedly as .
' many times as th . .
25 + 25 + - e multiphe r .
- 25 + 25 + 22+25:1?+25+25+25:a250 /J 4---F- :Z... J-
MOV A,#0 ,!Jd' C) 2 ,-
MOV R2,#1.Q ;A:O,clear ACC ~
AGAIN: ADD A #25 ;the multiplier .
1~-1~ 6JNZ-~2,AGAIN ;add the multipl7s placed in R2
0 MOV RS A ;repeat until R2~cand to the Ace
i. 1 , ;save A in Rs . -0 (10 times)
,RS:FAH

Example 3-2
Write a program to add the first t
en natural numbe ,

56
THE sos1 Mrcao
CONTR.OLLER.
AND E1>.
YIBEDDED SYSTEMS
;A=O,clear ACC .
MOV A,#0 load counter value in R2
MOV R2,#10 '
;n; tialize RO to zer
o mb s
1 MOV RO #0 , ... d h natural nu er
):I' .It,- - , . increment RO to hol t e
AGAI~~ INC RO '. add first number to ACC
~" ADD A,RO ' . 1 R2 0(10 times)
:~17........ 0

DJNZ R2,AGAIN ;repeat unt.1 =


save the result (37H .in
) RAM location 46H
MOV 4 6H, A ' d . nl 256 since the count
. . I 3-1 and 3-2 can be repeate LS o y
The maximunt number of times that a loop Ln Examp es 255
register R2 t!> an 8-bit register and can hold only numbers from O to

Example 3-3 Ht:. SJ '__.j ~p


d (b) omplement the ACC 700 times.
\Vrite a program to (a) load the accumulator with the value 5SH, an c

Solution:
Since 700 is larger than 255 (the maximum capacity of any register), we use two registers to hold the count. The
following code shows how to use R2 and R3 for the count. ( 6 10 . (21 ) _ 6 J (( - - )
MOV A,#SSH
MOV R3, #102 ,.,,.x { ..
_.'.l
~
;A=SSH
; R3=10, the outer loop count
Jo<" I\.J -c_ /

J' l I<, _ 7 .., l >.:::;


-

IJ.,,
J
1> _ - )
NEXT:
AGAIN~ -
MOV R2,#7qJ
CPL A
;R2=70, the inner loop count
; complement A register A
DJNZ R2,AGAIN ;repeat it 70 times (inner loop) L {)/._ )
DJNZ R3,NEXT
.
In this program, R2 is used to keep the inner loop count. In the instruction "DJNZ R2,AGAIN", whenever R2 becomes
Oit falls through and "DJNZ R3,NEXT" is executed. 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 finished.

~ r conditional jumps
Conditional jumps for the 8051 are summarized in Table 3-1. More Table 3-1: 8051 Conditional Jump
details of each instruction are provided in Appendix A. In Table 3-1, Instructions
~otice that some of the instructions, such as JZ Gump if A= zero) and JC
Oump if carry), jump only if a certain condition is met. Next we examine c. o:...n.:__ _ _ __
ln:-s_tru_c_ti_o_n_ _ _A_c_ti__
some conditional jump instructions with examples. v"}z JumpifA=O /

JZ (jump if A = 0)
t,/JNZ JumpifA.tO v
. . h f . A h ./ OJNZ Decrement and jum p
. In this mstruchon t e content o regtster IS c ecked. U it is zero it
Jumps to the target address. For examp le, look at the following code '
if register O * v
CJNE A, data Jun1p if A* data
MOV A,RO ;A=RO
JZ OVER ;jump if A = 0 CJNE reg, #d ata Jump if byte if. #data
MOV A,Rl ;A=Rl
JZ OVER
; Jump if A = 0
JC P5w 1 Jump if CY= 1
}NC Jump if CY= 0
OVER: JB Jump if bit = 1
N !" this program, if either RO or Rl is zero, it jumps to the lab JNB
I OVE Jump if bit = 0
~cc that the JZ instruction can be used only for register A It e R.
k to see whether the accumulator is zero, and it does not can only ,,.J~n lot V-''l Jump if bit = 1 a nd
app1y to any
- clear b it
) " '.. '1"

JUMP, LOOP, ANO C ALL INSTRUCl10NS


57
Example 3-4 . FFH If 50, move FFJ-f to RS.
Write a program to determme iJ the content of RO is .

Solution: nto the ACC


d the number l
MOV A,RO ;loa A.CC . earlier A=FFH
INC A ;increment.thewill cause A=0,1f
JNZ NEXT ;incrementing FFH into RS.
MOV RS,#OFFH ;if A=O now, move
NEXT:
. such as decrement to use the JNZ
trunetic instruction
other register. More importantly, you don't have to perform an an
instruction. See Example 3-4.

JNC (jump if no carry, Jumps if CY= 0) d . . whether toJump. In executing


. .15 sed to make the eos1on
In th.is instruction, the carry flag bit in the flag (PS~ r_egist~ u CY= l). If it is not, the CPU starts to fetch and execute
"JNC label", the processor looks at the carry flag to~ ~ it 15 r:used but will execute the next instruction below JNC.
instructions from the address of the label. If CY= l, it wiU not.Jump . iJ CY_ it jumps to the target address. We will
Note that there is also a "JC label" instruction. In the JC instruction, - 1ch
give more examples of these mstruchons th econ t~x t O f applications
1n
in future apters.
Th e discussed in Chapters 4
There are also JB fjump if bit is high) and JNB fjump 1f bit 1s low) instructions. ese ar
and 8 when bit manipulation instructions are discussed.

All conditional jumps are short jumps


It must be noted that all conditional jumps are short jumps, mearting that the address of the target must be within
-128 to +127 bytes of the contents of the program counter (PC). This very important concept is discussed at the end of
th.is section.

/ Unconditional jump instructions

The unconditiona_l jump _is a jump in which ~ontrol is transferred unconditionally to the target location. In the 8051
there are two unconditional Jumps: LJMP (long Jump) and S]MP (short jump). Each is discussed below.

Example 3-5

In Example 3-1, it was assumed that the result of multiplication will fit . .
ing two 1-byte numbers, the product can have a maximum length f m~o an 8-b1t register. But when multiply
0
hvo 8-bit_registers must be allocated to the product. two ytes. To accommodate this possibility,
Multiply the numbers OECH by 25H using the techni f
que o repeated addition.
Solution:
MOV Rl,#0
MOV A,#0 ;Rl~O,thia ie the .
MOV R0,#25H ;clear Ace register to store the MSB
AGAIN: ADD ;the multiplier ie :
A,#OECH .
JNC HERE ;add the multip1 Placed in Ro :,
INC Rl ;if no carry thicand to the Ace
HERE: . , en repeat
DJNZ RO ,AGA!N ;increment Rl f the additi
. or each c on
MOV RO ,A ,repeat until RO:o arry generated
;the LSB of th .
the MSB e Product is .
of the moved t R
;now Rl:22H d Product is in Rl o O
an Ro .. lC!i
z
I

58

I '
/
LJMP (tong Jump) . . . hich the first byte is the opcode, and the sec-
. It 3 b)!te mstrucbon in w
L~P is an unconditional Ion~ JIIWP , is a- ti, The 2.byte target address allows a Jump to any
1
ond and third bytes represent the 16-bit address of the target oca on.
memory location from 0000 to FFFFH. ti!,. . . 16-bit thereb ving a ROM address space of
Remember that although the program counter in the ~OSl is ROM Th~ ~ginal 8051 had only 4K bytes of
K bytes, not all 8051 family members have that much on-chip prog~am F ~hi ason there is also an SJMP (short
64
on-chip ROM for program space; consequently, every byte was pr~iout
3
ump) instruction, which is a 2-byte instruction as opposed to the - yte 1
r:;.
. mdi~
~ction. This can save some bytes of
d next
) h t pply SJMP JS scusse .
memory in many applications where memory space 1s rn s or su

Vs.IMP (short j ump)


ln this 2-byte instruction, the first byte is the opcode and the second byte is the _relati~e add_ress ~~~~g;t
: 1c;;
tion. The relative address range of 00 - FFH is divided into forward and backward Jumps, that is, wi ~d
bytes of memory relative to the address of the current PC (program counter). lf the jump is forward, the target a ress
can be within a space of 127 bytes from the current PC. If the target address is backward, the target address can be
within - US bytes from the current PC. This is explained in detail next.

Calculating the short jump address


In addjtion to the SJMP instruction, all conditional jumps such as JNC, JZ, and DJNZ are also short jumps due to
the fact that they are all two-byte instructions. In these instructions the first byte is the opcode and the second byte is the
relative address. The target address is relative to the value of the p rogram counter. To calculate the target address, the
second byte is added to the PC of the instruction immediately below the jump. To understand this, look at Example 3-6.

Jump backward target address calculation


While in the case of a forward jump, the displacen1ent value is a positive number between Oto 127 (00 to 7F in hex),
for the backward jump the displacement is a negative value of Oto -128 as explained in Example 3-7.

Example 36

Using the following list file, verify the jump forward address calculation.

Line PC Op code Mnemonic Operand


01 0000 ORG 0000
02 0000 7800 MOV R0,#0 0000 \4 0 \.\
03 0002 7455 MOV A,#SSH
04 0004 6003 JZ NEXT
05 0006 08 INC RO
06 0007 04 AGAIN: INC A
07 0008 04 INC A ~~ ~ ~ 64"- ~1e.
08 0009 2477 NEXT : ADD A,#77h
09
10
11
0008
OOOD
OOOE
5005
E4
F8
JNC
CLR
MOV
OVER
A
RO,A
.r"'\&_j " ......J> ~'-,..... ~,/_A

12 OOOF F9 MOV Rl, A


13
14
15
0010
0011
0012
FA
FB
28 OVBR:
MOV
MOV
ADD
R2, A
R3 ,A - I ). i
16
A, R3 0
0013 50F2 JNC AGAIN
17 0015 80FE HBRB: SJMp HERS
, ... =t
18 0017 END

-flJMp, LOOP, AND CALL INSTRUCTIONS


-
.

59
. for a fon.vard jump is calcu-
Solution: d The target address . truction which is called .
h p forwar t urnp u1S ,
First notice that the JZ and JNC instructions b~t iumthe second byte of the shor J d of 03 at the addresses of 0004
lated by adding the PC ~f the foU_owing i.ns~~ct:J:;,,
the relative address. In line 4 the instruction J~
has opcode of 60 and_ opera:ion INC RO, which is 0006. By
th address of the next uistruc I the san1e way for line 9, the
and 0005. The 03 is the relative address, relative to e hich is 0009, is generated. n d OS the relative address.
adding 0006 to 3, the target address of the label NEXT, ~v here 50 is the opcode an
"JNC OVER" instruction has opcode and operand of 5? ~? OS iv ,, ivin JZH, the address of label OVER.
Therefore, 05 is added to 0000, the address of instruction CLR A 'g g

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

Solution:
In that program list, "JNC AGACN" has opcode 50 and relative address F2H. When the relative ad~ress of F2H
is added to 15H, the address of the instruction below the jump, we have 15H + F2H = 07 (the carry 1s drop ped).
Notice that 07 is the address of label AGAfN. Look also at "SJMP HERE", which has 80 and FE for the opcode an d
relative address, respectively. The PC of the following instruction, 0017H, is added to FEH, the relative address, to
get 0015H, address of the HERE label (17H + FEH = lSH). Notice that FEH is -2 and 17H + (-2) = lSH. For further
discussion of the addition of negative numbers, see Chapter 6.

It must be emphasized that regardless of whether the SJMP is a forward or backward um for an short um th
:~~::~o~ : : ~~ ~1:;:~::;~~er bedm~re ~h~ -12~ to +127 bytes from the addres~ ass~ciated :ith th~ insfruc~ mtirlll
-~10
is out of range. . is ma e o v10 ate th.is rule, the assembler will genera te an error stating the jump
. ur!EAY
Review Questions
I.
2.
The mnemonic DJNZ stands for
True or false,; "DJNZ RS, BACK"--b.--
.....
la!-.

,, . com mes a decrement and a . . .


3. ~1;:~~~,,s ah. . -byte instruction. Jump in a smgle mstruction.
4
LJMP . , iv 1ch register's content is checked to see if t .
5. i.s a -byte instruction. i is zero?

SECTION 3.2: CALL INSTRUCTIONS


Another control transfer instruction is the .
often used to perform tasks that need t b CALL mstruction, which is
to s~v~g memory space. ln the 8051 th:reeJ:~:med fre~uently. This mak~:e: to call a subroutine. Subroutines are
Deeding which one to use depends on the target a~tructions for call: LCALL (rrogram more structured in addition
ess. Each instr . ong call) and ACAL
uction is explain d L (absolute call).
/ LCALL (long call) e next.
In this 3-byte instruction, the first b t .
target subroutine. Therefore LCA y e IS the opcode and the ~
f th , an be used t U --.ond and thir
space o e 8051. To make sure that aft o ca subroutines d bytes are
the processor automatically saves on theer txecution o thecaUed sub loca_ted anywhere w~s~d for the address of the
subroutine is called, control is transferred st a: the address of the ins:ou~me the 8051 kn t hm the 64K-byte add~
stack and begins to fetch instructions from~ at subroutine, and the Uchon immediate! ows where to come bade to,
RET (return) transfers control back to the c Ile new location. After f1' . phinr?Cessor saves th YPCbelow the LC ALL. When a
a er. Every b n1s g e (p
su routine n d execution of th rogram counter) on the
ee s RET e subr tin
60 as the last i . ou e, the instruction
nstruction See E
THE sosi xample 3-8.
MICRoc oN
TROLLER AND
EMBEDDED SYSTEMS
Eiample 3-8 SSH d AAH continuously. Put a time
. 1b ding to it the values an th 8051 . the next
\\I rite a program to toggle all the bits of port y~ am will be used to test the ports of e m
delay in ben-veen each issuing of data to port 1. This progr
chapter.

Solution:
ORG 0
BACK: MOV A,#SSH load A with SSH
'
;send SSH to port l
MOV Pl,A
LCALL DELAY ;time delay
MOV A,#OAAH ;load A with AA (in hex)
MOV Pl,A ;send AAH to port 1
-LCALL DELAY
;keep doing this indefinitely
.
/ SJMP BACK
this is the delay subroutine
--- ORG 300H ;put time delay at address 300H
DELAY: MOV RS,#OFFH ;RS= 2SS(FF in hex) ,the counter
AGAIN: DJNZ RS,AGAIN ;stay here until RS becomes 0
RET ;return to caller (when RS - 0)
END ;end of asm file

The following points should be noted for the program in Example 3-8.

1. Notice the DELAY subroutine. Upon executing the first "LCALL DELAY", the address of the instruction right
below it, "MOV A,#OAAH", is pushed onto the stack, and the 8051 starts to execute instructions at address 300H.
2. In the DELAY subroutine, first the counter RS is set to 255 (RS = FFH); therefore, the loop is repeated 256 times.
When RS becomes 0, control falls to the RET instruction, which pops the address from the stack into the program
counter and resumes executing the instructions after the CALL.

The amount of time delay in Example 3-8 depends on the frequency of the 8051. How to calculate the exact time will
be explained in detail in Chapter 4. However you can increase the time delay by using a nested loop as shown below.

DELAY: ;nested loop delay


MOV R4,#2SS ;R4 = 2SS(FF in hex)
NEXT: MOV RS,#2SS ;RS= 2SS(FF in hex)
AGAIN: DJNZ RS,AGAIN ;stay here until RS becomes o
DJNZR4,NEXT ;decrement R4
;keep loading RS until R4 = 0
RET ;return (when R4 = 0)

CALL instruction and the role of the stack


The stack and stack pointer were covered in the last chapter To unde t d th .
troUers, we now exanune the contents of the stack and stack pointer fo ;s an e unp~rt~nce of the stack in m.icrocon -
r xamp1e 3 -8. This lS shown in Example 3-9.

Use of PUSH and POP instructions In subroutines


U?on calling a subroutine, the stack keeps track of where th CPU h
:or
this reason, we must be very careful in any manipulation of s~ k s ould return after completing the subro utine
~p instructions must always match in any called subroutine c ~on tents. The rule is that the n umber of PUSH and
Example 3-10.
1
n er w ords, for every PUSH there must be a POP.

-
J\Jtvtp, LOOP, ANO CALL INSTRUCTIONS
61
Example 3-9 L . the following.
f the first LCA L m
Analyze the stack contents after the execution o

Solution:
ORG 0 -load A with SSH
001 0000 A,#SSH ;send SSH to port 1
7455 BACK: MOV
002 0000 Pl,A
003 0002 F590 MOV ;time delay
LCALL DELAY -load A with AAH
004 0004 120300 A,#OAAH
005 0007 74AA MOV ;send AAH to port 1
MOV Pl,A
006 0009 F590
120300 LCALL DELAY ;keep doing this
007 OOOB
80FO SJMP BACK
008 OOOE
009 0010
010 0010 - - - -this is the delay subroutine
011 0300 ORG 300H
012 0300 DELAY:
MOV RS,#OFFH ;R5=255
013 0300 7DFF
014
015
016
0302
0304
0305
DDFE
22
AGAIN: DJNZ
RET
END
RS,AGAIN ;stay here
;return to caller
;end of asm file
--
~ I
When the first LCALL is executed, the address of the instruction "MOY A,#OAAH" is saved on the
stack. Notice that the low byte goes first and the high byte is last. The last instruction of the called
subroutine must be a RET instruction, which directs the CPU to POP the top bytes of the stack into
OA
09 00
08 07
--::
~blii~
the PC and resume executing at address. The diagram shows the stack frame after the first LCALL. SP = 09 (tit..,
&

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,#SSH
03 0002 F590 ;load A with SSH
04 0004 7C99 MOV Pl,A
MOV
;send SSH to port 1
05 0006 7D67 R4,#99H
06 0008 120300 MOV RS,#67H
07 OOOB 74M LCALL DELAY
MOV ;time delay
08 OOOD F590 A, #OAAH
MOV ;load A with AA
09 OOOF 120300 Pl, A
10 0012 80EC LCALL ;send AAH to port
DELAY 1
11 0014 . SJMp
this is the delay
BACK
12 0300 ' b ; keep doing this
13 0300 C004 ORG su routine
DELAY: 300H
14 0302 coos PUSH 4
15 0304 7CFF PUSH s ;PUSH R4
16 0306 7DFF MOV ;PUSH R.5
NEXT: R4,#0FFH
17 0308 DDFE MOV ; R.4=FFH
AGAIN: RS,#OFFH
18 030A DCFA DJNz ; R5=25S
RS,AGA!N
19 030C DOOS DJNz R4,NEXT
20 030E 0004 POP s
21 0310 22 POP 4 ;Pop into R
22 0311 RET
END
;PQp into
:return t
R!
;ena of o caller
-
&11111 file
62
THE 8051 MICRO
CONTROLLER AN
D EMBEDDED SYSTEMS
Solution: ecify the direct address of the register being
firSt notice that for the PUSH and POP instructions we m ust sp
pushed or popped. Here is the stack frame.

After P USHS
After PUSH4
After the first LCALL
OB 67 RS
OB
OB
OA 99 R4
OA 99 R4
OA I
09 00 PCH
09 00 PCH
09 00 PCH
08 OB PCL
08 OB PCL 08 OB PCL

Calling subroutines
In Assembly language p rogramming it is common to have one main program and many subroutines that are called
from the main program. This allows you to make each subroutine into a separate module. Each module can be tested
separately and then brought together with the main program. More importantly, in a large program the mod ules can
be assigned to different programmers in order to shorten development time.
It needs to be emphasized that in using LCALL, the target ad dress of the subroutine can be anywhere within the
64K-byte memory space of the 8051. This is not the case for the other call instruction, ACALL, which is explained
next.

; MAI N program calling subrout i n e s


ORG 0
MAIN: LCALL SUBR 1
LCALL SUBR 2
-
LCALL SUBR 3
-
HERE: SJMP HERE
; -- - -,end of MAIN
.
'
SUBR l: .. ..
....
RET
, - - - ~ n d of subroutine 1
'
SUBR 2 : .. ..

RET
; end of subr outine 2
SUBR 3: ....

RET
: - - -- nd of s ubroutine 3
END ;end of the asm file

Figure 3-1. 8051 Assembly Ma.in Program That Calls Subroutines

-
JlJMI,, LOOP, AND CALL INSTRUCTIONS
63
C. ~I.MC. -\1Jv,
i;:.J).o - r"-"'J ,,v;v-
/ ACALL (absolute call) M '~ . ce ACALL is a 2-byte instruction the
hich is 3 bytes. 5l.11 d t th '
ACALL is a 2-byte mstruction in contrast to LCALL, w n1 11 bits of the 2 bytes are use or e address.
target address of the subroutine must be within 21< bytes because .
0
~
gram counter on the s tack or the function
There is no difference betv.een ACALL and LCALL in terms of savin~ ~~LL can be anywhere within _th~ 64K-byte
of the RET inStruction. The only difference is that the target address or hin a zJ(-byte range. In many vanabons of the
address space of the 8051 while the target address of ACALL must be ;it
I such cases, the use of ACALL instead of
8051 marketed by differen t companies, on-chip ROM is as low as lK yte. n
LCALL can save a number of bytes of program ROM space. ti . tly by having a detailed knowledge 0 f
Of_course, _in addition to using compact inStructions, we can program e ~c,~ Look at Example 3-12.
all the instructions supported by a given microprocessor, and using them wise Y
.

Example 3-11
'vVrite ,, program to toggle the bits of port I with a delay \Vhich depends on the value of a number in RO.

Solution:
;Tested for an AT89C51 with XTAL = 22 MHz .

ORG Oo ll 0
START: MOV A, #0 o c,;_;J,f;
MOV Pl, A/' / ;move t he value of Oto port Pl
MOV R0,#30H
ACALL DELAY'
CPL A
MOV Pl,A ,f
;RO=the value correspo nding to the req u ire d d elay
;call the delay routine
;complement A
; the bits of port 1 are all at ' l ' le 1
.
..
....
MOV RO, #OFFH ;RO value is c hange d to ve now
ACALL DELAY ;call the delay r o ut ' get _a longer delay
1ne again
SJ MP START 1

\ DELAY:
AGAIN:
"-._. ORG 3 OOH
NOP ,-., ;do nothing
.

DJNZ RO, AGAIN ;decrement RO unt1 l 1t


. 1s
. ze
.
~RET ,return to caller ( h ro
END _. . d wen RO=O)
\ , en of asm file
In this program if LED
')
LEDS. n,; ACALL ::f
in practice the ~mo s are connected to port l, the ON .
d~Jay_possible with an 8-bit co;~e
~f the LEDs will be lar er
two bytes of program m uction is used here instead of LCA[ ~gtste.r will be too small fo
t~an the OFF time. But.
.

ernory space (one byte each f ch , so in this progra th n_o ce the blinking of the
or ea call). m ere IS an e ffective saving of

;------------1A~,,.,;,-:;t_~&~
l~Exa=m~p~l~e3~-~
1
2
...:., ~ (' t' -r

Rewri te Example 3-8 as effic1ent


. Iy as you ca
n.
Solution:
ORG 0
MOV A, #SSH
BACK: MOV Pl ,A ;~oad A wi th SSH
ACALL DELAY ;issue val
t. ue i n reg
CPL A
; ime delay A to l>Or t l
SJMP BACK ;complement r
; keep doi eg A
ng thi s indefin
.1.t e1y

THEsos1 Ml
CRoco
NTROLLER AND
EMBEDDED SYSTEMS
-~~~-this is the delay subroutine
,
DELAY: , hex), the counter
RS,#OFFH 2
;RS= SS(FF in becomes 0
MOV ;stay here until RS
AGAIN: DJNZ R5,AGAIN . return to caller
RET ~end of asm file
END '
AAH. and by comple-
. . B om lementing SSH, we have ' . .
Notice in this program that reg15ter A is s';,t _to S~H. YS~H) becomes "10101010" in binary (AAH) when it ts
menting AAH we have SSH. Why? "01010101 m b~~ _( Iemented.
complemented; and "10101010" becomes "01010101 if it is comp

Review Questions
l. What do the mnemonics "LCALL" and "ACALLf" standd for?h e within the 64K bytes of code space if using the
2. True or false. In the 8051, control can be trans erre anyw er
LCALL instruction. . . 1 ( c_...\. v,...'f..,..
3. How does the CPU know where to return to after executing the RET mstruchon . LL.A~ b bv,.j
4. Describe briefly the function of the REI instru~tion. . A CALL ~1.. l.dro ~..,._,._~
5. The LCALL instruction is a -byte instruction.
I.. N~ ~ ' I ~ (" <.t-\ \
SECTION 3.3: TIME DELAY FOR VARIOUS 8051 CHIPS
In the last section we used the DELAY subroutine. In this section we discuss how to generate various time delays
and calculate exact delays for the 8051 and DS89C4x0.
- V,. -c....9,. ( \

Machine cycle for the 8051


\t\&
I \\C..'"' lJ"" 's \'\,

The CPU takes a certain number of clock cycles to execute an instruction. In the 8051 family, these clock cycles are
referred to as ,nncliine cycles. Table A-1 provides the list of 8051 instructions and their 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 oscil-
lator cormected to the 8051 system. The crystal oscillator, along with on-chip circuitry, provide the clock source for the
8051 CPU (see Chapter 8). The frequency of the crystal connected to the 8051 family can vary from 4 MHz to 30 MHz,
depending on the chip rating and manufacturer. Very often the 11.0592 MHz crystal oscillator is used to make the 8051-
based system compatible with the serial port of the IBM PC (see Chapter 10). In the original 8051, one machine cycle
lasts 12 oscillator periods. Therefore, to calculate the machine cycle for the 8051, "ve take 1/12 of the crystal frequency,
then take its inverse, as shown in Example 3-13. c,.. ( t-<: , "< , ,11 ~ o;....
' o,. t l~::. IL- c..,tbtvt t t\S"1 -#..S (),1\
\ W\."--C.~ ~c::( ~(" "' ~ p . /--
Example 3-13

cvcle 1n each case.


.
(a) 11.0592 MHz (b) 16 MHz (c) 20 ~ " .. I\.~~
,(I'-...<. llC. ._,,.
~
~
The f~llowing shows crystal frequency for three differ!nt 8051-based systems. Find the e riod f th
P O
h"
e mac me

Solution: ~ ~ v""'
(a) 11.0592 MHz/ 12 = 921 .6 kHz; machine cycle is 1/921.6 kHz= I 085 ( .
(b) 16 MHz/ 12 = 1.333 MHz; machine cycle (MC)= 1/ 1.333 MHz ~
(c) 20 MHz/12 = 1.66 MHz; MC a 1/ 1.66 MHz "' 0.60 s 0.
.J5s microsecond)

--
J\JM_p, LOOP, AND CALL INSTRUCTIONS
-

65
the following i.n5tructions.
Example 3-14 . to execute each of
. find how long it takes
For an 8051 system of 11.0592 MHz '
DJNZ R2,target
(al MOV R3,#SS (bl DEC R3 (cl
(dl LJMP (el SJMP (fl NOP (no operation)
(g) MUL AB ..
Sol uti on.. Examp1e 3 _13 Table A-1 in Appendix A .
H . 1 085 s as shown L11
The machine cycle for a system of 11.0592 ~ z IS : Therefore, we have: '.
shows machine cycles for each of the above instructions. .
Titne to execute .
lnstructio11 Machine cycles 1x1.oss s"' 1.085 s
(al MOV R3,#55 1
lxl.085 s = 1.085 s
(b) DEC R3 1
2xl.085 s - 2 .17 s
(c) DJNZ R2,target 2
2xl.OB5 s - 2.17 s
(d) LJMP 2
(el SJMP 2
2x1.oas s _ 2.17 s
(f) NOP 1 lxl.085 s "'1.085 s
(g) MUL AB 4 4Xl.085 s = 4.34 s

Delay calculation for 8051


As seen in the last section, a delay subroutine consists of two parts: (1) setting a counter, and (2) a loop. Most of the
time delay is performed by the body of the loop, as sho~vn in Example 3-15.
Very often we calculate the time delay based on the instructions inside the loop and ignore the clock cycles associ-
ated with the instructions outside the loop.

I Example 3-15

Find the size of the delay in the following program, if the crystal frequency is 11.0592 MHz.
MOV A,#SSH ;load A with SSH
AGAIN: MOV Pl,A
1 ;issue value in reg A to port 1
ACALL DELAY ;time delay
CPL A ;complement reg A.
SJMP AGAIN ;keep doing
;--Time delay this indefinitely
DELAY: MOV R3,#200
HERE: ;load R3 with 200
DJNZR3,HERE
RET ;stay here until R3 become 0
;return to caller
Solution:
From Table A-1 in Appendix A, we have the foll .
subroutine. owmg machin
e cycles for each instruction of the
DELAY: MOVJR3,#200 lfacb1ne Cycle
HERE: DJNz R3,HBRE l
RET

Therefore, we have a time delay of ((200 ic 2) + + x


1 2
] l.085 JJS =: A">c 25
-.JO. 5 s.

66
THI! 8051 MICRoco
NTROLLER
AND EMBEDDED SYSTEMS
e the delay is to use NOP
. 255 therefore one way to mcreas
I Example 3-15, the largest value the R3 register can tak~ is " .' ply was;es time. This is shown in Example 3-16.
. n uons in the loop. NOP which stands for "no operation, s tm
tM~~ I

Loop inside loop delay . . ll d a nested loop. See Example 3-17.


. d loop1 which 1s a 1so ca e
Another way to get a large delay is to use a loop ms1 ea

/
V

Example 3-16
For an 8051 system of 11.0592 MHz, find the time delay for the following subroutine:
N""" re;,rr.."o ~ "'.{
Ma c h i n e cycle ~ :r.- Q
DELAY: MOV R3, #250 1 \ \,\
HERE: NOP 1 \-\C..Jt. C ~~
NOP 1 I

NOP 1
J 1 ,I/
NOP
"
.~3,HERE t(:)\\\)
OJNZ
RET
2,
2
}
\=M~C~
Solution: ,- "'\ f
The time delay inside the HERE loop is [250(1 + 1 + 1 + 1 + 2)) x 1.085 s =1500 x 1.085 s = 1627.5 s. Ad ding the
n.vo instructions outside the loop we have 1627.5 s + 3 x 1.085 s = 1630.755 s.
If machine cycle timing is critical to your system design, make sure that you check the manufacture's da ta sheets
for the device specification. For example, the DS89C420 has 3 machine cycles instead of 2 machine cycles for the
RET instruction.

Example 3-17

For an 89C51 with a crystal frequency of 22 MHz, generate a delay of 5 ms.

Solution:
~ ~\..'it "o
;Tested for an AT89C51 with XTAL~22 MHz. N'\ (:, " Q. )... J ;:; \ '
DELAY: Machine Cycle t-\t. , e :
MOV R2,#19 1 'fY'\OV (Z.l7~'l,_r
HERE: MOV R3, #255 1
AGAIN: DJNZ R3,AGAIN 2
OJNZ R2,HERE 2
RET 2
For a crystal frequency of 22 MHz, one machine cycle will be o546
=
The AGAIN loop takes (2 x 255 ) x 0.546 278 s. . s.
The HERE loop repeats the AGAIN loop 19 times.
=
Hence the delay is 278 x 19 5.29 ms =- 5 ms
However there is an extra delay corresponding to the instructions
gets repeated 19 times equaling a delay of 19 x 3 x 0.546 .,. 31 U 'MOV R3,#255' M ~ , which
we should remember that in delay loop&, the time is only ,as, which can llllfely 'be J.1~ lit,;.;.w
U\structions in the subroutine. lfPl'4 ... . maw. &lave igl ft)Jpfr. . . . . . . . . .

~~~~~--~~~====:
llrMP, LOOP, AND CALL INSTRUCTIONS
67
. Clocks per Machine Cycle (MC)
Table 3~2. 8051 Versions
Delay calculation for other versions of 8051 for Various Clocks per _
In creating a time delay using Assembly language chip/Maker Machine Cycle
instructions, one must be mindful of ti.vo factors that can 12
affect the accuracy of the delay. AT89C51 Atmel 6
-
1. The crystal frequency: The frequency of the crystal oscil-pP!Bg~C::S4~X2~P~h~jJ~ip~s~--------~~ - -
lator connected to the Xl - X2 input pins is one factor : 4 -
in the time delay calculation. 1l1e duration of the clock D55000 Dallas Semi . 1
period for the machine cycle is a function of this crystal OS89C420/30/40/50 Dallas SeIJU
frequency. -

m 1980, both the field of IC technology and the architectural design of nucro~rocessors a~e seen grea ~ vance-
2. The 8051 Design: Smee the original 8051 was designed . h t d
ments. Due to the limitations of IC technology and limited CPU design expe~,en~e at that time, the machine cycle
duration was set at 12 clocks. Advances in both IC technology and CPU design in :ecent years have made the 1-
cl?'k ma~e cycle a common feature of many new 8051 chips. Indeed, one way to increase the ~051 performance
w1~out lo~mg code compatibility with the original 8051 is to reduce the number of clock c~cles it takes t~ execute
an 1:"5truction. For these reasons, the number of machine cycles and the number of clock periods per machine cycle
vanes among .the different versions of the 8051 microcontrollers. While the original 8051 design used 12 clock peri-
ods per machine cycle, many of the newer generations of the 8051 use much fewer clocks per machine cycle. For
example, the DS5000 uses 4 clock periods per machine cycle v,hile the D589C4x0 uses only one clock p er m achine
cycl~. The 8051 products from Philips
~nuconductors have the option of using
either 6 or 12 docks per machine cycle. Table 3-3: Comparison of 8051 and DS89C4x0
T~ble 3-~ shows some of the 8051 versions Machine Cycles
with theJI machine cycles.
Instruction 8051 DS89C4x0
MOV R3,#va1ue 1 2
Delay calculation for DS89C4 xo DECRx 1 l
In the case of the DS89C4x0, since the DJNZ 2 4
number
fr docks per ma ch'me eye1e was reduced
om 12 to 1, the number of machine cycles used LJMP 2 3
to execute an instruction had to be chang d SJMP
chin th.IS rearity. Table 3-3 compares the
to reflect e 2 3
ma . e cycles for the DS89C4x0 and 8051 f NOP
1 1
some instructions. or MULAB
4 9

Example 3-18
: rom Table 3-2, find the period of the .
rmpact on performance. (a) AT89CS} machine cycle (MC) in each .
(b) P89CS4X2 (c) DSS case if XTAL - 11
Solution: OOO (d) DS89C4x0 - .OS92 MHz, and disctm the

(a) 11.0592 MHz/ 12 = 921.6 kHz M .


(b) 11.0592 MHz/ 6 = 1.8432Mlh C ~ 1/ 921.6 kHz = 1 085
I MC IS 1/ 1.8432 MHz .

~~c
(c) 11.0592 MHz/ 4 = 2 7648 s (rnicrosecon
(d) 11.0592 MHz/ I = i1.a592 is. t/2.7648 MHz :g.5425 s :: 542 nsd) == 1085 ns
. . , MC IS 1/ 11.0592 MHz .:.36 s == 360 ns
This means that if we connect - 0.0904 s _
~
mately 9 to 10 times...-_ __ AT89Cs1 and a DS89C
y ~ u u , u ~ boost for the nccn,. 4xO to a
- 90 ns
..,~~4x0 chip crystal of the
over the A Ton,, &aJne ' - - - -
;;68~----------~~~;;:::: THE 80St 1l.n
8-20.
0~~s1. 5ee ~ w e p t 4ffilo,d,,
.
.
"'lCRoco
NTROLLERAN
D EMBEDDED SYSTEMS
See the following Web sites for_D~89.C420/30/40/50
instructions and t1m1ng.

www.maxim-le.com
www.MicroDigitalEd.com

Example 3-19
For an AT8051 and D589C420/30/40/S0 system of 11.0592 MHz, find how long it takes to execute each of the
following instructions.

(b) DEC R3 (c) DJNZ R2, target


(a) MOV R3, #55
(e) SJMP (f) NOP (no operation)
(d) LJMP
(g) MUL AB

Solution:
The machine cycle time for the AT8951 and DS89C420/30 was shown in Example 3-18. Table 3-3 shows machine
cycles for each of the above instructions. Therefore, we have:

Instn,ction AT8051 DS89C420/30l40/50


(a) MOV R3,#55 lxl085 ns - 1085 ns 2x90 ns - 180 ns
lx90 ns = 90 ns
(bl DEC R3 lxl085 ns = 1085 ns
(cl DJNZ R2, .. 2xl085 ns - 2170 ns 4x90 ns - 360 ns
(d) LJMP 2xl085 ns = 2170 ns 3x90 ns - 270 ns
(e ) SJMP 2xl085 ns - 2170 ns 3x90 ns - 270 ns
( f ) NOP lxl085 ns = 1085 ns lx90 ns = 90 ns
(g) MUL AB 4xl085 ns - 4340 ns 9x90 ns = 810 ns

Example 3-20

Find the time delay for the loop section of the following subrouti 1'f t
1 15
a crystal frequency of 11.0592 MHz. ne run on a DS89C420/30 chip , assuming

DS89C420/30 Hachine Cycle


DELAY: MOV R3,#250
HERE: NOP 1
NOP l
NOP 1
NOP 1
DJNZ R3,HERE 4
RET

Solution:
The time delay inside the HERE loop is (250(1 + 1 + 1 + 1 + 4
Example 3-16, we see DS89C4x0 le about 9 timet faster' (l )] >cJII90/ na
627 ,.._
180 2000,,
x 90 na 180 a.~. ttlis-..u.1..
ff IUl

. . -- ..... - - - ..
-JlJMp, LOOP, AND CALL INSTRUCTIONS
..,

69
bl'nking is clearly seen.
so that the L ncy 22 MHz.
Example 3-21 ed to port Pl at a slo9~;tt~se a crystal of freque
. k all the LEDs connect . . the ATS
Write a program to blin Hz and that the system is using
A~sume a frequency of 22 M

Solution:

51 . th XTAL = 2 2 MHz . .
h blinking o f the LEDs. Two th.
8-bit
d
Tested for an AT89C wi to observe t e I e of delay. Hence a Lr
, d h"ch will be necessary h large va u
Let us consider a delay of l /2 secon w ~ ill ot be sufficient to give sue
registers with a maximum count of 255 ea w n
register needs to be employed.
MOV A,#OFFH
AGAIN: MOV Pl,A
ACALL DELAY
CPL A
SJMP AGAIN

-----------Time delay
DELAY: MOV R2, #7
HEREl: MOV Rl, #255
HERE2: MOV R0,#255
HEREJ: DJNZ RO, HEREJ
DJNZ Rl , HERE2
DJNZ Rl,HEREl
RET s
Delay =7 x 255 x 255 x 2 MC x 0.546 = 497 ms = 0.5 second = 1/2 second

DI
Example 3-22
atil
:~-
~
Write a program to toggle all the bits of Pl every 200 ms. Assume crystal frequency is 11.0592 MHz and the
system is using DS89C420/30/40/50. I it,
Solution: :~
')
l)uy,
;Tested for DS89C420 of 11.0592 MHz.
MOV A,#55H 1CAi
AGAIN: MOV Pl,A Illa:
ACALL DELAY 200m
CPL A -
SJMP AGAIN
;----Time delay
DELAY 200m:
MOV RS,#9
HEREl: MOV R4 ,#242
HERE2: MOV R3,#255
HERE3: DJNZ RJ,HEREJ
DJNZ R4,HERE2
DJNZ RS,HEREl
RET

Delay 9 x 242 x 255 x 4 MC x 90 ns =199,940 s


Use an oscilloscope to measure the system square wa .
ve period to Verify deJ4y.

70
THE 8051 MlCRocoN
TROLLER AN
D EMBEDDED SYSTEMS
. . atin time delay is not the most reliable
d th t use of the instruction m gener g hil t t an accurate time
from the above discussion we con clu e a . s as described in Chapter 9. Meanw e, ~ ge

:~ay
thod. To get more accurate time delay we use tuner cilloscope to measure the exact time de ay.
for a given 8051 microcontroller, we must use an os

See the following Web sites for 8051 produc~s


and their features from various companies.
www.8052.com
www.MicroOigitalEd.com

SJMP to itself using $ sign


t t lf in order to keep the microcontroller
ln cases where there is no monitor p rogram, we need to s h ort JUJnP o 1 s~
busy. A simple way of doing that is to use the$ sign. That means in place of this

HERE: SJMP HERE

we can use the following:


SJMP $

Review Questions
1. True or false. In the 8051, the machine cycle lasts 12 clock cycles of the crys tal frequency.
2. The minimum number of machine cycles need ed to execute an 8051 ins truction is - - - - -
3. For Question 2, what is the maximum number of cycles needed, and for which instructions?
4. Find 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 o f the following
DELAY subroutine.
DELAY : MOV R3 , #1 0 0
HERE : NOP
NOP
NOP
DJNZ R3 , HERE
RET
6. True or false. In the DS89C420/30, the machine cycle lasts 12 clock cycles of the crystal fr
7. Find the machine cycle for a DS89C420/30 if the crystal frequency is 11.0592 MHz. equency.

SUMMARY
The flow of a program proceeds sequen tially, from instruction to instr ti
is executed. The various types of control transfer instructions in A bl ~c on, ~ess a contr ol transfer instruction
tional jumps, and call instructions. ssem Y anguage mclu de conditional and uncondi-
The looping action in 8051 Assembly language is performed us . .
ter and jumps to the top of the loop if the counter is not zero. Other ~~a ~pecial ~ ~ction, whi~~ decrements a coun-
value of the carry flag, the accu mulator, or bits of the 1/ 0 port Un~on~ ~ s tru~tions Jump cond1tionally, based on the
~n the relative value of the target address. Special attention m t b . itional Jumps can be long or short, depending
tions on the s tack. us e gtven to the effect of LCALL and ACALL instruc-

-
JUMP, LOOP, AND CALL INSTRUCTIONS

11
PROBLEMS MP INSTRUCTIONS . n,<P HERE, where HERE cor-
SECTION 3.1: LOOP AND JU 4 ti.Jl'les. et address 111 SJJ....
dd 3 to the accumulator Jculate the targ
1. Write a program to a t r (PC) value is 0100H, ca tents of register-----
2 If the current program coun e is added to the.con tion.
responds to 003FH. f ump a displacement -byte JJlStrUC
3 ln calculating the target address or a J , and it is a - - - -
4: The mnemonic SJMP ~tands f?r L and SJMP different? corresponds to 0630H.
5 ln what ways are the mstructions. ~JMP THERE where THERE, f the current PC.
6. Repeat Problem 2 for the instructi~n . within -'128 to +127 bytes o
7. True or false. The target of a short 1ump IS
s:
True or false. All 8051 j~ps ar~ sh~rt(Jur;)p~~t a short jump?
9 Which of the following mstructtons is ar
10: (a) JZ (b? JNC _(c) LJMP (d)
11 A short Jump 1s a
D]NtYte instruction.. Why?
12 True or false. All condition
al Jumps
are short Jumps.
ti 1000 times.
13. Show code for a nested loop to perform an ac .on 100 000 times
14. Show code for a nested loop to perform an a~tton f ' ed
15. Find the number of times the fo llowmg
Joop 15perorm .
MOV R6,#200
BACK: MOV RS,#100
HERE: DJNZ RS HERE I

DJNZ R6, BACK . . f bytes from the current PC.


15. The target address of a jump backwar? 15 a
m~XImwn -----bytes from the current PC.
16. The target address of a jump forward 1s a maxunum of _ _ _ __

SECTION 3.2: CALL INSTRUCTIONS


17. Why do we need subroutines? .. . . ,
18. Ln \Vhat way is the LCALL instruction different from an ACALL instruction.
-
19. The ACALL 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? . :w
I l
22. On returning from a subroutine, where will the next instruction be taken from?
23. Why do the PUSH and POP instructions in a subroutine need to be equal in number?
24. How is the stack used in the case of a CALL( ACALL or LCALL) instruction?
, 25. Show the stack for the following code:
OOOB 120300 LCALL DELAY
OOOE 80FO SJMP BACK
0010 ;keep doing this
OOlO; _ _ _ this is the delay subroutine
0300 ORG 300H
0300 DELAY:
0300 7DFF MOV RS,#OFFH ;Rs~2ss
0302 DDFE AGAIN: DJNZ RS,AGAIN ;stay h
0304 22 RET ere
;return
26. Reassemble Example 3-10 at ORG 200 (instead of ORC O) and show th
e stack frame for the first LCALL instruction.
SECTION 3.3: TIME DELAY FOR VARlOUS 8051 CHIPs
27. Find the system frequency of an 89CS1 if the machine cl . .
28. Find the machine cycle if the crystal frequency is ~ e peno<i IS 0.546 s_
29. Find the machine cycle if the crystal frequency is 18
12 MHz.
30. Find the machine cycle if the crystal frequency is 25 MHz:
31. True or false. L]MP and SJMP mstructions take the sam
instruction and the other is a 2-byte instruction. e amount of time to execute
even though one is a 3-byte
72
THE 8051 M}t"n
~ocoNTROLLE
R ANO EMBEDDED SYSTEMS
th t pecified in Problem 27.
. Find the delay with the following program for e sys em s
32
DELAY: MOV R2,#100
HERE: MOV R3,#255
AGAIN: DJNZ R3,AGAIN
DJNZ R2,HERE
RET h 8051 with frequency of 11.0592 MHz.
33. Find the time delay for the following delay subroutine, if the system as an
DELAY: MOV R3,#200
HERE: NOP
NOP
NOP
DJNZ R3,HERE
RET
34. Find the time delay generated by the following routine if the XTAL =22 MHz.
HERE: MOV R0,#200
AGAIN: DJNZ RO AGAIN
I

RET
35. Write a program to toggle all pins of Port 2 continuously with a delay of 1 second between the toggling XTAL =
22MHz.
36. Repeat problem 32 for DS89C420/30.
37. Repeat problem 33 for DS89C420/30.
38. Repeat problem 34 for DS89C420/30.
39. Repeat problem 35 for DS89C420/30.
40. In an AT89C51-based system, explain performance improvement if we replace the AT89C51 chip with a
DS89C420/30. Is it 12 times faster?

ANSWERS TO REVIEW QUESTIONS


SECTION 3.1: LOOP AND JUMP INSTRUCTIONS
1. Decrement and jump if not zero
2. True
3. 2
4. A
5. 3

SECTION 3.2: CALL INSTRUCTIONS


1. Long CALL and Absolute CALL
2. True
3. The address of where to return is in the stack.
4. Upon executing the RET instruction, the CPU pops off the to tw O b
register and starts to execute from this new location. p ytes of the stack into the program counter (PC)
5. 3

SECTION 3.3: TIME DELAY FOR VARIOUS 8051 CHIPS


1. True
2. 1
3. MUL and DIV each take 4 machine cycles.
4. 12 MHz I 12 = 1 MHz, and MC= 1/1 MHz= 1 s
5. [100(1 + 1 + 1 + 2)1 x 1 s = 500 s = 0.5 milliseconds
6. False. It takes l clock.
7. 11.0592 MHz/1 = 11.0592 MHz; machine cycle is l/l l.05 MHz_
92 - 0.0904 s =90.4 ns

-TUMP, LOOP, AND CALL INSTRUCTIONS


CHAPTER4

1/0 PORT
PROGRAMMING

OBJECTIVES

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

,,. List the 4 ports of the 8051


)> Describe the d ual role of port O in providing both data and addresses
)> Code Assembly language to use the ports for input or output
)> Explain the dual role of port Oand port 2
)> Code 8051 instructions for 1/0 handling
)> Code I/0 bit-manipulation programs for the 8051

..
' - .... 'I! - . l

75
In Section 4.1, we describe 1/0
examp Ies. d 1
. f the 8051 with ma11Y . discussed in eta1 .
This chapter describes the 1/0 ~ort p~ogramnung ~nipularion of the I/0 ports is
access using byte-size data, and tn Section 4.2, bit m

SECTION 4.1: 8051 1/0 PROGRAMMING . . re 4_1, note that of the 40 pins, a total
ations. Exarnirung Figu . Th rest of the pins are desig-
ln the 8051 there are a total of four ports for I/0 oper h ch port takes 8 pms. e
of 32 pins are set aside for the four ports PO, Pl, P2, and P3, w d~;~ are discussed in Chapter 8. 'I.
nated as VCC' GND, XTALl, XTAL2, RST, EA, ALE/PROG an
~
}
.
'
VO port pins and their functions . . -bit orts. All the ports upon RESET are co nfigured
The four ports PO, Pl, P2, and P3 each use 8 pins, makin? the~ 8 P t t becomes an output. To reconfigure it
as inputs, ready to be used as input ports. When the first Ois written to .a por '~rt it must be programmed, as we will
as an input, a 1 must be sent to the port. To use any of these ports as an mput P '
explain throughout this section. First, we describe each port.

Port 0
,_
. Port O occupies a total of 8.J?ins (pins 32 - 39). It can be used for .input or output. To u~e the p~_of port Oas both ,;,
1nput and output ports, each__in_must be connected externally to a 10K-ohrn_pull-U re~1stor:.: This 1s due to the fact
that PO is an open drain, unlike Pl, P2, ancl P3, as we will soon see. Open drain is a term used for MOS chips in the same -~It
iiJOl'
way that open collector is used for lTL chips. fu any system using the 8051/52 chip, we normally connect PO to pull-up
~ .
PDlP/Cerdip

Pl.0 1 40 cc
Pl.I 2 39 ~ \ ".: \ ,(>( 1
PO.O(ADO)
Pl.2 3 38 P0.1 (ADI}
'P "')..} "f
Pl.3 4 37
8051 P0.2 (AD2)
Pl.4 5 36
r..!ftlle
(8031) P0.3 (AD3)
Pl.5 6
Pl.6
Pl.7
7
8
(89420)
35
34
33
P0.4 (A04)
P0.5 (ADS)
P0.6 (AD6)
""'
~
RST 9
(RXD) P3.0
(TXD} PJ.1
10
11
32
31
P0.7 (AD7)
EA/vPP
1, b 4- 1,_,
(INTO} P3.2
30 ALE/PROG ,J...t/rcA'f
L 12
' ~:!>~
-~-
(INTI) P3.3 13
29 PSEN ltiaPort1 1
28 P2.7 (AlS}
1 (TO) P3.4 14
L
[
(Tl) P3.5
~)P3.6
(RD) P3.7
IS
16
17
27
26
25
P2.6 (A14)
P2.S (Al3)
P2.4 (A 12)
''
24
XTALl
GND
18
19
20
23
22
P2,3 (A 11)
P2.2 (AlO)
P2.1 (A9)
'
21
P2.0(A8) J
fjgure 4-1. 8051 Pin Diagro1m

76
THE 8051 MICRocoNT
ROLLER AND
EMBEDDED SYSTEMS
. 4-2 In this way we take ad vantage of Vee ~ --.--.-.-,-i-1 1~1~0 K
resistors. Seei'.guret and
ou tput. For example, the follow-
p ort Ofor bot mpu t O the altemat-
. ode will continuously send out to por
mg c AH ,
ing values of SSH and A O'o'',
;Toggle all bits of PO /".!'---..
BACK: [ MOV A, I/SSH ' Ll-+--+-++-t-t-C
PO.OC.J-4-4-t-t-it
MOV PO,A PO.l C~-L-+-+-t-11- ~... -
ACALL DELAY
8051 P0.2 L---l-+-t--t--i--::::
P0.3c=---~f--r-~
0

MOV A,IIOAAH
MOV PO , A P0.4L
P0.5c:___ -
_ -_
- -_
-_....-
__.. i ,-t
. l
.r " ;i ACALL DELAY P0.6L-- - - - - - -+--
1
~~9 P.- SJMP BACK P0.7
It must be n~ted th at complementing SSH (01010101)
turns it into AAH (10101010). By send ing SSH ~d AAH
to a given port continuously, we toggle all the bits of that
port. Figure 4. 2. Porto w ith Pull-Up Resistors

Port O as input 1 .
. the ort mus t be p rogrammed by writing 1 to all the
With resistors connected to p ort 0, m_order t~ make it ~ in put, b P r' tin ls to it, and then data is received from
bits. In the following code, port Ois configured first as an mput port Y w 1 g
that port and sent to Pl.
;Get a byte from PO and send it to Pl
l"1' '>J l"O ..._f'"" [ MOV A, #O FFH ; A = FF he x /..
MOV PO , A ;make PO an input port
;by writing all ls to it-
BACK: MOV A,PO ;get data f rom PO
MOV Pl , A ;send it to port 1,
SJMP BACK ;keep d o ing i t .

Dual role of port 0


As sho\vn in Figure 4-1, por_t Ojs also.designated a~ ADO - AD7, allowing it to be used for both address and d a ta.
When connecting an 8051 / 31 to an external memory, port O provides both address and data . The 8051 multiplexes
a ddress and d ata through port Oto save pins. We discuss that in Chapter 14.

../ Port 1
Port 1 occupies a total of~ pins (~ins ~ through 8). I!_can be used as input o r ou tput. In contrast to port o, this port
does not need an y pull-uf resistors ~tnce it.alread y has pull-up resistors internally. Upon reset, port 1 is configured as
an input port. The following code will con tinuously send out to port 1 the al ternating values SSH and AAH .

MOV A,#SSH
BACK: MOV Pl,A
ACALL DELAY
l CPL A ; complement(Invert) reg. A
SJMP BACK

Port 1 as input
. If port 1 has been configured as an output port, to make it an inpu t ort . .
it
mg_ 1 to all its bits. The reason for this is discussed in Appendix C.Z. th ~g~, ~t m ust progra ~ed as s uch by writ-
an input port by writing l s to it, then d ata is received from that port d e O 0 _
wmg code, port 1 15 configured first as
-
110 PORT PROGRAMMING
an saved m R7, R6, and RS.

'1'1
,
I
~ MOV A,#OFFH ;A=FF hex i'nput port.
MOV Pl.A k Pl
;ma e , . an 1s to it
by writing a 11
A,Pl ' e t data from Pl
MOV
;g
save it in reg R7
MOV R7,A
'
ACALL DELAY ;wait hr data from Pl
MOV A,Pl get anot e
MOV R6,A '
save 1tin reg R6
'
V ACALL DELAY
;wait from Pl
f MOV A,Pl get another data
~ MOV RS,A '.save it in reg RS
'

like Pl _Eort ~oes OQt


used as input or output. tJust . ' -d as an input
2 is configure_ .
PortPort
2 2 occupies a_ total o~ in,~~
( ins 21 thmugh 28). beH'"'
temally. Opon n,;et,
it al~ady has pull-up res1sto~;altemating values SSH an
po, d AAH. That ,s, all the b,o
port. anuull-~
need The followmgr~co o ew~ :send out continuously to port 2
of P2 toggle continuously. /

MOV A,#SSH
BACK: MOV P2 ,A
ACALL DELAY
CPL A ;complement reg. A
SJMP BACK

Port 2 as input writin 1 to ,u it,; bit,;. In the following ,ode, po,t 2 is ron-
To make
figured port
first as an input,
an 2input it mus_t
port by _program~e;:,:~s~~~
writing ls to . ~~ receivfd from that port and is sent to Pl continuously.

/ ;Get a byte from P2 and send it to Pl


MOV A,#OFFH ;A=FF hex
MOV P2,A ;make P2 an input port by
;writing all ls to it
BACK: MOV @) P2 ;get data from P2
MOV Pl,A ;send it to Port 1
SJMP BACK ;keep doing that

Dual role of portr'l'l2ov' ' ' .I p),.

ln many systems based on the 8051, ~2 is used, as simple 1/Q ~wevec, Ul 803l:based sysrell\S~Port 2 must f2t used
~oog with PO to ,1><0:ide the 16-b_it address fo, !"""''
memo,y. A, shown in Figu" 4-1, po, t 2 is also designated "
,;g.Ais,-ma;ca,ng ,s du.rfun<"oo. Smc, ao 8051/31 " capable o_f "'."'mg 64K byte, of external memo,y, it needs a
~
p,th fo. the 16 bit,; of the add,ess. Wrule PO p,os,de, the lowe, 8 b,t,; "" AO A7, it is the job of P2 to pmvide b;t,; A8
A15 of th, address. In Dtw '.
woros, who, th, 8051/31 '.'"''.'"ted e>tem,1memo,y, P2 is Used fo, the up pe, 8 bib
of the 16-bit address, and 1t cannot be used fort/~). Th1s 1s discussed 1n detail in Chapter _
From the discussion so far, we conclude that m systems based on 8751 89CS1 or 05 14 C4xo . tr we
have three
leaves port ports,.PO,
3 for mterrupts w asf/0
Pl, andasP2,el~r ~
o thope~ati~ns. Thiwe
er sign s, as s shoilluld
w seebe enough' for most
next. ' rnicrocontroUe
589 nucr
r app
ocon o ers,That
lications.
11

Port3

Port 3 occupies a totaJ of 8 pins, pins 10 through 17. Jt can be used as in t


resistors just as Pl and P2 did not. AJthou h confi ed as an input or ou tput. P3 does n ot need any pull-up

78 , u Ortu " <eset, thi, ;.notthew,y 11


THE 8051 MlCRocoNl'
ROLLER AND EMBEDnEo SYSTEMS
o!>I con1monly used. Port 3 has the additional function of provid- Table 4-1: Port 3 Alternate Functions
~g son1e extremely important signals su~ a~ interrupts. Tab~e 4-1 P3 Bit Function Pin
pro,ides these alternate functions of P3. This information appbes to 10
P3.0 RxD
both 8051 and 8031 chips. .
P3.0 and P3.1 are used for the RxD and TxD serial commun1ca- P3.1 TxD 11
tJoll!, signals. See Chapter 10 to see how they are connected. Bits INTO 12
P3.2 and P3.3 are set aside for external interrupts, and are discussed P3.2
1n Chapter 11. Bits P3.4 and P3.5 are used for timers O and 1, and P3.3 INTI 13
are discur,sed in Chapter 9 where timers are discussed. Finally, P3.6 TO 14
P3.4
and P3.7 are used to provide the WR and RD signals of external
memories connected in 8031-based systems. Chapter 14 discusses P3.5 Tl 15
ho~v they are used in 8031-based systems. In systems based on the P3.6 WR 16
8751, 89C51, or DS89C4x0, pins 3.6 and 3.7 are used for I/0 while
the rest of the pins in port 3 are normally used in the alternate func- P3.7 RD 17
tion role.

Example 4-1

Write a test program for the DS89C420/30 chip to toggle all the bits of PO, Pl, and P2 every 1/ 4 of a second .
Assume a crystal frequency of 11.0592 MHz.

Solution:

;Tested for t he DS89C4 20/30 with XTAL 11 . 0592 MHz .

ORG 0
BACK: MOV A, #SSH
MOV PO, A
MOV Pl, A
MOV P2, A
ACALL QSDELAY ,Quarter of a econd delay
MOV A,IOAU
MOV PO, A
MOV Pl,A
MOV P2,A
ACALL QSDV~Y
SJMP BACX

; - - -----------1/4 SEcoal)
QSDELAY:
MOV RS, tfi
H3: MOV
H2:
Rt.
MOV D,IIID
Hl: DJNZ Rl,._
oowz R4,
DJNZ R5,
RBT
END

Delay 11 >< 248 >< 255 x 4 MC

Uo PORT PROGRAMMING
/ . Reset Value of Some
Table 4-2,
f ccessing the entire
s
bits
he entire 8051 Ports
Reset Value (BinaryI
-
Different ways o a . 1/ 0 examples, t
. many previous
In the following code, as in
f p> -
Register 111111U
-
8 bits of port I are accessed. ,/
v -
l'O
11111111
I:
BACK: HOV
MOV
A,#SSH
Pl,A . ('~ -1'2
J'l
11111111
I
ACALL DELAY
HOV A,#OAAH (lcJ
f.>! -P3 IJ ll llll

MOV Pl, A

ACALL DELAY bo e program before. Now


SJMP BACK seen a variation of the a ~out going through the
The above code toggles every bit of Pl co~. uo a~er by accessir1g the port dlrectly w1
tin usJy ~Ve have
we can re\,,rite the above code in a more effictent m
accumulator. This is shown next.

BACK: MOV Pl,#SSH


ACALL DELAY
MOV Pl, ijOAAH
ACALL DELAY
SJMP BACK
The following is another way of doing the same thing.
MOV A,#SSH ;A=SS HEX
BACK: MOV Pl,A
ACALL DELAY
CPL A ; complement reg. A
SJMP BACK

We can write another variation of the above code by using a technique called read-modify-write. This is sho,vn at the
end of this chapter.

Ports status upon reset


Upon re$<?! all ports have value PFH on them as shown in Table 4-2. This makes them input ports upon reset.

Review Questions
I. There are a total of Y ports in the 8051 and each has .o~~ bits.
2. True or false. AU of the 8051 ports can be used for both input and output. \/
3. Which 8051 ports need pull-up resistors to function as an 1/0 port?~ Pe
4. True or false. Upon power-up, the 1/0 pins are configured as output ports. F-
5. Show simple statemC(ltS to send 99H to ports Pl and P2. ""IS r, , ..._ 9c, !-4
I

Y'l\11~ <> ' A


/
efECTlON 4.2: VO BIT MANIPULATION PROGRAMMING "' , " ~ ~~
In this section we further examine 8051 1/0 instructions. We pay spec:; l .
isa powerful and widely used feature of the SOSl family. ,a attention to 1/0 bit manipulation since it

VO ports and bltaddressablllty


Somebmes we need to access only l or 2 bits of the port instead f .
1/0 ports is their capability to access individual bits of the port With O the entire 8 bits. A pownrful f tu f onc51
'the th . out alterln th
four 8051 ports, we can access e1 r e entire 8 bits or any single bit . ~,g e rest of the bits in th< ea re OOfau.the
in sll\gle-bit manner, we use the synt.1x "SETB . Y" where Xis th without altering the rest w.. . . at ~rt.
e port "Ulllber O 1 2, """"' accessing port
80 l,,, f ' ' or 3, and Y is the desired bit
Table 4-3: Single-Bit Addressability
number from Oto 7 for data bits DO to 07. For example, "SETB P_l 5"
sets high bit 5 of port 1. Remember that DO is the LSB an~ D7 is the of Ports Port Bit
MSBJor example, the follo~5 ode to9g~es bit Pl.2 continuously. PO P2 P3
P1
P2.0 P3.0 DO
P0.0 Pl.0
~ ACK: CPL Pl.2 ;complement Pl.2 only P3.1 Dl
PO.I Pl.l P2.l
ACALL DELAY
SJMP BACK P2.2 P3.2 D2
P0.2 Pl.2
P3.3 03
;another variation of the above program follows P0.3 Pl.3 P2.3
AGAIN: SETB Pl.2 ;change only Pl.2=high 04
Pl.4 P2.4 P3.4
ACALL DELAY P0.4
;change only Pl.2=low P2.5 P3.5 D5
CLR Pl.2 P0.5 Pl.5
ACALL DELAY P2.6 P3.6 D6
P0.6 Pl.6
SJMP AGAIN 07
P0.7 Pl.7 P2.7 P3.7
Notice that P1.2 is the third bit of P1, since the first bit is P1 .0, the sec-
ond bit is Pl.1, and so on. Table 4-3 shows the bits of the 80511/0 ports.
See Example 4-2 for an exan1ple of bit manipulation of 1/0 bits. Notice in Example 4-2 that unused portions of ports 1 and 2
are undisturbed. This single-bit addressability of I/0 ports is one of most powerful features of the 8051 microcontroller ai1d is
among the reasons that many designers choose the 8051 over other microcontrollers. We will see the use of the bit-addressability
of 1/ 0 ports in future chapters.
Table 4-4 lists the single-bit instructions for the 8051. We will see the use of these instructions throughout future
chapters.

Example4-2
Write the following programs.
(a) Create a square wp.ve of 50/o duty cycle on bit Oof port 1.
(b) Create a square wave of 66/o duty cycle on bit 3 of port 1.

Solution:
(a) The 50o/o duty cycle means that the "on" and "off" states (or the hi h d l
same length. Therefore, we toggle Pl Owith a time delay ;"... between
g anchow portions of the pulse) have the
ea state.

HERE: SETB Pl. O ;set to high bit o of port 1


LCALL DELAY ;call the delay subroutine
CLR Pl . O ;Pl.OcO
LCALL DELAY
SJMP HERE ;keep doing i t

Another way to write the above program is:

HERE: CPL Pl .O ; complement bit o of po rt 1


LCALL DELAY ; call the delay subroutine
SJMP HERE ;keep doing it

8051

Pl.O i,.....-
l J
.
-1/Q PORT PROGRAMMING
.- ,

81
" f(" state.
.
cethe o
th "on" state tS twl
(b) The 66% duty cycle means e . h
bit 3 hl9 .
BACK: SSTB Pl. 3 set port 1 broutine n
LCALL DELAY '.call the delaY s::i,routine aga>
t.Cill,L DELAY '.call the delay 5 1(Pl.JslOW)
2 of port
CLR Pl.3 :clear bit ubroutioe
LCALL DELAY call the delays
SJMP BACK ; keep doing it

8051

Pl.3 ..__
_ J ~ - - 11 L-___.r

I Table 4-4: Single-Bit Instructions


Instruction Function
SETB bit Set Lhe bit (bit - l )
CLR bit Clear the bit (bit - 0)
CPL bit Complement the bit (bit - NOT b it)
JB bit,target Jump to target ii bit : I fj ump if bit)
) NB b it,target Jump to target if bit : 0 fj ump if no b it)
? JBC bit,target Jump to target if bit: l, clear bit Gump if bit, then .s.J"Wr)
'

&amplt4-3
Write a program to perform the following
(a) keep monitoring pin P0.1 until it becomes high
(b) when P0.1 becomes high, read in the data from port 1
(c) send a low-to-high pulse on P0.2 to indicate that the data has been read
Solution:
SETB PO.l
MOV Pl, JOPFH :make Po.2 an input
AGAIN: JNB PO .1, AGAIN ;make Pl an nput
;check if PO 1 . port
MOV A, Pl
if . 18 high if
CLR P0.2 ; Po .1 1 8 found hi not, keep checking
SETS P0.2 ,clear Po.2 9h, take in data froaa Pl
:set Po .2
Tius type of a program is required to read m data from
(mdicated by showing a high on P0.2 here). Note that: A to D COflverte, after .
programmed as such by writing ls to it. mal(e Ports or Uldi . venfyinglflheconveslianll
VJduat l)Clrt lines to 9Ct lapu\ It

82
/
Checking an input bit
The JNB Gump if no bit) and JB Gump if bit = 1) instructions are also w idely used single-bit operations. They all.ow
Y'" to mocitor a bit and make a decis;on depending on whether it is Oor I. Instructions JNBand ]B can be used for any
bits of I/ 0 ports 0, l, 2, and 3, since all ports are bit-addressable. H owever, m ost of port 3 is used for interrupts and
serial communication signals, and typicaUy is not used for any I/0 , either s ingle-bit or byte-wise. This is discussed in
Chapters 10 and 11. Table 4-5 shows a list of instructions for read ing the ports.

Table 4-5: Instructions For Reading an Input Port


Description
Mnemonic Example
Bring into A the data a t P2 pins
MOV A, PX MOV A, P2
Jump if pin P2.l is low
JNB PX . y I
JNB P2 . 1 , TARGET
Jump if pin Pl .2 is high
JB PX. Y, .. JB Pl . 3 , TARGET
Copy s ta tus of pin P2.4 to CY
MOV C, PX . y MOV C, P2.4

Example 4-4
Asswne that
Monitor the bit P2.3 is an input
bitcontinuously and epr~~ ts t h ';;nd.it~n
When: . ~ ~
. goes high, it means that the oven is hot.
an oven. If it
Solution: . ver i goes g 'sen a high-to-lo\v pulse to port Pl.5 to tum on a buzzer.

HERE : JNB P2 .3,HERE ;keep monitor ing for high


SETB Pl.5 ;set bit Pl.5=1
CLR Pl .5 ;make high-to-low
SJMP HERE ;keep repeating
vcc

~
J
S,vttch 8051

P2.3
....
4.7k ~ ~ B~r

Pl.5 --'0....._
1-----ll/)O--
V 74LS04
V

Example 4-5
A switch is connected to pin Pl .7. wr1te a p rogram to check
(a) If SW=O, send letter 'N' to P2 the s tatus of SW and ri
(b) lfSW=l, send letter 'Y' to P2. pe orm the following:
Solutjon: p,.'1- o_ ...._ j4
SETB Pl.7 ;make Pl.7 an i 'f
AGAIN: JB Pl.-:,, OVER ;jump if nput
Pl.7:1
MOV P2,#'N' , SWcO ' issue
'N'
SJMP AGAIN ;keep monitoring to P2
OVER: MOV P2,#'Y' ;SWl , is sue y,
SJMP AGAIN ke to P2
' ep monitoring

-
1/Q PORT PROGRAMMING
83
( EJcimpl 4-6 . a rogram tocheek the statuSed toopin pJ.7.
. 11.!ld perform the following:
f the s,\lttch
ected to port pin P0.1. Wnte p . siren connect
A ,witch is conn I pulse to acttvate a
da h1gh-~ow
() If switch 1, sen the pin status
(b) Conbnue monitonng

U,e the carry Ong to check the switch status.

Solution:
n input . ato carry Jlag 1 t
SETB PO.l make PO, l a f PO. l 1
MOV C,PO.l contents o . ue t. 0 -onitor
m
AGAIN: ;read the h "gh cont in Pl 7
JNC AGAIN ; if PO .1 ~s nh?gth i se~d a high tolse. on Pl. 7
SETB Pl. 7 if PO.l i s i . ' a H-to-L pu
CLR Pl. 7 ~send low now: i.~~~ the pin status
SJMP AGAIN ;continue monitori

~
t, p:'AE~x;a;m;p;1.;~;7~~~;-:::--::;::
switch lS connected to pm
:--;;;~:;;:;;LE1Jt;;--;;;;;i;;:;~~-;;;;;;;:ram:;;~~ge~t~thhe;s;t;a;tus~o~f~thhe;;;sw:;;itc~h~a;n~d~se;;,;n~d
. Pl .Oand an LED to pm P2.7. Wnte a prog ' 10
1t to the LED.

Solution:
SBTB Pl . 7 ;make Pl.7 an input
AGAIN: MOV C,Pl.0 :read the sw status into CF
MOV P2.7,C ,send the sw status to LED
SJMP AGArN ;keep re~ating
Note: The instruction "MOV P2. 7, Pl. o" is wrong since such an instruction does not exist. owever,
Pl" 1~ a valid instruction. H "MOV P2 ,

Reading a single bit into the carry flag

tion We canC,
"MOV alsoPx
use the carry flag to save or examine the status or a single bit of the port. To do that, we use the instruc-
. y" as shown in Examples 4-6 and 4-7.
Notice in Examples 4-6 and 4-7 how the carry flag is us! to get a bit of data from the port.

Reading input pins vs. port latch

In reading a port, some instructions read the status of port pins while others read th tatu f . I I tch
Therefore, When reading ports there are two possibilities: es so an m tema port a
I. Read the status of the input pin.
2. Read the internal latch of the output port.

We must make a distinction between these two categories of instru . .


source of errors in 8051 progYamming, especially where external h.1.rd ctions smce confusion between them is a major
briefly_However, reade_rs must study and understand the material : : : 1~ c~ncerned. We diseuss these instructions
that is given In Appendix C.2. 0 op,c and on the internal working of ports

84
THE sos1 MJCRocoN'f
ROLLER AND EMBEDDED SYSTEMS
Table 4-6: Instructions Reading a Latch
structions for reading input ports (Read-Modify-Write)
In . t
As stated earlier, to make any bit of any. 8051 port an in~u- Example
Mnem onic
t we must write 1 (logic high) to that bit. After we co~ g ANL Pl,A
~;; ;he port bits as input, we can use only certain '.11s~ct1ons ANL PX
. order to get the external data present a t the pins in to the ORL P2,A
ORL PX
~PU. Table -!-6 shows the list of such instructions. XRL PO,A
XRL PX
JBC Pl.l,TARGET
JBC PX.Y,TARGET
Reading latch for output port
CPL Pl.2
Some instructions read the contents of an inte rnal port CPL PX.Y
latch instead of reading the status of a n external pin. Table 4-6 INC Pl
INC Px
provides a list of these instructions. For example, look a t the DEC P2
"ANL Pl, A" instruction. The sequence of actions ta ken whe n DEC PX
such an instruction is executed is as follows. DJNZ PX . Y,TARGET OJNZ Pl,TARGET
MOV PX . Y,C MOV Pl.2 , C
1. The instruction reads the inte rnal la tch of the port and
bri.ngs that da ta into the CPU. CLR PX . Y CLR P2 . 3
2. This data is ANDed with the conten ts of register A. SETB PX. Y SETB P2 . 3
3. The result is rewritten back to the port la tch. Note: ,: is 0, I, 2, or 3 for PO - P3.
4. The port pin data is changed and now has the same value
as the port latch.
From the above discussion, we concl ude tha t the instructions tha t read the po rt latch n ormally read a v alue, perform
an operation (and possibly change it), then rewrite it back to the port la tch . This is often caUed "Read-M odift1-Write" .

~ Read-modify-write

feature
The ports in the 80ql can be accessed by the read-mod ify-wri te technique. This fea ture saves many lines of code by
combining in a single instruction all three actions of (1) reiiding the port, (2) m odifying its value, and (3) writing to the
port. The following code first p laces 010101Ql (binary) into p ort 1, Next,, the instruction "XLR Pl , # OF FH" performs an
XOR logic operation on Pl with 11111111 (binary), and then.writes th.e res4Jt back into Pl.
MOV Pl ,#SSH ;Pl= 0101010 1
A.GAIN: XLR Pl,#OFFH ; EX-OR Pl with 1 1111111
ACALL DELAY
SJMP AGAIN

Notice that the XOR of SSH and FFH gives AAH. Likewise, the XOR of AAH and FFH gi ves SSH L
are discussed in Ch a pte r 6. ogic instructions

Review Questions
1. True or false. The instn1ction "SETS P2 . l " makes pin P2 l high while le h . ~-
2. Sho,,.., one way to toggle the pin Pl.7 continuously using 8051 instru t avmg ot e r bits of P2 unchanged.
3 U . th . . " " c ions. t
s~g. e tns~uction JNB P2 . 5 , HERE assumes that bit P2.S is an I l/.
4. Wr'.te instructions to get the s tatus of P2.7 and put it on p 2.o. (input, o utp ut). 70
5. Write instructions to toggle both bits of Pl .7 and Pl.0 continuo usly. v'

CAUTION '
We strongly recommend that you stud y Section C.2 (Ap e d 1' .
to your 8051 sys tem. Failure to use the right instruction 0 ~ t::e
~ C) if you ~e connecting any e xternal hardware
of your 8051 system. right connection to p ort p ins can damage the ports
-
Pl P2 and P3, each use 8 pins
SUMMARY f p<>rts of the S05L Po, -~-' f~r either address or data'
8051. The our can be usev .
This chapter focused on the J/0 parts of the . t or output. Port O !/O instructions of the 8051 were
be used for inpu . J '[hen
mal<ing them 8-bit parts. These ports can . IJUT\unication s1gna s. b'lity of the 8051 ports.
Port 3 can be used to provide interrupt ru_>d scna1 co showed the bit-add.ressa ,
e,plained, and numerous examples were g,ven. We also

PROBLEMS
SECTION 4.1: 8051 1/0 PROGRAMMING I and_.=::::\::.:--
I. The crystal for the oscillator of the chip is to be connected to pinS _ _::.'---
r
2. 1'.'hich pins are assigned lo VCl: and GND? , ... I -d <-I'
3. Whal is tlie dual role of port 2? l.ll<....I ~.,,.. ,... . th DIP ackage?
4 How many pins are designated as PO and which number are they in e DIP p ka e? I
s:
How many pins are designated as Pl and which number are they!" the
6. How many pins are designated as P2 and which number are they '.n the DIP pac age?
pack g ;

7. How many pins are designated as P3 and which number are they ,~e DIP package
8. Upon RESET, all the bits of ports are configured as (input, output).
9. Why does port Oneed pull up resistors?
IO. Which port of the 8051 does not have any alternate function and can be used solely for 1/0?
'1 I. Write a program to gel 8-bil data from Pl and send it to parts PO, 1'2, and 1'3.
12. Wr,tea program to get 8-bit data from P2 and send ii to ports PO and Pl.
13. Which pins of port 3 cater to interrupts?
1-1. Write a program to output 00 on port 0, OFH on port 1, FOH on port 2, and FFH on port 3.
/ JS. Write . program to toggle aU the bits of Pl and P2 continuously (a) using AAH and SSH (b) using the CPL
tnStruction.

SECTION 4.2: 1/0 BIT MANIPULATION PROGRAMMING


16. Which ports of the 8051 are bit-addressable? ~
17. What is the advantage of bit-addressability for 8051 ports?
18. When .Pl ,s accessed as a single-bit port, it is designated as
19. What IS the error II\ the following code? ----
MOV Pl, #OFH
CPL Pl
20. Write a program to take in data through P1 0 and sen .
21. Write a program to toggle Pl 3 Pl 7 and 1'2. S . d ,1 out through P2.7.
22. w conllnuousl 'th .
W~tea program lo monitor bit Pl.3. When ii is hlgh se d ~;~ out d,sturbing the rl'st of the bits
23. nle a program to monitor the P2.7 bit. When it is 1' w n to P2. .
24. Wnte a program to monitor the P2.0 bit. When it is I~ send SSH and AAH to PO con tin
25. Wnte a program to monitor the Pl 5 b't Wh . ugh, send 99H to Pi If 11. I uously .
. /26
.
wn1ea program to get the status or Pl.3
'
a d
en 11 is high
. k is ow send 66H
ma c a low-to-high t I to p 1.
27. A switch SW is connected to pin Pl 4 W . n put ,1 on Pl .4. - o- ow pulse on Pl.3.
SW;J. . . nteaprogramiooutputOOon .
28. Writea program to generate a square wa,e of 25% d portt 1ISW:O'and output FFH on port 1 ii
uty cycle on pin P2.3.

ANSWERS TO REVIEW QUESTIONS


SECTION 4.1: 8051 1/0 PROCRAMMJNG
I. 4, 8.
2. True
3. PO
4. False
5. MOV Pl,#99H
MOVP2,#99H

SECTION 4.2: 1/ 0 BIT MANIPULATION PROGRA.MMJNG

]. True /
2. Hl: CPL Pl.7
SJMP Hl
3. Input
4. MOV C,P2.7
MOV P2.0,C
5. Hl: CPL Pl.7
CPLPl.O
SJMPHl

,- .. """c\J 1l\ it: C>~ ~ H


,)

\oc::I.C...'L. ~

f'(' t>" ,.. .) Pl


r,'t~ '('(\ 6 -.J Po> A
w,.i:.\J Pl.) -tt.
m,v P~J~
~'3 ~ f.> b "-C..V.

-110 PORT PR.OCllAMMING


CHAPTERS

8051 ADDRESSING MODES

OBJECTIVES

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

> List the five addressing modes of the 8051 rnicrocontroller


> Contrast and compare the addressing modes
> Code 8051 Assembly language instructions using each addressing mode
> Access RAM using various addressing modes
> List the SFR {special function registers} addresses
> Discuss how to access the SFR
> Manipulate the stack using direct addressing mode
> Code 8051 instructions to manipulate a look-up table
> Access RAM, 1/0, and ports using bit addresses
> Discuss how to access the extra 128 bytes of RAM space in the 8052
r be provided as an immediate
. .,,; ter or in rnernor}', ~e discuss 8051/52 addressing
d ta ould be t11 a r,.,..5 ',_ this chapter
u data in various ways. The a c d 11 ru modes, u,
The CPThcan ace~55 "ays of accessing data are called ad ress " d . aned and therefore cannot be
value. ese vanous "
modes in the context or some examples. .
h it JS
sor are determined w ~ . modes. They are as o ows.
f U es,.,.. '
.
The various addressing modes of a llU~oproces J of five distinct addresstllg
changed by the programmer. The 8051 provides a tota

, / l. immediate
( 2. register
3. direct
./ 4. register indirect
. / S. indexed . memory using
" n 5 2 we cover accessmg .
. dd modes In SeCuO bil f RAM
lnSectionS.I we look at immediate and register a resst11g . discusses the bit-addressa ,ty O
3 , reg,s-
5
the direct, register indirect, and indexed addressing modes. Sect1onl2S b tes of RAM in the 8052.
ters, and 1/ 0 ports. ln Section 5.4 we show how to access the extra Y

SECTION 5.1: IMMEDIATE AND REGISTER ADDRESSING MODES


In this section first we examine immediate addressing mode and then register addressing mode.
'
I u" ,...J - ... " t . . """" It' '
(
i ""' ( L.~ C

~ Immediate addressing mode It i S fl !1111111


In this addressing mode, the source operand is a i;gnst~t. In immediate addressing mode, as the name implies,
when the instruction is assembled, the operand comes immediately after the opcode. Notice that the immediate data
must be preceded by the pound sign, #". This addressing mode can be used to load information into any of the regis-
ters, including the DPTR N?gister. Examples follow.
! .t
c,
I lio1
I J.,r1
MOV A,#25H ; load 25H into A i iltl
MOV R4,#62 ; load the decimal value 62 into R4
MOV 8,#40H I ;load 40H into B
MOV DPTR,#4521H ;DPTR4Sl2H _.., ff,. I,, J :l / : ,SJ .3 (,

-
. ~though the DPTR register \s 16-bit, it can also be accessed
high yte and DPL is the low byte. Look at the following coae. as two 8-bit reers, ~and DPL, where OPH is the

MOV DPTR, #25;H


is the same as;
-
MOV DPL,o50H
MOV DPH, #3SH

Also notice that the following would produ .


ce an error sance the value.IS Iarger than
16 b'
MOV DPTR, #68975. illegal!' l its.
' - ' v ~ > 65535 (PFFFFH)
We can use the EQU directive to access immedi t d -
a e ata as shown bel
COUNT 'OU- J.o ) ow
.._ 1
~
MOV R4,#COUNT
MOV DPTR, #MYDATA

ORG 200H
HYDATA: 08 America

. Notice that we can also use immediate dd .


JS a valid instruction. a ressang mode to send d
ata tosos1
90 ports. For example, "Mov Pl tssll"

THE 80S1 l\.11c1toc


ONTROttER "
ANO EMBEDDED SYSTEMS
We.....1) ~
.~, 'TO -, ,~ 1~
\l e! .. ~ .. ,. ~ 1
1
" 1J , h,1 t ) t ( ;JV
Register addressing mode - ( . h ld the d a ta to be manipulated. Examples o f registe r
J I the use of registers to o
Register addressing mode invo ves
add ressing mode follow. .
MOV A,RO ;copy the contents of RO . i nto~
MOV R2,A ;copy the contents o f A i nto Rten t s of A
add the contents of RS to con
ADD A,RS , t nt s of A
ADD A,R7 ;add the cont ents ~f R7 t o cone
MOV R6 , A ; save accumula tor i n R6 . d d ' g " MOV DPTR, A"
. . . must match in size. In other wor s, co m .
It should be noted that thesour~e and de~tina~on re~t:: destination is a 16-bit register. See the folJowmg.
will give an error, since th e source 1s an 8-b1t register an

MOV DPTR, #25[2.H r- H


MOV R7,DPL 'l=-o
MOV R6 , DPH - ., :> S H Rn
Notice that we can move data between the accumulator an d . ~r n -: Rn (f - 0 to 7) but m ovement of d a ta betw een
th ti "MOV R4 R7" 15 invalid.
registers is not allowed. For example, e mstruc on 'th ' . 'd of the registers or tagged alon g w ith the
1J1 the firs t two addressing modes, the operands are ei .er
51
.e one f
instruction itself. In most programs, the data to be processed 1s o ten m some 1:11emo
ry location o f RAM o r in the code
. d
space of ROM. There are many ways to access this d ata. The next section describes these different m etho s .
...
>( (. V' ": )
,r\<,J ~ JI ,i(\_"'}:.
Review Problems ,,,.
1. Can the programmer of a microcontroller make up new addres~ing modes? N"0
2. Show the instruction to load .1000 0000 (binary) into R3. I l,.. o 1)1"' f. i ; 1 g 1,;+ .
3. Why is the following invalid? "MOV R2, DPTR" 0 P7 ll ,.J , 6 ~ ~ d . _
4. True or false. DPTR is a 16-bit register tha t is also accessible in low-byte and high -byte formats. I
5. Is the PC (program counter) also available in low-byte and high-byte formats? NO
~..k ]>P'rf? ~ ~M
SECTION 5.2: ACCESSING MEMORY USING VARIOUS ADDRESSING MODES
We can use direct or register indirect add ressing modes to access data s tored either in RAM or registers of the 8051.
This topic will be discussed thoroughly in this section. We will also s how how to access on-chip ROM containing d ata
using indexed addressing mode.

/ Direct addressing mode


As mentioned in Chapter 2, there are 128 by tes of RAM in the 8051. The RAM has been assigned dd 00 t 0
7FH. The following is a summary of the allocation of ffiese 128 byEes. a resses

1. RAM locations 00 - l FH are assigned to the register banks and stack.


2. RAM locations 20 - 2FH are set aside as bit-addressable space to save single-b 1't d a ta. This 1s discussed m
. Sectio
. n53
3. RAM locations 30 - 7FH are available as a place to save byte-sized data.

Although the entire 128 bytes of RAM can be accessed usin direct ddr . .
RAM locations 30 - 7FH. This is due to the fact that register baiJl . a ess mg m od e, it is most often used to access
but there is no such name for other RAM locations. In th d ' oca~ns ar~ accessed by the registe r names of RO- R7,
location whose address is known, an d this add ress is give e irect a dress~g mod.e, the data is in a RAM memory
addressing mode, in which the operand itself is provided;.:~ ~p~rt of th~ instruction . Contrast this w ith immediate
two modes. See the examples below, and note the absence 0 ; the '~#~:~tion . The "#" sign dis tinguishes between the
MOV R0 ,4 0H ;save c ontent of RAM l ocation 40 .
MOV 56H,A ;save content of A in .Hin RO
MOV R4, 7FH ;move contents of RAM~ l?cation 56H
ocation 7 FH to R4
-
S0s1 ADDRESSING MODES
91
1nese registers can be accesse(f
oo.
o..-isterS " R7-
ed to bank '-.,
oto 7 are aUocat
As d,scussc.-d earUcr, RAM locations
,n two ways, as shown below.
MOV A,4 ;is same as
copy R4 inCO A
MOV A, R4 which means
MOV A, 1 ;is same as
MOV A,R7 ;which means copy R1 into A
MOV A,2 ; is the same as
MOV A,R2 ;which means copy R2 into A
MOV A, o ;is the same as . .
MOV A, RO ;which means copy RO into A . nstructions. See the followmgcode.
The above examples should reinforce the importance 0 f the "#" sign Ill 8051 ,

MOV R2,#5 ;R2 with value 5


MOV A,2 ;copy R2 to A (A R2=05)
MOV 8,2 ;copy R2 to B (B=R205}
MOV 7,2 ;copy R2 to R1
since Mov R7, R2" is invalid
' dd
Although it is easier to use the names RO - R7 than their memory a resses,
RAM locations 30H to 7FH cannot be
accessed in any way other than by their addresses since they have no names.

SFR registers and their addresses


Among the registers we have disrussed so far, we ha,e seen that RO - R7 are part of the 128 by tes of RAM memory.
What about registers A, 8, PSW, and DPTR? Do they also have addresses? The answer is yes. In the 8051, registers A, 8,
PSW, and DPTR are part of the group of registers oommonly referred to asSFR (special function registers). There are many
special function registers and they are widely used, as we will discuss in fu ture chapters. The SFR can be accessed by their
names (which is much easier) or by their addresses. For example, register A has address EOH, and registc:,r B has been des-
ignated Uie address FOH, as shown in Table 5-1. Notice how the following pairs of instructions mean the same thing.
MOV ~ - #SSH ; is the same as
MOV~#SSH ;which means load SSH into A (A=SSH)
MOV OFOH,ij2SH ;is the same as
MOV B.~25H ;which means load 25H into B (B25H )
MOV O&OH,R2 ; is the same as
MOV A,R2 ;which means copy R2 into A
MOV OPOH ,RO ; ie the same as
MOV B, RO :which means copy RO into 8
MOV Pl , A ;is the same as
MOV 90H,A ;which means copy reg A to Pl
Table 5-1 Lists the 8051 P.ecial function registers (SFR)
noted about the SFR addresses. and their addresses. The foll .
owmg two points should be
1. The special function registers have addresses b tw
addresses 00 to 7FH are addresses of RAM mcm~ ':'!'\flH and FFH. These add
2. Not all the address space o( 80 to FF is used b thry UtS c the 8051. l"eS.'leS are above 80H, since the
not be used by the 8051 programmer. y e SFR. The unused locations
80
H to FFH are l'eSel"ved and must
Regarding direct addressing mode, notice the f II .
00 - FFH, which means this addressing mode is lm::t:ving two points: (a) th
8051. (b) if you examine the 1st file for an Assembly I to accessing RAM I e ddress value is lim .led b.-
! 0 0
replaced with their addresses as listed in Table S-I. anguage program, you 1lons and registers toe' ..:, ~d 1..;:
,11see that ,.__ a,...., ln5l e ..,..
u.., SFR r e ~ names are
92

OCoNTRottER AND -
f!M8mD1D SWiiMS
. I Function Register (SFR) Addresses
Table 5-1: 8051 S pecta Address
OEOH
OFOH
} B register QDOH
8
PSW Program status word
81H
SP Stack pointer
DPTR Data pointer 2 bytes 82H
OPPIL~~~====~~L~ow~bfy~te~~~~~~~~~~~~~S:8331H=.-~
DPH High byte 80H
po r'"'""' PortO
90H
P1 Port 1
OAOH
p2 Port 2
OBOH -
P3" / Port 3
088H
w Interrupt priority control
ffi Interrupt enable control OA8H
TMOO Timer/counter mode control 89H
Timer/counter control 88H
T2CON" TLIDer / counter 2 control OCSH
T2MOO TLIDer/counter mode control OC9H
THO Timer/counter Ohigh byte SCH
TLO Timer/counter O low byte BAH
THl Tuner/ counter 1 high byte SDH
Tll Timer/counter 1 low byte 88H
TH2 TimerI counter 2 high byte OCDH
TL2 TimerI counter 2 low byte OCCH
RCAP2H T /C 2 capture register high byte OCBH
RCAP2L TIC 2 capture register low byte OCAH
SCON Serial control 98H
SBUF Serial data buffer 99H
PCON Power control 87H
Bit-addressable

Example 5-1

Write code to send SSH to ports Pl and P2, using (a) their names, (b) their addresses.
Solution:
(a) MOV A, #SSH ; A=SSH
MOV Pl, A ;Pl =SSH
MOV P2 , A ;P2=5SH
(b) From Table 5-1 , Pl address = 90H; P2 address = AOH
MOV A, #SSH ; ASSH
MOV 90H , A ; Pl S SH
MOV OAOH , A ;P2SSH

-
80s1 ADDRESSING MODES
93
( th registers ,
B RO and Rl, of bank I
'

Sol lion: . does not create a conflicr


u stacJ<~bon
On rese~ the stack pointer is initialized to (17. cl< location is 40H and the
Let us now anitialire it to 3FH so that the first sta
w,th bank I registers.

MOV SP, #3FH ; SP=lFH stack top


PUSH 00 push RO of bank Oto ck
PUSH 01 '.push Rl of banko to st:
PUSH OEOH ; push A registerto scac. RSO bit ; of PSW ( PSW. 1) = l
SETS PSW.l
. h to bank l
;SW1tC
by making .
k t p to B register
POP OPOH ;pop the content of stack t~p co Rl of bank l
POP 09 ;pop the content of stac top to RO of bank 1
POP 08 ;pop the content of stack

. ters RO and Rl are transferred to bank 1


Now we have the content ol A in B, and the contents of bank O reg)S
registers RO and RI.
-

Stack and direct addressing mode


Another major use ol direct addressing mode is the stack. In the 8051 family, only direct addressing mode is
allowed for pushing onto the stack. Therefore, an instruction such as "PUSH A" is invaUd. Pushing the accumulator
onto the stack must be coded as "PUSH OEOH" where OEOH is the address of register A. Similarly, pushing R3 of bank 0
is coded as "PUSH OJ". Direct addressing mode must be used for the POP instruction as weU. For example, "POP 04
wiU pop the top ol the stack into R4 of bank O.

, Register indirect addressing mode


Jn the register indirect addressing mode, a register is used as a pointer to the da [f - . .
registers RO and RI are used for this purpose_ ln other words R2. R b ta. the data 1s lllS1de the CPU, only
7
located in RAM when using this addressing mode. When RO and RJ :nnot e Used .to hold the address of an operand
addresses ol RAM locations, they must be preceded by the ..,,,.. - ehused as pomters, that is, when they hold the
"' sign, ass own below.
HOV A,eRo
;~~e con~ents of RAM location whose
;a resa 1s held by RO into A
MOV <tRl,B
;move contents of B into RAM loca .
;whoae addreaa is held by Rl tion

Notice that RO (as well as Rl) is preceded by the"@" -


as an instruction moving the contents of register RO t s,gn. ln the absence of the"@" -
0
to by RO. A, tnstead of the conte ts f s ,gn, MOV wiU be interpreted
n
the memory location pointed
Advantage of register indirect addressing mode
One of the advantages of register indire,:t address-
static as in the case of direct addressing mode Exa ng mode is that it rnak
mp1e 5-3 sho es accessin d
ws two cases of . g ata dynamic rather than
copyll\g SSH into RAM locations
THE 805t MICRocoNTR
OLLER AND EMBEDDED SYSTEMS
40H to 45H. Notice in solution (b) that the<e " e two instTuctions that "e <epeated numerous times. We can create
a loop with those two u>Strnctions as shown in solution (c). Solution (c) is the most effident and is possible only
because of ,egister indirect add,essing mode. Looping is not possible in di<ect addcessing mode. This is the main
difference between the direct and register indirect add ressing mod es.

An.
./ .....
Example 5--3
Write a program to copy the value 55H into RAM memory locations 40H to 45H using
(a) direct addressing mode,
(b) register indirect addressing mode without a loop and
(c) with a loop. '
L-\~)
Solution: ~<c.L- vJ'-

MOV A,#55H ;load A with value SSH


(a)
MOV 40H, A ;copy A to RAM l ocat ion 40H
MOV 41H,A ;copy A to RAM locat i on 41H
MOV 42H,A ;copy A to RAM location 42H
MOV 43H,A ;copy A to RAM l ocation 4 3H
MOV 44H,A ;copy A to RAM locat i on 44H

(b) MOV A, #SSH ;load A with value SSH


MOV R0,#40H ;load the pointer. R0=40H
MOV @RO,A ;?opy A to RAM location RO points to
INC RO ;increment pointer. Now R0=41H
MOV @RO,A ?opy A to RAM location RO points to
INC RO ;increment pointer. Now ROc 42H
MOV @RO,A ?opy A to RAM location RO points to
INC RO ;increment pointer. Now R0=43H
MOV @RO,A ?opy A to Rru:1 location RO points to
INC RO ;increment pointer. Now R0=44H
MOV @RO,A
I,

\ (c) MOV A, #55 ;AzSSH


MOV R0,#1.Q!ll ;load pointer. R0:40H RAM
MOV R2,#0S I ;load counter, R2 =S ' address
AGAIN: MOV @RO,A 4-1 ;copy SSH to RAM l .
INC RO ;increment RO poin~:;tion RO points to
DJNZ R2,AGAIN ;loop until counter = zero

Example 5-4
wnte
a program to clear 16 RAM locations starting
. a t RAM address 60H . /

Solution:

CLR A 1AO
MOV Rl,#60H ;load
MOV R7,#16 ;load poi n t er. Rl60H
counter R7
AGAIN: MOV <tRl ,A ;clear RAM ' .16 (10 in hex)
10
INC Rl , i ncrement Rl cation Rl pointa to
DJNZ R7,AGAIN ;loop until pointer
counter. ze ro

-
8051 ADDRESSING MODES
95
d save the result in dall
h of them, an
Exmpl S-5 54H add 02 to eac
l ations 45H to ,
Take 10 byres of data from data RAM oc
RAM locations 79H down to 70H.

Solution:
h counter
HOV R2,#10 ;R2 is used as t e location
o first source location
MOV R0,#45H ;RO points t destination
MOV Rl. #79H ;Rl points to first
HOV A, liRO ;move source byte to A
BACK:
ADD A, #02 ;add 2 to i t .
co desci nat1on
MOV @Rl,A ,move it inter
INC RO ,increment the sour~e ~on pointer
DSC Rl ,decrement the desc1na of destination is in
;this is because the address
~decreasing order s zero
DvNZ R2,BACK ;repeat until counter va 1ue i

ter indirect
An example of how to use both RO a.n d Rl in the regJs m ode in a block transfer is given in
a ddressmg
Example 5-5.

Limitation of register indirect addressing mode in the 8051


As stated earlier, RO and RI are the o nly registers that can be used fo r pointers in register indirect addressing mode.
Since RO and Rl are 8 bits wide, their use is limited to accessing any information in the internal RAM (scratch pad
memory of JOH 7FH, or SFR). However, there are times when we need to access data stored in externa l RAM or in the
code space of o n-chip ROM. Whether accessing externally connected RAM or on-chip ROM, we need a 16-bit pointer
In such cases, the DPTR register is used, as shown next.

Indexed addressing mode and on-chip ROM access


Indexed addressing mode is widely used in accessing data elements of look- - .
ROM space of the 805). The instruction used for this purpose is "MOVC up table entries located m the program
register A are used to fonn the address of the dara element stored . h . A, ~ +DPTR". The 16-bit register DPTR and
in the program (code) space ROM of the 8051 the instruction MO~~".-<: 'PR_ M. Because the data elements are stored
this instruction the contents of A are added t~ the 16-bit register D~ used instead of MOV. The "C" means code. In
See Example 5-6. to fonn the 16-bit address of the needed data.

. < '..-<>:S
wmpleS-6 6/)f , -
The word "SAM" is to be burned in the llash ROM .
1
to do this and to read this data into internal RAM otation starting from 040oH f
I
- ocatrons starling frorn 60H o an A1'89C51. Write a progrma
Solution:
ORO OOOOH
f CLR A ;program Starts at 1
,A-o oeation
I/ ' HOV DP'TR, #04 OOH ;0PTR400H (poi
OOOOH
, MOVC I\, '1~PTR
( . HOV 60H,A \<J ;get s fr"' l~~=t ~o first aou:rce
;move it to !(JIM >on 40 0H locat::ion)
' I - 1oCation 60H
D (>''
I
I
f: / "'.,,...
96
~

w~(\';jJ-<U' ) Tl-IE 8051 MICRoc


l:l' ONTROL
LERAN
D EMllEDDED SYSTEMS
;DPTR 401 H (points to next location )
INC DPTR
AO
I
CLR A ;get ' A' from 1ocat10~ 401H
MOVC A, @A +DPTR ;move it to RAM location 61H
MOV 61H,A
;OPTR402H
INC OPTR
;A:sO
CLR A ;get 'M' from location 401H
MOVC A, @A+OPTR
;move it to RAM location 62H
MOV 62H, A
HERE: SJMP HERE
;stay here
6- ')
ORG 400H ;data is burned into location starting from 400H
DB "SAM''
;directive for end o f file
END

DcJ ,V' <-- bd t L


J,, ~ 6b r,~cj1 ct-.,,_,

Example 5-7
Assuming that ROM space starting at 250H contains "America", write a program to transfer the bytes into RAM
locations starting at 40H.

Solution:
; (a) This method uses a counter
ORG 0000
MOV DPTR, #MYDATA -i: fC~ load pointer
ROM
MOV RO, #4 OH ' ... ~- ; load pointer
RAM
MOV R2, #7 -1 1 :i.. ; load counter

BACK: CLR A ;A = 0
MOVC A, @A+DPTR ;move data from code space
MOV @RO,A- - ;save it in RAM
INC DPTR
.
;~ncre ment ROM pointer
INC RO ;increment RAM pointer
' DJNZ R2,BACK ;loop until counter =O
HERE: SJMP HERE

: - --- - - ----on-chip code s pac e used for storing da t a


ORG 250H
MYDATA DB "AMERICA"
END

't l4;1... <1b Str~ (i


; (bl This method uses null char f or end of str1ng
ORG 0000
HOV DPTR #MYDATA
I
;loa d ROM pointer
HOV R0, #4 0H ; load RAM point e r
BACK: CLR A ; AO
MOVC A , <IA+DPTR al ,move dat a frOftt c
J/ J Z HBRB- ~ '
exit if ode epace
' null cha
~ MOV & O,A $ ,eave it i n RAM racter
IIJC DPTR
, 1nctant: Rell poiatff

-
8051 ADDRESSING MODES
;increment
INC RO
;lOOP
SJMP BACK
HERlt: SJMP HeRE

space Used for stor1 ng data


j -------- on-chip code

MYDATA : DB
ORG 25011
AMERICA .. ,0
- .;end
not i ce null char for
,
of string
&ND
Z [nStruction to detect that.
. and how we use e J
th
Notice the null character, 0, indicating the end of the stnng.

j Look-up table and the MOVC instruction


It allows access to elements of a fre-
The lookup table is a widely used concept ln microprocessor progra ~ g. t application we need x' va]lJ6
quently used table with minimum operations. As an example, assume that""'-ora shown
cer am.,n Examp1e 5 8
ul
m the range of O to 9. We can use a look-up table instead of calc anng ,t. n1s is
1n addition to being used to access program ROM, DPTR can be used to access memory externalJy connected to the
8051. This is di.scu.ssed in Chapter 14.
Another register used in indexed addressing mode is the program counter. This is discussed in Appendix A.
1n many of the examples above, the MOV instruction was used for the sake of clarity, even though one can use any
instruction as long as that instruction supports the addressing mode. For example, the instruction "ADD A, @RO" would
ad~ the conte~ts of the memory location pointed to by RO to the contents of register A. We will see more examples of
usmg addressing modes with various instructions in the next few chapters.

Indexed addressing mode and MOVX instruction
As we have stated earlier, the 8051
has 64K bytes of !'()(le s d th di

ter. We just showed how to use the MOVC instruction pace un er e rect control of the Program Counter regi
I
space. In many applications the size of program code dee:n:~:v: portion of this 64K-byte code space as data memory
any room to share the 641<-byte code space with data.

Exampl 5-8

Wnte a program to get the x value from Pl and send x' to P2 .


, continuously.
Solution:
... ORG 0
MOV DPTR,#JOOH
MOV A, #OPFH ;load look-up tabl
:A-Pr e address
MOV ~,,A
BJ\CK : MOV A,91 ;configure Pl a .
;get X s lnput port
MOVC A,eA.DPTR
MOV P2,A ;~et X squared fr
SJJ1P BACK ; issue it to 1>2 Oln table

XSOR_TABLE:
r = JbOH
~

~ ;keep doing it

DB 1.1,4',19,16,25 JS 49 6
END ' ' ' 4 81
. . the below table. Store this
Example 5-9 f the numerals from O to 9 are g1ve~e~ts of these locations one by
The common cathode 'sev~-se~~~~:~s~~rite a program to ;~~;~aeyu;~: displays the numerals repeat-
look up table in ~OM loca;~::hich is connected to a seven-segmen
one, an.cl output 1t t~ r;~s between displays.
edly with a delay o
Decimal digit Seven-segment code
0 3F

1 06
2 SB
3 4F
4 66
5 6D
6 7D
7 07
8 . 7F
9 6F

Solution:
ORG OOOOH
START: MOV Rl,#10 ;Rl=no of digits, i.e., counter
MOV DPTR,#400H ;load ROM pointer
BACK: CLR A ;A=O
MOVC A,@A+DPTR ;move data from code space to A
MOV Pl,A ;output data to port 1 for displaying it
ACALL DELAY ;delay of 100 ms
INC DPTR ;increment ROM pointer
DJNZ Rl, BACK ;loop until counter=O
SJMP START ' ;repeat continuously

ORG 0400H ;store data at locations starting from 400H


DB 3FH,06H,5BH,4FH,66H,6DH,7DH,07H,7FH,6FH
END ;directive for end of file

' for this reason the 8051 has another 64K bytes of memory space set aside exclusively for data storage. This data memory
'"'1 space is referred to as external n1emory and it is accessed only by the MOVX instruction. In other words, the 8051 has a total
of 128K bytes of memory space since 64K bytes of code added to 64K bytes of d ata space gives us 128K bytes. One major
difference between the code space and data space is that, unlike code space, the data space cannot be shared between code
and data. This is such an important topic that we have dedicated an entire chapter to it: Chapter 14.

Accessing RAM Locations 30 - 7FH as scratch pad


As we have seen so far, in accessing registers RO - R7 of various banks, it is much easier to refer to them by their
RO - R7 names than by their RAM locati?ns. The only problem is that we have only 4 banks and very often the task of
~ank switching and keeping track of register bank usage is tedious and prone to errors. For this reason in many a p plica-
tions we use RAM locations 30 - 7FH as scratch pad and leave addresses 8 - IFH for stack usage. That m eans that we use
Ro - R7 of bank 0, and if we need more regis ters we simply use RAM locations 30 _ 7FH. Look at Example 5-10.
-
8051 ADDRESSING MODES
99
Eic mplt S-10 . SH as the (Ountcr.
Write delay subroubne using
RAM IQC'abOn ~

Solution:
RJ>JII 1ocacion 4SH
value in
d counter 1 countO
DELAY, MOV 45H,#OFPH ;loa counL untl
decremenc
RBPBAT: DJNZ 45H.REPEAT
RET

Review Questions ddressing mode. Why?


a
1. The instruction "MCV ~~4 OH '~!r R2 of bank O?
What address is assign,~ to reg1s k 2?
;: What address is assigned to reg!stcr R2 of ban . . data is jn on-chip RAM?
4. What addrl'SS is assigned to registe~ ~\ ister indirect addressing mode if the
5. Which registers are allowed to be use or reg

Byte
SECTION 5.3: BIT ADDRESSES FOR 1/0 AND RAM address
Many microprocessors such as t he 386 o r Pentium allow ln 7F
ro rams to access registers and 1/0 ports in byte size only.
~th! words if you need lo check a single bit of an 1/0 port, you General-
must read the entire b yte first and then manipulate the whole purpose
byte with some logic instructions to get hold of lhe desired sin- RAM
gle bit. This is not the case with the 805!. Indeed, one of the m~st
important features of the 8051 is the ability to acces~ the regis-
30
ters, RAM, and 1/0 ports in bits instead of bytes. This 1s ~ very
2F 7F 78 70 7C ?8 7A 79 78
unique and powerful feature for a microprocess~,r made in t~e
early 1980s. In this section we show address assignment of bits 2 77 76 75 74 73 72 71 70
of 1/0, register, and memory, in addition to ways of program- 20 6F 6E 60 6C 68 61' 69 68
ming them. 2C 67 66 65 64 63 62 61 60
~ 28 SF SE SD SC SB SA 59 58
= 2A 57 56 ss
Bit-addressable RAM ] 29 4P 48 40
54 53 52 51 50
4C 48 4A 49 48
Of the l 28-byte internal RAM of the 8051, only 16 bytes are ~
bit-addressable. The rest must be accessed in byte format. The bit-
address.1ble RAM locations arc 20H to 2FH. These J6 bytes pro-
i-
..,
28
27
47
31'
46
38
45
lD
44
3C
43
38
42
3A
41 40
39 38
26 37 36
vide 128 bits of RAM bit-addressability since 16 x 8 = 128. They "2 25 2F 28
35
20
34
2C
33
28
32
2A
31 30
are addressed as Oto 127 (in decimal) or 00 to 7FH. Therefore, iii 29 28
24 27 26 25
the bit addresses Oto 7 are for the first byte of internal RAM loca- 24 23 22 21 20
23 lF
tion 20H, and 8 to OFH are the bit addresses of the second byte 1 10 lC 18 lA 19 18
of RAM location 21 H, and so on. The last byte of 2FH has bit 22 17 16 15 14 13 12 11 10
addresses of 78H to 7FH. See Figure 5-t and Example 5-11. Note 21 OF OE OD
that internal RAM locations 20 2FH are both byte-address.,bl
and bit-addressable.
In order to avoid confusion regarding the add~ 00. 7FJ;
the following two points must be noted.
e


- 20
lF
18
17
07 06 05 04 03
oc OB
02 01 00
Bank3
OA 09 08

10 S.nk 2
OF
t. The 128 bytes of RAM have the byte addresses of 00 . 7FH 08 &nk 1
and can be accessed in byte size using various add . 07
modes such as direct and register-indirect as we h ressmg 00 Default register bank for RO R7
in this chapter and p revious chapters. Th~ ;,1 ~ seen
accessed using byte-type instructions. 128 Y es are
Figure s.1. 1611)1
both bit. nd b 10$ of lnte"'al RAM. Notr. Thy 1.e
100 Y e-o O$Sibl.
l'HEsos1 M:ICRocoNTRo
LLER ANO EMBEDDED SYSTEMS
5-11 . s of the RAM byte in hex.
Example . bits belongs. Give the addres bi t 28H to 1
F. d t to \vhich byte each of the follow1ng (d) SETB 28H ; set b . t 12 (dec ima l)
('~si;B 42H ;set bi t 42H t o 1 (e)CLR 12 ;clear i.
;) CLR 67H ; clea r b ~t 6;H (f) SETB 05
(c)CLR OFH ; c lear b it 0

Solution: 28H
of RAM locabon
(a} RAM bit address of 42H belongs to 02 f RAM location 2CH.
(b) RAM bit address of 67H belongs to 07 of RAM location 21H.
(c) RAM bit address of OFH belongs to 07 of RAM location 25H.
(d) RAM bit address of 28H belongs to DOf ~M location 21H.
(e) RAM bit address of 12 belongs to D4 of RAM location 20H.
(f) RAM bit address of 05 belongs to D5

Table 52; Single-Bit Instructions


Instruction Function
SETB bit Set the bit (bit = 1)
CLR bit Clear the bit (bit= O)
CPL bit Complement the bit (bit - NOT bit)
JB bit,target Jump to target if bit = 1 (jump if bit)
JNB bit,target Jump to target if bit - 0 (jump if no bit)
JBC bit,target Jump to target if bit= l, clear bit (jump if bit, then clear)

2 Th 16 b tes of RAM locations 20 - 2PH also have bit addresses of 00 - 7FH since 16 x 8 = 128 (00 - 7FH). Tn order
e ythese u 8 bits of RAM locations and other bit-addressable space of 8051 individually, we can use ~nly th.e
!:~~:~~t instructions such as SETB. Table 5-2 provides a list of single-bit instructio~. Notice t~at the s1~gle-b1t
instructions use only one addressing mode and that is direct addressing mode. In the first two s~ch?ns of this ch~p-
ter we showed various addressing modes of byte-addressable space of the 8051, among them mdIIect addressmg
mode. It must be noted that there is no indirect addressing mode for single-bit instructions.

1/0 port bit addresses


As we discussed in Chapter 4, the 8051 has four 8-bit 1/0 ports: PO, Pl, P2, and P3. We can access either the entire
8 bits or any single bit without altering the rest. When accessing a port in a single-bit manner, we use the syntax "SETB
x. y" where X is the port number 0, 1, 2, or 3, and Y is the desired bit number from O to 7 for data bits DO to 07. See
Figure 5-2. For example, "SETB Pl. 5" sets high bit 5 of port 1. Remember that DO is the LSB and 07 is the MSB.
As we mentioned earlier in this chapter, every SPR register is assigned a byte address and ports PO P3 are part of
the SFR. For example, PO is assigned byte address 80H, and Pl has address of 90H as shown in Figure 5-2. While all of
the SFR registers are byte-addressable some.of them are also bit-addressable. The PO - P3 are among this category of SFR
registers. From Figure 5-2 we see that the bit addresses for PO are 80H to 87H, and for Pl are 90H to 97H, and so on.
Notice that when code such as "SETB Pl. O" is assembled, it becomes "SETB 90H" since Pl.O has the RAM address
of 90H. Also notice from Figures 5-1 and 5-2 that bit addresses 00 - 7FH belong to RAM byte addresses 20. 2FH, and bit
addresses 80 - F7H belong to SFR of PO, TCON, Pl, SCON, P2, etc. The bit addresses for PO - P3 are shown in Table 5-3
and discussed next. '

Bit memory map


From Figures 5-1 and 5-2 and Table 5-3 once again notice the following facts.
-
8051 ADDRESSING MODES
101
I
. ed to RAM JocatioOS of Byto Bit oddn>SS
I. The bit addresses 00 7FH are assign address
20 2FH- . eel to the PO port. FP FO B
F4 Pl F2 Fl
2 The bit addresses 80 87H are assign "'CON ....,,;,ter.
PO F7 P6 PS
FH
3 The bit addresses 88 8 are asst
gned to the ..,,-
E4 &l 62 &l EO ACC
eel to the Pl port. 67 E6 65
4. The bit addresses 90 97H are assign th SCON register. &O
The bit addresses 98. 9FH are assigned to e Dl D2 Dl DO PSW
00 D7 D6 DS D4
:: The bit addresses AO. A7H are assigned to the P2.port.
The bit addresses A8. AFH are assigned to the IE register. 88 .. .. . . BC BB BA B9 88 IP

;. The bit addresses BO. 87H are assigned to the P3 port. 82 Bl BO Pl


BO 87 86 BS 84 Bl
9. The bit addresses 88 BFH are assigned to [P.
AP .. AC AB AA A9
A8 1E
10. The bit addresses CO - CFH are not assigned. AB
11. The bit addresses DO D7H are assigned to the PSW register. P2
AO A7 A6 A5 A4 AJ A2 Al AO
12. The bit addresses 08 DPH are not assigned.
13. The bit addresses EO - E7H are assigned to the Accumulator SBUP
99 not bit"1ddressable
register.
98 9F 96 9D 9C 98 9A 99 98 SCON
14. The bit addresses E8 EFH are not assigned.
15. The bit addresses FO F7H are assigned to the B register. 97 96 95 94 93 92 91 90 Pl
90

8D not bit~add.rcssabJe THl


Registers bit-addressability
8C not bit...addre$Sable THO
While all J/0 ports are bit-addressable, that is not the case
88 not bit..addressable TLl
with registers, as seen from Figure 5-1. Only registers A, B,
PSW, IP, IE, ACC, SCON, and TCON are bit-addressable. Or 8A not bit-addressable TLO
the bit-addressable registers, we will concentrate on the familiar 89 not bit-addressable TMOD
registers A, B, and PSW. The rest will be discussed in future 88 BF 8E 80 SC es 8A 89 88 TCON
chapters. 87 not bit-address.'lble PCON
Now let's see how we can use bit-addressability or registers
such as A and PS~V. As we discussed in Chapter 2, in the PSW
83 not bit-addressable DPH
register two bits are set aside for the selection of the register banks.
82 not bit.:tddress.1ble
See Figure .>-3. Upon RESET, bank Ois selected. We can select any DPL
oti\er banks using the bit-addressability of the PSW as was shown 81 not bit...addressable SP
in Chapter 2. The bit addressabilityof PSW also eliminates the need 80 87 86 8$ 84 83 82 81
80 PO
for instru~tionssuch asJOV Oump if OV=l). See Example 5-14.
llxamme the next few examples of bitaddressabilty to gai SpedaJ Function Registers
better understanding of U,is important feature of the 80Sl. na
Figure 5-i. S~ RAM Address <Byte and Bil)
Table 5-3: Bit Addresses for All Ports
PO Addr Pl Addr P2
PO.O 80 Pl.O Addr P3
90 1'2.0 Ad dr Port's Bil
P0.1 81 Pl.I AO P3.o
91 1'2.1 BO DO
P0.2 82 P!.2 Al
92 1'2.2 P3.1 Bl
P0.3 83 A2 01
Pl.3 93 P3.2
P2.3 B2 D2
P0.4 84 Pl.4 A3
94 1'2.4 P3.3 B3
PO.S 85 P!.S A4 D3
95 P3.4
P0.6
P2.s 134 D4
86 P!.6 96 AS
P0.7 1'26 P3.5 85
87 Pt.7 A6 05
9'1
P2.7 P3.6
86
A7 06
P3.7
87
THl; 8051 MICRoc o
07
-
-
NTROLLER.
AND EMBEDDED SYSTEMS
p
RSl RSO ov --
CY AC FO

Address
~Sl RSO
"~!.__~~~~~~~~Reg~J~St~e~rB~a~nk~~-==========_QOH -07H
o o O 08H -OFH
1
o 1 10H -17H
2
1 0 18H -1FH
1 1 3

. e 5-3 Bits of the PSW Register


F1gur

Example 5-12 . h"ch ort the bit belongs. Use Table 5-3.
For each of the following instructions, state t)o w IB ~2H (d) SETB QA7H
(a) SETB 86H (b) CLR 87H (c SET

Solution:
(a) SETB 86H is for SETB PO 6
(b) CLR 87H is for CLR PO 7
(c) SETB 92H is for SETB Pl. 2.
(d) SETB OA7H is for SETB P2 7

Example 5-13
Write a program to save the Accumulator in R7 of bank 2.

Solution:
CLR PSW. 3
SETB PSW .4
MOV R7 ,A

Example 5-14

While there are instructions such as }NC and JC to check the carry flag bit (CY), there are no such instructions for
the overflow flag bit (OV). How would you write code to check OV?

Solution:

The OV flag is PSW.2 of the PSW register. PSW is a bit-addressable register; therefore, we can use the following
instruction to check the OV flag.
JB PSW.2,TARGET ;jump if ov-1

- - -

8051 ADDRESSING MODES


103
d it 10 P2. If not, make it even
Exmpl S-15 en value. If SO, sen
. 37H contains an ev
Write a program to s If the RAM location
and then send It to P2.

Solution: . accumulator
.
J?H 1nto
l'iOV A,37H ,. 1oad RAM 1ocat1on if 90 jump
JNB ACC.0,YBS
;is DO of reg AO?
;it is odd, make ic even
TNC A
YES: l'iOV P2,A ,send it to P2

Exmple S-16
27H Verify if the stored result is positive or
The result of a signed arithmetic operation is stored in RAM location
negative. II it is negative send a high value toPJ.7, otherwise send a low value.

Solution:
MOV A, 27H ;move the content of RAM location 27H to A
JNB ACC.7,POS ;check the value of 07 of ACC. If it is set, the sign
;bic shows it to be a negative number
SETB Pl. 7 ;because ic is a negative number, send a high to Pl. 7
SJMP Nl>XT ;exit the program
PCS: CLR Pl. 7 ;the sign bit is not set, implies a positive number,
;send a low value to Pl.7
NEXT: NOP ;do nothing on exit
END ,end of file

ExampleS-17

The status of bits Pl.2 and Pl.3 of l/0 port Pl must be sa


the status of Pl.2 m bit location 06 and the status of Pl.J inv~ ::i:~~!~ are changed. Write a program tu....,
Solution:
CLR 06
CLR 07
;clear bit address 06
JNB Pl.2,0VER
;clear bit address 07
;check bit Pl 2 1"f
SETB 06 i O then
; f Pl.21 set b" Jump
OVER: JNB p 1.3,NBXT . check b. it location 06 to l
SBTB 07 ' lt Pl.) if O
NEXT: ... ;if Pl . Jal, set.bit then jump
location 07 to l

Example S-18

\Vrite a program to ..ve lhe slatua of bit Pl 7


00 RAMad~
Solution: bit 05.
HOV C, Pl. 7 ;get bit frOIII port
MOV 05,C ;save bit

104
T1iES0s1 Mi
CRocoN
TROLLER -
ANO Et.lBEODED svsTEMS
Example S-19
Move the content of the 7th bit of the A register to pin P0.7, and also save it in RAM location 08H.

Solution:
;move the 7th bit of A register to carry
MOV C,ACC.7
MOV P0.7,C ;put it on P0.7
;move to RAM location OS(bit-addressable area)
MOV 08,C

Using BIT directive


The BIT directive is a widely used directive to assign the bit-addressable I/ 0 and ~~ocati?ns. The B.IT direc-
tive allows a program to assign the I/ 0 or RAM bit at the beginning of the program, making 1t easier to modify them.
Examine the next few examples to see how we use the BIT directive.

Example 5-20
Assume that bit P2.3 is an input and represents the condition of an oven. If it goes high, it means that the oven is hot.
Monitor the bit continuously. Whenever it goes high, send a low-tq-high pulse to port Pl.5 to tum on a buzzer.

Solution:
OVEN HOT BIT P2 . 3
BUZZER BIT Pl . 5
HERE: JNB OVEN_HOT ,HERE ;keep monitoring for HOT
ACALL DELAY .
'
;sound the buzzer
CPL BUZZER
ACALL DELAY .
I

SJMP HERE
~ is similar t~xample 5-16, except the use of BIT directive allows us to assign the OVEN HOT and BUZZER
1 o any port. 1s way you do not have to search the program for them. -

Example 5-21
An LED Pl.7. Write a program to toggle the LED forever.
. IS connected to pm
SoI ution:
LED BIT P.7 ;using BIT directive
HERE: CPL LED ;toggle LED
LCALL DELAY ;delay
SJMP HERE ;repeat forever

Example S-22
~ switch is connected to pin Pl.7 and an LED t 0 .
it to the
. LED. pm P2.0. Write a program to get the status of the switch and send

Solution:
SW BIT Pl.7 ;assign bit
LED BIT P2. 0 ;assign bit
HERE: HOV C,SW ;get the bit f
MOV LED,C ;send the bit ~~t~he port
SJMP HERE ; repeat forever e port

-
80St ADDR ESSING MODES
- --- - - - -

105
Solution:
PRONlllT BIT 12H
12H co carry
bit 1ocacion 1
HOV C, PHONll!T ; copy . f is high
JNC NO
;check co see i of message
MOV DPTR, #400H ;yes, load addres~see Chap. 12)
;display message
LCALL DISPLAY
SJIIP EXIT ;get out of No message
MOV DPTR, #420H
;load the address
NO:
LCALL DISPLAY ,display it
EXIT: ;exit .

; ~~~~~~-data to be displayed on LCD .'


ORG 400H I
YBS_MG: DB ~New Messagesio
ORG 420H
NO_MG: OB ~No New MessagesN,0

Using EQU directive


We can also use the EQU directivetoassignaddresses,as shown in the next few examples. Notice that in Example 5-24
the ports are de6ned by their names, while in Example 5-25, they are defined by their addresses.

Example S-24

The cost prices of 10 Items are stored in RAM locations starting from SOH onw rd Wh th I
ch th
out as md JCa ted b y 'h',gh' on sw11 a s.
, e cost price is replaced by the selling b dd' en ese terns att
of 19 to each value. This changed data is sent out through port 1 wth d ..~nee Ya 1ng a constant
program for this scenario. 1 1
a e ay ""tween each data transfer. W
..;r
Solution: JI..,~
1j> SW EQO P0.1
V 11
l " - DAT EOU Pl
MOV c,sw ;read awiteb value i
JNC NEXT Iif awiteh value . n to the <;arry. bit.
MOV 1U, #10
MOV
,counter for numb is not high, e\cit the loop
RO,.SOH ;RO is the point er Of data items
BACK: MOV A,IIRO ,move the dat er to the data
ADD A, #19 dd a to the A .
MOV 4DR0, A ;a the profit " 1 register
MOV ;replace the a ue
OAT,A ,send value t~Ontent of RAM
ACALL DELAY ;delay Pl
INC RO
DJNZ 1 increment
Rl,BACK ,check if po1nter value
NEXT : NOP
END ;On exit ~UnteraO
;end ot i11.,
nothing

106
Tffl! 8051 MtCR,
0<::0NTRottE -
R ANO EMBEDDED SYSTEMS
Q line connected to PO1 Ten milli-f
Example 5-25 . d 'low' on its 'DAT-RE PO This indicates the en~ o
d t from Pl, ,t sen s a . CK line connected to .2 . f this scenario.
When an output devi~ w~ts a~ device sends a low on .its A request. Write a program or
seconds after the data IS ~ece1ved,ues~' line is monitored again for a new
~"~"ction and the data req
one tr..,..,...

OAT-REQ
P0.1
8051

~ OUTPlIT
Pl DAT
v DEVICE

P0.2
ACK

Solution: po'
DAT-REQ EQU 81H
ACK EQU 82H por
DAT EQU 90H f
p o
BACK: MOV C,DATREQ h k if there is a request for d~ta
;c
if ecnot low, monitor the DA~
T REQ line
JC BACK
SEND: MOV Pl,A '.move data to Pl if DAT-REQ is low
'
ACALL DELAY ;wait for 10 ms . received
HERE: JB ACK, HERE check if acknowledgment is
SJMP BACK ;if yes, await next request for data

Review Questions
1. True or false. All l/0 ports of the 8051 are ~it-addressable.
2. True or false. All registers of the 8051 are b1t-ad~essable.
3 T false. All RAM locations of the 8051 are bit-addressable.
rue or b' dd bl
4. Indicate whlch of the following registers are 1t-a ressa e.
(a) A (b) B (c) R4 (d) PSW (e) R7
5. Of the 128 bytes of RAM in the 8051, how many by~es ~re bit-addressable? List them.
6. How would you check to see whether bit DO of R3 is high or low? .
7. Find out to whlch byte each of the following bits belongs. Give the address of the RAM byte m hex.
( ) SETB 20 (b) CLR 32 (c) SETB 12H (d) SETB 95H (e) SETB OE6H
8. ~ e bit addresses 00 - 7FH belong to bit addresses 80 - F7H belong t o - - - - - - -
9. True or false. PO, Pl, P2, and P3 are part of SFR.
10. True or false. Register ACC is bit-addressable.

SECTION 5.4: EXTRA 128-BYTE ON-CHIP RAM IN 8052


The 8052 rnicrocontroller is an enhanced version of the 8051. In recent years the 8052 has replaced the 8051 due to
many of its new features. DS89C420/30 is an example of 8052 archltecttue. One of the new features of the 8052 is an extra
128 bytes of on-chip RAM space. In other words, the 8051 has only 128 bytes of on-chip RAM, while the 8052 has 256 bytes
of it. To understand it, first let's recall the following two facts from earlier discussion in this chapter and Chapter 2.

1. The 8051 has 128 bytes of on-chlp RAM with addresses 00 - 7FH. They are used for (a) register banks (addresses
00- lFH), (b) bit-addressable RAM space (addresses 20 - 2FH), and (c) the scratch pad (addresses 30 - 7FH).
2. Another 128 bytes of on-chip~ with add r~sses 80 - FFH are designated as Special Function Registers (SFRs).
Again, the SFRs are accessed by drrect addressing mode as we saw earlier in this chapter.
-
8051 ADDRESS[NG MODES

107
f n-chip RAM with addresses 80. FFH This
In addition to the abo,c two features, the 8052 has another l 28 bytes? h.t from the tower 128 bytes of 00. 7
FH 1l1t
..,.1ra l28by1cs of on-chip RAM is often called upper mcmor)' to dJstinguis -~ed to the SfRs. In other words, the
only ?roblem is, the address space SO. FFH is the same address spa~~~!'~,raUcl address space in the 8052 forcy are
phys,cally two separate memories, but they have the same addresse5 ..-- es U$
to use two dillerent add~ing modes to access them as described next. 5
I To access the SFRs. we use direct addressing mode. The instruction "MOV .90H # ~~" is a n c xa;;ple ,?f accessing
thcSFRwith direct addressing mode. Since 90H is the address of Pl, this is same as MOV Pl' . SSH
2. To access the upper 128 bytes, we use the indirect addressing n,ode, which uses RO a nd Rl registers as pointe~
Therefore, instructions "MOV RO, A" and r,,ov @Rl, A" are employed to access t~e u ppe r m~mory as Jong as
regu,tcrs RO a nd Rl have values of 80H or higher. For example, the following codes will put SSH into address 90H

of the upper 128 bytes of RANI.


;load the upper memory address
MOV R0,#90H
;put SSH into an address pointed to
MOV CRO,#SSH
;by RO reg.
shows how to a th arn e space shared between thcSFRand the upper 128 bytes of RAM in the 8052. Example 5-,,
Figure 5-4 shows the p U 1
'cccss e upper 128 bytes of on-<hip RAM in the 8052 microcontroUer. ..,

FF FF Indirect Access
Oin."d Access
(MOV 90H,#55H) (MOV@RO,A)

1111
Spt..--ci.\l Function Upper RAM
Rcgist~r Only
80
7F
80

..
20
IF
Accumu lator

Registers,
18 Bank 3 Program St,llus Word
17 Stack Pointer '
'
Status
~ and Control Bits
Orts, '
10 O.nk 2 Timers,
a OP
Serial Control
P ,
ower Control
olh , and
08 Bank 1 ers

"'
Oil
:::::::::::~~Ba~n~k10~~_J
Figure 5-4. 8052 On-0,ip RAM Ad dress Sp~,

108
1llEso51MtCR.
OC011rrR.
OLLER.ANO -
EMBEDDED sYSTEMS
Example 5-26
. the ...-:;;;;;,RAM locations of 90 - 99H.
\Vrite a program for the 8052 to put SSH Lnto .....,...... 1 -,
I 'O

Solution:
ORG 0
MOV A,#SSH
MOV R2,#10 on-chip RAM
access the upper 128 bytes of
MOV R0,#90H
~use indirect addressing mode
BACK: MOV @RO,A
INC RO
OJNZ R2 , BACK ;repeat for all locations
SJMP $ o>,v ;stay here
END ~~~
h y to see the result (See Figures 5-5 a nd
Run the above progra1n on your simulator and examu1e t e upper memor
5-6 for screen shots.) .

Exam ple 5-27


Assume that the on-chip ROM has a message. Write a program to copy it from code space into the upper memory
space starting at address 80H. Also, as you place a byte in upper RAM, give a copy to PO.
-

Solution:
ORG 0
MOV DPTR, #MYDATA
MOV Rl,#SOH ;access the upper 128 bytes of on-chip RAM
Bl: CLR A
MOVC A,@A+DPTR ;copy from code ROM space
.:J MOV @Rl,A
PO,A
q# ;store in upper RAM space
;give a copy to PO
/ MOV
V JZ EXIT ;exit if last byte
INC DPTR ;increment DPTR
INC Rl
SJMP Bl
./
~
;increment Rl
;repeat until the last byte
EXIT: SJMP $ .........._,.'i ;stay here when finished
;------------
ORG 300H
MYDATA: DB ~The Promise of World Peace",0
~\
END
,i ,,c-
Run the above program on your simulator and examine the
u pper memory to see the result.

Simulators and Data RAM space


th AU the major 8051/52 simulators have ways of s how h
em. mg t e da ta RAM contents. Figures 5-5 and 5-6 show some of
-8051
ADDRESSING MODES
109
~,,
.,.
80: 00
ala uppeupace)

00 00
~
I

ea: oo oo 00
uu. . . . . ..
~
90: 55 55 55
98: 55 55 00 . . . . .. .
o: 00 00 00 . .... .
. . . . . . .. .. "I
8: 00
80: 00
88: 00
00 00
00 00
00 00
......
... ... . ~
~
CO: 00 00 00 . .. . . . . . J,=
ca: oo oo 00 ...... . r,f
DO: 00 00 00 ....... .
D8: 00
EO: 00
E8: 00
FO: 00
F8: 00
00 00
00 00
00 00
00 00
00 00
. . .. ... .
...... .
.. .....
. . . . . . . . .:.I
.~
r~
,p

00
,..
Upper Memory for th 8052
Figu.rt: 5-5. Fr.anklin S<>ftwatt's Pro View a1ll
\ll'.1:
l la
I'!'=
E'I
l'i
1131
I : Ox80 00 00 00 00 00 00 00 00 ... . . . . .
,,tiiii~.
'.
I:Ox88 00
!:Ox90 55
00
55
00
55
00
55
00
55
00
55
00
55
00
55
. . . .. . . . I lld[

I:Ox98 55 55 00 00 00 00 00 00 tJtJ
I:OxAO 00 00 00 00 00 00
. . . . . .. .
00 00
l
!:OxA8 00
I:OxBO 00
00
00
00
00
00
00
00
00
00
00.. .. . . ..
00
00
00
00 Iii\
I:OxB8 00 00 00 00 00 00. ... . . . .
00 00
I:OxCO 00 00 00 00 00 00... . . . . .
00 00
i ~
111\ii
!:Oxes oo oo oo oo oo oo oo oo . . . . . . . . ."-
I:OxDO 00 00 00 00 00 00 DO 00 . . . . . . . . 1._
I:OxD8 00 00 00 00 00 00 00 00 . . . . . . . .
00 00 00 00 00 00 00 . .. . . . . .
l:OxEO 00
I:OxE8 00
I:OxFO 00
I:OxFB 00
00 00 00 00 00 00 00 . . .. . . . .
00 00 00 00 00 00 00 . .. . . . . .
00 00 00 00 00 00 00 . .. . . . . .
j~
> l:OxBO . OxFF ... . . . .. l~
<start address> <encl addrea>t (\iiia,;),.==a9
... c.........
figurt ~- Keil's Vision Upper Memory for the 805?
'
~~
!~
110
Tli 8051 l'YflCRO -
CONTROLLER AND EMBEDDED SYSTEMS
-~
Review Questions
True or false. The 8052 is an upgraded version of the 8051. . ..
l. True or false. The 8052 has a total of 256 bytes of on-chip RAM m addition to the SFRs.
2 True or false. The extra 128 bytes of RAM in the 8052 is physically the same RAM as the SFR.
3.
4. Give the address for the upper RAM of the 8052. .
s. Show how to put value 99H into RAM location F6H of upper RAM m the 8052.

SUMMARY
This chapter described the five addressing modes of the 8051. Immed iate addressing mod_e uses a co1:5tant for ~e
source operand. Register addressing mode involves the use of registers to hold data to be marupulated._ Direct or re~-
ter indirect addressing modes can be used to access data stored in either RAM or registers of the 8051. Direct addressing
mode is also used to manipulate the stack. Register inclirect addressing mode uses a register as a pointer to the d ata.
The advantage of this is that it makes addressing dynamic rather than static. Indexed ad dressing mode is widely used
in accessing data elements of look-up table entries located in the program ROM space of the 8051.
A group of registers called the SFR (special function registers) can be accessed by their names or their addresses. We
also discussed the bit-addressable ports, registers, and RAM locations and showed how to use single-bit instructions
to access them directly.

PROBLEMS
SECTIONS 5.1 AND 5.2 IMMEDIATE AND REGISTER ADDRESSING MODES/ ACCESSING MEMORY USING
VARlOUS ADDRESSING MODES
1. What is the difference between the following two instructions in terms of addressing mode and function
performed?
MOV A, #46H
MOV A, 46H
2. W~te one ~truction ea~ using the following addressing modes:
(a) ~ed1ate (b) register (c) register indirect (d ) direct
3. Indicate the address assigned to each of the following
(a) RO of bank O (b) ACC (c) R7 of bank O .
(g) ~4 _of bank 1 (h) DPL (i) R6 of bank 1 (? )R~o~fbbank 2 (e) B (f) R7 of bank 3
4. Wnte instructions to push the contents of the follow G) . ank 3 (k) DPH (I) PO
(a) A (b) B (c) RO of bank O (d) Rl f b ; g regis ters onto the stack: c
O 1
5. In accessing the stack we mus t use ddr . (e) R2 of bank 2 (f) R3 of bank 3 'C')
6. What does the following instruction do? " MOV ! 0Fei !1;;g mode.
7. ~ at does the following instruction d o? " MOV A ' l FH"
8. Wn
~ What te is
code
th to .push
. ROh ' Rl , and R3 of bank O onto 'th e stack and pop th b ack into RS, R6, and R7 of bank 3
vfo. . e error m t e followu:ig instruction ? MOV A 2 em
~;r W~te a program to copy FFH into RAM locations 6 ' R
Ai. Wnte a program to copy 10 bytes of data Startin iQB to 6FH.
- ;~ Write a program to find y where = x2 + 2x + g at RC?Madd.ress 400H to RAM locatio .
t/j Write a program to add the follo!in d 5, and x is between O and 9. ns starting at 30H.
ORG 200H g ata and store the result in RAM location 30H
MYDATA: DB 06,09,02,0S,07 .

SECTION 5.3: BIT ADDRESSES FOR 1/ 0 ANO RAM


14 "SETB A" is a(n) ( . .
15. "CLR A". vahd, invalid) ins truction
IS a(n) ( lid . .
16. "CPL A" . ( ) va ' invalid) instruction
17 IS a n (valid invalid)
True or False? All the l/ O orts of' ~truction.
18. Are the registers TCON an! TMOD805 btl
1 -a
adrde bit-addressable.
ressable?
-
8051 ADDRESSING MODES
111

'
--

' 19.
.
win actions using
~Vrite instnictions to perform the follo g
bit addrllSses cc
D-1 bit of the A
(b) dear the D3 bit of pO
(a) set the bit D<I of Pl 71-1 (d) clear the
(cl dear the content of RAM address 6 on bit PJ.5.
(e) set the D<I bit of PSW. 1
with 75% duty cycle n bit f'2.7. Uild (square wave of 50% duty
20 Write a program to generate a square wave 'th 80% duty eye e o ill generate a so
. t are wave w1 ram \V .
21 Write a program to genera ea squ . oes high the prog H to PO
22. Write a program to monitor Pl.4. When ,t g ' . d the value 55
P2
cycle) on pin 7 . oes low the progr aot will sen
23. Write a program lo monitor P2. I. Wh~ 11 g '
24. What bit addresses are assigned to PO,
25. Vvhat bit addresses are ass'.gned to Pl~
26. What bit addresses are assigned to P2.
27. What bit addresses are assigned to 1'3? 1
28. What bit addresses are assigned to the PCON r~ste\
29. Whatbit addressesareassigned to theTCON reg,ster.
30. A;
\Vhat bil addresses are assigned to register
31. What bit addresses are assigned to register B.
32. What bit addresses are assigned to register PSW?
33. What do the following instructions do? Ol'.)H
(a) S!lTB 87H (b) CLR 84H (c) SETB 95H (d) CLR 2 res ectively.
34. Write a program to save registers A and Bon R3 and RS of bank P
JS.
36.
37.

38.
Give another instruction for "CLR C".
~Vhat does the following instruction do?
JNB PSW.2,THERE
What does the following instruction do?
d 'ff
ln Problem 19, assemble each instruction and slllte if there 1s any .1 erenc:e e
b tween them .

-..
il

JB PSW. 6, HERE
39. Show how you would check whether the P flag is high. ' ,W], Rl,
40. Show how you would check whether the AC flag is high. j Xll!II
41. Give the bit addresses assigned to the flag bit of CY, P, AC, and OV. I L,r
42. Of the 128 bytes of RAM locations in the 8051, how many of them are also assigned a bit address as well? Indicate i II
which bytes those are.
43. Indicate the bit addresses assigned to RAM locatior,s 20H to 2FH.
44. The byte addresses assigned to the I 28 bytes of RAM are t o - - -- -
45. The byte addresses assigned to the SFR are to .
46. Indicate the bit addresses assigned to both of the following. ls there a gap between them?
(a) RAM locations 20H to 2FH (b) SFR
47. The following are bit addresses. Indicate where each one belongs
W~H ~47H ~ 18H 00 ~ 00 ~ ro~
(g) 67H (h) 55H (i) 14H Q) 37H (k) 7fH
48. What is done by the following instructions?
MOV A,Pl
JN8 ACC . O, YES
49. True or false. The bit addresses of 80H and beyond ar
50. What does the following instruction do? e assigned to SFR (special function registers)
SBTB PSW . 4
51. What is the effect of executing the following two in - . .
MOV C, P2. J Su ucaons?
MOV 15H,C
52. What is the effect of executing the following tw .
MOV C, PSW. O O instructions?
MOV 13H, C
53. What is U1e effect of executing the following tw .
MOV C, l'.CC 0 O IOSIJ'uctions?
JB HERB
54. Write a program highlighting the use of the EQU d ' .
lrective to denot
ea PDt1.
JU
TH E8051 l',fJcRoc
ONTROLLER -
ANO l!MBEODED SYSTEMS
55. Write a program to show the use of the BIT directive: in the followin methods:
56. Write a program to set high all the bits of RAM locations 20H to 2FH us g g
(a) byte addresses (b) bit addresses . . ..
57. Write a program to see whether the accumulator 1S div1S1ble by 8.
58. Write a program to find the number of zeros in register R2.

SECT10N 5.4: EXTRA 128-BYfE ON-CHIP RAM IN 8052


59. What is the total number of bytes of RAM in the 8052 including the SFR resi:'ters? Contras~ that with the 8051.
6(). The addressing mode used to access the SFRs of the 8052 is while for ad~ess1ng the upper 128 bytes
of RAM, the addressing mode is used.
61. Write an example to show how the upper 128 bytes of 8052 are accessed.
62. Give the address range of the lower and the upper 128 bytes of RAM in the 8052.
63. In the 8052, the SFR shares the address space with the (lower, upper) 128 bytes of RAM.
64. In Question 63, discuss if they are physically the same memory.
65. Explain what is the difference between these two instructions.
(a) MOV BOH, #99H (b) MOV @RO, #99H if R0=80H
66. Write a program to load 10 bytes of data from locations 80H to locations starting at AO of the upper bank of the
8052.
67. Wr!te a program to put SSH into RAM locations CO- CFH of upper memory.
68. Wnte a program to copy the contents of lower RAM locations 60 - 6FH to upper RAM locations DO - DFH.

ANSWERS TO REVIEW QUESTIONS


SECTION 5.1: IMMEDIATE AND REGISTER ADDRESSING MODES
1. No
2. MOV R3,#10000000B
3. Source and destination registers' sizes do not match.
4. True
5. No

SECTION 5.2: ACCESSING MEMORY USING VARIOUS ADDRESSING MODES


1. Direct; because there is no "#" sign
2. 02
3. 12H
4. EOH
5. RO and Rl

SECTION 5.3: BIT ADDRESSES FOR 1/0 AND RAM


1. True
2. False
3. False
4. A, 8, and PSW
!: ~6,t~'~e bit-addressable; they are from byte location 20H to 2FH.

JNBACC.O
7 For (a), (b), and (c) use Figure 5-1.
(a) RAM byte 22H, bit D4
(b) RAM byte 24H, bit DO
(c) RAM byte 22H, bit D2
8. ~diy~d ~ u;O Figure .5-2. (d) SEIB Pl.5 (e) SETS
9. True es - H, special function registers.
ACC 6
.
10. True

-8051 ADDRESSING MODES


113
' SEcn ON 5.4: EXTRA 128-BYTE ON-C
HIP RAM 1NSOS2

I. True
2. True
3 False /
4 80-FFH
. MOY A,#99H
5. MOY RO,#OF6H
MOY@RO,A

114
CHAPTER6

ARITHMETIC, LOGIC
INSTRUCTIONS, AND
PROGRAMS

OBJECTIVES

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

Define the range of numbers possible in 8051 unsigned data


Code addition and subtraction instructions for unsigned data
Perform addition of BCD data
Code 8051 unsigned data multiplication and division instructions
Code 8051 Assembly language logic instructions AND, OR, and EX-OR
Use 8051 logic instructions for bit manipulation
Use compare and jump instructions for program control
Code 8051 rotate instruction and data serialization
Explain the BCD (binary coded decimal) system of data representation
Contrast and compare packed and unpacked BCD data
Code 8051 programs for ASCII and BCD data conversion
Code 8051 programs to create and test the checksum byte

115
' . . tntction,. Program e~
n,,,, ,11.,pter de<,er1bes all SOS1 arithmetic and 1oi;1c ,ns .
<'iven to illustrate the application
amples are o b cti. I.
to addition, su tra on, mu hphc;a.
and programs relat~ 2 In 5ection 6.3, we discuss the logi(
Q( th,,'St' instructions. In Section 6.1 we d'.5"uss tns~tio: discussed in Se<:
1100
TEn51ruction and data serialization
11on, and dh ision or unsigned numbers. Signed ni;; w1RE instrUction. R~TA ~ as BCD and ASCH conversion
n,c.
,n,tructions ANO, OR. and XOR. as well as the C . IV re 1.,vorld appUcattons su
MC discussed in Section 6.4. In Section 6.5 we provide some a

aml chcck>um byte testing.

SECTION 6.1: ARITHMETIC INSTRUCTIONS . sed to represent d~,


- a nd nobitsaresetasideforth
. e
U"'igned numbers are defined as data in ,vhichall the b,tsare u d FfH (0 to 255 decimal) for 8-bit data.
00
pos,ti,e or negative sign. This means that the operand can be between an

Addition of unsigned numbers (A) ust be involved. The form of the ADD
In the 8051, in order to add numbers together, the accumulator register rn
instruction is
ADO A, source ;A =- A + s ource
The instruction ADD is used to add two operands. The destination operand is always in regi~ter A ~hile the source
operand can be a register, immediate data, or in memory. Remember that memory-to-memory arithmetic operations are
ne,er aUowed in 8051 Assembly language. The insi-ruction could change any of the AF, CF, or P bits of the flag register,
d_e~dmg on the ~J)\.>rnnds involved. The effect o( the AOD instn,ction on the overAow flag is discussed in Section 6J
smce 11 ,s used mamly m s,gned number operations. Look at Example 6-1.

Addition of individual bytes


mu~f~:r.~ ~~;,t:;:~t:::!~o~d~(~ ;~:~d 5bytes of data. The sum was purposely kept less than FFH, the maxi
after the addition of efch operand. E~ample _;t:: :~; of any numlber o( operands, the carry flag shou Id be checked
o accumu ate carries as the operands are added t 0 A
6
' .
,
' Ex.unple 6-1
RI .Verify if th eir
Two numbers are stored in registers RO and--. . sum
. .,s greater than FFH
Solution:
HOV A,RO
..,
;move first number to A
ADD A,Rl" ,add second number to it
.
JC M&SSAG8 ;if sum>FPH, cv.1
SJMP N&XT ;if CYO, exit
MESSAGE: MOV 1\, #'Y' ;if CYcl,move 'Y' into A
MOV Pl,A ;send the message y'
NEXT: NOP ;do nothing through Pl
ENO ;end of file
/

Exa mple 6-2


Assume that RAM locations 40 -44 have

116
THE 8051 MICRocoNl"
ROLL ER AN -
D EMBEDDED SYSTEMS
42= (CS)
'
43=(5B)
' 44:: (30)

Solution:
MOV R0,#40H ;load pointer
MOV R2,#5 ;load counter
CLR A<> ;A=O
MOV R7,A ~ ...., ;clear R7
A,@RO ;add the byte pointer to A by RO
AGAIN: ADD
;if CY=O don't accumulate carry
JNC NEXT
INC R7 ;keep track of carries
NEXT: INC RO ;increment pointer
DJNZ R2,AGAIN ;repeat until R2 is zero

Analysis of Example 6-2


Three iterations of the loop are shown below. Tracing of the program is left to the reader as an exercise.

1. In the first iteration of the loop, 7DH is added to A with CY= 0 and R7 = 00, and the counter R2 = 04.
2. In the second iteration of the loop, EBH is added to A, which results in A = 68H and CY= 1. Since a carry occurred,
R7 is incremented. Now the counter R2 = 03.
3. In the third iteration, CSH is added to A, which 1nakes A = 2DH. Again a carry occurred, so R7 is incremented
again. Now counter R2 = 02.

At the end when the loop is finished, the sum is held by registers A and R7, where A has the low byte and R7 has
the high byte.

ADDC and addition of 16-bit numbers


When a~ding two 16-b~t data ~perands, we need to be concerned with the propagation of a carry from the lower
~yte to the higher byte. The instruction ADDC (add with carry) is used on such occasions. For example look at the addi-
tion of 3CE7H + 3B8DH, as shown below. '

l
3C E7
+ 38 SD
78 74

When the first byte is added (E7 + BD = 74, CY= 1). The carr is ro .
3B + 1 = 78 (all in hex). Example 6-3 shows the above steps in y ~ pa gated to the higher byte, which results in 3C +
/ an 80 1 program.

Example6-3
.
Write programs to
(a) add two 16-bit numbers, the numbers are ~ 4SH and 0.,,cirt__y
(b) add two 32-bit numbers stored in RAM locations :,:::::1
.. .
- . . '

A.R.ITliMETIC,LOCIClNSTRUCl10NNs,S~A~N~D~;;RO~;;:~;--~~~~~~--,~~~~~~~~---
, GRAMS
117
'
Solution:
(al ,make cv~o into A
CLR C '.1oad the lo" byte no" AJ1,CY=l
MOV A,1!4SH '.add the 10w byte, f sum in RO
ADD A,#OECH byte o
-save the low ino A
MOV RO.A ' b byte
1
MOV A,#02H -load the h 9 ith carr/
'.add the high bytes w
ADOC A, #OFCH '
02+FCH+lFFH of result in Rl
MOV Rl,A
',save the h19
h byte
,,,.
Fin.i.Uy, we gel the result as R0"31H and R!=FFH- ~~

(bl
Let the 32-bil numbers be Ol453BC0H and 56C705FEH and let them be stor
ed in RAM locations as shown below.

Addresses
Data
""
,#~
(lid'
tlllll
Addresses Data FEH if
40H COH SOH
SIH
05H .i;
41H 3BH
52H C7H
42H 45H !.ldl
53H 56H
OH 01H 111illl
i.L.
The result of addition will be at least 4 bytes long. If RO and RI (of bank Oby defattlt) are used as pointers to the
addends, there is no other register available to act as pointer to the result. Hence, it will be necessary to use RO of
the second register bank. Observe how the banks are switched.
,.-,
al1lrl

CLR
MOV
MOV
C
R2,#04H
RO, #40H
,clear CY Qag
;move into R2 the number of bytes in each number
;RO points to the low byte of the first number
-
p!II

MOV Rl, #SOH ;Rl points to the low byte of the second number
SETB PSW. 3 ;switch to bank 1
MOV RO, #60H ; use RO of bank l as pointer to the result
CLR PSW.3 ;return to bank o
BACK: MOV A,liRO ;bring one byte of the first .
ADDC A,liRl 1 add one byte of th number 1nt.o A
INC RO ;increment the po e second number to it
INC Rl . inter of the fl mb
; increment the poi t rat nu er
SETS PSW . 3 ;switch to bank 1 n er of the second number
MOV IIRO,A ; store one byte of t~h store one byte of the sum
INC RO ;increment the poi e sum
CLR PSW . 3 ;return to bank o nter of the result. location
DJNZ R2, BACK
;repeat until all f
our bytes have been added
The result of the addition will be stored in RAM as

Add~ Dahl
60H BEH
61H 41H
62H OCH
63H S8H

118
Digit BCD
eco (binary coded decimal) number
.
system .
. eeded because in everyday life we use
0 0000
l 0001
BCD stands for binary coded de_cimal. BCD is n bers Binary representation of O to 9
2 0010
the digits O to 9 for numbers, not binary or ~ex num . ounters two terms for BCD
is called BCD (see Figure 6-1). In computer literature one ~;c ch one next 3 0011
numbers, (1) unpacked BCD, and (2) packed BCD. We descri e ea 4 0100
5 0101
6 0110
Unpacked BCD 7 0111
In unpacked BCD the lower 4 bits of the number represent the BCD number, and th~ 8 1000
rest of the bits are O. F~r example, "0000 1001" and "0000 0101" are ~pa~ked BCD f~r;: 9 1001
5, respectively. Unpacked BCD requires 1 byte of memory or an 8-b1t regJ.Ster to con a
Figure 6-1. BCD Code

Packed BCD
In packed BCD, a single byte has two BCD numbers in it, one in the lower 4 bits, and one in the upper 4 ~:s~~
example, "01011001" is packed BCD for 59H. It takes o~y 1 ~yte of_ memory to store the packed BCD operan
so one reason to use packed BCD is that it is twice as efficient m storing data. . .
There is a problem with adding BCD numbers, which must be corrected. The problem 1s that after adding packed
BCD numbers, the result is no longer BCD. Look at the following.

MOV A,#l7H
ADD A,#28H
Adding these two numbers gives 0011 11118 (3FH), which is not BCD! A BCD number can only have digits from
0000 to 1001 (or Oto 9). In other words, adding two BCD numbers must give a BCD result. The result above should have
been 17 + 28 = 45 (0100 0101). To correct this problem, the programmer must add 6 (0110) to the low digit: 3F + 06 =
45H. The same problem could have happened in the upper digit (for example, in 52H + 87H = D9H). Again to solve this
problem, 6 must be added to the upper digit (D9H + 60H = 139H) to ensure that the result is BCD (52 + 87 = 139). This
problem is so pervasive that most microprocessors such as the 8051 have an instruction to deal with it. In the 8051 the
instruction "DA A" is designed to correct the BCD addition problem. This is discussed next.

DA instruction
~e DA ~decimal adj~~t for addition) ~~~cti?,n in the 8051 is provided to correct the aforementioned problem
assooated with BCD addition. The mnemoruc DA has as its only operand the accumulator "A" The DA t f10
will add 6 to the lower nibble or higher nibble if needed; otherwise it will leave the result alo
will clarify these points. ,
Th
ne.
f ll . ms rue 1n
e o owing examp e

0
MOV A, #47H ;A=47H first BCD operand
MOV B,#2SH ;B=25 second BCD operand
ADD A,B ;hex(binary) addition (A=6CH)
DA A ;adjust for BCD addition (A=72H)

After the program is executed, register A will contain 72H (47 + 25 _ 72 11 11

other words, while the source can be an operand of any addressin mod )- The .DA_ instructio~ wor~ only on A. In
for DA to work. It also needs to be emphasized that DA m t b g e, the destination must be in register A in order
us e used after th ddi f
operands can never have any digit greater than 9. In other words _ . ~a h on o BCD operands and that BCD
note that DA works only after an ADD instruction it will n t k' A F digits are n ot allowed. It is also imp ortant to
, o wor after the INC instruction.

Summary of DA action
After an ADD or ADOC instruction,

1. If the lower nibble (4 bits) is greater than 9, or if AC_ 1


2. If the upper nibble is greater than 9, or if CY= 1 ad; ' add 0110 to the lower 4 bits.
_ , 0110 to the up per 4 bits.

IJUTHMETIC, LOGIC INSTRUcnONS, AND PROGRAMS


119
' si,own be1o
Y.'
.
write a program lo
at 40H, as
,
Eumple..., - star!Ulg
. RA,\;l locallv-
D dara 1trois are stored in t,e 1n BCD-
A>sume that 5 BC mbers The result must
find the sum of all the nu .
40= (71)
41 (11)
42 (65)
43.(59 )
44 (37)

Solution:
MOV RO, ~40H
,load pointer
load counter
MOV R2, #5
CLR A AO
MOV R7,A ;' clear R7 . nter to A by RO
ADD A,IJRO
. add the byte poi
AGAIN: ' BCD
DA A ;adjust fodr ' t accumulate carry
JNC NEXT if CYO on .
tNC R7 ;keep track o~ carries
NEXT: INC RO increment pointer
DJNZ R2, AGAIN
;repeat unt11 R2 is zero

T carry) flag bit except for BCD adclition and correction. For example,
In reality there is no other use for the A~ (a~~ ,ary as far as BCD is concerned.
adding 29H and 18H will result in 41H, wh,ch ,s incorrect
Bex BCD
29 0010 1001
+ 18 + 0001 1000
41 0100 0001 AC=l
+ 6 + 0110
47 0100 0111

Since AC= 1 after ~,e addition, "DA A" will add 6 to the lower nibble. The final result is in BCD format.

Subtraction of unsi gned numbers


SUBB A, source ;A= A - sou~ce - CY

In many microprocessors there are two different instructions for subtraction: SUB and SUBB (subtract with bor
row). In the 8051 we have only SUB6. To make SUB out of_SUBB, ':"e have to make CY: o prior to the execution of
=
the instruction. Therefore, thel'\1 ru:e two cases for _the SUBB mstruc_tion: (1) with CY o, and (2) with CY 1. Fi.r.;t we =
examine the case where CY= 0 paor to the execution ofSUBB. Notice that we use the CY flag for the borrow.

SUBB (subtract with borrow) when CY= O

tn subtraction, the 8051 microprocessors (indeed, all modern CPUs) th , .i.


every CPU contains adder circuitry, it would be too cumbersome (and ta;:se
e 2 s complement method. AlthOUb
subtracter circuitry. For this reason, the 8051 uses adder circu.itry to per( e~oo many transistors) to design sepatlt
the 8051 is executing a simple subtract instruction and that CY,. prior
0 1
:nn
e subtraction command. Assurning th,lt
marize the steps of the hardw"' of the CPU in executing the SUBB inst th~ execution of the instruction, one can surn
1. Take the 2's complement of the subtrahend (source operand). ruct1on for unsigned n umbers, as follows.
2. Add It to the minuend (A).
3. Invert the carry.

120
Tl-rE 80s1 MlCRoco -
N"rROLLER. ANO EMBEDDED 5ys,vfS
Example 6-5
Sho\\l the steps involved in the following.

I CLR C
;make CY=O
: MOV 113FH
A,
;load 3FH into A (A= 3FH)
MOV R3,#23H ;load 23H into R3 (R3 = 23H)
SUBB A,R3 ;subtract A - R3, place result in A

Solution:
A = 3F 0011 1111 0011 1111
+ 1101 1101 (2's complement)
R3 = 23 0010 0011
lC 1 0001 1100
0 CF=O (step 3)
The flags \vould be set as follows: CY = O, AC = 0, and the programmer must look at the carry flag to determine
if the result is positive or negative.

These three steps are performed for every SUBB instruction by the internal hardware of the 8051 CPU, regardless
of the source of the operands, provided that the addressing mode is supported. After these three steps the result is
obtained and the flags are set. Example 6-5 illustrates the three steps.
If the CY= 0 after the execution of SUBB, the result is positive; if CY= 1, the result is negative and the destination has the
2's complement of the result. Normally, the result is left in 2's complement, but the CPL (complement) and INC instruc-
tions can be used to change it. The CPL instruction performs the l's complement of the operand; then the operand is
incremented (INC) to get the 2's complement. See Example 6-6.

SUBS (subtract with borrow) when CY= 1


This instruction is used for multibyte numbers and will take care of the borrow of the lower operand If CY= 1
t tin th SUBB . . . a1s . prior
o execu g e mstruction, 1t o subtracts 1 from the result. See Example 6-7.

Example 6-6

Analyze the following program:


CLR C
MOV A,#4CH ;load A with value 4 CH (A=4 CH )
SUBB A,#6EH ;subtract 6E from A
JNC NEXT ;~f CYaO jump to NEXT target
CPL A ;1f ~=l then take l's complement
INC A ;and increment to get 2 , 8
NEXT:MOV Rl,A ;save A in Rl complement

Solution:
Following are the steps for "SUBB A, #6EH":
4C 0100 1100 0100 1100
-6E 2's comp. 1001 0010
0110 1110
22 0 1101 1110
CY "' l, the result is negative, in
2, s c01uple11e12t.
. .. .
-ARlTHMETIC,LOGICINSTRUCflONSA~;NND~~~~~;---,..~~~~~....,....~~~.......~~,......~---- .

,, OGRAMS
121
'
Wmp1~7
Analyze the following program:
CLR C '
CY o
MOV A,.62H ;A 62119611 CCII with CY l
62H - s
SOBB A,#96H ' he result
MOV R7,A ,save t
MOV A.~2711 ;A27H 1411
SUBB A,#l2H ;27H - 12H - l
MOV R6,A ;save the result

. th e is a borro"". Since CY = l,
Solution: is set high indicabng er 2762H -1296H = 14CCH
Alter the SUBB, A= 62H -96H = C~H an~ the c~~~gl = l4.H, Therefore, we have
when SUBB is ex<?Cuted the second tirne A - 27H

,,~
UNSIGNED MULTl PLICATION AND DIVISION .dB - required since the multiplication re
. th 8051 the use of reglsters A an ,5 .:, ,
In multiplying or dividing two numbers an e '. W first discuss multiplication. i::-;.,
and di,ision instructions work only with these two registers. e ,.,.,.
Ellli''
Multiplication of unsigned numbers .
The 8051 supports byte-by-byte multiplication only. The bytes are assumed to be unsigned data. The syntax IS as
follows:

MUL AB ;Ax B, place 16-bit result in Band A

In byte-by-byte multiplication, one of the operands must be in register A, and the second operand must be in regis
.-.
llli
ter B. After multiplication, the result is in the A and B registers; the lower byte is in A, and the upper byte is in B. The
following example multiplies 25H by 65H. The result is a l~bit data that is held by the A and B registers.
MOV A, N25H ;load 25H to reg. A
MOV B,~6SH ;load 65H in reg. B

MUL AB ;2SH 65H E99 where
; B = OEH and A 99H

Division of unsigned numbers


In the division of unsigned numbers the 8051 supports byt b
' e over yte only. The syntax is as follows.
DIV AB ;divide A by B

When dividing n byte by a byte, the numerator must be


DIV instruction is performed, the quotient is in A and th tn ~egtster A and the denominate b f .~.
e remamder is in B. See th ( . r must e in B. A ter u~
e oUowmg example.
Table 6-1: Unsigned Multi
Multiplication lication Summary (MlJL
Operand1 Operand 2 AB)
byte byte A R.esult
8
Notr Mulbpbc.,llon of operands largo, than A" low byte B h' h
e>-ptnmtnt with 8 bits talc-."'""' ma . ' - g byte
rupulau.on. It is lt'ft lo the d
S"('il er to
122
THE 8051 MICROcoN -
TR.OttER.
AND EMBEDDED svs-ratS
AB)
Table 6-2: Unsigned Division Summary (DIV Quotient Remainder
Denominator
Division Numerator B
A
A B
byte I byte
{If B = 0, then OV =1 indicating an error)

MOV A, #95 ;load 95 into A


MOV B, #10 ;load 10 into B
DIV AB ;now A = 09 (quot i ent) and
;B - OS(remainderl

Notice the following points for instruction "DIV AB".

1. This instniction always makes CY = Oand OV == O if the denominator is not 0.


2. If the denominator is O(B = 0), OV = 1 ind icates an error, and CY= 0. The stan d ard practice in a ll rnicrop0r~c~sso~s
when dividing a number by Ois to ind icate in some way the invalid result of infinity. In the 8051, the ag is
set to 1.

An application for DIV instructions


There are times when an ADC (analog-to-digital converter) is connected to a port and the A DC represents som e
quantity such as temperature or pressure. The 8-bit ADC provides da ta in hex in th e range of 00 - FFH . This h ex
data must be converted to decimal. We do that by dividing it by 10 rep eatedly, saving the remainde rs as sh own in
Example 6-8.
/

Example 6-8
In a semester, a ~tudent has to take six courses. The marks of the student (out of 25) are stored in RAM locations
47H onwards. Fmd the average marks, and output it on port 1.

Solution:
MOV Rl ,#06 ;Rl stores the number of courses
MOV B,#06 ;only B can be used as the divisor register
MOV R0,#47H ;RO acts as the pointer to the data
MOV A,#0 ;clear A
BACK: ADD A, @RO ;a~d the data to the A register
;~ince each number is less than 25 CY:O I

I NC RO ;increment the pointer


DJNZ Rl BACK I . ,.S ;r~p~at addition until Rl =O
DIV AB ""'-t,,ft ~ ~""I ;divide the sum by 6 to get th
. the t e average
'. quo ient is in A, remainder in B
MOV Pl,A ;ignore the rem aind er, output the average

Example6-9 - - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-

Convert a hexadecimal number to decimal.


Method
For example, let the hex number be 9CH whoee d
~he _m_e thod is to divide by 10 until the quotient
,v,ding by 10 twice will be enough.
is.:.
equivalent ia 156. To convert it to a decimal
IO. In the case of a hex number between 00 and
number,
FFH,

-
.A.R.ITHMETIC, LOGIC INSTRUCTIONS ANO
, PROGRAMS
123
' lowest o .
. erwilJbethe 'ddledig,t
rder c:ilgi t

. 6(retnainder}-dus rernaiJ'dder will be the lfl~gJi digit.


9C/OA~F(quobent), - ,emajnder}-~ re,naJ1I 10) will be the
F/ OA~l(quollent), :,( 11ent which ,stessthan
l(quo

The Deomal equi,-..lent lS thus 156.

Solution: n,ber is loaded into A


the hex nu r into B
HOV A, ij9CH ;move the divisonumber by 10 it to RO
HOV B, #OA!! ;divide the hex is in B, move
DIV AB ; the remaindde: 1 sor into B
MOV RO,B l d the lV 10
HOV B, #OA!! ;re oa h quot ient by
;divide t e inder to Rl
DIV AB move the rema . ent to R2
MOV Rl, B '."'ve the last quot1 . 't
MOV R2 , A ' . holding the lowest dig
. . R2
The decimal number as now t.n , 'RI and RO w,th RO

Review Questions A _ __ and the other in register


one byte in register_.;,_
. . of two bytes .ITT the 8051, we must p Iace
1 In multiplication ( )

. . ulti lication, the product will be placed in register s - - - - - . .


2. In unsigned byte-by-byte":' 1 ~MOL A, Rl". Explain your a~wcr. and the denominator m regtslt'r
3. Is this a valid 8051 instruction.
4.. In byte/byte division, the numera or m
t ust be placed in register--- -

5. In unsigned byte/byte division, the quotient will be placed in register - - - - and the remainder in regislt'r
Is this valid 8051 instruction.>"DIV A' Rl" . Explain
6 .,--:-:---;:- . your
A. answer.
7. Th . truction "ADD A, source" places the sum m --=---
. e,ns . . ill~?
8. Why is the following ADD ,nstru~
"ADD Rl, R2" f''rtS"'1T r1t
"J.<..
in" .J
'
"""'c:,,' -.
r, , )
9. Rewrite the instruction above in con;;ct form. ,. i, . I t \.. 1
10. The instruction "AODC A, source places the sum ,n - .- - -
l J. Find the value of the A and Cf flags in each of the foUowmg.
(a) MOV A, #4FR (b) MOV A, #9CH
ADD A, #OBlH ADD A, #63H
12. Show how the CPU would subtract 05H from 43H. . "
~ 4FH prior to the execution of
13
If CY= 1, A= 95H, and B
. subtraction? SUBS A, B", what will be the contents of A after the

SECTION 6.2: SIGNED NUMBER CONCEPTS AND ARITHMETIC OPERATIONS


All data items us! so.far have~ unsigned nurn~ers, m_eaning that the entire 8-bit operand was used for the
magnitude. Many applicalfuons reqwrlie st1gnedddata.t~ this S~tion the concept of signed numbers is discussed along
with related instructions. your app ca ions o no mvo1ve signed numbers you c b h' .
, an ypass t IS Section.
Concept of signed numbers In computers
In everyday life, numbers are used that could be positive or negati F
below zero can be represented as -5, and 20 degrees above zero as + Cve. or example, a temperature of 5 degrees
20 omputers rnust be able to accommodate such
numbers. To do that, computer scientists h;,ve devised the following,.,.;
live and negative numbers: The most significant bit (MSB) is set aside t:'~ernent for the representation of signed po5'"

124 r e s,gn (+ or-), whiJe the rest of the bits ate


Tit 8051 MICR.oc
ON'fR.OLLER. AND EMBEDDED SYSTEMS
used for the magnitude. The sign is repres~ted by O for positive_(+)
numbers and 1 for negative(-) numbers. Signed byte representation
magnitude
is discussed below. sign
I I
Signed 8-bit operands
Figure 6-2. 8-Bit Signed Operand
In signed byte operands, 07 (MSB) is the sign and DO to 06 ai:e
set aside for the magnitude of the number. If 07 = 0, the operand 1s
positive, and if 07 = 1, it is negative.
0 0000 0000
+1 0000 0001
Positive numbers
The range of positive numbers that can be represented by the format shown in Figur~ 6-2
...
+5 0000 0101
is Oto+127. lf a positive number is larger than+127, a 16-bit size operand must be used. Smee
the 8051 does not support 16-bit da ta, we .,.,riJ.l not discuss it.
. ..
+127 0111 1111

Negative numbers
For negative numbers, 07 is 1; however, the magnitude is represented in its 2's complement. Although the assem-
bler does the conversion, it is still important to understand how the conversion works. To convert to negative number
representation (2's complement), follow these steps.

1. Write the magnitude of the number in 8-bit binary (no sign).


2. Invert each bit.
3. Add 1 to it.

Examples 6-10, 6-11, and 6-12 de1nonstrate these three steps.

Example 6-10
Show how the following numbers are represented in the 8051
(a) - 7 {b)-56 (c)-128 (d) O

Solution:
In th~ 8051, negative numbers are represented in 2's com !em . .
negahve number in 2's complement form are p ent form. The steps involved m rep resenting a
(1) write the number in binary form
(2) complement each bit
(3) add 1
These
an are carried out for the conversion of each of the four numbers It
steps
Y_~egative number 1s 1. The biggest negative number that be lS important to note that the MSB of
P(os1hve or negative and has a unique representation. can represented by 8 bits is - 128. Also, o is neither
a) -7
(1) 0000 0111
(2} 1111 1000
(3) 1111 1001
(4 ) F9H ;representation i n hex
(b) -56
( 1) 0011 1000 Ii
(2) 1100 0111 I:
(3) 1100 1000
(4) CBH ; repr esent at i on in hex
'

-
! ~ _... .. -

ARITHMETIC, LOGIC INSTRUCTIONS AND .;~~-------------------


' PROGRAMS
125
'
( (c) - 128
(I)
(2)
1000 0000
0111 1111
(3) 1000 0000 . n in he"
(4) 80H
,representat10

{d) 0
ti
(1) 0000 0000
(2) 1111 1111
/
(3) 0000 0000
,,ii
...,j..
(4) OH
.
;representation in hex .,.!

...
'
Example 6-11 ..

Show how the 8051 does the following calculations I
(a) add +37 and-115 ...
(b) add -13 and -78 ..
Solution:
(a) .37 00 1 0 010 1
-~..
-115 + 1000 1101
1011 0010 B2H
--78
-
(bJ - 43 1 101 0101
+ -78 + 1011 0010
- -
--121- 11000 0111 ,the result is 1000 0111 = 87H
(as c arry is to be ignored)

Example 6-12

Show how lhe 8051 would do lhe following calculations


(a) subtract - 27 from +68
(b) s ubtract -78 from -43

Solution:
(a) +6 8 in bi nary i s 01 0 0 010 0
-27 in 2 ' s complement f o rm i s 1110 0101

Since !he operation is subtraction, lhe805J sends-27 to a 2's com I . .


traction means adding the 2's complement number, P ement Circuit to Produce 0001 1011. Since sub-
0100 0100
+ 0001 1011
01 0 1 1111 SFH +95

(b) 43 in 2'complement fora, is 1101


-78 in 2'complel88nt form ia 1011 0101
0010

.
126
. it to produce 0100 1110. Since
. s -78 to a 2's complemen t c1rcu
ce the operation is subtraction, the 8051 send
::traction means adding the 2's complement n umber,

1101 0101
+ 0100 1110
10010 0011 = 0010 0011 = 23H = + 35
. b . _ 1 to -128. The following lists
. . f b t - ized negative num ers tS
From the examples above 1t 1s clear that the range o Y e s
byte-sized signed number ranges:

Decimal Bin ary Hex


-128 1000 0000 80
-127 1000 0001 81
-126 1000 0010 82
. .. . . . . . .. . . ..
-2 1111 1110 FE
-1 1111 1111 FF
0 0000 0000 00
+l 0000 0001 01
+2 0000 0010 02
......... ..
+127 0111 1111 7F
The above explains the mystery behind the relative address of - 128 to+127 in the short jump discussed in Chapter 3.

Overflow problem in signed number operations


When using signed numbers, a serious problem arises that must be dealt with. Thls is the overflow problem. The
8051 indicates the existence of an error by raising the OV (overflow) flag, but it is up to the programmer to take care of
the erroneous result. The CPU understands only Os and ls and ignores the human convention of positive and negative
numbers. What is an overflow? If the result of an operation on signed numbers is too large for the register, an overflow
has occurred and the programmer must be notified. Look at Example 6-13.
In Example 6-13, +96 is added to +70 and the result according to the CPU was-90. Why? The reason is that the resul t
was larger than what A could contain. Like all other 8-bit registers, A could only contain up to +127. The designers of

Example 6-13

Examine the following code and analyze the result.

MOV A, #+96 ;A= 0110 0000 (A 6 0H)a


MOV Rl,#+70 ;Rl = 0100 0110 (Rl 46H)
ADD A, Rl ; A 1010 0110
;A= A6H - 9 0 d e cimal , I NVALI D!

Solution:
+96 0110 0000
6 t,+Jl "a.,,
+ +70 QlOO 01 10 l1~-r l 1t.-,o
+ 166 1010 0110 and ov-1
According to the C PU, the result is -90, wbidt ii wrong The CPU
lela OV 1 to wiic:ate the 09eluw.

- -

ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS


U7
' the CPU created the overflow lag specifically /or the purpose
of infornili'S t),e progr
anuner that the result of thesjo,,.,
.,....,

number operation is erroneous.


When is the OV flag set? fOU0 wing two conditions occurs:
In S-b1t signed number operations, OV is set to I f ' ther of the
I ei
0
l. There is a carry from 06 to 07 but no carry out of 07 (CY " >0 7
, from 06 to
2. There is a carry from 07 out (CY= I) but no carr) . f 06 to 07 or from 07 out' but
. not both This means
In other words, the overllow flag is set to 1 ifthere IS a carry rom E ample 6-13, since there 1s only a carry from 06
that if there is a carry both from 06 to 07 and from D7 out, OV "O. In ; 6_16 to w,derstand the overflow flag in signed
0
to 07 and no carry from D7 oul, OV =\.Study Examples 6-14, 6-15, a
arithmetic.

Example 6-14
Observe the followmg, noting the role of the OV flag.
MOV A, #-128 ;A = 1000 0000 (A = 80H)
MOV R4, #-2 ;R4 1111 1110 {R4 = FEH)
ADD A, R4 ;A 0111 1110 (A 7EH +126, invalid)

Solution:
-128 1000 0000
-2 1111 1110
-130 0111 1110 and OVl
According to the CPU, the resu.lt is+ 126, which is wrong (OV = 1).

Example 6-15

Observe the following, noting the OV flag.


MOV A,#-2 ;Allll 1110 (AFEH)
MOV Rl, #-5 ;Rl llll 1011 (Rl=FBH)
ADD A,Rl ;Allll 1001 (A=F9H= -7 corre t
' C ,OV=O)
Solution:
-2 1111 1110
-5
-7
1111 1011
1111 1001 and ov = 0
According to the CPU, the result is -7 which .
' s correct (OV _ O).

EumPIt 6-16
Examine the following, noting the roleofOV
MOV A, #+7 '
;AOOOO 0111 (A07u
MOV IU,#18 ;RlOOOl 0010 (R q)
ADD A,Rl ;AOOOl 1001 IA 112!!)
l9ff+2s
'

128
THE sos
Solution:
7 0000 0111
+ 18 0001 00 1 0
25 0001 1001 and ov '" O

According to the CPU, this is +25, which is correct (OV =O)

From the above examples we conclude that in any signed number addition, OV indicates_ whether ~e re~ult is
valid or not. If OV = 1, the result is erroneous; if OV = O, the result is valid. We can state emphattcally that m unsigned
number addition we must monitor the status of CY (carry flag), and in signed number addition, the OV (overflow) flag
must be monitored by the programmer. In the 8051, instructions such as JNC and JC allow the program to branch right
after the addition of unsigned numbers, as we saw in Section 6.1. There is no such instruction for the OV flag. However,
this can be achieved by "JB PSW. 2" or "JNB PSW. 2" since PSW, the flag register, is a bit-addressable register. This is
discussed later in this chapter.

Instructions to create 2's complement


The 8051 does not have a special instruction to make the 2's complement of a number. To do that we can use the
CPL (complement) instruction and ADD, as shown next. '

CPL A ;l's complement (Invert )


ADD A, #1 ;add 1 to make 2's complement

Review Questions
1. In an 8-bit operand, bit is used for the sign bit.
2. Convert-16H to its 2's complement representation.
3. The range of byte-sized signed operands is - to +
4. Show +9 and -9 in binary. - -- - ----
5. Explain the difference between a carry and an overflow.

SECTION 6.3: LOGIC AND COMPARE INSTRUCTIONS


_Apart from I/0 and arithmetic instructions, lo c instru .
sethction we cover Boolean logic instructions such as ~ ORctions l ~re some of m ost widely used instru ctions In thi
e compare instruction . , ' exc us1ve-or (XOR), and complem en t W e will
. also
. s tudys

Logical AND Function

AND Inputs Output


ANL destination, source ; dest = dest hu,-,
=u source X y XANDY
0 0 0
This instruction will perform a looical AND h
result in the d es tin
and .
a tion. Th e destination
o ontht e two op erand s an d place the
is normally 0 1 0
add can. be a rP<>ic;t
--o- er, m memory, or un.mediate. See A
e accumulat
. or. The source oper- 1 0 0
no er;:5smg modes for this instruction. The ANL instructippe;d1x A.l for more on the l 1 1
bits O~no;i;rn~.~fi:!:~1:i: ~ instruction is often ~:e~~:::~~~:e~; ~~a;'C~~i: X
y ...__,, - XANDY
-
ARITHMETIC, LOGIC INSTRUCTIONS AND
- -

' PROGRAMS
129
' '
v'Exmpl 6-17
Show the results of the following.
;As )SH s 05)
HOV A, R35H A
;A A AND OFH (now
ANL A, #OFH

Solution:
35H 0011 0101
OFH 0000 1111 OSH
)SH AND OFH
OSH 0000 0101
Logical OR Function

Inputs Output
OR y
dest OR source X XORY
ORL dest i nation, source;dest
0 0 0
Red and the result is placed tn the

.-.
The destination and source operands arc O . b' ts of"'' operand to 1. 0 I I
. .
destination The ORL mstruct1on can b used to set certatn can be a register,
and . .tn
I to The source oper, 1 0 I
The destination is normally the accumu a r. h dd ssing modes supported 1 I
. . "- A dix
memory, or unmed,ate. .,._~ _PpeR . , bA for more on
. I ea has no effect on any o f
pccands
l

~ = = f ) - x oRY
bv this instruction. The ORL mstruction ,or yte-s1ze o
the flags. See Example 6-18.

XOR
XRL dest i nation, source ;deat dest XOR source Logical XOR Function

ThJs instruction will perfocm the XOR operation on the two operands, and place Inputs Output
the result in the destination. The destination is normally the accumulator. The source
operand can be a register, in memory, or immediate. See Appendix A. l for the address- X y XXORY
ing modes of this instruction. The XRL instruction for byte-siie ope.rands has no effect 0 0 0
on any of the flags. See Examples 6-19 and 6-20. 0 I 1
XRL can also be used to see if two registers have the same value. "XRL A, Rl" will
exclusive-or register A and register Rl, and put the ~ult in A. If both registers have I 0 1
the same value, 00 is pla(t'd in A. Then we can use the )Z instruction to make a decision I l 0
based on the result. See Example 6-20.
~ ~ XXORY

Exampl 6-18
Show the results of the following
''1r-vtf~ -IO l,fl\#~
I rX
MOV A, #04,. ;A 0 4 ~.., >'c,il
ORL A,#30H IA A oa )OH (now A 34H)
Solution:
04H
..
0000 0100

-
lOH
l ,H
0011 0000
0011 0100 o,H oa JOH ) 4H '
.'
130
.
'lllE80s1 MICRoc oN't' -
ROLLER AND EMBEDDED svsTEMS
Example 6-19
Show the results of the following.

MOV A,#54H
XRL A, #78H

Solution:
54H 0101 0100
78H 0111 1000
2CH 0010 1100 54H XOR 78H _ 2CH

Exam ple 6-20 . XORin it with itself. Show how "XRL A, A"
The XRL instruction can be used to clear the contents of a register by g
clears A, assuming that A = 45H .

Solution:
45H 0100 0101
0100 0101
-45H
00 0000 0000 XOR a number with itself = 0

,.
,
Example 6-21
Read and test Pl to see whether it has the v alue 4lH. If it d oes, send 99H to P2; o therwise, it stays cleared.

Solution:
MOV P2,#00 ;clear P2
MOV Pl,#OFFH ;make Pl an input port
MOV R3,#45H ;R3=45H I,
MOV A,Pl ;read Pl
XRL A,R3
JNZ EXIT ;jump if A has value other than 0
MOV P2,#99H
EXIT: ...

In the program in Example 6-21 notice the use of the JNZ instruction . JNZ and JZ test the con ten ts of the accumula-
tor only. In other words, there is no such thing as a zero flag in the 8051.
Another widely used application of XRL is to toggle bits of an operand. For example, to toggle b it 2 of regis ter A,
we could use the following code. This cod e causes 02 of register A to change to the opposite value, while all the o ther
bits remain unchanged.

XRL A,#04H ;EX-OR A with 0000 0100

CPL A (complement accumulator)


. ~is instruction complements the contents of register A. The complement action changes the Os to ls and the ls to Os.
ThtS 1s also called l's complement.

-
AlllTHM1IC, LOGIC INSTRUCTIONS, AND PROGRAMS
131
'
EJ<,n,ple 6-22
Fmd the 2's complement or the value SSH.

Solution:
851! 1000 0101
MOV A,#SSH l'S = 0111 1010
CPL A ;1 1 8 comp. + 1
ADO A, fl
;2'9 comp. 781!
0111 1011

MOV
CPL
l'., #SSH
A ; now AAAH ( AAII )
Logical loverter

Input Output
-
,0101 0101 becomes l OlOl OlO
. d l to the l's complement. See X NOTX
To get the 2's complement, aU we have to do ,s to ad . truction in the 8051. Notice
1
&ample 6-22. In other words, there is no 2's complement Although the CPL instruc-
0
l
1
0
that in complementing a byte, the data must be"' reg~ter PO-P3 ports See Appendix A
tion cannot be used to complement RO-R7, it does wor .on .
10 see which addressing mode is available for the CPL instruction. X ---{)o-NOT X

Compare Instruction
The 8051 has an instruction for the compare operation. It has the following syntax.

CJNE destination,source,relative addr ess

In the 8051, the actions of comparing and jumping are combined into a single instruction called CJNE (compare

and jump if not equal). The CJNE instruction compares two operands, and jumps ii they are not equa l In addition, it
changes the CY flag to indicate ii the destination operand is larger or smalle;. It is important to notice that lhe operands
themselves remain unchanged. For example, alter the execution of the instruction "CJNE A, #67H, NEXT", register A
still has its original value. This instruction compares register A with value 67H and jumps to the target address NEXT
only ii register A has a value other than 67H.

Exmple 6-23

Examine the foUowing code, then answer the following qu ti


(a) ):YUi 1.tiJJmp to NEXT? es ons.
(b) What is in A after the C]NE Instruction is el<ecuted?

MOV A, NSSH :tf ,


: r.
CJNE A, l 99H,NEXT
I
NBXT:

Solution:
(a) '(es, it Jwnps ~ SSH and 99H are not equal.
(b) A; SSH, its onginal value before the cornpar1
son.

132
Table 6-3: Carry Flag Setting
CJNE. the destination operand can be in the accumulator ~r in one For CJNE Instruction
111
of the Rn registers. The source operand can be in a register, 111 me~- Carry Flag
ory, or immediate. See Appendix A for the addressing mo~es of this Compare
rnstruction. This instruction affects the carry lag only. CY lS changed CY = O
destination~ source
as shown in Table 6-3. CY=l
The following shows how the comparison works for all possible destination < source

conditions.
;check RS for 80
CJNE RS,#80,NOT_EQUAL
;R5=80
; jump if R5>80
NOT_EQUAL: JNC NEXT
;RS<BO
NEXT:
Notice in the CJNE instruction that any Rn register can be compared with an i.ounecliate value. There is no need
for register A to be involved. Also notice that CY is always checked for cases of greater or less than, but only after it is
determined that they are not equal. See Examples 6-25 through 6-27.

Example 6-24 /
~' .

Ten hex i:umbers are stored in RAM locations SOH onwards. Write a program to find the biggest number in the
'-o~ ~ -\ J"'-""-i
set. The biggest number should finally be saved in 60H. .
,,. .....-~,~If:,..,.,.\
Solution: "t>...,- (...."\ --- " J ~
e_ ,/A/ I
MOV RO,#SOH ;RO i s t he poi nter t o t he data '~
t(t> ....
-~
MOV Rl,#10 ;Rl i s the ~ ~nter
MOV B, #0 ;B=O
BACK: MOV A, @RO ;move a number to A
CJ?IE A,B,LOOP ;compare with B
LOOP : JC LOO Pl ;if A<B, j ump to LOOPl
MOV B,A ;if A>B, move it to 8
. '
;~.e., the bigger number should be in B
INC RO ;increment the pointer
DJNZ Rl,BACK ;~epeat until the counter=O
SJMP NEXT ;Ju~p ~o EXIT, the biggest number is in B
LOOPl: INC RO ;this is another loop , t a k en wh en the b"
;number was already in B a f t igger
,. compari. son er a
DJNZ Rl, BACK ;repeat until the counter=O
NEXT : MOV A,B ;transfer the biggest number to the Ar .
MOV 60H,A ;transfer the result to RAM location 60H egister
END

I/
Example 6-25
Assume that Pl is an input port connected to
test it for the value 75 According to the a temperature sensor Write
the following. . test results, place the te~pera a progr~ to read the temperature and
If T 75 ture value mto the registers indkllted ._.
a then A 75 v7
If T < 75 t hen Rl T
I f T > 75 then R2 . ~

-ARllliM ETIC, LOGIC INSTRUCTIONS, ANDPROGRAMs


133


'
Solution: ut Port
,maJ<e Pl an ,nptemperature
MOIi Pl. MOFFH d Pl p0rt, l tO 75
,rea ot equa
HOV
CJNl!
A.Pl
" .,s.ovn
-jump if A n
'
;A~75,
e,cit A~75
'
.., p
SJMP EXIT -if c;Y#O then ~ Rl
OVER: JllC NEXT 7 <
CY=-l, A< ;;,,
9 ave
HOV Rl, A_
EXIT -~d
,P->-
exit . R2
1n
SJMP A>75, save lt
NEXT: MOV R2 ,A
EXIT: ...

V
I

E,,mple 6-26
. r ngth 7, stored
Write a program to check if the character string o Ie
. RAM locations SOH onwards is a
Ill
palin-
,,.
,,;,
o;f
-
drome. If it is, output 'Y' to Pl.

.i""
Solution: the forward or back
h h th string is read in
A pahndrome is a string in which the characters are the same w et er e II"
ward direction, e.g. 'MADAM', 'RADAR'. etc. ,Ml
MOV
HO\/
MO\/
R2, #03
RO,#SOH
Rl.#56H
;take half ehe string length as a counter value
1
take RO as pointer co the forward reading
;take Rl as the pointer for the backward
:...
. r,,I

(JI
;reading of the atr1ng W*c
SACK: MOV A,eRO , move into A the character _pointed by RO :a.
MOV B,@Rl ;move into 8 the character pointed by Rl. II.
CJNE A,B,NEXT ;compare it with the character pointed by Rl (I,
INC RO ;increment the forward co,unter
DEC Rl ;decrement the backward counter
IJJNZ R2,BACK :repeat until all the characters are compared
MOV Pl,#'Y' ;since the string is a palindrome, output y
N"l!XT: NOP
, if not equal' do nothing since it is not a
;palindrome
,
;end of file

Exompl 6-27
Assume mtemal RAM memory locations 40H. 44H . lia_ _
Search to see if any of the values equals 65 If val c;1a 111 the daily temperatu ( f' .,.
make R4 O. ue d~ exist in the table ,:e ~r ive days, as shown btloW, ,
40H 176) 41H (79l 42 H <691 give ts location to R4; othenirilll...1
43 Ii (6SJ
44 .,
<>(62
Solution:
MOV R4, 10 ;R40
MOV RO.il40R
;load pointer
HOV R2,#0S
,load counter
MOV A, #65
;A65, Value
arched
-: 70 ;compare RAM data with 65
BACK: CJNE A,@RO,NEXT if 65, save address
MOV R4,RO
SJMP EXIT ;and exit
otherwise increme~t pointer
INC RO 1 count=O
NEXT: ;keep checking un t 1
DJNZ R2,BACK
EXIT

d do not change. Flags are


.
The compare instruction is really a subtrac~on, exc_ep
t that the values of the operan s . JNE
t be em hasized again that m the C . . ms .
. truction
'
changed according to the execution of the SUBB instruction. It mus_ oJ:iy the CY flag is affected. This 15 despite the
15
the operands are not affected, regardless of the result of the combr on.
fact that CJNE uses the subtract operation to set or reset the CY ag.

Review Questions
Find the content of register A after the following code in each case.
1. (a) MOV A,#37H (b) MOV A,#37H (c) MOV A,#37H
ANL A #OCAH ORL A,#OCAH XRL A,#OCAH
To mask c~rtain bits of the accumulator we must ANL it. wi~ - - - -
;: To set certain bits of the accumulator to 1 we must ORL it with _ _ __
4. XRLing an operand with itself results in .
s. True or false. The CJNE instruction alters the co~ten!s of its ?perands.. ,
6. What value must R4 have in order for the following instruction not to Jump.
CJNE R4,#53,0VER
7. Find the contents of register A after execution of the following code.
CLR A
ORL A, #99H
CPL A

SECTION 6.4: ROTATE INSTRUCTION AND DATA SERIALIZATION


In many applications there is a need to perform a bitwise rotation of an operand. In the 8051 the rotation instruc-
tions RL, RR, RLC, and RRC are designed specifically for that purpose. They allow a program to rotate the accumulator
right or left. We explore the rotate instructions next since they are widely used in many different applications. In the
8051, to rotate a byte the operand must be in register A. There are two type of rotations. One is a simple rotation of the
bits of A, and the other is a rotation through the carry. Each is explained below.

Rotating the bits of A right or left


RR A;rotate right A

1n rotate right, the 8 bits of the accumulator are rotated right one bit and bit DO exits fr th l t 'gnifi b'
and enters into D7 (most significant bit). See the code and diagram. ' om e eas 51 cant it

MOV A,#36H ;A=0011 0110


RR A ;A=OOOl 1011
RR
RR
RR
A
A
A
;A=lOOO
;A=llOO
;A=OllO
1101
0110
0011
... MSB LSB i--

RL A ;rotate left A

-
-'RITHMETJC, LOGIC INSTRUCTIONS, AND PROGRAMS
135
' ul tor are rotat
ed left one bit, an
. aJ1\

. from the MSB (most signi6can1
d bt D7 eJOtS .~
I ,
ill rotate left, the 8 bits of ~e.accum . a See the code and d1agr . ~'.
bit) and enters into DO (least s,gruficant bit).
~e- -LSB~
,.j
HOV A, #?2H ; AOlll 0010
RL A ;A lllO 0100
RL A , A=l lOO 1001
fl re affected.
Notice in the RR and RL ills!nlctions that no ags a

Rotating through the carry .-, flag. Each is sho,-.,n next.


They involve the c- ,
There are two more rotate illslnlctions in the 8051
RRC A ; rotate-i,ight through carry th MS
and the carry flag enters e B.
fl
1th LSB to the carry ag, fl ts if t
ln RRC A as bils are rotated from left to right, they ex e th MSB In reality, the carry ag ac as I IS
ln other words, in RRC A the LSB is moved to CY and CY is moved to e
part of register A, making it a 9-bit register. ~-------------,

CLR
MOV
C
A,#26H
;make CY O
;AOOlO 011\ L1MSB LSBf-CYJ
RRC A ;AOOOl 00 CYO
RRC A ;AOOOO 10 l CY l
RRC A ; A='i:,pOO 01 0 CYl
..,.. ...
RLC A ;rotate left through carry

ln RLC A, as bits are shifted from righl lo left they exit the MSB and enter the carry flag, and the carry flag enters
the LSB. ln other words, in RCL the MSB is moved to CY (carry flag) and CY is moved to the LSB. See the foUo,ving
code and diagram.

SETS C ill\ake CY=l


MOV A,ijlSH ;A=OOOl 0101
RLC A ;AOOlO 1011 CYO
RLC A ;AOlOl 0110 CYO
RLC A ;AlOlO 1100 CY=O
RLC A ;A-0101 1000 CY=l

Serializing data
Serializing data is a way of sending a byte of data one bit at a tim .
are two ways to transfer a byte of data seriaUy: e through a smgle pin of rnicrocontroller. There

I. Using the serial port. In using the serial port pmg


transfer. Thedet:iils of serial port data transf:r are d : " : :;:~every limited control over these uence of data
2. The second method of serializing dat., is 10 transf d hapter 10. q
spaces .m beM..veen them. ln many new generatio erf data one b't I t
a a time and c
th~ devices are becoming popular since they ta::S ~ evices such as LCD, ADC ontro1 the sequence of data and
topic next. e ess space on a printed cir . boarand ROM, the serial versions ol
cuit d. We djscuss this important
, byte of data se<iall y (one bit " a time). Repeating the following sequence 8 tunes will t<ansfe< an enti,e byte, as shown

in Example 6-28.

RRC A ;move the bit to CY


MOV Pl . 3, C ;output carry as data bit
Exa,nple 6-29 shows how to bring in a byte of data se,ially one bit at a time. We will see how to use these concept,;
in Chapter 13 for a seriaJ ADC chip.

Example 6-28 /
Write a program to transfer value 41H serially (one bit at a time) via pin P2.l. Put two highs at the start and end
of the data. Send the byte LSB first.

Solution:
MOVA,#41H
P2.1
SETB ;high
P2.l
SETB ;high
MOVRS,#8
HERE: RRC A
MOV P2.l,C ;send the carry bit to P2.1
DJNZ RS,HERE
SETB P2.l ;high
SETB P2.l ;high

I
I l
'-~D7~-_ _ _RE_G_A_ _ _JI__Jt-1-----,---l..~1CY't-- ~1 I
--1..
PIN
P2.1
DO

Example 6-29
Write a program to bring in data in serial form an d send Jt
. out in paraJlel form

Solution:

8051
- - --.! PO.O
Pl

Let us take in data through port pin PO.O and transnut


. 1t
. through Pl.

MOV R0,#08 :counter for 8 bits


SETB PO .0 ,make PO .O an in
BACK: ~ P O . O ;move data from ~~to~rt
..._.t~c __~ ;rotate right,the dat nto the carry bit
OJNZ RO,BACK ;repeat until all a goes from 'CY ' i
MOV Pl,A ; the data is now ta bits are moved in nto A
BND
ranaferred. 1n parallel to Pl

-AR.ITH.M
ETIC, LOGIC INSTRUCTIONS, AND PROGRAMS
137
' Single-bit operations with CY . etic and logic a
. n structions, in the 8051 there are ,t
. ed .

Aside from the fact that the carry Oag (CY) is altered by arat~ These jJlstructions are last an Table 6-4.1 ""<l
Of '"' -= ,
several instructions by which the CY flag can be rnanipulated directl~ LR. and 5E"[B in n'lany exao1ples in the
T,s<, 64. - h,~ . , , _ " ' "" of JNC a;,;,
e ,obi< 64, >cl"d;og oo= de,JJ:' ..
...,,_Th<"" fow ~"" ,,~ Smpl< PP"" ""' ol<I ~ g"<

r--~~~----------------~--
the logic operations AND and OR.

Exmplc r,.30bit operations, write a program to blink continuously an LED connected to Pl .2, with a delay between-
Usmg carry

each ON and OFF states al the LED.

Solution:
,complement the carry bit
BACK: CPI, C
MOY Pl.2,C ;move i t co pin Pl.2
ACl\t.t. DELI\ y ;cal l a delay
SJMP BACK ;repeat continuously

Table 6 4: Carry Bit-Related Instructions


Instruction
SETB C f unchon
,
make CY -1
CLR C clear carry bit (CY = 0)
CPL C complement carry bit
MOV b,C copy ~rry status to bit location (CY = b)
MOV C,b copy bit location s tatus to ca (b
/NC target
JC target Jump to target if CY - 1
ANL C,bit AND CY with
AND . b',t and save it on CY
ANL C,/bit CY wath inverted bit a
ORL C,bit OR CY with b't nd save it on CY
ORL C,/bit ORCY, . , ' and save it on CY
vtth inverted b't
, and save it on CY

Ex~mpJe r,.31

0Assume that bit P2 2 I~


. US<.-d t
n lhe outside hght ,ind o control an outd . and b1t P2
tum off the inside one oor hght
Solution: .5 a light ,lnS1de
. a build.ng. Show how to 111111

SETB C ;CY 1
ORt. C,P2 . 2 ;CY P2.2 0
HOV P2 . 2,C 'turn i
t
Red "ith cy
"on if
CLR C ;CY. 0P2 S not al
AN!, C, P2 . 5
;CY ready ~on
. ANl>ed
MOY P2.5,C With cY
:turn it Off if not
already Off

138
. . X-OR which has the mnemonic . in
Here we u.se another logical operation, 1.e., E . R2
sum of the number obtained from port 1 and a number m .

Solution: , . ht' ans the nu mber of ls in it. Here it


. , b. ary numbe rs. Weig me
Modulo-2 addition is a n EX-OR operation on tw o m d ffe rent.
implies the number of bit positions in which the two numbers are J

e.g. 1101 the two numbers, we get 1110.


0011 Doing EX-OR opera tion on
1110 This is the modulo-2 sum
The weight of the modulo-2 sum is . l +1+ 1+O= 3

; load the number of b its in RO
MOV RO, #08
MOV Rl,#0 ;make Rl=O
MOV Pl, #OFFH ;make Pl an input port
MOV A, Pl take in one number from port 1
'
;EX-OR the numbers
XRL A, R2
BACK: RLC A ; rot ate left through carry
JNC AGAIN ;check for carry
!NC Rl ;if CY l , add one to count
AGAIN: DJNZ RO, BACK ;repeat 8 times
END ; end of file
The register RI contains the result

SWAP A
Another useful instruction is the SWAP instruction. It works only on the accumu lator (A). It swaps the lower nibble
and the higher nibble. In other words, the lower 4 bits are put into the higher 4 bits, and the higher 4 bits are put into
the lower 4 bits. See the diagrams below and Example 6-33.

before: 07-04 1 03 -00


after:
SWAP D3-DO II 07 - 04

before: after:
01,1 11 0010
SWAP 0010 11 011 1

.
.
Example <,.33

I PO.O . P0.3 ~/ 8
0
Pt.4 Pt.7
... 5
t

Port bnes PO.Oto P0.3 are uaed lo talre in a '-bit data from an
' Ollnected to port liMs Pl.4 to Pl.7 of port t. Write a Jll'OgilD'I 1:'::c,~ Thie data ii lo be dilplaywd on 4 IJQl&
-A llffltMETJC, LOGIC [NSTRUcnONS, ANO PROCRAMs
'' .

139
'
. s useful data
Solution: patt: conc.<1 10 f ;,. are O
. ake PO an input nlY po-P3 4 bit:S o
MOV PO , IOPFH ,m ftom po, o uppeX' is now in the
,move data Now the data
MOV A,PO AND it with oFH, he useful
ANL A, MOPH 'bbles, t bits of Pl
;s1o1ap the n1 f A per
SIIAP A upper nibble o Pl Now the up
'move cbe data to '
ibble o f PO
MOV Pl,A . t.h e 1ower Jl
'' ';contain

Review Questions . ;nsttuctions?


h f the foUow111g
I. What is the value of register A alter eac o
MOV A, #25H
RR A
RR A
RR A
RR A f u 1nsttuctions?
2. What is the value of register A after each of the o ow111g
MOV A , #A2H
RL A
RL A
RL A
RL A

CLR A
. , . ?
3. What is the value of register A after each of the following 111Sttucttons. -
S&TB C
RRC A
SETS C
RRC A
4. Why does "RLC RI" give an errorin the 8051?
S. What is in register A after the execution of the following code?
MOV A , #S SH
SWAP A
ANL A, #OPOH
6. Find the status of the CY flag after the following code.
CLR A
ADD A,#OFFH
JNC OVER
CPL C
OVER:
7. Find the status of the CY flag after the folloWing cod
CLR C e.
JNC OVER
SETS C
OVER:
8. Find the status of the CY flag after the foUowin od
CLR C gc e.
JC OVER
CPL C
OVER:
9. Show how to save the status of P2.7 in RAM bit 1
10. Show how to move the status of RAM bit locau OCation 31.
on 09 to Pl,4.

140
SECTION 6.5: BCD, ASCII, AND OTHER APPLICATION PROGRAMS .
rith.metic and logic instructions. We will see
In this section we provide some real-world examples on how to use a ewer microcontrollers have a
their applications in real-world devices covered in future chapters. For exam}:' e,~ n crocontrollers provide the
1
real time clock (RTC), where the time and date are kept even when the power ~~iI ;set nu show the application of
time and date in BCD. However, to display them they must be converted to ex , we
logic and rotate instructions in the conversion of BCD and ASCII.

ASCII numbers
On ASCII keyboards, when the key "O" is activated, "011 0000" (30H) is provided to the computer. Similarly, 31H
(0110001) is provided for the key "l", and so on, as shown in Table 6-5. .
It must be noted that although ASCII is standard in the United States (and many other countries), BCD numbers are
universal. Since the keyboard, printers, and monitors all use ASCII, how does data get converted from ASCII to BCD,
and vice versa? These are the subjects covered next. I

Packed BCD to ASCII conversion


Many systems have what is called a real-time clock (RTC). The RTC provides the time of day (hour, minute, second)
and the date (year, month, day) continuously, regardless of whether the power is on or off (see Chapter 16). H owever,
this data is provided in packed BCD. For this data to be displayed on a device such as an LCD, or to be printed by the
printer, it must be in ASCII format.
. To convert packed BCD to ASCII, it must first be converted to unpacked BCD. Then the unpacked BCD is tagged
with 0110000 (30H). The following demonstrates converting from packed BCD to ASCII. See also Example 6-34.

Packed BCD Unpacked BCD ASCII


29H 02H & 09H 32H & 39H
0010 1001 0000 0010 & 0011 0010 &
0000 1001 0011 1001

ASCII to packed BCD conversion


To convert ASCil to packed BCD, it is first converted to un a k d BCD (
make packed BCD. For example, for 4 and 7 the ke board v p c e toge~ nd of the 3), and then combined to
"0100 0111", which is packed BCD. This process is fuustrat~ ;::. and 37, respectively. The goal is to produce 47H or

Table 6-5: ASCII Code for Digits o. 9


Key ASCII (hex) Binary BCD (unpacked)
0 30 0110000 0000 0000
1 31 0110001 0000 0001
2 32 0110010 0000 0010
3 33 0110011 00000011
4 34 0110100 0000 0100
5 35 011 0101 0000 0101
6 36 0110110 00000110
7 37 0110111
00000111
8 38 0111000
00001000
9 39 0111001
00001001
-
~ETIC, LOGIC INSTRUCTIONS, AND PROGRAMs
1,1
' D to two ASCII numbers and
acked BC
E,wnple 6-34 Write a progtaJI\
to convert P
..-istcr 0
A has packed SC '
Assume ,L.t
u"" .,,
plce them in R2 and R6 -

Solution:
:A=29H, packedfB~~ data in R2
.
MOV A, #29H . keep a copy O ibble (As09)
MOV R2 A ' er n ,)
'
ANL A' "~OFH mask the upp ll A39H ('9
tan ASC ) .
A,#30H ;make, 9H ASCll char
ORL save it (R63 , i nal data
MOV R6,A ' et the orig )
MOV R2 ;A=29!l , g 'bble(A20 !
ANL
A,
A, "OFOH mask
the lower
c
n1
,rotate rigut
RR A ; rotate right
RR A ; rotate right
RR A rotate right, (A02)
RR A ';A~32H, ASCII Ca: h '2'
ORL A, #30H ASCII char in R2 '
MOV R2, A ; save . . le "SWAP A" instruction.
th
Of course, in the above code we can replace all e RR instructions with a sing

Key ASCII unpacked BCD Packed BCD


4 34 00000100
7 37 00000111 01000111 or 47H

MOV A,# ~4' hex for ASCII char


; A.=34H, 4
ANI. A, #OFH ,mask upper nibble {A04 )
SWAP A ;A40H
MOV B,A
MOV A,# 1 7' ;Rl=37H, hex for ASCII char 7
AN1, A, #OFH ;mask upper nibble (Rl=07 )
ORI. A,B ;A 47H, packed BCD

After this conversion, the packed BCD numbers are processed and the result will be in packed BCD format. As Wt
saw earher in this chapter, a special instruction, "DA A", requires that data be in packed BCD fo rmat.

Using a look-up table for ASCII

In some applications it is much easier to use a look-up table to get the ASCIJ charact . eed This a widell'
-' kb d th
used concept m mte, ,acmg a ey oar to e m,crocontroUcr. This is shown in Example . _ erwen . 1
5
6 35

Example 6-35

Assume that the lower three b,ts of P1 are connected to three swit h .
ASCU characters to P2 based on the status of the switches. c es. Wnte a Program to send the followllll
ooo o
001 'I'
.
010 '2'
OH '3'

142 I
THE 80S1 MICROcoNT -
ROLLER AND EMBEDDED sYS'fDd
100 4'
I

101 '5'
110 '6'
111 '7'

Solution:
MOV OPTR, #MYTABLE
MOV A,Pl get SW status
A,#07H
;mask all but lower 3 bits
ANL
;get the data from look-up table
MOVC A,@A+DPTR
MOV P2,A ;displ ay value
SJMP $ ; stay here
----------------
, ------ ---- -- ---
ORG 400H
MYTABLE DB '0' I 'l' I '2' I '3' I '4' I '5 ' I '6', '7'
END

You can easily modify this program for the hex values ofO- P, which are supplied by 4x4 keyboards. See Chapter
12
for a keyboard example.

Checksum byte in ROM


To ensure the integrity of the ROM contents, every system must perform the checksum calculation. The process of
checksum will detect any corruption of the contents of ROM. One of the causes of ROM corruption is current surge,
either when the system is turned on or during operation. To ensure data integrity in ROM, the checksum process uses
what is called a clrecksurn byte. The checksum byte is an extra byte that is tagged to the end of a series of bytes of data.
To caJculate the checksum byte of a series of bytes of data, the following steps can be taken.

1. Add the bytes together and drop the carries.


2. Take the 2's complement of the total sum; this is the checksum byte, which becomes the last byte of the series.

. '.o perform the checksum operation, add all the bytes, including the checksum byte. The result must be zero.
lf 1t 1s not zero, one or more bytes of data have been changed (corrupted). To clarify these important concepts see
Example 6-36. '

-
Example 6-36

Assume that we have 4 bytes of hexadecimal data: 25H 62H 3FH d 52H
(a) Find the checksum byte, (b) perform the checksum o~eration t 'an .
62H has been changed to 22H, show how checksum detects the e::r:ure data integrity, and (c) if the second byte

Solution:
(a) Find the checksum byte.
25H
+ 62H
+ 3F'H
+ S2H
118H (Dropping the carry of l, we have 18H I ,
byte is ESH.) ts 2 8 complement is ESH. Therefore the checksum

-.\RfrliMETIC, LOGIC INSTRUCTIONS, AND PROGJlAMs


.

143
I
' re data ;,,1egntr
rerfonn the checksum operation to cnSU
(b)
25H
62H
t 3PH
s2H . not corrupted,)
' ESH . ' 00 indjcating data tS
200H (Dropping the cames, "e see ' checksum detects the error.
22H show how
If the Sl'<Ond byte 62H has been changed to ' ,'.
(c)
25H
+ 22H
+ JPH
+ 52H . d that means data is corrupted.)
+ 58H . 00
COH ,~hich ,snot ' an
lCOH (Dropping the carry, we get ,
I

Checksum program in modules


The checksum generation and testing program is given in modular form. We have divided ~e p~ogram into several
modules (subroutines or subprograms) Dividing a program into several modu!es (called fun~tlons in C programnung)
allows us to use its modules in other applications. It is common practice to d1v1de a program mto several modules, Ifs! .
each module, and pul U1em into a library. The checksum program shown next has three modules: It (a) gets the tbt,
from code ROM, (b) calculates the checksum byle, and (c) tests the checksum byte (or any data error. Eacho( the!!
modules can be used in olher applications.
"
Checksum Program
;CALCIJLATrNG ANO TESTING CHECKSUM BYTE

DATA_AODR BQU 4 00H


COUNT EQU 4
Rl_AODR EQU JOR

;---------------main program
ORG 0
A.CALL COPY DATA
A.CALL CAL_CHKSUM
A.CALL TEST CHKSUM
SJMP $ -
,.. -- --- ---------calculating checksum byte
...
CAL CHKSUM: ;load data address
- MOV Rl,#RAM_ADDR
MOV R2,#COUNT load count
I
clear accumulator
CLR A , . re carries
A, @Rl
;add bytes and igno
H2: ADD
INC Rl increment Rl
';repeat for all
DJNZ R2,H2
CPL A l's complement byte )
A
:2 s complement(checksum
INC
MOV @Rl,A ;save it in data RAM
RET

---- ------------testing checksum byte


'
TEST_ CHKSUM:
MOV Rl,#RAM_ADDR ;load data address
MOV R2,#COUNT+l ; load counter
CLR A ;clear accumulator
A,@Rl ;add bytes and ignore carries
H3: ADD
INC Rl increment Rl I

DJNZ R2,H3 ;repeat for all


JZ G l ;is result zero? then good
MOV Pl,# ' B' ;if not, data is bad
SJMP OVER I

G 1: MOV Pl,#'G ' ;data is not corrupted


-
OVER: RET

-------- -- --- ---my data in code ROM


'
ORG 400H
MYBYTE: DB 25H, 62H, 3FH, 52H
END

Binary (hex) to ASCII conversion


Many ADC (analog-to-digital converter) chips provide output data in binary (hex). To display the data on an
LCD or PC screen, we need to convert it to ASCII. The following code shows the binary-to-ASCII conversion pro-
gram. Notice that the subroutine gets a byte of 8-bit binary (hex) data from Pl and converts it to decimal digits,
and the second subroutine converts the decimal digits to ASCII digits and saves them. We are saving the low digit
in the lower address location and the high digit in the higher address location. This is referred to as the Little-Endian
convention, that is, low-byte to low-location and high-byte to high-location. All Intel p roducts use the Little-Endian
convention.

Binary-to-ASCII Conversion Program


;CONVERTING BIN (HEX) TO ASCII

RAM_ADDR EQU 40H


ASCI RSULT EQU SOH
COUNT - EQU 3

:--- - --- - --- - ---- main pr ogram


ORG 0
ACALL BIN_DEC_CONVRT
ACALL DEC ASCI CONVRT
SJMP $
- -
-
AllrrHMmc,. LOGIC INSTRUCTIONS, AND PROCRAM5
lM
' ---------Convercing
(oo -f' F
TO 0 00-255)
tnese RAM
locations

~;;~;~~coNVRT:
- MOV RO,#RAM_ADDR
MOV A,Pl
MOV B,#10
OIV AB
MOV @RO,B
INC RO rnore
10 once
MOV B,#10 divide by t digit
OIV AB -save t h e ne"
MOV @RO,B ' . .t
INC RO 1ast d1g1
-save the

MOV @RO,A
RET
1 ASCII digits
to displayab e
DEC digits
----------------Converting
DEC ASCI CONVRT: f oEC data
- - MOV RO, #RAM_ADDR ;addr of ASCII data
Rl, #ASCI_RSUl,T ;addr o
MOV
R2,#3
count
MOV
MOV A,iiRO '.get DEC digit digit
BACK: ;mal<e it an ASCII
ORI. A,# 30H
MOV @Rl ,A ;save it
INC RO next digit

INC Rl ;next
DJNZ R2,BACK ;repeat until the last one
RET

;---- ---- --- ------------------- ---- ---- ---- ---- ---- --- ------- - - - - .. ----- -- - -- ---- ------~
ENO

Review Questions
1. For the following decimal numbers, give the packed BCD and unpacked BCD representations.
(a) 15 (b) 99
2. Show the binary and hex formats for "76" and its BCD version.
3. Does the register A have BCD data after the following instruction is executed?
MOV A,#54
4. 67H in BCD when converted to ASCll is Hand H.
s. Does the following convert unpacked BCD in register A to ASCU?
MOV A,#09
ADD A, #JOH
6. The checksum byte method is used to test data integrity in
7. Find the checksum byte for the following hex values: 88H H A (RAM, ROM).
8. True or false. If we add all the bytes, including the checksU:,,99b ' AH, BBH, CCH, DOH
yte, and the result is FFH, there is no error in !ht dill-
SUMMARY
This chapter discussed arithmetic instructions for both .
all 8 bits of the byte for data, making a range of Oto 25S d signed and unsi ed .
-
ta.-
making a range or -128 to+ 127 decimal ectmal. Signed datgn data_ t.r\ the 8051. Unsigned di_ biL
Binary coded decimal (BCD) data represents the d" . a uses 7 bits for data and 1 for the siS"
discussed. The 8051 contains special instructions for a i_g,ts Ot_hrough 9. Bot
In coding arithmetic instructions for the 8051, s~~etic Operatio h Packed and unpacked BCD fortJlllS wflf
ttention hast':~n ~ data.
1
flow condition.
given to the possibility of a cartY or~
146
T ~ __.,
ocoN'ra - ..-.
OttEa AND EMBEDDED SW...-
. OR and complement. In addition, 80?1 Assembly
This chapter also defined the log}c instructions ~ , iR~Xare 'and jump instructions were descnbed as well.
e instructions for these functions were described. o p 1
ag
tangu
func
marupu
tions are often used for bit l a ti o n purposes.
. li ations s uch as sena1 d ev1ces. This chapter a so
These 051 d ITT many a pp c
The rotate and swap instructions of the 8 are use f ts and conversions.
described checksum byte data checking, BCD and ASCIJ orma '

PROBLEMS
SECTION 6.1: ARITHMETIC INSTRUCTIONS
1. Find the CY and AC flags for each of the following. (c) MOV A, #OFFH
(a) MOV A, #3FH (b) MOV A, #99H SETB C
ADD A,#4SH ADD A,#58H ADDC A,#00
(f) CLR C
(d) MOV A, #OFFH (e) MOV A, #OFEH
MOV A,#OFFH
ADD A,#1 SETB C
ADDC A,#01 '
ADDC A,#01
ADDC A,#0
d th s Jt in R3 The resuJt m ust be in BCD.
2. Write a program to add aJl the digits of your ID number an save . e re u . a ta is s tored in on -chi ROM.
3. Write a program to add the following numbers and save the result ITT R2, R3. The d P
ORG 250H
MYDATA: DB 53, 94 , 56, 92, 74, 65, 43, 23, 83
4. Modify Problem 3 to ma ke the result in BCD. . ,
s. Write a program to (a) write the value SSH to RAM locations 40H - 4FH, and (b) add all these RAM locations con -
tents together, and save the result in RAM locations 60H and 61H. .
6. State the steps tha t the SUBB instruction will go through and for each of the following.
(a) 23H - 12H (b) 43H - 53H (c) 99 - 99
7. For Problem 6, write a program to perform each operation.
8. True or false. The "DA A" instruction works on register A and it must be used after the ADD and ADDC
instructions.
9. Write a program to add 897F9AH to 34BC48H and save the resul t in RAM mem ory loca tions s tarting a t 40H.
10. Which lags a re affected by the multiply and divide instructions?
11. Write a program to multiply two numbers s tored in R.AM locations 35H and 36H, and s tore the result in the next
two locations.
12. Multiply two numbers which are stored in program ROM locations 0100H and 0101H. The resuJt is to be s tored in
any RAM location of 8051.
13. Divide the content of RAM location 45H b y the content of location 46H, and store the resuJt in the next RAM
locations.
14. Which are the registers used by the multiply and divide instructions?
15. Writ~ a program with three subroutines to (a) ~ransfer the following data from on-chip ROM to RAM locations
starting at 30H, (b) add them and save the result m 70H, and (c) find the average of the data and store it in R7 N 0 ti
that the data is stored in a code space of on-chip ROM. ce
ORG 250H
MYDATA: DB 3 , 9 , 6 , 9, 7, 6, 4, 2 , 8

SECTION 6.2: SIGNED NUMBER CONCEPTS AND ARITHMETIC OPERATIONS


16. How does the 8051 represent the following numbers?
(a)-21 (b) --46 (c) 120 (d)-110 (e) 9CH
17. Th~ memory addresses in computers are (signed, unsi ed n
si;
18. Wnte a program for each of the following and indicate the status th) O~~ers.
0
(a)(+lS)+(- 12) (b)(- 123)+(-l2 7) e agforeach.
(c) (+25H) + (+34H) (d) (- 127) + (+127)
19. Find the result of the following operations and state wheth th
adrution operations. er e 0 V and CY flags will be set after the following
(a)-100 and +23 (b) +56 and +97
(c) +100 and +25
20. Explain when the OV flag is raised. (d )-122 and-75
..,
AllllHMrnc, LOGIC INSTRUCTIONS, ANO PROGRAMs
1C7
' .
I ,.
_ ~'/hichregisterholds theOV Bag? f
21 Write program to detect the status o the
22
OV flag.
."~
'#'
,rn COMP ARE INSTRUCTIONS 90 perform the following operati0ns,
SECTION 63: LOGIC ru,v B _ 56 and Rl "'
A-fO - '
23. AsSume that these registers contain the f~U?wmg. - '
Indicate the result and the register where 1t 1s stored.
Nott: The operations are independent of each other .
(a) ANL A, #45H (b) ORL A, B
(c) XRL A, #76H (d) ANL A, RJ.
(e) XRL A, Rl (I) ORL A, RJ.
(g) ANL A, #OFFH (h) ORL A, @9911
I (i) XRL A, #OEEH ij) XRL A, #OAAH
24. Write instructions to do the foUowing, ~
(a) complement the content of RAM location 38H t/$
(b) mask the upper4 bits of A .;,
(c) get the result of ANDing OC6H and 97H l~
(d) E.x-OR the contents of A and R1
(e) make the lower nibble of RS, the high nibble . . t f R3 with 6 7H illl
25. Find the error in the foUowing instruction if the intention 1s to compare the con ten .t:
CJNB R3,67H, HERE t
26. Is the following a valid instruction? "ONE R4, #67,HERE" (,0
27. Does the 8051 have a "CfE" (compare and jump if equal) instruction? llO'
28. Indicate the status of CY after CjNE is executed in each of the following cases.
(a) MOV A, #25H (b) MOV A, #OFF!! mu
CJNE A,#44H,OVBR CJNE A,#6Fl!,NEXT
tll'.
(c) MOV A, #34 (d) MOV RJ.. #0
C:JNE A,#34,NEXT C:JNE Rl.#0,NEXT Jr!
(e) MOV RS, #54H (I) MOV A, #OAAH l!];
C:JNE RS,#OFFH,NBXT ANL A, #SSH 1011
CJNE A, #00, NEXT Ill
29. In Problem 28, indicate whether or not the jump happens for each case. 11.1
lllO
SECTION 6.4: ROTA TE JNSTRUCTION AND DATA SERIALIZATION llil
30. Find the contents of register A after each of the folio . . t lid
(a) MOV A #56H (b) wmg IS executed. C!111
SWAP A' MOV A, #39H
CLR C li!t
6~

-
RR A RL l\
RR A RL A
(c) C:LR C (d) SETB C ~~
MOV A, #40H MOV A,#7l\H
SWJ\P A SWJ\P l\
iii I
RRC l\ t)'
RLC A
RRC: A RLC A l ~,
RRC: A
31. Show the code to replace the SW AP od
(a) using the rotate right instructio~ e.
\\"
(b) usmg the rotate left instructions
32. ~tare the addressing modes for the
~
33. "'.nte a program that finds the position~~ OR~ instnictions?
Give the result for68H.
34. If A ~ 901-1, what is the content of A aft
(a) RR A (b) RL A ( j'
e st high in an 8-b"
the folloWing instnicti
.
it data item. Th .
e data IS scanned from 00 to 0:
"
~
35 A stepper motor uses the following ~u~o:b. (d) l\R~ns, if CY'=1? ~
~
1100, 0110, 0011, 1001 U\a.ryOUJnbers to move
A th
e ltlotor H ow would you generate t1,e111 l
148
THEsos1 MICQo ~
~
CON"fROLLQ -
A.No EMBEDDED s ~
SECTION 6.5: BCD, ASCfi, AND OTI-IER APPLICATION PR(x;RAMS
36. Write a program to convert the following packed BCD 0111 0101 number to two binary numbers and transfer
these numbers to registers RO and R1.
37. Write a program to convert a series of ASCil numbers to packed BCD. Assume that the ASCII data is located in
ROM locations starting at 300H. Place the BCD data in RAM locations starting at 60H.
ORG 300H
MYDATA: DB "87675649"
38. Write a program to get an 8-bit binary number from Pl, convert it to ASCII, and save the result in RAM locations
4?H, 41H, and 42H. ~at is the result if Pl has 1000 1101 binary as input?
39. Find the result at pomts (1), (2), and (3) in the following code.
CJNE A,#50,NOT_EQU
;point (1)
NOT_EQU: JC NEXT
;point (2)
NEXT:
A th
;point ( 3)
40 chssume at thp e lower four bits of Pl are connected to four switches. Write a program to send the following ASCII
aracters to 2 based on the status of the switches.
0000 'O'
0001 'l'
0010 '2'
0011 '3'
0100 '4'
0101 '5'
0110 '6'
0111 '7'
1000 '8'
1001 '9'
1010 'A'
1011 'B'
1100 'C'
1101 'D'
1110 'E'
1111 'F'
41 . pmd the checksum byte for the followin ASCII
42. True or false. If we add all the bytes, in~udin :;:::ge: "Hello"
the data. g ecksum byte, and the result is OOH th .
43. Write a program: (a) To get the data "Hello ' en there is no error in
sum byte, and (c) to test the checks ' my fellow World citizens" from code RO
44. Find the ASCII equivalent of th f umll ~yte for any data error. M, (b) to calculate the ch eck-
(a) # (b) " e o owmg characters:
(c) < (d) o/o
(e) @ (f) &
:: To display data on LCD or PC monitors it must b .

~:~~~ :;~t!e~ ~rite~


Assume that the lower four bits of Pl ar~ co em (BIN, BCD ASC
~acters t~O': based on the status of the s:t::: p ro!m to send the followin ASCII
00
0001 'l' -up table method. g

0010 '2'
0011 '3'
0100 '4'
0101 'S'
0110 '6'
0111 '7'
1000 '8'
1001 '9'
-
.\JlrntMETic, LOGIC INSTRUCl10NS, AND
' ANSWERS TO REVIEW QUESTIONS
SECTION 6.1: ARJTHMETIC INSTRUCTIONS
1. A, B
2. A, B . =ration.
3. No. We must use registers A and Bfor this Or-
4. A, 8
'. 5. A, B tion
6. No. We must use registers A and B for this opera
I
'
7. A, the accwnulator . n
8. No. We must use registers A and B for thiS operat,o
9. MOV A, Rl
ADD A,R2
10. A, the accumulator
I' 11. (a) A= OOand CY= 1 (b) A= FF and CY =0 0100 0011
12. 43H 0100 0011 + !_111 1011
~ 0000 0101 2s complement
3EH 0011 1110
13. A=95H-4FH-l=45H

SECTION 6.2: SIGNED NUMBER CONCEPTS AND ARITHMETIC OPERATlONS


I. 07
2. 16H is 00010110 in binary and its 2's complement is 1110 1010 or -16H = EA in hex.
3. -128 to +127
4. +9 = 00001001 and -9 = 11110111 or F7 in hex.
5. An overflow is a carry into the sign bit (D7), but the cai:ry is a carry out of register (07).

SECTION 6.3: LOGIC AND COMPARE INSTRUCTIONS


I. (a) 02 (b) FFH (c) FOH
2. Zeros
3. One
4. All zeros
5. False
6. #53
7. 66H

SECTION 6.4: ROTATE INSfRUCTION AND DATA


1. 52H SERIALIZATION
2. 2AH
3. COH
4. Because aU the rotate instructions work with th
5. SOH e accumulator onl
6.CYO y
7. CY= 1
8. CY=l
9. MOV C, P2.? ;save statue of P2 7
MOV 31,C :save carry in RAM.b on CY
10. MOV C, 9 ;save status of RAM!~ location 06
MOV Pl.4,C ;save carry in Pl ,4 it 09 in CY

SECTION 6.5: BCD, ASCII, AND OTHER APPLICATJQ


1. (a) 15H = 0001 0101 packoo BCD 0000 1 N l'RoCRAMs
(b) 99H = 10011001 packed sco' 0000 ~ .0000 0101
' 001.00001001 unpacked BCo
150 unpacked BCD

llit~
CRacoNTao ___.
LLR AND EMBEDDED~
, o. \\'t n, i.'d to ,, nti' 1t c..i11 (,, 1th th~ f-1} i,r OH)\ ll Il\)B t,, n,al, 11 1n B(l) Th, \ ,,lu, ~ 1 ,, 1th,,11t th Ht I" ,., 1ntl'r
1 ,-3oH 001101 l l 0.11101 \0B anJ an BCO ,,, h.ivt' 7(11l 0111 01 IOB
,
rn.-tl"d .... Joli b~ th\ ..~ mbl,r.
t ,)tit{, 11li
5., \t ,ini.\' \ .:Wtl
6 R tl\I \IQtl + 1\ ,\H + BBlt
1 li + OD11. 4~n1. 0n,pping th c11m ,, ha~c, 2Fl I, enJ 1t 2'., '-ompl mc..-nt i
Dlt~
f1l

-'lnHMrnc, lOCIC INS I AUCTIONS, AND . .


ocw.
CHAPTER 7
' I

8051 PROGRAMMING IN C I

OBJECTIVES

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

Examine the C data type for the 8051


Code 8051 C programs for time delay and I/0 operations
Code 8051 C programs for 1/0 bit manipulation
Code 8051 C programs for logic and arithmetic operations
Code 8051 C programs for ASCD and BCD data conversion
Code 8051 C programs for binary (hex) to decimal conversion
Code 8051 C programs to use the 8051 code space
Code 8051 C programs for data serialization
' Why Program the 8051 in C?
,ml d into the
. ntroUer. The size of the hex me
ROM of the IJ\lcroeo for two reasons:
.,,-ain01ers,
Pf;,
compilers produce hex files that we do, ~ 1 crocontroller pro,,-
O
duced by the compiler is one of the roam concems nil

I. M,crocontrollers have limited on-chip ROM.


2. The code space for the 8051 is limited to 64l< byteS-
. raO'l size? While Assembly language pro-
I ffect the compiled prog tedious and ti.me consurnm
How does the choice of progr-amming language a . . A5SCO'lbly Janguage JS g. C
~ ~
. .
~ duces a hex file that is much smaller than C, progr~U\g much easier to write, but the hex file_ ~ize produCE,j
programming, on the other hand, is less time consummg an are some of the major reasons for ,vntmg programs in
much larger than if we used Assembly language. The following
C mstead of Assembly:

I. It is easier and less time consuming to write in C than Assembly.


2. C is easier to modify and update.
3. You can use code available in function libraries.
4. C code is portable to other microcontrollers with little or no modification.

The study of C programming for the 8051 is the main topic of this chapter. In Section 7.1, we discuss data types
and lime delays. J/0 programming is shown in Section 7.2. The logic operations AND, OR, XOR, inverter, and shi/1
are discussed in Section 7.3. Section 7.4 describes ASCII and BCD conversions and checksums. In Section 7.5 llt
show ho~ 8051 C compilers use the program (code) ROM space for data. Finally, in Section 7.6 data serialization
for 8051 1s shown. I

SECTION 7.1: DATA TYPES AND TIME DELAY IN 8051 C


In this section we first discuss C data types for the 8051 a nd th en prov1'd e code for time delay functions.

C data types for the 8051


Since one of the goats of 8051 c

m,crocontroller

f~=0
.
types for 8051 C. ln other words a programmers IS to create smaller hex fil . .
sn:iaUer hex files. In this section .:e ~n!erstan~mg of C data types for :~ ~~;lworlhwh.ile to re-examine C ~
e spificC data types that are can help programmers to crete
most useful and widely used for the ~I

Unsigned char
Since the 8051 is an 8-bit microcontroUer
The unsigned char is an 8-bit data t Iha ' the character dat., type i5
used dara types for the 8051. In m YP<'. t. tak<?s a value in the r the most natural ch .
we should use the unsi ned cha:~y situations, such as settin aange of O 255 (OO. FF Ol~e for many applicati~
';?
default if we do not put ~e keywo;s,~ea~ 0 ~ ~e signed char.\ counter value, where 1 It _as one of the mo~! width'
data type for a string of ASCIJ charac/151gned in front of the cha~ember that c com .1 ere IS no need for signed dill
characters. See Example 7.3 for =gliners, including extended ASC(see Example 7-J)
Ind bl -., g ports. 1l char
.J'ers use the s,gni'd char a tht
. . 1
ec anng vana es, we must pay careful acters. Exa I 7 also use t h e un.<iKned ......
e can u-
mt ,r po55ible. llc,cause the 8051 has a limited n attention to the Si f mp e 2 shows ,1 Mring ot A5CU
1:
char data type can lead to a larger size hex Iii umber of registers o the data and
C++ for x86 IBM PCs is not a significant issue.e. Such a misuse of th": ;aia RAM loc::i;;o u,;e, _u nsigned chdr ,n.,h...W ol
ata types in corn n~ using th.<.' int in plan ,,I tlW
154 p,1"rs bU,h as M 1cn>"<>fl \'i,1U1I

THE 80SJ
..,,cRoco
NTROLLER -
..,
I

Example 7-1
Write an 8051 C program to send values 00 - FF to Port Pl.
~

Solution: '," "'\


#include <reg51.h> / J "v
void main(void) cf.
{ unsigned z;
f or( z =O ; z<=255; z ++) . I
Pl=Z;
}

Run the above program on your simulator to see how Pl displays values 00 FFH in binary.
r
/
/
Example 7-2
Write an 8051 C progran1 to send hex values for ASCU characters of 0, 1, 2, 3, 4, 5, A, B, C, and D to port Pl.

Solution:
#inc lude <reg5l.h>
void main (void)
{
unsigned char mynum [.] = "012345ABCD";
unsigned char z;
f or (z=01z< ~t; z++ )
Pl=mynum(z];
}

Run the above program on your simulator to see how Pl displays values 30H, 31H, 32H, 33H, 34H, 35H, 41H,
42H, .t3H, and 44H, the hex values for ASCII 0, 1, 2, and so on.

/
V
Example 7-3

Write an 8051 C program to toggle all the bits of Pl continuously.

Solution:
II Toggle Pl forever
#include <regSl.~>
void main(voidl ~
{ 1
for (;;) -4
{
'f-
,
I /repeat forever
PlaOxSS1 //Ox indicates the
PlOxAA;
data is in hex (binary)
}
}

Run the above program on your simulator m1ee how pt ~


by the C compiler. JUltl8 cioatll:-a fly. _. . thl 11 m~ lilbid
-~
~:~ ~~ .- . ' . .. .
~---~~~~~~--
8051 PROGRAMMING INC

155

..
' Signed char
(D7 o f D7
[)O) to represent the - or +
._;i;cant b 1t . . us values from -128 to+ 127. !n . '-
th most S1!Y- giving eel
>al
O f th S1~
The signed char is an 8-bit data type that-'::e0
; the signed ouJll~~perature, the use e s ign char data lypi
As a result, we have only 7 bits for the magni . uantity s uch as
tions where+ and - are needed to represeot a given q . the signed value. For that reason we ~hOlilil
is a must. d unsigned, the default ~ ed nurnbers.
Again notice that if we do not use the keywor be represented as s ign
stick with the unsigned char unless the data oeeds to

Unsigned int of o to 65535 (0000 FFFFH). In the &l5t


The unsigned int is a 16-bit data type that takes value i~i~::elt is also used to set counte r values of ~
unsigned int is used to define J6-bit variables such as mernoryd t taJ<es two by tes of RAM, we mus t not use~
than 2.56. Since the 8051 is an 8-bit microcontroller and the int ata ype ,~ 8-bit chu.n ks, the misuse o f int variables ~-. .
' . . d
mt data type unless we have to. Smee registers a~ memo
ry accesses are u ,
'th megabytes of memory,
32 b'1t P

. ,,.
enbum regts1ai
result in a larger hex file. Such misuse is not a big deal in PCs
and memory accesses, and a bus speed of 133 MHz. Ho,vever,. or I
7 1 256
8051 programming do not use unsigned int in Pla<ii
erate an e rror for this misuse, bu t the overn~
where unsigned char wiU do the job. Of course the compiler.w, 11 00
~e~ ned data (such as setting counter val
in hex file size is noticeable. Also in situations where there ,s no nee . or s,g i d ata dee Iara tion . Aga ues1
we should use unsigned int instead of signed int. This gives a much w,der range or. m, remembir
that theC compiler uses signed int as the default if we do not use the keyword 1msigued.

Signed int
Signed int is a 16-bit data type that uses the most significant bit (015 of D15 DO} to rep resent the - or + value.As
a result, we have only IS bits for the magnitude of the number, or values from -32,768 to +32,767.

Sbit (single bit)

spec,'Iiically to access single-bit addressable regisre~


The sbit keyword is a widely used 8051 Cdata type des'gned
It allows access to the single bits of the SFR regist As I
Among the SFRs that are widely used and are also~~-ad;::~ m Chapter 5, some of the SFRs a re b it-addressable
v1dual bits of the ports as shown in Example 75. e are ports PO P3. We can use s bit to access the in<fi.

IJ
Example 7-4
Write an 8051C program to send values of -4 to +4 to port Pl.

Solution:
//sign numbers
#inc lude <regS l . h>
void mai n (void )
(
char mynumll {+1 -1 + 2 ~ - 2 + 3 3
uns igned c ha r z; , - ,+4,-4 }
f or(zO ;Z<z8;z++) '
Plmynum [zJ; .
J
Run the above program on yQUr simulato 10
the hex values for+ 1, -I ' +2 _2, and so on.r Ste how .,.,, ti;-
-pla
ys "lues of 1
' FFH, 2, FEH, 3, FDH, , . and pClt.
156
Example 7-5
Wnte an 8051 C program to toggle bit DO of the port Pl (P1 .0) 50,000 times.

Solution: .
tiinclude <regSl .h> ~ , ''
~ ~ .'\"'
sbit MYBIT = PlAO; //notice that shit is
~ ~ e t ......,.._-4.t, / /declared outside of main
void main (void )
{ I
unsignedg;,
for (z =O; Z<=SOOOO; Z++)
{
MYBIT - 0.'
MY BIT = l I

}
}

Run the above program on your simulator to see how Pl .0 toggles continuously.

Bit and sfr


The bit data type allows access to single bits of bit-addressable memory spaces 20 - 2FH. Notice that while the s bit
data type is used for bit-addressable SFRs, the bit data type is used for the bit-addressable section of RAM space 20 - 2FH.
To access the byte-size SFR registers, we use the sfr data type. We will see the use of sbit, bit, and sfr data types in
Table 7-1.

Time Delay
There are two ways to crea te a time delay in 8051 C:

1. Using a simple for loop


2. Using the 8051 timers

In either case, when we write a time delay we must use the oscilloscope to measure the duratio f 0 tim d la
Next, we use the for loop to create time delays. Discussion of the use of the 8051 timer to ere te tim dneJo ~ e e Y
until Chapter 9. a e ays ts postponed

Table 7-1: Some Widely Used Data Types for 8051 c


Data Type Size in Bits
Data Range/Usage
unsiged char 8-bit
0 to 255
:igned) char 8-bit
-128 to +127
unsigned int 16-bit
0 to65535
(signd) int 16-bit
-32,768 to +32,767
sbit 1-bit
SFR bit-addressable only
bit 1-bit
sfr RAM bit-addressable only
8-bit
RAM addresses 80 - FFH only

157

..
' In creating a time delay using a for Ioop,
delay.
we must be
iniJ1dful of thfE?<'
factors that can affect the accuracy 01

e fields of re technology an~ rnicropr


tlit

. ed in 1980, both th 3
the number of machine cycles~
3
J. Toe 8051 design. Since the original 8051 ,~as design AS wesa~ in Ch P!e~/ of the 8051 / 52 microcontroller~~
arclutectural design have seen grea! advancements-mong different versOany of the newer generations of th~ Sri
nwnber of clock periods per machine cycle v~ a per machine cycle,; .k periods per machine cycle Whil l
5
the original 8051 / 52 design used 12 clock pen th [)55000 u5es 4 OC ' e t!ie
use fewer clocks per machine cycle. for example, e .
0589C420 uses only one dock per machine cycle. . ,
1ne duratto n of the cloc.k period for the machine eye'-.
.. _
5
2. The crystal frequency connected to the Xl X2 mpul pill
a function of this crystal frequency. . th mpiler used to compile the C program. When
3. Compiler choice. The third factor that affects the time delay ,s ~i~ctions and their sequences used in the dlh
7' .. we program in Assembly language, we can control ~e exact ,erts the C statements and functions to Asse,;;;.1
\
subroutine. In the case of C programs, it is theCcompiler that c~;;I
nt code. In other words, if we compile a . Y
language instructions. As a result, different compilers .produodce e:ifferent hex code. 8'!11
8051 C programs with different compilers, each compiler pr uces
' For the above reasons, when we write time delays for C, we must use the oscilloscope to measure the exact dllll, ,1
lion. Look at Examples 7-6 through 7-8.
'

\ ' Example 7~ .
Write an 8051 C program to toggle bits of Pl continuously forever with some delay.

Solution:
II Toggle Pl forever with some delay in between "'on and off".
#include cregSl.h>
void main (void)
{
unsigned int X;
for ( , ; ) //repeat forever

\~ ,
Pl=OxSS;
for(x=O;x<40000;x++).
Pl=OxAA; '
//delay size unknown
'
-l for(xO;X<40000;x++);

l
:
/
I\/
Exampl 7.7
Wn1e an 805J C program to toggle the bits of P
l ports contin
Solution: uously With a 2SO ms delay

The program below is tested for the


#include <regSl. h> DS89C420 with XTAL
void MSOelay (unsigned int). z 11.0592 Mliz
void main (void) L' '
{ r,v>.,,...
wh~le(l) //repeat forever

158
lli~
Oco,.,
tllott .-
ER AND EMBEDDED S ~
Pl=Ox55; .?
MSDelay (250 ) ;
Pl =OxAA;
MSDel ay (250) ;
}
l
void MSDelay (unsigned int itime )
{
unsigned i n~ i , j ;
for{i =O; i <i time; i ++) ,.r--~
for{j=0;J <l275;j ++ l; '\.
}
Run the above program on your Trainer and use the oscilloscope to measure the delay. ,

V
Example7-8
Write a 8051 C program to toggle all the bits of PO and P2 continuously with a 250 ms delay.

Solution:
'
//This program is tested for the DS89C420 with XTAL = 11.0592 MHz
#i nclude <regSl.h>
void MSDelay {unsigned int);
void main (void) -
{
while (l ) //another way to do it forever
{ I,

( PO=OXSS;
P2=0XSS;
MSDelay(250);
( PO=OxAA;
P2=0xAA;
MSDelay(250);
}
}
void MSDelay(unsigned int itime)
{
unsigned inti, j;
for(isO;i<itime;i++)
fo r (j O;j<l275;j++);
}

Review Questions
1.
2. G!ve the magnitude of the unsigned char and signed char dat
Give the magnitude of the unsigned int and signed int dat a types.
3.
4.
~ we are declaring a variable for a person's age, we shoul; :!'es.
;;,e or false. Using a for loop to create a time delay is not r the - d~ta type.
5. c .1 versions. ecommended if you want your code be portable to other
ive three factors that can affect the delay size.

159
' SECTION 7.2: 1/0 PROGRAMMING IN 1
. 805 CJ/ 0 parts ,,or the 8051- We 1001< at both byte and b11 I

ln this section we look at C prograJ!lOW'S of the l(j

progrrunming.
152
Byte size 1/0 th p0. pJ Jabels as defined in the 8051
As we stated in Chapter4 ports p0 .1'3 are byte-accessible. We u:de':standing of how ports arc accessed in~ h~
file. See Example 7-9. Examin; the next few exaJ11ples to get a t,etter Ste_

~~Ex~am~p1~.1~-9~~~~~~~~~~~~~--:-~::-:::::::::.-;:::-;;::-;;:;:;::-::::-:---..~I
LEDs are connected to bits Pl and P2. Write an SOS! C program that shows the count from OI? FfH (0000~19
7',
111l 1111 m binary) on the LEDs.
' Solution: O () () (] S D O <)

'
#include <regSl . h>
#define LED P2 V' I /notice how we can de.fine P2 "" D
void main (void) 0 0 U
(
PlOOY //clear Pl
LED~, //clear P2
for ( ; ; ) //repeat forever
{
Pl+:-t; I I increment Pl
LED++; //increment P2
)
l ltl
llt
II!
Example 7-10 ll!a
Writean8051C
program to get a byte of data fro . 61 ..,s ai
Solution: m Pl, wait 1/2 second' and t hensendittoP2

#include <regSl.h> .
void MSDelay(unaigned .
void main(voidl int);
{
unsigned charm b
PlOXPF y yte;
' I /make Pl an input po
while (l) rt

"
{ mybyte:Pi.
HSDelay(s~o(.
//get abyte from Pl

}
P2amybyte
. ' //send it to P2
}
voi{d HSDelay (unsigned i nt itime )

unsigned inti, j
for(iOi<1t
,' '
ime;i+)
} for(JO;j<l27S;j++);

160
.

xample 7-11 . . s than 100 send it to Pl; otherwise, send it to


Write an 8051 c program to get a byte of data from PO. If it 15 Jes '
P2.
Solution:
#include <regSl.h>
void main (void)
{
unsigned char mybyte;
PO=OxFF; //make PO an input port J
while (1)
{
mybyte=PO; //get a byte from PO
if(mybyte<lOO)
Pl=mybyte; //send it to Pl if less than 100 I

else
P2=mybyte; //send it to P2 if more than 100
}
}

Bit-addressable VO programming
The I/ 0 ports of PO - P3 are bit-addressable. We can access a single bit without disturbing the rest of the port. We
use the sbit data type to access a single bit of PO - P3. One way to do that is to use the PxAy format where x is the port
0, 1, 2, or 3, and y is the bit O - 7 of that port. For example, P1A7 indicates Pl.7. When using this method, you need to
include the reg51.h file. Study the next few examples to become familiar with the syntax.

Exam.pie 7-12

Write an 8051 C program to toggle only bit P2.4 continuously without disturbing the rest of the bits of P2.
Solution:
/ / toggling an individal bit
#include cregSl. h>
sbit mybit. P2A4; //notice the wa y single bit i s declared
void main (void)
{
while(l)
{
mybitl; //turn on P2 . 4
mybit O; //t urn off P2.,
}
}
-
. . . .
8051
PROGRAMMING IN C

161
' se send AAH to P2.
-
Eumple 713 d 55}-I to l'O; otherWl '
. . Pl.5 uit is high, sen
Wnte an 8051 C program to morutor bit .

Solution:
is declared
''
,incl ude <regSl.h> the way single bit
eb i t mybit = p1s; //notice
void main (void)
{
mybitl; //make mybit an input
while (l )
{
i f (mybitl)
P0=0x55;
else
P20xAA;
l
l

Example 7-14
A door sensor is connected to the Pl.1 pin, and a bUZ2er is connected to PJ.7. Write an 8051 C program to monitor
the door sensor, and when it opens. sound the buuer. You can sound the buzzer by sending a square wave of 1
few hundred Hz.

Solution:
Ninclude <reg51.h>
void MSDelay(uneigned int);
abic Dseneor P111 //notice tile way single bit is defined
abit Buzzer PlA7;
void main(void)
{
Dsenaorl; //make Pl.l an input
while(Dsenaorll
{
buzzerO;
MSDelay(200);
buzzerl;
MStlelay(200);
l
l
void MSDelay(unsigned int iti111e)
/
unsigned int 1, j;
for(iO;i<itime;i++l
for(jO;j<l275;j++);
l

162
THE sos1 Mlcaoc
ONTROLLER - '-
AND EMBEDDED SYSTEMS \ '\
~
wrople 7-15 . . J t hed into the LCD whenever its Enable pin
The data pins of an LCD are coMected to Pl. The info~tion~ : but One Country" to this LCD.
goes from high to low. Write an 8051 C program to send The

#include <regSl.h>
#define LCDData Pl //LCDData declaration
sbit EnP2"0; //the enable pin
void main (void)
{
unsigned char message[] The Earth is but One Country#;
unsigned char z;
for(zO;z<28;z++) //send all the 28 characters
{
LCDData=message[z];
En=l; //a high-
En-O; l e to latch t he LCD data
// -to- 1ow pus
l
l
Run the above program on your simulator to see how Pl displays each character of the message. Meanwhile,
monitor bit P2.0 after each character is issued.

Accesssing SFR addresses 80 - FFH


Another way to access the SFR RAM space 80 - FFH is to use the sfr data type. This is shown in Example 7-16. We can
also access a single bit of any SFR if we specify the bit address as shown in Example 7-17. Both the bit and byte addresses
for the PO- P3 ports are given in Table 7-2. Notice in Examples 7-16 and 7-17, that there is no#include <reg51.h> statement.
This allows us to access any byte of the SFR RAM space 80 - FFH. This is a method widely used for the new generation of
8051 m.icrocontrollers, and we will use it in future chapters.

Table 7-2: Single Bit Addresses of Ports


PO Addr Pl Addr P2 Addr P3 Addr Port's Bit
PO.O 80H Pl.0 90H P2.0 AOH P3.0 BOH DO
P0.1 81H Pl.I 91H P2.1 AlH P3.l B1H 01
P0.2 82H Pl.2 92H P2.2 A2H P3.2 B2H 02
P0.3 83H Pl.3 93H P2.3 A3H P3.3 B3H 03
P0.4 84H Pl.4 94H P2.4 A4H P3.4 B4H 04
P0.5 85H Pl.5 95H P2.5 ASH P3.5 BSH
P0.6 05
86H Pl.6 96H P2.6 A6H P3.6 B6H
P0.7 87H Pl.7 06
97H P2.7 A7H P3.7 87H 07

-
111st PROGRAMMING IN C
163
' .
.
ously with a
250 ms delay. Use the 1fr
.

d P2 cooltJlU
e,wnple 7-16 bits of PO, Pl, ao
am to toggle all the
Write an 805dJeclC P1: port addresses.
keyword to are
.
Solution: .
e sfr data t~e data eype
II Accessing POrts as sFRs using t.h PO usin9 sf
afr PO Ox80;
/ /declar~ng
I sfr Pl Ox90;
sfr P2 = OxAO:
i d MSDelay{unsigned iot);
VO .d) .
1 void main{vo1
{ //do it forever
while(l)
{
PO=Ox55;
Pl=OxSS; '
'
P2=0x55;
MSDelay (250); /; 2 so ms delay
PO=OxAA;
Pl=OxAA;
P2=0xAA;
MSDelay(250 ):
l
}
void MSDelay(unsigned int itime)
I unsigned int
. 1,. J;
.
for(i=O;i<icime;i++)
for (jO:j<l275;j++I;
I

Exmpl 7-17
Write an 8051 C program to tum bit Pl .5 on and off 50,000 times.
Solution:

sbit MYBIT = Ox95; //another way to declare bit Pl'S


void main(void)
{
unsigned int z;
for(z=O;z<S0000;2++)
{
MYBlT:l;
MYBITO;
l
I

Using bit data type for bit-addressable RAM


The shit data type is used for bit-addressable SFR registe
addressable section of the data RAM space 20 - 2FH. To do ,~_rs only. Sometimes we n= d , a bi~
uiat, we use the b 11
' '"" to store some ala m
164 data type, as shown in Ex~mple 7-IS.
no:: sos1 MICRoco
Nl'Ro tlEll AND EM1SEDDED svsred
.

ExVJ1ple 718 . and send it to P2.7 continuously.


Write an 8051 C program to get the status of bit Pl.O, save it,

Solution:
#include <regSl.h>
sbit inbit = PlAO;
sbit outbit = P2A7; //sbit is used to dee l are SFR bits
bit membit; //notice we use bit to declare
//bit-addressable memory
void main(void)
{
while (1)
'
{
membit=inbit; //get a bit from Pl.O
I outbit=membit; //and send it to P2.7
I
}
}

Review Questions
1. The address of Pl is _ __ __
2. Write a short program that toggles all bits of P2.
3. Write a short program that toggles only bit Pl.O. . . dd bl l .
4. True or false. The sbit data type is used for both SFR a~d RA~ smgle-b1t a res~a e ocahons.
5. True or false. The bit data type is used onJy for RAM s ingle-bit addressable locations.

SECTION 7.3: LOGIC OPERATIONS IN 8051 C


One of the most important and powerful features of the C language is its ability to perform bit manipulation.
Because many books on C do not cover this important topic, it is appropriate to discuss it in this section. This section
describes the action of bit-wise logic operators and provides some examples of how they are used.

Bit-wise operators in C
While every C programmer is familiar with the logical operators AND (&&), OR ( I I), and NOT (!), many C p ro-
gr~ers are less f~ar ~ith the bitwise op_erators AN_D (&), OR (I), EX-OR (A), Inverter(-), Shift Right(>>), and
Shilt Left (<<).These b1t-w1se operators are widely used 1n software engineering for embedded systems and control;
consequently, understanding and mastery of them are critical in microprocessor-based system design and interfacing.
See Table 7-3.

Table 7-3: Bit-wise Logic Operators for C


AND OR EX-OR Inverter
A B A&B AIB A"B
0 0 0
Y=-B
0 0
0 1 1
0 1 1 0
1 0 0 1 1
1 1 1
1
-
8051 PROGRAMMING INC
0

165
' The following shows some examp
I cal operators
les using the C ogt

Od5 & OxOF = OxOS 1 ANDing I


J. I
2. Ox04 I Ox68 = Ox6C / ' ORing:
3 0x54 "Ox78 = Ox2C I' XORing I
..() SS = OxAA / ' Inverting 55H ' I
4. x . vise operators.
Examples 7-19 and 7-20 show the usage bit-, .I
I .>
~
Example 719
Run the following program on your simulator an
th resuJts.
d exaJl\lll
;,"
7

Solution:
llindude <reg51.h>
void main (void)
(
PO OxJS & OxOF; / / ANOi ng
Pi Ox04 I Ox68; / / ORing
P2= Ox54 Ox7B; //XORing
PO - Ox55; // inversing .
I ' Pl Ox9A >> 3; //shifting r i ght 3 times
Pl Ox77 >> 4: //shift i ng right 4 times
PO Ox6 << 4; //shifti ng left 4 times
}

Example 7-20
Write an 8051 C program to toggle all the bits of PO and P2 continuously with a 250 ms de lay. Use the inve ...
operator.

Solution:
The program below is tested for the DS89C420 with XTAL= 11.0592 MHz.
#i nc l ude <r egSl. h >
void IISDelay (unsigned i nt) ;
void mal n (void)
(
PO OX55;
P2 0xS5;
whi le(l )
{
PO-PO ;
P2 -P2;
MSDelay (250);
}
J
voi d MSDelay(unsigned int itime)
{
uns i gned inti, j;
for (i O:i<itime;i++ )
for(jO;j<l27S;j++);
l

166
THE~
JCRocor-,ii-a -
OLLER ANO EMBEDDED 5ySTPd
Bit-wise shift operation in C
There are two bit-wise shift operators in C: (1) shift right(>>), and (2) shift left (<<).

Their format in C is as follows:


data>> number of bits to be shifted right
data<< number of bits to be shifted left
The following shows some examples of shift operators in C.

1. Ox9A >> 3= Ox13 / shifting right 3 timesI


2. Ox77 >> 4 = Ox07 I"' shifting right 4 times I

3. Ox6 << 4 = Ox60 / * shifting left 4 times I
Study Examples 7-21, 7-22, and 7-23, showing how the bit-wise operators are used in the 8051 C.

Example 7-21
Write an 8051 C program to toggle all the bits of PO, Pl, and P2 continuously with a 250 ms delay. Use the Ex-OR
operator.

Solution:
The program below is tested for the DS89C420 with XTAL = 11.0592 MHz.
#includee <regSl.h>
void MSDelay(unsigned int);
void main(void)
{
PO=OXSS;
Pl=OxSS;
P2=0x55;
while(l)
{
PO=PO"'OxFF;
Pl=Pl"OxFF;
P2=P2"0xFF;
MSDelay(250);
}
}
void MSDelay(unsigne d int iti me)
{
unsigned inti, j;
for(iO;i<itime;i++)
for(j=O;j<l275;j++);
}

Example 7-22

Write an 8051 C program to get bit Pl .O and send it to P2 7 aft . .


er mverttng it.
Solution:
#include <regSl.h>
9 bitinbitPl "'O;

-8051
PROGRAMMING IN C
=

167

..
' //
rt (Sf'R) bits
sbit is used dec~areddporessaJ:>le memory
bit-a
abic outbitP21, //nocice thlS is
bit membit;
void 01ain(void)
{
while(l)
( //get a bit from pi.o to p2.7
membitinbit; //invert it and send it
outbit -membit;
l
\ }

Example 7-23
Write an 8051 C program to read the Pl.0 and Pl.I bits and issue an ASCII character to PO according to the fof.
lowing table.
I
t>I.J Pt.0
0 0 send o to PO
(' 0 I send 1 to l'O
1 0 send '2' 10 PO
1 l send '3' to PO

Solution:
~i~clude <regSl.h>
void maio(void)
{
unsigned char z
'
ZPl; I /read Pl
z=z&Oxl; //mask the unused bits
switch(z) //make decision
I
caoe (O):
I
PO' 0 . //issue ASCII o
break; '
l
case(!):
{
PO=' l' . //issue ASCII l
break
I ,
case (2) ,
I
PO' 2 .
//issue ASCII 2
} break,
case (J):
I
PO' 3 .
break; '
//issue ASCII 3
}
J
)

168
Review Questions
find the content of Pl after the follo"ving C code in each case. ,.. CA.
1. (a) Pl=Ox37&0xCA; (b) Pl=Ox37 I OxCA; (c) Pl=Ox37 Ox '
To mask certain bits we must AND them w i t h - - - - -
2. th
3. To set high certain bits we must OR them wi - - - - -
4. Ex-ORing a value with itself results in d
s. find the contents of P2 after execution of the following co e.
P2=0;
P2=P210x99;
P2=-P2;

SECTION 7.4: DATA CONVERSION PROGRAMS IN 8051 C


ewer microcontrollers have a real-
Recall that BCD numbers were discussed in Chapter 6. As stated th ere, many n C .d th time
time clock (RTC) where the time and date are kept even when the power is off. Very often the RT provi es e li '
and date in packed BCD. However, to display them they must be converted to ASCil. ln this section we show the app -
cation of logic and rotate instructions in the conversion of BCD and ASCII.

ASCII numbers
On ASCTI keyboards, when the key "O" is activated, "011 0000" (30H) is provided to the computer. Similarly, 31H
(011 0001) is provided for the key "l", and so on, as shown in Table 7-4.

.
Packed BCD to ASCII conversion
The RTC provides the time of day (hour, minute, second) and the date (year, month, day) continuously, regardless
of whether the power is on or off. However, this data is provided in packed BCD. To convert packed BCD to ASCII, it
must first be converted to unpacked BCD. Then the unpacked BCD is tagged with 011 0000 (30H). The following dem-
onstrates converting from packed BCD to ASCll. See also Example 7-24.

Pa c ked BCD Unpac ked BCD ASCII


Ox29 Ox02, Ox09 Ox32, Ox39
00101001 00000010,00001001 00110010,00111001

Table 7-4: ASCII Code for Digits O- 9


Key ASCIJ (hex) Binary BCD (unpacked)
0 30 011 0000 0000 0000
1 31 011 0001 00000001
2 32 0110010 0000 0010
3 33 011 0011 0000 0011
4 34 0110100
00000100
5 35 011 0101
0000 0101
6 36 0110110
00000110
7 37
011 0111
0000 0111
8 38
011 1000
00001000
9 39
011 1001
-
8051
PROGRAMMING IN C
00001001

169
' ~
ASCII to packed BCD conversion - -l...t BCD Ito i,..
'
_. ~d of the 31and uu,n
L-
comb,
T, c. - m A5C1I pio-d BCD. 11 fit5I COl''-ertrd ~.;.i 3;-H. respecti'el) . The goal "' to prod l1(d lo
awk pavd BCD For OAtl'f'lt 4 - i 7 on tlW i.i,,t,oatd ~ t Ute 'I!

or "OUXl 0111 whW. 11 f*Md BCD

ASCI I Ot,pack.ed 1a>


34 0 o~.u o.ooc111 or 47H
ouooo:11

' n,gram "'''""~rt p,o<ud BCD0-29 10 ASCII .and d.,,pl~> the b) te,, on r1 .ind P2.
Wr11~ n 3051 C p
I
Solution .

'I l lnc l ude ,r,egSl . h


void '""in (YOidl
{
unaignd c~ x y ,.. I
unalgned char o,ybyt Ox2P r
" I Ox 'l0 oxo,
"Pl mybyt 1 I I / u 1k lower ' bit
-by //Nkl lt UCtt
Y Y 4 1" ox,o,
- , >>t I / u1k "l)per 4 b1 ta
O
Y
P2 Y I OxlO // lhi! t I t to l ower 4
I 1 / /... ke i t ASCII

Ex.ampl 725

gib of '4' Ind 7'


Solution: to ~ BCD and d ISp
' la
Ythem on Pl .

include <regSl , h>


vo1d ""'In (void)
I
une i gned char b
una l gned Char Wcdbyte
' 4. '
:
una1gned c"r
,.._ Z' 7 r.
w
w
w' OxOF
w . '
1

, , ..... . 3
4
z z 'Ox~F; //ehift left to niaJt"uppe r BC!)
bedbyt~. w I 11.... k l to ...,.., digit
Pl bcdbyte, ~, / / c0ffib1ne t>acked BCD
)
Checksum byte in ROM
To ensure the integrity of ROM contents, every system must perform the checksum calcuJa_tion_. The process of
checksum ,vill detect any corruption of the contents of ROM. One of the causes of ROM corruption is current surge,
either ,vhen the system is turned on or during operation. To ensure data integrity in ROM, the ch~ksum process uses
what is called a cltecksun, l!yte. The checksum byte is an extra byte that is tagged to the end of a series of bytes of data.
To calculate the checksum byte of a series of bytes of data, the following steps can be taken.
1. Add the bytes together and drop the carries.
2. Take the 2's complement of the total sum. This is the checksum byte, which becomes the last byte of the series.

To perform the checksum operation, add all the bytes, including the checksum byte. The result must be zero. If it is not
zero, one or more bytes of data have been changed (corrupted). To clarify these important concepts, see Example 7-26.

Example 7-26

Assume that we have 4 by!es of hexadecimal data: 25H, 62H, 3FH, and 52H. (a) Find the checksum byte, (b) per-
form the checksum operation to ensure data integrity, and (c) if the second byte 62H has been changed to 22H,
show how checksum detects the error.

Solution:
(a) Find the checksum byte.
2 5H
+ 62 H
+ 3FH
+ 52H
118H (Dropping carry of 1 and taking the 2's complement, we get E8H.)
{b)
Perform the checksum operation to ensure data integrity.
25H
+ 62H
+ 3FH
+ 52H
+ ESH
200H (Dropping the carries we get 00, which means data . t
(c)
is no corrupted.)
Uthe second byte 62H has been changed to 22H h h
, s ow ow checksum detects the error
25H
+ 22H
+ 3 FH
+ 52 H
+ ESH
l COH (Dropping the carry, we get COH, whi h .
c means data IS corrupted.)

Ex.tmple 7-27
wnte an 8051 C program to calculate the checks b
um yte for the data
Solution: given in Example 7-26.

! i nc1uc1e <regSl . h>


01 d main(void)
{

IOs1 PR~
~RAMMING INC

171
checksum byte in ROM
To ensure the integrity of ROM contents, every system must perform the checksum calcuJa~on: The process of
checksum will detect any corruption of the contents of ROM. One of the causes of ROM corruption 1s current surge,
either when the system is turned on or during operation. To ensure data integrity in ROM, the che~sum process uses
\~hat is called a checksum vyte. The checksum byte is an extra byte that is tagged to the end of a series of bytes of data.
To calculate the checksum byte of a series of bytes of data, the following steps can be taken.

1. Add the bytes together and drop the carries.


2. Take the 2's complement of the total sum. This is the checksum byte, which becomes the last byte of the series.

To perform the checksum operation, add all the bytes, including the checksum byte. The result must be zero. If it is not
zero, one or more bytes of data have been changed (corrupted). To clarify these important concepts, see Example 7-26.

Example 726
Assume that we have 4 by!es of hexadecimal data: 25H, 62H, 3FH, and 52H. (a) Find the checksum byte, (b) per-
form the checksum operation to ensure data integrity, and (c) if the second byte 62H has been changed to 22H,
show how checksum detects the error.

Solution:
(a) Find the checksum byte.
25H

I + 62H
+ 3FH
' + 52H
I
118H (Dropping carry of 1 and taking the 2's complement, we get E8H.)
(b) Perform the checksum operation to ensure data integrity.
25H
' + 62H
' + 3FH
+ 52H
+ ESH
200H (Dropping the carries we get 00' which means data ts
. not corrupted.)
(c) If the second byte 62H has been changed to 22H' show h ow checksum detects th
25H e error.
+ 22H
+ 3FH
+ 52H
+ EBH
lCOH (Dropping the carry, we get COH, which .
means data is corrupted.)

Example 7-27
wnte an 8051 C program to calculate the checksum b te i
Y or the data .
Solution: given m Examp le 7-26.

:i~clude <regSl.h>
01 d main(void)
{

80s1 PR
0GRAMMING IN C

171

...
'

,'
ned
uns19 char mydatall
unsigned char sumO;
un signed char x;
unsigned char chksumby te'
for(xO;x<4;x++) P2
ch byte to
{ //issue ea together
( P2mydata[x);
//add chem um to Pl
sum=sum+mydata[xl; //issue the 9
l Plsum;
J ' complement
//make 2 s byte
chkaumbyte-sum+l; che checksum
l //sbOW
Pl=chksumbyte;
} f Pl and P2. Notice that each by1f
e the contents o
8051 simulator and eiraJTUll
Single-step the above program on the
is put on Pl they are added together.

ASCU h
c aracter 'C' t o PO.
Exm>plt 7-28
Write an 8051 C program to perform step (b) of Example 7.26. If d a ta is good' send

Othenvise send 'B' h> PO.

Solution:
#include <regS1.h>
void maintvoid)
{
unsigned char mydata[J{Ox25,0x62,0x3F,Ox52,0xE8};
unsigned char chksumeO;
unsigned char x;
for(x0;x<S;x++ )
chksumchkaum+mydata[x); //add them together
if(chksum=Ol
PO= 'G';
else
P0'8';
}
,

Binary (hex) to decimal and ASCII conversion In a 051


C
The printf function is part of the standard 1/0 Library C
binary (hex) to decimal, or vice versa. But printf takes a 11\ and can do many thin . frOIII
1
For this reason, in systems based on the 8051 microcontro~t of_ ~emory space nd . gs, including converting datatiiJ]v
of using printf. er, ll ,s better low . mcreases your hex file subs~ ie,d
One of the most widely used conversions is the b' 1
n e Your own conversion function i.nS
Digital Conversion) chips, the dala is provided to the~y to decirnai COnve .
dates are also provided in binary. In order to display b' croeontroller in b rsion. In devices such as AOC (Anal~
Since the hexadecimal format is convenient way of r ina.ry data we neect'~ry. In some RTCs, data such as time
O
epresenting binary d convert it to decimal and then ID~
172 ata we refer to the binary data as ht',.. 11't
T1iE sos1 Mtcao
CON'fao - .~
LLER AND EMBEDDSDSYlt,._..
Example 7-29 . d d' l the digits on PO, Pl, and P2.
Write an 8051 C program to convert 11111101 (FD hex) to decimal an isp ay

Solution:
ffincludee <reg51.h>
void main (void )
{
unsigned char x, binbyte, dl, d2, d3;
binbyte = OxFD; //binary(hexl byte
x = binbyte I 10; //divide by 10
dl = binbyte \ 10; / /find remainder (LSD)
d2 - X \ 10; //middle digit
d3 -
X I 10;
//most significant digit (MSD)
PO - dl;
Pl = d2;
P2 : d3;
}
I

'
binary data 00 FFH converted to decimal will give us 000 to 255. One way to do that is to djvide it by 10 and keep the
remainder, as was shown in Chapter 6. For example, 11111101 or FDH is 253 in decimal. The following is one version
of an algorithm for conversion of hex (binary) to decimal:

Quotient Remainder
FD/OA 19 3 (low digit) LSD
19/0A 2 5 (middle digit)
2 (high d igit) (MSD)

Example 7-29 shows the C program for that algorithm.

Review Questions
I. For the foUo\ving decimal numbers, give the packed BCD and unpacked BCD representations
(a)lS ~~
2. Show the binary and hex formats for "76" and its BCD version.
3. 67H in BCD when converted to ASCII is H and H.
4. Does the following convert unpacked BCD in register A to ASCII?
mydata = Ox 09 + Ox30;
S. Why is the use of packed BCD preferable to ASCII?
6. Which one takes more memory space: packed BCD or ASCII?
7 ln Question 6, which is more universal?
8 Find the ch~ksu~ byte for the following values; 22H, 76H, SFH, SCH, 99H.
9 To test data mtegnty, we add them together, includ ing the checks b .
be equal to if the data is not corrupted. um y te. Then drop the carnes. The result must
lO. An ADC provides an input of 0010 0110. What happens if we Ou tp u t th at to the screen?

SECTION 7.5: ACCESSING CODE ROM SPACE IN 8051 C


In ~~ing the code (program) space for predefined data is the wide! . .
SJ>ace ~ha~ter we saw how to use the Assembly language instructio~ ~d o ption m the 8051, as we saw in Chapter 5.
. 1h15 chapter, we explore the same concept for 8051 C. OVC to access the data stored in the 8051 code

173
' ce v code data space e are as rouows:
RAM data spa . wJuch to store data, Th Y . . b tes.) We can read (from) or"'~
In the 8051 ,ve have three spaces l1l ...cU (In the 8052, ,tis 256 ~w in Chapter 5. It
eOO. ,n stcrs as we .
n, 128 bytes of RAM sp,1ce with address rang g the RO and Rl regi J-1 'fhis 641< bytes of on-chip ROM space ts
I. . e ) th' RAM space directly or indirectly usm f ()()(JO pfFF trol of the program counter (PC). W
(,nto ,s . h addresses o d the coo Ch 5) Th '
2. The 64K bytes of code (programod)sp)a:~~1erefore is difeCtlY c'::'on~o access it for data <bs:n oitpe;ed~fmederedail?
used for storing programs (ope 5 ! Ian uage instr~ . memory, we can . fa
use the "MOVC A @A+DPTR Assembly gF'rst since ,t ,s ROM gram The second problem JS that the
can ' . d ce for data. t of the pro if h on-
two problems ,vith using this co e ~pa. it during the execution code. for e.xan1ple, we ave an ov~l dup
and tables into it. But we cannot wnte mt: less is left for our progra~ b tes of it to store son1e look-up table, onlj
more of this code space we use lor data, 1 e hi ROM and we use 4K Y b lem For th.is reason Intel created
7 such as DS89C420 with only 16K bytes ;;;::,m~ appli~ations thiS ca_n ~; ~ : ~ ;ext very briefly and we J)OSI.
0
L J2K bytes is left for the code program. . Uy for data. Tlus 1s
another memory space called extemnl memory espec1a .
pone the fuJ1 discussion to Chapter 14. RAM and ROM. This 64K bytes 1s called external
3. The 6'11( bytes of cxtemal memory, which! can beeu:i::::.~o access it. At the time dtheb80t51 lwlaseddesigned, the
since we must use the MOVX Assembly anguag used all the on-chip ROM for co e u ~ ow conn~on
cost of on-chip ROM was very high; therefore, Intel a total of l2SK bytes of memory space smce the off-chip or
to extemal RAM and ROM. In other words, we ha, e f hp space provides you a total of UBK bytes cl
external memory space of 641< b Ytes P u l s the 64.K bytes o on-c
. and , how to access it for bo th Assembl y and Cin
memory space. We will discuss the external memory expansion
O,apter 14.
Nex~ we discuss on-chip RAM and ROM space usag~ by the 8051 C ~mpiler._ We have used the Proview32 C oom-
piler to verify the concepts discussed next. Use the compiler of you, choice to verify these concepts.

RAM data space usage by the 8051 C compiler


In Assembly language programming, as shown in Chapters 2 and 5, the 128 bytes of RAM space is used mainly
by register banks and the sta.ck. Whatever remains is used for scratch pad RAM. The 8051 C compiler first allocates
the first 8 bytes of the RAM to bank Oand then some RAM to the stack.
Then 1t starts to aUocate the rest to the variables declared by the C pro-
gram. While in Assembly the default starting address for the stack is 08
the C compiler moves the stack's starting address to somewhere in th~ 7F
range of 50 7FH. Thls allows us to allocate contiguous RAM locati
to array elements. ons
In cases whehre the program ~as individual variables in addition to Scratch Pad RAM
1
array e ements, t e 8051 C comptler aUocates RAM locati h
lowing order: ons n t e fol- 30
:::-t---~f-
2F
I. Bank O addresses O. 7 Bit-Addressable W t
2. Individual variables 20
addresses 08 and beyond IF
3. Array elements
addresses right after variables Register Bank 3
4. Stack addresses n'gh t after array elements 18
17
You can verify the above order by running Exam Register Bank 2
8051 C simulator and examining the contents of the pie 730 on your 10
Remember that array elements need contiguous RAM data RAM space. OF
lirruts the size of the array due to the fact that, h locations and that
RAM ,or ' everything.
. ln the case of Example7-31 ve thave on] Y128 bytes of Register Bank I (Stad<l
08
limit4:'1 to around 100. Run Example 7-31 on your~array.elements are
examine the RAM space allocation. Keep changi h1 C Slll\ulator and
and monitor the RAM space to s,-e what happe ng t e size of the rra . Register Bank 0
ns. y

174 Figure 7 1 D
"""" Allocation in the 8051
Example 7-30 . e th e contents of the 128-byte
8051 simulator. Exanun
. p rogram on your
om ile and single-step the following
~AJspace to locate the ASCII values.

Solution:
#include <regSl .h>
void ma i n (void)
//This uses RAM space
{ uns i gned char mynum [] = "ABCDEF" ;
//to store data
unsigned char z;
f or( z=O;Z<=6;z++)
Pl=mynum [z); ,

} . th RAM space to locate values 41H, 42H, 43H , 44H,


on our 8051 simulator and exanune e
Run the above program y l 'A' ' B' 'C' and so on.
etc., the hex values for ASCII etters ' ' '

Example 7-31 8051 simulator Examine the contents of the code


Write, compile, and single-step the following p rogram on your .
space to locate the values.

Solution:
#include <reg5l.h>
void main (void)
{
uns igned char mydata[lOO]; //100 byte space in RAM
uns i g ned char x, z=O;
for (x= O;x<lOO;x++)
{
z--; //count do wn
mydata[x],.z ; //save i t i n RAM
Pl=Z; //give a copy to Pl too
}
: }

Run the above program on your 8051 simulator and examine the data RAM space to locate values PFH, PEH,
FDH, and so on in RAM. .

The 8052 RAM data space


lntel added some new features to the 8051 microcontroller and called it the 8052. One of the new features was an
extra 128 bytes of RAM space. That means that the 8052 has 256 bytes of RAM space instead of 128 bytes. Remember
that the 8052 is code-compatible w ith the 8051. This means that any program written for the 8051 will run on the 8052,
but not the other way around since some features of the 8052 do not exist in the 8051 . The extra 128 bytes of RAM helps
the 8051/ 52 C compiler to manage its registers and resources much more effectively . Since the vast m ajority of the new
versions of the 8051 such as DS89C4x0 are re~Jly based on 8052 architecture, you should compile your C programs for
~ e 8052 microcontroller. We do that by (1) using the reg52.h header file, and (2) choosing the 8052 option w hen com pil-
1t1g the program.

-
IOs1 PROGRAMMING INC
179
' ne the contents of the code 6Pace
r E,arru
Example 7-32 on<l siinU Ia to
_,..m on your"""'
Compile and $11\gle-step the following Pvo-
to locate the ASCII values

Solution:
include <regSl.h>
vo1d main (void}

'
//uses code space
I code unsigned char mynum [l = "ABCDEF"; I
//for: data
I

,,-
unsigned char z:
for(zO;Z<6;z++l
Pl=mynum(zl;
J
h code space to locate values 41 H, 42H, 43H,44H:
Run the above program o n your 8051simulator and examine t e
etc. the hex values for ASCII characters of 'A', 'B', 'C:, and so on.

Accessing code data space in 8051 C I


In all our 8051 C examples so far, byte-size variables were stored in the 128 bytes of RA,"1. To make the C compiler
use the code space instead of the RA,"1 space, we need to put the keyword code in front of the variable declaration. The
i
following arc some examples:

code unsigned char mynum(l "01234SABCD"; //use code space



code unsigned char weekdays=7, month=Oxl2; I /use code space
"
Example 7-32 shows how to use code space for data in 8051 C.

Compiler variations
'
L~k at Example 7-33. It shows three different versions of
c
Compile each program with the 8051 compiler of ch . a program that sends the string "HELLO" to the Pl port.
gr~m o~ . different 8051 C compiler, and examine th~~ur fil o,~e and compare the hex file size. Then compile each pro-
M1croD1g1taJEd.com for 8051 C compilers. ex e s ize to see the effectiveness of your C compiler. See www.

Example 7-33

Compare and controst the following programs and d '


ISCUSs the advanta
{a) ges and disadvantages of each one.
include <regSl.h>
void main(void)
I
Pl' H';
Pl 8';
Pl'L';
Pl'L';
Pl '0';
.
l

176
(b)
#include <regSl .h>
void main(void)
{
unsigned char mydata[]="HELLO" ;
unsigned char z;
for(z=O;Z<=S;z+ +)
Pl=mydata[z];
}

(c)
#include <reg51 .h>
void main(void)
{
//Notice Keyword code
code unsigned char mydata( ]= "HELLO";
unsigned char z;
for(z=O;z<=S;z++)
Pl=mydata[z];
l
Solution: