100%(1)100% found this document useful (1 vote) 297 views256 pagesThe 8051 Microcontroller Architecture, Programming and Applications PDF
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
The 8051
Microcontroller
So
"
eyekyDe
The 8051 Microcontroller
ARCHITECTURE, PROGRAMMING,
and APPLICATIONS
Kenneth J. Ayala
Western Carolina University
WEST PUBLISHING COMPANY
ST. PAUL = NEW YORK = LOS ANGELES * SAN FRANCISCO.Copyediting: Technical Texts, Inc.
Text and Cover Design: Roslyn Stendahl, Dapper Design
Cover Image: Christopher Springmann, The Stock Market
‘Composition: G&S Typesetters, Inc.
Artwork: George Barile, Accurate Art
COPYRIGHT © 1991 By WEST PUBLISHING COMPANY
50 W. Kellogg Boulevard
PO. Box 64526
St.Paul, MN 55164-0526
All rights reserved
Printed in the United States of America @
98 97 96 95 9493 9291 87654321
Library of Congress Cataloging in-Publication Data
‘Ayala, Kenneth J
The 8051 microcontroller : architecture, programming,
and applications / Kenneth J. Ayala,
poem.
Includes index.
ISBN 0-314-77278-2 (soft)
1, Inte! 8051 (Computer) 2. Digital control systems.
|. Title
QA76.8.127093 1991
004.165—de20 90-12928,
cP=
To John Jamison of VMI and
John Peatman of Georgia Tech,
both of whom made this book possible>
Contents
‘1 MICROPROCESSORS AND MICROCONTROLLERS 1
Introduction 1
Microprocessors and Microcontrollers 2
Microprocessors 2
Microcontrollers 3
Comparing Microprocessors and Microcontrollers 4
The 280 and the 8051 4
A Microcontroller Survey 5
Four-Bit Microcontroller 5
Eight-Bit Microcontrollers 6
Sixteen-Bit Microcontrollers 7
Thirty-Two Bit Microcontrollers 8
Development Systems for Microcontrollers 9
Summary 9
Questions 10
2 =~ THE 8051 ARCHITECTURE 11
Introduction 11
8051 Microcontroller Hardware = 11
The 8051 Oscillator and Clock 16
Program Counter and Data Pointer 17
AandB CPU Registers 17
Flags and the Program Status Word (PSW) 18
internal Memory 19
Internal RAM = 19
The Stack and the Stack Pointer 19
Special Function Registers 21
Internal ROM = 22
Input/Output Pins, Ports, and Circuits 22
PortO = 23
Port1 25
viiviii
CONTENTS
Port2 25
Port3 25
External Memory 26
Connecting External Memory 26
Counter and Timers 28
Timer Counter interrupts 29
Timing 30
Timer Modes of Operation 30
Timer Mode 0 30
Timer Mode 1 30
Timer Mode 231
Timer Mode 3 32
Counting 32
Serial Data Input/Output _ 32
Serial Data Interrupts 32
Data Transmission 34
Data Reception 34
Serial Data Transmission Modes 34
Serial Data Mode 0-Shift Register Mode 34
Serial Data Mode 1-Standard UART 35
Made 1 Baud Rates 36
Serial DataMode 337
Interrupts 37
Timer Flag Interrupt 39
Serial Port Interrupt 39
External Interrupts 39
Reset 40
Interrupt Control 40
Interrupt Enable/Disable 40
Interrupt Priority 41
Interrupt Destinations 41
Software Generated Interrupts 41
Summary 41
Questions 42
3° MOVING DATA 44
introduction 44
Addressing Modes 45
Immediate Addressing Mode 45
Register Addressing Mode 45
Direct Addressing Mode 47
Indirect Addressing Mode 49
External Data Moves 50
‘Code Memory Read-Only Data Moves 51
PUSH and POP Opcodes
Data Exchanges 53
Example Programs 54
Summary 56
Problems 57‘CONTENTS, ix
LOGICAL OPERATIONS 59
Introduction 59
Byte-Level Logical Operations 60
Bit-Level Logical Operations 62
Internal RAM Bit Addresses 62
SFR Bit Addresses 62
Bit-Level Boolean Operations 63
Rotate and Swap Operations 66
Example Programs 68
Summary 69
Problems 70
ARITHMETIC OPERATIONS 71
Introduction = 71
Flags 72
Instructions Affecting Flags 72
incrementing and Decrementing 73
Addition 74
Unsigned and Signed Addition 74
Signed Addition 75
Multiple-Byte Signed Arithmetic 76
Subtraction 77
Unsigned and Signed Subtraction 78
Unsigned Subtraction 78
Signed Subtraction 78
Multiplication and Division 80
Multiplication 80
Division 80
Decimal Arithmetic 81
Example Programs 82
Summary 84
Problems 85
JUMP AND CALL OPCODES 86
Introduction 86
The Jump and Call Program Range 87
Relative Range 87
Short Absolute Range 88
Long Absolute Range 88
Jumps 89
Bit Jumps 89
Byte Jumps 90
Unconditional Jumps 90
Calls and Subroutines 92
Subroutines 92
Calls and the Stack 92CONTENTS
Calls and Returns 93.
Interrupts and Returns 94
Example Problems 95
Summary 97
Problems 98
7 AN 8051 MICROCONTROLLER DESIGN 100
Introduction 100
A Microcontroller Specification 101
A Microcontroller Design 102
External Memory and Memory Space Decoding 102
Reset and Clock Circuits 102
Expanding /O = 103
Memory-Mapped /O0 104
Part Speed 106
Production Concerns 106
Testing the Design 107
Crystal Test 107
ROM Test 107
RAM Test 108
Timing Subroutines 110
Time Delays 110
Pure Software Time Delay 111
Software Polled Timer 112
Pure Hardware Delay 114
Lookup Tables for the 8051 117
PC as aBase Address 118
DPTR as a Base Address 120
Serial Data Transmission 121
Character Transmission Using a Time Delay 123
Character Transmission by Polling 124
Interrupt-Driven Character Transmission 125
Receiving Serial Data 126,
Polling for Received Data 126
Interrupt-Driven Data Reception 127
Summary 128
Problems 129
8 APPLICATIONS = 131
Introduction 131
Keyboards 132
Human Factors 132
Key Switch Factors 132
Key Configurations 133
Programs for Keyboards 134
A Scanning Program for Small Keyboards 136
Interrupt-Driven Programs for Small Keyboards 139CONTENTS. xi
Program for a Large Matrix Keyboard 147
Displays 151
Seven-Segment Numeric Display 151
Intelligent LCD Display 155
Pulse Measurement 158
Measuring Frequency 158
Pulse Width Measurement 161
D/A and A/D Conversions 162
D/A Conversions 163
A/D Conversion 165
Multiple interrupts 166
Hardware Circuits for Multiple Interrupts 173
Putting it all Together 177
Summary 181
Problems 182
Q SERIAL DATA COMMUNICATION 185
Introduction
Network Configurations 186
8051 Data Communication Modes _ 189
Mode 0: Shift Register Mode 189
Mode 1: Standard 8-Bit UART Mode 192
Modes 2 and 3: Multiprocessor 197
Summary 202
Problems 202
Appendix A 8051 Operational Code Mneumonics 203
Appendix B How to Use the Assembler 212
Appendix C How to Use the Simulator 220
Appendix D The 8255 Programmable /O Port 233
Appendix E Control Registers 236
Index 238>
Preface
‘The microprocessor has been with us for some fifteen years now, growing from an awkward
4-bit child to a robust 32-bit adult. Soon, 64- and then 128-bit wizards will appear to
crunch numbers, spreadsheets, and, CAD CAM. The engineering community became
aware of, and enamored with, the &-bit microprocessors of the middle to late 1970's. The
bit size, cost, and power of these early CPUs were particularly useful for specific tasks
involving data gathering, machine control, human interaction, and many other applica-
tions that granted a limited intelligence to machines and appliances.
‘The personal computer that was spawned by the 8-bit units predictably became faster
by increasing data word size and more complex by the addition of operating system hard-
ware. This process evolved complex CPUs that are poorly suited to dedicated applications
and more applicable to the generic realm of the computer scientist and system program-
mer. Engineering applications, however, did not change: these applications continue to
be best served by 8-bit CPUs with limited memory size and 1/0 power. Cost per unit
also continues to dominate processing considerations. Using an expensive 32-bit micro-
processor to perform functions that can be as efficiently served by an inexpensive 8-bit
microcontrotier will doom the 32-bit product to failure in any competitive marketplace.
Many designers continue to use the older families of 8-bit microprocessors. The
8085, 6502, 6800, and Z80 are familiar friends to those of us who had our first successes
with these radical new computers. We know their faults and idiosyncrasies; we have, quite
literally, tons of application software written for them. We are reluctant to abandon this
investment in time and money.
New technology makes possible, however, a better type of small computer—one with
not only the CPU on the chip, but RAM, ROM, Timers, UARTS, Ports, and other com-
mon peripheral 1/0 functions also. The microprocessor has become the microcontroller.
Some manufacturers, hoping to capitalize on our software investment, have brought
‘out families of microcontrollers that are software compatible with the older micro-
processors. Others, wishing to optimize the instruction set and architecture to improve
speed and reduce code size, produced totally new designs that had litle in common with
their earlier microprocessors. Both of these trends continue.This book has been written for a diverse audience. It is meant for use primarily by
those who work in the area of the electronic design and assembly language programming
of small, dedicated computers.
An extensive knowledge of electronics is not required to program the microcontroller.
Many practitioners in disciplines not normally associated with computer electronics —
transportation, HVAC, mechanisms, medicine, and manufacturing processes of all types —
can benefit from a knowledge of how these “smart chips” work and how they can be used
to improve their particular product.
Persons quite skilled in the application of classical microprocessors, as well as novice
users who have a basic understanding of computer operation but little actual experience,
should all find this book useful. The seasoned professional can read Chapter 2 with some
care, glance at the mnemonics in Chapters 3 through 6, and inspect the applications in
Chapters 7. 8, and 9. The student may wish to quickly read Chapter 2, study the mnemonics
and program examples carefully in Chapters 3 through 6, and then exercise the example
programs in Chapters 7, 8, and 9 (0 see how it all works.
The text is suitable for a one- oF two-semester course in microcontrollers. A two
semester course sequence could involve the study of Chapters 1 to 6 in the first semester
and Chapters 7. 8. and 9 in the second semester in conjunction with several involved stu-
dent programs. A one-semester course might stop with Chapter 7 and use many short
student assignments drawn from the problems at the end of each chapter. The only pre-
requisite would be introductory topics concerning the basic organization and operation
of any digital computer and a working knowledge of using a PC compatible personal
computer.
‘No matter what the interest level, I hope all groups will enjoy using the software that
has been included on a floppy disk as part of the text. It is my belief that one should not
have to buy unique hardware evaluation boards, or other hardware-specific items, in order
to “try out” a new microcontrolter. ¥ also believe that it is important to get to the job of
writing code as easily and as quickly as possible. The time spent learning to use the hard-
ware board, board monitor, board communication software, and other boring overhead is
time taken from learning to write code for the microcontroller.
The programs included on the disk, an 8051 assembler named ASI, and a simulator,
named $51. were both written by David Akey of PscudoCorp, Newport News, Virginia,
PseudoCorp has provided us all with a software development environment that is not only
casy to use but one that we can uniquely configure for our own special purposes. Details
on the assembler and simulator are provided in the proper appendixes; use them as early as
possible in your studies. Many points that are awkward to explain verbally become clear
when you see them work in the simulator windows! Further information on products
developed by PseudoCorp follows this Preface.
Thave purposefully not included a great deal of hardware-specific information with
the text. If your studies include building working systems that interface digital logic to the
microcontroller. you will become very aware of the need for precise understanding of
the electrical loading and timing requirements of an operating microcontroller. These
details are best discussed in the manufacturer's data book(s) for the microcontroller and
any associated memories and interface logic. Timing and loading considerations are not
trivial; an experienced designer is required to configure a system that will work reliably.
Hopefully, many readers will be from outside the area of electronic design and are mainly
concerned with the essentials of programming and interfacing a microcontroller. For these
users, I would recommend the purchase of complete boards that have the electrical design
completed and clear directions as to how to interface common 1/0 circuits.Many people have played a part in writing this book. Special thanks go to all of the
following people:
The reviewers of the early, really rough, drafts of the text
Richard Barnett, Purdue University
Richard Castetlucis, Southern College of Technology
Jerry Cockrell, Indiana State University
James Grover, University of Akron
Chris Conant, Broome Community College—New York
Alan Cocchetto, Alfred State College~New York
for their thoughtful criticisms and words of encouragement
Cecil A. Moore, Staff Applications Engineer for Intel Corporation in Chandler,
Arizona, whose meticulous comments have greatly improved the technical accuracy
and readability of the text.
‘Tom Tucker of West Publishing for his willingness to experiment.
Anne, my wife, for many years of patience and understanding.
My students, past and present, who have taught me much more than | have taught
them.
Finally, let me thank you, the reader. I would be very grateful if any errors of omission or
commission are gently pointed out to me by letter or telephone. Thank you for your help.
Kenneth J. Ayala
Western Carolina University
Cullowhee, North CarolinaCHAPTER
ee
Microprocessors
and Microcontrollers
Chapter Outline
Introduction Development Systems
Microprocessors and Microcontrotiers for Microcontrollers
‘The Z80 and the 8051 summary
‘A Microcontroller Survey
Introduction
‘The past two decades have seen the introduction of a technology that has radically changed
the way in which we analyze and control the world around us. Born of parallel develop-
ments in computer architecture and integrated circuit fabrication, the microprocessor, or
“computer on a chip,” first became a commercial reality in 1971 with the introduction of
the 4-bit 4004 by a small, unknown company by the name of Intel Corporation. Other,
more well-established, semiconductor firms soon followed Intel’s pioneering technology
0 that by the late 1970s one could choose from a half dozen or so microprocessor types.
‘The 1970s also saw the growth of the number of personal computer users from a
handful of hobbyists and “hackers” to millions of business, industrial, governmental,
defense, educational, and ite users now enjoying the advantages of inexpensive
‘computing.
A by-product of microprocessor development was the microcontroller. The same fab-
rication techniques and programming concepts that make possible the general-purpose
microprocessor also yielded the microcontroller.
Microcontrollers are not as well known to the general public, or even the technical
‘community, as are the more glamorous microprocessors. The public is, however, very
well aware that “something” is responsible for all of the smart VCRs, clock radios, wash-2 CHAPTER ONE
ers and dryers. video games. telephones, microwaves, TVs, automobiles, toys, vending
machines, copiers, elevators, irons, and a myriad of other artictes that have suddenly be-
come intelligent and “programmable.” Companies are also aware that being competitive
in this age of the microchip requires their products, or the machinery they use to make
those products, to have some “smarts.”
The purpose of this chapter is to introduce the concept of a microcontroller and sur-
vey a representative group. The remainder of the book will study one of the most popular
types, the 8051, in detail,
Microprocessors and Microcontrollers
FIGURE 1.1
Microprocessors and microcontrollers stem from the same basic idea, are made by the
same people, and are sold to the same types of system designers and programmers. What
is the difference between the two?
Microprocessors
A microprocessor, as the term has come to be known, is a general-purpose digital com-
puter central processing unit (CPU). Although popularly known as a “computer on a
chip,” the microprocessor is in no sense a complete digital computer.
Figure 1.1 shows a block diagram of a microprocessor CPU, which contains an arith-
‘metic and logic unit (ALU), a program counter (PC), a Stack pointer (SP), some working
registers, a clock timing circuit, and interrupt circuits
To make a complete microcomputer, one must add memory, usually read-only pro-
gram memory (ROM) and random-access data memory (RAM), memory decoders, an
oscillator, and a number of input/output (1/0) devices, such as paralfel and serial data
ports. Additionally, special-purpose devices, such as interrupt handlers, or counters, may
A Block Diagram of a Microprocessor
Arithmetic
and
Logic Unit
‘Accumulator
Working Register(s)
Program Counter Stack Pointer
Clock Interrupt
Circuit CircuitsFIGURE 1.2
MICROPROCESSORS AND MICROCONTROLLERS. 3
be added to relieve the CPU from time-consuming counting or timing chores. Equipping
the microcomputer with a mass storage device, commonly a floppy disk drive, and VO
peripherals, such as a keyboard and a CRT display, yields a small computer that can be
applied to a range of general-purpose software application
‘The key term in describing the design of the microprocessor is “general-purpose.”
‘The hardware design of a microprocessor CPU is arranged so that a small, or very large.
system can be configured around the CPU as the application demands. The internal CPU
architecture, as well as the resultant machine level code that operates that architecture, is
comprehensive but as flexible as possible.
‘The prime use of a microprocessor is to fetch data, perform extensive calculations on
that data, and store those calculations in a mass storage device or display the results for
human use. The programs used by the microprocessor are stored in the mass storage de-
vice and loaded into RAM as the user directs. A few microprocessor programs are stored
in ROM. The ROM-based programs are primarily small fixed programs that operate pe-
ripherals and other fixed devices that are connected to the system. The design of the mi-
croprocessor is driven by the desire to make it as expandable as possible, in the expecta-
tion of commercial success in the marketplace.
Microcontrollers
Figure 1.2 shows the block diagram of a typical microcontroller, which is a true computer
on a chip. The design incorporates all of the features found in a microprocessor CPU:
ALU, PC, SP, and registers. It also has added the other features needed to make a com-
plete computer: ROM, RAM, parallel! I/O, serial 1/0, counters, and a clock circuit
Like the microprocessor, a microcontroller is a general-purpose device. but one
which is meant to fetch data, perform limited calculations on that data, and control its
A Block Diagram of a Microcontroller
AW Timer/Counter i
Port
‘Accumulator
Register(s) an
Port
Internal
Internal iad Interrupt
RAM Circuits
Clock
‘Stack Pointer Circuit
Program Counter4
(CHAPTER ONE
environment based on those calculations. The prime use of a microcontroller is to control
the operation of a machine using a fixed program that is stored in ROM and that does not
change over the lifetime of the system.
‘The design approach of the microcontroller mirrors that of the microprocessor: make
a single design that can be used in as many applications as possible in order to sell, hope-
fully, as many as possible. The microprocessor design accomplishes this goal by having a
very flexible and extensive repertoire of multi-byte instructions. These instructions work
in a hardware configuration that enables large amounts of memory and 1/0 to be con-
nected to address and data bus pins on the integrated circuit package. Much of the activity
in the microprocessor has to do with moving code and data words to and from external
memory to the CPU. The architecture features working registers that can be programmed
to take part in the memory access process, and the instruction set is aimed at expediting
this activity in order to improve throughput. The pins that connect the microprocessor to
external memory are unique, each having a single function, Data is handled in byte, or
larger, sizes
The microcontroller design uses a much more limited set of single- and double-byte
instructions that are used to move code and data from internal memory to the ALU. Many
instructions are coupled with pins on the integrated circuit package; the pins arc “pro-
grammable”—that is, capable of having several different functions depending upon the
wishes of the programmer.
The microcontroller is concerned with getting data from and to its own pins: the ar-
chitecture and instruction set are optimized to handle data in bit and byte size.
Comparing Microprocessors and Microcontrollers
The contrast between 2 microcontroller and a microprocessor is best exemplified by
the fact that most microprocessors have many operational codes (opcodes) for moving
data from external memory to the CPU; microcontrollers may have one, or two. Micto-
Processors may have one or two types of bit-handling instructions: microcontrollers will
have many.
To summarize, the microprocessor is concerned with rapid movement of cade and
data from external addresses to the chip; the microcontroller is concerned with rapid
movement of bits within the chip. The microcontroller can function as a computer with the
addition of no external digital parts: the microprocessor must have many additional parts
to be operational.
The Z80 and the 8051
To see the differences in concept between a microprocessor and a microcontroller, in the
following table we will examine the pin configurations, architecture, and instruction sets,
for a very popular 8-bit microprocessor. the Zilog Z80. and an equally ubiquitous micro-
controller, the 8-bit Intel 8051:
780 8051
Pin Configurations
Total pins 40 40
Address pins 16 (fixed) 16
Data pins 8 (fixed) 8
Interrupt pins 2 (fixed) 2
VO pins o 32
ContinuedMICROPROCESSORS AND MICROCONTROLLERS 5
z80 8051
Architecture
B-bit registers 20 34
16-bit registers 4 2
Stack size ak 128
Internal ROM 0 4K bytes
Internal RAM ° 128 bytes
External memory 64K 128K bytes
Flags 6 4
Timers ° 2
Parallel port 0 4
Serial port 0 1
Instruction Sets
(types/variations)
External moves 4/14 216
Block moves 214 0
Bit manipulate aia 122
Jump on bit ° 323
Stack 35, 22
Single byte 203 49
Multi-byte 490 62
Note that the point here is not to show that one design is “better than the other; the
two designs are intended to be used for different purposes and in different ways. For ex-
ample, the Z80 has a very rich instruction set. The penalty that is paid for this abundance
is the number of multi-byte instructions needed, some 71 percent of the total number.
Each byte of a multi-byte instruction must be fetched from program memory, and each
fetch takes time; this results in longer program byte counts and slower execution time
versus single-byte instructions. The 8051 has a 62 percent multi-byte instruction content;
the 8051 program is more compact and will run faster to accomplish similar tasks.
The disadvantage of using a “lean” instruction set as in the 8051 is increased pro-
grammer effort (expense) to write code; this disadvantage can be overcome when writing
large programs by the use of high-level languages such as BASIC and C. both of which
are popular with 8051 system developers. The price paid for reducing programmer time
(there is always a price) is the size of the program generated.
A Microcontroller Survey
Markets for microcontrollers can run into milions of units per application. At these vol-
umes the microcontroller is a commodity item and must be optimized so that cost is at a
minimum. Semiconductor manufacturers have produced a mind-numbing array of designs
that would seem to meet almost any need. Some of the chips listed in this section are no
longer in regular production, most are current, and a few are best termed “smokeware":
the dreams of an aggressive marketing department
Four-Bit Microcontrollers
In a commodity chip, expense is represented more by the volume of the package and the
number of pins it has than the amount of silicon inside, To minimize pin count and pack-
age size, it is necessary that the basic data word-bit count be held to a minimum, while
still enabling useful intelligence to be implemented6
CHAPTER ONE
Although 4 bits. in this era of 64-bit “maximicros.” may seem somewhat ludicrous,
‘one must recall that the original 4004 was a 4-bit device, and all else followed. Indeed. in
terms of production numbers. the 4-bit microcontroller is today the most popular micro
made. The following table lists representative models from major manufacturers’ data
hooks. Many of these designs have been licensed to other vendors.
RAM ROM
Manufacturer:Model Pins:1/O Counters (bytes) (bytes) Other Features
Hitachi: HMCS40 28:10 — 32 512 10-bit ROM.
National :COP420 28:23 ' 4 IK Serial bit VO.
OKI:MSM6d 11 16:11 _ 32 1K
T-TMS 1000 2:23 — 64 1K LED display
Toshiba: TLCS47 42:35 2 128 2K Serial bit 0
These 4-bit microcontrollers are generally intended for use in large volumes as true
‘computers; expanding external memory, while possible, would negate the cost ad-
vantage desired. Typical applications consist of appliances and toys: worldwide volumes
tun into the tens of millions.
Eight-Bit Microcontrollers
Eight-bit microcontrollers represent a transition zone between the dedicated. high volume,
4-bit microcontrollers, and the high performance. 16- and 32-bit units that will conclude
this chapter.
Eight bits has proven to be a very useful word size for small computing tasks. Ca-
pable of 256 decimal values, or quarter-percent resolution. the 1-byte word is adequate for
many control and monitoring applications. Serial ASCH data is also stored in byte sizes,
making 8 bits the natural choice for data communications. Most integrated circuit memo-
ries and many logic functions are arranged in an 8-bit configuration that interfaces easily
to data buses of 8 bits.
Application volumes for 8-bit microcontrollers may be as high as the 4-bit models, or
they may be very low. Application sophistication can also range from simple appliance
control to high-speed machine control and data collection. For these reasons, the micro-
controller vendors have established extensive “families” of similar models. All feature
a common language, but differ in the amount of internal ROM, RAM, and other cost-
sensitive features. Often the memory can be expanded to include off-chip ROM and
RAM: in some cases. the microcontroller has no on-board ROM at all, or the ROM is an
Electrically Reprogrammable Read Only Memory (EPROM),
‘The purpose of this diversity is to offer the designer a menu of similar devices that can
solve almost any problem, The ROMIess or EPROM versions can be used by the designer
{© prototype the application, and then the designer can order the ROM version in large
‘quantities from the factory. Many times the ROM version is never used. The designer
makes the ROMIess or EPROM design sufficiently general so that one configuration may
be used many times, or because production volumes never justify the cost of a factory
ROM implementation. As a further enticement for the buyer, some families have members
with fewer external pins to shrink the package and the cost: others have special features
such as analog-to-digital (A/D) and digital-to-analog (D/A) converters on the chip.
The 8-bit arena is crowded with capable and cleverly designed contenders; this is the
‘growth segment of the market and the manufacturers are responding vigorously to the
marketplace. ‘The following table lists the generic family name for each chip, but keepMICROPROCESSORS AND MICROCONTROLLERS 7
in mind that ROMless, EPROM, and reduced pin-count members of the family are also
available, Each entry in the table has many variations; the total number of configurations
available exceeds a total of eighty types for the cleven model numbers listed.
RAM ROM
Manufacturer: Model Pins:1/O Counters (bytes) (bytes) Other Features
Intel: 8048 40:27 1 64 1K External memory
8k
Intel: 8051 40:32 2 128 4K External memory to
128K; serial port
National:COP820 28: 1 64 1K Serial bit 1/0
Motorola: 6805 28: 1 64 IK
Motorola:68HCI1 52: 2 256 8K Serial ports; A/D;
watch dog timer
wot)
Rockwell: 6500/1 40:32 1 64 2K
Signetics:87C552 68:48 3 256 8K Serial port; A/D: WDT
T1:TMS7500 40:32 1 128 2K External memory
10 64K
TI:TMS370C050 68:55 2 256 4K External memory to
112K; A/D: serial
ports; WDT
Zilog:Z8 40:32 2 128 2K External memory to
124K; serial port
Zilog :28820 44:40 2 272 8K External memory to
+f CAUTION
Not all of the pins can be used for general-purpose I/O and addressing external memory at the
same time, The sales literature should be read with some care to see how many of the pins have
more than one function. Inspection of the table shows that the designers made tradeoffs: ex-
ternal memory addressing for extra on-chip functions. Generally, the ability to expand memory
off of the chip implies that a ROMless family member is available for use in limited production
numbers where the expense of factory programming can be avoided. Lack of this feature
implies that the chip is meant for high production volumes where the expense of factory-
programmed parts can be amortized over a large number of devices.
Sixteen-Bit Microcontrollers
Eight-bit microcontrollers can be used in a variety of applications that involve limited cal-
culations and relatively simple control strategies. As the requirement for faster response
and more sophisticated calculations grows, the 8-bit designs begin to hit a limit inherent
with byte-wide data words. One solution is to increase clock speeds; another is to increase
the size of the data word. Sixteen-bit microcontrollers have evolved to solve high-speed
control problems of the type that might typically be confronted in the control of ser-
vomechanisms, such as robot arms, or for digital signal processing (DSP) applications.
The designs become much more focused on these types of real-time problems; some
generality is lost, but the vendors still try to hit as many marketing targets as they can. The
following table lists only three contenders. Intel has recently begun vigorously marketingthe $0% Lamy Other vendors are expected to appear as this market segment grows in
inportanee.
RAM ROM
Manufacturer: Model Pins:1/O Counters (bytes) (bytes) Other Features
Hitachi: H8/532 84:65 5 1K 32K External memory to
1 megabyte; serial
port; A/D; pulse
width modulation
Intel :8096 68:40 2 232 8K —_ External memory to
64K; serial port;
A/D; WDT; pulse
width modulation
National: HPCI6164 68:52 4 $12 16K External memory to
64K; serial port:
AID; WDT; pulse
width modutation
The pulse width modulation (PWM) output is useful for controlling motor speed: it
can be done using software in the 8-bit units with the usual loss of time for other tasks.
‘The 16- (and 32-) bit controllers have also been designed to take advantage of high-
level programming languages in the expectation that very little assembly language pro-
gramming will be done when employing these controlters in sophisticated applications.
Thirty-Two Bit Microcontrollers
Crossing the boundary from 16 to 32 bits involves more than merely doubling the word
size of the computer. Software boundaries that separate dedicated programs from super
visory programs are also breached. Thirty two bit designs target robotics, highly intell
‘gent instrumentation, avionics, image processing, telecommunications, automobiles, and
other environments that feature application programs running under an operating system.
‘The line between microcomputers and microcontrollers becomes very fine here,
‘The design emphasis now switches from on-chip features, such as RAM, ROM,
timers, and serial ports, to high-speed computation features. The following table provides
a general list of the capability of the Inte! 80960:
HARDWARE FEATURES SOFTWARE FEATURES
132-pin ceramic package Efficient procedure calls
20 megahertz clack Fault-handling capability
32-bit bus Trace events
Floating-point unit Global registers
§12-byte instruction cache Efficient interrupt vectors
Interrupt control Versatile addressing
All of the functions needed for 1/0, data communications, and timing and counting are
done by adding other specialized chips.
This manufacturer has dubbed all of its microcontrollers “embedded controllers,”
a term that seems to describe the function of the 32-bit 80960 very well.MICROPROCESSORS AND MICROCONTROLLERS, 9
Development Systems
for Microcontrollers
Summary
What is needed to be able to apply a microcontroller to your product? That is, what pack-
age of hardware and software will allow the microcontroller to be programmed and con-
nected to your application? A package commonly called a “development system” is
required
First, trained personnel must be available either on your technical staff or as consul
tants. One person who is versed in digital hardware and computer software is the mini-
mum number.
Second, a device capable of programming EPROMs must be available to test the
prototype device. Many of the microcontroller families discussed have a ROMIess ver-
sion, an EPROM version, or an Electrically Erasable and Programmable Read Only Mem-
ory (EEPROM) version that lets the designer debug the hardware and software prototype
before committing to full-scale production. Many inexpensive EPROM programmers are
sold that plug into a slot of most popular personal computers. More expensive, and more
versatile, dedicated programmers are also available. An alternative to EPROMs are vendor-
supplied prototype cards that allow code to be down loaded from a host computer, and the
program run from RAM for debugging purposes. An EPROM will eventually have to be
‘Programmed for the production version of the microcontroller.
Finally, software is needed, along with a personal computer to host it. The minimum
software package consists of a machine language assembler. which can be supplied by the
microcontroller vendor or bought from independent developers. More expensive software
mainly consisting of high-level language compilers and debuggers is also available.
‘A minimum development system, then, consists of a personal computer, a plug-in
EPROM programmer, and a public-brand assembler. A more extensive system would con-
sist of vendor-supplied dedicated computer systems with attendant high-level software
packages and in-circuit emulators for hardware and software debugging. In 1990 dollars,
the cost for the range of solutions outlined here is from $1000 to $10,000.
‘The fundamental differences between microprocessors and microcontrollers are:
© Microprocessors are intended to be general-purpose digital computers while micro-
controllers are intended to be special-purpose digital controllers,
© Microprocessors contain a CPU, memory addressing circuits, and interrupt han-
dling circuits. Microcontrotiers have these features as well as timers. parallel and
serial 1/O, and internal RAM and ROM.
© Microcontroller models vary in data size from 4 to 32 bits. Four-bit units are pro-
duced in huge volumes for very simple applications, and 8-bit units are the most
versatile. Sixteen- and 32-bit units are used in high-speed control and signal pro-
cessing applications.
© Many models feature programmable pins that allow external memory to be added
with the loss of 1/0 capability. :10 CHAPTER ONE
Questions
1, Name four major differences between a microprocessor and a microcontroller.
2. The 8051 has 40 pins on a Dual Inline Package (DIP) package. yet the comparison with
the Z80 microprocessor totals 58 pins. Explain this difference,
3. Name 20 items that have a built-in microcontroller.
microcontroller,
4, Name 10 items that should have a built
5. Name the most unusual application of a microcontroller that you have seen actually
for sale
6. Name the most likely bit size for each of the following products.
Modem
Printer
Toaster
Automobile engine control
Robot arm
Small ASCH data terminat
Chess player
House thermostat
7. Explain why ROMIess versions of microcontrollers exist
8. Name wo ways to speed up digital data processing
9. List three essential items needed to make up a development system for programming
microcontroller.
10. Search the literature and determine whether any manufacturer has announced a 64-bit
microcontroller.CHAPTER
I
2) ee
The 8051 Architecture
Chapter Outline
Introduction Serial Data Input/Output
8051 Microcontroller Hardware Interrupts
External Memory Summary
Counters and Timers
Introduction
The first task faced when learning to use a new computer is to become familiar with the
capability of the machine. The features of the computer are best learned by studying the
internal hardware design, also called the architecture of the device, to determine the type.
number, and size of the registers and other circuitry
‘The hardware is manipulated by an accompanying set of program instructions, or
software, which is usually studied next. Once familiar with the hardware and software, the
system designer can then apply the microcontroller to the problems at hand.
‘A natural question during this process is “What do I do with all this stuff?" Simitar to
attempting to write a poem in a foreign language before you have a vocabulary and rules
of grammar, writing meaningful programs is not possible until you have become ac-
quainted with both the hardware and the software of a computer.
This chapter provides a broad overview of the architecture of the 8051. In subsequent
chapters, we will cover in greater detail the interaction between the hardware and the
software.
8051 Microcontroller Hardware
‘The 8051 microcontroller actually includes a whole family of microcontrollers that have
‘numbers ranging from 8031 to 8751 and are available in N-Channel Metal Oxide Silicon
" (NMOS) and Complementary Metal Oxide Silicon (CMOS) construction in a variety of12. CHAPTER TWO
FIGURE 2.1a 8051 Block Diagram
Arithmetic Special. 7 ef 10
A Funetion £ g Eww
Logie Unit Registers 5 [Aone
L | 7
: : B.Bit Dataand IE
Address Bus s Pana
5 2 wo
3 & Casais
16-Bit Adress Bus ~
rH Ww
aa ‘Special. a oF tntercupt
me ‘system ogee Function g = E counter
Ae Timing ses Registers 3 © be serial bata
PSEN [= Seria
XTALI System Register te T eae
xTAaL2 | faterrupts Aine ®
RESET Timers PCON I
Data Buffers |" seurF_] !
vec —] Data Gutters Register
go] Memerrcontor| | Sans \
T 1
Register 1
1 Bank 1
1 1
1 Register '
1 Banko 7 1
! Inferal RAM Stucture| !
t '
es
package types. An enhanced version of the 8051, the 8052, also exists with its own family
of variations and even includes one member that can be programmed in BASIC, This gal-
axy of parts, the result of desires by the manufacturers to leave no market niche unfilled,
would require many chapters to cover. In this chapter, we will study a “generic” 8051,
housed in a 40-pin DIP, and direct the investigation of a particular type to the data books.
The block diagram of the 8051 in Figure 2.1a shows all of the features unique to micro-
controllers:
Internal ROM and RAM
1/0 ports with programmable pins
‘Timers and counters
Serial data communicationTHE 8051 ARCHITECTURE = 13.
FIGURE 2.1b 8051 Programming Model
fe Tes") 3 [*-) [e Tas) [2 88")
iE TG Too fr J)
register | [_seaster | [Reser
Te | AS Tnerot Reis Tine Cool Regs
Rete
st Fa =) Coe] Pee
Math Reistes Fa 715 TH 7
comer} [_comter_} {counter J |_cavntr
Tirer/Gouter Registers
Te] Cos
7 Seow SB0F 75H
repster_| |_Repster egster
Seria Data Registers Fins
Genera
Parpose
‘ea a
Sack
fete
x»
2 ry
aaaress Bit Aeresses forthe RAM Aveo Oly
zo “are oh
1 | Reser
an
18 3
i cep epe Temes
a ata Pomter al ae
10 2 orn | om ee
oF [faite
‘enk
7 "
oy (a7 71m =| =
06 RS Foto For a
register 05 % tate tater tach taten
fone 08 ae
oo cE
02 az I
e a umber ot Direct yt ders
7 ar Ste + nseates st Ateesabie
oo L___]
Byte Ine Totem
Addresses RAM ROM14 CHAPTER TWO
The figure also shows the usual CPU components: program counter, ALU, working regis-
ters, and clock circuits."
‘The 8051 architecture consists of these specific features:
Eight-bit CPU with registers A (the accumulator) and B
Sixteen-bit program counter (PC) and data pointer (DPTR)
Eight-bit program status word (PSW)
Eight-bit stack pointer (SP)
Internal ROM or EPROM (8751) of 0 (8031) to 4K (8051)
Internal RAM of 128 bytes:
Four register banks, each containing eight registers
Sixteen bytes, which may be addressed at the bit level
Eighty bytes of general-purpose data memory
‘Thirty-two input/output pins arranged as four 8-bit ports: PO-P3
‘Two 16-bit timer/counters: TO and TI
Full duplex serial data receiver transmitter: SBUF
Control registers: TCON, TMOD, SCON, PCON, IP, and IE
‘Two external and three internal interrupt sources
Oscillator and clock circui
‘The programming model of the 8051 in Figure 2. 1b shows the 8051 as a collection of
8 and 16-bit registers and 8-bit memory locations. These registers and memory locations
can be made to operate using the software instructions that are incorporated as part of the
design. The program instructions have to do with the control of the registers and digital
data paths that are physically contained inside the 8051, as well as memory locations that
are physically located outside the 8051
‘The model is complicated by the number of special-purpose registers that must be
present to make a microcomputer a microcontroller. A cursory inspection of the model is
recommended for the first-time viewer; return to the model as needed while progressing
through the remainder of the text.
Most of the registers have a specific function; those that do occupy an individual
block with a symbolic name, such as A or THO or PC. Others, which are generally indis-
tinguishable from each other, are grouped in a larger block, such as internal ROM or
RAM memory.
Each register, with the exception of the program counter, has an internal I-byte ad-
dress assigned to it. Some registers (marked with an asterisk * in Figure 2.1b) are both
byte and bit addressable. That is, the entire byte of data at such register addresses may be
read or altered, or individual bits may be read or altered. Software instructions are gener-
ally able to specify a register by its address, its symbolic name, or both.
‘A pinout of the 8051 packaged in a 40-pin DIP is shown in Figure 2.2 with the full
and abbreviated names of the signals for each pin. It is important to note that many of the
"Knowledge of the details of circuit operation that cannot be affected by any instruction or external data, while
iellectually stimulating, tends to confuse the student new to the 8051, For this reason. this text will concentrate
‘onthe essential features ofthe ROS1L: the more advanced student may wish to refer to manufacturers" data books
for additions! informationFIGURE 2.2 8051 DIP Pin Assignments.
Port 1 Bito
Port 1 it 1
Port 1Bit2
Port 1 it’s
Port 1 Bit
Port 1 Bit 5
Port 1 Bit
Port 1 Bit7
Reset input
Port 3 Bit.
(Receive Data)
10
Port 38it1 | 12
‘(XMIT Data)
Port aBit2 | 12
(interrupt 0)
Pot 3eita | 13
(interrupt 1)
Port 3eits | 14
imer 0 input)
Port 3nit 5 | 15
Timer 1 taput)
Port 3Bité | 16
(Write Strobe)
Port 3Bit7 | 17
(Read Strobe)
Cysstal input 2 | 18
Crystal mput 1 | 19
Ground | 20
ast
P3.0(RX0)
P3.1(TxD)
P3.2cINTO)
P3.30INTD)
P3.4(70)
P3.5(71)
P3.6 (WR)
P3.7(RD)
XTAL2
XTALL
vss
Vee
{AD0}PO.0
{AD1)PO.1
(an2}Po.2
(AD3)P0.3
(a04)P 0.4
(A05)PO.5
(AD6)PO.6
(AD7)P0.7
(Wppv/EA
(PROG)ALE,
SEN
(A15)P2.7
(A14yP2.6
(A13)P2.5,
(al2)P2.4
(AL DP2.3
(A10)P2.2
(A9)P2.1
(48)P2.0
a7
36
35
34
33
32
29
28
a
26
25
2a
23
22
ai
THE 8051 ARCHITECTURE
+5v
Port 0 Bit 0
(Address/Data 0)
Porto Bit 1
(Address/Data 1)
Port 0 Bit 2
(Address/Data 2)
Port 0 Bit 3
(Address/Data 3)
Port 0 Bit
Address/Data 4)
Port 0 Bit 5
(Address/Data 5)
Port 0 Bit 6
(Address/Data 6)
Port 0 Bit 7
(Address/Data 7)
External Enabie
{EPROM Programming Voltage)
‘Address Latch Ensble
(EPROM Program Pulse)
Program Store Enable
Port 2 Bit 7
(Address 15)
Port 2 Bit 6
(Address 14)
Port 2 Bit §
(Address 13)
Port 2 Bit 4
Address 12)
Port 2 Bit 3
(address 11)
Port 2 Bit 2
(Address 10)
Port 2 Bit)
(Address 9)
Port 2 Bit 0
(address 8)
Note: Alternate functions are shown below the port name (in parentheses). Pin num-
bbers and pin names are shown inside the DIP package
1516 CHAPTER TWO.
pins are used for more than one function (the alternate functions are shown in parentheses
in Figure 2.2). Not all of the possible 8051 features may be used at the same time.
Programming instructions or physical pin connections determine the use of any multi-
function pins. For example, port 3 bit 0 (abbreviated P3.0) may be used as a general-
purpose 1/0 pin, or as an input (RXD) to SBUF, the serial data receiver register. The
systém designer decides which of these two functions is to be used and designs the hard-
ware and software affecting that pin accordingly.
The 8051 Oscillator and Clock
The heart of the 8051 is the circuitry that generates the clock pulses by which all internal
operations are synchronized, Pins XTAL and XTAL2 are provided for connecting a reso-
nant network to form an oscillator. Typically, a quartz crystal and capacitors are em-
ployed, as shown in Figure 2.3. The crystal frequency is the basic internal clock fre-
quency of the microcontroller. The manufacturers make available 8051 designs that can
run at specified maximum and minimum frequencies, typically 1 megahertz to 16 mega-
hertz. Minimum frequencies imply that some internal memories are dynamic and must
always operate above a minimum frequency, or data will be lost
‘Communication needs often dictate the frequency of the oscillator due to the require-
‘ment that internal counters must divide the basic clock rate to yield standard communica-
tion bit per second (baud) rates. If the basic clock frequency is not divisible without a
remainder. then the resulting communication frequency is not standard.
FIGURE 2.3 Oscillator Circuit and Timing
cl
i/+-— 18 XTALZ.
Coystal
or 8051 DIP
Ceramic Resonator ci
t-— 19 xTALI
2
‘Crystal or Ceramic Resonator Oscillator Circuit
Po Pl 2 pl 2 pl op2 Pl po pl pe pl Po
Oscillator
Frequency
t
sate | siz [sites | sitee | sates | sates
(One Machine Cycle
Address Latch l
Enable (ALE)
8051 TimingTHE 8051 ARCHITECTURE «17
Ceramic resonators may be used as a low-cost alternative to crystal resonators. How-
ever, decreases in frequency stability and accuracy make the ceramic resonator a poor
choice if high-speed serial data communication with other systems, or critical timing, is to
be done.
The oscillator formed by the crystal, capacitors, and an on-chip inverter generates a
pulse train at the frequency of the crystal, as shown in Figure 2.3.
‘The clock frequency, f, establishes the smallest interval of time within the micro-
controller, called the pulse, P, time. The smallest interval of time to accomplish any
simple instruction, or part of a complex instruction, however, is the machine cycle. The
machine cycle is itself made up of six states. A state is the basic time interval for discrete
operations of the microcontroller such as fetching an opcode byte, decoding an opcode,
executing an opcode, or writing a data byte. Two oscillator pulses define each state,
Program instructions may require one, two, or four machine cycles to be executed,
depending on the type of instruction. Instructions are fetched and executed by the micro-
controller automatically, beginning with the instruction located at ROM memory address
0000h at the time the microcontroller is first reset
To calculate the time any particular instruction will take to be executed, find the num-
ber of cycles, C, from the list in Appendix A. The time to execute that instruction is then
found by multiplying C by 12 and dividing the product by the crystal frequency:
Cx 124
Tinst = ————___
crystal frequency
For example, if the crystal frequency is 16 megahertz, then the time to execute an ADD
A, RI one-cycle instruction is .75 microseconds, A 12 megabertz crystal yields the con-
venient time of one microsecond per cycle. An 11.0592 megahertz crystal, while seem-
ingly an odd value, yields a cycle frequency of 921.6 kilohertz, which can be divided
evenly by the standard communication baud rates of 19200, 9600, 4800, 2400, 1200, and
300 hertz
Program Counter and Data Pointer
‘The 8051 contains two 16-bit registers: the program counter (PC) and the data pointer
(DPTR). Each is used to hold the address of a byte in memory.
Program instruction bytes are fetched from locations in memory that are addressed by
the PC. Program ROM may be on the chip at addresses 0000h to OFFFh, external to the
chip for addresses that exceed OFFFh, or totally external for all addresses from 0000h to
FFFFh. The PC is automatically incremented after every instruction byte is fetched and
may also be altered by certain instructions. The PC is the only register that does not have
an internal address.
‘The DPTR register is made up of two 8-bit registers, named DPH and DPL. that are
used to furnish memory addresses for internal and external code access and external data
access. The DPTR is under the contro! of program instructions and can be specified by its
16-bit name, DPTR, or by each individual byte name, DPH and DPL. DPTR does not
have a single internal address; DPH and DPL are each assigned an address.
Aand B CPU Registers
‘The 8051 contains 34 general-purpose, or working, registers. Two of these, registers A
and B, comprise the mathematical core of the 8051 central processing unit (CPU). The
other 32 are arranged as part of internal RAM in four banks, BO-B3, of eight registers
each, named RO to R7.48 © CHAPTER TWO
FIGURE 2.4
The A (accumulator) register is the most versatile of the two CPU registers and is
used for many operations, including addition, subtraction, integer multiplication and di
sion, and Boolean bit manipulations. The A register is also used for all data transfers be-
tween the 8051 and any external memory. The B register is used with the A register for
‘multiplication and division operations and has no other function other than as a location
where data may be stored.
Flags and the Program Status Word (PSW)
Flags are I-bit registers provided to store the results of certain program instructions. Other
instructions can test the condition of the flags and make decisions based upon the flag
states. In order that the flags may be conveniently addressed, they are grouped inside the
program status word (PSW) and the power control (PCON) registers.
‘The 8051 has four math flags that respond automatically to the outcomes of math
operations and three general-purpose user flags that can be set to I or cleared to 0 by the
programmer as desired. The math flags include carry (C), auxiliary carry (AC), overflow
(OV), and parity (P). User flags are named FO, GFO, and GFI; they are general-purpose
flags that may be used by the programmer to record some event in the program. Note that
all of the flags can be set and cleared by the programmer at will. The math flags, however,
are also affected by math operations.
‘The program status word is shown in Figure 2.4. The PSW contains the math flags,
user program flag FO, and the register select bits that identify which of the four general-
purpose register banks is currently in use by the program. The remaining two user flags,
GFO and GF1, are stored in PCON, which is shown in Figure 2.13.
PSW Program Status Word Register
4
THE PROGRAM STATUS WORD (PSW) SPECIAL FUNCTION REGISTER
Bit Symbol Function
7 &Y Carty flag; used in arithmetic, JUMP, ROTATE, and BOOLEAN instructions
6 AC Auxiliary carry flag; used for BCD arithmetic
5 FO User flag 0
4 RST Register bank select bit 1
3 R50 Register bank select bit 0
RSI -RSO
0 —0_ Select register bank 0
o 1 Select register bank 1
1 0 Select register bank 2
1 1 Select register bank 3
2 ow Overflow flag; used in arithmetic instructions
eee Reserved for future use
oP Parity flag; shows parity of register A: 1 = Odd Parity
Bit addressable as PSW.0 to PSW.7THE 8051 ARCHITECTURE = 19)
Detailed descriptions of the math flag operations will be discussed in chapters that
cover the opcodes that affect the flags. The user flags can be set or cleared using data move
instructions covered in Chapter 3.
Internal Memory
A functioning computer must have memory for program code bytes. commonly in ROM.
and RAM memory for variable data that can be altered as the program runs. The 8051 has
internal RAM and ROM memory for these functions. Additional memory can be added
externally using suitable circuits.
Unlike microcontrollers with Von Neumann architectures, which can use a single
memory address for either program code or data, but not for both, the 8051 has a Harvard
architecture, which uses the same address, in different memories, for code and data. In-
ternal circuitry accesses the correct memory based upon the nature of the operation in
progress.
Internal RAM
‘The 128-byte internal RAM, which is shown generally in Figure 2.1 and in detail in Fig~
ure 2.5, is organized into three distinct areas:
1. Thirty-two bytes from address 00h to 1Fh that make up 32 working registers or-
ganized as four banks of eight registers each. The four register banks are num-
dered 0 to 3 and are made up of eight registers named RO to R7. Each register
can be addressed by name (when its bank is selected) or by its RAM address.
Thus RO of bank 3 is RO (if bank 3 is currently selected) or address 18h (whether
bank 3 is selected or not). Bits RSO and RSI in the PSW determine which bank
of registers is currently in use at any time when the program is running. Register
banks not selected can be used as general-purpose RAM. Bank 0 is selected
upon reset.
2. A bit-addressable area of 16 bytes occupies RAM byte addresses 20h to 2Fh,
forming a total of 128 addressable bits. An addressable bit may be specified by
its bit address of 00h to 7Fh, of 8 bits may form any byte address from 20h to
2Fh. Thus, for example, bit address 4Fh is also bit 7 of byte address 29h. Ad-
dressable bits are useful when the program need only remember a binary event
(switch on, light off, etc.). Internal RAM is in short supply as it is, so why use a
byte when 2 bit will do?
3. A general-purpose RAM area above the bit area, from 30h to 7Fh, addressable
as bytes.
The Stack and the Stack Pointer
‘The stack refers to an area of internal RAM that is used in conjunction with certain op-
codes to store and retrieve data quickly. The 8-bit stack pointer (SP) register is used by the
8051 to hold an internal RAM address that is called the “top of the stack.” The address
held in the SP register is the location in internal RAM where the last byte of data was
stored by a stack operation.
When data is to be placed on the stack, the SP increments before storing data on the
stack so that the stack grows up as data is stored. As data is retrieved from the stack, the
byte is read from the stack, and then the SP decrements to point to the next available byte
of stored data.20 © CHAPTER TWO
FIGURE 2.5
Internal RAM Organization
7F
u Ri
10 RO
OF RT ar DF 7
OE RG 2 [7 70,
oof Rs | 20ler 6a}
= oc Ra 2c [67 60.
& 0B RS 28 SF 58
On R2 2a [57 50.
09 RI 29 [ar 48
08, RO. 28 [a7 40,
~~ ——~or[— a7 | 27 [BF 38
06 RE 26 [37 30
05, RS 25 [2F 28
S 04 Ra 24 [27 20,
5 03 3 2a fF 18
° 02 2 227 10
o1 Ri 21 [Or 08,
Ea 00} RO, 20 [o7, 00} 39
Working Bit Addressable General Purpose
Registers
Note: Byte addresses are shown to the left; bit addresses registers are shown inside
2 location.
Operation of the stack and the SP is shown in Figure 2.6. The SP is set to 07h when
the 8051 is reset and can be changed to any internal RAM address by the programmer.
The stack is limited in height to the size of the internal RAM. The stack has the poten-
tial (if the programmer is not careful to limit its growth) to overwrite valuable data in the
register banks, bit-addressable RAM, and scratch-pad RAM areas. The programmer is
responsible for making sure the stack does not grow beyond pre-defined bound:
The stack is normally placed high in internal RAM, by an appropriate choice of the
number placed in the SP register, to avoid conflict with the register, bit, and scratch-pad
internal RAM areas.THE 8051 ARCHITECTURE 21
FIGURE 2.6 Stack Operation
store ot cetoate
ee -_H ven |
Store Data
Store Data
Storing Data on the Stack Internat RAM Getting Data From the Stack
(Increment then store) (Get then decrement)
Special Function Registers
‘The 8051 operations that do not use the internal 128-byte RAM addresses from 00h to 7Fh
are done by a group of specific internal registers, each called a special-function register
(SFR), which may be addressed much like internal RAM, using addresses from 80h
to FFh.
Some SFRs (marked with an asterisk * in Figure 2.1b) are also bit addressable, as is
the case for the bit arca of RAM. This feature allows the programmer to change only what
needs to be altered, leaving the remaining bits in that SFR unchanged.
Not all of the addresses from 80h to FFh are used for SFRs, and attempting to use an
address that is not defined, or “empty,” results in unpredictable results. In Figure 2. 1b,
the SFR addresses are shown in the upper right corner of each block. The SFR names and
equivalent internal RAM addresses are given in the following table:
INTERNAL RAM
NAME FUNCTION ADDRESS (HEX)
A Accumulator Of
8 Arithmetic FO
DPH — Addressing external memory 83
DPL ‘Addressing external memory 82
le Interrupt enable control oas
i» Interrupt priority ogg
Po Input/output port latch 80
Pr Input/output port latch 30
P2 Input/output port latch A0
P3 Input/output port latch 080
PCON Power control 87
PSW Program status word 000
SCON Serial port contro! 98
SBUF Serial port data buffer 99
Continued22 CHAPTER TWO
INTERNAL RAM.
NAME FUNCTION ADDRESS (HEX)
Continued
Ed Stack pointer 81
TMOD —Timer/counter mode control 89
ICON Timer/counter control 88
m0 Timmer 0 low byte 8A
THO Timer 0 high byte 8c
mu Timer 1 low byte 8B
m1 Timer 1 high byte 80
Note that the PC is not part of the SFR and has no internal RAM address.
SFRs are named in certain opcodes by their functional names, such as A or THO, and
are referenced by other opcodes by their addresses, such as OEOh or 8Ch. Note that any
address used in the program must start with a number; thus address E0h for the A SFR
begins with 0. Failure to use this number convention will result in an assembler error
when the program is assembled
Internal ROM
The 8051 is organized so that data memory and program code memory can be in two
entirely different physical memory entities. Each has the same address ranges.
The structure of the internal RAM has been discussed previously. A corresponding
block of internal program code, contained in an internal ROM, occupies code address
space 0000h to OFFFh. The PC is ordinarily used to address program code bytes from
addresses 0000h to FFFFh. Program addresses higher than OFFFh, which exceed the inter-
nal ROM capacity, will cause the 8051 to automatically fetch code bytes from external
program memory. Code bytes can also be fetched exclusively from an external memory,
addresses 0000h to FFFFh, by connecting the external access pin (EA pin 31 on the DIP)
to ground. The PC does not care where the code is; the circuit designer decides whether
the code is found totally in internal ROM, totally in external ROM, or in a combination of
internal and external ROM.
Input/Output Pins, Ports, and Circuits
One major feature of a microcontroller is the versatility built into the input/output (1/0)
circuits that connect the 8051 to the outside world. As noted in Chapter 1, microprocessor
designs must add additional chips to interface with external circuitry; this ability is built
{nto the microcontroller.
To be commercially viable, the 8051 had to incorporate as many functions as were
technically and economically feasible. The main constraint that limits numerous functions
is the number of pins available to the 8051 circuit designers. The DIP has 40 pins, and the
success of the design in the marketplace was determined by the flexibility built into the use
of these pins.
For this reason, 24 of the pins may each be used for one of two entirely different
functions, yielding a total pin configuration of 64. The function a pin performs at any
given instant depends, first, upon what is physically connected to it and, then, upon what
software commands are used to “program” the pin. Both of these factors are under the
complete control of the 8051 programmer and circuit designer.THE 8051 ARCHITECTURE 23.
Given this pin flexibility, the 8051 may be applied simply as a single component with
V/O only, or it may be expanded to include additional memory, parallel ports, and serial
data communication by using the alternate pin assignments. The key to programming an
alternate pin function is the port pin circuitry shown in Figure 2.7.
Each port has a D-type output latch for each pin. The SFR for each port is made up
of these eight latches, which can be addressed at the SFR address for that port. For in-
stance, the eight latches for port 0 are addressed at location 80h: port 0 pin 3 is bit 2 of the
POSER. The port latches should not be confused with the port pins; the data on the latches
does not have to be the same as that on the pins.
The two data paths are shown in Figure 2.7 by the circuits that read the latch or pin
data using two entirely separate buffers, The top buffer is enabled when latch data is read,
and the lower buffer, when the pin state is read. The status of each latch may be read from
a latch buffer, while an input buffer is connected directly to each pin so that the pin status
may be read independently of the latch state.
Different opcodes access the latch or pin states as appropriate. Port operations are
determined by the manner in which the 8051 is connected to external circuitry.
Programmable port pins have completely different alternate functions. The configura-
tion of the control circuitry between the output latch and the port pin determines the nature
of any particular port pin function. An inspection of Figure 2.7 reveals that only port 1
cannot have alternate functions; ports 0, 2, and 3 can be programmed.
The ports are not capable of driving loads that require currents in the tens of milli-
amperes (mA). As previously mentioned, the 8051 has many family members, and many
are fabricated in varying technologies. An example range of logic-level currents, volt-
ages, and total device power requirements is given in the following table:
Parameter Von ton Vor Na Va hy Vin ty Lt
cmos 24V -60pA ASV 1.6mA OV |10nA) 19V [10 pA] SOmW
NMOS 24V -B0wA 45V1.6mA BV -BODWA 20V 10 pA B00 mW
These figures tell us that driving more than two LSTTL inputs degrades the noise
immunity of the ports and that careful attention must be paid to buffering the ports when
they must drive currents in excess of those listed. Again, one must refer to the manufac-
turers* data books when designing a “real” application.
Port 0
Port 0 pins may serve as inputs, outputs, or, when used together, as a bi-directional low-
order address and data bus for external memory. For example, when a pin is to be used as
an input, a 1 must be written to the corresponding port 0 latch by the program, thus turn-
ing both of the output transistors off, which in turn causes the pin to “float” in a high-
impedance state, and the pin is essentially connected to the input buffer.
‘When used as an output, the pin latches that are programmed to a 0 will turn on the
lower FET, grounding the pin. All latches that are programmed to a I still float; thus,
external pullup resistors will be needed to supply a logic high when using port 0 as an
output.
When port 0 is used as an address bus to external memory, internal control signals
switch the address lines to the gates of the Field Effect Transistories (FETs). A logic | on
an address bit will turn the upper FET on and the lower FET off to provide a logic high at
the pin. When the address bit is a zero, the lower FET is on and the upper FET off toFIGURE 2.7 Port Pin Circuits
Yee
Enhancement.
Mode FET
1_frwooseitator
Resa ater Bt Penede
Internal FET Pot
tetera Bus =
Write to Late ox
ort 0 Pin Configuration
Rend Fin Dat
Read Latch Data a
Internat Bos re
Write to Lath
Port Pin Configuration
esd in Daty ———____—_]
Control Signals
serese
Read Latch Bt
Internal us ——
wate to Latch ——t
Pont SFR Latch
ead Pia Data
‘aerate Dutt
Read Late Bit
Interna Ba
Wate toLaten
Pott 2 Pin Configuration
Port SFR Lateh
endPin Osta
‘terate put
Pott 3 in Configuration
Depletion
Mode FETTHE 8051 ARCHITECTURE 25,
provide a logic low at the pin. After the address has been formed and latched into external
circuits by the Address Latch Enable (ALE) pulse, the bus is turned around to become a
data bus. Port 0 now reads data from the external memory and must be configured as an
input, so a logic 1 is automatically written by internal contro! logic to all port 0 latches.
Port 1
Port | pins have no dual functions. Therefore, the output latch is connected directly to the
gate of the lower FET, which has an FET circuit labeled “Internal FET Pullup” as an
active pullup load.
Used as an input, a 1 is written to the latch, turning the lower FET off; the pin and the
input to the pin buffer are pulled high by the FET load. An external circuit can overcome
the high impedance pullup and drive the pin low (o input a 0 or leave the input high for a 1.
If used as an output, the latches containing a I can drive the input of an external
circuit high through the pullup. If a 0 is written to the latch, the lower FET is on, the
pullup is off, and the pin can drive the input of the external circuit low.
To aid in speeding up switching times when the pin is used as an output, the internal
FET pullup has another FET in parallel with it. The second FET is turned on for two
‘oscillator time periods during a low-to-high transition on the pin, as shown in Figure 2.7
This arrangement provides a low impedance path to the positive voltage supply to help
reduce rise times in charging any parasitic capacitances in the external circuitry.
Port 2
Port 2 may be used as an input/output port similar in operation to port 1. The alternate use
of port 2 is to supply a high-order address byte in conjunction with the port 0 low-order
byte to address external memory.
Port 2 pins are momentarily changed by the address control signals when supplying
the high byte of a 16-bit address. Port 2 latches remain stable when external memory is
addressed, as they do not have to be turned around (set to 1) for data input as is the case
for port 0.
Port 3
Port 3 is an input/output port similar to port 1, The input and output functions can be
programmed under the control of the P3 latches or under the control of various other spe-
cial function registers. The port 3 alternate uses are shown in the following table:
PIN ALTERNATE USE SFR
P3.0-RXD Serial data input SBUF
Serial data output SBUF
External interrupt 0 TCONA
External interrupt 1 TCON.3
External timer 0 input MOD
External timer 1 input MoD
External memory write pulse = —
External memory read pulse —
Unlike ports 0 and 2, which can have external addressing functions and change all
eight port bits when in alternate use, each pin of port 3 may be individually programmed
to be used either as I/O or as one of the alternate functions.26
CHAPTER TWO
External Memory
The system designer is not limited by the amount of internal RAM and ROM available
con chip. Two separate external memory spaces are made available by the 16-bit PC and
DPTR and by different control pins for enabling external ROM and RAM chips. Internal
control circuitry accesses the correct physical memory, depending upon the machine cycle
state and the opcode being executed
‘There are several reasons for adding external memory, particularly program memory,
when applying the 8051 in a system. When the project is in the prototype stage, the
expense—in time and money—of having a masked internal ROM made for each program
“try” is prohibitive. To alleviate this problem, the manufacturers make available an
EPROM version, the 8751, which has 4K of on-chip EPROM that may be programmed
and erased as needed as the program is developed. The resulting circuit board layout will
bbe identical to one that uses a factory-programmed 8051. The only drawbacks to the 8751
are the specialized EPROM programmers that must be used to program the non-standard
40-pin part, and the limit of “only” 4096 bytes of program code.
The 8751 solution works well if the program will fit into 4K bytes. Unfortunately,
many times, particularly if the program is written in a high-level language, the program
size exceeds 4K bytes, and an external program memory is needed. Again, the manufac-
turers provide a version for the job, the ROMless 8031. The EA pin is grounded when
using the 8031, and all program code is contained in an external EPROM that may be as
large as 64K bytes and that can be programmed using standard EPROM programmers.
External RAM, which is accessed by the DPTR, may also be needed when 128 bytes
of internal data storage is not sufficient. External RAM. up to 64K bytes, may also be
added to any chip in the 8051 family.
Connecting External Memory
Figure 2.8 shows the connections between an 8031 and an external memory configuration
consisting of 16K bytes of EPROM and 8K bytes of static RAM. The 8051 accesses exter-
nal RAM whenever certain program instructions are executed. External ROM is accessed
whenever the EA (external access) pin is connected to ground or when the PC contains an
address higher than the last address in the internal 4K bytes ROM (OFFFh). 8051 designs
can thus use internal and external ROM automatically; the 8031, having no internat ROM,
must have EA grounded.
Figure 2.9 shows the timing associated with an external memory access cycle. Dur-
ing any memory access cycle, port 0 is time multiplexed. That is, it first provides the
lower byte of the 16-bit memory address, then acts as a bidirectional data bus to write or
read a byte of memory data. Port 2 provides the high byte of the memory address during
the entire memory read/write cycle.
The lower address byte from port | must be latched into an external register to save
the byte. Address byte save is accomplished by the ALE clock pulse that provides the
correct timing for the °373 type data latch. The port 0 pins then become free to serve as a
data bus.
If the memory access is for a byte of program code in the ROM, the PSEN (program
store enable) pin witl go low to enable the ROM to place a byte of program code on the
data bus. If the access is for a RAM byte, the WR (write) or RD (read) pins will go low,
‘enabling data to ow between the RAM and the data bus.
‘The ROM may be expanded to 64K by using a 27512 type EPROM and connecting
the remaining port 2 upper address lines Al4—A1S to the chip,
AL this time the largest static RAMS available are 32K in size; RAM can be expanded
to 64K by using two 32K RAMS that are connected through address A14 of port 2. TheFIGURE 2.8 External Memory Connections
FA
1g 16 13 11
19 15 12
FIGURE 2.9 External Memory Timing
Port 0 AO-AT
Port 2
Latch Add |
aE ich Address
ALE Pulse a
External Memory Addressing I
PSEN Pulse
SEN
Enable ROM
Reading ROM Using PSEN |
Read Pulse _
0
Enable Read
Write Pulse
WR
Enable write
‘Accessing RAM Using RD or WR28 © CHAPTER TWO.
FIGURE 2.10 TCON and TMOD Function Registers
7 6 5 4 3 2 1 +O
‘THE TIMER CONTROL (TCON) SPECIAL FUNCTION REGISTER
Bit Symbol
7 TF
6 TR
5 Tr
4 TRO
3 EY
207
1 EO
Function
Timer 1 Overflow flag. Set when timer rolls from all ones to zero. Cleared when processor
vectors to execute interrupt service routine located at program address O01Bh.
Timer 1 run control bit. Set to 1 by program to enable timer to count: cleared to 0 by
program to halt timer. Does not reset timer
Timer 0 Overflow flag, Set when timer rolls from all ones to zero. Cleared when processor
vectors to execute interrupt service routine located at program address 000Bh.
Timer 0 run control bit. Set to 1 by program to enable timer to count; cleared to 0 by
program to halt timer. Does not reset timer.
External interrupt | edge flag. Set to 1 when a high to low edge signal is received on port 3
pin 3.3 (INTT), Cleared when processor vectors to interrupt service routine
located at program address 03h. Not related to timer operations
External interrupt | signal type contro! bit, Set to 1 by program to enable external interrupt 3
10 be triggered by a falling edge signal. Set to 0 by program to enable a low level
signal on external interrupt 1 to generate an interrupt.
External interrupt 0 edge flag. Set to 1 when a high to low edge signal is received on port 3
pin 3.2 (INTO). Cleared when processor vectors to interrupt service routine located at
program address 0003h. Not related to timer operations.
Continued
first 32K RAM (0000h—7FFFh) can then be enabled when A15 of port 2 is low, and the
second 32K RAM (8000h—FFFFh) when AIS is high, by using an inverter.
Note that the WR and RD signals are alternate uses for port 3 pins 16 and 17. Also,
port Os used for the lower address byte and data: port 2 is used for upper address bits. The
use of external memory consumes many of the port pins, leaving only port 1 and parts of
port 3 for general 1/0.
Counters and Timers
Many microcontroller applications require the counting of external events, such as the
frequency of a pulse train, or the generation of precise internal time delays between com-
puter actions. Both of these tasks can be accomplished using software techniques, but
software loops for counting or timing keep the processor occupied so that other, perhaps
‘more important, functions are not done. To relieve the processor of this burden. two 16-bit
up counters, named TO and T!,, are provided for the general use of the programmer. Each
counter may be programmed to count internal clock pulses. acting as a timer, or pro-
‘grammed to count external pulses as a counter,THE aos ARCHITECTURE = 29)
Bit Symbol — Function
om External interrupt O signal type control bit. Set to 1 by program to enable external interrupt 0
to be triggered by a falling edge signal. Set to 0 by program to enable a low level
signal on external interrupt 0 to generate an interrupt
Bit addressable as TCON.O to TCON.7
7 5 4
C Timer 1 Tf Timer 0 J
‘THE TIMER MODE CONTROL (TMOD) SPECIAL FUNCTION REGISTER.
Symbol — Function
713 Gate OR gate enable bit which controls RUN/STOP of timer 1/0. Set to 1 by program to enable
timer to run if bit TR1/0 in TCON is set and signal on external interrupt INT1/0 pin is
high. Cleared to 0 by program to enable timer to run if bit TR1/0 in TCON is set.
62 CT Set to 1 by program to make timer 1/0 act as a counter by counting pulses from external
input pins 3.5 (T1) or 3.4 (T0). Cleared to 0 by program to make timer act as a timer
by counting internal frequency.
sami Timer/counter operating mode select bit 1, Set/cleared by program to select mode.
470 MO Timer/counter operating mode select bit 0, Set/cleared by program to select mode.
M1 MO Mode
o 0 0
o 1 1
1 0 2
1 4 38
TMOD is not bit addressable
The counters are divided into two 8-bit registers called the timer low (TLO, TL1) and
high (THO, THI) bytes. All counter action is controlled by bit states in the timer mode
control register (TMOD), the timer/counter control register (TCON), and certain program
instructions.
‘TMOD is dedicated solely to the two timers and can be considered to be two duplicate
4-bit registers, each of which controls the action of one of the timers. TCON has control
bits and flags for the timers in the upper nibble, and control bits and flags for the external
interrupts in the lower nibble. Figure 2.10 shows the bit assignments for TMOD and TCON.
Timer Counter Interrupts
‘The counters have been included on the chip to relieve the processor of timing and count-
ing chores. When the program wishes to count a certain number of internal pulses or
external events, a number is placed in one of the counters. The number represents the
maximum count less the desired count, plus one. The counter increments from the initial
number to the maximum and then rolls over to zero on the final pulse and also sets a timer
flag. The flag condition may be tested by an instruction to tell the program that the count
has been accomplished, or the flag may be used to interrupt the program.30 CHAPTER TWO.
FIGURE 2.11
Oscitlator
Frequency
Counter, G/T = 1 (TMOD Counter Operation)
11/0 input 9. ——————
Gate Bit inTMOD
INTH/0 tnput Pin
Timer/Counter Control Logic
CHF = 0 (TMOD Timer Operation)
> To Timer Stages
TR1/0 Bit In TCON
Timing
Ifa counter is programmed to be a timer, it will count the internal clock frequency of the
8051 oscillator divided by 12d, As an example, if the crystal frequency is 6.0 megahertz,
then the timer clock will have a frequency of 500 kilohertz,
‘The resultant timer clock is gated to the timer by means of the circuit shown in Figure
2.11, In order for oscillator clock pulses to reach the timer, the C/T bit in the TMOD
register must be set to 0 (timer operation), Bit TRX in the TCON register must be set to 1
(timer run), and the gate bit in the TMOD register must be 0, or external pin INTX must
be a1. In other words, the counter is configured as a timer, then the timer pulses are gated
to the counter by the run bit and the gate bit or the external input bits INTX.
Timer Modes of Operation
‘The timers may operate in any one of four modes that are determined by the mode bits,
MI and MO, in the TMOD register. Figure 2.12 shows the four timer modes.
Timer Mode 0
Setting timer X mode bits to 00b in the TMOD register results in using the THX register
as an 8-bit counter and TLX as a 5-bit counter; the pulse input is divided by 32d in TL so
that TH counts the original oscillator frequency seduced by a total 384d. As an example,
the 6 megahertz oscillator frequency would result in a final frequency to TH of 15625
hertz, The timer flag is set whenever THX goes from FFh to 00h, or in .0164 seconds for
a 6 megahertz crystal if THX starts at 00h,
Timer Mode 1
Mode | is similar to mode 0 except TLX is configured as a full 8-bit counter when the
mode bits are set to O1b in TMOD. The timer flag would be set in .1341 seconds using.
86 megahertz crystal.THE 8051 ARCHITECTURE = 317
FIGURE 2.12 Timer 1 and Timer 0 Operation Modes
Pulse
Inout ——be|TLXS Bits
(Figure 2.11)
Interrupt
‘Timer Mode 0 13- Bit Timer/Counter
ruse
tm) ——ef_taeem Ff meee LL rn Interupt
gianna) a
Timer Mode 1 16-Bit TimeriCounter
Pulse
Input ] =
‘THE POWER MODE CONTROL (PCON) SPECIAL FUNCTION REGISTER.
Bit Symbol Function
7 SMOD —_ Serial baud rate modify bit. Set to 1 by program to double baud rate using timer 1 for
modes 1, 2, and 3. Cleared to 0 by program to use timer 1 baud rate,
64 — ‘Not implemented.
3 GF General purpose user flag bit 1. Set/cleared by program.
2 GFO General purpose user flag bit 0. Set/cleared by program.
1 °D Power down bit. Set to 1 by program to enter power down configuration for CHMOS-
processors.
oD Idle mode bit. Set to 1 by program to enter idle mode configuration for CHMOS
processors. PCON is not bit addressable.34
CHAPTER TWO
included in SCON to aid in efficient data transmission and reception. Notice that data
transmission is under the complete control of the program, but reception of data is unpre-
dictable and at random times that are beyond the control of the program.
‘The serial data flags in SCON, TI and RI, are set whenever a data byte is transmitied
(TI) or received (RI). These flags are ORed together to produce an interrupt (o the pro-
‘gram, The program must read these flags to determine which caused the interrupt and then
clear the flag. This is unlike the timer flags that are cleared automatically; itis the respon-
sibility of the programmer to write routines that handle the serial data flags.
Data Transmission
Transmission of serial data bits begins anytime data is written to SBUF. TI is set to a I
when the data has been transmitted and signifies that SBUF is empty (for transmission
purposes) and that another data byte can be sent. If the program fails to wait for the TI flag.
and overwrites SBUF while a previous data byte is in the process of being transmitted, the
results will be unpredictable (a polite term for “garbage out”).
Data Reception
Reception of serial data will begin if the receive enable bit (REN) in SCON is set to | for
all modes. In addition, for mode 0 only, RI must be cleared to 0 also. Receiver interrupt
flag RI is set after data has been received in all modes, Setting REN is the only direct
program control that limits the reception of unexpected data; the requirement that RI also
be 0 for mode 0 prevents the reception of new data until the program has dealt with the old
data and reset RI.
Reception can begin in modes 1, 2, and 3 if RI is set when the serial stream of bits
begins. RI must have been reset by the program before the last bit is received or the
incoming data will be lost. Incoming data is not transferred to SBUF until the last data bit
has been received so that the previous transmission can be read from SBUF while new
data is being received,
Serial Data Transmission Modes
The 8051 designers have included four modes of serial data transmission that enable data
communication to be done in a variety of ways and a multitude of baud rates. Modes are
selected by the programmer by setting the mode bits SMO and SMI in SCON. Baud rates
are fixed for mode 0 and variable, using timer | and the serial baud rate modify bit (SMOD)
in PCON, for modes 1, 2, and 3,
Serial Data Mode 0—Shift Register Mode
Setting bits SMO and SMI in SCON to 00b configures SBUF to receive or transmit cight
data bits using pin RXD for both functions. Pin TXD is connected to the internal shift
frequency pulse source to supply shift pulses to external circuits. The shift frequency, or
baud rate, is fixed at 1/12 of the oscillator frequency, the same rate used by the timers
when in the timer configuration. The TXD shift clock is a square wave that is low for
machine cycle states S3—S4~S5 and high for S6~S1~-S2. Figure 2.14 shows the timing
for mode O shift register data transmission.
‘When transmitting, data is shifted out of RXD; the data changes on the falling edge
of S6P2, or one clock pulse after the rising edge of the output TXD shift clock. The sys-
tem designer must design the external circuitry that receives this transmitted data to te-
ceive the data reliably based on this timing.THE gost ARCHITECTURE «35
FIGURE 2.14 Shift Register Mode 0 Timing
Shift Data Out
S6P2
L 1 i 1 1 1 i 1
RxDDataout [po | oi 1 oz Tos | pa | os | pe | 7 External Data Bits Shifted Out
TKO Clock
XD Data in
13
eet cet
S3PL | S6P1 | I 1
8 1
! t
it | __ Externat Data Bits Shifted in
Tat T
poor pet os toa Tost] ve Port
EEE EEE 1
s5P2
Shift Data In
Received data comes in on pin RXD and should be synchronized with the shift clock
produced at TXD. Data is sampled on the falling edge of S5P2 and shifted in to SBUF on
the rising edge of the shift clock
Mode 0 is intended not for data communication between computers, but as 2 high-
speed serial data-collection method using discrete logic to achieve high data rates. The
baud rate used in mode 0 will be much higher than standard for any reasonable oscillator
frequency; for a 6 megahertz crystal, the shift rate will be 500 kilohertz
Serial Data Mode 1—Standard UART
When SMO and SMI are set to Olb, SBUF becomes a 10-bit full-duplex receiver!
‘transmitter that may receive and transmit data at the same time. Pin RXD receives all data,
and pin TXD transmits all data. Figure 2.15 shows the format of a data word.
‘Transmitted data is sent as a start bit. eight data bits (Least Significant Bit, LSB,
first), and a stop bit. Interrupt flag TI is set once all ten bits have been sent. Each bit
interval is the inverse of the baud rate frequency, and each bit is maintained high or low
over that interval.
Received data is obtained in the same order; reception is triggered by the falling edge
of the start bit and continues if the stop bit is true (0 level) halfway through the start bit
interval. This is an anti-noise measure; if the reception circuit is triggered by noise on the
transmission line, the check for a low after half a bit interval should limit false data
reception.
Data bits are shifted into the receiver at the programmed baud rate, and the data word
will be loaded to SBUF if the following conditions are true: RI must be 0, and mode bit
‘SM2 is 0 or the stop bit is I (the normal state of stop bits). RI set to 0 implies that the
program has read the previous data byte and is ready to receive the next; a normal stop bit
will then complete the transfer of data to SBUF regardless of the state of SM2. SM2 set
to0 enables the reception of a byte with any stop bit state, a condition which is of limited
use in this mode, but very useful in modes 2 and 3. SM2 set to 1 forces reception of only
“good” stop bits, an anti-noise safeguard
Of the original ten bits, the start bit is discarded, the eight data bits go to SBUF, and
the stop bit is saved in bit RB8 of SCON. RI is set to 1, indicating a new data byte has
been received.36 © CHAPTER TWO.
FIGURE 2.15 Standard UART Data Word
Receiver Samples Data in Center of Bit Time
woe LE ae
ae ie ee ane Te eet
Protetat4¢4tstet7 8 |
ee ae 4
Start Bit Data Bits Minimum of
‘One Stop Bit
1
Bit Time = —
i .—
If RI is found to be set at the end of the reception, indicating that the previously
received data byte has not been read by the program, or if the other conditions listed are.
not true, the new data will not be loaded and will be lost
Mode 1 Baud Rates
Timer | is used to generate the baud rate for mode 1 by using the overflow flag of the timer
to determine the baud frequency. Typically, timer | is used in timer mode 2 as an autoload
8-bit timer that generates the baud frequency:
f 2a00 | _ oscillator frequency
wet 32d 12d X [256d — (THD)
SMOD is the control bit in PCON and can be 0 or 1, which raises the 2 in the equation to a
value of 1 or 2.
If timer 1 is not run in timer mode 2, then the baud rate is
2s"o0
Set = 339
X (timer I overflow frequency)
and timer I can be run using the internal clock or as a counter that receives clock pulses
from any external source via pin TI
The oscillator frequency is chosen to help generate both standard and nonstandard
‘auld rates. If standard baud rates are desired, then an 11.0592 megahertz crystal could be
selected. To get a standard rate of 9600 hertz then, the setting of THI may be found as
follows:
2se4 - (20
aia (S
11.0592 x 10°
12 « 96008
THI 253.0000d
if SMOD is cleared to 0.
Serial Data Mode 2—Multiprocessor Mode
Mode 2 is similar to mode 1 except 11 bits are transmitted: a start bit, nine data bits, and a
stop bit, as shown in Figure 2.16. The ninth data bit is gotten from bit TBS in SCON
during transmit and stored in bit RB8 of SCON when data is received. Both the start and
stop bits are discarded.
‘The baud rate is programmed as follows:
sMoo
fame = X oscillator frequencyTHE 8051 ARCHITECTURE «37.
FIGURE 2.16 Multiprocessor Data Word
Idle State
Te In Center of Bit Time
ee te Ltd Ld Ls
peeeeeeeee eee ee Be ae a A eI
ry 2
reget ts eee Le Era 4
Minimum Of
Start Bit panne
Laon ‘One Stop Bit
ime =
7
‘—
Interrupts
Here, as in the case for mode 0, the baud rate is much higher than standard communica-
tion rates. This high data rate is needed in many multi-processor applications. Data can be
collected quickly from an extensive network of communicating microcontrollers if high
baud rates are employed.
The conditions for setting RI for mode 2 are similar to mode 1: RI must be 0 before
the last bit is received, and SM2 must be 0 or the ninth data bit must be a |. Setting RI
based upon the state of SM2 in the receiving 8051 and the state of bit 9 in the transmitted
message makes multiprocessing possible by enabling some receivers to be interrupted by
certain messages, while other receivers ignore those messages. Only those 8051's that
have SM? set to 0 will be interrupted by received data which has the ninth data bit set to 0;
those with SM2 set to 1} will not be interrupted by messages with data bit 9 at 0. All re-
ceivers will be interrupted by data words that have the ninth data bit set to 1; the state of
'SM2 will not block reception of such messages.
This scheme allows the transmitting computer to “talk” to selected receiving comput-
ers without interrupting other receiving computers. Receiving computers can be com-
manded by the “talker” to “listen” or "‘deafen” by transmitting coded byte(s) with the
ninth data bit set to 1. The 1 in data bit 9 interrupts all receivers, instructing those that are
programmed to respond to the coded byte(s) to program the state of SM2 in their respec
tive SCON registers. Selected listeners then respond to the bit 9 set to 0 messages, while
all other receivers ignore these messages. The talker can change the mix of listeners by
transmitting bit 9 set to 1 messages that instruct new listeners to set SM2 to 0, while others
are instructed to set SM2 to 1
Serial Data Mode 3
using Timer 1 to generate communication frequencies.
‘A computer program has only two ways to determine the conditions that exist in internal
and external circuits. One method uses software instructions that jump on the states of
flags and port pins. The second responds to hardware signals, called interrupts, that force
the program to call a sub-routine. Software techniques use up processor time that could be
devoted to other tasks: interrupts take processor time only when action by the program
is needed. Most applications of microcontrollers involve responding to events quickly
enough to control the environment that generates the events (generically termed “real-FIGURE 2.17 IE and IP Function Registers
7 6 5 4 3
eT T[s]a
‘THE INTERRUPT ENABLE (IE) SPECIAL FUNCTION REGISTER
Bit Symbol —_ Function
7 OA Enable interrupts bit. Cleared to 0 by program to disable all interrupts; set to 1 to permit
individual interrupts to be enabled by their enable bits
6 = Not implemented
5 em Reserved for future use.
4 Enable serial port interrupt. Set to 1 by program to enable serial port interrupt; cleared
10 0 to disable serial port interrupt.
300 Enable timer 1 overflow interrupt. Set to 1 by program to enable timer 1 overflow
interrupt; cleared to 0 to disable timer 1 overfiow interrupt.
2 ext Enable external interrupt 1. Set to 1 by program to enable INT1 interrupt: cleared to 0 to
disable (NTT interrupt.
1&0 Enable timer 0 overflow interrupt, Set to 1 by program to enable timer 0 overflow interrupt;
cleared to 0 to disable timer 0 overflow interrupt
0 EXO Enable external interrupt 0. Set to 1 by program to enable INTO interrupt; cleared to 0 to
disable INTO interrupt
Bit addressable as 1E.0 to 16.7
7 6 5 4 3 2 1 oo
THE INTERRUPT PRIORITY (IP) SPECIAL FUNCTION REGISTER
Bit Symbol Function
7h Not implemented
6 - Not implemented
5 Pra Reserved for future use,
ns) Priority of serial port interrupt. Set/cleared by program.
3 PTY Priotty of timer 1 overflow interrupt. Set/cleared by program.
2 PKI Priority of external interrupt 1. Set/cleared by program,
1 Pt Priority of timer 0 overflow interrupt. Set/cleared by program.
0 Pxo Priority of external interrupt 0. Set/cleared by program,
Note: Priority may be 1 (highest) or 0 (lowest)
Bit addressable as IP. to IP7THE 8051 ARCHITECTURE 39.
\¢ programming”). Interrupts are often the only way in which real-time programming
can be done successfully.
Interrupts may be generated by internal chip operations or provided by external
sources. Any interrupt can cause the 8051 (o perform a hardware call to an interrupt-
handling subroutine that is located at a predetermined (by the 8051 designers) absolute
address in program memory.
Five interrupts are provided in the 8051. Three of these are generated automatically
by internal operations: timer flag 0. timer flag 1, and the serial port interrupt (RI or TD).
‘Two interrupts are triggered by external signals provided by circuitry that is connected to
pins INTO and INTI (port pins P3.2 and P3.3).
Al interrupt functions are under the control of the program. The programmer is able
to alter control bits in the interrupt enable register (IE), the interrupt priority register (IP),
‘and the timer control register (TCON). The program can block all or any combination of
the interrupts from acting on the program by suitably setting or clearing bits in these regis-
ters. The IE and IP registers are shown in Figure 2.17.
‘After the interrupt has been handled by the interrupt subroutine, which is placed by
the programmer at the interrupt location in program memory, the interrupted program
‘must resume operation at the instruction where the interrupt took place. Program resump-
tion is done by storing the interrupted PC address on the stack in RAM before changing
the PC (o the interrupt address in ROM. The PC address will be restored from the stack
after an RETI instruction is executed at the end of the interrupt subroutine.
Timer Flag Interrupt
When a timer/counter overflows, the corresponding timer flag, TFO or TFI, is set to 1
‘The flag is cleared 10 0 when the resulting imerrupt generates a program call to the appro-
priate timer subroutine in memory.
Serial Port Interrupt
Ifa data byte is received, an interrupt bit, RI, is set to 1 in the SCON register. When a data
byte has been transmitted an interrupt bit, TI, is set in SCON. These are ORed together to
provide a single interrupt to the processor: the serial port interrupt. These bits are nor
cleared when the interrupt-generated program call is made by the processor. The program
that handles serial data communication must reset RI or TI to 0 to enable the next data
communication operation
External Interrupts
Pins INTO and INTT are used by external circuitry. Inputs on these pins can set the inter-
rupt flags 1E0 and IE! in the TCON register to | by two different methods. The IEX flags
may be set when the INTX pin signal reaches a low level, or the flags may be set when a
high-to-low transition takes place on the INTX pin. Bits ITO and ITI in TCON program
the INTX pins for low-level interrupt when set to 0 and program the INTX pins for transi-
tion interrupt when set to 1.
Flags IEX will be reset when a transition-gencrated interrupt is accepted by the pro-
cessor and the interrupt subroutine is accessed. It is the responsibility of the system de-
signer and programmer to reset any level-generated external interrupts when they are
serviced by the program. The external circuit must remove the low level before an RETI is
executed. Failure to remove the low will result in an immediate interrupt after RETI, from
the same source.40
CHAPTER TWO.
Reset
‘A reset can be considered to be the ultimate interrupt because the program may not block
the action of the voltage on the RST pin. This type of interrupt is often called “non-
maskable,” since no combination of bits in any register can stop, or mask the reset action
Unlike other interrupts. the PC is not stored for later program resumption; a reset is an
absolute command to jump to program address 0000h and commence running from there.
‘Whenever a high level is applied to the RST pin, the 8051 enters a reset condition.
‘After the RST pin is brought low, the internal registers will have the values shown in the
following table:
REGISTER — VALUE(HEX)
PC 0000
err 000
A 00,
B 00
‘SP 07
PSW 00,
PO-3 FF
° Xxx00000b
3 ‘0xx000005
ICON 00
TMOD: 00,
THO 00
m0 00
THI 00
mu 00
SCON 00
SBUF x
PCON OXXXXXXXbB
Internal RAM is not changed by a reset; however, the states of the internal RAM
‘when power is first applied to the 8051 are random. Register hank (is selected upon reset
as all bits in PSW are 0.
Interrupt Control
The program must be able, at critical times, to inhibit the action of some or all of the
interrupts so that crucial operations can be finished. The IE register holds the program-
mable bits that can enable or disable all the interrupts as a group, or if the group is en-
abled, each individual interrupt source can be enabled or disabled.
Often, it is desirable to be able to set priorities among competing interrupts that may
conceivably occur simultaneously. The IP register bits may be set by the program to assign
priorities among the various interrupt sources so that more important interrupts can be
serviced first should two or more interrupts occur at the same time.
Interrupt Enable/Disable
Bits in the El register are set to 1 if the corresponding interrupt source is to be enabled and
set to 0 to disable the interrupt source. Bit EA is a master, or “global,” bit that can enable
‘or disable all of the interrupts.Summary
THE SOS1 ARCHITECTURE = 4.
Interrupt Priority
Register IP bits determine if any interrupt is to have a high ot low priority. Bits set to 1
give the accompanying interrupt a high priority while a O assigns a low priority. Interrupts
with a high priority can interrupt another interrupt with a lower priority: the low priority
interrupt continues after the higher is finished.
If two interrupts with the same priority occur at the same time, then they have the
following ranking:
1. 160
2. TRO
3. IEI
4, TFL
5. Serial = RIOR TI
The serial interrupt could be given the highest priority by setting the PS bit in IP to 1, and
all others to 0.
Interrupt Destinations
Each interrupt source causes the program to do a hardware call to one of the dedicated
addresses in program memory. It is the responsibility of the programmer to place a routine
at the address that will service the interrupt.
‘The interrupt saves the PC of the program, which is running at the time the interrupt
is serviced on the stack in internal RAM. A call is then done to the appropriate memory
location. These locations are shown in the following table:
INTERRUPT — ADDRESS(HEX)
160 0003
Tro 0008
ie 0013
Te 0018
SERIAL 0023
A RET! instruction at the end of the routine restores the PC to its place in the inter-
rupted program and resets the interrupt logic so that another interrupt can be serviced.
Interrupts that occur but are ignored due to any blocking condition (IE bit not set or a
higher priority interrupt already in process) must persist until they are serviced, or they
will be fost. This requirement applies primarily to the level-activated INTX interrupts.
Software Generated Interrupts
When any interrupt flag is set to 1 by any means, an interrupt is generated unless blocked.
This means that the program itself can cause interrupts of any kind to be generated simply
by setting the desired interrupt flag to 1 using a program instruction.
‘The internal hardware configuration of the 8051 registers and control circuits have been
examined at the functional block diagram level. The 8051 may be considered to be a cot-
lection of RAM, ROM, and addressable registers that have some unique functions.a2
CHAPTER TWO.
SPECIAL-FUNCTION REGISTERS
Register Bit Primary Function Bit Addressable
A 8 Math, data manipulation Y
8 8 Math Y
PC 16 Addressing program bytes N
DPTR 16 Addressing code and external data. N.
SP 8 Addressing internal RAM stack data_—N
Pw 8 Processor status Y
PO-P3 8 Store I/O port data Y
THO/TLO 8/8 _—_Timer/counter 0 N
THV/TL1 8/8 Timer/counter 1 N
TCON = 8—_—_Timer/counter control Y
TMOD = 8_—_Timer/eounter control N
SBUF 8 Serial port data N
SCON 8 _ Serial port control Y
PCON —-8_—_—_ Serial port control, user flags N
ie 8 Interrupt enable control Y
P 8 Interrupt priority control Y
DATA AND PROGRAM MEMORY
Internal Bytes. Function
RAM 128 RO-R7 registers, data storage, stack
ROM aK Program storage
External Bytes Function
RAM 64K Data storage
ROM 64K Program storage
EXTERNAL CONNECTION PINS
Function
Port pins 36 VO, external memory, interrupts
Oscillator 2 Clock
Power 2
Questions
Find the following using the information provided in Chapter 2.
1, Size of the internal RAM.
2, Internal ROM size in the 8031
3. Execution time of a single byte instruction for a 6 megahertz crystal.
4, The 16-bit data addressing registers and their functions.
5. Registers that can do division.
6. The flags that are stored in the PSW,
7. Which register holds the serial data interrupt bits TH and RI.
8. Address of the stack when the 8051 is reset.
9. Number of register banks and their addresses.
10. Ports used for external memory access.
1, The bits that determine timer modes and the register that holds these bits.THE 8051 ARCHITECTURE 4B
12, Address of a subroutine that handles a timer 1 interrupt.
13. Why a low-address byte latch for external memory is needed.
14, How an 1/0 pin can be both an input and output
15, Which port has no altemate functions.
16. The maximum pulse rate that can be counted on pin TI if the oscillator frequency is
6 megahertz,
7, in which registers must be set to give the serial data interrupt the highest
18. The baud rate for the serial port in mode 0 for a 6 megahertz crystal
19, The largest possible time delay for a timer in mode | if a 6 megahertz crystal is used.
20. The setting of THI, in timer mode 2, to generate a baud rate of 1200 if the serial port is
in mode | and an 11.059 megahertz crystal is in use. Find the setting for both values of
SMOD.
21, The address of the PCON special-function register.
2, ‘The time it will take a timer in mode 1 10 overflow if initially set to 03AEh with a
6 megahertz crystal.
23. Which bits in which registers must be set to 1 to have timer 0 count input pulses on pin
‘TO in timer mode 0.
24, The register containing GFO and GF.
25. ‘The signal that reads external ROM.
26. When used in multiprocessing, which bit in which register is used by a transmitting
8051 to signal receiving 8051's that an interrupt should be generated.
27. The two conditions under which program opcodes are fetched from external, rather than
internal, memory.
28, Which bits in which register(s) must be set to make INTO level activated, and INTT edge
triggered
29. ‘The address of the interrupt program for the INTO level-generated interrupt.
30. The bit address of bit 4 of RAM byte 2Ah.CHAPTER
I [
Moving Data
Chapter Outline
Introduction Data Exchanges
Addressing Modes Example Programs
External Data Moves Summary.
PUSH and POP Opcodes:
Introduction
‘A computer typically spends more time moving data from one location to another than it
spends on any other operation. It is not surprising, therefore, to find that more instructions
are provided for moving data than for any other type of operation.
Data is stored at a source address and moved (actually, the data is copied) to a desti-
nation address. The ways by which these addresses are specified are called the addressing
modes. The 8051 mnemonics are written with the destination address named first, fol-
lowed by the source address.
A detailed study of the operational codes (opcodes) of the 80511 begins in this chapter.
Although there are 28 distinct mnemonics that copy data from a source to a destination,
they may be divided into the following three main types:
1, MOV destin:
2. PUSH source or POP destination
3. XCH destination, source
mn, SOUTCE
The following four addressing modes are used to access data:
1, Immediate addressing mode
2. Register addressing modeMOVING DATA 45
3. Direct addressing mode
4, Indirect addressing mode
‘The MOV opcodes involve data transfers within the 8051 memory. This memory is
divided into the following four distinct physical parts:
1, Internal RAM
2, Internal special-function registers
3. External RAM
4, Internal and external ROM
Finally, the following five types of opcodes are used to move data:
1, Mov
2, MOVX
3. MOVC.
4, PUSH and POP
5. XCH
Addressing Modes
‘The way in which the data sources or destination addresses are specified in the mnemonic
that moves that data determines the addressing mode. Figure 3.1 diagrams the four ad-
dressing modes: immediate, register, direct, and indirect.
Immediate Addressing Mode
The simplest way to get data to a destination is to make the source of the data part of the
opcode. The data source is then immediately available as part of the instruction itself.
When the 8051 executes an immediate data move, the program counter is automat-
ically incremented to point to the byte(s) following the opcode byte in the program mem-
‘ory. Whatever data is found there is copied to the destination address.
‘The mnemonic for immediate data is the pound sign (#). Occasionally, in the rush to
meet a deadline, one forgets to use the # for immediate data, The resulting opcode is
often a legal command that is assembled with no objections by the assembler. This omis-
sion guarantees that the rush will continue.
Register Addressing Mode
Certain register names may be used as part of the opcode mnemonic as sources or destin
tions of data. Registers A, DPTR, and RO to R7 may be named as part of the opcode
mnemonic. Other registers in the 8051 may be addressed using the direct addressing
mode. Some assemblers can equate many of the direct addresses to the register name (as is
the case with the assembler discussed in this text) so that register names may be used in
lieu of register addresses. Remember that the registers used in the opcode as RO to R7 are
the ones that are currently chosen by the bank-select bits, RSO and RSI in the PSW.
The following table shows all possible MOV opcodes using immediate and register
addressing modes:AG CHAPTER THREE
Mnemonic
MOV A.#n te data byte n to the A register
MOV A.Rr Copy data from register Rr to register A
MOV Rr.A, Copy data from register A to register Rr
MOV Rr,#n Copy the immediate data byte n to register Rr
MOV DPTR,#nn Copy the immediate 16-
it number nn to the DPTR register
FIGURE 3.1 Addressing Modes
Opcode (#n) Next Byte(s) | Source Only
Instruction | Data
Immediate Addressing Mode
Opcode (Ri)
Instruction Source
Or
Destination
Data
Register Addressing Mode
Oncode (Adc)
Instruction Source
Or
Destination
[Address In Ram
Opcode (@Rp)
Source
Or
Destination
[Address In Ram ROOrRI
Data ‘Address
Indirect Addressing ModeMOVING DATA 47
‘A data MOV does not alter the contents of the data source address. A copy of the data
is made from the source and moved to the destination address. The contents of the destina-
tion address are replaced by the source address contents. The following table shows ex-
amples of MOV opcodes with immediate and register addressing modes:
Mnemonic Operation
MOV A,#0FIh Move the immediate data byte FIh to the A register
MOV A.RO Copy the data in register RO to register A
MOV DPTR.#0ABCDh Move the immediate data bytes ABCDh to the DPTR
MOV R5.A Copy the data in register A to register RS
MOV R3,#1Ch Move the immediate data byte 1Ch to register R3
—[>— cAuTION
{tis impossible to have immediate data as a destination
All numbers must start with a decimal number (0-9), or the assembler assumes the number is
a label.
Register-to-register moves using the register addressing mode occur between registers A and
RO to R7
Direct Addressing Mode
All 128 bytes of internal RAM and the SFRs may be addressed directly using the single-
byte address assigned to each RAM location and each special-function register.
Internal RAM uses addresses from 00 to 7Fh to address each byte. The SFR addresses
exist from 80h to FFh at the following locations:
SFR ADDRESS (HEX)
A £0
8 FO
PL. 82
DPH 83
Ie a8
° 088
PO 80
Pt 90
2 AO
3. 080
PCON 87
Psw = 00
sBur 99
SCON 98
sP 81
ICON 88
Tmop 89
THO 8c
TO BA
THI 8D
Tu 8B
Note the use of a leading 0 for all numbers that begin with an alphabetic (alpha) character.
RAM addresses 00 to 1Fh are also the locations assigned (o the four banks of eight
working registers, RO to R7. This assignment means that R2 of register bank 0 can be48
CHAPTER THREE
addressed in the register mode as R2 or in the direct mode as 02h. The direct addresses of
the working registers are as follows:
BANK ADDRESS BANK ADDRESS
REGISTER (HEX) REGISTER (HEX)
0 FO 00 2 RO 10
o RI 1 2 RI "
oO R2 02 2 2 2
O° RB 03 2 RB 13
oO Ra oa 2 Ra 14
oO RS 0s 2 RS 15
0 6 06 2 R6 16
oO RF o7 2 7 v7
1 RO 08 3 RO 18
1 RI 09 3 RI 19
1 R2 oA 3 R2 1A
1 RB 0B 3 RB 1B
1 Ra oc 3 RA 1c
1 RS oD 3 RS. 10
1 R6 OF 3 RE 1€
1 R7 OF 30 OR? 1
Only one bank of working registers is active at any given time. The PSW special-
function register holds the bank-select bits, RSO and RSI, which determine which register
bank is in use.
When the 8051 is reset, RSO and RS1 are set to 00b to select the working registers in
bank 0, located from 00h to O7h in internal RAM. Reset also sets SP to O7h, and the stack
will grow up as itis used. This growing stack will overwrite the register banks above bank
0. Be sure to set the SP to a number above those of any working registers the program
may use.
The programmer may choose any other bank by setting RSO and RSI as desired: this
bank change is often done to “save” one bank and choose another when servicing an
interrupt or using a subroutine.
‘The moves made possible using direct, immediate, and register addressing modes are
as follows:
Mnemonic Operation
MOV A,add Copy data from direct address add to register A
MOV add.A. Copy data from register A (o direct address add
MOV Rr,add Copy data from direct address add to register Rr
MOV add,Rr Copy data from register Rr to direct address add
MOV add,#n Copy immediate data byte n to direct address add
MOV add1,add2 Copy data from direct address add? to direct address add1
The following table shows examples of MOV opcodes using direct, immediate, and
register addressing modes:
Mnemonic ‘Operation
MOV A,80h Copy data from the port 0 pins to register A
MOV 80h,A Copy data from register A to the port 0 latch
MOV 3Ah,#3Ah Copy immediate data byte 3Ah to RAM location 3Ah
MOV RO,12h Copy data from RAM location 12h to register ROMOVING DATA 49.
MOV 8Ch,R7 Copy data from register R7 to timer 0 high byte
MOV SCh,A Copy data from register A to RAM location SCh
MOV OA8h,77h Copy data from RAM location 77h to IE register
{[>>— CAUTION
MOV instructions that refer to direct addresses above 7Fh that are not SFRS wil result in errors,
‘The SFRs are physically on the chip; all other addresses above 7Fh do not physically exist.
Moving data to a port changes the port latch; moving data from a port gets data from the
port pins,
Moving data from a direct address to itself is not predictable and could lead to errors.
Indirect Addressing Mode
For all the addressing modes covered to this point, the source or destination of the data is an
absolute number or a name. Inspection of the opcode reveals exactly what are the addresses
of the destination and source. For example, the opcode MOV A,R7 says that the A regis-
ter will get a copy of whatever data is in register R7; MOV 33h,#32h moves the hex
number 32 to hex RAM address 33.
The indirect addressing mode uses a register to hold the actual address that will
finally be used in the data move; the register itself is nor the address, but rather the number
in the register. Indirect addressing for MOV opcodes uses register RO or RI, often called
“data pointers,” to hold the address of one of the data locations, which could be a RAM
or an SFR address. The number that is in the pointing register (Rp) cannot be known un-
less the history of the register is known. The mnemonic symbol used for indirect address-
ing is the “at” sign, which is printed as @.
The moves made possible using immediate, direct, register and indirect addressing
modes are as follows:
Mnemonic Operation
MOV @Rp.#n Copy the immediate byte n to the address in Rp
MOV @Rp,add Copy the contents of add to the address in Rp
MOV @Rp,A Copy the data in A to the address in Rp
MOV add,@Rp Copy the contents of the address in Rp to add
MOV A.@Rp Copy the contents of the address in Rp to A
The following table shows examples of MOV opcodes, using immediate, register,
direct, and indirect modes
Mnemonic Operation
MOV A,@RO Copy the contents of the address in RO to the A register
MOV @R1,#35h Copy the number 3Sh to the address in RI
MOV add,@RO Copy the contents of the address in RO to add
MOV @RI.A Copy the contents of A to the address in RI
MOV @RO.80h Copy the contents of the port 0 pins to the address in RO
—[>— caution
‘The number in register Rp must be a RAM or an SFR address.
‘Only registers RO or R} may be used for indirect addressing,