The 8051 Microcontroller and Embedded Systems Using Assembly and C PDF
The 8051 Microcontroller and Embedded Systems Using Assembly and C PDF
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
•
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
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
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
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.
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.
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
>
> 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.
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.
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
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.
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
-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. ,, - <:)
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
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
..
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).
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
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
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
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
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
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
-
~
,. 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
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.
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.)
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
,
Address Bus
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.
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
')... -
lo -
SECTION 0.3: INSIDE THE COMPUTER , \;,!Gr ~ i ~
21. Answer the following: ,,.
\ "'\:) ~ )
) 0
-
-
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
' •
18 •
THE 8051 MICROCONTROLLBR AND BMDDDID _- I .. ,
CHAPTERl
THE 8051
MICROCONTROLLERS
OBJECTIVES
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.
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
-
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·
s g
ON-CHIP t,,/
~'f
ROM
"(7
INTERRUPT -- for
program ON-CHIP
ETC.
CONTROL TlMERO
- code RAM
TIMER1 ,c
" -
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.
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
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. '
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.
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 · ~ •
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. "'"' ~ "' ' )
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 .
-
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 ·
28
CHAPTER2
8051 ASSEMBLY
LANGUAGE PROGRAMMING
OBJECTIVES
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
-
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
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
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'>
-
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
:'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 •
-
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
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.
;;-~~~~~~~~~~~~~~~-:;:::~~=
36 .__ ce file
sour
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
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
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.
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
~======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'\
,
(. :::,
\
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.
-
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 ]
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
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
-
Bost ASSEMBLY LANGUAGE PROGRAMMING
45
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
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'' .
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
-
. (
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
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 •
• • •
•
• •
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
,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
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.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.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.
-
80s1 ASSEMBLY LANGUAGE PROGRAMMING
•
1¥
SECTION 2.6: 8051 FLAG BITS AND THE PSW REGISTER
1. PSW (program status register)
2. 8 bits
3. Dl and OS, which are referred to as PSW.1 and PSW.5, resp
ectively.
I
4.
Hex binary
FF 1111 1111
1
+
-1001 +
10000 0000
This leads to CY =1 and AC =1.
/
5.
Hex binary
C2 1100 0010
+ 30 + 0011 1101
FF 1111 1111
OBJECTIVES
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.
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
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_ /
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"
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 ·
Example 3·6
Using the following list file, verify the jump forward address calculation.
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!-.
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.
-
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.
RET
; end of subr outine 2
SUBR 3: ....
RET
: - - -- nd of s ubroutine 3
END ;end of the asm file
-
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
.
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
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,. ( • \ •
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
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
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
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 •
/
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
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
~~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.
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:
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
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
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
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
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?
1/0 PORT
PROGRAMMING
OBJECTIVES
..
' - • .... '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 .
../ 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
'
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.
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
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:
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
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
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.
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
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.
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
&lt4-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.
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.
~
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
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 ,
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.
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.
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.
]. 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
\oc::I.C...'L. ~
•
•
OBJECTIVES
, / 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
-
. ~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
ORG 200H
HYDATA: 08 ·America•
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 ,
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
'
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'-
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.
. < '..-<>: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
~
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
-
8051 ADDRESSING MODES
;increment
INC RO
;lOOP
SJMP BACK
HERlt: SJMP HeRE
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.
Exampl• 5-8
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
' 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.
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
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 °
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.
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
- - -
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
Example S-18
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
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 ·.
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.
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
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.) .
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.
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
1¢
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[
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 .
'
--
' 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.
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
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
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
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.
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
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.
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)
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,
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.
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.
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.
Example 6-6
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:
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
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
Example6-9 - - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-
-
.A.R.ITHMETIC, LOGIC INSTRUCTIONS ANO
, PROGRAMS
123
' lowest o .
. erwilJbethe 'ddledig,t
rder c:ilgi t
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
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.
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
'
-
! ~ _... .. • -
{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
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
.
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:
Example 6-13
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.
- -
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
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
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.
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.
' 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.
-
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
&le 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.
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
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 . ~
•
'
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 ···
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
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
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
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.
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
in Example 6-28.
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
-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
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
Ex~mpJe r,.31
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 .
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: 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
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
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
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.
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.
. '.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
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
;·---------------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
~;;·~;~~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
-
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 .
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
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
8051 PROGRAMMING IN C I
OBJECTIVES
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
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.
~
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
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)
}
}
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
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.
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.
Time Delay
There are two ways to crea te a time delay in 8051 C:
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
157
..
' In creating a time delay using a for Ioop,
delay.
we must be
iniJ1dful of thfE?<'
factors that can affect the accuracy 01
. 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
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
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
.
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.
-
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:
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.
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.
165
' The following shows some examp
I ·cal operators·
les using the C ogt
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 (<<).
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
-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;
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.
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!
' 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 .
Ex.ampl• 7·25
, , ..... . 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.
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.
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';
}
,
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)
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?
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.
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); ,
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. .
-
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.
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
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).
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;
}
}
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
'
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.
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.
182
ilill sos1 M1cR.ocoN1' -
ROLLER AND EMBEDDED sYSTfil'IS \
CHAPTERS
OBJECTIVES
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
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<
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
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?
Vee 10 K
> > > ? .> -?
+ -~
8751/89CS1
~~:;~:.E:E~i
.. >- "I .. .. ..
~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.
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.
www.MlcroOlg ltalEd.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~
,,
\,
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
---
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.
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?
;;;;;: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
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?
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
-
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
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).
no
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
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
Solution:
-
- .11, • •• I 0 .
'I
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'
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
---
!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
., 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
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
-------~~~~~~~~~~· .. •
IOsi lll\1ER PROGRAMMING IN ASSEMBLY AND c
207
I
(a) in bex
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.
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
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
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
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
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
'
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.
~
IQIIIS/ 0.546 pa = 18,315 cycle
65
.536 - 18,315 " 47,221 • 8875H
-
211
I I Of}
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.
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: '
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
~ overflow
XTAL
oscillator + 12 / ' _J
1
TL 1' flag
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.
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.
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:
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
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.
(MSB)
(lSB)
GATE I CIT I Ml I MO GATE I C/T I
Timer 1
Ml I MO
TlmerO
217
I .
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
TRO
Tl-iO TLO
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
8051
Pl
to
LCD
1 Hz clock TO
:---_
;-;;~~~;;;~~:;~;:~~;;------------------==
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.
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
XTAL
+12
OSCILLATOR
C/T=O
-------c_>--1--ruY--f
CIT= 1
Tl IN
Pin 3.5 - - - - l
TRl -----f--.._
.-J ,'
Pin3.3
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
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 ·
/
(
[
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
~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 ., ~
..
~
•'-I!~,
224
.
..-'
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
}
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
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
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
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•
'
}
)
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;
}
}
Pl
Pl and
P2 to
P3.4 P2 LEDs
60Hzclock TO
•
By usu,g
. 60 Hz, we can generate seconds, minutes, hours.
..
.
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.
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
v
CHAPTER 10
OBJECTIVES
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
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.
238
'
-
V Simplex Transmitter •[ Receiver
I 'T,v , ~1..1D
Receiver
I"-~
V
---- ,/1
~
Receiver
Transmitter
l
I
r/
Full Duplex Transmitter ·I Receiver
I
Receiver , .. [ Transmitter
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)
~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
•
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
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
: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.
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:
!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
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
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
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:
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
"
1nere are two ways to increase the baud rate of data transfer in the 8051.
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:
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.
-- 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.
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
252
~tOD
111th S'
=O. we have
22
·-'
,i.,dun~ cyue freq - - = 1833 KHz
.- 12
I
~=57.281 KHz= 57,281
-
p,d .31
,/
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
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
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'·
;;--: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
-
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
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
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
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:
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:
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?
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:
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
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
.
.
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:
' . 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
}
}
}
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
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.
(
• 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.
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·
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?
--~ (a) 9,600 (b} 4,800 (c) 1,200 (d) 300 (e) 150
( . .
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 ·
t 'fllller 1
PinS Pl.2 and Pl.3
:,. -1of FFH
4. S8Uf1
S. Serial Control 1, 8
6. SCONl
...._
llsJ SElJAL PORT PROCIIAMMJNC IN ASSEMBLY ANO c
v
CHAPTERll
INTERRUPTS PROGRAMMING
IN ASSEMBLY AND C
OBJECTIVES
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
.. ..
r ·' EA
EA
IE.7
I En j ES j Er1 I EXJ I ETO
=;=====~------------------_.,
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
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
·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
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:
Example 11-4•
·' Write a program to toggle pin Pl .2 every second.
Solution:
;Tested for an AT89CS1 with a crystal frequency of 22MHz .
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
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)
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
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.
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
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.
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·•
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
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
'
(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
~
·-
•··••· ---· --- - - - - - • - -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
'
-
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
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
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.
..
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.
, 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.
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).
~~~~~ :...:~:::: ~~ :!
• 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
=
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
Example 11-16
.
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
,. 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.
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.
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
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.
CHAPTER12
OBJECT[VES
> 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.
:
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
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'
~·---~~~~~~~~~~~~,
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 _ _ _ _ _....
"'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
-./ , 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.
DO· D7
I
~--1----L·-
RJW ;
F.,
.I
RS - - - l tAS I b. ._______
l-
,i
,i
j
304
E-----1 tosw ...... '
\ tH '
R/W - - l tAS ,
i . ., __ _ _ __ _M
tJ>wH :IAH -- - - - - -
t• ?l ~
RS---
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~
-
~
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
~
(nrtm•J operation,
BF.o C•n......, •
1
p '"•lruc:tion
'~
- - - -
www.dlglkey.com
www.jameco.com
• www.elexp.com
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
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;
}
Review Questions
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 '
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
(
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
)
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·
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?
•
'•
nt
CHAPTER 13
OBJECTIVES
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
·
s·
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
•
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.
" 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 !
., 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
I
-WR
I
'
'
DO- 07 Loaia out :
iNTR
Start conversion
-RD find conversion
'
•
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.
"
_,..
+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
-
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
I
...... GND Vee
..
!NO Clock 00
1N7
.... AOC0808/0809
D7
Vref(+) EOC
Vref(-) OE
SC ALE C B A
(LSB)
.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)---
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
: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
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,
..
[)()/ 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
...
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.
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
10k
POT
...
~
AGND
I DGND
-•.'
1 •
=
.
• I
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 .
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.
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.
•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
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
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
v(JD
...
V is the +5 volt power supply .
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.
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
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 ,.,
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)
'''
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
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
,.
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
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
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.
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.
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
It
!r
ll
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
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
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
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
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
'
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.
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.
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
+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
.. 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;
( ,
for(x•O;x<v•lueix++)
for(y•O;yc127S;y++);
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?
354
•
CHAPTER14
8051 INTERFACING TO
EXTERNAL MEMORY
OBJECTIVES
> 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
..
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
DO-DJ 04-D7
/ 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
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.
~~
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,
--
:..-- 16K 2Kx8 tOO ns
6116LP·l Lo,v-power CMOS
120ns 24
6!16Ll'·2 16K 2Kx8 Low-power CMOS
24
-
6!256LP·12 256K 32Kx8 120 ns 28 Low-power CMOS
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.
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
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 •
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 ~
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
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.
I I
:
DO
07 DO
-
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
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)
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.
PO.O r
=
AIYZ_
1D Q J-<'.
74LS373
A7
AO
A7 program
AO
ROM
oc D7 00
-~
07
'LJU
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
370
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
, .'
•
MOVX
MOV
A,@DPTR
6lfl, A
INC DPTR
MOVX A,SDPTR
MOV 62H, A
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
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.
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.
,
.,., 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
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 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
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
~
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
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:
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
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
-
•
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.
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
- Example 14-20
382
TliEso51 ...
..uCRocoN -
TROLLER ANO EMBEDDED svsfEMS
..'
-
unsigned char msg [SJ •"Hello";
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;
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
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
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
(. (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
8051 INTERFACING
WITH THE 8255
O BJECTIVES
> 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.
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
/ 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
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
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
(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
.
-
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
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?
,_________
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
-·
.r
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
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
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.
~
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
~
-
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.
-
CHAPTER16
DS12887RTC
INTERFACING AND
PROGRAMMING
OBJECTIVES
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
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.
-
/
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
(
' 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
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.
,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
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.
- 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.
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.
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.
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
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
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.
.. • 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
)
l MOVX @RO,A
ACALL DELAY
;
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
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.
+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
'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?
~;;;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.
MOTOR CONTROL:
RELAY, PWM, DC, AND
STEPPER MOTORS
OBJECTIVES
;
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.
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
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
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
MAGNET
,.
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
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
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
('),~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
.. •
:
Pl.2 .• :
-
Pl.J
•
. -
:
-
Use one power supply for
the motor and ULN2003
""' ""
and another for the so.;1
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:
ORG OOOOH
MOV A,lt66H
MOV R0,#32
BACK: RR A
MOV Pl,A
ACALL DELAY
DJNZ RO,BACK
END
-
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. '
~o 30 :;
(Q)
.:]F')F') '
m
(a) Universal
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
--
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
u·
+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:
-
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
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
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)
llJ.8 g-crn
,_,, 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
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.
/ +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
f
+12V
+SV
ILD74
330 OPTOISOLATOR
8051
I 8 10 k
TlP1 20
2 7
Pl.O +12V
t()()k
6
5
-
-
- ~<>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
ORG 0003R
SJMP PIRST
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
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.
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
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);
~~
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.
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.
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.
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".
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:
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.
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:
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
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.
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:
In the third addressing mode, any register, RO • R7, can be the destination.
In the fourth addressing mode, any RAM location can be the destination. The RAM location is held by register
RO or Rl.
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
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. ~
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)
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.
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.
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
;incr. byte .
INC Rl or INC RS
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
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: 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
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:
]NZ target
!'unction; Jump if accumulator is not zero
Flags: None
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).
•'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
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
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.
(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.
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)
Example:
MOV A, #3 2H ;A=32H
MOV R4, # SOH ;R4 =SOH
ORL A,R4 ; (A=72H )
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:
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:
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
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
474
)ddressing Modes
n,e following four addressing modes are supported for the SUBB.
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:
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)
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:
416
XRL direCt,A
6. Example: Find the contents of B after the following:
•
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
80 87 86 85 84 83 82 81 80 PO
.
Special Function Registers
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
• User software should not write ls to reserved bits. These bits may be used
in future flash microcontrollers to invoke new features.
07
DO
PT2 PS PT! PX! PTO PXO
-
APPENDIX A
~I - I - I - I GFl I GFO PD IDL
figUlt A-5. PCON Register (not bit-addressable)
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.
APPENDIX A
(
Finding the TH, value for various baud rates:
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
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.
-
APPIINDIXA
07 DO
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.
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.
Al'PENDIXA
APPENDIXB
OVERVIEW
487
I
l
-
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.
figure B-1. Daisy Chain Connection (not recommended for power lines)
-
APPENDIXC
IC TECHNOLOGY AND
SYSTEM DESIGN ISSUES
OVERVIEW
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.
. . 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
- C N
8 p
C
Oxide
E N
E
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.
Re Re Re
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
H,gh
input Input
AIPENoixc
..orr J PMOS
i - -- Output
Input V OV Output
Input
OV sv
5
NMOS
NMOS '"off,.
"on''
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
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
as the CMOS circuit's operating frequency rises, the power dissipation also increases. This is not the case for bipolar-
based TTL.
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.
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
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
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.
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
I Wh,
Wh,
lllp1
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
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.
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
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
- 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 . '
Internal
ll Load {LI) T
CPU bus D Q '\ __/ Vee
'O'
Pl·X
Write to latch 'I'
Clk Q
On tMI Pl·X
pin
Figu,e C-13. Never Conntct Dirttt Vtt to lht 8051 Port Pin
APPl!NDIXC
Read latch Vee
~
CPU bus D Q
Pl ·X
Pl·X pin
Write to latch Clk Q
-
;~
A
. .
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
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)
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
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
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.
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
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
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.
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
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.
: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
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
...
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
.. •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..
( Stop )
511
Al'PENDIXD
~
.
'
"·
'
"'
•
APPENDIXE
••..
' .
• •
•
8051 .'
X86 •
~ J'•
• ...
8-bit registers: AL, AH, BL, BH, CL, CH, DL, DH A,B,RO, Rl, R2, R3, R4, RS, R6, R7 ..'
..' .••
•
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) • •
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
(
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
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
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
521
~IXH
jr,i
AND INSTRUCTION SET
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 , ~~~~~-
APPl!NDIXH
.....
infel. MCS~-51 PROGRAMMER'S GUIDE AND INSTRUCTION SET
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
-
•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,
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
[ CY I AC I FO I RS1 I RSO I ov I P
NOTE:
1. The value presented by RSO and RS1 selects the corresponding register bank.
0 0 0 OOH-07H
0 1 1 OBH-OFH
•
1 0 2 10H-17H
1 1 3 18H-1FH
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).
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
•
£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
ftcme:rnbe.r that while an interrupt service is in prog.ress, it cannot be interrupted by a lower or same level intetrupL
IEO
TFO
1£1
Tl'l
JU or Tl
mor EXF2
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.
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.
TMOO TMOD
COUNTERO INTERNAL EXTERNAL COUNTER 1 INTERNAL EXTERNAL
IIIODE MOOE
FUNCTION CONTROL FUNCTION CONTROL CONTROL
CONTROL
(NOTE 1) (NOTE2) (NOTE 1) (NOTE2)
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
~, FI I I I ... \~ \~
intel· MCS* -51 PROGRAMMER'S GUIDE AND INSTRUCTION SET
,
0 1
0
1
2
8-BltUAAT
9-Bit UART
Variable
Fosc./640R
Fosc.132
1 1 3 9-Bit UART Variable
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:
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.
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
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 •
2-20
532
APPl!NDIXH
MCS*·51 PROGRAMMER'S GUIDE AND INSTRUCTION SET
=-
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
2-22
Al'PENDIXH
intel· MCS~ -51 PROGRAMMER'S GUIDE AND INSTRUCTION SET
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
•
• ./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
{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
• DIV
AB
SUBB
A, #Cleta
MUL
AB
CJNEA.
14-la, , ..
SWAP
A
DA
A .
CUI
..
CPL
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
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
APP!NDIXH
....... - Intel.
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
~
...
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
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
-• 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
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
....._____