8051 (Volume-1)
8051 (Volume-1)
T1
... "
SECOND EDITION
--
PEARSON
Prentice
Hall
op)'Tlght 0 2006 by Pearson Edncation, Ine., Upper Saddle River, New Jersey 074~8.Pearson Prentice Hall. All rights
"""rved. Printed in the United States of America. This publication is protected by Copyright and permission should be obtaine
d
from the publisher prior to any prohibited reproduction, storage in a retrieval system, or tranSmission in any form or by any means,
electrcmc, mechanical,
Pcmllssiol\s Department. photocopying, recording, or likewise. For information regarding pennission(s), write to: Rights and
ISBN: o-l3-119402-X
... man's glory lieth in his knowledge,
his upright conduct, his praiseworthy character,
his wisdom, and not in his nationality or rank.
- Baha'u'llah
CONTENTS AT A GLANCE
CHAPTERS
I
0: Introduction to Computing 23
I: The 8051 Microcontrollers 37
2:
8051 Assembly Language Programming
69
3: Jump, Loop, and Call Instructions
9
4: I/O Port programming
109
s: 80SI Addressing Modes
1'9
6: Arithmetic & Logic Instructions and Programs
I I
7: 80SI Programming in C
80SI Hardware Connection and Intel Hex File 217
8:
8051 Timer Programming in Assembly and C 2 9
9:
Ed 10: 80SI Serial Port Programming in Assembly and C 277
Ed II: Interrupts Programming in Assembly and C 317
PI 51
De 12: LCD and Keyboard Interfacing
Co 13: ADC. DAC. and Sensor Interfacing 37
Co 14: 8051 Interfacing to External Memory 411
PI
So IS: 8051 Interfacing with the 8255 449
So 16: DS12887 RTC Interfacing and Programming 467
17: Motor Control: Relay, PWM. DC. and Stepper Motors 491
APPENDICES
A: 8051
B. Instructions
. I
Timing and Registers
,
.
52
B: asrcs of WIre Wrapping
C: Ie Technology adS . Issues 56
0:
FI h n ystem DeSIgn 567
Owe arts and Pseudocode
E: 8051 Primer for X86 P 7
F: ASCII Codes rogrammers 592
G: Assemblers. Development R 593
H: Data Sheets eSOurces. and Suppliers 594
596
CONTENTS
v
-
CHAPTER 7: 8051 PROGRAMMING IN C
181
Section 7.1: Data types and time delay in 805 I C
182
Section 7.2: I/O programming in 8051 C
188
Section 7.3: Logic operations in 8051 C
194
Section 7.4: Data conversion programs in 8051 C
199
Section 7.5: Accessing code ROM space in 8051 C
204
Section 7.6: Data serialization using 8051 C
209
VI
CHAPTER 14: 8051 INTERFACING TO EXTERNAL MEMORY 411
Section 14.1: Sem iconductor memory 412
Section 14.2: Memory address decoding 422
Section 14.3: 803 1/51 interfacing with external ROM 425
Section 14.4: 8051 data memory space 430
Section 14.5: Accessing external data memory in 8051 C 440
INDEX 617
vii
K .. ,ad....,
h J In III Iroduc 1(1) dlgilal 'our e. Knowledge of
hIp/iii ut I n t neces ry. A hhough the book is
tt lund in,~ 'mhly language programming, stu-
pcncnce w ill be able 10 gain a ma tery of
nd I.m on their proje ts right away. For the 8051
~ k, a ha", knowledge of C programming is
ix
ond edition .. of 0-1 program-
What is new in the sec . edition is the addition A sembI languag
The biggest change inWhile
this new
Chapters I t hough
r 6 blyand
use language pr _
ming throughou t ,the book.
ith ChapterI 7, we haddition
ve both Assem
includes t h e following new
. Iy, starting .ws discussed. The secon e
exclusive
grams for all the topic
features: . (Chapter 7)
8051 C programming . ers ( ection 9.3)
Anew chapter 00 he 80" C programm ing of ";89<:4'0 ch ip ( ecti n 10:')
A new secuon on 1 d serial port of the D d erial pan ( e lion
A new section on the ~~;~ C programming of the econ
A new secnon on the . I I 6)
10.5) . . of interrupts
th 8051 C programming ( c lion 14.4)
0 h' (Section .
A new secuon on e KB SRAM of the DS89C4x C Ip ( ecti n 14. )
Programming of", , ro ramming of ~I"",, memory 16)
A new section on the 8051 ~:7 :TC (real-time clock) chip ( hapter
A new chapter
A new chapter on
on motors,
the DSI2relays, and optoisolators (Chapter 17)
E
E
P
lab manual h b k b the
The lab manual and suppo~ rnat~.rialslEd' and otite.er
for this Web
authors can be found at the www.MlcroDlglla.eom
This book is the result of the dedication and encouragement of many indi-
viduals. Our sincere and heartfelt appreciation goes to all of them.
First, we Would like 10 thank PrOfessor Danny Morse, the rno t knowl-
edgeable and experienced person on the 8051 that we know. He felt a trong need
for a book such as this, and due to his lack of time he encOuraged 1I 10 write it. He
i the one who introduced us to this microcontroller and was always there, ready
10 discuss issues related to 8051 architecture.
0 Also we Would like to express our sincere thanks to Profe SOr Iyde
book.
K ,hI o f De Vry Univers. 0/ for hi, h"p'o' ""'''''"' 00 the ,~'" ,f the '''''00
in .dll'"" the""ow'"8 pmf,",," ,"d _"" 'Oo"' '"'" whII," ing
the""" in '" "P"""",oo
'h'm """"y, ,,"r.~,
f,""
in "'" m
PhilG"Id~"diobo B,"Y"
"",,'01" II" '"""' ,,' we mM'
Do V~ UoI;",~, R,bon
lV'gh"",,, p,,,,,,,, "'",""
U"'i,m '" "m boo, D"" B'.m", J'Im H'.. ''''
~ Rob."", y'''Y Ch""" N"
J,m" Doo'" Ro,," MI,,,,, I B,,,, ''''00
"0
Hoang, and Trevor Isra.
II,J"" ~ ""Y H'", """
J"h"~",J"" K,,,,:M""" I M'"h;", M,"
Acknowledgments for the second edition
Thanks to the reviewers of this edition: Jack Adams, Merrimack College;
Hector Gutierrez, Florida Institute of Technology; Martin Hebel, Southern Illinois
University; Gary Hill, California State University - Long Beach; Juan Vargas,
University of Central Florida; Richard W. Wall, University of Idaho; and Rainer
Weschke, SUNY - Suffolk.
Numerous professors, students, and individuals sent us comments and
errors found in the first edition. Many others made suggestions for the second
edition. We would like to thank all of them sincerely for their enthusiam and support.
We hope to create a list of their names on our Web site at
www.MicroDigitaIEd.com. They are Danny Morse, Clyde Knight, Shah ram
Rohani (all from DeVry University), Javad Rasti (Esfahan University), Nassir
Abedi (KN. Toosi University), Hooman Shayani (BIHE), Jaco Vosloo
(Stellenbosh University), Mohammad Khalid Kerani, Hassan Mohammadi Abdar
(Azad University), Jeff Solinsky, Alijah Ballard, Jacob Stauffer, Vaibhav Joshi,
Michael Kelley, and Dan Masterson.
Finally, we would like to thank the people at Prentice Hall, in particular
our editor Kate Linsner, who continues to support and encourage our writing, and
our production editor Kevin Happell, who made the book a reality.
We enjoyed writing this book, and hope you enjoy reading it and using it
for your courses and projects. Please let us know if you have any suggestions or
find any errors .
. Assemblers
The following gives sites where you can download assemblers:
www.MicroDigitalEd.com
www.keil.com for Keil Corporation
www.fsinc.com for Franklin Software, Inc.
http://developer.intel.com/design/mcs51/docs_mcs51.htm
- xi
AtlUU I 1m: I\U II """ ..
Whati
Ali Mazidi went to Tabrll
Muhamma d U . ahe
fi both Southern Methodi l 0I1e1'l11)
degrees rom d hi Ph D In a
Dallas. He is currenlly a.b. : on. . .
Department of Southern Methodist VOile II) lie I
textbook, The 80x86 IBM PC and CIlI/lf'</IIh1l'
Prentice Hall. He leaches microproce t-
A University in Dallas, Texas. .
• A Janice Gillispie Mazidi has a M rer 01
A Science from the University of orth Texas. h h " c
A as a software engineer in Dallas. he h been hid 'ChilI I \ III r
10. lionmanager, and was responsible for solhl re ckl I pm III a
• A Iy used textbook, The 8Ox86 IBM PC anti 1I1IIp</lr"l tN I/' 1/
P from Prentice Hall.
• A
A
Rolin McKinlay has a BSEET fr m De\/) llll\1;
working on his Masler's degree and PE licen . In Ih' ,.
I'I I
, A
rently self-employed as a programmer and ir UII rd d I '/I r, r
in MicroDigitaIEd.com.
To Betsy.for all the love, encouragement, and sacrifice she has made/or me.
- Rolin D. Mckinlay
xiii
r
r
"
f>
I'
CHAPTER 0
INTRODUCTION TO
COMPUTING
OBJECTIVES
» Convert any number from base 2, base 10, or base 16 to either of the
other two bases
» Add and subtract hex numbers
» Add binary numbers
» Represent any binary number in 2's complement
» Represent an alphanumeric string in ASCII code
» Describe logical operations AND, OR, NOT, XOR, NAND, NOR
» Use logic gates to diagram simple circuits
» Explain the difference between a bit, a nibble, a byte, and a word
» Give precise mathematical defmitions of the terms kilobyte, megabyte,
gigabyte, and terabyte
» Explain the difference between RAM and ROM and describe their use
» Describe the purpose of the major components of a computer system
» List the three types of buses found in computers and describe the
purpose of each type of bus
» Describe the role of the CPU in computer systems
» List the major components of the CPU and describe the purpose of each
1
ana 1I'1lu·.....·- ...... - . _. )' ~
To understand the software basic concep!. underlymg mput r d ign
ter some very , be II d .
one must first mas d'tl'on of digital comput rs n h pIer
iem, hi h 10 the tra I d
I this chapter (w ic 'and coding 'yslems rc pre enre Iter an
On)the fundamentals of numbenng llew of the work 109 In rd the c mpul r is
, , I' gates, an overv " f' P
'ntroduetIon to ogle . we give a brief hi I ry o r hlle lure
I 'I' the last sectIOn , d f .
given, Fmal y, 10 have an adequale ba kgrourt 10 10'10) rh I pic
Although some,readers maYendcdthat the matcrial be 00 d. h wever bneny.
of Ihis chapter, It IS rccomIO
SoluMa:
Quot:ient
25/2 = 12 Rema:inder
12/2 = 6 1 LSB (leas
6/2 =
3
o 81 01 c n b1 )
3/2 =
1
o
1/2 = 1
o
1
MSB (moSt signi
Therefore,2510" Jl001 c 0 1t)
2·
- --::------
2
-
Converting from binary to decimal 74068310
To convert from binary to decimal, it is
important to understand the concept of weight ~ 10°
~ 3
101 = 80
associated with each digit position. First, as an 6 x
102 = 600
analogy, recall the weight of numbers in the base 0 x
103 = 0000
10 system, as shown in the diagram. By the same 4 104
x = 40000
token, each digit position in a number in base 2 7 X 105 = 700000
has a weight associated with it: 740683
Knowing the weight of each bit in a binary number makes it simple to add
them together to get its decimal equivalent, as shown in Example 0-2.
Example 0-2
Convert 110012 to decimal.
SOlution:
Weight: 16 8 4 2 1
Digits: 1 I 0 0 1
Sum: 16 + 8+ 0+ 0+ 1=2510
Knowing the weight 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-3
Use the concept of weight to convert 39, 0 to binary.
Solution:
Weight: 32 16 8 4 2 1
1 0 0 I 1 1
32 + 0+ 0+ 4+ 2+ 1=39
Therefore, 3910 = 1001112,
Example 0-4
Solution:
First the number is d .
Then each groupe. mto sets of 4 bits: 100 I I11I 0101
group of 4 bits IS replaced with its hex e . I .
1001 1111 0101 quiva ent:
9 F 5
Therefore, 100111110 I0 12 = 9F5 hexadecimal.
Example 0-5
Convert hex 29B to binary.
I Solulion:
2 9 B
Dropping the I~ding ~e~~~ gi 100 II0 II 0 II
ves 0011011
Converting from decimal to hex .
onvertmg from deCimal t h
I. Convert to bimary first and0 ex could be a
th pproaehed in two
method of conven: . en Convert to h ways:
2. C nvcn direetlye~lng ddeclmal to hex. ex. Example 0-6 shows this
. om eelmal to I b
remamders. Experimentin . lex y repeated divisio .
g With this method is left n, keepmg track of the
to the reader.
4
Example 0-6
(a) Convert 4510 to hex.
Example 0-7
7
Table 0-2: Counting in Bases . bases 10, 2 , and 16
Counting In
Decimal Binary Hex To show the relationship between all
o 00000 o . bl 0 2 we show the sequence
three bases, In Ta e - . d . I along with
00001 of numbers from 0 to 31 In ecimar,
2 00010 2 the equiva- Table 0-3: Binary Addition
3 00011 3 lent binary Sum
4 00100 4 A+ B Carry
5 00101 5 numbers. 0 I
6 00110 6 . 0+ I
Notice 111 0 I
7 00111 7 1+0
each base I 0
8 01000 8 that when 1.~+...!I
1 __ L;__ ..::....
__
9 01001 9 one more IS
10 01010 A added to
II 01011 B
the highest digit, that digit becomes zero and a
12 01100 C
I is carried to the next-highest digit position.
13 01101 o For example, in decimal, 9 + I = 0 with a carry
14 01110 E
15
to the next-highest position. In binary, I + I =
01111 F
16 10000
o with a carry; similarly, in hex, F + I = 0 with
10 a carry.
17 10001 II
18 10010 12 Addition of binary and hex numbers
19 10011 13
20 10100 14 The addition of binary numbers is a
21 10101 15 very straightforward process. Table 0-3 shows
22 10110 16 the addition of two bits. The discussion of sub-
23 10111 17 traction of binary numbers is bypassed since all
24 11000 18 computers usc the addition process to imple-
25 11001 19 ment SUbtraction. Although computers have
26 11010 IA adder circuitry, there is no separate circuitry for
27 11011 IB sUbtractors. Instead, adders arc used in con-
28 11100 IC junction with 2 s complement circuitry to per-
29 11101 ID form SUbtraction. In other words, to implement
30 11110 IE "x - y", the computer takes the 2's complement
31 11111 IF ofy and adds it to x. The concept of2's com-
plement is reviewed next. Example 0-8 shows
the addition of binary numbers.
Example 0-8
Add the following binary numbers. Cheek against their decimal equivalents.
Solution:
Binary
Decimal
1101
13
+ lllill
10110
-.2
22
6
·2's complement
To get the 2's complement of a binary number, invert all the bits and then
add I to the result. Inverting the bits is simply a matter of changing all Os to ls
and J s to Os. This is called the I :\'complement, See Example 0'-9,
Example 0-9
Take the 2's complement of JOOIIIOl.
Solution:
10011101 binary number
01100010 I's complement
+ 1
01100011 2's complement
Example 0-10
Perform hex addition: 2309 + 94BE,
Solution:
2309 LSD: 9 + 14 = 23 23 - 16 = 7 with a carry
+ 94BE I + 13 + II = 25 25 -16 = 9 with a carry
B897 1+3+4=8
MSD: 2+ 9=B
7
bimary P attcrns
, for numbers 0 to 9, all the Hex Symbol Hex Symbol
letters of the English alphabet, both 41 A 61 a
uppercase (capital) and lowercase, and 42 B 62 b
many control codes and punctuation :~ C 63 c
marks, The great advantage of this sys- D 64 d
tem is that it is used by most computers, 59
y 79 y
so that information can be shared among 5A
computers, The ASCII system uses a Z 7A z
total of? bits to represent each code, For LF-igu-r-e
":'"0--1-, S=-e":'"le-e':-te"":d"":A-::S:::C::-n:-C;:-:-od;e:::s--
example, 100 0001 is assigned to the
uppercase letter "A" and 110 000 I is for "" ,
the lowercase "a", Often, a zero is placed in the most significant bit position to
make it an 8-bit code, Figure 0-1 shows selected ASCII codes, A complete list of
ASCII codes is given in Appendix F. The usc of ASCII is not only standard for
keyboards used in the United States and many other countries but also provides a
standard for printing and displaying characters by output devices such as printers
and monitors,
Notice that the pattern of ASCII eodcs was designed to allow for easy
manipulation of ASCII data, For example, digits 0 through 9 are represented by
ASCII eodcs 30 through 39, This enables a program to easily convert ASCII to
decimal by masking off the "3" in the upper nibble, Also notice that there is a rela-
tionship between the uppercase and lowercase letters, The uppercase letters arc
represcnted by ASCII codes 41 through 5A while lowercase letters arc represent-
ed by codes 61 through 7A, Looking at the binary code, the only bit that is differ-
ent between the uppercase "A" and lowercase "a" is bit 5, Therefore, conversion
between uppercase and lowercase is as simple as changing bit 5 of the ASCII code,
Example 0-11
Perform hex Subtraction: 59F 2B8,
olution:
59F
LSD: 8 from 15 ~ 7
- 2B8
2E7 J 1 1T0m 25 (9 + 16) = 14 (E)
21T0m4(5-1)=2
ReView Questions
I.
Why do computcrs use thc binary number system instead of the dcei nal
tern? I sys-
2, Convert 3410 to binary and hex,
3. Convert /10 I012 to hex and dccimal.
4, Pcrfonll binary addition: 101100 + 101.
5, Convert 101/002 to its 2 's complemcnt representation
6, Add 36BH + F6H, '
7, SUbtract 36BH _ F6H,
8, Write "80x86 CPUs" in its ASC/J code (in hex 1'0 )
rm).
8
4
This section gives an overview of digital logic and design. First, we cover
binary logic operations, then we show gates that perform these functions. Next,
logic gates are put together to form simple digital circuits. Finally, we cover some
logic devices commonly found in microcontroller interfacing.
~--------,
Binary logic
Sf-
As mentioned earlier, computers use the
binary number system because the two voltage lev- 4 Logic I
els can be represented as the two digits 0 and l. 3f-
Signals in digital electronics have two distinct volt-
age levels. For example, a system may define 0 Vas 2f-
logic 0 and +5 V as logic I. Figure 0-2 shows this
system with the built-in tolerances for variations in· If-
the voltage. A valid digital signal in this example Logic 0
Of-
should be within either of the two shaded areas.
___ c _
Inverter
~=D-XNANDY
Logic design using gates
1+/=
o I I J 0
I 0
;=D-XNORY
10
-
2
Notice that when we add I + I we get 0 with a carry to the next higher
place. We will need to determine the sum and the carry for this design. Notice that
the sum column above matches the output for the XOR function, and that the carry
column matches the output for the AND function. Figure 0-3 (a) shows a simple
adder implemented with XOR and AND gates. Figure 0-3 (b) shows the same
logic circuit implemented with AND and OR gates. . .
X
x l--- Sum
Y ---'---I
Y -.--1-1-/
}---Sum
X---I
Y
'-_~----,)--- Carry
X-----.,
y-- }------- Carry
(a) Half-Adder Using XOR and AND (a) Half-Adder Using AND, OR, Inverters
x X Half- Carry
y Sum y Adder
Sum
Half-
- C out
Adder Carry
C in
C in
Final Sum
Flip-flops
X1
A widely u cd component in digital Y1
Full· r-.-----S1
) ,Icm I the nip-nop. Frequently, nip- Adder
IIIlfl' Me u. cd to tore data. Figure 0-8 Carry
ho"" the logic diagram, block dIagram,
nd lrulh wble f r a nip-nop.
Thc 0 nip.nop (D-FF) is widely X2
u\(d to latch data. oucc from the truth Y2 Full- r-----_S2
I ble th(ll 0·1'1' grab the data at the input Adder Carry
Ihe clock is tivated. A D·FF holds the r-----_S3
d.1l long s the POwer is n. ';F;::j'::'gu:-r:-c';>O_-;6,.-.
3:;---;;B-;;jt-;A-:;d::;dc:::r:-;u'7:s7:in::g:-::3~F;;:u:-;III'A;;;:dd;;:c::r-:s
__
1~1l
LSU
D
elk D
Q No
II. x
Ik 1- 0
1- I
Q
(~)
'rcull draglllm
Q - x .:::::
don', care
-
/2
-
Review Questions
1. The logical operation gives a I output when all inputs are I.
2. The logical operation __ gives a 1 output when I or more of its inputs is I.
3. The logical operation __ is often used to compare if two inputs have the
same value .
. 4. A __ gate does not change the logic level of the input.
5. Name a common use for flip-flops.
6. An address is used to identify a predetermined binary address.
Address Bus
Memory Peripherals
CPU
(monitor,
(RAM, ROM) printer, etc.)
Data Bus
Address Bus
•
RAM ROM
~
Printer •
Disk •
Monitor •
Keyboard
CPU
Data Bus
Read/write
Control Bus
Program Counter
Internal
buses
Register A
Register B
Register C
Register 0
Inside CPUs
I. Foremost among the resources at the disposal of the CPU are a number of reg-
isters. The CPU uses registers to store information temporari Iy. The informa-
tion could be two values to be processed, or the address of the value needed to
be fetched from memory. Registers inside the CPU can be 8-bit, 16-bit, 32-bit,
or even 64-bit registers, depending on the CPU. In general, the more and big-
ger the registers, the better the CPU. The disadvantage of more and bigger reg-
isters is the increased cost of such a CPU.
2. The CPU also has what is called theALU (arithmetic/logic unit). The ALU sec-
tion of the PU is responsible for performing arithmetic functions such as add
ubtract, multiply, and divide, and logic functions such as AND, OR, and NOT:
Every CPU has what is called a program COUnter. The function of the program
16
7
counter is to point to the address of the next instruction to be executed. As each
instruction is executed, the program counter is incremented to point to the
address of the next instruction to be executed. The contents of the program
counter are placed on the address bus to find and fetch the desired instruction.
In the IBM PC, the program counter is a register called IP, or the instruction
pointer. .
4. The function of the instruction decoder is to interpret the instruction fetched'
into the CPU. One can think of the instruction decoder as a kind of dictionary,
storing the meaning of each instruction and what steps the CPU should take
upon receiving a given instruction. Just as a dictionary requires more pages the
more words it defines, a CPU capable of understanding more instructions
requires more transistors to design. i
If the program to perform the actions listed above is stored in' memory
locations starting at 1400H, the following would represent the contents for each
memory address location:
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. The
program counter must be set to the value 1400H, indicating the address of the
first instruction code to be executed. After the program counter has been
Review Questions
I, How many bytes is 24 kilobytes?
2. What docs "RAM" stand Cor? Ho ' ,
3. " , r W IS It u"ed '
W hat docs "ROM" stand f< ? H " s 111 computer systems?
4 Wh ' RA or, ow IS It used i '
. . Y IS M called volatile mcmor ') n computer systems?
5. List the three major com y,
6. What docs "CPU" t d ~onents of a computcr system
' san for? Explain it f' '
7, L I t the three types of b 'c ,s unction in a computer
uses round 111 COl '
purpose of each type of bus nputer systems and state b ' fl
8, tate which of the followi " " ne y the
ng IS unidirectional and hi h i "
W IC IS bidirectional.
18
(a) data bus (b) address bus
9. If an address bus for a given computer has 16 lines, what is the maximum
amount of memory it can access?
10. What does "ALU" stand for? What is its purpose?
II . How are registers used in computer systems?
12. What is the purpose of the program counter?
13. What is the purpose of the instruction decoder?
SUMMARY
7
PROBLEMS
I. Computers use the binary system because each bit can have one of two voltage levels: on and
off.
2. 3410 = 1000102 = 2216
3. 1101012=3516=5310
4. 1110001
5. 010100
6. 461
7. 275
7
8. 38 30 78 38 36 2043 50 55 73
I. AND
2. OR
3. XOR
4. BulTer
5. Storing data
6. Decoder
I. 24,576 .
2. Random access memory; it is used for temporary storage of programs that the CPU IS run-
ning, such as the operating system, word processing programs, etc.
3. Read-only memory; it is used for permanent programs such as Ihose that control the keyboard.
etc.
4, The contents of RAM arc lost when the computer is powered 01T.
5. The CPU, memory, and 110 devices
6. Central processing unit; it can be consideredthe "brain" or the computer; it executes the pro.
grams and controls all other devices in the computer.
7. The address bus carries Ihe location (address) needed by the CPU; the data bus carries infor-
mation in and out ofthe CPU; the control bus is used by the CPU 10 send signals controlling
I/O devices,
R. (aJ bidirectional (b) unidirectional
9. 64K. or 65,536 byres
10. Arithmetic/logic unit; it performs all arithmetic and logic operations
1I. It IS for temporary storage of information
12. It holds the address of the next instruclion to be executed,
13. It tells the CPU what steps to perform for each instruction,
CHAPTER 1
THE 8051
MICROCONTROLLERS
OBJECTIVES
- 23
This chapter begins with a discussion of the role and importance of micro-
controllers in everyday life. In Section 1.1 we also discuss cntena to consider In
choosing a microcontroller, as well as the usc ofmicrocontroUers In the embedded
market. Section 1.2 covers various members of the 8051 family such as the 8052
and 8031, and their features. In addition, we discuss vanous versions of the 8051
such as the 8751, AT89C51, and OS5000.
In this section we discuss the need for microcontrollers and contrast them
with general-purpose microprocessors such as the Pentium and other x86 micro-
processors. We also look at the role of microcontrollers in the embedded market.
In addition, we provide some criteria on how to choose a microcontroller.
D ata b us
CPU
r I .i. I I
CPU RAM ROM
General-
Purpose RAM Serial
ROM VO Timer
Miero- COM
Port
processor Port I/O Timer Serial
T I I I I COM
Addresss bus Port
Engine control disk controller, sound card, CD-ROM driver, mouse, and so on.
Air bag Each one of these peripherals has a microcontroller inside it that
ABS performs only one task. For example, inside every mouse there is
Instrumentation a microcontroller that performs the task of finding the mouse
Security system position and sending it to the Pc. Table I-I lists some embedded
Transmission control products.
Entertainment
Climate control X86 PC embedded applications
Cellular phone
Keyless entry Although microcontrollers are the preferred choice for
many embedded systems, there are times that a microcontroller is .
Table I-I: Some inadequate for the task. For this reason, in recent years many
Embedded Products manufacturers of general-purpose microprocessors such as Intel,
Using
Freescale Semiconductor Inc. (formerly Motorola), AMD
Microcontrollers
(Advanced Micro Devices, lnc.), and Cyrix (now a division of
Choosing a microcontroller
There arc four rna' '.
Intel's 8051 Zilo ' ~or 8-blt mlerOcontrollers Th
mieroeontr;lIers ~a: :8~ and PIC 16X from Microchip
not compatible w'th nlque instruction set and reoi
T~~tei Freeseale's 6811,
no ogy. Each of these
I each othe P egrste- set: th f
ers. There arc also 16-bit and r. rograms written for one will ere ore, they are
crs, With all these dl'fIi 32-bll mleroeontrollers d not run on the oth-
. hoosi erent mie ma e by vari .
111 COOing one? Three . . roeontrollers, what eri' anous chIp mak-
meeling the eompulin entena 111 choosing mieroeo ten a do deSIgners consider
(2) availability of soft g needs of the task at hand ffi ntrollers are as follows' (I)
debugger, and (J) wi;are development tools sue~ lelently and cost effecti~e1
ext we elaborate limh e availability and reliable s as compilers, aSScmblers and
cr on each of h ourees of the' ,
t e above criteria mleroController.
26
Criteria for choosing a microcontroller
1. The first and foremost criterion in choosing a microcontroller is that it must
.meet the task at hand efficiently and cost effectively. In analyzing the needs
of a microcontroller-based project, we must first see whether all 8-bit, 16-bit,
or 32-bit microcontroller can best handle the computing needs of the task most
effectively. Among other considerations in this category are:
(a) Speed. What is the highest speed that the microcontroller supports?
(b) Packaging. Does it come in a 40-pin DIP (dual inline package) or a QFP
(quad flat package), or some other packaging format? This is important in
terms of space, assembling, and prototyping the end product.
(c) Power consumption. This is especially critical for battery-powered prod-
ucts.
(d) The amount of RAM and ROM on chip.
(e) The number of I/O pins and the timer on the chip.
(f) How easy it is to upgrade to higher-performance or lower power-con-
sumption versions.
(g) Cost per unit. This is important in terms of the final cost of the product in
which a microcontroller is used. For example, there are microcontrollers
that cost 50 cents per unit when purchased 100,000 units at a time.
In this section we first look atthc various members of the 8051 family of
mjcrocontrollcrs and their internal features. Plus we see who are the different man-
ufacturers of the 8051 and what kind of products they offer.
ON-CHIP o
Y 't ROM o
c
INTERRUPT 1--._. . for ETC ~
__ .. program
CONTROL
'-----,-----'-
~.
.-- code
ON-CHIP
RAM
TIMER 0 f-oc--} - g]
TIMER 1 _- Z
I • '?-
1J
c
Y oJ
~
IA I
CPU
\
A A .lJ
BUS
~
4 I/O
~7
SERIAL
CONTROL PORTS PORT
I
A
t .~
f t f
PO P2 P1 P3
I
Y
TXD RXD
I
...... .
-
ADDRESS/DATA
8052 micr.ocontroller
The 8052 is another member of the 8051 family The 8052 has all the stan-
dard features of the 8051 as well as an extra 128 bytes of RAM and an extra timer.
In other words, the 8052 has 256 bytes of RAM and 3 timers. It also has 8K bytes
of on-chip program ROM instead of 4K bytes. See Table 1-4.
Table 1-4: Comparison of 8051 Family Members
Feature 8051 8052 8031
ROM (on-chip program space in bytes) 4K 8K OK
RAM (bytes) 128 256 128
Timers 2 3 2
I/O pins 32 32 32
Serial port 1
Interrupt sources 6 8 6
As can be seen from Table 1-4, the 8051 is a subset of the 8052; therefore,
all programs written for the 8051 will run on the 8052, but the reverse is not true.
8751 microcontroller
This 8751 chip has only 4K bytes of on-Chip UV-EPROM. Using this chip
for development requires acecss to a PROM bumer, as well as a UV-EPROM eras-
er to crase the COntentsof UV-EPROM inside the 8751 chi b C
gram It. agarn.
. Beeausc the on-Chip . ROM for the 875/ is tpUV-EPROM
e,ore you can pro-
it takes
around
Id 20 mmutes to erase the 8751 before it can be d' ' .
e many manUfacturers to Introduce
. flash and NV RAM .
programme agam. This has
'11di - verSions of the 8051 as
;~:~iff~~~~~~~~~~n~~re arc also various speed versions of the 875 I availa'ble
DS89C4xO Trainer
WWW.8052.com/chips.phtml
WWW.MicroDigilaIEd.com
2
, ,,Review Questions
c..,V
(}t . I. Name three features of the 8051.
~ 2. What is the major di fference between the 805 I and 8052 microcontrollers?
3. Give the size of RAM in each of the following.
(a) 8051 (b) 8052 (c) 8031
4. Give the size of the on-chip ROM in each of the following.
(a) 8051 (b) 8052 (c) 8031
5. The 8051 is a(n) -bit microprocessor.
6. State a major difference between the 8751, the AT89C5 I, and the
DS89C420/30.
7. True or false. The DS89C420/30 is really an 8052 chip.
8. True or false. The DS89C420/30 has a loader embedded to the chip, therefore
eliminating the need for ROM burner.
9. The DS89C420/30 chip has bytes of on-chip ROM.
10. The DS89C420/30 chip has bytes of RAM.
SUMMARY
PROBLEMS
14. What does the term "third-party s~PP~rttl ~~~~'and 16-bir ver ions, which of
15. If a mierocontroller arehlteetur~ as 0 1
the following statements IStrue. .
(a) The 8-bit software will run on the 16-blt system.
(b) The 16-bit software will run on the 8-blt system.
I. 128 bytes of RAM, 4K bytes of on-ehip ROM, [our 8-bit JlO pons.
2. The 8052 has everything that the 8051 has, plus an extra timer, and the on-chip ROM is 8K
bytes instead of 4K bytes. The RAM in the 8052 is 256 bytes instead of 128 bytes.
3. Both the 8051 and the 8031 have 128 bytes of RAM and the 8052 has 256 bytes.
4. (a) 4K bytes (b) 8K bytes (c) OK bytes
5. 8
6. The main difference is the type of on-chip ROM. III the 8751 it is UV-EPROM; in the
AT89C51 it is flash; and in the DS89C420130 it is flash with a loader on the ehip.
7. True
8. True
9. 16K
10. 256
___ ...-z _
36
CHAPTER 2
8051 ASSEMBLY
LANGUAGE
PROGRAMMING
OBJECTIVES
37
--17 _
In Section 2.1 we look at the inside of the 8051. We demonstrate some of
the widely used registers of the 8051 with simple instructions such as MOV and
ADD. In Section 2.2 we examine Assembly language and machine language pro-
gramming and define terms such as mnemonics, opcode, operand, etc. The process
of assembling and creating a ready-to-run program for the 8051 is diseu sed in
Section 2.3. Step-by-step execution of an 8051 program and the role of the pro-
gram counter are examined in Section 2.4. In Section 2.5 we look at some widely
used Assembly language directives, pseudocode, and data types related to the
8051. In Section 2.6 we discuss the flag bits and how they are affected by arith-
metic instructions. Allocation of RAM memory inside the 8051 plus the stack and
register banks of the 8051 arc discussed in Section 2.7.
. In this section we examine the major registers of the 8051 and show their
use with the simple instructions MOV and ADD.
Registers
In the CPU, reg-
isters arc used to store
information temporarily. That information could be a byte of data to be proce d
or an address pomtmg to the data to be fetched. The vast rna' . es e ,
ters arc 8-blt registers In the 8051 th . I jonty of 8051 regis-
. ere IS on y one data type' 8 bits TI 8 bi f
a register arc shown in the diagram from the MSB .', ' ,le It 0
LSB (least significant bit) DO With 8 bi d (most significant bit) 07 to the
. 1 an - It ara type a d I
must be broken into 8-bit chunk be' . ' ny ata arger than 8 bits
. . s erore It IS process, d S'
number 01' registers in the 8051 'II eo. 1I1eethere arc a large
, we WI concentrate on f the wi
general-purpose registers and cover . I . some 0 t e widely u ed
r------=--~ A endi specia registers 111 future chapters, See
pp x A.2 for a complete list of 8051 .
I A .
I registers,
I B I DPTR
I RO I [_D_PH_I DPL
I RI I -----
PC
\ R2 I [ PC (program counter)
I R3 ] F'
Igure 2-1 (b). Some 8051 16-b't R .
I R4 ]
I Rsl
J
The most widel .
a\<cUm"I"fiO' D bOY used registers of the 8051
l
[
R6~''D
R7
]
l 1IJ l'lt
J
iIt._ ..", • RI R2 R
pointer), and Pc ' 3, R4, R,
0fhe above registers arc 8 ,{p gram COUn er . All
arc
6, R7,
'";1:::~-:-:-:----
1
program COUnter Iieaccuml-OilS, exce(lt DPTR a n d tne
fo' h
Figure 2-1 (a), Some 8-bit rail arithmetie and 10 ' , u ator, reglste A is used
Registers or the 8051 the use of th esc registersglc Instructions
. '
,0 understand
Context oftw' .' we will show th .
o Simple Instructions Mo em In the
38 , Vand ADD.
MOV instruction
Simply stated, the MOV instruction copies data from one location to anoth-
er, It has the following format:
This instruction tells the CPU to move (in reality, copy) the source operand
to the destination operand, For example, the instruction "MOV A, RO" copies the
contents of register RO to register A, After this instruction is executed, register A
will have the same value as register RO, The MOV instruction does not affect the
source operand, The following program first loads register A with value 55H (that
is 55 in hex), then moves this value around to various registers inside the CPU,
Notice the "#" in the instruction, This signifies that it is a value, The importance
of this will be discussed soon,
otice in instruction "MOV R5, #0 F9H" that a 0 is used between the # and
F to indicate tbat F is a hex number and not a Ie er. In other words "MOV
R5, #F9H" will cause an error,
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 "MOV
A, 17H"means to move into A the value held in memory location 17H, which
could 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
valid 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
The ADD instnletion tells the CPU to add the Source byte to register A and
put
b the result In register A. To add two numbers such as 25H and 34H h
e move d to a register
. and then added together: ,cae can
MOV A,#25H
;load 25H into A
MOV R2,#34H
ADD A,R2 ;load 34H into R2
;add R2 to accumulator
; (A = A + R2)
In the above case, while one register contained one value, the second value
followed the instruction as an OReland. This is calle an immediate 0 erand. The
examples shown so far for the 00' nstructi n indicate that the source 0 erand
can be either a register or immediate data, but the destination must w ys be rcg
list r , he accumulator. n other words, an instruction such as "ADD R2, #12H"
is invalid since register A (accumulator) must be involved in any arithmetic oper-
ation. 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 forego-
ing discussion explains why register A is referred to as the accumulator. The for-
mat for Assembly language instructions, descriptions of their use, and a listing of
legal operand types are provided in Appendix A.I.
There are two 16-bit registers in the 8051: PC (program counter) and
OPTR (data pointer). The importance and use of the program counter are covered
in Section 2.3. The OPTR register is used in accessing data and is discussed in
Chapter 5 where addressing modes are covered.
Review Questions
I. Write the instructions to move value 34H into register A and value 3FH into
register B, then add them together.
2. Write the instructions to add the values 16H and COHo Place the result in reg-
ister R2.
3. True or false. No value can be moved directly into registers RO - I3-7.
4. What is the largest hex value that can be moved into an 8-bit register? What is
the decimal equivalent of the hex value?
5. The vast majority of registers in 8051 are __ bits.
__ .dtn-.__
viations that arc relatively easy to--lG!!!£.mber.ssembly language rograms must
be translated into machine code by a program called an assemoler Assembl J -
uage is referred 10as a 10 Ilanlmage because it deals directly with the inter-
nal tructure of the CPU. To program in Assembly language, the programmer must
know all the registers of the CPU and the size of each, as well as other dctai Is.
Today, one can use many different programming languages, such as
SA IC. Pascal. C, CH. Java>rnd numerous others. These languages are called
high-level languages cause t rogJ!mmer ooes not ha e toJ>~ cgneemed with
the internal details of the CPU. hereas an assembler is used to translate an
Assembly language program into machiPc code (somcti also called object
code or opcode for operation c~e), high- evel anguages are translated int
rftiIehinecode by a program called a compil . For instance, to write a program in
, one must usc a C compiler to trans ate t e program into machine language. Now
we look at 805I Assembly language format and use an 8051 assembler to create a
ready-to-run program.
Brackets indicate that a field is optional, and not all lines have them.
Brackets should not be typed in. Regarding the above format, the following points
should be noted.
I. The label field allows the program to refer to a line of code by name. Thc label
field cannot exceed a certain number of characters. Check your assembler for
the rule.
ADD A, B
MOV A, #67
ADD and MOY are the mnemonics, which produce opcodes; and "A, B" and
"A, #67" are the operands. Instead of a mnemonic and an operand, these two
fields could contain assembler pseudo-instructions, or directives. Remember
that directives do not generate any machine code (opeode) and are used only
by the assembler, as opposed to instructions that are translated into machine
code (opcode) for the CPU to execute. In Program 2-1 the commands ORG
(origin) and END are examples of directives (some 8051 assemblers usc .ORG
and .END). Check your assembler for the rules. More of these pseudo-instruc-
tions are discussed in detail in Section 2,5.
4. Notice the label "HERE" in the label field in Program 2-1. Any label referring
to an instruction must be followed by a colon symbol, ":". In the SJMP (short
jump instruction), the 8051 is told to stay in this loop indefinitely, If your sys-
tem has a monitor program you do not need this line and it should be deleted
from your program, In the next section we will see how to create a ready-to-
run program.
Now that the basic form of an Assembly language program has been given,
the next question is: How it is created, assembled, and made ready to run? The
steps 10 create an executable Assembly language program are outlined as follows.
44
machine code. The assembler will produce an object file and a list file. The
extension for the object file is "obj' while the extension for the list file is "lst".
3. Assemblers require a third step called linliing. The liii:Kprogram taRes one or
more object files ana produces an a5soluteobject file with the extension "abs".
This ab de is used by 8051 trainers t at have a monitor program.
4. Next, the "abs" file is fed into a program called "OH" (object to hex convert-
er), which creates a file with extension "hex" that is ready to burn into ROM.
This program comes with all 8051 assemblers. Recent Windows-based assem-
blers combine steps 2 through 4 into one step.
1stfile
The 1st (list) file, which is optional, is very useful to the programmer
because it lists all the ope odes and addresses as well as errors that the assembler
detected. Many assemblers assume that the list file is not wanted unless you indi-
cate that 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 lst file that the obj file is ready to be input to the link-
er program.
In this section we examine the role of the program counter (PC) register in
executing an 8051 program. We also discuss ROM memory space for various 8051
family members.
After the program is burned into ROM of an 80S 1 family member such as
875 I or AT89S 1 or DSSOOO, the opcode and operand are placed in ROM memory
locations starting at '0000 as shown in the list below.
The list shows that address 0000 con-
tains 7D, which is the opcode for moving a Program 2-1: ROM Contents
value into register RS, and address 000 J con- Address Code
tains the operand (in this case 2SH) to be 0000 7D
moved to RS. Therefore, the instruction "MOV 0001 25
R5, #25H" has a machine code of "7D2S", 0002 7F
where 7D is the opcode and 25 is the operand. 0003 34
Similarly, the machine code "7F34" is located 0004 74
in memory locations 0002 and 0003 and rep- 0005 00
resents the opcodc and the operand for the 0006 2D
instruction "MOV R7, #34H". In the same 0007 2F
way, machine code "7400" is located in mem- 0008 24
ory locations 0004 and 0005 and represents 0009 12
the opcode and the operand for the instruction OOOA 80
"MOV A, #0".The memory location 0006 has 0008 FE
the opcode of 2D, which is the opcode for the
I. When the 8051 is powered up, the PC (program counter) has 0000 and starts
to fetch the first opcodc from location 0000 of the program ROM. In the case
of the above program the first opeode is 70, which is the code for moving an
operand to R5. Upon executing the opcode, the CPU fetches thc value 25 and
places it in R5. Now onc instruction is finished. Then the program counter is
incremented to point to 0002 (PC = 0002), which contains opcode 7F, the
opcode for the instruction "MOV R7, .. ".
2. Upon cxeeuting the ope ode 7F, the value 34H is moved into R7. Then the pro-
gram counter is incremented to 0004.
3. ROM location 0004 has the opeodc for thc instruction "MOV A, #0". This
instruction is executed and now PC = 0006. Notice that all the above instruc-
tions arc 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 l-byte instruction. After the execution of this instruction, PC = 0007.
5. The location 0007 has the opeode 2F, which belongs to the instruction "ADD
A, R7". This also is a l-bytc instruClion. Upon execution of this instruction
PC is incremented to 0008. This process goes on until all the instructions are
fetched. and executed. The fact that the program counter points at the next
msrrucnon to be executed explains why some microprocessors (notably the
x86) call the program counter the ins/ruction pointer.
. As we saw in the last chapter, some family members have only 4K bytes
of on-chip ROM (e.g., 8751, AT895 J) and some, such as the AT89C52 have 8K
bytes of ROM. Dallas Semiconductor's DSSOOO-32 h 32K b ' .
ROM . 0 a llas Semi -
as emlconduetor also has an 8051 with 6'4K bas ytcs of . on-chIp
Th·· I f '1 ytes of on-chip ROM .
e pomt to remember IS that no member of the 8051
64K bytes of opcode since the program counter' ami y can access more than
(0000 to FFFF address range). It must be noted th~tn:he 8051 IS a 16-~lt register
gram ROM inside the 8051 has the address of 0000 hile the first location of pro-
ferent depending on the size of the ROM h ' the last locatior, can be dif-
members, the 875 J and AT895 J have 4K b on t fe chiP: Among the 8051 family
0
ROM memory has memory addresses of06~~St O~~ChIP ROM. This 4K bytes of
lion of on-chip ROM of this 8051 h 0 FH. Thereforc, the first loca-
the address ofOFFFH. Look at E as tc ;ddress 01'0000 and the last location has
xarnp e -I to see how this is computed.
48
Example 2-1
Find the ROM memory address of each of the following 8051 chips.
(a) AT89C51 with 4KB (b) DS89C420 with 16KB (c) DS5000-32 with 32KB
Solution:
(a) With 4K bytes of on-chip ROM memory space, we have 4096 bytes' (4 x 1024 =
4096). This maps to address locations of 0000 to OFFFH. Notice that 0 is always
the first location. (b) With 16K bytes of on-chip ROM memory space, we have
16,384 bytes (16 x 1024 = 16,384), which gives 0000 - 3FFFH. (c) With 32K bytes
we have 32,768 bytes (32 x 1024 = 32,768). Converting 32,768 to hex, we get
8000H; therefore, the memory space is 0000 to 7FFFH.
0000
.. byte
..
0000
.. byte
. ,.
byte
..
0000
8051
AT89C51 3FFF
DS89C420/30
7FFF
'------'
DS5000-32
In this section we look at some widely used data types and directives sup-
ported by the 8051 assembler.
DB (define byte)
The DB directive is the most widely used data directive in the assembler.
It is used to define the 8-bit data. When DB is used to define data, the numbers can
be in decimal, binary, hex, or ASCII formats. For decimal, the "D" after the deci-
mal number is optional, but using "B" (binary) and "H" (hexadecimal) for the oth-
ers is required. Regardless of which is used, the assembler will convert the num-
bers into hex. To indicate ASCII, simply place the characters in quotation marks
('like this'). The assembler will assign the ASCII code for the numbers or charac-
ters automatically. The DB directive is the only directive that can be used to define
ASCII strings larger than two characters; therefore, it should be used for all ASCII
data definitions. Following are some DB examples:
ORG 500H
DATAl: DB 28 ;DECIMAL(lC in hex)
DATA2: DB 00110101B ;BINARY (35 in hex)
DATA3: DB 39H ;HEX
ORG 510H
DATA4: DB 11259111 ;ASCII NUMBERS
ORG 518H
DATA6: DB "My name is Joel! ;ASCII CHARACTERS
Either
C'
single or double
.
quotes can be used around ASCII strings . Thi1 scan
b e use ful tor stnngs, which contain a single quote such as "O'Leary". DB is also
used to allocate memory in byte-sized chunks.
Assembler directives
The following arc some more widely used directives of the 8051.
ORG (origin)
This . is used
. to define a constant WIithout oec .
TI ic EQ U directive does not set aside stora e uPY1l1ga memory location.
stant value with a data label so that h g for a data item but associates a con-
. W cn the label a .
I
Slant va ue will be substituted for the label ' ppears In the program, its can-
er constant and then the consta t" . The follOWing uses EQU for the
n ISused to load the R3 . count-
register.
o
COUNT EQU 25
MOV R3,#COUNT
_When executing the instruction "MOV R3, #COUNT", the register R3 will
be loaded with the value 25 (notice the # sign). What is the advantage of using
EQU? Assume that there is a constant (a fixed value) used in many different places
in the program, and the programmer wants to change 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 entire program trying to find every occur-
rence.
END directive
Review Questions
I. The directive is always used for ASCII strings.
2. How many bytes are used by the following?
DATA 1: DB "AMERICA"
3. What ~ the advantage in using the EQU directive to define a constant value?
4. How many bytes are set aside by each of the following directives?
(a) ABC DATA: DB "1234" (b) MY_DATA: DB "ABC1234"
5. State the contents of memory locations 200H - 205H for the following:
ORG 200H
MYDATA: DB "ABC123"
Like any other microprocessor, the 8051 has a flag register to indicate
arithmetic conditions such as the carry bit. The flag register in the 8051 is called
the program status word (PSW) register. In this section we discuss various bits of
this register and provide some examples of how it is altered.
This flag is set whenever there is a carry out from thb D7 bit. This flag bit
is affected after an 8-bit addition or subtraction. It can also be set to 1 or 0 direct-
ly by an instruction such as "SETB C" and "CLR . C" where "SETB C" stands for
"set bit carry" and "CLR C" for "clear carry". More about these and other bit-
addressable instructions will be given in Chapter 8.
A C, the auxiliary carry flag
This flag is set whenever the result of a signed number operation is too
large, causing tbe high-order bit to overflow into the sign bit. In general, the carry
flag is used to detect errors in unsigned arithmetic operations. The overflow flag
is only used to detect errors in signed arithmetic operations and is discussed in
detail in Chapter 6.
Solution:
38 00111000
+ 2F 00101111
67 0110011 I
Show the status of the CY, AC, and P flags after the addition of9CH and 64H in the fol-
lowing instructions.
MOV A,#9CH
ADD A,#64H ;after addition A=OO and
CY=l
Solution:
9C 1001 I 100
+ 64 01100100
100 00000000
Show
lowmgthe status of the CY, AC, and P flags after the addition of 88H and 93H in the II0 1-
mstruetlons.
MOV A,#88H
ADD A,#93H
;after the
addition A=lBH,CY=l
Solution:
88 10001000
+ 93 100100] I
liB
00011011
The 8051 microcontroller has a total of 128 bytes of RAM. In this section
we discuss the allocation of these 128 bytes of RAM and examine their usage as
registers and stack.
_ As we can see from Figure 2-5, bank J uses the same RAM space as the
stack.
. This IS a major problem m programming the 8051 W
. c must.' ert h er not use
register bank I, or allocate another area of RAM for the stack. This will b dis-
cussed below. I e IS
Example 2-5
Solution:
This is called direct addressing mode and uses the RAM address location for the desti-
nation address. See Chapter 5 for a more detailed discussion of addressing modes.
Solution:
By default, PSW.3=O and PSw'4=O; therefore, the instruction "SETB PSW,4" sets
RS 1= I and RSO=O, thereby selecting register bank 2. Register bank 2 uses RAM loca-
tions IOH - 17H. After the execution of the above program we have the following:
RAM location IOH has value 99H RAM location J JH has value 85H
RAM location 12H has value 3FH RAM location 17H has value 63H
'RAM location ISH has value J2H
Show the stack and stack pointer for the following. Assume the default stack area and
register 0 is selected.
MOV R6,#25H
MOV Rl,#12H
MOV R4,#OF3H
PUSH 6
PUSH 1
PUSH 4
Solution: After PUSH 6 After PUSH I
After PUSH 4
OB
OB OB OB
OA
OA OA OA F3
09
09 09 12
09 12
08
08 25 08 25
08 25
Start SP: 07 Sp: 08
SP - 09
SP OA
S8
Popping from the stack
Popping the contents of the stack back into a given register is the opposite
process
. of. pushing . With every pop, t he top byte of the stack IS
. copied
. to the reg-
ister specified by the instruction and the stack pointer is decremented once.
Example 2-9 demonstrates the POP instruction. .
Example 2-9
Examining the stack, show the contents of the registers and SP after execution of the
following mstrucnons, All values are in hex.
Solution:
OA F9 OA F9 OA OA
09 76 09 76 09 76 09
08 6C 08 6C 08 6C 08 6C
Solution:
Recall (rom our earlier discussion that the stack pointer register points to
the current RAM location available for the stack. As data is pushed onto the stack,
SP is incremented. Conversely, it is decremented as data is popped 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 instructions, we
would be using RAM locations 7, 6, 5, ctc., which belong to R7 to RO of bank 0,
the default register bank. This incrementing of the stack pointer for push instruc-
tions also ensures that the stack will not reach location 0 at the bottom of RAM,
and consequently run out of space for the stack. However, there is a problem with
the default setting of the slack. Since SP = 07 When the 8051 is powered up, the
first location of the stack is RAM location 08, which also belongs to register RO
or register bank I. In other words, registcr bank 1 and the stack are using the same
mcmory space. If in a given program we need to usc register banks I and 2, we
can reallocatc another section of RAM to the slack. For cxample, we can allocate
RA M locations 60H and higher to the stack as Shown in Example 2-10.
60
Viewing registers and memory with a simulator
Many assemblers and C compilers come with a simulator. Simulators
allow us to view the contents of registers and memory after executing each instruc-
tion (single-stepping). We strongly recommend that you use a simulator to single-
step some of the programs in this chapter and future chapters. Single-stepping a
program with a simulator gives us a deeper understanding of microcontroller
architecture, in addition to the fact that we can use it to find errors in our programs.
Figures 2-7 through 2-10 show screen-shots for 8051 simulators from Proview 32
and Keil. See www.MicroDigitalEd.com for tutorials on how to use the simula-
tors.
IB roo R4 00
C 0 R5 00
lEA ro- R6 00
IE roo R7 00
Re!)isle, Volue
-. Regs
10 0.00
,1 0.00
12 0.00
13 0.00
14 0.00
,5 0.00
,6 0.00
17 0.00
- Sys
a 0.00
b 0.00
sp 0.07
sp_max 0.07
dpl, 0.0000
PC $ C:O:<OOOO
states 0
sec 000000000
" psw 0,00
GllU.fIltmffli.l
C:OxOOOO
C:OxOOlO 0000000000000000. 0000000000000000 '" ' ~
c. Ox0020 00 00 00 00 00 00 00 00 • 00 00 00 00 00 00 00 00 ......•.•...
C:Ox0030 00 00 00 00 00 00 00 00 . 00 00 00 00 00 00 00 00 ........•••....
c. 0](00400000000000000000.0000000000000000 ....•.
C:OX0050 00 00 00 00 00 00 00 00 . 00 00 00 00 00 00 00 00 ............•...
c. Ox0060 00 00 00 00 00 00 00 00 • 00 00 00 00 00 00 00 00 ....•.•......•..
C:Ox0070 00 00 00 00 00 00 00 00 . 00 00 00 00 00 00 00 00 ..
00 00 00 00 00 00 00 00 . 00 00 00 00 00 00 00 00 .......••.......
>0 OOh. 7Fh
DEFINE OIR D1Splay
(.!..l!JlU\~C;~ .....~-,. - ....
SUMMARY
This chapter began with an exploration of the major registers of the 8051,
including A, S, RO, RI, R2, R3, R4, R5, R6, R7, DPTR, and PC. The use of these
registers was demonstrated in the 'context of programming examples. The process
of creating an Assembly language program was described from writing the source
file, to assembling it, linking, and executing the program. The PC (program count-
er) register always points to the next instruction to be executed. The way the 805 I
uses program ROM space was explored because 8051 Assembly language pro-
grammers must be aware of where programs are placed in ROM, and how much
memory is avai lable.
An Assembly language program is composed of a series of statements that
are either instructions or pseudo-instructions, also called directives, Instructions
are translated by the assembler into machine code. Pseudo-instructions are not
translated into machine code: They direct the assembler in how to translate instruc-
tions into machine code. Some pseudo-instructions, called data directives, are used
to define data. Data is allocated in byte-size increments. The data can be in bina-
ry, hex, decimal, or ASCII formats.
Flags are useful to programmers since they indicate certain conditions,
such as carry or overflow, that result from execution of instructions. The stack is
used to store data temporarily during execution of a program. The stack resides in
the RAM space of the 8051, which was diagrammed and explained. Manipulation
of tbe stack via POP and PUSH instructions was also explored.
I .
Most registers . tear
In h 8051 e __ ._ bits
. wide.
. Registers RO - R7 arc all __ bits wide
2. Registers ACC and Bare __ bits wide.
; Name a l6-b; t register in the S05 I. .. (necessary,
. To load R4 with the value 65H, the pound slg~ IS _
SECTION
AND 22: INTRODUCTION TO 8051 ASSEMBLY PROGRAMMING
21. Every 8051 family member wakes up at address __ when it is powered up.
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, #55H (b) MOV R3, #3 (c) INC R2
(d) ADD A, #0 (e) MOV A, R1 (I) MOV R3, A
(g) ADD A, R2
24. Pick up a program listing of your choice, and show the ROM memory address-
es and their contents.
25. Find the address of the last location of on-chip ROM for each of the following.
1i1"'. (a) DS5000-16 (b) 085000-8 (c) OS5000-32-1I=-f
(d) AT89C52 (e) 8751 (I) AT89C51-l.\.~
(g) DS5000-64· oFI1-
26. Show the lowest and highest values (in hex) that the 8051 program counter
can take.
27. A given 805 J has 7FFFH as the address of its last location of on-chip ROM.
What is the size of on-chip ROM for this 8051?
28. Repeat Question 27 for 3FFH.
29. Compile and statc the contents of each ROM location for the following data.
<,
ORG 200B r- ~
I " "'ll.-I.."'\ .. r:
MYDAT_1: DB "Eartf':'.-~ W--
MYDAT_2: DB "987-65" -~~\V
MYDAT_3: DB "GABEH 98" 2:9
30. Compile and state the contents of each ROM location for the following data.
ORG 340H
DAT 1: DB 22,56H,10011001B,32,OF6H,11111011B
39. Which bits of the PSW are responsible for selection of the register banks?
40. On power-up, what is the location of the first stack?
41. In the 8051, which register bank conflicts with the stack?
42. In the 8051, what is the size of the stack pointer (SP) register?
43. On power-up, whieh of the register banks is used?
44. Give the address locations of RAM assigned to various banks.
45. Assuming the use of bank 0, find at what RAM location each of the following
Jines stored the data.
(a) MOV R4,#32H (b)MOV RO,#12H
(e)MOV R7,#3FH (d)MOV R5,#55H
46. Repeal Problem 45 for bank 2.
47. After power-up, show how to select bank 2 with a single instruction.
48. Show the stack and stack pointer for each line of the following program
ORG
MOV RO,#66H
° .
MOV R3,#7FH
MOV R7,#SDH
PUSH 0
PUSH 3
PUSH 7
CLR A
MOV R3,A
MOV R7,A
POP 3
POP 7
POP °
49. In Problem 48, does the sequence of POP instru .
ues of registers RO, R3, and R7? If not h ctrons restore the original val-
nons ,s ow the correct sequence of instruc.
50. Show the staek and stack pointer for each line of the foil .
ORG 0 oWlllg program.
MOV SP,#70H
MOV RS,#66H
~10V R2,#7FH
MOV R7,#SDH
PUSH 5
PUSH 2
PUSH 7
CLR A
MOV R2,A
MOV R7,A
POP 7
POP 2
POP 5
CHAP
ANSWERS TO REVIEW QUESTIONS
I. MOY A,#34H
MOY B,#3FH
ADDA,B
2. MOY A,#16H
ADDA,#OCDH
MOYR2,A
3. False
4. FF hex and 255 in decimal
5. 8
I. The real work is performed by instructions such as MOY and ADD. Pseudo-instructions, also
called assembler directives, instruct the assembler in doing its job.
2. The instruction mnemonics, pseudo-instructions
3. False
4. All except (c)
5. Assembler directive
6. True
7. (c)
I. True
2. True
3. (a)
4. (b) and (d)
5. (d)
SECTION 2.4: THE PROGRAM COUNTER AND ROM SPACE IN THE 8051
I. 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 IFFFH.
I. DB
2. 7
3. If the value is to be changed later, it can be done once in one place instead of at every occur-
rence.
4. (a) 4 bytes (b) 7 bytes
5. This places the ASCII values for each character in memory local ions starting at 200H. Notice
that all values are in hex.
200 = (41)
201 = (42)
202 = (43)
203 = (31)
204 = (32)
205 = (33)
5.
Hex binary
C2 1100 0010
+ 1Q +.QQll 1101
FF 1111 1111
This leads to CY = a and AC = O.
I. 8-bit
2. Incremented
3. Decremented
4. 08
5. 0
6. 0-7
7. Register bank 3
8. RAM locations 18H to I FH
68
I
OBJECTIVES
69
In the sequence of instructions to be executed, it is often neee sary [0 trans-
fer program control to a different location. There arc many instruction in the 8051
to achieve this. This chapter covers the control transfer instructions available in
8051 Assembly language. In the first section we discuss instructions used for loop-
ing, as well as instructions for conditional and unconditional jumps. ln the second
section wc examine CALL instructions and their uses. ln the third section, time
delay subroutines are described for both the traditional 8051 and its newer gener-
ation.
In this section we first discuss how to perform a looping action in the 8051
and then talk about j limp instructions, bothconditional and unconditional.
Looping in the 8051
Solution:
;This program dd
a s value 3 to the ACe ten times
Mav A,#O
Mav R2,#10 ;A~O, clear ACe
AGAIN: ADD A.#03 ;load COunter R2~lO
DJNZ R2,AGAIN ;add 03 to ACe
MaV RS,A ;repeat until R2~O(lO
•. Sa ve A in RS times)
What is the maximum number of times that the loop in Example 3-1 can be repeated?
Solution:
Since R2 holds the count and R2 is an 8-bit register, it can hold a maximum of FFH
(255 decimal); therefore, the loop can be repeated a maximum of 256 times.
Example 3-3
Write a program to (a) load the accumulator with the value 55H, and (b) complement
the ACC 700 times.
Solution:
Since 700 is larger than 255 (the maximum capacity of any register), we use two regis-
ters to hold the count. The following code shows how to use R2 and R3 for the count.
Ol..<.-D
MOV A,#55H ;A=55H
MOV R3,#10 ;R3=10, the outer loop count
NEXT: MOV R2,#70 ;R2=70, the inner loop count
AGAIN: CPL A ;complement A register
DJNZ R2,AGAIN ;repeat it 70 times (inner loop)
DJNZ R3,NEXT
b'10\)
In this program, R2 is used to keep the inner loop count. In the instruction "DJNZ
R2 ,AGAIN", whenever R2 becomes 0 it falls through and "DJNZ R3, NEXT" is exe-
cuted. This instruction forces the CPU to load R2 with the count 70 and the inner loop
starts again. This process will continue until R3 becomes zero and the outer loop is fin-
ished.
Write a program to determine if R5 contains the value O. If so, put 55H in it.
Solution:
MOV A,RS ;eopy RS to A
JNz NEXT
MOV ;jump if A is not zero
R5,#SSH
NEXT:
72
--- Example 3-5
Find the sum of the values 79H, FSH, and E2H. Put the sum in registers RO (low byte)
and RS (high byte).
Solution:
Example 3-6 .
Using the following Jist file, verify t e Jump
. he i forward address calculatIon.
Line PC Opcode
01 0000 Mnemonic Operand
02 0000 7800
ORG 0000
03 0002 7455 MOY RO, #0
04 0004 6003 MOY A, #55H
as 0006 08 JZ NEXT
06 OOQ] _ 04 INC RO
07 0008- AGA~ INC A
08 ~
-0009 2477 INC A
Q2 OOOB NEXT: ADD A, #77h
5005
10 OOOD JNC OYER
E4
11 OOOE CLR A
F8
12 OOOF MOY RO,A
F9
13· 0010 FA May Rl,A
14 0011 MOy R2,A
FB
15 0012 MaY R3,A
2B OVER:
16 0013 50F2 ADD A,R3
17 0015
18
80FE
HERE: JNc AGAIN
0017 SJMP HERE
END
Solution:
First notice that the J2 and INC instructions both jump forward. The target address for
a forward jump is calculated by adding the PC of the follOWing instruction to the sec-
ond byte of the short jump instruction, which is called the relative address. In line 4 the
instruction "JZ NEXT" has opeode of 60 and operand of 03 at the addresses of 0004
and 0005. The 03 is the relative address, relative to the address of the next instruction
INC RO, which is 0006. By adding 0006 to 3, the target address of the label NEXT,
which is 0009, is generated. In the same way for line 9, the "JNC OVER" instruction
has 0pcode and operand of 50 and 05 Where 50 is the 0pcode and 05 the relative address.
address
Therefore,
of label
05 is OVER.
added to 0000, the address of instruction "CLR A", giving 12H, the
Example 3-7
Solution:
In that program list, "JNC AGAIN" has opcode 50 and relative address F2H. When the
relative address of F2H is added to ISH, the address of the instruction below the jump,
we have 15H + F2H = 07 (the carry is dropped). Notice that 07 is the address of label
AGAIN. Look also at "SJMP HERE",which has 80 and FE for the opcode and rela-
tive address, respectively. The PC of the following instruction, OOI7H, is added to FEH,
the relative address, to get 0015H, address of the HERE label (l7H + FEH = 15H).
Notice that FEH is -2 and 17H + (-2) = 15H. For further discussion of the addition of
negative numbers, see Chapter 6.
Review Questions
I. The mnemonic DJNZ stands for
---
2. True or false. "DJNZ R5, BACK" combines a decrement and a jump in a sin-
gle instruction.
3. "JNC HERE" is a -byte instruction.
4. In "JZ NEXT"" which register's content is checked to see if it is zero?
5. LlMP is a -3 -byte instruction.
Solution:.
ORG o
BACK: MOV A, #55H ;load A with 55H
MOV Pl,A ;send 55H to port 1
LCALL DELAY ;time delay
MOV A,#OAAH ;load A with AA (in hex)
MOV Pl,A ;send AAH to port 1
LCALL DELAY
SJMP BACK 'keep do i hi
---this is the delaY'SUbrou~t~~ t 1S 1ndefinitely
ORG 300H ;put time d 1
DELAY: MOV R5,#OFFH 'R5 _ 255 e ~y at address 300H
AGAIN: DJNZ R5,AGAIN ;sta~ her~FF tlnlhex),the counter
RET . un 1 R5 becomes 0
END :return to caller (when R5 = 0)
,end of asm file
The amount of time delay 111 Exarnpl 3 8 d
80S I. How to calculate the exact time 'Ileb' epends on the frequency of the
e explall1ed
H owever you can increase the time deja WIbv usi d '1'
111 etai 111 Chapter 4.
y y usmg a nested loop as shown bel
D~M: ~
;nested loop delay
MOV R4,#255
NEXT: ;R4 = 255(FF
MOV RS,#25S in hex)
AGAIN: ;RS = 2SS(FF
DJNZ R5,AGAIN in hex)
;stay here until
DJNZ R4,NEXT R5 becomes 0
;decrement R4
;keep loading
RET RS until R4
;return (when R4 = 0
= 0)
76
-c
CALL instruction and the role of the stack
. The stack and stack pointer were covered in the last chapter. To understand
the Importance of the stack in microcontrollers, we now examine the con tenis of
the stack and stack pointer for Example 3-8. This is shown in Example 3-9.
Example 3-9
Analyze the stack contents after the execution of the first LCALL in the following.
Solution:
Calling subroutines
In Assembly language programming it is common to have one main pro-
gram 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 modules can be assigned to different programmers in order to
shorten development time.
01 0000 ORG 0
02 0000 "'1455BACK: MOV A,#55H ;load A with 55H
#-
03 0002 F590 MOV P1,A ;send 55H to port 1
..
04 0~04 7C99
05 0006 7D67
MOV R4,#99H
MOV R5,#67H
06 0d'08 120300 LCALL DELAY ;time delay
~
07 OOOB 74M MOV A,#OAAH ;load A with AA
08 O~OD F590 MOV P1,A ;send AAH to port 1
09 O~OF 120300 LCALL DELAY
10 0~12 80EC SJMP BACK ;keep doing this
11 0014 -------this is the delay subroutine
12 0300 ORG 300H
13 0300 C004 DELAY: PUSH 4 ;PUSH R4
14 0302 COOS PUSH 5 ;PUSH RS
15 0304 7CFF MOV R4,#OFFH ;R4=FFH
16 0306 7DFF NEXT: MOV R5,#OFFH ;R5=255
17 0308 DDFE AGAIN: DJNZ R5,AGAIN
18 030A DCFA DJNZ R4,NEXT
19 030C D005 POP 5 ;POP into R5
20 030E D004 POP 4 ;POP into R4
21 0310 22 RET ;return to caller
22 0311 END r end of asm file
Solution:
First notice that for the PUSH and POP instructions we must specify the direct address
of the register being pushed or popped. Here is the stack frame.
Example 3-11
A developer is using the Armel AT89CI051 microcontroller chip for a product. This
chip has only IK byte of on-chip flash ROM. Which instruction, LCALL or ACALL, is
more useful in programming this chip?
Solution:
The ACALL instruction is more useful since it is a 2-byte instruction. It saves one byte
each time the call instruction is used.
Example 3-12
Rewrite Example 3-8 as efficiently as you can.
Solution:
ORG 0
MOV A,#55H ;load A with 55H
BACK: MOV Pl,A ;issue value in reg A to port
ACALL 1
DELAY ;time delay
CPL A ;complement reg A
SJMP BACK ;keep doing this indefinitely
-------this is the delay subroutine
DELAY:
MOV
AGAIN: DJNZ R5,#OFFH ;R5=255(FF in hex), the counter
RET
R5,AGAIN ;stay here until R5 becomes 0
;return to caller
END ;end of asm file
Notice in this program that register A is set to 55H. By complementing 55H, we have
AAH; and by complementing AAH we have 55H. Why? "0101OIOJ" in binary (55H)
becomes "10 I 0 I0 I0" in binary (AAH) when it is complemented; and "1010 1010"
becomes "0) 0 I0 101" if it is complemented.
Review Questions
Example 3-13
The following shows crystal frequency for three different 8051-based systems. Find the
period of the machine cycle in each case.
(a) 11.0592 MHz (b) 16 MHz (c) 20 MHz
Solution:
(a) 11.0592 MHz/12 = 921.6 kHz; machine cycle is 11921.6 kHz = 1.085 us (microsec-
ond)
(b) 16 MHz/12 = 1.333 MHz; machine cycle (MC) = 111.333 MHz = ().75 us
(c) 20 MHz/I2 = 1.66 MHz; MC = 1/1.66 MHz = 0.60 us
Example 3-14 '
For an 8051 system of 11.0592 MHz, find how long it takes to execute each of the fol-
lowing instructions.
(a) MOV R3, #55 (b) DEC R3 (c) DJNZ R2, target
(d) LJMP (e) SJMP (I) NOP (no operation)
(g) MUL AB
Solution:
The machine cycle for a system of 11.0592 MHz is 1.085 us as shown in Example 3-
13. Table A-I in Appendix A shows machine cycles for each of the above mstructions.
Therefore, we have:
Solution:
From Table A-I in Appendix A, we have the following machine cycles for each instruc-
tion of the DELAY subroutine.
Machine Cycle
DELAY: MOV R3,#200 1
HERE: DJNZ R3,HERE 2
RET
2
Very often we calculate the time dclay based on the instructions inside the
loop and ignore the clock cycles associated with the instructions outside the loop.
In Example 3-15, the largest value the R3 register can take is 255; there-
fore, one way to increase the delay is to usc NOP instructions in the loop. NOP,
which
3-16. stands for "no operation," simply wastes time. This is shown in Example
82
Example 3-16
For an 8051 system of 11.0592 MH z, find th e time
. delay for the followmg
.. subroutme:
Machine Cycle
DELAY: MOV R3,#250 1
HERE: NOP 1
NOP 1
NOP 1
NOP 1
DJNZ R3,HERE 2
RET 2
Solution:
The time delay inside the HERE loop is [250( I + 1 + I + I + 2)] x 1.085 /1S= 1500 x
1.085 /1S= 1627.5 I1S.Adding the two instructions outside the loop we have 1627.5 /1S+
3 x 1.08511s = 1630.755I1S.
If machine cycle timing is critical to your system design, make sure that you check the
manufacture's data 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 a machine cycle of 1.085 I1S,find the time delay in the following subroutine.
Example 3-18
www.maxim·ic.com
www.MicroDigitaIEd.com
Example 3-19
For an AT8051 and D889C420/30/40/50 system of 11.0592 MHz, find how long it takes
to execute eaeh of the following instructions.
(a) MOV R3, #55 (b) DEC R3 (c) DJNZ R2, target
(d) LJMP (e) SJMP (f) NOP (no operation)
(g) MUL AB
Solution:
The machine cycle time for theAT8951 and DS89C420/30 was shown in Example 3-18.
Table 3-3 shows machine cycles for each of the above instructions. Therefore, we have:
HERE: NOP 1
NOP 1
NOP 1
NOP 1
DJNZ R3,HERE 4
RET
Solution:
The time delay inside the HERE loop is [250( I + I + 1 + I + 4)] x 90 ns = 2000 x 90 ns
= J 80 us, Comparing this with Example 3-16, we see DS89C4xO is about 9 times faster.
(1627 us I 180 ps = 9)
Example 3-21
Write a program to toggle all the bits of PI every 200 ms. Assume that the crystal fre-
quency is 11.0592 MHz, and that the system is using the AT89C51.
Solution:
;Tested for AT89C51 of 11.0592 MHz.
MOV A,#55H
AGAIN: MOV P1,A
ACALL DELAY
CPL A
SJMP AGAIN
;----Time delay
DELAY: MOV R5,#2
HERE1: MOV R4,#180
HERE2: MOV R3,#255
HERE3: DJNZ R3,HERE3
DJNZ R4,HERE2
DJNZ R5,HERE1
RET
86
Example 3-22
Write a program to toggle all the bits of P I every 200 ms. Assume crystal frequenc is
11.0592 MHz and the system is using DS89C420/30/40/50. y
Solution:
;----Time delay
DELAY 200m:
MOV R5,#9
HEREl: MOV R4, #242
HERE2: MOV R3,#255
HERE3 : DJNZ R3,HERE3
DJNZ R4,HERE2
DJNZ R5,HEREI
RET
Use an oscilloscope to measure the system square wave period to verify delay.
From the above discussion we conclude that use of the instruction in gen-
erating time delay is not the most reliable method. To get more accurate time
delay we use timers as described in Chapter 9. Meanwhile, to get an accurate time
delay for a given 8051 microcontroller, we must use an oscilloscope to measure
the exact time delay.
See the following Web sites for 8051 products and their
features from various companies:
www.8052.com
www.MicroDigitaIEd.com
87
CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS
SJMP to itself using $ sign . d t short jump to itself
. ograrn we nee 0 h
here there is no monitor pr., f doing that is to use t e
. order Intocases
keep w.
the rrucrocontro IIer busy. A simple way 0
I$n.
sign. That means in plaee of this
SJMP $
Review
I.
Questions clesof the '0".
True or false. In the 8051, the machine cycle lasts 12 clock cy
2.
~~:r~;~~~~~ number of machine cycles needed to execute an 8051 instruc-
3. For
tion Question
IS _. 2, what IS
. t h e rnaximu
. m number of cycles needed, and for which
instructions? f 12 MH
. hi c1e for a crystal frcquency 0 z. .
4. Find the mac me cy f 12 MHz find the time delay associated with
5. Assuming a crystal frequency 0 DE1LAy'Subroutine
the loop section of the followmg .
DELAY: MaV R3,#lOO
HERE: Nap
Nap
Nap
DJNZ R3,HERE
RET
6.
True or false. In the DS89C420/30, thc machine cycle lasts 12 clock cycles of
the crystal frequency.
SUMMARY
88
CHAPT
PROBLEMS
27. Find the system frequency if the machine cycle = 1.2 ~s.t{)Mrlt.
~Find the machine cycle if the crystal frequency is 18 MHz.
29. Find the machine cycle if the crystal frequency is 12 MHz.
JD. Find the machine cycle if the crystal frequency is 25 MHz.
31. True or false. LJMP and SJMP instructions take the same amount of time to
execute even though one is a 3-byte instruction and the other is a 2.byte
instruction.
32. Find the time delay for the
delay subroutine shown to
DELAY:
HERE:
MOV
NOP
R3,#150.] ';i-,
the right, if the system has
an 8051 with frequency of
NOP
NOP
."
., r
• ;;t. ~
,
"-
11.0592 MHz. DJNZ R3,HERE
RET
~
33. Find the time delay for the
delay subroutine shown to DELAY: MOV R3,#200
the right, if the system has HERE: NOP
an 805 J with frequency of NOP
16 MHz. NOP
DJNZ R3,HERE
RET
G
16 MHz. NOP I
NOp
I
JNZ R3,HERE II
JNZ R2,AGAIN l{-
RET
90
CHAP'
38. Repeat proplem 34 for DS89C420/30.
;J.9~Repeat problem 35 for DS89C420/30.
40. In an AT89C51-based system, explain performance improvement if we replace
the AT89C51 chip with a DS89C420/30. Is it 12 times faster?
I. True
2. 1
3. MUL and DIY each lake 4 machine cycles.
4. 12 MHz /12 = I MHz, and MC = 1/1 MHz = 1 us,
5. [100(1 + I + I + 2)] x J us = 500 us = 0.5 milliseconds.
6. False. 11takes 1 clock.
7. 11.0592 MHz/I = 11.0592 MHz; machine cycle is 1/11.0592 MHz = 0.0904 us = 9004 ns
91
CHAPTER 3: JUMP, LO()P, AND CALL INSTRUCTIONS
92
CHAPTER 4
I/O PORT
PROGRAMMING
OBJECTIVES
93
This chapter describes the I/O port programming of the 8051 with many
examples. In Section 4.t, we describe I/O access using byte-size data, and in
Section 4.2, bit manipulation of the IIO ports is discussed in detail.
In the 8051 there are a total of four ports for 1/0 operations. Examining
Figure 4-1, note that of the 40 pins, a total of 32 pins are set aside for the four ports
PO, P J, P2, and P3, where each port takes 8 pins. The rest of the pins arc desig-
nated as Vrco GND, XTALI, XTAL2, RST, EA, ALE/PROG and PSEN are dis-
cussed in Chapter 8.
PDIP/Cerdip
Pl.0 1 40 Vee
Pl.1 2 39 POO (ADO)
Pl.2 3 38 POl (AD1)
Pl.3 4 37
P1A
8051 P02 (AD2)
5 36 PO.3 (AD3)
P1.5 6
(8031 )
35 POA (AD4)
Pl.6 7 (89420) 34 P05 (ADS)
Pl.7 8 33 P06 (AD6)
RST 9 32 PO.7 (AD7)
(RXD) P3.0 10 31 ENVPP
(TXD) P3.1 11 30 ALEfPROG
(INTO) P3.2 12 29 PSEN
(INT1) P3.3 13 28 P2.7 (A15)
(TO) P3A 14 27 P2.6 (A14)
(T1) P3.5 15
26 P25 (A13)
(WR) P3.6 16
25 P2A (A12)
(RD) P3.7 17
24 P2.3 (Al1)
XTAL2 18
23 P2.2 (Al0)
XTALl 19
22 P2.1 (A9)
GND 20
21 P20 (A8)
94
Port 0
Vec
Port 0 occupies a 10 K
;Toggle all bi ts of PO
BACK: MOV A,#55H
MOV PO,A
ACALL DELAY
MOV A,#OAAH
MOV PO,A
ACALL DELAY
SJMP BACK
lt must be noted that complementing 55H (01010101) turns it into AAH
(10 1a 1a I0). By sending 55H and AAH to a given port continuously, we toggle all
the bits of that port.
Port 0 as input
95
CHAPTER 4: I/O PORT PROGRAMMING
Dual role of port 0
As shown in Figure 4-1, port 0 is also designated as ADO - AD7, allowing
it to be used for both address and data. When connecting an 8051/31 to an exter-
nal memory. port 0 provides both address and data. The 8051 multiplexes address
and data through port 0 to save pins. We discuss that in Chapter 14.
Port 1
Port I occupies a total of 8 pins (pins I through 8). It can be used as input
or output. In contrast to port 0, this port does not need any pull-up resistors since
it already has pull-up resistors internally. Upon reset, port I is configured as an
input port. The following code will continuously send out to port I the alternating
values 55H and AAH.
;Toggle all bits of PI continuously
MOV A,#55H
BACK: MOV Pl,A
ACALL DELAY
CPL A ;complement (Invert) reg. A
SJMP BACK
Port 1 as input
. .1f port I has been configured as an output port, to make it an input port
agam, It must programmed as such by writing I to all its bits. The reason for this
is discussed in Appendix C.2. In the following code, port I is configured first as
an input port by wntmg Is to it, then data is received from that port and saved in
R7, R6, and R5.
CHAPT
MOV A,#55H
BACK: MOV P2,A
ACALL DELAY
CPL A ;complement reg. A
SJMP BACK
Port 2 as input
. To make port 2 an input, it must programmed as such by writing I to all its
bits. In the following code, port 2 is configured first as an input port by writing Is
to It. Then data IS received from thai port and is sent to PI continuously.
97
TER 4: I/O PORT PROGRAMMING
•
P3.0 and P3.1 are used for the RxD and TxD serial communications sig-
nals. See Chapter 10 to see how they are connected. Bits P3.2 and P3.3 are set
aside for external interrupts, and are discussed in Chapter II. Bits P3.4 and P3.5
are used for timers 0 and I, and are discussed in Chapter 9 where timers are dis-
cussed. Finally, P3.6 and P3.7 are used to provide the WR and RD signals of
external memories connected in 803 I-based systems. Chapter 14 discusses how
they arc used in 803 I-based systems, In systems based on the 8751, 89C51, or
DS89C4xO, pins 3.6 and 3.7 are used for I/O while the rest of the pins in port 3 are
normally used in the alternate function role,
Example 4-1
Write a test program for the DS89C420/30 chip to toggle all the bits of PO, PI, and P2
every 1/4 of a seeond. Assume a crystal frequency of 11.0592 MHz.
Solution:
98
Different ways of accessing the entire 8 bits
In the following code, as in many previous I/O examples, the entire 8 bits
of port 1 are accessed.
BACK: MOV A,#55H
MOV Pl,A
ACALL DELAY
MOV A,#OAAH
MOV Pl,A
ACALL DELAY
SJMP BACK
The above code toggles every bit of PI continuously. We have seen a vari-
ation of the above program before. Now we can rewrite the above code in a more
efficient manner by accessing the port directly without going through the accumu-
lator. This is shown next.
Review Questions
tal of ports in the 80S I and each has . bits.
l. Th ere area to -- b hi d
2. ~ I All f the 8051 ports can be used for ot input an output.
T rue or ra se. a .?
3. Which 80S I ports need pull-up resis/tors to funCtIOnfjasandI/O porttp'torts
4. True or s:ra Ise. U pan power-up , the I 0 pins are can igure as ou up.
5. Show simple statements to send 99H to ports P I and P2.
99
CHAPTER 4: 110 PORT PROGRAMMING
SECTION 4.2: 1/0 BIT MANIPULATION PROGRAMMING
\
bit i Notice that Pl.2 is the third bit of PI, since the first bit is PI.O, the second
It IS P 1.1, and so on. Table 4- 3 shows the bits of the 8051 I/O rt S E
4-2 for an example of bit manipulation of I/O bits Not. pOE s. ele xample
d . . Ice III xamp e 4-2 that
unuse portions of ports I and 2 are undisturbed. This single-bit addressability of
I/O ports IS one of most powerful features of the 8051 . .
mlcroeontroller and IS
among t IlC reasons that many designers choose tl 8051 .
t II W ·11 lC over other rmcrocon-
ro ers. e WI see the use of the bit-addrcssability f I/O . fu
ters. ° ports 111 ture chap-
Solution:
(a) The 50% duty cycle means that the "on" and "off' states (or the high and low
portions of the pulse) have the same length. Therefore, we toggle Pl.O with a
time delay in between each state.
8051
Pl.D I-- J
(b) The 66% duty cycle means the "on" state is twice the "off' state.
8051
P1.3 I-- J
101
CHAPTER 4: 1/0 PORT PROGRAMMING
Table 4-4: Single-Bit Instructions
Instruction Function
SETB bit Set the bit (bit I)
CLR bit Clear the bit (bit 0)
CPL bit Complement the bit (bit NOT bit)
JB bit,target Jump to target if bit I (jump ifbit)
JNB bit,target Jump to target ifbit 0 (jump ifno bit)
JBC bit.target Jump to target ifbit - I, clear bit (jump if bit, then clear)
Table 4-4 lists the single-bit instructions for the 8051. We will see the use
of these instructions throughout future chapters.
Example 4-3
Solution:
SETB PI.2
MOV A,#45H ;make PI.2 an input
AGAIN: ;A=45H
JNB PI.2,AGAIN
MOV PO ,A ;get out when PI.2=1
SETB P2.3 ;issue A to PO
CLR P2.3 ;make P2. 3 high
;make P2.3 low for H-to-L
In this program, instruction "JNB PI 2 AG" .
stays in the loop as long as P 1.2 is low WhenPI' AIN (JNB means Jump if no bit)
writes the value 45H to port 0 and' H·2 becomes high, It gets out of the loop
lions SETB and CLR. ' creates an -to-L pulse by the sequence of instruc~
Table 4-5: Instructions For Reading an Input Port
Mnemonic Example Description
MOV A, PX MOV A, P2 Bring into A the data at P2 pins
JNB PX. Y, .. JNB P2. I, TARGET Jump if pin P2.l is low
JB PX. Y, .. JB Pl. 3, TARGET Jump if pin P1.2 is high
MOV C, px. Y MOV C, P2.4 Copy status of pin P2.4 to CY
Example 4-4
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 high-to-low pulse to port P 1.5 to tum on a buzzer.
Solution:
4.7k
.~
.....
: i>
---IP2.3
74LS04
Example 4-5
A switch is connected to pin P 1.7. Write a program to check the status of SW and per-
form the following:
(a) If SW=O, send letter 'N' to P2.
(b) IfSW=I, send letter 'Y'toP2.
Solution:
;make Pl.? an input
SETB Pl.?
JB Pl.2,OVER ;jump if Pl. ?=l
AGAIN: ;SW=O, issue 'N' to P2
MOV P2,#'N'
;keep monitoring
SJMP AGAIN
;SW=l, issue 'Y' to P2
OVER: MOV P2,#'Y'
'keep monitoring
, i
SJMP AGAIN
103
CHAPTER 4: I/O PORT PROGRAMMING
Reading a single bit into the carry flag
We can also use the carry flag to save or examine the status of a single bit
of the port. To do that, we use the instruction "Mav C, Px. v" as shown in the
next two examples.
Example 4-6
A switch is connected to pin PI. 7. Write a program to check the status of the switch and
perform the following:
(a) If switch = 0, send letter 'N' to P2.
(b) Ifswitch = I, send letter 'Y'toP2.
Use the carry flag to check the switch status. This is a repeat of the last example.
Solution:
Example 4-7
Solution:
SETB PI. 7
AGAIN: Mav
Mav
C, PI.
P2.7,C
° ;make
;read
Pl.7 an input
the SW status into CF
SJMP ;send the SW status to LED
AGAIN
;keep repeating
In reading a port, some instructions read the status of port pins while oth-
ers read the status of an internal port latch. Therefore, when reading ports there
are two possibilities:
105
CHAPTER 4: 1/0 PORT PROGRAMMING
From the above discussion, we conclude that the instructions that read the
port latch normally read a value, perform an operation (and possibly change it),
then rewrite it back to the port latch. This is often called "Read-Modify-Write".
Read-modify-write feature
The ports in the 8051 can be accessed by the read-modify-write technique.
This feature saves many lines of code by combining in a single instruction all three
actions of (I) reading the port, (2) modifying its value, and (3) writing to the port.
The following code first places 01010101 (binary) into port I. Next, the instruc-
tion "XLR P1, #OFFH" performs an XOR logic operation on PI with 1111 1111
(binary), and then writes the result back into PI.
MOV P1,#55H ;P1 = 01010101
AGAIN: XLR P1, #OFFH ;EX-OR P1 with 11111111
ACALL DELAY
SJMP AGAIN
Notice that the XOR of S5H and FFH gives AAH. Likewise, the XOR of
AAH and FFH gives 551-l.Logic instructions arc discussed in Chapter 6.
Review Questions
I. True or false. The instruction "SETB P2. 1" makes pin P2.1 high while leav-
ing other bits of P2 unchanged.
2. Show one way to toggle the pin P 1.7 continuously using 8051 instructions
3. Using the mstructim, "JNB P2 . 5, HERE" assumes that bit P2.5 is' an
____ (input, output). .
4. Write instructions to get the status of P2.7 and put it on P2.0.
5. Write instructions to toggle both bits of PI 7 a d PI 0 .
. n . continuously.
CAUTION
We strongly recommend that you study Section C 2 (A di .
you are connecting any external hard
Failure to use the right instruction or the
can damage the ports of your 8051 system.
:r~t
. ppen IX C) If
~o your 8051 system.
onneclton to port pins
SUMMARY
I 4.
2. lruc
) PO
4 False
5. M V 1'1.# 9H
\1 V 1'2.#9911
I True
2 III: l'l.PI.7
JMP III
3 Inpul
M V '.1'2.7
M V no.
5. III PLPI.7
PL 1'1.0
JMP III
CHAPTER 5 (;\JtV\5
8051 ADDRESSING
MODES
OBJECTIVES
109
The CPU can access data in various ways. The data could be in a register,
or in memory, or be provided as an immediate value. These various ways of
accessing data are called addressing modes. In this chapter we discuss 8051/52
addressing modes in the context of some examples. ..
The various addressing modes of a microprocessor arc determined when It
is designed, and therefore cannot be changed by the programmer. The 8051 pro-
vides a total of five distinct addressing modes. They are as follows:
(1 ) immediate-'\).\o. ~ ~~ .
(2) register :~\"~ .&l&.... ')¢\"\tr'\Q'l"O"'Wc(>.-{IiN'
(3) direct ~-. . . ~~
(4) register indirect ~~ ~'Io~
(5) indexed .
In this section, first we examine immediate addressing mode and then reg-
ister addressing mode.
MOV DPTR.#2550H
is the same as:
MOV DPL. #50H
MOV DPH. #25H
110
Also notice that the following would produce an error since the value is
larger than 16 bits. ,
We can usc the EQU directive to access immediate data as shown below.
COUNT EQU 30
ORG 200H
MYDATA: DB "Amer i cav
Notice that we can also use immediate addressing mode to send data to
8051 ports. For example, "MOV PI,#55H" is a valid instruction.
It should be noted that the source and destination registers must match in
size. In other words, coding "MOV DPTR, A" will give an error, since the source
is an 8-bit register and the destination is a 16-bit register. See the following.
MOV DPTR,#25F5H
MOV R7,DPL
MOV R6,DPH
Notice that we can move data between the accumulator and Rn (for n = 0
to 7) but movement of data between Rn registers is not allowed. For example, the
instruction "MOV R4, R 7" is invalid.
In the first two addressing modes, the operands are either inside one of the
registers or tagged along with the instruction itself. In most programs, the data to
be processed is often in some memory location of RAM or in the code space of
ROM. There are many ways to access this data. The next section describes these
different methods.
. controller make up
C th programmer 0 f a micro . newR3 addressing mode .
I. an e. . I d 10000000 (binary) Into .
2 Show the instrucuon to oa DPTR"
. . h f, II ing invalid? "MOV R2, b d
3. ~:~ ~~ ~a~seoDOp~Ris a 16-bit register that is also accessible in low- ytc an
4.
high-byte
5. Is formats, counter ) a Iso available in low-byte and high-byte formats?
the PC (program
As mentioned in Chapter 2, there are 128 bytes of RAM in the 8051. The
RAM has been assigned addresses 00 to 7FH. The following is a summary of the
allocation of these 128 bytes.
I. RAM locations 00 - IFH are assigned to the register banks and stack.
2. RAM locations 20 - 2FH arc set aside as bit-addressable space to save single-
bit data. This is discussed in Section 5.3.
3. RAM locations 30 - 7FH arc available as a place to save byte-sized data.
Although the entire 128 bytes of RAM can be accessed using direct
addressing mode, it is most often used to access RAM locations 30 _ 7FH. This is
due to the fact that register bank locations arc accessed by the register names of
RO- R7, but there is no such name for other RAM locations. In the direct address-
ing mode, the data is in a RAM mcmory location whose address is known, and this
address is given as a part of the instruction. Contrast this with immediate address-
ing mode, in which the operand itself is provided with the instruction. The "#"
sign distinguishes between the two modes. Sec the examples below, and note the
absence of the "#" sign.
Mav RO,40H
Mav 56H,A ;save Content of RAM lOcation 40H in RO
nov R4, 7FH ;save content of A in RAM location 56H
;mOve contents of RAM location 7FH to R4
. The above examples should reinforce the importance of the "#" sign in
8051 msrructrons. See the following code.
113
CHAPTER 5: 8051 ADDRESSING MODES
Table 5-1 lists the 8051 special function registers (SFR) and their address-
. The following two points should be noted about the SFR addresses,
I. The pecial function registers have addresses between 80H and FFH. These
addrc se arc above 80H, since the addresses 00 to 7FH arc addresses of RAM
mem ry in ide the 8051 , .
2. 'ot all the addres space of 80 to FF is used by the SFR, The unused locations
80H to FFH arc reserved and must not be used by the 8051 programmer.
Write eode to send 55H to ports P I and P2, using (a) their names, (1:» their addresses.
Solution:
,
Stack and direct addressing mode
Another major use of direet addressing mode is the stack. In the 8051 fam-
ily, only direet addressing mode is allowed for pushing onto the stack. Therefore,
an instruetion such as "PUSH A" is invalid. Pushing the accumulator onto the
staek must be coded as "PUSH OEOH" where OEOH is the address ofregister A.
Similarly, pushing R3 of bank 0 is coded as "PUSH 03".Direct addressing mode
must be used for the POP instruction as well. For example, "POP 04" will pop
the top of the stack into R4 of bank O.
Example 5-2
Show the code to push R5, R6, and A onto the staek and then pop them baek them into
R2, R3, and B, where register B = register A, R2 = R6, and R3 = R5.
Solution:
115
CHAPTER 5: 8051 ADDRESSING MODES
pointers, that is, when they hold the addresses of RAM locations, they must be pre-
ceded by the "@" sign, as shown below.
Notice that RO (as well as R I) is preceded by the "@" sign. In the absence
of the "@" sign, MOY will be interpreted as an instruction moving the contents of
register RO to A, instead of the contents of the memory location pointed to by RO.
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.
Solution:
(a)
MaV A, #55H ;load A with value 55H
Mav 40H,A ;copy A to RAM location 40H
Mav 41H,A ;copy A to RAM location 41H
Mav 42H,A ;copy A to RAM location 42H
Mav 43H,A ;copy A to RAM location 43H
Mav 44H,A ;copy A to RAM location 44H
(b)
MOV A,#55H ;load A with value 55H
Mav RO,#40H ;load the pointer. RO=40H
MOV @RO,A r copy A to RAM location
INC RO RO points to
;increment pointer. Now RO=41H
MaV @RO,A ;copy A to RAM location RO
INC RO points to
;increment pointer. Now RO=42H
MOV @RO,A ;copy A to RAM location
INC RO RO points to
;increment pointer. Now RO=43H
MOV @RO,A ;copy A to RAM location RO
INC RO points to
;increment pointer. Now RO=44H
MOV @RO,A
(c)
MOV A,#55 ;A=55H
MOV RO,#40H ;load pointer.
MOV RO=40H, RAM address
R2,#05 ;load counter, R2=5
AGAIN: MOV
@RO,A ;copy 55H to RAM location RO .
INC RO .' , pOlnts to
DJNZ ,lncrement RO pointer
R2,AGAIN ;loop until
counter = zero
116
Advantage of register indirect addressing mode
. . One of the advantages of register indirect addressing mode is that it makes
aeeessmg data dynamic rather than static as in the ease of direct addressing mode.
Exa~pl.e 5-3 shows two eases of copying 55H into RAM locations 40H to 45H.
Notice 111 solution (b) that there are two instructions that are repeated numerous
tImes: We can create a loop with those two instructions as shown in solution (c).
Solution (c) IS the most efficient and is possible only because of register indirect
addressing mode. Looping is not possible in direct addressing mode. This is the
main difference between the direct and register indirect addressing modes.
Example 5-4
Solution:
CLR A ;A=O
MOV Rl,#60H ;load pointer. Rl=60H
MOV R7,#16 ;load counter, R7=16 (10 in hex)
AGAIN: MOV @Rl,A ;clear RAM location R1 points to
INC Rl ;increment R1 pointer
DJNZ R7,AGAIN ;loop until counter = zero
Solution:
MOV RO,#35H ;source pointer
MOV Rl,#60H ;destination pointer
MOV R3,#10 ;counter
BACK: MOV 'A,@RO ;get a byte from source
;copy it to destination ,
MOV @Rl,A
INC RO ;increment source pointer
INC Rl ,'increment destination pointer
DJNZ R3,BACK ;keep doing it for all ten bytes
117
CHAPTER 5: 8051 ADDRESSING MODES
Indexed addressing mode and on-chip ROM access
Indexed addressing mode is widely used in accessing data elements of
look-up table entries located in the program ROM space of the 8051. The instruc-
tion used for this purpose is "MOVCA, @A+DPTR". The 16-bit register DPTR and
register A are used to form the address ofthc data clement stored in on-chip ROM.
Because the data clements are stored in the program (code) space ROM of the
8051, the instruction MOVC is used instead ofMOV. The "C" means code. In this
instruction the contents of A arc added to the 16-bit register DPTR to form thc 16-
bit address of the needed data. See Example 5-6.
Example 5-6
In this program, assume that the word "USA" is burned into ROM locations starting at
200H, and that the program is burned into ROM locations starting at O.Analyze how the
program works and state where "USA" is stored after this program is run.
Solution:
ORG OOOOH
;burn into ROM starting at 0
MOV DPTR,#200H
;DPTR;200H look-up table address
CLR A ;clear A(A;O)
MOVC A,@A+DPTR
;get the char from code space
MOV RO,A
;save it in RO
INC DPTR
;DPTR;201 pointing to next char
CLR A
;clear A(A=O)
MOVC A,@A+DPTR
;get the next char
MOV Rl,A
;save it in Rl
INC DPTR
;DPTR;202 pointing to next char
CLR A
; clear A (A=O)
MOVC A,@A+DPTR
;get the next char
MOV R2,A
;save it in R2
HERE:SJMP HERE
;stay here
;Data is burned into
code space starting at 200H
ORG 200H
MYDATA: DB "USA"
END
;end of program
20 IH, which holds cha~acter "S"o A~~e:1I1hto get the contents of the next ROM location
53H, and R2 = 41H the ASCII 'I ,t IS program IS run, we have RO = 55H Rl =
) va ues lor the characters "U", "S" and "A", '
118
Example 5-7
Assuming that R~M space starting at 250H contains "America", write a program to
transfer the bytes II1toRAM locations starting at 40H.
Solution:
; (a) This method uses a counter
ORG 0000
MOV DPTR,#MYDATA ;load ROM pointer
MOV RO,#40H ;load RAM pointer
MOV R2,#7 ;load counter
BACK: CLR A ;A = 0
MOVC A,@A+DPTR ;move data from code space
MOV @RO,A ;save it in RAM
INC DPTR ;increment ROM pointer
INC RO ;increment RAM pointer
DJNZ R2,BACK ;loop until counter=O
HERE: SJMP HERE
Notice the null character, 0, indicating the end of the string, and how we use the
JZ instruction to detect that.
119
CHAPTER 5: 8051 ADDRESSING MODES
Look-up table and the MOVe instruction
The look-up table is a widely used concept in microprocessor program-
ming. It allows access to elements of a frequently used table with minimum oper-
ations. As an example, assume that for a certain application we need x2 values in
the range of 0 to 9. We can use a look-up table instead of calculating it. This is
shown in Example 5-8.
Example 5-8
Write a program to get the x value from P I and send x2 to P2, continuously.
Solution:
ORG o
MOV DPTR,#300H ,load look-up table address
MOV A, #OFFH ,A=FF
MOV Pl,A ,configure PI as input port
BACK: MOV A,Pl ;get X
MOVC A,@A+DPTR ,get X squared from table
MOV P2,A ,issue it to P2
SJMP BACK ;keep doing it
ORG 300H
XSQR_TABLE:
DB 0,1,4,9,16,25,36,49,64,81
END
Notice that the first instruction could be replaced with "MOV DPTR, #XSQR TABLE"
Example 5-9
Answe~ the following questions for Example 5-8.
(a) Indicate the content of ROM locations 300 _ 309H.
(b) At what ROM location is the square of 6, and what value should b ?
(c) Assume that PI bas a value of9' What I . P '. e there.
. va ue IS at 2 (in binary)?
Solution:
120
In addition to being used to access program ROM, DPTR can be used to
access memory externally connected to the 805 I. This is discussed in Chapter 14.
. . Another register used in indexed addressing mode is the program counter.
This IS discussed In Appcndix A.
In many of the examples above, the MOVinstmction was used for the sake
of clarity, even though one can use any instruction as long as that instruction sup-
ports the addressing mode. For example, the instruction "ADD A,@RO" would
add the contents of the memory location pointed to by RO to the contents of regis-
ter A. We wi II see more examples of using addressing modes with various instruc-
tions in the next few chapters.
Example 5-10
Write a program to toggle PI a total of 200 times. Use RAM location 32H to hold
your counter value instead of registers RO - R7.
Solution:
MOV PI,#55H ;PI=55H
MOV 32H,#200 ,.load counter value into RAM loc 32h
LOPI:CPL PI ;toggle PI
ACALL .DELAY
DJNZ 32H,LOPI ;repeat 200 times
121
CHAPTER 5: 8051 ADDRESSING MODES
Review Questions
I. The instruction "MOV A, 4 OR" uses addressing mode. Why?
2. What address is assigned to register R2 of bank 0'1
3. What address is assigned to register R2 of bank 2'1
4. What address is assigned to register A? . de if
5. Which registers are allowed to be used for register indirect addressing mo e I
the data is in on-chip RAM?
Bit-addressable RAM
Of the I28-byte internal RAM of the 8051, only 16 bytes arc bit-address-
able. The rest must be accessed in byte format, The bit-addressable RAM loca-
tions arc 20H to 2FH. These 16 bytes provide 128 bits of RAM bit-addressabili-
ty since 16 x 8 = 128. They arc addressed as 0 to 127 (in decimal) or 00 to 7FH.
Therefore, the bicaddres~ to 7 are for the firs\):>yl of iutemal RAM location
JOH, and 8 to OFH arc the bit addresses of the second byte ofRAMlo~H
and so on. The last byte of2FH has bit addresses of78H to 7FH. See Figure 5-1'
and Example 5-/1. Note that internal RAM locations 20 _ 2FH arc both byte-
addressable and bit-addressable.
Example 5-11
Find out to which byte each of the following bits belongs. Give the address ofth RAM
byte 111 hex. e
(a) SETB 42H ; set bit 42H to 1 (d)
(b) CLR 67H ; clear bit 67 SETB 28R ;set
(e) CLR bit 28H to 1
(c) CLR OFH ; clear bi t OFH (t) SETB1205;clear bit 12 (decimal)
Solution:
(a) RAM bit address of 42H belongs to 02 of RAM I .
(b) RAM bit dd ocatton 28H
I a ress of 67H belongs to 07 of RAM location 2CH'
(e) RAM bit address ofOFH belongs to 07 of RAM I' .
(d) RAM bit address 01'2811 belongs to DO of RAM loeatlon 21H.
(e) RAM bit address of 12 belongs to 04 of RAM locatIon 25H.
(I) RAM bit address 01'05 belongs to 05 of RAM locatton 21H.
ocation 20H.
122
ln order to avoi d
confusion regarding th e Byte
addresses 00 - 7FH, the fo 1- address
[owing two points must b e
7F
noted.
General-
r. The [28 bytes of RAM purpose
have the byte addresse S
of 00 - 7FH and can be
accessed in byte siz e
~'1je
(30
1>., RAM
2F 7F 7E 7D 7C 7B 7A 79 78
using various address - I
2E 77 7~ 75 74 7< 77 71 70
ing modes such a S 2D 6F 6E 6D 6C 6B 6A 69 68
direct and register-indi - I ?r Ih7 ~h ~" ~A h< h7 ~1 ~n
Instruction
SETB bit
CLR bit
CPL bit
JB bit, target
JNB bit,tar et if bit, then clear
JBC bit,tar et
123
CHAPTER 5: 8051 ADDRESSING MODES
I/O port bit addresses
As we discussed in Chapter 4, the 8051 has four 8-bit VO ports: PO, PI, 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 usc 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 J. Remember that DO is the LSB and D7 is the MSB.
As we mentioned
Byte
earlier in this chapter, every
address Bit address
SFR register is assigned a
byte address and ports PO - FF
P3 are part of the SFR. For FO F7 F6 F5 F4 F3 F2 Fl FO B
example, PO is assigned
byte address 80H, and PI EO E7 E6 E5 E4 E3 E2 El EO Ace
has address of 90H as
DO D7 D6 D5 D4 D3 D2 Dl DO psw
shown in Figure 5-2. While
all of the SFR registers are B8 -- BC BB 8A B9 88 IP
byte-addressable some of
them are also bit-address- BO B7 B6 85 B4 B3 82 Bl BO
P3
able. The PO - P3 are among
this category of SFR regis- AS AF AC AB AA A9 A8 IE
ters. From Figure 5-2 we
AD A7 A6 AS A4 A3 A2 Al
see that the bit addresses for AO P2
PO are 80H to 87H, and for
P I arc 90H to 97H, and so 99
not bit-addressable SBUF
on. 98 9F 9E 9D ge 9B 9A
99 98 seaN
Notice that when
code such as "SETB 90 97 96 95 94 93
92 91 90 PI
Pl.0" is assembled, it
becomes "SETB 90H" 8D
not bit-addressable T HI
since P 1.0 has the RAM 8e
not bit·addressable T HO
address of 90H. Also notice 88
not bit-addressable T Ll
from Figures 5-1 and 5-2 8A
not bit-addressable T LO
that bit addresses 00 - 7FH 89
not bit-addressable T MOD
belong to RAM byte 88 8F 8E 8D
8e 8B 8A 89 88 T eON
addresses 20 - 2FH, and bit 87
addresses 80 - F7H belong not bit-addressable P eON
[a SFR of PO, TCON, PI
83
SCON, P2, etc. The bi; not bit-addressable D PH
82
addresses for PO - P3 arc not bit-addressable D PL
81
shown in Table 5-3 , an d not bit-addressable sP
.
d iscusscd next. 80 87 86 85 84
83 82 81 80
Pa
Special Function Registers
124
=
Bit memory map
From Figures 5-1 and 5-2 and Table 5-3 once again notice the following
facts.
1) The bit addresses 00 -7FH are assigned to RAM locations of20 - 2FH.
2) The bit addresses 80 - 87H are assigned to the PO port.
3) The bit addresses 88 - 8FH arc assigned to the TCON register.
4) The bit addresses 90 - 97H are assigned to the PI port.
5) The bit addresses 98 - 9FH are assigned to the SCaN register.
6) The bit addresses AO- A7H are assigned to the P2 port .:
7) The bit addresses A8 - AFH are assigned to the IE register.
8) The bit addresses BO - B7H are assigned to the P3 port.
9) The bit addresses B8 - BFH arc assigned to IP.
10) The bi t addresses CO - CFH are not assigned.
11) The bit addresses ,DO- D7H are assigned to the PSW register.
12) The bit addresses D8 - DFH 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.
Example 5-12
Use Table
For each of the following instructions, state to which port the bit belongs.
5-3. (d) SETB OA7H
(b)CLR 87H (c) SETB 92H
(a) SETB 86H
Solution:
125
CHAPTER 5: 8051 ADDRESSING MODES
Registers bit-addressability
While all VO ports arc bit-addressable, that is not the case with registers,
as seen from Figure 5-1. Only registers A, B, PSW, IP, IE, ACC, SCaN, and
TCON are bit-addressable. Of the bit-addressable registers, we will concentrate
on the familiar registers A, B, and PSw. The rest will be discussed in future chap-
ters.
Now let's see how we can use bit-addressabiJity of registers such as A and
PSw. As we discussed in Chapter 2, in the PSW register two bits are set aside for
the selection of the register banks. See Figure 5-3. Upon RESET, bank 0 is select-
ed. We can select any other banks using the bit-addressability of the PSW as was
shown in Chapter 2. The bit addressability of PSW also eliminates the need for
instructions such as JOV (Jump if Ov> I). Sec Example 5-14.
Examine the next few examples ofbit-addressabilty to gain a better under-
standing of this important feature of the 8051 .
I
RSI
Cy
RSO
AC FO RSl
Register Bank
RSO ov P
Address
0 0 0 OOH - 07H
0 I I 08H - OFH
J 0 2 lOB - 17H
I I 3 18H - IFH
Figure 5-3. Bits of the PSW Register
Example 5-13
Solution:
CLR PSW.3
SETB PSW.4
MOV R7,A
Example 5-14
Solution:
Write a program to see if the RAM location 37H contains an even value. If so, send it
to P2. If not, make it even and then send it to P2.
Solution:
MOV A,37H ;load RAM location 37H into accumulator
JNB ACC. 0, YES ;is DO of reg A O? if so jump,
INC A ;it is odd, make it even
YES: MOV P2,A ;send it to P2
Example 5-16
Assume that bit P2.3 is an input and represents the condition of a door. If it goes high,
it means that the door is open. Monitor the bit continuously. Whenever it goes high,
send a low-to-high pulse to port P 1.5 to tum on a buzzer.
Solution:
.....
---1P2.3
Buzzer
4.7k
P1.51---1
74LS04
Example 5-17
The status of bits P 1.2 and P 1.3 of I/O port P I must be saved before they are cha~ged.
. th tatus of PI 2 in bit location 06 and the status of P 1.3 In bit
Wnte a program to save e s .
location 07.
Solution:
;clear bit address 06
CLR 06
;clear bit address 07
CLR 07
.check bit P1.2,if 0 then jump
JNB P1.2,OVER
:if P1.2=1,set bit location 06 to 1
SETB 06
:check bit P1.3, if 0 then jump
OVER:JNB P1.3,NEXT
:if
, P1.3=1, set bit location 07 to 1
SETB 07
NEXT: ...
127
CHAPTER 5: 8051 ADDRESSING MODES
Example 5-18
Write a program to save the status 0f bit1 PI .7 on RAM address bit 05.
Solution:
Example 5-19
Write a program to get the status of bit pin PI.7 and send it to pin P2.0.
Solution:
Example 5-20
Assume that bit P2J 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-to-high pulse to port PI .5 to tum on a buzzer.
\
Solution:
HERE:JNB OVEN_HOT,HERE
ACALL DELAY ;keep monitoring for HOT
CPL BUZZER
ACALL DELAY
;sound the buzzer
SJMP HERE
~~~~ s~~;:~~ ~xample 5-16, except the use of BIT directive allows us to assign the
gram f;r them. UZZER bit to any port. This way you do not have to search the pro-
128
.~",: -
" ".
- .
Example 5-21
An LED is connected to pin Pl.? Write a program to toggle the LED forever.
Solution:
Example 5-22
A switch is connected to pin Pl.? and an LED to pin P2.0. Write a program to get the
status of the switch and send it to the LED.
Solution:
Example 5-23
Assume that RAM bit location 12H holds the status of whether there has been a phone
call or not. If it is high, it means there has been a new call since it was checked the last
time. Write a program to display "New Messages" on an LCD ifbit RAM 12H is high.
If it is low, the LCD should say "No New Messages".
Solution:
129
CHAPTER 5: 8051 ADDRESSING MODES
Using EQU directive
Wc can also use the EQU directive to assign addresses, as shown in the
ncxt few examples, Notice that in Example 5-24 the ports arc defined by their
names, while in Example 5-25, they are defined by their addresses.
Example 5-24
A switch is connected to pin PI.? Write a program to check the status of the switch and
make the following decision.
(a) If SW = 0, send "NO" to P2.
(b) If SW = I, send "YES" to P2.
Solution:
SW EQU Pl. 7
MYDATA EQU P2
Example 5-25
A switch is connected to pin PI.? Write a r
makc the following decision. p ogram to check the status of the switch and
(a) If SW = 0, send '0' to P2.
(b)/fSW= I,send ']'toP2.
USC EQU to designate the I/O ports.
Solution:
SW EQU 97H
MYDATA ;P1.7 bit address
EQU OAOH
HERE: ;P2 address
MOV C,SW
JC OVER
MOV MYDATA,#'O'
SJMP HERE ; 00110000 to P2
OVER:
MOV MYDATA,#'l'
SJMP HERE ; 00110001 to P2
END
130
=
Review Questions
I. True or false. All I/O ports of the 805[ are bit-addressable.
2. True or false. All registers of the 8051 are bit-addressable.
3. True or false. All RAM locations of the 8051 are bit-addressable.
4. Indicate which of the following registers are bit-addressable.
(a) A (b) B (c) R4 (d) PSW (e) R7
5. Of the 128 bytes of RAM in the 8051, how many bytes are bit-addressable?
LIst them.
6. How would you check to see whether bit DO ofR3 is high or low?
7. Fmd out to which byte each of the following bits belongs. Give the address of
the RAM byte in hex.
(a) SETB 20 (b) CLR 32 (c) SETB I2H
(d) SETB 95H (e) SETB OE6H
8. While bit addresses 00 - 7FH belong to , bit addresses 80 - F7H
belong to .
9. True or false. PO, PI, P2, and P3 are part of SFR.
10. True or false. Register ACC is bit-addressable.
Figure 5-4 shows the parallel space shared between the SFR and the upper
128 bytes of RAM in the 8052, Example 5-26 shows how to access the upper 128
bytes of on-chip RAM in the 8052 microcontrollcr.
FF FF
Direct Access Indirect Access
(MOV 90H,#55H) (MOV@RO,A)
20
1F
Accumulator,
Registers,
18 Program Status Word
Bank 3
17 Stack Pointer , '
Status and Control Bits
Ports, '
10 Bank 2 Timers,
OF Serial Control ,
Power Control, and
others
08 Bank 1
07
00 Bank 0
Write a program for the 8052 to put 55H into the upper RAM locations of 90 - 99H.
Solution:
ORG o
MOV A,#55H
MOV R2,#10
MOV RO,#90H ;access the upper 128 bytes of on-chip 'RAM
BACK:MOV @RO,A ;use indirect addressing mode
INC RO
DJNZ R2,BACK ;repeat for all locations
SJMP $ ;stay here
END
Run the above program on your simulator and examine the upper memory to see the
result. (See Figures 5-5 and 5-6 for screen shots.)
Example 5-27
Assume that the on-chip ROM has a message. Write a program to copy it from code
space into the upper memory space starting at address 80H. Also, as you place a byte
in upper RAM, give a copy to PO.
Solution:
ORG 0
MOV DPTR, #MYDATA
MOV R1,#80H iaccess the upper 128 bytes of on-chip RAM
B1: CLR A
MOVC A,@A+DPTR ;copy from code ROM space
MOV @R1,A ;store in upper RAM space
MOV PO,A ;give a copy to PO
JZ EXIT ;exit if last byte
INC DPTR ;increment DPTR
INC R1 ;increment R1
SJMP B1 ;repeat until the last byte
EXIT: SJMP $ ;stay here when finished
i -----------
ORG 300H
MYDATA: DB "The Promise of World Peace", 0
END
R un teah bove program 0n your simulator and examine the upper memory to see the
result.
133
CHAPTER 5: 8051 ADDRESSING MODES
Simulators and Data RAM space
All the major 8051/52 simulators have ways of showing the data RAM
contents. Figures 5-5 and 5-6 show some of them.
88: 00 00 00 00 00 00 00 00 ·.......
90: 55 55 55 55 55 55 55 55 UUUUUUUU
98: 55 55 00 00 00 00 00 00 UU......
0: 00 00 00 00 00 00 00 00 · .......
8: 00 00 00 00 00 00 00 00 ·.... ...
BO: 00 00 00 00 00 00 00 00 · . . .....
B8: 00 00 00 00 00 00 00 00 · .......
CO: 00 00 00 00 00 00 00 00 · .......
C8: 00 00 00 00 00 00 00 00 · .......
DO: 00 00 00 00 00 00 00 00 · .......
08: 00 00 00 00 00 00 00 00 ·..... ..
EO: 00 00 00 00 00 00 00 00 · .......
EO: 00 00 00 00 00 00 00 00 · .......
FO: 00 00 00 00 00 00 00 00 · .......
F8: 00 00 00 00 00 00 00 00 · .......
rOO
,;J
Figure 5-5. Franklin Software's Pro View Upper Memory for the 8052
I:Ox80 00 00 00 00 00 00 00 00
I:Ox88 00 00 00 00 00 00 00 00 · .
I:Ox90 55 55 55 55 55 55 55 55 · .
I:Ox98 55 55 00 00 00 00 00 00 UUUUUUUu
I:OxAO 00 00 00 00 00 00 00 00 UU ......
I:OxA8 00 00 00 00 00 00 00 00 · .
I :OxBO 00 00 00 00 00 00 00 00 · .
I:OxB8 00 00 00 00 00 00 00 00 · .
I:OxCO 00 00 00 00 00 00 00 00 · .
I:OxC8 00 00 00 00 00 00 00 00 · .
I:OxDO 00 00 00 00 00 00 00 00 · .
I:OxD8 00 00 00 00 00 00 · .
I:OxEO 00 00 00 00 00 00
00 00 · .
I:OxE8 00 00 00 00 00 00
00 00 · .
I:OxFO 00 00 00 00 00 00
00 00 · .
I:OxF8 00 00 00 00 00 00
00 00 · .
> I:Ox80, OxFF
00 00 · .
134
Review Questions
I. True or false. The 8052 is an upgraded version of ;he 8051.
2. True or false. The 8052 has a total of256 bytes of on-chip RAM in addition to
the SFRs.
3. True or false. The extra 128 bytes of RAM in the 8052 is physically the same
RAM as the SFR.
4. Give the address for the upper RAM of the 8052.
5. Show how to put value 99H into RAM location F6H of upper RAM in the
8052.
SUMMARY
This chapter described the five addressing modes of the 8051. Immediate
addressing mode uses a constant for the source operand. Register addressing
mode involves the use of registers to hold data to be manipulated. Direct or reg-
ister 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 indirect addressing mode uses a register as a pointer to the data. The
advantage of this is that it makes addressing dynamic rather than static. Indexed
addressing mode is widely used in accessing data elements ofJook-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 IMMEDIATEAND REGISTERADDRESSING MODES I
ACCESSING MEMORY USING YARIOUS ADDRESSING MODES
136
CHAP
35. Give another instruction for "CLR C".
36. In Problem 19, assemble each instruction and state if there is any difference
between them,
37. Show how you would check whether the OV flag is low.
38 Show how yO!! wo!!ld check whether the CY flag is high.
39. Show how you would check whether the P flag is high.
40. Show how you would check whether the AC flag is high.
41. Give the bit addresses assigned to the flag bit of CY, P, AC, and O'V,
42. 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.
43. Indicate the bit addresses assigned to RAM locations 20H to 2FH.
44. The byte addresses assigned to the 128 bytes of RAM are to .
45. The byte addresses assigned to the SFR are to -,-- ---
46. Indicate the bit addresses assigned to both of the following. Is there a gap
between them?
(a) RAM locations 20H to 2FH (b') SFR
47. The following are bit addresses. Indicate where each one belongs.
(a) 05H (b) 47H (c) 18H (d) 20H (e) 53H (0 ISH
(g) 67H (h) 55H (i) 14H (j) 37H (k) 7FH
48. True or false. The bit addresses of less than 80H are assigned to RAM loca-
tions 20 - 2FH.
49. True or false. The bit addresses of 80H and beyond are assigned to SFR (spe-
cial function registers).
50. Write instructions to save the CY flag bit in bit location 4.
51. Write instructions to save the AC flag bit in bit location 16H.
52 Write inill:uctiousJo save the P flag bit in bit location 12H.
53. Write instructions to sec whether the DO and 01 bits of register A are high. If
0, divide register A by 4.
54. Write a program to see whether the D7 bit of register A is high. If so, send a
me sage to the LCD stating that ACC has a negative number.
55. Write a program to see whether the D7 bit of register B is low. If so, send a
mes age to the LCD stating that register B has a positive number.
~ Write a program to set high all the bits of RAM locations 20H to 2FH ..using
the following methods:
(a) byte addresses (b) bit addresses
57. Write a program to see whether the accumulator is divisible by 8.
58. Write a program to find the number of zeros in register R2.
59. What is the total number of bytes of RAM in the 8052 including the SFR reg-
isters? Contrast that with the 8051. '~"l-'l-f.t\.
60. What addressing mode is used to access the SFR? .
61. What addressing mode is used to access the upper 128 bytes of RAM In the
8052? f . h
62. Give the address range of the lower and the upper 128 bytes 0 RAM In t e
8052.0Y'lFt-t >:, ~O -r~H
137
CHAPTER 5: 8051 ADDRESSJNG MODES
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,#99HifRO=80H
66. Which registers can be used to access the upper 128 bytes of RAM in the
8052?
67. Write a program to put 55H into RAM locations CO - CFH of upper memory.
68. Write a program to copy the contents of lower RAM locations 60 - 6FH to upp-
per RAM locations DO- DFH.
I. No
2. MOV R3,#10000000B
3, Source and destination registers' sizes do not match.
4. True '
5. No
I. Tmc
2. False
3. False
4. A, B, and PSW
5. \6 bytes are bit-addressable; they are from byte location 20H to 2FH
6. MOY A,R3 .
JNB ACC.O
7. For (a). (b), and (c) usc Figure 5-1. (a) RAM byte 22H, bit D4
(b) RAM byte 24H, bit DO (c) RAM byte 22H. bit D?
For (d) and (e) usc Figure 5-2. (d) SETB P 1.5 -
8. RAM bytes 00 - 20H, special function registers. (c) SETB ACC.6
9. True
10. True
I. Tme
2, True
3. False
4. 80 - FFH
5. MOV A,#99H
MOV RO,#OF6H
MOV @RO,A
138
CHAPTER 6
ARITHMETIC, LOGIC
INSTRUCTIONS, AND
PROGRAMS
OBJECTIVES
139
This chapter describes all 8051 arithmetic and logic instructions. Program
examples arc given to illustrate the application of these instructions. In Section 6.1
we discuss instructions and programs related to addition, subtraction, multiplica-
tion, and division of unsigned numbers. Signed numbers are discussed in Section
6.2. In Section 6.3, we discuss the logic instructions AND, OR, and XOR, as well
as the COMPARE instruction. The ROTATE instruction and data serialization arc
discussed in Section 6.4. In Section 6.5 we provide some real-world applications
such as BCD and ASCII conversion and checksum byte testing.
Unsigned numbers are defined as data in which all the bits are used to rep-
resent data, and no bits arc set aside for the positive or negative sign. This means
that the operand can be between 00 and FFH (0 to 255 decimal) for 8-bit data.
Addition of unsigned numbers
In the 8051, in order to add numbers together, the accumulator register (A)
must be involved. The form of the ADD instruction is
The instruction ADD is used to add two operands. The destination operand
is always in register A while the source operand can be a register, immediate data,
or in memory. Remember that memory-to-memory arithmetic operations are
never allowed in 8051 Assembly language. The instruction could change any of
the AF, CF, or P bits of the flag register, depending on the operands involved. The
effect of the ADD instruction on the overflow flag is discussed in Section 6.3 sine.
it is used mainly in signed number operations. Look at Example 6-1. e
Example 6-1
MOV A,#OF5H
;A=F5 hex
ADD A,#OBH
;A=F5+0B=00
Solution:
Example 6-2
Assume that RAM locations 40 - 44 have the followi .
the sum of the values. At the end of the r ollowing values. Wnte a program to find
and R7 the high byte All I . P ogram, register A should contain the low byte
. va ues are 111 hex.
40= (7D)
41=(EB)
42=(C5)
43=(5B)
44=(30)
Solution:
At the end when the loop is finished, the sum is held by registers A and R 7,
where A has the low byte and R7 has the high byte.
1
3C E7
+ 38 8D
78 74
When the first byte is added (E7 + 8D = 74, CY = I). The carry is propa-
gated to the higher byte, which results in 3C + 3B + I = 78 (all in hex). Example
6-J shows the above steps in an 8051 program.
Example 6-3
Write a program to add two 16-bit numbers. The numbers are JCE7H and 3B8DH.
Place the sum in R7 and R6; R6 should have the lower byte.
Solution:
142
Packed BCD
In packed BCD, a single byte has two BCD numbers in it one in the lower
4 bits, and one in the upper 4 bits. For example, "0101 100I" is'packed BCD for
59H. It takes only I byte of memory to store the packed BCD operands. And so
one reason to use packed BCD is that it is twice as efficient in storing data.
There IS a problem with adding BCD numbers, which must be corrected.
The problem is that after adding packed BCD numbers, the result is no longer
BCD. Look at the following.
MOV A,#17H
ADD A,#28H
Adding these two numbers gives 00 II 1111B (3FH), which is not BCD! A
BCD number can only have digits from 0000 to 1001 (or 0 to 9). In other words,
adding two BCD numbers must give a BCD result. The result above should have
been 17 + 28 = 45 (0 I00 0 I0 1). To correct this problem, the programmer must add
6 (0 II 0) 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 prob-
lem, 6 must be added to the Lipperdigit (D9H + 60H = 139H) to ensure that the
result is BCD (52 + 87 = 139). This problem is so pervasive that most micro-
processors 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 I is dis-
cussed next.
DA instruction
The DA (decimal adjust for addition) instruction in the 8051 is provided to
correct the aforementioned problem associated with BCD addition. The mnemon-
ic "DAn has as its only operand the accumulator "A". The DA instruction will add
6 to the lower nibble or higher nibble ifneeded; otherwise, it will leave the result
alone. The following example will clarify these points.
2 4If bits.
the upper nibble is greater than 9, or if CY = I, add. 01 J 0 to th c upp e r 4 bits .
. In reality there is no other use for the AC (auxiliary carry) flag bit except
for BCD addition and correction. For example, adding 29H and 18H WIll result in
41H, which is incorrect as far as BCD is concerned.
Hex BCD
29 0010 1001
+ 18 + 0001 1000
41 0100 0001 ACd
+ ---..2. + 0110
47 0100 0111
Since AC = 1 after the addition, "DA A" will add 6 to the lower nibble.
The final result is in BCD format.
Example 6-4
Assume that 5 BCD data items are stored in RAM locations starting at 40H, as shown
below. Write a program to find the sum of all the numbers. The result must be in BCD.
40~(71)
41~(1l)
42~(65)
43~ (59)
44~ (37)
Solution:
These three steps are performed for every SUBB instruction by the inter-
nal 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,
Example 6-5
Show the steps involved in the following,
MOV R3,#23H in A
; subtract A - R3, place result
SUBB A,R3
Solution:
145
CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS
lfthe CY = 0 after the execution ofSUBB, the result is positive; ifCY = I,
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 rNC
instructions can be used to change it. The CPL instruction performs the I's com-
plement of the operand; then the operand is incremented (INC) to get the 2 's com-
plement. See Example 6-6.
Example 6-6 .
Analyze the following program:
CLR C
MOV A,#4CH ;load A with value 4CH (A=4CH)
SUBB A,#6EH ;subtract 6E from A
JNC NEXT ;if CY=O jump to NEXT target
CPL A ;if CY=l then take l's complement
INC A ;and increment to get 2's complement
NEXT:MOV R1,A ;save A in R1
Solution:
CLR C
;CY = 0
MOV A,#62H
;A = 62H
SUEB A,#96H
MOV ;62H - 96H = CCH with CY = 1
R7,A
MOV ;save the result
A,#27H
;A=27H
SUEB A,#12H
MOV R6,A ;27H - 12H - 1 = 14H
;save the result
Solution:
146
UNSIGNED MULTIPLICATION AND DIVISION
.In multiplying or dividing two numbers in the 8051, the use of registers A
and B IS required since the multiplication and division instructions work only with
these two registers. Wc first discuss multiplication.
Note: Multipliealion of operands larger than 8 bits takes some manipulation. It is len to the
reader to experiment with.
DIV AB ;divide A by B
147
CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS
Notice thc following points for instruction "DIV ABu.
Example 6-8
Write a program (a) to make PI an input port, (b) to get a byte of hex data in the range
of 00 - FFH from PI and convert it to decimal. Save the digits in R7, R6, and R5, where
the least significant digit is in R7.
Solution:
MOV A,#OFFH
MOV Pl,A
;make PI an input port
MOV A,Pl ;read data from PI
MOV B,#10 ;B=OA hex (10 dec)
DIV AB ;divide by 10
MOV R7,B ;save lower digit
MOV B,#10
DIV AB
;divide by 10 once more
MOV R6,B
;save the next digit
MOV RS,A
;save the last digit
148
Example 6-9
Analyze the program in Example 6-8, assuming that P I has a value of FDH for data.
Solution:
To convert a binary (hex) value to decimal, we divide it by 10 repeatedly until the quo-
tient IS less than 10. After each division the remainder is saved. In the case of an 8-bit
binary such as FDH we have 253 decimal as shown below (all in hex).
Quotient Remainder
FD/OA= 19 3 (low digit)
19/0A= 2 5 (middle digit)
2 (high digit)
Therefore, we have FDH = 253. In order to display this data it must be converted to
ASCIl, which is described in a later section in this chapter.
Review Questions
1. In multiplication of two bytes in the 8051, we must place one byte in register
____ and the other in register _
2. In unsigned byte-by-byte multiplication, the product will be placed in regis-
teres) _
3. Is this a valid 8051 instruction? "MUL A, Rl". Explain your answer.
4. In byte/byte division, the numerator must be placed in register and
the denominator in register _
5. In unsigned bytelbyte division, the quotient will be placed ITI regis-
ter and the remainder in register ____
6. Is this a valid 8051 instruction? "DIV A, R1". Explain your answer.
7. The instruction "ADD A, source" places the sum in ----
8. Why is the following ADD instruction illegal?
"ADD R1, R2"
9. Rewrite the instruction above in correct form.
10. The instruction "ADDC A, source" places the sum in ------
l l , Find the value of the A and CY flags in each of the following.
(a) MOV A, #4FH (b) MOV A, #9CH
ADD A,#OB1H ADD A,#63H
12. Show how the CPU would subtract aSH from 43H.
13. !fCY = I, A = 95H, and B = 4FH prior to the execution of"SUBB A, B", what
.?
will be the contents of A after the su btraction.
149
CHAPTER 6: AIUTHMETlC, LOGIC INSTRUCTIONS, AND PROGRAMS
SECTION 6.2: SIGNED NUMBER CONCEPTS AND
ARITHMETIC OPERATIONS
All data items used so far have been unsigned numbers, meaning that the
entire 8-bit operand was used for the magnitude. Many applications require signed
data. In this section the concept of signed numbers is discussed along with relat-
ed instructions. J f your applications do not involve signed numbers, you can
bypass this section.
ISO
Examples 6-10 , 6- 11, an d 6- I2 demonstrate these three steps:
Example 6-10
Show how the 8051 would represent -5.
Solution:
Therefore -5 = FBH, the signed number representation in 2 's complement for -5.
Example 6-11
Show how the 8051 would represent -34H.
Solution:
Therefore -34 = CCH, the signed number representation in 2's complement for -34H.
Example 6-12
Show how the 8051 would represent -128.
Solution:
Therefore -128 = 80H, the signed number representation in 2's complement for -128.
The above explains the mystery behind the relative address of -128 to + 127
in the short jump discussed in Chapter 3.
MOV A,#+96
MOV R1,#+70 ;A = 0110 0000 (A = 60H)
ADD A,R1 ;R1 = 0100 0110 (R1 = 46H)
;A = 1010 0110
Solution: ;A = A6H = -90 decimal, INVALID!
According
cate to the CPU, the result is -90, which is wrong. The CPU sets OV
the overflow. = I to indi-
Solution:
According to the CPU, the result is + 126, which is wrong (OV = 1).
Example 6-15
Observe the following, noting the OV flag.
Solution:
-2 1111 1110
±-=2 1111 1011
-7 1111 1001 and OV = 0
153
GIC INSTRUCTIONS, AND PROGRAMS
CHAPTER 6: ARITHM ETIC , LO
Example 6-16
Examine the following, noting the role of Ov.
Solution:
7 0000 0111
+ -lJl 0001 0010
25 0001 1001 and OV ; 0
From the above examples wc conclude that in any signed number addition,
OV indicates whether the result is valid or not. If OV; I, the result is erroneous;
if OV = 0, the result is valid. We can state cmphatically that in unsigned number
addition we must monitor the status ofCY (carry nag), and in signed number addi-
tion, the OV (overflow) nag must be monitored by the programmer. In the 8051,
instructions such as JNC and JC allow the program to branch right after the addi-
tion of unsigned numbers, as we saw in Section 6.1. There is no such instruction
for the OV nag. However, this can be achieved by "JB PSW. 2" or "JNB
PSW. 2" since PSW, the nag register, is a bit-addressablc register. This is dis-
cussed later in this chapter.
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
1'8 complement (Invert)
ADD A,#l
add 1 to make 2'8 complement
Review Questions
Apart from 1/0 and arithmetic instructions, logic instructions are some of
most widely used Instructions. In this section we cover Boolean logic instructions
such as AND, OR, exclusive-or (XOR), and complement. We will also study the
compare instruction.
AND
ANL destination,source ;dest = dest AND source
Example 6-17
Show the results of the following.
Solution:
OR
;dest = dest OR source
ORL destination,source
Logical OR Function
The destination and source operands are Inputs Output
ORed and the result is placed in the destination. The
ORL instruction can be used to set certain bits of an x Y XORY
operand to l , The destination is normally the accu-
mulator. The source operand can be a register, In °° ° I °
I
memory or immediate. See Appendix A for more on
the addressing modes supported by this instruction.
I
1
° I
I
I
The ORL instruction for byte-size operands has no
~=r>-XORY
effect on any of the flags. See Example 6-18.
155
CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS
Example 6-18
Show the results of the following.
MOV A,#04 ;A 04
ORL A, #30H ;A A OR 30H (now A ; 34H)
Solution:
04H 0000 0100
30H 0011 0000
34H 0011 0100 04H OR 30H ; 34H
XOR
XRL destination, source ;dest ; dest XOR source
This instruction will perform the XOR operation on the two operands, and
place the result in the destination. The destination is
normally the accumulator. The source operand can Logical XOR Function
be a register, in memory, or immediate. Sec
Appendix A.I for the addressing modes of this Inputs Output
instruction. The XRL instruction for byte-size x Y X XOR Y
operands has no effect on any of the flags. See o 0 0
Examples 6-19 and 6-20.
o I I
XRL can also be used to see if two registers I 0 I
have the same value. "XRL A, R1" will exclusive-or I I 0
register A and register RI, and put the result in A. If
both registers have the same value, 00 is placed in A.
Then we can use the JZ instruction to make a dcci-
~=J[)- X XOR Y
Solution:
54H 0101 0100
zaa 0111 1000.
2CH 0010 1100
54H XOR 78H _ 2CH
Example 6-20
Solution:
In the program in Example 6-21 notice the use of the JNZ instruction. JNZ
and JZ test the contents of the accumulator only. In other words, there is no such
thing as a zero flag in the 80SI. I
Another widely used application of XRL is to toggle bits of an operand.
For example, to toggle bit 2 of register A, we could use the following code. This
code causes D2 of register A to change to the opposite value, while all the other
bits remain unchanged.
Logical Inverter
MOV A, #55H
CPL A .now A;AAH Input Output
(AAH)
;01010101 becomes, 10101010 X NOT X
To get the 2's complement, all we, have to ~O ~I __
do is to add I to the I's complement. See Example :,.1 --"-0--
6-22. In other words, there is no 2's complement x --J>o- NOT X
instruction in the 8051. Notice that in comple-
Example 6-22
Find the 2 's complement of the value 8SH.
CPL A + 1
i 2 IS compo
ADD A, #1 0111 1011 ; 7BH
157
CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS
menting a byte, the data must be in register A. Although the CPL instruction
cannot be used to complement RO-R7, it does work on PO-P3 ports. See Appendix
A to see which addressing mode is available for the CPL instruction.
Compare instruction
The 8051 has an instruction for the compare operation. It has the follow-
ing syntax.
In the 8051, the actions of comparing and jumping are combined into a sin-
gle instruction called CINE (compare and jump ifnot equal). The CJNE instruc-
tion compares two operands, and jumps if they arc not equal. In addition, it
changes the CY flag to indicate if the destination operand is larger or smaller. It
is important to notice that the operands themselves remain unchanged. For exam-
pic, after the exccution of the instruction "CJNE A, #67H, NEXT", register A still
has its original valuc. This instruction compares register A with value 67H and
jumps to thc target address NEXT only ifrcgister A has a value other than 67H.
Example 6-23
MOV #55H
A,
CJNE A,#99H,NEXT
NEXT:
Solution:
(a) Yes, it jumps because 55H and 99H are not equal.
(b) A = 55H, Its ongInal value before the comparison.
. In CJNE, the destination operand can Table 6-3: Carry Flag Setting
be In the accumulator or in one of the Rn For CJNE Instruction
registers.
. .
The SOurceoperand can bC In . a
register, In mcmory, or immediatc S Compare
Carry Flag
A d' . ~ destination> Source CY 0
. ppen .IX A for the addrcssing modes ofth'
II1structlOn.This instruction affects thc ca~; destination < source CY-I
~_a3g only. CY ISchanged as shown in Table
158
Example 6-24
Write code to determine if register A contains the value 99H. If so make RI = FFR
otherwise, make Rl = O. "
Solution:
The following shows how the comparison works for all possible condi-
tions.
Example 6-25
Assume that PI is an input port connected to a temperature sensor. Write a program to
read the temperature and test it for the value 75. According to the test results, place the
temperature value into the registers indicated by the following.
1fT = 75 thenA=75
1fT < 75 then Rl = T
1fT> 75 then R2 =T
Solution:
Solution:
Example 6-27
Assume internal RAM memory locations 40H - 44H contain the daily temperature for
five days, as shown below. Search to see if any of the values equals 65. If value 65 does
exist in the table, give its location to R4; otherwise, make R4 = O.
40H= (76) 41H= (79) 42H= (69) 43H= (65) 44H= (62)
Solution:
MOV R4,#O ;R4=O
MOV RO,#40H ;load pointer
MOV R2,#05 ;load counter
MOV A,#65 ;A=65, value searched for
BACK: CJNE A,@RO,NEXT;compare RAM data with 65
MOV R4,RO ;if 65, save address
SJMP EXIT ;and exit
NEXT: INC RO ;otherwise increment pointer
DJNZ R2,BACK ;keep checking until count=O
EXIT ...
Review Questions
I. 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
2. To mask certain bits of the accumulator we must ANL it with
3. To set certain bits of the accumulator to I we must ORL it with---
4. XRLing an operand with itself results in _
5. True or false. The CJNE instruction altcr~c con;ents of its operands.
6. What value must R4 have in order for the following instruction not to jump?
CJNE R4,#53,OVER
7. Find the contents of register A after execution of the following code.
CLR A
ORL A, #99H
CPL A
;rotate left A
RL A
161
. OGIC INSTRUCTIONS, AND PROGRAMS
CHAPTER 6: ARITHMETIC, L
Rotating through the carry . h 805 J They involve the carry
There are two more rotate instructions In t e .
flag. Each is shown next.
Serializing data is a way of sending a byte of data one bit at a time through
aally:
single pin of microcontroller. There are two ways to transfer a byte of data seri-
1. Using the serial port. In using the serial port, programmers have very limited
control over the sequence of data transfer. The detai Is of serial port data trans-
fer are discussed in Chapter 10.
2. The second method of serializing data is to transfer data one bit at a time and
162
control the sequence of data and spaces in between them. In many new gen-
erations of devices such as LCD, ADC, and ROM, the serial versions of these
devices are becoming popular since they take less space on a printed circuit
board. Wc discuss this important topic next.
Example 6-29 shows how to bring in a byte of data serially one bit at a
time. We will see how to usc these concepts in Chapter 13 for a serial ADC chip.
Example 6-28
Write a program to transfer value 41H serially (one bit at a time) via pin P2.1. Put two
highs at the start and end of the data. Send the byte LSB first.
Solution:
MOV A,#41H
SETB P2.1 ;high
SETB P2.1 ;high
MOV RS, #8
HERE:RRC A
;send the carry bit to P2.1
MOV P2 .1,C
DJNZ RS, HERE
SETB P2.1 ;high
SETB P2.1 ;high
PIN
D 1...-_----
REG DI--"'~
E ll--·~
,
A
DO
P2.1 ,
07
163
LOGIC INSTRUCTIONS, AND PROGRAMS
CHAPTER6:A RlTHMETIC '
Example 6-29 . .. d
Write a program to bring in a byte of data sena. IIyon e bit at a time Via pm P2.7 an save
.. In regis. t er R2 . The byte comes in with the LSB first.
It
Solution:
MOV R5, #8
HERE:MOV C,P2. 7 bring in bit
RRC A
DJNZ R5, HERE
MOV R2,A ;save it
PIN
I p2.7I-~·~El--·~D
...__... 07
R_EG_A D DO
Aside from the fact that the carry flag (CY) is altercd by arithmetic and
logic instructions, in the 8051 there are also several instructions by which the CY
flag can be manipulatcd directly. These instructions are listed in Table 6-4.
Of the instructions in Table 6-4, we have shown the usc of lNC, CLR, and
SETB in many examples in the last fcw chaptcrs. The next few examples give
simple applications of the instructions in Table 6-4, including some dealing with
the logic operations AND and OR.
Example 6-30
Write a program to save the status of bits PI.2 and PI.3 on RAM bit locations 6 and 7,
respectively.
Solution:
MOV C,PI.2
MOV 06,C ;save status of PI.2 on Cy
MOV C, Pl.3 ;save carry in RAM bit location 06
MOV 07,C ;save status of PI.3 on CY
;save carry in RAM bit location 07
164
s
ORL Cfbit
, ORCY wit. h iInverted bit and save it on CY
Example 6-31
Assume that bit P2.2 is used to control an outdoor light and bit P2.5 a light inside a
building, Show how to turn on the outside light and turn off the inside one.
Solution:
SETB C ;CY = 1
ORL C,P2.2 iCY = P2.2 ORed with CY
MOV P2.2,C ;turn it "on" if not alr-eady "on"
CLR C ;CY = o
ANL C,P2.5 iCY = P2 .5 ANDed wi th CY
MOV P2.5,C ;turn it off if not already off
Example 6-32
Write a program that finds the number of Is in a given byte.
Solution:
;Rl keeps the number of Is
MOV Rl,#O
;counter = 08 rotate 8 times
MOV R7,#8
;find the number of Is in 97H
MOV A, #97H
;rotate it through the CY once
AGAIN: RLC A
NEXT ;check for CY
JNC ;if CY=1 then add one to count
INC Rl
;go through this 8 times
NEXT: DJNZ R7,AGAIN
SWAP A
Another useful instruction is the SWAP instruction. It works only on the
accumulator (A). It swaps the lower nibble and the higher nibble. In other words,
before: I 07 - 04 II 03 - 00 I Sa~~p I 03 - 00 II 07 - 04 I
before: I 0111
" 0010
after:
SWAP 0010 " 0111
Example 6-33
Solution:
(a)
MOV A,#72H ;A = 72H
SWAP A ;A = 27H
(b)
MOV A, #72H ;A=Olll 0010
RL A ;A=lllO 0100
RL A
;A=llOO 1001
RL A
;A=lOOl 0011
RL A ;A=OOlO 0111
Review Questions
-
CHA
3. WhatCLR
is theAvalue of register Aft·
a er each of the following. instructions?
.
SETB C
RRC A
SETB C
RRC A
4. Why does
. . "RLC R I" give . an error in the 805 I?
5. What IS in register A after the execution of the following code?
MOV A, #8SH .
SWAP A
ANL A,#OFOH
9. Show how to save the status of P2.? in RAM bit location 31.
1O. Show how to move the status of RAM bit location 09 to P 1.4.
ASCII numbers
On ASCII keyboards, when the key "0" is activated, "0 II 0000" (30/-1) is
provided to the computer. Similarly, 31H (01 J 000 I) is provided for the key" I",
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 usc ASCII, how does data get converted from ASCII to BCD, and
vice versa? These are the subjects covered next.
Packed BCD to ASCII conversion
Many systems have what is called a real-time clock (RTC). The RTC pro-
vides the time of day (hour, minute, second) and the date (year, month, day) con-
tinuously, regardless of whether the power is on or off (see Chapter 16). However,
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 0 II 0000 (30H). The following
demonstrates converting from packed BCD to ASCII. See also Example 6-34.
Packed BCD
Unpacked BCD
29H ASCII
02H & 09H
0010 1001 32H & 39H
0000 0010 &
0011 0010 &
0000 1001
0011 1001
ASCII to packed BCD conversion
After this conversion, the packed BCD numbers are processed and the
result will be in packed BCD format. As we saw earlier in this chapter, a special
instruction, "DA A", requires that data be in packed BCD format.
Example 6-34
Assume that register A has packed BCD. Write a program to convert packed BCD to
two ASCII numbers and place them in R2 and R6.
Solution:
Of course, in the above code we can replace all the RR instructions with a single
"SWAP A" instruction.
169
CHAPTER 6: ARITHMETIC, LOGJC INSTRUCTIONS, AND PROGRAMS
Example 6-35 .
000 '0'
001 'I'
010 '2'
011 '3' .
100 '4'
101 '5'
110 '6'
III '7'
Solution:
MOV DPTR,#MYTABLE
MOV A, PI ;get SW status
ANL A,#07H ;mask all but lower 3 bits
MOVe A,@A+DPTR ;get the data from look-up table
MOV P2,A ;display value
SJMP $ ; stay here
,"-------- -------------
ORG 400H
MYTABLE DB '0' 'I' '2' '3' t4
I , , 1
t
I '5' I '6' I '71
END
You can easily modify this program for the hex values of 0 - F, which are supplied by
4x4 keyboards. See Chapter 12 for a keyboard example.
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 checksum byte. The checksum byte is
an extra byte that is tagged to the end of a series of bytes of data. To calculate the
checksum byte of a series of bytes of data, the following steps can be taken.
To perform the checksum operation, add all the bytes, including the check-
sum 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 6-36.
170
Example 6-36
Assume that we have 4 byte f h .
(a) Find the checksum b t sOb exadecimal data: 25H, 62H, 3FH, and 52H.
integrity, and (c) ifthe s:C~~d
detects the error.
~\:~~~rm
y
the checksum operation to ensure data
has been changed to 22H, show how checksum
Solution:
(c) If the second byte 62H has been changed to 22H, show how checksum detects
the error. .
25H
+ 22H
+ 3FH
+ 52H
+ E8H
leOH (Dropping the carry, we get COH, which is not 00, and that means data
is corrupted.) .
·------------main program
, ORG 0
ACALL COPY DATA
ACALL CAL CHKSUM
ACALL TEST CHKSUM
SJMP $
-
Binary (hex) to ASCII conversion
Many ADC (analog-to-digital converter) chips provide output data in bina-
ry (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 P I and con-
verts it to decimal digits, and the second subroutine converts the decimal digits to
ASCIl 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 products use the Little-Endian convention.
END
173
OGIC INSTRUCTIONS, AND PROGRAMS
:HAPTER 6: ARITHME TIC , L
Review Questions
I. 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 isrructio is executed?
3. Does the register A have BCD data after the following mstruc Ion .
MOV A, #54
4. 67H in BCD when converted to ASCII is __ H and __ H ?
5. Does the following convert unpacked BCD in register A to ASCII.
MOV A,#09
ADD A,#30H
6. The checksum byte method is used to test data integrity in __ (RAM R~~J'
7. Find the checksum byte for the following hex values: 88H, 99H, AA, H ,
CCH,DDH
8. True or false. If we add all the bytes, including the checksum byte; and the
result is FFH, there is no error in the data.
SUMMARY
This chapter discussed arithmetic instructions for both signed and unsigned
data in the 8051. Unsigned data uses all 8 bits of the byte for data, making a range
of 0 to 255 decimal. Signed data uses 7 bits for data and I for the sign bit, mak-
ing a range of -128 to +127 decimal.
Binary coded decimal (BCD) data represents the digits 0 through 9. Both
packed and unpacked BCD formats were discussed. The 8051 contains special
instructions for arithmetic operations on BCD data.
In coding arithmetic instructions for the 8051, special attention has to be
given to the possibility of a carry or overflow condition.
This chapter also defined the logic instructions AND, OR, XOR, and com-
plement. In addition, 8051 Assembly language instructions for these functions
were described. Compare and jump instructions were described as well. These
functions are often used for bit manipulation purposes.
The rotate and swap instructions of the 8051 are used in many applications
such as serial devices. This chapter also described checksum byte data checking,
BCD and ASCll formats, and conversions. .
PROBLEMS
174
--------
2. Write a program to add all the digits of your lD number and save the result in
R3. The result must be in BCD
3. Write a program to add the following numbers, and save the result in R2, R3.
Thc data IS stored In on-chip ROM. '
ORG 250H
MYDATA: DB 53,94,56,92,74,65,43,23,83
4. Modify Problem 3 to make the result in BCD.
5. Write a program to (a) write the value 55H to RAM locations 40H - 4FH, and
(b) add all these RAM locations' contents together, and save the result in RAM
locations 60H and 61H.
6. State the steps that the SUBB instruction will go through and for each of the
following.
(a) 23H - 12H (b) 43H - S3H (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 result in RAM
memory locations starting at 40H.
10. Write a program to subtract 197F9AH from 34BC48H and save the result in
RAM memory locations starting at 40H.
II. Write a program to add BCD 197795H to 344548H and save the BCD result
in RAM memory locations starting at 40H.
12. Show how to perform 77 x 34 in the 805 I.
13. Show how to perform 77 -i- 3 in the 8051.
14. True or false. The MUL and DIY instructions work on any register of thc 805 j .
15. Write a program with three subroutines to (a) transfer the following data from
on-chip ROM to RAM locations starting at 30H, (b) add them and save the
result in 70H, and (c) find the average ofthc data and store it in R7. Notice that
the data is stored in a code space of on-chip ROM.
ORG 250H
MYDATA: DB 3,9,6,9,7,6,4,2,8
175
CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS
. c. h of the following and indicate the status of the OV
18. Write a program lor eac
flag for eaeh.
(a)(+15) + (-12) (b)(-123) + (-127)
(c) (+25H) + (+34H) (d) (-127) + (+127) .
19. Explain the difference between the CY and OV flags and where each one IS
used.
20. Explain when the OV flag is raised.
21. Which register holds the OV flag?
22. How do you detect the OV flag in the 8051? How do you detect the CY flag?
23. Assume that these registers contain the following: A = FO, B = 56, and R 1 =
90. Perform the following operations. Indicate the result and the register where
it is stored.
Note: The operations are independent of eaeh other.
(a) ANL A, #4SH (b) ORL A, B
(c) XRL A, #76H (d) ANL A, Rl
(e) XRL A,Rl (I) ORL A,Rl
(g) ANL A, #OFFH (h) ORL A, #99H
(i) XRL A, #OEEH 0J XRL A, #OAAH
24. Find the contents of register A after each of the following instructions
(a) MOV A, #6SH (b) MOV A, #70H .
ANL A,#76H ORL A,#6BH
(c) MOV A, #9SH (d) MOV A, #SDH
XRL A,#OAAH MOV R3,#78H
ANL A,R3
(e) MOV A, #OCSH (I) MOV A, #6AH
MOV R6,#12H MOV R4,#6EH
ORL A,R6 XRL A,R4
(g) MOV A,#37H
ORL A,#26H
25. True or false. In using the ClNE . .
'.
t he destination IIlstructlon ' we must use tIic accumulator as
26. Is the following a valid instruction? "CJNE R
27. Does the 8051 have a "ClE" (' . 4, #67, HERE"
28 [ di compare and jump if .
. n icatc the status ofCY after ClN . P I equal) instruction?
(a) MOV A, #2SH E IS executed in each of the following cases
CJNE A, #44H OVER (b) MOV A, #OFFH .
(c) MOV A, #34 ' CJNE A, #6FH, NEXT
CJNE A,#34,NEXT (d) MOV Rl,#O
(e) MOV RS,#S4H CJNE Rl,#O,NEXT
CJNE RS,#OFFH,NEXT (I) Mav A,#OAAH
A.."JL A, #55H
29. In Problem 28, indicate Whether 0 h CJNE
r not t e jurn h
°
A, # 0, NEXT
p appens for each case.
176
CHAP
SECTION 6.4: ROTATE INSTRUCTION AND DATA SERIALIZATION
30. Find the contents of register A after each of the following is executed,
(a) MOV A, #56H (b) MOV A, #39H '
SWAP A CLR C
RR A RL A
RR A RL A
SWAP A SWAP A
RRC A RLC A
RRC A RLC Ai'
RRC A
31. Show the code to replace the SWAP code
(a) using the rotate right instructions
(b) using the rotate left instructions
32. Write a program that finds the number of zeros in an 8-bit data item.
33, Write a program that finds the position of the first high in an 8-bit data item.
The data is scanned from DO to 07. Give the result for 68H,
34, Write a program that finds the position of the first high in an 8-bit data item,
The data is scanned from 07 to DO. Give the result for 68H.
35, A stepper motor uses the following sequence of binary numbers to move the
motor. How would you generate them? '
1100,0110,0011,1001
36. Write a program to convert a series of packed BCD numbers to ASCII. Assume
that the packed BCD is located in ROM locations starting at 300H, Place the
ASCII codes in RAM locations starting at 40H.
ORG 300H
MYDATA: DB 76H,87H,98H,43H
37. Write a program to convert a series of ASCII 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 PI, convert it to ASCII,
and save the result in RAM locations 40H, 41H, and 42H, What IS the result If
P I has 1000 1\ 0 I binary as input?
39. Find the result at points (I), (2), and (3) in the following code,
CJNE A,#50,NOT_EQU
, ;point (1)
NOT_EQU: JC NEXT
;point (2)
;point (3)
NEXT:
177
CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS
40 Assume that the lower four bits of P I are connected to four switches. Write a
. program to send the following ASCII characters to P2 based on the status of
the switches.
0000 '0'
0001 'I'
0010 '2'
0011 '3'
0100 '4'
0101 '5'
0110 '6'
0111 '7'
1000 '8'
1001 '9'
1010 'A'
1011 'B'
1100 'C'
1101 '0'
1110 'E'
Ij II 'F'
41. Find the checksum byte for the following ASCII message: "Hello"
42. True or false. If we add all the bytes, including the checksum byte, and the
result is DOH,then there is no error in the data.
43. Write a program: (a) To get the data "Hello, my fellow World citizens" from
code ROM, (b) to calculate the check-sum byte, and (c) to test the checksum
byte for any data error.
44. Give three reasons you should write your programs in modules.
45. To display data on LCD or PC monitors, it must be in (BIN, BCD,
ASCII).
46. Assume that the lower four bits of P I arc connectcd to four switches. Write a
program to send the following ASCII characters to P2 based on the status of
the switches. Do not use the look-up table method,
0000 '0'
0001 'I'
0010 '2'
0011 '3 '
0100 '4'
0101 '5'
0110 '6'
0111 '7'
1000 '8'
1001 '9'
ANSWERS TO REVIEW QUESTIONS
I. A, B
2. A, B
3. No. We must use registers A and B for this operation.
4. A, B
5. A, B
6. No. We must use registers A and B for this operation.
7. A, the accumulator
8. No. We must usc registers A and B for this operation.
9. MOV A, R1
ADD A,R2
10. A, the accumulator
II. (a) A = 00 and CY = I (b) A = FF and CY ~ 0
12.
43H 0100 0011 0100 0'011
.:..Q.5.!:! 0000 0101 2' s complement + 1111 .1011
3EH 0011 1110
13. A = 95H - 4FH'- I = 45H
SECTION 6.2: SIGNED NUMBER CONCEPTS AND ARITHMETiC OPERATIONS
I. 07
2. 16H is 00010110 in binary and its 2's complement is 1110 1010 or
-16H = EA in hex.
3. -128 to +127
4. +9 = 00001001 and -9 = 11110111 or F7 in hex.
5. An overflow is a carry into the sign bit (07), but the carry is a carry out of register (07).
I. 52H
2. 2AH
3. COH
4. Because all the rotate instructions work with the accumulator only
5. SOH
6. CY =0
7. CY= I
8. CY= I
9. MOV C, P2. 7 i save status of P2.7 on CY
carry in RAM bit location 06
MOV 31,C jsave
10. MOV C,9 ;save statuS of RAM bit 09 in CY
179
CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS
SECTION 6.5: BCD. ASCIJ, AND OTHER APPLICATION PROGRAMS
I. (a) 15H = 000 I 0101 packed BCD, 0000 000 I,00000 I0 I unpacked BCD
(b) 99H = 1001 1001 packed BCD, 00001001,00001001 unpacked BCD
2. 3736H = 00110111 OOIIOIIOB.
and in BCD we have 76H = 0111 OIIOB
3. No. We need to write it54H (with the H) or OIOIOIOOBto make it in BCD. The value 54
without the "H" is interpreted as 36H by the assembler.
-
4. 36H,37H
5. Yes, since A = 39H
6. ROM
7. 88H + 99H + AAH + BBH + CCH + DOH = 42FH. Dropping the carries we have 2FH, and
its 2's complement is OIH.
8. False
CHAPTER 7
8051 PROGRAMMING
INC
OBJECTIVES
181
Why program the 8051 in C?
Compilers produce hex files that we download into the ROM of the miero-
controller. The size of the hex file produced by the compiler IS one of the mam
concerns of microcontroller programmers, for two reasons:
How does the choice of programming language affect the compiled pro-
gram size'? While Assembly language produces a hex file that is much smaller
than C, programming in Assembly language is tedious and time consumrng, C
programming, on the other hand, is less time consuming and much easier to write,
but the hex file size produced is much larger than if we used Assembly language.
The following arc some of the major reasons for writing programs in C instead of
Assembly:
The study of C programming for the 8051 is the main topic of this chapter.
In Section 7.1, we discuss data types and time delays. I/O programming is shown
in Section 7.2. The logic operations AND, OR, XOR, inverter, and shift arc dis-
cussed in Section 7.3. Section 7.4 describes ASCII and BCD conversions and
checksums. In Section 7.5 we show how 8051 C compilers usc the program (code)
ROM space for data. Finally, in Section 7.6 data serialization for 8051 is shown.
In this section we first discuss C data types for the 8051 and then provide
code for time delay functions.
" Since one of the goals of 805 I C programmers is to create smaller hex files,
It IS worthwhile to re-examine C data types for 8051 C. In other w d d
d d' or s, a goo
un erstan II1g of C data types for the 805 I can help programmcrs to create small-
er hex files. In this section we focus on the specific C data types that are most use-
ful and Widely used for the 8051 microcontroller.
Unsigned char
Example 7-1
Write an 8051 C program to send values 00 - FF to port PI.
Solution:
#include <reg51.h>
void main(void)
{
unsigned char Z;
for(z=O;z<=255;Z++)
Pl=z;
Run the above program' on your simulator to see how PI displays values 00 - FFH in
binary.
Example 7-2
Write an 8051 C program to send hex values for ASCII characters of 0, I, 2, 3, 4, 5, A,
S, C, and D to port PI.
Solution:
#include <reg51.h>
void main (void)
{
unsigned char mynum [] = "012345ABCD";
unsigned char Z;
for(z=O;z<=lO;Z++)
Pl=mynum[z] ;
}
. lator to see how PI displays values 30H, 3\ H,
Run the above program ~ ~~~ s;:;~ and 441-1the hex values for ASCII 0, 1, 2, and
32H, 33H, 34H, 35H, 41, " ,
so on.
183
CHAPTER 7: 8051 PROGRAMMING IN C
Example 7-3
Write an 8051 C program to toggle all the bits ofPl continuously,
Solution:
II Toggle PI forever
#include <regSI.h>
void main(void)
{
for (;;) Ilrepeat forever
(
PI=OxSS; Ilox indicates the data is in hex (binary)
Pl=OxAA;
Run the above program on your simulator to see how PI toggles continuously.
Examine the asm code generated by the C compiler.
Signed char
The signed char is an 8-bit data type that uses the most significant bit (07
of 07 - DO) to represent the - or + value. As a result, we have only 7 bits for the
magnitude of the signed number, giving us values from -128 to + 127. In situa-
tions where + and - are needed to represent a given quantity such as temperature,
the use of the signed char data type is a must.
Again notice that if we do not use the keyword unsigned, the default is the
signed value. For that reason we should stick with the unsigned char unless the
data needs to be represented as signed numbers.
Example 7-4
Solution:
Iisign numbers
#include <regSl.h>
void main (void)
{
char mynum[]= {+1,-1,+2/-2,+3,-3,+4,_4}j
unsigned char z;
for(z=O;z<=8;z++)
PI=mynum [zj .
Run the above program on your simulator to see how PI displays values of I FFH 2
FEH, 3, FDH, 4, and FCH, the hex values for + I _I +2 -2 d " ,
, , , ,an so on,
184
Unsigned int
The unsigned int is a lti-bit data type that takes a value in the range of 0 to
65535 (0000 - FFFFH). In the 8051, unsigned int is used to define l6-bit variables
such as memory addresses. It is also used to set counter values of more than 256.
Since the 8051 is an 8-bit microcontroller and the int data type takes two bytes of
RAM, wc must not use the int data type unless we have to. Since registers and
memory accesses are in 8-bit chunks, the misuse of int variables will result in a
larger hex file. Such misuse is not a big deal in PCs with 256 megabytes of mem-
ory, 32-bit Pentium registers and memory accesses, and abus speed of 133 MHz.
However, for 805\ programming do not use unsigned int in places where
unsigned char will do the job. Of course the compiler will not generate an error
for this misuse, but the overhead in hex file size is noticeable. Also in situations
where there is no need for signed data (sueh as setting counter values), we should
usc unsigned int instead of signed int. This gives a much wider range for data dec-
laration. Again, remember that the C compiler uses signed int as the default if we
do not use the keyword unsigned.
Signed int
Signed int is a 16-bit data type that uses the most significant bit (D 15 of
DIS - DO) to represent the - or + value. As a result, we have only 15 bits for the
magnitude of the number, or values from -32,768 to +32,767.
Solution:
#include <reg5l.h>
sbit MYBIT = P1AO; //notice that sbit is
//declared outside of main
void main (void)
{
unsigned int z,
for (z=O; z<=50000; z++)
{
MYBIT = 0;
MYBIT = 1;
}
}
. 1 tor to see how P 1.0 toggles continuously.
Run the above program on your SII11U a
185
CHAPTER 7: 8051 PROGRAMMING IN C
Bit and sfr
Time Delay
. For the above reasons, When we write time delays lor C, we must use the
oscilloscopc to measure the exact duration. Look at Examples 7-6 through 7-8.
186
Example 7-6
Write an 8051 C program to toggle bits of Pl continuously forever with some delay.
Solution:
// Toggle PI forever with some de'lay in between "on" and "off".
#include <reg51.h>
void main (void)
{
unsigned int X;
fort; ;) //repeat forever
{
Pl=Ox55;
for(x=O;x<40000;x++); //delay size unknown
Pl=OxAA;
for(x=0;x<40000;x++) ;
}
}
Example 7-7
Write an 8051 C program to toggle the bits of PI ports continuously with a 250 ms
delay.
Solution:
The program below is tested for the DS89C420 with XTAL = 11.0592 MHz.
#include <reg51.h>
void MSDelay(unsigned inti;
void main (void)
{
while (1) //repeat forever
(
Pl=Ox55;
MSDelay (250) ;
Pl=OxAA;
MSDelay(250) ;
}
187
CHAPTER 7: 8051 PROGRAMMING IN C
Example 7-8 .
}
void MSDelay(unsigned int itime)
{
unsigned int i, j;
for(i;O;i<itime;i++)
for(j;0;j<1275;j++) ;
Review Questions
I. Give the magnitude of the unsigned char and signcd char data types.
2. Give the magnitude of the unsigned int and signed int data types.
3. If we are declaring a variable for a person's age, we should usc the _ data
type.
4. True or false. Using a for loop to create a time delay is not recommended if
you want your code be portable to other 8051 versions.
5. Give three factors that can affect the delay size.
In this section we look at C programming of the 1/0 ports for the 805J. We
look at both byte and bit 1/0 programming.
188
Example 7-9
LEDs are connected to bits P I and P2. Write an 8051 C program that shows the count
from 0 to FFH (0000 0000 to 1111 1111in binary) on the LEDs.
Solution:
#include <regs1.h>
#define LED P2 //notice how we can define P2
void main (void)
{
P1:OO; //clear P1
LED:O; //clear P2
for( ; ;) //repeat forever
{
Pl++i //increment P1
LED++ i //increment P2
}
Example 7-10
Write an 8051 C program to get a byte of data from PI, wait 112 second, and then send
it to P2.
Solution:
#include <regS1.h>
void MSDelay(unsigned int);
void main (void)
{
unsigned char mybyte;
P1:OxFF; //make P1 an input port
while (1)
{
mybyte:P1; //get a byte from P1
MSDelay (500) ;
p2:mybyte; //send it to P2
189
CHAPTER 7: 8051 PROGRAMMING IN C
Example 7-11
Write an 8051 C program to get a byte of data from PO. If it is less than 100, send it to
PI; otherwise, send it to P2.
Solution:
#include <regSl.h>
void main(void)
Example 7-12
Writeof an
rest the8051 C P2.
bits of program to toggle only bit P2.4 continuously without disturbing the
Solution:
sbit main(void)
void mybit = P2 4; Iinotice the way single bit is declared
{
while (1)
{
mybit=l;
Ilturnonp2.4
mybit=O;
/Iturn off P2.4
190
Example 7-13
Write an 8051 C program to monitor bit P 1.5. If it is high, send 55H to PO; otherwise,
send AAH to P2.
Solution:
#include <regS1.h>
sbit mybit = P1AS; //notice the way single bit is declared
void main (void)
{
mybit=l; //make mybit an input
while (1)
(
if (mybit==l)
PO=OxSS;
else
P2=OxAA;
}
}
Example 7-14
A door sensor is connected to the PI.I pin, and a buzzer is connected to PI.7. Write an
8051 C program to monitor the door sensor, and when it opens, sound the buzzer. You
can sound the buzzer by sending a square wave of a few hundred Hz.
SOlution:
#include <regS1.h>
void MSDelay(unsigned intl ;
sbit Dsensor = P1A1; //notice the way single bit is defined
A
sbit Buzzer = P1 7;
void main(void)
{
Dsensor=l; //make P1.1 an input
while (Dsensor==l)
{
buzzer=O;
MSDelay(200) ;
buz~er=l;
MSDelay (200) ;
}
}
unsigned int i, j;
for(i=O;i<itime;i++)
for(j=O;jd27S;j++) ;
19\
CHAPTER 7: 8051 PROGRAMMING IN C
Example 7-15 .. .
Solution:
#include <regsl.h>
#define LCDData PI IILCDData declaration
A
sbit En=P2 O; lithe enable pin
void main (void!
(
unsigned char message [ ]= "The Earth is but One Country";
unsigned char Z;
for(z=O;Z<28;z++) Iisend all the 28 characters
(
LCDData=message[z] ;
En=l; Iia high-
En=O;
II-to-low pulse to latch the LCD data
)
}
Run the above program on your simulator to see how P I displays each character of
the message. Meanwhile, monitor bit P2.0 after each character is issued.
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 wc specify the bit address as shown in Example 7-17. Both the bit and byte
addresses for the PO - P3 ports are given in Table 7-2. Notice in Examples 7-16
and 7-17, that there is no #include <reg51.h> statement. This allows us to access
any byte of the SFR RAM space 80 - FFH. This is a method widely used for thc
new generation of 8051 microcontrollers, and we will usc it in future chapters.
-
CI
Example 7-16
Write an 8051 C program to toggle all the bits of PO, PI, and P2 continuously with a
250 ms delay. Use the sfr keyword to declare the port addresses.
Solution:
II Accessing Ports as SFRs using the sfr data type
sfr PO = OX80; Iideclaring PO using sfr data type
sfr PI = OX90;
sfr P2 = OxAO;
void MSDelay(unsigned int);
void main (void)
{
while (1) lido it forever
{
PO=Ox55;
Pl=Ox55 ':
P2=Ox55';
MSDelay (250) ; 11250 ms delay
PO=OxAA;
PI=OxAA;
P2=OxAA;
MSDelay(250) ;
}
}
Example 7-17
Write an 805 J C program to turn bit P 1.5 on and off 50,000 times.
Solution:
193
fAPTER 7: 8051 PROGRAMMING IN C
. ddressable RAM
.
bit data type for bit-a ble SFR registers only.
Using . d for bit-addressa . f the data
. d type IS use . dd essable section 0
The sbit ala tore some data in a bit-a r· as shown in Example
Sometimes we need to s d that we usc the bit data type,
RAM space 20 - 2FH. To 0 ,
7-18.
Example 7-18 f bit PI .,a save it, and send it to P2.? con-
. an 8051 C program to get the status 0 I
Write
tinuously.
Solution:
Review Questions
I. The address of P I is -:-_
2. Write a short program that toggles all bits of P2.
3. Write a short program that toggles only bit PI.O. . I bit
4. True or false. The sbit data type is used for both SFR and RAM sing c- 1
addressable locations.
5. True or false. The bit data type is used only for RAM single-bit addressable
locations.
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.
194
Bit-wise operators in C
While every C programmer is familiar with the logical operators AND
(&&), OR (II), and NOT (!), many C programmers are less familiar with the bit-
wise operators AND (&), OR (I), EX-OR ("), Inverter H, Shift Right (»), and
Shift Left «<). These bit-wise operators are widely used in software engineering
for embedded systems and control; consequently, understanding and mastery of
them are critical in microprocessor-based system design and interfacing. See
Table 7-3.
Table 7-3: Bit-wise Logic Operators for C
AND OR EX-OR Inverter
A B A&B AlB A"B Y~B
0 0 0 0 0 1
0 1 0 I 1 0
I 0 0 1 I
1 1 I I 0
Example 7-19
Run the following program on your simulator and examine the results.
Solution:
#include <reg5I.h>
void main (void)
{
PO= ox35 & OxOF; I lANDing
PI= Ox04 I Ox68; IIORing
P2= Ox54
A
Ox?8; IIXORing
PO= -Ox55; Ilinversing
3; Iishifting right 3 times
PI= Ox9A »
4; Iishifting right 4 times
P2= Ox?? »
4; Iishifting left 4 times
PO= Ox6 «
}
195
CHAPTER 7: 8051 PROGRAMMING IN C
Solution: . · h XTAL = 11 .0592 MHz.
d for the DS89C420 WIt
The program below IS teste
Uinclude <reg51.h>
void MSDelay(unsigned inti ;
void main(voidl
(
PO;Ox55;
P2=Ox55;
while (1)
(
PO;-PO;
P2;-P2;
MSDelay(250) ;
There are two bit-wise shift operators in C: (I) shift right ( »), and
(2) shift left (<<).
Study Examples 7-21,7-22, and 7-23, showing how the bit-wise operators
are used in the 805 J C.
196
Example 7-21
Write
250 msandelay
8051 UsC program
th E to
0 togg I-eat 11 h e bits
. of PO, PI, and P2 continuously
. with a
. e e x- R operator.
Solution:
The program below is tested for the DS89C420 with XTAL = II 0592 MH
#lnclude <reg51.h> . z.
void MSDelay(unsigned int);
void main (void)
{
PO~Ox55;
Pl~Ox55;
P2~Ox55;
while(l)
{
PO=POAOxFF;
Pl=P1AOxFF;
P2=P2AOxFF;
MSDelay (250);
}
}
Example 7-22
Write an 8051 C program to get bit Pl.O and send it to P2.7 after inverting it.
Solution:
#include <reg5l.h>
sbit inbit=P1AO;
A //sbit is used declare port (SFR) bits
sbit outbit=P2 7;
//notice this is bit-addressable memory
bit membit;
void main(void)
{
while (1)
{ //get a bit from Pl.O
membit=inbit; //invert it and send it to P2.7
outbit=-membit;
}
}
197
CHAPTER 7: 8051 PROGRAMMING IN C
Example 7-23 d the P 1.0 and PI. J bits
. an d issue an ASCII character to
. 51 C program to rea
Write an 80 he following table.
PO accordmg to t
PI.I PI.O
o 0 sen d '0' to PO
o I send']'toPO
I 0 send '2' to PO
I I send '3' to PO
Solution:
#include <reg5l.h>
VOlid main (voi d)
{
unsigned char z;
z=Plj //read PI
z=z&Ox3; //mask the unused bits
switch(z) / /rnake decision
(
case (0):
(
po= ' 0 I ; / / issue ASCII 0
break;
)
case n ) .
{
po= II! i / / issue ASCII I
break;
}
case tz) :
(
PO=' 2' ; / / issue ASCII 2
break;
)
case (3) :
(
PO='3 1;
/ / issue ASCII 3
break;
Review Questions
198
SECTION 7.4: DATA CONVERSION PROGRAMS IN 8051 C
ASCII numbers
. On ASCII keyboards, when thc key "0" is activated, "0 II 0000" (30H)' is
provided to the computer. Similarly, 31H (01 I 0001) is provided for the kcy "I",
and so on, as shown in Table 7-4.
199
CHAPTER 7: 8051 PROGRAMMING IN C
unpacked BCD Packed BCD
Key ASCII
4 34 00000100
00000111 01000111 or 47H
7 37
After this conversion, the packed BCD numbers are processed and the
result will be in packed BCD format. Chapter 16 discusses the RTC ehip and uses
the BCD and ASCrr conversion programs shown in Examples 7-24 and 7-25.
Example 7-24
Writean 8051 C program to convert paeked BCD Ox29 to ASCII and display the b te
on PI and P2. y s
Solution:
#include <regSI.h>
void main (void)
{
unsigned char x, y, Z;
unsigned char mybyte ; OX29;
x ; mybyte & OxOF' //mask lower 4 bits
PI; x I OX30; r //make it ASCII
Y ; mybyte & OxFO', //mask upper 4 bits
y;y»4; //shift it to lower 4 bits
P2 ; Y I OX30; //make it ASCII
Example 7-25
Write an 8051 C program to convert ASC rr di .
play them on PI. igits of'4' and '7' to packed BCD and dis-
Solution:
#i~clude <regSI.h>
vord main (void)
{
unsigned char bcdbyte;
unsigned char w:;: 141 j
unsigned char z:::: 7 j I I
w ; W & OXOF.
II W ::: W < 4.
Z = Z & OX;F.
I
//mask 3
//shift left
I/mask 3
to make upper BCD d'19lt
.
bCdbyte = W I' z .
PI ; bCdbyte., ' I/combine to make packed BCD
200
c1
Checksum byte in ROM
To ensure the integrity of 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 checksum byte. 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 .
. I. 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 check-
sum 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 bytes 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 check-
sum detects the error.
Solution:
(c) If the second byte 62H has been changed to 22H, show how checksum detects
the error.
25H
+ 22H
+ 3FH
+ 52H
+ EBH d)
1COH (Dropping the carry, we gel COH, which means data is corrupte .
201
CHAPTER 7: 8051 PROGRAMMING IN C
&
Example 7-27
Write an 8051 C program to ca Icu Iate the checksum byte for the data given in Example
7-26.
Solution:
#include <reg51.h>
void main (void)
Single-step the above program on the 8051 simulator and examine the contents of P I
and P2. Notice that each byte is put on P j as they are added together.
Example 7-28
Write an 8051 C program to perform step (b) of Example 7-26. If data is good, send
ASCII character 'G' to PO. Otherwise send 'B' to PO.
Solution:
#include <reg51.h>
void main (void)
(
The printf function is part of the standard I/O library in C and can do many
things, including converting data from binary (hex) to decimal, or vice versa. But
printf takes a lot of memory space and increases your hex file substantially .. For
this reason, in systems based on the 8051 microcontroller, it is better to write your
own conversion function instead of using printf.
One of the most widely used conversions is the binary to decimal conver-
sion. Tn devices such as AOC (Analog-to-Digital Conversion) chips, the data is
provided to the microcontroller in binary. In some RTCs, data such as time and
dates are also provided in binary. In order to display binary data we need to con-
vert it to decimal and then to ASCII, Since the hexadecimal format is a conven-
ient way of representing binary data we refer to the binary data as hex. The bina-
ry data 00 - FFH converted to decimal will give us 000 to 255. One way to do that
is to divide it by 10 and keep the remainder, as was shown in Chapter 6. For exam-
ple, 1111110 I or FOH is 253 in decimal. The following is one version of an algo-
rithm for conversion of hex (binary) to decimal:
Quotient Remainder
FD/OA 19 3 (low digit) LSD
19/0A 2 5 (middle digit)
2 (high digit) (MSO)
Example 7-29
Write an 8051 C program to convert 11111101(FD hex) to decimal and display the dig-
its on PO, PI, and P2.
SOlution:
#include <reg51.h>
void main (void)
{
unsigned char x, binbyte, d1, d2, d3;
binbyte ; OXFD; Ilbinary(hex} byte
x ; binbyte I 10; Iidivide by~O
d1 ; binbyte % 10; I Ifind remal~der (LSD)
d2 ; x % 10' Ilmiddle d i.q
i t; .'
' Ilmost significant di q i t (MSD)
d3 ; X I 10; .
PO = d1;
PI = d2;
P2 ; d3;
}
203
CHAPTER 7: 8051 PROGRAMMING IN C
Review Questions
.
I. For the following decimal numbers,. give
. the Packcd BCD and unpacked BCD
representations.
(a) 15 (b) 99 f t for "76" and its BCD version.
2. Show the binary and hex orma ~SC" . Hand H
3 67H in BCD when converted to IS -- . --.. to ASCII?
4.. Does the following convert unpacked BCD In register A
mydata ~ Ox09 + Ox30; ?
Why is the use of packed BCD preferable to ASCII.
5. Which one takes more memory space: packed BCD or ASCII?
~: In Question 6, which is more universal? I 22H 76"H 5FH 8CH 99H
Find the checksum byte for the following va ues; . ' , , , .
8. To test data integrity, we add them together, includmg the checksum byte. Then
9. dro the carries. The result must be equal to __ If the data IS not corrupted.
10. An ~DC provides an input of 0010 0110. What happens if we output that to
the screen?
Using the code (program) space for predefined data is the widely used
option in the 8051, as we saw in Chapter 5. In that chapter we saw how to use the
Assembly language instruction MOVe to access the data stored In the 8051 code
space. In this chapter, we explore the same concept for 8051 C.
RAM data space v. code data space
In the 8051 we have three spaces in which to store data. They arc as fol-
lows:
I. The 128 bytes of RAM space with address range 00 - 7FH. (In the 8052, it is
256 bytcs.) We can read (from) or write (into) this RAM space directly or indi- .
rectly using the RO and R I registers as we saw in Chapter 5.
2. The 64K bytes of code (program) space with addresses of 0000 _ FFFFH. This
64K bytes of on-chip ROM space is used for storing programs (opcodes) and
therefore is directly under the control of the program counter (PC). We can use
the "MOve A, @A+DPTR" Assembly language instruction to access it for
data (see Chapter 5). There are two problems with using this code space for
data. First, since it is ROM memory, we can bum Our predefined data and
tables into it. But we cannot write into it during the execution of the program.
The second problem is that the more of this code space we use for data, the less
is left for our program code. For example, if we have an 8051 chip such as
DS89C420 with only 16K bytes of on-chip ROM, and we usc 4K bytes of it to
store some look-up table, only 12K bytes is left for the code program. For
some applications this can be a problem. For this reason Intel created another
memory space called external memory especially for data. This is discussed
next very briefly and we postpone the full discussion to Chaptcr 14.
204
CHAP
3. The 64K bytes of external memory, which can be used for both RAM and
ROM. This 64K bytes is called external since we must use the MOVX
Assembly language instruction to access it. At the time the 8051 was designed,
the cost of on-chip ROM was very high; therefore, Intel used all the on-chip
ROM for code but allowed connection to external RAM and ROM. In other
words, we have a total of 128K bytes of memory space since the off-chip or
external memory space of 64K bytes plus the 64K bytes of on-chip space pro-
vides you a total of 128K bytes of memory space. We will discuss the exter-
nal memory expansion and how to access it for both Assembly and C in
Chapter 14.
Next, we discuss on-chip RAM and ROM space usage by the 8051 C com-
piler. We have used the Proview32 C compiler ro verify the concepts discussed
next. Use the compiler of your 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 J 28
bytes of RAM space is used mainly by register banks and the stack. Whatever
remains is used for scratch pad RAM. The 8051 C compiler first allocates the first
8 bytes of the RAM to bank 0 and then some RAM to the stack. Then it starts to
allocate 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 the range of 50 - 7FH. This allows us to allocate
contiguous RAM locations to array elements.
In cases where the program has individual variables in addition to array
elements, the 8051 C compiler allocates RAM locations in the following order:
1. Bank 0 addresses 0 -,7
2. Individual variables addresses 08 and beyond
3. Array elements addresses right after variables
4. Stack addresses right after array elements
7F
You can verify the above order by
running Example 7-30 on your 8051 C Scratch Pad RA M
simulator and examining the contents of
the data RAM space. Remember that 30
205
CHAPTER,7: 8051 PROGRAMMING IN C
Example 7-30 8051 simulator. Examine the
. h fi llowing program on your
Compi Ie and single-step teo I te the ASCII values.
contents of the I28-byte RAM space to oca
Solution:
#include <regsl.h>
void main(void)
Run the above program on your 8051' sirnu lator and ASCIIexamineI ttthe RAM space'C'to and
'A' '8' locate
so
va Iues
41 H., 42H , 43H , 44H , etc ., the hex values for e ers , , ,
on.
Example 7-31
Write, compile, and single-step the following program on your 805 J simulator.
Examine the contents of the code space to locate the values.
Solution:
#include <regsl.h>
void main(void)
{
unsigned char mydata(lOO]; 11100 byte space in RAM
unsigned char x,z=O;
for(x=O;x<lOO;x++)
z--;
Ilcount down
mydata[x]=z;
Iisave it in RAM
Pl=z;
} Ilgive a copy to PI too
Run the above program on your 8051 simulator and examine the data RAM space to
locate values FFH, FEH, FDH, and so on in RAM.
Intel 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 with the 8051. This means that any program written
for the 8051 will run on the 8052, but not the other way around since some fea-
206
-
tures 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 majority of the new versions of the 8051 such as DS89C4xO arc
really based on 8052 architecture, you should compile your C programs for the
8052 microcontroller. We do that by (I) using the reg52.h header file, and (2)
choosing the 8052 option when compiling the program.
Example 7-32 shows how to use code space for data in 8051 C.
Example 7-32
Compile and single-step the following program on your 8051 simulator. Examine the
contents of the code space to locate the ASCII values.
Solution:
#include <reg51.h>
void main (void)
{
code uns igned char mynum[]; "ABCDEF"; Iluses code space
Ilfor data
unsigned char z;
for(z;O;z<;6;z++)
Pl;mynum [z] ;
}
51 simulator and examine the code space to locate
Run the above program on your 80 f 'A' 'B' 'C'
43H 44H etc the hex values for ASCII characters a , , ,
va 1ues 41H , 42H , , , 0'
and so on.
Compiler variations
shows three different versions of a program that
Look at Examp Ie 7 -33 . It . '. h h 8051 C
." LO" to the PI port. Compile each program WIt t e
sends the stnng HEL the hex file size Then compile each pro-
compiler of your choice and co~pare d examine tile hex file size to see the effec- .
gram on a different 8051 C com;~ e~: MicroDigilalEd.com for 8051 C compil-
tiveness of your C compder. e .
ers.
207
CHAPTER 7: 8051 PROGRAMMING IN C
Example
Compare 7-33 . programs an d discuss the advantages and disad-
and contrast the following
vantages of each one.
(a)
#include <regSl.h>
void main(void)
{
PI:::: I H' i
PI:::: E
I r ;
Pl='Lr i
Pl='L'j
PI= '0' i
(b)
#include <regSl.h>
void main (void)
{
unsigned char mydata []= "HELLO" ;
unsigned char z;
for(z=O;z<=S;z++)
P1=mydata Izl ;
(c)
#include <regSl.h>
void main (void)
{
//Notice Keyword code
code unsigned char mydata [J = "HELLO";
unsigned char Z;
for(z=o;z<=s;z++)
Pl=mydata[z] ;
}
Solution:
All the programs send out "HELLO" to P I, one character at a time, but they do it in dif-
ferent ways. The first one is short and simple, but the individual characters are embed-
dcd into the program. ]f 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 separate
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 upgrad-
gramif(a).
able we want to change the string itself or make it longer. That is not the case for pro-
See the following Web sit~sfor 8051 C compilers:
www.MicroDigitaIEd.com
www.8052.com.
Review Questions
1. The 8051 has __ bytes of data RAM, while the 8052 has bytes.
2. The 8051 has __ K bytes of code space and __ K bytes of external data
space.
3. True or false. The code space can be used for data but the external data space
cannot be used for code.
4. Which space would you use to declare the following values for 8051 C?
(a) the number of days in the week .
(b) the number of months in a year
(c) a counter for a delay
5. In 8051 C, we should not use more than 100 bytes of the RAM dataspace for
variables. Why?
Serializing data is a way of sending a byte of data one bit at a time through
a single pin of mir.rocontroller. There are two ways to transfer a byte of data
serially:
I. Using the serial port. When using the serial port, the programmer has very
limited control over the sequence of data transfer. The detail of serial port data
transfer is discussed in Chapter 10.
2. The second method of serializing data is to transfer data one bit a time and con-
trol the sequence of data and spaces in between them. In many new generations
of devices such as LCD, ADC, and ROM the serial versions are becoming pop-
ular since they take less space on a printed circuit board.
Examine the next four examples to see how data serialization is done in
8051 C.
209
CHAPTER 7: 80S1 PROGRAMMING IN C
Example 7-34
Write a C program to send out the value 44H serially one bit at a time via P 1.0. The
LSB should go out first.
Solution:
((SERIALIZING DATA VIA Pl.0 (SHIFTING RIGHT)
#include <regsl.h>
sbit PlbO = PIAO;
sbit regALSB = ACCAO;
void main (void)
PIN
DL-__
D7
R_E_G_A Df---~.1
DO
P1.O'
Example 7-35
Write a C program to send out the value 44H serially one bit at a time . PI 0 The
MSB should go out first. via ..
Solution:
((SERIALIZING DATA VIA Pl.0 (SHIFTING L
#1nclude <regSl.h> EFT)
sbit PlbO = PI O'A
sbit regAMSB = AC~A7'
void main (void) ,
Solution:
//BRINGING IN DATA VIA PI.O (SHIFTING RIGHT)
#include <reg51.h~
sbit PIbO = PIAO;
A
sbit ACCMSB = ACC ?;
void main (void)
PIN
Example 7-37
Write a C program to bring in a byte of data serially one bit at a time via PI.O. The MSB
should come in first.
Solution:
//BRINGING DATA IN VIA PI.O (SHIFTING LEFT)
#include <reg51.h~
sbit PIbO = PIAO;
sbit regALSB = ACCAO;
void main (void)
unsigned char x;
for(x=O; x<8; x++)
{
regALSB = PIbO;
ACC = ACC « 1;
}
P2=ACC;
}
211
CHAPTER 7: 8051 PROGRAMMING IN C
SUMMARY
PROBLEMS
I. Indicate what data type you would use for each of the following variables:
(a) the temperature
(b) thc number of days in a week
(e) the number of days in a year
(d) the number of months in a year
(e) the counter to keep the number of people getting on a bus
(I) the eounter to 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 state-
ments:
(a) PI=14; (b) PI=OxI8; (e) PI:' A' ; (d) PI=?;
(e) PI=32; (f) PI=Ox45; (g) Pl=255; (h) PI=OxOF;
3. Give three factors that can affect time delay code size in the 8051 rrucrocon-
troller.
4. Of the three factors in Problem 3, which one can be set by the system design-
er?
5. Can the programmer set the number of clock cycles used to execute an instruc-
tion? Explain your answer.
6. Explain why various 8051 C compilers produce different hex file sizes.
7. What is the difference between the sbit and bit data types?
8. Write an 8051 C program to toggle all bits of PI every 200 ms.
9. Use your 8051 C compiler to see the Shortest time delay that you can produce.
10. Write a lime delay funetion for 100 ms,
II. Write an 8051 C program to toggle only bit P 1.3 every 200 ms.
12. Write an 8051 C program to Count up PI from 0 _ 99 eontinuously.
212
SECTION 73: LOGIC OPERATIONS IN 8051 C
I
19. Write a program to convert the following series of packed BCD numbers to
ASCIl. Assume that the packed BCD is located in data RAM. :
76H,87H,98H,43H
20. Write a program to convert the following series of ASCII numbers to packed
BCD. Assume that the ASCII data is located in data RAM. ' I
"8767"
21. Write a program to
gct an 8·bit binary number from PI, convert it to ASCII,
and save the result if the input is .packed BCD of 00 . Ox99. Assume P I has
1000 100 I binary as input.
22. Indicate what memory (embedded, data RAM, or code ROM space) you would
use for the following variables:
(a) the temperature
(b) the number of days in 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 getting on a bus
(f) the counter to keep the number of people gomg to a class
(g) an address of 64K bytes RAM space
(h) the voltage· . .
(i) a string for a message to welcome people to building
213
CHAPTER 7: 8051 PROGRAMMING IN C
23. Discuss why the total size of your 8051 C variables should not exceed 100
bytes.
24. Why do we usc the ROM code space 'for video game characters and shapes?
25. What is the drawback of using RAM data space for 8051 C variables?
26. What is the drawback of using ROM code space for 805 J C data?
27. Write an 8051 C program to send your first and last names to P2. Use ROM
code space.
I. 0 to 255 for unsigned char and -128 to +127 for signed char
2. 0 to 65,535 for unsigned int and -32,768 to +32.767 for signed int
3. Unsigned char
4. True
5. (a) Crystal frequency of8051 system, (b) 8051 machine eycle timing and (c) compiler use for
8051 C '
I. 90H
2. #include <reg51.h>
void rnainj)
1
P2 = Ox55;
P2 = OxAA
}
3. #include <reg51.h>
sbit PIObit = PIAO;
void mainO
{
PIObit = 0;
PIObit = I;
}
4. False, only to SFR bit
5. True
214
3. 36H,37H
4. Yes, since A = 39H
5. Space savings
6. ASCII 7. ASCII
8. 21CH
9. 00
10. First convert from binary to decimal, then to ASCII, then send to screen.
I. 128,256
2. 64K,64K
3. True
4. (a) data space, (b) data space, (c) RAM space
5. The compiler starts storing variables in code space.
215
CHAPTER 7: 8051 PROGRAMMING IN C
CHAPTER 8
8051 HARDWARE
CONNECTION AND
INTEL HEX FILE
OBJECTIVES
217
This chapter describes the process of physically connecting and testing
805 l-based systems. In the first section we describe the function of the pins of
8051 chip. The second section shows the hardware connection for an 8051 Trainer
using the DS89C4xO (DS89C420/30/40/50) chip. It also shows how to download
programs into a DS89C4xO-based system using PC HyperTerminal. In Section 8.3
wc explain thc characteristics of the Intel hex file.
PDIP/Cerdip
P1.0 1 40 Vee
P1.1 2 39 PO.O(ADO)
P1.2 3 38 P01 (AD1)
P1.3 4 37
P1.4
8051/52 PO.2 (AD2)
5 36 PO.3 (AD3)
P1.5 6
(DS89C4xO
35 POA (AD4)
P1.6 7 AT89C51 34 PO.5 (ADS)
P1.7 8 8031) 33 P06 (AD6)
RST 9 32 PO.7 (AD7)
(RXD) P3.0 10 31 EANPP
(TXD) P3.1 11 30 ALE/PROG
(INTO) P3.2 12 29 PSEN
(INT1) P3.3 13 28 P2.7 (A15)
(TO) P3A 14 27 P2.6 (A14)
(T1) P35 15 26 P25(A13)
(WR) P36 16
25 P2A(A12)
(RD) P3.7 17
24 P2.3 (A11)
XTAL2 18
23 P2.2 (A10)
XTAL1 19
22 P21 (A9)
GND 20
21 P2.0 (A8)
218
Examining Figure 8-1 note h' -
aside for the four ports PO P l P2 t at of the 40 pins, a total of 32 pins are set
of the pins are designat d V ' and P3, where each port takes 8 pins. The rest
Of the . . e as co GND, XTALl, XTAL2, RST, EA PSEN and
ALE . esc pins SIX (V GND ' ,
all members of the 805 lee, d ' XTAL 1, XTAL2, RST, and EA) are used by
.. - an 803t
families, In other words, they must be i--C--2------------,
connected In order for the system to I-----....j XTAL2
work, regardless of whether the micro-
controller is of the 8051 or 8031 fami-
ly. The other two pins, PSEN and
o
ALE, are used mainly in 8031-based
...--;11---.-...---1 XTAL 1
systems. We first describe the function
30 pF
of each pin. Ports are discussed sepa-
rately.
+------.....j GND
Vee
Pin 40 provides supply voltage
to the chip. The voltage source is +5Y. ","=:-o-::;-;:::-;-~;;;-;--;::;---,----,-,-J
Figure 8-2 (a). XTAL Connection to 8051
GND
Pin 20 is the ground.
XTAL 1 and XTAL2 NC ------I XTAL2
This isan output pin. PSEN stands for "program store enable." In an 8031-
based system In which an external ROM holds the program code, this pin is con-
nected to the OE pin of the ROM. See Chapter 14 to see how this is used.
ALE
. ALE (address latch enable) is an output pin and is active high. When con-
necting an 8031 to external memory, port 0 provides both address and data. In
other words, the 8031 multiplexes address and data through port 0 to save pins.
The ALE pin is used for demultiplexing the address and data by connecting to the
G pin of the 74LS373 chip. This is discussed in detail in Chapter 14.
Ports 0, 1,2 and 3
As shown in Figure 8-1 (and discussed in Chapter 4), the four ports PO, PI,
P2, and P3 each use 8 pins, making them 8-bit ports. All the ports upon RESET
are configured as input, since PO- P3 have value FFH on them. The following is
a summary of features of PO - P3 based on the materials in Chapter 4.
PO
As sbown in Figure 8-1, port 0 is also designated as ADO - AD7, allowing
it to be used for botb address and data. When connecting an 80S I/31 to an exter-
nal memory, port 0 provides both address and data. The 80S I multiplexes address
and data through port a to save pins. ALE indicates if PO has address or data.
When ALE = 0, it provides data DO - D7, but when ALE = I it bas address AO -
A 7. Therefore, ALE is used for demuliplexing address and data with the help of a
74LS373 'latch, as we will see in Chapter 14. In the 80Sl-based systems where
there is no external memory connection, tbe pins of POmust be connected exter-
nally to a J OK-ohm pull-up resistor. This is due to the fact that POis an open drain,
unlike PI, P2, and P3. Open drain is a term used for MOS chips in the same way
that open collector is ..----------~---------,
used for TTL chips. In Vce
10 K
many systems using the
8751, 89C51,
DS89C4xO chips, we nor-
or £ ~~~~ ~~~ ~ 3E
mally connect PO to pull-
up resistors. See Figure
PO.Or-:=±=t=t==t==t=~==~
PO.11-
8051/52 M2
"J1
8-4. With cxternal pull- PO.3 ~
0
P1 and P2
ln 805 I-based systems with no external memory connection, both P I and
P2 are used as simple I/O. However, in 8031/51-based systems with external
memory connections, port 2 must be used along with PO to provide the l6-bit
address for the external memory. As shown in Figure 8-1, port 2 is also designat-
cd as A8 - A 15, indicating its dual function. Since an 8031/51 is capable of access-
ing 64K bytes of external memory, it needs a path for the 16 bits of the address.
While PO provides the lower 8 bits via AO - A7, it is the job ofP2 to provide bits
A8 - A IS of the address. In other words, when the 803 l/51 is connected to exter-
nal mcmory, P2 is used for the upper 8 bits of the 16-bit address, and it cannot be
used for 110. This is discussed in detail in Chapter 14.
From thc discussion so far, we conclude that in systems based on 8051
microcontrollers, we have three ports, PO, PI, and P2, for I/O operations. This
should be enough for most microeontroller applications. That leaves port 3 for
interrupts as well as other signals, as we will sec next.
Port 3
Port 3 occupies a total of 8 pins, pins 10 through 17. It can be used as input
or output. P3 does not need any pull-up resistors, the same as P J and P2 did not.
Although port 3 is configured as an input POl1 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 ofP3. This information applies to both 805] and 8031 chips.
P3.0 and P3.! are used for the RxD and TxD serial communications sig-
nals. Sec Chapter 10 to see how they are connected. Bits P3.2 and P3.3 are set
aside for external interrupts, and arc discussed in Chapter II. Bits P3.4 and P3.5
arc used for Timers 0 and ~nd are discussed in Chapter 9. Finally, P3.6 and P3.7
are uscd to provide the WR and RD signals of external memory connections.
Chapter 14 discusses how they are used in 803 I-based systems. In systems based
on the 8051, pms 3.6 and 3.7 are used for I/O while the rest of the pins in port 3
are normally used 111 the alternate function rolc.
P3.0 RxD 10
P3.! TxD II
P3.2 INTO 12
P3.3 INTI 13
P3.4 TO 14
P3.5 TI 15
P3.6 WR 16
P3.7 RD 17
222
•
Example 8-1
Find the machine cycle (MC) for the following chips if XTAL = 1J .0592 MHz.
(a) AT89C51 (b) DS89C4xO (c) DS5000
Solution:
In this section we show connections for 805 l-based systems using chips
such as the AT89C51 and DS89C4xO. If you decide to wire-wrap one of these,
make sure that you read Appendix B on wire wrapping.
AT89C51/52·based trainer connection
In systems based on an AT89C51/52-type mieroeontroller, you need a
ROM burner to bum your program into the microcontroller. For the AT89C51, the
ROM burner can erase the flash ROM in addition to burning a program into it. In
the case of the 8751, you also need an EPROM erasure tool since it uses UV-
EPROM. To burn the 8751, you need to erase its contents first, which takes
approximately 20 minutes for UV-EPROM. For the AT89C51, this is not required
since it has flash ROM.
Figure 8.5 shows the minimum connection for the 8751 or 89C51-based
system. Notice that "EA=V cc" indicates that an 8751 or 89C51 has on-chip ROM
for the program. Also notice the PO connection to pull-up resistors to ensure the
availability of PO for I/O operations. If you need to use a momentary switch for
RESET, refer to Figure 8-3 (b).
DS89C4xO family
224
I
Vee
Vee
:b 10 K
>
~;:
r-1:
30 pF
1 l ~
I
EANPP
X1
-+-+-+-+--+---1---1_
PO ..........
.0,
'~2 K \ 9110592MHz 19 ~g~I----4~I--+-+-+----+~1- J
P---+--J!----L------JX2 PO.3 ;:l.
30 ~F 18 PO.4 0
PO.5r-------L-+-+_
PO.6r----------..-1-
PO.7r---------~L
P3.0/RXD
P3.1ITXD P2.0
P3.2/lillQ P2.1
P3.3/INT1 P2.2
P3.41T0 P2.3
P3.51T1 P2.4
P25 '
P1.0 P2.6
P1.1 P2.7
P1.2
P1.3
P1.4
P1.5
ALElt~6~
P1.6 P 3,61i'\it{
P1.7 P3.7/RD
the web site www.maxim-ic.com for further information, Notice that while the
AT89C51 comes with 4K bytes of on-chip ROM, and theAT89C52 comes with 8K
bytes, the DS89C4xO has 16K bytes of on-chip ROM, Also notice that the
DS89C430 is a replacement for the OS89C420 with the bugs fixed.
Example 8-2
Find the address space for the on-chip ROM of the following chips,
(a) AT89C51, (b) AT89C52, and (c) OS89C420/30
Solution:
(a) AT89C51 has 4K bytes of on-chip ROM, That gives us 4 x 1024 = 4,096 bytes,
Converting the 4096 to hex, we get 1000H. Therefore, the address space is 0000 -
OFFFH.
(b) AT89C52 has 8K bytes of on-chip ROM. That gives us 8 x 1024 = 8,192 bytes,
Converting the 8,192 to hex, we get 2000H. Therefore, the address space is 0000 -
IFFFH.
(c) DS89C420/30 has 16K bytes of on-chip ROM, That gives us 16 x 1024 = 16,384
bytes, Converting the 16,384 to hex, we get 4000H. Therefore, the address space is
0000 - 3FFFH.
+5V
rJ
+5V
0:
<'"
~~4
>- 0 +
10uF vee
2 5
OB·9F
~'" ...,N
" 8.2k
+5V
RST TxD
RxD
a
..
~ 4 ,0 }
1k
I,
1k DS89C4xD
....
10k EA
2N3904
P2.6 ) DPENDR
.5V
PULLED UP
P2.7
:I: l;UN
"'~
1
>-0
~!= 10k PsEN 30pF
2N3904 XTAL1
.~
(J) PROGRAM
GND XTAL2
11.0592 MHz
Figure 8-6. DS89C4xO Trainer (for MAX232 connection, see Section 10.2)
Notice from Figure 8-6 that ihe reset circuitry and setial port connections
are the same as in any 805 l-based system, However, the extra circuitry needed for
programming are two transistors, a switch, and 10K and IK-ohm resistors, In fact,
you ean add these components to your 8751/89C51 system and use it as a
DS89C4xO system by simply plugging a DS89C4xO chip in the socket. The switch
allows you to select between the program and run options, We can load our pro-
gram into the DS89C4xO by setting the switch to V cc. and run the program by set-
ting it to Gnd.
Figure 8-6 shows the connection for the 8051 Trainer from
www.MieroDigitaIEd.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 termi-
nal blocks. It also comes with an on-board power regulator.
www.MicroDigitaIEd.com
FIgure 8-7. Screen Capture from HyperTerminal for DS89C4xO Trainer "
228
If you do not see ">" after pressing the ENTER key several times, go
through the above steps one more time. Then, if you do not get ">", you need to
check your hardware connections, such as the MAX232/233. See the end of this
section for some troubleshooting tips.
I. At the ">" prompt, enter L (L is for Load). Example: ">L" an~ pr~s~ En~ri
2. In HyperTerminal, click on the Transfer m~,nu option. ,~IIck on en ext I e.
3. Select your file from your disk. Example: C:test.hex h "GGGG " t
4. Wait until the loading is complete. The appearance of t e > promp
indicates that the loading is good and finished.
5. Now use D to dump the contents of the flash ROM of the DS89C4xO onto the
screen Example: >D 00 4F . ..
. '11'
The dump WI gIve you the opcodes and operands
. . of all. the mstrucnons
. m
id
Y, mpare this information with the information provt -
your program' ou Icanthcoext section we will examine the Intel hex file and
ed by the list lilI e. n en,
compare it with the list file of the test program.
DS89C4xO commands
. There are many commands embedded into the DS89C4xO loader. The most
widely used among them are L, K, and D. Here is the summary of their opera-
nons.
L Load standard ASCII Intel hex formatted data into flash memory.
K Erases the entire contents of flash memory. .
D <begin> <end> Dumps the Intel hex file.
We have shown the use of the L (load), K (klean), and D (dump) com-
mands earlier. A complete list of commands and error messages can be obtained
from www.MicroDigitalEd.com.
. Intel hex file is a widely used file format designed to standardize the load-
mg of executable machine codes into a ROM chip. Therefore, loaders that come
OOOOOOOOOOODOOOOOOOOOOOOOOOOOOOO 55
:CC AAAA TT 9F
75805575905575A0557DFA111C7580AA
:10 0000 00 01
7590AA75AOAA7DFA111C80E47C237B4F
:10 0010 00 35
DBFEDCFADDF622
:07 0020 00
:00 0000 01 FF
ow, compare the data portion of the Intel hex tile in Figure 8-9 with the
informationunder the OBl field of the list file in Figure 8-8. Notice that they are
identical, as they should be. The extra information is added by the Intel hex file
fonnalter. You can run the C language version of the test program and verify its
operation. YourC compiler will provide you both the list tile and the Intel hex file
if you want explore the Intel hex file concept.
Examine the next three examplcs to gain an insight into the Imel hex fil1 e.
Example 8-3
From Figure 8-9, analyze the six parts of line 3.
Solution:
Example 8-4
Verifythe
corrupted.checksum byte for line 3 of Fiigure 8-9. Verify also that the information is not
Solution:
07 + 00 + 20 + 00 + OB +
ries (S)gives CB . FE + DC + FA + DD + F6 + 2 -
If we add H, and ItS2's complement is 3 . 2.- 5CBH. Dropping the car-
ries . hall the mfonnation in line 3 incl di SH, which IS the last byte of line 3.
07 +~~ s+ould get 00. ' u mg the checksum byte, and drop the car-
20 + 00 + DB + FE + DC+FA+ DD + F6 + 22 + 35 = 600H
234 -
Example 8-5
Compare the data p,ortion 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 Figure 8-9, the data portion starts with 75H, the opcode for the instruc-
tion "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.
Review Questions
I. True or false. The Intel hex file uses the checksum byte method to ensure data
integrity.
2. The first byte of a line in the Intel hex file represents __ .
3. The last byte of a line in the Intel hex file represents __ .
4. In the TT field of the Intel hex file, we have 00. What does it indicate?
5. Find the checksum byte for the following values: 22H, 76H, 5FH, 8CH, 99I-1.
6. In Question 5, add all the values and the checksum byte. What do you get?
SUMMARY
. This chapter began by describing the function of each pin of the 8051, The
four ports of the 8051, PO, PI, P2, and P3, each use 8 pins, making them 8-bit
ports. These ports can be used for input or output. Port 0 canbe used for. either
address or data. Port 3 can be used to provide interrupt and serial communication
signals. Then the design of the DS89C4xO-based trainer was shown. We also
explained the Intel hex format.
PROBLEMS
25. Write a program to get 8-bit data from PI and send it to ports PO, P2, and P3.
26. Write a program to get 8-bit data from 1'2 and send it to ports PO and PI.
27. In 1'3, which pins are for RxD and TxD?
28. At what memory location does the 8051 wake up upon RESET? What is the
implication of that?
29. Write a program to toggle all the bits of P I and P2 continuously
(a) using AAH and 55H (b) using the CPL instruction.
30. What is the address of the last location of on-chip ROM for the AT89C5 I 'I
31. What is the address of the last location of on-Chip ROM for the DS89C420?
32. What is the address of the last location of on-chip ROM for the D889C440?
33. What is the address of the last location of on-chip ROM for the DS89C450?
34. What is the fastest frequency that DS89C4xO can run on?
35. What is the slowest frequency that DS89C4xO can run on?
36. Calculate the machine cycle time for the OS89C430 ifXTAL = 33 MHz.
37. Before we reprogram the DS89C4xO we must (dump era c) the flash
ROM. . ,
38. True or false. In order to download the hex file into the OS89C4xO, it must be
111 the Intel hex file formal.
39. have.
Give two features of the DS89C4xO that earlier 8051 and 8052 chips do not
236
SECTION 8.3: EXPLAINING THE INTEL HEX FILE
I. True
2. Pin 9
3. Low
4. Flash
5. Serial .
6. a) It comes with a loader inside the chip and b) it has t~o serial ports
7. ,. The SWallows to load the program or to run It.
8. 33 MHz
9. True
10. >K
II. >L
f2. >D
l. True .
2. The number of bytes of data in the line
3. Checksum byte . d there are more lines or data to be followed.
4. 00 means this IS not the last line ""21CH D pping the carries we have ICH and its 2's cam-
S. 22H + 76H + 5FH + 8CH + 99H - . ro
plement is E4H. E4 = 300H. Dropping the carries we have 00, which means
6. 22H + 76H + 5FH + 8CH + 99H +
data is not corrupted.
8051 TIMER
PROGRAMMING
IN ASSEMBLY AND C
OBJECTIVES
239
, / t s They can be used either as timers to
The 8051 has two timers eoun e~u'ntevents happening outside the micro.
, delay or as counters to c ,
generate a time h these timers arc used to generate time delays,
Scetion 9 I we see ow ,
contro IIer, In ' h used as event counters. In Section 9.3 we
In Section 9.2 we show how t eyare
usc C language to program the 8051 timers.
The 8051 has two timers: Timer 0 and Timer I. They can be ,used either as
.umcrs or as event cu.
a nters In this section we first discuss
. the timers registers and
then show how to program the timers to generate time delays.
Timer 0 registers
The 16-bit register ofTimer 0 is accessed as low byte and high byte. The
low byte register is called TLO (Timer 0 low byte) and the high byte register is
referred to as THO (Timer 0 high byte). These registers can be accessed like any
other register, such as A, B, RO, RI, R2, etc. For example, the instruction "MOV
TLO, #4FH" moves the value 4FH into TLO, the low byte ofTimer O. These reg-
isters can also be read like any other register. For example, "MOV R5, THO" saves
THO(high byte ofTimer 0) in R5.
Timer 1 registers
Timer I is also 16 bits a d it 16 bi . ,
to as TLI (1' . I I b ,n IS - It register IS split into two bytes referred
imer ow ytc) and THI (1' I hi h b '
accessible in the same he reci imcr Ig yte). These registers are
way as t e registers of Timer O.
THI
240
TMOD (timer mode) register
Both timers 0 and I use the ' '
timer operation mode TMOD te same register, called TMOD, to set the various
set aside for Timer 0 s. d h IS an 8-bll register in which the lower 4 bits are
bits are used to set thant' t e upper 4 bits for Timer I, In each case, the lower 2
, elmer mode and th 2 b' ,
These options are disc d e upper Its to spec] fy the operation,
usse next.
(MSB)
(L S B)
GATE I CIT I MI I MO GATE I CIT I MI T MO
Timer 1 Timer 0
GATE Gating control when s t Th 'I ' enabled only while the \NTx pin
, hi he, e timer count,er IS
ISh ig and the TRx can t to I PI~
' ISset
. When cleared, Ihe timer is enabled
w enever the TRx control bit is set
CIT Timer or counter selected cleared for timer operation (input from internal
system clock), Set for counter operation (input from Tx input pin)
Ml Mode bit I '
MO Mode bit 0
MI MO Mode ~Q~p,;:er~a~tin~g;.lM=odlJ;e~ _
o 0 0 l3-bit timer mode
8-bit timer/counter THx with TLx as 5-bil prescaler
o 16-bit timer mode
16-bit timerlcounters THx and TLx are cascaded; there is
no prescaler
o 2 8-bit auto reload
8-bit auto reload timer/counter; THx holds a value that is
to be reloaded into TLx each time it overflows.
3 Split timer mode '
Figure 9-3. TMOD Register
M1, MO
MO and Ml select the timer mode, As shown in Figure 9-3, there arc three
modes: 0, I, and 2, Mode 0 is a 13-bit timer, mode I is a 16-bit timer, and mode 2
is an 8-bit timer. We will concentrate on modes I and 2 since they arc the ones
used most widely, We will soon describe the characteristics of these modes, after
describing the rest ofthe TMOD register.
CIT (clock/timer)
This bit in the TMOD register is used to decide whether the timer is used
as a delay generator or an event counter, If CIT = 0, it is used as a timer for time
delay generation, The clock source for the time delay is the crystal frequency of
the 805 L This section is concerned with this choice, The timer's use as an event
counter is discussed in the next section,
Solution:
We convert the values from hex to binary. from Figure 9-3 we have:
0 is selected.
(a) TMOD = 00000001, mode 1 of Timer
(b) TMOD = 00100000, mode 2 of Timer
1 is selected.
(c) TMOD = 00010010, mode 2 of Timer
0, and mode 1 of
Timer 1 are selected.
Solution:
XTAL -i- 12
oscillator
d
Although various 8051-based systems have an XTAL frequency of 10
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 the 8051. XTAL = 11.0592 MHz allows the 8051 system to com-
municate with the IBM PC with no errors, as we will see in Chapter 10.
GATE
The other bit of the TMOD register is the GATE bit. Notice in the TMOD
register of Figure 9-3 that both Timers 0 and 1 have the GATE bit. What is its pur-
pose? Every timer has a means of starting and stopping. Some timers do this by
software, some by hardware, and some have both software and hardware controls.
The timers in the 8051 have both. The start and stop of the timer are controlled by
way of software by the TR (timer start) bits TRO and TR1. This is achieved by the
instructions "SETS TRl" and "CLR TRl" for Timer I, and "SETS TRO" and
"CLR TRO" for Timer O. The SETB instruction starts it, and it is stopped by the
CLR instruction. These instructions start and stop the timers as long as GATE =
o in the TMOD register. The hardware way of starting and stopping the timer by
an external source is achieved by making GATE = 1 in the TMOD register.
However, to avoid further confusion for now, we will make GATE = 0, meaning
that no external hardware is needed to start and stop the timers. In using software
to start and stop the timer where GATE = 0, all we need are the instructions "SETS
TRx" and "CLR TRx". The use of external hardware to stop or start the timer is
discussed in Chapter 1I when interrupts are discussed.
Example 9-3
Find the value for TMOD if we want to program Timer 0 in mode 2, use 8051 XTAL
for the clock source, and use instructions to start and stop the timer.
Solution:
. . limit
hes Us ., and ro lis. over , in order to repeat the process
d TF
4. After the timer reae L t be reloaded with the original value, an must
the registers TH and T mus
be reset to O.
.JL.JL
L-
XTAL
oscillator
_
1--/ +12
I I
~
244
Example 9-4
Solution:
1. TMOD is loaded.
2. FFF2H is loaded into THO - TLO:
3. Pl.5 is toggled for the high and low portions of the pulse.
4. The DELAY subroutine using the timer is called.
5. In the DELAY subroutine, Timer 0 is started by the "SETB TRO" instruction.
6. Timer 0 counts up with the passing of each clock, which is provided by the crystal
oscillator. As the timer counts up, it goes through the states of FFF3, FFF4, FFF5,
FFF6, FFF7, FFF8, FFF9, FFFA, FFFB, and so on until it reaches FFFFH. One more
clock rolls it to 0, raising the timer flag (TFO = I). At that point, the JNB instruction
falls through.
7. Timer 0 is stopped by the instruction "CLR TRO". The DELAY subroutine ends,
and the process is repeated.
Notice that to repeat the process, we must reload the TLand TH registers and start the
timer again.
8--®-8······························~
TF = 0 TF = 0 TF = 0 TF = 0 TF = I
245
CHAPTER 9: 8051 TIMER PROGRAMMING IN ASSEMBLY AND C
Example 9-5
amount of time delay in the DELAY subroutine generat.
In Examp Ie 9-4 ,ca Icu Ia te the
cd by the timer. Assume that XTAL ~ 11.0592 MHz.
Solution:
The timer works with a clock frequency of 1/12 of the XTAL frequency; therefore, we
have 11.0592 MHz / 12 ~ 921.6 kHz as the timer frequency. As a result, each clock has
a period ofT ~ 1/921.6 kHz ~ 1.085 I1S. In other words, Timer 0 counts up each 1.085
I1S resulting in delay ~ number of counts x 1.085 I1S.
The number of counts for the rollover is FFFFH - FFF2H ~ ODH (13 decimal).
However, we add one to 13 because of the extra clock needed when it rolls over from
FFFF to 0 and raises the TF flag. This gives 14 x 1.085 I1S ~ 15.19 I1S for half the pulse.
For the entire period T ~ 2 x 15.I 9 115 ~ 30.38 I1S gives us the time delay generated by
the timer.
Example 9-6
In Example 9-5, calculate the frequency of the square wave generated on pin P1.5.
Solution:
In the time delay calculation of Example 9-5, we did not include the overhead due to
instructions in the loop. To get a more accurate timing, we need to add clock cycles due
to the instrucnons In the loop. To do that, we use the machine cycles from Table A-I in
Appendix A, as shown below.
Cycles
HERE: TLO, #OF2H
MOV 2
MOV THO,#OFFH 2
CPL PI.5 1
ACALL DELAY
2
SJMP HERE 2
;--------~delay using Timer 0
DELAY:
SETB TRO
AGAIN: 1
JNB TFO ,AGAIN
14
CLR TRO
1
CLR TFO
1
RET
L
Total 28
T ~ 2 x 28 x 1.085 I1S = 60.76 us and
.. F = 16458.2 Hz.
NOTE THAT 8051 TIME
REGARDLESS OF MAC~SINUESE 1112 OF XTAL FREQUENCY,
CYCLE TIME.
246
Example 9-7
Find . the delay generated . b ot h 0f t he met ha d s
. by Timer 0 in the foil'owmg co d e, usmg
of Figure 9-4. Do not Include the overhead due to instructions.
AGAIN:
SETB
JNB
TRO
TFO,AGAIN
!; start Timer
;monitor Timer 0 flag
°
CLR TRO ;stop Timer °
CLR TFO ;clear Timer
;next round
°
flag for
CLR P2.3
Solution:
(a) (FFFF - B83E + I) ~ 47C2H ~ 18370 in decimal and 18370 x 1.085 J.1S ~ 19.93145
ms.
(b) Since TH - TL ~ B83EH ~ 47166 (in decimal) we have 65536 - 47166 = 18370.
This means that the timer counts from B83EH to FFFFH. This plus rolling over to
o goes through a total of 18370 clock cycles, where each clock is 1.085 J.1S in dura-
tion. Therefore, we have 18370 x 1.085 J.1S ~ 19.93145 ms as the width ofthe pulse.
Example 9-8
Modify TL and TH in Example 9-7 to get the largest time delay possible. Find the delay
in ms. In your calculation, exclude the overhead due to the instructions in the loop.
Solution:
To get the largest delay we make TL and TH both O. This will count up [Tom 0000 to
FFFFH and then roll over to zero.
247
CHAPTER 9: 8051 TIMER PROGRAMMING IN ASSEMBLY AND C
Example 9-9 ave on pin P I 5 continuously using Timer 1
The following program generates a squ~r~: square wave if XTAL = 11.0592 MHz. In
for a lime delay. Find the frequ~ncy 0 h ad due to instructions in the loop.
your calculation do not include t e over e
Solution:
In the above program notice the target of SIMP. In mode I, the program must reload the
TH, TL register every time if we want to have a continuous wave. Now the calculation.
Since FFFFH - 7634H = 89CBH + I = 89CCH and 89CCH = 35276 clock count.
35276 x 1.085 us = 38.274 ms for half of the square wave. The entire square wave
length is 38.274 x 2 = 76.548 ms and has a frequency = 13,064 Hz.
Also notice that the high and low portions of the square wave pulse are equal. In the
above calculation, the overhead due to all the instructions in the loop is not included.
In Examples 9-7 and 9-8, we did not reload TH and TL since it was a sin-
gle pulse. Look at Example 9-9 to sec how the reloading works in mode I.
Finding values to be loaded into the timer
. Assuming that we know the amount of timer delay we need, the question
IS how to find the values needed for the TH, TL registers. To calculate the values
to be loaded into the TL and TH registers look at Example 9-10 where we usc crys-
tal frequency of 11.0592 MHz for the 8051 system.
, Assuming XTAL = 11.0592 MHz from Example 9-10 we can use the fol-
lowmg steps for findmg the TH, TL registers' values.
248
-
CI
Assume that XTAL - 11.0592 MHz, What value do we need to load into the timer's reg-
isters if we want to have a time delay of 5 ms (milliseconds)? Show the program for
Timer 0 to create a pulse width of 5 ms on P2,),
Solution:
Since XTAL = 11,0592 MHz, the counter counts up every I ,085 ~,S, This means that out
of many 1.085 us intervals we must make a 5 ms pulse, To get that, we divide one by
the other, We need 5 rns /1,085 ILS= 4608 clocks, To achieve that we need to load into
TL and TH the value 65536 - 4608 = 60928 = EEOOH,Therefore, we have TH = EE and
TL= 00,
CLR P2,3 ;clear P2,3
MOV TMOD,#Ol ;Timer 0, mode 1 116-bit mode)
HERE: MOV TLO,#O ,TLO = 0, Low byte
MOV THO,#OEEH ;THO = EE( hex), High byte
SETB P2,3 ,SET P2, 3 high
SETB TRO ,start Timer °
AGAIN: JNB TFO,AGAIN ,monitor Timer °
flag
;until it rolls over
CLR P2.3 ;clear P2,3
CLR TRO ;stop Timer °
CLR TFO ;clear Timer °
flag
Example 9-11
Assuming that XTAL = 11.0592 MHz, write a program to generate a square wave of 2
kHz frequency on pin P1.5.
Solution: ,
This is similar to Example 9-10, except that we must toggle the bit ,to generate the
square wave. Look at the following steps,
(a) T = 1 / f= 1/2 kHz = 500 us the period of the square wave,
(b) 112 of it for the high and low portions of the pulse IS250 ILS, ,
(c) 250 ILS/ 1,085 ILs= 230 and 65536 - ,230 = 65306, which in hex IS FF lAI-!,
(d) TL = IAH and TI-!= FFH, all in hex, The program ISas follows,
249
CHAPTER 9: 8051 TIMER PROGRAMMIN G IN ASSEMBLY AND C
Example 9-12 . m to generate a square wave of 50 Hz
. XTA1 ~ J 1.0592 MHz, wnte a progra
AssumIng
frequency on pin P2.3.
Solution:
Solution:
TH - TL = 0 108H = 264 in decimal and 65536 - 264 = 65272. Now 65272 x 1.085 us
=70.820 ms, and for 200 of them we have 200 x 70.820 ms = 14.164024 seconds.
Mode 0
Mode 0 is exactly like mode I except that it is a 13-bit timer instead of 16-
bit. The 13-bit counter can hold values between 0000 to I FFFH in TH - TL.
Therefore, when the timer reaches its maximum of IFFH, it rolls over to 0000 , and
.
TF is raised.
Mode 2 programming
The following are the characteristics and operations of mode 2.
J.It is an 8-bit timer; therefore, it allows only values of 00 to FFH to be loaded
into the timer's register TH.
2. After TH is loaded with the 8-bit value, the 8051 gives a copy of it to TL. Then
the timer must be started. This is done by the instruction "SETB TRO" for
Timer a and "SETB TRI" for Timer I. This isjust like mode I.
3. After the timer is started, it starts to count up by incrementing the TL register.
It counts up until it reaches its limit of FFH. When it rolls over from FFH to
00, it sets high the TF (timer flag). If we are using Timer 0, TFO goes high; if
we are using Timer I, TFI is raised.
.rt.rt
XTAL
~I T~.overnow
+ 12
oscillator
·1 I TR
I ru ]
reload TF ;:: high
when FF .....O
cif=o
Example 9-14
Assuming that XTAL = II 0592 MH f d
ated on pin PI 0 in the [,0110'
wi z, m (a) the frequency of the square wave gener-
. . mg program and (b) th II t: ..
this program, and the TH value to do that. e sma est rrequency achievable 111
MOV TMOD,#2DH
MOV THl,#5 ;Tl/mode 2/S-bit/auto-reload
SETB TRI ; THI = 5
BACK: JNB TFl,BACK ;start Timer 1
CPL Pl.D ;stay until timer rolls over
CLR TFl .comp . Pl.O to get hi, 10
SJMP BACK ;clear Timer 1 flag
Solution: rmcde 2 is auto-reload
(a) First notice the target address of SIMP In m
It IS auto~reload. Now (256.05)
0de
X'I 085 _2 we do not need to reload TH since
high portion of the pulse. Since it is a 500/, du - 251 x I .085 us = 272.33 us is the
twice that; as a result T = 2 x 272 33 s _0 uty cycle square wave, the period T is
(b) ~z. . u .. 544.67 us and the frequency = 1.83597
o get the smallest frequency
= 00 In th ' we need the lar t T
= I 8' kH at case, we have T = 2 x 256 I ges and that is achieved when TH
. z. x .085 us -- 555 .52 ~s and the frequency
252
-
Example 9-15
Find the frequency of a square wave generated on pin P j .0.
Solution:
Example 9-16
Assuming that we are programming the timers for mode 2, find the value (in hex) loaded
into TH for each of the following cases.
Solution:
You can use the Windows scientific calculator to verify the results provided by the
assembler. In Windows calculator, select decimal and enter 200. Then select hex, then
+/- to get the TH value. Remember that we only use the-right two digits and ignore the
rest since our data is an 8-bit data. The following is what we get.
Find (a) the frequency 0 f thee squar wave generated In the following code, and (b) the
duty cycle of this wave,
Solution:
For the TH value in mode 2, the conversion is done by the assembler as long as we enter
a negative number. This also makes the calculation easy. Since we are using 150
clocks, we have time for the DELAY subroutine = 150 x 1.085 ~s = 162 us, The high
portion of the pulse is twice that of the low portion (66% duty cycle). Therefore, we
have: T ~ high portion + low portion = 325.5 us + 162.25 us = 488.25 us and frequen-
ey = 2.048 kHz.
Notice that in many of the time delay calculations we have ignored the
clocks caused by the overhead instructions in the loop. To get a more accurate
umc delay, and hence frequcncy, you need to include them, ] f you use a digital
scope and you don't get exactly the same frequency as the one we have calculat-
ed, It ISbecause of the overhead associated with rhos . t . .
I hi . e InS ructions.
n uns section, we used the 8051 timer for time delay generation.
However, a more powerful and c ti f h '
, . rea ivc use 0 t esc tlmcrs is to use them as event
counters. We diSCUSSthis use of the counter next.
254
-
Review Questions
I. How many timers do we have in the 8051?
2. Each timer has __ registers that are bits wide.
3. TMOD register is a(n) _-bit register. -
4. True or false. The TMOD register is a bit-addressable register.
5. Indicate the selection made in the instruction "MOV TMOD, #2 OH".
6. In mode J, the counter rolls over when it goes from to .
7. In mode 2, the counter rolls over when it goes from --to --.
8. In the instruction "MOV TH1, # - 2 00", find the hex value for the TH register.
9. To get a 2-ms delay, what number should be loaded into TH, TL using mode
I? Assume that XTAL = 11,0592 MHz. '
10. To get a IOO-~sdelay, what number should be loaded into the TH register using
mode 2? Assume XTAL = I J .0592 MHz.
In the last section we used the timerlcounter of the 8051 to generate time
delays. These timers can also be used as counters counting events happening out-
side the 8051. The use of the timerlcounter as an event counter is covered in this
section. As far 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 also 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 fre-
quency. When it is used as a counter, however, it is a pulse outside the 8051 that
increments the TH, TL registers, In counter mode, notice that the TMOD 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.
Notice in the above program the role of the instruction "SETB P3. 5". Since
pons are SCI up for output when the 805 J is powered up, we make P3.5 an input port by
making it high. In other words, we must configure (set high) the TI pin (pin P3.5) to
allow pul es to be fed into it.
8051
P2 is connected to 8 LEOs P2 to
and input TI to pulse. LEDs
~P3.5
Tl
.ru-t. overtlow
fl
r-~,,~-=
~
,-,=------------,
overflow
Timer 0 L..J L
external ag Timer I flag
input
pin 3.4
[TFO I external
input
I TFII
TFO goes high pin 3.5
TRO TF I goes high
when FFFF -- 0 eif = I TRI
when FFFF ..... O
Figure '/..5. (I) Timer 0 wllh Ellernaiinpul
( lode i) (b) Timer 1 with External Input (Mode 1)
2 6
Example 9-19
Assume that a I-Hz frequency pulse is connected to input pin 3.4. Write a program to
display counter 0 on an LCD. Set the initial value of THO to -60.
Solution:
To display the TL count on an LCD, we must convert 8-bit binary data to ASCJJ. Sec
Chapter 6 for data conversion.
8051
..----f--- -,
f--- to
Plf---
~P3.4
I Hz clock TO
§ LCD
Figure 9-6. Ttmer 0 with Extemal Input (Mode 2) Figure 9-7. Timer I with External Input (Mode 2)
258
TeON register
In the examples so far we have seen the use of the TRO and TR 1 flags to
tum on or off the timers. These bits are part of a register called TCON (timer con-
trol). This register is an 8-bit register. As shown in Table 9-2, the upper four bits
are used to store the TF and TR bits of both Timer 0 and Timer 1. The lower four
bits are set aside for controlling the interrupt 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 TR1" and "CLR TR1", we could use
"SETB TCON. 6" and "CLR TCON. 6", respectively. Table 9-2 shows replace-
ments of some of the instructions we have seen so far.
XTAL
OSCILLATOR
1- +12 r--
CIT =0
' ....... ~
-u '-J
., V
! CIT =1
TO IN ~
Pin 3.2
:
TRO
--LJ
r-,
Gate
....5>-
-
INTO Pin
-- ,
Pin 3.2
T1IN~
t cii» 1
Pin3.5
TR1------j
Gale ----{>--~l~
INTI Pin ~
Pin 3.3
Review Questions
I. Who provides the clock pulses to 8051 timers if CIT = O?
2. Who provides the clock pulses to 8051 timers if CIT = J?
3. Does the discussion in Section 9.1 apply to timers if CIT = I? ?
4. What must be done to allow P3.4 to be used as an input for TI, and why.
5. What is the equivalent of the following instruction? "SETB TCON. 6"
. In 8051 C we can access the timer registers TH, TL, and TMOD directly
usingthe reg51.h header file. This is Shown in Example 9-20. Example 9-20 also
shows how to access the TR and TF bits.
-
Example 9-20
Write a 8051 C program to toggle all the bits of port P I continuously with some delay
in between. Use Timer 0, 16-bit mode to generate the delay.
Solution:
#include <reg5I.h>
void TODelay(void);
void main (void)
{
while(l) //repeat forever
{
Pl=Ox55: //toggle all bits of PI
TODelay (); //delay size unknown
Pl=OxAA; //toggle all bits of PI
TODelay ();
}
}
void TODelay ()
{
TMOD=OxOI: //Timer 0, Mode 1
TLO=OxOO: //load TLO
THO=Ox35: //load THO
TRO=l; //turn on TO
while (TFO==O) ; //wait for TFO to rollover
TRO=O;
TFO=O;
//turn off TO
//clear TFO I
FFFFH - 3500H = CAFFH = 51967 + I = 51968
8051
PO LEOs
262
Example 9-21
Write an 8051 C program to toggle only bit P 1.5 continuously every 50 ms. Use
Timer 0, mode I (l6-bit) to create the delay. Test the program (a) on the AT89C51 and
(b) on the DS89C420.
Solution:
#include <regsl.h>
void TOMIDelay(void);
sbit mybit=PIAS;
void main (void)
{
while(l)
{
mybit=-mybit; //toggle Pl.S
TOMIDelay (); //Timer 0, mode 1(16-bit)
}
}
(a) Tested for AT89C51, XTAL=II.0592 MHz, using the Proview32 compiler
void TOMIDelay(void)
{
TMOD=OxOl; //Timer 0, mode 1(16-bit)
TLO=OxFD; //load TLO
THO=Ox4B; //load THO
TRO=l; //turn on TO
while (TFO==O) ; //wait for TFO to rollover
TRO=O; //turn off TO
TFO=O; //clear TFO
}
(b) Tested for D589C420, XTAL=II.0592 MHz, using the Pioview32 compiler
I
void TOMIDelay(void)
{ I
TMOD=OxOl; //Timer 0, mode 1(16-~it)
TLO=OxFD; //load TLO
THO=Ox4B; //load THO
TRO=l; //turn on TO
while (TFO==O) ; //wait for TFO to rollover
TRO=O; //turn off TO
TFO=O; //clear TFO
}
Solution:
//tcsted for 0889C420, XTAL = II .0592 MHz, using the Proview32 compiler
#include <regsl.h>
void TIMIDelay(void);
void main (void)
unsigned char X;
P2=OxSS;
wh i Le I I )
(
P2=-P2; //toggle all hi ts of P2
for(x=O;x<20;x++)
TIMlDelay ();
void TIMIDelay(void)
TMOD=OxlO;
//Timer 1, mode 1(16-bit)
TLl=OxFE; //load TLI
THl=OxAS; //load THI
TRl=l; //turn on Tl
while (TFl==O);
//wait for TFI to rollover
TRl=O;
//turn off Tl
TFl=O; //clear TFI
264
Example 9-23
Write an 8051 C program to toggle only pin P 1.5 continuously every 250 ms. Use
Timer 0, mode 2 (8-bit auto-reload) to create the delay.
Solution:
Iitested for DS89C420, XTAL = 11.0592 MHz, using the Proview32 compiler
#include <reg51.h>
void TOM2Delay(void) ,
A
sbit mybit=PI 5;
void main (void)
{
unsigned char x, y,
while (1)
{
mybit=-mybit; //toggle Pl. 5
for(x=O,x<250;x++) //due to for loop overhead
for(y=O;y<36;y++) //we put 36 and not 40
TOM2Delay() ,
void TOM2Delay(void)
{
TMOD=Ox02; //Timer 0, mode 2(B-bit auto-reload)
THO=-23; //load THO (auto-reload value)
TRO=I; //turn on TO
while (TFO==O) ; //wait for TFO to rollover
TRO=O, / / turn off. TO
TFO=O; //clear TFO
}
256 - 23 = 233
23 x 1.085 us = 25 lls
However the scope output does not give us this result. This is due to overhead of the
, C. To correct this problem, we put 36' mstea df40
for loop in 0 .
Solution:
//tested for D589C420, XTAL ~ 11.0592 MHz, using the Proview32 compiler
#include <regS1.h>
void T1M2Delay(void);
sbit mybit=P2A7;
void main (void)
(
unsigned char X;
while (1)
(
mybit=-mybit; Iitoggle P2. 7
TlM2Delay ();
void T1M2Delay(void)
I / 2500 Hz ~ 400 us
400 us / 2 ~ 200 us
8051
2500 Hz
P2.7~
266
Example 9-25
A switch is connected to pin P 1.2. Write an 8051 C program to monitor SW and create
the following frequencies on pin PI.7:
SW=O: 500 Hz
SW=l: 750Hz
Use Timer 0, mode I for both of them.
Solution:
!!tested for AT89C51!52, XTAL = 11.0592 MHz, using the Proview32 compiler
#include <reg51.h> '
sbit mybit=PIA5;
A
sbit SW=PI 7;
void TOMIDelay(unsiged char);
void main (void)
{
SW=l, //make PI.7 an input
while (I)
{
mybit=-mybit; //toggle P1.5
if (SW==O) //check switch
TOMlDelay (0);
else
TOMlDelay (I);
}
void TOMIDelay(unsigned char c)
{
TMOD=OXOI;
if (c==O)
{
TLO=Ox67; //FC67
THO=OxFC;
}
else
(
TLO=Ox9A; //FD9A
THO=OxFD;
)
TRO=l;
while (TFO==O) ;
TRO=O;
TFO=O,
FC67H = 64615
65536 - 64615 = 921
921 X 1.085 us = 999.285 IlS
1 ! (999.285 Ils X 2) = 500 Hz
Example 9-26
Assume that a l-Hz external clock is being fed into pin TJ (P3.5). Write a C program
for counter I III mode 2 (8-blt auto reload) to count up and display the state of the TLI
count on P I. Start the count at OH.
Solution:
#include <regSI.h>
sbit Tl = P3'S;
void main (void)
{
T1=1;
Ilmake T1 an input
TMOD=OX60;
II
TH1=O;
Iiset count to 0
while (1)
{ Ilrepeat forever
do
{
TR1=1;
Iistart timer
PhTL1;
} Ilplace value on pins
While (TF1==O) .
TRl:;;O i I
Ilwait here
TFl=O;
Iistop timer
I I clear flag
8051
P I is connected to 8 LEDs.
T1 (P3.5) is connected to a PI to
I-Hz external clock. LEDs
I Hz TI
Example 9-27
Assume that a I-Hz external clock is being fed into pin TO (P3.4). Write a C program
for counter 0 in mode 1 (I 6-bit) to count the pulses and display the THO and TLO reg-
isters on P2 and PI, respectively.
Solution: '1
I
#include <reg51.h>
do
{
TRO;l; Iistart timer
Pl;TLO; Ilplace value on pins
P2;THO; II
}
while (TFO;;O) ; Ilwait here
TRO;O; Iistop timer
TFO;O;
}
}
8051 "
~-....,~
f-- PI and
P!f--
P2 to
LEDs
5LJL- ~
I Hz clock TO P3.4
Solution:
To display the TL I count we must convert 8-bit binary data to ASCII. See Chapter 7
for data conversion. The ASCII values will be shown in binary. For example, '9' will
show as 00 I J J 001 on ports.
#include <reg51.h>
void BinToASCII(unsigned char);
void main ()
(
unsigned char value;
T1;1;
TMOD;OX06;
THO;O;
while!l)
(
do
(
TRO;l;
value;TLO;
BinTOASCII!value);
)
while (TFO;;O) ;
TRO;O;
TFO;O;
}
)
dl ; value % 1~
d2 ; x % 10.
d3 x / 10'
PO ; 30 I dl;
PI 30 I d2;
P2 ; 30 I d3
Example 9-29
Assume that a 60-Hz external clock is being fed into pin TO (P3.4). Write a C program
for counter 0 in mode 2 (8-bit auto-reload) to display the seconds and minutes on P I and
P2, respectively.
Solution:
#include <reg51.h>
void ToTime(unsigned char);
void main ()
{
unsigned char val;
TO=I;
TMOD=Ox06;
THO=-60;
liTO, mode 2, counter
while (I)
Iisec = 60 pUlses
{
do
{
TRO=I;
sec=TLO;
ToTime (val);
)
while (TFO==O) ;
TRO=O;
TFO=O;
)
},
void ToTime(unsigned char val)
{
unsigned char sec, min;
min = value I 60;
sec = value % 60;
PI = sec;
P2 = min;
8051
'--'1-- <,
I-- PI and
PI-
P2 to
~
-fL......JL-. P3.4 P2~ LEDs
f--
60 Hz clock TO
Review Questions
SUMMARY
The 8051 has two timers/counters, When used as timers they can generate
time delays, When used as counters they can serve as event counters, This chap-
ter showed how to program the timers/counters for various modes,
The two timers are aceesscd as two 8-bit registers: TLO and THO for
Timer 0, and TL I and TH I for Timer I, Both timers usc the TMOD register to set
timer operation modes, The lower 4 bits of TMOD arc used for Timer 0 and the
upper 4 bits are used for Timer I,
There are different modcs that can be used for each timer. Mode 0 sets the
timer as a 13-bit timer, mode I sets it as a 16-bit timer, and mode 2 sets it as an 8-
bit timer,
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,
PROBLEMS
43. To use the timer as an event counter we must set the CIT bit in the TMOD reg-
ister to (low, high).
44. Can we use both of the timers as event counters?
45. For counter 0, which pin is used to input clocks?
46. For Counter I, which pin is used to input clocks?
47. Program Timer I to be an event Counter. Use mode I and display the binary
count on PI and P2 continuously. Ser the initial count to 20,000.
48. Program Timer 0 to be an event counter. Use mode 2 and display the binary
count on P2 continuously, Set the initial count to 20.
49. Program Timer I to be an event counter. Use mode 2 and display thc decimal
I
I
count on P2, PI, and PO continuously. Set the initial count to 99.
50. The TCON register is a(n) __ -bit register.
5l. True or false. The TCON register is not a bit-addressable register.
52. Give another instruction to perform the action of "SETB TRO". I
°
53. Program Timer in C to generate a square wave of 3 kHz. Assume that XTAL
= 11.0592 MHz.
54. Program Timer I in C to generate a square wave Of 3 kHz. Assume that XTAL
= 11.0592 MHz. ,
°
55. Program Timer in C to generate a' square wave of 0.5 kHz. Assume that
XTAL = 11,0592 MHz.
56. Program Timer I in C to generate a square wave of 0.5 kHz. Assume that
XTAL = 11.0592 MHz. , ,
57 Program Timer I in C to be an event counter. Use mode I and display the bina-
. ry count on P I and P2 continuously. Set the initial count to 2 O,0010,
th bi
58. Program Timer 0 in C to be an event counter. Use mode 2 and dISP ay e ina-
ry count on P2 continuously. Set the initial count to 20.
I. Two
2, 2.8
3, 8
4,
False , L r t;
5,
00100000 indicates Timer I. mode 2, software start and stop, and usmg XTA lor ircqucncy.
6, FFFFH 10 0000
7, FFH 1000
8, -200 is 38H; therefore, TH I = 38H
9, 2 msll ,085 ms = 1843 = 0733H where TH = 0711 and TL = 33H
10, 100 ms/1.085 ms = 92 or 5CH; therefore, TH = 5CH
277
Computers transfer data in two ways: parallel and serial, In parallel data
transfers, often 8 or more lines (wire conductors) are used to transfer data to a
device that is only a few feet away. Examples of parallel transfers arc pnnters and
hard disks: each uses cables with many wire strips. Although III such cases a lot of
data can be transferred in a short amount of time by using many wires in parallel,
the distance cannot be great. To transfer to a device located many meters away, the
serial method is used. In serial communication, the data is sent one bit at a time,
in contrast to parallel communication, in which the data is sent a byte or more at a
time, Serial communication of the 8051 is the topic of this chapter. The 8051 has
serial communication capability built into it, thereby making possible fast data
transfer using only a few wires.
In this chapter we first discuss the basics of serial communication. In
Section 10.2, 8051 interfacing to RS232 connectors via MAX232 line drivers is
discussed. Scrial port programming of the 8051 is discussed in Section I D.3. The
second serial port of DS89C4xO is programmed in Section I D.4. Section 1D.5 cov-
crs 8051 C programming for serial ports #0 and # I.
Serial Transfer
Parallel Transfer
l~s~e~n~d~e~rJI-_---j~~1
Receiver' DO
Sender Receiver
D7
• •
space
stop
bit
0 1 o o o o o 1 start mark:
;t~:--'
. .
bit ;
goes out last 07 t:
DO goes out first
Figure 10-3. Framing ASCII "A" (4IH)
Notice in Figure 10-3 th t he h '
hi h ' a w en t ere IS no transfer, the signal is I (high)
w IC IS referred to as mark The 0 (I )' ,
t " , , ,e ow IS referred to as space, Notice that the
ransmrssion begins With a start bit followed b DO ' ,
of the bits until thc MSB (D7) d f y uu, which ISthe LSB, then the rest
the character "A", ,an mally, the one stop bit indicating the end of
In asynchronous serial eommunicati ' h '
be programmed for data that' 7 8 bi ons, penp eral chips and modems can
IS or Its Wide Thi " ddi
of stop bits I or 2 Whl'le in Id ' IS IS III a dition to the number
" 0 er systems ASClI h
years, due to the extended ASCII h c araeters were 7-bit, in recent
c araeters 8-bit d t h b
some older systems due to the sl f ' a a as eeome common, In
, ' owness 0 the rec ' , , ,
stop bits were used to give the d '. ffici ,elvlllg mechanical device, two
, , cvice su IClent time t "
miSSion of the next byte In mod PC h . 0 organize Itselfbefore trans-
d ar d ,Assuming that we are'em s oweve th
tran r ' r, e usc of one stop bit is stan-
bi sJerrlllg a text til f ASC J
It, we have a total of 10 bils fi each ea I characters using I stop
b' or eac character' 8 b' f
It each for the start and stop b't Th ,Its or the ASCII code and I
' I s, erefore for e h 8 bi ,
ex tfa 2 b ItS, which gives 200//0 over h cad, ' ae - It character there are an
-
CHAPTE
In some systems, the parity bit of the character byte is included in the data
frame in order to maintain data integrity. This means that for each character (7- or
8-bit, depending on the system) we havc a single parity bit in addition to start and
stop bits. The parity bit is odd or even. In the case of an odd-parity bit the number
of data bits, including the parity bit, has an odd number of 1s. Similarly, in an
even-parity bit system the total number of bits, including the parity bit, is even. For
example, the ASCII character "A", binary 0 I 00 000 I, has 0 for the even-parity bit.
UART chips allow programming of the parity bit for odd-, even-, and no-parity
options.
The rate of data transfer in serial data communication is stated in bps (bits
per second). Another widely used terminology for bps is baud rate. However, the
baud and bps rates are not necessarily equal. This is due to the fact that baud rate
is the modem terminology and is defined as the number of signal changes per sec-
ond. In modems a single change of signal, sometimes transfers several bits of data.
As far 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 interchangeably.
The data transfer rate of a given computer system depends on communica-
tion ports incorporated into that system. For example, the early IBM PC!XT could
transfer data at the rate of 100 to 9600 bps. In recent years, however, Pentium-
based PCs transfer data at rates as high as 56K bps. It must be noted that in asyn-
chronous serial data communication, the baud rate is generally limited to
100,000 bps.
R5232 standards
To allow compatibility among data communication equipment made by
various manufacturers, an interfacing standard called RS232 was set by the
Electronics Industries Association (EIA) in 1960. In J 963 it was modified and
called RS232A. RS232B and RS232C were issued in 1965 and 1969, respective-
Iy. In this book we refer to it simply as .RS232. Today, RS232 IS th~ most Widely
used serial I/O interfacing standard. This standard IS used 111PCs and numerous
types of equipment. However, sinee the standard was set long before the advent of
the TTL logic family, its input and output voltage levels are not TTL compatible,
In RS232, a I IS . represente db y -, 3 to -25 V while a 0 bit IS +3 .to +25 Y, making
-3 to +3 undefined.For this reason, to connect any RS232 to a mlcroc:n~~~~ sys-
I converters such as MAX232 to convert t e ogre
tern we must use vo tage . MAX232 Ie chips are com-
levels to the RS232 voltage levels, and vice versa. t MAX232 is discussed in
monly referred to as line drivers. RS232 connecnon 0
Section 10.2.
RS232 pins .
. d their labels for the RS232 cable, com-
Table 10-1 provides the p111San I b I' DB-25P refers to the plug
DB 25 onnector In a e mg,
monly referred to as the - c h' ket connector (female). See Figure
connector (male) and DB - 25S I's for t e soc
10-4.
o •••••••••••••
•••••••••••• o
14 25
CHAPTE
l. OTR (data terminal ready). When a
term mal (or a PC COM par t)' IS 5
turned on, after going through a
<-.,
self-test, It sends out signal OTR to
indicate that it is ready for commu-
o •••• o
mcation .. If there is something ••••
wrong with the COM port, this sig-
nal will not be activated. This is an 6
9
active-low signal and can be used
to inform the modem that the com- Figure 10-5. DIJ..9 9-Pin Connector
puter is alive and kicking. This is
an output pin from OTE (PC COM Table 10-2: IBM PC DB-9 Signals
port) and an input to the modem.
Pin Description
2. OSR (data set ready). When OCE
I Data carrier detect (DCD)
(modem) is turned on and has gone
2 Received data (RxD)
through the self-test, it asserts OSR
3 Transmitted data (TxO)
to indicate that it is ready to com-
4 Data terminal ready (OTR)
municate. Thus, it is an output
from the modem (DCE) and input
s Signal ground (GND)
6 Data set ready (psR)
to the PC (DTE). This is an active-
low signal. If for any reason the 7 Reguest to send (RTS)
modem cannot make a connection 8 Clear to send (CIS)
to the telephone, this signal 9 Ring indicator (RI)
remains inactive, indicating to the
PC (or terminal) that it' cannot 1------------
accept or send data, OTE OTE
3. RTS (request to send). When the TxD TxD
OTE device (such as a PC) has a
byte to transmit, it asserts RTS to RxD RxD
signal the modem that it has a byte
of data to transmit. RTS is an ground
acti ve-low output from the DTE
and an input to the modem. Figure 10-6. Null Modem Connection
4. CTS (clear to send). In response to
RTS, when the modem has room for storing 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 OTE to start transmission.
S. OCO (carrier detect, or DCD, data carrier detect). The modem asserts signal
OCO to inform the DTE (PC) that a valid carrier has been detected and that
contact between it and the other modem is established. Therefore, OCO is an
output from the modem and an input to the PC (DTE).
6. Rl (ring indicator). An output from the modem (DCE) and an input to a PC
(OTE) indicates that the telephone is ringing. lt goes on and off in synchro-
nization with the ringing sound. Of the six handshake signals, this is the least
often used , due to the fact that modems take care of answering the phone.
However, if the PC is in charge of answering the phone, this signal can be used.
Review Questions
I. The transfer of data using parallel lines is (faster, slower) but
---- . (more expensive, less expensive).
2. True or false. Sending data to a printer is duplex.
3. True or false. In full duplex we must have two data lines one for transfer and
one for receive. '
4. The start and stop bits are used in the (svnch
nous) method. sync ronous, asynchro-
5. Assuming that we are transmitting the ASClI letter "E" (0 I00 0101' b' )
With no panty bit and one stop bit h h m mary
ally. ' s ow t e sequence of bits transferred seri-
6. In Question 5, find the overhead due t f .
7 ti
. Ca Ieu Iate the
e time 0 rammg
it takes to transfer 10 O· .
usc 9600 bps Wh I . ,00 characters as 111 Question 5 if we
. a percentage of lime is wast d d
8. True or false. RS232 is not TTL : e uc to overhead?
9 -compatible
10 What voltage levels arc used for binary 0 in' RS232?
. True or false. The 8051 has a built-in UART .
II. On the back of x86 PCs, we normally have . .
12. The PC COM ports arc designated b '0 - COM port connectors,
___ ' y as and Windows as and
SECTION 10.2: 8051 'CONNECTION TO RS232
In this section, the details of the physical connections of the 8051 to RS232
connectors are given, As stated in Section 10,2, the RS232 standard is not TTL
compatible; therefore, it requires a line driver such as the MAX232 chip to con-
vert RS232 voltage levels to TTL levels, and vice versa. The interfacing of 8051
with RS232 connectors via the MAX232 chip is the main topic of this section.
RxD and TxD pins in the 8051
The 8051 has two pins that are used specifically for transferring and receiv-
ing data serially. These two pins arc called TxD and RxD and are part of the port
3 group (P3.0 and P3.1). Pin I j of the 8051 (P3d) is assigned to TxD and pin 10
(P3.0) is designated as RxD. These pins are TTL compatible; therefore, they
require a line driver to make them RS232 compatible. One such line driver is the
MAX232 chip. This is discussed next.
MAX232
Vee
16
1C3 +
+ 2
8051 MAX232
C1 1
3 MAX232 6 11 11 14 2
TxDO (P3.1)
+
C2
4
5 T+
C4
13 3 '0 5
T11N T10UT 10 12
11 14 RxDO (P3.0) 08-9
R10UT R11N .
12 13
T21N T20UT
10 7
R20UT R21N
9 8
To save board space, some designers usc the MAX233 chip from Maxim.
The MAX233 performs the same job as the MAX232 but eliminates the need for
capacitors. However, the MAX233 chip is much more expensive than the
MAX232. Notice that MAX233 and MAX232 are not pin compatible. You cannot
take a MAX232 out of a board and replace it with a MAX233. See Figure 10-8
for MAX233 with no capacitor used.
Vee
13
14 7
11
12 MAX233 15
17 16 8051
MAX233
10 11
TxDO (P3.1) 2 5 2,-
T11N T10UT
2
5 4
R10UT R11N 31Jh
3
4 RxDO (P3.0) 10 3
T21N T20UT DB·9
18
R20UT R21N
20
19
6 9
TIL side
RS233 side
286
-
CH
SECTION 10.3: 8051 SERIAL PORT PROGRAMMING IN
ASSEMBLY .
Table 10-3: PC
Baud Rates . In this section we discuss the serial communication regis-
110 ters of the 8051 and show how to program them to transfer and
150 receive data serially. Since IBM PC/compatible computers are so
300 widely used to communicate with 805] -based systems, we will
600 emphasize serial communications of the 8051 with the COM port
1200 of the Pc. To allow data transfer between the PC and an 8051 sys-
2400 tem without any error, we must make sure that the baud rate of thc
8051 system matches the baud rate of the PC's COM port. Some of
4800
the baud rates supported by PC BIOS are listed in Table 10-3. You
9600
can examine these baud rates by going to the Windows
19200
Note: Some of the
HyperTcrminal program and clicking on the Communication
Baud rates sup- Settings option. The HyperTerminal program comes with
ported by 486/ Windows. HyperTerminal supports baud rates much higher than
Pentium IBM
PC BIOS. the ones listed in Table 10-3.
Table 10-4: Timer t TUt Register Values for Various Baud Rates
Solution:
Notice that II 12th of the crystal frequency divided by 32 is the default value up~n acti-
vation of the 8051 RESET pin. We can change this default settmg. This IS explained at
the end of this chapter.
11.0592 MHz
by UART To Timer I to
L -J ratethe baud
set
SBUF register
SBUF is an 8-bit register used solely for serial communication in the 8051.
For a byte of data to be transferred via the TxO line, it must be placed in the SBUF
register. Similarly, SBUF holds the byte of data when it is received by the 8051 's
RxD line. SBUF can be accessed like any other register in the 8051. Look at the
following examples of how this register is accessed:
MOV SBUF,#'D'
MOV SBUF,A ;load SBUF=44H, ASCII for 'D'
MOV A,SBUF ;copy accumulator into SBUF
;copy SBUF into accumulator
The moment a byte is written into SBUF, it is framed with the start and stop
bits and transferred serially via the TxD pin. Similarly, When the bits are received
serially via RxD, the 8051 deframes it by eliminating the stop and start bits, mak-
ing a byte out of the data received, and then placing it in the SBUF.
SCON (serial control) register
. The SCON register is an 8-bit register used to program the start bit, stop
bit, and data bits of data framing, among other things.
The fOllowing describes various bits of the SCON register.
CHAPT
SMO I SMI I SM2 I REN I TB8 I RB8 I TJ R1
SMO, SM1
. SMO and SM I are 07 and D6 of the SCON register, respectively. These
two bits determme the framing of data by specifying the number of bits per char-
acter, and the start and stop bits. They take the following combinations.
SMO SMI
o o Serial Mode 0
o I Serial Mode I, 8-bit data, I stop bit, I start bit
I o Serial Mode 2 '
I I Serial Mode 3
RB8 (receive bit 8) is bit D2 of the SCON register. In serial mode I, this
bit gets a copy of the stop bit when an 8-bit data is received. This bit (as ISthe ~ase
for TB8) is rarely used anymore. In all our applications we will make RB8 - O.
Like TB8, the RB8 bit is also used in serial modes 2 and 3.
TI
290
Example 10-2
Write a program for the 8051 to tr ansfer letter "An serially at 4800 ba ud , continuously.
.
Solution:
MOV TMOD,#20H ;Timer 1 , mod
0 e 2(auto-reload}
MOV TH1,#-6 ;4800 baud rate
MOV SCON,#50H ;8-bit, 1 stop, REN enabled
SETB TRl ;start Timer 1·
AGAIN: MOV SBUF,,#IIA" ;le~ter "A" to be transferred
HERE: JNB TI,HERE ;walt for the last bit
CLR TI ;clear TI for next char
SJMP AGAIN ;keep sending A
Example 10-3
Write
bit. Doa this
program to transfer the messa ge "YES" serially
continuously. . at 9600 baud, 8-bit data, I stop
Solution:
MOV TMOD,#20H ;Timer 1,'mode 2
MOV TH1,#-3 ;9600 baud
MOV SCON, #50H ;8-bit, 1 stop bit, REN enabled
SETB TRl ;start Timer 1
AGAIN: MOV A,#"yll ;transfer "yu
ACALL TRANS
MOV A, #11£11 ;transfer liE"
ACALL TRANS
;transfer IISIl
MOV A, #ltSH
ACALL TRANS
SJMP AGAIN ;keep doing it
;-----serial data transfer subroutine
TRANS: MOV SBUF ,A ;load SBUF
HERE: JNB TI ,HERE ;wait for last bit to transfer
CLR TI ;get ready for next byte
RET
Solution:
MOV TMOD,#20H T'
MOV TH1,#-6 ; ~mer 1, mode 2(auto-reload)
;4800 baud
MOV SCON,#50H
SETB TR1 ;8-bit, 1 stop, REN enabl~d
HERE: JNB ;start Timer 1
RI,HERE
MOV A,SBUF ;wait for char to come in
MOV P1,A ;save incoming byte in A
CLR RI ;send to port 1
SJMP HERE ;get ready to rece've
• next byte
;keep getting data
292
Example 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 HyperTerminal program to send and receive data serially. PI
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 send 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 , #OFFH ;make P2 an input port
MOV TMOD,#20H ;Timer 1, mode 2 (auto-reload)
MOV TH1, #OFAH ;4800 baud rate
MOV scon. #50H ;s-bit,l stop, REN enabled
SETB TR1 ;start Timer 1
MOV DPTR,#MYDATA ;load pointer for message
H 1: CLR A
MOVC A,@A+DPTR ;get the character
JZ B 1 ;if last character get out
ACALL SEND ;otherwise call transfer
INC DPTR jnext one
SJMP H 1 ; stay in loop
B 1: MOV A, P2 ; read data on P2
ACALL SEND ;transfer it serially
ACALL RECV ;get the serial data
MOV P1,A ;display it on LEDs
SJMP B_1 ;stay in loop indefinitly
t
·--------------serial data transfer. ACC has the data
SEND: MOV SBUF,A ·load the data
H2: JNB TI,H_2 ;stay here until last bit gone
- CLR TI ;get ready for next char
RET ;return to caller
,.----------------receive data serially in Ace
RECV: JNB RI ,RECV ,.wait here for char
MOV A, SBUF ,. save it in ACC
;get ready for next char
CLR RI
RET ,'return to caller
. The message
,
MYDATA: DB "We Are Ready", 0
END
8051
-,
) LED
PI
To TxO 7
PC
COM /
SW
port RxO P2 "\
"
MMING IN ASSEMBLY AND C 293
CHAPTER 10: 8051 SERIAL PORT PROGRA
Importance of the RI flag bit
In receiving bits via its RxO pin, the 805 I goes through the following
steps.
I. It receives the start bit indicating that the next bit is the first bit of the charac-
ter byte it is about to receive. .. '"
2. The -bit character is received one bit at lime. When the last bit IS received, a
byte is formed and placed in SBUF. . _
J. The stop bit is received. When receiving the stop bit the 8051 makes RI -k J ,
indicating that an entire character byte has been received and must be pIC e d
up before it gets overwritten by an incoming character.
4. By checking the Rl flag bit when it is raised, we know that a character has been
received and is sitting in the SBUF register. We copy the SBUF contents to a
safe place in some other register or memory before it is lost.
5. Aller the SBUF contents are copied into a safe place, the RI flag bit must be
forced to 0 by the "CLR RI" instruction in order to allow the next received
character byte to be placed in SBUF. Failure to do this causes loss of the
received character.
From the above discussion we conclude that by checking the RI flag bit we
know whether or not the 8051 has received a character byte. If we fail to copy
BUF into a safe place, we risk the loss of the received byte. More importantly, it
must be noted that the RI flag bit is raised by the 805 I, but it must be cleared by
the programmer with an instruction such as "CLR RI". It also must be noted that
if we copy SBUF into a safe place before the RI flag bit is raised, we risk copying
garbage. The RI flag bit can be checked by the instruction "JNB RI, xx" or by
u ing an interrupt, as we will sec in Chapter I I.
There arc two ways to increase the baud rate of data transfer in the 8051.
To see how the baud rate is doubled with this method, we show the role of
the SMOO bit (07 bit of the peON register), which can be 0 or I. We discuss each
case.
Baud rates for SMOD =0
When SMOO = 0, the 8051 divides 1/12 of the crystal frequency by 32 and
uses that frequency for Timer I to set the baud rate. In the case ofXTAL = 11.0592
MHz we have:
This is the frequency used by Timer I to set the baud rate. This has been
the basis of all the examples so far since it is the default when the 8051 is powered
up. The baud rate for SMOO = 0 was listed in Table 10-4.
Baud rates for SMOD =1
With the fixed crystal frequency, we can double the baud rate by making
SMOO = I. When the SMOO bit (07 of the PCON register) is set to I, 1/12 of
XTAL is divided by 16 (instead of32) and that is the frequency used by Timer 1
to set the baud rate. In the case of XTAL = 11.0592 MHz, we have:
Solution:
Example 10-7
Find the TH 1 value (in both decimal and hex) to set the baud rate to each of the following.
(a) 9600 (b) 4800 if SMOD = 1 Assume that XTAL = I] .0592 MHz.
Solution:
With XTAL = 11.0592 MHz and SMOD = I, we have Timer I frequency = 57,600 Hz.
(a) 57,600/9600 = 6; therefore, TH I = -6 or TH I = FAH.
(b) 57,600/4800 = ]2; therefore, THI = -12 or THI = F4H.
XTAL
oscillator -
G +12
Machine cyele freq
921.6 kHz
'.
rl + 16 157,600 Hz
J ~ 128,800
-~L . 32 I
SMOD = 0
Hz
To
__ Timer I
to set
baud
rate
296
-c
Example 10-8
Find the baud rate ifTHI = -2, SMOD = I, and XTAL = 11.0592 MHz. Is this baud
rate supported by IBM/compatible PCs?
Solution:
With XTAL = 11.0592 MHz and SMOD = 1, we have Timer 1 frequency = 57,600Hz.
The baud rate is 57,600/2 = 28,800. This baud rate is not supported by the BIOS of
the PCs; however, the PC can be programmed to do data transfer at such a speed. Also,
HyperTerminal in Windows supports this and other baud rates.
Example 10-9
Assume a switch is connected to pin Pl.7. Write a program to monitor its status and
send two messages to serial port continuously as follows:
SW=O send "NO"
SW=I send "YES"
Assume XTAL = 11.0592 MHz, 9600 baud, 8-bit data, and 1 stop bit.
Solution:
SW1 EQU Pl.?
ORG OH ;starting position
MAIN: MOV TMOD,#20H
MOV TH1,#-3 ;9600 baud rate
MOV SCON,#50H
SETB TR1 ;start timer
SETB SW1 ;make swan input
Sl: JB P2.1,NEXT ; check SW status
MOV DPTR,#MESS1 ; if' Sw=o display "NO"
FN: CLR A
MOVC A,@A+DPTR ;read the value
JZ Sl ;check for end of line
ACALL SENDCOM ,.send value to serial port
DPTR ,.move to next value
INC
SJMP FN ;repeat
DPTR,#MESS2 ;if SW= 1 d i sp lay "YES"
NEXT: MOV
LN: CLR A
MOVC A,@A+DPTR ,'read the value ,
MESS1: DB II NO ,0
If
MESS2 : DB lIYES",O
END
Solution:
SW BIT PI.2
ORG OH ;Starting position
MAIN:
MOV TMOD,#20H
MOV TH1,#-6 ·4800 baud rate
r (default)
MOV SCON,#50H
SETB TR1
SETB SW ;make SWan input
81: JNB SW,SLOWSP ;check SW status
MOV A,PCON ;read PCON
SETB ACC.7 ;set SMOD High for 9600
MOV PCON,A ;write PCON
SJMP OVER ;send message
SLOWSP: MOV A,PCON ;read PCON
CLR ACC.7 ;make SMOD Low for 4800
MOV PCON,A
OVER: ;write PCON
MOV DPTR,#MESS1
FN: ;load address to message
CLR A
MOVC A,@A+DPTR ;read value
JZ Sl
ACALL SENDCOM ;check for end of line
INC ;send value to the serial port
DPTR
SJMP ;move to next value
FN
;repeat
i----------- __
SENDCOM:
MOV SBUF,A
HERE: JNB ;place value in buffer
TI,HERE
CLR TI ;wait until transmitted
RET ;clear
/'return
i-------- _
MESS1: DB "The Earth l·S b t 0
END u ne Country",o
298
Interrupt-based data transfer
By now you might have noticed that it is a waste of the microcontroller's
time to poll the TI and RI flags. In order to avoid wasting the microcontroller's
time we use interrupts instead of polling. In Chapter II, we will show how to use
interrupts to program the 8051 's serial communication port.
Review Questions
I. Which timer of the 8051 is used to set the baud rate?
2. If XTAL = 11.0592 MHz, what frequency is used by the timer to set the baud
rate?
3. Which mode of the timer is used to set the baud rate?
4. With XTAL = 11.0592 MHz, what value should be loaded into THI to have a
9600 baud rate? Give the answer in both decimal and hex.
5. To transfer a byte of data serially, it must be placed in register _
6. SCON stands for and it is a(n) __ -bit register.
7. Whieh register is used to set the data size and other framing information such
as the stop bit?
8. True or false. SCON is a bit-addressable register.
9. When is TI raised?
10. Whieh register has the SMOD bit, and what is its status when the 8051 is pow-
ered up?
serial ports already installed. It also uses the MAX232 for the RS232 connection
DB9 The connections for the RS232 to the DS89C4xO of the MDE8051
W . .I
Trainer are shown in Figure 10-11. Notice that the first and seeond sen a ports are
designated as Serial #0 and Serial # I, 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 the default serial port since every version of the 8051 eomes 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 eaeh of the SFRs is shown
in Table 10-6. Notice that SCON has address 98H, SBUF has address 99H, and
finally PCON is assigned the 87H address. The first serial port is supported by all
assemblers and C compilers in the market for the 8051. If 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 ver-
sions of the 8051/52 mieroeontroller. Only a few versions of the 8051/52, sueh as
the DS89C4xO,come with the second serial port. As a result, the second serial port
uses some reserved SFR addresses for the SCaN and SBUF registers and there is
no universal agreement among the makers as to which addresses should be used.
In the case of the DS89C4xO, the SFR addresses of COH and C IH are set aside for
SBUF and SCaN, as shown in Table 10-6. The DS89C4xO technical doeumenta-
tion refers to these registers as SeON I and SBUF I since the first ones are desig-
nated as SCONOand SBUFO.
(T2) P10 1
40 Vee
(T2EX) P1, 1 2 39 PO.O(ADO)
(RXD1) P1,2 3
38 PO.1 (AD1)
(TXD1) P1,3 4
OS 37 PO.2 (AD2)
(INT2) P14 5 36 PO.3 (AD3)
(INT3) P1,5 6 89C4xO
35 P04 (AD4)
(INT4) P16 7 (89C420 34 PO.5 (AD5)
(iNT5) P1,7 8 89C430 33 PO.6 (AD6)
RST 9 89C440 32 PO.7(AD7)
(RXDO) P3,0 10
89C450) 31 EANPP·
(TXDO) P3,1 11 30 ALE/PROG
(INTO) P3.2 12 29 PSEN
(lNT1) P3.3 13 28 P2.7 (A15)
(TO) P3.4 14 27 P26(A14)
(T1) P3.5 15 26 P2.5 (A13)
(WR) P3.6 16 25 P24 (A12)
(RD) P3.7 17 24 P2.3 (A11)
XTAL2 18 23 P2.2 (A10)
XTAL1 19 22 P2.1 (A9)
GND 20 21 P2.0 (A8)
t:
Figure 10-10. DS89C4xO Pin Diagram
Notice Pl.2 and PI.3 pins are used by Rx and Tx lines of the 2nd serial
Vee
C3
16 +
+ 2
C1 1
3 MAX232 6 DS89C4xO MAX232
i
+
C2
4
5
I ~4 TxDO(P3.1) 11 11 14 2 5
ro
'C
RxDO(P3.0) 10 12 13 3 0 ~
Ul
T1IN T10UT
11 14
R11N 7 5 it
R10UT 20 ro
12 13 4 10 'C
TxD1(P1.3) 8 3 ~
Ul
T21N T20UT RxD1(P1,2j
3 9
10 7
R20UT R21N
9 8
SP Stack pointer
DPTR Data pointer 2 bytes
DPL Low byte 82H
DPH High byte 83H
PO" Port 0 80H
PI" Port I 90H
P2" Port 2 OAOH
P3" Port 3 BOH
JP" Interrupt priority control B8H
IE" Interrupt enable control A8H
TMOD Timer/counter mode control 89H
TCON" Timer/counter control 88H
T2CON" Timer/counter 2 control C8H
T2MOD Timer/counter mode control C9H
THO Timer/counter 0 high byte 8CH
TLO Timer/counter 0 low byte 8AH
TH I Timer/counter I high byte
8DH
TL I Timer/countcr I low byte
8BH
TH2 Timer/counter 2 high byte
CDf-/
TL2 Timer/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 ort
98H
SBUFO Serial data buffer first serial art
PCON Power control 99H
87H
SCON I" Serial control (second serial port)
COH
SBUF I Serial data buffer (second serial port)
" Bit-addressable CIH
302
SMO I SM] I SM2 I REN I TS8 I RE8 I TI I RJ
Example 10-11
Write a program for the second serial port of the DS89C4xO to continuously transfer the
letter "A" serially at 4800 baud. Use 8-bi! data and 1 stop bit. Use TImer I.
Solution:
Solution:
SCONI EQU OCOH
SBUFI EQU OClH
TIl BIT OClH
ORG OH ;starting position
MOV TMOD,#20H
MOV THl,#-3 ; 9600 baud rate
MOV SCONl,#50H
SETB TRI
MOV DPTR,#MESSI ;display "Hello·
FN: CLR A
MOVC A,@A+DPTR ;read value
JZ SI ,'check for end of line
ACALL SENDCOM2 'send to serial port
INC DPTR ;move to next value
SJMP FN
SI: SJMP SI
SENDCOM2:
MOV SBUFl,A
HEREl: JNB ;place value in buffer
TIl,HERE 1 ;wait until transmitted
CLR TIl ;clear
RET
MESSI : DB "Hellon,o
END
Example 10-13
Program the second serial port of the DS89C4xO to receive bytes of data serially and put
them on PI. Set the baud rate at 4800, 8-bit data, and 1 stop bit.
Solution:
SBUFI EQU OClH
;second serial SBUF addr
SCONI EQU OCOH
;second serial SCON addr
RIl BIT OCOH
ORG OH ;second serial RI bit addr
;starting Position
MOV TMOD,#20H
MOV THl,#-6 ;COM2 uses Timer 1 Upon reset
; 4800 baud rate
MOV SCONl,#50H
SETB TRI ;COM2 has its own SCONI
HERE: ;start Timer 1
JNB RIl,HERE
MOV A,SBUFI ;wait for data to come in
;save data
MOV Pl,A
CLR RIl ;display on PI
SJMP HERE
END
304
Example 10-14
Assume that a switch is connected to pin P2.0.
Write a program to monitor the switch and perform the following:
Solution:
SCONl EQU DCOH
TIl BIT OC1H
SWl BIT P2.0
ORG OH
MOV ;starting position
TMOD,#20H
MOV TH1, #-3 ;9600 baud rate
MOV SCON,#50H
MOV SCON1,#50H
SETB TR1
SETB SW1 ;make SWl an input
Sl: JB SW1,NEXT ;check SW1 status
MOV DPTR,#MESS1 ;if SW1=0 display "Hello"
FN: CLR A
MOVe A,@A+DPTR ;read value
JZ Sl ;check for end of line
ACALL SEND COM 1 ;send to serial port
INC DPTR ;move to next value
SJMP FN
NEXT: MOV DPTR,#MESS2 ;if SW1=1 display "Goodbye"
LN: CLR A
MOVC A,@A+DPTR ;read value
JZ Sl ;check for end of line
ACALL SENDCOM2 ;send to serial port
INC DPTR ;move to next value
SJMP LN
SENDCOM1:
MOV SBUF,A ;place value in buffer
HERE: JNB TI,HERE iwait until transmitted
CLR TI ;clear
RET
SENDCOM2:
MOV SBUFl,A ;place value in buffer
HEREl: JNB TI1,HEREl ;wait until transmitted
CLR TIl ;clear
RET
MESS1: DB I1Helloll
I 0
MESS2: DB /lGoodbyerr,U
END
As we stated in the last chapter, the SFR registers of the 8051 are accessi-
ble directly in 8051 C compilers by using the reg51.h file. Examples 10-15
through 10-19 show how to program the serial port in 8051 C. Connect your 8051
Trainer to the PC's COM port and usc HyperTerminal to test the operation of these
examples.
Example] O-IS
Write a C program for the 8051 to transfer the letter "A" serially at 4800 baud continu-
ously. Use 8-bIt data and 1 stop bit.
Solution:
#include <regSl.h>
void main(void)
(
TMOD=Ox20;
TH1=OXFA; //use Timer 1,8-BIT auto-reload
SCON=OxSO; //4800 baUd rate
TR1=l;
while(l)
(
SBUF=' A' ;
While (TI==O) ; //place value in buffer
TI=O;
306