0 ratings0% found this document useful (0 votes) 706 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,50 CHAPTER THREE
FIGURE 3.2 External Addressing using MOVX and MOVC
8051 I
Read T write | Read J write Read
ARegister l Data, a
Extemal Internal
ROOrR} aa coe
External
ROM
MOVX @ DPTR
ork Ey
{_movea, ga + PTR
DPTR +A
MOVE A, @A + PC
——--~-—J
External Data Moves
As discussed in Chapter 2, it is possible to expand RAM and ROM memory space by
adding external memory chips to the 8051 microcontroller. The external memory can be
as large as 64K bytes for each of the RAM and ROM memory areas. Opcodes that access
this external memory always use indirect addressing to specify the external memory.
Figure 3.2 shows that registers RO, Rl. and the aptly named DPTR can be used to
hold the address of the data byte in external RAM. RO and RI are limited to external
RAM address ranges of 00h to OFFh, while the DPTR register can address the maxi-
mum RAM space of 0000h (o OFFFFh.
‘An X is added to the MOV mnemonics to serve as a reminder that the data move is
external to the 8051, as shown in the following table.
Mnemonic Operation
MOVX A,@Rp Copy the contents of the external address in Rp to A
MOVX A,@DPTR Copy the contents of the external address in DPTR to A
MOVX @Rp.A Copy data from A to the external address in Rp
MOVX @DPTR,A Copy data from A to the external address in DPTR
The following table shows examples of external moves using register and indirect
addressing modes:
Mnemonic Operation
MOVX @DPTR,A Copy data from A to the 16-bit address in DPTR
MOVX @RO,A. Copy data from A to the 8-bit address in ROMOVING DATA 51
MOVX A.@R1 Copy data from the 8-bit address in R1 to A
MOVX A,@DPTR Copy data from the 16-bit address in DPTR to A
-[>— CAUTION
All external data moves must involve the A register.
Rp can address 256 bytes; OPTR can address 64K bytes.
MOV‘ is normally used with external RAM or 1/0 addresses.
Note that there are two sets of RAM addresses between 00 and OFFh: one internal and one
external to the 8051
Code Memory Read-Only Data Moves
Data moves between RAM locations and 8051 registers are made by using MOV and
MOVX opcodes. The data is usually of a temporary or “scratch pad” nature and disap-
pears when the system is powered down,
There are times when access to a preprogrammed mass of data is needed, such as
when using tables of predefined bytes. This data must be permanent to be of repeated use
and is stored in the program ROM using assembler directives that store programmed data
anywhere in ROM that the programmer wishes.
Access to this data is made possible by using indirect addressing and the A register in
conjunction with either the PC or the DPTR, as shown in Figure 3.2. In both cases, the
number in register A is added to the pointing register to form the address in ROM where
the desired data is to be found. The data is then fetched from the ROM address so formed
and placed in the A register. The original data in A is lost, and the addressed data takes
its place.
‘As shown in the following table, the letter C is added to the MOV mnemonic to high-
light the use of the opcodes for moving data from the source address in the Code ROM to
the A register in the 8051
Mnem Operation
MOVC A,@A+DPTR Copy the code byte, found at the ROM address formed by
adding A and the DPTR, to A
MOVC A,@A+PC Copy the code byte, found at the ROM address formed by
adding A and the PC, 10 A
Note that the DPTR and the PC are not changed; the A register contains the ROM byte
found at the address formed.
‘The following table shows examples of code ROM moves using register and indirect
addressing modes:
Mnemonic Operation
MOV DPTR,#1234h Copy the immediate number 1234h to the DPTR
MOV A,#56h Copy the immediate number __ 56h to A
MOVC A,@A+DPTR Copy the contents of address 128Ah to A
MOVC A,@A+PC Copies the contents of address 4059h to A if the PC
‘contained 4000h and A contained 58h when the opcode
is executed.52. CHAPTER THREE
-[>— CAUTION
The PC is incremented by one (to point to the next instruction) before it is added to A to form
the final address of the code byte.
All data is moved from the code memory to the A register.
MOVC is normally used with internal or external ROM and can address 4K of internal or 64K
bytes of external code,
PUSH and POP Opcodes
FIGURE 3.3
‘The PUSH and POP opcodes specify the direct address of the data. The data moves
between an area of internal RAM, known as the stack, and the specified direct address.
‘The stack pointer special-function register (SP) contains the address in RAM where data
from the source address will be PUSHed, or where data to be POPed so the destination
address is found, The SP register actually is used in the indirect addressing mode but
is not named in the mnemonic. It is implied that the SP holds the indirect address when-
ever PUSHing or POPing. Figure 3.3 shows the operation of the stack pointer as dat
PUSHed or POPed to the stack area in internal RAM.
‘A PUSH opcode copies data from the source address to the stack. SP is incremented
by one before the data is copied to the internal RAM location contained in SP so that the
data is stored from low addresses to high addresses in the internal RAM. The stack grows
up in memory as it is PUSHed. Excessive PUSHing can make the stack exceed 7Fh (the
top of internal RAM), after which point data is lost. :
‘A POP opcode copies data from the stack to the destination address. SP is decre-
mented by one afier data is copied from the stack RAM address'to the direct destination to
ensure that data placed on the stack is retrieved in the same order as it was stored.
‘The PUSH and POP opcodes behave as explained in the following table:
Mnemonic Operation
PUSH add Increment SP; copy the data in add to the internal RAM address
contained in SP
POP add Copy the data from the internal RAM address contained in SP to add:
decrement the SP
PUSH and POP the Stack
P
axe Jo Peony Y Poy #
Shei x [Pop x —| ‘SP—1 T
Push x
Peet Soe eee ‘SP-2
Ierement Before hotel Decrement after
PUSHing RAM PoPingMOVING DATA 53.
The SP register is set to 07h when the 8051 is reset, which is the same direct address
in internal RAM as register R7 in bank 0. The first PUSH opcode would write data to RO
of bank 1. The SP should be initialized by the programmer to point to an internal RAM
address above the highest address likely to be used by the program.
‘The following table shows examples of PUSH and POP opcodes:
Mnemonic Operation
MOV 81h,#30h Copy the immediate data 30h to the SP
MOV RO, #0ACh Copy the immediate data ACh to RO
PUSH 00h SP = 31h; address 31h contains the number ACh
PUSH 00h SP = 32h; address 32h contains the number ACh
POP OIh SI 31h; register RI now contains the number ACh
POP 80h SP = 30h; port 0 latch now contains the number ACh
{ CAUTION
When the SP reaches FFh it “rolls over” to 00h (RO).
RAM ends at address 7Fh; PUSHes above 7Fh result in errors,
The SP is usually set at addresses above the register banks.
The SP may be PUSHed and POPed to the stack.
Note that direct addresses, not register names, must be used for most registers. The stack
mnemonics have no way of knowing which bank is in use.
Data Exchanges
MOV, PUSH, and POP opcodes all involve copying the data found in the source address to
the destination address; the original data in the source is not changed. Exchange instruc
tions actually move data in two directions: from source to destination and from destination
to source. All addressing modes except immediate may be used in the XCH (exchange)
opcodes:
Mnemonic Operation
XCH ARr Exchange data bytes between register Rr and A
XCH A,add Exchange data bytes between add and A
XCH A.@Rp Exchange data bytes between A and address in Rp
XCHD A,@Rp Exchange lower nibble between A and address in Rp
Exchanges between A and any port location copy the data on the port pins to A, while
the data in A is copied to the port latch. Register A is used for so many instructions that
the XCH opcode provides a very convenient way to “save” the contents of A without the
necessity of using a PUSH opcode and then a POP opcode.
‘The following table shows examples of data moves using exchange opcodes:
Mnemonic Operation
XCH A,R7 Exchange bytes between register A and register R7
XCH A,OFOh Exchange bytes between register A and register B
XCH A,@RI Exchange bytes between register A and address in RI
XCHD A,@RI_—_ Exchange lower nibble in A and the address in RI54
(CHAPTER THREE
CAUTION
All exchanges are interna to the 8051
‘All exchanges use register A.
‘When using XCHD, the upper nibble of A and the upper nibble of the address location in Rp do
not change.
This section concludes the listing of the various data moving instructions; the remain-
ing sections will concentrate on using these opcodes to write short programs.
Example Programs
Programming is at once a skill and an art. Just as anyone may learn to play a musical
instrument after sufficient instruction and practice, so may anyone learn to program a
computer, Some individuals, however, have @ gift for programming that sets them apart
from their peers with the same level of experience, just as some musicians are more tal-
ented than their contemporaries.
Gifted or not, you will not become adept at programming until you have written and
rewritten many programs. The emphasis here is on practice: you can read many books on
how to ride a bicycle, but you do not know how to ride until you do it
If some of the examples and problems seem trivial or without any “real-world” appli-
cation, remember the playing of scales on a piano by a budding musician. Each example
will be done using several methods; the best method depends upon what resource is in
short supply. If programming time is valuable, then the best program is the one that uses
the fewest Tines of code; if either ROM or execution time is limited, then the program that
uses the fewest code bytes is best
[__] exapce pRoBLeM 3.1
Copy the byte in TCON to register R2 using at least four different methods.
Method 1: Use the direct address for TCON (88h) and register R2.
Mnemonic Operation
MOV R2,88h Copy TCON to R2
© Method 2: Use the direct addresses for TCON and R2.
Mnemonic ‘Operation
MOV 02h,88h, Copy TCON to direct address 02h (R2)
© Method 3: Use Ri as a pointer to R2 and use the address of TCON.
Mnemonic Operation
MOV R1.#02h Use RI as a pointer to R2
MOV @RI.88h Copy TCON byte to address in R1 (02h = R2)
© Method 4: Push the contents of TCON into direct address 02h (R2).
Mnemonie Operation
MOV 81h,#01h Set the SP to address Oth in RAM
PUSH 88h Push TCON (88h) to address 02h (R2)MOVING DATA 5S.
EXAMPLE PROBLEM 3.2
Set timer TO to an initial setting of 1234h.
= Method 1: Use the direct address with an immediate number to set THO and TLO.
Mnemonic Operation
MOV 8Ch,#12h Set THO to 12h
MOV 8Ah,#34h Set TLO to 34h
Totals: 6 bytes, 2 lines
© Method 2: Use indirect addressing with RO for TLO and R1 for THO.
Mnemonic Operation
MOV RO.#8Ah Copy 8Ah, the direct address of TLO, to RO
MOV RI,#8Ch Copy 8Ch, the direct address of THO, to RI
MOV @RO,#34h Copy 34h to TLO
MOV @R1,#12h Copy 12h to THO
Totals: 8 bytes, 4 lines
‘The first method is also the better method in this example,
EXAMPLE PROBLEM 3.3
Put the number 34h in registers RS. R6, and R7.
= Method 1; Use an immediate number and register addressing.
Mnemonic Operation
MOV R5,#34h Copy 34h to RS
MOV R6,#34h Copy 34h to RO
MOV R7,#34h Copy 34h to R7
Totals: 6 bytes, 3 lines
= Method 2: Since the number is the same for each register, put the number in A and
MOV A to each register.
Mnemonic Operation
MOV A.#34h Copy a 34h 0A
MOV RSA Copy A to RS
MOV R6,A Copy A to R6
MOV R7,A Copy A to R7
Totals: 5 bytes, 4 lines
© Method 3: Copy one direct address to another.
Mnemonic Operation
MOV RS.#34h Copy 34h to register RS
MOV 06h,05h Copy RS (add 05) to R6 (add 06)
MOV 07h,06h Copy R6 10 R7
Totals: 8 bytes, 3 lines56 CHAPTER THREE
Summary
EXAMPLE PROBLEM 3.4
Put the number 8Dh in RAM locations 30h to 34h.
= Method 1: Use the immediate number to a direct address:
Mnemonic ‘Operation
MOV 30h,#8Dh Copy the number 8Dh to RAM address 30h
MOV 31h.#8Dh Copy the number 8Dh to RAM address 31h
MOV 32h,#8Dh Copy the number 8Dh to RAM address 32h
MOV 33h,#8Dh Copy the number 8Dh to RAM address 33h
MOV 34h,#8Dh Copy the number 8Dh to RAM address 34h
Totals: 15 bytes, 5 lines
© Method 2: Using the immediate number in each instruction uses bytes; use a register 10
hold the number:
Mnemonic Operation
MOV A.#8Db ‘Copy the number 8Dh to the A register
MOV 30h.A Copy the contents of A to RAM location 30h,
MOV 31h, ‘Copy the contents of A to the remaining addresses
MOV 32h,
MOV 33h,
MOV 34h.A Totals: 12 bytes, 6 lines
= Method 3: There must be a way to avoid naming each address: the PUSH opcode can
increment to each address:
Mnemonic Operation
MOV 30h,#8Dh Copy the number 8Dh to RAM address 30h,
MOV 81h,#30h Set the SP 10 30h
PUSH 30h Push the contents of 30h (=8Dh) to address 31h
PUSH 30h Continue pushing to address 34h
PUSH 30h
PUSH 30h Totals: 14 bytes, 6 lines
—C>— comment
Indirect addressing with the number in A and the indirect address in R1 could be done; how-
ever, R1 would have to be loaded with each address from 30h to 34h. Loading R1 would take
2 total of 17 bytes and 11 fines of code. Indirect addressing is advantageous when we have
‘opcodes that can change the contents of the pointing registers automatically.
‘The opcodes that move data between locations within the 8051 and between the 8051 and
external memory have been discussed. The general form and results of these instructions
are as follows.
Instruction Type Result
MOV destination,source Copy data from the internal RAM source address to the
internal RAM destination addressMOVING DATA 57
MOVC A.source Copy internal or external program memory byte from the
source to register A
MOVX destination,source Copy byte to or from external RAM to register A
PUSH source Copy byte (o internal RAM stack from internal RAM
source,
POP destination Copy byte from internal RAM stack to internal RAM
. destination
XCH A, source Exchange data between register A and the internal RAM.
source
XCHD A. source Exchange lower nibble between register A and the
internal RAM source .
There are four addressing modes: an immediate number, a register name, a direct
internal RAM address, and an indirect address contained in a register.
Problems
Write programs that will accomplish the desired tasks listed below, using as few lines of
code as possible. Use only opcodes that have been covered up to this chapter. Comment
on each line of code
1, Place the number 3Bh in internal RAM locations 30h to 32h.
2. Copy the data at internal RAM location F1h to RO and R3.
3. Set the SP at the byte address just above the last working register address.
4, Exchange the contents of the SP and the PSW.
5. Copy the byte at internal RAM address 27h to external RAM address 27h.
6. Set Timer 1 to A23Dh.
7. Copy the contents of DPTR to registers RO (DPL) and Ri (DPH).
8. Copy the data in external RAM location 0123h to TLO and the data in external RAM
location 0234h to THO.
9. Copy the data in internal RAM locations 12h to 15h to internal RAM locations 20h to
23h: Copy 12h to 20h, 13h to 2th, etc.
10. Set the SP register to 07h and PUSH the SP register on the stack; predict what number is
PUSHed to address O8h.
11. Exchange the contents of the B register and external RAM address 02CFh.
12, Rotate the bytes in registers RO to R3; copy the data in RO to RI, RI to R2, R2 to R3,
and R3 t0 RO.
13, Copy the external code byte at address 007Dh to the SP.
14, Copy the data in register RS to external RAM address 032Fh.
1S. Copy the internal code byte at address 0300h to external RAM address 0300h.
16. Swap the bytes imer Q, put TLO in THO and THO in TLO.
17. Store DPTR in external RAM locations 0123h (DPL) and 02BCh (DPH).
48, Exchange both low nibbles of registers RO and R1: put the low nibblé of RO in RI, and
the tow nibble of RI in RO.58
CHAPTER THREE
19. Store the contents of register R3 at the internal RAM address contained in R2. (Be sure
the address in R2 is legal.)
20, Store the contents of RAM location 20h at the address contained in RAM location O8h.
21. Store register A at the internal RAM location address in register A.
22. Copy program bytes 0100h to 0102h to internal RAM locations 20h to 22h
23. Copy the data on the pins of port 2 to the port 2 latch.
24, PUSH the contents of the B register to TMOD.
25. Copy the contents of external code memory address 0040h to IE.
26, Show that a set of XCH instructions executes faster than a PUSH and POP when saving
the contents of the A register.CHAPTER
ple
Als
Logical Operations
Chapter Outline
Introduction Rotate and Swap Operations
Byte-Level Logical Operations Example Programs
Bit-Level Logical Operations Summary
Introduction
59
‘One application area the 8051 is designed to fill is that of machine control. A large part of
machine control concerns sensing the on-off states of external switches, making deci-
ns based on the switch states, and then turning external circuits on or off.
Single point sensing and control implies a need for byte and bir opcodes that operate
‘on data using Boolean operators. All 8051 RAM areas, both data and SFRs, may be ma-
nipulated using byte opcodes. Many of the SFRs, and a unique internal RAM area that is
bit addressable, may be operated upon at the individual bit level. Bit operators are notably
efficient when speed of response is needed. Bit operators yield compact program code that
enhances program execution speed.
‘The two data levels, byte or bit, at which the Boolean instructions operate are shown
in the following table:
BOOLEAN OPERATOR 8051 MNEMONIC
AND ANL (AND logical)
oR ‘ORL (OR logical)
XOR XRL (exclusive OR logical)
NoT CPL (complement)
There are also rotate opcodes that operate only on a byte, or a byte and the carry flag,
to permit limited 8- and 9-bit shift-register operations. The following table shows the
rotate opcodes:60 CHAPTER FOUR
Mnemonic
RL
RLC
RR
RRC
SWAP
Operation
Rotate a byte to the left: the Most Significant Bit (MSB) becomes the
Least Significant Bit (LSB)
Rotate a byte and the carry bit left; the carry becomes the LSB, the
MSB becomes the carry
Rotate a byte to the right; the LSB becomes the MSB
Kotate a byte and the carry to the right; the LSB becomes the carry, and
the carry the MSB
Exchange the low and high nibbles in a byte
Byte-Level Logical Operations
The byte-level logical operations use all faur addressing modes for the source of a data
byte. The A register or a direct address in internal RAM is the destination of the logical
‘operation result.
Keep in mind that all such operations are done using each individual bit of the desti-
nation and source bytes. These operations, called byte-level Boolean operations because
tife entire byte is affected, are listed in the following table:
Mnemonic
ANL A,#n
ANL, A.add
ANL A,Rr
ANL A\@Rp
ANL add,A
ANL add.#n
ORL A,#n
ORL A,add
ORL A.Rr
ORL A.@Rp
ORL add,A
ORL add,#n
XRL A,#n
XRL A,add
XRL A,Rr
XRL A.@Rp
XRL add.A
Operation
AND each bit of A with the same bit of immediate number n; put the
results in A
AND each bit of A with the same bit of the direct RAM address; put
the results in A
AND each bit of A with the same bit of register Rr: put the results in A
AND each bit of A with the same bit of the contents of the RAM
address contained in Rp; put the results in A
AND each bit of A with the direct RAM address: put the results in
the direct RAM address
AND each bit of the RAM address with the same bit in the number n;
put the result in the RAM address
OR each bit of A with the same bit of n; put the results in A
OR each bit of A with the same bit of the direct RAM address: put
the results in A
OR each bit of A with the same bit of register Rr: put the result
OR each bit of A with the same bit of the contents of the RAM
address contained in Rp; put the results in A
OR each bit of A with the direct RAM address; put the results in the
direct RAM address
OR each bit of the RAM address with the same bit in the number n:
put the result in the RAM address
XOR each bit of A with the same bit of n; put the results in A
XOR each bit of A with the same bit of the direct RAM address; put
the results in A
XOR each bit of A with the same bit of register Rr; put the results in A
XOR each bit of A with the same bit of the contents of the RAM
address contained in Rp; put the results in A.
XOR each bit of A with the direct RAM address; put the results in the
direct RAM address
ALOGICAL OPERATIONS «61
XRL add.#n —_XOR each bit of the RAM address with the same bit in the number n:
put the result in the RAM address
CLRA Clear each bit of the A register to zero
CPLA ‘Complement each bit of A; every I becomes a0, and each 0 becomes
al
Note that no flags are affected unless the direct RAM address is the PSW.
Many of these byte-level operations use a direct address, which can include the port
SFR addresses, as a destination. The normal source of data from a port is the port pins; the
‘normal destination for port data is the port latch. When the destination of a logical opera-
tion is the direct address of a port, the latch register, not the pins, is used both as the
source for the original data and then the destination for the altered byte of data. Any port
‘operation that must first read the source data, logically operate on it, and then write it
back to the source (now the destination) must use the larch. Logical operations that use the
port as a source, but nor as a destination, use the pins of the port as the source of the data
For example, the port 0 latch contains FFh, but the pins are all driving transistor
bases and are close to ground level. The logical operation
ANL PO,#0Fh
which is designed to turn the upper nibble transistors off, reads FFh from the latch, ANDs
it with OFh to produce OFh as a result, and then writes it back to the latch to turn these
transistors off. Reading the pins produces the result 0h, turning all transistors off, in
error. But, the operation
ANL APO
produces A = 00h by using the port 0 pin data, which is OOh.
‘The following table shows byte-level logical operation examples:
Mnemonic Operation
MOV A.#0FFh =A = FFh
MOV RO.#77h = RO= 77h
NL A,RO A=7Th
MOV [5h,A 15h = 77h
cPLA A = 88h
ORL 15h,#88h 15h = FFh
XRL A,15h A= 77h
XRL A,RO A= 00h
ANL A,15h A = 00h
ORL A,RO
CLRA
XRL ISh,A
XRL ARO
Note that instructions that can use the SFR port latches as destinations are ANL, ORL,
and XRL.
{[>— CAUTION
If the direct address destination is one of the port SFRs, the data latched in the SFR, not the pin
data, is used.
No flags are affected unless the direct address is the PSW.
Only internal RAM or SERS may be logically manipulated.62
CHAPTER FOUR
Bit-Level Logical Operations
Certain internal RAM and SFRs can be addressed by their byte addresses or by the address,
of each bit within a byte. Bit addressing is very convenient when you wish to alter a single
bit of a byte, in a control register for instance, without having to wonder what you need to
ddo to avoid altering some other crucial bit of the same byte. The assembler can also equate
bit addresses to labels that make the program more readable, For example, bit 4 of TCON
can become TRO, a label for the timer O run bit.
The ability to operate on individual bits creates the need for an area of RAM that
contains data addresses that hold a single bit, Internal RAM byte addresses 20h to 2Fh
serve this need and are both byte and bit addressable. The bit addresses are numbered
from 00h to 7Fh to represent the 128d bit addresses (16d bytes X 8 bits) that exist from
byte addresses 20h to 2Fh. Bit 0 of byte address 20h is bit address 00h, and bit 7 of byte
‘address 2Fh is bit address 7Fh. You must know your bits from your bytes to take advan-
tage of this RAM area.
Internal RAM Bit Addresses
‘The availability of individual bit addresses in internal RAM makes the use of the RAM
very efficient when storing bit information. Whole bytes do not have to be used up to store
one o two bits of data.
‘The correspondence between byte and bit addresses are shown in the following table:
BYTE ADDRESS (HEX) —_ BIT ADDRESSES (HEX)
20 00-07
2 0g—oF
22 10-17
23 18-1F
24 20-27
25 28..2F
26 30-37
27 38-3F
28 40-47
29 Agar
2A 50-57
28 58—5F
2c 60-67
2D 68_6F
2E 70-77
2 78-7F
Interpolation of this table shows, for example, the address of bit 3 of internal RAM byte
address 2Ch is 63h, the bit address of bit S of RAM address 21h is ODh, and bit address
47h is bit 7 of RAM byte address 28h.
‘SFR Bit Addresses
All SFRs may be addressed at the byte level by using the direct address assigned to it, but
not all of the SFRs are addressable at the bit level. The SFRs that are also bit addressable
form the bit address by using the five most significant bits of the direct address for that
SFR, together with the three least significant bits that identify the bit position from posi-
tion 0 (LSB) to 7 (MSB).LOGICAL OPERATIONS «6.
The bit-addressable SFR and the corresponding bit addresses are as follows:
SFR DIRECT ADDRESS (HEX) —_ BIT ADDRESSES (HEX)
A 0e0 00-087
8 OF ‘OFO~0F7
te OAB OA8—OAF
P 088. 0B8_08F
°0 80 80-87
al 90 90-97
°2 0A0 ‘0A0-0A7
P3 080 ‘080-087
Psw = 0D0 0D0-007
ICON 88 88-8F
SCON 98 98—9F
‘The patterns in this table show the direct addresses assigned to the SFR bytes all have
bits 0-3 equal to zero so that the address of the byte is also the address of the LSB. For
example, bit OE3h is bit 3 of the A register. The carry flag, which is bit 7 of the PSW, is
bit addressable as OD7h. The assembler can also “understand” more descriptive mne-
monics, such as PO.5 for bit 5 of port 0, which is more formally addressed as 85h.
Figure 4.1 shows all the bit-addressable SFRs and the function of each addressable
bit. (Refer to Chapter 2 for more detailed descriptions of the SFR bit functions.)
Bit-Level Boolean Operations
The bit-level Boolean logical opcodes operate on any addressable RAM or SFR bit.
‘The carry flag (C) in the PSW special-function register is the destination for most of the
‘opcodes because the flag can be tested and the program flow changed using instructions
covered in Chapter 6.
‘The following table lists the Boolean bit-level operations.
Mnemonic Operation
ANL Cb AND C and the addressed bit; put the result in
ANL C,/b AND C and the complement of the addressed bit; put the result in C: the
addressed bit is not altered
ORLC,b ORC and the addressed bi
ORLC./b OR C and the complement of the addressed bit: put the result in C; the
addressed bit is not altered
cPLC ‘Complement the C flag
CPL b Complement the addressed bit
CLRC Clear the C flag to zero
CLR b Clear the addressed bit to zero
MOV Cb Copy the addressed bit to the C flag
MOV b,C Copy the C flag to the addressed bit
SETBC Set the flag to one
SETB b Set the addressed bit to one
Note that no flags, other than the C flag, are affected, unless the flag is an addressed bit.
As is the case for byte-logical operations when addressing ports as destinations, a
port bit used as a destination for a logical operation is part of the SFR latch, not the pin. A
port bit used as a source only is a pin, not the latch. The bit instructions that can use
a SFR latch bit are: CLR, CPL, MOV, and SETB.64 CHAPTER FOUR
FIGURES 4.1 _Bit-Addressable Control Registers
7
6 5 4 3 2
cy
ac | Fo | Rs
vo |
Reserved
PROGRAM STATUS WORD (PSW) SPECIAL FUNCTION REGISTER. BIT ADDRESSES DOh to D7h.
Bit
O-Nwauay
7
Function
Carry flag
Auxiliary carry flag
User flag 0
Register bank select bit 1
Register bank select bit 0
Overflow flag
Not used (reserved for future)
Parity flag
6 5 4 a 2
ER
mofo] # [|e
ETO
bo
INTERRUPT ENABLE (IE) SPECIAL FUNCTION REGISTER. BIT ADDRESSES A8h TO AFh.
Bit
OaNunuas
Function
Disables all interrupts
Not used (reserved for future)
Not used (reserved for future)
Serial port interrupt enable
Timer 1 overflow interrupt enable
External interrupt 1 enable
Timer 0 interrupt enable
External interrupt 0 enable
EA disables all interrupts when cleared to 0; if EA = 1 then each individual interrupt will be enabled if 1, and
disabled if 0.
6 5 4 3 2
1
0
+ Reserved!
PTO
PxO,
INTERRUPT PRIORITY (IP) SPECIAL FUNCTION REGISTER. BIT ADDRESSES B8h to BFh,
Bit
7
6
Function
Not implemented
Not implemented
ContinuedBit
e-Nwaw
LOGICALOPERATIONS «65
Function
‘Not used (reserved for future)
Serial port interrupt priority
Timer 1 interrupt priority
External interrupt 1 priority
Timer 0 interrupt priority
External interrupt 0 priority
‘The priority bit may be set to 1 (highest) or 0 lowest).
7
6 5
TFL
tri | FO teo | 110
a3
wo [ot [mi
TIMER/COUNTER CONTROL (TCON) SPECIAL FUNCTION REGISTER. BIT ADDRESSES 88h to 8Fh.
Bit Function
7 Timer 1 overflow flag
6 Timer run control
5 Timer 0 overflow flag
4 Timer 0 run control
3 External interrupt 1 edge flag
2 External interrupt 1 mode control
1 External interrupt 0 edge flag
09 External interrupt 0 mode control
All flags can be set by the indicated hardware action; the flags are cleared when interrupt is serviced by
the processor.
7 6 5 4 3 2 1 o
SERIAL PORT CONTROL (SCON) SPECIAL FUNCTION REGISTER. BIT ADDRESSES 98h to 9Fh.
Bit
eonNwauan
Function
Serial port mode bit 0
Serial port mode bit 1
Multiprocessor communications enable
Receive enable
Transmitted bit in modes 2 and 3
Received bit in modes 2 and 3
Transmit interrupt flag
Receive interrupt flag66 ‘CHAPTER FOUR
Bit-level logical operation examples are shown in the following table:
Mnemonic Operation
SETB 00h Bit 0 of RAM byte 20h = 1
MOVC.00h C=1
MOV 7Fh,C Bit 7 of RAM byte 2Fh
ANL C/00h bit 0 of RAM byte 20h = 1
ORL C.00h
CPL 7Fh Bit 7 of RAM byte 2Fn = 0
CLRC c=o
ORL C,/7Fh C= 1; bit 7 of RAM byte 2Fh = 0
—-{ CAUTION
Only the SFRs that have been identified as bit addressable may be used in bit operations
if the destination bit is a port bit, the SFR latch bit is affected, not the pin.
ANL C,/b and ORL C,/b do not alter the addressed bit b.
Rotate and Swap Operations
The ability to rotate data is useful for inspecting bits of a byte without using individual bit
opcodes. The A register can be rotated one bit position to the left or right with or without
including the C flag in the rotation. If the C flag is not included, then the rotation involves
the eight bits of the A register. If the C flag is included, then nine bits are involved in the
rotation, Including the C flag enables the programmer to construct rotate operations in-
volving any number of bytes.
‘The SWAP instruction can be thought of as a rotation of nibbles in the A register.
Figure 4.2 diagrams the rotate and swap operations. which are given in the following table:
Mnemonic Operation
RLA Rotate the A register one bit position to the left; bit AO to bit Al, Al to
A2, A2 to A3, A3 to A4, A4 to AS, AS to A6, A6 to A7, and A7 to AO.
RLCA Rotate the A register and the carry flag. as a ninth bit, one bit position to
the left; bit AO to bit Al, Al to A2, A2 to A3, A3 to Ad, A4 to AS,
AS 10 AG, A6 to A7, A7 to the carry flag, and the carry flag to AO
RRA Rotate the A register one bit position to the right; bit AO to bit A7, A6 to
AS, AS to A4, Ad to A3, A3 to A2, A2 to Al, and Al to AO
RRCA Rotate the A register and the carry flag, as a ninth bit, one bit position to
the right: bit AO to the carry flag, carry flag t0 A7, A7 to A6, A6 to
AS, AS to Ad, A4 to A3, A3 to A2, A2to Al, and Al to AO
SWAP A Interchange the nibbles of register A: put the high nibble in the low nibble
position and the low nibble in the high nibble position
Note that no flags, other than the carry flag in RRC and RLC, are affected. If the carry is
used as part of a rotate instruction, the state of the carry flag should be known before the
rotate is done.LOGICAL OPERATIONS «67
FIGURE 4.2 Register A Rotate Operations
eer ee
cary Flag
RLA
RRA
Carry Flag,
7.6 5 4 3 2 1 +0
‘SWAP A
‘The foltowing table shows examples of rotate and swap operations:
Mnemonic
MOV A.#0ASh
RRA
RRA
RRA
RRA
SWAP A
CLRC
RRCA
RRCA
RLA
RLA
Operation
A = 101001016 = ASh
110100106 = D2h
O1IO1001b = 69h
C = 0; A = 10100101b = ASh
1010010b = 52h
}0101001b = Adh
O1010011b = 53h
10100110b = A6h68
+f
‘CHAPTER FOUR,
SWAP A 011010100
RLCA : A = 11010100b = Dah
RLCA A = 10101000b = A8h
SWAP A 100010106
CAUTION
Know the state of the carry flag when using RRC or RRL.
Rotation and swap operations are limited to the A register
Example Programs
The programs in this section are written using only opcodes covered to this point in the
text, The challenge is to minimize the number of lines of code.
EXAMPLE PROBLEM 4.1
Double the number in register R2, and put the result in registers R3 (high byte) and Rd
(ow byte),
= Thoughts on the Problem The largest number in R2 is FFh; the largest result is 1FEh.
There are at least three ways to solve this problem: Use the MUL instruction (multiply,
covered in Chapter 5). add R2 to itself, or shift R2 left one time. The solution that shifts
R2 left is as follows:
Mnemonic Operation
MOV R3.#00h Clear R3 to receive high byte
CLRC Clear the carry to receive high bit of 2% R2
MOV A.R2 Get R20 A
RLCA Rotate left, which doubles the number in A
MOV R4,A Put low byte of result in R4
CLRA Clear A to receive carry
RLCA ‘The carry bit is now bit 0 of A
MOV R3.4 Transfer any carry bit to R3
—[>— COMMENT
Note how the carry flag has to be cleared to a known state before being used in a rotate
operation,
EXAMPLE PROBLEM 4.2
OR the contents of ports | and 2; put the result in external RAM location 0100h,
«= Thoughts on the Problem The ports should be input ports for this problem to make any
physical sense; otherwise, we would not know whether to use the pin data or the port SFR
latch data.
‘The solution is as follows:
Mnemonic Operation
MOV A,90h Copy the pin data from port I to A.
ORL A,OAOh OR the contents of A with port 2: results in A.
MOV DPTR,#0100h Set the DPTR to point to external RAM address
MOVX @DPTR,A Store the resultSummary
LOGICAL OPERATIONS, 69
—{>— comment
Any time the port is the source of data, the pin levels are read: when the port is the destination,
the latch is written. If the port is both source and destination (read-modify—write instruc
tions), then the latch is used.
EXAMPLE PROBLEM 4.3
Find a number that, when XORed to the A register, results in the number 3Fh in A.
= Thoughts on the Problem Any number can be in A, so we will work backwards:
3Fh = AXORN A XOR 3Fh = AXOR AXORN=N
The solution is as follows:
Mnemonic Operation
MOV RO,A, Save A in RO
XOR A.#3Fh —-XOR A and 3Fh; forming N
XOR A,RO XOR A and N yielding 3Fh
[>— COMMENT
Does this program work? Let's try several A’s and see.
A= FFh A XOR 3Fh = COh COh XOR FFh = 3Fh
A=00h A XOR3Fh=3Fh —3Fh XOR 00h = 3Fh
Ah A XOR 3Fh = 65h 65h XOR SAh = 3Fh
Boolean logic, rotate, and swap instructions are covered in this chapter. Byte-level opera-
tions involve each individual bit of a source byte operating on the same bit position in the
destination byte; the results are put in the destination, while the source is not changed:
ANL destination source
ORL destination,source
XRL destination, source
CLRA
CPLA
RRA
RLA
RRCA
RLCA
SWAP A
Bit-level operations involve individual bits found in one area of internal RAM and
certain SFRs that may be addressed both by the assigned direct-byte address and eight
individual bit addresses. The following Boolean logical operations may be done on each
of these addressable bit
ANL bit
ORL bit70
CHAPTER FOUR
CLR bit
CPL bit
SETB bit
MOV destination bit, source bit
Problems
Write programs that perform the tasks listed using only opcodes that have been discussed
in this and previous chapters. Write comments for each line of code and try to use as few
fines as possible.
1, Set Port 0. bits 1.3.5, and 7. to one: set the rest to zero.
2. Clear bit 3 of RAM location 22h
13. Invert the data on the port 0 pins and write the data to port |
4. Swap the nibbles of RO and R1 so that the low nibble of RO swaps with the high nibble
OF RI and the high nibble of RO swaps with the low nibble of RI
. Complement the lower nibble of RAM location 2Ah.
Make the low nibble of RS the complement of the high nibble of R6.
7, Make the high nibble of RS the complement of the low nibble of R6,
8. Move bit 6 of RO to bit 3 of port 3
9. Move bit 4 of RAM location 30h to bit 2 of A
10. XOR a number with whatever is in A so that the result is FFh.
ithout affecting any other bit.
aw
11, Store the most significant nibble of A in both nibbles of register RS; for example. if
A= Boh, then RS = BBh.
12, Store the least significant nibble of A in both nibbles of RAM address 3Ch; for example.
if A = 36h. then 3Ch = 66h.
13, Set the carry flag to one if the number in A is even: set the carry flag to zero if the
number in A is odd.
14, Treat registers RO and R1 as 16-bit registers, and rotate them one place to the left: bit 7
of RO becomes bit O of RI. bit 7 of RI becomes bit 0 of RO, and so on,
15, Repeat Problem 14 bat rotate the registers one place to the right.
16, Rotate the DPTR one place to the left; bit 15 becomes bit 0.
17, Repeat problem 16 but rotate the DPTR one place to the right.
18. Shift register B one place to the left: bit O becomes a zero. bit 6 becomes bit 7. and so
on. Bit 7 is lost,CHAPTER
I I
Si
Arithmetic Operations
Chapter Outline
Introduction Multiplication and Division
Flags Decimal Arithmetic
Incrementing and Decrementing Example Programs
Addition summary
Subtraction
Introduction
n
Applications of microcontrollers often involve performing mathematical calculations on
data in order to alter program flow and modify program actions. A microcontroller is not
designed to be a "number cruncher.” as is a general-purpose computer. The domain of the
microcontroller is that of controlling events as they change (real-time control). A suffi-
cient number of mathematical opcodes must be provided, however, so that calculations
associated with the control of simple processes can be done, in real time, as the controlled
system operates. When faced with a control problem. the programmer must know whether
the 8051 has sufficient capability to expeditiously handle the required data manipulation.
If it does not, a higher performance mode! must be chosen.
‘The 24 arithmetic opcodes are grouped into the following types:
Mnemonic Operation
INC destination Increment destination by 1
DEC destination Decrement destination by 1
ADD/ADDC destination,source Add source 10 destination without/with carry (C)
flag
SUBB destination,source Subtract, with carry, source from destination
MUL AB Multiply the contents of registers A and B2
Flags
CHAPTER FIVE
DIV AB Divide the contents of register A by the contents of
register B
DAA Decimal Adjust the A register
‘The addressing modes for the destination and source are the same as those discussed in
Chapter 3: immediate, register, direct, and indirect.
‘A key part of performing arithmetic operations is the ability to store certain results of
those operations that affect the way in which the program operates. For example, adding
together two one-byte numbers results in a one-byte partial sum, because the 8051 is and
ight-bit machine. But it is possible to get a 9-bit result when adding two 8-bit numbers.
‘The ninth bit must be stored also, so the need for a one-bit register, or carry flag in this
‘case, is identified. The program will then have to deal with the ninth bit, perhaps by
adding it to a higher order byte in a multiple-byte addition scheme. Similar actions may
hhave to be taken when a larger byte is subtracted from a smaller one. In this case, a borrow
is necessary and must be dealt with by the program.
‘The 8051 has several dedicated latches, or flags, that store results of arithmetic opera-
tions. Opcodes covered in Chapter 6 are available to alter program flow based upon the
state of the flags. Not all instructions change the flags, but many a programming error has
been made by a forgetful programmer who overlooked an instruction that does change
a flag
The 8051 has four arithmetic Rags: the carry (C), auxiliary carry (AC), overflow (OV),
and parity (P).
Instructions Affecting Flags
‘The C. AC, and OV flags are arithmetic flags. They are set to | or cleared to 0 automat-
ically, depending upon the outcomes of the following instructions. The following instruc-
tion set includes alf instructions that modify the flags and is not confined to arithmetic
instructions
INSTRUCTION MNEMONIC FLAGS AFFECTED
ADD c AC ov
‘ADDC c AC Ov
ANL C.direct c
CINE c
CRC c
CPHL c
DAA c
ow c=0 ov
c
c
c
c
c
c
c
MOV C.direct
MUL
ORL C.direct
REC
RRC
SeTB.C
suBs
AC Ov
‘One should remember, however, that the flags are all stored in the PSW. Aiyy instruc-
tion that can modify a bit or a byte in that register (MOV, SETB, XCH, etc.) changes the
flags. This type of change takes conscious effort on the part of the programmer.ARITHMETIC OPERATIONS 73
‘A flag may be used for more than one type of result. For example, the C flag indicates
a carry out of the lower byte position during addition and indicates a borrow during sub-
traction. The instruction that last affects a flag determines the use of that flag,
‘The parity flag is affected by every instruction executed. The P flag will be set to at
if the number of 1's in the A register is odd and will be set to 0 if the number of 1's is even.
AIL 0's in A yield a I's count of 0, which is considered to be even. Parity check is an
clementary error-checking method and is particularly valuable when checking data re-
ceived via the seriat port
incrementing and Decrementing
The simplest arithmetic operations involve adding or subtracting a binary 1 and a number.
These simple operations become very powerful when coupled with the ability to repeat the
‘operation—that is, to “INCrement” or “DECrement”—until a desired result is reached.
Register, Direct, and Indirect addresses may be INCremented or DECremented. No math
flags (C. AC, OV) are affected.
The following table lists the increment and decrement mnemonics.
Mnemonic Operation
INCA ‘Add a one to the A register
INC Rr Add a one to register Rr
INC add Add a one to the direct address
INC @ Rp ‘Add a one to the contents of the address in Rp
INC DPTR ‘Add a one to the 16-bit DPTR
DEC A ‘Subtract a one from register A
DEC Rr Subtract a one from register Rr
DEC add ‘Subtract a one from the contents of the direct address
DEC @ Rp Subtract a one from the contents of the address in register Rp
Note that increment and decrement instructions that operate on a port direct address alter
the latch for that port.
The following table shows examples of increment and decrement arithmetic
operations:
Mnemonic Operation
MOV A,#3Ah A= 3Ah
DEC A A= 39h
MOV RO,#15h RO = 15h
MOV 15h,#12h Internal RAM address [5h = 12h
INC @RO Internal RAM address 15h = 13h
DEC 15h Internal RAM address 15h = 12h
INC RO RO = 16h
MOV 16h,A Internal RAM address 16h = 39h
INC @RO Internal RAM address 16h = 3Ah
MOV DPTR,#12FFh PTR = 12FFh
INC DPTR 1300h
DEC 83h 1200h (SFR 83h is the DPH byte)
‘This subject will be explored in Chapter 6.7A CHAPTER FIVE
[> CAUTION
Addition
Remember: No math flags are affected,
All bit address contents overtiow from FFh £0 00h
DPTR is 16 bits; DPTR overflows from FFFFh to 0000h.
The 8-bit address contents underflow from 00h to FFh.
There is no DEC DPTR to match the INC DPTR.
All addition is done with the A register as the destination of the result. All addressing
modes may be used for the source: an immediate number, a register, a direct address, and
an indirect address. Some instructions include the carry flag as an additional source of a
single bit that is included in the operation at the /east significant bit position.
The following table lists the addition mnemonics.
Mnemonic Operation
ADD A.#n Add A and the immediate number n; put the sum in A
ADD A.Rr ‘Add A and register Rr; put the sum in A
ADD A,add Add A and the address contents; put the sum in A
ADD A.@Rp Add A and the contents of the address in Rp; put the sum in A.
Note that the C flag is set to 1 if there is a carry out of bit position 7; it is cleared to 0
otherwise. The AC flag is set to I if there is a carry out of bit position 3; it is cleared
otherwise. The OV flag is set to 1 if there is a carry out of bit position 7, but not bit
position 6 or if there is a carry out of bit position 6 but not bit position 7, which may be
expressed as the logical operation
OV = C7 XOR CO
Unsigned and Signed Addition
The programmer may decide that the numbers used in the program are to be unsigned
numbers—that is, numbers that are 8-bit positive binary numbers ranging from 00h to
FFh. Alternatively. the programmer may need to use both positive and negative signed
numbers.
Signed numbers use bit 7 as a sign bit in the most significant byte (MSB) of the group
of bytes chosen by the programmer to represent the largest number to be needed by the
program. Bits 0 to 6 of the MSB, and any other bytes, express the magnitude of the num-
ber. Signed numbers use a I in bit position 7 of the MSB as a negative sign and a 0 as a
positive sign. Further. all negative numbers are not in true form, but are in 2's comple-
ment form. When doing signed arithmetic, the programmer must know how large the
largest number is to be—that is, how many bytes are needed for each number.
In signed form, a single byte number may range in size from 10000000b, which
is ~ 128d fo O1111111b, which is +1274. The number 000000000 is 000d and has a posi-
tive sign, so there are 128d negative numbers and 128d positive numbers. The C and OV
flags have been included in the 8051 to enable the programmer to use either numbering
scheme.
Adding or subtracting unsigned numbers may generate a carry flag when the sum ex-
ceeds FFh or a borrow flag when the minuend is less than the subtrahend. The OV flag is
not used for unsigned addition and subtraction. Adding or subtracting signed numbers canARITHMETIC OPERATIONS 75
ead t0 carries and borrows in a similar manner, and to overflow conditions due to the
actions of the sign bits.
Unsigned Addition
Unsigned numbers make use of the carry flag {0 detect when the result of an ADD opera-
tion is a number larger than FFh. If the carry is set to one after an ADD, then the carry can
be added to a higher order byte so that the sum is not lost. For instance,
95d = O1OILI Ib
189d = 101111016
284d 1 000111000 = 284¢
‘The C flag is set to 1 to account for the carry out from the sum. The program could add the
carry flag to another byte that forms the second byte of a larger number.
Signed Addition
Signed numbers may be added two ways: addition of like signed numbers and addition
‘of unlike signed numbers. If unlike signed numbers are added, then it is not possible
for the result to be larger than ~ 128d or +1274, and the sign of the result will always be
correct. For example,
—O0ld = WILIItIb
+0274 = Qoo11011b
+026d = 00011010b = +0264
Here, there is a carry from bit 7 so the carry flag is 1. There is also a carry from bit 6, and
the OV flag is 0. For this condition, no action need be taken by the program to correct
the sum.
If positive numbers are added, there is the possibility that the sum will exceed + 127d,
as demonstrated in the following exampl
+100d = 011001006
+050d = 001100106
+150d — 10010110b = —106d
Ignoring the sign of the result, the magnitude is seen to be +22d which would be correct if
we had some way of accounting for the +128d, which, unfortunately, is larger than a
single byte can hold. There is no carry from bit 7 and the carry flag is 0; there is a carry
from bit 6 so the OV flag is 1
‘An example of adding two positive numbers that do not exceed the positive limit is:
+045d = 00101101b
+075d = 0100101 1b
+1204 011110001
1204
Note that there are no carties from bits 6 or 7 of the sum; the carry and OV flags are
both 0.
‘The result of adding two negative numbers together for a sum thal does not exceed the
negative limit is shown in this example:
11001110
10110000b = —080d76
CHAPTER FIVE
Here, there is a carry from bit 7 and the carry flag is 1; there is a carry from bit 6 and the
OV flag is 0. These are the same flags as the case for adding unlike numbers; no correc
tions are needed for the sum.
When adding two negative numbers whose sum does exceed ~ 128d, we have
070d = 10111010b
=070d = 101110106
=140d 01110100b = + 116d
Or, the magnitude can be interpreted as ~ 12d, which is the remainder after a carry out of
= 128d. In this example, there is a carry from bit position 7, and no carry from bit position
6, so the carry and the OV flags are set to 1. The magnitude of the sum is correct; the sign
bit must be changed to a 1
From these examples the programming actions needed for the C and OV flags are as
follows:
FLAGS ACTION
c¢ ov
a) None
oo4 Complement the sign
1 0 None
Seen Complement the sign
A general rule is that if the OV flag is set, then complement the sign. The OV flag also
signals that the sum exceeds the largest positive or negative numbers thought to be needed
in the program.
Multiple-Byte Signed Arithmetic
The nature of multiple-byte arithmetic for signed and unsigned numbers is distinctly
different from single byte arithmetic. Using more than one byte in unsigned arithmetic
means that carries or borrows are propagated from low-order to high-order bytes by the
simple technique of adding the carry to the next highest byte for addition and subtracting
the borrow from the next highest byte for subtraction.
Signed numbers appear to behave like unsigned numbers until the last byte is reached.
Fora signed number, the seventh bit of the highest byte is the sign; if the sign is negative,
then the entire number is in 2's complement form.
For example, using a two-byte signed number, we have the following examples:
+32767d = OFFIITLL HSE 1b = 7FFFh
+00000d = 00000000 00000000b
—00001d = HENLE THIEL
—32768d = 10000000 00000000b
Note that the fowest byte of the numbers 00000d and — 32768d are exactly alike, as are the
lowest bytes for +32767d and —00001d.
For multi-byte signed number arithmetic, then, the lower bytes are treated as un-
signed numbers. All checks for overflow are done only for the highest order byte that
contains the sign. An overflow at the highest order byte is not usually recoverable. The
programmer has made a mistake and probably has made no provisions for a number larger
than planned. Some error acknowledgment procedure, or user notification, should be in-
cluded in the program if this type of mistake is a possibility.ARITHMETIC OPERATIONS 77.
‘The preceding examples show the need to add the carry flag to higher order bytes in
signed and unsigned addition operations. Opcodes that accomplish this task are similar to
the ADD mnemonics: A C is appended to show that the carry bit is added to the sum in bit
position 0.
‘The following table lists the add with carry mnemonics:
Mnemonic Operation
ADDC A,#n Add the contents of A, the immediate number n, and the C flag: put
the sum in A
ADDC A.add Add the contents of A, the direct address contents, and the C flag:
put the sum in A
ADDC A.Rr Add the contents of A, register Rr, and the C flag; put the sum in A
ADDC A,@Rp Add the contents of A, the contents of the indirect address in Rp,
and the C flag; put the sum in A
Note that the C, AC, and OV flags behave exactly as they do for the ADD commands.
The following table shows examples of ADD and ADDC multiple-byte signed arith.
metic operations:
Mnemonic
MOV A,#1Ch
MOV RS5,#0A1h
ADD A,RS
ADD A,RS
ADDC A,#10h
ADDC A,#10h
—l>— caution
ADOC is normally used to add a carry after the LSB addition in a multi-byte process. ADD is
normally used for the LSB addition,
Subtraction
Subtraction can be done by taking the 2's complement of the number to be subtracted, the
subtrahend, and adding it to another number, the minuend. The 8051, however, has com:
mands to perform direct subtraction of two signed or unsigned numbers. Register A is the
destination address for subtraction. All four addressing modes may be used for source
addresses, The commands treat the carry flag as a borrow and always subtract the carry
flag as part of the operation.
‘The following table lists the subtract mnemonics.
Mnemonic Operation
SUBB A.#n ‘Subtract immediate number a and the C flag from A; put the result
ind
SUBB A,add Subtract the contents of add and the C flag from A; put the result in A,
SUBB A.Rr Subtract Rr and the C flag from A; put the result in A
SUBB A,@Rp Subtract the contents of the address in Rp and the C flag from A;
ut the result in A78
CHAPTER FIVE
Note that the C flag is set if a borrow is needed into bit 7 and reset otherwise. The AC flag
is set if a borrow is needed into bit 3 and reset otherwise. The OV flag is set if there is a
borrow into bit 7 and not bit 6 or if there is a borrow into bit 6 and not bit 7. As in the case
for addition, the OV Flag is the XOR of the borrows into bit positions 7 and 6.
Unsigned and Signed Subtraction
‘Again, depending on what is needed, the programmer may choose to use bytes as signed
or unsigned numbers. The carry flag is now thought of as a borrow flag to account for
situations when a larger number is subtracted from a smaller number. The OV flag indi-
cates results that must be adjusted whenever two numbers of unlike signs are subtracted
and the result exceeds the planned signed magnitudes,
Unsigned Subtraction
Because the C flag is always subtracted from A along with the source byte, it must be set
to 0 if the programmer does not want the flag included in the subtraction. If a multi-byte
subtraction is done, the C flag is cleared for the first byte and then included in subsequent,
higher byte operations.
The result will be in true form, with no borrow if the source number is smaller than
‘A, or in 2's complement form, with a borrow if the source is larger than A. These are not
‘signed numbers, as all eight bits are used for the magnitude. The range of numbers is from
positive 255d (C = 0, A = FFh) to negative 255d (C = 1, A = O1h).
The following example demonstrates subtraction of larger number from a smaller
number:
015d = 0000111 1b
SUBB _ 100d = 011001006
085d 1 1010101 1b = 171d
‘The C flag is set to 1, and the OV flag is set to 0. The 2’s complement of the result is O8Sd.
The reverse of the example yields the following result:
100d = 01100100b
015d = 0000111 tb
85d O1010101b = 085d
The C flags set 100, and the OV flag
set to0. The magnitude of the result is in true form,
Signed Subtraction
{As is the case for addition, two combinations of unsigned numbers are possible when sub-
tracting: subtracting numbers of like and unlike signs. When numbers of like sign are
subtracted, it is impossible for the result to exceed the positive or negative magnitude
limits of +127d or ~128d, so the magnitude and sign of the result do not need to be
adjusted, as shown in the following example:
+100d = 01100100b (Carry flag = 0 before SUBB)
SUBB +126d = OL1I1110b
026d 1 111001105 = -026¢
‘There is a borrow into bit positions 7 and 6; the carry flag is set to 1, and the OV flag is
cleared.ARITHMETIC OPERATIONS «79
The following example demonstrates using two negative numbers:
—061d = 11000011b (Carry flag = 0 before SUBB)
SUBB —116d = 100011006
+055d OOLIOI Ib = +55d
There are no borrows into bit positions 6 or 7, so the OV and carry flags are cleared to zero.
An overflow is possible when subtracting numbers of opposite sign because the situa-
tion becomes one of adding numbers of like signs, as can be demonstrated in the following,
‘example:
—099d = 10011101 (Carry flag = 0 before SUBB)
SUBB +100d = 011001000
=199d 00111001b = +0574
Here, there is a borrow into bit position 6 but not into bit position 7; the OV flag is set to 1,
and the carry flag is cleared to 0. Because the OV flag is set to I, the result must be
adjusted. In this case, the magnitude can be interpreted as the 2's complement of 714, the
remainder after a carry out of 128d from 199d. The magnitude is correct, and the sign
needs to be corrected to a 1
The following example shows a positive overftow:
+087d = O1010111b (Carry flag = 0 before SUBB)
152d = 110011006
+139d 1000101 1b = —1174
SUBB
‘There is a borrow from bit position 7, and no borrow from bit position 6; the OV flag and
the carry flag are both set to 1. Again the answer must be adjusted because the OV flag is
set to one, The magnitude can be interpreted as a +011, the remainder from a carry out
of 128d. The sign must be changed to a binary 0 and the OV condition dealt with.
The general rule is that if the OV flag is set t0 1, then complement the sign bit. The
OV flag also signals that the result is greater than —128d or +1274.
Again, it must be emphasized: When an overflow occurs in a program, an error has
been made in the estimation of the largest number needed to successfully operate the pro-
gram. Theoretically, the program could resize every number used, but this extreme proce-
dure would tend to hinder the performance of the microcontroller.
Note that for all the examples in this section, it is assumed that the carry flag = 0
before the SUBB. The carry flag must be 0 before any SUBB operation that depends upon
C = Ois done.
The following table lists examples of SUBB multiple-byte signed arithmetic
operations:
Mnemonic Operation
MOV 0D0h,#00h Carry flag = 0
MOV A,#3Ah A=3Ah
MOV 45h,#13h Address 45h = 13h
SUBB A,43h A= 27h,C =0,0V=0
SUBB A,45h
SUBB A.#80h
SUBB A.#22h
SUBB A,#0FFhBO CHAPTER FIVE
-[>— CAUTION
Remember to set the carry flag to zero if itis not to be included as part of the subtraction
‘operation
Multiplication and Division
‘The 8051 has the capability to perform 8-bit integer multiplication and division using the
A and B registers. Register B is used solely for these operations and has no other use
except as a location in the SFR space of RAM that could be used to hold data. The
A register holds one byte of data before a multiply or divide operation, and one of the
result bytes after 2 multiply or divide operation.
Multiplication and division treat the numbers in registers A and B as unsigned. The
programmer must devise ways (0 handle signed numbers.
Multiplication
Mutiplication operations use registers A and B as both source and destination addresses
for the operation. The unsigned number in register A is multiplied by the unsigned number
in register B, as indicated in the following table:
Mnemonic Operation
MUL AB Multiply A by B: put the low-order byte of the product in A, put the
high-order byte in B
‘The OV flag will be set if AXB > FFh. Setting the OV flag does not mean that an error
has occurred. Rather, it signals that the number is larger than eight bits, and the program-
‘mer needs to inspect register B for the high-order byte of the multiplication operation, The
carry flag is always cleared to 0.
‘The largest possible product is FEOIh when both A and B contain FFh. Register A
contains O1h and register B contains FEh after multiplication of FFh by FFh. The OV flag
is set to I to signal that register B contains the high-order byte of the product: the carry
fag is 0
The following table gives examples of MUL multiple-byte arithmetic operations:
Mnemonic Operation
MOV A.#7Bh A = 7Bh
MOV OFOh.#02h B 2h
MUL AB A = 00h and B = Fh; OV Flag = 0
MOV A,#0FEh A = FEh
MUL AB 14h and B = F4h; OV Flag = |
-[>— CAUTION
Note there is no comma between A and B in the MUL mnemonic.
Division
Division operations use registers A and B as both source and destination addresses for the
operation. The unsigned number in register A is divided by the unsigned number in regis-
ter B, as indicated in the following table:ARITHMETIC OPERATIONS «BY
Mnemonic Operation
DIV AB Divide A by B; put the integer part of quotient in register A and the
integer part of the remainder in B
‘The OV fiag is cleared (0 0 unless B holds 00h before the DIV. Then the OV flag is set to 1
to show division by 0. The contents of A and B, when division by 0 is attempted, are.
undefined. The carry flag is always reset.
Division always results in integer quotients and remainders, as shown in the following
example:
A= 213d
Bara ~ !2 (quotient) and 9 (remainder)
213 [(12 x 17) + 9}
When done in hex:
A = 0DSh
B= 0th
The following table
= C (quotient) and 9 (remainder)
examples of DIV multiple-byte arithmetic operations:
Mnemonic Operation
MOV A,#0FFh (A = FFh (255d)
MOV OFOh,#2Ch B= 2C (44d)
DIV AB A = 05h and B = 23h [255d = (5 x 44) + 35]
DIV AB 00h and B = OSh {0Sd = (0 x 35) + 5]
DIV AB ‘A = 00h and B = 00h (00d = (0 x 5) + 0)
DIV AB
WV flag is set to one
+ CAUTION
The original contents of B (the divisor) are lost.
Note there is na comma between A and B in the DIV mnemonic,
Decimal Arithmetic
Most 8051 applications involve adding intelligence to machines where the hexadecimal
numbering system works naturally. There are instances, however, when the application
involves interacting with humans, who insist on using the decimal number system. In such
cases, it may be more convenient for the programmer to use the decimal number system to
represent all numbers in the program.
Four bits are required to represent the decimal numbers from 0 to 9 (0000 to 1001)
and the numbers are often called Binary coded decimal (BCD) numbers. Two of these
BCD numbers can then be packed into a single byte of data.
‘The 8051 does all arithmetic operations in pure binary. When BCD numbers are being
used the result will often be a non-BCD number, as shown in the following example:
49BCD = 01001001
+38BCD = 00111000b
87BCD —10000001b = 81BCD
Note that to adjust the answer, an O6d needs to be added to the result82
+
CHAPTER FIVE
‘The opcode that adjusts the result of BCD addition is the decimal adjust A for addi-
tion (DA A) command, as shown in the following table:
Mnemonic Operation
DAA Adjust the sum of two packed BCD numbers found in A register: leave
the adjusted number in A.
‘The C flag is set to 1 if the adjusted number exceeds 99BCD and set to 0 otherwise. The
DA A instruction makes use of the AC flag and the binary sums of the individual binary
nibbles to adjust the answer to BCD. The AC flag has no other use to the programmer and no
structions —other than a MOV or a direct bit operation to the PSW—affect the AC flag.
It is important to remember that the DA A instruction assumes the added numbers
were in BCD before the addition was done. Adding hexadecimal numbers and then using
DA A will nor convert the sum to BCD.
The DA A opcode only works when used with ADD or ADDC opcodes and does not
give correct adjustments for SUBB, MUL or DIV operations. The programmer might best
consider the ADD or ADDC and DA A as a single instruction and use the pair automat:
ically when doing BCD addition in the 8051.
The following table gives examples of BCD multiple-byte arithmetic operations:
Mnemonic Operation
MOV A.#42h_ A = 42BCD
ADD A,#13h
DAA
ADD A,#17h
DAA
ADDC A,#34h
DAA
ADDC A.#11h
DAA
DoF
CAUTION -
All numbers used must be in BCD form before addition,
Only ADD and ADDC are adjusted to BCD by DA A.
Example Programs
The challenge of the programs presented in this section is writing them using only opcodes
that have been covered to this point in the book. Experienced programmers may long for
some of the opcodes to be covered in Chapter 6, but as we shall see. programs can be
written without them.
EXAMPLE PROBLEM 5.1
Add the unsigned numbers found in internal RAM locations 25h, 26h, and 27h together
and put the result in RAM locations 30h (MSB) and 31h (LSB).
= Thoughts on the Problem The largest number possible is FFh + FFh = O1FEh + FFh =
02FDh, so that two bytes will hold the largest possible number. The MSB will be set to 0
and any carry bit added to it for each byte addition,ARITHMETIC OPERATIONS «BB.
To solve this problem, use an ADD instruction for each addition and an ADDC to the
MSB for each carry which might be generated. The first ADD will adjust any carry flag
which exists before the program starts.
The complete program is shown in the following table:
Mnemonic Operation
MOV 31h,#00h Clear the MSB of the result to 0
MOV A,25h Get the first byte to be added from location 25h.
ADD A,26h Add the second byte found in RAM location 26h
MOV RO,A, Save the sum of the first two bytes in RO
MOV A,#00h Clear A to 00:
ADDC A,31h ‘Add the carry to the MSB; carry = 0 after this operation
MOV 31h,A Store MSB
MOV A,RO Get partial sum back
ADD A,27h Form final LSB sum
MOV 39h,A Store LSB
MOV A,#00h Clear A for MSB addition
ADDC A,3th Form final MSB
MOV 31h.A Store final MSB
{ COMMENT
1
Notice how awkward it becomes to have to use the A register for al operations. Jump instruc-
tions, which will be covered in Chapter 6, require less use of A
EXAMPLE PROBLEM 5.2
Repeat problem 5.1 using BCD numbers.
= Thoughts on the Problem The numbers in the RAM locations must be in BCD before
the problem begins. The largest number possible is 99d + 99d = 198d + 99d = 297d, so.
that up to two carries can be added to the MSB.
The solution to this problem is identical to that for unsigned numbers, except a DA A
must be added after each ADD instruction. If more bytes were added so that the MSB
could exceed 09d, then a DA A would also be necessary after the ADDC opcodes.
‘The complete program is shown in the following table:
Mnemonic Operation
MOV 31h,#00h Clear the MSB of the result to 0
MOV A,25h Get the first byte to be added from location 2h
ADD A,26h ‘Add the second byte found in RAM location 26h
DAA Adjust the answer to BCD form
MOV RO,A Save the sum of the first two bytes in RO
MOV A.#00h Clear A 10. 00
ADDC A,31h ‘Add the carry to the MSB; carry = 0 after this operation
MOV 31h,A Store MSB
MOV A,RO Get partial sum back
ADD A,27h Form final LSB sum
DAA Adjust the final sum to BCD
MOV 30h,A Store LSB
MOV A,#00h Clear A for MSB addition
ADDC A,31h Form final MSB
MOV 31h,A Store final MSB84 CHAPTER FIVE
{>— coMMeENT
When using BCD numbers, DA A can best be thought of as an integral part of the ADD
instructions,
[_] examece proBLem 5.3
Summary
Multiply the unsigned number in register R3 by the unsigned number on port 2 and put the
result in external RAM locations 10h (MSB) and 11h (LSB).
= Thoughts on the Problem The MUL instruction uses the A and B registers; the prob-
tem consists of MOVes to A and B followed by MOVes to the external RAM. The com-
plete program is shown in the following table:
‘Mnemonic Operation
MOV A.0AGh Move the port 2 pin data to A
MOV OFOb,R3.—- Move the data in R3 to the B register
MUL AB Multiply the data; A has the low order result byte
MOV RO,#11th Set RO to point to external RAM location 11h
MOV @RO,A Store the LSB in external RAM
DEC RO Decrement RO to point to 10h
MOV A.OF0h Move B to A
MOV @RO,A. Store the MSB in external RAM.
—[>— comment ———
Again we see the bottleneck created by having to use the A register for all external data
ransfers,
‘More advanced programs which do signed math operations and multi-byte multiplication and
division will have to wait for the development of Jump instructions in Chapter 6.
‘The 8051 can perform all four arithmetic operations: addition, subtraction, multiplication,
and division. Signed and unsigned numbers may be used in addition and subtraction; an
‘OV flag is provided to signal programmer errors in estimating signed number magnitudes
needed and to adjust signed number results. Multiplication and division use unsigned
‘numbers. BCD arithmetic may be done using the DA A and ADD or ADDC instructions.
The following table lists the arithmetic mnemonics:
Mnemonic Operation
ADD A, source Add the source byte to A; put the result in A and adjust the C and
‘OV flags
ADDC A, source Add the source byte and the carry to A; put the result in A and
adjust the C and OV flags
DAA Adjust the binary result of adding two BCD numbers in the A
register to BCD and adjust the carry flag
DEC source Subtract a 1 from the source: roll from 00h to FFh
DIV AB Divide the byte in A by the byte in B; put the quotient in A and
the remainder in B; set the OV flag to 1 if B = 00h before the
divisionARTHMENC OPERATIONS «85
INC source ‘Add a 1 to the source: roll from FFh or FFFFh to 00h or 0000h
MUL AB ‘Multiply the bytes in A and B: put the high-order byte of the
result in B, the low-order byte in A; set the OV flag to 1 if the
result is > FFh
SUBB A, source Subtract the source byte and the carry from A; put the result in A
and adjust the C and OV flags
Problems
Write programs that perform the tasks listed using only opcodes that have been discussed
in this and previous chapters. Use comments on each line of code and try to use as few
lines as possible. All numbers may be considered to be unsigned numbers.
1, Add the bytes in RAM locations 34h and 3Sh: put the result in register RS (LSB) and
R6 (MSB),
2. Add the bytes in registers R3 and R4; put the resutt in RAM location 4Ah (LSB) and
4Bh (MSB).
3. Add the number 84h to RAM locations 17h and 18h.
4. Add the byte in external RAM location 02CDh to internal RAM location 19h; put the
result into external RAM location 00COh (LSB) and 00C 1h (MSB).
5-8. Repeat Problems 1-4, assuming the numbers are in BCD format.
9. Subtract the contents of R2 from the mumber F3h; put the result in external RAM loca-
tion 028Bh,
10, Subtract the contents of RI from RO; put the result in R7.
11. Subtract the contents of RAM location 13h from RAM location 2Bh; put the result in
RAM location 3Ch.
12. Subtract the contents of THO from THI: put the result in TLO.
13. Increment the contents of RAM location 13h, 14h, and 15h using indirect addressing only.
14, Increment TL1 by 10h.
15, Increment external RAM locations 0100h and 0200h,
16. Add a | to every external RAM address from 00h to O6h.
17. Add a 1 10 every external RAM address from 0100h to 0106h.
18. Decrement TLO, THO, TL.!, and THI
19. Decrement external RAM locations 0123h and 01BDh.
20. Decrement external RAM locations 45h and 46h.
21. Multiply the data in RAM location 22h by the data in RAM location 15h; put the result
in RAM locations 19h (low byte). and 1Ah (high byte).
22, Square the contents of RS: put the result in RO (high byte), and RI (low byte).
23. Divide the data in RAM location 3Eh by the number 12h: put the quotient in R4 and the
remainder in RS.
Divide the number in RAM location 1Sh by the data in RAM location 16h; put the result
in external RAM location 7Ch
2. Divide the data in RAM location 13h by the data in RAM location 14h, then restore the
original data in 13h by multiplying the answer by the data in 14h,CHAPTER
6.
Jump and Call Opcodes
Chapter Outline
Introduction Calls and Subroutines:
‘The Jump and Call Program Range Interrupts and Returns
Jumps Problems
Introduction
‘The opcodes that have been examined and used in the preceding chapters may be thought
of as action codes. Each instruction performs a single operation on bytes of data.
The jumps and calls discussed in this chapter are decision codes that alter the flow of
the program by examining the results of the action codes and changing the contents of the
program counter. A jump permanently changes the contents of the program counter if cer-
tain program conditions exist. A call temporarily changes the program counter to allow
another part of the program to run. These decision codes make it possible for the program.
‘mer to let the program adapt itself, as it runs, to the conditions that exist at the time.
While it is true that computers can’t “think” (at least as of this writing), they can
make decisions about events that the programmer can foresee, using the following deci-
sion opcodes:
Jump on bit conditions
‘Compare bytes and jump if nor equal
Decrement byte and jump if zero
Jump unconditionally
Call a subroutine
Return from a subroutine
Jumps and calls may also be generically referred to as “branches,” which emphasizes that
86 two divergent paths are made possible by this type of instruction.JUMP AND CALL OPCODES 87
The Jump and Call Program Range
‘A jump or call instruction can replace the contents of the program counter with a new
program address number that causes program execution to begin at the code located at the
new address, The difference, in bytes, of this new address from the address in the program
where the jump or call is located is called the range of the jump or call. For example, if a
jump instruction is tocated at program address 0100h, and the jump causes the program
counter to become 0120h, then the range of the jump is 20h bytes.
Jump or call instructions may have one of three ranges: a relative range of +127d,
—128d bytes from the instruction following the jump or call instruction; an absolute range
on the same 2K byte page as the instruction following the jump or call; or a long range of
any address from 0000h to FFFFh, anywhere in program memory. Figure 6.1 shows the
relative range of all the jump instructions.
FIGURE 6.1 Jump Instruction Ranges
Memory Address HEX
er LADD Limit
NextPage (______
SADD Limit
Pc + 127d [Relative Limit
UMP
Pc - 1284 [Relative Limit
This Page | SAD mit
l=]
ese ey
———~——-————— 4CHAPTER SIX
Relative Range
Jumps that replace the program counter contents with a new address that is greater than the
address of the instruction following the jump by 127d or less than the address of the in-
struction following the jump by 128d are called relative jumps. They are so named
because the address that is placed in the program counter is relative to the address where
the jump occurs. If the absolute address of the jump instruction changes, then the jump
address changes also but remains the same distance away from the jump instruction. The
address following the jump is used to calculate the relative jump because of the action of
the PC. The PC is incremented to point to the next instruction hefore the current instruc-
tion is executed, Thus, the PC is set to the following address before the jump instruction is
executed. or in the vernacular: “before the jump is taken.”
Relative jumping has two advantages. First, only one byte of data need be specified,
cither in positive format for jumps ahead in the program or in 2's complement negative
format for jumps behind. The jump address displacement byte can then be added to the PC
to get the absolute address. Specifying only one byte saves program bytes and speeds up
program execution. Second, the program that is written using relative jumps can be lo-
cated anywhere in the program address space without re-assembling the code to generate
absolute addresses.
The disadvantage of using relative addressing is the requirement that all addresses
jumped be within a range of +127d, —128d bytes of the jump instruction. This range is
not a serious problem. Most jumps form program loops over short code ranges that are
within the relative address capability. Jumps are the only branch instructions that can use
the relative range.
If jumps beyond the relative range are needed, then a relative jump can be done to
another relative jump untit the desired address is reached, This need is better handled,
however. by the jumps that are covered in the next sections.
Short Absolute Range
Absolute range makes use of the concept of dividing memory into logical divisions called
“pages.” Program memory may be regarded as one continuous stretch of addresses from
0000h to FFFFh. Or, it may be divided into a series of pages of any convenient binary
size, such as 256 bytes, 2K bytes, 4K bytes, and so on.
The 8051 program memory is arranged as 2K byte pages, giving a total of 32d (20h)
pages. The hexadecimal address of each page is shown in the following table:
PAGE ADDRESS(HEX) PAGE ADDRESS(HEX) PAGE ADDRESS(HEX)
00 0000~o7FF 08 '5800-SFFF 16 8000-B7FF
01 0800~0FFF oc 6000-67FF 7 B800—BFFF
02 1000~17#F 00 6800-6FFF 18 (000-C7FF
03 1800~1FFF of 7000-77FF 19 800-CFFF
04 2000-27FF OF 7800-7FFF 1A D000-D7FF
05, 2800 2FFF 10 8000-8 7FF 18 0800-DFFF
06 3000~37FF n 8800-BFFF 1c 000-E7FF
07 3800~3FFF 2 9000.-97FF 1D €800—EFFF
08 4000-47FF 1B 9800. 9FFF 1 F000-F7FF
09 4800-4FFF 14 ‘A000-A7FF 1F F800_-FFFF
0A 5000~S7FF 15 ‘A800 AFFF
Inspection of the page numbers shows that the upper five bits of the program counter
hold the page number, and the lower eleven bits hold the address within each page. An
absolute address is formed by taking the page number of the instruction following theJumps
JUMP AND CALLOPCODES «BD
branch and attaching the absolute page range address of eleven bits to it to form the 16-bit,
address,
Branches on page boundaries occur when the jump or call instruction finishes at
X7FFh or XFFFh. The next instruction starts at X800h or XOOOh, which places the jump
or call address on the same page as the next instruction after the jump or call. The page
‘change presents no problem when branching ahead but could be troublesome if the branch,
is backwards in the program. The assembler should flag such problems as errors, so ad-
justments can be made by the programmer to use a different type of range.
Absolute range addressing has the same advantages as relative addressing; fewer
bytes are needed and the code is relocatable as long as the relocated code begins at the
start of a page. Absolute addressing has the advantage of allowing jumps or calls over
longer programming distances than does relative addressing.
Long Absolute Range
‘Addresses that can access the entire program space from 0000h to FFFFh use long range
addressing. Long-range addresses require more bytes of code to specify and are relocat-
able only at the beginning of 64K byte pages. Since we are limited to a nominal ROM.
address range of 64K bytes, the program must be re-assembled every time a long-range
address changes and these branches are not generally relocatable
Long-range addressing has the advantage of using the entire program address space
available to the 8051. It is most likely to be used in large programs.
The ability of a program to respond quickly to changes in conditions depends largely upon
the number and types of jump instructions available to the programmer. The 8051 has a
rich set of jumps that can operate at the bit and byte levels. These jump opcodes are one
reason the 8051 is such a powerful microcontroller.
Jumps operate by testing for conditions that are specified in the jump mnemonic. If
the condition is true, then the jump is taken—that is, the program counter is altered to the
address that is part of the jump instruction. If the condition is false, then the instruction
immediately following the jump instruction is executed because the program counter is
not altered. Keep in mind that the condition of érwe does nor mean a binary | and that false
does not mean binary 0. The condition specified by the mnemonic is either true or false.
Bit Jumps
Bit jumps all operate according to the status of the carry flag in the PSW or the status of
any bit-addressable location. All bit jumps are relative to the program counter.
Jump instructions that test for bit conditions are shown in the following table:
Mnemonic Operation
JC radd Jump relative if the carry flag is set to 1
JNC radd Jump relative if the carry flag is reset to 0
JB b,radd Jump relative if addressable bit is set to 1
JNB b,radd Jump relative if addressable bit is reset to 0
JBC b,tadd_—_ Jump relative if addressable bit is set, and clear the addressable bit to 0
Note that no flags are affected unless the bit in JBC is 2 flag bit in the PSW. When the bit
used in a JBC instruction is a port bit, the SFR latch for that port is read, tested, and
altered.90 CHAPTER Six
The following program example makes use of bit jumps:
ADDRESS MNEMONIC COMMENT
Loop MOV A,#10h cA 10h
MOV RO,A ;RO 10h
ADDA ADD A,RO jadd RO to A
JNC ADDA f the carry flag is 0, then no carry is
;true; jump to address ADDA; jump until A
;is FOh; the C flag is set to
;l on the next ADD and no carry is
; false; do the next instruction
MOV A, #10h :A = 10h; do program again using JNB
ADDR : ADD A.RO ;add RO to A (RO already equals 10h)
JNB ODTh, ADDR :D7h is the bit address of the carry flag
JBC OD7h, LOOP ithe carry bit is 1; the jump to LOOP
;is taken, and the carry flag is cleared
;to 0
CAUTION
Alljump addresses, such as ADDA and ADDR, must be within + 127d, —128d of the instruction
following the jump opcode
If the addressable bit is a flag bit and JBC is used, the flag bit will be cleared.
Do not use any label names that are aso the names of registers in the 8051. These are called
“reserved” words and will cause great agitation in the assembler
Byte Jumps
Byte jumps—jump
structions that test bytes of data—behave as bit jumps. If the condi-
tion that is tested is rrue, the jump is taken; if the condition is false, the instruction after
the jump is executed. All byte jumps arc relative to the program counter.
The following table lists examples of byte jumps:
Mnemonic
CINE A,add,radd
CINE A,#n,radd
CINE Rn,#n,radd
CINE @Rp,#n,radd
Operation
‘Compare the contents of the A register with the contents of the
direct address; if they are not equal, then jump to the relative
address; set the carry flag to 1 if A is less than the contents
of the direct address; otherwise, set the carry flag to 0
‘Compare the contents of the A register with the immediate
number n; if they are not equal, then jump to the relative
address; set the carry flag to | if A is Tess than the number;
otherwise, set the carry flag to 0
Compare the contents of register Rn with the immediate
number n; if they are not equal, then jump to the relative
address; set the carry flag to 1 if Rnis less than the number;
otherwise, set the carry flag to 0
‘Compare the contents of the address contained in register Rp
to the number n; if they are not equal, then jump to the
relative address; set the carry flag to 1 if the contents of the
address in Rp are less than the number; otherwise, set the
carry flag 10 0ADDRESS
BGN
AGN:
AEQ
NXT:
DWN:
JUMP AND CALLOPCODES = 9
DINZ Rn,radd Decrement register Rn by 1 and jump to the relative address if
the result is not zero; no flags are affected
DINZ, add,radd Decrement the direct address by | and jump to the relative
address if the result is nor 0; no flags are affected unless the
direct address is the PSW
JZ radd Jump to the relative address if A is 0; the flags and the A
register are not changed
INZ radd Jump to the relative address if A is nor Q; the flags and the A
register are not changed
Note that if the direct address used in a DINZ. is a port, the port SFR is decremented and
tested for 0.
Unconditional Jumps
Unconditional jumps do not test any bit or byte to determine whether the jump should be
taken. The jump is always taken. All jump ranges are found in this group of jumps. and
these are the only jumps that can jump to any location in memory.
The following table shows examples of unconditional jumps:
Mnemonic Operation
JMP @A+DPTR Jump to the address formed by adding A to the DPTR; this is an
unconditional jump and will always be done; the address can
be anywhere in program memory; A, the DPTR, and the flags
are unchanged
AIMP sadd Jump to absolute short range address sadd; this is an unconditional
jump and is always taken; no flags are affected
LIMP ladd Jump to absolute long range address ladd; this is an unconditional
jump and is always taken; no flags are affected
SUMP radd Jump to relative address radd; this is an unconditional jump and
is always taken; no flags are affected
NOP Do nothing and go to the next instruction; NOP (no operation) is
used to waste time in a software timing loop: or to leave room.
in a program for later additions; no flags are affected
The following program example uses byte and unconditional jumps:
MNEMONIC ‘COMMENT
ORG 0100h ibegin program at 0100h
MOV A, #30h = 30h
MOV 50h, #00n ;RAM location 50h = 00h
CJNE A,50h,AEQ ;compare A and the contents of 50h in RAM
SIMP NXT ;SUMP will be executed if (50h) = 30h
DJNZ 50h, AGN fount RAM location 50h down until (50h) =
NOP ; (50h) will reach 30h before 00h
MOV RO,#0FFh :RO = FFh
DJNZ RO,D¥N recount RO to 00h; loop here until done
MOV A, RO :A = RO = 00h
JNZ ABIG the jump will not be taken
JZ AZRO ;the jump will be taken
Continued92 CHAPTER six
ADDRESS ~—MNEMONIC COMMENT
Continued
ABIG NOP his address will not be reached
ORG 1000h tart this segment of program code at
;1000h
AZRO: MOV A, #08h 08h (code at 1000.1h)
MOV DPTR,#1000h :DPTR = 1000h (code at 1002,3.4h)
JMP @A+DPTR ;jump to location 1008h (code at 1005h)
NOP :(code at 1006h)
NOP : (code at 1007h)
HERE: AJMP AZRO :(code at 1008h, all code on page 2)
{ CAUTION
DINZ decrements first, then checks for 0. A location set to 00h and then decremented goes to
Ffh, then FEh, and so on, down to OOh.
CINE does not change the contents of any register or RAM location, It can change the carry
flag to 1 if the destination byte is fess than the source byte.
There is no zero flag; the JZ and JNZ instructions check the contents of the A register for 0.
IMP @A+DPTR does not change A, DPTR, or any flags,
Calls and Subroutines
The life of a microcontroller would be very tranquil if all programs could run with no
thought as to what is going on in the real world outside. However, a microcontroller is
specifically intended to interact with the real world and to react, very quickly, to events
that require program attention to correct or control.
‘A program that does not have to deal unexpectedly with the world outside of the
microcontroller could be written using jumps to alter program flow as external conditions
require. This sort of program can determine external conditions by moving data from the
port pins (0.4 location and jumping on the conditions of the port pin data. This technique is
called “polling” and requires that the program does not have to respond to external condi-
tions quickly. (Quickly means in microseconds; slowly means in milliseconds.)
Another method of changing program execution is using “interrupt” signals on cer-
tain external pins or internal registers to automatically cause a branch to a smaller program
that deals with the specific situation. When the event that caused the interruption has been
dealt with, the program resumes at the point in the program where the interruption took
place. Interrupt action can also be generated using software instructions named calls.
Call instructions may be included explicitly in the program as mnemonics or im-
plicitly included using hardware interrupts. In both cases, the call is used to execute a
smaller, stand-alone program, which is termed a routine or, more ofien, a subroutine.
Subroutines
A subroutine is a program that may be used many times in the execution of a larger pro-
‘gram. The subroutine could be written into the body of the main program everywhere itis
needed, resulting in the fastest possible code execution. Using a subroutine in this manner
has several serious drawbacks.
‘Common practice when writing a large program is to divide the total task among
many programmers in order to speed completion. The entire program can be broken into
smaller parts and each programmer given a part to write and debug. The main programJUMP AND CALLOPCODES 93.
can then call each of the parts, or subroutines, that have been developed and tested by each
individual of the team.
Even if the program is written by one individual, itis more efficient to write an oft-used
routine once and then call it many times as needed. Also, when writing a program, the
programmer does the main part first. Calls to subroutines, which will be written later,
‘enable the larger task to be defined before the programmer becomes bogged down in the
details of the application.
Finally, it is quite common to buy “libraries” of common subroutines that can be
called by a main program. Again, buying libraries leads to faster program development
Calls and the Stack
A call, whether hardware or software initiated, causes a jump to the address where the
called subroutine is located. At the end of the subroutine the program resumes operation at
the opcode address immediately following the call. As calls can be located anywhere in
the program address space and used many times, there must be an automatic means of
storing the address of the instruction following the call so that program execution can
continue after the subroutine has executed.
‘The stack area of internal RAM is used to automatically store the address, called the
return address, of the instruction found immediately after the call. The stack pointer regis
ter holds the address of the Jast space used on the stack. It stores the return address above
this space, adjusting itself upward as the return address is stored. The terms “stack” and
“stack pointer” are often used interchangeably to designate the top of the stack area in
RAM that is pointed to by the stack pointer.
Figure 6.2 diagrams the following sequence of events:
1, A call opcode occurs in the program sofiware, or an interrupt is generated in the
hardware circuitry.
2, The return address of the next instruction after the call instruction or interrupt is
found in the program counter.
3. The return address bytes are pushed on the stack, low byte first
4. The stack pointer is incremented for cach push on the stack.
5. The subroutine address is placed in the program counter.
6. The subroutine is executed
7, A RET (return) opcode is encountered at the end of the subroutine
FIGURE 6.2 Storing and Retrieving the Return Address
Program Counter
[ew [me
T T
! 1
ee Pd PCH sP+2—e— ot 4
po parat3 EES
[etm] t* vt
Ee
Interrupt Internal RAM94
CHAPTER SIX
8, Two pop operations restore the return address to the PC from the stack area in
internal RAM.
9. The stack pointer is decremented for each address byte pop.
All of these steps are automatically handled by the 8051 hardware. It is the responsi-
bility of the programmer to ensure that the subroutine ends in a RET instruction and that
the stack does not grow up into data areas that are used by the program.
Calls and Returns
Calls use short- or long-range addressing: returns have no addressing mode specified but
are always long range. The following table shows examples of call opcodes:
Mnemonic Operation
ACALL sadd Call the subroutine located on the same page as the address of the
‘opcode immediately following the ACALL instruction; push the
address of the instruction immediately after the call on the stack
LCALL ladd Call the subroutine located anywhere in program memory space; push
the address of the instruction immediately following the call on
the stack
RET Pop two bytes from the stack into the program counter
Note that no flags are affected unless the stack pointer has been allowed to erroneously
reach the address of the PSW special-function register.
Interrupts and Returns
‘As mentioned previously, an interrupt is a hardware-generated call. Just as a call opcode
‘can be located within a program to automatically access a subroutine, certain pins on the
8051 can cause a call when external electrical signats on them go to a low state. Internal
‘operations of the timers and the serial port can also cause an interrupt call to take place.
The subroutines called by an interrupt are located at fixed hardware addresses dis-
cussed in Chapter 2. The following table shows the interrupt subroutine addresses.
INTERRUPT — ADDRESS (HEX) CALLED
i) 0003
FO 0008
let 0013
TH 0018
SERIAL 0023
When an interrupt call takes place, hardware interrupt disable flip-flops are set to pre-
vent another interrupt of the same priority fevel from taking place until an interrupt return
instruction has been executed in the interrupt subroutine. The action of the interrupt rou-
tine is shown in the table below.
Mnemonic Operation
RETI Pop two bytes from the stack into the program counter and reset the
imerrupt enable flip-flops
Note that the only difference between the RET and RET! instructions is the enabling
of the interrupt logic when RETI is used. RET is used at the ends of subroutines called by
an opcode. RETI is used by subroutines called by an interrupt.JUMP AND CALLOPCODES «95,
The following program example use a call to a subroutine.
ADDRESS: MNEMONIC (COMMENT
MAIN: MOV 81h, #30h ;set the stack pointer to 30h in RAM
LCALL SUB ;push address of NOP; PC = #SUB; SP = 32h
NOP sreturn from SUB to this opcode
SUB: MOV A, #45h ;SUB loads A with 45h and returns
RET ;pop return address to PC; SP = 30h
f CAUTION
Set the stack pointer above any area of RAM used for additional register banks or data memary.
‘The stack may only be 128 bytes maximum: which limits the numberof successive calls with no
returns to 64
Using RETI at the end of a software called subroutine may enable the interrupt logic erroneously,
To jump out of a subroutine (not recommended), adjust the stack for the two return address:
bytes by POPing it twice or by moving data to the stack pointer to reset it to its original value.
Use the LCALL instruction if your subroutines are normally placed at the end of your program.
In the following example of an interrupt call to a routine, timer is used in mode 0 to
overflow and set the timer 0 interrupt flag. When the interrupt is generated, the program
vectors to the interrupt routine, resets the timer 0 interrupt flag, stops the timer, and returns
ADDRESS MNEMONIC COMMENT
ORG 0000h ;begin program at 0000
AJMP OVER jump over interrupt subroutine
.ORG OOOBh put timer 0 interrupt subroutine here
CLR 8Ch ;stop timer 0; set TRO 0
RETI ;return and enable interrupt structure
OVER MOV OA8h, #82h jenable the timer 0 interrupt in the IE
MOV 89h, #00h ;set timer operation, mode 0
MOV 84h, #00h clear TLO
MOV 8Ch, #00h clear THO
SET 8Ch start timer 0; set TRO = 1
;the program will continue on and be interrupted when the timer has
jtimed out
CAUTION
+
Example
‘The programmer must enable any interrupt by setting the appropriate enabling bits in the IE
register.
Problems
‘We now have all of the tools needed to write powerful, compact programs. The addition of
the decision jump and call opcodes permits the program to alter its operation as it runs.96 CHAPTER six
(_] exampte prostem 6.1
ADDRESS
ONE
DONE,
ADDRESS
TRO
ADDRESS
THREE
Place any number in internal RAM location 3Ch and increment it until the number equals
2Ah.
= Thoughts on the Problem The number can be incremented and then tested to see
whether it equals 2Ah. If it does, then the program is over: if not, then loop back and
decrement the number again.
Three methods can be used to accomplish this task.
= Method 1:
MNEMONIC = COMMENT
CLR C :this program will use SUBB to detect equality
MOV A,#2An —:put the target number in A
SUBB A,3Ch —; subtract the contents of 3Ch; C is cleared
JZ DONE :if A = 00h, then the contents of 3Ch = 2Ah
INC 3Ch rif A is not zero, then loop until it is
SUMP ONE :loop to try again
NOP rwhen finished, jump here and continue
—l>— coMMENT
‘As there is no compare instruction for the 8051, the SUBB instruction is used to compare A
against a number. The SUBB instruction subtracts the C flag also, so the C flag has to be cleared
before the SUBB instruction is used.
= Method 2:
MNEMONIC COMMENT
INC 3h :incrementing 3Ch first saves a jump later
MOV A,#24h this program will use XOR to detect equality
XRL A,3Ch :KOR with the contents of 3Ch: if equal, A = 00h
INZ THO ;this jump is the reverse of program one
NOP ;finished when the jump is false
—[>— commeENT
‘Many times if the loop is begun with the action that is to be repeated until the loop is satisfied,
only one jump, which repeats the loop, is needed.
= Method 3:
MNEMONIC COMMENT
INC 3Ch begin by incrementing the direct address
MOV A, #2An this program uses the very efficient CJUNE
CJNE A,3Ch, THREE ; jump if A and (3Ch) are not equal
NOP jall done
—[>— COMMENT
CINE combines a compare and a jump into one compact instruction.
Q EXAMPLE PROBLEM 6.2
‘The number AGh is placed somewhere in external RAM between locations 0100h and
0200h. Find the address of that location and put that address in R6 (LSB) and R7 (MSB).JUMP AND CALLOPCODES «97
= Thoughts on the Problem The DPTR is used to point to the bytes in external memory,
and CINE is used to compare and jump until a match is found.
ADDRESS = MNEMONIC
MOV 20h, #0A6h
MOV DPTR, #00FFh
MOR: INC DPTR
MOVX A, @DPTR
CJNE A,20h,MOR
MOV RT,83h
MOV R6,82h
COMMENT
sload 20h with the number to be found
start the DPTR below the first address
sincrement first and save a jump
:get a number from external memory to A
:compare the number against (20h) and
sloop to MOR if not equal
smove DPH byte to R7
smove DPL byte to R6;
finished
—C>— comment
This program might loop forever unless we know the number will be found; a check to see
whether the DPTR has exceeded 0200h can be included to leave the loop if the number is not
found before DPTR = 0201h,
EXAMPLE PROBLEM 6.3
Find the address of the first two internal RAM locations between 20h and 60h which con-
tain consecutive numbers. If so, set the carry flag to I, else clear the flag.
‘= Thoughts on the Problem A check for end of memory will be included as a Called
routine, and CJNE and a pointing register will be used to search memory.
ADDRESS = MNEMONIC
MOV 81h, #65h
MOV RO, #20h
NXT: MOV A,@RO
INC A
MOV 1Fh,A
INC RO
CALL DUN
JNC THRU
MOV A,@RO
CJNE A, 1Fh, NXT
SETB OD7h
SJMP THRU
PUSH A
CLR C
MOV A, #61n
XRL A.RO
JNZ BCK
RET
BCK POP A
cPL C
RET
THRU:
DUN:
COMMENT
rset the stack above memory area
pload RO with address of memory start
:get first number
rincrement and compare to next number
store incremented number at 1Fh
;point to next number
isee if RO greater than 60h
:DUN returns C = 0 if over 60h
iget next number
:if not equal then look at next pair
rset the carry to 1; finished
:jump here if beyond 60h
save A on the stack
relear the carry
suse XOR as a compare
2A will be 0 if equal
:if not 0 then continue
;A 0, signal calling routine
iget A back
;A not 0, set C to indicate not done
{[>— COMMENT
Set the stack pointer to put the stack out of the memory area in use.98 CHAPTER SIX
Summary
Jumps
Jumps alter program flow by replacing the PC counter contents with the address of the
jump address. Jumps have the following ranges:
Relative: up to PC +127 bytes, PC —128 bytes away from the PC
Absolute short: anywhere on a 2K-byte page
‘Absolute long: anywhere in program memory
Jump opcodes can test an individual bit, or a byte, to check for conditions that make
the program jump to a new program address. The bit jumps are shown in the following
table:
INSTRUCTION TYPE RESULT
IC radd Jump telative if carry flag set to 1
INC rad Jump celative if carry fiag cleared to 0
8 badd Jump relative if addressable bit set to 1
JNB b,radd Jump relative if addressable bit cleared to 0
JBC bradd Jump relative if addressable bit set to 1 and clear bit to 0.
Byte jumps are shown in the following table:
INSTRUCTION TYPE RESULT
CINE destination source,address ‘Compare destination and source: jump to address if
not equal
DINZ destination address Decrement destination by one; jump to address if
the result is not zero
SZ rad Jump A = 00h to relative address
INZ rad Jump A > 00h to relative address
Unconditional jumps make no test and are always made. They are shown in the fol-
lowing table:
INSTRUCTION TYPE RESULT
IMP @A+DPTR Jump to 16-bit address formed by adding A to the DPTR
AMP sadd Jump to absolute short address
UMP ladd Jump to absotute long address
SIMP radd Jump to relative address
NOP Bo nothing and go to next opcode
Call and Return
Software calls may use short- and long-range addressing; returns are to any long-range
address in memory. Interrupts are calls forced by hardware action and call subroutines
located at predefined addresses in program memory. The following table shows calls and
returns:
INSTRUCTION TYPE RESULT
ACALL sadd Call the routine located at absolute short address
LCALL lad Call the routine located at absolute long address
RET Return to anywhere in the program at the address found on the
top two bytes of the stack
ReTI Retum from a routine called by a hardware interrupt and reset
the interrupt fogicJUMP AND CALL OPCODES «99
Problems
Write programs for each of the following problems using as few lines of code as you can.
Place comments on each line of code.
1. Put a random number in R3 and increment it until it equals E1h.
2. Put a random number in address 20h and increment it until it equals a random number
put in RS.
3. Put a random number in R3 and decrement it until it equals Eth.
4, Put a random number in address 20h (LSB) and 21h (MSB) and decrement them as if
they were a single 16-bit counter until they equal random numbers in R2 (LSB) and
R3 (MSB).
5. Random unsigned numbers are placed in registers RO to R4. Find the largest number and
put it in RO,
6. Repeat Problem 3, but find the smallest number.
7. If the lower nibble of any number placed in A is larger than the upper nibble, set the
C flag to one: otherwise clear it
8 Count the number of ones in any number in register B and put the count in RS,
9. Count the number of zeroes in any number in register R3 and put the count in RS.
10. If the signed number placed in R7 is negative, set the carry flag to 1; otherwise clear it.
11, Increment the DPTR from any initialized value to ABCDh.
12. Decrement the DPTR from any initialized value to 0033h,
13. Use R4 (LSB) and RS (MSB) as a single 16-bit counter, and decrement the pair until
they equal 0000h.
14, Get the contents of the PC to the DPTR.
15. Get the contents of the DPTR to the PC.
16. Get any two bytes you wish to the PC.
V.
Write a simple subroutine, call it, and jump back to the calling program after adjusting
the stack pointer.
18. Put one random number in R2 and another in RS. Increment R2 and decrement RS untit
they are equal
19, Fill external memory locations 100h to 200h with the number AA.
20. Transfer the data in internal RAM locations 10h to 20h to internal RAM locations 30h
to 40h.
21, Set every third byte in internal RAM from address 20h to 7Fh to zero,
22. Count the number of bytes in external RAM locations 100h to 200h that are greater than
the random unsigned number in R3 and less than the random unsigned number in R4.
Use registers R6 (LSB) and R7 (MSB) to hold the count.
23, Assuming the crystal frequency is 10 megahertz, write a program that will use timer 1 to
interrupt the program after a delay of 2 ms.
24, Put the address of every internal RAM byte from 50h to 70h in the address; for instance,
internal RAM location 6Dh would contain 6Dh
25, Put the byte AAh in all internal RAM locations from 20h to 40h, then read them back
and set the carry flag to 1 if any byte read back is not AA.CHAPTER
oo
Zip
An 8051 Microcontroller Design
Chapter Outline
Introduction Timing Subroutines
A Microcontroller Specification Lookup Tables for the 8051
A Microcontroller Design Serial Data Transmission
Testing the Design Summary
Introduction
Jn this chapter a hardware configuration for an 8051 microcontroller, which wilt be used
for all of the example applications in Chapters 8 and 9, is defined. Programs that check the
initial prototype of the design (debugging programs) are given in this chapter, followed by
several common subroutines that can be used by programs in succeeding chapters.
The design of the microcontrotler begins with an identified need and a blank piece of
paper or computer screen. The evolution of the microcontroller follows these steps:
1, Define a specification.
2. Design a microcontroller system to this specification.
3. Write programs that will assist in checking the design.
4, Write several common subroutines and test them.
‘The most important step is the first one. If the application is for high-volume produc-
tion (greater than 10,000 units), then the task must be very carefully analyzed. A precise
or “tight” specification is evolved for what will become a major investment in factory-
programmed parts. As the volume goes down for any particular application, the specifica-
tions become more general as the designers attempt to write a specification that might fit a
100 wider range of applications.‘AN 8051 MICROCONTROLLER DESIGN 104
The list leaves out a few real-world steps, most notably the redesign of the micro-
controller after itis discovered that the application has grown beyond the original specif
cation or, as is more common, the application was not well understood in the beginning.
Experienced designers learn to add a little “fat” to the specification in anticipation of the
inexorable need for “one more bit of 1/O and one more kilobyte of memory.”
A Microcontroller Specification
A typical outline for a microcontroller design might read as fotlows:
““A requirement exists for an intelligent controller for real-time control and data moni
toring applications. The controller is part of a networked system of identical units that are
connected to a host computer through a serial data link. The controller is to be produced in
low volumes, typically less than one thousand units for any particular application, and it
must be low cost.””
The 8051 family is chosen for the following reasons:
Low part cost
Multiple vendors
Available in NMOS and CMOS technologies
Software tools avaitable and inexpensive
High-level language compilers available
The first three items are very important from a production cost standpoint. The soft-
ware aids available reduce first costs and enable projects to be completed in a timely
manner.
The low-volume production requirement and the need for changing the program to fit
particular applications establish the necessity of using external EPROM to hold the appli-
cation program. In turn, ports 0 (ADO—AD7) and 2 (A8—A15) must be used for inter-
facing to the external ROM and will not be available for I/O.
Because one possible use of the controller will be to gather data, RAM beyond that
available internally may be needed. External RAM is added for this eventuality, The
immediate consequence of this decision is that port 3 bits 6 (WR) and 7 (RD) are needed
for the external RAM and are not available for 1/0. External memory uses the 28-pin
standard configuration, which enables memories as large as 64K to be inserted in the
memory sockets.
Commercially available EPROM parts that double in size beginning at 2K bytes can
be purchased. The minimum EPROM size selected is 8K and the maximum size is 64K.
These choices reflect the part sizes that are most readily available from vendors and parts
that are now beginning to enter high-volume production.
Static RAM parts are available in 2K, 8K, and 32K byte sizes; again, the RAM sizes,
are chosen to be 8K or 32K to reflect commercial realities. The various memory sizes can
be incorporated by including jumpers for the additional address lines needed by largct
memories and pullup resistors to enable alternate pin uses on smaller memories.
The serial data needs can be handled by the internal serial port circuitry. Once again,
two more I/O pins of port 3 are used: bits 3.0 (RXD) and 3.1 (TXD). We are left with all
of port I for general-purpose I/O and port 3 pins 2~5 for general-purpose 1/0 or for exter-
nal interrupts and timing inputs.
Note that rapid loss of 1/O capability occurs as the alternate port functions are used ari!
should be expected unless volumes are high enough to justify factory-programmed parts.102
CHAPTER SEVEN
The handicap is not as great as it appears, however: two methods exist that are commonly
used to expand the 1/O capability of any computer application: port I/O and memory-
mapped 1/0.
Finally, we select a 16 megahertz crystal to take advantage of the latest high-speed
devices available, and the specification is complete. To summarize, we have
80C31-1 (ROMIess) microcontroller
GAK bytes of external EPROM
32K bytes of external RAM
8 general-purpose 1/0 lines
4 general-purpose or programmable I/O lines
| full-duplex serial port
16 megahertz crystal clock
Now that the specification is complete, the design can be done.
A Microcontroller Design
‘The final design, shown in Figure 7.1, is based on the external memory circuit found in
Chapter 2. Any 1/O circuitry needed for a particular application will be added to the basic
design as required, A design may be done in several ways; the choices made for this design
are constrained by cost and the desire for flexibility,
External Memory and Memory Space Decoding
External memory is added by using port 0 as a data and low-order address bus, and port 2
as a high-order address bus. The data and low addresses are time multiplexed on port 0.
An external 373 type address latch is connected to port 0 to store the low address byte
whenever external memory is accessed, The low-order address is gated into the trans-
parent latch by the ALE pulse from the 8051. Port O then becomes a bidirectional data bus
during the read or write phase of a machine cycle.
RAM and ROM are addressed by entirely different control lines from the 8051: PSEN
for the ROM and WR or RD for the RAM. The result is that each occupies one of two.
parallel 64 kilobyte address spaces. The decoding problem becomes one of simply adding
suitable jumpers and pullup resistors so that the user can insert the memory capacity
needed. Jumpers are inserted so that the correct address line reaches the memory pin or
the pin is pulled high as required by the memory used. The jumper table in Figure 7.1 for
the EPROM and RAM memories that can be inserted in the memory sockets shows the
jumper configuration. Figure 7.2 graphically demonstrates the relative sizes of the internal
and external memories available to the programmer.
Reset and Clock Circuits
“The 8051 uses an active high reset pin, The reset input must go high for two machine
cycles when power is first applied and then sink low. The simple RC circuit used here will
supply system voltage (Vcc) to the reset pin until the capacitor begins to charge. At a
threshold of about 2.5 V, the reset input reaches a low level, and the system begins to run.
Internal reset circuitry has hysteresis necessitated by the slow fall time of the RC circuitAN 8051 MICROCONTROLLER DESIGN 103.
FIGURE 7.1 8031 Microcontroller with External ROM and RAM
oe wee
279M
iaunc,
bl acaicee
erro rane
pane east 0
Pi180 226.020
on on
Psion :
a
5
6
35 asm 7
aa Shiceo ae a
23 se ag 3
32 eer as 10
3m a 1817161513121 3918173635131211
al 30 o7 30
a01
2
wy 3 106
ise x ou
rent =
14 PS reat pono 38 ist
aos ” a
na? x
wi 5 » Ag
cto me Tate
oH Tenoyse | ro [a
ar ope ——| Rone
Reset 16K a NAL
4 ak sigs
95.1 maaan ar wea [we
The addition of a reset button enables the user to reset the system without having to turn
power off and on.
‘The clock circuit of Chapter 2 is added, and the design is finished.
Expanding 1/0
Ports | and 3 can be used (0 form small control and bidirectional data buses. The data
bbuses can interface with additional external circuits to expand 1/0 up to any practical
number of lines.104 CHAPTER SEVEN
FIGURE 7.2 8031 Memory Sizes
External ROM
(0000 to FFF
External RAM
0000h to 7FFFh
Joternal RAM
‘00h toFFh
Mov Movt @ Program ROM
Move @
‘There are many popular families of programmable port chips. The one chosen here is
the popular 8255 programmable interface adaptor, which is available from a number of
vendors, Details on the full capabilities of the 8255 are given in Appendix D. The 8255
has an internal mode register to which control words are written by the host computer.
These control words determine the actions of the 8255 ports, named A, B, and C, enab-
Jing them to act as input ports, output ports, or some combination of both.
Figure 7.3 shows a circuit that adds an 8255 port expansion chip to the design. The
number of ports is now three B-bit ports for the system. The penalty paid for expanding
/O in this manner is a reduction in speed that occurs due to the overhead time needed to
write control bits to ports 1 and 3 before the resulting 1/0 lines selected can be accessed.
‘The advantage of using I/O port expansion is that the entire range of 8051 instructions can
be used to access the added ports via ports 1 and 3.
Memory-Mapped I/O
The same programmable chip used for port expansion can also be added to the RAM
memory space of the design, as shown in Figure 7.4. The present design uses only 32K of‘AN 8051 MICROCONTROLLER DESIGN 105
FIGURE 7.3 Expanding /O Using 8031 Ports
4 pro
6 ak eat
3 aE re
9 1h Pag
aid 8 40 -— Pad
5 39} PAS
36 38 Pas
a7 Paz
34 18 = P80
33 19 Pal
32 20 f= Pez
318285 21 a3
peer rett 30 22 Ba
29 23 PBs
28 2a L PR6
27 25 | P87
14 L Poo.
15 ec
16 L pce
17 Pcs
13 Poa
12 Fees,
Al F— Pce.
to cr
the permitted 64K of RAM address space: the upper 32K is vacant. The port chip can be
addressed any time AIS is high (8000h or above), and the 32K RAM can be addressed
whenever A15 is low (7FFFh and below). This decoding scheme requires only the addi-
tion of an inverter to decode the memory space for RAM and 1/0.
‘Should more RAM be added to the design, a comprehensive memory-decoding scheme
will requite the use of a programmable array-type decoder to reserve some portion of mem-
ory space for the 1/0 port chips. Figure 7.4 shows a design that permits the addition of three
‘memory-mapped port chips at addresses FFFOh—FFF3h, FFF4h—FFF7h, FFF8h—FFFBh
and FFFCh—FFFFh. RAM is addressable from 0000h to FFEFh.
Memory-mapped I/O has the advantage of not using any of the 8051 ports. Disadvan-
tages include the loss of memory space for RAM that is used by the 1/O address space, or
the addition of memory decoding chips in order to limit the RAM address space loss
Programming overhead is about the same as for port 1/O because only the cumbersome
MOVX instruction may be used to access the memory-mapped 1/0.
For both types of 1/0 expansion, the cost of the system begins to mount. At some
point, a conventional microprocessor, with a rich set of 1/O and memory instructions.
may become a more economical choice.106 CHAPTER SEVEN
FIGURE 7.4 Expanding /O Using Memory Mapping
ToRAN TS Pn
&
as a eso as 4
6 aE pat ata
fest set I, tem Ma]
8051 —»— E
‘Adsress Bus a aL 2 Ihe pas aes
Pa? a cy aol rae a
pa? o—e——s 39, pas Mom} yaa | rrrce
we 36 38f— as wo] ns Frr¥83 tppess
37k ear ws] sry LE rra ‘esPin
i wwe Peto
00 oo Py 18} P80 6
201 ot 33 19 pan s—|
oz oe 32 20-— vez a
50st 03 = 31 21f Pes a
raaendramn og yg oe
0s, a 23 23; Pes
N06 8 2 | pee tea
toy 23 ol mee banal Lai
vat eco 8
35F per
wh ree ox
vk pcs
13 poe
Bee vo
TE Pos
toh pcr HF T
£8255 Connections Fr Memany Mapping :
Reset Celt
Part Speed
‘One consideration, that does not appear on the design drawings, is the selection of parts
that will work atthe system speeds determined by the crystal frequency. All memory parts
are priced according to the nanosecond of access time. The longer the access time (the
time it takes for a byte of data to be read or written from or to the device after the address
is valid), the cheaper the part. For our design, Figure 7.4 shows the timing involved in
reading data from the ROM and reading and writing data to the RAM. These times are
totally determined by the selection of the crystal frequency, and the designer must choose
‘memory parts that are fast enough to keep up with the microcontroller at the chosen fre-
quency. For our example, EPROMS with maximum access times of 150-ns and RAM with
access times of 400 ns must be used. These access times are representative of standard
commercial types currently available at the low end of the cost spectrum. These times are
worst-case times; actual access times are at least 30 percent longer.
Other parts, such as the °373 type latch can be any family from LSTTL to HCMOS.
‘The speeds of these parts far exceed the speed of the 8051
Production Concerns
The design omits many features that would be incorporated by a design-manufacturing
team. Chief among these are the inclusion of test-points, LED indicators, and other items
that should be added to enhance manufacturing and field service of the microcontroller.‘AN 8051 MICROCONTROLLER DESIGN 107.
These concerns are well beyond the scope of this book, but the wise designer always
ensures that the legitimate concerns of the technical, manufacturing, and service depart-
ments are addressed.
Testing the Design
ADDRESS
begin:
add2:
add3:
adda:
adds:
add:
‘Once the hardware has been assembled, it is necessary to verify that the design is correct,
and that the prototype is built to the design drawing. This verification of the design is done
by running several small programs, beginning with the most basic program and building
on the demonstrated success of each.
Crystal Test
The initial test is to ensure that both the crystal and the reset circuit are working. The 8051
is inserted in the circuit, and the ALE pulse is checked with an oscilloscope to verify that
the ALE frequency is 1/6 of the erystal frequency. Next, the resct button is pushed, and
all ports are checked to see that they are in the high (input) state
ROM Test
The most fundamental program test is to ensure that the microcontroller can fetch and
execute programs from the EPROM. Code byte fetching can be tested by verifying that
each address line of the ROM is properly wired by using a series of repeated jump instruc-
tions that exercise all of the address lines. The test used here will jump to addresses that
are a power of two. Only one address line will be high, and all of the rest will be low. The
address pattern tests for proper wiring of each address line and also checks for shorts
between any two lines.
If the test is successful, the program stops at the highest possible ROM address. The
address bus can then be checked with a logic probe to verify that the highest address has
been reached. Correct operation is indicated by the highest order address bus bit, which
will appear constant. If not, the probe will blink indicating random program fetches.
The test is run by inserting the "373 latch, the programmed 64K EPROM, inserting
jumpers 1-3 and resetting the 8051. The test can be stopped at any address by jumping to
that address, as is done in the last statement in the following ROM test program:
MNEMONIC COMMENT
org 0000h =; start at the bottom of ROM
ljmp adaz test address lines AO and Al
org 0004h =; next. jump at address 0004h (A2)
ljmp adds ;test address line A2
org 0008h =: next. jump at address 0008h (A3)
ljmp adda ;test address line AS
org 0010h = ;next jump at address 0010h (A4)
jmp add5 itest address line A4
-org 0020h = ;next_ jump at address 0020h (A5)
1jmp add6 stest address line A5
org 0040h = :next_ jump at address 0040h (A6)
jmp ada? itest address line AG
-org 0080h imext jump at address 0080n (A7)
Continued108 CHAPTER SEVEN
ADDRESS = MNEMONIC COMMENT
Continued
aad? ljmp adds itest address line A7
org 0100h = ;next jump at address 0100h (A8)
add8 jmp add9 test address line Ag
-org 0200h jump at address 0200h (A9)
adag: ljmp addl0 address line A9
org 0400h jump at address 0400h (A10)
add10: jmp addl) address line Al0
org 0800h jump at address 0800n (A11)
addll 1jmp addl2 address line All
org 1000h jump at address 1000h (412)
addl2 ljmp adal3 address line al2
-org 2000h jump at address 2000h (A13)
addl3: jmp addl4 address line Al3
org 4000h jump at address 4000h (A14)
addl4 jmp add15 address line Al4
org 8000h address line Al5 and remain here
addl5 jmp adds jump here in a loop
vend jassembler use
:This address, Al5, will remain latched while A2—Al4 will
sremain low. AO and Al will vary as the bytes of the jump
rinstruction are fetched
Inspection of the listing for this program in Figure 7.5 shows that all the address lines are
exercised
RAM Test
‘Once sure of the ability of the microcontroller to execute code, the RAM can be checked. A
common test is to write a so-called checkerboard pattern to RAM—that is, an alternating
pattern of I and 0 in memory. Writing bytes of SSh or Ah will generate such a pattern
The next program writes this pattern to external RAM, then reads the pattern back
and-checks each byte read back against the byte that was written. Ifa check fails, then the
address where the failure occurred is in the DPTR register. Port | and the free bits of port 3
can then be used to indicate the contents of DPTR.
There are 14 bits available using these ports (the serial port is not in use now, so bits
3.0 and 3.1 are free), and 15 are needed to express a 32K address range. The program will
test a range of 8K bytes at a time, using 13 bits to hold the 8K. address upon failure. Four
versions have to be run to cover the entire RAM address space. If the test is passed, then
bit 14 (port 3.5) is a 1. If the test fails, then bit 14 is a 0, and the other 13 bits hold the
address (in the 8K page) at which the failure occurred.
Interestingly. this test does not check for correct wiring of the RAM address lines. As
Tong as all address lines end on some valid address, the test will work. A wiring check
requires that a ROM be programmed with some unique pattern at each address that is a
power of two and read using a check program that inspects each unique address location
for a unique pattern,
‘The RAM test program is listed on the following page.‘AN 8051 MICROCONTROLLER DESIGN 109
FIGURE 7.5 Assembled ROM Check Program
0000 org 0000h = ;start at the bottom of ROM
0000 020004 begin: 1jmp add2 jtest address lines AO and Al
0004 org 0004h =; next. jump at address 0004h (A2)
0004 020008 ada2: jmp add3 :test address line A2
0008 -org 0008h = :next jump at address 0008h (A3)
0008 020010 adds: jmp adda rtest address line A3
0010 -org 0010h = :next jump at address 0010n (A4)
0010 020020 ada4: 1 jmp add5 ;test address line Ad
0020 ,org 0020h = next jump at address 0020h (A5)
0020 020040 adds: jmp addé itest address line AS
0040 .org 0040h — ;next jump at address 0040h (A6)
0040 020080 add6: jmp add7 stest address line A6
0080 -org 0080h — :next jump at address 0080h (A7)
0080 020100 ada7: ljmp adds itest address line AT
0100 org 0100h = next jump at address 0100h (A8)
0100 020200 addé: jmp ada9 ;test address line A8
0200 -org 0200h =; next. jump at address 0200n (A9)
0200 020400 addg: jmp addl0 —; test address line A9
0400 :org 0400h = ;next jump at address 0400h (A10)
0400 020800 addl0: jmp addll —s; test address line Al0
0800 org O800h =; next. jump at address 0800h (A11)
0800 021000 addll: 1jmp addl2 —s; test. address line All
1000 :org 1000h = :next jump at address 1000h (A12)
1000 022000 addi2: 1jmp addl3_—; test address line Al2
2000 -org 2000h =: next. jump at address 2000h (413)
2000 024000 addl3: 1jmp addl4_—s; test address line A13
4000 -org 4000h =; last jump at address 4000n (A14)
4000 028000 addl4: 1jmp addl5 —s; test address line Al4 and remain
8000 vorg 8000h —; test. address line Al5 and remain
jhere
8000 028000 addi5: jmp addl5 =; jump here in a loop
8003 end sassembler use
ADDRESS = MNEMONIC COMMENT
-equ ramstart,0000h :set RAM test start address
-equ rmstphi,20h :set RAM test high stop address
-equ pattern, 55h jdetermine test pattern
equ good, 20h ;RAM good pattern P3.5 = 1
-equ bad, Odfh ;RAM bad pattern, P3.5 = 0
-org 0000h jbegin test program at 0000h
mov p3,#0ffh :set Port 3 high
mov dptr,#ramstart sinitialize DPTR
test: mov a,#pattern rset pattern byte
movx @dptr.a iwrite byte to RAM
Continued110 CHAPTER SEVEN
ADDRESS MNEMONIC COMMENT
Continued
inc dptr ;point to next RAM byte
mov a,#rmstphi ieheck to see if at stop address
cjne a,dph, test ;if not then loop until done
mov dptr,#ramstart :start read-back test
check: movx a,@dptr iread byte from RAM
cjne a,#pattern.fail ;test against what was written
inc dptr :go to next byte if tested ok
mov a,#rmstphi icheck to see if all bytes tested
cjne a,dph,check ;if not then check again
mov pS, #g000 jchecked ok, set Port 3 to good
here: sjmp here istop here
fail: mov p3,dph itest failed, get address
anl p3,#bad iset 3.5 to zero
nov pl,dpl ;set Port 1 to low address byte
there sjmp there ;stop there
end
—>— comment ————
‘Change the ramstart and rmstphi equ hex numbers to check pages 2000h to 3FFFh, 4000h to
SFFFh, and 6000h to 7FFFH.
Note that a full 16-bit check for end of memory does not have to be done due to page bounda-
fies of (20)00, (40300, (60)00, and {80}00h,
There is no halt command for the 8051; jumps in place serve to perform the halt function.
We have now tested all the external circuitry that has been added to the 8051. The
remainder of the chapter is devoted to several subroutines that can be used by the applica-
tion programs in Chapters 8 and 9.
Timing Subroutines
‘Subroutines are used by call programs in what is known as a “transparent” manner—that
is, the calling program can use the subroutines without being bothered by the details of
what is actually going on in the subroutine. Usually, the call program preloads certain
locations with data, calls the subroutine, then gets the results back in the preload locations.
“The subroutine must take great care to save the values of all memory locations in the
system that the subroutine uses to perform internal functions and restore these values be-
fore returning to the call program. Failure to save values results in occasional bugs in the
main program. The main program assumes that everything is the same both before and
after a subroutine is called.
Finally, good documentation is essential so that the user of the subroutine knows pre-
cisely how (0 use it
Time Delays
Perhaps the most-used subroutine is one that generates a programmable time delay. Time
delays may be done by using software loops that essentially do nothing for some period,
‘or by using hardware timers that count internal clock pulses.ADDRESS
softine
ok:
timer:
onemil
AN 8051 MICROCONTROLLER DESIGN 117
‘The hardware timers may be operated in either a software or a hardware mode. In the
software mode, the program inspects the timer overflow flag and jumps when it is set. The
hardware mode uses the interrupt structure of the 8051 to generate an interrupt to the pro-
gram when the timer overflows.
‘The interrupt method is preferred whenever processor time is scarce. The interrupt
mode allows the processor to continue to execute useful code while the time delay is
taking place. Both the pure software and timer-software modes tie up the processor while
the delay is taking place.
If the interrupt mode is used, then the program must have an interrupt handling rou-
tine at the dedicated interrupt program vectot location specified in Chapter 2. The program
must also have programmed the various interrupt control registers. This degree of “non-
transparency” generally means that interrupt-driven subroutines are normally written by
the user as needed and not used from a purchased library of subroutines.
Pure Software Time Delay
‘The subroutine named “‘softime" generates detays ranging from 1 to 65,535 milliseconds
by using register R7 to generate the basic | millisecond delay. The call program loads the
desired delay into registers A (LSB) and B (MSB) before calling Softime,
The key to writing this program is to calculate the exact time each instruction will
take at the clock frequency in use. For a crystal of 16 megahertz, each machine cycle
(12 clock pulses) is
12 pulses
Cycle Time = = pulses __
‘yele Time * 76,000,000 pulses/s
= 75 ws
Should the crystal frequency be changed, the subroutine would have to have the internal
timing loop number “delay” changed.
Softime
Softime will delay the number of milliseconds expressed by the binary number, from 1 to
65,535d, found in registers A (LSB) and B (MSB). The call program loads the desired
delay into registers A and B and calls Softime. Loading zeroes into A and B results in an
immediate return.
‘The number after the comma in the comments section of the following program is the
number of cycles for that instruction.
MNEMONIC COMMENT
-equ delay,dech ;for 996 ws time delay = 2224
-org 0000h iset origin
push O7h isave R7
push ace isave A for A = B = 00 test
orl a,b :will be 00 if both 00
ojne a,#00h,ok — : return if all 00
pop ace rkeep stack balanced
sjmp done
Pop acc not all zeroes, proceed
mov r7,#delay sinitialize R7, 1
nop ;tune the loop for 6 cycles
nop ithis makes 2 cycles total, 1
nop cycles total, 1
Continued412 ciaprer seven
ADDRESS — MNEMONIC COMMENT
Continued
nop | :4 cycles total, 1
djnz ‘'7,onemil —_; count R7 down; 6 cycles total, 2
itotal delay is 6 cycles (4.5 us) x 222d = 999d us
bdown,
done
4
nop ;tune subroutine .75 4s more
total delay is 999.75 ys, which is as close as possible for the
frequency used (1000 us ~ 4000/3 cycles)
djnz acc.timer ;count A and B down as one
cjne a,b. bdown = 00, count B down until = 00
sjmp done if so then delay is done
dec b ount B down and time again
sjmp timer
pop 07h restore R7 to original value
ret return to calling routine
vend
COMMENT
Note that register A, when used in a defined mnemonic is used as “A.” When used as a direct,
address in a mnemonic (where any add could be used), the equate name ACC is used. The
equate usage is also seen for R7, where the name of the register may be used in those mne-
monics for which itis specifically defined. For mnemonics that use any add, the actual address
must be used
The restriction on A = B = 00 is due to the fact that the program would initially count A from
00... FH. . .00 then exit. if it were desired to be able to use this initial condition for A and B,
then an all zero condition could be handled by the test for 0000 used, set a flag for the condi
tion, decrement 8 from 00 to FFh the first time B is decremented, then reset the flag for the
remainder of the program.
‘The accuracy of the program is poorest for a 1 millisecond delay due to time delay for the rest
of the program to set up and return. The actual delay if 0001 is passed to the subroutine is.
1014.75 microseconds or an error of 1.5 percent
Software Polled Timer
‘A delay that uses the timers to generate the delay and a continuous software flag test
(the flag is “polled” to see whether it is set) to determine when the timers have finished
the delay is given in this section. The user program signals the total delay desired by pass-
ing delay variables in the A and B registers in a manner similar to the pure software delay
subroutine. A basic interval of | millisecond is again chosen so that the delay may range
from 1 to 65,535 ms.
‘The clock frequency for the timer is the crystal frequency divided by 12, or one
machine cycle, which makes each count of the timer .75 microsecond for a 16 megahertz
crystal. A I millisecond delay gives
Count for 1000 microseconds = 1000/.75 = 1333.33 (1333)
Due to the fraction, we ean not generate a precise 1 millisecond delay using the crystal
chosen. If accurate timing is important, then a crystal frequency that is a multiple of 12ADDRESS
timer:
go
onems:
wait
dwnab:
bdown:
done:
‘AN 8051 MICROCONTROLLER DESIGN 143
must be chosen. Twelve megahertz is an excellent choice for generating accurate time
delays, such as for use in systems which maintain a time of day clock.
Timer 0 will be used to count 1333 (053Sh) internal clock pulses to generate the basic
| millisecond delay; registers A and B will be counted down as TO overflows. The timer
counts up, s0 it will be necessary to put the 2's complement of the desired number in the
timer and count up until it overflows.
Timer
The time delay routine named “Timer” uses timer O and registers A and B to generate
delays from 1 to 65,535d milliseconds. The calling program loads registers A (LSB) and
B (MSB) with the desired delay in milliseconds. Loading a delay of 0000h results in an
immediate return.
MNEMONIC COMMENT
equ onemshi,Ofah = ;2's complement of 535h = FACBh
equ onemslo,Ocbh
org 0000h :set program origin
push t10 rsave timer 0 contents
push thO
cjne a, #00h.go stest for A = 00
orl a,b ;A = 00, test for B = 00
jz done will be 00 if A = B = 00
clr A is not 00, clear A
anl tcon, #0cfh selear timer 0 overflow and run
flags in TCON
anl tmod, #0f0h relear TO part of TMOD, set TO for
orl tmod, #01h ;timer operation, mode 1 (16 bit)
mov t10,#onemslo et TO to count up from FACBh
mov th0, #onemshi
orl tcon, #10h :start timer 0
jbo tf0,dwnab :poll TO overflow flag
sjmp wait oop until TO overflows
anl toon, #0efh :stop TO
djnz acc, onems scount A down and loop until zero
cjne a,b, bdown sif A = B = 00 then done, return
sjmp done
dec b idecrement B and count again
sjmp onens
pop tho srestore TO contents
pop tl0
ret
end
[>— COMMENT
TO cannot be used accurately for other timing or counting functions in the user program; thus,
there is no need to save the TCON and TMOD bits for TO. T0 itself could be used to store data;
it is saved.
This program has no inherent advantage over the pure software delay program; both take up
all processor time, The software polled timer has a slight advantage in flexibility in that the
Continued114
(CHAPTER SEVEN
COMMENT
Continued
‘number loaded into TO can be easily changed in the program to shorten or lengthen the basic
timing loop. Thus, the call program could also pass the basic timing delay (in other memory
locations) and get delays that could be programmed in microseconds or hours.
‘One way for the program to continue to run while the timer times out is to have the program
loop back on itself periodically, checking the timer overflow flag. This looping is the normal
‘operating mode for most programs; if the program execution time is small compared with the
desired delay, then the error in the total time delay will be small
Pure Hardware Delay
If lengthy delays must be done or processor time is so valuable that no time can be wasted
for even relatively short software delays, then the time delays must be done using a timer
in the interrupt mode. The program given in this section operates in the following manner:
1, The occurrence of a timer overflow will interrupt the processor, which then per-
forms a hardware call to whatever subroutine is located at the dedicated timer
flag interrupt address location in ROM
2. The subroutine determines whether the time delay passed by the using program
is finished. (If not, an immediate return is done to the user program at the place
where it was interrupted. If the delay is up, then a call to the user part of the
program that needed the delay is done, followed by a return to the program
where it was interrupted.)
‘The time delay is initiated by the user program that stores the desired delay at an
external RAM location named “Savetime,"” and then calls “Startime,” which sets the
timing in motion. The main program then runs while the delay is timing out.
This type of program must use the manufacturer-specified dedicated interrupt loca-
tions in ROM that contain the interrupt handling routines. For this reason, the user must
have placed some set of instructions at the ROM interrupt location before incorporating
the time delay subroutine program in the user program.
In this example, the following three subroutines have been placed at the interrupt
location in ROM:
1, Hardtime: a subroutine located at the timer flag interrupt location that determines
whether the time delay has expired (If time has not expired, then the subroutine
immediately returns to the main user program at the location where it was inter-
rupted by the timer flag; if time is up, then it calls the user program, “Usertime.")
2. Usertime: a subroutine, written by the user, that needed the delay (For this
example, the subroutine is simply a return.)
3. Stoptime: a subroutine that stops the timer
= Note: To the assembler, the name of the subroutine can be in any combination of
uppercase ot lowercase: for example, HARDTIME, hardtime, and HaRdTiMe are all
read as the same label name.
‘The hardware delay subroutine examined here uses timer 1 for the basic delay. When
timer | overflows and sets the overflow flag, the program will vector to location 001Bh in
Program memory if the proper bits in the interrupt control registers IE and IP are set.
‘As in previous examples, the user can set timer 1 for delays of 1 to 65,535 milli-
seconds by setting the desired delay in external RAM locations ““Savetime” (LSB) and
“Savetime” + 1 (MSB), which is a two-byte address pointed to by DPTR. Registers A‘AN 8051 MICROCONTROLLER DESIGN 115,
and B cannot be used as in previous examples because to do so would preclude their use
for any other purpose in the program.
‘The hardware delay called “Hardtime” is listed in the following subsection. To avoid
confusion as to which is the subroutine and which is the user program, all user code will
begin with a label that starts with the name “User.” Everything else is the timing routine.
Hardtime
‘The “Hardtime” subroutine is a hardware-only time delay. To start the delay, IE.7 and
IE.3 (EA and ET1) must be set and the subroutine “Startime” called. Three instructions
‘must be assembled at timer | location 001Bh: LIMP hardtime, ACALL usertime (with the
label “Userdly”), and ACALL stoptime. The priority of the interrupt can be set at bit
IP.3 (PT1) to high (1) or low (0). An excerpt from the calling program follows to show
these details:
ADDRESS = MNEMONIC ‘COMMENT
-equ savetime,0010h ; external RAM address for delay
userpgm: -org 0000h pstart user program
sjmp userover :jump over interrupt addresses
-org 001bh interrupt location for TF1
jmp hardtime jump to time delay subroutine
userdly: acall usertime called if delay is up
acall stoptime idissable timer interrupt
reti jreturn to main program
userover: mov dptr,#savetime | ;point to delay address
mov a, #01h istore desired delay, LSB first
novx @dptr,a
ine dptr spoint to next byte (MSB)
mov a,#10h
movx @dptr.a :desired delay now stored
orl ie, #88h renable Tl and all interrupts
acall startime istart time delay
here: sjmp here sloop to simulate user program
jthe user program now continues while timer 1 runs until TF1 = 1.
jthe interrupt generated will vector to location 001Bh and execute
sa jump to hardtime that will decrement the contents of savetime
suntil the desired time delay has been done; hardtime will return to
he main program if the delay is not finished, or to userdly if the
sdelay is up: userdly returns to call stoptime, which stops the timer
ind returns to the RETI instruction for return to the main program
startime: mov thi, #0fah iset Tl for a 1 ms delay
mov tll, #0cbh ;(see TIMER example)
anl tmod, #0fh selear Tl part of TMOD
orl tmod, #40h sset Tl to timer mode 1
orl tcon, #40h istart timer 1
ret sreturn to calling program
hardtime: push ace jsave registers to be used
push dph
Continued116 CHAPTER SEVEN
ADDRESS
Continued
MNEMONIC
push dpl
mov dptr, #savetime
movx a,@dptr
dec a
cjne a,#00h, aff
movx @dptr,a
ine dptr
movx a,@dptr
jz done
sjmp sava
aft ejne a. #0ffh, sava
movx @dptr.a
ine dptr
movx a,@dptr
dec a
sjmp sava
done pop dpl
pop dph
Pop acc
ljmp userdly
movx @dptr,a
pop dp]
pop dph
pop ace
acall startime
reti
sava:
COMMENT
rget pointer to time delay
count delay number down to 0000
plow byte first
soheck for 0000
rsave low byte = 00
iget high byte and look for 00
;done if low, high byte = 0
jot 0, delay again
:if low byte = FF dec high
rsave low byte = FF
rpoint to high byte
:count high byte down
isave the high byte
finished, jump to userdly
irestore all registers used
;continue at user delay
:delay not up, save byte
irestore saved registers
:start Tl for next 1 ms
rreturn to user program
;the user program “usertime'' can now be written as needed; a return
;will be used to simulate the user routine.
usertime: ret
safter the user program is done then ‘stoptime'’ will stop timer Tl
rand return to the interrupted main program
anl tcon, #obfh
ret
end
stoptime:
:stop timer Tl
rreturn to reti
—>— comment
The minimum usable delay is 1 ms because a 1 ms delay is done to begin the delay interrupt
cycle.
{All timing routines can be assembled at interrupt location 00 18h if stack space is limited
The RETI instruction is used when returning to the main program, after each interrupt, while
RET instructions are used to return from called routines,
There is no check for an initial delay of 0000h,AN 8051 MICROCONTROLLER DESIGN = 117,
Lookup Tables for the 8051
There are many instances in computing when one number must be converted into another
‘number, or a group of numbers, on a one-to-one basis. A common example is to change an
ASCII character for the decimal numbers 0 to 9 into the binary equivalent (BCD) of those
numbers. ASCII 30h is used to represent 00d, 31h is Old, and so on, until ASCII 39h is
used for 09d.
Clearly, one way to convert from ASCII to BCD is to subtract a 30h from the ASCII
character. Another approach uses a table in ROM that contains the BCD numbers 00 to
09. The table is stored in ROM at addresses that are related to the ASCII character that is
tobe converted to BCD. The ASCII character is used to form part of the address where its
‘equivalent BCD number is stored. The contents of the address “pointed” to by the ASCII
character are then moved to a register in the 8051 for further use. The ASCH character is
then said to have “looked up” its equivalent BCD number.
For example, using ASCII characters 30h to 39h we can construct the following pro-
gram, at the addresses indicated, using .db commands:
ADDRESS MNEMONIC COMMENT
org 1030h = ;start table at ROM location 1030h
db 00h ocation 1030h contains 00 BCD
-db O1h ocation 1031h contains 01 BCD
db 02h location 1032h contains 02 BCD
db 03h location 1033h contains 03 BCD
db O4n location 1034h contains 04 BCD
db 05h location 1035h contains 05 BCD
db 06h location 1036h contains 06 BCD
-db O7h location 1037h contains 07 BCD
-db 08h location 1038h contains 08 BCD
-db 09h jlocation 1039h contains 09 BCD
Each address whose low byte is the ASCIE byte contains the BCD equivalent of that ASCII
byte. If the DPTR is loaded with 1000h and A is loaded with the desired ASCII byte, then a
MOVC A,@A+DPTR will move the equivalent BCD byte for the ASCII byte in A to A.
Lookup tables may be used to perform very complicated data translation feats, in-
cluding trigonometric and exponential conversions. While lookup tables require space
in ROM, they enable conversions to be done very quickly, far faster than using computa-
tional methods,
‘The 8051 is equipped with a set of instructions that facilitate the construction and use
of lookup tables: the MOVC A,@A+DPTR and the MOVC A,@A+PC. In both cases A
holds the pointer, or some number calculated from the pointer, which is also called an
“offset.” DPTR or PC holds a “base” address that allows the data table to be placed at
any convenient location in ROM. In the ASCII example just illustrated, the base address
is 1000h, and A holds an offset number ranging from 30h to 39h.
Typically, PC is used for small “local” tables of data that may be included in the
body of the program. DPTR might be used to point to large tables that are normally as-
sembled at the end of program code.
In both cases, the desired byte of data is found at the address in ROM that is equal to
base + offset. Figure 7.6 demonstrates how the final address in the lookup table is calcu-
lated using the two base registers.118
(CHAPTER SEVEN,
FIGURE 7.6 MOVC ROM Address Calculations
DPTR + FR
} __s ____|
DPTR + OIn
DPTR + 00h
A+ DPTR
‘ny Address From DPTR To DPTR + FFA PC + FH
ARegister | + DPTR = Any Number nn
PC + O28
PC + 01h
Nest Instruction | PC = NI
A+ PC = Address From NIToNI + FFh
‘A Register PC = Address 01 Next Instruction MOVCA, @A + PC
MOVCA, @A+ DPTR
MOV OPTR, #an
External ROM
Eee
One limitation of lookup tables might be the appearance that only 256 different
values—corresponding to the 256 different values that A might hold—may be put in
a table. This limitation can be overcome by using techniques to alter the DPTR such that
the base address is changed in increments of 256 bytes. The same offset in A can point
to any number of data bytes in tables that differ only by the beginning address of the
base. For example, by changing the number loaded in DPTR from 1000h to 1 100h in the
ASCII-to-BCD table given previously. the ASCII byte in A can now point to an entirely
new set of conversion bytes.
Both PC and DPTR base address programs are given in the examples that follow.
PC as a Base Address
‘Suppose that the number in A is known to be between OOh and OFh and that the number
in A is to be squared. A could be loaded into B and a MUL AB done or a local lookup
table constructed,‘AN 8051 MICROCONTROLLER DESIGN 119)
‘The table cannot be placed directly after the MOVC instruction. A jump instruction
must be placed between the MOVC and the table, or the program soon fetches the first
data byte of the table and executes it as code. Remember also that the PC contains the
address of the jump instruction (the Next Instruction, after the MOVC command) when
the table address is computed.
Pclook
‘The program “pclook” looks up data in a table that has a base address in the PC and the
offset in A. After the MOVC instruction, A contains the number that is the square of the
original number in A.
ADDRESS — MNEMONIC COMMENT
-org 0000h
pelook: — mov a, #0ah :find the square of OAh (64h)
add a, #02h sadjust for two byte sjmp over
move a,@a+pe get equivalent data from table to A
simp over :jump over the lookup table
ithe lookup table is inserted here, at PC + 2. (PC = 0005h)
db 00h sbegin table here, 00°2 = 00
db 01h 0192 = Old
db 04h ;02°2 = O4d
-db 09h 0342 = 09d
db 10h 10492 = 16d
-db 19h 0542 = 25d
-db 24h 0642 = 36d
-db 31h 10792 = 49d
-db 40h 10842 = 64d
db 51h :09°2 = Bld
100d
1zla
db 64n Oana
db 79h OBn2
db 90h 002 = 144d
db 0a9h :0D*2 = 169d
db Ocah sOBS2 = 196d
-db Oelh OF2 = 225d
over: sjmp over isimulate rest of user wrogram
end
Figure 7.7 shows the assembled listing of this program and the resulting address of the
table relative to the MOVC instruction.
{[>— COMMENT
The number added to A reflects the number of bytes in the SJMP instruction. If more code is
inserted between the MOVC and the table, a similar number of bytes must be added. Adding
bytes can result in overflowing A when the sum of these adjusting bytes and the contents of A
‘exceed 255d. If this happens, the lookup data must be limited to the number of bytes found by
subtracting the number of adjustment bytes from 255d120
‘CHAPTER SEVEN
FIGURE 7.7 Lookup Table using the PC
0000 org 0000h
0000 740A pclook: mov a,#0ah :find the square of OAh (64h)
0002 2402 add a,#02h jadjust for two byte sjmp over
0004 83 move a,@a+pe —:get_ equivalent data from table
ito A
0005 8010 sjmp over ; jump over the lookup table
0007 ;the lookup table is inserted here, at PC + 2 (PC = 0005h)
0007 00 db 00h begin table here, 00°2 = 00
0008 01 db Oth 10142 = Old
0009 04 .db 04h = Oda
000A 09 db 09h = 094
000B 10 db 10h 16a
o00c 19 db 19h = 254
oop 24 .db 24h = 36d
000E 31 db 31h = 494
oooF 40 db 40h = 64d
0010 Sl -db 51h = 81d
0011 64 db 64h ood
0012 79 .db 79h jeid
0013 90 db 90h 144d
0014 Ao -db OAS esd
0015 4 -db OC4h = 196d
0016 El db OF1h = 225d
0017 80F over sjmp over :Simulate rest of user program
0019 send
DPTR as a Base Address
‘The DPTR is used to construct a lookup table in the next example. Remove the restriction,
that the number in A must be less chan 10h and let A hold any number from OOh to FEh,
‘The square of any number larger than OFh results in a four-byte result; store the result in
registers RO (LSB) and Rt (MSB).
Two tables are constructed in this section: one for the LSB and the second for the
MSB. A points to both bytes in the two tables, and the DPTR is used to hold two base
addresses for the two tables. The entire set of two tables, each with 256 entries, will not be
constructed for this example. The beginning and example values are shown as a skeleton
of the entire table.
Dplook
The lookup table program “dplook™ holds the square of any number found in the A regis-
ter, The result is placed in RO (LSB) and R1 (MSB). A is stored temporarily in RI in order
{0 point to the MSB byte
ADDRESS — MNEMONIC COMMENT
-equ lowbyte,0200h — :base address of LSB table
equ hibyte,0300n sbase address of MSB table
org 0000h
ContinuedADDRESS
dplook:
here:
AN 8051 MICROCONTROLLER DESIGN 121
MNEMONIC COMMENT
mov a, #5ah :find the square of 5Aah (1FA4h)
nov rl.a istore A for later use
mov dptr,#lowbyte set DPTR to base address of LSB
move a,@a+dptr rget LSB
mov r0.a sstore LSB in RO
mov a.rl irecover A for pointing to MSB
mov dptr, #hibyte ;set DPTR to base address of MSB
move a,@atdptr sget MSB
mov rla ;store MSB in Rl
sjmp here imulate rest of user program
-0rg lowbyte lace LSB table starting here
db 00h :00%2 = 0000
db O1h :01%2 = 0001
rest of table up to the LSB of 59°2 here
org lowbyte + 5ah ut LSB of 5A‘2 here
db Oadh ;LSB is Adh
rest of LSB table here
.org hibyte lace MSB table starting here
db 00h 0*2 = 0000
-db 00h 142 = 0001
iplace rest of table up to the MSB of 59°2 here
org hibyte + Sah
db 1fh
ut MSB of 5A°2 here
SB is 1Fh
splace rest of MSB table here
end
—>— COMMENT
Note that there are no jumps to “get over" the tables; the tables are normally placed at the end
Of the program code.
A does not require adjustment; DPTR is a constant.
Figure 7.8 shows the assembled code; location 025Ah holds the LSB of SA®2, and
location 035Ah holds the MSB.
Serial Data Transmission
‘The hallmark of contemporary industrial computing is the linking together of multiple
processors to form a “local area network” or LAN. The degree of complexity of the LAN
may be as simple as a microcontroller interchanging data with an 1/O device, as compli-
cated as linking multiple processors in an automated robotic manufacturing cell, or as
truly complex as the linking of many computers in a very high speed, distributed system
with shared disk and 1/0 resources.
All of these levels of increasing sophistication have one feature in common: the need
to send and receive data from one location to another. The most cost-effective way to meet
this need is to send the data as a serial stream of bits in order to reduce the cost (and bulk)
of multiple conductor cable. Optical fiber bundles, which are physically small, can be
used for parallel data transmission. However, the cost incurred for the fibers, the termina-
tions, and the optical interface to the computer currently prohibit optical fiber use, except
in those cases where speed is more important than economic122 CHAPTER SEVEN
FIGURE 7.8 Lookup Table using the DPTR
0200 equ lowbyte,0200h
0300 equ hibyte,0300h
0000 org 0000h
0000 745A dplook mov a.#5ah
0002 F9
0003 900200
mov rl.a
mov dptr,#lowbyte
0006 93 move a,@a+dptr
0007 Fa mov r0,a
0008 £9 mov a,rl
0009 900300 mov dptr.#hibyte
oooc 93 move a,@atdptr
000D Fo mov rl,a
0008 80FE here sjmp here
sbase address of LSB table
sbase address of MSB table
:find the square of 5Ah
: (AFA4h)
istore A for later use
iset DPTR to base address
sof LSB
et LSB
tore LSB in RO
ecover A for pointing
0 MSB
et DPTR to base address
:of MSB
:get MSB
istore MSB in RL
imulate rest of user
iprogram
0200 org lowbyte iplace LSB table starting
rhere
0200 00 -db 00h 100°2 = 0000
0201 01 db Oh 0142 = 0001
0202 :place rest of table up to the LSB of 59°2 here
025A org lowbyte + 5ah ;put LSB of 5A‘2 here
O25A Ad db Oadh :LSB is Adh
0258 place rest of LSB table here
0300 -org hibyte :place MSB table starting
shere
0300 00 db 00h ;00°2 = 0000
0301 00 -db 00h :01°2 = 0001
0302 iplace rest of table up to the MSB of 592 here
035A org hibyte + 5ah = ;put MSB of 5A°2 here
035A 1F db 1fh iMSB is 1Fh
0358 place rest of MSB table here
0358 -end
So pervasive is serial data transmission that special integrated circuits, dedicated solely
to serial data transmission and reception, appeared commercially in the early 1970s. These
chips, commonly called “universal asynchronous receiver transmitters,” or UARTS, per-
form alll the serial data transmission and reception timing tasks of the most popular data
communication scheme still in use today: serial 8-bit ASCII coded characters at pre-
defined bit rates of 300 to 19200 bits per second. 7
Asynchronous transmission utilizes a start bit and one or more stop bits, as shown
in Figure 7.9, to alert the receiving unit that a character is about t0 arrive and to signal
the end of a character. This “overhead” of extra bits, with the attendant slowing of data
byte rates, has encouraged the development of synchronous data transmission schemes.
‘Synchronous data transmission involves alerting the receiving unit to the arrival of data‘AN 8051 MICROCONTROLLER DESIGN 123
FIGURE 7.9 Asynchronous 8-Bit Character
dle State
ADDRESS
here:
Idle State
ores
Pa See eee eee
---p--4---4q---7---
Stop
Data Bits ait
_—_
by a unique pattern that starts data transmission, followed by a long string of characters.
The end of transmission is signaled by another unique pattern, usually containing error-
checking characters.
Each scheme has its advantages. For relatively short or infrequent messages, the
asynchronous mode is best; for long messages or constant data transmission, the synchro-
nous mode is superior.
‘The 8051 contains serial data transmission/receiver circuitry that can be programmed
to-use four asynchronous data communication modes numbered from 0 to 3. One of these,
mode 1, is the standard UART mode, and three simple asynchronous communication pro-
‘grams using this mode will be developed here. More complicated asynchronous programs
that use all of the communication modes will be written in Chapter 9.
Character Transmission Using a Time Delay
Often data transmission is unidirectional from the microcontroller to an output device,
such as a display or a printer. Each character sent to the output device takes from 33.3
to .5 milliseconds to transmit, depending upon the baud rate chosen. The program must
‘wait until one character is sent before loading the next, or data will be lost. A simple way
to prevent data loss is to use a time delay that delays the known transmission time of one
‘character before the next is sent.
Sendchar
A program called “Sendchar™ takes the character in the A register, transmits it, delays for
the transmission time, and then returns to the calling program. Timer | must be used to sct
the baud rate, which is 1200 baud in this example. The delay for one ten-bit character
is 1000/120 or 8.4 milliseconds. The software delay developed in Section 7.5 is used for
the delay with the basic delay period of | milliseconds changed to .1 milliseconds by re-
defining “delay.” Timer | needs to generate a final baud rate of 1200 at SBUF. Using a
16 megahertz crystal, the reload number is 256 — 16E6/(16 x 12 x 1200), which is
186.6 or integer 187. This yields an actual rate of 1208.
MNEMONIC COMMENT
org 0000h
set delay,16h ;basic delay = 22d x 4.5 = 99 us
mov a,#'A' :for this example, send an A
acall sendchar ;send it
sjmp here simulate rest of user program
Continued124 CHAPTER seveN
ADDRESS MNEMONIC COMMENT
Continued
sendchar: anl tcon, #0fh lter timer 1 configuration only
orl toon, #20h set timer 1 for mode 2 (auto reload)
mov thl,#0bbh ;set reload number to 187d (256 - 69)
orl pcon, #80h set SMOD bit to l
orl tcon, #40h ;start timer 1 by setting TRI
mov scon, #40h iset serial port to mode 1
mov sbuf,a ;load transmit register and wait
mov a, #54h lelay for 8.4 ms (84d = 54h)
acall softime iwait
ret haracter now sent
;softime will be simulated by a return instruction
Softime: ret
-end sassembler use only
+ COMMENT
If timer 1 and the serial port have different uses in the user program, then push and pop
affected control registers. But remember, T1 and SBUF can only be used for one function at any
given time
The use of the set statement lets the user change the basic delay interval to different values in
the same program.
The 16 megahertz crystal does not yield convenient standard baud rates of 300, 1200, 2400,
4800, 9600, or 19200. The errors using this crystal for these rates are given in the following
table:
RATE —_ ERROR (%)
300 08
1200 64
4800 212
‘9600 355
19200851
‘The error grows for higher baud rates as ever smaller reload numbers are rounded to
the nearest integer. Using an 11.059 megahertz crystal reduces the errors to less than
002 percent at the cost of speed of program execution,
Character Transmission by Polling
‘An alternative to waiting a set time for transmission is to monitor the TI flag in the SCON
register until it is set by the transmission of the last character written to SBUF. The polling
routine must reset TI before returning to the call program. Failure to reset TI will inhibit
all calls after the first, stopping all data transmission except the first character.
This technique has the advantage of simplicity; less code is used, and the routine does
not care what the actual baud rate is. In this example, it is assumed that the timer 1 baud
rate has been established at the beginning of the program in a manner similar to that used.
in the previous example.‘AN 8051 MICROCONTROLLER DESIGN 125
Xmit
The subroutine “xmit™ polls the TI flag in the SCON register to determine when SBUF is
ready for the next character. The calling part of the user program follows:
ADDRESS MNEMONIC COMMENT
.org 0000h
mov a,#'3' ;send an ASCII 3 for this example
acall xmit ;send the character using xmit
here: sjmp here ;Simulate remainder of user program
xmit: mov sbuf,a ;transmit the contents of A and wait
wait: jnb scon,1,wait ;loop until TI = 1 (SBUF is empty)
clr scon.1 ireset TI to 0
ret
end
{ COMMENT
‘Thremains a 0 until SBUF is empty; when the 8051 is reset, or upon power up, TI is set 10 0.
Interrupt-Driven Character Transmission
‘The third method of determining when transmission is finished is to use the interrupt
structure of the 8051. One interrupt vector address in program code, location 0023h, is
assigned to both the transmit interrupt, TI, and the receive interrupt, RI. When a serial
interrupt occurs, a hardware call to location 0023h accesses the interrupt handling routine
placed there by the programmer.
The user program “calls” the subroutine by loading the character to be sent into
SBUF and enabling the serial interrupt bit in the El register. The user program can then
continue executing. When SBUF becomes empty, TI will be set, resulting in an immedi-
‘ate vector to 0023h and the subroutine placed there executed. The subroutine at 0023h,
called “serial,” will reset TI and then return to the user program at the place where it was
interrupted.
‘This scheme is satisfactory for testing the microprocessor when only one character is
sent from the program. Long strings of character transmission will overload SBUF. Chap-
ter 9 contains routines that will build on this technique and send arbitrarily long strings
with no loss of data.
SBUFR
‘An interrupt-driven data transmission routine for one character which is assembled at the
routine is shown,
ADDRESS = MNEMONIC COMMENT
-org 0000h
sbufr: sjmp user ;jump over interrupt vectors
org 0023h :put serial interrupt routine here
icrrupt vector location 0023h. A portion of the user program that activates the interrupt
Continued126 CHAPTER SEVEN
ADDRESS
Continued
serial:
user
here:
MNEMONIC COMMENT
clr scon.1 clear TI
reti rreturn to interrupted user program
mov sbuf,#'X' ;send an X in this example
orl ie, #90h jenable serial interrupt
sjmp here simulate remainder of program
-end
[>>— COMMENT
If Tlis not cleared before the RETI instruction is used, there will be an immediate interrupt and
vector back to 0023h.
RET! is used to reset the entire interrupt structure, not to clear any interrupt bits.
Recei
9 Serial Data
‘Transmissions from outside sources to the 8051 are not predictable unless an elaborate
time-of-day clock is maintained at the sender and receiver. Messages can then be sent at
predefined times. A time-of-day clock generally ties up timers at both ends to generate the
required “wake-up” calls.
‘Two methods are normally used to alert the receiving program that serial data has
arrived: software polling or interrupt driven. The sending entity, or “talker,” transmits
data at random times, but uses an agreed-upon baud rate and data transmission mode. The
receiving unit, commonly dubbed the “listener,” configures the serial port to the mode
and baud rate to be used and then proceeds with its program.
If one programmer were responsible for the talker and another for the listener, lively
discussions would ensue when the units are connected and data interchange does not take
place. One common method used to test communication programs is for each programmer
to use a terminal to simulate the other unit. When the units are connected for the final test,
a CRT terminal in a transparent mode, which shows all data transmitted in both direc-
tions, is connected between the two systems to show what is taking place in the communi-
cation tink
Polling for Received Data
Polling involves periodically testing the received data flag RI and calling the data receiving
subroutine when it is set. Care must be taken to remember to reset RI, or the same character
will be read again. Reading SBUF does not clear the data in SBUF or the RI flag.
‘The program can sit in a loop, constantly testing the flag until data is received, or run
through the entire program in a circular manner, testing the flag on each circuit of the
program. The loop approach guarantees that the data be read as soon as it is received;
however, very little else will be accomplished by the program while waiting for the data
‘The circular approach lets the program run while awaiting the data.
In order not to miss any data, the circular approach requires that the program be able
to run a complete circuit in the time it takes to receive one data character. The time re-
straint on the program is not as stringent a requirement as it may first appear. The receiver
is double buffered, which lets the reception of a second character begin while @ previous
character remains unread in SBUF. If the first character is read before the last bit of theADDRESS
here:
ADDRESS
there:
ADDRESS
intdat:
[AN 8051 MICROCONTROLLER DESIGN 127
second is complete, then no data will be lost. This means that, after a two-character burst,
the program still must finish in one-character time to catch a third.
The character time is the number of bits per character divided by the baud rate. For
serial data transmission mode 1, a character uses ten bits: start, eight code bits, and stop.
‘A 1200 baud rate, which might be typical for a system where the talker and listener do not
interchange volumes of data, results in a character rate of 120 characters per second, or a
character time of 8.33 milliseconds. Using an average of 18 oscillator periods per instruc-
tion, each instruction will require 1.13 microseconds to execute, enabling a program
length of 7371 instructions. This large machine language program will suffice for many
simple control and monitoring applications where data transmission rates are low. If more
time is needed, the baud rate could be reduced to as low as 300 baud, yielding a program
size of over 29K bytes, which approaches half the maximum size of the ROM in our ex-
ample 8051 design.
‘The polling program for the loop approach follows:
MNEMONIC ‘COMMENT
jb scon.0,here — ; wait here until RI = 1
clr scon.0 ielear the RI bit
acall getchar ;getchar is some user routine
swhich reads SBUF
‘The circular approach is very similar:
MNEMONIC COMMENT
jnb scon.0 there :test for RI = 1, go on if not
elr scon.0 relear the RI bit
acall getchar reall user routine
sjmp there :rest of user program getchar:
ret :simulate user routine
send
Interrupt-Driven Data Reception
When large volumes of data must be received, the data rate will overwhelm the polling
approach unless the user program is extremely short, a feature not usually found in sys-
tems in which large amounts of data are interchanged. Interrupt-driven systems allow the
program to run with brief pauses to read the received data. In Chapter 9, a program is
developed that allows for the reception of long strings of data in a manner completely
‘transparent to the user program.
Intdat
This interrupt-driven data reception subroutine assembles the program at 0023h, which is,
the serial interrupt vector location.
MNEMONIC COMMENT
org 0000h
orl ie, #90h renable serial and all interrupts
sjmp over :jump over the interrupt locations
Continued128 CHAPTER SEVEN
ADDRESS
Continued
xmit:
over:
trans:
recy:
MNEMONIC COMMENT
org 0023h :put serial interrupt program here
jbe soon.l,xmit ;if TI bit set, clear it and jump
clr scon.0 ;must have been RI, clear it
leall recy :eall receive subroutine
reti :return to program where interrupted
Jeall trans all transmit program
reti eturn to program where interrupted
sjmp over
ret idummy transmit/receive routines
ret
{>— COMMENT
Summary
If both Rl and Tlare set, this routine will service the transmit function first. After the RETI, which
follows the LCALL to trans, the RI bit will stil be set, causing an immediate interrupt back to
location 0023h where the receive routine will be called.
If the transmit or receive subroutines that are called take longer to execute than the character
time, then data will be lost. Long subroutine times would be highly unusual; however, itis
possible to overload any system by constant data reception.
‘An 8051 based microprocessor system has been designed that incorporates many features
found in commercial designs. The design can be easily duplicated by the reader and uses
‘external EPROM and RAM so that test programs may be exercised. Various size memo-
ries may be used by the impecunious to reduce system cost.
‘The design features are
External RAM: 8K to 32K bytes
External ROM: 8K to 64K bytes
1/0 ports: 1-8 bit, port 1
Other ports: port 3.0 (RXD)
3.1 (TXD)
3.2 (NTO)
3.3 (NTI)
3.4.(T0)
3.57)
Crystal: 16 megahertz
Other crystal frequencies may be used to generate convenient timing frequencies. The
design can be modified to include a single step capability (see Problem 2).
Methods of adding additional ports to the basic design are discussed and several ex-
ample circuits that indicate the expansion possibilities of the 8051 are presented.
Programs written to test the design can be used to verify any prototypes that are built
by the reader. These tests involve verifying the proper operation of the ROM and RAM.
connections.‘AN 8051 MICROCONTROLLER DESIGN 129
Several programs and subroutines are developed that let the user begin to exercise the
8051 instruction code and hardware capabilities. This code can be run on the simulator or
on an actual prototype. These programs cover the most common types found in most
applications:
Time delays: software; timer, software polted; timer, interrupt driven
Lookup Tables: PC base, DPTR base
Serial data communications transmission: time delay, software polled, interrupt
driven
Serial data communications reception: software polled, interrupt driven
‘The foundations laid in this chapter will be built upon by example application pro-
grams and hardware configurations found in Chapters 8 and 9.
Problems
1. Determine whether the 8051 can be made to execute a single program instruction
(ingle-stepped) using external circuitry (no software) only.
2, Outline a scheme for single-stepping the 8051 using a combination of hardware and
software. (Hint: use an INTX.)
3. While running the EPROM test, itis found that the program cannot jump from 2000h to
4000h successfully. Determine what address line(s) is faulty.
4, Calculate the error for the delay program ““Softime” when values of 2d, 10d and 100d
milliseconds are passed in A and B.
5. The program “‘Softime” has a bug. When A = O0h the delay becomes: (B+ I)d x 256d x
delay. Find the bug and fix it without introducing a new bug.
6. Find the shortest and longest detays possible using “Softime” by changing only the
equate value of the variable ‘“delay.””
7. Give a general description of how you would test any time delay program. (Hint: use a
port pin.)
In the discussion for the program named “Timer,” the statement is made that an accurate
I ms delay cannot be done due to the need for a count of 1333.33 using a 16 megahertz
‘clock. Find a way to generate an accurate 60 second delay using T0 for the basic delay
and some registers to count the TO overflows.
9. Calculate the shortest and longest delays possible using the program named “Timer” by
changing the initial value of TO.
8 value of 0000h in the program named
11. Write a lookup table program, using the PC as the base, that finds a one-byte square root
(to the nearest whole integer) of any number placed in A. For example, the square roots
OF O1 and 02 are both 01, while the roots of 03 and 04 are 02. Calculate the first four
and last four table values.
12, Write a lookup table, using the DPTR as the base, that finds a two-byte square root of
the number in A. The first byte is the integer value of the root. and the second byte is the
fractional value. For example, the square root of 02 is O1.6Ah. Calculate four first and
last table values.130
(CHAPTER SEVEN
Write a lookup table program that converts the hex number in A (0-F) to its ASCIT
equivalent.
14, A PC based lookup table, which contains 256d values, is placed 50h bytes after the
MOVC instruction that accesses it. Construct the table, showing where the byte associ-
ated with A = 00h is located. Find the largest number which can be placed in A to
access the table.
15. Construct a lookup table program that converts the hex number in A to an eq
BCD number in registers R4 (MSB) and RS (LSB).
16. Reverse Problem 15 and write a lookup table program that takes the BCD number in R4
(MSB) and RS (LSB) and converts it to a hex number in A.
Verify the errors listed for the 16 megahertz crystal in the third comment after the pro-
gram named “Sendchar.””
18, Verify the error listed for the 11.059 megahertz crystal in the fourth comment after the
program named “Sendchar.”
19. Does asynchronous communication between two microprocessors have to be done at
standard baud rates? Name one reason why you might wish 10 use standard rates.
lent
17.
20, Write a test program that will “loop test” the serial port. The output of the serial port
(TXD) is connected to the inpat (RXD), and the test program is nun. Success is indicated
by port I pin I going high.
21, What is the significance of the transmit flag, TI, when itis cleared to 0? When set to 1?
22, Using the programmable port of Figure 7.3, write a program that will configure all ports
as outputs, and write a 5Sh to each.
23. Repeat problem 22 using the memory-mapped programmable port of Figure 7.4.CHAPTER
ee
Applications
Chapter Outline
Introduction
Keyboards Putting it all Together
Displays Summary
Pulse Measurement
Introduction
131
Microcontrotiers tend to be underutilized in many applications. There are several reasons
for this anomaly. Principally, the devices are so inexpensive that it makes little economic
sense to try fo select an optimal device for each application. A new microcontroller in-
volves the expense of new development software and training for the designers and pro-
grammers that could easily cost more than the part savings. Also, some members of the
technical community are unfamiliar with the microcontroller due to a dearth of established
academic course offerings on the subject. These individuals tend to apply classic eight-bit,
microprocessor families to problems that are more economically served by a micro-
controller. Finally, there is always the pressure to use the latest multibyte processor for
‘marketing reasons or just to keep up with the “state of the art.”
The result of this application pattern is that microcontrollers tend to become obsolete at
a slower rate than their CPU cousins. The microcontroller will absorb more eight-bit CPU
applications as the economic advantage of using microcontrollers becomes compelling
Application examples in a textbook present a picture of use that supports the previ-
‘ously-made claim of underutilization. Limitations on space, time, and the patience of the
reader preclude the inclusion of involved, multi-thousand line, real-time examples. We
will, instead, look at pieces of larger problems, each piece representing a task commonly
found in most applications.
‘One of the best ways to get 2 “feel” for a new processor is to examine circuits and
programs that address easily visualized applications and then to write variations. To assist132 CHAPTER EIGHT
Keyboards
in this process, we will study in detail the following typical hardware configurations and
their accompanying programs:
Keyboards
Displays
Pulse measurements
AID and D/A conversions
Multi-source interrupts
The hardware and software are inexorably linked in the examples in this chapter. The
choice of the first leads to the programming techniques of the second. The circuit designer
should have a good understanding of the software limitations faced by the programmer.
‘The programmer should avoid the temptation of having all the tricky problems handted by
the hardware.
The predominant interface between humans and computers is the keyboard. These range
in complexity from the “up-down” buttons used for elevators to the personal computer
QWERTY layout, with the addition of function keys and numeric keypads. One of the
first mass uses for the microcontroller was to interface between the keyboard and the main
processor in personal computers. Industrial and commercial applications fall somewhere
in between these extremes, using layouts that might feature from six to twenty keys,
The one constant in all keyboard applications is the need to accommodate the human.
user. Human beings can be irritable. They have little tolerance for machine failure: watch
‘what happens when the product isn't ejected from the vending machine. Sometimes they
are bored, or even hostile, towards the machine. The hardware designer has to sefect keys
that will survive in the intended environment. The programmer must write code that will
anticipate and defeat inadvertent and also deliberate attempts by the human to confuse the
program, It is very important to give instant feedback to the user that the key hit has been
acknowledged by the program. By the light a light, beep a beep, display the key hit, or
whatever, the human user must know that the key has been recognized. Even feedback
sometimes is not enough; note the behavior of people at an elevator. Even if the “up” light
is lit when we arrive, we will push it again to let the machine know that “I'm here too.”
‘Human Factors
‘The keyboard application program must guard against the following possibilities:
More than one key pressed (simuttancously or released in any sequence)
Key pressed and held
Rapid key press and release
All of these situations can be addressed by hardware or software means: software, which
is the most cost effective, is emphasized here.
Key Switch Factors
‘The universal key characteristic the ability to bounce: The key contacts vibrate open
and close for a number of milliseconds when the key is hit and often when itis released.
‘These rapid pulses are not discernable to the human, but they last a relative eternity inAPPLICATIONS 133
the microsecond-dominated life of the microcontroller. Keys may be purchased that do
rot bounce, keys may be debounced with RS flip-flops, or debounced in software with
time delays.
Keyboard Configurations
Keyboards are commercially produced in one of the three general hypothetical wiring con-
figurations for a 16-key layout shown in Figure 8.1. The lead-per-key configuration is
typically used when there are very few keys to be sensed. Since each key could tie up a
port pin, itis suggested that the number be kept to 16 or fewer for this keyboard type. This
configuration is the most cost effective for a small number of keys.
‘The X-Y matrix connections shown in Figure 8.1 are very popular when the number
of keys exceeds ten. The matrix is most efficient when arranged as a square so that N leads
for X and N leads for Y can be used to sense as many as N? keys. Matrices are the most
cost effective for large numbers of keys.
FIGURE 8.1 Hypothetical Keyboard Wiring Configurations
KeyO Key] Key 2 Key Key 4 KeyS Key6 Key 7
Key8 Key? KeyA = KeyB Key KeyD Key £ Key F
fuels gael
Common
(2) Lead-Per-Key Keyboard
KeyO Keyl Key2—Key3.
0 1 2 3
Columns
(b) X-¥ Matrix Keyboard
Continued134 CHAPTER FIGHT
FIGURE 8.1
Continued
Coded keyboards were evolved originally for telephonic applications involving touch-
tone signating. The coding permits multiple key presses to be easily detected, The quality
and durability of these keypads are excellent due to the high production volumes and in-
tended use. They are generally limited to 16 keys or fewer, and tend to be the most expen-
sive of all keyboard types.
Programs for Keyboards
Programs that deal with humans via keyboards approach the human and keyswitch factors
identified in the following manner: 7
Bounce: A time delay that is known to exceed the manufacturer's specification is
used to wait out the bounce period in both directions.
Muttiple keys: Only patterns that are generated by a valid key pressed are ac-
cepted—all others are ignored—and the first valid pattern is accepted.APPLICATIONS 135
Key held: Valid key pattern accepted after valid debounce delay; no additional keys
accepted until all keys are seen to be up for a certain period of time.
Rapid key hit: The design is such that the keys are scanned at a rate faster than any
human reaction time.
The last item brings up an important point: Should the keyboard be read as the pro-
{gram loops (software polled) or read only when a key has been hit (interrupt driven)?
In general, the smaller keyboards (lead-per-key and coded) can be handled either
way. The common lead can be grounded and the key pattern read periodically. Or, the
lows from each can be active-low ORed, as shown in Figure 8.2, and connected to one of
the external INTX pins.
Matrix keyboards are scanned by bringing each X row low in sequence and detecting
Y column low to identify each key in the matrix. X—Y scanning can be done by using
dedicated keyboard scanning circuitry or by using the microcontroller ports under pro-
{gram control. The scanning circuitry adds cost to the system. The programming approach
takes processor time, and the possibility exists that response to the user may be sluggish if
the program is busy elsewhere when a key is hit. Note how long your personal computer
takes to respond to a break key when it is executing a print command, for instance. The
choice between adding scanning hardware or program software is decided by how busy the
processor is and the volume of entries by the user.
FIGURE 8.2 Lead-per-Key and Coded Keyboard Interrupt Circuits
To Port Pins
+V
+5v
ToiNTX
+8
To Port Pins ov
Common Lead
Two-Of-Eight
Coded Keyboard To Port Pins
evan136
CHAPTER EIGHT
A Scanning Program for Small Keyboards
‘Assume that a lead-per-key keyboard is to be interfaced to the microcontroller. The key-
‘board has ten keys (0-9), and the debounce time, when a key is pressed or released, is 20
milliseconds. The keyboard is used to select snacks from a vending machine, so the pro-
cessor is only occupied when a selection is made. The program constantly scans the key-
board waiting for a key to be pressed before calling the vending machine actuator sub-
routine, The keys are connected to port | (0-7) and ports 3.2 and 3.3 (8-9), as shown in
Figure 8.3,
‘The 8031 works best when handling data in byte-sized packages. To save internal
space, the ten-bit word representing the port pin configuration is converted to a single-byte
number.
Because the processor has nothing to do until the key has been detected, the time
delay “Softime” (see Chapter 7) is used to debounce the keys.
Getkey
‘The routine “Getkey” constantly scans a ten-key pad via ports 0 and 3. The keys are
— COMMENT
MNEMONIC COMMENT
acall keydown isee if keys are up after delay
jnz delay sif not then delay again
sjmp goback ireturn with Tl stopped
-end
This program is large enough to require additional attempts to make it legible. All of the sub-
routines are arranged in alphabetical order.
Codekey
The completely interrupt-driven small keyboard example given in this section requires no
program action until a key has been pressed. Hardware must be added to attain a com-
pletely interrupt-driven event. The circuit of Figure 8.4 is used.
FIGURE 8.4 Keyboard Configuration Used for “Codekey” Program
+v
Two-Of- Four
Coded Keyboard
12. NTO
8031ADDRESS
codekey
keyint
timo:
APPLICATIONS «145,
“The keyboard is a two-of-eight type which codes the ten keys as follows:
KEY — CODE(HEX)
te
©
&B
7
OE
bb
bB
7
BE
80
wavauaunso
An inspection of the code reveals that each nibble has only one bit that is low for each
key and that two of the eight bits are uniquely low for each key. If more than one key is
pressed, then three or more bits go low, signaling an invalid condition. This popular
scheme allows for up to 16 keys to be coded in this manner. Unlike the lead-per-key
arrangement, only four of the lines must be active-low ORed to generate an interrupt
‘The hardware serves to detect when any number of keys are hit by using an AND gate
to detect when any nibble bit goes low. The high-to-low transition then serves to interrupt
the microcontroller on port 3.2 (INTO). The interrupt program reads the keys connected to
port I and uses timer TO to generate the debounce time and TI for the keys-up delay. The
total delay possible at 16 megahertz for the timers is 49.15 milliseconds, which covers the
delay times used in the previous examples.
‘The program “Codekey” which is interrupt driven by a high-to-low transition on
INTO. Timers TO and T1 generate the debounce and delay times in an interrupt mode.
‘The INTO interrupt input is disabled until all keys have been seen up for the TI delay.
A lookup table is used to verify that only one key is pressed.
MNEMONIC COMMENT
vequ newkey,70h ystore a new key in RAM
equ base, 400h jbase of lookup table
equ newflg,00n saddressable bit 00 for new key flag
org 0000h
sjmp over jump over interrupt locations
-org 0003h :this is the INTO interrupt vector
sjmp keyint
org 000bh ;timer TO interrupt vector
sjmp timd
org 001bh ;timer Tl interrupt vector
sjmp tim]
mov tl0, #0d4n set TO for 20 ms delay
mov th0, #97h soount from 97D4n to 0000
setb tcon.4 istart timer 70
clr ie.0 :disable INTO interrupt
reti senable interrupt structure and
ireturn
push acc ssave registers used
push dp]
Continued146 carter EIGHT
ADDRESS
Continued
good
Timl
wait:
over:
simulate
key:
MNEMONIC
push dph
clr tcon.4
mov a,pl
mov dptr,#base
move a,@atdptr
ejne a, #0ffh, good
pop dph
pop dpl
pop acc
setb ie.0
reti
mov newkey,a
setb newflg
anl 11, #00h
anl thi, #00h
setb tcon.6
pop dph
pop dpl
Pop acc
reti
push ace
clr tcon.6
mov a,pl
cjne a, #0ffh,wait
setb ie.0
pop ace
reti
anl 111, #00
anl thl,#00h
setb tcon.6
pop acc
reti
mov tcon, #01h
mov ie, #8bh
mov tmod,#11h
jbo newflg,key
sjmp simulate
mov a,newkey
simp simulate
sore O4bdh
db 09h
db 08h
COMMENT
istop TO
:get key pattern
:set DPTR to point to lookup table
snot valid = FFh
renable INTO interrupt
:enable interrupt structure and
sreturn
istore the newkey
;signal main program; new key present
iset Tl for maximum delay (49.1 ms
start timer Tl
irestore retgisters
renable interrupt structure and
rreturn
save A
stop Tl
isee if keys up yet
:all inputs will be high if all up
yenable INTO for next key
rrestart Tl and delay again
istart Tl
;return with interrupt enabled
:set INTO for falling edge interrupt
enable INTO. T0, and Tl interrupts
;choose timer operation: mode 1
;see if there is a new key and get it
;Simulate rest of program
iget key and simulate rest of program
splace lookup table here, keys 9
sand 8
ContinuedADDRESS
AppucaTiONS 147
MNEMONIC COMMENT
org 04d7h skey 7
db O7h
org O4dbh key 6
db 06h
org O4ddh skeys 5 and 4
db 05h
db 04h
org O4e7h ikey 3
db 03h
org O4ebh key 2
db 02h
-org O4edh rkeys 1 and 0
-db 01h
db 00h
end
[>— COMMENT
The lookup table will work only if every bit from 0400h to O4FFh that is not a db assignment is
FFh. Most EPROMS will be FFh when erased, and the assembler will not program unspecified
locations. The table will have to be assembled so that an FFh is at every non-key location if this
is not true.
Key bounce down is eliminated by the TO delay, and key bounce up, by the T1 delay. More than
two keys down is detected by the self-coding nature of the keyboard. A held key does not
interrupt the edge-triggered INTO input.
Program for a Large Matrix Keyboard
A 64-key keyboard, arranged as an 8-row by 8-column matrix will be interfaced to the
8051 microcontroller, as shown in Figure 8.5. Port 1 will be used to bring each row low,
‘one row at a time, using an 8-bit latch that is strobed by port 3.2. P1 will then read the
8-bit column pattern by enabling the tri-state buffer from port 3.3. A pressed key will have
a unique row-column pattern of one row low, one column low. Multiple key presses are
rejected by either an invalid pattern or a failure to match for three complete cycles. Each
row is scanned at an interval of I millisecond, or an 8 millisecond cycle for the entire
keyboard. A valid key must be seen to be the same key for 3 cycles (24 milliseconds).
‘There must then be three cycles with no key down before a new key will be accepted. The
1 millisecond delay between scans is generated by timer TO in an interrupt mode.
Bigkey
‘The “Bigkey” program scans an 8 x 8 keyboard matrix using TO to generate a periodic
I ms delay in an interrupt mode. Each row is scanned via an external latch driven by port 1
and strobed by port 3.2. Columns are read via a tri-state buffer under control of port 3.3.
Keys found to be valid are passed to the main program by setting the flag ““newflg” and
placing the key identifiers in locations “‘newrow" and “newcol."” The main program
resets “newflg” when the new key is fetched. R4 is used as a cycle counter for successful
matches and up time cycles. RS is used to hold the row scan pattern: only one bit low.148 CHAPTER EIGHT
FIGURE 8.5. Circuit for “Bigkey” Program
Matrix Switeh Connection
ian ie
=
columa
mM Latch Row Pattern
8 x B Keyboard
8031
Reae
133.3
T ‘columns
19171615 14131211
541 Tri-State Butter
ADDRESS = MNEMONIC COMMENT
equ newrow,70h
.equ newcol,71h
equ newflg,00h
jstore any valid key row address
jstore any valid key column address
juse addressable bit as a new
skey flag
ContinuedADDRESS = MNEMONIC
equ upflg.01h
org 0000h
bigkey: sjmp over
:The interrupt program begins here
:the next interrupt in 1 ms
org 000bh
mov %10,#0cbh
mov th0, #0fah
push acc
push psw
mov pl,r5
setb p3.2
clr p3.2
nov pl, #0ffh
elr p3.3
mov a,pl
setb p3.3
jb upfig, upyet
setb ¢
mov r3,#08h
look tro a
jne test
djnz r3,look
mov a,r5
cjne a,newrow, goback
mov newrow, #00h
mov r4,#00h
sjmp goback
ojne a,#0ffh,bad
rre a
djnz r3,here
cjne r4,#00h,match
mov newcol.a
mov newrow,r5
inc r4
sjmp goback
push ace
mov a.r5
test:
here:
newone:
match
APPUCATIONS 149.
‘COMMENT
jupflag signals start of key up
idelay
:Jump over TO interrupt to main
:program
TO is reloaded to permit
ivector location for TO overflow
iflag
ireload T0 for next interrupt
:save A and the flags
iget row scan pattern to port 1
sgenerate a strobe to the latch
:set Pl as an input port
iread buffer and see if any
ikey down
:get column pattern
idisable buffer
rif upflg = 1 then wait for
eys up
set C to 1 and rotate A to find
a low
rotates will restore A to
poriginal
isee if only one zero in A (valid)
fC = 0 then see if A = FFh
:go until C = 0 or rotate finished
:check for a key down previous scan
sif so then not repeated; zero
jnewrow
:if so then zero R4 and scan again
:return to main program
if A not all ones then invalid key
:good pattern; restore A
R4 counts pattern matches
:first time seen: see if it recurs
;R4 contains key detected count
:save A and check R5 for a new row
Continued150 CHAPTER EIGHT
ADDRESS
Continued
good:
unk
unkn:
bad:
upyet:
notup:
goback
MNEMONIC
cjne a,newrow,unk
Pop acc
cjne a.newcol,unkn
ine
r4
cjne r4,#04h, goback
mov
mov
newrow,r5
newcol,a
setb newflg
setb upflg
mov
r4,#00h
sjmp goback
pop
mov
ace
r4,#00h
sjmp newone
mov
4, #00h
simp goback
ojne a, #0ffh, notup
ine
cjne r4,#18h, goback
clr
mov
mov
rla
mov
Pop
pop
reti
r4
upflg,
4, #00h
ars
r5.a
psw
ace
COMMENT
:if no match then this is a new key
rrestore A and check for a new
;oolumn
f no match then this is a new key
jmatch: see if 24 ms have expired
ikeep if seen for at least 3 cycles
;save new key row and column
iset up flag for 3 cycles up
;reset R4 to count key up cycles
irestore new column pattern to A
ireset r4 to reflect a new key
slook for matches on next cycles
reset match counter
jlook for A = FFh
:R4 now counts 3 cycle of up time
look for 24d scans (3 cycles
p time done, look for next key
eset R4
rrotate R5 low bit to next row
restore PSW and A
:the interrupt program finishes here and the main program begins;
over
main:
simulate
mov
mov
mov
mov
mov
r5,#0feh
tmod, #01h
t10, #ocbh
tho. #ofan
ie, #82n
setb tcon.4
mov
elr
elr
jbo
14, #00h
upflg
newflg
newflg, simulate
sjmp main
nop
sjmp main
end
he main program would normally get the new key row and column
atterns and convert these to a single byte number
sinitialize R5 for bottom row low
set TO to mode 1
iset TO for a 1 ms delay
count 1333d @ .75 ws/count
senable the TO interrupt
pstart timer
ireset R4 for no valid key
ireset key up flag
ireset new key flag
:get key row and column addresses
simulate main program
rmain program would get addresses
shereAPPUCATIONS 151
Displays
COMMENT
Once begun by the main program, TO continues to time out and generate the row scan pattern
in the interrupt program. To the main program, the keys appear in some unknown way; the
interrupt program is said to run in the “background.”
‘There is considerable adjustment (tweak) in this program to accommodate keys with various
bounce characteristics. The debounce time can be altered in a gross sense by changing the
‘number of cycles (RA) for acceptance and in a fine way by changing the basic row scan time (10).
This same program can be used to monitor any multipoint array of binary data points. The array
can be expanded easily to a 16 x 16 matrix by adding one more latch and tristate buffer and
sing two more port 3 pins to generate the latch and enable strobes.
Note that only A can compare against memory contents in a CJNE instruction,
If keyboards are the predominant means of interface to human input, then visible displays
are the universal means of human output. Displays may be grouped into three broad
2. Single character(s)
3. Intelligent alphanumeric
Single light displays include incandescent and, more likely, LED indicators that are
treated as single binary points to be switched off or on by the program. Single character
displays include numeric and alphanumeric arrays. These may be as simple as a seven-
segment numeric display up to intelligent dot matrix displays that accept an 8-bit ASCII
‘character and convert the ASCII code to the corresponding alphanumeric pattern. /ntelli-
‘gent alphanumeric displays are equipped with a built-in microcontroller that has been op-
timized for the application. Inexpensive displays are represented by multicharacter LCD
windows, which are becoming increasingly popular in hand-held wands, factory floor ter-
minals, and automotive dashboards. The high-cost end is represented by CRT ASCII
terminals of the type commonly used to interface to a multi-user computer.
The individual light and intelligent single-character displays are easy to use. A port
presents a bit or a character then strobes the device. The intelligent ASCII terminals are
normally serial devices, which are the subject of Chapter 9.
The two examples in this section—seven-segment anf intelligent LCD displays—
require programs of some length.
Seven-Segment Numeric Display
‘Seven-segment displays commonly contain LED segments arranged as an “8,” with one
common lead (anode or cathode) and seven individual leads for each segment. Figure 8.6
shows the pattern and an equivalent circuit representation of our example, a common cath-
‘ode display. If more than one display is to be used, then they can be time multiplexed; the
human eye can not detect the blinking if each display is relit every 10 milliseconds or so.
‘The 10 milliseconds is divided by the number of displays used to find the interval between
‘updating each display.
The example examined here uses four seven-segment displays; the segment informa-
tion is output on port 1 and the cathode selection is done on ports 3.2 to 3.5, as shown in152
CHAPTER EIGHT
FIGURE 8.6 Seven-Segment LED Display and Circuit
Common Cathode
Segment Circuit
Figure 8.7. A segment will be Tit only if the segment line is brought high and the common
cathode is brought low.
Transistors must be used to handle the currents required by the LEDs, typically
10 milliamperes for each segment and 70 milliamperes for each cathode. These are aver-
age current values; the peak currents will be four times as high for the 2.5 milliseconds.
each display is illuminated.
‘The program is interrupt driven by TO in a manner similar to that used in the program
“Bigkey.” The interrupt program goes to one of four two-byte character locations and
finds the cathode segment pattern to be latched to port 1 and the anode pattern to be latched
to port 3. The main program uses a lookup table to convert from a hex number to the
segment pattern for that number, In this way, the interrupt program automatically displays
whatever number the main program has placed in the character locations. The main pro-
gram loads the character locations and is not concerned with how they are displayed.
Svnseg
The program “‘svnseg” displays characters found in locations “chi” to “ch4” on four
common-cathode seven-segment displays. Port 1 holds the segment pattern from the low
byte of chx; port 3 holds the cathode pattern from the high byte of chx. TO generates a
2.5 ms delay interval between characters in an interrupt mode. The main program uses a
Jookup table to convert from hex to a corresponding pattern. RO of bank one is dedicated
as a pointer to the displayed character.APPUCATIONS 153,
FIGURE 8.7 Seven-Segment Display Circuit Used for “Svnseg” Program
+0
rents
CH Cd eo Ns ms
6 Ps
J
or
=—
8031
12 P32
13 P3.3
1a P38
15 P35,
ADDRESS
svnseg
MNEMONIC
-equ
-equ
-equ
equ
-org,
chl,50h
ch2, 52h
ch3, 54h
oh4.56h
o000n
mov sp, #0fh
sjmp
over
COMMENT
sassign RAM character locations
;two bytes per character
:jump over TO interrupt location
jget the stack above bank one
Continued154 CHAPTER EIGHT
ADDRESS
Continued
sbegin the
nxt:
MNEMONIC. COMMENT
interrupt-driven program at the TO interrupt location
-org 000bh
mov t10,#0fbh :reload TO for next interrupt
mov tho, #0f2n
setb psw.3 iselect bank one
mov pl, @r0 place segment pattern on port 1
inc r0 spoint to accompanying cathode pattern
mov p3,@r0 lace cathode patten on port 3
ine ro ieheck for fourth character
ojne r0,#58h, nxt
mov r0. #ch1 rif cha just displayed go to chi
clr psw.3 eturn to register bank 0
reti sTeturn to main program
;the main program loads sample characters and starts the TO
vinterrupt.
mov a, #00h suse an example sequence of 0, 1, 2, 3
acall convert onvert to segment pattern and store
mov chl,a
mov a, #01h
acall convert
mov ch2,a
mov a, #02h
acall convert
mov ch3,a
mov a. #03h
acall convert
mov ch4,a slast segment pattern stored
setb psw.3 iselect register bank one
mov r0,#chl :set RO to point to chl RAM location
ine r0 snow load anode pattern for ch
nov @r0,#20h ;set anode for character 1 only high
ine r0 point to next character and continue
ine 10 sload ch2 pattern
mov @r0,#10h
ino ro
inc r0 rload ch3 pattern
nov @ro, #08h
inc ro
ine ro :load ch4 pattern
mov @r0, #04h
mov r0,#chl spoint to RAM address for chl
mov t10,#0fbh jload TO for first interrupt
mov tho, #0f2h
ContinuedAPPLICATIONS 155
ADDRESS = MNEMONIC COMMENT
mov tmod. #01h rset TO to mode 1
mov ie, #82h senable TO interrupt
setb toon.4 istart timer
clr psw.3 ireturn to register bank 0
here: sjmp here :loop and simulate rest of program
sconvert uses the PC to point to the base of the 16-byte table
ine a scompensate for RET byte
mov a,@pota rget byte
ret rreturn with segment pattern in A
db coh :
db f9n
.ab aah
-ab bOh
+b 99h
-db 92h
-db 82h
db f8h
-db f0h
-db 98h
-ab 88h
db 83h
-db 6h
-db blh
db 86h
-db Beh
send
2
3
4
5
6
7
8
9
A
b
c
id
[>>— COMMENT
Using bank 1 as a dedicated bank for the interrupt routine cuts down on the need for pushes
and pops. Bank 1 may be selected quickly, giving access to the eight registers while saving
the bank 0 registers. Note that the stack, at reset, points to RO of bank 1, so that it must be
relocated.
The intensity of the display may also be varied by blanking the displays completely for some
interval using the program.
Intelligent LCD Display
Jn this section, we examine an intelligent LCD display of two lines, 20 characters per line,
that is interfaced to the 8051. The protocol (handshaking) for the display is shown in
Figure 8.8, and the interface to the 8051 in Figure 8.9.
‘The display contains two internal byte-wide registers, one for commands (RS = 0) and
the second for characters to be displayed (RS = 1). It also contains a user-programmed
RAM area (the character RAM) that can be programmed to generate any desired character
that can be formed using a dot matrix. To distinguish between these two data areas, the
hex command byte 80 will be used to signify that the display RAM address 00h is chosen.156
‘CHAPTER EIGHT
FIGURE 8.8 Intelligent LCD Display
6 45-5
123
ttt ttt tt
Do D1 02 03 04 05 06 07 RSRWEN
Inteltigent LOD Displey
BIT RS RAW D7 DE DS D4 D3 D2 D1 DO Function
0 0 0 0 © 0 0 0 6 4 — Clear LED and memory, home cursor
0 9 9 0 0 0 0 0 14 0 Clear and home cursor only
0 0 0 0 6 0 0 4% WO Ss Screen action as display character written
5 = 1/0: Shift screen/cursor
VO = 1/0: Cursor RIL, screen UR
0 0 09 0 0 © 1 D C€ B D=1/0: Screen on/oft
C = 1/0: Cursor on/off
B = 1/0: Cursor Blink/Noblink
0 0 0 0 0 1 Si RL 0 0 SIC = 110: Screen/Cursor
RIL = 1/0: Shift one space R/L
0 0 0 0 1 OH N F OG 0 DL = 1/0: 8/4 Bits per character
N= 1/0; 2/1 Rows of characters
F = 1/0; 5X10/5X7 DotsiCharacter
0 0 0 1 Character address ‘Write to character RAM Address after thr
0 0 1 Display data address Write to display RAM Address after thy
o 1 BF Current address BF = 1/0: Busy/Notbusy
1 0 Character byte Write byte to last RAM chosen
tot Character byte Read byte from last RAM chosen
Port | is used to furnish the command or data byte, and ports 3.2 to 3.4 furnish regis
ter select and read/write levels.
The display takes varying amounts of time to accomplish the functions listed in Hy
ure 8.8. LCD bit 7 is monitored for a logic high (busy) to ensure the display is not over
written. A slightly more complicated LCD display (4 lines x 40 characters) is currently,
being used in medical diagnostic systems to run a very similar program,
Ledisp
The program “Iedisp" sends the message “hello” to an intelligent LCD display shown i
Figure 8.8. Port 1 supplies the data byte. Port 3.2 selects the command (0) or data (11
registers. Port 3.3 enables a read (0) or write (1) level. and port 3.4 generates an active
low-enable strobe,APPUCATIONS 157
FIGURE 8.9 Intelligent LCD Circuit for “Lcdisp” Program
+5V -5v
ADDRESS:
ledisp:
Two Line x 20 Character
Intelligent LCD Display 14P3.4
Enable Low 8031
123.2
13P3.3
1P1.0
2PL1
3PL2
4PL3.
SP14
6P1S
7PL6
aPL7
MNEMONIC
org 0000h
clr p3.2
clr p3.3
mov a.#3fh
acall strobe
mov a,#0eh
acall strobe
mov 2, #06h
acall strobe
mov a,#01h
acall strobe
setb p3.2
nov a,#'h
acall strobe
mov a.#'e"
acall strobe
mov a,#'1'
acall strobe
acall strobe
mov a.#'o
acall strobe
COMMENT
select the command register
select write level
command 8 bits/char., 2 rows, 5 x 10
strobe command to display
command screen and cursor on, no blink
;command curser right as data displayed
;elear all and home cursor
select display data RAM register
say ‘“hello'
Continued158 CHAPTER EIGHT
ADDRESS — MNEMONIC ‘COMMENT
Continued
here simp here rmessage sent
:the subroutine ‘'strobe' is used to check for a display busy
:¢ondition, and pulse P3.3 high-low-high to enable the display
iwrite or read
strobe: mov pl,#Offh ;configure port 1 as an input
setb p3.3 jset read level
wait: setb p3.4 igenerate read strobe
clr p3.4 yenable the display
jb pl.7,wait ;check for busy when BF = 1
setb p3.4 send of read strobe
clr p3.3 rwrite character to display
setb p3.2 :choose data RAM
mov pl.a :character to port 1
clr p3.4 igenerate write strobe
setb p3.4
clr p3.2 ireturn with display as before call
ret
end
COMMENT —
If long character strings are to be displayed, then a subroutine could be written that receives
the beginning address of the string, The subroutine then displays the characters until a unique
“end-of-string” character is found,
Pulse Measurement
Sensors used for industrial and commercial control applications frequently produce pulses
that contain information about the quantity sensed. Varying the sensor output frequency,
using a constant duty cycle but variable frequency pulses to indicate changes in the mea-
sured variable, is most common. Varying the duration of the pulse width, resulting in
constant frequency but variable duty cycle, is also used. In this section, we examine pro-
grams that deal with both techniques.
Measuring Frequency
Timers TO and TI can be used to measure external frequencies by configuring one timer as
a counter and using the second timer to generate a timing interval over which the first can
count. The frequency of the counted pulse train is then
Unknown frequency = Counter/timer
For example, if the counter counts 200 pulses over an interval of .1 second generated by
the timer, the frequency is
UF = 200/.1 = 2000 Hz