THE 8051 MICROCONTROLLER AND EMBEDDED SYSTEMS
,,1; , 0
Using Assembly and C
·
SECOND EDITION ~ L;r
·,<:>
o:,~
'°' '
o>-"'
:Ir
\}.._~M °'-"'
~e_ E_
~
t'\ '<"' S V\ °'-. cl \\ -
C
~ ~
-
~o-<
®
$ 1:\... t.f!...""" ~~c- . Muhammad Ali Mazidi Janice Gillisp~~ Mazidi Rolin D. McKinlay
~ · l:1 Cj · I ()
•
.f
')..fl-
/J~
'tJ
•
~ (!.A.{e.y ~ #"">
CONTENTS 1 2
CHAPTER O: INTRODUCTION TO COMPUTIN G Section 0.1: Numbering and coding systems Section 0.2: Digital primer Section 0.3: Inside the computer
8 12
19 CHAPTER 1: THE 8051 MlCROCONTROLLERS Section 1.1: Microcontrollers and embedded processors Section 1.2: Overview of the 8051 family
20
23 29
CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING Section 2.1: Inside the 8051 Section 2.2: Introduction to 8051 Assembly programming Section 2.3: Assembling and running an 8051 program Section 2.4: The program counter and ROM space in the 8051 Section 2.5: 8051 data types and directives Section 2.6: 8051 flag bits and the PSW register Section 2.7: 8051 register banks and stack
30 32 34 35 38 40
43
CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS Section 3.1: Loop and jump instructions Section 3.2: Call instructions Section 3.3: TUl1e delay for various 8051 chips
55
56 60
65 •
CHAPTER 4: 1/0 PORT PROGRAMMING Section 4.1: 8051 I/0 programming Section 4.2: I/0 bit manipulation programming CHAPTER 5: 8051 ADDRESSING MODES Section 5.1: Irruned iate and register addressing modes Section 5.2: Accessing m em ory using various addressing modes Section 5.3: Bit addresses for I/ 0 and RAM Section 5.4: Extra 128-byte on-chip RAM in 8052 CHAP'I ER 6: ARITHMETIC, LOGIC INSTR UCTIONS, AN D PROG RAMS Section 6.1: Arithmetic instructions Section 6.2: Signed number concepts and arithmetic operations Section 6.3: Logic and compare instructions Section 6.4: Rotate instruction and data serialization Section 6.5: BCD, A.Sell, and other application programs CHAP'I'ER 7: 8051 PROG RAMMI NG IN C Section 7.1: Data types and time delay in 8051 C Section 7.2: l/ 0 programming in 8051 C Section 7.3: Logic operations in 8051 C Section 7.4: Data conversion programs in 8051 C Section 7 5; Accessing code ROM space in 8051 C St.>ction 7.6: Data serialization using 8051 C
75 76 80
89
90 91 100 107 115 116 124 129 135 141
153 154 160
165 169 173 178
V
D INTEL }JEX FILE
CHAPTEK 8: 8051 HARDWAR~ CONNECTION AN Se tion 8 1. Pin description o f the 8051 . S:tion Section
183 184 188 195
: ; Design and test o f D589C~x0 tramer 82 8.3: Explainin g the Intel hex file
CHAPTER 9: 8051 TIMER PROGRAMMING IN ASSEMBLY AN D C Section 9.1: Programming 8051 timers Section 92: Counter programming Section 9.3: Programming timers Oand 1 in 8051 C CHAPTER 10: 8051 SERIAL PORT PROGRAMMING IN ASSEMBLY AND C Section 10.1: Basics of serial comm unication Section 10.2: 8051 connection to RS232 Section 10.3: 8051 serial p ort programming in Assembly Section 10.4: Program.ming the second serial port Section 10.5: Serial port programming in C CHAPTER 11: INTERRUPTS PROGRAMMIN G IN ASSEMBLY AND C Section 11.1: 8051 interrupts Section 11.2: Programming timer interr upts Section 11.3: Programming external h ard ware interrupts Section 11.4: Programming the serial communication interrupt Section 11.5: Interrupt p riority in the 8051 /52 Section 11.6: Interrupt programming in C
201 202 217
222 237
238 242
244 255
261 271 272 275 279 284 288 290 299
CHAPTER 12: LCD AND KEYBOARD INTERFACING Section 12.1: LCD interfacing Section 12.2: Keyboard interfacing
300 311
CHAPTER 13: ADC, DAC, AND SENSOR INTERFAC ING Section 13.1: Parallel and serial ADC Section 13.2: DAC interfacing Section 13.3: Sensor interfacing and signal conditioning
321
CHAPTER ~4: 8051 INT~RFACING TO EXTERNAL MEMORY Sect~on 14.1: Serruconductor memory Sec~on 14.2: Memory address decoding Sect~on 14.3: 8031 / 51 interfacing with external RO M Sect~on 14.4: 8051 data memory space Section 14.5: Accessing external data me mory .m8051
35S
322 344
348
356 364 '361 371
c
381
CHAPTER ~5: 8051 INTERFACING WlTH THE 8255 Section 15.1: Programming the 8255 Sec~on 15.2: 8255 interfacing Section 15.3: 8051 C programming for the 8255 CHAPTER 16: DS12887 RTC INTERFACING Section 16.1: DS12887 RTC interfacin AND PROGRAMMING Section 16.2: DS12887 RTC program!in . Section 16.3: Alarm, SQ.W, and IRQ t g m C eatures of the DS12887 .
ch1p
vi
427 428 432
CHAPTER 17: MOTOR CONTROL: RELAY, PWM, DC, AND STEPPER MOTORS Section 17.1 · Rclav~ tlnd optoisolators Sc-:tion l7.2: Stepper motor intcrfacmg Section 17.3· DC motor interfaang and PWM
441
453 \ PPE.'.\01'< A 8051 INSTRUCTIONS, TlMING, AND REGISTERS
487 \ PPf DIX 8: BASlCS OF WIRE WRAPPING
49] APPE DIX C: TC TEC}INOLOGY AND SYSTEM DESIGN ISSUES
509 APPf\.DlX D: FLO\.VCHARTS AND PSEUDOCODE 513
APPFNDIX E: 8051 PRIMER FOR X86 PROGRAMMERS
514
,-\PPEXDIX F: ASCil CODES
Ci17
APPENDIX G: ASSEMBLERS, DEVELOPMENT RESOURCES, AND SUPPLIERS ,\PPL'\DIX H: DATA SHEETS
519
l:'l:DEX
545
7
C
t I
'.
1n Chapter 14 \Ve cover 8031/5 1 interfacing with external memories, both R?M and RAM:
Chapter 15 addresses the it>Sue of adding additional ports to the 8031/51 using an 8255 chip. Chapter 16 shO\\'S ho\v to connect and program the DS12887 real-time clock chip. Final!}, Chapter 17 shows basic interfacing to relays, optoisolators, and motors. . . The appendice5 have been designed to provide aJJ reference material required for the topics covered m the book. Appendix A describes each 8051 instruction in detail, with exan1ples. Appendix A also provides the clock count for instructions, 8051 register diagrams, and RAM memory maps. Appendix B describes basics of wire wrapping. Appendix C covers IC technology and logic families, as well as 8051 J/0 port interfacing and fan-out. Make sure you study this before c~nne~ting the 8051 to an external device. Jn Appendix D, the use of flow charts and psuedocode is explored. Append'.x E ts fo.r students familiar with x86 architecture who need to make a rapid transition to 8051 architecture. Appendix F pr~v1des the table of ASCII characters. Appendix G lists resources for assembler shareware, and electronics parts. Appendix H contains data sheets for the 8051 and other IC chips.
What is new in the second edition hrThe ~ggest change in this ne~v edition is the addition of 8051 C programmmg throughout the book. W11ile Chapters 1 t oug f6 us; Assem~ly l.anguage exclusively, starting with Chapter 7, we have both Assembly and C language programs or a the topics discussed. The second edition includes the following new features· new cha~ter on 8051 C programming (Chapter 7) · : new se~on on the 8051 C progran1ming of timers (Section 9.3) A new sec~on on the second serial port of the DS89C4x0 chip (Section 10 4) •• A · of the second serial port (Section · 10 5) A new section . on the 8051 c progranun1ng • 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 . of external memory (Section . • A new h 14.5) • A chapter on the DS12887 RTC (real-time clock) chip (Chapter 16) new c apter on motors, relays, and optoisolators (Chapter 17)
•1
~ab manual The lab Inanual and support mat . ls f . M.icroDigita!Ed.com Web site. er1a or this and other books by the authors can be f d otm at the www.
Solutions manualleQ.werPoinie slides The solutions manual was produced with th and Po~erPoint' sUdec. for the drawin are , ~ help of ~ rdeshir Eslamj (of Sharif U . . Education representative or visit wwwgs pea a, a1dlabl~ onhnc for instructors only Instrruvers1ty). The solu tions manua l . rsone .co.1n/muhammadaJ.1maz1d1 . . . uctors can contact the·1r p earson
Acknowledgments This book is thl' result of the ded·
. ciation goes to all of them icahon and encouragement of man . . . p· · Y t.nd1v1duaJs Ou . that ~;t~ :.w~ul~ l; ke to thank Professor Danny Morse th . r sincere and heartfelt appreHe is the one wh~ a strong need f~r a book such as ;hise :,ost knowledgeable and e ri architecture 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,
i;!
°
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. '
[email protected] [email protected] [email protected]
CHAPTERO
INTRODUCTION TO COMPUTING
OBJECTIVES Upon completion of this chapter, you will be able to:
> > > > > > > > > > > > >
>
Convert any number from base 2, base 10, or base 16 to either of the other h-vo bases Add and subtract hex numbers Add binary numbers Represent any binary number in 2's complement Represent an alphanumeric string in ASCII code Describe logical operations AND, OR, NOT, XOR, NANO, NOR Use logic gates to diagram simple circuits Explain the difference between a bit, a nibble, a byte, and a ivord Give precise mathematical definitions of the terms kilobyte, megabyte, gigabyte, and terabl(te Explain the difference between RAM and ROM and describe their use • Describe the purpose of the major components of a computer svstem
Uot dw thn!e typos in computers Describe the role of of the"-found CPU in computer systemsand describe the pu
1
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.
~
SECTION 0.1: NUMBERING AND CODING . SYSTEMS . rs use the base 2 (b'111ary) system.• In this section we \\lhereas human beings use base 10 (decimal} anthmetic, compu te d , ·ce versa. The convenJent representation explain how to convert from the decimal system to the binary sys~emll anth' ~inary format of the alphanumeric code of binary numbers in base 16, called hexadecimal, also is covered. Frna Y, e • called ASCII, is explored.
Decimal and binary number systems
Although there has been speculation that the origin of the base JO system is the fact th~t human beings have 10 fin. gers,. there ~ absolutely no speculation about the reason behind the use of the binary system Ul com,i:iuters. The bmary sys ~m.'s used in computers because 1 and Orepresent the two voltage levels of on and off. Where, s m base 10 there are JO distinct symbols,_O, 1, 2,..., 9'. in base 2 there are only hvo, Oand 1, with which to genera te numbers. Base 10 contains dig ,tsO through 9; binary contains digits Oand 1 only. These two binary digits, 0 and l, are commonly referred to as bits.
• Converting from decimal to binary of thOne m~thdod ofThic~nverting from _decimal to binary is to divide the decima I number by 2 repeatedly keeping track remain · ' ordere to obtainers. the b' s processbcontinues Thi . until the q uoti:"t beeomes zero. TI,e remainders are then written in revene mary num er. s 1s demonstrated ,n Example 0-1.
Example0-1 Convert the following deci mal numbe rs to binary . fonn: (a) 27 and (b} 125. Solution: (a) 27 Quot1 eiit 27/2 =
13/2 • 6/2 = 3/2 • l/2 •
13 6 3
Jl...,indar l LSB (least l 0
1 0
l l
MSB (moat
The binary equh•alent of 2710 : l lOl l z·
aignificant bit)
significant bit )
(b) 125 125/2 ~ 62/2 = 31/2 15/2 7 /2 3/2 1/2
• • • • •
Quot .I. et 62 31 15 7 3 l O
••••indftl LSB 0 l l l l l
The . MSB binary equivalent of 125,. • l llllOl:r
2
THE 80St MlCROC:o
_.
NTROLLER
ANO EMBEDDED
5'1••ff
must first master some very b . stem, one b ll Ilic . r ontroller-based ~.Y di jtal computers can e ca ed Cha 1 To understand the software and h:""dware _of a m:r~hich in the tradition of iJl!oduction to logic gates, an over,};" concepts underlying computer design. In this chap! are presented. After an . a brief histor y of CPU architecture\\, 0), the fundamentals of numbering an~ c~ing 5F~s ell in the last section we _givef thiS chapter, it is recommended ,L~· of the "'orkings inside the computer IS given. rna Y• . ny of the topics o u14t Although some readers may have an.adequate background ,n ma the material be scanned, however bnefly.
~
SECTION 0.1 : NUMBERING AND CODING SYSTEMS ~Q·ti·on we . rs use the base 2 (b.11111,Y) system • ln this =~ Whereas human beings use base 10 (decimal) arithmetic, compute d v·ce versa The con venient representation . • . th b. system an 1 explain how to convert from the decimal system to e rnary . th binary format of the alphanumeric code of binary numbers in base 16, called hexadecimal, also is covered. Pin Y, e ' called ASCJJ, is explored.
all
Decimal and binary number systems Although there has been speculation that the origin of the base 10 system is the fact that human beings ha~e 10 fin. gers, there is absolutely no speculation about the reason behind the use of the binary system m computers. The binary sys tern is used in computers because 1 and Orepresent the two voltage levels of on and off. Where,.s m base 10 there are 10 ~stinct symbols, 0, 1, 2, ..., 9, in base 2 there are only hvo, oand 1, with which to generate numbers. Base 10 contains dig its Othrough 9; binary contains digits Oand 1 only. These hvo binary digits, 0 and 1, are commonly referred to as bits.
Converting from decimal to binary One method of c~11verting from _decimal to binary is to divide the decimal number by 2 repeatedly, keeping track of ~he rema,~ders. ~s process contiflues until the quotient becomes zero. The remainders are then w ritten in reverse or er to obtain the binary number. This is demonstrated in Example 0-1.
Example 0-1 Convert the following decimal numbers to binary form: (a) 27 and (b) 125. Solution: (a) 27 27/ 2 • 13/2 •
Quotient
Rmui nder
13
l l
0
6 /2 3/2
=
6 3
=
l
1
l /2
•
0
1
LSB (least aigni!icant bit)
MSB (moat significant bi t)
The binary equivalent of 27 IC> = 11011 2• (b) 125
Quo t i ent 125 / 2 6 2/2 31/ 2 1 5/2 7/ 2 3/2 l/2
•
e
62 31 15 7 3 1
•
0
=
=
• •
R-..1.nder l LSB 0 1 1
1
1
1
MSB
The bJJ1ary equivalent of 125,. • 111110~.
2
THE 8051 MICRocoNTR.ott -ER. AND EMBEDDED 5yS'llld
Converting from binary to decimal To con, ert from binary to dec1n,al. it ts important to unders tand the con~ept of 11·eight as~oci.ited 1vith each Jigit position. First, as an analogy, recall the weight of numbers in the base 10 system, as shown in the diagram. By the same token, each digit position in a nun1ber in ba!>e 2 has a weight associated with it: 1101012 = lx2 Ox2 = lx2· = Ox2 lx2' = lx2 5 =
-
-
lxl Ox2 = lx4 Ox8 lxl6 lx32 =
-
Decimal
Binary
1 0 4 0 16 32 53
1 00 100 0000 10000 1 00000 110101
-
740683 0 3 X 10 1 8 X 10 1 6 X 10 0 X 10 4 X 10• 7 X 10s
-
-
-
3
80 600 0000 40000 700000 740683
Kno""·ing the ,veight of each bit in a binary number makes it simple to add them together to get its decimal equivalent, 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: Digit~ Sum:
(b) 1100101 \.\'eight: Digits: Sum: (c)lOill Weight: Digits:
Sum:
8 8+
4 0 O+
64
32
l 64+
1 32 +
1
2
]
1
1
2+
1 = 11 10
16 0 O+
8 0 0+
4 I 4+
1 I
16 1
8 0
4 1
16 +
O+
2 I
4+
2+
2 0
1 1
O+
1 = 101,0
1 = 2310
Eumple0-3 Use the concept of weight to convert 39 to binary. 19
Solution: Weight:
32 1
16 0
32+
O+
'1?1.mefowe,39.. • 100111r
8 0
O+
4 1 4+
2
1 2+
1 1
l •39
INTRooucnoN TO COMPUTING
3
I
Table o-1: Base 16 Number Systelt\s
Converting between binary and hex
i2
Binary 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100
To represent a binary number as its equivalent hexadecimal nwnbe r, start from ~he.right and iroup 4 bits at a time, re placing each 4-bit binary nun1ber with its hex cqmvalent s hown in Table 0-1. To convert from hex to binary, each hex d igit is replaced with its 4-bit binary equivalent. See Examples 0-4 and 0-5.
13 14
1101 1110
D E
15
1111
F
. .
Hexadecimal system
oecintal -
lied in computer
10 f 3 s4
Base 16 ' or the hexatfecimnl system as it · 1s caf b inary num bers · rep resentation o . literature· is used as a convenient . · resent a s trlllg 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 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· its. ln base 16, the fi rst 10 d igits, 0 to 9, are the same as u1 decima l, and for the remait1irlg six digits, the le tters A, B, C, D, E, and F a re used. Table 0-1 shows the equivalent b inary, deci mal, and h exad ecimal
has
;
8
9
To
representations for Oto 15.
11
H;;
oi-
234 -
5 6 -
78 9 A B
C
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
Convert . the hexadecimal numbers to b ,nary (a) F035, (b) AOl, and (c) 2E Solution:
·
(a) F035
The b'
Hex: Bina rv:
F 11 ll
0
0000
3 0011
m.uy representation is 1111000000110
Cb) AOI
5 0101
lOI Hex: Binary:
A 1010
0000
Hex:
2
E
Binary:
0010
0
I The btnary repl"l.'9elltation is 10100000000~1 (c)2E
1110 Th, binary ~ttNntation 111 101110 on
dropping the leeding Zffll9.
4
THt 80St MICROC
ONTROLLER
-
AND EMBEDDED Sffl ...
Converting from decimal to hex Converting from decimal to hex could be approached in two ,vays: l.
Convert to binary first and then convert to hex. Example 0-6 shows this method of converting deci,nal to hex.
2.
Convert directly from decimal to hex by repeated division, keeping track of the remainders. Experimenting with this method is left to the reader.
Converting from hex to decimal Conversion fron1 hex to decimal can also be approached in two ,vays: l.
Convert from hex to binary and then to decimal. Example 0-7 demonstrates this method of con verting from hex to decimal.
2.
Convert directly from hex to decimal by summing the weight of all digits.
E,cample 0-6 (a) Con\'ert 451d to hex.
-l
32
16
-8
-
0
l
- ,_-7)..
4 1
-
2
-ll
-0
'First, convert to binary. 321-8+4+1=45
.,__
45111 = 0010 1101 2 = 20 hex
512
256
l
0
-
,
-0128
-64 l
12
-1
-16 J
-08
-14
2 0
-
-1
2
-I
256
-0
128
-064
4 -132 -116 -8 0 0 171 4,,, =(1024 + 512 + 128 + 32 + 16 + 2) =011 010110010 , - 6B2 hex I
-1
i
.
,,
-
<:)
T .. ).
-
-
' -
~-
(:)
t~~~~.S,' \ C \J L
(c) Con\'ert 1714 hl to hex •
512
":>..
1
629,o =(512 + 64 + 32 + 16 + 4 + 1) = 0010 0111 0101 = 275 hex
1024
~
2.
(b) Convert 629 1 to hex. ~
~
-12
-1 0
',3J:,
Convert the following hexadecimal numbers to decimal. (a) 68210
\
=0110 101I 0010
1024 1
( (
2
512
t
256
o
-I
128
-064
-132
1024 + 512 + 128 + 32 + 16 + 2 = 1714
16 I
-
-08
-04
-21
1 0
10
Cb) 9F20" =1001 1111 0010 1101l 16384 8192 Allft.£ ""'"a 1 "IU7V ""1'90 02, 512 0 0 1 t 1 l ~ 128 32168 + 4096 + 20M + 1024 + Sl2 + 256 + 32 8 0 + +4+1 • . _ 32768 l
64
0
~ 1
16
8
4 2 o r 1 -0 -1 ]
10
INTRODUCTION TO COMPUTING
5
I
~~~~·~a~!A~d~d~i~ri~on~~==========~~=-Table 0-3: Bin carry Sum
Table 0-2: Counting in Bases Bina!}' Decimal
0 I 2 3 4 5 6
1 2
00()()1 ()()()10
00011 00100 00101 00110 00111 01000 01001 01010 01011 01100 01101 01110 01111
7
8 9 10 11
12 13 1-l
15
16
10000
17
10001 10010 10011 10100 10101 10110 10111
18 19
20 21 22
23 24
31
-
[+O ~Ai+iB==============~Ot::::=============tl====~ O L -
3
l+l
4 5
. ·n bases 1O, 2, and 16 Counting 1 . . between all tluee base~, in Table 0-2 we To show the relationship frorn o to 31 in d ecima l, along with show the sequence of nu~b:C! numbers. Notice in each base that
th:
the equivalent ~,nary;"to highest digit, that digit becomes zero when one more ,s add I-highest digit position. For example, in and a 1 is earned toththe nerrxy to the next-highest position. ln binary, .h . al9+1-0w1 aca d ec,m • . . . ·iady in hex, p + 1 = 0 w1t a carry. 1 + 1 : 0 with a carry, s1m1 '
9 A
B C D
E F 10 11 12
13 14 15 16 17 18
11001 11010 11011 11100 11101 11110 11111
26 27 28 29 30
0
QOi+!1:::=:::::::=::=::=::::oc=:::::::::=:::::::::::::::::::::::::::::Jot==::I+o 1
6 7 8
11000
25
Hex 0
!-
19
lA 18 lC 10
lE lF
Addition of binary and hex numbers The addition or binary numbers is a very straightforward process. Table 0-3 shows the addition of two bits. The discussion or subtraction of binary numbers is bypassed s.i nce all computers use the addHion process to implement subtraction . Although computers have adder circuitry, there is no separate circuitry £or subtractors. Ins tead, adders are used in conjunction with 2's co111pleme11t circuitry to perform subtraction. In other words, to implement "x - y", the computer takes the 2's complement of y and adds it to x. The con· cept of 2's complement is reviewed next. Example 0-8 shows the addition or binary numbers.
2's complement To get the 2'scomplementof a binary number invert all the bits and 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.
then
Exampleo-8
Add the binary numbers (a) 1011 + 111 and (b) 11010011 + 11011
11.
Solution: (a) 1011 + 111
IO 1 I
0111 10010 (b) 11010011 + 1101111
110100 11 01 1 0111 1 101000010
Decimal Equivalent 11 +7
18 Dttima/ Eq1livaltnt
211 + 111
322
6
THE 8051 MlCROC
ONTROL
. .....-.d
LER AND EMBEDDED SD•.....-
....
Example 0-9 Take the 2's complement of 10011101.
Solution:
+
binary number l's complement
10011101 01100010 1 01100011
2's complement
Addition and subtraction of hex numbers ln studying issues related to software and hardware of computers, it is often necessary to add or subtract hex numbers. Mastery of these techniques is essential. Hex addition and subtraction are discussed separately below.
Addition of hex numbers This section describes the process of addmg hex numbers. Starting with the least significant digits, the digits are added together. If the result is less than 16, write that digit as the sum for that position. If it is greater than 16, subtract 16 from it to get the digit and carry 1 to the next digit. The best way to explain this is by example, as shown in Example 0-10.
Subtraction of hex numbers In subtracting two hex numbers, if the second digit is greater than the first, borrow 16 from the preceding digit. See Example 0-11.
..
Example 0-10 Perform hex addition: 2309 + 94BE.
Solution: +
~ ·~
;l, I
(:) 2309 94BE 8897 ,.
/
LSD:
/-1 I
9 + 14 =23
1+ 13+11 = 25 1 +3 +4=8
23 - 16 = 7 with a carry 25 - 16 = 9 with a carry
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 41
Sy,,.bol A
Ha 61 62
sy,,,i,.1
a
ASCII code tation of number b 8 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
2. 3. 4. 5. 6. 7. 8.
CWhy do computers use the binary number system instead of the decimal system1 onvert 3-1 10 to bmary and hex. · Convert 110101, to hex and decimal. Perform binary addition: 101100 + 101. Convert 101100, to its 2's complement representation Add 368H + F6H. . Subtract 36BH - F6H. ~Vrite "80x86 CPUs" in its ASCII rode (in hex form).
SECTION 0.2: DIGITAL PRIMER This s«tion gives an overview of digital I · . gate:, tha! perform these functions. Next I . og1c and design. First, we cover b' . some logic devices commonly found . , .ogic gates are put together to fo . mary logic operations then we show in microcontroUer interfacing. rm sunple digital circuits. F~lly, we CO\'ff
Binary logic As mentioned earlier, computers use th . 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 +S Vas logic w1thm either of the tw nsha in the voltage A 05 ded are Logic gates as.
va?~i an~
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
ere.
t
5
r -~-~
3 J._~i,lfj 2
I
0
lnd send out
8
Fla- ~2- lh7ZJ' •••• THE 80St MICR OCoNTROLLER
.\ND EMBEDDED 9'1QS
C
logical AND function
AND gate
· AND on them. See 1 f The AND gate takes two or more inputs and per o~ a ~gic AND ate the truth table and diagram of the AND gate. Notice that 1f both ~p~ts tote tp t ~e are 1 the output wiU be l. Any other combination of inputs will give a 0 ~ ut. In ex~ple shows two inputs, x and y. Multiple outputs are also possible for logic ?a es. . . f . t · o the output IS zero. the case of AND, 1£ all .Inputs are 1, the output 1s 1. l any mpu IS ,
OR gate
Inputs
XY
XANDY
00
0
01
0
10
0
11
1
X y
XANDY
The OR logic function will output a 1 if one or more inputs is 1. If all inputs are 0, then and only then will the output be 0.
?,
Output
Logical OR Function
Tri-state buffer
.
A buffer gate does not change the logic level of the input. It is used to 1so1ate or
amplify the signal.
Inverter The inverter, also called NOT, outputs the value opposite to that input to the gate. That is, a 1 input will give a O output, while a O input will give a l output.
inputs
Output
XY
XORY
00
0
01 10
1
11
1
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 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.
NANO and NOR gates The NAND gate functions like an AND gate with an inverter on the output. It produces a zero output when all inputs are 1; otherwise, it produces a 1 output. The NOR gate functions like an OR gate with an inverter on the output. It produces a 1 if all inputs are O; othenvise, it produces a 0. NAND and NOR gates are used extensively in digital design because they are easy and inexpensive to fabricate. Any circuit that can be designed with AND, OR, XOR, and INVERTER gates can be implemented using only NANO and NOR gates. A simple example of this is given below. Notice in NAND, that if any input is zero the output is one. Notice in NOR, that if any input is one, the output is zero. '
Buffer
ContTol
Logical Inverter Input
Output
X 0
NOTX
1
0 X
1
--{)o- NOTX
Logic design using gates
_
d. ·ts If we add two bina.tY digits there are four J)Ossib!t
Next we wiU show a sitrtple logic design to add two bmary igi . outcomes;
Carry
S11m
0
0
O+O= O+l= ]+0=
0
1
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 e D flip-flop (D-FF) is widely used tot h d · a ,p- op. as the clock is activated. A 0-FF holds the as ~:e~: ~~~ table that a 0-FF grabs the data at the input
d:: r;~:a~::
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 HalfAdder
y
Carry out
f',gun 11-4. Block Dia
gr•i:n of• H•lf·Adder
10
TJiE 8051 MlCROC
ONTROLLER
AND EMBEDDED
sw•-
--
HalfAdder
X y
\..---Sum
Carry
____,sum
Final Carry
Half-
Cou t
Adder Carry Cin
Cm-----~
Final Sum
figure 0-5. FuJI-Adde r Built from a Half- Adder
I ct>
,.. )
~
). f
~ 1)
)
lJ I
i
i
XO
-
Full-
\ '
YO
d- -)
>
-so
Adder Carry
10 t I
-4'
Xl
SJ
Full-
Adder Yl
Carry
I X2 y2
PullAdder
52 Carry
S3
Figure 0-6. 3-Bit Adder Using 3 Full-Adders /'•O, V' •
-
t,\s)
lP
>'~ .J b''
I LS
p
'o
1 - - --
0 I (a) Address decoder for 9 (b11u1ry ~001 ) The output of tM AND gate y.·1U be 1 if and only If the input ill bmary 100I.
Cb) Addre"s decoder for 5 Cbinary 0101) The output of the AND gate " 'ill be 1 If and only if the input ill binary 0101.
.... IN'raooucr10N ro coMPUnNG lt
', ''}
X
y
"
>.
Su m
HaJf. Adder
y
Carry Final
Carry
/
~-_.JSum .
~
.
-
'
",, ' - Cout
HaU- 1---1 Adder Carry
Cm
Final Sum
Figure 0-5. Full-A dder Built from a H alf-Adder
It, b
,. )
~
I
'(
-
. , XO
>I
YO
Carry
' r,
~ -) ;,
-~ ' so
FullAdder
0 'O ' \
~
~
1
I
..f"
XI
51
Full·
Adder
Yl
Carry
I X2
52
FullAdder
Y2
Carry 53
Figure ~ . 3-Bit Adder Using 3 Full-Adders /'·~ "'
~
-
l (/c,,
I
LS
p p
.)I~
b; {
___,,
..__
I (a} Addl'l'Ss d ecoder for q (bina ry 1001) The output of the AND gai. 'l\'ill be 1 iJ and only If the input is bane,y 1001.
lless M . Addn 11
.,,
(b) Add ~ decod.r for 5 (binary 0101) The output of the A'.\10 gai. will be 1
If md only ti the input is binary 0101.
Decod•• 11
I •
D
Clk
D
.-
,.,
,
,.,
Q
-
-
ak
4>
'
'
,
/
J.)
Q
- - D
-No
X
v~it ~d C.
0
0
1,
1
1
Cl.k
-Q
-Q
x == don't care
(c) Truth table (b) Block diagram
-
4. 5. 6.
)
I
C..."'
Review Questions l. 2. 3.
no chan2e
-1,
(a) Circuit diagram
Figure 0-8. D Flip-Flops
Q
hen all inputs are 1.. . 1 . ,. ~t) gives a 1 outpu w re of its mputs ts . r. gives a 1 output when 1 o~ : : inputs have the same value. The logical operation The logical opera~on JV • I is often used to comp~e t The logical operationd :,< t change the logic level of the mpu . A gate oesn? Name a common use for ~p-flops. 'd tify a predetermined binary address. An address is used to i en t
SECTION 0.3: INSIDE THE COMPUTER
.
.
.
al workin of computers. The model.used . 'de an introduction to the orgaruzahon and ~teclmdin the £M PC PS/2, and compatibles. In this section we provt Li bl to all computers in u g ' d t · ology is generic, but the conc:pts d~scu~sed_are a~~ ~It~ review definitio~ of some of the most wfely use ermm Before embarking on thlS subject, it will ~e b ~e ROM RAM and so on. c*-'{ ?-,'-:_ ~ in computer literature, such as K, n1ega, g1ga, y ' ' ' ~ ~ <\ ('.
Some important terminology
a
\o- A:.
I
......_ _ _ :_ ::, _ __ __ _ _ _ _ _ _
One of the n,ost important features of a computer is h?w 1 / much memory it has. Here we review terms. used to describe Bit 0 amounts of memory in IBM PCs and comp~tibles. Recall from Nibble 4 0000 the discussion above that a bit is a binary d1g1t that can have the \ Byte r 0000 0000 value Oor 1. A byte is defined as 8 bits. A ni~ble is ~a~ a byte, or Word 0000 '()000 0000 0000 4 bits. A word is two bytes, or 16 bits. The display IS intended to show the relative size of these units. Of course, they could all be composed of any combination of zeros and ones. . Id 10 A kilobyte is 2 bytes, which is 1024 bytes. The abbreviation K is often used. For example, some flopp~ ~sks ho 356K bytes of data. A megabyte, or meg as some call it, is 220 bytes. That is a little over 1 million bytes; 1t LS exactly 1,048,576 bytes. Moving rapidly up the scale in size, a gigabyte is 230 bytes (over 1 billion), and a terabyte is 2 bytes (over 40 1 trillion). As an example of how some of these terms are used, suppose that a given compu ter has 16 megabytes of 20 4 20 memory. That would be 16 x 2 , or 2 x 2 , "."hie~ is 224. Therefore, 16 megabytes is 2 24 bytes. ,, Two types of memory commonly used in ffilcrocomputers are RAM, which stands for " random access memory (sometimes called read/write rnemory), ~d.ROM, ~hich stands for "read-only memory." RAM is u sed by the computer for temporary ~torage of progr~ that 1t 1s runn.mg. ~at data is lost when the computer is turned off. For this reason, RAM is sometimes called volat1/e niemory. ROM contams programs and informati ·a1 ti' o f the corn· · m · ROM ·is permanent, cannot be changed by the use puter. The .mformation d on . essenti to h opera th on is turned off. Therefore, it is called nonvolatile memory. r, an 1s not 1ost w en e power
Internal organization of computers The internal working of every computer can be broken down int thr . . . ) mem· ory, and I/0 (input/output) devices (see Figure 0-9). The function of~ ee P~rts: CPU (cen tral p rocessmg ~ t 'stored in memory. The function of I IO devices such as the keyboard and v. d e CP ~ is. to execu te (process) informabo~,-.dd'Ul 1 eo monitor LS to provid e a means of commwuu-...,.
12 THE
8051
-
MICRocoNTR.otLER AND EMBEDDED~
Address Bus Peripherall>
Memory CPU
•
(monitor, printer, etc.)
(RAM, ROM) \
,
Data Bus
figure 0-9. Inside the Computer
· f · all d bus The bus carries information ~,'ith the CPU. The CPU is connected to memory and I/0 through strips o Wll'e c e a · . t there are from place to place ~ e a computer just as a street bus carries people from place to place. In every compu er three types of buses: address bus, data bus, and control bus. dr · d For a device (memory or I/0) to be recognized by the CPU, it must be assigned an address. The ad ess assign~ to a given device must be unique; no two devices are allowed to have the same address. The CPU puts the addre~s (m binary, of course) on the address bus, and the decoding circuitry finds the device. Then the CPU ~ses_ the data bus et~er to get data from that device or to send data to it. The control buses are used to provide read or write signals to the device to indicate if the CPU is asking for information or sending it information. Of the three buses, the address bus and data bus determine the capability of a given CPU.
More about the data bus Since data lines are used to carry information in and out of a CPU, the more data lines available, the better the CPU. Uone thinks of data lines as highway lanes, it is clear that more lanes provide a better pathway between the CPU and its external devices (such as printers, RAM, ROM, etc.; see Figure 0-10). By the same token, that increase in the number of lanes increases the cost of construction. More data buses mean a more expensive CPU and computer. The grouping of data lines is called data bus. The average size of data buses in CPUs varies between 8 and 64. Early computers such as Apple 2 used an 8-bit data bus, while supercomputers such as Cray use a 64-bit data bus. Data buses are bidirectional, since the CPU must use them either to receive or to send data. The processing power of a computer is related to the size of its buses, since an 8-bit bus can send out 1 byte a time, but a 16-bit bus can send out 2 bytes at a time, which is twice as fast.
More about the address bus _Since the address bus is used to id~ntify the devices and memory connected to the CPU, the more address buses available, the larger the number of devices that can be addressed. In other words, the number of address buses for a
Address Bus
RAM
ROM
Printer
Disk
Monitor
Keyboard
CPU
Data Bus
Read/write Control Bus
F'
•gure 0.10. Jntemal Organization of Computers
-
1NnooucnoN TO COMPUTING
13
.
Th
umber of locations j5 al,vays equal to 2
:Or
.
I ations """ith \.vhich it can commurucatebus e 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 are what is called byte addressabl:. As another
&us
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
CPU and its relation to RAM and ROM
ROM The function of ROM in compute For the CPU to process information, the data must be stored in r · 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).
n
A
1'A
1 J.V'UY.
O
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 : ;ee~t~d m:rory. Registers inside the CPU can ~:;~bi~ 1~~~c;;s~~' o r the address of the value needed 0 registers is ~he an; biCPgger the registers, the bett~r the1CPU ; or~vedn 64-bit registers, depending su a U. · e sa vantage of more and bigger
:om
~~::s;~~:::t
:i,.
I I
[ Program Counter
I
a. a.
a (/)
c:, C:
Flags
(/)
ALU
lnstruction Register Instruction decoder, liming and control '
I
lniemal buses
Q ::,
ac:,
~
..or
0
Register A Register B
a,
~
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 0 ~ the next instruction to be executed. The contents of the progr~ co~ter are plac ~ truction pointer. 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 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.
t
Internal working of computers To demonstrate some of the concepts discussed above, a step-by-step analysis of the p rocess a CPU would go ~ough to add three numbers is given next. Assume that an imaginary CPU has registers called A, B, C, and D. It has an 8-b1t data bus and a 16-bit address bus. Therefore, the CPU can access memory from addresses 0000 to FFFFH (for a total of lOO?OH locations). The action to be performed by the CPU is to put hexadecimal value 21 into register A, and then add to register A values 42H and 12H. Assume that the code for the CPU to move a value to register A is 1011 0000 (BOH) and the code for adding a value to register A is 0000 0100 (04H). The necessary steps and code to perform them are as follows. Action Move value 21H i nto register A Add value 42H t o regis t er A Add va l ue 12H t o register A
Data 21H 42H 12H
Code BOH 04H 04H
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 1400 1401 1402 1403 1404 1405 1406
Contents of memory address (BO)code for moving a value to register A (21 ) value to be moved (04 )code for adding a value to register A (42) value to be added (04 )code f or adding a val ue to register A (12)va l ue to be added (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 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
/Y
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 04 ,nstea o n ove e I · 1 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 .intoerregts · t'er A, regardless of its value.
Review Questions J. How many bytes is 24 kilobytes?
2. 3. 4
s· 6. . 7. 8. 9. 10. 11. 12. 13.
. . sed ·n computer systems? What does "RAM" stand for? How ,sa t u ~ rs stems? What does "ROM" stand for? How ·~ ,t used ,n compute y Why is RAM called volatile memory· . componen ts of a computer. system. List the three ma1or . t 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 List the three type . •as uru'd'rectional and which is bidirectional. 1 State which of the fo LIowing . (a) data bus (b) address bus compu_t~ has 1O; rin~, w ha I is the maxinlum amount of memory 1t can access.1 [fan address bus for a given What does" ALU" stan~ for? What 1s ,ts pur~ose. How a,e registers used in computer systems; What is the purpose of the program counter. 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 to output. represent alphanumeric data internally in the computer. It is frequently used in peripheral devices for input used and/or 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 · · des,gn. · n=.cod ers are used to detect certain address- FLi ers flwere given as examp use o o c gates cor c1rcwt tch · 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()........
F ..:.---a
... • "'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 5. Convert the values in Problem 1 to hex. 6. Find the 2's complement of the following binary numbers. (a) 1001010 (b) 111001 (c) 10000010 (d) 111110001 7. Add the following hex values. (a) 2CH + 3FH (b) F34H + SD6H (c) 20000H + 12FFH (d) FFFFH + 2222H 8. Subtract the following hex numbers. (a)56-3E (b) 456F-OECF (c) F089EE - 897DEF (d) 76F-2AD , 9. Show the ASCII codes for numbers 0, 1, 2, 3, ... , 9 in both hex and binary . 10. Show the ASCII code (in hex) for the following string: · "in North America" C R, LF, "U.S.A. is a cow1try" CR, LF, CR is carriage return, LF is line feed
".> "
..o
::::>I
o
~
o"
J
b
c1 _J,(l4!- ~
v~
~e
~~
tftY'
~ ~~·
SECTION 0.2: DIGITAL PRIMER
' ~~ -rf, 11. Draw the logic diagram for Y =AB+ CD. "'-.... ' 12. Show the truth table for a 3-input OR gate. ,..)If 13. Realize the logic equation of Problem 11 using NANO gates only. 14. Sho\.v the truth table for a 3-input AND gate. (15. Design a 3-input XOR gate w ith a 2-input XOR gate. Show the tr uth table for a 3-input XOR. " 16. List the truth table for a 3-input NANO. 1 17. List the truth table for a 3-input NOR. \ __:::;-I ? 18. Show the d ecoder for binary 1100.$ .b-~ 0 t> " 4.9. Draw the d ecoder for'binary 01110}!4 o--t;r- I - tp. 20. List the truth table 'for a D-Ff._.., 1v-J' -\ t{, ') IA 1,,·f 1~
~
SECTION 0.3: INSIDE THE COMPUTER
cl'
J
, \;,!Gr ~ i ~
\ "'\:)
~
iol!t
,o--~ -
-
lo ')...
) 0
-
) 21. Answer the following: ,,. (a) How many nibbles are 16 bits? (b) How many bytes are 32 bits? '1 (c) If a word is defined as 16 bits, how many words is a 64-bit data item? ~ i ,,Q. (d) What is the exact value (in d~al) of 1 meg? ~J.():::. to'4 ~ S?b ~\ i(e)....How many K is 1 meg? IoV 1 ~ ~ .,.. ) I.( ' vJi t \I ~ What is the exact value (in decimal) <1f 1 giga? 0 , o ,o (g) How many K is 1 giga? {1 c. ) < '» ~ v l. v l. 1 (h) How many meg is 1 giga? f · • f "I (i) If a given computer has a total of 8 megabytes of memory how man b ; ' (' . kilobytes is this? ' Y Yes m decunal) is this? How many "- 22. A given mass storage device such as a hard disk can store 2 gigabytes of informa . . text has 25 rows and ea~ row h~ 8~ columns of ASCD characters (each char tio~ Asswrung that ~ch page of many pages of information can this disk store? acter - 1 byte), approxunately how ~ 23. In a given byte-addressable computer, memory locations 10000H to 9Pf . . first location is 10000H and the last location is 9FFFFH. Calculate th f FF1: are available for user programs. The (a) The total number of bytes available (in decimal) e O11owing: (b) The total number of kilobytes (in decimal)
... lknlooucr ION TO COMPUTING 1'1
,
ing capability? ,d_mum value that can address list the ma l What is its memory each computer, S ssor has a 20--bit addres~ b:~ir data bus widths- for 24. A micropr::ed several comp~ters(~1~~th hex and decimal). 1 at a tune m 25· Below areh · toth e cr1t ru be broug t m .th S-bit data bus A le 2 w1 an b ? (a) PC with a 16-bit data us PU given the size of the -
.----=
1J
icj ~:M PC with a 32·~:: ~ : ~:-bit data bus
ted for each of the following emory, in the units reques ' to ( ' •
c-
26.
c. ./
~;: 29. 30.
i
C
s,
(d) Cray supercompu f Find the total amount o m n- .._ ,. ., " !:;,, c address buses. . K) , - "t! r1 (a) 16-bit address bus(~ e ab tes) '" • (b) 24-bit address bus(~ m g aby tes and gigabytes) ? (c) 32-bit address bus(~ meg bytes gigabytes, and terabytes) . unidirectional. Why. (d) 48-bit address bus (m mega. yb"directiona1 and the address bus is mputer, the data bus lS 1 . omputer? ~;'~ function of the_ progra:;:i:;~~rp:r;~;~g addition? 4r. WhichsectionoftheCPU1sres~o CPU. 1t1,tl''"' t I"/' re,1 Rt.. List the three bus types present in every
~~e
~
ANSWERS TO REVIEW QUESTIONS SECTION 0.1: NUMBERING AND CODING SYSTEMS h f two voltage levels: on and off. 1. Computers use the binary system b ecause e ach bit can ave ,.. one o 2. 3410 =1000102= 2216 3. 1101012 = 3516 = 5310 4. 1110001 5. 010100
6. 461 7. 275 8. 38 30 78 38 36 20 43 50 55 73
C'""'
{) ' ""
')
k{
~
by
I
,.
SECTION 0.2: DIGIT AL PRIMER
l._ ~ I
1. AND 2. OR 3. XOR 4. Buffer 5. Storing data 6. Decoder
-,.( I
Y-
J'
SECTION 0.3: INSIDE THE COMPUTER 1. 24,576 2. Random access memory; it is used for temporary storage of programs that the CPU is running, such as the operating system, word processing programs, etc. 3. Read-only memory; it is used for permanent programs such as those that control the keyboard, etc. 4. The contents of RAM are lost when the computer is powered off. 5. The CPU, memory, and 1/0 devices 6. Central processing unit; it can be considered the "brain" of the computer; it executes the programs and controla all other devices in the computer. 7. The address bus carries the location (address) needed by the CPU; the data bus carries information in and out of the CPU; the control bus is used by the CPU to send signals controlling 1/0 devices. 8. (a) bidirectional (b) unidirectional 9. 641(, or 65,536 bytes 10. Arithmetic/ logic unit; it performs all arithmetic and logic operations. 11. It is for temporary storage of information. 12. It holds the address of the next irtstruction to be executed. 13. It tells the CPU what steps to perform for each irtstruction.
18
THE 8051 MICROCONTROLLBR AND BMDDDID
• _-
I ..
,
CHAPTERl
THE 8051 MICROCONTROLLERS
OBJECTIVES Upon completion of this chapter, you will be able to: ),,
> > >
),,
> >
Con1pare and contrast microprocessors and microcontrollers Describe the advantages of microcontrollers for some applications Explain the concept of embedded systems Discuss criteria for considering a microcontroller Explain the variations of speed, packaging, memory, and cost per unit and how these affect choosing a microcontroller Compare and contrast the various members of the 8051 family Compare 8051 microcontrollers offered by various manufacturers
,.
> , ••• , •.• \ • ,.
a-,,
19
. ,veryday life. In Section 1 1 Uers in e . th . 1¥t of microcontro f .....,1 · crocontrollers in e em~dl>,l Ce d ·mportan h use o "' · f I -~ 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
. with g_eneral-pupose rrucroerocessors
. MICROCONTROLLERS AND EMB 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
,J
e microprocessor 1 Microcontroller versus genera -purpos B micropro!;._essor is meant the general. 7 . d microcontroller · ~ . ) M t l • ~ Q/\.,J\
What is the difference between a microprocessor an 80386 80486 and the Penh um o r o oro as vvvAv 286 (8086, 80 , ' t . n' 0 RAM no ROM, and no I/ 0 ports on Purpose microprocessors such as Intel's x86 fanuly · onrocessors con am '. = ) Th 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. A-system designer usin& a general-purpose rmc~oprocessor su~ a:di:n of ext~al RAM, ROM, and 1/ 0 ports" 1/ 0 ports, and timers extem~y to make them funcho_nal. Althoug e d a e of versatility such tl1at the designer makes these systems bulkier and much more expensive, they have the a vant g d Thi . t th .th . can decide on the amount of RAM, ROM, and I/ 0 ports needed to fit the task at han · s 15 no e case WI rrucrocontrollers. A microcontroller has a CPU (a microprocessor} in addition to a fixed amo~t of.RA.M, ROM, l /0 '1orts, ~ a timer all ona smg1e chip:Tn other words, the processor, RAM, ROM, I/ 0 por~, and t~er ar~ all eml:2.edde .togei_L.. on ~ chh>; therefore, the designer cannot add any external memory, 1/ 0 , or tuner to 1t. Th_e fi~ed ~mo~t of on-chip ROM, RAM, and number of l / 0 ports in microcontrollers makes them ideal for many applications m which cost and space are critical. Jp mans applicatiQns, for examp!g_a JV remote control, there is no need for the computing power of a 486 or even an 8086 microprocessor. In many applications, the space it takes, the power it consumes, and the price per unit are much more critical consTclerations than the computing power. These applications most o ften require some 1/ 0 operations to read signals and tum on and off certain bits. For this reason some call these processors IBP, "itty-bitty proces~ors" (see "9ood Thing_s in Sma!] Packag_es Are Generati~g Big Product OePor_tunities" by Rick Grehan, BYTE maga~~e, Sept~mber 1994; www.byte.com, for an excellent discussion of microcontrollers). . _It 1s interesting to note that some microcontroiler manufacturers have gone as far as integrating an AOC (analog-tod1gital converter) and other peripherals into the microcontroller.
;s
V M·1crocontrollers for embedded systems ln the lit~ature discussing microprocessors, we often see the te . . trollers are \v1dely used in embedded system products An b dd nn embedded systcn,. Microprocessors and rrucrocon. _em e ed product uses a n\icroprocessor .{_or microcontroller)
CPU
Data bus
General-
Purpose Micro-
RAM
1/0 Port
ROM
processor
Timer
CPU
RAM
ROM
1/ 0
limer
Serial
Serial
COM Port
COM
Address bus
Port
(a) General-Purpose Microprn.-~- S ~~'"""r
ystem {b) Microcontroller
Figure 1-1. M icroprocessor System Contruted With Mi crocontroUer Syste m
20
THE 80St MICR.<>c ONTROLLER AND EMBEDDED S~
le of embedded system since to do one task and on~sk only_.[!. printer exa~pgetting the data and printing me processor inside it perf~rms only one tas , nam~ IBM-compatible PC). 1 PC can it)Contrast this with a Penbum-based PC (or any x rocessor print server, bank ~ used for any number of applications such as wor~ P t te~al. Software for :..:;....-.-:~la twork server or inteme teller terminal, video game p yer, ne se the reason a PC can perof applications can be loaded and run. cour . tin system that loads form myria~ tasks is tha_t it has RAM memory and an angembedded system, the application software mto RAM and lets_the ~PU run ed into ROM. An x86 PC there is only one application software that IS typically b ~ the keyboard, printer, contains or is connected to various embedded products sue as d Each one 0 modem, disk controller, sound card, CD-~OM ~ver, mouse, an ~ ~~~ task. For of these peripherals has a microcontroller ms1de it that performs 0 Y th t k f · tr u that performs e as o . example inside every n1ouse there ts a microcon o er b dd d finding the mouse position and sending it to the PC. Table 1-1 lists some em e e
i~'.111
Of
avanety
°Ft~:
products.
...~.J
p, odJ.J.d
~ ft.A "tt:> t
~
4 ~\ "--
- ( c._
' X86 PC embedded applications
C>""'~ .
Although microcontrollers are the preferred choice for many embedded sy~tems there are times that a microcontroller is inadequate for the task. For this reason, in recent years many manufacturers of general-purpose microprocessors such as Intel, Freescale Semiconductor Inc. (formerly Motorola), AMD (Advanced Micro Devices, Inc.), and Cyrix (now a division of National Semiconductor, Inc.) have targeted their microprocessor for the high end of the embedded market. While Intel and AMD push their x86 processors for both the embedded and desktop PC markets, Freescale is determined to keep the 68000 family alive by targeting it mainly for the high end of embedded systems now that Apple no longer uses the 680x0 in their Macintosh. In the early 1990s Apple computer began using Power PC microprocessors (604,603, 620, etc.) in place of the 680x0 for the Macintosh. The Power PC microprocessor is a joint venture between IBM and Freescale, and is targeted for the high end of the embedded market as well as the PC market. It must be noted that when a company targets a general-purpose microprocessor for the embedded market it optimizes the processor used for embedded systems. For this reason these processors are often called high-end embedded processors. Very often the terms embedded processor and rnicrocontroller are used interchangeably. One of the most critical needs of an embedded system is to decrease power consumption and space. This can be achieved by integrating more functions into the CPU chip. All the embedded processors based on the x86 and 680x0 have low power co'.15ump~on in addition to some forms of I/0, COM port, and ROM all on a single chip. In high-performance embedded processors, the trend is to integrate more and more functions ~n the C~~ chip_and let the designer decide which features he/she ~ants to use. This trend 1s mvadmg PC system design as well. Normally, in designing the PC motherboard we need a CPU plus a chip-set containing 1/0 a ch controller, a flash ROM containing BIOS, and finally a secondary cache ' ca e F memory. . . . . d N . ew d es1gns are emerging in m ustry. or example, Cyrix has announ d th . . th t · th · PC, except for DRAM. In other ce w atd 1t IS working on a ch1p a contains e entire we are about to see an entire computer on a chip. or s, Currently, because ofMS-[X)S and Windows standardization m systems are using x86 PCs. In many cases using x86 PCs for the high- an~ em~edded ?PPlications not only saves money but also shortens development e~ edded 1s a vast library of software already written for the DOS and w· d e since there The fact that Windows is a widely used and well understood ~ ows platforms. 1 developing a Windows-based embedded product reduces the ~ or;; hmeans that 5 development time considerably. an s ortens the I
•
i:
!o
Table 1-1: Some Embedded Products Using Microcontrollers Home Appliances Intercom Telephones Security systems Garage door opei:ers Answering machines Fax machines Home computers ~
TVs _. Cable TV tuner VCR Camcorder Remote controls Video games Cellular phones ' Musical instruments v Sewing machines Lighting control Paging Camera ' Pinball machines Toys Exercise equipment Office Telephones Computers Security systems Fax machine Microwave Copiet/ Laser printer,/ Color printer"" Paging Auto Trip computer Engine control./ Airbag ...., ABS Instrumentation . Security system _,,, Transmission control Entertainment Climate control Cellular phone Keyless entry
-
Tl-IE 8051 MICROCONTROLLERS
21
V
/
, Zilog's Z8, and PIC 16~ from 051 Choosing a microcontroller h are: Freescale's 6811, ~tels ~d'r;gister set; theref~re, they are f a·or a-bit rn.icrocontroJlers. T ey h s unique instrucnon set There are also 16-bit and 32-bit 0 The~e are_1. m J Each of these microco~troUefr!L-ae ... :11,Jtot run on lll.e other__s.U_ what criteria do designers M' ochip Teuu,o1ogy. . writti>n .ct on WJ.1..1 • • contro er6 , . 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.
/
:r
a
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 raor 32-bit microcontrolJer can best handle the computmg , P. 7. r tions in this category are: , P . h hi h t ed that the microcontroller supports. (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.
t,
(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~ations 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.
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. Company See Table 1-2. Web Site • Intel www.intel.com/ design/ mcs51 It should be noted that Freescale, Zilog 1 Atmel and Microchip Technology have all dedicated www.atmel.com ma~siv~. resource~ to ensure wide and timely Philips /Signetics www.serniconductors.philips.com availab1lity of their product since their product Infineon is stable, mature, and single sourced. In recent www.infineon.com Dallas Semi/Maxim years they also have begun to sell the ASIC www.maxim-ic.com library celJ of the microcontrolJer. 3.
-
~,~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
. 3 4.
s. 6. 7.
. h O f th f llowing devices on-chip? A microcontroller normally has "vhlc ( )~/~ v(d) all of the above (a) RAM (b) ROM c hi h f the following devices to be attached to it? A general-purpose microprocessor normally needs w c o ""(d) 11 of the above (a) RAM (b) ROM (c) I/0 a An embedded system is also <;.a~d a dedicat~ systetn- Why? What does the term etnbedded system mean? ? Why does having multiple sources of a given product matter·
SECTION 1.2: OVERVIEW OF THE 8051 FAMILV
ontrollers and their internal features. · f il f 1 In this section we first look at the various members of the 805 am Yo nucroc Plus we see who are the different manufacturers of the 8051 and what kind of products they offer.
A brief history of the 8051 In 1981, Intel Corporation introduced an 8-bit microcontroller called the 8051. This microcontroller had 128 bytes of RAM, 4K bytes of on-chip ROM, two timers, one serial port, and four ports (each 8-bits wide) all on a single chip. At the time it was also referred to as a "system on a chip." The 8051 is an 8-bit processor, meaning that the CPU can work on only 8 bits of data at a time. Data larger than 8 bits has to be broken into 8-bit pieces to be processed by the CPU. The 8051 has a total of four I/0 ports, each 8 bits wide. See Figure 1-2. Although the 8051 can have a maximum of 64K bytes of on-chip ROM, many manufacturers have put only 4K bytes on the chip. This will be discussed in more detail later. The 8051 became widely popular after Intel allowed other manufacturers to make and market any flavors of the 8051 they ~leas~ with the condition that they remain code-compatible with the 8051. This has led to many versions of the 805~ with different speeds and amounts of on-chip ROM marketed by more than half a dozen manufacturers. Next we review some of them. It is important to note that although there are different flavors of the 8051 in terms of speed
gos-' --,./
S s ON-CHIP ROM INTERRUPT
CONTROL
--
"'
ETC. TlMERO
ON-CHIP RAM
I,.
:::..
•
'<- ./.,.
~/
BUS CONTROL
-
~
·-+
"
TIMER1
,c
L"'~
I\
osc
"
g
I/
CPU ~
c:i0tS5 '
(7
for program code
"' rJ.;
~'f
t,,/
I ~
...+
Figure 1-2. Inside the 8051 Mlcrocontroller Block Diagram
-THE IOSl MICllOCONTROLLEllS
'<:'.._
41/0
7
SERIAL
PORTS
PORT
tttt
PO
TXD RXD '
w .( . -t ~ •
23
. iJ1al soSl .th the orig ol.11' all compatible w1 if you write y unt of on-chip ROM, they ared This means thatth manufacturer· O d an am . e concerne · di s of e as far as the instructions ar of them regar es . will run on any program for one, 1t
8051 mlcrocontroller
·t as
~-:1
. . b f the 8051 fauwY· The 8051 is the original me~ ~:a':ures of the 8051. MCS-51. Table 1-3 shows the mrun
Other members of the 8051 family
.
Intel refers to i
ra
ble 1-3: Features of the 8051 Quantify 4K bytes'
feature
jzoM
128 bytes
~~-----2;--::...:.::-Tl~iIJl~e~r----~~~~~~;----_:: 32
I/0 pin.S
1
-
0 t-- ~ r i al port 6. - terrupt sources ~ M !Jlount indicates on-chip program Note: RO a of microcontrollers. space.
There are two other members in the 8051 family They are the 8052 and the 8031.
8052 microcontroller
d d features of the 8051 as well as an extra b f th 8051 familv. The 8052 has all the stan arf RAM and 3 timers. It also has BK bytes . The 8052 IS another mem er o e ~ d the 8052 has 256 bytes o 128-bytes of RAM and an extra timer. In other wor s, . of on-chip program ROM instead of 4K byt~s. See Table 1-4. 8052· therefore, all programs written for the 8051 will run As can be seen from Table 1-4, the 8051 is a subset of the ' on the 8052, but the reverse is not true.
8031 microcontroller Another member of the 8051 family is the 8031 chip. 'l]\is chip is often referred to as a ROM-less 8051_ since it has OK bytes of on-chip ROM. To use this-chip you musTadd external ROM to it. This external ROM must con tam the program that the 8031 will fetch and execute. Contrast that to the 8051 in which the on-chip ROM contains the program to be fetched and executed but is limHed to only 4K bytes of code. The ROM containing the program attached to the 8031 can be as large as 64K bytes. In the process of adding external ROM to the 8031, you lose two ports. That leaves only 2 ports (o~ the 4 ports) for I/0 operations. To solve this problem, you can add external I/0 to the 8031. Interfaciru! the 8031 with memory and l/0 ports such as the 8255 chip is discussed in Chapter 14 There a l · d- -v · f the 8031 available from different companies. · re a so vanous spee versions o
Various 8051 microcontrollers . ~though the 8051 is the most popular member of the f . . 8051 This IS because the 8051 is available in different memo typ amily, you will not see "80Sl,, in th art umber have different part numbers. A discussion of th . ry es, such as W-EPROM fl.a h e p n . version of the 8051 is the 875l The flash ROM e vai:ious types of ROM will be . ' . s I and NV-RAM, all of which Dallas Semiconductor. The A~el Flash 8051 . ve~1on is marketed by many c given~ C~apter 14. The UV-EPROM (DS89C420/430/440). The NV-RAM version of!Sthc ed AT89C51, while Dallas omp~es including Atmel Corp. and an OTP (on~time programmable) version of the 8~:f51 made by Dallas Semico:nuco~ductor calls theirs DS89C4x0 the above chips and describe applications where th made by various man:ut ductor lS called DSsooO There is also ey are used acturers Ne t . · · · x we discuss briefly each of
Table 1-4: Comparison of 8051 F . Feature atnily Members ROM (on-chip program space in b
8051 8052 81(
8031 01(
'l')
24
Serial port Interrupt sources
3 1
32
6
l
8
128 2
32 l 6
u::r
,, · this chi for development reqwres access to a . 8751 mlcrocontroller This 8751 chlp has only 4K bytes of on-chip UV-EPROMi 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 before it can be programmed again. This has le~ many manufa~er; ~ ~ :vailable from different companies. 8051, as we will discuss next. There are also various speed versions o e
d:
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 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.
c
DS89C4x0 Trainer . In C:1~pter 8, we dis~uss ~e design of DS89C4x0 Trainer extensively. The MDE8051 Trainer is available from www.
~croDigitalEd.com. This Trainer allows you to program the DS89C4x0 chip from the COM port of the x86 IBM PC with no need for a ROM burner. '
For a D5B9C4x0-based trainer see www.MlcroDlgltalEd.com.
AT89C51 from Atmel Corporation The Atmel Corp. has a wide selection of 8051 chips as shown · T a popular and inexpensive chlp used in many small pr~ects Ith ~ ables 1-6 and 1-7. For example, the AT89C51 is where "C" before the 51 stands for CMOS which has a low · as byt~s of flash ROM. Notice the AT89C51-12PC "C" . ' power consumption "12" in . dicates 12 MHz, "P" is for plastic' pac ge, 1s for commercial. , DIP ka
Table 1-5: Versions of 8051/52 Microcontroller From Dall Part Number
ROM
-
RAM
DS89C420/30
16K (Flash)
DS89C440 \tbS89C450
UO ·
. as Semiconductor (Maxim) Timers
Interrupts
3
6
sv
256
pins 32
321< (Flash)
256
32
64K (Flash)
3
256
6
5V
32
DSsooo
8K(NVRAM)
3
128
6
-DS8oo20 DS87520
oK
32
5V
2
6
32 32
3 3
6 6
sv sv sv
-
16K (UVROM)
256 256
Sourct·. www .maxim-,ccom/products/microcontrollers/8051 . . _d rop_m.cfrn
-
TliE 80S1 MICROCONTROLLERS
25
OM flash) . 051 From Atmel (All R Table 1-6: Versions of 8 I/0 pins ROM
Part Number AT89CS1
4K
AT89LV51
4K
AT89C1051
1K
2K
AT89C2051
BK BK
AT89C52 AT89LV52
JnterruPt 6
Timer 2
RAM 128
32
128
32
64
15
128
15
128 128
32 32
6
2
3
1
6
2
8 8
3 3
V SV
Pac 40
3V
40
3V 3V
20 20
SV 3V
40
40-
'
Nolt: "C" in the part number indicates CMOS.
Table 1-7: Various Speeds of SO51 Fr om Atmel
.
AT89C51-12PC
Speed 12MHz
Pins
40
Packaging DIP plastic
AT89C51-16PC AT89C51-20PC
16MHz 20MHz
40 40
DIP plastic DIP plastic
Part Number
Use commercial commercial commercial
OTP version of the 8051
There are also OTP (one-time-programmable) versions of the 8051 available from different sources. Flash and NVRAM versions are typically used for product development. When a product is designed and absolutely finalized, the OTP version of the 8051 is used for mass production since it is much cheaper in terms of price per unit.
8051 family from Philips Another major producer of·the 8051 family is Philips Corporatio Ind d · 8051 m.icrocontrollers. Many of their products include featur ch n. ee , they have one of the largest selections ol 1/0, and both OTP and flash. For the list of companies prod:~;u thas A-to-D ~onverters, D-to-A converters, extended g e 8051 family see the Web sites in the box below.
See the following Web sites f 8 their features from va I or 051 products and r ous companies. • www.aos2.com/chipa.phtm1 WWW.MicroDlgitalEd
.com
Review Questions 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 · ~ • 11 0 ntroUers? 4. Give the size of the on-chip ROM in :ac~wing: (a) 805] {b) 5. The 8051 is a(n) (/-, -bit microp of the following· 2 (c) 8031 6. State a major difference between ther;~~s; · (a) 8051 {b) 80si ( ) c 8031 7. True or false. The DS89C420/JO is r " ' e AT89c:5 1 ea y an 8052 chi , anct the Qssar, p. J'-420/30. u v
~~f
Uminating the need for ROM burner. dded to the chip, therefore e mb 30 has a loader e e £ chi ROM. 8 True or false. Th e DS89C42o/
9: The DS89C420/30 chip has
10. The DS89C420/30 chjp has
bytes o on- p bytes of RAM.
SUMMARY
. d !if Microprocessors and rrucro. ntrollers m every ay e. k W als This chapter discussed the role and importance o rrucroco f . ocontrollers in the embedded mar et. e . o controllers were contrasted and compared. We discussed the o rrue:d memory I/0, packaging, and cost per wu.t. discussed criteria to consider in choosing a microcontroller s ue ~ sp f the 8051 s~ch as the 8052 and 8031, and their The second section of this chapter described various family mem echrs o th AT89C51 and DS89C4x0, which are mar. · f the 8051 su as e features. In addition, we discussed various versions o keted by suppliers other than Intel. f
us:
~
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..) 1 2. True or False. The 8051 is manufactured by more than o~ manufacturer. l f>-. ~ J 3. True or False. A microcontroller has on-chip 1/0 ports. I . . ? e..c,rr, Q ,._ -M. -\ 'fV' ' l ,. c_~u._., ,, 4. Trtie or False. A microcontroUer has a fixed amount of RAM on the chi.P· 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. "'"' ~ "' ' ) Why would someone want to use an x86 as an embedded processor? ( , , (¢-A ) -{ t cc;,,.. CftG.. c... ( M ~ <:f"'~O... 1 9. Name two 16-bit microcon trollers. .S LC.. I ~ 1 b - ' 2., 1-o ~ 10. True or False. The 8051 has on-chip ADC. 7c ,.. (" "' "('.. r ~ 11. Which operating mode of a microcontroller is useful in battery-based embedd ed products?POL-" ·
. Jo
1
SECTION 1.2: OVERVIEW OF THE 8051 FAMILY L
\ -:::,~ 1t..\1Y\I<" '"''-
The 8751 has !li3). bytes of on-chip ROM. The 89C51ED2 has :2- l& bytes of on-chip ROM. Which timer of the 80ql can be used as a counter as well? .:t:.,\'V'\~ , o,. "\ 'y,.,.""'~ < , The 8052 has S: b bytes of on-chip RAM. The ROM-less version of the 8051 uses t,o 5I as the part number. The 8051 family has ~').... pins for 1/ 0 . How many pa rallel and serial port lines the 8051 has? ~ Sc,A..je.R. H'"'d YlO The 8751 on-chip RO M is of typ e S":i The AT89C51 on-chip ROM is of type ot The DSSOOO on-chip ROM is of type f...f.A •f.t /"J" l /.I n"\ The DS89C420/30 on-chip ROM is of type ~ Give the amo unt of ROM and RAM for the following chips· {) I (a) AT89C51 ~'-~~ (b? DS89C420/ 30'!?, "'t (c) DS89C440 . JJ. "28. Of the 8051 family, which memory type is the most cost eff ~) 6. ~ product? ( c-r P) .Jc t'f, o" ective if you are using a m illion o f the m in an embedded
16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27.
z
f>.u..
P.
fl ~~
.,,. (_
p
29. Which vers io~ of the 8051 does not have on-chip ROM? ~O!. I 30. Of the 8051 m1crocontrollers, which one is the best for h to a ROM burner.) a ome d evelo pment e nv ironment? (Yo u d o not have access
THE 8051 MlCJlOCONTROLLBRS
' 27
C)
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 7. Having multiple sources for a given part means you ~e nt among suppliers brings about lower cost for that pro uc ·
oq
SECTION 1.2: OVERVIEW OF THE 8051 FAMILY l. 128 bytes of RAM, 4K bytes of on-chip ROM, four 8-bit I(O ports. th on-chip 2. The 8052 has everything that the 8051 has, plus an extra tuner, and e The RAM in the 8052 is 256 bytes instead of 128 bytes.
ROM is 8K bytes instead of 4J( 1..-...... "11Q
3. Both the 8051 and the 8031 have 128 bytes of RAM and the 8052 has 256 bytes. 4. (a) 4.K bytes (b) 8K bytes (c) OK bytes 5. 8
6. The main difference is the type of on-chip ROM. In the 8751 it is UV-EPROM; in the AT89C51 it is flash; and in~ DS89C420/30 it is flash with a loader on the chip. 7. True 8. True 9. 16K 10. 256
28
CHAPTER2
8051 ASSEMBLY LANGUAGE PROGRAMMING
-
OBJECTIVES Upon completion of this chapter, you will be able to: List the registers of the 8051 microcontroller Manip~ate data using the registers and MOV instructions Code sunple 8051 Assembly language instructions Assemble and run an 8051 program Describe the sequence of events that occur u on 805 Exam~e programs in ROM code of the 8051 p 1 power-up Explain the ROM memory map of the 8051 Detail the execution of 8051 Assembly langu . . age instructions Describe 8051 data types . E~plain the purpose of the PSW (program status wor ~scuss RAM memory space allocation in the 8051 d) register Dia~am the use of the stack in the 805l Marupulate the register ban.ks of the 8051
1,
Ir
. --
.'
29
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 direcprogramming and define terms su.ch ~s rnne;.0 ~~tion 2.3. Step-by-~e~ sorne widely us~ and hoW tlley are affected ban.ks of tile 8051 are ready-to-run program for the 8051 ts d1scu.sse in In 5eetion 2.5 we Loo a . cuss the f)ag bits . 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.
d
. with the siJllple instructions MOY . d show thelI use 6 Ln this section we examine the major registers of the 805l an ;; andADD.
SECTION 2.1 : INSIDE THE 8051
~~ ~
·
Y
Th inf tion could be a byte of data to be Registers 1n the CPU, registers are used to store information temporarily. at orma . . . 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 gJ,
list of 8051 reg1Sters.
f,, ~
,#
GGGGGGGG
. The most widely used registers of the 8051 are A (accumula pointerlla,and PC .
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 instructions. counter. The MOY and ADD.To understand th e useprfogram O these registers, we
MOV instruction
A
)( \~I ,.,
~
B
==R0=~11
rl
I I I I I
I I I
Rl
j~
R2
I q,v> I I
R3i0R4
R5
.,;,
Simply stated, the MOV i . i has the following format·· nstruction copies data from one 1 ti' MOV dest · . oca on to another. It 1nat1on , 60 urce ·c This · tru · ' opy sour destinati· ms ction tells the CPU t ce to dest. on operand F o move (' . or example, the . m reality, copy) th of register ROto re same value as regi~t!!e;~- After this ins~~~tio~ " Mov A, : 0~?urc~ op erand to the The following program f. The MOY inst ~on ts executed . copies the contents 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 soon. on~ signifies that registers ~ i;alue SSH (that ~ siu~ce operand. 5 a value. The. e the CPU N ~ 5 m hex), then • unportan . Otice the ,, #" . th 1 t rf, ce of th' . m e 'I fJ lS W 1ll be discussed
i
IS
~PTR
I
[ _
R7 ~'<>
Figure 2-1 (a). Some 8-bit Registers of the 8051
30
~~1fus
j
DPH J -..:.:_-JL-
g '7
-;;,r PC
-
-
d.d r /
.:>I
so•
uee..
_,,-,
value SSH into reg. A MOV A,#SSH ;load contents of A into RO MOV RO,A ;copy ) ; {now A=RO=SSH ;copy contents o f A into Rl MOV Rl,A . (now A=RO=Rl=SSH) ;copy contents of A into R2 MOV R2,A ;now A=RO=Rl=R2=5SH) ,·load value 95H into R3 MOV R3,#95H ; (now R3=9SH) MOV A,R3 ;copy contents o f R3 into A ·now A=R3=95H) ' . oints should be noted: When programming the 8051 microcontroller, the following P . . . . th t ·t is an unmed1a te . or RO - R7. However, to indicate a l t Valu es can be loaded directly into any of registers A, B, 1. value it must be preceded with a pound sign . (#)Thi' 0 · sis shwnnex. MOV MOV MOV MOV MOV MOV MOV MOV
A,#23H R0,#12H Rl,#lFH R2,#2BH B,#3CH R7,#9DH RS,#OF9H R6,#12
;load ;load ;load ;load ;load ;load ;load ;load ;into
23H into A (A=23H) 12H into RO {RO=l2H) lFH into Rl {Rl=lFH) 2BH into R2 (R2=2BH) 3CH into B (B=3CH) 9DH into R7 (R7=9DH) F9H into RS (RS=F9H) 12 decimal (OCH) reg. R6 (R6=0CH)
Notice in instruction "MOV RS, #OF9H" that a Ois used between the# and F to indicate that Fis a hex number and not a letter. In other words "MOV RS, #F9H" will cause an error. 2. If values oto fare moved into an 8-bit register, the rest of the bits are assumed to be all zeros. For example, in "MOV A, #5" the result will be A= 05; that is, A= 00000101 in binary. 3. Moving a value that is too large into a register will cause an error.
-
-
MOV A,#7F2H ;ILLEGAL: 7F2H > 8 bits {FFH) MOV R2,#456 ;ILLEGAL: 456 > 255 decimal {FFH)
4. A value to be loaded into a register must be preceded with a pound sign (#). Otherwise it means to load from a memory location. For example ''MOVA, l 7H" means to move into A the value held in memory location 17H, which coiila have any value. In order to load the value 17H into the accumulator we must write "MOV A, #1 7H" with the # preceding the number. Notice that the absence of the pound sign will not cause an error by the assembler since it is a alid instruction. However, the result would not be what the programmer intended. This is a common error for beginning programmers in the 8051.
ADD instruction The ADD instruction has the following format:
•
ADD A,source
;ADD the source operand ;to the accumulator
{ ov.n:
,,..,J
~
b~ ~ dJ ~4. .! -I-arc_ of. ..f-t> ('A > ~ • ...,~
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 MOV R2, #34H ; load 34H into R2 r~ , ;..,, ~~ 't · ADD A, R2 ; add R2 to accumulator { ' ' ; (A • A + R2) ~ It\ p_.) ~ u.~,~·
l
8051 ASSEMBLY LANGUAGB PROGRAMMING 31
. e that the content of R2
~,u Nobe d R2 == .;'tl • · gisters used. Another way 34fl == 591-{) an ding on the re ults in A :: 59H (25B + ways, depeJl Executing the program above res ..,,.;tten in Jllal\Y bove can be .... .
does not change. The program a might be: (RS:2SH) ;load 25H into RS :34Hl MOV RS,#2SH ;load 34H into R7 (R71ear A) MOV R7, #34H ·load o into A {A=o,c MOV A,#0 '.add to A content of RS ADD A,RS ·where A= A+ RS ' f R7 ADD A,R7 ;add to A content O ram One q uestion ;where A = A + R7 write the same prog · . . . are always manY way~ ~o to move both data items into The program abo~e results m ': "' 59H. There bove is whether it 1s necess31Oll0 wing variation of the same that might come to mlI\d after looking at the pro~am a.tis ~ot necessary. Look at the 1 registers before adding them together. The answer 1s no, program: MOV A,#25H ;load one operand into A {A=25H) ADD A,#34H ;add the second operand 34H to A . th d alue followed the instruction as an o p erln the above case, while one register contained one val ue, e secon v . · · di te that the so rce u and. This is called an immediate operand. The examples shown so far for the ADD instructlo~ in ca operand can be either a register or immediate data, but the destination mus~ always be register A, the acc~ulator. In other words, an instruction such as "ADD R2, #12H" is invalid since register A (accumulator) must be involved in any arithmetic operation. Notice that "ADD R4, A" is also invalid for the reason that A must be the destination of any arithmetic operation. To put it simply: In the 8051, register A must be involved and be the destination for all arithmetic operations. The foregoing discussion explains why register A is referred to as the accumulator. The format for Assembly language II\Structions, descriptions of their use, and a listing of legal operand types are provid ed in AppendlX A.l. There are two 16-bit registers in the 8051: PC (program counter) and DPTR · use of the program counter are covered in Section 2.3. The DPTR . . .(data p~mter). The imp o rtance and Chapter 5 \vhere addressing modes are covered. register IS used Lil accessing data and is d iscussed in
Review Questions 1.
2. 3. 4. 5
·
Write the instructions to move value 34H. t . Write the instructions to add the values 16~ o r~g~;r A and value 3FH into re ·st True ~r false. No value can be moved direct! an ~- Place the result in rel>'i R2er 8, then add them together. What IS the largest hex value that c b y mt~ registers RO - R7. o·S er . value? an e moved into an 8-b·t . Th . t regISter? What . e vast majority of registers in 8051 are · IS the decimal bits. eqw. valent of the h ex
r
SECTION 2.2: INTRODUCTION TO 8 . 051 ASSEM In this section we discuss Assembl BLY PROG Assembly language progr~=='y language format a d RAMMING Whit the - ·=u.ug. n defin e CPU can work only in binar . e some Wide( ous ~d slow to deal with Os and ls . Y, it can do so at Y USed ter · n111ch1ne ~anguage. In the early days of~horder to program thea very high speed F llUnology associated with computer. A . or hUJna.ns hexadeC1mal system was used as am e co.~puter, pro code was still cumbersome for ore efficient wa t &ranuners CO
: a~
ecru
· l such as BASIC Pascal, C, C++, Java, and numerous Today, one can use many different progranurung anguages, 'does not have to be concerned with others. These languages are called high-level languages because the rrogra~er bl language program into machine the internal details of the CPU. Whereas an assembler is use~ to trans at~ anl ss1e:n y s are translated into machine code (sometimes also called object code or opcode for operation code), ~gh- eve an~age C com iler to translate the code by a program called a con1piler. For instance, to write a program in C, one mus ;se a 805iassembler to create program into machine language. Now we look at 8051 Assembly language format an use an a ready-to-run program.
Structure of Assembly language An Assembly language program consists of, among other things, a series of lines of Assembly language instructions. An Assembly language instruction consists of a mnemonic, optionally followed by one or two ~per~nds. The operands are the data items being manipulated, and the mnemonics are the commands to the CPU, telling it what to
do with those items. A given Assembly language program (see Program 2-1) is a series of statements, or lines, which are either Assembly language instructions such as ADD and MOV, or statements called directives. While instructions tell the CPU what to do, directives (also called pseudo-instructions) give directions to the assembler. For example, in the above program while the MOY and ADD instructions are commands to the CPU, ORG and END are directives to the assembler. ORG tells the assembler to place the opcode at memory location O while END indicates to the assembler the end of the source code. In other words, one is for the start of the program and the other one for the end of the program.
_ ... ~ / ;u..., fi~ .
An Assembly language instruction consists of four fields:
09~~ e.
V
[label:) mnemonic [operands]
"'-
~"'--,~
[;comment)
~ ~
V\I\V\U. ~ ~ "''\
c..
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
d . nno excee a certain number t
of characters. Check your assembler for the rule. ~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 proas wn en. Assembly language statements such as ADD A B MOV A,#67 I
ORG OH
MOV RS,#2SH MOV R7,#34H MOV A,#0 ADD A,RS ADD A,R7
ADD A,#12H
HERE:SJMP HERE ENO
C
-+ ,.,
r
.
I
h(
M...,...;_,, (., v- d")' o,{ )
vO'>
;start (origin) at location 0 ;load 2SH into RS ;load 34H into R7 ;load O into A ;add contents of RS to A ;now A= A+ RS ;add contents of R? to A ;now A= A+ R7 ;add to A value 12 H ;now A= A+ 12H ;stay in this loop ;end of asm source file
Prog,am 2-1: Sample of an A111mbly Langu1g1 Program
8051 ASSEMBLY LANGUAGE PROGRAMMING
# ,, are the operands. Instead of a . and" A, B'' and .A, 67ctions or directives. Remember ,,
ch od ce opcodes, do-i.flStru , bl ADD ,nd MDV"' the mn,moni<', whi P' u t . as¢1'bl,t ps,u Onl bY th• ass,,rn er, as opposed lo
'f
mnemonieand ,n ope,and, these two field,; .,,uld ""de) .,,d are used Y fl, program Z-1 the commands that dire
3. Thee•'"'""'' field begins with a ,emicolon "''""'"'' ,nd"ato<
' :111d.
tine by themselves. The assembler ignores comments, but they ar~
nsable 1o programmers. Although
th!Spe ogracn
com-
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, . · 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 4
~ line and it should be del-1 from your program. In the next
'""'" has a monitor prog,am you do not need this
section \~e will see how to create a ready-to-run program.
Review Questions 1.
23.. 4.
s. 6. 7.
What is the purpose of pseudo-instructions? re translated by the .assembl . machine code, whereas . er into True or false.aAssembl are not. Which of the foll . y 1anguage is a high-level language. (a) ADD A R2 O\vmg produces opcode? p . ' (b) MOVA #12 ( ) ORG seudo-mstructions are also called c 2000H (d) SjMP HERE 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 EDITOR
. Now that the basic form given, the next questi . of an Assembly Ian a to run? The steps to How it is created, ass:b~:Jro~am has been are outlined as follows. e an executable Assembly nguage an made ready . program
~;e:;
1.
PROGRAM
l;
J ~ rrcf'J
Fust we use an editor to type· M
' any excellent editors m a program similar and/or e~~t~:~r;;essors are avail~~l:r~gram 2-1. all Microsoft prog_ram (or Notepad widely used ediatt be mdows) or IS th operating syst pro uce an ASCil fil ems. Notice th t ' which co e - dal -e. For · a the ed' 0 mes With :~'sr~e~:~::ons, ~~i:l~s, e ~a%'!t~able t~
~~cr;;ri'
:'w·~
b=
1
~
f ~!
~
;ou~,lli'
myfile.asm
r.-=1:___ASSEMBLER PROGRAM
m~~,,,:.='._J
•
~~ 1 / myfile.obj
r-:-::-1..l.- ~ other obj files
:,:,::,::, fo, the oon':en"::':."'~ble< e,ten,i.:. ~:" y an assembler in e asm" exte .e using. Ch asm 2. The "asm" the next step. ns1on for the eek your is fed t source file contain. source file . o an 8051 assembl mg the progr er. The assembler am I'intofiJmachine cod e. The asse c code created · ist e. The extens· f mbler will onverts th . in step 1 for the list file is ,,~;~• or the object fi le~r~~uce mstructio IS obj" an ob~ Ject fil ns
LlNl
rnyfiJe.abs
Assemblers require a thi While the ex~ and a one or more object fiJ rd step called link. ension extension "abs" Th' es and produces a r11g. The link monitor progra~ · is abs file is used Y absolute progra.rn 8051 tr ob· . Ject file . takes ainers th Wtth th 34 at h ave ae 3.
~
Esosl ~ Clt
rnyfile.he)(
OcoNl'Q.
2 "' -2. s~Ptto c
OttEa .\Nt)
~ate a ..____ • •ugl'UJI
~BEoonr.. twuSYSTEMS
\.
1
2 3 4
5
6 7 8 9
0000 0000 0002 0004 0006 0007 0008 OOOA
7025 7F34 7400 20 2F 2412 80FE HERE:
oooc
ORG MOV MOV MOV ADD ADD ADD
;start (origin} at 0 ·load 25H into RS ·load 34H into R7 '·load o into A RS to A ;now A= A+ ,·add contents of RS ·now A = A+ R7 to A I ;add contents of R7 12H ·add to A value 12H ·now A = A + ' ;stay in this loop ·end of asm source file
OH
RS,#25H R7,#34H A,#0 A,RS A,R7 A,#12H SJMP HERE END
I
I
I
I
Program 2-1: List File
4.
. ,, . h nverter) which creates a file with extension Next, the "abs" file is fed into a program called "OH (ob1ec! to exO~~ bl s Recent Windows-based assem"hex" that is ready to burn into ROM. This program comes with a 118 assem er · e,,v.,.(' ,. YJ ~ c v !' e ~ biers combine steps 2 through 4 into one step.
More about " asm" and " obj" files
~ """ .,,t ,.C, e.
t,vv;
5rc ~e
-
t
· th The "asm" file is also called the source file and for this reason some assemblers require . at thi. s fil . e.h ave the "src" . extension. Check your 8051 assembler to see which extension it requires. As mentioned earlier, this file LS created with an editor such as DOS EDIT or Windows Notepad. The 8051 assembler converts the_ a~m file'~ A~embly language instructions into machine langu_ag_e and provides the obj (object) file. In addition to creating the obJect file, the assembler also produces the 1st file (list file).
,._vr(e \ Ait.11,11?\
~ fl ,_
1st file
1
1>
\
fto1,!?l ob J.
J' • 'e .
L ' _:_2_!__J
The 1st (list) file, which is optional, is very useful to the programmer because it Jists all the opcodes and addresses as well as errors that the assembler detected. Many assemblers assume that the list file is not wanted unless you indicate 1nat you want to produce it. This file can be accessed by an editor such as DOS EDIT and displayed on the monitor or sent to the printer to produce a hard copy. The programmer uses the list file to find syntax errors. It is only after fixing all the errors indicated in the 1st file that the obj file is ready to be input to the linker program.
-
Review Questions
v
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 (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
C
b~•
f1f ,
A •
..,.J
SECTION 2.4: THE PROGRAM COUNTER AND ROM SPACE IN THE 8051 In this section we examine the role of the program counter (PC) re · t · discuss ROM memory space for various 8051 family members. gis er in executing an 8051 program. We also
Program counter In the 8051 An other important register in the 8051 is the PC (program count ) Th the next instruction to be executed. As the CPU fetches the opcod e program counter points to the address of lllcremented to point to the next instruction. ~pro_gram counter; thorn the _progr~m R_O M, the program counter is can access program addresses 0000 to FFFFH, a total of 64'R 6 fe S05l i ~ 16 bits wide. This means that the 8051 0 t~ entire 64K bytes of on-chip ROM installed, as we will see ~~ae. liowever, not al11nembers of the 8051 have We will d iscuss this important topic next. n. ere does the 8051 wake up when it is powered?
%·
::,S
-
8051 ASSEMBLY LANGUAGE PROGRAMMING
35
/
• .
ered up
. . t what address does the CPU Where the 8051 wakes up when it 15 pow ( rnicroprocessor) · 8A051 fa]llilY (that is, all members · ocontroller or e of the · · an. qu"tion ""t w, must ,sk ,bout any nucr . different. fp th"" ddte5S 0000 when ti ts powered up. w,ke up upon applying Po"" to ;t? Earh nu,rop"""'°;: wal
"'""I"'
15
~
° .
0 powered up, the pC (program counter) has the value of 00 Ul · de must be burne in h. b otROM ,ddre,s OOOOH. FOJ u,;, reason u, the S05lsystom, th• n~iopco h ;t is booted. We acttleve t JS Y the ORG
of progJam ROM'"'".,,;,;, whe" ;t looks fOJ th• fu>t """"'"'": ,:; -by-s"J' action of the program counter in statement in the source program as shown earlier. Next, we discuss th P fetching and executing a sample program.
Placing code in program ROM
To.get a betts'"" rountoJ in r,tdtlng and executing a program, we ex~min'
the action of the program counter as each instruction is fetched and executed. First, we exarrune once more the list file
;f "'' ""'pie prog,am and how tt,, rode a pl~OO rn the ROM of an SOS! ,hip. As we ran see, the oprode and ope,and
or each mstruction are listed on the left side of the list file (Program 2-1). and~;' ::,~;:"f"' • b=ed rnto ROM of an 8051 f~ily membeJ surh as 8751 o, AT8951 o, D55000, the opcode e P aced Ul ROM memory locations starting at 0000 as shown in the list below. ROM Address
Machine Language
Assembly Language
0000
7025
MOV RS, #2SH
0002
7F34
MOV R7, #34H
0004
7400
MOVA, #0
0006
20
ADD A, RS
0007
2F
ADD A, R7
0008
2412 80FE
ADD A, #12H
OOOA
0001The I.is! shows that address 0000 . HERE: SJMP HERE con tams the operand (in . contains 7D, which is th machine code of "7D25" h 1h15 case 25H) to be mo d e opcode for movin in 7D is th veis th to RS. Th erefore, theginstr a value. m . to register R5 and dd ln me th mory Iocations 0002' wandere0003 d e opcode and 25
e "me way ma hln
an "'"""" th
""""'' S;mit
urtion .. MOV
,
a
'"'
the operand for tile . c e ~ode "7400" is located . e opcode and the . arly, the mach.in RS, #2 SH" has a for the instruction ..::iction "Mov A, #o". Thtn memory locationsoOpOerand for the inst e. code "7F34" is located A R ,, · . A, Rs" and e memo l 04 and 000 ruction "MO ' 7 mstruetion. The opcode for the. location ;o;:tion 0006 has th 5 and represent thv R7, #34H". lllS etion "ADD A #1 s the content 2Fe opcode of 20 his e opcode and • 2H" ·IS located at ' w,uch L .• , W ch ·LS the opcode is the address 0008 an~pcode for the "ADD 1 0000 the operand 12H at ORG OH 2 0000 702S ;start at l MOV RS #2SH ; load ocat1·
~o~
3 0002 7p3 4 4 0004 7400 S 0006 20
6 0007 2F 7 0008 2412 8 OOOA 80FE HERE· 9 oooc .
MOV R7 ' #34H MOVA ' #o ' ADD A RS ' ADD A, R7 ADD A, #12H SJ'Mp HERE
0 n 25H • 34H :nto Rs o . into R7
;load ;load ;add into A Conte ;now A - nts of R ,-add - A+ Rs s to A ;now Acontent 8 " - A of R7 '. -add t~ A + R7 to A ,now A "va1 "' - A
END ;end
Program 2-1: List File
Ue
l
n this H of asrn loop
;;-~~~~~~~~~~~~~~~-:;:::~~=
36
o
.__ ce file sour
TfiE sos1 ~rcaoc -----oN"raott£a -'Nt>~ Et>t>Et> SYSTEMS
\
th address 0009. The memory !?cation OO?A has . e ·on and its target address 1s located 1n locabon 1 ddress is FE is explained in the next chapter.
!
ode for the SJMP instrucThe reason the target ·
o6o~B
Program 2-1: ROM Contents Address 0000
executing a program byte by byte
0001
. burned mto . th e ROM of an Assunung that the above program 1s . .8051 chip f the (or 8751, AT8951, or D55000), the following is a step-by-step descnption action of the 8051 upon applying power to it.
0002
°
1. When the 8051 is powered up, the PC (program counter) haRsOOMOOOinan!:::r:: to fetch the first opcode from location 0000 of the program · . of the above program the first opcode is 70, which is the code for movmg an operand to RS. Upon executing the opcode, the CPU fetches the value 25 and places it in RS. Now one instruction is finished. Then th: program counter is incremented to point to 0002 (PC = 0002), which contai.ns opcode 7F, the opcode for the instruction "MOV R7, .. ". 2.
Upon executing the opcode 7F, the value 34H is moved into R7. Then the program counter is incremented to 0004.
0003 0004
Cod e
70 25 7F
34 74
0006
00 20
0007
2F
0008
24
0009
12
OOOA OOOB
80
0005
FE
3. ROM location 0004 has the opcode for the instruction "MOV A, #0". This instruction is executed and now PC= 0006. Notice that all the above instructions are 2-byte instructions; that is, each one takes two memory locations. 4. Now PC= 0006 points to the next instruction, which is "ADD A, RS". This is a 1-byte instruction. After the execution of this instruction, PC = 0007. 5. The location 0007 has the opcode 2F, which belongs to the instruction "ADD A, R7". This also is a I-byte instruction. Upon execution of this instruction, PC is incremented to 0008. This process goes on until all the instructions ,1re fetched and executed. The fact that the program counter points at the next instruction to be executed explains \-vhy some microprocessors (notably the x86) call the program counter the instruction pointer.
/ ROM memory map in the 8051 family As we sa,v in the Last chapter, some family members have only 4K bytes of on-chip ROM (e.g., 8751, AT8951) and some, such as the AT89C52, have 8K bytes of ROM. Dallas Semiconductor's DSS000-32 has 32K bytes of on-chip ROM. Dallas Semiconductor also has an 8051 ,vith 64K bytes of on-chip ROM. The point to remember is that no member of the 8051 family can access more than 64K bytes of ~pcode ~ince the_ program counter in the 8051 is a 16-bit register (0000 to FFFF address ran~c). It must ~e noted that w~le the firs~ locahon of program ROM inside the 8051 has the add ress of 0000, the Last locahon can be different depend!ng on the s1~e of the ROM on the chip. A m ong the 8051 family members, the 8751 and AT8951 hav~ 4K byt~s of on-chi~ ROM. This 4K bytes of ROM memory has memory addresses of 0000 to OFFFH. Therefore, the firs t location of on-chip ROM of this 8051 has an address of 0000 and the last I ti h h address of OFFFH. Look at Example 2-1 to see how this is computed. oca o n as t e
Example 2·1 Find the ROM memory address of each of the following 8051 chips. (a) AT89C51 w ith 4KB (b) DS89C420 with 16KB (c) DSS000-32 with 32KB
Solution:
we have 4096 bytes ( 4 1024 ti x(b locations of 0000 to OFFPH. Notice that O is always the first . = 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 ~
(a) With 4K bytes of on-chip ROM memory space,
!IOS~l~A~S;S~EM;;B~l~Y~LA~N~ciu~A~G~E~PR~OG~RA~M;M~IN;G~------------------~~~~~~--------37
byte byte
,..
byte
..
oOOo
()(JOO
0000
OFFF 8051
3FFF
AT89C51
[)589C420/30
7FFF
DS5000-32 Figure 2-3. 8051 On-Chip ROM Address Range
Review Questions
.
:e
;: ~ru~eo~~~~!~~t;~:;~~::~r 3
·
. .
bits wide. OOOOH w h en 1t lS 8051 family, regardless of the maker, wakes up at memory
~~:~:;1R6M location do we store the first opcode of 3:" 8051 ~rogram?
4.· The .ins truc11,on "MOV A , # 44H" is a . ?-byte instruction. 5 _ What is the ROM address space for the 8052 chip.
,/
SECTION 2.5: 8051 DATA TYPES AND DIRECTIVES in this section we look at some \videly used data types and directives supported by the 8051 assembler.
8051 data type and directives
The 8051 rnicrocontroller has only one data type. It is 8 bits, and the size of each . . . . . . . register 1s also 8 bt ts . It 1s the JOb of the programmer to break down data larger than 8 bits (00 to FFH, or to 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 . ta5 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 ORG soott · cters; therefore, it should be DATAl: DB 28 . DEcr DATA2, DATA3:
38
os DB ORG
001101010 39H 510H
' MAL (1c ;BlNARy (35 ;HE}(
-~~'"o..~, . a:,!'
r~ ~"
DATA4: DATA6:
rfa
7
ORG DB
0
'-'a.
"2591" 518H . " "My name 1s Joe
;ASCII NUMBERS ·ASCII cHA.RACTERS 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..~) ~"v-e
Assembler directives
~ '• e c. ""'
The following are some more widely used directives of the 8051.
I'
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 _m u easter to read and mainm Assembly language programming consist of alphabetic letters in both u ercase 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.
fe
::;iue.
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
-
8051 ASSEMBLY LANGUAGE PROGllAMMING
a constant value?
. &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 ~.zostfforthefo ow · 5. State the contents of memory locations ZOO
8
ORG 200H
MYDATA:
DB •ABC123"
/secTION 2.6: 8051 FLAG BITS AND THE PSW REGISTER ..i..... ti·c conditions such as· theb1carry bit. · clicate anu.,,,e ·t f this Like any other microprocessor the 8051 has a flag register to Ul . In ti.;~ section we discuss various ' d (PSW) reer1c;ter. "'" The flag register in the 8051 is called the program status wcr oregister and provide some examples of how it is altered.
so
PSW (program status word) register
Jb~ogram status word (.PSW) register is an 8-bit register. It is also referred to .as the fiag regis.ter. Although the PSW register lsl! bits wide, only 6 bits of it are used by the 8051. The two unused bits are user-definab~e flags. Four of the flags are called conditional flags, meaning that they indicate some conditions that result after an mstruction is executed. These four are CY (carry), AC (auxiliary carry), P (parity), and OV (overflow). As seen from Figure 2-4, the bits PSW.3 and PSW.4 are designated as RSO and RSl, respectively, and are used to :an~i: r:f~ters. They are explained in the next section. The PSW.5 and PSW.l bits are general-purpose status forgthe bits of the PS~Jt!e programmer for any purpose. In other words, they are user definable. See Figure 2-4
tt;:~
following t.extdiscussed. is a brief explanation of £our of the fl ag bits . of the PSW register. The impact of instru ctions on theseThe registers is then
-
CY
•
FO
AC
m
~
3
I
C
..._~~~~;.~~: ~~ 9 ,i.:!"'-;~~~--;:---~~1-~~J__~RSO~~L_~o~v~~~=--~~~P V
CY
AC
~
c
Carry flag.
FO
PSW.6
RS1
l'SW.5
RSO OV
PSW.3 PSW.2
p
!'SW.I PSW.O
Auxiliary carry flag. Available to the user f Re . or general p ~ler Bank selector bit 1 U!pOSe. RegJSter Bank selector bit o· Overflow flag. · User..,,.efinable ..., bit.
L
't - IL (;l "" -
05~ <'.!.'-J
PSW.7
PSW.4
\
I
p .
flag. Set/cleared b o indicate an odd/ y h.udware each. even nu.inL11\Stuctj vu of 1 bits . on cycle
the ac Ctunu!ator
Addl'l!ss
~======f=====~==~I~===~
;_
2
3
Figure 2-4. Bits of the PSW Register
40
b I I
t ~ty
l~======~======~=R:e&:·sjte0tr~Banl(======
I
~
~ ~
-
-
A c..
\t)\\\o
_\ o I
In
I'
(I)'
·
t>
o \
/ . fl b't · 15 1 ' . fr the 07 bit. This ag This flag is set whenever there 1s a ~ out om be set to 1 or odirectly by ffected after an 8-bit addition or subtraction. It can also ,, t ds for "set bit
CY. the carry flag
Table 2-1: Instructions That Affect Flag Bits
AC ov ~-;-CY ---:;;--1.lin~s~tru ~ c~ti:,: ·o::":.--:~ X X X instruction such as "SETB c" and "CLR C" where "SETB c s ~t-addressable ~A~D~D~---~---:---~X X X carry" and "CLR C" for "clear carry". More about these and other b ~\...c,.fi~ ::;A~D~DC~--~--:----::;---~X instructions will be given in Chapter 8. .....i SUBB X X
:n
~~-.:.:__--::-MUL
AC, the auxiliary carry flag
0
X
0
X
. . ADD SUB operation this bitD 1.,'.:IV~-----=------lf there 1s a carry from D3 to D4 during an or ' BCD X _ _ _ _ __ is set; otherwise, it is cleared. This flag is used by instructi?ns that ~erform ::D'.:A:___ _ _......:...:__ (binary coded decimal) arithmetic. See Chapter 6 for more info~ation. " RRC X
v "l"'
P, the parity flag
~=-----=-------X
v'"
OT-' ~ p
~
~RL~C:___
'
The parity flag reflects the number of ls in the A (accumulator) regist~r only. lf the A register contains an odd number of ls, then P 1. Therefore, P - 0 if A has an even number of ls.
=
l
ov, the overflow flag
Ci (l
>
I 1 7)
l'J
r 0
/'). ~ ,"
//14.f 'J v-
This flag is set whenever tne result of a signed number operation is too larg~, causing the high-order bit to overflow into the sign bit. ln general, the carry. flag is 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 Chapter 6.
___:_.:.__--:---SETS C 1 :::C:. L.:.R:.C-=---- - - - - - - -
0
.::C:.P.=L:....:C:__ _ _X_ _ _ _ _ __ ANLC, bit
X
ANLC, /bit
X
ORLC, bit
X
ORLC, /bit
X
MOV C, bit
X
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 . 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.
a)
Solution:
OSOH DB OFCH, OSH, 76H, 28 DB "SAM" The program memory location will contain data as follows.
a)
ORG
Data PC
Addre11 0 050 0051 0052 0053
01 7fS
l:C •
-
••
;Hex equivalent of 28D
.
.
.
.
'
.
80s1 ASSEMBLY LANGUAGE PROGRAMMING
41
0054
oo5S
53
of S ivalent · ASCII equ nt of P. '. ASCI r equi vale f M
41 4D
;ASCII equivalent ~•en
"SAM" would have to be
here. In that case'
AS(il string as g1\
0056
Some assemblers do not allow the use of an written as 'S',' A','M'. b) MOV A,#56H ADD A, #95H 56H + 95H
01010110 10010101 11101011
EBH 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 +~ DA
10111111 00011011 11011010
c,,
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 . or it 1 - 0 . . : eg15ter bank selector bit RSO since by default PSW.2: OV =0 since there is - 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 ~\
Toe flag register in the 8051 is called _ _ __ ~: What is the size of the flag register in the 8051 ?bl , r.., v' Which bits o f the PSW register are user-defina e . r ' 3. d Find the CY and AC flag bits for the fo llowing co e. - - - - - - } , -1. • MOVA , #OFFH
I
(I c,1) I
r
s.
ADD A,
#01
Find the CY and AC flag bits for the following code. MOV A, #OC2H ADD A, #3DH
I I I
OO O
<.
'
, \ ,
1'\
(.
0
\
:::,
SECTION 2.7: 8051 REGISTER BANKS AND STACK The 8051 microcontroller has a total of 128 bytes of RAM. 1n this section we discuss the allocation of these
128
bytes
of RAM an d examine their usage as registers and stack.
RAM memory space allocation in the 8051 There are 128 bytes of RAM in the 8051 (some members, notably the 8052, have 256 bytes of RAM). The ~28 bytes of RAM inside the 8051 are assigned addresses 00 to 7FH. As we will see in Chapter 5, they can be accessed d1rectJy as memory locations. These 128 bytes are divided into three different groups as follows.
1. A total of 32 bytes from locations 00 to lF hex are set aside for regis ter banks and the stack. 2. A total of 16 bytes from locations 20H to 2FH are set aside for bit-addressable read/write memory. A detailed discussion of bit-addressable memory and instructions is given in Chapter 8.
3. A total of 80 bytes from locations 30H to 7FH are used for read and write storage, or what is normally called a scratch pad. These 80 locations of RAM are widely used for the purpose of storing data and parameters by 8051 programmers. We will use them in future chapters to store data brought into the CPU via [/0 ports.
Register banks in the 8051 As mentioned earlier, a total of 32 bytes of RAM are set aside for the register banks and stack. These 32 bytes are divided into 4 banks of registers in which each bank has 8 registers, RO - R7. RAM locations from O to 7 are set aside for bank O of RO - R7 where RO is RAM location 0, Rl is RAM location 1, R2 is location 2, and so on, until memory location 7, which belongs to R7 of bank 0. The second ~ank of registers RO - R7 s tarts at RAM location 08 and goes to location OFH. The third bank of RO - R7 starts at memory location lOH and goes to location 17H. Finally, RAM locations 18H to lFH are set aside for the fourth bank of RO - R7. Figure 2-6 shows how the 32 bytes are allocated into 4 banks. As we can see from Figure 2-5, bank 1 uses the same RAM space as the stack. This is a major problem in program.ming the 8051. We must either not use register bank 1, or allocate another area of RAM for the stack. This will be discussed in Example 2-5.
Default register bank . URAM locations 00 - l F are set aside for the four register banks Which register bank of RO- R7 do we have access to when the 8051 ·' powered up? The answer is register bank 0; that is, RAM locations; l, 2, 3, 4, 5, 6, and 7 are accessed with the names RO, Rl, R2, R3, R4 '.
-
7F
Scratch Pad RAM 30 2F
Bit-Addressable RAM
20
IF Register Bank 3 18 17 Register Bank 2
10
OF 08
Register Bank 1 (Stack)
07 00
Register Bank O
Figure 2-5. RAM Allocation in the 8051
8051 ASSEMBLY LANGUAGE PROGRAMMING 43
Bark I
1 1 J
F[
R7 ]
E[
Rn
]
R4
]
o[ C[
0
RlJ
J£ [
R6
R5
I~ [
R5 ]
14 [
R-1 ]
tB [
R3
]
lA [
R3 R2
]
19 [
Rl
18 [
RO
}:, -
'° J
R7
ID [ tC [
RJ
J
13 [
] ]
12 [
'J [
R2 RI
8[
RO
]
8[ A[
Rb
6
lf [
J
~
n [ RO ] IO L[_;.:.._.--
R4
figure 2-6. 805 I R~giJler Banka and th et·r RAM AddresK5
J J J J J J J
1 -
Exi mpl~ 2-5
am·
folloY. ing ~tJtc thl' conrenl!> of RAM loca tion, aftt·rt ,thl'value 99Hpn-.gr H ·load RO Wl 1 MOV R0,#99 '.load Rl with value 85H MOV Rl,#BSH , ith value JFlf H · load R2 w MOV R2.#3F . 1 d R7 with value 63H MOV ;; load MOV R7,N63H RS,#12H oa RS with valu~ 12H
.
Solution; A ftxr the l"(l'Cuhon of the ,1bu, c pro~r,1m Wl' h.i,~he f~llo;1~g: RAl\1 locahon Ohi!~ value 9911 RAI\I k1cat1,•n l ~ \a ue
~1 location 2 hJ~ , ,1luc 3f'I I RAM lol'illil•n 7 ha~ \'alue 6311 RAlvl loc.itton 5 hi!,\ ,llUl' 12H
Rcpt>at Ex.imple 2-5 using RAM addresses tlll>tead of register names. Solution:
1, fo,,
Thl, called dtrl'Ct addressing mode and uses the RAM address locatton f 5 more detailed discus,,.,., of add"""'S modo, 1".0V 00, #99H ;load RO with value 99H MOV 01 ,IIBSH ;load Rl With Value BSH MOV 02, #3FH ;load R2 with value 3F'ii MOV 07,1163H ;load R7 With value 6JH MOV 05, 1112H ;load RS with value llH
h
.
.
°' 1 • de,tinahon •d
RS, R6, .inu R7 "'hrn progran1m1ng the 8051, It i~ much e . b h . , to these RAl• RI, and l>
2
How to switch register banks
~ stilted ,1bo, t.', reg1Ster bank O1s the default When o( the PS\.V (progr.im st.itus ,,·ord) rt.>gi~ter. B1ts D4 and
'"""'" m r ,bte 2-2 44
1 c anfies this co ncept.
,vi
l0cations With . nam es such as RO,
~ 8051 is Powered of the Ps\y , ,. •p. Iv,
'"'tct,
U5e(f to &elect the
t? other banks by use des,red register bank as
Tabl e 2-2: PSW Bits Bank Selection
The D3 and D-l bits of register PSW are often referred .to rsW.4 and PSW.3 since they can be accessed by the bit:~dressable instructions SETB and CLR. For example, "SETB pSW, 3" will make PSW.3 = 1 and select bank register 1. See Example 2-7. i;1L-D
~~r~e:..
RS1 (PSW.4)
Bank O O 0 ~~~--~-------:;-1- - - -
~~ ~ -\-,~e.
~Bank~~l~--O~------;:O;----Bank 2 1
u
v stack in the 8051
I"
RSO (PSW .3)
)... 1-o
~~--..:.----------
il This information could be data or The stack is a section of RAM used by the CPU to store information temporar Y· . 15 an address. The CPU needs this storage area since there are only a limited number of reg ters. ~"".\-~~ ?.
.
.
How stacks are accessed in the 8051 · CPU · t to 1·t The register used to access the • lf the stack is a section of RAM there must be registers inside the to porn tha t 1·t can ' . . · l 8 b't ide which means stack is called the SP (stack pointer) register. The stack pomter m the 8051 is on Y I s w ' th RAM 1 ti 0 take values of 00 to FFH. When the 8051 is powered up, the SP register contains value 07. This me~ns at oca ~ 08 is the first location used for the stack by the 8051. The storing of a CPU register in the stac~ is c~lled a PUSH, a n pulling the contents off the s tack back into a CPU register is called a POP. 1n other words, a register 1s pushed ? nto the stack to save it and popped off the stack to retrieve it. The job of the SP is very critical when push and pop actions are performed. To see how the stack works, let's look at the PUSH and POP instructions.
Pushing onto the stack In the 8051 the stack pointer (SP) points to the last used location of the stack. As we push d ata onto the stack, the stack pointer (SP) is incremented by one. Notice that this is different from many microprocessors, notably x86 processors in \Vhich the SP is decremented when data is pushed onto the stack. Examining Example 2-8, we see that as each PUSH is executed, the contents of the register are saved on the stack and SP is incremented by 1. N o tice that for every byte of data saved on the stack, SP is incremented only once. Notice also that to push the registers onto the stack we must use their RAM addresses. For example, the instruction "PUSH 1" pushes register Rl onto the s tack. .
Example 2-7 Write instructions to use the registers of bank 3, and load the same vaJue 05H in the registers RO to R3. Solution:
PSW.4 SETB PSW.3 MOV RO,#OSH MOV Rl,#OSH MOV R2,#0SH MOV R3,#0SH
;make ;make ;load ;load ;load ;load
SETB
RS1=1 for selecting bank 3 RS0=1 for selecting bank 3 RO with value OSH Rl with value OSH R2 with value OSH R3 with va lue OSH
After execution, the four registers ROto R4 of bank 3 (RAM locations 18H to 1BH) will . program can be rewri tten as contam the value OSH . The
SETB PSW.4 SETB PSW.3 MOV A,#OSH MOV RO,A MOV Rl,A MOV R2,A MOV R3,A
;make ;make ;load ;move ;move ;move ;move
RS1=1 for selecting bank 3 RSO=l for selecting bank 3 A with OSH the contents of A to RO the contents of A to Rl the contents o f A to R2 t he contents of A to R3 We_will see later that it will be more economical to use the above set 0 f . . fer IS a shorter instruction and thus saves program memory space. instructions, as a register to register trans-
-
Bost ASSEMBLY LANGUAGE PROGRAMMING
45 '
. . or.,.
....,
.. ~
. :a\"' '-,
.. ..".: ,, -~,, < '
•·.' ~ ..
..
•
. ter Ois selected.
a and regJS
Example 2-8
. t
Show the stack and stack porn er R6, 1i25H MOV Rl, lil2H MOV R4, ltOF3H MOV
. for the fotlowing.
-
p,.; \.. "~
I
\ ~p
default h Assume t e
stack are
•
j
6
PUSH PUSH PUSH
l
tJ1
4
After pUSH4
~
Solution:
After PUSH 1
After PUSH 6 OB
OB
OA
OA
09 08
09
09
12
08
08
25
25
F3
09
12
08
25
SP =OA ;
-
SP : 09
-
-
OA
OA
SP =08
Start SP =07
OB
OB
1"
~opejng from the stack Popping the contents of the stack back into a given register is the opposite process of pushing. With every pop, the top byte of the stack is copied to the register specified by the instruction and the stack pointer is decremented once. Example 2-9 demonstrates the POP instruction. The upper limit of the stack As mentioned earlier, locations 08 to lF in the 8051 RAM can be used for the sta k Th'1 . . of RAM are reserved for bit-addressable memory and must not be used b the c · s_1s bec.ause locations 20 - 2FH Y stack. If m a gtven program we need Example 2-9
(
I i__ f)
Examining the stack, show the contents of the registers and SP values are in hex. after execution of the foll . . ,... , t_ 1 owing II\Structions. All ~P 3 ; POP stack into R3 POP 5 \ ;POP stack into RS , POP 2 ;POP stack into R2
.
'
Solution: \...._
({5
/
~
---,:. R.
l.
AfterPOP3
OB
54
OB
OA
F9
OA
F9
09
76
09
08
76
6C
StartSP zOB
08
6C
SP •OA
After PQp 5
-
OA
-09
08
76 -
AfterPQp2 08
-
0A
-
I
-
6C-
t · t t RAM locations 30 - 7FH. This is done Sp th ,ore than 24 bytes (08 to 1FH = 24 bytes) of stack, we can change e o pom o n . a·. on "MOV SP, #xx'' . with the 1nstruc
CALL instruction and the stack
·· · th k tO the address of the instruction just In add1t:1on to· usmg the · stack to save recnc:.ters o' the CPU also uses e stac h save ·t tur s from the ca11e d sub rou tin'e. belo\V the CALL mstru chon. This is how the CPU knows where to resume w en t re n More information on this will be given in Chapter 3 when we discuss the CALL instruction.
Stack and bank 1 conflict Recall from our earlier discussion that the stack pointer register points to the current RAM location_ available for the stack. As data is push ed onto the stack, SP is incremented. Conversely, it is decremented as data 1s p opp e d off the stack into the registers . The reason that the SP is incremented after the push is to make sure that the stack is growing toward RAM location 7FH, from lower addresses to upper addresses. If the stack pointer were decremented after push instru ctions, we would be using RAM locations 7, 6, 5, etc., which belong to R7 to RO of b ank 0, the default register bank. This incrementing of the stack pointer for push instructions also en s u res that the sta ck \\lill not reac~ location Oat the bottom of RAM, and consequently run out of space for the stack . However, there is a problem with the default setting of the stack. Since SP= 07 when the 8051 is powered up, the first location of the stack is RAM lo~ation 08, which also belongs to register RO of register bank 1. In other words, register bank 1 and the stack are using the same memory s pace. If in a given program we need to use register banks 1 an d 2, we can reallocate another section of RAM to the stack. For example, we can allocate RAM locations 60H and higher to the stack as shown in Example 2-10.
Example 2-10
~rite P~SH instructions to push the contents of the registers on stack afte r the execution of the following set of instructions.
MOV SP ,#4FH SETB PSW.3 MOV R0 ,#25H MOV Rl ,#OCH MOV R2,#0SH MOV A, #OCEH Solution : The first instruction defines the stack to be from 50H onwards Th d · bank 1. Since the register bank 1 has been selected, the address~s ofe se~otn : address of the A register is OEOH. Hence the PUSH instructions areregts ers
PUSH PUSH PUSH PUSH
truction defines the use of register ' Rl, and R2 are 8, 9, and OAH . The
8 9 OAH OEOH
After the four PUSH instructions, the conten t of the RAM select d e as the stack locations will be
-
Address
Data
50 51
25H OCH
52 53
05H CEH .
(
80S1 ASSEMBLY LANGUAGE P R O G R A M M I N G G : ~ - - - - - - - - - - - - - - - - - - - -
47
. I
1ator
·ew the contents of registers
. uiators aUoW us to vdi that you use a simulator to . ·mulator. 5itJ1 I eeoJll.Tllen ·th · I t · Many assemblers and C comp_ilers co~e w~th a 51 in ). We strong Y r . a rograrn w1 . a sin:iu a or gtv~s and memory after executing each instruction (smgle-5teppchg pters. Sirlgle-stepplJ\t we can use 1t to fmd errors m single-step some of the programs in this chapter an~ future : addition to the fact t a ovieW 32 and Keil. See www. us a deeper understanding of microcontroller architecture, f 8051 simulators from Pr our programs. Figures 2-7 through 2-10 shov, screen-shots or MicroDigitalEd.com for tutorials on how to use the sunulators. Viewing registers and memory with a s,mu
r
~p;
,• ' .
I
Data
8""~
CP
.
. :IIPit. f _,~ IJfJ
Cl Ha1dware
-
@RO 00 PC J0003 RB 00 ACC Joo RO 00 @R1 00
PO
FF
P1 P2
00
SP ~ IR2 00 ~@RO FF DPT 0000 R3 00 X@Al FF
P3 TCON 00 THU 0000 THLl 0000 THI r... .\A PCON 00
PS\11
(oolA1 00
@DPTR FF
B C
loo
SP>< >¢< XAAEA >¢<
10
ro
EA
A• 00
R5 00 R6 00
fro R7
IE ~-
00
Taik >¢< Ta\kP >¢<
FF FF
I,_
~
'====~~~~~-----~ I
Figure 2-7. Register's Screen from Pr0 v·,ew . 32 Simulator .
00: 08: 1O: 18: 20: 28: 30: 38: 40: 48: 50: 58: 60: 68: 70: 78:
I I
00 00 DO DO DO OD OD OD DO DO OD 00 DO DO 00
00 00 00 OD 00 00 DO DO 00 00 00 OD 00 00 00 DO
00 00 00 DO 00 00 00 00 00 OD 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 00 00 00 OD 00 00 00 00 00 00 00
00 00 00 00 00 00 DO 00 00 00 00 00 DO 00
00 00 00 00 00 00 DO DO 00 00
oo
00 00
oo oo oo 00 oo
Figure 2-8. 128-Byte Memory S PilCe from Prov· •ew 32 s· 48 nnutiltor
00 00 00 00 00 00 00
oo 00 oo oo oo 00 oo oo oo
2SJ • • • •
• • •
. .. •
•
• • • • • • • • • • • • • • • • • • • • • • • • • • • • • •
• • •
. . . •• ••
• • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • •
..
- • r
Pro1ect Work~pc1ce
Regs
0><00 O,d)() OxOO OlCOO OxOO OxOO OxOO OxOO
rO rl r2 r3 -- ,4
~p;
~~ I'-~
pc>'"'~ t
r5 • 16 ·- 17 ' El - Sys • a~
r
"l'! •• ·· -
VM
Reos•
e
•
OxOO OxOO Ox07 Ox07 OxOOOO C:OxOOOO 0
b ...
• . $p
',..
sp_max dpt1
- PC$
$tates
' 1±1
O00000000 OxOO
sec
psw
Figure 2·9. Register's Screen from Keil Simulator
,w - - -
C:OxOOOO C:OxODlO C:OxOD2D C:OxOD3D C:Ox0040 C:OxOOSO C:Ox0060 C:Ox0070
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 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 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 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 00 00 00
00 00 00 00 00 00 00 00
.
.
..
~
·-,,
. . .. ... . . . .. .... . .
00 . . . . . . . . . . . . . . 00 . . . . . . . . . . . . . 00 . . . .. . .. ... 00 . . . . . . . . . . . . . . 00 . . . . . . . . . . . . . . 00 . . .. . ... .. . . 00 . - . . . . . . . . . . . . . 00 . - . . . . . . . . . . . . .
.
.
..........- - . . ~ ~ ~............~~~~~- ~ • J$ iJ L_"'.J:Cc
Figure 2-10. US-Byte Memory Space from Keil Simulator
Review Questions 1. What is the size of the SP register?
2. 3. 4. 5.
With each PUSH instruction, the s~ck pointer regi~ter, SP, is (incremented, decremented) by 1. With each POP instruction, the SP is (mcremented, decremented) by 1. On power-up, the 8051 uses RAM location as the first location of the stack. 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
..1:"g A
B RO Rl, R2, R3, R4, RS, R6
. th 8051 inc uuu • I I I 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 pseudoAn 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 b1 .st w1 'de 4 N b. . 1 s w1 e. . ame a 16- 1t register in the 8051. p p'fl 5. It is necessary to add 45H to SSH. Are . .
e
r
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? o' o MOV R2, #13H pi 1 "' ,ti ~ ~ ~ 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 ,(g) MOV R9) #SOH ' #~OH Xf) MOV A, /tFSH h ~ 8. l~oofthefollowingis(are)illegal? ~or[f/ .1cJ_/'{~r-1 •i.t~-f 1 R3, #SOH (b)ADD W ct r...J}.. (\) C'.J.' ~(d) ADD A, #255H te) ADD~ ii.sSOH (CJ ADD R7 • R4 ~ (,~ ~ ( ,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 A instructions? e content of the de tin . . ADD .., A, ~o (' -,B ~ ) : /. s ation reg15ter after MOV
')
tl'b
ADD
~
R0,#07
r· '° s P. ~ fl
!I
sP ;;.,--
{;) \
,b
; ,o
0- I.J
lo
,.. ' -
~
•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 · '
·r
. . ' ' '
uses)? I f ~ r rr q 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? 19. Why are the ORG and END directives also called pseudocode? 20. True or false. The ORG and END directives appear in the" .1st" file.
wr~c
SECTION 2.4: THE PROGRAM COUNTER AND ROM SPACE IN THE 8051
e.Y C.. t:>
I ('(' C
,t- .at_ 11
\• ,1,r<>- t
'\ \e..)(
.,
1"
21. Why do we always write programs starting with ORG 0000? 'io f ,:~ ,..,.- & m 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. OOOOH RO, #26H Rl, #36H A, #0 A, RO R2, A
ORG MOV MOV MOV
ADD MOV
_
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 26. 89C51ED-2 has a program memory space of 64K What are its first and l t d 27. A given 8051 has 7FFFH as the address of its las/location of on-chip ~m?rytha ~resses? 8051? · at 15 e size of on-chip ROM for this
RO:;
28. How many bytes space does the instruction MOV A, #4 o occupy?
SECTION 2.5: 8051 DATA TYPES AND DIRECTIVES 29. Compile and state the contents of each ROM location for the fOll . ORG 200H owing data. MYDAT_l: DB "Earth" MYDAT_2: DB "987-65" MYDAT 3 : DB "GABEH 98" 30. List thicontents of the locations that change with these ct· . ORG OSOOH 1rectives. DB "MANGO"
SEcnoN 2.6: 8051 FLAG BITS AND TI-IE PSW REGISTER
!~·. Wh~t Which
is ~e function of the bits PSW. 3 and PSW.4? / ,,-
_
bits of PSW are used for the CY and AC fla b. ' g its, respectively?
8ost ASSEMBLY LANGUAGE PROGRAMMING 51
b1ts respecti \:el}'? 31 Which bit,, of PSW are u:,ed for the OV a.nd P flag . ' ( the Ul5t:r\Jct1ons 3,i. find the value or the rsw regt:,te"r after the executton O A, 1195
HOV ADD
A, 1il20
35 In thr ADD tmtr\lctlon, when IS AC raised? , 36 Whal 1> the value of the CY flag after the following code· CLR C CPL C
;CY
=0
;complement carry 37. find the CY flag value after each of the following codes. 2 50 (a) MOV A, #54H (b) MOV A, #00 (c) MOV A, # ADD A, #OC4H
ADD A, #OFFH
ADD A, #OS
38. Add 25H and 70H and find the contents of the AC, CY, and P flags. SECTION 2.7: 8051 REClSTER BANKS AND STACK 39. Which bit~ of the PSW are responsible for selection of the register banks? 40. On power·up, what is the location of the first stack? . d Wh ? 41 If bank 1 regi~ters are being used, the default value of the stack pomter cannot be use · Y· 42. In the 8051, what is the size of the stack pointer (SP) register? 43. On power-up. which of the register banks is used? 44. Does the stack of 8051 grow upwards or downwards? 45. Assuming the use of bank 0, find at what RAM location each of the following tines stored the data. (a) MOV R4,#32H
(b) MOV R0,#12H
(c) MOV R7,#3FH
(d) MOV RS,#SSH
46. Repeat Problem 45 for bank 2. 47. After p~wer-up, show how to select bank 2 with a single instruction. 48. What 1v11J be performed by the (ollowing set of in.'ilructions? MOV MOV MOV
ADD PUSH PUSH SET POP POP ')
.•,
SP, #52H A, #04 RO, #OSH A, RO OEOH O PSW. 4 lOH OBOH
I
•41
49. In Problem 48, does the sequence of POP . . show the correct sequence of instructions instructions restore the original values of r . SO. Show the stack and stack pointer for each· r . eg1sters RO, R3, and R7? lf not, ORG o me of the followmg program. MOV MOV MOV MOV POSH PUSH PUSH CLR MOV MOV POP POP POP
SP, #70H RS, #66H R2, #7FH R7, #SDH 5 2 7 A R2,A R7 ,A 7 2
~-\. ~ltt
-\''1 \-
5
:~~~ \'
52
THE 80s1 MICROC ON'fROttER AN D EMBEDDED SYSTEMS
ANSWERS TO REVIEW QUESTIONS SECTION 2.1: lNSIDE THE 8051 ].
2.
3. 4. 5.
MOV A,#34H MOV B,#3FH ADDA,B MOY A,#16H ADDA,#OCDH MOV R2,A False FF hex and 255 in decimal 8
SECTION 2.2: INTRODUCTION TO 8051 ASSEMBLY PROGRAMMING d . tr ctions also called assembler . ch MOV and ADD. Pseu o-ms u , The real work is performed by instru~noi:is ~u as 1. directives, instruct the assembler in doing it~ Job. 2. The instruction mnemonics, pseudo-instructions 3. False 4. All except (c) 5. Assembler directive 6. True 7. (c) SECTION 2.3: ASSEMBLING AND RUNNING AN 8051 PROGRAM 1. True 2. True 3. (a) 4. (b) and (d)
5. (d)
SECTION 2.4: THE PROGRAM COUNTER AND ROM SP ACE IN THE 8051 1. 16 2. True
3. OOOOH 4. 2
5. With 8K bytes, we have 8192 (8 x 1024 = 8192) bytes, and the ROM space is 0000 to lFFFH. SECTION 2.5: 8051 DATA TYPES AND DIRECTIVES 1. DB 2. 7
3. Uthe value is to be changed later, it can be done once in one place instead of at every occurrence. 4. (a) 4 bytes (b) 7 bytes
5. This places the ASCII values for each character in memory locations starting at 200H. Notice that all values are in hex. 200 = (41) 201 = (42)
202 = (43) 203 = (31) 204 = (32) 205 = (33)
-
80s1 ASSEMBLY LANGUAGE PROGRAMMING
• 1¥
SECTION 2.6: 8051 FLAG BITS AND THE PSW REGISTER 1. PSW (program status register) 2. 8 bits ectively. 3. Dl and OS, which are referred to as PSW.1 and PSW.5, resp
4. Hex FF +
-1001
binary 1111 1 + 10000 0000 1111
This leads to CY =1 and AC =1. 5. Hex C2
+
30
FF
binary 1100 0010 + 0011 1101 1111 1111
SECTION 2.7: 8051 REGISTER BANKS AND STACK 8-bit 2. Incremented 3. Decremented 1.
4. 5. 6. 7. 8.
I
08 0 0•7 Register bank 3 RAM locations 18H to 1FH
/
JUMP, LOOP, AND CALL INSTRUCTIONS
OBJECTIVES Upon completion of this chapter, you will be able to:
> > > >
> > > > > >
Code 8051 Assembly language instructions using loops Code 8051 Assembly language conditional jump instructions Explain conditions that determine each conditional jump instruction Code long jump instructions for unconditional jumps Code short jump instructions for unconditional short jumps Calculate target addresses for jump instructions Code 8051 subroutines Describe precautions in using the stack in subroutines Discuss crystal frequency versus machine cycle Code 8051 programs to generate a time delay
55
. m control to a different IOcation fer progra . . . sary to trans trol transfer mstructions available . d ·t 1·s often neCes rs the con U · . . This chapter cove ln the sequence of instruchons to be execute , .• oping, as we as instructions for 1O 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 8051 and its newer g 1 section, time delay subroutines are described for both the tra
SECTION 3.1: LOOP AND JUMP INSTRUCTIONS •
•
ln this section we first discuss how to perform a looping acho both conditional and unconditional.
in the 8051 an 11
d th n talk about jwnp instructions e ,
Looping in the 8051 . · all d loop The loop is one of most widely 15 Repeating a sequence of instructions a certain number of tunes •c _e a · ed b the instruction "DJNZ r used actions that any microprocessor performs. In the 8051, the loop a~ti~n ts perform Y eg, label"· In this instruction, the register is decremented; if it is not zero, 1t Jumps to the target addr~~ referre~ to by t~e label. Prior to the start of the loop the register is loaded with the counter for the n~ber ~f rep:tttions .. Notice that 1n this instruction both the register decrement and the decision to jump are combined mto a single instruction. . In ~e program in Example 3-1, the R2 register is used as a counter. The counter is first set to 10. ln eac~ iteration the instruction DJNZ decrements R2 and checks its value. If R2 is not zero, it jumps to the target address assoetated with the label "AGAIN". This loopin~ action continues until R2 becomes zero. After R2 becomes zero, it falls through the loop and execut~s the 111struction immediately below it, in this case the "MOV RS, A" instruction. ~otice ~ the DJNZ instruction that the registers can be any of RO - R7. The counter can also be a RAM location as we \Vlll see 111 Chapter 5. Loop inside a loop As shown in Exan1ple 3-2, the maximum count is 256. What ha if · 256? To do that, we use a loop inside a loop which is II d ~~ens we want to repeat an acbon more times than
the count. See Example 3-3
.
So Iution: ')
rl .,
Example 3-1 .p y
()
' D
ca e _ a ne_;te oop. In a nested loop, we use two registers to hold
~<·"'-~
-"1~
t/J
r , , .
! co
y 10 using the technique of repeated addition.
J
Multiplication can be achieved b add in t . . e.g., 25 x 10 = 250 (FAH) y g he multiplicand repeatedly as . ' many times as th . . 25 + 25 + e multiphe r . 25 + 25 + 22+25:1?+25+25+25:a250 /J 4---F- :Z... JA,#0 R2,#1.Q ADD A #25 6JNZ-~2,AGAIN MOV RS A MOV MOV
AGAIN:
• 1~-1~ 0
i.
1
,
,!Jd°'
;A:O,clear ACC ;the multiplier . ;add the multipl7s placed in R2 ;repeat until R2~cand to the Ace ;save A in Rs . -0 (10 times)
C)
2 ,~
,RS:FAH
Example 3-2 Write a program to add the first t en natural numbe ,
56
THE sos1 Mrcao CONTR.OLLER.
AND E1>.• •YIBEDDED SYSTEMS
;A=O,clear ACC . MOV A,#0 ·load counter value in R2 MOV R2,#10 ' o • ;n; tialize RO to zer 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) DJNZ R2,AGAIN ;repeat unt.1 = ) · RAM location 46H ·save the result (37H .in MOV 4 6H, A ' d . nl 256 since the count . . I 3-1 and 3-2 can be repeate LS o y The maximunt number of times that a loop Ln Examp es 255 register R2 t!> an 8-bit register and can hold only numbers from O to ·
:~17........
Example 3-3
0
Ht:. SJ «'__.j ~p
d (b) omplement the ACC 700 times. \Vrite a program to (a) load the accumulator with the value 5SH, an c
Solution: Since 700 is larger than 255 (the maximum capacity of any register), we use two registers to hold the count. The following code shows how to use R2 and R3 for the count.
NEXT: AGAIN~
MOV A,#SSH MOV R3, #102 ,.,,.x { MOV R2,#7qJ CPL A DJNZ R2,AGAIN
-
..
~·
_.'.l
Jo<"
;A=SSH ; R3=10, the outer loop count ;R2=70, the inner loop count ; complement A register ;repeat it 70 times (inner loop)
(
6
10
I\.J -c_
/
.
(21 )
_ 6 J (( -
J' « l I<, _ 7 °.., l >.:::;
J
IJ.,,
- - ) 1> _ -
A
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
Table 3-1: 8051 Conditional Jump Instructions
Conditional jumps for the 8051 are summarized in Table 3-1. More details of each instruction are provided in Appendix A. In Table 3-1, ~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 some conditional jump instructions with examples.
JZ (jump if A
= 0)
c. ln:-s_tru_c_ti_o_n_ _ _A_c_ti__ · o:...n.:__ _ _ __
v"}z
JumpifA=O
t,/JNZ
JumpifA.tO
. . h f . A· h ./ OJNZ . 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 ' · CJNE A, data MOV A,RO ;A=RO CJNE reg, #d ata ;jump if A = 0 JZ OVER MOV A,Rl ;A=Rl JC P5w ·1 • JZ OVER ; Jump if A = 0 }NC
OVER:
JB
!" this program, if either RO or Rl is zero, it jumps to the lab
JNB ~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 N
-
) " '.. '1"
v
Decrement and jum p if register O v
*
Jun1p if A* data Jump if byte if. #data
Jump if CY= 1 Jump if CY= 0 Jump if bit = 1
I OVE
app1y to any
/
lot
V-''l
Jump if bit = 0 Jump if bit = 1 a nd clear b it
JUMP, LOOP, ANO C ALL INSTRUCl10NS
57
)
Example 3-4 . FFH If 50, move FFJ-f to RS. . Write a program to determme iJ the content of RO is Solution: MOV INC JNZ MOV
d
A,RO A NEXT RS,#OFFH
the number
·nto the ACC
l
;loa A.CC . earlier A=FFH ;increment.thewill cause A=0,1f ;incrementing FFH into RS. ;if A=O now, move
NEXT:
. such as decrement to use the JNZ ·trunetic instruction other register. More importantly, you don't have to perform an an instruction. See Example 3-4. JNC (jump if no carry, Jumps if CY= 0)
. . whether toJ·ump. In executing . .15 sed to make the eos1on In th.is instruction, the carry flag bit in the flag (PS~ r_egist~ u CY= l). If it is not, the CPU starts to fetch and execute "JNC label", the processor looks at the carry flag to~ ~ it 15 r:used but will execute the next instruction below JNC. instructions from the address of the label. If CY= l, it wiU not.Jump . iJ CY_ it jumps to the target address. We will - 1ch Note that there is also a "JC label" instruction. In the JC instruction, · · th econ t~x t O f applications in future• apters. • • • • give more examples of these ·mstruchons 1n Th e discussed in Chapters 4 There are also JB fjump if bit is high) and JNB fjump 1f bit 1s low) instructions. ese ar and 8 when bit manipulation instructions are discussed. d
All conditional jumps are short jumps It must be noted that all conditional jumps are short jumps, mearting that the address of the target must be within -128 to +127 bytes of the contents of the program counter (PC). This very important concept is discussed at the end of th.is section.
/
Unconditional jump instructions The unconditiona_l jump _is a jump in which ~ontrol is transferred unconditionally to the target location. In the 8051 there are two unconditional Jumps: LJMP (long Jump) and S]MP (short jump). Each is discussed below. Example 3-5 In Example 3-1, it was assumed that the result of multiplication will fit· . . ing two 1-byte numbers, the product can have a maximum length f m~o an 8-b1t register. But when multiply· · 0 hvo 8-bit_registers must be allocated to the product. two ytes. To accommodate this possibility, • f Multiply the numbers OECH by 25H using the techni que o repeated addition. Solution:
AGAIN:
HERE:
MOV MOV MOV ADD JNC INC DJNZ MOV
Rl,#0 A,#0 R0,#25H A,#OECH HERE Rl RO ,AGA!N RO ,A
;Rl~O,thia ie the . ;clear Ace register to store the MSB ;the multiplier ie ;add the multip1· Placed in Ro ;if no carry thicand to the Ace . , en repeat ;increment Rl f the additi . or each c on ,repeat until RO:o arry generated ;the LSB of th ·the MSB e Product is • of the moved t R d Product is in Rl o O ;now Rl:22H an Ro .. lC!i
58
•
I
'
•
:
. :,
.•
.
z 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 ati, 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 ~ction. This can save some bytes of 3 1 ·ump) instruction, which is a 2-byte instruction as opposed to the - yte . mdi~ d next · · h t pply SJMP JS scusse . ) · memory in many applications where memory space 1s rn s or su
r:;.
Vs.IMP (short j ump)
~~~~g;t
ln this 2-byte instruction, the first byte is the opcode and the second byte is the _relati~e add_ress : 1c;; tion. The relative address range of 00 - FFH is divided into forward and backward Jumps, that is, wi ~d bytes of memory relative to the address of the current PC (program counter). lf the jump is forward, the target a ress can be within a space of 127 bytes from the current PC. If the target address is backward, the target address can be within - US bytes from the current PC. This is explained in detail next.
Calculating the short jump address In addjtion to the SJMP instruction, all conditional jumps such as JNC, JZ, and DJNZ are also short jumps due to the fact that they are all two-byte instructions. In these instructions the first byte is the opcode and the second byte is the relative address. The target address is relative to the value of the p rogram counter. To calculate the target address, the second byte is added to the PC of the instruction immediately below the jump. To understand this, look at Example 3-6.
Jump backward target address calculation While in the case of a forward jump, the displacen1ent value is a positive number between Oto 127 (00 to 7F in hex), for the backward jump the displacement is a negative value of Oto -128 as explained in Example 3-7.
Example 3·6
Using the following list file, verify the jump forward address calculation. Line 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15
16 17
18
-
PC
0000 0000 0002 0004 0006 0007 0008 0009 0008 OOOD OOOE OOOF 0010 0011 0012 0013 0015 0017
Op code 7800 7455 6003 08 04 04 2477 5005 E4 F8 F9 FA
Mnemonic Operand ORG MOV MOV
JZ INC INC INC ADD JNC CLR MOV MOV MOV MOV
AGAIN: NEXT :
FB 28 50F2 80FE
0000 R0,#0 A,#SSH NEXT RO A A A,#77h OVER A RO,A Rl, A R2, A
OVBR:
ADD
R3 ,A A, R3
HBRB:
JNC SJMp
AGAIN HERS
0000
\4
0 \.\
~~ ~ ~
64"- ~1e.
.r"'\&_j " ......J>
-
I ).
~'-,.....
~,/_A
i
0
, ... =t
END . -
flJMp, LOOP, AND CALL INSTRUCTIONS 59
. Solution:
for a fon.vard jump is calcud 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 has opcode of 60 and_ opera:ion INC RO, which is 0006. By the relative address. In line 4 the instruction J~ 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 OS iv ,, ivin JZH, the address of label OVER. Therefore, 05 is added to 0000, the address of instruction CLR A 'g g
i.ns~~ct:J:;,,
5? ~?
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
~~ ~1:;:~::;~~er bedm~re ~h~ -12~ to +127 bytes from the addres~ ass~ciated :ith th~ insfruc~
:~~::~o~ : : is out of range.
.
is ma e o v10 ate th.is rule, the assembler will genera te an error stating the jump
Review Questions I.
2. 3. 4
·
5.
The mnemonic DJNZ stands for True or false,; "DJNZ RS, BACK"--b.--· ,, . com mes a decrement and a · . . . ~1;:~~~,,•s ah. . -byte instruction. Jump in a smgle mstruction. LJMP . , iv 1ch register's content is checked to see if ·t . i.s a -byte instruction. i is zero?
SECTION 3.2: CALL INSTRUCTIONS
/
Another control transfer instruction is the . CALL mstruction, which is often used to perform tasks that need t b to s~v~g memory space. ln the 8051 th:reeJ:~:med fre~uently. This mak~:e: to call a subroutine. Subroutines are Deeding which one to use depends on the target a~tructions for call: LCALL (rrogram more structured in addition ess. Each instr . ong call) and ACAL uction is explain d L (absolute call). LCALL (long call) e next. In this 3-byte instruction, the first b t . target subroutine. Therefore LCA y e IS the opcode and the ·~ f th , an be used t U --.ond and thir space o e 8051. To make sure that aft o ca subroutines d bytes are the processor automatically saves on theer txecution o thecaUed sub loca_ted anywhere w·~s~d for the address of the subroutine is called, control is transferred st a: the address of the ins:ou~me the 8051 kn t hm the 64K-byte add~ stack and begins to fetch instructions from~ at subroutine, and the Uchon immediate! ows where to come bade to, RET (return) transfers control back to the c Ile new location. After f1' . phinr?Cessor saves th YPCbelow the LC ALL. When a a er. Every b n1s g e (p su routine n d execution of th rogram counter) on the ee s RET e subr tin 60 as the last i . ou e, the instruction nstruction See E THE sosi · xample 3-8.
MICRoc oN TROLLER AND
EMBEDDED SYSTEMS
mtirlll
-~10 . ur!EAY la!-.
.....
Eiample 3-8
SSH
d AAH continuously. Put a time . 1b ding to it the values an th 8051 . the next \\I rite a program to toggle all the bits of port y~ am will be used to test the ports of e m delay in ben-veen each issuing of data to port 1. This progr chapter. Solution:
BACK:
ORG MOV MOV LCALL MOV MOV -LCALL
0
A,#SSH Pl,A DELAY A,#OAAH Pl,A DELAY
·load A with SSH
' ;send SSH to port l
;time delay ;load A with AA (in hex) ;send AAH to port 1
;keep doing this indefinitely . this is the delay subroutine ·--- ORG ;put time delay at address 300H 300H ;RS= 2SS(FF in hex) ,the counter RS,#OFFH DELAY: MOV ;stay here until RS becomes 0 RS,AGAIN AGAIN: DJNZ ;return to caller (when RS - 0) RET ;end of asm file END
/
SJMP
BACK
The following points should be noted for the program in Example 3-8. 1.
Notice the DELAY subroutine. Upon executing the first "LCALL DELAY", the address of the instruction right below it, "MOV A,#OAAH", is pushed onto the stack, and the 8051 starts to execute instructions at address 300H.
2.
In the DELAY subroutine, first the counter RS is set to 255 (RS = FFH); therefore, the loop is repeated 256 times. When RS becomes 0, control falls to the RET instruction, which pops the address from the stack into the program counter and resumes executing the instructions after the CALL.
The amount of time delay in Example 3-8 depends on the frequency of the 8051. How to calculate the exact time will be explained in detail in Chapter 4. However you can increase the time delay by using a nested loop as shown below. DELAY:
NEXT: AGAIN:
MOV R4,#2SS MOV RS,#2SS DJNZ RS,AGAIN DJNZR4,NEXT RET
;nested loop delay ;R4 = 2SS(FF in hex) ;RS= 2SS(FF in hex) ;stay here until RS becomes o ;decrement R4 ;keep loading RS until R4 = 0 ;return (when R4 = 0)
CALL instruction and the role of the stack The stack and stack pointer were covered in the last chapter To unde t d th . e unp~rt~nce of the stack in m.icrocon troUers, we now exanune the contents of the stack and stack pointer fo ;s an r xamp1e 3 -8. This lS shown in Example 3-9.
Use of PUSH and POP instructions In subroutines U?on calling a subroutine, the stack keeps track of where th CPU h this reason, we must be very careful in any manipulation of s~ k s ould return after completing the subro utine ~p instructions must always match in any called subroutine c ~on tents. The rule is that the n umber of PUSH 1 Example 3-10. · n er w ords, for every PUSH there must be a POP.
:or
-
°
and
J\Jtvtp, LOOP, ANO CALL INSTRUCTIONS
61
Example 3-9
· Analyze the stack contents after the execution o
L . the following. f the first LCA L m
Solution: 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016
0000 0000 0002 0004 0007 0009 OOOB OOOE 0010 0010 0300 0300 0300 0302 0304 0305
ORG MOV MOV LCALL MOV MOV LCALL SJMP
BACK:
7455 F590 120300 74AA F590 120300 80FO
- - - -this
0
A,#SSH
Pl,A DELAY A,#OAAH
Pl,A DELAY BACK
7DFF AGAIN:
22
A with SSH to delay A with AAH to
SSH port 1 AAH port 1
;keep doing this
is the delay subroutine ORG 300H
DELAY:
DDFE
-load ;send ;time -load ;send
MOV DJNZ
RS,#OFFH RS,AGAIN
RET
END
;R5=255
;stay here ;return to caller ;end of asm file
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 the PC and resume executing at address. The diagram shows the stack frame after the first LCALL.
---:: ~
~ I
OA 09 00 08 07
SP
= 09
blii~
(tit.., &
Example 3-10
Analyze the stack for the first LCALL instruction in the following program. 01 0000 02 0000 7455 03 0002 F590 04 0004 7C99 05 0006 7D67 06 0008 120300 07 OOOB 74M 08 OOOD F590 09 OOOF 120300 10 0012 80EC 11 0014 12 0300 13 0300 C004 14 0302 coos 15 0304 7CFF 16 0306 7DFF 17 0308 DDFE 18 030A DCFA 19 030C DOOS 20 030E 0004 21 0310 22 22 0311
62
BACK:
.
ORG MOV MOV MOV MOV LCALL MOV MOV LCALL SJMp
0 A,#SSH Pl,A R4,#99H RS,#67H DELAY A, #OAAH Pl, A DELAY BACK
this is the delay
'
ORG
DELAY:
NEXT: AGAIN:
PUSH PUSH MOV MOV DJNz DJNz POP POP
RET END
300H 4
;load A with SSH ;send SSH to port 1 ;time delay ;load A with AA ;send AAH to port 1
b ; keep doing this su routine
s R4,#0FFH RS,#OFFH RS,AGA!N R4,NEXT
;PUSH R4 ;PUSH R.5 ; R.4=FFH ; R5=25S
•
s
4
•
;Pop into R ;PQp into
R!
:return t ;ena of o caller &11111
-
file
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
OA
I
OA
08
67
RS
OA
99
R4
PCH
09
00
PCH
PCL
08
OB
PCL
OB
OB
09
OB
00
09
PCH
OB
08
PCL
99
00
OB
R4
Calling subroutines In Assembly language p rogramming it is common to have one main program and many subroutines that are called from the main program. This allows you to make each subroutine into a separate module. Each module can be tested separately and then brought together with the main program. More importantly, in a large program the mod ules can be assigned to different programmers in order to shorten development time. It needs to be emphasized that in using LCALL, the target ad dress of the subroutine can be anywhere within the 64K-byte memory space of the 8051. This is not the case for the other call instruction, ACALL, which is explained next.
; MAI N program calling subrout i n e s ORG 0
MAIN:
LCALL SUBR 1 SUBR 2 LCALL LCALL SUBR 3 HERE: SJMP HERE ; -- - -,end of MAIN
-
.
' SUBR l: .. ..
....
RET , - - - ~ n d of subroutine 1 '
SUBR 2 : .. ..
;
RET end of subr outine 2
SUBR 3:
....
RET
: - - -- nd of s ubroutine 3 END ;end of the asm file Figure 3-1. 8051 Assembly Ma.in Program That Calls Subroutines
-
JlJMI,, LOOP, AND CALL INSTRUCTIONS 63
C.
~I.MC. -\1Jv,
r"-"'J
i;:.J).o -
/ ACALL (absolute call)
• ,,v;v-
. 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. 0 target address of the subroutine must be within 21< bytes because . 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 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·
M '~
~
;it
. 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 ORG Oo ll
\
DELAY: AGAIN:
')
.
;move t he value of Oto port Pl ;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 ;RO value is c hange d to ve now ;call the delay r o ut ' get _a longer delay 1ne again
.
"-._. ORG 3 OOH NOP DJNZ
,-.,
RO, AGAIN
~RET END
\
MHz
0 c,;_;J,f;
MOV A, #0 o MOV Pl, A/' • / MOV R0,#30H ACALL DELAY' CPL A MOV Pl,A ,f MOV RO, #OFFH ACALL DELAY SJ MP START 1
START:
= 22
_.
.
;do nothing ;decrement RO unt·1 l 1t . 1s . ze . ,return to caller ( h ro . d wen RO=O) , en of asm file
In this program if LED
::f
co;~e
in practice the ~mo s are connected to port l, the ON . . LEDS. ACALL d~Jay_possible with an 8-bit ~f the LEDs will be lar er two bytes of program m uction is used here instead of LCA[ ~gtste.r will be too small t~an the OFF time. But. ernory space (one byte each f ch , so in this progra th n_o ce the blinking of the or ea call). m ere IS an e ffective saving of
n,;
fo
;------------1A~,,.,;,-:;t_~&~
...:., ~ (' t' -r
l~Exa=m~p~l~e3~-~ 1
2
Rewri te Example 3-8 as effic1ent . Iy as you ca
n.
Solution:
BACK:
ORG 0 MOV A, #SSH MOV Pl ,A ACALL DELAY
CPL SJMP
A
BACK
;~oad A wi th SSH ;issue val t. ue i n reg ; ime delay A to l>Or t l ;complement r eg A ; keep doi ng thi s indefin · .1.t e1y THEsos1 Ml
CRoco
NTROLLER AND
EMBEDDED SYSTEMS
.. ....
-~~~-this is the delay subroutine , , hex), the counter DELAY: 2 RS,#OFFH ;RS= SS(FF in becomes 0 MOV ;stay here until RS DJNZ R5,AGAIN . return to caller AGAIN: 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.
2. 3. 4. 5.
What do the mnemonics "LCALL" and "ACALLf" standd for?h e within the 64K bytes of code space if using the True or false. In the 8051, control can be trans erre anyw er LCALL instruction. . . 1 ( c_...\. v,...'f..,.. How does the CPU know where to return to after executing the RET mstruchon . LL.A~ b bv,.j Describe briefly the function of the REI instru~tion. . A CALL ~1.. l.dro ~..,._,._~ • 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.
\t\& Machine cycle for the 8051
•
-
I
\\C..'"' lJ•""
's
\'\,
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 oscillator 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 8051based 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\S"1 -#..S (),1 \ W\."--C.~ ~c::( ~(" "' ~
t
\
p
. /--
Example 3-13
~·
The f~llowing shows crystal frequency for three differ!nt 8051-based systems. Find the e riod f th h" O cvcle 1n each case. ~ P e mac me . (a) 11.0592 MHz (b) 16 MHz (c) 20 ~ " .. I\.~~ ,(I'-...<. llC. ._,,. Solution:
~
~
v""'
(a) 11.0592 MHz/ 12 = 921 .6 kHz; machine cycle is 1/921.6 kHz= I 085
( . microsecond)
.J5µs
(b) 16 MHz/ 12 = 1.333 MHz; machine cycle (MC)= 1/ 1.333 MHz ~ 0. (c) 20 MHz/12 = 1.66 MHz; MC a 1/ 1.66 MHz "' 0.60 µs
--
-
J\JM_p, LOOP, AND CALL INSTRUCTIONS
65
Example 3-14
.
For an 8051 system of 11.0592 MHz '
.
find how long it takes
to execute each of
the following i.n5tructions.
DJNZ R2,target (al MOV R3,#SS (bl DEC R3 (cl (dl LJMP (el SJMP (fl NOP (no operation) (g)
..
MUL AB
· 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 . Machine cycles 1.085 µs lnstructio11 1x1.oss µs"' 1 (al MOV R3,#55 lxl.085 µs = 1.085 µs Sol uti on..
(b) DEC R3
(c) DJNZ R2,target
(d) LJMP (el SJMP (f) NOP (g)
1 2 2 2 1
2xl.085 µs - 2 .17 µs 2xl.OB5 µs - 2.17 µs 2x1.oas µs _ 2.17 µs lxl.085 µs "'1.085 µs 4Xl.085 µs = 4.34 µs
4
MUL AB
Delay calculation for 8051 As seen in the last section, a delay subroutine consists of two parts: (1) setting a counter, and (2) a loop. Most of the time delay is performed by the body of the loop, as sho~vn in Example 3-15. Very often we calculate the time delay based on the instructions inside the loop and ignore the clock cycles associated with the instructions outside the loop.
I
Example 3-15 Find the size of the delay in the following program, if the crystal frequency is 11.0592 MHz. AGAIN:
1
;·--·Time DELAY: HERE:
MOV A,#SSH MOV Pl,A ACALL DELAY CPL A SJMP AGAIN delay MOV R3,#200 DJNZR3,HERE RET
;load A with SSH ;issue value in reg A to port 1 ;time delay
;complement reg A. ;keep doing this indefinitely ;load R3 with 200
;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 lfacb1ne Cycle DELAY: MOVJR3,#200
HERE:
l
DJNz R3,HBRE
RET
Therefore, we have a time delay of ((200 ic 2) + + x 1 2
] l.085 JJS =: A">c 25 -.JO. 5 µs.
66
THI! 8051 MICRoco NTROLLER AND EMBEDDED SYSTEMS
·
e the delay is to use NOP
. 255· therefore one way to mcreas I Example 3-15, the largest value the R3 register can tak~ is " .' ply was;es time. This is shown in Example 3-16.
.
n u·ons in the loop. NOP which stands for "no operation, s tm
tM~~
I
•
Loop inside loop delay
.
.
ll d a nested loop. See Example 3-17.
. ·d loop1 which 1s a 1so ca e Another way to get a large delay is to use a loop ms1 ea
/ V
Example 3-16
For an 8051 system of 11.0592 MHz, find the time delay for the following subroutine: e;,rr.."o ~ "'.{ ~ :r.Q N""" r
Ma c h i n e cycle
DELAY: HERE:
MOV
1
\
NOP NOP
1 1
\-\C..Jt.
NOP NOP
1 1•
OJNZ
R3, #250
J
.~3,HERE "
2, 2
RET
C
~~
\,\
I
•
,I/
\=M~C~
}
t(:)\\\)
f
Solution: ,"'\ The time delay inside the HERE loop is [250(1 + 1 + 1 + 1 + 2)) x 1.085 µs =1500 x 1.085 µs n.vo instructions outside the loop we have 1627.5 µs + 3 x 1.085 µs = 1630.755 µs.
= 1627.5 µs. Ad ding the
If machine cycle timing is critical to your system design, make sure that you check the manufacture's da ta sheets for the device specification. For example, the DS89C420 has 3 machine cycles instead of 2 machine cycles for the RET instruction.
Example 3-17 For an 89C51 with a crystal frequency of 22 MHz, generate a delay of 5 ms.
Solution:
~ ~\..°'it "o
;Tested for an
AT89C51 with XTAL~22 MHz.
DELAY: HERE: AGAIN:
Machine Cycle MOV MOV DJNZ OJNZ RET
R2,#19 R3, #255 R3,AGAIN R2,HERE
1 1
Q. )... J
N'\ (:, "
;:; \
°'
t-\t. , e : 'fY'\OV
(Z.l7~'l,_r
2 2 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 for Various Clocks per _
Delay calculation for other versions of 8051 In creating a time delay using Assembly language
instructions, one must be mindful of ti.vo factors that can affect the accuracy of the delay. 1.
2.
Machine Cycle
chip/Maker
12
-
AT89C51 Atmel
6 The crystal frequency: The frequency of the crystal oscil-p P!Bg~C::S4~X2~P~h~jJ~ip~s~--------~~ - lator connected to the Xl - X2 input pins is one factor : 4 1 in the time delay calculation. 1l1e duration of the clock D55000 Dallas Semi . period for the machine cycle is a function of this crystal OS89C420/30/40/50 Dallas SeIJU
frequency. The 8051 Design: Smee the original 8051 was designed . h t d m 1980, both the field of IC technology and the architectural design of nucro~rocessors a~e seen grea ~ vancements. 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 1cl?'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 periods 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 Table 3-3: Comparison of 8051 and DS89C4x0 either 6 or 12 docks per machine cycle. 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
In the case of the DS89C4x0, since the
docks per ma ch'me eye1e was reduced number fr om 12 to 1, the number of machine cycles used to execute an instruction had to be chang d to reflect e chin th.IS rearity. Table 3-3 compares the ma . e cycles for the DS89C4x0 and 8051 f some instructions. or
DECRx
1
l
DJNZ
2
4
LJMP
2
3
SJMP
2
3
1 4
1
NOP
MULAB
9
Example 3-18 : rom Table 3-2, find the period of the . rmpact on performance. (a) AT89CS} machine cycle (MC) in each . (b) P89CS4X2 (c) DSS case if XTAL - 11 Solution: OOO (d) DS89C4x0 - .OS92 MHz, and disctm the (a) 11.0592 MHz/ 12 = 921.6 kHz· M . (b) 11.0592 MHz/ 6 = 1.8432 C ~ 1/ 921.6 kHz = 1 085 (c) 11.0592 MHz/ 4 = 2 7648 I MC IS 1/ 1.8432 MHz . µs (rnicrosecon (d) 11.0592 MHz/ I = i1.a592 is. t/2.7648 MHz : µ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 - 90 ns y ~ u u , u ~ boost for the nccn,. 4xO to a ..,~~4x0 chip crystal of the over the A Ton,, &aJne ' - - - -
Mlh· ~~c
g.5425
~
;;68~----------~~~;;::::·
8-20.
0~~s1. 5ee ~ w e p t 4ffilo,d,,
THE 80St 1l.n "'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. (a) MOV R3, #55 (d) LJMP (g) MUL AB
(c) DJNZ R2, target (f) NOP (no operation)
(b) DEC R3 (e) SJMP
Solution: The machine cycle time for the AT8951 and DS89C420/30 was shown in Example 3-18. Table 3-3 shows machine cycles for each of the above instructions. Therefore, we have:
Instn,ction (a) MOV R3,#55 (bl DEC R3 (cl DJNZ R2, .. (d) LJMP (e ) SJMP ( f ) NOP (g) MUL
AB
AT8051 lxl085 • lxl085 2xl085 2xl085 2xl085 lxl085 4xl085
ns ns ns ns ns ns ns
- 1085 = 1085 - 2170 = 2170 - 2170 = 1085 - 4340
DS89C420/30l40/50 2x90 ns - 180 ns lx90 ns = 90 ns 4x90 ns - 360 ns 3x90 ns - 270 ns 3x90 ns - 270 ns lx90 ns = 90 ns 9x90 ns = 810 ns
ns ns ns ns ns ns ns
Example 3-20
Find the time delay for the loop section of the following subrouti 1'f ·t · 1 15 a crystal frequency of 11.0592 MHz. ne run on a DS89C420/30 chip , assuming DS89C420/30 Hachine Cycle
DELAY: HERE:
MOV
R3,#250
NOP NOP NOP NOP DJNZ
R3,HERE
1 l 1 1 4
RET Solution:
The time delay inside the HERE loop is (250(1 + 1 + 1 + 1 + 4 Example 3-16, we see DS89C4x0 le about 9 timet faster' (l )] >cJII90/ na • ,.._ 2000,, x 90 na • 180 180
627
-JlJMp,
.
.
µa.~. --· ..... - - -
..,
ttlis-..u.1.. IUl ff
..
•
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: . 8-bit . th XTAL = 2 2 MHz . h blinking o f the LEDs. Two th. 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
51
registers with a maximum count of 255 ea register needs to be employed.
n
w
#OFFH Pl,A ACALL DELAY CPL A SJMP AGAIN MOV MOV
AGAIN:
A,
•·-----------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
atil
Example 3-22
')
:~·~
•it,
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
Solution:
:~
l)uy,
;Tested for DS89C420 of 11.0592 MHz. MOV A,#55H AGAIN: MOV Pl,A 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
1CAi
Illa:
-
RET
Delay 9 x 242 x 255 x 4 MC x 90 ns =199,940 µs Use an oscilloscope to measure the system square wa . ve period to Verify deJ4y.
70 THE 8051 MlCRocoN
TROLLER AN D EMBEDDED SYSTEMS
. . atin time delay is not the most reliable d th t use of the instruction m gener g hil t t an accurate time from the above discussion we con clu e a . s as described in Chapter 9. Meanw e, ~ ge 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
:~ay
See the following Web sites for 8051 produc~s and their features from various companies. www.8052.com www.MicroOigitalEd.com
SJMP to itself using $ sign
· t ·t lf in order to keep the microcontroller ln cases where there is no monitor p rogram, we need to s h ort JUJnP o 1 s~ busy. A simple way of doing that is to use the$ sign. That means in place of this HERE:
SJMP HERE
we can use the following: SJMP $
Review Questions 1. 2. 3. 4. 5.
True or false. In the 8051, the machine cycle lasts 12 clock cycles of the crys tal frequency. The minimum number of machine cycles need ed to execute an 8051 ins truction is - - - - - · For Question 2, what is the maximum number of cycles needed, and for which instructions? Find the machine cycle for a crystal frequency of 12 MHz. Assuming a crystal frequency of 12 MHz, find the time delay associated with the loop section o f the following DELAY subroutine. DELAY :
MOV
HERE :
NOP NOP NOP DJNZ RET
R3 , #1 0 0
R3 , HERE
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 uncondiThe 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 counvalue 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,
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 True or false. All 8051 j~ps ar~ sh~rt(Jur;)p~~t a short jump? 9 Which of the following mstructtons is ar
s:
10: (a) JZ (b? JNC _(c) LJMP (d) A short Jump 1s a
11
D]NtYte instruction.. Why?
· · al Jumps · are short Jumps. 12· True or false. All condition 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 · Joop 15perorm 15.· Find the number of times the fo llowmg . · MOV R6,#200 BACK: MOV RS,#100 HERE: DJNZ RS HERE I
bytes from the current PC. 15. The target address of a jump backwar? m~XImwn -----bytes from the current PC. 16. The target address of a jump forward 1s a maxunum of _ _ _ __ DJNZ R6, BACK
.
15 a
.
f
°
-
SECTION 3.2: CALL INSTRUCTIONS 17. Why do we need subroutines? .. . . , 18. Ln \Vhat way is the LCALL instruction different from an ACALL instruction. 19. The ACALL target address is limited to bytes from the present PC.
,
20. 21. 22. 23. 24. 25.
The LCALL target address is limited to bytes from the present PC. When LCALL is executed, how many bytes of the stack are used? On returning from a subroutine, where will the next instruction be taken from? Why do the PUSH and POP instructions in a subroutine need to be equal in number? How is the stack used in the case of a CALL( ACALL or LCALL) instruction? Show the stack for the following code: OOOB 120300 LCALL DELAY OOOE 80FO SJMP BACK 0010 OOlO; _ _ _ this is the delay subroutine 0300 ORG 300H 0300 DELAY: 0300 7DFF MOV RS,#OFFH 0302 DDFE AGAIN: DJNZ RS,AGAIN 0304 22 RET
.• •:w I
;keep doing this
;Rs~2ss
;stay h
ere ;return 26. Reassemble Example 3-10 at ORG 200 (instead of ORC O) and show th
SECTION 3.3: TIME DELAY FOR VARlOUS 8051 CHIPs 27. 28. 29. 30. 31.
e stack frame for the first LCALL instruction.
Find the system frequency of an 89CS1 if the machine cl . . Find the machine cycle if the crystal frequency is ~ e peno
even though one is a 3-byte
72 THE 8051 M}t"n ~ocoNTROLLE
R ANO EMBEDDED SYSTEMS
l •
th t pecified in Problem 27. . Find the delay with the following program for e sys em s 32 DELAY: MOV R2,#100 HERE: MOV R3,#255 AGAIN:
DJNZ R3,AGAIN DJNZ R2,HERE RET h 8051 with frequency of 11.0592 MHz. 33. Find the time delay for the following delay subroutine, if the system as an DELAY: MOV R3,#200 HERE: NOP NOP NOP DJNZ R3,HERE RET 34. Find the time delay generated by the following routine if the XTAL =22 MHz. HERE: MOV R0,#200 AGAIN: DJNZ RO AGAIN RET 35. Write a program to toggle all pins of Port 2 continuously with a delay of 1 second between the toggling XTAL I
=
22MHz. 36. 37. 38. 39. 40.
Repeat problem 32 for DS89C420/30. Repeat problem 33 for DS89C420/30. Repeat problem 34 for DS89C420/30. Repeat problem 35 for DS89C420/30. In an AT89C51-based system, explain performance improvement if we replace the AT89C51 chip with a DS89C420/30. Is it 12 times faster?
ANSWERS TO REVIEW QUESTIONS SECTION 3.1: LOOP AND JUMP INSTRUCTIONS 1. Decrement and jump if not zero
2. True 3. 2 4. A
5. 3 SECTION 3.2: CALL INSTRUCTIONS 1. Long CALL and Absolute CALL 2. True 3. The address of where to return is in the stack.
4. Upon executing the RET instruction, the CPU pops off the to tw O b register and starts to execute from this new location. p ytes of the stack into the program counter (PC) 5. 3 SECTION 3.3: TIME DELAY FOR VARIOUS 8051 CHIPS 1. True
2. 1 3. MUL and DIV each take 4 machine cycles. 4. 12 MHz I 12 = 1 MHz, and MC= 1/1 MHz= 1 µs 5. [100(1 + 1 + 1 + 2)1 x 1 µs = 500 µs = 0.5 milliseconds 6. False. It takes l clock. · 7. 11.0592 MHz/1 = 11.0592 MHz; machine cycle is l/l l.05 MHz_ 92 - 0.0904 µs
-TUMP,
LOOP, AND CALL INSTRUCTIONS
=90.4 ns
CHAPTER4
1/0 PORT PROGRAMMING
OBJECTIVES Upon completion of this chapter, you will be able to: ,,. )> )> )> )> )>
List the 4 ports of the 8051 Describe the d ual role of port O in providing both data and addresses Code Assembly language to use the ports for input or output Explain the dual role of port Oand port 2 Code 8051 instructions for 1/0 handling Code I/0 bit-manipulation programs for the 8051
.. '
- •
.... 'I!
-
.
l
75
In Section 4.1, we describe 1/0 examp Ies. d ·1 Y . f the 8051 with ma11 . 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 desigI/0 ln the 8051 there are a total of four ports for 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. nated as VCC' GND, XTALl, XTAL2, RST, EA, ALE/PROG an
'I.
~ . }
VO port pins and their functions
. . -bit orts. All the ports upon RESET are co nfigured P The four ports PO, Pl, P2, and P3 each use 8 pins, makin? the~ 8 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 way that open collector is used for lTL chips. fu any system using the 8051/52 chip, we normally connect PO to pull-up
~
'
,_••
,;,
-~It
iiJOl'
.
PDlP/Cerdip
Pl.0
1
40
Pl.I
39
PO.O(ADO)
38
P0.1 (ADI}
Pl.3
2 3 4
37
P0.2 (AD2)
Pl.4
5
36
Pl.5
6
P0.3 (AD3)
35
P0.4 (A04)
34
P0.5 (ADS)
33
P0.6 (AD6)
32
P0.7 (AD7)
31
EA/vPP
1,
30
ALE/PROG
,J...t/rcA'f
29
PSEN
28
P2.7 (AlS}
Pl.2
Pl.6
7
Pl.7
8
RST
9
(RXD) P3.0
10
(TXD} PJ.1
11
(INTO} P3.2 (INTI) P3.3 1 (TO) P3.4
12
(Tl) P3.5
IS
~)P3.6 [ (RD) P3.7
16
L
L
13 14
17 18
XTALl
GND
8051 (8031) (89420)
27 26
25 24
19
23
20
22
21
cc 'P "')..}
"f
~
\ ".: \ ,(>( 1
r..!ftlle
""' ~
b• 4-
' ~:!>~
1,_,
-~-
ltiaPort1 1
'' '
P2.6 (A14) P2.S (Al3) P2.4 (A 12) P2,3 (A 11) P2.2 (AlO) P2.1 (A9) 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 resistors. Seei'.guret ou tput. For example, the followort Ofor bot mpu t O the altematp . ode will continuously send out to por mg c AH , ing values of SSH and A · O'o'',
Vee
and
;Toggle all bits of PO /".!'---.. BACK: [ MOV A, I/SSH ' MOV PO,A ACALL DELAY MOV A,IIOAAH MOV PO , A . l .r " ;i ACALL DELAY ~~9 P.- SJMP BACK 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.
~ --.--.-.-,-i-1 1~1~0 K
Ll-+--+-++-t-t-C PO.OC.J-4-4-t-t-it
PO.l C~-L-+-+-t-11- ~...
8051
L---l-+-t--t--i--::::
P0.2 P0.3c=---~f--r-~ P0.4L - -_ -_....i ,-t P0.5c:__ _ _ -_ __..
P0.6L-P0.7
-
0
1
- - - - - -+--
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'"" [
BACK:
MOV MOV
A, #O FFH
; A = FF he x /..
PO , A
;make PO an input port• ;by writing all ls to it;get data f rom PO· ;send it to port 1, ;keep d o ing i t .
A,PO Pl , A SJMP BACK
MOV MOV
Dual role of port 0 As sho\vn in Figure 4-1, por_t Ojs also.designated a~ ADO - AD7, allowing it to be used for both address and d a ta. When connecting an 8051 / 31 to an external memory, port O provides both address and data . The 8051 multiplexes a ddress and d ata through port Oto save pins. We discuss that in Chapter 14.
../ Port 1 Port 1 occupies a total of~ pins (~ins ~ through 8). I!_can be used as input o r ou tput. In contrast to port o, this port does not need an y pull-uf resistors ~tnce it.alread y has pull-up resistors internally. Upon reset, port 1 is configured as an input port. The following code will con tinuously send out to port 1 the al ternating values SSH and AAH .
BACK:
l
MOV MOV
A,#SSH
Pl,A ACALL DELAY CPL A SJMP BACK
; complement(Invert) reg. A
Port 1 as input If port 1 has been configured as an output port, to make it an inpu t ort . . 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 writan 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 an saved m R7, R6, and RS.
.
it
-
110 PORT PROGRAMMING
'1'1
,
~
I MOV MOV MOV MOV
A,#OFFH Pl.A
;A=FF hex i'nput port. k Pl an ;ma e , . 1s to it ·by writing a 11 ' e t data from Pl ;g · save i·t in reg R7
A,Pl R7,A
'
ACALL DELAY MOV MOV
;wait hr data from Pl ·get anot e ' ·save 1·tin reg R6
Pl R6,A
A,
'
V ACALL DELAY f MOV
A,Pl
~ MOV
RS,A
;wait from Pl ·get another data '.save it in reg RS '
like Pl _Eort ~oes OQt
. ' -d as an input used as input or output. tJust 2 is configure_ . PortPort 2 2 occupies a_ total o~ in, ( ins 21 thmugh 28). be temally. Opon n,;et, po, d AAH. That ,s, all the b,o it al~ady has pull-up res1sto~;altemating values SSH an need The anuull-~ r~ ~ :send out continuously to port 2 followmg co o ew port.
H'"'
~~
of P2 toggle continuously.
BACK:
/
A,#SSH P2 ,A
MOV MOV
ACALL DELAY
CPL SJMP
;complement reg. A
A
BACK
Port 2 as input an input, it mus_t _program~e;:,:~s~~~ To make port figured first as an 2input port by writing ls to .
/
~~
writin 1 to ,u it,; bit,;. In the following ,ode, po,t 2 is ronreceivfd from that port and is sent to Pl continuously.
;Get a byte from P2 and send it to Pl MOV A,#OFFH ;A=FF hex MOV P2,A ;make P2 an input port by ;writing all ls to it BACK: MOV @) P2 ;get data from P2 MOV Pl,A ;send it to Port 1 SJMP BACK ;keep doing that
Dual role of portr'l'l2ov'
' ' .I
p),.
ln many systems based on the 8051, ~2 is used, as simple 1/Q ~wevec, Ul 803l:based sysrell\S~Port 2 must f2t used ~oog with PO to ,1><0:ide the 16-b_it address fo, memo,y. A, shown in Figu" 4-1, po, t 2 is also designated "
!"""''
,;g.Ais,-ma;ca,ng ,s du.rfun<"oo. Smc, ao 8051/31 " capable o_f "'."'mg 64K byte, of external memo,y, it needs a
~
p,th fo. the 16 bit,; of the add,ess. Wrule PO p,os,de, the lowe, 8 b,t,; "" AO · A7, it is the job of P2 to pmvide b;t,; A8 • A15 of th, address. In 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
Dtw
'°.
~
589 have three Pl, andasP2,el~r Thiwe s shoilluld enough' for most ' rnicrocontroUe nucr r app ocon lications. o ers,That leaves port ports,.PO, 3 for mterrupts w asf/0 o thope~ati~ns. er sign· s, as w seebe next. 11
Port3 Port 3 occupies a totaJ of 8 pins, pins 10 through 17. Jt can be used as in resistors just as Pl and P2 did not. AJthou h 78
,
· confi
t
ed as an input or ou tput. P3 does n ot need any pull-up
Ortu °"
u THE 8051 MlCRocoNl'
ROLLER AND EMBEDnEo SYSTEMS
o!>I con1monly used. Port 3 has the additional function of provid~g son1e extremely important signals su~ a~ interrupts. Tab~e 4-1 pro,·ides these alternate functions of P3. This information appbes to both 8051 and 8031 chips. . P3.0 and P3.1 are used for the RxD and TxD serial commun1catJoll!, signals. See Chapter 10 to see how they are connected. Bits P3.2 and P3.3 are set aside for external interrupts, and are discussed 1n Chapter 11. Bits P3.4 and P3.5 are used for timers O and 1, and are discur,sed in Chapter 9 where timers are discussed. Finally, P3.6 and P3.7 are used to provide the WR and RD signals of external memories connected in 8031-based systems. Chapter 14 discusses ho~v they are used in 8031-based systems. In systems based on the 8751, 89C51, or DS89C4x0, pins 3.6 and 3.7 are used for I/0 while the rest of the pins in port 3 are normally used in the alternate function role.
Table 4-1: Port 3 Alternate Functions Function
Pin
P3.0
RxD
10
P3.1
TxD
11
P3.2
INTO
12
P3.3
INTI
13
P3.4
TO
14
P3.5
Tl
15
P3.6 P3.7
WR
16
RD
17
P3 Bit
Example 4-1
Write a test program for the DS89C420/30 chip to toggle all the bits of PO, Pl, and P2 every 1/ 4 of a second . Assume a crystal frequency of 11.0592 MHz. Solution:
;Tested for t he DS89C4 20/30 with XTAL • 11 . 0592 MHz .
BACK:
ORG MOV MOV MOV MOV
0 A, #SSH
PO, A Pl, A P2, A
ACALL QSDELAY
MOV MOV MOV MOV
A,IOAU PO, A Pl,A P2,A
ACALL QSDV~Y SJMP BACX
; - - -----------1/4 SEcoal)
QSDELAY: H3: H2: Hl:
MOV MOV MOV DJNZ
tfi Rt. • • RS,
D,IIID
Rl,._
oowz R4, DJNZ RBT
R5,
END
Delay• 11 >< 248 >< 255 x 4 MC
Uo PORT PROGRAMMING
,Quarter of a •econd delay
/
· s
bits f ccessing the entire he entire Different ways o a . 1/ 0 examples, t . many previous In the following code, as in 8 bits of port I are accessed. BACK:
HOV MOV
,/
A,#SSH Pl,A
. ('~
ACALL DELAY HOV MOV
(lcJ
A,#OAAH Pl, A
v
f
. Reset Value of Some
Table 4-2, 8051 Ports
-1'2
Register l'O
p>
Reset Value (BinaryI 111111U
11111111
J'l
-
11111111 IJ ll llll
-P3
f.>!
-
bo e program before. Now
ACALL DELAY
BACK seen a variation of the a ·~out going through the tin usJy ~Ve have The above code toggles every bit of Pl co~. uo a~er by accessir1g the port dlrectly w1 we can re\,,rite the above code in a more effictent m SJMP
accumulator. This is shown next. BACK:
MOV
Pl,#SSH
ACALL DELAY MOV
Pl, ijOAAH
ACALL DELAY SJMP
BACK
The following is another way of doing the same thing. BACK:
MOV MOV
A,#SSH Pl,A
;A=SS HEX
ACALL DELAY CPL SJMP
A BACK
; complement reg. 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.
Ports status upon reset Upon re$! all ports have value PFH on them as shown in Table 4-2. This makes them input ports upon reset.
Review Questions I. There are a total of
2.
3. 4. 5.
Y
.o~~
ports in the 8051 and each has bits. True or false. AU of the 8051 ports can be used for both input and output. \/ Which 8051 ports need pull-up resistors to function as an 1/0 port?~ Pe True or false. Upon power-up, the 1/0 pins are configured as output ports. FShow simple statemC(ltS to send 99H to ports Pl and P2. ""IS r, , ..._ 9c, !-4 I
/ Y'l\11~ <> ' A efECTlON 4.2: VO BIT MANIPULATION PROGRAMMING "'• , "
~ ~~
In this section we further examine 8051 1/0 instructions. We pay spec:;· l . isa powerful and widely used feature of the SOSl family. ,a attention to 1/0 bit manipulation since it
VO ports and blt•addressablllty Somebmes we need to access only l or 2 bits of the port instead f . 1/0 ports is their capability to access individual bits of the port With O the entire 8 bits. A pownrful f tu f onc51 'the th • . out alterln th < ea re O four 8051 ports, we can access e1 r e entire 8 bits or any single bit . · ~,g e rest of the bits in th Ofau. the in sll\gle-bit manner, we use the synt.1x "SETB . Y" where Xis th without altering the rest w.. . . at ~rt. e port "Ulllber O 1 2, """"' accessing• port l,,, f ' ' or 3, and Y is the desired bit 80
I: I
Table 4-3: Single-Bit Addressability number from Oto 7 for data bits DO to 07. For example, "SETB P_l · 5" sets high bit 5 of port 1. Remember that DO is the LSB an~ D7 is the of Ports Port Bit P3 P2 MSBJor example, the follo~5 ode to9g~es bit Pl.2 continuously. PO P1 ~ ACK:
CPL Pl.2 ACALL DELAY SJMP BACK
Pl.0
P2.0
P3.0
DO
PO.I
Pl.l
P2.l
P3.1
Dl
P0.2
Pl.2
P2.2
P3.2
D2
P0.3
Pl.3
P2.3
P3.3
03
P0.4
Pl.4
P2.4
P3.4
04
P0.5
Pl.5
P2.5
P3.5
D5
P0.6 P0.7
Pl.6 Pl.7
P2.6 P2.7
P3.6 P3.7
D6
P0.0
;complement Pl.2 only
;another variation of the above program follows ;change only Pl.2=high SETB Pl.2 AGAIN: ACALL DELAY ;change only Pl.2=low CLR Pl.2 ACALL DELAY SJMP AGAIN
07
Notice that P1.2 is the third bit of P1, since the first bit is P1 .0, the second bit is Pl.1, and so on. Table 4-3 shows the bits of the 80511/0 ports. See Example 4-2 for an exan1ple of bit manipulation of 1/0 bits. Notice in Example 4-2 that unused portions of ports 1 and 2 are undisturbed. This single-bit addressability of I/0 ports is one of most powerful features of the 8051 microcontroller ai1d is among the reasons that many designers choose the 8051 over other microcontrollers. We will see the use of the bit-addressability of 1/ 0 ports in future chapters. Table 4-4 lists the single-bit instructions for the 8051. We will see the use of these instructions throughout future chapters.
Example4-2 Write the following programs. (a) Create a square wp.ve of 50°/o duty cycle on bit Oof port 1. (b) Create a square wave of 66°/o duty cycle on bit 3 of port 1. Solution: (a) The 50o/o duty cycle means that the "on" and "off" states (or the hi h d l · same length. Therefore, we toggle Pl ·Owith a time delay ;" g anchow portions of the pulse) have the ... between ea state. HERE:
SETB
Pl. O LCALL DELAY CLR Pl . O LCALL DELAY SJMP HERE
;set to high bit o of port 1 ;call the delay subroutine ;Pl.OcO
;keep doing i t
Another way to write the above program is: HERE:
CPL
Pl .O
LCALL DELAY
SJMP
HERE
; complement bit o of po rt 1 ; call the delay subroutine ;keep doing it 8051
Pl.O
-
i,.....-
l
J .-
.
,
1/Q PORT PROGRAMMING
81
.
" f(" state.
·cethe o th "on" state tS twl . h (b) The 66% duty cycle means e SSTB
BACK:
LCALL DELAY t.Cill,L DELAY CLR
Pl.3
LCALL DELAY SJMP
bit 3 hl9 . broutine ·n '.call the delaY s::i,routine aga> '.call the delay 5 1(Pl.JslOW) • 2 of port :clear bit ubroutioe ·call the delays ; keep doing it
·set port
Pl. 3
BACK
1
8051
Pl.3 ..__
I
L-___.r
_ J ~ - - 11
Table 4-4: Single-Bit Instructions SETB bit
Function Set Lhe bit (bit - l )
CLR
bit
Clear the bit (bit - 0)
CPL
bit
Complement the bit (bit - NOT b it)
JB
bit,target
Jump to target ii bit : I fj ump if bit)
) NB
b it,target bit,target
Jump to target if bit : 0 fj ump if no b it)
Instruction
? JBC
Jump to target if bit: l, clear bit Gump if bit,
'
then .s.J"Wr)
&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: PO.l MOV Pl, JOPFH JNB PO .1, AGAIN MOV A, Pl CLR P0.2 SETS P0.2 SETB
AGAIN:
:make Po.2 an input ;make Pl an •nput ;check if PO 1 . port if . 18 high if ; Po .1 1 8 found hi • not,
keep checking
,clear Po.2 9h, take in data froaa Pl :set Po .2 Tius type of a program is required to read m data from (mdicated by showing a high on P0.2 here). Note that: A to D COflverte, after . programmed as such by writing ls to it. mal(e Ports or Uldi . venfyinglflheconveslianll VJduat l)Clrt lines to 9Ct • lapu\ It 82
/
Checking an input bit
The JNB Gump if no bit) and JB Gump if bit = 1) instructions are also w idely used single-bit operations. They all.ow Y'" to mocitor a bit and make a decis;on depending on whether it is Oor I. Instructions JNBand ]B can be used for any bits of I/ 0 ports 0, l, 2, and 3, since all ports are bit-addressable. H owever, m ost of port 3 is used for interrupts and serial communication signals, and typicaUy is not used for any I/0 , either s ingle-bit or byte-wise. This is discussed in Chapters 10 and 11. Table 4-5 shows a list of instructions for read ing the ports.
Table 4-5: Instructions For Reading an Input Port Description
Mnemonic
Example
MOV A,
MOV
A,
JNB
P2 . 1 , TARGET
JB
Pl . 3 , TARGET
MOV
C,
PX
JNB PX . y
JB
I
PX. Y,
MOV C,
••
..
PX . y
Bring into A the data a t P2 pins
P2
Jump if pin P2.l is low Jump if pin Pl .2 is high Copy s ta tus of pin P2.4 to CY
P2.4
Example 4-4
~
°~
Asswne that bitcontinuously P2.3 is an input and epr~~ ts t h ';;nd.it~n . . goes high, it means that the oven is hot. When: an oven. If it Monitor the bit Solution: . ver i goes g 'sen a high-to-lo\v pulse to port Pl.5 to tum on a buzzer.
HERE : JNB SETB CLR SJMP
P2 .3,HERE Pl.5
Pl .5 HERE
;keep monitor ing for high ;set bit Pl.5=1 ;make high-to-low ;keep repeating
vcc
J ~
S,vttch
....
8051
P2.3
~
4.7k ·~
Pl.5
B~r
1-----ll/)O-· --'0....._
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:
p,.'1-· o_ ...._ j4
Solutjon:
AGAIN:
SETB Pl.7 Pl.-:,, OVER JB
;make Pl.7 an i ;jump if nput
MOV
· ,• SWcO ' issue 'N' ;keep monitoring to P2 ;SW•l , is sue •y, ·ke to P2 ' ep monitoring
P2,#'N'
SJMP AGAIN
OVER:
MOV
P2,#'Y'
SJMP AGAIN
'f
Pl.7:1
-
1/Q PORT PROGRAMMING
83
(
. 11.!ld perform the following: f the s,\lttch
. a rogram tocheek the statuS ed toopin pJ.7. 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
EJcimpl• 4-6
U,e the carry Ong to check the switch status.
Solution: AGAIN:
SETB PO.l MOV C,PO.l JNC AGAIN SETB Pl. 7 CLR Pl. 7 SJMP AGAIN
~
n input . ato carry Jlag 1· t ·make PO, l a f PO. l 1 • contents o . ue t. 0 -onitor m ;read the h "gh cont in Pl 7 ; if PO .1 ~s nh?gth i se~d a high tolse. on Pl. 7 ·if PO.l i s i . ' a H-to-L pu
~send low now: i.~~~ the pin status ;continue monitori
t, p:'AE~x;a;m;p;1.;~;7~~~;-:::--::;:: :--;;;~:;;:;;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 switch lS connected to pm 1t to the LED. Solution:
Pl . 7 MOV C,Pl.0 MOV P2.7,C SJMP AGArN SBTB
AGAIN:
;make :read ,send ;keep
Pl.7 an input the sw status into CF the sw status to LED re~ating
Note: The instruction "MOV P2. 7, Pl. o" is wrong since such an instruction does not exist. owever, · H "MOV P2 , Pl" 1~ a valid instruction.
Reading a single bit into the carry flag canC, alsoPx use the carry flag to save or examine the status or a single bit of the port. To do that, we use the instruction We "MOV . y" as shown in Examples 4-6 and 4-7. Notice in Examples 4-6 and 4-7 how the carry flag is us«! to get a bit of data from the port.
Reading input pins vs. port latch In reading a port, some instructions read the status of port pins while others read th tatu f . I I tch Therefore, When reading ports there are two possibilities: es so an m tema port a · Read the status of the input pin. 2. Read the internal latch of the output port. I.
We must make a distinction between these two categories of instru . . source of errors in 8051 progYamming, especially where external h.1.rd ctions smce confusion between them is a major briefly_However, reade_rs must study and understand the material : : : 1~ c~ncerned. We diseuss these instructions 0 that is given In Appendix C.2. op,c and on the internal working of ports 84
THE sos1 MJCRocoN'f ROLLER AND EMBEDDED SYSTEMS
structions for reading input ports In
.
Table 4-6: Instructions Reading a Latch (Read-Modify-Write)
t
As stated earlier, to make any bit of any. 8051 port an in~ut we must write 1 (logic high) to that bit. After we co~ g ~;; ;he port bits as input, we can use only certain '.11s~ct1ons . order to get the external data present a t the pins in to the ~PU. Table -!-6 shows the list of such instructions.
•
Mnem onic
ANL
PX
Example ANL
Pl,A P2,A
ORL
PX
ORL
XRL
PX
XRL
PO,A
JBC
JBC
Pl.l,TARGET
Reading latch for output port
PX.Y,TARGET PX.Y
CPL
Pl.2
Some instructions read the contents of an inte rnal port latch instead of reading the status of a n external pin. Table 4-6 provides a list of these instructions. For example, look a t the "ANL Pl, A" instruction. The sequence of actions ta ken whe n such an instruction is executed is as follows.
CPL INC
Px
INC
Pl
DEC
PX
DEC
P2
DJNZ PX . Y,TARGET MOV PX . Y,C
OJNZ Pl,TARGET MOV Pl.2 , C
bri.ngs that da ta into the CPU. 2. This data is ANDed with the conten ts of register A.
CLR PX . Y SETB PX. Y
CLR P2 . 3 SETB P2 . 3
3. The result is rewritten back to the port la tch.
Note: ,: is 0, I, 2, or 3 for PO - P3.
1. The instruction reads the inte rnal la tch of the port and
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 A.GAIN:
XLR
Pl ,#SSH Pl,#OFFH
;Pl= 0101010 1 ; 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 (input, o utp ut). 70 5. Write instructions to toggle both bits of Pl .7 and Pl.0 continuo usly. v'
.o.
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 ~ ~ C) if you ~e connecting any e xternal hardware of your 8051 system. right connection to p ort p ins can damage the ports
t::e
'
Pl P2 and P3, each use 8 pins 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 mald scna1 co showed the bit-add.ressa ,
SUMMARY
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 _ _::.'--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? How many pins are designated as Pl and which number are they!" the pack g ; 6. How many pins are designated as P2 and which number are they '.n the DIP pac age? 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
r
s:
tnStruction.
SECTION 4.2: 1/0 BIT MANIPULATION PROGRAMMING 16. 17. 18. 19.
20.
21. 22.
23. 24. 25.
. /26 . 27.
28.
Which ports of the 8051 are bit-addressable? ~ What is the advantage of bit-addressability for 8051 ports? When .Pl ,s accessed as a single-bit port, it is designated as What IS the error II\ the following code? ---MOV Pl, #OFH CPL Pl Write a program to take in data through P1 0 and sen . Write a program to toggle Pl 3 Pl 7 and 1'2. S . d ,1 out through P2.7. w · · • · • · conllnuousl 'th . W~tea program lo monitor bit Pl.3. When ii is hlgh se d ~;~ out d,sturbing the rl'st of the bits nle a program to monitor the P2.7 bit. When it is 1' w n to P2. . Wnte a program to monitor the P2.0 bit. When it is I~ • send SSH and AAH to PO con tin Wnte a program to monitor the Pl 5 b't Wh . ugh, send 99H to Pi If 1·1. I uously . wn·1ea program to get the status or· Pl.3 ' · en 11 is high k · is ow send 66H a d . • ma c a low-to-high t I • to p 1. A switch SW is connected to pin Pl 4 W . n put ,1 on Pl .4. - o- ow pulse on Pl.3. SW;J. . . nteaprogramiooutputOOon . Writea program to generate a square wa,•e of 25% d portt 1ISW:O'and output FFH on port 1 ii uty cycle on pin P2.3.
ANSWERS TO REVIEW QUESTIONS SECTION 4.1: 8051 1/0 PROCRAMMJNG 4, 8. 2. True 3. PO I.
••
I
4. False 5. MOV Pl,#99H MOVP2,#99H SECTION 4.2: 1/ 0 BIT MANIPULATION PROGRA.MMJNG True Hl: CPL Pl.7 SJMP Hl Input MOV C,P2.7 MOV P2.0,C Hl: CPL Pl.7 CPLPl.O SJMPHl
].
2. 3. 4.
5.
,..
/
1l\ it: C>~ ~ H
"""c\J
,)
\oc::I.C...'L. ~ °f'('
r,'t~
t>"
'('(\ 6
-.J
w,.i:.\J
m,v ~'3 ~ f.>
,..
.)
Pl
Po> A Pl.)
-tt.
P~J~ b "-C..V.
• •
-110 PORT PR.OCllAMMING
CHAPTERS
8051 ADDRESSING MODES
OBJECTIVES Upon completion of this chapter, you will be able to:
>
>
> >
> >
> >
> >
List the five addressing modes of the 8051 rnicrocontroller Contrast and compare the addressing modes Code 8051 Assembly language instructions using each addressing mode Access RAM using various addressing modes List the SFR {special function registers} addresses Discuss how to access the SFR Manipulate the stack using direct addressing mode Code 8051 instructions to manipulate a look-up table Access RAM, 1/0, and ports using bit addresses Discuss how to access the extra 128 bytes of RAM space in the 8052
r be provided as an immediate . .,,; ter or in rnernor}', ~e discuss 8051/52 addressing d ta ould be t11 a r,.,..5 ',_ this chapter u data in various ways. The a c d 11· ru modes, u, The CPThcan ace~55 "ays of accessing data are called ad ress " • d . aned and therefore cannot be value. ese vanous " h it JS f U . modes in the context or some examples. . sor are determined w ~ . modes. They are as o ows. The various addressing modes of a llU~oproces J of five distinct addresstllg changed by the programmer. The 8051 provides a tota
es,.,.. '
, / l.
(
2.
3. ./ 4.
immediate register direct register indirect 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 , reg,s5 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
. / S.
3
~
SECTION 5.1: IMMEDIATE AND REGISTER ADDRESSING MODES In this section first we examine immediate addressing mode and then register addressing mode. ' (•
I
u"
,...J•
- • ...
"
•
t • . . """"
It'
i ""' It i S fl '
• (
C
L.~
Immediate addressing mode In this addressing mode, the source operand is a i;gnst~t. In immediate addressing mode, as the name implies, when the instruction is assembled, the operand comes immediately after the opcode. Notice that the immediate data must be preceded by the pound sign, • #". This addressing mode can be used to load information into any of the registers, including the DPTR N?gister. Examples follow. MOV MOV MOV MOV
; load 25H into A ; load the decimal value 62 into R4 ;load 40H into B ;DPTR•4Sl2H _.., ff,. I,, J :l / : ,SJ .3
A,#25H R4,#62
I
8,#40H
DPTR,#4521H
(,
-
-
MOV DPTR, #25;H
is the same as; MOV DPL,o50H MOV DPH, #3SH
MOV DPTR, #68975. illegal!'
'
-
l
.
ce an error sance the value.IS Iarger than
' v ~ > 65535 (PFFFFH)
16 b' its.
We can use the EQU directive to access immedi t d a e ata as shown bel COUNT '€OU- J.o ) ow• .._ 1 ~
MOV MOV
R4,#COUNT DPTR, #MYDATA
ORG 200H
HYDATA:
.
08
90
·America•
Notice that we can also use immediate dd
JS a valid instruction.
a
.
ressang mode to send d
.t
•c,•
! I lio1
I J.,r1 i iltl
. ~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
Also notice that the following would produ
!1111111
ata tosos1 ports. For example, "Mov Pl• tssll"
THE 80S1 l\.11c1toc ONTROttER
" ANO EMBEDDED SYSTEMS
\l e! .. ~ .. ,.
"
1
·.~,
·- (
I Register addressing mode invo ves add ressing mode follow.
MOV MOV ADD ADD MOV
A,RO R2,A A,RS A,R7 R6 , A
-,
1J , h,1 t ) t ( ;JV
Register addressing mode
J
'TO
£We.....1)
~ ,~ 1~ ~ 1
.
h ld the d a ta to be manipulated. Examples o f registe r the use of registers to o .
;copy the contents of RO . i nto~ ;copy the contents o f A i nto Rten t s of A ·add the contents of RS to con , t nt s of A ;add the cont ents ~f R7 t o cone ; save accumula tor i n R6 .
d
d ' g " MOV DPTR, A"
. . . must match in size. In other wor s, co m . It should be noted that thesour~e and de~tina~on re~t:: destination is a 16-bit register. See the folJowmg. will give an error, since th e source 1s an 8-b1t register an
MOV DPTR, #25[2.H r- H MOV R7,DPL 'l=-o MOV R6 , DPH ., :> S H
Rn (f
- 0 to 7) but m ovement of d a ta betw een
Rn
Notice that we can move data between the accumulator an d · . ~r n -: th · ti "MOV R4 R7" 15 invalid. registers is not allowed. For example, e mstruc on 'th ' . 'd of the registers or tagged alon g w ith the 51 1J1 the firs t two addressing modes, the operands are ei .er .e one ry location o f RAM o r in the code instruction itself. In most programs, the data to be processed 1s o ten m some 1:11emo . d space of ROM. There are many ways to access this d ata. The next section describes these different m etho s .
f
...
,r\<,J
Review Problems 1. 2. 3. 4. 5.
~ JI
,i(\_"'}:.
>(
(. V' ": )
,,,.
Can the programmer of a microcontroller make up new addres~ing modes? N"0 Show the instruction to load .1000 0000 (binary) into R3. I l,.. o 1)1"' f. i ; 1 g 1,;+ . Why is the following invalid? "MOV R2, DPTR" 0 P7 ll ,.J , 6 • ·~ ~ d . _ True or false. DPTR is a 16-bit register tha t is also accessible in low-byte and high -byte formats. I Is the PC (program counter) also available in low-byte and high-byte formats? NO ·
~..k ]>P'rf?
~ ~M
SECTION 5.2: ACCESSING MEMORY USING VARIOUS ADDRESSING MODES We can use direct or register indirect add ressing modes to access data s tored either in RAM or registers of the 8051. This topic will be discussed thoroughly in this section. We will also s how how to access on-chip ROM containing d ata using indexed addressing mode.
/
Direct addressing mode As mentioned in Chapter 2, there are 128 by tes of RAM in the 8051. The RAM has been assigned dd 00 t 0 7FH. The following is a summary of the allocation of ffiese 128 byEes. · · a resses
1.
RAM locations 00 - l FH are assigned to the register banks and stack.
2. 3.
RAM locations 20 - 2FH are set aside as bit-addressable space to save single-b 1't d a ta. This 1·s discussed m . Sectio . n53 RAM locations 30 - 7FH are available as a place to save byte-sized data. · ·
Although the entire 128 bytes of RAM can be accessed usin direct ddr · . . RAM locations 30 - 7FH. This is due to the fact that register baiJl . a ess mg m od e, it is most often used to access but there is no such name for other RAM locations. In th d ' oca~ns ar~ accessed by the registe r names of RO- R7, location whose address is known, an d this add ress is give e irect a dress~g mod.e, the data is in a RAM memory addressing mode, in which the operand itself is provided;.:~ ~p~rt of th~ instruction . Contrast this w ith immediate two modes. See the examples below, and note the absence 0 ; the '~#~:~tion . The "#" sign dis tinguishes between the
MOV R0 ,4 0H MOV 56H,A MOV R4, 7FH
-
;save c ontent of RAM l ocation 40 . ;save content of A in .Hin RO ;move contents of RAM~ l?cation 56H ocation 7 FH to R4
S0s1 ADDRESSING MODES
91
1nese registers can be accesse(f oo. R7o..-isterS " ed to bank '-.,·
· oto 7 are aUocat
As d,scussc.-d earUcr, RAM locations
,n two ways, as shown below. MOV A,4 MOV A, R4
;is same as copy •·which means
MOV A, 1 MOV A,R7
;is same as ;which means copy R1 into A
MOV A,2 MOV A,R2
; is the same as ;which means copy R2 into A
MOV A, o MOV A, RO
;is the same as
R4
inCO A
.
;which means copy RO into A
The above examples should reinforce the importance
.
.
·nstructions. See the followmgcode.
•
0 f the "#" sign Ill 8051 ,
;R2 with ;copy R2 ;copy R2 ;copy R2
value 5 to A (A• R2=05) to B (B=R2•05} to R1 · since ·Mov R7, R2" is invalid ' · dd RAM locations 30H to 7FH cannot be Although it is easier to use the names RO - R7 than their memory a resses, accessed in any way other than by their addresses since they have no names. MOV R2,#5 MOV A,2 MOV 8,2 MOV 7,2
SFR registers and their addresses Among the registers we have disrussed so far, we ha,•e seen that RO - R7 are part of the 128 by tes of RAM memory. What about registers A, 8, PSW, and DPTR? Do they also have addresses? The answer is yes. In the 8051, registers A, 8, PSW, and DPTR are part of the group of registers oommonly referred to asSFR (special function registers). There are many special function registers and they are widely used, as we will discuss in fu ture chapters. The SFR can be accessed by their names (which is much easier) or by their addresses. For example, register A has address EOH, and registc:,r B has been designated Uie address FOH, as shown in Table 5-1. Notice how the following pairs of instructions mean the same thing. MOV ~ - #SSH ; is the same as MOV~#SSH ;which means load SSH into A (A=SSH) MOV OFOH,ij2SH ;is the same as MOV B.~25H ;which means load 25H into B (B•25H ) MOV O&OH,R2 ; is the same as MOV A,R2 ;which means copy R2 into A MOV OPOH ,RO ; ie the same as MOV B, RO :which means copy RO into 8 MOV Pl , A ;is the same as MOV 90H,A ;which means copy reg A to Pl Table 5-1 Lists the 8051 •P.ecial function registers (SFR) noted about the SFR addresses. and their addresses. The foll
. owmg two points should be
1.
The special function registers have addresses b tw addresses 00 to 7FH are addresses of RAM mcm~ ':'!'\flH and FFH. These add 2. Not all the address space o( 80 to FF is used b thry UtS• c the 8051. l"eS.'leS are above 80H, since the not be used by the 8051 programmer. y e SFR. The unused locations 80 H to FFH are l'eSel"ved and must Regarding direct addressing mode, notice the f II . 00 - FFH, which means this addressing mode is lm::t:ving two points: (a) th 8051. (b) if you examine the 1st file for an Assembly I to accessing °RAM I e •ddress value is lim .led b.0 0 replaced with their addresses as listed in Table S-I. anguage program, you • 1lons and registers toe' ..:, • ~d 1..;: ,11see that ,.__ a,...., ln5l e ..,.. u.., SFR r e ~ · names are
!
92
OCoNTRottER AND
f!M8mD1D SWiiMS
. I Function Register (SFR) Addresses Table 5-1: 8051 S pecta
Address OEOH OFOH
8
} B register
•
PSW•
Program status word
SP
Stack pointer
DPTR
Data pointer 2 bytes
QDOH 81H 82H
OPPIL~~~====~~L~ow~bfy~te~~~~~~~~~~~~~S:8331H=.-~
High byte r'"'""' PortO
DPH
po•
Port 1 Port 2
P1 •
p2• P3"
/ Port 3 Interrupt priority control Interrupt enable control Timer/counter mode control
w• ffi•
TMOO
80H 90H OAOH OBOH 088H OA8H 89H
Timer/counter control
88H
T2MOO
TLIDer / counter 2 control TLIDer/counter mode control
OCSH OC9H
THO
Timer/counter Ohigh byte
SCH
TLO
Timer/counter O low byte
BAH
THl
Tuner/ counter 1 high byte
SDH
Tll TH2
Timer/counter 1 low byte
88H
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
T2CON"
-
• 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 MOV Pl, A MOV P2 , A
; A=SSH ;Pl =SSH ;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
(
B RO and Rl, of bank I '
th registers ,
Sol lion: . does not create a conflicr u stacJ<~bon On rese~ the stack pointer is initialized to (17. cl< location is 40H and the Let us now anitialire it to 3FH so that the first sta w,th bank I registers. MOV SP, #3FH
PUSH 00 PUSH 01
PUSH OEOH SETS PSW.l POP OPOH POP 09 POP 08
; SP=lFH ·push RO of bank '.push Rl of bank ; push A register . h to bank l ;SW1tC
stack top Oto ck o to st: to scac. RSO bit ; of PSW ( PSW. 1) = l by making . k t p to B register ;pop the content of stack t~p co Rl of bank l ;pop the content of stac top to RO of bank 1 ;pop the content of stack
. ters RO and Rl are transferred to bank 1 Now we have the content ol A in B, and the contents of bank O reg)S registers RO and RI. -
Stack and direct addressing mode Another major use ol direct addressing mode is the stack. In the 8051 family, only direct addressing mode is allowed for pushing onto the stack. Therefore, an instruction such as "PUSH A" is invaUd. Pushing the accumulator onto the stack must be coded as "PUSH OEOH" where OEOH is the address of register A. Similarly, pushing R3 of bank 0 is coded as "PUSH OJ". Direct addressing mode must be used for the POP instruction as weU. For example, "POP 04• wiU pop the top ol the stack into R4 of bank O.
,
Register indirect addressing mode Jn the register indirect addressing mode, a register is used as a pointer to the da [f - . . registers RO and RI are used for this purpose_ ln other words R2. R b ta. the data 1s lllS1de the CPU, only 7 located in RAM when using this addressing mode. When RO and RJ :nnot e Used .to hold the address of an operand addresses ol RAM locations, they must be preceded by the ..,,,.. ehused as pomters, that is, when they hold the "' sign, ass own below. HOV A,eRo ;~~e con~ents of RAM location whose ;a resa 1s held by RO into A MOV
;move contents of B into RAM loca . ;whoae addreaa is held by Rl
tion
Notice that RO (as well as Rl) is preceded by the"@" as an instruction moving the contents of register RO t s,gn. ln the absence of the"@" 0 to by RO. A, tnstead of the conte ts f s ,gn, MOV wiU be interpreted n the memory location pointed
°
Advantage of register indirect addressing mode One of the advantages of register indire,:t addressstatic as in the case of direct addressing mode Exa •ng mode is that it rnak · mp1e 5-3 sho es accessin d ws two cases of . g ata dynamic rather than copyll\g SSH into RAM locations
THE 805t MICRocoNTR OLLER AND EMBEDDED SYSTEMS
40H to 45H. Notice in solution (b) that theStrnctions as shown in solution (c). Solution (c) is the most effident and is possible only because of ,egister indirect add,essing mode. Looping is not possible in di
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:
~
vJ'-
;load ;copy ;copy ;copy ;copy ;copy
A with value SSH A to RAM l ocat ion A to RAM locat i on A to RAM location A to RAM l ocation A to RAM locat i on
(a)
MOV A,#55H MOV 40H, A MOV 41H,A MOV 42H,A MOV 43H,A MOV 44H,A
(b)
MOV MOV MOV INC MOV INC MOV INC MOV INC MOV
A, #SSH R0,#40H @RO,A RO @RO,A RO @RO,A RO @RO,A RO @RO,A
;load A with value SSH ;load the pointer. R0=40H ;?opy A to RAM location RO points ;increment pointer. Now R0=41H ·?opy A to RAM location RO points ;increment pointer. Now ROc 42H ·?opy A to RAM location RO points ;increment pointer. Now R0=43H •?opy A to Rru:1 location RO points ;increment pointer. Now R0=44H
MOV MOV MOV MOV INC DJNZ
A, #55 R0,#1.Q!ll R2,#0S I @RO,A 4-1 RO R2,AGAIN
;AzSSH ;load pointer. R0:40H RAM ;load counter, R2 =S ' address ;copy SSH to RAM l . ;increment RO poin~:;tion RO points to
40H 41H 42H 4 3H 44H
to to to to
I,
\
(c)
AGAIN:
;loop until counter
=
zero
Example 5-4
•
wnte · a program to clear 16 RAM locations starting . a t RAM address 60H . / Solution:
· CLR
AGAIN:
A
Rl,#60H R7,#16
MOV MOV MOV INC
1A•O
;load ;load poi n t er. Rl•60H counter R7 ;clear RAM ' .•16 (10 in hex) 10 ,· i ncrement Rl cation Rl pointa to ;loop until pointer counter. ze ro
8051 ADDRESSING MODES
95
d save the result in dall
h of them, an
Ex•mpl• S-5
l ations 45H to Take 10 byres of data from data RAM oc RAM locations 79H down to 70H. Solution:
,
h counter
HOV MOV MOV HOV
BACK:
54H add 02 to eac
ADD MOV INC DSC
R2,#10 R0,#45H Rl. #79H A, liRO A, #02 @Rl,A RO Rl
DvNZ R2,BACK
;R2 is used as t e location first source location o ;RO points t destination ;Rl points to first ;move source byte to A ;add 2 to i t . co desci nat1on ,move it inter
,increment the sour~e ~on pointer ,decrement the desc1na of destination is in ;this is because the address ~decreasing order · s zero ;repeat until counter va 1ue i
· ter ·indirect · · m ode in a block transfer is given in An example of how to use both RO a.n d Rl in the regJs a ddressmg Example 5-5.
Limitation of register indirect addressing mode in the 8051 As stated earlier, RO and RI are the o nly registers that can be used fo r pointers in register indirect addressing mode. Since RO and Rl are 8 bits wide, their use is limited to accessing any information in the internal RAM (scratch pad memory of JOH· 7FH, or SFR). However, there are times when we need to access data stored in externa l RAM or in the code space of o n-chip ROM. Whether accessing externally connected RAM or on-chip ROM, we need a 16-bit pointer In such cases, the DPTR register is used, as shown next.
Indexed addressing mode and on-chip ROM access Indexed addressing mode is widely used in accessing data elements of look-
-
.
ROM space of the 805). The instruction used for this purpose is "MOVC up table entries located m the program register A are used to fonn the address of the dara element stored . h . A, ~ +DPTR". The 16-bit register DPTR and
in the program (code) space ROM of the 8051 the instruction MO~~".-<: 'PR_ M. Because the data elements are stored this instruction the contents of A are added t~ the 16-bit register D~ used instead of MOV. The "C" means code. In
to fonn the 16-bit address of the needed data.
See Example 5-6.
.
6/)f , ·-
wmpleS-6
<
'..-<>:S
. 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: ·
f I/ ' ( '
D
96
(>''
ORO OOOOH
CLR A HOV DP'TR, #04 OOH , MOVC I\, '1~PTR . HOV 60H,A
\
I -
I
• I ~
/ "'.,,...
f:
w~(\';jJ-
;program Starts at 1 ,A-o oeation OOOOH ;0PTR•400H (poi ;get ·s· fr°"' l~~=t ~o first aou:rce locat::ion) ;move it to !(JIM >on 40 0H 1oCation 60H
Tl-IE 8051 MICRoc ONTROL
LERAN
D EMllEDDED SYSTEMS
;DPTR• 401 H (points to next location )
INC DPTR
·A•O ;get ' A' from 1ocat10~ 401H ;move it to RAM location 61H
I
CLR A
MOVC A, @A +DPTR MOV 61H,A INC OPTR
;OPTR•402H ;A:sO ;get 'M' from location 401H ;move it to RAM location 62H ;stay here
CLR A MOVC
A, @A+OPTR
MOV 62H,
A
HERE: SJMP HERE
6- ') ORG 400H
;data is burned into location starting from 400H
DB "SAM''
;directive for end o f file
END
DcJ
,V'
J,,
<--
~
•
bd t L
6b
r,~cj1 ct-.,,_,·
Example 5-7
Assuming that ROM space starting at 250H contains "America", write a program to transfer the bytes into RAM locations starting at 40H.
Solution: ; (a)
This method uses a counter ORG 0000 MOV MOV
DPTR, #MYDATA -i: RO, #4 OH ' ... ~-
MOV
R2, #7 A
CLR
BACK:
MOVC
HERE:
MOV
INC INC
DPTR RO
SJMP
pointer ; load pointer ; load counter
-1 ·1 :i..
A, @A+DPTR @RO,A- -
' DJNZ
fC~ load
ROM RAM
;A = 0
;move data from code space ;save it in RAM . ;~ncre ment ROM pointer ;increment RAM pointer ;loop until counter =O
R2,BACK HERE
: - --- - - ----on-chip code s pac e used for storing da t a ORG 250H MYDATA DB "AMERICA" END
't
l4;1...
<1b
Str~
(i
; (bl This method uses null char f or end of str1·ng
BACK:
ORG HOV HOV
0000 DPTR #MYDATA R0, #4 0H
CLR
A A ,
MOVC J/ J Z ~
I
MOV
HBRB- ~ ' & O,A
IIJC
DPTR
8051 ADDRESSING MODES
°$
;loa d ROM pointer ; load RAM point e r ; A•O
,move dat a frOftt c ode epace ·exit if ' null cha ,eave it i n RAM racter , 1nct•ant: Rell poiatff
HERlt:
j
INC
RO
SJMP
BACK
SJMP
HeRE
---·----·-
;increment ;lOOP
d for stor1 ng data Use space on-chip code 25011
ORG
·not i ce null char for .;end of string
-
•AMERICA .. ,0
MYDATA : DB
,
&ND
. Notice the null character, 0, indicating the end of the stnng.
j
• Z [nStruction to detect that. th and how we use e J
Look-up table and the MOVC instruction
· It allows access to elements of a freThe look•up table is a widely used concept ln microprocessor progra ~ g. t · application we need x' va]lJ6 cer am.,n Examp1e 5 •8 quently used table with minimum operations. As an example, assume · ·that ""'-·or·a shown ul m the range of O to 9. We can use a look-up table instead of calc anng ,t. • n1s is · 1n addition to being used to access program ROM, DPTR can be used to access memory externalJy connected to the 8051. This is di.scu.ssed in Chapter 14. Another register used in indexed addressing mode is the program counter. This is discussed in Appendix A. 1n many of the examples above, the MOV instruction was used for the sake of clarity, even though one can use any instruction as long as that instruction supports the addressing mode. For example, the instruction "ADD A, @RO" would ad~ the conte~ts of the memory location pointed to by RO to the contents of register A. We will see more examples of usmg addressing modes with various instructions in the next few chapters.
Indexed addressing mode and MOVX instruction has 64K bytes of !'()(le s d th di ter. We just showed how to use the MOVC instruction pace un er e rect control of the Program Counter regi¥ I space. In many applications the size of program code dee:n:~:v: portion of this 64K-byte code space as data memory any room to share the 641<-byte code space with data. As we have stated earlier, the 8051
Exampl• 5-8
Wnte a program to get the x value from Pl and send x' to P2 . , continuously. Solution:
...
ORG
0
MOV DPTR,#JOOH MOV A, #OPFH MOV ~,,A MOV A,91 MOVC A,eA.•DPTR
BJ\CK :
r
XSOR_TABLE:
MOV
P2,A
SJJ1P
BACK
=
DB END
~
JbOH
;load look-up tabl :A-Pr e address ;configure Pl a . ;get X s lnput port
~
;~et X squared fr ; issue it to 1>2 Oln table ;keep doing it
1.1,4',19,16,25 JS 49 6 ' ' ' 4 • 81
•
•
. . the below table. Store this the numerals from O to 9 are g1ve~e~ts of these locations one by
f The common cathode 'sev~-se~~~~:~s~~rite a program to ;~~;~aeyu;~: displays the numerals repeatlook 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 Example 5-9
0
3F
1 2
06 SB
3
4F
4
66
5
6D 7D 07 7F 6F
6 7 8 9
.
Solution:
START: BACK:
ORG OOOOH MOV Rl,#10 MOV DPTR,#400H CLR A MOVC A,@A+DPTR MOV Pl,A ACALL DELAY INC DPTR DJNZ Rl, BACK SJMP START '
;Rl=no of digits, i.e., counter ;load ROM pointer ;A=O ;move data from code space to A ;output data to port 1 for displaying it ;delay of 100 ms ;increment ROM pointer ;loop until counter=O ;repeat continuously
ORG 0400H ;store data at locations starting from 400H DB 3FH,06H,5BH,4FH,66H,6DH,7DH,07H,7FH,6FH END ;directive for end of file
' for this reason the 8051 has another 64K bytes of memory space set aside exclusively for data storage. This data memory '"'1 space is referred to as external n1emory and it is accessed only by the MOVX instruction. In other words, the 8051 has a total of 128K bytes of memory space since 64K bytes of code added to 64K bytes of d ata space gives us 128K bytes. One major difference between the code space and data space is that, unlike code space, the data space cannot be shared between code and data. This is such an important topic that we have dedicated an entire chapter to it: Chapter 14.
Accessing RAM Locations 30 - 7FH as scratch pad As we have seen so far, in accessing registers RO - R7 of various banks, it is much easier to refer to them by their RO - R7 names than by their RAM locati?ns. The only problem is that we have only 4 banks and very often the task of ~ank switching and keeping track of register bank usage is tedious and prone to errors. For this reason in many a p plications we use RAM locations 30 - 7FH as scratch pad and leave addresses 8 - IFH for stack usage. That m eans that we use Ro - R7 of bank 0, and if we need more regis ters we simply use RAM locations 30 _ 7FH. Look at Example 5-10.
-
8051 ADDRESSING MODES
99
Eic• mplt S-10 . •SH as the (Ountcr. RAM IQC'abOn ~ Write• delay subroubne using Solution:
DELAY, RBPBAT:
MOV 45H,#OFPH DJNZ 45H.REPEAT RET
Review Questions
•
RJ>JII 1ocacion 4SH value in counter ·1 count•O d ;loa counL untl ·decremenc
•
a
ddressing mode. Why?
1. The instruction "MCV ~~4 OH '~!r R2 of bank O? What address is assign,~ to reg1s k 2? ;: What address is assigned to reg!stcr R2 of ban . . data is jn on-chip RAM? 4. What addrl'SS is assigned to registe~ ~\ ister indirect addressing mode if the 5. Which registers are allowed to be use or reg
Byte
SECTION 5.3: BIT ADDRESSES FOR 1/0 AND RAM
address
Many microprocessors such as t he 386 o r Pentium allow ln 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 must read the entire b yte first and then manipulate the whole byte with some logic instructions to get hold of lhe desired single 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 registers, RAM, and 1/0 ports in bits instead of bytes. This 1s ~ very unique and powerful feature for a microprocess~,r made in t~e early 1980s. In this section we show address assignment of bits of 1/0, register, and memory, in addition to ways of programming them.
RAM 30 2F
2£ 20 2C 28 2A 29 28 27 26
]
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 bitaddress.1ble RAM locations arc 20H to 2FH. These J6 bytes provide 128 bits of RAM bit-addressability since 16 x 8 = 128. They are addressed as Oto 127 (in decimal) or 00 to 7FH. Therefore, the bit addresses Oto 7 are for the first byte of internal RAM location 20H, and 8 to OFH are the bit addresses of the second byte of RAM location 21 H, and so on. The last byte of 2FH has bit addresses of 78H to 7FH. See Figure 5-t and Example 5-11. Note that internal RAM locations 20 · 2FH are both byte-address.,bl and bit-addressable. e In order to avoid confusion regarding the add~ 00. 7FJ; the following two points must be noted. ·
100
Generalpurpose
~ =
Bit-addressable RAM
t.
7F
The 128 bytes of RAM have the byte addresses of 00 . 7FH and can be accessed in byte size using various add . modes such as direct and register-indirect as we h ressmg ;,1 ~• seen in this chapter and p revious chapters. Th~ 128 accessed using byte-type instructions. Y es are
~
i-
.., "2
25
iii
24
-
23 22 21 20 lF 18 17 10
7F 77 6F 67 SF 57
40 45 lD 35 20 25 10 15
7C 74 6C 64 SC 54 4C 44 3C 34 2C 24 lC 14
OF OE OD
oc
4P 47 31' 37 2F 27 lF 17
78 76 6E 66 SE 56 48 46 38 36 28 26 1£ 16
70 75 60 65 SD
ss
7A 79 78 72 71 70 61' 69 68 62 61 60 SA 52 4A 42 3A 32 2A 22 lA 12 OA
59 58 51 50 49 48 41 40 39 38 31 30 29 28 21 20 19 18 11 10 09 08
07 06 05 04 03 02 01 00
Bank3 S.nk 2
OF 08 07 00
?8 73 68 63 SB 53 48 43 38 33 28 23 18 13 OB
&nk 1
Default register bank for RO· R7
Figure s.1. 1611)1 both bit. •nd b 10$ of lnte"'al RAM. Notr. Th•y 1.e
Y e-o« O$Sibl•.
l'HEsos1 M:ICRocoNTRo LLER ANO EMBEDDED SYSTEMS
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 5-11
(c)CLR OFH
.
; c lear b it 0
Solution: · 28H of RAM locabon · (a} RAM bit address of 42H belongs to 02 f RAM location 2CH. (b) RAM bit address of 67H belongs to 07 of RAM location 21H. (c) RAM bit address of OFH belongs to 07 of RAM location 25H. (d) RAM bit address of 28H belongs to DOf ~M location 21H. (e) RAM bit address of 12 belongs to D4 of RAM location 20H. (f) RAM bit address of 05 belongs to D5 °
Table 5•2; Single-Bit Instructions Instruction SETB bit
Function Set the bit (bit = 1)
CLR bit
Clear the bit (bit= O)
CPL bit
Complement the bit (bit - NOT bit)
JB bit,target
Jump to target if bit = 1 (jump if bit)
JNB bit,target JBC bit,target
Jump to target if bit - 0 (jump if no bit) Jump to target if bit= l, clear bit (jump if bit, then clear)
2 Th 16 b tes of RAM locations 20 - 2PH also have bit addresses of 00 - 7FH since 16 x 8 = 128 (00 - 7FH). Tn order · e ythese u 8 bits of RAM locations and other bit-addressable space of 8051 individually, we can use ~nly th.e !:~~:~~t instructions such as SETB. Table 5-2 provides a list of single-bit instructio~. Notice t~at the s1~gle-b1t instructions use only one addressing mode and that is direct addressing mode. In the first two s~ch?ns of this ch~pter we showed various addressing modes of byte-addressable space of the 8051, among them mdIIect addressmg mode. It must be noted that there is no indirect addressing mode for single-bit instructions.
1/0 port bit addresses As we discussed in Chapter 4, the 8051 has four 8-bit 1/0 ports: PO, Pl, P2, and P3. We can access either the entire
8 bits or any single bit without altering the rest. When accessing a port in a single-bit manner, we use the syntax "SETB x. y" where X is the port number 0, 1, 2, or 3, and Y is the desired bit number from O to 7 for data bits DO to 07. See Figure 5-2. For example, "SETB Pl. 5" sets high bit 5 of port 1. Remember that DO is the LSB and 07 is the MSB. As we mentioned earlier in this chapter, every SPR register is assigned a byte address and ports PO • P3 are part of the SFR. For example, PO is assigned byte address 80H, and Pl has address of 90H as shown in Figure 5-2. While all of the SFR registers are byte-addressable some.of them are also bit-addressable. The PO - P3 are among this category of SFR registers. From Figure 5-2 we see that the bit addresses for PO are 80H to 87H, and for Pl are 90H to 97H, and so on. Notice that when code such as "SETB Pl. O" is assembled, it becomes "SETB 90H" since Pl.O has the RAM address of 90H. Also notice from Figures 5-1 and 5-2 that bit addresses 00 - 7FH belong to RAM byte addresses 20. 2FH, and bit addresses 80 - F7H belong to SFR of PO, TCON, Pl, SCON, P2, etc. The bit addresses for PO - P3 are shown in Table 5-3 and discussed next. '
Bit memory map From Figures 5-1 and 5-2 and Table 5-3 once again notice the following facts.
8051 ADDRESSING MODES
101
I . ed to RAM JocatioOS of The bit addresses 00 · 7FH are assign I. 20 • 2FH. eel to the PO port. 2 The bit addresses 80 • 87H are assign "'CON ....,,;,ter. FH ·gned to the • ..,,· 3 The bit addresses 88 • 8 are asst · · eel to the Pl port. 4. The bit addresses 90 • 97H are assign th SCON register. The bit addresses 98. 9FH are assigned to e :: The bit addresses AO. A7H are assigned to the P2.port.
Byto address FP
Bit oddn>SS
PO
F4 Pl F2 Fl F7 P6 PS
FO
B
&l EO
ACC
&O
E4 &l 62 67 E6 65
PSW
00
Dl D2 Dl DO D7 D6 DS D4
.. .. . .
BC BB BA B9 88
IP
88
82 Bl BO 87 86 BS 84 Bl
Pl
BO
AB
A8 AP •· .. AC AB AA A9
1E
A7 A6 A5 A4 AJ A2 Al AO
P2
12. The bit addresses 08 · DPH are not assigned. 13. The bit addresses EO - E7H are assigned to the Accumulator register. 14. The bit addresses E8 • EFH are not assigned. 15. The bit addresses FO · F7H are assigned to the B register.
AO
99
not bit"1ddressable
SBUP
98
9F 96 9D 9C 98 9A 99 98
SCON
90
97 96 95 94 93 92 91 90
Pl
Registers bit-addressability
8D
not bit~add.rcssabJe not bit...addre$Sable not bit..addressable
THl
The bit addresses A8. AFH are assigned to the IE register. ;. The bit addresses BO. 87H are assigned to the P3 port.
9. The bit addresses 88 • BFH are assigned to [P. 10. The bit addresses CO - CFH are not assigned. 11. The bit addresses DO • D7H are assigned to the PSW register.
8C
While all J/0 ports are bit-addressable, that is not the case with registers, as seen from Figure 5-1. Only registers A, B, PSW, IP, IE, ACC, SCON, and TCON are bit-addressable. Or the bit-addressable registers, we will concentrate on the familiar registers A, B, and PSW. The rest will be discussed in future chapters. Now let's see how we can use bit-addressability or registers such as A and PS~V. As we discussed in Chapter 2, in the PSW register two bits are set aside for the selection of the register banks. See Figure .>-3. Upon RESET, bank Ois selected. We can select any oti\er banks using the bit-addressability of the PSW as was shown in Chapter 2. The bit addressabilityof PSW also eliminates the need for instru~tionssuch asJOV Oump if OV=l). See Example 5-14. llxamme the next few examples of bit·addressabilty to gai better understanding of U,is important feature of the 80Sl. na
88 8A
THO TLl
TLO TMOD
88
not bit-addressable not bit-addressable BF 8E 80 SC es 8A 89 88
87
not bit-address.'lble
PCON
83
not bit-addressable
DPH
82
not bit·.:tddress.1ble not bit...addressable
DPL
81
SP
80
87 86 8$ 84 83 82 81 80
PO
89
TCON
SpedaJ Function Registers
Figure 5-i. S~ RAM Address
Table 5-3: Bit Addresses for All Ports PO
Addr
Pl
PO.O
Addr
80
P2
Pl.O
90 91 92 93
1'2.0 1'2.1 1'2.2
P0.1
81
Pl.I
P0.2
82
P!.2
P0.3
83
Pl.3
P0.4
Pl.4
PO.S
84 85
P!.S
95
P0.6
86
P!.6
P0.7
87
Pt.7
96 9'1
94
P2.3
1'2.4
P2.s 1'26
P2.7
Addr
AO Al A2 A3
A4 AS
A6 A7
P3
Ad dr
Port's Bil
P3.o
BO
DO
P3.1
Bl
01
P3.2
B2
D2 D3 D4
P3.3 P3.4
B3
P3.5
134 85
P3.6 P3.7
05
86
06
87
07
THl; 8051 MICRoc o
-
NTROLLER.
AND EMBEDDED SYSTEMS
AC
CY
RSl
FO
RSO
ov
p
--
Address
•
~Sl RSO "~!.__~~~~~~~~Reg~J~St~e~rB~a~nk~~-==========_QOH -07H
o o
o
1
1 0
1
1
O 1 2
08H -OFH 10H -17H 18H -1FH
3
. e 5-3· Bits of the PSW Register F1gur
Example 5-12 . h"ch ort the bit belongs. Use Table 5-3. (d) SETB QA7H For each of the following instructions, state t)o w IB ~2H (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 SETB MOV
PSW. 3 PSW .4 R7 ,A
Example 5-14
While there are instructions such as }NC and JC to check the carry flag bit (CY), there are no such instructions for the overflow flag bit (OV). How would you write code to check OV? Solution:
The OV flag is PSW.2 of the PSW register. PSW is a bit-addressable register; therefore, we can use the following instruction to check the OV flag.
JB PSW.2,TARGET
-
;jump if ov-1 -
-
8051 ADDRESSING MODES
103
Ex•mpl• S-15
en value.
.
Write a program to s« If the RAM location and then send It to P2. Solution:
37H contains an ev
If SO, sen
d it 10 P2. If not, make it even
. accumulator J?H 1nto ,. 1oad RAM 1ocat1on if 90 jump ;is DO of reg AO? ;it is odd, make ic even ,send it to P2 .
l'iOV A,37H
JNB ACC.0,YBS TNC A P2,A l'iOV YES:
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 JNB ACC.7,POS
PCS:
SETB Pl. 7 SJMP Nl>XT CLR Pl. 7
;move the content of RAM location 27H to A ;check the value of 07 of ACC. If it is set, the sign ;bic shows it to be a negative number ;because ic is a negative number, send a high to Pl. 7 ;exit the program ;the sign bit is not set, implies a positive number, ;send a low value to Pl.7 ;do nothing on exit
NEXT: NOP
END
,end of file
ExampleS-17
The status of bits Pl.2 and Pl.3 of l/0 port Pl must be sa the status of Pl.2 m bit location 06 and the status of Pl.J inv~
::i:~~!~
are changed. Write a program
tu....,
Solution: CLR
06
07 JNB Pl.2,0VER SETB 06 CLR
OVER:
JNB p 1.3,NBXT SBTB 07
NEXT: ...
;clear bit address 06 ;clear bit address 07 ;check bit Pl 2 1"f i · • O then · ; f Pl.2•1 set b" Jump . check b. • it location 06 to l ' lt Pl.) if O ;if Pl . Jal, set.bit then jump location 07 to l
Example S-18 \Vrite a program to ..ve lhe slatua of bit Pl 7
· 00 RAMad~
Solution: HOV C, Pl. 7
MOV 05,C
bit 05.
;get bit frOIII port ;save bit
104
T1iES0s1 Mi
CRocoN
TROLLER
-
ANO Et.lBEODED svsTEMS
Example S-19 Move the content of the 7th bit of the A register to pin P0.7, and also save it in RAM location 08H. Solution: MOV C,ACC.7 MOV P0.7,C MOV 08,C
;move the 7th bit of A register to carry ;put it on P0.7 ;move to RAM location OS(bit-addressable area)
Using BIT directive
~
The BIT directive is a widely used directive to assign the bit-addressable I/ 0 and ~ocati?ns. The B.IT directive allows a program to assign the I/ 0 or RAM bit at the beginning of the program, making 1t easier to modify them. Examine the next few examples to see how we use the BIT directive. Example 5-20 Assume that bit P2.3 is an input and represents the condition of an oven. If it goes high, it means that the oven is hot. Monitor the bit continuously. Whenever it goes high, send a low-tq-high pulse to port Pl.5 to tum on a buzzer. Solution: OVEN HOT BIT P2 . 3 BIT Pl . 5 BUZZER OVEN_HOT ,HERE JNB HERE: ACALL DELAY BUZZER CPL ACALL DELAY HERE SJMP
;keep monitoring for HOT
.
' the buzzer ;sound
.
I
~ 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 HERE: CPL LCALL SJMP
P.7 LED DELAY HERE
;using BIT directive ;toggle LED ;delay ;repeat forever
Example S-22 ~ switch is connected to pin Pl.7 and an LED t 0 . it to the pm P2.0. Write a program to get the status of the switch and send . LED.
Solution: SW BIT LED BIT HERE:
-
Pl.7
P2. 0 HOV C,SW MOV LED,C SJMP HERE
;assign bit ;assign bit ;get the bit f ;send the bit ~~t~he port ; repeat forever e port
-
---
-
-
-
-
80St ADDR ESSING MODES
105
Solution:
12H co carry bit 1ocacion ; copy . f is high ;check co see i of message ;yes, load addres~see Chap. 12) ;display message ;get out of No message ;load the address ,display it
PRONlllT BIT 12H HOV C, PHONll!T JNC NO MOV DPTR, #400H LCALL DISPLAY SJIIP EXIT MOV DPTR, #420H LCALL DISPLAY
NO:
;exit
EXIT:
•
• ·.
; ~~~~~~-data to be displayed on LCD
.'
ORG 400H YBS_MG: DB
·1
I
~New Messages•io
ORG 420H NO_MG:
OB
~No New MessagesN,0
Using EQU directive We can also use the EQU directivetoassignaddresses,as shown in the next few examples. Notice that in Example 5-24 the ports are de6ned by their names, while in Example 5-25, they are defined by their addresses.
Example S-24 The cost prices of 10 Items are stored in RAM locations starting from SOH onw rd Wh th I out as md JCa ted b y • 'h',gh' on• sw11 · ch th a s. en ese terns att , e cost price is replaced by the selling · b dd' of 19 to each value. This changed data is sent out through port 1 w·th d ..~nee Ya 1ng a constant 1 1 • program for this scenario. a e ay ""tween each data transfer. W
..;r
Solution:
JI..,~·
SW 1j> 11 l " - DAT
V
BACK:
NEXT :
EQO P0.1
EOU Pl
MOV
c,sw
JNC
NEXT
MOV
1U, #10
MOV MOV
RO,.SOH A,IIRO
ADD MOV MOV
A, #19
4DR0, A OAT,A
ACALL
DELAY
INC DJNZ NOP
RO Rl,BACK
END
;read awiteb value i awiteh value . n to the <;arry. bit. ,counter for numb is not high, e\cit the loop ;RO is the point er Of data items ,move the dat er to the data dd a to the A . ;a the profit " 1 register ;replace the a ue ,send value t~Ontent of RAM ;delay Pl 1 increment ,check if po1nter value ;On exit ~UnteraO ;end ot nothing Iif
i11.,
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
Pl
DAT
~
OUTPlIT DEVICE
v
P0.2 ACK Solution:
DAT-REQ ACK DAT BACK: SEND:
HERE:
po·' EQU 81H EQU 82H EQU 90H
po·r p o·
f
C,DAT·REQ JC BACK MOV Pl,A ACALL DELAY JB ACK, HERE SJMP BACK MOV
h k if there is a request for d~ta ;c T REQ line ·if ecnot low, monitor the DA~ '.move data to Pl if DAT-REQ is low '
;wait for 10 ms . received ·check if acknowledgment is ;if yes, await next request for data
Review Questions 1. True or false. All l/0 ports of the 8051 are ~it-addressable.
2. True or false. All registers of the 8051 are b1t-ad~essable. 3 T false. All RAM locations of the 8051 are bit-addressable.
· rue or b' dd bl 4. Indicate whlch of the following registers are 1t-a ressa e. (a) A (b) B (c) R4 (d) PSW (e) R7 5. Of the 128 bytes of RAM in the 8051, how many by~es ~re bit-addressable? List them. 6. How would you check to see whether bit DO of R3 is high or low? . 7. Find out to whlch byte each of the following bits belongs. Give the address of the RAM byte m hex. ( ) SETB 20 (b) CLR 32 (c) SETB 12H (d) SETB 95H (e) SETB OE6H 8. ~ e bit addresses 00 - 7FH belong to bit addresses 80 - F7H belong t o - - - - - - 9. True or false. PO, Pl, P2, and P3 are part of SFR. 10. True or false. Register ACC is bit-addressable.
SECTION 5.4: EXTRA 128-BYTE ON-CHIP RAM IN 8052 The 8052 rnicrocontroller is an enhanced version of the 8051. In recent years the 8052 has replaced the 8051 due to many of its new features. DS89C420/30 is an example of 8052 archltecttue. One of the new features of the 8052 is an extra 128 bytes of on-chip RAM space. In other words, the 8051 has only 128 bytes of on-chip RAM, while the 8052 has 256 bytes of it. To understand it, first let's recall the following two facts from earlier discussion in this chapter and Chapter 2.
1. The 8051 has 128 bytes of on-chlp RAM with addresses 00 - 7FH. They are used for (a) register banks (addresses 00- lFH), (b) bit-addressable RAM space (addresses 20 - 2FH), and (c) the scratch pad (addresses 30 - 7FH). 2.
-
~
Another 128 bytes of on-chip with add r~sses 80 - FFH are designated as Special Function Registers (SFRs). Again, the SFRs are accessed by drrect addressing mode as we saw earlier in this chapter.
8051 ADDRESS[NG MODES
107
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 f n-chip RAM with addresses 80. FFH
..,.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$ 5 to use two dillerent add~ing modes to access them as described next. 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 I
of the upper 128 bytes of RANI. ;load the upper memory address MOV R0,#90H ;put SSH into an address pointed to MOV CRO,#SSH ;by RO reg. shows how to a th arn e space shared between thcSFRand the upper 128 bytes of RAM in the 8052. Example 5-,, Figure 5-4 shows the p U 1 'cccss e upper 128 bytes of on-
FF
FF
Oin."d Access
Indirect Access (MOV@RO,A)
(MOV 90H,#55H)
1111 Upper RAM
Spt..--ci.\l Function Rcgist~r Only 80 7F
..
80
20 IF Accumu lator
•
Registers, 18
Program St,llus Word Stack Pointer ' ' Status ~ and Control Bits
Bank 3
17
Orts,
10
O.nk 2
Timers, Serial Control P , ower Control
OP
a
08
'
olh ers
Bank 1
, and
"' 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. 1 \Vrite a program for the 8052 to put SSH Lnto .....,...... -, I 'O
Solution:
ORG MOV MOV MOV MOV INC
BACK:
OJNZ
0
A,#SSH R2,#10 R0,#90H
·access the upper 128 bytes of ~use indirect addressing mode
@RO,A RO R2 , BACK
SJMP $ END
on-chip RAM
•
o>,v
~~~
;repeat for all locations ;stay here
·
h
y to see the result (See Figures 5-5 a nd
Run the above progra1n on your simulator and examu1e t e upper memor 5-6 for screen shots.) .
·
Exam ple 5-27
Assume that the on-chip ROM has a message. Write a program to copy it from code space into the upper memory space starting at address 80H. Also, as you place a byte in upper RAM, give a copy to PO. -
Solution:
Bl:
.:J / V
ORG MOV MOV CLR MOVC MOV MOV
0 DPTR, #MYDATA Rl,#SOH A A,@A+DPTR @Rl,A q# PO,A EXIT JZ INC DPTR INC Rl SJMP Bl ~ SJMP $ .........._,.'i
./
EXIT:
;------------
;access the upper 128 bytes of on-chip RAM ;copy from code ROM space ;store in upper RAM space ;give a copy to PO ;exit if last byte ;increment DPTR ;increment Rl ;repeat until the last byte ;stay here when finished
ORG 300H MYDATA: DB ~The Promise of World Peace",0 END
~\
,i ,,c-
Run the above program on your simulator and examine the
u pper memory to see the result.
Simulators and Data RAM space th AU the major 8051/52 simulators have ways of s how· h em. mg t e da ta RAM contents. Figures 5-5 and 5-6 show some of
-8051
ADDRESSING MODES
109
~,,
.,.
·~ I
ala uppeupace)
80: 00
ea: oo
90: 55 98: 55 o: 00 8: 00 80: 00 88: 00 CO: 00
ca: oo
DO: 00 D8: 00
EO: 00 E8: 00
FO: 00 F8: 00
•
00 00 oo 00 55 55 55 00 00 00 00 00 00 00 00 00 00 00 oo 00 00 00 00 00 00 00 00 00 00 00 00 00
uu. . . . . ..
~
. . • . . .. . . .... . . . . . . . .. .. ...... ... ... . . .. . . . . . ......• . ....... . . . .. ... . ......• . ..• ..... . . . . . . . . .:.I
"I
~·
~ J,= r,f
.~
r~ ,p
1¢
,..
00
a1ll
• Upper Memory for th• 8052 Figu.rt: 5-5. Fr.anklin S<>ftwatt's Pro View
\ll'.1:
l la
I'!'= E'I l'i
I : Ox80 00 I:Ox88 00 !:Ox90 55 I:Ox98 55 I:OxAO 00 !:OxA8 00 I:OxBO 00 I:OxB8 00 I:OxCO 00 !:Oxes oo I:OxDO 00 I:OxD8 00 l:OxEO 00 I:OxE8 00 I:OxFO 00 I:OxFB 00 > l:OxBO
00 00 55 55 00 00 00 00 00
00 00 55 00 00 00 00 00 00
00 00 55 00 00 00 00 00 00
00 00 55 00 00 00 00 00 00
00 00 55 00 00 00 00 00 00
00 00 55 00 00 00 00 00 00
00 00 55 00 00 00 00 00 00
1131
... . . . . . . . . .. . . . tJtJ ••••••
. . . . . .. . .. .. . . .. . ... . . . . ... . . . . . oo oo oo oo oo oo oo . . . . . . . . 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 00 00 . .. . . . . . 00 00 00 00 00 00 00 . .. . . . . . ... . . . .. . OxFF
••
•
• •t (\iiia,;),.==a9
... c.........
,,tiiii~.
'.
I lld[
•
l
Iii\
i ·~
111\ii
."1._
j~ l~
' !~ -~ ~~
figurt ~- Keil's µVision Upper Memory for the 805?
110
Tli£ 8051 l'YflCRO
CONTROLLER AND EMBEDDED SYSTEMS
Review Questions True or false. The 8052 is an upgraded version of the 8051. . .. l. True or false. The 8052 has a total of 256 bytes of on-chip RAM m addition to the SFRs. 2· True or false. The extra 128 bytes of RAM in the 8052 is physically the same RAM as the SFR. 3. 4. Give the address for the upper RAM of the 8052. . s. Show how to put value 99H into RAM location F6H of upper RAM m the 8052.
SUMMARY
This chapter described the five addressing modes of the 8051. Immed iate addressing mod_e uses a co1:5tant for ~e
source operand. Register addressing mode involves the use of registers to hold data to be marupulated._ Direct or re~ter indirect addressing modes can be used to access data stored in either RAM or registers of the 8051. Direct addressing mode is also used to manipulate the stack. Register inclirect addressing mode uses a register as a pointer to the d ata. The advantage of this is that it makes addressing dynamic rather than static. Indexed ad dressing mode is widely used in accessing data elements of look-up table entries located in the program ROM space of the 8051. A group of registers called the SFR (special function registers) can be accessed by their names or their addresses. We also discussed the bit-addressable ports, registers, and RAM locations and showed how to use single-bit instructions to access them directly.
•
PROBLEMS SECTIONS 5.1 AND 5.2 IMMEDIATE AND REGISTER ADDRESSING MODES/ ACCESSING MEMORY USING VARlOUS ADDRESSING MODES 1. What is the difference between the following two instructions performed? MOV MOV
in terms of addressing mode and function
A, #46H 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 te is code to .push RO Rl , and R3 of bank O onto 'th e stack and pop th ~ What th . h ' b ack into RS, R6, and R7 of bank 3 vfo. . e error m t e followu:ig instruction ? MOV A em 2 W~te a program to copy FFH into RAM locations 6 ' ®R · 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
!
~;r
Ai.
MYDATA:
DB
06,09,02,0S·,07
.
SECTION 5.3: BIT ADDRESSES FOR 1/ 0 ANO RAM 14· "SETB A" is a(n) 15. "CLR A". IS a(n) 16. "CPL A" . ( )
( . . vahd, invalid) ins truction ( lid . . va ' invalid) instruction 17 IS a n (valid invalid) · · · True or False? All the l/ O orts of' ~truction. 18. Are the registers TCON an! TMOD805 b·tl adrde bit-addressable. 1 -a ressable?
-
8051 ADDRESSING MODES
'
111
'
-bit addrllSses· cc D-1 bit of the A ~Vrite instnictions to perform the follo g (b) dear the D3 bit of pO (a) set the bit D
19.
20 . 21 22.
23. 24. 25. 26. 27. 28. 29.
30. 31. 32.
33. 34. JS. 36. 37. 38.
win actions using
A;
JB PSW. 6, HERE
39. 40. 41. 42.
43. 44. 45. 46. 47.
Show how you would check whether the P flag is high. Show how you would check whether the AC flag is high. Give the bit addresses assigned to the flag bit of CY, P, AC, and OV. Of the 128 bytes of RAM locations in the 8051, how many of them are also assigned a bit address as well? Indicate which bytes those are. Indicate the bit addresses assigned to RAM locatior,s 20H to 2FH. The byte addresses assigned to the I 28 bytes of RAM are t o - - -- The byte addresses assigned to the SFR are to . Indicate the bit addresses assigned to both of the following. ls there a gap between them? (a) RAM locations 20H to 2FH (b) SFR The following are bit addresses. Indicate where each one belongs
ro~
W~H ~47H ~ 18H 00 ~ 00 ~ (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 MOV 15H,C
Su ucaons?
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
-..
¢ il ' ,W], Rl, j
Xll!II
I L,r
i II
55. Write a program to show the use of the BIT directive: in the followin methods: 56. Write a program to set high all the bits of RAM locations 20H to 2FH us g g (a) byte addresses (b) bit addresses . . .. 57. Write a program to see whether the accumulator 1S div1S1ble by 8. 58. Write a program to find the number of zeros in register R2.
SECT10N 5.4: EXTRA 128-BYfE ON-CHIP RAM IN 8052 59. What is the total number of bytes of RAM in the 8052 including the SFR resi:'ters? Contras~ that with the 8051. 6(). The addressing mode used to access the SFRs of the 8052 is while for ad~ess1ng the upper 128 bytes of RAM, the addressing mode is used. 61. Write an example to show how the upper 128 bytes of 8052 are accessed. 62. Give the address range of the lower and the upper 128 bytes of RAM in the 8052. 63. In the 8052, the SFR shares the address space with the (lower, upper) 128 bytes of RAM.
64. In Question 63, discuss if they are physically the same memory. 65. Explain what is the difference between these two instructions. (a) MOV BOH, #99H
(b) MOV @RO, #99H if R0=80H
66. Write a program to load 10 bytes of data from locations 80H to locations starting at AO of the upper bank of the 8052.
67. Wr!te a program to put SSH into RAM locations CO- CFH of upper memory. 68. Wnte a program to copy the contents of lower RAM locations 60 - 6FH to upper RAM locations DO - DFH.
ANSWERS TO REVIEW QUESTIONS SECTION 5.1: IMMEDIATE AND REGISTER ADDRESSING MODES 1. No 2. MOV R3,#10000000B 3. Source and destination registers' sizes do not match.
4. True 5.
No
SECTION 5.2: ACCESSING MEMORY USING VARIOUS ADDRESSING MODES 1. Direct; because there is no "#" sign 2. 02
3. 12H 4. EOH 5. RO and Rl
SECTION 5.3: BIT ADDRESSES FOR 1/0 AND RAM 1. True
2. False 3. False 4. A, 8, and PSW
!:
~6,t~'~e bit-addressable; they are from byte location 20H to 2FH.
JNBACC.O 7· For (a), (b), and (c) use Figure 5-1. (a) RAM byte 22H, bit D4 (b) RAM byte 24H, bit DO (c) RAM byte 22H, bit D2
~diy~d ~ u;O Figure .5-2. (d) SEIB Pl.5 (e) SETS
8. 9. True
es
-
H, special function registers.
ACC 6 .
10. True
-
8051 ADDRESSING MODES
113
'
HIP RAM SEcn ON 5.4: EXTRA 128-BYTE ON-C I. True 2. True 3 False 4 · 80-FFH
1NSOS2
/
. MOY A,#99H 5. MOY RO,#OF6H MOY@RO,A
/
114
CHAPTER6
ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS
OBJECTIVES Upon completion of this chapter, you will be able to: Define the range of numbers possible in 8051 unsigned data Code addition and subtraction instructions for unsigned data Perform addition of BCD data Code 8051 unsigned data multiplication and division instructions Code 8051 Assembly language logic instructions AND, OR, and EX-OR Use 8051 logic instructions for bit manipulation Use compare and jump instructions for program control Code 8051 rotate instruction and data serialization Explain the BCD (binary coded decimal) system of data representation Contrast and compare packed and unpacked BCD data Code 8051 programs for ASCII and BCD data conversion Code 8051 programs to create and test the checksum byte
115
'
<'iven to illustrate the application amples are o· b cti. I. . . tntction,. Program e~ to addition, su tra on, mu hphc;a. n,,,, ,11.,pter de<,er1bes all SOS1 arithmetic and 1oi;1c ,ns . and programs relat~ 2 In 5ection 6.3, we discuss the logi( 1100 Q( th,,'St' instructions. In Section 6.1 we d'.5"uss tns~tio: discussed in Se<: ·n51ruction and data serialization 11on, and dh ision or unsigned numbers. Signed ni;; w1RE instrUction. R~TA ~ as BCD and ASCH conversion ,n,tructions ANO, OR. and XOR. as well as the C . IV re 1.,vorld appUcattons su MC discussed in Section 6.4. In Section 6.5 we provide some a aml chcck>um byte testing.
·TE
n,c.
SECTION 6.1: ARITHMETIC INSTRUCTIONS . - a nd nobitsaresetasideforth sed to represent d•~·, . e U"'igned numbers are defined as data in ,vhichall the b,tsare u d FfH (0 to 255 decimal) for 8-bit data. 00 pos,ti,·e or negative sign. This means that the operand can be between an Addition of unsigned numbers · (A) ust be involved. The form of the ADD In the 8051, in order to add numbers together, the accumulator register rn instruction is ADO A, source
;A
=-
+ s ource
A
The instruction ADD is used to add two operands. The destination operand is always in regi~ter A ~hile the source operand can be a register, immediate data, or in memory. Remember that memory-to-memory arithmetic operations are ne,·er aUowed in 8051 Assembly language. The insi-ruction could change any of the AF, CF, or P bits of the flag register,
d_e~dmg on the ~J)\.>rnnds involved. The effect o( the AOD instn,ction on the overAow flag is discussed in Section 6J smce 11 ,s used mamly m s,gned number operations. Look at Example 6-1.
Addition of individual bytes mu~f~:r.~ ~~;,t:;:~t:::!~o~d~(~ ;~:~d 5•bytes of data. The sum was purposely kept less than FFH, the maxi· after the addition of efch operand. E~ample _;t:: :~; of any numlber o( operands, the carry flag shou Id be checked o accumu ate carries as the operands are added t 0 A 6
'
,
'
•
.
Ex.unple 6-1 Two numbers are stored in registers RO and--. RI .Verify if th eir . sum . .,s greater than FFH Solution:
· HOV
MESSAGE: NEXT:
..,
A,RO ADD A,Rl" JC M&SSAG8 SJMP N&XT MOV 1\, #'Y' MOV Pl,A NOP ENO
;move first number to A ,add second number to it . ;if sum>FPH, cv.1 ;if CY•O, exit ;if CYcl,move 'Y' into A ;send the message • y'
;do nothing ;end of file
•
through Pl
/
Exa mple 6-2
Assume that RAM locations 40 -44 have
116
THE 8051 MICRocoNl" ROLL ER AN
-
D EMBEDDED SYSTEMS
'
42= (CS) 43=(5B)
'
44:: (30)
Solution:
AGAIN: NEXT:
MOV MOV CLR MOV ADD JNC INC INC DJNZ
R0,#40H R2,#5 A<>• R7,A ~ ...., A,@RO NEXT
R7 RO R2,AGAIN
;load pointer ;load counter ;A=O ;clear R7 ;add the byte pointer to A by RO ;if CY=O don't accumulate carry ;keep track of carries ;increment pointer ;repeat until R2 is zero
Analysis of Example 6-2 Three iterations of the loop are shown below. Tracing of the program is left to the reader as an exercise. 1.
In the first iteration of the loop, 7DH is added to A with CY= 0 and R7 = 00, and the counter R2 = 04.
2.
In the second iteration of the loop, EBH is added to A, which results in A = 68H and CY= 1. Since a carry occurred, R7 is incremented. Now the counter R2 = 03. 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.
3.
At the end when the loop is finished, the sum is held by registers A and R7, where A has the low byte and R7 has the high byte.
ADDC and addition of 16-bit numbers When a~ding two 16-b~t data ~perands, we need to be concerned with the propagation of a carry from the lower ~yte to the higher byte. The instruction ADDC (add with carry) is used on such occasions. For example look at the addition of 3CE7H + 3B8DH, as shown below. ' l
3C E7 +
38 SD
78 74
When the first byte is added (E7 + BD = 74, CY= 1). The carr is ro . 3B + 1 = 78 (all in hex). Example 6-3 shows the above steps in y ~ pa gated to the higher byte, which results in 3C + / an 80 1 program.
Example6-3 .
Write programs to
(a) add two 16-bit numbers, the numbers are ~ 4SH and 0.,,cirt__y (b) add two 32-bit numbers stored in RAM locations :,:::::1
-
.
.
..
'
.
A.R.ITliMETIC,LOCIClNSTRUCl10NNs,S~A~N~D~;;RO~;;:~;--~~~~~~--,~~~~~~~~--, GRAMS 117
' Solution:
(al
CLR
,make cv~o into A '.1oad the lo" byte no" A•J1,CY=l '.add the 10w byte, f sum in RO • byte o -save the low in•o A ' · b byte • 1 -load the h 9 ith carr/ '.add the high bytes w ' ·02+FCH+l•FFH of result in Rl ',save the h19 · h byte
C
MOV
A,1!4SH ADD A,#OECH MOV RO.A MOV A,#02H ADOC A, #OFCH MOV
Rl,A
,,,. ~~
Fin.i.Uy, we gel the result as R0"31H and R!=FFH-
(bl ed in RAM locations as shown below. Let the 32-bil numbers be Ol453BC0H and 56C705FEH and let them be stor
40H
Data COH
41H
3BH
Addresses
42H
45H
OH
01H
Addresses
SOH SIH
52H 53H
Data FEH 05H C7H 56H
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. CLR
C
,clear CY Qag
MOV MOV MOV
R2,#04H RO, #40H Rl, #SOH
;move into R2 the number of bytes in each number ;RO points to the low byte of the first number ;Rl points to the low byte of the second number
;switch to bank 1 ; use RO of bank l as pointer to the result ;return to bank o ;bring one byte of the first . 1 add one byte of th number 1nt.o A
SETB PSW. 3
MOV BACK:
RO, #60H
CLR
PSW.3
MOV
A,liRO A,liRl RO
ADDC
INC INC
;increment the po· e second number to it . inter of the fl mb ; increment the poi t rat nu er ;switch to bank 1 n er of the second number
Rl
SETS PSW . 3
MOV INC
IIRO,A RO
; store one byte of t~h store one byte of the sum ;increment the poi
CLR PSW . 3 DJNZ R2, BACK
;return to bank o nter of the result. location ;repeat until all f our bytes have been added
The result of the addition will be stored in RAM as
118
e sum
Add~
Dahl
60H
BEH
61H
41H
62H
OCH
63H
S8H
""
,#~
(lid'
t»lllll if .i;
!.ldl
111illl i.L.
,.-,
al1lrl
-
p!II
Digit
eco (binary coded decimal) number system . . . eeded because in everyday life we use
0 l
BCD stands for binary coded de_cimal. BCD is n bers Binary representation of O to 9 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 numbers, (1) unpacked BCD, and (2) packed BCD. We descri e ea ·
2 3 4
5
In unpacked BCD the lower 4 bits of the number represent the BCD number, and th~ rest of the bits are O. F~r example, "0000 1001" and "0000 0101" are ~pa~ked BCD f~r;: 5, respectively. Unpacked BCD requires 1 byte of memory or an 8-b1t regJ.Ster to con a ·
0000 0001 0010 0011 0100 0101
7
0110 0111
8
1000
9
1001
6
Unpacked BCD
BCD
Figure 6-1. BCD Code
Packed BCD
~:s~~
In packed BCD, a single byte has two BCD numbers in it, one in the lower 4 bits, and one in the upper 4 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 f ll . ms rue 1n will clarify these points. , ne. e o owing examp e
Th
MOV MOV ADD DA
A, #47H B,#2SH A,B A
;A=47H first BCD operand ;B=25 second BCD operand ;hex(binary) addition (A=6CH) ;adjust for BCD addition (A=72H)
0
After the program is executed, register A will contain 72H (47 + 25 _ 72 11 11 • • other words, while the source can be an operand of any addressin mod )- The .DA_ instructio~ wor~ only on A. In for DA to work. It also needs to be emphasized that DA m t b g e, the destination must be in register A in order us e used after th ddi · f operands can never have any digit greater than 9. In other words _ . ~a h on o BCD operands and that BCD note that DA works only after an ADD instruction· it will n t k' A F digits are n ot allowed. It is also imp ortant to , o wor after the INC instruction.
Summary of DA action After an ADD or ADOC instruction,
1. If the lower nibble (4 bits) is greater than 9, or if AC_ 1 2. If the upper nibble is greater than 9, or if CY= 1 ad; ' add 0110 to the lower 4 bits. _ , 0110 to the up per 4 bits. IJUTHMETIC, LOGIC INSTRUcnONS, AND PROGRAMS
119
' si,own be1o
Y.'
.
write a program lo
at 40H, as •- • star!Ulg . RA,\;l locallv•D dara 1trois are stored in t,e 1n BCDA>sume that 5 BC mbers The result must find the sum of all the nu . , • Eumple...,
40= (71) 41• (11)
42• (65) 43.(59 ) 44• (37)
Solution:
AGAIN:
NEXT:
MOV MOV
RO, ~40H R2, #5
CLR
A
MOV ADD DA JNC
R7,A A,IJRO A NEXT
tNC
R7
INC
RO
,load pointer ·load counter •
·A•O ;' clear R7 . nter to A by RO . add the byte poi
' BCD ;adjust fodr ' t accumulate carry ·if CY•O
on
.
;keep track o~ carries ·increment pointer •;repeat unt1·1 R2 is zero
DJNZ R2, AGAIN
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 18 41 6 47
0010 0001 0100
+
+ 0100
1001 1000 0001 0110 0111
AC=l
Since AC= 1 after ~,e addition, "DA A" will add 6 to the lower nibble. The final result is in BCD format.
Subtraction of unsi gned numbers SUBB A, source
;A= A - sou~ce - CY
In many microprocessors there are two different instructions for subtraction: SUB and SUBB (subtract with bor· row). In the 8051 we have only SUB6. To make SUB out of_SUBB, ':"e have to make CY: o prior to the execution of the instruction. Therefore, thel'\1 ru:e two cases for _the SUBB mstruc_tion: (1) with CY o, and (2) with CY 1. Fi.r.;t we examine the case where CY= 0 paor to the execution ofSUBB. Notice that we use the CY flag for the borrow.
=
=
SUBB (subtract with borrow) when CY= O tn subtraction, the 8051 microprocessors (indeed, all modern CPUs)
ta;:se
th
,
.i.
every CPU contains adder circuitry, it would be too cumbersome (and e 2 s complement method. AlthOUb·· subtracter circuitry. For this reason, the 8051 uses adder circu.itry to per( e~oo many transistors) to design sepat•lt the 8051 is executing a simple subtract instruction and that CY,. prior e subtraction command. Assurning th,lt 0 1 marize the steps of the hardw°"' of the CPU in executing the SUBB inst th~ execution of the instruction, one can surn·
:nn
1. 2. 3.
Take the 2's complement of the subtrahend (source operand). Add It to the minuend (A). Invert the carry.
ruct1on for unsigned n umbers, as follows.
120
Tl-rE 80s1 MlCRoco
-
N"rROLLER. ANO EMBEDDED 5ys,vfS
Example 6-5
Sho\\l the steps involved in the following. I
:
CLR
;make CY=O ;load 3FH into A (A= 3FH) ;load 23H into R3 (R3 = 23H) ;subtract A - R3, place result in A
C
113FH R3,#23H SUBB A,R3
MOV MOV
A,
Solution:
A R3
0011 1111 0010 0011
3F = 23
=
lC
0011 1111 1101 1101 0001 1100
+ 1
(2's complement)
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 instructions can be used to change it. The CPL instruction performs the l's complement of the operand; then the operand is incremented (INC) to get the 2's complement. See Example 6-6.
SUBS (subtract with borrow) when CY= 1 This instruction is used for multibyte numbers and will take care of the borrow of the lower operand If CY= 1 · t tin th SUBB . . . a1s . prior o execu g e mstruction, 1t o subtracts 1 from the result. See Example 6-7.
Example 6-6
Analyze the following program: CLR
C
A,#4CH SUBB A,#6EH
MOV
JNC CPL INC
NEXT A A
NEXT:MOV
Rl,A
;load A with value 4 CH (A=4 CH ) ;subtract 6E from A ;~f CYaO jump to NEXT target ;1f ~=l then take l's complement ;and increment to get 2 , 8 ;save A in Rl complement
Solution: Following are the steps for "SUBB A, #6EH": 4C
0100 1100 0110 1110
0100 1100
2's comp. 1001 0010 0 1101 1110 CY "' l, the result is negative, in 2, s c01uple11e12t.
-6E 22
.
.. .
-ARlTHMETIC,LOGICINSTRUCflONS·A~;NND~~~~~;---,..~~~~~....,....~~~.......~~,......·~---,,
.
OGRAMS
121
•
' Wmp1•~7
Analyze the following program:
·CY• o
CLR
C
'
MOV SOBB MOV MOV SUBB MOV
A,.62H A,#96H R7,A
;A• 62119611 CCII with CY • l • 62H s ' he result
A.~2711 A,#l2H R6,A
;A•27H • 1411 ;27H - 12H - l ;save the result
,save
t
. 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
UNSIGNED MULTl PLICATION AND DIVISION
,,~
.
dB - required since the multiplication . th 8051 the use of reglsters A an ,5 In multiplying or dividing two numbers an e '. W first discuss multiplication. and di,•ision instructions work only with these two registers. e
re
.:, ,
i::-;.,
,.,.,.
Ellli'' Multiplication of unsigned numbers
.
The 8051 supports byte-by-byte multiplication only. The bytes are assumed to be unsigned data. The syntax IS as follows: MUL AB
;Ax B, place 16-bit result in Band A
In byte-by-byte multiplication, one of the operands must be in register A, and the second operand must be in regis·
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 MOV B,~6SH
•
MUL
AB
;load 25H to reg. A ;load 65H in reg. B ;2SH • 65H • E99 where
; B
=
OEH and A• 99H
Division of unsigned numbers In the division of unsigned numbers the 8051 supports byt
'
DIV AB
b e over yte only. The syntax is as follows.
;divide A by B
When dividing n byte by a byte, the numerator must be · • DIV instruction is performed, the quotient is in A and th tn ~egtster A and the denominate b e remamder is in B. See th ( . r must e · e oUowmg example.
Table 6-1: Unsigned Multi Multiplication byte• byte
Operand1 A
in
f .~. B. A ter u~
lication Summary (MlJL Operand 2 8
R.esult
AB)
Notr Mulbpbc.,llon of operands largo, than A" low byte B h' h e>-ptnmtnt with 8 bits talc-."'""' ma . ' - •g byte rupulau.on. It is lt'ft lo the d S"('il
er to
122
THE 8051 MICROcoN
TR.OttER.
-
AND EMBEDDED svs-ratS
.-.
llli
Table 6-2: Unsigned Division Summary (DIV Division
Numerator
byte I byte
A
Remainder
Quotient
B
A
B
=1 indicating an error)
{If B = 0, then OV
MOV A, #95 MOV B, #10 DIV AB
Denominator
AB)
;load 95 into A ;load 10 into B ;now A = 09 (quot i ent) and ;B - OS(remainderl
Notice the following points for instruction "DIV AB". 1. This instniction always makes CY = Oand OV == O if the denominator is not 0. 2. If the denominator is O(B = 0), OV = 1 ind icates an error, and CY= 0. The stan d ard practice in a ll rnicrop0r~c~sso~s when dividing a number by Ois to ind icate in some way the invalid result of infinity. In the 8051, the ag is set to 1.
An application for DIV instructions There are times when an ADC (analog-to-digital converter) is connected to a port and the A DC represents som e quantity such as temperature or pressure. The 8-bit ADC provides da ta in hex in th e range of 00 - FFH . This h ex data must be converted to decimal. We do that by dividing it by 10 rep eatedly, saving the remainde rs as sh own in Example 6-8. /
Example 6-8
In a semester, a ~tudent has to take six courses. The marks of the student (out of 25) are stored in RAM locations 47H onwards. Fmd the average marks, and output it on port 1. Solution:
MOV MOV MOV MOV BACK:
ADD
Rl ,#06 B,#06 R0,#47H A,#0 A, @RO
;Rl stores the number of courses ;only B can be used as the divisor register ;RO acts as the pointer to the data ;clear A ;a~d the data to the A register ;~ince each number is less than 25 CY:O ;increment the pointer ;r~p~at addition until Rl =O ;divide the sum by 6 to get th . the t· e average '. quo ient is in A, remainder in B ;ignore the rem· aind er, output the average I
I NC RO DJNZ Rl BACK . ,µ.S DIV AB ""'-t,,ft ~ ~""I I
MOV
Example6-9
Pl,A
- - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-
Convert a hexadecimal number to decimal. Method
is.:
For example, let the hex number be 9CH whoee d ~he _m_e thod is to divide by 10 until the quotient ,v,ding by 10 twice will be enough.
.
equivalent ia 156. To convert it to a decimal IO. In the case of a hex number between 00 and number, FFH,
.A.R.ITHMETIC, LOGIC INSTRUCTIONS ANO , PROGRAMS
123
'
rder c:ilgi t lowest o . . erwilJbethe 'ddledig,t . 6(retnainder}-dus rernaiJ'dder will be the lfl~gJi digit. 9C/OA~F(quobent), - ,emajnder}-~ re,naJ1I 10) will be the F/ OA~l(quollent), :,( 11·ent which ,stessthan l(quo • · thus 156. The Deomal equi,-..lent lS n,ber is loaded into A ·the hex nu r into B HOV A, ij9CH ;move the divisonumber by 10 it to RO HOV B, #OA!! ;divide the hex is in B, move DIV AB ; the remaindde: 1· sor into B MOV RO,B l d the lV 10 HOV B, #OA!! ;re oa h quot i·ent by ;divide t e inder to Rl DIV AB •move the rema . ent to R2 MOV Rl, B '."'°ve the last quot1 . 't MOV R2 , A ' . holding the lowest dig• · . . R2 RI and RO w,th RO The decimal number as now t.n , '
Solution:
Review Questions
. . of two bytes .ITT the 8051, we must p Iace 1 In multiplication
one byte in register_.;,_ A _ __ and the other in register •
( )
. ulti lication, the product will be placed in register s - - - - . . 2. In unsigned byte-by-byte":' 1 ~MOL A, Rl". Explain your a~wcr. and the denominator m regtslt'r 3. Is this a valid 8051 instruction. t ust be placed in register--4.. In byte/byte division, the numera or m .
5. In unsigned byte/byte division, the quotient will be placed in register
- - - - and the remainder in regislt'r
your answer. 6 .,--:-:---;:-· Is this• valid 8051 instruction.>"DIV A' Rl" . Explain . A. 7. Th . truction "ADD A, source" places the sum m --=---· . e,ns . . ill~? '• 8. Why is the following ADD ,nstru~ in•" .J "ADD Rl, R2"
f''rtS"'1•T
r1t •
"J.<..
"""'°c:,,' -.
9. Rewrite the instruction above in con;;ct form. ,. i,
. I
r, •,
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. . 13 . subtraction? If CY= 1, A= 95H, and B
~ 4FH prior to the execution of
" SUBS A,
B", what
will be the contents of A after the
SECTION 6.2: SIGNED NUMBER CONCEPTS AND ARITHMETIC OPERATIONS All data items us«! so.far have~ unsigned nurn~ers, m_eaning that the entire 8-bit operand was used for the
magnitude. Many applicalfuons reqwrlie st1gnedddata.t~ this S~tion the concept of signed numbers is discussed along with related instructions. your app ca ions o no mvo1ve signed numbers you c b h' . , an ypass t IS Section.
Concept of signed numbers In computers In everyday life, numbers are used that could be positive or negati F below zero can be represented as -5, and 20 degrees above zero as + Cve. or example, a temperature of 5 degrees 20 omputers rnust be able to accommodate such numbers. To do that, computer scientists h;,ve devised the following,.,.; live and negative numbers: The most significant bit (MSB) is set aside t:'~ernent for the representation of signed po5'"
124
r
e s,gn (+ or-), whiJe the rest of the bits ate
Tit£ 8051 MICR.oc ON'fR.OLLER. AND EMBEDDED SYSTEMS
used for the magnitude. The sign is repres~ted by O for positive_(+) numbers and 1 for negative(-) numbers. Signed byte representation is discussed below.
magnitude
sign
I I
Signed 8-bit operands In signed byte operands, 07 (MSB) is the sign and DO to 06 ai:e set aside for the magnitude of the number. If 07 = 0, the operand 1s positive, and if 07 = 1, it is negative.
Figure 6-2. 8-Bit Signed Operand
Positive numbers
+1
0000 0000 0000 0001
The range of positive numbers that can be represented by the format shown in Figur~ 6-2 is Oto+127. lf a positive number is larger than+127, a 16-bit size operand must be used. Smee the 8051 does not support 16-bit da ta, we .,.,riJ.l not discuss it.
+5
0000 0101
+127
0111 1111
0
...
. ..
Negative numbers For negative numbers, 07 is 1; however, the magnitude is represented in its 2's complement. Although the assembler does the conversion, it is still important to understand how the conversion works. To convert to negative number representation (2's complement), follow these steps. 1.
Write the magnitude of the number in 8-bit binary (no sign).
2.
Invert each bit. Add 1 to it.
3.
Examples 6-10, 6-11, and 6-12 de1nonstrate these three steps.
Example 6-10 Show how the following numbers are represented in the 8051 (a) - 7 {b)-56 (c)-128 (d) O
Solution: In th~ 8051, negative numbers are represented in 2's com !em . . negahve number in 2's complement form are p ent form. The steps involved m rep resenting a (1) write the number in binary form (2) complement each bit (3) add 1
These steps an · are carried· out for the conversion of each of the four numbers It · · 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) (2} (3) (4 )
0000 0111 1111 1000 1111 1001 F9H
;representation i n hex
(b) -56 ( 1) (2) (3) (4)
0011 1000 1100 0111 1100 1000 CBH
Ii
I:
; repr esent at i on in hex
'
-
!
~ _...
.. •
-
ARITHMETIC, LOGIC INSTRUCTIONS AND .;~~------------------' PROGRAMS
125
'
(
(c)
- 128 (I) (2) (3) (4)
1000 0000 0111 1111 1000 0000 80H
. n in he" ,representat10
ti
{d) 0
/
(1) 0000 0000
(2) 1111 1111
,,ii
(3) 0000 0000
...,j.. ... .,.·!
. in hex ;representation
(4) OH
•' •
..
Example 6-11
I
Show how the 8051 does the following calculations (a) add +37 and-115 (b) add -13 and -78
... ..
-~..
Solution: .37
(a)
-115 --78 -
(bJ
- 43 +
-78 --121-
+
00 1 0 010 1 1000 1101 1011 0010
1 101 0101 + 1011 0010 11000 0111
• B2H
,the result is 1000 0111 = 87H (as c arry is to be ignored)
Example 6-12
Show how lhe 8051 would do lhe following calculations (a) subtract - 27 from +68 (b) s ubtract -78 from -43 Solution: (a)
+6 8 in bi nary i s 01 0 0 010 0
-27 in 2 ' s complement f o rm i s 1110 0101 Since !he operation is subtraction, lhe805J sends-27 to a 2's com I . . traction means adding the 2's complement number, P ement Circuit to Produce 0001 1011. Since sub0100 0100 + 0001 1011 01 0 1 1111
(b)
•
SFH •
+95
· 43 in 2'complement fora, is 1101 -78 in 2'complel88nt form ia 1011 0101 0010
. 126
it to produce 0100 1110. Since . . s -78 to a 2's complemen t c1rcu ce the operation is subtraction, the 8051 send ::traction means adding the 2's complement n umber, 1101 0101 + 0100 1110 10010 0011
= 0010
0011
= 23H = + 35
. b . _ 1 to -128. The following lists . . f b t - ized negative num ers tS From the examples above 1t 1s clear that the range o Y e s byte-sized signed number ranges:
Decimal
Bin ary
Hex
-128 -127 -126
80 81 82
-2 -1 0 +l +2
1000 0000 1000 0001 1000 0010 . . . . . .. . . 1111 1110 1111 1111 0000 0000 0000 0001 0000 0010
.........
..
+127
0111 1111
7F
. ..
.. FE
FF 00 01 02
The above explains the mystery behind the relative address of - 128 to+127 in the short jump discussed in Chapter 3.
Overflow problem in signed number operations When using signed numbers, a serious problem arises that must be dealt with. Thls is the overflow problem. The
8051 indicates the existence of an error by raising the OV (overflow) flag, but it is up to the programmer to take care of the erroneous result. The CPU understands only Os and ls and ignores the human convention of positive and negative numbers. What is an overflow? If the result of an operation on signed numbers is too large for the register, an overflow has occurred and the programmer must be notified. Look at Example 6-13. In Example 6-13, +96 is added to +70 and the result according to the CPU was-90. Why? The reason is that the resul t was larger than what A could contain. Like all other 8-bit registers, A could only contain up to +127. The designers of
Example 6-13 Examine the following code and analyze the result. MOV MOV
ADD
A, #+96
Rl,#+70 A, Rl
;A= 0110 0000 (A
6 0H) ;Rl = 0100 0110 (Rl • 46H) ; A • 1010 0110 ;A= A6H • - 9 0 d e cimal , I NVALI D!
Solution: +96 + +70 + 166
0110 0000 QlOO 01 10 1010 0110
a
"a.,,
6 t,+Jl l1~-r l 1t.-,o
and
ov-1
According to the C PU, the result is -90, wbidt ii wrong
·
The CPU
-
lela OV • 1 to wiic:ate the 09eluw. -
ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS
U7
'
anuner that the result of thesjo,,., of infornili'S t),e progr .,...., the CPU created the overflow £lag specifically /or the purpose number operation is erroneous. When is the OV flag set? In S-b1t signed number operations, OV is set to
I ·f ' ther of the I
fOU0 wing two conditions occurs:
ei
0 There is a carry from 06 to 07 but no carry out of 07 (CY " >·0 7 , from 06 to · 2. There is a carry from 07 out (CY= I) but no carr) . · f 06 to 07 or from 07 out' but . not both· This means In other words, the overllow flag is set to 1 ifthere IS a carry rom E ample 6-13, since there 1s only a carry from 06 that if there is a carry both from 06 to 07 and from D7 out, OV "O. In ; 6_16 to w,derstand the overflow flag in signed 0 to 07 and no carry from D7 oul, OV =\.Study Examples 6-14, 6-15, a arithmetic. l.
Example 6-14 Observe the followmg, noting the role of the OV flag. MOV A, #-128 MOV R4, #-2 ADD A, R4
;A = 1000 0000 (A = 80H) ;R4 • 1111 1110 {R4 = FEH) ;A • 0111 1110 (A • 7EH • +126, invalid)
Solution:
•
-128 -2 -130
1000 0000 1111 1110 0111 1110
and OV•l
According to the CPU, the resu.lt is+ 126, which is wrong (OV = 1).
Example 6-15 Observe the following, noting the OV flag. MOV MOV ADD
A,#-2 Rl, #-5 A,Rl
;A•llll 1110 (A•FEH) ;Rl• llll 1011 (Rl=FBH) ;A•llll 1001 (A=F9H= -7 corre t ' C ,OV=O)
Solution:
•
-2 -5 -7
1111 1110 1111 1011 1111 1001
and ov = 0 According to the CPU, the result is -7 which .
'
•s correct (OV _ O).
EumPIt 6-16 Examine the following, noting the roleofOV MOV A, #+7 MOV ADD
128
IU,#•18 A,Rl
' ;A•OOOO 0111 (A•07u ;Rl•OOOl 0010 (R q) ;A•OOOl 1001 IA 1•12!!)
•l9ff•+2s
'
THE sos
Solution: 7
+
18
25
0000 0111 0001 00 1 0 0001 1001
and
ov '"
O
According to the CPU, this is +25, which is correct (OV
=O)
From the above examples we conclude that in any signed number addition, OV indicates_ whether ~e re~ult is valid or not. If OV = 1, the result is erroneous; if OV = O, the result is valid. We can state emphattcally that m unsigned number addition we must monitor the status of CY (carry flag), and in signed number addition, the OV (overflow) flag must be monitored by the programmer. In the 8051, instructions such as JNC and JC allow the program to branch right after the addition of unsigned numbers, as we saw in Section 6.1. There is no such instruction for the OV flag. However, this can be achieved by "JB PSW. 2" or "JNB PSW. 2" since PSW, the flag register, is a bit-addressable register. This is discussed later in this chapter.
Instructions to create 2's complement The 8051 does not have a special instruction to make the 2's complement of a number. To do that we can use the CPL (complement) instruction and ADD, as shown next. '
CPL A ADD A, #1
;l's complement (Invert ) ;add 1 to make 2's complement
Review Questions 1.
2. 3. 4. 5.
In an 8-bit operand, bit is used for the sign bit. Convert-16H to its 2's complement representation. The range of byte-sized signed operands is to + Show +9 and -9 in binary. - -- ---Explain the difference between a carry and an overflow.
SECTION 6.3: LOGIC AND COMPARE INSTRUCTIONS _Apart from I/0 and arithmetic instructions, lo ·c instru . sethction we cover Boolean logic instructions such as ~ ORctions l ~re some of m ost widely used instru ctions In thi e compare instruction . , ' exc us1ve-or (XOR), and complem en t · W e will . also . s tudys Logical AND Function
AND
Inputs
ANL destination, source
; dest
= dest
hu,-, =•u source
This instruction will perform a looical AND h result in the d es tin . o· ontht e two op erand s an d place the and a tion. Th e destination is normally · • e accumulat add can. be a rP<>ic;t --o- er, m memory, or un.mediate. See A . or. The source operno er;:5smg modes for this instruction. The ANL instructippe;d1x A.l for more on the bits O~no;i;rn~.~fi:!:~1:i:
-
~ instruction is often ~:e~~:::~~~:e~; ~~a;'C~~i:
ARITHMETIC, LOGIC INSTRUCTIONS AND ' PROGRAMS
-
Output
X
y
0 0
0
1
0
0 0 0
l
1
1
X
y
1
XANDY
...__,, - XANDY
-
129
'
' v'Ex•mpl• 6-17 Show the results of the following. ;As )SH
HOV A, R35H
A ;A • A AND OFH (now
ANL A, #OFH
s
05)
Solution: 35H
OFH OSH
0011 0101 0000 1111 0000 0101
)SH AND OFH
• OSH Logical OR Function
OR ORL dest i nation, source;dest •
dest OR source Red and the result is placed ·tn the
The destination and source operands arc O • . b' ts of"'' operand to 1. . . b used to set certatn • can be a register, . .tn destination The ORL mstruct1on can • and · I to The source oper, The destination is normally the accumu a r. h dd •ssing modes supported . . "-· A dix A for more on I ea « has no effect on any o f memory, or unmed,ate. .,._~ _PpeR . , b . pccands bv this instruction. The ORL mstruction ,or yte-s1ze o the flags. See Example 6-18.
Inputs
Output
X
y
XORY
0 0
0
0
I
I
1
0
I
l
1
I
~ = = f ) - x oRY
XOR ;deat • dest XOR source
XRL dest i nation, source
ThJs instruction will perfocm the XOR operation on the two operands, and place 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 addressing modes of this instruction. The XRL instruction for byte-siie ope.rands has no effect on any of the flags. See Examples 6-19 and 6-20. 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 the same value, 00 is pla(t'd in A. Then we can use the )Z instruction to make a decision based on the result. See Example 6-20.
Logical XOR Function Inputs
Output
X
y
0 0
0
I
0
0 1 1
I
l
0
I
XXORY
~ ~ XXORY
Exampl• 6-18 Show the results of the following ''1r-vtf~
MOV A, #04,.
;A• 0 4
ORL A,#30H
IA •
Solution: 04H lOH l ,H
130
-IO l,fl\•#~ ~.., >'c,il
I rX
A oa )OH (now A• 34H)
..
0000 0100 0011 0000 0011 0100
o,H
oa
JOH • ) 4H
'
.' .
'lllE80s1 MICRoc oN't' ROLLER AND EMBEDDED svsTEMS
.-.
Example 6-19 Show the results of the following.
MOV A,#54H XRL A, #78H
Solution: 0101 0100 0111 1000 0010 1100
54H 78H 2CH
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 -45H 00
0100 0101 0100 0101 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 MOV MOV MOV XRL JNZ MOV
P2,#00 Pl,#OFFH R3,#45H A,Pl A,R3
;clear P2 ;make Pl an input port ;R3=45H ;read Pl
EXIT
;jump if A has value other than 0
I,
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 accumulator only. In other words, there is no such thing as a zero flag in the 8051. Another widely used application of XRL is to toggle bits of an operand. For example, to toggle b it 2 of regis ter A, we could use the following code. This cod e causes 02 of register A to change to the opposite value, while all the o ther bits remain unchanged.
XRL A,#04H
;EX-OR A with 0000 0100
CPL A (complement accumulator) . ~is instruction complements the contents of register A. The complement action changes the Os to ls and the ls to Os. ThtS 1s also called l's complement.
AlllTHM£1IC, LOGIC INSTRUCTIONS, AND PROGRAMS
131
' EJ<,n,ple 6-22 Fmd the 2's complement or the value SSH. Solution: 851! •
A,#SSH CPL A ADO A, fl
MOV
;1 1 8 ;2'9
comp. comp.
l'S
=
1000 0101 0111 1010 + 1 • 781! 0111 1011
Logical loverter MOV
CPL
l'., #SSH
; now A•AAH
A
,0101 0101 becomes l OlOl OlO
( AAII )
. d l to the l's complement. See To get the 2's complement, aU we have to do ,s to ad . truction in the 8051. Notice &le 6-22. In other words, there is no 2's complement Although the CPL instructhat 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.
1
Input
Output
X 0
NOTX
l
-
1
0
X ---{)o-NOT X
Compare Instruction The 8051 has an instruction for the compare operation. It has the following syntax. CJNE destination,source,relative addr ess In the 8051, the actions of comparing and jumping are combined into a single instruction called CJNE (compare and jump if not equal). The CJNE instruction compares two operands, and jumps ii they are not equa l In addition, it
changes the CY flag to indicate ii the destination operand is larger or smalle;. It is important to notice that lhe operands themselves remain unchanged. For example, alter the execution of the instruction "CJNE A, #67H, NEXT", register A still has its original value. This instruction compares register A with value 67H and jumps to the target address NEXT only ii register A has a value other than 67H.
Ex•mple 6-23
Examine the foUowing code, then answer the following qu ti (a) ):YUi 1.tiJJmp to NEXT? es ons. (b) What is in A after the C]NE Instruction is el
A, NSSH
CJNE A, l 99H,NEXT
:tf , •
•
: r.
I
NBXT: Solution: (a) '(es, it Jwnps ~ SSH and 99H are not equal. (b) A; SSH, its onginal value before the cornpar1
son.
132
•
CJNE. the destination operand can be in the accumulator ~r in one 111 of the Rn registers. The source operand can be in a register, 111 me~ory, or immediate. See Appendix A for the addressing mo~es of this rnstruction. This instruction affects the carry £lag only. CY lS changed
Table 6-3: Carry Flag Setting For CJNE Instruction
as shown in Table 6-3. The following shows how the comparison works for all possible
Carry Flag
Compare
CY = O
destination~ source destination < source
CY=l
conditions. CJNE RS,#80,NOT_EQUAL NOT_EQUAL: JNC NEXT
;check RS for 80 ;R5=80 ; jump if R5>80 ;RS
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 set. The biggest number should finally be saved in 60H. . '-o~ ~ -\ J"'-""-i
"t>...,-
Solution:
MOV MOV MOV MOV CJ?IE JC MOV
BACK: LOOP :
RO,#SOH Rl,#10 B, #0 A, @RO A,B,LOOP LOO Pl B,A
INC RO DJNZ Rl,BACK SJMP NEXT INC RO
LOOPl:
DJNZ Rl, BACK A,B MOV 60H,A MOV
NEXT :
~,~If:,..,.,.\
,,. .....-»
END
e_
'~
(...."\ ---
-~
" ,/A/
J ~ I
;RO i s t he poi nter t o t he data t(t> .... ;Rl i s the ~ ~nter ;B=O ;move a number to A ;compare with B ;if AB, move it to 8 . ' ;~.e., the bigger number should be in B ;increment the pointer ;~epeat until the counter=O ;Ju~p ~o EXIT, the biggest number is in B ;this is another loop , t a k en wh en the b" ;number was already in B a f t igger er a ,. compari. son ;repeat until the counter=O ;transfer the biggest number to the Ar . egister ;transfer the result to RAM location 60H
I/
Example 6-25 Assume that Pl is an input port connected to test it for the value 75 According to the a temperature sensor Write the following. . test results, place the te~pera a progr~ to read the temperature and If T 75 ture value mto the registers indkllted ._. a then A • 75 v7 If T < 75 t hen Rl • T I f T > 75 then R2 . ~
-ARllliM
ETIC, LOGIC INSTRUCTIONS, ANDPROGRAMs
133
•
' Solution:
,maJ
Pl. MOFFH
HOV
A.Pl
CJNl!
OVER: NEXT: EXIT:
"· .,s.ovn
·
ut Port
an ,nptemperature
d Pl p0rt, l tO 75 ,rea ot equa -jump if A n ' e,cit ;A~75, A~75 -if c;Y#O then ·~ Rl • < 9 ave •·· 7 ·CY=-l, A< ;;,,
SJMP
EXIT
JllC
NEXT
HOV
Rl, A_
SJMP
EXIT
-·~d ,P->•
MOV
R2 ,A
•
...
Pl
•
•
exit
•
·A>75, save lt
'
.., p
. R2 1n
I
V E,,mple 6-26
. r ngth 7, stored Write a program to check if the character string o Ie drome. If it is, output 'Y' to Pl.
. RAM locations SOH onwards is a
palin-
Ill
SACK:
N"l!XT:
R2, #03 RO,#SOH
MO\/
Rl.#56H
MOV MOV
A,eRO B,@Rl
CJNE INC DEC
A,B,NEXT
IJJNZ MOV NOP
RO
Rl
R2,BACK Pl,#'Y'
;take half ehe string length as a counter value take RO as pointer co the forward reading 1 ;take Rl as the pointer for the backward ;reading of the atr1ng , move into A the character _pointed by RO ;move into 8 the character pointed by Rl. ;compare it with the character pointed by Rl ;increment the forward co,unter ;decrement the backward counter :repeat until all the characters are compared ;since the string is a palindrome, output •y• , if not equal' do nothing since it is not a ;palindrome ;end of file
,,;, o;f
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 ward direction, e.g.• 'MADAM', 'RADAR'. etc. MOV HO\/
,,.
.i"" :...
II" ,Ml
. r,,I
(JI
W*c :a.
II.
(I,
,
Exompl• 6-27
Assume mtemal RAM memory locations 40H. 44H . 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 • give •ts location to R4; othenirilll...1 42 H• <691 43 Ii• (6SJ
44 ., <>•(62
Solution: MOV
R4, 10 RO.il40R
MOV HOV
R2,#0S
MOV
A, #65
;R4•0
;load pointer ,load counter ;A•65, Value
••arched
lia_ _
.,.
,
-: 70 CJNE A,@RO,NEXT R4,RO MOV
BACK:
SJMP
EXIT
NEXT:
RO DJNZ R2,BACK
EXIT
···
INC
;compare RAM data with 65 ·if 65, save address • ;and exit ·otherwise increme~t pointer • 1 count=O ;keep checking un t 1
d do not change. Flags are . t that the values of the operan s . JNE . truction The compare instruction is really a subtrac~on, exc_ep t be em hasized again that m the C . . ms . ' changed according to the execution of the SUBB instruction. It mus_ oJ:iy the CY flag is affected. This 15 despite the 15 the operands are not affected, regardless of the result of the combr on. fact that CJNE uses the subtract operation to set or reset the CY ag.
Review Questions 1.
;: 4.
s. 6. 7.
Find the content of register A after the following code in each case. (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 _ _ __ XRLing an operand with itself results in · . True or false. The CJNE instruction alters the co~ten!s of its ?perands.. , What value must R4 have in order for the following instruction not to Jump. CJNE R4,#53,0VER Find the contents of register A after execution of the following code. CLR A ORL A, #99H CPL A
SECTION 6.4: ROTATE INSTRUCTION AND DATA SERIALIZATION In many applications there is a need to perform a bitwise rotation of an operand. In the 8051 the rotation instructions RL, RR, RLC, and RRC are designed specifically for that purpose. They allow a program to rotate the accumulator right or left. We explore the rotate instructions next since they are widely used in many different applications. In the 8051, to rotate a byte the operand must be in register A. There are two type of rotations. One is a simple rotation of the bits of A, and the other is a rotation through the carry. Each is explained below.
Rotating the bits of A right or left RR A;rotate right A
1n rotate right, the 8 bits of the accumulator are rotated right one bit and bit DO exits fr
and enters into D7 (most significant bit). See the code and diagram. MOV A,#36H RR A RR A
-
RR
A
RR
A
;A=0011 ;A=OOOl ;A=lOOO ;A=llOO ;A=OllO
0110 1011 1101 0110 0011
RL
A
;rotate left
'
th l t 'gnifi b' 51 om e eas cant it
...
MSB
LSB
i--
A
-'RITHMETJC, LOGIC INSTRUCTIONS, AND PROGRAMS 135
'
ed left one bit, an ul tor are rotat . aJ1\ ill rotate left, the 8 bits of ~e.accum . a See the code and d1agr .
. from the MSB (most signi6can1 d b·t D7 eJOtS •
~e- -LSB~
; A•Olll 0010 ;A• lllO 0100 , A=l lOO 1001
Notice in the RR and RL ills!nlctions that no
fl
re affected.
ags a
Rotating through the carry
• .-, flag. Each is sho,-.,n next.
They involve the c- ·, There are two more rotate illslnlctions in the 8051·
th MS and the carry flag enters e B. ·1th LSB to the carry ag, fl ts if ·t · ln RRC A as bils are rotated from left to right, they ex• e th MSB In reality, the carry ag ac as I IS ln other words, in RRC A the LSB is moved to CY and CY is moved to e ·
RRC A
; rotate-i,ight through carry
part of register A, making it a 9-bit register.
CLR MOV RRC RRC RRC
C
A,#26H A A A
..,.. RLC
A
...
;rotate left through
fl
~-------------,
;make CY• O ;A•OOlO 011\ CY•O ;A•OOOl 00 ;A•OOOO 10 l CY• l ; A='i:,pOO 01 0 CY•l
L1MSB
LSBf-CYJ
carry
ln RLC A, as bits are shifted from righl lo left they exit the MSB and enter the carry flag, and the carry flag enters the LSB. ln other words, in RCL the MSB is moved to CY (carry flag) and CY is moved to the LSB. See the foUo,ving code and diagram.
SETS C
ill\ake CY=l
MOV
;A=OOOl ;A•OOlO ;A•OlOl ;A•lOlO ;A-0101
RLC RLC RLC RLC
A,ijlSH A A A A
0101 1011 0110 1100 1000
CY•O CY•O CY=O CY=l
Serializing data Serializing data is a way of sending a byte of data one bit at a tim . are two ways to transfer a byte of data seriaUy: e through a smgle pin of rnicrocontroller. There I.
2.
I
,
~'.
bit) and enters into DO (least s,gruficant bit).
HOV A, #?2H RL A RL A
.~
Using the serial port. In using the serial port pmg transfer. Thedet:iils of serial port data transf:r are d : " : :;:~every limited control over these uence of data The second method of serializing dat., is 10 transf d hapter 10. q t I spaces .m beM..veen them. ln many new generatio erf data one b't a a time and c th~ devices are becoming popular since they ta::S ~ evices such as LCD, ADC ontro1 the sequence of data and topic next. e ess space on a printed cir . •boarand ROM, the serial versions ol cuit d. We djscuss this important
,.j
, byte of data se
;move the bit to CY ;output carry as data bit
RRC A MOV
Pl . 3, C
Exa,nple 6-29 shows how to bring in a byte of data se,ially one bit at a time. We will see how to use these concept,; in Chapter 13 for a seriaJ ADC chip.
/
Example 6-28 Write a program to transfer value 41H serially (one bit at a time) via pin P2.l. Put two highs at the start and end of the data. Send the byte LSB first.
Solution: MOV SETB SETB MOV
A,#41H P2.1 P2.l RS,#8 HERE: RRC A MOV P2.l,C DJNZ RS,HERE SETB P2.l SETB P2.l
I l
I
'-·~D7~-_
;high ;high ;send the carry bit to P2.1 ;high ;high
_ _RE_G_A_ _
_JI__Jt-1-----,---l..~1
CY't--
~1 I
--1..
PIN P2.1
DO
Example 6-29 Write a program to bring in data in serial form an d send Jt . out in paraJlel form Solution: 8051
- - --.! PO.O
Pl
Let us take in data through port pin PO.O and transnut . 1t . through Pl. MOV R0,#08 SETB PO .0 BACK: ~ P O . O
..._.t~c __~ OJNZ RO,BACK MOV Pl,A BND
:counter for 8 bits ,make PO .O an in ;move data from ~~to~rt ;rotate right,the dat nto the carry bit ;repeat until all a goes from 'CY ' i ; the data is now ta bits are moved in nto A ranaferred. 1n parallel to Pl
-AR.ITH.M
ETIC, LOGIC INSTRUCTIONS, AND PROGRAMS
137
'
. etic and logic a . ed . Single-bit operations with CY . ·n structions, in the 8051 there are ,t Aside from the fact that the carry Oag (CY) is altered by arat~ These jJlstructions are last an Table 6-4.1 ""cl"d;og oo= de,JJ:' ..
•-= ,
JNC• a;,;,
...,,_Th<"" fow ~••"" ,,~ Smpl< •PP"" ""' ol
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 betweenUsmg carry each ON and OFF states al the LED. Solution: BACK: CPI, MOY
,complement the carry bit ;move i t co pin Pl.2 ;cal l a delay
C Pl.2,C
ACl\t.t. DELI\ y SJMP BACK
;repeat continuously
Table 6 •4: Carry Bit-Related Instructions Instruction SETB C
f unchon , make CY -1
CLR C
clear carry bit (CY = 0)
CPL
complement carry bit
C
MOV b,C
copy ~rry status to bit location (CY = b)
MOV C,b
copy bit location s tatus to ca
/NC target target JC ANL C,bit
(b
Jump to target if CY - 1 AND CY with AND . b',t and save it on CY
ANL C,/bit
CY wath inverted bit a OR CY with b't nd save it on CY ORCY, . , ' and save it on CY vtth inverted b't , and save it on CY
ORL C,bit ORL C,/bit
Ex~mpJe r,.31 that bit P2 2 I~ . US<.-d t 0Assume n lhe outside hght ,ind o control
Solution: SETB C ORt. C,P2 . 2
HOV CLR
C
AN!,
C, P2 . 5
MOY
P2.5,C
138
P2 . 2,C
an outd . and b1t P2 one oor hght tum off the inside · .5 a light ,lnS1de . a build.•ng. Show how to 111111 ;CY• 1
;CY• 'turn ;CY. ;CY•
P2.2 0
i
Red "ith cy not al
"on• if
t
0P2 S
.
ANl>ed
ready ~on•
:turn it Off if not With cY already Off
.
X-OR which has the mnemonic
.
Here we u.se another logical operation, 1.e., E . R2 sum of the number obtained from port 1 and a number m .
. in
Solution: , . ht' ans the nu mber of ls in it. Here it . , b. ary• numbe rs. Weig me Modulo-2 addition is a n EX-OR operation on tw o m d· ffe rent. implies the number of bit positions in which the two numbers are J e.g. 1101
Doing EX-OR opera tion on This is the modulo-2 sum
0011 1110
the two numbers, we get 1110.
The weight of the modulo-2 sum is . l +1+ 1+O= 3 MOV
MOV MOV MOV
BACK:
AGAIN:
· in RO ; load the number of b its ;make Rl=O ;make Pl an input port ·take in one number from port 1 ' ;EX-OR the numbers ; rot ate left through carry ;check for carry ;if CY• l , add one to count ;repeat 8 times ; end of file
RO, #08 Rl,#0 Pl, #OFFH A, Pl
XRL A, R2 RLC A JNC AGAIN !NC Rl DJNZ RO, BACK END
The register RI contains the result
SWAP A Another useful instruction is the SWAP instruction. It works only on the accumu lator (A). It swaps the lower nibble and the higher nibble. In other words, the lower 4 bits are put into the higher 4 bits, and the higher 4 bits are put into the lower 4 bits. See the diagrams below and Example 6-33.
before:
07-04
before:
01,1
1
after:
03 -00
11
SWAP
D3-DO
II
07 - 04
0010
11
011 1
after:
0010
SWAP
.
.
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 10 patt: conc.<1 f ;,. are O . ake PO an input nlY po-P3 4 bit:S o ,m ftom po, o uppeX' is now in the ,move data Now the data ·AND it with oFH, he useful • 'bbles, t • bits of Pl ;s1o1ap the n1 f A per • ·upper nibble o Pl Now the up '·move cbe data to ' ibble o f PO
Solution: MOV MOV
PO , IOPFH A,PO
ANL
A, MOPH
SIIAP A
''
MOV
Pl,A
';contain . t.h e 1ower Jl
Review Questions
.
h f the foUow111g I. What is the value of register A alter eac o
;nsttuctions?
MOV A, #25H RR A
RR RR
A A
RR A f u · ·1nsttuctions? 2. What is the value of register A after each of the o ow111g MOV A , #A2H
RL RL
A A
RL
A
RL A . , . ? 3. What is the value of register A after each of the following 111Sttucttons. CLR A 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 CLR C
od
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 1 their applications in real-world devices covered in future chapters. For exam}:' e,~ n ·crocontrollers provide the real time clock (RTC), where the time and date are kept even when the power ;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.
~~iI
ASCII numbers On ASCII keyboards, when the key "O" is activated, "011 0000" (30H) is provided to the computer. Similarly, 31H
(0110001) is provided for the key "l", and so on, as shown in Table 6-5. . It must be noted that although ASCII is standard in the United States (and many other countries), BCD numbers are universal. Since the keyboard, printers, and monitors all use ASCII, how does data get converted from ASCII to BCD, and vice versa? These are the subjects covered next.
I
Packed BCD to ASCII conversion Many systems have what is called a real-time clock (RTC). The RTC provides the time of day (hour, minute, second) and the date (year, month, day) continuously, regardless of whether the power is on or off (see Chapter 16). H owever, this data is provided in packed BCD. For this data to be displayed on a device such as an LCD, or to be printed by the printer, it must be in ASCII format. . To convert packed BCD to ASCII, it must first be converted to unpacked BCD. Then the unpacked BCD is tagged with 0110000 (30H). The following demonstrates converting from packed BCD to ASCII. See also Example 6-34. Packed BCD 29H 0010 1001
Unpacked BCD
ASCII
02H & 09H 0000 0010 & 0000 1001
32H
& 39H
0011 0010 & 0011 1001
ASCII to packed BCD conversion To convert ASCil to packed BCD, it is first converted to un a k d BCD ( · make packed BCD. For example, for 4 and 7 the ke board ·v p c e toge~ nd of the 3), and then combined to "0100 0111", which is packed BCD. This process is fuustrat~ ;::. and 37, respectively. The goal is to produce 47H or
Table 6-5: ASCII Code for Digits o. 9
-
Key 0
ASCII (hex)
Binary
BCD (unpacked)
30
0110000
0000 0000
1
31
0110001
0000 0001
2
32
0110010
0000 0010
3
33
0110011
00000011
4
34
0110100
5
35
0000 0100
011 0101
6
36
0000 0101
0110110
7
37
00000110
0110111
8
38
9
39
0111000 0111001
00000111 00001000 00001001
~ETIC, LOGIC INSTRUCTIONS, AND PROGRAMs
1,1
'
D to two ASCII numbers and
acked BC
E,wnple 6-34 Write a progtaJI\ 0 ..-istcr A has packed SC · Assume ,L.t u"" .• ,, pl•ce them in R2 and R6 -
to convert P
' ·
Solution:
:A=29H, packedfB~~ data in R2 . keep a copy O ibble (As09) ' er n ,) •mask the upp ll A•39H ('9 ANL • ·tan ASC • ) ;make, 9H ASCll char ORL ·save it (R6•3 , i nal data MOV ' et the orig ) MOV ;A=29!l , g 'bble(A•20 •mask the lower n1 ANL • c ,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 RR instructions with a sing Of course, in the above code we can replace all e
MOV MOV
A, #29H R2 A A' "~OFH A,#30H R6,A R2 A, A, "OFOH
Key
ASCII
unpacked BCD
Packed BCD
4 7
34 37
00000100 00000111
01000111 or 47H
MOV ANI.
A,# ~4'
MOV AN1, ORI.
A,# 1 7'
A, #OFH SWAP A MOV B,A A, #OFH A,B
hex for ASCII char ,mask upper nibble {A•04 ) ;A•40H ; A.=34H,
.
' .
• !
'
4
;Rl=37H,
hex for ASCII char 7 ;mask upper nibble (Rl=07 ) ;A• 47H, packed BCD
After this conversion, the packed BCD numbers are processed and the result will be in packed BCD format. As Wt saw earher in this chapter, a special instruction, "DA A", requires that data be in packed BCD fo rmat.
Using a look-up table for ASCII In some applications it is much easier to use a look-up table to get the ASCIJ charact . eed This · a widell' · · -' · kb d th · erwen . 1 • used concept m mte, ,acmg a ey oar to e m,crocontroUcr. This is shown in Example . _ 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'
I
142
THE 80S1 MICROcoNT
-
ROLLER AND EMBEDDED sYS'fDd
100 4' I
101 '5' 110 '6' 111 '7'
Solution:
OPTR, #MYTABLE A,Pl A,#07H ANL MOVC A,@A+DPTR MOV P2,A SJMP $
MOV MOV
·get SW status ;mask all but lower 3 bits ;get the data from look-up table ;displ ay value ; stay here
, ·--------------------- ---- -- --MYTABLE
ORG DB END
400H '0'
I
'l'
I
'2'
I
'3'
I
'4'
I
'5 '
I
'6',
'7'
You can easily modify this program for the hex values ofO- P, which are supplied by 4x4 keyboards. See Chapter for a keyboard example.
12
Checksum byte in ROM To ensure the integrity of the ROM contents, every system must perform the checksum calculation. The process of checksum will detect any corruption of the contents of ROM. One of the causes of ROM corruption is current surge, either when the system is turned on or during operation. To ensure data integrity in ROM, the checksum process uses what is called a clrecksurn byte. The checksum byte is an extra byte that is tagged to the end of a series of bytes of data. To caJculate the checksum byte of a series of bytes of data, the following steps can be taken. 1.
Add the bytes together and drop the carries.
2.
Take the 2's complement of the total sum; this is the checksum byte, which becomes the last byte of the series.
. '.o perform the checksum operation, add all the bytes, including the checksum byte. The result must be zero. lf 1t 1s not zero, one or more bytes of data have been changed (corrupted). To clarify these important concepts see Example 6-36. '
-
Example 6-36
Assume that we have 4 bytes of hexadecimal data: 25H 62H 3FH d 52H (a) Find the checksum byte, (b) perform the checksum o~eration t 'an · . 62H has been changed to 22H, show how checksum detects the e::r:ure data integrity, and (c) if the second byte Solution:
(a)
Find the checksum byte. 25H + 62H + +
3F'H
S2H 118H
(Dropping the carry of l, we have 18H I , byte is ESH.) · ts 2 8 complement is ESH. Therefore the checksum
-
.
.\RfrliMETIC, LOGIC INSTRUCTIONS, AND PROGJlAMs
143
I
'
re data ;,,1egntr· (b)
rerfonn the checksum operation to cnSU
• t
•
'
25H 62H 3PH s2H
ESH 200H
•
(c)
.
.
'
(Dropping the cames, "e see
00 indjcating data
'
If the Sl'
22H show how '
not corrupted,)
tS
checksum detects the error.
,'.
25H 22H
JPH
. d that means data is corrupted.) 00 . COH ,~hich ,snot ' an (Dropping the carry, we get , lCOH 52H 58H
I
Checksum program in modules The checksum generation and testing program is given in modular form. We have divided ~e p~ogram into several modules (subroutines or subprograms) Dividing a program into several modu!es (called fun~tlons in C programnung) allows us to use its modules in other applications. It is common practice to d1v1de a program mto several modules, Ifs! each module, and pul U1em into a library. The checksum program shown next has three modules: It (a) gets the tbt, from code ROM, (b) calculates the checksum byle, and (c) tests the checksum byte (or any data error. Eacho( the!! modules can be used in olher applications. Checksum Program ;CALCIJLATrNG ANO TESTING CHECKSUM BYTE DATA_AODR COUNT R»l_AODR
BQU 4 00H EQU 4 EQU JOR
;·---------------main program ORG 0 A.CALL COPY DATA A.CALL CAL_CHKSUM A.CALL TEST CHKSUM SJMP $ -
.
"
,.. -- --- ---------calculating checksum byte ...
CAL CHKSUM: MOV MOV CLR ADD H2: INC DJNZ CPL INC MOV RET
Rl,#RAM_ADDR R2,#COUNT A A, @Rl Rl R2,H2 A A @Rl,A
;load data address · load count ·clear accumulator , . re carries ;add bytes and igno · increment Rl ';repeat for all ·l's complement byte ) :2 •s complement(checksum ;save it in data RAM I
·---- ------------testing checksum byte ' TEST_ CHKSUM: ;load data address Rl,#RAM_ADDR MOV ; load counter R2,#COUNT+l MOV ;clear accumulator CLR A carries ;add bytes and ignore A,@Rl ADD H3: ·increment Rl INC Rl ;repeat for all DJNZ R2,H3 ;is result zero? then good JZ G l ;if not, data is bad Pl,# ' B' MOV SJMP OVER ;data is not corrupted MOV Pl,#'G ' G 1: RET OVER: I
I
· -------- -- --- ---my data in code ROM ORG 400H DB 25H, 62H, 3FH, 52H MYBYTE: END '
Binary (hex) to ASCII conversion Many ADC (analog-to-digital converter) chips provide output data in binary (hex). To display the data on an LCD or PC screen, we need to convert it to ASCII. The following code shows the binary-to-ASCII conversion program. Notice that the subroutine gets a byte of 8-bit binary (hex) data from Pl and converts it to decimal digits, and the second subroutine converts the decimal digits to ASCII digits and saves them. We are saving the low digit in the lower address location and the high digit in the higher address location. This is referred to as the Little-Endian convention, that is, low-byte to low-location and high-byte to high-location. All Intel p roducts use the Little-Endian convention.
Binary-to-ASCII Conversion Program ;CONVERTING BIN (HEX) TO ASCII RAM_ADDR ASCI RSULT COUNT
-
EQU 40H EQU SOH EQU 3
:--- - --- - --- - ---- main pr ogram ORG 0 ACALL BIN_DEC_CONVRT ACALL DEC ASCI CONVRT - SJMP $
-
AllrrHMmc,. LOGIC INSTRUCTIONS, AND PROCRAM5
lM
'
0 00-255) TO (oo -f' F locations tnese RAM ---------Convercing ~;;·~;~~coNVRT: RO,#RAM_ADDR MOV MOV A,Pl MOV B,#10 AB OIV @ RO,B MOV RO INC B,#10 MOV AB OIV @RO,B MOV RO INC MOV @RO,A RET --------Converting ·-------DEC ASCI CONVRT: -
-
BACK:
MOV MOV MOV MOV ORI. MOV INC INC
DJNZ
·divide by
•-save t h e ne"
' . .t 1ast d1g1 -save the •
DEC digits
RO, #RAM_ADDR Rl, #ASCI_RSUl,T R2,#3 A,iiRO A,# 30H @Rl ,A RO Rl R2,BACK
rnore t digit
10 once
1 ASCII digits to displayab e
f oEC data ;addr of ASCII data ;addr o ·count '.get DEC digit digit ;mal
;save it
·next digit ;next ;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 s. Does the following convert unpacked BCD in register A to ASCU?
H.
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-
ta.-
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 . 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 1 flow condition. • •ttention hast':~n ~ data.
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 · marupu · l a ti· o n purposes. tions are often used for bit . li ati·ons s uch as sen·a1 d ev1·ces. This chapter a so func 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. (a) MOV A, #3FH (b) MOV A, #99H ADD A,#4SH ADD A,#58H
(c) MOV A, #OFFH SETB C ADDC A,#00
(f) CLR C (d) MOV A, #OFFH MOV A,#OFFH ADD A,#1 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 (e) MOV A, #OFEH SETB C ADDC A,#01
SECTION 6.2: SIGNED NUMBER CONCEPTS AND ARITHMETIC OPERATIONS 16. How does the 8051 represent the following numbers? (a)-21 (b) --46 (c) 120 (d)-110 (e) 9CH 17. Th~ memory addresses in computers are (signed, unsi ed n 18. Wnte a program for each of the following and indicate the status th) O~~ers. 0 (a)(+lS)+(- 12) (b)(- 123)+(-l2 7) e agforeach. (c) (+25H) + (+34H) (d) (- 127) + (+127) 19. Find the result of the following operations and state wheth th adrution operations. er e 0 V and CY flags will be set after the following (a)-100 and +23 (b) +56 and +97 (c) +100 and +25 20. Explain when the OV flag is raised. (d )-122 and-75
si;
..,
AllllHMrnc, LOGIC INSTRUCTIONS, ANO PROGRAMs 1C7
'
•
.
'
I ,. 22
• ,rn COMP ARE INSTRUCTIONS SECTION 63: LOGIC ru,v · ·A-fO 23. AsSume that these registers contain the f~U?wmg. - '
•
•I
."~·
'#'
_ ~'/hichregisterholds theOV Bag? f OV flag. 21 Write• program to detect the status o the
90 perform the following operati0ns, B _ 56 and Rl "' · -
'
Indicate the result and the register where 1t 1s stored. Nott: The operations are independent of each other . (a) ANL (c) XRL (e) XRL
A, #45H A, #76H A, Rl
(g)
A, #OFFH
ANL
(b) (d) (I) (h)
ORL ANL ORL ORL
A, B A, RJ. A, RJ. A, @9911
ij) XRL A, #OAAH 24. Write instructions to do the foUowing, (a) complement the content of RAM location 38H (b) mask the upper4 bits of A (c) get the result of ANDing OC6H and 97H (d) E.x-OR the contents of A and R1 (e) make the lower nibble of RS, the high nibble . . t f R3 with 6 7H 25. Find the error in the foUowing instruction if the intention 1s to compare the con ten (i) XRL
A, #OEEH
°
CJNB R3,67H, HERE
A, #25H CJNE A,#44H,OVBR (c) MOV A, #34 C:JNE A,#34,NEXT (e) MOV RS, #54H C:JNE RS,#OFFH,NBXT
A, #OFF!! CJNE A,#6Fl!,NEXT (d) MOV RJ.. #0 C:JNE Rl.#0,NEXT (I) MOV A, #OAAH ANL A, #SSH CJNE A, #00, NEXT
RR
RR
(c) C:LR MOV
A A C A, #40H
CLR RL RL (d) SETB
MOV
t
Jr!
1011
Ill 11.1 lllO llil
t lid
l\
C!111 li!t 6~
A C
~~
A, #39H
C
-
A,#7l\H
SWJ\P
A
RRC RRC: RRC:
l\
RLC
A
A A
RLC
A
iii I
SWJ\P l\
t)'
l ~,
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. e st high in an 8-b" . 34. If A ~ 901-1, what is the content of A aft it data item. Th . (a) RR A (b) RL A ( the folloWing instnicti e data IS scanned from 00 to 0:
j'
35• A stepper motor uses the following ~u~o:b. 1100, 0110, 0011, 1001
illl .t:
l!];
30. Find the contents of register A after each of the folio . . (a) MOV A #56H (b) wmg IS executed. MOV
l~
tll'.
SECTION 6.4: ROTA TE JNSTRUCTION AND DATA SERIALIZATION A'
.;,
••mu
(b) MOV
29. In Problem 28, indicate whether or not the jump happens for each case.
SWAP
t/$
(,0 llO'
26. Is the following a valid instruction? "ONE R4, #67,HERE" 27. Does the 8051 have a "CfE" (compare and jump if equal) instruction? 28. Indicate the status of CY after CjNE is executed in each of the following cases. (a) MOV
~
(d) l\R~ns, if CY'=1?
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
· ( 3) th · ·· ;point 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 0011
0100 0101 0110
0111 1000 1001
1010 1011 1100 1101
41 . 42.
43. 44.
'2'
'3' '4' '5'
'6' '7' '8' '9' 'A' 'B' 'C'
'D' 1110 'E' 1111 'F' p·md the checksum byte for the followin ASCII True or false. If we add all the bytes, in~udin :;:::ge: "Hello" the data. g ecksum byte, and the result is OOH th . 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 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 . em · Assume that the lower four bits of Pl ar~ co ~acters t~O': based on the status of the s:t::: 0001 'l'
~:~~~ :;~t!e~· ~rite~ p ro!m to send the followin ASCII -up table method. g
0010
'2'
0011
'3' '4' 'S' '6' '7' '8' '9'
0100 0101 0110 0111
-
1000 1001
.\JlrntMETic, LOGIC INSTRUCl10NS, AND
(BIN, BCD ASC 00
' 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
'.
tion 6. No. We must use registers A and B for this opera · 7. A, the accwnulator . · n 8. No. We must use registers A and B for thiS operat,o ·
5. A, B
I
'
••
9.
I'
MOV A, Rl ADD A,R2
10. A, the accumulator 11. (a) A= OOand CY= 1 (b) A= FF and CY =0 43H 0100 0011 ~ 0000 0101 2•s complement 3EH 0011 1110 13. A=95H-4FH-l=45H
12.
0100 0011 + !_111 1011
SECTION 6.2: SIGNED NUMBER CONCEPTS AND ARITHMETIC OPERATlONS I. 2.
07
16H is 00010110 in binary and its 2's complement is 1110 1010 or -16H = EA in hex. 3. -128 to +127 4. +9 = 00001001 and -9 = 11110111 or F7 in hex. 5. An overflow is a carry into the sign bit (D7), but the cai:ry is a carry out of register (07). SECTION 6.3: LOGIC AND COMPARE INSTRUCTIONS I. 2. 3. 4.
(a) 02 Zeros One
(b) FFH
(c) FOH
All zeros
5. False 6. #53 7. 66H
SECTION 6.4: ROTATE INSfRUCTION AND DATA 1. 52H SERIALIZATION 2. 2AH 3. COH
4. Because aU the rotate instructions work with th 5. SOH e accumulator onl
6.CY•O
y
7. CY= 1
8. CY=l 9. MOV C, P2.? MOV 31,C 10. MOV C, 9 MOV Pl.4,C
;save statue of P2 7
:save carry in RAM.b on CY ;save status of RAM!~ location 06 ;save carry in Pl ,4 it 09 in CY
SECTION 6.5: BCD, ASCII, AND OTHER APPLICATJQ 1. (a) 15H = 0001 0101 packoo BCD 0000 N l'RoCRAMs 1 (b) 99H = 10011001 packed sco' 0000 ~ .0000 0101 001.00001001 unpacked BCo ' 150 unpacked BCD
llit~ CRacoNTao
___. LL£R AND EMBEDDED~
1 ,
,-3oH • 001101 l l 0.11101 \0B anJ an BCO ,,,• h.ivt' 7(11l 0111 01 IOB , 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·
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
Dlt~ f1l
-'lnHMrnc,
lOCIC INS I AUCTIONS, AND . .
ocw.
,, ha~c, 2Fl I, enJ 1t 2'., '-ompl mc..-nt i
CHAPTER 7 ' I
8051 PROGRAMMING IN C
I
I
OBJECTIVES Upon completion of this chapter, you will be able to: Examine the C data type for the 8051 Code 8051 C programs for time delay and I/0 operations Code 8051 C programs for 1/0 bit manipulation Code 8051 C programs for logic and arithmetic operations Code 8051 C programs for ASCD and BCD data conversion Code 8051 C programs for binary (hex) to decimal conversion Code 8051 C programs to use the 8051 code space Code 8051 C programs for data serialization
'
. ntroUer. The size of the hex me Why Program the 8051 in C? ROM of the IJ\lcroeo for two reasons: Pf;, ,ml d into the .,,-ain01ers, compilers produce hex files that we do, ~ 1 ·crocontroller pro,,O duced by the compiler is one of the roam concems nil I. 2.
I ~
M,crocontrollers have limited on-chip ROM. The code space for the 8051 is limited to 64l< byteS-
. raO'l size? While Assembly language proffect the compiled prog · tedious and ti.me consurnm How does the choice of progr-amming language a . . A5SCO'lbly Janguage JS . . g. C duces a hex file that is much smaller than C, progr~U\g much easier to write, but the hex file_ ~ize produCE,j programming, on the other hand, is less time consummg an are some of the major reasons for ,vntmg programs in much larger than if we used Assembly language. The following C mstead of Assembly:
~
I.
~
It is easier and less time consuming to write in C than Assembly.
C is easier to modify and update. You can use code available in function libraries. 4. C code is portable to other microcontrollers with little or no modification.
2. 3.
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.
SECTION 7.1: DATA TYPES AND TIME DELAY IN 8051 C In this section we first discuss C data types for the 8051 a nd th en prov1'd e code for time delay functions.
C data types for the 8051
f~=
Since one of the goats of 8051 c . 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 ~ 0 m,crocontroller 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"<>fl \'i,1U1I
';?·
.J'
1:
THE 80SJ ••
..,,cRoco
NTROLLER
-
I
..,
I
Example 7-1
Write an 8051 C program to send values 00 - FF to Port Pl. ~
'," "'\
Solution:
J
#include / void main(void)
"v
cf.
{ unsigned § z; f or( z =O ; z<=255; z ++) Pl=Z; }
. I
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 • void main (void) { unsigned char mynum [.] = "012345ABCD"; unsigned char z; f or (z=01z< ~t; z++ ) Pl=mynum(z]; }
Run the above program on your simulator to see how Pl displays values 30H, 31H, 32H, 33H, 34H, 35H, 41H, 42H, .t3H, and 44H, the hex values for ASCII 0, 1, 2, and so on.
V
/
Example 7-3 Write an 8051 C program to toggle all the bits of Pl continuously.
Solution: II Toggle Pl forever #include void main(voidl ~
{
for (;;) -4
{
1
'f,
PlaOxSS1 Pl•OxAA; }
I /repeat forever //Ox indicates the
data is in hex (binary)
}
Run the above program on your simulator m1ee how pt ~ by the C compiler. JUltl8 cioatll:-a
~---~~~~~~--
fly•. _. . thl 11 m~ l••ilbid -~ ~:~
~~
.-
.
'
.
.. .
8051 PROGRAMMING INC
155
..
'
· (D7 o f D7 •
[)O) to represent the - or +
>al
._;i;cant b 1t . . us values from -128 to+ 127. !n . 'th most S1!Y-· giving · eel S1~ O f th The signed char is an 8-bit data type that e s ign char data lypi ; the signed ouJll~~perature, the use 0 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 char
-'::e
of o to 65535 (0000 · FFFFH). In the &l5t
Unsigned int
'
The unsigned int is a 16-bit data type that takes• value i~i~::elt is also used to set counte r values of ~ unsigned int is used to define J6-bit variables such as mernoryd t taJ
7
Signed int Signed int is a 16-bit data type that uses the most significant bit (015 of D15 • DO} to rep resent the - or + value.As a result, we have only IS bits for the magnitude of the number, or values from -32,768 to +32,767.
Sbit (single bit) The sbit keyword is a widely used 8051 Cdata type des'gned It allows access to the single bits of the SFR regist As I spec,'Iiically to access single-bit addressable regisre~
Among the SFRs that are widely used and are also~~-ad;::~ m Chapter 5, some of the SFRs a re b it-addressable v1dual bits of the ports as shown in Example 7•5. e are ports PO • P3. We can use s bit to access the in
IJ
Example 7-4
Write an 8051C program to send values of -4 to +4 to port Pl. Solution: //sign numbers #inc lude 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
'
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 sbit MYBIT
~
.'\"'
.
= PlAO; //notice that shit ~ ~ e t ......,.._-4.t, / /declared outside
is of main
void main (void )
{
• I
unsignedg;, for (z =O; Z<=SOOOO; { MYBIT - 0.' MY BIT = l· }
Z++)
•
I
}
Run the above program on your simulator to see how Pl .0 toggles continuously.
Bit and sfr The bit data type allows access to single bits of bit-addressable memory spaces 20 - 2FH. Notice that while the s bit data type is used for bit-addressable SFRs, the bit data type is used for the bit-addressable section of RAM space 20 - 2FH. To access the byte-size SFR registers, we use the sfr data type. We will see the use of sbit, bit, and sfr data types in Table 7-1.
Time Delay There are two ways to crea te a time delay in 8051 C: 1.
2.
Using a simple for loop Using the 8051 timers
In either case, when we write a time delay we must use the oscilloscope to measure the duratio f 0 tim d la Next, we use the for loop to create time delays. Discussion of the use of the 8051 timer to ere te tim dneJo ~ e e Y· until Chapter 9. a e ays ts postponed
Table 7-1: Some Widely Used Data Types for 8051 c Data Type
Size in Bits
unsiged char
8-bit
:igned) char
8-bit
unsigned int
16-bit
(signd) int
16-bit
sbit
1-bit
bit sfr
1-bit 8-bit
Data Range/Usage
0 to 255 -128 to +127 0 to65535
-32,768 to +32,767 SFR bit-addressable only
RAM bit-addressable only RAM addresses 80 - FFH only
157
..
'
factors that can affect the accuracy 01
tlit
iniJ1dful of thfE?<' In creating a time delay using a for Ioop, delay.
e fields of re technology an~ rnicropr . ed in 1980, both th the number of machine cycles~ 3 3 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~ nwnber of clock periods per machine cycle v~ a per machine cycle,; .k periods per machine cycle Whil l 5 th [)55000 u5es 4 OC ' e t!ie the original 8051 / 52 design used 12 clock pen use fewer clocks per machine cycle. for example, e . 0589C420 uses only one dock per machine cycle. , n of the cloc.k period for the machine eye'-. • . 1ne duratto .. _
J.
Sri
5
2.
7' .. \
•
we must be
The crystal frequency connected to the Xl • X2 mpul pill ·
. th mpiler used to compile the C program. When a function of this crystal frequency. 3. Compiler choice. The third factor that affects the time delay ,s ~i~ctions and their sequences used in the d•lh we program in Assembly language, we can control ~e exact ,erts the C statements and functions to subroutine. In the case of C programs, it is theCcompiler that c~;; nt code. In other words, if we compile a ·. Y I language instructions. As a result, different compilers .produodce e:ifferent hex code. 8'•!11 8051 C programs with different compilers, each compiler pr uces
Asse,;;;.1
'
For the above reasons, when we write time delays for C, we must use the oscilloscope to measure the exact dllll, 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 ( , ; )
\~ ,
l
-l
//repeat forever
Pl=OxSS; for(x=O;x<40000;x++). Pl=OxAA; ' for(x•O;X<40000;x++);
//delay size unknown '
:
/
I\/
Exampl• 7.7 Wn·1e an 805J C program to toggle the bits of P
Solution:
l ports contin uously With a 2SO ms delay
The program below is tested for the #include DS89C420 with XTAL void MSOelay (unsigned int). z 11.0592 Mliz void main (void) • L' ' ·
{
·
r,v>.,,...
wh~le(l) //repeat forever
158
lli£~
Oco,., ••tllott
.-
ER AND EMBEDDED S ~
,1
.?
Pl=Ox55; MSDelay (250 ) ; Pl =OxAA; MSDel ay (250) ;
}
l void MSDelay (unsigned int itime )
{ unsigned i n~ i , j ; for{i =O; i
,.r--~ '\.
}
,
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 #i nclude void MSDelay {unsigned int); void main (void) { while (l ) //another way to do it forever { ( PO=OXSS; P2=0XSS; MSDelay(250); ( PO=OxAA; P2=0xAA; MSDelay(250); } } void MSDelay(unsigned int itime) { unsigned inti, j; for(isO;i
= 11.0592
' MHz
I,
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. ~ we are declaring a variable for a person's age, we shoul; :!'es. 4. ;;,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
'
1 SECTION 7.2: 1/0 PROGRAMMING IN . 805 CJ/ 0
parts ,,or the 8051- We
1001< at both byte and b11 I
ln this section we look at C prograJ!lOW'S of the
l(j
progrrunming.
152
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_
Byte size 1/0
~~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.
'
O () () (] S D
Solution:
O
<)
' #include #define LED P2 V' void main (void)
I /notice how we can de.fine P2
(
0 0
""
D
U
//clear Pl //clear P2 //repeat forever
Pl•OOY LED•~,
for ( ; ; ) {
I I increment Pl
Pl+:-t; LED++;
//increment P2
)
ltl
l
llt
•II! Example 7-10
ll!a
Writean8051C program to get a byte of data fro . 61 ..,s Solution: m Pl, wait 1/2 second' and t hensendittoP2
ai•
#include void MSDelay(unaigned . void main(voidl int);
.
{ unsigned charm b Pl•OXPF· y yte; ' while (l)
"
{ mybyte:Pi.· HSDelay(s~o(.
}
.
P2amybyte·
'
I /make Pl an input po rt //get abyte from Pl //send it to P2
} voi{d HSDelay (unsigned i nt itime )
unsigned inti, j· for(i•O·i<1·t· ' ,' ime;i+•) }
160
for(J•O;j
.
£xample 7-11 Write an 8051
c
. .
s than 100 send it to Pl; otherwise, send it to program to get a byte of data from PO. If it 15 Jes '
P2. Solution:
#include void main (void) { unsigned char mybyte; PO=OxFF; while (1) { mybyte=PO; if(mybyte
//make PO an input port
J
//get a byte from PO //send it to Pl if less than 100
I
//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
. . Pl.5 uit is high, sen Wnte an 8051 C program to morutor bit .
Solution:
,incl ude eb i t mybit = p1•s; void main (void) { mybit•l; while (l ) { i f (mybit••l) P0=0x55;
//notice
the way single bit
l'O; otherWl '
is declared
''
//make mybit an input •
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 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)
/
l
unsigned int 1, j; for(i•O;i
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 //LCDData declaration #define LCDData Pl //the enable pin sbit En•P2"0; void main (void) { unsigned char message[]• ·The Earth is but One Country#; unsigned char z; //send all the 28 characters for(z•O;z<28;z++) { LCDData=message[z]; En=l; //a highEn-O; l e to latch t he LCD data // -to- 1ow pus
l
l
Run the above program on your simulator to see how Pl displays each character of the message. Meanwhile, monitor bit P2.0 after each character is issued.
Accesssing SFR addresses 80 - FFH Another way to access the SFR RAM space 80 - FFH is to use the sfr data type. This is shown in Example 7-16. We can also access a single bit of any SFR if we specify the bit address as shown in Example 7-17. Both the bit and byte addresses for the PO- P3 ports are given in Table 7-2. Notice in Examples 7-16 and 7-17, that there is no#include statement. This allows us to access any byte of the SFR RAM space 80 - FFH. This is a method widely used for the new generation of 8051 m.icrocontrollers, and we will use it in future chapters.
Table 7-2: Single Bit Addresses of Ports
PO
Addr
Pl
Addr
P2
Addr
P3
Addr
PO.O
Port's Bit
80H
Pl.0
90H
P2.0
AOH
P3.0
BOH
DO
81H
Pl.I
91H
P2.1
AlH
P3.l
B1H
82H
01
Pl.2
92H
P2.2
A2H
P3.2
B2H
02
93H
P2.3
A3H
P3.3
B3H
03
P2.4
A4H
P3.4
B4H
04
P2.5
ASH
P3.5
BSH
05
P2.6
A6H
P3.6
B6H
06
A7H
P3.7
87H
07
P0.1 P0.2 P0.3 P0.4 P0.5 P0.6 P0.7
83H 84H 85H 86H 87H
Pl.3 Pl.4 Pl.5 Pl.6 Pl.7
94H 95H 96H 97H
P2.7
-
111st PROGRAMMING IN C 163
'
.
.
d P2 cooltJlU
. 250 ms delay. Use the 1fr · ously with a
bits of PO, Pl, ao
e,wnple 7-16 am to toggle all the
Write an 805dJeclC P1: port addresses. keyword to are Solution:
e sfr data t~e data eype sFRs using t.h PO usin9 sf II Accessing POrts as / /declar~ng afr PO• Ox80; I
1
sfr Pl• Ox90; sfr P2 = OxAO: iot); i d MSDelay{unsigned VO .d) void main{vo1 { //do it forever while(l) { PO=Ox55; Pl=OxSS; P2=0x55; /; 2 so ms delay MSDelay (250); PO=OxAA;
. .
.
' '
Pl=OxAA; P2=0xAA;
MSDelay(250 ): }
l
void MSDelay(unsigned int itime)
I unsigned int . 1, . J; . for(i=O;i
for (j•O:j
I
Ex•mpl• 7-17 Write an 8051 C program to tum bit Pl .5 on and off 50,000 times. Solution:
sbit MYBIT = Ox95; //another way to declare bit Pl'S void main(void) { unsigned int z; for(z=O;z
MYBIT•O;
I
l
Using bit data type for bit-addressable RAM The shit data type is used for bit-addressable SFR registe addressable section of the data RAM space 20 - 2FH. To do ,~_rs only. Sometimes we n=• d , a bi~ uiat, we use the b 11 ' '"" to store some ala m 164 data type, as shown in Ex~mple 7-IS.
no:: sos1 MICRoco Nl'Ro tlEll AND EM1SEDDED svsred
.
ExVJ1ple 7·18 . and send it to P2.7 continuously. Write an 8051 C program to get the status of bit Pl.O, save it, Solution:
#include sbit inbit = PlAO; sbit outbit = P2A7; bit membit;
//sbit is used to dee l are SFR bits //notice we use bit to declare //bit-addressable memory
void main(void) { while (1) {
'
//get a bit from Pl.O //and send it to P2.7
membit=inbit; outbit=membit;
I I
•
}
}
Review Questions 1. The address of Pl is _ __ __ 2. Write a short program that toggles all bits of P2. 3. Write a short program that toggles only bit Pl.O. . . dd bl l . 4. True or false. The sbit data type is used for both SFR a~d RA~ smgle-b1t a res~a e ocahons. 5. True or false. The bit data type is used onJy for RAM s ingle-bit addressable locations.
SECTION 7.3: LOGIC OPERATIONS IN 8051 C One of the most important and powerful features of the C language is its ability to perform bit manipulation. Because many books on C do not cover this important topic, it is appropriate to discuss it in this section. This section describes the action of bit-wise logic operators and provides some examples of how they are used.
Bit-wise operators in C While every C programmer is familiar with the logical operators AND (&&), OR ( I I), and NOT (!), many C p rogr~ers are less f~ar ~ith the bitwise op_erators AN_D (&), OR (I), EX-OR (A), Inverter(-), Shift Right(>>), and Shilt Left (<<).These b1t-w1se operators are widely used 1n software engineering for embedded systems and control; consequently, understanding and mastery of them are critical in microprocessor-based system design and interfacing. See Table 7-3.
Table 7-3: Bit-wise Logic Operators for C AND OR EX-OR A B A&B AIB A"B 0 0
0
1
1
0 1
1
-
0
Inverter
Y=-B
0
0
1
1
0
1
0
1
1
1
1 0
0
8051 PROGRAMMING INC
165
'
I ·cal operators· les using the C ogt
The following shows some examp
Od5 & OxOF = OxOS 1• ANDing •I I 2. Ox04 I Ox68 = Ox6C / ' ORing: • 3 0x54 "Ox78 = Ox2C I' XORing •I / ' Inverting 55H ' I · ..() SS = OxAA J.
x
4.
. vise operators.
.I•
Examples 7-19 and 7-20 show the usage bit-,
I
.>
~
;,"
Example 7·19 • th resuJts. d exaJl\lll• • Run the following program on your simulator an
7
Solution: llindude void main (void) ( PO• Pi• P2= PO• Pl•
I •'
OxJS & OxOF; Ox04 I Ox68; Ox54 • Ox7B; - Ox55; Ox9A >> 3;
Pl• Ox77 PO• Ox6
>> 4: << 4;
/ / ANOi ng / / ORing //XORing // inversing . //shifting r i ght 3 times //shift i ng right 4 times //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 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
l
166 THE~
JCRocor-,ii-a
-
OLLER ANO EMBEDDED 5ySTPd
Bit-wise shift operation in C There are two bit-wise shift operators in C: (1) shift right(>>), and (2) shift left (<<). Their format in C is as follows: data>> number of bits to be shifted right data<< number of bits to be shifted left The following shows some examples of shift operators in C. 1. 2.
Ox9A >> 3= Ox13 Ox77 >> 4 = Ox07
3.
Ox6 << 4 = Ox60
/ • shifting right 3 times•I I"' shifting right 4 times• I / * shifting left 4 times • I
•
Study Examples 7-21, 7-22, and 7-23, showing how the bit-wise operators are used in the 8051 C.
Example 7-21 Write an 8051 C program to toggle all the bits of PO, Pl, and P2 continuously with a 250 ms delay. Use the Ex-OR operator. Solution: The program below is tested for the DS89C420 with XTAL = 11.0592 MHz. #includee 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
Example 7-22 Write an 8051 C program to get bit Pl .O and send it to P2 7 aft
·
.
.
er mverttng it.
Solution: #include inbit•Pl "'O;
9 bit
-
8051
PROGRAMMING IN C =
167
..
'
rt (Sf'R) bits
sbit is used dec~areddporessaJ:>le memory · · bit-a // //nocice thlS is
abic outbit•P2·1, bit membit; void 01ain(void)
{
while(l)
(
membit•inbit; outbit• -membit;
}
\
//get a bit from pi.o to p2.7 //invert it and send it
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 0 0
Pt.0 0
1 1
0 l
I
send ·o· to PO send ·1 • to l'O send '2' 10 PO send '3' to PO
Solution: ~i~clude void maio(void)
{ unsigned char z · ' Z•Pl; z=z&Oxl; switch(z)
I
I /read Pl //mask the unused bits //make decision
caoe (O):
I
PO•' 0 • .
break; '
//issue ASCII o
l
case(!):
{ PO=' l' •.
I
break·
,
case (2)
I
//issue ASCII l
,
PO•' 2 • .
} break·,
•
//issue ASCII 2
case (J):
I
PO•' 3 • .
break; '
}
)
168
J
//issue ASCII 3
Review Questions 1.
2.
3. 4.
s.
find the content of Pl after the follo"ving C code in each case. ,.. CA. (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 - - - - th To set high certain bits we must OR them wi - - - - Ex-ORing a value with itself results in · d find the contents of P2 after execution of the following co e. P2=0; P2=P210x99; P2=-P2;
SECTION 7.4: DATA CONVERSION PROGRAMS IN 8051 C ewer microcontrollers have a realRecall that BCD numbers were discussed in Chapter 6. As stated th ere, many n C .d th time time clock (RTC) where the time and date are kept even when the power is off. Very often the RT provi es e li and date in packed BCD. However, to display them they must be converted to ASCil. ln this section we show the app cation of logic and rotate instructions in the conversion of BCD and ASCII.
ASCII numbers On ASCTI keyboards, when the key "O" is activated, "011 0000" (30H) is provided to the computer. Similarly, 31H (011 0001) is provided for the key "l", and so on, as shown in Table 7-4.
.
Packed BCD to ASCII conversion The RTC provides the time of day (hour, minute, second) and the date (year, month, day) continuously, regardless of whether the power is on or off. However, this data is provided in packed BCD. To convert packed BCD to ASCII, it must first be converted to unpacked BCD. Then the unpacked BCD is tagged with 011 0000 (30H). The following demonstrates converting from packed BCD to ASCll. See also Example 7-24. Pa c ked BCD Ox29 00101001
Unpac ked BCD Ox02, Ox09 00000010,00001001
ASCII Ox32, Ox39 00110010,00111001
Table 7-4: ASCII Code for Digits O- 9 Key
ASCIJ (hex)
Binary
BCD (unpacked)
0
30
011 0000
0000 0000
1
31
011 0001
00000001
2
32
0110010
0000 0010
3
33
011 0011
4
0000 0011
34
0110100
5
35
6
36
7
-
8051
37
8
38
9
39
011 0101 0110110 011 0111 011 1000 011 1001
00000100 0000 0101 00000110 0000 0111 00001000 00001001
PROGRAMMING IN C
169
'
'
~
- -l...t BCD Ito i,··.. comb, ASCII to packed BCD conversion _. ~d of the 31•and •uu,n LT, c. - m A5C1I pio-d BCD. 11 fit5I COl''-ertrd ~.;.i 3;-H. respecti'·el) . The goal "' to prod l1(d lo awk pavd BCD For OAtl'f'lt 4 - i 7 on tlW i.i,,t,oatd ~ · t Ute •'I!
'°
or "OUXl 0111 • whW. 11 f*Md BCD Ot,pack.ed 1a>
ASCI I
0 o~.u ouooo:11
34
••
o.ooc111 or 47H
l
' Wr11~
I
'I
n,gram "'''""~rt p,o the b) te,, on r1 .ind P2.
•n 3051 C p
Solution .
l lnc l ude ,r,egSl . h• void '""in (YOidl { unaign•d c~ x • y • ,.. •I unalgned char o,ybyt• • Ox2P r "Pl • • mybyt• I I / u 1k lower ' bit• " I Ox 'l0 oxo, 1 -by //Nkl lt UCtt - , >>t• I / u1k "l)per 4 b1 ta Y• Y Y 4 1" ox,o, P2 • Y I OxlO // lhi! t I t to l ower 4 1 I / /... ke i t ASCII O
Ex.ampl• 7·25 gib of '4' Ind 7'
Solution:
to ~
Ythem on Pl . BCD and d ISp ' la
• include vo1d ""'In (void)
I une i gned char b una l gned Char Wcdbyte : •' 4. ' una1gned c"·r ,.._ Z•' 7 • r. w• OxOF· w •
w' w ••
1
4
. '
, , ..... . 3
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) perform 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: Find the checksum byte.
(a)
2 5H + 62 H + 3FH + 52H 118H
{b)
(Dropping carry of 1 and taking the 2's complement, we get E8H.)
Perform the checksum operation to ensure data integrity. 25H + 62H + 3FH
+ 52H
+ ESH
(Dropping the carries we get 00, which means data . t is no corrupted.) Uthe second byte 62H has been changed to 22H h h , s ow ow checksum detects the error 200H
(c)
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 Solution:
b um yte for the data · given in Example 7-26.
! i nc1uc1e 01 d main(void) {
IOs1 PR~ ~RAMMING INC 171
checksum byte in ROM To ensure the integrity of ROM contents, every system must perform the checksum calcuJa~on: The process of checksum will detect any corruption of the contents of ROM. One of the causes of ROM corruption 1s current surge, either when the system is turned on or during operation. To ensure data integrity in ROM, the che~sum process uses \~hat is called a checksum vyte. The checksum byte is an extra byte that is tagged to the end of a series of bytes of data. To calculate the checksum byte of a series of bytes of data, the following steps can be taken. 1.
2.
Add the bytes together and drop the carries. 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) perform 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:
Find the checksum byte.
(a)
25H + 62H + 3FH + 52H
I '
I
118H
(b)
• (Dropping carry of 1 and taking the 2's complement, we get E8H.)
Perform the checksum operation to ensure data integrity. 25H + 62H + 3FH + 52H
' '
+
ESH 200H
(c)
(Dropping the carries we get 00' which means data ts . not corrupted.)
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 Solution:
te i Y or the data · . given m Examp le 7-26.
:i~clude 01 d main(void) {
80s1 PR
0GRAMMING IN C
171
...
'
•
· ned uns19
char unsigned char un signed char unsigned char
for(x•O;x<4;x++)
ch byte to //issue ea together //add chem um to Pl //issue the 9
{
(
P2•mydata[x); sum=sum+mydata[xl;
l
Pl•sum; chkaumbyte•-sum+l;
Pl=chksumbyte;
}
P2
' complement byte //make 2 s che checksum //sbOW
J
l
,'
mydatall • sum•O; x; chksumby te·'
• e the contents o 8051 simulator and eiraJTUll
f Pl and P2. Notice that each by1f
Single-step the above program on the is put on Pl •• they are added together.
••
Exm>plt 7-28 ASCU h c aracter 'C' t o PO. 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
void maintvoid) {
unsigned char mydata[J•{Ox25,0x62,0x3F,Ox52,0xE8}; unsigned char chksumeO; unsigned char x; for(x¥0;x
chksum•chkaum+mydata[x); if(chksum•=Ol
//add them together
PO= 'G';
else P0•'8';
}
,
a
Binary (hex) to decimal and ASCII conversion In C 051 The printf function is part of the standard 1/0 Library · C binary (hex) to decimal, or vice versa. But printf takes a 11\ and can do many thin . frOIII 1 For this reason, in systems based on the 8051 microcontro~t of_ ~emory space •nd . gs, including converting datatiiJ]v of using printf. er, ll ,s better low . mcreases your hex file subs~ ie,d 1 One of the most widely used conversions is the b' n e Your own conversion function i.nS Digital Conversion) chips, the dala is provided to the~y to decirnai COnve . dates are also provided in binary. In order to display b' •croeontroller in b· rsion. In devices such as AOC (Anal~ Since the hexadecimal format is• convenient way of r ina.ry data we neect'~•ry. In some RTCs, data such as time O epresenting binary d convert it to decimal and then ID~ 172 ata we refer to the binary data as ht',.. 11't
T1iE sos1 Mtcao CON'fao - .~ LLER AND EMBEDDSDSYlt•,._..
Example 7-29 . d d' l the digits on PO, Pl, and P2. Write an 8051 C program to convert 11111101 (FD hex) to decimal an isp ay Solution:
ffincludee 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) //middle digit d2 - X \ 10; //most significant digit (MSD) X I 10; d3 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:
FD/OA 19/0A
Quotient 19 2
Remainder 3 (low digit) LSD 5 (middle digit) 2 (high d igit) (MSD)
Example 7-29 shows the C program for that algorithm.
Review Questions I. For the foUo\ving decimal numbers, give the packed BCD and unpacked BCD representations (a)lS ~~ ·
2. Show the binary and hex formats for "76" and its BCD version. 3. 67H in BCD when converted to ASCII is H and H. 4. Does the following convert unpacked BCD in register A to ASCII? mydata = Ox 09 + Ox30; S. Why is the use of packed BCD preferable to ASCII? 6. Which one takes more memory space: packed BCD or ASCII? 7· ln Question 6, which is more universal? 8· Find the ch~ksu~ byte for the following values; 22H, 76H, SFH, SCH, 99H. 9· To test data mtegnty, we add them together, includ ing the checks b . be equal to if the data is not corrupted. um y te. Then drop the carnes. The result must lO. An ADC provides an input of 0010 0110. What happens if we Ou tp u t th at to the screen?
SECTION 7.5: ACCESSING CODE ROM SPACE IN 8051 C In ~~ing the code (program) space for predefined data is the wide! . . SJ>ace ~ha~ter we saw how to use the Assembly language instructio~ ~d o ption m the 8051, as we saw in Chapter 5. .
1h15 chapter, we explore the same concept for 8051 C.
OVC to access the data stored in the 8051 code
173
'
'
ce v code data space e are as rouows: RAM data spa • . wJuch to store data, Th Y . . b tes.) We can read (from) or"'~ In the 8051 ,ve have three spaces l1l ...cU (In the 8052, ,tis 256 ~w in Chapter 5. It eOO. ,n •· ·stcrs as we . n, 128 bytes of RAM sp,1ce with address rang g the RO and Rl regi J-1 'fhis 641< bytes of on-chip ROM space ts I. . e ) th' RAM space directly or indirectly usm f ()()(JO • pfFF · trol of the program counter (PC). W (,nto ,s . h addresses o d the coo Ch 5) Th ' 2. The 64K bytes of code (programod)sp)a:~·~1erefore is difeCtlY c'::'on~o access it for data
!
7 L
Nex~ we discuss on-chip RAM and ROM space usag~ by the 8051 C ~mpiler._ We have used the Proview32 C oompiler to verify the concepts discussed next. Use the compiler of you, choice to verify these concepts.
RAM data space usage by the 8051 C compiler In Assembly language programming, as shown in Chapters 2 and 5, the 128 bytes of RAM space is used mainly by register banks and the sta.ck. Whatever remains is used for scratch pad RAM. The 8051 C compiler first allocates the first 8 bytes of the RAM to bank Oand then some RAM to the stack. Then 1t starts to aUocate the rest to the variables declared by the C program. While in Assembly the default starting address for the stack is 08 the C compiler moves the stack's starting address to somewhere in th~ 7F range of 50 • 7FH. Thls allows us to allocate contiguous RAM locati to array elements. ons In cases whehre the program ~as individual variables in addition to Scratch Pad RAM 1 array e ements, t e 8051 C comptler aUocates RAM locati · h 30 lowing order: ons •n t e fol:::-t---~f2F
Bank O 2. Individual variables 3. Array elements 4. Stack I.
addresses O. 7 addresses 08 and beyond addresses right after variables addresses n'gh t after array elements
You can verify the above order by running Exam 8051 C simulator and examining the contents of the pie 7·30 on your Remember that array elements need contiguous RAM data RAM space. lirruts the size of the array due to the fact that, h locations and that ' everything. . ln the case of Example7-31 ve thave on] Y128 bytes of RAM ,or limit4:'1 to around 100. Run Example 7-31 on your~array.elements are examine the RAM space allocation. Keep changi h1 C Slll\ulator and and monitor the RAM space to s,-e what happe ng t e size of the •rra . ns. y 174
20
Bit-Addressable W t
IF
18
Register Bank 3
17 10
Register Bank 2
OF 08
Register Bank I (Stad
Register Bank 0
Figure 7 1 D • • • • · """" Allocation in the 8051
. e th e contents of the 128-byte Example 7-30 8051 simulator. Exanun . p rogram on your om ile and single-step the following ~AJspace to locate the ASCII values. Solution:
#include void ma i n (void) { uns i gned char mynum []
=
"ABCDEF" ;
//This uses RAM space //to store data
unsigned char z; f or( z=O;Z<=6;z++) Pl=mynum [z);
,
} . th RAM space to locate values 41H, 42H, 43H , 44H, on our 8051 simulator and exanune e Run the above program y l 'A' ' B' 'C' and so on. etc., the hex values for ASCII etters ' ' ' •
Example 7-31 8051 simulator Examine the contents of the code . Write, compile, and single-step the following p rogram on your space to locate the values. Solution:
#include void main (void) { uns igned char mydata[lOO]; uns i g ned char x, z=O; for (x= O;x
mydata[x],.z ; Pl=Z;
//100 byte space in RAM
//count do wn //save i t i n RAM //give a copy to Pl too
}
:
} Run the above program on your 8051 simulator and examine the data RAM space to locate values PFH, PEH, FDH, and so on in RAM. .
The 8052 RAM data space lntel added some new features to the 8051 microcontroller and called it the 8052. One of the new features was an extra 128 bytes of RAM space. That means that the 8052 has 256 bytes of RAM space instead of 128 bytes. Remember that the 8052 is code-compatible w ith the 8051. This means that any program written for the 8051 will run on the 8052, but not the other way around since some features of the 8052 do not exist in the 8051 . The extra 128 bytes of RAM helps the 8051/ 52 C compiler to manage its registers and resources much more effectively . Since the vast m ajority of the new versions of the 8051 such as DS89C4x0 are re~Jly based on 8052 architecture, you should compile your C programs for ~ e 8052 microcontroller. We do that by (1) using the reg52.h header file, and (2) choosing the 8052 option w hen com pil1t1g the program.
-
IOs1 PROGRAMMING INC
179
'
·ne the contents of the code 6Pace
r E,arru on
Example 7-32
_,..m on your"""' Compile and $11\gle-step the following P•vo·-· to locate the ASCII values Solution: •include vo1d main (void}
I code
unsigned char mynum [l = "ABCDEF";
'
//uses code space //for: data
I I
,,-
unsigned char z: for(z•O;Z<•6;z++l
Pl=mynum(zl;
J
· h code space to locate values 41 H, 42H, 43H,44H: Run the above program o n your 8051simulator and examine t e • etc.• the hex values for ASCII characters of 'A', 'B', 'C:, and so on.
Accessing code data space in 8051 C In all our 8051 C examples so far, byte-size variables were stored in the 128 bytes of RA,"1. To make the C compiler use the code space instead of the RA,"1 space, we need to put the keyword code in front of the variable declaration. The following arc some examples: code unsigned char mynum(l• "01234SABCD"; code unsigned char weekdays=7, month=Oxl2;
//use code space I /use code space
Example 7-32 shows how to use code space for data in 8051 C.
Compiler variations L~k at Example 7-33. It shows three different versions of 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 proM1croD1g1taJEd.com for 8051 C compilers. ex e s ize to see the effectiveness of your C compiler. See www.
c
Example 7-33 Compare and controst the following programs and d '
{a) •include
ISCUSs the advanta
ges and disadvantages of each one.
void main(void)
I Pl•' H';
Pl•• 8'; Pl•'L'; Pl•'L'; Pl• '0';
l .
176
.
I
• i
•• "• '
(b)
#include void main(void) { unsigned char mydata[]="HELLO" ; unsigned char z; for(z=O;Z<=S;z+ +) Pl=mydata[z]; } (c)
#include void main(void) { //Notice Keyword code code unsigned char mydata( ]= "HELLO"; unsigned char z; for(z=O;z<=S;z++) Pl=mydata[z];
l Solution: All the programs send out "HELLO'' to Pl, one character at a time, but they do it in different \vays. The first one is short and simple, but the individual characters are embedded into the program. If we change the characters, the whole program changes. It also mixes the code and data together. The second one uses the RAM data space to store array elements, therefore the size of the array is limited. The third one uses a separ ate area of the code space for data. This allows the size of the array to be as long as you want if you have the on-chip ROM. However, the more code space you use for data, the less space is left for your program code. Both programs (b) and (c) are easily upgradable if we want to change the string itself or make it longer. That is not the case for program (a).
See the following Web sites for 8051 C compilers: www.MlcroDlgltalEd.com www.8052.com
Review Questions 1· 2· 3. 4·
The 8051 has bytes of data RAM, while the 8052 has The 8051 has K bytes of code space and K bytes. True or false. The code space can be used for data but the e t l bytes of external data space. Which space would yo~ use to declare the following value: ~data,space cannot be used for code. 8 1 (a) the number of days m the week 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?
t::"
80s1 PROGRAMMING IN C
177
\
'
8051 C . through a single pin of microcontroller. '1'1.. ne bit at a 1111te "14!!,
SECTION 7.6: DATA SERIALIZATI ON US ING 0
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~
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 . and control the sequence of data and d ta one bit a tu:ne . J . s~ 2. The second method or serializing data is to transfer a LCD, ADC, and ROM the sena versions are beco I
m between them. In many new generations of dev1~ s~ch as ing popular since they take less space on a printed c1rcu1t boafd.
Dl-
-
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 .
'
} }
l
07
PIN
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
. .
//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 •
178
OX44.
'
e MSB should go out first.
unsigned char x; ACC = conbyte; for(x=O; X
{
PlbO = regAMSB; ACC = ACC << l;
} }
J
Example 7-36 . . ·a Pl O The LSB should come in first. Write a C program to bring in a byte of data serially one bit at a time v1 ..
•
Solution:
//BRINGING IN DATA VIA Pl.O (SHIFTING RIGHT) #include sbit PlbO = PlAO; sbit ACCMSB = ACCA7; void main (void) { unsigned char conbyte = Ox44; unsigned char x; for(x=O; X<8; x++)
'
•
{ ACCMSB - PlbO; ACC = ACC >> l; } P2=ACC;
}
'
PIN
I
Pl.QI~~.. ,L..-_.._I_ _
R_EGA - - - L - '__.~,
07
DO '
Example 7-37
Write a C program to bring in a byte of data serially one bit at a time via Pl.O. The MSB should come in firaL Solution:
//BRINGING DATA IM VIA Pl .O (SHIFTING LEFT) #include Bbit PlbO. PlAO; &bit regALSB • ACC"'O; Void main (void) ( unsigned char x,
--
8051
PROGRAMMING IN C
1'19
'
~
F
'
t f
~,
for(xsO; x<8; x++) ( regALSB • PlbO; 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 . d alt with 8051 C programming, e~aent. In addition, some_ : C. We also compared and (l)f!, 51 This chapt~r e AND OR XOR, and comp em t and conversions m . 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. 3
c
PROBLEMS I•
SECTION7.l:DATATYPESANDTIMEDELAYIN8051 . . . I. Indicate what data type you would use for each or the following vanables. (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; (e) Pl=J2;
••
(b) Pl•OX18; (f)Pl•OX45;
(c) Pl•' A' ; (g) Pl•25S;
(d) Pl•7; (h) Pl:OxOP;
3. Give three factors that can affect time delay code siie in the 8051 mkrocontroUer. 4. Of the three factors in Problem 3, which one can be set by the system designer? s. Can the programmer set the number of clock cycles used to execute an instruction? Explain your answer. 6. Explain why various 8051 C compilers produce different hex file sizes. SECTION 7.2: l/0 PROGRAMMING IN 8051 C 7. What is the difference between the sbit and bit dam types? 8. Write an 8051 C program lo toggle all bits of Pi every 200 ms 9. Use your 8051 C compiler lo see the shortest time delay th · IO. Write a time delay function for JOO ms. a1 you can Produce. II. Write an 8051 C program to toggle only bit Pt.3 every 200 12. Write an 8051 C program to count up Pl from O. 99 co tinms. n uousty. SECTION 7.3: LOGIC OPERATIONS IN 8051 C 13. lndkate the data on the ports for each of the followin Note: The operations are independent of each other. g.
'i
(a) Pl•OxFO:Ox4 5; (b) Pl•OXFO&Ox 56 ; (c) Pl=O xPO Ox76; (d ) P2=0xFO&Ox 90 ; (f) P2=0xFO I Ox 90; (e) P2•0xFO'Ox90; (g)P2•0xFO&Ox FF; (h)P2=0 x FOJOx99; (i) P2:0xFO'OxEE; (j) P2=0xFO'OxAA; . It Find the contents of the port a fter each of the fo Uo wing opera tions. (a) Pl=Ox 65&0x76 ; (b) Pl=Ox 70 J Ox6B ; (c) P2=0X95'0xAA; {d ) P2=0x 5D&Ox 78; (e) P2=0xCS I Oxl2; (f) PO•Ox6 A· o x 6E; (g) Pl=Ox37 J Ox26;
15. find the port value after each of the following is executed. (a) Pl•Ox65>>2; (b) P2=0x39<<2; (c) Pl•Ox04>>3; (d) Pl•OxA7<<2; 16. Show the C code to swap Ox95 to make it Ox59. 17 Write a C program that finds the number of zeros in an 8-bit data item. th 18: Astepper motor uses the following sequence o f blnary numbers to move the motor. How would you generate · em
in 8051 C? 1100.0110.0011,1001
SECTION 7.4: DATA CONVERSION PROGRAMS IN 8051 C
19. Write a program to convert the following series of packed BCD numbe rs to ASCil. Assume that the packed BCD is located in da ta RAM. 76H, 87H, 98H, 4 3H 20. Write a p rogram to convert the fo llowing series o f ASCLI numbers to p acked BCD. Assume that the ASCil data is located in da ta RAM. ·8767"
21. Write a p rogram to get an8-bit binary number fro m Pl,convert itto ASCLI, and save the result if the input is packed
BCD of 00 - Ox99. Assume Pl has 1000 1001 binary as input. SECTION 7.5: ACCESSING CODE ROM SPAC61N 8051 C 22. Indicate what memory (embedded, data RAM., or code ROM space) you would use for the following variables: (a) the tempe rature (b) the number of days in week (c) the number of days in a year (d) the number o f months in a year (e} the counter to keep the number of people getting on a bus (I) the counter to keep the number of people going to a class (g) an add ress of 64.K bytes RAM space (h) the voltage (i) a string for a message to welcome people to building ?3. Discuss why the total size of your 8051 C variables should not exceed 100 b 1 24. Why do we use the ROM code space for video game characters and shape es. 5 25. What ~s the drawback of using RAM data space for 8051 C variables? ~ What 1s the drawback of using ROM code space for 8051 C data? · Wnte an 8051 C program to send your first and last names to P2 · Use ROM code space.
j
ANSWERS TO REVIEW QUESTIONS SECJ10N 7.1: DATA TYPES AND TIME DELAY IN 8051 C
~
0 to255 for unsigned char and-128 to +127 for signed char l OUto ~.535 for unsigned int and -32,768 to +32.767 for signed · t · ns1gned char '" t True S. (a) Crystal frequency of 8051 system, (b) 8051 machine cyd ti . --. e rrung, and (c) compiler use for 8051 C
8osi PROGRAMMING IN C 181
•
'
ING !N 8051 C SECTION 71: f/0 PROGRI\MM 1. 90H
2. #include
/
void mainO
l
P2 = Ox55; P2=0xAA
I
3. #include sbit PlObit= Pl "0; void mainO
L
l
7
,,•
/
P10bit =0; PIObit = 1;
I
4. False, only to SFR bit s. True
r
f • l
SECTION 7.3: LOGIC OPERATIONS IN 8051 C ). (a) 02 (b) FFH (c) FDH
2. Zeros 3. One 4. All zeros 5. 66H
SECTION 7.4: DATA CONVERSION PROGRAMS IN 8051 C 1. (a) ISH = 0001 0101 packed BCD, 0000 0001,0000 0101 unpacked BCD (b) 99H =10011001 packed BCD, 00001001,00001001 unpacked BCD 2. 3736H = 00110111 00110110B and in BCD we have 76H = Olli 01108 3. 36H, 37H 4. Yes, since A= 39H 5. Space savings 6. ASCU 7. ASCll 8. 21CH 9. 00 10. First convert from binary to decimal, then to ASCD, th en send to screen.
SECTION 7.5: ACCESSING CODE ROM SPACE IN 8051 C I. 128,256 2. 641<, 64K
3. True 4. (a) data space, (b) data space, (c) RAM space 5. The compiler starts storing variables in codespace.
182
ilill sos1 M1cR.ocoN1' ROLLER AND EMBEDDED
-
sYSTfil'IS
\
CHAPTERS
8051 HARDWARE CONNECTION AND INTEL HEX FILE
OBJECTIVES Upon completion of this chapter, you will be able to: )I, )I, )I, )I, )I, )I, )I, )I,
Explain the purpose of each pin of the 8051 microcontroller Show the hardware connection of the 8051 chip Explain how to design an 8051-based system Show the design of the DS89C4x0 Trainer Code the test program in Assembly and C for testing the DS89C4x0 Show how to delete programs from DS89C4x0 flash RO · M usmg PC HyperTerminal Show how to download programs into a DS89C4 0 Explain the Intel hex file x system using PC HyperTerminal
183
'
.based systems· .1n the first 5ection 8051 ting and tesbllg hatd ware connection for an 805! 1 ."I .
This chapter describes the process of phy~icallY connecd section si,o,vs
:11• ~
10
:e?"'"·
describe the function of the pins of 8051 ch•P· shO'"s hO'" . 1 using the D589C4x0 (D589C420/ 30/ 40/ 50} chiP· 1 . the charactensbCS system using PC HyperTenninaJ, In Section 8.3 we exp all1
1oad programs into a DS89C~~ ·• """I 0 f the Intel hex file.
.n
SECTION 8.1: PIN DESCRIPTION Of THE 80S,1 D589C4JC0) come u, different packages, 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~ 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/~
t11te~t, f
r
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 2 Examining Figure 8-1, note that of the 40 pins, a total of 32 pins are set as, e ' ' , and PJ, 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 3
l'O.O (ADO)
4
5 6
PO.I (AOl) 8051152
P0.2 (AD2)
P0.3 (A03) P0.4 (A04)
Pl .7
P0.5(AD5)
RST
P0.6(AD6)
(RXOJ P3.0
P0.7 (AD7)
(l'XD) P3.J {IN11)) 1'3.2
EA/VPP
CINTl) 1'3.3 {TO) PJ.4 (Tt) P3.5
!>SEN
(WR) P3.6
(RD) 1'3.7
ALE/PROG
1'2.7 (AlS)
27 26 25
P2.6 (Al4) P2.S (Al3) P2.4 (Al2)
24
XTALI
23
CNO
22
P23(All) P2.2 (AlO)
1'2.1 (A9)
21
1'2.o (A8)
Figure 8-1 . 8051 Pin Diagram
184
TliEsos1 ~ 'Clloco
Nl'ROLLl!R.
-
ANO EMBEDDED S ~
C2 ", ; 30 pF
(JNO Pin 20 is the ground.
-
XTAL2
-
D
tfAL.1 and XTAL.2 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 each capacitor is connected to the ground as shown in Figure 8-2 (a). . It must be noted that there are various speeds of the 8051 fanuly. Speed refers to the maximum oscillator frequency connected to XTAL. for example, a 12-MHz chip must be connected to a crystal with 12 MHz frequency or less. Likewise, a 20-MHz nucrocontrolle r requires a crystal frequency of no more U,an 20 MHz. When the 8051 is connected to a aystal oscillator and is powered up, we can observe the frequency on the XTAL2 pin using the oscilloscope. I( you decide to use a frequency source other than a crystal oscillator, such as a TIL oscillator, it will be connected to XTALl; XTAL2 is left unconnected, as shown in Figure 8-2 (b).
I
Cl
.__ _,/'L-f_ __.__ _ _I
30 pF
XTALl
GND
Figure 8-2 (a). XTAL Connection to 8051
NC
- - - - -1 XTAL2
RST Pin 9 is the RESET pin. It is an input and is active high (normally low). Upon applying a high pulse to this pin, the mkrocontroller will reset and terminate a ll activities. This is often referred to as a power-on r
EXTERNAL OSCILLATOR - - - - 1 XTALl SIGNAL ,------1
GND
figu.re 8-2 (b). XTAL Connection to an External Oock Source
Vee
+
31 10 aµJ'
31
30pf 8.2 K
D
ll.OS92MHz
JO pf
19
18 9
EA/VPP
19
EA/VPP
lOµF
XI
Xl 30pF
.
X2
RST
30pF
D
18
X2
9 RST
8.2 1< tigure 8-3 < •). Power-On RESET Cimall -
Fi~
&-3 (b), Power-On RESET with Momentary Swikh
lls1 liAR.ow
ARE CONNECTION AND lNTEL HEX FILE
115
I
t of time that depends on the capa . in high for ~mount be held high long enough Lo 5 ·When power is turned on, the circuit holds the ~ ; reset the RsT pill ':'1° and a 10-µF capacitor will take ca the 1 value and the rate at which it charges. To ens'!'e a h, s.21<-olun res : '1 ou are using. l"eq oscillator to start up plus two machine cycles. Alth ; data sheet for the Y the vast majority of the cases. you still need to check t e
an
anO:to,
":u an
,,,
p
EA
come with on-chip ROM to store programs. O II The8051 family members• suchas· the875J / 52,S9C5J/ 52, or [)589Cd4Xas ,thae 8031 and 8032thin which • t,ers SU 1 . · there is beno on~•• ""P In such rues, the !A pin is coMecled to Vcc· For family mem · Therefore for the 8031 e t r \ pin must c o ~ 32 ROM,codeisstoredonanextemal ROM and is fetched b__l' theB03l/ f r ''ext~rnal access," is pin number 31 in the DIP to GND to indicate that the code is stored externally. ~· which sti~ ~ other words, it cannot be left unconnected. packages. It is an input pin and must be coMected to e1the~ Vct; or ~ith PSE/q to access programs stored in ROI In Chapter 14, we will show how the 8031 uses this !"n alMong h the 8751 / 52, 89C51/52, or 0589(4 xO memory located outside the 8031. In 8051 crups with on-chip RO , sue as • OIi is COMected to Vrx• as we will see in the next section. . b 15 . used The next f:\vo · The pins discussed so far must be connected no matter which family mem er . •• . .P~ are USl'd mainly in 8031-based systems and are discussed in more detail in Chapter 14. The following 1s a bnef description of each.
d
l
~
I
.
.
PSEN_ . 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
sa~·:
" ~~
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~
Ports O, 1, 2 and 3
As shown in Figure 8-1 (and discussed . Ch 0 ~o~fig::::~:ii::::e 1 e matenals Ill Chapter 4.
!~~:~t:!:~.::i~;~~~~.5~ ~~e
:_Pg3:!~1;:.:ru!
:~ch uthse 8 pThins, makin~ lh_em on em. e foUowmg IS a
PO As shown in Figure 8-l . as ADO - AD7 allow· . ' port O is also designated
and data. Wh;n conn~~ to be used /or both address memory, port O provides fo: ~~1/31 to an extemal 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 plex111g address and data with th ~ ~ for demulilatch, as we will see in Chapter 14. e p of a 74LS373 t~ms where there ,s no extemaI mem:e 8051-based syspms of PO must be connected ry connection, the uJI • externally t o a 1OK-ohm P -up resistor. This ls due to th i drain, unlike Pl, P2, and P3 0 e act ~at PO is an Open /or MOS chips in the same w~ pen dram is a term use for ITL chips. In many syste?:.stha1_opt11 collector is use:: or DS89C4x0 chips, we normaU using the 8751, 89Cs1 resistors. See Figure .,.... • ., w·th' Y connect r extemal puJJPO to pull-up' -up resistors
i
186
T!il!
Vcc
. ~ ..; •. ~: > ~
8051152
PO.O PO.I P0.2
-- ~. ;:~
.:: >~
< ><
-:':>
•
'
:> • >
10 K
.::• > <~> >< ~
.
>.
P0.3 P0.4
PO.s P0.6 l'0.7
Fig.,,. S-4
• Po11 o wl th
80SJ M1cao
Puu-u
.
P Resistors
CONTROLLER
_.
AND EMBEDDED SYS,vas
<
•
•
''
II
.
.
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 . h PO to provide the 16-bit 1 s031 /5J-based systems with external memory connections, po~t 2 must~ used a ong _w•~ 5 indicatin its dual funcaddress 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 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.
t
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 RxD 10 !or 1/0 while the rest of the pins in port 3 are normally used in the P3.0 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 be lost. Table 8-2 provides a partial list or 8051 registers and their vallleS after power-on reset From Table 8-2 we note that the value of the PC (program counter) is Oupon reset, forcing the CPU to fetch the first opcode from ROM memory location 0000. This means that we must place the first byte of opcode in ROM location Obecause that is where the CPU expects to find the first instruction.
P3.4
TO
14
P3.5
TI
15
P3.6
WR
16
Machine cycle and crystal frequency As we discussed in Chapter 3, the 8051 uses one or more machin 1 ~te an instruction. The period of machine cycle varies am e c~c es to :~•ons of 8051 from 12 clocks in the AT89C51 to l clock. thonDS8gthe different = . m eto th 9C4x0 chip d' tal'able 8-3· Th e frequency o f the crystal oscillator connected X . · ~cites the speed of the clock used in the machine cycle. Prom Tabl: • X2 pins 'nd :!,~!!'at using the same crystal frequency of 12 MHz for both th8-3, we can d1i ~"""'-4x0 chips gives performance almost 12 times bett e AT89CS1 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 -..,,.,., tn Chapter 3. 9C4xQ chips as we
---
-RD
P3.7
17
Table 8-2: RESET Value of Some 8051 Registers Regis ter
PC
DPTR ACC
PSW
Reset Value (hex)
0000 0000 00 00
SP
07
B
00
PO-P3
FF
llls1 HAR
OW ARE CONNl!CTION ANO JNT1!L HEX FILI!
187
I .
Table 8-3: Clocks per Machine
eyde (MC
. B051 Versions ) for Vanous Machine Cycle
Clocks per 12
Chip (Maker) AT89C51 / S2 (Atmel)
6 4
P89C5.JX2 (Phillips) OSSOOO (Dallas Semiconductor)
l
0589C4x0 (Dallas Semiconductor)
l Example 8-1 . . if the )CTAL frequency .15 22.MJ-lz . Find the madune cycle (MC) for the:owing chips a) AT69C51 b) DS89C4XO c) D5S
l
,, I.
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
2. 3. 4.
5.
X'TAL2pins? . ? Which pin is used to infonn the 8051 that the on
SECTION 8.2: DESIGN AND TEST OF DS89C4x0 TRAINER In lhlsse<:tion we show COMeclions for 8051-based systems using chips s uch as the AT89C5l and DS89C-1x0. If you decide to wire-wrap one of these, make sure that you read Appendix Bon wire wrapping.
AT89C51/52-based trainer connection In systems based on an A T89C51 /52-type microcontroller you eed RO · the microcontroller. For the AT89C5J, !he ROM burner can erase 'th nn a _M bu mer to burn your program mto . In the case of the 8751, you also need an EPROM erasure tool ,. e ~sh ROM m addilion to burning a program into 11. erase its contents first, which takes approximately 20 minut s~ce~uses UV-EPROM. To bum the 8751, you need to since it has flash ROM. es or ·EPROM. For the A T89C5t, this is not requi...,.J Figure 8.5 shows the minimum connection for the 8751 89CS 0 an 8751 or 89C51 has on
use a;
The DS89C4x0 chip from Maxim/Dallas Semicond . also has a built-in loader allowing it to download ro uctor '.5 ~ 8051 type rn.icr . It need for an external ROM burner. This important fea~arns into the chip via th O<:o~trolJer with on-dup Oash ROM home development systems. re ma.kes the DS8gc x ~ s_enaJ ~ort, therefore climinabng_~\ 40 hip an idea.I candidate for 8051-ba><"
188
llill sos1 MICR 0CONTRo
-•~ LLER AND EMBEDDED SYST~1" "
r
. Fl h ROM Size for Table 8-4: On-CbJp as M ·m-DaJlas c xo flash ROM size 4 F ily from aXJ 89 0 am WWW maxim-ic.com the DSS9C4x 1)5 . 11 DS89C4x0 chips share the same features, they S miconductor. See · W~~ ~ifferent amounts of on-chip ROM. Table 8-4sho~s e On-chip ROM size (flash)
eome'.:'i,· ROM size for various DS89C4x0 chips. Refer tot_ e 00 the . maxim•ic.com for further information. Nobce ..-eb s,ht .1 the T89CS1 comes with 4K bytes of on-chip ROM, 0 ,1 w 1 e ... e AT89C52 comes ,vith SK bytes, the DS89C4x0 has . ~ ,nd ~htesof on-chip ROM. Also notice that the DS89C430 15 3 16 ym.ent for the DS89C420 with the bugs fixed. repK1ace
e:vwA
Chip DS89C420/30
16K bytes
321< bytes
DS89C440
64.K bytes
DS89C450
Vee >
+ -~
>
~~:;~:.E:E~i .. >-
8751/89CS1
~ 10 uF
10 K > ? .> -?
"I
..
..
..
r--,--- - -- ~ u >-+--l--1f-+ --t-t-1 rl , EA / VPP P0.0 ~ - --+ -t-J-T"°i"- I " : >:: 30 p'F l 19 Xl PP00.2l ~ - - _..-1r + -t-r , ~ :> 0 11.0592 MHz P0..3 ~ - - -~._+ -t-f-1 ° 8.2 K T 1--- - ---4- r - t - 1 ...___._, ·~ - - - - -"'.".:4 X2 P0.4 l--- - -- -- - -t--r-
_:
31
1
',
30 pF
1s 9
ro.s 1----
RST
P0.6 l'0.7
------ - r
1-- - -- - -- ----
P3.0/ RXD P3.1 / 1XQ. P3.2/ ll:itl) P3.3/ INT1 P3.4/ TO P3.5/T1
PLO Pl. 1 Pl.2 Pl.3 Pl.4 Pl.5 Pl.6 Pl.7
P2.0 P2.I 1'2.2
1'2.3 1'2.4 1'2.5 1'2.6 1'2.7
PSEN ALE/ PROG
P3.6 \'ill._ P3.7/ RD
Figu,. S.S. Minimum Connection for89CS1/52-Based Systems
~mpteS-2
Find the address space for the on-chip ROM of the following chips. (a) AT89C51, (b) AT89C52, and (c) D589C420/30 Solution:
{a) AT89C51 has 4K bytes of on-chip ROM. That giV< 1024 = 4.()96 bytes. Converting the 4096 to hex, we get IOOOH. Therefore, the address space Is 0000 • OPPFH. (bJ AT8< 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 frOOld thhe S 0 w how to use them bi chI'p taken 9(4,<0 1:tJfe5 an of the [)58 of t/leSI! fea
f the OS89C4x0 th key featuJCS k at manY some of e The following are axim-ic.com,) We will loo
Key features o webs1' te
(http://www.m
chapters.
SOCS2 compatible
mpatible truction-set co (a) 8051 1 l/ 0 ports (b) Four 1'6-b'I t timer counters (c) Three d RAM (d) 256 bytes scratchpa 2. On-chip flash memory (a) 16KB for OS89C4lO/JO (b) 32KB for OSS9C440
~i-~::::
1.
l 1
t.
•
.
(c) 64KB for DS89C4SO h the serial port 3. ln-system progra aunable throug
,...
lKB SRAM for MOVX 4
.
f
ROMSIZE Feature ize from Oto 64K al gram memory s (a) Selects intern pro . external memory map (b) Allows access t~ entib~ b software (c) Dynamically ad1usta e Y
S. High-speed architecture cl (a) 1 clock per machine ~y e (b) IX to 33MHz opera_tio~ (c) Single-cycle ~tructlon m 30 ~ to access fast/ slow peripherals (d) Optional vanable length MO 6. Two full-duplex serial ports 7. Programmable watchdog timer
8. 13 interrupt sources (six external)
9. Five levels of interrupt priority
10. Power-fail reset 11. Early warning power-fail interrupt
0589c4x0 trainer connection
.
We selected the DS89C4x0 for an 8051 Tr~iner because it is inexpensive but powerful, and one can easily wueit to be used at work and h~me. The connection for the DS89C4xO Trainer is shown in Figure 8-6. lf you decide notweb to "'.'re-wrap the tramer yourself, you can buy this DS89C4xO-based Trainer from the MicroDigitaLEd.com site. . two Using major the reasons. D589C4x0 for development IS more advantageous than using the I.
8751
or S9CSl systeo, for the foll
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?' in a much longer development time for the 89Cs1 system Program contents of the on-chip ROM. ThlS t . With the Dss9c4xO system. 411' The two serial ports on the DS89C4x0 allow us to~ onecompared
~
~
2 .
acquisition.
190
Or Pc tnterfactng With the chip, and the other fer
~:::-::--------:::-::-.:
Nl'R.otLER. AND EMBEDDED
+5V
+SV
~
i~
~~
T
DB·9F
-j 11-lOuF
VCC
'--"--- -- - -- -------1 RST
~
5
2 TxDl---t~
4
8.2k
2
30
+SV
5
lk
Ty
DS89C4x0 lk J,-----1 D. 10k t - -;:,;;;.-1:'. 2N3904 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
=
=
GND XTAL21-.-..- - - IH 11.0592 MHz =
figure S-6. DS89C4x0 Trainer (for MAX232 connection, see Section 10.2)
Notice from Figure 8-6 that the reset circuitry and serial porl connections a re the sam e as in any 8051-based system. However, the extra circuitry needed for programntlng are two transistors, a switch, and !OK and lK-o hm resistors. 1n fact, you can add these components to your 8751/89C51 system and use it as a DS89C4x0 system by simply plugging • D589C4x0 chip in the socket. The switch allows you to select between the program and run options. We can load our program into the DS89C4x0 by setting the switch to VCC' and run the program by setting it to Gnd . FigureS-Oshows the connection for the8051 Trainer from www.MicroDigitalEd.com. The Trainer provided by this web site has both of the serial ports connected and accessible via two DB-9 connectors. It also has 8 LEDs and 8 switches along with the PO - P3 ports, all of which are accessible via terminal blocks. It also comes with an on-board power regulator.
See the following Web site for the OS89C4x0 Trainer: www.MlcroOlg ltalEd.com
Communicating with the DS89C4x0 trainer Alter we build o ur DS89C4x0-based system, we can communicate with it usin th H T . HyperTerminal comes with Microsoft Windows 98, NT, 2000, and XP. g e yper errruna l software.
Using HyperTerminsl with the DS89C4x0
'?55Uming that your serial cable has a DB-9 connector on both end . mun,cation between the DS89C4x0 Trainer and HyperTerminal. s, we take the foUow,ng steps to establish com-
1.
With the trainer's power off, connect the COMl port on the back of
PC 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-
2. Th
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 •
DS-S9C'420 LCAD~
vtR,SJGJil 1.0
l
,, \,
'
:'<>•-•01 ,
.WO Of*,I
57&00 I H 1
. J for OS89C4x0 Trainer Figure ~7. Saeen Cipture from Hypt.rTenmna
•
Type a name, and dick OK (or HyperTem1inal will not let you go on). ::
For "Connect Using" select COM1 and dick OK. Choose COM2 if COMl is used by the mouse.
6.
Pick 9600 baud rate, 8-bit data, no parity bit, and l stop bit.
7.
Change the "Flow Control" to NONE or Xon/Xoff, and click OK (Definitely do not choose th~ hardware optiml 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>
8.
If you do not see">" after pressing the ENTER key several times, go through the above steps one more time. lllll. if you do not get">", you ~eed.to check your hardware connections, such as the MAX232/233. See the end of thi,!lt' tion for some troubleshooting bps.
I
t t
' I
Loading and running a program with the DS89C4x0 Trainer
I I I I
After we get the">" from the DS89C4x0, we are ready t 1 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 15 provided by your 8051 assembler I compiler., about Intel hex format 1s given m the next section.
I
Erase command for the DS89C4xO
'
To reload ~ DS89C4x0 chip with another progr . wiU erase the entire contents of the flash ROM of the~- we first nee.i to e . the ROM before you can reload any progra1t1. You chip. Remember that rase Its contents. The K (Klean) c·Ollll!lm command to display ROM contents on sereen. y 0 verily the operati you rnust use the ">K" comma11d to ">K" command. s Ould see aU FF . on of the ">1<" command by using the 5 Go to www.MicroOigitalEd.com to see the above steps an all the locations of ROM after applyil1
i•~
192
Presented with screen shots.
''
'
ding the program
L08
..
h
After making sure that you have the switch on the program position and you ave
th ">" prompt on your screen, e
go thrOugh the following steps to load a program: 1.
At the ">" prompt, enter L (L is for Load). Example: ">L" and press Enter. Ill HyperTenninal, click on the Transfer menu option. Click on Send Text File.
2, 3- Select your file from your disk. Example: "C:test.hex"
d ,. \,Vail until the loading is complete. The appearance of the "GGGG>" prompt indicates that the loading is good an finished. 5 Now use D to dump the contents of the flash ROM of the D589C4x0 onto the screen. Example: >D 00 4F . The durnp will give you the opcodes and operands of all the instructions in your program. You can comp~re this information with the information provided by the list file. In the next section, we will examine the Intel hex file and compare it with the list file or the test program.
Running the program Change the switch to the run position, press the reset button on the D589C4x0 system, and the program will execute. Use a logic probe (or scope) to see the PO, Pl, and P2 bits toggle "on" and "off" continuously with some delay in between the "ON" and "OFF" states.
Test program for the DS89C4x0 in Assembly and C To test your DS89C4x0 hardware connection, we can run a simple test in which all the bits of PO, Pl, a.nd P2 tog· gle continuously with some delay in-between the "on" and "off" states. The programs for testing the trainer in both Assembly and C_ are provided below. N_otice that the tin,e delay is for a D589C4x0 based on the 11.0592 MHz crysta l freque~cy. Th,s tlJl'le delay must be modified for the AT89C51 /52 chips since DS89C4x0 uses a machine cycle of 1 clock penod instead of the 12 clock periods used by the AT89CSI /52 chip.
Trainer Test Program in Assembly AAIN:
ORG OH MOV PO, #SSH MOV Pl, #SSH MOV P2, #SSH MOV RS, #250 ACALL MSOELAY MOV PO, #OAAH MOV Pl, #OAAH MOV P2, #OAAH MOV RS, #250 ACALL MSOELAY SJMP MAIN
; ·-- · -· ·· --250 MILLISECOND DELAY MSDELAY: l!ERE3: MOV R4,
HERB2:
MOV Rl,
H1!RE1:
DJNZ R3,
#35 #79
HBREl OJNZ R4 , HERE2
DJNZ RS, HEREl RET
---
END MAIN
IOsi ll>.Row ARE CONNECTION AND INTEL HEX FILE
193
•
I Trainer Test Program In C #include d void MSOelay~unsigne intl; void main (void) fo:reve:r { //repeat while(l ) o Port { //send value t PO•Ox55; Pl=OxSS; function P2=0x55; //call 2SO m:o port MS0elay(2SO}; //set value PO= OxAA; Pl= OxAA; P2 • OxAA;
//call 250 ms
MS0elay(250l;
function
) ) . d void MSDelay (uns19ne
l•
nt itimel
{ . . unsigned int 1, J; for(i•O;icitime; i++) for lj•O ;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 Dumps the Intel hex file.
we have shown the use of the L (load), I< (klean), and D (dump) commands earlier. A complete list of col!U!W'li and error messages can be obtained from www.MicroDigitalEd.com. Some troubleshooting tips Running the test program on your DS89Cx0-based trainer (or 805! s ) . with di delay. If your system does not work, follow these steps to c_d th ystem should toggle all the I/0 bits w, e problem. L With the power off, check your connection for all pins es ·a11 Check RST (pin 119) using an oscilloscope. When the' pea .y Vcc and GNO· ... system IS po momentary sw,·1ch •'t goes high . M·'· .u.e sure the momentary Switch . wered up, pin #9 is low. Upon press•;,a .., .. 3. Observe the XTAl.2 pin on the oscilloscope while th . IS connected properly. cates that the crystal oscillator is good. • Power is on. You should Thissee a crude square wave. 4. If all the above steps pass inspection, check the c must be the same as the opcodes provided by the ~~t~ts of the on"(.tup . ~I Lists the opcodes and operands on the left side of ht £iJe of l'i&ure • y ROM starting at memory locabon ~ 8 8 .0 Ur assembler produces the list filt~ of your on-chip ROM if the proper steps were tak t ~ •SSell\bly instri; 2.
en 194
10
bllrning and lo~~~ns. This must match exactly the ~ ing the program into the on
-
LOC
OBJ
LINS
ORG OH
0000
l
0000 758055
2
0003 759055
3
0006 75A055
4
0009 70PA
5
0008 lllC
6
0000 7580AA
7
0010 7590AA
8
0 013 75AOAA
9
0016 70FA
10
MOV P2, #OAAH MOV RS, #250
0018 lllC
11
ACALL MSDELA'i
OOlA 8084
12
SJMP MAIN
OOlC 7C23 OOlE 7B4F 0020 OBFE 0022 OCFA 0024 OOF6 0026 22
MAIN:
MOV PO, #SSH MOV Pl, #SSH MOV P2, #SSH MOV RS, #250 ACALL MSDELAY MOV PO, #OAAH MOV Pl, #OAAH
OELAY. 13 •.•. · THE 250 MILLISECOND MSOELAY: 14 MOV R4, #35 HERE3: 15 MOV R3,#79 HERE2: 16 17
HEREl:
18 19 20 21
OJNZ R3, HEREl OJNZ R4, HERE2 OJNZ RS, HERE3
RET ENO
Figure S.S. Lisi File ForTes l Program (Assembly)
Review Questions I. True or false. The DS89C4x0 is an 8052 chip. 2. Which pin is used for reset?
3. Whal is the status of the reset pin when it is not activated? t What kind of ROM is used in the DS89C4x0 chip? . S. The loader for the DS89C4x0 works with the (senal, parallel) port. 6. Give two reasons that the DS89C4x0 is preferable over 89C51 crops. 7. ln the DS89C4x0 Trainer, what is the role of the Prog/Rw, switch? 8. What is the highest frequency that we can connect to the DS89C420/30? 9. True or false. The DS89C4x0 can download the file into its ROM only if it is in Intel hex file format. 10. Which command is used to erase the contents of ROM in the DS89C4x0 chip? II. Which command is used to load the ROM in the DS89C4x0 chip? 12. Which command is used to dump the contents of ROM in the DS89C4x0 chip?
SECTION 8.3: EXPLAINING THE INTEL HEX FILE Intel hex file is a widely used file format designed to standardize the loading of executable machine codes into a ~OM chip. Therefore, loaders that come with every ROM burner (programmer) support the Intel hex file format While In ll\any newer Windows-based assemblers the lntel hex file is produced automatically (by selecting the right setting), Ina Dos.based PC you need a utility caUed OH (?bject-to-hex) to produce that. In the IX)S environment, the object file ~l'dtntothe linker program to produce the abs file; then the abs file is fed into the OH utility to create the Intel hex file. ile the abs file is used by systems ~t have a monitor program, the hex file is used only by the loader of an EPROM l'!Ogramme.r to load it into the ROM crup.
;;;;;:A-R_D_W _AR~E-C_O _N_N~J!C-C-11-0-N-AN~D~IN-TE~L-KEX~-A~L-E~~~,__..,.....,.....,_..,.....,.....,.....,.....,.....,.....,.....,.....,..._1~95
I ,v.9f
fA111C7580 &4FOI OO(XXJ(XY7":,&l5Sr:fl()5575A::i11c80E47CZ37 :1 5AOAA ,1000100075~AODf62235 ,07002()0008
,CJ()OOOOO!fF
·ng
.
Id we gel Seperaling the fie s
I
1
,, \,
,cc
AMA
TT
:10 ,10 ,07 ,00
0000 0010 0020 0000
00 00 00 01
th• rouow•
DDDDD DDDDDD
ppDDDDDPD 75SOAA oDDDD:~:~~==75A05S7P:~!!~~2 37B4 P 75805 p.A DFA111C 7590,a.A?SAO 7 OBFEl)CFAPDF622
ss 9F 01 35
FF ssembler
. Te.sl Prograim as Provided by th • A Fig·ure S-9. lntel H,x: File
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 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. hex file. Next, we will analyze the hex file belonging Analyzing Intel hex file h . t file is given in Figure 8-8. Since the ROM bUl!il! 1 w ose is file must provide the f o IIow1ng: · (1) the numbu Figure 8-9 shows the lnteI hex fil e i or the test program . ROM the hex (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> 9, be placed. Each line o( the hex file consists o six parts. n •gu analyze. The foUowing describes ead, part.
s t
• '
-
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).
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 ;n
n
I
address.
4.
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~ 01, it means that this is the last line and the loading should slop after this line.
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
t!
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~ 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
t~t
"""'Suin byte.
'
""·-·
196
l'ltE 80St l\,fJ
Clocol>fr
~--'
lOLLER AND EMBEOOEOSY51....-
•b
ii
iA I I
--
Vrrifi the checksum byte for tine 3 of Figure 8-9. Verify also that the
·ru I
tion is not corrupted. orma
solution:
. th · (5) uives CBH a.nd .,ts 2,s (fl + 00 + 20 + 00 +DB+ FE + DC+ FA+ DD + F6 + 22 = SCBH. Dropping e carries o· ' complement is 35H, wt,Jch is the last byte of Line 3. . h Id et oo. If we add all the information in line 3, including the checksum byte, and drop the carries we s ou g 07 + 00 + 20 + 00 + DB + FE + DC + FA + DD + F6 + 22 + 35 = 6001-1
Example 8-5 Compare the data portion of the Intel hex file of Figure 8-9 with the opcodes in the list file of the test program given in Figure 8-8. Do they match? Solution: In the first line of Figtlfe 8-9, the data portion starts with 75H, the opcode for the instruction "MOV", as shown in the list file of Figure 8-8. The last byte of the data in line 3 of Figure 8-9 is 22, which is the opcode for the "RET" instruction in the list file of Figure 8-8. file formatter. You can run the C language version of the test program and verify its operation. Your C compiler will provide you both the list file and the Intel hex file if you want explore the Intel hex file concept. Examine the next three examples to gain an insight into the Intel hex file.
Review Questions I. True or false. The Intel hex file uses the checksum byte method to ensure data integrity.
2. 3. 4. 5. 6.
The first byte of a line in the Intel hex file represents . The last byte of a line in the lntel hex file represents--- - - In the TT field of the Intel hex file, we have 00. What does it indicate? Find the checksum byte for the following values: 22H, 76H, SFH, SCH, 99H. 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
2 P3, each use 8 pins, making them 8-bit ports. These ports can be used for input or outpp t 0 rt Oe b' O, Pl, P ,. and address or data. Port 3 can be used to provide interrupt and sena · 1 commurucation ~· . . signals Thca.n the used d · for either f uao9C4x0-based trainer was shown. We also explained the Intel hex format. · en e esign o the
..,,. 0
•
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 ' hi ROM such as the 3 If a TfL osciUator ts used, on 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? 17 ALE is u.sed mainly m systems s PO and what are those m th DIP package? 18. How many P'.ns .ire des~gna::: :s Pl and what are those DIP package? 19. How many pms are des~gna . and what are those JJ1 ackage? 20. How many pins are designated a, P2 nd what are those in the D_IP Pt output). 21. How many pin, are designated as P3 a nfi red as (mpu ' 22. Upon RESET, all the bits of ports are co ~or to be used as J/0? d solely for 1/0? 2.1 In the 8051, which port needs a pull-up res IS te function and can be use 2~ \'lhich port of the 8051 does not have any altema
in::
.' t'
{ • I
SECTION 82: DESIGN AND TEST OF DS89C4x0 TRA CNER l
25. What are the functions of pins 1'3.4 and P35? . . _ 8 26. 'A'hy is pm 31 connected to V« for the sy,tcm ,n Figure 51.
j.
• 27. In P3, wluch pins are for RxD and TxD? n RESET? What is the implication of that? 28. At what memory location does the 8051 wake up upo . 29. Write a program to toggle aU the bits of Pl and P2 conbnuous1Y (a) using AAH and 55H (b) using the CPL 1r1Strucbon 30. ~Vhat is the address of the last location of on-<:hip ROM for the AT89C51?, 31 What is the address of the last location of on-chip ROM for the DS89C420. 32. 1-Vhat is the address of the last location of on-chip ROM for the DS89C440; 33. \\'hat is the address of the last location of on-chip ROM for lhe DS89C450. 34 What is the range of frequency allowed for DS89C4x0? 35. \\'hat ,s the slowest frequency lhat D589C4x0 can run on? 36. \Vhat are the functions of pins TxD and RxD? 37. Before we reprogram the DS89C4x0 we must (dump, erase) the flash ROM. 38. How many timers/counters has the DS89C4x0? 39 Give two features of the DS89C4x0 that earlier 8051 and 8052 chips do not have. 40. After downloading a program, the DS89C4x0 gives the message ">GCGG". What does it mean? SECTION 8.3: EXPLAINING THE INTEL HEX FILE 41 What is obtained in the HFX file? 42. In Figure 8.9, what is meant by the column lT?
-13. Verify the checksum byte for lme 1 of Figure 8-9 and also verity th 41.
45.
~47.
. . . Verify the checksum byte for line 2 of Figure g.9 and also ver· at the ~orrnat~on is not corrupted. 1 1 the mforrnanon ,snot corrupted. Reassemble Lhe test program with ORG addr,,>s,, of lOOH and Reassemble the test program w,th ORG address of 300H d na yze the Intel hex file. Write a program to toggle all the b11s of Pl and P2 cont~ oo~pa~ the Intel hex file "~th the results of Problem -15. inuous y with no deldy and analyze the l ntel hex file.
'7 ~·~
ANSWERS TO REVIEW QUESTIONS SECTION 8.1: PIN DESCRIPTJON OF THE 8051 l. From Oto 16 MHz, but no more than L6 MHz
2.
EA
1. PC = ()(JO() -l 0000 5. Port 0 198
TH esos1 MtcRoc o
NTROLL"R '" AND EMBEDDED SYSTE~iS
sECflON 8.2: DESIGN AND TEST OF DS89C4x0 TRAINER 1. True 2. pjn9 3. 1.0,v 4. Flash
s. Serial
6. (a) It comes ,vith a loader inside the chip and (b) it has two serial ports
7. The SW allows to load the program or to run it.
8. 33 MHz 9. True 10. >K 11. >L
12. >D
SECTION 8.2: EXPLA!NING lNTEL THE HEX FILE l. 2. 3. 4. S. 6.
True The number of bytes of data in the line Checksum byte 00 mea.ns this is not the last line and there are more lines of data to be foUowed. 22H + 76H + 5FH +SCH+ 99H = 21CH. Dropping the carries we have lCH and its 2's complement is E4H. 22H + 76H + 5FH +SCH+ 99H + E4 = 300H. Dropping the carries we have 00, which means data is not corrupted.
•
-
IOst IIARDWAll CONNIC110N AND INTEl Hl!X FILE 199
CHAPTER9
8051 TIMER PROGRAMMING IN ASSEMBLY AND C
OBJECTIVES i ' I
Upon completion of th,• chapter, you will be able to:
>
> >
>
List the timers of the 8051 and their associated ~gisters ./ ~ribe the various modes of the 8051 nmcrs Program the 8051 timers ITT Assembly and C to generate timi: delays Program the 8051 counter~ ,n As."
I
, time dday or as counters to, to gener,1 le , . ·"'1r~ <;Cd either a~ timers timers are uS<.>d to general,• trme del.li· The 1,()51 ha< I:\"' tJmcrs/counters They can be~ 9 1 we ,.ee hoW these C language to program the 8051 tin,' In e, enb h•pperung outside the m1crocontr0Uer. l.n ~: ·In 5ection 9.3 we use •ri. Sc>chon 9.2 we show how they are u.sed as event roun
SECTION 9.1: PROGRAMMING 8051 TIMERS . tirnersoraseventcounters. ln this'<'C"bc used either as · d I ..., The so,1 has two tuners: TimerO and Timer t They can th timers to generate tune e ays. we first discuss the timers' registers and then show how to program
e
Basic registers of the timer . timer . . accessed., 8-bit architecture, each 16-bit 1s . · Both Timer Oand Timer J are 16 bits wide. 51.llce the 8051 has an t 1 two separate registers of I~ byte and hip,oyte. Each timer rs drscussed separa e Y·
;
,i
I
r •
Timer O registers 11,c l(l-b1t regi.,ter of Timer ois acce,,ed as tow byte and high byte. The low byte register is called TLO (Timer Oloi, ~yte) ond the high byte register., re/erred to as THO (rimer Ohigh byte). These registers can be accessed like any oi!i;., reg,stt
,n
Timer 1 registers
b~:~) I~!;;';~ ~ts lb·bit regis~cr is split mto two bytes, referred to as TLl (Timer t low byte) .md THI
(flmT:;r;e~~~
·
grs ers are accessible m the same way as the registers of Timer O (See Figure 9-2).
TMOD (timer mode) register Both timers Oand 1 use the same register, called TMOD . . ~·~i~g~;~~which the lower 4 bits are set aside for Timer O~n~tth~euvarrous timer operation modes. TMOD is an 8discu,sed ne,t lo set the nnwr mode and the upper 2 bits to specify T1:;1er 1. In each ca!'oe, the lower e •gure 9-3) These uptions ar~
th:~;:;.~~~ r;
-M1,MOMOand Ml select the timer mode timer, mode I is a 16-bit timer, and
m~::
.
;~so::a'.~;;ilf"re 9-3, there are three modes· tuner. We will concentr t · 0, I, .ind 2. l\1ode O "a 13-b:I aeon modes 1 an d 2 ~tnce they arc !ht
no 03
Figure 9..1. Timero Registers
I I I[)() 02
DI
i:D: =6~F~l ~ T; L ; l ~~==~I :0:S~~D.;~ l ~]l~~I~Q I I
l DIS IDH IDB I D12 j 011 IDtOI D9 I 0s] G~o~7i1 - -figure 9-2. Tim•r 1 R•gi5tcr, 202
:::::·
Dl
D2
DI
DO
j
(
(MS6)
I
..,,-
I CIT I
GATE
I
Ml
GATE
MO
]
CIT
Ml
MO 2.
MO
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
l
I
Ml.
MQ. 0
0
- -.
\,
I
whe11ever the TRx control bit is set. aJ 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). Mode bit I Mode bit 0
err
("'";
Ml
1imer0
Timer 1
GATE
I
(LSB)
~
Mode 0
Operating Mode 13-bit timer mode 8-bit timer/ counter THx wilh TLx as 5-bit prescaJer 16-bit timer mode 16-bit tbner/ c:oun ti,rs THx and TLx .ue cascaded; there is no prescaler 8-bit auto reload 8-bit au to reload timer/coun ter; TH x holds a value that is to be reloaded into TLx each time it overflows. Split timer mode .,
I
I
0
2
1
1
3
..I
Figure 9-J. TMOD Register
ones used most wide!y . We w i ll soon describe the characteristics o f these m o d es, after d escribing the rest of the TMOD reglster.
CIT (clock/timer) This bit in the TMOD regis ter is used to decide whether the tim er is lised as a d e la y gen erato r o r an event counter. If C/ T :0, it is used as a tim er for time d elay generatio n. The clock source for the time d e lay is the crystal frequency of the 8051. This section is concerned w ith this cho ice. The timer's use as an event counte r is discussed in the next section. Ex•mple 9-1 Find the \'aluc'!> of TMOD to operate ai timers m the following modes. (a) Mode I Timer 1 lb) Mode 2 Timer O, M ode 2 Tuner 1
1
(c) Mod~ 0 Timer I
·
•
Solution: From Figure 9--3 \
.;,it6
0
,.; l"
(a) TlloD i e 0001<>000 • 1 0H
The gace control b it and CIT bit are llade
ie alee 01 /. lbJ TMco i .. jlOjf>Olt ,• 5:ilB
k) 1lloo i a OOOOOOOOII • 008
-
.11,
• ••
~
o,
an4 t be Wl\189d t imtr (Tillllr
O
b i .. "
t:> O I o c, o f 0 I
' °5l TIMER PROGRAMMING IN ASSEMBLY ANO C
0
.
I Eumpl• 9-2 . nod for various . ... ,. frequency and its pe Find the hmer'• c1uu, frequencies
se
.,.,ith the following Cl)>IJI
·
(a) 12 MHz
(b)l6 MHz (c) 11. 0592 MHz
-1
Lf,_)
Solution:
l
XTAL oscillator
1
+ 12
,,,. !
,..,.
(
d T
l/1 MHz= l µs
(a) 1/12 • 12 MHz • 1 Hl!Z an • - 1/1. 333 MHz •. 75 µs (b) 1/12 • 16 MHz " 1. 333 MHZ and T (c) 1/12 • 11. 0592 MHz • 921. 6 kHz; T • 1/921.6 kHz= l.085 µs
NOTE THAT 8051 TIMERS USE 11U OF XTAL FREQUENCY, REGARDLESS OF MACHINE CYCLE TIME.
'I Clock source for timer As you know, every timer needs a clock pulse to tick. What is the source of th~ dock ~ulse for the 8051 ~ers? IT C/T = o, the crystal frequ,>ncy attached to the8051 is the source of the dock for the timer. This means that the s1zeof the crystal frequency attached to the8051 also decides the speed at which the 8051 timer ticks. The frequency for the hmer 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 XTAL frequency of 11 .0592 MHz. The reason behind such an odd number has to do with the baud rate for serial com· munication of in theChapter 8051. XTAL PC with no errors, as we will see 10. = 11.0592 MHz allows the 8051 system to conununicate with the
fBM
L
. I
l
GATE The other bit of the TMOD register is the GATE bit. Notice in the TMQ . . . 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 5 by software, some by hardware, and some have both softwar 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> _ GA 1s achieved by making GATE = I m the TMOD rt><>ister ... ting and stopping the t't b tc I soul'(t' ...,. o · th t t h . ., · "owever to • .d mer y an ex maill ake I , c = , meaning a no ex ema ardware is needed t • .. vo1 IUrther con{ , f 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 rn "ers In u · f d I"" to stop or start the timer is discuss(!(! in Chapter 11 wnen in KTB TRx" and "CLR sing SO hv
t'Rx"
Beca:
I
Eomple 9-3
How are timers Oand l st,1rted and stopped by instructions' Solution: . . d TRI which are called timer run control The timers are started by using instructions to set timt'r start bits TRO an . 'x·mum va lue it sets a flag TFO or . unts to ,ts ma , . , I bits. They can be cleared by clearing th~ bits. When a timer co i r and l. While TMOD contro s 50 Tfl. At this point, it is necessary to know rnoreabout the b,tsTF an_d TR ;;u::roperations. The lower four bits the timer modes, another register called the TCON controls the timer1 fons The details of the TCON • ofTCON cater to interrupt functions, but the upper four bits are for timer opera 1 register are shown below.
MSB
I
TFl
TRI
TFO
SYMBOL
BIT TCON.7
TFI
TCON.6 TCON.5 TCON.4
TRJ TFO TRO
LSB
I TRO
I
IEI
ITl
I
rEO
I
rTO
I
FUNCTION Timer I overflow flag Timer I run control bit Timer Ooverflow flag 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:
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. I.
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
t
I n.
:.---i:TF I
TF goes high when FPFF -..o
overnow
flag
Steps to program In mode 1 £,. To geni>rate a time delay, using the timer's mode I the following step ar t k T ·1y .... -mpJe 9-4. ' s e a en. o can u,ese steps, see 1
---
!Osi,iM ER PROCRAMMJNC IN ASSEMBLY ANDC 205
I
t) is 10 be used and which time, """'· ·-..e Tin1er rr.11\er Oor
TMOD ,•alue register
1
. t'ng whi·ch timer l " andica J
G
(0 or JJthe is selected. •th initial count,,a Jues, ...,on to see ·fit I Load is raised. 2. Load registers TL and TH "I target" [nstrtJcu Start the timer. (TF) with the •JNB TFX,
3. Keep monitoring th~ timer nag when TF becomes high.
4
,,
Stop th~ timer. h ~1 round. the TF flag for t e neA . a 6. ear TH and TL again. 7. Go back lo Step 2 to load
5.
re creating a squ
MOV
TMOD,#01
HOV
TLO,#OP2H THO, #OPFH
MOV CPL
.,
1·
ortions high and low) on
(with equa 1p are wave of S(f,o. du ty cycle ogram.
In the following p ~ ~ ~o.generate the time delay. lhePJ.5 bil Tuner01su HERE:
7 J
Pl.S
Ar,a)yze the pr
.
mode)
mode l(l6-b1t
;Timer O,
he LOW byte
•TLO • F2H, t . h byte ' the Hlg ·THO o FFH '
;toggle Pl.5
' ••
~
ACALL DELAY SJMP
; 1oad TH , TL again
H5R£
··-···········delay using Timer 0 DELAY, SETS TRO
AGAIN:
t Timer O ,star until ;monitor Timer O flag ;it rolls over ; stop Timer O ;clear Timer O flag
JNS TFO,AGAIN CLR
TRO
CLR RET
TFO
-:,
Vt1,
~" ,\
.,. . •·
,.Y
..
(¥SY'
CT
,t. \,-. f}.....P
Solution:
i
In the above program notice the following steps.
'
TMOD is loaded.
2. 3.
FfF2H is loaded into THO · TL.Oj . f th ls Pl.5 is toggled for the high and o~ por~on~~ e pu e. The DELAy subroutine using the timer 1s ~ b .h
0
r '~ r
'),
\I)..
,
fj;/ ,f(v'(/
1. 4.
et out o t e l0op
ly'°
•.
V 9-4 Example
f h
'
y
r\
e "SETS TRO" instruction. th timer 65. In the DELAy subroutine, Timer Ois s;arteh . Timer o counts up with the passing o ••c c oc , which is provided by the crystal oscillator As e til counts up, it goes through lhestatesof FFF3, FFF4, FFFS, FFF6, fFF7, FFF8, fFF9, FFFA, FFFB, and so on un it hon reaches falls through. FFFFH. One more clock roUs it lo 0, raising the timer nag (TFO ,. 1}. A that point, the JNB mstruC· 7 I _ TimerO is stopped by the instruction "CLR TRo". The DELA y subroutine ends, and the process is repeated Notice that lo repeal the process, we must reload the TL and Tl-[ reg,'sters and
th Start
FFF3
.
.
e timer again.
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
1r.,,u
,XTAL= 11.0592 MHz.
I 1,,.,.,"
' -=::;,+ ~"~ 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 Solution:
·
=
,
~~~
'
,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 frequenry 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
c:i·th~
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. i I I
l!ERE:
MOV MOV
TLO, #OF2H THO, #OFFH
1
.,..,....
/""'\
2
2
CPL Pl.S ACALL DELAY SJMP HERE
1 2 2
•-· - · --·---delay using Timer o DELAY: AGAIN:
'l.
,,.... Cycle•
fpf
+
-
~
"'7
'1
•
I SETB JNB
TRO TFO, AGAIN
CLR
TRO
CLR RET
TFO
Total T" 2 • 28 x 1085 µs = 60.16 )IS and F = 16458.2 Hz.
l 14 l l 2 28
'~' >
-
-
NOTE THAT 8051 TIMERS USE 1112 MACHINE CYCLE TIME. OF XTAL FREQUENCY, REGARDLESS OF
-------~~~~~~~~~~·
IOsi lll\1ER PROGRAMMING IN ASSEMBLY AND c
..
• 207
I (a)
in bex
chat values YYXJC are 1 XTAL = 1).0592 MHz figu_re ..i. Ti,ntr Delay C.Jltulalion for
9
. not reIoo,1THand TL In Ex,1mple;, 9-7 and 9-8, we did reloading works in mode I.
since .,t was ~ single pulse
LoOk at Example 9-9 to see how tlie
Example 9-7 . both ollhe method ' . h folio" mg rode, u,mg El.nd 1h,· ddav genera led by TimerO ,n t c
0 I figure
9~. Do not include
them crht."'Jd due to instructions.
MOV
P2.3 TMOD, #01
MOV MOV
TLO,#JEH TH0,ij0B8H
;clear P2. J d ) ;Timer o. mode l( 16 ·bit mo e ;TLO • JE:H, LOW byt:e ; THO • B8H, High byte
S£TB
P2. 3
•SET ru.gh P2.3
SETS JNB
TRO TF'O,AGAlN TRO
•·start Timer 0
CLR H~RE:
AGAIN:
CLR CLR
TPO
CW!
P2.3
'
J
,monitor Timer o nag ;stop Timer O ;clear Timer 0 flag tor ;next round
Sol ution:
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.
(d) (FFFF -
=
./ Example 9-8
E,-,..,, lh(lugh lhe XTA L frequency or 11.0592 is a very convenient f u . , . II " ,·cry important lo I.now lh,• cry for cn-abng • delay ~sing an AT89C51 \\'11h XTAL fn,quct When c.1kulating delay, . Thi• e,amplr M.1,w aswmbl,•r,. don I allow the use of TFO TRO "I. but q. MH.l, us ing hmo:r I in mod,: I Use pm r1.3. · · 111Stead n
.~~t"sed,
Tested for an AT89C51
~1th
a c rys t al fr equency o f 22MJ.t
For a cr)'blal trequenc} of 22 l>fHz, the value uf th z· r = n546 µs , ). ,,.. H ~ e •nstruclion cycle "' ~ I
'
-
I
....
,p
..,
I/ Ji of 22 ~11iz "' 18..13 MHz and
,Z. JJ f()
~
,~
208 THE S0s1 il11CRoc
I
~ µ,_....
-
ONiROLLER ANO EMBEDDED svsTDfS
l.
CLR MOV MOV MOV SETS SETB
AGAI N:
JNB CLR CLR CLR
Pl . 3 TMOD, #lOH THO,#OFFH TLO,li OOH Pl. 3 TCON. 6 /f"Rj TCON .7 ,AGAIN TCON. 6 TCON . 7 Pl . 3
; c lear Pl . 3 _.,,, >,, ~ 0 ; Time r 1 , mode 1 ;load high byte va l ue ;load low byte ;set bit Pl.3 ;TRl is set to start Timer 1 ;monitor Timer 1 Oag ;st op Timer 1 by making TRl • O ; c lear Ti mer 1 flag for next round ;clear the port for next round 1Slb "\
-
The dela)' is calculated as FFFFH - FFOOH = FFH = 255 + 1 = 256. X I Delay= 256 x ~ = 139.;t µs. o.,..,., c~•'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 .
AGAIN:
ORG MOV MOV MOV SETB
BACK:
JNB
CLR CPL CLR SJMP
0000
TMOD, #OOH TL l , #OllH THl, lt<)PH TRl TFl , BACK TRl P0 .6
TFl AGAIN
;timer l,mode O ;TLleOOH, low byte ;THl•OFH,high byte ;start cimer 1 ;remain until the timer rolls over ;stop t i mer 1 ;complement t he bit ;clear the timer flag ;reload the counter
For a cryst.11 fr~quency of 22 MHz, the value of the instruction cyde
,l: 0.546 µ,
_I ,, (
•
,
,
=I /12 of 22 MHz -_ 1 o-,-, MHz and .cu..,
With a 13-bjt yl!leio,.th~ um value of tinter 1 reg~r will be I FFFH The wa to · ualize . . Tli register fulJ1 mtd the I ~ 5 bits of the TL register, i.e., TH can ha · _Y Vis this 18 to use the ~,th TL t.1king 5 bit,,, i.e., 1 1_1 I I. These two values concatena~, wil~e i~~ur;u~ value of 111111 1 1 1 OW, wht n THI ,s loaded with OFH and TLl with OOH the effecti l3-gb. \!..I~ 1 1 l J 111, I.e., l FFFH. ~ , ie.,O IOOH - · ve itnum rwillbeOOOOllllOOOO
- i,- calcul.ited as .. Thc deL1y 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 .
t,
f::-
O
I
-=======--------------~=-=~~o:.:: : . : s quare~: : . w : a ve: : _ m~4~~~x~2~· ~ 8. 4 ~ms. : ____ J,, :----~~8osi l'lMER PROGRAMMING JN ASSEMBLY AND c
I eed the question is holw tko ;;11:X!1;P~:1~-~0n:~~ for tht , delay we n • ..-u gisters oo e we llSe Assun1ing that we know the amount of t11t1erded into the TL and • n re TH, TL ttgisters. To calculate the values Joa tem ing steps for finding the TH, TL registe , II crystal frequency of 11.0592 MHz for the 80 sysl _j 0 we ,an use the fo ow rs 9 AssumingXTAL = 11.0592 MHz from Examp e values.
Finding values to be loaded into the timer
to~:
I. Divide the desired time delay by 1.085 µs. . 1 2. Perform 65536- 11, where II is the decimal value we got 111 Step · e to be loaded into the timer's registers. 1 3. Convert the result of Step 2 to hex, where yyrx is the initial hex va u 4.
o••
SetTL=rxandTH=yy.
--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 and TL= 00. 71-1 T L 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
7~
L
I
With a frequency of 22
~ generate a frequency of
Solution, :Tested for an AT89CS1
I
o
·J C. I(
._
100 l
J.J. w
i
th a crystal
For a JOO.KHz square wave (a)T = 1/f ~O.OI ms= JO~ (b) I /2 of it for high and low porti (c) 5 µs/0.546 µs = 9 cycle;; ons-" = 5 µs
~
frequency of
22MHz.
,JS 1•---• f
•
"
(d) 65,536 - 9 ~ 65,527" FFF7H
' 210
n,e program is as follows. BACK: ;.GAIN:
MOV MOV MOV SETB JNB
TMOO,#lOH TLl,#OF7H THl,#OFFH TRl TFl , AGAIN CLR TRl CPL 1?2 . 3 CLR TFl SJMP BACK
;Timer 1, Mode 1 ; TLleF7H ; THl:FFH ; sta r t Timer 1 ; wait for timer rollover ; stop Timer l ;complement P2.3 ;cl ear timer flag ;reload timer
Example 9-U
-~
· an ON time · o f 3 ms and an OFF hme · o f 10 Generate a square wave with ~ 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. BACK:
~
i •
MOV MOV MOV MOV ACALL MOV MOV MOV ACALL
OBLAlt'
S'1MP
BACK
TMOD,#OlH TL0,#075H THO,#OB8H P~,#OOH DELAY' TL0,#8AH THO,#OEAH PO, #OF.E'H
• DELAY ·
AGAIN:
ORO SBTB JNB
CLR CLR RET
JOOH TRO TPO,AGAIR TRO
TPO
END
~
I
;Ti mer O in mode 1 ;to generate the OFF time, load TLO ;load OFF time value in THO ;make port bits low ;call delay routine ;to generate tbe ON time , load TLO ; l oad ON t i me value in THO ;make port bits high ;call delay ;repeat for reloading counters to get a ;cont inuous square wave
.
;start the counter ;check time r overflow ;when TFO is set, stop the timer ;clear timer flag ;end of file
For OFF tinw calculation: IQIIIS/ 0.546 pa = 18,315 cycle 65 .536 - 18,315 " 47,221 • 8875H
-
211
I
I Of} For 0"1 bme calculation: 3 rns/0 5-16 µs = 549~ cycles . d clearing it are done in a s_ubroutinc, Which t,5,536- 5-194 = 60,0U = EA8AH. . kin for the nag bat, an ded u,to TH and TL are different In Iha, example, the starting of the bmer, ch~hil!the vafues to be lo.1 c, common for both the ON and OFF tunes,
I Generating a large time delay · d ds on two factors, (a) the crystal frequ""-· · f the time delay epen r f th 8051 "'Y, As we have seen in the examples so far, the size o f • are beyond the con tro o e programmPI and (b) the 11mer's 16-bit register in mode 1. Both of these a~tor:,both TH and TL zero. What if that is not enough> . that the largest tune . de1ay JS · ach'eved by makmg · We saw earlier ' Example 9-13 shows how to achieve large time delays. Using Windows calculator to find TH, TL The scientific calculator in Mkrosoft Windows is a handy m,d easy-to-use tool to find the TH, TL values.. Assume that we would like to find the TH, TL values for a time delay that uses 35,000 clocks of l .085 µs. The followmg steps show the calculation. Bring up the scientific calculator in MS Windows and select decimal. Enter 35,000. Select hex. This converts 35,000 to hex, which is 88B8H. Select +/- to give-35000 decimal (n48H). The l_owcst two digits _(48) or this hex value arc for TL and the next hvo (77) are for TH. We ignore all the Fs on••· left since our number is 16-bit data. ""'
1.
.~ .
2.
3. 4.
5. 1,.. \.
Example 9.-13
•
in mode 1.
Assuming XTAL - 22 MHz
·t
• wn
ca program to generate a puls,' train of2 seconds period on pin P2.4. Use Timer I Jrc.<.
Solution:
\
I
;Tested for an AT89CS1 with a crystal f ,, ~ 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 MOV CPL [ MOV MOV SETB JNB CLR CLR •
"-~ :
BACK:
AGAIN:
DJNZ SJMP
TMOD, #lOH RO, #28 P2. 4 TLl,#OO!f Tlll #00 TRI, H TPl,AGAIN TRl TPl
, 1'1
RO,IIACK REPT -, i.~-•
-
Calculation= 28 x 35.75 ms= 1001 ms.
212
-, ,IP
:Timer l, mOde 1
:counter tor
.
;complement P;u!tlple delay : load count . : load coun value in TLl :start tim:r value in TH1
'1.(,,..-i ...~ - ._/
o+"'
(>
Pulae gene r a tion
---
.'"
.Al' • ..~ ,
v-:;, • .c.:"
; Stay Until I stop t.irner timer rolls over :clear lei ; if RO ,s ' mer not ~9
; repeat for continuous zero, reload t i 111er
~
y
.
/ E.o mple 9-13• ~erate the following wa,•eform on Pl.2. XTAL = ~ MHz
SO ms
"'=""-
-
-
-
so·ms
Solo.lion:
'
;Tested for an AT89C51 with a crystal frequency of 22MHz. This means first creating a delay of 50 ms ON time and SO ms OFF time, followed by five repetitions of 10 ms ON time and ~ OFF time. To generate a delay of 50 ms, a 10 ms delay is repeated 5 times. The first 13 lines of the program are for generating the 50 ms ON and OFF times. The rest are for generating five pulses of 10 ms
each. START:
BACK:
RPT:
AGAIN:
SETB MOV MOV MOV MOV MOV SETB JNB
CLR CLR OJNZ
CPL DJNZ
BACKl:
SETB MOV MOV MOV SETB
AGAINl:
JNB
CLR CPL CLR DJNZ
SJMP
~
Pl.5 Rl, #02 I• to >;. TMOO, # l OH _,, ~0 . #QS TL1,#75H THl,#OB8H TRl TFl,AGAIN TRl TFl RO,RPT Pl.S Rl,BACK Pl.S Rl,#10 TLl,#75H THl,#OB8H TRl TFl,AGAINl TRl Pl.5 TFl Rl, BACKl START
;set port pin for generat~ng the ON time ;one ON time and one OFF time ;Timer 1, Model ;repeat the 10 ms delay 5 times
;stop after 2 periods of 50 ms are over ;start the sequence of s pulses of T . 20 ms ;this part for 10 ON-OFF periods of 10 ms
;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 3-bit timer ·ts maxi.mum Mode O 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.
/
· er's re ·ster TI-!. Mode 2 programming . . rations of mode 2· The following are thecha~actenstics and ope f()() to FFH to be loaded : e r mu! be started. This is 11 only values o f ·t to TL Then 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 2. done by the instruction "SETB TRO for tmeb ·ncrementing tl1e n ref~~t:~ are using Ti.mer 0, TFO goes high;u
into::
I
3.
After the timer is started, it star~c~: of FFH. When it rolls over 1.ro"'. ' we are using Timer !, TFl ,s nused.
XTAL oscillator
~rse'
+ 12
·' c/ i' ~ o
4.
~gh the TF (timer flag ·
/
I
'
_J
1
~ overflow flag
TL 1' reload
TR
I
TH
I
TPgoes hlgh when FF-.. o
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 progranuner 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 thesee original value.10. Thls mode has many applications, including setting the baud rate in serial communication. as weof will in Chapter
Steps to program in mode 2 To gene,ate a time delay using the timer's mode 2, take the following steps. 1.
2. 3.
Load the TMOD ,•alue register indicating which timer rnmer o r T· (mode 2). Load the TH registers with the initial count value. Start the timer.
0
.
tmer 1) IS to be used, and select the timer mode
S.
Keep monitoring the timer flag (TF) with the "JNs T"-· (th J h TF ,., ' "' • target"· . en goes ,ugh. UlStruction to S<.>e whether it is raised. Get out o e the oop Clear TPwflag.
6.
Go back to Step 4, since mode 2 is auto-reload.
4.
Example 9-14 illustrates these points. To ach;ev Example 9-15. ea 1a.rger delay, ,ve can
214
. use multiple registers as shoWII 111
uare wave generated o n pin Pl. tn uoting tha t XTAL = 11.0592 MHz, find (a) the frequency .of ~e sq and the TH valu e to d o that. ~owing program, and (b) the s mallest frequency achievable m this program, l
1'.0 V
BACK:
TMOD,#20H MOV THl,#5 SETB TRl JNB TFl,BACK CPL Pl .O CLR TFl SJMP BACK
; Tl / mode 2/ 8-bi t/a uto - r eload ; THl = 5 ;start Time r 1 ·stay until t i mer r ol ls ove r : c omp . Pl.Oto get hi , lo ; clear Timer 1 ilag ; mode 2 is auto-reload
Solution: d t I ad TH -reload. (a) First notice the targe t address of SJMP. Jn mode 2 we do ~ot nee . 0 r~ oh uJ s ince a SOo/o duty . ceit . isisauto 1 fre u e nc = 5 ind t~e Now (256 - 05) x 1.085 µs 251 x 1.085 µs = 272.33 µsis the high p ortion° ~ e P cycle square wave, the period Tis twice that; as a result T = 2 x 272.33 µs - 544.6 µs an q Y
;e.
=
1.83597 kHz. .s ach1ev · ed w h en TH -- 00· Jn that case ' we have (bl To get the smallest fre quency, we need the largest T and that 1 T = 2 x 256 x 1.085 µs = 555.52 µs and the frequency= 1.8 kHz.
• Example 9-15 Assuming that XTAL = 22 MHz, write a program to generate a square wave of frequency 1 kHz on pin Pl .2. Solution:
;Tesced for an AT89C5l wi th a crystal frequency of 22MHz. The smallest frequency possible in this setup is when the delay is maximum. Largest delay is when TH reduces to 00 from FF, i.e., delay is 256 x 0.546 = 139 µs. T = 2 x 139 = 278 µs i.e., the smallest frequency is 3.6 kHz. Hence, to get a smaUer frequency, we need to use a
register for creating the additional delay. To get a d elay of 0.5 ms, we need 0.5 ms/0.546 µs = 915 cycles. This can be achieved in various w ays, one which is lo use the TH register to get a delay of 915/5 = 183 cycles, and a register RO to get the rest of it. 183 cycles have to be covered by the TH register when it rolls from its count value to FFH. 183 = 87H. The TH value should be FFH - 87H = 48H. Thus the effective delay is 183 x 0.546 x 5 = 499 µs 0.5 ms T=0.5 ~ 2 = t ms and frequency = 1 kHz.
=
MOV
REPT : AGAIN: BACK:
CPL MOV MOV SETS JN8
CLR CLR DJNZ SJMp
ENO
TMOD,#02H Pl. 2 RO, #05 TH0,#48H
TRO TFO,BACK TRO TFO RO,AGAIN RBPT
;Timer O, mode 2
;complement Pl.2 ;count for multiple delay ;load THO value ;start Timer o ;stay until timer rolls over ; stop timer ;clear timer nag ;repeat until RO•O ;repeat to get a train of pulse•
215
,.
I (
(' heX) Joaded iJ'lto TH for each Of !lit~ £umplt 9-16 . the t:uners for m As.surrung that we are programrrung
following cases. (a) (c) (c)
I
(b)
lJ1
60
#12 Tl!l, #-
MQV T HO,
(d) MOV
MOV Tlll, #-200 MOV 'THl, # - 3
ode 2, fiod the value
MOV THO, ij- 48 •
·
SoIution. You can use the Windows scientific calculator~
·ded by the assembler. In Windows calc,i.
TH R~:~::::
ults prov,
ve!~:1:j~e:o
get the va!ue .. lator,select decimal and enter 200. Then select ex'._ an B-bil data. The follo,vlllg IS 15 right two digits and ignore the rest since our data
Dtcimal -200 -oO
2's complement (fH value) 38H C4H
-3
FOH
-12 -48
DOH
th ge:.t we o nly use the
F4H
C
•
Assemblers and negative values V
r
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, #-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
Find (a) the frequency of the square wave generated in the following code, and (b) the duty cycle of this wav•.
AGAIN:
MOV
TMOD,#21!
MOV SETS
TH0,#-150
AGAIN
SETB
TRO TFO,SACK TRO TFO
r.
; Timer o, mode 2
;(8 -bit, auto - reload)
C
;THO~ 6AH ~ 2's comp o f - 150
Pl . 3 ACALL DELAY ACAI.L DELAY CLR Pl.3 ACAI.L DELAY
SJMP
T
; Pl. 3 • l
; Pl. 3
=-:
o
DELAY:
BACK:
JNB CLR CLR RET
; start Timer 0 ,stay Until ti ·stop T'11ner mer rolls over · O :clear TF f or next round
Solution: For the Tif value in mode 2 the conv-.
.
k 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,•
tso
- ~~
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.
"" In thiS section, we used the 8051 timer for time delay generation. However, a more
owerful and creative use of
P
•
these timers is to use them as event counters. We discuss this use of the counter next.
Review Questions 1. Ho1~ many timers do we have in the 8051? 'i'o,. T l 2. Each timer has registers that are ~
bits ,vide.
3. TMOD register is a(n) & -bit register. t, True or false. The TMOD register is a bit-addressable register. s. indicate the selection made in the instruction "MOV TMOD, #20H". 6. 1n mode 1, the counter rolls over when it goes from to - - - 7. 1n mode 2, the counter rolls over when it goes from to . 8. In the instruction "MOV THl, #-200", find the hex value for the TH register. 9, To get a 2-msdelay, what number should be loaded into TH, TL using mod~ 1? Ass~e that XT:-L = 11.0592 ~ 10. To get a 100-µs delay, what number should be loaded into the TH register usmg mode 2. Assume XTA I 1.0592 MHz.
SECTION 9.2: COUNTER PROGRAMMING In the last section we used the timer/counter of the 8051 to generate time delays. These timers can also be used as counters counting events happening outside the 8051. The use of the timer/counter as an event counter is covered in !his section. As for as the use of a timer as an event counter is concerned, everything that we have talked about in programming the timer in the last section a lso applies to programming it as a counter, except the source of the frequency. When the timer/counter is used as a timer, the 8051's crystal is used as the source of the frequency. When it is used as a counter, however, it is a pulse outside the 8051 that increments the TH, TL registers. ln counter mode, notice that the TMOO and TH, TL registers are the same as for the timer discussed in the last section; they even have the same names. The timer's modes are the same as well.
err bit in TMOD register RecaU from the last section that the C/T bit in the TMOD register decides the source of the clock for the timer. II Ctr= 0, the tim~r gets pulses from the crystal. In contrast, when CIT= 1, the timer is used as a counter and gets its pulses ~m outside the 8()51. Th~refore, when C~T = 1, _the counter counts up as pulses are fed from pins 14 and 15. ~ pms are called TO (T,?'er Omput~ and Tl (Timer 1 mput). Notice that these two pins belong to port 3. In the case unerO, when C/T = 1, pm P3.4 provides the cloclc pulse and the counter counts up for each clock pulse coming fr that pm. Similarly, for Timer l, when C/T = 1 each clock pulse coming in from pin P3.5 makes the counter count u:.rn
Table 9-1: Port 3 Pins Used For Timers Oand 1 Pin
Port Pin
Function
14
P3.4
TO
15
P3.5
Tl
Description Tuner /Counter Oexternal input 11mer/Counter 1 external input
(MSB)
GATE
I
CIT I Ml Timer 1
(lSB)
I
MO
GATE
I
C/T
I
Ml
I
MO
TlmerO
217
I
.
,,,,. to be counted are fed to pin P3.4. X'l'Al•
Ex•mple 9-18 tses of an mpu t signal. n,epu=· g 1he pu Design a. counter for counttn 22~tHz.
Of 22MHz, 1 . Solution: . rysta frequency d Timer is run as a counter, f .. ,, __With 9 0 ATa cs1 "itb a c . this l seem, ' ·ve the number o p..,..,. that ;Tested for an . . 1second. [)uJ'lng ·n TLO and THO gtkn ,vn signal, i.e., the num~
I I
~
,.,
base the values • of the un In thls, Timer I 1s ~ •~3time of 1 se_;::n d~ves the frequency At thefor endrunang 4 input pulses fed into pm d · : this I second. IS were received at pin P3.4 u~ng of pulses received m I secon .
I
,/" RPT:
/. .
AGAIN:
BACK,
OOOOH ORG MOV TMOD,#lSH SETB P3.4 MOV TL0,#00 MOV TH0,#00 SETB TRO MOV R0,1!28 MOV TLl,#OOH MOV THl,#OOH SETB TRl JNB TFl,BACK CLR TFl CLR TRI OJNZ RO,AGAIN 1'.0V A,TLO MOV P2,A MOV A,THO MOV Pl,A SJMP RPT END
o
imer and Timer o as counter ;timer last 4 an input port •make port P3. '.clear TLO '·clear THO : tart counter d ,s . l secon ·R0-=28,co time ' ••TLl•O ·THl=O '.start Timer 1 ;test Timer 1 flag ;clear Timer 1 flag
·stop Timer l ; repeat the loop until ROaO TLO ;since l sec has elapsed, check •·move TLO to port 2 ;move THO to ACC ;move it to port l ;repeat
As the frequency varies, the values obtained at ports l and 2 vary. The values obtained for 10 Hz, 25 Hz, 100 Hz, ... are respectively, OAH, 19H, 64H ..•
/
~, ....._, "'"'""' =··-•'"""· . .
.
In Example 9-18, we use Timer 1 as an event counter where it counts up as clock pulses a re fed into pin 3.5. These clock pulses could represent the number of people passing through an entrance, or the nun,ber of wheel rotations, or
be displayed on 9-18, an LCD. In Example the TI.. data was displayed m binary. In Example 9-19, the 11. registers are converted to ASCII
T1merO exlemal
--i '
input
pm 3.~
c;r. I
TRO
ove:rflo"', nag
Tl-iO TLO
TFO
Timer
-rDi l-J
L
overnow Oag
external in pin 3.Sp u 1 T H 1 TL1}r- •j TFJ
TFO goes high when FFFF- o
Figuro 9-S. (a) Timer O with ExttmoJ Input (MOdt 1)
218
.:::;-----------i
r, -J
C/f ~ 1 ~1 W'tb 1
(b) Ti.n,tr J
I
j
TF1 goes high When l'FFF -.. 0 E"~rn•I Input fMOd,. 1)
Tttt sos1 M1caoc
ON'rROLLER AND EMBEDDED SYSJVIS
£:Ull'Plt 9.19 .
t
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().
d'splay counter O on an 1
5olution: . bmary . d ata t o ASCH · See Chapter 6 for data To display the TL count on an LCD, we must convert 8-bit conversion.
AGAJJI:
SACK:
ACALL MOV MOV SETB SETB MOV ACALL ACALL JNB CLR CLR SJMP
-
LCD SET OP TMOD,#000001100 TH0,#-60 Pl. 4 TRO A,TLO CON\/' DISPLAY TFO,BACK TRO TFO AGAIN
-
;initialize the LCD ;counter O,mode 2,C/T=l ;counting 60 pulses ;make TO as input ;starts the counter ;get copy of count TLO ;convert in R2, R3, R4 ;display on LCD ; loop if TFO=O ;stop the counter O ;make TFOaO ;keep doing it
;converting 8-bit binary to ASCII ;upon return, R4, R3, R2 have ASCII data (R2 has LSD) COllV:
MOV
B,#10
DIV
AB
MOV MOV DIV ORL MOV MOV ORL MOV MOV ORL MOV
R2,B B,#10
;divide by 10 ;save low digit ;divide by 10 once more
AB
A,#30H R4 ,A A,B A, #3011 R3,A
;make it ASCII ;save MSD ;make 2nd digit an ASCII
;save it
A,R2
A,#3011 R2,A
;make 3rd digit an ASCII ;save the ASCII
RET
8051 Pl
to
LCD 1 Hz clock
TO
By llSing 60 Hz we can generate secorufs, minutes, hows.
~that on the first round, it mJ1B from 0, since on RESET, TU) = o. ve tlus problem, lold n.o with -(,() at the begiMing of the program. :---_
;-;;~~~;;;~~:;~;:~~;;------------------==
los111'-' ER PROGRAMMING IN ASSEMBLY AND C
219
I
_rL.Jl .f1._.lL
no
TuncrO extcmal input pin 34
CIT= 1
I
Tl.ffler I e,cterl'lal input pin 3.5
overflow nag i-.--i TFO
_.._, reload
TRO
THO
TP I goes high
c/f= I
TFO goes high
whenfF-.o
Figure9-7.
~...__reload THI
TRl
T.
when ff..-O er 1 with External Input (Mode 2)
lffl
External Input (Mode 2) 'eed an external square wave of 61)Lz. 1 '" . . f th timer with CIT -_ '.we can ''d the hour out o f this ·input freq Ul'nn. 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 wgi and display the result on an LCD· This wiJJ be a ruce h important '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. 1u · waste of the microcontroller's time. . y ou are n·ght· There,saso · d · ill . f . IT Uer When the TF flag is raise it w in orm US. llii! · th thin with the rrucrocon o ter · 11. d ruptswecangoabout omgo er gs . . in Cha 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 ' Eigm,9~, TimerOwllh
next.
TCON REGISTER
'r
In the examples so fur we have seen the use of the TRO and TRI Oags to turn on or off the timers. These bits are part of a register called TCON (timer control). This register is an 8-bit register. As shov,n in Table 9-2, the upper four bits are
used to store the TF and TR bits of both Timer Oand Timer 1. The lower four bits are set aside for controlling the inter• rupt bits, which will be discussed in Chapter 11. We must notice that the TCON register is a bit-addressable register Instead of using instructions such as "SETB TRl" and "CLR TRl ", we could use "SETB TCON. 6" and "CLR TCON. 6", respectively. Table 9-2 shows replaoements of some of the instructions we have seen so far. Table 9-2: Equivalent Instructions for the Timer Control Register (TCON) For1imerO
SETB TRO
CLR
TRO
SETB TFO
CLR
=
TFo
-
ForT1mer l
SETB TRI
CLR
TFI
TRI
TRJ
SETB
TFt
CI.R
TFt
= =
= =
SETO TCON.4 CLR TCON.4 SETO TCON.S CLR TCON.5
SETB TCON.6 Cl.R
TCON.6
SETJl TCON.7 CLR TCON.7
TCON, Tirner/Counter C ontroJ Regisi TFO
er
TR
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 50 si~- TlU ", for r·~ers 0 an d 1, respectively. What happens ' if the GATE bit in TMOD is set to 1? As can be seen .in •sSTB 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
-l
Ga te
•
- '
.....J
I
)-
IN1"0 p in Pin 3.2
Figure 9--8. Timer/CounterO
XTAL OSCILLATOR
+12
C/T=O
-------c_>--1--ruY--f CIT= 1
Tl IN Pin 3.5 - - - - l
TRl -----f--.._
.-J
Gate
iNTIPin _ _ _ _ ___,
I
,'
' /'---'
Pin3.3
Figure 9--9. Tlmn/Counter t
221
I
,~gs Timer O is turned on by th.. other thu• ' od 'SOit., . ddition to manY f the user of that pr uct. However .,, . Ti o ,.,..,haps 1n a , a S'Yj 11 troI o 1 an alarm every second using ,mer , r- . d is beyond the co h uing down the a arm. 1<1i 5 method of using the "SETB TRO" instruction ff the timer, thereby u connected to pin P3.2 can be used to tum on an
a:;
Review Questions I. Who provides the clock pulses to 8051 timers
°
!f c1!T: ~J
T
2. ~Vho provides the clock pulses to 8051 tiJ:ne~s 1f C. T - = 1? 3. Does the discussion in Section 9.1 apply to bmers '.f C1 Tl and why? 4. What must be done to allow P3.4 to be used as :111 mrut for ~N 6• 5. What is the equivalent of the following mstruct1on? SBTB T ·
SECTION 9.3: PROGRAMMING TIMERS OAND 1 IN 8051 C In Chapter 7 we showed some examples of C programming for the 8051. In this ~ection we study C progra~ for the 8051 timers. As we saw in the examples in Chapter 7, the general-purpose registers of the 8051, such as RO. R7
.... i
r
A, and. B, are under the control of the c compiler and are not accessed directly by C statements. 1n the case of sf'Rs'. ~e entire RAM space of SO. FFH is accessible directly using 8051 C statements. As an example of accessing the SFRs duecUy, we saw how to access ports PO - P3 in Chapter 7. Next, we discuss how to access the 8051 timers directly usrn, C statements. -..
Accessing timer registers In c in
In 8051 C we can access the timer registers TH TL a d TMOD dir . &le 9-20. Example 9-20 also shows how to ~cc~:the TR and .;ii~~smg the reg51.h header file. This is shown
/ (
[
Example 9-20
w·nt.e a 8051 C program to toggle aJJ the b' 16-b,t mode to generate the delay.
,ts of port PI continuously with so
C
I
. me d elay m between. Use Timer O.
I
I
Solution:
I
#include
I I
while(l)
I
J
I
Pl•OxSS; TODelay() 1 Pl•OXAA·• TOOelay(I I
I /repeat fo rever
I
//toggle all //delay size bi t e of Pl // t oggle a11 "'?known b1te Of Pl
l
ro0e1ayO
1/0ld \
fflOO•OxOl; '!'LO•OXOO; TRO•Ox35; 1'1!0•1; >1hile (Tr'Os•O) : TRO=O;
TFO•O;
//Timer O, Mode 1 //load TLO //load THO //t:urn on TO //wait: for TFO t:o roll over //t:urn off TO //clear TFO
l FFffH - 3500H =CAFFH = 51967 + 1 =51968 51968 x 1.085 µs = 56.384 ms is the approximate delay. 8051
P0 1 - - - - -
LEDs
• Calculating delay length us ing timers As we mentioned in Chapter 7, the d elay length depends on three factors: (a) the crystal frequency, (b) the number
of clocks per machine cycle, and (c) the C compiler. The original 8051 used 1/12 of the crys tal oscillator frequency as ln!machine cycle. In other words, each machine cycle is equal to 12 clocks periods of the crystal frequency connected IO l!lt Xl - X2 pins. The time it takes for the 8051 to execute an ins truction is one or more n,achine cycles, as shown in Appendix A. To speed up the 8051, many recent versions of the 8051 have reduced the number of clocks per machine cydt from 12 to four, or even one. For example, the AT89C51 /52 uses 12, whi le the D55000 uses 4 clocks, and the ll589C4xO uses only one dock per machine cycle. As we mentioned earlier in this chapter, the 8051 timers also use the Cl}ital frequency as the clock source. The frequency for the timer is always 1 / 12th the frequency of the crystal a ttached IDlhe 8051, regardless of the 8051 version. In other words, for the AT89C51/52, DS5000, or DS89C4x0 the duration o f lbttime to execute an instruction varies, but they all use 1 / 12th of the crystal's oscillator frequency for the dock source Iii lhe timers. This is done in order to maintain compatibility With the original 8051 since many designers use timers liltttate time delay. This is an important point and needs to be emphasized. The C compiler is a factor in the d elay lilt since various 8051 C compilers generate different hex code si.zes. This explains why the timer delay duration is ~ for Example 9-20 since none of the other factors mentioned is specified.
Delay duration for the AT89C51 /52 and DS89C4x0 c hips At we stated before, there is a major difference between the AT89CSJ and DS89C4x0 chips in term of the time it bl~ to he(Utt, a ~ingle Instruction. Althoug~ the DS89C4x0 ext>cutes instructions 12 times faster than the AT89CSJ ~-thty both •hll u1,e O.C/ 12 dock for their timers. The faster execution tim~ for the instructions wilJ have an impa t d~l.ay il'ngth ro verify thl!> very important point, compare parts (a) and (b) of Example 9-21 since they ha c ~ on thc-,,e two chip• with the same ~peed and C compi ler. ve
~°"'
lltt.er, o and 1 delay using mode 1 (16-blt non auto-reload) ~'.,"PW'• 9-21 and 'J-22 •how 8051 C programming of the timers O and 1 in mode 1 (16-bit non-auto ~I d) ,_, tJi..m to g..i famthar w ith the •yntax. o.i ·
.......__
~11~,;;:;--;;;;:::::: ::::;.::::-;::;::-;;:;:;::;;;-::;-::::::::-~~~~~~~~~~~~~~~~~~~ l'1£R PROCRAMMINC IN ASSEM BLY ANO C
I . mode 2 (8-bit auto-reload). Study th. (8•b it auto-reload) oand 1111 · mode 2 ~'
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 void TOMlDelay(void); sbit mybit=Pl"S;
void main(void) { while(!) { mybit•-mybit; TOMlDelay();
//toggle Pl.5 //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; TLO=OxFD; THO=Ox4B; TRO•l; while (TFO•wO); TROc.0;
TFO•O; }
//Timer o. mode 1(16-bit) //load TLO //load Tl!O //turn on TO //wait for TPO to r oll over I /turn off TO //clear TPO
(b)TestedforDS89C420,XTAL=11.0S92 •"-'-
.
'"'=, using
th . e Provtew32 compiler
void TOMlDelay{void)
I
TMOD•OxOl; TLO•OxFD; TIIO•OX48;
TRO=l; while (TFO••O) ; TROcO;
TFO•O; )
//Timer o, IDOde l(l& b. //load TLO - it) //load Tllo //turn Oil TO //wai t for TFo t //turn off To O ro11 over //clea r TPo
: .
..
FFFFH - 4BFDH =8402H a 46082 + J ., ~
..
~
Timer delay = 46083 x 1.085 µa ,. SO 111a
•'-I!~, .
224
TliE 8oSJ l\ftc1t OcoNTR.ott
.
..-'
ER. AND EMBEDDED 5yST&IS
' -
E,r,ll' Man 8051 C program to toggle all bits of P2 continuously every 500 ms. Use Timer 1' mode 1 to create wn.-
JtlaY· 5o1ution:
//iestecl for D589C420, XTAL = 11.0592 MH2, using the Proview32 compiler rinclude void TlMlDelay (void) ; void main (void)
{ unsigned char x; P2=0x55; while(l)
{ P2=-P2; for(x=O;X<20;x++) TlMlDelay {) ;
//toggle all bits of P2
}
) void TlMlDelay (void)
•
( TMOD=OxlO; TLl • OxFE; TlllsOxAS;
TRl=l; while (TFl=•Ol ; TRl•O; TFl• O;
}
//Timer 1, mode 1(16-bitJ //load TLl //load THl //turn on Tl //wait for TFl to roll over //turn off Tl //clear TFl
A5FEH " 42494 in decimal
&m6- 42494 = 23042
lJOU • 1.085 µs" 25 ms and 20 x 25 ms = 500 ms
N0TETHATS051TIMERSUSE11120FXTALFREQUENCY, REGARDLESSOFMACHINE cYCLETIME.
~ple9-23 IVnte an 8051 C program to toggle only pin Pl.5 continuously every 250 ms. Use Timer O, mode 2 (8-bit ll\lllc>-ieload) locrrate the delay.
Solution: 1 llested for DS89C420, XTAL ,. 11.0592 MHz, using the Proview32 compiler
•• .include
~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 //due co forand not 40 //we put 36
for(x•O;xc250; x++ )
I
for(y•O;ya36;y++) TOM2Delay () ;
l,-
,I .... I'' /:.
void TOM2Delay(void) {
. auto -reload) de 2 (8-blt //Timer 0, mo load value) //load THO(auco-re
TMOD•Ox 021 TH0=-23;
•
TRO•l;
r'.'.
//turn on TO co roll over //wait for TFO //turn off TO //clear TFO
while (TFO==O); TRO=O; TFO•O;
(2
l
,....
256-23 =233 23 X J,085 µs: 25 µS
L
r
25
x
250 x 40: 250 ms by calculation.
. C ~
H:.ever, the scope output does not give us this result. This JS due to overhead of the for loop JJl problem, we put 36 instead of 40.
•
this
o correct
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 void TlM2Delay(void>; &bit mybit,p2•7,
void main {void)
I unsigned char x; while(l)
I l
I
mybit•-mybit; T1M2De1ay();
//toggle P2,7
'
226
'
I
....
.
·d T1M2Delay(void) ,111
I
TMOD•OX20; TJ!l• - 184;
TRl•l; .,bile (TFl•=O ) ; TRl• O; TFl=O;
//Timer 1, mode 2(8 - bi t a uto -reload) //load TH l( auto - r e l oad val ue) //turn on Tl //wait f o r TFl to roll over // turn off Tl //clear T Fl
I 1/'J:IJJ Hz = 400 µs
=
~ µs/ 2 200 µs
200 )JS/ 1.085 µs = 184
8051
2500 lu P2.7 n.nn..JlJlJ1.J1
I
Example 9-25 Aswitch is connected to pin Pl.2. Write an 8051 C program to monitor SW and create the following frequencies on pin Pl.7:
SIV=O:
500 Hz
SW:!:
750 Hz
Use Tuner 0, mode I for both of them. Solution: //tested for AT89C51 /52, XTAL= 11.0592 MHz, using the Proview32 compiler
Jinclude mybit • Pl 'S ; sbit SW :Pl '7 • • •oid TOMI Delay (unsiged char) ; • 0 1d ma i n (void) { 9bi t
SW• l; ~hil e (l ) { mybi t • -mybit; if (SW••O) TOM1De1ay(Ol; else TOM1Delay(l)1
//make Pl.7 an input //toggle Pl.S //check switch
I
227
•
I void TOHlDelay(onsigned char c) { TMOO=OxOl; if(C••O) ( //FC67 TLO•Ox67; THO•OxFC;
l else { TLO•Ox9J\; THO•OXFO;
//F09A
} TRO=l; while (TFO••O) ;
TRO•O; TF'0=-0;
)
.,... I
FC67H = 64615 65536 - 64615 =921 921 x 1.085 JJS = 999.285 µs 1 I (999.285 µs x 2) = 500 Hz
C Programming of timers Oand 1 as counters In Section 9.2 we showed how to use timers Oand I as event counters. A timer can be used as a counter if we pro, vide pulses from outside the chip instead of using the frequency of the crysta l oscillator as the clock source. By f~ing pulses to the TO (P3.4) and Tl (P3.5) pins, we tum Timer Oand Timer 1 into counter Oand counter l , respectively. Study the next few examples to see how timers Oand I are programmed as counters using the C language. Eumple9-26 Assume tru,t • l ·Hz external clock is being fed into pin Tl (P3 5) w · C 1 auto reload) to count up and display the state of lh TLI · · n ea program for counter 1 in mode 2 (8-bit e count on Pl. Start the count at OH. Solution: #include sbit Tl • Pl"'S;
void main (void)
I Tl•l;
TMOO•Ox60; T'Hl•O; Wlti.le(l)
I
//make Tl an input // //set count too //repeat forever
Do
( TRlcl;
Pl•TLl;
}
//start timer
//place value on Pine
11·11, 80S1 MlC·"0<:oNl'llol 'R n : ~ ~ ~ ~ : : : - - - - - - - - - lEll AND EMBEDDED svsTOfS
while (TFl==O); TRlsO; TFlsO;
//wait here //stop timer //clear flag
l l Pl ,sronnected to 8 LEDs. Tl (P3.5} is connected to a 1-Hz external clock. 8051
Pl
1 Hz
to LEDs
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 void main (void ) { TO=l; TMOD=OxOS; TLO•O; THO•O;
while ( l ) ( do {
//mak.e TO an input
II //set count too //set count too //repeat forever
TRO:l; Pl=TLO; P2•THO;
l while(TFO••O); TRO•O;
//start timer //place value on pins
II //wait here //atop timer
TFO•O;
8051
Pl
lHzdock
Pl and P2to LEO.
1ll P3.4
229
'
I . E,ca.mplr 9·28
. Tl (PJ.5)- Write a C program for counter oin
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 vo~d BinToASCII(unsigned char); void main()
I unsigned char value; Tl•l; TMOD•Ox06;
-. . .
Tff0;;0i
while (1) { do
I TRO•l; value•TLO·
'
BinToASCII(value);
t while {TFO· =OJ; TRO•O;
}
TFO•O• '
)
void BinToASCII{ unsigned . c har value) { unsigned char x , d 1 d2 d x • val , , 3. ue I 10 · '
//see Chapter 7
dl • value , l~
10; d3 • x f 10 d2 •
X \
PO • JO
Pl • )O
P2 • 30
I d1 •• I ~. I d3'
}
230
'
"
Ei',nple 9·29 A--reload) to display the seconds and minutes on Pl and P2, respectively. 5olotion:
~include void ToTime {unsigned char) ; void main{)
I
unsigned char val·•
TOsl; n,,ODtOX06; THOs-60 ;
//TO, mode 2 , counter //sec • 60 pulses
while(ll
I
do { TRO=l ; secoTLO;
ToTime(val); } whi le (TFO==O); TROsO ; TFO=O; } } void ToTime (unsigned char val)
{
unsigned char sec, min; min= value I 60; sec • value t 60; Pl= sec; P2 = min;
} 8051 Pl
P3.4 P2 60Hzclock
Pl and
P2 to LEDs
TO •
By usu,g . 60 Hz, we can generate seconds, minutes, hours.
.. .
For Examples of Timer 2, see the www.MlcroDlgltalEd.com Web site.
231
I 8051 timers if c/T = o;x2 o".
Review Questions
the lock pulses to t "TMOD 1. Who providest--•,Con made in the statemenoes from
to - - to---frotn · ter. value for the TI-f reg!S s
2. Indicate these <>-u Us over when it g 3. In mode 1, the coun:: over when it 4 _ In mode 2, the co,:mTl!l __ .., find the ex - 200 . 5 In the statement . TFl part of register bl ? 6. TFO and are . b"t-addressa e. C 7. In Question 6, is ~e regithstee ,-';,/oag for high in 8051 . 8. Show how to morutor
:Us
I
g:S
. delays. When as counters !hey erate counters tuJle · u sed used as timers they can g:ners/ for vanous modes.. The8051 has two timers/counters. Whenwed how to program the Timer 0, and TLl and THl fo~ Tuner l. Boin chapter sh~ reg,s . ters·· n.o and for4 bits . o f TMOD a re used for Tm1er Oand~ can serve as e~ent counters. This ed as two S-bit TheTHO lower
SUMMARY
)
p >
r
The two tuners are access
.
peration modes.
O
timers use the TMOD register to set timer th timer as a 13-bit timer, mode 1 sets it as 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 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 TMODcrystal. value for both Timer Oand Timer 1, mode 2, software start / stop (gate "' 0), with the clock coming the80SJ's
10. (a) Find frequency timer20 if the crystal attached to the 8051 has the following values XTthe AL= 11.0592 and MHzperiod used by (b) the XTAL= Ml-iz (c)XTAL=24MHz {d)XTAL=30Ml-[z JI. What is the difference in the timer lengths in modes O, l, and 2? 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. 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 TMOD, #01 n or timing IS MOV THO,#O!'FH
°-·
MOV
TL0,#00
SETB
TRO
17. Assuming that XTAL= 16 MHz, indicate when the TFo MOV MOV
232
TMOD, #01
TLO, #l2R
. Oag IS raised for the foll
.
Owtng
program.
J
J l
l
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 THO, #FOH
sSTB
TRO
l'l)V
;.ssuaungthat XTAL = 20 MHz, indicate when the TFO flag is raised for the following program. t9. Yl)V -,,ov
TMOD, # 0 1 TL0,#12H THO, #lCH
l'l)V
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 l!OV l!OV
TMOD, # lOH TLO, #33H TH0,#05 TR1
sm
!·
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. l\!:PT . ilACK;
~AlN:
\ t 11\d
MOV MOV CPL MOV MOV
SETB JNB CLR CLR DJNZ SJM P
TMOD, #lOH R0,#10 P2.4 TLl,#05 TH1,#50H TRl TFl,AGAIN
TRl TFl RO, BACK 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 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 (b) MOV
I
,
SECTION 9.2: COUNTER PROGRAMMING th tiJJletS operate as counters? . d to. makeeachof e · 43. How is the TMOD register modifie 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. 1 47. Program Timer 1 to be an event counter. Use m . .. the initial count to 20,000. od and display the binary count on P2 continuously. Set the lllltiii 48. Program Timer Oto be an event counter. Use m e 2 . count to 20 d dis lay the decin,al count on P2, Pl, and PO continuoU!ly 49. Program rimer 1 to be an event counter. Use mode 2 an P Set the initial count to 99. . f h · er? 50. Which bits of the TCON register function as start bits o I e tim · SJ. Which bits of the TCON register are the timer rollover fla~s.1 52. How can an external frequency be counted using the 8051.
SECTION 9.3: PROGRAMMING TIMERS OAND 1 IN 8-051 C 53. Program TimerO in C to generate a square wave of 3 kHz, Assume that XTAL = 11.0592 MHz. 54. Program Timer 1 in C to generate a square wave of 3 kHz. Assume that XTAL= 11.0592 MHz. 55. Program Timer Oin C to generate a square wave of 0.5 kHz. Assume that XTAL = 11.0592 MH;:. 56. Program Timer 1 in C to generate a square wave of 0.5 kHz. Assume that XTAL = 11.0592 MHz. 57. Program Tuner 1 in C to be an event counter. Use mode 1 and display the binary count on Pl and P2 continuouslv
Set the initial count to 20,000.
•
58. lllltial P~ram Timer Oin C to be an event counter. Use mode 2 and display the binary count on P2 continuously. Set tht count to 20.
ANSWERS TO REVIEW QUESTIONS SECTION 9.1: PROGRAMMING 80.51 TCMERS 1. Two 2. 2, 8
3. 8 4. False 5. 0010 0000 indicates Timer 1, mode 2, software start 6. FFFFH to 0000 and stop, and using XTAL i fr 7. FFH 1000 or equency. 8. -200 is 38H; therefore, THI "38H 9. 2 ms/1.085 ms= 1843 = 0733H where TH "07H an 10. 100 ms/1.085 ms= 92 or SCH; therefore, TH = SCHd TL= 33H SECTION 9.2: COUNTER PROGRAMMING
I. The crystal attached to the 8051 2. The dock source for the timers comes from · 3. Yes Pins TO and Tl. 234
'
-
~,iernust use the inst'"'.'c~on "SETB P3. 4µ to configure the Tl pin as input, which allows the clocks to come from 1 external source. Th.is IS because all ports are configured as output upon reset. 111
;. 5Ef8TRI I
s£Cf10N 9.3: PROGRAMMlNG TIMERS O AND 1 IN 8051 C n,e crystal attached to the 8051 \ runer 2, mode 2, 8-bit auto reload FffFH toO i FfHtoO s. 38H
i
~ TMOD i Yes s. while (TFl ==0);
•
I
v CHAPTER 10
8051 SERIAL PORT PROGRAMMING IN ASSEMBLY AND C "' -e. cl .J2
OBJECTIVES Upon completion of this chapter, you wiU be able to:
>
> >
>
>
>
>
>
> >
>
>
>
>
Contrast and compare serial versus parallel communication list the advantages of serial communication over parallel Explain serial communication protocol Contrast synchronous versus asynchronous communication Contrast half- versus full-duplex transmission Explain the process of data framing Oesribe data transfer rate and bps rate Define the RS232 standard Explain the u,e of the MAX232 and MAX23.3 chips Interface the 8051 with an RS232 connector Discuss the baud rate of the 8051 Describe serial communication features of the 8051 Program the 8051 aerial port in Assembly and C Program the l«'Oltd serial port of DS89C4x0 in Assembly and
•
,,-
·-· ·~ >·
.....
c
237
I
t often 8 or more lines (wire~lld raJJel data trans ~Jel transfers are printers and hardu~,
r:;t
In':.
ExaIJ1PJes of be transferred in a short amount ~'.a. . araJJel and serial. 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~ 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 2 10 the data is sent a bytebilio:tymbouilretain~o it thereby making passuru•·cation, Jn 5ecbodin. us.'s ed in Section 10.3. The second~ mmunication capa ' . f · I comiJl on51 is sc 'al -·"1 co In thlschapterwefirstdiscuss thebas'.cs o ~ am01ing of the ""i C rogramming for sen ports #Oand #1, via MAX232 line drivers is discus~- Se~al . ~°tn J0.5 covers 805 p 4 port of 058901x0 is prograwned in Secaon ·
c;,:
io
SECTION 10.1 : BASICS OF SERIAL CO
.,
MMUNICATION . . vides the data in byte-siz~ chunks. In somecasei,
11 pro . 'th the outside world, -a~ted to the 8-b,tdata bus of thepri••· occssorcommurucates,_, · d tabusan d P•=-· ··"" a nucropr_ . . . grabbed from the 8-b,t a . . L d even distort signals. Furthermore, an 1 such as printers the information IS sunp Y bles dimJIUS" an be tw fems I 8.llt This can work ~nly if the cable is not too long, since Ion? C:on is used for transferring data ~~d to fers
-,
When
:ys
:ck
;<., I
.
• I
r
v
. In darn transmission if the data can be transmitted and · . . s1mpltx trarLSmissions such as with printers in which th r~ived, ,tis a duplex transmission This is in contrast to
Sender
I
•[ Receiver J
I $
e computer only sends data . Duplex tr~smissions can be half
Serial Transfer
I
I
••
Halt- and full-duplex transmission
'
V
''
'' •'
'• '
•'• •
i
Para!Jel Transfer Sender
DO Rece1\ler
•'
••'
''•
•
Figure 10. I. Serial versus P•r•lleJ D•ta Transfer
'' '
D7
238
'
-
V
Simplex
•[
Transmitter
Receiver
I 'T,v ,
~1..1D
I
v
Half Duplex
I"-~ V
Transmitter Receiver
----
r/ Full Duplex
l
~
Transmitter
I
Receiver
I
·I
Transmitter
..
,
Receiver
Receiver
,/1
[
Transmitter
figun, 10.2. Simplex, Half-, and Full-Duplex Transfers
full duplex depending on w he ther or no t the d ata transfer can be s imultaneous. If data is trans mitted on e way at a 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
:ne,
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. ' ,· , '-I . ,....oc#..._"'"- J -0 \ "- ;..-"'._r.r,.V. ........... • '"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.
(
I.) (:>.Q_ 1
,r'
V S,,. r
Start and stop bits
1..1.\\\Vc_~.j
A't,"'<-'-
~C.:.v<.,. -
1..-, ...,-,\\-t.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
..
•
stop
Space
bit :
t
1
0
..
..
0 :
...• . .. :
0
.. .. 0 . .
goes o ut last
.. .. 0 .. .. .
. .. .. 0 . : ..
:
start
1
DO
:
mark
bit
..
+
. ..
..
goes out first
-~ISEJl~:-;;;.;:;;:~ ;::-:;;:;:-::::;:::;;:::::::-:-:::::~~~~ ~~~_;_......::.=-~~~~~ 0.3. Froming ASCD • A• (41H)
UAL PORT PROGRAMMING IN ASSl!MBtY AND C
I
V •
t
. the device sufficient time to organi~ 1 b·ts were used to give stop bit is standard. Assuming Iha~ slowness of the receiving mechanical device, two~h~wever, the use ~~~:ieof 10 bits for each character: 8 b!ts for "'• before transmission of the next byte. In mod~ g 1 stop bit, we have; 8-bit character there are an extra 2 bits, w~ are transferring a text file of ASCU characters u~its. n,erefore, for ea . . ASCU code, and 1 bit each for the start and stop '-ame in order to mamtain data inteo.; in the data" ·ty b·t dd· · .,.,~ 1 · g;ves 20% overhead. b te is included have a single pan '" a •hon to~ In some systems, the parity bit of the ch~ra~tepenrYding on the system)_w; number of data bits, including the Pilll This means that for each character (7- or 8-bit, e fan odd-parity bit e ty and stop bits. The parity bit is~d.oreven. In the~~ty bit system T bl l0-1: RS232 Pins (DB-25) bit, has an odd number of ls. Sunilarly, 1~ an_e~en en For example, ::,a'.:.'.:.e:..=.:.....~-:::::;::-;.;::-- - - - - - the total number of bits, including the panty bit, is ~v the even-parity PP~in~---:D~e:;s~c~r-;:ip::'.ti:·o-:n==:.---the A5CD character "A", binary ~100 OOOl, has O ~r r odd-,even-, ;.. Protective ground bit UART chips aUow programming of the panty bit fo .:l_ _ _ _ and no-parity options. ;. 2 _ _ _-:]:.ran~s_nu_·-,-tt:ed=d:at;;a~(T;::-x:--0-')'----~ Received data (RxD) 3 Data transfer rate ::.----R:_.:e:.q~u-es-:t-:to-sen--",d;--;(:;:;RTS~)--• ti. ·s stated 4 The rate of data transfer in serial data commuruca on 1 ~ - - - - - : ~ ' - - - - - ; - ~ ~ . . . . . ; ._ _ __ • in bps (bits per second). Another widely used tenninology for bps lS S Clear to send (CTS) baud rate. However, the baud and bps rates are not necessanly equal. :;:_____0:..:a_t_a_se_ t -re_a_d:--y'-(::DS~R;e:)- - - 6 This is due to the fact that baud rate is the modem tenninology and is defined as the number of signal changes per second. In modems a 7 Signal ground (GND) single change of signal, sometimes transfers several bits of data. As :....----0-'a"-ta_c..::ar'""r-ie_r_d-:-e-t_ec_t_(DC:;:::=D=)--8 rar as the conductor wire is concerned, the baud rate and bps are the same, and for this reason in this book we use the terms bps and baud 9 /10 Reserved for data testing interchangeably. -'-----U-n_a_ss_i_gn_e_d-----"--11 The data transfer rate of a given computer system depends on communication ports incorporated into that system. For example, the 12 Secondary data carrier detect early IBM PC/XT could transfer data at the rate of JOO to 9600 bps. - - - - - -,,-___.:....__ _ _ _..:;.=:.:.....ln recent years, however, Pentium-based PCs transfer data at rates _13_____.,.,_co_n_d_ary_,__c_l_ear_t_;o_sen;___:.::d:...._ _ as high as56K bps. rt must be noted that in asynchronous serial data 14 Secondary transmitted data communication, the baud rate is generally limited to 100,000 bps. - ---------'---;___:....:..::...=:::....15 / Transmit signal element timing
~.:..:.:.=-::=~-::;::-:=-;:;::~:----
RS232 stan dards
16
To a!Jo"'. compatibility among data communication cc:iwpment made by vanous manufacturers,'."' interfacing standard caUed R5232 was set by the Electr01Ucs Industries Assoeialion (ElA)" 1960 In ii was modified and called RS232A. RS232B and RS2J~~ · . l963 in 1965 and 1969 respective! In this were issued RS232. Today, RS232 is the 1 wide~!;:,":~r17~t. simply as standard. Tlus swidarcl is used in PCs and nume~ ~nt~rfa~g O equ,pment. However, stnce the standard was set I bef the Til. logic family, its input and output vit'::ge or:i:he advent of I ~m3palib25le. In RS2J2, a l is represented by -3 to _;,vv arehilnot .IS ~ to+ \!, ~king 3 to +3 undgfin~ Por this - ' w ea Obit any R5232 to a microcontroller system we m t reason, to connect such as MAX232 to convert the Til. logic !eus ;:,se voltage converters levels, and vice versa. MAX232 IC chips are ve to the RS232 voltage line drivers. RS232 connection to MAX23z i s : = ~ referred to as in Section 10.2. RS232 pins
!~
rn.
Table 10-J provides the pins and their 1 commonly referred to as the DB-25 conn~bels for the RS232 cab! refers to the plug connector (male) and DB-~~-. ln labeUng, DB-2Se, nector (female). See Figure 104. IS for the SOcket p
con-
Secondary received data
17
-:-:-_ _ _ _R_ec :.:..:e:..: iv_:e:..:s:.:ign!2:'.::al::...:e::l:::em:.:.:::e::.n.'. .t.'.'.timln~ ·::lg~ 18 Unassigned
::-----==?:.::=--------
_l9~--~Sec:=.:::::o::. nd::_a:ry~req~~ues~t~to~se:.'.n~d~20 :;:;----Da~ta:::..:t:::errrun~'.'..·:_:a!_I~rea~d:X:yl(D~'l'R~)__ 21 :;:;----~S:=iE.gn:.:a::::l~q!.::u'..'.:a'..'.:li~ty~d~et~ec~t~o~r_ __
Rin :;:;-----~·'._'.!g~in.'.!di~·~ca~t~o~r_ _ _ _ _ __ 23 ;;;----:::D.::a~ta:_:s'..'.jign~a~l_.'.:r~at~e..:se~lec:,t~--22
24
;;;----~11~ran:'...'.:snu~~·t..:s~ign~al~e~lem~~en~t~timll1~· ~·~g-~- - - - . : :U:'..'.n!as~~i~gn~e~d:__ _ _ _ _ _ 1
0
13
• • •• • • •• • • • • • •••• • • • • • • • •
0
14
Fisu.re 10-4 RS23 · 2 Connector DB-25
TH}:
sos1 t.t1ca
0CONTROtt
.-
ER ANO EMBEDDED svsf91S
I
.
not aJI the pins are used in PC cables, IBM introduced the 0~9 ~illce0 f the serial 1/0 standard, which uses 9 pins only, as shown m 00 r~ 0-2 The DB-9 pins are s hown in Figure 10-5. fable I ·
/ commun1catton · . oata cI asst'fl ca t·10n
.
current terminology_ classifies data communication ~q~pment
.3:
(data terminal eqwpment) or DCE (data commwucabo~ eqwp [)'!£) DTE refers to terminals and computers that send and receive data, refers to comm~cation equipm~t, such as modems, th~t •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
~:·ocE
~or
"e,~ simplest connection between a PC and microcontroUer requires a aurumum of three pins, TxD, RxD, and ground, as shown in Figure 10-6.
Notice in that figure that the RxD and TxD pins are interchanged.
Table 10-2: IBM PC DB-9 Signals Pin
Description
1
Data carrier detect ([)CD)
2
Received data (RJ
4
Data terminal ready (DTR)
5
Signal ground (GND)
6
Data set ready (DSR)
7
Request to send (RTS)
8
Clear to send (CTS)
9
Ring indicator (Rl)
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 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.
I
•
~--------------,
5
1
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 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 reference and they can be bypassed since they are not supported by Ille 8051 UART chip.
Transmitted data (TxD)
3
o
0 \
6
9
L - - - - - - - -- - - - - - - - - ' Figure 10-5. OB-9 9-Pin Connector
DTE
RxD
DTE
RxO
2. OSR (data set ready). When DCE (modem) is turned on and has ground gone through the self-test, it asserts DSR to indicate that it is 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
'
, ed as follows: While signals DfR . lion can be suJTUllliavnzeand well, it is RTS and CTs that a~ munica .... . . C and modem com . . te that they are a d in response, 1'f th e m odem ·IS ready 0,. from the above descnptlon~ 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 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 0
,
i:~~~n°:~~y~~~'
4B6, and Pentium)chmicfr:;0 386 b ed x86 (8086, 286' ' use one ea o '"'-'2 IBM PC/ compatible computers asRS;·type connectors. Many 5 resent time COM 1 is used for the m Use 0 two COM ports. Both COM ports h~ve ed COM 1 and COM 2. At the p serial port to the COM 2 port of a PC for connectors. The COM ports are des1gnat as We can connect the 5051 and COM 2 is available for devices such as a modem. ext section we disc serial communication experiments. ady to look at the 8051. In then . USS illP With this background in serial communication, we are reSecti' 10_3 we show how to program the 8051 senal com. . of the 8051 and RS232 connector, and m on physical connection
IBM PC/compatible COM ports
•
~
re
munication port.
\
. I j
Review Questions 1.
·' I
r
2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
12.
The transfer of data using parallel lines is - - -- (faster, slower) b u t - - - - - - - (more expensil'e, less expensive). True or false. Sending data to a printer is duplex. . True or false. In fuU duplex we must have two data lines, one for transfer and on) for ~1ve. The start and stop bits are used in the (synchronous, asynchronou~ met ·. b. . 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. In Question 5, f:ind the overhead due to framing. 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? True or false. RS232 is not ITL-compatible. What voltage levels are used for binary Oin RS232? True or false. The 8051 has a built-in UART. On the back of x86 PCs, w~ normaUy have COM port connectors. The PC COM ports are designated by DOS and Windows as and
---
SECTION 10.2: 8051 CONNECTION TO RS232 _In this section, the details of the physical connections of the 80.S
.
. I to RS232 connectors are given. As stated in Secbon l0.2, the RS232 standard is not m compatible· th f to convert RS232 voltage levels to ITL levels and vi e' ere oThre, '.t requires a line driver s uch as the MAX232 chip MAX232 chi · th . ' c versa. e tnterfac· f 80 p 1s e main topic of this section. mg o 51 with RS232 connectors via the
RxD and TxD pins in the 8051 The 8051 has two pins that are used speci6caU i caUed TxD and RxD and are part of the port 3 ro Y or transferring and receiv· . . pin 10 (1'3.0) is designated as RxO. These pins! ~ (P3.0 •nd P3.1). Pin 11 of thmg data serially. These two ptnS art' RS232 compatible. One such line driver is the M~~ co_mpali_bl~; therefore, th e 8051_ (P3.l) is assigned to TxD and chip. This 1s diSCIJssed ey require a lliie d river to make them
MAX232
next.
Since the RS232 is not compatible with toda 's · converter) to convert the RS232's signals torr( i;ucropr<>cessors and
.
:~::ntroJJers,
One example of s uch a converter is MAX232 fr~~ ~~';;.els that Will w e need a line driver (,•oltagt! Corp. (\\'Ww. . P~ ble to the 80Sl's TxD and RxD plll> 242 ma)(Jm. ic.com). The MAX232 con\'ertll ft
T!iE 80s1 Mic R<>coNiROLL
ER AND EMBEDDED 5ySl'Pd
'
,., voltage levels to TTL voltage levels, and vice versa. One ad vantage of the MAX232 chip is that it uses a +5 V power p:.32 which, is the same as the source voltage for the 8051. In other words, with a single +5 V power supply we can ~b<>ththe8051 and MAX232, ~ith no need for the dual power su pplies that are common in m~y older syst~ 1""n,e MAX:232 has two sets of line drivers for transferring and receiving data, as shown "' Figure 10-7. The line r.;used forTxD a recalled Tl and T2, while the line drivers for RxDare designated as Rl and R2. In many appbcaJfl''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
I
:Jell
I
./ 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 See Figure 10-8 for MAX233 with no capacitor used.
.~wm3.
Vee
C3
16
+ Cl
I 3 MAX232
+
6
4
5
C2
Tl-
Tl L,
u
R1,,.
RI°"'
12
n..
10
T2ou,
i?4 14
TxDO (P3.1) 11
RxDO(P3.0)
10
11
14 13
2
3
Q~
12
DB-9
13 7
8
15
TILside
MAX232
8051
R2.,
~
9
'
+
2
RS232 side e
fi&,,tt t0-7. fa) Inside MAX232 and (bl its Connection to th e 8051 (Null Modem)
Vee 13r-- -7L---~ 14
12
8051
MAX232
TxOO (P3.1 ) 3
2 l
20
n ..
Tl""'
Rloor
RxDO (P3.0)
10
4
2
3
5 4
2 _
3
os c_n
DB-9
T2ou,
n,,.
18
R21N
~
TILside
5
Rl.,
u
6
9
19
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
'
· functions'. Review Questions . the R5232 t~ed what are t h e1r OM port connector ts unicat,on, an True or false. The PC C 'd for serial comm 1. Which pins of the 8051 are set as, e232 used for? RJCD. TxD and '~'.;!!~hip? ; : What a.re line drivers such ~ MAX232 can support MAX23 over the MJ\.N-J 3 5. What is the advantage of the MBLY
:~i
/
ORT PROGRAMMI d how how to SECTION 10.3: 8051 SERIAL p . . reoisters of the ~ t an sputers are so . • 1 mmun1cahon o· I rnpatlble com . . 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 syswidely 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. tem without any error, we must ma e sure pported by PC BIO are d clickrate of the PC's COM port. Some of the baud rates s;indows HyperTerminal progr~m ~ o,vs You can examine these baud rates by g?mg to th~ Terminal program comes with Wind · ing on the Communication Settings option. The ~~~rthe ones listed in Table 10·3. HyperTermina.l supports baud rates much higher
• ~
•
,,J'•) i:.
I
r:
(J ,, I
'r
Table 10-3:
PC Baud Raies 110 --......
NG IN ASSE
\../
v ISO--.... 300--....., 600 - 1200
2400
9600 19200
i/
Baud rate in the 8051
f;!.i-'< 5 \
S«-c.
.
.
d'f!
t baud rates. The baud rate m the
Nole. Some o/ the Lui ratessupPOrtectby,156; Pentium IBM PC~
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<: will look at the relationsrup between the crystal frequ':"~ and the baud rate m the 8051· . . 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
3 once more before it is used by Tinier I to set the i>aud rate. Therefore, 9600 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-400 When Timer l is used to set the baud rate it must be programmed in 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:"" XT=A :cL,-•- ,-ll"" .om = -M - l-i.i-. - - - - - - - 10-J shows how to verify the data in Table 10-4.
With XTAL-11.0592 MHz. find the THI value needed t ha th (a) 9600 (b) 2400 (c) 1200 ve e following baud rates.
°
Solution: With XTAL= 11.0592 MHz, we have:
where -3 ~ FD
(
'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.
tivation of the 8051 RESET
pin.
11,0592 MHz 28,800 Hz
Machine cyde freq.
XTAL oscillator
+
12
+32 by UART
921.6 kHl.
To TI mer I to set the baud
rate
r
.t
sBUF regts er
s,,__,,_~
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:
;load SBUF=44H, ASCII for '0' ; copy accumulator into SBUF ;copy SBUF into accumulator
SBUF, #' D' MOV SBUF,A MOV A,SBUF
II/JV
I
The momenta byte is written intoSBUF, it is framed with the start and s top bits and transferred serially via the TxD pin. Similarly, when the bits are received seria lly via RxD, the 8051 deframes it by elilninating the stop and start bits, making a byie out of the data received, and then placing lt in the SBUF.
-rSCON (serial control) register The SCON register is an 8-bi t register used to program the start bit, stop bit, and data bits of data framing, an,ong otlwr things. Figure 10-9 describes various bits of the SCON register.
v SMO, SM1
SM? and SMl are D7 and D6 of the SCON register, respectively. These two bits determine the framing of data by specifying the number of bits per character, and the start and s top bits. They take the following combiJ,ations:
I SMO I SM! I SM2 I REN I SMO SM1 SM2
REN
~g•rt10.9
......_
SCON.7 SCON.6 SCON.5 SCON.4 SCON.2
RI
SCON.O
Nolt:
Make SM2, Tll8, •nd RBS e O.
SCON.I
Tl
RI
Transmit Interrupt nag. Set by hardware at the beginning of the ,top _bit in mode t. Must be cleared by software. Rccc,v~ mte~pt Oa.{!. Set by hardwan.- hallway through the &top b,t time ,n mode I. Must be cleared by software.
s
· CON ~al Port Control Register (Bit-Addressable!
!os1 SElJ.>.
RBS
Serial port mode sp«i6er Serial port mode sp«:ifier Used for multiprocessor communication. (Make it O.) Set/cleared by software to enable/disable reception. Not widely used. Not widely used.
TBS RB8 Tl
SCON.3
TBS
L PORT PllOCRAMMINC IN ASSEMBLY AND c
'
SMO 0 0
Serial Mode O top bit I start bit Serial Mode 1, 8-bit data, 1 5 ' Serial Mode 2 l 1 1 Serial Mode 3 . for the other three modes is in Append.ix,, explanation d f · · 8 b. ''-{ h er . . 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 · Y are transferred, where the first bit is the start bit, follow
/
.
,
SM1
o 1 o
./ 2 SM
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 multiproetsdiscussion 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
v
~88 (receive bit_S) is bit 02 of the SCON register. In serial m . . 1• this bit gets a copy of the stop bit when an IJ.bd ode data as received. This bit (as is the case for TB8) is 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. 3
.
Tl
Tl (transmit interrupt) is bit DJ of the SCON re . . . . gaster. This 1s an extreme! · ter. When the 8051 ftnishes the transfer ( h •mp_ort?nt flag bit in the SCON regi;another byte. The TI bit is raised at the ~ t. e ~-bit character, it raises the TI examples of data transmission are given. guullng of the stop bit. We will discu~~ indicate that it is ready to tranSfef its role further when programming - / RI
or
. Rl (receive interrupt) is the DO bit of the . register. When the8051 receives data seriaJJ ~ON register. Tlus is an th O er extreme! · Yvia RxD it gets ·d register Then ii raises th RJ 11 is halfway Im ~ th ag bit _10 indicate that ;byte h n b of the start and sto b .Y unportant flag bit in the SCON oug e stop bit, and we wiJJ soon as een received and hp •ts and places the byte in the 581.J see how this b·•tis . USed ·s Ould be P•=ed ·-•- up before it is lost RI / p . rogramm1ng the 8051 to transfer data I 111 programs for receiving data senaU, 1n ~rally · programming the 8051 to transfer char acter bytes senau 1 The TMOD register is loaded with th y, the following Ste I the baud rate. • va ue 201-!, indicann ps must be taken. & theUSe 0 ( . Timer J 111 • rnocte 2 (8-b1t auto-reload) to st1 246
raised
.
n,e THI is loaded with one of the
values in Table 10-4 to set the bau
d
( rial data transfer (assumi ng ra te or se
l X'fAL = 1t.0592 MHz). ' h s-b·t 1 data is framed ,vith start u,eSCON register is loaded ,vi th the value SOH, indicating serial mode 1, w ere an 3· .i11d stop bits. l,
I
Till is set to 1 to start Timer 1.
,.• nisdeared by the " CLR
T I • instruction.
6- The character b yte to be transferred serially is written into the SBUF register. The TI flag bit is n,onitored with the use of the instruction •JNB TI. xx " to see if the characte r has been trans·
7 · ferred completely.
s.
To transfer the next character, go to Step 5. Example 10-2 shows a p rogram to transfer d ata serially a t 4800 baud. Example 10-3 shows how to tra
nsi r "YES" e
continuously.
Importance of the Tl flag To understand the importance o f the role of Tl, look a t the following sequence of steps tha t the 8051 goes thro ugh in transmitting a character via TxD. I. The byte character to be transmitted is written into the SBUF register. I
2. The start bit is transferred.
Example 10-2 Write a program to transfer a letter 'Y' serially at 9600 baud continuously, and also to send a letter 'N' through port 0, 1vhich is connected to a display device.
Solution: Here one byte of data is transmitted serially through pin 11 (P3.1), and another is sent in parallel form through port 0. •y•
P3.!
r
. ..> '
~
8051
~
1----l"''N' - ',
1---~i,/....._D_IB_P_LA_Y__, ~
I : I
I----=-----
_____...:...:.. PO
TMOl>, #20H THl,1·3 SCOll,#SOH
:t,.,,,y, CLR MOV
TI,RBRB TI PO,t•••
SJMP
MMDI
;Timer 1 , mode 2 (auto-reload) ; 9600 baud rate ,:.Ori ;8 bit, 1 atop, REN enabled ;atart Timer 1 ;tranafer 'Y' aerially ;wait for tranemiaeion to be over ;clear TI for next tran•mi••ion ;move 'N' to PO for parallel t r anafer ;repeat
247
' v
r . data serially, continuously. d transfer thJS Ex•mple J0-3 fte the other an 0 I and2,onea r Take data 1n through ports ' • Solution:
/
MOV MOV \ MOV
f :~~
.
'
\. MOV SBTB RPT:
TM00,#20H THl,ii-6
SCON,#SOH PO,#OPFH Pl,#OFFH P2,#0FFH TRl
MOV
A; PO ACALL @"END)
MOV
mode
2
·Timer 1, te '.4soo baud ra bit REN enabled
' top ' ;8 bit,l sn input port ;make PO a input port ;make Pl an ·nput port ·make P2 an J. :start Timer l
.
.
. for transmissJ.on ;call subroutJ.ne
A, Pl
ACALL SEND MOV A, P2 ACALL SEND
SJMP RPT . ·----------transferr,ng ser,'ally · to SBUF • MOV SBUF,A ;load data ,n . '
)!=: -
·'
JNB
Tl,HERE
CLR
TI
d ;wait for transmission to.::ion ;clear TI for next transmi
RET
3.
The S·bit character is transferred one bit at a time.
4.
The stop bit is transferred. It is during the transfer of the stop bit that the 8051 raises the Tl flag (Tf = 1), indicating that the last character was transmitted and it is ready to transfer the next character.
S.
By monitoring the Tl flag, we make sure that we are not overloading the SBUF register. If we write another byte into the SBUF register before Tl is raised, the untransmitted portion of the previous byte will be lost. In other words, when the 8051 finishes transferring a byte, it raises the TI flag to indicate it is ready for the next character. Afternew SBUF is to loaded with a new byte, the Tl Oag bit must be forced to Oby the ·CLR TI• instruction in order fat this byte be transferred.
6.
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 ~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, 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
th:
0
:;ve
rogrammlng the 8051 to receive data serially In the programming of the 8051 to receive character b t
. Y es serially, the follow· I. The TMOO register is loaded with the value 20H . d' . mg steps must be taken. the baud rate. ' '" •c•ting the use of Tuner . ... 1 2. THI is loaded with one of the values in Table 10-4 t l.n mode 2 (8-bit auto-reload) to><• 0 set the baud 3. TheSCON register is loaded with the valueSOH ind· . rate (assuming XTAL., MHz) stop bits and receive enable is turned on. ' •eating serial ltlOcfe ._ · ._, 11 ·0592 1 'w.,ere 8-bit data is framed with sblrt .....
;RI 15 set to 1 to start Timer 1. l. • •,·scleared with the "CLR RI" instruction. < "' ,. . n,e Rl nag bit is monitored with the use of the instruction " JNB RI •
h
been
as xx• to see if an entire character ·
°'
received yet.
~
When RI is ra ised, SBUF has the byte. Its contents are moved into a safe place. To receive the next characte r, go to Step 5.
I
Examples 10-4 and 10-5 shows the coding of the above steps .
.,,,, ex,111ple 10-4
. senal . f orm an d send it o ut to p ort Oin parallel form. Write a program to receive the data which has been sent m Also save the data at RAM location 60H. Solution: MOV MOV MOV /" SETB
l
~
LR
JNB MOV MOV MOV END
TMOD , #20H
; Timer l ,mode 2,auto-re l oad
THl ,#-3
;9600 baud
SCON, #SOH
; 8 bit, l stop,REN enabled ;start Timer 1 ;RI is cleared for reception ;wait for character to come in ;move received data into A ;1110ve it to PO ;1110ve it to RAM location 60H
TRl RI
RI, RPT A,SBOF PO,A 60H,A
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 '1'40D, #2 0H TB1,#01AH SC011, #5 0H
MOV HOV
MOV SBTB MOV
a' 1..
TIU
OR1R, IMYDATA
A MOVC A,eA+DPTR JZ B_l. ACA!,L 88'ID CLR
.....
;make P2 an input port ; Timer l , mode 2 (auto- reload) 14800 baud rate 18-bit, 1 atop, JUDI enabled , •tart Ti mer 1 : load pointer for 111eaeage
:get the character 1 if l ut character p t Clllt ,otherwue ~11 ,
.t~.,
249
,
' INC SJMP
DP1'R H_ l
'
2
1n
;scaa~ data on epriallY . re it s MOV A, P2 B_l: '.cransfer ial data ACALL SEND ' the ser LEDS ACALL RECV ;g:t lay it on. definitlY ;disp. lOOP 1n MOV Pl,A ;staY in che data SJMP B_l haS a . ------serial data transfer. ACC d che dat . last bit ;--------- MOV S8UF,A gone · loa until SEND: H 2 ;stay here for next char JNB TI, _ H_2: ;get ready caller CLR TI ·return co RET --------receive data serial 1'y in ACC here for c har ;------JNB RI,RECV RBCV: ;wait ·n ACC MOV A,SBUF ;save itdl for next char t rea Y CLR RI ;ge ·return to c all er RET ' ----The message ;-----------DB •we Are Ready•,o MYDATA:
I
V 1
one •next . 100P
•
·I')~ ' ~-
I
I
r
ENO
·'I
80$1
•r
To PC COM
port
"
Pl
/
TxD
LED
/
/
RxO
P2
SW
\
"
Importance of the RI flag bit In receiving bits via its RxD pin, the 8051 goos through the foUowing steps. I.
I
2 3.
t receives the start bit indicating that the next bit is the first bit of the character byte it is about to receive. The 8-bit character is received one bit at time. When the last bit is received, a byte is formed and placed in SBUF,
.
The stop bit is re<:eived. When re~eke iving the stop _bit the 8051 rnakes RI == 1, indicating that an entire character byre has been received and rnust be p,c d up before 1t gets overwritten by an incoming character.
4.
s.
By checking the RI flag bit when it is raised, we kno_w that a character has been received and is sitting in the SBUF register. We copy the SBUF content~ to a safe place m some Other register or rnem before it is lost. After the SBUF contents arecop1eddchinto a safe place, the RI llagbit rnust be forced to 0 ryOby th "CLR RI" instruction order aracter byte to be placed in SBUF F . . e th ...,...;ved cinhara cter.to aUow the next receive 1 · a, Ure to do th15 causes loss of e •=~ From the above discussion we cond_ude that by che.:king the RI fla bi ,-eel
•""""" .... ""' ''" """''"""•••~r,p1.._ "'"" "'f g w, "-, w"""' w""'"" ""If"'""' • _, ... "'~ ... "',,"""by ....,. "'' "-~,.. """' !:"" •• - ... S,,.. - ""-·~· ""'!".,, f
2.50
Ythe Programmer With an instruction such as
,
also must be noted that if we copy SBUF into a safe place before the RI flag bit is raised, we_risk copying gar~;ge. 1 0Jg bit can be checked by the instruction •JNB RI, xx• or by using an interrupt, as we will see JJl Chapter ·
;;,R:
[)Oublin9 the baud rate in the 8051
I
1nere are two ways to increase the baud rate of data transfer in the 8051. I.
use a higher-frequency crystal.
2- (hange a bit in the PCON register, shown below.
I•
DO Q.\100
I
GFl
GFO
PO
fDL
Option 1 is not feasible in many situations since the system crystal is fixed. More intportantly, ii is n~t feasible 1,ecauselhe new crystal may not be compatible with the IBM PC serial COM port's baud rate. Therefore, we will explore option 2. There is a software way to double the baud rate of the 8051 while the crystal frequency is fixed. This is done with the register called PCON (power control). The PCON register is an 8-bit register. Of the 8 bits, some are unused, and some are used for the power control capability of the 8051. The bit that is used for the serial communication is D7, theSMOD(serial mode) bit. When the 8051 is powered up, 07 (SMOD bit) of the PCON register is zero. We can set it iohigh by software and thereby double the baud rate. The following sequence of instructions must be used to set high 07 of PCON, since it is not a bit-addressable register: MOV SETI! MOV
A, PCON ACC. 7 PCON,A
;place a copy of PCON in ACC ;make 07=1 ;now SMOO=l without ;changing any other bits
\
To~ how the baud rate is doubled with this method, we show the role of the SMOD bit (07 bit of the PCON regisler), which can be Oor 1. We discuss each case.
Baud rates for SMOD = o ,. IVhen SMOD = 0, the 8051 divides 1/12 of the crystal frequency by 32 and uses that frequency for T" 1t th wud rate. In the case of XTAL = 11.0592 MHz we have: ,mer O set e llachine cycle freq. and
=
11.0592 MHz I 12 = 921.6 kHz
921.6 kHz I 32 • 28,800 Hz since SMOO.
o
is This is the frequency used by Timer 1 to set the baud rate. This has been the b ·
f
0 !ht default when the 8051 is powered up. The baud rate for SMOD O li ads~ all the examples so far since it = was ste m Table 10-4.
Baud rates for SMOD = 1 IVith the fIXed crystal frequency, we can double the baud rate by iliePc
kin SMO0 1 lo set ~N cegister) is set to 1, 1/12 of XTAL is divided by 16 (instead :;;2) ! d tha . = · When the SMOO bit (07 of 1 e baud rate. In the case of XTAL= 11.0592 MHz, we have: t 15 the frequency used by Timer 1 l!ach · •na 1.ne 921 6
·
--
Thi$.15
cycle freq. • 11. 0592 MHz I 12 = 921. 6 kHz
kH
z I 16 = 57,600 Hz since SHOO. 1
the frequency used by Timer 1 to set the baud rate
.
~ISEJt;;;:~:;;:;.;:~~~;;;~~;;;;~~~..,......__,..,........,......~..,......~~..,........,........,........,........,........,......_ ~IAJ. PORT PROGRAMMING IN ASSEMBLY AND C 251
'
.,,00 == oand SMOD = 1 S ·son for JV•
Table 10-5: Baud Rate Compan
sMOD"' o
SMOD - l
THJ
9,6()() ,BOO 4
19,200
( Decimal)
(Hex)
-3
FD
FA 12
F4
-24
E8
/
I
2,400 1,200
9,600 4,800 2,400
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 10-6 through 10-10.
., .
u,
'
17
lllple.
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.
·'I
MOV
A, PCON
SETB MOV
ACC. 7
MOV
'r A_l:
MOV
1'MOD,N20H THl,-3
HOV
SCON,#SOH
SETB MOV CLR
TRl
MOV H l:
PCON,A
A,#"'B"
TI
Jl'lB
SBUF,A TI H_l
SJMP
A1
Solution:
;A= PCON
;make 07 s 1 ;SMOD • 1, double baud rate ;with same XTAL freq. ;Timer l, mode 2 (auto-reload) ;19200 (57,600 I 3 = 19200 baud rate ; since SMOD•l) :8-bit data,l stop bit, RI enabled ;start Timer 1 ;transfer letter B ;make sure TI• O :transfer it ;stay here until the last bit . ;keep sending ., 8 ,, . 1.s gone again and again
(a) This program transfers ASCU letter B ( (b) With XTAL: 11.0592 MHz and SMOoo!~lO binary) continuously.
in the abo,•e pr tl.0592 MHz/ 12 z 921 kH . ogram, we have: 6 921.Q kHz I 16 =57,600 Irz machine cycle frequency 57,600 Hz/ 3: 19,200 bau~ ~!uency used by Timer 1 to set th b e aud rate
H
Example 10..7 If the crystal frequency is 22 MHz SMOD : 1? ' what wiU be the ba
Solution:
With a 22 MHz crystal, the calculation IS the
Ud rate if. (a) THt 3 - - ; {b) Tl-lJ" -12 with Sl\.iOO,. 0 and
5'1me as on Ex
ample 10-1.
252
~tOD 111th S'
=O. we have
22 ·-' freq - = 1833 KHz ,i.,dun~ cyue .- 12 I
~=57.281 KHz= 57,281 p,d .31
-
(a) \Vith THl = -3, the baud rate is (b) With THI = - 12, the baud ra te is
57, 281
3
= 19,093
'<> "\M...&
57,281 = 4773 12
11,lh 5'"10 D = 1, the baud rates a.re do ubled. (a) iVith THl = - 3, the baud rate is 38,186 (bl With TH I = - 12, the baud rate is 9546
,/
find the baud rate if THl = - 2, SMOD = 1, and XTAL = 1l.0592 MHz. Is this baud rate s upported by IBM/ com pa~ble PCs? Solution: \\'ith )ITAL= 1l .0592 MHz and SJ\100 = 1, we have Timer 1 frequency = 57,600 Hz. The baud rate is 57,600 I 2
=
28,500. This baud rate is no t s upported by the BIOS o f U,e PCs; however, the PC can be programmed to do data tran.fer at such o speed. Also, HyperTerminal in Windows s upports this and other baud rates.
Eumple 10-9 Port Oof an 8051 is used to monito r a parameter in an industrial environment. Uthe parameter gives a readjng aboveOFl-1, a n1essage 'HI' is to be sent serially. Otherwise, a message 'OK' is to be sent. The words 'HI' and 'OK' a,.. burned into progr,1m ROM locations
Ttsr,
CJ.
OOOOH PO , #OF FH '!'MOD , #20H
ORG MOV MOV MOV MOV
SCON, #S OH
SETS
TRl
MOV CJNE
A , PO A, #OFH, TEST
SJMP
OK
JNC
HI DPTR,#OOAOH
MOV
THl , # -3
ACALL ACCESS SJMP
;make PO an input port
CHSCK
: move PO into A
; check if it is equal to OPII, if not go to TEST ;if equal to OFH, go to OK ;if it is greater than OFH, go to HI ; let DPTR point to me••age Olt ;call subroutine to ace••• .,.••age ROM area ,continue lll<>Ditoring PO
•
'
sage HI int co mes oP'J'R po , to acce ss mes s ag e area
DPTR,#009011 ;let ··"-rout111e . PO ACALL ACCESS •-call . s= ue moo1· coring where me ssage s are stored . ;cont1n ROM area SJMP C!!ECK program ····--- subroutine co access CLR A ACCESS: A MA+DPTR MOVC ,• HOV
HI:
,-----·
ACALL SEND
INC CLR MOVC
.._./
DPTR A
A,eA+OPTR ACALL SEND RET ··············subroutine to send data serially MOV JNB CLR RET ORG DB ORG DB
SEND ,
HERE:.
MESI: MES2:
S8UF, A
T!,HERE TI 009011 "'HI"'
OOAOH "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.
REPT : BACK:
ORG MOV MOV MOV MOV SETB HOV CLR SETB
.me CPL CPL MOV CLR CLR
254
OOOOH TMOD,#2 2H SCON,#SOH THl,#- 3 THO,#OOH TRl A, #OOH Pl . 2 TRO TPO,BACK A
Pl.2 SBOP,A TRO TPO
;Timer O and Timer l in made 2 ;count value for Timer 0 ,start Timer 1 ;move A e.Oo
;start Timer 0 ;watt for Timer ;complement A
o ro11°"9r
ICO!llplement P1.2 ;move A to S8t,p
; •top Timer a for trana111••ion ;clear Timer o llag
JNB
TI , HERB
CLR
Tl
SJMP END
REPT
;check for TI Oag t transm~ssion ·clear TI to enable nex ' ;repeat thewh o 1e process I
I
terrupt·based data transfer
.
th Tl and Rl flags. In order to n . e h t use 6 now you might have noticed that it is a waste of the ~,croc~n f oiling. In Chapter 11, we will show ow 0 . ywasti'.ng the microcontroller's time we use. interrupts a,·01d • t 1nstea o P interrupts to program the 8051's serial communication por · trO ller's tm,e to po 11
'
Review Questions Which timer of the 8051 is used to set the baud rate? . t the baud rate? I. If XT 11.0592 MHz, what frequency is used by the llmer to se . ;· Which mode of the tin,er is used to set the baud rate? . have a baud rate? Give the answer in 9600 1 0 With = 11.0592 MHz, what value should be loaded mto THI t both decimal and hex. . . To transfer a byte of data serially, it must ~e pla_ced m register __.
AL= XTAL
:: SCON stands for and it is a~n) _._-b1t ~eg:t~r.framing information s uch as the stop bit? 7. Which register is used to set the a tabsize an to er s. True or false. SCON is a bit-addressa 1e regis e r. 9 When is Tl raised? 10 Which register has the SMOD bit, and ,vhat is its s tatus w nen the 8051 ·is P0 we red up'·
SECTION 10.4: PROGRAMMING THE SECOND SERIAL PORT Man of the new enerations of the 8051 mkrocontroUers come with two serial ports. The DS89C4~0 (DSS9C4i0/30/40/ ...) an~ DS80C320 a.re among them. In this section we show the programming of the second senal port of the DS89C4x0 chip.
DS89C4x0 second serial port The second serial port of the DS89C4x0 uses pins Pl.2 and Pl .3 for the Rx and Tx Lines, respectively. See Figure 10· 10 The MDE8051 Trainer (available from www.MicroDigitalEcLcom) uses the DS89C4x0 chip and comes with two se;ial ports already installed. It also uses the MAX232 for the RS232 connection to 089. The connections for the RS232 to tne DS89C4x0 of the MDE8051 Trainer a.re shown in Figure 10-11. Notice that the first and second serial ports are designated as Serial #0 and Serial #1 , respectively.
Addresses for all SCON and SBUF registers All the programs we have seen so far in this chapter assume the use of the first serial port as thedefaultsetiaJ port since every version of the 8051 comes with at least one serial port. The SCON, SBUF, and PCON registers of the 8051 are part of the special function registers. The address for each of the SFRs is shown in Table 10-6. Notice that SCON has address 98H, S81JF has address 99H, and finally PCON is assigned the 87H address. The first serial port is supported by all assemblers •nd Ccompilers in the market for the 8051. U you examine the list file for 8051 Assembly language programs, you will see that these labels are replaced with their SFR addresses. The second serial port is not implemented by all versions of the 8051152 microcontroller. Only a few versions of the 8051/52, such as the DS89C4x0, come with the second serial port. As a !tsult, the second serial port uses some reserved SFR addresses for the SCON and SBUF registers and there is no universal ~ment among the makers as to which addresses should be used. In the case of the DS89C4x0, the SFR addresses of illld _Cl H are set aside for SBUF ai:'d SCON: as shown in Table 10-6. The DS89C4x0 technical documentation refers to registers as SCONl and SBUFl smce the first ones are designated as SCONO and SBUFo.
~
;;--:S;ER:1A~L~P=o=R=T=P=R~OG-:::RAMMIN-::-::-::::::G~IN::-::A:s=sEMB=-==L~Y-AN~o~c~~~~~~~~~~~~~~-~ 255
\
'
DD' 40
7
39 38
(12) Pl.0 (T2EX) Pl.I (RXDI) P12 (TXDI) Pl.3 (INT2) Pl.4 (INT3) P1.5 (INT4) Pl.6 (!NTs) PJ.7
-
OS 89C4JCO (89C420 s9C430 s9C440 89C4S0l
RST
I
(RX[)()) P3.0 (TXDO) P3.l (INTO) P3.2 (INTI) P3.3 (TO) P3.4 (Tl) P3.5 (WR)P3.6 (Im) P3.7
•
·~ I
18 19 20
XTAL2 XTAL1
GNO
Vee P().0(AD0) P().l (ADI) P().2 (AD2) P0,3 (AD3) P0.4 (A D4) P0.5 (ADS) P0.6 (AD6) P0.7 (AD7) i,A/VPP ALE/PROG PSEN 1'2.7 (AIS) 1'2.6 (A 14) P2.5 (A13) P2.4 (AI2) P2.3 (All) P2.2 (A IO) P2.1 (A9) 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 +
Cl
C3
16
2
!
+
6
DS89C4x0
:I
0
ll
Tl,,
TIOl/f
12
RIOl/f
RI.,
10
T2,.
9
R2ou,
1'2w,
..
R2,,
TxDO (P3.J) II RxDO (1'3.0)
14
13
i
MAX232 11
14 13
TxD1 {PI.J) 4 RxOI (Pt.2)
7
8 1Tlside·L-•1s5,-RRS232 side Flgu,e 10-U. (a) ln51 •
'd MAX23z and Cb) its Connection to the 0S89C4xo
Table 10-6: SFR Byte Addresses for DS89C4xO Serial P orts
SFR
SCON (byte address) SBUP (byte address)
First Serial Port
SCONo,.981-! SBUFQ,,991-!
Second Serial Port
ni (byte address)
n.1 "881-!
SCONt =COH SBUFl =C!H
TCON (byte address)
Tl-it" 801-f
Tl.1 "881-J
PCON (byte address)
TCONo " 881-J l'CON,.871-!
11i1 "8D1i
TL (byte address)
-
TCONo"' 881i !'CON "87H
-
Table 10-7: SFR Addresses for the DS89c4x0 (4201 430' etc.) Address
Symbol
Name
ACC•
Accumulator
a•
B register
PSW•
Program status word
SP
Stack pointer
DPTR
Data pointer 2 bytes
DPL
Low byte
82H
DPH
High byte
83H
PO'
Porto
80H
PJ•
Port 1
90H
P2'
Port 2
OAOH
P3'
Port3
BOH
IP'
Interrupt priority control
BSH
IE'
Interrupt enable control
A8H
TMOD
TID\er I counter mode control
89H
TCON'
TID\er / counter control
88H
TICON'
Timer/counter 2 control
C8H
T2MOD
TID\er/counter mode control
C9H
THO
T=er/ cow,ter O high byte
SCH
TU!
Tuner/ counter O low byte
BAH
THl
TID\erI counter I high byte
80H
TLl
TimerI counter 1 low byte
BBH
TH2
TID\er/ counter 2 high byte
CDH
TL2
Tuner/counter 2 low byte
CCH
RCAP2H
T/C 2 capture register high byte
CBH
RCAP2L
T/C 2 capture register low byte
CAH
SCONO'
Serial control {first serial port)
98H
SB UFO
Serial data buffer {first serial port)
99H
PCON
Power control
SCONl'
Serial control (second serial port)
COH
SBUFl
Serial data buffer (second serial port)
ClH
EOH
,
FOH DOH 81H
87H
• Bit,addres,abl•
Programming the second serial port using timer 1 ltlcj While each serial port has its owi:i SCON and SBUF registers, both ports can use Timer 1 for setting the baud rate. upon reset, the DS89C4x0 chip uses Tm~er l for setting the baud rate of both serial ports. Since the old e r 8051 1 ~rsdo not support this new second serial port, we need to define them as s hown in Example 10-11. Notice ~. tn both C and Assembly, SBUF and SCON refer to the SFR registers of the first serial port. To avoid confusion, in
~
.......___~--~~~~~~~~~~~~~~~~~~~~~~~~~~ 8 '1s] ERIAL PORT PROGRAMMING IN ASSEMBLY AND C
257
'
ONl and SBUFl for the second serial SC d the first an 5e · I #1 · d P<>tts DS89Clx0 programs we use SCONO and SBUF0 Ior • 1 portS as "" ,.-rial #0 and na in o r er to comply . · Foi With h this reason, the MDE8051 Trainer designates t e sena
~
designation. See Examples 10-12 through 10-14.
I SMO I SMI I SM2 I
/
•
Serial IHl
•
Note:
Make SM2, TBS, and RBS= O.
TBS RBS
Tl
I
RJ
Serial port mode specifier Serial port mode specifier Multiprocessor com. Enable/ disable reception Not widely used Not widely used Transmit interrupt flag Receive interrupt flag
SCONl .7 " C7H SCON 1.6 =C6H SC0Nl.5 = CSH SCONl.4 =C4H SCONl.3 = O H SCONJ.2 = C2H SCONl. l =C!H SCONl.O =COH
lU
REN
TB8
Serial #1
SCON0.7 = 9FH SCON0.6 =9EH SCONO.S = 90 H SCON0.4 = 9CH SCON0.3 • 9BH SCON0.2 = 9AH SCONO.l • 99H SCONO.O = 98H
SMO SMl SM2
I
Tl
Bit Addresses
Bits
(i
REN
RB8
Figt,r,, 10-12. SCONO and SCO Nl 811 • Addres.,es (Tl and RI bits must be noted)
E=ple 10.11 Write a program i
th or and • second port of the baud. usc 8.b'it data 1 stop serial bit. Use Timer 1. D589C4x0 to continuously transfer the letter "A" . II Solution: sena Y at 4800 SBUFl SCONl Til Ril
EQU EQU BIT BIT
ORG
OH
MOV MOV MOV SETS MOV
TM00,#20H Tlil,#-6 SCONl,~SOH Tl!l
MAIN:
AGAIN:
'
OClH OCOH OC!H OCOH
A.,#'A'
ACALL SEN0COM2 SJMP AGAIN
;second ; second ,second ;second
serial SBUP serial addr serial SCON_addr ser· 1 TI bit addr ia RI bit ;Startin . addr g POSltion
.
;COM2 uses Ti ;4800 baud mer l upon reset ; COM2 h . rate as lts ;start T'1mer own SC0N1 ,send oha r 'A'1
,--------- ------
S£N0COM2: HERE::
2.58
MOV JNB CL!! RET END
SBI.IFl, A
Til,HERE Til
:COM2 has 1 ,._ ta own ,..,9 ite S8lJF
1 COM2
0 wn
TI flag
I
'
01 plel0-12
b'
£.-(11
t
\~rite a proS"am to send the text string "Hello" to Serial #1. Set the baud ra ea
t 9600 8-bit data, and 1 stop
'
11•
Solution:
f'N:
Sl:
SCONl SBUFl Til ORG MOV MOV MOV SETB MOV CLR MOVC JZ ACALL INC SJMP SJMP
EQU OCOH EQU OClH BIT OClH OH TMOD,#20H THl. , #- 3 SCONl ,#SOH TRl DPTR, #MESS1 A A, @A+DPTR Sl SENDCOM2 DPTR
MOV JNB CLR RET DB END
SBUFl,A Til,HEREl Til
,starting position ;9600 baud rate ;display "He l lo• ;read value ;check for end of line ;send co serial port ;move to next value
FN
Sl
SENDCOM2 : KEREl : MESS1 :
;pl ace value in buffer ;wait until transmitted ;clear
,,
nHello",0
Example 10-13 Program the second serial port of the DS89C4x0 to receive bytes of data serially and put them on Pl. Set the baud rate at 4800. 8-bit data, and 1 stop bit. Solution:
SBOFl SC0Nl Ril ORG MOV MOV MOV SETB HEQE:
JNB
MOV MOV CLR SJMP EN'D
EQU OClH EQU OCOH BIT OCOH OH TMOD,#20H THl,#-6 SCONl,#SOH TRl
Rll,HERE A,SBUFl Pl,A Rll
;second serial SBUF addr ;second serial SCON addr
;second serial RI bit addr ;starting position ;COM2 uses Timer 1 upon reset ;4800 baud rate ;COM2 has its own SC0Nl ;start Timer 1 ;wait for data to come in ;eave data ;display on Pl
HERE
'
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'.
to the . 1# J port (a) If SW = 0 send the message "Hello" "Goodbye" to Sena the Sena (b) If SW= Jsend the message
(
Solution:
l
,., ' '
51:
,,
FN:
I
SCONl Til SWl ORG MOV MOV MOV MOV SETB SETB JB MOV CLR MOVC
JZ ACALL
NEXT: LN:
INC SJMP MOV CLR MOVC
EQU OCOH BIT OClH BIT P2.0 OH TMOD,#20H TH.l,#-3 SCON,#SOH SCONl,#SOH TRl SWl SWl,NBXT Dl?TR, #MESS1
. ·start1n9 po sit ion
'
·9600 baud rate
'
·make SWl an input '.check SWl statue '.if SWl=O display "Hello" •
A
A,ltA+DPTR
;read value
Sl SENDCOMl
;check for end of line ;send to serial port
DPTR FN DPTR, #MESS2
;move to next value
; if SWlal display "Goodbye"
A
A,~A+OPTR Sl
JZ ACALL
SEIIDCOM2
INC
DPTR
SJMp
LN
MOV JNB CLR RET
SBUF,A Tl,HE:RE TI
MOV
SBUFl,A
JNB
Til,HERJ;:l Til
;read value ;check for end of line ;send to serial port
;move to next value
Sl!NDC0M1:
HERe:
SENDCOM2,
HEREl:
CLR RET
MESS1, M.ESS2:
DB DB
;place value in buffer ;wait until transmitted ; clear
;place value in buffer ;wait until transmitted ;clear
•Hello•,o "Goodbye"' , O
J;:111)
Review Questions (AU questions refer to the DS89C4x0dtip)
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 #! ? I.
260
l'liE 80s1 ~ CRoco l'f l'ROLLER ANO EMBEDDED 5YSTV'5
3. 4·
5•
6.
~Vith XTAL= 11.0592 MHz, what value s hould be loaded into THl to have a 28,800 baud rate? Give the answer in t,oth decimal and hex. To transfer a byte of data via the second serial port, it must be placed in register - S(ON1 refers to and it is a(n) -bit register. . . \,vJuch register is used to set the data size and other framing information sud, as the stop bit for the second serial
port?
SECTION 10.5: SERIAL PORT PROGRAMMING INC This section shows C programming of the serial ports for the 8051/52 and DS89C4x0 chjps.
Transmitting and receiving data in 8051 C As ,ve stated in the las t chapter, the SFR regis ters of the 8051 are accessible directly in 8051 C compilers by usinS: the regSl.h file. Examples 10-15 through 10-19 show how to program the serial port in 8051 C. Connect your 8051 Tramer to the PC's COM port and use HyperTerminal to test the operation of these examples.
Example 10-15 \,I/rite a C program for the 8051 to transfer the letter" A" serially at 4800 baud continuously. Use 8-bit data and 1 stop bit. Solution:
I
#include void main (void) { TMOD=Ox20; THl=OxFA· ' SCON=OxSO; TRl=l; while (l) {
//use Timer 1,8-BIT auto-reload //4800 baud rate
SBUF= 'A';
//place value in buffer
while(Tl==O); Tl=O; } }
Example 10-16
w·nte an 8051 C p rogram to transfer the message "YES"
continuously.
· senally at 9600 baud, 8-bit data, 1 s top bit. Do trus
Solution:
#include vo·d v ~ SerTx (unsigned char); 01 d main(void) {
TMoo.ox20;
//uae Timer 1,8-BIT ... •ut o-re 1oa.d
261
' THlsOxf'D; SCON•OxSO; TRl=l;
//9600 bau d rate //stut ti·mer
whlle (l) { SerTx{'Y') 1 SerTx('E' ) ; serTx( 'S') •
,,. I
V
l
l
void Ser'l'x(unsigned char x ) { in buffer SBUFsx; //place val~etransmitted //wait untl while{TI••O); TI•O;
l
Example 10-17 . Pl Set the baud rate at 4800, 8-bit data, Program the 8051 in C to receive bytes of data ser,a . lly and put them m · and l stop bit.
.
~
I
Solution:
r
#include void main (void) { unsigned chaI mybyte; TMOD•Ox20; THl•OXFA; SCON=OxSO; TEU•l;
wbile(l) {
while (Rl==O); mybyte•SBOF; P1=mybyte; Rl•O;
)
//use Timer 1,8-BIT auto-reload //4800 baud rate //start timer //repeat forever //wait to receive //save value //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: &eriaJ port. SW 2 O: send your first name SW • I: send your last ll8JJ1e
.
·
Aa.iuning that SW is COl'li't«ad • flt,- .
Assume XTAL ~ 11.ll592 MHz, baud tlleof~,8-bit data, I stop bit
'. 262
.
.
NTROtLER. AND EMBEDDED sY5'fPd
solution: ude "' . t MYSW=P2 0; sb1 . voi'd main (void) { unsigned char Z; unsigned char fname [] ="ALI"; unsigned char lname[]="SMITH"; TMOD=Ox20; THl=OxFD; SCON=OxSO; TRl=l; if(MYSW==O) { for(z=O;z<3;z++) { SBUF=fname[z]; while (Tl==O); TI=O; } } #l!lC l
//input switch
I
. 1,8-BIT auto-reload //use Timer //9600 baud rate //start timer //check switch //write name //place value in buffer //wait for transmit
else {
\
for ( Z=O; Z
SBUF=lname[z]; while(TI==O); TI=O;
//write name //place value in buffer //wait for transmit
} } }
Example 10-19 \\.'rite an 8051 C program to send the two messages "Normal Speed" and "High Speed" to the serial port. Assuming that SW is connected to pin P2.0, monitor its status and set the baud rate as follows: S\V:: 0 28,800 baud rate S\V:: 1 56K baud rate Assume that XTAL = 11.0592 MHz for both cases.
Solution: ~lnclude sb1t . MYSW=P2"0 ,· //input switch \told main (void) { unsigned char z·, unsigned char Messl[] .. "Normal Speed"; Unsigned char Mess2[]="High Speed";
•
•
'
263
'
.aIT auto-reload 8 l · rner ' //use Tl for normal speed
TMOD•Ox20; THl•OXFF; SCON•OXSO; TRl•l1
//28,800
//start tl·mer
if (MYSW-0)
{ for{z•O;z
{ SBUP•Messl(z);
while(TI••O);
·n buffer lace value l . I IP fr cransmit I /wait o
Tl•O;
'
.
I
J
else
{
PCON=PCON Ox80;
. I I for high spee d
for(z=O;Z
//place value in ~uffer //wait for transmit
I
of 56K
} } }
8051 C compilers and the second serial port Since many C compilers do not support the second serial port o( the DS89C4x0 chip, we have to decia1e ~ byte addresses of the new SFR registers using the sfr keyword. Table 10-6 and Figure 10-12 provide the SFR bytt and bit addresses for the DS89C4x0 chip. Examples 10-20 and 10-21 show C versions of Examples 10-1 J and 10-13 in Section 10.4. Notice in _both Examples 10-20 and 10-21 that we are using Timer 1 to set the baud rate for the second serial port Upon reset, Tamer l ,s the default for the second serial port of the DS89C4x0 chip.
Example 10.20
Write a C program for the DS89C4x0 to transfer letter" A" · u serial port with 8-bit data and I stop biL We can only use T' sena Y at 4800 baud continuously. Use the second 1 mer I to set the ba ud rate. Solution: Hinclude
SC0Nl•0XS0; TRl•l;
//use Timer l f 2 //4800 ba ud rat~r nd serial P<>rt //uee 2nd •er1a1 //start ti··-r P<>rt SCON1
"•
264
register
Ii
wh.i le (1) { SBOFl•'A':
while(Tll••O); Tll•O;
//uae 2nd aerial port SBUFl register //wait for transmit
} DS89C4x0 TxDO (1'3.1) RxDO (P3.0)
11
It
14
10
12
13 7
TxD1 {Pl.3) RxDI (Pl.2)
4
10
3
9
8
2 3 2 3
-Ds i [1. ·ccX" - -.. -Ds .. _[1.
D
I
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 •fr SBUFl=OxCl; afr SCONl=OXCO; 1bit R!l=OxCO; void main(void)
I unsigned char mybyte; TMOO•Ox20; Tl!leOxFO; SCONleOxSO; TRl=l; while(l) { while(Ril=•O);
mybyteeSBUFl; l'2=mybyte; Ril=O;
//use Timer 1, 8-BIT auto-reload //9600 //use SCONl of 2nd serial port
//monitor Ril of 2nd serial port //use SBUFl of 2nd serial port //place value on port
}
111.-., Questions ~~are the SFR registers accessed in C? l I"- or false. C compilers support the second serial port Of th lepiters SBUF and SCON are declared inc using the e
.,. . . IIJuAL PORT PllOCRAMMJNC IN ASSEMBLy AND C
DS8 9C420 chip. keyword.
'
hOW to use
Timer 2 to set
~~ Serial #0. see www.MlcroDigltalEd.comte the baud ra
( .._/ 7
l•
~'
/\ I
'
• 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 · J commuruca • ti on has !hi This h t began with an introducbon . which da~? s~nt one bit a time, is ~sed can cause ~istor:;:~cation uses hvo methods: synchronOUs here data is sent a byte or more a bme,_gr_e 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( send and receive, but not at the 5amt a chr commurocabon, . ) h l( duplex c-, . . and asynchronous. ln syn ~nous d but cannot receive , ~ dard for serial commurucation connectois. Data communication can be simplex (c3!1 the same time). RS232 IS a st~l 'th an RS232 connector and change thp time), or full duplex (can sen? and :hawed how to interface the 8 :, ( w~res the 8051, and programmed the
wh:;i:~·n~
:n
sei;
r:e;e
;;.a::~~~~:ew~
bau~:t:o:r1;~~:S;. d~cribed th.:it~ 8051 for serial data communication. We also show Assembly and C.
;i;:::::;
o(
s:ond serial port of the DS89C4x0 chip
m
PROBLEMS SECTION 10.1: BASICS OF SERIAL COMMUNICATION
co;
1. What is the advantage of serial communicatio:'5 ov:iparflel :mmc:~~ons? 2. Distinguish between half duplex and full dup ex m ) e o ~ b't · 3. Show the framing of the letter ASCil "2" (0101 1010 , no pan , s O(p 'k. ) 4. U there is no data transfer and the line is high, it is called mar , space . 5. True or false. The stop bit can be 1, 2, or none at aU. 6. Distinguish between synchronous and asynchronous data transfer. 7. Which are the voltage levels used in RS232C? 8. What is the function of the MAX 232 chip? 9. True or false. DB-25 and DB-9 are pin compatible for the first 9 pins. 10. How many pins of the RS232 are used by the IBM serial cable, and why? 11. Which are the minimum signals required in serial data transmission? 12. are State the absolute those signals? minlmum number of signals needed to transfer data behveen hvo PCs connected serially. What 13. U two PCs are connected through the RS232 without the modem they both nfi ed (OTI. OCEJ -to(DTE, DCE) connection. ' are co gur as a _ ___ 14. State the nine most important signals of the RS232. 15. Calculate the total number of bits transferred if 200 pages of ASCn . transfer. Assume a data size of 8 bits, 1 stop bit, and no pa ·ty Ass data are sent using asynchronous senal data 16. Jn Problem 15, how long will the data transfer lake if the bn d. ume each page has 80x25 of text characters. au rate 1s 9,600? SECTION 10.2; 8051 CONNECTION TO RS232
17. Wha t is the function of the chip MAX232? 18. Which pins of the 805 I are connected to MAJ<232? 19. The MAX233 DIP package has pins. 20. For the MAX233, indicate the Vcc and GNO Pins. 21. What is the advantage of using the MAX233 from M . , 22. State the advantages and disadvantages of the MAX:m. 23. MAX232/233 has line driver(s) for the Rxo "'~-• nd
MAX233.
Tlie 80s1 Micb
~0coNTao
.....-.d LLQ AND EMBEDDED sn•-
•
'
MA)(232/233 has line driver(s} for the TxD wire. t . the second set of line drivers ?4. Show the connection of pins TxO and RxD of the 8051 to a DB-9 RS232 connec or Vta
15 of MA)(232. 26. Show the connection of the TxD and RxD pins of the 805! to a D B-9 RS232 connector via the second set of line drivers of MAX233.
t
v · a MAX232
'tl Show the connection of ~he TxO and RxD pins of the 8051 to a OB-25 RS232 COM~ or '. MAX
zi. Show the connection of the TxD and RxD pins of the 8051 to a DB-25 RS232 conn
or Vta
· 233·
SECTION 10.3: 8051 SERIAL PORT PROGRAMMING IN ASSEM13LY 29. Which of the following baud rates are supported by the BIOS of 486/Pentium PCs? (a) 4,800 (b} 3,600 (c} 9,600 (d) 1,800 (e) 1,200 (f) 19,200 30_ \'{hat is the role p layed by Timer 1 in serial communication? 31. Which mode of the timer is used for baud rate programming? 32. l'fhat is the role of the SBUF register in serial data transfer? 33. l'fhat is the function of the SBUF register ? 34. \'fhat is the role of the SCON register in serial data transfer? 35. Which a.re the important functions specified in the SCON register? . 36. For XTAL= 11.0592 MHz, find the THI vaJue (in both decimal and hex} for each of the following baud rates. (a) 9,600 (b) 4,800 (c) 1,200 (d} 300 (e) 150 J7. \'fhat is the baud rate if we use ·MOV THl, #-1" to program the baud rate? 38. Write an 8051 program to transfer serially the letter "2" continuously at a 1,200 baud rate. 39. Write an 8051 program to transfer serially the message "The earth is but one country and mankind its citizens" continuously at a 57,600 baud rate. 40. Under what conditions are the Tl and RI bits raised? 41. Write a program to transfer the numbers 1 to 9 serially. 42. To which register do RJ and TI belong? ls that register bit-addressable? 43. What is indicated by the REN bit of the SCON register? ~- In a given situation we cannot accept reception of any serial data. How do you block such a reception with a single instruction? "5. To whic.h register does the SMOD bit belong? State its role in the rate of data transfer. "6. Is the SMOD bit high or low when the 8051 is powered up? In the following questions the baud rates are not compatible with the COM ports of the PC (x86 IBM/compatible).
47. Find the baud rate for the following if XTAL= 16 MHz and SMOD,. O. (a) MOV THl,#-10 (c) MOV THl, #-200
(b) MOV THl,#•25 (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 (c) MOV THl, #-200
(b) MOV THl, #-25 (d) MOV THl, # -180
SO. How can the baud rate of data transfer be doubled?
5EcnON 10.4: PROGRAMMING THE SECOND SERIAL PORT
~ N~e o~e version of 8051 whkh comes with a second serial port. Sl Which timer of the DS89C4x0 IS used to set the baud rate for the seco d 'al ? Wluch mode of the timer is used for baud rate programming of the n ~rt 55 What are the addresses of the SCON and SBUF of the second seri secon f sena port? · SBUFJ. is a(n) _ -bit register. a I port O 0589C4x0? : , ~ t is the role of the SCONl register in serial data transfer? ,.· F,or using the second serial port, how are the SFRs designated' · or XTAL"' 11.0592 MHz, find the THI value (in both dee· · (a) 9,600 (b} 4,800 (c) 1,200 (d) 300 (e) 150 unal and hex) for each of the following baud rates.
ix:rt
St
--~
SER.IAt PORT PROGRAMMING IN ASSEMBt y ANO C
'
. ly at a 1,200 baud rate. Use the S&-n... 4'2" conb.fluOUS ~~
. Uy the Jetter .,,..,,,.4 o to transfer sena arth is but one country and 59 Write a program (or '-""''~ x sage "The e . . ·aJJ the mes rt ser,al port transfer sen Y d serial po · 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?
( ,/ I
t/
'
. ~' I
rnan~=-. "'"Cl 1b
. PORT PROGRAMMING INC . I at a 1,200 baud rate. SECDON 10.5. SERIAL "Z" continuous Y UI1try and mankind its ' H,~ · Uy the letter th ·s but one co a._. 1 62. Write an 8051 C program to transfer sena the message "The ear 1 63. Write an 8051 C program to transfer senal Y . sly at a 1 200 baud rate. Use the second continuously at a 57,600 baud rate. . IJ the letter "Z" continuou ' . C f DS89C4z0 to transfer sena Y 64. Wnte a program or · ,, th is but one country and manJcind , serial port. riaU the message The ear '~ 65. Write a C program for the DS89C4x0 to transier sethe Jcond serial port. citizens" continuously at a 57,600 baud rate. 0 se
ANSWERS TO REVIEW QUESTIONS SECTION 10.J: BASICS OF SERIAL COMMUNJCATION Faster, more expensive 2. False; it is simplex. 1.
3. True
Asynchronous With 0100 0101 binary the bits are transmitted in the sequence: (a) 0 (start bit) (b) 1 (c) O(d) I (e) 0 (f) 0 (g) O(h) 1 (i) 0 Q) 1 (stop bit) 6. 2 bits (one for the start bit and one for the stop bit). Therefore, for each 8-bit character, a total of 10 bils ~ transferred. 7. 10000 x JO; 100000 bits total bits transmitted. 100000/9600 = 10.4 seconds; 2/10 = 20o/o. 4. 5.
r
8. True 9. +3to+25V 10. True 11. 2 12. COM I and COM 2
SECTION 10.2: 8051 CONNECTION TO RS232 1.
True .
2. Pins lOand 11. Pin IO is forTxDand pin 11 forRxD
3. They are used for converting from RS232 voltage le~els to TTL 4. 2, 2 vo1tage levels and vke versa. 5. It does not need the lour capacitors that MAX232 must have. SECTION 10.3: 8051 SERIAL PORT PROCRAMMfNG lN ASSEMBL y . I. Timer .J 2. 28,800 Hz 3. Mode2 4. -3 or FDH since 28,800 / 3 = 9,6()() 5. SBUF 6, Serial control, 8 7. SCON 8. False 9. During transfer of stop bit 10. PCON; it is low upon RESET.
SE(TION 10.4: PROGRAMMING THE SECOND SERIAL PORT
t
'fllller 1
PinS Pl.2 and Pl.3 :,. -1of FFH 4. S8Uf1 S. Serial Control 1, 8 6. SCONl
SECTION 10.5: SERIAL PORT PROGRAMMING INC 1 By using the reg5l.h file 2. False :,. sfr
...._ llsJ SElJAL PORT PROCIIAMMJNC IN ASSEMBLY ANO c
v
CHAPTERll
INTERRUPTS PROGRAMMING IN ASSEMBLY AND C
OBJECTIVES Upon completion of this chapter, you will be able to:
> > >
>
> >
>
>
> > >
Contrast and compare Interrupts versus polling Explain the purpose of the JSR (interrupt service routine) list the 6 btterrupts of the 8051 Explain the purpose of the interrupt vector table Enable or disable 8051/52 interrupts Program the 8051 /52 tuners using interrupts Describe the external hAr~ware interrupts of the 8051/52 Contrast edge-triggered with level-triggered Interrupts Program the 8051 for interrupt-bued serial CODununicati Define the Interrupt priority of the 8051 on Program 8051/ 52 lntenupts In C
' SECTION 11.1: 8051 INTERRUPTS palling .,.d inrerruP"' .ind then de-,rn~ the ,·anOlls ~ In tt, I f11.,t w, f ~ - "' 1/w d.Ji ~ r t>ff'ri ~ rupt:1 c,r u.., /!051 l
•
,,
f
. to do that ,nh.'rTUf'"' or rolling. In the-.. Thttt •tt rwo w•} > """ mocn.. ontrol~'f c•• ~ .. w-n,I ~1Ct':> ~r. •'-- nucrOC'Ontroller b1 sending U an 1n......_ " "'"" th<- Je- "-'C nowl< u"' d .... .,, rwpl m.,thuJ whmt"\ff anv df'\n nttds It~ «n l'l'<~•"'II an mtt'mlpl .. gnat. tlw mlcron:,nrrol~tlltt (ISR) or mtfl'f'Upt lw11dler. In 11<.'l/lmg, lht ~ rn'KJ'•m ....,wt..'r tlwo ""'' elf'\ 1<1' untl • no1 an effioent U!,e of 111!" m,crocontrulltr 11.. . ., d. - -• • h ··' ... _ .. muon rond1tk)f\.• att ml'!. •1"' ••• -~,.., t\l('{-.Jnu tcnt ea< "'""'"' od,ono..,ge o/ 1nt~rrupl111 th.it the mocroc,,ntr,,lkr c•n Af'f\« rnanv de,ice, (not all at the
I
oAAIA
n.
Jev,n• con get the altt-nlltm of (h(' m1Ctt1C,,nlrolltt i,a,,rJ "" tlw pnontv ..S.SIKJlt'CI to it The polling m11thod c.,nnot a '"P pnantv ••~ ,t ~hl'Ckt •II dl"ICN m • round n,t,i,, fa!ohton Mc:tre 1mp;lrtantly, 111 the interrupt method the 11\Jet0 1gn1>rt' lm.t k) 1 dc-v'.:t' '"l""'' tor,.....,..., Th~ t, •g•m not p(>'a~n lh.11 the ,ntff1'Vrt mtth.lJ,. rttft-r•bl~ iiJ 1/wl 11w polling method wastes much of the m1CTOc1>nu.. ler·, t,me by poll1n11 de\ln th.11 do nnl nt'nl """n <;,, 111 ord..r In ,void tying down the m,crocontroller, mlt'mlf* •rt> us.>d For f'<'1mple. 1n JL..:uwng trmcn m 0..rttt Y.... uwd tlw 10,,truchcm • JNB TP, target", and waited Wtli thv timer rolll>J o,er, .u,d wlul,• "<' ,.,.,.. ,.1,ttng ,..,rou!J n,;,c Jo •n} thing tlse That~~ waste of the microcontroll«'• ume th.it could lw,e br..'11 =-d tu p«rt,...-m .._ u,,rtul la~. In tM cai,e of th<.' timer, ,f we use the interrupt mcthod. the mkrocontrollrr go •buu1 dotng other t.ul , anJ whm the TF O..g ~ ra~ the hme r \viii interrupt the mlCI<> controller in wh.lte, er 11 i:, dn,nit
,•n
Interrupt service routine For eve') 111terrup1 ~ mu,t be an 1n1ttrup1 sen ltt (IS mvokoo, the m1cro<'ontrOller l'UO$ the mtem.pt ~"'''"' routuw IOUf:llnc! R), or interrupt handler When an inrerrupl • th.ti holds the addl'l'SS ol its ISR. The group of or interrupt, there IS a fixed location in mem«y I Interrupt vector I.Ible, shown in Table 11·1 "'ftnOry <>abons 5e1 aside to hold the addresses of !SRs i~ called ttw
f'\.'er,:
J Steps In executing an Interrupt
upon nct1v1t1on of an interrupt, the rrucrocontrou II fin1fflt'S the tnMruction it is executing
er goes through the foUowin
d g steps. an save, I.he address OI 2. It •I~ ~,es the current status of aU the · t the ne~t tnslructton (PC) th k '" erntp~ mi...rnau on e stac 3 11 jum~ to• fixed l11C•tJon "' memon cal~ I.he Y <• e., not on the Slack) nee routme · interrupt veaor bbl e that holds u,, dd . 4 The 11\lc'rorontrolter gru lhe add,... of lhc ISR f c a ~ of the mterrupt ltf lht' interrupt ~"'let' subroutine unw II rear""" :m the interrupt vecio mterrupt) last IIISlructJon of t~ table and /Umps to it It stlrts to ext(Ult s upon e>.l'CUbng the Rm inl.trucnon, I.he subroutine, whJch is RETI (retum frOIII llt'ts the program counter (l'C) •ddn-.s fro ll\lcrocon1ro11er r,riy ot tart. io ~ t e from th.it • dd,-. m the lack b)· 0nn.. l'l\s 10 the pi.c._. wh d • -rytng the tor hv by ere It Was interrupted f'tt,I. O le$ of the Stack into the pC ~ I.
nt1;-.
--1M1c anr.
~ 0
Nl"Rott
Ell ANO EMBEDDED 5yS'J'PIS
J.
111
contents Notice from Step 5 the critical role of the stack. For this reason, we must be carefuJ.tn m ani ulating the ust stack be equal the 15R. SpecificaUy, in the ISR, just as in any CA LL subroutine, the number of pushes an pops m
SIX interrupts in the 8051 [JI reality, only five .tnterrupts are available to the user in the 8051, but many manufacturers' t lJ data sheets state tha t
d,tre are six interrupts since they include reset. The six interrupts in the 8051 are allocated as
O
ows.
I Reset. When the reset pin is activated, the 8051 jumps to address location 0000. This is the power-up reset discussed in Chapter 4.
,.._
· for the timers: · · o and one for Timer 1· Memory locations OOOBH and 2. Two ·interrupts are set aside 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 toas EXl and EX2. Memory locations 0003H and 0013H in the interrupt vector table are assigned to CNTO and INTI, respectively.
'....r.n. .... ........
!nit
-•...... .....
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 location 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 Reset
ROM Location
-External hardware interrupt O(INTO) Tuner Ointerrupt (TFO)
Pin
Flag Clearing
0000
9
Auto
0003
P3.2 (12)
Auto
0008
5x~mal hardware interrupt 1 (INTI) :!:°llller 1 interrupt (TF1) ~rial COM interrupt (Rf and TI)
Auto
0013 0018
P3.3 (13)
Auto Auto
0023
Programmer clears it
0
...----
ORG
o
WMP
MAIN
;wake-up ROM r eset location ; bypass i nterrupt vector table
the wake-up p rogra m ORG 30H
.. .. ·l. RNl.irttling the 8051 from the lnlenupt VtttorT•ble •t p
---
~IUlllPTs PROGRAMMING IN ASSEMBLY ANO C
owel'-up
'
e will be responded to by the rn· eaning that non . . IJ •croeontr Upon reset all interrupts are disabled (masked}, m in order for the microcontro · er to respond olle, • bled by software ( kin ) d d' bl ' to 11... if they are activated. The interrupts must be ena . 'ble for enabling unmas g an ,sa 1ng {ll'lask;n:,"'l There is a register called 1£ (interrupt enable} that 1s respansi b ·t-addressable register. · -
Enabling and disabling an interrupt
r
/ ./
l
Steps in enabling an interrupt 1. 2.
'
;
~
/ \.
'
To enable an interrupt, we take the following steps: Bit 07 of the [E register (EA) must be set to high to allow the rest of register to take effect.
If EA = 1, interrupts are enabled and will be responded to if their corresf'.on~g bits in TE are high. If EA =0 111 mterrupt will be responded to, even if the associated bit in the IE register ,s h1gh. • To understand this important point look at Example 11-1.
i:,
I
00
07
r
I En j
EA
·'
EA
j Er1
I
EXJ
I
ETO
I
EXO
IE.7
Disables all interrupts. If EA - O, no interrupt is acknowledged. If EA~ 1, each tnterl'\lpt source IS individually enabled o r disabled by setttng or clearing its enable bit.
IE.6
Not Implemented, reserved for future use.•
ET2
IE.5
Enables or disables nuner 2 ovecRow or capture interrupt (8052 only).
ES
CE.4
Enables or dlsables the serial port interrupt.
ETI
IE.3
Enables or disables Timer I overflow interrupt.
EXI
IE.2
Enables or disab!es external interrupt I.
ETO
IE.I
Enables or disables Tuner O
't
[
ES
f
0 over ow interrupt EXO .O Enables or disables extemal . . ·u interrupt o . ser software should not Writ . tn future flash microro els to reserve(! bits Th ntroUers to invoke new fe;ture~e bits may be used Figure 11-2. IE Onterrupt En,bl ) R
lE
e
egister
·
,
I/
Eumple 11·1 Show. the instructions to (a)enable the (b
=;=====~------------------_., . .
274
• I
;mask (disable~ Timer o interrupt only
jll)CLR IE .1
;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 (c)CLR IE, 7
.....
Review Questions 1 or the interrupt and polling methods, which one avoids tying down the mkrocontroller? 1. Besides reset, how many interrupts do we have in the 8051? ch e the memory , In the 8051, what n,emory area is assigned to the interrupt vector table? Can the programmer ang space assigned to the table? 4. What are the contents of register rE upon reset, and what do these contents mean? 5. Show the instruction to enable the EXO and Tinler Ointerrupts. 6. Which pin of the 8051 is assigned to the external hardware interrupt INTI? . 7. What address in the interrupt vector table is assigned to the INTI and Timer 1 interrupts?
SECTION 11 .2: PROGRAMMING TIMER INTERRUPTS In Chapter 9 we discussed how to use Tinler Oand Timer 1 with the polling method . In this section we use interrupts to program the 8051 tinlers. Please review Chapter 9 before you study thls section.
Roll-over timer flag and interrupt In Chapter 9 we stated that the timer flag (TF) is raised when the timer rolls over. In that chapter, we also showed how to monitorTF with the instruction "JNB TF, target". In polling TF, we have to wait until the TF is ralsed. The problem with this method is that the microcontrolle.r is tied down while waiting for TF to be raised, and carinot do any thlng else. Using interrupts solves this problem and avoids tying down the contro!Jer. If the timer interrupt in the [E lfgister is enabled, whenever the timer rolls over, TF is raised, and the microcontroller ls interr upted in whatever it is doing. and jumps to the in terrupt vector table to service the !SR. In this way, the microcontroller can do other thlngs until it is notified that the timer has rolled over. See Figure 11-3 and Example 11-2. Notice the following points about the program in Example 11-2. I. ':Ve must avoid using the memory space allocated to the interrupt vector table. Therefore, we p lace all the initialization codes in memory starting a t 30H. The LIMP instruction is the first instruction that the 8051 executes when it is powered up. LIMP redirects the controller away from the interrupt vector table.
l. The ISR for Timer Ois located starting a t memory location OOOBH since it is small enough to fit the address s-n allocated to this interrup t. r ace
TFO
Tuner O Interrupt Vector
'11 - - 11....._ooo_e_H__J L'._J 1umps to ~g,,,. l)
TFJ
Timer I Interrupt Vector
GJ jumps
to
_00_1_BH_ _,
.__l
·3. TF lnt,mapt
.......__
'N°ttRRUPTs PROGRAMMING IN ASSEMBLY ANO C 275
I E•ample 11-l
.
rt 2and a ' , t rort Oand 'N' ot Po
a \/alue of Ya
MHz·
\\lritea program that d1,;p1ays m Pl.Z .XTA L = 22 • with Timer Oin mode 2 at port P
,,/
quencY of 22MHz. 'th a crystal fre 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 ·bypass interrup LJMP MAIN · re wave ·· · ·ISR for Timer Oto generate squa . rrupt vector ' ·Timer o inte ORG OOOBH ' CPL Pl.2 RETI ·· ··the main program for initialization c:he interrupt vectors ' ·a location after ) ORG 0030H ' d 2 (auto· reload ·Timer o. mo e MAIN: MOV TMOD,#02H ;move count value i~co THO MOV TH0,#0B6H 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
.
I
~
'
/\
'
Solution;
Ii
'
?
so g enerates a square wave of 10 ki... . .,.
'
,,
•' •'
!;!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.
foe a·ons allo dIn Example th T 11-2, the interrupt service routine was short enough that it could be I ed · · not always the case. See Exam le I 1-3.p ac 1n memor\/ a cate to_ e .,mer o·mterrup_t. However, that 1s ' Notice that the low portion of the pulse is created by the 14 MC (m ch· p d 0 me eyeIes) where each MC = 1 .085 µs a~ 14 x 1.085 µs = 15.19 µs.
Example 11-3 Rewrite Example 11-2 to create• square wave that has a hi AssumeXTAL=11.0592MHz.UseTimerl. Solution:
. gh portion of 1085 µsand a tow portion of !Sia
Smee 1085 Jts is 1000 x 1.085 we ne.!d to use mode I oft· ;··Upon wake-up go to main, avoid usin tmer].
;--allocated to Interrupt Vector Tabl 9 memo,:y space ORO OOOOH e LJMP MAIN
;bYPass intert-u Pt vector table
276
.
.JSR for Timer l to generate square wave ORG OOlBH ;Timer l interrupt vector table LJMP ISR Tl ; jump to ISR ,-The main program for initialization ORG 0030H ;after vector table MOV TMOD,#lOH ;Timer l, model IN: MOV PO,#OFFH ;make PO an input port MOV TL1,#0l8H ;TLlalS the Low byte of -1000 MOV THl,#OFCH ;THlaFC the High byte of -1000 MOV IE,#88H ;IE=lOOOlOOO enable Timer lint. SETB TRl ;start Timer 1 MOV A,PO JACK: ;get data from PO MOV Pl, A ;issue it to Pl SJMP BACK ; keep doing it ;
·• · ·Timer l ISR. Must be reloaded since not auto-reload ISR_Tl: CLR TRl ;stop Timer 1 CLR P2. l ;P2.1=0, start of l ow portion MOV R2,#4 ; 2 MC HERS: DJNZ R2,HERE ;4x2 machine cycle(MC) 8 MC MOV TLl,#lSH ;load Tl Low byte value 2 MC MOV THl, #OFCH ;load Tl High byte value 2 MC SETB TRl ;starts Timer 1 l MC SETB P2.l ;P2.l=l, back to high l MC RETI ;return to main END
Ex;unple 11-4
Write a program to generate two square waves - one of 5 KHz frequency at pin Pl.3, and another of frequency 25 kHz at pin P2.3. Assume XTAL= 22 MHz. 8051 PJ .3 1 - - --
...
P2.3 1----
..
_J
L
Solution:
,Teated for an AT89C51 with a cryatal frequency of 22 MIiz . ORG
OOOOH
MOf 1 ··ISR for Timer o LJMp
ORO
.....___
OOOB
;avoid using the interrupt vector table
; Interrupt vector for Timer 0
1 ~RUPfS PROGRAMMING IN ASSEMBLY AND C
2'17
I CPL Pl.3 RETI for Timer l ·• - -- ISR for Ti mer 1 t vector -InterruP ORG OOlBH ' CPL P2 . 3 RETI . tion ·• -- -main program for initial1za . . . alized for Mode 2 ORG OOJOH ·both timers are iru~~d Timer l Interrupts MAIN: MOV TMOD,#22H • able the Timer o quare wave MOV IE, #8AH ;en for 5 KHz s 0,#048H ;count value for 25 KHZ square wave HOV TH t value HOV TH1,#0B6H ;coun O .• start Timer SETB TRO 1 · h t . er SETB TRl . start Timer the roll off of ei t er im ;keep waiting for WAIT: SJMP WAIT
~'
/\
'
Example 11-4•
·'
Write a program to toggle pin Pl .2 every second. Solution:
;Tested for an AT89CS1 with a crystal frequency of 22MHz . To get a large delay of I second, we need to use a register, in addition to a timer. Here register RO is used along with Timer I to get the large time delay.
,--- e upon wake up.go to main.avoid using memory space allocated to interrupt vector tabl ORG OOOOH ;bypass interrupt vector table LJMP MAIN ; • --!SR
for Timer l to generate square wave
ORG OOlBH DJ'NZ RO,ST/\RT
CPL
Pl. 2
;toggle pin Pl.2 every HOV R0,#28 ;reload register value second HOV TLl,#OOH ;reload counter value MCV THl,#OOH ;reload counter value START: RJ;;TI ;---the main program for initialization ORG 0030H MAIN: MOV TMOD, lOH ;Timer 1, mode 1 MOV lE, #SSH ;enable Timer lint HOV RO, #28 •·count f or 1 seco d errupt MOV TLl,#OOH ;count value for ~ldelay MCV THl,#OOH ;count value for TH1 SET1! TIU HERE: SJMP HERE In the main program, the n1 and THI are inilutJized monitored in the ISR, because each tune the tim •.but they have to 28 times to get a delay of 1 second. er flag"' S
a««
278
ieW Questions
I, J. 3. 4·
•).
.
. ed t both Timer oand Timer 1. eor false. There is only a single interrupt in the interrupt vector table assign 1 ~;t address in the interrupt vector table is assigned to Timer O? Which bit of IE belongs to the timer interrupt? Show how both are enabl~d. . . bl d Explain how the Assume that Timer 1 is programmed in mode 2, THt = FSH, and the fE b,t for Tuner 1 is ena e · interrupt for the timer works. rrue or false. The last two instructions of the !SR for Timer Oare:
AeV
°
I
CLJ! TFO RETl
SECTION 11 .3: PROGRAMMING EXTERNAL HARDWARE INTERRUPTS The 8051 has hvo external hardware interrupts. Pin 12 (P3.2} and pin 13 (P3.3) of the 8051, design;ted a~ ~O ~.~ !NT1 are used as external hardware interrupts. Upon activation of these pins, the 8051 gets interrupte in w a ever 1 ~
doing and jumps to the vector table to perform the interrupt service routine. In this section we sh.tdy these two extern l,ardware interrupts of the 8051 with some examples.
External interrupts INTO and INT1 There are onJy h'IO extemal hardware interrupts in the 8051: INTO and INTl. They are located on pins P3.2 and P3.3 cl port 3, respectively. The interrupt vector table locations 0003H and 0013H are ~t asjde for INTO and ~ l , respecti,-dy. As mentioned in Section 11.1, they are enabled and disabled using the IE register. How are they activated? There arelwo types of activation for the extemal hardware interrupts: (1) level triggered, and (2) edge triggered. Let's look at each one. First, we see how the level-triggered interrupt works.
Level-triggered interrupt In the level-triggered mode, INTO and INTI pins are normaJJy high (just like all 1/0 port pins) and if a low-level signal is applied to them, it triggers the interrupt. Then the microcontroller stops whatever it is doing and jumps to the intmupt vector table to service that interrupt. This is caUed a level-triggered or level-activated interrupt and is the default mode upon reset of the 8051. The low-level signal at the INT pin must be removed before the execution of the last instruction of the interrupt service routine, RETI; othenvise, another interrupt will be generated. In other words, if ~ low-level interrupt signal is not removed before the !SR is finished it is interpreted as another interrup t and the 8051 JUlllps to the vector table to execute the JSR again. Look at Example 11-5.
Level-triggered
INTO 0 (Pin 3.2) - - - - ITO l 't..._--r=;---i Edge-triggered
1_
JEO
0003
(TCON.1)
- ·- ·-·- - ·-·-·-·-·-·-·- ·- - ·-·-·- ·-·- -·-·-·-·-·- - ·- ·-·-·-·-·-·- ·-·Level-triggered
INTI or-~~i)c>-~~~~~ (Prn 3.3) - - - - 1... ITl
L-_..r::;-, Edge-triggered
lig,.,• ll-4. Activation of INTO and lNT1
...__
L'Otaa_UP'TS PROGRAMMING IN ASSEMBLY ANO C
l_
!El (TCON .3)
0013
•
I
I , Exilfflple 11·5
.
. tch rs pressed,
3 2 and p J.3. Whenasw1
the corresponding line goes I°"'
to P1115
.,/ / V'
' l
connected p · Two ~witches are . ressed, Write a program to O if the first swi~ ~~s pressed· ( ) I h t all LEDs connected to port 2' 'f the second swrt a ig ted to port , 1 (b) light aU LED:. connec Solution:
·Tested for an AT89C5 w1 . ' 3.2 is the pin for Interrupt 0, and Pin 3.3 IS t Pin ·upon wake up.go to rnain ' ORG OOOOH LJMP
!
r
ORG MOV MOV
OJNZ
'
table ;bypass interruPt vector
ISR
0003H PO,#OFFH RO, #255 RO,LEOl
tor interrup t INTO for rnterrup t 0 ;interrupt vec~~rport ;turn on LBDs
o
;keep the LEDs ON for a Short time
RETI
INT l ··-·--·-ISR for ;---------------·Interrupt vector f o r
LE02
''
r,!HZ •
MAIN
···················-the ' LEOl,
frequency of 22 I h• pin for Interrupt .
. th a crysta1
Interrupt
1
ORG MOV
0013H P2,#0FFH
' ;turn on LEDs of port 2
MOV
RO, #255 RO, LED2
;keep the LEDs ON f or a short time
DJNZ RETI
l'
.
'·---------------main p~ogram for initia ization ORG 0030H MAIN, MOV IE, #SSH ;enable INTO and INTl HERE, SJMP
HERE
ENO
The LEDs will remain ON if the corresponding switch is kept pressed.
In this program, the microcontroller is looping continuously in the HERE loop. Whenever the switch on INTI (pill P3.3) is activated, the microcontroller gets out of the loop and jumps to vector location 0013H. The JSR for INTI hJJJlS on the LED, keeps it on for a while, and tun,s it off before it returTIS. lfby the time it executes the RETI instruction. d1t INTI pin is back st;U low, the microcontroJJer the interrupt again. Therefore' to end th.is problem' the CNT1 pin must be broL1ght to high by the time RETIinitiates is executed.
Sampling the low level-triggered interrupt Pins P3.2 and P3.3 a.re used for normal I/0 unless the INTO and INiJ . . tht hardware interrupts in the IE register are enabled, the control[ k bas~ the IE registers are enabled. ~gi>ll once each m~chine cycle. According to ~ne manufacturer's data:~ ~f5 ~phng the INTn pin for a low-l~el SI.;lllll of the execution or JSR. If the INT11 p,n 1s brought back to a lo . ';'!1 the Ptn must be held in a low state until the be no interrupt." However, upon activation of the interrupt d gic high before the start of the execution of JSR there wrll the execution of RETI. Again, according to one manufacturer'u~ to the low level, it must be brought back to high befo«t RETI inst~ction of the ISR, an~ther interrupt will be activat~ ata 5 hee1,_ "lf the lNT pin is left at a logic low after !lit 11 executed ,, Th the activation of the hardware interrupt at the 1NT11 Pin m k after 0 ne Instruction is fore to eJ1SUlf machine cycles, but no more. Th,s is due to the fact th• sure that lhe duration of th J e_re UJ1(l4 1 be held in a low state untU the start of the ISR execution e evel-tr;ggered intern ·pt . e 1lO w. eve srgnathe pin ust
that ° •
·"
1
rs not atched. Thus
~
1 310
111
1 MC l'.'oaSµs~ [~~~~ ~4- ma ~ ch~in-e_cy ~ c-Jes~~~~--'~or~:ins 4X
Note:
l.085µs
I
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).
• DO
07 TRl TFl
TCON.7
TFO
TRO
!El
m
IEO
ITO
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.
ill
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.
TRO
TCON.4
Timer Orun control bit. Set/ cleared by software to tum timer I counter Oon/ off.
fE I
TCON.3
External _interrupt 1 edge flag. Set by CPU when the
II
"
"
external interrupt edge (H-to-L transition) is detected. Cleared ~y CPU when the interrupt is processed. Note: This flag does not latch low-level triggered interrupts.
.. ,, =
!Tl
TCON.2
Interrupt 1 type control bit. Set/cleared by software to specify falling edge/low-level triggered external interrupt.
IEO
TCON.l
~xtemal interrupt Oedge flag. Set by CPU wh interrupt (H·t 1. .. en external h . o- transition) edge is detected. Cleared by CPU ~ c':,"1 ,nte~pt is processed. Nott;This flag does no t at ow- eve! triggered interrupts.
ITO
TCON.O
Interrupt O ~ control b' Set f •l / cleared by software to 8 ·1y alllng edge/low-level triggered e"-maJ I pea
ii!
f'
MC
nterrupt.
'SUrt II~· TCO N (Ttmrr/Counter) Rrgistrr (Bit-addttt9'1blr)
...___
IN'fEJl:R~;;:;-;;~~;;;;;;;:;;;~;;;;~~;;;-;:--~~~~~~~~~~~~~~~~ "' lIPTs PROGRAMMING JN ASSEMBLY AND C
281
I Exampl• 11-6 hich is J,alf the frequency o Generate from all pms ol Port 0, a sq uare \\'ave w No32).
f the signal applied at INTO pin !P'ir,
I
8051
JUl.fL_..., P3.2
.
' I'
r
I
PO
Solution: stal frequency o f 22 MHz . ;Teated for an ATS9CS1 with a ry . 0003) interrupt to be activated. . 3.2 w,11 . cause the INTO (vectored to location Every negative edge at Pm ORG OOOOH c
LJMP
MAIN
;--!SR for hardware interrupt INTO ORG 0003H CPL RETI
'r
PO
ORG
0030H
MAIN,
SETB
TCON . O
·make INTO an edge-triggered interrupt
MOV
HERE,
SJMP SND
IE,#BlH HERE
;enable hardware interrupt INTO
Look at Example J 1-6. Notice that the only difference between this program and the program in Example 11·5 isin the fust line of MAJN where the instruction "SETB TCON. 2" makes INTI an edge-triggered interrupt. When the falling edge of the signal is applied to pin INTI, the LED will be turned on momentarily. The LED's on-state duration depends on the time delay inside the !SR for INTI. To turn on the LED again, another high-to-low pulse n1ust be applied to J)l11 3.3. This is the opposite of Example 11·5. In Example 11·5, due to the level-triggered nature of the interrupt, as long as INTI is kept at a low level, the LED is kept in the on state. But in th.is example, to turn on the LED again, the INTl pulst must be brought back high and then forced low to create a falling edge to activate the interrupt.
Sampling the edge-triggered interrupt Before ending this section, we need to answer the
Minimum pulse duration question of how often the edge-triggered interrupt is to detect edge-triggered sampled. In edge-triggered interrupts, the extemal tnterrupts. XTALc 11.0592 M.fu source must be held high for at least one machine cycle, and then held low for at least one machine cycle to ensure that the transition is seen by the microcontroUer The falling edge is latched by the 8051 and is held b th T
l MC 1.085 µs
I
1.085 JIS
L:~=::::=::!: IMC
T~N
latched laUing edge of pins INTO and INTI, respectively. fc~N register. lne TCON. I and TCON.J bits hold tht as shown m Figure 11-6. They function as interrupt-in-service fl~ d TCON.3 are also called IEO and !El, respecH,·el), rates to theextemaJ world that the interrupt is being se i g8 · When an interru _. • . . . d · nd•· 1 to until this service is finished. This is just likl.' the b rv ~ and no new interru P 11:' service ~ag ,s ra,se , 11' ed Regarding the ITOand !TI bits in the TCON ,_. 1 usy s1gna1 you get if all' pt on th.is INTn p,n ,vl]J be n>spond · -o•s er, the following two . c •ng a telephone number that is in u:,t'. . 1s . that when the JSRs are finished h . points must be ernphas,zed. . I. The first point and TCON.3) are cleared, indicating that the int (t •hs, upon executJo . rupt on that pin. For another interrupt to be re:,rru_pt lS finished and th in~truction REn), thei,e bits (TCON 1 2 back low to be considered an cdge-triooerec{ ;nt 8ni ed, the Pin lllu t e 51 lS ready to respond to ani)t.her inter· 00 " ' errup1 s go bad( 1 hi . 0 1 • a ogic high state and be brou~ 282
nari
Tlit 8051
i11J,-.,, ~nOc oNTRQ
S LlER ANO EMB EDDED SYSTEM
II
E,;olfllple 11-7 . h we cannot use RET ins tead of RETl is the difference between the RET and RETI instructions? Explain w Y 1 : ~ last instruction of an ISR. 5olution: . . into the rogram counter, and maki~g Both perform the same actions of poppmg off the top two bytes of the s:f. ta! of clearing the interrupt-1n1 the 8051 return to where it left off. However, RETI also ~erforms an a w can accept new interrupt on service flag, indicating that the servicing of the interrupt is over and the ~~rvice routine you simply block th;lt pin. lf you use RET instead of RETl as the last instruction°! the mterru~d 'ndicate that the interrupt is still y new interrupt on that pin after the first interrupt, since the pm statu~wo d ~ the execution of RETI. : 1118 serviced. In the cases of TFO, TPl, TCON.1, and TCON.3, they are eare Y
;;;a
a
. . . . uted the [NT11 pin is ignored, no matter , The second point is that while the interrupt service routme •s bemg execfu . ' • f the RETI instruction is to dear ,., · · k h.i h I ~ ·h· ln reality one of the nctions o . . how many times ,t ma es a g -to- ow "ans, on. . Th.is . i that the service routtne tS no 5 the corresponding bit in the TCON register (TCON.1 o r TCON.3). CO~; or~~~ON in the TCON register are 3 longer in progress and has finished b~ing servked. Fo~ this reason,~ h whe~:ver a fatiing edge is detected at the called interrupt-,n-servtce flags. The mterrupl·m-serv,ce flag g~s ~ cl ed b RETI the last instruction of the INT pin, and stays high during the entire e~ecutio~ of the ISR.,!t ,son y ear,, ( ~'C R ~CON . 3" for INTI) before ISR Becau of this there is no need for an mstruct1on such as CLR TCON · 1 or L . . . th lhe.RETI i:the lSR,associated with the hardware interrupt INTO. As we will see in the next section, this •snot e c.1se for the serial interrupt.
More about the TCON register Next we look at the TCON register more closely to understand its role in handling interrupts. Figure 11-6 shows the bits of the TCON register.
I Is
ITOand /Tt
II
TCON.Oand TCON.2 are referred to as ITO and m , respectively. These two bits set the low-level or edge-triggered 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-tngse,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.
II
"
•
•
I
•
I
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 lowlel'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
Ch,~ese are the 04 (TCON.4) and 06 (TCON.6) bits of the TCON register. We were introduced to these bits in ?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.
r
..__
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
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 ,...,__ 1 They are used by timers Oand 1, res~ we could have u '-'"'Per . t " and "CLR Trx ' the syntax "JNB TFx' targe '. · ddressable. and "CLR TCON. s" since TCON JS bit·•
es;
external hardware interrupts t ector table ass,·gned to b oth t · the interrup " i.3 True or false. There is a smgle interrup in INTI, How about the pin numv,;:rs on port ? ITO and m. . igned to INfO and both are enabled. What address in the interrupt vector interrupts? Show h~~ d and is active low. Explain how this inter. Which bit of IE belongs to the extern I h rdware interrupt E)(1 is ena e Assume that the IE bit for the extema a . red
• R eview Q ues tions
v , •' •,
..•\ /
D ( ~
t. 2.
3. 4.
:~~.:i~:::e
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
s.
CLR TCON . l J• tO RETI N 2 la in the execution of extema mterrup . 8. Explain the role that each of the two bits TCON.Oand TCO · P y
S EC TIO N 11.4: PROGRAMMING THE SERIAL CO MMUNIC ATION INTERRUPT
.
· · O( Ih 8051 All examples in that chapter used the polling In Chapter 10 we studied the _serial commsedunic,,bonl e n·catlon which allows the 8051 to do many things, in method. In thls section we explore mterrupt-ba sena comm~ '. , addition to sending and receiving data from the serial communication port. RI a n d Tl flags and interr u pts As you may recall from Chapter 10, Tl (transfer interrupt) is raised when the last bit of the f~med data, _the stop bit, is transferred, indic.1ting that the SBUF register is ready to transfer the next byt('. RI ( received interrupt), IS raised when the entire frame of data, including the stop bit, is received. In other words, when the SBUF register has a byte, RI is rais«l to indicate that the received byte needs to be picked up before it is lost (overrun) by new incoming serial ~ata. As far as serial ~mmuni~a?on is concem~d, aU the above concepts apply equally when using either polling or aa interrupt. The only d,ffer_ence 1s ".' how th~ serial cornmun1cat10~1 needs are served. [n the polling method, we wait for the flag (Tl or RI) _to be raised; w~lle we watt we cannot do anything else. In the interrupt method, we are notified wheii th__:~l hseasrv receed.,ved a byte, or JS ready to send the next byte; we can do other things while the serial communication n~sar:e
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 0 to memory address location 0023H to execute the ISR. In that ISR we m 5 the 8051 gets uiterrupted and 1ump.1 1 51 caused the interrupt and respond accordingly. See Example l l-S. l examine the Tl and RI flags to see w hich one
••SM
Use of s e rial COM In the 8051
In the vast majonty of applications, the serial interrupt · ing data serially. ThJs is like receiving a telephone call where we need a ring to be notified. If we need to mak~ a phone call there are other ways to remind ourselves and so no need /or ringing. In recei\•ing the phone caU however, we must respond immediately no matter wh ' we are doing or we will miss the call. SimJlarly we at the serial interrupt to receive incoming data so ihat i~e 5 not lost. Look at Example 11-9.
15
. Used mamty for rec6ving data a.nd. d f send· ' IS never use or
Serial 111terru t . . F'
p IS IIWoko!d by Tl Or RI 0
•sure ll -7. Singlo lnte
ag,
rrupt for Both TI •nd RI
'
(vfo ,(f
/ pie 11-8
S:,
£P"' . · 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. iolheserial COM port to be transferred serially. Assume that XTAL - 11.0592 I
5olution:
Ii
..
I
•
p
• ••
I,
'
I
•
' '
~}.IN:
ORG LJMP - ORG WMP ORG MOV
0
MAIN 23H
SERIAL 30H
Pl,11-0FFH MOV TMOD, 11-~ THl. #OFDH MOV SCON,#SOH MOV IE, #100100008'1 (t!OV 11 TRI > ,.... SETB ~
BACK:
MOV
A, Pl
...\
MOV MOV
SBUF, A P2,A BACK
\
"'--._SJMP
·-
;jump to serial interrupt ISR ;make Pl an input port ;ti mer 1, mode 2(auto-reload) ;9600 baud rate ;8-bit, 1 stop, REN enabled ;enable serial interrupt ;start time r l ;read data from port 1 ;give a copy to SBUF ;send it to P2 ;stay in loop indefinitely
•··••· ---· --- - - - - - • - -Serial Port ISR ORG lOOH TI, TRANS ;jump if TI is high SERIAL: JB ;otherwise due to receive MOV A,S~UF ;clear RI since CPU does not CLR RI RETI ireturn from ISR TRANS: CLR TI ;clear TI since CPU does not ;return from ISR RETI END
-
In the above program notice the role of TI and RI. The moment a byte is written into SBUF it is framed and transferred t.eriaUy. As a result, when the last bit (stop bit) is transferred the Tl is raised, which causes the serial interrupt to be invoked since the corresponding bit in the IE register is high. In the serial lSR, we check for both Tl and 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 IIAIN:
--
WMP
SERIAL
ORG
OOlOH TNOD,1208
MOV
;jump to ISR for serial traJU1nliasion
;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
sCON,ijSOH IE,lr90H SSTB TRl RO,ijlO MOV MOV Rl,#4SH MOV BACK: A.•Rl SBUF,A HOV DJNZ RO.BACK HERE: SJMP HERE ·------------serial port !SR • TI,RECE SERIAL: JNB A,RO MOV MOV Pl,A CLR TI RETI REC£: MOV A,SBUF CLR RI RETI ( HOV MOV MOV
•, ,I'..
'' I ~
n (
•set baud race REN enabled • bit 1 scop, pt enable • ,·8 re. l·nterru ·serial po '.scart timer 1 m1>er of bytes •. counter for nu ft~".• • cer to ,.,.. • 01n . Rl is the p ~•" to A '.. mov e data fromnsnucte ""':' d is loaded into ;data to ~e t:~l data is sent ;repeat t1ll it
SBUF
implies reception
f RO into A ·if Tl is not high, . h move value o '·if TI is h1g' • . . ;transfer it to Pl ;clear TI for next transmiss1on
to SBOF ·if reception, move received data
next reception •'.clear RI to enable
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 the RETI is the clearing of the RJ or Tl Rags. This is necessary since there is only one interrupt for both receive and transmit, and the 8051 does not know who generated it; therefore, ii is the job of the ISR to clear the Rag. Contrast this with the external and timer interrupts where it is the job of the 8051 to clear the interrupt flags. By contrast, in serial communication the RI (or Tl) must be cleared by the programmer using software instructions such as "CLR TI" and "Ci:.R RI" in the ISR. See Example 11-10. Notice that followed the last two instructions of the JSR are clearing the flag, by Ref!.
Interrupt Flag SFR Register Bit -E-xt_e_m_a.,_I_O_ ___IE _O ....:;.._ __ _ T_C_O _ N_.l=--- - - External 1 TEl TCON.3 -Ti-,m-e_r_O_____T_F_O_____T_C_O_N-.5----:Ti_1111_e_,_1_ _ _ _...;TF_;1_ _ _ __:TC.::.:O:..:.N:.;..7:.__ _ __ Serial port ::---':-----Tl _____.:SC:.=.:O::N:..:.:.:.1:..._ _ __ T1mer 2 TF2 T2CON.7 (AT89C52) :;: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 · . 10 four of the interrupt Rags, in the 8051 the SCON re<>ister hap th agRJs given Table 11-2. While the TCON register holds o· s e and n Rags.
Ex•mple 11·10
be atte ded . used here the serial interrupt timer ointerru t n to sunuJtaneousJy usin . baud rate for serial communk~tions. P • and the external interrupt ~ tnterrup~. Three interrupts ue 1 Write a program to · Timer 1 IS used to generate lht This example is to show that many jobs can
(1) generate a S3.2) is kl"'t the l£Ds c<>nnected lo IL The LEDi
lNTo
.,.. Pre11Cid.
'
-
t
-
-
I
8051 Pl.2
Data
P2
PO P3.2
LEDs I
L - - - -+ oata
5-0Jution:
ORO OOOOH WMP MAIN ....... ---·········· ---- -Timer O !SR • ORO OOOBH ;lSR for Timer 0 CPL Pl.2 ;toggle pin Pl.2 ; Timer is in model so reload count values MOV THO, #OOH 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 ;········ -··-- ----- ---- main program for initialization ORO 0030H MAIN: MOV P2, #OFFH ;make P2 an input port ;Timer o in mode 1, Timer l in mode 2 MOV TMOD,#21H MOV THl,#-6 ;select baud rate ;load count values for Timer O MOV THO, #OOH MOV TLO,#O FOH ;load count values for Timer O ;8 bit, 1 stop,REN enabled MOV SCON,#SOH MOV IE,#93H ;enable Timer O, serial and EXO interrupts ;start Timer l SETB TRl ;start Timer O SETB TRO a.>.cK: MOV A, P2 ;move data in P2 to A MOV SBUF,A ;move A to SBUP for transmission ;continue SJM P Bl\.CK ----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 ;clear RI CLR RI
•
RET!
: "'· · - - .. - .. - - ... - _ - .. - - • - ... - - - - ... - - - • ISR f or INTO
:.t:D:
MOV MOV DJNZ
MOV
PO,#OOH RO,#OFFH RO.HERB PO,IOPFH
;move Oto PO to switch off LBDa ;for de lay ;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 it is enabled. O 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 1 15 3 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 are activated at the same time? Which or 1 The next topic that we must deal with is what happc_ris '. two • 1 • of discussion in this section. these two interrupts is responded to first' lnterropt pnonty 15 the m,1an opic
,I
Interrupt priority upon reset \\'hen the 8051 is pawered up, the pnonlics are assigned according to Table 11·3. From Table 11-3 we see, for exam. pie, that ii external hardware Interrupts Onnd I are activated at the same bme, external interru p t O(INTO) is responded to fusL Only alter INTO has been sen-lCl'
,
•
scheme m the 1able Is nolhmg but an inl~mal polling sequence in which lhe 8051 polls the inte rrupts in the sequence listed in Table 11-3, and responds acrord,ngly.
Setting interrupt priority with the IP register
Table 11-3: 8051/52 lnterrupt Priority Upon Reset
\Ve can alter the 5"
pnonty) Figure 11-8 shows the bill! of the IP register. Upon power-up reset, the IP register contains all Os malting the pnority M"qucnce based on Table 11-3 T' give a higher priority lo any ol the interrupts, we,,;.,~ the rom,spondmg b,t m the IP register high. Look al Example 11 -12. '
Highest to Lowest Priority External Interrupt O
(INTO)
Timer Interrupt O
(TFO)
External Interrupt J
(INl1)
Timer Interrupt J
(fFl)
Senal Commurucation TI mer 2 (8052 only)
(RI+ Tl)
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 c-iemal hardw . at th;, "'1mc 1· Solution: 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
288
THEsos1 ~CR
0CONTRo
-
LlER ANO EMBEDDED 5ySTOIS
DO
D7
PT2
PS
PTl
PX1
PTO
PXO
Priority b it = 1 assigns high priority. Priority b it = O assigns low priority.
IP.7 lP.6 PT2
CP.S
PS PTt PXt PTO PXO
IP.4
IP.3 CP.2 lP.1 CP.O
t
Reserved Reserved Time r 2 interrupt prio rity b it (8052 o nly) Serial port interrupt priority bit Timer l interrupt prio rity b it External interrup t 1 priority bit Timer Ointerrupt priority bit Exte rnal interrupt O priority bit
User software should never write ts to unimplemented bilS, since they may be used in
future products. fig,," 11-8. tnterrupt Priority Register (Bit-addressable)
..
d
., •
tumple 11·12
(•)Program the IP register to assign the highest priority to INTI (external interrupt 1), then (b) discuss what happens if INTO, lNTl, and Tl'O are activated at the same time. Assume that the interrupts arc both edge-triggered. Solution:
--
t
(a)MOV IP, # OO OOOlOOB;IP.2=1 to assign INTl higher priorityTheinstruction ·SETS IP.2" also will do the same thing as the above li.1\e sillce IP is bit-addressable.
lb) The instruction in Step (a) assigned a higher priority to ll\'Tl than the others; therefore, when INTO, INTI, 3.1\d TFOinterrupts are activated at the same time, the 8051 services INTJ first, then it services INTO, then TFO. Th.is is due to the fact that INTI has a higher priority than the other hvo because of the instruction in Step (a). The instruction in Step (a) makes both the INTO and TFO bits in the IP register 0. As a result, the sequence in Table 11-3 is followed, which gives a higher priority to LNTO over TFO .
•
•
•
I
•
•
Ex•mple 11-13
A.sume that after reset. the interrupt pnority is set by the instruction "MOV IP, #000011oos•. Discuss the sequence rn wluch the interrupts are serviced. Solution:
1he i~truction
"MOV IP, #000011008" (Bis for binary) sets the external interrupt J (INT]) and Timer 1 (TFI)
~ • higher priority level compared with the rest of the interrupts. However, since they are polled according to able 11-3, they will have the following priority.
fltghest Priority
External Interrupt 1 Timer lntenupt I External Interrupt 0 Timer lntenupt O SeriAl Comm unication
......._
(lNTJ)
(TFJ) (lNTO)
{TFO) (RI + Tl)
-;:;:;::::-:=::::=:::-::~==:::--::::-:----------'--------
l~"ftlllluPTs PROGRAMMING lN ASSEMBLY AND C
'
I
or more interrupt bits in the JP re . . pt priority when two thers they are serviced according~~ cl rified is the ,nterru riority than o , ,,. Another point that needs to be a . ts have a higher P are set to high. In this case, while these mterrup sequence of Table 11-3. See Example !1-I3. interrupt and another_intedrrupt_is/ctiva tedln? lnslldi 1 lhe8Qs1 . !SR belonging to an . . n interrupt u,s1 e an m errup. What happens 1f the 8051 1s ex~ting an _ riority interrupt. This 15 : t not by another low-priority interru l 10 cases, a ~g~-p~ority interrupt c~ interru::; ~\!gher-priority inte_r~P1•. ~rrupt can get the immediate attention~ a low-pnonty interrupt can be interrupt . lly no low-pnonty 1.11 Although all the interrupts are latched and kept m'.emha .~rity interrupts, the CPU until the 8051 has finished servicing the hig -pn
Interrupt Inside an Interrupt . - .
.
:y
,
I •
., • '
~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 There are times when we need to test an !SR bY wa Y of slOluJahon. . 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 1 is set, an instruction such as "SETB Tf'l " will interrupt to roU over to have an in terrupt. We can cause interrupt vector table. In other words, we do not need to wait or IOler 1 an interrupt with an instruction that raises the interrupt flag.
th: {
Review Questions
·'
•
r
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 . 5. Explain what happens if a higher-priority interrupt is activated while the 8051 is serving a lower-priority interrupt (that is, executing a lower-priority ISR).
SECTION 11 .6: INTERRUPT PROGRAMMING IN C
:...:~:::: ~~ :!
• So~ all the pro~rams in this chapter have been written in Assembly. In this section we show how to program the 1 J.~"i:rage. In reading this section, it is assumed that you already know the material in
~~~~~
8051 C interrupt numbers The 8051 C compilers have extensive support for the 8051 · . . interrupts with two major features as follows· I. They ass,gn a uruque number to each of the 8051 . t . 2. It can also assign a register bank to an ISR Thi tn ~rrupts, as shown in Table 11-4. registers. · s avoids code overhead due to the P h d R7 us es an pops of the ROExample 11-14 shows how a simple interrupt . . . ts wntten m 8051 c.
Table 11-4: 8051152 lnterrupt Numbe . Interrupt rs in C Name External Interrupt o Numbets used by 8051 C (INtO) Tuner Interrupt o 0 CTFO) External Interrupt 1 1 (INTJ) Timer Interrupt J 2 (TFl) Serial Communication 3 (ru + Tl) Timer 2 (8052 only) CTF2) 4
290
s
_,,.. ple11-14
EX&lll ends it to Pt.0, while simultaneous - . ·tea c program that continuously gets a single bit of data from Pl.7 and 5 e wave. Assume that XTAL= :ting a square wave of 200 µs period on pin P2.5. Use timer Oto create the squar !l,o592 MHz.
= ._
pl
I
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
Pl
•
ly
dnclude sbit SW = Pl• 7; sbit IND • p1•0; sbit WAVE = p2•5;
void timerO (void) interrupt 1 { WAVE = -WAVE;
//toggle
pin
l void main()
! I
I I
SW = 1; TMOO = Ox02;
//make switch input
THO • Ox.A4;
IE= Ox82;
//THO• -92 //enable interrupts for timer O
while(l) { IND= SW;
//send switch to LED
l ll)) JI$
Ill
l I 2 = 100 µs
100 JI$ / l.085 µs = 92
In
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
......._
~"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 //toggle pin
!AVE. - WAVE;
l void serialO(J int errupt 4
{
\.
if (TI == 1)
~
{
. I
l
.,
'
RI = 0;
//clear inter rupt
e lse {
~
(
'A, ;
l
/,
'
TI• O;
//send A t o serial port //clear interrupt
SBUF •
•
l
l
[~
void main() { SW= l ; THl = -3;
·'
TMOD = Ox22 I THO = OxA4 ;
I
SCON = OxS O; TRO • l;
''
TRl = l;
IE= Ox92; while (ll
/
l
IND= SW;
J
//make s witch input //9600 baud . //mode 2 for both timers ;;.92 •A4H for timer O //start timer //enable i nterrupt for TO //sta y her e //send s witch to LED
Example 11-16
Write a C program using interrupts to do the following: (a) Receive dat;, serially and send it to PO, (b) Read port Pl, transmi t data serially, and give a cop y to P:2, (c} Make timer Ogenerate• square wave of 5 kHz freque ncy on PO, 1. Assume thatXTAL ; 11.0592 MHz. Set the baud rate at 4800. Solution:
#include J sbit WAVE • PO"l; void t i merO (J interrupt 1
/
J
WAVE • -WAVE;
//toggle Pin .
292
'
'd ser i alO () interrupt 4
·.? l
(
if (TI
S 5
l)
{ Tl = 0 ;
//clear interrupt
) el se (
PO• SBOF; RI = 0;
//put value on pins / /clear interrupt
}
l
void main ()
{ unsig ned char x; Pl = Oxf'F; TMOD = Ox22; THl = OxF6; SCON = OxSO;
//make Pl an input //4800 baud rate
THO = OxA4;
//5 kHz has T = 200 µ s
IB = Ox92:
//enable interrupts //start timer l //start timer 0
TRl = 1 ; TRO •
1;
while (l ) { X = Pl; SBUF = X; P2
e
X;
//read value from pins //put value in buffer //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 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
I PO • enc,
I
void ea1nll
{
cnt. • O: TMOD • OX42;
H7
co zero
-mo• ox .. 46;
//1000°
11. ox96;
0 / /start ti111er ·mer 1 //start ti . terrupted //wait until in
TRO • l; TRl • 1;
while(l);
//enable inte
rrupt•
l
1 •'
••
//set counter
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 chapter showed how to program 8051 / 52 interrupts in both Assembly and C languages.
PROBLEMS SECCTON 11.1:8051 INTERRUPTS 1 2. 3. 4. 5. 6.
7 8 9.
10.
What ,s the advantage of interrupt-bas..'(! dat.1 transfer? Why is reset considered as an mterrupt as well? What is meant by the term !SR? What is meant by the term interrupt vector? What memory address in the interrupt Vector tab!~ is •~s· cd What memory address in the mterrupt vector table is ass~gn to INT()? What memory address in the interrupt vector table is ~gncd to INTI? Wh.lt memory address 1n the interrupt vector table is assigned to Timer O? What memory address in the interrupt vector table is ::sncd to Timer 1? 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~
-
....
fl
,.
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 . d T "mer interrupts? 1 bytes in 1 P. }loW many bytes of address space in the interrupt vector table are assigned to the Timer 16 · To put the entire interrupt service routine in the interrupt vector table, it must be no more an
a;ii:;,
11.
sjze.
8 When an interrupt is activated, what is the first step taken by the 8051? \ With a single instruction, show how to disable all the interrupts. ~ With a single instruction, show how to disable the EXl interrupt. ll. What does the 8051 do on encountering the RETI instruction? . 22. &, the 8051, how many bytes of ROM space are assigned to the reset interrupt, and why·1
SECTION 11.2: PROGRAMMING TIMER INTERRUPTS
23. True or false. For both Timer Oand Timer l, there is an interrupt assigned to it in the interrupt vector table.
,t
What address in the interrupt vector table is assigned to Timer l? 25. Which bits of the IE register are allocated for the timers? 26. What is the effect of clearing the EA bit of the IE register? . v. Assume that Timer Ois programmed in mode 2, THl = FOH, and the IE bit for Timer Ois enabled. Explau, how the interrupt for the timer works. 28. Can the 8051 generate two square waves simultaneous ly? . . . 29. Assume that Timer 1 is programmed for mode 1, THO = FFH, TLl = P8H, and the IE bit for Timer 1 1s enabled . Explain how the interrupt is activated. . . . 30. UTimer tis programmed for interrupts in mode 2, explain when the mterrupt 1s activated. 31. Write a program to create a square wave of T = 160 ms on pin P2.2 while at the same time the 8051 is sending out SSH and AAH to Pl continuously. 32. Write a program in which every 2 seconds, the LED connected to P2.7 is turned on and off four times, while at the same time the 8051 is getting data from Pl and sending it to PO continuously. Make sure the on and off states a.re 50 ms in duration.
SECTION 11.3: PROGRAMMING EXTERNAL HARDWARE INTERRUPTS 33. How many hardware interrupts has the 8051? How are they activated? ll. IVhat address in the interrupt vector table is assigned to INTO and INTI? How about the pin numbers on port 3? .l5. Which bits of the IE register are used to set/reset the external hardware interrupts? 36. Write a program to transfer a data FFH through port 1 when EXO is enabled and to transfer OOH ii EXl is enabled? "!I. Show how to enable both external hardware interrupts. 38. Assume that the IE bit for external hardware interrupt EXO is enabled and is low-level triggered. Explain how this mterrupt works when it is activated. How can we make sure that a single interrupt is not interpreted as multiple interrupts? 39. True or false. Upon reset, the external hardware interrupt is edge-triggered. 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 uare wave 18 u, 3 kHz.
tti
·
~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
I
ition is received on INTO. . h-to-JOW tran5 ,rhen a hig
once, ' W ·tea program to generate a rising edgets? 49. n od disable au interrup . ered? 50 What is the meth to or edge-tngg JNTl? 1 51 · Which interrupts are latched, lo"'.·1eve t for INTO and Which register keeps the latched mterrup
si
.~rrrRRUPT
MMlJNICAnoN u" • ,. THE SERIAL CO G SEcnON 11.4: PROGRAMMIN Ho,v many bytes are assigned to it? 1 th 805J? ·a1 interrupt. 53 How many serial interrupts has e ·. igned to the sen ·t is enabled. 54: What address in the interrupt vector table 15 interrupt? Sho~ how~ interrupt gets activated and also expJ4in 55. Which bit of the JE register belon.gs to the set is enabled. Explall\ how 56. Assume that the rE bit for the senal tnterrup . till enabled. · tion. . 1in . terrupt1ss . its working upon activa · ter the sena. 57. True or False? On making EA= 0 ~f the IE rer;.R f~r the receive interrupt are. 58. True or false. The last two instructtons of the
Z
'
1 •
CLR TI
,I,
'
. tnterrup. · t. . d' w ha t happens subsequently? 59. RBTI Answer Question 58 for the receive . bled when TI •is raise 60. Assuming that the interrupt bit in th~ IE reg15ter is .en~ ' . . . . 61. u RI is kept enabled, can data be received on Rx~ lin:;,d send it to P2 while at the same time Tuner O1s generating 62. Write a program using interrupts to get data senaJJy
square wave of using 5 kHz.interrupts to get data sen.Uy . 63. aWrite a program and send 1' t to P2 ,vhile Timer O is turning the LED connected to PJ.6 on and off every second. SECTION 11.5: INTERRlJPT PRlORllY IN THE 8051/52 64. Which is the highest priority interrupt of 8051_7 . . .. 65. Whlch register caters to the function of chan~g ~terrupt pnonties.1 . . . . . 66. Which bit of IP belongs to the EX2 interrupt pnonty? Show how to assign ~t th.e h1gh~t prion~.. 67. Whlch bit of IP belongs to the Timer 1 interrupt priority? Show how to assign ,t the highest pr1onty. 68. True or False? Interrupts can be enabled by software. 69. Assume that the IP register has all Os. Explain what happens if both INTO and lNT1 are activated at the same time.
70. 71. 72. 73.
Assume that the IP register has all Os. Explain what happens if both TFO and TFl are activated at the same lime. If both TFO and TFI in the IP are set to high, what happens if both are activated at the same time? U both INTO and INTI in the lP are set to high, what happens if both are activated at the same time? Explain what happens if a low-priority interrupt is activated while the 8051 is serving a higher-priority interrupl
ANSWERS TO REVIEW QUESTIONS SECTION II.I: 805\ INTERRlJPTS I. Interrupts 2. 5 3. . 4. Address locations 0000 to 25H. No. They are set when th ~ processor IS designed. 5. All Os means that aU interrupts a.re masked and as a IE'. #1_00~0011e • ' resu t no interrupts will be responded to by the 8051. 6. Mov P3.3, which 1s pm 13 on the 40-pm DlP package 7. 0013H for lNTJ. and 0018H for Timer 1 SECTION 11.2: PROCRAM,\,flNG TIMER INTERRUJ>:rs
r·
I. False. There is an interrupt for each of the time 2. OOOBH · rs, uner and IO\er 1. 3. Bits DI and 03 and ·Mov IE, #10001010 • will 8 4. After Tlll1er I is started with instruction "SETe enable both of the ti
o
r·
. the 8051 is executing other tasks. Upon rolling TRl·, the timer Will mer llltetrupts. over from f.,,_, coUnt up fr L"• 0 m FSH to FFH on its own wrw< . · .,., to 00, the 1'F1 0 296 ag IS raised, Which will interrupt tl,t, THE 8051 MIC,tnr. ~--0 NT1tOLL
ER AND EMBEDDED 5ySTEMS
l )
t
.l
. whatever it is doing and force it to jump to memory location 001 BH to execute the JSR belonging to this
so,1 il1
illierru,l;'.~re is no need for "CLR TFo• since the RETI instruction does that for us. .) f~·
;fCf!ON 11.3: P_ROG~G EXTERNAL HARDWARE INTERRUPTS alst· There IS an interrupt for each of the external hardware interrupts of INTO and INTl. ~rl and 0013H. The piras numbered 12 (P3.2) and 13 (P3.3) on the DIP package. .
i
• 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
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. {NTJ is no wider than
SECTION 11.4: PROGRAMMING THE SERJAL COMMUNICATION INTERRUPT 1. True. There is only one interrupt for both the transfer and recejve. t 23H l Bit 04 (IE.4) and "MOV IE, ff 10010000B" will enable the sedal interrupt. l TheRI (received interrupt) flag is raised when the entire frame of data, including the stop bit, is received. As a result the received byte is delivered to the SBUF register and the 8051 jumps to memory location 0023H to execute the JSR belonging to this interrupt. In the serial COM interrupt service routine, we o,ust save the SBUF contents before it is la;t by the incoming data. i false l Tiw. We must do it since the RETI instruction will not do it for the serial interrupt. I. CLR TI P.ET!
5£.CnON 11.5: INTERRUPT PRIORITY lN THE 8051/52 L l l l
False. They are assigned priority according to Table 11-3. IP(interrupt priority) register. Yes, it is bit-addressable. 811 D4 (lP.4} and the instruction ·MOV IP, nooo1ooooa" ,.,ill do it. Uboth are a_ctivated at the same time, INTO. is serviced first since it has a higher priority. After INTO Js serviced, LWt 1Sserv1ced, assuming that the external tnterrupts are edge-triggered and H·to-L transitioras are latched. In the ~ of low-level trigg~r~ interrupts, _if both are activated at the same time, the INTO is serviced first; then after the ~I has firushed serv,c,ng the INTO, 11 scans the INTO and !NTl pins again, and if the INTl pin is still high it w·u 1
""serviced. ' i We have an interrupt inside an interrupt, meaning that the lower-priority interrupt is put on hold and th hi h °'1e1Ssc rv1,,:u. ···" After servicing · · ·h· · ·ty ·m terrupt, the 8051 resumes servicing the lower-prioritye ISR. g er , JS hig her-pnon
I
I
CHAPTER12
LCD AND KEYBOARD INTERFACING I
OBJECT[VES Upon completion of this chapter, you will be able to:
>
>
>
>
> > >
>
List reasons that LCDs are gaining widespread use, replacing LEDs Descnbe the functions of the pins of a typical LCD List instruction conunand codes for programming an LCD Interface an LCD to the 8051 Program an LCD In Assembly and C Explain the basic operation of a keyboard Describe the key p.- and detection mechanisms Interface a 4x4 keypad to the 8051 using C and Assembly
I
in how to interface the 8051 to devices 1 . . ( the 8051. We exp a 805 1 Section 12 2 ke bo d · SUdiThis chapter explores some real-world applicattons O . '-cing with the 1. n · ' Y ar lllterfa,.;. . shOw LCD interr~ ·••• an L.CD and a keyboard- In Secbon 12.1, we h sections• with the 8051 is shown We use C and Assembly for bot
SECTION 12.1: LCD INTERFACING describes how to program and interface an LCD to This section describes the operation modes of LCDs, then llQ 8051 using Assembly and C.
LCD operation
!
1
-' I') ~I
I
D
·
In recent years the LCD is finding widespread use replaang LEDs). This is due to the foUowing reasons:
LEDs (seven-segment LEDs or o ther multi-...
--.,...en,
The declining prices of LCDs. 2. The ability to display numbers, characters, and graphics. This is in contrast to L ED s, which are limited to numbet, and a few characters. 3. Incorporation of a refreshing control.fer into the LCD, thereby relieving the CPU of task of refreshing the LCD. In contrast, the LED must be refreshed by the CPU (or in some other way) to keep d1Splaymg the data. I.
t!'e
4.
Ease of programming for characters and graphics.
(
LCD pin descriptions
·'
Thepositions LCD discussed in th·~~~.tion has 14 pins. • The function of each pin is given in Table 12-1. Figure 12-1 shows the pin for various
• Vceo Vss, and vE, . used f . ' "'is or control.ling LCD contrast.
While Va: and Vss provide +SY and ground, respectively V
Table 12-1: Pin Descr iptions for LCD Pin Symbol UO I
2 3
V"
4
RS
s
R/ W
6
E
7
DBO
8
DBt
9
DB2
10
DB3
11
DB4 DBS
12 13
14
300
v'6 voc
DB6 DB7
I
Description Ground +SV power supply Power supPIY to control contrast
RS - 0 to select command . RS " 1 to select d . register,
I 1/ 0
1/0 1/ 0
1/ 0
1/ 0 1/ 0
1/o 1/0
1/0
Enable
r wnte, R/W _
The 8-bit data bus The 8-bit data bus The 8-bit data b Th us e 8-bit data bus TheS-b·it data bus The 8-bit data bus TheS-b·It data bus The 8-bit d ata bus
- l for read
t
•
14
I2
I
()DOOODDDDDDOOOD
I
0
14
[.__
l
oo
13
gg I 2
14
OMC1610A OMC1606C OMCl6117 OMC16128 OMC16129 OMC1616433 OMC20434
00
00
1
:
OMC161068 OMC16207 OMC16230 OMC20215 OMC322l6
21
OMC20261 OMC24227 OMC24138 DMC321 32 OMC32239 OMC4-0131 OMC4-0218
rc,rt U•I. Pin Positions for Vuious LCDs from Optrex RS, register select There are two very important registers inside the LCD. The RS pin is used for their selection as follows. If RS = 0, 1,tl!lStruction command code register is selected, allowing the user to send a command such as clear display, cursor at 11.lnt, etc. If RS = 1 the data register is selected, allowing the user to send data to be displayed on the LCD.
I
,
••
0
0
()
0 00
PIN, read/write R/Winput allows the user to write information to the LCD "read information from it. R/W = 1 when reading; R/W = 0 when writing.
Tab le 12-2: LCD Command Codes Code (Hex)
Command to LCD Instruction Register
E, enable
1
Clear display screen
The enable pin is used by the LCD to latch information prtlented to its data pins. When data is supplied to data pins, •high·to-low pulse must be applied to this pin in order for the U:O lo latch in the data present at the data pins. This pulse illllllbea minimum of 450 ns wide.
2
Return home
4
Decrement cursor (shift cursor to left)
6
Increment cursor (shift cursor to right)
5
Shift display right
7
Shift display left
8
Display off, cursor off
A
Oispla y off, cursor on
C
Display on, cursor off
00-07 The8-bit data pins, DO- D7, are used to send information to iheLCDor read the contents of the LCO's internal registers. !he To display letters and numbers, we send ASCII codes for in.~~lters A • Z, a • z, and numbers O - 9 to these pins while ""'g RS = l. There are also instruction command codes that can be sent 111 l'OsithelCo to dear the display or force the cursor to the home ~ or blink the cursor. Table 12-2 lists the instruction W dcodes. lCo .e also use RS = O to check the busy flag bit to see if the ~ ready to receive information. The busy flag is D7 and 1~ read when R/W = 1 and RS = 0, as follows: if R/W = ~ ; O. When D7 1 (busy flag 1), the LCD is busy taking 0 ' -~ I operations and will not accept any new infor' N 07 = 0, the LCD is ready to receive new infor'lllin olt: It is recommended to check the busy flag before ganydata to the LCD.
i::
=
=
Display on, cursor blinking
\F
Display on, cursor blinking
10 14
Shift cursor position to left
18
Shift the entire display to the left
lC
Shift the entire display to the right
80
Force cursor to beginning of 1st line
co 38
Shift cursor position to right
Force cursor to beginning of 2nd line 2 lines and 5x7 matrix
Nott; Thi. table ia extr1ctttl horn Tobie 12-4.
• ~~~~;;;-;;;;;;:;;;;.:;;;:;~~~~~~~~~~~~~~~~~ .\Nt) i(EyBOARD JNTl!RPACINC
I
I
·th a time delay Sending commands and data to LCDs WI k ·n RS"' o. For data, mak e RS = 1. The LCD ma e P' · p n send 12 To send any of the commands from Tab!e 12·2 of th~ LCD. This is shown ltl rogram •1. See Figure 12:
to:~~
h.igh•to-low pulse to the E pin to enable the u,temal la for I.CD roMections.
.. ' !
·'I I
r
d ta/command ,calls a time delay before sending next a · s DO· 07 ;Pl.O·Pl.7 are connected to LCD data pln ;P2.0 is connected to RS pin of LCD ;P2.l is connected to R/W pin of LCD :P2.2 is connected to B pin of LCD ORG OH . . 't LCD 2 lines, Sx7. matrix ,1n1 . MOV A,#38H ;call command subroutine ACALL COMNWRT ;give LCD some time ACALL DELAY ;display on, cursor on MOV A,#OEH ;call command subroutine ACA.LL COMNWRT ;give LCD some time ACALL DEW\Y MOV A,#01 ;clear LCD ,call command subroutine ACA.LL COMNWRT ACALL DEW\Y ;give LCD some time MOV A,#06H ;shift cursor right ACALL COMNWRT ;call command subroutine ACA.LL DELAY ;give LCD some time MOV A,#84H :cursor at line l,pos. 4 ACALL COMNWRT ;cal l command subroutine ACALL DELAY ;give LCD some time MOV A,#'N' ;display letter N ACA.LL DATAWRT ;call display subroutine ACALL DELAY ;give LCD some time MOV A,#'0' ;display letter O ACALL DATAWRT ,call display subroutine AGAIN: SJMP AGAIN ;stay here COMNWRT: :send command to LCD MOV Pl, A :copy reg A to portl CLR P2.0 :RS=O for command CLR P2.l ;R/W=O for write SETS P2.2 for high pulse ACALL DELAY ,give LCD some t 'ime CLR P2.2 ; E =O for H-to-L Puse 1 RET DATAWRT: ;write data to LCD MOV Pl,A ;copy reg A SETS P2.0 for da~o porti :RS=l CLR P2.l :R/W=O for write ~ SETS P2.2 :ll•l for h . h ACALL DELAY ;give LCD 19 Pulse CLR P2.2 some ti :ll•O for I! me RET -to-L Pulse DELAY: MOV R3,#SO ,so or bi HERB2: MOV R4,#2SS :R4~2ss 9her for fast HERE: DJNZ R4, HERE CPUs ; Stay Wltil R4 DJNZ R3,l!ERB2 becomes 0 RET BND
'.E~l
Program 1:Z.1: Communi<•ting with LCD
.
uaiog • dtl•y
2
. g code or data to the LCD with checking busy flag sei1d10
fl N ti that we must t,ove code showed how to send commands to the LCD without checking the busy a~. 0 ce . th busy delay between issuing data or commands to the LCD. However, a much better ,,vay 1s to morutor e issuing a command or data to the LCD. Th.is is shown in Program 12-2.
rr,e: rit
~!!
j/lj t"'v
~·---~~~~~~~~~~~~, LCD ~ - - - -:-, ..sv
8051
Pl.O
1-----1
~~
Pl.7
~
DO
Vcc
l
,> lOK VEE _.,~ POT
<
07
RS R/ WE
Vss
I
P2.0t---'I P2.1 1 - - - - - ' P2.2 _ _ _ _ _....
Ii!'" U-2. LCD Connections ;Check busy flag befo re sending data, command t o LCD ;Pl=data pin, P2. OaRS, P2. l=R/W, P2. 2=E pins MOV A,#38H ;init. LCD 2 l i nes, Sx7 ma trix ACALL CbMMAND ; issue command ;LCD on, curso r o n MOV A, #OEH ;issue command ACALL COMMAND MOV A,#O l H ;clear LCD command ;issue command ACALL COMMAND ;shift cursor right MOV A, #06H ;issue command ACALL COMMAND ;cursor: line 1, pos. 6 MOV A,#868 ACALL COMMAND ;command subrout i ne ;display letter N MOV A.# 'N' ACALL DATA DISPLAY ;display letter O MOV A,# 0' ACALL DATA DISPLAY 2EF.S: ;STAY HERE SJMP HERE COMMA!lo: ACALL READY ;is LCD ready? MOV Pl,A ;issue command code CLR P2. 0 ;RS•O for command CLR P2. l ;R/W•O to write to LCD SETB P2. 2 ;E=l for H·to·L pulse ;B•O,latch in CLR P2. 2 1
RET ilJ,?A_DISPLAY:
ACALL READY MOV Pl,A SETS P2. 0 CLR P2. l SETS
P2. 2
ACALL DELAY CLR P2. 2
;is LCD ready? ;issue data ;RSal for data ; R/ W•O to write to LCD ;B•l for H·to-L pulse ;give LCD some time ; B•O, l a tch in
RET
"'Ir.,,. U-1: Communbtlng with LCD ulng 11w buy hg (continiud on nut pagtJ
~~:;;~~:;;;;;;;::;:;;;:;;;;-~~~~~~~~~~~~-=--~~~ ANo l(EYBoARD IN'l'DPACING
\
I R.BADY:
SETB CLR SETB
7 input port ,make Pl. command reg . RSsO access d reg ;R/Wsl read comman
Pl.7
P2.0 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 SETS P2 .2 JS Pl.7,BACK
'.Esl L-to·H pulse ;stay until bUSY fiagsO
RET S.ND
Program 12·2. (tt1ntlnued from prtviow; ptJg<)
-./ ,
'
Notice in the above program that the busy flag is 07 of the command register. To read th~ command register Wt make R/W: J and RS: o, and a L-to-H pulse for the E pin wiU provide u~ the coo:imand register. After reading tht '.'°mmand register, if bit 07 (the busy flag) is high. the LCD is busy and no informa.tion .(command or data} should lJf issued to it. Only when D7 : o can we send data or commands to the LCD. Notice 1n this method that no time dela •.re.used since we are checking the busy flag before issuing commands or data to the LCD. Contrast the Read and 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.
wrf;
., LCD data sheet
•
In the LCD, one <'an put data at any location. The following shows address locations and how they are accessed.
I
RS 0
R/W 0
DB7 1
DB6 A
DBS A
DB4 A
DB3 A
DB2 A
~Bl
DBO A
where AAAAAAA -- 0000000 to 0100111 for line I and AAAAAAA _ 1 - 000000 to 1100111 for line 2. See Table 12-3.
DO· D7
I
~--1----L·-
RJW
;
F., .I
RS - - - l tAS
l -
I ,i
b. ._______ j
,i
J
to= Data output delay tl ; -Sc , 1me . 1 AS tup time prior to I! (go· . tAH = Hold time after Eh U1g high) for both RS as come down I •nd RJW ~ I Note: Read requites an Lor both RS and R/W 40 ns (minimum) . to+! pulse for the . "10 ns (minimum F,gure 12-J. LCD Timing for R••d (L-to-H f • E Plll. ) or E hnt) 304
E-----1
\ tH '
R/W - - l tAS
t•
tJ>wH _ __ _M :IAH -- - - - - -
, i . ., __ _
~
?l
RS--IPWH = Enable pulse width = 450 ns (minimum) tosw = Data setup time = 195 ns (minimum) tH = Data hold time = JO ns (minimum) tAS =Setup time prior to E (going high) for both RS and R / W = 140 ns (minimum) IAH = Hold time after E has come down for both RS and R/ W =10 ns (minimum)
e e
e s
e s
'
......
tosw
rig111f 124. LCD Timing for Write (H-to-L for E line)
Table12-3: LCD Addressing DB7
DB6
DBS
DB4
D B3
DB2
DB1
O BO
tine I (min)
1
0
0
0
0
0
0
0
Urie 1(max)
I
0
1
0
0
1
I
1
line2(min) Lne2 (max)
l
l l
0 l
0 0
0 0
0 1
0
0
1
1
l
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
,,.
,
J
0
0
0
0
0
~ 0
0
0
0
0
l
0
0
0
0
1
Return Home
0
0
0
0
Entry Mode Set
0
0
0
0
0
0
0
l
1/D
s
Display On/ Off Control
0
0
0
0
0
0
l
D
C
B
Cursor or Display Shift
0
0
0
0
0
l
S/C
R/L
Function Set
0
0
0
0
1
DL
N
p
~
,
I
•
.,
Ii
'
,;
ri (
·'I r
0
Set DD RAM Addn>SS
0
0
0
Read Busy 0 Flag & Address
1
Write Data CG 1
0
l
0
1
t/0• t 5:1
SIC= I R/L o t DL • l No I Fol
BP ,- I
Sets cursor move direction and
BP
40µs
Sets interface data length (DL),
40µs
1
data is sent and received after this setting.
Write Data
:
lq, or rose ii 270 kHz:
Displ•y d•ta RAM Chiltacter &enet.ltor RAM CC RAM add,.,.
40
40µs
40µs
Reads Busy flag {BF) indicating mtemal operation is being performed and reads address counter contents.
40µs
Writes data into DO or CG RAM.
40µs
Read Data from DD or CG RAM.
40µs
Read Data
8 .._
40µs
Moves cursor and shifts display with-out changing OD RAM contents.
Sets DD RAM address. DD RAM
AC
---
l.64 ins
40µs
Sets CG RAM address. CG RAM
AOD
l.64 ll\s
Sets On/Off of entire display (D), cursor On/Off (C), and blink of cursor position character (B).
data is sent and received after this setting. l
(~
specifies shift of display. These operations are performed during data write and read.
AGC
Notn: I &ec·u.t~on hmts art' maximum tunts whion rep or (0$( 250 ktu.. 18 2. EM.:ution bmo ch.loge, when frtquency ch4n Ex When 3. Abbrevuilions: 00 RAM CC RAM ACC AOD AC
Description 5 entire display and sets 0 ea~M address Oin address DD · counter Sets DD RAM address Oas dd ss counter. Also returns are d ··a1 display being shifte to ongm pos1·tion· DD RAM contents remain unchanged·
number of display lines (L), and character font (F).
Set CG RAM Address
or DD RAM Read Data CG or DD RAM
Tiin,
0
...
"' "' " = = 0 0 ::1 ~ 0 "'
Instruci;on Oear Display
0=
... = "' 0 0= 0=
Execu«o~
µs •
250 I 270 ~ 37 JJS.
l
(
DO RAM address, corresponds to C'U1$0f .add . Add,.... counter used for i,.,11, OD and CC .;;,: lnc.rm,cn.1
Ae
Sl,lft to 111. l'!ght; 8 bu•, DI. • o 4 bu, lli.nt,N•O; I line SXIOdolS,P:O ,x7doos (nrtm•J operation,
I/O.
•ddr~ O o.n.,,,..,t
s1c.o cu '$0t rnov~ -o $hJ11 to the i.r,
R/ L -
BF.o C•n......,
1
p
•
'"•lruc:tion
~
'~
-
-
-
-
Optrex Is one of the largest ma.n ufacturer of LCOs. You can obtain datasheets from their Web site, www.optrex.com. The LCOs can be purchased from the following Web sites: www.dlglkey.com www.jameco.com
•
www.elexp.com
• Sending information to LCD using MOVC instruction The Program 12·3 shows how to use the MOYC instruction to send data and commands to an LCD. For an 8051 C version of LCD programming see Examples 12-1 and 12·2.
,calls a time delay before sending next data/command Pl .O·Pl.7=00·07, P2.0=RS, P2.1~R/W, P2.2=E pins ORG 0 OPTR,#MYCOM MOV Cl: A CLR MOVC A,l!IA+DPTR ACALL COMNWRT ;call command subroutine ;give LCD some time ACALL DELAY SEND DAT JZ INC OPTR SJMP Cl SBlfD_DAT: MOV DPTR,#MYDATA Dl: CLR A MOVC A,@A+DPTR ACALL DATAWRT ;call command subroutine ACALL DELAY ;give LCD some time DPTR INC AGAIN JZ SJMP Dl AGAIN: SJMP AGAIN ;stay here CXll!NwRT: ;send command to LCD MOV Pl,A ;SEND COMND to Pl CLR P2. 0 ;Rs~o for command CLR P2. l ;R/W=O for write SETB P2.2 :E•l for high pulse ACALL DELAY ;gi ve LCD some time CLR P2.2 ;E•O for H-to-L RET
. ~ 11,.3: ~ding information lo LCD with MOVC in•lnlcllon· ~con1mutd on ntxt pogt)
lflaANo Kl!Y80ARD INTEKJIACING
I
I Oi\TAWRT :
· SEND DATA to Pl '.RSsl for dat:~ ' w o for write ; R/' h igh puls e ·E•l for i ' LCD some t me 1 give H- to · L pulse ;E=O for fast CPUs ; LONG DELAY POR
Pl,A SETB P2.0 CLR P2.1 SETB P2.2 ACALL DELAY CLR P2.2 RET MOV R3,#250 I MOV R4, #2SS DJNZ R4, HERE OOl,IZ R3,HERE2 RET ORG 300H 38H,OEH,01,06 , 84H,0 •·commands and nu ll DB ;data a nd nul l "HELLO", 0 DB MOV
/ DELAY: HERE2: HERE: l
! -, •
MYCOM:
(• I
MYOATA :
~
END
I
r
I
Program 12-3. (cotttimitd from prmious page)
0 (
Example U-1
'
Write an 8051 C program t6 send letters 'M', ' D', and 'E' to the LCD using delays.
,
•
Solution: #include sfr l data = Ox90; sbi t rs • p2·0;
// PlaLCD daca pins (Fig. 12-2)
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); lcddata('M•) 1 MSOelay (2 50) ; lcddata('O') 1 MSDelay(2SO); lcddata {• E')
}
308
1
//line 1
•
poi
s tion 6
vOld
(
1cdcmd(unsigned char value) ldata = value; rs • o; rw , O; en~ l; MSDelay(l); e.n = O;
II put the value on the pins II strobe the enable pin
return;
J 'IOid lcddata (unsigned char value)
{ ldata • value; rs= l; rw ;: 0; en = l;
MSDelay ( 1)
II put the value on the pins II strobe the enable pin
;
en = 0; return;
} void MSDelay (unsigned int itime) \
(
unsigned inti, j; for(i=O;i
wmplet2-2
Repeat Example 12-1 using the busy flag method. Solution:
l inc:lude 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) ; lcdd&ta ( 'M'); lcddata ( • o• ) ;
l
//line l, position 6
lcdda.ta(' E');
309
I void lcdcmd(unsigned char value) { 1cdready O ; ldata
v
en= l; MSDelay(l};
•'
abl e pin //strobe the en
•
en .. O:
return; ~
l
1,
l
valuei
rs • O; rw = O;
/ /
=
the LCD busyhenag. pins I /checJc value on t //put the
•
void lcddata(unsigned char value) { lcdready Cl : ldata = value; rs• l; rw = 0; en • 1;
//check t be LCD busy flag //put t he value on the pins
//strobe
t
he
enable pin
MSDelay (1), en • O;
rec.urn;
'I •
t
l void led.ready() { busy= 1; rs
= 0:
II ma ke the b usy pin an input
rw = l;
while (busy••l) { en = O; MSDelay(l); en
e-
//wait here for busy flag //strobe tbe enable pin
l;
l
return;
}
void MSDelay(unsigned int itime) {
unsigned inti, j;
l
for(iaO;i
Review Questions 1. The RS pin is an .Cinput, output) pin for the LCD. 2. The E pin is an (mput, output) pin for the LCD. 3. The E pin requires an . . .(H·to-L, L-to-H) pulse to latch in . . 4. For the LCD to recogn12e information at the data pins as d Rs tnformalion at the data pins of the LCD. s. Give the command codes for line 1, first character, and I2•,fi trnhUst be set to (high, low). 310 ' rs c arac:ter.
1m:
~
.,
secr10N 12.2: KEYBOARD INTERFACING J(eyt,oards and LCDs are the most widely used input/output devices of the 8051, and a basic understandin~ of is essential. In this section, we first discuss keyboard fundamentals, along with key press and key detection =:aiusms· Then we show how a keyboard is interfaced to an 8051.
r1acing the keyboard to the 8051 1118
At the lowest level, keyboards are organized in a matrix of rows and columns. The CPU accesses ~oth rows and (1liuJlU1S thr~ugh ports; therefore, with two 8-bit ports, an s x 8 matrix of keys can be conn_ected to a rrucroprocessor~ Wbfll a key lS pressed, a row and a column make a contact; otherwise, there 1s no connection between rows and col ~ . In IBM PC keyboards, a single microcontroller (consisting of a microprocessor, RAM and EPROM, and _s~veral ~aUon a single chip) takes care of hardware and software interfacing of the keyboard. In such.systems, it IS the .,,v:tion or programs stored in the EPROM of the microcontroller to scan the keys continuously, identify which one has blfJl activated, and present it to the motherboard. In this section we look at the mechanism by which the 8051 scans .,i identifies the key.
Scanning and identifying the key Figure 12-6 shows a 4 x 4 matrix connected to two ports. The rows are connected to an output port and the columns ueconnected to an input port. If no key has been pressed, reading the input port will yield ls for all columns since they mall coMected to high 01o:l· If all the rows are grounded and a l
Grounding rows and reading the columns To detect a pressed key, the microcontroller grounds all rows by providing Oto the output latch, then it reads the mlumns. lf the data read from the columns is D3 ·DO= 1111, no key has been pressed and the process continues until
cc
V
' '>
4.7k .~ >
3
);'.•
2
• •
I );'.'
·~
>
>;:'•
0
DO 7 DI
Y.•
6);'.,
5
>;;'•
4
4.7k
Y.• >;;'•
.
.
.
.
V
BY.•
A
F
E
);'..
9
02 >;:'' 03
Y.•
Y.•
D
Y.'
8 C
Y.• );;'•
-
Port 1 (Out)
03
02
DI
DO
Port 2 (In)
I f the pressed dcolumn o From Figure 12-0, identify the row •_n = for the coJum~ 1011 00 (a) 03. DO= 1110 for the row, D3 • DO= 0111 for the col um (b) 03. DO = 1101 for the row, 03 Ex•mple 12·3
I.·
1
ey
t'n
Solution: used to identify the key. number 2 was pressed. From figure 12-o th.e row and column bebclongs to D2; therefore, ~:~ number 7 ,vas pressed. ( ) The row belongs to DO and the co umn D3· therefore, 10 • · d h I mn belongs ' (b) The row belongs to 01 an t c co u
-
j •'
that a key press has occurred. For h . means 15 has a 7-erO, ' . d elected, a key press is detected. However, if one of the col~mn b·t column hastis been pressed. After a kcy pre~s ,s 1 I if 03 • DO = t l01 this means that ,1 key in the D ,vith the .top ro,v, the examp e, • f 'd hfying the k ey. Starting • k aucrocontroUer · h ·
'
'r
the microcontroUer will go through the process o '. en ads the columns. Jf the data read ,s all ls, no ey int at row IS grounds it by providing a low to row DO only; then 11 ..._,, the next row, reads the columns, and checks for any zero. activated and the process is moved to the next row. Jt growtdtifi~. • of the row in which the key has been pressed, the . , · I·d tif d After ,den ca 1ion . This process conhnues until the row is en ,e · b t This should be easy since the 1rucrocontroller kno-..1 next task is to find out which column the pressed key eIongs o.
. . b · esscd Look al Examp1c 12•3 · at any time which row and column are elmg ace . for detection •and identification of key activation. Pro ram 12-4 is the 8051 Assembly anguage program thr ln this progra!, it is assumed that Pl and P2 are initialized as output and input, respectively. Program 12-4 goes following four major stages: 1.
ough the
To maJ
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 for .that row e 00 ·up table holding the scan codes (or the ASCU ,-a!uel . and goes to the next s tage to identify the key. 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 . . . a e. igtu-e 12-7 flowcharts this process. Whde the key press detection IS standard for aU k b . 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 ,-arThere 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 ~ 2.
f
-4 shows keypad pr:o ll\Jcrocontroller) to implement the und~r· 312
grall'lnitng in 8051 C.
I
'
I ~
I
l
i,oard subroutine. Thie program sends t he ASCII code ,t~Y pressed key to PO . l :!0 1 .3 connected to rows P2 . 0·P2 .3 conne cted to columns ;Pl· MOY P2,#0FFH ;make P2 an input por t ;ground all rows at once MOY Pl, #0 iO : · read all col. ensure all keys open MOY A, P2 •;masked unused bits • ANL A,#OOOOllllB ·check til all keys released CJNE A,#OOOOllllB,Kl ' ACALL DELAY ·call 20 ms delay '2= ;see if any key is pressed MOY A, P2 ANL A,#OOOOllllB ·mask unused bits ;key pressed, await closure CJNE A,#OOOOllllB,OVER SJMP K2 •· check if key pressed • ;wait 20 ms debounce time ACALL DELAY ()VER: ;check key closure MOY A,P2 ·mask unused bits ANL A,#000011118 ' ;key pressed, find row CJNE A,#OOOOllllB,OVERl ;if none, keep polling SJMP K2 ;ground row 0 OVERl: MOY Pl , #111111108 ;read all columns MOY A,P2 ;mask unused bits A,#000011118 ANL ; key row o, find the col. CJNE A,#000011118,ROW_O ;ground row 1. Pl,#llllllOlB MOY ;read all columns MOY A,P2 ; mask unused bi ts A, #000011118 ANL ; key row 1, find the col . CJNE A,# 000011118,ROW_ l ;ground row 2 MOY Pl , #111110118 ;read all columns A, P2 MOY ;mask unused bits A,# 000011118 ANL ;key row 2, find the col. CJNE A, #0000llllB, ROW_2 ;ground row 3 MOY Pl , #l l l lOlllB ; r ead al l columns MOY A, P2 ;ma sk unused bits A, #OOOO ll l lB ANL ;ke y r-0w 3 , find the col. CJNE A,# 00001111B, ROW_3 ; i f none, false input , repeat LJMP K2
\.p
ROW O:
lOW l: lOW 2:
ltOII ) :
FIND :
:Asc11
DPTR, #KCODEO MOY SJMP PINO MOY DPTR, #KCODEl SJMP PI NO MOY DPTR, #KCODE2 SJMP PINO f'.OY DPTR , #KCODE3 RRC A JNC MATCH INC DPTR SJMP FIND CLR A MOYC A, e A+DPTR MOY PO,A LJMP Kl LOOK-UP TABLE FOR EACH ROW ORG 300H
; set DPTR=star t o f row o ; find col. key belongs t o ; set DPTR•s tart of r ow 1 ;find col. key belongs t o ; s et DPTR=s t art o f r ow 2 ;find col. key belongs to ; set DPTR=s t art o f row 3 ;see i f any CY b it is low ;if zero , get the ASCI I code ;point t o next col. address ;keep searching ;set A=O (ma t ch is found) ; get ASCI I code from tabl e ;displ ay pressed key
DB DB DB DB
;ROW ;ROW ;ROW ;ROW
JrnD
'0','l','2', ' 3' ' 4 ','S','6','7' '8','9','A','B' 'C', 'D' I 'E', 'F'
0 1 2
3
3U
I '
(
-
l
..
/
I I
(
Figure 12•7, Flowclurt for Progr•m
Eumple12~ Two \WH(ho arc ton~ \\'rit,• .t program tot, t ... ~""1,
Solution: Th<: two ~" okfK'j an, r'llfll"'-"''"'-1
pondtng port hne to go lo
314
·tch 2 (SW2) is pressed, the progran1. whenever switch 1 (S\Vl) is pressed, Ol is displayed on ~ort _2, w h en swi 1~. displayed and when both switches are sin,ultaneously pressed, OFH 1s displayed. ,'11> S)Y 1 / 5W2
8051
PO. I P0.2 P2
P3.2(1NTO)
ORG
OOOOH
LJMP
MAIN
·--main program • ORG AA!II: SETB MOV !!ERE: SJMP ;· ·ISR for INTO ORC
LJMP iBST:
TESTl:
ORG SElTB SBTB SBTB MOV J NC MOV JNC MOV
for initialization of interrupt 0030H ;make INTO an edge-triggered interrupt TCON.O ;enable interrupt INTO IE,#81H ;wait for i nterrupt HERE 0003H TEST 0080H PO .1 P0.2 C
C,PO.l SWl C,P0.2
SW2 P2,#0FFH
'
;jump to new location ;make PO.l an input port ;make P0.2 an input port ;set carry ;use carry flag to test the status of PO.l ;if C=O, it means switch SWl is pressed ;use carry flag to test the status of PO.l ;if C• O, it means switch SWl is pressed ; if both switches are not pressed, P2 •FFH
RETI SWl:
MOV
C,P0.2
JNC
BOTH
MOV
P2, #OlH TESTl P2, #02H TESTl P2,#0FH TESTl
SJMP
SW2:
MOV SJMP
MOV SJMP END
;since SWl is found pressed.test SW2 ;since both are pressed, jump to BOTH ;only SWl is pressed, make P2•0l ;continue monitoring the switches ;this is reached when SW2 is pressed ;continue monitoring the switches ;this is the case of both switches pressed
~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
1. er reading eas pores for
//define jj
,I /'
•4 , ' \711.I I B' , I ,91•9,ri.,} '; • C' ' ; •, D'• , • EF I
"l
1 •
., I•
void main() { . 1 mode 2 unsigned Char colloc, rowloc; //timer , TMOD = Ox20; //9600 baud t P bit THl • -3; //8-bit, 1 s 0 SCON = Ox50: //start timer 1 TRl • l; //keyboard routine. This sends the ASCII , //code for pressed key to the serial port //make P2 an input port COL• OxFF; //repeat forever while(l) { do
'
I
r '
{ ROW• OxOO;
colloc = COL; colloc &• OxOF; }while(colloc l• OxOF) ;
//ground all rows at once //read the columns //mask used bits //check until all keys released
do { do
{ MS0elay(20J; colloc • COL;
colloc &= OxOF; } while(colloc == OxOF); MSDelay(20); colloc • COL; colloc &= OxOP; } wbile(colloc == OxOF); while(l)
r
OxFE; colloc • COL; col loc & = OxOF; if(colloc l• OxOF) ( rowloc • O; ROW =
break ;
)
//call delay //see if any key is pressed //mask unused bits //keep checking for keypress //call //read //mask //wait
delay for debounce columns unused bits for keypress
//ground row o //read columns //mask unused bits //column detected I /save
//eXit row location While loop
-
316
THE80s1 MlCRo co
-; NiROLLER AND EMBEDDED SYST~
'
ROW• OxFD; colloc a COL; colloc &• OxOF; if(colloc !• OxOF) { rowloc • l; break;
I /ground row l //read columns //mask unused bits //column detected //save row location //exit while loop
l ROW= OxFB; colloc = COL; colloc &= OxOF; if(colloc !• OxOF) (
//ground row 2 //read columns //mask unused bits //column detected
break;
//save row location //exit while loop
ROW• OxF7; colloc • COL; colloc &= OxOF; rowloc = 3; break;
//ground row 3 //read columns //mask unused bits //save row location //exit while loop
rowloc • 2;
l
) //check column and send result to the serial port if(colloc •• oxOE) SerTX (keypad (rowlocJ [O J ) ; else if(colloc •• OxOD) SerTX(keypad[rowlocJ [l)); else if(colloc =• OxOB) SerTX (keypad (rowlocJ [2]) ; else SerTX(keypad [rowloc) [3)); )
l
void SerTX (unsigned char x )
{ SBUF • x; while(Tle•O); TI • O;
//place value in buffer //wait until transmitted //clear flag
J Void MSDelay(uneigned int value)
{
)
unsigned int x, y; for(x•O;X
ANO 1<£YBOARD INTERFAONC
317
I Review Questions
t'~~
i /
V •
11
1 •
.'
/1
key belong to? II ro,.-s are g.ro unded· Jurnn does the p ressed esses.
True or false. To see if any key: ~Jumns, whi~uire two dif;':1: fJ D3. DO = 01 I I is the data rea ~d ke identificabon a.re D3 • 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
SUMMARY
.
f
h~which key is pressed?
• ' ''I
' ,•
k ypads to the 8051. First, we described . es such as LCDs andd. e data or commands to it via its inte,. real-world dev,c LCD by sen ,ng
This chapter showed how to inter a"': w to ,ogram the . th ,.,.. ati·on modes of LCDs, then descnbed ho p . t This chapter also descnbed the oper. c oF.r , S051 proiec s. . , · ·th ,._ lace to the 8051. sed. ut devices ,or was shown ,nter,aang w, a "'Y· 8051 Keyboords are one of the most widely u d t:on mechanisms. Then ation of keyboords, including key press and t~e ASCU code (or the pressed ey. boo rd. 8051 programs were written to return
th:
I
r,
I
PROBLEMS SECTION 12.1: LCD INTERFACING
{) ' •
•
r
I. Which are the two registers in the LCD 7odule? rt using only 4 port tines? 2. How can data be transferred to the LCD rom ~ po code
3. To display letters and numbers, we sedndoddatad~a item) and its v~Jue is 4 "Clear LCD" is a (comman c e, a ,., S.· What is the hex value of the command code for "display . on'. cursor , on · 6. Which are the control pins of the LCD? What are the,r functton.5.' o the LCD
hex.
1
5
7. Give sthate{oUf RS,. E, and !,_~Wedwonh:es~pd:tdi:~::;:::t;:Jm:nd code (~r data) to be latched in by the LCD? 8. Whichtheoft e o owmg ,s nc,;u (a) H-to-L pulse (b) L-to-H pulse 9. How does the LCD distinguish between data and command? . 10. How does the busy Dag aid in making the LCD program more eflioent? . 11. For a 16x2 LCD, the location of the last character of line 1 is SFH (its comn\and code). Show how this value was calculated. 12. For a 16x2 LCD, the location of U1e first character of line 2 is COH (its command code). Show how this value was calculated. 13. calculated. For a 20x2 LCD, the location of the last character of line 2 is 93H (its command code). Show how this value was 14. calculated. For a 20x2 LCD, the location of the third character of line 2 is C2H (its command code). Show how this value was 15. For a 40x2 LCD, the location of the last character of line 1 is A7H (its comma d cod ) SI
ca Jculated. 16. For a 40x2 LCD, the location of the last character of line 2 is E7H ('ts
n
e.
\OW
h
ow
thi alue was sv
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
( ) IJ a a rows
(b)
. one row at tame
II
1 grounded? get a - - - - (l s, Os) · (c) bo ow h 111., " ·s ot (a) •nd (b)
318
' I
In Figure 12-6, to identify the key pressed, which of the following is grounded? :J. (,) all rows . .(b) one row at time (c) both (a) and (b) For figure 12-6, mdicate the column and row for each of the following. Jl, (al D3- DO= 0111 (b) 03 - DO= 1110 l5, ipdicate the steps to ~etec! the key press. Indicate the steps to identify the key pressed. : we need to operate a key in the interrupt mode. How should the key be connected? . ii, Ifa switch is connected to pin P3.2, what happens when the switch is pressed and a low is received on the pin?
ANSWERS TO REVIEW QUESTIONS 5tCf!ON 12.1: LCD INTERFACING I Input l Input ~ H-to-L
I High
~ 80Hand COH
SfCTION 12.2: KEYBOARD INTERFACING I. True l Column3
l True t
0
;. True
I
•
'•
nt
CHAPTER 13
ADC, DAC, AND SENSOR INTERFACING
OBJECTIVES Upon completion of tlus chapter, you will be able to: interface ADC (analog-to-digital converter) chips to the 8051 Interface temperature sensors to the 8051 Explain the process of data acquisition using ADC chips De:,cribe factor. to coru.1der in ;,elecnng an ADC chip De!.cribe the funchon of the pins of 804/809/848 ADC chips Dcscnbe the function of the pins of thl' MAXl 112 serial ADC chip Interface serial ADC chips to the 8051 Program !>Crial and parallel ADC chips In 8051 C and Assembly Descnbe the bab•C operation of a DAC (digital-to-analog converter) chip Interface a DAC chip to the 8051 Program a DAC chip to produce a sine wave on an oscilloscope Program DAC chip, in 8051 C cU1d A.sembly Explain the function of predMon IC temperature sensors De,,cribe ,ignal conditioning and its role an data acquisition
321
I
analog-to-digital conve~ters), DACs (digil.lJ . ch as Af)Cs ( h 8051 to these devices. In Section 13 1 ~ Id devu:es su · rface t e 1.: ADC0804 ADC · '" This chapter explores some more real-wor lain how to u,te b ·t arallel ADC c, ups . ' OSOstO&);' analog converters), and sensors. We will also ~ewiJlstudythe~e ~aracteristics of DAC ch1r~ are discusSEI! -' describeanalog-to-digitalconverter (ADC) cllif'SDC chip MJ\Xt112. . ss the issue of SJgnal cond.itiorung. Ii and AOC:0848 We will also look at the se;1aJ A cin of sensors and dtsCU 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~rAOC: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
· ·· Digtt · al computers use sed devices for data acquisition. alo (continuous). Temperature, pressure (wind 0 binary (discrete) values, but in the physical world every~ing ,s an .h. g that we deal with every day. A physical q r • 'd), h um,'d',ty, and ve1oc,ty · are a ',ew examples of physical I,qui · quantl · eslied' transducer Transducers are also f uan. tity is converted to electrical (voltage, current) signals using• device ca a titi d re erred to as seirsors. Sensors for temperature, velocity, pressure, light: ~nd many other natura quan es pro_ uce an o~tput that is voltage (or current). Therefore, we need an analog-to-digital converter to ?'anslate _the analog signals to digital 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 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], 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 data out. Senal AOCs are discussed at the end of this section. ADC devices
•
Analog-to-digital converters are among the most wtd~1Y ~
i::I
I
,I
fJ( ·'
'
I t
t
ADC0804 chip The ADC0804 IC is an 8-bit parallel AOC in the family of the ADC0800 · · · ser:ies from National Semiconductor (www. national.com). It is also available from many other manuf tur 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 . on vs Ste rr-bit Numb · P 1:i;e for A.DC er of s teps 8 256 Step Size (m V)
s·
lO
1024
51256: 19.53
l2 16
4096
5/1024: 4.88
65536
5 I 4096 = 1.2
N
5/65536:: 0.076 -
Strpsrze(.....,luhon)bth
'
T1-r1:sos1r.u CRoc oNTROL
-
LE& AND EMBEDDED svsrfMS
'
lied to the RD pin, the 8-bit digital output shows up at the DO_ D7 data pins. The RD pin is also referred to as I 1Pl'1""able (OE). ~utpU
Wfi (wrlte; a better name might be "start conversion") lhis is an active low input used to inform the AlX0804 to start the conversion process. lf CS= 0 when WR
Jo ·-to-high transition, the ADC0804 starts converting the analog input value of v,. to an 8-bit digital number.d
e ':ntof time it takes to convert varies depending on the CLK [N and CLK R va lues explained below. When the ata :.ersion is complete, the INTR pin is forced Jo,v by the ADC0804. 1
CLK INand CLK R CU( IN is an input pin connected to an external dock source when an exten,al clock is used for timing. However,
d,el!OI has an internal clock generator. To use the interna l clock generator (also called self-docking) of the ADCOB04, 111eCLK IN and CLK R pins are connected to a capacitor and a resistor, as shown in Figure 13-1. In that case the clock 1,tquency is determined by the equation:
If II'
I=
..
d
•II
rna:s
i
J.l RC
T)'pical values are R = !OK ohms and C = 150 pP. Substituting in the above equation, we get f = 606 kHz. In that case,theconversion time is 110 µs.
1,
••
•
11-
:r
.
r.
//fTR (Interrupt; a better name might be " end of conversion") 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 high-to-low pulse to the RD pin to gel the data out of the AlX0804 chip.
v. (+) and V,. (-) These are !_he differential analog_inputs where v,. = V,,. (+) - V.. (-). Often the Vm ( - ) pin is connected to ground and the v. (+) pm 1s used as the analog input to be converted to digital.
"
r.
AOCOS04 +SV
20 10k
POT
•
I
•..
-~
6 7 8
Vin(+) Vin(•) AGND Vref/2
9 19
. -150pF !Ok
--
4
CLK in
1 2
10
--
CLKR
cs RD DGNO
Vee
18
00 17
DJ
16
D2 15 D3 14 D4
13
D5 12 D6 11 D7 WR
INTR
3
5
LEDs
I 12 Relation to
T able 13-2: V ttl'
2 (V)
;n
..,
(ADC0804) VI Step Size (m _ J953 5 1256
Va/
O10 5
4/255 = 15.62
2.0
O10 4
3/ 256 = 11.71
O103 oto 2.56
2.56/ 256 = 10
not coMected·
1.5
.../
V CV>
V Range
I
'
,
! .,
1
V cc
,,,•)
ltage wh.en rh.e V,./2 input (pin 9) is open (not
d as a reference vo
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 an e v /2 is used to implement analog input O the analog input applied lo V. needs to'?" other than. the to+ rds ·be Oto 4 volts, V /2 is connected to 2 volls.
5J
voltages other than O10 S V . For example, 1f the analog mput range nee Table 13-2 shows the V'" range for various V.../ 2 inputs.
'
r
f
0
(
..i
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 buffered and the converted data is accessed only when CS= 0 and RD is forced low. To calculate the output voltage. use the following formula.
p
D = V~ "' steps,u . where D.., = digital data output (in decimal), V change, which is (2 xv,,/2)/256 for ADC0804. •
=analog input voltage• and step s12e · ( I · } • th llesl reso ution 1s e sma
Analog ground and digital ground These are the input pins providing the ground for both th
. connected to the ground of. the. anaJ.og v,, while digital groun~ :snalog signal and the digital signal. Analog ground IS that we have two ground pms 1s to isolate the analog v . connected to the ground of the v pin The reason 11 the output DO- D7. Such isolation contributes to theaccu":-!~gn:r rom_ transient voltages caused by d~ital ~"itching ol nccted to the same ground; however, in the real 1vorld of drta 1Jthe ~l~tal data output. In our discussion both areconseparately. cqu,s,tion the analog d d · . al ' h dled From this discussion we conclude that the foUo . an 1g1t grounds are an chip. wmg steps must be follow ed. for data conversion by the A[)C08()l 1. Ma.ke CS = 0 and send a low-to-high pulse to in WR. 2. Keep monitoring the INTR pin. If INTR is lowpth to start the conversion high, keep poUing until it goes low. ' c conversion is finished an~ w .
3.
324
After the INTR has become low, we make CS., e can go to the next step. If J.NTRIS 0 the ADC0804 IC chip. The timing for this Proces ~nd 5end a high-to-) s 1s shown · ow Pulse t 0 th i,/ u, Figure 13.2 , e RD pin to get the data out
TliE 80S1 l\fJ<::Rrv-. ~ONTRot lER ANO EMBEDDED
a
SYsT£M5
t
• •
,,,... I
I
cs
-WR
Loaia out
DO- 07
' '
:
iNTR '
-RD
Start conversion
find conversion
Note: CS is set to low for both RD and WR pulses. Read it fipll'l3-2. Read and Write Timing for AOC0804
I
L
•,.
Clock source for ADC0804 the speed at which an analog input is converted to the digital output depends on the speed of the CU< input. Acrording to the ADC0804 datasheets, the typical operating frequency is approximately 640 kHz at 5 volts. Figures 13-3 l!ld 13-4 show two ways of providing cloc.k to the ADC0804. ln Figure 13-4, notice that the clock in for the ADC0804 is millg from the crystal of the mic:rocontroUer. Since this frequency is too high, we use D flip-flops (74LS74) to divide !he frequency. A single D flip-Aop divides the frequency by 2 if we connect its Q to the D input. For a higher-frequency O)llal, you can use 4 Aip-Aops.
Programming ADC0804 In Assembly . Examine the ADC0804 connection to the 8051 in Figure 13-4. The following program monitors the INTR pin and bring;an analog input into register A. It then calls hex-to-ASCII conversion and data display subroutines.
" _,.. +SV 8051 P25 1'2.6 Pl.O
ADC0804
ro, WR DO
VCC CLKR CL!< IN
10k.
T
Vref/2 Vin (+l Vin (-
Pl.7 P27
07 INTR
1.28V
+SV
--
-
-
t
-es GND
AGNO
;1
150pF
V
--
10k
•
---
POT
I .
+SV ,...
AJJCCJ804
8051
_RD
vcc
WR DO
CLKR CLKIN
1'2.S
'
' 11.0592
c!:J
,MHz T I
I
Lo -
~
,
I>
XTAL 1'26
Pt.0 ''
~,-
0
-
PJ.7
07
1'2.7
b\fffi
Q
..... AGND ~GND .....
I
/)
IOk
POT
~
•1:'
'
.,
LD
• I
{ \
'I
~
~
)
Q
0
LD
LD
Q
0 ...
'-
Q
> 0
74l.S14
I
r
-~
VU1(+l VU1 (·
-
'
+SV
~
Vref/2
-
' --
XTA!.2
~
Use 4 to5 OFF to obtain the correct
frequency for the AOC chip
. C lock from XTAL2 of the BOSl Figurt' 134. 8-051 Connection to AOC080ol with
'
RD
WR INTR
t
MYDATA
MOV S8'!'B
BACK:
HERB,
CLR
BIT P2.5 BIT P2.6 BIT P2.7 EOU Pl Pl,#OFFH
INTR
SETS
WR WR
JB
INTR,HERE
CLR
RD
MOV
A,MYDATA
ACALL ACALL SETS
CONVERSION DATA DISPLAY RD
SJMP
BACK
·RD
.
,'.wR (start conversion) •end~of~convers1on ;Pl.O·Pl.7=00-07 of the ADC804 ;make Pl• input ;WR•O
;WR•l L-to·H to start conversion ;wait for end of conversion ;conversion finished,enable RO ; read the data ;hex-co-ASCII conversion{Chap 6) ;display the data(Chap 12) ;make Ro~1 for next round
For hex-to-ASCII conversion and data display, see Chapters 6 and 12, respectively.
F
Programming ADC0804 in C
The 8051 C version of the above program is given below. #include sbit RD • P2'5; sbit WR= P2'6;
sbit INTR • P2'7; sfr MYDATA = Pl; void main() { unsigned char value; MYDATA = OxP!"; INTR • l; RO= l; WR • l;
I lmake Pl //rnake INTRand input
//set Ro hi ~nd input //sec WR hi:h
326
llie sos1 l\11cR.ocoN
TROLLER ANO EMBEDDED SYS~
'
>1hile(l) {
//send WR pulse //L-to-H(Start conversion) //wait for EOC //send RD pulse //read value //(Chap 7 and 12)
WR • O;
WR s l; while (INTR RD
~
=s
1);
O;
value= MYDATA; ConvertAndDisplay(value), RD = l;
}
l Al)COBOB/0809 chip with 8 analog channels Another useful chip is the ADCOSOS/0809 from National Semiconductor. See Figure 13-5. While the ADC0804 has (t11yone analog input, this chip has 8 of them. The ADCOSOS/0809 chip allows us to moni tor up to 8 different analog illpUIS using only a single chip. Notice that the ADC0808/0809 has an 8-bit data output just like the ADC804. The 8 analog input channels are multiplexed and selected according to Table 13-3 using three address pins, A, B, and C. tnthe ADCOSOS/0809, V...,(+) and V.,.(-) set the reference voltage. If V.J-) = Gnd and V..,(+) = 5 V, the step size is ;V/2j6 =19.53 mV. Therefore, to get a 10 mV step size we need to set V..,(+) 2.56 V and V..i(-) Gnd. From Figure 13.s,notice the ALE pin. We use A, B, and C addresses to select INO - IN7, and activate ALE to latch in the address. SC jsro,startconversion. SC is the same as the WR pin in other ADC chips. EOC is for end-of-conversion, and OE is for oulpllt enable (READ). The EOC and OE are the same as the lNTR and RD pins repectively. Table 13-4 shows the step ;izerelation to the V"'voltage.Notice that there is no V...,/2 in the ADC0808/0809 chip.
=
!NO
1N7
......
.. ....
=
I GND
Vee
Clock
00
AOC0808/0809
D7 Vref(+)
EOC OE
Vref(-)
SC ALE C B A
(LSB)
Rg,ue u..s. ADC0808/0809
Table 13-3: ADCOSOB/0809 Analog Channel Selection Selected Analog Channel
C 0
B
A
0
0
0
0
1
!N2
0
1
0
!N3
0
1
1
IN4
1
0
0
INS
1
0
I
IN6 IN7
1
1 1
0
!NO !NI
......__ 4
tlc, DAc, ANO SENSOR INTERFACING
1
1
I
V Range f o r Table 13-4: V,., Relation to '" V1• (VJ not connected 4.0
/ 1
.,
• ()
1
.I
D ( ·'
I
3/ 256
=J].71 2.56/256 =10
2/256
7.81
=
1/256 3.90
Steps to program the ADC0808/0809 The following are steps to get data from an AOCOSOS/0809. . b" A d addresses accord ing to Table 13-3. 1. Seleel an analog channel by providing ,ts to , 8, an 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.
c
3. 4.
5.
t
'
0 to4
Oto2 Oto 1
2.0
.)
4/255 = ]5.62
Oto 2.56
2.56
Step Size (m V) 5/256 = 19.53
0105 O to3
3.0
ADC0808/0809
Activate SC (start conversion) by an L-to-H pulse to initiate conversion. Monitor EOC (end of conversion) to see whether conversion is finished. H-to-L output indicates that the data is 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. 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 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
WR(SC)---
R0(0~ - - 1i- ---------------.I-~--!
Al..E-~
;
ADOR
--'ri--------00.07--~'I-------------~~...r-~-, . -+,--.i~
EOC(lNTR)
i.__:
LATCH ADDRESS
j
Fig1trr 13-(,. Selrcting • Cha11nel and Re•d T" . IIJ\Jng for AO<:o3o9
LATCH DATA
328
lliE 80s1 ~11CRo CO!lf~OLLE
RAND EMBEDDED svsretS
p
+SV
--
•
'11.0592,-!....
,MHz'
J
'
-t;S~V
ADC0809 RO(OE) VCC WR (SC) Vref (+)
8051 P2.5 XTALI P2.6 Pl .O XTAL2
TN2 1~3 41~5 [ 6IN, CLOC ALE Vref (·) INTR(EOC)~ DO
2.56V
10k POT
!NO
fNl
I
O..-N
S!&:!&:!
Lo Q
Pl.7 P2.4 P2.7
D7
-
ABCG
t
Q-
Lo
ii If
Q
- Lo
Q
•
Lo
Q
0
~--
Q
0
74LS74
iw,tt 13-7. 8051 Connedion lo ADC0809 for Channel 1
:t
Figure 13-7 shows the connections for the following programs.
I
Programming ADCOSOS/0809 in Assembly BIT P2.4 BIT P2. 5 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 SETI! EOC CLR ALE CLR SC CLR OE ALE OE SC
a.>.cK:
kt,!:
~
;make Pl an input ;make EOC an input ;clear ALE ;clear WR ;clear RO ;C-0
CLR CLR SETB ACALL SETB ACALL SETB ACALL CLR CLR
ADOR_C ADOR_B ADOR_A DELAY ALE DELAY SC DELAY ALB SC
;make sure the addr ia stable ;latch address ;delay for fast OS89C4x0 Chip ;start conversion
JB
BOC, H&RB
; wait until done
Ile, DAc, .\ND Sll!NIOa INTDJIAONG
;B•O ;A•l (Sel ect Channel 1)
~
I !fEREl: JNB
EOC, HEREl
SETB
OE DELAY A,MYDATA OE CONVERSION DATA_DISPLAY BACK
ACALL
MOV CLR ACALL ACALL
SJMP
. until done -wait ~n ';enaJ:>l e "" ,wait • d data xt time ·rea fol' ne J
I
6 ' clear RD ) 1 (ChaP 12 '. hex to ASCI data (Chap '.displ ay t he
•
Programm·1ng AOCOSOS/0809 In C
,.
~include sbit ALE• P2.4; sbit OE= p 2·s,
t
.,
sbit. SC • P2"'~;
sbit EOC = P2 ?; .• ADDR- A= P2'0; 6 b 1... sbit ADDR_B • P2 . l; sbit ADDR_C = p2 21 sfr MYDATA = Pl; void main() { unsigned char va lue; MYDATA • OxFF;
t
A
soc •
1; AL£ • 0;
t
OE= O; SC= O; while(l)
//make Pl an input //make EOC an i nput //c l ear ALE / / clear OE //clear SC
{ ADDR_C • 0;
ADDR_B • 0; ADDR A = l; MSDelay(l); ALE = l; MSDelay ( l) ;
//C•O / /B•O //A•l (Select Channel 1) / /delay for fast DS89C4x0
SC= l;
MSDela y(l); ALE• O;
SC• O; while(EOC••l ) ; while (EOC.•O) ;
//start conversion //wait for data conversion
OE = l;
)
J
MSOelay (1); value• MYOATA;
//enable RD
OE• O;
//get the data / / disable RD for next round //Chap 7 & 12
ConvertAndOi splay (value ) ;
I
ADC0848 interfacing The AOC:0848 IC is another analog-to-digital converter · th . ~ Semiconductor Corp. Data sheets for this chip <>an be follnd at~ . e fatniJy of the AOC:0800 series from Na to Products > Analog-Data Acquisition> A-to-D Converter.r.. al Petr Web site, WWW national com From there, go =er urpose. . . • 330
-
°fJ{l! 8051 ~CR<>c .. ONTROLLl!R AND EMBEDDED SYllil-
AJJCOS48 has a resolution of 8 bits. It is an 8-channel AOC, thereby ~e it 10 monitor up to 8 different analog inputs. See Figure 13·8. The ,lk!~ chip in the same fami ly has 4 channels. The foUowi.ng describes A the AOC0848. 11,t pLflS
or
cs
(hip select is an active low input used to activate the 848 chip. To access 11><'&18, this pin must be low.
vcc 24 0
1 RD
2 CHI
CS23
3 CH2
i¥R22 0
-
lNTR 21
S Cl-14
0
0
OB0/MA020 0 DBI / MAJ 19 0
RO(read) RO is an input signal and is active low. ADC converts the analog input ·isbinarY equivalent and holds it in an internal register. RD is used to get :ronverted data out of the 848 chip. When CS= 0, if the RD pin is asserted loW, the3-bit digital output shows up at the DO · 07 data pins. The RD pin ~also referred to as output enable (OE).
,.,
7 CH6
DB2/ MA218 0
8 CH7
DB3/MA.317 0
9 CHS
D84/MA416 0
10 AGND
05515
0
11 Vref
08614
0
12 DGND
06713
0
v
is 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 V (V) Step size (mV) o/ JOmV, then V..., = 2.56 V, since 2.56 V/256 10 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 output.the 848 must be an 8-bit ADC. The step size, which is the 111allest change, is dictated by the number of digital outputs and the V,. voltage. To calculate the output voltage, we use the following formula;
2.56
10 (2.56V /256)
1.26
5
0.64
2.5
Dlit;, =
•
Note: Step saze = V,,.,./256.
~.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
Sot111ion: •}:1ee ~Slep ueit2.56/ 2S6 • 10mV, we have the following. (b\ 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,
g.. •
..
~ C , ANO SENSOR INTElll'ACING
v, and
I
......
Vee
GND
CHI
'
...
ADC0848
D7
CHS
. _/
AGND Vrel
J
[)()/ MAO DI/ MAl D2/ MA2 D3/ MA3 D.J/ MA4
JNTR
cs
WR
'I -,
RD
•
' l ~ /
D
(
,,
Figuro 13-9. AOC0848 Blc>
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 00 07 4 080 - DB7 pms are also designated _as ~AO· MA . The 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.
p
I
't
I
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! channel. If CS = Owhen WR makes a low-to-high transition, the Atx:0848 latches in the address of the selected channel 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.
CH1- CH8 CH1 · CH8are8channelsoftheV analog inputs lnwhatis<:alleds' gl 10 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. used for analog V.,. where the AGNO (;nalog ground) in is used
Table 13-6: ADC0848 Analog Chan nel Selected Analog Channel MA 4 CHI 0 CH2 0 CH3
CH4 CHS CH6 CH7 CHS Nair Ch.lnnello,elec1,'
0
0
(s·mg1e- Ended Mode)
MAJ 1
1 I
0
I
0 0 0
.
echon
e
1
1
I d
• iln
332
S I
•n L-lo-J.J
l
J>Ul.o is applJed
MA2
0 0
0 0 1
1 1 ] lo IVR.
T1iE 8051 MlcRo CON~ROLL
MAl 0
0
0
1
1
0
1
1
0
0
0
1
I
0
l
I
MAO
-
__ .-1!16
ER AND l!MBEODEDSTlJ'....-
s
I.
he
...
in.
~
.~tial mode, two channels, such as CHl and CH2, are paired together for the V..<+) a_nd ..(-) differ~!;::~~ 11Ji lJ1 that case V~ = CH I (+) - CH2(-) is the differential analog input. To use ACX:0848 lfl d,fferenhal m e,. 1 f'f,~,and MA3 is set to low. For more on this, see the ADC0848 data sheet on the www.national.com Webs, e. ;to
r/J y
is the+ 5 volt power supply.
(C
~GIID, DGND (analog ground and digital ground)
.
Both are input pins providing the ground for both the analog signal and the djgital signal. Analog ground ,s con· r,ected IO the ground of the analog V ~ while digital ground is connected to the ground of the Vq: pin. The r~ason that
tha•e two ground pins is to isolate the analog v signal fron, tra,15ient voltages caused by d1g1tal sw itching of the ~ t 00 • D7. Such isolation contributes to the a;curacy of the digital data output. Notice that the single-ended lll)de the voltage at the channel is the analog input and ACND is the re ference for the v,•. In our_ ~1scuss1on, both the ,c;.,roand DCN0 are connected to the same ground; however, in the real world of data acqu1s1tion, the analog and
m
digiWgtoWlds are handled separately.
,ml (/nte"upt; a better name might be " end of conversion") This is an output pin and is active low. It is a normally high pin and when the conversion is finished, it goes low to ;,gnal the CPU that the converted data is ready to be picked up. After INTR goes low, we make CS= 0 and apply a low pulse to the RD pin to get the binary data out of the ADC0848 chip. See Figure 13-10.
Selecting an analog channel The following are the s teps we need to take for data conversion by the ADC0848 chip. t While CS= 0 an~ RD= I provide the ~ddress of _the selected channel (see Table 13-6) to the DBO - DB7 pins, and
apply a low-to-high pulse to the WR prn to latch ,n the address and start the conversion. The channel's addresses are 08H for CHl, 09H for CH2, OAH for CH3, and so on, as shown in Table 13-6. Notice that this process not only selects the channel, but also starts the conversion of the analog input at the selected channel.
WR----.
m---__.;__________
TRIN-----'-----~~~ MA~MA4 1)().[]7
---~I MA~MA4 f----------~~--· 00-07 f-LATCH ADDRESS
....... 13-10. Stloct1n11 • Owtnel ond llead Tlmln11 for the ADC0848
"Ile. DAc, .\ND SENSOR INTDFACING
LATCH DATA
I +5V
10k
POT
... ~
AGND
I
DGND
-•.'
1 •
=
. • I
i:
. to A OC0848 (or Channel 2 Figure 13-11. 8051 Connection
I
r
2 ·
3.
·'
. WhileWR =l and RD = J keep n'.onitormgthe
w the conversion is finished and wee.an
INTR goes lo ' R · When · · end_-of.conversion. · polling until it goes Jow, signalling
rr-.:1:k~s
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 - 1• an After the INTR has become low, we mus·t makeCS -0 - ' out of the 848 IC chip.
'
••
ADC0848 connection to 8051
.
.
The following is a summary or the coMection between the 8051 and the ADC0848 as shown m Figure 13-11 . P1 .O-P1.7 DO- 07 of ADC: P2.7 to INTR P2.6to WR P2.5 to RO
Channel selection (out), data read (in} P2.7 as Input P2.6 as output P2.5 as output
Notice the following facts about Figure I'.>-11. 1.
2.
P2 is an output when we select a channel, and it is an input when we read the converted data. We can monitor the lNTR pin of the ADC for end-of-conversion or we can wait a few milliseconds and then read the converted data.
Olsplayl ng ADC0848 data In order to display the ADC result on a screen or LCD, it must be conv r . h w· ever, it must first be converted to decimal. To convert a 00 _PF h e te~ to ASCII. To convert it to ASCII, . O remainder is less than 10. Each time we divide it by 10 we kee ·~:•Iue to decunaJ, we keep dividing it by 10 uotil the of an 8-bit data, dividing it by 10 twice will do the job. For ex P e uotient as one of our decimal digits. In the case convert from decimal to ASCIJ format, we OR each digit with;:I 1 we have Pl'H it will become 255 in decimal. To digits to the PC screen using a serial port, or send them to th LCD see Chapter 6). Now all ,ve have to do is to send the
t' 1
Programming ADC0848 in Assembly
e
' as was sho,vn in the Chapter 12.
The following program selects channel 2, reads the data
cs RD 334
BIT P2. 4 BIT P2.S
'and calls corwersio . n and display subroutines.
p
BIT P2.6 BIT P2.7 OH INTR
WR
!NTR ORG SETB SE'l'B SETB SETB a1
WR
;make INTR an input ;set Chip Select high ;Set Read high ;set Write high
Pl,#OAH
;Chan 2 address(Table 13-6)
cs RD
MOV NOP CLR CLR NOP NOP SETB SE'l'B MOV
cs WR WR
cs Pl,#OFFH
HERE:
II\
la
JB
INTR ,HBRB
CLR CLR NOP NOP SETB MOV SETB ACALL ACALL
cs RD
RD
A,Pl
cs CONVERT DATA_OISPLAY
;wait
;chip select (CSsO) ;write= LOW ;make pulse width wi de enough ;for DS89C4x0 you might need a delay ;latch the address and s t art conv ;de-select the chip ,make Pl an input ;wait for EOC ;chip select (CS=O) ;read RD=O ;make pulse width wi de enough
;bring out digit al data ;get the value ;de-select for next round ;convert to ASCI I (Chap 6) ;display the data (Chap 12)
Programming ADC0848 In C The following prog:ram selects channel 2, reads the data, and calls conversion and display subroutines.
!include sbit CS • P2A4; sblt WR c P2AS; 1bit RD • P2A6; sbit INTR • P2A7 1 •1oid main()
{ unsigned char value; lNTR = l;
//make INTR an input
cs •
l; WR • l;
RD• 1;
whi le (l) { Pl oxOA; D
CS• O; WR= O;
Delay() ; WR• l; cs. l; Pl• OxFF;
while(INTR••l)1
.\be, DAc, AND SENSOll lNTDJIACINC
//Chan 2 addr see Table 13-6 //chip s elect //wr ite•WW //make pul se wide enough //L·to-H to l a tch addr //de - sel ect //make Pl an i nput //wa it for BOC
I
//chiP select ;;read
cs•
0; RD = O;
RO• l;
data // read t he the value //get
value• Pl; cs. l;
//Chap 7 & 12
Delay();
I
ConvertAndI>isplay(value); }
I
-•.
1 • r' )
~I
r 'l
•
l
,
Serial ADC chips f the parallel type. The DO - D7 data pins of !he 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 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 this reason, serial devices such as the senal. ADC are ~com~ Maxim used. Next, we examine the MAX1112 senal ADC chip fro . .th Corporation (www.maxim-ic.com), and show how to interface ti wt the microoonlroUer.
0
1 CHO
VDD 20
0
2 CHl
SCU< 19
MAX1112 ADC
D 3 CH2
CS 18
The MAXl 112 is an 8-bit serial ADC chip with 8 channels of analog input. II has a single Door pin to bring out the digital data after it has been converted. It is compatible with a popular SP! and Microwire serial standard. The following are descriptions of the MAX1112 pins. (See Figure 13-12.)
0
4 Cl-13
DiN17
D 5 CH4
SSTRB 16
0
CHO-CH7 O!O - CH7 are 8 channels of the analog inputs. In the single-ended mode, ~ach of the channels can be used for an analog input where the COM pm lS used as a ground reference for all the channels In · l ended mode, 8 chaMels of input allow us to read 8 diff~ t sm~ einputs. W~ select the input channel by sending in !he conn ana og trol byte v,a the DIN pin. In differential mode, we have 4 sets of 2-channel differentials. CHO and CHI go together and CH2 • CHJ, and so on. '
6 CHS
Dovr 15
D 7 CH6
DGN014
D 8 CH7
AGNDJ3
D 9COM
REFOUT12
D 10 SHON
..
CHO
Ground reference for the analog input . , ended mode. in single-
I
AGNDDGNO
MAXu12
REFIN 11
I VDD
.. cs
SCLK
0!7
cs
REF!N
Chip select is an active low input used to 1 ~Xll12 chip. To send in the control byte vi:ect the pm, CS must be low. When CS is high the ~e ON OCllrr IS high impedance.
REFOUT
336
s
Figure 13-U. MAXllU Chip
I COM
•
'
DIN OOlIT SHUN
SSTRB
Fi.s ure ll-13
· 1'1AJCtiu Ser1.i AOC Block Oiogram
Tl:fl! 80St 1'11<:Roc:
ONlltou."n -
ANO EMBEDDED sY5fOd
•
•
..•
5CLJ(
.
5erial clock input. SCLK is used to bring data out and send
0#
.
Ill
ntrol byte, one bit at a time. the co
.
e H·to·L edge (falling edge) of SCLK. Serial data out. The digital data is clocked out one bit at a ttme on th
O,.
.
th L to·H edge (rising edge ) of SCLK. Serial dat,1 in the control byte is clocked in one bit at a tLme on e •
S5TRB
.
. d ' tes end-of-conversion. Serial strobe output. In internal clock mode this m ,ca (llll\plete.
It goes high when the conversion is
v(JD
...
V is the +5 volt power supply .
AGND, DGND (analog ground and digital ground) Both ~re input pins providing ground for both the analog and the digital signals.
SHON Shutdown is an input and is normally not connected (or is connected to V co>, If low, the ADC is shut down to save po~er. This is shut down by hardware. The control byte causes shutdown by software.
REF/N Reference voltage input. This voltage dictates the step size. REFOUT Internal Reference Generator output. A l µF bypass capacitor is placed between this pin and AGND.
MA.X1112 control byte The MAXI 112 chip has 8 channels of analog inputs that are selected using a control byte. The control byte is fed Into the MAXI 112 serially one bit at a time via the D,,. pin with the help of SCLK. The control byte must be sent in with !ht MSB (most significant bit) going in first. The MSB of the control byte is high to indicate the start of the control byte, ~shown in Figure 13-14.
REFlN vottage and step size
-• The 6!ep siz.e for the MAXl112 depend~ ~n the voltage connected to the REFIN pin. In unipolar mode, with V re"' 5 V , tel4.o% V for full-<;eale 1f the RERN pm u; connected to the AGND with a l·µF capacitor. That gives us a 16-mV step ~llnce 4 096 V/'256,. 16mV. To get a 10-mV step si2e, we need to connect the REFIN pin to a 2.56 V e'Ctemal voltage
>.De, DAC. ANO SENSOR INTIIRl'ACING
I I [
Start
I
I
SEl.2
SE1.0 j lJN/ BIPl SGL/ DF I
POI
I
PDO
SLEl
'•
....,.,~~ing of the control byte.
define the ~.,uu•
The MSB (07) must be high to 1t must be sent in /irsL N (SJNGI.E-ENDED MODE) Sl!l l SELO O{ANNEL SELECflO
St.rt
/
., 1 ! ., •
,' \
•
SEU 0 0 0 0 1
o
O
CHAND
O
l
CHAN!
I
O
CHAN2
1
1
CHAN3
0
0
CHAN4
1
O
1
CHANS
1 l
I
O
CHAN6
I
1
CHAN7
1 e unipolar: Digital data output is binary 00 · FFH. O= bipolar. Digital data output is in 2's complement. 1 = single-ended: 8 chaMels of single-ended with COM as reference O= differential: Two chaMels (eg., CHO - CHI) are differential.
UNI/BIP
SGUOfF
PO!
'
'
I • fully operational 0 = power-down: Power down to save power using sofh,.are. 1 a extemal clock mode: The conversion speed is dictated by SCLK. 0 = intemal clock mode: The conversion speed is d ictated interna lly, and the SSTRB pin goes high lo indicate end--0f-conversion (EOC).
PDO
Figutt 13-14. MAX1l12 Control Byte
--
+SV 8051
MAX1112 1'2.0 P2.J 1'2.2 1'2.3
.
-cs
SCLK DIN D0UT
+_sy YDD SHON J--..J CHO f - -
CH1 CH2
t:------+--1~' ) • '
CH3 1--CH4 f - -
2.56V ,-
~
R£FOUT
---
AGNO
luF
FigUtt 13-15. 8051 Connoclion to MAX1112 f
338
REFJN
or 2nd Ch•nntl
CHs r--CH6 t--CH7 t---
COM t--DCNo .--..,,1
j
-
- '-
al f e ce voltage must be between ,inct' 2.56 V/ 256 = 10 mV. According to the MAX1112 data sheet, the cxtem, re e r n ~~~-V . Notice the lower limit fo r the reference voltage. II
~r,u
,.,
selecting a channel.
N0 tic that the MSB (D7) of the control
WrS<'lcd the analog input ch annel using the control byte. See Exa mple 13·2. e · :tt 111u>t lie high. · d ks in the control by te on the M the control byte is fed into the DIN pin one bit a t a time using SCLJ<. The DIN p m oc o;u,g edge of SCLK as shown in Figure 13-16.
iAss81Dl>lY Code for sendin g in contro l b yte in ;!W<1112 , see Figure 13·15
Hl:
CS SCLK DIN OOllT
BIT BIT BIT BIT
HOV MOV CLR
l\ , #9EH Rl , #8
CLR
C
RLC
l\ DIN, C
MOV CLR
P2 . 0 P2. l P2 . 2 P2. 3
;channel l selection ;load count. ;CS;O
cs
;give bit to CY ,send b i t to DIN ;low SCLK f or L· H pul se ;delay ;latch dat a, see Fig 1 3 ·16 ; delay ;repea t fo r al l 8 b i ts
SCLK ACALL DELAY SETB
SCLK
l\CALL DELAY Rl, Hl DJ!IZ
E.wnple lJ-2
rmd the 1'1AXl 112 control byte for (a) CHO, and (b) CH3. Assume sin gle-ended , unipolar, intemal clock, and fully opmbonal mode:; Solution: from F,gure 13-14, we hove the following: l•l l!XXll 110 (SF ,n hex) (b) 101111 10 (S E ,n hex)
MAXI 112 lntcmol Clock Mode Tuning Dfogram
Srnding Control Byte into MAXI\ 12
r
''' I
I
1
,
SCLK - - ~ I
DIN
3
2
_J STtRT I
,i
st I
i S~ I
1
t-;;;, tl-J6. S.nd lng Control Bytr into MAXll 12
~ DAC. AN D SENSOR INTERFACING
1
4
,I
I
s
7
6
j
I
I sf juNtys1r!scLrou:1 P£1 I I :
!
1
'
8
' p~
I '
I
I
onversion scares
cs
;de
CLR
SCLK
'
~-o
. 50,...,...
during
HJIX1112 }l!)C
byte for / /C Code for eending iJl control pigure 1)-15 ijinclude //see sbit CS= P2'0; sbit SCLK • P2' 1 ; sbit DIN= P2A2; sbit OOUT • P2A3; sbit MSBRA • ACCA7 ; void mai n (void) { unsigned char conbyte•Ox9B ; //Chan 1 unsigned char x; ACC•COnbyte ;
/ '
v' J
1
SETS
• select JIDC, C conversion
-, l•
CS•O; for{ x =O; X<8; x+ +)
{ OIN•MSBRA; Delay() : SCLK=l;
//Send D7 of Reg A to Din //latch in the bit
Delay(); ACC = ACC << l;
l
CS=l; SCLK=O ;
r
//next bit //deselect MAX1112 //Make SCLK low during conversion
I Start conversion and end of conversion for MAX1112 When the last bit of U,e control byte, PDO, is sent in, the conversion starts, and SSTRB goes low. The end1>I· conversion state is indicated by SSTRB going high, which happens 55 µs after PDO is clocked in. We can either wail 55 µs, or monitor SSTRB before we get the digital data out of the ADC chip. Next we show how to get digital data out of the MAX1112.
Reading out digital data The 8-bit converted digital data is brought out of the MAXll 12 via th O · · I negativ~ge pulse to the SCLK pin, the 8-bit digital data is read b' e 00! pm usmg SCLK. As we app Ya first. The SSTRB goes high to indicate that the conversion . . . ou I one It a tune with the MSB (07) commg oot SSTRB goes high, the second falling edge of SCLK produces :et•sh~d. According to the MAXI112 data sheet, "afttf we ne«l 9 pulses to gel data out. To bring data out CS mus t be SB of c~nverled data at the DO
•!
cs
MAX1112 lnternaJ Clock M Reading Data ADC ,,. Odpe Timing Oiagr~m 8, ,e rorn MAxt 112
SCLJ< _ ___,
340
Tli1: sos1Micao
CONTRQ
-
..~u~
LLER AND EMBEDDED 5y::,1.,.-
'
4
r,1-
llit
,ut
,.
IIUl
rw
dt,
'(1,e following is Assembly code for reading o ut d igita l da ta in the MAXI 112:
BIT BI T BI T BIT
cs SCLK DIN OOUT SETB CLR SETB ACALL CLR ACALL CLR MOV R2: 56TB ACALL CLR ACALL MOV RLC
P2.0 P2. l P2.2 P2 . 3
OOUT cs SCLK DELAY SCLK DLELAY
;make it an input
;CS=O ;need delay for DS89C4XO ;first H• tO• L ; read da t a out on 2ND H- to-L
A
R3,#B; SCLK; DELAY SCLK DELAY; C,DOUT A
R3 ,H2 cs Pl, A
DJNZ
SETB MOV
;need delay for DS89C4x0 ;H-to-L pulse to get bit out ;move bit to CY flag ;bring in the bit ;repeat for all B bits ;CS=l ; send converted data to Pl
/IC code for r eading data in MAX1112 Uncl ude sbit cs = p2•0; sbit SCLK • P2 .l; sbit DIN s P2"2; sbit DOUT • P2.3 ; sbi t LSBRA = Acc•o , void main (void) { unsigned char x; CS =O; SCLK•l ; Delay () ; SCLK=O ; Delay () ; for( x •O ; x<8; x++ )
//select maxl ll2 //an ext ra H-to- L pul se
//get a l l 8 bi ts
{ SCLK=l; Delay () ; SCLK: 0; Del ay() LSBRA=OOUT; ACC • ACC << l;
l CS•l;
Pl•ACC;
//bring i n b i t from OOUT / /pin to DO of Reg A //keep shi ft i ng data //for all a bits //deselect AOC //display data on Pl
l ~ . DAC, AND SENSOR INTIRPACING
Hl
I MAX1112 program In Assem bly ·Tl>
fc>.10' >09
,r......... •
Ao
t.be
..
DIN DOUT
BIT BIT BIT BIT
ORG
OH
CS SCU:
,
M)C
progr... se~ec~•
P2 . 0 P2. I P2 . 2 P2. 3
,aending tn control HAUis HOV HOV
1 •
• Hl 1
CLR RLC MOV
CS A
D111.c
SCLl' CLR ACALL DELAY
'
SETB
SCLK
AC.ALL O&LAY OJNZ R3,Hl
SETB
CS CLR SCLK S£T8 DOUT ;Reading data out
r
CLR
CS
SETB
SCLI<
ACALL DELAY CLR SCLK ACALL DLELAY MOV RJ,#8 H2 :
SBTB
;chanllel 1 •• load count
A, •9EH R3. 1 8
SCLK
ACALL DELAY CLR SCLK ACALL DELAY; MOV C, DOUT
RLC
A
OJNZ SET& MOV SJMP
RJ,H2 CS Pl,A MAlN
,cs-o
;give bit: to CY •send bit tO D1N '.1ow SCLK for L·H pulse • ;delay •· latch data . 1 delay trepea t for all 8 bits •daaelect AI)C, conv atarts ;SCLK•O during conversion 1111ake it an input 1CS•O
:neod delay for DS89C4x0 ;II.rat R • tO • L :read data out on 2ND H-L I ;
;need delay for DS89C4x0 :H-to-L pulse to gee bit out ,move bit to CY flag ;bring in the bit ;repeat for all 8 bits
:cs.1
;display data on Pl ;keep doing it
MAX1112 program in C //The following program selects the channel and //reads ADC data #include
• 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; Delay(); SCLK• l ; Del ay () ; JI.CC a JI.CC < < 1 ;
l
// send 07 of Reg J\. t o Di n //latch i n t he b i t //next b it //deselect MJ>.)(111 2 //Make sCLK low during conver sion //read the data //an ext ra H- to- L pul se
CS= l; SCLK•O ; CSsO ; SCLK=l; Dela y(); SCLK• O; Delay ();
//ge t all
8
bi ts
for(x s O; x
I
SCLK=l; Delay () ; SCLK=O; Delay () LSBRA=D00T; JI.CC = JI.CC <<
1;
//bri ng i n bi t f rom OOUT //p i n to DO of Reg J\. //keep shi f ting data // for a ll 8 bit s
) CS• l; //deselect ADC Pl • J\.CC; //display data on Pl
}
Review Questions I. In the ADCOS04, the INTR signal is an - - - - {input, output). l. In the ADC0804, to begin conversion, send a(n) pulse to pin _ _ __
3. Which pin of the ADC0804 indicates end-of-conversion? 4. Both the AOCOS04 and ADCOSOS/0809 are -bit converters. 5. Indicate the direction (out, in) for each of the following pins of the ACX:0808/0809. (a) A, B, C {b) SC (c) EOC 6· In the ADC0848, the INTR signal is an (input, output). 7· In the AOC0848, to begin conversion, send a(n) pulse to 8· Which pin of the AOC0848 indicates end-of-conversion? ---19
1lie ADC0848 is a(n)
-bit converter. ~· Tru~or false. While the AOC0848 has 8 pins for Dour• the MAX1112 has only one Door pin. 1 md.kate the number of analog input channels for each of the following ADC chips. l2. (l) ADCoso4 (b) ADC0848 (c) MAX1112 Explain how to select analog input channel for the MAXl112. ~ . DAC, AND SENSOll lNTBllfAONG
I halog converter) to the 8051. Then we demonstrate ..... ON 13 2· DAC INTERFACING SECTI . . . face a DAC (digital-to-an This section wiU show how to inter . DAC. SCO"" using the to generate a sine wave on the r·
•
jI 1 •
--,
•l
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 5 me~ha
MC1408 DAC (or DAC0808)
. . ed tO rent (I ) and by connecting a resistor to the I In the MC1408 (DAC0808), the digital inputs are convedrt db ~: pini; a function of the binary numbers at th~ pin we convert the result to voltage. The total current prov, e Y e 1-• DO'. D7 inputs of the DAC0808 and the reference current (1..,), and is as follows: 07 06 05 04 03 D2 D1 DO) 1~, = I,.. ( 2+4+8+ 16 +32+ 64 + 128 + 256
t
where DO is the LSB, 07 is lhe MSB for the inputs, and I"' is the input current that must be applied to pin 14. The),. current is generally set to 2.0 mA. Figure 13-18 shows the generation of current reference (setting I.. = 2 rnA) by using the standard 5-V power supply and l Kand l.5K-ohm standard resistors. Some DACs also use the zener ctiode (LMJ36), which overcomes any Ouctuation associated with the power supply voltage. Now assuming that I = 2 mA, if all the inputs to the DAC are high, the maximum output current is 1.99 mA (verify this for yourself). "' Ex~mple 13-3 For the circuit of Figure 13-18, find the maximum output ampl"tud f th 1 following program. e o e saw tooth waveform obtained with the (a)
HOV MOV
BACK, INC SJMP
(b)
A,#0011 Pl,A
A BACK
C
MOV RPT: HOV BACK: HOV INC
R0,#6411 A, #OOH Pl,A 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
,
I
r.
l
I.
!E.+E£.
I,,.. =I"' ( 2+4+8+16+32+64+ 128
256
=2 mA X 255/256 =2 X 0.996 = I .99 D\A. V.... = l.99mAx5 K =9.% V
n,e peak amplitude _of the saw tooth waveform is 9.96 V.
8
ib)ln this case, the maxunum value of the digital number is 64 H = 01100100 · I :0.78125 mA {i :3.906 V
w 1·th the same calculation,
..
It
!r
ll
"
...he
,..
+SV DAC0808
8051
RO WR Pl.O 1---
-.i 00
01 02 03 D4 05
+SV Sk
vcc
Vre.f (+)
lk
OUT + Vref (·)
Sk =
06
Pl.7 1---~
ng
Sk
07
O.luFI
TO SCOPE Vout = 0 tolOV
=
ECOMPCN
6), :he
O.luF
-
-12V
Fig,u, IJ..18. 8051 Connection to OAC808
Converting 1.u1 to voltage In OAC0808 Ideally we connect the output pin 1.., to a resistor, convert this current to voltage, and monitor the output on the !Cope. In real life, however, this can cause inaccuracy since the input resistance of the load where it is connected will •lsoaffect the output voltage. For this reason, the ,... current output is isolated by connecting it to an op-amp such as the ill ~ith R." SK ohms for the feedback resistor. Assuming that R = 5K ohms, by changing the binary input, the output 1
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~-
--·~
~Ile. DAC, AND SENSOR. INTE)lfACING
wavefu.u,.
I .
ement of each step is 51. After~
So the mer "5 I 5 "'st. Solution: f r 5 steps. Now 25th next cycle starts. waveform Let us design the staircase tputodrops to zero and e maximum value IS reached. the ou
;
/
.,
I.
CHECK:
'
~
1
START:
'
•
,'
• ()
,,
RPT:
~
/
r ,,
'r
EQU P0.0
SW ORG
OOOOH
SETB
SW
MOV
c,sw
JC
TRI ANG
A,#00 Pl,A MOV ACALL DELAY A,#51 ADD Pl,A MOV ACALL DELAY CJNE A,#255,RPT SJMP CHECK MOV
input port carry ; move SW t~ m to TRIANG ;if SW=l, JU ~he staircase, A=O . this is for ' Pl •·move A to ;delay step ,add 51 to get the next Port 1 ;output value to ;mak e
swan
; delay , f not go to next step ' k · f A=255 · 1 l ,chec i ached maximum va ue . the staircase has re. .
TRIANG: MOV
A,#00
'. h k SW before continuing ,c ec is for the tri angu lar wave, A•O ·this
!NCR:
MOV INC
Pl,A
;output value on Pl
A
CJNB
A,#255,INCR P1,A A
;increment A for upward transition ;check if A•255, if no t k e ep incrementing
DBCR:
MOV DBC SJMP
A,#00,DBCR CHECK
RE'Tl: RE'T2:
MOV
Rl,#2-0
MOV
R2,#200
RPT3:
DJNZ
R2,RPT3 Rl, RPT2 RO, RPTl
CJNB
DELAY:
OJNZ OJNZ RET ENO
,output value on Pl
;decrement A for downward transition ;if A•O,the minimum., step out
:check sw before starting the next cycle ;this delay routine gives a delay 'T'
Generati ng a sine wave To generate a sine wave, we first need a table whose values les between O and 360 degrees. The values for the sine functi represent the magnitude of the sine of ang from -1.0 to +1.0 for 0- to 360-degree angles, Therefore,thetablevaluesareintegernumbersrepresentin : ensures that only integer numbers are output to the DAC ~ t~ vo tage inagn.ttude for the sine of theta. This method the sine values, the voltage magnitudes, and the integer v e SOSl m1crocontr0Uer. Table 13-7 shows the angles, (with 30-degree increments). To generate Table 13-7, we a a ues representing the voltage magnitude for each anglt designed in Figure 13-18). Full-scale output of the DAC. ss~ed the full-scale voltage of 10 y for DAC output (as Therefore, to achieve the fuU-scaJe 10 V output, we use t~: ~cl ieved When all the data inputs of the DAC are high, 0 lowmg equation.
var{
j
s
V... = V + (5 X Sin 0)
V~, of DAC for various angles is calcuJate,:1 and sh . ca.lculations. own in 'l'abJe 13- See t'1e 7 · Example 13-5 for verification c,l
TlfEsos1 l'.ttcRoco 1'1TROLLER AND EMBEDDED SyS1915
.,,. ~ ~
Table 13-7: Angle vs. Voltage Magnitude for Sine Wave v ;\Jig.le 0 (degrees)
Sin 0
-
o
0
V0 . , (Voltage Magnitude) 5 V + (5 V x sin 0)
5
-60
0.866
90
1.0
120
0.866
9.33
0.5
7.5
0
5
.
I}
1 5 Sent to OAC (decuna a u(eVolta e Mag. x 25.6) g ]28 192
238
150 180 210
240
9.33 10
- 0.5
2.5
-0.866
0.669
270
1.0
300
- 0.866
330
o.s
360
0
0 0.669
2.5 5
255
238 192 128
64 17 0 17
64 128
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
AGAIN: llACK :
t<" l'ABLl!:
MOV MOV CLR MOVC MOV I NC OJNZ SJMP ORG DB OB
DPTR,#TABLE R2,#C00NT A A, @A+OPTR Pl ,A OPTR R2,BACI< AGAIN
3 00 128,192,238,255,238, 1 92 ;see Table 13- 7 1 28,64,17,0,17,64,128 ;To get a better looking sine wave, regenerate ;Tabl e 13-7 for 2-degree angles
~t>c, DAC, A.ND SENSOR INTEllfACING
347
I ProgrammIng OAC in C #include sfr Dn'CDATA • Pl; void main() 238,255,
{ unsigned char WAVEVALOE [12) •
V
{12s.192, 12s ,64, ) 23 8 192, ' 64 17,0,17, ,'
unsigned char x; while(l)
'
{ for(x=O;X
I
1 • ,'
{ OACDATA = WAVEVALUE [xJ
• (\ I
l
l
;
l
Volts
10 r
9·8 ' ... 7 •
...
6 . +5 4
...
3· f2 fI .
0
-
'
30
.
I '
'
60
90
I
I
120 150
I
_J
.
'
180 210 240
270
Figure 13-19. Angle vs. Voltage M,gru
I
300 330
360
Degrees
'tudt for Sine Wave
Review Questions (digital, analog) and output is ----(digital analog). 2. In an AOC, input is (digital, analog) and output is (digital, analog). 3. DAC0808 is a(n) ·bit D-to-A converter. 4. (a) The output of DAC0808 is in (eurrent, voltage). (b) True or false. The output of DAC0808 is ideal to drive a motor. 1.
1n a DAC, input is
SECTION 13.3: SENSOR INTERFACING AND SIGNAL CONDITIONING This section wiU show how to interface sensors to the lllicrocontroU . . sors and then diseuss the issue of signal conditioning. Although w er. We examme some popular tempera~-~ discussed in this section axe the same for other types of sensors su~concentrate on temperature sensors, the pnnop
Temperature sensors Transduarsconvert physical data such as temperature light .
as light and pressure sensors. .
on the transducer, the output produced is in the fol"ll'J 'or vo;:ensity,Oow,andspee.j toelectJicalsignals.
~
ge, Cltrrent, resistance, or capacitance. For examplt,
.
I
• I
•
'
ible 13-8: Thermistor f ·sta11ce vs. Temp erature ReSI
Table 13-9: LM34 Temperature Sensor Series Selection Guid e Accuracy
Output_ tOmV/F
Temperature Range
~ r e (C)
Tf (K ohms)
Part Scale
~
29.490
LM34A
~
10.000
LM34
3.893
LM34CA
-50 F to +300 F -50 P to +300 P -40 p to +230 F
1.700
LM34C
-40 F to +230 P
0.817
LM34D
-32 F to +212 F
y9,1 :;.----
~
1ro ;;;1lliMl' l K1e1t2., Digital Electromcs
+2.0 P +3.0 F +2.0 F +3.0F +4.0 F
-
1omV/F
-
10 mV/F lOmV/F
10 mV /F
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 temperatutt change by changing resistance, but its response is not linear, as seen in Table 13-8. The complexity associated with writing software for such nonlinear devices has led many manufacturers to a,arket a linear temperature sensor. Simple and widely used linear temperature sensors include the LM34 and LM35 se,ies from National Semiconductor Corp. They are discussed next.
LM34 and LM35 temperature sensors The sensors of the LM34 series are precision integrated-circuit temperature sensors whose output voltage is Lin· wly proportional to the Fahrenheit temperature. See Table 13·9. The LM34 requires no external calibration since it is internally calibrated. It outputs 10 mV for each degree of Fahrenheit temperature. Table 13-9 is a selection guide for t!ie 1.M34. The LM35 series sensors are precision integrated-circuit temperature sensors whose output voltage is linearly proportional to the Celsius (centigrade) temperature. The LM35 requires no external calibration since it is internally call· brated. It outputs 10 m V for each degree of centigrade temperature. Table 13-10 is the selection guide for the LM35. (For further information see www .national.com.)
Signal conditioning and interfacing the LM35 to the 8051 Signal conditioning is widely used in the world of data acquisition. The most common transducers produce an output in the form of voltage, current, charge, capacitance, ~ resistance. However, we need to convert these signals to voltage in order to send input to. ~n ~-to-~ convert~r: Thls conversion (modification) is commonly called sig.,J co_nd11Jonrng. Signal cond1 tton1ng C3'.' be a current-to-_voltage conversion or a signal !mpli6cation. For example, the thermistor changes resistance with temperature. The change of resistance must be translated into voltages in order to be of any use to an ADC.
Analog world (temperature, pressure, etc.)
Transducer
Signal conditioning
~ble 13-10: LM35 Temperature Sensor Series Selection Guide pill
Temperature Range
Accuracy
Output Scale lOmV/C
L'13sA
55Cto+150C
lM3s
-55 C to +150C
+1.0C +1.5C
-40Cto+UOC
+1.0C
lOmV/C
-40Cto+UOC
+l.SC
lOmV/C
OC to+lOOC
+2.0C
tOmV/C
l.M:J::r ~ ~D
T""""•""" ••nge 1$ In degte<'S c;.lJius.
.\I>(:, 0>.C, AND SENSOR lN'fllFACING
ADC
lOmV/C Microcontrotler Figutt l l-20. Getting Oat,, From the Analog World
349
I
ADCCJ848- Since Look at the case of connecting an LM35 to an O f 2.56 (2'l the Al)C0848 has 8-bit resolution with a maximum degree steps and the LM35 (or LM34) produces 10 mV for of temperature change, we can condition V.. of the le output. to produce a V..,. of 2560 mV (2.56 VJ for full-SC• 6 V for Therefore, in order to produce the full-scale V,.., of Z.5 f the the ADC0848, we need to set V"' = 2.56. This makes V,.., ~ ed AOC:0848 correspond directly to the temperature as monitor by the LM35. See Table 13-11. Figure 13-21 shows the connection of a temperature sensor to the AOC0848. Notice that we use the LM336-2.5 zener diode to fix the voltage across the 10K pot at 2.5 volts. The use of the LM3362.5 should overcome any fluctuations in the power supply.
evezoco848
,,,,
Table 13-11: Temperature vs. v f ADC0848 .., or V • (mV) 1
Temp. (C}
0 10 20
0
1
2
oooooooj--
ooooooi:o-
30 100 300
3
10 30
v,nu
0000001i-0000101;-000111]0-
1 •'
Reading and displaying temperature The following two programs show code for displaying temperature in both Assembly and C. The programs ('Or. respond to Figure 13-21.
I
;Program 13·1
(i
;Assembly code to read cemperature, convert it, :and put it on PO wich some delay lUJ BIT P2. 5 ;RD WR BIT P2.6 ;WR (scart conversion)
(
• r
INTR
BIT P2 . 7
MYDATA
eou
Pl
MOV
Pl,#OFFH
SETS
INTR
BACK: CLR SETS
HERE: JB
CLR
;end-of-conversion ;Pl.O·Pl.7=00·07 of the ADC0848 ;make Pl• input
WR WR
;WR=O ;WR=l L•to-H to start conversion ;wait for end of conversion , conversion finished, enable RD
INTR, Hl:1R8
RD
+5V
8051 ADC0848 P2.5 r---11~ iw
P2.6r--- .i WR PLO i .--1..J 00/MAO OJ/MAJ
02/MA2 D3/MA3 D4/MA4 05
06 Pl.7 ~ - - - J 07 P2.4 t---1..I P2.7 INTR
cs
vcc CHI CH2 CHJ CH4 CHS CH6 CH7 CHS
2.5k
LMJs
or LM34
Vref (+)
AGNO
Set to 2,56V
DGNO Figuro tJ.;n, 8051 Conntdion to ADC0848
POT IOk
.,,,_ and Tompera1..,. S
•nsor
350
Tli
ES0s1 MJC"
...oco..,,,TROLLER ,
AND EMBEDDED svsfPCS
'
.. .. .. ..
...
MOV ACALL ACALL
A,MYDATA CONVERSION DATA_DISPLAY
SETB
RD
;read the data f rom l\DC0848 ;hex-to-ASCII conversion ; display the dat a ;make RD=l f o r next r ound
BACK
SJMP coiNERSION: MOV DIV MOV MOV DI V MOV MOV RET
B,#10 AB
; l east significant byte
R7, B B,#1 0 AB
R6,B RS,A
DATA_DISPLAY MOV ACALL MOV ACALL MOV ACALL
; most significant byte
PO,R7 DELAY PO,R6 DELAY PO , RS 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 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 //make I NTR and i nput // set RD high //sec WR hi gh
MYDATA = OxFF; INTR
=
l ;
RD • l ;
WR = l; while (1)
•
{ WR •
0;
WR • l ;
whil e (INTR ~• l ) ; RD •
0;
val ue • MYOATA; Co nvertAndDisplay(value ) ;
// send WR pulse / /wait for EOC / / send RD pulse / /read value from ADC0848
RD• 1;
I
l
"Oid ConvertAndDisplay (unsigned char value )
I unsigned char x, dl, d2 , d3 ; X• val ue/10;
~Ile. D.\C, AND SENSOR IN11!RfAONG
dl•ValuetlO; d2•><110 dl•>10 PO•dl; MSOelay(2SO); POod2; MSOelay (250); PO•d3; MSOelay (250 l;
/
//LSBYce
//MSByce
I void HSOelay (uneigned int value)
I
~
I
..,
1 • ( ,
unaigned char x,y; for(x•O;x
I
'
~
Review Questions . . circuitry before it is sent to the AOC. b ted to signal condthorung 1. True or folse. The transducer must e connec ( (Fahrenheit, Celsius) temperature. 2. The LMJSprovides mV foreachdegreeo, (Fahrenheit,Celsius) temperature. 3. ThWhe LM34d pro,,•,th 'desv I Aocno:~:~t,fir::iog input is connected to the LM35? 4 y owese e .,o """° . ! 1001' 5. IJ'I Queshon 4, what ,s the temperature 1f the ADC output ts 00 I · I
SUMMARY This chapter showed how to interface real-world devices such as DAC dups, ADC chips, and sensors to the 80Sl Fust, we discussed both pa.rallel and serial ADC chips, then described how to interface them to the 8051 and program 11 in both Assembly and C. Next we explored the DAC chip, and showed how to interface it to the 8051. ln the last sectim we studied sensors We also discussed the relation between the analog world and a digita l device, and described sip conditioning, an essential leature ol data acquisition systems.
PROBLEMS SEcnON 13.1: PARALLEL AND SERIAL ADC I. Write a program segment to generate the start conversion pulse f ADC0804 2. To access the chip, what logic level should be given on the CS r or · Use pin
tne o1AOC:0804?
Pt.O.
3. The ADC0804 1s a bit ADC. 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
151. nit ion
~
\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
1 woo-01 . 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? ll. With a step size of 19.53 mV, what is the analog input voltage i1 all outputs are J? ll With V.,. = 1.28V, find the V~ for the following outputs. (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? 19 iO. ~ t is the step size if REFIN ~ c~nnected to AGND with REFOUT? single-ended mode, which pm IS used for ground reference for CHANO _ CHAN7?
~
AOc:, DAC, ANO SENS0Jl INTl!JD'AONG
I /
SECTION 13.2' DAC!NTERFACING C {Orm using a DA · 51. Write a program to generate a saw tooth wave sin a DAC. . . 52. Write a program to generate a triangular w~ve~orm u gis this considered as an inbuilt DAC for these chips? 53. Some microcontroUers have inbuilt FWM orcu1trY· Why { DAC080854. Find the I for the following inputs. Assume I"'= 2 mA or (a) 10011001 (b) 11001100 (c) JllOtllO (d) 00100010 (e) 00001001 ({) 10001000 fewer) di ·1a1 inputs. 55. To get a smaller step, we need a DAC with (more, gi 56. To get full-scale output what should be the inputs for DAC? SECTION 13.3: SENSOR INTERFACING AND SIGNAL coNDmoNJNG
..,
, .'
I
57. What does it mean when it is said that a given sensor has a linear output? 58. The LM34 sensor produces mv for each degree of temperature. 59. What is signal conditioning? 60. What is the purpose of the LM336 Zener diode around the pot setting the V.., in Figure 13-21?
ANSWERS TO REVIEW QUESTIONS
SECTION 13.1: PARALLEL AND SERIAL ADC 1. Output
2. L-to-H, WR
3. INTR 4. 8 S. (a) all in (b) in (cl out
'I
6. Output 7. L-to-H, WR
8. !NTR 9. 8
10. True 11. (a)I (b)8 (c}S 12. We send the control byte to the DIN p·m one b'11 at a time.
SECTION 13.2: DAC INTERFACTNG 1. Digital' analog. Jn ADC the input · 2. 8 is analog, the output is digit I 3. (a) current (b) true a•
SECTION 13.3·. SENSOR INTERPACING AND SIG
. NALCONDJTIQN]N
I. True
G
2;~~us.
3. 10, Fahrenheit. 4. Since ADC0848 is an 8-blt A
. . degree of temperatur . DC, ,t gives us 256 5. 00111001 = 57, wluch ~ :Uhich m_at_ches the ADC's ::eps, _and 2.56 V/256 m cates 1t 18 57 degrees ep size. - 10 tnV. LlvfJS
·
P~mlO~b·
354
•
·-
CHAPTER14
8051 INTERFACING TO EXTERNAL MEMORY
OBJECTIVES Upon completion of this chapter, you will be able to:
>
> > >
> > > > > >
Contrast and compare various types of semiconductor memories in terms of their capacity, organ· ization, and access time Describe the relationship between the number of memory locations on a chip, the number of data pins, and the chip capacity Define ROM memory and describe its use in 8051-based systems Contrast and compare PROM, EPROM, UV-EPROM, EEPROM, flash memory EPROM, and mask ROM memories Define RAM memory and describe its use in 8051-based systems Contrast and compare SRAM. NV-RAM, checksum byte, and DRAM memories Ust the steps a CPU follows in memory address decoding Explain how to interface ROM with the 8031 / 51 /52 Explain how to use both on-chip and off-chip memory with the 8051/52 Code 8051 Assembly and C programs accessing the 64l<-byte data memory space Show how to acce96 the ll<-byte RAM of the DS89C4x0 in Assembly and C
I
n,enlory. tnSection 14.1 westudysemic:ond
1 . th BOJ1 /51 / 52 to ext~rna 2 address decocting concepts are discu ~ 4 In this chapter we disruSS how to mterface e or ROM. In Section 1 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 ·
Mand
SECTION 14.1: SEMICONDUCTOR MEMORY •
~
'
l
'
·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 . rocessor· ase th CPU d th ""'-'as organization, and access time. In the design of a nucrop . O""ected directly to e an ey a.re thememones 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.
Memory capacity
,
-{J (
'
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. 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 hold 1 bat, 4 bats: 8 bats, or even 16 bits, depending on how it is desi ed ~temally. The number of bits that each location within the memory chip ca Id IS always equal to the number of data pins on U1e chi H . n o inside a memory chip? That do>nends on then be fp.ddow m~ny locations exist I ti ·u,· -r . um ro a ress pUlS 11,e numbe f oca ons w1 ma memory IC always equals 2 t th . ro pins. Therefore, the total number of bits that e powe~ of the number or address number of locations times the number of data b'~moryl ch,~ can store is equal to the i per ocation. To summarize: 1.ocation can
f
a:
I.
2. 3 .
A memory chip contains 2' locations, where x is u, Each location contains IJ bits where IJ is th bee number of address pins. Th . ' e num r of data . e entire chip wiU contain 2• x IJ b'ts h . pins on the chip. and IJ is U,e number of data pins on ~;;;.;;.ex ,s the number of address pins
Speed ·~ dOne of the mos t ·unporta.nt characteristics of a ,~ 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 ' Ill IS activated, and after a .. •s Presented t the data shows up at the data pins Th certain amount of ti o address 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 cona few. nanoseconds to hundreds e access time of memo e ~cmory ch.ip is used m the desi_gn and fabrication roe oseconds, depending o? ~hips vanes frorn The three important memo.J t e IC technoio access bme wilJ be explored extensive! . ctenstics of capaci gy ence for the calculation of memory ch Y tn this chapter. Table organiZation d Strate these concepts. aracter_,stics. Exam I I serves as ' an P es 14-1 and l4- a re(e,. 2 demon. 356
ot~
ch:::· . .
i4-
Table 14-1: Powers of2 X
10
IK
11
2K
12
4K
13
BK
14
16K
l5
32K
16 17
128K
18
256K
19
512K
20
lM 2M
21
22 23
8M
24
t6M
25
32M
I
26 27
128M
t
"rHe 80s1 MicRoco NTRotLER
ANO EMBEOOEO svslVfS
l
'
EJ
.
.
•
chips, while data is organized
tow m~ny address Imes are required for accessing the data 111 the to!lowmg memory 1 bV!t!S in the first l\o\'O cases and as nibbles in U,e last case? ~ find the memory capacity of each chip and the organization. (al ;12 bytes RAM {b) 8 K RAM (c) 8 KROM
..
ty,
Ill•
-
"'es.
>its
11111.
n is
hat
'an
that
5olulion: n,e memory in the first two cases is organized as bytes. (~\ 512 = 2•. So 9 address lines are required . 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 .
(cl Whether it is RAM or ROM, the calculation is U,e same. 8 K = 2' x 2 1• = 2" . Hence 13 address lines are needed. Data is organized as 4 bits. The memory capacity = 2u x 4 = 32,768 bits. The organization is 8 K x 4.
f2
Example 14-2
--
Is it possible to realize a memory of 256 x 8 bytes by using chips of 256 x 4 bytes?
-
2'
K
:K
-
Solution: 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-2
RAM-I A0-A7
256x4
DO-DJ
AO-A7
2S6x4
AO· A7
04-D7
ROM (read-only memory) <>u!OM is a type of memory that does not lose its contents when the power is turned off For this
ROM 15 -
EPR,o 11,mvo/atrlt memory. There are different types of read-only memory such as PROM EPRO~~~ROM also M, and mask ROM. Each is explained below. ' ' • , flash
!osi INTERFACING TO EXTERNAL MEMORY
357
I
. . In other words, ~ROM is a user-proo,._ burn information ITTto. arruned by blowing the fuses. If lhe'/:i~ 0 th kind of ROM that the userc.ITT fuse. PROM is P~ ~ ternal fuses are blown permanently ~PROM refers to e M th re eJCJSts a d ince ,ts U1 M l all d b . ·~ ' F every bit of the PRO , e be discarde 5 .,.,.,.mming RO , a soc e urning RO).f ma~le memoedry .. ~r PROM is wrong, that PROM must ,,..ramrnable). Proi;,•~•• matton burn in o OTP (one-tiJJ1e pr~o er PROM is also referred to as ROM prograoun · th.LS re'"hn ~ ' ROM burner or reqwres special equipment caJJed a PROM (programmable ROM) and
/
OTP
and uv-EPROM EPROM (erasable programmable ROM) f PROM after it is bum~d. In EPROM, one can O
. h n es in the contents 'all necessary dunng development of the EPROM was invented to allow m~ktng 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~'. . 1·ts contents can . v,~ ototype of a microprocessor-base proiec · pr . Th bl "th UV-EPROM is that erasing . let (VV) radiation to erase its contents. uJtravtolet. eonIy pro em w, can shine u 1trav10 F" l 4-l h th . For chips have a window Uuough which the programmerEPROM or simply uv-EPROM. 1gure s ows e pms for this reason, EPROM is also referred to as UV-erasable a UV·EPROM chip. t be taken· T0 UV EPROM chip the following s teps mus . program a • ' . . rom its socket on the system board and place it in EPROM 1. Its contents must be erased. To erase a chip, remove it f . erasure equipment to expose it to UV radiation for 15-20 minutes. ) T b od · OM ch.1 lace it in the ROM burner (programmer · o urn c eordab 2. Program the chip. To program a UV-EPR P: P din th EPROM type. This voltage is referred lo into EPROM, the ROM burner uses 12.5 volts or higher, depen g on e as v,. in the UV-EPROM data sheet. 3. Place the chip back into its socket on the system board.
:,~ls
!
1
.'
1,
I
'•
' r
I
As can be seen from the above steps, not only is there an EPROM programmer (burner), but there is also sep<1rate
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.
~
-:::.
Vpp
Vpp
~
A12 A7 A6 AS A4
A12
A3
A3
A2
A2 Al AO 00 OJ
Al AO 00 01 02 GNC
A7
;5
.,,
N
"
~
A6
A7 A6
AS
AS
A4
A4 A3 A2
Al AO 00
2764
Vpp
I
A12 A7 A6
2 4
A6
AS
5
AS
A4
A4
A3
A3 A2
6 7
A2
8
Al AO 00
9 10
OJ 02
u
~
N
A7
Al AO 00 OJ 02
01 02 02 GNO GNO GNI
GND
Figure 14-1. Pin ConBguration, for 27'°' ROM F•inily
3
11 13
14
28 27 26 25 24 23 22 21 20 19 18 17
16 lS
Vee PCM N.C. AS A9 Al]
~ AlQ
CE 07 06 05 OI
03
.., "
-
N
;s ~
N
00
~ .... N
~
M
Vee
Vee AS
A9
di!
AlO
a
03
Vee A8 A9 All
OE/Vp1 AlO
a
07
06 OS 04
03
Vee PCM A14 A13 Al3 AS AS A9 A9
~ OE
~
AlO AIO
cr 07
06 05 04 03
CE
07 06
05 04 03
358
lliE sos1 Mlcaoc 0 11rraoLL
ER AND EMBEDDED SYSTEMS
E
Table 14-2: Some UV-EPROM Chips
Ill\-
-Part#
vcf
Capacity
Org.
Access
Pins
450 ns
24
25V
2Kx8
lor-
2716
"°'lt.t.
-2732
16K
-
4Kx8
4S0 ns
24
25V
32K 32K
4Kx8
200 ns
24
21 V
2732A-20
24
12.5 VCMOS
4Kx8
450 ns
28
21 V
27C32-1
~
!ht f0r
OM
32K
2764-20
64K
8Kx8
200 ns
64K
8Kx8
200 ns
28
J2.5 V
2764A·20
28
12.5 VCMOS
27C64-12
64K
8Kx8
120 ns
128K
16Kx8
250ns
28
21 V
27128-25
28
12.SVCMOS
For
27C128-12
128K
16Kx8
120ns
'for
256K
32Kx8
250ns
28
12.5 V
27256-25
256K
150 ns
28
12.5 VCMOS
27C256-15
32Kx8
64Kx8
250ns
28
12.5 V
27512-25
512K
64Kx8
150ns
28
12.5 VCMOS
27C512-15
5121<
27C010-15
1024K
t28Kx8
1S0ns
32
12.5 VCMOS
27C020-15 27C040-15
2048K 40961<
256Kx8 5 12Kx8
lSOns
32 32
12.5 VCMOS 12.SVCMOS
,OM
data !d to
1S0ns
arate
otbe
d.
[ that
Eumple14-3
!f*'
Find the number of address and data pins for the chip 27C010-15.
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.
! that
EEPROM (electrlcally erasable programmable ROM) EEPROM has several advantages over EPROM, such as the fact that its method of erasure is electrical and therefore llslant, as opposed to the 20-minute erasure time required for UV-EPROM. In addition, in EEPROM one can select ~hich byte to be erased, in contrast to UV-EPROM, in which the entire contents of ROM are erased. However, the lllainadvantage of EEPROM is that one can program and erase its contents while it is still in the system board. It does ~require physical removal of the memory ~p fron:, tts sock~~- In other words, unlike UY-EPROM, EEPROM does ~require an external erasure and programm.ng dev,ce. To utilize EEPROM fully, the designer must incorporate the Clteuitry to program the EEPROM into the system board. In general, the cost per bit for EEPROM is much higher than
foi W-EPROM.
~lash memory EPROM Since the early 1990s, flash EPROM has become a popular user-programmable memory chip, and for good realclns. Fu-st, lhe erasure of the entire cont~ts takes_ less than a second, or one might say in a flash, hence its name, flash ~ - In addition the erasure method is electrical, and for this reason it is sometimes referred to as flash EEPROM Oavc;d confusion, is commonly called flash memory. The major difference between EEPROM and flash memory ;~
it
~ 11 N'TatPACING TO EXTERNAL MEMORY
359
Table 14-3: Some EEPROM Capacity Pa.rt No.
24
SV
SV
2Kx8
2864A
64K
28C64A·25
64K 256K
1sons
28 28 28
28C256-15
SVCMOS
256K
250ns
28
28C256-25
SJ
250ns
32Kx8
2oons
32
12VCMOS
l28Kx8 256Kx8
tSOns
32 32
12 VCMOS 12VCMOS
28FU10·15 281'020.15
~
Pins
16K
• I
v,,
Speed
250ns
Aash 28f256.20
f
:rg.
EEPROMs 2816A·25
• I 1 I
.,
d f lash ChiPs
256K J024K 2048K
zsons
IS0ns
sv SVCMOS
I ~
10 EEP·ROM, where one can etast trastthe that when £lash memory's contents are erased, the entire_ · dev,'ceiserased,incon entl made .available contents are d.'.v''ded in · to blocis a desired d th section or byte. Although in some nash.memones rec Oas~ memory has no byte erasure option. Because flash EEPROM. widely used to upgrade BIOS ROM an e erasure can be done block. by. block, . . . unl,ke k ton the system board, ·tis 1 ..,, the'l"L, ld memory can be programmed while ti is"' ,ts soc e II I the hard disk as a mass storage me...,urn. uus wou of the PC Some designers believe that Rash memory w\ rep acefuish memory is semiconductor mea,ory with a~ increase Uie perfonnance of the comp~ter ~remendo':,,;~ ~n~: ran eof tens of milliseconds. For this to happen, flash time in the range of JOO ns compared w,th disk ·ust like harJ(tisks. Program/erase cycle refers to the number memory's program/erase cycles must become, edbeiore 1't. becomes unusable. At .this time, the program/erase cycle of times that a chip can be erased and progranun . is 100,000 for flash and EEPROM, 1000 for UV-EPROM, and 1116nite for RAM and disks.
D ( ' •
.[
•:e
r
b
Mask ROM
I•
k Mask ROM refers to a kind of ROM in which the contents are program.med by the JC manufacturer. In other words, it is not a user-programmable ROM. The term mask is used in lC fabrication. Since the process is costly, mask ROM IS used when the needed volume is high (hundreds of thousands) and it is absolutely certain that the contents will nol change. It is common practice to use UV-EPROM or flash for the development phase of a project, and only after lht c?
is
H
RAM (random access memory)
RAM memory is called volalile memory since cutting off the w . RAM is also referred to as RAWM (read and write memory) in po er to the IC resuJts in the loss of data. SometiJJ'tes three types of RAM: static RAM (SRAM), NV-RAM (nonvol;titec~s) t 10 ROM, Which cannot be written to. There are separately. 'and dyna.nuc RAM (DRAM). Each is explained SRAM (static RAM) Storage cells in static RAM memory are made of llip-n their data. This is in contrast to DRAM, discussed below and therefore do not r . . . kee]) each cell reqUtres al feast 6 transistors to build, and the · e Problem With the eq~re refreshing m order t •• th,lt 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,
~
f1
3~
Tl-rE
transistor <:ells pf · us
~~
~ a.
15
recent years, the cells hove e use of CMOS technology has gi,-en
l
fab r¢
te 14-4: Some SRAM and NV-RAM Chips No
.
Org.
Speed
16K
2Kx8
1oons
16K
2Kx8
12ons
16K
2Kx8
tSOns
Capacity
:;.-:-:--
siv\M :::-::-:61161'·1 ::---:-2 61161'· ;...--:' 6116P·3 :..-6116LP·l
--
16K
2Kx8
24 24
tOO ns
Low-powe r CMOS Lo,v-power CMOS
6!16Ll'·2
16K
2Kx8
120ns
24
1116U'·3
2Kx8
150 ns
Low-power CMOS
16K
24
--
CMOS
64K
8Kx8
28
62b!P·l0
tOOns
28
Low-power CMOS
8Kx8
70 ns
-6!256LP-lO
8Kx8
28
Low-power CMOS
64K
120 ns
28
-
32Kx8
tOOns
Low-power CMOS
256K
6!256LP·12
32Kx8
120 ns
28
Low-power CMOS
256K
161<
2Kx8
150 ns
24
64K
8Kx8 32J
lSOns 85 ns
28 28
6161LP·70 6,1(,!U'· t 2
64K
NV-RAM from Dallas Semiconductor
-OOJ220Y-1S0
-l)51225AB-1S0 ~ !230Y-85
256K
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 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.
24 23 A5
.rdlt
NV-RAM (nonvolatile RAM) 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
'aiusl
loit, but when the power is tumed off the contents are not lost. NV-RAM IO!nbines the best of RAM and ROM: the read and write ability of RAM, plus the nonvolatility of ROM. To retain its contents, every NV-RAM chip llllttnaJly is made of the following components:
a,tbr
CMOS CMOS C.\IIOS
24
24
,olds.
::JM ii llnol
v,.
Pins
A4
4
A3 A2 Al AO
5 6 7 8
22 21
20 19 18
17 16 1/01 9 15 1/0 2 10 14 1/0 3 11 13 GNO ....,,__1:::2_ _ _~::....i
Vrt A8 A9
WE OE AIO
cs
1/ 08 1/07 1/06 I/ OS 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 control tircu.itry switches automatically to Its internal power source, the lithium battery. The internal lithium power source is used to retain the NV-RAM contents only when the external power source is off. It must be emphasized that all t ~ of the components above a~e incorporated into a single IC chip, and for this rea"'ri nonvolatile RAM is a very expensive type of RAM as far as cost per bit is concerned. Offsetting the cost, however, fact that it can retain its contents up to ten years after the power has been turned off and allows one to read and in exactly the same way as sRAM. See Table 14-4 for NV-RAM parts made by Dallas Semiconductor.
:!;:
!Qsl lN"rERfACING TO EXTERNAL MEMORY
361
the checksum calculation. The prOCEss Checksum ve system must performuses of ROM corruption is current Of To ensure the integrity of the ROM contents, e ' \ ROM One of the ca . . ROM the checksum proc SUr8', checksum w,Jl detect any corruption of th~ conte;~ti:n. To ~ure da~a inte~~omthe of a series of bytes:: uses either when the system is turned on or dunng op . .xtra byte that J.S tagg t ken data. what is called a checksum byte. The checksum byte e the following steps can be a · To calculate the checksum bvte , of a series of bytes of ata,
byte ROM
end
IS:'
.,.,
Add the bytes together and drop the carries. ks byte which becomes the last byte of the series 2. Take the 2's complement of the total sum, and that is the chec urn ' · . din the checkswt1 byte. The result must be zero. [fit is not To perform the checksum operation, add all the bytes, inclu ~ gclarify these iniportant concepts, see Example 14.J. zero, one or more bytes of data have been changed (corrupted). 0 I.
J V
• I
1
•
,,
DRAM {dynamic RAM) Since the early days of the computer, the need for huge, inexpensive read/ wri te ,~emory has been a major preoccu. pation of computer designers. In 1970, Intel Corporation introduced the first dynarruc ~ (random access memory} Its density (capacity) was !024 bits and it used a capacitor to store each bit. Using a capa_c,tor to store data cuts down the number of transistors needed to build the cell; however, it requires constant refreshing due to leakage. This is in contrast to SRAM (static RAM), whose individual cells are made of flip-flops. Since each bit in SRAM uses a single flipflop. and each flip-flop requires 6 transistors, SRAM has mucli larger memory cells and consequently lower density. The use of capacitors as storage cells in ORAM results in much smaller net memory ceU size. . The •?vantag~ and disadvantages of ORAM memory can be summarized as follows. The major advantages are high density (capacity), cheaper cost per bit, and lower power consumption per bit. The disadvantage is that it must be
• ( I
, • I
'
(] (
'
1
r d
a
h
~
rJ.
II)
t
DI ~l
Example 14-4
Ass~e Ilia! we have 4 bytes of hexadecimal data: 25H, 62H, JFH and 52H (a) Fmd the checksum byte, (b) perform the checksum O a . • · . . 62H has been changed to 22H, show how checksum def:ts ~~~!~data mtegnty, and (c) if the second byte
I!!
II-,
Solution: (a)
25H • 62H • 3 FH 52 • H
118H
(b)
The checksum is cakuJated b firs . The sum is 118H, and dro _Y t adding the bytes. we get 18H. The checksW:1mg ~he carry, of 18H, which is ESH. yte 15 the 2's complement
Perform the checksum operation to ens d . 25H lite ata tn"""'ty Adding the series of b -r,.. · 62 • H must result in zero. Yle_s, ".'eluding the checks + 3 FH are unchan ed This indicates that all th um byte, + 52H g and no byte is corru e bytes
Pied.
+ ESH
(c)
(dropping the carries) If the second byte 62H has been ha 25H c nged to 22H h Adding the series f b • 9 ow how checks : ::.:: shows that the res:t Jtes Ulduding the ch~etects the error. one or more bytes have~'lero, Which ind.i um byte • 52 H + ESH COll'IJpted. cates that
lCOH (dropping
362
llf
Find the checksum byte.
the carry, we get COii.)
Thi
1)6
.
· · 1 hll DRAM ·s 1 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 ~refreShed, and whose contents can be accessed at any time Since 1970, the capacity of DRAM od P . f 641< 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:"", 256M, and the begmrung . swill be rolling off 0 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
~
Mi:1,
~
~ 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~nvol pinS, Using ~e conventional method of data access, the large number of pins defeats the_ purpose of high density s,l sn,all pacl
DRAM organization . 1n the discussion of ROM, we noted that a ll of them have 8 pins for data. This is not the case for DRAM memory chips, which can have xl, x4, x8, or \16organizations. See Example 14-5. In memory chips, the data pins are also called 1/0. 1n some DRAMs there 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.
DlN
2
15
CAS
WE
3
14
DOUT
RAS
4
13
A6
AO A2 Al
5 6 7
u
A3
n
Vee
8
A4 AS A7
Figure 14-3. 256K,c1 DRAM
Table 14-5: Some Widely Used DRAMs Part No.
Speed
Capacity
Org.
4164-15
1S0ns
64K
64Kx1
16
41464-8
S0ns
256K
64Kx4
18
41256-15
1S0ns
256K
256Kxl
16
41256-6
60ns
256K
256Kxl
16
414256-10
lOOns
lM
256Kx1
20
Sl!OOOP-S 514100-7
80 ns
lM 4M
lMxl 4Mxl
18 20
70 ns
AClNC TO EXTERNAL MEMORY
10 9
Pins
dd~ II\ eaCh of
EJWDplt 14-5 I
o,.cu~, the number o p l•l 16lu<4 ORA\1
,
i~
s..-1 a,,de for • 16Kx4 SAAM
!bl
··
AAS~~
illS ,llld 2 pitlS for . they are as.,;ocia.ted only Will . . AO Ab) for the adclreSS P for RAS and CA5 smce 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
Sol5ull'.'e 2" " 16K·
ha,•
• • •
f) I
Review Question.s f l The speed or semiconductor memory is in the range o (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 • 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 13 (a) 11 addre.s, I data SRAM 8 add""5, data ORAM (c) 17 address,SdataSRAf.l 4data ORM1 · (e) 9 address, I data ORAM (I) 9 address,.d r ddress and data for memory chips Wlth the follo,,,,r-5 Find the capacity and number of plns set ""' e or a
~i
3
4
4
orgaruzallon.. M ( ) JMxl DRAM (a) 16Kx4 SRAM (b) 32K..S £PRO, c (d) 256Kx4 SRA'1 (e) &,tKxS EEPR0~1 (I) 1Mx4 ORM1 5. Which of the following tS (are) volollle) OmlW~~ry? (d) NV-RAM !•) EEPRO:>.t (bl SRA.\t (c •
SECTION 14.2: MEMORY ADDRESS DECODING 1n this s«t,on we d.15CU» address deco,bng The CPU provides the address of the data d esired, but it is tht job of the decoding circuitry to locate the selected memory block_ To explore the concept of decoding circuitry, "·e 1ooi.. at ,·anous methods used m decoding the addresses. In tlus discussion we use SRAM or ROM for the sakr" simplicity. \lemoryclups h.a,e one or more pins called CS(chip select), wluch must be activated for lhe memory's (.;()l'ddalSID be acassed. Somebm~ the chip select 1s also referred to as crup enable (CE). In connecting a memory chip to the Cl'll, note the following points.
1. The data bus of the CPU IS ronnected directly to the data pms of the _._, memory uup. 2. Control signals RD (read) and WR (memory write) from the CPU are --• WE (write ~ble) pm, of the memo<) clup, n-spedi,el>· connected to the OE (output enable}""" 3
In the c~ of the address bu<;et,, while the lower bits of the addresses fr . . · a.ddre, 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 N the memory chip. It is the pm that along with 0 clup ~ CS IS acti,atro p. data can be written into or read from t h e ~
l
cs
As can be seen from the data sheets of SRA.\t and RO\i th and b •ct" a.led by the output of the memory decoder N~ ' e CS input of a memo ch . a ~ 11"' 15 11 of the decoder selects a given memory block_ n..,re..; thrrmaUy memories are dh, I d~ . 'P n ~ the outP"t slll\ple logic ,:•to, (b) using the 741.Slltl, or (c) using e ee \\·ays to generate a mto bloc , ( )~ some examples. progrartunable lo.,; ., __ memory block selector. • -""
aJ
-.,.cs. '"""h method is deteribed belaW '""'
07
07
--
AO
< 0
'
<
A12 A13 Al4 A15
00
41(,cS AU
~
Ri'5 WR MEMR MEMW
f~tt Jol,4. Logic G•t• as Oe<:oder
Block Diagram
I
Vee
GND YO YI
A
-
Simple logic gate address decoder
I
I'
0--
Y2 0--
B
Y3 Y4 0-Y5 0-Y6 0--
C
Y7 0--
G1A G28 GI
- '( l l ,
The simplest method of constructing decoding circuitry is the use of a NANO gate. The output of a NAND gate is active low, and the CS pin is also active low, whlch makes them a perfect match. In cases where the CS input is active high, an AND gate must be used. Using a combination of NAND gates and inverters, one can decode any address range. An example of this is shown in Figu.re 14-4, which shows that A15· A12 must beOOll in order to select the chip. This results in the assignment of addresses 3000H to 3FFFH to this memory chlp.
Enable Function Tabl• In UIS Enable Select Cl C2 CB A
XH LX HL HL HL HL HL HL HL HL
OutpulS YO Yl Y2 Y3 Y4 Y5Y6 Y7
XXX HHHHHHHH XXX HHHHHHHH LLL LHHHHHHH LLH HLHHHHHH L HL HHLHHHHH LHH HHHLHHHH HLL HHHHLHHH HLH HHHHH L HH H HL HHHHHH L H HHH HHHHHHH L
list 11'frERFACING TO EXTEllNAL MEMORY
Using the 74LS138 3-8 decoder This is one of the most widely used address decoders. The 3 inputs A, B, and C generate 8 activelow outputs YO· Y7. See Figure 14-5. Each Y output is connected to CS of a memory chip, allowing control of 8 memory blocks by a single 74LS138. ln the 74l.Sl38, where A, B, and C select which output is activated, there are three additional inputs, C2A, C2B, and Cl. G2A and G2B are both active low, and G1 is active high. U any one of the inputs GI, G2A, or G2B is not connected to an address signal (sometimes they an! 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.
,
t,
. I I
:
DO
07
DO
--<
.,., A
A12 Al3 Al4 A15
L•
YO
Y2
Y3 Y4 Y5 Y6
QA ~ GI
GNO Ve<
<
YI
B C
cr, 5E
Vpp
MEMR
Y7
, ',.
4J
0'
Vee
Figure 1~ 74LS138 •• Decoder
I.
Exa.mple 14-6
l
Lookmg at the design in Figure 14-6, find !he address range for the following. (a) Y4, (b) Y2, and (c) Y7.
~
<
Solution: I
(a) The address range for Y4 is calculated as rollows. Al5 Al4 All Al2 All AlO A9 A8 0 I 0 0 0 0 0 0 I 1 0 0 0 l I I
A6
A5
A4
A3
A2
0
0
0
0
0 1
0 1
AS
A7
A6
AS
0
A4
A3
0
0
A2
Al
AO
I
1
0 1
0 1
0 1
0
0
I
I
A7
Al
AO
0 0 1 1 1 1 1 The above shows that lhe range for Y4 is 4000H to 4FFFH. In Figure 14-6, notice that Al5 must be O for the decodff to be achvaled. Y4 will be selected when Al4 Al3 A12 = 100 (4 in binary). The remaining A 11 - AO will be Ofor the lowest address and 1 for the highest address. (bJ The address range for Y2 is 2000H lo 2FFFH.
AlS
0
-
Al4 0
AlJ l
Al2 0
All
AlO
A9
0
0 0 0 0 1 0 I 1 I (c) The address range for Y7 is 7000H to 7FFFH.
1
0 l
AlS 0
AB
A7
A6
0 I
0
AS
A4
0
A3
A2
AO
1
I
0
Al
l
0
0
I
0
1
0 1
0
l
0
Al4
All
1
l
I
I
Al2 1 I
All
AlO
A9
0 1
0
0
1
1
1
Using programmable logic as an address decoder Other widely~ decoders are programmable lo · ch· chif)6 is that they require rAL/CALsortware and ab gic ips such as PAL and GAL h ' . The advantage of these chips is that they can b urner (programmer) wh C 1ps. One d1sadvant.~ge of lhese more ,ersatile. nu,. plus !he fact that p~ anJ t~°t":,mmed for any co~bin:i~~s ~e 74LSJ38 needs neither oft":, 0 address range:., and so are rn they can accommodate more address inputs ave 10 or more inputs c· ·
•n contrast to 6 in the 74138) means th,ll
Review Questions I A g,ven memory block use'! addresses 4000H _?FFPJ; 2. The 74138 ,s a(n) by decoder · How many Kb
1
.
.
y es 15 this memory block? 3"
lliE sos1 MJcaoc
-
ON"fROLLEJt AND EMBEDDED s'Yfl'Od
I
the 7~138 S!"e the status of G2A and G2B for the chip to be enabled. 10 ~ 1/1 the 1; 138 g,ve the s~tus of Gl for the chip to be enabled. ~· Example 14-6, what is the range of addresses assigned to Y5? 10
5ECTION 14.3: 8031151 INTERFACING WITH EXTERNAL ROM AS discussed in Chapter 1 , the 8031 chip is a ROMless version of the 805). In othe r words, it is exactly like any ~ r of the ~ l family such as the 8751 or 89C as far as executing the instructions and features are concerned, but
51 ihaS oo on-chip ROM. Therefore, to make the execute 8051 code, it must be connected to external ROM memory 8031 ~ taininS th~ program cod.e . In this section we look at interfacing the 8031 microcontroller with extemal ROM. Before •-tdiS(USS this topic, o~e might wonder why someone would want to use the 8031 when they co~d buy an 8751, 89C51, Cf [)55000. The reason 1s that all these chlps have a limited amount of on-chip ROM. Therefore, m many systems where t1,ton
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 Pl.2
2
3
39 38
PO.O(AD0) PO.I (AOl)
Pl.3 Pl.4 Pl.5 Pl.6 Pl.7
4
37
J>0.2 (AD2)
5
36 35 34
P0.3 (AD3)
P0.6 (AD6)
10
33 32 31
u
30
ALE/PROG
12
29
PSEN
13
28
P2.7 (A15)
14 15
27
P2.6 (A 14)
26
1'2.5 (A13)
16
25
P2.4 (A12)
17
24
1'2.3 (A 11)
18
23
P2.2 (AIO)
22
P2.I (A9)
21
1'2.0 (AS)
R5T (RXD) P3.0 (TXD) 1'3.1 (INTO) P3.2 (INTI) P3.3 (TO) P3.4 (Tl) P3.5 (WR) P3.6 (RD) 1'3.7 XTAL2 XTALI
~-'~
:.,.-
6 7
8 9
GNO
8031/8051 / 8052
P0.4(AD4) l'0.5 (ADS) l'0.7 (A07) EA/VPP
Flg,,,. l4-7. 8051 Pin Diagram
ilDst INTEAFAO NC T O EXTEJlNAL M EMORY
367
/ ' •,NI.J
v,,•
ll
11
?5'J ,{
' I}
l
1t.lr1•••11
",(J II)
tJI J
7Q
Ill ~I)
('
J.nJbl,
IN
6 lJ, 11:p
J ~noon T•ble (Julpu
._or,uO,
c,
,.,.01.. ~
H
l I I.
If L
H
X
D
Output
H L
II
X
QO
X
-
L
z
~
"
On
-
I I
Al
1'·
i" <.•· JI • 1 I
,~ ,,,
I <'Wff' 1',t \Jdre,.. BH"
I 1''
'"
I \-tt~ Hu,
iutor
)plat
-~
8031/51
EA
RD
WR
(RD) 1'3.7 (WR) 1'3.6 PSEN
PSEN Al5
1'2.7
Upper $-Bit Address Bus
A8
P2.0
,G
ALE
~
AD7
P0.7 PO.O
=
IO
'-lJ
A7
"I<
74LS373
AO
oc
ADO
Lower 8-Bit Address Bus
.,.'-
D7
Data
00
Bus
figure 14-10. D•t•, AddJ:ess, and Control Buses for the 8031 rftv ~ •nd crystal connectwn. see Ouipt
In systems where the external ROM contains the progran1 code, burning the program into ROM leaves the microcontroller chip untouched. This is preferable in some applications due to flexibility. In such applications the software is updated via the serial or parallel ports of the !BM PC. This is especially the case during software development and this method is widely used in many 8051-based trainers and emulators.
On-chip and off-chip code ROM
Ill 6ar
In all our examples of 8051-based systernsso far, we used either the on
dlWI :nphl·
1lee are times that we want to use both of them. ls this possible? The answer is yes. For example, in an 8751 (or 89C51) system "'roukl use the on
GND,
INpin
ilollOI
8031
.r EA
al
P2.7
PO.O
I
I
PSm P2.0 ALE P0.7
Vee
RD WR
P3.7 1'3.6
Al'
=
AIYZ_
1D Q J-<'.
8Kx8
A7
A7 program ROM
AO
AO
74LS373
r
oc -~
Ypp
Al2 2864 AS (2764)
N>
,G
o£
D7 00
07 'LJU
lls,.,.14-U. 8031 Connodlon to Exlfflw Program ROM
'°51 iNT£RFAONG TO EX'J'EllNAL MEMORY
369
,
_, ded .,nto off
""'""msthe 011 -chip · P•..no-ram · ~
'""Y·:U':.::
~r:;
.,.,
(etch:
t
Jr
.~
' \I
' \I
I I'
•
• I'
'. f
8052 8051
8031/51
v
,.
0000
I
OW) [
OFFF
••
J
OOOo
Qn-dtip 4K
Off
•'
-
I
•
Off Chip
Off
Chip
-
FFFF'.__ _ _1
Chip
-
On-chip SK
IFFl'~===j 2000
1000
'' l
.'
EA= Vee
EA=CND
•
EA- Vee
-
FFFf- 'L-----'I
1
FFF-;-;-L----
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. (b) EA = v with both on-chip and off-chip ROM for the 8751. (c) EA= with both on-chip and off-chip ROM for the 8752.
v:
Solution:
ingc I«)'
(a) When EA = 0, the EA pin is strapped to GND, and all program fetches are directed to external memory regardless of whether or not the 8751 has some on-chip ROM for program code. This external ROM can be as high as 64K bytes with address space of 0000 - FFl'l'H. In this case an 8751 (89C51) is the same as the 8031 system. (b) With the8751 (89CS~)system ~vhe~ EA= Vcc• the microcontroller fetches the program code of addresses 0000
• OFFPH from on-chip ROM since it has 41< bytes of on-chip program ROM and any fetches from addresses 1000H • FFPPH are directed to external ROM. (c) With the 8752 (89C5~) system '.vhere EA" VCt! the rnkrocontroller fetches the ro ram code of addresses 0000 - lFFFH from on-chip ROM since 1t has SK bytes of on-chip progra ROM P dg f fr dd-2000H - PFFl'H are directed to external RO}-!. m an any etches om a ,.,.....
ElCllmpte 14-8 Discuss the role of the PSEN pin in accessing on-chip and ff . o -chip program codes. Solution: In the process of fetching the intemal on..:hip pro
However, l'SEN is used for all external Program fetgram <:ode the PSEN · . the CE pin of the program ROM. ches. In Figure 14-JJ P~ 15 not used and is never activated· • notice that PSEN is also used to activate 370
TlfE 8051 MICRoco
-
N°fROLLER AND EMBEDDED svsTOfS
Re~ieW Questions 1, ;: l
=
_
'
~
If EA GND, in_d icate from what source the program code is fetched. Ji EA= Vee' indicate f~m what source the program code is fetched. l\'hich port of the 8051 ,s used for address/data multiplexing? Which port of the 8051 provides DO - 07? Which port of the 8051 provides AO - A7? ;l'hich port of the 8051 provides AS - A15? . rrue or false. In accessing extemaUy stored program code, the PSEN signal is always activated.
5ECTION 14.4: 8051 DATA MEMORY SPACE So far in this book all our discussion about memory space has involved program code. We have stated that 5~e prod gram counter in the 8051 is 16--bit and therefore can access up to 641< bytes of program code. ln Chapter 6, we owe Joi< to place data in the code space and used the instruction "MOVC A, @A+DPTR" to get the data. The ~OVC 1I1:5truc· titm. where C stands for code, indicates that data is located in the code space of the 8051. 1n the 8051 fa,ruly there ,s also ,separate data memory space. 1n this section we describe the data memory space of the 8051 and show how to access it in Assembly.
Data memory space In addition to its code space, the 8051 family also has 64K bytes of data memory space. Tn other words, the 8051 has
12SKbytesofaddress space of which 64K bytes a reset aside for program code and the other 64K bytes are set aside for ci,ta. Program space is accessed using the program counter (PC) to locate and fetch instructions, but the data memory space is accessed using the DPTR register and an instruction called MOVX, where X stands for external (meaning that the data memory space must be implemented externally).
External ROM for data . "To connect the 8031/51 to external ROM containing data, we use RD (pin P3.7). See Figure 14-13. Notice the role of signals PSEN and RD. For the ROM containing the program code, PSEN is used to fetch the code. For the ROM containing data, the RD signal is used to fetch the data. To access the external data memory space we must use the instruction MOVX as described next.
8051
WR
P3.6 !'SEN
I
P2.7
A12
P2.0
,C
ALE l'0.7
l'O.O
Vee
R~
1'3.7
AOL
' Dtif""<, ~
,..,.,..
A15 Al' A13 •
.
p- al
I Vpp
OE
A12
AS
8Kx8
A7
ROM
Data
1
74LS373
Auv
oc
AO
AO
07
DO
_.._ 07
DO rig,.,.1
4-13. 8051 Connection to External Data ROM
!os11•- 1 "
ERFAClNC TO EXTERNAL MEMORY
371
data ROM 1ocahons s h·ch does not have on-chip ROM) sti\11. 1 "SA,\i" has been burned in the extern• tions of an 8031 (w The wotd . 1 data RAM Joe• Wnte a program to read this data in O rng from 60 H . source location) Solution: ints to urst ·DPTRs4lOOH (po · on tOOOH MOV DPTR, #4100H • 1ocat1 ;get •s• from RAM location 60H MOVX A,41DPTR ,move it to dat~ to next location) MOV 60H, A ;OPTR;4l01H (points Example 14-9
, .' •
'
t•
1
INC MOVX
DPTR A,@DPTR
MOV
6lfl, A
INC MOVX
DPTR A,SDPTR
MOV
62H, A
END b ,med in on-chip program memory. Here, the data is This is• modification of Example !Hi. There, the data was ' burned in external data ROM. J ROM, th e ·nst ·s MOVX. · I ruct·on 1 1 The ·lllStructJons to access on
(
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 RAMTBLE COUNT
BOU SQU EQU MOV
BACK,
MOV MOV MOVX MOV INC INC DJN
OOOH 30H
10 DPTR, #TABLE RS,#COUNT R0,#RAl1TBLE A,@DPTR 41RO,A DPTR RO RS,BACK
;pointer to external data ;counter ;pointer to internal RAM ;get byte from external mem ;store it in internal RAM ;next data location :next. RAM locati on :unt1l all are read
MOVX In s tru ction MOVX is a widely used instruction aUowin berof the8051 family is usect To bring extem!i<'>leSs toextemaldata memo instruction will read the byte of data pointed ,0 i stored data into the CPU ry ~-pace. This is true regardless of which mernJargedata space is needed, the look-up table meth~~t~ DPTR and sto' '~e.use the instruction "MOVX A @OP'J'R". ThiS Contrast Example 14-10 with Example 5-8 from IS widely ~ . See E::: It m the accumulator. In a lk~tions where a gram code space of the 8051 and we used the . ~apter 5. In that lllples 14-9 and 14-lO fo t~p f MOVX. A+DPTR" and "MOVX A, 41DPTR" look ver s· mstruction "MOVc" t example the table el r e use O • data in the data space of the micr Y •nular, one is used o atce$ each el ements are stored m the proI0 get data ·5 h o-contro1 ler. ement. Although both "MOVC A,• int ecode ..i space and the other is used to to·· 372
TlfEsos1 MI
CRoco NTRo
--
LLER AND EMBEDDED svsra,tS
,
,.
1"
j
£tl)l'Ple 14-11
OM nd BK bytes of data ROM. a
Sb<>"' the design of an 8031-based system with BK bytes of program R
ROM PSEN is used to ch ROM Fo r prog ram , F,gure 14-14 shows the design. Notice the rote of PSEN and RD in ea hil is activated by a s imple decoder. ~ vale both OE and CE. For data ROM, w e use RD to activate OE, w · e
5olution:
.
CE
8031 EA
.
P3.7 P3.6
~
PSEN
Iii
AS
Vpp
CE
CE A l2
A12 8Kic8 Dal• ROM
G
oJ; Vp p
8Kx8 Program ROM
DQ
P0.7
PO.O
i5E
AtS Al Al
P2.7
P2.0 A LE
Vee.
Ve<:
74LS373 ADO
AO
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 torage of data, any additional memory space for read/write data must be implemented extemally. This is discussed further next.
External data RAM To connect the 8051 to an external SRAM, we must use both RD (P3.7) and WR (P3.6). This is s hown in Figure 14-15.
MOVX instruction for external RAM data In writing data to external data RAM, we use the instruction " MOVX @DPTR, A" where the contents of regis ter A ~ Written 10 e xternal RAM whose address is pointed to by the DPTR regis ter. This has many applications, especially where we are collecting a large number of bytes of data. ln s uch a pplications, as we collect data we must s tore them in NV-RAM so that when power is lost we do not lose the data. See Example 14-12 and Figure 14-15.
Ex.mpte 14-U (a) In Figure 14-15, what is the address space allocated to the data RAM? tb) Write a program to tranafff an array of 10 bytes stored In locations starting from 8000 H in this RAM to locations starting from 9000 H .
Solution:
(•) The data add,- epace Is 8000 H to BFFF H.
II05t INTERFACING TO EXTERNAL MEMORY
373
d lhe destination array. The DPTR is used as th Here two arrays have to be addressed - i.e. the sourc~ a~Yt ~e first array, the current pointing address of~ powter to address both arrays. When the ~PTR as poUl~g ~ewiSe, when the DPTR is pointing to lhe second
second array is temporarily stored in registers Rl an~ · rarily pushed on the stack. array, the current powhng address of the first array 1s ternPo
.,.,
,
ARRAYl ARRAY2 COUNT
,,-.., ,
,,'
'
START:
!
(J ( >
I
EQU SQU SQU ORG MOV MOV
BOOOH 9000H 10 0 R2,#COUNT DPTR, #ARRAY2
MOV MOV MOV MOVX INC PUSH PUSH MOV MOV MOVX INC MOV MOV POP POP OJNZ
RO,DPL Rl,DPH DPTR, ~ARRAYl A,3DPTR DPTR DPH DPL DPH,Rl OPL,RO 3DPTR,A DPTR RO,OPL Rl,OPH DPL DPH R2 ,START
;the number of bytes (•10) is stored in R2 ;DPTR has the first address of the second array ;i.e. destination array ;save the destination pointer in RO and Rl ;OPTR points to the source array ;move the source co A ;increment DPTR for next operation ;push DPTR onto stack ;get the destination address in DPTR ;source to destination transfer ; increment OPTR to point to next des ti na t.ion ·l b
'ower yte of destination address in RO ;upper byte of destination address i n Rl ;get back source pointer from st k I repeat until the count is zero ac
END
8051
P3.7 P3.6 PSEN P2.7
...
ffi
WR I
Al?
Al:;
j)-
I
CE
WE
OE
A 13
Al2
P2.0 ALI!
,c AD7
l'0.7
ro.o
1.J',,A 15_ A14 v
,
A8
16Kx8
,D Qr-<"
Data RAM
_A7
74LS373
oc
-AO
AO 07
--
DO
~
07 fig11tt 14-15. 8051 Connoction lo Ext•m.J 0
•t• RAM
Do
374.
ROcoNTROLLER
ANO EMBEDDED svs'l'EftlS
•
·ogle external ROM for code and data
I ROM chip · This single , 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 t> ." to provide both program code space and data s pace, we use an A 8 in Figure 14-16. ~ SI
:,1'
. . . E ample 14-13. 8031 system with ROM and RAM . tern This ,s shown m x, ~ are times that we need program ROM, data ROM, and data RAM ma sys ·
8031
+
EA
R
..~.7
WR
1'3.6
PSEN
l
A tS
P2.7 A
P2.0
1'0,0
I AIS
0
o)-
74LS373 Auu
QC
~-
Vpp
64Kx8 ROM
,G A07
OE
A t3
1'0
ALE
J'0.7
Vee
'
Program/
A7
Data AO
AO
07 DO CE
-b 07
Agvrt 14-16. A Single ROM for Both Progr•m and Data
E.umple 14-13
~rer to Figure 14-17.
11] Find thit 1ddreH lf)AC1t of thit d11A RAM, d1t1 ROM and program ROM . /bi Writlt I progrem to 1aeM I byte of datA which It In d1t1 ROM, dlvldit it by 2, and 11v1t !hit quotient in the data
RAM
lrJ R..writlt lhlf progr•m for the cue !NI I~ data bytlt 11 in program ROM. So111t1on:
!.i/ ltw addreH lbw A15 and Al' of the dalA RAM have to bit 10 for thlt chip to bit w lected. Hence, its addrn& 1pace 11 1000 0000 0000 0000 to 1011 1111 1111 1111 .
I~ IIOOOU to BFFfH , for tlw d•IA ROM, A15 and Al' hive to bit 00 for th" chip to bit wlected. I t.-nce, lta lddre9 IIJIII" It from 0000 0000 OCXXl 0000 to 0011 1111 1111 1111 , l e OOOOH to 3FFfH For IN prog,am ROM, lhtaddNM 1111ft Al, and A151NP not 1111d In add,-decodlng. l.1t. A15 and A14 ""'don't a,._ How.vlf, If W.CONlder Al5 and Al4110, th.1dd,- 1pt1C1 la from OOOOH to 3FFFH. But, It ~
lt;\I INHAfAC ING 101'.XJ'f.RNAL Ml!MORV
375
,
.... ,, A M because different instn,ictions are ,"
rdata RO M or "'""
"''ied
does not create a clash with the addreSS space o to access code space and data space, n5fer the quotient to the fizst t . d ta .ROM and let us 1ra C>cabon (b) I.kt the required data be in the first locabon in a ,n data RAM. Note that MOVX instrucilon is used to access data ROM- · n oooOH of program ORG OOOOH ; load t:he program l ;memory . ; let OPTR poinc co data 1ocac1on DPTR,#OOOOH MOV MOVX A,eDPTR B,#02 MOV AB DIV DPTR,#8000H MOV MOVX ODPTR,A END (c) Assume that the required data has already been burnt into location 0100H of program ROM. Here the MOVC instruction is to be used to access data from program R0,\4.
( l
, .' ..
•
('
'
'
'
•
'
'
ORG MOV CLR MOVC MOV DIV MOV MOV X
t.l ,I
OOOOH DPTR,#OlOOH A A.A+@DPTR B, #02
/
;let DPTR poinc co data location
AB
DPTR,#SOOOR 41DPTR,A
ENO
8031
EA
R:°j~-===---- ---,--- --- WR
P3.7 P3.6
PSEN"i--~----;~~--t-+-~~~~--~ I
. ...
74LS138
1'2.61----Al 1'2.71---AJS
Vee
1---1C2B Y G2A GI
-
1'2.0
CE WEm;
A13 ~A~l~~~~~~V~cc~ AS
~
ALE t-_:_--C
CE
POO
F.
agure 14-17. 8031 Connection to External p
~I ~
_
111
OEVpp
CE
~~Al3
Data RAM
A7
I 'OE Vpp
-
16Kx8
Vcr.
16I
~§~AJ3 16Kx8 Pro~am
Data ROM AO
~~! ~
ROM AO
.___
_:D7DO
00
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 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
1;eS051
e
S051
To
P3.7
1'3.6
WR
r A17 A16 A15
Pl.2 Pl. l
PLO
I
I
cr m
:JE
1'2.7 256Kx8
1'2.0
ALE P0.7
PO.O
AD7
ADO
Data
AS
,c
NV-RAM A7
DO~ 74LS373
oc
AO
AO
07
00
_.._ D7
DO f,g,,rr 14-18.8051 Accessing 256KxS External NV-RAM
Eumplt 14-14 In a certain application, we need 2561< bytes of NV-RAM to store data collected by an 8051 microcontroller. (a) Show the connection of an 8051 to a single 256Kx8 NV-RAM chip. (b) Show how various blocks of this single chip ~ accessed.
Solution: (a) The 256Kx8 NV-RAM has 18 address pins (AO-Al7) and 8 dJta lines. As shown in Figure 1-i-18, AO- A15 go directly to the memory chip while A16 and A17 are controlled by Pl.O and Pl.1. respectively. Also notice that chip select of external RAM is connected to Pl.2 of the 8051. (b) The 256K bytes of memory are divided into four blocks, and each block is accessed as follows:
Chip ~lect Pl. 2 O 0 0 0 l
A 17 Pl ,l O 0 1 1 x
A16 Pl .O O l 0 1 x
Block a ddreee apac e
OOOOOH-OFFFFH lOOOOH-lFFFFH 20000H·2FFFFH 30000H-3FFFFH External RAM disabled
For cumple, to access the 20000H - 2FPFFH address space we need the following:
~l lNTERFACLNC TO EXTERNAL MEMORY
377
Pl.2
CLR
/
HOV CLR
DP'!'R,#0
SETB HOV l!OVX
Pl .1
Pl.O
•
•• •
fl
f:~
A,SBUF IDPTR, A
DPTR
INC
..
•
al RAM -~1e extern y block ;en..., of 64K memor ·start ' ;A16c0 OOOH block ;A17cl for 20m serial port ,get data block 20000H addr. ve data 1 I Sa , n ;nex t 1ocac10
ACCESSING 1K-BYTE SRAM IN ASSEMBLY
. ing the MOVX instruction. Next,weWilJ his accessible by us oiven ll1 · """'· h' Th DS89C4x0 chip family has IK byte of SRAM, w ,c The c versions of th ese programs are o· show :ow lo access this l K byte of SRAM in Assembly language . next section .
• •
'
>
f
1K Byte of SRAM In DS89C4x0
.
eofSRAM embedded into the chip. This is in add.
1;;
The DS89C4x0 family (DS89C420/30/4~/50)com:s with !K the DS89C4x0. This l K byte (1KB) of SRAM can 5 5 2 80 ition to the 256 bytes of RAM that comes :"'th any " ~p ';;. ~eecl to store data va riables. Another case in which be very useful in many appLications, espec,aUy for C comp crs • 1 this 1K-byte RAM can be put to.great ) d . d f the 8051 family. To access this lK byte of SRAM use is the tiny RIOS (real time operating systems es,gne or . . b f RAM · in the DS89C4x0 chip, we mu,t use the MOVX instruction. Notice that while accessing the 256. y tes O ll1 the 8052, we use either direct or register-indirect addressing modes, but to access the d~ta stored m this 1KB of RAM, we must use the MOVX instruction. On power-on reset, the access to the l KB SRAi:1 1s blocked. 1n ? rder to ac~s 1~ we must enable some bits in lhe SFR registers called PMR (power management register). The PMR ts an SFR reg15ter and is located at address C4H. The SPR location C4.H is one of the reserved byte spaces o f the 8052 used by Dallas Semiconductor for PMR. The PMR bits related to the IKB SRAM are shown in Figure 14-19. Examine the information in Figure 14-19 very carefully. The IKB SRAM is not accessible upon reset. This is the default state that allows us to interface the DS89C4x0 chip to external data memory, just like any member of the 8051/52 family. To access the 1KB SRAM, we must make PMR bits DEMO = 1and DMEl = O. In that case, any MOVX address of 0000 - 03FFH will go ID the on-chip IKB SRAM and all other addresses are directed to the external data memory. That means that if we want IO add external data memory to the DS89C:4x0 chip we must designate it as 0400- FFFFH since the first lK-byte space is already taken by the IKB SRAM, assum~g that the proper bits in the PMR are enabled. Again, it must be emphasized !h•t upo.n reset, access to the 1KB SRAM is blocked, and can be accessed only if we set the ro er bits in the PMR reg· !Ster. Th,s must be done every time we power up the DS89C4x0.based system Stud th P fp h we access this IKB SRAM. · Y e next ew examples to see ow 1
0
DM£1 OMEO 0
0
0
0
0
o
I DME1 I DMEoJ
DATAMtMORY ADDRESS RANGE MEMORY ACCESS
0000-FFFFH Ex(temal Data Memory (Default)
X
0000 ·03FPH 0400 • FFFFH
After every Reset) lnte""1] SRAM D External D ala Memory •ta Memory
0
Reserved
Powtr Managemtnt Rtglator (PMR) l ,>d •t addn..,. C41I. s •n SPR In the DS8gc
4.xo family and is locatflguro 14-19, PMR Rtgltlor Bit, for lf<•bytt SRAM of OS 378 T HE 8051 MIC:Roco
-
NTROLLE
R AND EMBEDDED SYST£~5
inldd-
~an
lwhich
SRAM I in 1hr I RAM.
cc:as it
regiP'I' I Dalin rmalioll nus to the llCB ill go to w8111IO
._,_
If*""
~420/ 30
16KB 32KB 64KB
~
-
~50
256B 256B 256B
Example 14-15
JKB 1KB
. con(b) multi ly l\vo by tes stored ,n Writ.. a progra m to (a) enable access to the 1 KB SRAM of the DS89C4XO, ti . SRAM and also o utput the securtve locations in the SRAM and (c) s to re the result in the ne,ct two toca ons u, result bytes to port Oand port 1.
le
Solution:
DATA ORG MOV SETB MOV MOV MOVX MOV I NC MOVX MUL l NC MOVX MOV INC MOV MOVX MOV END
EOU 00001! 0 A, OC4H ACC.0 OC4H , A OPTR,#DATA A,
;read PMR register ;make DMEO~l ; e nable l K8 SRAM
AB
OPTR .
!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 ORG MOV SETB
MOV
CLR MOV
EQO 0400H 0
A, OC411 ACC.0 OC4H,A
C OPTR, #DATA
address of LSB of first number ;read PMR register ;make DMEO•l ;enable l KB SRAM ; clear C 1 let OPTR point to LSB of the 16 bit word -
8051 INTERFACING TO EXTERNAL M EMORY
379
MOVX ADD MOY
A,@DPTR A, 45H 47H,A
!NC
DPTR
l\DDC
MOV
A,46H 48H,A
cLR
A
MOVX A••DPTR
,
.r
·-ove LSB to A in ~•M location 45H ,,., byte ,.,... .. ;add it to the location 4 7H ,move sum to RAM int to upper byte '.increment DPTR cop~ • co ,.. ,move uppel-' byte , R)IM 1ocatiOD 46H • the byte 1n ;add it coco RAM 1ocation 48R ,move sum ; clear A
ADDC A, ijOO MOV 4 9H. A
; AsA+O+C tion 48H ; move A into RAM loca . dh the carry bit holding the extra bit. This carry is
'
I
The result of adding two 16-bit numbers may be 17 bits, '" . 49H mo"ed in to A, which is then transferred to internal RAM location ·
• ' I
•
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 COUNT RAM_l\DDR ORG ACALL MOY
r
SETI!
MOV ACl\LL MOV MOV MOV Sl!TB
ACl\LL SJMP COPY
-·MOV
Rl,
EQU 400H EQU 5 EQU 40H
;code data
;messsage size ;8051 internal RAM address
0
COPY l l\,OC4R ACC.O OC4H,A COPY_2 TMOD,#20H THl,#-3 SCON,#SOH TRl COPY_COM $
;copy from code ROM to internal RAM :read PMR of DS89C4x0 :enable PMR bit for lK SRAM ;write it to PMR of DS89C4x0 ;copy from internal RAM to 1KB SRAM ;set up serial port ;9600 baud rate ,copy from 1KB SRAM . ;stay here to ser1al port
l ·
MOV MOV CLR MOVC MOV INC INC DJNZ
l l. l
i.
' 7.
DPTR, #DATA l\DDR RO • #RAM l\DDR R2,#COONT
s
A
A,eA+DPTR eRO ,l\
h 4
DPTR
RO R2,l!l
'
RET
;-----transfer data f COPY_2: rom internal RAM HOV DPTR,#0 to external 1DS89C4xo lk!I ad(h,
380
J
'I RAM
THE sos
lM1cRoco
NTROLLER
l ANO EMBEDDED svs,VCS
•
I
MOV MOV MOV
112:
MOVX INC INC DJNZ RBT
RO, #RAM_!>.DDR R2,IICOUNT A, 4DRO ®DPTR, A DPTR RO R2,H2
internal RAM ;get a byte from sRAM of DS89C4x0 ;store it in 1KB
.~~~--data transfer from lKB SRAM to serial port roPY_COM:
MOV MOV H3:
M()VX
!>.CALL INC
DJNZ
DPTR,#0 R2, #COUNT !>.,@DPTR SERIAL OPTR R2,H3
;OS89C4XO 1KB addr 1KB sRAM space ;get a byte from ;send it co com pore
RET ·-----send data to serial port
•
Sl!RIAL: H4:
MOV
SBUF,!>.
JNB
Tl,H4
CLR
TI
RET
--~data in code space ORG !l'll!YTE: END
400H
OB
"HELLO"
Review Questions 1. The 8051 has a total of_ bytes of memory space for both progran, code and data. 2. All the data memory space of the 8051 is (intemal, external). 3. True or false. In the 8051, program code must be read-only memory.
4 True or false. In the 8051, data memory can be read or write n,emory.
5. Explain the role of pins PSEN. RD, a.nd WR in accessing extemal memory. 6. True or false. Every 8051 chip comes with 1KB of SRAM. 7. True or false. Upan reset, access to the 1KB SRAM of the DS89C4x0 is blocked.
SECTION 14.5: ACCESSING EXTERNAL DATA MEMORY IN 8051 C In Chapter 7, we showed how to place fixed data into the code space using 8051 C. In that chapter we also sho,ved how to access fixed data stored in the code space of the 8051 family. ln this section we show how to access the external data space of the 8051 family using C langu.age. To access the external data space (RAM or ROM) of the 8051 using C, We use XBYTE(locl where loc is an address m the range of 0000- FFFPH. Example 14-18 shows how to write some data lo t'l(lemal RAM addresses starting at 0. Notice that the XBYTE function is part of the absacc.h header file. Examine Examples 14-19 and 14-20 to gain some mastery of accessing extemal data memory using C.
Accessing DS89C4x0's 1KB SAAM In C In Section 14.4 we discussed how to access the 1KB SRAM of the DS89C4x0 chip using Assembly language. Examples 14·21 and 14-22 will show the 8051 C version of some of the Assembly programs. IIOSl lNTERFAClNC TO EXTERNAL MEMORY
381
ddresse5 startiJ1g at 0, then (b) get the S
'
~
,. te(Tlal RAM a 'A' to 'E in ex Wntea C program (a) to store ASCH letters P1 one byte at a tiJne. data from the external RAM and send 11 to E.u mple 14-18
Solution:
/
#include #include void main(void) ( unsigned char x;
,. ~
I
XBYTE (OJ•' l>,; XBYTE[l )='B'; XBYTE (2) •' C'; XBYTE(3)•'0'; XBYTE(4)•'E';
., •
()
'
for(x•O;x
I
//notice the header
file for
xsYTE
location O location 1 location 2
to External //write ASCII , A' to External //write ASCII '8' //write ASCII , C' co sxcernal
//read external RAM
d
ata
and send it to Pl
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 program to read 30 bytes of table data and send it to Pl.
I
, I
Solution: #include #include
I
//notice the header ftle for
XBYTE
I
void main (void) { unsigned char count,
1
for(coun~=O;count<30;count++) Pl=XBYTE[OxlOO+count);
)
-
Example 14-20
Assume that we have an external RAM with addre
//not ice the h
eac:1.er file
382
TliEso51 ...
..uCRocoN
-
TROLLER ANO EMBEDDED svsfEMS
..'
-
unsigned char msg [SJ •"Hello";
,ioid main (void)
t
unsigned char x; TMOD = Ox20; THl • OxFD; SCON = OxSO; TRl
//OSE TIMER 1,8- BIT AOTO·RELOAD //9600
• 1;
for(x• O;x
=
msg[x];
for(X=O; x
}
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 ~include sfr PMRREG • OxC4;
//notice the header file for XBYTE
void main (void)
I
unsigned char x; PMRREG = Ox81; XBYTE[O]='A'; XBYTE(2]•'C';
//write ASCII 'A' to External RAM location O //write ASCII 'B' to External RAM location 1 //write ASCII ·c· to External RAM location 2
for(x=O;x
//read ext RAM data and send it to PO //read ext RAM data and send it to Pl //read ext RAM data and send it to p2
XBYTE [l] •' B';
l
l
lils1 INTERFAONG TO EXTERNAL MEMORY
383
~
•
block of data from the CCdt 9C4,c0, (b) mo~and send it to the serial po,t the [)58 data from SR wmplet4-22 tothe!KBSRAJMdofthesatne am to /a) enable aCCC5S !\1 then (c) rea ~'/rite a C P~9C.J20 chip into 1KB SRA. ' space of the . of the 8051 one byte at a ttme
, I
/
J
,.,-.
#include #include sfr PMRREG - OxC4;
data space extern1·na DS89C4XO / /needed for ddress I /PMR reg a l
void main (void)
I
,,• I
'-
Solution:
'
• I
i n code space //data •HELLO"; . ed char msg (] code uns1gn . RAM bit unsigned char x,I Oxl; / /enable 1KB S t up in PMR reg PMRR.EG • PMRREG //serial port se TMOD • Ox20; / / 9600 baud rate = OxPD; THl SCON = OxSO; TRl
.' "
• l;
for{X=O; x< S; X++)
//transEer data from code a rea to 1KB SRJ\M
{
XBYTE[OxO+x] • msg (x] : } for(x•O; X< S;x++)
I
//send data from 1KB SRAM to serial port
{ SBUF = XBYTE (OxO+x]; while (TI==O); TI=O; }
while Ill; )
//and stay here forever
SEC
19.
Note: This is the c version of Example 14-17
~.
n
SUMMARY
This chapter described memory interfacing with 8031/51-based systems. We began with an overview of semicon· ductor memories. Types of memories were compared in '.erms of their capacity, organization, and access time. . ROM (read-only memory) as nonvolable memory typically used to store programs. The relative advantages of van· ErROM mask were ROM.described in this chapter, including PROM, EPROM, UV·EPROM, EE PROM, flash memory ous typesand of ROM 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 tSCussed. . RAM and ROM memories were interfaced with 8031 systems, and pro am; w d pro~rammable logic were covered. these external memories. The 64KB of external data space of the was e_re Written to access code and data st~redooth 1 011 Assembly and C to access them Finally, the IKB SRAM memory f th ~~sed, and programs "'ere written m ed 0 how to access it in both Assembly and C. e ~.:>09C4xo Chip was explored and we show
=~e
J;
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 07-00 17. Find the checksum byte for these bytes: 34H, 54.H, 7FH, I lH, E6H, 99H 18. For each of the following sets of data (the last byte is the checksum byte) AO AO ,·erify if the data is corrupted. Al3 (a) 29H, lCH, 16H, 38H, and 60H (b) 29H, lCH, 16H, 30H, and 60H 16Kx8
SECTION 14.2: MEMORY ADDRESS DECODING 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
A14 AlS
cs
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. . 23. Find the address range for Y3, Y6, and Y7 m Problem 22. H. Using the 74138, design memory decoding circuitry in which the memory block controlled by YO is in the OOOOH to 3FFFH space. Indicate the size of the memory block . controUed by each Y. . . . 25. The chip select line of a memory chip tS usually active _ _
74LS138
A12 A13 A14
A
B C
GNO GND Al5
SECTION 14.3: 8031/51 INTERFACING WITH EXTERNAL ROM
26. For an 8031 with external program memory of 41<, if the starting address is 0000. the
Diagram for Problem 21
last address is . 27 What is the role of the chjp 74LS373 in Figures 14-9 and 14-10? 28. Can data be stored in program ROM? 29. The 8051 supports a maximum of K bytes of p~ogram memory space. JO. True or false. For any member of the 8051 family, tf EA = Gnd the microcontroller fetches program code fr external ROM. om ~SJ INTERfACTNG TO EXTEJlNAL Ml!MORY
38.5
~! 33 ·
34 ;
'
35. 36. 37. 38. 39.
ROM is to be added to the systern? rogram if externa I P de? has to be changed, for program co Whi h in connection of the 8051 exterl'lal memory For ~.hfci, of the lollowinlg(; )u:-~e have am code optional? (a) 8751 (b) 89C51 (c) 803 . :> I memory tor progr For which of the following 15 ext!ma (a) 8751 (bl S9C51 (cl 8031 (d) 80;)2 _ A7 address bi~? 0 In the 8051 , which port prov'.des ~S-A15 address bits? 1n the 805 I. which port prov'.des th DO· D7 data bits? In the 8051, ,~hich port pro,~des t e = 0 and ALE= J. ? Explain the difference between.ALE of P3. What about PSENode from external ROM? RD is pin of P3, and WR 15 pm - ed . fetching program c Which of the following signals must be us in
t:
I 'I ,' I ~
I
1
•
•
•
I '
'•
(a) RD (b) WR (c) PSEN . M how are they acc~ed · ro am ROM and data ROM? .w. If a system has on-chip and ofl:chthip ~f :ence in the connechon to the P Jn~ther words, the memory code space 41 In an 8051-based system, what ,s e e t be read-only memory. . 8051 th ogrnm code mus 42. True or false. For the · e pr ( ff hi ) code ROM? of the 8051 is read-only memory. . hlp code ROM or externa1 O ·C P · 43. Indicate when PSEN is used. ls it used in accessing on-< SECTION 14.4; 8051 DATA MEMORY SPACE 44. Indicate when RD and WR are used. Are they
r
l
.I
).
?
used in accessing external data memory.
be directly connected to the 8051?
45. What is the maximum capacity of a data RA~ t~•::;g data from external data ROM? 46. Which of the following signals must be used m ,e (a} RD (b) WR (c) PSEN (d} both (a) and (b) . . 47. For each of the following, indicate if it is active low or active high. (a) PSEN (b) RD (c) ViR d dift ti t between the 1Jwe 48. If a system uS
89C4xo to Pl one byte at a time e,•ery 386
''
'•
,..
SE(
,l J l
i
•I
NSWEAS TO REVIEW QUESTIONS
A
sfC110N 14.1: SEMICONDUCTOR MEMORY
(. (a) 16J
5ECf10N 14.2: MEMORY ADDRESS DECODING 1. 16K bytes
!. 3, 8
,_ Both must be low. 4. Gl must be high.
·l , 5000H · 5FFFH SECTION 14.3: 8031/51 INTERFACING WITH EXTERNAL ROM
1. From external ROM (that is off-chip) z. From internal ROM {that is on-chip) J. t 5. 6. 1.
PO PO PO P2 True
SECTION 14.4: 8051 DATA MEMORY SPACE 1. 128K 2. External
3. True 4. Troe S. Only PSEN is used to access external ROM containing program code, but when accessing extemaJ data memory we must use RO and WR signals. In other words, RD and WR are only for external data memory and are never used for external progran, ROM. 6. False 7. True
•
lost INTERfAONG TO EXTEJlNAL MEMORY
387
CHAPTER15
8051 INTERFACING WITH THE 8255
O BJECTIVES Upon completion of this chapter, you will be able to:
> > > > >
Describe how to expand the l/0 ports of the 8031 /51 by connecting it to an 8255 chip
>
List the 3 ports of the 8255 and describe their features Explain the use of the control register of the 8255 in selecting a mode Define the modes of the 8255 Define the term memory-mapped 1/0 and describe its application Program the 8255 as a simple 1/0 port for connection with devices such as stepper motors, LCDs, and AOC devices Interface the 8051 with external devices such as stepper motors, LCDs, and AOC devices via
> > >
the 8255 Diagram the 8031 interf~ce with external program ROM and the 8255 Explain how address aliases are used m address decoding techniques Program the 8255 as a simple 1/0 port ln 8051 C
>
389
Table 15-1: 8255 Port Selection
~o, A1, and~ 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 ~- B. c. or the control register as shown in Table 15-1. Note that is .,ctii·e-lOW,
~ode selection of t he 8255
CS
Al
AO
Selection
0
o
o
Port A
0
0
1
Port B
0
1
0
PortC
0 1
1
1
X
X
Control register 8255 is not selected
1\'hile ports A, B, and C are used to input or output data it is tilt' control register that must be programmed to select the o~era· . b(1l1 mode of the three ports. The ports of the 8255 can be programmed in any of the followtng modes.
1. Mode 0, simple 1/0 mode. In this mode, any of the ports A, 6, CL, and CU can be programmed a~ input ~r ou~~~ In this mode, all bits are out or all are in. In other words, there is no such thing as single-bit contro as we aves .11 in PO· P3 of the 8051. Since the vast majority of applications involving the 8255 use this simple I/0 mode, we wt concentrate on this mode in this chapter. 1. Mode I. In this mode, ports A and 6 can be used as input or output ports with handshaking capabilities. Handshaking signals are provided by the bits of port C. This mode will not be explored further in this book.
3. Mode 2. ln this mode, port A can be used as a bidirectional l/0 port with handshaking capabilities whose signals are provided by port C. Port 6 can be used either in simple 1/0 mode or handshaking model. This mode will not be explored further in this book. t BSR (bit set/ reset) mode. ln this mode, only the individual bits of port C can be programmed. This mode will not be explored further in this book.
Figure 15-3 shows the control word for mode selection of the 8255.
Simple 1/0 pro gramming Intel calls mode Othe basic i11p11t/011tput mode. The more commonly used term is simple 1/0. In this mode, any of ports A. B, or C can be programmed as input or output. It must be noted that in this mode, a given port cannot be both an input and output port at the same time.
Group A - - - - - - - - ~... - - - - - GroupB 06
07
'-
I= l/0 Mode 0= BSRMode
-
04_
05
D3
I
I
O=Output
Mode Selection 00= ModeO 01 =Mode l lx = Mode 2
Porte (Upper PC7 • PC4) 1 = lnput 0= Output
DO
"
-
...
.
01
L V!ode Selection O=ModeO 1 = Mode 1
A~ 1Port = Input
.
D2
-·-
Porte (Lower PC3 - PCO) 1 = lnput
~Port,. B ..0 • Ou"'"' = Input Output
J
Figu,t 15-J. 8255 Control Word format (UO Mode) . 'R.q,nnted by permission of Intel Corporation, Copyright Intel Corp., 1983)
8051 llliTERfAONG WITH THE 8:ZSS
391
( Example IS-1 nfigurations: f111d the control word of lite 8255 for the foUoWll'lg co (al All the ports of A, 8, and Care output p<>rtS (mode OJ. lb) PA ,,in, PB = out, PCL = out, and PCH = out. Solution:
/
Fmm Figure 15-3 we have: (a) 1000 0000 = 80H •
.
•• 'I '• I
•
(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 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 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.
E
I I
Exa.mple lS-2
,\
F
Rderlng to Figure 15-4. I
!,
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) to transfer the $talus of these switches to LEDs connected to the upper 4-bits of port A (a) Find
;~•.~x;gr•m 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
Port A Port B Port C Control Register
Al 0
's
(1
~
AO O
0 1 1
1 0 1 The rest of the address lines can be 1 0 F for ~rt A, 4001H for port B, 4002H ~ri°r example, if we take all th . (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 DPTR, l\ , move Port upper bring switch · ENO A nibbl e data :move the address to DPTR content of A to Port A
cZ:
i!
392 ii{£ sos1
l\fJc:ao CONiROLLER
AND EMBEDDED SYST~IS
(
(
SOS1
P3.7 P3.6
RD
WR A14
P2.7
cs
- WR
RD
PA P2.0
8255
ALE
re
--, G
P0.7
A07
PO.O
AOO
;o ,.
..r-,.
Al AO
... "> '-- Al
'-- AO
74LS373
oc
07 DO RES
--I
_J_ .
PS
07 DO
r,gurt Js-4. 80S1 Connec:lion to the 8255 for Example 15·2
Example 15-3 For Figure 15-5, (a) Find the 1/ 0 port addresses assigned to ports A, 8, C, and the control register. (b) Find the control byte for PA = in, PB =out, PC = out. (c) Write a program to get data from PA and send it to both p orts Band C. Solution: (a) Assuming all the unused bits are Os, the base port address for 8255 is 1000H. Therefore we have: 1000H 1001H 1002H 1003H
PA
PB PC Control register
lb)The control word is 10010000, or90H. {c) ; (PAolN,PB•OUT,PCeQl.J'l') A,#90H MOV ;load control reg port addr OPTR,#1003H; MOV ;issue control word MOVX @DPTR,A ;PA address OPTR,#lOOOH MOV ;get data from PA MOVX A,.DPTR ;PB address DPTR INC ;send the data to PB MOVX /IDPTR ,A ;PC address OPTR INC ;send it also to PC MOVX eoPTR,A in Example 15-3, it is recommended that you use the EQU directive for port addresses as s h own rtexLFor the program ·
"1>oRT BPORT CPORT CN'FPORT
EOU EOU EOU EOU
lOOOH lOOlH 1002H 1003H
~l lNTERFAONG WITH THE 82.55
393
.
8051
-RB-
WR
PJ.7 P3.6
I
b-
Al4-,,,- ~-
Al
~
./
8255
.,.•
P2.0 ALE
V
AD7
•
-AO
D7 DO RES
oc
ADO
• I•
PA PB
Al AO
......
D !J
74LS37.3
PO.O
ru5
PC 1--.
G
P0.7
•
I
.
.;-
•,
(I•
07
••
DO
(
•
~
WR
A)~ • V
AJJ-v
P2.7
!
I
.
Figute lS-5. 8-051 Connechon to the 8255 fo r Example lS-3
I
A,#90H OPTR, #CNTl?ORT @OPTR, A OPTR, #A PORT A,@OPTR OPTR eOPTR,A OPTR COPTR,A
HOV
' I
MOV MOVX MOV MOVX INC MOVX
I
'
INC
MOVX
;(PA=IN,PBsOUT,PC=OUT1dr
;load cntr reg port a ·issue control word ' ·PA address ;get data from PA ;PB address ;send the data to PB ;PC address ;send it also to PC
or the following, also using EQU:
CONTRBYT BAS825SP
EQU EQU MOV MOV MOVX MOV
90H 1000H A, #CONTRBYT OPTR,#BAS8255P+3 @OPTR, A OPTR, #BAS8255P
;(PA=IN,PB=OUT,PC=OUT) ;base address for 8255 chip
;load c port addr ;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 16-btt tf the base ad¢'ess for the 8255 is 8·bit, we can use the instructions "MOVX A, @RO" and "MOVX @RO, A" where RO (or RI) holds the 8-bit port address of the port. ~ Exa_?lp!e 15-4. Notice in Example 15-4 that we used a simple logic gate to do the address decoding for the 8255. For multiple 8255s ma system, we can use a 74LS138, as shown in Example 15-5. Example 1S-3a
R~fernng to Figure 15·5, -
(a) fmd the addresses of the ports and control register. (b) Write a progr.tm to generate a square wave at bit O of port C. Solution:
has
(a) Assuming all the unused address lines are 0, and noting that Al
2
to be l, the addresses are
394
ll-11; sos11vucao
-
CONTROLLER AND EMBEDDED svsT£ftf5
G
rort ;\ rort B
1000H 1001H 1002H 1003H
rortC (Ofltrol register
(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
START:
MOV MOV MOVX MOV MOV MOVX ACALL MOV MOVX ACALL ACALL SJMP END
A, #80H DPTR,#l003H @DPTR,A DPTR, #1002H A,#OlH @DPTR,A DELAY A,#OOH @DPTR,A DELAY DELAY START
;control word to A ;DPTR points to control register ;transfer control word ;DPTR points to port C ;A:OlH ;PCO:l ;call a delay for the ON time ;A=O
;PCOeO ;call delay for OFF time ;one more delay time for OFF time ;repeat to generate a continuous waveform
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 (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
o,
respectively, 20H, 21 H, 22H and 23H.
CWDl CWD2
PORTA PORTS PORTC CONREG NOV NOV
8QU EQU EQU EQU
BQU EQU
91H 83H :IOH :llH 22H 23H
A, tClfDl
RO,ICONRBG
MOVX IIRO, A
IPT, '-
NOV RO,t»oRIC MOVX A,91l0 . .
lilsi INT£RFACING WITH THE 8255
;move one of the control words into A - this ;ensures that port Clower is an input port ;move the control register address to RO ;move the data in A to the address pointed ;by RO, i.e., the control register ,move port C address to RO ;get port C data into A
•
• 395
port A
port 8 portC cootrol register
1OOOH 1001H 1002H 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
START:
MOV MOV MOVX MOV MOV MOVX ACALL MOV MOVX
ACALL ACALL SJMP
A, #80H DPTR,#l003H @DPTR,A DPTR,#1002H A,#OlH @DPTR, A DELAY A,#OOH @DPTR,A DELAY DELAY START
; control word to A ; DPTR points to control reg i ster ; t r ansfer control word ;DPTR points co port C ;AsO lH ;PCO=l
;call a delay for the ON time ;A=O ;PCO=O
;call del ay for OFF time . ; one more delay time for OFF time ;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.
=
91H 83H 20H 21H 22H 23H A, #CWDl
BOU EOU EOU EOU EOU EOU
CWDl CWD2 PORTA PORTB PORTC CONREG
MOV
RO, #CONRJIG MOVX •RO, A
MOV
RPT:
RO, tl'ORTC MOVX A,eRO
MOY
80s1 INTERFACING WITH THE 8255
;move one of the control words into A - this ;ensures that port Clower is an input port ;move the control register address to RO ;move th~ data in A to the address pointed ;by RO, i.e., the control register ;move port C address to RO ;get port C data into A .
395
'
-
l!ERE:
) L
THERE:
• •
.•' "
I
RRC JC HOV MOV MOVX HOV MOVX MOV MOVX SJMP MOV MOVX MOV MOVX SJMP
A THERE A,#CWD2; RO,#CONREG tRO,A RO, #PORTS A,l'RO RO,#PORTA RO, A RPT RO,#PORTA A,f/RO RO,ffPORTB @RO,A RPT
. g A into carry rota tin of A bY THERE JUIIIP co he control word change t
input port B oint co A ; let RO ~ B data into ort A get por output P '.1et RO point to1·n A co port A • h data ·move t e rocess '.repeat the p co input port A '.1et RO point input port A to A reg. ' da ta ' from ;move nt to output p ore B , let RO poi·n A to port B ·move data l ' ;repeat
END
•
'
r.
RD
P3.7 P3.6
t
'
WR
8 0 5
r
I
_[
,-A•
"'
' p cs
A~
WR RD
-A3 A2
ALE P0.7
PO.O
AD7
ADO
.J
PA PB
8255
C
' D Ql-d" ' .' . 74LS373
PCL
Al AO
Al AO
oc
-
PCU
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; however, in Examples 15-3 and 1~ 2 we ~ecodcd only a portion of the upper addresse, of AS_· A15. Th,s partial address decoding leads to what is called addms al1nS1.'<. In other words, the same physical port h different addresses; Ll1us, the same port is known by different nam as In Examples 15-2 and 15-3 we could have changed alJ x's to va . es. combinations or ls and Os to come up with diffel1'nt addresse:•ous they would aU refer to the sam,• physica l port. In your ha d ' yet . rware reference document.1hon, ma ke sure th at i a I address aliases are d umented, so that the user knowo what addresses arc available if h
74lS138 A2
A3
A
A4
B C
AS A6
G2A
A7
c2a
AO Al Y2
-cs
8255
GJ
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: G2B GI A6 ~1
-
-G2A
0
l
AS
C A4
0
0
B A3 1
Address
A A2 0
Al
AO
0
0
88H
8031
.J: C
EA
P3.7 P3.6 PSEN P2.7
RD WR
L
PO.O
CE
A12 - Al2 AS - AS
P2.0 ALE P0.7
v::c
G
AD7
,oQK 7 4LS373
ADO
oc .,.
A7- A7 AO -
AO
OE
Vpp
2864 (2764) 8Kx8 program ROM
07 DO
R R!5 • AUY
cs
PA
8255
PB
PC Al AO
RES
I.L 07 DO
figure J;;-3. 8031 Connection to External Program ROM and the 8255
8031 system with 8255 In the 8031-based system where external progran, ROM is an absolute must, the use of an 8255 is most welcome. This ii due to the fact that in the process of connecting the 8031 to external program ROM, we lose the two ports PO and P2, le.Ving only Pl. Therefore, connecting an 8255 is the best way to gain some extra ports. This is shown in Figure 15-8.
Review Questions l t l. l S.
Find the control byte if all ports are inputs. Find the control byte for re = in, PB = out, and PA = out. True or false. To avoid aliases, we must decode addresses AO - A15. Can 86H be the base address for port A of the 8255? Why do we use the MOVX instruction to access the ports of the 8255?
SECTION 15.2: 8255 INTERFACING . Chapters t 2 and 13 detailed real-world interfacing of LC~, sensors, and ADC devices. ln this section we show how lo1nterface the 8255 to LCDs, stepper motors, and ADC devices, then program it using 8051 instructions.
Stepper motor connection to the 8255 Chapter 17 will detail the interface of a stepper motor to the 8051. Herc we show stepper motor connection t0 h ~ and programming. See Figure 15·9. t e
IOst INnJtpACING WITH THE 8255
,_________
397
'
/ 16
DO D7
,,• A2
•
8051
RD
DO D7
PAO
WR
PAI
RD AO Al
cs
• I
,
0
JS 14
PA2 1
RESET
Decoding Circuitry
.(
•
COM
ULN2003 Connection for Stepper Motor Pin S•GND Pin9 = +SV
'•
2
A7
•
"
WR
AO Al
•••
,
from
Stepper Motor
ULN2003
8255
t'
COM +SV
. power supply for the 1notor Use a separate
Figure 15-9. 8255 Connection to Stepper Motor
•
r
( (
j. I
r
MOV A,#BOH MOV Rl, #CRPORT MOVX @Rl ,A MCV Rl,#APORT MOV A,#66H AGAil'l; MOVX @Rl,A RR A ACALL DELAY SJMP AGAil'f
: control word for PA ; out ;control reg port address ;configure PA= out ;load PA address ;A•66H,stepper motor sequence ·issue motor sequences to PA • • ;rotate sequence for clockwise ;wait.
8255
PAO
--
LCD
DO
I-
PA7 -
D7
V
+SV
cc-
VEE
';:. !OK
-
~
I
;C
-·
.r
RS R/WE Vss """~ PBO PB1
I
-:.=-
PB2
i..RESET
LCD connection to the 8255
Program 15-1 shows how to issue commands and data to an LCD Figure 15-10. LCD Connection connected to an 8255. See Figure 15-10. In Program 15-1. we must put a Jong delay before issuing any information (command or data) to the LCD. A better way is to check the busy Oag before issuing anything to the LCD. This was discussed in Chapter 12. Program 15-2 is a repeat of Program 15-1 with the checking of the busy aag. Notice that no DELAY is used the main program in Program 15-2.
;Writing commands and data to LCD without checking bus Ila ;Assume PA of 82SS connected to 00-07 of LCD and y 9 ;PB0=RS, PBl=R/W, PB2•8 for LCD•s control pins c . " onnection MOV A, .eoH ;al l 8255 MOV RO. #CtlTPORT ·l ports as output MOVX GRO,A 'oad control reg address MCV A, #38H '~~ue control word ACALL CMDWRT '. . ' 2 lines• 5)(7 matrix ACALL DELAY 'write command to LCD I MOV A. # OEH wait before next i ; Leo command f ssue (2 ms) ACALL CMDWRT , write or cursor on MOV A #olH command t • ; Clear LCD O LCD ACALL CMDWRT ACALL ;Write Com-. DELAY :wait b ......,.nd to LC!) efore next
:>
:I :l
issue
Progr.un 15-1. (co111111urd 011fo/Jowmg pag,J
398 'rliE 8051 "-llcn
-
-
"OCONTRo S lll!R ANO EMBEDDED sySTEftf
;shift cursor right command CMDWRT ;write command to LCD 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 ;issue info to LCD data pins MOVX @RO,A MOV RO,#BPORT ;load port B address ;RS=O,R/W=O,E=l for H-to-L MOV A,#000001008 ;activate LCD pins RS,R/W,E MOVX @RO ,A ;make E pin pulse wide enough NOP NOP ;RS=O,R/ W=O,E=O for H-to-L MOV A,#00000000 8 ;latch in data pin info @RO ,A MOVX RET ;Data write subroutine, write data to be displayed to LCD ;load port A address OATAWRT : MOV RO, #A PORT ;issue info to LCD data pins @RO, A MOVX ;load port B address RO , #BPORT MOV ; RS=l,R/W=O,E=l for H-to-L A,#000001018 MOV ;activate LCD pins RS,R/W,E @RO ,A MOVX ;make E pin pulse wide enough NOP NOP ;RS=l,R/W=O,E=O for H-to-L A,#000000018 MOV ;latch in LCD's data pin info @RO, A MOVX RET
-,,cv
A,#06 ACALL ACALL
i'logri111 lS-l. (contit1ued from previous P"ge)
;writing commands to the LCD with checking busy flag ;PA of 8255 connected to DO-D7 of LCD and :PBO=RS, PBl=R/W, PB2•E for 8255 to LCD's control pins connect. MOV A,#SOH ;all 8255 ports as output MOV RO,#CNTPORT ;load control reg address ;issue control word @RO,A MOVX ;LCD: 2 LINES, 5X7 matrix A,#38H MOV ;write command to LCD NCMDWRT ACALL ;LCD command for cursor on A, #OEH MOV ;write command to LCD NCMOWRT ACALL ;clear LCD A, #OlH MOV ;write command to LCD NCMDWRT ACALL ;shift cursor right command A,#06 MOV ;write command to LCD NCMDWRT ACALL P ~ lS-2. /continued onfallowrng pagt)
losJ 1NT!RFACING WITH THE 8255
399
'
I
I •
•• .
,.
,•• '
( l)
LCD commands for al l (letter Nl ;etc. data 1 y .. . . . ·displaY to LCD diSP a A. J:; 'N' MOV 'end data (letter 0) NOATAWRT ACALL '.~isplaY data LCD display A,ij'O' ' d ta tO MOV · send a ther data NOATAWRT • for o CALL ;etc: busy flag checking e ··· ·ne with ;New comma nd write subrouti ,save A valu d LCD status • rea NCMDWRT: MOV R2 • A ·PA•IN to reg address A, #90H '.1oad control N PB=OUT MOV RO' #CNTpORT HOV '.coniigure PA=sl1,read command @RO,A MOVX ' /W l ~ ·RS=O,R =' ddress A,#000001108 MOV '. load port Bfa RD and RS p ins RO, #SPORT MOV ' R/W-1 or 9RO,A ;RS•O, ddress MOVX · load port A a RO,#APORT MOV • d ommand reg A,®RO READY: MOVX ; rea c flag) into carry move D7(busy d A RLC ; . til LCD is rea y READY JC ;wait un d PB output again A,#SOH MOV ;make PA an ort address ·load control P 8255 RO,#CNTPORT MOV :issue control word to MOVX eRO,A '.get back value to LCD MOV l'., R2 ' 1 d port A address MOV RO,#APORT '.;::ue info to LCD'S data pi ns lilRO,A MOVX '.load port B address MOV RO,ijBPORT MOV A,#000001008 '.RS•O R/W•O,E•l for H-to-L MOVX @RO,A '.acti~ate RS,R/W,E pins of LCD NOP ;make E pin pulse wide enough NOP MOV MOVX RET
A,#000000008
®RO,A
I
/
' I
-
;RS•O,R/Wa0,8=0 for H-to-L ;latch in LCD'S data pin info
;New data write subroutine with checking busy nag NDATAWRT: MOV R2,A ; save A value MOV A,#90H ;PA•IN to read LCD status, PB=OUT MOV RO,#CNTPORT ;load control port address MOVX @RO, A ;configure PA•IN, PB•OUT MOV A,#000001108 ;RS=O,R/W•l,E•l to read command reg MOV RO,#BPORT ;load port B address MOVX @RO, A ;RS•O,R/W•l for RO and RS pins MOV RO,#APORT ;load port A address READY: MOVX A,®RO ;read command reg RLC A JC ;tno~e 07(busy flag) into carry READY MOV ;wait until LCD is ready A,#SOH MOV ,make PA and PB output again RO, #CNTPORT MOVX ;load control port addr II/RO , A · iasu ess MOV A,R2 , e control word to 8255 MOV ;get back value to b R0,#1'.PORT MOVX e sent to Leo ; load po GIRO, A . rt A address MOV ;issue info to LC RO, #BP0RT MOV ;load port 8 dd D's data pin s A,#00000101a ·Rs a ress MOVX • •l,R/wko Bl IRO, A ·act· " for R-to , 1vate Rs' R/ . -L Progr•m 15,-2. /Ct•11l1111._,, v11 followmg pog.-J ' W,e P1ns of LCD
TliE 80s1 M.ICRoco
NTROLLER ANO EMBEDDED SYSyS,f.S
a
NOP NOP MOV MOVX RET
;make E pin pulse wide enough ;RSal,R/W•O,E=O for H-to-L ;latch in LCD'S data pin info
A,#OOOOOOOlB @RO,A
J't081",n 15-2. l«mti1111ed from previous pag~)
5V
)
AOC804 Vee
RD 8255
DO from 8051
AO Al
A7 -
cs
Decodi ng
Circuitry
RESET
~
CLKlN DO Vin(+) Vin(-)
-WR -RD
RD
.
WR CLKR
D7
Wit
A2
PAO
10k 150 pP
10k
• POT
AGND •
Vref/2
PA7 PCO
I -
D7
GND ,--
LNTR
cs -
-
-
...
I
figure 15-11. 8255 Connection to AOC804
ADC connection to the 8255 ADC devices were covered in Chaprer 13. The following is a program for the ADC connected to the 8255 as shown
in Figure 15-11.
MOV MOV MOVX BACK: MOV MOVX ANL
JNZ
A,#SOH Rl, #CRPORT ®Rl,A Rl,#CPORT A,@Rl A,#OOOOOOOlB BACK
;control word for PA•OUT,PC•IN ;control reg port address ;configure PA=OUT AND PC=IN ;load port C address ;read port C to see if ADC is ready ;mask all except PCO ;keep monitoring PCO for EOC ;end of conversion, now get ADC data ;load PA address ;A•analog data input
Rl, #APORT MOV A, ®Rl MOVX So far we have discussed the simple 1/0 mode of t~e 8255 and showed many applications for it using Assembl language. Next, we discuss how to program the 8255 using 8051 C language. Y
Review Questions I. Modify the stepper motor program to ~ counterclockwise. l. True or false. In programming the LCD vi.a an 8255 (without checking the busy flag), port A is always an output
3 P<>rt. · True or false. In the LCD cormection to the 8255, we must have a long delay before issuing the next data if we are 1101 checking the busy flag.
flOsi INT£RFAC1NG WITH TH£ 8255
401
SECTION 15.3: 8051 C PROGRAMMING FOR THE 8255
In this section ,ve show how to prograot the 8255 using the 8051 C languag~- In the last chapter we Showe
•-"'' •="' ""="'" - r y ,p,re of>• 805' s,re '"' 8255 " """' "~ ""m•I d ho. '10), )(DATA[... ( >H• 805' C. ,~mpl~ g,ffl ,o """• ..., fm=ry-m,,,.,
d.,o
s,,,dy ' " " " ••
,o -
we -
W
"' of 805 >C P"'8'"""" e, "' S'55. Example 15-6
"'""'·
~
825S is4000H (Seeam send SSH and AAH to all ports of the 8255 continuously. Assume the base addre 1 Write a C progr · Figure 15-4) ss of the V
•
Solution:
#include #include
'•
void main() ( unsigned char value;
'
(
//intialize all ports as output
XBYTE[Ox4003J=Ox80·•
l
while(l) {
·'
. .
511
value. OxSS· XBYTE [Ox4000]' •va l ue· XBYTB[Ox4001] 0 va 1ue·' XBYTB(Ox4002)-va1ue ,·
r
Ms Delay(lOO);
//send SSH to all ports
Ill
•
1111
value,; Ox.AA· XBYTE (Ox4000 ], evalue . BYTE [Ox400l] •value •. X XB YTE [Ox4002] •value.'
Ms Delay(lOO);
//send OAAH t o all ports
,
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 8255. (See f; ...!:m1•""'·l t? get data from PA and send 1·1 to both
.
o-·
. Solution·
ports B
a~cu • sea b ase a ddress of 4000H fot ......
#incl include d
us
402
THE80s1 Mien
"ocoNTROLLE"
~AND
EMBEDDED sYSJ9fS
unsigned char value·• XDATA[Ox4003]=0x90· '
wbile(l) { value= XOATA[OX4 000) ; XDATA[Ox 400l ]=value·• XDATA[Ox4002]avalue; }
// PA=in, PB=PCsout
// get a byte f rom PA // s e nd i t t o PB //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 hnclude void MSDelay (unsigned int itime ) ; voi.d main (l { uns i gned c har value; XDATA[Ox4003) s Ox80; wbile ( l ) { XDATA [Ox4000) • OxCC; MSDelay(SOO); XDATA[Ox4000] • Ox99; MSDelay (SOO); XDATA[Ox4000] • Ox33; MSDelay (500); XDATA [Ox4000] • Ox66; MSOelay(SOO); }
I / PA=output
I void MSDelay(uneigned int i t ime) { unaigned inti, j; for ( i•O; icit iee; i ++) for (j•01 jc1275; j++)1
l lest lNTERFAaNC WJTH 'OfE 8255
403
,, ,'· •
connecting it to an 8255 chip. The 8255 51 SUMMARY rts of the 80311 . Y uch as stepper motors, LCDs, and All(: This chapter described how to expand the •;~o':rol interfaced devices s -
b
O
(
~ ~
c
e .bit port can be pro?rarnm~ as one 8-bit could then be programmed as a simple 1/0 port 8 d vices . b·d·rectional ports. Th ed b the control register. Vanous addres& 1 " Th~ 8255 has 3 ports. Ports A and Bar~ S-bit~ of the 8255 are select 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 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
?1'
• •
.•
•
'•
'
•
I l ·'
PROBLEM S
•
SECTION 15.l: PROGRAMMJNG THE 8255 1. Find the control byte to set
2. 3. 4. 5.
6. 7. 8.
9. 10.
lJ.
aU the ports as simple input.uts and
c
ort as output. Find the control word to configure ports A and Bas mp d reo;
:o)
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
u,e
13. In Problem 12, find the base address of the 8255 for foll , · (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 ~w are they categorized? 5 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 . ch 1,5 • low. to-high Generate this pulse at pin PAO. Use the addr 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 · re is equal to 100, then the result should . to port C.
th ~
404 TH£sos1 ••
,.. 1cRocoNT
-
ROLLER AND EMBEDDED 5ySTEMS
L •1 : 1 >
. . Id be ved and send AAH to port 8 write a C program to monitor PA for a temperature of 1()(). If it is equal, ,t shou sa 'If,. and SSH to port C before exiting. ,g write a C program to get data from PA and send it to both PB and PC. ~ write a C program to get data from PC and send it to both PA and PB.
ANSWERS TO REVIEW QUESTIONS icnoN 15.1: PROGRAMMING THE 8255 }. 9BH i 89H i True -1. It cannot since we must have Al :: Oand AO"' Ofor the base address.
ed 1/0 5. The MOVX instruction allows access to external memory and 8255 is mapped as memory-mapp ·
sECTION 15.2: 8255 INTERFACING I. •RR A" is changed to "RL A". 2. True
,. True
-
CHAPTER16
DS12887RTC INTERFACING AND PROGRAMMING
OBJECTIVES Upon completion of this chapter, you will be able to:
>
>
> > >
>
> >
Explain how the real-time dock (RTC) chip works Explain the function of the 0512887 RTC pins Explain the function of the 0512887 RTC registers Understand the interfacing of the 0512887 RTC to the 8051 Code programs in Assembly and C to access the RTC registers Code programs to di5play time and date in Assembly and C Understand the interrupt and alann features of the DS12887 Explore and program the alarm and interrupt features of the RTC
I:
!
12CS87 re.ii-time arnni1ng of the OS. functio/\S and nu, ch.lptet sh<>WS the ,nterlaCJ/\g and progrbe 0512887 RTC pin0'" to program d oclc (RTC) ch•~· In s«oon 80516 ;;,es::: 16.l, we also shof~12887 is sho"'.n sh<>W ,ts '"terfK111S with the . sed 1n 3 ,nnung o the 051288'1 ill Assembly language. The C P~ the 05J2287 are d,SCUS ,n ~ 16 2 The alarm and S-0_\'J features
~
SECTION 16.1: 0 $12887 RTC INTERFACING . te time that pto'"des accur• The real-time clock (RTQ is a widely used de, ace
VCC24
2 NC
SQW 23
NC
NC22
3
5ed10C\ 16.3.
•
1 MOT
the x86 IBM pC come and date for many applications. Many systems sut ~~e IBM pro..-ides tiJl\e
re
4 ADO
NC21
s
ADI
NC20
6 A02
lRQ 19
7 ADJ
RESET 18
8 AD4 9 ADS
OS 17
1 NC16 with such a chip on the motherboard. The ~TC '~ ~ n to the date/calendar com· components of hour, minute, and SC(Ofl(I, in addillO . tern al battery, wluch R/W IS 10 A06 ponents of year, month, and day. The RTC chip uses an: h ~me 8051 family AS 14 keeps the time and date even when the pawer is off. Allh d g bedded into the 11 AfYl members, such as the DSSOOOT. come w,th the RTC alrt• y RTC chip. One CS 13 12 CND chip, we have to interface the vast majority of them to an ext~m,Sc .conductor/ of the most widely~ RTC chi~ ,s lhe 0512887 f_rom Oa as ~~e ori inal x86t 2887 l'Cs is the repS1ace•Maxim Corp. This chip · LS found ,n lhc vast ma1or1ty I Thof OS IBM PC/ AT used the MC14618B RTC from Motoro a. e . f •er Figure 16-1. OS12887 RTC Chip ment for that chip. It uses an intem.>l lithium battery to keep operating or ov 10 years in the absence of external power. According to the DS12887 data sheet . from Maxim. it keeps track of •SC(OR(I•. minute-, hours. da)'S, day _of w~k, date'. month, and year with leap-year compensation valid up to year 2100". The above Information is provided ,n both bma ry (hex) and BCD fo rmats. The DS12887 supports both U-hour and 24-hour dock modes with AM and PM ,n the 12-hour mode. It also supports the Daylight Savings Time option The DS12887 uses CMOS technology to keep the power consumption low and it has the designation DS12C887. where C is (or CMOS The DS12887 ha, a total of 128 bytes of nonvolatile RAM. It uses 14 bytes of RA.'vl for clock/ calendar and control registers. and the other 114 bytes of RAM are for general-purpose d1ta storage. In the J<86 IBM PC, these 114 bytes of NV-RAM are used for the CMOS configuratio n, where the system setups are kept before the operatmg system takes over. Next we descnbe the pl/\S of the 0512887. See Figure 16-1.
-
en:1
•
'
( '
,L:4 provides exte":'al s~ppty voltage to the chip The external voltage source is +SV \Vhcn v
Pm
It
falls below the JV
14!\'e 1, ""' external source ts switched off and the ,ntemal lithium batte
d "' ~ prov,.._<': power to the RTC. continues to operate. and all of the RAM. time, calendar, and ala,,,'.. ccor '"S to u."' 051 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 illld ;:!~le. It must .also be thilll 4.25V, the devke becomes accessible after 200ms.• s a level of greater C DS12887 8051 ADO PO.O GND ThLS nonvolatile capability of the RTC prevents any loss of data A
osik,
Ui8'?
~
vc
RSTLJ
P,n 12 Is the ground A07
P07 AD0-AD7
MOT
I-
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 '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 l 805l l5 shown ln F ~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 u,c m5lruction SltlCt' 11 tS mapped as external lf>:2. we use ~O•des e will dJoCuo6 ~ '" VX
...;::.ory·~
ALE RD WR
~f:::.
shortly.
THE 8051 MICROC
~
'T
!,z.
Flg,u.1~2,
ON'fR
'
D512117C-Mdl• .. -
-
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 connectl'd. In other words "when V"' falls below 4.25V, the chip-select input is internally forced to an inactive level regardless 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 frequency of the square wave is set by programming register A and is discussed in Section 16.3.
RESET Pin 18 is the reset pin. It is an input and.is ~ctive lo~ (normally high). [n most applications the reset pin is connected to the V« pin.In applications where this pm 1s used, tt has ~o effect on the dock, calendar, or RAM if it is forced low. The low on this pin will cause the reset of the IRQ and cleanng of the SQW pin, as we will see in Section 16.3.
Address map of the 0$12887 The DS12887 has a total of 128 bytes of RAM space with addresses 00 - 7FH The first ten locations 00 09
·"ca1~-' · for the control and status ' - registe , are set 1s....., for RTC values of tirne, e11uar, and alarm data· The next four bytes are used
They are registers A, B, C, and D and are located at addresses 10 - 13 (OA - OD in hex). Notice that their hex admess:;
11\alch their names. The next 114 bytes from addresses OEH to 7FH are available for data storage. The entire 128 b o! RAM are accessible directly for read or write except the following: ytes I
RegL~ten C and D are read-only.
2. D7 bit of regi5ter A ls read-only· 3 The high-order bit of the eeconds byte ls retid-only. Fi~ 1~3 ahoW8 the addretS DlllP of the DS12887.
-
/ 0 0
00
13
OD OE
14
I
2 3 4
5 6 7
/
8 9 10 J1 12 13
•
..
127
•
•
7F
5ec<>nds Seconds Alarm Minutes .Minutes Alarm Hours Hours Alarm D•" ot the Week Dav of the Month Month Year Reeister A Remster B Remster C R""'ster D
...0
,.,.f
Figure 16-3. DS12887 Address Map
,i •
Time calendar and alarm address locations and modes
I
' ' . d I da ta Table 16-1 shows their address locations The byte addresses 0- 9 are set aside for the time, calendar, an a arm · and modes. Notice the data is available in both binary (hex) and BCD formats.
(. (
' • I
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 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 Location 0
Seconds
I
Seconds Alarm
2
Minutes
3 4
Minutes Alarm
Function
Hours, U-Hour Mode Hours, 12-Hour Mode Hours, 24-Hour Mode
5
Hours Alarm, 12-Hour Hours Alarm, 12-Hour Hours Alarm, 24-Hour
6
Day of the Week, Sun " 1
7
Day of the Month
8 9
Month
410
Year
Decimal Range 0 -59 0 - 59 0- 59
0-59 1-12 I -12
0 -23 I· 12
....
Data Mode Range Binary (hex) BCD 00 - 38
00-S
00·3B
00-S
00 ·3B
00-59
00- 38
..
..
00-59
01-0CAM
01-12AM
81-BCPM 0 -17
81- 92 PM
l · 12
01-0CAM
0- 23 1- 7
81-BCPM 0 • 17
1 • 31 l - 12
01-07 01-tF
0.99
01-0C
00-63
0 -23 01-12AM 81-92 PM 0-23 01- 07 01 · 31 01 • 12 00-99
-
-
..
I
UIP
! DV2 ! DVl ! DVO
J
R5.3
I
UTP
Update in progress. Trus is a read-only bit.
DV2
0
DVl DVO 1 0 ,vUl tum the oscillator on
RS3
RS2
RS1
RS2
RSI
I
RSO
J
RSO
Provides 14 different frequencies at the SQW pin. See Section 16..3 and the DS12887 data sheet.
f,g!l1t J(,-4. Register A Bits for Turning on the DS12887's Oscillator sinC'~ =~;See Chapter 1~ for a discussion of external memory in the 8051. For the programs in this char,ter, we use ll\ltlU;1ion MOVX A'. @RO since the address is only 8-bit. In the case of a 16-bit address, we must ':'se MOVX A, @ o!'!R as was shown m Chapter 14. Examine the following code to see how to access the DS12887 of Figure 16-2.
ACJILL DELAY_ 200ms MOV RO, #10 MOV A, #20H MOVX @RO,A
;RTC NEEDS 2ooms AFTER POWER- UP ;R050AH,Reg A address ;010 in D6-D4 to turn on osc . ;send it to Reg A of DS12887
Setting the time When we initialize the time or date, we need to set 07 of register B to 1. This will prevent any update at the middle of the initialization. After setting the time and date, we need to make D7 = 0 to make sure that the clock and time are llj>dated. The update occurs once per second. The following code initializes the clock at 16:58:55 using the BCD mode ind 24-hour clock mode with daylight savings time. See also Figure 16-5 for details of register B. ;···--- WAIT 2oomsec FOR RTC TO BE READY AFTER POWER-UP ACALL DELAY_200ms ;• • - - - - - - - - - -TURNING ON THE RTC MOV R0,#10 ;RO=OAH,Reg A address HOV A,#208 ;010 in D6 - D4 to turn on osc. MOVX @RO,A ;send it to Reg A of DS12887 :·-- - ----- -----setting the Time mode MOV RO #11 ;Reg B address MOV A,#83H ;BCD,24hrs,Daylight saving,D7 • 1 No update MOVX @RO,A ;send it to Reg B :· ·· - · ·----Setting the Time MOV RO,#O ;paint to seconds address HOV A,#SSH ;seconds• SSH (BCD numbers need Hl MOVX @RO,A ;set seconds HOV RO,#OZ ;point to minutes address HOV A,#SBH ;minut~s· 58 MOVX @RO, A ; se~ minutes HOV R0,#0 ;po1 nt to hours address 4 HOV A,#16H ;hou~s-16 MOVX @RO A ; set hours HOV RO,#~l ; Reg e address MOV A,#Ol ;D7•0 of reg B to allow update MOvx eRO, A I send it to reg B
,u
SQWE
DM
24/12
DSE
UTE d .nd time and datest mar:ic~~;;:\) -· • we mus · once pet se Interrupt Enable. e ·dd) are the same as AIE all three bytes of time (yy:mm. Section I6.3. t UlE See the ()512887 data shee . 163 . (hex) data format le· See 5ection d DM I· B111ary b SQWI! Square wave ena .' 0 data fom,at an - . . 2 OM Data mode. DM O. 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
/
PIE
AIE
•'
.' .
9'.;
•
•
•
Figun 16-5. Some M•jor Bits of Register 8
'
Setting the date . .L twhen we initialize tin1e or date, we need The following shows how to set the date to ,.,.~ u,.,ober !9th' 2004. Notice u ,a to set 07 of register B to 1. . .... •...•••• TURNING ON THE RTC ' MOV RO, #10 ; RO• OAH, Reg A address MOV A,#20H ;010 i n 06 · 04 to turn on osc MOVX @RO,A ;send it to Reg A of OS12887 '···-····· ······ Setting the Time mode MOV R0,#11 ;Reg B address MOV A, #83H ;BCD, 24 hrs, daylight saving MOVX @RO,A ;send it to Reg B ;··· ······· Setting the DATE MOV R0,#07 ;load pointer for DAY OF MONTH MOV A,#l9H ;OAY=l9H (BCD numbers need H) MOVX @RO,A ;set DAY OF MONTH ACALL DELAY; MOV R0,#08 ;point to MONTH MOV A,#lOH ;lO=OCTOBER. MOVX @RO,A ;set MONTH ACALL DELAY ; MOV R0,#09 ;point to YEAR address MOV A,#04 ;YEARa04 FOR 2004 MOVX IIIRO ,A ;set YEAR to 2004 ACALL DELAY MOV R0,#11 ;Reg B address MOV A,#03 ;D7a0 of reg B to allow update MOVX @RO,A ;send it to reg B
'l
•
(. l ' I
RTCs setting, reading, displaying time and date The following is a complete Assembly code for setting di dates a.re sent to the screen via the serial port after they a ' rea ng, and disp laying the ti re converted frorn BCD me to ASCU. ;·•··RTCTIME.ASM: SETTING TIME,REJ\DING AN!) O ORG O !SPLAYING IT ACALL DELAY 200ms ;RTC needs 200 ;SERIAL PORT SET-UP nis upen MOV TM00,#20H Power.up
an
d d
Th ..,_ and ate. e ...,.,es
412
Tlit 8051 ~CR"'""-Ol\/11to
_
LLER AND EMBEDDED SY5fEMS
MOV MOV
SCON,#SOH 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. ;set MONTH MOVX @RO.A ACALL DELAY ;point to YEAR address MOV R0,#09 ;YEARa 04 FOR 2004 MOV A, #04 ;Set YEAR to 2004 MOVX @RO,A ACALL DELAY ;Reg B address MOV R0,#11 ;D7=0 of reg B to allow update MOV A,#03 ;send it to reg B MOVX @RO,A ; · ••• ··· • READ Time (HH:MM:SS), CONVERT IT AND DISPLAY IT ;ASCII for SPACE OV1 : MOV A, #20H ACALL SERIAL ;point to HR loc MOV R0,#4 ;read hours MOVX A,@RO ACALL DISPLAY ;send out SPACE MOV A,#20H ACALL SERIAL ;point to minute loc MOV R0,#2 ;read minute MOVX A,@RO ACALL DISPLAY ;send out SPACE MOV A,#20H ACALL SERIAL ;point to seconds loc MOV R0,#0 ;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 Dl: ;
OJNZ
R7,#250 R7, 01
.... __________ _ coNVSRT
BCD TO ASCII AND SEND IT TO SCRBEN
DISPLAY: NOV
B,A
SWAP A
,u
fl
/
ANL ORL ACALL HOV ANL ORL ACALL RET
A, #OFH A, #)OH SERIAL A,B A, #OPH A,#30H SERIAL
''. .• i t
•
•
·--·--------
•
SERIAL: SI: • •
MOV JNB CLR RET
SBUF,A TI, Sl TI
ta ~
;------------
•
BND
• •• • J
•
( I •j
fl
The foUowing shows how to read and display the date. You can replace the time display portion of the above program with the program below.
; -------- READ DATE('lYYY:MM:MM), CONVERT IT AND OSIPLAY IT OV2: MOV A,#20H ;ASCII SPACE ACALL SERIAL MOV A,#'2' ;SEND OUT 2 (for 20) ACALL SERIAL MOV A,#'0' ;SEND OUT O (for 20) ACALL SER!AL MOV RO, #09 ;point to year loc MOVX A,@RO ;read year ACALL DISPLAY MOV A,#• : , ;SEND OUT: for yyyY:mrn ACALL SERIAL MOV R0,#08 ;point to month loc MOVX A,@RO ;read month ACALL DISPLAY ACALL DELAY
-
MOV
A,#':,
ACALL MOV MOVX ACALL ACALL
SERIAL R0,#07 A,@RO DISPLAY DELAY
MOV
A,#'
,
ACALL SERIAL ACALL DELAY MOV
A,#'
,
ACALL SERIAL ACALL DELAY MOV A,#OAH ACALL SERIAL MOV A,#ODH ACALL SERIAL ACALL DELAY LJMP OV2 414
;SEND OUT: for mrn:dd ;point to DAY loc ;read day ;send out SPACE ;send out SPACE ;send out LF ;send CR ;display d
ate forever
I
'' ~
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? . 3i. ,. 6.
)-[ow I l l ~ by~~ RAM in the DS12887 are set aside for general-purpose applications? source 1 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? True or false. When the DS12887 is shipped, its oscillator is turned on.
SECTION 16.2: DS12887 RTC PROGRAMMING INC
c
In this section we program the DS12887 in 8051 language. Before you embark on this section, make sure that the t,asic concepts of the D512887 chip covered in the first section are understood. Also, review external memory access
using 8051 C, as discussed in Chapter 14.
Turning on the oscillator, setting the time and date in C In Chapter 14 we discussed how to access external memory using 8051 C. We also discussed the details of the [)512887 in the previous section. ln this section we provide the C version of the programs given in the previous section-To access the DS12887 in Figure 16-2, we use the 8051 C conunand XBYTE[addr], where addr points to the external address location. Notice that XBYrE is part of the absacc.h library 6\e. The following C program shows how to turn on the oscillator, and set the time and date for the configuration in Figure 16-2.
//RTC Time&Dat:e initialization in C Oncl ude I i nclude void main (void) { Delay(200) XBYTE[l0]=0x20; XBYTE[ll]•OX83; XBYTE[O]aOxSS; XBYTE[2]•0x58; XBYTE[4)=0xl6; XBYTE(7J•Ox19; XBYTE[8]=0xl0; XBYTE[9]•0X04; XBYTE[ll]•Ox 03; }
//RTC needs 200 ms upon power-up //turn on osc. //BCD, 24 hrs, daylight savings //SECOND•SSh for BCD //MINUTE=58h for BCD //HOUR•l6H for BCD //day•l9h //month•lOh for October //year•04 //allow update
Reading and displaying the time and date In C The following c program shoWS how to read the time, ronvert it to ASCl1, and send it to the PC screen via the serial port. I /Displaying Time and Da te in C *include I include "Oid bcdcoov (unsigned xl ; Void aerial (unsigned x ) ; 'loid main ( void) { unsigned cha r br,min,sec; TMOOaOx 20; //9600 baud ra te Tlll•OxFO;
,
ff
I ~
sCON•OxSO; TRl=l;
while(l)
I
hr•XBYTE[4]; bcdconv (hr) ; serial (' : ' ) I min=XBYTB [2] , bcdconv(min); serial ( ' : ' ) ; sec•XBYTB[O]; bcdconv (sec) ; serial (OxOD); serial(OxOA); }
/
)
•• •
"' '•
//display time
forever
//get hour display //convert and separate . to t //send ou · //get minute display //convert and separate //send out : to //get second lay //convert and disp //send out CR d //send out Line fee
//clnvert BCD to ASCII and send it to serial //see chapter 7 void bcdconv(unsigned mybyte) {
I
unsigned char x,y,z;
I
xsmybyte&OxOF; x=x(oxJO; yamybyte&OxFO;
.
•
l'
Y=Y>>4;
J
y=yJOx30; serial (y); serial Ix);
I
//send out one char serially void serial!unsigned x ) { SBUF=X; 1'1hile (Tl==O); TI=O;
I Theprogr.un following shows how to read and display the date in 8051 C. You can replace the time display portion of the with the
while(l) { serial I '2'), serial ( •o•); yr•XBYTB(9); bcdconv Iyr) ; serial ( • : •) ; month=XBYTB(8); bcdconv(month); serial<':' ) ;
day=XBYTB(7)1 bcdcoov(sec); serial(OxOD); serial!OxOA); } 416
//display date forever //send out 2 for 20xx //send out o for 20xx I /get year //convert and display //send out : to separate //get month //convert and display //send out : to separate //get day //convert and display //send out CR //send out line feed
•' ( l C
I C \
~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? the address of the first RAM location belonging to general-purpose applications. is
4- Give the C statement to set the month to October. S. Gh·e the C statement to set the year to 2009.
SECTION 16.3: ALARM, saw, AND IRQ FEATURES OF THE DS12887 CHIP In trus section ,ve program the ';;-OW, alarm, and interrupt features of the D512887 ~p using Assembly langu age.
n,e;e powerful features of the DS12887 can be very useful in many real-world applications. programming the
saw feature
R5:J
~e S-O.W pin provides '."s a square wave output of various frequencies. The frequency is chosen by bits RSO · of register A, as shown 1n Figure 16-6. In addition to choosing the proper frequency, we must also enable the ':-OW bit 111 register B of the DS12887. This is shown below. ;RO= OAH,reg A address ;turn on osc .• lll0=RS4 -RS0 4HZ SQW ;send it to Reg A of OS12887 ;RO= OBH, Reg B address ;get reg B of OS12887 to ACC ;need delay for fast 8051 ;let 4Hz come out ;send it back to reg B
MOV R0,#10 MOV A,#2EH MOVX @RO , A MOV R0,#11 MOVX A, ilRO ACALL DELAY SETS ACC.3 MOVX @RO,A
I
I
OV2
I
OVl
ovo
I
RS3
UCP
Update in progr.,ss. This is a read-only bit.
OV2
OVl 1
0 RSl 0 0 0
0 0 0
0 0 1 1 I I I
I 1 I
F.,_ lW.....,
UIP
RS2
0 0 0 0 1
RS2
RSl
I
RSO
ovo 0
will tum the oscillator on
RSl 0
RSO 0 I 0 I 0
0 I
SQW Output Frequency None
256 Hz
1 I
0 I
0 0 0 0
0 0
0 I
l I
0 I
128 Hz. 8.192 kHz 4.096 kHz 2.048 kHz 1.024 kHz 512 Hz 256 Hz (rept"at) 128 Hz (repeat) 64Hz 32Hz
l l 1 1
0
0
16Hz
0 1 I
I 0 l
8 Hz
I
1 I
I
1
0 0
I
4Hz 2Hz
Ill A bltl f o r ~ c _ . . . i .i the SQW Output Pin
a,
M I 24/ 12 I DSE
1'1E I D
I SET
.,'
PIE
J
d UIE I SQ tes are update . SET I PIE I AJE I d and time and da st make SET - l}. ' . tiOn we mu • . uoting once ~rsecon[nitiaUza 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 ' bl lf PIE; ' n,erefore, J>I bit The Periodic interrup; is assert~ 1~:·not want to poll tt~er A. Remember the JRQ pin of th . . register C if>,e 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 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 . Alarm interrupt enable. . (hh·mm:ss) are the sa nd once-per•mJnute, all three bytes of th~ real tt~e the ·cases of on~-per·se:be;that AIE allows the bit in register C and of hh:mm:ss. Also, if:i~;,rt low the IRQ p,n.f and on':""p~·:;:i.u~~;dware interrupt vers•o;;AlE wUI simply direct the A I generation o . In other words, ff ton Al generation. . no e ec . h IRQ output pm. of register C into t. e
~~7
!'I
ll,e
AIE
.,
'
• I
UIE
(.
~:::i
t:!
WE;
See the D5J2a87 data sheet I, the square-wave frequencyWgenerated ou ut pin of . t r A will show up on the SQ tp by the RSO . RS3 options o reg1s e
SQWE Square wave enable .. If~
(
the DS12877 chip. . d ta format ond OM~ !:binary (hex) data forma t Data Mode. OM ; 0. BCD a 12-hour mode 24/12 I for 24-hour mode and Ofor OSE Daylight saving enable
J
OM
on
Figure 16-7. Pl!, AJE, and SQWE bits of Rtgis t•r B
On +SV
lt1(
DS12887
8051 ALE
AS
WR
vcc
R/W
RESET
RD P0(0..7)
.
OS AD(0..7)
Us
SQW
MOT
-cs
,
BUZZER
CNO ;.
'.
--==-
Pl.7 Figure 16-8. Using SQW to Sound a B=or
IRQ output pin and Interrupt sources Interrupt request {IRQ) is an output pin for the DS12887 RTC chi
(br·
.
.
• 1t ~~active low signal There are three possible
sources that can activate the IRQ pin. They are (a) alarm interrupt We can choose which source to activate the IRQ pin using the inte ' penod.tc Pulse interrupt, and (c) update intemJpl non we discuss the alann and periodic interrupts and refer reade~~t~:ble bit in register B of the DS12887. ln this sec· 418
DS12887 data sheet for the update interrupt.
THE80s1 MICRQc ON°fROLtER ANO EMBEDDED SYSTEMS
fl1ealarm and IRQ output pin
. . te jhe alarm mterrupt can be programmed to occur at rates of (a) once per day, (b) once per hour, (c) once per mmu ' attd (d) once per second. Next, ,ve look at each of these.
once-per-day alarm Table 16· 1 in Se~tion 16.1 shows that address locations 1, 3, and 5 belong to the alarm seconds, alarm _minutes, and 11,lflll hours, respectively. To program the alarm for once per day, we write the desired time for the alarm mt~ the hour, a,iJlUle, and second_ RAM locations 1, 3, and 5. As the clock keeps the time, when all three bytes of hour, ~nute, _and second for the real time clock match the values in the alarm hour minute and second, the AF (alarm flag) btt 1n regJster Cof the 0512887 ,vill go high. We can poll the AF bit in regist;r C whlch is a waste of mkrocontroller resources, or UoWthe ~Q pin to be activated upon matching the alarm time with the real time. It must be noted that in ?rder to use 1 the IRQ pm of th~ ~12~7 for an alarm, the interrupt-enable bit for alarm in register B (AlE) must be set high. How to ~ ble the AIE bit m reglSter Bis shown shortly.
once-per-hour alarm To program the alarm for once per hour, we write value llxxxxx into the alarm hour location of 5 only. Value 11roxx means any hex value of FCH to FFH. Very often we use value FFH.
Once-per-minute alarm To program the alarm for once per minute, we write value FFH into both the alarm hour and alarm minute locations of 5 and 3.
Once-per-second alarm To program the alarm for once per second, we write value FFH into all three locations of alarm hour, alarm minute, and alarm second.
Using IRQ of DS12877 to activate the 8051 interrupt We can connect the TRQ of the 0512887 to the external interrupt pin of the 8051 (INTO). This allows us to perform • task once per day, once per minute, and so on. The program given i.n the next two pages will (a) sound the buzzer a>ruiected toSQW pin, and (b) will send the message "Y~S'.' to the serial port once per minute at exactly 8 seconds past !he minute. The buzzer will stay on for 7 seconds before 1t 1s turned off.
:· --·- ··SEND HELLO TO SCREEN 8 SEC PAST THE MINUTE ;------- USING ALRAM IRQ ORG 0 ·SOME INITIALIZATION WMP MAIN ' ORG 03 ·GO TO INTERRUPT SRVICE ROUTINE LJMP ISR_EXO ' lOOH ORG 11>.IN: ·INTO (EXO ) IS ENABLED MOV IE,#81H ';MAKE IT EDGE-TRIG SETS TCON.1 ·SERIAL !'ORT SET UP IIOV THOD,#20H • MOV SC0N,ll50H ; 9600 MOV THl,#·3 Sl!TB TIU
Dsuae, RTC 1NTllllfACING AND PllOGllAMMING
t19
;·······TORNING ON o
..
•
•
., .• I
'
• I
•
l
''J
THE RTC A address ·RO•OAH, Reg n osc., sow-8HZ HOV RO. #1 , i 06-04 turn O 12887 MOV A,#20H ;010 ~ o Reg A of OS uovx •RO A ; send 1t t r• ' • . mode ········Setting the T1me · •·• •· • ddress i g • MOV RO.fill ;Reg 8 a daylight saV n MOV A, #83H ;BCD, 24hrs, ACALL DELAY ;send it to Reg B MOVX @RO.A 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 ;set seconds•8 MOV RO• #3 ; point to mi nu tes address MOV A, #OFFH ;ONCE PER MINUTE MOVX @RO,A MOV RO, #5 ; MOV A, #OFFH ;FF FOR THE HOUR MOVX @RO,A ; ACALL DELAY MOV R0,#11 ;Reg B address MOV A, #23H ;07• 0 to update,AIEcl to allow IRQ MOVX i/RO, A ;activae INTO of 8051 ·········READING TIME • PLACE READING TIME CODE HERE ;·······SERIAL TRANSFER SERIAL: CLR IE.7 ;DISABLE EXTERNAL INTERRUPT MOV SBUF,A Sl: JNB TI, Sl CLR TI SETB IE . 7 ;RE-ENABLE THE INTERRROPT RET ;•-·!SR SENDS ·YEs• TO SCREEN AND SOUND THE BUZZER ORG SOOH ; the ISR for the IRQ of DS12887 ISR_EXO: MOV RO, #12 ;Reg C address ACALL DELAY MOVX A,@RO ;READING REG C WILL DISABLE THE IRQ MOV RO, #11 ;Reg B address ACALL DELAY MOVX A,ilRO ACALL DELA'i SETB ACC.3 ;LBT SQW COMB OUT OF RTC SE:TB Pl. 7 ; ENABLE THE AND GATE TO so•~ACALL DELAY v ... u BUZZER MOVX •RO ,A MOV A,#'Y' ACALL SERIAL MOV
!
'
) j
A,#'E'
ACALL SERIAL MOV A,#'S' ACALL SERIAL 420
Tlil: 80Sl f\1JCRoc
ONl'Rot
lER ANO EMBEDDED SYSTEMS
ACALL DELAY_l 14QV RO, #11 ACALL DELAY MOVX A,@RO CLR ACC. 3 ACALL DELAY MOVX @RO ,A CLR
;7 SEC DELAY TO HEAR THE BUZZER ;Reg B address ;BLOCK SQW FROM COMING OUT OF RTC ;SHORT DELAY TO LET RTC REST ;BEFORE ACCESSING IT AGAIN ;TURN OFF THE AND GATE ;RETURN FROM INTERRUPT
Pl. 7
RBTI
Regarding the last program, several points must be noted. 1. Ill the beginning of th.e program we enabled the external hardware interrupt and made it edge triggered to match the IRQ of the DS12887. l
Ill register B, the AIE bit was set high to allow an alarm interrupt.
3. Ill the serial subroutine, we d isabled the external interrupt INTO to prevent conflict with the TI flag.
1 In the JSR, we enabled the SQWE to allow a square wave to come out of the RTC chip in order to provide pulses to the buzzer. We disabled it at the end of JSR after 7 seconds duration in the DELA Y_J subroutine. ;
In the !SR, we also read the C register to prevent the occurrence of multiple interrupts from the same source.
The periodic interrupt and IRQ output pin The second source of interrupt is the periodic interrupt flag (PF). The periodic interrupt flag is part of register C. Jt will go high at a rate set by the RS3 -RSObitsof register A. Th.is rate can be from once every 500 ms to once every 122 µs as shown in Figure 16-11. The PF becomes 1 when an edge is detected for the period. Just like alarm interrupt, the periodic 111terrupt can also be directed to the lRQ pin. To use IRQ. the interrupt-enable bits of PIE in register B n1ust be set to 1. In ocher words, we can poll the PF bit of register C, which is a waste of the microcontroller's resources, or it can be directed ID the hardware IRQ pin. If we set PIE = 1, the IRQ pin is asserted low when PF goes high. While the alarm intern,pt gave us the options from once per day to once per second, the periodjc interrupt gives us the option of subsecond inter· rupts. For example, we can write a program to send a message to the screen twice per second (2 Hz). The following code fragments show how to send the message "HELLO" to the screen twice per second using the periodic interrupt with the help of hard ware [RQ (see Figure 16-9).
+5V
--
0512887
8051 AU! WR
R5
-
P0(0•.7)
-INTO
-
AS R/W DS
vcc RESET
AD(0 .. 7)
SQW
IRQ
MOT
BUZZER
cs GND
-Pt.7 ..... l'-9, Utlng DSUll7 lllQ la Activate an 8051 lntel'Npt
Osu.e, RTC INTDl'ACING AND ,aoGllAMMING
, jlRQFj lRQF
s
Pf
I
I
AF
UF
I
0
0
0
J
0
I: if PF s PIE s l or AF s AJE" I or UF" U!E" I (PIE, AIE, and UlE are the bits of Register B)
. . • ts can be generated at a rate of once Periodic interrupt flag. Penod1c mterruP . set by bits RS3. RSO of register every 500 ms to once every 122µs. 'f!'e rate ,sed {or the period- We can poll this A. The PF b<:comes 1 when an ed~e is detect . f 0512887 can be asserted or, with the help of bit PIE of reg.st~r 6, the P~5 wLll be done if the PIF low for the hardware interrupt version of this '(· 8 1 ther (if both are bit of Reg 8 is set to J. That is, PF and PIE of reg,ster oge. .. 1) will allow IRQ to be asserted low. Reading PF will clear ,t, and that IS
PF
!R~
I
how we deassert the IRQ pin.
•
.•
••
AF
Alarm interrupt flag. The AF becomes I when the current real time matches the alarm time. AF and AlE of register B together (if both are 1) will allow the IRQ to be asserted low when all the three bytes of the real time (yy:mm:dd) are the same as the bytes in the alarm fune. The AF also becomes 1 for cases of once per second, once per minute, and once per hour alarm. Reading AF will clear, it and that is how we deassert the lRQ pin.
UF
See the 0512887 data sheet.
'
• I
I 'J
...
..
Figure 16-10. Register C bits for Interrupt Flag Sources
I
DV2 I· OVl I· DVO I. RS3 I. RS2
uw
UIP
Update in progr0$S. This is a read-only bit.
DVZ 0
DVI OVO 1 0 will tum the oscillator on
RS3
0 0 0 0 0 0 0
0 t I
1 I
I
I I
l
RS2 0 0 0 0 1 1 I
1 0 0 0 0 I I I I
RSI
RSO
0 0
0
I I
0 I 0
0 0 I I
0 0
Tpi PERIODIC INTERRUPT RATE None 3.9062 ms 7.812 ms 122.070 µs 244.141 µs 488.281 µs 976.5625 µs 1.953125 ms 3.90625 ms 7,8125 ms 15.625 ms 31.25 ms 62.S ms 125 ms 250 ms
I
1 0 I
0
1 0
I I
1
0
0
0
1
I 0
I
1
SOOms
Figure 16-11. Rtgisl~r A bits for Ptrio,rIC In terrupt R
SQW Output Freq.
;
MlCRoco111
..
:l"i]
None
256Hz 128 Hz 8.192 kHz
4.096 kHz 2,048 kHz 1.024 kHz 512 Hz 256Hz 128 Hz 64HL 32Hz 16Hz 8Hz 4Hz
2Hz
••• 'Ili Esos1
j RSl j RSO
TROttERA
-
ND EMBEDDED SYSTEMS
1endi ng Hl'ILLO to screen twice p er second CRG
0
LJKP MAIN ORO
03
WMP ISR_ EXO 100H ORO MOV 1£,#BlH ;INTO (EXO ) I S ENABLED TCON.l SITB :MAKE IT EDGE-TRIG ,pIAL PORT SET-UP 1 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 ,set hours to 16 MOVX f/RO,A 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 ;point to HR loc MOV RO, #4 ;read hours MOVX A,lilRO ACALL DISPLAY ;SEND OUT SPACE MOV A, #20H ACALL SERIAL MOV RO, #2 ;point to minute loc ; read minute MOVX A,@RO ACALL DISPLAY ;send out SPACE MOV A, #20H ACALL SERIAL ;point to sec loc MOV R0,#0 ;read sec MOVX A,411RO ACALL DISPLAY HOV A, #OAH ;eend out CR A.CALL SERIAL IIOV A,#ODH ;send LF
··.....·~
, forever Time ;Read and displ ay
ACALL sERlAL SJHP OVl 1······ ·-·SMALL DELAY
osLAY:MOV Dl:
/
• •
•• •
'\
••
. I
I. I
,
(
~=•z
R7,#2S0 R7, Dl
""" RET ;----- ······--CONVERT BCD TO ASCII DISPLAY: HOV B,A SWAP A A!IL A, #OFH ORL A, #)OH ACALL SERIAL MOV A, B ANL A, #OFH ORL A, #30H ACALL SERIAL RET __________ __
AND ssND IT 'l'O scREEN
..
·-----·---'
SERIAL: CLR
·DISABLE INTO INTERRUPT IE.7 ' HOV SBUF,A Sl: JNB TI,Sl CLR TI ·RE-ENABLE INTO INTERRUPT SETB IE.7 ' RET ·-----!SR TO SEND •HELLO" TO SCREEN TWICE PER SEC ' ORG SOOH !SR EXO: HOV- R0,#12 ;Reg c address ACALL DELAY HOVX A,@RO ;READING REG C WILL DI SABLE · THE PERIODIC INTR ' MOV
A,H'H'
ACALL SERIAL MOV A,#'E' ACALL SERIAL MOV A,#'L' ACALL SERIAL MOV
A,-'L'
ACALL SERIAL MOV
A, It '0'
ACALL SERIAL RETI
Review Questions 1. 2. 3. 4. S. 6. 7.
Which bit of register 8 belongs to the SQW pin? True or false. The CRQ out pin of DS12887 is active low. Which bit of register B belongs to alam, interrupt? Give the address locations for hh:mm;ss of the alarm. If the source of activation for IRQ is alarm, then explain how th , . Wh.1t is the difference between the AF and AJE bils? e IRQ Pin IS •c:tivall!d. What is the difference between the PF and PJE bils?
~
f
I 11
• \I
•
) Ir
l'
~r ~
• rs
•0
s~ Ir
,1
U. C
C. F
U. C
It}
Ii ,I
;. D
s
Ii I!. F
19 [ !I 11
l\ !l. 1
:t I
15. 1
ll ~- '
l•
~·
». n. l2. 13 lt lS
5111,1MARY · Th timing of ADO· AD7 of 1llii (h.1pter beJ;,1n by de,;cnbing the function of each pin of the DS12887 RTC ch,~. che h as the 74LS373. The M ci,1~7 rruakhl'11 tht- tuning of PO of the 8051 eliminating the need for an external at fsuc f the RTC were .. ..._ ___ , • t· ns Various eatures o 0,1~7 c•n "" u~-... to provide a real·ttme clock and dates for many app 1,ca 10 • f ' ~ ' •nd numerous programmJng examples were given.
pROBLEMS q:(TION lb!· DS12.887 RTC INTERFACING
I The DSl 2887 OIP package is a(n) -pin package. t Which pins are assigned to V" and GNO? 1 In the 0512887, how many pins are designated as address/data pins? t True or false. The 0512887 needs an external crystal oscillator. 5. True or false. The DS12887's crystal oscillator is turned on when it is shipped . ._ In 0512887, what is the maximum year that it can provide? i. Descnbe the functions of pins 05, AS, and MOT. g, RESET is an (input, output) pin. 9 The RESET pin is normally (low, high) and needs a (low, high) signaJ to be activated. 10 What are the contents of the 0512887 time and date registers if power to lhe V" pin is cut off? 11 OS pin stands for and is a.n (input, output) pin. U. For the 0512887 chip, pin RESET is connected to (V.,, GNO). ll OS is an (input, output) pin and it is connected to pin of the 8051 . ll. AS is an (input, output) pin and it is connected to pin of the 8051. 15 ALE of 8051 is connected to pin of the 0512887. 16. IRQ is an (input, output) pin. 17. SQW is an (input, output) pin. ta R/ W is an (input, output) pin. 19. DS12887 has a total of bytes of NV-RAM. lO. What are the contents of the 0512887 time and date registers if power to lhe V" pin is lost? 21. What are the contents of the general-purpose RAM locations if power lo lhe V" is lost? !2. When does the DS12887 switch to its internal battery? ?I. What are the addresses assigned to the real-time clock registers? lt What are the addres.qes assigned to registers A· C? lS. Which register is used to set the AM/PM mode? Give the bit location of that register. l6. Which register is used to set the daylight savings mode? Give the bit location of that register. ll. At what memory location does lhe 0512887 store the year 200n 28. What is the address of the lasl location of RAM for the OSI 2887? 29. Write a program to dlsplay the time in AM/PM mode. lO. Write a program to get the year data in BCO and send it lo ports Pl and P2. lt. Write a program to gel lhe hour and minute data in binary (hex) and send it to ports Pl and P2. 32. Write a program to set the time to 9:15:05 PM. l3 Write a program to set the time to to 22:47:J 9. ~ Write a program to set the date to May 14, 2009. ll. On what day in October, is daylight savings time changed?
SECTION 16.2: 0512887 RTC PROGRAMMING 1N C 36 Wnte a C program to display the time in AM/PM mode. : Write a C program to get the year data in_BCO and ~d it to ports Pl and P2. l9 Wnte a C program to get lhe ~our and minute data tn binary {hex) and send it to rts Pl d P2 t> Write a C prQgram to set lhe time to 9:15:05 PM. po an · 41 Wnte • C program to !>Ct the time to 22:47:19. ll. Wnte a C program to set the dale to May 14, 2009. In Queshon 41, where did you get the 20H?
~;;;R;T~C~INTl!;;;:;;R~F~A~C;IN;G;;-;;A~N~D;;;PR~OG;;-~RAM~;M~l~ N~G:----~~.;._...;;...-.a:..._--c--"'.;;;_~---~.a.._-.~~-
/
•
••• ' I
•
'
, I
'I
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: t' 52. What is the lowest period that we can use for the perioodd,~ ~t;r;rp;' 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? 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? 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. 65. Write a program to generate a 64 Hz square wave on the SQW pin.
/
ANSWERS TO REVIEW QUESTIONS SECTION 16.1: 0512887 RTC INTERFACING I.
True
2. 3. 4. 5.
9 114
r
True AS
6. False
SECTION 16.2: DS12887 RTC PROGRAMMJNG INC 1. True 2. 3. 4. 5.
0·9 OEH (14 in decimal) XBYTE(S]:OxOA; XBYTE(09J=Ox09; where the 20 part of 2009 JS . assumed. ·
SECTION 16.3: ALARM, SWQ, AND ffiQ FEA11JRE L D3 of DO • 07 S OF THE DS12887 CHIP 2. True 3. D5 4. Byte addresses of 1, 3, 5 5. u_ the AIE bit of Reg B is set tQl, then the IR . . high when the alarm time and real tim Q pm is activated . 6. The AP bit in register c becomes hi h e values match. · This happens due tO the AF bit in register C going Bsimply allows the AP to be direct~ when the alarm time and 7. The PF bit in register C becomes hi tohthe IRQ pin. real time values m ister B simply allows the pp to be wt en the edge is det a tc.h, while the AIE bit of register rec ed to the IRQ Pm. . ectect for the periodic . i t n errupt, while the PfE bit of reg·
ff'
426
Tlil: 80St MrcRoc: ONTROLL
-
ER ANO EMBEDDED svsT&fS
CHAPTER17
MOTOR CONTROL: RELAY, PWM, DC, AND STEPPER MOTORS
OBJECTIVES Upon completion of this chapter, you will be able to:
>
> > > >
> > > > > >
> >
Describe the basic operation of a relay Interface the 8051 with a relay Describe the basic operation of an optoisolator Interface the 8051 with an optoisolator Describe the basic operation of a stepper motor Interface the 8051 with a stepper motor Code 8051 programs to control and operate a stepper motor Define stepper motor operdtion in terms of step angle steps per revolution, tooth pitch, rotation speed, and RPM ' Describe the basic operation of a DC motor Interface the 8051 with a DC motor Code 8051 programs to control and operate a DC motor ~ how PWM is used to control motor speed
; 427
. .th relays, optoisolators, stepper motors . d shows 8()51 interfaClJlg WliJ>ed. Then we show their interfacing Withatid This chapter discusses motor control an d toisolators are descr characteristics of DC motors are cl ;...... ex: motors. In Section 17.1, the basics of relays an . Op e 8051 is shoWll· The . WM ( uJse width modula-:-'~ 8051. In Section 172 , stepper motor interfacing with ~ill also diSC:USS the topic of P P lion). W, in 5ect1on 17.3, along with interfacing to the_S051. We 1 use both Assembly and C in our programmmg ex:arnp es.
~
•
,I'
SECTION 17.1: RELA VS AND OPTOISOLA . TORStions of electromechanical relays, solid-state relays, reeci This section begins with an overview of the bas•: opera th to the 8051. We use both Assembly and C language switches, and optoisolators. Then we describe how to mterface ern programs to demonstrate their control.
c\11
•
Electromechanical relays ., '
I
.•
l I I
/
11'
. . d · · d strial controls auton,obiles, and applian- It A relay is an electricaUy controllable s,v1tch widely use lll lll u ' •••· allows the isolation of two separate sections of a system with two different voltage so~rces. For example, a +5V system can be isolated from a 120V system by placing a relay between them. One such relay 15 called 3':' electromechanical (or electromagnetic} relay (EMR) as shown in Figure 17-1. The EMRs have three cornpon~nts: the cot!, spnng, 3':'d contacts. In Figure 17-1, a digital +SV on the left side can control a J2V motor on the right side without any physical contact be~een them. When current flows through the coil, a magnetic 6eld is created around the coil (the coil is energized), "'.hi~ causes the armature to be attracted to the coil. The armature's contact acts li ke a switch and closes or opens the °;"Cmt. When the coil is not energized, a spring pulls the armature to its normal state of open or closed. ln the block 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:
• 111
' "°
111
(II
g-,
1,tJ
I))
I 1? ID
di fa
"d Normally Closed
~Common
t
l)ivl
Common
t
Normally
Open
D !!1111 din·e
Normally Open
T
ll'!ry
<•l SPST
Cb) SPOT
Normally Closed
L_
Common Normally Open
k) DPDT Figun, 17-L R•l•y Diag,ams
428
Tli£ 80St MlCJtoc oNT
-
llOLLl!R AND EMBEDDED svsfEMS
\;
---
t,~lt 17-1: Selected DIP Relay Characteristics (www.Jameco.com)
,.~ ,o.
Contact Form
Coil Volts
Coil Ohms
Contact Volts-Current
~"'CP
Sl'ST-NO
SVDC
500
1oovDC-O.SA
,;
SPST-NO
SVDC
500
1oovoc-0.sA
1-"'47tCr
SPST-NO
12VOC
1000
JOOVDC·O.SA
;ijiscP
SPST-NO
12VDC
1000
lOOVDC-0.5A
:%,°:,Cl'
DPOT
SVDC
62.5
30VDC·1A
•
Ill
It
.
. It
(Cir
:II.
let
cl),
ht
d
,ol
..-
1 The contacts can be normally open (NO) or normally closed (NC). In the NC tn:ie, the contacts are closed when the 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 rurrent can be from a £ew mA to 20 mA. The relay has a minimum voltage, below which the coil will not be energized. This minimum voltage is called the "pull-in" voltage. In the datasheet for relays we might not see current, but rather coil resistance. The V / R will give you the puU-in current. For example, i( the coil voltage is SV, and the roil resistance is 500 ohms, we need a minimum of 10 mA (5V/500 ohms= JO mA) pull-in current. 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/current 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
10
DS89C4x0
+12V
UL\12803
4.7k
II 8 _ __,!6LJ l'J.O,J---.__ _;;:.i..f;;>.Lj:....:.
8
9
, --
,,
+SV
+SV
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: MOV R4,#100 Ml: H2: MOV R3, #2S 3 H3: OJNZ R3, H3 DJNZ R4 , H2 DJNZ RS, Ml
•
..'
••
-
•
•
I \
I
•j
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. The entire relay is made out of semiconductor mate1ials. Because no m~an1cal parts are involved m s ol~d-s tate relays, their switching response time is much faster than that of electromecharucal relays. Another problem w,th the electromechanical relay is its life expectancy. The life cycle for the electromechanical relay can vary from a few hundred thousands 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 ) Part No. Contact Style Control Volts Contact Volts 143058CP SPST 4·32VDC 240VAC 139053CP SPST 3-32VDC 240VAC 16234JCP SPST 3-32VDC 240VAC 17259JCP SPST 3·32VDC 60VDC 17S222CP SPST 3-32VDC 60VDC 176647CP SPST 3·32VOC 120VOC
lm,ng SIS
Conta ct Current 3A
11is lll hil
25A
1!119t
ll!d&
lOA
~
-
2A
4A
SA
120VAC -
,
75
8051
\.v ' ,
-
16234!
3
PI.O
~~
4
I ZERO VOLTACE 0 1\CUJT
FAN
2
.
I
~ I
.
Flptt 17•3. 8051 Conntclion to a Solid-State R~lay
..
T!iE 80St MICR.,...,..
"'-ONllt
-
OLLER ANO EMBEDDED sYS'fDIS
,.,ti.
'Il-
a-
,.
It.
•• n-
--
--
-
M
WHEEL
A
WHEEL
G
N E T
MAGNET
REED SWITCH
REED SWITCH
(Closed)
(Open)
Rgurt 174. Reed Switch and Magnet Combination
Reed switch Another popular switch is the reed switch. When the reed switch_is pla~ed in a magnetic field: ~e contact is dosed. When the magnetic field is removed, the contact is forced open by its spring. The reed switch lS ideal for moist and uwme environments where it can be s ubmerged in fuel or water. They are also widely used in dirty and dusty atmospheres since they are tightly sealed.
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 current 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, separa~ 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 t 6
IL074 OPTOISOLATOR 8
2
2
3
3
ILQ74 OPTOISOLATOR I 2 3
4
~g,,l't 17-S. Optoloolator Pad
431
JL074 OPT0IS0LATOR
. used in conunuOJ·cation 0pto,solotors are ai:, wide~ allows a computer ~ : uipment such ii!. m ems. . · k of damage eq It'd to a telephone Tine without ns . nd receiver connec the transmitter a pcwersurges. Thegapbetwtheenl trical current surge froJTI of optoisolators prevents e e ec reaching the system.
8051
Interfacing an optoisolator
-
•
•
'
2
7
re Package with th t contain
The optoisolator comes in a sma four or more pins. There are also packages at ·solator more than one optoisolator. When placing an op o1oltage . . wc mu.s·t use .two. separate between two c1rcmts, .6 vUnlike 17 sources, one for each side, as shown in Ftgu~h mlcroconrelays no drivers need to be placed between e trolle;/digital output and the optoisolators.
+12V
6
Pt.0
. II
•
8
3
•
;f'
•
l
4
5
+SV
Figure 17-6. ControIf,ng a Lamp via Optoisolator ~~~~~~~~,
A
'
Review Questions
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 3. What is an NC relay? . ,
I
I
•
!IIP I
Ho ~
4. Why are relays that use coils called electromech•:~ relays . 7el , 5. What is the advantage of a solid-state relay over 6. What is the advantage of an optoisolator over an EM r ay ·
jrlllll jr IJIIJ
l11111U
111111! 11111!1
SECTION 17.2: STEPPER MOTOR INTERFACING
llrota
This section begins with an overview of the basic operation of stepper 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.
§
?dip,
s
Average North
kt 1:11. a
... I
Stepper motors
thii
"'5
A stepper motor is a widely used device that t~anslates electrical pulses in.to m.echanical move~ent. In applications such as disk drives, dot matrix printers, and robotics, the stepper motor is used for position control. Stepper motors commonly have a permanent magnet rotor (al called the shaft) surrounded by • stator (see Figu re 17-7). There a re ~ steppers called variable reluctance stepptr motors that do not have a PM rotor. The most common stepper motors have four stator Wind· tha are paired with • cent~r-tapped common as shown in Figure type of stepper motor IS commonly referred to as a four-phase or : This stepper motor. The center tap allows a change of current d . . Wu polar of two coils when a winding is grounded, thereby resulti uection in e~ch change of the stator. Notice that while a conventional m:1 i.n • polanty freely, the stepper motor shalt moves in a fixed re ata or .shaft runs which allows one to move it to a precise position. ~ ble increment, movement is possible as a result of basic magnetic th is repeatable fixed the same polarity repel and opposite poles attract ;;:ry ':"he': poles of rotati<>n is dictated by the sta tor poles. The stator ~Ole: direction of the by the current sent through the wire coils. As the d. . are determined •Ieetion of the current
") C
Average South
l~r .1
lliOci
Figure 17-7. Rotor AUgnment
COM
F·
ig~ l 7-8. St1tor Windings Confipntioll
THI! aos1 M1c11.oco
IIITROLl.liR AND EMBEDDED SYSTEMS
-
r,ttle 17-3: Nom1al 4-Step Sequence ('),~W ....
Sttp I
Winding A
Winding 8
Wi nding C
Wind ing D
I
I
0
0
I
2
I
I
0
0
)
0
I
l
0
4
0
0
I
I
CounterClockwi..c
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. 5 changed,
Step angle How much movement is associated with a single step? This depfflds on the internal construction of the motor, in particular tht number of teeth on the stator and the rotor. The step a11gle is the minimum degree of rotation associated with a single step. V,rious motors have different step angles. Table 17-4 shows 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 lo rotate one complete rotation or 360 degrees (e.g., 180 steps ,
!degrees ; 360). . It must be noted that perhaps contrary to one's initial impres-
sion, a stepper motor does not need more terminal leads for the •ator to achieve smaller steps. All the stepper motors discussed in this section have 4 leads lor the stator winding and 2 COM
Table 17-4: Stepper Motor Step An gles Step Angle
Steps per Revolution
0.72
500
1.8
200
2.0
180
2.5
141
5.0 7.5
72
15
24
48
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 trO ding are con ' transistors as d n·vers, asshown · 3 The four leads of the sta tor wm . the stepper n,o tor win inused 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 h an internal d10 e to 3 2 as the use of transistors as drivers is that the uLN
tu';;o
..
•
BACK:
MOV MOV RR
•
•
DELAY
•
Hl: H2:
••
•
'
A
ACALL DELAY SJM2 BACK
•
.,
·load step sequence tor e to mo ;issue sequenc · se ·rotate right clockwi ';wait ;keep going
A,#66R Pl,A
MOV MOV DJNZ DJNZ RET
R2,#100 R3,#2S5 R3,H2 R2,Hl
Change the value of DELAY to set the speed of rotation. We can use the single-bit instructions SETB and CLR instead of RR A to create the sequences.
+S___.. To stepper motor
I,
supply DS89C4x0
4.7k 4.7k 4.7k 4.7k
Unipolar Stepper Motor
ULN2003
9
-
Pl .O Pl.2
. .•
:
Pl.J
.
:
V
Pl.I
:
-
-
•
""' ""
Use one power supply for the motor and ULN2003 and another for the so.;1
Steps per second and rpm relation The relation between rpm (revoluti
.
ons per rninute), steps per rev I .
o ution, and ste
Stq,s per 5eeoud " pm l< Steps
per revo/util)/1
60
ps per second is as roUows.
-
11il! 80511'.fJCtt 0CONTttOLLE
-
RAND EMBEDDED SYSTEMS
,
ll"four-1tep sequence and number of teeth on rotor l1'! ,witrhnigS<-qi1t·n« ,ho"n earlier m Table 17-3 is called the 4-step switching sequence since after four. steps the f11Jt tw<' ,.,nJ,ng,, will I:,(' "ON" How much movement is associated with these four s teps? After cornpletmg eve~
1,,Jtll'J'S• th~ rotor mo,"" only one tooth pitch Therefore in a stepper motor with 200 steps per revolution, the r~t~ ,a,!011'\'lh ,mce 4 "50 ~ 200 steps are needed ; 0 complet~ one revolution. Titis leads to the conclusion that the miru·
'IIJJft •tcp an19e 1s always a function of the number of teeth on the rotor. In other words, the smaller the step angle, the p-1tltl'lh the rotor pas..<1."1. See Example 17-2. l,.10\Jngat Exa~ple 17·2,one might wonder what happens if we want tomove45 degrees, since the steps are 2 degrees ...i, To allow for finer resolutions, all stepper motors allow what is called an B·slep switching sequence. The 8-step ~ ,s also called lralf-steppillg, since in the 8-step sequence each step is half of the normal s tep angle. For example, a ,....-with a 2-degrce step angle can be used as a 1-degree step angle if the sequence of Table 17·5 is applied.
(Uttlplt 17-2 Wnte • program to rot,,te a motor 64° in the clockwise direction. The motor has a step angle of 2°. Use the 4-step s,equence in Table 17-3 Solution: Amotor with a 2° step angle has the following characteristics:
5'ep angle, 2° S4eps per revolution: 180 :>lo. of rotor teeth: 45 \lovement per 4-step sequence: s• To move the rotor 64°, we have to send eight consecutive 4-step sequences, i.e., 32 steps.
ORG MOV MOV
OOOOH A,lt66H
R0,#32 RR A Pl,A MOV ACALL DELAY DJNZ RO,BACK END
BACK:
~e 17-5: Half-Step 8-Step Sequence
~
......_
Step II Winding A I 1
2
Windjng B 0
WindingC 0
WindingD
l
0
0
1
1
0
3
0
0 0 0 0 0
I l
0
4
0 I 1
0 0 0
1
1 I
5 6 7 8
0 0 0
0
1
Counter.. Clockwise
l!o-roR CONTROL: RELAY, PWM, DC, AND STEPPER MOTO RS 435
,
/ WindingC
Table 17-6: Wave D rive 4-Step Sequen:ding 8
0
0 0
I
2
0
3
0
4
0
Counter. Clockwise
0 0
1
0 0
Winding D
1
0
•
, f the switching rate. Notice in Example 17-t Motor speed /s) is a function o . eed The motor speed measured in steps per second (steps achi'.eve various rotation sp s. . d eIay loop, we can that by changing the 'length of the time
'
Holding torque haft at standstill or zero rpm condition, the "W'th the motor s . . Th'1s ·is meas=.,.. ,...,.,, 1 , uowtng · is a definition of holding torque: th h ft from its holding pos1bon. The ,o .red break away es a ) amount of torque, from anextemal source, requi 10 "The unit of torque is ounce-inch (or kg-cm . with rated voltage and current applied to the motor.
,
Wave drive 4-step sequence
. d' ssed earlier there is another sequence called the wave drive In addition to the 8-step a_nd the 4-step sequ.ences tSCU se u~nce of Table 17·5 is simply the combination of I 4-step sequence. 11,s shown m Table 17-6. Notice that the 8-s ep . qT bl • and 17-3 respectively. Experimenting the wave drive 4-step and normal 4-step normal sequences shown 111 a es 17 6 ' with the wave drive 4-step is left to the reader.
-
rptr 17
•
Unipolar versus bipolar stepper motor interface There are three common types of stepper motor interfacing: universal, unipolar, and bipolar. They can be identified by the number of connections to the motor. A universal stepper motor has eight, while the unipolar has six and the bipolar has four. The universal stepper motor can be configured for all three modes, while the unipolar can be either unipolar or bipolar. Obviously the bipolar carmot be configured for universal nor unipolar mode. Table 17-7 shows selected stepper motor characteristics. Figure 17-10 shows the basic internal connections of all three type of configurations. Unipola~ stepper ~oto~ c~ be controlled using the basic interfacing shown in Figure 17-11, whereas the bipolar stepper requires H-Bndge circuitry. Bipolar stepper motors require a higher operational current than the unipolar· the advantage of this is a higher holding torque. ' Tab le 17-7: Selected Stepper Motors Ch aracteristics (www.Jameco .com) Part No. Step Angle Drive System Volts Phase Resistance 151861CP 7.5 unipolar 5v 9ohms t71601CP 3.6 unipolar 7V l640S6CP 7.5 20ohms bipolar sv 6rnA
~o 30 .:]F')F') m (a) Universal
:; '
Current
S50mA 350mA SOOmA
(Q) ~
Cb) Unipolar
(c) Bipolar
Figure 17·10. Common Sl•ppor Motor Type,
Tli!: 8051
l'.tlCJtoco
Nl'ROLLER. AND EMllEDDED SYSTDIS
+V Motor
cf IN 1001
4 7l fl Pl
.....
A
~+-C> B To Stepper Motor
..
1111d
--
I
0 Use11P120
OarUngton transistor if the motor needs several amps. figurt 1?•11. U$ing Tra.nsi_stors for Stepper Motor Driver
Using transistors as d rivers Figure 17-11 shows an interface to a unipolar stepper motor using transistors. Diodes are used to reduce the back E.\IF spike created when the coils are energized and de-energized, similar to the electromechanical relays discussed earlier. TIP transistors can be used to supply higher current to the motor. Table 17-8 shows the co,nmon industrial O.riing1on transistors. These transistors can accommodate higher voltages and currents.
Controlling stepper motor via optoisolator 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
-
.,
-
COM COM
-
NPN
PNP
Vceo (volts)
k(amps)
nrno
TIPIIS
hfe
2
1000
TfPl16
60 80
TIPIII
2
1000
TIPl 12
TIPl17
100
2
1000
TIP120
TIP125
60
5
1000
TIP121
TIP126
80
5
TIPl27
1000
TJP122
100
5
TIP140
TIP145
1000
60
10
TIP141
TIP146
1000
80
10
TIPl42
TIP147
1000
100
10
I000
lltOTOR CONTROL: RELAY, pWM, DC, AND ST EPPER MOTORS 43'7
, +12
-
+5
+~2
470 470 ,10 ,10 n..Q74
Oplo
8051 PI.O
,r•
16
2
ll
Jk
!.l
••
lk
5
ll,!;
lk
Pl.3
1
:t_
lk
Stepper Motor
--:-
. V
12
Pl.2
'
•
I
Pl.1
uLN2803
]I
u· rupo ar
•
--
-
.•
-
• 9
, 1111 '111 I
- L..
•
=
11,e optoisolotor provides
additional prolection of the 8051.
••. •
'
Use one power supply for the motor and ULN2003 and another for the 8051 .
-+12
• Figure 17•12. Controlling Stepper Motor via Optoisolator
J
Example 17·3 A switch is connected to pin P2.7. Write a program to monitor the s tatus of SW and perform the following: (a) U SW = 0, the stepper motor moves clockwise. (b) lf SW= I, the stepper motor moves counterclockwise.
Ill
Solution:
ORG MAIN: SETB
OH
P2. 7
MOV MCV
A, #66H Pl, A
JNB
P2.7,
TURN:
-
cw
RR A ACALL DELAY MOV Pl,A SJMP TURN RL A ACALL DELAY MOV Pl,A
CW,
SJMP
TURN
HOV MOV OJNZ DJNZ
R2, #100
DELAY, Hl: H2,
R!T END
R3. #2S5 R3, H2
R2,Hl
;starting address ;make an input ;starting phase value :send value to port ;check switch result ,rotate right ;call delay ;write value to PQrt ;repeat ;rotate left
;call delay ;write va1ue to port ;repeat
ti.iii
1l
'ii):
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. START: l!PT:
ORG OOOOH MOV RO, #04 MOV DPTR,#OlOOH 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. START: RP!:
ORG OOOOH HOV RO,j08 HOV DPTR,#0200H CLR A MOVC A,eA+DPTR Pl,A MOV ACALL DELAY INC DPTR DJNZ RO,RPT SJMP START 0200H ORG 09,08,0CH,04,06,02,03,01 DB END
Stepper motor control with 8051 C The 8051 C version of the stepper motor control is given below. ln this program we uld h , d . ollld>> (shift right) as was shown in Chapter 7. co a, e use << (sh.ift left) #include Void main() { while(l) {
Pl• Ox66; MSDelay(lOO); Pl• OxCC;
439
MSDelayllOO); Pl• Ox99; MSDelay(lOO); Pl = Ox33;
.
MSDe layllOO);
,. •
...
I
p . J,l~'
I
.,•
~
I
• •
onitor the status o A ,w,tch 1s connected to pin P2.7. Write a C program to m (a) 1r SW= 0. the stepper motor moves dockw,se. . (b) lf SW = l, the stepper motor moves co1mtcrclockw1se•
1J11 111
I,
•
•
l ••
,.... I"re r
Solution:
'iii, l
#include
-,J:d'
sbit SW• P2""7; void main()
-.:111'
,!~
{
'• •
SW
s
~~II
l;
while {1) { 1f{SW {
~· :,l!!lt I
,:l!lll1
== 0)
,jl!l
Pl . Ox66;
1Jlat,
MSDelay ( 100);
1iltd I
Pl• OxCC;
lb rt
MSDelay(lOO); Pl= Ox99; MSDelay(lOO);
lidlr
Pl• Ox33;
MSDelay{lOO);
~
J
'!fl(
{
~r
else 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
l
-
lh
unsigned ,nt x. y; forlx•O;x<127S;x,+t for
llil! 80S1 MIQt ocoNTRott
-
ER AND EMBEDDED SYSTEMS
jwvltW aucatlon, !he 4 t I' ,;equ,nc. p( a It. rp<·r molt•r ,t we• ,earl with 0110. A.i'l'f"'' motor" uh a &lcp angl,• of 5 J,1;r«" h,» _ ,t<>p, per revolution. i'1'y do we I J 1• •·r l1<,fween lh m1unn1n1roll,•r ,1nJ th<> ,tepper motor>
secnoN 17.3: DC MOTOR INTERFACING AND PWM • d ,sc:-ribe how lo interfuce ,1 ~ se<"llnn t.. i;111, with an ""'"' "'"' of th,· l, ,sic on.•r,itinn of OC motor,. Then "c '· f ' dth 1 ' ' t ti ept o pu se w1 ,,01,,r 111 the l!ll'll I 1n.11l), "e use As.,.,mbly and C language progr,,ms tn demonstra e 1e cone J u11nn (Pl'IIMJ and ,h,,w ht>w to control th,• 'l"-""l and dir('(tinn of a DC motor.
Ad1n'C1 currl.'nl (DC) motor~ another widely used d,•vice that tr,,nslatcs e l('(trical pulses into mech11nical ~,ove:n,111 In the OC motor we have onl) + and_ leads. Connectmg them to a DC voltage source mov~s the motor LO o_ne ,i,«IIOll 81· re,ersing the polarity, the DC motor will move ,n the opposite direction. One can easily exp('nment with !ht DC motor For ,•xample, small fans ust.-d ,n manv molherhoards to cool the CPU are run by DC motors. By con.«lil1g their leads to the+ and -voltage source, the DC motor moves While a stepper mo_t~r moves in st~ps of 1 to 15 J,glre,, thc DC motor mo\'es continuously. In a stepper motor, 1f we know the starting position we can easily count the 3'111berof steps the motor has moved and c,1 lculate the final pos1tlon of the motor. TI1is is not possible in a DC motor. lbtmaxinium spe.>d of a OC motor 1s indicated in rpm and 1s f;iven 111 the data sheet. The OC motor has two rpms: nololdand 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, drpa~. 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 "'H·Brid1,1e control"' DC motors. Figuri, 17-14 show, the connection of an H-Bndge IISlng simple switches. All the switches ,,re open, which clces not allow the motor to tum
Clockwise
Counter-
Rotation
Clockwtse Rotation
Figur, 17-13. DC Motor Rot.ition (Ptrmanent Magnet f ield)
:able 17-9: Selected DC Motor Characteristics (wwv,.Jameco.com) •rt No. ~SCP
Nominal Volts 3V
Voll Range 1 5-JV
Current
RPM
Torque
llJ.8 g-crn
R CONTROL: RELAY, PWM, DC, ANO STEPPER MOTORS
441
Figure 17-15 shows the switch configuration for turning the rnotor in one direction. When switches t and ,_,, rorrm
of""" .,.,s. '""" ~•-'""' 3•• """"' ro""'' 0 ' "'""' " P'" Uuo• gh
4 '"
.
••
+V +V
l
•
urrent
•
.•
••
SWITCH 2
SWITCH I
M
I
•
SWITCH
SWITCH 3
SWITCH 2
Flow
I
M
SWITCH 4
SWITCH 3
SWITCH 4
I
•
MOTOR NOT RUNNING
•
C LOCKWISE
-
oatEcnON
Figure 17-15. H-Bridge Motor Clockwise Configuration .
Figure 17-14. H-Bridge Motor Configuration
+V
tY
!
i
-
Current
SWITCH
-
Plow
1
SWITCH
SWITCH
/ ~
SWITCH
SWITCH
4
SWITCH 4
DIRl!CT!ON
able 17-10: So
_,_+ INVALID STATE I(SHORT C [R
.
. Figure 17-11 H . · · Bn dge i ge Logic Confj n a.n inval id Confi
me H-Brid
Motor Operation Off
Clockw· Counler Clockwise
Invalid
h
,., ---.J
. Figure 17-16. H -8 n'dgo Motor Co unten:lockwise Con•. ·-,,;ur•tion
T
M -
3
! COUNTER _ CLOCKWJSI! -
SWITCH 2
1
M
3
-
SWITCH 2
SWt
. gu.Tafions for F' guratton agure 17-14 SWz
Open
Open
$"\,\'3
$"\,\'4
Closed
Open
Open
Open
Open
Cl~ ClOSed
Open Closed ClOSed
Closed
Closed
CUTT)
Open Closed.
nt1: sos1 Mlca OCON'fRottER AND
EMBEDDED SYSTEMS
H
..-ipi, 17•5
.
A twitch" cvnnt'Ctl'd to ptn 1'2.7. Using a simulator, " rote a program tht following 1, 1uS\\/ • O. the OC motor moves clockwise . ...!bl If SW ., I, the OC motor moves counterclockwise.
to monitor the status of SW and perform
5olutio'
ORG
OH
CLR
Pl.O \ Pl.l Pl.2 P:i.J P2.7
MAIN : CLR
CLR CLR SETB i«>!l!TOR :
;switch ; switc h ;switch ;switch
l 2 3 4
JNB
P2. 7 ~- CLQCICWISE SETB . Pl. fl ; switch CLR Pl . l ;switch CLR i>1.2 ;Switch SE:TB -Pl . J ;switch SJMP MONITOR CLOCKWISE:: CLR Pl.O ;switch SETB Pl.l ;switch SE:TB Pl.2 ;switch CLR Pl.3 ;switch SJMP MONITOR
.
L
END
l 2
3 4
1 2 3
r
4
/
I
View the results on your simulator. This example is for simulation only and should not be 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 do not show the relay control of an H-Bridge, Example 17-5 shows a simple program to operate a basic H-Bridge. .. . . . 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.
:.-e
Pulse width modulation (PWM) The Speed of the motor depen~ on three factors: (a) load,~) voltage, and (c) current. For a given fixed load we Cl~ maintain a steady speed by usmg • method called pulse w1dtl, mod11/atio11 (PWM). By changing (modulating) the >
.,
'°'•
(I
!.totOR CONTROL: RELAY, PWM, DC, ANO STEPPER MOTORS
,
. In such microcontrollcrs all we hav . . embedded in t~e ch•r;he desired pulse, and the_ rest IS lake~ me with the PW1"1 c,rcu•try hand Jow portions° For microcontrollcrs without PWM 11 that !.Orne microcontro crs_~~crs with the ,,aJues of the h1gUer to do other things. ents the microcontroller from doing todo is load ~e proper r~t;i This allows the microcontro software, which prev care by the nucrocontro er. . d ty cycle pulses using . u1try, we mu;,t create the vanous u arc
, /
+t2V .
I
+S . 410
•
•
8051
I
Hfl t
•
6 5
Pl.2
u
~rf!D
VCC2 L293
lk
I ENABLE 3 2 1NrUT I OUTrUT I
Jk
7
lh
lk
lNPUT 2
OIJTl'IJT ?
6
GND
4,5, 12, 13
The optoisol.itor provides
use uSC'pMate power supply for the motor and "£ L293 than for the 8051
i'ldditional protection of the
8051
-~
8
16 VCCI
ILQ74 +12 Opto
3
Pl.I
•
410
-;:
Pl.O ••
:'7
+12 V
01
~
~\'
02
'MI
f"fi
,.i,.tl 04
D3
'
*
D1. 02, 03, D4 are 1N4004
..fl''·
"Fir
~1
j,11 ol
fig' ftcplC
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
CLR CLR
Pl. 0 Pl.l
CLR
Pl.2
SETB
P2.7
/MAJN:
MONITOR: SETB JNB
Pl.O
;enable the chip
SBTB
P2. 7, CLOCKWISE Pl .1 ;turn Pl.2
SJMP
MONITOR
Cl.R
the motor count
erclockw1se
CLOCKWISE: SETS
Pl.l
C'LR
Pl. 2
SJMP END
MONITOR
;turn motor Clock . wise
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 Ji.tatc-d by the AC fr<'qucncy of the voltage applied the n,otor and the frequency is <>cnerallv fixed A 10 I <> , . s ,result, wecam1ot contro the speed of the AC motor .hell the toad is increased. As was shown earlier, we ,,nJlso ch,1nge the IX motor's di rection and torque. ~Figure 17-19 for PWM con1parisons. •
'A l'O~VER 25% DC ~ POWER 50% DC ~ POWER
75% DC
FUI..L l'OWER JOO~• 0C
figure 17-19. Pulse Width Modulation Com parison
oc motor control w ith optoisolator As we discussed in the fi rst section of this chapter, the optoisolator is indispensable in many motor control applicabOI\S. Figures 17-20 and 17-21 show the connections to a simple DC motor using a bipolar and a MOSFET tranststor. Notire that the 8051 is protected from EMl created by motor brushes by using an optoisolator and a separate power
lllpply. figures 17·20 and 17-21 show optoisolators for control of sing.l e directional n1otor control, and the same principle stiould be used for most motor applications. Separating the power supplies of the motor and logic will reduce the posi· bi1il)' of damage to the control circuity. Figure 17-20 shows the connection of a bipolar transistor to a motor. Protection of the con trol ci rcui t is p rovided by lhe optoisolator. The motor and 8051 use separate power supplies. The separation of power supplies also allows the use of high-voltage motors. Notice that we use a decoupling capacitor across the motor; th.is helps red uce the EMI c reated bylhe motor. The motor is switched on by clearing bit Pl.O. Figure 17-21 shows the connection o f a MOSFET transistor. The optoiso-lator protects the 8051 from EMl. The zener d,ode is required for the transistor to reduce ga te voltage below the rated maximum value.
f
-
-
+12V
1N400-I
O.l uF
+SV ILD74 OPTOISOLATOR
330
8051
I
8
2
7
Pl.O
10 k
TlP1 20
+12V t()()k
6 5
figurt 17-ZO. DC Motor conn«tlon lding a Darlington Transistor
~<>Toa CONTROL: RELAY, pWM, DC. AND STEPPER MOTORS
MOTOR
, +12V
MOTOR
JN4004 :• +5V
ILD74
8051
•
G D !RF521
330 OPTOJS0l.ATOR 1
•
2 Pl.O L - -- ~f--' •
3
•
~8~___.Jl~Ok~~r-...=.,'.s~ 7
!OOk 6.2V Zene Diode
L-j-'-- - i +12V
6 5
• Figure 17·21. DC Motor Connection using a MOSFET Transistor
Example 17•7 Refer to the DC motor connection of Figure 17-20. To the 8051 of this figure, a switch SW is connected to pin 3.2, which is the INTO pin. Write a program (a) normally the motor runs with a 33% duty cycle (b) when INTO is activated, the motor runs with 10% duty cycle for a short duration. Solution: ;-upon wake up, avoid using the space allocated to interrupt vector table ORG
0000
LJ'MP
MAIN
;;- - - -the !SR for interrupt INTO ORG
0003R
SJMP
PIRST
;-main program for initialization ORG
0030H
MAIN:
MOY
IE.#Blll
HERE:
Sl!TB MOV ACALL CLR HOV ACALL
Pl. O RO, #33 DELI>.¥ Pl. O RO, #67 DBLAY
SJMp
HERB
;enable INT 0
;Pl.o aet for
331
;Pl.O cleared f
time
or 671 t ime
'
TliE 8051 r.tl
CRocoNlROLL
.
.
•
. . ··'
ER AND EMBEDDED SYSTEMS
,,.. ._this is the !SR for INT O
•
RS• #OFFH Pl . 0 MOV R0,#10 ACALL DELAY CLR Pl . 0 MOV RO, #90 ACALL DELAY
; this is to create a delay
OJNZ RETI
; exit from lSR when R5s0
r1RST: MOV rf!ERE: SETB
RS,THERE
; p 1.0 set for 10 t time
; p 1. 0 c l eared for 90t time
·-6ubrouline named DELAY
'
osLAY, RPTl: MOV FP1'2:
MOV
Rl, # 20 R2,#100
RPT3 :
DJNZ
R2,RPT3
OJNZ
Rl,RPT2 RO, RPTl
DJNZ
RET
END In trus to ma ke the moto r to run continuously at l
See the www.MlcroDlgltalEd.com Web alte for addit ional Information on motor control.
DC motor control and PWM using C Examples 17-8 thro ugh 17-10 show the 8051 C v ersion o f the ea rlier programs controlling the DC motor.
Exmlple 17-8 ~ to figure 17-18 for connecti011 of the motor. A , witch i s ~ to pin P2.7. Write a C program to mcnitor
lht sutus of SW and pet fc-111 the following: 11) USW "' o. the DC motor mows clodr;wile. lb! lfSW e 1, the DC motor IJIO\Wa,untffl:Jockwi.
Solation: l!nc lude creg51 , b > •bit SW • n •11 6 •bit IX.UL&• Pl 0 1 •bi t MTR 1 • p1•1 1 abi t NTll- 2 • Pl•a,
-
~Ol'Oll CONTROL: U LAY, pWr.t, DC AND S I EPPEll MOTORS
,
/ void ""'ln fl
{ SW• l; ENABLE• 0; MTP_l • 0: MTR_2 •
Di
I
•
while (1)
{ ENABLE• l; if(SW • • l)
I ••
MTR_O = l; MTR l ~ O;
l
else {
••
MTR_O • O;
•
MTR_l • l;
I f
}
l
I
E,c,lm ple 17·9
Reter to the figure in this example Write,, C program to monitor the status of SW and perform the following: Ca) lfSV.1 = 0, the DC motor mo,es with 50% duty cycle pulse. (b) If SW= I, the OC motor move,, with 25% duty cycle pulse. Solution:
#include 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
} +12V
+5V
O.luF
IN4004
4.71<
MOTOR
+SV llD74
3-10 OPTOISOLATOR
8
P2.7 8051 2 P1 .0 1 - - -- ---=!_J
..,.,..
7
IOk
Tll'l20
+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) OC motor move~ slowly (25°'., duty cycle) 0 0 OC motor movei. moderately (50"/o duly cycle). 0 1 OC motor moves fast (75°/o duly cycle). I 0 DC motor moves very fast (HXl"'u duty cycle). 1 1 Solution:
•include •bit MTR • Pl AO; void MSDelay(unaigned int val ue);
t.toro1 CONTROL: REI.A Y, l'WM, DC, AND STEPPER MOTORS
.
void maiD O { unsigned c:har z;
P2 • OxFF; z • P2: 2 • z t.. Ox03; MTR• 0;
while ( l) ( ewitc:h(z)
( c:ase(O):
{
..•
MTR • l;
MSDelay(25);
•
' •
MTR= 0;
~SI
MSDelay(75); break;
j(IIO:
}
can
case(l): { MTR = l; MSDelay(SO);
: Holl
l Gi\"E t 1110 : fll\d I Gil1
MTR= 0;
MSDelay (50); break;
' GiVE
} case (2) : {
! Ofd • TlllE l Tllll
MTR = l;
MS0elay (75); MTR= O; MS0elay(2S ) ;
Ki!O
l Ua t Cale
break;
} default:
aFor
MTR • l;
'In F ,i F'aii
)
}
t Fini
• Wh
mo
l lY!,
~~
l 1n1
Review Questions 1.
2. 3. 4. 5. 6.
True or false. The permanent magnet field DC motor has only two leads for + d _ True or false. ]U$l like a stepper motor, one can control the exact angle of a Dean t v?Itages. Why do we put a driver between the mkrocontroller and the DC motor' mo ors move. How do we change a DC motor's rotation direction? · What is stall in a DC motor? 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 450
(no loarndclphase, but different amplitude pulses. • ' Daded).
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?
How does a reed switch work? Give the advantages of a solid-state relay over an EM relay. ln circuits with relays and microcontrollers, why are driver !Cs used? 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. 2. 3 4. 5.
SEcnON 17.2: STEPPER MOTOR INTERFACING
11. If a motor takes 90 steps to make one con1ple1e revolution, what is the step angle for this motor? 12. Calculate the number of steps per revolution for a step angle of 7.5 degrees. 13. For what kinds of applications are stepper motors popular? It In Figure 17-11, is it mandatory to use transistors in the Darlington configuration? 15. Finish the normal four-step sequence counterclockwise if the first step is 1001 (binary). 16. Finish the normal four-step sequence counterclockwise if the first step is 0110 (binary). 17. What is the purpose of the ULN2003 placed between the 8051 and the stepper motor? Can we use that for 3A motors? 18. Which of the following cannot be a sequence in the normal 4-step sequence for a stepper motor? (a) CCH (b) DOH (c) 99H (d) 33H 19. What is the effect of a time delay between issuing each step? 20. ln Figure 17-11, why are diodes used?
SECTION 17.3: DC MOTOR INTERFACING AND PWM 21. Which motor is best for moving a wheel exactly 90 degrees? 22. What is the relationship between the load, torque, and current of a DC motor? 23. True or false. The rpm of a DC motor is the 5an1e for no-load and loaded. 24 The rpm given in data sheets is for (no-load, loaded). 25. What is the advantage of DC motors over AC motors? 26. What is the advantage of stepper motors over DC motors? 27. True or false. Higher load on a DC motor slows it down if the current and voltage supplied to the motor are fixed. 28. How can a microcontroller be used to control automatically the speed of a OC motor?
'->tua COl\rTROL: RELAY, l'WM, DC, AND STEPPER MOTORS
451
· p\.\lM cifcuitry. d LI microcontroller? 29. N~me two microcontroUcrs w_ith in-built . tor between the motor an ,e 15 _ What ,s the advantage of placing an opto ola 30
ANSWERS TO REVIEW QUESTIONS SECTION 17.1: RELAYS ANDOPTOISOLATORS 1
•
~
• •
•• •
•
•
••
. 23. 4. 5. 6.
•
y.120Vdev1cessu
ch as horns a nd appliances. . '
\\lith a relay we can use a 5 V dig1tnl system to contro112 gize the relay, we need a dnver. k ffi . t current to cner Since microcontroller/ digital outputs lac su cien \.\'hen the coil is not energized, the contact is closed. d ou.nd the coil, which causes the armature to be When current Oows through the coil, a magnetic field is create ar attracted to the coil. It is faster and needs less current to get en~rgized. . without a driver. It IS smaller and can be connected to the microcontroller d,rectly
SECTION 17.2: STEPPER MOTOR INTERFAClNG I. OllO. 0011, 1001, 1100 £or clockwise; and 0110, 1100, 1001, 0011 for counterclockwise 2. 72
3. Because the microcoi,troller pins do not provide sufficiei,t current to drive the stepper n1otor
SECTION 17.3: DC MOTOR INTERFAONG AND PWM I.
True
2. 3. 4. 5. 6. 7.
False Since mic~ocontrollerI digital outputs lack sufficient current to drive the DC motor, we need a driver. By reversing th<' polarity of voltages connected to the leads The DC motor is staJJed if the load is beyond what it can handle False No-load
452
lliE aos1 M1caoco..,..,... ·• '"OLLl!ll
AND EMBEDDED s'YSffMS
APPENDIX A
8051 INSTRUCTIONS, TIMING, AND REGISTERS
OVERVIEW 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. (n
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: Flags:
i
Absolute Call None
• l' ,,
. 'th target address with.in 2K bytes from the current 3 ACALL stands for "absolute call." II calls subrouttnes WI program counter (PC). See LCALL for more discussion on this.
ADD A,source byte Function: Flags:
•
.. •
I
J I
I
ADD OV, AC, CY
This adds the source byte to the accumulator (A), and places the result in A. Since register A is one byte in size, the
source operands must also be one byte. The ADD instruction is used for both signed and unsigned numbers. Each one is discussed separately.
.c: re
Unsigned addition addition of unsigned numbers, the status of CY, AC, and OV may cha!lge. The most important of these flags JS • t becomes I when there is a carry from 07 out in 8-bit (DO - D7) operations.
w
•
Example: MOY ADD
A,#45H A,#4FH
1A=45H ;A=94H (4SH+4FH• 94H) ;CY=O,AC=l
Example: MOY MOY ADD
A,#OFEH R3,#75H A,R3
;AaFEH ;R3:r7SH
1A=FE+75=73H ;CY=l,AC=l
Example: MOY ADD
A,#2SH A,#42H
;A=25H ;A=67H (2SH+42H=6?H) 1CY=O ,AC=O
b
~(
Addressing modes 1.
2. 3. 4.
The following addressing modes are supported for the ADD . . Immediate: •~ inSITuction: =D A, #data Ex RP<>ister: ample: ·o· ADD A, Rn ADD A, #2SH Direct: Example: ADO A,direct ADO A,R3 Example: Register-indirect: ADD A,@Ri where i•O ADO A,30H . =Ro or i•l onl 'add to A d aa1.'nr.•u t Examples: y ADD A. • ' add to A d = 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 454
th oge er, and the 5um 1ssav · ed m ·
APPENDIX A
I I
B_l :
CLR A MOV RO,#SOH MOV R2,#16 MOV R3 ,# 0 ADD A, @RO JNC B l INC R3 I NC RO DJNZ R2 , A_l MOV 70H,A MOV 71H,R3
;A=O
;sour ce poin t er ;counter ;cl ear R3 ;ADD to A from source ; I F CY=O g o t o next byte ;otherwise keep car r i es ;next l ocati on ;repeat for all bytes ;save low byte of sum ;save high byte of sum
. ~otice in all the ~ove examples that we ignored the status of the OV flag. :""l.tho~gh A DD instructions do affect OV, it 15 IJ\ the context of signed numbers that the OV flag has any significance. This IS discussed next.
Signed addition and negative numbers In the addition of signed numbers, special attention should be given to the overflow flag (OV) since this ~dicates ii there is an error in the result of the addition. There are two rules for setting OV in signed number operation. The overflow flag is set to 1: 1. U there is a carry from D6 to D7 and no carry from 07 out. 2. U there is a carry from 07 out and no carry from D6 to 07.
Notice that if there is a carry both from 07 out and from D6 to 07, OV = O. Example:
MOV A,#+8 MOV Rl, #+4 ADD A, Rl
;A=OOOO 1000 ;Rl=OOOO 0100 ;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 MOV ADD
A, #+66 R4, #+69 A,R4
;A=OlOO 0010 ;R4•0100 0101 ;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 indication 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 MOV ADD
A,#-12 R3,#+18 A, R3
;A=llll 0100 ; R3•0001 0010 ;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 HOV ADD
A, #-30
R0,#+14 A,RO
;A=lllO 0010 •ROsOOOO 1110 •;A•llll 0000 (-16, CORRECT) ·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;
MOV A.~·126 MOV ADD
I
("II'
;A•lOOO 0010 ;R7=1000 0001 WRONG) ;A•OOOO 0011 (+3, ;D7=0, OV•l
R7,#-127 A,R7
{,~
r,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 From the above di'lCUSSion we condude that while CY is ,mpo~ result is volid. As we will see in instruction •oA 1 signt>d number addition since it is used to indicate whether or nf. ~ in DIV and MUL instructions as weU. See the ,.,.. , the AC flag is us..-d in the ~ddition of BCD numbers. OV ,s a sou description of these two instructions for further details.
...
AD D C A,source byte
•
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.
Function: Flags:
i
•
i-<,
f<" I
~~
IJ!lll
.~ •
Add with carry OV, AC, CY
Example: t
CLR MOV ADDC MOV MOV ADDC
C A,f!89H A,#OF2H R3,A A,#31H A,#25H
;CY=O ;A=89H ;A•89H+F2H+0=17BH, A=7B, CYal ;SAVE A ;A=31H+25H+l=57H
Therefore the result is:
25P2H + 3189H 577BH
The addressing modes· for AODC are the same as for "A DO A.byte".
AJMP target address Function; Flag.
T
Absolute jump None
AJMP stands for "absolute jump" lt tr f address for this instruction must be .:,ithi a2J
Function. Flamgs:
l
Logical ANO for byte variables None affocted
Th,s performs a logical ANO on th• dcstinatJon Nohce that both the source e•nodperands, dcsti ·bit by bit• storing th Exampk: nation values are byte-s~ result in the 1ze only. MOV ANL
456
•I
A,#3911 A•• 09H
;As39H ;A•39H ANDed With 09
A
B
AANDB
0
0
0
0
1
0
1
0
0
l
1
1
APPENDIXA
~
...
39 09 09
0011 1 001 0000 1001 0000 1001
i;xample: MOV MOV
ANL
A, #3 2H R4 , #50H A,R4
;A• 32H ;R4e50H ; (A•lOH)
32
50 10
0011 001 0 0101 0000 0001 0000
For the ANL instruction there are a total of six addressing modes. In four of them, the accumulator must be the destination. They are as follows: Immediate: ANLA,#data ANLA,Rn 2. Register: ANL A,direct 3. Direct: 4. Register-indirect: !.
Example: Example: Example: Example:
ANL A,#25H ANL A,R3 ;AND A wi t h data i n RAM location JOH ANL l\ ,@RO ;AND A with data po inted to by RO
ANL A,30H
1n the next two addressing modes the destination is a direct address (a RAM location or one of the SFR registers) while the source is either A or immediate data.
;. ANL direct,#data Example: Assume that RAM location 32H has the value 67H. Find its content after execution of the following code. ANL 32H , #44H
44H 0100 0 100 67H 011 0 01 11 44H 010 0 0101
Therefore, it has 44H.
Or look at these examples: Pl , #lllllllOB Pl,#OlllllllB Pl , #1111.0lllB ANL Pl ,#llllllOOB
ANL l\NL ANL
;mask ;mask ;mask ;mask
Pl.O(DO of Port l ) Pl .7(07 of Port l ) Pl. 3 (D3 of Port 1) Pl . O and Pl . 1
The above instructions clear (mask) certain bits of the output port of Pl. 6.
ANL direct,A Example: Find the contents of register B after the following: MOV B, #44H HOV A,#67H
l\NL
OFOH,A
;B• 44H ;As67H ;A AND B(B is located at RAM FOH) ;after the operation Bs44H
Note: We cannot use this to mask bits of input ports! For example, "ANL A, Pl" is incorrect!
ANL C,source-bit Function:
Logical AND for bit variable
Rag:
CY
In this iNtruction the carry flag bit is ANDed ~th a source bit and the result is placed in carry. Therefore, if source bu .. o, CY ;8 cleared; QtherWiBe, the CT flag rem11N unchanged.
,
P2 2 are both . bits P2.l and . r the accumulator if Examp le.· Write code to clea
I
MOV A, #OFFH
MOV C,P2.l ANL C,P2 . 2 JNC B_l •
;
•
high' otherwise, make A = PFH. '
;A~FFH . P2.l to car., ""nag ;copy bit ·and then 10w '; jump if one of them i s
. 'th the complement of the source bit. . of the CY flag bit w1 . . ti n involves the ANDmg Another variation of this mstru~ ~ . example. Its format is" ANL C,/bit". See the o owmg A - FFH. · make . high . and P2·2 is low; otherwise, Example: Oear A if P2.l 1s
e_1:
CLR A
MOV A, #OFFH MOV C,P2.l ANL C,/P2.2 JNC B l CLR A
;get a copy of P2 . 1 bit of P2.2 ·ANO P2.l with complement
'
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. BACK:
MOV Pl,OFFH MOV A, Pl CJNE A,#99,BACK
;make Pl an input port ; read Pl
-
: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: 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, UPl has a value greater than 65, it is kept by R3.
3.
Dest < Source
CY=O
Dest?. Source
CY= 0
At the end of the program, A will contain the equal value or R2 th II ' e sma er value, or R3 the greater value. Eleampie:
NE:XT: OVER: EXIT:
MOV CJNE SJMP JNC MOV SJMP MOV
A,Pl A, #65,Nl::XT EXIT OVER R2,A EXIT R3,A
;READ Pl ;IS IT 65? ;YES, A KEEPS IT, EXIT ;NO ;SAVE THE SMALLE:R ;ANO EXIT lN R.2 ;SAVE THE LARGER IN R3
458
nus instruction supports four addressing modes. tn two of them, A is the destination. laUJlediate:
CJNE A,#data,target CJNE A,#96,NEXT ;JUMP IF A IS NOT 96 C)NE A,direct,target CJNE A,40H,NEXT ;JUMP IF A NOT~ ;WITH THE VALUE HELD BY RAM LOC. 40H
1. E,camp1e: 2.
Direct 1
E,camp e:
Notice the absence of the"#" sign in the above instruction. This indicates RAM location 40H. Notice in ~s m.o de that we can test the value at an input port. This is a widely used application of this instruction. See the following: MOV MOV
Pl,IIOFF A,ttlOO CJNE A,Pl,HERE
!!ERE:
;Pl is an input port ;A • 100 ;WAIT HERE TIL Pl; 100
In the third addressing mode, any register, RO • R7, can be the destination. 3. Register: Example:
C)NE Rn,#data,target CJNE RS,#70,NEXT
; jump if RS is not 70
In the fourth addressing mode, any RAM location can be the destination. The RAM location is held by register RO or Rl. 4. Register-indirect: Example:
CJNE @Ri,#data,target ;jump if RAM ;location whose address is held by Rl ;is not equal to so
CJNE ®Rl,#80,NEXT
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: Flag:
Clear accumulator None are affected
This instruction clears register A. AU bits of the accumulator are set to O. Example:
CLR
A
HOV
RO,A R2,A Pl,A
HOV HOV
;clear RO ;clear R2
;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 CLR CLR CI.a
C P2 .4 Pl. 7 ACC. 7
.\Pl>ENo(X A.
;Cf•O ·CLEAR P2.5 (P2.5;0) Pl.7 (Pl.7•0) ·CLEAR 07 OF ACCUMULATOR (ACC.7c0)
;ct.BAR '
, CPLA C Jement accumulator f th omp a/f ed . th l's complement o e accumulator. 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. . function: Flags:
••
Example:
MOV
,
AGAIN:
CPL
MOV SJMP
•
;A=0101010l ·complement reg. A '; toggle bits o f Pl ;continuously
A, #SSH A Pl,A AGAIN
CPL bit Function:
Complement bit
.
.
•
This instruction complements a single bit. The bit can be
an bit-addressable location Ill the 8051. Y
Example: SETB
AGAlN:
CPL
;set Pl.O high ;complement reg. b it :continuous ly
Pl. 0 Pl. 0
SJMP AGAIN
DAA Function: Flags:
h,p
Decimal-adjust accumulator after addition CY
This instruction is used after addition of BCD numbers to convert the result back to BCD. The data is adjusted in
the following two possible cases.
1. It adds 6 to the lower 4 bits of A if it is greater than 9 or if AC = L 2. It also adds 6 to the upper 4 bits of A if it is greater than 9 or if CY= 1.
Example:
MOV
A,#47H A, #38H A
ADD
DA
+
47H 38H 7PH
(invalid BCD)
6H
+
;A•OlOO 0111 ;A•47H+38H•7PH, invalid BCD ;A•lOOO 010l•S5H, valid BCO
(after DA A) (valid BCD)
SSH
In the a~o"e example, since the lower nibble was greater th • . but AC= l, at also adds 6 to the tower rubble. See the i U . an 9, DA added 6 to A If th 0 1 owing example. · e ow e r lllbble as less than 9 Example:
MOV ADO DA
A,#29H A, #18H A
;A•OOlO 1001 ;A•OlOO 0001 INCOAA£cr ;A•OlOO 0111 - 47H VA..10 BCD
APPENDIX A
'!OV
~
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 ADD
A, #52H A., 1191H
DA
A
;A=OlO l 0010 ;AelllO 0011 INVALID BCD ;A=OlOO 0011 AND CY=l
52H
-
• 91H ( i n valid BCD) (after DA A, adding to uppe r nibble) valid BCD
E3H
+
6 143H
Similarly, if the upper nibble is less than 9 and CY= 1, it must be corrected. See the following example. Example: MOV ADD DA
A,#94 H A , #91H
; A=l 001 0100 ;AaOOlO 0101 INCORRECT ;A.•1000 0101 , VALID BCD ; FOR 85 , CY~l
A
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
ADD DA
A., #87H A
;A.•01 01 0100 ;A• ll Ol 1011 INVALID BCD ;A.=0100 0001 , CY• l (BCD 14 1)
DEC byte Function:
Flags:
Decrement None
This instruction subtracts 1 from the byte operand . Note that CY (carry I borrow) is unchanged even if a value 00 is decremented and becomes PF. This instruction supports four addressing modes. I.
Accumulator:
2. Register: l
4.
Direct: Register-indirect: Example:
OECA OECRn DEC direct OEC@Ri DEC @RO
Example: DEC A Example: DEC Rl or DEC R3 Example: DEC 4 0H ;dee byte in RAM locat i on 40H ;where i = 0 or 1 only ;deer. byte poi nted to by RO
DIV AB Function:
Flags:
Divide CYandOV
This ll\5truction dlvidl!!l a byte accumulator by the ~yte in register B. It is assumed that both registers A and B conta,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
,
. re.,uister A and aJues U1 . B are undefined and AB"), the v ·n this instruction. tion of •orv CY is always O • 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 MOV DIV
A, #35 B,#10 AB
;A= 3 and B=S
;
EJ
MOV
• •
DIV
A, #978 B, #12H
-''vide A by O' in which case the cl red unless we w
;A• 8 and B=7
AB
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: Flags:
Decrement and jump if not zero None
Ln this instruction a byte is decremented, and .,f the result is not zero it will jump to the target address. Example: Count from l to 20 and send the count to Pl.
BACK:
CLR
A
;A=O
MOV
R2,#20
;R2=-20
counter
INC
A MOV Pl,A DJNZ R2,BACK
;repeat if R2 not= zero
The following two formats are supported by this instruction. 1. 2.
Register: Direct:
DJNZ Rn,target (where n=O to 7) DJNZ direct.target
Example:
DJNZ
R3,HERE
Notice that target address can be no more than 128 bytes backward or 127 bytes forward, since it is a 2-byte instruction. For the more on this see SJMP.
INC byte Function: Increment Flags: None This iristruction adds I to the register or memory location Specjfi d b even if value FF is incremented to 00. This instruction supports fo ded Y ~e operand. Note that CY is not affected ur a ressmg modes. 1. Accumulator: INC A Example: INC A 2. Register: INC Rn Example: 3. Direct: INC direct INC Rl or INC RS Example: INC 30H ;incr. byte . 4. Register-indirect: INC@ru ( i = Oor 1) in RAM loc. 30!i Example: INC eRO ;incr. byte Pointed to by RO 462
APPIINDIXA
•
tNCDPTR function: Flags:
lncrement data pointer 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
INC
DPTR, #l6FFH DPTR
;DPTR•l6FFH ;now DPTR•l700H
J11 bit,target also: JNB bit,target Jump if bit set Jump if bit not set None
Function: Flags:
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 bitaddressable bits of RAM, ports, or registers of the 8051. Example: Monitor bit Pl.5 continously. When it becomes low, send SSH to P2. SETB
JB
HERE:
MOV
Pl. S Pl . S, HERE P2,#SSH
;make Pl.San input bit ;stay here as l ong as Pl.5=1 ;since Pl.5=0 send SSH to P2
Example: See if register A has an even number. If so, make it odd. JB INC
ACC.O,NEXT A
;jump if it is odd ;it is even , make it odd
NEXT:
Example: Monitor bit Pl .4 continously. When it becomes high, send 55H to P2. SETB
JNB
HERE:
MOV
Pl .4 Pl. 4, HERE P2, #SSH
;make Pl.4 an input bit ;stay here as long as Pl . 4e0 ;since Pl.4el send SSH to P2
Example: See if register A has an even number. lf not, make it even. JNB INC
ACC.0,NEXT A
;jump if DO is o (even) ;DO=l, make it even
NEXT:
TBC bit,target Function: Flags:
Jump if bit is set and clear bit 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 MOV NEXT:
"1'P£NDIX A
ACC. 7, NEXT
Pl,A
,
d or 127 bytes forward since it is a 2-byte 28 bytes back war be 11o more than 1 N bee that the target address can instru~tion. For more on this see SJMP.
•
,('
f
.,.
JC target
/
I
Function:
Jump if CY= I.
Flags:
None
the target address.
J'-' l'lJ•,.t,1•
. . . hi h it will jump to This instruction examines the CY flag; ,f ,t ,s g '
• Gel!
.-
•
]MP @A+DPTR Function: Flags:
•
I
Jump indirect None
.. . dress. The target address is p rovided ~y the ~otaJ s~ of 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: Flags:
Jump if no carry (CY= 0) 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. CLR A ;A=O MOV RJ,A ;R3=0 ADD A,#0F6H JNC OV.:Rl INC R3 OVERl: ADD A,#98H JNC 0VSR2 INC RJ OVER2: ADD A,#8AH JNC OVSR3 INC R3 OVERJ:
EX!T
1
---
1111di
Fan
Notice that this is a 2-byte instruction and the tar program counter. See Jcondition for more on this get address cannot be farther Iha . n - 128 to +127 bytes from the
]NZ target !'unction; Flags:
Jump if accumulator is not zero None
This instruction jumps if register A has a value oth th er ao zero.
APPENDIX A
E,cample: Search RAM locations 4-0H _ 4FH to find how many of them have the value 0.
BACK:
OVER:
MOV MOV MOV MOV JNZ INC INC DJNZ
RS,16 RJ,#0 Rl,#40H A,/IRl OVER R3 Rl RS, BACK
,set counter ;R3 holds number of Os ;address ;bring data to reg A
;point to next location ;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:
Flags:
Jump if A= zero 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.
BACK:
MOV MOV
RO, #SOH A,@RO
JZ
EXIT
MOV ACALL INC SJMP
Pl,A
;address ;bring the value into reg A ;end of string, exit ;send it co Pl
DELAY
RO BACK
;point to next
EXIT:
Notice that this is a 2-byte instruction; therefore, the target address cannot be more than-128 to +127 bytes ,n\'ay from the program counter. See J condition for further ctiscussion on this.
Jcondition target Function:
Conditional jump
In this type of jump. control is transferred to a target address if certain conditions are met. The targPt address cannot be more than-128 to +127 bytes away from the current PC (program counter).
JC )NC JZ )NZ JNB bit JB bit
JBC bat DJNZ Rn, ... CJNE A,#va l, ...
Jump carry Jump no carry Jun,p zero Jump no zero Jump no bit Jun,p bit Jump bit cle.ir bit Decrement and jump if not zero Compare A with value and jump if not equal
jump if CY= t jumpifCY=O jump if register A = 0 jump if register A is not O jump if bit= 0 · jump if bit I jump if bit = I and clear bit
=
•'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. •=o . . "togo toa "J conctition n..o> iJlStrUCt·on l , ass" if a progranund~rti.n~~=I~~useg wi~h the uncondltional L1,.u use the "J con i on ORG ADD
lOOH 11, RO
JNC
NEXT
•target more •
LJMP OVER
than l 28
bytes away
NEXT:
OVER :
ORG ADD
300H 11, R2
LCALL 16-bit addr also: ACALL 11-bit addr Function:
Fl s· None ddress is within 2K bytes of the current ag . fCALLs· ACALLand LCALL. In ACALL, the ta~get a ROM space of the 8051, we must use o reach the · target address in · the 64J< bytesress maXJmurn .u th A CALL) is pushed There am are counter) two typesTo of the instruction "-' ,er e
.
I
Transfers control to a subroutine
~,!t~ calling a subroutine, the PC register (which has th~td'!iie program counter is loaded with the new address !s
onto the stack, and the stack pointer (SP) incremented br ~e ;~edure, when RET is executed, PC IS popped off the and control is transferred to the subroutine. At the end O L P . stack, which returns control to the '."5truch.on ~ter t~e CAL e is the O code, and the other two bytes are the l6-~1t Notice that LCALL is a 3-byte instruction, m which on~ yt hich bits are used for the opcode and the remam2 address of the target subroutine. ACALL ::ress limits the range to 2K bytes. -byte 1 ing I I bits are used for the target subroutine address.
b
!s •
ins!;'~~~~";
f
iiglS~
i 114 i. M •. M
LJMP 16-bit addr also: SJMP 8-bit addr Function:
"1tiCl
Transfers control unconditionally to a new address.
In the 8051 there are two unconditional jumps: LJMP Qong jump) and SJMP (short jump). Each is described next. L
LJMP (long jump): This is a 3-byte instruction. The first byte is the opcode and the next two bytes are the target address. As a result, LJMP is used to jump to any address location within the 641<-byte code space of the 8051. Notice that the difference between LJMP and LCALL is that the CALL instruction will return and continue execution with the instruction following the CALL, whereas JMP will not return.
SJMP (short jump~: This is a 2-byle instruction. The first byte is the opcode and the second byte is the signed number displacement, whi~ 1s •.dded to the PC (program counter) of the instruction following the SJMP to get the target address. Therefore, m this Jump the target address must be within-128 to+ 127 bytes of the PC ( rogram counter) of the instruction after the S)MP since a single byte of address can take values of+127 to -128. address is often (PC) In referred to as a re/atrve address since the target address is -128 to+ 127 bytes relati t th th d th ve o e program counter .1s AppendJx, we '-· n<1ve use e term target address in place of relative dd nl f - ·· · . a ress o y or the sake of sunpilioty. Example: Line 2 of the code below shows 803E as the object cod f instruction. The 80H, located at address !OOH, is the opcode for theS M~ or 'SJMp OVER", which is a forward jump live address. The address is relative to the next address location wJch: and 3Eli, located at address 101H, is the rela· target address of the "OVER" label. ' IS l02H. Adding 102H + FBH = 140H gives the L0c OBJ LINE 0100 l ORG lOOH 0100 803B 2 SJM.p OVER 0140 3 ORO 140H 0140 7AOA 4 OVER: MOV 0142 7B64 RZ,#10 s AGAIN: MOV 0144 00 R3,#lOO 6 B1\Cl(: NOP 0145 00 7 NOP 0146 DBFC 8 DJNZ 0148 80P8 R3, Bl\Cl( 9 SJMP 2.
To1;
AGAIN
APPENDIX A
inis'
s.9. "~
IO. I,
The<
11. I
QI
ll J
ll
15.
'1°'5 lb,
17,
la.
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
14AH.
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 . Move byte variable Function:
---
Flags:
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 2. MOY A,Rn 3. MOY A.direct 4. MOY A,@Ri (i=O or l) Examples:
Example: Example: Example:
MOV A, #25H MOV A , R 3 MOV A , 3 OH
MOV A ,@RO MOV A, @Rl
; (A=25H)
;A=
data in 30H
;A• data pointed to by RO ;A• data pointed to by Rl
Notice that "MOV A. A" is invalid. (b) Register A is the source. The d estination can take the following forms.
S. MOY Rn,A 6. MOY direct,A 7. MOY@Ri,A (c) Rn is the destina tio n.
8. MOY Rn,#immed.iate 9. MOY Rn,A 10. MOY Rn,direct (d) The destination is a direct address.
11. 12. 13. 14. 15.
MOY direct,#d ata MOV d irect,@Ri MOY direct,A MOY direct,Rn MOY d irect,direct
(e) Destination is an indirect address held by RO or Rl . 16. MOV @Ri,#data 17. MOY @Ri,A 18. MO Y @Ri,direct
Mov dest-bit source-bit
- Function:
'
Move bit data
This MOV instnaction copies the source bit to the destination bit. In this instruction one of the operands must be the cY flag. Look at the following examples. Hov Pl. 2 , C HOV C, P2 . 5
,copy carry bit to port bit Pl . 2 ; c opy port bit P2.5 to carry bit
, MOV DPTRI #16-b it value F ction:
Load data pointer b't immediate value. un N 'tha 16-, Flags: one inter) register WI . .,nstructi'on loads the 16-bit OPTR (da~a po This
,pf'
·~
Examples:
HOV DPTR,#456FK HOV DPTR,#H¥DATA
;DPTR•456FK ddress ·load 16-bit a •·assigned to MYOATA
•
•
MOVC A,@A+DPTR
...
I
.
.
Mo,•e code byte
Function.
1:
l
l
-fh~
. Tius allows us to put strings of Flags: None . am (code) ROM into register address of the desired byte in This instruction moves a byte of data~oc:! ~p~:~nd read them 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 the code space (on-chip ROM) is fo
Y
.
-chip ROM program
memory starting at add ress
. is stored ,n the on ) Example: Assume that an ASCD character stnngU CPU and send it to Pl (port 1 . 200H. Write a program to bri,,g each d,aracter into ,e
Bl,
ORG HOV CLR MOVC
JZ
lOOH DPTR,#200H A A, liA+DPTR EXIT Pl ,A DPTR
MOV INC SJMP Bl EXIT, DATA,
ORG DB OB 2ND
tttP1 illll·
riluE
'11t II
belol Jhjs l
;load data pointer
!!pi
;A=O
byte
;move data at A+DPTR into A ;exit if last (null) char ;send character to Pl ;next character ;continue
200H "The earth is but one country and• "mankind ice citizens", ·~eaha ,u, llah"', o
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 MOVC instruction, register A has the character. Notice that the DPTR is incremented to point to the n ext character m the DATA table.
ll)l'bi
Example: Look-up table thethe squares of values Write a program to fetch the SQUR squareshas from look-up table. between Oand 9, and register R3 has the values of Oto 9.
'll ~
MOV
DPTR,#SQUR A,R3 HOVC A, eA+DPTR HOV
SQUR,
ORG OB
It
;load pointer for table
.
lOOfi 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. connected externally, we use the MOVX instruction. See MOvx, fu · To 4CCess off-chip memory that is memories ,or rther di= · ' ' - ....••• ,,non.
-
APPENDIXA
'
l
ll't I
•
~oVC A,@A+PC ~ction: flags:
Move code byte 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.
9:
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 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 RET
A, @A+ PC
SQUR:
DB O,l,4,9,16,25,36,49,64,81
The follo,ving should be noted concerning the above code. (a) The program counter, which is pointing to instruction RET, is added to register A to form the address of the desired data. In other words, the PC is incremented to the address of the next instruction before it is added to the original value of the accumulator. (b) The role of ·INC A" should be emphasized. We need instruction "INC A" to bypass the single byte of opcode belonging to the RET instruction. (c) This method is preferable over "MOVC A, @A+DPTR" if we do not want to divide the program code space into two separate areas of code and data. As a result, we do not waste valuable on-chip code space located between the last byte of program (code) and the beginning of the data space where the look-up table is located.
MOVX des t-byte,source-b y t e Function: Flags:
Move external None
This instruction transfers data between external memory and register A. As discussed in Chapter 14, the 8051 has 641< bytes of data space in addition to the 64.K bytes of code space. This data space must be connected externally. This instruction allows us to access externally connected memeory. The address of external memory being accessed can be 16-bit or 8-bit as explained below. (a) The 16-bit external memory address is held by the DPTR register. MOVX A,@OPTR
This moves into the accumulator a byte from external memory whose address is pointed to by DPTR. In other words, this brings data into the CPU (register A) from the off-chip memory of the 8051. HOVX @DPTR,A
This moves the contents of the accumulator to the external memory location whose address is held by DPTR. In other words, th.is takes data from inside the CPU (register A) to memory outside the 8051. (b) The 8-bit ad dress of extemal memory is held by RO or Rl. MOVX A,@Ri
;where i ~ o or 1
This moves to the accumula tor a byte from external memory whose 8-bit address is pointed to by RO (or Rl in MOVX A,@Rl). MOVX eRi,A
Af'PENDIX A
,
S-bit address is held by RO {or Rl in MOY)( rocation whose
xternal memory hil th 8 b . ..... ,. oves a byte from register A to an e mal memory w e e - ti version ,..,_, m sed t0 access ex Ie @Rl.A) . . · is widely u The 16-bit address version of this ltlStructJo0 used to access external 1/0 ports.
.I S
MUL AB Function: Flags:
Multiply A x B OV, CY
.
.
. ed byte in register 8·
The result is placed in A and B where A
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 ;A•35•23H, B•OO
MUL AB
•
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 greater than FFH, OV = 1; otherwise, it is cleared (OV = 0).
ilgiSI
!D the
lhe i
Example: MOV A,#25H MOV 8,#78H MUL AB
QIU..,
Ewr
;A=SSR, B=llH, CY=O, and OV•l ;(2SH x 78H • 1158H)
ORL
Example:
llJV
MOV A,#100 MOV 8,#200 MOL
AB
t4R 67R
-
OV•l , and CY•O ;(100 x 200 = 20,000 • 4 E2 0H) •· A=20H, 8 • 4EH •
I 'll!
NOP Function: Flags:
No operation 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: Flags:
Logical OR for byte variable None
This perfomu; a lnoicaJ OR O th b the destin b' · o· n e yte operands b't b . a on. • 1 Ybit and ' sto·~• the result in 470
A
B
AORB
0
0
0
0
1
1
1
0
1
l
1
1
APPENDIX A
sxaniple: r,10V
oRL
A,#3 9H A,#0 9H
;A=39H ;A=39H OR 09 (A=3 9H)
39H 001 1 1 001 09H 0000 1001 0011 1001 39
-
Example:
A, #3 2H R4, # SOH ORL A,R4
;A=32H ;R4 =SOH ; (A=72H )
MOV MOV
32H 0011 0010 50H 010 1 00 00 72H 0111 0010 For the ORL instruction there are a total of six addressing modes. In four of them the accumulator must be the destination. They are as follows: Immediate:
1.
ORLA,#data
ORLA,Rx 2. Register: ORL A,direct 3. Direct: 4. Register-Indirect: ORLA,@Rn
Example: ORL A,#2SH Example: ORL A, R3 located in RAM 30H data ;OR A with ORL A, 30H Example: to by RO Example: ORL A, @RO ; OR A with data pointed
1n the next two addressing modes the destination is a direct address (a RAM location or one of the SFR registers), while the source is either A or immediate data as shown below:
5. ORL direct,#data
Example: Assuming that RAM location 32H has the value 67H, find the content of A after the following:
ORL 32H,#44H MOV A,32H
;OR 44H with contents of RAM loc. 32H ;move content of RAM loc. 32H to A
44H 01 00 0100 67H 0110 0111 67H 01 10 0111
Therefore A will have 67H.
6. ORL direct.A Example: Find the content of B after the following: MOV B, #44H MOV A, #67H ORL OFOH,A
;B=44H ;A=67H ;OR A and B (Bis at RAM FOH) ;After the operation B=67H.
Note: This cannot be used to modify data at input pins.
ORL C,source-bit
-
Function: Logical OR for bit variables
Rags: CY tn this instruction the carry flag bit is O Red with a s~urce bit and the result is placed in the carry flag. Therefore, if the source bit is 1, CY is set; otherwise, the CY flag remains unchanged.
APl'ENDIXA
471
cz is high, le: Set the C311)' ilag ii either PlS or AC .
ExiUJ\P ·
-get Pl· 5 '
H()VC,Pl.S ORL c. ;,.cc . 2
statUS
.-cu
kA::rr"·
.
)ugh- ()therWise, ma e
·r Pl 2 or !'2-2 15 Example: Write a program to clear A I . MOV A, HFFH MOV C, Pl. 2 ORL C,P2.2 JNC OVER
R.
•
CLR A
OVE .
.
•
y with the complemen ~on involves ORing C .
t of the source bit. Its format is "ORl
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 MOV C,P2.l ORL C,/P2.2
I
·get a copy of P2.l bit of P2. 2 ;OR P2.l with complement
JNC OVER CLR A
I OVER:
POP direct Fur,ction: Rags:
Pop from the stack 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: Aags:
Push onto the stack 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
!
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 , ao,, A-00110010 and CY•l l'fOw ~~011~0 101 ,nd CY•O
""'
'• '
MSB - - - LSI! ~-
~
, .
t
b"ts 1 of the accumulator ngh . This rotates the • d f the accumulator. ·-• . to the opposite en o rotan:u"'
The bits rota
ted out of register A are r
otated into CY and the CY bit is
Example: SETS MOV RRC SETS RRC
C A, #99H A
•
;CY•l ·A•lOOllOOl '.Now A=llOOllOO and CY=l
'
C
and CYsO
A
SETB bit
• J
r
Function: Set bit . ectl ddressable bit of a port, register, or RAM . the carry or any drr ya This sets high the indicated bit. The bit can be location.
E
Examples: ;Pl.3=1 ;P2 .6 • 1
SETS Pl. 3 SETS P2. 6 SETS ACC. 6 SETS 05 SETB C
;ACC.6•1
;set high OS of RAM loc. 20H ;Set Carry Flag CY=l
-
xa
F
F
SJMP
1
See LJMP &: SJMP.
rot
SUBB A,source b yte Function: Flags:
Subtract with borrow OV, AC, CY
This subtracts the source byte and the carry flag from the accumulator and puts the result in the accumulator. The steps for subtraction performed by the internal hardware of the CPU are as follows: 1. 2. 3.
Take the 2's complement of the source byte. Add this to register A. Invert the carry. This instruction sets the carry flag according to the followmg:
i
dest > source dest = source dest < source
!:X 0 0 I
the result is positive the result is 0 the result is negative in 2's complement
Notice that there ls no SUB instruction in the 8051. There( and then using SUBB: A = (A - byte -CY). ore, we perform the SUB instruction by making CY = O Example: MOV A, #4SH CLR C SOBS A, #23H
474
;45H·23H·0=22H
l l l
)ddressing Modes n,e following four addressing modes are supported for the SUBB. !Jllmediate: I, Register: ? Direct: J. Register-indirect: -1,
SUBS A,#data SUBB A,Rn SUBB A,direct SUBB A,@Rn
Example: Example: Example: Example:
SUBS A,#25H SUBS A,R3 SUBS A,30H SUBS A, @RO
;A•A· 25H· CY ;As A• R3 - CY data at (30H) ;A ;A . data at (RO)
-
-
CY
- CY
5WAPA Swap nibbles within the accumulator None
Function: Aags:
The SW AP instruction interchanges the lower nibble (DO • D3) with the upper nibble (04 • 07) inside register A. Example: MOV
A,
SWAP
A
ll59H
;A: 59H (0 1 01 1001 in bi nary) ;A• 95H (1001 01 0 1 in b i nary)
XCH A,Byte Function: Flags:
Exchange A with a byte variable 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
MOV
R2, #97 H A, R2
XCH
;A=65H ;R2s97H ;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: I.
Register: 2. Direct: Example: 3. Register-Indirect: Examples:
XCHA,Rn XCH A,direct XCH A, 40H XCHA,@Rn XCR A, @RO XCH A,@Rl
Example: XCH A,R3 ;exchange A wi th data in RAM loc. 40H
;XCH A with data pointed to by RO ;XCH A with data pointed to by Rl
XCHDA,@Ri Function: Exchange cligits None Flags: 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) HOV A, #12R
;A•l2H (0001 0010 b inary) ffl
1oad painter ble of lOl'ler ni b MOV Rl, 14011 , exchange the ion 40H XC!!D A, eRl • and RAM 1ocat ti ,nH has 92H. d RAM Joca on "" . we 11ave A '" 171-1 aJ\ After execution of the XCHD instrUdiOO. ; R.1•40H , ; ft
XRL dest-byte,source-byte -
Function: Logical exclusive-OR for byte variables
Flags:
. 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 None
---=------:~==~
Example: MOV A,#39H XRL A, • o 9H
;A•39H ·A• 3 9H ORed wi t h 0 9
•
39H 0011 1001 0 9H 0000 1 001 0011 0000 30
0
0
0
0
1
1
1
0
1
1
1
0
Example: MOV A, #3 2H MOV R4 , I SOH
XRL A,R4
; A•3 2H ; R4•SOH ; (A•62H)
32H 0011 001 0 SOH 0101 0000 62H 0110 00 10
For the XRL instruction there are total of six addressing modes. In four of them the accumulator must be the destination. They are as follows: I. 2. 3.
4.
XRLA,#data XRLA,Rn XRL A.direct Example: XRL A, JOH Registtt•indir«t XRL A,ORn Example: XRL A,•RO
Immediate: Register: Direct
Example: XRL A, #2SH Example: XRL A, R3 ;XRL A with dat a in RAM location lOH ;XRL A with data pointed to by RO
In the next two addressing modes the destination Is a direct 1 d"-while the source is either A or unmediate data as shown below: ''"""' (a
5.
XRL direct,ldata Example: Assume that RAM location 32H has the value 67H Find the content of A after execution of the follOWlng code. · XRL
32H, #44H
MOV
A, 32H
44H 0100 0100 67H 0110 0111 23H 0010 0011
416
RAM location or one of the SFR registers)
;move content ot RAM 1 oc:: • Therefore A Will ha Ve 23H.
32H to A
XRL direCt,A 6. Example: Find the contents of B after the following: i,10V B , #44H l'l()V A , #67H J(RL OFOH , A
; B•44H ;A=67H
;OR register A and B ; (register B i s located at RAM l ocation FOH) ,after t he operati on B•23H • Note: We cannot use this instruction to exclusive-OR the data at the input port.
•
•
Table A· l : 8051 lnstruction Set Summary Machine Cycle Byte Mntmonic Arithmetic Opera.lions ADD A,Rn ADD ADD ADD
t
1
A,direct A,@RJ
2
1
l
1
A,lldata
2
1
I
1
ADDC A,Rn ADDC A,direct
1
2
ADDC A,@Ri ADOC A,lldata
Mrternonic Logical Opeta tions direct,A ORL
Machine Cycle
2
1
ORL
direct,#data
3
2
XRL
A,Rn
1
1
XRL
A,clirect
2
1
XRL
A,@Ri
l
I
XRL
A,#data
2
1
direct,A
2
1
1
1
XRL
I
XRL
direct,#data
3
2
2
SUBB SUBB SUBB SUBB
A,Rn A,direct A,@Ri
1
1
CLR
A
1
1
2
I
CPL
A
1
1
I
I
RL
A
1
1
A,#data
2
I
RLC
A
1
1
INC INC INC
A
1
1
RR
A
1
1
Rn direct
1
I
RRC
A
1
1
2
I
SWAP
A
1
1
@Ri
1
A
1
1 1
Data Transfer
Rn
I 2
1
MOY
1
MOY
A,direct
2
1
1
1
MOY
A,@Ri
1
1
1
2
MOY
A,#data
2
1
1
4
MOY
Rn,A
1
1
1
4
MOY
Rn,direct
2
1
MOY
2
1
Rn,#data
MOY
2
1
direct,A
MOY
2
1
direct,Rn
2
2
3
2
2
2
3
2
l
l
2
2
2
1
3
2
1
2
1
2
INC DEC DEC DEC DEC INC MUL DIV DA
direct @Ri DPTR AB AB A
Logical Operations
ANL
ANL
A,Rn
1
I
2
1
ANL
A.direct A,@Ri
ANL
A,#data
2
ANL
I
direct,A
2
1
ANL
1
1
ORL
dircct,#data A,Rn
1
ORL
A,direct
2
ORL
A,@Ri
1
1
ORL
A,#data
2
1
3
2 1
I
~ -- ~ ~
Byte
.
f
~ ~ "!,: ~ ~ ~ ~ ~ ~ ~
-~
~ (Pl
-
(]'I.
MOV
-MOV Mov -MOV
-
A,Rn
direct,direct direct,@Ri direct,#data @Ri,A
Mov
@Ri,direct
Mov
@Ri,#data
Moy
\.'ll.
DPTR,#data16
Movx A,@Ri Movx A,@DPTR
1
1
A,'11.
-
(IL
-Ill.
-lOV
-
--
ll)y
(
'fable A-1 (continued)
---
~ine111onic ~Transfer
-
~
MOV
@DPTR,A
pVSH
direct
Byte
1
M achine Cycle
JNC
rel
2
2
3
2
bit,rel
3
2
2
JB JNB
bit.rel
JBC
bit,rel
3
2
ACALL adclrll
2
2
LCALL addrl6
3
2
RET RETI
1
2
1
2
2
1
2
2
Byte Mnemonic Boolean Variable Manipulation
Machine cycle
p()P
direct
2
2
.xcH ;
A,Rn
1
1
A,direct
2
l
xCH
A,@Ri
1
1
xCHD A,@Ri
1
1
Program Branching
5o0lean Variable ManJpulation
1
A}MP
addrll
2
2
1
L}MP
adclrl6
3
2
2
1
rel
2
2
CLR CLR
C
SETB SETB CPL
C
1
1
SJMP
2
1
JMP
@A+DPTR
1
2
bit
1
JZ
rel
2
2
C
1
1
JNZ
rel
2
2
bit
2
2
CJNE
A,direct,rel
3
2
C,bit
2
CJ bit
2
2
CJNE
A,#data,rel
3
2
2
CJNE
Rn,#data,rel
3
2
C,bit
2
2
CJNE
@Ri,#data,rel
3
2
C,/bit
2 2
1
OJNZ
Rn.rel
2
2
C,bit
2
2
OJNZ
direct,rel
3
2
bit,C
2
NOP
1
l
rel
2
CPL ANl. ANl.
ORL ORL MOV MOV JC
bit
.\PnNDIXA
'"
/
f
ECTION A.2: 8051 REGISTERS
S
I
. (SFR) .Addresses . RegJster Table A-2: Special Function
Address
Symbol ACC•
Name Accumulator
OEOH
a• PSw•
B register Program status word
ODOH
SP
Stack pointer Data pointer 2 bytes
OPTR
OPL
Low byte
OPH
High byte
OFOH 81H 82H 83H 80H
PO'
Porto
P1•
Port 1
P2·
Port2
P3' [P•
Port3 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
TiiO
OC9H
TimerI counter Ohigh byte
TLO
SCH
Timer I counter Olow byte TimerI counter 1 high byte Ttmer I counter I low byte Timer I counter 2 high byte Timer I counter 2 low byte
THI
TLI TH2
TU RCAP2H RCAP2L SC0N' SBUF
PCON • Bit-a.ddressabJe
,r; ,
TIC 2 capture register high byte TIC 2 capture register low byte
90H
OAOH OBOH
8AH 8DH 8BH
OCDH OCCH OCBH
Serial control
Serial data buffer Power control
98H 99H 87H
APPIINDIX A
.. Byte address
Byte address
Bit address
7F
FF FO
F7 F6 FS F4 Fl F2 Fl FO
B
General·
80
E7 E6 ES E4 E3 E2 El EO
ACC
purpose RAM
00
D7 D6 DS D4 D3 D2 Dl DO
PSW
B8
..
BC BB BA 89 88
IP
BO
87 86 BS 84 83 82 Bl BO
P3
AS
AF
AC AB AA A9 AS
IE
AO
A7 A6 AS A4 1\.3 A2 Al AO
P2
..
..
.. ..
not bit-addressable
SBUF
99 98
9F 9E 90 9C 98 9A 99 98
SCON
90
97 96 95 94 93 92 91 90
Pl
8D SC 88 8A 89 88 87 83 82 81 80
not bit-addressable not bit-addressable not bit-addressable not bit-addressable not bit-addttSSable SF SE 80 SC 88 SA 89 88
not bit-addressable not bit-addressable not bit-addressable not bit-addressable 87 86 85 84 83 82 81 80 . Special Function Registers
THl
THO TLl
TLO TMOD
TCON PCON DPH DPL SP
PO
Figure A•l . SFR RAM Address (Byte and Bit)
Al'PENDJXA
30 78 2F 7F 7E 70 7C 78 7A 79 70 2E 77 76 75 74 73 72 71 2D 6F 6E 60 6C 68 6A 69 68 6n 2C <7 •6 , . 64 63 "2 <1 58 28 SF SE SD SC SB SA 59 2A 57 56 55 54 53 52 51 so 49 29 4F 4E 40 4C 48 4A 49 40 28 47 46 45 44 43 42 41 38 27 3F lE 30 JC 38 3A 39 37 36 35 34 33 32 31 30 26 25 2F 2E 20 2C 29 2A 29 28 27 26 25 24 23 22 21 20 24 lF lE lD lC 18 lA 19 18 23 17 16 15 14 13 12 11 10 22 21 OF"" OD nc OB OA 09 08 20 07 06 OS 04 03 02 01 00 lF Bank3 18 17 Banlc 2 10 OP Bank 1 08 07 Default register bank for RO· R7 00
Figutt A•2. 128 Bytes of lntem•I RAM
DO
EA
I ET2 I F.S I ET!
I
BXO ]
EJ(l
. 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.
ed •·'or future use. '
.
IE,6
Not implemented, reserv
ET2
IE.5
Enables or disables timer 2 overflow or cap
ES
!E.4
Enables or disables the serial part interrupt.
ET1
IE.3
Enables or disables timer I overflow interrupt.
EX1
IE.2
Enables or disables external interrupt 1.
ETO
IE.I
Enables or disables timer Ooverflow interrupt.
e:xo
LE.O
Enables or disables external in~upt O.
ture interrupt (8952).
• User software should not write ls to reserved bits. These bits may be used
in future flash microcontrollers to invoke new features. Figutt A•3. IE (Interrupt Enoble)
Register
07
DO
PT2
PS
PT!
PX!
PTO
PXO
Priority bit : 1 assigns high priority. Priority b' t _ . i - 0 ass,gns low priority. CP.7 reserved IP.6 reserved
~ :s PT1
IP~
PXl PTO
lP.2 IP.I
PXO
IP.O
~:: 2 interrupt priority bit (8052 only) . ~rt ll\terrupt priority bit. Tuner I mterrupt priority b't External interrupt I priori~ i,. Tuner Ointerrupt priority b' ,t. External interrupt Opriori;tbit.
·
User software should never write Is t0 . u.rutnplernented bits . future products. , smce they · L u~y "". used . F' A 111 ,gure -4. lnterrupt Priority Regi1ter (Bit·• ddres10bie)
APPENDIX A
~I
- I - I - I
I
GFl
GFO
PD
IDL
figUlt A-5. PCON Register (not bit-addressable)
Finding the TH, value for various baud rates: SMOD = 0 {default on reset) TH, =
256
_ Crystal frequency 384x Baud rate
SMOD = 1 TH, =256
Crystal frequency
192x Baud rate
CY CY AC
PSW.7 PSW.6
FO RSI RSO
PSW.5
OV
PSW.4
PSW.3 PSW.2
PSW.1 P
PSW.0
RSl 0 0 1
RSO 0 1 0 1
1
FO
AC
RSI
RSO
I
r
OV
Carry flag. Auxiliary carry flag. Available to the user for general purposes. Register Bank selector bit 1. Register Bank selector bit O. Overflow flag. User-definable bit. Parity flag. Set/ cleared by hardware each instuction cycle to indicate an odd/ even number of 1 bits in the accumulator. Address OOH-07H OSH-OPH 10H-17H 18 H -1FH
Regis ter Bank 0
1 2 3
figure A-6. Bits of the PSW Register (bit-addressable)
l SMO S M1 S M2 REN T BS RBS Tl
RI
Nott:
SMO
SM!
! SM2
] REN
SCON.7 SCON.6 SCON.5 SCON.4 SCON.3 SCON.2 SCON.1
i
RBS
Tl
!
RI
Serial port mode specifier Serial port mode specifier Used for multiprocessor communication. (Make it O.) Set/cleared by software to enable/disable reception. Not widely used. Not widely used. TransmH interrupt 8ag. Set by hardware at the beginning of the stop bit in mode 1. Must be cleared by software. SCON.O Receive interrupt flag. Set by hardware halfway through the stop bit time in mode 1. Must be cleared by software. Make SM2, TBS, and RBS z 0.
Figure A-7. SCON Serial Port Control Regit ter (Bit-addretsable)
APPENDIX A
TB8
( Finding the TH, value for various baud rates:
sMOD" 0 (default on reset) TH =256-
Crystal frequency 384xBaud rate
1
SMOD= I
m
= 1
256
_ Crystal frequency 192x Baud rate
l
(MSB)
GATE
I C/T I
Ml
I
MO
I
GATE
(LSB)
I Cl~ I
Mt
GATE Gating control when set. Timer/cou.nter is enabled only while the !NTx pin is
err Ml MO
Ml
high and the TRx control pin is set. When cleared, the timer is enabled whenever the TRx control bit ts set Tuner or counter sele<:ted cleared for timer operation (input from internal system dock). Set for counter operation (input from Tx input pin). Mode bit I ModebitO
0
MO 0
Ml&• Operating Mode
0
I
I
I
0
2
I
I
0
3
13-bit timer mode S-bil timer/ counter TI-Ix with nx as 5-bit prescaler 16-bil timer mode 16·bit timer/ counters THx and TLx are cascaded· th . no prescaJer. , ere lS S-bit auto reload S-bit auto reload tim I to be reloaded into cou~t~r; THx holds a value tha t is x eac time ,1 overflows. Split timer mode
Tr
Figwe A-8. TMOO Register (not Bit-addressable)
•
APPIINDIXA
DO
07
I
TFI
TIU
TFO
I
TRO
1 m
CEO
ITO ]
Tfl
TCON .7
Timer J overflow flag. Set by hardware when timerI counter 1 overflows. Cleared by hardware as the processor vectors to the interrupt service routine.
TR1
TCON.6
Timer 1 run control bit. Set/ cleared by software to tum timer/ counter 1 on/ off.
TFO
TCON.5
Timer Ooverflow flag. Set by hardware when timer/ counter 0 overflows. Cleared by hardware as the processor vectors to the service routine.
TRO
TCON.4
Tuner Orun control bit. Set/ cleared by software to turn timer / counter O on/ off.
lEl
TCON.3
External inter rupt 1 edge flag. Set by CPU when the external interrupt edge (H·to-L transition) is detected. Cleared by CPU when the interrupt is processed. Nott: This flag does not latch low-level triggered interrupts.
m
TCON.2
Interrupt 1 type control bit. Set/ cleared by software to specify falling edge/ low-level triggered extem al interru.pt.
IEO
TCON.1
Extemal interrupt Oedge flag. Set by CPU when external interrupt (H·to·L transition) edge detected. Cleared by CPU when interrupt is processed. Note:This flag does not latch low-level triggered interrupts.
ITO
TCON.O
Interrupt O type control bit. Set/ cleared by software to specify falling edge/low-level triggered external interrupt.
Figu.tt A-9. TCON (Timer/Counter) Regist4'r (Bit-addressable)
Al'PENDIXA
1E1
APPENDIXB
BASICS OF WIRE WRAPPING
OVERVIEW This appendix shows the basics of wire wrapping.
487
I
l
BASICS OF WIRE WRAPPING
f UowinS: . . ou will need the o Note: For this tutonal ap~clix, Y ber 276-1570) ~\lite-wrapping tool (Radio Sha.ck part n~ this section.) :JO-gauge (30-A~\IG) wire for wrre wrapp~; for their assistance on (Thanks to Shannon Looper and Greg Boy · .
Th following descn"bes the basics of wire wrappmg. . available from Radio Shack for less e Th best one 1s fu ti · h . tools available. e . the wrap and unwrap nc ons m t e I. There are several different typesR odi~ w:;;r~;276-JS70. 'fhjs tool cthio~~:: much easier to use than the tools that O 5 • than SJO. The part number for a tripper. we found p guns, which are, of course, more
same end of the tool and includes a separate~ shaft. There are also wrre-wra combined all these features on one two-ende . d . . . ulk spool The prestrippe wire 1s usuexpensive. . . various lengths or in b on a f~ t buy Bulk wire can be cut · 2. Wire-wrapping wire is available prestnpped in different wire lengths you can a or O ally more expensive and you are restricted to the ft 1 to any length you wish, which allows each wire to be custom • Uy called perfboards or wire- wrap boards. 3. Serveral different types of wire-wrap boards are available. Th:a:r;:; aShack). The best type of board has plating 0 These types of boards are sold at many electronics store:d~':.re better because the sockets and pins can be soldered arowid the holes on the bottom of the board. These boa bl to the board, which makes the circuit more mechanically sta e. . d . · th room to spare so that the wirod te all the parts u, your es,gn w1 4. Choose a board that is largeenoug h toaccomm a . ct · the future you should be sure to include 01 ing does not become too cluttered. If you wish to expan~ your P( e.f u, ible the' layout of the IC on the board enough room on the original board for the complete rucwt. A so, t po~s , needs be done such that signals go from left to nght JUSt ltke the schematics. s. To make the wiring easier and to keep pressure off the pins, install one standoff on eda<:h co~erbockfthe board. You may also wish to put standoffs on the top of the board to add stability when the boar IS on its a . 6. For power hook-up, use some type of standard binding post. Solder a few single wire-wrap pins to each power post to make circuit connections (to at least one pin for each IC in the circuit).
d
7.
To further reduce problems with power, each IC must have its own connection to the main power of the board. If your perfboard does not have built-in power buses, run a separate power and ground wire from each IC to the main power. In other words, 00 NOT daisy chain (chip-to-chip connection is called daisy chain) powe r connections, as each connection down the line will have more wire and more resistance to get power through. However, daisy chaining is acceptable for other connections such as data, address, and control buses.
8.
You mustaround use wire-wrap wrapped the pm. sockets. These sockets have long square pins whose edges will cut into the wire as it is
9.
i
Wire wrapping will not work on round legs. U you need to wrap to co round I""• you must al$O solder these connectio Th '--· mponents, such as capacitors, that have """'' ns. e =t way to connect sing!e components IS · to UlSt · all tn · d'1vidual wire-wrap pins into the board and then solder the components to . to use an empty IC socket to hold small components s uch as resistors d th the pins · An alternate meth o d 1s . should be stripped . . an10wrap em to the socket 10. The wire about 1 inch. This will allow 7 to tu and-a-half should be insulated. This prevents s tripped Wire f ms _for ~ach connection. The first tum or turn· accomplished by inserting the wire as far as it will go into th rtomlbconung in contact with other pirls. This can be 11. Try to keep wire lengths to a minimum. This prevents th e. oo. efore making the connection. 1;om _looking Hke a bird nest. Be neat and use color coding as much as possible. Use only red wires for ve ferent colors for data, address, and control signal connecti cc Th 1 ck wires for ground connect· Al difeasier. ons. ese suggesti . ions. so use . to connect all power lines first and ch ons will make troubleshooting much 12. It .is standard practJce on. eek them for contin i . . , also a good idea . . orientation . u ty.1'hjg wil l eliminate trouble later 13. Its to mark the pm on th bo pin numbers preprinted on them specifically for this e ttom o( the board. Pl ti to reverse pin order when looking at the bottom of :~se o~ you Ci\n make as c templates are available ~ith circuits. e Dard ts a very corrun your ?Wn from paper. Forgetting on mistake when wire wrapping
:~u;,
-
APPENDIX &
To prevent damage to your circuit, place a diode {such as INS338) in reverse bias across the power supply. Uthe 14· wer gets hooked up backwards, the diode will be forward biased and will act as a short, keeping the reversed ~Jtage from your circuit. • Jn digital circuits, there can be a problem with current demand on the pov.rer supply. To filter the noise on the 1 '' p0wer supply, a 100 µF electrolytic capacitor and a 0.1 µP monolithic capacitor are connected from Vq:. t~ ground, ill parallel wtlh each other, at the entry point of the power supply to the board. These two together will filter both the high· and the low-frequency noises. Instead of using two capacitors in parallel, you can use a single 20-100 µF taJ\talum capaotor. Remember that the long lead is the positive one. t6. To 6Jter the transient current, use a 0.1 µP monolithic capacitor for each IC. Place the 0.1 µF monolithic capacitor t,etween Vcc and ground of each IC. Make sure the leads are as short as possible.
IC#l
IC#2
figure B-1. Daisy Chain Connection (not recommended for power lines)
IC#3
IC#4
-
APPENDIXC
IC TECHNOLOGY AND SYSTEM DESIGN ISSUES
OVERVIEW This appendix provides an overview of IC technology and 8051 interfacing. In addition, we look at the microcontroller-based system as a whole and examine some general issues in system design. fin;t, in Section C.l, we provide an overview of IC technology. Then, in Section C.2, the internal details of 80511/0 porte and interfacing are discussed. Section C.3 examines system desip issues.
-
t91
-
s~
ments in advanced logic.families. . 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 15 . .11 ·IS assum ed that the reader this IS an overview, electronics books. h J950s, transistors replaced vacuum Transistors . t Bell Laboratory. Intht et the first integrated circuit was sue. . b thr scientists a til 1959 a C h f · The transistor was m,•ented m 1947 Y ee . ention of the I , t e use o transistors II was not un tubes in many electronics systems, including compu:er:~ents. Prior 10 the mv on in computer design. Early trans;; 5 cessfully fabricate~ and tested by Jack Kilby of:e::~t:rs and resistors, co~s was due to the fact that the slightest along with other discrete components such as P d ed in favor of silicon. . t In senuconductor terms it is 5 tors were made of gcrmani~, which. was later a~n : : germanium-based tr~nsJS or ~assive flow of electrons 'from rise in temperattue resulted m ~ass'.ve current than that of silicon, r~sulttntm;elate 1960s and early 1970s th because the band gap of germanium 1s much sma1er rises even slightly. vY . , e the valence band to the conduction band wh~n the_ temperatu~ minicomputers. Transistors a nd ICs at first were based use of the silicon-based JC was widespread m mainframes an . much higher (about two and a half times) than eed of electroris 1s · h a d replaced th on P-type materials. Lateron,dueto thefoct that esp_ ' d. 19705 NPN and NMOS transistors the speed of holes, N-type devices replaced P·type devices. By the mi. s du,stry including in the design of microproc. . 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
~"?
f"'
t ' n
MOS vs. bipolar transistors There are two type of transistors: bipolar and MOS (metal-oxide semicond~cto.r). Both have .three leads. ln bipolar transistors, the three leads arc referred to as the emitter, base, and collector, while m MOS transtStors they are named source, gate, and drni11. In bipolar transistors, the carrier Rows from the emitter to the collector, and the base is used as a flow controller. In MOS transistors, the carrier flows from the source to the drain, and the gate is used as a flow controller. Jn NPN-typc bipolar transistors, the electron carrier leaving the emitter must overcome nvo voltage barriers before it reaches the collector (see Figure C-1). One is the N-P junction of the emitter-base and the other is the P-N junction of !"'e base-co~ector. The ."oltage bamer of the bas~o~ector is the most difficult one fo r the electrons to overcome (since it IS reverse-biased) and 1t cause~ the most power dissipation. This led to the design of the unipola r type transistor called MOS. In N-channel MOS transistors, the electrons leave the source and reach the dram· 'th t · thr h It · The av..-nce '-·. .m the path of the CaJ'rier is one rea w1 ou going· · o ug any vo • of any ,•oltage barner age ba mer. power than bipolar transistors The low power dis's· ti f MOS son why MOS d 1ss1pa tes much less · •pa on o allows ·u· f · · c chip. ln today's technology, putting 10 million transistors into an IC is co nu ions ~ transistors to £it on a single I Without the MOS transistor, the advent of. desktop personal mmon, and it is all because of MOS technology. O soon. The bipolaJ' transistors in both the mainframes and mputers would not have been possible, a t least not so expensive cooling systems and large rooms. MOS transistors d~~::::~eof th_e 1960s and 1970s were b ulky and required maior dra wback: They are slo,ver than bipolar
mini/
C N 8 p E N
C
Oxide
E
Bipol,n NPN Trans istor
NMos Trans istor Figur• C-1. Bipolar vs. MOS Transisto"'
APPENDIX C
f t
transistors. This is du_e partly to the gate capacitance of the MOS transistor. For a MOS to be turned on, the input capacitor of the gate ta.Ices time to charge up to the tum-on (threshold) voltage, leading to a long~ propagation delay.
overview of logic families Logic fa?'~l~es are judged according to (1) speed, (2) power dissipation, (3) noise immunlty, (4) input/ou~ut inter/a~ c~mpahbthty, and (5) cost. Desirable qualities are high speed, low power dissipation,. and high no,~ tmmuruty (s111ce ti prevents the occurrence of false logic signals during switching transition). In interfacing logic famthes, the ~ore in~uts that can be driven ~y a single output, the better. This means that high-driving-capability outputs are des,red. '[his, plus the fact that the .•nput and output voltage levels of MOS and bipolar transistors are not compatible ?'ean th~t Olle _m~t _ be ~oncem_ed with the ability of one logic family to drive the other one. ~ terms of th~ cost of a given logic family, ti ts high during the early years of its introduction but it declines as production and use rise.
The case of Inverters As an example_ of logic gates, we look at a simple inverter. ln a one-transistor inverter, the transisto~ play~ the r~le
of a switch, and R ts the pull-up resistor. See Figure C-2. However, for this inverter to work most effecbvcly tn digital circuits, the R value must be high when the transistor is "on" to limit the current Oow from V<'C to ground in order to have low power dissipation (P =VT, where V = s V). Ln other words, the lower the I, the lower the power dissipation. On the other hand, when the transistor is "off", R must be a small value to Um.it the voltage drop across R, thereby making su.re that Vour is close to Vcc- This is a contradictory demand on R. This is one reason that logic gate designers use active componen.ts (transistors) instead of passive components (resistors) to implement the p111J-up resistor R. Vee
Vee
Vee
Re
Re
Re
Out In
Low
Hlgh
Re must be a very high value.
Low
) - - High
Re must bea
very low value.
Figu~ C-2. One-T raruoistor lnv•rt•r with Pull•up Resistor
The case or a TTL inverter with totem-pole output is shown in Figure C-3. ln Figure C-3, Q3 plays the role of a pullup resistor. ,--..,...--,- Vee
. - - - , - - - . - Vee Vee
H,gh input
Fi.... C-3. Tn lan*r with To-·Pol• Output
AIPENoixc
Input
-
..orr Input V 5
J
PMOS OV Output
Input
OV
i - --
sv
Output
NMOS
NMOS
'"off,.
"on''
Figutt C-4. CMOS Inverter
CMOS inverter In the case of CMOS-based logic gates, PMOS and NMOS are used to construct a CM_OS (comple~entary MOS) inverter as shown in Figure C-4. In CMOS inverters, when the PMOS transistor is off, it provides a very high unpedance path, making leakage current almost zero (about 10 nA); when the PMOS is on, it provides a low resis tance on the path of V00 to load. Since the speed of the hole is slower than that of lhe electron, the PM OS transistor is ,vider to compensate 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 slandard TTL (trans,s tor-trans,stor logic) family. The firs t MOS-based logic family the C D4000/ 74C · k d in 1970. The addition of the Schottky diode to the base-collector of bipolar tran'sis tors m · th I se19~0es, was mar ete ·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 o•c a ,es. able C-1, note that
Table C-1: Characteristics of Some Logic Families ChaJ"acteristic
STD TTL
~
SV 2.0 V 0.8 V 2.4 V
0.4 V - l.6mA 40µA
'"'-
JOH
16mA -400µ.A
Propagation delay
lOns
Static power dissipation (f = 0) Dynamic power dissipation
IOmw
..
JO mW
Hi
LSTTL
ALS1"fL
5V
H CMOS
5V
2.0 V
sv
2.ov
0.8 V
o.s v
2.7V 0.5 V -0,36mA
20µA
8mA
--400 µA 9.5ns
2mw 2 mW
2.7V 0.4 V -0.2 ll\A 20 µA
4mA
--400 µA 4 ns
l mW lrnW
3.15 V 1.1 V
3.7V 0.4 V
- 1 µA
1 µA 4rnA 4 rnA
9ns 0.0025 nW
0.17 mW
APPENOIX C
ml f(
Ta
f able C-2: Logic Family Overview Sp eed (ns)
Static Su pply Current (mA)
High/Low Family D rive (mA)
1968
40
30
- 2/32
1970
70
0.3
-0.48/6.4
~ /5 ttC/ HCT
1971
18
54
- 15/24
1977
25
0.08
-6/- 6
FAST AS
1978
6.5
90
- 15/64
1980
6.2
90
- 15/64
ALS
1980
10
27
- 15/64
AC/ACT
1985 1986
10 6.5
0.08 1.5
- 24/ 24 -15/64
Year Introd uced
Std 1TL cD4K/ 74C
product
FCT
Reprinted by permission of Electronic Design Magazine, c. 1991.
as the CMOS circuit's operating frequency rises, the power dissipation also increases. This is not the case for bipolar-
based TTL.
History of logic families Early logic families and microprocessors required both positive and negative power voltages. In the mid-1970s, 5 V Vcc became standard. In the late 1970s, advances in IC technology allowed combining the speed and drive of the Sfamily with the lower power of l.S to form a new logic family called FAST (Fairchild Advanced Schottky TTL). In 1985, AC/ ACT (Advanced CMOS Technology), a much higher speed version of HCMOS, was introduced. With the introduction of FCT (Fast CMOS Technology) in 1986, the speed gap between CMOS and TTL at last was closed. Since FCT is the CMOS vers ion of FAST, it has the low power consumption of CMOS but the speed is comparable with ·rrL. Table C-2 provides an overview of logic families up to FCT.
Recent advances In loglc famllles As the speed of high-performance microprocessors reached 25 MHz, it shortened the CPU's cycle time, leaving less time for the path delay. Designers normally allocate no more than 25% of a CPU's cycle time budget to path delay. Following this rule means that there m ust be a corresponding decline in the p ropagation delay of logic families used in the address and data path as the system frequency is increased. In recent years, many semiconductor manufacturers have responded to this need by providing logic families that have high sp eed , low noise, and high drive 1/ 0. Table C-3 provides the characteristics of high-per formance logic families introd uced in recent years. ACQ/ ACTQ are
Table C-3: Advanced Logic General Characteristics Family
-ACQ
-ACTQ
--8CT
fCTx fCTxT
FASTr
Tech Base
1/0 Level
Speed (ns)
Static Current
1o./IoL
1989
2
CMOS
CMOS/CMOS
6.0
80µA
-24/ 24mA
1989
2
CMOS
TTL/CMOS
7.5
80 µA
- 24/ 24mA
1987
3
CMOS
TTL/ CMOS
4.1 - 4.8
l.5mA
- 15/64mA
1990
2
CMOS
TTL/TTL
4.1 - 4.8
1.S mA
- 15 / 64mA
l 2
Bipolar BICMOS
TTL/ TTL TTL/ TTL
3.9
SOmA
5.5
l OmA
- 15/64 mA - 15 / 64mA
Year
Number Suppliers
1990 1987
P.ti,,u,~ by penni.ton of Elec:trOnlc Design Magazine, c. 1991.
APl'!Notxc
495
. . . - - - . - - , , Vc.c ACMOS) with much ( advanced CM OS . J ACTQ External the second-generation . 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 Figure C-5. Open Collector the low power consumption of CMOS has given birth to what 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, External had to use high-speed bipolar transistors to speed up some of the mtemaJ func· pull-up tions.) Table C-3 provides advanced logic characteristics. The "x" is for differen t resistor speeds designated as A, B, and C. A is the slowest one while C is the fastest one. 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 Figure C-6. O pen Drain given d.ie size. As fabrication processes improve, the decline in the line size is reaching submicron level and transistor densities are approaching 1 billion transistors.
9
Open-collector and open-drain gates · To allow multiple outputs to be connected together we use O en -coll resistor will serve as load. This is shown in Figures C-S a'nd C _ _ P ector logic gates. In such cases, an external
-
6
SECTION C.2: 8051 VO PORT STRUCTURE AND INTERFACIN In interfacing the 8051 microcontroUer with other IC ch" d . G ~ders~and the8051 fan-out we must first unders tand the 0 ~ps or evices, fan-out is the most important issue. To discussion of the 8051 port structure and its fan-out. It is ~e t stru.cture of the 8051. This section rovides ad t . e ailed the 8051 lest we damage it while trying to interface 1.t .th ry critical that we understand the I/ PO port structure of w1 an external device.
'
IC fan-out . ~\/hen. connecting IC chips together, we need to find out pm. This 1s a very important issue and involves the dis how many input pins can b . be addressed for both logic " O" and logic " l " outp cuss1on of what is called IC e dnven by a single output as follows: uts. Fan-out for logic low and f fan-out. The IC fan-out must J an-out for logic high are defined fan-out (of low) ~ !.l1I.. fan-out (of high)"'~ I 11. I
"'
Of 11w above two values, the lower number is used 1111d IOU!dng of current when !Cs are connected to thto ensure the proper . ge er. noise margin p·
..
· igure C-7 show s the sinking
APPENDJXC
High
j
" Off'
j
(
\
lot
Low
(~ (
!IL
Ill
"On"
j
"On"
1o H
( !Di
l1L
}
IIH
)
Im
}
.... "OW' l oL = I]IL
loH = I: (IH
VOL = ~ (transistor) x IOL \
figutt C-7. Current Sinking and Sourcing in TIL
\
ExampleC-1
Find how many unit loads (UL) can be driven by the output of the LS logic family. Solution: The unit load is defined as I,,_= 1.6 mA and 1,,. = 40 µA. Table C-1 shows Io,.• 400 µA and I = 8 mA for the LS family. Therefore, we have OL
fan-out (low) ..
fan-out (high) "'
Ia .. 111
'
\·.
8mA =5
L6mA
Ia. 400pA •18 1,,
40pA
This means that the fm-olitls 5. li\ ~ words, the LS output must Nltbe'wlaihlled*'mmetban S Inputs with unit load cha~c:11-
' Notice that in Figure C-7, as the number of input pins connected to a single output increases, IOI. rises, which causes Va. to rise. If this continues, the rise of VOL makes the noise margin smaller, and this results in the occurrence of false
logic due to the slightest noise.
74LS244 and 74LS245 buffers/drivers In cases where the receiver current requirements exceed the driver's capability, we must use buffers/drivers such as the 74LS245 and 741.$244. Figure C-8 shows the internal gates for the 74l.S244 and 74LS245. The 74l.S245 is used for bidirectional data buses, and the 74l.S244 is used for unidirectional address buses.
•
ld'PENntxc
•
/ Vee
Al
I
-
A2 L..--;J--N
IG
Ve,;
lA-2
IY-2
IA-3
lY-3
lA-4
lY-4
A5 A6 A7
2Y-1
2Y·3
B7 BB
Enable G
-
IC
I
L L H
,
Figure C-8 (;i). 74LS244 Oct.J Buffer (Reprm1ed by permi>.5ion or Toxas lnstrume,,18, Copyright Texas mstruments. 1988)
(~
Enable
Direction control OnPration DIR B Data to ABus L A Data toB Bus H Isolation X
Figitrt C-a (1>). 74LS245 Bidfrectional Buffer (!«,printed by permission o( Texas Instruments, Copyright Texas
Notice that the 74t.5244 is simply 8 tri-state buffe_rs in a single chip. As shown in Figure C-9 a tri-state buffer ha.s a ~mgle tnput, a single output, and the enable control input. By acbvating the enable, data at the input is transferred to the output. The ena?le can be an active-low or an active-high. Notice that the enable tnput for the 74LS244 is an active low whereas the enable input pin for Figure C-9 is active high.
(A)
~
(c)
Out Tri-state control (active high)
~ • , H
It must be noted that the output of the 741.S245 and 741.S244 can sink and source a much larger amount of current than that of other LS gates. See Table C-4. That is the reason we use these buffers for driver when a signal is travelling a long distance through a cable or it has to drive many inputs. After this background on the fan-out, next we discuss the structure of 8051 ports. We first discuss the structure of Pl - P3 since their structure is slightly different from the structure of PO.
P1 • P3 structure and operation Since all the ports of 8051 are bidirectional they all have the foll I.
2. 3.
D latch Output driver Input buffer
(b)
LT" H
(d)
74LS245 and 74LS244 fan-out
•
Reldir
lnstrumenl8, 1988)
Tri-state buffer
-
C·
Function Table
2Y·4
~
CND
B6
DIR Direetion control
2Y-2
.,"
2A-4
BS
A8 '-r'l"l
.",
2A-3
B4
A4
I{
2A-2
B3
A3
IY-1
IA-I
2A-l
GNDB1 ,----,-B;;::2:,
-1?:-
y' Low
H.igh-impedence (open-circuit)
Table C-4: Electrical Specifications for Buffers/Drivers 3
3
t Ase
The
.'
Sine
l
Wh,
lllp1
I Wh,
ln 0 Tll1
and
Figure C-9. Tri-Sute Buffer
74LS244 74LS245 . '"-- _
As¥ Ii.at bit.
12 12
owing uu,:e components in their structure;
APPENDJXC
Vcc
Read latch ,.
TB2
Load (Ll )
"
L.. ~
Internal CPU bus
Write to latch
D
Pl·X CJk Q
Read pin
Pl ·X pin
Q : ~Ml
l
TB1
figuttC·lO. 8051 Port 1 Structure
Figu~e C-10 shows _the structure of Pl and its three components. The other ports, P2 and P3, are basicaUy the ~me except with e xlTa c,rcwtry to allow their dual functions (see Chapter 14). Notice in Figure C-10 that the Ll load 1s an internal load for Pl, P2, and P3. As we will see at the end of this section, that is not the case for PO. Also notice that in Figure C-10, the 8051 ports have both the latch and buffer. Now the question is, in reading the port, are we reading the status of the input pin or are we reading the status of the latch? That is an extremely important question and its answer depends on which instruction we are using. Therefore, when reading the ports there are two po55ibilities: (1) reading the input pin, or (2) reading the latch. The above distinction is very important and must be understood lest you damage the 8051 port. Each is described next.
Reading the input pin As we stated in Chapter 4, to make any bits of any port of 8051 an input port, we first must write a 1 (logic high) to that bit. Look at the following sequence of events to see why. I. As can be seen from Figure C-11, a 1 written to the port bit is written to the latch and the D latch has "high" on its Q. Therefore, Q 1 and Q = 0. 2. Since Q = Oand is connected to the transistor Ml gate, the Ml transistor is off. 3. When the Ml transistor is off, it blocks any path to the ground for any signal connected to the input pin and the input signal is directed to the tri-state TBl. 4. When reading the input port in instructions such as "MOV A, Pl• we are reaUy reading the data present at the pin. In other words, it is bringing into the CPU the status of the external pin. This instruction activates the read pin of TBI (tristate buffer 1) and lets data at the pins flow into the CPU's internal bus. Figures C-11 and C-12 show high and low signals at the input, respectively.
=
Vee Read latch - - - - ,
TB2
Internal __..,~--1.fn- nl-_J CPU bus D Q 'I' Pl ·X '0' Write to latch - ~ - - l Ok Q 1 - - - - - - - 1 Off Read pin _ _ _.,
Figure C·lL Reading #High" at Input Pin
APl'ENorxc
TBI
Load (Ll)
High
Pl ·X
pin
/ Vee Read latch - - - ,
1.,oad (LI)
TB2
~t-.'..::---i
Internal -
+--
CPU bus Pl ·X 'O' Write to latch --
Read pin _ __.,
Pl ·X pin
'I'
Q
0
Low
Tlll
Ml
~
0t(ft
,,,..-
Figure C-12. R..djng •1..ow• •t tht lnput Pin
Writing "O" to the port •
11
t' b·ts m · order to make it an input port. ru gh" to a por s 1 • . t port? From Figure C-13 we see that if
The above discussion s howed why we mus t write•. What happens if we write a "O" to a port that ~as conf,gured ~5 '.:'~Uthe Ml transistor is "on". If Ml is "on," 1 we write a O(low) to port bits, then Q = 0 and Q = 1.. As a re~\l ~ for~ an attempt to read the input pin will ; p ·J This can also damage the port, as it provides the path to ground for both LJ and the input pin. f there always get the "low" ground signal regardless of the s tatus o e 1npu 1 · e,cplained next.
i°5
Avoid damaging the port We must be very careful when connecting a switch to an input port of the 8051. This is due to the fact that the wrong kind of connection can damage the port. Look at Figure C-13. If a switch with v,, and ground is connected directly to the pin and the Ml transistor is "on" it will sink current from both internal load Ll and external Vcc· This can be too much current for Ml , which will blow the transis tor and, as a result, damage the port bit. There aie several ways to avoid this problem. They are shown in Figures C-14, C-15, and C-16.
.
I.
One way is to have a lOK-ohm resistor on the Vcc path to limit current flow through the Ml transistor. See Figure C-14.
2.
The second method is to use_a switch with a ground only, and no Vee, as shown in Figure C-15. In this m ethod we read a low when the SW1tch 1s pressed and we read a high when it is released . '
Read latch
Vee
TB2 Internal CPU bus
Write to latch
D
Q
Pl·X Clk Q
'O'
ll
Load {LI)
'\
__/
'I'
On
tMI
__:~_J
Read pin -~=-:=.=:,fJ"-:TBrait______
T Vee
Pl·X pin
wiU damage Ml
Figu,e C-13. Never Conntct Dirttt Vtt to lht 8051 Port Pin
APPl!NDIXC
rptC-1!
Vee
Read latch TB2
J
..... Internal CPU bus
'--
D
Q
Voc 10K
~
Pl ·X pin
Pl·X Clk Q
Write to latch
-
Load {Ll)
;~
A
I" TBl
Read pin
.
.
figute C·14. lnput Switch with Pull-Up Resistor
Read latch
Internal CPU bus Write to latch
Vee
~
TB2 L-
Pl·X
Pl ·X Clk Q
•
'
/I
Read pin
,
..L
Q
D
.
Load {Ll)
Ml pin
&
I" TBl
.
figure C·lS. Input Switch with No Vcc
Voc
Read latch
TB2
Voc
Load (Ll) 74l.S244
lntema.l CPU bus Write to latch
Read p i n - - ~
Q
D
Pl·X Clk Q
Ml
b
Pl ·X pin
TBl
Figure C-16. Buffering Input Switch with Direct Vcc 3.
Another way is to connect any input switch to a 74LS244 tri-state buffer before it is fed to the 8051 pin. Trus is shown in Figure C-16.
The above points are extermely important an~ must be emphasized since many people damage thetr ports and wonder how it happened. We must also use the right instruction when we want to read the status ~f an input pin. Table C-5 shows the list of instruchons in which reading the port reads the status of the tnput pin.
>.Pt>!No1Xc
Table C-5: Instructions Reading the Status of Input Port Mnemonics
Examples
MOV A,PX
MOV A,Pl
JNB PX. Y, ...
JNB Pl.2,TARGET
JB
PX.Y, ...
MOV C,PX.Y CJNE A,PX, ...
JB Pl.3,TARGET
MOV C,Pl.4 CJNE A,Pl,TARGET
Vee Read latch
JL-
Internal CPU bus
Wnte to latch
--
• T82
Pl ·X pin
Q
D
Pl·X Ok Q
~II
I I
\1
,, Read pm
Load (Ll)
T61 (olf)
figure C-17. Reading th• Latch
Reading latch
h d the lalch we next consider the case . . d the port and ot ers rca , . ds th Since, in reading the port, sorne u\Struchons rca • • . example of an instruction that rea e of readlng the port where it reads the internal port latch: ANLk'Pl' ~ac~ :en an instruction such as "ANL Pl, A" is latch instead ol the input pin. Look at the sequence of actJons ta mg P e~ecuted. . 7) d b · th data from the Q latch into the CPU. 1. The read latch activates the tri•statc buffer ol TB2 (Figure · 1 an nn~ e
·
c
2. This data 1s ANDed with the contents of register A. 3. The result is rewritten to the latch. After rewnting the result to the latch, there are two possibilities: (1) If Q = 0, then O= 1 and Ml is "on," and ~e output pin has "O," the same as the status ol the Q latch. (2) If Q l , then Q = 0 and the Ml is "off," and the output pm has · 1,• the same as the status o( the Q latch. From the above discussion. we conclude that the instruction that reads the latch normally reads a value, performs an operation (possibly changing the value), and rewntes the value to the latch. This is often called "read-modify-write." Table C-6 provides a list ol read-modify-write instructions. Notice from Table C-6 that all the read-modify-write instructions u,e the port as the destination operand.
=
PO structure A major difference between PO and other ports is that PO has no intemal pull-up resistors. (The reason is to allow it to multiplex address and data. See Chapter 14 for a detailed discussion of address/data multiplexing.) Since PO has no Ullemal pull-up resistors, ,t is simply an opendrain as shown in Figure C-18. (Open-drain in MOS is the same u open-coUector in TTI.). Now by writing a •1• to the bit latch, the Ml transistor is "off• and that causes the pin to lloaL That is the reason why when PO is used for simple data 1/0 we must COMect it to extemal pull-up resistors. As can be seen from Figures C-18 and C-19, (or a PO bit to dri,·e an input. there must be a pull-up resistor to source current. Notice that when PO ts used for address/data mu]. tiplexing and i_t is conntcted to the 74lS373 to latch the addn!,Js, there IS no need for external pull-up resistors as shown in detail in Chapter 14. '
-
Table C-6: Read-Modify-Write Instructions Mnemonics ANL
ORL
XRL JBc CPL INC DEC
-DJNz
-MOV PX.Y,C ~LR PX.Y SET& PX. y
-
Exam.pie ANL Pl,A ORL
Pl,A
XRL Pl,A
Jl!C Pl.l,TARGBT CPL Pl.2 INC Pl DEC Pl DJNz Pl , TARGET HOV Pl.2,C CLR Pl.3 SBTB Pl. 4
4ff1ND1XC
.-c1161 ft
Read latch • TB2 Internal CPU bus
PO·X pin
Q
D
PO·X Clk Q
-
Write to latch
<'!
Read pin
: ~ Ml
TBl
Figure C-18. PO Structure (notice open-drain)
Vee
Read latch - - - -
Internal CPU bus _
TB2
._----1 D
lOK
Read pin - -- - '
1--- - - PO·X
Q
PO·X Write to latch -+---! Clk Q
External pull-up resisto r pin
1 - - - - -- - 1
Ml
TBl
Figure C-19. PO With External Pull-Up Resistor
8051 fan-out Now that we are familiar with the port structure of the 8051, we need to examine the fan-out for the 8051 microconctroller. While the early 8051 microcontrollers were based on NMOS IC technology, today's 8051 microcontrollers are all based on CMOS technology. However, note that while the core of the 8051 microcontroller is CMOS, the circuitry driving its pins is all TTL compatible. That is, the 8051 is a CMOS-based product with TTL-compatible pins.
P1, P2, and P3 fan-out The three ports of Pl, P2, and P3 have the same l/0 structure, and therefore the same fan-out. Table C-7 provides the 1/0 characteristics of Pl, P2, and P3.
Port Ofan-out PO requires external pull-up resistors in o~er to drive ~ input since it is an open drain I/0. The value of this resistor deades the Ian-out. However, since Io,_= 3.2 mA for VoL = 0.45 ':', we must make sure that the pull-up resistor connected to each pm of the PO is no less than 1422 ohms, since (5 V - 0.45 V) I 3.2 mA = 1422 ohms. ln applications in which PO is not connected to an external pull-up resistor, or is used in bus mode connected to a 74LS373 or other chip, it can drive up to 8 lS TTL inputs.
APPENorx c
Table C-7: 8051 Fan-out for Pl, P2, P3 Pin
Fan-out
IOL
l.6mA
!OH
60µA
llL
SOµA 650µA
IDi
Nair. Pl. P2.u1d P3c.ndrivtupto4 LSTil. inputs wi..
connectod to olJ,er JC chip.
, •
74LS244 driving an output pin .
. ,. g multiple infuts,
,----1---T14 >--t-- DO
when an 8051 port 1s dnHn e (e.g., printer ut via a long wire or cab! driving an 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. In many cases .
SECTION C.3: SYSTEM DESIGN ISSUES
74LS244
8051 Pl
Printer data
D7 port
P2.tf---~ t---ACK
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 topics.
74LS244 . C•20 · 8051 Connection to Printer Signals Figure
r dissipation considerations
P
.
.
owe . concem in of which systembatteries provide . the power . Power dissipation 1s a Power dissipation of a system .,s a ma1or ers, especially for laptop and hand-held sy~tems
desi
func':::m of frequency and voltage as shown b~o:"cv
since
and
l=Q T
Asw• 11he ind ldtage d li!aken l
I= CVF /IOW
P= Vl=CV'F
In th bove uations the effects of frequency and Vcc voltage should be noted. While the power d issipation goes up ::n:arly Example C-2. :Ith freq~ency, the impact of the power supply voltage is much more pronounced (squared). See
-
Dynamic and static currents
...
Two major types of currents flow through an IC: dynamic and s tatic. A dynamic current is I = CVF. It is a function of the frequency under which the component is working. This means that as the frequency goes up , the dyn amic current and power dissipation go up. The ~ta tic curre~t, ~lso ~aUed DC, is ~e current consumption of the com ponent w h en it is inacti"e (not selected). The dynamic current ~,ss,pa.tion is much higher than the s tatic current consumption. To red uce power consumption, many nucrocontrollers, including the 8051, have power-saving modes. In th e 8051, the power saving modes are called idle mode and power down mode. Each one is described next.
1 The ' 14-pi
gale!
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.-,--
~
l'hll l9Ulla in 111ing 16 W 1-power,
..
1• have P • 5' • 25 Wand p • 32 whichmean,"°""-;;;;;:,'!:_a,;6125 We
JC
lOO) for 'J 13
a
9
w.
IW llling 3 V for powa
APPENOJXC
a 14tradi
/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 provide clock to the serial_Port, interrupt, and timers, but no clock is provided to the CPU. Notice that during this mode all Ille contents of the registers and on-dtip RAM re.m ain unchanged.
power down mode In the power ~own mode, the on-chip oscillator is frozen, which cuts off frequency to the CPU and peripheral func· tions, such as Sena] ports, interrupts, and timers. Notice that while this mode brings power consumption down to an absolute minimum, the contents of RAM and the SFR registers are saved and remain unchanged.
Ground bounce One of the major issues that designers of high-frequency systems must grapple ,vith is ground bounce. Be~ore we define ground bounce, we \¥ill discuss lead inductance of IC pins. There is a certain amount of capacitance, resistance, and inductance associated with each pin of the IC. The siZe of these elements varies depending on many factors such as length, area, and so on. The inductance of the pins is commonly referred to as self-inductance since there is also what is called 11111t11a/ inductancr, 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
DO Vout
OJ
02
Tune
03 1ccL
Ground Ground bounce occurs when data switches from all ls to all Os
Fla,u. C-21. t.) GIOIIJld 8 -
APPENDIXC
Translent current going from O to 1
(bl Transient Cunent
-
..
l 'ble to reduce the lead length. This is exactly d V as pass1 d d . 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, are over 50 pins . for. ground, and another .SO pins for V. cc· v when a large numb er o f ou tp u ts change.s ftom d
2.
The abothvehi~h10n of ground bounce 1s al~~ apphcab~~evtoer ~e effect of y cc bounce is not as severe as ground 8 ' ("0") state th e !ow to e g state·' this is referred to as Vcc wu11ce. o-. bounce since the high ("l ") state has a wider noise margin than the low ·
Filtering the transient currents using decoupling capacitors tn the TfL family, the change of the output from low to high can cause.what is called ~ransient current. In a totempole 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
.All
ii' ~
~r -
~·
of tl'
-"'l' ,..iii'
p . :rt• v·<>
al'cl tt30
5
i01'
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 capacitor can .be pl?ced between the Vcc and ground for each 1TL JC. However, the lead for this capacitor should be as small as poss'.ble.smce a long lead results in a large self-inductance, and that results in a spike on the Vcc line [V = L (di/ dt)J. Thisbulk sdpike lS ~ed Vcc, bounce. The ceramic capacitor for each IC is referred to as a decoupling capadtor. There is also a ecoupl1ng capaotor, as described next.
Bulk decoupling capacitor the :;;a;y~C chips change state at the same time, the combined currents drawn from board hs ccUpothwersupplycanbemassivea11dmaycauseaOuctuationofV on the w ere a e ICs are mounted T limin thi cc tantalum capacitor is placed behveen· tho ~ ate s, a r.e latively l~ge decoupling of this tantalum capacitor varies depend~ a: ground lines. The size and location amount of current drawn by each IC b i~~ ?n e number of ICs on the board and the capacitor for each of the 16 devices '1 ~~common to have a single 22 µF to 47 µF •P" hveen the Va: and ground lines.
•;d
Crosstalk
Figure C-22. Crosstalk (EMT)
~rosstalk is due to mutual inductan self-tnductance, which is inherent in a p ce. ~ Figure C-22. Previously, we discussed ~ ~lecbic lines running parallel toe:::th:n:ctor. Muh,al i11d11ct1111ce is caused , e ength of two conductors runnin . · e mutual inductance is a fun . the m~um material placed between th~: ~allel, d, the distance between th Ction mcreastng the distance between the rall 1' e effect of crosstalk can be redem, and they will be traces). In man . pa e or adjacent lines (in . . . uced by cated ground for each sisnii.c:r~guch as pdrmter and disk drive boards, the effect of crosstalk. This m . groun lines (ti:aces) betw . ' ~ lS a dediare a V and GNO . ethod is used even in some ACT I ee.n Stgnal lines reduces inlerfer~nce). This if';;, ~~:;o other. Crosstalk is also cal:~families where there capacitive coupling between::: od.ESI (electrostatic interferen ) Ml (electromagnetic o a iacent conductors. ce , which is caused by
:r1
~~:i:cu,.t
~·t
Ringing Buffer
Series terllli.nation
Transmission line ringing The square wave used in di . . . . pulse and man harm · gttal orcuits lS in reality not aU the h._n:onics :S~~f. v~ous amplitudes. When~ e .of a sing le funda
:i~:.':o
;~uses
~ ~~
1 fU::e !is w~at ~~~;h:~:citan:~~~:~~ on th:~~ drivers are termina~ ;ver, ~ong other factors. To redu depends on the thl : d resistare 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 · araIlei, serial re C-23. 1n ...._ , and Theve . ere ....., nm.
~
Para11e1lerrnination Figu~ c Trana •23. · Reducing OU..ton Line Ringing
APPENDIX C
....
)
APPENDIXD
FLOWCHARTS AND PSEUDOCODE
OVERVIEW
This appendix provides an introduction to writing ftowchans and pseudocode.
(Terminal)
. ses you are pro bably famil· If you have taken any previous progr~g cour ' esent different types iar with Oowcharting- Aowcharts IISe graphic symbols to r'J:r into a flowchart to 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· monly used symbols. Aowchart templates are available to h P you bols quickly and neatly.
FLOWCHARTS
(
' l
Process
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 control structures. Structured programming uses three basic types of program control structures: 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.
Subroutine
Input/ Output
Statement 1
Connector
Statement 1 Statement 2
0
Statement 2
Figure D·l. Cornmonly Used Flowchart Symbols
... figure D-2. SEQUENCE Pseudocode versus Flowchart
... I F (condition) THEN Statement 1
r---
Condition
ELSE
No
? Statement 2
Statement 1
IF (condit ion) 'l'H£N
Statement 2
Yes
State1t1ent Statement
....... D-3. IF TH!?N ELSE i'Hudoeode
..
•er1u1 Flowchart
Figure 0-4 {F
·
THEN p
-docode V"9ua Flowcbut
APPENDIXD
•
•
Note in Figures D·2 through D-6 that "statement" can indicate one statement or a group of statements. figures D-5 and D-6 show two iteration control structures: REPEAT UNTIL and WHILE DO. Both structures execute 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 (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 purpase of flowcharts or pseudocode is to show the flow of count • S the program and what the program does, not the specific Address • 40H Repeat Assembly language instructions that accomplish the proAdd next byte gram's objectives. Notice also that the pseudocode gives the Count= 5 Increment addreeo Address • 40H same information in a much more compact form than does Oecrement eoun ter the flowchart. It is important to note that sometimes pseuUntil Count • 0 docode is written in layexs, so that the outer level or layer 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 Decrement COUJ\teT
Statement UNTIL
(condition) No
No
'----
Count =07
? Yes
v.. Store sum
Figure D-5. REPEAT UNTIL Pseudocode versus Flowchart
(
Stop
)
Figure D-7. Pseudocode versus Flowchart for Program D-1 llilILE (condition) DO
Cond ition
No
7
Statement
CLR MOV MOV
Yes Snitement
BACK:
ADD
INC DJNZ
NOV Fig,a~ D1. WHILE DO PMudocod1t .,_.,. flowchart
Al'PENDIXD
A R0 , #40H R2 , #5 A, e RO RO R2,BACK B,A
;A ~ 0 ;addre ss ; counte r
Progt- D-1
511
I
~
.
'
"· '
"'
•
APPENDIXE
' • •
8051 PRIMER FOR X86 PROGRAMMERS
• •
.
·,
-.,,.'
. .'"'..
• • k
••
t
X86
8051
A,B,RO, Rl, R2, R3, R4, RS, R6, R7 DPTR
..'
16-bit (data pointer):
AL, AH, BL, BH, CL, CH, DL, DH BX, 51, DI
Program Counter:
fP(16-bit)
PC (16-bit)
•
8-bit registers:
..
•
~
MOV A,Pn
MOV DX.port addr OUT DX,AL
MOV Pn,A
DEC CL
DJNZ R3,TARGBT (Using RO-R7)
..
;(n•0-3) I
..
Output:
JNZ TARGET
Stacie pointer:
SP(l6-bit) As we PUSH data onto the stack, it decrements the SP. As we POP data from the stack, it increments the SP.
Data movement: From the code segment: MOV AL,CS: [SI) From the data segment: MOV AL, [SI]
From RAM: To RAM:
...
..' .•• .' ,
MOV DX,port addr IN AL,DX
.'
• • J'•
•
Input:
Loop:
.
..
••
; (n •
0 - 3)
SP(8-bit) As we PUSH data onto the atllek, it increments the SP. As we POP data from the &tllek.
:
,
•
•
...
•
•
• •
it decrements the SP.
MOVC A, eA+ PC
•
MOVX A, liDPTR
MOV AL, [Sl] (Use 51, DI, or BX only.)
MOV A,liRO (Use RO or Rt only.)
MOV [SI] ,AL
MOV eRO,A
••
•
•
•
'
••
•
•
••
•
'
'•• { •.
APPENDIXF
ASCII CODES Ctrl •11
Dec
•A
1
·e "C
·o •E •p
•c "H ·1 ·J
·x •L
-
."
"N -0
•p
•q •R "S
•r ·u
•
"II
·w "K
•y "Z
•c
"' •• •1
•
51f
Hex 88 81
Ch
l!2
II
..s
83 114
• •
6 ?
86 II?
8 9
88
e 2 3
18 11 12 13 14 15 16 1? 18 19 28 21 22 23 21 25 26 2? 28 29 31 31
HUL !iii
..
85
••
8A IIC
$
OD
I /I
15 16 1? 18 19 1A 18 1C 1D 1E 1P
EHQ
ACK
9 LP 6 UT
OB
11
SOH STX ETX EOT
BEL Cl BS 0 HT
119
BE 8P 18 11 12 13
Code
•
PP CR
so
SI ~ DLE 4 DCt I DC2 ! ! DC3
..
DC1
§
-
IMK
l
SYN ETB
f
CAH
'
sue
~
• L M
• "
EN
ESC PS
cs RS
UC
Doc Hex Ch 32 211 33 21 ! 31 22 35 23 36 24 $ 3? 25 X 38 26 39 • 2? 411 ( 28 41 ) 29 42 2A • 43 28 • 44 2C • 45 2D 46 2E . 17 2P ; 48 38 e 49 31 1 58 32 2 51 33 3 52 31 4 53 35 5 54 36 6 55 3? ? 56 38 8 S? 39 9 58 3A : 59 38 ; 68 3C < 61 JD • 62 3£ > 63 3P ?
..
•
'
-
Ch
Dec
Hex
I!
96
A 8
9?
C
99
D
180 181 182 183 184 185 186 18? 188 1119 118 111 112 113 114 115 116 11? 118 119 128 121 122 123 124 12S 126 12?
68 61 62 63 64 65 66 6? 68 69 6A 68 6C 6D 6E 6P 78 ?1 ?2
p
?3
s
?4 ?S ?6 ?? ?8 ?9 ?A ?B ?C
t
?S
Hex 48 11 42 43 44 45 46 4? 48 49 4A 48
)(
?6
4C
L
?? ?8 ?9
4D 4E 1P 58 51 52 S3 51
Dec
64 65 66 6? 68 69 ?9 ?1
?2 ?3
74
811 81 82 83 84 85 86 8? 88 89 98 91 92 93 94 95
ss 56 S? 58 59 SA 58
sc SD
SE SP
E p
G
H I J
"
H 0 p Q
R
s T
u u II X y
z C
' • ]
98
71)
?E ?P
Ch •
a b C
d
• f
g
h i j k
1
.. n 0
p
q
u u
w X
y
z (
I
>
..-
Dec
Hex
Ch
Dec
He><
128 129 130 131 132 133 134 135 136 13? 138 139 1411 141 142 143 144 145 14' 14? 148 149 1se 1S1 152 1S3 154 15S 1s6 15? 151 159
80 81 82 83 84 85 86 8? 88 89 BA BB BC 8D
<;
1611 161 162 163 164 165 166 16? 168 169 1?II 1?1 1?2 1?3 1?4 1?S 1?6 1?? 1?8 1?9 181 181 182 183 184 185 186 18? 188 189 191 191
All
BE BP 91! 91 92 93 94 95 96 9? 98 99 9A 9B 9C 9D 9E 9P
0
e ii :I
a ~ ~
e !!
e I •I
1
,.
A
E al
ft;
0 I!
0 0
u y
0
u
c
,, £
A>
f
Ai A2 A3 A4 AS A6 A? AB A9 AA AB AC AD AE AP BIi
B1 82 83 B4 BS B6
B? BB B9
Ch ,
"{ 6 ,
u ii
..
R
"t ~ ~
~
Ii
•
((
»
I I I I i 4 ti n
'll
BA BB
;i
BC
!J
BD BE BP
u
II
J
,
Dec
He ><
Ch
192 193 194 195 196 19? 198 199 2111! 2111 202 2113 2114 2115 2116 211? 208 219 211 211 212 213 214 21S 216 21? 218 219 221 221 222 223
Cl! Ct
...•
C2
T
C3 C4
~
cs
-
+ ~
C6 C?
II
CB
I!
C9
Ii !.!
CA CB
cc
;;
11 =
CD CE CF
",!,"
DI
u
D1
'r
D2
D3 D4 D5 D6 D?
"" 7
f
" ... II
DI D9 DA
,
DB
I
DC
• I
DD DE DP
T
r
I
•
Dec 224 225 226 22? 228 229 2311 231 232 233 234 235 236 23? 238 239 241 241 242 243 244 245 246 24? 241 249 258 251 252 253 254 255
Hex
Ch
Ell E1
a II
E2
r
E3
ES
I E a
E6
µ
E?
'(
E8
ll 8 II
E4
E9 EA EB EC ED
..•
EE
(
EP Pl P1
~
6
•
P2 P3 P4
<
PS P6 P?
J
r
n
Ill
"
PA PB PC PD PE pp
i
t
.
Ill
. .
.J
•
• I
515
.\PJ>ENDIXF
APPENDIXG
ASSEMBLERS, DEVELOPMENT RESOURCES, AND SUPPLIERS This appendix provides various sources for 8051 assemblers and trainers. In addition, it lists some suppliers for chips and other hardware needs. While these 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 them. You are neither encouraged nor discouraged from purchasing any of the products mentioned; you must make your own judgment in evaluating the products. This list is simply provided as a service to the reader. It also must be noted that the list of products is by no means complete or exhaustive. To suggest other products to be included in future editions of this book, please send your compa· ny's name, product name and description, and Tnternet address to the authors' e-mail listed in the introduction.
Keil www.keil.com Franklin Software
www.fsinc.com Dunfield Development Systems www.dunfield.com Figure G -1. Assembler S uppliers
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 sites. However, the size of code for these shareware versions is Limited to lK (or 2K). Figure G-1 lists some suppliers of assemblers.
www.MicroDigitalEd .com
RSR Electronics www.elexp.com
8051 TRAINERS There are many companies that produce and market 8051 trainers. Figure G-2 provides a list of some of then,. The following is a Web site for !'AQ (frequently asked questions) about the 8051: http: / / www.faqs.org/faqs/m1crocontrol1er-faq/ 8051 I
PARTS SUPPLIERS Figure C-3 provides a list of suppliers for many electronics parts.
Axiom Manufacturing 717 Lingco Dr. Ste. # 209 Richardson, TX 75081 (972) 994-9676 Fax: (972) 994-9170
www.axman.com
Rigel Corp. P. O. Box 90040 Gainesville, FL 32607 (352)373-4629 http:// rigelcorp.com Figure C-2. Triliner Suppliers
517
Mouser Electronics RSR Electronics Electronix Express 365 Blair Road Avenel, NJ 07001 Fax: (732)381-tSn Mail Order: 1-800-972·2225 1n New Je~y: (732) 381-$)20 www.elexp.com Altex Electronics
11342 tH-35 North San Antonio, TX 78233 Fax: (210) 637-326,1 Mail Order: 1-800·531·5369 wY.rw.altex.oom
Digi-Key 1-80().344-4539 (I..SOO.DIGI-KEY) PAX: (218) 681-3380 www.digikey.com Radio Shack Mail order: 1·800-THE· SHACK JDR Microdevices 1850South IOth St. San Jose, CA95112-1108 Sales 1-8()0.538-5000 (408) 494-1400 Fax: 1·800-538-5005 Fax: (408) 494-1420
958 N. Main St. Mansfield, TX 76063 1-800-,346-6813 w,'IW,inouser.com
Jameco Electronic 1355 Shoreway Road Belmont, CA94002-4l OO 1-8()0.831-4242 (415) 592-8097 Fax: J.80()-237-6948 Fax: (415) 592-2503 W\•1w•.jameco.com B. G. Micro
P. O. Box 280298 Dallas, TX 75228 J-800-276-2206 (orders only) (9n) 271-5546 Fax: (972) 271-2462 This is an excellent source of LCDs, !Cs, keypads, etc. www.bgmicro.com
-
Tanner Electronics
for
1100 Valwood Parkway, Suite #100 Carrollton, TX 75006 (9n) 242-8702 www.tannerelectronics.com
80:
In
Th• De
Ill
W\vw.jd.r.com
Figutt G-3. EltttTonics Suppli•rs
•
518
Al'Pl!NDIXG
...
APPENDIXH
DATA SHEETS infel.
MCS•-s1 PROGRAMMER'S GUIDE AND INSTRUCTION SET
The information presented in this chapter is collected from the MCse-51 Architectural Overview and the Hardware Description of the 8051, 8052 and 80C51 chapters of this book. The material has been selected and rearranged to form a quick and convenient reference for the programmers of the MCS-51. This guide pertains specifically to the 8051, 8052 and 80C51.
MEMORY ORGANIZATION PROGRAM MEMORY The 8051 has separate address spaces for Program Memory and Data Memory. The Program Memory can be up to 64K
bytes long. The lower 4K (8K for the 8052) may reside on-chip. Figure 1 shows a map of the 8051 program memory, and Figure 2 shows a map of the 8052 program memory. FFFP
FPFF ~
60 K
BYTES EXTERNAL OR
1000
0:1
..
64 K
BYTES EXTERNAL
AND
4J< BYTES INTERNAL
I
0000
27024~1
Figure 1. The 8051 PtojlaDI Memory
519
1"1
-
'S GUIDE AND INSTRUCTION SET
infel.
MCS~51 PROGRAMMER
/
FFFF.,__-- - 1
56K
BYTES
64K
EXTERNAL
BYTES - - OR
:
I
8 ~_K_ _F_N_A_L_ .....
l j . ._ _
-
EXTERNAL
ooooL------=27=0:;;--;249-2
fig Figure 2. The 8052 Program Memory
INI
Data Memory: 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
No are
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 (MOV @Ri). Figure 3 shows the 8051 and the 8052 Data Memory organization.
wr
wr
infel.
OA MCS~-51 PROGRAMMER'S GUIDE AN O INSTRUCTION SET
Ne
Sia
bl
Th lis
INTl1RNAL
1
FPr--------..
ic
SFRs
DIRECT ADDRESSING : /--"O:.:.;NL,.,,.,_:ot:_ _ _...j DfRECT&c INDIRECT ADDRESSING 00 .__ _ _ _ __ J
C1
64 1(
BYfES
RE
EXTERNAL
re-
-AN0--..,,•-1
to'
2.
•
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
SFRs DIRECT ADDRESSING ONLY
80 7F
64K
BYTES EXTERNAL
'--
--AND-- ~--1
DIRECT & INDIRECT ADDRESSING
00
0000'---- ----.....l
270249-4
Figure 3b. The 8052 Data Memory
INDIRECT ADDRESS AREA: Note that in Figure 3b the SFRs and the indirect address RAM have the same addresses (80H-OFFH). Nevertheless1 they are two separate areas and are accessed in two different ways. For example the instruction MOY
80H,#OAAH
writes OAAH to Port O which is one of the SFRs and the instruction R0,#80H MOY @RO,#OBBH MOY writes OBBH in location 80H of the data RAM. Thus, after execution of both of the above instructions Port Owill contain OAAH and location 80 of the RAM will contain OBBH. Note that the stack operations are examples of indirect addressing, so the upper 128 bytes of data RAM are available as stack space in those devices which implement 256 bytes of internal RAM.
DIRECT AND INDIRECT ADDRESS AREA: The 128 bytes of RAM which can be accessed by both direct and indirect addressing can be divided into 3 segments as listed below and shown in Figure 4. 1. Register Banks 0-3: Locations O through lFH (32 bytes). ASM-51 and the device after reset default to register bank 0. To use the other register banks the user must select them in the software (refer to the MCS-51 Micro Assembler User's Guide). Each register bank contains 8 one-byte registers, 0 through 7. Reset initializes the Stack Pointer to location 07H and it is incremented once to start from location 08H which is the first register (RO) of the second register bank. :n:ius, in order to use more than one register bank, the SP should be intialized to a different location of the RAM where it is not used for data storage (ie, higher part of the RAM). 2. Bit Addressable Area: 16 bytes have been assigned for this segment, 20H-2FH. Each one of the 128 bits of this segment can be directly addressed (0-7FH). The bits can be referred to in two ways both of which are acceptable by the ASM-51. One way is to refer to their addresses, ie. oto 7FH. The other way is with reference to bytes 20H to 2FH. Thus, bits 0-7 can also be referred to as bits 20.0-20.7, and bits 8-FH are the same as 21.0-21.7 and so on. Each of the 16 bytes in this segment can also be addressed as a byte. 3. Scratch Pad Area: Bytes 30H through 7FH are available to the user as data RAM. However, if the_stack pointer has been initialized to this area, enough nu.mber of bytes should be left aside to prevent SP data destruction.
521
~IXH
jr,i AND INSTRUCTION SET
-
MCS~ 51 PROGRAMMER'S GUIDE
infel.
/
sP fat Figure 4 shows the different segments of the on-chip RAM.
co:
,..,
I
cal
,i...E--- - -- - - 8 Bytes - - - - - -- ~
7ll
~t-~~~~~~~~~~~~~--1
68
~i--~~~~~~~~~~~~--l
7F 77
6F 67
SF
58
57
~r-----------__j 4F
SCRATCH PAD
.
AREA
~i--~~~~~~~~~~
3a1___________J 47 ~r--~~~~~~~~__J 3P
~r-------------37 =--==--o... ···
20
7F 2F ADDRESSABLE BIT 27 SEGMENT
18 3
W
10
08 00
2 1
17
REGISTER
OF
BANKS
'-~~~~~o~~-;--==]w ,
f'•gure 4.128 Bytes of RAM 0 . tree! ud ln~ct Add ress.ble
~~~~~-
.
270249-5
APPl!NDIXH
.....
infel.
MCS~-51 PROGRAMMER'S GUIDE AND INSTRUCTION SET
SPECIAL FUNCTION REGISTERS: Table 1 contains a list of all the SPRs and their addresses. Comparing Table 1 and Figure 5 shows that all of the SFRs that are byte and bit addressable are located on the first column of the diagram in Figure 5. Table 1
APP!NDIXH
Symbol
Name
•Ace ·B •PSW SP DPTR DPL DPH •po •p1 •p2 •p3 •1p •1E TMOD •TCON • + T2CON THO TLO TH1 TL1 +TH2 + TL2 + RCAP2H +RCAP2L • sCON SBUF PCON • d Bit addressable + - 8052 only
Accumulator B Register Program Status Word Stack Pointer Data Pointer 2 Bytes Low Byte High Byte Porto Port 1 Port 2 Port 3 Interrupt Priority Control Interrupt Enable Control Timer/Counter Mode Control Timer/Counter Control Timer/Counter 2 Control Timer/Counter O High Byte Timer/Counter O Low Byte Timer/Counter 1 High Byte Timer/Counter 1 Low Byte Timer/Counter 2 High Byte Timer/Counter 2 Low Byte TIC 2 Capture Reg. High Byte TIC 2 Capture Reg. Low Byte Serial Control Serial Data Buffer Power Control
Add re as OEOH OFOH ODOH 81H 82H 83H 80H 90H OAOH OBOH OB8H OA8H 89H 88H OC8H SCH 8AH 8DH 8BH OCDH OCCH OCBH OCAH 98H 99H 87H
• ~
infel.
MCSlt.61 PROGRAMMER'S GUIDE AND INSTRUCTION SET
WHAT DO THE SFRs CONTAIN JUST AFTER POWER-ON OR A RESET? Table 2 lists the contents of each SFR after power-<>n or a hardware -1.
Table 2. C-.C,, of the SFRe -
A0111o4w
·a
PSW SP DPTR DPH
· PO
.,,.
·TOON
• • T2CON
Tlt
00000000 00000000 00000000 00000000 00000000
•TH2
00000000
THO TLO
THI
00000000
SBUF
Indeterminate HMOS OXXXXXXX CHMOS OXXXOOOO
l052 orw,
I
ca co
T2CON
ea
IP
I .f
80
P3
87
M
IE
,-$
AO
P2
1<7
911
SCON
90
Pl
88
TCON
TMOD
TLO
1'1.1
80
PO
SP
DPL
OPH
RCAP2L
1\.2
RCAP2H
C
TH2
<.7
9F
SBUF
117 THO
THI
8f'
!'CON
&7
Figure 5
Blt -
•
PSW
-
·SCOH
+
D:
00
9'1
00000000 00000000 00000000
- U,-,od
•
Of
f
•Tl2 oRCAP2H +RCAP2t.
X
E7
ACC
08
oxoooooo
TMOO
EF
Eo
11111111 8051 )()()(00000, 8052 )()(000000 8051 OXXOOOOO, 8052 00000000 00000000
•IE
F7
B
E8
11111111 11111111
·P2 ·P3
FF
FO
00000000 00000000 11111111
•f>!
I Bytea
F8
00000000 0000011 t
OPI.
PCOH
SFR MEMORY MAP
V - lnBlnary 00000000 00000000
• AfX 0
reset
µ::_t:
6 ...;~~
I ,_ ,
~D X
I
L \ -- ..~
....
I
O
,.
'e. 'l, ... <:). , , , n.. .l,.. \ - -
<,~ -
.. ~
-' ~
\..~
MCS~-51 PROGRAMMER'S GUIDE AND INSTRUCTION SET
TbOSC SFRs that ~ave their bits assigned for various functions are listed in this section. A brief description of each bit pro\llded for qwck reference. For more detailed information refer to the Architecture Chapter of this book. 15
pSW: PROGRAM STATUS WORD. BIT ADDRESSABLE. [
CY
I
AC
CY
PSW.7
AC
PSW.6
FO
PSW.5
RSI
PSW.4
RS0
PSW.3
ov
PSW.2 PSW.I PSW.O
p
I
FO
I
RS1
I
RSO
I
ov
I
P
Carry Flag. Auxiliary Carry Flag. Flag O available to the user for general purpose. Register Bank selector bit I (SEE NOTE I). Register Bank selector bit O (SEE NOTE I). Overflow Flag. User definable flag. Parity flag. Set/cleared by hardware ca.c h instruction cycle to indicate an odd/even number of 'I' bits in the accumulator.
NOTE: 1. The value presented by RSO and RS1 selects the corresponding register bank.
RS1
RSO
Register Bank
Addreaa
0 0
0 1 0 1
0 1 2
OOH-07H OBH-OFH 10H-17H 18H-1FH
1
1
3
•
PCON: POWER CONTROL REGISTER. NOT BIT ADDRESSABLE.
I
SMOD
I
l
1
GF1
GFO
PD
IDL
SMOD Double baud rate bit. If Timer I as used to generate baud rate and SMOD = I, the baud rate is doubled when the Serial Port is used in modes I, 2, or 3. Not implcm.c ntcd, reserved for future use. • Not implemented, reserved for future use.• Not implemented, reserved for future use.•
GFI GPO PD IDL
General purpose flag bit. General purpose flag bit. Power Down bit. Setting this bit activates Power Down operation in the 80CS1BH. (Available only in CHMOS). Idle Mode bit. Setting this bit activates Idle Mode operation in the SOCS IBH. (Available only in CliMOS).
If Is arc written to PD and LDL at the same time, PD takes precedence. 'User aottware shOuld not write ts to r-rved bill. These bits may be used In future MCS-51 products to Invoke feallKes. In that case, the reset or Inactive value of the new bit will be 0, and its active value will be 1.
2· 11
APPENDIXH
MW
w,i
jnfel.
MCS-.51PROGRAMMER
TRUCTION SET 'S GUIDE AND INS
INTERRUPTS:
-
I
mu.st be wen.
• g 1hree steps IA Ofdd' to llK any of tbc w1muplS i.n the Mes., I, I.he IoII.owtn 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.
Tl'O IE t TF1
RI& Tl TF2 & EXF2
tfi1 11"
).El
11' JU
Tf.
__ be Sd 10 1 and depending on whether 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
fTx •
V"
fl1>
0003H OOOBH 0013H 001BH 0023H 0028H
IEO
1# 0
priC
vector Addreu
Source
,, ~
J, &pa tbc 1oterrupt 5CfV!ce routme at tbt corrcspOnd.a:ng Vector Address 0
Interrupt
/
e
tt
IP:
olevel activated
If l
fh • 1 tranSitlon activated
biJ
[
IE: INTERRUPT ENABLE REGISTER. BIT ADDRESSABLE. If the bit is 0, the corresponding interrupt is disabled. lf lhc bi1
I
EA
EA
I- l lE.7 IE.6
•
En
JE.S
ES ETI
IE.4 IE.l
EX I
JE.l
ETO £XO
IE.I IE.O
ET2
J
ES
l
ET1
I
EX!
I
-
ts 1. che comsp0ndio3 in1errupt is enabled. ETO
I
EXO
I
Disables all interrupts. If EA - o. no interrupt will be acknowledged. rr £A $OU.rot" is individually mabtcd or disabled by setting or cbrin.a iLS enable b1L Nol unplctnctHtd, rcsctved for fu1u.rc U$C. •
PT
I. each ioletnipt
PS
PT PX
En,bJe or disable the 'rimer 2 overflow or capcurc Uucm.ip1 (80$2. onJy). Enabkc or disable chc st:ria.l pon fntcrrupL &able c>r diltble the Timer 1 overOow interrupt. Enable or di$Able Ex1cmal Interrupt I.
P'J1
Enable or disable die Timer O overflow unerrupc.
...
PX
'U
Ena.blc or disabtc £x1cmal lnlcm)pt 0.
• ·user software .sho1.1Jd t)()I write h 10 reserved bi1s. These bi1s may be ttscd in furure Mes new features. 1ft th9' C8$e, lh.c rtSct or in11ctivc v:aJue of the new bit ll'lll be Ind .... • • ·S 1 pr~uccs to IDVOkc O, 1.., actwe \1'8.luc wtll be I.
2·12
526
APl'ENDIX H
intel·
MCS®·51 PROGRAMMER'S GUIDE ANO INSTRUCTION SET
ASSIGNING HIGHER PRIORITY TO ONE OR MORE INTERRUPTS: [p
order to assign higher priority to an interrupt lhc corresponding bil h1 the JP register must be set to 1.
ftcme:rnbe.r that while an interrupt service is in prog.ress, it cannot be interrupted by a lower or same level intetrupL
PRIORITY WITHIN LEVEL: Priority ..vithin levcJ is on1y to resolve simultaneous requests of the same priority level.
From high to 10"-', interrupt sources arc listed below:
IEO TFO 1£1 Tl'l JU or Tl mor EXF2
IP: INTERRUPT PRIORITY REGISTER. BIT ADDRESSABLE. lf lhc bit is 0, the corresponding interrupt bas • lower priority and ff the bit is I the corresponding interrupt has a blgllcr priority.
I- I
PT2
PS
PT1
PX1
PTO
PXO
rP. 7 Not implemented, reserved for future use.• PTl PS
IP. 6 Not implemented. reserved for future use.• IP . S DefmC$ the Timer 2 interrupt priority level (8052 only). IP. 4 Defines the Serial Pon interrupt priority level.
PTl
IP. 3 Defmcs the Timer 1 interrupt priority level.
PXI PTO PXO
IP. 2 Defines External Interrupt I priority level lP. 1 De('mes the Timer O interrupt priority level. IP. 0 Defines the External Interrupt O priority level.
' Uaer software should not write Is to tescrved bits. These bits may be used in ruture MCS·S I products to in\•okc new reatures. 1n lha.t case, the reset or inactive value of 1he new bit will be 0, ind its 1ctive value will be l.
2· 13
ND INSTRUCTION SET MCS•-51 PROGRAMMER'S GUIDE A
jnfel.
TCON: TIMER/ COUNTER CONTROL REGISTER. BIT ADDRESSABLE.
rw1lffl1iml~l1e1irr1l1~1mJ TFI TRI
TFO TRO
re,
ITI
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. 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~ wate" processor vec:ton to the scrvkc rouunc. TCON. 4 Tuner O run ooor.rol biL Set/cleared by sof'twarc to tum Timer/Counter O ON/OFF. 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 ~. 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
ITO
by harchrn.te when intun1p1 is processed. TCON". O lnl
TMOD: TIMER/ COUNTER MODE CONTROL REGISTER NOT BIT ADDRESSABLE. •
IJATE
I c_i[!
M1
TIMER 1 GATE
$z
I Mo __,I.___GATE I ctQ M1 I Mo=) TIMER 2
fi
WhenTJu(mTCON)iuc,an
cer Opcrat1on (input from Tx input pin). Ml
Mode ,cleetnr boo (NOTE J)
MO
Mode .sdccior bit, (NOTE J)
.
:i
~z
('
-
perauon inpul rrom int~ sys.tern cloc:lc). Set ror Coun·
NOTE t:
Ml
MO
Oper1t1ng Mode
0 0
0
1
1
0 1
0
13,blt Timer (MCS-48 compatible) 16-btt Timer/Countet
2
1
I
8-tJit Auto-Rek>ad Timer/Coun!er
3
(Time, O) TLO Is an 8-bff Timer/Count ~trol bits, THO is an &·bit Tomer and~; ::i~':;il~ by lhe standard Time, 0 •mer 1) Time,/Counter 1 stOj)ped, r • byTime, 1 C0<1trol bits.
1
1
3
..:
g
2-1 4
528
APPENDIX H
I :a
lnfel.
MCSG'-51 PROGRAMMER'S GUIDE AND INSTflUCTION SET
TIMER SET-UP Tollli:s 3 lluouah 6 give some values for TMOD which can be used IO sci up Timer O in differenl mod,s.
ll ii UIWDCd that Ollly oae timer i.s bc:iog used at a time. If it tS desired to run Timen O and l simultaneously, in any mode. thc value in TMOD for Tuner O must be ORed with the value shown for Timer I (Tabl,s S and 6). f'or oumple. ifit is dclircd IO run Timer Oin mode I GATE (utemal control), and Timer I in mode 2 COUNTER, lbcD the vall>C that must be loodcd into TMOD is 69H (09H from Table 3 ORcd with 60H from Table 6).
Motec>wr, ii is assumed that the user, at this pOigt. is not ready to tum the timers on and will do lhat at a different point in the pros,mn by Jettuli bit Tiu (,n TOON) to I.
TIMER/ COUNTER 0
TIMER/COUNTER 1
Asa Timer:
As a Timer:
Table 5
T•ble3
TMOD
TMOD
MOOE
0 1
2 3
TlMERO FUNCTION
INTERNAL CONTROL (NOTE 1)
EXTERNAL CONTROL (NOTE2)
MODE
13-bll Timer t 6-bit Timer 8-bi1 Auto-Reloed two 8-bil Timers
OOH OIH 02H 03H
08H 09H OAH OBH
0 I 2 3
TIMER 1 FUNCTION
INTERNAL CONTROL ( NOTE 1)
EXTERNAL CONTROL (NOTE 2)
13-bit Timer 1S.bit Timer
OOH IOH 20H 30H
80H 90H AOH BOH
S.bil Auto-Reload does not run
As a Counter:
As. Counter:
Table 6
T8ble4
TMOD
TMOO
IIIODE
COUNTERO
INTERNAL
FUNCTION
CONTROL (NOTE 1)
0 1
2 3
--
13-blt llmer 16-blt rom... 8-bi1 Auto-Reloed one 8-bil Counter
04H 05H
06H 07H
EXTERNAL CONTROL (NOTE2)
OCH OOH OEH OFH
1. Thi Tlmor II unod ON/OFF by Nllong/c:IHrlOI} bil TRO in lhe aoflware. Z. Thi Tlmor II unod ON/OFF by the t IO O 1flnoit
c,..0w•• coneroo
MOOE
'
0 I
2 3
COUNTER 1 FUNCTION
INTERNAL CONTROL (NOTE 1)
EXTERNAL CONTROL (NOTE2)
t 3-blt Timer 1S.bit Timer 8·blt Allio-Reload not available
40H 50H 60H
COH OOH EOH
-
-
NOTI!;S,
1, The Timer is turned ON/OFF by setting/ clearing bil TR1 W'I tne sohwa,e, 2. The Tim« Is 1Umed ON/OFF by 1he 1 to O transition on fm'T (P3.3) when TRI • (~atdwaro coneol~
I
infel.
MC~-51 PROGRAMMER'S GUIDE AND INSTRUCTION SET
T2CON: TIMER/COUNTER 2 CONTROL REGISTER. BIT ADDRESSABLE
8052 Only [ TF2
I EXF2
RCLK
I TCLK
EXEN2
I rR2 I cm I cPru I
Asa Timer:
TP2
TlC'ON. 7 Timcr 2 o,·crfJow Rig act by hudwatC and cbn:d b)' toftwarc. TF2 cannot be xt when either RCLK • l or CLK • 1
£XF'2
T2CON. 6 TImer 2 external flag•• whm dtbc:r a capc:ure or rdo!M:I b c,iuscd by • neptiYC ua.nsition on Tl.EX,. and EXEN2 - I. Whca:11imc:r 2 interrupt is taal>lcd, EXF'2 • I wiJJ «:aiJJM the CPU CO vector lO the Timer- 2 intetrup( routine. EXPl mu.u be cleated by ,oft:ware. T2CON. 5 Receive clock Oag. When set, CAU$C$ the ~ Pon to Uk Tuner 2 ovc:rflow pubc, for ics receive clod in lbQda: I & 3. RCLK - 0 ca~ Timer I o,-crflow to be med for the rccrivc
RCL.K
•lode.
TLCK
1"2:CX>N. 4 Trattsm.it c:loc-k Oag. When .kt. causes the. Sc:ru.l Pon 10 use TI:tnct 2 ovcrflo• pub,et for its U'aflsmu cloek to moc:ICJ I & 3. TCLK • o caUStS Timer I ovcrllo-'S to ht \lkd ror tbc tnLNmi1 doof(.
llXEN2
TR2
cm
T2CON. l Timer 2 extcnuJ cnabk na,g, When set, aUovrs a c.aphuc or rt&c.d lO occur as a n:a.u.h ol ncgatrvc ttan$1t100 on Tlal?X if lilJler 2 is nor belog used l.O clock the Scnal Pon. SXEN.2 • 0 causes Timcr- l to ignore evcrits at T2(3.X. T2CON. 2 Solt~ STA.RI/STOP concroJ for nmcr l. A fogi,e I siaru tbc Ti:mcr. T2CON. J TiG:icr or Courtier 5dcct.
Table 7
T:ICON IHT£RNAL CONTROL (NOTE 1)
EXTERNAL CONTROL (NOTE2)
16-oit Auto-Reloed
OOH
08H
16-bit Capture
01H
09H
BAUD rate generatOf receive & transmit same baud rate
34H
36H
receive ontv
24H
26H
transmit onty
14H
16H
MODE
As a Counter:
0 • JmcmaJ Timer, I • Eucroal E"'enl Counlcr (fa.lJin,g edge tri,ggcr«I),
CP/RL2 T.ZCON. 0 C.ptutt/kdoed 0.ag. Wbcn -«. caP4:Ul'C$ will occur On nepti...e 1ro.os.i.h0ns al Tl..E:X if EXBNl - J. Wbcti cleatcc4 Auto-.Rclc:w.ds v.-i1J OC(':ur cit.her with Timer 2 overflows Or neptive U'a.nSltioos a.t T2EX when EX.EN2 c I, When ri1hcr RCLK • 1 or TCLK - I, this bt1 J,i J.gnOttd aod t.bc- Timer is forced t0 Au10-Rdoad on Timel'" l O\·c:rflow.
TIMER/COUNTER 2 SET-UP Except for the baud rate generator mode. the values given for T2CON do noc include the setting Tbctdorc. bit TR2 m~ be set. separately. to tum the Timer on.
~,
FI
I
I
or the TR2 biL
I
TMOO MODE
INTERNAL CONTROL (NOTE 1)
1&-bit Auto-Reload
02H
1s-b;1 Cat,lure
03H
EXTERNAL CONTROL (NOTE2) OAH OBH
NOlES: 1. Clp1Uf9/Relo*CI occut1 only on Tln"lef/Countor ov8'110w. 2. Cap1ure/ Aeioad occurs on Timer/ Countee O'Verllow end ei , o transition (P1,1) pin excop1 when Tun• 2 it used ,n the baud rate Qenera\ing mode.
'°
... \~
°"' T2EX
\~
intel·
MCS* -51 PROGRAMMER'S GUIDE AND INSTRUCTION SET
scoN: SERIAL PORT CONTROL REGISTER . BIT ADDRESSABLE. [
SMO
I
I
SM1
I
SM2
REN
I
TBS
I
ABB
I
Tl
I
RI
I
SMO SMI SM2
SCON. 7 Serial Port mode speedier. (NOTE 1). SCON. 6 Serial Port mode specifier. (NOTE 1). SCON. S Enables the multiprocessor communication feature in modes 2 & 3. In mode 2 or 3. if SMl is set to I then RI will not be activated if the received 9th data bit (RBS) Is 0. In mode I. ifSM2 = I then RI will not be activated if a va.lid stop bit wa.s not received. ln mode 0, SM2 should be 0. (See Table 9).
REN T88
SCON. 4 Set/Cleared by software to Enable/Disable reception. SCON. l The 9th bit that will be tran.smincd in modes 2 & 3. Set/Oearcd by software. SCON. 2 In modes 2 & 3, is the 9th data bit that was r"'eivcd. 1.n mode I, if SM2 = 0, RBS is the •top bit that was received. In mode 0, RBS is not used. SCON. I Trall$mit interrupt flag. Set by hardware at the cod or the 8th bit time in mode 0, or at tile beginning of the stop bit in the other modes. Must be cleared by software. SCON. 0 Receive interrupt flag. Set by hardware at the end or the 8th bit time in mode 0, or halfway through the stop bit llmc in the other modes (c.xciept see SM2). Must be cleared by soRware.
RBS Tl RI NOTt 1:
$MO
SM1
Mode
Oeacrlptlon
B1ud Rite
0 0
0 1
0
Fosc.11 2 Variable Fosc./640R Fosc.132 Variable
, 1
0
1 2
SHIFT REGISTER 8-BltUAAT 9-Bit UART
1
3
9-Bit UART
SERIAL PORT SET-UP: Table 9 MOOE
SCON
SM2 VARIATION
0
10H SOH 90H DOH
Single Processor Environment (SM2 = O)
NA 70H BOH FOH
Multiprocessor Environment (SM2 - 1)
1 2
3 0 1
2 3
GENERATING BAUD RATES
S.rlal Port In Mode 0: Mode O bas a fbcd beud rate which i5 1/12 or the oscillator frequency. To run the serial port in th.is mode none of the Timer/C:Ounters need 10 be set up. Only the SCON regi'1er needs to be defined.
Osc Freq
Baud Rate • -'----' 12
Serial Port In Mode 1: MOde I bu I variable baud rate. The baud natc can be generated by either Timer I or Timer l (8052 only).
2·19
531
Al'PENDIXH
-
' UIDE AND INSTRUCTION SET MCSl<-51 PROGRAMMERS G
jnfel.
USING TIMER/COUNTER 1 TO GENERATE BAUD RATES: r h. ch•p«r. Set SC(.110JJ O t I) For th.it putpc:)l'C. Ti.inc::r J ts U1Cd in n,ode 2 (Auco-Rdoad). Refer 10 Timer up K ,: OSCiilatot FttJQ. Baud RAIO • :)2 x 12 • ( 25G _ (THI))
lfSMOD • 0, thco K • I II SMOD • I. 1hcn K 2 (SMOD "the PCON rcgisier). Most oftbc tune the user \nows the bflud rate and n«ds to know the ~lood value foe THI. Then:(orc, 1he cqu.1tion to calculare TH I can be wriuen as:
t< x Osc Freq THl ._ 256 - 384 "baud tale ...... the d«;red baud ra«. In 'TH I muse be M integer vaJQC. Roundmg off TH I to the nearest integer niay not ._,..,.,.uce thts ~ the user ma)' hav.: to choose another tt)·Sctl frequency.
S.incc the PCON cc:gistc:r i!t noc btt addrcsA.blc. one way co ~t 1bc bh 1s logical ORing the PCON regjstcr. (it~ ORL PCON, 180H). The tddrcss o( J>CON as 87H.
USING TIMER/COUNTER 2 TO GENERATE BAUD RATES: For th,s purpose:. Timer 2 rouse be u~ 1n the baud talc gencnltmg mode. Refer 10 Timer 2 Sc:cup TA.blc in I.his ch.apter. If Timer 2 1s being clocked through ptn T2 (Pl.0) the baud nHc ii: Saud Rate • Tl"* 2 Ovfrflow Raia 18
And d' 11 is befog eloc-ked intern.illy the blud rate S.udRate
i.-.·
OseFteq 32 , 1815536 - (RCAP2H. ~AP2L)J
To obcam the reload value ror RCA.PlH and RCAP2L 1hc above -, Nlu:.D.tion - · be · ........ rcwnuen as: ACAP2Ji, RCAP2L • 65636 -
0sc F,Gq 3:Zx~Ra10
SERIAL PORT IN MODE 2: The baud 1111e iii (u.td in this mode and is 'In or 1/t of 1hc oscilla btt in 1he PCON register. •• tor frequcnt..'Y depending oo the vaJuc o.f thc SMOD In this mode none or the Timers arc used and the clock ccnncs from th . c 1n tcmat pl1ase 2 cioc\; • SMOO ... I. Baud Rare =- 11,, Osc Freq SMOO = 0, B:tud Rate
c
To.., the SMOD b11, ORL
Y•• O$c: Freq, PCON. # 80H. The nddrc,s
or PCON "87H.
SERIAL PORT IN MOOE 3: The baud ntc in mode 3 l5 vanable and ~~
- - up ex.act1y
t
b
e same as in mode I.
2-20
532
APPl!NDIXH
MCS*·51 PROGRAMMER'S GUIDE AND INSTRUCTION SET
MCS®-51 INSTRUCTION SET Table 10. 8051 Instruction Set Summary r-~~~~~~~~~~~-
r~~~~~~~~~~~._.,
Interrupt Response Time: Refer to Hardware Desc:ripdon Chaptc.r. lnatrucllona that Affect Flag Settlngs(1) ln1lructlon
Flog
C X X X
ADO ADOC SUBB MUL DIV DA ARC RLC SET8C
0 0 X X )(
lnttructlon
av AC X X X X X
X X X
Flag
C OV AC
0
CLRC CPlC ANLC,bit ANLC.lb
X X X X X X X
Mnemonic;
oe,crlptlon
ARITHMETIC OPERATIONS A,Rn Add re~ter to ADO Accu,,..,,lator A,d1tect Add cSrect byte 10 ADO Ac:cumuta1or A,OAJ Add Indirect RAM ADO to Aoeumulatoc ADO A. • data Add immediate
Byte
Osclllator Poriod
1
12
2
12
t
12
2
12
1
12
data to
Aacumuf.alor
AOOC A.Rn
Add register to Accumulator
t
withCany
(l)Note that opcr•tions on SFR byte oddr
AOOC A.direct
Add direct byte to AccumlAator with Corry
2
12
ADOC A,eRI
Add indirect
1
12
Note on instruction set and 1ddressi,n9 modes:
RAMIO Aocumulato, withCtrty AOOC A.# 41UI Add Immediate date to Ace with C11ry SUBB A.An Subtraci Regbter
2
12
I
12
2
12
1
12
2
12
1
12
1
2
12 12
1
12
Rn
-
Register R7 - RO of the currently lccted Rcgistet Bank.
direct
- 8-bit internal data location's addr¢S.1f. This could be an lntemal Data RAM location (0- 127) or • SFR [i.e., VO p0rt. control register, itatUs register,
SC·
tromAccwM borrow
etc. (128-255)}.
41 Ri
- S..bit intern.a] data RAM location (0SUBB
255) addres,cd indirectly through reg· ister R 1 or RO. #data - 8-bit constant included in instruction. # data 16 - 16-bit constant included in instruction. addt 16 - 16-bit destination addre$$. Used by I.CALL & UMP. A branch can be
rel
SUBB
A,eRI
Subtract ln
SUBB A. #data SUblfOCI Immediate data trom Ace with borrow tnc,&m8(11 INC A Accumulator lncrem&n1 register INC Rn Increment direct INC ddoct
-
11-bit destmauon addte.u. Used by ACALL & AJMP. The branch will be within the same 2K-byte page of program memory as the fl.rst byte of the foUowing instruction. - Signed (two's complement) 8-bit olfset byce. Used by SJMP and aU condition• e.1 jumps. Range is - 128 10 + 127
INC
OAI
byte lncr•m•nt direct
lowing instruction. - Direct Addressed bit io lntema.l Data.
DEC
A
RAM Dect«nent
RAM or s ~ial Functfon Reiriste:r.
DEC
Rn
DEC
direct
bytes relative to first byte o( the fol•
bit
Subtract direct b)'1e from Ace w1thbotrow
anywhere wlthin the 64K•byte Program Memory address space. addr 11
A.direct
12
Accumulator
12
o.c,-
=Re,g11t.,
byte
direct
2
12
12 1 0ec:rement lnaoreci RAM All mnemonics copyriglltocl ©Intel Cofl>c)rallon 1990
0£C
2·21
~H
____________
._.
~~-
•RI
MCS · -51 PROGRAMMER'S GUIDE AND INSTRUCTION SET
intel,
OKllletor ,------~ T~1b~le~ 10'.::.a~s~11n11ructlon o Se;:t:.:S:: u::: m:.:. m::•:..: rr...:.:
Byte c,.c11t1tor
t-;;;;;:;;;;::::-::::::=__:.::.::=~.:::._p,nod ARITIIMETIC OPERATIONS (COr\1,nuedl INC OPTR lncrtmtn1 Oata 1
LOGICAL OPERATIONS 1coo•nued) AL A ROUlle A~fator Lel1 Rotate RLC A Acx:t1mU1ator Latt
24
Pointer MUI. AB
""'1lply A & 8
DIV DA
OlvldeAbyB
AB A
I
12
ARC
A
12
to Aocumulator
A/Ill A... data
RAM co Acc:umu'41or AND wnmedlalt
2 SWAP A
2
DATA TRANSFER MOV A.Rn
Accumulator 2
12
3
24
OAL
A.Rn
OAL A,eR1 ORL A,#def,11.
OAL - ·
data 10 dcf.c1 by1.1 OR reglNC to Aocumu11ior 0A direct byte to Accumt,q,io, OR lndittct RAM to AccunMJf,.IOf
I
12
2
12
OR tmmtd.iate dala"' Accu"'-'a10, OR ACCLfflulato,
CAL direct, .. data to direc:t byte
OR immediate drta to d,tocl byte
XAL A.Aft
2
--
12
2
12
12
immediate da!l 10
1
12
2
24
2
12
2
12
2
24
3
24
2
24
3
24
1
12
A.eRI
lfflln8d.lte data
2
12
3
24
Rn.A
Aoc:umula10, to register
MOV
Rn,
c,..,
CPI. A
ComAcCUmulalOf
AccU'nulalOI'
Move direct bytO lo
reglsar
MOV 2
Rn. I dale
Move lmm0d1a10 data
12
MOV
direct.A
to,~e, Move A.ocumulato, to direc1 byte
2
M(N
Move regisae, dlrect.dtfect to direct byte Move direct
by1e to
12
Move llld1rec1
RAM to 3
MOV
24
d1rect, ' da11 dlrtct byte
MoYe
immect111e data &0 Cl!rtct i,..,.
IO ClltOCC byte
CUI A
-·
Accumulator
MOV
lmmec:11110 ct,11 10
XRl di.tect. • d•ta EiccluS!Yt-OR dtfect byte
Accumul.ato, Mcwedirect byle10 AccumlAator
12
MOV
Elcelu....e-OR tndi,(ICt AAM 10
ExdJslvo-OA Aocumufator to
12
Move register to
1
Aooumulato<
-OR
12
RAM to Accum.,1a1or Move
A,dfrect
Accumuta.lO(
XRL A..•data
12
Move lndiect
Accumulator
XAL A.eftl
I
12
regls!A)J to
cl
AQCumula1or Right Aotate Aoc;umulator Right 111roug.h Ille carry Swap nibbles w!IIW'I ti'!&
2
MOV
e~ ExciullYe-OA
12
,Acc:omulttto,
12
da:a 10
ANL di
1
ROta1e
AR
AOCWlLi!ait>t LOOIC" I.. OPERATIONS AHL A.Rn ANO RIQl$let to Accumulator ANl A.direct ANO direct byte ANO ,ricl,rect
12
tl>r011(1h the carry
Docimal-t
ANl A,eR!
12
1
Mew&
12
All
mne-
..,,e
Accumu&a_to, 1
indir8CI RAM o
2-22
Al'PENDIXH
intel·
MCS~ -51 PROGRAMMER'S GUIDE AND INSTRUCTION SET
Table 10. 8051 l natructlon Set Summery (ConUnued) Mnemonic
Dea.c:rlptlon
OAT A TRANSFER (Continued) MOV • Rt d,rect Move d1rect b)'1e to illdlrecl RAM MOV ORl.•data Move immed.ate
Byte
O•clllator
2
24
2
12
data to MOV
indirect RAM DPTR, # data 16 Load Data Pointe, with a
3
24
16-bit constant
MOVC A.OA + OPTR
MOVC A.eA+ PC
MOVX A.ORi
MOVX A.e DPTfl
Move Cod(t byte relative to DPTR to JV;c M
1
24
24
1
1
24
24
addt) to Ace
MOVX ORi,A
24
Move Aceto
Mnemonic
Period
PUSH direct
Jump i1 direct Bit 1s set Jump K direct JNB bllrel Bit ls Not Mt Jump ff direct blt,rel JBC Bit ls set & olearbi1 PROGRAM BRANCHING ACALL addr1 1 Absolute Sub
1
24
2
24
2
2A
byte onto
stack POP
XCH
direct
A.An
Pop direct b)'1e from Stadt Exehange regiStGC' with
1
12
bit.rel
XCH
XCH
A,dlrect
A.ORI
XCHO A.ORI
-
Accumulator Exchange indirect RAM Accumulator Exchange low· O ACC
Period 12 12 12 12 12 12 24
24 24 24
12 24 24 24
3
24
3
24
3
24
2
24
3
24
s~
Accumulator Exchange direct b)'18
Otclltalor
not set
(S·bit addr)
Move AIX to External RAM ( 1ti.bi! addr) Pushditect
8~
BOOLEAN VARIABLE MANIPULATION Cte.rCany CLA C 1 bi1 Clear direct bit CLA 2 SetCeny SETS C 1 bit Set direct bl1 SETB 2 CPL C Complement 1 Car,y CPL bit ~ement 2 direct bit AND direc1 btt ANL C.bi1 2 to CARRY ANL C.lbit ANO complement 2 of direct bi1 10Cany C,M OAL OA direct bi1 2 to Carry C,/bit OR complement ORL 2 of direct bit to Carry MOV C,bll Move direct bit 2 to Carry bi1,C MOV Move C.r,y to 2 direct bit rel Jump if Carry JC 2 ls set JNC rel JumpHCany 2
Extemal RAM
MOVX OOPTA.A
OHCrlptlon
2
1
Cell
12 RET
Retumtrotn
RETI
Sub
12 AJMP
eddr11
WMP SJMP
addr18
Long J"""'
rel
Sho
Ju""' 1
12
24
24 2
24
3 2
24
24
(ro!atlYO addr)
AHmnemonice c:opyrightad C>lnfal Cotpordon IIIIO
2-23
AfnNDIXH
-
lnfel.
......
__.. --···~~... ....... ........ _.,.. .. _.,.,_ -- -Du ff lU
- ••·ll"TA - -
.,.. o.«tt ,....a 1
24
2
2,
Cl'TR
ll
N:O.r. . .
JHl
...
.z...
.,.,u...
C,jN£
CJNE
...........
........
w
-0/ldt111dt M'IO
•No
__.,.......,
CJHE
Ar<•_.,.. eo,..ltNM :ta•e to
CJNE
•Al. •.....,..
'
Equol
Col,..,.
__ ,....
0..-.IOI Pertod
'
2•
3
2•
2
24
3
24
I
12
,._
2 )
eyw
l'IIO(IIIAIII IIIWIQUICI (Ccitl6'"Adl
trtmlrllr:M IO
,doodond
2•
_,_ -~ .... -~ Equol o.c,,wmenl
,.,.....,
DIH2 ANol
tNo
011 !Ip-
Ql'a
-
_,..
Al Mr..-O• •
lMo
O.C,tmenl
Hoel-
No
OOW"'
~
APl'ENDIXH
MCS~-51 PROGRAMMER'S GUIDE AND INSTRUCTION SET
.
T1ble 11 ln1tructlon Opcode, In He.xadeclmal Order Hox Codi 00 01 02
03 04 05
06 07
08 09 OA OB
oc OD OE OF
10 11 12 13 1' 15 16 17 18 19 1A 1B 1C 1D lE
IF 20 21 22
23 24 25
28 27 28 29 2A 28
2C 20 2E 2F
30 31 32
Number of Bytoo 1 2 3 1 1 2 I 1 1 1 1 1 1 1 1 I 3 2 3 1 1 2 1 1 1 1 1 1 1 1 1 I
3 2 I I 2 2 1 1 I 1 1 1 1 1 1 I 3 2 I
Mnemonic NOP AJMP UMP RR INC INC INC INC INC INC INC INC INC INC INC INC JBC ACALL LCALL RAC DEC DEC DEC DEC DEC DEC DEC DEC DEC DEC DEC DEC JB AJMP RET Rl AOO ADD ADD
ADD ADD
ADD ADD ADD ADD ADD ADD ADD JNB ACALL RETI
Hex Code
Oporami.
A A
33 34 35 38 37
dataaddt
38
8RO IRI Ro A1 R2 R3 R4 R5 Rs A7 bit addr, code addr
39 3A
cOdeeddr codeaddr
38 3C 30 3E 3F 40 41 42 43
«
OOde addr code S:ddr
45 48 47 48 49 4A 4B
A A
data ackft IRO 8A1 AO Rt R2 R3 A4 RS AS R7
4C 4D 4E 4F
50 51 52
bit add!'. OOde addf codeeddr
53 54
A A, • data
55 58 57
A,data addr
56
A,IRO A,IAI A.RO A,A1 A,R2 A.R3 A,R4 A,RS A.AS A,A7
59 SA 58
SC eD 5E 5F
60 61 82 63 84 85
bit addr. OOd• ldm" codeaddr
2·25
...____
"'°'ENDIXR
Number of llytn 1 2 2 I 1 I 1 1 1 I
1 1 1
2 2 2
3 2 2 I 1 1 I 1 1 I I I 1 2 2 2 3 2 2 1 1 1 I 1 I I
1 1
Mnemonic ALC ADDC ADDC ADDC ADDC ADDC ADDC ADDC ADOC AOOC AOOC AOOC AOOC JC AJMP DAL DRL DAL DRL DRl DRL DAL DRl DRL DRL DRL DRL DAL DRL JNC ACALL ANl ANL ANL ANL ANL ANL ANL ANL ANL ANL ANl ANL ANL ANL
1 2 2
JZ
2 3 2
XRl XRl XRl XRL
2
AJMP
Oporanda
A A,#ckla A,ck1aaddr A.IRO A.IRI A.Ro A.Al A.A2 A,R3 A,.R4 A,AS A,R6 A,A7
code addr code addr dala oddr,A
data addr, * data A, # dlto A,dala odclr A,IRO A,IRI A,RO A.Al A.A2 A.R3 A,R4 A,R5 A.R8 A.R7
oodeaddr oodelddr dalaoddt.A
data addr, # dlta A,#dato A,d110oddr A,IRO A,IRI A.RO A.R1 A.AZ A,R3 A.Re A.RS A,Re A.R7
oodeoddr oode oddr
__
da10oddr.A
--·""'" ,., A,#da10
, infel.
,;;;---;;::=::--....:T~a~bl!!t. !1_!:1.J.!ln~a~tru:!!:c~t~lon ,,.,,,<)dH r,, tte~,nal Ord•rMnemonic (Continued)
rr~Coclo;"":._~o~IB~•~•:._;M;•"""": ::~~'.._~~o,,o,ond~~· ~~ He.x
Numbtt
156 87 88
69 8A 88 8C
I
60
I I
8E 8F 70
I
71
2 2
72
2
T3
I
,.
2 3 2 2
75
76 77
78
2 2 2
79 7A
XRL XRL XAI. XAL XRL XRL XRL XRL
XAL
A,eAO A.ORI A.AO ",Rf •
oode~
ACALL
code ad«
CAL JMP
C,l,il eddr
MOV
A.#data
MOV
data.addr, l data
WJV
•RO,#data
MOV
•A1,, c;tata
MOV MOV
AO,# dtta Al .l dlta R2, # data R3, #data
70
2 2
MOV
A•, l dala
7E
2
7F
2
MOV MCV
A15, • dt11 R8, # data
80 81
2 2 2
82 83 e, 85 88
87 88
89 84
88
BC 80
8e
8F 90 91
92 93 9' 95 96 97 96
I
3 2 2 2 2 2 2 2 2 2 2 3 2 2 1 2 2 I 1
se 9F
ANL MOVC
C,bit addr
OIV
A.eA+PC
MOY MOV
AB adClr data de , dtla 1ddt taaddf'.• RO da1aaddr,eR1 data ldct.RO data lddr.R1 data lddt.R2
MOV MOY MOV MOV
"°"
MOY MOYC
bltlddr,C
MOY MOV MOV
AC.All
sues
suee SUBS
svee
SUBS
42 A3
2 1 1
48
,.,
2 2
AfJ
49
2 2
M AB 4C
2 2 2
40
2
AE AF 80
2 2 2
91
2
92 93
2
a, 85 98
data lddr,R3
data oddr,R, da.. oddr.R5 dati tddr.RS d1ta 1ddr.A7 DPTA, ' datt ._,~
2 2
A5
A7,• data OOdt lddr
M(JII
,.,NJ ....
SJMP AJMP
MOV
1 1 1
90
eA+OPTR
2
7C
99 9A
ec
A.R3 A.R• A.RS ii.RS A.R 7
XAL JNZ
f 1 1
98
A.R2
MOV MOV
78
e1
98
es
94 88
ec eo ae BF co c1 C2
SUB8 SUBS OAL AJMP MOV
ll'IC
'~
MOV MOV
A3,data a
MOY
4NL
R,,ctata addr R5,oe1a addr RS.data addr R7.da.ta addr C,/bit addr
AC...LL
codeaddr
CPL
bit adclr
MOV MOV MOV
1
CPL
C
3
CJNE CJNE CJNE CJNE CJNE CJNE CJNE CJNE CJNE CJNE CJNE CJNE
A.• data.Oodt addr
3 3
3 3 3 3 3
3 3 3
3 2 2
PUSJi AJMP
ClR
cs
' 2
C7
1 1
XCH
xci;
I
XCI;
A.•4 +llPTR A. • c1a,. A.dataoddr A.•Ro
ce
A.eR1 A.RO
C4
C8
Ct
ca
OAO.data addr eR1,data addt RO.data addr R1,data addr R2,data addr
MOY
CLR
cc
AB
MUL MOV MOV MOV
o~ ...nc1·
A,R1 A.R2 A,R3 A.R• A.RS A,R6 A.R7 CJb!t eddr code addr C,b!taddr DPTR
suss suss suss suss suss
2
C3
2-28
538
-
MCSL 51 PROGRAMMER'S GUIDE AND INSTRUCTION SET
1
1 I
1
SWAP
XCH
XCH XCH XCH
A.data addr code
•Ro,• e1ata'.COc1e: : eR1. RO • • <1ata,code addr R • data.Code addr R 1, # data""'ode addr 2, • data.code
R3, • data.code=
fW,• data c:ooe RS,• e1a•-' addr Re -code addr R , # daia-..1..~addr
'· • data.OO
d•,.•ddr eodeaddr bit addr C
A A.data addr
A,eRo A,eR1 A.RO A.RI A.R2 A.R3
add<
M CS~-51 PROGRAMMER'S GUIDE AND INSTRUCTION SET
.
Table 11 lnatrucllon Opcodu In Hexadecimal Order (Continued) H•:a Code
cc
co CE CF
00 D1
02 03
oc 05
06 07
06 09 DA DB DC 00
OE OF EO
e,
E2 E3
E• ES
Humber
or
By!•• 1 1 1 1 2
2 2 1
1 3 1 1 2 2 2 2 2 2 2 2 1 2 1
,
1 2
Mnemonic
XCH XCH XCH XCH POP ACALL SETS SETS DA OJNZ XCHO XCHD OJNZ OJNZ OJNZ OJNZ DJNZ DJNZ OJNZ OJNZ MOVX AJMP MOVX MOVX CLA MOV
Hex Code
Oper1_nda A,R4 A,R5 A,R6 A,R7 dataaddr code addr bit acldf C A data addr,code addr A,9RO A,9A1 RO.code addr A 1,code adcsr A2.code addr R3,codeaddr R4,code addr AS.code lddr R6,code addr R7,oode addr A.ODPTR code addr A.eRo A.e R1 A A.data addr
E6 E7 E8 E9 EA ES EC ED EE EF FO F1 F2 F3 F• F5 F8 F7 Fe F9 FA FB FC FD FE FF
Number 0 1 8)'111
1 1 1
1 1 1 1 1 2 1 1 1 2
,, ,,
1 1 1
,
1 1
Mnemonic
MOV MOV MDV MOV MDV MOV MOY MOV MOY MOY MOVX ACALL
MOVX MOVX CPL MOV MDV MOV MOV MDV MOY MOV MOY MOY MOY MOV
~
A.e Ro A,eR1 A.AO A,A 1 A.A2 A.A3 A.A4 A.R5 A.RB A,R7 e DPTR.A codeaddr eRO,A • R1 ,A A dala addr,A eRO.A e A1,A RO.A A l .A R2,A R3,A A4.A R5,A RB.A R7.A
2-27
4PPliNDIXH
•
0
• lnetructlon Set Summary
•
0
I
NOP
...... JllC
(38, 2CI
I
MAP (PO) (28, 2CJ
2
UMP
3
""'"' •
(39, 2C!
• $
• 1
RR
INC A
..,
ACALL (PO) !29,2CJ
lCALL •cldr18 138. 2CI
,.
RAC
DEC
• ...
INC
DEC
(2BJ
1281
2
3
•
......
JNB
JC
JB
... tel
..I
138, 2CJ
1!'!:_2CI
128. 2CJ
,t,CAl.L (Pll (28. 2C1
AJMP
RET (2CJ
RE'TI 12CI
138, 2CJ
........ (Pl)
AL A
.......
ALC A
(P2l 129, 2CJ OAL
s JNC ,el {28. 2Cj
I
7
JZ
./NZ
(28, 2CI
120. 2CI
,.,
ACALL (P2) (2B, 2CJ
AJMP (P3) (2B, 2CJ
ANL
XAL
,el
ACAU. (P3) (28, 2CJ
dlr, A
dor, .
(281
(28)
(28. 2CJ
OAL (hr. 1eti1a (38. 2CJ
ANL dil, ldata (38. 2CI
XAL d1r, l(Sata (38, 2CI
OA +DPTR
ANl A, ldala 12B1
lffil A. ,c1a1a
A. #
(281
(281
ANL
(2CI
{281
A. fdaMI (281
ORL A. •d31t (281
AOOC
ORL
1281
1281
(291
XRL A. dor (2BJ XRL A, ORO
MOI ORO, Odalll (281
XRL A, 0R1
M<:N
A, Or
INC ORO
DEC ORO
ADO A, ORO
ADOC
OAL
A. ORO
A. ORO
INC ORI
DEC
AOO A. OA1
AOOC A. ORI
ORL
ANL
A, OAI
A, ORI
•
MOV
AOOC
.... ....
3
JMP
AOO
AOO A,6' 1291
2
OAL
c.b,I
dlr. A (29)
ANL A, ORO
ORI
6
5
M()V
ldata (38. 2CI
(lir,
6
7
OAt, #dOf.l
l2BJ
•
INC RO
DEC AO
ADD A.RO
•
INC Rt
DEC
ADO A.RI
ADDC
INC R2
DEC R2
AOO
AOOC
A.112
.... 112
INC
DEC R3
AOO A.R3
ADOC
A
9
D
E
F
ORL A. RO
XAL A. AO
MCN
6
RO. klata
...
INC
"'
DEC
"'
INC R•
DEC
...
DEC RO
INC
INC R7
R$
DEC R7
ADO A,R4
ORL A.Al
ANL
XRL
M()V
A. A1
A, Rt
Al, ldJta (291
ORL A.R2
ANL A, A2
XRL A,R2
A.R3
ORL A. R3
ANL A,R3
XRL A. R3
AOOC A.R•
ORL
A.Ac
ANL AR,
XRL
M()V
A,A.C
DAL A.RS
A4, ldaJa (28)
A,R5
XAL A A$
M()V
A. RI
ADO A, RS
ADOC A.RS
ADO
AOOc .... R6
A.Re
AOO A.A7
MOIi
m. ,oata
9
A
(281
AOOC A.R>
--
ORI.
A,R6
ORL A, R>
Kay: (281 • 2 llyle, (38) • 3 llylt, (2CJ • 2 Cyde, (4CJ • • Cycle, Blank. I byte11
a-12
ANL A,AO
(2B1
R3 C
ADOC A.AO
ANL
M()V
R3, #data 1281
RS. idata 12B1
AM. A.lie ANL A.R>
XRL A. Re
M()V
A6, J~UII
(:WJ XRL A.R7
M(N
R? ldlta (2BJ
Instruction Set - - - - - - - • • • • •
9
C
D
------------------~~--------...........
.....
Instruction Set instruction Set Summary (Continued) 0
8
9
SJMP REL 128, 2CI
MOV DPTR.o dlta 1$
138. 2CJ
AJMP
I
..
B
C
0
OAL C. lbot 128.2C)
Nil C.Jblt 128, 2CI
PUSH dir 128, 2CJ
POP
A.CALL
I
E
F
dot 120 . 2CJ
MOl)( A. OOPTR l2CJ
MClYX ODPTR, A 12CJ
AJMP (1'6> 128, 2CJ
A.CALL (1'6) 128. 2CI
AJMP (P7) 120, 2CJ
.ACALL (P7) (28. 2CJ
MOVX A. OAO 12CI
wAO, A
(P<) (28, 2CJ
A.CALL (P• > 12a, 2CI
AJMP (PS) (28. 2CJ
128. 2CI
ANL C, bn (28. 2CJ
MOV
MDV C, btl 128)
CPL bil 12BJ
CI.R
bil. C (28. 2CJ
12BJ
SETS bl1 (28)
3
INJIICA. O A • PC (2CJ
MDVC A. OA + OPTR (2CJ
INC DPTR 12CI
CPL C
CUI C
SETS C
MOVX A. ORI (201
MOVX ORl, A (201
•
DIV AB [28, •CJ
SUBB
MUL AB 14CJ
CJNEA.
SWAP A
DA A
CUI
.
CPL
A, #Cleta
CJNE A. dlr. ,.i 136,201
Xett A. dw 128)
OJNZ rel 138, 2CI
MDV
MDV
A. dlr 1281
dlr, A (28)
CJNE ORO, t data. rtl 138, 2CI
xett A, ORO
XC'10 A. ORO
MOY A.ORO
MOY ORO.A
CJNE OR1 , 1oa1a, rtl (38, 2CJ
XC*i A. OR1
XCHD A.0R1
MDV
MOV
A. OR1
O R1, A
CJNE
XC*i A, RO
DJNZ AO. rel f2B.2CI
MDV
MOV AO, A
1
2
5
6
7
MDV dlr. dir 138. 2CJ
MOV dit, OAO 128,201 MOY
1201 SUBS A,dir
1281
sues
MOV
A.ORO
ORO. di, [28. 2CI
SU88 A. 0R1
128. 201
8
9
MOV
SUBB
dir, RO 128. 2CJ
A, AO
MDV
SUBB A. A1
dlr, A1 (28, 2CJ
• B
MOY dir, R2 120. 2C)
SUB8 A. R2
MOY
SUBB A. R3
""· R3 (213, 2CI C
14-la, , ..
138, 20)
-
RO. Jdata. cei 136, 2CJ CJNE
XC*i A, AI
MOV A1.0lr
A l , #dala. rel
(28, 2CJ
138, 2CJ
MOV
CJNE A2. #data. ritl 138. 2Ci
XCH A, R2
CJNE A3. l data. rel (38, 2CI
XCH A. R3
"'' R2. 2CJ (28, MOV R3, dir
MOY
CJNE
XCH
A. A4
R4, dlr
A4, f data, rel
A, R4
(28, 2C)
[3B, 2CI
MO\/
CJNE
SUBB A. RS
MOY dlr, R6 (28, 2C)
SUBB A, R6
MOV
SU8B A.R7
dlf, A7 )28, 2CJ
RS. dlr 128, 2CI
MOV Fl8. dlr (28, 201
MDV A7, dir (28, 2C(
A, RO
[2CJ
..
DJNZ
IICN
IICN
R1, rtl
A. A1
Al, A
ut:N
RS, • daita, rol [38. 2CJ
CJNE A6, #data,
DJNZ R2, ,el 128, 2CI
A, R2
MOV R2. A
OJNZ
MOV A, R3
MOY R3, A
OJNZ Re, reJ (28, 2CJ
MOV A.R4
A... A
DJNZ
MOV A.AS
RS. A
MOY A.R6
MOY R6 A
MOV
MOV R7, A
R3, ,.,
(28, 20)
sues
MOV
di,,
MOVX
(28, 2C)
MDV
'*•RS
F
bd
dif. A<
[28, 2CJ E
MOV RO, dor (28. 2C)
128, 2CJ
128, 2CJ D
MOV 0R1. dlr (28. 2CJ
( P5)
XCH .... A5
RS.NII
IICN
MOV
128, 2CJ XCH
OJNZ
.... R6
R6,ret (28. 2CJ
XCH A, R7
DJNZ R7, rtf (28, 2CJ
A.R7
Key(2BJ• 2 Byte, (381 • 3 Byte, (2CI = 2 Cycle. (4CJ= 4 Cycle. Blank ~ I byte/1 cycle
AilD&L .\PJ>ENoD( H
...____
2-73
N1
, I
PACKAGING
intel. PACKAGE TYPES
GES CERAMlCPA CJ(A
Surface Mount
CQFP
1 - - - - - - - - (Ceramic Quad Flatpack)
•
)
-
LGA (Land Grid Array)
C
Socket Mount
PGA (Pin Grid Array)
• (Bottom View)
C·DIP Insertion/Socket Mount
(Ceramic Dual in-Line Package) (Side-Braze)
240817-1
(Reprinted by permJoolon of lnlel Co,pontion, Copynght Intel C~rp. 1992)
APP!NDIXH
-
.......
Intel. PACKAGE TYPES (oontinuedl PLASTIC PACKAGES Swface mount
LEAOLESS ClllP C>JUUEll PACKAGES
SOP
LCC (Socket Mount)
(Small Outline Packagi,) (Gull-Wing)
(Bottom View) Dual Row
1 - - -- - - l - --
0
LCC (Sumce Mount)
SOJ (Small Outline Packagi,) 0 -Lead)
(Bottom View)
'---
TSOP (Thin Small Outline Paclcagi,)
G ~ L E D PACKAGES
CERDIP
. - - - PLCC (Plastic le•ded Chip Carrier)
(Ceramic Dual ln· Une Packagi,) (Insertion Mount; UV Window)
CERQUAD (Cerami<: Quadpack) (Surfac.. Mount)
f - - - PQFP
(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 1-4
240817-3
1-5
~
...
£
Intel.
intel.
PACKAGING
PACKAGE TYPES (CX>ntin
PACKAGING
PACKAGE TYPES (continued) PCMClA PC CARD-TYPE 1 ANO TYPE II
PLASTIC PACKAGES • Insertion Mount
TYPE!
Connec10<
Su,gleRow
~
ZIP (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
240817-6
' - - - SJ(JNNY DIP
(Slcinny Dual In-Line Pa,clcage)
~40817-4 1~
1-7
II:
8 F I I I ~ - ~ ~ ~ i= ~"' ... ~
c.- ,,. o..
!!
S2
;»>>>
>>>l!:-
!2>1>1S
~ ~i
';,) ~ ""s!. i
~~~~
"1" 0. c:. to' ..
~~~
~
.._.- INDEX t
inkrocontroOrr 2t
I n,lc:rocmUOllc, 24 ,ddm,ing modn 90, 91 wni!y mant,,i,n 2 t jn!'.zin ol &ht! l 24 ~"'I of the t!OS I 2.l OTP vmlari 26 llA\t memory map 43 rrp1tr bmb t). 44
~ · JO l!O~I mnnorv mar :17 ~
UCD add•uon ifflll cor1ect1M I UCDqplb 169 biN,y nun,,t,.,r, 2 ilddition 6 r t ' p l ~rion
CAU lmtiruction _.-,
4
thKbum~ CJ!,,1! 1iNtnaction
bit 12 buthn 4W bin 13 t,,tr 12
CLR instnKtio1!1 , commmb
C d.1.1 lypct f« &hr IO.'i I
4~
bit 1.57 eblt (mgk- bit} 156 tfr 1.57 Jign,dchu 1 ,gncd int I wwgnt'd dur IS,4
I mkroproc""'>r pir, ikk"nptwn I "'1 ttp,ter \ Ill! on
RE...,ET 1117 !I052 1111(r1~trollcr 24 ~ , t,,p :\•11 675l llU(:.Nr.'Ol'ltrl.li.Lrr 2S
umllf'l'd Im
1
AC fl.lg "'1. '41
ACAU i~ru.;bon 60, 64 ,454 AOCJ~14
to K2SS
ADO UlMl\KUOl'I
326, 1, 402.415 • .,, 8255 41J2 A001f04 AU( ·o-m 30 A
ACJCl)l!C),l chip :)22 ACX..1J!,l)i I 0609 chip '\27, '\28 A lS chip 3JO 31 41 , 116,
45,-455
AOOC illltructlon 117 119, 45o tdJ1a5 buJ 12. 13 .ad.JrtMing modes CJ()-91
bit ~ - ~ a ton
IM
A.'\0 16.5
countuO 229 counter 1 228
293
CPL lnRn,ctlon 121, ¥iO
CPU 12, 1:1 fflll!l:t
d.Jt.i COl\\t'fSIOl'l 169 dai. iwnah.tabon 178
.lJ.(' pUI
A.\ L 11\atruction 456 457
e,tuN.I RAM 3112 Interrupts 2QO ~t')~J 3 15
'-"Lil
LCD 108 MAXl112
ltri.lJ
16.l
DA iNlrucuon 119 460. 461 DACIJ80II 3'4 CWI)' ch.ti,, 4.48 cuia but 1J
441
t,w.inc1ioNI ax,n111,ti ...mllll 441 U9)
44.)
lllilda«110ft cm•m 441
DEC~ 461 dKodffl
10
d1r«tt-• J3, lM • I ZZ. 461, 462
()I\' iNIN(tll1n
"" -.2 J62 OGl9C..0 T1zl v . .
[JltAM
174
f'0'1 264
IIIIVI pon lt('a.,. 261 Nri&I port b-wdt 2'1 SfR
CY D..!g
OfSZ lftlllNdlOII
342
PW~I 447 RAM~i. tpec:e RTC '41"i IK(lil ,d
dyn,,imlc
ocmoeon
DAC0808348
DS89C41CO SRAM 384
h.uct rate 240 8CO n11111bff •ys111tt1• 119
pKbd IC o (O&llft!tff, Set IUnttl
09 dirtclh C JI OM apls 2,1
Al\fl' INU\lctlon 456
169
5 A.r.cD 169
Q I . I ~ Ji"
t.mm.'(h.1111.1ddra!!tng mode 90 inJ ,tJ ..Jd n:sltng ffl('t(M 96 ng~ttt add~g mode 91 tqbl"1' lru.hrcct -..Id~ mode CU, 9S
I\SCII rnwammang A..'iCU t.1ble S14 ~ hie ;1.4, \."i "-nhlft 3.1 ll.!1ff11bltt!l 514-515
A5CD lo pd.ed ICD 170 hinary I ll binar, hP 4 J«im..ll to bvwy 2 ~!Oho' tlo. lO ry ..
1.ttJC
tX.OR 165 ln,·trttr 165 OR 165 shill 165 ~ u m 111 code daui 5J)IICt' 176 C'OW\ler
'.!\O tt•te 9
Cllffi'etlkk\
a.rmu,
dirttt aJJ~ing mode 91 , CM
l&i
13
aintm!
he,; IO dmm.tJ
C P"'f7.ll!'VIUJl8 222. l61, o&IC! ~ . 35
cuta !)'pt
-• l i.
c(IIIIIIWII rlt
«=· -
1M I •
1'1
(UIU!. . . .
I to• Ill l'2
Im"·
-
DS89C4JC0 Trainer (wntinued) running 193 tr0ubleshooting 194 duplex traJ1Smission 238 EA pin 186 embedded systems 20, 21 END directive 39 EPROM 358 EQU directive 39 fan-out 496, 498,503 Oag register 40
Oip-flops 10 flowcharts 510 gigabyte 12 ground bounce 505
half duplex 238 hex 6Je 34 hexadecimal numbers 4 addition 7 subtraction 7 1/0ports 76 fan-out 503 programming 80, 391-397 reading input pin 499 writing to the ports 500 LC technology 492-496 idle mode 504 INC instruction 121, 462, 463 Intel hex file 195 interrupts 272-296 disabling 274 edge-triggered interrupts 281-284 enabling 274 external hardware interrupts 279-284 interrupt handler 272 interrupt vector table 272 level-triggered interrupt 279-284 programming 27$-279 inverter 9 inverters 493, 494 JB instruction 463 ]BC instruction 463 JC instruction 57, 464 JMP instruction 464 JNB instruction 464 JNC instruction 58, 464 JNZ instruction 58, 464
jump inStrUct:ions s(,--60 7 58 59 conditional jumps 5 , ' 58 unconditional 1ump5 JZ inStruction 57, 465 keyboards 311-318 interfacing 311 311 scanning and identifying kilobyte 12 labels 33, 39 LCALL instruction 60-61, 64,466
LCDs 300--310 command codes 301 connection to 8255 397 data sheet 304 LCD timing 304 pin descriptions 300 programming 302-304
LEDs 300 linking 34 LJMP instruction 59, 466 loop 56 nested loop 67 1st file 34, 35 machine cycles 65 machine language 32 MAXl112 chip 336 MAX232/ 233 chips 242,243 megabyte 12 m~ory, See semiconductor memory microcontroller 20 choosing a rnicrocontroller 22 microprocessor 20 mnemonic 32 MOV ~!ruction 30, 467 MOVC ~truction 468, 469 MOVX mstruction 469 MUL instruction 122, 470 NANDgate 9 nested loop 67 nibble 12 NOP instruction 470 NORgate 9
NV-RAM 361 obj file 34, 35 one's complement 6 open collectors 496 open. drain gates 496 opto,solator 431 OR gate 9 ORC _directive 39 ORL instruction 470,471
oscillator t 85 OV flag 40, 41, 127,129,455 overflow 126, 129 p £lag 40,41 packed BCD 11? . parallel cornrnurocatJon 238 pCON register 251 poUing 272.
' '
POP jnstruCbOll 61, 472 port O 76, 186 port J 77, 187 port 2 78, 187 port 3 78, 187 power dissipation 504 power down mode 505 prograrn counter 35, 37
s
C
•
C
s
-s
C
s 5
PROM
358 PSEN pin 186 pseudocode 510
s:
PSW register 40, 41, 44 pulse width modulation 443 PUSH instruction 61,472
RP.ll.1 12,14,360 Real Time Clock 408 alarm 417 interrupt 417 setting the date 412 setting the time 411 SQW 417 reed switch 431 registers 30 SFR registers 92, 93
relays 428 electromechanical relays 428 solid-state relay 430 RESET 36, 185 RET instruction 472
RETI . ·instruction 334, 286, 473 RL mstruction 473 RLC instruction 473 ROM 12, 14, 36, 357 RR~rogram. ROM 35 36 RR ~!ruction 473 '
Cinstruction 473 RS232 standards 240,241
SBUF register 245
SCON regt5ter · 245 secondsenal semi port
,246
255
conductor m address decoct·emory 356-387 interfacing I O smosg 364 mem 1 367 ory space of the 8051 371
S46
INDEX
s·
MOVX instruction 372 organization 356 speed 356
sensors
selection 349 serial communication 238-242, 244-255 8051 programming 246-255 asynchronous 238 data framing 239 synchronous 238 serial communication port 284-288 SETB instruction 204 SFR registers 92 signed number representation 124 S]MP instruction 59,474 sleep mode 505 source fiJe 35 SRAM 360 src fiJe 34, 35 stack 45, 46, 47 in CALL instruction 61
•
....._____
popping 46 pushing 45 stepper motors 432-441 programming 433 structured programming 510-PB 592 SUB instruction 120 SUBB instruction 120, 121, 474, 475 subroutines 61 SWAP instruction 475
timer interrupt programming 275-279 TMOD register 202 217 transient current transistors 492 tr~nsmission line ringing 506 tri-state buffer 498 tri-state buffer 9 TTL technology 494, 495 two's complement 6, 120
TCON register 220, 281-284, 286 terabyte 12 Time Delay 157, 212 ti.me delays 65, 66 timers 202-217 dock source 204 event counter 217-222 mode Oprogramming 214 mode 1 programming 205-206 mode 2 programming 214 registers 202
UART /USART 238 unpacked BCD 119
506
wire wrapping 488 word 12 XCH instruction 475 XCHD instruction 475 XORgate 9 XRL instruction 476, 477 XTALl, XTAL2 185
5'7