Sie sind auf Seite 1von 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 the·1r 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 .
. troller·based 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 equh•alent 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'1••ff
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 =~
~Q·ti·on we
Whereas human beings use base 10 (decimal) arithmetic, compute d v·ce 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
11·eight 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

Ex•mple 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 "ask·E") ·- -
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 s«tion 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 w·th' 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


gr•i:n of• H•lf·Adder

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 . 1¥t
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 M·1crocontrollers 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. .
a·or 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 of·the 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 2·4· 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 twos·tmp 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 w·th 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
o·S er
R2er 8, then add them together.
.
value? an e moved into an 8-b·t .
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 . as¢1'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 Ch•pt•: · 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"raott£a
-'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 2·1

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..... ti·c 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 W·5: 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 et·r RAM AddresK5 -

Exi mpl~ 2-5 am·


~tJtc thl' conrenl!> of RAM loca tion, aftt·rt ,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'illil•n 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 1·t 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 1·t 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
'
1±1 psw OxOO

Figure 2·9. 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 J•·f·rrrC.. '"'
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 q·r . . ' ' ' 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 power·up, 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


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. 0•7
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 1·s 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 toJ·ump. 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 3·6

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 unt·1 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.
.J5µs 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 u·ons 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 i·t in reg R7
MOV R7,A
'
ACALL DELAY ;wait hr data from Pl
MOV A,Pl ·get anot e
MOV R6,A '
·save 1·tin 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 blt•addressablllty


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. wr1·te 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' ;SW•l , 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 1·1. I uously .
. /26
.
wn·1ea 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 ;DPTR•4Sl2H _.., 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 1·s 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=R2•05}
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 (B•25H )
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 ; A•SSH
MOV 90H , A ; Pl •S SH
MOV OAOH , A ;P2•SSH

-
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 1A•O
MOV Rl,#60H ;load
MOV R7,#16 ;load poi n t er. Rl•60H
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
Ex•mpl• 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 ;0PTR•400H (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
·A•O
I •
CLR A ;get ' A' from 1ocat10~ 401H
MOVC A, @A +DPTR ;move it to RAM location 61H
MOV 61H,A
;OPTR•402H
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 str1·ng
ORG 0000
HOV DPTR #MYDATA
I
;loa d ROM pointer
HOV R0, #4 0H ; load RAM point e r
BACK: CLR A ; A•O
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
, 1nct•ant: 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 look•up 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""'-·or·a 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 count•O
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. Th•y 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 5•2; 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 bit·addressabilty 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
Ex•mpl• 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

Ex•mple 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.2•1 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 Messages•io
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 w·th 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 PO·1· 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 po·r
DAT EQU 90H f
p o·
BACK: MOV C,DAT·REQ 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 b·tl
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
·TE·n51ruction 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 5•bytes 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 CY•O, 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" A•J1,CY=l
MOV A,1!4SH '.add the 10w byte, f sum in RO
ADD A,#OECH • byte o
-save the low in•o 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+l•FFH 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'
t»lllll
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 ·A•O
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 CY•O on .
tNC R7 ;keep track o~ carries
NEXT: INC RO ·increment pointer
DJNZ R2, AGAIN
•;repeat unt1·1 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 sepat•lt
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,LOGICINSTRUCflONS·A~;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 ;A•27H • 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), :,( 11·ent 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 i·ent 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"'1•T 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 OV•l
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 ;A•llll 1110 (A•FEH)
MOV Rl, #-5 ;Rl• llll 1011 (Rl=FBH)
ADD A,Rl ;A•llll 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 '
;A•OOOO 0111 (A•07u
MOV IU,#•18 ;Rl•OOOl 0010 (R q)
ADD A,Rl ;A•OOOl 1001 IA 1•12!!)
•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'Ex•mpl• 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.

-
AlllTHM£1IC, 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 A•AAH ( 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.

Ex•mple 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 ;R4•0
MOV RO.il40R
;load pointer
HOV R2,#0S
,load counter
MOV A, #65
;A•65, 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 b·t 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 ; A•Olll 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
;A•OOlO 011\ L1MSB LSBf-CYJ
RRC A ;A•OOOl 00 CY•O
RRC A ;A•OOOO 10 l CY• l
RRC A ; A='i:,pOO 01 0 CY•l
..,.. ...
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 ;A•OOlO 1011 CY•O
RLC A ;A•OlOl 0110 CY•O
RLC A ;A•lOlO 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.

Ex•mplc 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"" .•,,
pl•ce 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 A•39H ('9
• ·tan ASC • ) .
A,#30H ;make, 9H ASCll char
ORL ·save it (R6•3 , i nal data •
MOV R6,A ' et the orig )
MOV R2 ;A=29!l , g 'bble(A•20 !
ANL
A,
A, "OFOH •mask
• the lower
c
n1
,rotate rigut
RR A ; rotate right
RR A ; rotate right
RR A •rotate right, (A•02)
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 {A•04 )
SWAP A ;A•40H
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
R»l_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 ati·ons s uch as sen·a1 d ev1·ces. 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 . p·md 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 2•s 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.CY•O 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 ___.
LL£R 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 sp«ificC data types that are can help programmers to cre•te
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
Pl•OxAA;
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~ l••ilbid
-~
~:~ ~~ .- . ' . .. .
~---~~~~~~--
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 7•5. 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(z•O ;Z<z8;z++) '
Pl•mynum [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 vers•Oany 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 d•lh
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(x•O;X<40000;x++);

l
:
/
I\/
Exampl• 7.7
Wn·1e 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
(
Pl•OOY //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
Pl•OXPF· 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(i•O·i<1·t·
,' '
ime;i+•)
} for(J•O;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)
{
mybit•l; //turn on P2 . 4
mybit •O; //t urn off P2.,
}
}

. . . .
8051
PROGRAMMING IN C

161
' ·se send AAH to P2.
-
Eumple 7·13 • 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 = p1•s; //notice
void main (void)
{
mybit•l; //make mybit an input
while (l )
{ •
i f (mybit••l)
P0=0x55;
else
P2•0xAA;
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 • P1·11 //notice tile way single bit is defined
abit Buzzer• PlA7;
void main(void)
{
Dsenaor•l; //make Pl.l an input
while(Dsenaor••ll
{
buzzer•O;
MSDelay(200);
buzzer•l;
MStlelay(200);
l
l
void MSDelay(unsigned int iti111e)
/
unsigned int 1, j;
for(i•O;i<itime;i++l
for(j•O;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 En•P2"0; //the enable pin
void main (void)
{
unsigned char message[]• ·The Earth is but One Country#;
unsigned char z;
for(z•O;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 (j•O:j<l275;j++I;
I

Ex•mpl• 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;
MYBIT•O;
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 7·18 . 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 7·19
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(j•O;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 times•I


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(i•O;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 bitinbit•Pl "'O;

-8051
PROGRAMMING IN C
=

167

..
' //
rt (Sf'R) bits
sbit is used dec~areddporessaJ:>le memory
· · bit-a
abic outbit•P2·1, //nocice thlS is
bit membit;
void 01ain(void)
{
while(l)
( //get a bit from pi.o to p2.7
membit•inbit; //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 ·
'
Z•Pl; 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 31•and •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
{
unaign•d 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• 7·25

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
w·nte 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 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.
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
w·nte 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 sum•O;
un signed char x;
unsigned char chksumby te·'
for(x•O;x<4;x++) P2
ch byte to
{ //issue ea together
( P2•mydata[x);
//add chem um to Pl
sum=sum+mydata[xl; //issue the 9
l Pl•sum;
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(x¥0;x<S;x++ )
chksum•chkaum+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 h·p 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 7·30 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 P•vo·-·
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(z•O;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: \

All the programs send out "HELLO'' to Pl, one character at a time, but they do it in different \vays. The first one
is short and simple, but the individual characters are embedded into the program. If we change the characters,
the whole program changes. It also mixes the code and data together. The second one uses the RAM data space to
store array elements, therefore the size of the array is limited. The third one uses a separ ate area of the code space
for data. This allows the size of the array to be as long as you want if you have the on-chip ROM. However, the
more code space you use for data, the less space is left for your program code. Both programs (b) and (c) are easily
upgradable if we want to change the string itself or make it longer. That is not the case for program (a).

See the following Web sites for 8051 C compilers:


www.MlcroDlgltalEd.com
www.8052.com

Review Questions
1· The 8051 has bytes of data RAM, while the 8052 has
2· The 8051 has K bytes of code space and K bytes.
3. True or false. The code space can be used for data but the e t l bytes of external data space.
4· Which space would yo~ use to declare the following value:
(a) the number of days m the week
t::"~data,space cannot be used for code.
8 1
C.
(b) the number of months in a year
(c) a counter for a delay
S. In 8051 C, we should not use more than 100 bytes of the RAM
- data space for variables. Why?

80s1 PROGRAMMING IN C
177
' SECTION 7.6: DATA SERIALIZATI ON US ING
0
8051
C . through a single pin of microcontroller. '1'1..
ne bit at a 1111te "14!!,
Serializing data is a way of sending a byte of data
are two ways to transfer a byte of data serially: er has very fjJ:Jl.ited controI over the sequ~
I Using the serial port. When using the serial port, the proya~ o,apter JO. o/
data transfer. The detail of serial port data transfer 15 disc sse .
d ta one bit a tu:ne and control the sequence
. J of data
. and s~
2. The second method or serializing data is to transfer a LCD, ADC, and ROM the sena versions are beco
m between them. In many new generations of dev1~ s~ch as Dl-
ing popular since they take less space on a printed c1rcu1t boafd.

Examine the next four examples to see how data serialization is done in SOS! C.
-
Example 7.34
~Vrite a C program to send out the value 44H serially one bit at a time via PJ.0. The LSB should go out first.

Solution:
//SERIALiiING DATA VIA Pl.0 (SHlFTING RIGHT}
Hinclude cregSl.h>
Sbit PlbO • p1•0;
sbit regALSB. Acc·o·
void main/void) '
{
unsigned char conbyte • Ox44 ;
unsigned char x·
ACC = conbyte; ·
for(x=O; x<8; x++)
{
PlbO • regl\LSB 1
ACC • ACC << l .
'
}
}

PIN

l 07
I RECA
I 00
I .. , l PLO

Ex•mple 7.35
Write a C program to send out the v a Iue44H se ·a11
Solution: n Y one bit at a time v,a
. Pl O Th
. . e MSB should go out first.
//S&RIALIZ!NG DATA Vl
Winclude cregSl.h, A Pl.O (SHIFTING LEFT}
sbit PlbO • Pl•o,
sbit regAMSB. A~c·,.
void main(void) '
{
unsigned char conbyte • OX44.
'

178
unsigned char x;
ACC = conbyte;
for(x=O; X<B; X++)
{
PlbO = regAMSB;
ACC = ACC << l;
}
}

Example 7-36 . . ·a Pl O The LSB should come in first.


Write a C program to bring in a byte of data serially one bit at a time v1 .. •

Solution:
//BRINGING IN DATA VIA Pl.O (SHIFTING RIGHT)
#include <reg5l.h>
sbit PlbO = PlAO;
sbit ACCMSB = ACCA7;
void main (void) •
{
unsigned char conbyte = Ox44;
'
unsigned char x;
for(x=O; X<8; x++)
{
ACCMSB - PlbO;
ACC = ACC >> l;
}
P2=ACC;
'
}
PIN

I Pl.QI~~.. ,L..-_.._I_ _ R_EGA - - - L - '__.~,


07 DO

'

Example 7-37

Write a C program to bring in a byte of data serially one bit at a time via Pl.O. The MSB should come in firaL
Solution:
//BRINGING DATA IM VIA Pl .O (SHIFTING LEFT)
#include <regSl.h>
Bbit PlbO. PlAO;
&bit regALSB • ACC"'O;
Void main (void)
(
unsigned char x,

--
8051
PROGRAMMING IN C
1'19
' ~

'
t
for(xsO; x<8; x++)
(
regALSB • PlbO;
~, f
'
ACC • ACC << l;
)
P2•A.CC;
l ;f
'

~~~~~~~~~~~~~~~~~~~~~~-~an~d~ltimITT.edclaysm8051C.WeaJso
SUMMARY , Uy 1/0 progra)J\OUl'lg
lications for these operators Wert
3
. d alt with 8051 C programming, e~aent. In addition, some_ : C. We also compared and (l)f!,
This chapt~r e AND OR XOR, and comp em t and conversions m .51 f data serialization wasaJso ••
showed the logtc operators d '.bed BCD and A5Cil lorma s . dely used technique o
discussed. This chapter also ~r~ data space in 8051 C. The WI
,.. trasted the use of code space an
discussed.

PROBLEMS c
SECTION7.l:DATATYPESANDTIMEDELAYIN8051 . . .
I•
I. Indicate what data type you would use for each or the following vanables. 'i
(a) the temperature
(b) the number of days in a week
(c) the number of days in a year
(d) the number of months in a year ,
(e) the counter to keep the number of people gelling on a bus
(f) the counter 10 keep the number of people going to a class
(g) an address of 64K bytes RAM space
(h) the voltage
(i) a string for a message to welcome people to a building
2. Give the hex value that is sent to the port for each of the following C statements:
(a) Pl=l4; (b) Pl•OX18; (c) Pl•' A' ; (d) Pl•7;
(e) Pl=J2; (f)Pl•OX45; (g) Pl•25S; (h) Pl:OxOP;
3. Give three factors that can affect time delay code siie in the 8051 mkrocontroUer.
4. Of the three factors in Problem 3, which one can be set by the system designer?
s. Can the programmer set the number of clock cycles used to execute an instruction? Explain your answer.
6. Explain why various 8051 C compilers produce different hex file sizes.

SECTION 7.2: l/0 PROGRAMMING IN 8051 C


7. What is the difference between the sbit and bit dam types?
8. Write an 8051 C program lo toggle all bits of Pi every 200 ms
9. Use your 8051 C compiler lo see the shortest time delay th ·
IO. Write a time delay function for JOO ms. a1 you can Produce.
II. Write an 8051 C program to toggle only bit Pt.3 every 200
12. Write an 8051 C program to count up Pl from O. 99 co tinms.
n uousty.
SECTION 7.3: LOGIC OPERATIONS IN 8051 C
13. lndkate the data on the ports for each of the followin
Note: The operations are independent of each other. g.
(a) Pl•OxFO:Ox4 5; (b) Pl•OXFO&Ox 56 ;
(c) Pl=O xPO Ox76; (d ) P2=0xFO&Ox 90 ;
(e) P2•0xFO'Ox90; (f) P2=0xFO I Ox 90;
(g)P2•0xFO&Ox FF; (h)P2=0 x FOJOx99;
(i) P2:0xFO'OxEE; (j) P2=0xFO'OxAA; .
It Find the contents of the port a fter each of the fo Uo wing opera tions.
(a) Pl=Ox 65&0x76 ; (b) Pl=Ox 70 J Ox6B ;
(c) P2=0X95'0xAA; {d ) P2=0x 5D&Ox 78;
(e) P2=0xCS I Oxl2; (f) PO•Ox6 A· o x 6E;
(g) Pl=Ox37 J Ox26;
15. find the port value after each of the following is executed.
(a) Pl•Ox65>>2; (b) P2=0x39<<2;
(c) Pl•Ox04>>3; (d) Pl•OxA7<<2;
16. Show the C code to swap Ox95 to make it Ox59.
17 Write a C program that finds the number of zeros in an 8-bit data item. th
18: Astepper motor uses the following sequence o f blnary numbers to move the motor. How would you generate · em •
in 8051 C?
1100.0110.0011,1001

SECTION 7.4: DATA CONVERSION PROGRAMS IN 8051 C


19. Write a program to convert the following series of packed BCD numbe rs to ASCil. Assume that the packed BCD is
located in da ta RAM.
76H, 87H, 98H, 4 3H
20. Write a p rogram to convert the fo llowing series o f ASCLI numbers to p acked BCD. Assume that the ASCil data is
located in da ta RAM.
·8767"
21. Write a p rogram to get an8-bit binary number fro m Pl,convert itto ASCLI, and save the result if the input is packed
BCD of 00 - Ox99. Assume Pl has 1000 1001 binary as input.

SECTION 7.5: ACCESSING CODE ROM SPAC61N 8051 C


22. Indicate what memory (embedded, data RAM., or code ROM space) you would use for the following variables:
(a) the tempe rature
(b) the number of days in week
(c) the number of days in a year
(d) the number o f months in a year
(e} the counter to keep the number of people getting on a bus
(I) the counter to keep the number of people going to a class
(g) an add ress of 64.K bytes RAM space
(h) the voltage
(i) a string for a message to welcome people to building
?3. Discuss why the total size of your 8051 C variables should not exceed 100 b 1
24. Why do we use the ROM code space for video game characters and shape es.
5j
25. What ~s the drawback of using RAM data space for 8051 C variables?
~ What 1s the drawback of using ROM code space for 8051 C data?
· Wnte an 8051 C program to send your first and last names to P2 · Use ROM code space.

ANSWERS TO REVIEW QUESTIONS


SECJ10N 7.1: DATA TYPES AND TIME DELAY IN 8051 C
~ 0 to255 for unsigned char and-128 to +127 for signed char
l OUto ~.535 for unsigned int and -32,768 to +32.767 for signed · t
· ns1gned char '"
t True
S. (a) Crystal frequency of 8051 system, (b) 8051 machine cyd ti .
--. e rrung, and (c) compiler use for 8051 C

8osi PROGRAMMING IN C
181
' SECTION 71: f/0 PROGRI\MM
ING !N 8051 C

1. 90H
2. #include <reg51.h> /
void mainO
l
P2 = Ox55;
P2=0xAA
I
L 3. #include <reg51.h>
sbit PlObit= Pl "0; /
void mainO
7 l
,,-
• P10bit =0;
PIObit = 1;
I
4. False, only to SFR bit
s. True
r
SECTION 7.3: LOGIC OPERATIONS IN 8051 C
). (a) 02 (b) FFH (c) FDH
f 2. Zeros
3. One

4. All zeros
l 5. 66H
SECTION 7.4: DATA CONVERSION PROGRAMS IN 8051 C
1. (a) ISH = 0001 0101 packed BCD, 0000 0001,0000 0101 unpacked BCD
(b) 99H =10011001 packed BCD, 00001001,00001001 unpacked BCD
2. 3736H = 00110111 00110110B
and in BCD we have 76H = Olli 01108
3. 36H, 37H
4. Yes, since A= 39H
5. Space savings
6. ASCU
7. ASCll
8. 21CH
9. 00
10. First convert from binary to decimal, then to ASCD, th en send to screen.

SECTION 7.5: ACCESSING CODE ROM SPACE IN 8051 C


I. 128,256
2. 641<, 64K
3. True
4. (a) data space, (b) data space, (c) RAM space
5. The compiler starts storing variables in codespace.

182
ilill sos1 M1cR.ocoN1' -
ROLLER AND EMBEDDED sYSTfil'IS \
CHAPTERS

8051 HARDWARE CONNECTION


AND INTEL HEX FILE

OBJECTIVES

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

)I, Explain the purpose of each pin of the 8051 microcontroller


)I, Show the hardware connection of the 8051 chip
)I, Explain how to design an 8051-based system
)I, Show the design of the DS89C4x0 Trainer
)I, Code the test program in Assembly and C for testing the DS89C4x0
)I, Show how to delete programs from DS89C4x0 flash RO ·
)I, Show how to download programs into a DS89C4 0 M usmg PC HyperTerminal
)I, Explain the Intel hex file x system using PC HyperTerminal

183
' This chapter describes the process of phy~icallY connecd section si,o,vs
describe the function of the pins of 8051 ch•P· :11• ~
shO'"s hO'" .
.
8051

10
.based systems· .1n the first 5ection

:e?"'"·
ting and tesbllg hatd ware connection for an 805! 1 ."I
1oad programs into a DS89C~~
0 f the Intel hex file. ·• """I
1
using the D589C4x0 (D589C420/ 30/ 40/ 50} chiP· 1 . the charactensbCS
system using PC HyperTenninaJ, In Section 8.3 we exp all1

SECTION 8.1: PIN DESCRIPTION Of THE 80S,1 D589C4JC0) come u, different packages, .n .
such as DIP(~"'I
....
Although 8051 family members (e.g., 875t, 89CSJ, 89C52• . carrier), they aU have 40 pins that are dedicate,j lo
in-line package}, QFP (quad Oat package), and LLC (leadle~s chiP t It must be noted that some companies p~
t11te~t, f
variou_s functions such as f/ 0 , ITT), WR', address, data, and ~ss demanding applications. However, sinct
a 20-p~ v~rs,on of the 8051 with a reduced number ~f J/ 0 parts eon that. Figure S-1 shows the pms for the 8051/~
vast ma1onty of developers use the 40-pin chip, we will concentrat . b d' ssed as we study them.
For the 8052 chip some of the pins have extra functions and they wdl e ,scu. d for the four ports PO Pl P2
Examining Figure 8-1, note that of the 40 pins, a total of 32 pins are set as, e 2 ' ' , and PJ,
r where each port takes 8 pins. The rest of the pins are designated as VCC' GND, XTALl, XTAL , RST, tA, PSEN, and
ALE. Of these pins, six (Voc• GND, XTAll, XTAL2, RST, and hA) are used by aU members of the 8051 _and 8031 fami&5
In other words, they must be connected in order for the system to work, regardless of whether the nucrocontroUer ~cf
the 8051 or 8031 family. The other two pins, PSE,\J and ALE, are used mainly in 8031-based systems. We first desai!,e
the function of each pin. Ports are discussed separately.

p·,n 40 provides
. supply voltage to the chip. The voltage source is +SV.

POIP/Cerdip

1 Voc
2 l'O.O (ADO)
3 PO.I (AOl)
4 8051152 P0.2 (AD2)
5 <OS89C4x0
AT89C5! P0.3 (A03)
6
8031) P0.4 (A04)
Pl .7 P0.5(AD5)

RST P0.6(AD6)
(RXOJ P3.0 P0.7 (AD7)
(l'XD) P3.J EA/VPP
{IN11)) 1'3.2 ALE/PROG
CINTl) 1'3.3 !>SEN
{TO) PJ.4 1'2.7 (AlS)
(Tt) P3.5 27
P2.6 (Al4)
(WR) P3.6 26
P2.S (Al3)
(RD) 1'3.7 25
P2.4 (Al2)
24
P23(All)
XTALI 23
P2.2 (AlO)
CNO 22
1'2.1 (A9)
21
1'2.o (A8)
Figure 8-1 . 8051 Pin Diagram

184
TliEsos1 ~
'Clloco
Nl'ROLLl!R. -
ANO EMBEDDED S ~
(JNO C2
Pin 20 is the ground. ",
;
XTAL2
30 pF - -
tfAL.1 and XTAL.2 D
The 8051 has an on-chip oscillator but requires an external cJocl< to
run it. Most often a quartz.crystal osci llator is connected to inputs XTALl
(pill 19) and XTAL2 (pin 18). The quartz crystal oscillator connec~ed to
XTALl and XTAL2 a lso needs two capacitors of 30 pF value. One side o f 30 pF
Cl
I
.__ _,/'L-f_ __.__ _ _I XTALl

each capacitor is connected to the ground as shown in Figure 8-2 (a). .


It must be noted that there are various speeds of the 8051 fanuly.
Speed refers to the maximum oscillator frequency connected to XTAL. GND
for example, a 12-MHz chip must be connected to a crystal with 12 MHz
frequency or less. Likewise, a 20-MHz nucrocontrolle r requires a crystal
frequency of no more U,an 20 MHz. When the 8051 is connected to a
aystal oscillator and is powered up, we can observe the frequency on Figure 8-2 (a). XTAL Connection to 8051
the XTAL2 pin using the oscilloscope.
I( you decide to use a frequency source other than a crystal oscilla-
tor, such as a TIL oscillator, it will be connected to XTALl; XTAL2 is left
unconnected, as shown in Figure 8-2 (b). NC - - - - -1 XTAL2

RST
Pin 9 is the RESET pin. It is an input and is active high (normally
low). Upon applying a high pulse to this pin, the mkrocontroller will EXTERNAL
reset and terminate a ll activities. This is often referred to as a power-on OSCILLATOR - - - - 1 XTALl
r<Stl. Activating a power-on reset will cause all values in the regis ters to SIGNAL
be lost. It will set program counter to all Os.
Figures 8-3 (a) and (b) show two ways of connecting the RST pin to
the power-on reset circuitry. Figure 8-3 (b) uses a momentary s,vitch for ,------1 GND
reset circuitry.
In order for the RESET input to be effective, it must have a mini-
mum duration of two machine cycles. ln other words, the high pulse
must be high for a minimum of two machine cycles before it is allowed figu.re 8-2 (b). XTAL Connection to an
to go low. Here is what the Intel manual says about the Reset circuitry: External Oock Source

Vee
+
31
10 aµJ' EA/VPP
31 19
EA/VPP
XI lOµF
30pf 19 Xl
8.2 K D ll.OS92MHz 30pF

X2 . D 18
JO pf 18
X2
RST 30pF
9
9 RST

8.2 1<

tigure 8-3 <


•). Power-On RESET Cimall
- Fi~ &-3 (b), Power-On RESET with Momentary Swikh
lls1 liAR.ow
ARE CONNECTION AND lNTEL HEX FILE
115
I t of time that depends on the capa .
in high for an
~mount be held high long enough Lo
5
·When power is turned on, the circuit holds the ~ ; reset the RsT pill ':'1° and a 10-µF capacitor will take ca the
anO:to, ,,,
value and the rate at which it charges. To ens'!'e a ":u an 1
h, s.21<-olun res : '1 ou are using. l"eq
oscillator to start up plus two machine cycles. Alth ; data sheet for the Y
the vast majority of the cases. you still need to check t e p
EA come with on-chip ROM to store programs.
O II <
The8051 family members• suchas· the875J / 52,S9C5J/ 52, or [)589Cd4Xas ,thae 8031 and 8032thin - . · there is
which beno on~••

In such rues, the !A pin is coMecled to Vcc· For family mem ·
t,ers SU 1
Therefore for the 8031 e t r \ pin must c o
""P
~ •
ROM,codeisstoredonanextemal ROM and is fetched b__l' theB03l/
32
d
f r ''ext~rnal access," is pin number 31 in the DIP
to GND to indicate that the code is stored externally. ~· which sti~ ~ other words, it cannot be left unconnected.

~ith PSE/q to access programs stored in ROI ''
~
packages. It is an input pin and must be coMected to e1the~ Vct; or
In Chapter 14, we will show how the 8031 uses this !"n alMong h the 8751 / 52, 89C51/52, or 0589(4 xO II
l
memory located outside the 8031. In 8051 crups with on-chip RO , sue as • OIi
is COMected to Vrx• as we will see in the next section. . b 15 . used The next f:\vo ·
The pins discussed so far must be connected no matter which family mem er . •• . .P~ are USl'd
mainly in 8031-based systems and are discussed in more detail in Chapter 14. The following 1s a bnef description of each.

PSEN_ . I . .
This 1s an output pin. PSEN stands for "program store enable." In an 8031-based system ,n wluch an external ROM
holds the program code, this pin is connected to the OE pin of the ROM. See Chapter 14 to see how this is used.

ALE
" ~~
A~: <•:dr~ss latch enable) is an output pin and is active high. When connecting an 8031 to external memo
0J;";'.~EC:,ino~ ~nd dt:\In.other words, the 8031 multiplexes address and data through port Oto
discussed in detail in ~~.;/;,ul:.p exmg the address and data by connecting to the G pin of the 74LS373 chip. This~
sa~·:
Ports O, 1, 2 and 3
As shown in Figure 8-1 (and discussed . Ch
!~~:~t:!:~.::i~;~~~~.5~ ~~e ~o~fig::::~:ii::::e
0

1 e matenals Ill Chapter 4.


:_Pg3:!~1;:.:ru! :~ch uthse 8 pThins, makin~ lh_em
on em. e foUowmg IS a

PO
As shown in Figure 8-l .
as ADO - AD7 allow· . ' port O is also designated
and data. Wh;n conn~~ to be used /or both address
memory, port O provides fo: ~~1/31 to an extemal Vcc
8051 multiplexes address and d ress and data. The
save pins .. ALE indicates if PO has ::dthrough port O to
ALE ; 0, >I provides data DO. D7 ress or data. When
has ~ddress AO -A7. There/ore, AL:~t when ALE; 1 it
. ~ ..;
•.~

~: > ~
-- ~. ;:~
.:: >- <
><
-:':> •
:> • >
.::• > <~>
><
~
>.
.
10 K

'
plex111g address and data with th ~ ~ for demuli-
latch, as we will see in Chapter 14. i e p of a 74LS373
t~ms where there ,s no extemaI mem:e 8051-based sys-
8051152
PO.O
PO.I
P0.2
pms of PO must be connected ry connection, the P0.3
uJI • externally t
P -up resistor. This ls due to th i o a 1OK-ohm P0.4
drain, unlike Pl, P2, and P3 0 e act ~at PO is an Open PO.s
/or MOS chips in the same w~ pen dram is a term use P0.6
for ITL chips. In many syste?:.stha1_opt11 collector is use:: l'0.7
or DS89C4x0 chips, we normaU using the 8751, 89Cs1
resistors. See Figure .,....
• ., w·th' puJJPO to pull-up'
Y connect
r extemal
-up resistors
Fig.,,. S-4
• Po11 o wl th Puu-u .
186
T!il! P Resistors
80SJ M1cao
CONTROLLER _.
AND EMBEDDED SYS,vas
. . P2 l trast to port 0, ports Pl, P2, and P3 do
ected to PO, it can be used as a simple 1/0 port, 1ust like Pl ~d : n con U on reset, rts Pl, P2, and P3 are
~eed any pull-up resistors since they already have puU-up res1Stors rntemally. P po
~guted as input ports.

p1 and P2 .
. th Pl d P2 are used as simple 1/ 0. However, J1\
In 8051-based systems with no external memory connection, bo an
1 . h PO to provide the 16-bit
s031 /5J-based systems with external memory connections, po~t 2 must~ used a ong _w•~ 5 indicatin its dual func-
address for the external memory. As shown in Figure8-l, port 21salso desi~ated as AS A ' 16 bits~f the address.
tiQn. smcean 8031/51 is capable of accessing 64K bytes of external memory, it needs a path for the th ords
While PO provides the lower 8 bits via AO - A7 it is the job of P2 to provide bits AS· A15 of the address. in° d ~r 11 w t
when the 8031/51 is connected to external m:mory, P2 is used for the upper 8 bits of the 16-bit address, an canno
be used for 1/0. This is discussed in detail in Chapter 14. . ts PO Pl
From the discussion so far, we conclude that in systems based on 8051 m1crocontr~Hers, \Ve have three por ' . ' r~
and 1'2, for 1/ 0 operations. This should be enough for most microcontroUer applications. That leaves port 3 for mte
rupts as weU as other signals, as we will see next.

Port 3
Port 3 occupies a total of 8 pins, pins 10 through 17. Lt can be used as input or output. P3 does not need any puU-up
resistors, the same as Pl and P2 did not. Although port 3 is configured as an input port upon reset, this is not the way
it is most commonly used. Port 3 has the additional function of providing some extremely important signals such as
interrupts. Table 8-1 provides these alternate functions of P3. This information applies to both 8051 and 8031 cltips.
P3.0 and P3.I are used for the RxD and TxD serial communications signals. See Chapter 10 to see how they are
coMected. Bits P3.2 and P3.3 are set aside for external interrupts, and are discussed in Chapter 11. Bits P3.4 and P3.5
are used for Timers O and l, and are discussed in Chapter 9. Finally,
P3.6 and P3.7 are used to provide the WR and ID:> signals of external Table 8-1: Port 3 Alternate Functions
memory connections. Chapter 14 discusses how they are used in 8031· Pin
P3 Bit Function
based systems. Ln systems based on the 8051, pins 3.6 and 3.7 are used
!or 1/0 while the rest of the pins in port 3 are normally used in the P3.0 RxD 10
alternate function role. P3.l TxD 11
P3.2 INTO 12
Program counter value upon reset P3.3 INTI 13
Activating a power-on reset w;JJ cause aU values in the registers to P3.4 TO 14
be lost. Table 8-2 provides a partial list or 8051 registers and their val-
lleS after power-on reset From Table 8-2 we note that the value of the
P3.5 TI 15
PC (program counter) is Oupon reset, forcing the CPU to fetch the first P3.6 WR 16
opcode from ROM memory location 0000. This means that we must
place the first byte of opcode in ROM location Obecause that is where
P3.7 -RD 17
the CPU expects to find the first instruction.
Table 8-2: RESET Value of
Some 8051 Registers
Machine cycle and crystal frequency
Regis ter Reset Value (hex)
As we discussed in Chapter 3, the 8051 uses one or more machin
~te an instruction. The period of machine cycle varies am
1
e c~c es to PC 0000
:~•ons of 8051 from 12 clocks in the AT89C51 to l clock. thonDS8gthe different DPTR
= 0000
d' tal'able 8-3· Th e frequency o f the crystal oscillator
. m eto th 9C4x0
connected X chip
. · ACC
~cites the speed of the clock used in the machine cycle. Prom Tabl: • X2 pins 00
'nd :!,~!!'at using the same crystal frequency of 12 MHz for both th8-3, we can PSW 00
d1i ~"""'-4x0 chips gives performance almost 12 times bett e AT89CS1
SP 07
fl<~l'he r~ason we say "almost" is that the number of mac~~eom the '?589C4x0
di,..,,.~-~- mstruction is not the same for the AT89C5l and DS8 cycles•! takes to B 00

---
-..,,.,., tn Chapter 3. 9C4xQ chips as we
PO-P3 FF
llls1 HAR
OW ARE CONNl!CTION ANO JNT1!L HEX FILI!
187
I . B051 Versions
) for Vanous
. eyde (MC Machine Cycle
Table 8-3: Clocks per Machine Clocks per 12

Chip (Maker) 6
AT89C51 / S2 (Atmel) 4
P89C5.JX2 (Phillips)
OSSOOO (Dallas Semiconductor) l
0589C4x0 (Dallas Semiconductor)

l
l Example 8-1 . . if the )CTAL frequency .15 22.MJ-lz . r
,,
I. Find the madune cycle (MC) for the:owing chips
a) AT69C51 b) DS89C4XO c) D5S

Solution:
l /22 ~!Hz= 45.45 ns
Referring to Table 8-3,
(a) MC= 12 x 45.45 ns = 545.4 ns
(b) MC= l x ~SAS ns = 45.45 ns
(c) MC - 4 x 45.45 ns - 181.8 ns

Review Questions
1. A given AT89CS1 chip has a speed of 16MHz. What is the range of frequency that can be applied to the XTAU and
X'TAL2pins? . ?
2. Which pin is used to infonn the 8051 that the on<hip ROM contains the program.
3. Upon power-up, the program counter (PC) has a value of .
4. Upon power-up, the 8051 fetches the first opcode from ROM address location _ _ __
5. Which 8051 port needs pull-up resistors to function as an 1/0 port?

SECTION 8.2: DESIGN AND TEST OF DS89C4x0 TRAINER


In lhlsse<:tion we show COMeclions for 8051-based systems using chips s uch as the AT89C5l and DS89C-1x0. If you
decide to wire-wrap one of these, make sure that you read Appendix Bon wire wrapping.

AT89C51/52-based trainer connection


In systems based on an A T89C51 /52-type microcontroller you eed RO · the
microcontroller. For the AT89C5J, !he ROM burner can erase 'th nn a _M bu mer to burn your program mto .
In the case of the 8751, you also need an EPROM erasure tool ,. e ~sh ROM m addilion to burning a program into 11.
erase its contents first, which takes approximately 20 minut s~ce~uses UV-EPROM. To bum the 8751, you need to
since it has flash ROM. es or ·EPROM. For the A T89C5t, this is not requi...,.J
Figure 8.5 shows the minimum connection for the 8751 89CS
0
an 8751 or 89C51 has on<hip ROM for the program_ AJs r . l-base,t system. Notice that "EA= v ." indicates th.II
use a;
availability of PO for l/0 operations. If you need to noocc the PO_ connection to puU-up resist~ ensure tht
omentary switch t RE 10
DSS9C4x0 family or SET, refer to Figure 8-3 (b).

The DS89C4x0 chip from Maxim/Dallas Semicond .


also has a built-in loader allowing it to download ro uctor '.5 ~ 8051 type rn.icr . It
need for an external ROM burner. This important fea~arns into the chip via th O<:o~trolJer with on-dup Oash ROM
home development systems. re ma.kes the DS8gc x ~ s_enaJ ~ort, therefore climinabng_~\
40
hip an idea.I candidate for 8051-ba><"
188

llill sos1 MICR -


0CONTRo -•~
LLER AND EMBEDDED SYST~1" "
. Fl h ROM Size for
c xo flash ROM size Table 8-4: On-CbJp as M ·m-DaJlas
89 4 F ily from aXJ
0 am WWW maxim-ic.com
the DSS9C4x
1)5 . 11 DS89C4x0 chips share the same features, they S miconductor. See ·
W~~ ~ifferent amounts of on-chip ROM. Table 8-4sho~s e On-chip ROM size (flash)
eome'.:'i,· ROM size for various DS89C4x0 chips. Refer tot_ e
the . e:vwA
00
maxim•ic.com for further information. Nobce
..-eb s,ht .1 the T89CS1 comes with 4K bytes of on-chip ROM,
Chip
DS89C420/30
16K bytes
321< bytes
...~ e AT89C52 comes ,vith SK bytes, the DS89C4x0 has
0 ,1 w 1 e
. DS89C440
,nd ~htesof on-chip ROM. Also notice that the DS89C430 15 3 64.K bytes
16 DS89C450
ym.ent for the DS89C420 with the bugs fixed.
repK1ace

Vee 10 K
> > > ? .> -?
+ -~
8751/89CS1
~~:;~:.E:E~i
.. >- "I .. .. ..

_: ~ 10 uF 31 r--,--- - -- ~ u >-+--l--1f-+ --t-t-1


rl , EA / VPP P0.0 ~ - --+ -t-J-T"°i"- I "
~
1
: >:: 30 p'F l 19 Xl PP00.2l ~ - - _..-1r + -t-r ,
:> 0 11.0592 MHz P0..3 ~ - - -~._+ -t-f-1 °
8.2 K T 1--- - ---4- r - t - 1
...___._, ·~ - - - - -"'.".:4 X2 P0.4 l--- - -- -- - -t--r-
', 1s ro.s 1---- ------ - r
30 pF
9
RST P0.6
l'0.7
1-- - -- - -- ----<o-
P3.0/ RXD
P3.1 / 1XQ. P2.0
P3.2/ ll:itl) P2.I
P3.3/ INT1 1'2.2
P3.4/ TO 1'2.3
P3.5/T1 1'2.4
1'2.5
PLO 1'2.6
Pl. 1 1'2.7
Pl.2
Pl.3 PSEN
Pl.4 ALE/ PROG
Pl.5
Pl.6 P3.6 \'ill._
Pl.7 P3.7/ RD

Figu,. S.S. Minimum Connection for89CS1/52-Based Systems

~mpteS-2

Find the address space for the on-chip ROM of the following chips.
(a) AT89C51, (b) AT89C52, and (c) D589C420/30
Solution:

{a) AT89C51 has 4K bytes of on-chip ROM. That giV<!S us 4 >< 1024 = 4.()96 bytes. Converting the 4096 to hex, we
get IOOOH. Therefore, the address space Is 0000 • OPPFH.
(bJ AT8<JCS2 has SK bytes of on-chip ROM. That gives 119 8 >< 1024 • 8,192 bytes. Converting the 8,192 to hex, we
get 2000H. Therefore, the addme space is 0000- IFFFH.
!c) D589c420/30 has 161C bytes of on-dtip ROM. That gives us 16 ,c 1024 a 16,384 bylea. Conw,tb.g the 16,384 to
hex, we get 4000H. Theiefon, thr addre9s space ifl 0000 - 3FFFH.

~~H-A-kD-W
~AR-E~CO~N-N-ECTI~-O-N_AN_D_INTE~-l~HEX~-A-l-E~~~~~~~~~ ~ ~ ~ ~ ~ ~ ~ ~ -
189
I
Maxin1-Dallas SemJCOnd
chI'p taken S 0 w how to use them bi
frOOld thhe
f the OS89C4x0 9(4,<0
of the [)58 of t/leSI! fea 1:tJfe5 an
Key features o th key featuJCS k at manY
some of e
The following are axim-ic.com,) We will loo
webs1' te (http://www.m
chapters.

SOCS2 compatible mpatible


1.
(a) 8051 ~i-~:::: truction-set co
.
1 l/ 0 ports
(b) Four 1'6-b'I t timer counters
l (c) Three d RAM
(d) 256 bytes scratchpa
2. On-chip flash memory
1
t. (a) 16KB for OS89C4lO/JO
(b) 32KB for OSS9C440
(c) 64KB for DS89C4SO h the serial port
• 3. ln-system progra aunable throug
,... lKB SRAM for MOVX
4 ROMSIZE Feature ize from Oto 64K
. al gram memory s
f (a) Selects intern pro . external memory map
(b) Allows access t~ entib~ b software
(c) Dynamically ad1usta e Y
S. High-speed architecture cl
(a) 1 clock per machine ~y e
(b) IX to 33MHz opera_tio~
(c) Single-cycle ~tructlon m 30 ~ to access fast/ slow peripherals
(d) Optional vanable length MO
6. Two full-duplex serial ports
7. Programmable watchdog timer
8. 13 interrupt sources (six external)
9. Five levels of interrupt priority
10. Power-fail reset
11. Early warning power-fail interrupt

0589c4x0 trainer connection .

We selected the DS89C4x0 for an 8051 Tr~iner because it is inexpensive but powerful, and one can easily wue-
it to be used at work and h~me. The connection for the DS89C4xO Trainer is shown in Figure 8-6.
lf you decide notweb
MicroDigitaLEd.com to "'.'re-wrap
site. the tramer
. yourself, you can buy this DS89C4xO-based Trainer from the

two Using
major the D589C4x0 for development IS more advantageous than using the
reasons. or S9CSl systeo, for the foll
8751

I. Using the DS89C4x0 for an 805h I microcontroUer allows us to program the hi 'th need for a
burner. Because not everyone as access to a ROM burner th nc.,;;- . c p Wl out any l'slll!
~
The advantage of the DS89C4x0 is that it can be progranuned -h"'-4xO is an ideal home-developmen~ IO
while it is in the system. Contrast this with the 89<:51 syste ~lat e COM port of a PC (x86 IBM or compa it.
install it back in the system every time you want to change~: which you must remove the chip, progra?' ~
2 in a much longer development time for the 89Cs1 system Program contents of the on-chip ROM. ThlS
. The two serial ports on the DS89C4x0 allow us to~ onecompared t . With the Dss9c4xO system. 411'
acquisition. Or Pc tnterfactng With the chip, and the other fer

190 ~:::-::--------:::-::-.:
Nl'R.otLER. AND EMBEDDED
+SV +5V
~ T
i~ -j 11-lOuF VCC 2 5 2
DB·9F

~~
~
'--"--- -- - -- -------1 RST
8.2k
TxDl---t~
4 30
+SV 5
lk
lk DS89C4x0 =
10k J,-----1 D.
t - -;:,;;;.-1:'. 2N3904 )
Ty P2.6 )
OPEN OR
P2.71----0 PULLED UP
6 0 b.RUN = 30pf
c. t: , __4 _--,ili, ,.Ok;;.....t"'- - ---1 PSEN XTA Ll~ -..---lh
<ll 3: y, ' 2N3904
!!l. j_PROGRAM 30p
= GND XTAL21-.-..- - - IH
= 11.0592 MHz
=

figure S-6. DS89C4x0 Trainer (for MAX232 connection, see Section 10.2)

Notice from Figure 8-6 that the reset circuitry and serial porl connections a re the sam e as in any 8051-based system.
However, the extra circuitry needed for programntlng are two transistors, a switch, and !OK and lK-o hm resistors. 1n
fact, you can add these components to your 8751/89C51 system and use it as a DS89C4x0 system by simply plugging
• D589C4x0 chip in the socket. The switch allows you to select between the program and run options. We can load our
program into the DS89C4x0 by setting the switch to VCC' and run the program by setting it to Gnd .
FigureS-Oshows the connection for the8051 Trainer from www.MicroDigitalEd.com. The Trainer provided by this web
site has both of the serial ports connected and accessible via two DB-9 connectors. It also has 8 LEDs and 8 switches along
with the PO - P3 ports, all of which are accessible via terminal blocks. It also comes with an on-board power regulator.

See the following Web site for the OS89C4x0 Trainer:

www.MlcroOlg ltalEd.com

Communicating with the DS89C4x0 trainer


Alter we build o ur DS89C4x0-based system, we can communicate with it usin th H T .
HyperTerminal comes with Microsoft Windows 98, NT, 2000, and XP. g e yper errruna l software.

Using HyperTerminsl with the DS89C4x0


'?55Uming that your serial cable has a DB-9 connector on both end .
mun,cation between the DS89C4x0 Trainer and HyperTerminal. s, we take the foUow,ng steps to establish com-

1.
With the trainer's power off, connect the COMl port on the back of PC
2. Th your to one end of the serial cable
e other end of the serial cable is connected to the DB-9 co . ·
SERlAUO. After you connect your DS89C420 Trainer to you p~ection on the ~9C4x0 Trainer desigJlated as
gram position. r • power up the trainer. Set the switch to the pro-
3. In Windows Accessories, click on HyperTermina!. (lf ou . .
---. Y get a modem mstallation option, choose "No".)

~~:H;A~;;:;;;;;;;;;;~;;;~~;;;:;;:-;;;:;;;~~~~~~~~~~~~~~~~~~
" ROW ARE CONNl!CTION AND INTEL HEX FILE
191
I

vtR,SJGJil 1.0
DS-S9C'420 LCAD~

,,
\,

' .WO Of*,I 57&00 I H 1


:'<>•-•01 , . J for OS89C4x0 Trainer
• Figure ~7. Saeen Cipture from Hypt.rTenmna

Type a name, and dick OK (or HyperTem1inal will not let you go on).
:: For "Connect Using" select COM1 and dick OK. Choose COM2 if COMl is used by the mouse.
6. Pick 9600 baud rate, 8-bit data, no parity bit, and l stop bit.
7. Change the "Flow Control" to NONE or Xon/Xoff, and click OK (Definitely do not choose th~ hardware optiml
8. Now you are in Windows HyperTerminal, and when you press the ENTER key a couple of times, the DS89COA"~
will respond with the following message: DS89C420 LOADER VERSION 1.0 COPYRIGHT (C) 2000 I.UV
SEMICONDUCTOR>

If you do not see">" after pressing the ENTER key several times, go through the above steps one more time. lllll. I
if you do not get">", you ~eed.to check your hardware connections, such as the MAX232/233. See the end of thi,!lt' t t
tion for some troubleshooting bps.
'
I
I
Loading and running a program with the DS89C4x0 Trainer I
After we get the">" from the DS89C4x0, we are ready t I
the file you are loading. is in lnt!I hex format. The Intel hex fo~~~ the P_rogram into it and run. firs t, make sure
1
I
about Intel hex format 1s given m the next section. 15 provided by your 8051 assembler I compiler.,
I

Erase command for the DS89C4xO '


To reload ~ DS89C4x0 chip with another progr .
wiU erase the entire contents of the flash ROM of the~- we first nee.i to e .
the ROM before you can reload any progra1t1. You chip. Remember that rase Its contents. The K (Klean) c·Ollll!lm
i•~
command to display ROM contents on sereen. y 0
">K" command.
verily the operati you rnust use the ">K" comma11d to
s Ould see aU FF . on of the ">1<" command by using the
Go to www.MicroOigitalEd.com to see the above steps
5
an all the locations of ROM after applyil1
''
192
Presented with
screen shots.
'
ding the program
L08 .. h th ">" prompt on your screen,
After making sure that you have the switch on the program position and you ave e
go thrOugh the following steps to load a program:
At the ">" prompt, enter L (L is for Load). Example: ">L" and press Enter.
1.
Ill HyperTenninal, click on the Transfer menu option. Click on Send Text File.
2,
3- Select your file from your disk. Example: "C:test.hex" d
,. \,Vail until the loading is complete. The appearance of the "GGGG>" prompt indicates that the loading is good an
finished.

5 Now use D to dump the contents of the flash ROM of the D589C4x0 onto the screen. Example: >D 00 4F .
The durnp will give you the opcodes and operands of all the instructions in your program. You can comp~re this
information with the information provided by the list file. In the next section, we will examine the Intel hex file and
compare it with the list file or the test program.

Running the program


Change the switch to the run position, press the reset button on the D589C4x0 system, and the program will exe-
cute. Use a logic probe (or scope) to see the PO, Pl, and P2 bits toggle "on" and "off" continuously with some delay in
between the "ON" and "OFF" states.

Test program for the DS89C4x0 in Assembly and C


To test your DS89C4x0 hardware connection, we can run a simple test in which all the bits of PO, Pl, a.nd P2 tog·
gle continuously with some delay in-between the "on" and "off" states. The programs for testing the trainer in both
Assembly and C_ are provided below. N_otice that the tin,e delay is for a D589C4x0 based on the 11.0592 MHz crysta l
freque~cy. Th,s tlJl'le delay must be modified for the AT89C51 /52 chips since DS89C4x0 uses a machine cycle of 1 clock
penod instead of the 12 clock periods used by the AT89CSI /52 chip.

Trainer Test Program in Assembly


ORG OH
AAIN: MOV PO, #SSH
MOV Pl, #SSH
MOV P2, #SSH
MOV RS, #250
ACALL MSOELAY
MOV PO, #OAAH
MOV Pl, #OAAH
MOV P2, #OAAH
MOV RS, #250
ACALL MSOELAY
SJMP MAIN
; ·-- · -· ·· --250 MILLISECOND DELAY
MSDELAY:
l!ERE3: MOV R4, #35
HERB2: MOV Rl, #79
H1!RE1: DJNZ R3, HBREl
OJNZ R4 , HERE2
DJNZ RS, HEREl
RET
END MAIN

---
IOsi ll>.Row ARE CONNECTION AND INTEL HEX FILE
193
I
Trainer Test Program In C
#include <regsl.h> d
void MSOelay~unsigne intl;
void main (void)
{ fo:reve:r
//repeat
while(l )
{ o Port
//send value t
PO•Ox55;
Pl=OxSS;
P2=0x55; function
MS0elay(2SO}; //call 2SO m:o port
PO= OxAA;
//set value
Pl= OxAA;
P2 • OxAA; function
MS0elay(250l; //call 250 ms
)
)
.
void MSDelay (uns19ned l• nt itimel
{ . .
unsigned int 1, J;
for(i•O;icitime; i++)
for lj•O ;j<l27S;j++J;
)

OS89C4x0
There are commands
many commands embedded .mto the D589C4x0 loader. The most widely used among them are L, K,a:d
-
D. Here is the summary of their operations.

L Load standard ASCII Intel hex formatted data into flash memory.
K Erases the entire contents of flash memory.
D <begin> <end> Dumps the Intel hex file.

we have shown the use of the L (load), I< (klean), and D (dump) commands earlier. A complete list of col!U!W'li
and error messages can be obtained from www.MicroDigitalEd.com.

Some troubleshooting tips


Running the test program on your DS89Cx0-based trainer (or 805! s ) . with di
delay. If your system does not work, follow these steps to c_d th ystem should toggle all the I/0 bits
w, e problem.
L With the power off, check your connection for all pins es ·a11
2. Check RST (pin 119) using an oscilloscope. When the' pea .y Vcc and GNO· ...
momentary sw,·1ch •'t goes high . M·'· system
.u.e sure the momentary IS po
Switch . wered up, pin #9 is low. Upon press•;,a.., ..
3. Observe the XTAl.2 pin on the oscilloscope while th . IS connected properly.
cates that the crystal oscillator is good. • Power is on. You should This-
4. If all the above steps pass inspection, check the c see a crude square wave.
must be the same as the opcodes provided by the ~~t~ts of the on"(.tup . ~I
Lists the opcodes and operands on the left side of ht £iJe of l'i&ure • y ROM starting at memory locabon ~
of your on-chip ROM if the proper steps were tak t ~ •SSell\bly instri;
8 8 .0 Ur assembler produces the list filt~
bllrning and lo~~~ns. This must match exactly the ~
10
en
ing the program into the on<hiP
194
LOC OBJ LINS
ORG OH
0000 l
MAIN: MOV PO, #SSH
0000 758055 2
MOV Pl, #SSH
0003 759055 3
MOV P2, #SSH
0006 75A055 4
5 MOV RS, #250
0009 70PA
ACALL MSDELAY
0008 lllC 6
0000 7580AA 7 MOV PO, #OAAH

0010 7590AA 8 MOV Pl, #OAAH

0 013 75AOAA 9 MOV P2, #OAAH


0016 70FA 10 MOV RS, #250
11 ACALL MSDELA'i
0018 lllC
OOlA 8084 12 SJMP MAIN
OELAY.
13 •.•. · THE 250 MILLISECOND
14 MSOELAY:
OOlC 7C23 15 HERE3: MOV R4, #35
OOlE 7B4F 16 HERE2: MOV R3,#79
0020 OBFE 17 HEREl: OJNZ R3, HEREl
0022 OCFA 18 OJNZ R4, HERE2
0024 OOF6 19 OJNZ RS, HERE3
0026 22 20 RET
21 ENO

Figure S.S. Lisi File ForTes l Program (Assembly)

Review Questions
I. True or false. The DS89C4x0 is an 8052 chip.
2. Which pin is used for reset?
3. Whal is the status of the reset pin when it is not activated?
t What kind of ROM is used in the DS89C4x0 chip? .
S. The loader for the DS89C4x0 works with the (senal, parallel) port.
6. Give two reasons that the DS89C4x0 is preferable over 89C51 crops.
7. ln the DS89C4x0 Trainer, what is the role of the Prog/Rw, switch?
8. What is the highest frequency that we can connect to the DS89C420/30?
9. True or false. The DS89C4x0 can download the file into its ROM only if it is in Intel hex file format.
10. Which command is used to erase the contents of ROM in the DS89C4x0 chip?
II. Which command is used to load the ROM in the DS89C4x0 chip?
12. Which command is used to dump the contents of ROM in the DS89C4x0 chip?

SECTION 8.3: EXPLAINING THE INTEL HEX FILE


Intel hex file is a widely used file format designed to standardize the loading of executable machine codes into a
~OM chip. Therefore, loaders that come with every ROM burner (programmer) support the Intel hex file format While
In ll\any newer Windows-based assemblers the lntel hex file is produced automatically (by selecting the right setting),
Ina Dos.based PC you need a utility caUed OH (?bject-to-hex) to produce that. In the IX)S environment, the object file
~l'dtntothe linker program to produce the abs file; then the abs file is fed into the OH utility to create the Intel hex file.
ile the abs file is used by systems ~t have a monitor program, the hex file is used only by the loader of an EPROM
l'!Ogramme.r to load it into the ROM crup.

;;;;;:A-R_D_W
_AR~E-C_O
_N_N~J!C-C-11-0-N-AN~D~IN-TE~L-KEX~-A~L-E~~~,__..,.....,.....,_..,.....,.....,.....,.....,.....,.....,.....,.....,..._1~95
I
,v.9f
fA111C7580 &4FOI
OO(XXJ(XY7":,&l5Sr:fl()5575A::i11c80E47CZ37
:1 5AOAA
,1000100075~AODf62235
,07002()0008
,CJ()OOOOO!fF ·ng
. th• rouow•
Id we gel ss
Seperaling the fie s DDDDD
DDDDDD 9F
I ppDDDDDPD 75SOAA
TT 01
,cc AMA oDDDD:~:~~==75A05S7P:~!!~~2 37B4 P
0000 00 75805 p.A DFA111C
:10
00 7590,a.A?SAO 7 35
,10 0010
0020 00 OBFEl)CFAPDF622
,07
,00 0000 01 FF
1

,,
\,
. Te.sl Prograim as Provided by th • A
Fig·ure S-9. lntel H,x: File
ssembler

Program list tile for test program LOC and OBJ fields in Figure 8-8 ~ust be noted.~
. . en in Figure 8-8. The Th LOC and OBJ informa tion 1s used to createlht s
The list file for the test program LS g,v ·ect codes) are placed, ~
location is the address where the opcodes (obj . to the list file of Figure 8-8. t
hex file. Next, we will analyze the hex file belonging

Analyzing Intel hex file
Figure 8-9 shows the lnteI hex fil e i or the test program
. ROM
h
w ose 1
. t file is given in Figure 8-8. Since the ROM bUl!il!
is file must provide the f o IIow1ng:
the hex · (1) the numbu
(loader) uses the hex file to download the ~pcode mto ·iself and (3) the s tarting address ,v h ere the information mllll
- '
or bytes of information to be loaded, (2) _the '"rformaa.on; F' ' re 8- we have separated the pa rts to make it easiei 11>
be placed. Each line o( the hex file consists o six parts. n •gu 9,
analyze. The foUowing describes ead, part.
I. ":" Each line starts with a colon.
2. CC, the count b)•te. This teUs the loader how many bytes are in the line. CC can ra nge from 00 to 16 (10 in hex). •b
3. AAAA is for the address. This is a 16-bit address. The loader places the first byte o f data into this me!llM :r
address. ;n
4. n is for type. This field is either 00 or 01. I( it is 00, it means that there are more lines to com e after this line. Uit~ I ii
01, it means that this is the last line and the loading should slop after this line. iA
I I
5. ~ D ..... D is ~erealinfo~mation (dataor code). Thercisa maximum ofl6 b tes i thi t Th I der lacestlns
mformaoon mto successive memory locations o ( ROM. Y n S par · e oa P
6. SS is a single byte. This las t byte is the checksum byte o( eve th' · .
checking. Checksum bytes are discussed in detail in Cha t ry ing III tha t lane. The checks um byte is used forerr<J
--
each line represents everything in that line and noti'ust thp edrs 6 and :· Notice that the checksum byte at the end~
e ata portion.
. No~, c~mpare the d~ta portion o ( the Intel hex file in Fi .
ILSt file m Figure 8-8. Nohce that they are identical, as they sh~': t!
with the inlormation unde r the OBJ field oftl,t
· · The extra information is added by the Jntelhtl
Enmp!e 8-3
From Figure 8-9, analyze the six parts of line 3
Solution:
Arter the col on(:) we have (Tl, w hich means that
the dat.t starts. Next, 00 means that this IS not ~ven byt~ of d
follows: DB FE DC FA DD F6 22. Finally the I~
'
t~t
line of !he ata are in this line nn-.nH . he ad_._ ... -
-t w1te 3S · ~Ord 'I\._ _ • """ ' IS t ~.,
' ' IS !he ch.._, · '""" the data wh.ich · · - - 1,y• ...
15
"""'Suin byte. ' ""·-·
196
l'ltE 80St l\,fJ
Clocol>fr ~--'
lOLLER AND EMBEOOEOSY51....-
·ru tion is not corrupted.
Vrrifi the checksum byte for tine 3 of Figure 8-9. Verify also that the I
orma

solution: . th · (5) uives CBH a.nd .,ts 2,s


(fl + 00 + 20 + 00 +DB+ FE + DC+ FA+ DD + F6 + 22 = SCBH. Dropping e carries o· '
complement is 35H, wt,Jch is the last byte of Line 3. . h Id et oo.
If we add all the information in line 3, including the checksum byte, and drop the carries we s ou g
07 + 00 + 20 + 00 + DB + FE + DC + FA + DD + F6 + 22 + 35 = 6001-1

Example 8-5
Compare the data portion of the Intel hex file of Figure 8-9 with the opcodes in the list file of the test program
given in Figure 8-8. Do they match?

Solution:
In the first line of Figtlfe 8-9, the data portion starts with 75H, the opcode for the instruction "MOV", as shown in
the list file of Figure 8-8. The last byte of the data in line 3 of Figure 8-9 is 22, which is the opcode for the "RET"
instruction in the list file of Figure 8-8.

file formatter. You can run the C language version of the test program and verify its operation. Your C compiler will
provide you both the list file and the Intel hex file if you want explore the Intel hex file concept.
Examine the next three examples to gain an insight into the Intel hex file.

Review Questions
I. True or false. The Intel hex file uses the checksum byte method to ensure data integrity.
2. The first byte of a line in the Intel hex file represents .
3. The last byte of a line in the lntel hex file represents--- - - -
4. In the TT field of the Intel hex file, we have 00. What does it indicate?
5. Find the checksum byte for the following values: 22H, 76H, SFH, SCH, 99H.
6. In Question 5, add all the values and the checksum byte. What do you get?

SUMM ARY
This chapter began by describing the function of each pin of the 8051. The four orts f th 8051 p
l
P3, each use 8 pins, making them 8-bit ports. These ports can be used for input or outpp t 0 rt Oe

. . signals
2
b' O, Pl, P ,. and
address or data. Port 3 can be used to provide interrupt and sena
..,,. •
· 1 commurucation Thca.n the used
d · for either
f
0
uao9C4x0-based trainer was shown. We also explained the Intel hex format. · en e esign o the

PROBLEMS
SECftON 8.1: PIN DESCRIPTION OF THE 8051
1. The.8051 DIP package is a ·pin package.
!· Which are the functions assigned to pins 20 and 40?
· ln the 8051, how many pins are designated as 1/0 port pins?
4· The crystal oscillator is connected to pins and
5· If a~ 8051 is rated as 25 MHz, what is the maximum frequenc th t ·
6 lnd1c.a te th~ pin number assigned to RST in the DIP packa e. Y a can be connected to it?
7
~- : 1s an (,~put, output) pin. g
at function docs pin 9 carry out?

197
I RESET 0
fthe8051?
ram counter) upan 8051?
ntents of the PC (prog RESET of the ,,,.~
9 _ \\lh.1t are the co ts f the SP regi,ter upon U:SET ~ignal? than the g,.__,11
JO "'h.>t are the conten o . duration of the E r crformance
11 Wh,,t should be the =~mOchip g,ves 12 limes bette n~ted? S')CSI pin is connected to (Vee, CND).
12 Wh)' »,t said that.a 'whiCh pin should it be con 8751 and the '
3 If a TfL osciUator ts used, on hi ROM such as the
I. For 8051 fam1lv
1~ , members "~th . on-c p
15 !'SEN is an (input. output1p1~E s,gnal? (8051, 8031),
t6 What i> the funebon_of the A based on the . e DIP package?

19. How many pms are des~gna


in::
17 ALE is u.sed mainly m systems s PO and what are those m th DIP package?
18. How many P'.ns .ire des~gna::: :s Pl and what are those
. and what are those JJ1
DIP package?
ackage?
20. How many pins are designated a, P2 nd what are those in the D_IP Pt output).
21. How many pin, are designated as P3 a nfi red as (mpu '
22. Upon RESET, all the bits of ports are co ~or to be used as J/0? d solely for 1/0?
2.1 In the 8051, which port needs a pull-up res IS te function and can be use
2~ \'lhich port of the 8051 does not have any altema
.'
SECTION 82: DESIGN AND TEST OF DS89C4x0 TRA CNER
t' l
25. What are the functions of pins 1'3.4 and P35? . . _
26. 'A'hy is pm 31 connected to V« for the sy,tcm ,n Figure 51.
8 j.

{ 27. In P3, wluch pins are for RxD and TxD?
28. At what memory location does the 8051 wake up upo .
n RESET? What is the implication of that?
29. Write a program to toggle aU the bits of Pl and P2 conbnuous1Y
(a) using AAH and 55H (b) using the CPL 1r1Strucbon
•I
30. ~Vhat is the address of the last location of on-<:hip ROM for the AT89C51?,
31 What is the address of the last location of on-chip ROM for the DS89C420.
32. 1-Vhat is the address of the last location of on-chip ROM for the DS89C440;
33. \\'hat is the address of the last location of on-chip ROM for lhe DS89C450.
34 What is the range of frequency allowed for DS89C4x0?
35. \\'hat ,s the slowest frequency lhat D589C4x0 can run on?
36. \Vhat are the functions of pins TxD and RxD?
37. Before we reprogram the DS89C4x0 we must (dump, erase) the flash ROM.
38. How many timers/counters has the DS89C4x0?
39 Give two features of the DS89C4x0 that earlier 8051 and 8052 chips do not have.
40. After downloading a program, the DS89C4x0 gives the message ">GCGG". What does it mean?

SECTION 8.3: EXPLAINING THE INTEL HEX FILE


41 What is obtained in the HFX file?
42. In Figure 8.9, what is meant by the column lT?
-13. Verify the checksum byte for lme 1 of Figure 8-9 and also verity th . . .
Verify the checksum byte for line 2 of Figure g.9 and also ver· at the ~orrnat~on is not corrupted.
41.
45.
~-
Reassemble Lhe test program with ORG addr,,>s,, of lOOH and
Reassemble the test program w,th ORG address of 300H d
'7 ~·~
1 1 the mforrnanon ,snot corrupted.
na yze the Intel hex file.
47. Write a program to toggle all the b11s of Pl and P2 cont~ oo~pa~ the Intel hex file "~th the results of Problem -15.
inuous y with no deldy and analyze the l ntel hex file.
ANSWERS TO REVIEW QUESTIONS
SECTION 8.1: PIN DESCRIPTJON OF THE 8051
l. From Oto 16 MHz, but no more than L6 MHz
2. EA
1. PC = ()(JO()
-l 0000
5. Port 0

198
TH esos1 MtcRoc o -
NTROLL"R
'" AND EMBEDDED SYSTE~iS
sECflON 8.2: DESIGN AND TEST OF DS89C4x0 TRAINER
1. True
2. pjn9
3. 1.0,v
4. Flash
s. Serial
6. (a) It comes ,vith a loader inside the chip and (b) it has two serial ports
7. The SW allows to load the program or to run it.
8. 33 MHz
9. True
10. >K
11. >L
12. >D

SECTION 8.2: EXPLA!NING lNTEL THE HEX FILE


l. True
2. The number of bytes of data in the line
3. Checksum byte
4. 00 mea.ns this is not the last line and there are more lines of data to be foUowed.
S. 22H + 76H + 5FH +SCH+ 99H = 21CH. Dropping the carries we have lCH and its 2's complement is E4H.
6. 22H + 76H + 5FH +SCH+ 99H + E4 = 300H. Dropping the carries we have 00, which means data is not corrupted.

-
IOst IIARDWAll CONNIC110N AND INTEl Hl!X FILE
199
CHAPTER9

8051 TIMER
PROGRAMMING
IN ASSEMBLY AND C

OBJECTIVES
i
'
I Upon completion of th,• chapter, you will be able to:

> List the timers of the 8051 and their associated ~gisters ./
> ~ribe the various modes of the 8051 nmcrs
> Program the 8051 timers ITT Assembly and C to generate timi: delays
> Program the 8051 counter~ ,n As."<!mbly and C a, event cot,nters
I to gener,1 le ,
, time dday or as counters to,
. ·"'1r~
<;Cd either a~ timers timers are uS<.>d to general,• trme del.li·
The 1,()51 ha< I:\"' tJmcrs/counters They can be~ 9 1 we ,.ee hoW these C language to program the 8051 tin,' In
e, enb h•pperung outside the m1crocontr0Uer. l.n ~: ·In 5ection 9.3 we use •ri.
Sc>chon 9.2 we show how they are u.sed as event roun

SECTION 9.1: PROGRAMMING 8051 TIMERS . tirnersoraseventcounters. ln this'<'C"-


bc used either as · d I ...,
The so,1 has two tuners: TimerO and Timer t They can th timers to generate tune e ays.
we first discuss the timers' registers and then show how to program e

Basic registers of the timer . . timer


8-bit architecture, each 16-bit . . accessed.,
1s
Both Timer Oand Timer J are 16 bits wide. 51.llce the 8051 has an t 1 ·
two separate registers of I~ byte and hip,oyte. Each timer rs drscussed separa e Y·
;
Timer O registers
11,c l(l-b1t regi.,ter of Timer ois acce,,ed as tow byte and high byte. The low byte register is called TLO (Timer Oloi,
,i ~yte) ond the high byte register., re/erred to as THO (rimer Ohigh byte). These registers can be accessed like any oi!i;.,
reg,stt<r, such•• A, B, RO, RI, R2, etc. For example, the in,truchon "MOV TLO, #4 FH" n1oves the value 4FH into TlO
I the lo" byte of Timer 0. TI,ese registers can also be read Ii.kc any other regi,ter. For example, "MOV RS, THO" sa,·~

r ,n
THO (h,gh byte ur Timer 0) RS (See Fill"re 9.1)

Timer 1 registers

(flmT:;r;e~~~ b~:~) I~!;;';~ ~ts lb·bit regis~cr is split mto two bytes, referred to as TLl (Timer t low byte) .md THI
· grs ers are accessible m the same way as the registers of Timer O (See Figure 9-2).

TMOD (timer mode) register


Both timers Oand 1 use the same register, called TMOD . .
~·~i~g~;~~which the lower 4 bits are set aside for Timer O~n~tth~euvarrous timer operation modes. TMOD is an 8-
discu,sed ne,t lo set the nnwr mode and the upper 2 bits to specify th:~;:;.~~~ r;
T1:;1er 1. In each ca!'oe, the lower
e •gure 9-3) These uptions ar~
(

-M1,MOMOand Ml select the timer mode


timer, mode I is a 16-bit timer, and m~::
.
;~so::a'.~;;ilf"re 9-3, there are three modes·
tuner. We will concentr t · 0, I, .ind 2. l\1ode O "a 13-b:I
aeon modes 1 an d 2 ~tnce they arc !ht

no

Figure 9..1. Timero Registers


03 I I I[)()
02 DI

l DIS IDH IDB I D12 j 011 IDtOI D9 I 0s] G~o~7i1


- -figure 9-2. Tim•r 1 R•gi5tcr, :::::·
i:D: =6~F~l ~ T;
:0:S~~D.;~
L;
l ~~==~I
l ~]l~~I~Q
DlI I D2 DI DO j
202
(MS6) I (LSB)
..,,-
GATE I CIT I Ml I MO GATE ] CIT I Ml I MO

Timer 1 1imer0

GATE Gating control when set The timer/co unter 1.s enabled only while . the INTx pin
is high and the TRx control pin 1.s set. When c1ea red, the timer ,s enabled
whe11ever the TRx control bit is set. aJ
err Timer o r coun ter selected cleared for timer o peratio n (input from intern
system clock). Set for counter operation (input from Tx input pin). l
Ml Mode bit I
MO Mode bit 0
2. I
Ml. MQ. Mode Operating Mode
0 0 0 13-bit timer mode
\,
("'"; - -. 8-bit timer/ counter THx wilh TLx as 5-bit prescaJer

~ I 16-bit timer mode


16-bit tbner/ c:oun ti,rs THx and TLx .ue cascaded; there is
no prescaler
I 0 2 8-bit auto reload
8-bit au to reload timer/coun ter; TH x holds a value that is
to be reloaded into TLx each time it overflows.
1 1 3 Split timer mode .,

Figure 9-J. TMOD Register ..I

ones used most wide!y . We w i ll soon describe the characteristics o f these m o d es, after d escribing the rest of the TMOD
reglster.

CIT (clock/timer)

This bit in the TMOD regis ter is used to decide whether the tim er is lised as a d e la y gen erato r o r an event counter. If
C/ T :0, it is used as a tim er for time d elay generatio n. The clock source for the time d e lay is the crystal frequency of the
8051. This section is concerned w ith this cho ice. The timer's use as an event counte r is discussed in the next section.

Ex•mple 9-1

Find the \'aluc'!> of TMOD to operate ai timers m the following modes.


1
(a) Mode I Timer 1
lb) Mode 2 Timer O, M ode 2 Tuner 1
(c) Mod~ 0 Timer I · •

Solution:

From Figure 9--3 ,.; l"


\ 0 .;,it6
(a) TlloD i e 0001<>000 • 1 0H
The gace control b it and CIT bit are llade o, an4 t be Wl\189d t imtr (Tillllr b i ..
ie alee 01 /. O "
lbJ TMco i .. jlOjf>Olt ,• 5:ilB ~ t:> O I o c, o f 0
k) 1lloo i a OOOOOOOOII • 008

-
- .11, • •• I 0 .

' °5l TIMER PROGRAMMING IN ASSEMBLY ANO C


I
.,.,ith the following Cl)>IJI
se<I ,y~temS,
8()51-bil.
Eumpl• 9-2 . nod for various ·
. ... ,. frequency and its pe
Find the hmer'• c1uu,
frequencies
(a) 12 MHz
(b)l6 MHz -1
(c) 11. 0592 MHz Lf,_)
Solution:
l
XTAL + 12
1 oscillator
,,,.
! d T l/1 MHz= l µs
(a) 1/12 • 12 MHz • 1 Hl!Z an • - 1/1. 333 MHz •. 75 µs
,..,. (b) 1/12 • 16 MHz " 1. 333 MHZ and T -
(c) 1/12 • 11. 0592 MHz • 921. 6 kHz;
T • 1/921.6 kHz= l.085 µs

( NOTE THAT 8051 TIMERS USE 11U OF XTAL FREQUENCY, REGARDLESS OF


MACHINE CYCLE TIME.

'I

Clock source for timer

As you know, every timer needs a clock pulse to tick. What is the source of th~ dock ~ulse for the 8051 ~ers? IT
C/T = o, the crystal frequ,>ncy attached to the8051 is the source of the dock for the timer. This means that the s1zeof the
crystal frequency attached to the8051 also decides the speed at which the 8051 timer ticks. The frequency for the hmer L
is always I / 12th the frequency of the crystal attached to the 8051. See Example 9-2.
Although various 8051-based systems have an XTAL frequency of JO MHz to 40 MHz, we will concentrate on the
.
I

XTAL frequency of 11 .0592 MHz. The reason behind such an odd number has to do with the baud rate for serial com·
8051. XTAL fBM l
munication
as of in
we will see theChapter 10. = 11.0592 MHz allows the 8051 system to conununicate with the PC with no errors,

GATE

The other bit of the TMOD register is the GATE bit. Notice in the TMQ . . . -
I
and l have the GATE bit. What is its purpose? Every timer has a mean D rc~ster of Figure 9-3 that both T1mers_O
by software, some by hardware, and some have both softwar 5 of starting and stopping. Some tin1ers do thiS
both. The start and stop of the timer are controlled by wa of e ~nd hardware controls. The timers in the 8051 hal'e
is achieved by tl1e instructions "SETB TIU" and "CLR Tii" f so;~are by the TR {tirner start) bits TRO nnd TRt . Toil
0. The SETB instruction starts it, and it ts stopped by the CLR ~r ime~ 1, and "SETS TRO" and "CLR TRO" for Time!
as long as GATE =() in the TMOD_register.,The hardware way ~7::~~ion. These iru.tructions start and stop the ti met>
1s achieved by making GATE = I m the TMOD rt><>ister ...
_ GA ting and stopping the t't b tc I soul'(t'
...,. o · th t t I h
, c = , meaning a no ex ema ardware is needed t .., · "owever to • .d
• .. vo1 IUrther con{ , f mer y an ex maill ake
0
the timer where GATE= O all wen-" are th , start and stop the"- us,on or now, we 1v m
, "'-'" e instruct,ons • s
to stop or start the timer is discuss(!(! in Chapter 11 wnen in KTB TRx" and "CLR t'Rx"
rn "ers In u · f d I""
sing SO hv<U"e to start an • -~
Now that we have this basic understand mg of the r are diseusscd · The use of external hardwa
how they are programmed to create a time delay.
1e O7rrupts
Beca: the TMoo 'egister · . d
in detail se ffiodes I .md 2 'we will look at the timer's modes an
· are so Widely USed, we describe ench of them
Eomple 9-3
How are timers Oand l st,1rted and stopped by instructions'

Solution: . . d TRI which are called timer run control


The timers are started by using instructions to set timt'r start bits TRO an . 'x·mum va lue it sets a flag TFO or
. unts to ,ts ma , . , I
bits. They can be cleared by clearing th~ bits. When a timer co i r and l. While TMOD contro s
50
Tfl. At this point, it is necessary to know rnoreabout the b,tsTF an_d TR ;;u::roperations. The lower four bits
the timer modes, another register called the TCON controls the timer1 fons The details of the TCON
ofTCON cater to interrupt functions, but the upper four bits are for timer opera 1 •
register are shown below.

MSB LSB
I I
TFl TRI TFO TRO
I IEI ITl
I rEO
I rTO
I
BIT SYMBOL FUNCTION
TCON.7 TFI Timer I overflow flag
TCON.6 TRJ Timer I run control bit
TCON.5 TFO Timer Ooverflow flag
TCON.4 TRO Timer Orun control bit

Some assemblers don't allow the use of TFO, TRO, etc;. in programs, but instead need the use of these as bits of
TCON. For example, TFl is TCON.7 and TRl is TCON.6.

Mode 1 programming
lhe following are the characteristics and operations of mode 1:

I. It is a 16-bit timer; therefore, it allows values of 0000 to FFFFH to be loaded into the timer's registers TL and TH.
2. After TH and TL are loaded with a 16-bit initial va lue, the timer must be started. Titis is done by "SETB TRO" for
Timer Oand "SETB TRl" for Timer 1.
3. After the timer is started, it starts to rount up. It counts up until it reaches its limit of FFFFH. When it rolls over
from FFFFH to 0000, it sets high a flag bit c.'llled TF (timer flag). This timer flag can be monitored. When this timer
flag is raised, one option would be to stop the timer with the instructions "CLR TRO" or "CLR TRl", for Timer o
and Timer 1, respectively. Again, it must be noted that each timer has its own timer Aag: TFO for Timer O, and TFl
for Timer I.
4. Alter the timer reaches its limit and rolls over, in order to repeat the process the registers TH and TL must be
reloaded with the o riginal value, and TF must be reset to O.

XTAL
osc,llator + 12
r-L_,,/1-__,i TH I n. :.---i:TF I
t TF goes high
when FPFF -..o
overnow
flag

Steps to program In mode 1


£,. To geni>rate a time delay, using the timer's mode I the following step ar t k T ·1y ....
-mpJe 9-4. ' s e a en. o can
1 u,ese steps, see

---
!Osi,iM ER PROCRAMMJNC IN ASSEMBLY ANDC
205
I Tin1er t) is 10 be used and which time, """'·
·-..e
rr.11\er Oor
. t'ng
andica J whi·ch timer l "
1 TMOD ,•alue register G f h
(0 or JJthe
Load is selected. •th initial count,,a Jues, ...,on to see ·fit
I is raised. et out o t e l0op
2. Load registers TL and TH "I target" [nstrtJcu
Start the timer. (TF) with the •JNB TFX,
3. Keep monitoring th~ timer nag
4 when TF becomes high. 1·
5. Stop th~ timer. h ~1 round.
,, ly'°

6.
a ear
the TF flag for t e neA .
TH and TL again.
7. Go back lo Step 2 to load

V 9-4 •. ortions high and low) on


Example are wave of S(f,o. du ty cycle (with equa 1p
ogram.
re creating a squ Ar,a)yze the pr
In the following p ~ ~ ~o.generate the time delay. . mode)
lhePJ.5 bil Tuner01su mode l(l6-b1t
MOV TMOD,#01 ;Timer O, he LOW byte
HERE: HOV
MOV
CPL
TLO,#OP2H
THO, #OPFH
Pl.S
7
J
•TLO • F2H, t
'
·THO o FFH '
;toggle Pl.5
. h byte
the Hlg
' ••
..
Vt1,
-:,

., ACALL DELAY
; 1oad TH , TL again
~
SJMP H5R£
··-···········delay using Timer 0
DELAY,

AGAIN:
SETS TRO
,star
t Timer O
until
.,.
. •·
~" ,\
JNS TFO,AGAIN ;monitor Timer O flag ,.Y (¥SY'
;it rolls over CT
CLR
CLR
TRO
TFO
; stop Timer O -
;clear Timer O flag f}.....P
,t. \,-. 0

RET

Solution: r '~ \I)..


i r
In the above program notice the following steps. ' '),
,
fj;/
1.
2.
TMOD is loaded.
FfF2H is loaded into THO · TL.Oj . f th
,f(v'(/
y
ls
'
3. Pl.5 is toggled for the high and o~ por~on~~ e pu e.
4. The DELAy subroutine using the timer 1s ~ b .h
65. In the DELAy subroutine, Timer Ois s;arteh r\
e "SETS TRO" instruction.
. Timer o counts up with the passing o ••c c oc , which is provided by the crystal oscillator As e
th timer
til
counts up, it goes through lhestatesof FFF3, FFF4, FFFS, FFF6, fFF7, FFF8, fFF9, FFFA, FFFB, and so on un
hon
it FFFFH. One more clock roUs it lo 0, raising the timer nag (TFO ,. 1}. A that point, the JNB mstruC·
falls through.
reaches
7 I
_ TimerO is stopped by the instruction "CLR TRo". The DELA y subroutine ends, and the process is repeated
Notice that lo repeal the process, we must reload the TL and Tl-[ reg,'sters and th . .
Start e timer again.

FFF3 FFF4

0000

TF = 1
206

lliEao~ -;
CONT RO LLER AND EMBEDDED SYSTEM
V
Example 9·5
In Exomple 9-4, calculate the amount of time delay in the DELAY subroutine generated by the timer. Assume that
,XTAL= 11.0592 MHz. 1r.,,u
I 1,,.,.,"
Solution: ' -=::;,+
· ~"~ 9 MH I 12 =
The timer works w,th a clock frequency of 1/1 2 of the XTAL frequency; therefore, we have 11.05 2 z
=
921.6 kHz as the timer frequency. As a result, each clock has a period of T = 1 I 921.6 kHz 1.085 µs. In other
\\O«is. Timer Ocounts up each 1.085 µs resulting in delay= nun1ber of counts x 1.085 µs .
The number of counts for the rollover is FFFFH _ FFF2H = OOH (13 decimal). However, we add one to 13 because
of the extra clock needed when it rolls over from FFFP to O and raises the TF flag. This gives 14 x 1.085 µs =
15.19 µs for half the pulse. For the entire period T = 2" 15.19 µs = 30.38 µs gives us the time delay generated by
~~~ , '
,t '(, - - - :.,., I J

To calculate the exact time delay and the square wave frequency generated on pin Pl.5, we need to know the XTAL
frequency. See Example 9-5.
From Example 9-6 we can develop a formula for delay calculations using mode J (16-bit) of the timer for a crystal fre-
quenry of XTAL= 11.0592 MHz. This is given in Figure 94. The scientificcalculator in the Accessories di rectory of Microsoh
Windows can help you to find the TH, TL values. This calculator supports decimal, hex, and bina.ry calculations.

/ '
Ex•mple 9-6

In Example 9-5, calculate the frequency of the square wave generated on pin Pl.5.

Solution:
ln the time delay calculation of Example 9-5, we did not include the overhead due to instructions in the I T
get a '.°ore accurate timing, we ~eed to add clock cycles due to the instructions in the loop. To do that, we
machine cycles from Table A-1 m Appendix A, as shown below.
c:i·th~
i
.,..,....
I
I
l!ERE: MOV TLO, #OF2H 1 ,,.... Cycle•
2
'l.

/""'\ -
MOV
CPL Pl.S
THO, #OFFH 2
1
~
ACALL DELAY 2 fpf + "'7

SJMP HERE '1


2
•-· - · --·---delay using Timer o
DELAY:
SETB TRO
I •
l
AGAIN: JNB TFO, AGAIN 14 '~'
CLR TRO l >
CLR TFO l
RET
- 2
Total

T" 2 • 28 x 1085 µs = 60.16 )IS and F = 16458.2 Hz.


28
-
NOTE THAT 8051 TIMERS USE 1112
MACHINE CYCLE TIME. OF XTAL FREQUENCY, REGARDLESS OF

-------~~~~~~~~~~· .. •
IOsi lll\1ER PROGRAMMING IN ASSEMBLY AND c
207
I
(a) in bex

chat values YYXJC are 1 XTAL = 1).0592 MHz


figu_re ..i. Ti,ntr Delay C.Jltulalion for
9
LoOk at Example 9-9 to see how tlie
. not reIoo,1THand TL since .,t was ~ single pulse
In Ex,1mple;, 9-7 and 9-8, we did
reloading works in mode I.

Example 9-7 . both ollhe method ' 0 I figure 9~. Do not include
. h
El.nd 1h,· ddav genera led by TimerO ,n t c folio" mg rode, u,mg
them crht."'Jd due to instructions.

CLR P2.3 ;clear P2. J d )


MOV TMOD, #01 ;Timer o. mode l( 16 ·bit mo e
H~RE: MOV TLO,#JEH ;TLO • JE:H, LOW byt:e
MOV TH0,ij0B8H ; THO • B8H, High byte
S£TB P2. 3 •SET ru.gh P2.3
TRO ' J
SETS •·start Timer 0
AGAIN: JNB TF'O,AGAlN ,monitor Timer o nag
CLR TRO ;stop Timer O
CLR TPO ;clear Timer 0 flag tor
;next round
CW! P2.3

Sol ution:

(d) (FFFF - B83E + I) = 47C2H - 18370 in deomal and 18370 x 1.085 µs = 19.931 -1.5 m,.
=
(b) Since TH - TL= B8JCH e 47166 (in decimal) we have 65536-47166 18370. Tiu, n1e,1ns tha t the timer cc>unts
lrom B83EH lo FFffH This plu. rolling o, er to Ogoes lhrou~ a total of 111370 dock C'Vd e,, where l'ach clock
is 1.085 JI$ u, duration. Therefore we hd,·e 18370 • 1.08, µs = 19.93145 m,.a, 1he width of lhl.' pulse.

./
Example 9-8

E,-,..,, lh(lugh lhe XTA L frequency or 11.0592 is a very convenient f u . , .


II " ,·cry important lo I.now lh,• cry<lal fr,.'<juency of the ch, b, rcq ency• otl,~ r frequ~nCll'S ~r" ,llS<1 used So.
1> for cn-abng • delay ~sing an AT89C51 \\'11h XTAL fn,quct
M.1,w aswmbl,•r,. don I allow the use of TFO TRO "I. but q.
.~~t"sed, When c.1kulating delay, . Thi• e,amplr
MH.l, us ing hmo:r I in mod,: I Use pm r1.3.
·
example, TFI is TCON.7 and TRI 1.s TCON.6.·So let· 'us'·Writ
· 111Stead
th, n<!e(I Ihe LI$(! o f th,·,e ,b. bits ot ·TCON. f«
Solution, e s program us,ng TFl and TR t 1n thi~ wav .

Tested for an AT89C51 ~1th a c rys t al fr


equency o f 22MJ.t
For a cr)'blal trequenc} of 22 l>fHz, the value uf th z·
r = n546 µs , ). ,,.. H ~ e •nstruclion cycle "' ....
~ I ,p
'
208
- I ,Z. JJ f() ~
,~ ..,
I/ Ji of 22 ~11iz "' 18..13 MHz and

THE S0s1 il11CRoc I ~ µ,_.... -


ONiROLLER ANO EMBEDDED svsTDfS
CLR Pl . 3 ; c lear Pl . 3 _.,,, >,, ~
MOV TMOD, #lOH ; Time r 1 , mode 1 0

l. MOV
MOV
THO,#OFFH
TLO,li OOH
;load high byte va l ue
;load low byte
SETS Pl. 3 ;set bit Pl.3
SETB TCON. 6 /f"Rj ;TRl is set to start Timer 1
AGAI N: JNB TCON .7 ,AGAIN ;monitor Timer 1 Oag
CLR TCON. 6 ;st op Timer 1 by making TRl • O
CLR TCON . 7 ; c lear Ti mer 1 flag for next round
CLR Pl . 3 ;clear the port for next round

The dela)' is calculated as FFFFH - FFOOH = FFH = 255 + 1 = 256. X I


Delay= 256 x ~ = 139.;t µs. o.,..,., c~•'-
- 1Slb "\

o-, ~ ~
The maximum d elay possible is when both TH and TL stores values of 00. ~~
=
Then FFFFH - 0000 = FFFFH 65,535 + I = 65.2§.
Delay= 65,536 x 0.546 = 35,782 !'5 = 35.75 ms. f..... 1C- 7 (",..... 'I.. "). ~ 7 / · ( m .r

Examplc9·9
Thb example is for creating a de lay us ing an A T89C51 with XTAL frequency of 22MHz. Use Timer 1 in Mode 0.
Mode Ohas been retained as a 13-bit counte r in the 8051 architecture only fo r compatibility with the earlier 8048
microcontro ller. Mode O mode ls the timers as 13-bit timers with TH s toring the upper byte and the lower five bits
of TL storing the lower byte. A square wave is to be o utputted on P0.6.

Solution:
;Test ed for an AT89CS1 with a crys t al frequency o f 22MHz .

ORG 0000
MOV TMOD, #OOH ;timer l,mode O
AGAIN: MOV TL l , #OllH ;TLleOOH, low byte
MOV THl, lt<)PH ;THl•OFH,high byte
SETB TRl ;start cimer 1
BACK: JNB TFl , BACK ;remain until the timer rolls over
CLR TRl ;stop t i mer 1
CPL P0 .6 ;complement t he bit
CLR TFl ;clear the timer flag
SJMP AGAIN ;reload the counter

For a cryst.11 fr~quency of 22 MHz, the value of the instruction cyde


,l: 0.546 µ, _I ,, ( • , ,
=I /12 of 22 MHz -_ 1 o-,-, MHz and
.cu..,

With a 13-bjt yl!leio,.th~ um value of tinter 1 reg~r will be I FFFH The wa to · ualize . .
Tli register fulJ1 mtd the I ~ 5 bits of the TL register, i.e., TH can ha · _Y Vis this 18 to use the
~,th TL t.1king 5 bit,,, i.e., 1 1_1 I I. These two values concatena~, wil~e i~~ur;u~ value of 111111 1 1 1
OW, wht n THI ,s loaded with OFH and TLl with OOH the effecti l3-gb. \!..I~ 1 1 l J 111, I.e., l FFFH.
~ , ie.,O IOOH - - · ve itnum rwillbeOOOOllllOOOO
.. Thc deL1y
- i,- calcul.ited as t, f::- -
O I
IFFFH - Ot DOH = I E2FH "' m7 + I = 7728
Thrrefurc d~ay = 7728 x 0.546 µs • 4.219 ms. Hence the period T f the .
-=======--------------~=-=~~o:.::
:----~~-
:.:square~:: .w: ave::_m~4~~~x~2~·~8.4~ms.: ____J,,
8osi l'lMER PROGRAMMING JN ASSEMBLY AND c
I
Finding values to be loaded into the timer eed the question is holw tko ;;11:X!1;P~:1~-~0n:~~ for tht
, delay we n • ..-u gisters oo e we llSe

TH, TL ttgisters. To calculate the values to~:


Assun1ing that we know the amount of t11t1erded into the TL and • n re
Joa tem
II
crystal frequency of 11.0592 MHz for the 80 sysl _j 0 we ,an use the fo ow
9
ing steps for finding the TH, TL registe ,
rs
AssumingXTAL = 11.0592 MHz from Examp e
values.
I. Divide the desired time delay by 1.085 µs. . 1
2. Perform 65536- 11, where II is the decimal value we got 111 Step · e to be loaded into the timer's registers.
1

SetTL=rxandTH=yy. o••
3. Convert the result of Step 2 to hex, where yyrx is the initial hex va u
4. --1-
1-14"\;,l,W

Ex.;(ple 9-10
Assume that XTAL= 11.0592 MHz. What value do we need to load into the timer's r~gisters if we want to have1
time delay of s ms (milliseconds)? Show the program for Timer O to create a pulse width of 5 ms on P2.3.

Solution:
Since XTAL = 11.0592 MHz, the counter counts up every 1.085 µs. This means that out of man, 1.085 µs intervals
we must make a 5 ms pulse. To get that, we djvide one by the other. W e need 5 ms / 1.085 µsl= 4608 docks. To
achie\'e that we need to load mto TL and TH the value 65536-4608 = 60928 = , ,. 1, ,eretore, we have TH = EE
L and TL= 00. 7~
71-1 T L
I
CLR P2.3 ;clear P2.3
MOV TMOD,#01 ;Timer O, mode 1 (16-bit mode)
HERE: MOV TL0,#0 ;TLO = 0, Low byte
MOV THO,#OEEH ;THO = EE (hex ), High byte
SETB P2. 3 ;SET P2.3 high
SETB TRO ;start Timer o
AGAIN: JNB TFO,AGAIN :mon~to: Timer a nag
;until it rolls over
CLR P2. 3 :clear P2.3
CLR TRO ;stop Timer o
CLR; TFO ;clear Timer O nag

I o ·J C.
With a frequency of 22 ~ generate a frequency of I( ._
100 l<Hzon · P2
Solution, pm .3. Use Timer 1 in od
J.J. t,.
, ,..,_-.. O '01 4"\ __ \oiLlS
m el.

:Tested for an AT89CS1 i ~ "
For a JOO.KHz square wave
w th a crystal
frequency of
22MHz.
1•---•
f
,JS

(a)T = 1/f ~O.OI ms= JO~


(b) I /2 of it for high and low porti
(c) 5 µs/0.546 µs = 9 cycle;; ons-" = 5 µs
(d) 65,536 - 9 ~ 65,527" FFF7H

'
210
n,e program is as follows.
MOV TMOO,#lOH ;Timer 1, Mode 1
BACK: MOV TLl,#OF7H ; TLleF7H
MOV THl,#OFFH ; THl:FFH
SETB TRl ; sta r t Timer 1
;.GAIN: JNB TFl , AGAIN ; wait for timer rollover
CLR TRl ; stop Timer l
CPL 1?2 . 3 ;complement P2.3
CLR TFl ;cl ear timer flag
SJMP BACK ;reload timer

Example 9-U -~
· an ON time
Generate a square wave with · o f 10
· o f 3 ms and an OFF hme ~ o n all pins of port 0. Assume an XTAL
of22MHz.

'

' --- -
3 ms tO olS

Solution:
;Tested for an AT89C51 wi th a cryst al frequency o f 22MHz .
Let us use Timer Oin Mode 1.

MOV TMOD,#OlH ;Ti mer O in mode 1


BACK: MOV TL0,#075H ;to generate the OFF time, load TLO
MOV THO,#OB8H ;load OFF time value in THO
MOV P~,#OOH ;make port bits low
~ ACALL DELAY' ;call delay routine
i

MOV
MOV
MOV
TL0,#8AH
THO,#OEAH
PO, #OF.E'H
I ;to generate tbe ON time , load TLO
; l oad ON t i me value in THO
;make port bits high
ACALL OBLAlt' ;call delay
S'1MP BACK ;repeat for reloading counters to get a
• ;cont inuous square wave .
ORO JOOH
DELAY · SBTB TRO ;start the counter
AGAIN: JNB TPO,AGAIR ;check time r overflow
CLR TRO ;when TFO is set, stop the timer
CLR TPO ;clear timer flag
RET
END ;end of file
For OFF tinw calculation:

~
IQIIIS/ 0.546 pa = 18,315 cycle
65
.536 - 18,315 " 47,221 • 8875H
-
211
I I Of}

For 0"1 bme calculation:


3 rns/0 5-16 µs = 549~ cycles . d clearing it are done in a s_ubroutinc, Which
t,5,536- 5-194 = 60,0U = EA8AH. . kin for the nag bat, an ded u,to TH and TL are different
In Iha, example, the starting of the bmer, ch~hil!the vafues to be lo.1
c, common for both the ON and OFF tunes,

I
Generating a large time delay · d ds on two factors, (a) the crystal frequ""-·
· f the time delay epen r f th 8051 "'Y,
As we have seen in the examples so far, the size o f • are beyond the con tro o e programmPI
and (b) the 11mer's 16-bit register in mode 1. Both of these a~tor:,both TH and TL zero. What if that is not enough>
. that the largest tune
We saw earlier . de1ay JS· ach'eved
' by makmg ·
Example 9-13 shows how to achieve large time delays.

Using Windows calculator to find TH, TL


The scientific calculator in Mkrosoft Windows is a handy m,d easy-to-use tool to find the TH, TL values.. Assume
that we would like to find the TH, TL values for a time delay that uses 35,000 clocks of l .085 µs. The followmg steps
show the calculation.
1. Bring up the scientific calculator in MS Windows and select decimal.
.~
. 2.
3.
Enter 35,000.
Select hex. This converts 35,000 to hex, which is 88B8H.
4. Select +/- to give-35000 decimal (n48H).
5. The l_owcst two digits _(48) or this hex value arc for TL and the next hvo (77) are for TH. We ignore all the Fs on••·
left since our number is 16-bit data. ""'

1,..
\. Example 9.-13
Assuming XTAL - 22 MHz ·t
• in mode 1. • wn ca program to generate a puls,' train of2 seconds period on pin P2.4. Use Timer I
Jrc.<.
Solution:
;Tested for an AT89CS1 with a crystal f ,, ~
\ I
F reguency of 2 2 MH
or• time period of2 seconds th half . z.
maximum delay possible with' a cc penod should be I second. We h •
iJ. 35.75 ms. If this delay is repea1J;:/rt•quency of 22 MH2., as when n~"~ a~ready seen in Example'll-8 that the
The program is as foUows. ' imes, wee.in get a delay of I OOJ an Tl take values of Oand that dela1
ti~ , ms: l second. ,., ·
s/ • MOV TMOD, #lOH -, ,IP ~
"-~ : MOV RO, #28 , 1'1 :Timer l, mOde 1 o+"' .'"
CPL P2. 4 :counter tor . '1.(,,..-i .Al' •
BACK: [ MOV TLl,#OO!f ;complement P;u!tlple delay ...~ - ._/ ..~ ,
MOV Tlll #00 : load count . v-:;, • .c.:"
SETB TRI, H : load coun value in TLl (> y
AGAIN: JNB TPl,AGAIN :start tim:r value in TH1
CLR TRl ; Stay Until
CLR TPl I stop t.irner timer rolls over .
DJNZ RO,IIACK :clear lei
SJMP REPT -, i.~-• ' mer
; if RO ,s not ~9

-
Calculation= 28 x 35.75 ms= 1001 ms. ; repeat for continuous
zero, reload t i 111er
Pulae gene r a tion

212 ---
/
E.o mple 9-13•
~erate the following wa,•eform on Pl.2. XTAL = ~ MHz

SO ms
"'=""- - - -

so·ms

Solo.lion: '

;Tested for an AT89C51 with a crystal frequency of 22MHz.

This means first creating a delay of 50 ms ON time and SO ms OFF time, followed by five repetitions of 10 ms
ON time and ~ OFF time. To generate a delay of 50 ms, a 10 ms delay is repeated 5 times. The first 13 lines
of the program are for generating the 50 ms ON and OFF times. The rest are for generating five pulses of 10 ms
each.

START: SETB Pl.5 ;set port pin for generat~ng the ON time
MOV Rl, #02 I• to >;. ;one ON time and one OFF time
MOV TMOO, # l OH _,, ;Timer 1, Model
BACK: MOV ~0 . #QS ;repeat the 10 ms delay 5 times
RPT: MOV TL1,#75H
MOV THl,#OB8H
SETB TRl
AGAIN: JNB TFl,AGAIN
CLR TRl
CLR TFl
OJNZ RO,RPT
CPL Pl.S
DJNZ Rl,BACK ;stop after 2 periods of 50 ms are over
SETB Pl.S ;start the sequence of s pulses of T . 20 ms
MOV Rl,#10 ;this part for 10 ON-OFF periods of 10 ms
BACKl: MOV TLl,#75H
MOV THl,#OB8H
SETB TRl
AGAINl: JNB TFl,AGAINl
CLR TRl
CPL Pl.5
CLR TFl
DJNZ Rl, BACKl
SJMP START ;repeat

~
This Program is to illustrate that any type of sequences can be gen ~
......, .... ,.
era..,.. ....., a clever UR of the thneni.

---------~-
IOsI TIM
ER PROCRAMMJNG IN ASSEMBLY ANO C
213
I
. The 13-bit counter can hold va~
. iJ1Stead of 16_-bit. of lFFH, it rolls over to~. alld
Mode O 3-bit timer ·ts maxi.mum
I that it is a 1 . er reaches 1
Mode Ois exactly ~e ;°':e,i~!efore, when the 11111
between 0000 to 1FFFH '"
TF ,s raised.

/
Mode 2 programming . . rations of mode 2· · er's re ·ster TI-!.
I
The following are thecha~actenstics and ope
11 only values o
f()() to FFH to be loaded
f ·t to TL Then
into::
: e r mu! be started. This is
rk d I
L It is an 8-bit timer; therefore, ii a ow; the 8051 gives a copy Ro l'.. for T~er 1. This is just l e mo e h.
After TH is loaded with the 8-bit va" ue, T' rO and "SETB T . It counts up until it reac es its lunit

After the timer is started, it star~c~:


of FFH. When it rolls over 1.ro"'. '
~rse'
2. done by the instruction "SETB TRO for tmeb ·ncrementing tl1e n ref~~t:~ are using Ti.mer 0, TFO goes high;u
3. ~gh the TF (timer flag ·

we are using Timer !, TFl ,s nused.

~ overflow
XTAL
oscillator + 12 / ' _J
1
TL 1' flag

·' I reload TPgoes hlgh


TR when FF-.. o
c/ i' ~ o
I TH I

4. When the TL register rolls from FFH to Oand TF is set to 1, Tl is reloaded automatic'.'1ly with the original value
kept by the TH register. To repeat the process, we mustsimplyclearTP and_let 1t go Wlth?ut any n ~ by ~e pro-
granuner to reload the original value. Thls makes mode 2 an a uto-reload, 111 contrast with 01ode l m whlch the
prognunmer has to reload TH and TL

II must be emphasized that mode 2 is an 8-bit timer. However, it has an auto-reloading capability. 1n auto-reload,
TH is loaded with the initial count and a copy of it is given to TL This reloading leaves TH w1changed, still holding•
copy
as weof thesee
will original value.10.
in Chapter Thls mode has many applications, including setting the baud rate in serial communication.

Steps to program in mode 2

To gene,ate a time delay using the timer's mode 2, take the following steps.
1.
Load the TMOD ,•alue register indicating which timer rnmer o r T· .
0
(mode 2). tmer 1) IS to be used, and select the timer mode
2. Load the TH registers with the initial count value.
3. Start the timer.
4. Keep monitoring the timer flag (TF) with the "JNs T"-·
(th J h TF ,., ' "' • target"· .
S. o e the
Clear oop en
TPwflag. goes ,ugh. UlStruction to S<.>e whether it is raised. Get out
6. Go back to Step 4, since mode 2 is auto-reload.

Example 9-14 illustrates these points. To ach;ev


Example 9-15. ea 1a.rger delay, ,ve can .
use multiple registers as shoWII 111
214
uare wave generated o n pin Pl. tn
uoting tha t XTAL = 11.0592 MHz, find (a) the frequency .of ~e sq and the TH valu e to d o that.
~owing program, and (b) the s mallest frequency achievable m this program,
l

1'.0 V TMOD,#20H ; Tl / mode 2/ 8-bi t/a uto - r eload


MOV THl,#5 ; THl = 5
SETB TRl ;start Time r 1
BACK: JNB TFl,BACK ·stay until t i mer r ol ls ove r
CPL Pl .O : c omp . Pl.Oto get hi , lo
CLR TFl ; clear Timer 1 ilag
SJMP BACK ; mode 2 is auto-reload

Solution:
d t
(a) First notice the targe t address of SJMP. Jn mode 2 we do ~ot nee . 0 r~ oh
I ad TH
uJ s ince
. ceit . isisauto -reload.
=
Now (256 - 05) x 1.085 µs 251 x 1.085 µs = 272.33 µsis the high p ortion° ~ e P ;e.
5 ind t~e
cycle square wave, the period Tis twice that; as a result T = 2 x 272.33 µs - 544.6 µs an
a SOo/o duty
1 fre u e nc =
q Y
1.83597
(bl To kHz.
get the .s ach1ev
smallest fre quency, we need the largest T and that 1 · ed w h en TH -- 00· Jn that case ' we have
T = 2 x 256 x 1.085 µs = 555.52 µs and the frequency= 1.8 kHz.


Example 9-15

Assuming that XTAL = 22 MHz, write a program to generate a square wave of frequency 1 kHz on pin Pl .2.

Solution:

;Tesced for an AT89C5l wi th a crystal frequency of 22MHz.


The smallest frequency possible in this setup is when the delay is maximum. Largest delay is when TH reduces
to 00 from FF, i.e., delay is 256 x 0.546 = 139 µs.
T = 2 x 139 = 278 µs i.e., the smallest frequency is 3.6 kHz. Hence, to get a smaUer frequency, we need to use a
register for creating the additional delay.
To get a d elay of 0.5 ms, we need 0.5 ms/0.546 µs = 915 cycles. This can be achieved in various w ays, one which
is lo use the TH register to get a delay of 915/5 = 183 cycles, and a register RO to get the rest of it.
183 cycles have to be covered by the TH register when it rolls from its count value to FFH.
=
183 = 87H. The TH value should be FFH - 87H = 48H. Thus the effective delay is 183 x 0.546 x 5 = 499 µs 0.5 ms
T=0.5 ~ 2 = t ms and frequency = 1 kHz.

MOV TMOD,#02H ;Timer O, mode 2


REPT : CPL Pl. 2 ;complement Pl.2
MOV RO, #05 ;count for multiple delay
AGAIN: MOV TH0,#48H ;load THO value
SETS TRO ;start Timer o
BACK:
JN8 TFO,BACK ;stay until timer rolls over
CLR TRO ; stop timer
CLR TFO ;clear timer nag
DJNZ RO,AGAIN ;repeat until RO•O
SJMp RBPT ;repeat to get a train of pulse•
ENO

215

,.
I
( £umplt 9-16
. the t:uners for m
ode 2, fiod the value
(' heX) Joaded iJ'lto TH for each Of !lit~
lJ1

As.surrung that we are programrrung


60
following cases. (b) MQV T HO, #-
12
(a) MOV Tlll, #-200 (d) MOV Tl!l, #-
(c) MOV 'THl, # - 3
I (c) MOV THO, ij- 48

• · ·ded by the assembler. In Windows calc,i.


SoIution.
You can use the Windows scientific calculator~ ve!~:1:j~e:oget the TH R~:~::::
ults prov,
va!ue ..
lator,select decimal and enter 200. Then select ex'._ an B-bil data. The follo,vlllg IS
th
ge:.t we o nly use the
15
right two digits and ignore the rest since our data

Dtcimal 2's complement (fH value)


-200 38H
-oO C4H
-3 FOH
-12 F4H
-48 DOH

C

Assemblers and negative values
V
Since the timer is 8-bit in mode 2, we con let the assembler calculate the value for TH. For example, in "MOV T!U,
r #-100", the assembler will calculate tl,e-lCJO = 9C, and makes THI = 9C in hex. This makes our job easier.
0


g
~
Ex~mplt 9·17 i
T
Find (a) the frequency of the square wave generated in the following code, and (b) the duty cycle of this wav•.
r.
MOV TMOD,#21! ; Timer o, mode 2
;(8 -bit, auto - reload)
MOV TH0,#-150
;THO~ 6AH ~ 2's comp o f - 150 C
AGAIN: SETS Pl . 3 ; Pl. 3 • l
ACALL DELAY
ACAI.L DELAY
CLR Pl.3
; Pl. 3 =-: o
ACAI.L DELAY
SJMP AGAIN
DELAY:
SETB TRO
BACK: JNB TFO,SACK
; start Timer 0
CLR TRO
,stay Until ti
·stop
· T'11ner mer rolls over
CLR TFO O
RET :clear TF f
or next round
Solution:
For the Tif value in mode 2 the conv-. .
tsok the ' ..,,on ,s done by
a ma es calculation easy. Since we a . the as&ernbt
1.085 µs = 162 µs. The high portion of the re usmg 150 clacks er as long as
have; T = high portion + low portion z 325~uJse IS twice that.;,We have liine ; ~ a negative m 1111Nf.1llt
• 1JS + 162.25 115 the low P<>ttian DELAy subroutine. 191•
z 488.25 JIS oll\d ~~ dnty cyde). n...ilall,•

ll6 - ~~ ;
TliEsos~
ocoNTa -- ,
OLLER ANO EMBEDDED sY5'f96 111
ocks used by the overhead instructions
1'J nee that in many of the time delay calculations we have ignored the cl . ;: d them If you use a digital scope
ci:e~OOP·To get a more accurate time delay, and hence frequency, you need to~15 bu e use of the overhead associated
~ )·ou don't get ~xactly the same frequency as the one we have calculated, it eca
'lh !hose instructions. owerful and creative use of
"" In thiS section, we used the 8051 timer for time delay generation. However, a more P
these timers is to use them as event counters. We discuss this use of the counter next. •

Review Questions
1. Ho1~ many timers do we have in the 8051? 'i'o,. T l
2. Each timer has registers that are ~ bits ,vide.
3. TMOD register is a(n) & -bit register.
t, True or false. The TMOD register is a bit-addressable register.
s. indicate the selection made in the instruction "MOV TMOD, #20H".
6. 1n mode 1, the counter rolls over when it goes from to - - - -
7. 1n mode 2, the counter rolls over when it goes from to .
8. In the instruction "MOV THl, #-200", find the hex value for the TH register.
9, To get a 2-msdelay, what number should be loaded into TH, TL using mod~ 1? Ass~e that XT:-L = 11.0592 ~
10. To get a 100-µs delay, what number should be loaded into the TH register usmg mode 2. Assume XTA -
I 1.0592 MHz.

SECTION 9.2: COUNTER PROGRAMMING


In the last section we used the timer/counter of the 8051 to generate time delays. These timers can also be used as
counters counting events happening outside the 8051. The use of the timer/counter as an event counter is covered in
!his section. As for as the use of a timer as an event counter is concerned, everything that we have talked about in pro-
gramming the timer in the last section a lso applies to programming it as a counter, except the source of the frequency.
When the timer/counter is used as a timer, the 8051's crystal is used as the source of the frequency. When it is used as
a counter, however, it is a pulse outside the 8051 that increments the TH, TL registers. ln counter mode, notice that the
TMOO and TH, TL registers are the same as for the timer discussed in the last section; they even have the same names.
The timer's modes are the same as well.

err bit in TMOD register


RecaU from the last section that the C/T bit in the TMOD register decides the source of the clock for the timer. II
Ctr= 0, the tim~r gets pulses from the crystal. In contrast, when CIT= 1, the timer is used as a counter and gets its
pulses ~m outside the 8()51. Th~refore, when C~T = 1, _the counter counts up as pulses are fed from pins 14 and 15.
~ pms are called TO (T,?'er Omput~ and Tl (Timer 1 mput). Notice that these two pins belong to port 3. In the case
unerO, when C/T = 1, pm P3.4 provides the cloclc pulse and the counter counts up for each clock pulse coming fr
that pm. Similarly, for Timer l, when C/T = 1 each clock pulse coming in from pin P3.5 makes the counter count u:.rn

Table 9-1: Port 3 Pins Used For Timers Oand 1


Pin Port Pin Function Description
14 P3.4 TO Tuner /Counter Oexternal input
15 P3.5 Tl
11mer/Counter 1 external input

(MSB)
(lSB)
GATE I CIT I Ml I MO GATE I C/T I
Timer 1
Ml I MO
TlmerO

217
I .

,,,,. to be counted are fed to pin P3.4. X'l'Al•


Ex•mple 9-18 tses of an mpu t signal. n,epu=-
· g 1he pu
Design a. counter for counttn
22~tHz.

Of 22MHz,
I .
Solution: 9 1
rysta frequency .
d Timer f .. ,, __With
is run as a counter,
I ATa cs1 "itb a c . this l seem, ' 0
·ve the number o p..,..,. that
;Tested for an . . 1second. [)uJ'lng ·n TLO and THO gtkn ,vn signal, i.e., the num~
In thls, Timer I 1s ~ •~3time
4
base
At thefor
endrunang
of 1 se_;::n d~ves
the values •
the frequency of the un o
input pulses fed into pm d · : this I second. IS
were received at pin P3.4 u~ng
~ I
,., of pulses received m I secon .

,/" OOOOH
ORG imer and Timer o as counter
/. . RPT: MOV TMOD,#lSH ;timer last 4 an input port
SETB P3.4 •make port P3.
MOV TL0,#00 '.clear TLO
'·clear THO
MOV TH0,#00
SETB TRO : tart counter d
MOV R0,1!28
,s .
·R0-=28,co time l secon
'
AGAIN: MOV TLl,#OOH ••TLl•O
MOV THl,#OOH ·THl=O
SETB TRl '.start Timer 1
BACK, JNB TFl,BACK ;test Timer 1 flag
CLR TFl ;clear Timer 1 flag
CLR TRI ·stop Timer l
OJNZ RO,AGAIN
; repeat the loop until ROaO TLO
1'.0V A,TLO ;since l sec has elapsed, check
MOV P2,A
MOV A,THO
•·move TLO to port 2
;move THO to ACC
MOV Pl,A ;move it to port l
SJMP RPT
;repeat
END

As the frequency varies, the values obtained at ports l and 2 vary.


The values obtained for 10 Hz, 25 Hz, 100 Hz, ... are respectively, OAH, 19H, 64H ..•

~, ....._, "'"'""' =··-•'"""· . .


In Example 9-18, we use Timer 1 as an event counter where it counts up as clock pulses a re fed into pin 3.5. These
clock pulses could represent the number of people passing through an entrance, or the nun,ber of wheel rotations, or
be displayed on 9-18,
In Example an LCD.
the TI.. data was displayed m binary. In Example 9-19, the 11. registers are converted to ASCII
.
T1merO ove:rflo"',
.:::;-----------i
exlemal
input
pm 3.~
c;r. I
--i '

TRO
Tl-iO TLO

TFO goes high


when FFFF- o
nag
TFO Timer
external
in
pin
-J
-rDi
r,
l-J L

3.Sp u 1 T H 1 TL1}r- •j TFJ I


overnow
Oag

j
Figuro 9-S. (a) Timer O with ExttmoJ Input (MOdt 1) C/f ~ 1 ~1 TF1 goes high
When l'FFF -.. 0
(b) Ti.n,tr J W'tb
1
218
E"~rn•I Input fMOd,. 1)
Tttt sos1 M1caoc
ON'rROLLER AND EMBEDDED SYSJVIS
£:Ull'Plt 9.19
. t d'splay
1 counter O on an
Al ume that a 1-Hz frequency pulse is connected to input pin 3.4. Wnte a program o
l~· Set the initial v~lue of THO to -6().

5olution:
. bmary
To display the TL count on an LCD, we must convert 8-bit . d ata t o ASCH · See Chapter 6 for data
conversion.

ACALL
MOV
LCD SET OP
- -
TMOD,#000001100
;initialize the LCD
;counter O,mode 2,C/T=l
MOV TH0,#-60 ;counting 60 pulses
SETB Pl. 4 ;make TO as input
AGAJJI: SETB TRO ;starts the counter
SACK: MOV A,TLO ;get copy of count TLO
ACALL CON\/' ;convert in R2, R3, R4
ACALL DISPLAY ;display on LCD
JNB TFO,BACK ; loop if TFO=O
CLR TRO ;stop the counter O
CLR TFO ;make TFOaO
SJMP AGAIN ;keep doing it

;converting 8-bit binary to ASCII


;upon return, R4, R3, R2 have ASCII data (R2 has LSD)

COllV: MOV B,#10 ;divide by 10


DIV AB
MOV R2,B ;save low digit
MOV B,#10 ;divide by 10 once more
DIV AB
ORL A,#30H ;make it ASCII
MOV R4 ,A ;save MSD
MOV A,B
ORL A, #3011 ;make 2nd digit an ASCII
MOV R3,A ;save it
MOV A,R2
ORL A,#3011 ;make 3rd digit an ASCII
MOV R2,A ;save the ASCII
RET

8051

Pl
to
LCD
1 Hz clock TO

By llSing 60 Hz we can generate secorufs, minutes, hows.

~that on the first round, it mJ1B from 0, since on RESET, TU) = o.


ve tlus problem, lold n.o with -(,() at the begiMing of the program.

:---_
;-;;~~~;;;~~:;~;:~~;;------------------==
los111'-' ER PROGRAMMING IN ASSEMBLY AND C
219
I _rL.Jl
overflow nag Tl.ffler I
.f1._.lL e,cterl'lal
TuncrO no i-.--i TFO input
extcmal pin 3.5 TRl ~...__reload
input THI
pin 34
TRO
_.._, reload
THO TP I goes high
c/f= I when ff..-O
I CIT= 1 TFO goes high T. er 1 with External Input (Mode 2)
whenfF-.o Figure9-7. lffl

Eigm,9~, TimerOwllh External Input (Mode 2) 'eed an external square wave of 61)Lz.
f th timer with CIT -_ '.we can ''d the hour out o f this ·input freq Ul'nn. '"
1
. .
As another example of the applicaho_n o e te the second, the [JUJlute, an urate one. ..,,
frequency into the timer. The program will gener~ ,, . clock but not a very ace
131
and display the result on an LCD· This wiJJ be a ruce h
wgiimportant 'points.
10
Before we futlsh this chapter, we need state vo · t the raising of the TFx Oa ·
. .. TFX carget" to morn or . g IS;
1 You might think that the use of the instruction JNB . ' tt·on to this: the use of interrupts. By usmg irita.
· waste of the microcontroller's time.
. y ou are n·ght· There,saso 1u · d · ill . f
. IT Uer When the TF flag is raise it w in orm US. llii!
d
ruptswecangoabout omgo er · th thin with
gs . . the rrucrocon o ter
in Cha · 11.
important and powerful feature of the 8051 ,s dIScussed P . alled TCON which is discus5ed
2. You might wonder to what register TRO and TRI belong. They belong to a register c '
next.

TCON REGISTER
'r In the examples so fur we have seen the use of the TRO and TRI Oags to turn on or off the timers. These bits are part
of a register called TCON (timer control). This register is an 8-bit register. As shov,n in Table 9-2, the upper four bits are
used to store the TF and TR bits of both Timer Oand Timer 1. The lower four bits are set aside for controlling the inter•
rupt bits, which will be discussed in Chapter 11. We must notice that the TCON register is a bit-addressable register
Instead of using instructions such as "SETB TRl" and "CLR TRl ", we could use "SETB TCON. 6" and "CLR TCON. 6",
respectively. Table 9-2 shows replaoements of some of the instructions we have seen so far.

Table 9-2: Equivalent Instructions for the


Timer Control Register (TCON)
For1imerO
SETB TRO
= SETO TCON.4
CLR TRO
CLR TCON.4

SETB TFO
CLR
- SETO TCON.S
TFo
ForT1mer l CLR TCON.5
SETB TRI
= SETB TCON.6
CLR TRJ = Cl.R TCON.6
SETB TFt
CI.R = SETJl TCON.7
TFt
= CLR TCON.7
TCON, Tirner/Counter C
TFI TRI ontroJ Regisi
TFO TR er
O lEJ
rn fEO
ITo
Tlit 80s1 l\fJ
C1toco N-r1to t L
Ea ANO EMBEDDED svs1VA5 '
-
Th' case of GATE = 1 in TMOD
aetore we finish this section we need to discuss another case of the GATE bit in the TMOD register. All discus·
._ (ar has assumed that GATE :: O. When GATE == o the timer is started with instructions "SETB TRO" and
si~- TlU ", for r·~ers 0 an d 1, respectively. What happens
•sSTB
50 ' if the GATE bit in TMOD is set to 1? As can be seen .in
Figures 9-8 and 9·9, if GATE "' 1, the start and stop of the timer are done externally through pins P3.2 and P3.3 for
fUl1ersOand 1, respec~vely. Th.is is in spite of the fact that TRx is turned on by the "SETB TRx" instruction. This allows
u, to start o~ stop the timer externally at any time via a simple switch. This hardware way of controlling the stop and
sw-1 of the tuner can have many applications. For example, assume that an 8051 system is used in a product to sound

XTAL
OSCILLATOR +U
C/T=O

-~ - .
~
!
(
.


CIT= I
TOIN
Pin 3.2

TRO

- '
.....J I

Ga te -l
)-
IN1"0 p in
Pin 3.2

Figure 9--8. Timer/CounterO

XTAL
+12
OSCILLATOR
C/T=O

-------c_>--1--ruY--f
CIT= 1
Tl IN
Pin 3.5 - - - - l

TRl -----f--.._
.-J ,'

Gate ' /'---'


iNTIPin _ _ _ _ ___,
-
I

Pin3.3

Figure 9--9. Tlmn/Counter t

221
I ,~gs Timer O is turned on by th..
other thu• ' od 'SOit.,
. ddition to manY f the user of that pr uct. However .,,
. Ti o
an alarm every second using ,mer , r- .
,.,..,haps 1n a
d is beyond the co 11 troI o 1
h uing down the a arm.
, a S'Yj
1<1i
method of using the "SETB TRO" instruction a:;
ff the timer, thereby u
5

connected to pin P3.2 can be used to tum on an °

Review Questions
I. Who provides the clock pulses to 8051 timers !f c1!T: ~J
2. ~Vho provides the clock pulses to 8051 tiJ:ne~s 1f C. T - = 1? T
3. Does the discussion in Section 9.1 apply to bmers '.f C1 Tl and why?
4. What must be done to allow P3.4 to be used as :111 mrut for ~N 6•
5. What is the equivalent of the following mstruct1on? SBTB T ·

SECTION 9.3: PROGRAMMING TIMERS OAND 1 IN 8051 C


In Chapter 7 we showed some examples of C programming for the 8051. In this ~ection we study C progra~
for the 8051 timers. As we saw in the examples in Chapter 7, the general-purpose registers of the 8051, such as RO. R7
A, and. B, are under the control of the c compiler and are not accessed directly by C statements. 1n the case of sf'Rs'.
~e entire RAM space of SO. FFH is accessible directly using 8051 C statements. As an example of accessing the SFRs
duecUy, we saw how to access ports PO - P3 in Chapter 7. Next, we discuss how to access the 8051 timers directly usrn,
C statements. -..
....
i Accessing timer registers In c
r In 8051 C we can access the timer registers TH TL a d TMOD dir .
in &ample 9-20. Example 9-20 also shows how to ~cc~:the TR and .;ii~~smg the reg51.h header file. This is shown

/
(

[
Example 9-20
C
w·nt.e a 8051 C program to toggle aJJ the b' I
16-b,t mode to generate the delay. ,ts of port PI continuously with so . I
me d elay m between. Use Timer O. I
Solution: I
#include <regSl.h, I
void TODelay(void). I
void main(void) '
(
while(l) I
I I /repeat fo rever
Pl•OxSS;
TODelay() 1 //toggle all
//delay size bi t e of Pl
Pl•OXAA·•
TOOelay(I I // t oggle a11 "'?known
b1te Of Pl
I
J
l
1/0ld
ro0e1ayO
\
fflOO•OxOl; //Timer O, Mode 1
'!'LO•OXOO; //load TLO
TRO•Ox35; //load THO
1'1!0•1; //t:urn on TO
>1hile (Tr'Os•O) : //wait: for TFO t:o roll over
TRO=O; //t:urn off TO
TFO•O; //clear TFO
l
FFffH - 3500H =CAFFH = 51967 + 1 =51968
51968 x 1.085 µs = 56.384 ms is the approximate delay.

8051

P0 1 - - - - - LEDs

Calculating delay length us ing timers


As we mentioned in Chapter 7, the d elay length depends on three factors: (a) the crystal frequency, (b) the number
of clocks per machine cycle, and (c) the C compiler. The original 8051 used 1/12 of the crys tal oscillator frequency as
ln!machine cycle. In other words, each machine cycle is equal to 12 clocks periods of the crystal frequency connected
IO l!lt Xl - X2 pins. The time it takes for the 8051 to execute an ins truction is one or more n,achine cycles, as shown in
Appendix A. To speed up the 8051, many recent versions of the 8051 have reduced the number of clocks per machine
cydt from 12 to four, or even one. For example, the AT89C51 /52 uses 12, whi le the D55000 uses 4 clocks, and the
ll589C4xO uses only one dock per machine cycle. As we mentioned earlier in this chapter, the 8051 timers also use the
Cl}ital frequency as the clock source. The frequency for the timer is always 1 / 12th the frequency of the crystal a ttached
IDlhe 8051, regardless of the 8051 version. In other words, for the AT89C51/52, DS5000, or DS89C4x0 the duration o f
lbttime to execute an instruction varies, but they all use 1 / 12th of the crystal's oscillator frequency for the dock source
Iii lhe timers. This is done in order to maintain compatibility With the original 8051 since many designers use timers
liltttate time delay. This is an important point and needs to be emphasized. The C compiler is a factor in the d elay
lilt since various 8051 C compilers generate different hex code si.zes. This explains why the timer delay duration is
~ for Example 9-20 since none of the other factors mentioned is specified.

Delay duration for the AT89C51 /52 and DS89C4x0 c hips


At we stated before, there is a major difference between the AT89CSJ and DS89C4x0 chips in term of the time it
bl~ to he(Utt, a ~ingle Instruction. Althoug~ the DS89C4x0 ext>cutes instructions 12 times faster than the AT89CSJ
~-thty both •hll u1,e O.C/ 12 dock for their timers. The faster execution tim~ for the instructions wilJ have an impa t
~°"' d~l.ay il'ngth ro verify thl!> very important point, compare parts (a) and (b) of Example 9-21 since they ha c
~ on thc-,,e two chip• with the same ~peed and C compi ler. ve

lltt.er, o and 1 delay using mode 1 (16-blt non auto-reload)


~'.,"PW'• 9-21 and 'J-22 •how 8051 C programming of the timers O and 1 in mode 1 (16-bit non-auto ~I d)
,_, tJi..m to g..i famthar w ith the •yntax.
.......__ o.i ·

~11~,;;:;--;;;;::::::
l'1£R PROCRAMMINC ::::;.::::-;::;::-;;:;:;::;;;-::;-::::::::-~~~~~~~~~~~~~~~~~~~
IN ASSEM BLY ANO C
I
· mode 2 (8•b it auto-reload) oand 1111
. mode 2 (8-bit auto-reload). Study th.
~'<!t
Timers o and 1 delay usrng ouninS of tiJners
Examples 9-23 through 9-25 shows 8051 C progT<'
examples to get familiar with the syntax.

tilluously every 50
Write an 8051 C program to toggle only bi~i :~ (b) on the D589C420.
the delay. Test the program (a) on the AT8

,I Solution:
#include <regSl.h>
void TOMlDelay(void);
sbit mybit=Pl"S;
void main(void)
{
while(!)
{
mybit•-mybit; //toggle Pl.5
TOMlDelay(); //Timer o, mode 1(16-bit)
)
}

(a) Tested for AT89C5J, XTAL~l 1.0592 MHz, using the Proview32 compiler

voi d TOMlDelay(void)
I
TMOD=OxOl; //Timer o. mode 1(16-bit)
TLO=OxFD; //load TLO
THO=Ox4B; //load Tl!O
TRO•l; //turn on TO
while (TFO•wO);
TROc.0;
//wait for TPO to r oll over
I /turn off TO
TFO•O; //clear TPO
}

(b)TestedforDS89C420,XTAL=11.0S92 •"-'- . th .
'"'=, using e Provtew32 compiler
void TOMlDelay{void)
I
TMOD•OxOl;
TLO•OxFD; //Timer o, IDOde l(l& b.
//load TLO - it)
TIIO•OX48;
TRO=l; //load Tllo
while (TFO••O) ; //turn Oil TO :
TROcO; //wai t for TFo t
TFO•O; //turn off To O ro11 over .
//clea r TPo
) ..
FFFFH - 4BFDH =8402H a 46082 + J ., ~
..
~

Timer delay = 46083 x 1.085 µa ,. SO 111a

•'-I!~,
224

TliE 8oSJ l\ftc1t


.

.
..-'
OcoNTR.ott '
ER. AND EMBEDDED 5yST&IS -
Man 8051 C program to toggle all bits of P2 continuously every 500 ms. Use Timer 1' mode 1 to create
E,r,ll'
wn.-
JtlaY·

5o1ution:
//iestecl for D589C420, XTAL = 11.0592 MH2, using the Proview32 compiler
rinclude <reg51. h>
void TlMlDelay (void) ;
void main (void)
{
unsigned char x;
P2=0x55;
while(l)
{
P2=-P2; //toggle all bits of P2
for(x=O;X<20;x++)
TlMlDelay {) ;
}
)
void TlMlDelay (void)
( •
TMOD=OxlO; //Timer 1, mode 1(16-bitJ
TLl • OxFE; //load TLl
TlllsOxAS; //load THl
TRl=l; //turn on Tl
while (TFl=•Ol ; //wait for TFl to roll over
TRl•O; //turn off Tl
TFl• O; //clear TFl
}

A5FEH " 42494 in decimal


&m6- 42494 = 23042
lJOU • 1.085 µs" 25 ms and 20 x 25 ms = 500 ms

N0TETHATS051TIMERSUSE11120FXTALFREQUENCY, REGARDLESSOFMACHINE
cYCLETIME.

~ple9-23

IVnte an 8051 C program to toggle only pin Pl.5 continuously every 250 ms. Use Timer O, mode 2 (8-bit ll\lllc>-ieload)
locrrate the delay.
Solution:
1
llested for DS89C420, XTAL ,. 11.0592 MHz, using the Proview32 compiler
••
.include<regs1 ,h>
~id TOM2De1ay (void ) 1
it "'Ybit•Pl•5,
......... .
I
( void main(void)
I
unsigned char x, y;
while {l)
{
mybit•-mybit; //toggle p1.s loop 0 verhead
for(x•O;xc250; x++ ) //due co forand not 40
for(y•O;ya36;y++) //we put 36
I
l,- TOM2Delay () ;

,I
.... void TOM2Delay(void)
I'' { . auto -reload)
de 2 (8-blt
TMOD•Ox 021 //Timer 0, mo load value)
/:.
• TH0=-23; //load THO(auco-re
TRO•l; //turn on TO co roll over
r'.'. while (TFO==O); //wait for TFO
TRO=O; //turn off TO
(2 l
TFO•O; //clear TFO

,....
256-23 =233
L 23 X J,085 µs: 25 µS
r 25 x 250 x 40: 250 ms by calculation. . C ~ this
H:.ever, the scope output does not give us this result. This JS due to overhead of the for loop JJl • o correct
problem, we put 36 instead of 40.

Example 9-24

Write an 8051 C program to create a frequency of 2500 Hz on pin P2.7. Use Tinier 1, mode 2 to create the delay.
Solution:

/ / tested for DS89C420, XTAl= 11.0592 MHz, using the Pro,•iew32 compiler
#include <regSl.b>
void TlM2Delay(void>;
&bit mybit,p2•7,
void main {void)
I
unsigned char x;
while(l)
I
mybit•-mybit;
T1M2De1ay(); //toggle P2,7
I
l
'

226
-
'
I
.... ·d T1M2Delay(void)
.
,111
I TMOD•OX20; //Timer 1, mode 2(8 - bi t a uto -reload)
TJ!l• - 184; //load TH l( auto - r e l oad val ue)
TRl•l; //turn on Tl
.,bile (TFl•=O ) ; //wait f o r TFl to roll over
TRl• O; // turn off Tl
TFl=O; //clear T Fl
I
1/'J:IJJ Hz = 400 µs
=
~ µs/ 2 200 µs
200 )JS/ 1.085 µs = 184

8051

2500 lu
P2.7 n.nn..JlJlJ1.J1

I •

Example 9-25

Aswitch is connected to pin Pl.2. Write an 8051 C program to monitor SW and create the following frequencies
on pin Pl.7:
SIV=O: 500 Hz
SW:!: 750 Hz
Use Tuner 0, mode I for both of them.

Solution:

//tested for AT89C51 /52, XTAL= 11.0592 MHz, using the Proview32 compiler

Jinclude <r eg 51. h >


9bi t mybit • Pl 'S ;
sbit SW :Pl '7 •

•oid TOMI Delay (unsiged char) ;
• 0 1d ma i n (void)
{
SW• l; //make Pl.7 an input
~hil e (l )
{
mybi t • -mybit; //toggle Pl.S
if (SW••O) //check switch
TOM1De1ay(Ol;
else
TOM1Delay(l)1
I

227
I
void TOHlDelay(onsigned char c)
{
TMOO=OxOl;
if(C••O)
(
TLO•Ox67;
//FC67
THO•OxFC;
l
else
{
TLO•Ox9J\; //F09A
THO•OXFO;
}
TRO=l;
while (TFO••O) ;
TRO•O;
TF'0=-0;
)
FC67H = 64615
65536 - 64615 =921
.,... 921 x 1.085 JJS = 999.285 µs
I
1 I (999.285 µs x 2) = 500 Hz

C Programming of timers Oand 1 as counters


In Section 9.2 we showed how to use timers Oand I as event counters. A timer can be used as a counter if we pro,
vide pulses from outside the chip instead of using the frequency of the crysta l oscillator as the clock source. By f~ing
pulses to the TO (P3.4) and Tl (P3.5) pins, we tum Timer Oand Timer 1 into counter Oand counter l , respectively. Study
the next few examples to see how timers Oand I are programmed as counters using the C language.

Eumple9-26

Assume tru,t • l ·Hz external clock is being fed into pin Tl (P3 5) w · C
auto reload) to count up and display the state of lh TLI 1
· · n ea program for counter 1 in mode 2 (8-bit
e count on Pl. Start the count at OH.
Solution:
#include <regSl.h>
sbit Tl • Pl"'S;
void main (void)
I
Tl•l;
TMOO•Ox60; //make Tl an input
T'Hl•O; //
Wlti.le(l)
//set count too
I //repeat forever
Do
(
TRlcl;
Pl•TLl; //start timer
} //place value
on Pine

11·11, 80S1 MlC·"0<:oNl'llol


'R n : ~ ~ ~ ~ : : : - - - - - - - - - -
lEll AND EMBEDDED svsTOfS
while (TFl==O); //wait here
TRlsO; //stop timer
TFlsO; //clear flag
l
l
Pl ,sronnected to 8 LEDs. Tl (P3.5} is connected to a 1-Hz external clock.

8051

Pl to
LEDs

1 Hz Tl

Example 9-27
Assume that a 1·Hz external dock is being fed into pin TO (P3.4). Write a C program for counter Oin mode 1 (16-bit}
to count the pulses and display the THOand TLO registers on P2 and Pl, respectively.
'
Solution:
!include <regs 1. h>
void main (void )
{
TO=l; //mak.e TO an input
TMOD=OxOS; II
TLO•O; //set count too
THO•O; //set count too
while ( l ) //repeat forever
(
do
{
TRO:l; //start timer
Pl=TLO; //place value on pins
P2•THO; II
l
while(TFO••O); //wait here
TRO•O; //atop timer
TFO•O;

8051

Pl
Pl and
P2to
LEO.
lHzdock 1ll P3.4

229
I
. . Tl (PJ.5)- Write a C program for counter oin
E,ca.mplr 9·28
Assume that a 2-Hz external dock is being red into pin . b. ry count ,nust be converted to ASCn tn_odt2
(8-bit auto reload) to display the count in ASCll- The s,batth ~:ast significant digit. Set the initial val · Di~
the ASCO digits (in binary) on PO, Pl, and P2 where PO has e ue of lJ.tii
to 0.

7
Solution:
To display the TL! count we must convert S-bit binary data to ASCII. See Chapter for data conversion_ Tlit
ASCn values will be shown in binary. for example, '9' wiU show as 00111001 on parts.
7

#include <regSl.h>
vo~d BinToASCII(unsigned char);
void main()
I
unsigned char value;
Tl•l;
TMOD•Ox06;
-. . . Tff0;;0i
while (1)
{
do
I
TRO•l;
value•TLO·
'
BinToASCII(value);
t
while {TFO· =OJ;
TRO•O;
TFO•O•
'
}
)

void BinToASCII{ unsigned


. c har value)
{ //see Chapter 7
unsigned char x , d 1 d2 d
x • val , , 3.
ue I 10 · '
dl • value , l~
d2 • 10;
X \
d3 • x f 10
PO • JO I d1 ••
Pl • )O I ~.
P2 • 30 I d3'
}

230

'
"
Ei',nple 9·29
A-<SUJlle that a 60-Hz external dock is being fed into pin TO (P3.4). Write a C program for counter Oin n1ode 2 (8-bit
aut<>-reload) to display the seconds and minutes on Pl and P2, respectively.

5olotion:
~include <regSl. h>
void ToTime {unsigned char) ;
void main{)
I unsigned char val·•
TOsl;
n,,ODtOX06; //TO, mode 2 , counter
THOs-60 ; //sec • 60 pulses
while(ll
I
do
{
TRO=l ;
secoTLO;
ToTime(val);
}
whi le (TFO==O);
TROsO ;
TFO=O;
}
}

void ToTime (unsigned char val)


{
unsigned char sec, min;
min= value I 60;
sec • value t 60;
Pl= sec;
P2 = min;
}
8051

Pl
Pl and
P2 to
P3.4 P2 LEDs
60Hzclock TO

By usu,g
. 60 Hz, we can generate seconds, minutes, hours.

..
.

For Examples of Timer 2, see the


www.MlcroDlgltalEd.com Web site.

231
I
Review Questions 8051 timers if c/T = o;x2 o".
the lock pulses to t "TMOD s to - - -
1. Who providest--•,Con made in the statemenoes from to----
2. Indicate these <>-u Us over when it g frotn - · ter.
3. In mode 1, the coun:: :Us
4 _ In mode 2, the co,:mTl!l __
over when it g:S
.., find the ex
value for the TI-f reg!S
5 In the statement - 200 .
. TFl part of register bl ?
6. TFO and are . b"t-addressa e. C
I ,-';,/oag for high in 8051 .
7. In Question 6, is ~e regithstee
8. Show how to morutor

. delays. When
· u sed as counters !hey
SUMMARY erate counters
used as timers they can g:ners/ tuJle for vanous modes..
The8051 has two timers/counters. Whenwed how to program the Timer 0, and TLl and THl fo~ Tuner l. Boin
can serve as e~ent counters. This chapter
ed as . ters·· n.o and
sh~ reg,s
two S-bit TheTHO . o f TMOD a re used for Tm1er Oand~
for4 bits
lower
) The two tuners are access .
timers use the TMOD register to set timer
O
peration modes.
th timer as a 13-bit timer, mode 1 sets it as

p
upper 4 bits are used for Tuner l . b used for each timer. Mode Osets e
There are different modes that canB-~il timer. . h urce of the frequency; when it is us«!
a l6-bil timer, and mode 2 sets it as an . the 80SI's crystal ts used as t e 50 .
When the timer/counter is used as~ ti~er80SI that increments the TH, TL registers.
as a counter, however, it is a pulse outside e

> PROBLEMS
r
SECTION 9.1: PROGRAMMING 8051 TIMERS
I Wh t is the difference behvcen the operation of a timer and a counter?
2: Th/timers of the 8051 are -bit and are designated as and - - - -
3. The registers of Timer Oare accessed as and - - - -
4. The registers of Timer I a.re accessed as and _ _ _ __ .
"
s. In Questions 3 and 4, a.re the registers bit-addressable?
6. The TMOD register is a(n) -bit register.
7. What is the function of the TMOD register?
8. True or false. TMOD is a bit-addressable register. .
9. from
Find the value for both Timer Oand Timer 1, mode 2, software start / stop (gate "' 0), with the clock coming
TMODcrystal.
the80SJ's
J
10. (a)
FindXTthe
AL=frequency
11.0592 and
MHzperiod used by
(b) the if the
timer20
XTAL= crystal attached to the 8051 has the following values
Ml-iz J
(c)XTAL=24MHz {d)XTAL=30Ml-[z
JI. What is the difference in the timer lengths in modes O, l, and 2? l
12. Indicate the rollover value (in hex and decimal) of the timer for each of th i ll ·
(a) mode O (b) model (c) mode 2 e o owrng modes. l
13. Indicate when the TFl Oag is raised for each of the following rnOd
(a) mode O (b) mode l (c) mode 2 es.
14. In which register do we find the timer start bits and timer roll fl
l 5. True or false. Both Timer Oand Timer l have their own tirn over ags?
16. Find the delay for XTAL= 22 MHz, if the program se""'e ~; sta~t O'R):
MOV
MOV
TMOD, #01
THO,#O!'FH
°-· n or timing IS
MOV TL0,#00
SETB TRO
17. Assuming that XTAL= 16 MHz, indicate when the TFo .
MOV TMOD, #01 Oag IS raised for the foll .
MOV TLO, #l2R Owtng program.

232
fl(JV THO, # l CH
S'J'B TRO • . be ?
:or the following program, and XTAL= 22 MHz, after how much time will the timer O flag set
IS. IIIJV TMOD , # 01
l'l)V TL0, # 00
'l'l)V THO, #FOH
sSTB TRO
;.ssuaungthat XTAL = 20 MHz, indicate when the TFO flag is raised for the following program.
t9. Yl)V TMOD, # 0 1
-,,ov TL0,#12H
l'l)V THO, #lCH
sSTBTRO T' 1 · r~
. ASSUI!le that XTAL = 11.0592 MHz. Find the TH1,TL1 value to generate a tirne delay of 2 ms. wer ISP
20
grammed in mode 1. d ·
. A5Sume that XT AL= 16 MHz. Find the THl,TLl value to generate a time delay of 5 ms. Timer 1 is programme m
11
mode I.
11. A5Suming that XTAL = 11.0592 MHz, program Timer O to generate a time delay of 2.5 ms.
23. Wrire a program to create a delay of 1 ms, with XTAL = 22 MHz.
14. AsSuming that XTAL = 20 MHz, program Timer 1 to generate a ti.me delay of 100 ms . .
25. With XTAL =22 MHz, write a program to generate the lowest possible frequen cy on pm PO.I.
26. Assuming that XTAL = 11.0592 MHz, and we are generating a square wave on pin Pl.2, find the highest square
wave frequency that we can generate using mode 1.
v. Assuming that XTAL = 16 MHz, and we are generating a square wave on pin PI.2, find the lowest square wave
frequency that we can generate using mode I. •
23. Assuming tha t XTAL= 16 MHz, and we are generating a square wave on pin Pl.2, find the highest square wave
frequency that w e can generate using mode 1.
l9. Using Timer 1 in mode 2 , generate a delay of 92 µs .
.Jl ln what way is mode 2 programming different from mode Oand mode 1?
ll What is mode O? What does it do?
32. Program Tuner Oto generate a square wave of 0.5 kHz. Assume that XTAL = 20 MHz.
3.l. Program Timer 1 to generate a square wave of 10 kHz. Assume that XTAL = 20 MHz.
34. With XTAL = 22 MHz, find the delay obtained using the following program.
!'CV TMOD, # lOH
l!OV TLO, #33H
l!OV TH0,#05
sm
!· TR1
Assuming that XTAL = 16 MHz, show a program to generate.a 0.25-second time delay. Use any timer you want.
· Assuming that XTAL = 11.0592 MHz and that we are generating a square wave on pin Pl.3, find the lowest square
;; wave frequency that we can generate using mode 2.
· Assummg that XTAL = 11.0592 MHz and that we are generating a square wave on pin Pl.3, find the highest uare
38. wave frequency that we can generate us,ng mode 2. sq
Assuming that XTAL = I 6 MHz ~d that we are generating a square wave on pin Pl.3, find the lowest s uare wav
l9 freq~ency that we can generate us,ng mode 2. q e
· SJ>ecify what exactly is being done by the following program.
MOV TMOD, #lOH
l\!:PT . MOV R0,#10
CPL P2.4
ilACK; MOV TLl,#05
MOV TH1,#50H
SETB TRl
~AlN: JNB TFl,AGAIN
CLR TRl
CLR TFl
DJNZ RO, BACK
\ t 11\d SJM P REPT
the value (In hex) loaded into TH in each of the following.
~
1
-n..El PllOCRAMMJNG IN ASSEMBLY AND C
233
I THO 11-22
(b) MOV o' 11-92
(a) MOV THO, #-12 (d) MOVTH '11-t04
(c) MOV THO, #-34 (I) MOV THI, iHi7 of 92 1.6 kHz (XTAL = 11.0592 MJ-ti
(e) MOVTHl, 11-120 (h) MOVTHl,_ne cycle frequency 1,
(g) MOV TH I, _11-222 b what number the machi ts to the time the TF flag is raised
41. 1n Problem 40, md,cate Y . e the tuner star ·
divided se from the tun
42. In Problem 41, find the time delay for each ca

I
SECTION 9.2: COUNTER PROGRAMMING th tiJJletS operate as counters?
43. How is the TMOD register modifie . d to. makeeachof e ·
1
44 Which pins are used as extemal count mputs.
· sed vent counters.1
45. Which of the timers can be u as~ ks? . ton Pl and P2 continuous! Sit
46. for counter 1, which pin is used to mput doc ~e and display the bUlary coun y.
47. Program Timer 1 to be an event counter. Use m 1 . ..
the initial count to 20,000. od and display the binary count on P2 continuously. Set the lllltiii
48. Program Timer Oto be an event counter. Use m e 2 .
count to 20 d dis lay the decin,al count on P2, Pl, and PO continuoU!ly
49. Program rimer 1 to be an event counter. Use mode 2 an P
Set the initial count to 99. . f h · er?
50. Which bits of the TCON register function as start bits o I e tim ·
SJ. Which bits of the TCON register are the timer rollover fla~s.1
, 52. How can an external frequency be counted using the 8051.

SECTION 9.3: PROGRAMMING TIMERS OAND 1 IN 8-051 C


53. Program TimerO in C to generate a square wave of 3 kHz, Assume that XTAL = 11.0592 MHz.
54. Program Timer 1 in C to generate a square wave of 3 kHz. Assume that XTAL= 11.0592 MHz.
55. Program Timer Oin C to generate a square wave of 0.5 kHz. Assume that XTAL = 11.0592 MH;:.
56. Program Timer 1 in C to generate a square wave of 0.5 kHz. Assume that XTAL = 11.0592 MHz.
57. Program Tuner 1 in C to be an event counter. Use mode 1 and display the binary count on Pl and P2 continuouslv
Set the initial count to 20,000. •
P~ram
58. lllltial Timer
count Oin C to be an event counter. Use mode 2 and display the binary count on P2 continuously. Set tht
to 20.

ANSWERS TO REVIEW QUESTIONS


SECTION 9.1: PROGRAMMING 80.51 TCMERS
1. Two
2. 2, 8
3. 8
4. False
5. 0010 0000 indicates Timer 1, mode 2, software start
6. FFFFH to 0000 and stop, and using XTAL i fr
7. FFH 1000 or equency.
8. -200 is 38H; therefore, THI "38H
9. 2 ms/1.085 ms= 1843 = 0733H where TH "07H an
10. 100 ms/1.085 ms= 92 or SCH; therefore, TH = SCHd TL= 33H

SECTION 9.2: COUNTER PROGRAMMING


I. The crystal attached to the 8051
2. The dock source for the timers comes from ·
3. Yes Pins TO and Tl.

234

'
-
~,iernust use the inst'"'.'c~on "SETB P3. 4µ to configure the Tl pin as input, which allows the clocks to come from
1 external source. Th.is IS because all ports are configured as output upon reset.
111
;. 5Ef8TRI
I

s£Cf10N 9.3: PROGRAMMlNG TIMERS O AND 1 IN 8051 C


n,e crystal attached to the 8051
\ runer 2, mode 2, 8-bit auto reload
i FffFH toO
i FfHtoO
s. 38H •
~ TMOD
i Yes
s. while (TFl ==0);
I

v
CHAPTER 10

8051 SERIAL PORT


PROGRAMMING IN
ASSEMBLY AND C
"' -e. cl .J2

OBJECTIVES

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

> Contrast and compare serial versus parallel communication


> list the advantages of serial communication over parallel
> Explain serial communication protocol •
> Contrast synchronous versus asynchronous communication
> Contrast half- versus full-duplex transmission ,,-
> Explain the process of data framing ·-·

> ·~
>
Oesribe data transfer rate and bps rate
Define the RS232 standard
.....
> Explain the u,e of the MAX232 and MAX23.3 chips
> Interface the 8051 with an RS232 connector
> Discuss the baud rate of the 8051
> Describe serial communication features of the 8051
> Program the 8051 aerial port in Assembly and C
> Program the l«'Oltd serial port of DS89C4x0 in Assembly and c

237
I t often 8 or more lines (wire~lld
raJJel data trans ~Jel transfers are printers and hardu~,
In':.
. araJJel and serial. ExaIJ1PJes of r:;t be transferred in a short amount ~'.a.
Computets transfer data in hvo ~ays. Pis only a few feet aw~ a lot of data ~ vice located many meters away, lhl!0 ~
arellSed to transfer data toa d~v,ce that Although in such~ To tran5fer t? 8 e trast to parallel communication, in~
each uses cables with_many w~e;~ck~ce cann~t be greae. bit at a tiJne, 1~ c;,: topic of this chapter_- The 8051 has S:.,~
by using. many wucs ~ paralle:..Ucation, the data is sent ontion of the 5051 ,s fer using only a few wires. ....,
method LS used. In senal comm t lime Serial coounuruca 'ble fast data trans 8051 interfacmg to RS232 ~nn
10 2
the data is sent a bytebilio:tymbouilretain~o it thereby making passuru•·cation, Jn 5ecbodin. us.'s ed in Section 10.3. The second~
co In thlschapterwefirstdiscuss thebas'.cs o ~ am01ing of the ""i C rogramming for sen ports #Oand #1,
mmunication capa ' . f · I comiJl on51 is sc 'al -·"1

via MAX232 line drivers is discus~- Se~al


port of 058901x0 is prograwned in Secaon ·
io 4
. ~°tn J0.5 covers 805 p

MMUNICATION .
., SECTION 10.1 : BASICS OF SERIAL CO . vides the data in byte-siz~ chunks. In somecasei,
11 pro
-, When
a
·
nucropr_ . .
.
occssorcommurucates,_,
. 1
'th
grabbed
the outside
from the
world,
· d tabusan d P•=-·
8-b,t a . . L d
-a~ted to the 8-b,tdata bus of thepri••-
even distort signals. Furthermore, an
··""
fems I 8.llt
such as printers the information IS sunp Y bles dimJIUS" an
This can work ~nly if the cable is not too long, since Ion? C:on is used for transferring data ~~d to
be

data path is expensive. For these re~ns, serial _commuru~ e J().l diagrams seri3!- versus par e a a _ans ·
tw
:ys
fers <Xll!!,!
at distances of hundreds of feet to millions of '_llJles •part: ~tead of the 8-bit data line of paralJ~I commurucabon not Olli)
The fact that serial communication uses asingle data line ms. different cities to commurucate over the lelephone.
makes it much cheaper but also enables hvo computers :;c"ted m ~~o converted to serial bits using a parallel-in-serial'(!Ot
1
For S<?rial data communication to work, the ~yte of ata;usTh~ aJso means that at the receiving end there must be
shift _re~ister; then it can ~ tr~m,tted ov~r • single.data e. d
a senal-m-parallel-out shift register to receive the senal data and p
:ck them into a byte. Of course, if data is to be tr~
d" to es which are sinusoidal-shaped sigNJs.
;<., /erred on the telephone line, it must be converted from Os an ls to au LO n , ,, •
I
. Th.is conversion· ·ts performcdbya pen'phe•al .. dev,·ce -...ulled a modem, which . for .modulatorI .demodulator. .
. . · stands
• I When the distance is short, the digital signal can be transferred as ,t 1s on a simple wtre and requires no m~ulation V
r This is how IBM PC keyboards transfer data to the motherboard. However, for long-distance data transfers usmg com- I
munication lines such as a telephone, serial data communication requires a modem to 111odt1/ale (convert from Os and Ii
to audio tones) and demod11/ate (converting from audio tones to Os and ls).
Serial darn communication uses two methods, asynchronous and synchronous. The sy11chro11ous method transfu!sa
block of darn (charactetS) at a time, while the asyncl1rono11s method trarisfers a single byte at a time. It is possible to writr
softw_are to use either of these methods, but ~e programs can be tedious and Jong. For this reason, there are specuJ
IC chips made by many manufacturetS for senal data conununications. These chips are commonly referred to as UART
(universal a~ynchrono~ rece1vcr-trans.aut_1er) and USART (universal synchronous-asynchronous receiver-transmittl!ri
The 8051 chip has a bwll-tn UART, which 1s discussed in detail in Section 10.3.

v Halt- and full-duplex transmission ••


I
. In darn transmission if the data can be transmitted and · . . $
s1mpltx trarLSmissions such as with printers in which th r~ived, ,tis a duplex transmission This is in contrast to
' e computer only sends data . Duplex tr~smissions can be half

Serial Transfer ''


'' i
•' Para!Jel Transfer
I Sender
I •[ Receiver J '•
'
•'• DO
Sender

Rece1\ler
•'
••'
''•

''
Figure 10. I. Serial versus P•r•lleJ D•ta Transfer ' D7

238

'
-
V Simplex Transmitter •[ Receiver
I 'T,v , ~1..1D

v Half Duplex Transmitter

Receiver
I"-~
V
---- ,/1
~
Receiver

Transmitter
l
I

r/
Full Duplex Transmitter ·I Receiver
I
Receiver , .. [ Transmitter

figun, 10.2. Simplex, Half-, and Full-Duplex Transfers

full duplex depending on w he ther or no t the d ata transfer can be s imultaneous. If data is trans mitted on e way at a
:ne, it is refe;,.ed to as half d11plex. If th e d ata can go both ways at the same time, it is full duplex. Of co~rse, full d uplex
requires two wire conductors for the data lines_ (in add ition to the ~ignal ground), one for trans mission a nd on e fo r
reception, in order to transfer and receive da ta simultaneously. See Figure 10-2.
V. ........... . ,....oc#..._"'"- J -0 \ "- ;..-"'._r.r,.-
' ,· , '-I • '"J • •
Asynchronous serial commun1cat1on and data fram ing
The data coming in at the receiving end of the data line in a serial data transfer is all Os and ls;.it is difficult to make
sense of the data unless the sender and receiver agree on a set of rules, a protocol, on how the data 1s p acked, h ow many
bits constitute a character, and when the d ata begins and ends.
,r' I.) (:>.Q_ 1 ( 1..1.\\\Vc_~.j A't,"'<-'- ~C.:.v<.,. - 1..-, ...,-,\\-t.r)
Start and stop bits V S,,. r
Asynchronous serial data communica tion is widely used for character-oriented transmissions, while block-orie nt.e d
data transfers use the synchronous me thod. In the asynchronous me thod, a aracter is laced between s tart and
~ts. This is called fra ming. In data framing for asynchronous communications, the data, such as ASCU aracters,
•iepaded between a start bit and a s top bit. The start bit is always one bit, but the s top bit can be one or two bits. The
start bit 1salways a O (low) and the s top bit(s) is 1 (high). For example, look at Figure 10.3 in which the ASCn character
'A' (8-bit binary 0100 0001) is framed be tween the start bit and a single s top bit. Notice that the LSB is sent out first.
Notice in Figure 10-3 that when there is no transfer, the signal is 1 (high), which is referred to as mark. Theo (low) is
"1med to as space. Notice that the transmission begins with a start bit followed by DO, which is the LSB, then the rest
ol lhe bits until the MSB (07), and finally, the one stop bit indicating the end of the character " A".
_In asynchronous serial communications, peripheral chips and moderns can be programmed for data that is 7 or
Sbits wide. This is in addition to the number of stop bits, 1 or 2. While in older systems ASCII characters were 7-bit in
ti,;ent years, due to the extended A5CU characters, 8-bit data has become common. In some older systems, due to Ute

..
.. .. . .
...• ..
• : :
.. 0 ..
Space
stop 0 1 0 . 0 .. 0 .. .. 0 1 start
mark
bit
..
.. . .. . bit
.. . ..
:
goes o ut last
t : : . :
DO
..
+
..
goes out first

--
0.3. Froming ASCD • A• (41H)

~ISEJl~:-;;;.;:;;:~ ;::-:;;:;:-::::;:::;;:::::::-:-:::::~~~~ ~~~_;_......::.=-~~~~~


UAL PORT PROGRAMMING IN ASSl!MBtY AND C
I . the device sufficient time to organi~ 1
b·ts were used to give stop bit is standard. Assuming Iha~
slowness of the receiving mechanical device, two~h~wever, the use ~~~:ieof 10 bits for each character: 8 b!ts for "'•
before transmission of the next byte. In mod~ g 1 stop bit, we have; 8-bit character there are an extra 2 bits, w~
are transferring a text file of ASCU characters u~its. n,erefore, for ea . .
ASCU code, and 1 bit each for the start and stop '-ame in order to mamtain data inteo.;
in the data" ·ty b·t 1 · dd· · .,.,~
g;ves 20% overhead. b te is included have a single pan '" a •hon to~
In some systems, the parity bit of the ch~ra~tepenrYding on the system)_w; number of data bits, including the Pilll
This means that for each character (7- or 8-bit, e fan odd-parity bit e ty
and stop bits. The parity bit is~d.oreven. In the~~ty bit system T bl l0-1: RS232 Pins (DB-25)
bit, has an odd number of ls. Sunilarly, 1~ an_e~en en For example, ::,a'.:.'.:.e:..=.:.....~-:::::;::-;.;::-- - - - - - -
the total number of bits, including the panty bit, is ~v the even-parity PP~in~---:D~e:;s~c~r-;:ip::'.ti:·o-:n==:.----
V the A5CD character "A", binary ~100 OOOl, has O ~r r odd-,even-, ;.. Protective ground -
• bit UART chips aUow programming of the panty bit fo .:l_ _ _ _ ~.:..:.:.=-::=~-::;::-:=-;:;::~:----
and no-parity options. ;.
2 _ _ _-:]:.ran~s_nu_·-,-tt:ed=d:at;;a~(T;::-x:--0-')'-----
~ Received data (RxD)
3
Data transfer rate ::.----R:_.:e:.q~u-es-:t-:to-sen--",d;--;(:;:;RTS~)---

The rate of data transfer in serial data commuruca on 1ti. ·s stated

4
~ - - - - - : ~ ' - - - - - ; - ~ ~ . . . . . ; ._ _ __
in bps (bits per second). Another widely used tenninology for bps lS S Clear to send (CTS)
baud rate. However, the baud and bps rates are not necessanly equal. :;:_____0:..:a_t_a_se_ t -re_a_d:--y'-(::DS~R;e:)- - - -
This is due to the fact that baud rate is the modem tenninology and 6
is defined as the number of signal changes per second. In modems a 7 Signal ground (GND)
single change of signal, sometimes transfers several bits of data. As :....----0-'a"-ta_c..::ar'""r-ie_r_d-:-e-t_ec_t_(DC:;:::=D=)---
rar as the conductor wire is concerned, the baud rate and bps are the
8
same, and for this reason in this book we use the terms bps and baud 9 /10 Reserved for data testing
interchangeably. -'-----U-n_a_ss_i_gn_e_d-----"---
11
The data transfer rate of a given computer system depends on
t communication ports incorporated into that system. For example, the 12 Secondary data carrier detect
early IBM PC/XT could transfer data at the rate of JOO to 9600 bps. - - - - - -,,-___.:....__ _ _ _..:;.=:.:.....-
ln recent years, however, Pentium-based PCs transfer data at rates _13_____.,.,_co_n_d_ary_,__c_l_ear_t_;o_sen;___:.::d:...._ _
as high as56K bps. rt must be noted that in asynchronous serial data 14 Secondary transmitted data
communication, the baud rate is generally limited to 100,000 bps. - ---------'---;___:....:..::...=:::....-
/ 15 Transmit signal element timing
RS232 stan dards 16 Secondary received data
17
To a!Jo"'. compatibility among data communication cc:iwpment -:-:-_ _ _ _R_ec iv_:e:..:s:.:ign!2:'.::al::...:e::l:::em:.:.:::e::.n.'. .t.'.'.timln~
:.:..:e:..: ·::lg~
made by vanous manufacturers,'."' interfacing standard caUed R5232 18 Unassigned
was set by the Electr01Ucs Industries Assoeialion (ElA)" 1960 In ::-----==?:.::=--------
ii was modified and called RS232A. RS232B and RS2J~~ · . l963 _l9~--~Sec:=.:::::o::. nd::_a:ry~req~~ues~t~to~se:.'.n~d~-
in 1965 and 1969 respective! In this were issued 20
RS232. Today, RS232 is the !~ 1 wide~!;:,":~r17~t. simply as :;:;----Da~ta:::..:t:::errrun~'.'..·:_:a!_I~rea~d:X:yl(D~'l'R~)__
21
standard. Tlus swidarcl is used in PCs and nume~ ~nt~rfa~g O equ,p-
:;:;----~S:=iE.gn:.:a::::l~q!.::u'..'.:a'..'.:li~ty~d~et~ec~t~o~r_ __
ment. However, stnce the standard was set I bef 22 Rin
the Til. logic family, its input and output vit'::ge or:i:he advent of :;:;-----~·'._'.!g~in.'.!di~·~ca~t~o~r_ _ _ _ _ __
I 23
~m3palib25le. In RS2J2, a l is represented by -3 to _;,vv arehilnot rn. ;;;----:::D.::a~ta:_:s'..'.jign~a~l_.'.:r~at~e..:se~lec:,t~---
.IS ~ to+ \!, ~king 3 to +3 undgfin~ Por this - ' w ea Obit 24
any R5232 to a microcontroller system we m t reason, to connect ~·~g-
;;;----~11~ran:'...'.:snu~~·t..:s~ign~al~e~lem~~en~t~timll1~·
such as MAX232 to convert the Til. logic !eus ;:,se voltage converters -~- - - - . : :U:'..'.n!as~~i~gn~e~d:__ _ _ _ _ _ -
levels, and vice versa. MAX232 IC chips are ve to the RS232 voltage -
line drivers. RS232 connection to MAX23z i s : = ~ referred to as
in Section 10.2. 1
13
RS232 pins
Table 10-J provides the pins and their 1
0 • • •• • • •• • • • • •
commonly referred to as the DB-25 conn~bels for the RS232 cab!
refers to the plug connector (male) and DB-~~-. ln labeUng, DB-2Se,
•••• • • • • • • • • 0
nector (female). See Figure 104. IS for the SOcket p 14
con-
Fisu.re 10-4 RS23
TH}: · 2 Connector DB-25
sos1 t.t1ca
0CONTROtt .-
ER ANO EMBEDDED svsf91S I
. not aJI the pins are used in PC cables, IBM introduced the 0~9 Table 10-2: IBM PC DB-9 Signals
~illce0 f the serial 1/0 standard, which uses 9 pins only, as shown m Pin Description
00
r~ 0-2 The DB-9 pins are s hown in Figure 10-5. Data carrier detect ([)CD)
fable I · 1
2 Received data (RJ<D)
/ commun1catton
oata · . cI asst'fl ca t·10n . Transmitted data (TxD)
3
current terminology_ classifies data communication ~q~pment .3: 4
Data terminal ready (DTR)
(data terminal eqwpment) or DCE (data commwucabo~ eqwp
[)'!£) DTE refers to terminals and computers that send and receive data, 5 Signal ground (GND)
~:·ocE refers to comm~cation equipm~t, such as modems, th~t Data set ready (DSR)

~or
•hi res nsible for transfernng the data. Notice that all the RS232 pm
definitions of Tables 10-1 and 10-2 are from the DTE point of
6
7
8
Request to send (RTS)
Clear to send (CTS)
I

"e,~ simplest connection between a PC and microcontroUer requires a


Ring indicator (Rl)
aurumum of three pins, TxD, RxD, and ground, as shown in Figure 10-6. 9
Notice in that figure that the RxD and TxD pins are interchanged. ~--------------,

1 5
Examining RS232 handshaking signals
To ensure fast and reliable data transmission between two de~ices,
lhedata transfer must be coordinated. Just as in the case of the pnnter,
because the receiving device in serial data communication may have
o 0
no room for the data, there must be a way to inform the sender to s top \

sending data. Many of the pins of the RS-232 connector are used for
handshaking signals. Their descriptions are provided below o.n ly as a 6 9
reference and they can be bypassed since they are not supported by L - - - - - - - -- - - - - - - - - '
Ille 8051 UART chip. Figure 10-5. OB-9 9-Pin Connector
1. DTR (data terminal ready). When a terminal (or a PC COM port)
is turned on, after going through a sell-test, it sends out signal
DTR to indicate that it is ready for communication. U there is DTE DTE
something wrong with the COM port, this s ignal will ~ot be acti·
vated. This is an active-low signal and can be used to inform the
modem that the computer is alive and kicking. This is an output
pin from DTE (PC COM port) and an input to the modem. RxD RxO

2. OSR (data set ready). When DCE (modem) is turned on and has
gone through the self-test, it asserts DSR to indicate that it is ground
ready to communicate. Thus, it is an output from the modem
(tx:E) and input to the PC (DTE). This is an active-low signal. Figure 10-6. Null Modem Connection
II for any reason the modem cannot make a connection to the
telephone, this signal remains inactive, indicating to the PC (or terminal) that it carmot accept or send data.
l. RTS (request to send). When the DTE device (such as a PC) has a byte to transmit, it asserts RTS to signal the modem
that it has a byte of data to transmit. RTS is an active-low output from the DTE and an input to the modem.
l CTs (clear to send). ln response to RTS, when the modem has room for s toring the data it is to receive, it sends out
signal CTS to the DTE (PC) to indicate that it can receive the data now. This input signal to the DTE is used by the
DTE to start transmission.
i
~ ( ~er detect, or OCD, data carrier detect). The m_odem asserts signal DCD to inform the DTE (PC) that a
aUd cam er has been detected and that contact between it and the other modem is established. Therefore, DCO is
an output from the modem and an input to the PC (DTE).
l RI \ring indicator). An output from the modem (DCE) and an input to a PC (DTE) indicates that the telephone
: 11nging. It goes on and off in synchronization with the ringing sound. Of the six handshake signals, this is the
a ast of!en used, due to the fact that modems take care of answering the phone. However, if the PC is in charge of
riswering the phone, this signal can be used.

;;;---~:-::=----~-=-===-=-::-::::::-:::~~~~ ~~__;;..._...:._~~~~~
8
ElllAL PORT PROG RAMMING IN ASSEMBLY AND C
241
' . .
from the above descnptlon~
munica
, ed as follows: While signals DfR
. lion can be suJTUllliavnzeand well, it is RTS and CTs that a~
C and modem com . . te that they are a d in response, 1'f th e m odem ·IS ready 0,.
respectively, to ,n~c~ it asserts RT5, : not activate CTS, the PC Will de....
DSR are used by the PC and m e:;:,e PC wanlS to send a m the modem oe~ als
....

-..rt
aUy control the/1;"';\da:~~~ack crs.If, for lack i:w;re controRSI~~;· i~sh~ke signals plus TxD, RxD,
room) to accep e a a, d CTS re also referred to as
0
i.nS of the ,.,
~
OTR and try again. RTS an . . a f the most important p
This concludes the descnption o . al und).
, ground. Ground is also referred to as 5G (sign gro

IBM PC/compatible COM ports


b ed x86 (8086, 286'
386
'
4B6, and Pentium)chmicfr:;0
re
use one ea o
i:~~~n°:~~y~~~'
'"'-'2

IBM PC/ compatible computers asRS;·type connectors. Many 5 resent time COM 1 is used for the m Use
0
two COM ports. Both COM ports h~ve ed COM 1 and COM 2. At the p serial port to the COM 2 port of a PC for
connectors. The COM ports are des1gnat as We can connect the 5051
and COM 2 is available for devices such as a modem. ext section we disc
serial communication experiments. ady to look at the 8051. In then . USS illP
With this background in serial communication, we are reSecti' 10_3 we show how to program the 8051 senal com.
. of the 8051 and RS232 connector, and m
physical connection on
\
munication port.
.
I

j
Review Questions
1. The transfer of data using parallel lines is - - -- (faster, slower) b u t - - - - - - - (more expensil'e,
less expensive). -
·' I 2. True or false. Sending data to a printer is duplex. .
3. True or false. In fuU duplex we must have two data lines, one for transfer and on) for ~1ve.
4. The start and stop bits are used in the (synchronous, asynchronou~ met ·. b. .
r 5. Assuming that we are transmitting the ASCU letter "E" (0100 0101 in binary) ,v1th no panty 1t and one stop bit,
show the sequence of bits transferred serially.
6. In Question 5, f:ind the overhead due to framing.
7. Calculate the time it takes to transfer 10,000 characters as in Question 5 iJ we use 9600 bps. What percentage of time
is wasted due to overhead?
8. True or false. RS232 is not ITL-compatible.
9. What voltage levels are used for binary Oin RS232?
10. True or false. The 8051 has a built-in UART.
11. On the back of x86 PCs, w~ normaUy have COM port connectors.
12. The PC COM ports are designated by DOS and Windows as and

SECTION 10.2: 8051 CONNECTION TO RS232


---
_In this section, the details of the physical connections of the 80.S .
Secbon l0.2, the RS232 standard is not m compatible· th f . I to RS232 connectors are given. As stated in
to convert RS232 voltage levels to ITL levels and vi e' ere oThre, '.t requires a line driver s uch as the MAX232 chip
MAX232 chi · th . ' c versa. e tnterfac· f 80
p 1s e main topic of this section. mg o 51 with RS232 connectors via the

RxD and TxD pins in the 8051


The 8051 has two pins that are used speci6caU i
caUed TxD and RxD and are part of the port 3 ro Y or transferring and receiv· . .
pin 10 (1'3.0) is designated as RxO. These pins! ~ (P3.0 •nd P3.1). Pin
11 of thmg data serially. These two ptnS art'
RS232 compatible. One such line driver is the M~~ co_mpali_bl~; therefore, th e 8051_ (P3.l) is assigned to TxD and
chip. This 1s diSCIJssed ey require a lliie d river to make them
MAX232 next.
Since the RS232 is not compatible with toda 's ·
converter) to convert the RS232's signals torr( i;ucropr<>cessors and .
One example of s uch a converter is MAX232 fr~~ ~~';;.els that Will
Corp. (\\'Ww.
:~::ntroJJers,
w e need a line driver (,•oltagt!
. P~ ble to the 80Sl's TxD and RxD plll>
242 ma)(Jm. ic.com). The MAX232 con\'ertll ft<ll11
T!iE 80s1 Mic
R<>coNiROLL '
ER AND EMBEDDED 5ySl'Pd
,., voltage levels to TTL voltage levels, and vice versa. One ad vantage of the MAX232 chip is that it uses a +5 V power
p:.32 which, is the same as the source voltage for the 8051. In other words, with a single +5 V power supply we can
~b<>ththe8051 and MAX232, ~ith no need for the dual power su pplies that are common in m~y older syst~ -
1""n,e MAX:232 has two sets of line drivers for transferring and receiving data, as shown "' Figure 10-7. The line
r.;used forTxD a recalled Tl and T2, while the line drivers for RxDare designated as Rl and R2. In many appbca- I

:Jell
Jfl''t()lily one of each~ u~d. For example, Tl and Rl are used together for TxD and RxD of the 8051, ~nd the second
unu~- Notice ln ~A~2 that the Tl line driver has a designation of Tl in and Tl out on ~"' numb~rs l 1
~ 14, respech~ely. The T11n pm is the TTL side and is connected to TxD of the microcontroller, w~ le ,:1out 1s t~e
~ side that_is connected to the RxD pin of the RS232 DB connector. The Rl line d river has a designation of Rl~
2
Jll<lRlouton pm numbers 13 and 12, respectively. The Rlin (pin 13) is the R5232 side that is connected to the TxD pin
of the 1(5232 DB co~ector, and Rl out (pin 12) is the TTL side that is connected to the RxD pin of the microcontroller.
See figure J().7. Nonce the null modem connection where RxD for one is TxD for the other. I
MAX232 requires four capacitors ranging from 1 to 22 µF. The most widely used value for these capacitors is 22 µF.

./
1,1AX233
Tosave bo~rd_ space, some d esigners use the MAX233 ch ip from Maxim. The MAX233 performs the same job as the
\1AX232but ehrrunates the need for cap acitors. However, the MAX233 chip is m uch more expensive than the MAX232.
\'oticelhat MAX233 and MAX232 a re not pin compatible. You cannot take a MAX232 out of a b oard a nd replace it with
.~wm3. See Figure 10-8 for MAX233 with no capacitor used.

Vee
C3
16 + '
+ 2
Cl I 8051 MAX232
3 MAX232 6 11 14 2
TxDO (P3.1) 11
+
C2
4
5
i?4 13 3 Q~
Tl L, Tl-
u 14 RxDO(P3.0)
10 12
R1,,. DB-9
RI°"'
12 13

10
n.. T2ou,
7
~ R2.,
9 8
TILside 15 RS232 side
e

fi&,,tt t0-7. fa) Inside MAX232 and (bl its Connection to th e 8051 (Null Modem)

Vee
13r-- -7L---~
14 8051
12 MAX232
2 _

3
n .. Tl""'
5
TxOO (P3.1 ) u

10
2

3
5
4 3 os
c_n
Rl., RxDO (P3.0)
Rloor DB-9
2 4
n,,. T2ou,
l 18
~ R21N
20 19
TILside 6 9 RS232side

lig,,.10-9. (I) I • .
::----__ nside MAX233 •nd (b) Its Connection to the 8051 (Null Modm,)

lllis~1~~L~;;;::;;~~;;;~-;;-;~~;;~~~~~~~~~~~~~~~~~~-
~ , l'ORT PROGRAMMING IN ASS EMBLy AND C
243
' Review Questions
OM port connector ts
. the R5232 t~e-
unicat,on, an
d what are t h e1r
· functions'.
True or false. The PC C 'd for serial comm
1. Which pins of the 8051 are set as, e232 used for? RJCD. v
; : What a.re line drivers such
~ MAX232 can support -
:~i TxD and -
MAX23 over the MJ\.N-J
'~'.;!!~hip? Table 10-3:
5. What is the advantage of the 3 MBLY PC Baud Raies
/ NG IN ASSE 110 --......
ORT PROGRAMMI d how how to ISO--....
SECTION 10.3: 8051 SERIAL p . . reoisters of the ~ t an sputers are so
\../ . • 1 mmun1cahon o· I rnpatlble com . . 300--.....,
ln this section we discuss the seria co rially. Since UlM PC co . erial commurucations
• program them to transfer and receive da':; tems we will emphasiz~5 pC and an 8051 sys-
600 - -
~ • widely used to communicate with:is:CbaTo a:i~:v dat; trar1Sfer betw;n 1 ~em ma tches the baud
of the 805 I with the COM port of : · that the baud rate of the 80 vs listed in Table 10-3. 1200
,,J'•) tem without any error, we must ma e sure pported by PC BIO are
rate of the PC's COM port. Some of the baud rates s;indows HyperTerminal progr~m ~ o,vs
d click-
2400
i:. You can examine these baud rates by g?mg to th~ Terminal program comes with Wind ·
I ing on the Communication Settings option. The ~~~rthe ones listed in Table 10·3.
r: HyperTermina.l supports baud rates much higher 9600
19200
(J i/
Baud rate in the 8051 f;!.i-'< 5 \ S«-c. . Nole. Some o/ the Lui
ratessupPOrtectby,156;
. d'f! t baud rates. The baud rate m the
,, Toe 8051 transfers and receives data se.nally at m~y I eren , di USS how to do that, we
8051 is programmable. This is done with the help ofTlll1er I. Before we 5<:
Pentium IBM PC~
I
will look at the relationsrup between the crystal frequ':"~ and the baud rate m the 8051· . .
'r As discussed in previous chapters, the 8051 divides the crys- Table 10-4: Timer 1 TH1 Register
ta! frequency by 12 to get the machine cycle frequency: In the case Values for Various Baud Rates
of XTAL : 11.0592 MHz, the machine cycle frequency IS 921.6 kHz
(11.0592 MHz/12 : 921.6 kHz). The 805J's serial communication Baud Rate THI (Decimal) THI (Heu (
UART circuitry divides the machine cycle frequencyof921.6 kHz by 32 _ FD
once more before it is used by Tinier I to set the i>aud rate. Therefore, 9600 3
921.6 kHz divided by32gives28,800 Hz. This is the number we will use 4800
throughout this section lo find the Timer l value to set the baud rate.2- - - - - - - - -- - - - - - - F -FA 4--
When Timer l is used to set the baud rate it must be programmed in 400 12
mode 2, that is 3-bit, auto-reload. To get baud rates compatible with the 1200 -24 E8
PC, we must lo.id THI with the values shown in Table 10-4. Example 7N:"'. o,,-
r:"" :cL,-•- ,-ll""
XT=A .om
= -M- l-i.i-. - - - - - - - -
10-J shows how to verify the data in Table 10-4.

With XTAL-11.0592 MHz. find the THI value needed t ha th


(a) 9600 (b) 2400 (c) 1200 °
ve e following baud rates.
Solution:

With XTAL= 11.0592 MHz, we have:

where -3 ~ FD <hl.'x) .
1
where-12 = F4 (hex) ~ l~adect into llil
where-24 ~ E8 (hex) IS oaded into llil
1
IS Dadect into llit

244
tivation of the 8051 RESET
'ol)ce that I /12th of the crystal frequency divided by 32 1s the defa u1 t v_aJue upon ac
"- We can change thL• default setting. The. is explained at the end of the; chapter.
pin.
11,0592 MHz
28,800 Hz
Machine cyde freq.
XTAL +32
oscillator + 12 by UART To TI mer I to
921.6 kHl.
set the baud
rate

r .t s,,__,,_~
sBUF regts er
SBUf is an 8-bit register used solely for serial communication in the 8051. For a byte of data to ?e tra.rc;ferred via
the TxD line, it must be placed in the SBUF register. Similarly, SBUF holds the byte of data ".'hen it ,s received by t~e
S05J's RxD line. SBUF can be accessed like any other register in the 8051. Look at the following exa mples of how this
register is accessed:

SBUF, #' D'


II/JV ;load SBUF=44H, ASCII for '0'
MOV SBUF,A ; copy accumulator into SBUF
MOV A,SBUF ;copy SBUF into accumulator
I
The momenta byte is written intoSBUF, it is framed with the start and s top bits and transferred serially via the TxD
pin. Similarly, when the bits are received seria lly via RxD, the 8051 deframes it by elilninating the stop and start bits,
making a byie out of the data received, and then placing lt in the SBUF.

-rSCON (serial control) register


The SCON register is an 8-bi t register used to program the start bit, stop bit, and data bits of data framing, an,ong
otlwr things.
Figure 10-9 describes various bits of the SCON register.
v
SMO, SM1
SM? and SMl are D7 and D6 of the SCON register, respectively. These two bits determine the framing of data by
specifying the number of bits per character, and the start and s top bits. They take the following combiJ,ations:

I SMO I SM! I SM2 I REN I TBS RBS Tl RI

SMO SCON.7 Serial port mode sp«i6er


SM1 SCON.6 Serial port mode sp«:ifier
SM2 SCON.5 Used for multiprocessor communication. (Make it O.)
REN SCON.4 Set/cleared by software to enable/disable reception.
TBS SCON.3 Not widely used.
RB8 SCON.2 Not widely used.
Tl SCON.I Transmit Interrupt nag. Set by hardware at the beginning of
the ,top _bit in mode t. Must be cleared by software.
RI SCON.O Rccc,v~ mte~pt Oa.{!. Set by hardwan.- hallway through the
&top b,t time ,n mode I. Must be cleared by software.
Nolt: Make SM2, Tll8, •nd RBS e O.
~g•rt10.9 s
......_ · CON ~al Port Control Register (Bit-Addressable!

!os1 SElJ.>.
L PORT PllOCRAMMINC IN ASSEMBLY AND c
' SMO SM1
o Serial Mode O top bit I start bit
0
1 Serial Mode 1, 8-bit data, 1 5 '
0
l o Serial Mode 2
1 1 Serial Mode 3 . for the other three modes is in Append.ix,,
h er explanation d f · · 8 b. ''-{
. . finterestto us. furl . chosen, the ata ra.nung 1s its, 1 stoP bi
/ Of the4serial modes,onlymode 1150 . t when serial mode 115 .bl PCs More importantly serial \
They are rarely used today..In the SCON ~s :·COM part of 1BM/compat1 ; 1 for each character a'iotaJ O ~!I
and 1 start bit, which makes 1t compatible wi t ~ of the BOS!. In senal mo ~ ' bit 01,j~
allows the baud rate to be variable and is set by TIJT\er 1ed b 8 bits of data, and finally 1 stop ·
are transferred, where the first bit is the start bit, follow Y

, . ./
SM
2
. . Iii rocessing capability of the 8051 and is beyond Ifie
SM2 is the OS bit of the SCON register._This bit en.ables ~h~:~ =~since we are not using the 8051 in a multiproets-
discussion of this chapter. for our applicattons, we will ma e
sor environn,ent.

REN
The REN (receive enable) bit is 04 of the SCON register. The REN bit is also referred to as SC0~.4 since SCON ~
a bit-addressable register. When the REN bit is high, it allows the 8051 to receive data on the RxD pm of the 8051. As
a result ii we want the 8051 to both transfer and receive data, REN must be set to 1. By making REN = 0, the recei,·er
is disabled. Making REN= J or REN = O can be achieved by the instructions ·SETB SCON. 4 • and "CLR SCON .4•,
respectively. Notice that these instructions use the bit-addressable features of register SCON. This bit can be used to
block any serial data reception and is an extremely important bit in the SCON register.
r
TBS
TB8 !transfer bit 8) is bit 03 of SCON. Jt is used for serial modes 2 and 3. We make TB8 = o · ·· used·
our applicabons. since 11 ,s not ui

RBS
~88 (receive bit_S) is bit 02 of the SCON register. In serial m . .
data as received. This bit (as is the case for TB8) is ode 1• this bit gets a copy of the stop bit when an IJ.bd
I
Like TBS, the RBS bit is also used in serial modes 2 ~:~ Y used anymore. In all our applications we will make RBS =0.
v 3.
Tl

Tl (transmit interrupt) is bit DJ of the SCON re . . .


ter. When the 8051 ftnishes the transfer ( h . gaster. This 1s an extreme! ·
another byte. The TI bit is raised at the ~ t. e ~-bit character, it raises the TI or
•mp_ort?nt flag bit in the SCON regi;-
examples of data transmission are given. guullng of the stop bit. We will discu~~ indicate that it is ready to tranSfef
its role further when programming
- / RI
. Rl (receive interrupt) is the DO bit of the .
register. When the8051 receives data seriaJJ ~ON register. Tlus is an th
register Then ii raises th RJ 11 Yvia RxD it gets ·d O er extreme! ·
is raised halfway Im ~ th ag bit _10 indicate that ;byte h n b of the start and sto b .Y unportant flag bit in the SCON
oug e stop bit, and we wiJJ soon as een received and hp •ts and places the byte in the 581.J
/ p . see how this b·•tis
. USed ·s Ould be P•=ed
·-•- up before it is lost RI
rogramm1ng the 8051 to transfer data I 111 programs for receiving data senaU,
1n ~rally ·
programming the 8051 to transfer char
acter bytes senau
1 The TMOD register is loaded with th y, the following Ste
the baud rate. I
• va ue 201-!, indicann ps must be taken.
& theUSe 0 ( .
Timer J 111

246 rnocte 2 (8-b1t auto-reload) to st1
. d ( rial data transfer (assumi ng
n,e THI is loaded with one of the values in Table 10-4 to set the bau ra te or se
l X'fAL = 1t.0592 MHz).
' h 1 data is framed ,vith start
s-b·t
u,eSCON register is loaded ,vi th the value SOH, indicating serial mode 1, w ere an
3· .i11d stop bits.
I
Till is set to 1 to start Timer 1.
l,

,.• nisdeared by the " CLR T I • instruction.


6- The character b yte to be transferred serially is written into the SBUF register.
The TI flag bit is n,onitored with the use of the instruction •JNB TI. xx " to see if the characte r has been trans·
7
· ferred completely.
s. To transfer the next character, go to Step 5.
nsi r "YES"
Example 10-2 shows a p rogram to transfer d ata serially a t 4800 baud. Example 10-3 shows how to tra e
continuously.

Importance of the Tl flag


To understand the importance o f the role of Tl, look a t the following sequence of steps tha t the 8051 goes thro ugh
in transmitting a character via TxD.

I. The byte character to be transmitted is written into the SBUF register.


I
2. The start bit is transferred.

Example 10-2
Write a program to transfer a letter 'Y' serially at 9600 baud continuously, and also to send a letter 'N' through
port 0, 1vhich is connected to a display device.

Solution:

Here one byte of data is transmitted serially through pin 11 (P3.1), and another is sent in parallel form through
port 0.

•y•
P3.! I----=-----
r
. ..> ' 8051 1----l"'-
~ 'N' - ',
~ 1---~i,/....._D_IB_P_LA_Y__,

~ _____...:...:..
PO
I
: TMOl>, #20H ;Timer 1 , mode 2 (auto-reload)
I THl,1·3 ; 9600 baud rate ,:.Ori
SCOll,#SOH ;8 bit, 1 atop, REN enabled
;atart Timer 1
:t,.,,,y, ;tranafer 'Y' aerially
TI,RBRB ;wait for tranemiaeion to be over
CLR TI ;clear TI for next tran•mi••ion
MOV PO,t••• ;move 'N' to PO for parallel t r anafer
SJMP MMDI ;repeat

247
' r . data serially, continuously.
v Ex•mple J0-3 fte the other and transfer thJS
0 I
Take data 1n through ports ' • and2,onea r

Solution:
/ ·Timer 1, te
mode 2
MOV TM00,#20H
MOV THl,ii-6 '.4soo baud ra bit REN enabled
' top '
\ MOV SCON,#SOH ;8 bit,l sn input port
PO,#OPFH ;make PO a input port
f :~~ Pl,#OFFH ;make Pl an ·nput port
' . \. MOV
SBTB
P2,#0FFH
TRl
·make P2 an J.
.
:start Timer l
.
RPT: MOV A; PO . for transmissJ.on
ACALL @"END) ;call subroutJ.ne
MOV A, Pl
ACALL SEND
MOV A, P2
ACALL SEND
SJMP RPT
.
·----------transferr,ng ser,'ally · to SBUF
·' )!=: • MOV SBUF,A
JNB
CLR
Tl,HERE
TI
;load data ,n . ' d
;wait for transmission to.::ion
;clear TI for next transmi
- RET

3. The S·bit character is transferred one bit at a time.

4. The stop bit is transferred. It is during the transfer of the stop bit that the 8051 raises the Tl flag (Tf = 1), indicating
that the last character was transmitted and it is ready to transfer the next character.
S. By monitoring the Tl flag, we make sure that we are not overloading the SBUF register. If we write another byte
into the SBUF register before Tl is raised, the untransmitted portion of the previous byte will be lost. In other
words, when the 8051 finishes transferring a byte, it raises the TI flag to indicate it is ready for the next character.
6. Afternew
this SBUF is to
byte loaded with a new byte, the Tl Oag bit must be forced to Oby the ·CLR TI• instruction in order fat
be transferred.

From the above discussion.we conclude.that by checking the Tl flag bit, we know whether or not the 8051 is ready
to transfer another byte. More unportantly, 1t must be noted thal the Tl o b't · · db . elf h 'tlin·
ishes the transfer of data, whereas it must be cleared by th ag I is ra ise y the 8051 its w en 1
must be noted that if we write a byte into SBUF before th:
~r~f~er with an ~truction such as "CLR TI·. It also
being transferred . The Tl Oag bit can be checked by the instructio~ • •s raised, :;ve
nsk the loss of a portion of the by~
see in Chapter 11. In Chapter 11 we will show how to use int JNa Tl,··· or we ca.n use an interrupt, as we will
microcontroller with instructions such as •JNa TI, xx•. errupts to transfer data serially, and avoid tying down tht

0 rogrammlng the 8051 to receive data serially


In the programming of the 8051 to receive character b t .
Y es serially, the follow·
I. The TMOO register is loaded with the value 20H . d' . mg steps must be taken.
the baud rate. ' '" •c•ting the use of Tuner . ...
2. THI is loaded with one of the values in Table 10-4 t 1
l.n mode 2 (8-bit auto-reload) to><•
0
set the baud
3. TheSCON register is loaded with the valueSOH ind· . rate (assuming XTAL., MHz)
stop bits and receive enable is turned on. ' •eating serial ltlOcfe ._ 11 ·0592 · ._,
1
'w.,ere 8-bit data is framed with sblrt .....
;RI 15 set to 1 to start Timer 1.
l. • •,·scleared with the "CLR RI" instruction. h been
< "'
,. .
n,e Rl nag bit is monitored with the use of the instruction " JNB RI • xx• to see if an entire character
· as
°' received yet. I
When RI is ra ised, SBUF has the byte. Its contents are moved into a safe place.
~ To receive the next characte r, go to Step 5.

Examples 10-4 and 10-5 shows the coding of the above steps .

.,,,,
ex,111ple 10-4
. f orm an d send it o ut to p ort Oin parallel form.
. senal
Write a program to receive the data which has been sent m
Also save the data at RAM location 60H.

Solution:

MOV TMOD , #20H ; Timer l ,mode 2,auto-re l oad

l MOV
MOV
/" SETB
THl ,#-3
SCON, #SOH
TRl
;9600 baud
; 8 bit, l stop,REN enabled
;start Timer 1
~ LR RI ;RI is cleared for reception
JNB RI, RPT ;wait for character to come in
MOV A,SBOF ;move received data into A
MOV PO,A ;1110ve it to PO
MOV 60H,A ;1110ve it to RAM location 60H
END

Ex•mple 10-5

Assume that the 8051 serial port is connected to the COM port of the IBM PC, and on the PC we are using the
HrperTerminal program to send and receive data serially. Pl and P2 of the 8051 are connected to LEDs and
SWitches, respectively. Write an 8051 program to (a) send to the PC the message "We Are Ready", (b) receive any
data sent by the PC and put it on LEDs connected to Pl, and (c) get data on switches connected to P2 and lend
it to the PC serially. The program should perform part (a) once, but parts (b) and (c) continuously. Use the 4800
baud rate.

Solution:

ORG 0
MOV P2, #0FFH ;make P2 an input port
MOV '1'40D, #2 0H ; Timer l , mode 2 (auto- reload)
HOV TB1,#01AH 14800 baud rate
MOV SC011, #5 0H 18-bit, 1 atop, JUDI enabled
SBTB TIU , •tart Ti mer 1
a' 1.. MOV OR1R, IMYDATA : load pointer for 111eaeage
CLR A
MOVC A,eA+DPTR :get the character
JZ B_l.
..... ACA!,L 88'ID
,otherwue ~11
,
.t~.,
1 if l ut character p t Clllt

249

,
' one
•next . 100P
INC DP1'R ' 1n 2
SJMP H_ l ;scaa~ data on epriallY
. re it s
B_l: MOV A, P2
'.cransfer ial data
ACALL SEND ' the ser LEDS
ACALL RECV ;g:t lay it on. definitlY
MOV Pl,A ;disp. lOOP 1n
SJMP B_l ;staY in che data
I ------serial data transfer. ACC haS a .
;--------- MOV S8UF,A d che dat . last bit gone
· loa until
V SEND:
JNB
H 2
TI, _ ;stay here for next char
H_2:
CLR TI ;get ready caller
1 • ·return co
·I')~ ' ;-------
RBCV:
RET
--------receive
JNB
data serial 1'y in ACC
RI,RECV
;wait
here for c har
·n ACC
MOV A,SBUF ;save itdl for next char
~- CLR RI t rea Y
I ;ge
·return to c all er
RET
I ----The message
'
;-----------DB •we Are Ready•,o

r
MYDATA:
ENO

·'I 80$1

•r To
Pl " / LED
TxD /
PC

COM
/
RxO P2 \ SW
port
"

Importance of the RI flag bit


In receiving bits via its RxD pin, the 8051 goos through the foUowing steps.
I. I
2 t receives the start bit indicating that the next bit is the first bit of the character byte it is about to receive.
3. The 8-bit character is received one bit at time. When the last bit is received, a byte is formed and placed in SBUF,
. iving the stop _bit the 8051 rnakes RI == 1, indicating that an entire character byre
The stop bit is re<:eived. When re~eke
4. has been received and rnust be p,c d up before 1t gets overwritten by an incoming character.
By checking the RI flag bit when it is raised, we kno_w that a character has been received and is sitting in the SBUF
register. We copy the SBUF content~ to a safe place m some Other register or rnem before it is lost.
s. After the SBUF contents arecop1eddchinto a safe place, the RI llagbit rnust be forced to
0 ryOby th "CLR RI" instruction
cinhara cter.to aUow the next receive
order aracter byte to be placed in SBUF F . . e th ...,...;ved
1
· a, Ure to do th15 causes loss of e •=~
From the above discussion we cond_ude that by che.:king the RI fla bi ,-eel
•""""" .... ""' ''" """''"""•••~r,p1.._ "'"" "'f g w, "-, w"""' w""'"" ""If"'""' •
_, ... "'~ ... "',,"""by ....,. "'' "-~,.. """' !:"" •• - ... S,,.. - ""-·~· ""'!".,,
f

2.50 Ythe Programmer With an instruction such as


, also must be noted that if we copy SBUF into a safe place before the RI flag bit is raised, we_risk copying gar~;ge.
;;,R: 1 0Jg bit can be checked by the instruction •JNB RI, xx• or by using an interrupt, as we will see JJl Chapter ·

[)Oublin9 the baud rate in the 8051 I

1nere are two ways to increase the baud rate of data transfer in the 8051.

use a higher-frequency crystal.


I.
2- (hange a bit in the PCON register, shown below.

DO I•
Q.\100 I GFl GFO PO fDL

Option 1 is not feasible in many situations since the system crystal is fixed. More intportantly, ii is n~t feasible
1,ecauselhe new crystal may not be compatible with the IBM PC serial COM port's baud rate. Therefore, we will explore
option 2. There is a software way to double the baud rate of the 8051 while the crystal frequency is fixed. This is done
with the register called PCON (power control). The PCON register is an 8-bit register. Of the 8 bits, some are unused,
and some are used for the power control capability of the 8051. The bit that is used for the serial communication is D7,
theSMOD(serial mode) bit. When the 8051 is powered up, 07 (SMOD bit) of the PCON register is zero. We can set it
iohigh by software and thereby double the baud rate. The following sequence of instructions must be used to set high
07 of PCON, since it is not a bit-addressable register:

MOV A, PCON ;place a copy of PCON in ACC \

SETI! ACC. 7 ;make 07=1


MOV PCON,A ;now SMOO=l without
;changing any other bits

To~ how the baud rate is doubled with this method, we show the role of the SMOD bit (07 bit of the PCON regis-
ler), which can be Oor 1. We discuss each case.

Baud rates for SMOD = o


,. IVhen SMOD = 0, the 8051 divides 1/12 of the crystal frequency by 32 and uses that frequency for T" 1t th
wud rate. In the case of XTAL = 11.0592 MHz we have: ,mer O set e

llachine cycle freq. = 11.0592 MHz I 12 = 921.6 kHz


and
921.6 kHz I 32 • 28,800 Hz since SMOO. o
is This is the frequency used by Timer 1 to set the baud rate. This has been the b ·
0
f
!ht default when the 8051 is powered up. The baud rate for SMOD O li ads~ all the examples so far since it
= was ste m Table 10-4.
Baud rates for SMOD = 1
IVith the fIXed crystal frequency, we can double the baud rate by
iliePc kin SMO0 1
lo set ~N cegister) is set to 1, 1/12 of XTAL is divided by 16 (instead :;;2) ! d tha . = · When the SMOO bit (07 of
1 e baud rate. In the case of XTAL= 11.0592 MHz, we have: t 15 the frequency used by Timer 1
l!ach ·
•na 1.ne cycle freq. • 11. 0592 MHz I 12 = 921. 6 kHz
921 6 kH
· z I 16 = 57,600 Hz since SHOO. 1

-- Thi$.15
the frequency used by Timer 1 to set the baud rate
.
~ISEJt;;;:~:;;:;.;:~~~;;;~~;;;;~~~..,......__,..,........,......~..,......~~..,........,........,........,........,........,......_
~IAJ. PORT PROGRAMMING IN ASSEMBLY AND C
251
' Table 10-5: Baud Rate Compan
S
.,,00 == oand SMOD = 1
·son for JV•
sMOD"' o SMOD - l
THJ ( Decimal) (Hex) 19,200
9,6()()
-3 FD
4
,BOO 9,600
FA 4,800
2,400
12 F4 2,400
/ 1,200
-24 E8
I Not< XTAI- = 11.0592MHz.
,__ / same for both cases; however, the baud rates
1
,. Table 10-5 shows that the values loaded into THl are tht ·t the data given in Table l 0-5. See also Exa ~
doubled when SMOD = 1. Look at the following examples to c an Y lllple.
., .
u, 10-6 through 10-10.

17
' Example 1()..6
Assuming that XTAL = 11.0592 MHz for the following program, state (a) what this program does, (b) compute the
frequency used by Timer l to set the baud rate, and (c) find the baud rate of the data transfer.

MOV A, PCON ;A= PCON


SETB ACC. 7 ;make 07 s 1
·'I MOV PCON,A ;SMOD • 1, double baud rate
;with same XTAL freq.
MOV 1'MOD,N20H
'r MOV THl,-3
;Timer l, mode 2 (auto-reload)
;19200 (57,600 I 3 = 19200 baud rate
; since SMOD•l)
HOV SCON,#SOH :8-bit data,l stop bit, RI enabled
SETB TRl ;start Timer 1
MOV A,#"'B" ;transfer letter B
A_l: CLR TI ;make sure TI• O
MOV SBUF,A :transfer it
H l: Jl'lB TI H_l
SJMP A1 ;stay here until the last bit .
;keep sending ., 8 ,, . 1.s gone
again and again
Solution:

(a) This program transfers ASCU letter B (


(b) With XTAL: 11.0592 MHz and SMOoo!~lO binary) continuously.
in the abo,•e pr
tl.0592 MHz/ 12 z 921 kH . ogram, we have:
6
921.Q kHz I 16 =57,600 H
Irz machine cycle frequency
57,600 Hz/ 3: 19,200 bau~ ~!uency used by Timer 1 to set th b
e aud rate

Example 10..7
If the crystal frequency is 22 MHz
SMOD : 1? ' what wiU be the ba
Ud rate if. (a) THt -
3
Solution: - - ; {b) Tl-lJ" -12 with Sl\.iOO,. 0 and

With a 22 MHz crystal, the calculation IS the


5'1me as on Ex
ample 10-1.

252
~tOD
111th S'
=O. we have
22
·-'
,i.,dun~ cyue freq - - = 1833 KHz
.- 12
I
~=57.281 KHz= 57,281
-
p,d .31

57, 281 '<> "\M...&


(a) \Vith THl = -3, the baud rate is = 19,093
3
57,281
(b) With THI = - 12, the baud ra te is = 4773
12

11,lh 5'"10 D = 1, the baud rates a.re do ubled.


(a) iVith THl = - 3, the baud rate is 38,186
(bl With TH I = - 12, the baud rate is 9546

,/

find the baud rate if THl = - 2, SMOD = 1, and XTAL = 1l.0592 MHz. Is this baud rate s upported by IBM/ com -
pa~ble PCs? •
Solution:

\\'ith )ITAL= 1l .0592 MHz and SJ\100 = 1, we have Timer 1 frequency = 57,600 Hz. The baud rate is 57,600 I 2 =
28,500. This baud rate is no t s upported by the BIOS o f U,e PCs; however, the PC can be programmed to do data
tran.fer at such o speed. Also, HyperTerminal in Windows s upports this and other baud rates.

Eumple 10-9

Port Oof an 8051 is used to monito r a parameter in an industrial environment. Uthe parameter gives a readjng
aboveOFl-1, a n1essage 'HI' is to be sent serially. Otherwise, a message 'OK' is to be sent. The words 'HI' and 'OK'
a,.. burned into progr,1m ROM locations

ORG OOOOH
MOV PO , #OF FH ;make PO an input port
MOV '!'MOD , #20H
MOV THl , # -3
MOV SCON, #S OH
SETS TRl
MOV A , PO : move PO into A
CJNE A, #OFH, TEST ; check if it is equal to OPII, if not go to TEST
SJMP OK ;if equal to OFH, go to OK
Ttsr, JNC HI
CJ. ;if it is greater than OFH, go to HI
MOV DPTR,#OOAOH ; let DPTR point to me••age Olt
ACALL ACCESS ;call subroutine to ace••• .,.••age ROM area
SJMP CHSCK ,continue lll<>Ditoring PO
' HI: HOV DPTR,#009011 ;let
int
oP'J'R po ,
··"-rout111e . PO
co
sage HI
to acce ss mes s ag e area
mes

ACALL ACCESS •-call . s=


ue moo1· coringwhere me ssage s are stored .
SJMP C!!ECK ;cont1n ROM area
program
,-----·····--- subroutine co access
CLR A
ACCESS: A MA+DPTR
MOVC ,•
ACALL SEND
INC DPTR
CLR A
.._./ A,eA+OPTR
MOVC
ACALL SEND

RET
··············subroutine to send data serially
SEND , MOV S8UF, A
HERE:. JNB T!,HERE
CLR TI
RET
ORG 009011
MESI: DB "'HI"'
ORG OOAOH
MES2: DB "OK"
ENO

Example 10-10

A square wave is being generated a_t pin Pl.2. This square wave is to be sent to a receiver connected in serial form
to thJ.s 8051. Write a program for this.

Solution:

Timer O in mode 2 is used to generate the square wave on pin Pl.2. Whenever this pin is high, a data FFH is
transmitted serially, and when this pin is low, a data OOH is transmitted. This data can be converted into parallel
fonn at the receiver side to regenerate the square wave the,:e.

ORG OOOOH
MOV TMOD,#2 2H
MOV SCON,#SOH ;Timer O and Timer l in made 2
MOV THl,#- 3
MOV THO,#OOH
SETB TRl ;count value for Timer 0
HOV A, #OOH ,start Timer
;move A e.Oo 1
CLR Pl . 2
REPT : SETB TRO
BACK: .me ;start Timer 0
TPO,BACK
CPL A ;watt for Timer
CPL Pl.2 ;complement A o ro11°"9r
MOV SBOP,A ICO!llplement P1.2
CLR TRO ;move A to S8t,p
CLR TPO ; •top Timer a for trana111••ion
;clear Timer o llag

254
JNB TI , HERB ;check for TI Oag t transm~ssion
CLR Tl ·clear TI to enable nex
SJMP REPT '
;repeat thewh o 1e process
END
I

I terrupt·based data transfer . th Tl and Rl flags. In order to


n . trO ller's tm,e to po 11
e h t use
6 now you might have noticed that it is a waste of the ~,croc~n f oiling. In Chapter 11, we will show ow 0
. ywasti'.ng the microcontroller's time we use. interrupts
a,·01d • t 1nstea o P
interrupts to program the 8051's serial communication por ·
'
Review Questions
Which timer of the 8051 is used to set the baud rate? . t the baud rate?
I. If XT AL=11.0592 MHz, what frequency is used by the llmer to se .
;· Which mode of the tin,er is used to set the baud rate? . have a baud rate? Give the answer in
t With XTAL = 11.0592 MHz, what value should be loaded mto THI 10 9600
both decimal and hex. . .
To transfer a byte of data serially, it must ~e pla_ced m register __.
:: SCON stands for - and it is a~n) _._-b1t ~eg:t~r.framing information s uch as the stop bit?
7. Which register is used to set the a tabsize an to er
s. True or false. SCON is a bit-addressa 1e regis e r. \

9 When is Tl raised?
10 Which register has the SMOD bit, and ,vhat is its s tatus w nen the 8051 ·is P0 we red up'·

SECTION 10.4: PROGRAMMING THE SECOND SERIAL PORT


Man of the new enerations of the 8051 mkrocontroUers come with two serial ports. The DS89C4~0
(DSS9C4i0/30/40/ ...) an~ DS80C320 a.re among them. In this section we show the programming of the second senal
port of the DS89C4x0 chip.

DS89C4x0 second serial port


The second serial port of the DS89C4x0 uses pins Pl.2 and Pl .3 for the Rx and Tx Lines, respectively. See
Figure 10· 10 The MDE8051 Trainer (available from www.MicroDigitalEcLcom) uses the DS89C4x0 chip and comes
with two se;ial ports already installed. It also uses the MAX232 for the RS232 connection to 089. The connections
for the RS232 to tne DS89C4x0 of the MDE8051 Trainer a.re shown in Figure 10-11. Notice that the first and second
serial ports are designated as Serial #0 and Serial #1 , respectively.

Addresses for all SCON and SBUF registers


All the programs we have seen so far in this chapter assume the use of the first serial port as thedefaultsetiaJ port since
every version of the 8051 comes with at least one serial port. The SCON, SBUF, and PCON registers of the 8051 are part of
the special function registers. The address for each of the SFRs is shown in Table 10-6. Notice that SCON has address 98H,
S81JF has address 99H, and finally PCON is assigned the 87H address. The first serial port is supported by all assemblers
•nd Ccompilers in the market for the 8051. U you examine the list file for 8051 Assembly language programs, you will see
that these labels are replaced with their SFR addresses. The second serial port is not implemented by all versions of the
8051152 microcontroller. Only a few versions of the 8051/52, such as the DS89C4x0, come with the second serial port. As a
!tsult, the second serial port uses some reserved SFR addresses for the SCON and SBUF registers and there is no universal
~ment among the makers as to which addresses should be used. In the case of the DS89C4x0, the SFR addresses of
~ illld _Cl H are set aside for SBUF ai:'d SCON: as shown in Table 10-6. The DS89C4x0 technical documentation refers to
registers as SCONl and SBUFl smce the first ones are designated as SCONO and SBUFo.

;;--:S;ER:1A~L~P=o=R=T=P=R~OG-:::RAMMIN-::-::-::::::G~IN::-::A:s=sEMB=-==L~Y-AN~o~c~~~~~~~~~~~~~~-~
255
' DD'
Vee
40
P().0(AD0)
(12) Pl.0 39
(T2EX) Pl.I P().l (ADI)
38
(RXDI) P12 P().2 (AD2)
(TXDI) Pl.3 OS P0,3 (AD3)
(INT2) Pl.4 89C4JCO P0.4 (A D4)
(INT3) P1.5 (89C420 P0.5 (ADS)
s9C430
(INT4) Pl.6 P0.6 (AD6)
s9C440
(!NTs) PJ.7 P0.7 (AD7)

7
- I

RST
(RX[)()) P3.0
89C4S0l
i,A/VPP
ALE/PROG
(TXDO) P3.l
·~ I PSEN
(INTO) P3.2
1'2.7 (AIS)
(INTI) P3.3
1'2.6 (A 14)
(TO) P3.4
P2.5 (A13)
(Tl) P3.5
(WR)P3.6 P2.4 (AI2)
(Im) P3.7 P2.3 (All)
XTAL2 18 P2.2 (A IO)
XTAL1 19 P2.1 (A9)
GNO 20 P2.0 (A8)

Figure 10-10. DS89C4x0 Pin Diagra'.:, Rx and lie Imes of lhe 2nd serial port
Nat,: Notict Pl .2 and PL3 pins If(' used"'/'

Vee
C3
+ 16 +
2
Cl
! 6 DS89C4x0
:I MAX232 i
0 14
TxDO (P3.J) II 11
ll
Tl,, TIOl/f RxDO (1'3.0)
14 13
12 RIOl/f RI.,
13
10
T2,. 1'2w, TxD1 {PI.J) 4
7 RxOI (Pt.2)
R2ou, R2,,

..
9
8
1Tlside·L-•1s5,-RRS232 side

Flgu,e 10-U. (a) ln51 •


'd MAX23z and Cb) its Connection to the 0S89C4xo

Table 10-6: SFR Byte Addresses for DS89C4xO Serial P orts


SFR
SCON (byte address) First Serial Port
SCONo,.981-! Second Serial Port
SBUP (byte address)
SBUFQ,,991-! SCONt =COH
TL (byte address)
n.1 "881-! SBUFl =C!H
ni (byte address)
TCON (byte address) Tl-it" 801-f Tl.1 "881-J
TCONo " 881-J 11i1 "8D1i

-
PCON (byte address)
l'CON,.871-! TCONo"' 881i
!'CON "87H
-
Table 10-7: SFR Addresses for the DS89c4x0 (4201 430' etc.)
Symbol Address
Name
ACC• Accumulator EOH

a• B register
FOH
,
PSW• DOH
Program status word
SP Stack pointer 81H

DPTR Data pointer 2 bytes


DPL Low byte 82H
DPH High byte 83H

PO' Porto 80H


PJ• Port 1 90H
P2' Port 2 OAOH
P3' Port3 BOH
IP' Interrupt priority control BSH
IE' Interrupt enable control A8H
TMOD TID\er I counter mode control 89H
TCON' TID\er / counter control 88H
TICON' Timer/counter 2 control C8H
T2MOD TID\er/counter mode control C9H
THO T=er/ cow,ter O high byte SCH
TU! Tuner/ counter O low byte BAH
THl TID\erI counter I high byte 80H
TLl TimerI counter 1 low byte BBH
TH2 TID\er/ counter 2 high byte CDH
TL2 Tuner/counter 2 low byte CCH
RCAP2H T/C 2 capture register high byte CBH
RCAP2L T/C 2 capture register low byte CAH
SCONO' Serial control {first serial port) 98H
SB UFO Serial data buffer {first serial port) 99H
PCON Power control
87H
SCONl' Serial control (second serial port) COH
SBUFl Serial data buffer (second serial port) ClH
• Bit,addres,abl•

Programming the second serial port using timer 1

ltlcj While each serial port has its owi:i SCON and SBUF registers, both ports can use Timer 1 for setting the baud rate.
~ upon reset, the DS89C4x0 chip uses Tm~er l for setting the baud rate of both serial ports. Since the old e r 8051
~. 1 ~rsdo not support this new second serial port, we need to define them as s hown in Example 10-11. Notice
tn both C and Assembly, SBUF and SCON refer to the SFR registers of the first serial port. To avoid confusion, in

.......___~--~~~~~~~~~~~~~~~~~~~~~~~~~~
8
'1s] ERIAL PORT PROGRAMMING IN ASSEMBLY AND C
257
' the first an
DS89Clx0 programs we use SCONO and SBUF0 Ior • 1 portS as ""
h
this reason, the MDE8051 Trainer designates t e sena
d SC
ONl and SBUFl for the second serial
5e · I #1 ·
,.-rial #0 and na
d P<>tts
in o r er to comply . · Foi
With
~
designation.
See Examples 10-12 through 10-14.

RB8 Tl RJ
/ I SMO I SMI I SM2 I REN I TB8 I
Bits Bit Addresses
Serial #1
Serial IHl Serial port mode specifier
(i SMO SCON0.7 = 9FH SCONl .7 " C7H
Serial port mode specifier
• • SMl SCON0.6 =9EH SCON 1.6 =C6H
Multiprocessor com.
SM2 SCONO.S = 90 H SC0Nl.5 = CSH
Enable/ disable reception
REN SCON0.4 = 9CH SCONl.4 =C4H
SCONl.3 = O H Not widely used
TBS SCON0.3 • 9BH
RBS SCON0.2 = 9AH SCONJ.2 = C2H Not widely used
Tl SCONO.l • 99H SCONl. l =C!H Transmit interrupt flag
lU SCONO.O = 98H SCONl.O =COH Receive interrupt flag

Note: Make SM2, TBS, and RBS= O.

Figt,r,, 10-12. SCONO and SCO Nl 811


• Addres.,es (Tl and RI bits must be noted)

E=ple 10.11
Write a program i th
baud. usc 8.b'it data
or and
• second
1 stop serial port
bit. Use 1. D589C4x0 to continuously transfer the letter "A"
of the
Timer . II
Solution: sena Y at 4800

SBUFl EQU OClH


SCONl ;second serial SBUP
EQU OCOH ; second serial addr
Til BIT OC!H ,second serial SCON_addr
Ril BIT OCOH ;second ser· 1 TI bit addr
ORG ia RI bit
OH ;Startin . addr
MAIN: g POSltion
MOV
MOV
TM00,#20H
Tlil,#-6 ;COM2 uses Ti
;4800 baud mer l upon reset
. '
MOV SCONl,~SOH ; COM2 h . rate
SETS Tl!l as lts
AGAIN: MOV ;start T'1mer own SC0N1
A.,#'A'
ACALL SEN0COM2 ,send oha r 'A'1
SJMP AGAIN
' ,--------- ------
S£N0COM2:
MOV SBI.IFl, A
HERE:: JNB Til,HERE :COM2 has 1
CL!! 1 COM2,._ ta own
Til ,..,9 ite S8lJF
RET 0 wn TI flag
I
END

2.58
01 plel0-12 b'
£.-(11 t t 9600 8-bit data, and 1 stop 11•
\~rite a proS"am to send the text string "Hello" to Serial #1. Set the baud ra ea '

Solution:

SCONl EQU OCOH


SBUFl EQU OClH
Til BIT OClH
ORG OH ,starting position
MOV TMOD,#20H
MOV THl. , #- 3 ;9600 baud rate
MOV SCONl ,#SOH
SETB TRl
MOV DPTR, #MESS1 ;display "He l lo•
f'N: CLR A
MOVC A, @A+DPTR ;read value
JZ Sl ;check for end of line
ACALL SENDCOM2 ;send co serial port
INC DPTR ;move to next value
SJMP FN
Sl: SJMP Sl
SENDCOM2 :
MOV SBUFl,A ;pl ace value in buffer
KEREl : JNB Til,HEREl ;wait until transmitted
CLR Til ;clear
RET ,,
MESS1 : DB nHello",0
END

Example 10-13

Program the second serial port of the DS89C4x0 to receive bytes of data serially and put them on Pl. Set the baud
rate at 4800. 8-bit data, and 1 stop bit.

Solution:

SBOFl EQU OClH ;second serial SBUF addr


SC0Nl EQU OCOH ;second serial SCON addr
Ril BIT OCOH ;second serial RI bit addr
ORG OH ;starting position
MOV TMOD,#20H ;COM2 uses Timer 1 upon reset
MOV THl,#-6 ;4800 baud rate
MOV SCONl,#SOH ;COM2 has its own SC0Nl
SETB TRl ;start Timer 1
HEQE: JNB Rll,HERE ;wait for data to come in
MOV A,SBUFl ;eave data
MOV Pl,A ;display on Pl
CLR Rll
SJMP HERE
EN'D
'

259
'
Exam ple 10-14 . .
ed pin n.o. followtng.
A"UITle th.It a switch is connect !otch •nd perform the
- a program to morn'tor the sw1
~Vrite • t
. l#OPo'.
(a) If SW = 0 send the message "Hello" to the
"Goodbye" to Sena . 1# J port
the Sena
( (b) If SW= Jsend the message

Solution:

,., SCONl
Til
EQU OCOH
BIT OClH
l '' SWl BIT P2.0 .
·start1n9 po sit ion
ORG OH '
MOV TMOD,#20H
MOV TH.l,#-3 ·9600 baud rate
'
MOV SCON,#SOH
MOV SCONl,#SOH
SETB TRl
SETB SWl ·make SWl an input
51: JB SWl,NBXT '.check SWl statue
MOV Dl?TR, #MESS1 '.if

SWl=O display "Hello"
,, FN: CLR A
I MOVC A,ltA+DPTR ;read value
JZ Sl ;check for end of line
ACALL SENDCOMl ;send to serial port
INC DPTR ;move to next value
SJMP FN
NEXT: MOV DPTR, #MESS2 ; if SWlal display "Goodbye"
LN: CLR A
MOVC A,~A+OPTR ;read value
JZ Sl ;check for end of line
ACALL SEIIDCOM2 ;send to serial port
INC DPTR ;move to next value
SJMp LN
Sl!NDC0M1:
MOV SBUF,A
HERe: JNB Tl,HE:RE ;place value in buffer
CLR TI ;wait until transmitted
; clear
RET
SENDCOM2,
MOV SBUFl,A
HEREl: JNB Til,HERJ;:l ;place value in buffer
CLR Til ;wait until transmitted
RET
;clear
MESS1, DB •Hello•,o
M.ESS2: DB "Goodbye"' , O
J;:111)

Review Questions
(AU questions refer to the DS89C4x0dtip)
I. Upon reset, which timer is used to set the baud rate fo Ser·
2. Which pins are used for the second serial ports> r •al #0 llnd Serial #! ?

260
l'liE 80s1 ~ CRoco
l'f l'ROLLER ANO EMBEDDED 5YSTV'5
~Vith XTAL= 11.0592 MHz, what value s hould be loaded into THl to have a 28,800 baud rate? Give the answer in
3. t,oth decimal and hex.
To transfer a byte of data via the second serial port, it must be placed in register - -
4· S(ON1 refers to and it is a(n) -bit register. . .
5• \,vJuch register is used to set the data size and other framing information sud, as the stop bit for the second serial
6.
port?

SECTION 10.5: SERIAL PORT PROGRAMMING INC


This section shows C programming of the serial ports for the 8051/52 and DS89C4x0 chjps.

Transmitting and receiving data in 8051 C


As ,ve stated in the las t chapter, the SFR regis ters of the 8051 are accessible directly in 8051 C compilers by usinS: the
regSl.h file. Examples 10-15 through 10-19 show how to program the serial port in 8051 C. Connect your 8051 Tramer
to the PC's COM port and use HyperTerminal to test the operation of these examples.

Example 10-15

\,I/rite a C program for the 8051 to transfer the letter" A" serially at 4800 baud continuously. Use 8-bit data and
1 stop bit.

Solution: I

#include <regSl.h>
void main (void)
{
TMOD=Ox20; //use Timer 1,8-BIT auto-reload
THl=OxFA· //4800 baud rate
'
SCON=OxSO;
TRl=l;
while (l)
{
SBUF= 'A'; //place value in buffer
while(Tl==O);
Tl=O;
}
}

Example 10-16
w·nte an 8051 C p rogram to transfer the message "YES" ·
continuously. senally at 9600 baud, 8-bit data, 1 s top bit. Do trus

Solution:

#include <regSl. h>


vo·d
v ~ SerTx (unsigned char);
01
d main(void)
{
TMoo.ox20; //uae Timer 1,8-BIT ...
•ut o-re 1oa.d

261
' THlsOxf'D; //9600 bau d rate
SCON•OxSO;
TRl=l; //stut ti·mer
whlle (l)
{
,,. SerTx{'Y') 1
SerTx('E' ) ;
serTx( 'S') •
I l
V l
void Ser'l'x(unsigned char x )
{
in buffer
SBUFsx; //place val~etransmitted
while{TI••O); //wait untl
TI•O;
l

Example 10-17 . Pl Set the baud rate at 4800, 8-bit data,


. ~ . lly and put them m ·
Program the 8051 in C to receive bytes of data ser,a
I and l stop bit.

r Solution:

#include <regSl.h>
void main (void)
{
unsigned chaI mybyte;
TMOD•Ox20;
THl•OXFA; //use Timer 1,8-BIT auto-reload
//4800 baud rate
SCON=OxSO;
TEU•l;
//start timer
wbile(l)
{ //repeat forever
while (Rl==O);
//wait to receive
mybyte•SBOF; //save value
P1=mybyte;
Rl•O; //write value to port
I
)

Example 10-18
.
Write an 80.51 C program to send two different strings lo the . ·
P2.0, monitor its status and malce a decision as follows:
SW 2 O: send your first name
&eriaJ port. Aa.iuning that SW is COl'li't«ad • flt,- .
SW • I: send your last ll8JJ1e
Assume XTAL ~ 11.ll592 MHz, baud tlleof~,8-bit data, I stop bit
'.

262
.
.

NTROtLER. AND EMBEDDED sY5'fPd


solution:
ude <regSl. h>
#l!lC l "'
. t MYSW=P2 0; //input switch
sb1 .
I
voi'd main (void)
{
unsigned char Z;
unsigned char fname [] ="ALI";
unsigned char lname[]="SMITH";
TMOD=Ox20; .
//use Timer 1,8-BIT auto-reload
THl=OxFD; //9600 baud rate
SCON=OxSO;
TRl=l; //start timer
if(MYSW==O) //check switch
{
for(z=O;z<3;z++) //write name
{
SBUF=fname[z]; //place value in buffer
while (Tl==O); //wait for transmit
TI=O;
}
}
else
{ \

for ( Z=O; Z<S; z++) //write name


{
SBUF=lname[z]; //place value in buffer
while(TI==O); //wait for transmit
TI=O;
}
}
}

Example 10-19

\\.'rite an 8051 C program to send the two messages "Normal Speed" and "High Speed" to the serial port. Assuming
that SW is connected to pin P2.0, monitor its status and set the baud rate as follows:
S\V:: 0 28,800 baud rate
S\V:: 1 56K baud rate
Assume that XTAL = 11.0592 MHz for both cases.
Solution:

~lnclude <regSl. h>


. MYSW=P2"0 ,·
sb1t
//input switch
\told main (void)
{
unsigned char z·,
unsigned char Messl[] .. "Normal Speed";
Unsigned char Mess2[]="High Speed";


'
263
' TMOD•Ox20;
l
· rner ' 8 .aIT auto-reload
//use Tl for normal speed
//28,800
THl•OXFF;
SCON•OXSO; //start tl·mer
TRl•l1
if (MYSW-0)
{
for{z•O;z<l2;Z++)
{ ·n buffer
I lace value l .
SBUP•Messl(z); IP
I /wait ofr cransmit
while(TI••O);
Tl•O;

' . I
J
else
{ .
I
PCON=PCON Ox80;
I I for high spee d of 56K

for(z=O;Z<lO;z++l
{
SBUF•Mess2(z); //place value in ~uffer
while {TI==O); //wait for transmit

}
}
}

8051 C compilers and the second serial port


Since many C compilers do not support the second serial port o( the DS89C4x0 chip, we have to decia1e ~
byte addresses of the new SFR registers using the sfr keyword. Table 10-6 and Figure 10-12 provide the SFR bytt
and bit addresses for the DS89C4x0 chip. Examples 10-20 and 10-21 show C versions of Examples 10-1 J and 10-13
in Section 10.4.

Notice in _both Examples 10-20 and 10-21 that we are using Timer 1 to set the baud rate for the second serial port
Upon reset, Tamer l ,s the default for the second serial port of the DS89C4x0 chip.

Example 10.20

Write a C program for the DS89C4x0 to transfer letter" A" · u


serial port with 8-bit data and I stop biL We can only use T' sena Y at 4800 baud continuously. Use the second
1
Solution: mer I to set the ba ud rate. Ii

Hinclude <regSl.b,
sfr S8UF1.oxc1,
Sfr SCONl:OxCO;
sbit Til•OXCl;
void main(voidJ
(
nioo.ox20;
'nU.sOxFA; //use Timer l f
2
SC0Nl•0XS0; //4800 ba ud rat~r nd serial P<>rt
TRl•l; //uee 2nd •er1a1
//start ti··-r P<>rt SCON1
"• register

264
wh.i le (1)
{
SBOFl•'A': //uae 2nd aerial port SBUFl register
while(Tll••O); //wait for transmit
Tll•O;
}

DS89C4x0
TxDO (1'3.1) 11 It 14 2
-Ds i
[1. ·ccX"
RxDO (P3.0)
10 12 13 3
- -.. D
4
7 2
-Ds ..
TxD1 {Pl.3)
RxDI (Pl.2)
10
8 3 _[1. I
3 9
PC

llumple 10-21

Program the DS89C4x0 in C to receive bytes of data seria lly via the second serial port and put them in Pl. Set the
baud rate at 9600, 8-bit data, and I stop bit. Use Timer I for baud rate generation.
Solution:

ll.nclude <regSl.h>
•fr SBUFl=OxCl;
afr SCONl=OXCO;
1bit R!l=OxCO;
void main(void)
I
unsigned char mybyte;
TMOO•Ox20; //use Timer 1, 8-BIT auto-reload
Tl!leOxFO; //9600
SCONleOxSO; //use SCONl of 2nd serial port
TRl=l;
while(l)
{
while(Ril=•O); //monitor Ril of 2nd serial port
mybyteeSBUFl; //use SBUFl of 2nd serial port
l'2=mybyte; //place value on port
Ril=O;
}

111.-., Questions
~~are the SFR registers accessed in C?
l I"- or false. C compilers support the second serial port Of th DS8
lepiters SBUF and SCON are declared inc using the e 9C420 chip.
.,. keyword.

. . IIJuAL PORT PllOCRAMMJNC IN ASSEMBLy AND C


' see www.MlcroDigltalEd.comte
the baud ra
hOW to use
~~ Serial #0.
Timer 2 to set

(
• unication. Se.rial communication, in
.._/ SUMMARY fundamentals of senal dicommtances since in parallel communicatiOI\
· to the . sent over s1b'~·· _;r;cant sf the data. Ser,a • ti on has !hi
· J commuruca

7
l•
This h t began with an introducbon
which da~? s~nt one bit a time, is ~sed wh:;i:~·n~
here data is sent a byte or more a bme,_gr_e
.
can cause ~istor:;:~cation uses hvo methods: synchronOUs
hone lines. Sena! co f b tes· in asynchronous, data 1s sent m bytes.
~' wdditi'onal advantage of allowing transrruss,?n ~ver ~ata is sent in blocks O Y( :n send and receive, but not at the 5amt
d but cannot receive , ~
/\ a chr commurocabon, . ) h l( duplex c-, . .
and asynchronous. ln syn ~nous dard for serial commurucation connectois.
I
Data communication can be simplex (c3!1 sei; the same time). RS232 IS a st~l 'th an RS232 connector and change thp
' time), or full duplex (can sen? and r:e;e o(
:hawed how to interface the 8 :, ( w~res the 8051, and programmed the
bau~:t:o:r1;~~:S;. ;;.a::~~~~:ew~d~cribed th.:it~
8051 for serial data communication. We also show
;i;:::::; s:ond serial port of the DS89C4x0 chip m
Assembly and C.

PROBLEMS
SECTION 10.1: BASICS OF SERIAL COMMUNICATION

co;
1. What is the advantage of serial communicatio:'5 ov:iparflel :mmc:~~ons?
2. Distinguish between half duplex and full dup ex m ) e o ~ b't ·
3. Show the framing of the letter ASCil "2" (0101 1010 , no pan , s O(p 'k. )
4. U there is no data transfer and the line is high, it is called mar , space .
5. True or false. The stop bit can be 1, 2, or none at aU.
6. Distinguish between synchronous and asynchronous data transfer.
7. Which are the voltage levels used in RS232C?
8. What is the function of the MAX 232 chip?
9. True or false. DB-25 and DB-9 are pin compatible for the first 9 pins.
10. How many pins of the RS232 are used by the IBM serial cable, and why?
11. Which are the minimum signals required in serial data transmission?
12. are
State the absolute
those signals? minlmum number of signals needed to transfer data behveen hvo PCs connected serially. What
13. U two PCs are connected through the RS232 without the modem they both nfi ed (OTI.
OCEJ -to- (DTE, DCE) connection. ' are co gur as a _ ___
14. State the nine most important signals of the RS232.
15. Calculate the total number of bits transferred if 200 pages of ASCn .
transfer. Assume a data size of 8 bits, 1 stop bit, and no pa ·ty Ass data are sent using asynchronous senal data
16. Jn Problem 15, how long will the data transfer lake if the bn d. ume each page has 80x25 of text characters.
au rate 1s 9,600?
SECTION 10.2; 8051 CONNECTION TO RS232
17. Wha t is the function of the chip MAX232?
18. Which pins of the 805 I are connected to MAJ<232?
19. The MAX233 DIP package has pins.
20. For the MAX233, indicate the Vcc and GNO Pins.
21. What is the advantage of using the MAX233 from M . ,
22. State the advantages and disadvantages of the MAX:m.
23. MAX232/233 has line driver(s) for the Rxo "'~-• nd MAX233.

Tlie 80s1 Micb


~0coNTao .....-.d •
LLQ AND EMBEDDED sn•-
'
MA)(232/233 has line driver(s} for the TxD wire. t . the second set of line drivers
?4. Show the connection of pins TxO and RxD of the 8051 to a DB-9 RS232 connec or Vta

15 of MA)(232.
26. Show the connection of the TxD and RxD pins of the 805! to a D B-9 RS232 connector via the second set of line
drivers of MAX233. t v · a MAX232
'tl Show the connection of ~he TxO and RxD pins of the 8051 to a OB-25 RS232 COM~ or '. MAX ·
zi. Show the connection of the TxD and RxD pins of the 8051 to a DB-25 RS232 conn or Vta 233·

SECTION 10.3: 8051 SERIAL PORT PROGRAMMING IN ASSEM13LY


29. Which of the following baud rates are supported by the BIOS of 486/Pentium PCs?
(a) 4,800 (b} 3,600 (c} 9,600
(d) 1,800 (e) 1,200 (f) 19,200
30_ \'{hat is the role p layed by Timer 1 in serial communication?
31. Which mode of the timer is used for baud rate programming?
32. l'fhat is the role of the SBUF register in serial data transfer?
33. l'fhat is the function of the SBUF register ?
34. \'fhat is the role of the SCON register in serial data transfer?
35. Which a.re the important functions specified in the SCON register? .
36. For XTAL= 11.0592 MHz, find the THI vaJue (in both decimal and hex} for each of the following baud rates.
(a) 9,600 (b) 4,800 (c) 1,200 (d} 300 (e) 150
J7. \'fhat is the baud rate if we use ·MOV THl, #-1" to program the baud rate?
38. Write an 8051 program to transfer serially the letter "2" continuously at a 1,200 baud rate.
39. Write an 8051 program to transfer serially the message "The earth is but one country and mankind its citizens"
continuously at a 57,600 baud rate.
40. Under what conditions are the Tl and RI bits raised?
41. Write a program to transfer the numbers 1 to 9 serially.
42. To which register do RJ and TI belong? ls that register bit-addressable?
43. What is indicated by the REN bit of the SCON register?
~- In a given situation we cannot accept reception of any serial data. How do you block such a reception with a single
instruction?
"5. To whic.h register does the SMOD bit belong? State its role in the rate of data transfer.
"6. Is the SMOD bit high or low when the 8051 is powered up?

In the following questions the baud rates are not compatible with the COM ports of the PC (x86 IBM/compatible).
47. Find the baud rate for the following if XTAL= 16 MHz and SMOD,. O.
(a) MOV THl,#-10 (b) MOV THl,#•25
(c) MOV THl, #-200 (d} MOV THl, #-180
48. F?r a XTAL of frequency 22 MHz, what is the baud rate if THI is loaded with-IO?
49. Ftnd the baud rate for the following if XTAL = 16 MHz and SMOD = 1.
(a) MOV TIU, #-10 (b) MOV THl, #-25
(c) MOV THl, #-200 (d) MOV THl, # -180
SO. How can the baud rate of data transfer be doubled?

5EcnON 10.4: PROGRAMMING THE SECOND SERIAL PORT


~ N~e o~e version of 8051 whkh comes with a second serial port.
Sl Which timer of the DS89C4x0 IS used to set the baud rate for the seco d 'al ?
St Wluch mode of the timer is used for baud rate programming of the n ~rt ix:rt
55 What are the addresses of the SCON and SBUF of the second seri secon f sena port?
· SBUFJ. is a(n) _ -bit register. a I port O 0589C4x0?
: , ~ t is the role of the SCONl register in serial data transfer?
,.· F,or using the second serial port, how are the SFRs designated'
· or XTAL"' 11.0592 MHz, find the THI value (in both dee· ·

--~ (a) 9,600 (b} 4,800 (c) 1,200 (d) 300 (e) 150

SER.IAt PORT PROGRAMMING IN ASSEMBt y ANO C


unal and hex) for each of the following baud rates.
' .,,..,,,.4 o to transfer sena
59 Write a program (or '-""''~ x
.
4'2" conb.fluOUS
. Uy the Jetter
sage "The e
ly at a 1,200 baud rate. Use the S&-n...

arth is but one country and


~~
rnan~=-.
"'"Cl 1b

( . .
ser,al port
·aJJ the mes
transfer sen Y
6(). Write a program for DS89C4x0 t:aud rate. Use the secon
citizens" continuously at a 57,600
61 . When is the TH Oag bit raised?
rt
d serial po ·

. PORT PROGRAMMING INC . I at a 1,200 baud rate.


,/ SECDON 10.5. SERIAL
· Uy the letter
"Z" continuous Y
62. Write an 8051 C program to transfer sena the message "The ear th ·s
1 but one co
UI1try and mankind its ' H,~
a._.
I
1
63. Write an 8051 C program to transfer senal Y . sly at a 1 200 baud rate. Use the second
t/ continuously at a 57,600 baud rate. . IJ the letter "Z" continuou '
. C f DS89C4z0 to transfer sena Y
64. Wnte a program or · ,, th is but one country and manJcind ,
'
~'
. I
serial port. riaU the message The ear
65. Write a C program for the DS89C4x0 to transier sethe Jcond serial port.
'~
citizens" continuously at a 57,600 baud rate. 0 se

ANSWERS TO REVIEW QUESTIONS


SECTION 10.J: BASICS OF SERIAL COMMUNJCATION
1. Faster, more expensive
2. False; it is simplex.
3. True
4. Asynchronous
5. With 0100 0101 binary the bits are transmitted in the sequence:
r (a) 0 (start bit) (b) 1 (c) O(d) I (e) 0 (f) 0 (g) O(h) 1 (i) 0 Q) 1 (stop bit)
6. 2 bits (one for the start bit and one for the stop bit). Therefore, for each 8-bit character, a total of 10 bils ~
transferred.
7. 10000 x JO; 100000 bits total bits transmitted. 100000/9600 = 10.4 seconds; 2/10 = 20o/o.
8. True
9. +3to+25V
10. True
11. 2
12. COM I and COM 2

SECTION 10.2: 8051 CONNECTION TO RS232


1. True .
2. Pins lOand 11. Pin IO is forTxDand pin 11 forRxD
3. They are used for converting from RS232 voltage le~els to TTL
4. 2, 2 vo1tage levels and vke versa.
5. It does not need the lour capacitors that MAX232
must have.
SECTION 10.3: 8051 SERIAL PORT PROCRAMMfNG lN
.
I. Timer .J ASSEMBL y
2. 28,800 Hz
3. Mode2
4. -3 or FDH since 28,800 / 3 = 9,6()()
5. SBUF
6, Serial control, 8
7. SCON
8. False
9. During transfer of stop bit
10. PCON; it is low upon RESET.
SE(TION 10.4: PROGRAMMING THE SECOND SERIAL PORT

t 'fllller 1
PinS Pl.2 and Pl.3
:,. -1of FFH
4. S8Uf1
S. Serial Control 1, 8
6. SCONl

SECTION 10.5: SERIAL PORT PROGRAMMING INC


1 By using the reg5l.h file
2. False
:,. sfr

...._
llsJ SElJAL PORT PROCIIAMMJNC IN ASSEMBLY ANO c
v
CHAPTERll

INTERRUPTS PROGRAMMING
IN ASSEMBLY AND C

OBJECTIVES

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

> Contrast and compare Interrupts versus polling


> Explain the purpose of the JSR (interrupt service routine)
> list the 6 btterrupts of the 8051
> Explain the purpose of the interrupt vector table
> Enable or disable 8051/52 interrupts
> Program the 8051 /52 tuners using interrupts
> Describe the external hAr~ware interrupts of the 8051/52
> Contrast edge-triggered with level-triggered Interrupts
> Program the 8051 for interrupt-bued serial CODununicati
> Define the Interrupt priority of the 8051 on
> Program 8051/ 52 lntenupts In C
'
SECTION 11.1: 8051 INTERRUPTS palling .,.d inrerruP"' .ind then de-,rn~ the ,·anOlls ~
In tt, I f11.,t w, f ~ - "' 1/w d.Ji ~ r t>ff'ri ~
rupt:1 c,r u.., /!051

l • Interrupts vs. polllng . to do that ,nh.'rTUf'"' or rolling. In the-..


,, I

" "'""
oAAIAmocn.. ontrol~'f c•• ~ .. w-n,I ~1Ct':>
rwpl m.,thuJ whmt"\ff anv df'\n nttds It~ «<TVl(e,
Thttt •tt rwo w•} >
~r.
th<- Je- "-'C nowl< u"' d
"""
•'-- nucrOC'Ontroller b1 sending U an 1n......_
.... .,,
pb whatr\ er ,t ,s doing an !!el"\ es the dl'\K'f n.
••l!l"•I l,;p<>n l'l'<~•"'II an mtt'mlpl .. gnat. tlw mlcron:,nrrol~tlltt (ISR) or mtfl'f'Upt lw11dler. In 11<.'l/lmg, lht ~
rn'KJ'•m ....,wt..'<i with~ mtem,pt i.. c,11<,;11M mt,mipl hen th<! !tatu.• rondit,on IS met, 1t p<'rlonns the ""'lCl
«,nln,114-r (l,ntmuomlv morutor< t/1'!' •Utu• o4 • It"n\d!::f~ " ..._'f'Vlced Although polling can monitor the! ~l.ltu,
Afwr th.\t, 11 '""',., oo tn mOOJt<>r tlwo ""'' elf'\ 1<1' untl • no1 an effioent U!,e of 111!" m,crocontrulltr 11.. 111
. ., d. - -• • h ··' ... _ .. muon rond1tk)f\.• att ml'!. •1"' •••
od,ono..,ge o/ 1nt~rrupl111 th.it the mocroc,,ntr,,lkr c•n Af'f\« rnanv de,ice, (not all at the <am!"
-~,.., t\l('{-.Jnu tcnt ea< "'""'"'
. hme, of COUl'SI'), tJd
Jev,n• con get the altt-nlltm of (h(' m1Ctt1C,,nlrolltt i,a,,rJ "" tlw pnontv ..S.SIKJlt'CI to it The polling m11thod c.,nnot a '"P
pnantv ••~ ,t ~hl'Ckt •II dl"ICN m • round n,t,i,, fa!ohton Mc:tre 1mp;lrtantly, 111 the interrupt method the 11\Jet<l(Or
1r,,11.., c~n 11>0 1gn1>rt' lm.t k) 1 dc-v'.:t' '"l""'' tor,.....,..., Th~ t, •g•m not p(>'<Sible with the polling method Them,
import.ml n.>a~n lh.11 the ,ntff1'Vrt mtth.lJ,. rttft-r•bl~ iiJ 1/wl 11w polling method wastes much of the m1CTOc1>nu..
f ler·, t,me by poll1n11 de\ln th.11 do nnl nt'nl """n <;,, 111 ord..r In ,void tying down the m,crocontroller, mlt'mlf*
•rt> us.>d For f'<'1mple. 1n JL..:uwng trmcn m 0..rttt Y.... uwd tlw 10,,truchcm • JNB TP, target", and waited Wtli
thv timer rolll>J o,er, .u,d wlul,• "<' ,.,.,.. ,.1,ttng ,..,rou!J n,;,c Jo •n} thing tlse That~~ waste of the microcontroll«'•
ume th.it could lw,e br..'11 =-d tu p«rt,...-m .._ u,,rtul la~. In tM cai,e of th<.' timer, ,f we use the interrupt mcthod.
the mkrocontrollrr ,•n go •buu1 dotng other t.ul , anJ whm the TF O..g ~ ra~ the hme r \viii interrupt the mlCI<>
controller in wh.lte, er 11 i:, dn,nit

Interrupt service routine


For eve') 111terrup1 ~ mu,t be an 1n1ttrup1 sen ltt (IS
mvokoo, the m1cro<'ontrOller l'UO$ the mtem.pt ~"'''"' routuw IOUf:llnc! R), or interrupt handler When an inrerrupl •
th.ti holds the addl'l'SS ol its ISR. The group of I or f'\.'er,:
interrupt, there IS a fixed location in mem«y
Interrupt vector I.Ible, shown in Table 11·1 "'ftnOry <>abons 5e1 aside to hold the addresses of !SRs i~ called ttw

J Steps In executing an Interrupt


upon nct1v1t1on of an interrupt, the rrucrocontrou
er goes through the foUowin
I. II fin1fflt'S the tnMruction it is executing
d g steps.
an save, I.he address OI
2. It •I~ ~,es the current status of aU the · t the ne~t tnslructton (PC) th k
'" erntp~ mi...rnau on e stac
3 11 jum~ to• fixed l11C•tJon "' memon cal~ I.he Y <• e., not on the Slack)
nee routme · interrupt veaor bbl
e that holds u,, dd
c a ~ of the mterrupt ltf
.
4 The 11\lc'rorontrolter gru lhe add,... of lhc ISR f
lht' interrupt ~"'let' subroutine unw II rear""" :m the interrupt vecio
mterrupt) last IIISlructJon of t~ table and /Umps to it It stlrts to ext(Ult
s upon e>.l'CUbng the Rm inl.trucnon, I.he subroutine, whJch is RETI (retum frOIII
llt'ts the program counter (l'C) •ddn-.s fro ll\lcrocon1ro11er r,riy
ot tart. io ~ t e from th.it • dd,-. m the lack b)· 0nn.. l'l\s 10 the pi.c._. wh d
• -rytng the tor hv by ere It Was interrupted f'tt,I.
O le$ of the Stack into the pC ~
nt1;-.
--1M1c anr.
~ 0 Nl"Rott
Ell ANO EMBEDDED 5yS'J'PIS
J.
Notice from Step 5 the critical role of the stack. For this reason, we must be carefuJ.tn m ani ulating the
the 15R. SpecificaUy, in the ISR, just as in any CA LL subroutine, the number of pushes an pops m
ust stack contents
be equal
111

SIX interrupts in the 8051


[JI reality, only five .tnterrupts are available to the user in the 8051, but many manufacturers'
t lJ data sheets state tha t
d,tre are six interrupts since they include reset. The six interrupts in the 8051 are allocated as O ows.

I Reset. When the reset pin is activated, the 8051 jumps to address location 0000. This is the power-up reset discussed
in Chapter 4.
2. Two ·interrupts are set aside
· for the timers:
· · o and one for Timer 1· Memory locations OOOBH and
,.._ one for Tuner
OOIBH in the interrupt vector table belong to Timer Oand Timer 1, respectively.

:? 3 Two interrupts are set aside for hardware external hardware interrupts. Pin nurnbersa112. o:3.2) antsd l3 (P3 ·3r)e~er,::
3arc for the external hardware interrupts INTO and INTI, respectively. These extern 1n,errup are a 150

'....r.n.
toas EXl and EX2. Memory locations 0003H and 0013H in the interrupt vector table are assigned to CNTO and INTI,
!nit respectively.
4. Serial communication has a single interrupt tha t belongs to both receive and transmit. The interrupt vector table

....
........ location 0023H belongs to this interrupt.

Notice in Table 11·1 that a limited number of bytes is set aside for each interrupt. For example, a tota l of 8 bytes

-•...... from location 0003 to 0000A is set aside for INTO, external hardware interrupt 0. Similarly, a total of 8 bytes from loca-
tion OOOBH to 0012H is reserved for TFO, Timer Ointerrupt. If the service routine for a given interrupt is s hort enoug h
to fit in the memory space a llocated to it, it is p laced in the vector table; otherwise, an LJMP instru ction is p laced in the
vector table to point to the add ress of the JSR. In that case, the rest of the bytes allocated to that interrupt are u nused. In

..... the next three sections we will see many examples of interrupt programming that clarify these concepts .
From Table 11·1, also notice that only three bytes of ROM space are assigned to the reset pin. They are ROM ad dress
locations 0, 1, and 2. Add ress location 3 belongs to external hardware interrupt 0. For this reasol'\, in our p rogram we put
the LIMP as the first instruction and redirect the processor away from the interrupt vector table, as shown in Figure 11-1.
ht the next section we ,viii see how this works in the context of some examples.
_,/'
Table 11-1: Interrupt Vector Table for the 8051
Interrupt ROM Location <Hex) Pin Flag Clearing
Reset
-External hardware interrupt O(INTO) 0000 9 Auto
0003 P3.2 (12) Auto
Tuner Ointerrupt (TFO) 0008
Auto
5x~mal hardware interrupt 1 (INTI) 0013 P3.3 (13) Auto
:!:°llller 1 interrupt (TF1) 0018
~rial COM interrupt (Rf and TI) Auto
0023
Programmer clears it 0

ORG o ;wake-up ROM r eset location


WMP MAIN ; bypass i nterrupt vector table

...---- the wake-up p rogra m


ORG 30H

.. ..

·l. RNl.irttling the 8051 from the lnlenupt VtttorT•ble •t p


--- owel'-up

~IUlllPTs PROGRAMMING IN ASSEMBLY ANO C


' Enabling and disabling an interrupt
Upon reset all interrupts are disabled (masked}, m
eaning that non
e will be responded to by the rn·
. . IJ •croeontr
in order for the microcontro · er to respond olle,
• bled by software ( kin ) d d' bl ' to 11...
if they are activated. The interrupts must be ena . 'ble for enabling unmas g an ,sa 1ng {ll'lask;n:,"'l
There is a register called 1£ (interrupt enable} that 1s respansi b ·t-addressable register. · -<g1 ~
5
interrupts. Figure 11-2 shows the IE register. Note t~t !E_• a U~ EA (enable all). This must be set to 1 in Ord
From Figure 11·2 notice that bit 07 in the IE register 15 cath 8052 The 04 bit is for the serial interrupt a rfor~

/ rest of the register 10 take effect. D6 is unused. D5 is used by e · ' n SO Olt

./ Steps in enabling an interrupt


l To enable an interrupt, we take the following steps:
Bit 07 of the [E register (EA) must be set to high to allow the rest of register to take effect.
1.
If EA = 1, interrupts are enabled and will be responded to if their corresf'.on~g bits in TE are high. If EA =0 111
2.
; ' mterrupt will be responded to, even if the associated bit in the IE register ,s h1gh. •
/ \.
' To understand this important point look at Example 11-1.
i:,
I 07 00

r ·' EA
EA

IE.7
I En j ES j Er1 I EXJ I ETO

Disables all interrupts. If EA - O, no interrupt is acknowledged.


I EXO f

If EA~ 1, each tnterl'\lpt source IS individually enabled o r disabled


't by setttng or clearing its enable bit.
IE.6 Not Implemented, reserved for future use.•
ET2 IE.5 Enables or disables nuner 2 ovecRow or capture interrupt (8052 only).
ES CE.4 Enables or dlsables the serial port interrupt.
ETI IE.3 Enables or disables Timer I overflow interrupt.
[
EXI IE.2 Enables or disab!es external interrupt I.
ETO IE.I Enables or disables Tuner O 0
lE over ow interrupt
EXO .O Enables or disables extemal . .
·u interrupt o
. ser software should not Writ .
tn future flash microro els to reserve(! bits Th
Figure 11-2. IE Onterrupt En,bl ) R ntroUers to invoke new fe;ture~e bits may be used
e egister ·
,

=;=====~------------------_.,
I/

Eumple 11·1
Show. the instructions to (a)enable the
(b . .

274


I
jll)CLR IE .1 ;mask (disable~ Timer o interrupt only
(c)CLR IE, 7 ;disable all interrupt~ . . . in le-bit instructions as shown
AJ,Other way to perform the "MOV IE, #100101100~ instruction 1s by using s g
J,eloW,
sl'fS IE,? ;BA;l, Global enable
srre 1B.4 ;enable serial interrupt
Sl'l'B IE. l ;enable Timer O interrupt
sJTS IE.2 ;enable EXl

..... Review Questions


1 or the interrupt and polling methods, which one avoids tying down the mkrocontroller?
1. Besides reset, how many interrupts do we have in the 8051? ch e the memory
, In the 8051, what n,emory area is assigned to the interrupt vector table? Can the programmer ang
space assigned to the table?
4. What are the contents of register rE upon reset, and what do these contents mean?
5. Show the instruction to enable the EXO and Tinler Ointerrupts.
6. Which pin of the 8051 is assigned to the external hardware interrupt INTI? .
7. What address in the interrupt vector table is assigned to the INTI and Timer 1 interrupts?

SECTION 11 .2: PROGRAMMING TIMER INTERRUPTS


In Chapter 9 we discussed how to use Tinler Oand Timer 1 with the polling method . In this section we use inter-
rupts to program the 8051 tinlers. Please review Chapter 9 before you study thls section.

Roll-over timer flag and interrupt


In Chapter 9 we stated that the timer flag (TF) is raised when the timer rolls over. In that chapter, we also showed
how to monitorTF with the instruction "JNB TF, target". In polling TF, we have to wait until the TF is ralsed. The
problem with this method is that the microcontrolle.r is tied down while waiting for TF to be raised, and carinot do any
thlng else. Using interrupts solves this problem and avoids tying down the contro!Jer. If the timer interrupt in the [E
lfgister is enabled, whenever the timer rolls over, TF is raised, and the microcontroller ls interr upted in whatever it is
doing. and jumps to the in terrupt vector table to service the !SR. In this way, the microcontroller can do other thlngs
until it is notified that the timer has rolled over. See Figure 11-3 and Example 11-2.
Notice the following points about the program in Example 11-2.

I. ':Ve must avoid using the memory space allocated to the interrupt vector table. Therefore, we p lace all the initializa-
tion codes in memory starting a t 30H. The LIMP instruction is the first instruction that the 8051 executes when it is
powered up. LIMP redirects the controller away from the interrupt vector table.

l. The ISR for Timer Ois located starting a t memory location OOOBH since it is small enough to fit the address s-n
allocated to this interrup t. r ace

TFO Tuner O Interrupt Vector


TFJ Timer I Interrupt Vector
'11 - - 11....._ooo_e_H__J
~g,,,. l)
L'._J 1umps to
GJ jumps to _00_1_BH_ _,
.__l

·3. TF lnt,mapt
.......__
'N°ttRRUPTs PROGRAMMING IN ASSEMBLY ANO C
275
I
E•ample 11-l ' , t rort Oand 'N' ot Po
rt 2and a so g enerates a square wave of 10 ki...
. .,.
. a \/alue of Ya MHz· '
\\lritea program that d1,;p1ays m Pl.Z .XTA L = 22 •
?
with Timer Oin mode 2 at port P

,,/ Solution;
'th a crystal fre
quencY of 22MHz.
llocated to interrupt vector
;Tested for an AT89C51 W • space a
using memory
;··~ upon wake up. go to main,avoid
table
ORG OOOOH t vector cable
Ii ·bypass interrup
'
I
. LJMP MAIN
·
·· · ·ISR for Timer Oto generate squa .
'
re wave
rrupt vector
~ ' ORG OOOBH ·Timer o inte
/\ '
CPL Pl.2
' RETI
··
'
··the main program for initialization c:he interrupt vectors
ORG 0030H ·a location after )
MAIN: MOV TMOD,#02H '
·Timer o. mo e d 2 (auto· reload
MOV TH0,#0B6H ;move count value i~co THO
MOV IE, #82H •·enable interrupt timer 0
SETS TRO ·start Ti01er 0
,, BACK: MOV PO,~'Y' ;display'Y'at port PO

•'
MOV P2,#'N' ;display'N'at port P2
SJMP BACK ;keep doing this until interrupted
•' !;!ND

3. We enabled the Timer Ointerrupt with "MOV IE, #l O0 0001 OB" in MAJN.
4. l"lhile the PO data is brought in and issued to Pl continuously, whenever Timer O is rolled over, the TFO flag is
raised,0.and the microcontroUer gets o ut of the "BACK" loop and goes to OOOOBH to execute the rSR associated with
Timer

5. In the ISR for Timer 0, notice that there is no need for a "CLR TFO" instruction before the RETI instruction. This is
because the 8051 clears the TF flag internally upon jumping to the interrupt vector table.

th T 11-2, the interrupt service routine was short enough that it could be I ed ·
dIn Example foe a·ons allo
cate to_ e .,mer o·mterrup_t. However, that 1s · not always the case. See Exam le I 1-3.p ac 1n memor\/
' a
Notice that the low portion of the pulse is created by the 14 MC (m ch· p d
14 x 1.085 µs = 15.19 µs. 0 me eyeIes) where each MC = 1 .085 µs a~

Example 11-3

Rewrite Example 11-2 to create• square wave that has a hi .


AssumeXTAL=11.0592MHz.UseTimerl. gh portion of 1085 µsand a tow portion of !Sia
Solution:

Smee 1085 Jts is 1000 x 1.085 we ne.!d to use mode I oft·


;··Upon wake-up go to main, avoid usin tmer].
;--allocated to Interrupt Vector Tabl 9 memo,:y space
ORO OOOOH e
LJMP MAIN
;bYPass intert-u
Pt vector table .
276
.JSR for Timer l to generate square wave
ORG OOlBH ;Timer l interrupt vector table
LJMP ISR Tl ; jump to ISR

,-The main program for initialization


ORG 0030H ;after vector table
IN: MOV TMOD,#lOH ;Timer l, model
MOV PO,#OFFH ;make PO an input port
MOV TL1,#0l8H ;TLlalS the Low byte of -1000
MOV THl,#OFCH ;THlaFC the High byte of -1000
MOV IE,#88H ;IE=lOOOlOOO enable Timer lint.
SETB TRl ;start Timer 1
JACK: MOV A,PO ;get data from PO
MOV Pl, A ;issue it to Pl
SJMP BACK ; keep doing it
;
·• · ·Timer l ISR. Must be reloaded since not auto-reload
ISR_Tl: CLR TRl ;stop Timer 1
CLR P2. l ;P2.1=0, start of l ow portion
MOV R2,#4 ; 2 MC
HERS: DJNZ R2,HERE ;4x2 machine cycle(MC) 8 MC
MOV TLl,#lSH ;load Tl Low byte value 2 MC
MOV THl, #OFCH ;load Tl High byte value 2 MC
SETB TRl ;starts Timer 1 l MC
SETB P2.l ;P2.l=l, back to high l MC
RETI ;return to main
END

Ex;unple 11-4

Write a program to generate two square waves - one of 5 KHz frequency at pin Pl.3, and another of frequency
25 kHz at pin P2.3. Assume XTAL= 22 MHz.

8051
PJ .3 1 - - -- ...
_J L
P2.3 1---- ..

Solution:

,Teated for an AT89C51 with a cryatal frequency of 22 MIiz .


ORG OOOOH
;avoid using the interrupt vector table
MOf
LJMp
1
··ISR for Timer o
ORO OOOB
; Interrupt vector for Timer 0
.....___
1
~RUPfS PROGRAMMING IN ASSEMBLY AND C
2'17
I
CPL Pl.3
RETI
for Timer l
·• - -- ISR for Ti mer 1 t vector
ORG OOlBH -InterruP
'
CPL P2 . 3
RETI . tion
·• -- -main program for initial1za . . . alized for Mode 2
ORG OOJOH ·both timers are iru~~d Timer l Interrupts
MAIN: MOV TMOD,#22H • able the Timer o quare wave
MOV IE, #8AH ;en for 5 KHz s
0,#048H ;count value for 25 KHZ square wave
HOV TH t value
HOV TH1,#0B6H ;coun O
.• start Timer
~' SETB TRO
SETB TRl . start Timer
1 · h t . er
the roll off of ei t er im
/\ ;keep waiting for
' WAIT: SJMP WAIT

Example 11-4•
·' Write a program to toggle pin Pl .2 every second.
Solution:
;Tested for an AT89CS1 with a crystal frequency of 22MHz .

To get a large delay of I second, we need to use a register, in addition to a timer.


Here register RO is used along with Timer I to get the large time delay.
,--- e upon wake up.go to main.avoid using memory space allocated to interrupt vector
tabl
ORG OOOOH
LJMP MAIN ;bypass interrupt vector table
; • --!SR
for Timer l to generate square wave
ORG OOlBH
DJ'NZ RO,ST/\RT
CPL Pl. 2
HOV R0,#28 ;toggle pin Pl.2 every
HOV TLl,#OOH ;reload register value second
MCV THl,#OOH ;reload counter value
START: RJ;;TI ;reload counter value
;---the
main program for initialization
ORG 0030H
MAIN: MOV TMOD, lOH
MOV lE, #SSH ;Timer 1, mode 1
HOV RO, #28 ;enable Timer lint
MOV TLl,#OOH •·count f or 1 seco d errupt
MCV THl,#OOH ;count value for ~ldelay
SET1! TIU ;count value for TH1
HERE: SJMP HERE
In the main program, the n1 and THI are inilutJized
monitored in the ISR, because each tune the tim •.but they have to
28 times to get a delay of 1 second. er flag"' S<!t, an interru ~ reloaded in the JSR. The register ROil
Refer Example 9-13 for CAicuiations, for a 1 - ~ a««
P 18 Sllneraled. This 1n-...... hu to
-·-ou delay. - · ""I''

278
ieW Questions .
AeV . ed t both Timer oand Timer 1.
1
eor false. There is only a single interrupt in the interrupt vector table assign°
I, ~;t address in the interrupt vector table is assigned to Timer O?
J. Which bit of IE belongs to the timer interrupt? Show how both are enabl~d. . . bl d Explain how the
3. Assume that Timer 1 is programmed in mode 2, THt = FSH, and the fE b,t for Tuner 1 is ena e · I
4· interrupt for the timer works.
•). rrue or false. The last two instructions of the !SR for Timer Oare:
CLJ! TFO
RETl

SECTION 11 .3: PROGRAMMING EXTERNAL HARDWARE INTERRUPTS


The 8051 has hvo external hardware interrupts. Pin 12 (P3.2} and pin 13 (P3.3) of the 8051, design;ted a~ ~O ~.~
!NT1 are used as external hardware interrupts. Upon activation of these pins, the 8051 gets interrupte in w a ever 1 ~
doing and jumps to the vector table to perform the interrupt service routine. In this section we sh.tdy these two extern
l,ardware interrupts of the 8051 with some examples.

External interrupts INTO and INT1


There are onJy h'IO extemal hardware interrupts in the 8051: INTO and INTl. They are located on pins P3.2 and P3.3
cl port 3, respectively. The interrupt vector table locations 0003H and 0013H are ~t asjde for INTO and ~ l , respecti-
,-dy. As mentioned in Section 11.1, they are enabled and disabled using the IE register. How are they activated? There
I
arelwo types of activation for the extemal hardware interrupts: (1) level triggered, and (2) edge triggered. Let's look at
each one. First, we see how the level-triggered interrupt works.

Level-triggered interrupt
In the level-triggered mode, INTO and INTI pins are normaJJy high (just like all 1/0 port pins) and if a low-level
signal is applied to them, it triggers the interrupt. Then the microcontroller stops whatever it is doing and jumps to
the intmupt vector table to service that interrupt. This is caUed a level-triggered or level-activated interrupt and is the
default mode upon reset of the 8051. The low-level signal at the INT pin must be removed before the execution of the
last instruction of the interrupt service routine, RETI; othenvise, another interrupt will be generated. In other words, if
~ low-level interrupt signal is not removed before the !SR is finished it is interpreted as another interrup t and the 8051
JUlllps to the vector table to execute the JSR again. Look at Example 11-5.

Level-triggered

INTO 0
(Pin 3.2) - - - - ITO 0003
l 't..._--r=;---i JEO
Edge-triggered 1_ (TCON.1)

- ·- ·-·- - ·-·-·-·-·-·-·- ·- - ·-·-·- ·-·- -·-·-·-·-·- - ·- ·-·-·-·-·-·- ·-·-


Level-triggered
INTI or-~~i)c>-~~~~~
(Prn 3.3) - - - - 1... ITl
0013
L-_..r::;-, !El
Edge-triggered l_ (TCON .3)

lig,.,• ll-4. Activation of INTO and lNT1


...__
L'Otaa_UP'TS PROGRAMMING IN ASSEMBLY ANO C
I
,
. tch rs pressed,
the corresponding line goes I°"'
Exilfflple 11·5 . 3 2 and p J.3. Whenasw1
connected to P1115p ·
Two ~witches are . ressed,
Write a program to O if the first swi~ ~~s pressed·
( ) I h t all LEDs connected to port 2' 'f the second swrt
.,/ a ig
(b) light aU LED:. connec
ted to port , 1

Solution: frequency of 22 r,!HZ •


V'
/ . th a crysta1 I
·Tested for an AT89C5 w1 . h• pin for Interrupt .
' 3.2 is the pin for Interrupt 0, and Pin 3.3 IS t
Pin '

' l ·upon wake up.go to rnain table


' ORG OOOOH ;bypass interruPt vector
LJMP MAIN
···················-the ISR tor interrup t INTO for rnterrup t 0
' ORG 0003H ;interrupt vec~~rport o
! LEOl, MOV PO,#OFFH ;turn on LBDs
RO, #255

r
MOV
OJNZ RO,LEOl ;keep the LEDs ON for a Short time
RETI INT l
;---------------- ··-·--·-ISR for
·Interrupt vector f o r
Interrupt 1
LE02 ORG
MOV
0013H
P2,#0FFH
'
;turn on LEDs of port 2
MOV RO, #255
'' DJNZ RO, LED2 ;keep the LEDs ON f or a short time
RETI l' .
'·---------------main p~ogram for initia ization
ORG 0030H
MAIN, MOV IE, #SSH ;enable INTO and INTl
HERE, SJMP HERE
ENO

The LEDs will remain ON if the corresponding switch is kept pressed.

In this program, the microcontroller is looping continuously in the HERE loop. Whenever the switch on INTI (pill
P3.3) is activated, the microcontroller gets out of the loop and jumps to vector location 0013H. The JSR for INTI hJJJlS
on the LED, keeps it on for a while, and tun,s it off before it returTIS. lfby the time it executes the RETI instruction. d1t
INTI
be pin is back
broL1ght st;U low, the microcontroJJer
to high by the time RETIinitiates the interrupt again. Therefore' to end th.is problem' the CNT1 pin must
is executed.

Sampling the low level-triggered interrupt


Pins P3.2 and P3.3 a.re used for normal I/0 unless the INTO and INiJ . . tht
hardware interrupts in the IE register are enabled, the control[ k bas~ the IE registers are enabled. ~gi>ll
once each m~chine cycle. According to ~ne manufacturer's data:~ ~f5 ~phng the INTn pin for a low-l~el SI.;lllll
of the execution or JSR. If the INT11 p,n 1s brought back to a lo . ';'!1 the Ptn must be held in a low state until the
be no interrupt." However, upon activation of the interrupt d gic high before the start of the execution of JSR there wrll
the execution of RETI. Again, according to one manufacturer'u~ to the low level, it must be brought back to high befo«t
RETI inst~ction of the ISR, an~ther interrupt will be activat~ ata 5 hee1,_ "lf the lNT pin is left at a logic low after !lit
fore to eJ1SUlf
~
the activation of the hardware interrupt at the 1NT11 Pin m k after 0 ne Instruction is 11 executed ,, Th
machine cycles, but no more. Th,s is due to the fact that °
th• sure that lhe duration of th
1
J e_re UJ1(l4
be held in a low state untU the start of the ISR execution e evel-tr;ggered intern ·pt . e 1lO w. eve srgnathe pin ust
1 1 310
• ·" rs not atched. Thus 111
1 MC

l'.'oaSµs~ [~~~~ ~4- ma


~ ch~in-e_cy
~ c-Jes~~~~--'~or~:ins
4X l.085µs I

Note: On RESET, !TO (TCON.O) and !Tl (TCON.2) are both low, making
external interrupts lt>vel-triggered.

fig.,.11•5. Minimum Duration of the Low Level-Triggered Interrupt (XTAL = 11.0592 MHz)

edge-triggered interrupts
As stated before, upon reset the 8051 makes INTO and INTI low-level triggered interrupts. To make them_edge-trig·
gered interru~ts, we must pr_ogram the bits of the TCON register. The TCON register holds, among other bi_ts, the ITO
and (Tl Oag bits that determme level- or edge-triggered mode of the hardware interrupts. ITO and JT1 are b!ts DO ~d
D2of the TCON register, respectively. They are a lso referred to as TCON.O and TCON.2 since the TCON register IS bit·
addressable. Upon reset, TCON.O (ITO) and TCON.2 (IT1) are both Os, meaning tha t the external hardware interrupts
oi&\/TO and INTI pins are low-level triggered. By making the TCON.0 and TCON.2 bits high with instructions such as
"SBTB TCON. O'' and "SETB TCON. 2", the external hardware interrupts of INTO and [NTl become edge-triggered. For
example, the instruction "SETB CON. 2" makes INT1 what is called an edge-triggered interrupt, in which, when a high ·
to-low signal is applied to pin P3.3, in this case, the controller will be interrupted and forced to jump to location 0013H
in the vector table to service the ISR (assuming that the interrupt bit is enabled in the LE register).


07 DO
TRl TFO TRO !El m IEO ITO

TFl TCON.7 TI mer J overflow flag. Set by hardware when timer I counter 1
overflows. Oeared by hardware as the p ~ r vectors to
the interrupt service routine.
TRl TCON.6 Ttmer 1 run control bit. Set/ cleared by software to tum
timer/ counter 1 on/off.
TFO TCON.5 Timer Ooverf1ow f1ag. Set by hardware when timer/counter O
overflows. Cleared by hardware as the processor vectors to
the service routine.

ill TRO TCON.4 Timer Orun control bit. Set/ cleared by software to tum
II timer I counter Oon/ off.

" fE I TCON.3 External _interrupt 1 edge flag. Set by CPU when the

" external interrupt edge (H-to-L transition) is detected.


Cleared ~y CPU when the interrupt is processed.
Note: This flag does not latch low-level
triggered interrupts.

.. !Tl TCON.2 Interrupt 1 type control bit. Set/cleared by software to


specify falling edge/low-level triggered external interrupt.
IEO TCON.l ~xtemal interrupt Oedge flag. Set by CPU wh

=,, interrupt (H·t 1.


h .
.. en external
o- transition) edge is detected. Cleared by CPU
~ c':,"1 ,nte~pt is processed. Nott;This flag does no t
ii! at ow- eve! triggered interrupts.
ITO TCON.O Interrupt O ~ control b' Set
f •l / cleared by software to 8 ·1y
alllng edge/low-level triggered e"-maJ I pea
f' MC nterrupt.
'SUrt II~· TCO N (Ttmrr/Counter) Rrgistrr (Bit-addttt9'1blr)
...___
IN'fEJl:R~;;:;-;;~~;;;;;;;:;;;~;;;;~~;;;-;:--~~~~~~~~~~~~~~~~
"' lIPTs PROGRAMMING JN ASSEMBLY AND C
281
I
f the signal applied at INTO pin !P'ir,
Exampl• 11-6 hich is J,alf the frequency o
Generate from all pms ol Port 0, a sq uare \\'ave w
No32).
8051
I
JUl.fL_..., P3.2 PO

Solution:
' . cstal frequency o f 22 MHz .
I' ;Teated for an ATS9CS1 with a ry . 0003) interrupt to be activated.
r I
. cause the INTO (vectored to location
. 3.2 w,11
Every negative edge at Pm
ORG OOOOH
LJMP MAIN
;--!SR for hardware interrupt INTO
ORG 0003H
CPL PO
RETI
ORG 0030H
MAIN, SETB TCON . O ·make INTO an edge-triggered interrupt
MOV IE,#BlH ;enable hardware interrupt INTO
HERE, SJMP HERE
'r SND

Look at Example J 1-6. Notice that the only difference between this program and the program in Example 11·5 isin
the fust line of MAJN where the instruction "SETB TCON. 2" makes INTI an edge-triggered interrupt. When the falling
edge of the signal is applied to pin INTI, the LED will be turned on momentarily. The LED's on-state duration depends
on the time delay inside the !SR for INTI. To turn on the LED again, another high-to-low pulse n1ust be applied to J)l11
3.3. This is the opposite of Example 11·5. In Example 11·5, due to the level-triggered nature of the interrupt, as long as
INTI is kept at a low level, the LED is kept in the on state. But in th.is example, to turn on the LED again, the INTl pulst
must be brought back high and then forced low to create a falling edge to activate the interrupt.

Sampling the edge-triggered interrupt


Before ending this section, we need to answer the
question of how often the edge-triggered interrupt is
sampled. In edge-triggered interrupts, the extemal
source must be held high for at least one machine cycle,
Minimum pulse duration
to detect edge-triggered
tnterrupts. XTALc 11.0592 M.fu l MC
1.085 µs
I 1.085 JIS
L:~=::::=::!:
and then held low for at least one machine cycle to
ensure that the transition is seen by the microcontroUer IMC
The falling edge is latched by the 8051 and is held b th T
latched laUing edge of pins INTO and INTI, respectively. fc~N T~N register. lne TCON. I and TCON.J bits hold tht
as shown m Figure 11-6. They function as interrupt-in-service fl~ d TCON.3 are also called IEO and !El, respecH,·el),
rates to theextemaJ world that the interrupt is being se i g8 · When an interru _. • . . . d · nd•·
to until this service is finished. This is just likl.' the b rv ~ and no new interru P 11:' service ~ag ,s ra,se , 11' ed
1
Regarding the ITOand !TI bits in the TCON ,_. 1 usy s1gna1 you get if all' pt on th.is INTn p,n ,vl]J be n>spond
· -o•s er, the following two . c •ng a telephone number that is in u:,t'.
. 1s
I. The first point . that when the JSRs are finished h . points must be ernphas,zed.
.
and TCON.3) are cleared, indicating that the int (t •hs, upon executJo .
rupt on that pin. For another interrupt to be re:,rru_pt lS finished and th
2
nari in~truction REn), thei,e bits (TCON
1
back low to be considered an cdge-triooerec{
00 ;nt 8ni ed, the Pin lllu t e 51 lS ready to respond to ani)t.her inter·
" ' errup1 s go bad( 1 . hi
282 •
0 1
a ogic high state and be brou~
Tlit 8051 i11J,-.,,
~nOc oNTRQ S
LlER ANO EMB EDDED SYSTEM
E,;olfllple 11-7 . h we cannot use RET ins tead of RETl
1 is the difference between the RET and RETI instructions? Explain w Y
: ~ last instruction of an ISR.
I

5olution: . . into the rogram counter, and maki~g


Both perform the same actions of poppmg off the top two bytes of the s:f. ta! of clearing the interrupt-1n-
the 8051 return to where it left off. However, RETI also ~erforms an a ;;;a
service flag, indicating that the servicing of the interrupt is over and the
1
a
w can accept new interrupt on
~~rvice routine you simply block
th;lt pin. lf you use RET instead of RETl as the last instruction°! the mterru~d 'ndicate that the interrupt is still
y new interrupt on that pin after the first interrupt, since the pm statu~wo d ~ the execution of RETI.
: 1118 serviced. In the cases of TFO, TPl, TCON.1, and TCON.3, they are eare Y

. . . . uted the [NT11 pin is ignored, no matter


, The second point is that while the interrupt service routme •s bemg execfu . ' • f the RETI instruction is to dear
,., · · k h.i h I ~ ·h· ln reality one of the nctions o . .
how many times ,t ma es a g -to- ow "ans, on. . Th.is . i that the service routtne tS no
5
the corresponding bit in the TCON register (TCON.1 o r TCON.3). CO~; or~~~ON in the TCON register are
3
longer in progress and has finished b~ing servked. Fo~ this reason,~ h whe~:ver a fatiing edge is detected at the
called interrupt-,n-servtce flags. The mterrupl·m-serv,ce flag g~s ~ cl ed b RETI the last instruction of the
INT pin, and stays high during the entire e~ecutio~ of the ISR.,!t ,son y ear,, ( ~'C R ~CON . 3" for INTI) before
ISR Becau of this there is no need for an mstruct1on such as CLR TCON · 1 or L . . . th
lhe.RETI i:the lSR,associated with the hardware interrupt INTO. As we will see in the next section, this •snot e
c.1se for the serial interrupt. I

More about the TCON register


Next we look at the TCON register more closely to understand its role in handling interrupts. Figure 11-6 shows
the bits of the TCON register.
II

I ITOand /Tt
Is
II TCON.Oand TCON.2 are referred to as ITO and m , respectively. These two bits set the low-level or edge-triggered
II modes of the external hardware inte.crupts of the INTO and lNT1 pins. They are both O upon reset, .which makes them
low-lel'el triggered. The programmer can make either of them high to make the external hardware interrupt edge-tng-
" se,oo. Jn a given system based on the 8051, once they are set to Oor 1 they will not be altered again since the designer
has fixed the interrupt as either edge- or level-triggered.
IEOand /Et

TCON.1 and TCON.3 are referred to as IEOand IEl, respectively. These bits are used by the8051 to keep track of the
edge-triggered interrupt only. 1n other words, if the ITO and ITJ are 0, meaning that the hardware interrupts are low-
lel'el triggered, LEO and LEJ are not used at all The LEO and [El bits are used by the 8051 only to latch the high-to-low
edge transition on the fNTO and INT1 pins. Upon the edge transition pulse on the INTO (or !NTI) pin, the 8051 marks
[sets high) the fEx bit in the TCON register, jumps to the vector in the interrupt vector table, and starts to execute the
• ISlt.WhiJe it is execu ting the ISR, no H-to-L pulse transition on the INTO (or CNTl) is recognized,, thereby preventing
any111terrupt inside the interrupL Only the execution of the RETI instruction at the end of the !SR will clear the £Ex bit,
~IC'ating that a new H-to-L pulse will activate the interrupt again. From this discussion we can see that the £EO and JEl

• lsareus«1 internally by the 8051 to indicate whethe~ or not an interrupt is in use. In other words, the programmer is
~ concerned with these bits since they are solely for 1ntemal use.
TRoand TRt
I
Ch,~ese are the 04 (TCON.4) and 06 (TCON.6) bits of the TCON register. We were introduced to these bits in
r
• ?l! r 9. They are used to start Or Stop timers Oand 1, respectively. Although we have used syntax such as "SETS
b,~dand "CLR Trx", we could have used instructions such as "SETB TCON. 4" and HCLR TCON. 4 " since TCON is a
..__dressable register.

IN,Ell.~R~U;
PT:S~P=R:OC:='.:R~AM-:-:-:M~
IN~G:-:-:
IN~A:SS=E=M~B=L~Y~A~N~D-C~~~~~~~~~~~~~~~~~283~
I •
were introduced to these bits in
CON register. We Ued over. Although we have~
TFO and TF1 (TCON 7) bits of the T .1the tiJller has ro ch as ,,JNB TCON. 5, target'
Th are the 05 (TCON5) and 07 tively, to indicate ,sed ;nstructions su
,...,__ 1es;
'-'"'Per .
They are used by timers Oand 1, res~ we could have u
t " and "CLR Trx '
the syntax "JNB TFx' targe '. · ddressable.
and "CLR TCON. s" since TCON JS bit·•

external hardware interrupts



R eview Q ues tions t ector table ass,·gned to b oth

v t.
t · the interrup "
True or false. There is a smgle interrup in INTI, How about the pin numv,;:rsi.-
on port ?
3

, •' 2.
3.
ITO and m.
What address in the interrupt vector :~~.:i~:::e
. igned to INfO and
Which bit of IE belongs to the extern I h rdware interrupt E)(1 is ena e
both are enabled.
interrupts? Show h~~ d and is active low. Explain how this inter.
•, 4. Assume that the IE bit for the extema a . red
..•\ s.
rupt works when it is activated. rd e interrupt is low-level tngge · ultiple interrupts?
True or false. Upon reset, the external:• " '.';.'gle interrupt is not recogruzcd as m
6. In Question 5, how do we ~ake 5 ".'e at• 51 ISR for INTO are:
7. True or false. The last two instructions of the
/
CLR TCON . l J• tO
RETI N 2 la in the execution of extema mterrup .
D
(
8. Explain the role that each of the two bits TCON.Oand TCO · P y

~ S EC TIO N 11.4: PROGRAMMING THE SERIAL CO MMUNIC ATION INTERRUPT .


· · O( Ih 8051 All examples in that chapter used the polling
In Chapter 10 we studied the _serial commsedunic,,bonl e n·catlon which allows the 8051 to do many things, in
method. In thls section we explore mterrupt-ba sena comm~ '. ,
addition to sending and receiving data from the serial communication port.

RI a n d Tl flags and interr u pts

As you may recall from Chapter 10, Tl (transfer interrupt) is raised when the last bit of the f~med data, _the stop
bit, is transferred, indic.1ting that the SBUF register is ready to transfer the next byt('. RI ( received interrupt), IS raised
when the entire frame of data, including the stop bit, is received. In other words, when the SBUF register has a byte,
RI is rais«l to indicate that the received byte needs to be picked up before it is lost (overrun) by new incoming serial
~ata. As far as serial ~mmuni~a?on is concem~d, aU the above concepts apply equally when using either polling or aa
interrupt. The only d,ffer_ence 1s ".' how th~ serial cornmun1cat10~1 needs are served. [n the polling method, we wait for
the flag (Tl or RI) _to be raised; w~lle we watt we cannot do anything else. In the interrupt method, we are notified wheii
th__:~l hseasrv
n~sar:e receed.,ved a byte, or JS ready to send the next byte; we can do other things while the serial communication
In the 8051 only one interrupt is set aside for serial cornmunicatio Th' • . ·
1
data. If the interrupt bit in the fE register (IE.4) is enabled, when Rl ;;, i ~ •~terrupt •s used to. both send and recei,·e
to memory address location 0023H to execute the ISR. In that ISR we m 5
0
1
51
••SM
the 8051 gets uiterrupted and 1ump.1
caused the interrupt and respond accordingly. See Example l l-S. l examine the Tl and RI flags to see w hich one

Use of s e rial COM In the 8051

In the vast majonty of applications, the serial interrupt · .


15
ing data serially. ThJs is like receiving a telephone call Used mamty for rec6ving data a.nd. d f send·
where we need a ring to be notified. If we need to mak~ ' IS never use or
a phone call there are other ways to remind ourselves
and so no need /or ringing. In recei\•ing the phone caU
however, we must respond immediately no matter wh '
we are doing or we will miss the call. SimJlarly we at
the serial interrupt to receive incoming data so ihat i~e Serial 111terru t . .
not lost. Look at Example 11-9. 5
p IS IIWoko!d by Tl Or RI 0
F' ag,
•sure ll -7. Singlo lnte
rrupt for Both TI •nd RI

'
(vfo ,(f

/ '
'
pie 11-8
£P"' .
iolheserial COM port to be transferred serially. Assume that XTAL - 11.0592
S:,
· uousl while giving a copy of it
,...\\rite a progran, in which the 8051 reads d~ta from Pl and writes 11 '.'.' P2 con~. the baud rate at 9600.
I

5olution:
ORG 0
LJMP MAIN
Ii - ORG 23H
WMP SERIAL ;jump to serial interrupt ISR
ORG 30H
~}.IN: MOV Pl,11-0FFH ;make Pl an input port
.. MOV
MOV
TMOD, 11-~
THl. #OFDH
;ti mer 1, mode 2(auto-reload)
;9600 baud rate
MOV SCON,#SOH ;8-bit, 1 stop, REN enabled
(t!OV IE, #100100008'1 ;enable serial interrupt
SETB TRI > 11 ,.... ;start time r l
~

BACK: MOV A, Pl ;read data from port 1


MOV SBUF, A ;give a copy to SBUF
...\ MOV P2,A ;send it to P2
\ "'--._SJMP BACK ;stay in loop indefinitely

·-
•··••· ---· --- - - - - - • - -Serial Port ISR
ORG lOOH '
I
• SERIAL: JB
MOV
CLR RI
-
TI, TRANS
A,S~UF
;jump if TI is high
;otherwise due to receive
;clear RI since CPU does not
RETI ireturn from ISR
TRANS: CLR TI ;clear TI since CPU does not
RETI ;return from ISR
p

I,
END

•• In the above program notice the role of TI and RI. The moment a byte is written into SBUF it is framed and trans-
ferred t.eriaUy. As a result, when the last bit (stop bit) is transferred the Tl is raised, which causes the serial inter-
rupt to be invoked since the corresponding bit in the IE register is high. In the serial lSR, we check for both Tl and
'
I
RI stnee both could have invoked the interrupt. In other words, there is only one interrupt for both transmit and
~eive.

r

' Eumplell-9

Write a program in which 10 bytes of data stored in RAM locations starting from "5ff are transferred serially At
die end of data transfer, the value of RO (i.e., 0) is displayed on Pl. ·
• Solution:
ORO OOOOH
WMP MAIN
ORG 0023H ;jump to ISR for serial traJU1nliasion
WMP SERIAL
ORG OOlOH
IIAIN:
MOV TNOD,1208 ;timer l in mode 2

--
IN')-Ell;R~U~PT;; S-;;R
P:OC;:;: l AM::::MJ::::N:G
~l;:N;-A:;.;S;:S;:EM;: :B: L:Y:-:A: N::D-:C- -- - - - - - - - - - - - - -- -
I
THl,#·6
•set baud race REN enabled
• bit 1 scop, pt enable
sCON,ijSOH
( HOV
MOV ,·8 • re. l·nterru
IE,lr90H
MOV ·serial po
SSTB TRl
'.scart timer 1 m1>er of bytes
MOV RO,ijlO
•. counter for nu • cer to ft~".•
,.,..
• 01n
MOV Rl,#4SH . Rl is the p ~•" to A SBUF
BACK: MOV A.•Rl '.. mov e data fromnsnucte
""':' d is loaded into
HOV SBUF,A ;data to ~e t:~l data is sent
DJNZ RO.BACK ;repeat t1ll
HERE: SJMP HERE
·------------serial
• port !SR it implies reception
SERIAL: JNB TI,RECE ·if Tl is not high, f RO into A
. h move value o
'·if TI is h1g'
•, MOV A,RO •
MOV Pl,A ;transfer it to Pl . .
,I'..
CLR TI ;clear TI for next transmiss1on
''
~ RETI
·if reception, move received data
to SBOF
REC£: MOV A,SBUF
next reception
I CLR RI •'.clear RI to enable
RETI
n
(
ENO

'
't Clearing RI and Tl before the RETI Instruction Table 11-2: Interrupt Flag Bits for the 8051/52
Notice in Example 11-9 that the last instruction before Interrupt Flag SFR Register Bit
the RETI is the clearing of the RJ or Tl Rags. This is neces- -E-xt_e_m_a.,_I_O_ ___IE
_O
....:;.._ __ _ T_C_O
_ N_.l=--- - - -
sary since there is only one interrupt for both receive and
transmit, and the 8051 does not know who generated it; External 1 TEl TCON.3
therefore, ii is the job of the ISR to clear the Rag. Contrast -Ti-,m-e_r_O_____T_F_O_____T_C_O_N-.5-----
this with the external and timer interrupts where it is the
job of the 8051 to clear the interrupt flags. By contrast, in :Ti_1111_e_,_1_ _ _ _...;TF_;1_ _ _ __:TC.::.:O:..:.N:.;..7:.__ _ __
serial communication the RI (or Tl) must be cleared by Serial port
the programmer using software instructions such as "CLR ::---':-----Tl _____.:SC:.=.:O::N:..:.:.:.1:..._ _ __
TI" and "Ci:.R RI" in the ISR. See Example 11-10. Notice T1mer 2 TF2 T2CON.7 (AT89C52)
that followed
flag, the last two instructions of the JSR are clearing the
by Ref!. :;:Ti;:,m::'.e::,:-.:2;-----:E::-XF2=:::---....:T2~C::.:O:'.:N'..:'.:.'...()..'.A::T8'...'.'~2:!
.'.9C5 ):..
6
Before finishing this section notice the list of all interru t R · .
four of the interrupt Rags, in the 8051 the SCON re<>ister hap th agRJs given Table 11-2. While the TCON register holds
10
o· s e and n Rags.

Ex•mple 11·10

This example is to show that many jobs can be atte ded .


used here the serial interrupt timer ointerru t n to sunuJtaneousJy usin .
baud rate for serial communk~tions. P • and the external interrupt ~ tnterrup~. Three interrupts ue
Write a program to 1 · Timer 1 IS used to generate lht
(1) generate a S<juare wave at PJ.2 using timer .
O
(2) take data from port P2 and send it serially an~n mode I, interrupt lllod
(3) when wro is activated, port PO is ma<1e f continuously e
will ·'··- · ff 'f th O or a •hort "-
"""' remam O I e Switch connected to lNTo :une, to SWitch off
Ptn (f>3.2) is kl"'t the l£Ds c<>nnected lo IL The LEDi
.,.. Pre11Cid.

'
-
8051
Pl.2
Data P2 LEDs
PO I
L - - - -+ oata
P3.2

5-0Jution:
ORO OOOOH
WMP MAIN
....... ---·········· ---- -Timer O !SR

ORO OOOBH ;lSR for Timer 0
CPL Pl.2 ;toggle pin Pl.2
MOV THO, #OOH ; Timer is in model so reload count values
MOV TLO,#OFOH ;reload count value
RETI
•....... - - • • ·· - • • • - · - - - - - - - - -INT o interrupt vector
ORO 0003H ; ISR for INT 0
SJMP LED
···-· ·····-- -------serial port interrupt vector
'
ORG 0023H ;ISR for serial inte rrupt •
LJMP SERIAL
t ;········ -··-- ----- ---- main program for initialization
- ORO 0030H
- MAIN: MOV P2, #OFFH
MOV TMOD,#21H
;make P2 an input port
;Timer o in mode 1, Timer l in mode 2
MOV THl,#-6 ;select baud rate
- MOV THO, #OOH
MOV TLO,#O FOH
;load count values for Timer O
;load count values for Timer O
MOV SCON,#SOH ;8 bit, 1 stop,REN enabled
- MOV IE,#93H ;enable Timer O, serial and EXO interrupts
- SETB TRl ;start Timer l
- a.>.cK:
SETB TRO
MOV A, P2
;start Timer O
;move data in P2 to A
- MOV SBUF,A
SJM P Bl\.CK
;move A to SBUP for transmission
;continue
I
----serial port ISR
SERIAL: JNB TI,RECE ;if TI is not high, jump
CLR TI ;if TI•l, implying transmission, clear TI
RETI
MOV A,SBUF ;since reception is seen, move r e ceive d
;dat a to A
CLR RI ;clear RI
RET!
: "'· · - - .. - .. - - ... - _ - .. - - • - ... - - - - ... - - - • ISR f or INTO
:.t:D: MOV PO,#OOH ;move Oto PO to switch off LBDa
MOV RO,#OFFH
DJNZ RO.HERB ;for de lay
MOV PO,IOPFH ;light up LBDa again
RETI
ENO

--
~iER.ll;;;uPT;;;;s~r:R;OC
::::R~A:MM:::::lN:C:-::IN; A:S:S~EM:::B:L~Y~AN::::D:-::C:--=----=-=---,=-=-=-=-~=-=-~=-=-=-~
287
I · . d to t,oth the TI and RJ interrupts
Review Questions ·ector table ass1grie
· the interTUP1 ' • 1• tcrrupt?
1. True or false. There is a single interrur~: is assigned 10 the sennhlJ\W O
it is enabled.
2. \\'hat address in the mterrupt \'ector a • interrupt? 5hoW h.15 interrUPt gets activated and also exp~
1
. \\'luch bit of the IE register belongs to the sen ~ enabled, Explain hoW I
3 1 15
4 Assume thal the IE bit for the serial interrup
,ts actions upan activation. . . and ready to So·
15
5_ True or false. Upan reset, the serial interrupt ac~veth receive interrupt are:
6. True or false. The last two instnJdion5 of the !SR or e
CLR RI
RBTI
\.
7. Answer Qu!'Stion 6 for the send interrupt.

,.
• SECTION 11 .5: INTERRUPT PRIORITY IN THE 8051/52 .
·r ·nterrupts
1
are activated at the same time? Which or
The next topic that we must deal with is what happc_ris '. two • 1 • of discussion in this section.
these two interrupts is responded to first' lnterropt pnonty 15 the m,1an opic

,I

Interrupt priority upon reset


\\'hen the 8051 is pawered up, the pnonlics are assigned according to Table 11·3. From Table 11-3 we see, for exam.
pie, that ii external hardware Interrupts Onnd I are activated at the same bme, external interru p t O(INTO) is responded
to fusL Only alter INTO has been sen-lCl'<I is INTI set\ iced, ~11\CC INTI h.lS the lower pnority. In reality, the prionty
scheme m the 1able Is nolhmg but an inl~mal polling sequence in which lhe 8051 polls the inte rrupts in the sequence
,
• listed in Table 11-3, and responds acrord,ngly.

Setting interrupt priority with the IP Table 11-3: 8051/52 lnterrupt Priority Upon Reset
register
Highest to Lowest Priority
\Ve can alter the 5"<juence of Table 11-3 by assign-
ing a hlgher priority to any one ol th e intcrruplS This External Interrupt O (INTO)
IS d~ by programming a register called IP (interrupt Timer Interrupt O (TFO)
pnonty) Figure 11-8 shows the bill! of the IP register.
Upon power-up reset, the IP register contains all Os External Interrupt J (INl1)
malting the pnority M"qucnce based on Table 11-3 T' Timer Interrupt J (fFl)
give a higher priority lo any ol the interrupts, we,,;.,~
the rom,spondmg b,t m the IP register high. Look al Senal Commurucation (RI+ Tl)
Example 11 -12. ' TI mer 2 (8052 only)

Enmple 11·11
CM<:u.,_, what h.lppen, ,f interrupts INTO, TfO
,..,,., "-'I b, the pc)"tt-up , - . i ..nd that the . and INTI arc achvateJ
Solution:
c-iemal hardw . at th;, "'1mc 1·
are mlcrrupt, arc l~ge-trii;~ume priority 1ev•
II the..- thn.'t! interrupts are act,vated at the
all fl\ e mtrnupb a(Cordmg to the wme lime, they are la
Theref,•re, when the abov<' thrtt i n ~ ~ hsled in Table I I 3lched and kt-pt in
(TFI)), and finally IEI (exmnal mtmupt~~ are acttvate,1. fEo ( - . If •n) L• ol<.'tiva:nally. lnen tlw 8051 ,che(b
extemat tntl"n'U • tt lll'n<tc-t'S ,t In ~
pt O) is &ervQCI first. then n.,t

288
THEsos1 ~CR
0CONTRo -
LlER ANO EMBEDDED 5ySTOIS
D7 DO

PX1 PTO PXO


PT2 PS PTl

Priority b it = 1 assigns high priority. Priority b it = O assigns low priority. t

IP.7 Reserved
lP.6 Reserved
PT2 CP.S Time r 2 interrupt prio rity b it (8052 o nly)
PS IP.4 Serial port interrupt priority bit
PTt IP.3 Timer l interrupt prio rity b it
PXt CP.2 External interrup t 1 priority bit
PTO lP.1 Timer Ointerrupt priority bit
PXO CP.O Exte rnal interrupt O priority bit

User software should never write ts to unimplemented bilS, since they may be used in
future products.

fig,," 11-8. tnterrupt Priority Register (Bit-addressable)

..
d
., tumple 11·12
'
• (•)Program the IP register to assign the highest priority to INTI (external interrupt 1), then (b) discuss what hap-
pens if INTO, lNTl, and Tl'O are activated at the same time. Assume that the interrupts arc both edge-triggered.

Solution:

--
t (a)MOV IP, # OO OOOlOOB;IP.2=1 to assign INTl higher priorityTheinstruction ·SETS IP.2" also
will do the same thing as the above li.1\e sillce IP is bit-addressable.
lb) The instruction in Step (a) assigned a higher priority to ll\'Tl than the others; therefore, when INTO, INTI, 3.1\d
TFOinterrupts are activated at the same time, the 8051 services INTJ first, then it services INTO, then TFO. Th.is
is due to the fact that INTI has a higher priority than the other hvo because of the instruction in Step (a). The

instruction in Step (a) makes both the INTO and TFO bits in the IP register 0. As a result, the sequence in Table
• 11-3 is followed, which gives a higher priority to LNTO over TFO .

I

• Ex•mple 11-13

A.sume that after reset. the interrupt pnority is set by the instruction "MOV IP, #000011oos•. Discuss the
sequence rn wluch the interrupts are serviced.
Solution:

1he i~truction "MOV IP, #000011008" (Bis for binary) sets the external interrupt J (INT]) and Timer 1 (TFI)
~ • higher priority level compared with the rest of the interrupts. However, since they are polled according to
able 11-3, they will have the following priority.

fltghest Priority External Interrupt 1 (lNTJ)


Timer lntenupt I (TFJ)
External Interrupt 0 (lNTO)
Timer lntenupt O {TFO)
SeriAl Comm unication (RI + Tl)
......._
-;:;:;::::-:=::::=:::-::~==:::--::::-:----------'--------
l~"ftlllluPTs PROGRAMMING lN ASSEMBLY AND C
I .
or more interrupt bits in the JP re .
pt priority when two thers they are serviced according~~
cl rified is the ,nterru riority than o , ,,.
Another point that needs to be a . ts have a higher P
are set to high. In this case, while these mterrup
sequence of Table 11-3. See Example !1-I3.

Interrupt Inside an Interrupt . interrupt and another_intedrrupt_is/ctiva tedln? lnslldi


. - . . !SR belonging to an . . n interrupt u,s1 e an m errup. 1 lhe8Qs1
What happens 1f the 8051 1s ex~ting an _ riority interrupt. This 15 : t not by another low-priority interru l
a low-pnonty interrupt can be interrupt
:y10
cases, a ~g~-p~ority interrupt c~ interru::; ~\!gher-priority inte_r~P1•. ~rrupt can get the immediate attention~
. lly no low-pnonty 1.11
Although all the interrupts are latched and kept m'.emha .~rity interrupts,
the CPU until the 8051 has finished servicing the hig -pn

, I Triggering the interrupt by software . . Thi can be done with sin1ple instructions to set

., s table. For exampIe, if the IE b'it for Timer
~-

'I'
There are times when we need to test an !SR bY wa Y of slOluJahon.

1 is set, an instruction such as "SETB Tf'l " will interrupt


.

th: {
t ector
the interrupts high and thereby cause the 8051 !o j_ump to the in:;u~ :hatever it is doing and force it to jump to the
interrupt vector table. In other words, we do not need to wait or IOler 1
to roU over to have an in terrupt. We can cause
" an interrupt with an instruction that raises the interrupt flag.

Review Questions
I. True or false. Upon reset, all interrupts have the same priori~. . . ?
2. What register keeps track of interrupt priority in the 8051? ls ,ta b1t-add_ressable re~ster - . .
·' 3. Which bit of fP belongs lo the serial interrupt priority? Show how to ass1g,, 1t the highest pnonty.
4. Assume that the IP register contaiJ1s aU Os. Explain what happens if both INTO and INT1 are activated at the same
• time .
r 5. Explain what happens if a higher-priority interrupt is activated while the 8051 is serving a lower-priority interrupt
(that is, executing a lower-priority ISR).

SECTION 11 .6: INTERRUPT PROGRAMMING IN C

~~~~~ :...:~:::: ~~ :!
• So~ all the pro~rams in this chapter have been written in Assembly. In this section we show how to program the
1
J.~"i:rage. In reading this section, it is assumed that you already know the material in

8051 C interrupt numbers


The 8051 C compilers have extensive support for the 8051 ·
. . interrupts with two major features as follows·
I. They ass,gn a uruque number to each of the 8051 . t .
2. It can also assign a register bank to an ISR Thi tn ~rrupts, as shown in Table 11-4.
registers. · s avoids code overhead due to the P h d R7
us es an pops of the RO-
Example 11-14 shows how a simple interrupt . . .
ts wntten m 8051 c.

Table 11-4: 8051152 lnterrupt Numbe .


Interrupt rs in C
Name
External Interrupt o
(INtO) Numbets used by 8051 C
Tuner Interrupt o
CTFO) 0
External Interrupt 1
(INTJ) 1
Timer Interrupt J
(TFl) 2
Serial Communication
Timer 2 (8052 only) (ru + Tl) 3
CTF2) 4
290 s
_,,..
ple11-14 ly
EX&lll ends it to Pt.0, while simultaneous
- . ·tea c program that continuously gets a single bit of data from Pl.7 and 5 e wave. Assume that XTAL=
:ting a square wave of 200 µs period on pin P2.5. Use timer Oto create the squar
!l,o592 MHz. I

=
Pl
5oJution:
We will use timer Oin mode 2 (auto-reload). One half of the period is 100 µs .
._ t00/ 1. 085 µs = 92, and THO = 256- 92 = 164 or A4H
dnclude <regs1. h>
sbit SW = Pl• 7;
sbit IND • p1•0;
sbit WAVE = p2•5;
void timerO (void) interrupt 1
{
WAVE = -WAVE; //toggle pin
l
void main()
!
SW = 1; //make switch input
TMOO = Ox02;


I THO • Ox.A4; //THO• -92
IE= Ox82; //enable interrupts for timer O
I while(l)
pl {
I IND= SW; //send switch to LED
l
l
Ill ll)) JI$ I 2 = 100 µs
In 100 JI$ / l.085 µs = 92
8051

PI.O LED

SWITCH--1 Pl.7
I
.

l ....._~~~~~~~~~~~~~~~~~~~~~~~~-J

~mple t t-15

IVnte a C program that continuously gets a single bit of data from Pl.7 and sends It to Pl.0 in the main, while
snnultaneously (a) ctffling a square wave of 200 µs period on pin P2.5, and (b) 9ending letter' A' to the serial port.
Use Timer o to create the square wave. Assume that XTAL = 11.0592 MHz. Use the 9600 baud rate.
Solution:
IVe Will use T'lllleJ' oIn mode 2 (auto-relmd). THO • 100/1.085 µa .. -92, which la A4H
l lnclude <regS1 .h>

......._
~"fl':RR~U~PT-S--PR_O_G_llAMM
_____IN
__
G_I_N_AS
__S_E_
MB__
L_Y_AN
__D_C__________________________________29
__1
I
sbit SW • Pl·?~
abit IND• Pl ... :
sbit WAVE• P2 S;
void timerO!void) interrupt 1

!AVE. - WAVE; //toggle pin


l
void serialO(J int errupt 4
\. {
~
if (TI == 1)
{
l . I
SBUF • 'A, ; //send A t o serial port
., TI• O; //clear interrupt
/, l
' e lse
'
~ {
RI = 0; //clear inter rupt
( l

l
[~
·'
void main()
{
SW= l ;
THl = -3;
//make s witch input
//9600 baud .
TMOD = Ox22 I //mode 2 for both timers
I THO = OxA4 ; ;;.92 •A4H for timer O
'' SCON = OxS O;
TRO • l;
TRl = l; //start timer
IE= Ox92; //enable i nterrupt for TO
while (ll //sta y her e
/
IND= SW; //send s witch to LED
J
l

Example 11-16

Write a C program using interrupts to do the following:


(a) Receive dat;, serially and send it to PO,
(b) Read port Pl, transmi t data serially, and give a cop y to P:2,
(c} Make timer Ogenerate• square wave of 5 kHz freque ncy on PO, 1.
Assume thatXTAL ; 11.0592 MHz. Set the baud rate at 4800.
Solution:
#include <regSl . h>J
sbit WAVE • PO"l;
void t i merO (J interrupt 1
/
WAVE • -WAVE;
J //toggle Pin

.
292
'd ser i alO () interrupt 4

'
·.? l
(
if (TI S 5 l)
{
I
Tl = 0 ; //clear interrupt
)
el se
(
PO• SBOF; //put value on pins
RI = 0; / /clear interrupt
}
l
void main ()
{
unsig ned char x;
Pl = Oxf'F; //make Pl an input
TMOD = Ox22;
THl = OxF6; //4800 baud rate
SCON = OxSO;
THO = OxA4; //5 kHz has T = 200 µ s
IB = Ox92: //enable interrupts
TRl = 1 ; //start timer l
TRO • 1; //start timer 0
while (l )
{
X = Pl; //read value from pins
SBUF = X; //put value in buffer
P2 e X; //write value to pins
J

mmple 11-17
Wnte a C program using interrupts to do the following:
(a) Generate a 10000 Hz frequency on P2.l using TO 8-bit auto-reload,
(b) Use timer 1 as an event counter to count up a 1-Hz pulse and display it on PO. The pulse is coMected to EXl.

Assume that XTAL = 11.0592 MHz. Set the baud rate at 9600.
Solution:
h nclude <reg 51. h>
8bi t W/\VE = P2.l;
'"1signed char cnt;
V .
Old timero () interrupt l
I
) II/\VE • ~WAVE; I /toggle pin
•old tinier1 () interrupt 3
I
<:nt++; //incr911ent counter
I
PO • enc,
I
void ea1nll co zero
{ //set counter
cnt. • O:
TMOD • OX42;
-mo• ox .. 46; //1000°
//enable inte
H7 rrupt•
11. ox96;
TRO • l; / /start ti111er
·mer
0
1
//start ti . terrupted
TRl • 1; //wait until in
while(l);

1 •'
l
•• I / 10000 HJ : 100 µs
( '
' 100 µs / 2 • 50 )JS
50 µs I l.085 µs • 46
, 8051

fi' PO 1 - - - - LEDt
(

t
Pl.I
10000 Hz

SUMMARY
An lnterrupt is an external or internal event that interrupt;, the microcontroller to inform it that a device _needs
its service. Every 1ntenupt has a program associated with it called the !SR, or interrupt service routine. The 8051 N>
6 interrupts, 5 of which are user-accessible. The interrupts are for reset, two for the timers, two for external hardwaie
inti,rrupts, and a serial communication interrupt. The 8052 has an additional interrupt for Timer 2.
The 8051 can be programmed to enable or disable an interrupt, and the interrupt priority can be altered. This chap-
ter showed how to program 8051 / 52 interrupts in both Assembly and C languages.

PROBLEMS
SECCTON 11.1:8051 INTERRUPTS
1 What ,s the advantage of interrupt-bas..'(! dat.1 transfer?
2. Why is reset considered as an mterrupt as well?
3. What is meant by the term !SR?
4. What is meant by the term interrupt vector?
5. What memory address in the interrupt Vector tab!~ is •~s· cd
6. What memory address in the mterrupt vector table is ass~gn to INT()?
7 What memory address in the interrupt vector table is ~gncd to INTI?
8 Wh.lt memory address 1n the interrupt vector table is assigned to Timer O?
9. What memory address in the interrupt vector table is ::sncd to Timer 1?
10. Why do we put an I.JMP instruction at •ddreos 0, sned to the senat COM .
· interrupt?
294
THE 8051 MICJtOC -
ONTROLLl!Jl AND EMBEDDED~
vii ta.re the contents of the l£ register upon reset, and what do these values mean?
11· ~~' the ~nstruction to enable the EX_l and Timer 1 interrupts.
Jl. si, 1, the instruction to enable every interrupt of the 8051.
f3. \~ch pin of the 8051 is assigned to the external hardware interrupts _lNTO and INT~O d INTI interrupts?
J4. Ho'' many bytes of address space in the interrupt vector table are assigned to the .
P. }loW many bytes of address space in the interrupt vector table are assigned to the
a;ii:;,
Timer
d T "mer interrupts?
1 1 bytes in
'I
16
· To put the entire interrupt service routine in the interrupt vector table, it must be no more an
11.
sjze.
8 When an interrupt is activated, what is the first step taken by the 8051?
\ With a single instruction, show how to disable all the interrupts.
~ With a single instruction, show how to disable the EXl interrupt.
ll. What does the 8051 do on encountering the RETI instruction? .
22. &, the 8051, how many bytes of ROM space are assigned to the reset interrupt, and why·1

SECTION 11.2: PROGRAMMING TIMER INTERRUPTS


23. True or false. For both Timer Oand Timer l, there is an interrupt assigned to it in the interrupt vector table.
,t What address in the interrupt vector table is assigned to Timer l?
25. Which bits of the IE register are allocated for the timers?
26. What is the effect of clearing the EA bit of the IE register? .
v. Assume that Timer Ois programmed in mode 2, THl = FOH, and the IE bit for Timer Ois enabled. Explau, how the
interrupt for the timer works.
28. Can the 8051 generate two square waves simultaneous ly? . . .
29. Assume that Timer 1 is programmed for mode 1, THO = FFH, TLl = P8H, and the IE bit for Timer 1 1s enabled .
Explain how the interrupt is activated. . . .
30. UTimer tis programmed for interrupts in mode 2, explain when the mterrupt 1s activated.
31. Write a program to create a square wave of T = 160 ms on pin P2.2 while at the same time the 8051 is sending out
SSH and AAH to Pl continuously.
32. Write a program in which every 2 seconds, the LED connected to P2.7 is turned on and off four times, while at the
same time the 8051 is getting data from Pl and sending it to PO continuously. Make sure the on and off states a.re
50 ms in duration.

- SECTION 11.3: PROGRAMMING EXTERNAL HARDWARE INTERRUPTS


33. How many hardware interrupts has the 8051? How are they activated?
....
fl ll. IVhat address in the interrupt vector table is assigned to INTO and INTI? How about the pin numbers on port 3?
.l5. Which bits of the IE register are used to set/reset the external hardware interrupts?

,. 36. Write a program to transfer a data FFH through port 1 when EXO is enabled and to transfer OOH ii EXl is enabled?
"!I. Show how to enable both external hardware interrupts.
38. Assume that the IE bit for external hardware interrupt EXO is enabled and is low-level triggered. Explain how this
mterrupt works when it is activated. How can we make sure that a single interrupt is not interpreted as multiple
interrupts?
39. True or false. Upon reset, the external hardware interrupt is edge-triggered.
tti In Question 39, how do we make sure that a single interrupt is not recognized as multiple interrupts?
Which bits of TCON belong to EXO?
1
43. \/hich bits of TCON belong to EXl?
11 What _should be the minimum time peri~ of the high:to-low pulse used for an edge-triggered interrupt?
15· Explain the role of TCON.O and TCON.2 tn the execution of external interrupt o.
16· Explain the role of TCON.1 and TCON.3 in the execution of external interrupt 1.
· :'\Ssume that the IE bit for external hardware interrupt EXJ is enabled and is edge-triggered. Explain h th"
tnlerrut ks h . . . td H k OW IS
. P wor w en 11 IS activa e · ow can we ma e sure that a single interrupt is not interpreted as rn lti
l7 tnterrupts? u p 1e
· ~nte a program using interrupts to get data from Pl and send it to P2 while Timer o is generatin·g a sq
18 u, 3 kHz. uare wave
· ~ected
a Program using interrupts to get data from P1 and send it to P2 while Tim~r 1 is turning on and off th LEO
to P0.4 every second. e
:---__
'IJPTs PROCRAMMINC IN ASSEMBLY AND C
I . h-to-JOW tran5
,rhen a hig
ition is received on INTO.

W ·tea program to generate a rising edgets? once, '


49. n od disable au interrup . ered?
50 What is the meth to
1
or edge-tngg JNTl?
51 · Which interrupts are latched, lo"'.·1eve t for INTO and
si Which register keeps the latched mterrup .~rrrRRUPT
MMlJNICAnoN u" • ,.
G THE SERIAL CO
SEcnON 11.4: PROGRAMMIN 1
Ho,v many bytes are assigned to it?
53 How many serial interrupts has e th 805J?·. igned to the sen ·a1 interrupt.
·t is enabled.
Z
54: What address in the interrupt vector table 15 interrupt? Sho~ how~ interrupt gets activated and also expJ4in
55. Which bit of the JE register belon.gs to the set is enabled. Explall\ how
56. Assume that the rE bit for the senal tnterrup . till enabled.
· tion.
its working upon activa · ter the sena. . terrupt1ss .
. 1in
57. True or False? On making EA= 0 ~f the IE rer;.R f~r the receive interrupt are.
1 • ' 58. True or false. The last two instructtons of the
CLR TI
,I,
' 59. RBTI
Answer Question 58 for the receive
. tnterrup.
· t. . . d' w ha t happens subsequently?
bled when TI •is raise
60. Assuming that the interrupt bit in th~ IE reg15ter is .en~ ' . . . .
61. u RI is kept enabled, can data be received on Rx~ lin:;,d send it to P2 while at the same time Tuner O1s generating
62. Write a program using interrupts to get data senaJJy

63. aWrite
square 5 kHz.interrupts to get data sen.Uy
wave of using
a program . and send 1' t to P2 ,vhile Timer O is turning the LED connected
to PJ.6 on and off every second.

SECTION 11.5: INTERRlJPT PRlORllY IN THE 8051/52


64. Which is the highest priority interrupt of 8051_7 . . ..
65. Whlch register caters to the function of chan~g ~terrupt pnonties.1 . . . . .
66. Which bit of IP belongs to the EX2 interrupt pnonty? Show how to assign ~t th.e h1gh~t prion~..
67. Whlch bit of IP belongs to the Timer 1 interrupt priority? Show how to assign ,t the highest pr1onty.
68. True or False? Interrupts can be enabled by software.
69. Assume that the IP register has all Os. Explain what happens if both INTO and lNT1 are activated at the same
time.

70. Assume that the IP register has all Os. Explain what happens if both TFO and TFl are activated at the same lime.
71. If both TFO and TFI in the IP are set to high, what happens if both are activated at the same time?
72. U both INTO and INTI in the lP are set to high, what happens if both are activated at the same time?
73. Explain what happens if a low-priority interrupt is activated while the 8051 is serving a higher-priority interrupl

ANSWERS TO REVIEW QUESTIONS l


SECTION II.I: 805\ INTERRlJPTS )
t
I. Interrupts
2. 5
3.
4. Address locations 0000 to 25H. No. They are set when th .
5. All Os means that aU interrupts a.re masked and as a ~ processor IS designed.
6. Mov IE'. #1_00~0011e • ' resu t no interrupts will be responded to by the 8051. .l
P3.3, which 1s pm 13 on the 40-pm DlP package
7. 0013H for lNTJ. and 0018H for Timer 1

SECTION 11.2: PROCRAM,\,flNG TIMER INTERRUJ>:rs


I. False. There is an interrupt for each of the time r·
2. OOOBH o
· rs, uner and r·
3. Bits DI and 03 and ·Mov IE, #10001010 • will IO\er 1.
8
4. After Tlll1er I is started with instruction "SETe enable both of the ti .
the 8051 is executing other tasks. Upon rolling TRl·, the timer Will mer llltetrupts.
over from f.,,_, coUnt up fr L"•
· .,., to 00, the 1'F1 0 m FSH to FFH on its own wrw<
.
0
296 ag IS raised, Which will interrupt tl,t,
THE 8051 MIC,tnr.
~--0 NT1tOLL
ER AND EMBEDDED 5ySTEMS
. whatever it is doing and force it to jump to memory location 001 BH to execute the JSR belonging to this
so,1 il1
illierru,l;'.~re is no need for "CLR TFo• since the RETI instruction does that for us.
.) f~·
;fCf!ON 11.3: P_ROG~G EXTERNAL HARDWARE INTERRUPTS I

alst· There IS an interrupt for each of the external hardware interrupts of INTO and INTl.
i ~rl and 0013H. The piras numbered 12 (P3.2) and 13 (P3.3) on the DIP package. .
• Bits [)Oand 02 and "MOV IE, #lOOOOlOlB" will enable both of the external hardware mt~rupts. . . d in
> upcn application of a low pulse (4 machine cycles wide) to pin P3.3, the 8051 is interrupted m whatever 1t IS o g
l ;nd ;u01ps to ROM location 0013H to execute the ISR.

> !:e sure that the low pulse applied to pin {NTJ is no wider than 4 machine cycles. Or, make sure that the fNTl
• ~ill is brou~t back to high by the time the 8051 executes the RETI instruction in the !SR.
• false. There IS no need for the "CLR TCON. o• since the RETl mstructJon does that for us. . .
~ TCON.O is set to high to make INTO an edge-triggered interrupt. U INTO is edge-triggered (that is, TCON.O IS_set),
whenever a high· to-low pulse is appUed to the INTO pin it is captured (latched) and kept by the TCON? b1t by
making TCON.2 high. While the !SR for INTO is being serviced, TCON.2 stays high no matter ~ow many times an
H-to-Lpulse is applied to pin INTO. Upon the execution of the last irastruction of the !SR, which ,s RETI, the TCON.2
bit is cleared, indicating that the INTO pin can respond to another interrupt.

SECTION 11.4: PROGRAMMING THE SERJAL COMMUNICATION INTERRUPT


1. True. There is only one interrupt for both the transfer and recejve.
t 23H
l Bit 04 (IE.4) and "MOV IE, ff 10010000B" will enable the sedal interrupt.
l TheRI (received interrupt) flag is raised when the entire frame of data, including the stop bit, is received. As a result
the received byte is delivered to the SBUF register and the 8051 jumps to memory location 0023H to execute the JSR
belonging to this interrupt. In the serial COM interrupt service routine, we o,ust save the SBUF contents before it is
la;t by the incoming data.
i false
l Tiw. We must do it since the RETI instruction will not do it for the serial interrupt.
I. CLR TI
P.ET!

5£.CnON 11.5: INTERRUPT PRIORITY lN THE 8051/52


L False. They are assigned priority according to Table 11-3.
l IP(interrupt priority) register. Yes, it is bit-addressable.
l 811 D4 (lP.4} and the instruction ·MOV IP, nooo1ooooa" ,.,ill do it.
l Uboth are a_ctivated at the same time, INTO. is serviced first since it has a higher priority. After INTO Js serviced,
LWt 1Sserv1ced, assuming that the external tnterrupts are edge-triggered and H·to-L transitioras are latched. In the
~ of low-level trigg~r~ interrupts, _if both are activated at the same time, the INTO is serviced first; then after the
~I has firushed serv,c,ng the INTO, 11 scans the INTO and !NTl pins again, and if the INTl pin is still high it w·u 1
""serviced. '
i We have an interrupt inside an interrupt, meaning that the lower-priority interrupt is put on hold and th hi h
· · ·h·
···" After servicing
°'1e1Ssc rv1,,:u. , JS hig her-pnon g er
· ·ty ·m terrupt, the 8051 resumes servicing the lower-prioritye ISR.
I

CHAPTER12

LCD AND KEYBOARD


INTERFACING

OBJECT[VES

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

> List reasons that LCDs are gaining widespread use, replacing LEDs
> Descnbe the functions of the pins of a typical LCD
> List instruction conunand codes for programming an LCD
> Interface an LCD to the 8051
> Program an LCD In Assembly and C
> Explain the basic operation of a keyboard
> Describe the key p.- and detection mechanisms
> Interface a 4x4 keypad to the 8051 using C and Assembly
I . . 1
in how to interface the 8051 to devices
( the 8051. We exp a 805 1 Section 12 2 ke bo d · SUdi-
This chapter explores some real-world applicattons O . '-cing with the 1. n · ' Y ar lllterfa,.;.
. shOw LCD interr~ ·•••
an L.CD and a keyboard- In Secbon 12.1, we h sections- •
with the 8051 is shown We use C and Assembly for bot

SECTION 12.1: LCD INTERFACING describes how to program and interface an LCD to
This section describes the operation modes of LCDs, then llQ
8051 using Assembly and C.

LCD operation · LEDs (seven-segment LEDs or o ther multi-...


In recent years the LCD is finding widespread use replaang --.,...en,
LEDs). This is due to the foUowing reasons:
1 !
-'
I')
I. The declining prices of LCDs.
2. The ability to display numbers, characters, and graphics. This is in contrast to L ED s, which are limited to numbet,
and a few characters.
~I 3. Incorporation of a refreshing control.fer into the LCD, thereby relieving the CPU oft!'e task of refreshing the LCD.
I In contrast, the LED must be refreshed by the CPU (or in some other way) to keep d1Splaymg the data.
4. Ease of programming for characters and graphics.
D
( LCD pin descriptions
·' LCD discussed
Thepositions
the pin in th·~~~.tion has 14 pins.
for various • The function of each pin is given in Table 12-1. Figure 12-1 shows

Vceo Vss, and vE,
While Va: and Vss provide +SY and ground, respectively V . used f .
' "'is or control.ling LCD contrast.

Table 12-1: Pin Descr iptions for LCD


Pin Symbol UO
Description
I v'6 Ground
2 voc
3 +SV power supply
V"
4 Power supPIY to control contrast
RS I
RS - 0 to select command .
s R/ W RS " 1 to select d . register,
I
6 E r wnte, R/W _
1/ 0 Enable - l for read
7 DBO t
1/0
8
9
DBt 1/ 0
The 8-bit data bus •
DB2 The 8-bit data bus
1/ 0
10 DB3 The 8-bit data b
1/ 0 Th us
11 DB4
1/ 0 e 8-bit data bus
12 DBS TheS-b·it data bus
1/o
13 DB6
1/0 The 8-bit data bus
14 DB7
1/0 TheS-b·It data bus
The 8-bit d ata bus
300
I I2 14
I ()DOOODDDDDDOOOD 0 14
0
00 13

:
oo

[.__
••
gg I
l 00 1
2 00

() 0 0
OMC1610A 14 OMC161068 21 OMC20261
OMC1606C OMC16207 OMC24227
OMCl6117 OMC16230 OMC24138
OMC16128 OMC20215 DMC321 32
OMC16129 OMC322l6 OMC32239
OMC1616433 OMC4-0131
OMC4-0218
OMC20434

rc,rt U•I. Pin Positions for Vuious LCDs from Optrex

RS, register select


There are two very important registers inside the LCD. The RS pin is used for their selection as follows. If RS = 0,
1,tl!lStruction command code register is selected, allowing the user to send a command such as clear display, cursor at
11.lnt, etc. If RS = 1 the data register is selected, allowing the user to send data to be displayed on the LCD.
I
I
PIN, read/write
R/Winput allows the user to write information to the LCD Tab le 12-2: LCD Command Codes
"read information from it. R/W = 1 when reading; R/W = 0
when writing. Code Command to LCD Instruction
(Hex) Register
E, enable 1 Clear display screen
The enable pin is used by the LCD to latch information 2 Return home
prtlented to its data pins. When data is supplied to data pins,
4 Decrement cursor (shift cursor to left)
•high·to-low pulse must be applied to this pin in order for the
U:O lo latch in the data present at the data pins. This pulse 6 Increment cursor (shift cursor to right)
illllllbea minimum of 450 ns wide. 5 Shift display right
00-07 7 Shift display left

The8-bit data pins, DO- D7, are used to send information to 8 Display off, cursor off
iheLCDor read the contents of the LCO's internal registers. A Oispla y off, cursor on
!he To display letters and numbers, we send ASCII codes for C Display on, cursor off
in.~~lters A • Z, a • z, and numbers O - 9 to these pins while
""'g RS = l. Display on, cursor blinking
There are also instruction command codes that can be sent \F Display on, cursor blinking
111
l'OsithelCo to dear the display or force the cursor to the home
~ or blink the cursor. Table 12-2 lists the instruction 10 Shift cursor position to left
W dcodes. 14 Shift cursor position to right
lCo .e also use RS = O to check the busy flag bit to see if the
i::
~ ready to receive information. The busy flag is D7 and
18 Shift the entire display to the left
1~ read when R/W = 1 and RS = 0, as follows: if R/W = lC Shift the entire display to the right
0
= =
~ ; O. When D7 1 (busy flag 1), the LCD is busy taking 80 Force cursor to beginning of 1st line
' -~ I operations and will not accept any new infor-
' N 07 = 0, the LCD is ready to receive new infor- co Force cursor to beginning of 2nd line
'lllin olt: It is recommended to check the busy flag before 38 2 lines and 5x7 matrix
, ganydata to the LCD. Nott; Thi. table ia extr1ctttl horn Tobie 12-4.

• ~~~~;;;-;;;;;;:;;;;.:;;;:;~~~~~~~~~~~~~~~~~
.\Nt) i(EyBOARD JNTl!RPACINC
I ·th a time delay
k ·n RS"' o. For data, mak e RS = 1. The
Sending commands and data to LCDs WI
To send any of the commands from Tab!e 12·2 to:~~
LCD ma e P'

h.igh•to-low pulse to the E pin to enable the u,temal la


· p 12 n send
of th~ LCD. This is shown ltl rogram •1. See Figure 12:
2
for I.CD roMections.
d ta/command
,calls a time delay before sending next a
· s DO· 07
;Pl.O·Pl.7 are connected to LCD data pln
;P2.0 is connected to RS pin of LCD
;P2.l is connected to R/W pin of LCD
:P2.2 is connected to B pin of LCD
.. ORG
MOV
OH
A,#38H
. . 't LCD 2 lines, Sx7. matrix
,1n1 .
' ! ACALL COMNWRT ;call command subroutine
ACALL DELAY ;give LCD some time
MOV A,#OEH ;display on, cursor on
ACA.LL COMNWRT ;call command subroutine
ACALL DEW\Y ;give LCD some time
MOV A,#01 ;clear LCD
ACA.LL COMNWRT ,call command subroutine
ACALL DEW\Y ;give LCD some time
MOV A,#06H ;shift cursor right
ACALL COMNWRT ;call command subroutine
ACA.LL DELAY ;give LCD some time
·'I MOV A,#84H :cursor at line l,pos. 4
I ACALL COMNWRT ;cal l command subroutine
r ACALL DELAY ;give LCD some time
MOV A,#'N' ;display letter N
ACA.LL DATAWRT ;call display subroutine
ACALL DELAY ;give LCD some time
MOV A,#'0' ;display letter O
ACALL DATAWRT ,call display subroutine
AGAIN: SJMP AGAIN ;stay here
COMNWRT:
:send command to LCD
MOV Pl, A
CLR P2.0 :copy reg A to portl
:RS=O for command
CLR P2.l
SETS P2.2 ;R/W=O for write
ACALL DELAY '.E~l
for high pulse
,give LCD some t 'ime
CLR P2.2
RET ; E =O for H-to-L Puse 1
DATAWRT:
MOV Pl,A ;write data to LCD
SETS P2.0 ;copy reg A
CLR :RS=l for da~o porti
P2.l
SETS P2.2 :R/W=O for write ~
ACALL DELAY :ll•l for h . h
;give LCD 19 Pulse
CLR P2.2 some ti
RET :ll•O for I! me
DELAY: MOV -to-L Pulse
R3,#SO
HERB2: MOV R4,#2SS ,so or bi
HERE: :R4~2ss 9her for fast
DJNZ R4, HERE CPUs
DJNZ R3,l!ERB2 ; Stay Wltil R4
RET becomes 0
BND
Program 1:Z.1: Communi<•ting with LCD .
uaiog • dtl•y
. g code or data to the LCD with checking busy flag
sei1d10 fl N ti that we must
t,ove code showed how to send commands to the LCD without checking the busy a~. 0 ce . th busy
rr,e: delay between issuing data or commands to the LCD. However, a much better ,,vay 1s to morutor e
rit ~!!
j/lj t"'v
issuing a command or data to the LCD. Th.is is shown in Program 12-2.

~·---~~~~~~~~~~~~,
LCD
8051 ~ - - - -:-, ..sv
Pl.O 1-----1 DO Vcc l
~
~~ ,> lOK
VEE _.,~ POT
Pl.7 07 <
Vss I
RS R/ WE
P2.0t---'I
P2.1 1 - - - - - '
P2.2 _ _ _ _ _....

Ii!'" U-2. LCD Connections

;Check busy flag befo re sending data, command t o LCD


;Pl=data pin, P2. OaRS, P2. l=R/W, P2. 2=E pins
\
MOV A,#38H ;init. LCD 2 l i nes, Sx7 ma trix
ACALL CbMMAND ; issue command
MOV A, #OEH ;LCD on, curso r o n
ACALL COMMAND ;issue command
MOV A,#O l H ;clear LCD command
ACALL COMMAND ;issue command
MOV A, #06H ;shift cursor right
ACALL COMMAND ;issue command
MOV A,#868 ;cursor: line 1, pos. 6
ACALL COMMAND ;command subrout i ne
MOV A.# 'N' ;display letter N
ACALL DATA DISPLAY
MOV A,# 0' 1
;display letter O
ACALL DATA DISPLAY
2EF.S: SJMP HERE ;STAY HERE
COMMA!lo: ACALL READY ;is LCD ready?
MOV Pl,A ;issue command code
CLR P2. 0 ;RS•O for command
CLR P2. l ;R/W•O to write to LCD
SETB P2. 2 ;E=l for H·to·L pulse
CLR P2. 2 ;B•O,latch in
RET
ilJ,?A_DISPLAY:
ACALL READY ;is LCD ready?
MOV Pl,A ;issue data
SETS P2. 0 ;RSal for data
CLR P2. l ; R/ W•O to write to LCD
SETS P2. 2 ;B•l for H·to-L pulse
ACALL DELAY ;give LCD some time
CLR P2. 2 ; B•O, l a tch in
RET

"'Ir.,,. U-1: Communbtlng with LCD ulng 11w buy hg (continiud on nut pagtJ
~~:;;~~:;;;;;;;::;:;;;:;;;;-~~~~~~~~~~~~-=--~~~
ANo l(EYBoARD IN'l'DPACING
I 7 input port
,make Pl. command reg
R.BADY: SETB Pl.7 . RSsO access d reg
CLR P2.0 ;R/Wsl read comman
SETB P2.l
;read command reg and check busy nag ·EsO f or L-to·H pulse
.
BACK: CLR P2.2 • i LCD some time
·g ve
ACALL DELAY '.Esl L-to·H pulse
SETS P2 .2 ;stay until bUSY fiagsO
JS Pl.7,BACK
RET
S.ND

Program 12·2. (tt1ntlnued from prtviow; ptJg<)

-./ , Notice in the above program that the busy flag is 07 of the command register. To read th~ command register Wt
' make R/W: J and RS: o, and a L-to-H pulse for the E pin wiU provide u~ the coo:imand register. After reading tht
'.'°mmand register, if bit 07 (the busy flag) is high. the LCD is busy and no informa.tion .(command or data} should lJf
issued to it. Only when D7 : o can we send data or commands to the LCD. Notice 1n this method that no time dela
•.re.used since we are checking the busy flag before issuing commands or data to the LCD. Contrast the Read and wrf;
tiJn'.".g for the ~CD in Figures 12·3 and 12-4. Note that the E line is negative-edge triggered for the write while it.
positive-edge triggered for the read. ~
.,
LCD data sheet

I In the LCD, one <'an put data at any location. The following shows address locations and how they are accessed.

RS R/W DB7 DB6 DBS DB4 DB3 DB2 DBO


0 0 1 A A A A A ~Bl
A
where AAAAAAA -- 0000000 to 0100111 for line I and AAAAAAA _ 1
- 000000 to 1100111 for line 2. See Table 12-3.

DO· D7

I
~--1----L·-
RJW ;
F.,
.I

RS - - - l tAS I b. ._______
l-
,i
,i
j

to= Data output delay tl


1
-Sc , 1me
J;
.
AS - tup time prior to I! (go· .
tAH = Hold time after Eh U1g high) for both RS
as come down I •nd RJW ~ I
Note: Read requites an L- or both RS and R/W 40 ns (minimum)
. to+! pulse for the . "10 ns (minimum
F,gure 12-J. LCD Timing for R••d (L-to-H f • E Plll. )
or E hnt)

304
E-----1 tosw ...... '
\ tH '
R/W - - l tAS ,
i . ., __ _ _ __ _M
tJ>wH :IAH -- - - - - -
t• ?l ~

RS---

IPWH = Enable pulse width = 450 ns (minimum)


tosw = Data setup time = 195 ns (minimum)
e tH = Data hold time = JO ns (minimum)
e tAS =Setup time prior to E (going high) for both RS and R / W = 140 ns (minimum)
e IAH = Hold time after E has come down for both RS and R/ W =10 ns (minimum)
s
e rig111f 124. LCD Timing for Write (H-to-L for E line)
s
Table12-3: LCD Addressing
DB6 DBS DB4 D B3 DB2 DB1 O BO
DB7
tine I (min) 1 0 0 0 0 0 0 0 '
Urie 1(max) I 0 1 0 0 1 I 1
line2(min) l l 0 0 0 0 0 0
Lne2 (max) l l l 0 0 1 1 1

The upper address range can go as high as 0100111 for the 40-character-wide LCD, while for the 20-character-wide
=
LCD it goes up to 010011 (19 decimal = 10011 binary). Notice that the upper range 0100111 (binary) 39 decimal, ,vhich
aintsponds to locations O to 39 for the LCDs of 40x2 size.
from the above discussion we can get the addresses of cursor positions for various sizes of LCDs. See Figure U-5 for
lheCUI5()r addresses fo r common types of LCDs. Note that all the addresses are in h ex. Table U-4 provides a detailed list
of I.CD commands and instructions. Table 12-2 is extracted from this table.
I
Table 12-4: Lisi of LCD Instructions Execu«o~

... ... = 0 Tiin,


0= 0=
~ "' Description
0=
"' "'
= 0 (~
Instruci;on ::1 ~ 0 "'
"
= 0 0 0
1 0 5 entire display and sets l.64 ll\s
0 0 0 ea~M address Oin address
Oear Display 0 0 0 0 0 0 DD ·
,,.
---
, counter
Sets DD RAM address Oas l.64 ins
0 l
Return Home 0 0 0 0 0 0 0 dd ss counter. Also returns
are d ··a1
J display being shifte to ongm
pos1·tion· DD RAM contents

-
~
remain unchanged·
, I

s Sets cursor move direction and 40µs
., Entry Mode 0 0 0 0 0 0 0 l 1/D
specifies shift of display. These
Ii Set
operations are performed during

'
,; Display On/ 0 0 0 0 0 0 l D C B
data write and read.
Sets On/Off of entire display (D),
cursor On/Off (C), and blink of
40µs
Off Control
ri
( Cursor or 0 0 0 0 0 l S/C R/L
cursor position character (B).
Moves cursor and shifts display 40µs
Display Shift with-out changing OD RAM
·'I contents.
Function Set 0 0 0 0 1 N p
DL Sets interface data length (DL), 40µs
r number of display lines (L),
and character font (F).
Set CG RAM 0 0 0 1 AGC
Address Sets CG RAM address. CG RAM 40µs
data is sent and received after
this setting.
Set DD RAM 0 0 l AOD
Addn>SS Sets DD RAM address. DD RAM 40µs
data is sent and received after
Read Busy 0
this setting.
1 BP AC
Flag & Address
Reads Busy flag {BF) indicating 40µs
mtemal operation is being
performed and reads address
Write Data CG 1 0 counter contents.
or DD RAM Write Data
Writes data into DO or CG RAM. 40µs
Read Data CG l 1
or DD RAM Read Data

Notn: Read Data from DD


or CG RAM. 40µs
I &ec·u.t~on hmts art' maximum tunts whion rep or (0$( 250 ktu..
2. EM.:ution bmo ch.loge, when frtquency ch4n Ex When
18
8
3. Abbrevuilions: .._ : lq, or rose ii 270 kHz: µs •
00 RAM Displ•y d•ta RAM 40 250 I 270 ~ 37 JJS.
CC RAM Chiltacter &enet.ltor RAM l
ACC CC RAM add,.,. (
AOD
AC DO RAM address, corresponds to C'U1$0f .add .
Add,.... counter used for i,.,11, OD and CC .;;,:
t/0• t
5:1 lnc.rm,cn.1 I/O. •ddr~
Ae<omp,,nte, d.l.,pl•y sh,r, O o.n.,,,..,t
SIC= I O.spt.y shift
R/L o t
DL • l
Sl,lft to 111. l'!ght; s1c.o cu
8 bu•, DI. • o 4 bu, R/ L - '$0t rnov~
No I
lli.nt,N•O; I line
-o $hJ11 to the i.r,
Fol
SXIOdolS,P:O ,x7doos
BP ,- I

~
(nrtm•J operation,
BF.o C•n......, •
1
p '"•lruc:tion

'~
- - - -

Optrex Is one of the largest ma.n ufacturer of LCOs.


You can obtain datasheets from their I

Web site, www.optrex.com.

The LCOs can be purchased from the


following Web sites:

www.dlglkey.com
www.jameco.com
• www.elexp.com

Sending information to LCD using MOVC instruction


The Program 12·3 shows how to use the MOYC instruction to send data and commands to an LCD. For an 8051 C
version of LCD programming see Examples 12-1 and 12·2.

,calls a time delay before sending next data/command


Pl .O·Pl.7=00·07, P2.0=RS, P2.1~R/W, P2.2=E pins
ORG 0
MOV OPTR,#MYCOM
Cl: CLR A
MOVC A,l!IA+DPTR
ACALL COMNWRT ;call command subroutine
ACALL DELAY ;give LCD some time
JZ SEND DAT
INC OPTR
SJMP Cl
SBlfD_DAT: MOV DPTR,#MYDATA
Dl: CLR A
MOVC A,@A+DPTR
ACALL DATAWRT ;call command subroutine
ACALL DELAY ;give LCD some time
INC DPTR
JZ AGAIN
SJMP Dl
AGAIN: SJMP AGAIN ;stay here
CXll!NwRT: ;send command to LCD
MOV Pl,A ;SEND COMND to Pl
CLR P2. 0 ;Rs~o for command
CLR P2. l ;R/W=O for write
SETB P2.2 :E•l for high pulse
ACALL DELAY ;gi ve LCD some time
CLR P2.2 ;E•O for H-to-L
RET
~ 11,.3: ~ding information lo LCD with MOVC in•lnlcllon· ~con1mutd
.
on ntxt pogt)

lflaANo Kl!Y80ARD INTEKJIACING


I
Oi\TAWRT : · SEND DATA to Pl
MOV Pl,A '.RSsl for dat:~
SETB P2.0 ' w o for write
CLR P2.1 ; R/' h igh puls e
·E•l for i
SETB P2.2 ' LCD some t me
ACALL DELAY 1 give H- to · L pulse
/ CLR P2.2
;E=O for
RET fast CPUs
; LONG DELAY POR
DELAY: MOV R3,#250
HERE2: MOV R4, #2SS I
HERE: DJNZ R4, HERE
OOl,IZ R3,HERE2
l ! RET
-, ORG 300H
(• • MYCOM: DB 38H,OEH,01,06 , 84H,0 •·commands and nu ll
I
MYOATA : DB "HELLO", 0 ;data a nd nul l
~
END
I
I
r Program 12-3. (cotttimitd from prmious page)

0
( Example U-1
' Write an 8051 C program t6 send letters 'M', ' D', and 'E' to the LCD using delays.
,

Solution:
#include <regSl.h>
sfr l data = Ox90;
// PlaLCD daca pins (Fig. 12-2)
sbi t rs • p2·0;
sbit rw • P2'"'1;
sbi t en • P2"2;
void mai n()
{
lcdcmd(OxJS);
MSDelay(2SO);
lcdcmd(OxOE);
MSDe1ay(2SO);
lcdcmd{OxOl);
MS0e1ay(2SO);
lcdcmd{Ox06);
MS0e1ay(250);
lcdcmd{Ox86);
HSDelay(250); //line 1 poi
• s tion 6
lcddata('M•) 1
MSOelay (2 50) ;
lcddata('O') 1
MSDelay(2SO);
lcddata {• E') 1
}

308
1cdcmd(unsigned char value)
vOld
(
ldata = value; II put the value on the pins
rs • o;
rw , O;
en~ l; II strobe the enable pin
MSDelay(l);
e.n = O;
return;
J
'IOid lcddata (unsigned char value)
{
ldata • value; II put the value on the pins
rs= l;
rw ;: 0;
en = l; II strobe the enable pin
MSDelay ( 1) ;
en = 0;
return;
}
void MSDelay (unsigned int itime)
\
(
unsigned inti, j;
for(i=O;i<itime;i++)
for(j•O;j<1275;j++);

wmplet2-2

Repeat Example 12-1 using the busy flag method.

Solution:
l inc:lude <regSl. h>
lfr ldata • Ox 90; //Pl•LCD data pins (Fig . 12-2)
ab1t rs z p2""0;
•bit rw • p2•1;
•bit en • p2·2;
1bit busy • Pl •7;
•oid main()
(
lcdcmd ( Ox38) ;
lcdcmd(OxOE);
lcdcmd ( OxOl) ;
lcdcmd ( Ox06) ;
lcdcmd ( Ox86) ; //line l, position 6
lcdd&ta ( 'M');
lcddata ( • o• ) ;
lcdda.ta(' E');
l

309
I
void lcdcmd(unsigned char value)
{ the LCD busyhenag.
pins
1cdready O ;
I /checJc value on t
//put the
ldata = valuei
rs • O;
/ rw = O; abl e pin
//strobe the en •
en= l;
•'
MSDelay(l};
/ en .. O:
v return;
~

1, l
l •
void lcddata(unsigned char value)
{
lcdready Cl : //check t be LCD busy flag
ldata = value; //put t he value on the pins
rs• l;
rw = 0;
en • 1; //strobe t he enable pin
MSDelay (1),
en • O;
rec.urn;
'I l

void led.ready()
t {
busy= 1; II ma ke the b usy pin an input
rs = 0:
rw = l;
while (busy••l)
{ //wait here for busy flag
en = O;
MSDelay(l); //strobe tbe enable pin
en e- l;
l
return;
}

void MSDelay(unsigned int itime)


{
unsigned inti, j;
for(iaO;i<itime;i++)
for(j•O;j<l2?S;j++J;
l

Review Questions

1. The RS pin is an .Cinput, output) pin for the LCD.


2. The E pin is an (mput, output) pin for the LCD.
3. The E pin requires an . . .(H·to-L, L-to-H) pulse to latch in . .
4. For the LCD to recogn12e information at the data pins as d
1m: Rs tnformalion at the data pins of the LCD.
s. Give the command codes for line 1, first character, and I2•,fi trnhUst be set to (high, low). ~
310 ' rs c arac:ter. .,
secr10N 12.2: KEYBOARD INTERFACING
J(eyt,oards and LCDs are the most widely used input/output devices of the 8051, and a basic understandin~ of
is essential. In this section, we first discuss keyboard fundamentals, along with key press and key detection
=:aiusms· Then we show how a keyboard is interfaced to an 8051.

r1acing the keyboard to the 8051


1118
At the lowest level, keyboards are organized in a matrix of rows and columns. The CPU accesses ~oth rows and
(1liuJlU1S thr~ugh ports; therefore, with two 8-bit ports, an s x 8 matrix of keys can be conn_ected to a rrucroprocessor~
Wbfll a key lS pressed, a row and a column make a contact; otherwise, there 1s no connection between rows and col
~ . In IBM PC keyboards, a single microcontroller (consisting of a microprocessor, RAM and EPROM, and _s~veral
~aUon a single chip) takes care of hardware and software interfacing of the keyboard. In such.systems, it IS the
.,,v:tion or programs stored in the EPROM of the microcontroller to scan the keys continuously, identify which one has
blfJl activated, and present it to the motherboard. In this section we look at the mechanism by which the 8051 scans
.,i identifies the key.

Scanning and identifying the key


Figure 12-6 shows a 4 x 4 matrix connected to two ports. The rows are connected to an output port and the columns
ueconnected to an input port. If no key has been pressed, reading the input port will yield ls for all columns since they
mall coMected to high 01o:l· If all the rows are grounded and a l<ey is pressed, one of the columns will have Osince
illekey pressed provides lhe path to ground. It is the function of the microcontroller to scan the keyboard continuously
1Ddetect and identify the key pressed. How it is done is explained next.

Grounding rows and reading the columns


To detect a pressed key, the microcontroller grounds all rows by providing Oto the output latch, then it reads the
mlumns. lf the data read from the columns is D3 ·DO= 1111, no key has been pressed and the process continues until

Vcc
4.7k .~

3
>

2
'
'>
I


>

0
·~
);'.• );'.' >;:'• Y.• 4.7k
.
DO
7 5 4
6);'.,
Y.• >;;'• >;;'• . . .
DI V

A 9 8
BY.• );'.. Y.• Y.•
02
F E D C
>;:'' Y.• Y.' );;'•
03 -

Port 1
(Out)
03 02 DI DO
Port 2
(In)
I
Ex•mple 12·3 f the pressed ey
dcolumn o
From Figure 12-0, identify the row •_n = for the coJum~
00 1011
(a) 03. DO= 1110 for the row, D3 • DO= 0111 for the col um
(b) 03. DO = 1101 for the row, 03

I.·
Solution:
From figure 12-o th.e row and column t'n
( ) The row belongs to DO and the co umn
used to identify the key. number 2 was pressed.
bebclongs to D2; therefore, ~:~ number 7 ,vas pressed.
D3· therefore,

1 j •'
- • · d h
(b) The row belongs to 01 an t c co uI mn belongs 10 '

a 7-erO, h . means that a key press has occurred. For


a key press is detected. However, if one of the col~mn b·t 15 has
column hastis '
been pressed. After a kcy pre~s ,s . d elected,
I if 03 1
examp e, • DO = t l01 • this means that ,1 key in the D
f 'd hfying the k ey. Starting
• ,vith the .top ro,v, the
k aucrocontroUer
· h ·
the microcontroUer will go through the process o '. en ads the columns. Jf the data read ,s all ls, no ey int at row IS
grounds it by providing a low to row DO only; then 11 ..._,, the next row, reads the columns, and checks for any zero.
activated and the process is moved to the next row. Jt growtdtifi~. • of the row in which the key has been pressed, the
. , · I·d tif d After ,den ca 1ion .
' This process conhnues until the row is en ,e · b
next task is to find out which column the pressed key eIongs o. t This should be easy since the 1rucrocontroller kno-..1
. . b · esscd Look al Examp1c 12•3 ·
'r at any time which row and column are elmg ace .
Pro ram 12-4 is the 8051 Assembly anguage program thr ln this
for detection •and identification of key activation.
progra!, it is assumed that Pl and P2 are initialized as output and input, respectively. Program 12-4 goes ough the
following four major stages:

1. To maJ<e sure that the preceding key has been released, Os are output to all rows at once, and tlte columns are read
and checked repeatedly until all the columns are high. l'Vhen all columns are found to be high, the program w41ts
for a short amount of time before it goes to the next stage of waiting for a key to be pressed.
2. To see if any key is pressed, the columns are scanned over and over in an infinite loop until one of them has a Oon
iL Remember that the output latches connected to rows still have their initial zeros (provided in stage 1), ma.king
them grounded. After the key press detection, lhe microcontroUer waits 20 ms for the bounce and then scans the
columns again. This sen•es two functions: (a) it ensul't'S that the first key press detection was not an erroneous one
due to a spike noise, and Cb) th.e 20-ms ~elay prevents the sa.m e key press from being interpreted as a multiple ktJ
press. If after the 20-ms delay the key 1s still pressed, it goes to the next ta to d h.ch · bel Ill
otherwise, it goes back into the loop to detect a reaJ key press. s ge etect w i row ,t ongs '
3. To detect which row the key press belongs to the microcontroll
each time. If it finds that all columns are high: this means that lher grounds one row at a time, reading the columns
grounds th.e next ro"'. and continues until it finds the row the kee key press cannot belong to that row; therefore, II
key press belongs to, it sets up the starting address for th I k Ypress belongs to. Upon finding the row that tht
. and goes to the next s tage to identify the key.
for .that row e 00 ·up table holding the scan codes (or the ASCU ,-a!uel
4. To tdentify the key press, the microcontroller rotat,- th .
t if ·1 · I U findin '• eco1umn b,ts o b'
. o_see , IS ow. pon g the zero, it pulls out the ASCn , ne 1t ata time, into the carry Aag and che,:ks
,t increments the pomter to point to the next eleme t f h code for that key from the l k tabl . then;ise
n o t e look-up t bl p· 00 -up , e, o
. . .
Whde the key press detection IS standard for aU k b a e. igtu-e 12-7 flowcharts this process.
ies. The look-up table method shown in Program -4 ey oards, the process fo d .
12
provides the Oowchart for Program 12-4 for scannin can be modified to work' ~term.,rung which key is pres;ed ,-ar-
f
There are IC chips such as National Semicondu ~nd identifying the P es With any matrix up to 8 x 8. Figure I!-7
all in one chip. Such chips use combinations of co~or 5 MM74C923 that in~ Sed key.
lymg concepts presented in Program 12-4. Example 1~ •nd logic sates ( 0 '1;' 0 ra te keybo..,rd l;Canning and d ~
-4 shows keypad pr:o ll\Jcrocontroller) to implement the und~r·
312 grall'lnitng in 8051 C.
i,oard subroutine. Thie program sends t he ASCII code
,t~Y pressed key to PO . l
:!0\.p
;Pl·
1 .3 connected to rows P2 . 0·P2 .3 conne cted to columns
MOY P2,#0FFH ;make P2 an input por t
MOY Pl, #0 ;ground all rows at once
iO : MOY A, P2 · read all col. ensure all keys open
•;masked unused bits •
ANL A,#OOOOllllB
CJNE A,#OOOOllllB,Kl ·check til all keys released
ACALL DELAY '·call 20 ms delay
'2= MOY A, P2 ;see if any key is pressed
ANL A,#OOOOllllB ·mask unused bits
CJNE A,#OOOOllllB,OVER ;key pressed, await closure
SJMP K2 •· check if key pressed •
()VER: ACALL DELAY ;wait 20 ms debounce time
MOY A,P2 ;check key closure
ANL A,#000011118 ·mask unused bits
CJNE A,#OOOOllllB,OVERl '
;key pressed, find row
SJMP K2 ;if none, keep polling
OVERl: MOY Pl , #111111108 ;ground row 0
MOY A,P2 ;read all columns
ANL A,#000011118 ;mask unused bits
CJNE A,#000011118,ROW_O ; key row o, find the col.
MOY Pl,#llllllOlB ;ground row 1.
MOY A,P2 ;read all columns
ANL A, #000011118 ; mask unused bi ts
CJNE A,# 000011118,ROW_ l ; key row 1, find the col .
MOY Pl , #111110118 ;ground row 2
I MOY A, P2 ;read all columns
A,# 000011118 ;mask unused bits
' ANL
CJNE A, #0000llllB, ROW_2 ;key row 2, find the col.
;ground row 3
MOY Pl , #l l l lOlllB
MOY A, P2 ; r ead al l columns
I A, #OOOO ll l lB ;ma sk unused bits
ANL
~ ;ke y r-0w 3 , find the col.
CJNE A,# 00001111B, ROW_3
LJMP K2 ; i f none, false input , repeat
I ROW O: MOY DPTR, #KCODEO ; set DPTR=star t o f row o
l SJMP PINO ; find col. key belongs t o
lOW l: MOY DPTR, #KCODEl ; set DPTR•s tart of r ow 1
SJMP PI NO ;find col. key belongs t o
lOW 2: MOY DPTR, #KCODE2 ; s et DPTR=s t art o f r ow 2
SJMP PINO ;find col. key belongs to
ltOII ) : f'.OY DPTR , #KCODE3 ; set DPTR=s t art o f row 3
FIND : RRC A ;see i f any CY b it is low
JNC MATCH ;if zero , get the ASCI I code
INC DPTR ;point t o next col. address
SJMP FIND ;keep searching
CLR A ;set A=O (ma t ch is found)
MOYC A, e A+DPTR ; get ASCI I code from tabl e
MOY PO,A ;displ ay pressed key
LJMP Kl
:Asc11 LOOK-UP TABLE FOR EACH ROW
ORG 300H
DB '0','l','2', ' 3' ;ROW 0
DB ' 4 ','S','6','7' ;ROW 1
DB '8','9','A','B' ;ROW 2
DB 'C', 'D' I 'E', 'F' ;ROW 3
JrnD

3U
I

( '
- l

/ ..
I
I
(

Figure 12•7, Flowclurt for Progr•m

Eumple12~
Two \WH(ho arc ton~
\\'rit,• .t program tot, t ... ~""1,

Solution:
Th<: two ~" okfK'j an, r'llfll"'-"''"'-1
pondtng port hne to go lo

314
·tch 2 (SW2) is pressed,
the progran1. whenever switch 1 (S\Vl) is pressed, Ol is displayed on ~ort _2, w h en swi
1~. displayed and when both switches are sin,ultaneously pressed, OFH 1s displayed.
,'11>

S)Y 1 8051
/ PO. I
5W2 P0.2
P2

P3.2(1NTO)

ORG OOOOH
LJMP MAIN
·--main program for initialization of interrupt

ORG 0030H
AA!II: SETB TCON.O ;make INTO an edge-triggered interrupt
MOV IE,#81H ;enable interrupt INTO
!!ERE: SJMP HERE ;wait for i nterrupt
;· ·ISR for INTO
ORC 0003H
LJMP TEST ;jump to new location '
ORG 0080H
iBST: SElTB PO .1 ;make PO.l an input port
SBTB P0.2 ;make P0.2 an input port
SBTB C ;set carry
TESTl: MOV C,PO.l ;use carry flag to test the status of PO.l
J NC SWl ;if C=O, it means switch SWl is pressed
MOV C,P0.2 ;use carry flag to test the status of PO.l
JNC SW2 ;if C• O, it means switch SWl is pressed
MOV P2,#0FFH ; if both switches are not pressed, P2 •FFH
RETI
SWl: MOV C,P0.2 ;since SWl is found pressed.test SW2
JNC BOTH ;since both are pressed, jump to BOTH
MOV P2, #OlH ;only SWl is pressed, make P2•0l
SJMP TESTl ;continue monitoring the switches
SW2: MOV P2, #02H ;this is reached when SW2 is pressed
SJMP TESTl ;continue monitoring the switches
MOV P2,#0FH ;this is the case of both switches pressed
SJMP TESTl
END

~Ql111ple 12-4a
~nte a C program to read the keypad and send the result to the first serial port.
PlO.p·1.3 connected to rows
0.PJ .3 COMeelied to columns
-Cani.gur, the 5l'NI port for 9600 baud, 8-bit, and 1 stop bit.

315
I
Solution:
#include <reg51.h> eas 1. er reading
pores for
//define
jj<lefine COL P2
,I #define ROW Pl ).
/' .
void MSOelay(unsigne dint) . value ,
void SerTX (unsigned char' , •)',
{ •O' 'l',' 2 ,
unsigned Char keypad(4] 14] = ' . •6' '7',
' '5 '
•4 , I
' \711.I I B' ,
,91•9,ri.,}
"l • C' '
; •,
D'• , • EF I
';
1 •
., void main()
I• {
' unsigned Char colloc, rowloc; .
//timer
1 mode 2
,
TMOD = Ox20;
THl • -3; //9600 baud t P bit
I SCON = Ox50: //8-bit, 1 s 0
//start timer 1

r
TRl • l;
//keyboard routine. This sends the ASCII
//code for pressed key to the serial port ,
COL• OxFF; //make P2 an input port
' while(l) //repeat forever
{
do
{
ROW• OxOO; //ground all rows at once
colloc = COL; //read the columns
colloc &• OxOF; //mask used bits
}while(colloc l• OxOF) ; //check until all keys released
do
{
do
{
MS0elay(20J; //call delay
colloc • COL;
colloc &= OxOF; //see if any key is pressed
//mask unused bits
} while(colloc == OxOF);
//keep checking for keypress
MSDelay(20);
colloc • COL; //call delay for debounce
colloc &= OxOP; //read columns
} wbile(colloc == OxOF); //mask unused bits
//wait for keypress
while(l)
r
ROW = OxFE;
colloc • COL; //ground row o
col loc & = OxOF; //read columns
if(colloc l• OxOF) //mask unused bits
( //column detected
rowloc • O;
break ; I /save
) //eXit row location
While loop

316 -
THE80s1 MlCRo co -;
NiROLLER AND EMBEDDED SYST~ '
ROW• OxFD; I /ground row l
colloc a COL; //read columns
colloc &• OxOF; //mask unused bits
if(colloc !• OxOF) //column detected
{
rowloc • l; //save row location
break; //exit while loop
l
ROW= OxFB; //ground row 2
colloc = COL; //read columns
colloc &= OxOF; //mask unused bits
if(colloc !• OxOF) //column detected
(
rowloc • 2; //save row location
break; //exit while loop
l
ROW• OxF7; //ground row 3
colloc • COL; //read columns
colloc &= OxOF; //mask unused bits
rowloc = 3; //save row location
break; //exit while loop
)

//check column and send result to the serial port


if(colloc •• oxOE)
SerTX (keypad (rowlocJ [O J ) ;
else if(colloc •• OxOD)
SerTX(keypad[rowlocJ [l));
else if(colloc =• OxOB)
SerTX (keypad (rowlocJ [2]) ;
else
SerTX(keypad [rowloc) [3));
l
)

void SerTX (unsigned char x )


{
SBUF • x; //place value in buffer
while(Tle•O); //wait until transmitted
TI • O; //clear flag
J

Void MSDelay(uneigned int value)


{
unsigned int x, y;
for(x•O;X<l27S;x++)
for(yaO;y<value;y++);
)

ANO 1<£YBOARD INTERFAONC


317
I
Review Questions II ro,.-s are g.ro unded·
Jurnn does the p ressed key belong to?
esses.

i True or false. To see if any key: t'~~ ~Jumns, whi~uire two dif;':1:
fJ D3. DO = 01 I I is the data rea ~d ke identificabon a.re D3 • -
h~which key is pressed? •
'
''I
3. True or false. Key pressdetec;;_aDO= i11oand the c o ~ grounded. '
4. In Figure 12-6. if Ihde '°n.'fyvsthaerepressed key, one row at a ,•
s. True or (alse. Toi en
/
k ypads to the 8051. First, we described
V SUMMARY . f
This chapter showed how to inter a"':
th ,.,.. ati·on modes of LCDs, then descnbed ho
.
real-world dev,c
es
w to ,ogram the
p
such as LCDs andd. e data or commands to it via its inte,.
LCD by sen ,ng
.
. t This chapter also descnbed the oper.

11 c oF.r , S051 proiec s. . , · ·th ,._
1 •
.'
lace to the 8051. sed. ut devices ,or
Keyboords are one of the most widely u d t:on mechanisms. Then 8051
ation of keyboords, including key press and t~e ASCU code (or the pressed ey.
th:
was shown ,nter,aang w, a "'Y·

/1 boo rd. 8051 programs were written to return


I
r,
PROBLEMS
I SECTION 12.1: LCD INTERFACING
{) I. Which are the two registers in the LCD 7odule? rt using only 4 port tines?
2. How can data be transferred to the LCD rom ~ po code
3. To display letters and numbers, we sedndoddatad~a item) and its v~Jue is hex. 1
' • 4 "Clear LCD" is a (comman c e, a ,., 5
S.· What is the hex value of the command code for "display
. on'. cursor
, on ·
• 6. Which are the control pins of the LCD? What are the,r functton.5.' o the LCD
r
7. Give
8. Whichtheoft
sthate{oUf RS,. E, and
e o owmg !,_~Wedwonh:es~pd:tdi:~::;:::t;:Jm:nd code (~r data) to be latched in by the LCD?
,s nc,;u
(a) H-to-L pulse (b) L-to-H pulse
9. How does the LCD distinguish between data and command? .
10. How does the busy Dag aid in making the LCD program more eflioent? .
11. For a 16x2 LCD, the location of the last character of line 1 is SFH (its comn\and code). Show how this value was
calculated.
12. For a 16x2 LCD, the location of U1e first character of line 2 is COH (its command code). Show how this value was
calculated.
For a 20x2 LCD, the location of the last character of line 2 is 93H (its command code). Show how this value was
13. calculated.

For a 20x2 LCD, the location of the third character of line 2 is C2H (its command code). Show how this value was
14. calculated.

15. For a 40x2 LCD, the location of the last character of line 1 is A7H (its comma d cod ) SI h thi alue was
ca Jculated. n e. \OW ow sv
16. For a 40x2 LCD, the location of the last character of line 2 is E7H ('ts
1
calculated. command code). Show how tlus value was
17. Show the value (in hex) for the command code for the 10th toe r lin
value. • •on, e 1 on a 20x2 LCD. Show how you got your
18. Show the value (in hex) for the command code for the 20th I . .
value. OCation, line 2 on a 40x2 LCD. Show how you got your
19. Rewrite the COMJ',IWRT subroutine. Assume connectio Pl _
20. Repeat Problem 19 for the data write subroutine. Send ::: : 4 -..RS, Pl.5 = R/W, Pl.6 = E
1 5
the instruction MOVC. Iring Hello" to the LCD by ch~king the busy flag. Use
SECTION 12.2: KEYBOARD INTERFACING
21. In reading the columns of a keyboard matrix, if no ke is
22. In Pagure 12-6, to detect the key press, which of the f yll Pressed we should II
( ) IJ (b)
a a rows .
one row at tame (c) bo ow " ·s
h 111., 1 grounded? get a - - - - (l s, Os) ·
ot (a) •nd (b)
318

'
I
In Figure 12-6, to identify the key pressed, which of the following is grounded?
:J. (,) all rows . .(b) one row at time (c) both (a) and (b)
For figure 12-6, mdicate the column and row for each of the following.
Jl, (al D3- DO= 0111 (b) 03 - DO= 1110
l5, ipdicate the steps to ~etec! the key press.
Indicate the steps to identify the key pressed.
: we need to operate a key in the interrupt mode. How should the key be connected? .
ii, Ifa switch is connected to pin P3.2, what happens when the switch is pressed and a low is received on the pin?

ANSWERS TO REVIEW QUESTIONS


5tCf!ON 12.1: LCD INTERFACING
I Input
l Input
~ H-to-L
I High
~ 80Hand COH

SfCTION 12.2: KEYBOARD INTERFACING


I. True
l Column3
l True
t 0
;. True


'•

nt
CHAPTER 13

ADC, DAC, AND SENSOR


INTERFACING

OBJECTIVES

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

interface ADC (analog-to-digital converter) chips to the 8051


Interface temperature sensors to the 8051
Explain the process of data acquisition using ADC chips
De:,cribe factor. to coru.1der in ;,elecnng an ADC chip
De!.cribe the funchon of the pins of 804/809/848 ADC chips
Dcscnbe the function of the pins of thl' MAXl 112 serial ADC chip
Interface serial ADC chips to the 8051
Program !>Crial and parallel ADC chips In 8051 C and Assembly
Descnbe the bab•C operation of a DAC (digital-to-analog converter) chip
Interface a DAC chip to the 8051
Program a DAC chip to produce a sine wave on an oscilloscope
Program DAC chip, in 8051 C cU1d A.sembly
Explain the function of predMon IC temperature sensors
De,,cribe ,ignal conditioning and its role an data acquisition

321
I .
analog-to-digital conve~ters), DACs (digil.lJ
ch as Af)Cs ( h 8051 to these devices. In Section 13 1 ~
,
Id devu:es su · rface t e 1.: ADC0804 ADC · '"
This chapter explores some more real-wor lain how to u,te b ·t arallel ADC c, ups . ' OSOstO&);'
analog converters), and sensors. We will also ~ewiJlstudythe~e ~aracteristics of DAC ch1r~ are discusSEI! -'
describeanalog-to-digitalconverter (ADC) cllif'SDC chip MJ\Xt112. . ss the issue of SJgnal cond.itiorung.
and AOC:0848 We will also look at the se;1aJ A cin of sensors and dtsCU
Ii •
Section 13.2. In Section 13.3, we show the Ulterfa g
,'
/ SECTION 13.1: PARALLEL ANO SERIAL AOC . DC chips to nucrocontrollers. First, wedeso;betht
JJ J and serial A DC0808 / 0809 and A DC0848 cha
This section will explore interfacing of both par• e en we examine the A . . DC . ra~r-
AOC:0804 chip, then show how to interface it to the805l~: d of this section, we describe the serial A chip MAX1111
istics and show how to interface them to the 8051. Al th
and program it in both in C and Assembly.
,. I

ADC devices • · ··
sed devices for data acquisition. Digtt
· al computers use
Analog-to-digital converters are among the most wtd~1Y ~ alo (continuous). Temperature, pressure (wind 0
i::I binary (discrete) values, but in the physical world every~ing ,s an .h. g that we deal with every day. A physical q r
· are a ',ew examples of physical
• 'd), h um,'d',ty, and ve1oc,ty
I,qui · quantl· eslied' transducer Transducers are also f uan.
,I tity is converted to electrical (voltage, current) signals using• device ca a
I titi d
to as seirsors. Sensors for temperature, velocity, pressure, light: ~nd many other natura quan es pro_ uce an o~tput
re erred

that is voltage (or current). Therefore, we need an analog-to-digital converter to ?'anslate _the analog signals to digital
fJ( numbers so that the microcontroller can read and process them. An ADC has n-b,t re~ok1tion where n can be 8, 10, 12,
16 or even 24 bits. The higher-resolution AOC provides a smaller step size, where step size 1s the smallest change that can
I
·' be discerned by an ADC. This is shown in Table 13-1. In this chapter we examine several 8-bit ADC chips. In addition
' to resolution, conversion time is another major factor in judging an ADC. Co11uersio11 time is defined as the time it takes
the AOC to convert the analog input to a digital (binary) number. The ADC chips are either parallel or serial. In para], t
lel ADC, we ~ve 8 or more. pins dedicated to bringing out the binary data, but in serial ADC we have only one pin for t
data out. Senal AOCs are discussed at the end of this section.

ADC0804 chip
The ADC0804 IC is an 8-bit parallel AOC in the family of the ADC0800 · · ·
national.com). It is also available from many other manuf tur ser:ies from National Semiconductor (www.
I
1n the AOC0804, the conversion time varies dependin on.~e ~rs. _t wo~ks with +s. volts and has a resolution of 8 bits.
be faster than 110 µs. The following is the ADC0804 ~ d . ocking signals applied to the CLI< IN pin but it cannot
pUI escnption. '

cs
Chip select is an active low input used to activate th ADC
e 0804 chip· To access the ADC0804, this pin must be low.
RD(resd)
. This is an input signal and is active low. The A
an internal register. RD is used to get the converted~ :nverts the analog input to 1·ts b' . . .
a out of the ADC0804 hi mary equivalent and holds it 111
c p. When CS = 0, if a high-to-low pulst
Table 13-1· Resoluti
rr-bit
.
Numb
on vs Ste
·

P 1:i;e for A.DC
er of s teps
8 256 Step Size (m V)
lO 1024 51256: 19.53
l2 4096 5/1024: 4.88
16
65536 5 I 4096 = 1.2
N<Jlt1· Vn; • 5 V
Strpsrze(.....,luhon)bth 5/65536:: 0.076 -

'
T1-r1:sos1r.u
CRoc oNTROL
LE& AND EMBEDDED svsrfMS
-
'
lied to the RD pin, the 8-bit digital output shows up at the DO_ D7 data pins. The RD pin is also referred to as
I 1Pl'1""able (OE).
~utpU

Wfi (wrlte; a better name might be "start conversion")


lhis is an active low input used to inform the AlX0804 to start the conversion process. lf CS= 0 when WR
Jo ·-to-high transition, the ADC0804 starts converting the analog input value of v,. to an 8-bit digital number.d
e
rna:s
1 ':ntof time it takes to convert varies depending on the CLK [N and CLK R va lues explained below. When the ata
:.ersion is complete, the INTR pin is forced Jo,v by the ADC0804.

CLK INand CLK R


CU( IN is an input pin connected to an external dock source when an exten,al clock is used for timing. However,
d,el!OI has an internal clock generator. To use the interna l clock generator (also called self-docking) of the ADCOB04,
111eCLK IN and CLK R pins are connected to a capacitor and a resistor, as shown in Figure 13-1. In that case the clock
1,tquency is determined by the equation:
If
II' I= i
.. J.l RC
d
T)'pical values are R = !OK ohms and C = 150 pP. Substituting in the above equation, we get f = 606 kHz. In that
•II case,theconversion time is 110 µs.
1,
•• //fTR (Interrupt; a better name might be " end of conversion")


11-
This is an output pin and is active low. It is a normally high pin and when the conversion is finished, it goes lo,v
loggn.,J the CPU that the converted data is ready to be picked up. After 1NTR goes low, we make CS = 0 and send a
:r high-to-low pulse to the RD pin to gel the data out of the AlX0804 chip.

v. (+) and V,. (-)


These are !_he differential analog_inputs where v,. = V,,. (+) - V.. (-). Often the Vm ( - ) pin is connected to ground and
the v. (+) pm 1s used as the analog input to be converted to digital.
.
r.

" AOCOS04
+SV

20
r. 10k 6 Vee
POT • 7 Vin(+) 18
Vin(•) 00 17
I 8
AGND DJ

•.. -~ 9
19
Vref/2

CLKR
D2 15
D3 14
D4
16

LEDs

!Ok
. 4 D5 12
13

CLK in D6 11
--
150pF -- 1
cs
D7
2 3
RD WR
10 5
DGNO INTR

--
I V Range
(ADC0804)
VI
T able 13-2: V ttl'

Va/
2 (V)
not coMected·
12 Relation to
V CV>

O10 5
..,
;n Step Size (m

5 1256
_ J953
4/255 = 15.62
I
2.0
O10 4 3/ 256 = 11.71

1.5 O103 2.56/ 256 = 10


oto 2.56

'
.../
,
1 !
., V
cc d as a reference vo
ltage wh.en rh.e V,./2 input (pin 9) is open (not
,,,•) This is the +S volt power supply. II is also use '
connected). This is discussed next.
..I
I 12

r
V'"' If Uus in is open (not connected), the analo~ input voltage
Pin 9 is an input voltage used for the reference voltage. th V p in). However, there are many applications where
for the ADC0804 is in the range of Oto 5 volts (the same as e
the analog input applied lo V. needs to'?" other than. the to+O 5J
an e v /2 is used to implement analog input
f
rds ·be Oto 4 volts, V /2 is connected to 2 volls. (
' voltages other than O10 S V . For example, 1f the analog mput range nee 0 ..i
Table 13-2 shows the V'" range for various V.../ 2 inputs.

r
DO-D7
DO - 07 (07 is the MSB) are the digital data output pins since ADC0804 is a parallel ADC chip. These are tri-stale a
buffered and the converted data is accessed only when CS= 0 and RD is forced low. To calculate the output voltage.
use the following formula.

p
D = V~
.
"' steps,u

where D.., = digital data output (in decimal), V


change, which is (2 xv,,/2)/256 for ADC0804. •
=analog input voltage• and step s12e
· ( I · } • th
reso ution 1s e sma
llesl

Analog ground and digital ground


These are the input pins providing the ground for both th .
connected to the ground of. the. anaJ.og v,, while digital groun~ :snalog signal and the digital signal. Analog ground IS
that we have two ground pms 1s to isolate the analog v . connected to the ground of the v pin The reason
11
the output DO- D7. Such isolation contributes to theaccu":-!~gn:r rom_ transient voltages caused by d~ital ~"itching ol
nccted to the same ground; however, in the real 1vorld of drta 1Jthe ~l~tal data output. In our discussion both arecon-
separately. cqu,s,tion the analog d d · . al ' h dled
From this discussion we conclude that the foUo . an 1g1t grounds are an
chip. wmg steps must be follow
ed. for data conversion by the A[)C08()l
1. Ma.ke CS = 0 and send a low-to-high pulse to in WR.
2. Keep monitoring the INTR pin. If INTR is lowpth to start the conversion
high, keep poUing until it goes low. ' c conversion is finished an~ w .
3. After the INTR has become low, we make CS., e can go to the next step. If J.NTRIS
0
the ADC0804 IC chip. The timing for this Proces ~nd 5end a high-to-)
s 1s shown · ow Pulse t 0 th i,/
u, Figure 13.2 , e RD pin to get the data out
324
TliE 80S1 l\fJ<::Rrv-.
~ONTRot
lER ANO EMBEDDED SYsT£M5
,,,...
cs

I
-WR
I
'
'
DO- 07 Loaia out :
iNTR
Start conversion
-RD find conversion
'

Note: CS is set to low for both RD and WR pulses.


t
Read it

fipll'l3-2. Read and Write Timing for AOC0804


I


L
Clock source for ADC0804
the speed at which an analog input is converted to the digital output depends on the speed of the CU< input.
Acrording to the ADC0804 datasheets, the typical operating frequency is approximately 640 kHz at 5 volts. Figures 13-3
l!ld 13-4 show two ways of providing cloc.k to the ADC0804. ln Figure 13-4, notice that the clock in for the ADC0804 is
millg from the crystal of the mic:rocontroUer. Since this frequency is too high, we use D flip-flops (74LS74) to divide
!he frequency. A single D flip-Aop divides the frequency by 2 if we connect its Q to the D input. For a higher-frequency
•,. O)llal, you can use 4 Aip-Aops.

Programming ADC0804 In Assembly


. Examine the ADC0804 connection to the 8051 in Figure 13-4. The following program monitors the INTR pin and
bring;an analog input into register A. It then calls hex-to-ASCII conversion and data display subroutines.

"
_,..
+SV
ADC0804

;1
8051
P25 ro, VCC 10k. 150pF
1'2.6 WR CLKR V

CL!< IN +SV
Pl.O DO
Vref/2 1.28V
T
--
Vin (+l
-
Vin (- - t 10k

Pl.7 07 AGNO
es -- • POT

P27 INTR GND - ---


--
I
.
+SV
,...
AJJCCJ804
8051 _RD vcc +SV
1'2.S - CLKR
~
-~
XTAL 1'26 WR CLKIN
' DO
' 11.0592 c!:J Pt.0 '' ~

-
Vref/2
,MHz T XTA!.2 ' -- /) IOk
I
I -

-
VU1(+l
VU1 (·..... POT

' - AGND -
Lo ~,- ~-
-
Q 07
GND .....
PJ.7 ~
b\fffi
~ - I> 0 1'2.7
, '
I
•1:'
., LD
{ \ • LD Q LD Q Q
I
0 0 ... '- > 0 Use 4 to5 OFF to
'I
~
~ )
obtain the correct
74l.S14 frequency for the
I AOC chip

r '
RD BIT P2.5
. C lock from XTAL2 of the BOSl
Figurt' 134. 8-051 Connection to AOC080ol with

·RD
WR
INTR
BIT P2.6
BIT P2.7
,'.wR (start conversion) .
t •end~of~convers1on
MYDATA EOU Pl ;Pl.O·Pl.7=00-07 of the ADC804
MOV Pl,#OFFH ;make Pl• input
S8'!'B INTR
BACK: CLR WR ;WR•O
SETS WR
HERB, ;WR•l L-to·H to start conversion
JB INTR,HERE
CLR ;wait for end of conversion
RD
MOV
;conversion finished,enable RO
A,MYDATA ; read the data
ACALL CONVERSION
ACALL DATA DISPLAY ;hex-co-ASCII conversion{Chap 6)
SETS RD ;display the data(Chap 12)
SJMP BACK ;make Ro~1 for next round

For hex-to-ASCII conversion and data display, see Chapters 6 and 12, respectively.

Programming ADC0804 in C F

The 8051 C version of the above program is given below.


#include <regSl.h>
sbit RD • P2'5;
sbit WR= P2'6;
sbit INTR • P2'7;
sfr MYDATA = Pl;
void main()
{
unsigned char value;
MYDATA = OxP!";
INTR • l;
RO= l; I lmake Pl
//rnake INTRand input
WR • l;
//set Ro hi ~nd input
//sec WR hi:h
326

llie sos1 l\11cR.ocoN -


TROLLER ANO EMBEDDED SYS~ '
>1hile(l)
{
WR • O; //send WR pulse
WR s l; //L-to-H(Start conversion)
while (INTR =s 1); //wait for EOC
RD ~ O; //send RD pulse
value= MYDATA; //read value
ConvertAndDisplay(value), //(Chap 7 and 12)
RD = l;
}
l

Al)COBOB/0809 chip with 8 analog channels


Another useful chip is the ADCOSOS/0809 from National Semiconductor. See Figure 13-5. While the ADC0804 has
(t11yone analog input, this chip has 8 of them. The ADCOSOS/0809 chip allows us to moni tor up to 8 different analog
illpUIS using only a single chip. Notice that the ADC0808/0809 has an 8-bit data output just like the ADC804. The 8
analog input channels are multiplexed and selected according to Table 13-3 using three address pins, A, B, and C.
tnthe ADCOSOS/0809, V...,(+) and V.,.(-) set the reference voltage. If V.J-) = Gnd and V..,(+) = 5 V, the step size is
= =
;V/2j6 =19.53 mV. Therefore, to get a 10 mV step size we need to set V..,(+) 2.56 V and V..i(-) Gnd. From Figure
13.s,notice the ALE pin. We use A, B, and C addresses to select INO - IN7, and activate ALE to latch in the address. SC
jsro,startconversion. SC is the same as the WR pin in other ADC chips. EOC is for end-of-conversion, and OE is for
oulpllt enable (READ). The EOC and OE are the same as the lNTR and RD pins repectively. Table 13-4 shows the step
;izerelation to the V"'voltage.Notice that there is no V...,/2 in the ADC0808/0809 chip.

I
...... GND Vee
..
!NO Clock 00

1N7
.... AOC0808/0809

D7
Vref(+) EOC
Vref(-) OE
SC ALE C B A

(LSB)

Rg,ue u..s. ADC0808/0809

Table 13-3: ADCOSOB/0809 Analog Channel Selection


Selected Analog Channel C B A
!NO 0 0 0
!NI 0 0 1
!N2 0 1 0
!N3 0 1 1
IN4 1 0 0
INS 1 0 I
IN6 1 1 0
IN7 1 1 1
......__
4
tlc, DAc, ANO SENSOR INTERFACING
I V Range f o r
ADC0808/0809
Table 13-4: V,., Relation to '" Step Size (m V)
V1• (VJ 5/256 = 19.53
0105 4/255 = ]5.62
not connected
4.0
0 to4 3/ 256=J].71
2.56/256 =10
O to3
3.0
Oto 2.56
/ 2.56 2/256 7.81
2.0
Oto2 =
1/256 3.90
.) I
Oto 1

1 Steps to program the ADC0808/0809


., The following are steps to get data from an AOCOSOS/0809-

() . . b" A c
d addresses accord ing to Table 13-3.
1. Seleel an analog channel by providing ,ts to , 8, an

.I
1 2. Activate the ALE (address latch enable) pin. It needs an L-to-H pulse to latch in the address. See E'igure 13-6.
3. Activate SC (start conversion) by an L-to-H pulse to initiate conversion.
4. Monitor EOC (end of conversion) to see whether conversion is finished. H-to-L output indicates that the data is
D
(
converted and is ready to be picked up. U we do not use EOC, we can read tJ, e converted digital data after a brief
time delay. The del•)' size depends on the speed of the extemal clock we connect to the CLK pin. Notice that the
EOC 1s the same ns the INTR pin in other ADC chips.
·'
5. Activate OE (output ena~le) to read data out of the ADC chip. An L-to-H pulse to Ille OE pin wi ll bring digital dau
t out of the chip. Also nonce that the OE is the same as the RD pin in other ADC chips.

' to i~~ i;!'~~8~~0809 t~at terc is n_o self-docking and the clock must be provided from an external soum
cannot be foste; thanoli mic:!:in~~onvers1on depends on the frequency o f the clock connected to the CLK pin, ii
p

WR(SC)---

R0(0~ - - 1i- ---------------.I-~---


!
Al..E-~ ;

ADOR

EOC(lNTR)--'ri---------
00.07--~'I-------------~~...r-~-,
.
LATCH
ADDRESS
-+,--.i~ i.__:

j
LATCH
Fig1trr 13-(,. Selrcting • Cha11nel and Re•d T" .
IIJ\Jng for AO<:o3o9 DATA

328
lliE 80s1 ~11CRo
CO!lf~OLLE -
RAND EMBEDDED svsretS
+SV
--
-t;S~V
8051 ADC0809
• P2.5 RO(OE) VCC
'11.0592,-!.... XTALI P2.6 WR (SC) Vref (+) 2.56V
,MHz' J Pl .O DO
!NO
fNl- 10k
POT
TN2 -
1~3 -
' XTAL2
I4-
[ 6-
1~5
-
IN, - ~

D7 CLOC
O..-N Pl.7 Vref (·) -
INTR(EOC)~ -
S!&:!&:! P2.4
ALE
P2.7 -
Lo Q ABCG
Q- t ~--
Lo Q - Lo Q Lo Q
ii
If
Q 0 0
• 74LS74

iw,tt 13-7. 8051 Connedion lo ADC0809 for Channel 1

:t
Figure 13-7 shows the connections for the following programs.
I
Programming ADCOSOS/0809 in Assembly
ALE BIT P2.4
OE BIT P2. 5
SC BIT P2.6
EOC BIT P2. 7
ADDR A BIT P2. 0
ADDR B BIT P2 .1
ADDR_C BIT P2.2
MYOATA EQU Pl
ORG OH
MOV MYOATA,#OFFH ;make Pl an input
SETI! EOC ;make EOC an input
CLR ALE ;clear ALE
CLR SC ;clear WR
CLR OE ;clear RO
a.>.cK:
CLR ADOR_C ;C-0
CLR ADOR_B ;B•O
SETB ADOR_A ;A•l (Sel ect Channel 1)
ACALL DELAY ;make sure the addr ia stable
SETB ALE ;latch address
ACALL DELAY ;delay for fast OS89C4x0 Chip
SETB SC ;start conversion
ACALL DELAY
CLR ALB
CLR SC
kt,!:
JB BOC, H&RB ; wait until done
~
Ile, DAc, .\ND Sll!NIOa INTDJIAONG
I
. until done I
!fEREl: -wait ~n
JNB EOC, HEREl ';enaJ:>l e ""
SETB OE ,wait
ACALL DELAY • d data xt time
MOV A,MYDATA ·rea fol' ne J
' clear RD 6
CLR OE 1 (ChaP 12
)
'. hex to ASCI data (Chap
ACALL CONVERSION '.displ ay t he
ACALL DATA_DISPLAY •
SJMP BACK

Programm·1ng AOCOSOS/0809 In C
,. t ~include <reg5l.h>
sbit ALE• P2.4;
., sbit OE= p 2·s,
sbit. SC • P2"'~;
sbit EOC = P2 ?; t
.• ADDR- A= P2'0;
6 b 1... A

sbit ADDR_B • P2 . l;
sbit ADDR_C = p2 21
sfr MYDATA = Pl;
void main()
{
unsigned char va lue;
MYDATA • OxFF; //make Pl an input
soc • 1; //make EOC an i nput
t AL£ • 0; //c l ear ALE
OE= O; / / clear OE
SC= O; //clear SC
while(l)
{
ADDR_C • 0; //C•O
ADDR_B • 0; / /B•O
ADDR A = l; //A•l (Select Channel 1)
MSDelay(l);
ALE = l; / /delay for fast DS89C4x0
MSDelay ( l) ;
SC= l;
MSDela y(l);
ALE• O;
SC• O;
while(EOC••l ) ; //start conversion
while (EOC.•O) ; //wait for data conversion
OE = l;
MSOelay (1); //enable RD
value• MYOATA;
OE• O; //get the data
ConvertAndOi splay (value ) ; / / disable RD for next round
J //Chap 7 & 12
)

I
ADC0848 interfacing

The AOC:0848 IC is another analog-to-digital converter · th . ~


Semiconductor Corp. Data sheets for this chip <>an be follnd at~ . e fatniJy of the AOC:0800 series from Na to
Products > Analog-Data Acquisition> A-to-D Converter.r.. al Petr Web site, WWW national com From there, go
=er urpose. . . •
330

°fJ{l! 8051 ~CR<>c .. -


ONTROLLl!R AND EMBEDDED SYllil- -
AJJCOS48 has a resolution of 8 bits. It is an 8-channel AOC, thereby
~e it 10 monitor up to 8 different analog inputs. See Figure 13·8. The
,lk!~ chip in the same fami ly has 4 channels. The foUowi.ng describes 1 RD vcc 24 0
A
11,t pLflS
or
the AOC0848.
CS23 0
2 CHI
3 CH2 i¥R22 0
cs
(hip select is an active low input used to activate the 848 chip. To access
-
lNTR 21 0

11><'&18, this pin must be low. S Cl-14 OB0/MA020 0


DBI / MAJ 19 0
RO(read) 7 CH6 DB2/ MA218 0
RO is an input signal and is active low. ADC converts the analog input 8 CH7 DB3/MA.317 0
·isbinarY equivalent and holds it in an internal register. RD is used to get
:ronverted data out of the 848 chip. When CS= 0, if the RD pin is asserted 9 CHS D84/MA416 0
loW, the3-bit digital output shows up at the DO · 07 data pins. The RD pin 10 AGND 05515 0
~also referred to as output enable (OE).
11 Vref 08614 0

,., 12 DGND 06713 0

vis an input voltage used for the reference voltage. The voltage con-
~ t o this pin dictates the step size. For the ADC0848, the step size is Figure 13-8. AOC0848 Chip
YJ256since it is an 8-bit ADC and 2 to the power of 8 gives us 256 steps.
See Table 13-5. For example, if the analog input range needs to
1,e0to4 volts, V..., is connected to 4 volts. That gives 4 V/256 = Table 13·5: ADCOS48 Vref vs. Step Size
15.62 mV for the step size. In another case, if we need a s tep size
=
o/ JOmV, then V..., = 2.56 V, since 2.56 V/256 10 mV. V (V) Step size (mV)
5 19.53 (SV /256)
OBO-D87 4 15.62 (4V /256)
D80 - DB7 are the digital data output pins. With a DO · 07 2.56 10 (2.56V /256)
output.the 848 must be an 8-bit ADC. The step size, which is the 1.26 5
111allest change, is dictated by the number of digital outputs and 0.64 2.5
the V,. voltage. To calculate the output voltage, we use the fol- •
lowing formula; Note: Step saze = V,,.,./256.

Dlit;, = ~.J

step size
where D.. = digita l data output (in decimal), Vm =analog input voltage, and s tep size (resolution) is the smaUest
changt-, which is V"'/256 for an 8-bit ADC. See Example 13-1 for clarification. Notice that DO. D7 are tri-state buffered
llldthat the converted data is accessed only when CS= 0 and a low pulse is applied to the RD pin. Also, notice the dual
role of pins DO. 07. They are also used to send in the channel address. This is discussed next.

Exuiplet3-t

~ ~ t~en ADC0848, we have V"' = 2.56 V. Calculate the DO. D7 output if the analog input is: (a) 1.7
21
v, and

Sot111ion:
•}:1ee ~Slep ueit2.56/ 2S6 • 10mV, we have the following.
(b\ g.. •
1.7 V/ 10 mV • 170 In decimal, which gives us 10101011 in binary for D7 -DO.
• .. • 2.1 V/ lOmV •2101ndec:lmal. which gives us 11010010 in binary for 07 .00,
..

~ C , ANO SENSOR INTElll'ACING


I ......

[)()/ MAO
Vee DI/ MAl
GND '
CHI D2/ MA2
D3/ MA3
D.J/ MA4
ADC0848
...
CHS D7
AGND
J JNTR
. _/ Vrel
WR cs RD
'I
-,

' l Figuro 13-9. AOC0848 Blc><k Oiog"'m
~
/ MAO - MA4 (multiplexed address)
. · to select the channel. Notice in Figure 13-9 that a portion of the
The A~OS48 uses mul~plexed addrc.ss/data pms • ins are inputs when the charu,el's address is sent in I
D 080 - DB7 pms are also designated _as ~AO· MA . The 4 00 07
p ts While the use of multiplexed address/datasal'es
( However, when the converted data 1s bemg read, DO· 07 a~e outpu ·
,, some pins, it makes 1/ 0 interlacing mo re difficult as we w,11 soon see.
I p
't WR (write; a better name might be "start conversion")
This is an input into the ADC0848 chip and plays two important roles: (1) It latches the address of the selected
channel present on the DO - 07 pins, and (2) it informs the Atx:0848 to s tart the conversion of the analog input at IN!
s
channel. If CS = Owhen WR makes a low-to-high transition, the Atx:0848 latches in the address of the selected chan-
nel and s tarts converling the analog input value to an 8-bit digital number. The amount of time it takes to convert isa
maximum of 40 µs for the ADCOS48. The conversion time is set by an internal clock.
I.
CH1- CH8
CH1 · CH8are8channelsoftheV analog inputs lnwhatis<:alleds' gl
10
used for analog V.,. where the AGNO (;nalog ground) in is used e-ended mode, each of the 8 channels can bt
ncls of input allow us to read 8 different analog Si na~ but t ~•ground reference for all the channels. These 8 chan·
output. We select the input channel by using the ~O _'MA no a . at the same time since there is only a single DO· U1
4
13-6, notice that MA4 = low and MA3 = high for single-ended :uodltaplexed address pins according to Table 13-6. In Table
e. The ADC0848 can also be used in differential mode.
Table 13-6: ADC0848 Analog Chan nel S I .
Selected Analog Channel MA
e echon (s·mg1e- Ended Mode)
4
CHI MAJ MA2
0 1 MAl MAO
CH2 0
0
1 0 0
CH3 0
0 0 1
CH4 1
0 0 1
CHS I 0
0 0
CH6 I 1 1
0 1
CH7 1 0 0
0 1
CHS I 0 1
0 1
Nair Ch.lnnello,elec1,'<l when CS. 0, IID•I d l I
• iln •n L-lo-J.J ] 0
J>Ul.o is applJed l
lo IVR. I
332

T1iE 8051 MlcRo -


CON~ROLL __ .-1!16
ER AND l!MBEODEDSTlJ'....-
~
.~tial mode, two channels, such as CHl and CH2, are paired together for the V..<+) a_nd ..(-) differ~!;::~~
11Ji lJ1 that case V~ = CH I (+) - CH2(-) is the differential analog input. To use ACX:0848 lfl d,fferenhal m e,. 1
f'f,~,and MA3 is set to low. For more on this, see the ADC0848 data sheet on the www.national.com Webs, e.
;to

r/J y is the+ 5 volt power supply.


(C

~GIID, DGND (analog ground and digital ground) .


Both are input pins providing the ground for both the analog signal and the djgital signal. Analog ground ,s con·
r,ected IO the ground of the analog V ~ while digital ground is connected to the ground of the Vq: pin. The r~ason that
tha•e two ground pins is to isolate the analog v signal fron, tra,15ient voltages caused by d1g1tal sw itching of the
~ t 00 • D7. Such isolation contributes to the a;curacy of the digital data output. Notice that m the single-ended
lll)de the voltage at the channel is the analog input and ACND is the re ference for the v,•. In our_ ~1scuss1on, both the
,c;.,roand DCN0 are connected to the same ground; however, in the real world of data acqu1s1tion, the analog and
digiWgtoWlds are handled separately.

he ,ml (/nte"upt; a better name might be " end of conversion")

...
in. This is an output pin and is active low. It is a normally high pin and when the conversion is finished, it goes low to
;,gnal the CPU that the converted data is ready to be picked up. After INTR goes low, we make CS= 0 and apply a low
pulse to the RD pin to get the binary data out of the ADC0848 chip. See Figure 13-10.

Selecting an analog channel


The following are the s teps we need to take for data conversion by the ADC0848 chip.

t While CS= 0 an~ RD= I provide the ~ddress of _the selected channel (see Table 13-6) to the DBO - DB7 pins, and
apply a low-to-high pulse to the WR prn to latch ,n the address and start the conversion. The channel's addresses
are 08H for CHl, 09H for CH2, OAH for CH3, and so on, as shown in Table 13-6. Notice that this process not only
selects the channel, but also starts the conversion of the analog input at the selected channel.

WR----.
m---__.;__________

TRIN-----'-----~~~

MA~MA4
1)().[]7 ---~I MA~MA4 f----------~~---
· 00-07 f--

LATCH LATCH
ADDRESS DATA

....... 13-10. Stloct1n11 • Owtnel ond llead Tlmln11 for the ADC0848

"Ile. DAc, .\ND SENSOR INTDFACING


I
+5V

10k
POT

...
~
AGND
I DGND
-•.'
1 •
=
.
• I

i: . to A OC0848 (or Channel 2


Figure 13-11. 8051 Connection

I w the conversion is finished and wee.an


INTR goes lo '
. rr-.:1:k~s
R · When · · end_-of.conversion.
·

r
2 WhileWR =l and RD = J keep n'.onitormgthe polling until it goes Jow, signalling
· go to the next step. l( fNTR ,s high, we keep the WR _ d apply a low pulse to the RD pm to get the data
3. After the INTR has become low, we mus·t makeCS -0 - ' - 1• an
out of the 848 IC chip.
·'
'
ADC0848 connection to 8051 . .
••
The following is a summary or the coMection between the 8051 and the ADC0848 as shown m Figure 13-11 .

P1 .O-P1.7 DO- 07 of ADC: Channel selection (out), data read (in}


P2.7 to INTR P2.7 as Input
P2.6to WR p
P2.6 as output
P2.5 to RO P2.5 as output
Notice the following facts about Figure I'.>-11.

1. P2 is an output when we select a channel, and it is an input when we read the converted data.
2. We can monitor
the converted the lNTR pin of the ADC for end-of-conversion or we can wait a few milliseconds and then read
data.

Olsplayl ng ADC0848 data

In order to display the ADC result on a screen or LCD, it must be conv r . h w·


ever, it must first be converted to decimal. To convert a 00 _PF h e te~ to ASCII. To convert it to ASCII, . O
remainder is less than 10. Each time we divide it by 10 we kee ·~:•Iue to decunaJ, we keep dividing it by 10 uotil the
of an 8-bit data, dividing it by 10 twice will do the job. For ex P e uotient as one of our decimal digits. In the case
t' 1
convert from decimal to ASCIJ format, we OR each digit with;:I 1 we have Pl'H it will become 255 in decimal. To
digits to the PC screen using a serial port, or send them to th LCD see Chapter 6). Now all ,ve have to do is to send the
e ' as was sho,vn in the Chapter 12.
Programming ADC0848 in Assembly
The following program selects channel 2, reads the data
'and calls corwersio .
cs BIT P2. 4 n and display subroutines.
RD BIT P2.S

334
WR BIT P2.6
!NTR BIT P2.7
ORG OH
SETB INTR ;make INTR an input
SE'l'B cs ;set Chip Select high
SETB RD ;Set Read high
SETB WR ;set Write high
a1<CK:
MOV Pl,#OAH ;Chan 2 address(Table 13-6)
NOP ;wait
CLR cs ;chip select (CSsO)
CLR WR ;write= LOW
NOP ;make pulse width wi de enough
NOP ;for DS89C4x0 you might need a delay
SETB WR ;latch the address and s t art conv
SE'l'B cs ;de-select the chip
MOV Pl,#OFFH ,make Pl an input
HERE:
JB INTR ,HBRB ;wait for EOC
CLR cs ;chip select (CS=O)
II\
CLR RD ;read RD=O
NOP ;make pulse width wi de enough
la NOP
SETB RD ;bring out digit al data
MOV A,Pl ;get the value
SETB cs ;de-select for next round
ACALL CONVERT ;convert to ASCI I (Chap 6)
ACALL DATA_OISPLAY ;display the data (Chap 12)

Programming ADC0848 In C
The following prog:ram selects channel 2, reads the data, and calls conversion and display subroutines.

!include <reg51. h>


sbit CS • P2A4;
sblt WR c P2AS;
1bit RD • P2A6;
sbit INTR • P2A7 1

•1oid main()
{
unsigned char value;
lNTR = l; //make INTR an input
cs • l;
WR • l;
RD• 1;
whi le (l)
{
Pl oxOA;
D
//Chan 2 addr see Table 13-6
CS• O; //chip s elect
WR= O; //wr ite•WW
Delay() ; //make pul se wide enough
WR• l; //L·to-H to l a tch addr
cs. l; //de - sel ect
Pl• OxFF; //make Pl an i nput
while(INTR••l)1 //wa it for BOC

.\be, DAc, AND SENSOll lNTDJIACINC


I //chiP select
cs• 0; ;;read
RD = O;
data
Delay(); // read t he
RO• l; the value
//get
value• Pl;
cs. l; //Chap 7 & 12

I }
l
ConvertAndI>isplay(value);

I
f the parallel type. The DO - D7 data pins of !he
-•.
1 • Serial ADC chips
O
AU the AOC chips we have discussed so far have b~,nb t,. •een the AOC chip and the CPU. In the case of the
r' ) AOC0848/0808/0809/0804 provide a~ 8-bit parallel data P~ rec:n; years, for many applications where space isao;lj.
16-bit parallel AOC chip, we need 16 pins _for the data ~·~;t feasible. For •
cal issue, using such a large number of pms for data JS widely '
~I .
this reason, serial devices such as the senal. ADC are ~com~ Maxim
used. Next, we examine the MAX1112 senal ADC chip fro . .th

r
Corporation (www.maxim-ic.com), and show how to interface ti wt
the microoonlroUer. 0 1 CHO VDD 20

0 2 CHl SCU< 19
'l MAX1112 ADC D 3 CH2
, The MAXl 112 is an 8-bit serial ADC chip with 8 channels of ana-
log input. II has a single Door pin to bring out the digital data after it
0 4 Cl-13
CS 18
DiN17
has been converted. It is compatible with a popular SP! and Microwire D 5 CH4 SSTRB 16
serial standard. The following are descriptions of the MAX1112 pins.
(See Figure 13-12.) 0 6 CHS Dovr 15 s
D 7 CH6 DGN014

CHO-CH7 D 8 CH7 AGNDJ3


D 9COM REFOUT12
O!O - CH7 are 8 channels of the analog inputs. In the single-ended
mode, ~ach of the channels can be used for an analog input where the D 10 SHON REFIN 11
COM pm lS used as a ground reference for all the channels In · l
ended mode, 8 chaMels of input allow us to read 8 diff~ t sm~ e-
inputs. W~ select the input channel by sending in !he con- n ana og
Figure 13-U. MAXllU Chip
trol byte v,a the DIN pin. In differential mode, we have 4
sets of 2-channel differentials. CHO and CHI go together
and CH2 • CHJ, and so on. '

I I I
..
COM CHO AGNDDGNO VDD
Ground reference for the analog input . ,
ended mode. in single-
MAXu12
SCLK .. •
0!7
cs
cs REF!N DIN
Chip select is an active low input used to
REFOUT OOlIT
1
~Xll12 chip. To send in the control byte vi:ect the SHUN SSTRB
pm, CS must be low. When CS is high the ~e ON
impedance. OCllrr IS high

Fi.s ure ll-13


336 · 1'1AJCtiu Ser1.i AOC Block Oiogram
Tl:fl! 80St 1'11<:Roc:
ONlltou."n
- ANO EMBEDDED sY5fOd
5CLJ( . ntrol byte, one bit at a time.
5erial clock input. SCLK is used to bring data out and send Ill the co

0# . . e H·to·L edge (falling edge) of SCLK.


Serial data out. The digital data is clocked out one bit at a ttme on th

O,. . th L to·H edge (rising edge ) of SCLK.


Serial dat,1 in the control byte is clocked in one bit at a tLme on e •

S5TRB . It goes high when the conversion is


. d ' tes end-of-conversion.
Serial strobe output. In internal clock mode this m ,ca
(llll\plete.

v(JD

...
V is the +5 volt power supply .

AGND, DGND (analog ground and digital ground)


Both ~re input pins providing ground for both the analog and the digital signals.

SHON
Shutdown is an input and is normally not connected (or is connected to V co>, If low, the ADC is shut down to save
po~er. This is shut down by hardware. The control byte causes shutdown by software.

REF/N
Reference voltage input. This voltage dictates the step size.

REFOUT
Internal Reference Generator output. A l µF bypass capacitor is placed between this pin and AGND.

MA.X1112 control byte


The MAXI 112 chip has 8 channels of analog inputs that are selected using a control byte. The control byte is fed
• Into the MAXI 112 serially one bit at a time via the D,,. pin with the help of SCLK. The control byte must be sent in with
!ht MSB (most significant bit) going in first. The MSB of the control byte is high to indicate the start of the control byte,
..• ~shown in Figure 13-14.

REFlN vottage and step size


-• The 6!ep siz.e for the MAXl112 depend~ ~n the voltage connected to the REFIN pin. In unipolar mode, with V re"' 5 V ,
tel4.o% V for full-<;eale 1f the RERN pm u; connected to the AGND with a l·µF capacitor. That gives us a 16-mV step
~llnce 4 096 V/'256,. 16mV. To get a 10-mV step si2e, we need to connect the REFIN pin to a 2.56 V e'Ctemal voltage

>.De, DAC. ANO SENSOR INTIIRl'ACING


I j
POI I PDO
I SE1.0 j lJN/ BIPl SGL/ DF I
[ Start I SEl.2 I SLEl

The MSB (07) must be high to


....,.,~~ing of the control byte.
define the ~.,uu• '•
St.rt
1t must be sent in /irsL N (SJNGI.E-ENDED MODE)
Sl!l l SELO O{ANNEL SELECflO
SEU
/ o O CHAND
0
0 O l CHAN!
0 I O CHAN2
0 1 1 CHAN3
., 1 0 0 CHAN4
1 ! 1 O 1 CHANS
., 1 I O CHAN6
• I 1 CHAN7
,' \ l

UNI/BIP 1 e unipolar: Digital data output is binary 00 · FFH.
O= bipolar. Digital data output is in 2's complement.
SGUOfF 1 = single-ended: 8 chaMels of single-ended with COM as reference
O= differential: Two chaMels (eg., CHO - CHI) are differential.
PO! I • fully operational
0 = power-down: Power down to save power using sofh,.are.
' PDO 1 a extemal clock mode: The conversion speed is dictated by SCLK.
0 = intemal clock mode: The conversion speed is d ictated interna lly,
and the SSTRB pin goes high lo indicate end--0f-conversion (EOC).
' Figutt 13-14. MAX1l12 Control Byte

8051
--
+SV

MAX1112 +_sy
1'2.0 -cs YDD
P2.J . SCLK SHON J--..J
1'2.2 DIN
1'2.3 CHO f - -
D0UT
CH1
CH2
t:------+--1~')
• '
CH3 1---
CH4 f - -
2.56V ,- CHs r---
REFJN CH6 t---
CH7 t---
luF ~
R£FOUT - '-
-
AGNO COM t---
--- DCNo .--..,,1

FigUtt 13-15. 8051 Connoclion to MAX1112 f


or 2nd Ch•nntl

338
al f e ce voltage must be between
,inct' 2.56 V/ 256 = 10 mV. According to the MAX1112 data sheet, the cxtem, re e r n
~~~-V . Notice the lower limit fo r the reference voltage.
II ~r,u ,.,

selecting a channel. N0 tic that the MSB (D7) of the control


WrS<'lcd the analog input ch annel using the control byte. See Exa mple 13·2. e ·
:tt 111u>t lie high. · d ks in the control by te on the
M the control byte is fed into the DIN pin one bit a t a time using SCLJ<. The DIN p m oc
o;u,g edge of SCLK as shown in Figure 13-16.
iAss81Dl>lY Code for sendin g in contro l b yte in
;!W<1112 , see Figure 13·15
CS BIT P2 . 0
SCLK BIT P2. l
DIN BIT P2 . 2
OOllT BIT P2. 3

HOV l\ , #9EH ;channel l selection


MOV Rl , #8 ;load count.
CLR cs ;CS;O
CLR C
Hl: RLC l\ ;give bit to CY
MOV DIN, C ,send b i t to DIN
CLR SCLK ;low SCLK f or L· H pul se
ACALL DELAY ;delay
SETB SCLK ;latch dat a, see Fig 1 3 ·16
l\CALL DELAY ; delay
DJ!IZ Rl, Hl ;repea t fo r al l 8 b i ts

E.wnple lJ-2
rmd the 1'1AXl 112 control byte for (a) CHO, and (b) CH3. Assume sin gle-ended , unipolar, intemal clock, and fully
opmbonal mode:;

Solution:
from F,gure 13-14, we hove the following:
l•l l!XXll 110 (SF ,n hex) (b) 101111 10 (S E ,n hex)

MAXI 112 lntcmol Clock Mode Tuning Dfogram


Srnding Control Byte into MAXI\ 12

'''
I
I
r
1 2 3 4 s 6 7 8
SCLK - - ~
I
, ,i i
,I I j I
'
DIN _J STtRT I st I1
S~ I
1
I sf juNtys1r!scLrou:1 P£1 I
: ! 1 I
p~
I
I
' '
t-;;;, tl-J6. S.nd lng Control Bytr into MAXll 12

~ DAC. AN D SENSOR INTERFACING


I ;de
select JIDC, C
~-o
onversion scares

conversion
during
SETS cs . 50,...,...
CLR SCLK ' HJIX1112 }l!)C
byte for
/ /C Code for eending iJl control
ijinclude <regSl.h> pigure 1)-15
//see
sbit CS= P2'0;
sbit SCLK • P2' 1 ;
/ sbit DIN= P2A2;
sbit OOUT • P2A3;
sbit MSBRA • ACCA7 ;
' void mai n (void)
v' {
unsigned char conbyte•Ox9B ; //Chan 1
unsigned char x;
1 J ACC•COnbyte ;
-, CS•O;
l• for{ x =O; X<8; x+ +)
{

OIN•MSBRA; //Send D7 of Reg A to Din


Delay() :
SCLK=l; //latch in the bit
Delay();
ACC = ACC << l; //next bit
l
CS=l; //deselect MAX1112
SCLK=O ; //Make SCLK low during conversion
r I
Start conversion and end of conversion for MAX1112
When the last bit of U,e control byte, PDO, is sent in, the conversion starts, and SSTRB goes low. The end1>I·
conversion state is indicated by SSTRB going high, which happens 55 µs after PDO is clocked in. We can either wail
55 µs, or monitor SSTRB before we get the digital data out of the ADC chip. Next we show how to get digital data out
of the MAX1112.

Reading out digital data


The 8-bit converted digital data is brought out of the MAXll 12 via th O · · I
negativ~ge pulse to the SCLK pin, the 8-bit digital data is read b' e 00! pm usmg SCLK. As we app Ya
•!
first. The SSTRB goes high to indicate that the conversion . . . ou I one It a tune with the MSB (07) commg oot
SSTRB goes high, the second falling edge of SCLK produces :et•sh~d. According to the MAXI112 data sheet, "afttf
we ne«l 9 pulses to gel data out. To bring data out CS mus t be SB of c~nverled data at the DO<IT pin. In other words.
' Iow. See Figure 13-17.

MAX1112 lnternaJ Clock M


Reading Data ADC ,,. Odpe Timing Oiagr~m
cs 8, ,e rorn MAxt 112

SCLJ< _ ___,

340

Tli1: sos1Micao -
CONTRQ ..~u~
LLER AND EMBEDDED 5y::,1.,.- '
4
'(1,e following is Assembly code for reading o ut d igita l da ta in the MAXI 112:

cs BIT P2.0
SCLK BI T P2. l
DIN BI T P2.2
OOUT BIT P2 . 3

SETB OOUT ;make it an input


CLR cs ;CS=O
SETB SCLK
ACALL DELAY ;need delay for DS89C4XO
CLR SCLK ;first H• tO• L
ACALL DLELAY ; read da t a out on 2ND H- to-L
CLR A
MOV R3,#B;
R2: 56TB SCLK;
DELAY ;need delay for DS89C4x0
ACALL
SCLK ;H-to-L pulse to get bit out
CLR
ACALL DELAY;
C,DOUT ;move bit to CY flag
MOV
;bring in the bit
RLC A
R3 ,H2 ;repeat for all B bits
DJNZ
SETB cs ;CS=l
Pl, A ; send converted data to Pl
MOV

/IC code for r eading data in MAX1112


Uncl ude <regSl . h >
sbit cs = p2•0;
sbit SCLK • P2 .l;
r,1- sbit DIN s P2"2;
llit sbit DOUT • P2.3 ;
,ut sbi t LSBRA = Acc•o ,

void main (void)


{

,.
IIUl
unsigned char x;
CS =O;
SCLK•l ;
//select maxl ll2
//an ext ra H-to- L pul se
rw Delay () ;
dt, SCLK=O ;
Delay () ;
for( x •O ; x<8; x++ ) //get a l l 8 bi ts
{
SCLK=l;
Delay () ;
SCLK: 0;
Del ay()
LSBRA=OOUT; //bring i n b i t from OOUT
/ /pin to DO of Reg A
ACC • ACC << l; //keep shi ft i ng data
//for all a bits
l
CS•l; //deselect AOC
Pl•ACC; //display data on Pl
l

~ . DAC, AND SENSOR INTIRPACING Hl


I
MAX1112 program In Assem bly
·Tl> fc>.10' >09 progr... se~ec~•
,r.........
• Ao t.be M)C <UtA
CS BIT P2 . 0
SCU: BIT P2. I
,
DIN BIT P2 . 2
DOUT BIT P2. 3

ORG OH

.. ,aending tn control
HAUis HOV A, •9EH
;chanllel 1
•• load count
1 • HOV R3. 1 8
• CLR CS ,cs-o
Hl 1 RLC A
;give bit: to CY
•send bit tO D1N
MOV D111.c
SCLl'
'.1ow SCLK for L·H pulse
CLR •
ACALL DELAY ;delay
' SETB SCLK •· latch data
AC.ALL O&LAY 1 delay .
OJNZ R3,Hl trepea t for all 8 bits
SETB
CS •daaelect AI)C, conv atarts
CLR SCLK ;SCLK•O during conversion
S£T8 DOUT 1111ake it an input
;Reading data out
r CLR CS 1CS•O
SETB SCLI<
ACALL DELAY :neod delay for DS89C4x0
CLR SCLK ;II.rat R • tO • L
ACALL DLELAY :read data out on 2ND H-L
MOV RJ,#8 I
H2 : SBTB SCLK ;
ACALL DELAY
;need delay for DS89C4x0
CLR SCLK
ACALL DELAY; :H-to-L pulse to gee bit out
MOV C, DOUT
RLC A ,move bit to CY flag
OJNZ RJ,H2
;bring in the bit
SET& CS ;repeat for all 8 bits
MOV Pl,A
:cs.1
SJMP MAlN ;display data on Pl
;keep doing it

MAX1112 program in C

//The following program selects the channel and


//reads ADC data
#include <regSl.h,
abit CS • p2•0;
abi t SCI,K • P2• 1;
abit DIN • p2•2:
abit DOUT • P2•3;
ebit MSBRA • Acc·1:
•bit LSBRA. Acc·o:

342


I
'd main (void )
.,Ol
(
unsigned char conbyt e =Ox9E; //Chan l
uns i gned char x·•
while (l )
{
J\.CC•conbyte; //selec t the channel
CSaO ;
for (x=O; x<8; x++ )
(
SCLK=O;
DIN=MSBRA; // send 07 of Reg J\. t o Di n
Delay();
SCLK• l ; //latch i n t he b i t
Del ay () ;
JI.CC a JI.CC < < 1 ; //next b it
l //deselect MJ>.)(111 2
CS= l;
//Make sCLK low during conver sion
SCLK•O ;
CSsO ; //read the data
//an ext ra H- to- L pul se
SCLK=l;
Dela y();
SCLK• O; //ge t all 8 bi ts
Delay ();
for(x s O; x <B; x++)
I
SCLK=l;
Delay () ;
SCLK=O;
Delay ()
LSBRA=D00T; //bri ng i n bi t f rom OOUT
//p i n to DO of Reg J\.
JI.CC = JI.CC << 1; //keep shi f ting data
// for a ll 8 bit s
)
CS• l; //deselect ADC
Pl • J\.CC; //display data on Pl
}

Review Questions
I. In the ADCOS04, the INTR signal is an - - - - {input, output).
l. In the ADC0804, to begin conversion, send a(n) pulse to pin _ _ __
3. Which pin of the ADC0804 indicates end-of-conversion?
4. Both the AOCOS04 and ADCOSOS/0809 are -bit converters.
5. Indicate the direction (out, in) for each of the following pins of the ACX:0808/0809.
(a) A, B, C {b) SC (c) EOC
6· In the ADC0848, the INTR signal is an (input, output).
7· In the AOC0848, to begin conversion, send a(n) pulse to
8· Which pin of the AOC0848 indicates end-of-conversion? ----
19 1lie ADC0848 is a(n) -bit converter.
~· Tru~or false. While the AOC0848 has 8 pins for Dour• the MAX1112 has only one Door pin.
1 md.kate the number of analog input channels for each of the following ADC chips.
l2. (l) ADCoso4 (b) ADC0848 (c) MAX1112
Explain how to select analog input channel for the MAXl112.

~ . DAC, AND SENSOll lNTBllfAONG


I
ON 13 2· DAC INTERFACING alog converter) to the 8051. Then we demonstrate .....
h-
SECTI . . . face a DAC (digital-to-an
This section wiU show how to inter . DAC.
SCO""
to generate a sine wave on the r· using the

Digital-to-analog (DAC) con ve rter . . , used to convert d"1g1·tal pulses to analog signals · ln thii
C) . a device w1del)
The dig;tal-to-analog converter (DA JS AC to the 8051. . DAC: binary weighted and R/2R ladde,
section we discuss the basics of inter~acing a Dth two methods of creating ~OBOB) used in this section, use the R/2Jt
Recall from your digital electtoru~ ~~~ !eluding the MC!408 (DA_t ·on for judging a DAC is its resoJutiol\
The vast majority of integrated circ~t h d:gree of precision. The first en er~O and 12 bits. The number of data bit
me~ha<! since it ~an achiev~ • m~of ~in:r inputs. 11,e common ones ·~~ i:vel~ is equal to 2•, where n is the numliE,
• 5
jI
1 • which ,s •. functihon of llhet· um/ the DAC since the number of analog outpd= 256 discrete voltage (or curre.nt) levels of
--, inputs decides t e reso u ,on o DAC0808 prov, ·~ . th
of data bit inputs. Therefore, an 8-input DAC su~ as the lta e levels. There are also 16-bit DACs, but ey are morp
output. Similarly, lhe 12-bit DAC provides 4096 discrete vo g
•l
expensive.

MC1408 DAC (or DAC0808) . .


ed tO rent (I ) and by connecting a resistor to the I
In the MC1408 (DAC0808), the digital inputs are convedrt db ~: pini; a function of the binary numbers at th~
pin we convert the result to voltage. The total current prov, e Y e 1-•
DO'. D7 inputs of the DAC0808 and the reference current (1..,), and is as follows:

07 06 05 04 03 D2 D1 DO)
1~, = I,.. ( 2+4+8+ 16 +32+ 64 + 128 + 256
t
where DO is the LSB, 07 is lhe MSB for the inputs, and I"' is the input current that must be applied to pin 14. The),.
current is generally set to 2.0 mA. Figure 13-18 shows the generation of current reference (setting I.. = 2 rnA) by using
the standard 5-V power supply and l Kand l.5K-ohm standard resistors. Some DACs also use the zener ctiode (LMJ36),
which overcomes any Ouctuation associated with the power supply voltage. Now assuming that I = 2 mA, if all the
inputs to the DAC are high, the maximum output current is 1.99 mA (verify this for yourself). "'

Ex~mple 13-3

For the circuit of Figure 13-18, find the maximum output ampl"tud f th
1
following program. e o e saw tooth waveform obtained with the
(a) HOV A,#0011
MOV Pl,A
BACK, INC A C
SJMP BACK
(b) MOV R0,#6411
RPT: HOV A, #OOH
BACK: HOV Pl,A
INC A
CJNB A,RO,BACK
SJMP RPT

Solation:
(a) Here, the method to generate the aaw IIDoth
In this case, the maximum value of the digi;ave Is l o ~ ~ A
"wnber is FFff "il ll 111';T.'• &'*• 0 lo PP lo Q,c,01111MSllllh•lllfli

TliE80s1 MlCRoc
Ofll'raotll!R AND EMBEDDED s\'S"fllld ~
D7 D6 D5 D4 D3 D2 !E.+E£.
, I,,.. =I"' ( 2+4+8+16+32+64+ 128 256

=2 mA X 255/256 =2 X 0.996 = I .99 D\A.


V.... = l.99mAx5 K =9.% V

n,e peak amplitude _of the saw tooth waveform is 9.96 V. 8


w 1·th the same calculation,
I
ib)ln this case, the maxunum value of the digital number is 64 H = 01100100 ·
I :0.78125 mA
r.
l
I.
..
{i :3.906 V

It
!r
ll

" +SV +SV

Sk Sk
8051 DAC0808
RO vcc
WR Vre.f (+)
...he Pl.O 1--- -.i 00
01 OUT
lk
TO
SCOPE
02
03
D4 Vref (·)
+
O.luFI Vout = 0
tolOV
05 =
06 Sk =
,..
ng
Pl.7 1---~ 07

ECOMPCN
6),
:he O.luF
-

-12V

Fig,u, IJ..18. 8051 Connection to OAC808

Converting 1.u1 to voltage In OAC0808


Ideally we connect the output pin 1.., to a resistor, convert this current to voltage, and monitor the output on the
!Cope. In real life, however, this can cause inaccuracy since the input resistance of the load where it is connected will
•lsoaffect the output voltage. For this reason, the ,... current output is isolated by connecting it to an op-amp such as the
ill ~ith R." SK ohms for the feedback resistor. Assuming that R = 5K ohms, by changing the binary input, the output
1<itage changes as shown in Example 13-4.

la lilt circuit of P1gure t3-18, a,nnect a twitch SW to pin PO.O. Write a program to do the following.
Ill When SW • o, the DAC oatpGt giv. a Mllirc:Be waveforn..
•>wt.sw . t,the~- --·~ wavefu.u,.
~Ile. DAC, AND SENSOR. INTE)lfACING
I
. ement of each step is 51. After~
"5 I 5 "'st. So the mer
Solution: f r 5 steps. Now 25th next cycle starts.
Let us design the staircase tputodrops to zero and e
waveform
maximum value IS reached. the ou

; SW EQU P0.0
/
ORG OOOOH swan input port
SETB SW ;mak e carry
., CHECK: MOV c,sw ; move SW t~ m to TRIANG
I. ' JC TRI ANG ;if SW=l, JU ~he staircase, A=O
. this is for
~ START: MOV A,#00 ' Pl
•·move A to
1

,'
'
• MOV Pl,A
ACALL DELAY ;delay
step
• RPT: ADD A,#51 ,add 51 to get the next
() Port 1
,,
~
MOV Pl,A ;output value to
ACALL DELAY ; delay , f not go to next step
CJNE A,#255,RPT k · f A=255 · 1 ' l
/ ,chec i ached maximum va ue
SJMP CHECK . the staircase has re. .

r
'. h k SW before continuing
,c ec is for the tri angu lar wave, A•O
·this
TRIANG: MOV A,#00
!NCR: MOV Pl,A ;output value on Pl
,, INC A ;increment A for upward transition
CJNB A,#255,INCR ;check if A•255, if no t k e ep incrementing
'r DBCR: MOV
DBC
P1,A
A
,output value on Pl
;decrement A for downward transition
CJNB A,#00,DBCR ;if A•O,the minimum., step out
SJMP CHECK :check sw before starting the next cycle
DELAY:
RE'Tl: MOV Rl,#2-0
RE'T2: MOV
;this delay routine gives a delay 'T'
R2,#200
RPT3: DJNZ R2,RPT3
OJNZ Rl, RPT2
OJNZ RO, RPTl
RET
ENO

Generati ng a sine wave

To generate a sine wave, we first need a table whose values les


between O and 360 degrees. The values for the sine functi represent the magnitude of the sine of ang
Therefore,thetablevaluesareintegernumbersrepresentin : var{ from -1.0 to +1.0 for 0- to 360-degree angles,
ensures that only integer numbers are output to the DAC ~ t~ vo tage inagn.ttude for the sine of theta. This method
the sine values, the voltage magnitudes, and the integer v j e SOSl m1crocontr0Uer. Table 13-7 shows the angles,
(with 30-degree increments). To generate Table 13-7, we a a ues representing the voltage magnitude for each anglt
designed in Figure 13-18). Full-scale output of the DAC. ss~ed the full-scale voltage of 10 y for DAC output (as
Therefore, to achieve the fuU-scaJe 10 V output, we use t~: ~cl ieved When all the data inputs of the DAC are high,
0
lowmg equation.
s
V... = V + (5 X Sin 0)
V~, of DAC for various angles is calcuJate,:1 and sh .
ca.lculations. own in 'l'abJe 13- See t'1e
7
· Example 13-5 for verification c,l

TlfEsos1 l'.ttcRoco
1'1TROLLER AND EMBEDDED SyS1915
Table 13-7: Angle vs. Voltage Magnitude for Sine Wave
v . I}
1 5 Sent to OAC (decuna
;\Jig.le 0 Sin 0 V0 . , (Voltage Magnitude) a u(eVolta e Mag. x 25.6)
(degrees) 5 V + (5 V x sin 0) g
- o ]28
0 5 192

-60 0.866 9.33


238
255
90 1.0 10
238
120 0.866 9.33
192
150 0.5 7.5
128
180 0 5
64
210 - 0.5 2.5
17
240 -0.866 0.669
0
270 1.0 0
17
300 - 0.866 0.669
64
330 o.s 2.5
128
360 0 5

Enmple 13-5
Verify the values given for the following angles: (a) 30° (b) 60°.

Solution:
(a) V.,. = 5 V + (5 V x sin 9) = 5 V + 5 x sin 30° = 5 V + 5 x 0.5 = 7.5 V
DAC input values= 7.5 V x 25.6 = 192 (decimal)
(bJV.., =5 V + (5 v "sin 9) =5 V +5 x sin60° =5 V +5 x 0.866=9.33 V
OAC input values = 9.33 V x 25.6 = 238 (decimal)

To 6nd the value sent to the OAC for various angles, we s imply multiply the V..., voltage by 25.60 because there
<re256steps and full-scale V..., is 10 volts. Therefore, 256 s teps I 10 V = 25.6 steps pe r volt. To further cla rify this, look
it the following code. This program sends the values to the DAC continuously (in an infinite loop) to produce a crude
!Int wave. See Figure 13-19.
.,,. AGAIN: MOV DPTR,#TABLE

~ MOV R2,#C00NT
llACK : CLR A

~ MOVC A, @A+OPTR
MOV Pl ,A
t<" I NC OPTR
OJNZ R2,BACI<
SJMP AGAIN
ORG 3 00
l'ABLl!: DB 128,192,238,255,238, 1 92 ;see Table 13- 7
OB 1 28,64,17,0,17,64,128
;To get a better looking sine wave, regenerate
;Tabl e 13-7 for 2-degree angles

~t>c, DAC, A.ND SENSOR INTEllfACING 347


I
ProgrammIng OAC in C
#include <regSl.h>
sfr Dn'CDATA • Pl;
void main()
238,255,
{ unsigned char WAVEVALOE [12) • {12s.192, 12s ,64,
23 8 192, )
'
17,0,17, 64 ,'

' unsigned char x;


V while(l)
{
I for(x=O;X<l2;x++)
1 •
,' { OACDATA = WAVEVALUE [xJ ;

(\
I l
l
l

Volts

10 r
9·-
8 ' ...
7 • ...
6 . +-
5
4 ...
3· f-

-
2 f-
I .
0 ' I
' ' I I I _J
. I
30 60 90 120 150 180 210 240 ' Degrees
. 270 300 330 360
Figure 13-19. Angle vs. Voltage M,gru
'tudt for Sine Wave

Review Questions

1. 1n a DAC, input is (digital, analog) and output is ----(digital analog).


2. In an AOC, input is (digital, analog) and output is (digital, analog).
3. DAC0808 is a(n) ·bit D-to-A converter.
4. (a) The output of DAC0808 is in (eurrent, voltage).
(b) True or false. The output of DAC0808 is ideal to drive a motor.

SECTION 13.3: SENSOR INTERFACING AND SIGNAL CONDITIONING


This section wiU show how to interface sensors to the lllicrocontroU . .
sors and then diseuss the issue of signal conditioning. Although w er. We examme some popular tempera~-~
discussed in this section axe the same for other types of sensors su~concentrate on temperature sensors, the pnnop
Temperature sensors as light and pressure sensors.
Transduarsconvert physical data such as temperature light . .
on the transducer, the output produced is in the fol"ll'J 'or vo;:ensity,Oow,andspee.j toelectJicalsignals. ~ .
I

I
ge, Cltrrent, resistance, or capacitance. For examplt,

'
Table 13-9: LM34 Temperature Sensor Series
ible 13-8: Thermistor
f ·sta11ce vs. Temp erature Selection Guid e Accuracy Output_
ReSI
~ r e (C)
~
Tf (K ohms)
29.490
Part Scale
LM34A
Temperature Range
-50 F to +300 F
+2.0 P
+3.0 F
tOmV/F
1omV/F
-
~ -50 P to +300 P
y-
10.000
3.893
LM34
LM34CA -40 p to +230 F
+2.0 F
10 mV/F
lOmV/F
-
9,1 +3.0F
:;.---- 1.700 LM34C -40 F to +230 P 10 mV /F
+4.0 F
~ 0.817 LM34D -32 F to +212 F
1ro
;;;1lliMl'l K1e1t2., Digital Electromcs Nolt: Temperature r"nge is in degrees Fahrenheit.

11!11\perature is converted to electrical signals using a transducer called a. tltermistor. A thermistor responds to tempera-
tutt change by changing resistance, but its response is not linear, as seen in Table 13-8.
The complexity associated with writing software for such nonlinear devices has led many manufacturers to
a,arket a linear temperature sensor. Simple and widely used linear temperature sensors include the LM34 and LM35
se,ies from National Semiconductor Corp. They are discussed next.

LM34 and LM35 temperature sensors


The sensors of the LM34 series are precision integrated-circuit temperature sensors whose output voltage is Lin·
wly proportional to the Fahrenheit temperature. See Table 13·9. The LM34 requires no external calibration since it is
internally calibrated. It outputs 10 mV for each degree of Fahrenheit temperature. Table 13-9 is a selection guide for
t!ie 1.M34.
The LM35 series sensors are precision integrated-circuit temperature sensors whose output voltage is linearly pro-
portional to the Celsius (centigrade) temperature. The LM35 requires no external calibration since it is internally call·
brated. It outputs 10 m V for each degree of centigrade temperature. Table 13-10 is the selection guide for the LM35. (For
further information see www .national.com.)

Signal conditioning and interfacing the LM35 to the 8051


Signal conditioning is widely used in the world of data acquisition. The most com- Analog world
mon transducers produce an output in the form of voltage, current, charge, capacitance, (temperature,
~ resistance. However, we need to convert these signals to voltage in order to send pressure, etc.)
input to. ~n ~-to-~ convert~r: Thls conversion (modification) is commonly called sig-
.,J co_nd11Jonrng. Signal cond1 tton1ng C3'.' be a current-to-_voltage conversion or a signal
!mpli6cation. For example, the thermistor changes resistance with temperature. The Transducer
change of resistance must be translated into voltages in order to be of any use to an ADC.

Signal
conditioning
~ble 13-10: LM35 Temperature Sensor Series Selection Guide
pill Temperature Range Accuracy Output Scale ADC
L'13sA 55Cto+150C +1.0C lOmV/C
lM3s -55 C to +150C +1.5C lOmV/C
Microcontrotler
-40Cto+UOC +1.0C lOmV/C
l.M:J::r
~ -40Cto+UOC +l.SC lOmV/C
Figutt l l-20. Getting
~D OC to+lOOC +2.0C tOmV/C Oat,, From the Analog
World
T""""•""" ••nge 1$ In degte<'S c;.lJius.

.\I>(:, 0>.C, AND SENSOR lN'fllFACING 349


I Look at the case of connecting an LM35 to an
ADCCJ848- Since
O f 2.56 (2'l
Table 13-11: Temperature vs. v f
ADC0848 .., or
V • (mV)
the Al)C0848 has 8-bit resolution with a maximum degree Temp. (C} 1 v,nu<D~
steps and the LM35 (or LM34) produces 10 mV for evezoco848 0 OOOOOOOQ'
of temperature change, we can condition V.. of the le output.
to produce a V..,. of 2560 mV (2.56 VJ for full-SC• 6 V for -
0
1
10 oooooooj--
Therefore, in order to produce the full-scale V,.., of Z.5 f the
the ADC0848, we need to set V"' = 2.56. This makes V,.., ~ ed 2
20 ooooooi:o-
,,,, AOC:0848 correspond directly to the temperature as monitor 3 30 0000001i--
by the LM35. See Table 13-11. 100 0000101;--
Figure 13-21 shows the connection of a temperature sensor to 10
the AOC0848. Notice that we use the LM336-2.5 zener diode to fix 30 300 000111]0-
the voltage across the 10K pot at 2.5 volts. The use of the LM336-
2.5 should overcome any fluctuations in the power supply.

1 •'
Reading and displaying temperature
The following two programs show code for displaying temperature in both Assembly and C. The programs ('Or.
respond to Figure 13-21.

I ;Program 13·1

(i ;Assembly code to read cemperature, convert it,


:and put it on PO wich some delay
lUJ BIT P2. 5 ;RD
( WR BIT P2.6 ;WR (scart conversion)
INTR BIT P2 . 7 ;end-of-conversion
MYDATA eou Pl ;Pl.O·Pl.7=00·07 of the ADC0848
• MOV Pl,#OFFH ;make Pl• input
r SETS INTR
BACK: CLR WR ;WR=O
SETS WR ;WR=l L•to-H to start conversion
HERE: JB INTR, Hl:1R8
;wait for end of conversion
CLR RD , conversion finished, enable RD

+5V

8051 ADC0848
P2.5 r---11~ iw
vcc
P2.6r--- .i WR
PLO i .--1..J 00/MAO
CHI 2.5k
OJ/MAJ CH2 LMJs
02/MA2 CHJ or
D3/MA3 CH4 LM34
D4/MA4 CHS
05 CH6
CH7
06 CHS
Pl.7 ~ - - - J 07
P2.4 t---1..I
P2.7
cs Vref (+)
INTR
AGNO
Set to 2,56V POT
DGNO
IOk

Figuro tJ.;n, 8051 Conntdion to ADC0848 .,,,_


and Tompera1..,. S
•nsor
350
Tli
ES0s1 MJC"
...oco..,,,TROLLER
,
AND EMBEDDED svsfPCS '
MOV A,MYDATA ;read the data f rom l\DC0848
ACALL CONVERSION ;hex-to-ASCII conversion

.. ACALL
SETB
DATA_DISPLAY
RD
BACK
; display the dat a
;make RD=l f o r next r ound

.. SJMP
coiNERSION:
.. MOV B,#10

.. DIV
MOV
MOV
AB
R7, B
B,#1 0
; l east significant byte

DI V AB
MOV R6,B
MOV RS,A ; most significant byte
RET

DATA_DISPLAY
... MOV
ACALL
PO,R7
DELAY
MOV PO,R6
ACALL DELAY
MOV PO , RS
ACALL DELAY
RET

//Program 13 - 2
/IC code to read temp from ADC0848, convert it to
//decimal, and put i t on PO wit h some delay
iinclude <regSl. h>
sbit RD • p2 ·s;
sbit WR = P2A 6 ;
sbit INTR • P2A7;
sfr MYDATA = Pl; // Pl connected to 00-07 of ' 848
void Conver tAndDispl ay (unsigned char val ue ) ;
void MSDelay (uns igned i nt value);
void main()
I //make Pl and input
MYDATA = OxFF;
INTR = l ;
//make I NTR and i nput
RD • l ;
// set RD high
WR = l; //sec WR hi gh
while (1)
{ •
WR • 0;
// send WR pulse
WR • l ;
whil e (INTR ~• l ) ; / /wait for EOC
RD • 0;
/ / send RD pulse
val ue • MYOATA; / /read value from ADC0848
Co nvertAndDisplay(value ) ;
RD• 1;
l
I
"Oid ConvertAndDisplay (unsigned char value )
I
unsigned char x, dl, d2 , d3 ;
X• val ue/10;

~Ile. D.\C, AND SENSOR IN11!RfAONG


dl•ValuetlO;
d2•><110
dl•></10 //LSBYce
PO•dl;
MSOelay(2SO);
POod2;
MSOelay (250); //MSByce
/ PO•d3;
MSOelay (250 l;
I
void HSOelay (uneigned int value)
~ I
I unaigned char x,y;
..,
1 •

( ,
for(x•O;x<v•lueix++)
for(y•O;yc127S;y++);
I
'
~

Review Questions . . circuitry before it is sent to the AOC.


b ted to signal condthorung
1. True or folse. The transducer must e connec ( (Fahrenheit, Celsius) temperature.
2. The LMJSprovides mV foreachdegreeo, (Fahrenheit,Celsius) temperature.
3. ThWhe LM34d pro,,•,th
'desv I Aocno:~:~t,fir::iog input is connected to the LM35?
4 y owese e .,o """° . ! 1001'
5. IJ'I Queshon 4, what ,s the temperature 1f the ADC output ts 00 I ·

I
SUMMARY
This chapter showed how to interface real-world devices such as DAC dups, ADC chips, and sensors to the 80Sl
Fust, we discussed both pa.rallel and serial ADC chips, then described how to interface them to the 8051 and program 11
in both Assembly and C. Next we explored the DAC chip, and showed how to interface it to the 8051. ln the last sectim
we studied sensors We also discussed the relation between the analog world and a digita l device, and described sip
conditioning, an essential leature ol data acquisition systems.

PROBLEMS
SEcnON 13.1: PARALLEL AND SERIAL ADC
I. Write a program segment to generate the start conversion pulse f ADC0804
2. To access the chip, what logic level should be given on the CS r or · Use pin Pt.O.
3. The ADC0804 1s a bit ADC. tne o1AOC:0804?
4. What is the function of the EOC pulse•
5. illnte a program segment to check if the ADC has fin· hed .
6. Cive a more elfident way of using the EOC output ~ f conversion.
O
7. IJ'I the ADC0804, what should be the V,,/2 value for a th~ AOC.
8. In the AOC0804, what should be the v../2 value for a step s~ze of 20 mV?
9. IJ'ltheADC080t,whatistheroleofptnSV (+)ad V stepsiieofSmV?
10. With a step &1/e of 19.53 mV, what is the ~log .n ., (- )?
11. With V../2 = 0.64 V, find the V for the follow· input voltage if all outputs
(a) 07 - DO • 11111111 ,. mg Outputs. are 1?
(b) 07 · DO= 10011001
(c) 07 ·DO= 1101100
12. Assume that the EOC pin of the AOC 080,t 15 CX>nn
to the 8051? ccted to pin PJ.2 of the
8051 · How IS the ADC output tr~
352
THE 8051 MlCRoco -
NTROLLER ANO EMBEDDED svs1od
\l'nich of the fol.lowing ~DC sizes provide the best resolution?
tJ (a)S-bit (b) 10-b,t (c) 12-bit
(d) t6-bit (~) !hey are all the same.
IJ\ ouesnon 13, which provides the smallest step size?
I~ caiculate the step size fo_r the following ADCs, i1 v.., is 5 V.
1 (a)&-bit (b) 10-b,t (c) 12-bit (d) 16-bit
rrue or false. ADC0808/0809 is an 8-bit ADC.
0
\ Indicate the direction (in, out) for each of the following AOCOSOS/0809 pins.
1. (a)SC (b)EOC (c)A,B,C
(d) ALE (e) OE {f) !NO - IN7
woo-01 . 1
IS. Explain the role of the ALE pin in the ADCOSOS/0809 and show how to select channel 5 a~a~g ~pu ·1 . es·
. In the ADCOSOS/0809, assume V..,{-) = Gnd. Give they.,,(+) voltage value i1 we want the o owing s ep siz ·
19
(a) 20mV (b)SmV {c)lOmV
(d)15 mV {e) 2 n,Y (f) 25 mV
io. 111 lhe ADC0808/ 0809, assume V,, (-) = Gnd. Find the step size for the follo,ving values of V..,(+):
1
(a) 1.28 V (b) 1 V (c) 0.64 V
11. 111 what way is the ADC0808 different from ADC0804?
!Z. How is a particular analog channel selected?
2J. What is the need of ALE on this chip?
ll. Assume that pins P0.0 to P0.2 of the 8051 is connected to pins A, Band C, respectively of the AOC0808. What should
be lhe ,,atues on the port pins to select.
(a) !NO (b)IN4 {c) IN7?
i;. What is the importance of the OE pin?
26' 111 lhe ADC0848, INTR is an {input, output) signal. What is its function in the A OC0848?
'!J. !'or an ADC0848 chip, find the s tep size for each of the following V..r
(a)V..,= 1.28V (b)V..,=lV (c)V..,=1.9V
28. In lhe ADCOS48, what should be the V.., value if we want a step size of 20 m V?
19. In lhe ADC0848, what should be the V.., value i1 we want a step size of 5 m V?
J>. ln lhe ADC0848, how is the analog channel selected?
151. ll. With a step size of 19.53 mV, what is the analog input voltage i1 all outputs are J?
nit ll With V.,. = 1.28V, find the V~ for the following outputs.
ion (a) D7-D0=11111111 (b)D7-D0=10011001 (c)D7-00=1101100
~ 3.l True or false. MAXl 112 is an 8-bit ADC.
34. Indicate the direction (in, out) for each of the following MAXll12 pins.
(a)CS {b) OOUT {c) COM
(d) DIN (e) SCU< {f) CHANO - CHAN7
(g)SSTRB
35. How many analog inputs and digital outputs has the MAX1112 ADC?
36. What advantage does a serial ADC offer?
37. Name two 8051 family members with inbuilt ADC.
38. For MAX1112 chip, find the step size for each of the following REFIN provided externally.
(a) REFIN = 1.28 V (b) REFlN = l V (c) REFlN = 1.9 V
39. In the MAX11 t2, how is the analog channel selected?
~- In lhe MAX11l2, what should be the REFIN value i1 we want a step size of s mV?
ll With REFIN = 1.28 V, find the V.. for the following outputs.
(a) 07- DO= 11111111 (b) 07 ·DO= 10011001 (c) D7 - DO= 1101100
~ The control by!e is sent in on the (positiveedge/~~gative edge) of the SCU< signal.
" Converted d1gital data is brought out on the (positive edge/negative edge) of the SCU< signal
~ What is the lowest REFIN value? ·
IS. It takes SCl.Ks to send in the control byte.
: It takes SCl.Ks to bring out digital data for one channel after the conversion is completed.
· When does the conversion start in the. MAXI 112? ·
48· How do we recognize end-of-conversion m the MAXl112?
iO. ~ t is the step size if REFIN ~ c~nnected to AGND with REFOUT?
19
single-ended mode, which pm IS used for ground reference for CHANO _ CHAN7?

AOc:, DAC, ANO SENS0Jl INTl!JD'AONG


I
SECTION 13.2' DAC!NTERFACING C
{Orm using a DA ·
51. Write a program to generate a saw tooth wave sin a DAC. . .
52. Write a program to generate a triangular w~ve~orm u gis this considered as an inbuilt DAC for these chips?
53. Some microcontroUers have inbuilt FWM orcu1trY· Why { DAC0808-
54. Find the I for the following inputs. Assume I"'= 2 mA or
(a) 10011001 (b) 11001100 (c) JllOtllO
(d) 00100010 (e) 00001001 ({) 10001000 fewer) di ·1a1 inputs.
/ 55. To get a smaller step, we need a DAC with (more, gi
56. To get full-scale output what should be the inputs for DAC?

SECTION 13.3: SENSOR INTERFACING AND SIGNAL coNDmoNJNG


..,
, .' 57. What does it mean when it is said that a given sensor has a linear output?
58. The LM34 sensor produces mv for each degree of temperature.
59. What is signal conditioning?
60. What is the purpose of the LM336 Zener diode around the pot setting the V.., in Figure 13-21?

ANSWERS TO REVIEW QUESTIONS


-I

SECTION 13.1: PARALLEL AND SERIAL ADC


1. Output
2. L-to-H, WR
3. INTR
4. 8
S. (a) all in (b) in (cl out
'I 6. Output
7. L-to-H, WR
8. !NTR
9. 8
10. True
11. (a)I (b)8 (c}S
12. We send the control byte to the DIN p·m one b'11 at a time.

SECTION 13.2: DAC INTERFACTNG


1. Digital' analog. Jn ADC the input ·
2. 8 is analog, the output is digit I
3. (a) current (b) true a•

SECTION 13.3·. SENSOR INTERPACING AND SIG .


I. True NALCONDJTIQN]N
2;~~us. G
3. 10, Fahrenheit.
4. Since ADC0848 is an 8-blt A . .
degree of temperatur . DC, ,t gives us 256
5. 00111001 = 57, wluch ~ :Uhich m_at_ches the ADC's ::eps, _and 2.56 V/256 -
m cates 1t 18 57 degrees ep size. - 10 tnV. LlvfJS
· P~mlO~b·

354


CHAPTER14

8051 INTERFACING TO
EXTERNAL MEMORY

OBJECTIVES

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

> Contrast and compare various types of semiconductor memories in terms of their capacity, organ·
ization, and access time
Describe the relationship between the number of memory locations on a chip, the number of data
pins, and the chip capacity
> Define ROM memory and describe its use in 8051-based systems
Contrast and compare PROM, EPROM, UV-EPROM, EEPROM, flash memory EPROM, and mask
>
ROM memories
> Define RAM memory and describe its use in 8051-based systems
> Contrast and compare SRAM. NV-RAM, checksum byte, and DRAM memories
> Ust the steps a CPU follows in memory address decoding

·- >
>
>
>
Explain how to interface ROM with the 8031 / 51 /52
Explain how to use both on-chip and off-chip memory with the 8051/52
Code 8051 Assembly and C programs accessing the 64l<-byte data memory space
Show how to acce96 the ll<-byte RAM of the DS89C4x0 in Assembly and C
I .
In this chapter we disruSS how to mterface e or ROM. In Section 1
1
4
n,enlory. tnSection 14.1 westudysemic:ond
th BOJ1 /51 / 52 to ext~rna 2 address decocting concepts are discu ~
Mand RAM, respectively. We will also e~· 1,,
memory concepts with ernphasJS on different -~ ~cing with external RO ccess external data memory in C lll1rt
Sections 14.3and 14.4, weexplore8031 / 51 / 52 mt. we will show t,ow to a ·
14 5
the J K-byte SRAM of the DS89C4x0 chip. In 5ection ·

SECTION 14.1: SEMICONDUCTOR MEMORY ·es and their characteristics such as cap .
• d uctor mernon . d . ac11y
In this section we discuss various types or semacon b d systems, senucon uc 1or memones are ......, '
. 11 .
organization, and access time. In the design of a nucrop
rocessor· ase
. O""ected directly to
th CPU d th
e an ey a.re
""'-'as
them-
emones are c '"' . ...,.
primary storage for code and d~ta. Semi~on d uctor m For !his reason, semiconductor memones are sornenmes
ory that the CPU first asks for infonnation (code and data). d t memories are ROM and RAM. Before we discuss
referred to as primary memory. The most widely used .sernacon uc or. ology common to all semiconductor mernori
~ different types of RAM and ROM, we discuss some l111portant terrnm es,
' such as capacity, organization, and speed.
l '

Memory capacity
The number of bits that a semiconductor memory chip can store is ca lled chip capacity. lt can be in wtits of Kbits
, (kilobits), Mbits (megabits), and 50 on. This must be distinguished from the storage cap~c,ty of computer systems.

-{J While the memory capacity of a memory JC chip is always given in bits, the memory capacity of a computer system is
given in bytes. For example, an article in a technical journal may state that the 128M chip has become popular. In Iha!
case, it is understood, although it is not mentioned, that 128M means 128 megabits since the article is referring lo an
( IC memory chip. However, if an advertisement states that a computer comes with 128M memory, it is understood that
128M means 128 megabytes since it is referring to a computer sys tem.
'
Memory organization
I
Memory chips ";Te organiz~ into a number of locations within the JC. Each
1.ocation canhold 1 bat, 4 bats: 8 bats, or even 16 bits, depending on how it is desi ed Table 14-1: Powers of2
~temally. The number of bits that each location within the memory chip ca
IS always equal to the number of data pins on U1e chi H
f
. n o
Id X

inside a memory chip? That do>nends on then be fp.ddow m~ny locations exist 10 IK
I ti ·u,· -r
oca ons w1 ma memory IC always equals 2 t th
pins. Therefore, the total number of bits thata:
. um ro a ress pUlS 11,e numbe f
.

number of locations times the number of data b'~moryl ch,~ can store is equal to the
ro
e powe~ of the number or address 11
12
2K
4K
i per ocation. To summarize:
13 BK
I. A memory chip contains 2' locations, where x is u,
2. Each location contains IJ bits where IJ is th bee number of address pins. 14 16K
3 Th . ' e num r of data .
. e entire chip wiU contain 2• x IJ b'ts h . pins on the chip. l5 32K
and IJ is U,e number of data pins on ~;;;.;;.ex ,s the number of address pins
16
Speed 17 128K
·~ dOne of the mos t ·unporta.nt characteristics of a 18 256K
,~ ata can be accessed T memory chi . h
pins the READ p· . . . o access the data, the address . p IS t e speed at which 19 512K
' Ill IS activated, and after a .. •s Presented t the
data shows up at the data pins Th certain amount of ti o address 20 lM
sequently, the more expensive tlie ~:~ter ~is elapsed time, : : has elapsed, the
commonly referred to as its access 1· Th ry chip. The Speed of th better, and con- 21 2M
a few. nanoseconds to hundreds ot~ e access time of memo e ~cmory ch.ip is
used m the desi_gn and fabrication roe oseconds, depending o? ~hips vanes frorn
22
The three important memo.J ch:::· . .
access bme wilJ be explored extensive! . ctenstics of capaci
t e IC technoio
gy
23 8M

Strate these concepts. aracter_,stics. Exam I


i4-
ence for the calculation of memory ch Y tn this chapter. Table organiZation
I serves as ' an
d
24
25
t6M
32M I
P es 14-1 and l4- a re(e,.
2 demon. 26
356 27 128M t
l
"rHe 80s1 MicRoco
NTRotLER
ANO EMBEOOEO svslVfS '
EJ . . • chips, while data is organized
tow m~ny address Imes are required for accessing the data 111 the to!lowmg memory
1 bV!t!S in the first l\o\'O cases and as nibbles in U,e last case?
~ find the memory capacity of each chip and the organization.
(al ;12 bytes RAM {b) 8 K RAM (c) 8 KROM

..
ty,
Ill•
5olulion:
n,e memory in the first two cases is organized as bytes.
(~\ 512 = 2•. So 9 address lines are required .

-
"'es. Memory capacity = 512 x 8 = 4096 bits.
The organization is 512 x 8.
(b) I K = 1024 = 210; 8 K = 21 x 2'0 = 2"
So 13 address lines are required
Memory capacity = 213 x 8 = 65,536 bits.
The organization is BK x 8 .
>its
11111.
(cl Whether it is RAM or ROM, the calculation is U,e same.
n is 8 K = 2' x 2 1• = 2" .
hat Hence 13 address lines are needed.
'an Data is organized as 4 bits.
that The memory capacity = 2u x 4 = 32,768 bits.
The organization is 8 K x 4.

Example 14-2
f2
- Is it possible to realize a memory of 256 x 8 bytes by using chips of 256 x 4 bytes?
--
2'
K Solution:

-
:K The 8 address lines of two chips are connected in parallel to get the address lines AO· A7 The 4 bits of RAM-1

- oorrespond to DO. 03, and the 4 data lines of the second RAM chip (RAM-2) correspond to lines D4 • 07. Thus
we have the fl.bit data bus 00 to 07. lbis is shown in the figure below.

RAM-I RAM-2

A0-A7 256x4 AO-A7 2S6x4 AO· A7

DO-DJ 04-D7

ROM (read-only memory)


<>u!OM is a type of memory that does not lose its contents when the power is turned off For this ROM 15
-
EPR,o 11,mvo/atrlt memory. There are different types of read-only memory such as PROM EPRO~~~ROM also
M, and mask ROM. Each is explained below. ' ' • , flash

!osi INTERFACING TO EXTERNAL MEMORY 357


I PROM (programmable ROM) and
OTP . . In other words, ~ROM is a user-proo,._
burn information ITTto. arruned by blowing the fuses. If lhe'/:i~
0
th kind of ROM that the userc.ITT fuse. PROM is P~ ~ ternal fuses are blown permanently ~-
PROM refers to e M th re eJCJSts a d ince ,ts U1 M l all d b . ·~
' F every bit of the PRO , e be discarde 5 .,.,.,.mming RO , a soc e urning RO).f
ma~le memoedry .. ~r PROM is wrong, that PROM must ,,..ramrnable). Proi;,•~- ••
matton burn in o OTP (one-tiJJ1e pr~o er
th.LS re'"hn PROM is also referred to as ROM prograoun ·
~ ' ROM burner or
reqwres special equipment caJJed a

/ and uv-EPROM
EPROM (erasable programmable ROM) f PROM after it is bum~d. In EPROM, one can
O
'all necessary dunng development of the
EPROM was invented to allow m~ktng
.
:,~ls
h n es in the contents
of times. This is esp:c•, red UV-EPROM, where UV stands f
program the memory chip and erased it th_o t A widely used EPROM is cal take up to 20 minutes. AU UV-EPR~'.
ototype of a microprocessor-base proiec · . 1·ts contents can . v,~
pr . Th bl
uJtravtolet. eonIy pro em w, "th UV-EPROM is that erasing . let (VV) radiation to erase its th . For
contents.
1 ! can shine u 1trav10 F" l 4-l h
.'
1,
chips have a window Uuough which the programmerEPROM or simply uv-EPROM. 1gure
this reason, EPROM is also referred to as UV-erasable
s ows e pms for

I a UV·EPROM chip. t be taken·


T0 UV EPROM chip the following s teps mus .
'• program a • ' . . rom its socket on the system board and place it in EPROM
1. Its contents must be erased. To erase a chip, remove it f .
erasure equipment to expose it to UV radiation for 15-20 minutes. ) T b od
· OM ch.1 lace it in the ROM burner (programmer · o urn c eordab
2. Program the chip. To program a UV-EPR P: P din th EPROM type. This voltage is referred lo
into EPROM, the ROM burner uses 12.5 volts or higher, depen g on e
as v,. in the UV-EPROM data sheet.
' I 3. Place the chip back into its socket on the system board.

As can be seen from the above steps, not only is there an EPROM programmer (burner), but there is also sep<1rate
r EPROM erasure equipment. The main problem, and indeed the major disadvantage of UV-EPROM, is that it cannot be
erased and programmed while it is in the system board. To find a solution to this problem, EE PROM was invented.
Notice the patteITLS of the IC numbers in Table 14-2. For example, part number 27U8-25 refers to UV-EPROM that
has a capacity of 128K bits and access time of250 nanoseconds. The capacity of the memory chip is indicated in the part
number and the access time is given_ with a zero dropped._ ln ~art numbers, C refers to CMOS technology. Notice that
27XX always refers to UVEPROM chips. For a comprehensive list of available memory chips see JAMECO Qameco.com}
or JDR ydr.com) catalogs.

2764
.,,
~ -:::.
~ ;5
~ Vpp ..,
-
~

" I
28 Vee ;s 00

~
N N
A12 2 ~
Vpp Vpp
A7
27 PCM "
N ~ ....
A12 A12 3 26
N N M E
A7 A7 A7 A6 4
N.C. Vee
A7 Vee
A6 A6 A6 AS 25 AS
A6 5 PCM A14
AS AS AS AS A4 24 A9 Vee Vee A13 Al3
A4 6
A4 A4 A4 A3 23 Al] AS A8 AS
A3 7 A9 AS
A3 A3 A3 A2 22 ~ A9 A9 A9
A2 A2 8
Al
AO
Al
AO
A2
Al
AO
A2
Al
AO
Al
AO
9
10
21
20
AlQ
CE
di!
AlO
All
OE/Vp1
~
OE ~
AlO
00
01
00
OJ 01
00 00
OJ
00
OJ
11
u
19
18
07
06
a a AlO AIO
cr CE
02 <Yl 07
02 02 02 02 13 17 05 06 07 07
GNC GNO GNO GNI GND 16 06 06 06
14 OI OS OS
lS 04 05 05
03 04 04
Figure 14-1. Pin ConBguration, for 27'°' ROM F•inily 03 03
04
03 03
358
lliE sos1 Mlcaoc
0 11rraoLL
ER AND EMBEDDED SYSTEMS
Table 14-2: Some UV-EPROM Chips
Ill\-
-Part# Capacity Org. Access Pins vcf
25V
450 ns 24
lor- 2716 16K 2Kx8
-2732 24 25V
"°'lt.t. -
2732A-20
32K
32K
4Kx8
4Kx8
4S0 ns
200 ns 24 21 V

24 12.5 VCMOS
27C32-1 32K 4Kx8 450 ns
28 21 V
2764-20 64K 8Kx8 200 ns
28 J2.5 V
2764A·20 64K 8Kx8 200 ns
~ 12.5 VCMOS
120 ns 28
!ht 27C64-12 64K 8Kx8
f0r 28 21 V
27128-25 128K 16Kx8 250ns
OM 28 12.SVCMOS
For 27C128-12 128K 16Kx8 120ns
28 12.5 V
'for 27256-25 256K 32Kx8 250ns
28 12.5 VCMOS
27C256-15 256K 32Kx8 150 ns
250ns 28 12.5 V
,OM 27512-25 512K 64Kx8
150ns 28 12.5 VCMOS
27C512-15 5121< 64Kx8
data 1S0ns 32 12.5 VCMOS
27C010-15 1024K t28Kx8
!d to 12.5 VCMOS
2048K 256Kx8 lSOns 32
27C020-15
1S0ns 32 12.SVCMOS
27C040-15 40961< 5 12Kx8

arate
otbe
d. Eumple14-3
[ that
!f*' Find the number of address and data pins for the chip 27C010-15.
! that
CODI) Solution:
From Table 14-3, it is seen that the above chJp is organized as 128 K x 8 bits.
128 K = 2' x 2"' = 217•
The chip has 17 address lines and 8 data tines.

EEPROM (electrlcally erasable programmable ROM)


EEPROM has several advantages over EPROM, such as the fact that its method of erasure is electrical and therefore
llslant, as opposed to the 20-minute erasure time required for UV-EPROM. In addition, in EEPROM one can select
~hich byte to be erased, in contrast to UV-EPROM, in which the entire contents of ROM are erased. However, the
lllainadvantage of EEPROM is that one can program and erase its contents while it is still in the system board. It does
~require physical removal of the memory ~p fron:, tts sock~~- In other words, unlike UY-EPROM, EEPROM does
~require an external erasure and programm.ng dev,ce. To utilize EEPROM fully, the designer must incorporate the
Clteuitry to program the EEPROM into the system board. In general, the cost per bit for EEPROM is much higher than
foi W-EPROM.

~lash memory EPROM


Since the early 1990s, flash EPROM has become a popular user-programmable memory chip, and for good rea-
lclns. Fu-st, lhe erasure of the entire cont~ts takes_ less than a second, or one might say in a flash, hence its name, flash
~ - In addition the erasure method is electrical, and for this reason it is sometimes referred to as flash EEPROM
it
Oavc;d confusion, is commonly called flash memory. The major difference between EEPROM and flash memory ;~

~ 11 N'TatPACING TO EXTERNAL MEMORY 359


d f lash ChiPs
Table 14-3: Some EEPROM
Pa.rt No. Capacity
:rg. Speed Pins v,,
EEPROMs 24 SV
250ns
2816A·25 16K 2Kx8 sv
250ns 28
2864A 64K SJ<x8 SVCMOS
zsons 28
28C64A·25 64K SJ<x8
1sons 28 SV
28C256-15 256K 32Kx8
250ns 28 SVCMOS
28C256-25 256K 32.l<xS
• Aash
1 I
I
2oons 32 12VCMOS
28f256.20 256K 32Kx8
., tSOns 32 12 VCMOS
• 28FU10·15 J024K l28Kx8
f I
32 12VCMOS
281'020.15 2048K 256Kx8 IS0ns
~
I
~

10 EEP·ROM, where one can etast


that when £lash memory's contents are erased, the entire_ entl made .available
· dev,'ceiserased,incon trastthe contents are d.'.v''ded in
· to blocis
D
( d th section or byte. Although in some nash.memones rec Oas~ memory has no byte erasure option. Because flash
a desired
an e erasure can be done block. by. block,
. . . unl,ke the system board, ·tis
EEPROM.
k ton 1 widely used to upgrade BIOS ROM
..,, the'l"L, ld
' memory can be programmed while ti is"' ,ts soc e II I the hard disk as a mass storage me...,urn. uus wou

of the PC Some designers believe that Rash memory w\ rep acefuish memory is semiconductor mea,ory with a~ .[
r time in the range of JOO ns compared w,th disk
memory's
of program/erase
times that cycles must
a chip can be erased
•:e
increase Uie perfonnance of the comp~ter ~remendo':,,;~ ~n~: ran eof tens of milliseconds. For this to happen, flash
·ust like harJ(tisks. Program/erase cycle refers to the number
become, edbeiore 1't. becomes
and progranun . unusable. At .this time, the program/erase cycle
is 100,000 for flash and EEPROM, 1000 for UV-EPROM, and 1116nite for RAM and disks.
b
Mask ROM I•
k
Mask ROM refers to a kind of ROM in which the contents are program.med by the JC manufacturer. In other words, is
it is not a user-programmable ROM. The term mask is used in lC fabrication. Since the process is costly, mask ROM IS
used when the needed volume is high (hundreds of thousands) and it is absolutely certain that the contents will nol
change. It is common practice to use UV-EPROM or flash for the development phase of a project, and only after lht H
c?<fe(data.ha~e been finalized is the mask ~ersion of the pr~uct ordered. The main advantage of mask ROM is its cost
smce ,tis s1gruficantly cheaper than other kmds of ROM, but ,fan error is found in the data; Code the entire batch musl
be thrown away. Many m~ufacturers_of 8051 microcontrollers support the mask ROM version ~f the 8051. Jt must be
noted that alt ROM memones have 8 bits for data p111S; therefore, the Organization is x8.

RAM (random access memory)

RAM memory is called volalile memory since cutting off the w .


RAM is also referred to as RAWM (read and write memory) in po er to the IC resuJts in the loss of data. SometiJJ'tes
three types of RAM: static RAM (SRAM), NV-RAM (nonvol;titec~s) t 10 ROM, Which cannot be written to. There are
separately. 'and dyna.nuc RAM (DRAM). Each is explained
SRAM (static RAM) l

Storage cells in static RAM memory are made of llip-n


their data. This is in contrast to DRAM, discussed below ~ and therefore do not r . . . kee])

~~
each cell reqUtres al feast 6 transistors to build, and the · e Problem With the eq~re refreshing m order t •• th,lt
f1
made of 4 trans,stors, which stiU is too many. The USe 0 holds Only 1 bit of d Otp·Oops for s torage cells 0 t,eet,

3~ Tl-rE transistor <:ells pf ~ a. 15


recent years, the cells hove
· us e use of CMOS technology has gi,-en
te 14-4: Some SRAM and NV-RAM Chips v,.
fab Speed
Pins
No Capacity Org.
r¢ .
:;.-:-:-- CMOS
siv\M 24
:::-::-:-
61161'·1
16K 2Kx8 1oons
CMOS
24
::---:-2 16K 2Kx8 12ons
C.\IIOS
61161'· 24
;...--:' tSOns
16K 2Kx8 Low-powe r CMOS
6116P·3 24

--
:..-- 16K 2Kx8 tOO ns
6116LP·l Lo,v-power CMOS
120ns 24
6!16Ll'·2 16K 2Kx8 Low-power CMOS
24

- 16K 2Kx8 150 ns


1116U'·3 28 CMOS

-- 64K 8Kx8 tOOns


62b!P·l0
28 Low-power CMOS
64K 8Kx8 70 ns
6161LP·70 Low-power CMOS
120 ns 28
6,1(,!U'· t 2 64K 8Kx8
-6!256LP-lO 256K 32Kx8 tOOns 28 Low-power CMOS

-
6!256LP·12 256K 32Kx8 120 ns 28 Low-power CMOS

-NV-RAM from Dallas Semiconductor


-OOJ220Y-1S0 161< 2Kx8 150 ns 24
-l)51225AB-1S0 64K 8Kx8 lSOns 28
256K 32J<x8 85 ns 28
~ !230Y-85

birth IO a high-capacity SRAM, but its capacity is far below DRAM_. Table
tH shows some examples of SRAM. Figure 14-2 shows the pm d., agram
24 Vrt
lo, an SRAM chip. In Figure t 4-2, notice that WE is write enable, and OE
~output enable, for read and write signals, respectively. 23 A8
A5 22 A9
,olds. 21 WE
A4 4
::JM ii NV-RAM (nonvolatile RAM) A3 5 20 OE
llnol A2 6 19 AIO
.rdlt Whereas SRAM is volatile, there is a new type of nonvolatile RAM
9(05!, tailed NV-RAM. Like other RAMs, it allows the CPU to read and write Al 7 18 cs
loit, but when the power is tumed off the contents are not lost. NV-RAM AO 8 17 1/ 08
'aiusl 16
a,tbr IO!nbines the best of RAM and ROM: the read and write ability of RAM, 1/01 9 1/07
plus the nonvolatility of ROM. To retain its contents, every NV-RAM chip 1/0 2 10 15 1/06
llllttnaJly is made of the following components: 1/0 3 11 14 I/ OS
13
GNO ....,,__1:::2_ _ _~::....i 1/04
It uses extremely power-efficient (very, very low-power consump-
tion)SRAM cells built out of CMOS. Figutt 14-2. 2Kx8 SRAM Pins
l It uses an internal lithium battery as a backup energy source.
l It uses an intelligent control circuitry. The main job of this control circu.itry is to monitor the Vcc pin constantly to
detect loss of the external power supply. If the power to the Vcc pin faUs below out-of-tolerance conditions, the con-
trol tircu.itry switches automatically to Its internal power source, the lithium battery. The internal lithium power
source is used to retain the NV-RAM contents only when the external power source is off.

It must be emphasized that all t ~ of the components above a~e incorporated into a single IC chip, and for this rea-
"'ri nonvolatile RAM is a very expensive type of RAM as far as cost per bit is concerned. Offsetting the cost, however,
:!;: fact that it can retain its contents up to ten years after the power has been turned off and allows one to read and
in exactly the same way as sRAM. See Table 14-4 for NV-RAM parts made by Dallas Semiconductor.

!Qsl lN"rERfACING TO EXTERNAL MEMORY 361


byte ROM the checksum calculation. The prOCEss
Checksum ve system must performuses of ROM corruption is current Of
To ensure the integrity of the ROM contents, e ' \ ROM One of the ca . . ROM the checksum proc SUr8',
checksum w,Jl detect any corruption of th~ conte;~ti:n. To ~ure da~a inte~~omthe end of a series of bytes:: uses
either when the system is turned on or dunng op . .xtra byte that J.S tagg t ken data.
what is called a checksum byte. The checksum byte IS:'
e the following steps can be a ·
, of a series of bytes of ata,
To calculate the checksum bvte
.,.,
I. Add the bytes together and drop the carries. ks byte which becomes the last byte of the series
J
2. Take the 2's complement of the total sum, and that is the chec urn ' ·
. din the checkswt1 byte. The result must be zero. [fit is not
V
To perform the checksum operation, add all the bytes, inclu ~ gclarify these iniportant concepts, see Example 14.J.
• zero, one or more bytes of data have been changed (corrupted). 0
I
1

,,
• DRAM {dynamic RAM)
( I
, Since the early days of the computer, the need for huge, inexpensive read/ wri te ,~emory has been a major preoccu.
• pation of computer designers. In 1970, Intel Corporation introduced the first dynarruc ~ (random access memory}
I Its density (capacity) was !024 bits and it used a capacitor to store each bit. Using a capa_c,tor to store data cuts down 1
' the number of transistors needed to build the cell; however, it requires constant refreshing due to leakage. This is in r
(] contrast to SRAM (static RAM), whose individual cells are made of flip-flops. Since each bit in SRAM uses a single flip-
flop. and each flip-flop requires 6 transistors, SRAM has mucli larger memory cells and consequently lower density.
d
a
( The use of capacitors as storage cells in ORAM results in much smaller net memory ceU size. h
' . The •?vantag~ and disadvantages of ORAM memory can be summarized as follows. The major advantages are ~
high density (capacity), cheaper cost per bit, and lower power consumption per bit. The disadvantage is that it must be rJ.
II)
t
Example 14-4 DI
~l
Ass~e Ilia! we have 4 bytes of hexadecimal data: 25H, 62H, JFH and 52H I!!
(a) Fmd the checksum byte, (b) perform the checksum O a . • · . . II-,
62H has been changed to 22H, show how checksum def:ts ~~~!~data mtegnty, and (c) if the second byte
Solution:
(a) Find the checksum byte. llf
25H The checksum is cakuJated b firs .
• 62H The sum is 118H, and dro _Y t adding the bytes. Thi
• 3 FH we get 18H. The checksW:1mg ~he carry,
52 1)6
• H of 18H, which is ESH. yte 15 the 2's complement
118H
(b)
Perform the checksum operation to ens d .
25H lite ata tn"""'ty
62
Adding the series of b -r,.. ·
• H must result in zero. Yle_s, ".'eluding the checks
+ 3 FH are unchan ed This indicates that all th um byte,
+ 52H g and no byte is corru e bytes
+ ESH Pied.
<OOH (dropping the carries)
(c) If the second byte 62H has been ha
25H c nged to 22H h
Adding the series f b • 9 ow how checks
: ::.:: shows that the res:t Jtes Ulduding the ch~etects the error.
• 52 H one or more bytes have~'lero, Which ind.i um byte
+ ESH COll'IJpted. cates that
lCOH (dropping the carry, we get COii.)

362
· · 1 hll DRAM ·s1 being refreshed, the data
,.,.i,ed periodical Y because the capacitor cell loses its charge; furthermore, w e • d ot need
r<"'- be accessed, This is in contrast to SRAM's flip-flops, which retain data as long as the powe~:: ~:, 1;:d. After
1 od P . f 641<
~
~refreShed, and whose contents can be accessed at any time Since 1970, the capacity of DRAM
itc-bit (1024) chip came the 4K-bit in 1973, and then the 16K chip in 1976. The 1980s_ sa~ thef
O ~;.bitu~~nrJch.ips'.
;561(.aild 6nall~ lM and 4M memory chips. The 1990s saw 16:"", Mi:1, 256M, and the begmrung
0 . swill be rolling off
ll>t~' 2G-b1t are standard, and as the fabrication process 1s gettiJlg smaller, larger mem. 1')'. ch.ip
~
ed t be
i!>tn,anufacturing line. Keep in mind that when talking about IC memory chips, the capacity 1s always assum
• t,;ts. Therefore, a 1M chip means a 1 megabit chip and a 256K cnip means a 256K-bit ,nemory chip. However, w en
~ about the men,ory of a computer system, it is always assumed to be in bytes.
. packaging issue In DRAM
!JI ORAM there is a problem of packing a large number of cells into a single chip with the n~rmal num~r of pins
,LI.Sigtied to addresses. For example, a 641<-bit chip (64Kx1) must have J6 address lines and 1 data hne, reqmrmg 16 PIJ\S
rosend in the address if the conventional method is used. TI'lis is in addition to V,cpower, ground, and read(wnte c~n-
vol pinS, Using ~e conventional method of data access, the large number of pins defeats the_ purpose of high density
s,l sn,all pacl<agmg, so dearly cherished by re designers. Therefore, to reduce the number of p ins needed for addresses,
11\ultiplexing/ demultiplexing is used. The method used is to split the address in half and send 1n each half of the address
11,toUgh the same pins, thereby requiring fewer address pins. Internally, the DRAM structure is divided mto a squa re of
rows and columns. The first half o f the address is called the row and the second half is called the column. For example, ill
l!,ecaseof DRAM of 64Kxl organization, the first half of the address is sent in through the 8 pins AO - A7, and by activat·
;,,gRAS (row address strobe), the internal latches inside DRAM grab the first half of the address. After that, the second
1,Jl/of the address is sent in through the same pins, and by activating CAS (column address strobe), the internal latches
u,s,de ORAM latch the second half of the address. This results in using 8 pins for addresses plus RAS and CAS, for a total
cf!Opins, instead of the 16 pins that would be required without multiplexing. To access a bit of data from DRAM, both
row and column addresses must be provided. For this concept to work, there must be a 2-by-1 multiplexer outside the
DRAM circuitry and a demultiplexer inside every DRAM chip. Due to the complexities associated with DRAM interfac-
u-«{RAS, CAS, the need for multiplexer and refresning circuitry), there are DRAM controllers designed to make DRAM
1111macing much easier. However, many small microcontroller-based projects
that do not require much RAM (usually less than 641< bytes) use SRAM of
~,ies EEPROM and NVRAM, instead of DRAM. AS 1 16 GNO
DlN 2 15 CAS
WE 3 14 DOUT
DRAM organization 4
RAS 13 A6
. 1n the discussion of ROM, we noted that a ll of them have 8 pins for data. AO 5 u A3
This is not the case for DRAM memory chips, which can have xl, x4, x8, or A2 6 n A4
\16organizations. See Example 14-5. Al 7 10 AS
In memory chips, the data pins are also called 1/0. 1n some DRAMs there 8
Vee 9 A7
1teseparate D., and D..,;pins. Figure 14-3 shows a 256Kx1 DRAM chip with
I™ AO· AS for address. RAS and CAS, WE (write enable), and data 1n and
data out, as well as power and ground. Figure 14-3. 256K,c1 DRAM

Table 14-5: Some Widely Used DRAMs


Part No. Speed Capacity Org. Pins
4164-15 1S0ns 64K 64Kx1 16
41464-8 S0ns 256K 64Kx4 18
41256-15 1S0ns 256K 256Kxl 16
41256-6 60ns 256K 256Kxl 16
414256-10 lOOns lM 256Kx1 20
Sl!OOOP-S 80 ns lM lMxl 18
514100-7 70 ns 4M 4Mxl 20

AClNC TO EXTERNAL MEMORY


EJWDplt 14-5 dd~ II\ eaCh of
I i~ s..-1 a,,de for •
o,.cu~, the number o p 16Kx4 SAAM
l•l 16lu<4 ORA\1 !bl

Sol-
·· AAS~~
illS ,llld 2 pitlS for . they are as.,;ocia.ted only Will
,
5ull'.'e 2" " 16K· . . AO Ab) for the adclreSS P for RAS and CA5 smce
ha,•
Co) For l)RA1'1 ... e 7 pll"' ( ddttS> and no pins
(bl For SR.AM we have 14 pins for a for the data bus.
ORA.\I In bolha>6 "e t,a,e4 pins

Review Question.s f

• l The speed or semiconductor memory is in the range o
f)
(a) ~ s lb) mill,secer,d,, . ber of address and data Pll\S.
(c) nanost'COnds (d) picoseconds. each ROM with the ,nd1cated num
ind the ~.,ni,.ation and chip capaoty for ( ) 12 address, 8 data nd d •
I 2. Fi - . , - -d t (b) 16addr~s,8data c_ th d"cated number of address a ata Pll\S.
(a) 14 address, 8 a a . ty foe each RAM "'~th em I
Find the org,mi.z.thon and clup capao address 4 data SRAM
3
(a) 11 addre.s, I data SRAM
(c) 17 address,SdataSRAf.l
~i
13
4
8 add""5, data ORAM
4data ORM1 ·
(e) 9 address, I data ORAM (I) 9 address,.d r ddress and data for memory chips Wlth the follo,,,,r-5
4 Find the capacity and number of plns set ""' e or a
orgaruzallon.. M ( ) JMxl DRAM
(a) 16Kx4 SRAM (b) 32K..S £PRO, c
(d) 256Kx4 SRA'1 (e) &,tKxS EEPR0~1 (I) 1Mx4 ORM1
5. Which of the following tS (are) volollle) OmlW~~ry? (d) NV-RAM
!•) EEPRO:>.t (bl SRA.\t (c •

SECTION 14.2: MEMORY ADDRESS DECODING


1n this s«t,on we d.15CU» address deco,bng The CPU provides the address of the data d esired, but it is tht
job of the decoding circuitry to locate the selected memory block_ To explore the concept of decoding circuitry, "·e
1ooi.. at ,·anous methods used m decoding the addresses. In tlus discussion we use SRAM or ROM for the sakr"
simplicity.
\lemoryclups h.a,e one or more pins called CS(chip select), wluch must be activated for lhe memory's (.;()l'ddalSID
be acassed. Somebm~ the chip select 1s also referred to as crup enable (CE). In connecting a memory chip to the Cl'll,
note the following points.

1. The data bus of the CPU IS ronnected directly to the data pms of the _._,
memory uup.
2. Control signals RD (read) and WR (memory write) from the CPU are --• WE
(write ~ble) pm, of the memo<) clup, n-spedi,el>· connected to the OE (output enable}"""
3 In the c~ of the address bu<;et,, while the lower bits of the addresses fr . . ·
a.ddre<s plll>, the upper ones att used to •ctl\a.te the CS in of om the CPU go directly to t h e ~ dtil'
RD/\\IRallow" theOow of data in or out of the memory
clup ~ CS IS acti,atro
l p. 0
cs
N the memory chip. It is the pm that along with
data can be written into or read from t h e ~

As can be seen from the data sheets of SRA.\t and RO\i th


and b •ct" a.led by the output of the memory decoder N~ ' e CS input of a memo ch . a ~ 11"'

slll\ple logic ,:•to, (b) using the 741.Slltl, or (c) using e ee \\·ays to generate a
15
of the decoder selects a given memory block_ n..,re..; thrrmaUy memories are dh, I d~ . 'P n ~ the outP"t
mto bloc ,
11 aJ( )~
some examples. progrartunable lo.,; ., __ memory block selector. • -""
-.,.cs. '"""h method is deteribed belaW '""'
07
07 00

--
<
0 '
AO

AU
41(,cS

<
A12
A13 ~
Al4 Ri'5 WR
A15
MEMR
MEMW

f~tt Jol,4. Logic G•t• as Oe<:oder

Block Diagram
Simple logic gate address decoder
I' I I
Vee GND The simplest method of constructing decoding
YO 0-- circuitry is the use of a NANO gate. The output of
A YI a NAND gate is active low, and the CS pin is also
active low, whlch makes them a perfect match. In
- B Y2 0--
Y3 cases where the CS input is active high, an AND gate
C Y4 0-- must be used. Using a combination of NAND gates
Y5 0-- and inverters, one can decode any address range. An
Y6 0-- example of this is shown in Figu.re 14-4, which shows
Y7 0--
that A15· A12 must beOOll in order to select the chip.
G1A G28 GI This results in the assignment of addresses 3000H to
- '( l l , 3FFFH to this memory chlp.
Enable
Function Tabl•
OutpulS Using the 74LS138 3-8 decoder
In UIS
Enable Select This is one of the most widely used address
YO Yl Y2 Y3 Y4 Y5Y6 Y7
Cl C2 CB A decoders. The 3 inputs A, B, and C generate 8 active-
XH XXX HHHHHHHH low outputs YO· Y7. See Figure 14-5. Each Y output is
LX XXX HHHHHHHH connected to CS of a memory chip, allowing control of
HL LLL LHHHHHHH 8 memory blocks by a single 74LS138. ln the 74l.Sl38,
HL LLH HLHHHHHH where A, B, and C select which output is activated,
HL L HL HHLHHHHH there are three additional inputs, C2A, C2B, and Cl.
HL LHH HHHLHHHH
HL HLL HHHHLHHH G2A and G2B are both active low, and G1 is active
HL HLH HHHHH L HH high. U any one of the inputs GI, G2A, or G2B is not
HL H HL HHHHHH L H connected to an address signal (sometimes they an!
HL HHH HHHHHHH L connected to a control signal), they must be activated
permanently either by Vex or ground, depending on
the activation level. Example 1~ shows the design
and the address range calculation for the 74LS138
decoder.

list 11'frERFACING TO EXTEllNAL MEMORY


, . I
t,

I I
:
DO

07 DO

.,., --< 4J<x8


YO 0'
A12 A YI <
Al3 B Y2
L- Al4 C Y3 cr,
A15 QA Y4

~ Y5
5E Vpp
GNO
Ve< GI Y6 MEMR
Y7
Vee

Figure 1~ 74LS138 •• Decoder


,
',.
I. Exa.mple 14-6
~
Lookmg at the design in Figure 14-6, find !he address range for the following.
l (a) Y4, (b) Y2, and (c) Y7.
<
Solution:
I (a) The address range for Y4 is calculated as rollows.
Al5 Al4 All Al2 All AlO A9 A8 A7 A6 A5 A4 A3 A2 Al AO
0 I 0 0 0 0 0 0 0 0 0 00 0 0 0
0 I 0 0 1 l I I 1 1 1 1 1 1 1
The above shows that lhe range for Y4 is 4000H to 4FFFH. In Figure 14-6, notice that Al5 must be O for the decodff
to be achvaled. Y4 will be selected when Al4 Al3 A12 = 100 (4 in binary). The remaining A 11 - AO will be Ofor
the lowest address and 1 for the highest address.
(bJ The address range for Y2 is 2000H lo 2FFFH.
AlS Al4 AlJ Al2 All AlO A9 AS A7 A6 AS A4 A3 A2 Al AO
0 0 l 0 0 0 0 0 0
0 0 1
0 0 0 0 0 0 0
0 I 1 I 1 l I 1 1 1 1 I I
(c) The address range for Y7 is 7000H to 7FFFH.
AlS Al4 All Al2 All AlO A9 AB A7 A6 AS
0 1 l 1 0 0 0 A4 A3 A2 Al

-
0 0 AO
0 I I I 1 1
0 0 0 0
1 I l 1
0 0 0
I I 1 l 1 1

Using programmable logic as an address decoder


Other widely~ decoders are programmable lo · ch·
chif)6 is that they require rAL/CALsortware and ab gic ips such as PAL and GAL h ' .
The advantage of these chips is that they can b urner (programmer) wh C 1ps. One d1sadvant.~ge of lhese
more ,ersatile. nu,. plus !he fact that p~ anJ t~°t":,mmed for any co~bin:i~~s ~e 74LSJ38 needs neither oft":,
they can accommodate more address inputs ave 10 or more inputs c· 0 address range:., and so are rn
· •n contrast to 6 in the 74138) means th,ll
Review Questions
I A g,ven memory block use'! addresses 4000H _?FFPJ;
2. The 74138 ,s a(n) by decoder · How many Kb . .
1
y es 15 this memory block?
3"
lliE sos1 MJcaoc -
ON"fROLLEJt AND EMBEDDED s'Yfl'Od
the 7~138 S!"e the status of G2A and G2B for the chip to be enabled.
10
~ 1/1 the 1; 138 g,ve the s~tus of Gl for the chip to be enabled.
~· Example 14-6, what is the range of addresses assigned to Y5?
10

5ECTION 14.3: 8031151 INTERFACING WITH EXTERNAL ROM


AS discussed in Chapter 1 , the 8031 chip is a ROMless version of the 805). In othe r words, it is exactly like any
~ r of the ~ l family such as the 8751 or 89C as far as executing the instructions and features are concerned, but
51
ihaS oo on-chip ROM. Therefore, to make the execute 8051 code, it must be connected to external ROM memory
8031
~ taininS th~ program cod.e . In this section we look at interfacing the 8031 microcontroller with extemal ROM. Before
•-tdiS(USS this topic, o~e might wonder why someone would want to use the 8031 when they co~d buy an 8751, 89C51,
Cf [)55000. The reason 1s that all these chlps have a limited amount of on-chip ROM. Therefore, m many systems where
t1,ton<hiP ROM of the 8051 is not sufficient, the use of an 8031 is ideal since it allows the program s ,ze to ~e as large as
($b)1es. Although the 8031 chip itself is n,uch cheaper than other family members, an 8031-based syste~ ,s muct:i mo re
e,pensive since the ROM containing the program code is connected externally and requires more suppornng orcu1try, as
•-te,q,lain next. First, we review some of the pins of the 8031/ 51 used in external memory interfacing. See Figure 14-7.

EA pin
As shown in Chapter 4, for 8751/89C5l/0SS000-based systems, we connect the EA pin to Vcc to indicate that the
program code is s tored in the microcontroUer's on-chip ROM. To indicate that the program code is stored in external
RO~I. this pin must be connected to GND. This is the case for the 8051-based sys tem. In fact, there are times when, due
to repeated burning and erasing of on-chip ROM. its UV -EPROM is no longer working. In such cases 011e can also use

row / Cerdip

Pl.0 1 40 vcc
Pl.l 2 39 PO.O(AD0)
Pl.2 3 38 PO.I (AOl)
Pl.3 4 37 J>0.2 (AD2)
Pl.4 5 36 P0.3 (AD3)
Pl.5 6 8031/8051 35 P0.4(AD4)
7 / 8052 34 l'0.5 (ADS)
Pl.6
Pl.7 8 33 P0.6 (AD6)
R5T 9 32 l'0.7 (A07)
(RXD) P3.0 10 31 EA/VPP
(TXD) 1'3.1 u 30 ALE/PROG
(INTO) P3.2 12 29 PSEN
(INTI) P3.3 13 28 P2.7 (A15)
14

~--
(TO) P3.4 27 P2.6 (A 14)
(Tl) P3.5 15 26 1'2.5 (A13)
(WR) P3.6 16 25 P2.4 (A12)

'~
:.,.-
(RD) 1'3.7
XTAL2
17
18
24
23
1'2.3 (A 11)
P2.2 (AIO)
XTALI 22 P2.I (A9)
GNO 21 1'2.0 (AS)

Flg,,,. l4-7. 8051 Pin Diagram

ilDst INTEAFAO NC T O EXTEJlNAL M EMORY 367


/
v,,• '
•,NI.J
ll
11 ?5'J ,{ l<J ,
}J.J
' I}
~
f(J
1t.lr1•••11 ",(J
II)
tJI J
7Q
Ill
~I) (' <JC IN
6
J.nJbl, lJ, 11:p<M <0'1ttol

J ~noon T•ble
(Julpu ,.,.01.. ~
c, D Output
._or,uO,
l H H -
II
L L

-
I If
I. L X QO
H X X z
~
"

On

1'·
Al
I
I
i" <.•·
JI • 1 I
,~
I <'Wff' 1',t
,,, \Jdre,.. BH"

I
1''
I \-tt~
Hu,
'"
8031/51 RD
-
-~
EA (RD) 1'3.7
(WR) 1'3.6
WR
PSEN
PSEN Al5 Upper $-Bit
1'2.7 Address Bus
A8
P2.0
,G
ALE ~
A7
P0.7 AD7 IO '-lJ Lower 8-Bit
= "I<
Address Bus
74LS373 AO
PO.O ADO oc
.,.'-
D7 Data
Bus
00

figure 14-10. D•t•, AddJ:ess, and Control Buses for the 8031
rftv ~ •nd crystal connectwn. see Ouipt<r 4.)

In systems where the external ROM contains the progran1 code, burning the program into ROM leaves the micro-
controller chip untouched. This is preferable in some applications due to flexibility. In such applications the software is
iutor
)plat updated via the serial or parallel ports of the !BM PC. This is especially the case during software development and this
method is widely used in many 8051-based trainers and emulators.

On-chip and off-chip code ROM


Ill 6ar In all our examples of 8051-based systernsso far, we used either the on<hip ROM or theoff<hip ROM for the program code.
dlWI 1lee are times that we want to use both of them. ls this possible? The answer is yes. For example, in an 8751 (or 89C51) system
:nphl· "'roukl use the on<hip ROM for the boot code, and an external ROM (using NV-RAM) will contain the user's program. In this
GND,
INpin
ilollOI
8031
RD Vee
P3.7
.r EA 1'3.6 WR
I
I
PSm al
o£ Ypp
P2.7 Al' Al2 2864
P2.0 AS (2764)
N>
ALE ,G 8Kx8
P0.7

PO.O r
=
AIYZ_
1D Q J-<'.
74LS373
A7

AO
A7 program

AO
ROM

oc D7 00

-~
07

'LJU

lls,.,.14-U. 8031 Connodlon to Exlfflw Program ROM

'°51 iNT£RFAONG TO EX'J'EllNAL MEMORY 369


, . lnchsuch a"""-
_, ded .,nto off<hi p NV-RAM.
are dowiuoa
-,-""
first then, when 1t rea es the end t
""'""msthe 011 -chip
. d the user's pwo·· · P•..no-ram
~o· ·· 8051' trainers are d es1·gned usmg
· ~<II Jr
tem boot code resides on-chip an the B051 executeS am code. Many (S9C51) system with boU, on~ .~
'""Y·:U':.:: EA = v«.' meaning that upon:ior the rest of the P:exan1ple, in an 8751000(), then goes on to a d ~ ~
10
' \I
;: ~ P ROM it switches . ~emal ~o~atically by the SOS~es starting a t ~ =and is automatically directe:I to~
method. Again. notice tha~ this~ ~r:; (etch:
a':t.econtr0Uer
and off<hip ROM code w. ere M)-~ the program coun
generates addreSS4-J2 sho,vs the memory configuration.
d l4-8. Figure l
' \I
I I'

• I'
(the last location of on-chip RO · cod See Examples 14-7 an
'. f
.,., external ROM containing the program e.

8052
8051 EA- Vee
8031/51
v EA=CND
EA= Vee
.'
,. •
I 0000 OW) [
OFFF
Qn-dtip
4K
J OOOo On-chip

IFFl'~===j
SK
•• 1000 2000
'' l Off
Off Off
Chip


•'
I
-
FFFF'.__ _ _1 -
Chip

FFF-;-;-L----
- 1
Chip
FFFf- 'L-----'I -
Figure 14-12. On-,hip and Off•chip Program Code A«ess

Example 14-7
I Discuss the program ROM space allocation for each of the following cases.
(a) EA = Ofor the 8751 (89CS1) chip.

(c) EA= v:
(b) EA = v with both on-chip and off-chip ROM for the 8751.
with both on-chip and off-chip ROM for the 8752.

Solution: ingc
I«)'

(a) When EA = 0, the EA pin is strapped to GND, and all program fetches are directed to external memory
regardless of whether or not the 8751 has some on-chip ROM for program code. This external ROM can be
as high as 64K bytes with address space of 0000 - FFl'l'H. In this case an 8751 (89C51) is the same as the 8031
system.
(b) With the8751 (89CS~)system ~vhe~ EA= Vcc• the microcontroller fetches the program code of addresses 0000
• OFFPH from on-chip ROM since it has 41< bytes of on-chip program ROM and any fetches from addresses
1000H • FFPPH are directed to external ROM.
(c) With the 8752 (89C5~) system '.vhere EA" VCt! the rnkrocontroller fetches the ro ram code of addresses 0000
- lFFFH from on-chip ROM since 1t has SK bytes of on-chip progra ROM P dg f fr dd--
2000H - PFFl'H are directed to external RO}-!. m an any etches om a ,.,.....

ElCllmpte 14-8

Discuss the role of the PSEN pin in accessing on-chip and ff .


o -chip program codes.
Solution:
In the process of fetching the intemal on..:hip pro
However, l'SEN is used for all external Program fetgram <:ode the PSEN · .
the CE pin of the program ROM. ches. In Figure 14-JJ P~ 15 not used and is never activated·
• notice that PSEN is also used to activate

370

TlfE 8051 MICRoco -


N°fROLLER AND EMBEDDED svsTOfS
Re~ieW Questions
=
If EA GND, in_d icate from what source the program code is fetched.
1, Ji EA= Vee' indicate f~m what source the program code is fetched.
;: l\'hich port of the 8051 ,s used for address/data multiplexing?
l Which port of the 8051 provides DO - 07?
_ Which port of the 8051 provides AO - A7?
' ;l'hich port of the 8051 provides AS - A15? .
~ rrue or false. In accessing extemaUy stored program code, the PSEN signal is always activated.

5ECTION 14.4: 8051 DATA MEMORY SPACE


So far in this book all our discussion about memory space has involved program code. We have stated that 5~e prod
gram counter in the 8051 is 16--bit and therefore can access up to 641< bytes of program code. ln Chapter 6, we owe
Joi< to place data in the code space and used the instruction "MOVC A, @A+DPTR" to get the data. The ~OVC 1I1:5truc·
titm. where C stands for code, indicates that data is located in the code space of the 8051. 1n the 8051 fa,ruly there ,s also
,separate data memory space. 1n this section we describe the data memory space of the 8051 and show how to access
it in Assembly.

Data memory space


In addition to its code space, the 8051 family also has 64K bytes of data memory space. Tn other words, the 8051 has
12SKbytesofaddress space of which 64K bytes a reset aside for program code and the other 64K bytes are set aside for
ci,ta. Program space is accessed using the program counter (PC) to locate and fetch instructions, but the data memory
space is accessed using the DPTR register and an instruction called MOVX, where X stands for external (meaning that
the data memory space must be implemented externally).

External ROM for data


. "To connect the 8031/51 to external ROM containing data, we use RD (pin P3.7). See Figure 14-13. Notice the role of
signals PSEN and RD. For the ROM containing the program code, PSEN is used to fetch the code. For the ROM contain-
ing data, the RD signal is used to fetch the data. To access the external data memory space we must use the instruction
MOVX as described next.

8051
R~ Vee
1'3.7
P3.6 WR
A15,..,.,.. I
!'SEN
P2.7
I Al' .
A13 •
p- al OE Vpp
A12 A12
P2.0 AS 8Kx8
ALE ,C Data

l'0.7
AOL ~
' Dtif""<, A7 ROM
1

74LS373
l'O.O Auv AO AO
oc 07 DO
_.._
07

DO
rig,.,.1
4-13. 8051 Connection to External Data ROM

!os11•- 1
" ERFAClNC TO EXTERNAL MEMORY
371
Example 14-9 data ROM 1ocahons s h·ch does not have on-chip ROM) sti\11. ,
1 1
"SA,\i" has been burned in the extern• tions of an 8031 (w ,.
The wotd . 1 data RAM Joe• 1"
Wnte a program to read this data in O j
rng from 60 H

Solution: . source location)


ints to urst
·DPTRs4lOOH (po · on tOOOH
MOV DPTR, #4100H • 1ocat1
MOVX A,41DPTR ;get •s• from RAM location 60H
MOV 60H, A ,move it to dat~ to next location)
;OPTR;4l01H (points
INC DPTR

, .'

MOVX
MOV
A,@DPTR
6lfl, A
INC DPTR
MOVX A,SDPTR
MOV 62H, A

b ,med in on-chip program memory. Here, the data is


-'
END
This is• modification of Example !Hi. There, the data was '

t• burned in external
The ·lllStructJons
· data ROM.
to access on<h1p ROM
, ·LS MOVC, whereas to access extema
J ROM, th e ·nst
I ruct·on
1
·s
1
MOVX.

Example 14-10
I External data ROM has a look-up table for the squares of numbers 0- 9. Since the internal RAM of the 8031/51
has a shorter access time, write a program to copy the table elements into internal RAM starting at address 30H.
The look-up table address starts at address Oof external ROM.
Solution:
TABLE BOU OOOH
RAMTBLE SQU 30H
COUNT EQU 10

MOV DPTR, #TABLE ;pointer to external data


MOV RS,#COUNT ;counter
MOV R0,#RAl1TBLE
BACK,
;pointer to internal RAM
MOVX A,@DPTR
MOV
;get byte from external mem
41RO,A
INC DPTR
;store it in internal RAM
;next data location
INC RO
DJN<I
:next. RAM locati on
RS,BACK
:unt1l all are read

MOVX In s tru ction


MOVX is a widely used instruction aUowin
berof the8051 family is usect To bring extem!i<'>leSs toextemaldata memo
instruction will read the byte of data pointed ,0 i stored data into the CPU ry ~-pace. This is true regardless of which mern-
Jargedata space is needed, the look-up table meth~~t~ DPTR and sto' '~e.use the instruction "MOVX A @OP'J'R". ThiS
Contrast Example 14-10 with Example 5-8 from IS widely ~ . See E::: It m the accumulator. In a lk~tions where a
gram code space of the 8051 and we used the . ~apter 5. In that lllples 14-9 and 14-lO fo t~p f MOVX.
A+DPTR" and "MOVX A, 41DPTR" look ver s· mstruction "MOVc" t example the table el r e use O •
data in the data space of the micr •nular, one is used o atce$ each el ements are stored m the pro-
I0 get data ·5 h
Y
o-contro1 ler. ement. Although both "MOVC A,•
int ecode ..i
space and the other is used to to··
372
TlfEsos1 MI
CRoco NTRo --
LLER AND EMBEDDED svsra,tS
£tl)l'Ple 14-11
OM nd BK bytes of data ROM.
Sb<>"' the design of an 8031-based system with BK bytes of program R a

5olution: ROM PSEN is used to


.ch ROM Fo r prog ram ,
F,gure 14-14 shows the design. Notice the rote of PSEN and RD in ea hil CE
is activated by a s imple decoder.
~ vale both OE and CE. For data ROM, w e use RD to activate OE, w · e

8031
Vee.
Ve<:
P3.7
EA P3.6 ~
. PSEN oJ; Vp p
AtS i5E Vpp
P2.7 Al CE CE
Al A l2
A12
8Kic8 8Kx8
P2.0 AS Program
Iii A LE G Dal•
ROM ROM
P0.7 DQ
74LS373 AO
PO.O ADO
oc

Agvrt 14-14. 8031 Connection to External Data ROM and External Program ROM

from the discussion so far, we conclude that while we can use internal RAM and registers located inside the CPU for s tor-
age of data, any additional memory space for read/write data must be implemented extemally. This is discussed further next.

External data RAM


To connect the 8051 to an external SRAM, we must use both RD (P3.7) and WR (P3.6). This is s hown in Figure 14-15.

MOVX instruction for external RAM data


In writing data to external data RAM, we use the instruction " MOVX @DPTR, A" where the contents of regis ter A
~ Written 10 e xternal RAM whose address is pointed to by the DPTR regis ter. This has many applications, especially
where we are collecting a large number of bytes of data. ln s uch a pplications, as we collect data we must s tore them in
NV-RAM so that when power is lost we do not lose the data. See Example 14-12 and Figure 14-15.

Ex.mpte 14-U
(a) In Figure 14-15, what is the address space allocated to the data RAM?
tb) Write a program to tranafff an array of 10 bytes stored In locations starting from 8000 H in this RAM to loca-
tions starting from 9000 H .
Solution:
(•) The data add,- epace Is 8000 H to BFFF H.

II05t INTERFACING TO EXTERNAL MEMORY


373
d lhe destination array. The DPTR is used as th
Here two arrays have to be addressed - i.e. the sourc~ a~Yt ~e first array, the current pointing address of~
powter to address both arrays. When the ~PTR as poUl~g ~ewiSe, when the DPTR is pointing to lhe second
second array is temporarily stored in registers Rl an~ · rarily pushed on the stack.
array, the current powhng address of the first array 1s ternPo

,
.,., ARRAYl EQU BOOOH
ARRAY2 SQU 9000H
COUNT SQU 10
ORG 0 ;the number of bytes (•10) is stored in R2

MOV R2,#COUNT ;DPTR has the first address of the second array

,,-..,
MOV DPTR, #ARRAY2 ;i.e. destination array
MOV RO,DPL ;save the destination pointer in RO and Rl
, Rl,DPH
MOV
,,' MOV DPTR, ~ARRAYl
;OPTR points to the source array
' START: MOVX A,3DPTR ;move the source co A
;increment DPTR for next operation
INC DPTR
! PUSH DPH
PUSH DPL ;push DPTR onto stack
(J MOV
MOV
DPH,Rl
OPL,RO ;get the destination address in DPTR
( MOVX 3DPTR,A ;source to destination transfer
> INC DPTR ; increment
·l b OPTR to point to next des ti na t.ion
MOV RO,OPL 'ower yte of destination address in RO
MOV Rl,OPH ;upper byte of destination address i n Rl
I POP DPL
POP DPH ;get back source pointer from st k
OJNZ R2 ,START I repeat until the count is zero ac
END

8051

P3.7 ffi
P3.6 WR
PSEN I
P2.7
I 1.J',,A 15_
j)- CE WE

...
A14 v OE
Al? Al:; A 13
P2.0 Al2
ALI! ,c A8
AD7 16Kx8
l'0.7
,D Qr-<" _A7 Data
RAM
ro.o , 74LS373

oc -AO
AO
07 DO
--
~

07

fig11tt 14-15. 8051 Connoction lo Ext•m.J 0 Do


•t• RAM
374.

ROcoNTROLLER -
ANO EMBEDDED svs'l'EftlS
·ogle external ROM for code and data I ROM chip · This single
~ SI , Kx8 (27512) exicma d to
uine that we have nn 803l·based system connectt>d to a s,nglc 64 the space 0000. 7FFFH is allocate
I
; R0"1 chip is used for both program code and data s torage. For examJs~g the data, we use the MOVX i~tru;
fl' code, and address space OOOOH - FFFFH is set aside for data. 1~ ·~~ the rcvious discussion that [~EN 15 us
~ " ' do we connect the PSEN and RD signals to such a ROM? Not~ tem~l data space. To allow a single ROM
~ (1!SS the external code s pace and the RD signal is used to access~; e:te to signal the OE pin o f 1he ROM chip as
8
:,1'
t> ." to provide both program code space and data s pace, we use an A
in Figure 14-16.

8031 system with ROM and RAM .


. . . E ample 14-13.
tern This ,s shown m x,
~ are times that we need program ROM, data ROM, and data RAM ma sys ·

8031 Vee
'
EA ..~.7 R
I
+ PSEN
1'3.6

P2.7
WR
l
A t3
A tS AIS
OE Vpp

P2.0 64Kx8
1'0
,G ROM
ALE
A7 Program/
J'0.7 A07
0 o)-<f Data
74LS373 AO
1'0,0 Auu AO 07 DO CE
QC

~- 07
-b

Agvrt 14-16. A Single ROM for Both Progr•m and Data

E.umple 14-13
~rer to Figure 14-17.
11] Find thit 1ddreH lf)AC1t of thit d11A RAM, d1t1 ROM and program ROM .
/bi Writlt I progrem to 1aeM I byte of datA which It In d1t1 ROM, dlvldit it by 2, and 11v1t !hit quotient in the data
RAM
lrJ R..writlt lhlf progr•m for the cue !NI I~ data bytlt 11 in program ROM.
So111t1on:
!.i/ ltw addreH lbw A15 and Al' of the dalA RAM have to bit 10 for thlt chip to bit w lected. Hence, its addrn&
1pace 11 1000 0000 0000 0000 to 1011 1111 1111 1111 .
I~ IIOOOU to BFFfH ,
for tlw d•IA ROM, A15 and Al' hive to bit 00 for th" chip to bit wlected.
I t.-nce, lta lddre9 IIJIII" It from 0000 0000 OCXXl 0000 to 0011 1111 1111 1111 ,
l e OOOOH to 3FFfH
For IN prog,am ROM, lhtaddNM 1111ft Al, and A151NP not 1111d In add,-decodlng. l.1t. A15 and A14
""'don't a,._ How.vlf, If W.CONlder Al5 and Al4110, th.1dd,- 1pt1C1 la from OOOOH to 3FFFH. But, It
~

lt;\I INHAfAC ING 101'.XJ'f.RNAL Ml!MORV


375
, ,, A M because different instn,ictions are ,"
....
rdata RO M or "'"" ' "''ied
does not create a clash with the addreSS space o
to access code space and data space, n5fer the quotient to the fizst t
. d ta .ROM and let us 1ra C>cabon
(b) I.kt the required data be in the first locabon in a
,n data RAM.
Note that MOVX instrucilon is used to access data ROM- · n oooOH of program /
( ORG OOOOH ; load t:he program l
;memory
; let OPTR poinc co data 1ocac1on
.
l MOV DPTR,#OOOOH
MOVX A,eDPTR
MOV B,#02
, .' DIV
MOV
AB
DPTR,#8000H
.. MOVX ODPTR,A

(' END
' (c) Assume that the required data has already been burnt into location 0100H of program ROM. Here the MOVC
' •
instruction is to be used to access data from program R0,\4.
'
' ORG OOOOH
;let DPTR poinc co data location
t.l MOV
CLR
MOVC
DPTR,#OlOOH
A
A.A+@DPTR
,I MOV B, #02
DIV AB
MOV DPTR,#SOOOR
MOV X 41DPTR,A
ENO

8031
EA P3.7 R:°j~-===---- - ---,--- ---
PSEN"i--~----;~~--t-+-~~~~--~
I
P3.6

1'2.61----Al
- WR

74LS138
.
1'2.71---AJS
1---1C2B Y
G2A GI
CE WEm; -
Vee

I
'OE Vpp _
Vcr.

OEVpp
...
111

- ~~A~l~~~~~~V~cc~ A13 CE CE
1'2.0 AS
ALE t-_:_--C 16Kx8
~~Al3
16I<x8
~§~AJ3 16Kx8
Data

POO
A7 RAM
~I
~
Data
ROM
~~!
Pro~am

ROM
AO
~ AO
.___ _:D7DO

F. 00
agure 14-17. 8031 Connection to External p
rog,-am ROM
, Data RAM
376 '•nd Da~ ROM

T!iEaos1 MI
CRoco
NTROLLER -
ANO EM BEDDED sYSTEftlS "'
-
aclng to large external memory the 8051
1nterf f memory to store data. However,
IJ1 some applications we need a large amount (256K bytes, for ~xample) 0 soh·e this problem. we connect AO - A 15
uppOrt only 64K bytes of external data memory since DPTR IS lo-bit. T~ h Pl pins to access the 64K-byte blocks
1;eS051 e
directly to the external memory's AO- A15 pins. and use some; .1~ tr ted in Figure 14-18.
it6'de the single 256Kx8 memory chip. This is shown in Exan1p le 14-14, an 1 us a

S051
P3.7 To
1'3.6 WR I I
r cr m :JE
Pl.2 A17
Pl. l A16
PLO A15
1'2.7
256Kx8
1'2.0 AS Data
ALE ,c NV-RAM
AD7 A7
P0.7 DO~
74LS373 AO
PO.O ADO AO 07 00
oc
_.._
D7

DO

f,g,,rr 14-18.8051 Accessing 256KxS External NV-RAM

Eumplt 14-14
In a certain application, we need 2561< bytes of NV-RAM to store data collected by an 8051 microcontroller. (a)
Show the connection of an 8051 to a single 256Kx8 NV-RAM chip. (b) Show how various blocks of this single chip
~ accessed.

Solution:
(a) The 256Kx8 NV-RAM has 18 address pins (AO-Al7) and 8 dJta lines. As shown in Figure 1-i-18, AO- A15 go
directly to the memory chip while A16 and A17 are controlled by Pl.O and Pl.1. respectively. Also notice that
chip select of external RAM is connected to Pl.2 of the 8051.
(b) The 256K bytes of memory are divided into four blocks, and each block is accessed as follows:
Chip ~lect A 17 A16
Pl. 2 Pl ,l Pl .O Block a ddreee apac e
O O O OOOOOH-OFFFFH
0 0 l lOOOOH-lFFFFH
0 1 0 20000H·2FFFFH
0 1 1 30000H-3FFFFH
l x x External RAM disabled
For cumple, to access the 20000H - 2FPFFH address space we need the following:

~l lNTERFACLNC TO EXTERNAL MEMORY 377


al RAM
-~1e extern y block
Pl.2 ;en..., of 64K memor
CLR ·start
HOV DP'!'R,#0 '
Pl.O ;A16c0 OOOH block
CLR ;A17cl for 20m serial port
SETB
HOV
Pl .1
A,SBUF ,get data
ve data 1
f:~
block 20000H addr.
IDPTR, A I Sa , n
;nex t 1ocac10
l!OVX
/ INC DPTR
..

• ACCESSING 1K-BYTE SRAM IN ASSEMBLY . ing the MOVX instruction. Next,weWilJ


h'
Th DS89C4x0 chip family has IK byte of SRAM, w ,c
his accessible
The c versions of th ese programs are o·
by us oiven ll1
· """'·

show :ow lo access this l K byte of SRAM in Assembly language .
••
• next section .
fl

1K Byte of SRAM In DS89C4x0 . eofSRAM embedded into the chip. This is in add.
• ' The DS89C4x0 family (DS89C420/30/4~/50)com:s with !K 1;;
the DS89C4x0. This l K byte (1KB) of SRAM can
80 2 5 5
ition to the 256 bytes of RAM that comes :"'th any " ~p ';;. ~eecl to store data va riables. Another case in which
be very useful in many appLications, espec,aUy for C comp crs • 1
this 1K-byte RAM can be put to.great ) d . d f the 8051 family. To access this lK byte of SRAM
> use is the tiny RIOS (real time operating systems es,gne or . . b f RAM ·
in the DS89C4x0 chip, we mu,t use the MOVX instruction. Notice that while accessing the 256. y tes O ll1 the
8052, we use either direct or register-indirect addressing modes, but to access the d~ta stored m this 1KB of RAM,
f we must use the MOVX instruction. On power-on reset, the access to the l KB SRAi:1 1s blocked. 1n ? rder to ac~s 1~
we must enable some bits in lhe SFR registers called PMR (power management register). The PMR ts an SFR reg15ter
and is located at address C4H. The SPR location C4.H is one of the reserved byte spaces o f the 8052 used by Dallas
Semiconductor for PMR. The PMR bits related to the IKB SRAM are shown in Figure 14-19. Examine the information
in Figure 14-19 very carefully. The IKB SRAM is not accessible upon reset. This is the default state that allows us to
interface the DS89C4x0 chip to external data memory, just like any member of the 8051/52 family. To access the 1KB
SRAM, we must make PMR bits DEMO = 1and DMEl = O. In that case, any MOVX address of 0000 - 03FFH will go ID
the on-chip IKB SRAM and all other addresses are directed to the external data memory. That means that if we want IO
add external data memory to the DS89C:4x0 chip we must designate it as 0400- FFFFH since the first lK-byte space is
already taken by the IKB SRAM, assum~g that the proper bits in the PMR are enabled. Again, it must be emphasized
!h•t upo.n reset, access to the 1KB SRAM is blocked, and can be accessed only if we set the ro er bits in the PMR reg·
!Ster. Th,s must be done every time we power up the DS89C4x0.based system Stud th P fp h
we access this IKB SRAM. · Y e next ew examples to see ow

1 0 0 0
DM£1 OMEO
0
o I DME1 I DMEoJ
DATAMtMORY
ADDRESS RANGE MEMORY ACCESS
0 0 0000-FFFFH
X Ex(temal Data Memory (Default)
0000 ·03FPH After every Reset)
0400 • FFFFH lnte""1] SRAM D
External D ala Memory
0 •ta Memory
Reserved
Powtr Managemtnt Rtglator (PMR) l
,>d •t addn..,. C41I. s •n SPR In the DS8gc
4.xo family and is locat-
flguro 14-19, PMR Rtgltlor Bit, for lf<•bytt SRAM of OS

378
T HE 8051 MIC:Roco -
NTROLLE
R AND EMBEDDED SYST£~5
~420/ 30 16KB 256B JKB
~ 32KB 256B 1KB

-
~50 64KB 256B

Example 14-15 . con-


(b) multi ly l\vo by tes stored ,n
Writ.. a progra m to (a) enable access to the 1 KB SRAM of the DS89C4XO, ti le
.
securtve locations in the SRAM and (c) s to re the result in the ne,ct two toca ons u,
SRAM and also o utput the

result bytes to port Oand port 1.

Solution:
DATA EOU 00001!
ORG 0
MOV A, OC4H ;read PMR register
inldd- ;make DMEO~l
~an SETB ACC.0
MOV OC4H , A ; e nable l K8 SRAM
lwhich
MOV OPTR,#DATA
SRAM MOVX A,<itOPTR
I in 1hr MOV B,A
I RAM. I NC OPTR
cc:as it MOVX A, @DPTR
regiP'I' MUL AB
I Dalin l NC OPTR .
rmalioll MOVX <itDP'l'R , A
nus to MOV PO ,A
the llCB INC OPTR
ill go to MOV A,B
MOVX @OPTR,A

._,_
w8111IO
If*""
MOV
END
Pl,A

!dllief'
-)loW

Example 14-16
Wnte a program to (a) enable access to the 1 KB SRAM of the DS89C4x0, and (b) add two 16 bit numbers. One
number is stored in the external SRAM in two consecutive locations 0400H onwards, with the l.SB in the lower
address. The other 16-bit number is stored in internal RAM locations 45H and 46H. The result is stored in the next
locations in internal RAM .
I'
Solution:
DATA EQO 0400H address of LSB of first number
ORG 0
MOV A, OC411 ;read PMR register
SETB ACC.0 ;make DMEO•l
MOV OC4H,A ;enable l KB SRAM
CLR C ; clear C
MOV OPTR, #DATA 1 let OPTR point to LSB of the 16 bit word
-

8051 INTERFACING TO EXTERNAL M EMORY 379


·-ove LSB to A in ~•M location 45H
MOVX A,@DPTR ,,., byte ,.,... ..
ADD A, 45H ;add it to the location 4 7H
MOY 47H,A ,move sum to RAM int to upper byte
'.increment DPTR cop~
!NC DPTR • co ,..
MOVX A••DPTR ,move uppel-' byte , R)IM 1ocatiOD 46H
• the byte 1n
, l\DDC A,46H ;add it coco RAM 1ocation 48R
.r MOV 48H,A ,move sum
cLR A ; clear A
ADDC A, ijOO
MOV 4 9H. A
; AsA+O+C
; move A into RAM loca
.
tion 48H

dh the carry bit holding the extra bit. This carry is


'
• The result of adding two 16-bit numbers may be 17 bits, '" . 49H I
' I mo"ed in to A, which is then transferred to internal RAM location ·


f)
I

I Example 14-17

~l
Write a program in Assembly (a) to enable access to the 1KB SRAM of the DS89C4x0, (b) move a block of data
from code space of the D589C4x0 chip into LKB SRAM, and (c) then read the san1e data from RAM and send it to
the serial Pl)rt of the 8051 one byte at a time.

Solution:
Dl\TA_ADDR EQU 400H ;code data
r COUNT EQU 5 ;messsage size
RAM_l\DDR EQU 40H ;8051 internal RAM address
ORG 0
ACALL COPY l ;copy from code ROM to internal RAM
MOY l\,OC4R :read PMR of DS89C4x0
SETI! ACC.O :enable PMR bit for lK SRAM
MOV OC4H,A ;write it to PMR of DS89C4x0
ACl\LL COPY_2 ;copy from internal RAM to 1KB SRAM
MOV J
TMOD,#20H ;set up serial port
MOV THl,#-3 l
;9600 baud rate
MOV SCON,#SOH l.
Sl!TB TRl l
ACl\LL COPY_COM i.
,copy from 1KB SRAM .
SJMP ;stay here to ser1al port
'
$
COPY
-·MOV
l ·
DPTR, #DATA l\DDR
7.
MOV RO • #RAM l\DDR
MOV R2,#COONT
Rl, CLR
MOVC
A
A,eA+DPTR
s
MOV eRO ,l\
INC DPTR h
INC RO 4
DJNZ R2,l!l
RET '
;-----transfer data f
COPY_2:
HOV DPTR,#0
rom internal RAM
to external
'I
1DS89C4xo lk!I RAM
ad(h,

380
THE sos
lM1cRoco l
NTROLLER -
ANO EMBEDDED svs,VCS •
I
MOV RO, #RAM_!>.DDR
MOV R2,IICOUNT
internal RAM
;get a byte from sRAM
MOV A, 4DRO of DS89C4x0
112: ®DPTR, A ;store it in 1KB
MOVX
INC DPTR
INC RO
DJNZ R2,H2
RBT
.~~~--data transfer from lKB SRAM to serial port
roPY_COM:
MOV DPTR,#0 ;OS89C4XO 1KB addr
MOV R2, #COUNT 1KB sRAM space
M()VX !>.,@DPTR ;get a byte from
H3: ;send it co com pore
!>.CALL SERIAL
INC OPTR
DJNZ R2,H3
RET
·-----send data to serial port

Sl!RIAL:
MOV SBUF,!>.
H4: JNB Tl,H4
CLR TI
RET
--~data in code space
ORG 400H
!l'll!YTE: OB "HELLO"
END

Review Questions
1. The 8051 has a total of_ bytes of memory space for both progran, code and data.
2. All the data memory space of the 8051 is (intemal, external).
3. True or false. In the 8051, program code must be read-only memory.
4 True or false. In the 8051, data memory can be read or write n,emory.
5. Explain the role of pins PSEN. RD, a.nd WR in accessing extemal memory.
6. True or false. Every 8051 chip comes with 1KB of SRAM.
7. True or false. Upan reset, access to the 1KB SRAM of the DS89C4x0 is blocked.

SECTION 14.5: ACCESSING EXTERNAL DATA MEMORY IN 8051 C


In Chapter 7, we showed how to place fixed data into the code space using 8051 C. In that chapter we also sho,ved
how to access fixed data stored in the code space of the 8051 family. ln this section we show how to access the external
data space of the 8051 family using C langu.age. To access the external data space (RAM or ROM) of the 8051 using C,
We use XBYTE(locl where loc is an address m the range of 0000- FFFPH. Example 14-18 shows how to write some data
lo t'l(lemal RAM addresses starting at 0. Notice that the XBYTE function is part of the absacc.h header file. Examine
Examples 14-19 and 14-20 to gain some mastery of accessing extemal data memory using C.

Accessing DS89C4x0's 1KB SAAM In C


In Section 14.4 we discussed how to access the 1KB SRAM of the DS89C4x0 chip using Assembly language. Examples
14·21 and 14-22 will show the 8051 C version of some of the Assembly programs.

IIOSl lNTERFAClNC TO EXTERNAL MEMORY 381


E.u mple 14-18 ,. te(Tlal RAM a
ddresse5 startiJ1g at 0, then (b) get the S<l!nt-
'
~
'A' to 'E in ex
Wntea C program (a) to store ASCH letters P1 one byte at a tiJne.
data from the external RAM and send 11 to

Solution:
/ #include <regSl.h> file for xsYTE
#include <absacc.h> //notice the header

void main(void)
(
unsigned char x; location O
,.
~
to External
I
XBYTE (OJ•' l>,; //write ASCII , A' location 1
to External
., XBYTE[l )='B'; //write ASCII '8' location 2
• XBYTE (2) •' C'; //write ASCII , C' co sxcernal
()
XBYTE(3)•'0';

' XBYTE(4)•'E';
for(x•O;x<S;x++) d and send it to Pl
-
I
Pl•XBYTE[x); //read external RAM ata

R~ the above program on your 8051 simulator and examine the contents of xdata to verify the result.

'

Example 14-19
r
An external ROM uses the 8051 data space to store the )ook-up table (starting at 100H) for DAC data. Write a C I
program to read 30 bytes of table data and send it to Pl.
I
Solution:
#include <regSl.h>
,
I

#include <absacc.h> //notice the header ftle for XBYTE


I
void main (void)
{ 1
unsigned char count,
for(coun~=O;count<30;count++)
Pl=XBYTE[OxlOO+count);
)

- Example 14-20

Assume that we have an external RAM with addre

//not ice the h


eac:1.er file

382
TliEso51 ...
..uCRocoN -
TROLLER ANO EMBEDDED svsfEMS
..'
-
unsigned char msg [SJ •"Hello";

,ioid main (void)


t unsigned char x;
TMOD = Ox20; //OSE TIMER 1,8- BIT AOTO·RELOAD
THl • OxFD; //9600
SCON = OxSO;
TRl • 1;

for(x• O;x<S;x++)
XBYTE(OxOOO +x] = msg[x];

for(X=O; x<S;X++)
{
SBUF = XBYTE[OxOOO+x];
while(Tl=•O);
Tl•O ;
}
}

wmple14-21
Write a C program (a} to enable the access to the 1KB SRAM of the DS89C4x0, (b) put the ASCll letters 'A', 'B'
and 'C' in SRAM, and (c} read the same data from SRAM and send each one to ports PO, Pl, and P2. This is the C
version of an earlier example.

Solution:
!include <regSl. h>
~include <absacc. h> //notice the header file for XBYTE
sfr PMRREG • OxC4;

void main (void)


I
unsigned char x;
PMRREG = Ox81;
XBYTE[O]='A'; //write ASCII 'A' to External RAM location O
XBYTE [l] •' B'; //write ASCII 'B' to External RAM location 1
XBYTE(2]•'C'; //write ASCII ·c· to External RAM location 2

for(x=O;x<J;x++l
{
PO•XBYTE[x); //read ext RAM data and send it to PO
Pl•XBYTE[x]; //read ext RAM data and send it to Pl
P2,.XBYTE (x] ; //read ext RAM data and send it to p2
l
l

lils1 INTERFAONG TO EXTERNAL MEMORY 383


block of data from the CCdt
~

9C4,c0, (b) mo~and send it to the serial po,t


wmplet4-22 tothe!KBSRAJMdofthesatne
the [)58 data from SR
am to /a) enable aCCC5S !\1 then (c) rea
~'/rite a C P~9C.J20 chip into 1KB SRA. '
space of the .
of the 8051 one byte at a ttme
,
I
/ Solution: '-
#include <regSl.h> data space
l
J #include <absacc.h> / /needed for extern1·na DS89C4XO
ddress
sfr PMRREG - OxC4; I /PMR reg a

,.,-. void main (void)


I - •HELLO"; //data i n code space .'
,,•
. ed char msg (] -
code uns1gn . RAM bit "
' unsigned char x,I Oxl; / /enable 1KB S t up in PMR reg
I
• PMRR.EG • PMRREG //serial port se
TMOD • Ox20; / / 9600 baud rate
I THl = OxPD;
SCON = OxSO;
TRl • l;
for{X=O; x< S; X++) //transEer data from code a rea to 1KB SRJ\M
{
XBYTE[OxO+x] • msg (x] :
}

I for(x•O; X< S;x++) //send data from 1KB SRAM to serial port
{
SBUF = XBYTE (OxO+x];
while (TI==O);
TI=O;
}
while Ill; //and stay here forever
) SEC

Note: This is the c version of Example 14-17 19.


~.
n

SUMMARY

This chapter described memory interfacing with 8031/51-based systems. We began with an overview of semicon·
ductor memories. Types of memories were compared in '.erms of their capacity, organization, and access time. .
ROM (read-only memory) as nonvolable memory typically used to store programs. The relative advantages of van·
ous typesand
ErROM mask were
of ROM ROM.described in this chapter, including PROM, EPROM, UV·EPROM, EE PROM, flash memory

RAM (random-acce5$ memory) is typically used to store data or programs Th tt· d f its various
types indudingSRAM, NV-RAM.checksum byte RAM,and DRAM w d' · ere1a ve a vantages o
Address decoding techniques using simple logic gates, decode;s =~e tSCussed. . RAM
and ROM memories were interfaced with 8031 systems, and pro am; w d pro~rammable logic were covered.
J;
these external memories. The 64KB of external data space of the
1
was e_re Written to access code and data st~redooth
011
Assembly and C to access them Finally, the IKB SRAM memory f th ~~sed, and programs "'ere written m ed
how to access it in both Assembly and C. 0 e ~.:>09C4xo Chip was explored and we show
pflosLEMS
ON 14.1: SEMICONDUCTOR MEMORY
5£Cfl ?
\l'hJ!I is the clliference in capacity between a 4M memory chip and 4M of computer memory·
: If a memory ~hip has 20 address lines, it has the capacity to address bytes.. ti ular application?
• \'\'hat are the important characteristics to be considered in choosing a mem~ry chip for a par c
J. 1rue or false. The more data pins, the higher the capacity of the memory chip.
t \'/hat is the advantage of having more data lines?
~ The speed of a memory chip is referred to as its .
True or false. The price of memory chips varies according to capacity and speed.
~ The main advantage of EEPROM over UV-EPROM is-- - - -
9, true or false. SRAM has a larger cell size than ORAM. . .
!O. Which of the following, EPROM, DRAM, or SRAM, n,ust be refreshed periodically?
II, What type of ROM has the 89C51?
t2. Why is SRAM considered as a volatile memory?
J3 RAS and CAS are associated with which n,emory?
(a) EPROM (b) SRAM (c) DRAM (d) all of the above
It Which men,ory needs au exten,al multiplexer?
(a) EPROM (b) SRAM (c) DRAM (d) all of the above
15. Find the organization and capacity of memory chips with the following pins.
(a) EEPROM A0 - Al4, DO - 07 (b) UV-EPROM AO - Al2, DO - D7
(c) SRAM AO- A11, DO- D7 (d) SRAM AO-A12, 00 - 07
(e) ORAM AO- AlO, DO (I) SRAM AO - A 12, DO
(g) EEPROM AO- Al 1, DO · 07 (h) UV-EPROM AO - AlO, DO · 07
(i) DRAM AO- A8, DO - 03 Gl DRAM AO· A7, DO - 07
16. Find the address and data lines for the following memory chips .
(a) 64Kx8RAM (b)32Kx8ROM
(cl 64 K x 16 ROM (d) 256 x 4 RAM
17. Find the checksum byte for these bytes: 34H, 54.H, 7FH, I lH, E6H, 99H 07-00
18. For each of the following sets of data (the last byte is the checksum byte)
AO AO
,·erify if the data is corrupted.
(a) 29H, lCH, 16H, 38H, and 60H (b) 29H, lCH, 16H, 30H, and 60H Al3
16Kx8
SECTION 14.2: MEMORY ADDRESS DECODING A14
AlS cs
19. F'md lhe address range of the memory design in the diagram.
10. For a SK RAM, explain an address decoding scheme using sinlple gates.
21. Find the address range for YO, Y3, and Y6 of the 74LS138 for the diagrammed Diagram for Problem 19
design.
22. Using the 74138, design the memory decoding circuitry in which the memory block
controlled by YO is in the range OOOOH to lFFPH. Indicate the size of the memory block
controlled by each Y. . 74LS138
23. Find the address range for Y3, Y6, and Y7 m Problem 22. A12 A
H. Using the 74138, design memory decoding circuitry in which the memory block con- A13 B
trolled by YO is in the OOOOH to 3FFFH space. Indicate the size of the memory block A14 C
. controUed by each Y. . . . GNO
25. The chip select line of a memory chip tS usually active _ _ GND
Al5
SECTION 14.3: 8031/51 INTERFACING WITH EXTERNAL ROM
26. For an 8031 with external program memory of 41<, if the starting address is 0000. the Diagram for Problem 21
last address is .
27 What is the role of the chjp 74LS373 in Figures 14-9 and 14-10?
28. Can data be stored in program ROM?
29. The 8051 supports a maximum of K bytes of p~ogram memory space.
JO. True or false. For any member of the 8051 family, tf EA = Gnd the microcontroller fetches program code fr
external ROM. om

~SJ INTERfACTNG TO EXTEJlNAL Ml!MORY 38.5


ROM is to be added to the systern?
rogram
if externa I P de?
has to be changed, for program co
Whi h in connection of the 8051 exterl'lal memory
~! For ~.hfci, of the lollowinlg(; )u:-~e have am code optional? I 'I
(a) 8751 (b) 89C51 (c) 803 . :> I memory tor progr ,' I
33 For which of the following 15 ext!ma ~
(a) 8751 (bl S9C51 (cl 8031 (d) 80;)2
34
35.
·
t:
In the 8051 , which port prov'.des
0
_ A7 address bi~?
~S-A15 address bits?
1n the 805 I. which port prov'.des th DO· D7 data bits?
I

; ' 36. In the 8051, ,~hich port pro,~des t e = 0 and ALE= J. ?


37. Explain the difference between.ALE of P3. What about PSENode from external ROM?
38. RD is pin of P3, and WR 15 pm - ed . fetching program c
39. Which of the following signals must be us in
1
(a) RD (b) WR (c) PSEN . M how are they acc~ed · ro am ROM and data ROM?
• .w. If a system has on-chip and ofl:chthip ~f :ence in the connechon to the P Jn~ther words, the memory code space
41 In an 8051-based system, what ,s e e t be read-only memory. ''
. 8051 th ogrnm code mus l
• 42. True or false. For the · e pr ( ff hi ) code ROM?
• of the 8051 is read-only memory. . hlp code ROM or externa1 O ·C P ·
I ' 43. Indicate when PSEN is used. ls it used in accessing on-< .I
).
'•
SECTION 14.4; 8051 DATA MEMORY SPACE ?
used in accessing external data memory.
44. Indicate when RD and WR are used. Are they be directly connected to the 8051?
45. What is the maximum capacity of a data RA~ t~•::;g data from external data ROM?
46. Which of the following signals must be used m ,e '•
(a} RD (b) WR (c) PSEN (d} both (a) and (b) . .
47. For each of the following, indicate if it is active low or active high.
(a) PSEN (b) RD (c) ViR d dift ti t between the 1Jwe
48. If a system uS<!S data RAM, data ROM and program ROM, which pins are use to eren a e .
r 49 With an example show ho1v the instructions MOVX and MOVC are used. ,..
so: Write a program' to transfer 20 bytes of data from external data ROM to internal RAM. The external data ROM
address is 2000H, and internal RAM starts at 60H. SE(
51. Write a program to transfer 20 bytes of data from internal RAM 40H onwards to external data RAM location Start·
ing from AOOOH.
52. Write a program in Assembly to transfer 50 bytes of data from external data ROM to external data RAM. The exter- ,l
nal data ROM address is 3000H, and the external data RAM starts at SOOOH. J
53. Write a program in Assembly to transfer 50 bytes of data from external data ROM to 1KB SRAM of DS89C4x0. The l
external data ROM address is 3000H, and the SRAM data starts at OOOOH.
i
54. Write a program in Assembly to transfer 50 bytes of data from IKB 5RAM of DS89C4x0 to Pl one byte at a time
every second. The SRAM data starts at 0200H.
55. Give the address of the PMR and its contents upon reset.
56. Which instruction is used to access the SRAM available in DS89C4 0'
57. For the DS89C4x0, the 1KB SRAM is (available blOC:ed •I
58. What memory space is available for expansion if DMEO,. ' d ,,,.. l upon reset.
59. What memory space is available for expansion if DMEO 0 and 0 ""'1 = O?
= I an 0 MEI,. O?
SECTION 14.5: ACCESSING EXTERNAL DATA MEMORY IN 80SJ C
60. Write a program in C to transfer 20 bytes of data fr
address is 2000H, and internal RAM starts at 60H om external data ROM to internal o • , • Th t I d ~ ROM
61 • Wr,·1 ea program ·in c to trans1er 30 bytes of dat fr· · '""v1. e ex ema a,.
address is 6000H, and internal RA,l,f starts at 4~ orn internal data RAM to exte I RAM Th RAM
62. Wntc a progra.m in C to transfer 50 bytes of data from ma , e external data
ROM address 1s 3000H, and the external data RAM external data ROM toe
63. Write a program in _c to transfer 50 bytes of data fr starts at 80001-t. xternal data RAM. The external dat,
data ROM address IS 3000H, and the SRAM dat om extemai data ROM t
64. Write a program in C to transfer 100 bytes of da/tarts at 000oH. 0 1KB SRAM of DS89C4x0. The external
second. TheSRAM data starts at 0200H. ta from 1KB SRA.M of OS
89C4xo to Pl one byte at a time e,•ery
386
NSWEAS TO REVIEW QUESTIONS
A
sfC110N 14.1: SEMICONDUCTOR MEMORY

(. (a) 16J<x8, 128K bits (b) 64Kx8, 512K (c) 4Kx8, 32K
2- (a) ZJ<xl, 2K bits (b) 8Kx4, 32K (c) 128Kx8, 1M
J. (d) 64Kx~, 256K (e) 256Kxl, 256K (f) 256Kx4, 1 M
i (a)641< bats, 14 address, and 4 data (b) 256K, 15 address, and 8 data
(c) JM, 10 address, and 1 data (d) lM, 18 address, and 4 data
(e) Sl2K, 16 address, and 8 data (f) 4M, 10 address, and 4 data
;. b, C

5ECf10N 14.2: MEMORY ADDRESS DECODING


1. 16K bytes
!. 3, 8
,_ Both must be low.
4. Gl must be high.
·l , 5000H · 5FFFH
SECTION 14.3: 8031/51 INTERFACING WITH EXTERNAL ROM
1. From external ROM (that is off-chip)
z. From internal ROM {that is on-chip)
J. PO
t PO
5. PO
6. P2
1. True

SECTION 14.4: 8051 DATA MEMORY SPACE


1. 128K
2. External
3. True
4. Troe
S. Only PSEN is used to access external ROM containing program code, but when accessing extemaJ data memory we
must use RO and WR signals. In other words, RD and WR are only for external data memory and are never used
for external progran, ROM.
6. False
7. True

lost INTERfAONG TO EXTEJlNAL MEMORY 387


CHAPTER15

8051 INTERFACING
WITH THE 8255

O BJECTIVES

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

> Describe how to expand the l/0 ports of the 8031 /51 by connecting it to an 8255 chip
> List the 3 ports of the 8255 and describe their features
> Explain the use of the control register of the 8255 in selecting a mode
> Define the modes of the 8255
> Define the term memory-mapped 1/0 and describe its application
> Program the 8255 as a simple 1/0 port for connection with devices such as stepper motors, LCDs,
and AOC devices
> Interface the 8051 with external devices such as stepper motors, LCDs, and AOC devices via
the 8255
> Diagram the 8031 interf~ce with external program ROM and the 8255
> Explain how address aliases are used m address decoding techniques
> Program the 8255 as a simple 1/0 port ln 8051 C

389
Table 15-1: 8255 Port Selection
~o, A1, and~
CS Al AO Selection
1,rtule ~ (~p select) selects the entin! chip, ii is AO and Al
d',,ll ;elect speofic ports. :"ese three pins are used to access ports 0
o o Port A
~- B. c. or the control register as shown in Table 15-1. Note that is 0 1 Port B
0
.,ctii·e-lOW, PortC
0 1 0
1 Control register
0 1
~ode selection of t he 8255 8255 is not selected
X
1 X
1\'hile ports A, B, and C are used to input or output data it is
tilt' control register that must be programmed to select the o~era· .
b(1l1 mode of the three ports. The ports of the 8255 can be programmed in any of the followtng modes.

1. Mode 0, simple 1/0 mode. In this mode, any of the ports A, 6, CL, and CU can be programmed a~ input ~r ou~~~
In this mode, all bits are out or all are in. In other words, there is no such thing as single-bit contro as we aves .11
in PO· P3 of the 8051. Since the vast majority of applications involving the 8255 use this simple I/0 mode, we wt
concentrate on this mode in this chapter.
1. Mode I. In this mode, ports A and 6 can be used as input or output ports with handshaking capabilities. Handshaking
signals are provided by the bits of port C. This mode will not be explored further in this book.
3. Mode 2. ln this mode, port A can be used as a bidirectional l/0 port with handshaking capabilities whose signals
are provided by port C. Port 6 can be used either in simple 1/0 mode or handshaking model. This mode will not
be explored further in this book.
t BSR (bit set/ reset) mode. ln this mode, only the individual bits of port C can be programmed. This mode will not
be explored further in this book.

Figure 15-3 shows the control word for mode selection of the 8255.

Simple 1/0 pro gramming


Intel calls mode Othe basic i11p11t/011tput mode. The more commonly used term is simple 1/0. In this mode, any of ports
A. B, or C can be programmed as input or output. It must be noted that in this mode, a given port cannot be both an
input and output port at the same time.

Group A - - - - - - - - ~... - - - - - GroupB

07 06 05 04_ D3 D2 01 DO

-
'-
I= l/0 Mode
0= BSRMode I I 1Port A~
= Input
O=Output
L V!ode Selection
O=ModeO
1 = Mode 1
-
" -·-
Porte
(Lower
PC3 - PCO)
1 = lnput

Mode Selection
.
Porte
... ~Port,. B ..0 • Ou"'"'
00= ModeO
01 =Mode l
(Upper
PC7 • PC4)
= Input
Output
J
lx = Mode 2 . 1 = lnput
0= Output

Figu,t 15-J. 8255 Control Word format (UO Mode) .


'R.q,nnted by permission of Intel Corporation, Copyright Intel Corp., 1983)

8051 llliTERfAONG WITH THE 8:ZSS


391
(

Example IS-1 nfigurations:


f111d the control word of lite 8255 for the foUoWll'lg co
(al All the ports of A, 8, and Care output p<>rtS (mode OJ.
lb) PA ,,in, PB = out, PCL = out, and PCH = out.

/ Solution:
Fmm Figure 15-3 we have:
(a) 1000 0000 = 80H
(b) 1001 0000 =90H
• Connecting the 8031/51 to an 8255
The 8255 chip is programmed in any of the 4 modes mentioned earlier by ~nding a byte (Intel calls it a control
word) to the control register of the 8255. We must first find the part addresses assigned to each of ports A, B, C, and the
.
••
'I control register. This is called mapping the l/0 port. . . . . _
~an be seen from Figure 15-4, the 8255 is connected to an 8031 /51 as tf 11 1s RAM memory: Not.1c~ the use of RD
'• and WR signals. This method of connecting an 1/0 chip to a CPU is called 111emory-111npped 1/0, smce it 1s mapped into
I memory space. Ln other words, we use memory space to access l/0 devices. For this reason we use instructions such as

\.IOVX toac-cess the 8255. In Chapter 14 we used MOVX to access.RAM and ROM. For an 8255 connected to the 8031/51
we must also use the MOVX instruction to communicate with it. This is shown in Example l5·2.
I
I E
,\ Exa.mple lS-2
F
Rderlng to Figure 15-4.
!,
I (a) Find the addresses for the portS A, B, and C and the control register.
(b) ~our S\Vttches are connected to the lower +bit lines (PBO • PB3)
;~•.~x;gr•m to transfer the $talus of these switches to LEDs connected to the upper 4-bits of port A 's
(1

Solution;
~
(a) :11c•ddress oflhe ports is such that only if Al4 is 'I' th ch' .
or the ports and oonttol register are as follows: e 'P will be selected. Also the condition of J\ 1 and AO
Al AO
Port A 0 O
Port B 0 1
Port C 1 0 (
Control Register 1 1 (
The rest of the address lines can be 1 0 F
for ~rt A, 4001H for port B, 4002H cZ:~ri°r example, if we take all th .
i!
(b) ~'":::~-;::1.~ information has to reaf;;;~l~OO}H for the contr:C~;=~s 0, the addresses will be 4000H
, IS connected to LEDs which displae d tegtSter, port 8 has to be~ .
MOV l\, lt82H y ata fed into 11. The control input port. Port A is an output
MOV DPTR, #4003H :move contr 1 word JS 10000010, 1.e., 82H
MOVX ~DPTR,A ;load Cont O Word to A
MOV DPTR,#4001H ;issue con~ol register ad~-
MOVX A,eDPTR ;move rot word -.u.ess
SWAP A :move P~rt B address t~ control register
:swttc~ ~~be data to Ao DPTR
MOV DPTR, #4000H ; to the l bles of A t O
MOVX
ENO DPTR, l\ , move Portupper
A nibbl e bring switch· data
:move the address to DPTR
content of
A to Port A

392
ii{£ sos1 l\fJc:ao
CONiROLLER -
AND EMBEDDED SYST~IS
SOS1
P3.7 RD
P3.6

P2.7
WR
A14 cs
- -
WR RD

PA
P2.0 8255 PS
ALE --, G re
P0.7 A07 ;o ,. ..r-,. Al
... "> '-- Al
AO
74LS373 '-- AO
PO.O
AOO 07 DO RES
oc --I
_J_
. 07

DO

r,gurt Js-4. 80S1 Connec:lion to the 8255 for Example 15·2

Example 15-3
For Figure 15-5,
(a) Find the 1/ 0 port addresses assigned to ports A, 8, C, and the control register.
(b) Find the control byte for PA = in, PB =out, PC = out.
(c) Write a program to get data from PA and send it to both p orts Band C.

Solution:
(a) Assuming all the unused bits are Os, the base port address for 8255 is 1000H.
Therefore we have: 1000H PA
1001H PB
1002H PC
1003H Control register
lb)The control word is 10010000, or90H.
{c)
A,#90H ; (PAolN,PB•OUT,PCeQl.J'l')
MOV
OPTR,#1003H; ;load control reg port addr
MOV
;issue control word
MOVX @DPTR,A
OPTR,#lOOOH ;PA address
MOV
;get data from PA
MOVX A,.DPTR
;PB address
INC DPTR
;send the data to PB
MOVX /IDPTR ,A ;PC address
INC OPTR
;send it also to PC
MOVX eoPTR,A

rtexLFor the program


· in Example 15-3, it is recommended that you use the EQU directive for port addresses as s h own

"1>oRT EOU lOOOH


BPORT EOU lOOlH
CPORT EOU 1002H
CN'FPORT EOU 1003H

~l lNTERFAONG WITH THE 82.55 393


.

8051
-RB- I
!
PJ.7 WR A)~ WR ru5
P3.6 I
• V
Al4-,,,- ~- b- ~
AJJ-v ./ PA
P2.7 Al
8255 PB
.,.• P2.0
G PC 1--.
ALE
...... Al
AD7
V P0.7 D !J
74LS37.3

-AO
AO
D7 DO RES

• I•
• PO.O ADO oc I
.
•, .;- 07
(I•
•• DO
(

.
~ Figute lS-5. 8-051 Connechon to the 8255 fo r Example lS-3
I HOV A,#90H ;(PA=IN,PBsOUT,PC=OUT1dr
'
I
I MOV OPTR, #CNTl?ORT ;load cntr reg port a
' MOVX @OPTR, A ·issue control word
MOV '
OPTR, #A PORT ·PA address
MOVX A,@OPTR ;get data from PA
INC OPTR ;PB address
MOVX eOPTR,A ;send the data to PB
INC OPTR ;PC address
MOVX COPTR,A ;send it also to PC
or the following, also using EQU:
CONTRBYT EQU 90H ;(PA=IN,PB=OUT,PC=OUT)
BAS825SP EQU 1000H
;base address for 8255 chip
MOV A, #CONTRBYT
MOV OPTR,#BAS8255P+3 ;load c port addr
MOVX @OPTR, A
MOV OPTR, #BAS8255P ;issue control word
;PA address

Notice in both Examples 15-2 and 15-3 that we used the DPTR register since the base address assigned to 8255 was G
16-btt tf the base ad¢'ess for the 8255 is 8·bit, we can use the instructions "MOVX A, @RO" and "MOVX @RO, A" where RO (or
RI) holds the 8-bit port address of the port. ~ Exa_?lp!e 15-4. Notice in Example 15-4 that we used a simple logic gate to do
the address decoding for the 8255. For multiple 8255s ma system, we can use a 74LS138, as shown in Example 15-5.

Example 1S-3a

R~fernng to Figure 15·5,


-
(a) fmd the addresses of the ports and control register.
(b) Write a progr.tm to generate a square wave at bit O of port C.
Solution:

(a) Assuming all the unused address lines are 0, and noting that Al has
2
to be l, the addresses are
394
ll-11; sos11vucao -
CONTROLLER AND EMBEDDED svsT£ftf5
rort ;\ 1000H
rort B 1001H
rortC 1002H
(Ofltrol register 1003H
(b)Togenerate a sq~are wave of any time period with a 33'Yoduty cycle, it is necessary to have an OFF time which
iS twice the ON ttn,e.
To have the square wave at PCO, PCL must be an output port. All the other ports can be configured in any way.
The control word is 10000000, i.e., 80H
MOV A, #80H ;control word to A
MOV DPTR,#l003H ;DPTR points to control register
MOVX @DPTR,A ;transfer control word
MOV DPTR, #1002H ;DPTR points to port C
START: MOV A,#OlH ;A:OlH
MOVX @DPTR,A ;PCO:l
ACALL DELAY ;call a delay for the ON time
MOV A,#OOH ;A=O
MOVX @DPTR,A ;PCOeO
ACALL DELAY ;call delay for OFF time
ACALL DELAY ;one more delay time for OFF time
SJMP START ;repeat to generate a continuous waveform
END

Eumple15-4
For Figure 15-{;, a switch SW is connected to PCO.
(a) If SW = 1, the data received from port A is to be trans ferred to port B.
(b) If SW = O, the data received from port B is to be transferred to port A. Write a program for this to be done
continuously.
Solution:
We have two cases
(I) \Vhen SW= 1, port A is an input port and port Bis an output port. Port C lower is an input. The control word
is thus 10010001 = 91H
o,
(2) \\fhen SW = port Bis an input port and port A is an output port. Port C lower is an input port. The control
word then is 10000011 = 83H. From Figure l!>-6, we see that the addresses of port A, B, C and Control register are
respectively, 20H, 21 H, 22H and 23H.
CWDl 8QU 91H
CWD2 EQU 83H
PORTA EQU :IOH
PORTS EQU :llH
PORTC BQU 22H
CONREG EQU 23H
A, tClfDl ;move one of the control words into A - this
NOV
;ensures that port Clower is an input port
RO,ICONRBG ;move the control register address to RO
NOV
;move the data in A to the address pointed
MOVX IIRO, A ;by RO, i.e., the control register
IPT, ,move port C address to RO
NOV RO,t»oRIC ;get port C data into A
MOVX A,91l0 •
'- . . •
lilsi INT£RFACING WITH THE 8255 395
port A 1OOOH
port 8 1001H
portC 1002H
cootrol register 1003H .
. . to have an OFF tin1e which
(b) To gE:"erate a sq~are wave of any time period with a 33•;0 d u ty cycle, 11 IS necessary
is twice the ON lime. d · way
To have the square wave at PCO, PCL must be an output port. All the o the r ports can be configure in any ·
The control word is 10000000, i.e., 80H
MOV A, #80H ; control word to A
MOV DPTR,#l003H ; DPTR points to control reg i ster
MOVX @DPTR,A ; t r ansfer control word
MOV DPTR,#1002H ;DPTR points co port C
START: MOV A,#OlH ;AsO lH
MOVX @DPTR, A ;PCO=l
ACALL DELAY ;call a delay for the ON time
MOV A,#OOH ;A=O
MOVX @DPTR,A ;PCO=O
ACALL DELAY ;call del ay for OFF time .
ACALL DELAY ; one more delay time for OFF time
SJMP START ;repeat to generate a cont inuous waveform
END

Example 15-4
For Figure 15-6, a switch SW is connected to PCO.
(a) If SW= l, the data received from port A is to be transferred to port B.
(b) If SW = 0, the data received from port B is to be transferred to port A. Write a program for this to be d on e
continuously.

Solution:
We have two cases
(I) When SW= 1, port A is an input port and port Bis an output port. Port C lower is an input. The control word
=
is thus 10010001 91H
(2) When SW= O, po rt 8 is an input port and port A is an output port. Port Clower is an input port. The control
word then is 10000011 = 83H. From Figure 15-6, we see that the addresses of port A, B, C and Control register are
respectively, 20H, 21H, 22H and 23H.
CWDl BOU 91H
CWD2 EOU 83H
PORTA EOU 20H
PORTB EOU 21H
PORTC EOU 22H
CONREG EOU 23H
MOV A, #CWDl ;move one of the control words into A - this
;ensures that port Clower is an input port
MOV RO, #CONRJIG ;move the control register address to RO
MOVX •RO, A ;move th~ data in A to the address pointed
;by RO, i.e., the control register
RPT: MOY RO, tl'ORTC ;move port C address to RO
MOVX A,eRO ;get port C data into A
.

80s1 INTERFACING WITH THE 8255 395


' . g A into carry
rota tin
of A bY THERE
-

RRC A JUIIIP co he control word


JC THERE change t
l!ERE: HOV A,#CWD2;
MOV RO,#CONREG
MOVX tRO,A input port B
oint co A
HOV RO, #PORTS ; let RO ~ B data into ort A
MOVX A,l'RO get por output P
MOV RO,#PORTA '.1et RO point to1·n A co port A
• h data
MOVX RO, A ·move t e rocess
) '.repeat the p co input port A
L SJMP RPT
THERE: MOV RO,#PORTA '.1et RO point input port A to A reg.
MOVX A,f/RO '
;move da ta ' from
nt to output p ore B
• • MOV RO,ffPORTB , let RO poi·n A to port B
.•' MOVX @RO,A ·move data l
'
SJMP RPT ;repeat
" I
END

'
r. P3.7 RD
t P3.6 WR _[
' WR RD
8 A~ ' p cs
0
,-A•
-A3 A2
"'
PA

-
r 5
I
ALE C 8255 PB
.J
P0.7

PO.O
AD7 ' D Ql-d"
' .' .
74LS373
Al
AO
Al
AO
PCL
PCU
-
ADO
oc D7 DO RES
,.
-:._
,.I
D7

DO
Figu re J.5..6. 8051 Connection to the 8255 for Example 15-4

Address aliases
In Examples 15-4 and 15-5 we decode the AO · A7 address bits; 74lS138
however, in Examples 15-3 and 1~ 2 we ~ecodcd only a portion of the
A2 A
upper addresse, of AS_· A15. Th,s partial address decoding leads to AO
A3 B
what is called addms al1nS1.'<. In other words, the same physical port h A4 Al
different addresses; Ll1us, the same port is known by different nam as C
In Examples 15-2 and 15-3 we could have changed alJ x's to va . es. AS Y2
combinations or ls and Os to come up with diffel1'nt addresse:•ous G2A
they would aU refer to the sam,• physica l port. In your ha d ' yet
.
reference document.1hon, ma ke sure th at i rware
a I address aliases are d
A6
A7
c2a -cs 8255

GJ
umented, so that the user knowo what addresses arc available if h<x'.·
she wants to expand the system. e/
F'
396 •sure 15-7. 82SS Decoding Using 741.5138
THesos1 MICRoc
ONTROLLER ANO EMBEDDED SYS~
,,,..--
r,,tl!IPle 15-5
r,od the base address for the 8255 in Figure 15-7.

5oJution:
GI G2B - -G2A C B A Address
~1 A6 AS A4 A3 A2 Al AO
0 0 0 1 0 0 0 88H
l

8031
EA P3.7 RD
.J:
C
P3.6 WR v::c
PSEN R R!5
P2.7 L CE OE Vpp
A12 - Al2 2864

AUY
cs PA
P2.0 AS - AS (2764) 8255
ALE G 8Kx8 PB
P0.7 AD7 ,oQK A7- A7 program
ROM
PC
Al
7 4LS373 AO
PO.O ADO AO - 07 DO AO RES
oc I.L
.,. 07

DO

figure J;;-3. 8031 Connection to External Program ROM and the 8255

8031 system with 8255


In the 8031-based system where external progran, ROM is an absolute must, the use of an 8255 is most welcome. This
ii due to the fact that in the process of connecting the 8031 to external program ROM, we lose the two ports PO and P2,
le.Ving only Pl. Therefore, connecting an 8255 is the best way to gain some extra ports. This is shown in Figure 15-8.

Review Questions
l Find the control byte if all ports are inputs.
t Find the control byte for re = in, PB = out, and PA = out.
l. True or false. To avoid aliases, we must decode addresses AO - A15.
l Can 86H be the base address for port A of the 8255?
S. Why do we use the MOVX instruction to access the ports of the 8255?

SECTION 15.2: 8255 INTERFACING


. Chapters t 2 and 13 detailed real-world interfacing of LC~, sensors, and ADC devices. ln this section we show how
lo1nterface the 8255 to LCDs, stepper motors, and ADC devices, then program it using 8051 instructions.

Stepper motor connection to the 8255


Chapter 17 will detail the interface of a stepper motor to the 8051. Herc we show stepper motor connection t0 h
~ and programming. See Figure 15·9. t e

IOst INnJtpACING WITH THE 8255

,_________
397
' ULN2003
Stepper Motor
/
t'

8255
16
DO DO PAO

,,•
from
8051
WR
RD
AO
D7 D7
WR
RD
AO
PAI

PA2
2
JS

14

1
0
Al Al

A2
cs RESET
•••
Decoding .(

Circuitry
COM
, • A7
ULN2003 Connection for Stepper Motor
COM
+SV

• Pin S•GND
. power supply for the 1notor
" I Pin9 = +SV Use a separate

'•
, Figure 15-9. 8255 Connection to Stepper Motor

r LCD

--
: control word for PA ; out 8255
( MOV A,#BOH
MOV Rl, #CRPORT ;control reg port address PAO DO
V
cc-
+SV

( MOVX @Rl ,A ;configure PA= out ';:. !OK ;C


j. VEE
I MCV
MOV
Rl,#APORT
A,#66H
;load PA address
;A•66H,stepper motor sequence
PA7 -
I-
D7 I -
~


.r

AGAil'l; MOVX @Rl,A ·issue motor sequences to PA RS R/WE Vss """~


r • •
RR A ;rotate sequence for clockwise I
PBO -:.=-
ACALL DELAY ;wait.
PB1
SJMP AGAil'f
PB2

LCD connection to the 8255 i..RESET


Program 15-1 shows how to issue commands and data to an LCD Figure 15-10. LCD Connection
connected to an 8255. See Figure 15-10. In Program 15-1. we must put a
Jong delay before issuing any information (command or data) to the LCD. A better way is to check the busy Oag before
issuing anything to the LCD. This was discussed in Chapter 12. Program 15-2 is a repeat of Program 15-1 with the check-
ing of the busy aag. Notice that no DELAY is used the main program in Program 15-2.
-
;Writing commands and data to LCD without checking bus Ila
;Assume PA of 82SS connected to 00-07 of LCD and y 9
;PB0=RS, PBl=R/W, PB2•8 for LCD•s control pins c . :>
MOV "
A, .eoH ;al l 8255 onnection :I
MOV RO. #CtlTPORT ·l ports as output :l
MOVX GRO,A 'oad control reg address
MCV A, #38H '~~ue control word
ACALL CMDWRT '. . ' 2 lines• 5)(7 matrix
ACALL DELAY 'write command to LCD
I
MOV A. # OEH wait before next i
ACALL ; Leo command f ssue (2 ms)
MOV CMDWRT , write or cursor on
A #olH command t
ACALL •
CMDWRT ; Clear LCD O LCD
ACALL ;Write Com-.
DELAY :wait b ......,.nd to LC!)
efore next
Progr.un 15-1. (co111111urd 011fo/Jowmg pag,J issue

398
'rliE 8051 "-llcn -
"OCONTRo S
lll!R ANO EMBEDDED sySTEftf
A,#06 ;shift cursor right command
-,,cv ACALL CMDWRT ;write command to LCD
ACALL DELAY ;wait before next issue
.. . . . ;etc. for all LCD commands
MOV A,#'N' ;display data (letter NJ
ACALL DATAWRT ;send data to LCD display
ACALL DELAY ;wait before next issue
MOV A,#'0' ;display data (letter 0)
ACALL DATAWRT ;send data to LCD display
ACALL DELAY ;wait before next issue
;etc. for other data
-command write subroutine, wri tes instruction commands to LCD
'ct,mWRT : MOV RO, #APORT ;load port A address
MOVX @RO,A ;issue info to LCD data pins
MOV RO,#BPORT ;load port B address
MOV A,#000001008 ;RS=O,R/W=O,E=l for H-to-L
MOVX @RO ,A ;activate LCD pins RS,R/W,E
NOP ;make E pin pulse wide enough
NOP
MOV A,#00000000 8 ;RS=O,R/ W=O,E=O for H-to-L
MOVX @RO ,A ;latch in data pin info
RET
;Data write subroutine, write data to be displayed to LCD
OATAWRT : MOV RO, #A PORT ;load port A address
MOVX @RO, A ;issue info to LCD data pins
MOV RO , #BPORT ;load port B address
MOV A,#000001018 ; RS=l,R/W=O,E=l for H-to-L
MOVX @RO ,A ;activate LCD pins RS,R/W,E
NOP ;make E pin pulse wide enough
NOP
MOV A,#000000018 ;RS=l,R/W=O,E=O for H-to-L
MOVX @RO, A ;latch in LCD's data pin info
RET

i'logri111 lS-l. (contit1ued from previous P"ge)

;writing commands to the LCD with checking busy flag


;PA of 8255 connected to DO-D7 of LCD and
:PBO=RS, PBl=R/W, PB2•E for 8255 to LCD's control pins connect.
MOV A,#SOH ;all 8255 ports as output
MOV RO,#CNTPORT ;load control reg address
@RO,A ;issue control word
MOVX
A,#38H ;LCD: 2 LINES, 5X7 matrix
MOV
NCMDWRT ;write command to LCD
ACALL
A, #OEH ;LCD command for cursor on
MOV
NCMOWRT ;write command to LCD
ACALL ;clear LCD
MOV A, #OlH
NCMDWRT ;write command to LCD
ACALL
A,#06 ;shift cursor right command
MOV
NCMDWRT ;write command to LCD
ACALL

P ~ lS-2. /continued onfallowrng pagt)

losJ 1NT!RFACING WITH THE 8255 399


' ;etc.
LCD commands
for al l (letter Nl
data 1 y
I
.. . . . ·displaY to LCD diSP a
MOV A. J:; 'N' 'end data (letter 0) I
ACALL NOATAWRT '.~isplaY data LCD display
MOV A,ij'O' ' d ta tO
NOATAWRT · send a ther data
CALL • for o
;etc: busy flag
··· ·ne with checking e
I ;New comma nd write subrouti
NCMDWRT: MOV R2 • A
,save A valu d LCD status
• rea /
A, #90H ·PA•IN to reg address
MOV RO' #CNTpORT '.1oad control N PB=OUT
HOV
MOVX @RO,A '.coniigure PA=sl1,read command
' /W l ~
• MOV A,#000001108 ·RS=O,R =' ddress '
MOV RO, #SPORT '. load port Bfa RD and RS p ins
' R/W-1 or
MOVX 9RO,A ;RS•O, - ddress I
.
••
,. MOV RO,#APORT •
· load port A a
d ommand reg
,•• READY: MOVX
RLC
A,®RO
A
; rea c
move D7(busy
flag) into carry
d
; . til LCD is rea y
JC READY ;wait un d PB output again
' MOV A,#SOH ;make PA an ort address
MOV RO,#CNTPORT ·load control P 8255
:issue control word to
( MOVX
MOV
eRO,A
l'., R2 '.get back value to LCD
l) MOV RO,#APORT ' 1 d port A address
MOVX lilRO,A '.;::ue info to LCD'S data pi ns
MOV RO,ijBPORT '.load port B address
MOV A,#000001008 '.RS•O R/W•O,E•l for H-to-L
MOVX @RO,A '.acti~ate RS,R/W,E pins of LCD
NOP
NOP
;make E pin pulse wide enough -
MOV A,#000000008 ;RS•O,R/Wa0,8=0 for H-to-L
MOVX ®RO,A ;latch in LCD'S data pin info
RET
;New data write subroutine with checking busy nag
NDATAWRT: MOV R2,A ; save A value
MOV A,#90H
MOV ;PA•IN to read LCD status, PB=OUT
RO,#CNTPORT
MOVX @RO, A ;load control port address
MOV ;configure PA•IN, PB•OUT
A,#000001108
MOV RO,#BPORT ;RS=O,R/W•l,E•l to read command reg
MOVX @RO, A ;load port B address a
MOV RO,#APORT ;RS•O,R/W•l for RO and RS pins
READY: MOVX A,®RO ;load port A address
RLC A ;read command reg
JC READY ;tno~e 07(busy flag) into carry
MOV A,#SOH ;wait until LCD is ready
MOV RO, #CNTPORT ,make PA and PB output again
MOVX II/RO , A ;load control port addr
MOV A,R2
· iasu ess
, e control word to 8255
MOV R0,#1'.PORT ;get back value to b
MOVX GIRO, A ; load po e sent to Leo
. rt A address
MOV RO, #BP0RT ;issue info to LC
MOV A,#00000101a ;load port 8 dd D's data pin s
MOVX IRO, A ·Rs
• •l,R/wko Bl a ress
·act·
, 1vate Rs' R/
" for R-to
. -L
Progr•m 15,-2. /Ct•11l1111._,, v11 followmg pog.-J ' W,e P1ns of LCD

TliE 80s1 M.ICRoco -


NTROLLER ANO EMBEDDED SYSyS,f.S
NOP ;make E pin pulse wide enough
NOP
MOV A,#OOOOOOOlB ;RSal,R/W•O,E=O for H-to-L
MOVX @RO,A ;latch in LCD'S data pin info
RET

J't081",n 15-2. l«mti1111ed from previous pag~)

5V )

AOC804
RD Vee 10k 150 pP
.
8255
WR CLKR
CLKlN
~
DO PAO DO
Vin(+) 10k
D7
from Wit -WR Vin(-) • POT
8051 RD -RD AGND
AO Vref/2 •
Al - -
A2 -
A7 -
Decodi ng -
cs
PA7
PCO
D7 GND ,--
Circuitry LNTR
cs ...
RESET I
- -
I

figure 15-11. 8255 Connection to AOC804

ADC connection to the 8255


ADC devices were covered in Chaprer 13. The following is a program for the ADC connected to the 8255 as shown
in Figure 15-11.
MOV A,#SOH ;control word for PA•OUT,PC•IN
MOV Rl, #CRPORT ;control reg port address
MOVX ®Rl,A ;configure PA=OUT AND PC=IN
BACK: MOV Rl,#CPORT ;load port C address
MOVX A,@Rl ;read port C to see if ADC is ready
ANL A,#OOOOOOOlB ;mask all except PCO
JNZ BACK ;keep monitoring PCO for EOC
;end of conversion, now get ADC data
MOV Rl, #APORT ;load PA address
MOVX A, ®Rl ;A•analog data input
So far we have discussed the simple 1/0 mode of t~e 8255 and showed many applications for it using Assembl
language. Next, we discuss how to program the 8255 using 8051 C language. Y

Review Questions
I. Modify the stepper motor program to ~ counterclockwise.
l. True or false. In programming the LCD vi.a an 8255 (without checking the busy flag), port A is always an output
3 P<>rt.
· True or false. In the LCD cormection to the 8255, we must have a long delay before issuing the next data if we are
1101 checking the busy flag.

flOsi INT£RFAC1NG WITH TH£ 8255 401


SECTION 15.3: 8051 C PROGRAMMING FOR THE 8255
In this section ,ve show how to prograot the 8255 using the 8051 C languag~- In the last chapter we Showe
•-"'' •="'
'10),
fm=ry-m,,,.,
""="'" - r y ,p,re of>• 805' s,re '"' 8255 " """' "~ ""m•I
)(DATA[... ( >H• 805' C.
we - ,o -
d ho.
,~mpl~ g,ffl ,o """• ...,
s,,,dy ' " " " •• W
d.,o

"' of 805 >C P"'8'"""" e, "' S'55. "'""'·

~
Example 15-6
825S is4000H (Seeam send SSH and AAH to all ports of the 8255 continuously. Assume the base addre
Write a C progr
· 1
Figure 15-4) ss of the
V

Solution:
#include <regSl.h>
#include <absacc.h,
void MSDelay(unsigned int itime),
'•
void main()
' (
unsigned char value;
( XBYTE[Ox4003J=Ox80·• //intialize all ports as output
l while(l)
·' {

r
value. OxSS·
XBYTE [Ox4000]' •va l ue·
XBYTB[Ox4001] 0 va 1ue·'
XBYTB(Ox4002)- -va1ue ,·
//send SSH to all ports
.
511

Ill
Ms Delay(lOO); •
value,; Ox.AA·
XBYTE (Ox4000 ], evalue .
XBYTE [Ox400l] •value •.
XB
YTE [Ox4002] •value.'
//send OAAH t o all ports .
1111

Ms Delay(lOO); ,
I
I
vo~d MSDelay (unsigned int itime)

unsigned inti .
for(i•O; i??iti J;
for (j•01 j?? me; i++J
1275; j++);
I

Example 15-7
Write a c pro
o-· t? get data from PA and send 1·1 to both
8255. (See f; ...!:m1•""'·l
.
Solution·
. ports B
a~cu
• sea b
#incl
#
include
d <regSl. h, ase a ddress of 4000H fot ......
u e <abaacc. h> us

402
THE80s1 Mien
"ocoNTROLLE"
~AND -
EMBEDDED sYSJ9fS
unsigned char value·•
XDATA[Ox4003]=0x90· // PA=in, PB=PCsout
'
wbile(l)
{
value= XOATA[OX4 000) ; // get a byte f rom PA
XDATA[Ox 400l ]=value·• // s e nd i t t o PB
XDATA[Ox4002]avalue; //and PC
}
I

Example 15-8
Write a C program to move the stepper motor shown in Figure 15-9 clockwise. Use a base addtess of 4000H for
the 8255.

Solution:
#include <reg 51 . h>
hnclude <abeacc. h>
void MSDelay (unsigned int itime ) ;
voi.d main (l
{
uns i gned c har value;
XDATA[Ox4003) s Ox80; I / PA=output
wbile ( l )
{
XDATA [Ox4000) • OxCC;
MSDelay(SOO);
XDATA[Ox4000] • Ox99;
MSDelay (SOO);
XDATA[Ox4000] • Ox33;
MSDelay (500);
XDATA [Ox4000] • Ox66;
MSOelay(SOO);
}
I
void MSDelay(uneigned int i t ime)
{
unaigned inti, j;
for ( i•O; icit iee; i ++)
for (j•01 jc1275; j++)1
l

lest lNTERFAaNC WJTH 'OfE 8255 403


,,

~
-
SUMMARY 51
connecting it to an 8255 chip. The
b
8255
rts of the 80311 . Y uch as stepper motors, LCDs, and All(:
This chapter described how to expand the •;~o':rol interfaced devices s
,'·
(

O
could then be programmed as a simple 1/0 port c
e .bit port can be pro?rarnm~ as one 8-bit
8
d vices . b·d·rectional ports. Th ed b the control register. Vanous addres&
" Th~ 8255 has 3 ports. Ports A and Bar~ S-bit~ of the 8255 are select
1
jJect ports, a nd set the control registe
port or two 4-bit ports. The various operation m : the 8255 control reg~ter\ control devices such as LCDs, step~
decoding techniques were demonstrated to progr_•,en of 8051 ; 31 instructJons 0
In addition, numerous program examples were ?1'
8255
motors, and AOC devices that were interfaced via the the l~t section of this chapter.
Accessing the 8255 using 8051 C was discussed ,n



PROBLEM S
.• SECTION 15.l: PROGRAMMJNG THE 8255 L

• •1
1. Find the control byte to set aU the ports as simple input.uts and c
ort as output.
'•
2.
3.
Find the control word to configure ports A and Bas mp d
Which are the address lines needed to select the ports an con
:o) reo;<ter and wha t should be the value on thest
o-
: 1
>
'


1mes.?
dC · uts
I 4.
5.
Find the control byte to set PA = output, and both ports Ban as mp
Find the control byte to set PA = input, PB = input, and PC= output.
·
.
l 6. Write a program to receive a byte through port A, mask the upper nibble, and to transfer thts byte to port B. Use the
·' address configurations as in Figure 15-4. . . .
7. Write a program to set bit PCO. Use the address configutations as m Figure 15-4.
8. Show the design of the 8255 connection to the 8051 where port A has the address 20H. Then program the 8255 to
get data from port Band send it to both ports A and C.
9. Show the design of the 8255 connection to the 8051 where port A has the add ress 881-l. Then program the 8255 to
get data from port C and send it to boU, ports A and B.
10. Using the 74LSl38 as an address decoder, show the connection to address AO - A7 of the 8051 ,vhere YO is assigned
the 8255 base address of 80H.
lJ. In Problem 10, find the base address of the 8255 fo r the following.
(a) YI (b) Y2 (c) YS
12. Using the 74lS138 as an address decoder, s how the connection to address AO- A7 of the 8051 where YO is assignro
the 8255 base address of COH. Use any other simple gates you need
13. In Problem 12, find the base address of the 8255 for u,efoll , ·
(a) Y3 (b) YS (c) Y7 O\\ mg.
14. Using a 74lSl38 as an address decoder, show the conn ·
to the 8255 base address of OOH. echon to address AO - A7 of the 8051 where YO is assigned
15. In Problem 14, find the base address of the 8255 i th f U .
(a) Yl (b) Y2 (c) Y7 or e o owmg.
16. How many pins of the 8255 are used for ports a d h
17. What is the function of data pins oo. o7 in th ~5
~w are they categorized?
18. Pora control word of 82H, how is each port co:fi ; ,
19. Whatspecialfeaturedoesthebitsct/resetft'atu gu ed.
20. True or false. In simple J/0 programmin of re of 8255 allow?
for an input port. g port A of the 8255, we can p
21. Show the decoding circuitry for the 8255 if USe AO - P A3 for output and PA4 - PA7
22. Which of the following port addresses ca we;•nt port A to have add
(a) 32H (b) 45H (c) 89H (d) BAH nnot e assigned to port A of t~ess 68 H . Use NANO and inverter gares.
23. Are ports A and B bit-addressable? e 8255, and why?
24. An ADC r~uires a start conversion pulse, whi .
Generate this pulse at pin PAO. Use the addr ch 1,5 • low. to-high
25. Write a p~ogra'." 10 monitor PA for a temper: con1gurations as in /ulse, remaining high for a specified delay.
be saved m register R3. Also, send AAH to re o 100. lf the te 'SUre 15-4.
port Band 5S!i lllperatu ·
. to port C. re is equal to 100, then the result should
404
TH£sos1 ••
,.. 1cRocoNT -
ROLLER AND EMBEDDED 5ySTEMS
. . Id be ved and send AAH to port 8
write a C program to monitor PA for a temperature of 1()(). If it is equal, ,t shou sa
'If,. and SSH to port C before exiting.
,g write a C program to get data from PA and send it to both PB and PC.
~ write a C program to get data from PC and send it to both PA and PB.

ANSWERS TO REVIEW QUESTIONS


icnoN 15.1: PROGRAMMING THE 8255
}. 9BH
i 89H
i True
-1. It cannot since we must have Al :: Oand AO"' Ofor the base address. ed 1/0
5. The MOVX instruction allows access to external memory and 8255 is mapped as memory-mapp ·

sECTION 15.2: 8255 INTERFACING


I. •RR A" is changed to "RL A".
2. True
,. True

-
CHAPTER16

DS12887RTC
INTERFACING AND
PROGRAMMING

OBJECTIVES

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

> Explain how the real-time dock (RTC) chip works


> Explain the function of the 0512887 RTC pins
> Explain the function of the 0512887 RTC registers
Understand the interfacing of the 0512887 RTC to the 8051
> Code programs in Assembly and C to access the RTC registers
> Code programs to di5play time and date in Assembly and C
> Understand the interrupt and alann features of the DS12887 I:
> Explore and program the alarm and interrupt features of the RTC
>
! 12CS87 re.ii-time
arnni1ng of the OS. functio/\S and
1 MOT VCC24
nu, ch.lptet sh<>WS the ,nterlaCJ/\g and progrbe 0512887 RTC pin0'" to program
~
d oclc (RTC) ch•~· In s«oon 80516 ;;,es::: 16.l, we also shof~12887 is sho"'.n 2 NC SQW 23
sh<>W ,ts '"terfK111S with the 3 ,nnung o . sed 1n 3 NC NC22
the 051288'1 ill Assembly language. The C P~ the 05J2287 are d,SCUS
,n ~ 16 2 The alarm and S-0_\'J features 4 ADO NC21
5ed10C\ 16.3. s ADI NC20
6 A02 lRQ 19
• SECTION 16.1: 0 $12887 RTC INTERFACING . te time
that pto'"des accur• 7 ADJ RESET 18
The real-time clock (RTQ is a widely used de, acethe x86 IBM pC come
and date for many applications. Many systems sut ~~e IBM re 8 AD4 OS 17
pro..-ides tiJl\e
1 NC16
with such a chip on the motherboard. The ~TC '~ ~ n to the date/calendar com· 9 ADS
components of hour, minute, and SC(Ofl(I, in addillO . tern al battery, wluch R/W IS
ponents of year, month, and day. The RTC chip uses an: h ~me 8051 family 10 A06
keeps the time and date even when the pawer is off. Allh d g bedded into the 11 AfYl AS 14

members, such as the DSSOOOT. come w,th the RTC alrt• y en:1 RTC chip. One
12 CND
-
CS 13
chip, we have to interface the vast majority of them to an ext~m,Sc .conductor/
of the most widely~ RTC chi~ ,s lhe 0512887 f_rom Oa as ~~e ori inal
•Maxim Corp. This chip · LS found ,n lhc vast ma1or1ty
I Thof OS l'Cs is the repS1ace-
x86t 2887
IBM PC/ AT used the MC14618B RTC from Motoro a. e . f •er Figure 16-1. OS12887 RTC Chip
' ment for that chip. It uses an intem.>l lithium battery to keep operating or ov It
10 years in the absence of external power. According to the DS12887 data sheet .
( from Maxim. it keeps track of •SC(OR(I•. minute-, hours. da)'S, day _of w~k, date'. month, and year with leap-year
compensation valid up to year 2100". The above Information is provided ,n both bma ry (hex) and BCD fo rmats. The
' DS12887 supports both U-hour and 24-hour dock modes with AM and PM ,n the 12-hour mode. It also supports the
Daylight Savings Time option The DS12887 uses CMOS technology to keep the power consumption low and it has
the designation DS12C887. where C is (or CMOS The DS12887 ha, a total of 128 bytes of nonvolatile RAM. It uses
14 bytes of RA.'vl for clock/ calendar and control registers. and the other 114 bytes of RAM are for general-purpose d1ta
storage. In the J<86 IBM PC, these 114 bytes of NV-RAM are used for the CMOS configuratio n, where the system setups
are kept before the operatmg system takes over. Next we descnbe the pl/\S of the 0512887. See Figure 16-1.

Pm,L:4 provides exte":'al s~ppty voltage to the chip The external voltage source is +SV \Vhcn v falls below the JV
14!\'e 1, ""' external source ts switched off and the ,ntemal lithium batte d "'
ThLS nonvolatile capability of the RTC prevents any loss of data A ~ prov,.._<': power to the RTC.
continues to operate. and all of the RAM. time, calendar, and ala,,,'.. ccor '"S to u."' 051Ui8'? data sheet #the RTC function
level of the V.. inpuL" However, in order to access the . tcrs \'13 amemory locations remam non-volatile reardless of the
wools, when external V,. LS applied, the device is full;:essiblc ~rm, the V • must be supplied extemally. 1/\ other
4 25 volts, the read and write to the chip are pre-ented b t the ~n ata can be written and read When V falls t,eio,.
and RAM contl'llts are unaffected, since the are non • ~ timekeeping "
n oted tlwt "when V.. is applied to the osik, illld ;:!~le. It must .also be
thilll 4.25V, the devke becomes accessible after 200ms.• s a level of greater
DS12887 C vc
8051
GND PO.O ADO RSTLJ
P,n 12 Is the ground I-
MOT
P07 A07
AD0-AD7 cs '-
ASOS RW
The multiplexed address/ data pms pro,ideboth ad
clup. A d ~ are latched into the DS12887 on the fa.11 dn,,.'*'S and data to the ALE
RD
' T
'-
'llgnal A :111nple way of connccting 1hr DS12!187 to lh~ingedgeof lhe AS(ALE
16-2. Notice thal ACX). AD7 of lhc DS12887 ar 805l l5 shown ln F l WR
~1 &ncl there 11> no need for any 74xx373 lat~ ct>nno.'Ctl!d dlrfflly to PO
the latch Internally To acce;s the DS128II? Fi • Sin~ th~ DS12887
~f:::.
m5lruction SltlCt' 11 tS mapped as external...;::.ory·~ lf>:2. we use ~O•des
u,c

e will dJoCuo6 ~ '" VX


~ !,z.

shortly. Flg,u.1~2,
D512117C-Mdl• .. -
THE 8051 MICROC
ON'fR -
OLLER AND EMBEDDED 5yS'l'lld
}.S(ALE)
AS (a_d ~ress strobe) is an mput pin. On the falling edge it will cause the addresses to~ latched into t~e DS12887.
'[hf AS pin is used fo r demultiplexing the address a.nd data and is connected to the ALE pm of the 8051 chip.

1,1or
ThiS is an input pin that allows the choice benveen the Motorola and Intel microcontroller bus timings. The MOT pin
j;cOroiected to GND for the [ntel timing. That means when we connect ()512887 to the 8051, MOT = GND.

OS
Data strobe o r read is an input. When Mar = GND for Intel timing, the 05 pin is called the RD (read) signal and is
(lll1llected to the RD pin of the 8051.

Pl#
Read/\'Vrite is an input pin. When MOT = GND for the Intel timing, the R/W pin is called the WR (write) signal
and is connected to the WR pin of the 8051.

cs
Chip select is an input pin and an active low signal. During the read (RD) and write (WR) cycle time of [ntel timing,
the CS must be low in order to access the chip. It must be noted that the CS works only when the external V« is con-
nectl'd. In other words "when V"' falls below 4.25V, the chip-select input is internally forced to an inactive level regard-
less or the val ue of CS at the input pin." This is called the write-protected state. When the 0512887 is in write-protected
state, all inpu ts are ignored.

IRQ
Interrupt request is an output pin and active low signal. To use IRQ the interrupt-enable bits in register 6 must be
set high. The interrupt feature of the 0512287 is discussed in Section 16.3.

saw
Square wave is an output pin. We can program the DS12887 to provide up to 15 different square waves. The fre-
quency of the square wave is set by programming register A and is discussed in Section 16.3.

RESET
Pin 18 is the reset pin. It is an input and.is ~ctive lo~ (normally high). [n most applications the reset pin is connected
to the V« pin.In applications where this pm 1s used, tt has ~o effect on the dock, calendar, or RAM if it is forced low.
The low on this pin will cause the reset of the IRQ and cleanng of the SQW pin, as we will see in Section 16.3.

Address map of the 0$12887


The DS12887 has a total of 128 bytes of RAM space with addresses 00 - 7FH The first ten locations 00 09
·"-
1s....., for RTC values of tirne,
ca1~-'
e11uar, and alarm data· The next four bytes are used
· for the control and status
' - registe
, are set
They are registers A, B, C, and D and are located at addresses 10 - 13 (OA - OD in hex). Notice that their hex admess:;
11\alch their names. The next 114 bytes from addresses OEH to 7FH are available for data storage. The entire 128 b
o! RAM are accessible directly for read or write except the following: ytes

I RegL~ten C and D are read-only.


2. D7 bit of regi5ter A ls read-only·
3 The high-order bit of the eeconds byte ls retid-only.

Fi~ 1~3 ahoW8 the addretS DlllP of the DS12887.

-
/
5ec<>nds
0 Seconds Alarm
I Minutes
0 00
2 .Minutes Alarm
3 Hours
4
13 OD Hours Alarm
5
OE D•" ot the Week
14 6
Dav of the Month ...0
7
/ Month
,.,.f
8
9 Year
10 Reeister A
Remster B
J1
12 Remster C
• 13 R""'ster D
7F
..


127

Figure 16-3. DS12887 Address Map


,i

I
Time calendar and alarm address locations and modes
' ' . d I da ta Table 16-1 shows their address locations
The byte addresses 0- 9 are set aside for the time, calendar, an a arm ·
(. and modes. Notice the data is available in both binary (hex) and BCD formats.

(
' Turning on the oscillator for the first time
The DS12887 is shipped with the internal oscillator turned off in order to save the lithium battery. We need to tum
• on the oscillator before we use the time keeping features of the DS12887. To do that, bits D6 • 04 of register A must be
I set to value 010. See Figure 16-4 for details of register A.
The following code shows how to access the DS12887's register A and is written for the Figure 16-2 connection. In
Figure 16-2, the DS12887 is using the external memory space of the 8051 and is mapped to address space of 00 - 7fH

Table 16-1: DS12887 Address Location for Time, Calendar, and Alarm
Address Function ....
Decimal
Location Data Mode Range
Range
0 Seconds 0 -59
Binary (hex) BCD ..
I Seconds Alarm 00 - 38 00-S
0 - 59
2 Minutes 00·3B 00-S
0- 59
3 Minutes Alarm 00 ·3B 00-59 ..
0-59
4 Hours, U-Hour Mode 00- 38
1-12 00-59
Hours, 12-Hour Mode 01-0CAM 01-12AM
I -12

5
Hours, 24-Hour Mode
0 -23
81-BCPM 81- 92 PM ..
Hours Alarm, 12-Hour 0 -17
I· 12 0 -23
Hours Alarm, 12-Hour 01-0CAM
l · 12 01-12AM
Hours Alarm, 24-Hour 81-BCPM
6 0- 23 81-92 PM
Day of the Week, Sun " 1 0 • 17
7 1- 7 0-23
Day of the Month
1 • 31 01-07
8 Month 01- 07
9 l - 12 01-tF
Year 01 · 31
0.99 01-0C
00-63
01 • 12
-
410 00-99
-
I UIP ! DV2 ! DVl ! DVO J R5.3 I RS2 RSI I RSO J
UTP Update in progress. Trus is a read-only bit.
DV2 DVl DVO
0 1 0 ,vUl tum the oscillator on

RS3 RS2 RS1 RSO


Provides 14 different frequencies at the SQW pin. See Section 16..3 and the DS12887
data sheet.

f,g!l1t J(,-4. Register A Bits for Turning on the DS12887's Oscillator

sinC'~ =~;See Chapter 1~ for a discussion of external memory in the 8051. For the programs in this char,ter, we use
ll\ltlU;1ion MOVX A'. @RO since the address is only 8-bit. In the case of a 16-bit address, we must ':'se MOVX A, @
o!'!R as was shown m Chapter 14. Examine the following code to see how to access the DS12887 of Figure 16-2.

ACJILL DELAY_ 200ms ;RTC NEEDS 2ooms AFTER POWER- UP


MOV RO, #10 ;R050AH,Reg A address
MOV A, #20H ;010 in D6-D4 to turn on osc .
MOVX @RO,A ;send it to Reg A of DS12887

Setting the time


When we initialize the time or date, we need to set 07 of register B to 1. This will prevent any update at the middle
of the initialization. After setting the time and date, we need to make D7 = 0 to make sure that the clock and time are
llj>dated. The update occurs once per second. The following code initializes the clock at 16:58:55 using the BCD mode
ind 24-hour clock mode with daylight savings time. See also Figure 16-5 for details of register B.

;···--- WAIT 2oomsec FOR RTC TO BE READY AFTER POWER-UP


ACALL DELAY_200ms
;• • - - - - - - - - - -TURNING ON THE RTC
MOV R0,#10 ;RO=OAH,Reg A address
HOV A,#208 ;010 in D6 - D4 to turn on osc.
MOVX @RO,A ;send it to Reg A of DS12887
:·-- - ----- -----setting the Time mode
MOV RO #11 ;Reg B address
MOV A,#83H ;BCD,24hrs,Daylight saving,D7 • 1 No update
MOVX @RO,A ;send it to Reg B
:· ·· - · ·----Setting the Time
MOV RO,#O ;paint to seconds address
HOV A,#SSH ;seconds• SSH (BCD numbers need Hl
MOVX @RO,A ;set seconds
HOV RO,#OZ ;point to minutes address
HOV A,#SBH ;minut~s· 58
MOVX @RO, A ; se~ minutes
HOV R0,#0 ;po1 nt to hours address
4
HOV A,#16H ;hou~s-16
MOVX @RO A ; set hours
HOV RO,#~l ; Reg e address
MOV A,#Ol ;D7•0 of reg B to allow update
MOvx eRO, A I send it to reg B

,u
24/12 DSE
SQWE DM
SET PIE AIE UTE d .nd time and datest mar:ic~~;;:\)
• we mus
· once pet se<O". ' tializatiOn

15
SET SET= 0: Oock .~unt•~fed (durinS the uu ed when •'
SET= 1: Update ,s inhib• See 5ection 16.3, the IRQ to be assert~
Pll! Periodic Interrupt Enabl;,, AlE = I wiJJ alloW the alarm bytes.
AIE Alam> Interrupt Enable. e ·dd) are the same as
all three bytes of time (yy:mm.
/
Section I6.3. t .' .
UlE See the ()512887 data shee . 163 . (hex) data format
b le· See 5ection
SQWI! Square wave ena .' 0 data fom,at an d DM - I·
- . B111ary .
OM Data mode. DM O.
2
9'.;for J2-hour mode . viflg. (The first Sunday ltl
• 24112 I for 24-hour mode an 0lf I enables the daylight sa
OSE Daylight Saving Enab~. f'0ctob<?r)
April and the last Sun ay O

• Figun 16-5. Some M•jor Bits of Register 8
'l

Setting the date . .L twhen we initialize tin1e or date, we need


• ' The following shows how to set the date to ,.,.~
u,.,ober !9th' 2004. Notice u ,a
to set 07 of register B to 1.
(. . .... •...•••• TURNING ON THE RTC
l ' MOV RO, #10 ; RO• OAH, Reg A address
' MOV A,#20H ;010 i n 06 · 04 to turn on osc
MOVX @RO,A ;send it to Reg A of OS12887
'···-····· ······ Setting the Time mode
I MOV R0,#11 ;Reg B address
MOV A, #83H ;BCD, 24 hrs, daylight saving
MOVX @RO,A ;send it to Reg B
;··· ······· Setting the DATE
MOV R0,#07 ;load pointer for DAY OF MONTH
MOV A,#l9H ;OAY=l9H (BCD numbers need H)
MOVX @RO,A ;set DAY OF MONTH
ACALL DELAY;
MOV R0,#08 ;point to MONTH
MOV A,#lOH ;lO=OCTOBER.
MOVX @RO,A ;set MONTH
ACALL DELAY ;
MOV R0,#09 ;point to YEAR address
MOV A,#04 ;YEARa04 FOR 2004
MOVX IIIRO ,A ;set YEAR to 2004
ACALL DELAY
MOV R0,#11 ;Reg B address
MOV A,#03
MOVX @RO,A ;D7a0 of reg B to allow update
;send it to reg B

RTCs setting, reading, displaying time and date


The following is a complete Assembly code for setting di
dates a.re sent to the screen via the serial port after they a ' rea ng, and disp laying the ti d d Th ..,_ and
re converted frorn BCD me an ate. e ...,.,es
;·•··RTCTIME.ASM: SETTING TIME,REJ\DING AN!) O to ASCU.
ORG O !SPLAYING IT
ACALL DELAY 200ms
;SERIAL PORT SET-UP ;RTC needs 200
nis upen
MOV TM00,#20H Power.up

412
Tlit 8051 ~CR"'- _
""-Ol\/11to
LLER AND EMBEDDED SY5fEMS
MOV SCON,#SOH
MOV THl,# · 3 19600
8 TIU; - • • - • •• - - •• • TURNING ON THE RTC
s£1' MOV R0,#10 ;RO=OAH,Reg A address
MOV A,#20H ;010 in 06 - 04 to turn on osc.
MOVX @RO,A ;send it t o Reg A of OS12887
..-· ······ · ···· Setting the Time mode
' MOV R0,#11 ;Reg B address
MOV A,#83H ;BCD, 24 hrs, daylight saving
MOVX @RO,A ;send it to Reg B
.. ••.. • .•. • Setting the DATE
' MOV R0,#07 ;load pointer for DAY OF MONTH
MOV A,#24H ;DAY=24H (BCD numbers need H)
MOVX @RO,A ;set DAY OF MONTH
ACALL DELAY .

MOV R0,#08 ;point to MONTH
MOV A,#lOH ; l O=OCTOBER.
MOVX @RO.A ;set MONTH
ACALL DELAY
MOV R0,#09 ;point to YEAR address
MOV A, #04 ;YEARa 04 FOR 2004
MOVX @RO,A ;Set YEAR to 2004
ACALL DELAY
MOV R0,#11 ;Reg B address
MOV A,#03 ;D7=0 of reg B to allow update
MOVX @RO,A ;send it to reg B
; · ••• ··· • READ Time (HH:MM:SS), CONVERT IT AND DISPLAY IT
OV1 : MOV A, #20H ;ASCII for SPACE
ACALL SERIAL
MOV R0,#4 ;point to HR loc
MOVX A,@RO ;read hours
ACALL DISPLAY
MOV A,#20H ;send out SPACE
ACALL SERIAL
MOV R0,#2 ;point to minute loc
MOVX A,@RO ;read minute
ACALL DISPLAY
MOV A,#20H ;send out SPACE
ACALL SERIAL
MOV R0,#0 ;point to seconds loc
;read seconds
MOVX A,IIRO
ACALL DISPLAY
;send out CR
HOV A,#OAH
ACALL SERIAL
;send LF
MOV A,#ODH
ACALL SERIAL
;read and display forever
SJMP OVl
, ••.•..••• SMALL DELAY
DILAY:
MOV R7,#250
Dl: OJNZ R7, 01
; .... __________ _ coNVSRT BCD TO ASCII AND SEND IT TO SCRBEN
DISPLAY:
NOV B,A
SWAP A

,u
fl
ANL A, #OFH
ORL A, #)OH ''.
ACALL SERIAL .•
HOV A,B i
t
ANL A, #OPH •
ORL
ACALL
A,#30H
SERIAL

RET
/ ·--·--------

SERIAL:
MOV SBUF,A
SI: JNB TI, Sl
ta
CLR TI
• ~
RET

;------------
• BND
• fl
••

The foUowing shows how to read and display the date. You can replace the time display portion of the above pro-
J
• gram with the program below.

( ; -------- READ DATE('lYYY:MM:MM), CONVERT IT AND OSIPLAY IT


I OV2: MOV A,#20H ;ASCII SPACE
•j ACALL SERIAL
MOV A,#'2' ;SEND OUT 2 (for 20)
I
ACALL SERIAL
MOV A,#'0'
ACALL SER!AL
;SEND OUT O (for 20) ''
~

MOV RO, #09 ;point to year loc


MOVX A,@RO ;read year
ACALL DISPLAY
MOV A,#• : , ;SEND OUT: for yyyY:mrn
ACALL SERIAL
MOV R0,#08 ;point to month loc
MOVX A,@RO ;read month
ACALL DISPLAY
ACALL DELAY
MOV A,#':,
;SEND OUT: for mrn:dd
ACALL SERIAL
MOV R0,#07 ;point to DAY loc
MOVX A,@RO ;read day

- ACALL DISPLAY
ACALL DELAY
MOV A,#' ,
;send out SPACE
ACALL SERIAL
ACALL DELAY
MOV A,#' ,
;send out SPACE
ACALL SERIAL
ACALL DELAY
MOV A,#OAH
;send out LF
ACALL SERIAL
MOV A,#ODH ;send CR
ACALL SERIAL
ACALL DELAY
LJMP OV2
;display d
ate forever
414
Review Questions
rrue or false. All of the RAM contents of the DS12887 are nonvolatile.
~ HoW many bytes of RAM in the 0512887 are set aside for the clock and date?
. )-[ow I l l ~ by~~ RAM in the DS12887 are set aside for general-purpose applications? 1 source
3i. frueor . sef h e -RAM contents of the DS12887 can last up to JO years without an extema power ·
,. ~'/hich pm o t e 0512887 is the same as the ALE pin in the 8051?
6. True or false. When the DS12887 is shipped, its oscillator is turned on.

SECTION 16.2: DS12887 RTC PROGRAMMING INC


c
In this section we program the DS12887 in 8051 language. Before you embark on this section, make sure that the
t,asic concepts of the D512887 chip covered in the first section are understood. Also, review external memory access
using 8051 C, as discussed in Chapter 14.

Turning on the oscillator, setting the time and date in C


In Chapter 14 we discussed how to access external memory using 8051 C. We also discussed the details of the
[)512887 in the previous section. ln this section we provide the C version of the programs given in the previous sec-
tion-To access the DS12887 in Figure 16-2, we use the 8051 C conunand XBYTE[addr], where addr points to the external
address location. Notice that XBYrE is part of the absacc.h library 6\e. The following C program shows how to turn on
the oscillator, and set the time and date for the configuration in Figure 16-2.

//RTC Time&Dat:e initialization in C


Oncl ude <regSl. h>
I i nclude <absacc. h>
void main (void)
{
Delay(200) //RTC needs 200 ms upon power-up
XBYTE[l0]=0x20; //turn on osc.
XBYTE[ll]•OX83; //BCD, 24 hrs, daylight savings
XBYTE[O]aOxSS; //SECOND•SSh for BCD
XBYTE[2]•0x58; //MINUTE=58h for BCD
XBYTE[4)=0xl6; //HOUR•l6H for BCD
XBYTE(7J•Ox19; //day•l9h
XBYTE[8]=0xl0; //month•lOh for October
XBYTE[9]•0X04; //year•04
XBYTE[ll]•Ox 03; //allow update
}

Reading and displaying the time and date In C


The following c program shoWS how to read the time, ronvert it to ASCl1, and send it to the PC screen via the serial port.

I /Displaying Time and Da te in C


*include <regSl. b>
I include <absacc. h>
"Oid bcdcoov (unsigned xl ;
Void aerial (unsigned x ) ;
'loid main ( void)
{
unsigned cha r br,min,sec;
TMOOaOx 20;
//9600 baud ra te
Tlll•OxFO;
, ff
I ~
sCON•OxSO; •' (
TRl=l; forever
while(l) //display time l C
I C
I \
hr•XBYTE[4]; //get hour display
bcdconv (hr) ; //convert and separate
. to
serial (' : ' ) I //send ou ·
t

min=XBYTB [2] , //get minute display


/ bcdconv(min); //convert and separate
serial ( ' : ' ) ; //send out : to
) sec•XBYTB[O]; //get second lay
bcdconv (sec) ; //convert and disp
serial (OxOD); //send out CR d
serial(OxOA); //send out Line fee
}
••

"' //clnvert BCD to ASCII and send it to serial
void bcdconv(unsigned mybyte) //see chapter 7
'• {
I unsigned char x,y,z;
•. xsmybyte&OxOF;
I x=x(oxJO;
yamybyte&OxFO;
l' Y=Y>>4;
J y=yJOx30;
serial (y);
serial Ix);
I
//send out one char serially
void serial!unsigned x )
{
SBUF=X;
1'1hile (Tl==O);
TI=O;
I

Theprogr.un
~bove following shows
with how to
the <ode read and display the date in 8051 C. You can replace the time display portion of the
below.

•·---·--- R&AD DATE(YYYY:MM:MM), CONVERT ANO DISPLAY


while(l)
{
//display date forever
serial I '2'), //send out 2 for 20xx
serial ( •o•);
//send out o for 20xx
yr•XBYTB(9); I /get year
bcdconv Iyr) ;
serial ( • : •) ; //convert and display
month=XBYTB(8); //send out : to separate
//get month
bcdconv(month);
serial<':' ) ;
//convert and display
day=XBYTB(7)1 //send out : to separate
//get day
bcdcoov(sec);
serial(OxOD); //convert and display
//send out CR
serial!OxOA);
} //send out line feed

416
~evieW Questions
rrue or false. The ~e and date are not updated during the initialization of RTC.
t,. Give
W}lat address range used for the time and date?
is
the address of the first RAM location belonging to general-purpose applications.
4- Give the C statement to set the month to October.
S. Gh·e the C statement to set the year to 2009.

SECTION 16.3: ALARM, saw, AND IRQ FEATURES OF THE DS12887 CHIP
In trus section ,ve program the ';;-OW, alarm, and interrupt features of the D512887 ~p using Assembly langu age.
n,e;e powerful features of the DS12887 can be very useful in many real-world applications.

programming the saw feature


~e S-O.W pin provides '."s a square wave output of various frequencies. The frequency is chosen by bits RSO · R5:J
of register A, as shown 1n Figure 16-6. In addition to choosing the proper frequency, we must also enable the ':-OW bit
111 register B of the DS12887. This is shown below.

MOV R0,#10 ;RO= OAH,reg A address


MOV A,#2EH ;turn on osc .• lll0=RS4 -RS0 4HZ SQW
MOVX @RO , A ;send it to Reg A of OS12887
MOV R0,#11 ;RO= OBH, Reg B address
MOVX A, ilRO ;get reg B of OS12887 to ACC
ACALL DELAY ;need delay for fast 8051
SETS ACC.3 ;let 4Hz come out
MOVX @RO,A ;send it back to reg B

I UIP I OV2 I OVl ovo I RS3 RS2 RSl I RSO I


UCP Update in progr.,ss. This is a read-only bit.

OV2 OVl ovo


0 1 0 will tum the oscillator on

RS2 RSl RSO SQW Output Frequency


RSl
0 0 0 None
0
0 0 0 I 256 Hz
0 I 0 128 Hz.
0
0 1 I 8.192 kHz
0
0 1 0 0 4.096 kHz
I 0 I 2.048 kHz
0
1 1 0 1.024 kHz
0
I I I 512 Hz
0
0 0 0 256 Hz (rept"at)
1
0 0 I 128 Hz (repeat)
1
I 0 l 0 64Hz
0 I I 32Hz
I
l 0 0 16Hz
I
l 0 I 8 Hz
I 0
1 1 1 4Hz
1 I l 2Hz
I

F.,_ lW....., Ill A bltl f o r ~ c _ . . . i .i the SQW Output Pin

a,
M I 24/ 12 I DSE J
1'1E I D d
I UIE I SQ tes are update .
SET I PIE I AJE I d and time and da st make SET - l}.
. uoting once ~rsecon[nitiaUza ' . tiOn we mu •
SET SET; 0: Clock is co 'bited (duJ'lllg the eriodic-,nterrupt,
SET s 1· Update Is inhi eneration of the P es a hardware
· 1 upon g lRQ becom '
~~7
bl lf PIE; ' n,erefore, J>I bit The
is assert~ 1~:·not want to poll tt~er A. Remember
.,' PIE Periodic interrup;
the JRQ pin of th . . register C if>,e
!'I
RSO · RS3 of reg f bit Pl in
version of the b1t·~errupt is dictated by interrupt verS10~ o ln other words,
t f the penodic-tn ( a hardware t enerat1on.
;.~ ~IE allows the gen:~~~ ~e periodi.c-int~io ll,e
rnQ output pin.
register C and has no_e the Pl bit of register when
the PIE wiU simply direct IRQ pin will be asserted! low bytes
[f AlE ; I, the me as the a arm .
AIE Alarm interrupt enable. . (hh·mm:ss) are the sa nd once-per•mJnute,
.,
of hh:mm:ss. Also, if:i~;,rt low the IRQ p,n.f ~:::i
all three bytes of th~ real tt~e the ·cases of on~-per·se:be;that AIE allows the
t:!
bit in register C and


I
' and on':""p~·:;:i.u~~;dware interrupt vers•o;;AlE wUI simply direct the A I
generation o
no e
ff ton Al generation.
ec . h
of register C into t. e
. In other words,
IRQ output
.
pm.

UIE See the D5J2a87 data sheet WE;I, the square-wave frequencyWgenerated
ou ut pin of
(. SQWE Square wave enable .. If~ . t r A will show up on the SQ
by the RSO . RS3 options o reg1s e
tp
( on
J the DS12877 chip. . d ta format ond OM~ !:binary (hex) data forma t
OM Data Mode. OM ; 0. BCD a 12-hour mode
24/12 I for 24-hour mode and Ofor
OSE Daylight saving enable

Figure 16-7. Pl!, AJE, and SQWE bits of Rtgis t•r B

On
+SV
lt1(

8051 DS12887
ALE AS vcc
WR R/W Us
RD
RESET
. OS
P0(0..7)
AD(0..7)
SQW
MOT BUZZER
-cs ,

CNO
;.

'.
Pl.7 --==-
Figure 16-8. Using SQW to Sound a B=or

IRQ output pin and Interrupt sources


Interrupt request {IRQ) is an output pin for the DS12887 RTC chi . . •
sources that can activate the IRQ pin. They are (a) alarm interrupt (br· 1t ~~active low signal There are three possible
We can choose which source to activate the IRQ pin using the inte ' penod.tc Pulse interrupt, and (c) update intemJpl
non we discuss the alann and periodic interrupts and refer reade~~t~:ble bit in register B of the DS12887. ln this sec·
418 DS12887 data sheet for the update interrupt.
THE80s1 MICRQc
ON°fROLtER ANO EMBEDDED SYSTEMS
fl1ealarm and IRQ output pin
. . te
jhe alarm mterrupt can be programmed to occur at rates of (a) once per day, (b) once per hour, (c) once per mmu '
attd (d) once per second. Next, ,ve look at each of these.

once-per-day alarm
Table 16· 1 in Se~tion 16.1 shows that address locations 1, 3, and 5 belong to the alarm seconds, alarm _minutes, and
11,lflll hours, respectively. To program the alarm for once per day, we write the desired time for the alarm mt~ the hour,
a,iJlUle, and second_ RAM locations 1, 3, and 5. As the clock keeps the time, when all three bytes of hour, ~nute, _and
second for the real time clock match the values in the alarm hour minute and second, the AF (alarm flag) btt 1n regJster
Cof the 0512887 ,vill go high. We can poll the AF bit in regist;r C whlch is a waste of mkrocontroller resources, or
UoWthe ~Q pin to be activated upon matching the alarm time with the real time. It must be noted that in ?rder to use
1
the IRQ pm of th~ ~12~7 for an alarm, the interrupt-enable bit for alarm in register B (AlE) must be set high. How to
~ ble the AIE bit m reglSter Bis shown shortly.

once-per-hour alarm
To program the alarm for once per hour, we write value llxxxxx into the alarm hour location of 5 only. Value
11roxx means any hex value of FCH to FFH. Very often we use value FFH.

Once-per-minute alarm
To program the alarm for once per minute, we write value FFH into both the alarm hour and alarm minute loca-
tions of 5 and 3.

Once-per-second alarm
To program the alarm for once per second, we write value FFH into all three locations of alarm hour, alarm minute,
and alarm second.

Using IRQ of DS12877 to activate the 8051 interrupt


We can connect the TRQ of the 0512887 to the external interrupt pin of the 8051 (INTO). This allows us to perform
• task once per day, once per minute, and so on. The program given i.n the next two pages will (a) sound the buzzer
a>ruiected toSQW pin, and (b) will send the message "Y~S'.' to the serial port once per minute at exactly 8 seconds past
!he minute. The buzzer will stay on for 7 seconds before 1t 1s turned off.

:· --·- ··SEND HELLO TO SCREEN 8 SEC PAST THE MINUTE


;------- USING ALRAM IRQ
ORG 0 ·SOME INITIALIZATION
WMP MAIN '
ORG 03 ·GO TO INTERRUPT SRVICE ROUTINE
LJMP ISR_EXO '
ORG lOOH
11>.IN:
·INTO (EXO ) IS ENABLED
MOV IE,#81H ';MAKE IT EDGE-TRIG
SETS TCON.1 ·SERIAL !'ORT SET UP
IIOV THOD,#20H •
MOV SC0N,ll50H
; 9600
MOV THl,#·3
Sl!TB TIU

Dsuae, RTC 1NTllllfACING AND PllOGllAMMING t19


;·······TORNING ON
o THE RTC
·RO•OAH, Reg
A address
n osc., sow-8HZ
HOV RO. #1 , i 06-04 turn O 12887
MOV A,#20H ;010 ~ o Reg A of OS
uovx •RO A ; send 1t t
r• ' • . mode
········Setting the T1me
· •·• •· • ddress i g
• MOV RO.fill ;Reg 8 a daylight saV n
MOV A, #83H ;BCD, 24hrs,

.. • ACALL DELAY
MOVX @RO.A ;send it to Reg B !
ACALL DELAY
···········Setting
• the Time
PLACE THE CODE HERE; '
• ;··········Setting the Alarm Time 1arm seconds address
MOV R0,#1 ;pointer for a MINUTE
MOV A, #OS ; 8 SEC PAST THE
.,
.• MOVX @RO, A
MOV RO• #3
;set seconds•8
; point to mi nu tes address
)

' MOV A, #OFFH ;ONCE PER MINUTE j


I
• MOVX @RO,A
I MOV RO, #5 ;
• MOV A, #OFFH ;FF FOR THE HOUR

l MOVX @RO,A
ACALL DELAY
;

''J MOV R0,#11


MOV A, #23H
;Reg B address
;07• 0 to update,AIEcl to allow IRQ
MOVX i/RO, A ;activae INTO of 8051
·········READING
• TIME
PLACE READING TIME CODE HERE
;·······SERIAL TRANSFER
SERIAL:
CLR IE.7 ;DISABLE EXTERNAL INTERRUPT
MOV SBUF,A
Sl: JNB TI, Sl
CLR TI
SETB IE . 7 ;RE-ENABLE THE INTERRROPT
RET
;•-·!SR SENDS ·YEs• TO SCREEN AND SOUND THE BUZZER
ORG SOOH ; the ISR for the IRQ of DS12887
ISR_EXO:
MOV RO, #12 ;Reg C address
ACALL DELAY
MOVX A,@RO
MOV RO, #11 ;READING REG C WILL DISABLE THE IRQ
;Reg B address
ACALL DELAY
MOVX A,ilRO
ACALL DELA'i
SETB ACC.3
SE:TB Pl. 7
;LBT SQW COMB OUT OF RTC
ACALL DELAY ; ENABLE THE AND GATE TO so•~-
v ... u BUZZER
MOVX •RO ,A
MOV A,#'Y'
ACALL SERIAL
MOV A,#'E'
ACALL SERIAL
MOV A,#'S'
ACALL SERIAL

420
Tlil: 80Sl f\1JCRoc -
ONl'Rot
lER ANO EMBEDDED SYSTEMS
ACALL DELAY_l ;7 SEC DELAY TO HEAR THE BUZZER
14QV RO, #11 ;Reg B address
ACALL DELAY
MOVX A,@RO
CLR ACC. 3 ;BLOCK SQW FROM COMING OUT OF RTC
ACALL DELAY ;SHORT DELAY TO LET RTC REST
MOVX @RO ,A ;BEFORE ACCESSING IT AGAIN
CLR Pl. 7 ;TURN OFF THE AND GATE
RBTI ;RETURN FROM INTERRUPT

Regarding the last program, several points must be noted.

1. Ill the beginning of th.e program we enabled the external hardware interrupt and made it edge triggered to match
the IRQ of the DS12887.
l Ill register B, the AIE bit was set high to allow an alarm interrupt.
3. Ill the serial subroutine, we d isabled the external interrupt INTO to prevent conflict with the TI flag.
1 In the JSR, we enabled the SQWE to allow a square wave to come out of the RTC chip in order to provide pulses to
the buzzer. We disabled it at the end of JSR after 7 seconds duration in the DELA Y_J subroutine.
; In the !SR, we also read the C register to prevent the occurrence of multiple interrupts from the same source.

The periodic interrupt and IRQ output pin


The second source of interrupt is the periodic interrupt flag (PF). The periodic interrupt flag is part of register C. Jt
will go high at a rate set by the RS3 -RSObitsof register A. Th.is rate can be from once every 500 ms to once every 122 µs as
shown in Figure 16-11. The PF becomes 1 when an edge is detected for the period. Just like alarm interrupt, the periodic
111terrupt can also be directed to the lRQ pin. To use IRQ. the interrupt-enable bits of PIE in register B n1ust be set to 1. In
ocher words, we can poll the PF bit of register C, which is a waste of the microcontroller's resources, or it can be directed
ID the hardware IRQ pin. If we set PIE = 1, the IRQ pin is asserted low when PF goes high. While the alarm intern,pt
gave us the options from once per day to once per second, the periodjc interrupt gives us the option of subsecond inter·
rupts. For example, we can write a program to send a message to the screen twice per second (2 Hz). The following code
fragments show how to send the message "HELLO" to the screen twice per second using the periodic interrupt with the
help of hard ware [RQ (see Figure 16-9).

+5V
--
0512887
8051
AU! AS vcc
-
R/W
WR RESET
R5 DS
P0(0•.7)
- AD(0 .. 7) SQW
BUZZER

-INTO - -
IRQ
MOT
cs
GND

--
-
Pt.7

..... l'-9, Utlng DSUll7 lllQ la Activate an 8051 lntel'Npt

Osu.e, RTC INTDl'ACING AND ,aoGllAMMING


, 0 0 J
0 0
jlRQFj Pf I AF I UF I
s I: if PF s PIE s l or AF s AJE" I or UF" U!E" I
lRQF (PIE, AIE, and UlE are the bits of Register B)
. . • ts can be generated at a rate of once
Periodic interrupt flag. Penod1c mterruP . set by bits RS3. RSO of register
PF every 500 ms to once every 122µs. 'f!'e rate ,sed {or the period- We can poll this
A. The PF b<:comes 1 when an ed~e is detect . f 0512887 can be asserted
I
or, with the help of bit PIE of reg.st~r 6, the !R~
P~5 wLll be done if the PIF
low for the hardware interrupt version of this '(· 8 1 ther (if both are
bit of Reg 8 is set to J. That is, PF and PIE of reg,ster oge. ..
1) will allow IRQ to be asserted low. Reading PF will clear ,t, and that IS
how we deassert the IRQ pin.

•• .• AF Alarm interrupt flag. The AF becomes I when the current real time matches ...
the alarm time. AF and AlE of register B together (if both are 1) will allow
' the IRQ to be asserted low when all the three bytes of the real time (yy:mm:dd)

are the same as the bytes in the alarm fune. The AF also becomes 1 for cases
I of once per second, once per minute, and once per hour alarm. Reading AF will
clear, it and that is how we deassert the lRQ pin.

I UF See the 0512887 data sheet. ..


'J Figure 16-10. Register C bits for Interrupt Flag Sources

I uw DV2 I· OVl I· DVO I. RS3 I. RS2 j RSl j RSO


UIP Update in progr0$S. This is a read-only bit.

DVZ DVI OVO


0 1 0 will tum the oscillator on
RS3 RS2 RSI RSO Tpi PERIODIC
INTERRUPT RATE
SQW Output Freq. ; ..
0 0 0 0 :l"i]
None
0 0 0 I None
0 3.9062 ms
0 I 0 256Hz
0 0 7.812 ms
I I 128 Hz
0 1 122.070 µs
0 0 8.192 kHz
0 1 244.141 µs
0 1 4.096 kHz
0 I I
488.281 µs
0 976.5625 µs 2,048 kHz
0 1 I I
t 0 0 1.953125 ms 1.024 kHz
0
I 0 0 3.90625 ms 512 Hz
1
1 0 I 7,8125 ms 256Hz
0
I 0 I 1 15.625 ms 128 Hz
I I 0 0 31.25 ms 64HL
I I 0 I 62.S ms 32Hz
I I 1 0 125 ms 16Hz
l I I 1 250 ms 8Hz
SOOms 4Hz
Figure 16-11. Rtgisl~r A bits for Ptrio,rIC In terrupt R 2Hz
•••

'Ili Esos1
MlCRoco111
TROttERA -
ND EMBEDDED SYSTEMS
1endi ng Hl'ILLO to screen twice p er second
CRG 0
LJKP MAIN
ORO 03
WMP ISR_ EXO
ORO 100H
··.....·~ MOV 1£,#BlH
SITB TCON.l
;INTO (EXO ) I S ENABLED
:MAKE IT EDGE-TRIG
1
,pIAL PORT SET-UP
MOV TMOD, #20H
MOV SCON, #SOH
MOV THl.H - 3 ;9600
SETS TRl
.iURlflNG ON THE RTC

MOV RO, #10 ;RO=OAH,Reg A address
MOV A, #2PI! ;osc•on, Periodi c of twice Per sec
MOVX ltRO,A ;send it to Reg A of DS12887
;····· ··-··---Setting the Time mode
MOV RO, #ll ;Reg B address
MOV A, #83H ;BCD, 24hrs, daylight saving
ACALL D£LAY
MOVX • RO,A ,send it to Reg B
ACALL DELAY
,-····-----setting the Time
MOV R0,#0 ;load pointer for seconds address
MOV A, #SSH ;seconds• SSH (BCD numbers need H)
MOVX ltRO,A ;set seconds to 31
MOV RO, #02 ;point to minutes address
MOV A, #S6H ;minutes=56 (BCD numbers need H)
MOVX Ii/RO, A ;set minutes
MOV R0,#04 ;point to hours address
MOV A,#16H ;hours•l6
MOVX f/RO,A ,set hours to 16
ACALL DELAY
MOV RO, #11 ;Reg B address
MOV A , #4 38 ; D7•0 to update.periodic INTR is ON
MOVX @RO,A
; • · • · • - · -READING TIME
OVl: MOV A, #20H ;ASCII for SPACE
ACALL SERIAL
MOV RO, #4 ;point to HR loc
MOVX A,lilRO ;read hours
ACALL DISPLAY
MOV A, #20H ;SEND OUT SPACE
ACALL SERIAL
MOV RO, #2 ;point to minute loc
MOVX A,@RO ; read minute
ACALL DISPLAY
MOV A, #20H ;send out SPACE
ACALL SERIAL
MOV R0,#0 ;point to sec loc
MOVX A,411RO ;read sec
ACALL DISPLAY
HOV A, #OAH ;eend out CR
A.CALL SERIAL
IIOV A,#ODH ;send LF
,
Time forever
ACALL sERlAL
SJHP OVl ;Read and displ ay
1······ ·-·SMALL DELAY
osLAY:MOV R7,#2S0
Dl: """
~=•z R7, Dl
RET AND ssND IT 'l'O scREEN ~
/ ;----- ······--CONVERT BCD TO ASCII
DISPLAY:
HOV B,A
f
SWAP A I 11
• \I
A!IL A, #OFH •
ORL A, #)OH ) Ir

ACALL SERIAL l'

MOV A, B ~r
~
•• ANL A, #OFH
• • rs
'\ ORL A, #30H •0
•• ACALL SERIAL
s~
RET __________ __ .. Ir
.
I
·-----·----
' ,1
SERIAL:
I.
I
CLR
HOV
IE.7
SBUF,A
·DISABLE INTO INTERRUPT
'
U. C
C. F
,
( Sl: JNB TI,Sl
CLR TI
U. C
It}
SETB IE.7 ·RE-ENABLE INTO INTERRUPT Ii ,I
RET '
·-----!SR TO SEND •HELLO" TO SCREEN TWICE PER SEC
;. D
'
ORG SOOH Ii s
!SR EXO: I!. F
HOV- R0,#12 ;Reg c address 19 [
ACALL DELAY !I
HOVX A,@RO ;READING REG C WILL DI SABLE 11
· THE PERIODIC INTR
' l\
MOV A,H'H'
ACALL SERIAL !l. 1
MOV A,#'E' :t I
ACALL SERIAL 15. 1
MOV A,#'L' ll
ACALL SERIAL ~- '
MOV A,-'L' l•
ACALL SERIAL ~·
MOV A, It '0'
ACALL SERIAL
».
RETI n.
l2.
13
Review Questions lt
lS
1. Which bit of register 8 belongs to the SQW pin?
2. True or false. The CRQ out pin of DS12887 is active low.
3. Which bit of register B belongs to alam, interrupt?
4. Give the address locations for hh:mm;ss of the alarm.
S. If the source of activation for IRQ is alarm, then explain how th , .
6. Wh.1t is the difference between the AF and AJE bils? e IRQ Pin IS •c:tivall!d.
7. What is the difference between the PF and PJE bils?
5111,1MARY
· Th timing of ADO· AD7 of
1llii (h.1pter beJ;,1n by de,;cnbing the function of each pin of the DS12887 RTC ch,~. che h as the 74LS373. The
M ci,1~7 rruakhl'11 tht- tuning of PO of the 8051 eliminating the need for an external at fsuc f the RTC were
.. ..._ ___ , • - t· ns Various eatures o
0,1~7 c•n "" u~-... to provide a real·ttme clock and dates for many app 1,ca 10 •
f ' ~ ' •nd numerous programmJng examples were given.

pROBLEMS
q:(TION lb!· DS12.887 RTC INTERFACING
I The DSl 2887 OIP package is a(n) -pin package.
t Which pins are assigned to V" and GNO?
1 In the 0512887, how many pins are designated as address/data pins?
t True or false. The 0512887 needs an external crystal oscillator.
5. True or false. The DS12887's crystal oscillator is turned on when it is shipped .
._ In 0512887, what is the maximum year that it can provide?
i. Descnbe the functions of pins 05, AS, and MOT.
g, RESET is an (input, output) pin.
9 The RESET pin is normally (low, high) and needs a (low, high) signaJ to be activated.
10 What are the contents of the 0512887 time and date registers if power to lhe V" pin is cut off?
11 OS pin stands for and is a.n (input, output) pin.
U. For the 0512887 chip, pin RESET is connected to (V.,, GNO).
ll OS is an (input, output) pin and it is connected to pin of the 8051 .
ll. AS is an (input, output) pin and it is connected to pin of the 8051.
15 ALE of 8051 is connected to pin of the 0512887.
16. IRQ is an (input, output) pin.
17. SQW is an (input, output) pin.
ta R/ W is an (input, output) pin.
19. DS12887 has a total of bytes of NV-RAM.
lO. What are the contents of the 0512887 time and date registers if power to lhe V" pin is lost?
21. What are the contents of the general-purpose RAM locations if power lo lhe V" is lost?
!2. When does the DS12887 switch to its internal battery?
?I. What are the addresses assigned to the real-time clock registers?
lt What are the addres.qes assigned to registers A· C?
lS. Which register is used to set the AM/PM mode? Give the bit location of that register.
l6. Which register is used to set the daylight savings mode? Give the bit location of that register.
ll. At what memory location does lhe 0512887 store the year 200n
28. What is the address of the lasl location of RAM for the OSI 2887?
29. Write a program to dlsplay the time in AM/PM mode.
lO. Write a program to get the year data in BCO and send it lo ports Pl and P2.
lt. Write a program to gel lhe hour and minute data in binary (hex) and send it to ports Pl and P2.
32. Write a program to set the time to 9:15:05 PM.
l3 Write a program to set the time to to 22:47:J 9.
~ Write a program to set the date to May 14, 2009.
ll. On what day in October, is daylight savings time changed?

SECTION 16.2: 0512887 RTC PROGRAMMING 1N C


36 Wnte a C program to display the time in AM/PM mode.
: Write a C program to get the year data in_BCO and ~d it to ports Pl and P2.
l9 Wnte a C program to get lhe ~our and minute data tn binary {hex) and send it to rts Pl d P2
t> Write a C prQgram to set lhe time to 9:15:05 PM. po an ·
41 Wnte • C program to !>Ct the time to 22:47:19.
ll. Wnte a C program to set the dale to May 14, 2009.
In Queshon 41, where did you get the 20H?

~;;;R;T~C~INTl!;;;:;;R~F~A~C;IN;G;;-;;A~N~D;;;PR~OG;;-~RAM~;M~l~
N~G:----~~.;._...;;...-.a:..._--c--"'.;;;_~---~.a.._-.~~-
OF THE 0512887 CJ{!]'
SEC110N 16.3: ALARM, SQW, AND [RQ FEA~ (low, high),
. tp t) pin and acove
43. IRQ is an - - - - (m~ut, ou u . ow to enable it.
44. SQW is an (mput, output}_pm, e alarm interrupt. ShoW h w to enable it.
45. Give the bit location of register B belongmg to th eriodic interrupt. Show ho
46. Give the bit location of register B belonglllg to the PJarO'l interrupt.
47. Give the bit location of register C belonging to the a . oclic interrupt.
48. Give the bit location of register C belonging to the~· SQW pin?
/ 49. What is the lowest frequency that we can create on e SQW pin?
SO. What is the highest frequency that we can create on the .
51. Give two sources of interrupt that can activate the IR~ ~Ill:
52. What is the lowest period that we can use for the perioodd,~ ~t;r;rp;'
t' /
53. What is the highest period that we can use for the pen ic Ill e 1 •
• 54. Why do we want to direct the PF (periodic interrupt) flag to IRQ .
55. Why do we want to direct the AF (alarrn flag) to IRQ?
••• 56. What is the difference between the PF and PIE bits?
57. What is the difference between the Af and AfE bits?
' I
58. How do we aUow the square wave to come out of the SQW pin?
• 59. Which register is used to set the frequency of the SQW pin?
60. Which register is used to set the periodic-interrupt duration?
'
,
I
61. Which register is used to set the once-per-second alarm interrupt?
62. Explain how the IRQ pin is activated due to the alarm interrupt.
63. Explain how the IRQ pin is activated due to the periodic interrupt.
64. Write a program to generate a 512 Hz square wave on the SQW pin.
'I 65. Write a program to generate a 64 Hz square wave on the SQW pin.

ANSWERS TO REVIEW QUESTIONS


SECTION 16.1: 0512887 RTC INTERFACING
I.
2.
3.
True
9
114
r
4. True
5. AS
6. False

SECTION 16.2: DS12887 RTC PROGRAMMJNG INC


1. True
2. 0·9
3. OEH (14 in decimal)
4. XBYTE(S]:OxOA;
5. XBYTE(09J=Ox09; where the 20 part
·
of 2009 JS
. assumed.

SECTION 16.3: ALARM, SWQ, AND ffiQ FEA11JRE


L D3 of DO • 07 S OF THE DS12887 CHIP
2. True
3. D5
4. Byte addresses of 1, 3, 5
5. u_ the AIE bit of Reg B is set tQl, then the IR . .
high when the alarm time and real tim Q pm is activated .
6. The AP bit in register c becomes hi h e values match. · This happens due tO
Bsimply allows the AP to be direct~ when the alarm time and the AF bit in register C going

ister B simply allows the pp to be ff'


7. The PF bit in register C becomes hi tohthe IRQ pin.
wt en the edge is det
rec ed to the IRQ Pm.
real time values m
. ectect for the periodic
.
a tc.h, while the AIE bit of register
i t
n errupt, while the PfE bit of reg·
426
Tlil: 80St MrcRoc:
ONTROLL -
ER ANO EMBEDDED svsT&fS
CHAPTER17

MOTOR CONTROL:
RELAY, PWM, DC, AND
STEPPER MOTORS

OBJECTIVES

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

> Describe the basic operation of a relay


> Interface the 8051 with a relay
> Describe the basic operation of an optoisolator
> Interface the 8051 with an optoisolator
> Describe the basic operation of a stepper motor
> Interface the 8051 with a stepper motor
> Code 8051 programs to control and operate a stepper motor
> Define stepper motor operdtion in terms of step angle steps
> per revolution, tooth pitch, rotation speed, and RPM '
> Describe the basic operation of a DC motor
> Interface the 8051 with a DC motor
> Code 8051 programs to control and operate a DC motor
> ~ how PWM is used to control motor speed

;
427
. .th relays, optoisolators, stepper motors
. d shows 8()51 interfaClJlg WliJ>ed. Then we show their interfacing Withatid
This chapter discusses motor control an d toisolators are descr characteristics of DC motors are cl ;...... ~
ex: motors. In Section 17.1, the basics of relays an . Op e 8051 is shoWll· The . WM ( uJse width modula-:-'~
8051. In Section 172 , stepper motor interfacing with ~ill also diSC:USS the topic of P P lion). W,
in 5ect1on 17.3, along with interfacing to the_S051. We 1
use both Assembly and C in our programmmg ex:arnp es.

• SECTION 17.1: RELA VS AND OPTOISOLA


. TORStions of electromechanical relays, solid-state relays, reeci
,I'
This section begins with an overview of the bas•: opera th to the 8051. We use both Assembly and C language
switches, and optoisolators. Then we describe how to mterface ern
programs to demonstrate their control. 11'
c\11

Electromechanical relays . . d · · d strial controls auton,obiles, and applian- It • 111
.,
'
A relay is an electricaUy controllable s,v1tch widely use lll lll u ' •••·
allows the isolation of two separate sections of a system with two different voltage so~rces. For example, a +5V system ' "°
I can be isolated from a 120V system by placing a relay between them. One such relay 15 called 3':' electromechanical (or 111
.• electromagnetic} relay (EMR) as shown in Figure 17-1. The EMRs have three cornpon~nts: the cot!, spnng, 3':'d contacts. (II
In Figure 17-1, a digital +SV on the left side can control a J2V motor on the right side without any physical contact g-,
be~een them. When current flows through the coil, a magnetic 6eld is created around the coil (the coil is energized), 1,tJ
"'.hi~ causes the armature to be attracted to the coil. The armature's contact acts li ke a switch and closes or opens the
l
I
°;"Cmt. When the coil is not energized, a spring pulls the armature to its normal state of open or closed. ln the block
I))

I 1?
I diagram for eh,ctomcchankal relays (EMR) we do not show the spring, but it does exist intema lly. There are all types of
/ relays for all kinds of applications. In choosing a relay the following characteristics need to be considered: ID
di
fa

"d
Normally
~Common Closed
l)ivl
t Common
Normally
Open t Normally
Open
D
!!1111
din·e
T
<•l SPST ll'!ry
Cb) SPOT

Normally
Closed
Common
L_ Normally
Open

k) DPDT

Figun, 17-L R•l•y Diag,ams

428
Tli£ 80St MlCJtoc oNT - \;
llOLLl!R AND EMBEDDED svsfEMS
--
t,~lt 17-1: Selected DIP Relay Characteristics (www.Jameco.com)
,.~ ,o. Contact Form Coil Volts Coil Ohms Contact Volts-Current

--
1oovDC-O.SA
~"'CP Sl'ST-NO SVDC 500
1oovoc-0.sA
,;<l10CP SPST-NO SVDC 500
• JOOVDC·O.SA
1-"'47tCr SPST-NO 12VOC 1000
;ijiscP SPST-NO 12VDC 1000 lOOVDC-0.5A
Ill ..- DPOT 62.5 30VDC·1A
It :%,°:,Cl' SVDC

1 The contacts can be normally open (NO) or normally closed (NC). In the NC tn:ie, the contacts are closed when the

.
. It
(Cir
:II.
coil is not energized. In the NO, the contacts are open when the coil is unenergized .
l There can one or more contacts. For example, we can have SPST (single pole, single throw), SPOT (single pole,
double throw), and DPDT (double pole, double throw) relays.
J The voltage and current needed to energize the coil. The voltage can vary from a £.-~ volts to~ v.olts, while the
let rurrent can be from a £ew mA to 20 mA. The relay has a minimum voltage, below which the coil will not be ener-
cl), gized. This minimum voltage is called the "pull-in" voltage. In the datasheet for relays we might not see current,
ht but rather coil resistance. The V / R will give you the puU-in current. For example, i( the coil voltage is SV, and the
d roil resistance is 500 ohms, we need a minimum of 10 mA (5V/500 ohms= JO mA) pull-in current.
,ol
l The maximum DC/ AC voltage and current that can be handled by the contacts. This is in the range of a few volts
lo hundreds of volts, while the current can be from a few amps to 40A or more, depending on the relay. Notice the
difference between this voltage/ current specification and the voltage/current needed for energizing the coil. The
fact that one can use such a smaU amount of voltage/ current on one s ide to handle a large amount of voltage/cur-
rent on the other side is what makes relays so widely used in industria.l controls. Examine Table 17-1 for some relay
characteristics. ·

Driving a relay
Digital syste~ and micr~ntroller pins la_ck s ufficient current to drive the relay. While the relay's coil needs arow,d
10.mA to be ene,gized, the IJ\lcrocontroller's pm can provide a maximum of 1-2 mA current. For this reason, we place a
driver, such as ~e ULN2.803, or a power transistor between the microcontroller and the relay as shown in Figure 17-2.
The following program tums the lamp on and off shown in Figure 17-2 by eneroizing and de-ener<>i-rm · g th ·1
"'erysecond. ·o· 0 - ere ay

+SV +SV +12V

DS89C4x0 10 UL\12803
4.7k

II 8 _ __,!6LJ
l'J.O,J---.__ _;;:.i..f;;>.Lj:....:. 8

, --
,, r,g,,,, 17-2. DS89C4x0 Connection to Relay

1.!otoll
CONTROL: RELAY, PWM, DC, AND STEPPER MOTORS
-
ORG OH
MAl N:
SETS Pl. 0
HOV RS, #55
ACJ\LL DELAY
CLR Pl.O
MOV RS, #S S
./ ACALL DELAY
SJMP MAI N
DELAY:
Ml: MOV R4,#100
H2: MOV R3, #2S 3
• H3: OJNZ R3, H3
DJNZ R4 , H2
DJNZ RS, Ml
..'
••
• RET
END

• Solid-state re.lay
Another widely used relay is the solid-state relay. In this relay, there is no coil, s pring, ~r mecha~cal :ontact switch.
I
\ The entire relay is made out of semiconductor mate1ials. Because no m~an1cal parts are involved m s ol~d-s tate relays,
I their switching response time is much faster than that of electromecharucal relays. Another problem w,th the electro-
•j mechanical relay is its life expectancy. The life cycle for the electromechanical relay can vary from a few hundred thou-
sands to few million operations. Wear and tear on the contact points can cause the relay to malfunction after a while.
Solid-state relays have no such limitations. Extremely low input current an d s maJI packaging make solid-state relays
ideal for microprocessor and logic control switching. They are w idely used in controlling pumps, solenoids, alarms,
and othe~ pow~r application~. 5?me solid-state relays have a phase con trol option , which is ideal for motor-speed con·
trol and light-dmmung applications. Figure 17·3 shows control of a fan using a solid-state relay (SSR). ~I
Ins
Table 17-2: Selected Solid-State Relay Characteristics (www.Jame co.com ) lm,ng
Part No. Contact Style Control Volts SIS
Contact Volts Conta ct Current
143058CP SPST 4·32VDC
11is
240VAC 3A lll hil
139053CP SPST 3-32VDC 240VAC 25A 1!119t
16234JCP SPST 3-32VDC 240VAC ll!d&
17259JCP lOA
SPST 3·32VDC ~

-
60VDC 2A
17S222CP SPST 3-32VDC
176647CP 60VDC
4A

-
SPST 3·32VOC
120VOC
SA

120VAC
-
,
75 \.v ' ,
8051 16234! - I
3

~
I

~~
ZERO
VOLTACE
0 1\CUJT
-
PI.O 4
2 FAN

. .
Flptt 17•3. 8051 Conntclion to a Solid-State R~lay
I

.. T!iE 80St MICR.,...,..


"'-ONllt -
OLLER ANO EMBEDDED sYS'fDIS
M
WHEEL A WHEEL
G
N
E
T

MAGNET

REED SWITCH REED SWITCH


(Closed) (Open)

Rgurt 174. Reed Switch and Magnet Combination

,.,ti. Reed switch


'Il- Another popular switch is the reed switch. When the reed switch_is pla~ed in a magnetic field: ~e contact is dosed.
a- When the magnetic field is removed, the contact is forced open by its spring. The reed switch lS ideal for moist and

,.
It. uwme environments where it can be s ubmerged in fuel or water. They are also widely used in dirty and dusty atmos-
pheres since they are tightly sealed.
••
n-
Oploisolator
In some appLications we use an optoisolator (also called optocoupler) to isolate two parts of a system. An example is

-- driving a motor. Motors can produce what is caUcd back EMF, a high voltage spike p roduced by a sudden change of cur-
rent as indicated in the V = Ldi/ dt formula. In situations such as printed circuit board design, we can reduce the effect
al this unwanted voltage spike (called ground bounce) by using decoupling capacitors (see Appendix C). In systems
- lhat have inductors (coil winding), such as motors, decoupling capacitor o r a diode will not do the job. In such cases

- ~euseoptoisolators. An optoisolator has an LED (light-emitting diode) transmitter and a photosensor receiver, sepa-
ra~ from each other by a gap._When c_urrent flows through the diode, it transmits a signal light across the gap and the
-- receiver produces the same signal with the same phase but a different current and amplitude. See Figure 17·5.

- 11..74
OPTOISOLATOR
IL074
OPTOISOLATOR
ILQ74
OPTOISOLATOR
t 6 8 I
2 2 2
3 3 3

~g,,l't 17-S. Optoloolator Pad<age ua.m pl ..

431
JL074
. used in conunuOJ·cation OPT0IS0LATOR
0pto,solotors are ai:, wide~ allows a computer ~ : 8051
uipment such ii!. m ems. . · k of damage l 8
eq It'd to a telephone Tine without ns . nd receiver
connec the transmitter a
pcwersurges. Thegapbetwtheenl trical current surge froJTI 7 +12V
of optoisolators prevents e e ec 2
reaching the system.
6
;f' • 3
Pt.0
Interfacing an optoisolator .
5
The optoisolator comes in a sma
II re Package with
th t contain
4

• four or more pins. There are also packages at ·solator


• more than one optoisolator. When placing an op o1oltage
. . wc mu.s·t use .two. separate +SV
between two c1rcmts, .6 vUnlike
17
sources, one for each side, as shown in Ftgu~h mlcrocon-
• relays no drivers need to be placed between e Figure 17-6. ControIf,ng a Lamp via Optoisolator
• trolle;/digital output and the optoisolators.
' ~~~~~~~~,

A
' Review Questions
!IIP I
I I. Give one application whe1e would you u.se a relatroy.ller and the relay?
2. VVhy do we place a driver between the ,rucrocon
I
I
Ho
• 3. What is an NC relay? . ,
4. Why are relays that use coils called electromech•:~ relays . ~
jrlllll
5. What is the advantage of a solid-state relay over 7el ,
6. What is the advantage of an optoisolator over an EM r ay · jr IJIIJ
l11111U
111111!
SECTION 17.2: STEPPER MOTOR INTERFACING 11111!1
llrota
This section begins with an overview of the basic operation of stepper ?dip,
motors. Then we describe how to interface a stepper motor to the 8051.
Finally, we usc Assembly language programs to demonstrate control of
the angle and direction of stepper motor rotation. § s
Average
North ...
kt
1:11. a

I thii
Stepper motors "'5
") C
A stepper motor is a widely used device that t~anslates electrical Average
pulses in.to m.echanical move~ent. In applications such as disk drives, South lliOci
dot matrix printers, and robotics, the stepper motor is used for position

- control. Stepper motors commonly have a permanent magnet rotor (al


called the shaft) surrounded by • stator (see Figu re 17-7). There a re ~
steppers called variable reluctance stepptr motors that do not have a PM
rotor. The most common stepper motors have four stator Wind·
are paired with • cent~r-tapped common as shown in Figure l~r .1 tha Figure 17-7. Rotor AUgnment
type of stepper motor IS commonly referred to as a four-phase or : This
stepper motor. The center tap allows a change of current d . . Wu polar
of two coils when a winding is grounded, thereby resulti uection in e~ch
change of the stator. Notice that while a conventional m:1 i.n • polanty
freely, the stepper motor shalt moves in a fixed re ata or .shaft runs
which allows one to move it to a precise position. ~ ble increment,
movement is possible as a result of basic magnetic th is repeatable fixed
the same polarity repel and opposite poles attract ;;:ry ':"he': poles of COM
rotati<>n is dictated by the sta tor poles. The stator ~Ole: direction of the
by the current sent through the wire coils. As the d. . are determined
•Ieetion of the current

ig~ l 7-8. St1tor Windings Confipntioll
THI! aos1 M1c11.oco
IIITROLl.liR AND EMBEDDED SYSTEMS
-
r,ttle 17-3: Nom1al 4-Step Sequence

('),~W ....
Sttp I
I
2
Winding A
I
Winding 8
0
Wi nding C
0
Wind ing D
I
0
Counter-
Clockwi..c

I I 0
) 0 0
I l
4 0 I I
0

5 changed, the polanty i,, also changed causing the reverse motion of the rotor. The stepper motor discussed here has
, llltill of 6 leads: 4 leads representing the lour stator windings and 2 commons for the centcr: tapped leads. As the
~ of power is applied to each stator winding, the rotor will rotate. There are severa l widely used sequences
•httetach has a different degree of precision. Table 17-3 shows a 2-phase, 4-step stepping sequence. .
It must be noted that a lthough we can start with any of the sequences in Table 17-3, once we start we must continue
u,the proper order. For example, if we start with step 3 (0110), we must continue in the sequence of s teps 4, I, 2, e tc.

Step angle
How much movement is associated with a single step? This Table 17-4: Stepper Motor Step An gles
depfflds on the internal construction of the motor, in particular
tht number of teeth on the stator and the rotor. The step a11gle is Step Angle Steps per Revolution
the minimum degree of rotation associated with a single step. 0.72 500
V,rious motors have different step angles. Table 17-4 shows
1.8 200
some step angles fo r various motors. In Table 17-4, notice the
lmn sleps per revol11tio11. This is the tota l number of s teps needed 2.0 180
lo rotate one complete rotation or 360 degrees (e.g., 180 steps , 2.5
!degrees ; 360). 141
. It must be noted that perhaps contrary to one's initial impres- 5.0 72
sion, a stepper motor does not need more terminal leads for the 7.5 48
•ator to achieve smaller steps. All the stepper motors discussed
in this section have 4 leads lor the stator winding and 2 COM 15 24
wires for the cc_nter tap. Although some manufacturers set aside
only one lead for the common signal instead of two, they always have 4 leads for the srators N t di
'SSOdated terminology in order to understand the stepper motor further. · ex we scuss some

Eumpl, 17-t

Describe the 8051 connection to the s tepper motor of Figure 17-9 and code . .
a program to rotate 11 continuously.
Solution:

The following s teps show IN.' 8051 connection to the s tepper motor and ·- .
"" programming.
I Use •n olunrneter to measure the resistance of the leads. This sh0 uld 1.d tify .
to which winding lff(ljJ. en which COM leads are connected
2. Tht common witt(s) are connt'cted to 1hr positive &ide of the
IS 11t11fidffl1. motor's power supply. In many motors. +5 v

433
, . of the 8051 port (Pl.0 - Pl .3). However,
Jled by four bits . d ' gs we must use a driver such as 11\e
ding are trO ' transistors as d n·vers, asshown
3 The four leads of the sta tor wm ·
. the stepper n,o tor win inused
con
since the 8051 lacks sufficient rurrent to dn;e ULN2003, we could havee must also use diodes to take care of
t)LN2003 to energize the stator. Instead of . ~ors are used as drivers,~" using the ULN2003 is preferable to
1
in Figure 17-9. However, notice that if tr~JS ed off. One reason . ~ take care of back EMF.
inductive current generated when the coil ,s tu';;o
2 3
h an internal d10 e to
the use of transistors as drivers is that the uLN as
.. •

MOV A,#66R ·load step sequence tor


' e to mo
BACK: MOV Pl,A ;issue sequenc · se
·rotate right clockwi
• RR A
';wait
• ACALL DELAY
SJM2 BACK ;keep going
.,
• DELAY
•• MOV R2,#100
• Hl: MOV R3,#2S5
H2: DJNZ R3,H2
• DJNZ R2,Hl
RET

Change the value of DELAY to set the speed of rotation.


We can use the single-bit instructions SETB and CLR instead of RR A to create the sequences.

+S___.. To stepper motor


I,
supply
DS89C4x0 4.7k 4.7k 4.7k 4.7k Unipolar
9 ULN2003 Stepper Motor
Pl .O -
Pl.I .
V

:
Pl.2 .• :
-
Pl.J

. -
:
-
Use one power supply for
the motor and ULN2003
""' ""
and another for the so.;1

Steps per second and rpm relation


The relation between rpm (revoluti .
ons per rninute), steps per rev I .
o ution, and ste
Stq,s per 5eeoud " pm l< Steps ps per second is as roUows.
per revo/util)/1
60 -

11il! 80511'.fJCtt
0CONTttOLLE -
RAND EMBEDDED SYSTEMS
ll"four-1tep sequence and number of teeth on rotor
l1'! ,witrhnigS<-qi1t·n« ,ho"n earlier m Table 17-3 is called the 4-step switching sequence since after four. steps the
f11Jt tw<' ,.,nJ,ng,, will I:,(' "ON" How much movement is associated with these four s teps? After cornpletmg eve~
1,,Jtll'J'S• th~ rotor mo,"" only one tooth pitch Therefore in a stepper motor with 200 steps per revolution, the r~t~
,a,!011'\'lh ,mce 4 "50 ~ 200 steps are needed ; 0 complet~ one revolution. Titis leads to the conclusion that the miru·
'IIJJft •tcp an19e 1s always a function of the number of teeth on the rotor. In other words, the smaller the step angle, the
p-1tltl'lh the rotor pas..<1."1. See Example 17-2.
l,.10\Jngat Exa~ple 17·2,one might wonder what happens if we want tomove45 degrees, since the steps are 2 degrees
...i, To allow for finer resolutions, all stepper motors allow what is called an B·slep switching sequence. The 8-step
~ ,s also called lralf-steppillg, since in the 8-step sequence each step is half of the normal s tep angle. For example, a
,....-with a 2-degrce step angle can be used as a 1-degree step angle if the sequence of Table 17·5 is applied.

(Uttlplt 17-2
Wnte • program to rot,,te a motor 64° in the clockwise direction. The motor has a step angle of 2°. Use the 4-step
s,equence in Table 17-3

Solution:

Amotor with a 2° step angle has the following characteristics:


5'ep angle, 2°
S4eps per revolution: 180
:>lo. of rotor teeth: 45
\lovement per 4-step sequence: s•
To move the rotor 64°, we have to send eight consecutive 4-step sequences, i.e., 32 steps.

ORG OOOOH
MOV A,lt66H
MOV R0,#32
BACK: RR A
MOV Pl,A
ACALL DELAY
DJNZ RO,BACK
END

~e 17-5: Half-Step 8-Step Sequence


~ Step II Winding A Windjng B WindingC WindingD Counter..
I 1 0 0 Clockwise
1
2 l 0 0 0
3 1 1 0 0
4 0 I
0 0
5 0 l I
0 0
6 0 1
7 0 0
0 1 1
8 0 0
, ......_ 0 I

l!o-roR CONTROL: RELAY, PWM, DC, AND STEPPER MOTO RS


435
, Winding D Counter.
/
Table 17-6: Wave D rive 4-Step Sequen:ding 8 WindingC
0 Clockwise
0
0
0
0
2 0 1
3 0 0 1
0
I 4 0 0

Motor speed , f the switching rate. Notice in Example 17-t


, /s) is a function o .
The motor speed measured in steps per second (steps achi'.eve various rotation sp s.
eed
. d eIay loop, we can
that by changing the 'length of the time

Holding torque haft at standstill or zero rpm condition, the


, uowtng
· is a definition of holding torque: "W'th
1 the motor
th hs ft from its holding . . Th'1s ·is meas=.,..
pos1bon. ,...,.,,
The ,o .red break away es a )
amount of torque, from anextemal source, requi 10 "The unit of torque is ounce-inch (or kg-cm .
' with rated voltage and current applied to the motor.

Wave drive 4-step sequence .


d' ssed earlier there is another sequence called the wave drive
In addition to the 8-step a_nd the 4-step sequ.ences tSCU se u~nce of Table 17·5 is simply the combination of
I
4-step sequence. 11,s shown m Table 17-6. Notice that the 8-s ep . qT bl • and 17-3 respectively. Experimenting

-
the wave drive 4-step and normal 4-step normal sequences shown 111 a es 17 6 '
with the wave drive 4-step is left to the reader.
rptr 17
• Unipolar versus bipolar stepper motor interface
There are three common types of stepper motor interfacing: universal, unipolar, and bipolar. They can be identified
by the number of connections to the motor. A universal stepper motor has eight, while the unipolar has six and the bipo-
lar has four. The universal stepper motor can be configured for all three modes, while the unipolar can be either unipo-
lar or bipolar. Obviously the bipolar carmot be configured for universal nor unipolar mode. Table 17-7 shows selected
stepper motor characteristics. Figure 17-10 shows the basic internal connections of all three type of configurations.
Unipola~ stepper ~oto~ c~ be controlled using the basic interfacing shown in Figure 17-11, whereas the bipolar
stepper requires H-Bndge circuitry. Bipolar stepper motors require a higher operational current than the unipolar· the
advantage of this is a higher holding torque. '

Tab le 17-7: Selected Stepper Motors Ch aracteristics (www.Jameco .com)


Part No. Step Angle Drive System Volts
151861CP 7.5 unipolar 5v Phase Resistance Current
t71601CP 3.6 9ohms S50mA
unipolar 7V
l640S6CP 7.5 bipolar 20ohms 350mA
sv
6rnA SOOmA

~o 30 :;
(Q)
.:]F')F') '

m
(a) Universal

Figure 17·10. Common Sl•ppor Motor Type,


Cb) Unipolar ~
(c) Bipolar

Tli!: 8051
l'.tlCJtoco -
Nl'ROLLER. AND EMllEDDED SYSTDIS
+V Motor

4 7l
fl Pl cf
IN 1001
A

..... ~+-C> B

To Stepper

..
1111d
Motor

Use11P120
OarUngton transistor if COM
the motor needs
several amps. COM

figurt 1?•11. U$ing Tra.nsi_stors for Stepper Motor Driver

Using transistors as d rivers


Figure 17-11 shows an interface to a unipolar stepper motor using transistors. Diodes are used to reduce the back
E.\IF spike created when the coils are energized and de-energized, similar to the electromechanical relays discussed
earlier. TIP transistors can be used to supply higher current to the motor. Table 17-8 shows the co,nmon industrial
O.riing1on transistors. These transistors can accommodate higher voltages and currents.

Controlling stepper motor via optoisolator

--
I
1n the first section of this chapter we ei.amined the optoisolator and its use. Optoisolators are widely used to isolate the
~per motor's EMF voltage and keep ii from damagmg the digital/ microcontToller system. This is shov.11 in Figure 17-12.

-
I
Table 1 7-8: Darlington Transistor Listing
-•
I

-
NPN PNP Vceo (volts) k(amps) hfe <comm o n)
nrno TIPIIS 60 2 1000
TIPIII TfPl16 80 2 1000
TIPl 12 TIPl17 100 2 1000
TIP120 TIP125 60 5 1000
TIP121 TIP126 80 5 1000
TJP122 TIPl27 100 5 1000
TIP140 TIP145 60 10 1000
TIP141 TIP146 80 10 1000
TIPl42 TIP147 100

-
10 I000
.,
- lltOTOR CONTROL: RELAY, pWM, DC, AND ST EPPER MOTORS
43'7
,
+12

+5
- +~2
]I uLN2803
rupo ar
Stepper Motor
470 470 ,10 ,10 n..Q74

8051 I
2
Oplo
16
ll Jk .
V --:-
PI.O •• •
,r• !.l lk - --
Pl.1
Pl.2
5
12
ll,!; lk .• -
-


' Pl.3
1 :t_ lk
9
- L..
, 1111 '111 I


11,e optoisolotor provides =
additional prolection of the Use one power supply for
••. 8051.
the motor and ULN2003
• and another for the 8051 .
' --
+12

Figure 17•12. Controlling Stepper Motor via Optoisolator
J

Example 17·3
A switch is connected to pin P2.7. Write a program to monitor the s tatus of SW and perform the following:
(a) U SW = 0, the stepper motor moves clockwise.
(b) lf SW= I, the stepper motor moves counterclockwise.
Ill
Solution:

ORG OH ;starting address


MAIN: SETB P2. 7 ;make an input
MOV A, #66H ;starting phase value
MCV Pl, A :send value to port
TURN:
JNB P2.7, cw ;check switch result
RR A ,rotate right
ACALL DELAY ;call delay

-
MOV Pl,A ;write value to PQrt
SJMP TURN ;repeat
CW, RL A ;rotate left
ACALL DELAY ;call delay
MOV Pl,A ;write va1ue to port
SJMP TURN ;repeat ti.iii
DELAY,
HOV
1l
R2, #100 'ii):
Hl: MOV R3. #2S5
H2, OJNZ R3, H2
DJNZ R2,Hl
R!T
END
KtfertOflSUrt' 17-12
JIDUI~ the ~t<'pper motor continuously
(1) Cfod.w1w u•mg the wave drive 4-step sequence
~) Ou.;kwl>O! u.tng the half-step 8-step sequence.
Lie the ~uen,e values saved m program ROM locations.

Solution:

tll For this case, the sequence values are saved in ROM locations starting from 0100H.
ORG OOOOH
START: MOV RO, #04
MOV DPTR,#OlOOH
l!PT: CLR A
MOVC A,lilA+DPTR
HOV PI,A
ACALL DELAY
INC DPTR
DJNZ RO,RPT
SJMP START
ORG 0100H ;sequence values saved in program ROM
DB 8.4,2:,l
END

fZ) For this case, the sequence values are saved in ROM locatioris starting from 0200H.

ORG OOOOH
START: HOV RO,j08
HOV DPTR,#0200H
RP!: CLR A
MOVC A,eA+DPTR
MOV Pl,A
ACALL DELAY
INC DPTR
DJNZ RO,RPT
SJMP START
ORG 0200H
DB 09,08,0CH,04,06,02,03,01
END

Stepper motor control with 8051 C


The 8051 C version of the stepper motor control is given below. ln this program we uld h , d .
ollld>> (shift right) as was shown in Chapter 7. co a, e use << (sh.ift left)
#include <regSl.h>
Void main()
{
while(l)
{
Pl• Ox66;
MSDelay(lOO);
Pl• OxCC;

439
MSDelayllOO);
Pl• Ox99;
MSDelay(lOO);
Pl = Ox33;
MSDe layllOO); .
,. •
I
I p
...
.,• . J,l~'

I ~
onitor the status o 1J11
• A ,w,tch 1s connected to pin P2.7. Write a C program to m
111

(a) 1r SW= 0. the stepper motor moves dockw,se. .
(b) lf SW = l, the stepper motor moves co1mtcrclockw1se•
,....

I, I"re r
• Solution: 'iii, l
l
••
#include <reg.h> -,J:d'
sbit SW• P2""7;
void main()
-.:111'
{ ,!~

'•
• SW s

while {1)
{
l; ~~II

:,l!!lt I
1f{SW == 0) ,:l!lll1
{ ,jl!l lh
Pl . Ox66; 1Jlat,
MSDelay ( 100);
1iltd I
Pl• OxCC;
MSDelay(lOO); lb rt
Pl= Ox99;
MSDelay(lOO);
Pl• Ox33; lidlr
MSDelay{lOO);
~
J '!fl(
else
{ ~r
Pl • Ox66;
MSDelay{lOO);
Pl• Ox33;
MSDelay (lOO);

- Pl• Ox99·•
MSDelay( l OO)i
Pl• OxCC;
MSDelay(lOO);

l
)
void MSDelay(unsigned int value)
I
unsigned ,nt x. y;
forlx•O;x<127S;x,+t
for <y•O;y<value,y,+);
l

- llil! 80S1 MIQt


ocoNTRott -
ER AND EMBEDDED SYSTEMS
jwvltW aucatlon,
!he 4 t I' ,;equ,nc. p( a It. rp<·r molt•r ,t we• ,earl with 0110.
A.i'l'f"'' motor" uh a &lcp angl,• of 5 J,1;r«" h,» _ ,t<>p, per revolution.
i'1'y do we I J 1• •·r l1<,fween lh m1unn1n1roll,•r ,1nJ th<> ,tepper motor>

secnoN 17.3: DC MOTOR INTERFACING AND PWM


• d ,sc:-ribe how lo interfuce ,1
~ se<"llnn t.. i;111, with an ""'"' "'"' of th,· l, ,sic on.•r,itinn of OC motor,. Then "c '· f ' dth
' ' - t ti
,,01,,r 111 the l!ll'll I 1n.11l), "e use As.,.,mbly and C language progr,,ms tn demonstra e 1e cone ept o pu 1se w1
J u11nn (Pl'IIMJ and ,h,,w ht>w to control th,• 'l"-""l and dir('(tinn of a DC motor.

Ad1n'C1 currl.'nl (DC) motor~ another widely used d,•vice that tr,,nslatcs e l('(trical pulses into mech11nical ~,ove-
:n,111 In the OC motor we have onl) + and_ leads. Connectmg them to a DC voltage source mov~s the motor LO o_ne
,i,«IIOll 81· re,ersing the polarity, the DC motor will move ,n the opposite direction. One can easily exp('nment with
!ht DC motor For ,•xample, small fans ust.-d ,n manv molherhoards to cool the CPU are run by DC motors. By con-
.«lil1g their leads to the+ and -voltage source, the DC motor moves While a stepper mo_t~r moves in st~ps of 1 to 15
J,glre,, thc DC motor mo\'es continuously. In a stepper motor, 1f we know the starting position we can easily count the
3'111berof steps the motor has moved and c,1 lculate the final pos1tlon of the motor. TI1is is not possible in a DC motor.
lbtmaxinium spe.>d of a OC motor 1s indicated in rpm and 1s f;iven 111 the data sheet. The OC motor has two rpms: no-
loldand looded The manufacturer's data sheet gives the no-load rpm. The no-load rpm can be from a few thousand to
1a1>11f thousand~. The rpm is reduced when moving a lood and it decreases as the load 1s increased. For example, a drill
lll!IW1g a screw has a much lower rpm speed than when ii is in the no-load situation. OC motors also have voltage and
(llm,nt ratings. The nominal voltage is the voltage for that motor under normal conditions, and can be from I to 150V,
drp<nd1ng on the motor. As we increase the voltage, the rpm goes up. The current rating is the current consumption
•hffl the nom,nal voltage is applied with no load, and can be from 25mA to a few amp<. As the load increases, the rpm
1d!m>a~. unles.s the current or voltage provided to the motor ,s increased, which in turn increases the torque. W ith
16\ed ,·oltage, as the load mcrea!>es, the current (p0wer) consumption of a DC motor is increased. If we overload the
mot,,r 11 will stall, and thot can damage the motor due to the heal generated by high current consumption.

Unidirection Control
Figure 17-13 shows the DC motor rotation for clock-
•11t (GV) and counterclockwise (CCW) rotations. ~
Tobie 17-9 for selected DC motors. .,...--,
MOTOR +
Bidirectional control +
With the help of relay, or some specially d,-;igncd
dtips we can chang~ the dtrection of the DC motnr rol•·
lion. Figun'S 17-14 lhrough 17- 17 show the bas1Cconccpts Clockwise
"'H·Brid1,1e control"' DC motors. Counter-
Rotation
Figuri, 17-14 show, the connection of an H-Bndge Clockwtse
Rotation
IISlng simple switches. All the switches ,,re open, which
clces not allow the motor to tum
Figur, 17-13. DC Motor Rot.ition (Ptrmanent Magnet f ield)

:able 17-9: Selected DC Motor Characteristics (wwv,.Jameco.com)


•rt No. Nominal Volts Voll Range Current
~SCP 3V 1 5-JV RPM Torque

llJ.8 g-crn

R CONTROL: RELAY, PWM, DC, ANO STEPPER MOTORS


441
Figure 17-15 shows the switch configuration for turning the rnotor in one direction. When switches t and

,_,, rorrm<i,aUow.J
Figure pa• '""'""
17-16 shows the" switch "" •"''·
configuration for turning the motor .U'I the opposite
, direction
. . from the confi 4 '"
of""" .,.,s. '""" ~•-'""' 3•• """"' ro""'' 0 ' "'""' " P'" Uuo• gh <h< ~ oro,. ""' ""
Figure 17-17 shows an invaUd configuration. Current flows directly to ground, creating a short circuit. Th
effect occurs when switches 1 and 3 are closed or switches 2 and 4 are dosed, e same
Table 17-10 shows some of the logic configurations for the H-Bridge design,
.
•• +V
+V
l


urrent
• SWITCH
SWITCH Flow 2
SWITCH SWITCH I
2
.•
•• I
M
M
I
SWITCH
• SWITCH
SWITCH SWITCH 3 4
3 4

I
• MOTOR NOT C LOCKWISE
• RUNNING - oatEcnON

Figure 17-14. H-Bridge Motor Configuration Figure 17-15. H-Bridge Motor Clockwise Configuration
.

+V
tY
! i
-

SWITCH Current
Plow
SWITCH SWITCH
1 SWITCH

- SWITCH
3
M
2

SWITCH
1

SWITCH
~
/
M - h
2

4
3 SWITCH
4

! ,., ---.J
- -
COUNTER
_ CLOCKWJSI!
DIRl!CT!ON

Figure 17-16. H -8 n'dgo Motor Co unten:lockwise Con•. .


·-,,;ur•tion .
_,_+ INVALID
I(SHORT STATE
C [R
able 17-10: So . Figure 17-11 H . CUTT)
T me H-Brid · · Bn dge i
Motor Operation ge Logic Confj n a.n inval id Confi
.
Off SWt gu.Tafions for F' guratton
SWz agure 17-14
Open Open $"\,\'3 $"\,\'4
Clockw·
Closed Open Open Open
Counler Clockwise
Open Cl~ Open
Invalid Closed
Closed ClOSed Closed Open
ClOSed Closed.
nt1: sos1 Mlca
OCON'fRottER AND -
EMBEDDED SYSTEMS
..-ipi, 17•5 . to monitor the status of SW and perform
A twitch" cvnnt'Ctl'd to ptn 1'2.7. Using a simulator, " rote a program
tht following
1, 1uS\\/ • O. the OC motor moves clockwise . ...-
!bl If SW ., I, the OC motor moves counterclockwise.

5olutio'

ORG OH
MAIN :
CLR Pl.O \ ;switch l
CLR Pl.l ; switc h 2
CLR Pl.2 ;switch 3
CLR P:i.J ;switch 4
SETB P2.7
i«>!l!TOR :
JNBP2. 7 ~- CLQCICWISE
SETB . Pl. fl ; switch l
CLR
CLR
Pl . l
i>1.2 L
;switch
;Switch
2
3
.
SE:TB -Pl . J
SJMP MONITOR
;switch 4

CLOCKWISE::
CLR Pl.O ;switch 1
SETB Pl.l ;switch 2
SE:TB Pl.2 ;switch 3
CLR Pl.3 ;switch 4 r
SJMP MONITOR
END
/ I
View the results on your simulator. This example is for simulation only and should not be
H used on a connected system.

H-Bridge control can be created using relays. transistors, or a single IC solution such as the l.293. When using relays
111d transistors you must ensure that invalid configurations do not occur.
Although :.-e
basic H-Bridge.
do not show the relay control of an H-Bridge, Example 17-5 shows a simple program to operate a
.. . . .
See www.MicroDigitalEd.com for adclitional tnformation on us mg H·Bridges.
Figure 17-18 shows the connection of the L293 to •.n 8051. Be aware that the L293 will generate heat during opera.
lion. For sus tained operation of the motor, use• heat sink. Example 17-6 shows control of the l.293.

Pulse width modulation (PWM)


The Speed of the motor depen~ on three factors: (a) load,~) voltage, and (c) current. For a given fixed load we
Cl~ maintain a steady speed by usmg • method called pulse w1dtl, mod11/atio11 (PWM). By changing (modulating) the
><idth of the pulse applied to. the DC motor we can m.crease or decrease the amount of power provided to the motor,
thereby lnaeasing or decreasing th~ motor speed. Noac~ that, a lthough the voltage has a fixed amplitude, it has a Vari-
., '°'• duty cycle. That means the wider the pulse, the higher the Speed. PWM is so widely used in DC motor control

(I !.totOR CONTROL: RELAY, PWM, DC, ANO STEPPER MOTORS


, . In such microcontrollcrs all we hav
. . embedded in t~e ch•r;he desired pulse, and the_ rest IS lake~
11 me with the PW1"1 c,rcu•try hand Jow portions° For microcontrollcrs without PWM
that !.Orne microcontro crs_~~crs with the ,,aJues of the h1gUer to do other things. ents the microcontroller from doing
todo is load ~e proper r~t;i This allows the microcontro software, which prev
care by the nucrocontro er. . d ty cycle pulses using
. u1try, we mu;,t create the vanous u
arc

/ +t2V
.
I +S
+12 V
-~
.
16 8 ~rf!D

410 :'7 410 ILQ74 +12 VCCI VCC2 ~\'
• 8051 I
-;:
Opto L293
01 ~ 02
'
f"fi
Pl.O lh I ENABLE
3 lk 2 1NrUT I OUTrUT I
3 'MI ,.i,.tl
Hfl
••
Pl.I • Jk 7 OIJTl'IJT ?
6 D3 04 ..fl''·
Pl.2
6
5
t
u lk
lNPUT 2
GND
"Fir
• ~1

*
4,5, 12, 13
j,11 ol
The optoisol.itor provides use uSC'pMate power fig'
i'ldditional protection of the supply for the motor and "£ D1. 02, 03, D4
8051 ftcplC
L293 than for the 8051 are 1N4004
i~sh·
, lit I
Figure 17-18. Bidirectional Motor Control Using •n L293 Chi P fig-
~,ltf

E~e17·6

- Figure i 7-18 shows the collnect1on of an L293. Add a switch to pin P2.7. Write a program to monitor the status of
?' and perform the following:
• (j)rll SW= 0, the DC motor moves clockwise.
/(b) If SW= 1, the OC motor move; counterclockwise.

vlution:
/ ORG OH
/MAJN:
CLR Pl. 0
CLR Pl.l
CLR Pl.2
SETB P2.7
MONITOR:
SETB Pl.O ;enable the chip
JNB P2. 7, CLOCKWISE
Cl.R Pl .1
SBTB ;turn the motor count
Pl.2 erclockw1se
SJMP MONITOR
CLOCKWISE:
SETS Pl.l
C'LR Pl. 2
;turn motor Clock .
SJMP MONITOR wise
END

i
(Ill<'' things, _The ability to control the speed of the
oC ,notor u~mg P~VM ts one reason that IX motors
,rr preferable over AC motors. AC motor speed is 'A l'O~VER 25% DC
Ji.tatc-d by the AC fr<'qucncy of the voltage applied
the n,otor and the frequency is <>cnerallv fixed A ~ POWER 50% DC
10 I <> , . s
,result, wecam1ot contro the speed of the AC motor ~ POWER 75% DC
.hell the toad is increased. As was shown earlier, we
,,nJlso ch,1nge the IX motor's di rection and torque. FUI..L l'OWER JOO~• 0C
~Figure 17-19 for PWM con1parisons.

figure 17-19. Pulse Width Modulation Com parison

oc motor control w ith optoisolator


As we discussed in the fi rst section of this chapter, the optoisolator is indispensable in many motor control applica-
bOI\S. Figures 17-20 and 17-21 show the connections to a simple DC motor using a bipolar and a MOSFET tranststor.
Notire that the 8051 is protected from EMl created by motor brushes by using an optoisolator and a separate power
lllpply.
figures 17·20 and 17-21 show optoisolators for control of sing.l e directional n1otor control, and the same principle
stiould be used for most motor applications. Separating the power supplies of the motor and logic will reduce the posi·
bi1il)' of damage to the control circuity.
Figure 17-20 shows the connection of a bipolar transistor to a motor. Protection of the con trol ci rcui t is p rovided by
lhe optoisolator. The motor and 8051 use separate power supplies. The separation of power supplies also allows the use
of high-voltage motors. Notice that we use a decoupling capacitor across the motor; th.is helps red uce the EMI c reated
bylhe motor. The motor is switched on by clearing bit Pl.O.
Figure 17-21 shows the connection o f a MOSFET transistor. The optoiso-lator protects the 8051 from EMl. The zener
d,ode is required for the transistor to reduce ga te voltage below the rated maximum value.

f
+12V

1N400-I O.l uF MOTOR

+SV
ILD74
330 OPTOISOLATOR
8051
I 8 10 k
TlP1 20

2 7
Pl.O +12V
t()()k
6

5
-

figurt 17-ZO. DC Motor conn«tlon lding a Darlington Transistor

-
- ~<>Toa CONTROL: RELAY, pWM, DC. AND STEPPER MOTORS
,
+12V

MOTOR
JN4004
:•
+5V
ILD74
8051 330 OPTOJS0l.ATOR G D !RF521

• 1 ~8~___.Jl~Ok~~r-...=.,'.s~
2 7 !OOk 6.2V Zene
Pl.O L - -- ~f--' L-j-'-- - i +12V

Diode
3 6

• 5

Figure 17·21. DC Motor Connection using a MOSFET Transistor

Example 17•7
Refer to the DC motor connection of Figure 17-20. To the 8051 of this figure, a switch SW is connected to pin 3.2,
which is the INTO pin.
Write a program
(a) normally the motor runs with a 33% duty cycle
(b) when INTO is activated, the motor runs with 10% duty cycle for a short duration.

Solution:

;-upon wake up, avoid using the space allocated to interrupt vector table

ORG 0000
LJ'MP MAIN

;;- - - -the !SR for interrupt INTO

ORG 0003R
SJMP PIRST

;-main program for initialization

ORG 0030H
MAIN: MOY IE.#Blll ;enable INT 0
HERE: Sl!TB Pl. O
MOV RO, #33
ACALL DELI>.¥
;Pl.o aet for 331 time
CLR Pl. O
HOV RO, #67
;Pl.O cleared f
ACALL DBLAY or 671 t ime
SJMp HERB


' . .
. . ··'
TliE 8051 r.tl
CRocoNlROLL -
ER AND EMBEDDED SYSTEMS
,,..
._this is the !SR for INT O

r1RST: MOV RS• #OFFH ; this is to create a delay
rf!ERE: SETB Pl . 0
MOV R0,#10 ; p 1.0 set for 10 t time
ACALL DELAY
CLR Pl . 0
MOV RO, #90 ; p 1. 0 c l eared for 90t time
ACALL DELAY
OJNZ RS,THERE ; exit from lSR when R5s0
RETI

·-6ubrouline named DELAY


'
osLAY,
RPTl: MOV Rl, # 20
FP1'2: MOV R2,#100
RPT3 : DJNZ R2,RPT3
OJNZ Rl,RPT2
DJNZ RO, RPTl
RET
END

In trus to ma ke the moto r to run continuously at l<Wo d uty eye.le, it is necessary to keep the switch pressed. Once
the switch is released, the ISR is run for a time period corresponding to the delay decid ed by the value of the
number in RO. Aher this delay, control re turns to the main program.

See the www.MlcroDlgltalEd.com Web alte for


addit ional Information on motor control.

DC motor control and PWM using C


Examples 17-8 thro ugh 17-10 show the 8051 C v ersion o f the ea rlier programs controlling the DC motor.

Exmlple 17-8
~ to figure 17-18 for connecti011 of the motor. A , witch i s ~ to pin P2.7. Write a C program to mcnitor
lht sutus of SW and pet fc-111 the following:
11) USW "' o. the DC motor mows clodr;wile.
lb! lfSW e 1, the DC motor IJIO\Wa,untffl:Jockwi.

Solation:
l!nc lude creg51 , b >
•bit SW • n •11
6
•bit IX.UL&• Pl 0 1
•bi t MTR 1 • p1•1 1
abi t NTll- 2 • Pl•a,
-
~Ol'Oll CONTROL: U LAY, pWr.t, DC AND S I EPPEll MOTORS
, /
void ""'ln fl
{
SW• l;
ENABLE• 0;
MTP_l • 0:
MTR_2 • Di
I
• while (1)
{
ENABLE• l;
if(SW • • l)
I
MTR_O = l;
MTR l ~ O;
•• l
else
•• {
MTR_O • O;
• MTR_l • l;
I
f }
l
I

E,c,lm ple 17·9

Reter to the figure in this example Write,, C program to monitor the status of SW and perform the following:
Ca) lfSV.1 = 0, the DC motor mo,es with 50% duty cycle pulse.
(b) If SW= I, the OC motor move,, with 25% duty cycle pulse.

Solution:

#include <regSl.h>
sbi t SW • P2•7;
sbit MTR• P1•0;
void MSDelay(unsigned int value);
vold main()
-
{
SW • l;
MTR • O;
while(!)
(
if(SW •• l)
(

'
MTR ,. 1;
MS0elay(25I;
MTR• O;
MS0elay(7S);
I
elee
{

TH Esos1 MICRQc -
ONTROtt
ER AND EMBEDOl!D 5\'STD4S
MTR • l;
MSDelay(SO);
MTR • O;
MSDelay(SO);
l
}
)
void MSDelay(unsigned int value)
{
unsigned char x, y;
for(x=O; x<l275; x++
for(yeO; Y<Value; y++
}

+12V

+5V
IN4004 O.luF MOTOR
4.71<
+SV
llD74
3-10 OPTOISOLATOR
P2.7 8 IOk Tll'l20
8051 ..,.,..
2 7
P1 .0 1 - - -- ---=!_J +12V
JO(lk
3 6

5
-

Eu mple 17-10
Refer to Figure 17-20 for connection to the 1notor. Two switches arc eonne<:tcd to pins P2.0 a11d P2.l. \.Vritc a C
program to monitor the status of both switches and perform the follow,ng:
SW2(P2.7) SWl (P2.6)
0 0 OC motor move~ slowly (25°'., duty cycle)
0 1 OC motor movei. moderately (50"/o duly cycle).
I 0 OC motor moves fast (75°/o duly cycle).
1 1 DC motor moves very fast (HXl"'u duty cycle).
.
Solution:

•include <regSl.h>
•bit MTR • Pl AO;
void MSDelay(unaigned int val ue);

t.toro1 CONTROL: REI.A Y, l'WM, DC, AND STEPPER MOTORS


void maiD O
{
unsigned c:har z;
P2 • OxFF;
z • P2:
2 • z t.. Ox03;
MTR• 0;
while ( l)
(
ewitc:h(z)
(
c:ase(O):
{
..• MTR • l;
MSDelay(25);
• ~SI
MTR= 0;
' MSDelay(75);
j(IIO:
break;
• } can
case(l):
{ : Holl
MTR = l; l Gi\"E
MSDelay(SO); t 1110
MTR= 0; : fll\d
MSDelay (50); I Gil1
break; ' GiVE
}
! Ofd
case (2) :
{ • TlllE
MTR = l; l Tllll
MS0elay (75);
MTR= O; Ki!O
MS0elay(2S ) ;
break; l Ua
} t Cale
default:
MTR • l;
aFor
) 'In F
} ,i F'aii
t Fini
• Wh
mo
l lY!,

~~
Review Questions l 1n1

1. True or false. The permanent magnet field DC motor has only two leads for + d _
2. True or false. ]U$l like a stepper motor, one can control the exact angle of a Dean t v?Itages.
3. Why do we put a driver between the mkrocontroller and the DC motor' mo ors move.
4. How do we change a DC motor's rotation direction? ·
5. What is stall in a DC motor?
6. True or false. PWM allows the contTol of a DC motor With the sa
7. The RPM rating given for the DC motor is for (no loarndclphase, but different amplitude pulses.
• ' Daded).
450
T!iE 8051 MICRoe -
ONTROLLER ANO EMBEDDED SYSTEMS
suMMARY
This chapter continued showing how to inte rface the 8051 with real-world devices. Devices covered in this chapter
,,-e~ the relay, optoisolat?r, stepper motor, and DC motor. . . . con·
first, the basic operation of relays and optoisolators was defined along with key terms used in descnbing and .
lfOJUng _their oper~tions. Then the 8051 was interfaced with a steppe; motor. The stepper motor was then controUed via
in optmsolator using 805~ Assembly and c programming languages. .
fU1all~, the 80~1 was mterfaced with DC motors. A typical DC motor will take electronic pulses and convert the~
mecharucal motion. This chapter showed how to interface the 8051 with a DC motor. Then, sunple Assembly and
10
programs were written to show the concept of PWM.
Control systems that require motors must be evaluated for the type of motor needed. For ex~ple'. you would not
want to ll;se a s~epper m a high-velocity application nor a DC motor for a low-speed, high-torque situation. The stepper
motor IS ideal ,nan open-loop positional system and a DC motor is better for a high-speed conv~yer beH application.
I)( motors can be modified to operate in a closed-loop system by adding a shaft encoder, then using a rrucrocontroller
to monitor the exact position and velocity of the motor.

PROBLEMS
sEcnON 17.1: RELAYS AND OPTOISOLATORS
1. Can a relay have nom,ally open (NO) as well as normaUy closed (NC) contacts?
2. How does a reed switch work?
3 Give the advantages of a solid-state relay over an EM relay.
4. ln circuits with relays and microcontrollers, why are driver !Cs used?
5. Find the current needed to energize a relay if the coil resistance is 1200 ohms and the coil voltage is 5 V.
6. Give two applications for an optoisolator.
7 Give the advantages of an optoisolator over an EM relay.
8. Of the EM relay and solid-state relay, which has the problem of back EMF?
9. True or false. The greater the coil resistance, the worse the back EMF voltage.
10. True or false. We should use the same voltage sources for both the coil voltage and contact voltage.

SEcnON 17.2: STEPPER MOTOR INTERFACING


11. If a motor takes 90 steps to make one con1ple1e revolution, what is the step angle for this motor?
12. Calculate the number of steps per revolution for a step angle of 7.5 degrees.
13. For what kinds of applications are stepper motors popular?
It In Figure 17-11, is it mandatory to use transistors in the Darlington configuration?
15. Finish the normal four-step sequence counterclockwise if the first step is 1001 (binary).
16. Finish the normal four-step sequence counterclockwise if the first step is 0110 (binary).
17. What is the purpose of the ULN2003 placed between the 8051 and the stepper motor? Can we use that for 3A
motors?
18. Which of the following cannot be a sequence in the normal 4-step sequence for a stepper motor?
(a) CCH (b) DOH (c) 99H (d) 33H
19. What is the effect of a time delay between issuing each step?
20. ln Figure 17-11, why are diodes used?

SECTION 17.3: DC MOTOR INTERFACING AND PWM


21. Which motor is best for moving a wheel exactly 90 degrees?
22. What is the relationship between the load, torque, and current of a DC motor?
23. True or false. The rpm of a DC motor is the 5an1e for no-load and loaded.
24 The rpm given in data sheets is for (no-load, loaded).
25. What is the advantage of DC motors over AC motors?
26. What is the advantage of stepper motors over DC motors?
27. True or false. Higher load on a DC motor slows it down if the current and voltage supplied to the motor are fixed.
28. How can a microcontroller be used to control automatically the speed of a OC motor?

'->tua COl\rTROL: RELAY, l'WM, DC, AND STEPPER MOTORS 451


· p\.\lM cifcuitry. d LI microcontroller?
29. N~me two microcontroUcrs w_ith in-built . tor between the motor an ,e
15
_ What ,s the advantage of placing an opto ola
30

ANSWERS TO REVIEW QUESTIONS


SECTION 17.1: RELAYS ANDOPTOISOLATORS • ch as horns a nd appliances.
y.120Vdev1cessu ' .
1 \\lith a relay we can use a 5 V dig1tnl system to contro112 gize the relay, we need a dnver.
~
• . k ffi . t current to cner
2- Since microcontroller/ digital outputs lac su cien
3. \.\'hen the coil is not energized, the contact is closed. d ou.nd the coil, which causes the armature to be
4. When current Oows through the coil, a magnetic field is create ar
attracted to the coil.
• 5. It is faster and needs less current to get en~rgized. . without a driver.
• 6. It IS smaller and can be connected to the microcontroller d,rectly

•• SECTION 17.2: STEPPER MOTOR INTERFAClNG



• I. OllO. 0011, 1001, 1100 £or clockwise; and 0110, 1100, 1001, 0011 for counterclockwise

•• 2. 72
3. Because the microcoi,troller pins do not provide sufficiei,t current to drive the stepper n1otor

SECTION 17.3: DC MOTOR INTERFAONG AND PWM


I. True
2. False
3. Since mic~ocontrollerI digital outputs lack sufficient current to drive the DC motor, we need a driver.
4. By reversing th<' polarity of voltages connected to the leads
5. The DC motor is staJJed if the load is beyond what it can handle
6. False
7. No-load

452
lliE aos1 M1caoco..,..,...
·• '"OLLl!ll
AND EMBEDDED s'YSffMS
APPENDIX A

8051 INSTRUCTIONS,
TIMING, AND REGISTERS

OVERVIEW

(n the first section of this appendix, we describe the instructions of the 8051 and give their formats
with some examples. 1n many cases, more detailed programming examples wiU be given to clarify thae
instructions. These instructions will operate on any 8031, 8032, 8051, or 8052 microcontroller. The first
section concludes with a list of machine cycles (clock counts) for e.ich 8051 instruction.
In the second section, a list of all the 8051 registers is provided for case of referell<:e for the 8051
programmer.

453
SECTION A.1: THE 8051 INSTRUCTION SET

~A~C~A~L~L~t~a~rg~e!t~a~dd~r~e!s~s~~~~~~~~~~~~~~~~~~~~~~~~~~---
Function: Absolute Call • l'
,,
Flags: None . 'th target address with.in 2K bytes from the current
3
ACALL stands for "absolute call." II calls subrouttnes WI
i program counter (PC). See LCALL for more discussion on this.

ADD A,source byte


• Function: ADD
Flags: OV, AC, CY
..

This adds the source byte to the accumulator (A), and places the result in A. Since register A is one byte in size, the
I source operands must also be one byte.
The ADD instruction is used for both signed and unsigned numbers. Each one is discussed separately.

J
I
.c: re
Unsigned addition

JS
addition of unsigned numbers, the status of CY, AC, and OV may cha!lge. The most important of these flags
• t becomes I when there is a carry from 07 out in 8-bit (DO - D7) operations. w
I •

Example:
MOY A,#45H 1A=45H
ADD A,#4FH ;A=94H (4SH+4FH• 94H)
;CY=O,AC=l

Example:
MOY A,#OFEH ;AaFEH
MOY R3,#75H ;R3:r7SH
ADD A,R3 1A=FE+75=73H
;CY=l,AC=l

Example:
MOY A,#2SH ;A=25H
ADD A,#42H ;A=67H (2SH+42H=6?H)
1CY=O ,AC=O
b
~(
Addressing modes
The following addressing modes are supported for the ADD . I
.
1. Immediate: •~ inSITuction: I
=D A, #data Ex
2. RP<>ister:
·o· ADD A, Rn ample: ADD A, #2SH
3. Direct: Example:
ADO A,direct ADO A,R3
Example:
4. Register-indirect: ADD A,@Ri where i•O ADO A,30H .
Examples: =Ro or i•l onl 'add to A d aa1.'nr.•u
t
ADD A. • ' add to A d y = loc. 3 OH
ADD A,@Rl ;add to A data pointed to b
In the foll w· ata PDinted Y RO
RAM localior: 70u;f exadmple, the contents of RAM I , to by R.l
an 71H. ocattons SO!i
to SFJi are added t th
454 oge er, and the 5um 1ssav
· ed m
·

APPENDIX A
CLR A ;A=O
MOV RO,#SOH ;sour ce poin t er
MOV R2,#16 ;counter
MOV R3 ,# 0 ;cl ear R3
ADD A, @RO ;ADD to A from source
JNC B l ; I F CY=O g o t o next byte
INC R3 ;otherwise keep car r i es
B_l : I NC RO ;next l ocati on
DJNZ R2 , A_l ;repeat for all bytes
MOV 70H,A ;save low byte of sum
MOV 71H,R3 ;save high byte of sum
. ~otice in all the ~ove examples that we ignored the status of the OV flag. :""l.tho~gh A DD instructions do affect OV,
it 15 IJ\ the context of signed numbers that the OV flag has any significance. This IS discussed next.

Signed addition and negative numbers


In the addition of signed numbers, special attention should be given to the overflow flag (OV) since this ~dicates
ii there is an error in the result of the addition. There are two rules for setting OV in signed number operation. The
overflow flag is set to 1:
1. U there is a carry from D6 to D7 and no carry from 07 out.
2. U there is a carry from 07 out and no carry from D6 to 07.
Notice that if there is a carry both from 07 out and from D6 to 07, OV = O.

Example:
MOV A,#+8 ;A=OOOO 1000
MOV Rl, #+4 ;Rl=OOOO 0100
ADD A, Rl ;A=OOOO 1100 OV• O,CY=O
Notice that 07 = 0 since the result is positive and OV = 0 since there is neither a carry from 06 to 07 nor any carry
beyond 07. Since OV = 0, the result is correct ((+8) + (+4) = (+U)].

Example:
MOV A, #+66 ;A=OlOO 0010
MOV R4, #+69 ;R4•0100 0101
ADD A,R4 ;A=lOOO 0111 = -121
; (INCORRECT) CY=O, D7=1, OV•l
In the above example, the correct result is +135 [(+66) + (+69) =(+135)), but the result was-121. OV =l is an indica-
tion of this error. Notice that 07 = 1 since the result is negative; OV = 1 since there is a carry from 06 to D7 and CY= o.

Example:
MOV A,#-12 ;A=llll 0100
MOV R3,#+18 ; R3•0001 0010
ADD A, R3 ;A=OOOO 0110 (+6) correct
;D7=0,0Vs0, and CY=l
Notice above that the result is correct (OV = 0), since there is a carry from 06 to 07 and a carry from 07 out.

Example:
MOV A, #-30 ;A=lllO 0010
HOV R0,#+14 •ROsOOOO 1110
•;A•llll 0000 (-16, CORRECT)
ADD A,RO
·D7•l,OV=O, CY•O

OV = 0 since there is no carry from 07 out nor any carry from 06 to 07.

APl>ENorx A
, ¥

.,,
E>-Jmpfe; ("II'
;A•lOOO 0010
MOV A.~·126
MOV R7,#-127 ;R7=1000 0001
WRONG)
{,~
ADD A,R7 ;A•OOOO 0011 (+3, r,i
;D7=0, OV•l i-<,
from D6 to D7.
CY= 1 since there is a c,ury from D7 out but no carry .. . , .
. . . tant in any add1t1on, OV is extremely 1mportant in f<" I
I
From the above di'lCUSSion we condude that while CY is ,mpo~ result is volid. As we will see in instruction •oA
~~
signt>d number addition since it is used to indicate whether or nf. ~ in DIV and MUL instructions as weU. See the
1
,.,.. , the AC flag is us..-d in the ~ddition of BCD numbers. OV ,s a sou
IJ!lll
description of these two instructions for further details.
.~

AD D C A,source byte
... Function: Add with carry
i Flags: OV, AC, CY

This wiU add the source byte to A, in addition to the CY flag (A = A + byte+ CY). If CY = 1 prior to this instruction,
• CY is also 3dded to A. U CY= Oprior to the instruction, source is added to destination plus 0. This is used in multibyte
,1dd1Lions. In the addition of25F2H to 3189H, for example, we use the ADOC instruction a, shown below.
Example:
t
CLR C ;CY=O
MOV A,f!89H ;A=89H
ADDC A,#OF2H ;A•89H+F2H+0=17BH, A=7B, CYal
MOV R3,A ;SAVE A
MOV A,#31H
ADDC A,#25H ;A=31H+25H+l=57H
Therefore the result is:
25P2H
+ 3189H
577BH
The addressing modes· for AODC are the same as for "A DO A.byte".

AJMP target address T


Function; Absolute jump
Flag. None
AJMP stands for "absolute jump" lt tr f
address for this instruction must be .:,ithi a2J<ns bers program execution to th h
n ytes of pr e '" rget add ..
ogram memory. Se<, LJMP, ress uncond1honally. The target
ANL dest-byte,source-byte
,or more disc · .
uss1on o n this.
•I
l
Function. Logical ANO for byte variables
Flamgs: None affocted
Th,s performs a logical ANO on th•
dcstinatJon Nohce that both the source e•nodperands,
dcsti ·bit by bit• storing th A B AANDB
Exampk: nation values are byte-s~ result in the
1ze only.
0
~
0 0
MOV A,#3911 ;As39H 0 1 0
ANL A•• 09H
;A•39H ANDed With 09 1 0 0
456 l 1 1

APPENDIXA
...
39 0011 1 001
09 0000 1001
09 0000 1001

i;xample:
MOV A, #3 2H ;A• 32H 0011 001 0
32
MOV R4 , #50H ;R4e50H 0101 0000
50
ANL A,R4 ; (A•lOH) 0001 0000
10
For the ANL instruction there are a total of six addressing modes. In four of them, the accumulator must be the
destination. They are as follows:

!. Immediate: ANLA,#data Example: ANL A,#25H


2. Register: ANLA,Rn Example: ANL A,R3
3. Direct: ANL A,direct Example: ANL A,30H ;AND A wi t h data i n RAM location JOH
4. Register-indirect: Example: ANL l\ ,@RO ;AND A with data po inted to by RO

1n the next two addressing modes the destination is a direct address (a RAM location or one of the SFR registers)
while the source is either A or immediate data.

;. ANL direct,#data
Example: Assume that RAM location 32H has the value 67H. Find its content after execution of the following code.

ANL 32H , #44H


44H 0100 0 100
67H 011 0 01 11
44H 010 0 0101 Therefore, it has 44H.

Or look at these examples:

ANL Pl , #lllllllOB ;mask Pl.O(DO of Port l )


l\NLPl,#OlllllllB ;mask Pl .7(07 of Port l )
ANL Pl , #1111.0lllB ;mask Pl. 3 (D3 of Port 1)
ANL Pl ,#llllllOOB ;mask Pl . O and Pl . 1

The above instructions clear (mask) certain bits of the output port of Pl.

6. ANL direct,A
Example: Find the contents of register B after the following:

MOV B, #44H ;B• 44H


HOV A,#67H ;As67H
l\NL OFOH,A ;A AND B(B is located at RAM FOH)
;after the operation Bs44H

Note: We cannot use this to mask bits of input ports! For example, "ANL A, Pl" is incorrect!

ANL C,source-bit
Function: Logical AND for bit variable
Rag: CY
In this iNtruction the carry flag bit is ANDed ~th a source bit and the result is placed in carry. Therefore, if source
bu .. o, CY ;8 cleared; QtherWiBe, the CT flag rem11N unchanged.
, P2 2 are both
. bits P2.l and .
high' otherwise, make A = PFH.
'
r the accumulator if
Examp le.· Write code to clea

I MOV A, #OFFH
MOV C,P2.l
;A~FFH . P2.l to car.,
;copy bit
·and then
""nag
10w
ANL C,P2 . 2 '; jump if one of them i s
JNC B_l

• CLR A . 'th the complement of the source bit.


e_1: . of the CY flag bit w1
. . ti n involves the ANDmg
Another variation of this mstru~ ~ . example.
Its format is" ANL C,/bit". See the o owmg A - FFH.
; · make -
. and P2·2 is low; otherwise,
. high

Example: Oear A if P2.l 1s

MOV A, #OFFH
MOV C,P2.l ;get a copy of P2 . 1 bit
of P2.2
ANL C,/P2.2 ·ANO P2.l with complement
'
JNC B l
CLR A
B 1:

CJNE dest-byte,source-byte,target
Function: Compare and jump if not equal
Flag: CY

The magnitudes of the source byte and destination byte are compared. !f they are not equal, it jumps to the target
address.

Example: Keep monitoring Pl indefinitely for the value of 99H. Get out only when Pl has the value 99H.
MOV Pl,OFFH ;make Pl an input port
BACK: MOV A, Pl ; read Pl
CJNE A,#99,BACK :keep monitoring
-
Notice that CJNE jumps only for the not~qual value. To find out if it is greater or Jess after the comparison, we must
check the CY Hag. Notice also that the CJNE instruction affects the CY Hag only, and after the jump to the target address
the carry flag indicates which value is greater, as shown here.
In the following example, Pl is read and compared with value 65. Then:
Dest < Source CY=O
I. !f Pl is equal to 65, the accumulator keeps the result,
2. !f Pl has a value less than 65, R2 has the result, and finally, Dest?. Source CY= 0
3. UPl has a value greater than 65, it is kept by R3.

At the end of the program, A will contain the equal value or R2 th II


Eleampie: ' e sma er value, or R3 the greater value.
MOV A,Pl ;READ Pl
CJNE A, #65,Nl::XT
SJMP ;IS IT 65?
EXIT
NE:XT: JNC OVER ;YES, A KEEPS IT,
;NO EXIT
MOV R2,A
SJMP EXIT ;SAVE THE SMALLE:R
OVER: MOV ;ANO EXIT lN R.2
R3,A
EXIT: ;SAVE THE LARGER
IN R3

458
nus instruction supports four addressing modes. tn two of them, A is the destination.
laUJlediate: CJNE A,#data,target
1. E,camp1e:
CJNE A,#96,NEXT ;JUMP IF A IS NOT 96
2.
Direct 1 C)NE A,direct,target
E,camp e: CJNE A,40H,NEXT ;JUMP IF A NOT~
;WITH THE VALUE HELD BY RAM LOC. 40H

Notice the absence of the"#" sign in the above instruction. This indicates RAM location 40H. Notice in ~s m.o de
that we can test the value at an input port. This is a widely used application of this instruction. See the following:

MOV Pl,IIOFF ;Pl is an input port


MOV A,ttlOO ;A • 100
!!ERE: CJNE A,Pl,HERE ;WAIT HERE TIL Pl; 100

In the third addressing mode, any register, RO • R7, can be the destination.

3. Register: C)NE Rn,#data,target


Example: CJNE RS,#70,NEXT ; jump if RS is not 70

In the fourth addressing mode, any RAM location can be the destination. The RAM location is held by register
RO or Rl.

4. Register-indirect: CJNE @Ri,#data,target


Example: CJNE ®Rl,#80,NEXT ;jump if RAM
;location whose address is held by Rl
;is not equal to so

Notice that the target address can be no more than 128 bytes backward or 127 bytes forward, since it is a 2-byte
instruction. For more on this see SJMP.

CLRA
Function: Clear accumulator
Flag: None are affected

This instruction clears register A. AU bits of the accumulator are set to O.

Example:
CLR A
HOV RO,A ;clear RO
HOV R2,A ;clear R2
HOV Pl,A ;clear port l

CLR bit
Function: Clear bit
'
This instruction clears a single bit. The bit can be the carry flag, or any bit-addressable location in the 8051. Here are
SOme examples of its format:

CLR C ;Cf•O
·CLEAR P2.5 (P2.5;0)
CLR P2 .4
CLR Pl. 7
;ct.BAR Pl.7 (Pl.7•0)
·CLEAR 07 OF ACCUMULATOR (ACC.7c0)
CI.a ACC. 7 '

.\Pl>ENo(X A.
,
CPLA
. C Jement accumulator f th
function: omp a/f ed . th l's complement o e accumulator.
Flags: None are ect The resu lt ,s e
. the accumulator.
This complements the contents of register A,
That as: Os become ls and ls become Os.

•• Example:
MOV A, #SSH ;A=0101010l
AGAIN: CPL A ·complement reg. A
'; toggle bits o f Pl
, MOV Pl,A
;continuously

SJMP AGAIN

CPL bit
Function: Complement bit .
. an bit-addressable location Ill the 8051.
This instruction complements a single bit. The bit can be Y

Example:
SETB Pl. 0 ;set Pl.O high
AGAlN: CPL Pl. 0 ;complement reg. b it
SJMP AGAIN :continuous ly

DAA
h,p
Function: Decimal-adjust accumulator after addition
Flags: CY

This instruction is used after addition of BCD numbers to convert the result back to BCD. The data is adjusted in '!OV
the following two possible cases. ~

1. It adds 6 to the lower 4 bits of A if it is greater than 9 or if AC = L


2. It also adds 6 to the upper 4 bits of A if it is greater than 9 or if CY= 1.

Example:
MOV A,#47H ;A•OlOO 0111
ADD A, #38H
;A•47H+38H•7PH, invalid BCD
DA A
;A•lOOO 010l•S5H, valid BCO
47H
+ 38H
7PH (invalid BCD)
+ 6H (after DA A)
SSH (valid BCD)

In the a~o"e example, since the lower nibble was greater th


but AC= l, at also adds 6 to the tower rubble. See the i U . an 9, DA added 6 to A If th • .
0
owing example. · 1
e ow e r lllbble as less than 9
Example:
MOV A,#29H ;A•OOlO 1001
ADO A, #18H ;A•OlOO 0001 INCOAA£cr
DA A
;A•OlOO 0111
- 47H VA..10 BCD

APPENDIX A
29H
, 18H
~
41H (incorrect r e sult in BCD)
• 6H
:.---
47H correct result in BCD

The same thing can happe n fo r the uppe r nibble. See the following example.
Example:
MOV A, #52H ;A=OlO l 0010
ADD A., 1191H ;AelllO 0011 INVALID BCD
DA A ;A=OlOO 0011 AND CY=l
52H

-
• 91H
E3H
6
( i n valid BCD)
+ (after DA A, adding to uppe r nibble)
143H valid BCD

Similarly, if the upper nibble is less than 9 and CY= 1, it must be corrected. See the following example.

Example:
MOV A,#94 H ; A=l 001 0100
ADD A , #91H ;AaOOlO 0101 INCORRECT
DA A ;A.•1000 0101 , VALID BCD
; FOR 85 , CY~l

It is possible that 6 is added to both the high and low nibbles. See the fo llo wing e xa mple.

Example:
MOV A, #54 H ;A.•01 01 0100
ADD A., #87H ;A• ll Ol 1011 INVALID BCD
DA A ;A.=0100 0001 , CY• l (BCD 14 1)

DEC byte
Function: Decrement
Flags: None
This instruction subtracts 1 from the byte operand . Note that CY (carry I borrow) is unchanged even if a value 00 is
decremented and becomes PF. This instruction supports four addressing modes.

I. Accumulator: OECA Example: DEC A


2. Register: OECRn Example: DEC Rl or DEC R3
l Direct: DEC direct Example: DEC 4 0H ;dee byte in RAM locat i on 40H
4. OEC@Ri ;where i = 0 or 1 only
Register-indirect:
DEC @RO ;deer. byte poi nted to by RO
Example:

DIV AB
Function: Divide
Flags: CYandOV
This ll\5truction dlvidl!!l a byte accumulator by the ~yte in register B. It is assumed that both registers A and B con-
ta,n an unsigned byte. After the d)vmon, the quotient will be in register A and the remainder in register B. If you divide

461
, AB"), the v
. re.,-
aJues U1
tion of •orv CY is always O •
uister A and
. B are undefined and
·n this instruction.
. re ·ster B = 0 before the ~xecu ulL Notice that
by zero (that is, set gih . dicate an invalid res
the OV flag is set to h,g to m

Example:
MOV A, #35
MOV B,#10
DIV AB ;A= 3 and B=S
;
EJ<ample:
MOV A, #978
• MOV B, #12H
• AB ;A• 8 and B=7 -''vide A by O' in which case the
DIV cl red unless we w
and OV flags are both ea '
Notice in this instruction that the carr~ lid condition.
result is invalid and OV = 1 to indjcate the mva


DJNZ byte, target
Function: Decrement and jump if not zero
Flags: None

Ln this instruction a byte is decremented, and .,f the result is not zero it will jump to the target address.

Example: Count from l to 20 and send the count to Pl.


CLR A ;A=O
MOV R2,#20 ;R2=-20 counter
BACK: INC A
MOV Pl,A
DJNZ R2,BACK ;repeat if R2 not= zero

The following two formats are supported by this instruction.

1. Register: DJNZ Rn,target (where n=O to 7) Example: DJNZ R3,HERE


2. Direct: DJNZ direct.target

Notice that
instruction. For the
moretarget address
on this can be no more than 128 bytes backward or 127 bytes forward, since it is a 2-byte
see SJMP.

INC byte
Function: Increment
Flags: None

This iristruction adds I to the register or memory location Specjfi d b


even if value FF is incremented to 00. This instruction supports fo ded Y ~e operand. Note that CY is not affected
ur a ressmg modes.
1. Accumulator: INC A
Example: INC A
2. Register: INC Rn
3. Direct:
Example:
INC direct
INC 30H
4. Register-indirect: INC@ru ( i = Oor 1)
Example:

;incr. byte .
INC Rl or INC RS

in RAM loc. 30!i



Example: INC eRO
;incr. byte
Pointed to by RO
462

APPIINDIXA
tNCDPTR
function: lncrement data pointer
Flags: None

This ~truction increments the 16-bit register DPTR (data pointer) by 1. r:,iotice that DPTR is the only 16-bit register
that can be tncremented. Also notice that there is no decren,ent version of this instruction.

Example:
MOV DPTR, #l6FFH ;DPTR•l6FFH
INC DPTR ;now DPTR•l700H

J11 bit,target also: JNB bit,target


Function: Jump if bit set Jump if bit not set
Flags: None

These instructions are used to monitor a given bit a.n d jump to a target address if a given bit is high or low· In ~e
case of JB, if the bit is high it will jump, while for JNB if the bit is low it wil l jump. The given bit can be any of the bit-
addressable bits of RAM, ports, or registers of the 8051.

Example: Monitor bit Pl.5 continously. When it becomes low, send SSH to P2.
SETB Pl. S ;make Pl.San input bit
HERE: JB Pl . S, HERE ;stay here as l ong as Pl.5=1
MOV P2,#SSH ;since Pl.5=0 send SSH to P2

Example: See if register A has an even number. If so, make it odd.


JB ACC.O,NEXT ;jump if it is odd
INC A ;it is even , make it odd
NEXT:

Example: Monitor bit Pl .4 continously. When it becomes high, send 55H to P2.
SETB Pl .4 ;make Pl.4 an input bit
HERE: JNB Pl. 4, HERE ;stay here as long as Pl . 4e0
MOV P2, #SSH ;since Pl.4el send SSH to P2

Example: See if register A has an even number. lf not, make it even.


JNB ACC.0,NEXT ;jump if DO is o (even)
INC A ;DO=l, make it even
NEXT:

TBC bit,target
Function: Jump if bit is set and clear bit
Flags: None

If the desired bit Is high it will jump to the target address; at the same time the bit is cleared to zero.

Example: The following instruction will jump to label NEXT if 07 of register A Is high; at the same time 07 is
cleared to zero.
JBC ACC. 7, NEXT
MOV Pl,A
NEXT:

"1'P£NDIX A
, be 11o more than 1
28 bytes back war
d or 127 bytes forward since it is a 2-byte
I
N bee that the target address can
instru~tion. For more on this see SJMP. ,('
f

JC target
Function: Jump if CY= I.
.,.
• Flags: None the target address.
/
. . . hi h it will jump to J'-'
This instruction examines the CY flag; ,f ,t ,s g ' l'lJ•,.t,1•
• Gel!
.-
• ]MP @A+DPTR
Function: Jump indirect
Flags: None
• .. . dress. The target address is p rovided ~y the ~otaJ s~ of
I The JMP instruction is an uncond 1bonal iump to a _target ad . tru tion we w ill bypass further d.1scuss1on of 1t.
register A and the DPTR register. Since this is not a widely used LllS c

JNB bit,target
See )8 and )NB.

JNC target
Function: Jump if no carry (CY= 0)
Flags: None

This instruction examines the CY Oag, and if it is zero it wW jump to the target a dd ress.

Example: Find the total sum of the bytes F6H, 98H, and SAH. Save the carries in register R3. EX!T
CLR A ;A=O
MOV RJ,A ;R3=0
ADD A,#0F6H
JNC OV.:Rl
INC R3
OVERl: ADD A,#98H 1

OVER2:
JNC 0VSR2
INC RJ
ADD A,#8AH
JNC OVSR3
---
1111di
Fan
INC R3
OVERJ:

Notice that this is a 2-byte instruction and the tar


program counter. See Jcondition for more on this get address cannot be farther Iha
. n - 128 to +127 bytes from the

]NZ target
!'unction; Jump if accumulator is not zero
Flags: None

This instruction jumps if register A has a value oth th


er ao zero.

APPENDIX A
E,cample: Search RAM locations 4-0H _ 4FH to find how many of them have the value 0.
MOV RS,16 ,set counter
MOV RJ,#0 ;R3 holds number of Os
MOV Rl,#40H ;address
BACK: MOV A,/IRl ;bring data to reg A
JNZ OVER
INC R3
OVER: INC Rl ;point to next location
DJNZ RS, BACK ;repeat for all locations

The above .program will bring the data into the accumulator and if it is zero, it incren,ents counter R3. Notice that
this is a 2-byte ms~~tion; therefore, the target address cannot be more than-128 to +127 bytes away fron, the program
counter. Seel cond1t1on for further discussion on this.

JZ target
Function: Jump if A= zero
Flags: None

This instruction examines the contents of the accumulator and jumps if it has va lue 0.

Example: A string of bytes of data is stored in RAM locations s tarting at address SOH. The end of the s tring is indl·
cated by the value 0. Send the values to Pl one by one with a delay between each.
MOV RO, #SOH ;address
BACK: MOV A,@RO ;bring the value into reg A
JZ EXIT ;end of string, exit
MOV Pl,A ;send it co Pl
ACALL DELAY
INC RO ;point to next
SJMP BACK
EXIT:

Notice that this is a 2-byte instruction; therefore, the target address cannot be more than-128 to +127 bytes ,n\'ay
from the program counter. See J condition for further ctiscussion on this.

Jcondition target
Function: Conditional jump

In this type of jump. control is transferred to a target address if certain conditions are met. The targPt address cannot
be more than-128 to +127 bytes away from the current PC (program counter).

JC Jump carry jump if CY= t


)NC Jump no carry jumpifCY=O
JZ Jun,p zero jump if register A = 0
)NZ Jump no zero jump if register A is not O
JNB bit Jump no bit jump if bit= 0 ·
JB bit Jun,p bit =
jump if bit I
JBC bat Jump bit cle.ir bit jump if bit = I and clear bit
Decrement and jump if not zero
DJNZ Rn, ...
CJNE A,#va l, ... Compare A with value and jump if not equal

•'Johce that all "J condition" instructions are short jumps, meaning that the target address cannot be more than
-128 bytes backward or+ 127 byteS forward of the PC of the Instruction following the jump (see SJMP). What happens
_ 8 to +127 range? The solution is to
beyond the 12
.. ,..,et address '-own below.
. . "togo toa
"J conctition •=o
n..o> iJlStrUCt·on
l , ass"
wi~h the uncondltional L1,.u
if a progranund~rti.n~~=I~~useg
use the "J con i on
ORG lOOH
ADD 11, RO
bytes away
JNC NEXT than l 28
•target more
LJMP OVER •
NEXT:
ORG 300H
OVER : ADD 11, R2

LCALL 16-bit addr also: ACALL 11-bit addr


Function: Transfers control to a subroutine
Fl s· None ddress is within 2K bytes of the current
. ag .
There am two typesTo
are counter)
fCALLs· ACALLand LCALL. In ACALL, the ta~get a ROM space of the 8051, we must use
o reach the · the 64J< bytesress
· target address in maXJmurn .u th A CALL) is pushed
I of the instruction "-' ,er e
~,!t~ calling a subroutine, the PC register (which has th~td'!iie program counter is loaded with the new address
!s
onto the stack, and the stack pointer (SP) incremented br ~e ;~edure, when RET is executed, PC IS popped off the
and control is transferred to the subroutine. At the end O L P .
stack, which returns control to the '."5truch.on ~ter t~e CAL b e is the O code, and the other two bytes are the l6-~1t
Notice that LCALL is a 3-byte instruction, m which on~ yt f
hich bits are used for the opcode and the remam- "1tiCl
address of the target subroutine. ACALL !s • 2 ins!;'~~~~";
-byte
ing I I bits are used for the target subroutine address. 1
::ress limits the range to 2K bytes.
iiglS~

LJMP 16-bit addr also: SJMP 8-bit addr i 114


i. M
Function: Transfers control unconditionally to a new address. •. M
In the 8051 there are two unconditional jumps: LJMP Qong jump) and SJMP (short jump). Each is described next.
inis'
L LJMP (long jump): This is a 3-byte instruction. The first byte is the opcode and the next two bytes are the target
address. As a result, LJMP is used to jump to any address location within the 641<-byte code space of the 8051. s.9. "~
Notice that the difference between LJMP and LCALL is that the CALL instruction will return and continue execu-
tion with the instruction following the CALL, whereas JMP will not return. IO. I,
2. SJMP (short jump~: This is a 2-byle instruction. The first byte is the opcode and the second byte is the signed number
displacement, whi~ 1s •.dded to the PC (program counter) of the instruction following the SJMP to get the target The<
address. Therefore, m this Jump the target address must be within-128 to+ 127 bytes of the PC ( rogram counter) 11. I
of the instruction after the S)MP since a single byte of address can take values of+127 to -128.
referred to as a re/atrve address since the target address is -128 to+ 127 bytes relati t th
To1; address is often
(PC) In
QI
th.1s AppendJx, we '-· d th ve o e program counter ll J
n<1ve use e term target address in place of relative dd nl f - ·· · .
a ress o y or the sake of sunpilioty. ll
Example: Line 2 of the code below shows 803E as the object cod f 15.
instruction. The 80H, located at address !OOH, is the opcode for theS M~ or 'SJMp OVER", which is a forward jump
live address. The address is relative to the next address location wJch: and 3Eli, located at address 101H, is the rela· '1°'5
target address of the "OVER" label. ' IS l02H. Adding 102H + FBH = 140H gives the
L0c OBJ LINE lb,
0100 l 17,
ORG lOOH
0100 803B 2 SJM.p la.
0140 3 OVER
0140 7AOA ORO 140H
4 OVER: MOV
0142 7B64 s RZ,#10
AGAIN: MOV
0144 00 6 B1\Cl(:
R3,#lOO
0145 00 NOP
7
0146 DBFC NOP
8
0148 80P8 DJNZ R3, Bl\Cl(
9
SJMP
AGAIN

APPENDIX A
E,caf'IIPle: Line 9 of the co~e above shows 80F8 for •sJMP AGAIN"' which is a backward jump _instruction. The
ll)J-I, iocated at _add ress 148H, IS th e o pcode for the SJMP and FSH located a t address 149H, is the relabve address. The
j<ld~ is rela~ve to th~,next address location, which is 14AH. Th~refore, adding 14AH + F8H = 142H gives the target
,dd~ of the AGAIN label.
ll the.target add~ss is beyond the -128 to+127 byte range, th e assembler gives an error. All the conditional jumps
ire s]lort 1un,ps, as dtScussed next.

~OV dest-byte,source-byte
--- .
Function:
Flags:
Move byte variable
None

This copies a byte from the sou rce location to the destination. There are fifteen possible combinations for this
itlStrUction. They are as follows:

{a) Register A as the destination. This can h ave the follo,.,ing forma ts.
1. MOY A,#data Example: MOV A, #25H ; (A=25H)
2. MOY A,Rn Example: MOV A , R 3
3. MOY A.direct Example: MOV A , 3 OH ;A= data in 30H
4. MOY A,@Ri (i=O or l)
Examples: MOV A ,@RO ;A• data pointed to by RO
MOV A, @Rl ;A• data pointed to by Rl
Notice that "MOV A. A" is invalid.

(b) Register A is the source. The d estination can take the following forms.
S. MOY Rn,A
6. MOY direct,A
7. MOY@Ri,A

(c) Rn is the destina tio n.


8. MOY Rn,#immed.iate
9. MOY Rn,A
10. MOY Rn,direct

(d) The destination is a direct address.


11. MOY direct,#d ata
12. MOV d irect,@Ri
13. MOY direct,A
14. MOY direct,Rn
15. MOY d irect,direct
(e) Destination is an indirect address held by RO or Rl .
16. MOV @Ri,#data
17. MOY @Ri,A
18. MO Y @Ri,direct

Mov dest-bit source-bit


- Function: '
Move bit data
This MOV instnaction copies the source bit to the destination bit. In this instruction one of the operands must be the
cY flag. Look at the following examples.
,copy carry bit to port bit Pl . 2
Hov Pl. 2 , C
; c opy port bit P2.5 to carry bit
HOV C, P2 . 5
,
MOV DPTRI #16-b it value
F ction: Load data pointer b't immediate value.
un N 'tha 16-,
Flags: one inter) register WI
. .,nstructi'on loads the 16-bit OPTR (da~a po
This
,pf'
Examples:
HOV DPTR,#456FK ;DPTR•456FK ddress
·~
HOV DPTR,#H¥DATA ·load 16-bit a
•·assigned to MYOATA


MOVC A,@A+DPTR
... . . Mo,•e code byte

I Function.
Flags: None . -fh~
.
am (code) ROM into register
This instruction moves a byte of data~oc:! ~p~:~nd read them 1:
Tius allows us to put strings of
address of the desired byte in
the ;p~~tor to the 16-bit DPTR register.
data, such as look-up _table ele~ent::r,';,',i be adding the original value o e ac u tttP1
the code space (on-chip ROM) is fo Y . -chip ROM program memory starting at add ress illll·
l . is stored ,n the on ) riluE
Example: Assume that an ASCD character stnngU CPU and send it to Pl (port 1 .
l 200H. Write a program to bri,,g each d,aracter into ,e '11t II
belol
ORG lOOH Jhjs l
HOV DPTR,#200H ;load data pointer
Bl, CLR A ;A=O !!pi
MOVC A, liA+DPTR ;move data at A+DPTR into A byte
JZ EXIT ;exit if last (null) char
MOV Pl ,A ;send character to Pl
INC DPTR ;next character
SJMP Bl ;continue
EXIT,

ORG 200H
DATA, DB "The earth is but one country and•
OB "mankind ice citizens", ·~eaha ,u, llah"', o
2ND

In the program above first A = 0 and then it is ~dded to DPTR to form the address of the desired by te. After ~ e ll)l'bi
MOVC instruction, register A has the character. Notice that the DPTR is incremented to point to the n ext character m
the DATA table. It

Example:
Write Look-up
a program to fetch the SQUR
table squareshas thethe
from squares table. between Oand 9, and register R3 has the values of Oto 9.
of values
look-up ~'ll
MOV DPTR,#SQUR
;load pointer for table
HOV A,R3
HOVC A, eA+DPTR .
ORG lOOfi l
SQUR, OB 0,l, 4 ,9,16,25,36,49,64 ,81

Notice that the MOVC instruction transfers data from the int
mtemaJ ROM space belongs to program (code) o~-chip ROM of thee~~ ROM space of '!1e 8051 into register A. ~
'll't
I
connected externally, we use the MOVX instruction. See MOvx, fu · To 4CCess off-chip memory that is memories
,or rther di=

- ....••• ·
,,non. ' '

APPENDIXA
-
~oVC A,@A+PC
~ction: Move code byte
flags: None
This instruction m~ves a byte of data located in the program (code) area to A. The address of the desired byte ~f
data is formed by addmg the program counter (PC) register to the original value of the accumulator. Contrast thiS
iJIStrUction with "MOVC A, @A+DPTR". Here the PC is used instead of DPTR to generate the data address.

Example: Look-up table SQUR has the squares of values bet.veen oand 9, '.'1'd register R3 has the v'.'1ues of O to 9:
Write a program to fetch the squares from the table. Use the "MOVC A, @A+PC" ,nstrucbon (this 1s a rewnte of an exam
~e of the previous instruction "MOVC A, @A+DPTR" ).
MOV A, R3
INC A
MOVC A, @A+ PC
RET
SQUR: DB O,l,4,9,16,25,36,49,64,81
The follo,ving should be noted concerning the above code.

(a) The program counter, which is pointing to instruction RET, is added to register A to form the address of the desired
data. In other words, the PC is incremented to the address of the next instruction before it is added to the original
value of the accumulator.
(b) The role of ·INC A" should be emphasized. We need instruction "INC A" to bypass the single byte of opcode
belonging to the RET instruction.
(c) This method is preferable over "MOVC A, @A+DPTR" if we do not want to divide the program code space into two
separate areas of code and data. As a result, we do not waste valuable on-chip code space located between the last
byte of program (code) and the beginning of the data space where the look-up table is located.

MOVX des t-byte,source-b y t e


Function: Move external
Flags: None
This instruction transfers data between external memory and register A. As discussed in Chapter 14, the 8051 has
641< bytes of data space in addition to the 64.K bytes of code space. This data space must be connected externally. This
instruction allows us to access externally connected memeory. The address of external memory being accessed can be
16-bit or 8-bit as explained below.

(a) The 16-bit external memory address is held by the DPTR register.
MOVX A,@OPTR
This moves into the accumulator a byte from external memory whose address is pointed to by DPTR. In other
words, this brings data into the CPU (register A) from the off-chip memory of the 8051.

HOVX @DPTR,A
This moves the contents of the accumulator to the external memory location whose address is held by DPTR. In
other words, th.is takes data from inside the CPU (register A) to memory outside the 8051.

(b) The 8-bit ad dress of extemal memory is held by RO or Rl.


MOVX A,@Ri ;where i ~ o or 1
This moves to the accumula tor a byte from external memory whose 8-bit address is pointed to by RO (or Rl in
MOVX A,@Rl).
MOVX eRi,A

Af'PENDIX A
, rocation whose
S-bit address is held by RO {or Rl in MOY)(
xternal memory hil th 8 b .
..... ,. oves a byte from register A to an e mal memory w e e - ti version
sed t0 access ex Ie
.I S

,..,_, m
@Rl.A) . . · is widely u
The 16-bit address version of this ltlStructJo0
used to access external 1/0 ports.

MUL AB
Function: Multiply A x B
Flags: OV, CY . . The result is placed in A and B where A
. ed byte in register 8·
This multiplies an unsigned byte in A by an uns1gn
has the lower byte and B has the higher byte.

Example:
MOV A,#5
MOV 8,#7
MUL AB ;A•35•23H, B•OO

• Example:
MOV A,#J.0
MOV B,#15
MOL AB ;A=J.50=96H, B•OO

This instruction always clears the CY Oag; however, OV is changed according to the product. If the product is ilgiSI
greater than FFH, OV = 1; otherwise, it is cleared (OV = 0).
!D the
Example: lhe i
MOV A,#25H
MOV 8,#78H QIU..,
MUL AB ;A=SSR, B=llH, CY=O, and OV•l Ewr
;(2SH x 78H • 1158H)

Example: ORL
llJV
MOV A,#100
MOV 8,#200 t4R
MOL AB OV•l , and CY•O
•· A=20H, 8 • 4EH •
;(100 x 200 = 20,000 • 4 E2 0H) -
67R
I 'll!

NOP
Function: No operation
Flags: None
This performs no operation and exec 11·
d eIays to waste clock cycles. This instructiu on contin ues with
.
the next · .
foUowing NOP. on only updates the PC (progr':lruction. 1t is sometimes used for timing
counter) to ·
pomt to the next instruction
ORL des t-b y te,sow:ce-by te
Function: Logical OR for byte variable A B AORB
Flags: None
0 0 0
This perfomu; a lnoicaJ OR O th b 0
the destin b' · o· n e yte operands b't b . 1 1
a on. • 1 Ybit and
' ·~• the result in
sto- 1 0 1
470 l 1 1

APPENDIX A
sxaniple:
r,10V A,#3 9H ;A=39H
oRL A,#0 9H ;A=39H OR 09 (A=3 9H)

39H 001 1 1 001


09H 0000 1001
-39 0011 1001

Example:
MOV A, #3 2H ;A=32H
MOV R4, # SOH ;R4 =SOH
ORL A,R4 ; (A=72H )

32H 0011 0010


50H 010 1 00 00
72H 0111 0010
For the ORL instruction there are a total of six addressing modes. In four of them the accumulator must be the
destination. They are as follows:

1. Immediate: ORLA,#data Example: ORL A,#2SH


2. Register: ORLA,Rx Example: ORL A, R3
ORL A, 30H ;OR A with data located in RAM 30H
3. Direct: ORL A,direct Example:
to by RO
4. Register-Indirect: ORLA,@Rn Example: ORL A, @RO ; OR A with data pointed

1n the next two addressing modes the destination is a direct address (a RAM location or one of the SFR registers),
while the source is either A or immediate data as shown below:

5. ORL direct,#data
Example: Assuming that RAM location 32H has the value 67H, find the content of A after the following:

ORL 32H,#44H ;OR 44H with contents of RAM loc. 32H


MOV A,32H ;move content of RAM loc. 32H to A

44H 01 00 0100
67H 0110 0111
67H 01 10 0111 Therefore A will have 67H.

6. ORL direct.A
Example: Find the content of B after the following:

MOV B, #44H ;B=44H


MOV A, #67H ;A=67H
;OR A and B (Bis at RAM FOH)
ORL OFOH,A
;After the operation B=67H.

Note: This cannot be used to modify data at input pins.

ORL C,source-bit
- Function: Logical OR for bit variables
Rags: CY
tn this instruction the carry flag bit is O Red with a s~urce bit and the result is placed in the carry flag. Therefore, if
the source bit is 1, CY is set; otherwise, the CY flag remains unchanged.

471
APl'ENDIXA
cz is high,
le: Set the C311)' ilag ii either PlS or AC .
ExiUJ\P · statUS
-get Pl· 5 .-cu
H()VC,Pl.S ' kA::rr"·
ORL c. ;,.cc . 2 . )ugh- ()therWise, ma e
·r
Example: Write a program to clear A I
Pl 2 or !'2-2 15
.

MOV A, HFFH
MOV C, Pl. 2
ORL C,P2.2
JNC OVER
CLR A
• R. t of the source bit. Its format is "ORl
OVE . y with the complemen
.
. ~on involves ORing C
Another variabon of~his mstru, ..
C,/bit". See the foUowing exiUJ\ple.
• · mnke A "' FfJ-{.
Example: Clear A if P2.1 is high or P2.2 is low. Otherwise,

MOV A, #OFFH
·get a copy of P2.l bit
MOV C,P2.l of P2. 2
;OR P2.l with complement
ORL C,/P2.2
I
JNC OVER
I CLR A
OVER:

POP direct
Fur,ction: Pop from the stack
Rags: None
This cop,es the byte pointed to by SP (stat.k pointer) to the locahon whose direct address is indicated, and decre-
ments SP by 1. Notice that this instruction supports only direct addressing mode. Therefore, instructions such as •POP
A· or •POP R3" are illegal. Instead we must write "POP OEOH· where EOH is the RAM address belonging to register

-
A and ·POP 03• where03 is the RAM address of R3of bank 0.

PUSH direct
Function: Push onto the stack
Aags: None

nus rop,es the indicated byte onto the stack and increments SP b .
direct addressing mode. Th~refore, instructions such as "PUSH A.· !
1 Notice that this instruction supports o~y
•PUSH OEOH" where EOH IS the RAM address belonging tor . or PUSH R3• are illegal Instead we must wnte
or R3olbanl<O. egister A and ·PUSH 03• whe~ 03 is the RAM addreSS

RET
Function·
Aags:
Return hom subroutine
None -
This instruction is used to return from a subroutine .
two by1es of the st.tck are popped 1.1110 the program couift~vtously entered b .
After popping the top two bytes of the stack i n t o ~ ~ ) and P«>gT YUlStructions LCALL or ACALL. Tht IDf
C'Ourater, the ~ ":tcution continues at this new ..t~
472 P<>inter (SP) is decremented by l

-
.....

'

• ll011l1'l
,>.•11010010
• \•10100101

OW .a:umul.ltor left. The bits rotated out of register A are rotated uuo CY, and 1M CY bit ls
lbrwPol=rcd T:lw .lCCWllulator

, cv-o
A-100llt>Ol - MSB - - - LSI! ~-
, ao,, A-00110010 and CY•l
l'fOw ~~011~0 101 ,nd CY•O

'• ~
""' '
, . t The bits rota
ted out of register A are r
otated into CY and the CY bit is

b"ts
1 of the accumulator ngh .
This rotates the • d f the accumulator.
·-• .
rotan:u"' to the opposite en o

Example:
SETS C
;CY•l
MOV A, #99H ·A•lOOllOOl
RRC A
• '.Now A=llOOllOO and CY=l
'
SETS C and CYsO
RRC A

SETB bit

Function: Set bit . ectl ddressable bit of a port, register, or RAM r


.
This sets high the indicated bit. The bit can be
the carry or any drr ya

location. E
J
Examples:
SETS Pl. 3 ;Pl.3=1
SETS P2. 6 ;P2 .6 • 1
SETS ACC. 6
SETS 05
SETB C
;ACC.6•1
;set high OS of RAM loc. 20H
;Set Carry Flag CY=l -
xa
F
F
SJMP 1
See LJMP &: SJMP.
rot
SUBB A,source b yte
Function: Subtract with borrow
Flags: OV, AC, CY

This subtracts the source byte and the carry flag from the accumulator and puts the result in the accumulator. The
steps for subtraction performed by the internal hardware of the CPU are as follows:
1. Take the 2's complement of the source byte.
2. Add this to register A. l
3. Invert the carry. l

This instruction sets the carry flag according to the followmg:


l
i !:X
dest > source 0 the result is positive
dest = source 0 the result is 0
dest < source I
the result is negative in 2's complement
Notice that there ls no SUB instruction in the 8051. There(
and then using SUBB: A = (A - byte -CY). ore, we perform the SUB instruction by making CY = O
Example:
MOV A, #4SH
CLR C
SOBS A, #23H ;45H·23H·0=22H

474
)ddressing Modes
n,e following four addressing modes are supported for the SUBB.

SUBS A,#data SUBS A,#25H ;A•A· 25H· CY


!Jllmediate: Example:
I, ;As A• R3 - CY
Register: SUBB A,Rn Example: SUBS A,R3
?
SUBB A,direct Example: SUBS A,30H ;A - data at (30H) - CY
J.
Direct:
Register-indirect: SUBB A,@Rn Example: SUBS A, @RO ;A . data at (RO) - CY
-1,

5WAPA
Function: Swap nibbles within the accumulator
Aags: None
The SW AP instruction interchanges the lower nibble (DO • D3) with the upper nibble (04 • 07) inside register A.

Example:
MOV A, ll59H ;A: 59H (0 1 01 1001 in bi nary)
SWAP A ;A• 95H (1001 01 0 1 in b i nary)

XCH A,Byte
Function: Exchange A with a byte variable
Flags: None
This instruction swaps the contents of register A and the source byte. The source byte can be any register or RAM
location.

Example:
MOV A, #65H ;A=65H
MOV R2, #97 H ;R2s97H
XCH A, R2 ;now A=97H and R2=65H

For the "XCH A, byte" instruction there are a total of three add,essing modes. They are as follows:

XCHA,Rn Example: XCH A,R3


I. Register:
2. Direct: XCH A,direct
XCH A, 40H ;exchange A wi th data in RAM loc. 40H
Example:
3. Register-Indirect: XCHA,@Rn
XCR A, @RO ;XCH A with data pointed to by RO
Examples:
XCH A,@Rl ;XCH A with data pointed to by Rl

XCHDA,@Ri
Function: Exchange cligits
Flags: None
The XCHO instruction exchanges ~nly the lower. nibble of A with the lower nibble of the RAM location pointed to
by Ri while leaving the upper nibbles 1n both places Ullact.

Example: Assuming RAM location 40H has the value 97H, find its content after the following instructions.

;40H• (97H)
;A•l2H (0001 0010 b inary)
HOV A, #12R

ffl
1oad painter ble of
; R.1•40H , lOl'ler ni b
MOV Rl, 14011
, exchange the ion 40H
XC!!D A, eRl • and RAM 1ocat ti ,nH has 92H.
; ft d RAM Joca on ""
. we 11ave A '" 171-1 aJ\
After execution of the XCHD instrUdiOO.

XRL dest-byte,source-byte
- Function: Logical exclusive-OR for byte variables
Flags: None . the result iJl the destiJlation.
ds bit by bit, stonng
This performs a logical exclusive-OR on the operan '
---=------:~==~
:.A:__ _ B___A_X_O_R_B
0 0 0
Example:
0 1 1
MOV A,#39H ;A•39H
·A• 3 9H ORed wi t h 0 9 1 0 1
XRL A, • o 9H •
1 1 0
39H 0011 1001
0 9H 0000 1 001
30 0011 0000

Example:
MOV A, #3 2H ; A•3 2H
MOV R4 , I SOH ; R4•SOH
XRL A,R4 ; (A•62H)

32H 0011 001 0


SOH 0101 0000
62H 0110 00 10

For the XRL instruction there are total of six addressing modes. In four of them the accumulator must be the desti-
nation. They are as follows:

I. Immediate: XRLA,#data Example: XRL A, #2SH


2. Register: XRLA,Rn Example: XRL A, R3
3. Direct XRL A.direct
Example: XRL A, JOH ;XRL A with dat a in RAM location lOH
4. Registtt•indir«t XRL A,ORn
Example: XRL A,•RO ;XRL A with data pointed to by RO

In the next two addressing modes the destination Is a direct 1 d"--


while the source is either A or unmediate data as shown below: ''"""' (a RAM location or one of the SFR registers)
5. XRL direct,ldata
Example: Assume that RAM location 32H has the value 67H
Find the content of A after execution of the follOWlng code. ·
XRL 32H, #44H
MOV A, 32H ;move content ot RAM 1
oc:: • 32H to A
44H 0100 0100
67H 0110 0111
23H 0010 0011 Therefore A Will ha
Ve 23H.

416
XRL direCt,A
6. Example: Find the contents of B after the following:

i,10V B , #44H ; B•44H


l'l()V A , #67H ;A=67H
J(RL OFOH , A ;OR register A and B
; (register B i s located at RAM l ocation FOH)
,after t he operati on B•23H •

Note: We cannot use this instruction to exclusive-OR the data at the input port.


f
Table A· l : 8051 lnstruction Set Summary
Byte
Machine
~
Mntmonic Byte
Machine
Cycle
Mrternonic
Logical Opeta tions
Cycle
-- ~
Arithmetic Opera.lions
. direct,A 2 1 ~
~
ORL
ADD A,Rn t 1 direct,#data 3 2

~
ORL
ADD A,direct 2 1 1 1
XRL A,Rn
ADD A,@RJ l 1
XRL A,clirect 2 1 "!,:
ADD A,lldata 2 1
XRL A,@Ri l I ~
ADDC A,Rn I 1
XRL A,#data 2 1 ~
~
ADDC A,direct 2 1
XRL direct,A 2 1
~
ADDC A,@Ri 1 1
XRL direct,#data 3 2
ADOC A,lldata 2 I
CLR A 1 1
SUBB
~
A,Rn 1 1
CPL A 1 1
SUBB A,direct 2 I
SUBB A,@Ri I I RL A 1 1 ~
SUBB A 1 1 ~
--
A,#data 2 I RLC
A 1 ~
INC A 1 1 RR 1
INC Rn 1 I RRC A 1 1 ~
INC direct 2 I SWAP A 1 1
-
(Pl

INC
DEC
@Ri

A
1
1
1
1
Data Transfer -
(]'I.

\.'ll.
DEC Rn I 1 MOY A,Rn 1 1 A,'11.
DEC direct 2 1 MOY A,direct 2 1
-
(IL
DEC @Ri 1 1 MOY A,@Ri 1 1 -Ill.
INC DPTR 1 2 MOY A,#data 2 1 -lOV
MUL AB 1 4 MOY Rn,A
-
DIV
DA
AB
A
1
1
4
1
MOY
MOY
MOY
Rn,direct
Rn,#data
direct,A
1
2
2
1
2
1
--
ll)y
(

Logical Operations 2 1
ANL MOY direct,Rn
A,Rn 1 2 2
I
MOV
ANL A.direct 2 1 -MOV direct,direct
3 2
ANL A,@Ri 1 direct,@Ri
1 2 2
Mov
ANL
ANL
A,#data 2 I -MOV direct,#data
3 2
direct,A 2 @Ri,A
1 l l
ANL dircct,#data 3 2 -
Mov
Mov
@Ri,direct
2 2
ORL A,Rn 1 1 - @Ri,#data
2
ORL A,direct 2 I -
Moy
DPTR,#data16
3
1
ORL A,@Ri 1 1 -
Movx A,@Ri
1
2
ORL A,#data 2 1 -
Movx A,@DPTR
1
2
2
<conunue,t)
'fable A-1 (continued)

---
~ine111onic Byte
M achine
Cycle Mnemonic Byte
Boolean Variable Manipulation
Machine
cycle

~Transfer
2 2

- 1 2 JNC rel
~<OVX @Ri,A 2
bit.rel 3
MOV @DPTR,A 1 2 JB 2
bit,rel 3
pVSH direct 2 2 JNB 2
JBC bit,rel 3
p()P direct 2 2

.xcH A,Rn 1 1
Program Branching
;<CH A,direct 2 l 2 2
ACALL adclrll
xCH A,@Ri 1 1 3 2
LCALL addrl6
xCHD A,@Ri 1 1 1 2
RET
1 2
5o0lean Variable ManJpulation RETI
addrll 2 2
1 1 A}MP
CLR C
adclrl6 3 2
2 1 L}MP
CLR bit
2 2
SETB C 1 1 SJMP rel
@A+DPTR 1 2
SETB bit 2 1 JMP
rel 2 2
C 1 1 JZ
CPL 2
JNZ rel 2
CPL bit 2 1
CJNE A,direct,rel 3 2
ANl. C,bit 2 2
A,#data,rel 3 2
CJ bit 2 2 CJNE
ANl.
CJNE Rn,#data,rel 3 2
ORL C,bit 2 2
CJNE @Ri,#data,rel 3 2
ORL C,/bit 2 2
OJNZ Rn.rel 2 2
MOV C,bit 2 1
OJNZ direct,rel 3 2
MOV bit,C 2 2
NOP 1 l
2 2
JC rel

.\PnNDIXA '"
/
,r; ,
f
ECTION A.2: 8051 REGISTERS
I
S . (SFR) .Addresses
.
Table A-2: Special Function
RegJster Address
Symbol Name OEOH
ACC• Accumulator OFOH
a• B register ODOH
PSw• Program status word
81H
SP Stack pointer
OPTR Data pointer 2 bytes
82H
OPL Low byte
83H
OPH High byte
80H
PO' Porto
90H
P1• Port 1
P2· Port2 OAOH
P3' Port3 OBOH
[P• Interrupt priority control OB8H
IE' Interrupt enable control 0A8H
TMOO Timer/counter mode control 89H
TCON• TimerI counter control 88H
T2CON' Tl!ller/counter 2 control OCSH
T2MOD Tl!ller/counter mode control OC9H
TiiO TimerI counter Ohigh byte SCH
TLO Timer I counter Olow byte
8AH
THI TimerI counter 1 high byte
8DH
TLI Ttmer I counter I low byte
TH2 8BH
Timer I counter 2 high byte
TU OCDH
Timer I counter 2 low byte
RCAP2H OCCH
TIC 2 capture register high byte
RCAP2L OCBH
TIC 2 capture register low byte
SC0N' Serial control
SBUF 98H
Serial data buffer
PCON Power control 99H
• Bit-a.ddressabJe
87H

-
APPIINDIX A
..
Byte
Byte address
address Bit address
7F
FF
FO F7 F6 FS F4 Fl F2 Fl FO B General·
purpose
80 E7 E6 ES E4 E3 E2 El EO ACC RAM

00 D7 D6 DS D4 D3 D2 Dl DO PSW 30
78
2F 7F 7E 70 7C 78 7A 79
B8 .. .. .. BC BB BA 89 88 IP 2E 77 76 75 74 73 72 71
70
2D 6F 6E 60 6C 68 6A 69 68
87 86 BS 84 83 82 Bl BO P3 6n
BO 2C <7 •6 , . 64 63 "2 <1
58
.. .. 28 SF SE SD SC SB SA 59
IE 2A 57 56 55 54 53 52 51 so
AS AF AC AB AA A9 AS
49
29 4F 4E 40 4C 48 4A 49
AO A7 A6 AS A4 1\.3 A2 Al AO P2 40
28 47 46 45 44 43 42 41
38
27 3F lE 30 JC 38 3A 39
99 not bit-addressable SBUF 26 37 36 35 34 33 32 31 30
98 9F 9E 90 9C 98 9A 99 98 SCON 25 2F 2E 20 2C 29 2A 29 28
24 27 26 25 24 23 22 21 20
90 97 96 95 94 93 92 91 90 Pl 23 lF lE lD lC 18 lA 19 18
22 17 16 15 14 13 12 11 10
21 OF"" OD nc OB OA 09 08
8D not bit-addressable THl
THO 20 07 06 OS 04 03 02 01 00
SC not bit-addressable lF
not bit-addressable TLl Bank3
88 18
not bit-addressable TLO 17 Banlc 2
8A 10
89 not bit-addttSSable TMOD OP Bank 1
88 SF SE 80 SC 88 SA 89 88 TCON 08
07 Default register bank for RO· R7
87 not bit-addressable PCON
00

83 not bit-addressable DPH


DPL Figutt A•2. 128 Bytes of lntem•I RAM
82 not bit-addressable
81 not bit-addressable SP

80 87 86 85 84 83 82 81 80 PO
.
Special Function Registers

Figure A•l . SFR RAM Address (Byte and Bit)

Al'PENDJXA
DO

EJ(l
BXO ]
EA I I ET2 I F.S I ET!
. terrupt )s acknowledged.
EA !E.7 Disables all interrupts. If EA= O'. ";:J;vidually enabled or disabled
If EA: I, each interrupt source is
by setting or clearing its enable b1l.

.
Not implemented, reserv
ed •·'or future use. '
IE,6
ture interrupt (8952).
ET2 IE.5 Enables or disables timer 2 overflow or cap

ES !E.4 Enables or disables the serial part interrupt.

ET1 IE.3 Enables or disables timer I overflow interrupt.

EX1 IE.2 Enables or disables external interrupt 1.

ETO IE.I Enables or disables timer Ooverflow interrupt.

e:xo LE.O Enables or disables external in~upt O.

• User software should not write ls to reserved bits. These bits may be used
in future flash microcontrollers to invoke new features.

Figutt A•3. IE (Interrupt Enoble) Register

07
DO
PT2 PS PT! PX! PTO PXO

Priority bit : 1 assigns high priority. Priority b' t _ .


i - 0 ass,gns low priority.
- CP.7 reserved
IP.6 reserved
~ :s ~:: 2 interrupt priority bit (8052 only)
PT1 IP~ . ~rt ll\terrupt priority bit. ·
Tuner I mterrupt priority b't
PXl lP.2 External interrupt I priori~ i,.
PTO IP.I Tuner Ointerrupt priority b' ,t.
PXO IP.O External interrupt Opriori;tbit.

User software should never write Is t0 .


future products. u.rutnplernented bits .
, smce they - · L
u~y "". used .
F' A 111
,gure -4. lnterrupt Priority Regi1ter (Bit·• ddres10bie)

-
APPENDIX A
~I - I - I - I GFl I GFO PD IDL
figUlt A-5. PCON Register (not bit-addressable)

Finding the TH, value for various baud rates:

SMOD = 0 {default on reset)

TH, = _ Crystal frequency


256
384x Baud rate

SMOD = 1

Crystal frequency
TH, =256
192x Baud rate

CY AC FO RSI RSO OV r I
CY PSW.7 Carry flag.
AC PSW.6 Auxiliary carry flag.
FO PSW.5 Available to the user for general purposes.
RSI PSW.4 Register Bank selector bit 1.
RSO PSW.3 Register Bank selector bit O.
OV PSW.2 Overflow flag.
PSW.1 User-definable bit.
P PSW.0 Parity flag. Set/ cleared by hardware each instuction cycle
to indicate an odd/ even number of 1 bits in the accumulator.

RSl RSO Regis ter Bank Address


0 0 0 OOH-07H
0 1 1 OSH-OPH
1 0 2 10H-17H
1 1 3 18 H -1FH

figure A-6. Bits of the PSW Register (bit-addressable)

l SMO SM! ! SM2 ] REN TB8 i RBS Tl ! RI


SMO SCON.7 Serial port mode specifier
S M1 SCON.6 Serial port mode specifier
S M2 SCON.5 Used for multiprocessor communication. (Make it O.)
REN SCON.4 Set/cleared by software to enable/disable reception.
T BS SCON.3 Not widely used.
RBS SCON.2 Not widely used.
Tl SCON.1 TransmH interrupt 8ag. Set by hardware at the beginning of
the stop bit in mode 1. Must be cleared by software.
RI SCON.O Receive interrupt flag. Set by hardware halfway through the
stop bit time in mode 1. Must be cleared by software.
Nott: Make SM2, TBS, and RBS z 0.

Figure A-7. SCON Serial Port Control Regit ter (Bit-addretsable)

APPENDIX A
(
Finding the TH, value for various baud rates:

sMOD" 0 (default on reset)

Crystal frequency
TH =256-
1 384xBaud rate

SMOD= I

m =
256
_ Crystal frequency
1
192x Baud rate

(LSB)

l I
(MSB)
GATE I C/T I Ml I MO GATE I Cl~ I Mt

GATE Gating control when set. Timer/cou.nter is enabled only while the !NTx pin is
high and the TRx control pin is set. When cleared, the timer is enabled
whenever the TRx control bit ts set
err Tuner or counter sele<:ted cleared for timer operation (input from internal
system dock). Set for counter operation (input from Tx input pin).
Ml Mode bit I
MO ModebitO

Ml MO Ml&• Operating Mode


0 0 0 13-bit timer mode
S-bil timer/ counter TI-Ix with nx as 5-bit prescaler
0 I I 16-bil timer mode
16·bit timer/ counters THx and TLx are cascaded· th .
no prescaJer. , ere lS
I 0 2 S-bit auto reload

I I 3
to be reloaded into
Split timer mode
Tr
S-bit auto reload tim I
cou~t~r; THx holds a value tha t is
x eac time ,1 overflows.

Figwe A-8. TMOO Register (not Bit-addressable)

-
APPIINDIXA
07 DO

I TFI TIU TFO I TRO 1E1 1 m CEO ITO ]

Tfl TCON .7 Timer J overflow flag. Set by hardware when timerI counter 1
overflows. Cleared by hardware as the processor vectors to
the interrupt service routine.

TR1 TCON.6 Timer 1 run control bit. Set/ cleared by software to tum
timer/ counter 1 on/ off.

TFO TCON.5 Timer Ooverflow flag. Set by hardware when timer/ counter 0
overflows. Cleared by hardware as the processor vectors to
the service routine.

TRO TCON.4 Tuner Orun control bit. Set/ cleared by software to turn
timer / counter O on/ off.

lEl TCON.3 External inter rupt 1 edge flag. Set by CPU when the
external interrupt edge (H·to-L transition) is detected.
Cleared by CPU when the interrupt is processed.
Nott: This flag does not latch low-level
triggered interrupts.

m TCON.2 Interrupt 1 type control bit. Set/ cleared by software to


specify falling edge/ low-level triggered extem al interru.pt.

IEO TCON.1 Extemal interrupt Oedge flag. Set by CPU when external
interrupt (H·to·L transition) edge detected. Cleared by CPU
when interrupt is processed. Note:This flag does not
latch low-level triggered interrupts.

ITO TCON.O Interrupt O type control bit. Set/ cleared by software to specify
falling edge/low-level triggered external interrupt.

Figu.tt A-9. TCON (Timer/Counter) Regist4'r (Bit-addressable)

Al'PENDIXA
APPENDIXB

BASICS OF WIRE WRAPPING

OVERVIEW

This appendix shows the basics of wire wrapping.

487

I
l

BASICS OF WIRE WRAPPING f UowinS:


. . ou will need the o
Note: For this tutonal ap~clix, Y ber 276-1570)
~\lite-wrapping tool (Radio Sha.ck part n~ this section.)
:JO-gauge (30-A~\IG) wire for wrre wrapp~; for their assistance on
(Thanks to Shannon Looper and Greg Boy · .
Th following descn"bes the basics of wire wrappmg. . available from Radio Shack for less
e Th best one 1s fu ti · h
. tools available. e . the wrap and unwrap nc ons m t e
I. There are several different typesR odi~ w:;;r~;276-JS70. 'fhjs tool cthio~~:: much easier to use than the tools that
O 5 •
than SJO. The part number for a tripper. we found p guns, which are, of course, more
same end of the tool and includes a separate~ shaft. There are also wrre-wra
combined all these features on one two-ende . d . .
. ulk spool The prestrippe wire 1s usu-
expensive. . . various lengths or in b on a f~
2. Wire-wrapping wire is available prestnpped in different wire lengths you can a or O
d t buy Bulk wire can be cut
·
ally more expensive and you are restricted to the ft
1
to any length you wish, which allows each wire to be custom • Uy called perfboards or wire- wrap boards.
3. Serveral different types of wire-wrap boards are available. Th:a:r;:; aShack). The best type of board has plating
0
These types of boards are sold at many electronics store:d~':.re better because the sockets and pins can be soldered
arowid the holes on the bottom of the board. These boa bl
to the board, which makes the circuit more mechanically sta e. . d . · th room to spare so that the wir-
od te all the parts u, your es,gn w1
4. Choose a board that is largeenoug h toaccomm a . ct · the future you should be sure to include
01
ing does not become too cluttered. If you wish to expan~ your P( e.f u, ible the' layout of the IC on the board
enough room on the original board for the complete rucwt. A so, t po~s ,
needs be done such that signals go from left to nght JUSt ltke the schematics.
s. To make the wiring easier and to keep pressure off the pins, install one standoff on eda<:h co~erbockfthe board. You
may also wish to put standoffs on the top of the board to add stability when the boar IS on its a .
6. For power hook-up, use some type of standard binding post. Solder a few single wire-wrap pins to each power
post to make circuit connections (to at least one pin for each IC in the circuit).
7. To further reduce problems with power, each IC must have its own connection to the main power of the board.
If your perfboard does not have built-in power buses, run a separate power and ground wire from each IC to the
main power. In other words, 00 NOT daisy chain (chip-to-chip connection is called daisy chain) powe r connec-
tions, as each connection down the line will have more wire and more resistance to get power through. However,
daisy chaining is acceptable for other connections such as data, address, and control buses.
8. wrapped use wire-wrap
You mustaround the pm. sockets. These sockets have long square pins whose edges will cut into the wire as it is
9. Wire wrapping will not work on round legs. U you need to wrap to co
round I""• you must al$O solder these connectio Th '--· mponents, such as capacitors, that have
"""'' ns.
vidual wire-wrap pins into the board and then solder the e =t way to connect sing!e components IS · to UlSt
· all tn· d'1-
empty IC socket to hold small components s uch as resistors components
d th the pins · An alternate meth o d 1s
to . to use an
10. The wire . should be stripped
. .
about 1 inch. an10wrap
This will allow 7 to tu em to the socket
and-a-half should be insulated. This prevents s tripped Wire f ms _for ~ach connection. The first tum or turn·
i accomplished by inserting the wire as far as it will go into th rtomlbconung in contact with other pirls. This can be
11. Try to keep wire lengths to a minimum. This prevents th e. oo. efore making the connection.
color coding as much as possible. Use only red wires for ve :~u;, 1;om _looking Hke a bird nest. Be neat and use
ferent colors for data, address, and control signal connecti cc Th 1 ck wires for ground connect· Al dif-
easier. ons. ese suggesti . ions. so use
12. It .is standard practJce
. to connect all power lines first and ch ons will make troubleshooting much
on. eek them for contin i . .
13. Its, also a good idea
. to mark the pm. orientation
. on th bo u ty.1'hjg wil l eliminate trouble later
pin numbers preprinted on them specifically for this e ttom o( the board. Pl ti
to reverse pin order when looking at the bottom of :~se o~ you Ci\n make as c templates are available ~ith
circuits. e Dard ts a very corrun your ?Wn from paper. Forgetting
on mistake when wire wrapping

-
APPENDIX &
To prevent damage to your circuit, place a diode {such as INS338) in reverse bias across the power supply. Uthe
14· wer gets hooked up backwards, the diode will be forward biased and will act as a short, keeping the reversed
~Jtage from your circuit.
• Jn digital circuits, there can be a problem with current demand on the pov.rer supply. To filter the noise on the
1
'' p0wer supply, a 100 µF electrolytic capacitor and a 0.1 µP monolithic capacitor are connected from Vq:. t~ ground,
ill parallel wtlh each other, at the entry point of the power supply to the board. These two together will filter both
the high· and the low-frequency noises. Instead of using two capacitors in parallel, you can use a single 20-100 µF
taJ\talum capaotor. Remember that the long lead is the positive one.
t6. To 6Jter the transient current, use a 0.1 µP monolithic capacitor for each IC. Place the 0.1 µF monolithic capacitor
t,etween Vcc and ground of each IC. Make sure the leads are as short as possible.

IC#l IC#2 IC#3 IC#4

figure B-1. Daisy Chain Connection (not recommended for power lines)
-

APPENDIXC

IC TECHNOLOGY AND
SYSTEM DESIGN ISSUES

OVERVIEW

This appendix provides an overview of IC technology and 8051 interfacing. In addition, we


look at the microcontroller-based system as a whole and examine some general issues in system
design.
fin;t, in Section C.l, we provide an overview of IC technology. Then, in Section C.2, the internal
details of 80511/0 porte and interfacing are discussed. Section C.3 examines system desip issues.

t91
f
t
ments in advanced logic.families. s~
. OVERVIEW OF IC TECHNOLOGY major develop the level presented m basic digital
C.1. and diSCUSS som~ lo ic families on
In this section we examine IC technology, . (aJlliliar with g
. .11 ·IS assum ed that the reader 15
this IS an overview,
electronics books.

h J950s, transistors replaced vacuum


Transistors . t Bell Laboratory. Intht et the first integrated circuit was sue-
. . b thr scientists a
The transistor was m,•ented m 1947 Y ee
til 1959 a C h f ·
. ention of the I , t e use o transistors
II was not un
tubes in many electronics systems, including compu:er:~ents. Prior 10 the mv on in computer design. Early trans;;
cessfully fabricate~ and tested by Jack Kilby of:e::~t:rs and resistors, ~"? 5
co~s was due to the fact that the slightest
along with other discrete components such as P d ed in favor of silicon. . t
5
In senuconductor terms it is
tors were made of gcrmani~, which. was later a~n : : germanium-based tr~nsJS or ~assive flow of electrons 'from
rise in temperattue resulted m ~ass'.ve current
because the band gap of germanium 1s much sma1er
f"'
than that of silicon, r~sulttntm;elate 1960s and early 1970s th
rises even slightly. vY . , e
the valence band to the conduction band wh~n the_ temperatu~ minicomputers. Transistors a nd ICs at first were based
use of the silicon-based JC was widespread m mainframes an . much higher (about two and a half times) than
th
on P-type materials. Lateron,dueto thefoct that esp_ eed of electroris 1s
' d. 19705 NPN and NMOS transistors · h a d replaced
the speed of holes, N-type devices replaced P·type devices. By the mi. s du,stry including in the design of microproc-
t
' n

. . of the electronic , .
the slower PNP and PMOS transistors m every sec1or t MOS) has become the dominant technology of IC
essors and computers. Since the early 1980s, CMOS (complemenC:Y d b 'polar transistors. See Figure C-1.
design. Next we provide an overview of differences between M an 1

MOS vs. bipolar transistors


There are two type of transistors: bipolar and MOS (metal-oxide semicond~cto.r). Both have .three leads. ln bipolar
transistors, the three leads arc referred to as the emitter, base, and collector, while m MOS transtStors they are named
source, gate, and drni11. In bipolar transistors, the carrier Rows from the emitter to the collector, and the base is used as a
flow controller. In MOS transistors, the carrier flows from the source to the drain, and the gate is used as a flow control-
ler. Jn NPN-typc bipolar transistors, the electron carrier leaving the emitter must overcome nvo voltage barriers before
it reaches the collector (see Figure C-1). One is the N-P junction of the emitter-base and the other is the P-N junction of
!"'e base-co~ector. The ."oltage bamer of the bas~o~ector is the most difficult one fo r the electrons to overcome (since it
IS reverse-biased) and 1t cause~ the most power dissipation. This led to the design of the unipola r type transistor called
MOS. In N-channel MOS transistors, the electrons leave the source and reach the dram· 'th t · thr h It
· The av..-nce
age ba mer. '-·- . .m the path of the CaJ'rier is one rea
of any ,•oltage barner w1 ou going· · o ug any vo •
power than bipolar transistors The low power dis's· ti f MOS son why MOS d 1ss1pa tes much less
· •pa on o allows ·u· f · · c
chip. ln today's technology, putting 10 million transistors into an IC is co nu ions ~ transistors to £it on a single I
Without the MOS transistor, the advent of. desktop personal mmon, and it is all because of MOS technology.
soon. The bipolaJ' transistors in both the mainframes and mini/ O
mputers would not have been possible, a t least not so
expensive cooling systems and large rooms. MOS transistors d~~::::~eof th_e 1960s and 1970s were b ulky and required
maior dra wback: They are slo,ver than bipolar

- C N
8 p
C
Oxide

E N
E

Bipol,n NPN Trans istor

NMos Trans istor


Figur• C-1. Bipolar vs. MOS Transisto"'

APPENDIX C
transistors. This is du_e partly to the gate capacitance of the MOS transistor. For a MOS to be turned on, the input capaci-
tor of the gate ta.Ices time to charge up to the tum-on (threshold) voltage, leading to a long~ propagation delay.

overview of logic families


Logic fa?'~l~es are judged according to (1) speed, (2) power dissipation, (3) noise immunlty, (4) input/ou~ut inter-
/a~ c~mpahbthty, and (5) cost. Desirable qualities are high speed, low power dissipation,. and high no,~ tmmuruty
(s111ce ti prevents the occurrence of false logic signals during switching transition). In interfacing logic famthes, the ~ore
in~uts that can be driven ~y a single output, the better. This means that high-driving-capability outputs are des,red.
'[his, plus the fact that the .•nput and output voltage levels of MOS and bipolar transistors are not compatible ?'ean th~t
Olle _m~t _ be ~oncem_ed with the ability of one logic family to drive the other one. ~ terms of th~ cost of a given logic
family, ti ts high during the early years of its introduction but it declines as production and use rise.

The case of Inverters


As an example_ of logic gates, we look at a simple inverter. ln a one-transistor inverter, the transisto~ play~ the r~le
of a switch, and R ts the pull-up resistor. See Figure C-2. However, for this inverter to work most effecbvcly tn digital
circuits, the R value must be high when the transistor is "on" to limit the current Oow from V<'C to ground in order to
have low power dissipation (P =VT, where V = s V). Ln other words, the lower the I, the lower the power dissipation. On
the other hand, when the transistor is "off", R must be a small value to Um.it the voltage drop across R, thereby making
su.re that Vour is close to Vcc- This is a contradictory demand on R. This is one reason that logic gate designers use active
componen.ts (transistors) instead of passive components (resistors) to implement the p111J-up resistor R.

Vee Vee Vee

Re Re Re

Out Low ) - - High


In Hlgh Low

Re must be a Re must bea


very high value. very low value.

Figu~ C-2. One-T raruoistor lnv•rt•r with Pull•up Resistor

The case or a TTL inverter with totem-pole output is shown in Figure C-3. ln Figure C-3, Q3 plays the role of a pull-
up resistor.

. - - - , - - - . - Vee ,--..,...--,- Vee

Vee
H,gh

input Input

Fi.... C-3. Tn lan*r with To-·Pol• Output

AIPENoixc
..orr J PMOS
i - -- Output
Input V OV Output
Input
OV sv
5
NMOS
NMOS '"off,.
"on''

Figutt C-4. CMOS Inverter

CMOS inverter
In the case of CMOS-based logic gates, PMOS and NMOS are used to construct a CM_OS (comple~entary MOS)
inverter as shown in Figure C-4. In CMOS inverters, when the PMOS transistor is off, it provides a very high unpedance
path, making leakage current almost zero (about 10 nA); when the PMOS is on, it provides a low resis tance on the path
of V00 to load. Since the speed of the hole is slower than that of lhe electron, the PM OS transistor is ,vider to compensate Hi
for this disparity; therefore, PMOS transistors take more space than NMOS transistors in the CMOS ga tes. At the end
of this section we will see an open-collector gate in which the pull-up resistor is p rovid ed e xternally, thereby allowing
system designers to choose the value of the pull-up resistor.
Sa
Input/output cha racteristics of some logic families 19
In 1968 the. first logic.family ~ ade of bipolar transistors was marketed. It was commonly referred to as the sland- ml
ard TTL (trans,s tor-trans,stor logic) family. The firs t MOS-based logic family the C D4000/ 74C · k d f(
· th
in 1970. The addition of the Schottky diode to the base-collector of bipolar tran'sis tors m I se19~0es, was mar ete Ta
·1 Th "-c k d'od h e ea r y , , s gave nse to the
.S fam, Y· • e .x.nott y I es ortens the propagation delay of the TTL family by reventin h ll ·
into what IS called deep saturation. Table C-1 lists major characteristics of some lo~ f mil ..g t lne cTo ector from gomg

- Table C-1: Characteristics of Some Logic Families


ChaJ"acteristic STD TTL
LSTTL
o•c a

ALS1"fL
,es. able C-1, note that

~ SV 5V
H CMOS

2.0 V
5V sv
2.0 V 2.ov
0.8 V 3.15 V
0.8 V
2.4 V
o.s v 1.1 V
2.7V
2.7V
0.4 V 3.7V
0.5 V
0.4 V
- l.6mA 0.4 V
-0,36mA
40µA -0.2 ll\A
20µA - 1 µA
'"'- 16mA
8mA
20 µA
1 µA
JOH -400µ.A 4mA
--400 µA 4rnA
Propagation delay lOns --400 µA
9.5ns 4 rnA
Static power dissipation (f = 0) IOmw 4 ns
Dynamic power dissipation 2mw 9ns
l mW
JO mW 0.0025 nW

.. 2 mW
lrnW
0.17 mW

APPENOIX C
f able C-2: Logic Family Overview
product Year Static Su pply High/Low Family
Introd uced Sp eed (ns) Current (mA) D rive (mA)
Std 1TL 1968 40 30 - 2/32
cD4K/ 74C 1970 70 0.3 -0.48/6.4

~ /5 1971 18 54 - 15/24
ttC/ HCT 1977 25 0.08 -6/- 6

FAST 1978 6.5 90 - 15/64

AS 1980 6.2 90 - 15/64

ALS 1980 10 27 - 15/64


AC/ACT 1985 10 0.08 - 24/ 24
FCT 1986 6.5 1.5 -15/64
Reprinted by permission of Electronic Design Magazine, c. 1991.

as the CMOS circuit's operating frequency rises, the power dissipation also increases. This is not the case for bipolar-
based TTL.

History of logic families


Early logic families and microprocessors required both positive and negative power voltages. In the mid-1970s,
5 V Vcc became standard. In the late 1970s, advances in IC technology allowed combining the speed and drive of the
Sfamily with the lower power of l.S to form a new logic family called FAST (Fairchild Advanced Schottky TTL). In
1985, AC/ ACT (Advanced CMOS Technology), a much higher speed version of HCMOS, was introduced. With the
introduction of FCT (Fast CMOS Technology) in 1986, the speed gap between CMOS and TTL at last was closed. Since
FCT is the CMOS vers ion of FAST, it has the low power consumption of CMOS but the speed is comparable with ·rrL.
Table C-2 provides an overview of logic families up to FCT.

Recent advances In loglc famllles


As the speed of high-performance microprocessors reached 25 MHz, it shortened the CPU's cycle time, leaving
less time for the path delay. Designers normally allocate no more than 25% of a CPU's cycle time budget to path delay.
Following this rule means that there m ust be a corresponding decline in the p ropagation delay of logic families used
in the address and data path as the system frequency is increased. In recent years, many semiconductor manufactur-
ers have responded to this need by providing logic families that have high sp eed , low noise, and high drive 1/ 0.
Table C-3 provides the characteristics of high-per formance logic families introd uced in recent years. ACQ/ ACTQ are

Table C-3: Advanced Logic General Characteristics


Number Tech 1/0 Level Speed (ns) Static 1o./IoL
Family Year
Base Current
Suppliers
-ACQ 2 CMOS CMOS/CMOS 6.0 80µA -24/ 24mA
-ACTQ 1989
2 CMOS TTL/CMOS 7.5 80 µA - 24/ 24mA
1989
CMOS TTL/ CMOS 4.1 - 4.8 l.5mA - 15/64mA
-
fCTx 1987 3
2 CMOS TTL/TTL 4.1 - 4.8 1.S mA - 15 / 64mA
-
fCTxT 1990
TTL/ TTL 3.9 SOmA - 15/64 mA
--8CT
FASTr 1990
1987
l
2
Bipolar
BICMOS TTL/ TTL 5.5 l OmA - 15 / 64mA
P.ti,,u,~ by penni.ton of Elec:trOnlc Design Magazine, c. 1991.

495
APl'!Notxc
. . . - - - . - - , , Vc.c
(ACMOS) with much
the second-generation advanced CM OS . J ACTQ External
. CQ h th CMOS input 1eve '
lower noise. While A as e CTx-T are pull-up
,s equipped with TTL-lev~l input. Th~ FCTx and ~e "x" in resistor
second-generation FCT w ith much higher speed. ch as
the FCTx and FCTx-T refers to various speed grades, su h" h Input Output
A, B, and C, where A means low speed ~nd C meansF;~T
speed. For designers who a re well verse~ m ~s~n g the an
logic family, FASTr is an ideal choice smce 1t 1s faster th
FAST, has higher driving capability (Joi/ 10 ")'. and. ~rodu::~
much lower noise than FAST. At the time of this writing. n
to ECL and gallinm arsenide logic gates, FASTr is the fastest
logic family in the market (with the 5 V Vc,:), but the power
consumption is high relative to other logic families, as shown
.in Table C-3. The combining of high-speed bipolar TTL and
the low power consumption of CMOS has given birth to what Figure C-5. Open Collector
is called BICMOS. Although BICMOS seems to be the future
trend in IC design, at this time it is expensive due to extra ste~s
required in BICMOS IC fabrication, but in some cases there 1s
no other choice. (For example, Intel's Pentium microprocessor, a BIC~OS produ ct,
had to use high-speed bipolar transistors to speed up some of the mtemaJ func· External
tions.) Table C-3 provides advanced logic characteristics. The "x" is for differen t pull-up
speeds designated as A, B, and C. A is the slowest one while C is the fastest one. resistor
The above data is for the 74244 buffer.
Since the late 70s, the use of a +5 V power supply has become standard in all
microprocessors and microcontroUers. To reduce power consumption, 3.3 V V e<:
is being embraced by many designers. The lowering of Vc.c to 3.3 V has two major
advantages: (1) it lowers the power consumption, prolonging the life of the ba ttery
in systems using a battery, and (2) it allows a further reduction of line size (design
rule) to s ubmicron dimensions. This reduction results in putting more transistors in a
9
given d.ie size. As fabrication processes improve, the decline in the line size is reach- Figure C-6. O pen Drain
ing submicron level and transistor densities are approaching 1 billion transistors.

Open-collector and open-drain gates


To allow multiple outputs to be connected together we use O en -coll ·
- resistor will serve as load. This is shown in Figures C-S a'nd C _ _ P ector logic gates. In such cases, an external
6

SECTION C.2: 8051 VO PORT STRUCTURE AND INTERFACIN


In interfacing the 8051 microcontroUer with other IC ch" d . G
~ders~and the8051 fan-out we must first unders tand the 0 ~ps or evices, fan-out is the most important issue. To
discussion of the 8051 port structure and its fan-out. It is ~e t stru.cture of the 8051. This section rovides ad t .
the 8051 lest we damage it while trying to interface 1.t .th ry critical that we understand the I/ PO e ailed
w1 an external device. port structure of
' IC fan-out
. ~\/hen. connecting IC chips together, we need to find out
pm. This 1s a very important issue and involves the dis how many input pins can b .
be addressed for both logic " O" and logic " l " outp cuss1on of what is called IC e dnven by a single output
as follows: uts. Fan-out for logic low and f fan-out. The IC fan-out must
J an-out for logic high are defined
fan-out (of low) ~ !.l1I.. fan-out (of high)"'~
I 11. I
"'
Of 11w above two values, the lower number is used
1111d IOU!dng of current when !Cs are connected to thto ensure the proper .

.. ge er. noise margin p·


· igure C-7 show s the sinking

APPENDJXC
High j j j Low

1o H
" Off'
( (~ (
"On"
(
Ill !IL l1L !Di } IIH ) Im }
....
"On"

\lot
l oL = I]IL
VOL = ~ (transistor) x IOL
"OW'
loH = I: (IH

figutt C-7. Current Sinking and Sourcing in TIL


\

ExampleC-1
Find how many unit loads (UL) can be driven by the output of the LS logic family.

Solution:
'
The unit load is defined as I,,_= 1.6 mA and 1,,. = 40 µA. Table C-1 shows Io,.• 400 µA and I = 8 mA for the LS
family. Therefore, we have OL
\·.
fan-out (low) .. Ia .. 8mA =5
111 L6mA

fan-out (high) "'


Ia. 400pA •18
1,, 40pA

This means that the fm-olitls 5. li\ ~ words, the LS output must Nltbe'wlaihlled*'mmetban S Inputs with
unit load cha~c:11-

'
Notice that in Figure C-7, as the number of input pins connected to a single output increases, IOI. rises, which causes
Va. to rise. If this continues, the rise of VOL makes the noise margin smaller, and this results in the occurrence of false
logic due to the slightest noise.

74LS244 and 74LS245 buffers/drivers


In cases where the receiver current requirements exceed the driver's capability, we must use buffers/drivers such
as the 74LS245 and 741.$244. Figure C-8 shows the internal gates for the 74l.S244 and 74LS245. The 74l.S245 is used for
bidirectional data buses, and the 74l.S244 is used for unidirectional address buses.

ld'PENntxc •
/
Vee GNDB1
Al ,----,-B;;::2:,
I
Ve,;
-
IG A2 L..--;J--N B3
A3
IA-I IY-1 B4
A4 BS
lA-2 IY-2
A5
B6
IA-3 lY-3 A6
A7 B7
lA-4 lY-4
BB
I{ A8 '-r'l"l C·
2Y-1 (~
2A-l

2A-2
.", 2Y-2
DIR
Direetion Enable
control
2A-3 2Y·3
.," 2Y·4
Function Table
2A-4 ~ Direction control
Enable G DIR OnPration
- L L B Data to ABus
CND IC H A Data toB Bus
L
I
, H X Isolation

Figure C-8 (;i). 74LS244 Oct.J Buffer Figitrt C-a (1>). 74LS245 Bidfrectional Buffer
(Reprm1ed by permi>.5ion or Toxas lnstrume,,18, Copyright Texas (!«,printed by permission o( Texas Instruments, Copyright Texas Reldir
mstruments. 1988) lnstrumenl8, 1988)
As¥

LT"
Tri-state buffer Ii.at bit.
Notice that the 74t.5244 is simply 8 tri-state buffe_rs in a single (A) (b)
chip. As shown in Figure C-9 a tri-state buffer ha.s a ~mgle tnput, a Out t Ase
Tri-state H
single output, and the enable control input. By acbvating the enable, control The
~
data at the input is transferred to the output. The ena?le can be an (active high) .' Sine

- active-low or an active-high. Notice that the enable tnput for the


74LS244 is an active low whereas the enable input pin for Figure C-9
is active high.
(c) ~
• , H (d) -1?:-
y' Low
l

I Wh,
Wh,
lllp1

74LS245 and 74LS244 fan-out


H.igh-impedence ln 0
It must be noted that the output of the 741.S245 and 741.S244 can (open-circuit) Tll1
sink and source a much larger amount of current than that of other and
• LS gates. See Table C-4. That is the reason we use these buffers for
driver when a signal is travelling a long distance through a cable or
Figure C-9. Tri-Sute Buffer

it has to drive many inputs.


After this background on the fan-out, next we discuss the struc- Table C-4: Electrical Specifications for
ture of 8051 ports. We first discuss the structure of Pl - P3 since their Buffers/Drivers
structure is slightly different from the structure of PO.
74LS244
P1 • P3 structure and operation 3
74LS245 12
Since all the ports of 8051 are bidirectional they all have the foll . '"-- _ 3 12
I. D latch owing uu,:e components in their structure;
2. Output driver
3. Input buffer

APPENDJXC
Vcc
Read latch
,. TB2 Load (Ll )
" L.. ~

Internal Pl ·X
CPU bus D Q pin
Pl·X
Write to latch CJk Q
-
: ~Ml

TB1
l
Read pin

figuttC·lO. 8051 Port 1 Structure

Figu~e C-10 shows _the structure of Pl and its three components. The other ports, P2 and P3, are basicaUy the ~me
except with e xlTa c,rcwtry to allow their dual functions (see Chapter 14). Notice in Figure C-10 that the Ll load 1s an
internal load for Pl, P2, and P3. As we will see at the end of this section, that is not the case for PO.
Also notice that in Figure C-10, the 8051 ports have both the latch and buffer. Now the question is, in reading the
port, are we reading the status of the input pin or are we reading the status of the latch? That is an extremely important
question and its answer depends on which instruction we are using. Therefore, when reading the ports there are two
po55ibilities: (1) reading the input pin, or (2) reading the latch. The above distinction is very important and must be
understood lest you damage the 8051 port. Each is described next.

Reading the input pin


As we stated in Chapter 4, to make any bits of any port of 8051 an input port, we first must write a 1 (logic high) to
that bit. Look at the following sequence of events to see why.

I. As can be seen from Figure C-11, a 1 written to the port bit is written to the latch and the D latch has "high" on its Q.
=
Therefore, Q 1 and Q = 0.
2. Since Q = Oand is connected to the transistor Ml gate, the Ml transistor is off.
3. When the Ml transistor is off, it blocks any path to the ground for any signal connected to the input pin and the
input signal is directed to the tri-state TBl.
4. When reading the input port in instructions such as "MOV A, Pl• we are reaUy reading the data present at the pin.
In other words, it is bringing into the CPU the status of the external pin. This instruction activates the read pin of
TBI (tristate buffer 1) and lets data at the pins flow into the CPU's internal bus. Figures C-11 and C-12 show high
and low signals at the input, respectively.

Vee
Read latch - - - - ,
TB2 Load (Ll)

High
Internal __..,~--1.fn- nl-_J Pl ·X
CPU bus D Q 'I' pin
Pl ·X '0'
Write to latch - ~ - - l Ok Q 1 - - - - - - - 1
Off

Read pin _ _ _., TBI

Figure C·lL Reading #High" at Input Pin

APl'ENorxc
/
Vee
1.,oad (LI)
Read latch - - - , TB2
~t-.'..::---i Low
Pl ·X
'I' pin
Internal - +-- 0 Q
CPU bus Pl ·X 'O' Ml
Write to latch --<C..---1 Clk Q~ - - - ~

~
Off

Read pin _ __., Tlll 0t(ft


Figure C-12. R..djng •1..ow• •t tht lnput Pin ,,,..-
Writing "O" to the port t' b·ts m
· order to make it an input port.
The above discussion s howed why we mus t write•.

11
ru gh" to a por
.
s 1 •
t port? From Figure C-13 we see that if
What happens if we write a "O" to a port that ~as conf,gured ~5
1
i°5
'.:'~Uthe Ml transistor is "on". If Ml is "on,"
we write a O(low) to port bits, then Q = 0 and Q = 1.. As a re~\l ~ for~ an attempt to read the input pin will
it provides the path to ground for both LJ and the input pin. f there ; p ·J This can also damage the port, as
always get the "low" ground signal regardless of the s tatus o e 1npu 1 ·
e,cplained next.

Avoid damaging the port


rptC-1!
We must be very careful when connecting a switch to an input port of the 8051. This is due to the fact that the wrong
kind of connection can damage the port. Look at Figure C-13. If a switch with v,, and ground is connected directly to
the pin and the Ml transistor is "on" it will sink current from both internal load Ll and external Vcc· This can be too
much current for Ml , which will blow the transis tor and, as a result, damage the port bit. There aie several ways to
avoid this problem. They are shown in Figures C-14, C-15, and C-16.

- I.

2.
One way
Figure is to have a lOK-ohm resistor on the Vcc path to limit current flow through the Ml transistor. See
C-14.

The second method is to use_a switch with a ground only, and no Vee, as shown in Figure C-15. In this m ethod we
read a low when the SW1tch 1s pressed and we read a high when it is released . '

. Read latch Vee


TB2

Internal
ll Load {LI) T
CPU bus D Q '\ __/ Vee
'O'
Pl·X
Write to latch 'I'
Clk Q
On tMI Pl·X
pin

Read pin -~=-:=.=:,fJ"-:TBrait______ __:~_J wiU damage Ml

Figu,e C-13. Never Conntct Dirttt Vtt to lht 8051 Port Pin

APPl!NDIXC
Read latch Vee

J TB2 Load {Ll) - Voc


..... 10K
'--
Internal

~
CPU bus D Q
Pl ·X
Pl·X pin
Write to latch Clk Q
-
;~
A

Read pin I" TBl

. .
figute C·14. lnput Switch with Pull-Up Resistor

Vee
Read latch .
~ TB2 Load {Ll)

,
L-
..L
Internal
CPU bus D Q
Pl ·X Pl·X
Write to latch Clk Q • Ml pin
'
/I
&
I" TBl
Read pin

.
figure C·lS. Input Switch with No Vcc

Voc
Read latch
TB2 Load (Ll) Voc

lntema.l
74l.S244 b
CPU bus D Q
Pl·X Pl ·X
Ml pin
Write to latch Clk Q

Read p i n - - ~ TBl

Figure C-16. Buffering Input Switch with Direct Vcc

3. Another way is to connect any input switch to a Table C-5: Instructions Reading the Status of
74LS244 tri-state buffer before it is fed to the 8051 Input Port
pin. Trus is shown in Figure C-16. Examples
Mnemonics
The above points are extermely important an~ MOV A,PX MOV A,Pl
must be emphasized since many people damage thetr JNB PX. Y, ... JNB Pl.2,TARGET
ports and wonder how it happened. We must also use
JB PX.Y, ... JB Pl.3,TARGET
the right instruction when we want to read the status
~f an input pin. Table C-5 shows the list of instruc- MOV C,PX.Y MOV C,Pl.4
hons in which reading the port reads the status of the CJNE A,PX, ... CJNE A,Pl,TARGET
tnput pin.

>.Pt>!No1Xc
Vee
JL- Load (Ll)
Read latch • T82
-- Pl ·X
pin
Internal D Q
CPU bus Pl·X I ~II
Ok Q
I
Wnte to latch
\1
,,
T61
Read pm (olf)

figure C-17. Reading th• Latch

Reading latch h d the lalch we next consider the case


. . d the port and ot ers rca , . ds th
Since, in reading the port, sorne u\Struchons rca • • . example of an instruction that rea e
of readlng the port where it reads the internal port latch: ANLk'Pl' ~ac~ :en an instruction such as "ANL Pl, A" is
latch instead ol the input pin. Look at the sequence of actJons ta mg P
e~ecuted. .
· c
7) d b ·
1. The read latch activates the tri•statc buffer ol TB2 (Figure · 1 an nn~ e
th data from the Q latch into the CPU.

2. This data 1s ANDed with the contents of register A.


3. The result is rewritten to the latch.
After rewnting the result to the latch, there are two possibilities: (1) If Q = 0, then O= 1 and Ml is "on," and ~e
=
output pin has "O," the same as the status ol the Q latch. (2) If Q l , then Q = 0 and the Ml is "off," and the output pm
has · 1,• the same as the status o( the Q latch.
From the above discussion. we conclude that the instruction that reads the latch normally reads a value, performs
an operation (possibly changing the value), and rewntes the value to the latch. This is often called "read-modify-write."
.-c-
Table C-6 provides a list ol read-modify-write instructions. Notice from Table C-6 that all the read-modify-write instruc-
tions u,e the port as the destination operand. 1161 ft

PO structure
Table C-6: Read-Modify-Write Instructions
A major difference between PO and other ports is
that PO has no intemal pull-up resistors. (The reason is to Mnemonics Exam.pie
allow it to multiplex address and data. See Chapter 14 for ANL
ANL Pl,A
a detailed discussion of address/data multiplexing.) Since ORL
PO has no Ullemal pull-up resistors, ,t is simply an open- ORL Pl,A
drain as shown in Figure C-18. (Open-drain in MOS is the XRL
XRL Pl,A
same u open-coUector in TTI.). Now by writing a •1• to JBc
the bit latch, the Ml transistor is "off• and that causes the -
CPL
Jl!C Pl.l,TARGBT
pin to lloaL That is the reason why when PO is used for CPL Pl.2
simple data 1/0 we must COMect it to extemal pull-up INC
resistors. As can be seen from Figures C-18 and C-19, (or -
DEC
INC Pl
a PO bit to dri,·e an input. there must be a pull-up resistor
to source current.
-DJNz DEC Pl
Notice that when PO ts used for address/data mu]. -MOV PX.Y,C DJNz Pl , TARGET
tiplexing and i_t is conntcted to the 74lS373 to latch the
addn!,Js, there IS no need for external pull-up resistors as HOV Pl.2,C
~LR PX.Y
shown in detail in Chapter 14. '
-
SET& PX. y CLR Pl.3

- SBTB Pl. 4

4ff1ND1XC
Read latch
• TB2

Internal PO·X
CPU bus D Q pin
PO·X
Write to latch Clk Q
- : ~ Ml

Read pin
<'! TBl

Figure C-18. PO Structure (notice open-drain)

Vee
Read latch - - - -
TB2 External
lOK pull-up
resisto r
Internal 1--- - - PO·X
CPU bus _ ._----1 D Q
pin
PO·X
Write to latch -+---! Clk Q 1 - - - - -- - 1 Ml

Read pin - -- - ' TBl

Figure C-19. PO With External Pull-Up Resistor

8051 fan-out
Now that we are familiar with the port structure of the 8051, we need to examine the fan-out for the 8051 micro-
conctroller. While the early 8051 microcontrollers were based on NMOS IC technology, today's 8051 microcontrollers
are all based on CMOS technology. However, note that while the core of the 8051 microcontroller is CMOS, the circuitry
driving its pins is all TTL compatible. That is, the 8051 is a CMOS-based product with TTL-compatible pins.

P1, P2, and P3 fan-out


The three ports of Pl, P2, and P3 have the same l/0 structure, and therefore the same fan-out. Table C-7 provides
the 1/0 characteristics of Pl, P2, and P3.

Table C-7: 8051 Fan-out for Pl, P2, P3


Port Ofan-out
PO requires external pull-up resistors in o~er to drive ~ input Pin Fan-out
since it is an open drain I/0. The value of this resistor deades the IOL l.6mA
Ian-out. However, since Io,_= 3.2 mA for VoL = 0.45 ':', we must make !OH 60µA
sure that the pull-up resistor connected to each pm of the PO is no
less than 1422 ohms, since (5 V - 0.45 V) I 3.2 mA = 1422 ohms. llL SOµA
ln applications in which PO is not connected to an external pull-up IDi 650µA
resistor, or is used in bus mode connected to a 74LS373 or other chip, Nair. Pl. P2.u1d P3c.ndrivtupto4 LSTil. inputs wi..
it can drive up to 8 lS TTL inputs. connectod to olJ,er JC chip.

APPENorx c
,
• 74LS244
8051
74LS244 driving an output pin . . ,. g multiple infuts,
when an 8051 port 1s dnHn e (e.g., printer ,----1---T14 >--t-- DO Printer
data
In many cases . ut via a long wire or cab! driving an Pl D7 port
or driving a single ,npthe 74l.S244 as a driver. When your 8051
cable), we need to use. h 74l.S244 buffer betw~e~ urrent.
off-board circuit, plac,n.g I ~ th 8051 lacks sufficient c
and the circuit is essential since e
See figure C-20.

P2.tf---~ t---ACK
SECTION C.3: SYSTEM DESIGN ISSUES d ·gn
. related to system es1
In addition to fan-out, the other ,ssu~ bounce, crosstalk, and
are power dissipation, ground bounce, ~e an overview of these
. ·on lines· In this section we prov,
transm1SS1 74LS244
topics.
.
Figure C•20 · 8051 Connection to Printer Signals
P r dissipation considerations . .
owe
Power dissipation of a system .,s a ma1or
. concem in of which . the power . Power dissipation 1s a
systembatteries provide
desi ers, especially for laptop and hand-held sy~tems
func':::m of frequency and voltage as shown b~o:"cv

since and l=Q


T Asw•
I= CVF 11he ind
/IOW P= Vl=CV'F ldtage d
li!aken l
In th bove uations the effects of frequency and Vcc voltage should be noted. While the power d issipation
1 The '
goes C-2. :Ith freq~ency, the impact of the power supply voltage is much more pronounced (squared). See
up ::n:arly
Example
14-pi

- Dynamic and static currents


gale!
a 14-
tradi
Two major types of currents flow through an IC: dynamic and s tatic. A dynamic current is I = CVF. It is a function
of the frequency under which the component is working. This means that as the frequency goes up , the dyn amic current
and power dissipation go up. The ~ta tic curre~t, ~lso ~aUed DC, is ~e current consumption of the com ponent w h en it is
inacti"e (not selected). The dynamic current ~,ss,pa.tion is much higher than the s tatic current consumption. To red uce
... power consumption, many nucrocontrollers, including the 8051, have power-saving modes. In th e 8051, the power sav-
ing modes are called idle mode and power down mode. Each one is described next.

Ex•mple C-2

Compttt the powier consumpt1on of two 8051 S)'Stell1s. ~ USes s v and the other
Solatlon:
llle8 3 V for Vcc·
Since P • VI, by subetilullng I • V/ R we hive P • V'/ R. AM.-,--
whichmean,"°""-;;;;;:,'!:_a,;6125
1• have P • 5' • 25 Wand p • 32 w.
~
l'hll l9Ulla in 111ing 16 W 1-power, We a 9

.. JC lOO) for 'J 13 IW llling 3 V for powa

APPENOJXC
/dtemode
In idle °:'ode, whic~ is also called sleep mode, the core CPU is put to sleep while all on-chip peripherals, such as the
serial port, tuners, and interrupts, remain active and continue to function. In this mode, the oscillator continues to pro-
vide clock to the serial_Port, interrupt, and timers, but no clock is provided to the CPU. Notice that during this mode all
Ille contents of the registers and on-dtip RAM re.m ain unchanged.

power down mode


In the power ~own mode, the on-chip oscillator is frozen, which cuts off frequency to the CPU and peripheral func·
tions, such as Sena] ports, interrupts, and timers. Notice that while this mode brings power consumption down to an
absolute minimum, the contents of RAM and the SFR registers are saved and remain unchanged.

Ground bounce
One of the major issues that designers of high-frequency systems must grapple ,vith is ground bounce. Be~ore we
define ground bounce, we \¥ill discuss lead inductance of IC pins. There is a certain amount of capacitance, resistance,
and inductance associated with each pin of the IC. The siZe of these elements varies depending on many factors such
as length, area, and so on.
The inductance of the pins is commonly referred to as self-inductance since there is also what is called 11111t11a/ induct-
ancr, as we will show below. Of the three components o f capacitor, resistor, and inductor, the property of self-inductance
is the one that causes the most problems in high-frequency system d esign since it can result in ground bounce. Ground
bounce occurs when a massive amount of current flows through the ground pin caused by many outputs changing
from high to low all at the same time. See Figure C-21(a). The voltage is related to the inductance of the ground lead as
follows:

V =L!!i_
dt
As we increase the system frequency, the rate of dynamic current, di/dt, is also increased, resulting in an increase
in the inductance voltage L (di/dt) of the ground pin. Since the low state (ground) has a small noise margin, any extra
voltage due to the inductance can cause a false signal. To reduce the effect of ground bounce, the following steps must
be taken where possible.
I. The Vcc and ground pins of the chip must be located in the middle rather than at opposite ends of the IC chip (the
14-pin ITL logic IC uses pins 14 and 7 for ground and Vcc>· This is exactly what we see in high-performance logic
gates such as Texas Instruments' advanced logic ACllOOO and ACTllOOO families. For example, the ACT11013 is
a 14-pin DIP chip in which pin numbers 4 and 11 are used for the ground and V<X! instead of 7 and 14 as in the
traditional TIL family. We can also use the SOIC packages instead of DIP.

DO
Vout
OJ

02
Tune
03

1ccL

Ground
Ground bounce occurs when data Translent current going from O to 1
switches from all ls to all Os

Fla,u. C-21. t.) GIOIIJld 8 - (bl Transient Cunent

APPENDIXC
l
'ble to reduce the lead length. This is exactly .All
ii' ~
d d V as pass1 d d . ~r -

2. Another solution is to use as many pins for groun .an/arn/rres use many pins for Vcc ;inp groun instead of the
why all high-performance microprocessors and 1ogtc 1 in the case of Intel s entilllll processor there ~·
traditional single pin for Vcc and single pin for GND. For exarnp e, of tl'
. for. ground, and another .SO pins for V. cc· v when a large numb er o f ou tp u ts change.s ftom
are over 50 pins -"'l'
,..iii'
The abothvehi~h10n of ground bounce 1s al~~ apphcab~~evtoer ~e effect of y cc bounce is not as severe as ground p .
8
th e !ow to e g state·' this is referred to as Vcc wu11ce. o-. ' ("0") state :rt•
v·<>
bounce since the high ("l ") state has a wider noise margin than the low · al'cl
tt30
5
Filtering the transient currents using decoupling capacitors i01'
tn the TfL family, the change of the output from low to high can cause.what is called ~ransient current. In a totem-
pole output m which the output is low, Q4 is on and saturated, whereas Q3 1s off. By changtn? the output fron1 the low
to the high state, Q3 turns on and Q4 turns off. This means that there is a time when both transtStors are on and drawing
~rent from Vcc- The amount of current depends on the Ro,, values of the two transistors, which~ tum depend on the
mtemal parameters of the transistors. However, the net effect of this is a large amount of current 1n the form of a spike
for the output current, as shown in Figure C-21(b). To filter the transient current, a 0.01 µFor 0.1 µF ceramic disk capaci-
tor can .be pl?ced between the Vcc and ground for each 1TL JC. However, the lead for this capacitor should be as small
as poss'.ble.smce a long lead results in a large self-inductance, and that results in a spike on the Vcc line [V = L (di/ dt)J.
Thisbulk sdpike lS ~ed Vcc, bounce. The ceramic capacitor for each IC is referred to as a decoupling capadtor. There is also a
ecoupl1ng capaotor, as described next.

Bulk decoupling capacitor


the :;;a;y~C chips change state at the same time, the combined currents drawn from
board hs ccUpothwersupplycanbemassivea11dmaycauseaOuctuationofV on the
w ere a e ICs are mounted T limin thi cc
tantalum capacitor is placed behveen· tho ~ ate s, a r.e latively l~ge decoupling
of this tantalum capacitor varies depend~ a: •;dground lines. The size and location
amount of current drawn by each IC b i~~ ?n e number of ICs on the board and the
capacitor for each of the 16 devices '1 ~~common to have a single 22 µF to 47 µF
•P" hveen the Va: and ground lines.

Crosstalk Figure C-22. Crosstalk (EMT)


~rosstalk is due to mutual inductan
self-tnductance, which is inherent in a p ce. ~ Figure C-22. Previously, we discussed

- :r1 ~ ~lecbic lines running parallel toe:::th:n:ctor. Muh,al i11d11ct1111ce is caused


, e ength of two conductors runnin . · e mutual inductance is a fun .
the m~um material placed between th~: ~allel, d, the distance between th Ction
mcreastng the distance between the rall 1' e effect of crosstalk can be redem, and
they will be traces). In man . pa e or adjacent lines (in . . . uced by
cated ground for each sisnii.c:r~guch as pdrmter and disk drive ~~:i:cu,.t boards, Ringing

.. the effect of crosstalk. This m


are a V and GNO .
inlerfer~nce). This if';;, ~~:;o~·t
. groun lines (ti:aces) betw . ' ~ lS a dedi-
ethod is used even in some ACT I ee.n Stgnal lines reduces
other. Crosstalk is also cal:~families where there
capacitive coupling between::: od.ESI (electrostatic interferen ) Ml (electromagnetic
Buffer
o a iacent conductors. ce , which is caused by
Series terllli.nation
Transmission line ringing
The square wave used in di . . . .
pulse and man harm · gttal orcuits lS in reality
not aU the h._n:onics :S~~f. v~ous amplitudes. When~ e .of a sing le funda

:i~:.':o 1
;~uses
fU::e !is w~at ~ ~~ ~~~;h:~:citan:~~~:~~ on th:~~
drivers are termina~ ;ver, ~ong other factors. To redu depends on the thl : d resist-
~
are three major methoo!o~::!.lindg resistor at the end oft~~~ effect of rinc,;~ ess and
e rtve.r termination· p e u,1e. See Figu ou,g, the line
Para11e1lerrnination
· araIlei, serial re C-23. 1n
...._ , and Theve . ere Figu~ c
....., nm. Trana •23. · Reducing
OU..ton Line Ringing

APPENDIX C ....
)
APPENDIXD

FLOWCHARTS AND
PSEUDOCODE

OVERVIEW

This appendix provides an introduction to writing ftowchans and pseudocode.


(Terminal) (
FLOWCHARTS . ses you are pro bably famil·
If you have taken any previous progr~g cour ' esent different types
iar with Oowcharting- Aowcharts IISe graphic symbols to r'J:r into a flowchart to
'
l

of program operations. These symbols are connected toge er e of the more com·
show the flow of execution of a program. Figure 0-1 shows :m draw the sy.m· Process
monly used symbols. Aowchart templates are available to h P you
bols quickly and neatly. l

PSEUDOCODE
flowcharting has been standard practice in industry for decad~- However,
some find limitations in using nowcharts, such as the fact that you can t ,vnte much
in the little boxes, and it is hard to get the "big picture" of what the progra.m does
without getting bogged down in the details. An alternative to using flowcharts
is pseudocode, which involves writing brief descriptions of the Oow of the code.
Figures D-2 through D-6 show flowcharts and pseudocode for commonly used con-
trol structures.
Structured programming uses three basic types of program control structures:
Subroutine
sequence, control, and iteration. Sequence is simply executing instructions one after
another. Figure D·2 shows how sequence can be represented in pseudocode and
flowcharts.
Figures D-3 and D-4 show two control programming structures: If-THEN-ELSE
and IF-THEN in both pseudocode and flowcharts.

Input/
Output

Statement 1
Connector
Statement 1
Statement 2
Statement 2
0
Figure D·l. Cornmonly Used

... figure D-2. SEQUENCE Pseudocode versus Flowchart


Flowchart Symbols

...
I F (condition) THEN r---<CCondition..,.__
Statement 1 ? No
Condition
ELSE ?
Statement 2
Statement 1 IF (condit ion) 'l'H£N Yes
Statement 2
State1t1ent
Statement

....... D-3. IF TH!?N ELSE i'Hudoeode

.. •er1u1 Flowchart
Figure 0-4 {F
· THEN p
-docode V"9ua Flowcbut

APPENDIXD


Note in Figures D·2 through D-6 that "statement" can indicate one statement or a group of statements.
figures D-5 and D-6 show two iteration control structures: REPEAT UNTIL and WHILE DO. Both structures exe-
cute a statement or group of statements repeatedly. The difference between them is that the REPEAT UNTIL structure
4 Jways executes the statement(s) at least once, and checks the condition after each iteration, whereas the WHILE DO
may not execute the statement(s) at all since the condition is checked at the beginning of each iteration.
Pro~arr_i D-1 finds the sum of a series of bytes. Compare the flowchart versus the pseudocode for Pro~an, D-1 I

(shown m_F'.~~e _D-7). In this example, n,ore program details are given than one usually finds. For example, this shows
steps for wtiabzmg a.i:'d decrementing counters. Another
programmer may not mdude these steps in the flowchart
or pseudocode. It is important to remember that the pur-
pase of flowcharts or pseudocode is to show the flow of count • S
the program and what the program does, not the specific Address • 40H
Assembly language instructions that accomplish the pro- Repeat
gram's objectives. Notice also that the pseudocode gives the Add next byte Count= 5
Increment addreeo
same information in a much more compact form than does Oecrement eoun ter
Address • 40H
the flowchart. It is important to note that sometimes pseu-
docode is written in layexs, so that the outer level or layer Until Count • 0 !
shows the flow of the program and subsequent levels show store sum Add OM byte
more details of how the program accomplishes its assigned
tasks.

increment addres.s
pointer

Statement
REPEAT
Statement Decrement COUJ\teT

UNTIL (condition)
No
'----<Cond ition No
? Count
=07
Yes
v..

Figure D-5. REPEAT UNTIL Pseudocode versus Flowchart Store sum

( Stop )

Figure D-7. Pseudocode versus Flowchart for Program D-1


No
Cond ition
llilILE (condition) DO
7
Statement
Yes CLR A ;A ~ 0
MOV R0 , #40H ;addre ss
Snitement MOV R2 , #5 ; counte r
BACK: ADD A, e RO
INC RO
DJNZ R2,BACK
NOV B,A

Fig,a~ D1. WHILE DO PMudocod1t .,_.,. flowchart Progt- D-1

511
Al'PENDIXD
~

.
'

'
"'

APPENDIXE
••..
' .
• •

8051 PRIMER FOR X86 •


. ·,
PROGRAMMERS •

k ••
-.,,.'
. .'"'..
t
.. •

8051 .'
X86 •
~ J'•
• ...
8-bit registers: AL, AH, BL, BH, CL, CH, DL, DH A,B,RO, Rl, R2, R3, R4, RS, R6, R7 ..'
..' .••

16-bit (data pointer): BX, 51, DI DPTR


Program Counter: fP(16-bit) PC (16-bit) •
.'
Input:
, ..
MOV DX,port addr MOV A,Pn ;(n•0-3)
IN AL,DX I

Output:
MOV DX.port addr MOV Pn,A ; (n • 0 - 3)
..
OUT DX,AL

Loop:
DEC CL DJNZ R3,TARGBT : ,
JNZ TARGET (Using RO-R7) • •

Stacie pointer: SP(l6-bit) SP(8-bit)


As we PUSH data onto the stack, As we PUSH data onto the atllek, • ...
it decrements the SP. it increments the SP.
• • •
As we POP data from the stack, As we POP data from the &tllek.
it increments the SP. it decrements the SP.

Data movement:
From the code segment: •
MOV AL,CS: [SI) MOVC A, eA+ PC
From the data segment:
MOV AL, [SI] MOVX A, liDPTR

From RAM: ••
MOV AL, [Sl] MOV A,liRO •
• •
(Use 51, DI, or BX only.) (Use RO or Rt only.) ' '••
To RAM: • {
MOV [SI] ,AL MOV eRO,A
••
• ••
•.
• '
APPENDIXF

ASCII CODES

Ctrl Dec Hex Ch Code Doc Hex Ch Dec Hex Ch Dec Hex Ch

•11 e 88 HUL 32 211 64 48 I! 96 68
•A 81 SOH 33 21 65 11 A 9? 61 a
·e
1
2 l!2
!iii
II STX 31 22 ..
!
66 42 8 98 62 b
"C
·o
3
..s 83 •

ETX 35 23
• 6? 43 C 99 63 C

•E
114
85 .. EOT
EHQ
36
3?
24
25
$
X
68
69
44
45
D
E
180
181
64
65
d

•p
•c
6
?
86
II?
•• BEL
ACK 38
39
26
2? '•
?9
?1
46
4?
p 182 66 f
G 183 6? g
"H 8 88 Cl BS 411 28 ( ?2 48 H 184 68 h
·1 9 119 0 HT 41 29 ) ?3 49 I
·J 18 8A 9 LP 42 185 69 i
·x 11 OB 6 UT
2A • 74 4A J 186 6A j
43 28 • ?S
•L 48 )( 18?

-
12 IIC $ PP 44 2C 68 k
." 13 OD I CR
so
45 2D -
• ?6
??
4C
4D
L 188 6C
.. 1
"N
-0
•p
14
15
16
BE
8P
18
/I

SI
46
17
2E
2P ;
. ?8
?9
4E
1P
"
H
1119
118
6D
6E n
~ DLE 48 0 111
•q 1? 11 4 DCt
38 e 811 58 p
6P 0
49 31 1 112 78 p
•R 18 12 I DC2 81 51 Q
58 32 2 113 ?1 q
"S 82

•r
·u
19
28
21
13
11
15
..
! ! DC3

§
DC1
IMK
51
52
33
31
3
4
83
84
52
S3
51
R
s
114
115
?2
?3
p

s
"II
·w
"K
22
23
21
16
1?
18
-
l
SYN
ETB
53
54
55
35
36
3?
6
?
5 85
86
ss
56
T
u
u
116
11?
118
?4
?S
?6
t
u
f CAH 56 8? S? u
•y 25 38 8 II 119
19 88 ??
"Z
•c
26
2?
1A '
~
EN
sue
S?
58
39
3A
9
:
89
58
59
X
y
128 ?8
w
X
18 • ESC 59 38 ;
98 SA z
121 ?9 y
"'
•1
••
28
29
1C
1D
L

M
PS
cs
68
61
3C
JD
<
91
92
58
sc
C
122
123
?A
?B
z
(

31
31
1E
1P
• RS
UC
62 3£

>
93 SD '
]
124 ?C I
" 63 3P ?
94 SE • 12S 71)
>
..-
95 SP 126 ?E
- 12? ?P

51f
Dec Hex Ch Dec He>< Ch Dec He >< Ch Dec Hex Ch
,
...•
128 80 <; 1611 All 192 Cl! 224 Ell a
129 81 0 161 Ai "{ 193 Ct 225 E1 II
130 82 e 162 A2 6 194 C2 T 226 E2 r
,
131 83 ii 163 A3 u 195 C3 ~ 22? E3 I
132 84 :I 164 A4 ii 196 C4 - 228 E4 E
a cs + 229 a
133
134
85
86 ~
165
166
AS
A6 ..
R 19?
198 C6 ~ 2311
ES
E6
E?
µ
199 II 231 '(
135
136
8?
88
~
e
16?
168
A?
AB
"t 2111!
C?
CB I! 232 E8 ll
13? 89 !! 169 A9 ~ 2111 C9 Ii 233 E9 8
138 BA e 1?II AA ~ 202 CA !.! 234 EA II
1?1 AB ~ 2113 CB ;; 235 EB 6
139 BB I
1411
141
BC
8D
•I
1
1?2
1?3
AC
AD
Ii

2114
2115
cc
CD
11
=
236
23?
EC
ED ..•
142
143
BE
BP
,.
A 1?4
1?S
AE
AP
((

»
2116
211?
208
CE
CF ",!,"
u
238
239
241
EE
EP
Pl
(

144 91! E 1?6 BIi I DI ~

145 91 al 1?? B1 I 219 D1 'r 241 P1 •


1?8 82 I 211 D2 242 P2 <
14'
14?
92
93
ft;
0 1?9 83 I 211 D3 "" 243 P3 i

181 B4 i 212 D4 7 244 P4 t


148 94 I!
181 BS 4 213 D5 f 245 PS J
149 95 0
246 P6
.
182 B6 ti 214 D6 r
1se
1S1
96
9?
0
u 183 B? n 21S D? "II
...
24? P? Ill
241 n Ill
152 98 y 184 BB
'll
216 DI
,T
.
1S3
154
99
9A
0
u
185
186
B9
BA II
21?
218
D9
DA r
249
258 "
PA
PB .J
.
18? BB 219 DB I 251
15S 9B c ;i
252 PC •
1s6 9C
,,
£ 188
189
BC
BD
!J
u
221
221
DC
DD

I 253 PD •
15? 9D 254 PE I
A> 191 BE J 222 DE I
151
159
9E
9P f 191 BP , 223 DP • 255 pp

515
.\PJ>ENDIXF
APPENDIXG

ASSEMBLERS, DEVELOPMENT
RESOURCES, AND SUPPLIERS
This appendix provides various sources for 8051 assemblers and trainers. In
Keil
addition, it lists some suppliers for chips and other hardware needs. While these www.keil.com
are all established products from well-kno,vn companies, neither the authors nor
the publisher assumes responsibility for any problem that may arise with any of Franklin Software
them. You are neither encouraged nor discouraged from purchasing any of the www.fsinc.com
products mentioned; you must make your own judgment in evaluating the prod-
ucts. This list is simply provided as a service to the reader. It also must be noted Dunfield Development Systems
that the list of products is by no means complete or exhaustive. To suggest other www.dunfield.com
products to be included in future editions of this book, please send your compa·
Figure G -1. Assembler S uppliers
ny's name, product name and description, and Tnternet address to the authors'
e-mail listed in the introduction.

8051 ASSEMBLERS
The 8051 assembler is provided by many companies. Some of them provide
shareware versions of their products, which you can download from their Web www.MicroDigitalEd .com
sites. However, the size of code for these shareware versions is Limited to lK (or
2K). Figure G-1 lists some suppliers of assemblers. RSR Electronics
www.elexp.com

Axiom Manufacturing
8051 TRAINERS 717 Lingco Dr. Ste. # 209
Richardson, TX 75081
There are many companies that produce and market 8051 trainers. Figure G-2
(972) 994-9676 Fax: (972) 994-9170
provides a list of some of then,. www.axman.com
The following is a Web site for !'AQ (frequently asked questions) about the
8051: http: / / www.faqs.org/faqs/m1crocontrol1er-faq/ 8051 I Rigel Corp.
P. O. Box 90040
Gainesville, FL 32607
(352)373-4629
PARTS SUPPLIERS http:// rigelcorp.com
Figure C-3 provides a list of suppliers for many electronics parts.
Figure C-2. Triliner Suppliers

517
Mouser Electronics
RSR Electronics 958 N. Main St.
Electronix Express Mansfield, TX 76063
365 Blair Road 1-800-,346-6813
Avenel, NJ 07001 w,'IW,inouser.com
Fax: (732)381-tSn
Mail Order: 1-800-972·2225 Jameco Electronic
1n New Je~y: (732) 381-$)20 1355 Shoreway Road
www.elexp.com Belmont, CA94002-4l OO
1-8()0.831-4242
Altex Electronics
(415) 592-8097
11342 tH-35 North Fax: J.80()-237-6948
San Antonio, TX 78233 Fax: (415) 592-2503
Fax: (210) 637-326,1
Mail Order: 1-800·531·5369 W\•1w•.jameco.com
wY.rw.altex.oom
B. G. Micro
Digi-Key P. O. Box 280298
1-80().344-4539 (I..SOO.DIGI-KEY) Dallas, TX 75228
PAX: (218) 681-3380 J-800-276-2206 (orders only)
In
-
www.digikey.com (9n) 271-5546
Fax: (972) 271-2462
Radio Shack Mail order: 1·800-THE· This is an excellent source of LCDs, !Cs,
SHACK keypads, etc.
www.bgmicro.com Th•
JDR Microdevices De
1850South IOth St. Tanner Electronics for
San Jose, CA95112-1108 1100 Valwood Parkway, Suite #100
Sales 1-8()0.538-5000 Carrollton, TX 75006
80:
(408) 494-1400 (9n) 242-8702
Fax: 1·800-538-5005 www.tannerelectronics.com
Fax: (408) 494-1420
W\vw.jd.r.com Ill

Figutt G-3. EltttTonics Suppli•rs

518

Al'Pl!NDIXG ...
APPENDIXH

DATA SHEETS
infel. MCS•-s1 PROGRAMMER'S GUIDE AND INSTRUCTION SET

The information presented in this chapter is collected from the MCse-51 Architectural Overview and the Hardware
Description of the 8051, 8052 and 80C51 chapters of this book. The material has been selected and rearranged to
form a quick and convenient reference for the programmers of the MCS-51. This guide pertains specifically to the
8051, 8052 and 80C51.

MEMORY ORGANIZATION

PROGRAM MEMORY
The 8051 has separate address spaces for Program Memory and Data Memory. The Program Memory can be up to 64K
bytes long. The lower 4K (8K for the 8052) may reside on-chip.

Figure 1 shows a map of the 8051 program memory, and Figure 2 shows a map of the 8052 program memory.

FFFP
FPFF
~

60 K
BYTES
EXTERNAL
OR .. 64 K
BYTES
EXTERNAL

1000
AND

0:1 4J< BYTES


INTERNAL
I 0000 27024~1

Figure 1. The 8051 PtojlaDI Memory

519
1"1
/
infel. MCS~51 PROGRAMMER
'S GUIDE AND INSTRUCTION SET
-
FFFF.,__-- - 1

56K
BYTES 64K
EXTERNAL BYTES
- - OR - EXTERNAL

: l
j . ._ _
8
~_K_ _F_N_A_L_ ..... I ooooL------=27=0:;;--;249-2
fig
Figure 2. The 8052 Program Memory
INI
Data Memory: No
are
The 8051 can address up to 64K bytes of Data Memory external to the _chip: The "MOVX" ins~ction is_ ~ d to
access the external data memory. (Refer to the MCS-51 Instruction Set, tn this chapter, for detailed descnption of
instructions).

The 8051 has 128 bytes of on-chip RAM (256 bytes in the 8052) plus a number of Special Function Registers (SFRs).
The lower. I~ bytes of RAM can be accessed either by direct addressing (MOV data addr) or by indirect a d dressing wr
(MOV @Ri). Figure 3 shows the 8051 and the 8052 Data Memory organization.

wr
infel. MCS~-51 PROGRAMMER'S GUIDE AN O INSTRUCTION SET
OA
Ne
Sia

bl
Th
INTl1RNAL
lis
1
FPr--------.. ic
SFRs
DIRECT 64 1( C1
ADDRESSING BYfES RE
: /--"O:.:.;NL,.,,.,_:ot:_ _ _...j EXTERNAL re-
DfRECT&c -AN0--..,,•-1 to'
INDIRECT
ADDRESSING 2.
00 .__ _ _ _ __ J •
lb
11
Figure 3• . The 8051 O•lll Memory lie
270249-3
le
ti
3.
i,.
APPENJ>vcu
'4j
MCS®-51 PROGRAMMER' S GUIDE AND INSTRUCTION SET

INTERNAL
INDIRECT
ADDRESSING ONLY
80HTOFFH
FF

FF 64K
SFRs BYTES
DIRECT EXTERNAL
'--
ADDRESSING --AND-- ~--1
80 ONLY
7F
DIRECT &
INDIRECT
ADDRESSING
00 0000'---- ----.....l
270249-4

Figure 3b. The 8052 Data Memory

INDIRECT ADDRESS AREA:


Note that in Figure 3b the SFRs and the indirect address RAM have the same addresses (80H-OFFH). Nevertheless1 they
are two separate areas and are accessed in two different ways.

For example the instruction


MOY 80H,#OAAH
writes OAAH to Port O which is one of the SFRs and the instruction
MOY R0,#80H
MOY @RO,#OBBH
writes OBBH in location 80H of the data RAM. Thus, after execution of both of the above instructions Port Owill contain
OAAH and location 80 of the RAM will contain OBBH.
Note that the stack operations are examples of indirect addressing, so the upper 128 bytes of data RAM are available as
stack space in those devices which implement 256 bytes of internal RAM.

DIRECT AND INDIRECT ADDRESS AREA:


The 128 bytes of RAM which can be accessed by both direct and indirect addressing can be divided into 3 segments as
listed below and shown in Figure 4.
1. Register Banks 0-3: Locations O through lFH (32 bytes). ASM-51 and the device after reset default to register bank 0.
To use the other register banks the user must select them in the software (refer to the MCS-51 Micro Assembler User's
Guide). Each register bank contains 8 one-byte registers, 0 through 7.
Reset initializes the Stack Pointer to location 07H and it is incremented once to start from location 08H which is the first
register (RO) of the second register bank. :n:ius, in order to use more than one register bank, the SP should be intialized
to a different location of the RAM where it is not used for data storage (ie, higher part of the RAM).
2. Bit Addressable Area: 16 bytes have been assigned for this segment, 20H-2FH. Each one of the 128 bits of this seg-
ment can be directly addressed (0-7FH).
The bits can be referred to in two ways both of which are acceptable by the ASM-51. One way is to refer to their
addresses, ie. oto 7FH. The other way is with reference to bytes 20H to 2FH. Thus, bits 0-7 can also be referred to as bits
20.0-20.7, and bits 8-FH are the same as 21.0-21.7 and so on.
Each of the 16 bytes in this segment can also be addressed as a byte.
3. Scratch Pad Area: Bytes 30H through 7FH are available to the user as data RAM. However, if the_stack pointer has
been initialized to this area, enough nu.mber of bytes should be left aside to prevent SP data destruction.

521
~IXH
jr,i
AND INSTRUCTION SET

infel. MCS~ 51 PROGRAMMER'S GUIDE - /

sP
fat
Figure 4 shows the different segments of the on-chip RAM.
co:

I
,i...E--- - -- - - 8 Bytes - - - - - -- ~
,.., cal

7F
7ll
~t-~~~~~~~~~~~~~--1
77

68 6F
~i--~~~~~~~~~~~~--l
67
SCRATCH
58 SF
PAD
57
~r-----------__j 4F AREA
.

~i--~~~~~~~~~~

3a1___________J 47
~r--~~~~~~~~__J 3P
~r-------------37
o...
20 ···
=--==---
7F 2F ADDRESSABLE
BIT
27
18 SEGMENT
3
10 W
2
08 17 REGISTER
1
00 OF BANKS
'-~~~~~o~~-;--==]w , ~~~~~-

f'•gure 4.128 Bytes of RAM 0 .


270249-5 .
tree! ud ln~ct Add ress.ble

APPl!NDIXH
.....
infel. MCS~-51 PROGRAMMER'S GUIDE AND INSTRUCTION SET

SPECIAL FUNCTION REGISTERS:


Table 1 contains a list of all the SPRs and their addresses.

Comparing Table 1 and Figure 5 shows that all of the SFRs that are byte and bit addressable are located on the first
column of the diagram in Figure 5.

Table 1
Symbol Name Add re as
•Ace Accumulator OEOH
·B B Register OFOH
•PSW Program Status Word ODOH
SP Stack Pointer 81H
DPTR Data Pointer 2 Bytes
DPL Low Byte 82H
DPH High Byte 83H
•po Porto 80H
•p1 Port 1 90H
•p2 Port 2 OAOH
•p3 Port 3 OBOH
•1p Interrupt Priority Control OB8H
•1E Interrupt Enable Control OA8H
TMOD Timer/Counter Mode Control 89H
•TCON Timer/Counter Control 88H
• + T2CON Timer/Counter 2 Control OC8H
THO Timer/Counter O High Byte SCH
TLO Timer/Counter O Low Byte 8AH
TH1 Timer/Counter 1 High Byte 8DH
TL1 Timer/Counter 1 Low Byte 8BH
+TH2 Timer/Counter 2 High Byte OCDH
Timer/Counter 2 Low Byte OCCH
+ TL2
+ RCAP2H TIC 2 Capture Reg. High Byte OCBH
+RCAP2L TIC 2 Capture Reg. Low Byte OCAH
• sCON Serial Control 98H
SBUF Serial Data Buffer 99H
PCON Power Control 87H
• d Bit addressable
+ - 8052 only

APP!NDIXH

~ infel. MCSlt.61 PROGRAMMER'S GUIDE AND INSTRUCTION SET

WHAT DO THE SFRs CONTAIN JUST AFTER POWER-ON OR A RESET?


Table 2 lists the contents of each SFR after power-<>n or a hardware -1.

Table 2. C-.C,, of the SFRe - reset


SFR MEMORY MAP
A0111o4w V - lnBlnary I Bytea
• AfX 00000000 FF
F8
·a 00000000 F7
0
PSW 00000000 FO B
SP 0000011 t E8 EF
DPTR Eo ACC E7
DPH 00000000 Of
OPI. 00000000 08
· PO 11111111 00 PSW D:
•f>! 11111111
·P2 11111111
ca T2CON RCAP2L RCAP2H 1\.2 TH2 C
co <.7
.,,.
·P3 11111111
8051 )()()(00000, ea IP I .f
8052 )()(000000 80 P3 87
•IE 8051 OXXOOOOO,
IE ,-$
8052 oxoooooo M
TMOO 00000000 AO P2 1<7
·TOON 00000000 911 SCON SBUF 9F
• • T2CON 00000000
THO 00000000 90 Pl 117
TLO 00000000 88 TCON TMOD TLO 1'1.1 THO THI 8f'
THI 00000000 80 PO SP DPL OPH !'CON &7
Tlt 00000000
f Figure 5

-
•TH2 00000000
•Tl2 00000000 9'1
oRCAP2H 00000000
+RCAP2t. 00000000
·SCOH 00000000
SBUF Indeterminate
PCOH HMOS OXXXXXXX
CHMOS OXXXOOOO
X - U,-,od
• Blt -
+ l052 orw,

- I L \ -- ..~ .... I O ,. 'e. 'l, ... <:). , , ,


n.. .l,.. \ - -
.. ~ \..~
• I µ::_t: 6 ...;~~ I ,_ , ~D X <,~ - -' ~
MCS~-51 PROGRAMMER'S GUIDE AND INSTRUCTION SET

TbOSC SFRs that ~ave their bits assigned for various functions are listed in this section. A brief description of each bit
pro\llded for qwck reference. For more detailed information refer to the Architecture Chapter of this book.
15

pSW: PROGRAM STATUS WORD. BIT ADDRESSABLE.

[ CY I AC I FO I RS1 I RSO I ov I P

CY PSW.7 Carry Flag.


AC PSW.6 Auxiliary Carry Flag.
FO PSW.5 Flag O available to the user for general purpose.
RSI PSW.4 Register Bank selector bit I (SEE NOTE I).
RS0 PSW.3 Register Bank selector bit O (SEE NOTE I).
ov PSW.2 Overflow Flag.
PSW.I User definable flag.
p PSW.O Parity flag. Set/cleared by hardware ca.c h instruction cycle to indicate an odd/even number of
'I' bits in the accumulator.

NOTE:
1. The value presented by RSO and RS1 selects the corresponding register bank.

RS1 RSO Register Bank Addreaa

0 0 0 OOH-07H
0 1 1 OBH-OFH

1 0 2 10H-17H
1 1 3 18H-1FH

PCON: POWER CONTROL REGISTER. NOT BIT ADDRESSABLE.

I SMOD I l 1 GF1 GFO PD IDL

SMOD Double baud rate bit. If Timer I as used to generate baud rate and SMOD = I, the baud rate is doubled
when the Serial Port is used in modes I, 2, or 3.
Not implcm.c ntcd, reserved for future use. •
Not implemented, reserved for future use.•
Not implemented, reserved for future use.•
GFI General purpose flag bit.
GPO General purpose flag bit.
PD Power Down bit. Setting this bit activates Power Down operation in the 80CS1BH. (Available only in
CHMOS).
IDL Idle Mode bit. Setting this bit activates Idle Mode operation in the SOCS IBH. (Available only in CliMOS).

If Is arc written to PD and LDL at the same time, PD takes precedence.


'User aottware shOuld not write ts to r-rved bill. These bits may be used In future MCS-51 products to Invoke MW
feallKes. In that case, the reset or Inactive value of the new bit will be 0, and its active value will be 1.

2· 11

APPENDIXH
w,i
TRUCTION SET
'S GUIDE AND INS
- /
jnfel. MCS-.51PROGRAMMER

,,
INTERRUPTS:
IA Ofdd' to llK any of tbc w1muplS i.n the Mes., I, I.he IoII.owtn• g 1hree steps
mu.st be wen. I 1# 0

V"
I Sd ch< EA (mablc all) bl1 in 1hc IE tcglJlff IO I. • I
, · Ste tht oomspooding indl'i'ldual intcrrvpt enabie bit io tht LE ttgmer to , ·tba.t iDlertUpt. See Table below.
~
J, &pa tbc 1oterrupt 5CfV!ce routme at tbt corrcspOnd.a:ng Vector Address 0
Interrupt vector
priC
Source Addreu
fl1>
IEO 0003H
Tl'O OOOBH
0013H
tfi1
IE t 11"
TF1 001BH ).El
RI& Tl 0023H
0028H
11'
TF2 & EXF2 JU
__ be Sd 10 1 and depending on whether
Tf.
1n addition~ for atc:mal interrupts, pins n::f'ro a.nd INTI (P3.2 a.odin
PJ.lhj) ';,~N giJce; may need to be id lO I..
the interrupt is t.o be: le\'cl or transition activated, bi1s JTO or- ITI e tt

fTx • olevel activated IP:


fh • 1 tranSitlon activated If l
biJ
IE: INTERRUPT ENABLE REGISTER. BIT ADDRESSABLE. [
I
If the bit is 0, the corresponding interrupt is disabled. lf lhc bi1

EA I- l ET2 J ES l ET1 I EX! I


ts 1. che comsp0ndio3 in1errupt is enabled.
ETO I EXO I
-
EA lE.7 Disables all interrupts. If EA - o. no interrupt will be acknowledged. rr £A - I. each ioletnipt
PT
$OU.rot" is individually mabtcd or disabled by setting or cbrin.a iLS enable b1L PS
IE.6 Nol unplctnctHtd, rcsctved for fu1u.rc U$C. •
PT
En JE.S En,bJe or disable the 'rimer 2 overflow or capcurc Uucm.ip1 (80$2. onJy).
ES IE.4 Enabkc or disable chc st:ria.l pon fntcrrupL
PX
ETI IE.l &able c>r diltble the Timer 1 overOow interrupt. P'J1
EX I JE.l Enable or di$Able Ex1cmal Interrupt I. PX
ETO IE.I Enable or disable die Timer O overflow unerrupc.


£XO IE.O Ena.blc or disabtc £x1cmal lnlcm)pt 0. ...
'U

·user software .sho1.1Jd t)()I write h 10 reserved bi1s. These bi1s may be ttscd in furure Mes •
new features. 1ft th9' C8$e, lh.c rtSct or in11ctivc v:aJue of the new bit ll'lll be Ind .... • • ·S 1 pr~uccs to IDVOkc
O, 1.., actwe \1'8.luc wtll be I.

2·12

526

APl'ENDIX H
intel· MCS®·51 PROGRAMMER'S GUIDE ANO INSTRUCTION SET

ASSIGNING HIGHER PRIORITY TO ONE OR MORE INTERRUPTS:


[p order to assign higher priority to an interrupt lhc corresponding bil h1 the JP register must be set to 1.

ftcme:rnbe.r that while an interrupt service is in prog.ress, it cannot be interrupted by a lower or same level intetrupL

PRIORITY WITHIN LEVEL:


Priority ..vithin levcJ is on1y to resolve simultaneous requests of the same priority level.

From high to 10"-', interrupt sources arc listed below:

IEO
TFO
1£1
Tl'l
JU or Tl
mor EXF2

IP: INTERRUPT PRIORITY REGISTER. BIT ADDRESSABLE.


lf lhc bit is 0, the corresponding interrupt bas • lower priority and ff the bit is I the corresponding interrupt has a
blgllcr priority.
I- I PT2 PS PT1 PX1 PTO PXO
rP. 7 Not implemented, reserved for future use.•
IP. 6 Not implemented. reserved for future use.•
PTl IP . S DefmC$ the Timer 2 interrupt priority level (8052 only).
PS IP. 4 Defines the Serial Pon interrupt priority level.
PTl IP. 3 Defmcs the Timer 1 interrupt priority level.
PXI IP. 2 Defines External Interrupt I priority level
PTO lP. 1 De('mes the Timer O interrupt priority level.
PXO IP. 0 Defines the External Interrupt O priority level.
' Uaer software should not write Is to tescrved bits. These bits may be used in ruture MCS·S I products to in\•okc
new reatures. 1n lha.t case, the reset or inactive value of 1he new bit will be 0, ind its 1ctive value will be l.

2· 13
ND INSTRUCTION SET
MCS•-51 PROGRAMMER'S GUIDE A
jnfel.
TCON: TIMER/ COUNTER CONTROL REGISTER. BIT ADDRESSABLE.

rw1lffl1iml~l1e1irr1l1~1mJ
TFI TCON. 7 T"uncr I overllow flag, Set by lwtlwar< when 1he Tim..-/Co•nter I overllows. Cleared by batd·
ware u proceuor vectors to the inierrupt s,ervice toutlne.
TRI
TCON". 6 Tuner I run conltOI bit Set/cleared by son...,. 10 t•rn Timer/Counler I ON/OFF.
TOON. 5 Timer O ovttflow Rag.. Sec by h,rdv,ratc when the Timcr/Countc:t Oovtrflows. Oearcd by hard~
TFO
wate" processor vec:ton to the scrvkc rouunc.
TRO TCON. 4 Tuner O run ooor.rol biL Set/cleared by sof'twarc to tum Timer/Counter O ON/OFF.
re, TCON. 3 Extcm*1 ltucmap1 I edge nag. Set by hardware when .External interrupt edge is detected,
Clettcd b)' ba.rd...ate wbtil interrupt is p ~.
ITI TCON. l lnturupt l type control bil. Se1/clwc:d by toft'warc to specify falling edge/low lcveJ triggered
External lntenupt.
IEO TCON. I External lnterrupt Oedge Oag. Set by ha.rdwire when External Interrupt edge detmcd. Cleated
by harchrn.te when intun1p1 is processed.
ITO TCON". O lnl<mlp1 0 lype con,rol bl1. Set/cleared by soft-. 10 specify falling edge/low level triggered
ExtfflW Interrupt.

TMOD: TIMER/ COUNTER MODE CONTROL REGISTER NOT BIT


ADDRESSABLE. •
IJATE I c_i[! M1 I Mo __,I.___GATE I ctQ M1 I Mo=) $z
TIMER 1 TIMER 2
GATE WhenTJu(mTCON)iuc,an<IOATll • I TIMJ!R/CO
(hardware control). When GATE • 0, TlMJiRJco~ 8'!--1 wtll ruo onJr. wh:llc lNTx pjn ,s bigb
control). wdl run only whde Tiu • I (soft.ware
fi
:i

Ti.mer- or C.Ountcr sclet1or. Ocared for 'firncr o . (' ~z


MO
Ml
cer Opcrat1on (input from Tx input pin).
Mode ,cleetnr boo (NOTE J)
Mode .sdccior bit, (NOTE J)
perauon inpul rrom int~ sys.tern cloc:lc). Set ror Coun·
-
NOTE t:

Ml MO Oper1t1ng Mode
0 0 0 13,blt Timer (MCS-48 compatible)
0 1 1 16-btt Timer/Countet
1 0 2 8-tJit Auto-Rek>ad Timer/Coun!er
1 I 3 (Time, O) TLO Is an 8-bff Timer/Count
3 ~trol bits, THO is an &·bit Tomer and~; ::i~':;il~ by lhe standard Time, 0
1 1 •mer 1) Time,/Counter 1 stOj)ped, r • byTime, 1 C0<1trol bits.

..:
g

2-1 4

528

APPENDIX H
lnfel. MCSG'-51 PROGRAMMER'S GUIDE AND INSTflUCTION SET

I
:a TIMER SET-UP
Tollli:s 3 lluouah 6 give some values for TMOD which can be used IO sci up Timer O in differenl mod,s.

ll ii UIWDCd that Ollly oae timer i.s bc:iog used at a time. If it tS desired to run Timen O and l simultaneously, in any
mode. thc value in TMOD for Tuner O must be ORed with the value shown for Timer I (Tabl,s S and 6).

f'or oumple. ifit is dclircd IO run Timer Oin mode I GATE (utemal control), and Timer I in mode 2 COUNTER,
lbcD the vall>C that must be loodcd into TMOD is 69H (09H from Table 3 ORcd with 60H from Table 6).

Motec>wr, ii is assumed that the user, at this pOigt. is not ready to tum the timers on and will do lhat at a different
point in the pros,mn by Jettuli bit Tiu (,n TOON) to I.

TIMER/ COUNTER 0 TIMER/COUNTER 1

Asa Timer: As a Timer:


Table 5
T•ble3
TMOD
TMOD
TIMER 1 INTERNAL EXTERNAL
TlMERO INTERNAL EXTERNAL MODE
MOOE FUNCTION CONTROL
FUNCTION CONTROL CONTROL
CONTROL
( NOTE 1) (NOTE 2)
(NOTE 1) (NOTE2)
0 13-bit Timer OOH 80H
0 13-bll Timer OOH 08H
I 1S.bit Timer IOH 90H
1 t 6-bit Timer OIH 09H
2 S.bil Auto-Reload 20H AOH
2 8-bi1 Auto-Reloed 02H OAH
3 does not run 30H BOH
3 two 8-bil Timers 03H OBH

As. Counter: As a Counter:


T8ble4 Table 6

TMOO TMOD
COUNTERO INTERNAL EXTERNAL COUNTER 1 INTERNAL EXTERNAL
IIIODE MOOE
FUNCTION CONTROL FUNCTION CONTROL CONTROL
CONTROL
(NOTE 1) (NOTE2) (NOTE 1) (NOTE2)

0 13-blt llmer 04H OCH ' 0 t 3-blt Timer 40H COH


1 16-blt rom... 05H OOH I 1S.bit Timer 50H OOH
2 8-bi1 Auto-Reloed 06H OEH 2 8·blt Allio-Reload 60H EOH
- -
--
3 one 8-bil Counter 07H OFH 3 not available

NOTI!;S,
1. Thi Tlmor II unod ON/OFF by Nllong/c:IHrlOI} bil TRO in lhe aoflware. 1, The Timer is turned ON/OFF by setting/ clearing bil TR1 W'I tne sohwa,e,
Z. Thi Tlmor II unod ON/OFF by the t IO O 1flnoit<wl on m'ffl (P3.2) when TRO • 1 2. The Tim« Is 1Umed ON/OFF by 1he 1 to O transition on fm'T (P3.3) when TRI • I
c,..0w•• coneroo (~atdwaro coneol~
infel. MC~-51 PROGRAMMER'S GUIDE AND INSTRUCTION SET

T2CON: TIMER/COUNTER 2 CONTROL REGISTER. BIT ADDRESSABLE


8052 Only

[ TF2 I EXF2 RCLK I TCLK EXEN2 I rR2 I cm I cPru I Asa Timer:


TP2 TlC'ON. 7 Timcr 2 o,·crfJow Rig act by hudwatC and cbn:d b)' toftwarc. TF2 cannot be xt when Table 7
either RCLK • l or CLK • 1
T:ICON
£XF'2 T2CON. 6 TImer 2 external flag•• whm dtbc:r a capc:ure or rdo!M:I b c,iuscd by • neptiYC ua.nsition on
Tl.EX,. and EXEN2 - I. Whca:11imc:r 2 interrupt is taal>lcd, EXF'2 • I wiJJ «:aiJJM the CPU MODE IHT£RNAL EXTERNAL
CO vector lO the Timer- 2 intetrup( routine. EXPl mu.u be cleated by ,oft:ware. CONTROL CONTROL
RCL.K T2CON. 5 Receive clock Oag. When set, CAU$C$ the ~ Pon to Uk Tuner 2 ovc:rflow pubc, for ics (NOTE 1) (NOTE2)
receive clod in lbQda: I & 3. RCLK - 0 ca~ Timer I o,-crflow to be med for the rccrivc 16-oit Auto-Reloed OOH 08H
•lode.
16-bit Capture 01H 09H
TLCK 1"2:CX>N. 4 Trattsm.it c:loc-k Oag. When .kt. causes the. Sc:ru.l Pon 10 use TI:tnct 2 ovcrflo• pub,et for its
BAUD rate generatOf receive &
U'aflsmu cloek to moc:ICJ I & 3. TCLK • o caUStS Timer I ovcrllo-'S to ht \lkd ror tbc
tnLNmi1 doof(. transmit same baud rate 34H 36H
llXEN2 T2CON. l Timer 2 extcnuJ cnabk na,g, When set, aUovrs a c.aphuc or rt&c.d lO occur as a n:a.u.h ol receive ontv 24H 26H
ncgatrvc ttan$1t100 on Tlal?X if lilJler 2 is nor belog used l.O clock the Scnal Pon. transmit onty 14H 16H
SXEN.2 • 0 causes Timcr- l to ignore evcrits at T2(3.X.
TR2 T2CON. 2 Solt~ STA.RI/STOP concroJ for nmcr l. A fogi,e I siaru tbc Ti:mcr.
cm T2CON. J TiG:icr or Courtier 5dcct. As a Counter:
0 • JmcmaJ Timer, I • Eucroal E"'enl Counlcr (fa.lJin,g edge tri,ggcr«I),
CP/RL2 T.ZCON. 0 C.ptutt/kdoed 0.ag. Wbcn -«. caP4:Ul'C$ will occur On nepti...e 1ro.os.i.h0ns al Tl..E:X if TMOO
EXBNl - J. Wbcti cleatcc4 Auto-.Rclc:w.ds v.-i1J OC(':ur cit.her with Timer 2 overflows Or
neptive U'a.nSltioos a.t T2EX when EX.EN2 c I, When ri1hcr RCLK • 1 or TCLK - I, MODE INTERNAL EXTERNAL
this bt1 J,i J.gnOttd aod t.bc- Timer is forced t0 Au10-Rdoad on Timel'" l O\·c:rflow. CONTROL CONTROL
(NOTE 1) (NOTE2)
1&-bit Auto-Reload 02H OAH
1s-b;1 Cat,lure 03H OBH
NOlES:
TIMER/COUNTER 2 SET-UP 1. Clp1Uf9/Relo*CI occut1 only on Tln"lef/Countor ov8'110w.
2. Cap1ure/ Aeioad occurs on Timer/ Countee O'Verllow end ei , '° o transition
(P1,1) pin excop1 when Tun• 2 it used ,n the baud rate Qenera\ing mode.
°"' T2EX
Except for the baud rate generator mode. the values given for T2CON do noc include the setting or the TR2 biL
Tbctdorc. bit TR2 m~ be set. separately. to tum the Timer on.

~, FI I I I ... \~ \~
intel· MCS* -51 PROGRAMMER'S GUIDE AND INSTRUCTION SET

scoN: SERIAL PORT CONTROL REGISTER . BIT ADDRESSABLE.

[ SMO I SM1 I SM2 I REN I TBS I ABB I Tl I RI I


SMO SCON. 7 Serial Port mode speedier. (NOTE 1).
SMI SCON. 6 Serial Port mode specifier. (NOTE 1).
SM2 SCON. S Enables the multiprocessor communication feature in modes 2 & 3. In mode 2 or 3. if SMl is set
to I then RI will not be activated if the received 9th data bit (RBS) Is 0. In mode I. ifSM2 = I
then RI will not be activated if a va.lid stop bit wa.s not received. ln mode 0, SM2 should be 0.
(See Table 9).
REN SCON. 4 Set/Cleared by software to Enable/Disable reception.
T88 SCON. l The 9th bit that will be tran.smincd in modes 2 & 3. Set/Oearcd by software.
RBS SCON. 2 In modes 2 & 3, is the 9th data bit that was r"'eivcd. 1.n mode I, if SM2 = 0, RBS is the •top bit
that was received. In mode 0, RBS is not used.
Tl SCON. I Trall$mit interrupt flag. Set by hardware at the cod or the 8th bit time in mode 0, or at tile
beginning of the stop bit in the other modes. Must be cleared by software.
RI SCON. 0 Receive interrupt flag. Set by hardware at the end or the 8th bit time in mode 0, or halfway
through the stop bit llmc in the other modes (c.xciept see SM2). Must be cleared by soRware.
NOTt 1:

$MO SM1 Mode Oeacrlptlon B1ud Rite

0 0 0 SHIFT REGISTER Fosc.11 2

,
0 1
0
1
2
8-BltUAAT
9-Bit UART
Variable
Fosc./640R
Fosc.132
1 1 3 9-Bit UART Variable

SERIAL PORT SET-UP:


Table 9

MOOE SCON SM2 VARIATION

0 10H Single Processor


1 SOH Environment
2 90H (SM2 = O)
3 DOH
0 NA Multiprocessor
1 70H Environment
2 BOH (SM2 - 1)
3 FOH

GENERATING BAUD RATES

S.rlal Port In Mode 0:


Mode O bas a fbcd beud rate which i5 1/12 or the oscillator frequency. To run the serial port in th.is mode none of
the Timer/C:Ounters need 10 be set up. Only the SCON regi'1er needs to be defined.
Osc Freq
Baud Rate • -'----'
12

Serial Port In Mode 1:


MOde I bu I variable baud rate. The baud natc can be generated by either Timer I or Timer l (8052 only).

2·19

531
Al'PENDIXH
jnfel.
'
MCSl<-51 PROGRAMMERS G
UIDE AND INSTRUCTION SET
-
USING TIMER/COUNTER 1 TO GENERATE BAUD RATES: r h. ch•p«r.
Set SC(.110JJ O t I)
For th.it putpc:)l'C. Ti.inc::r J ts U1Cd in n,ode 2 (Auco-Rdoad). Refer 10 Timer up
K ,: OSCiilatot FttJQ.
Baud RAIO • :)2 x 12 • ( 25G _ (THI))

lfSMOD • 0, thco K • I
II SMOD • I. 1hcn K 2 (SMOD "the PCON rcgisier).
Most oftbc tune the user \nows the bflud rate and n«ds to know the ~lood value foe THI.
Then:(orc, 1he cqu.1tion to calculare TH I can be wriuen as:

t< x Osc Freq


THl ._ 256 - 384 "baud tale
...... the d«;red baud ra«. In
'TH I muse be M integer vaJQC. Roundmg off TH I to the nearest integer niay not ._,..,.,.uce
thts ~ the user ma)' hav.: to choose another tt)·Sctl frequency.

S.incc the PCON cc:gistc:r i!t noc btt addrcsA.blc. one way co ~t 1bc bh 1s logical ORing the PCON regjstcr. (it~ ORL
PCON, 180H). The tddrcss o( J>CON as 87H.

USING TIMER/COUNTER 2 TO GENERATE BAUD RATES:


For th,s purpose:. Timer 2 rouse be u~ 1n the baud talc gencnltmg mode. Refer 10 Timer 2 Sc:cup TA.blc in I.his
ch.apter. If Timer 2 1s being clocked through ptn T2 (Pl.0) the baud nHc ii:

Saud Rate • Tl"* 2 Ovfrflow Raia


18

And d' 11 is befog eloc-ked intern.illy the blud rate i.-.·

S.udRate OseFteq
32 , 1815536 - (RCAP2H. ~AP2L)J

To obcam the reload value ror RCA.PlH and RCAP2L 1hc above -,
Nlu:.D.tion - · be ·
........ rcwnuen as:
ACAP2Ji, RCAP2L • 65636 - 0sc F,Gq
3:Zx~Ra10

SERIAL PORT IN MODE 2:


The baud 1111e iii (u.td in this mode and is 'In or 1/t of 1hc oscilla
btt in 1he PCON register. •• tor frequcnt..'Y depending oo the vaJuc o.f thc SMOD

In this mode none or the Timers arc used and the clock ccnncs from th .
c 1n tcmat pl1ase 2 cioc\;
SMOO ... I. Baud Rare =- 11,, Osc Freq •

SMOO = 0, B:tud Rate c Y•• O$c: Freq,

To.., the SMOD b11, ORL


PCON. # 80H. The nddrc,s or PCON "87H.
SERIAL PORT IN MOOE 3:
The baud ntc in mode 3 l5 vanable and ~~ b
- - up ex.act1y t e same as in mode I.

2-20

532

APPl!NDIXH
MCS*·51 PROGRAMMER'S GUIDE AND INSTRUCTION SET

MCS®-51 INSTRUCTION SET


Table 10. 8051 Instruction Set Summary
r-~~~~~~~~~~~- r~~~~~~~~~~~._.,

Interrupt Response Time: Refer to Hardware De- Mnemonic; oe,crlptlon Osclllator


Byte
sc:ripdon Chaptc.r. Poriod
ARITHMETIC OPERATIONS
lnatrucllona that Affect Flag Settlngs(1)
ADO A,Rn Add re~ter to 1 12
ln1lructlon Flog lnttructlon Flag Accu,,..,,lator
C av AC C OV AC ADO A,d1tect Add cSrect byte 10 2 12
ADO X X X CLRC 0 Ac:cumuta1or
ADOC X X X CPlC X ADO A,OAJ Add Indirect RAM t 12
SUBB X X X ANLC,bit X to Aoeumulatoc
MUL 0 X ANLC.lb<I X ADO A. • data Add immediate 2 12
DIV 0 X OAL C,b<t X data to
DA X OAL C,bil X Aacumuf.alor
ARC X MOVC,bit X AOOC A.Rn Add register to 1 12
RLC )( c.JNE X Accumulator
SET8C t withCany
(l)Note that opcr•tions on SFR byte oddr<S! 208 or AOOC A.direct Add direct byte to 2 12
bit addresses 209·215 {i.e., the PSW or bit, in the AccumlAator
PSW) will e.lso affect flag settings. with Corry
ADOC A,eRI Add indirect 1 12
Note on instruction set and 1ddressi,n9 modes: RAMIO
Rn - Register R7 - RO of the currently SC· Aocumulato,
lccted Rcgistet Bank. withCtrty
direct - 8-bit internal data location's addr¢S.1f. AOOC A.# 41UI Add Immediate 2 12
This could be an lntemal Data RAM date to Ace
location (0- 127) or • SFR [i.e., VO with C11ry
p0rt. control register, itatUs register, SUBB A.An Subtraci Regbter I 12
etc. (128-255)}. tromAccwM
41 Ri - S..bit intern.a] data RAM location (0- borrow
255) addres,cd indirectly through reg· SUBB A.direct Subtract direct 2 12
ister R 1 or RO. b)'1e from Ace
#data - 8-bit constant included in instruction. w1thbotrow
# data 16 - 16-bit constant included in instruction. SUBB A,eRI Subtract ln<flrect 1 12
addt 16 - 16-bit destination addre$$. Used by RAM from ACC
I.CALL & UMP. A branch can be wllhbo!TOW
anywhere wlthin the 64K•byte Pro- SUBB A. #data SUblfOCI 2 12
gram Memory address space. Immediate data
addr 11 - 11-bit destmauon addte.u. Used by trom Ace with
ACALL & AJMP. The branch will be borrow
within the same 2K-byte page of pro- INC A tnc,&m8(11 1 12
gram memory as the fl.rst byte of the Accumulator
INC Rn lncrem&n1 register 1 12
foUowing instruction.
INC ddoct Increment direct 2 12
rel - Signed (two's complement) 8-bit olfset
byce. Used by SJMP and aU condition• byte
1 12
e.1 jumps. Range is - 128 10 + 127 INC OAI lncr•m•nt direct
bytes relative to first byte o( the fol• RAM
DEC A Dect«nent 12
lowing instruction.
bit - Direct Addressed bit io lntema.l Data. Accumulator
o.c,- 12

=-
RAM or s ~ial Functfon Reiriste:r. DEC Rn
Re,g11t.,
2 12
DEC direct direct
byte
0ec:rement 1 12
0£C •RI
lnaoreci RAM
All mnemonics copyriglltocl ©Intel Cofl>c)rallon 1990

2·21

~H

____________
._. ~~-
MCS · -51 PROGRAMMER'S GUIDE AND INSTRUCTION SET
intel,
,------~T~1b~le~ 10'.::.a~s~11n11ructlon
o Se;:t:.:S::
u:::
m:.:.
m::•:..:
rr...:.:<Con_:..lill.:.
· _ued_.:.)_ _ _ _ _ _ _ _,
OKllletor
oo..:rtptlon Byte Period
Oeacrlptton Byte c,.c11t1tor
t-;;;;;:;;;;::::-::::::=__:.::.::=~.:::._p,nod LOGICAL OPERATIONS 1coo•nued)
1 12
ARITIIMETIC OPERATIONS (COr\1,nuedl AL A ROUlle
INC OPTR lncrtmtn1 Oata 1 24 A~fator Lel1
12
Pointer Rotate
RLC A Acx:t1mU1ator Latt
MUI. AB ""'1lply A & 8
DIV AB tl>r011(1h the carry
DA A OlvldeAbyB 1 12
Docimal-t ROta1e
AOCWlLi!ait>t
AR AQCumula1or
LOOIC" I.. OPERATIONS Right
AHL A.Rn ANO RIQl$let to I 12 Aotate I 12
ARC A
Accumulator Aoc;umulator
ANl A.direct ANO direct byte 12 Right 111roug.h
to Aocumulator Ille carry
ANl A,eR! ANO ,ricl,rect 2 12
SWAP A Swap nibbles
RAM co
w!IIW'I ti'!&
Acc:umu'41or
A/Ill A... data 12 ,Acc:omulttto,
AND wnmedlalt 2
da:a 10 DATA TRANSFER
Accumulator MOV A.Rn Move 12
ANL di<eet,A AND AcCl,IIT'lulato, 2 12 register to
ANL IO d,recl byte Accumul.ato,
cl1ttet. • data ANO •mtnedlttt 3 24 MOV A,dfrect Mcwedirect 2 12
OAL A.Rn data 10 dcf.c1 by1.1 byle10
OR reglNC to I 12 AccumlAator
Aocumu11ior MOV A.eRI Move lndiect 1 12
0A direct byte to 2 12 RAM to
Accumt,q,io, Accum.,1a1or
OAL A,eR1 OR lndittct RAM 12 Move 2 12
to AccunMJf,.IOf immediate
ORL A,#def,11. OR tmmtd.iate 2 12


da!l 10
dala"' Accumulator
Accu"'-'a10, MOV Rn.A
OR ACCLfflulato, 1 12
2 12 Aoc:umula10,
OAL - ·
CAL direct, .. data to direc:t byte to register
OR immediate 3 24 MOV Rn,<k.ct
drta to d,tocl byte Move direct 2 24
XAL A.Aft e~ bytO lo
regls!A)J to reglsar
Accumulator MOV Rn. I dale Move 2 12
ExciullYe-OA 2 12 lmm0d1a10 data
cl<ec,byteto to,~e,
MOV direct.A
Aooumulato< Move 2 12
XAL A.eftl Elcelu....e-OR A.ocumulato,
tndi,(ICt AAM 10 to direc1 byte
Accumuta.lO( Move regisae, 2

--
XRL A..•data -OR 24
2 M(N dlrect.dtfect to direct byte
lmmec:11110 ct,11 10 Move direct
3 24
by1e to <i•rocc
ExdJslvo-OA 2 12 Move llld1rec1 2
Aocumufator to 24
RAM to
XRl di.tect. • d•ta EiccluS!Yt-OR
dtfect byte MOV d1rect, ' da11 dlrtct byte
3 24 MoYe
lfflln8d.lte data 3 24
immect111e data
IO ClltOCC byte
CUI A c,.., &0 Cl!rtct i,..,.
12 Mew& ..,,e
CPI. A
Com-
AcCUmulalOf

AccU'nulalOI' All mne- Accumu&a_to, 1


indir8CI RAM o
1 12

2-22

Al'PENDIXH
intel· MCS~ -51 PROGRAMMER'S GUIDE AND INSTRUCTION SET

Table 10. 8051 l natructlon Set Summery (ConUnued)

Mnemonic Dea.c:rlptlon
O•clllator Mnemonic OHCrlptlon Otclltalor
Byte 8~
Period Period
OAT A TRANSFER (Continued) BOOLEAN VARIABLE MANIPULATION
MOV • Rt d,rect Move d1rect 2 24 CLA C Cte.rCany 1 12
b)'1e to CLA bi1 Clear direct bit 2 12
illdlrecl RAM SETS C SetCeny 1 12
MOV ORl.•data Move 2 12 SETB bit Set direct bl1 2 12
immed.ate CPL C Complement 1 12
data to Car,y
indirect RAM CPL bit ~ement 2 12
MOV DPTR, # data 16 Load Data 3 24 direct bit
Pointe, with a ANL C.bi1 AND direc1 btt 2 24
16-bit constant to CARRY
MOVC A.OA + OPTR Move Cod(t 1 24 ANL C.lbit ANO complement 2 24
byte relative to of direct bi1
DPTR to JV;c 10Cany
MOVC A.eA+ PC M<W&Code 24 OAL C,M OA direct bi1 2 24
byte relative to to Carry
PC to Ace ORL C,/bit OR complement 2 24
MOVX A.ORi Move 1 24 of direct bit
EX1emal to Carry
RAM (II-Ill\ MOV C,bll Move direct bit 2 12
addr)toAcc to Carry
MOVX A.e DPTfl M°"" 1 24 MOV bi1,C Move C.r,y to 2 24
E)ctemal direct bit
RAM 116-bil JC rel Jump if Carry 2 24
addt) to Ace ls set
MOVX ORi,A Move Aceto 24 JNC rel JumpHCany 2 24
Extemal RAM not set
(S·bit addr) JB bit.rel
Jump i1 direct 3 24
MOVX OOPTA.A Move AIX to 1 24 Bit 1s set
External RAM JNB bllrel Jump K direct 3 24
( 1ti.bi! addr) Bit ls Not Mt
PUSH direct Pushditect 2 24 JBC blt,rel Jump ff direct 3 24
byte onto Bit ls set &
stack olearbi1
POP direct Pop direct 2 2A PROGRAM BRANCHING
b)'1e from ACALL addr1 1 Absolute 2 24
Stadt Sub<oulfne
XCH A.An Exehange 1 12 Cell
regiStGC' with LCALL addr16 Long 3 24
Accumulator s~

-
XCH A,dlrect Exchange 2 12 Cell
direct b)'18 RET Retumtrotn 24
Sub<oulfne
Accumulator RETI R""'m from 24

-
XCH A.ORI Exchange 1 12 lntemlpt
indirect RAM AJMP eddr11 Abeolute 2 24
Ju""' 24
Accumulator WMP addr18 Long J"""' 3
Exchange low· 1 12 Sho<I JufflP 2 24
XCHO A.ORI SJMP rel
O<dor Digit (ro!atlYO addr)
indirect RAM AHmnemonice c:opyrightad C>lnfal Cotpordon IIIIO
witl> ACC

2-23

AfnNDIXH -
lnfel.

...... ,....a
.,.. o.«tt w ........ 011 !Ip-
eyw
0..-.IOI
Pertod

--···~~-
__..
Du ff lU

__.,.......,
l'IIO(IIIAIII IIIWIQUICI (Ccitl6'"Adl
2•
1 24 CJHE Ar<•_.,.. eo,..-
ltNM :ta•e to '
- ••·ll"TA - - ,._
ll... ....... Cl'TR
2 2,
Equol
•Al. •.....,.. Col,..,. 3 2•

__ ,....
N:O.r. . .
.z... CJNE

-
........
... trtmlrllr:M IO
JHl 2 ,doodond

-- --
C,jN£
_.,.,_
_.,.. ..
...........
.,.,u... ) 2•
DIH2 ANol
_,_
Equol

,.,.....,
o.c,,wmenl 2 24

-~
tNo<E.....
_,..
.... -~
lMo
~
CJNE
' O.C,tmenl 3 24

-0/ld-
t111dt M'IO Ql'a

-
•No<E
Hoel-
No I 12
Al Mr..-O• • OOW"' ~

-
APl'ENDIXH
MCS~-51 PROGRAMMER'S GUIDE AND INSTRUCTION SET

.
T1ble 11 ln1tructlon Opcode, In He.xadeclmal Order
Hox Number Hex Number
Codi Mnemonic Oporami. Mnemonic Oporanda
of Bytoo Code of llytn
00 1 NOP 33 1 ALC A
01 2 AJMP cOdeeddr 34 2 ADDC A,#ckla
02 3 UMP codeaddr 35 2 ADDC A,ck1aaddr
03 1 RR A 38 I ADDC A.IRO
04 1 INC A 37 1 ADDC A.IRI
05 2 INC dataaddt 38 I ADDC A.Ro
06 I INC 8RO 39 1 ADDC A.Al
07 1 INC IRI 3A 1 ADDC A.A2
08 1 INC Ro 38 1 ADOC A,R3
09 1 INC A1 3C I AOOC A,.R4
OA 1 INC R2 30 1 AOOC A,AS
OB 1 INC R3 3E 1 AOOC A,R6
oc 1 INC R4 3F 1 AOOC A,A7
OD 1 INC R5 40 2 JC code addr
OE 1 INC Rs 41 2 AJMP code addr
OF I INC A7 42 2 DAL dala oddr,A
10 3 JBC bit addr, code addr 43 3 DRL data addr, * data
11 2 ACALL OOde addr « 2 DAL A, # dlto
12 3 LCALL code S:ddr 45 2 DRL A,dala odclr
13 1 RAC A 48 I DRl A,IRO
1' 1 DEC A 47 1 DRL A,IRI
15 2 DEC data ackft 48 1 DAL A,RO
16 1 DEC IRO 49 I DRl A.Al
17 1 DEC 8A1 4A 1 DRL A.A2
18 1 DEC AO 4B 1 DRL A.R3
19 1 DEC Rt 4C I DRL A,R4
1A 1 DEC R2 4D I DRL A,R5
1B 1 DEC R3 4E I DAL A.R8
1C 1 DEC A4 4F 1 DRL A.R7
1D 1 DEC RS 50 2 JNC oodeaddr
lE 1 DEC AS 51 2 ACALL oodelddr
IF I DEC R7 52 2 ANl dalaoddt.A
20 3 JB bit add!'. OOde addf 53 3 ANL data addr, # dlta
21 2 AJMP codeeddr 54 2 ANL A,#dato
22 I RET 55 2 ANL A,d110oddr
23 I Rl A 58 1 ANL A,IRO
24 2 AOO A, • data 57 1 ANL A,IRI
25 2 ADD A,data addr 56 1 ANL A.RO
28 1 ADD A,IRO 59 I ANL A.R1
27 1 ADD A,IAI SA 1 ANL A.AZ
28 I ADD A.RO 58 I ANL A,R3
29 1 ADD A,A1 SC I ANl A.Re
2A 1 ADD A,R2 eD 1 ANL A.RS
28 1 ADD A.R3 5E 1 ANL A,Re
2C 1 ADD A,R4 5F 1 ANL A.R7
20 1 ADD A,RS 60 2 JZ oodeoddr
AJMP oode oddr

__
2E 1 ADD A.AS 61 2
2F I ADD A,A7 82 2 XRl da10oddr.A
30
31
3
2
JNB
ACALL
bit addr. OOd• ldm"
codeaddr
63
84
3
2
XRl
XRl
--·""'"
,.,
A,#da10
32 I RETI 85 2 XRL

2·25

...____
"'°'ENDIXR
,

infel.
MCSL 51 PROGRAMMER'S GUIDE AND INSTRUCTION SET -
,;;;---;;::=::--....:T~a~bl!!t. !1_!:1.J.!ln~a~tru:!!:c~t~lon ,,.,,,<)dH r,, tte~,nal Ord•rMnemonic
(Continued) o~ ...nc1·
rr~Coclo;"":._~o~IB~•~•:._;M;•"""":
He.x Numbtt
::~~'.._~~o,,o,ond~~-
· ~~ f suss A,R1
A.R2
156 XRL A,eAO
99
1
suss A,R3
87 XRL A.ORI
9A
98 1 suss
suss A.R•
88
69
XAI.
XAL
A.AO

",Rf
ec 1 suss A.RS
90 SUB8 A,R6
8A XRL A.R2 se 1 A.R7
88 XRL A.R3 1 SUBS
9F CJb!t eddr
8C I XRL A.R• 2 OAL
60
8E
I
I
XRL
XAL
A.RS
ii.RS
,.,NJ 2 AJMP
MOV
code addr
C,b!taddr
42 2
8F I XAL A.R 7 ll'IC DPTR
A3 1
AB
70 2 JNZ
ACALL
oode~
code ad« .... 1 MUL
71
72 2
2
CAL A5 '~
MOV OAO.data addr
,.
T3
2
I
JMP
MOV
C,l,il eddr
eA+OPTR
A.#data
,.,
48 2
2 MOV
MOV
eR1,data addt
RO.data addr
75 AfJ 2
3 MOV data.addr, l data MOV R1,data addr
76 2 WJV •RO,#data 49 2
M 2 MOV R2,data addr
77 2 MOV •A1,, c;tata
78 AB 2 MOY A3,data a<ktf
2 MOV AO,# dtta
79 4C 2 MOY R,,ctata addr
2 MOV Al .l dlta
7A 2 40 2 MOV R5,oe1a addr
MOV R2, # data
78 2 AE 2 MOV RS.data addr
MOV R3, #data
7C 2 MOV A•, l dala AF 2 MOV R7.da.ta addr
70 2 MOV A15, • dt11 80 2 4NL C,/bit addr
7E 2 91 2 AC...LL codeaddr
MCV R8, # data
7F 2 92 2 CPL bit adclr
SJMP A7,• data
80 2 93 1 CPL C
81 AJMP OOdt lddr
2 a, 3 CJNE A.• data.Oodt addr
82 2 ANL
MOVC - -
C,bit addr 85 3 CJNE A.data addr code
83 98
e, I
OIV A.eA+PC
e1
3 CJNE •Ro,• e1ata'.COc1e: :
3 CJNE eR1.
85 3 MOY
MOV
AB adClr
data
de , dtla 1ddt 98 3 CJNE RO • • <1ata,code addr
88 2 M(JII taaddf'.• RO es R • data.Code addr
87 3 CJNE
2 MOV da1aaddr,eR1 94 3 CJNE R 1, # data""'ode addr
88 2 2, • data.code
MOV data ldct.RO 88 3 CJNE
89 2 R3, • data.code=
84 2
MOY data lddr.R1 ec 3 CJNE fW,• data c:ooe
88 2
MOV data lddt.R2 eo 3 CJNE RS,• e1a•-' addr
MOV data lddr,R3 ae
BC
80
8e
2
2 "°"
MOY
data oddr,R,
da.. oddr.R5
BF
co
3
3
2
CJNE
CJNE
Re -code addr
R , # daia-..1.-
.~addr
'· • data.OO<M
2 MOV dati tddr.RS PUSJi d•,.•ddr add<
8F 2 c1 2
MOV d1ta 1ddr.A7 AJMP eodeaddr
90 3 C2 2
AC.All DPTA, ' datt C3 ClR bit addr
91 2
92
93
2
1
MOY
MOYC
._,~
bltlddr,C
cc
cs
'
1
CLR
SWAP
C
A
A.•4 +llPTR
2 XCH
9' 2 sues
suee A. • c1a,.
ce 1 XCH
A.data addr
95 2 C7 A,eRo
96 I SUBS A.dataoddr C8
1 xci; A,eR1
I
97 svee A.•Ro Ct XCI;
A.RO
SUBS A.eR1 1 XCH
96 1 A.RO C4 A.RI
I XCH
ca 1 A.R2
XCH
A.R3

2-28

538
M CS~-51 PROGRAMMER'S GUIDE AND INSTRUCTION SET

.
Table 11 lnatrucllon Opcodu In Hexadecimal Order (Continued)
H•:a Humber Hex Number
Code or By!•• Mnemonic Oper1_nda Code 0 1 8)'111 Mnemonic ~
cc 1 XCH A,R4 E6 1 MOV A.e Ro
co 1 XCH A,R5 E7 1 MOV A,eR1
CE 1 XCH A,R6 E8 MDV A.AO
CF 1 XCH A,R7 E9 1 MOV A,A 1
00 2 POP dataaddr EA MDV A.A2
D1 2 ACALL code addr ES 1 MOV A.A3
02 2 SETS bit acldf EC MOY A.A4
03 1 SETS C ED 1 MOV A.R5
oc 1 DA A EE 1 MOY A.RB
05 3 OJNZ data addr,code addr EF 1 MOY A,R7
06 1 XCHO A,9RO FO 1 MOVX e DPTR.A
07 1 XCHD A,9A1 F1 2 ACALL codeaddr
06 2 OJNZ RO.code addr F2 1 MOVX eRO,A
09 2 OJNZ A 1,code adcsr F3 1 MOVX • R1 ,A
DA 2 OJNZ A2.code addr F• 1 CPL A
DB
DC
2
2
OJNZ
DJNZ
R3,codeaddr
R4,code addr
F5
F8 ,,
2 MOV
MDV
dala addr,A
eRO.A
00
OE
2
2
DJNZ
OJNZ
AS.code lddr
R6,code addr
F7
Fe ,, MOV
MOV
e A1,A
RO.A
OF 2 OJNZ R7,oode addr F9 MDV A l .A
EO 1 MOVX A.ODPTR FA 1 MOY R2,A
e, 2 AJMP code addr FB 1 MOV R3,A
E2
E3 ,
1 MOVX
MOVX
A.eRo
A.e R1
FC
FD ,
1 MOY
MOY
A4.A
R5,A
E• 1 CLA A FE 1 MOY RB.A
ES 2 MOV A.data addr FF 1 MOV R7.A

2-27

4PPliNDIXH •
0

lnetructlon Set Summary s 6 I 7

• ./NZ
0 I 2
JNB
3
JC
JNC ,.,
JZ
,el

• NOP
......
JllC

(38, 2CI
......
JB

138, 2CJ
... tel
138, 2CJ
..I
1!'!:_2CI
,el
{28. 2Cj
(28, 2CI
AJMP
120. 2CI
ACAU.
ACALL
I MAP ACALL ........
(Pl)
,t,CAl.L
(Pll
AJMP
(P2l
(P2) (P3)
(2B, 2CJ
(P3)
(28, 2CJ
2
(PO) (PO) (2B, 2CJ
(28. 2C1 129, 2CJ
(28, 2CJ !29,2CJ 128. 2CJ XAL OAL

2 UMP lCALL RET RE'TI OAL ANL


dlr, A dor, . c.b,I
dlr. A (28. 2CJ 3
•cldr18 (2CJ 12CI (28)
""'"'
(39, 2C! 138. 2CI
(29)
OAL
(281
ANL XAL JMP
OA +DPTR
3 RR
• ,.
RAC AL
A
ALC
A (hr. 1eti1a
(38. 2CJ
dil, ldata
(38. 2CI
d1r, l(Sata
(38, 2CI (2CI

lffil MOV
• INC
A
DEC
• .......
AOO

{281
AOOC
A. fdaMI
(281
ORL
A. •d31t
(281
ANl
A, ldala
12B1
A. ,c1a1a
(281
A. #<tata
(281 5
$
..,
INC

(2BJ
...
DEC

1281
AOO
A,6'
1291
.... ....
AOOC

1281
ORL

1281
ANL
A, Or
(291
XRL
A. dor
(2BJ
M()V
ldata
(lir,
(38. 2CI
6

• INC
ORO
DEC
ORO
ADO
A, ORO
ADOC
A. ORO
OAL
A. ORO
ANL
A, ORO
XRL
A, ORO
MOI
ORO, Odalll
(281
7
1 INC DEC AOO AOOC ORL ANL XRL M<:N
ORI ORI A. OA1 A. ORI A, OAI A, ORI A, 0R1 OAt, #dOf.l
l2BJ
• INC
RO
DEC
AO
ADD
A.RO
ADOC
A.AO
ORL
A. RO
ANL
A,AO
XAL
A. AO
MCN
RO. klata
6

(2B1
• INC DEC ADO ADDC ORL ANL XRL M()V 9
Rt
"' A.RI A. RI A.Al A. A1 A, Rt Al, ldJta
(291
A INC DEC AOO AOOC ORL ANL XRL MOIi
R2 R2 A.112 .... 112 A.R2 A
A, A2 A,R2 m. ,oata
(281
9 INC DEC AOO ADOC ORL ANL XRL
R3 R3 A.R3 A.R3 A. R3
M()V
A,R3 A. R3 9
R3, #data
C
...
INC DEC

"'
ADO
A,R4
AOOC
A.R•
ORL
A.Ac
ANL
AR,
XRL
A,A.C
1281
M()V
A4, ldaJa C
D INC DEC ADO (28)
ADOC DAL
R• R$ A, RS A.RS ANL XAL
A.RS M()V
A,R5
E
...
INC DEC
RO
ADO
A.Re
AOOc
.... R6
-- ORI.
A,R6
AM.
A A$

XRL
RS. idata
12B1
M()V
D

A.lie A. Re A6, J~UII


F INC DEC AOO
R7 AOOC ORL (:WJ
R7 A.A7 A.R> ANL
A, R> XRL M(N
A.R>
A.R7 R? ldlta
Kay:
(2BJ
(281 • 2 llyle, (38) • 3 llylt, (2CJ • 2 Cyde, (4CJ • • Cycle, Blank. I byte11 <ytlo

a-12 Instruction Set - - - - - - - • • • • •


..... ------------------~~--------...........
Instruction Set
instruction Set Summary (Continued)
8 9 I .. B C 0 I E F
0 SJMP MOV OAL Nil PUSH POP MOl)( A. MClYX
REL DPTR.o C. lbot C.Jblt dir dot OOPTR ODPTR, A
128, 2CI dlta 1$ 128.2C) 128, 2CI 128, 2CJ 120 . 2CJ l2CJ 12CJ
138. 2CJ

1 AJMP A.CALL AJMP A.CALL AJMP A.CALL AJMP .ACALL


(P<) (P• > (PS) ( P5) (1'6> (1'6) (P7) (P7)
(28, 2CJ 12a, 2CI (28. 2CJ 128. 2CI 128, 2CJ 128. 2CI 120, 2CJ (28. 2CJ
2 ANL MOV MDV CPL CI.R SETS MOVX MOVX
C, bn bil. C C, btl bil bd bl1 A. OAO wAO, A
(28. 2CJ (28. 2CJ 128) 12BJ 12BJ (28) 12CI [2CJ
3 INJIICA. MDVC A. INC CPL CUI SETS MOVX MOVX
O A • PC OA + OPTR DPTR C C C A. ORI ORl, A
(2CJ (2CJ 12CI (201 (201

• DIV
AB
SUBB
A, #Cleta
MUL
AB
CJNEA.
14-la, , ..
SWAP
A
DA
A .
CUI
..
CPL

[28, •CJ 1201 14CJ 138, 20)


5 MDV SUBS CJNE Xett OJNZ MDV MDV
dlr. dir A,dir A. dlr. ,.i A. dw di,, rel A. dlr dlr, A
138. 2CJ 1281 136,201 128) 138, 2CI 1281 (28)
6 MOV sues MOV CJNE xett XC'10 MOY MOY
dit, OAO A.ORO ORO. di, ORO, t data. rtl A, ORO A. ORO A.ORO ORO.A
128,201 [28. 2CI 138, 2CI
7 MOY SU88 MOV CJNE XC*i XCHD MDV MOV
<llr. ORt A. 0R1 0R1. dlr OR1 , 1oa1a, rtl A. OR1 A.0R1 A. OR1 O R1, A

8
128. 201
MOV SUBB
(28. 2CJ
MOV
-
(38, 2CJ
CJNE XC*i DJNZ MDV MOV
dir, RO A, AO RO, dor RO. Jdata. cei A, RO AO. rel A, RO AO, A
128. 2CJ (28. 2C) 136, 2CJ f2B.2CI
9 MDV SUBB MOV CJNE XC*i DJNZ IICN IICN
dlr, A1 A. A1 A1.0lr A l , #dala. rel A, AI R1, rtl A. A1 Al, A
(28, 2CJ (28, 2CJ 138, 2CJ (28, 2C)

• MOY
dir, R2
SUB8
A. R2
MOV CJNE
A2. #data. ritl
XCH
A, R2
DJNZ
R2, ,el
ut:N
A, R2
MOV
R2. A
120. 2C) (28, "''
R2. 2CJ 138. 2Ci 128, 2CI
B MOY SUBB MOV CJNE XCH OJNZ MOV MOY
A. R3 R3, dir A3. l data. rel A. R3 R3, ,., A, R3 R3, A
""· R3
(213, 2CI 128, 2CJ (38, 2CI (28, 20)
C MDV sues MOY CJNE XCH OJNZ MOV IICN
dif. A< A. A4 R4, dlr A4, f data, rel A, R4 Re, reJ A.R4 A... A
128, 2CJ (28, 2C) [3B, 2CI (28, 2CJ
D MOV SUBB MO\/ CJNE XCH DJNZ MOV MOV
RS. A
'*•RS
[28, 2CJ
A. RS RS. dlr
128, 2CI
RS, • daita, rol
[38. 2CJ
.... A5 RS.NII
128, 2CJ
A.AS

E MOY SUBB MOV CJNE XCH OJNZ MOY MOY


A, R6 Fl8. dlr A6, #data, <lltl .... R6 A.R6 R6 A
dlr, R6 R6,ret
(28, 2C) (28, 201 138. 2CI (28. 2CJ
F MOV SU8B MDV CJNE XCH DJNZ MOV MOV
A7, dir A7, tda-ia. rt! A.R7 R7, A
dlf, A7 A.R7 A, R7 R7, rtf
)28, 2CJ (28, 2C( (38, 2CI (28, 2CJ
Key-
(2BJ• 2 Byte, (381 • 3 Byte, (2CI = 2 Cycle. (4CJ= 4 Cycle. Blank ~ I byte/1 cycle

2-73
AilD&L
N1
.\PJ>ENoD( H
...____
,
I

PACKAGING
intel.

PACKAGE TYPES

GES
CERAMlCPA CJ(A

Surface Mount
CQFP
1 - - - - - - - - (Ceramic Quad Flatpack)


)

Socket Mount
LGA
(Land Grid Array)
-
C

PGA
(Pin Grid Array)

(Bottom View)

C·DIP
(Ceramic Dual in-Line Package)
Insertion/Socket Mount (Side-Braze)

240817-1

(Reprinted by permJoolon of lnlel Co,pontion, Copynght Intel C~rp. 1992)

APP!NDIXH
....... - Intel.

PACKAGE TYPES (oontinuedl

PLASTIC PACKAGES
LEAOLESS ClllP C>JUUEll PACKAGES Swface mount

SOP
LCC (Small Outline Packagi,)
(Socket Mount) (Bottom View) (Gull-Wing)

Dual Row
1 - - -- - - l - -- SOJ
(Small Outline Packagi,)
LCC
(Sumce Mount) 0 (Bottom View)

'---
0 -Lead)

TSOP
(Thin Small Outline Paclcagi,)

G ~ L E D PACKAGES

CERDIP
(Ceramic Dual ln· Une Packagi,)
. - - - PLCC
(Insertion Mount; UV Window) (Plastic le•ded Chip Carrier)

CERQUAD
(Cerami<: Quadpack) f - - - PQFP
(Surfac.. Mount)
(Plastic Quad Flatp;,ck)

Quad Row
MODULES

1 - - QfP
(Quad Flatpack)

Sil'
(Singlr In-Luu, LHded
Memory Module)
Fl.ATPACK
(Top View)
24-0817-2 240817-3
1-4 1-5
~
...

£ Intel. PACKAGING intel. PACKAGING

PACKAGE TYPES (CX>ntin<Jed)


PACKAGE TYPES (continued)
PCMClA PC CARD-TYPE 1 ANO TYPE II
PLASTIC PACKAGES
• Insertion Mount TYPE!

Connec10<

~
ZIP
Su,gleRow (ZigZ,g In-Line P..:bg•)
(Side View)

240817-5

TYPE2
r - P-D!P
(Plulk Du.,J In-Line Paclc•ge)

O....JRow
SHRINK DIP
(Shrinlc Dual In-Line Pad<age)
WPS

240817-6

' - - - SJ(JNNY DIP


(Slcinny Dual In-Line Pa,clcage)
~40817-4
1~
1-7

II:

;»>>> >>>l!:-
~ ~i ';,) ~ ""s!. i ~~~~ ~~~ ~
8 F I I I ~ - ~ ~ ~ i= ~"' ... ~ c.- ,,. o.. !! S2 !2>1>1S<Q li(Q(')~ "1" 0. c:. to' ..
.._.- -
INDEX

t inkrocontroOrr 2t UCD add•uon ifflll


I n,lc:rocmUOllc, 24 cor1ect1M I
,ddm,ing modn 90, 91 UCDqplb 169
wni!y mant,,i,n 2 t biN,y nun,,t,.,r, 2
jn!'.zin ol &ht! l 24 ilddition 6 cuta !)'pt
~"'I of the t!OS I 2.l r t ' p l ~rion 4 CAU lmtiruction _.-,
OTP vmlari 26 bit 12 thKbum~
llA\t memory map 43 buthn 4W CJ!,,1! 1iNtnaction
rrp1tr bmb t). 44 bin 13 CLR instnKtio1!1 ,
~ · JO t,,tr 12 commmb
l!O~I mnnorv mar :17 aintm! 13
~ 4~ C d.1.1 lypct f« &hr IO.'i I Cllffi'etlkk\
I mkroproc""'>r bit 1.57 A5CD lo pd.ed ICD 170
pir, ikk"nptwn I "'1 eblt (mgk- bit} 156 hinary I ll
ttp,ter \ Ill! on tfr 1.57 binar, hP 4
RE...,ET 1117 Jign,dchu 1 J«im..ll to bvwy 2
!I052 1111(r1~trollcr 24 ,gncd int I ~!Oho'
~ , t,,p :\•11 wwgnt'd dur IS,4 tlo. lO ry ..
675l llU(:.Nr.'Ol'ltrl.li.Lrr 2S umllf'l'd Im 1 he,; IO dmm.tJ 5
C P"'f7.ll!'VIUJl8 222. l61, pKbd IC o A.r.cD 169
o&IC! ~ . 35 326, 1, 402.415 • .,, (O&llft!tff, Set IUnttl
AC fl.lg "'1. '41 8255 41J2 CPL lnRn,ctlon 121, ¥iO
ACAU i~ru.;bon 60, 64 ,454 A001f04 CPU 12, 1:1
AOCJ~14 AU( ·o-m 30 fflll!l:t<I
<Onl'lt\chOn to K2SS A a.rmu,
ACJCl)l!C),l chip :)22 bit ~ - ~ a ton IM dyn,,imlc
ACX..1J!,l)i I 0609 chip '\27, '\28 A.'\0 16.5 1.ttJC
A lS chip 3JO tX.OR 165 CY D..!g
ADO UlMl\KUOl'I 31 41 , 116, ln,·trttr 165
45,-455 OR 165 DA iNlrucuon 119 460. 461
AOOC illltructlon 117 119, 45o shill 165 DACIJ80II 3'4
tdJ1a5 buJ 12. 13 ~ u m 111 CWI)' ch.ti,, 4.48
.ad.JrtMing modes CJ()-91 code daui 5J)IICt' 176 cuia but 1J
dirttt aJJ~ing mode 91 , CM C'OW\ler 293 Q I . I ~ Ji"
t.mm.'(h.1111.1ddra!!tng mode 90 countuO 229 09 dirtclh C JI
inJ ,tJ ..Jd n:sltng ffl('t(M 96 counter 1 228 OM apls 2,1
ng~ttt add~g mode 91 DAC0808348 ocmoeon 441
tqbl"1' lru.hrcct d.Jt.i COl\\t'fSIOl'l 169 t,w.inc1ioNI ax,n111,ti
...mllll 441

-..Id~ mode CU, 9S dai. iwnah.tabon 178 U9) 44.)


Al\fl' INU\lctlon 456 DS89C41CO SRAM 384 lllilda«110ft cm•m 441
.lJ.(' pUI l&i e,tuN.I RAM 3112 DEC~ 461
'.!\O tt•te 9 Interrupts 2QO dKodffl 10
A.\ L 11\atruction 456 457 ~t')~J 3 15 d1r«tt-• J3, lM •
'-"Lil LCD 108 I ZZ. 461, 462
()I\' iNIN(tll1n
I\SCII rnwammang 169 MAXl112 342 OfSZ lftlllNdlOII
"" -.2
A..'iCU t.1ble S14 PW~I 447 [JltAM J62
~ hie ;1.4, \."i OGl9C..0 T1zl v . .

-• l i.
RAM~i. tpec:e 174
"-nhlft 3.1 RTC '41"i c(IIIIIIWII rlt 1M
ll.!1ff11bltt!l 514-515 IK(lil ,d ltri.lJ f'0'1 264 «=· - I • 1'1
(UIU!. . . .
IIIIVI pon lt('a.,. 261
h.uct rate 240 Nri&I port b-wdt 2'1 I to• Ill
8CO n11111bff •ys111tt1• 119 SfR 16.l Im"· l'2

-
oscillator t 85
OV flag 40, 41, 127,129,455
jump inStrUct:ions s(,--60
7 58 59 overflow 126, 129
DS89C4JC0 Trainer (wntinued) conditional jumps 5 , ' '
running 193 58
unconditional 1ump5
tr0ubleshooting 194 JZ inStruction 57, 465 p £lag 40,41 '
duplex traJ1Smission 238 packed BCD 11? .
keyboards 311-318 parallel cornrnurocatJon 238
EA pin 186 interfacing 311 pCON register 251
embedded systems 20, 21 311
scanning and identifying poUing 272.
END directive 39 POP jnstruCbOll 61, 472
EPROM 358 kilobyte 12
port O 76, 186 s
EQU directive 39 labels 33, 39 port J 77, 187 C

LCALL instruction 60-61, 64,466
fan-out 496, 498,503 port 2 78, 187 C
LCDs 300--310 port 3 78, 187
Oag register 40 command codes 301 s
Oip-flops 10
flowcharts 510
connection to 8255 397
data sheet 304
power dissipation 504
power down mode 505
prograrn counter 35, 37
-s
C

LCD timing 304 s


gigabyte 12 PROM 358
pin descriptions 300 5
ground bounce 505 PSEN pin 186
programming 302-304 s:
LEDs 300 pseudocode 510
half duplex 238 PSW register 40, 41, 44 s·
hex 6Je 34 linking 34
LJMP instruction 59, 466 pulse width modulation 443
hexadecimal numbers 4
addition 7 loop 56 PUSH instruction 61,472
subtraction 7 nested loop 67
1st file 34, 35 RP.ll.1 12,14,360
1/0ports 76 Real Time Clock 408
machine cycles 65 alarm 417
fan-out 503
machine language 32
programming 80, 391-397 interrupt 417
reading input pin 499 MAXl112 chip 336
setting the date 412
writing to the ports 500 MAX232/ 233 chips 242,243
megabyte 12 setting the time 411
LC technology 492-496 SQW 417
idle mode 504 m~ory, See semiconductor memory
microcontroller 20 reed switch 431
INC instruction 121, 462, 463 registers 30
Intel hex file 195 choosing a rnicrocontroller 22
microprocessor 20 SFR registers 92, 93
interrupts 272-296
mnemonic 32 relays 428
disabling 274
edge-triggered MOV ~!ruction 30, 467 electromechanical relays 428
interrupts 281-284 MOVC ~truction 468, 469 solid-state relay 430
enabling 274 MOVX mstruction 469 RESET 36, 185
external hardware MUL instruction 122, 470 RET instruction 472
interrupts 279-284 RETI
. ·instruction 334, 286, 473
NANDgate 9
interrupt handler 272
nested loop 67 RL mstruction 473
interrupt vector table 272 nibble 12 RLC instruction 473
level-triggered interrupt 279-284 ROM 12, 14, 36, 357
NOP instruction 470
programming 27$-279 RR~rogram. ROM 35 36
NORgate 9
inverter 9 RR ~!ruction 473 '
inverters 493, 494 NV-RAM 361
Cinstruction 473
obj file 34, 35 RS232 standards 240,241
JB instruction 463 one's complement 6
]BC instruction 463 open collectors 496 SBUF register 245
JC instruction 57, 464 open. drain gates 496 SCON regt5ter
· 245
JMP instruction 464 opto,solator 431 secondsenal ,246
JNB instruction 464 OR gate 9 semi port
conductor m
255
JNC instruction 58, 464 ORC _directive 39 address decoct·emory 356-387
JNZ instruction 58, 464 ORL instruction 470,471 interfacing I O smosg 364
mem 1 367
ory space of the 8051 371
S46

INDEX
MOVX instruction 372 popping 46 timer interrupt
organization 356 pushing 45 programming 275-279
speed 356 stepper motors 432-441 TMOD register 202 217
sensors programming 433 transient current506
selection 349 structured programming transistors 492
serial communication 238-242, 510-PB 592 tr~nsmission line ringing 506
244-255 SUB instruction 120 tri-state buffer 498
8051 programming 246-255 SUBB instruction 120, 121, 474, 475 tri-state buffer 9
asynchronous 238 subroutines 61 TTL technology 494, 495
data framing 239 SWAP instruction 475 two's complement 6, 120
synchronous 238
serial communication port 284-288 TCON register 220, 281-284, 286 UART /USART 238
SETB instruction 204 terabyte 12 unpacked BCD 119
SFR registers 92 Time Delay 157, 212
signed number representation 124 wire wrapping 488
ti.me delays 65, 66 word 12
S]MP instruction 59,474 timers 202-217
sleep mode 505 dock source 204 XCH instruction 475
source fiJe 35 event counter 217-222 XCHD instruction 475
SRAM 360 mode Oprogramming 214 XORgate 9
src fiJe 34, 35 mode 1 programming 205-206 XRL instruction 476, 477
stack 45, 46, 47 mode 2 programming 214 XTALl, XTAL2 185
in CALL instruction 61 registers 202


5'7

....._____

Das könnte Ihnen auch gefallen