The 8051 Microcontroller and Embedded Systems Second Edition Muhammad Ali Mazidi Janice Gillispie Mazidi Rolin D Mckinlay
The 8051 Microcontroller and Embedded Systems Second Edition Muhammad Ali Mazidi Janice Gillispie Mazidi Rolin D Mckinlay
The 8051 Microcontroller and Embedded Systems Second Edition Muhammad Ali Mazidi Janice Gillispie Mazidi Rolin D Mckinlay
Prentice Hall
Upper Saddle River, New Jerse y Columbus, Ol-io
man's gIor'y lieth in his kncwledge,
his upri@t conduct, his praiseworthy character,
his wisdom, and not in his nationality o¿ rank.
Baha’u'llah
CONTfiHTS AT A GLANCE
CHAPTERS
: ›:itroduction to Computing l
1: ‘‹ne 8051 Microcontrollers 23
2' *.*)51 Assembly Language Programming 35
3i J!›mp, Loop, and Call Instructions 65
4' I *â Port Programming 83
5: i*I5l Addressing Modes 95
6: 'rithmetic Instructions and Programs 109
7. 1-r›gic Instructions and Programs 127
Single-bit Instructions and Programming 143
- timer/Counter Programming in the 6051 157
lG: *.*151 Serial Communication 183
11 Jnterrupts Programmirg 209
12! J’.cal-world Interfacing I: LCD, ADC, and Sensors 235
13: P.cal-wor!d Interfacing II: Stepped Motor, Keyboard, DAC 255
14: *› 151/31 Interfacing to External lvlemory 273
*.t)31/51 Interfacing to the 8255 303
APPENDICES
http://developer.intel.com/design/auto/mcs51/manuals
ABOUTTHSAUTHORS
Muhammad Ali Mazidi holds Master's degrees from both Southern
Methodist University and the University of Texas at Dallas, and currcntly is com-
pleting his Ph.D. in the Electrical Engineering Departmcni of Southern Methodist
University. He is a co-foundcr and chief researcliér of Microprocessor Education Group,
a company dedicated to bringing kr.owi•dge of microprocessors to the widest possible
audience. lie also teaches microprocessor-based system dcsign at DeVry Institute of’
4fichnology in Dallas, Texas.
Janice Giilispie Mazidi has a Master of Science degree in Computer
Science from the University of North Texas. After several years experiefice as a software
engineer in Dallas, she co-founded Microprocessor Education Group, where she is the
chief technical writer and production manager, and is responsible (or software develop-
ment and testing.
The Mazidis have been married since 1985 and have two sons, Robert
Nabil and Michael iamal.
The authcrs can be cor‹tacted at the following address if you have any com-
ments or suggestions, or if you find any errors.
mm.azidi@Tal.‹âevry.edu
This volume is dedicated to the memory of Dr. A. Davoodi, Professor of
p‹ hran L'niversity, who in the tumultuous yea'rs of my youth taught me th.e
importanceof an independent semi ch for truth.. -- Muhammad Ali Mazidi
CHAPTER 0
BNVRODUC&QON TO
OBJECTIVES
HH Convert any number from base 2, base 10, or base 16 to any 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, NOPR
Use logic =qates to diagram simple circuits
Explain the difference between a bit, a nibble, a iiyte, and a word
Give precise mathematical definitions of the terms kilobyte, megabyte,
terabyte, and gigabyfe
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 ty pe of bus
Describe the role of the CPU in computer systems
List the major components of the CPU and describe the purpose of each
To understanci the soft•ware and hardware of a microcontroller-based sys-
tem, one must first master some yep' bas.c concepts underlying computer
design. Jp {his chapter (which in the tradition of digital computers can be cal/ed
Chapter
0), the fundamentals of numbering and coding systems are presented. After an
introduction to logic gates, an overview of the workings inside the computer is
given. Finally, in the ›asi section we give a brief history of CPU architecture.
Although some reader may .have an adequate background in many of the
topics of this chapter, it is recommended that :h-• material be scanned, however
briefly.
Solution:
Quotient Remainder
25/2 = 12 1 LAB (least significant bit)
12/2 = 6 o
6/2 = 3 o
3/2 = 1 1
1/2 = 0 l MSB (most significant bit)
Example 0-2
Convcrt 110012 to decimal.
Weight: 16 8 4 2 1
Digits: 1 1 0 0 1
Sum: l6+ 8+ 0+ 0+ l=25l0
Knowing ihe weight associateci with cach binary bit position all ws 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 :o convert 3910 to binary. Solution:
Weight: 32 16 8 4 2 1
1 0 0 1 1 1
32 + 0 + 0- 4+ 2 r I = 39
Therefore, 39;0 = 1001112.
Example 0-5
C .ivert hex 29B to biI1'ury.
So!•.ition:
2 9 B
— 0010 1001 1011
Dropping the leading zeros gives 1010011011.
Converting from decimal to hex
Converting from decimal to hex could be approached in two ways:
1. Conven to binaw târst and then convert to hex. Example 0-fi shows this
method of cor.vening decimal to hex.
2. Convert directly from decimal to hex by repeated di ision, keeping track of
the remainders. Experimenting with this method is left to the reader.
Example 0-6 ,
(a) Convert 45 ;0 to hex.
Example 0-7
Convert the following hexadecimal numbers to decimal.
Solution:
Binary Decit ml
! 101 lo 9
+ 1001 22
10110
6
2’s compien1ent
To get the 2’s complement ot’ a binary nuiiiber, invert ali the bits and
then add l to the result. inv•Hing the bits is simply a matter of’ changing all 0s
to 1s and 1s to 0s. Ti:is is catled the 'r complement. See Example 0-9.
Example 0-9
Take thc 2’s complement of l00lll0l.
SOtutiOit:
1001-1101 binary number
01100010 l's complement
Example 0-10
Perform hex addition.: 23D9 + 94BE.
TO ltltlo11:
23D9 LSD: 9 + 14 = 23 2 - i 6 — 7 witi: a carry
+ 94BE 1 + 13 + 1i — 25 23 - 16 = 9 with a case
B897 1+3+4—8
MSD: 2 + 9 = B
So!:ition:
Review Questions
1. Why do computers use the binary number system instead of the decimal sys-
tem?
2. Convert 3410 to binary and hex.
. Convert 1101012 to hex and decimal.
4. Perform binary addition: ! 01100 + 101.
5 Convert 1011002 to its 2’s complement repres‹:ntation.
6. Add 36BH + F6H.
7. Subtract 36BH - F6H.
8. Write “80x86 CPUs” in its ASCII code (in hex form).
8
SECTiON 6.2: GiG!TAL PRliv1ER
FOR gate 0
1 0
The XOR gate performs an exclusive-OF
operation on th• inputs. Exclusive-OR produces a 1 X — NOT X
output if one (but only one) input is ! . lf both
operands are 0, the output is zero. Likewise, if both
Logical XOR Function
operands are 1, the output is also zero. Notice from
the XOR truth table, that whenever the two inputs Inputs Out ut
acre the same, the output is zero. Th.is function can be
used to compare two bits to see if they are the sane. XY X XOR
Y00 0
01 1
NAND and NOR gales 10 1
The NAND gate functions like an AND gate 1 1 0
with an inverter on the output. It produces a zero out- X
X XOR Y
put when all ir.puts are 1; otherwise, it produces a 1 Y
output. The NOR gate functions like an OR gate with
an inverter on the outpvt. It produces a l If all inputs
are 0. Gtherwise, it produces a 0. NAMED and L'OR Logical NAND £ unction
gates are used extensively in digital design because Ji;pu:s
they ar- easy and inexpensive to fabricate. Any cir-
_ fi«'.Pt
cuit that can be designed with .AND, OR, XOR, and X Y X NAND Y
INVERTER gates can be implemented using only 0 0 “i
NAND and FOR gates. A simple example of this is 0 1 1
given below. Notice ir. LAND, that if any input is 1 0 1
zero, the output is one. Notice in FOR, that if any 1 1 0
input is one, the output is zero.
X NAND Y
10 "
Notice that when we add 1 I we get 0 w'ith a car ry io the next higher
place. We wil! i ‹ced to determine the sum and the carty for t!iis design. Notice that
th.e sum column above matches the. output tor the XOR function, and that the carry
column iiiatehes the output for the AND function. Figure 0-3 (a) shows a simple
adder ilnplenienteci witi‹ XOR and AND gates. Figure 0-3 (b) shows the same
logic circuit iliiplemented with .6ñ!D and OR gates.
X Sum
— Cargo
X Carry
(a) Half-Adder *Using XOR and AND (a) Flalf-iidder Using AND, OR, I nvertei s
x Half— Carry
r Sum .Adder
r inal
Carry
Sum
— C OUt
Adde “
C Jp. ' Carry
C in
Final Sum
Flip-fIO|gS X1 S1
y1 Full
A widely used component in digital Addei
systems is the flip-flop. frequently, flip- Carry
flops are used to store data. F!gure 0-8
shows the logic diagram, block diagram,
and truth tabie for a flip-flop.
The D flip-flop is widely used to X2 S2
Full
latch data. Notice from the truth table that AdderCarn/
Y2 S3
a D-FF grabs the data at the input as the
clock is activated. A D-FF holds the data
as long as the power is on.
Figure 0-6. 3-Bit ii‹ider Using 3 Full-Adders
LSB LSB
(a) Address decoder for 9 (binary 1001) (b) Address decoder for 5 (binary 0101)
The output of the AND gate will be 1 Tne output of the AND gate will be 1
if and on1Y if the input is binary I 0c"1. if and only if the input is binary 010 I .
D Q
No x no change
T 0 0
Clk
Clk 1 1 1
x = don't care
(a) Circuit diagram (b) B!ock diagram (c) ‘1’! utii table
Peripherals
Memory
(monitor, printer, etc.
Data Bus
Read/write
Control Sus
foremost among the resources at the disposal of the CP'J are a number of reg-
i. l‹.•rs. The C.*U uses registers to store information temporarily. The
informa- tion could be two values to be processed, or the address of the value
needed to be fetched from memory. Registers ins'de the CPU can be 8-bit,
16-bit, 32-bit, '›t c’ en 64-bit registers, depending on the CPU. In general, the
more and big- Dyer the registers, the better the CPU. The disadvantage of more
and bigger reg- i.sk:re is the increased cost of such a CPU.
‘the CPU also has wb.at is called the ALU (arithmetic/logic unit). The ALU
cation of the CPU is responsible fr›r performing arithmetic functions such as
id, subtract, multiply, and divide, and logic functions su*h as AND, OR,
and
J(Very CPU has what is called a program counter. The function of the
program c‹iunter is to point to the address of the n•xt instruction to be executed.
As each instruction is executed, the program counter is incremented to
point to the
•!! âtess of the next instruction to be executed. I: is the contents of the
program c• Hunter that arc placed on the address bus to find and fetch the
desired instruc-
/i.›n. In the IBM PC, the program counter is a register called iP, or the
insir.ic- 1.ion pointer.
4.
’l'he function of the instruction decoc!er is to interpret the instruction fetched
into the CPU. On• 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 C.°U capable of understanding more instructions
requires more transistors to design.
Internal working of computers
To demonstrate some of the concepts discus“sed above, a step-by-step
"analysis of the process a CPU would go through to add three numbers is given
next. Assume that an imaginary CPU has repl sters called A, B, C, and D. It has
an
$-bit data bus and a l6-bit address bus. Therefore, the CPU can access memory
ffom addresses 0000 to FFFFH (for a total of 10000H locations). The action to be
QCrfprmed by the CPU is to put heKadecimal va!ue 21 into register A, and then add
to register A values 42H and 12H. Assume that the code for the CPU to move a
x'alue to register A is IN 11 0000 (BOH) and the code for adding a vaiue to
register A is 0000 0100 (04H). The necessary step• and code to perform them are
as UI- lOwS.
The actions perfonned by the CPU to run the program above would be as
follows:
1. The UPU's program count•r can have a value between 0000 and FFFFH. The
program counter must oe set io the value 1400i-I, indicating the address of
the tirst instruction cGde to be executed. After the pt ogram counter has been
loaded wi.h the address of the first instruction, the CPU is ready to execute.
2. The CPU puts l400H on the address bus and semis it out. The memory cir-
cuitry finds the location while tne CPU activates the READ signal, indicating
to memory that it wants the byte at location 1400H. This causes the contents
of memory location 14G0H, which is BG, to be put on the data bus and
brought into the CPU.
3. The CFU decodes i:le instt uction B0 with the help of its instruction decoder
dictionary. When it finds the definition for that instruction it knows it must
bring into register A of the CPU the byte in the next memory location.
Therefore, it commands its control!er circuitry to do exactly that. When it
brings in value 21H from memory location 1401, it makes sure that the doors
of all registers are closed except register A. Therefore, when value 21H comes
into the CPU it wiil go directly into register A. After completing one instruc-
tion, the program counter points to the address of the next in.struction to be
exe- cuted, which in this case is i 402H. Address 1402 is sent out on the
address bus to fetch the next instruction.
4. From memory location 1402H it fetches code 04H. After decoding, the CPU
kno that it must add to the contents of register A t!i byte sitting at the nex:
address (1403). After it brings the value (in this case 42!I) into the CPU, it
pro- vides the contents of register A along with this value to the ALU to
perform the addition. It then takes the result of the addition front the ALU's
output and
Program Counter
Internal buses
Contr
Pip•ure 0-11: Internal Block Diagram: of a CPU
Wu
Review Questions
How many bytes is 24 kilobytes?
s
18
7. h ist :he tlwee types of‘ btises found in computer systems atid state briefly the
purpose of each type of btis.
8. State which of” the following is unidi› cctional and which is bidirectional.
(a) data bus (b) address bus
9. If an addr ess btis for a gi'zen computer has 16 lines, what is the inaximuiii
fl1T1Oli!*.t ot’ r.ienaory it can access ?
10. What docs “A CU” stand for'? What is its purpose’?
1.1. !4ow ai e registers used in eoiiiputer systems?
1.2.What is the ptli pose of the prograiii counter?
1 u. What is the pu1 pose of the instruction decoder?
SUMh1ARY
COFJPUTER
20
(e) flow many K is 1 inc3?
(f) What is the exact value (in decimal) of i s'ga?
(g1 How many K is 1 giga?
(h) How many meg is 1 giga?
(i) If a given computer has a total of 8 megabytes of in•1uory, how many
bytes (in deciiiial) is this?• How iTlany kilobytes is this?
22. A givcn mass storaSC devic• such as a hat d disk can stoi e 2 Sigabytcs o I in.for-
mation. Assuiiiing heat each page of text has 25 rows and each low has 80
columns of ASCI I characters (each character = I bytc), approximately how
many pages of information can this disk store?
23. In a given byte-addressable computer, memory locations 10000i-i to
9FFFFH are available for user programs. The first location is l0000H and
the last loca- tioils 9FFFFH. Calculate the followiiig:
(a) The total number of bytes available (in decimal)
(b) Thc total number of kilobytes (in decimal)
?4. A given computer has a 32-bit data bus. What is the largest number that can
be carried into the CPU at a time?
25. Oe[ow are listed several computers with their data bus widths. For each com-
puter, list the maximum value that can be brought into the CPU at a tilue (in
both hex and decimal).
(a) Apple 2 with an 8-bit data bus
(b) IBh4 PS/2 with a 16-bit data bus
(c) IBM PS/2 model 80 with a 32-bit data bus
(d) CRAY supercomputer with a 64-bit data bus
26. Find the total amount of memory, in the •anits requested. for ach of th• fol-
1c›wing CPUs, given the size of the address buses.
(a) 16-bit addi‘ess bus (in Yr}
(b) 24-bit address bus (in meg)
(c) 32-bit address bus (in megabytes and giga.bytes)
(d) 48-bit address bus (in megabytes, gigabytes, and terabytes)
27. Regarding the data bus and address bus, '+h'c!i is unioirectional and which is
bidirectional?
2+. ’Vhich register of the CP'N holds the address of the instt uction to be fetched?
2<. Whicn section of the Ci'U is responsible for performing addition?
30. List the three bus types present in every CPU.
22
CH.4PTER 1
THE
RICRO6OHTRObLERS
OBJECTIVE 23
S
data bus
c.»u ROM
Figure 1-1. Microprocessor System
I Contrasted With Microcontroller System
General- Purpose h4icro- processor Serial
A system designerRC›M using a general-purpose
I/O Timer microprocessor such as the
COM
Pentium or the 68040 must add RAM, °ort ROI›4, I/O ports,
Port and tin.ers
I/Oexternally
Timer toSerial
make them functional. Although the addition of external RAM, ROM, and UOCOM
ports makes these systems bulkier and much more expCnsive, they have thePort
Address be..
advan- tage of versatility such that the designer can decide on the amount of
RAM, ROM, and I/O Microprocessor
(a} General-Purpose Syst•ln
ports needed to fit the task at hand. This is not the case
(b) filicrucontroller
with microcon- trollers. A microcon'rolier has a CPU (a microprocessor) in
addition to a fixed amount of RAM, ROM, I/O ports, and a timer all on a single
chip. In other words, the processor, the RAM, ROM, I/O pori and timer are all
embedded together on one chip; therefore, the designer cannot add any external
memory, I/C›", or timer to it. The fixed amount of on-chip ROM, RAM, and
number of I/O ports in micro- controllers makes them ideal for many
applications in which cost and space are
21
critical. In rivalry app!ications, for exaiiiple a I V retinoic control,
Home there is no need for the computing power of a 486 or cvcn an 5086
in icroprocessor.
Appliances In.tercom 7elepficrics Security systemsln man.y applications, the space it takes, the
garage door openers 9o› 'ei it consumes, and the price per unit are liiuch more critical
^.nswci ing machines Fax machines
consideratioiis than the computing power. These applications
Jomc computcrs most often require some I/O operations to 1 ead sisnals and turn on
rv and olT cci tail hits. Foi this rcasoi sowc call thcsc processoi's
Cable "IV tuner I Fi P. “itty-bitty processors” (see “Good Things in Siua!1
VCR
Packages
Caiizcorder
.AiCellt!1ar
R-smote controls Video games e Generating
phonesBig Product
ivlusical Opportunities”
instruments by MickLighting
Se ’ing machines Gi ehan,
control Paging
Camera B5 TE iiiagazine, September 1994; www.byte.coin, loi an excel-
Pinball machines Toys lent discussion of !*iicrocoi‘itrollers).
Exercise equipment lt is interesting to note that solne liiicl ocontroller rrianu-
' factuiers have gone as far as i›ritegrating an A DU (analog-to-digi-
tal co‹ivei ter) and other per iphe:als ilito the microcontroller‘.
Microcontrollers for emb dded systems
In the literature ‹discussing iiiicroprocessors, we often
see the term embedded syster.i. Microprocessors and
microcontrollers ate « idely used in embedded system products.
An embedded pioduct uses a microprocessor (or microcontroller)
to do one task and one task only. A printer is an example of
•mbedded system since the pi'ocessor inside it perforiiis one ta'sk
office only; namely, get- ting the data and printing it. Contrast this with
Telephones Computers a Pentium-based PC (or any x86 IBM-compatible PC). A PC can
Seeul itj‘ s3'stems be used for any number of applications such as woitl proc•ssor,
Fax i.iochine Microwave Cop‹er print-server, bank teller t•rminal, video game player, networx
Laser printer Color print•: Paging
! scrver, or internet ter- normal. Software for a variety of
applications can be loadcd and run Of coursc (he reason a PCB
can perform myriad tasks is that it has PROM memory and an
operating system that loads the appli- cation software into RAM
and lets the C.*U run it. In an eibed- cued s;•sterr., there is Gr.1y
oxic application software that is *ypical- ly burned into ROM. .In
Auto
xS6 PC contains or is connected to c.r- iots er.ibedded products
i rip computer Engine control Air bag
ABS such as the keyboard, printei‘, modem, disk controller, sour.d
Instrumentation Security system card, CD-ROMcontrol
Transmission driver, mouse, and
Entertainment so on.
Climate Each
control one phone
Cellular of these
Keyless entry
peripherals has a inicrocontro! er inside it that performs only one
task. For example, inside every mouse there is a inicrocontroiler
to perform the task of finding the mouse posi- tion and sending ii
to the PC. Table l -1 lists some embedded products.
Choosing a microcontroller
The:’e- are four major 8-bit nici‘ocontt’olleis. They are: Motorola's 6811,
Intel’s 8051, Zilog's ZS, and PIC l 6X front Microchip Technology. Each of the
abovc iriicrocontiollers has a unique inst1‘uction set and register set; therefore,
they are not compatible with each other. Programs written for one will not run on
the other s. There are also 16-bit and 2-bit microcontrollers made by various chip
makers. With all these differ ent na ict'oconti ollers, what criteria do designers
con- sider in choosing one? Thi'ee criteria in choosing m ici otontrollers are as
follows: l ) meeting the computing needs ot the task at hand efficiently and cost
effective- ly, (2) availability of software development tools such as compilers,
asseiiible.rs, and ‹!ebuggei s, and (3) wide availability ‹ilJd relial › c sources of
the inicrocon- trol lci Next we elabot ate fair ther on each o1 the abo c critei ia.
26
Criteria for choosing a microcontro!Ier
I. 1"hc fiist and rorcnzost ct itcrioiz in choosing a mici oconti ollcr is that it must
mcct thc task at hand efficiently and cost cftfictivcly. In analyzing the nccds of
a microcoi trullcr-based projcct, we must fiist sce wlzcthci ai› g-bit, 16-bit, or
32-hit microcontt ollci can bcst handle the computing nccds of tl c task most
(just j'y |y. A i11rH1 otl1CI Col1SIdCratIOilS Il1 tl1I S CatCL',OI y alC:
(a) Speed. Wh:•t is the highest speed tizat the n iciocoiztrollci sup/ooi Is?
(b) Packaging. Docs it conzc its 40-pin DIP (drtt‹l ii linc package) or a QFP
(qtiad 11a: pac!:i1Je), or sonic other packaging for iiiat? This 's ilTlportant in
ter:iis of” spc‹ce, asseiTlbling, and prototyping the child p'odticl.
(c) Power consumption. This is especially critical for battery-powered plod-
ucts.
The aiiiount of‘ RAM and ROM on chip.
3“1ie nun er of i/O pins and the tinier on tlic chip.
How casy it is to upgrade to higher-per for mance Gr lower power -con-
sriiiiption versions.
(g) Cost per’ unit. This is important in terms of the final cost of the product in
which a lnicrocontrollei is used. For example, there are ir icrocontrollers
that cost 50 cents per unit when purchased 100,000 units at a tiiiie.
In this s•.ction we first look at the various members of the 805 i family of
microcontrollers and their internal features. Plus w'e see who are the different
man- ufacturers of the 8051 and what kind of products they offer.
.4 brief history of the 8051
In l fi81, Intel Corporation introduced an 8-Sit microcontroller called the
8051. This microcontroller had 128 bytes of RAM, 4K bytes of on-chip ROM,
two timers, one s@ ial port, and four ports (eash S-bits wide) all on a single chip. At
thee i'm• it v.as a!so referred to ms a “system on a chip.” The 8051 is an 8-oit
proces- scr. meaning that the CPU can work on only 8 bits of data at a time. Data
larger than 8 bits has to be broken into S-bit pieces to be processed by the CPU.
The 8051 has a total of four I/O ports, each 8 bits wide. See Figure 1-2. Although
the 805 l can laave a maximum of 64K bytes of on-chip ROM, many
manufacturers have put o!‘.ly 4K by*es on th• chip. This will be discrissed in
more detail later.
TU.e 8051 became widely popular after Intel allowed other manufacturers
to make and ir.at ket any fiiavor of the 5051 they piease with the condition that
they reinaln code-compatible with. the 8051. This has led to :iiany vei'sions of
the 8051 with different speeds and amounts of on-chip ROM marketed by more
than half a dozen manufacturers. Next we review some of them. It is important
tO ilote that
although there are different flavors of the 8051 in terms Table 1-3: Features of the 8051
ot speed and amount of on-cfiip ROM, they are all com-
patible with the or iginal 8051 as far as the instructions Feature Quantity
are concerned. This means that if you write your ROM 4K bytes
program for one, it will run on any one of them RAM 128 bytes
regardless of the man- ufactui er. Timer 2
I/O pins 32
8051 microcontroller Serial port l
Tire 80 1 is the original member of the 8051 Ir‹ic! rupt sources 6
Note. ROM amount indicates on-chip
fam- ily. Intel refers to it as MCS-51. i able 1-3 shows program space.
the main features of the 8051.
28
EXTERNAL INTERRUPT S
ON-CHIP ROM
Y Y for program code
INTERRUPT ——— ON—CHIP RAM ETC.
CONTROL ” TIMER 0
TIIV!ER 1 -<
CPU “
BUS 4 IO SERIAL
OSC CONTROL PORTS . ORT
COUNTE
TXD RXD
P0 P1 P2 P3
ADDRESS/DATA
INPU
8052 microcontroller
The .°.052 is another irembei of the 805 i family. Thc 8052 has all the
s:an- dard featui'es of the 8051 in addition to an extra 12° bytes of RAM c.nd an
extra timer. In otfiei‘ words, the 8052 has 256 bytes of RAT* and 3 tii-crs. It a!so
has 8K bytes of on-chip progi'am RO›Vi instead of oK bytes. See t aS!c 1-4.
Ta'ole 1-4.: Com arison of 8051 FamilMembers
at! prograiiis ’ritten to’ the 8051 will run on the 8052, but the i ever se is not true.
Notice that the real-tilTle clock (PTC) is dit?erent from the iiirer. The
real- tiie clock generates and keeps the time of day (hr-min-sec) and date (yr-
mon-day) even when the power is off.
CHAPTER 1: THE 8051 MICROCONTROLLERS Sl
There are various speed and packaging versions of the DS5000 US S(1OWi1
in Table 1-8. For example, DS5000-8-8 has 8K NV-RAM and a speed of 8MHz.
Often the DS5000-8-12 (or DS5000T-8-12) is ideal for many student projects.
Review Questions
1. Name three features of the 5051.
2. \fhat is the major difference between the 8051 and 8052 inierocontro!!ers?
3. Give the size of RAM in each of the following.
(a) 8051 (b) 8052 (c) 8031
4. Give tire size of the on-chip ROM in each"of the following.
(a) 8051 (b) 8052 (c) °03 l
5. The 8051 is a(n) -bit inicroprocCssor.
6. State a major difference between the 8751, the AT89C51 and the DS5000.
7. List additional features introduced in the DS5000T that are not present in the
DS5000.
8. Ti‘rie or false. The AT89C5 l-12PC rhip has a DIP”package.
9. The AT89C5 l- l2PC chip can handle a maximum frequency of MHz.
10. The DS5000-3a has K b acs of on-chip NV-RAM for programs.
S2
SUMMARY
This chapter discussed the role and importance of microcontrollers in
everyday life. Microprocessors and microcontrollers were contrasted and com-
pared. We discussed the tise of iiiicioccntrollers in the embedded market. We
also discussed criteria to consider in choosing a microcontroller such as speed,
ieio- ry, I/O, packagins. and cost per unit. The second section of this chapter
described
various family numbers of’the 8051, such as the 8052 and 8031, and their features.
In addition. we discussed vai iotis versions ot’ the 5051 such as the AT89C5 I
and DS5000, which are marketed by suppliers other than lntel.
PROBLEMS
1. 125 b acs of RAM, 4K bytes of on-chip ROM, four 8-hit I/O ports.
2. The ?•L52 has everything that the 8051 has, plus an extra tim.er, and the on -c!:. :
byte› :n›tead of 4K bvtes. The RAM in the 8052 is 236 by:•s instead of ! 28 ! ,
3. Boti•. :.-.e 605 l and the S03 1 Isa 'e 1 28 bJ'tes of RAM and the S†52 has 25fi l›;
4. (a) - K oytes (0) c8 K bytes (c) OK bytes
5. 8
6. The fiiñ'erence is the type of on-chip ROM. In the 575 [ it is UV-EPRGM: in i!
is l“. : . and in the DS5000 it is N \'-RARI.
7. DS5fi *OT hat a read-time clock (RTC).
S. True
34
CHAPTER 2
8051 &SSEMBL9
L&HGUAGE
PROGRAMMING
OBJECTIVES
35
In Section 2.1 we look at the inside of the 805 I . We dciiionstratc some of
the widely uscd registers of the 8051 with simpie instructions such as MOV and
ADD. In Section 2.2 we examine Assembly lar.guage 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
discus.«ed in Section 2.3. Step-by-step execution of an 8051 program and the role
of the pro- gramcounter are examined in Section 2.4. In Section 2.5 we look at
some widely uscd Assembly language directives, pseudocode, and data types
related to the 5051. In Section 2.6 we discuss the flag bits and horn’ they are
atâ'ected by arith- metic instructions. Allocation of RAM memory inside the 8051
plus the stack and register banks of the 8051 are discussed in Section 2.7.
DPH DPL
PC
PC (program counter)
This instruction tells the CPU to move ( reality, copy) the sour cs operand
to the destination operand. For exaliipie, the insti‘uction “MOV A, R0” copies the
contents of register R0 to register A. After this instruction is executed, register A
will have the same value as register R0. The MOV instruction does not affect the
suui ce operand. The following program first loads register A with•valiie 55H (that
is 55 in hex), t:men 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.
4. To load a value into a register it must be preceded with. a pound sign (#).
Otherwise it means to load from a memory location. For example “MQV
A, 17 H” means to move into A the value he!d in memory location 17 Fi,
which cculd have any value. In order to load tf:e value l7H iiito the
accumulator we must write “MOV A, 117 H” with the # preceding the
number. Notice that the absence of the potind sign will not cause an error by
the assembler since it is a va!'d 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:
The ADD instruction felts the CPL to add the source byte to register‘ A
and" put the rest.ilt In rcgister A. To add two numbers such as 25H and 34H, each
can be moved to a ‹cgi.:•r and then °*ded together:
Executing the program above results in A — 59Fi (25H + 34H = 59H) and
R2 — 34H. Notice that the content of R2 does not change. The program above
can be wi ittcn in many ways, depending on the registers used. Another way
might be:
The program above i'esults in A = 59H. There are always many ways to
write the same program. One question that might come to mind after looking at
the program above, is whether it is necessary to move both data items into
registets
38
before adding them together. T'hc ans ver is no, it is not neccss*! y. Look at the
Al- lowing variation of the saiiic progralii:
In the above case, while one register contained one value, the second
value followed the instruction as an operand. This is called an iniii.•e‹fiafc•
operand. Fhe examples shown so far for the ADD instruction indicate that the
source operand can be either a register or iiniiiediate data, but the destination irtist
at ways be reg- ister A, the accriinttlator. In o:her words, an instruction such as
“ADD P 2, # 12 H” is invalid since register .4 (aGcuiiiulator) must be involved
in any arithmetic oper- ation. Notice that “ADD R4, A” is also invalid tor the
reason that A must be the destination ot any ai ithiiietic operation. T put it simply:
In. the 8051, l cgistci A must be involved and be the destination for a!1 arithmetic
operations. The forego- ing discussion explains the reason that register A is
referred to as the accumulator. The format for Assembly language instructions,
descriptions of their use, arid a listing of legal operand types are provided in
Appendix A.1.
There are two 16-bit registers in the 8051: PC (program counter) and
DPTR (data pointer). The importance and use of the program counter are covered
in Section 2.3. Fhe D!*TR register is used in accessing data and is discussed in
Chapter 5 when addressing mod•s are co 'ered.
Reviev\• Questions
1. Writ• time ins*uctions to move va!ue 34H 'mo register A and value 3FH into
register B, then add tiierii together.
2. Write the instructions to add the values 16H and CDH. Place the :esult in reg-
ister R2.
3. True or false. No value can be moved directly into registers R0 - R7.
4. What :s :he largest hex value that can be moved into an 8-bit re•qister? W'hat
is the decimal •.qtiivalent of the hex value?
5. Tree vas' rna.jority cf ies'S›els in 5051 ai e bits.
1. The label field allows the program to refer to a line of code by name. T!ic
label field cannot exceed a certain number of characters. Check your
assembler for the rule.
ADD A,B
MOV A,#67
ADD and MOV are the mnemonics which produce opco cs; “A,B” and
“A,#67” are the operands. Instead of a rr.nemonic and operand, these- two
fields would contain assembler pseudo-instructions, or fire tivcs. $errember
that directives do not generate any machine code (opcode) arid are used or!y
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) a*d END are examples of directive.› (some 5051 assemblers use
.ORG and
.END). Check you:r assembler for the rules. More of these pseudo-instructions
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 SIM P (short
jump instructi Fl‘), the .805 l is told to stay in this loop indefinitely. If your sys-
temhas a monitor pre 3ram you do not need thls llne and it should b deleted
from your program. i .. the next section we will see l•.ow :o create a idy-to-
run progiam.
‹i
R»view Questions
1. What is the purpose of pseudo-instructions?
2. are translated by the assembler into machine code, whereas
are not.
3. Ti ue or false. Assembly language is a high-level language.
4. Which of the following produces opcode?
(a) At)D A,R2 (b) MOV A,#12 (c) Oft 2000H (d) SJMP HERE
5. Pseudo-instructions are also called
6. Tt ue or false. Assembler directives are not used by the CPU itself. They are
simply a guide to the assembler.
7. I n question 4, » hich one is an assembler directive?
°How that the basic form of an Assembly language program has been
given, tne next question is: How it is created, assembled and made ‘ready to run?
The steps to create an executable Assembly language program are outlined as
follows.
EGITOR
PRocRAM
1. Fiist we use an editor to type in a 4
myfile.asiu
pt cgra.m similar to Pi ogram 2-1. 2
k4any excelleirt editors or word
processors are a ailable that can be ASSEMBLER PROGRANI
used to create and/or edit the pro-
gram. A widely used -ditor is the
n›yfi Ie.1st
MS-DOS EDIT program (or
Notepad in \Vindows), which comes my file.obj
other obj files
w ith all M lcrosoft operatin_•
systems. Notice that the editor mus: LINKER
be able to produce an SCl I fi le. For .°ROGRAM
many assemblers, the file names
follow the usual DOS conventions,
but the source fi le has thee ext•nsion my file.abs
“asm” or “src”, depending on which
assem- bler you are- us ing. Check your
assembler tor the convention. The OH PROGRAM
“asiii” extension for the source file is
used by an assembler in the next
Siep.
my file.hex
2. The “asiii” son: cc file con.ta.ining the
program code ci cated in step l is fed
to an 8051 fl5SClnbler. The assembler
converts the instructions into
Figure 2-2. Steps to Create a Program
izJaclJinc ccdc. 1"hc assembler \yi|! produce an (.icct filc ::nd a list liIe. The
cxtcnsion l1r the object fjlc is "ob]" while thc cxtci Sion lor tlzc list tllc is "lst".
3. Assemblers require a thiid step called linking. The iink program takes one or
more object files and produces an absolute object file with the extension
"abs". This abs fi ie is tised by 8051 trainers that have a monitor progra:n.
4. Next the "abs" fiic is lcd into a program called "OH" (object to hex convei t-
er) wli Fch ci eates a II le with extension "hex" that is ready to b.irn. into
ROM. This program cones with all 8051 assemblers. Recent Windows-based
assem- blers combine steps 2 ill otigli 4 iiito one step.
Ist file
The 1st (i ist) l3le which is optional, is every useful to the programmer
because it lists all t'ne opeodes ana addresses as well as •rrors that the- asserrlb!er
dctectco. Many assemblers assume that the list file is not wanted crless you indi-
cate that you want to produce it. This file can be accessed by an editor such as
DOS *DIT and displayed on the monitor or sent to the printer to get a hard copy.
The pi'ograiuiuel uses the list file to fir.d syntax errors. It is only after fixing all
the ei rois indicated in that 1st file that the obj file is ready to be inprit to the
linker pro- grams.
I SOOO ORG OH ;start (origin) at 0
2 0000 7D25 MOV R5,#25H ;load 25H into R5
0002 7F34 MOV R7,#3dH ;load odH into R7
4 0004 7400 MOV A,#0 ;load 0 into A
S 0006 2D ADD A,R5 ;add contents of R5 o A
;now A = A * R5
E 0007 2F ADD L, R7 ;add contents of R7 to A
;now A = A + R7
0008 2412 ADD A,#l2H ;add to-A value 12H
;row A = A + l2H
OOOA 80FE HERE: SJMP HERE ;stay in this loop
OOOC END ;end of asm source file
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.
Program counter in the 8051
Another important register in the 8051 is the PC (program counter). The
' sram counter points to the address of the neKt instruction to be executed. As the
CPU fetches the opcod- front the program ROM, the program counter is incre-
mented *o point to the next instruction. The program counter in the 6051 is 16
Sits wide. i b.is means that the SG51 can acces.s program addresses 0000 to FFr
FH, a total of 64*? bytes of*o‹i•. Howev'er, not al! mernb•rs of the 805'. has.e the
entire 6*.K bytes ot on-chip ROh4 installed, as we wil see socn firbere do•s the
805 i wake up when it is powered? We will discuss this important topic next.
Where the 8051 wakes up wilen it is powered up
O.ne question that we must ask about any microcontroller (or microproces-
sor) is: At what addi'ess does the CPU wake tip upcn applying power to it? Each
mic› oprocessor is ‹liiTerent. ln t!ie casc of the 8051 family. that is, all members
regardless of the maker and variation, the microcontroller wakes up at memory
addiess 0000 when it is powered up. By powering up eve mean applying V CC to
the RESET pin as discussed in Chapter 4. In other words, when the 8051 is pow-
ered tip, the PC (program counter) has tb.e value of 0000 in it. This means th.at it
expects thee first opcode to be stored at ROM address OOOOH. For this reason in the
8051 system, the first opcode must be burned into memory location OOOOH of
pro- grams ROM since this is where it looks for the first instruction when it is
booted. We achieve this by the ORG statement in the source program as shown
earlier. Next we discuss the step-by-step action of the progfim counter in fetching
and executing a sample program.
Placing code in program. ROM
To get a better understanding of the role of the program counter in fetch-
in.g end executing a program, we examine the action of the program counter as
each instruction is fetched and executed. First, we examine once more the list file
of thc sample program and how the code is placed in the llON^. of’ : n 8051 chi;:.
As we can see, thc opcode and operand for cach instruction arc listed on the lcft
side of the list file.
After the program is burned into ROM of an 8051 family rr.ember such as
875 l or AT895! or DS5000, tne opcode and operand are placed in ROM memory
locations starting at 0000 as shown in the list below.
The list shows that addiess 0000 con-
tains 7D which is *he opcode for iriovin3 a Program 2-1: I'.OM Contents
value into register R5, and address OOG l con-
taiiâs the operand (in this case 25H) to be
moved to R5. Therefore, the instruction “MOV
R5, # 25H” has a machine code of “7D25”,
where 7D is the opcode and 25 is the operand.
Similarly, the machine code “7F34” is located
in memory locations 0002 and 0003 and rep-
resents the opcode and the opeiand for the
instruction “MOV R7, # 34 H”. In the same
way, machine code “7400” is located in mem-
ory locations 0004 and 0005 and repress ,
the opcode and the operand for the instruction
“MOV A, 10”. The memory location 0006 has
the opcode of 2D which is the opcode for the'
1. When the 5051 is powered up, the PC (program counter) has 0000 and starts
to fetch the first opcoae from location 0000 c›f the program ROM. In the case
of the above program the first opcode is 7D, which is the code for moving an
operand to R5. Upon executing the opcode, the C. U fetches the value 25 and
places it in R5. Now one instruction is Finished. Then the program counter is
incrementefi to point to 0002 (PC = 0002), •xhich contains opcocie 7F, the
opcode for the instruction “NOV R7, ”.
2. Upon executing the opcode 7F, the value 34H is moved into R7. Then the
pro- gram counter is incremented to 0004.
3. ROM location 0004 has the opcode for instruction “MOV A, 10”. This
instruction is executed and now PC=0006. Notice that all th• above instruc-
tions are 2-byte instructions; that is, ea*.n one ta.kes two memory locations.
4. h'ow PC = 0006 points to the next instruction which iS “ADD Ps r R5”• Th @
a I-byte instruction.. A*er th.e execution of this instruction, PC — 0007.
5. The location 0007 has the opcode 2F which belon-gs to the instruction “ADD
A, R7”. This is also a l -byte instruction. L'pon execution of this instruction,
PC is in.cremented to 0008. This process goes on until all the instructions are
fetch.ed and executed. The fact the program counter points at the next instruc-
tion to be executed explains why some microprocessors (notably the x86) call
the program counter the in.sfrncf/on pointer.
ROM. memory map in the 6051 family
As we saw in the last chapter, some family members have only 4K byte›
of on-Gllip ROM (e.g., 8751, AT8951) and some, such as the AT89C52, have 8k
bytes of. ROM. Dallas Semiconductor’s DS5000-32 has 32K bytes ot’ on-chip
ROM. Dallas Semiconductoi’ also has an 5051 with 64K bytes of on-chip ROM.
The pcint to remember is that no ineiiiber of the 5051 famiiy can access more
than 64K bytes of opcode since the program counter in the 8051 is a 16-bit
register (0000 to FFFF address range). lt must be noted that while the first
location of pro- gram ROM inside the 8051 has the a‹idress of 0000, the last
location can be dif- ferent depending on the size of the ROkl on the chip. Among
the 8051 faluily members, the 8751 and AT8951 have 4k tiytes of on-chip ROM.
This 4K bytes ROM memory has memory addresses of 0000 to 0FFFi-I.
Therefore, the first local tion of on-chip ROM of this 8051 has an address of 0000
and the last location ha the address of OFFFH. Look at Example 2-1 to see how
this is computed.
46
rxamp!c 2-1
Find thc ROM memory address c each of the following 805.1 chips.
(a) AT89C51 (or 8751) with 4KB (b) DS5000-32 with 32KB
Solution:
(a) With 4K bytes of on-chip ROM iiieinory space, we have 4096 bytes, which is I OOOH
in hex (4 x 1024 = 4096 or 1000 in hex). This iuuch me1iioi‘y maps to address
loca- tions of 0000 to 0FFF1-1. Notice that 0 is always the first location.
(b) Witli 32K bytes we have 32,768 (32 x 1024 — 32,768) bytes. ConveHii:g 32,768 to
hex, we get 8000H; therefore, the memory space is 0000 to 7FFFH.
b3 te byte
0000
00 00
OF
8751
ATS9C 8752
AT89C
7F
In this section we look at some widely used data types and directives sup-
poi't ri by the 8051 assenibier.
ORG 500H
DATAl: DB 28 ;DECIMAL(lC in hex)
DATA2: DB 00l10l01B ;BINARY (35 in hex)
DATA3: DB 39H ;HEX
ORG 5l0H
DATAS: DB “2591” ;ASCII NUMBERS
ORG 5l9H
DATm6: DB “My name is Joe”;ASC I CHARACTERS
Either single or double quotes can be used around ASCII strings. This can
be useful for strings, which contain a single quote such as “O'Leary”. DB is also
used to allocatc memory in byte-sized chunks.
Assembler directives
The following are some more wide!y used directives of the 8051.
ORG (origin)
The ORG directive is used to indicate the beginning of the address. The
nuinbe: that comes after GRG can be either in hex or in decimal. If the number is
not followed by H, it is decimal and the assembler will convert it to hex. Some
assemblers use “ . oRG” (notice the dot) instead of “ORG” for the origin directive.
Check your assembler.
EQU (equate)
This is used to define a constant without occupying a memGry location.
The ")U directive does not set aside storage for a de!a item but assoclates a con-
stant aiue with a data labei so that when the label appears in the program, its con-
stant value will be substituted for the label. The following uses EQU for the
count- er constant and then the constant is used to load the R3 register.
48
COUNT EQU 25
MOV R3,#COUNT
END directive
Another important pseudocode is the END directive. This indicates to the
assembler the end of the source (asin) file. The END directive is the last line of an
8051 program, meaning that in the source code anything after the END directive
is ignored by th.e assembler. Sortie assemblers use “ . EN D” (notice tne dot) instead
O L “EN D”.
Review Questions
l. The directive is always used for ASCII stt in3s.
2. How man.y bytes are used by the following?
DATA l DB "AMERICA"
o. What is the advantage in using the EQU directive to define a constant value?
4. Fiow many bytes are set aside by each of the following directl yes?
(a) TSC DATA DB ” 1.2.3.4 ” (b) MY DATA DB "ABC 1.2.3.4 ”
5. State tl.e ntents of memory locations 2 0fi - -295H tj!’ ' followin,q
ORG 200H
MYDATA: DB "ABCl23"
CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 49
SECTION 2.6: 8051 F* AG BITS ANO THE PSW REGISTER
Like any oilier microprocessor. tic 805 lfas a hag regi‘star to ii›ñicaie
ai itIin›etic conditions such as the carp bit. TJ›e flag rogistei ir. '.1e 80a) is
called the piogram status word (PSW) register. In this scction wc discuss various
bits ot“ this i cgistei and provide some examples of loo a it is altci cdi
CY I AC F0 RS1 RS0 OV - P
_ Register Bank s
0 AOH' 7H’ " *”
I 08H -
OFH l0H -
l7H l8H -
l FH
The following is a brief eKplanation Of four of the flag bits of the PSW reg-
ister. The impact of instructions on these registers is then discussed.
CY, the carry flag
This flag is set whenevcr there is a carry out morn tl c d7 bit. This flag bit
is affected after an 8-bit addition or subtraction. It can also be set to ! or 0 direct-
ly by an instruction such as “SETB C” and “CLR C” 'there “SETB C” stands
Not “set bit carry” and “CLR C” for “clear carry”. More about these and other
bit- addressable instructions will be givers in Chapter 8.
AC, fhe auxiliary carry I/ag
If there is a carry front D3 to D4 during an ADD or SU E operation, this
hit is set; otherwise, it is cleared. 3“his flag is used by ilisti uctioas that perform
i3CD (binary coded decimal) arithmetic. See Chapter 6 for iiiore tutor mation.
P, the parity flag
The parity flag reflects the number of 1s in the A t accumulator) register
only. If the A register contains an odd number of 1s, risen P = 1. Fhei efore, P —
0 if A has an eveti number of 1s.
OV, the overf/ow flag
This flag is set whenever the resu!t of a signed nriiiiber opera(ion is too
large, causing the high-order bit ’to overflow into the sign bit. In general, the carry
flag is used to detect errcrs in unsigned arithmetic operations. Fhe overflow flag
is only used to detect ert‘ors in signed arith:netic operations and is discussed in
detail in Chapter 6.
SO IU tlO R'
38 00111000
+ 2F_ 00101111
67 01100111
Example 2-3
Show the status of the CY, AC, and P flags after the addition of 9CH and 64H in the fol-
lowing instructions.
MOV A,#9CH
ADD A,#64H ;after addition A=00 and CY=l
Solution:
.*C 10011100
+ 64 01100100
100 OOOGOOOO
Examp}e 2-4 ,
Show the status of the CY, AC, and P flags after the addition of 88H and 93H in the fol-
lowing ir.strueiions.
MOV A,#88H
ADD A,#93H ;after the addition A=1BH,CY-1
Solution:
86 10001000
+ 100l00'1
llB 00011011
The 8051 microcontroller has a total of 128 bytcs of R.PM. I n this section
we discuss the allocation of these 128 bytes of RAM am examine their us ge as
registers and stack.
RAM memory space allocation in the 8051
There are 128 bytes of RAM in the 8051 (Some members, notably the
8052, have 256 bytes of RAM). The 128 bytes of RAM inside the 8051 are
assigned addresses 00 to 7FH. As we will see in Chapter 5, they can be accessed
directly as rr‹emory locations. These 128 bytes are divided into three different
groups as follows.
1. A totai of 32 bytes from locations 7f
0G to IF b.ex arc se: aside for reg- ,
Scratch pad RAM
ister banks arid the stack.
2. A total of 16 bytes from locations 30
20H to 2FH are set aside for bit- 2F "
addressable read/write memory. A Bit-.^.ddressrble RAM
detailed discussion of‘bit-address-
20
able memory and instructions is IF
given in Chapter . Re•_ister Bank 3
A total of 80 bytes from locations i8
30H to 7FH are used for read and 17 Re•_ister Bank 2
10
write storage, or what is normally
0F
cal!ed a scratch pad. These 80 Register 6ank I (stack)
locations of RAM are widely used 08
for the purpose of stoi ing data 07
and parameters by 8051 Register Bank_0
programmers. We will use them in
00 ”
future chap- ters to store data
brougb.t into the
CPU via I/O ports. Figure 2-5. RAM .Allocation in the 8051
As we can see from Figure. 2-5, Sank 1 uses the same PPM space as the
stack. This is a majoi‘ problem in programming the 8051. We must either not use
re•_ister bank 1, or we must allocate another area of RAlvi for the stack. This
wiil be discussed be-low.
Example 2-5
Smite tl°.e contents of RAM locations after the following program:
.At‹ei the execution of the above program we have the following: 14M location 0 b.as value .°
0 It tlOR •
This is callcd direct addressing mode and uses the RAM address location for the ‹desti-
nation addless. See Chapter 5 for a more detailed discussion of add!cssing modes.
Solution:
RAM location l GH has vaiue 99H RAM location HH has value 85H
RAM location 12H has value 3FH RAM location 17H has value 63H
HAM location 15H has value 12H
OA 0A 0A “ 0A F3
09 09 09 i2 09 12
08 08 25 08 25 08 25
Start SP = 07 SP = 08 SP = 09 SP = 0A
56
Popping from the stack
Popping the contents of the stack back into a given register is the opposite
process of pushing. With every pop, the top byte of the stack is copied to the reg-
ister specifie‹i by the instruction and the stack pointer is dscrementcd once.
Examp!e 2-9 demonstrates the POP instruction.
Th.e upper limit of the stack
As mentioned earlier, in the 8051 RAM locations 08 to l F can be used for
the stack. This is due to the fact that locations,20 - 2FH of RAh4 are rcserved
for bit-addressable memory and must not be used by the stack. If in a given
program we need more than 24 bytes (08 to IFH = 24 bytes) of stack, we can
chanse the SP to point to RAM locations 30 - 7FH. This is done with the
instruction “NOV
so, sxx•.
Example 2-9
Examining the stack, show the contents of the registers and SP after execution of the
following instructions. All values are in hex.
0A F9 OA L'A
09 75 09 76 09 76 09
08 6C 08 6C 08 6C 08 6C
Start SP = 0B SP — 0A SP = 09 SP - 08
SOlUtlO R:
62 62 62F3
61 6112
,60 6025
SUMMARY
This chapter began with an •xploration of the major i egisteis n•f the 8051,
including A, S, R0, R1, R2, R3, R4, R5, R6, R7, DPTR, and PC. The use of these
registers was d•mor:strated in the context of programming examples. This process
of cieat np an Assembly language program was described from writing the source
file, to asscn.bling it, linking, and executing the program. The PC (program count-
cr) register always points tc the next in.struction to be execute‹i. 4 he way the
805.1 uses program ROM space- was explored because 8G51 Assembly language
pro- grammers must be aware of where programs are placed in ROM, and how
much memory is available.
An Asseiiibly !anguage p!Ogram is compose‹i of a series of statements
that ai e either irish uctions or pseudo-instructions. also called âirc•ctives. lnstl
uctions are tran.slated uy the assembler into machine code. PseudG-instructions
are not translated into machine code: They direct the assembler in how to translate
instruc- tions into machine code. Some pseudo-instructions, called dota directives,
ai‘e used to define data. Data is allocated in byte-size increments. T!ie 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 dtii‘ing execution of a program. The stack resides in
the RAM space of the 8051, which was diagrarptned and explained. Manipulation
of the stack via POP and PUSH instructions was also explored.
60
SECTION 2.4: THE PROGRAM COUNTER AND ROM SPACE IN ’HSE 5051
29. Compile and state the contents of each COM location for the following data.
OR? 200?
MYDAT 1: Db “Earth”
MYDAT 2: DB “987-65”
MYDAT 3: DB “GABEH 98”
30. Compile and state the contents of each ROM location *or the following data.
ORG 340H
DAT 1: D0 22,56H,10011001R, 32,0F6H, l1I1lp¿¿p
39. Which bits of the PS'N are responsible for selection of the register banks?
40. On power up, what is the location of t1< first stack?
41. In the 8051, which register bank conflicts with the stac!:?
42. ln the 8051, what is the size of the stack pointer (SP) register?
43. On power up, which of the register banks is used ?
44. Give :he address locations of RAM assigned :o various banks.
45. Assuiiiing the t!se of bank 0, find at what R.PM location each ot’ the following
lines stoi cd the data.
(a) MOV R4 , # 32 H (b) MOV RO , # 12 H
(c)MO\ R7,#3FH (d)MOV E5,#55H
46. RepeotProbem45 forbank 2.
47.ARerpowcrupshowl:owtose)ectbank2whhasngeinsWucton
48. Showthesackandsackp
onerforeachWneofthefolowingpog am. ORG 0
MOV RO,#66H
MOV R3,#7FH
MOV R7,#5DH
PUSH 0
.USM u
PUSH 7
CLR A
14OV .3,L
MOV R7,A
PGP 3
PG P 7
POP 0
49. In Problem 45, does :he sequence of POP instructions restore the original
val- ues of registers R0, R3, and R7? If not, show the correct sequence of
ins'ruc- tiois.
50. Sho the stack and stack pointer for each iine of the following profi tin.
ORG 0
MOV SP,#70H
MOV R5,€66n
MOV R2,#7FH
MOV R7,#5DH
PUSH 5
PUSH 2
PUSH 7
CLR A
MOV R2,A
MOV R7,A
POP 7
POP 2
AñiSWERS TO REVIEW Qi?ESTIOfidS
SECTION 2.\: INSIDE 1”NE 803t
I. MOV A,#34H
MOV B#3FH
ADD A,B
2. MOV A,#I GH
ADD A.//0CDI I
MOV R2,A
1. The real work is performe‹i by instructions such as MOV and ADD. Pseudo-instructions, also
called assembly 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)
SECTION 2.4: THE PROGRAM COUNTER #.ND ROM SPACE IN THE 8051
l. 16 2. True 3. OOOOH 4. 2
5. With SK bytes. we have S192 (8 x 1024 = 8192) bytes, and the RO4I space is 0000 to I FFFH.
VES 1. DB 2. 7
3. If the value is to be changed tater, it can be done once in one place instcad of at every occur-
rence.
4. (a) 4 bytes (b) 7 bytes
5. This places the ASCII values for each character in memory locations starting at 200H. Notice
that at l values are in hex.
200 = (4! )
20 l = (42)
202 = (43)
203 = (3 I)
204 = (32)
205 = (33)
&ND C&kL
INSTRUCTIONS
OBJECTIVES
65
In the sequence of instructions to be executed, it is often nec-•ssary to trans-
fer program control to a different location. Thetc are niany instructions in the
8051 to achieve this. This chapter covers the control transfer instructions
available in 805 Assembly language. In the first section we discuss instructions
used for loop- ing, as well as instructions ror conditional and unconditional
jumps. In the second section we examine CALL instructions and their uses. In
the third section. time
delay subroutines are described.
!n this section we first discuss huw to performs a looping action in the 8051
and then talk about jump instruction is, both conditional and unconditional.
Looping in the 8051
Rcpeating a sequence of instructions a certain number of times is called a
looD. The loop is one of most widely used actions that any microprocessor per-
forms. In the 5051, the loop action is performed by the instruction “DJNZ req,
l aLe1”.In this instruction, the register is decreniented; if it is not zero, it jumps
to the target address referred to by the label. Prior to the start of the loop the reg-
ister is loaded with the counter for the number of repetitions. Notice that in this
instrtiction both the register decrement an‹i the decision to jump are combined
into a single instruction.
Example 3-1
Wi ‹te a program to
(a) clear ACC, then
(b) add 3 to the accumulator ten times.
Soliition:
66
Example 3-2
What is the maximum number of times that the !oop in Example 3-1 can be repeated?
Solution:
Sincc R2 holds the count and R2 is an 8-bi‹ •s'slei, it can hold a rnaximuni of FFU
(255 decimal); therefore, the loop can be repeated a iiiaxiirtiin 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:
Sauce 700 is larger than 255 (th.e maximum capacitv of any register), we use two
regis- ters to hold the count. The tollow'ing code shows how to us•- Rz and R3 for the
count.
In this program, R2 is used to keep the inner loop count. In the insti’UG(iOlI "DJl9 Z
R2 , ACA I N”, whenever R2 becomes 0 it falls through and “DIN Z R , 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 fiil-
ished.
NO*/ A, R0 ; h=R0
JZ OVER ;jump if A = 0
MOV A,Rl ;A=Rl
JZ . OVER ;jump if A = 0
OVER:
Table 3-1: 8051 Conditional Jump Instructions
In this program, if either Instruction
Action' .....
R0 or R1 is zero, it jumps to the JZ
Jump if A = 0
label OVER. Notice that the IZ JNZ Jump if A 0
instruction can be used only for Decrement and jump if A z
DJNZ
é Jump if A byte
register A. It can only check to CJNE A,byte
Jump if byte #data
see whether the accumulator is CJNE
Jump if CY = 1
reg,#data zero, and it does nct apply to any JC
Jump if CY = 0
other register. More importantly, INC
Jump if bit = 1
you don't have to perform ;jjj JB
Jump if bit = 0
arithmetic instructions such as
Jumo if bit — i and clear bit
JNB decrement to use the JNZ instruc-
ABC tion. See Example 3-4.
Example 3-4
\Vrite a program to determine if n5 contains the value 0. If so, put 55H in ii.
Solution:
MOV A,R5 ;copy R5 to A
JNZ NEXT ;jump if is not zero
MOV R5,#55H
NEXT:
68
Example 3-5
Find the sum of the values 79H, F5H, and E2H. Put the sum in registers R0 (low byte)
and R5 (high byte).
Solution:
Example 3-6
Using the following list file, verify the jump forward address calculation.
Zlzze *C Xcode
01 0000
02 00 0 0 7800 MOV R0,#0
03 0 0 02 7455 MOV A,#55H
04 0004 60 03 JZ NEXT
05 0006 06 INC R0
06 0007 04 AGAIN: INC A
07 0006 04 IKC A
08 0009 2477 NEXT: AND A,#77h
09 OOOA 5005 JNC OVER
10 OOOD E4 CLR A
11 OOOE F8 MOv R0,A
12 OOOF F9 MOV Rl,A
13 0010 FA MOV R2,A
14 0011 FB MOV R3,A
5 0 01 2 2B OVER: ADD A,R3
16 0013 50F2 JN AGAIN
17 0015 80FE hERE: SJMP HERE
END
SOlutiOR°
First notice that the JZ and INC instructions both jump forward. The target address
a forward jump is calculated by adding the PC of the following instruction to the si
ond byte of the short jump instruc:ion, which is called the relative address. In line 4 i
instruction “JZ NEXT” has opcode of 60 and operand of 03 at the addresses of 0004 i
0005. The 03 is the relative address, relative to the address of the n•xt instruction P
R0, which is 0006. By adding 0006 to 3, the target address of the label NEXT, w,lHcl
0009, is generated. In the same way for line 9, the “INC OVER” instruction has oper
and operand of 50 and /15 where 50 is the opcode and 05 the relative adc!' ass.
Therefi 05 IS ñ€lded to i)00D, I!. aadress of instruction “CLR A”, giving l2H, ilie
address label OVER.
70
Example 3-7
Verify the calculation of backward jumps in Example 3-6.
S0llltlO£l l
In that program list, “JNC AGAIN” has opcode 50 and relative address F2H. When
the relative address of F2H is added to l 5H, the address of the instruction below the
jump, we have 15H + F2H = 07 (tlie carry is di opped). Notice that 07 is the address
o* label AGAIN. Lcok also at “S AMP HERE”, which has 80 and FT for the opcode
and rela- tive address, respectivcly. The PC of the following instruction, 0017H, is
added to FEH, the relative address, to get 0015H, address of the HERE label (l7H +
FEH = l 5H). Notice that FñH is —2 and 17Fi + (—2) = 15Fi. For further discussion
of the addition of negative numbers, see Chapter 6.
Solution:
OPG 0
bACK: MOV A,#55H ;load A with SSH
MOV Pl,A ,send SSH to port 1
LCALL DELAY ;time delay
MOV A,#JAAH ;load A 'with AA (in hex)
MOV, Pi,A ;send AAH to port 1
LCALL DELAY
SJMP BACK ;keep doing this indefinitely
; his is the delay subroutine
ORG 300H ;put time delay at address 300H
DELAY: i£OV R5,#0EFH :R5=255(FF in hex), he counter
AGAIN: DJNZ R5,AGAIN ;stay here until R5 becomes 0
RET ;return to caller (when R5 = 0)
END ;end o'f asm file
72
CALL instruction and the role of the stack
The s: ck and stack pointer were covered in the last chapter. To
understand the importance of the stack in microcontrollers, we now examine the
contents 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 ICC.4LL in the fol1cw'ing.
Sslutior:
01 0000 ORG 0
02 0000 7455 BACK: MOV A,#55H ;load A with SSH
03 0002 F5S0 MOV P1,A ;send SSH to port 1
04 0004 7C99 MOV R4,#99H
05 0006 7D67 MOV’ R5,#67H
06 0008 120300 LCALL DKLAY ;time delay
07 OOOB 74AA MOV A,#OAAH ;Load A with AA
08 OOOD F590 MOV P1,A ;send AAH to port l
09 OOOF 120300 LCALI DELAY
10 0012 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 C005 PUSH 5 ;PUSH R5
15 0304 7CFF MOV R4,#0FFH ;R4=FFH
16 0306 7DFF NEXT: MOV R5,#0FFH ;R5=255
17 0308 DDFE AGAIN:DJNZ R5,AGAIN
18 030A DCFA DTNZ 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 ;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.
0B OB 0B 67 R5
0A OA 99 R4 0A Qq *
08 0B 08 0B PCL 0B PCL
PCL
It needs to be emphasized tbyt in. i!Sir! I.CALL, the target addi‘•ss of ine
subroutine can be anywhere within the 64K bytes lnemory space of the 8051. This
is not the case for the other call instruction, ACALL, which is explained next.
74
;MAIN program calling subroutines
0
ORG TCALL LCALL
MAIN: SUBR_1 SUBR_2
*UBR 3
LCALL
SUBR l:
RET
end of subroutine l
SLBR 2:
RET
end of subroutine 2
RET
end of subroutine 3
END ;end of the asm file
Figure 3-1. 8051 .Assembly Main rogram Tiiat Cal!s Subroutines
ACAL! (absolute call)
ACALL is a 2-byte instruction in contrast to LCALL, which is 3 bytes.
Since ACALL is a 2-byt• instruction, the target address of the subroutine must be
within 2K bytes address becat‹se only 11 bits of the 2 bytes are used ior the
address. There is no difference between .ficALL and LCALL in terms of
saving the progiam cGunter on the stack or the Function of tne RET instruction.
l'he oniy difference is that the target address for LCALL can be anywhere within
the 64K byte address space of the 8051 while the target address of A TALL
must be with- in a 2K-byte range. In many variations of the 8051 marketed by
different compa- nies, on-chip ROM is as low as lK bytes. In such cases, the use
of ACALL instead of LCALL can save a number of bytes of program ROM
space.
Example 3-11
A developer is using the Atmel AT89C1051 microcqntroller chip for a product. This chip has only lK b
Solution:
The ACALL instruction is more useful since it is a 2-byte instruction. It saves one byte each ilme the c
CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS 75
Of course in addition to us.ng compact instructions, we can program
effe- ciently by having a detailed knowledge of all the instructions supported by
a given microprocessor, and usi•s them. » isely. look at E.xample 3-12.
Example 3-12
Rewrite Example 3-8 as efficiently as you can.
TO111 tlO fI•
OR0
MOV A,#55H
;load A with SSH
BACK. :MOVPl,A ACALL RELAY CPL value
;issue A in reg A to port 1
SJMP BACK ;time delay
;complement reg A
;keep doing this indefinitely
, this is the delay subroutine
DELAY:
AGAIN: ;R5'2/5(FF
MOV R5,#0FFH DJNZ R BAG INinRET
hex),the counter
END ;Stay here until R5 becomes 0
;return to caller
;end of asm file
h!otice in this program that register A is set to 55H. By complementing 55H, we havl AAH; a
Rex•iew questions
1. \\*hat do the mnemonics “LCALL.” and “ACALL” stand for?
2. True or false. In the 8051, control can be transferred anywhere within the
64K bytes of code space if using the LCALL ihstruction.
3. How does the C.>U know where to return to after execr:ting the RET instruc-
tion?
4. Describe briefly the function of the RET instruction.
5. The LCALL instruction is a -byte instruction.
In the last section we used the DELAY subroutine. How to generate vari-
ous time ‹relays and calculate exact delays is discussed in this section.
Machine cycle
FO!’ the CPU to execute an instruction takes a certain number of clock
cycles. I :1ie 805! family, tb.ese clock cyc1•s are referi‹ ‹! to as niac.hine cycles.
Appendix .fi.2 provides the list of 8051 instructions and iiicir machine cycles.
To calculate a time delay, we use this list. In the 8051 family, the length of the
machine cycle depends on the frequency of the crystal oscillator connected to the
76
505 I systeiii. The crystal oscillator, a!o1ig with on-chip circuitry, iii'oi !dc the clock
source for the 8051 CPU (see Chapter 4). The frequency of the crystal connected
to the 8051 family can vary from 4 MHz to 30 MI Iz, depending on the chip
rating and manufacturer. Very often the I 1.0592 MHz crystal oscillator is used to
wake the 8051-based system compatible with the serial port of the I BM PC (see
Chapter 10). In the 8051, one inachin• cycle !asts 12 oscillato pericds. Therefore,
to cal- culate the machine cycle, we take 1/1 2 of the ci)'sta! freqiic-iicy, tlicn
take its inverse, as shown its Example 3-13.
The following shows crystal frequency for three different 8051-based systems. Find the
p.eriod of the machine cycle in each case.
(a) i l .0592 MHz (h) 16 MHz (c) 20 MHz
SOIUtIOR •
Example 3-14
For an 8051 system of i 1.0592 MFz, find how long it takes to execct•. ea*h of the fol- lowing instructio
Solution:
the machine cycle for a system of 11.0592 MHz is 1.085 qs as shown in Example 3-
13. Table A-1 in AppCndix A sho›''s machine cycles for eacn of the above instructions. Therefore, we h
Rme to execute
Example 3-15
Find the size of the delay in the following program, if the crystal frequency is 11.0592
MHz.
MOV A,#55H
AGAIN: MOV Pl,A
ACALL DELAY
CPL A
SJMP AGAIN
r --Time delay
DELAY: MOV R3,#200
HERE : DJNZ R3, i-tERE
RET
Solution:
From Table A-1 in Appendix A, we have the following machine cycles for ea.ch instruc-
tion of the DELAY subroutine.
WacIn:Lne gcse
DZLA'f: MOV R3,#200 l
HERE: DJNZ R8,HLRE 2
RET
Very often we calculate the time delay based on the instructions inside the
loop and ignore the clock cycles associated with the insu uctions outside the loop.
In Example 3-15, the largest value the R3 register can take is 255; there-
fore, one way to increase the de!ay is to use NOP instructions in the
loop..NCiP, which stands for “no operation,” simply wastes time. This is shown in
Example 3- i6.
78
Example 3-16
Find the time deiay for the following subroutine, assuiiiiiig a crystal frequency of
11.0592 MHz.
HERE: ?TO°
NOP 1
NOP 1
NOP 1
DJNZ R3,HERE 2
RET 1
SOlutiOn:
The time d•1ay inside the HERE loop is [250 (1+ l + l +1+2)] 1.065 gs = 1500 x
1.085 gs = 1627.5 gs. Adding the two instructions outside the loop we ha've 1627.5 qs
+2x
1.085 g s = 1629.67 qs.
Example 3-17
For a m chine cycle. of 1.085 is, find the time delay in the following subroutine.
DELAY: Mach:ine C e
MOV R2,#200 1
AGAIN: MOV R3,#250
HERE: NOP 1
NOP
DJNZ R3,HERE 2
. DJNZ R2,AGAIN 2
RET 1
For the HERE loop, we have (4 250) 1.085 is = 1085 gs. The AGAIN ‘loop repeats
the HERE loop 200 times; therefore, we have 200 1085 qs — 217000, if we do not
include the overhead. However, the- instructions "MO*/ R3, 4 2 50" and "DJNZ
R2 , AGA.I N" at the beginning and end of the AGAIN-loop add (3 . 200 1.085 qs) —
651 qs to the time delay. As a result we have 217000 + 65 l = 21765 l t‹s = 217.651
mil- liseconds for total time delay associated with the above DELAY subroutine.
Notice that in the case n a •st•d !oo* +s in nil other tame delay !oops, th time is
since we have ignored the first and last instructions in t1 c sufiroa:i.,c.
approximate
SLiMMARY
The flow of a program proceeds sequentially, from instruction. to instruc-
tion, unless a control transfer instruction is executed. The various types of
control transfer instructions in Assembly language include conditional and
unconditional j•arnps, and call instructions.
The looping a*tion in 8051 Asseir.bly language is performed using a spe-
cial :n•'ruciion wb.ich decr•ments a counter and jumps to the top of the loop if
the counter is not zero. Other jump instructions jump conditionally, bassd on the.
value of tb.e carry flag, the accumulator, or bits of the I/O port. Ur.conditional
jumps can be long or short, depending on the relative value of the target address.
Special attention must be given to the effect of LCALL and ACALL instructions
on the stack.
PROBLEMS
80
9.
Which of t!-.e f‹•liowing instructions is (are) not a short juin p?
(a) JZ (b) JNC (c) Di MP (d) D NZ
10.
A short jump is a -byte instruction. Why?
II. True or false. All conditional juiiips are °hort julnps.
12. Show code for a nested loop to perfomi an action 1000 times.
|3.ShowcodcFraneod1oopto pdf manacGonl00,000Gncs.
1% Findthonuuborofthnesthcfoñuwingloopisperfonned
MOV R6,#200
BACK: MOV R5,#l00
HERE: DJNZ R5,HERE
DJNZ R6,BACK
15. Thee target address of a jump backward is a maximum of bytes from
the current PC.
16. The target address of a jump forward is a maximuin of bytes from
the current PC.
27. Find the systei» frequency if the machine cycle = 1.2 gs.
28. Find the macl. '.e cycle if crystal frequency is 18 MHz.
29. Find the mac!iiiie cycl• if crystal frequency is 12 MHz.
30. Find the machine cj.!-z if crystal frequency is 25 MHz.
DELAY: BACK:
MOV AGAIN:
MOV
R5,#l00
MOVHKRE:
R2,#200
NOP NOP DJNZ
R3,#250
DJNZ DJNZ RET
82
CHAPTER 4
PBOGRAMM4NG
Explain the purpose of each pin tif the ii051 microcontroller L:st the 4 ports of the 8051
Describe the dual role of port 0 :•n providing both data ard addresses Cod• Assembly language to use th
Code 8051 instructions for l/O handling
Code bit-manipulation instructions in the 8G51
83
This chapter describes 'he 8051 pins and then shows l/O port
programming cf the 8051 witii many examples.
PDIP/Cerdip
P1.0 1 40 Vcc
P1.1 2 39 P0.0 (ADO)
P1.2 3 38 P0.1 (AD1)
P1 3 4 8051 37 PO.2 (AD2)
P1.4 5 (8031) 36 P0.3 (AD3)
P1.5 6 35 P0.4 (AD4)
P1.6 7 34 PO.5 (ADS)
PI.7 8 33 PO.6 (AD6)
RST |9 32 PO.7 (AD7)
(RXD) P3.0 10 31 EA/VPP
(TXD) P3.1 11 30 ALE/PROG
(lNT0j P3.2 12 29 PSEN
(INT1) P3.3 13 28 P2.7 (A15)
(TOO P3.4 14 27 P2.6 (A14)
(T1) P3.5 15 26 P2.5 (A13)
(WR) P3.o 16 25 P2.4 (A12)
{RD) P3.7 17 2^. P2.3 (AII)
XTAL2 18 23 P2.2 (A10)
XTAL1 19 22 P2.1 (A9)
GND 20 21 P2.0 (A8)
Examining Figrne 4-1, note that of the 40 pins, a total of o2 pins are set
aside fcr the four ports PO, Pl. P2, and P3, where each port takes 8 pins. The rest
of’ the pins ai e desigFli!!v’d £fS VCC G1fiD9 XTAL 1, XTAL2, RS’F3 EA, !â›Ei9›
Of these 8 pins, six of them (VCt , GND, XTAL 1, XTAL2, RST, and EA) are used
by all members of the 8051 and 8031 families. In other words, they must be
connect- ed in order for the system to work, regardless of whether the
microcontroller is of
14
the 805 I or 8031 Tamil . The other two pins, PSEN and ALE, are uscd mainly
in 5031-based systems. We first describe the function of each pin. Ports *re
discussed separately.
Vcc
Pin 40 provides supply voltage C2
XTAL2
tO ihe chip. The v oltage soui‘cc is 5V.
CI
Pin 20 is the ground.
XTAL1
XTAL! and XTAL2 30 pF
The 8051 has an on-chip oscil-
lator but requires an extei nai clock to GND
run it. Most often a quartz crystal
oscillator is connected to inputs
XTAL l (pin 19) and XTAL2 (pin 18).
The quartz crystal oscillator connected
to XTAL1 and XTAL2 also needs two Figure 4-2 (a). XTAL Connection to 8051
capacitors of 30 pF value. One side of
each capacitor is connected to the
ground as shown in Figure 4-2 (a).
It must be noted that there arc NC XTAL2
various speeds of the 8051 family.
Speed refers to the maximum oscilla-
tor frequency connected to XT.AL.
For example, a i 2-R"Hz chip m'ast be EXTERNAI. OSL"ILLATOR. SIGNAL
con- nect•fi to a crysta! with 12 k4Flz XTAL1
fre- quency or less. Likewise, a 20-
MHz microcontroller requires a
crystal fre- quency of no more than 20 GND
MHz. When the 5051 is connected to
a cq's- tal oscillator and is powered up,
we can observe the frequency on tlic Figure 4-2 (b). XTAL Connection. to an
XTAL2 pin using the oscilloscope.
External Clock Source
If you decide to use a frequen-
cy source other than a crystal oscilla-
Table 4-1: RESET Value of Some
tor, such as a TTL oscillator, it will be
8051 Registers
connected to XTAL1; XTAL2 is left
unconnected, as shown in Figure 4-2 (b). Register Reset Values
PC 0000
RST ACC.”‘ 0000
s 0000
Pin 9 is the RESET pin. It is an Psw m*†
input and is active high (norina! I !ow). $p 0007
Upon applying a high puise to tu..; pin, DPTR 0000
the microcontroller will reset and termi-
nate all activities. This is often referred to
31
EA/VPP
10 ur
30 pF
X2
RST
9.2E
86
Example 4-1
Find the machine cycle for (a) XTAL = 11.0592 Mhz (b) XTAL = 16 MHz.
Solution:
(a)11 .0592 MHz / 12 = 921.6 kHz;
lrachine cycle = 1 / 921.6 kHz = 1.055 gs
(b)16 MHz / 12 — 1.333 MHz;
machine cycle = ! / 1.333 MHz = 0.75 his
ACALL DELAY
CPL A
SJMP BACK
* TER 4: FO PORT PROGRAMMING 87
Port 0 as input
Vcc
10 K
With resistors
connected to port 0, in
order to make it a.* input,
the port must be pro- P0.0
P0.1
grammed by writing 1 to DS5000
PO.2
all the bits. In the 9751 PO.3
follow- ing code, port 0 8951 P0.4 —
P0.5
is con- figured first as P0.6
an input port by writing P0.7
1s to it, and then data is
received from tb.at port
and sent to P1. Figure 4-4. Port 0 with Pull-Up
Resistors
Port 1
Port 1 occupies a total of 8 pin.s (pins l 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 res•t, port 1 is
configured as an output port. For example, the follcwing code will continuously
send out to port l the alternating values 55H and AAH.
MOV A,f55H
BACK: MOV Pl,A
ACALL DELAY
CrL A
SJMP BACK
88
Port 1 as input
To make port l an input port, it must programmed as Stich by i• riting I to
all its bits. The reason for this is discussed in Appendix C.2. In the foliowiiig
code, port l iS configured first as an input port by writing 1s to it, then data is
received from that port and saved in R7, R6, and R5.
MOV A,#,55H
BACK: MOV P2,A
ACALL DELAY
CPL A
SJMP BACK
Port 2 as input
To make port 2 an input, it must programmed as such by writii.g 1 to all
its bits. In the following code, port 2 is configured first as an input port by
writing 1s to it. Then data is received from that port and is sent to Pl
continuously.
8. Which of the 8051 ports need pull-up resistots to function as an I/O port?
9b
SECTION 4.2: IiO PROGRA?IMING; BIT MANIPULATION
Notice that the XOR of 55H and FFH gives AAH. Likewise, tlie this of
AAH and FFH gives 55H. Logic instructions are di.scussed in Chapter 7.
Solution:
In thi: Program, instruction “JNB P1 . 2, AGA I N” (iU'° means jump if no bit) stays in the loop as long as P1
92
Review Ques’.ions
l . Upon reset, thc 8051 ports are configured as
(a) input (b) output (c) both input and output.
2. Trike or false. The instruction “S ET B P2 . 1” makes pin PM.. I high while
leav- ing other bits of P2 unchanged.
3. Why do we use 55 H and AAH to test the bits of the poi t’?
4. As the following a valid insti uction: “MOV P l , 19 S H”? Exp!ain your answer.
5. Using the instruction “JNB P 2 . 5, HEf-IE” ‹issuiiies that bit P2.5 iS fllâ
(in ptit, outp ut).
SUMMARY
This chapter began by describing the function of each pin of the 805 t.
The four ports of the 8051, PO, P1, P2, and P3, each use 8 pins, leaking them 8-
bit ports. These ports cae. be used for input or output. Port 0 can be used for
either address or data. Port 3 can be used to provide interrupt and serial
communication signals. Then I/O instructions of the 8051 were explained, and
numerous exam- ples were given.
PROBLEMS
SECTION 4.1: PIN DESCRIPTION OF THE 8051
94