0% found this document useful (0 votes)
6 views58 pages

Microcontroller

This chapter discusses the 8051 microcontrollers, comparing them with general-purpose microprocessors and highlighting their advantages in embedded systems. It covers criteria for selecting microcontrollers, variations within the 8051 family, and the importance of integrated features for cost and space efficiency. Additionally, it reviews the history and specifications of the 8051 and its variants, emphasizing their compatibility and application in various embedded products.

Uploaded by

Saadman Abeer
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views58 pages

Microcontroller

This chapter discusses the 8051 microcontrollers, comparing them with general-purpose microprocessors and highlighting their advantages in embedded systems. It covers criteria for selecting microcontrollers, variations within the 8051 family, and the importance of integrated features for cost and space efficiency. Additionally, it reviews the history and specifications of the 8051 and its variants, emphasizing their compatibility and application in various embedded products.

Uploaded by

Saadman Abeer
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

The 8051 Microcontrollers

Objectives
Upon completion of this chapter, you will be able to:

• Compare and contrast microprocessors and microcontrollers


• Describe the advantages of microcontrollers for some applications
• Explain the concept of embedded systems

• Discuss criteria for considering a microcontroller


• Explain the variations of speed, packaging, memory, and cost per unit and how these affect choosing a
microcontroller
• Compare and contrast the various members of the 8051 family

• Compare 8051 microcontrollers offered by various manufacturers


This chapter begins with a discussion of the role and importance of microcontrollers in everyday life. In
Section 1 we also discuss criteria to consider in choosing a microcontroller, as well as the use of microcon-
trollers in the embedded market. Section 2 covers various members of the 8051 family such as the 8052 and
8031, and their features. In addition, we discuss various versions of the 8051 such as the 8751, AT89C51,
and DS5000.

1 Microcontrollers and Embedded Processors


In this section we discuss the need for microcontrollers and contrast them with general-purpose micropro-
cessors such as the Pentium and other x86 microprocessors. We also look at the role of microcontrollers in
the embedded market. In addition, we provide some criteria on how to choose a microcontroller.

1.1 Microcontroller versus General-Purpose Microprocessor


What is the difference between a microprocessor and microcontroller? By microprocessor is meant the
general-purpose microprocessors such as Intel’s x86 family (8086, 80286, 80386, 80486, and the Pentium)
or Motorola’s 680x0 family (68000, 68010, 68020, 68030, 68040, etc.). These microprocessors contain no
RAM, no ROM, and no I/O ports on the chip itself. For this reason, they are commonly referred to as
general-purpose microprocessors.

Figure 1: Microprocessor System Contrasted With Microcontroller System

1
CPU RAM ROM
I/O Timer Serial COM Port

Figure 2: Microcontroller Block

A system designer using a general-purpose microprocessor such as the Pentium or the 68040 must add
RAM, ROM, I/O ports, and timers externally to make them functional. Although the addition of external
RAM, ROM, and I/O ports makes these systems bulkier and much more expensive, they have the advantage
of versatility such that the designer can decide on the amount of RAM, ROM, and I/O ports needed to fit the
task at hand. This is not the case with microcontrollers. A microcontroller has a CPU (a microprocessor) in
addition to a fixed amount of RAM, ROM, I/O ports, and a timer all on a single chip. In other words, the
processor, RAM, ROM, I/O ports, and timer are all embedded together on one chip; therefore, the designer
cannot add any external memory, I/O, or timer to it. The fixed amount of on-chip ROM, RAM, and number
of I/O ports in microcontrollers makes them ideal for many applications in which cost and space are critical.

Table 1: Some Embedded Products Using Microcontrollers

Home Office
Appliances Telephones
Intercom Computers
Telephones Security systems
Security systems Fax machine
Garage door openers Microwave
Answering machines Copier
Fax machines Laser printer
Home computers Color printer
TVs Paging
Cable TV tuner Auto
VCR Trip computer
Camcorder Engine control
Remote controls Air bag
Video games ABS
Cellular phones Instrumentation
Musical instruments Security system
Sewing machines Transmission control
Lighting control Entertainment
Paging Climate control
Camera Cellular phone
Pinball machines Keyless entry
Toys
Exercise equipment

In many applications, for example a TV remote control, there is no need for the computing power of a
486 or even an 8086 microprocessor. In many applications, the space it takes, the power it consumes, and
the price per unit are much more critical considerations than the computing power. These applications most
often require some I/O operations to read signals and turn on and off certain bits. For this reason some call
these processors IBP, “itty-bitty processors.”
It is interesting to note that some microcontroller manufacturers have gone as far as integrating an ADC
(analog-to-digital converter) and other peripherals into the microcontroller.

1.2 Microcontrollers for Embedded Systems


In the literature discussing microprocessors, we often see the term embedded system. Microprocessors and
microcontrollers are widely used in embedded system products. An embedded product uses a microprocessor

2
(or microcontroller) to do one task and one task only. A printer is an example of embedded system since the
processor inside it performs only one task; namely, getting the data and printing it. Contrast this with a
Pentium-based PC (or any x86 IBM-compatible PC). A PC can be used for any number of applications such
as word processor, print server, bank teller terminal, video game player, network server, or internet terminal.
Software for a variety of applications can be loaded and run. Of course the reason a PC can perform myriad
tasks is that it has RAM memory and an operating system that loads the application software into RAM and
lets the CPU run it. In an embedded system, there is only one application software that is typically burned
into ROM. An x86 PC contains or is connected to various embedded products such as the keyboard, printer,
modem, disk controller, sound card, CD-ROM driver, mouse, and so on. Each one of these peripherals
has a microcontroller inside it that performs only one task. For example, inside every mouse there is a
microcontroller that performs the task of finding the mouse position and sending it to the PC. Table 1 lists
some embedded products.

1.3 X86 PC Embedded Applications


Although microcontrollers are the preferred choice for many embedded systems, there are times that a
microcontroller is inadequate for the task. For this reason, in recent years many manufacturers of general-
purpose microprocessors such as Intel, Freescale Semiconductor Inc. (formerly Motorola), AMD (Advanced
Micro Devices, Inc.), and Cyrix (now a division of National Semiconductor, Inc.) have targeted their
microprocessor for the high end of the embedded market. While Intel and AMD push their x86 processors
for both the embedded and desktop PC markets, Freescale is determined to keep the 68000 family alive by
targeting it mainly for the high end of embedded systems now that Apple no longer uses the 680x0 in their
Macintosh. In the early 1990s Apple computer began using Power PC microprocessors (604, 603, 620, etc.)
in place of the 680x0 for the Macintosh. The Power PC microprocessor is a joint venture between IBM and
Freescale, and is targeted for the high end of the embedded market as well as the PC market. It must be noted
that when a company targets a general-purpose microprocessor for the embedded market it optimizes the
processor used for embedded systems. For this reason these processors are often called high-end embedded
processors. Very often the terms embedded processor and microcontroller are used interchangeably.
One of the most critical needs of an embedded system is to decrease power consumption and space. This
can be achieved by integrating more functions into the CPU chip. All the embedded processors based on the
x86 and 680x0 have low power consumption in addition to some forms of I/O, COM port, and ROM all on
a single chip. In high-performance embedded processors, the trend is to integrate more and more functions
on the CPU chip and let the designer decide which features he/she wants to use. This trend is invading PC
system design as well. Normally, in designing the PC motherboard we need a CPU plus a chip-set containing
I/O, a cache controller, a flash ROM containing BIOS, and finally a secondary cache memory. New designs
are emerging in industry. For example, Cyrix has announced that it is working on a chip that contains the
entire PC, except for DRAM. In other words, we are about to see an entire computer on a chip.
Currently, because of MS-DOS and Windows standardization many embedded systems are using x86
PCs. In many cases using x86 PCs for the high-end embedded applications not only saves money but also
shortens development time since there is a vast library of software already written for the DOS and Windows
platforms. The fact that Windows is a widely used and well understood platform means that developing a
Windows-based embedded product reduces the cost and shortens the development time considerably.

1.4 Choosing a Microcontroller


There are four major 8-bit microcontrollers. They are: Freescale’s 6811, Intel’s 8051, Zilog’s Z8, and PIC
16X from Microchip Technology. Each of these microcontrollers has a unique instruction set and register
set; therefore, they are not compatible with each other. Programs written for one will not run on the
others. There are also 16-bit and 32-bit microcontrollers made by various chip makers. With all these
different microcontrollers, what criteria do designers consider in choosing one? Three criteria in choosing
microcontrollers are as follows: (1) meeting the computing needs of the task at hand efficiently and cost
effectively, (2) availability of software development tools such as compilers, assemblers, and debuggers, and
(3) wide availability and reliable sources of the microcontroller. Next we elaborate further on each of the
above criteria.

3
1.5 Criteria for Choosing a Microcontroller
1. The first and foremost criterion in choosing a microcontroller is that it must meet the task at hand
efficiently and cost effectively. In analyzing the needs of a microcontroller-based project, we must first
see whether an 8-bit, 16-bit, or 32-bit microcontroller can best handle the computing needs of the task
most effectively. Among other considerations in this category are:
(a) Speed. What is the highest speed that the microcontroller supports?
(b) Packaging. Does it come in a 40-pin DIP (dual inline package) or a QFP (quad flat package), or
some other packaging format? This is important in terms of space, assembling, and prototyping
the end product.
(c) Power consumption. This is especially critical for battery-powered products.
(d) The amount of RAM and ROM on chip.
(e) The number of I/O pins and the timer on the chip.
(f) How easy it is to upgrade to higher-performance or lower power-consumption versions.
(g) Cost per unit. This is important in terms of the final cost of the product in which a microcon-
troller is used. For example, there are microcontrollers that cost 50 cents per unit when purchased
100,000 units at a time.
2. The second criterion in choosing a microcontroller is how easy it is to develop products around it. Key
considerations include the availability of an assembler, debugger, a code-efficient C language compiler,
emulator, technical support, and both in-house and outside expertise. In many cases, third-party
vendor (that is, a supplier other than the chip manufacturer) support for the chip is as good as, if not
better than, support from the chip manufacturer.
3. The third criterion in choosing a microcontroller is its ready availability in needed quantities both now
and in the future. For some designers this is even more important than the first two criteria. Currently,
of the leading 8-bit microcontrollers, the 8051 family has the largest number of diversified (multiple
source) suppliers. By supplier is meant a producer besides the originator of the microcontroller. In
the case of the 8051, which was originated by Intel, several companies also currently produce (or have
produced in the past) the 8051. These companies include: Intel, Atmel, Philips/Signetics, AMD,
Infineon (formerly Siemens), Matra, and Dallas Semiconductor. See Table 2.

Table 2: Some of the Companies Producing a Member of the 8051 Family

Company Web Site


Intel [Link]/design/mcs51
Atmel [Link]
Philips/Signetics [Link]
Infineon [Link]
Dallas Semi/Maxim [Link]

It should be noted that Freescale, Zilog, and Microchip Technology have all dedicated massive resources
to ensure wide and timely availability of their product since their product is stable, mature, and single
sourced. In recent years they also have begun to sell the ASIC library cell of the microcontroller.

Review Questions
1. True or false. Microcontrollers are normally less expensive than microprocessors.
2. When comparing a system board based on a microcontroller and a general-purpose microprocessor,
which one is cheaper?
3. A microcontroller normally has which of the following devices on-chip?

4
(a) RAM (b) ROM (c) I/O (d) all of the above
4. A general-purpose microprocessor normally needs which of the following devices to be attached to it?
(a) RAM (b) ROM (c) I/O (d) all of the above
5. An embedded system is also called a dedicated system. Why?

6. What does the term embedded system mean?


7. Why does having multiple sources of a given product matter?

2 Overview of the 8051 Family


In this section we first look at the various members of the 8051 family of microcontrollers and their internal
features. Plus we see who are the different manufacturers of the 8051 and what kind of products they offer.

2.1 A Brief History of the 8051


In 1981, Intel Corporation introduced an 8-bit microcontroller called the 8051. This microcontroller had 128
bytes of RAM, 4K bytes of on-chip ROM, two timers, one serial port, and four ports (each 8-bits wide) all
on a single chip. At the time it was also referred to as a “system on a chip.” The 8051 is an 8-bit processor,
meaning that the CPU can work on only 8 bits of data at a time. Data larger than 8 bits has to be broken
into 8-bit pieces to be processed by the CPU. The 8051 has a total of four I/O ports, each 8 bits wide. See
Figure 3. Although the 8051 can have a maximum of 64K bytes of on-chip ROM, many manufacturers have
put only 4K bytes on the chip. This will be discussed in more detail later.
The 8051 became widely popular after Intel allowed other manufacturers to make and market any flavors
of the 8051 they please with the condition that they remain code-compatible with the 8051. This has led
to many versions of the 8051 with different speeds and amounts of on-chip ROM marketed by more than
half a dozen manufacturers. Next we review some of them. It is important to note that although there are
different flavors of the 8051 in terms of speed and amount of on-chip ROM, they are all compatible with the
original 8051 as far as the instructions are concerned. This means that if you write your program for one, it
will run on any of them regardless of the manufacturer.

2.2 8051 Microcontroller


The 8051 is the original member of the 8051 family. Intel refers to it as MCS-51. Table 3 shows the main
features of the 8051.

Table 3: Features of the 8051

Feature Quantity
ROM 4K bytes
RAM 128 bytes
Timer 2
I/O pins 32
Serial port 1
Interrupt sources 6

Note: ROM amount indicates on-chip program space.

2.3 Other Members of the 8051 Family


There are two other members in the 8051 family of microcontrollers. They are the 8052 and the 8031.

5
Figure 3: Inside the 8051 Microcontroller Block Diagram

2.3.1 8052 Microcontroller


The 8052 is another member of the 8051 family. The 8052 has all the standard features of the 8051 as well
as an extra 128 bytes of RAM and an extra timer. In other words, the 8052 has 256 bytes of RAM and 3
timers. It also has 8K bytes of on-chip program ROM instead of 4K bytes. See Table 4.

Table 4: Comparison of 8051 Family Members

Feature 8051 8052 8031


ROM (on-chip program space in bytes) 4K 8K 0K
RAM (bytes) 128 256 128
Timers 2 3 2
I/O pins 32 32 32
Serial port 1 1 1
Interrupt sources 6 8 6

As can be seen from Table 4, the 8051 is a subset of the 8052; therefore all programs written for the 8051
will run on the 8052, but the reverse is not true.

2.3.2 8031 Microcontroller


Another member of the 8051 family is the 8031 chip. This chip is often referred to as a ROM-less 8051 since
it has 0K bytes of on-chip ROM. To use this chip you must add external ROM to it. This external ROM
must contain the program that the 8031 will fetch and execute. Contrast that to the 8051 in which the
on-chip ROM contains the program to be fetched and executed but is limited to only 4K bytes of code. The
ROM containing the program attached to the 8031 can be as large as 64K bytes. In the process of adding
external ROM to the 8031, you lose two ports. That leaves only 2 ports (of the 4 ports) for I/O operations.
To solve this problem, you can add external I/O to the 8031. Interfacing the 8031 with memory and I/O
ports such as the 8255 chip is discussed in Chapter 14. There are also various speed versions of the 8031
available from different companies.

6
2.4 Various 8051 Microcontrollers
Although the 8051 is the most popular member of the 8051 family, you will not see “8051” in the part
number. This is because the 8051 is available in different memory types, such as UV-EPROM, flash, and
NV-RAM, all of which have different part numbers. A discussion of the various types of ROM will be given in
Chapter 14. The UV-EPROM version of the 8051 is the 8751. The flash ROM version is marketed by many
companies including Atmel Corp. and Dallas Semiconductor. The Atmel Flash 8051 is called AT89C51,
while Dallas Semiconductor calls theirs DS89C4x0 (DS89C420/430/440). The NV-RAM version of the 8051
made by Dallas Semiconductor is called DS5000. There is also an OTP (one-time programmable) version
of the 8051 made by various manufacturers. Next we discuss briefly each of the above chips and describe
applications where they are used.

2.4.1 8751 Microcontroller


This 8751 chip has only 4K bytes of on-chip UV-EPROM. Using this chip for development requires access to
a PROM burner, as well as a UV-EPROM eraser to erase the contents of UV-EPROM inside the 8751 chip
before you can program it again. Because the on-chip ROM for the 8751 is UV-EPROM, it takes around 20
minutes to erase the 8751 before it can be programmed again. This has led many manufacturers to introduce
flash and NV-RAM versions of the 8051, as we will discuss next. There are also various speed versions of
the 8751 available from different companies.

2.4.2 DS89C4x0 from Dallas Semiconductor (Maxim)


Many popular 8051 chips have on-chip ROM in the form of flash memory. The AT89C51 from Atmel Corp.
is one example of an 8051 with flash ROM. This is ideal for fast development since flash memory can be
erased in seconds compared to the twenty minutes or more needed for the 8751. For this reason the AT89C51
is used in place of the 8751 to eliminate the waiting time needed to erase the chip and thereby speed up
the development time. Using the AT89C51 to develop a microcontroller-based system requires a ROM
burner that supports flash memory; however, a ROM eraser is not needed. Notice that in flash memory
you must erase the entire contents of ROM in order to program it again. This erasing of flash is done by
the PROM burner itself, which is why a separate eraser is not needed. To eliminate the need for a PROM
burner, Dallas Semiconductor, now part of the Maxim Corp., has a version of the 8051/52 called DS89C4x0
(DS89C420/430/...) that can be programmed via the serial COM port of an IBM PC.
Notice that the on-chip ROM for the DS89C4x0 is in the form of flash. The DS89C4x0 (420/430/440/450)
comes with an on-chip loader, which allows the program to be loaded into the on-chip flash ROM while it is
in the system. This can be done via the serial COM port of an IBM PC. This in-system program loading of
the DS89C4x0 via a PC serial COM port makes it an ideal home development system. Dallas Semiconductor
also has an NV-RAM version of the 8051 called DS5000. The advantage of NV-RAM is the ability to change
the ROM contents one byte at a time. The DS5000 also comes with a loader, allowing it to be programmed
via the PC’s COM port. See Table 5. From Table 5, notice that the DS89C4x0 is really an 8052 chip since
it has 256 bytes of RAM and 3 timers. More details of this chip are given throughout the book.

Table 5: Versions of 8051/52 Microcontroller From Dallas Semiconductor (Maxim)

Part Number ROM RAM I/O Timers Int. VCC


DS89C420/30 16K (Flash) 256 32 3 6 5V
DS89C440 32K (Flash) 256 32 3 6 5V
DS89C450 64K (Flash) 256 32 3 6 5V
DS5000 8K (NVRAM) 128 32 2 6 5V
DS80C320 0K 256 32 3 6 5V
DS87520 16K (UVROM) 256 32 3 6 5V

Source: [Link]/products/microcontrollers/8051 drop [Link]

7
2.4.3 DS89C4x0 Trainer
In Chapter 8, we discuss the design of DS89C4x0 Trainer extensively. The MDE8051 Trainer is available
from [Link]. This Trainer allows you to program the DS89C4x0 chip from the COM port
of the x86 IBM PC, with no need for a ROM burner.
For a DS89C4x0-based trainer see [Link].

2.4.4 AT89C51 from Atmel Corporation


The Atmel Corp. has a wide selection of 8051 chips, as shown in Tables 6 and 7. For example, the AT89C51
is a popular and inexpensive chip used in many small projects. It has 4K bytes of flash ROM. Notice the
AT89C51-12PC, where “C” before the 51 stands for CMOS, which has a low power consumption, “12”
indicates 12 MHz, “P” is for plastic DIP package, “C” is for commercial.

Table 6: Versions of 8051 From Atmel (All ROM Flash)

Part Number ROM RAM I/O Timer Int. VCC


AT89C51 4K 128 32 2 6 5V
AT89LV51 4K 128 32 2 6 3V
AT89C1051 1K 64 15 1 3 3V
AT89C2051 2K 128 15 2 6 3V
AT89C52 8K 128 32 3 8 5V
AT89LV52 8K 128 32 3 8 3V

Note: “C” in the part number indicates CMOS.

Table 7: Various Speeds of 8051 From Atmel

Part Number Speed Pins Use


AT89C51-12PC 12 MHz 40 DIP plastic
commercial
AT89C51-16PC 16 MHz 40 DIP plastic
commercial
AT89C51-20PC 20 MHz 40 DIP plastic
commercial

2.4.5 OTP Version of the 8051


There are also OTP (one-time-programmable) versions of the 8051 available from different sources. Flash and
NV-RAM versions are typically used for product development. When a product is designed and absolutely
finalized, the OTP version of the 8051 is used for mass production since it is much cheaper in terms of price
per unit.

2.4.6 8051 Family from Philips


Another major producer of the 8051 family is Philips Corporation. Indeed, they have one of the largest
selections of 8051 microcontrollers. Many of their products include features such as A-to-D converters, D-to-
A converters, extended I/O, and both OTP and flash. For the list of companies producing the 8051 family
see the Web sites in the box below.
See the following Web sites for 8051 products and their features from various companies:

• [Link]/[Link]
• [Link]

8
Review Questions
8. Name three features of the 8051.
9. What is the major difference between the 8051 and 8052 microcontrollers?

10. Give the size of RAM in each of the following.


(a) 8051 (b) 8052 (c) 8031
11. Give the size of the on-chip ROM in each of the following.
(a) 8051 (b) 8052 (c) 8031

12. The 8051 is a(n) -bit microprocessor.


13. State a major difference between the 8751, the AT89C51, and the DS89C420/30.
14. True or false. The DS89C420/30 is really an 8052 chip.

15. True or false. The DS89C420/30 has a loader embedded to the chip, therefore eliminating the need for
ROM burner.
16. The DS89C420/30 chip has bytes of on-chip ROM.
17. The DS89C420/30 chip has bytes of RAM.

Summary
This chapter discussed the role and importance of microcontrollers in everyday life. Microprocessors and
microcontrollers were contrasted and compared. We discussed the use of microcontrollers in the embedded
market. We also discussed criteria to consider in choosing a microcontroller such as speed, memory, I/O,
packaging, and cost per unit. The second section of this chapter described various family members of the
8051, such as the 8052 and 8031, and their features. In addition, we discussed various versions of the 8051
such as the AT89C51 and DS89C4x0, which are marketed by suppliers other than Intel.

Problems
Section 1.1: Microcontrollers and Embedded Processors
1. True or False. A general-purpose microprocessor has on-chip ROM.
2. True or False. A microcontroller has on-chip ROM.

3. True or False. A microcontroller has on-chip I/O ports.


4. True or False. A microcontroller has a fixed amount of RAM on the chip.
5. What components are normally put together with the microcontroller into a single chip?
6. Intel’s Pentium chips used in Windows PCs need external and chips to store data and
code.
7. List three embedded products attached to a PC.
8. Why would someone want to use an x86 as an embedded processor?
9. Give the name and the manufacturer of some of the most widely used 8-bit microcontrollers.

10. In Question 9, which microcontroller has the most manufacture sources?


11. In a battery-based embedded product, what is the most important factor in choosing a microcontroller?

9
12. In an embedded controller with on-chip ROM, why does the size of the ROM matter?
13. In choosing a microcontroller, how important is it to have multiple sources for that chip?
14. What does the term “third-party support” mean?
15. If a microcontroller architecture has both 8-bit and 16-bit versions, which of the following statements
is true?
(a) The 8-bit software will run on the 16-bit system.
(b) The 16-bit software will run on the 8-bit system.

Section 1.2: Overview of the 8051 Family


16. The 8751 has bytes of on-chip ROM.
17. The AT89C51 has bytes of on-chip RAM.
18. The 8051 has on-chip timer(s).
19. The 8052 has bytes of on-chip RAM.
20. The ROM-less version of the 8051 uses as the part number.
21. The 8051 family has pins for I/O.
22. The 8051 family has circuitry to support serial ports.
23. The 8751 on-chip ROM is of type .
24. The AT89C51 on-chip ROM is of type .
25. The DS5000 on-chip ROM is of type .
26. The DS89C420/30 on-chip ROM is of type .
27. Give the amount of ROM and RAM for the following chips.
(a) AT89C51 (b) DS89C420/30 (c) DS89C440
28. Of the 8051 family, which memory type is the most cost effective if you are using a million of them in
an embedded product?
29. What is the difference between the 8031 and 8051?
30. Of the 8051 microcontrollers, which one is the best for a home development environment? (You do not
have access to a ROM burner.)

Answers to Review Questions


Section 1.1: Microcontrollers and Embedded Processors
1. True
2. A microcontroller-based system
3. (d)
4. (d)
5. It is dedicated since it is dedicated to doing one type of job.
6. Embedded system means that the application and processor are combined into a single system.
7. Having multiple sources for a given part means you are not hostage to one supplier. More importantly,
competition among suppliers brings about lower cost for that product.

10
Section 1.2: Overview of the 8051 Family
8. 128 bytes of RAM, 4K bytes of on-chip ROM, four 8-bit I/O ports.
9. The 8052 has everything that the 8051 has, plus an extra timer, and the on-chip ROM is 8K bytes
instead of 4K bytes. The RAM in the 8052 is 256 bytes instead of 128 bytes.
10. Both the 8051 and the 8031 have 128 bytes of RAM and the 8052 has 256 bytes.
11. (a) 4K bytes (b) 8K bytes (c) 0K bytes
12. 8
13. The main difference is the type of on-chip ROM. In the 8751 it is UV-EPROM; in the AT89C51 it is
flash; and in the DS89C420/30 it is flash with a loader on the chip.
14. True
15. True
16. 16K
17. 256
8051 Assembly Language Programming

Objectives
Upon completion of this chapter, you will be able to:
• List the registers of the 8051 microcontroller
• Manipulate data using the registers and MOV instructions
• Code simple 8051 Assembly language instructions
• Assemble and run an 8051 program
• Describe the sequence of events that occur upon 8051 power-up
• Examine programs in ROM code of the 8051
• Explain the ROM memory map of the 8051
• Detail the execution of 8051 Assembly language instructions
• Describe 8051 data types
• Explain the purpose of the PSW (program status word) register
• Discuss RAM memory space allocation in the 8051
• Diagram the use of the stack in the 8051
• Manipulate the register banks of the 8051
In Section 2.1 we look at the inside of the 8051. We demonstrate some of the widely used registers of the
8051 with simple instructions such as MOV and ADD. In Section 2.2 we examine Assembly language and
machine language programming and define terms such as mnemonics, opcode, operand, etc. The process
of assembling and creating a ready-to-run program for the 8051 is discussed in Section 2.3. Step-by-step
execution of an 8051 program and the role of the program counter are examined in Section 2.4. In Section 2.5
we look at some widely used Assembly language directives, pseudocode, and data types related to the 8051.
In Section 2.6 we discuss the flag bits and how they are affected by arithmetic instructions. Allocation of
RAM memory inside the 8051 plus the stack and register banks of the 8051 are discussed in Section 2.7.

11
3 Inside the 8051
In this section we examine the major registers of the 8051 and show their use with the simple instructions
MOV and ADD.

3.1 Registers
In the CPU, registers are used to store information temporarily. That information could be a byte of data to
be processed, or an address pointing to the data to be fetched. The vast majority of 8051 registers are 8-bit
registers. In the 8051 there is only one data type: 8 bits. The 8 bits of a register are shown in the diagram
from the MSB (most significant bit) D7 to the LSB (least significant bit) D0. With an 8-bit data type,
any data larger than 8 bits must be broken into 8-bit chunks before it is processed. Since there are a large
number of registers in the 8051, we will concentrate on some of the widely used general-purpose registers
and cover special registers in future chapters. See Appendix A.2 for a complete list of 8051 registers.
The most widely used registers of the 8051 are A (accumulator), B, R0, R1, R2, R3, R4, R5, R6, R7,
DPTR (data pointer), and PC (program counter). All of the above registers are 8-bits, except DPTR and
the program counter. The accumulator, register A, is used for all arithmetic and logic instructions. To
understand the use of these registers, we will show them in the context of two simple instructions, MOV and
ADD.

3.2 MOV Instruction


Simply stated, the MOV instruction copies data from one location to another. It has the following format:

Listing 1: MOV Instruction Format


MOV d e s t i n a t i o n , s o u r c e ; copy s o u r c e t o d e s t .
This instruction tells the CPU to move (in reality, copy) the source operand to the destination operand.
For example, the instruction “MOV A,R0” copies the contents of register R0 to register A. After this
instruction is executed, register A will have the same value as register R0. The MOV instruction does not
affect the source operand. The following program first loads register A with value 55H (that is 55 in hex),
then moves this value around to various registers inside the CPU. Notice the “#” in the instruction. This
signifies that it is a value. The importance of this will be discussed soon.

Listing 2: MOV Instruction Example


MOV A,#55H ; l o a d v a l u e 55H i n t o r e g . A
MOV R0 ,A ; copy c o n t e n t s o f A i n t o R0
; ( now A=R0=55H)
MOV R1 ,A ; copy c o n t e n t s o f A i n t o R1
; ( now A=R0=R1=55H)
MOV R2 ,A ; copy c o n t e n t s o f A i n t o R2
; now A=R0=R1=R2=55H)
MOV R3,#95H ; l o a d v a l u e 95H i n t o R3
; ( now R3=95H)
MOV A, R3 ; copy c o n t e n t s o f R3 i n t o A
; now A=R3=95H)
When programming the 8051 microcontroller, the following points should be noted:

1. Values can be loaded directly into any of registers A, B, or R0–R7. However, to indicate that it is an
immediate value it must be preceded with a pound sign (#). This is shown next.

Listing 3: Loading Immediate Values


MOV A,#23H ; l o a d 23H i n t o A (A=23H)
MOV R0,#12H ; l o a d 12H i n t o R0 (R0=12H)
MOV R1,#1FH ; l o a d 1FH i n t o R1 (R1=1FH)

12
Figure 4: Some 8-bit Registers of the 8051

13
Figure 5: Some 8051 16-bit Registers

MOV R2,#2BH ; l o a d 2BH i n t o R2 (R2=2BH)


MOV B,#3CH ; l o a d 3CH i n t o B (B=3CH)
MOV R7,#9DH ; l o a d 9DH i n t o R7 (R7=9DH)
MOV R5,#0F9H ; l o a d F9H i n t o R5 (R5=F9H)
MOV R6,#12 ; l o a d 12 d e c i m a l (0CH)
; i n t o r e g . R6 (R6=0CH)

Notice in instruction “MOV R5, #0F9H” that a 0 is used between the # and F to indicate that F is
a hex number and not a letter. In other words “MOV R5, #F9H” will cause an error.

2. If values 0 to F are moved into an 8-bit register, the rest of the bits are assumed to be all zeros. For
example, in “MOV A, #5” the result will be A=05; that is, A=00000101 in binary.
3. Moving a value that is too large into a register will cause an error.

Listing 4: Illegal MOV Instructions


MOV A,#7F2H ; ILLEGAL : 7F2H > 8 b i t s (FFH)
MOV R2,#456 ; ILLEGAL : 456 > 255 d e c i m a l (FFH)

4. A value to be loaded into a register must be preceded with a pound sign (#). Otherwise it means to
load from a memory location. For example “MOV A,17H” means to move into A the value held in
memory location 17H, which could have any value. In order to load the value 17H into the accumulator
we must write “MOV A,#17H” with the # preceding the number. Notice that the absence of the pound
sign will not cause an error by the assembler since it is a valid instruction. However, the result would
not be what the programmer intended. This is a common error for beginning programmers in the 8051.

3.3 ADD Instruction


The ADD instruction has the following format:

Listing 5: ADD Instruction Format


ADD A, s o u r c e ;ADD t h e s o u r c e operand
; to the accumulator
The ADD instruction tells the CPU to add the source byte to register A and put the result in register
A. To add two numbers such as 25H and 34H, each can be moved to a register and then added together:

Listing 6: ADD Instruction Example 1


MOV A, #25H ; l o a d 25H i n t o A
MOV R2 , #34H ; l o a d 34H i n t o R2
ADD A, R2 ; add R2 t o a c c u m u l a t o r
; (A = A + R2)

14
Executing the program above results in A = 59H (25H + 34H = 59H) and R2 = 34H. Notice that the
content of R2 does not change. The program above can be written in many ways, depending on the registers
used. Another way might be:

Listing 7: ADD Instruction Example 2


MOV R5 , #25H ; l o a d 25H i n t o R5 (R5 = 25H)
MOV R7 , #34H ; l o a d 34H i n t o R7 (R7 = 34H)
MOV A, #0 ; l o a d 0 i n t o A (A = 0 , c l e a r A)
ADD A, R5 ; add t o A c o n t e n t o f R5
; where A = A + R5
ADD A, R7 ; add t o A c o n t e n t o f R7
; where A = A + R7
The program above results in A = 59H. There are always many ways to write the same program. One
question that might come to mind after looking at the program above, is whether it is necessary to move
both data items into registers before adding them together. The answer is no, it is not necessary. Look at
the following variation of the same program:

Listing 8: ADD Instruction with Immediate Operand


MOV A,#25H ; l o a d one operand i n t o A (A=25H)
ADD A,#34H ; add t h e second operand 34H t o A
In the above case, while one register contained one value, the second value followed the instruction as an
operand. This is called an immediate operand. The examples shown so far for the ADD instruction indicate
that the source operand can be either a register or immediate data, but the destination must always be
register A, the accumulator. In other words, an instruction such as “ADD R2,#12H” is invalid since register
A (accumulator) must be involved in any arithmetic operation. Notice that “ADD R4,A” is also invalid
for the reason that A must be the destination of any arithmetic operation. To put it simply: In the 8051,
register A must be involved and be the destination for all arithmetic operations. The foregoing discussion
explains why register A is referred to as the accumulator. The format for Assembly language instructions,
descriptions of their use, and a listing of legal operand types are provided in Appendix A.1.
There are two 16-bit registers in the 8051: PC (program counter) and DPTR (data pointer). The
importance and use of the program counter are covered in Section 2.4. The DPTR register is used in
accessing data and is discussed in Chapter 5 where addressing modes are covered.

Review Questions
1. Write the instructions to move value 34H into register A and value 3FH into register B, then add them
together.
2. Write the instructions to add the values 16H and CDH. Place the result in register R2.

3. True or false. No value can be moved directly into registers R0–R7.


4. What is the largest hex value that can be moved into an 8-bit register? What is the decimal equivalent
of the hex value?
5. The vast majority of registers in 8051 are bits.

4 Introduction to 8051 Assembly Programming


In this section we discuss Assembly language format and define some widely used terminology associated
with Assembly language programming.
While the CPU can work only in binary, it can do so at a very high speed. For humans, however, it is quite
tedious and slow to deal with 0s and 1s in order to program the computer. A program that consists of 0s and
1s is called machine language. In the early days of the computer, programmers coded programs in machine

15
language. Although the hexadecimal system was used as a more efficient way to represent binary numbers,
the process of working in machine code was still cumbersome for humans. Eventually, Assembly languages
were developed that provided mnemonics for the machine code instructions, plus other features that made
programming faster and less prone to error. The term mnemonic is frequently used in computer science and
engineering literature to refer to codes and abbreviations that are relatively easy to remember. Assembly
language programs must be translated into machine code by a program called an assembler. Assembly
language is referred to as a low-level language because it deals directly with the internal structure of the
CPU. To program in Assembly language, the programmer must know all the registers of the CPU and the
size of each, as well as other details.
Today, one can use many different programming languages, such as BASIC, Pascal, C, C++, Java, and
numerous others. These languages are called high-level languages because the programmer does not have to
be concerned with the internal details of the CPU. Whereas an assembler is used to translate an Assembly
language program into machine code (sometimes also called object code or opcode for operation code), high-
level languages are translated into machine code by a program called a compiler. For instance, to write a
program in C, one must use a C compiler to translate the program into machine language. Now we look at
8051 Assembly language format and use an 8051 assembler to create a ready-to-run program.

4.1 Structure of Assembly Language


An Assembly language program consists of, among other things, a series of lines of Assembly language
instructions. An Assembly language instruction consists of a mnemonic, optionally followed by one or two
operands. The operands are the data items being manipulated, and the mnemonics are the commands to
the CPU, telling it what to do with those items.

Listing 9: Program 2-1: Sample of an Assembly Language Program


ORG 0H ; s t a r t ( origin ) at location 0
MOV R5,#25H ; l o a d 25H i n t o R5
MOV R7,#34H ; l o a d 34H i n t o R7
MOV A,#0 ; load 0 into A
ADD A, R5 ; add c o n t e n t s o f R5 t o A
; now A = A + R5
ADD A, R7 ; add c o n t e n t s o f R7 t o A
; now A = A + R7
ADD A,#12H ; add t o A v a l u e 12H
; now A = A + 12H
HERE: SJMP HERE ; stay in t h i s loop
END ; end o f asm s o u r c e f i l e
A given Assembly language program (see Program 2-1) is a series of statements, or lines, which are either
Assembly language instructions such as ADD and MOV, or statements called directives. While instructions
tell the CPU what to do, directives (also called pseudo-instructions) give directions to the assembler. For
example, in the above program while the MOV and ADD instructions are commands to the CPU, ORG and
END are directives to the assembler. ORG tells the assembler to place the opcode at memory location 0
while END indicates to the assembler the end of the source code. In other words, one is for the start of the
program and the other one for the end of the program.
An Assembly language instruction consists of four fields:

[label:] mnemonic [operands] [;comment]

Brackets indicate that a field is optional, and not all lines have them. Brackets should not be typed in.
Regarding the above format, the following points should be noted.

1. The label field allows the program to refer to a line of code by name. The label field cannot exceed a
certain number of characters. Check your assembler for the rule.

16
2. The Assembly language mnemonic (instruction) and operand(s) fields together perform the real work
of the program and accomplish the tasks for which the program was written. In Assembly language
statements such as “ADD A, B” and “MOV A, #67”, ADD and MOV are the mnemonics, which
produce opcodes; and “A, B” and “A, #67” are the operands. Instead of a mnemonic and an operand,
these two fields could contain assembler pseudo-instructions, or directives. Remember that directives do
not generate any machine code (opcode) and are used only by the assembler, as opposed to instructions
that are translated into machine code (opcode) for the CPU to execute. In Program 2-1 the commands
ORG (origin) and END are examples of directives (some 8051 assemblers use .ORG and .END). Check
your assembler for the rules. More of these pseudo-instructions are discussed in detail in Section 2.5.
3. The comment field begins with a semicolon comment indicator “;”. Comments may be at the end
of a line or on a line by themselves. The assembler ignores comments, but they are indispensable
to programmers. Although comments are optional, it is recommended that they be used to describe
the program and make it easier for someone else to read and understand, or for the programmer to
remember what they wrote.
4. Notice the label “HERE” in the label field in Program 2-1. Any label referring to an instruction must
be followed by a colon symbol, “:”. In the SJMP (short jump instruction), the 8051 is told to stay in
this loop indefinitely. If your system has a monitor program you do not need this line and it should
be deleted from your program. In the next section we will see how to create a ready-to-run program.

Review Questions
1. What is the purpose of pseudo-instructions?
2. are translated by the assembler into machine code, whereas are not.
3. True or false. Assembly language is a high-level language.
4. Which of the following produces opcode?

(a) ADD A,R2 (b) MOV A,#12 (c) ORG 2000H (d) SJMP HERE
5. Pseudo-instructions are also called .
6. True or false. Assembler directives are not used by the CPU itself. They are simply a guide to the
assembler.

7. In question 4, which one is an assembler directive?

5 Assembling and Running an 8051 Program


Now that the basic form of an Assembly language program has been given, the next question is: How it is
created, assembled, and made ready to run? The steps to create an executable Assembly language program
are outlined as follows.

1. First we use an editor to type in a program similar to Program 2-1. Many excellent editors or word
processors are available that can be used to create and/or edit the program. A widely used editor is the
MS-DOS EDIT program (or Notepad in Windows), which comes with all Microsoft operating systems.
Notice that the editor must be able to produce an ASCII file. For many assemblers, the file names
follow the usual DOS conventions, but the source file has the extension “asm” or “src”, depending on
which assembler you are using. Check your assembler for the convention. The “asm” extension for the
source file is used by an assembler in the next step.
2. The “asm” source file containing the program code created in step 1 is fed to an 8051 assembler. The
assembler converts the instructions into machine code. The assembler will produce an object file and
a list file. The extension for the object file is “obj” while the extension for the list file is “lst”.

17
Figure 6: Steps to Create a Program

18
3. Assemblers require a third step called linking. The link program takes one or more object files and
produces an absolute object file with the extension “abs”. This abs file is used by 8051 trainers that
have a monitor program.
4. Next, the “abs” file is fed into a program called “OH” (object to hex converter), which creates a file
with extension “hex” that is ready to burn into ROM. This program comes with all 8051 assemblers.
Recent Windows-based assemblers combine steps 2 through 4 into one step.

5.1 More About “asm” and “obj” Files


The “asm” file is also called the source file and for this reason some assemblers require that this file have
the “src” extension. Check your 8051 assembler to see which extension it requires. As mentioned earlier,
this file is created with an editor such as DOS EDIT or Windows Notepad. The 8051 assembler converts
the asm file’s Assembly language instructions into machine language and provides the obj (object) file. In
addition to creating the object file, the assembler also produces the lst file (list file).

5.2 List File


The lst (list) file, which is optional, is very useful to the programmer because it lists all the opcodes and
addresses as well as errors that the assembler detected. Many assemblers assume that the list file is not
wanted unless you indicate that you want to produce it. This file can be accessed by an editor such as DOS
EDIT and displayed on the monitor or sent to the printer to produce a hard copy. The programmer uses
the list file to find syntax errors. It is only after fixing all the errors indicated in the lst file that the obj file
is ready to be input to the linker program.

Table 8: Program 2-1: List File

Addr Opcode Instruction Comment


1 0000 ORG 0H ;start (origin) at 0
2 0000 7D25 MOV R5,#25H ;load 25H into R5
3 0002 7F34 MOV R7,#34H ;load 34H into R7
4 0004 7400 MOV A,#0 ;load 0 into A
5 0006 2D ADD A,R5 ;add contents of R5 to A
;now A=A+R5
6 0007 2F ADD A,R7 ;add contents of R7 to A
;now A=A+R7
7 0008 2412 ADD A,#12H ;add to A value 12H
;now A=A+12H
8 000A 80FE HERE:SJMP HERE ;stay in this loop
9 000C END ;end of asm source file

Review Questions
1. True or false. The DOS program EDIT produces an ASCII file.
2. True or false. Generally, the extension of the source file is “asm” or “src”.
3. Which of the following files can be produced by the DOS EDIT program? (a) [Link] (b)
[Link] (c) [Link] (d) [Link]
4. Which of the following files is produced by an 8051 assembler? (a) [Link] (b) [Link] (c)
[Link] (d) [Link]
5. Which of the following files lists syntax errors? (a) [Link] (b) [Link] (c) [Link]
(d) [Link]

19
6 The Program Counter and ROM Space in the 8051
In this section we examine the role of the program counter (PC) register in executing an 8051 program. We
also discuss ROM memory space for various 8051 family members.

6.1 Program Counter in the 8051


Another important register in the 8051 is the PC (program counter). The program counter points to the
address of the next instruction to be executed. As the CPU fetches the opcode from the program ROM,
the program counter is incremented to point to the next instruction. The program counter in the 8051 is 16
bits wide. This means that the 8051 can access program addresses 0000 to FFFFH, a total of 64K bytes of
code. However, not all members of the 8051 have the entire 64K bytes of on-chip ROM installed, as we will
see soon. Where does the 8051 wake up when it is powered? We will discuss this important topic next.

6.2 Where the 8051 Wakes Up When It Is Powered Up


One question that we must ask about any microcontroller (or microprocessor) is: At what address does the
CPU wake up upon applying power to it? Each microprocessor is different. In the case of the 8051 family
(that is, all members regardless of the maker and variation), the microcontroller wakes up at memory address
0000 when it is powered up. By powering up we mean applying VCC to the RESET pin as discussed in
Chapter 4. In other words, when the 8051 is powered up, the PC (program counter) has the value of 0000
in it. This means that it expects the first opcode to be stored at ROM address 0000H. For this reason in
the 8051 system, the first opcode must be burned into memory location 0000H of program ROM since this
is where it looks for the first instruction when it is booted. We achieve this by the ORG statement in the
source program as shown earlier. Next, we discuss the step-by-step action of the program counter in fetching
and executing a sample program.

6.3 Placing Code in Program ROM


To get a better understanding of the role of the program counter in fetching and executing a program, we
examine the action of the program counter as each instruction is fetched and executed. First, we examine
once more the list file of the sample program and how the code is placed in the ROM of an 8051 chip. As
we can see, the opcode and operand for each instruction are listed on the left side of the list file.

Table 9: Program 2-1: List File

ROM Addr Machine Language Assembly Language


0000 7D25 MOV R5,#25H
0002 7F34 MOV R7,#34H
0004 7400 MOV A,#0
0006 2D ADD A,R5
0007 2F ADD A,R7
0008 2412 ADD A,#12H
000A 80FE HERE:SJMP HERE

After the program is burned into ROM of an 8051 family member such as 8751 or AT89C51 or DS5000,
the opcode and operand are placed in ROM memory locations starting at 0000 as shown in the list below.
The list shows that address 0000 contains 7D, which is the opcode for moving a value into register R5,
and address 0001 contains the operand (in this case 25H) to be moved to R5. Therefore, the instruction
“MOV R5,#25H” has a machine code of “7D25”, where 7D is the opcode and 25 is the operand. Similarly,
the machine code “7F34” is located in memory locations 0002 and 0003 and represents the opcode and the
operand for the instruction “MOV R7,#34H”. In the same way, machine code “7400” is located in memory
locations 0004 and 0005 and represents the opcode and the operand for the instruction “MOV A,#0”. The
memory location 0006 has the opcode of 2D, which is the opcode for the instruction “ADD A, R5” and
memory location 0007 has the content 2F, which is the opcode for the “ADD A, R7” instruction. The

20
Table 10: Program 2-1: ROM Contents

Address Code
0000 7D
0001 25
0002 7F
0003 34
0004 74
0005 00
0006 2D
0007 2F
0008 24
0009 12
000A 80
000B FE

opcode for the instruction “ADD A, #12H” is located at address 0008 and the operand 12H at address 0009.
The memory location 000A has the opcode for the SJMP instruction and its target address is located in
location 000B. The reason the target address is FE is explained in the next chapter.

6.4 Executing a Program Byte by Byte


Assuming that the above program is burned into the ROM of an 8051 chip (or 8751, AT89C51, or DS5000),
the following is a step-by-step description of the action of the 8051 upon applying power to it.

1. When the 8051 is powered up, the PC (program counter) has 0000 and starts to fetch the first opcode
from location 0000 of the program ROM. In the case of the above program the first opcode is 7D,
which is the code for moving an operand to R5. Upon executing the opcode, the CPU fetches the value
25 and places it in R5. Now one instruction is finished. Then the program counter is incremented to
point to 0002 (PC = 0002), which contains opcode 7F, the opcode for the instruction “MOV R7,..”.
2. Upon executing the opcode 7F, the value 34H is moved into R7. Then the program counter is incre-
mented to 0004.
3. ROM location 0004 has the opcode for the instruction “MOV A, #0”. This instruction is executed
and now PC = 0006. Notice that all the above instructions are 2-byte instructions; that is, each one
takes two memory locations.
4. Now PC = 0006 points to the next instruction, which is “ADD A, R5”. This is a 1-byte instruction.
After the execution of this instruction, PC = 0007.

5. The location 0007 has the opcode 2F, which belongs to the instruction “ADD A,R7”. This also is a
1-byte instruction. Upon execution of this instruction, PC is incremented to 0008. This process goes
on until all the instructions are fetched and executed. The fact that the program counter points at the
next instruction to be executed explains why some microprocessors (notably the x86) call the program
counter the instruction pointer.

6.5 ROM Memory Map in the 8051 Family


As we saw in the last chapter, some family members have only 4K bytes of on-chip ROM (e.g., 8751,
AT89C51) and some, such as the AT89C52, have 8K bytes of ROM. Dallas Semiconductor’s DS5000-32 has
32K bytes of on-chip ROM. Dallas Semiconductor also has an 8051 with 64K bytes of on-chip ROM. The
point to remember is that no member of the 8051 family can access more than 64K bytes of opcode since the
program counter in the 8051 is a 16-bit register (0000 to FFFF address range). It must be noted that while
the first location of program ROM inside the 8051 has the address of 0000, the last location can be different
depending on the size of the ROM on the chip. Among the 8051 family members, the 8751 and AT89C51

21
have 4K bytes of on-chip ROM. This 4K bytes of ROM memory has memory addresses of 0000 to 0FFFH.
Therefore, the first location of on-chip ROM of this 8051 has an address of 0000 and the last location has
the address of 0FFFH.

Figure 7: 8051 On-Chip ROM Address Range

Review Questions
1. In the 8051, the program counter is bits wide.
2. True or false. Every member of the 8051 family, regardless of the maker, wakes up at memory 0000H
when it is powered up.
3. At what ROM location do we store the first opcode of an 8051 program?
4. The instruction “MOV A, #44H” is a -byte instruction.
5. What is the ROM address space for the 8052 chip?

7 8051 Data Types and Directives


In this section we look at some widely used data types and directives supported by the 8051 assembler.

7.1 8051 Data Type and Directives


The 8051 microcontroller has only one data type. It is 8 bits, and the size of each register is also 8 bits. It
is the job of the programmer to break down data larger than 8 bits (00 to FFH, or 0 to 255 in decimal) to
be processed by the CPU. For examples of how to process data larger than 8 bits, see Chapter 6. The data
types used by the 8051 can be positive or negative. A discussion of signed numbers is given in Chapter 6.

22
7.2 DB (Define Byte)
The DB directive is the most widely used data directive in the assembler. It is used to define the 8-bit
data. When DB is used to define data, the numbers can be in decimal, binary, hex, or ASCII formats. For
decimal, the “D” after the decimal number is optional, but using “B” (binary) and “H” (hexadecimal) for
the others is required. Regardless of which is used, the assembler will convert the numbers into hex. To
indicate ASCII, simply place the characters in quotation marks (“like this”). The assembler will assign the
ASCII code for the numbers or characters automatically. The DB directive is the only directive that can
be used to define ASCII strings larger than two characters; therefore, it should be used for all ASCII data
definitions. Following are some DB examples:

Listing 10: DB Directive Examples


ORG 500H
DATA1: DB 28 ;DECIMAL (1C i n hex )
DATA2: DB 00110101B ;BINARY (35 i n hex )
DATA3: DB 39H ;HEX

ORG 510H
DATA4: DB ” 2591 ” ; ASCII NUMBERS

ORG 518H
DATA6: DB ”My name i s Joe ” ; ASCII CHARACTERS
Either single or double quotes can be used around ASCII strings. This can be useful for strings, which
contain a single quote such as “O’Leary”. DB is also used to allocate memory in byte-sized chunks.

7.3 Assembler Directives


The following are some more widely used directives of the 8051.

7.3.1 ORG (Origin)


The ORG directive is used to indicate the beginning of the address. The number that comes after ORG
can be either in hex or in decimal. If the number is not followed by H, it is decimal and the assembler will
convert it to hex. Some assemblers use “.ORG” (notice the dot) instead of “ORG” for the origin directive.
Check your assembler.

7.3.2 EQU (Equate)


This is used to define a constant without occupying a memory location. The EQU directive does not set
aside storage for a data item but associates a constant value with a data label so that when the label appears
in the program, its constant value will be substituted for the label. The following uses EQU for the counter
constant and then the constant is used to load the R3 register.

Listing 11: EQU Directive Example


COUNT EQU 25
...
...
MOV R3 , #COUNT ; l o a d R3 w i t h 25 d e c i m a l
When executing the instruction “MOV R3, #COUNT”, the register R3 will be loaded with the value 25
(notice the # sign). What is the advantage of using EQU? Assume that there is a constant (a fixed value)
used in many different places in the program, and the programmer wants to change its value throughout.
By the use of EQU, the programmer can change it once and the assembler will change all of its occurrences,
rather than search the entire program trying to find every occurrence.

23
7.3.3 END Directive
Another important pseudocode is the END directive. This indicates to the assembler the end of the source
(asm) file. The END directive is the last line of an 8051 program, meaning that in the source code anything
after the END directive is ignored by the assembler. Some assemblers use “.END” (notice the dot) instead
of “END”.

7.4 Rules for Labels in Assembly Language


By choosing label names that are meaningful, a programmer can make a program much easier to read and
maintain. There are several rules that names must follow. First, each label name must be unique. The
names used for labels in Assembly language programming consist of alphabetic letters in both uppercase
and lowercase, the digits 0 through 9, and the special characters question mark (?), period (.), at (@),
underline ( ), and dollar sign ($). The first character of the label must be an alphabetic character. In other
words it cannot be a number. Every assembler has some reserved words that must not be used as labels
in the program. Foremost among the reserved words are the mnemonics for the instructions. For example,
“MOV” and “ADD” are reserved since they are instruction mnemonics. In addition to the mnemonics there
are some other reserved words. Check your assembler for the list of reserved words.

Review Questions
1. The directive is always used for ASCII strings.

2. How many bytes are used by the following? DATA 1: DB "AMERICA"


3. What is the advantage in using the EQU directive to define a constant value?
4. How many bytes are set aside by each of the following directives?

(a) ASC DATA: DB "1234" (b) MY DATA: DB "ABC1234"


5. State the contents of memory locations 200H–205H for the following: ORG 200H MYDATA: DB "ABC123"

8 8051 Flag Bits and the PSW Register


Like any other microprocessor, the 8051 has a flag register to indicate arithmetic conditions such as the
carry bit. The flag register in the 8051 is called the program status word (PSW) register. In this section we
discuss various bits of this register and provide some examples of how it is altered.

8.1 PSW (Program Status Word) Register


The program status word (PSW) register is an 8-bit register. It is also referred to as the flag register.
Although the PSW register is 8 bits wide, only 6 bits of it are used by the 8051. The two unused bits are
user-definable flags. Four of the flags are called conditional flags, meaning that they indicate some conditions
that result after an instruction is executed. These four are CY (carry), AC (auxiliary carry), P (parity), and
OV (overflow).
As seen from Figure 8, the bits PSW.3 and PSW.4 are designated as RS0 and RS1, respectively, and are
used to change the bank registers. They are explained in the next section. The PSW.5 and PSW.1 bits are
general-purpose status flag bits and can be used by the programmer for any purpose. In other words, they
are user definable. See Figure 8 for the bits of the PSW register.
The following is a brief explanation of four of the flag bits of the PSW register. The impact of instructions
on these registers is then discussed.

24
Figure 8: Bits of the PSW Register

Table 11: PSW Register Bit Descriptions

Bit Name Description


CY PSW.7 Carry flag
AC PSW.6 Auxiliary carry flag
F0 PSW.5 Available to the user for general purpose
RS1 PSW.4 Register Bank selector bit 1
RS0 PSW.3 Register Bank selector bit 0
OV PSW.2 Overflow flag
– PSW.1 User-definable bit
P PSW.0 Parity flag

Table 12: Register Bank Selection

RS1 RS0 Register Bank


0 0 Bank 0 (00H–07H)
0 1 Bank 1 (08H–0FH)
1 0 Bank 2 (10H–17H)
1 1 Bank 3 (18H–1FH)

25
8.1.1 CY, the Carry Flag
This flag is set whenever there is a carry out from the D7 bit. This flag bit is affected after an 8-bit addition
or subtraction. It can also be set to 1 or 0 directly by an instruction such as “SETB C” and “CLR C”
where “SETB C” stands for “set bit carry” and “CLR C” for “clear carry”. More about these and other
bit-addressable instructions will be given in Chapter 8.

8.1.2 AC, the Auxiliary Carry Flag


If there is a carry from D3 to D4 during an ADD or SUB operation, this bit is set; otherwise, it is cleared.
This flag is used by instructions that perform BCD (binary coded decimal) arithmetic. See Chapter 6 for
more information.

8.1.3 P, the Parity Flag


The parity flag reflects the number of 1s in the A (accumulator) register only. If the A register contains an
odd number of 1s, then P = 1. Therefore, P = 0 if A has an even number of 1s.

8.1.4 OV, the Overflow Flag


This flag is set whenever the result of a signed number operation is too large, causing the high-order bit to
overflow into the sign bit. In general, the carry flag is used to detect errors in unsigned arithmetic operations.
The overflow flag is only used to detect errors in signed arithmetic operations and is discussed in detail in
Chapter 6.

8.2 ADD Instruction and PSW


Next we examine the impact of the ADD instruction on the flag bits CY, AC, and P of the PSW register.
Some examples should clarify their status. Although the flag bits affected by the ADD instruction are CY
(carry flag), P (parity flag), AC (auxiliary carry flag), and OV (overflow flag) we will focus on flags CY, AC,
and P for now. A discussion of the overflow flag is given in Chapter 6, since it relates only to signed number
arithmetic. How the various flag bits are used in programming is discussed in future chapters in the context
of many applications.
See Examples 2-2 through 2-4 for the impact on selected flag bits as a result of the ADD instruction.

Table 13: Instructions That Affect Flag Bits

Instruction CY OV AC
ADD X X X
ADDC X X X
SUBB X X X
MUL 0 X
DIV 0 X
DA X
RRC X
RLC X
SETB C 1
CLR C 0
CPL C X
ANL C,bit X
ANL C,/bit X
ORL C,bit X
ORL C,/bit X
MOV C,bit X
CJNE X

Note: X can be 0 or 1.

26
Example 2-2
Show the status of the CY, AC, and P flags after the addition of 38H and 2FH in the following instructions.

Listing 12: Example 2-2


MOV A, #38H
ADD A, #2FH ; a f t e r t h e a d d i t i o n A=67H, CY=0
Solution:

38 00111000
+ 2F 00101111
-----
67 01100111

• CY = 0 since there is no carry beyond the D7 bit.

• AC = 1 since there is a carry from the D3 to the D4 bit.


• P = 1 since the accumulator has an odd number of 1s (it has five 1s).

Example 2-3
Show the status of the CY, AC, and P flags after the addition of 9CH and 64H in the following instructions.

Listing 13: Example 2-3


MOV A, #9CH
ADD A, #64H ; a f t e r a d d i t i o n A=00 and CY=1
Solution:

9C 10011100
+ 64 01100100
-----
100 00000000

• CY = 1 since there is a carry beyond the D7 bit.

• AC = 1 since there is a carry from the D3 to the D4 bit.


• P = 0 since the accumulator has an even number of 1s (it has zero 1s).

Example 2-4
Show the status of the CY, AC, and P flags after the addition of 88H and 93H in the following instructions.

Listing 14: Example 2-4


MOV A, #88H
ADD A, #93H ; a f t e r t h e a d d i t i o n A=1BH, CY=1
Solution:

88 10001000
+ 93 10010011
-----
11B 00011011

• CY = 1 since there is a carry beyond the D7 bit.


• AC = 0 since there is no carry from the D3 to the D4 bit.
• P = 0 since the accumulator has an even number of 1s (it has four 1s).

27
Review Questions
1. The flag register in the 8051 is called .
2. What is the size of the flag register in the 8051?

3. Which bits of the PSW register are user-definable?


4. Find the CY and AC flag bits for the following code.
MOV A, #0FFH
ADD A, #01

5. Find the CY and AC flag bits for the following code.


MOV A, #0C2H
ADD A, #3DH

9 8051 Register Banks and Stack


The 8051 microcontroller has a total of 128 bytes of RAM. In this section we discuss the allocation of these
128 bytes of RAM and examine their usage as registers and stack.

9.1 RAM Memory Space Allocation in the 8051


There are 128 bytes of RAM in the 8051 (some members, notably the 8052, have 256 bytes of RAM). The
128 bytes of RAM inside the 8051 are assigned addresses 00 to 7FH. As we will see in Chapter 5, they can
be accessed directly as memory locations. These 128 bytes are divided into three different groups as follows.

1. A total of 32 bytes from locations 00 to 1F hex are set aside for register banks and the stack.
2. A total of 16 bytes from locations 20H to 2FH are set aside for bit-addressable read/write memory. A
detailed discussion of bit-addressable memory and instructions is given in Chapter 8.
3. A total of 80 bytes from locations 30H to 7FH are used for read and write storage, or what is normally
called a scratch pad. These 80 locations of RAM are widely used for the purpose of storing data and
parameters by 8051 programmers. We will use them in future chapters to store data brought into the
CPU via I/O ports.

Figure 9: RAM Allocation in the 8051

28
9.2 Register Banks in the 8051
As mentioned earlier, a total of 32 bytes of RAM are set aside for the register banks and stack. These 32
bytes are divided into 4 banks of registers in which each bank has 8 registers, R0–R7. RAM locations from
0 to 7 are set aside for bank 0 of R0–R7 where R0 is RAM location 0, R1 is RAM location 1, R2 is location
2, and so on, until memory location 7, which belongs to R7 of bank 0. The second bank of registers R0–R7
starts at RAM location 08 and goes to location 0FH. The third bank of R0–R7 starts at memory location
10H and goes to location 17H. Finally, RAM locations 18H to 1FH are set aside for the fourth bank of
R0–R7. The following shows how the 32 bytes are allocated into 4 banks:

Figure 10: 8051 Register Banks and their RAM Addresses

As we can see from Figure 9, bank 1 uses the same RAM space as the stack. This is a major problem
in programming the 8051. We must either not use register bank 1, or allocate another area of RAM for the
stack. This will be discussed below.
Example 2-5
State the contents of RAM locations after the following program:

Listing 15: Example 2-5


MOV R0,#99H ; load R0 with value 99H
MOV R1,#85H ; load R1 with value 85H
MOV R2,#3FH ; load R2 with value 3FH
MOV R7,#63H ; load R7 with value 63H
MOV R5,#12H ; load R5 with value 12H
Solution:
After the execution of the above program we have the following:

• RAM location 0 has value 99H RAM location 1 has value 85H
• RAM location 2 has value 3FH RAM location 7 has value 63H

• RAM location 5 has value 12H

9.3 Default Register Bank


If RAM locations 00–1F are set aside for the four register banks, which register bank of R0–R7 do we have
access to when the 8051 is powered up? The answer is register bank 0; that is, RAM locations 0,1,2,3,4,5,6,
and 7 are accessed with the names R0, R1, R2, R3, R4, R5, R6, and R7 when programming the 8051. It is
much easier to refer to these RAM locations with names such as R0, R1, and so on, than by their memory
locations. Example 2-6 clarifies this concept.

29
Example 2-6
Repeat Example 2-5 using RAM addresses instead of register names.
Solution:
This is called direct addressing mode and uses the RAM address location for the destination address.
See Chapter 5 for a more detailed discussion of addressing modes.

Listing 16: Example 2-6: Direct Addressing Mode


MOV 00 ,#99H ; load R0 with value 99H
MOV 01 ,#85H ; load R1 with value 85H
MOV 02 ,#3FH ; load R2 with value 3FH
MOV 07 ,#63H ; load R7 with value 63H
MOV 05 ,#12H ; load R5 with value 12H

9.4 How to Switch Register Banks


As stated above, register bank 0 is the default when the 8051 is powered up. We can switch to other banks
by use of the PSW (program status word) register. Bits D4 and D3 of the PSW are used to select the desired
register bank as shown in Table 12.
The D3 and D4 bits of register PSW are often referred to as PSW.4 and PSW.3 since they can be accessed
by the bit-addressable instructions SETB and CLR. For example, “SETB PSW.3” will make PSW.3 = 1
and select bank register 1. See Example 2-7.
Example 2-7
State the contents of the RAM locations after the following program:

Listing 17: Example 2-7: Switching Register Banks


SETB PSW.4 ; s e l e c t bank 2
MOV R0,#99H ; l o a d R0 w i t h value 99H
MOV R1,#85H ; l o a d R1 w i t h value 85H
MOV R2,#3FH ; l o a d R2 w i t h value 3FH
MOV R7,#63H ; l o a d R7 w i t h value 63H
MOV R5,#12H ; l o a d R5 w i t h value 12H
Solution:
By default, PSW.3=0 and PSW.4=0; therefore, the instruction “SETB PSW.4” sets RS1=1 and RS0=0,
thereby selecting register bank 2. Register bank 2 uses RAM locations 10H–17H. After the execution of the
above program we have the following:

• RAM location 10H has value 99H RAM location 11H has value 85H
• RAM location 12H has value 3FH RAM location 17H has value 63H
• RAM location 15H has value 12H

9.5 Stack in the 8051


The stack is a section of RAM used by the CPU to store information temporarily. This information could
be data or an address. The CPU needs this storage area since there are only a limited number of registers.

9.5.1 How Stacks Are Accessed in the 8051


If the stack is a section of RAM, there must be registers inside the CPU to point to it. The register used to
access the stack is called the SP (stack pointer) register. The stack pointer in the 8051 is only 8 bits wide,
which means that it can take values of 00 to FFH. When the 8051 is powered up, the SP register contains
value 07. This means that RAM location 08 is the first location used for the stack by the 8051. The storing
of a CPU register in the stack is called a PUSH, and pulling the contents off the stack back into a CPU
register is called a POP. In other words, a register is pushed onto the stack to save it and popped off the

30
stack to retrieve it. The job of the SP is very critical when push and pop actions are performed. To see how
the stack works, let’s look at the PUSH and POP instructions.

9.5.2 Pushing onto the Stack


In the 8051 the stack pointer (SP) points to the last used location of the stack. As we push data onto the
stack, the stack pointer (SP) is incremented by one. Notice that this is different from many microprocessors,
notably x86 processors in which the SP is decremented when data is pushed onto the stack. Examining
Example 2-8, we see that as each PUSH is executed, the contents of the register are saved on the stack and
SP is incremented by 1. Notice that for every byte of data saved on the stack, SP is incremented only once.
Notice also that to push the registers onto the stack we must use their RAM addresses. For example, the
instruction “PUSH 1” pushes register R1 onto the stack.

Figure 11: Stack Action in the 8051

9.5.3 Popping from the Stack


Popping the contents of the stack back into a given register is the opposite process of pushing. With every
pop, the top byte of the stack is copied to the register specified by the instruction and the stack pointer is
decremented once. Example 2-9 demonstrates the POP instruction.
Example 2-9
Examining the stack, show the contents of the registers and SP after execution of the following instruc-
tions. All values are in hex.

Listing 18: Example 2-9: POP Instruction


POP 3 ;POP s t a c k i n t o R3
POP 5 ;POP s t a c k i n t o R5
POP 2 ;POP s t a c k i n t o R2
Solution:
After POP 3: R3 = F9, SP = 0A
After POP 5: R5 = 12, SP = 09
After POP 2: R2 = 25, SP = 08

31
9.5.4 The Upper Limit of the Stack
As mentioned earlier, locations 08 to 1F in the 8051 RAM can be used for the stack. This is because locations
20–2FH of RAM are reserved for bit-addressable memory and must not be used by the stack. If in a given
program we need more than 24 bytes (08 to 1FH = 24 bytes) of stack, we can change the SP to point to
RAM locations 30–7FH. This is done with the instruction “MOV SP,#xx”.

9.6 CALL Instruction and the Stack


In addition to using the stack to save registers, the CPU also uses the stack to save the address of the
instruction just below the CALL instruction. This is how the CPU knows where to resume when it returns
from the called subroutine. More information on this will be given in Chapter 3 when we discuss the CALL
instruction.

9.7 Stack and Bank 1 Conflict


Recall from our earlier discussion that the stack pointer register points to the current RAM location available
for the stack. As data is pushed onto the stack, SP is incremented. Conversely, it is decremented as data
is popped off the stack into the registers. The reason that the SP is incremented after the push is to make
sure that the stack is growing toward RAM location 7FH, from lower addresses to upper addresses. If the
stack pointer were decremented after push instructions, we would be using RAM locations 7, 6, 5, etc., which
belong to R7 to R0 of bank 0, the default register bank. This incrementing of the stack pointer for push
instructions also ensures that the stack will not reach location 0 at the bottom of RAM, and consequently
run out of space for the stack. However, there is a problem with the default setting of the stack. Since SP
= 07 when the 8051 is powered up, the first location of the stack is RAM location 08, which also belongs
to register R0 of register bank 1. In other words, register bank 1 and the stack are using the same memory
space. If in a given program we need to use register banks 1 and 2, we can reallocate another section of
RAM to the stack. For example, we can allocate RAM locations 60H and higher to the stack as shown in
Example 2-10.

9.8 Viewing Registers and Memory with a Simulator


Many assemblers and C compilers come with a simulator. Simulators allow us to view the contents of
registers and memory after executing each instruction (single-stepping). We strongly recommend that you
use a simulator to single-step some of the programs in this chapter and future chapters. Single-stepping a
program with a simulator gives us a deeper understanding of microcontroller architecture, in addition to the
fact that we can use it to find errors in our programs.

Review Questions
1. What is the size of the SP register?
2. With each PUSH instruction, the stack pointer register, SP, is (incremented, decre-
mented) by 1.
3. With each POP instruction, the SP is (incremented, decremented) by 1.
4. On power-up, the 8051 uses RAM location as the first location of the stack.
5. On power-up, the 8051 uses bank for registers R0–R7.
6. On power-up, the 8051 uses RAM locations to for registers R0–R7 (register bank 0).
7. Which register bank is used if we alter RS0 and RS1 of the PSW by the following two instructions?
SETB PSW.3
SETB PSW.4

8. In Question 7, what RAM locations are used for register R0–R7?

32
Summary
This chapter began with an exploration of the major registers of the 8051, including A, B, R0, R1, R2, R3,
R4, R5, R6, R7, DPTR, and PC. The use of these registers was demonstrated in the context of programming
examples. The process of creating an Assembly language program was described from writing the source
file, to assembling it, linking, and executing the program. The PC (program counter) register always points
to the next instruction to be executed. The way the 8051 uses program ROM space was explored because
8051 Assembly language programmers must be aware of where programs are placed in ROM, and how much
memory is available.
An Assembly language program is composed of a series of statements that are either instructions or
pseudo-instructions, also called directives. Instructions are translated by the assembler into machine code.
Pseudo-instructions are not translated into machine code: They direct the assembler in how to translate
instructions into machine code. Some pseudo-instructions, called data directives, are used to define data.
Data is allocated in byte-size increments. The data can be in binary, hex, decimal, or ASCII formats.
Flags are useful to programmers since they indicate certain conditions, such as carry or overflow, that
result from execution of instructions. The stack is used to store data temporarily during execution of a pro-
gram. The stack resides in the RAM space of the 8051, which was diagrammed and explained. Manipulation
of the stack via POP and PUSH instructions was also explored.

Problems
Section 2.1: Inside the 8051
1. Most registers in the 8051 are bits wide.
2. Registers R0–R7 are all bits wide.
3. Registers ACC and B are bits wide.
4. Name a 16-bit register in the 8051.

5. To load R4 with the value 65H, the pound sign is (necessary, optional) in the instruction
“MOV R4, #65H”.
6. What is the result of the following code and where is it kept?
MOV A,#15H
MOV R2,#13H
ADD A, R2

7. Which of the following is (are) illegal?


(a) MOV R3, #500 (b) MOV R1, #50 (c) MOV R7, #00
(d) MOV A, #255H (e) MOV A, #50H (f) MOV A, #F5H
(g) MOV R9, #50H
8. Which of the following is (are) illegal?
(a) ADD R3, #50H (b) ADD A, #50H (c) ADD R7,R4
(d) ADD A, #255H (e) ADD A,R5 (f) ADD A,#F5H
(g) ADD R3,A
9. What is the result of the following code and where is it kept?
MOV R4,#25H
MOV A,#1FH
ADD A, R4

33
10. What is the result of the following code and where is it kept?
MOV A,#15
MOV R5,#15
ADD A, R5

Section 2.2: Introduction to 8051 Assembly Programming and Section 2.3: Assembling and
Running an 8051 Program
11. Assembly language is a (low, high)-level language while C is a (low, high)-level language.
12. Of C and Assembly language, which is more efficient in terms of code generation (i.e., the amount of
ROM space it uses)?
13. Which program produces the “obj” file?

14. True or false. The source file has the extension “src” or “asm”.
15. Which file provides the listing of error messages?
16. True or false. The source code file can be a non-ASCII file.

17. True or false. Every source file must have ORG and END directives.
18. Do the ORG and END directives produce opcodes?
19. Why are the ORG and END directives also called pseudocode?
20. True or false. The ORG and END directives appear in the “.lst” file.

21. Every 8051 family member wakes up at address when it is powered up.
22. A programmer puts the first opcode at address 100H. What happens when the microcontroller is
powered up?
23. Find the number of bytes each of the following instructions takes.

(a) MOV A, #55H (b) MOV R3, #3 (c) INC R2


(d) ADD A, #0 (e) MOV A, R1 (f) MOV R3,A
(g) ADD A, R2
24. Pick up a program listing of your choice, and show the ROM memory addresses and their contents.

25. Find the address of the last location of on-chip ROM for each of the following.
(a) DS5000-16 (b) DS5000-8 (c) DS5000-32
(d) AT89C52 (e) 8751 (f) AT89C51
(g) DS5000-64

26. Show the lowest and highest values (in hex) that the 8051 program counter can take.
27. A given 8051 has 7FFFH as the address of its last location of on-chip ROM. What is the size of on-chip
ROM for this 8051?
28. Repeat Question 27 for 3FFH.

34
Section 2.5: 8051 Data Types and Directives
29. Compile and state the contents of each ROM location for the following data.
ORG 200H
MYDAT 1: DB ” Earth ”
MYDAT 2: DB ”987−65”
MYDAT 3: DB ”GABEH 98 ”

30. Compile and state the contents of each ROM location for the following data.
ORG 340H
DAT 1 : DB 2 2 , 5 6H, 1 0 0 1 1 0 0 1B, 3 2 , 0 F6H, 1 1 1 1 1 0 1 1B

Section 2.6: 8051 Flag Bits and the PSW Register


31. The PSW is a(n) -bit register.
32. Which bits of PSW are used for the CY and AC flag bits, respectively?
33. Which bits of PSW are used for the OV and P flag bits, respectively?
34. In the ADD instruction, when is CY raised?
35. In the ADD instruction, when is AC raised?
36. What is the value of the CY flag after the following code?
CLR C ;CY = 0
CPL C ; complement c a r r y

37. Find the CY flag value after each of the following codes.

(a) MOV A, #54H


ADD A, #0C4H

MOV A, #00
ADD A, #0FFH

(b)
(c) MOV A, #250
ADD A, #05

38. Write a simple program in which the value 55H is added 5 times.
39. Which bits of the PSW are responsible for selection of the register banks?
40. On power-up, what is the location of the first stack?
41. In the 8051, which register bank conflicts with the stack?
42. In the 8051, what is the size of the stack pointer (SP) register?
43. On power-up, which of the register banks is used?
44. Give the address locations of RAM assigned to various banks.
45. Assuming the use of bank 0, find at what RAM location each of the following lines stored the data.
(a) MOV R4, #32H (b) MOV R0, #12H
(c) MOV R7, #3FH (d) MOV R5, #55H
46. Repeat Problem 45 for bank 2.
47. After power-up, show how to select bank 2 with a single instruction.

35
Answers to Review Questions
Section 2.1: Inside the 8051
1. MOV A,#34H
MOV B,#3FH
ADD A,B ;A = A + B = 34H + 3FH = 73H
2. MOV A,#16H
ADD A,#0CDH
MOV R2,A ;result is in A, then moved to R2

3. False. Values can be moved directly into R0–R7.


4. FFH is the largest value. The decimal equivalent is 255.
5. 8

Section 2.2: Introduction to 8051 Assembly Programming


6. Pseudo-instructions (also called directives) give directions to the assembler.

7. Instructions are translated by the assembler into machine code, whereas directives are not.
8. False. Assembly language is a low-level language.
9. (a), (b), and (d) produce opcodes.

10. Assembler directives.


11. True.
12. (c) ORG 2000H is an assembler directive.

Section 2.3: Assembling and Running an 8051 Program


13. True.

14. True.
15. (a) [Link]
16. (b), (d) — the assembler produces the obj and lst files.
17. (d) [Link]

Section 2.4: The Program Counter and ROM Space in the 8051
18. 16
19. True.
20. 0000H

21. 2 (two-byte)
22. 0000H–1FFFH (8K bytes of ROM)

36
Section 2.5: 8051 Data Types and Directives
23. DB
24. 7 bytes (one for each character)

25. It allows the programmer to change the value once and the assembler will change all of its occurrences.
26. (a) 4 bytes (b) 7 bytes
27. 200H = 41H (‘A’), 201H = 42H (‘B’), 202H = 43H (‘C’), 203H = 31H (‘1’), 204H = 32H (‘2’), 205H
= 33H (‘3’)

Section 2.6: 8051 Flag Bits and the PSW Register


28. PSW (program status word)
29. 8-bit
30. PSW.1 and PSW.5 (bits D1 and D5)
31. CY = 1 (FFH + 01 = 00 with carry out), AC = 1 (carry from D3 to D4)

32. CY = 0, AC = 0 (C2H + 3DH = FFH, no carry from D7 or from D3 to D4)

Section 2.7: 8051 Register Banks and Stack


33. 8-bit
34. incremented
35. decremented

36. 08
37. 0
38. 00 to 07

39. Bank 3
40. 18H to 1FH

Jump, Loop, and Call Instructions

Objectives
Upon completion of this chapter, you will be able to:
• Code 8051 Assembly language instructions using loops
• Code 8051 Assembly language conditional jump instructions
• Explain conditions that determine each conditional jump instruction

• Code long jump instructions for unconditional jumps


• Code short jump instructions for unconditional short jumps
• Calculate target addresses for jump instructions
• Code 8051 subroutines

37
• Describe precautions in using the stack in subroutines
• Discuss crystal frequency versus machine cycle
• Code 8051 programs to generate a time delay
In the sequence of instructions to be executed, it is often necessary to transfer program control to a
different location. There are many instructions in the 8051 to achieve this. This chapter covers the control
transfer instructions available in 8051 Assembly language. In the first section we discuss instructions used for
looping, as well as instructions for conditional and unconditional jumps. In the second section we examine
CALL instructions and their uses. In the third section, time delay subroutines are described for both the
traditional 8051 and its newer generation.

10 Loop and Jump Instructions


In this section we first discuss how to perform a looping action in the 8051 and then talk about jump
instructions, both conditional and unconditional.

10.1 Looping in the 8051


Repeating a sequence of instructions a certain number of times is called a loop. The loop is one of most
widely used actions that any microprocessor performs. In the 8051, the loop action is performed by the
instruction “DJNZ reg, label”. In this instruction, the register is decremented; if it is not zero, it jumps
to the target address referred to by the label. Prior to the start of the loop the register is loaded with the
counter for the number of repetitions. Notice that in this instruction both the register decrement and the
decision to jump are combined into a single instruction.
Example 3-1
Write a program to (a) clear ACC, then (b) add 3 to the accumulator ten times.
Solution:

Listing 19: Adding Value 3 to Accumulator Ten Times


; This program adds v a l u e 3 t o t h e ACC t e n t i m e s
MOV A,#0 ;A=0, c l e a r ACC
MOV R2,#10 ; l o a d c o u n t e r R2=10
AGAIN:
ADD A,#03 ; add 03 t o ACC
DJNZ R2 ,AGAIN ; r e p e a t u n t i l R2=0 (10 t i m e s )
MOV R5 ,A ; s a v e A i n R5
In the program in Example 3-1, the R2 register is used as a counter. The counter is first set to 10. In
each iteration the instruction DJNZ decrements R2 and checks its value. If R2 is not zero, it jumps to the
target address associated with the label “AGAIN”. This looping action continues until R2 becomes zero.
After R2 becomes zero, it falls through the loop and executes the instruction immediately below it, in this
case the “MOV R5, A” instruction.
Notice in the DJNZ instruction that the registers can be any of R0–R7. The counter can also be a RAM
location as we will see in Chapter 5.
Example 3-2
What is the maximum number of times that the loop in Example 3-1 can be repeated?
Solution:
Since R2 holds the count and R2 is an 8-bit register, it can hold a maximum of FFH (255 decimal);
therefore, the loop can be repeated a maximum of 256 times.

38
10.2 Loop Inside a Loop
As shown in Example 3-2, the maximum count is 256. What happens if we want to repeat an action more
times than 256? To do that, we use a loop inside a loop, which is called a nested loop. In a nested loop, we
use two registers to hold the count. See Example 3-3.
Example 3-3
Write a program to (a) load the accumulator with the value 55H, and (b) complement the ACC 700
times.
Solution:
Since 700 is larger than 255 (the maximum capacity of any register), we use two registers to hold the
count. The following code shows how to use R2 and R3 for the count.

Listing 20: Nested Loop to Complement ACC 700 Times


MOV A,#55H ;A=55H
MOV R3,#10 ; R3=10 , t h e o u t e r l o o p c o un t
NEXT:
MOV R2,#70 ; R2=70 , t h e i n n e r l o o p c ou n t
AGAIN:
CPL A ; complement A r e g i s t e r
DJNZ R2 ,AGAIN ; r e p e a t i t 70 t i m e s ( i n n e r l o o p )
DJNZ R3 ,NEXT
In this program, R2 is used to keep the inner loop count. In the instruction “DJNZ R2,AGAIN”, whenever
R2 becomes 0 it falls through and “DJNZ R3,NEXT” is executed. This instruction forces the CPU to load
R2 with the count 70 and the inner loop starts again. This process will continue until R3 becomes zero and
the outer loop is finished.

10.3 Other Conditional Jumps


Conditional jumps for the 8051 are summarized in Table 14. More details of each instruction are provided in
Appendix A. In Table 14, notice that some of the instructions, such as JZ (jump if A = zero) and JC (jump
if carry), jump only if a certain condition is met. Next we examine some conditional jump instructions with
examples.

Table 14: 8051 Conditional Jump Instructions

Instruction Action
JZ Jump if A=0
JNZ Jump if A̸=0
DJNZ Decrement and jump if register̸=0
CJNE A,#data Jump if A̸=data
CJNE reg,#data Jump if byte̸=#data
JC Jump if CY=1
JNC Jump if CY=0
JB Jump if bit=1
JNB Jump if bit=0
JBC Jump if bit=1 and clear bit

10.4 JZ (Jump if A = 0)
In this instruction the content of register A is checked. If it is zero, it jumps to the target address. For
example, look at the following code.

Listing 21: JZ Instruction Example


MOV A, R0 ;A=R0

39
JZ OVER ; jump i f A=0
MOV A, R1 ;A=R1
JZ OVER ; jump i f A=0
OVER:
In this program, if either R0 or R1 is zero, it jumps to the label OVER. Notice that the JZ instruction
can be used only for register A. It can only check to see whether the accumulator is zero, and it does not
apply to any other register. More importantly, you don’t have to perform an arithmetic instruction such as
decrement to use the JNZ instruction. See Example 3-4.
Example 3-4
Write a program to determine if R5 contains the value 0. If so, put 55H in it.
Solution:

Listing 22: Checking if R5 Is Zero


MOV A, R5 ; copy R5 t o A
JNZ NEXT ; jump i f A i s not z e r o
MOV R5,#55H
NEXT:
...

10.5 JNC (Jump if No Carry, Jumps if CY = 0)


In this instruction, the carry flag bit in the flag (PSW) register is used to make the decision whether to
jump. In executing “JNC label”, the processor looks at the carry flag to see if it is raised (CY=1). If it is
not, the CPU starts to fetch and execute instructions from the address of the label. If CY=1, it will not
jump but will execute the next instruction below JNC.
Note that there is also a “JC label” instruction. In the JC instruction, if CY = 1 it jumps to the target
address. We will give more examples of these instructions in the context of applications in future chapters.
There are also JB (jump if bit is high) and JNB (jump if bit is low) instructions. These are discussed in
Chapters 4 and 8 when bit manipulation instructions are discussed.
Example 3-5
Find the sum of the values 79H, F5H, and E2H. Put the sum in registers R0 (low byte) and R5 (high
byte).
Solution:

Listing 23: Adding Multi-Byte Values with Carry Check


MOV A,#0 ; c l e a r A (A=0)
MOV R5 ,A ; c l e a r R5
ADD A,#79H ;A=0+79H=79H
JNC N 1 ; i f no c a r r y , add n e x t number
INC R5 ; i f CY=1, i n c r e m e n t R5
N 1:
ADD A,#0F5H ;A=79+F5=6E and CY=1
JNC N 2 ; jump i f CY=0
INC R5 ; I f CY=1 t h e n i n c r e m e n t R5 (R5=1)
N 2:
ADD A,#0E2H ;A=6E+E2=50 and CY=1
JNC OVER ; jump i f CY=0
INC R5 ; i f CY=1, i n c r e m e n t R5
OVER:
MOV R0 ,A ; Now R0=50H, and R5=02

40
10.6 All Conditional Jumps Are Short Jumps
It must be noted that all conditional jumps are short jumps, meaning that the address of the target must
be within −128 to +127 bytes of the contents of the program counter (PC). This very important concept is
discussed at the end of this section.

10.7 Unconditional Jump Instructions


The unconditional jump is a jump in which control is transferred unconditionally to the target location. In
the 8051 there are two unconditional jumps: LJMP (long jump) and SJMP (short jump). Each is discussed
below.

10.7.1 LJMP (Long Jump)


LJMP is an unconditional long jump. It is a 3-byte instruction in which the first byte is the opcode, and the
second and third bytes represent the 16-bit address of the target location. The 2-byte target address allows
a jump to any memory location from 0000 to FFFFH.
Remember that although the program counter in the 8051 is 16-bit, thereby giving a ROM address space
of 64K bytes, not all 8051 family members have that much on-chip program ROM. The original 8051 had
only 4K bytes of on-chip ROM for program space; consequently, every byte was precious. For this reason
there is also an SJMP (short jump) instruction, which is a 2-byte instruction as opposed to the 3-byte LJMP
instruction. This can save some bytes of memory in many applications where memory space is in short
supply. SJMP is discussed next.

10.7.2 SJMP (Short Jump)


In this 2-byte instruction, the first byte is the opcode and the second byte is the relative address of the
target location. The relative address range of 00–FFH is divided into forward and backward jumps; that is,
within −128 to +127 bytes of memory relative to the address of the current PC (program counter). If the
jump is forward, the target address can be within a space of 127 bytes from the current PC. If the target
address is backward, the target address can be within −128 bytes from the current PC. This is explained in
detail next.

10.8 Calculating the Short Jump Address


In addition to the SJMP instruction, all conditional jumps such as JNC, JZ, and DJNZ are also short jumps
due to the fact that they are all two-byte instructions. In these instructions the first byte is the opcode and
the second byte is the relative address. The target address is relative to the value of the program counter.
To calculate the target address, the second byte is added to the PC of the instruction immediately below
the jump. To understand this, look at Example 3-6.
Example 3-6
For the following program, state the target address for the jump instructions. Verify the calculation of
forward jumps.
Solution:
First notice that the JZ and JNC instructions both jump forward. The target address for a forward jump
is calculated by adding the PC of the following instruction to the second byte of the short jump instruction,
which is called the relative address. In line 4 the instruction “JZ NEXT” has opcode of 60 and operand
of 03 at the addresses of 0004 and 0005. The 03 is the relative address, relative to the address of the next
instruction INC R0, which is 0006. By adding 0006 to 3, the target address of the label NEXT, which is
0009, is generated. In the same way for line 9, the “JNC OVER” instruction has opcode and operand of 50
and 05 where 50 is the opcode and 05 the relative address. Therefore, 05 is added to 000D, the address of
instruction “CLR A”, giving 12H, the address of label OVER.
Example 3-7
Verify the calculation of backward jumps in Example 3-6.
Solution:

41
Figure 12: Target Address Calculation for Short Jump Instructions

Table 15: Program Listing for Target Address Calculation

Line PC Opcode Label Mnemonic Operand


01 0000 ORG 0000
02 0000 7800 MOV R0,#0
03 0002 7455 MOV A,#55H
04 0004 6003 JZ NEXT
05 0006 08 INC R0
06 0007 04 AGAIN: INC A
07 0008 04 INC A
08 0009 2477 NEXT: ADD A,#77h
09 000B 5005 JNC OVER
10 000D E4 CLR A
11 000E F8 MOV R0,A
12 000F F9 MOV R1,A
13 0010 FA MOV R2,A
14 0011 FB MOV R3,A
15 0012 2B OVER: ADD A,R3
16 0013 50F2 JNC AGAIN
17 0015 80FE HERE: SJMP HERE
18 0017 END

42
In that program list, “JNC AGAIN” has opcode 50 and relative address F2H. When the relative address
of F2H is added to 15H, the address of the instruction below the jump, we have 15H + F2H = 07 (the carry
is dropped). Notice that 07 is the address of label AGAIN. Look also at “SJMP HERE”, which has 80 and
FE for the opcode and relative address, respectively. The PC of the following instruction, 0017H, is added
to FEH, the relative address, to get 0015H, address of the HERE label (17H + FEH = 15H). Notice that
FEH is −2 and 17H + (−2) = 15H. For further discussion of the addition of negative numbers, see Chapter
6.

10.9 Jump Backward Target Address Calculation


While in the case of a forward jump, the displacement value is a positive number between 0 to 127 (00 to 7F
in hex), for the backward jump the displacement is a negative value of 0 to −128 as explained in Example
3-7.
It must be emphasized that regardless of whether the SJMP is a forward or backward jump, for any
short jump the address of the target address can never be more than −128 to +127 bytes from the address
associated with the instruction below the SJMP. If any attempt is made to violate this rule, the assembler
will generate an error stating the jump is out of range.

Review Questions
1. The mnemonic DJNZ stands for .
2. True or false. “DJNZ R5, BACK” combines a decrement and a jump in a single instruction.

3. “JNC HERE” is a -byte instruction.


4. In “JZ NEXT”, which register’s content is checked to see if it is zero?
5. LJMP is a -byte instruction.

11 Call Instructions
Another control transfer instruction is the CALL instruction, which is used to call a subroutine. Subroutines
are often used to perform tasks that need to be performed frequently. This makes a program more structured
in addition to saving memory space. In the 8051 there are two instructions for call: LCALL (long call) and
ACALL (absolute call). Deciding which one to use depends on the target address. Each instruction is
explained next.

11.1 LCALL (Long Call)


In this 3-byte instruction, the first byte is the opcode and the second and third bytes are used for the address
of the target subroutine. Therefore, LCALL can be used to call subroutines located anywhere within the
64K-byte address space of the 8051. To make sure that after execution of the called subroutine the 8051
knows where to come back to, the processor automatically saves on the stack the address of the instruction
immediately below the LCALL. When a subroutine is called, control is transferred to that subroutine, and
the processor saves the PC (program counter) on the stack and begins to fetch instructions from the new
location. After finishing execution of the subroutine, the instruction RET (return) transfers control back to
the caller. Every subroutine needs RET as the last instruction. See Example 3-8.

Listing 24: Calling a Delay Subroutine Using LCALL (Example 3-8)


ORG 0
BACK:
MOV A,#55H ; l o a d A w i t h 55H
MOV P1 ,A ; send 55H t o p o r t 1
LCALL DELAY ; time d e l a y

43
Figure 13: 8051 Assembly Main Program That Calls Subroutines

MOV A,#0AAH ; l o a d A w i t h AA ( i n hex )


MOV P1 ,A ; send AAH t o p o r t 1
LCALL DELAY
SJMP BACK ; keep doing t h i s i n d e f i n i t e l y
;−−−t h i s i s t h e d e l a y s u b r o u t i n e
ORG 300H ; p u t time d e l a y a t a d d r e s s 300H
DELAY:
MOV R5,#0FFH ; R5=255 (FF i n hex ) , t h e c o u n t e r
AGAIN:
DJNZ R5 ,AGAIN ; s t a y h e r e u n t i l R5 becomes 0
RET ; r e t u r n t o c a l l e r ( when R5=0)
END ; end o f asm f i l e
The following points should be noted for the program in Example 3-8.

1. Notice the DELAY subroutine. Upon executing the first “LCALL DELAY”, the address of the in-
struction right below it, “MOV A, #0AAH”, is pushed onto the stack, and the 8051 starts to execute
instructions at address 300H.
2. In the DELAY subroutine, first the counter R5 is set to 255 (R5 = FFH); therefore, the loop is repeated
256 times. When R5 becomes 0, control falls to the RET instruction, which pops the address from the
stack into the program counter and resumes executing the instructions after the CALL.

The amount of time delay in Example 3-8 depends on the frequency of the 8051. How to calculate the
exact time will be explained in detail in Section 12. However you can increase the time delay by using a
nested loop as shown below.

Listing 25: Nested Loop Delay Subroutine


DELAY: ; nested loop delay

44
MOV R4,#255 ; R4 = 255 (FF i n hex )
NEXT:
MOV R5,#255 ; R5 = 255 (FF i n hex )
AGAIN:
DJNZ R5 ,AGAIN ; s t a y h e r e u n t i l R5 becomes 0
DJNZ R4 ,NEXT ; decrement R4
; k e e p l o a d i n g R5 u n t i l R4 = 0
RET ; r e t u r n ( when R4 = 0)

11.2 CALL Instruction and the Role of the Stack


The stack and stack pointer were covered in the last chapter. To understand the importance of the stack
in microcontrollers, we now examine the contents of the stack and stack pointer for Example 3-8. This is
shown in Example 3-9.

Table 16: Stack Analysis for LCALL Instruction (Example 3-9)

Line PC Opcode Label Mnemonic Operand


001 0000 ORG 0
002 0000 7455 BACK: MOV A,#55H ;load A with 55H
003 0002 F590 MOV P1,A ;send 55H to port 1
004 0004 120300 LCALL DELAY ;time delay
005 0007 74AA MOV A,#0AAH ;load A with AAH
006 0009 F590 MOV P1,A ;send AAH to port 1
007 000B 120300 LCALL DELAY
008 000E 80F0 SJMP BACK ;keep doing this
009 0010
010 0010 ;—this is the delay subroutine
011 0300 ORG 300H
012 0300 DELAY:
013 0300 7DFF MOV R5,#0FFH ;R5=255
014 0302 DDFE AGAIN: DJNZ R5,AGAIN ;stay here
015 0304 22 RET ;return to caller
016 0305 END ;end of asm file

When the first LCALL is executed, the address of the instruction “MOV A,#0AAH” is saved on the
stack. Notice that the low byte goes first and the high byte is last. The last instruction of the called
subroutine must be a RET instruction, which directs the CPU to POP the top bytes of the stack into the
PC and resume executing at address 07. After the first LCALL, SP=09.

11.3 Use of PUSH and POP Instructions in Subroutines


Upon calling a subroutine, the stack keeps track of where the CPU should return after completing the
subroutine. For this reason, we must be very careful in any manipulation of stack contents. The rule is that
the number of PUSH and POP instructions must always match in any called subroutine. In other words,
for every PUSH there must be a POP. See Example 3-10.
Example 3-10
Analyze the stack for the first LCALL instruction in the following program.

Listing 26: Subroutine with PUSH and POP (Example 3-10)


ORG 0
BACK:
MOV A,#55H ; l o a d A w i t h 55H
MOV P1 ,A ; send 55H t o p o r t 1
MOV R4,#99H

45
MOV R5,#67H
LCALL DELAY ; time d e l a y
MOV A,#0AAH ; l o a d A w i t h AA
MOV P1 ,A ; send AAH t o p o r t 1
LCALL DELAY
SJMP BACK ; keep doing t h i s
;−−−t h i s i s t h e d e l a y s u b r o u t i n e
ORG 300H
DELAY:
PUSH 04 ;PUSH R4
PUSH 05 ;PUSH R5
MOV R4,#0FFH ; R4=FFH
NEXT:
MOV R5,#0FFH ; R5=255
AGAIN:
DJNZ R5 ,AGAIN
DJNZ R4 ,NEXT
POP 05 ;POP i n t o R5
POP 04 ;POP i n t o R4
RET ; return to c a l l e r
END ; end o f asm f i l e
Solution:
First notice that for the PUSH and POP instructions we must specify the direct address of the register
being pushed or popped. Here is the stack frame.

Table 17: Stack Frame for Example 3-10

After first LCALL After PUSH 4 After PUSH 5


0B 0B 0B 67 R5
0A 0A 99 R4 0A 99 R4
09 00 PCH 09 00 PCH 09 00 PCH
08 0B PCL 08 0B PCL 08 0B PCL

It needs to be emphasized that in using LCALL, the target address of the subroutine can be anywhere
within the 64K-byte memory space of the 8051. This is not the case for the other call instruction, ACALL,
which is explained next.

11.4 Calling Subroutines


In Assembly language programming it is common to have one main program and many subroutines that
are called from the main program. This allows you to make each subroutine into a separate module. Each
module can be tested separately and then brought together with the main program. More importantly, in a
large program the modules can be assigned to different programmers in order to shorten development time.

Listing 27: Main Program Calling Subroutines


;MAIN program c a l l i n g s u b r o u t i n e s
ORG 0
MAIN:
LCALL SUBR 1
LCALL SUBR 2
LCALL SUBR 3
HERE:
SJMP HERE
;−−−end o f MAIN

46
;
SUBR 1 :
...
RET
;−−−end o f s u b r o u t i n e 1
;
SUBR 2 :
...
RET
;−−−end o f s u b r o u t i n e 2
SUBR 3 :
...
RET
;−−−end o f s u b r o u t i n e 3
END ; end o f t h e asm f i l e

11.5 ACALL (Absolute Call)


ACALL is a 2-byte instruction in contrast to LCALL, which is 3 bytes. Since ACALL is a 2-byte instruction,
the target address of the subroutine must be within 2K bytes because only 11 bits of the 2 bytes are used for
the address. There is no difference between ACALL and LCALL in terms of saving the program counter on
the stack or the function of the RET instruction. The only difference is that the target address for LCALL
can be anywhere within the 64K-byte address space of the 8051 while the target address of ACALL must be
within a 2K-byte range. In many variations of the 8051 marketed by different companies, on-chip ROM is as
low as 1K byte. In such cases, the use of ACALL instead of LCALL can save a number of bytes of program
ROM space.
Example 3-11
A developer is using the Atmel AT89C1051 microcontroller chip for a product. This chip has only 1K
byte of on-chip flash ROM. Which instruction, LCALL or ACALL, is more useful in programming this chip?
Solution:
The ACALL instruction is more useful since it is a 2-byte instruction. It saves one byte each time the
call instruction is used.
Of course, in addition to using compact instructions, we can program efficiently by having a detailed
knowledge of all the instructions supported by a given microprocessor, and using them wisely. Look at
Example 3-12.
Example 3-12
Rewrite Example 3-8 as efficiently as you can.
Solution:

Listing 28: Efficient Rewrite of Example 3-8


ORG 0
MOV A,#55H ; l o a d A w i t h 55H
BACK:
MOV P1 ,A ; i s s u e value in reg A to port 1
ACALL DELAY ; time d e l a y
CPL A ; complement r e g A
SJMP BACK ; keep doing t h i s i n d e f i n i t e l y
;−−−t h i s i s t h e d e l a y s u b r o u t i n e
DELAY:
MOV R5,#0FFH ; R5=255 (FF i n hex ) , t h e c o u n t e r
AGAIN:
DJNZ R5 ,AGAIN ; s t a y h e r e u n t i l R5 becomes 0
RET ; return to c a l l e r
END ; end o f asm f i l e

47
Notice in this program that register A is set to 55H. By complementing 55H, we have AAH; and by
complementing AAH we have 55H. Why? “01010101” in binary (55H) becomes “10101010” in binary (AAH)
when it is complemented; and “10101010” becomes “01010101” if it is complemented.

Review Questions
6. What do the mnemonics “LCALL” and “ACALL” stand for?
7. True or false. In the 8051, control can be transferred anywhere within the 64K bytes of code space if
using the LCALL instruction.

8. How does the CPU know where to return to after executing the RET instruction?
9. Describe briefly the function of the RET instruction.
10. The LCALL instruction is a -byte instruction.

12 Time Delay for Various 8051 Chips


In the last section we used the DELAY subroutine. In this section we discuss how to generate various time
delays and calculate exact delays for the 8051 and DS89C4x0.

12.1 Machine Cycle for the 8051


The CPU takes a certain number of clock cycles to execute an instruction. In the 8051 family, these clock
cycles are referred to as machine cycles. Table A-1 provides the list of 8051 instructions and their machine
cycles. To calculate a time delay, we use this list. In the 8051 family, the length of the machine cycle
depends on the frequency of the crystal oscillator connected to the 8051 system. The crystal oscillator,
along with on-chip circuitry, provide the clock source for the 8051 CPU (see Chapter 8). The frequency of
the crystal connected to the 8051 family can vary from 4 MHz to 30 MHz, depending on the chip rating
and manufacturer. Very often the 11.0592 MHz crystal oscillator is used to make the 8051-based system
compatible with the serial port of the IBM PC (see Chapter 10). In the original 8051, one machine cycle
lasts 12 oscillator periods. Therefore, to calculate the machine cycle for the 8051, we take 1/12 of the crystal
frequency, then take its inverse, as shown in Example 3-13.
Example 3-13
The following shows crystal frequency for three different 8051-based systems. Find the period of the
machine cycle in each case.
(a) 11.0592 MHz (b) 16 MHz (c) 20 MHz
Solution:

(a) 11.0592 MHz / 12 = 921.6 kHz; machine cycle is 1 / 921.6 kHz = 1.085 µs (microsecond)
(b) 16 MHz / 12 = 1.333 MHz; machine cycle (MC) = 1 / 1.333 MHz = 0.75 µs

(c) 20 MHz / 12 = 1.66 MHz; MC = 1 / 1.66 MHz = 0.60 µs

Example 3-14
For an 8051 system of 11.0592 MHz, find how long it takes to execute each of the following instructions.
(a) MOV R3, #55 (b) DEC R3 (c) DJNZ R2, target (d) LJMP (e) SJMP (f) NOP (no
operation) (g) MUL AB
Solution:
The machine cycle for a system of 11.0592 MHz is 1.085 µs as shown in Example 3-13. Table A-1 in
Appendix A shows machine cycles for each of the above instructions. Therefore, we have:

48
Table 18: Instruction Execution Time for 11.0592 MHz 8051 (Example 3-14)

Instruction Machine Cycles Time to Execute


(a) MOV R3, #55 1 1 × 1.085 µs = 1.085 µs
(b) DEC R3 1 1 × 1.085 µs = 1.085 µs
(c) DJNZ R2, target 2 2 × 1.085 µs = 2.17 µs
(d) LJMP 2 2 × 1.085 µs = 2.17 µs
(e) SJMP 2 2 × 1.085 µs = 2.17 µs
(f) NOP 1 1 × 1.085 µs = 1.085 µs
(g) MUL AB 4 4 × 1.085 µs = 4.34 µs

12.2 Delay Calculation for 8051


As seen in the last section, a delay subroutine consists of two parts: (1) setting a counter, and (2) a loop.
Most of the time delay is performed by the body of the loop, as shown in Example 3-15.
Example 3-15
Find the size of the delay in the following program, if the crystal frequency is 11.0592 MHz.

Listing 29: Delay Subroutine for Delay Calculation (Example 3-15)


MOV A,#55H ; l o a d A w i t h 55H
AGAIN:
MOV P1 ,A ; i s s u e value in reg A to port 1
ACALL DELAY ; time d e l a y
CPL A ; complement r e g A
SJMP AGAIN ; keep doing t h i s i n d e f i n i t e l y
;−−−−Time d e l a y
DELAY:
MOV R3,#200 ; l o a d R3 w i t h 200
HERE:
DJNZ R3 ,HERE ; s t a y h e r e u n t i l R3 becomes 0
RET ; return to c a l l e r
Solution:
From Table A-1 in Appendix A, we have the following machine cycles for each instruction of the DELAY
subroutine.

Table 19: Machine Cycles for DELAY Subroutine Instructions

Label Instruction Machine Cycles


DELAY: MOV R3,#200 1
HERE: DJNZ R3,HERE 2
RET 2

Therefore, we have a time delay of [(200 × 2) + 1 + 2] × 1.085 µs = 436.255 µs.


Very often we calculate the time delay based on the instructions inside the loop and ignore the clock
cycles associated with the instructions outside the loop.
In Example 3-15, the largest value the R3 register can take is 255; therefore, one way to increase the
delay is to use NOP instructions in the loop. NOP, which stands for “no operation,” simply wastes time.
This is shown in Example 3-16.

12.3 Loop Inside Loop Delay


Another way to get a large delay is to use a loop inside a loop, which is also called a nested loop. See
Example 3-17.
Example 3-16

49
For an 8051 system of 11.0592 MHz, find the time delay for the following subroutine:

Listing 30: Delay Subroutine with NOP Instructions (Example 3-16)


DELAY: Machine Cycle
MOV R3,#250 1
HERE:
NOP 1
NOP 1
NOP 1
DJNZ R3 ,HERE 2
RET 2
Solution:
The time delay inside the HERE loop is [250×(1+1+1+1+2)]×1.085 µs = 1500×1.085 µs = 1627.5 µs.
Adding the two instructions outside the loop we have 1627.5 µs + 3 × 1.085 µs = 1630.755 µs.
If machine cycle timing is critical to your system design, make sure that you check the manufacturer’s
data sheets for the device specification. For example, the DS89C420 has 3 machine cycles instead of 2
machine cycles for the RET instruction.
Example 3-17
For a machine cycle of 1.085 µs, find the time delay in the following subroutine.

Listing 31: Nested Loop Delay Subroutine (Example 3-17)


DELAY: Machine Cycle
MOV R2,#200 1
AGAIN:
MOV R3,#250 1
HERE:
NOP 1
NOP 1
DJNZ R3 ,HERE 2
DJNZ R2 ,AGAIN 2
RET 2
For the HERE loop, we have (4 × 250) × 1.085 µs = 1085 µs. The AGAIN loop repeats the HERE loop
200 times; therefore, we have 200 × 1085 µs = 217,000, if we do not include the overhead. However, the
instructions “MOV R3,#250” and “DJNZ R2,AGAIN” at the beginning and end of the AGAIN loop add
(3 × 200 × 1.085 µs) = 651 µs to the time delay. As a result we have 217,000 + 651 = 217,651 µs = 217.651
milliseconds for total time delay associated with the above DELAY subroutine. Notice that in the case of
a nested loop, as in all other time delay loops, the time is approximate since we have ignored the first and
last instructions in the subroutine.

12.4 Delay Calculation for Other Versions of 8051


In creating a time delay using Assembly language instructions, one must be mindful of two factors that can
affect the accuracy of the delay.

1. The crystal frequency: The frequency of the crystal oscillator connected to the X1–X2 input pins
is one factor in the time delay calculation. The duration of the clock period for the machine cycle is a
function of this crystal frequency.
2. The 8051 Design: Since the original 8051 was designed in 1980, both the field of IC technology and
the architectural design of microprocessors have seen great advancements. Due to the limitations of IC
technology and limited CPU design experience at that time, the machine cycle duration was set at 12
clocks. Advances in both IC technology and CPU design in recent years have made the 1-clock machine
cycle a common feature of many new 8051 chips. Indeed, one way to increase the 8051 performance
without losing code compatibility with the original 8051 is to reduce the number of clock cycles it

50
takes to execute an instruction. For these reasons, the number of machine cycles and the number of
clock periods per machine cycle varies among the different versions of the 8051 microcontrollers. While
the original 8051 design used 12 clock periods per machine cycle, many of the newer generations of
the 8051 use much fewer clocks per machine cycle. For example, the DS5000 uses 4 clock periods per
machine cycle while the DS89C4x0 uses only one clock per machine cycle. The 8051 products from
Philips Semiconductors have the option of using either 6 or 12 clocks per machine cycle. Table 20
shows some of the 8051 versions with their machine cycles.

Table 20: Clocks per Machine Cycle (MC) for Various 8051 Versions

Chip/Maker Clocks per Machine Cycle


AT89C51, Atmel 12
P89C54X2, Philips 6
DS5000, Dallas Semi 4
DS89C420/30/40/50, Dallas Semi 1

Example 3-18
From Table 20, find the period of the machine cycle (MC) in each case if XTAL = 11.0592 MHz, and
discuss the impact on performance.
(a) AT89C51 (b) P89C54X2 (c) DS5000 (d) DS89C4x0
Solution:

(a) 11.0592 MHz / 12 = 921.6 kHz; MC is 1 / 921.6 kHz = 1.085 µs (microsecond) = 1085 ns
(b) 11.0592 MHz / 6 = 1.8432 MHz; MC is 1 / 1.8432 MHz = 0.5425 µs = 542 ns
(c) 11.0592 MHz / 4 = 2.7648 MHz; MC is 1 / 2.7648 MHz = 0.36 µs = 360 ns
(d) 11.0592 MHz / 1 = 11.0592 MHz; MC is 1 / 11.0592 MHz = 0.0904 µs = 90 ns

This means that if we connect an AT89C51 and a DS89C4x0 to a crystal of the same frequency we get
approximately 9 to 10 times performance boost for the DS89C4x0 chip over the AT89C51. See Example
3-19.

12.5 Delay Calculation for DS89C4x0


In the case of the DS89C4x0, since the number of clocks per machine cycle was reduced from 12 to 1, the
number of machine cycles used to execute an instruction had to be changed to reflect this reality. Table 21
compares the machine cycles for the DS89C4x0 and 8051 for some instructions.

Table 21: Comparison of 8051 and DS89C4x0 Machine Cycles

Instruction 8051 DS89C4x0


MOV R3,#value 1 2
DEC Rx 1 1
DJNZ 2 4
LJMP 2 3
SJMP 2 3
NOP 1 1
MUL AB 4 9

See the following Web sites for DS89C420/30/40/50 instructions and timing:
• [Link]
• [Link]

51
Example 3-19
Compare the execution time of the following instructions for AT89C51 (MC = 1085 ns) and DS89C420/30/40/50
(MC = 90 ns).

Table 22: Instruction Execution Time Comparison (Example 3-19)

Instruction AT8051 DS89C420/30/40/50


(a) MOV R3,#55 1 × 1085 ns = 1085 ns 2 × 90 ns = 180 ns
(b) DEC R3 1 × 1085 ns = 1085 ns 1 × 90 ns = 90 ns
(c) DJNZ R2,. . . 2 × 1085 ns = 2170 ns 4 × 90 ns = 360 ns
(d) LJMP 2 × 1085 ns = 2170 ns 3 × 90 ns = 270 ns
(e) SJMP 2 × 1085 ns = 2170 ns 3 × 90 ns = 270 ns
(f) NOP 1 × 1085 ns = 1085 ns 1 × 90 ns = 90 ns
(g) MUL AB 4 × 1085 ns = 4340 ns 9 × 90 ns = 810 ns

Example 3-20
Find the time delay for the loop section of the following subroutine if it is run on a DS89C420/30 chip,
assuming a crystal frequency of 11.0592 MHz.

Listing 32: DS89C420/30 Delay Subroutine (Example 3-20)


DELAY: DS89C420 /30 Machine Cycle
MOV R3,#250 2
HERE:
NOP 1
NOP 1
NOP 1
NOP 1
DJNZ R3 ,HERE 4
RET 3
Solution:
The time delay inside the HERE loop is [250 × (1 + 1 + 1 + 1 + 4)] × 90 ns = 2000 × 90 ns = 180 µs.
Comparing this with Example 3-16, we see DS89C4x0 is about 9 times faster. (1627 µs / 180 µs = 9)
Example 3-21
Write a program to toggle all the bits of P1 every 200 ms. Assume that the crystal frequency is 11.0592
MHz, and that the system is using the AT89C51.
Solution:

Listing 33: Toggle P1 Every 200 ms – AT89C51 (Example 3-21)


; T e s t e d f o r AT89C51 o f 11 . 0 5 9 2 MHz.
MOV A,#55H
AGAIN:
MOV P1 ,A
ACALL DELAY
CPL A
SJMP AGAIN
;−−−−Time d e l a y
DELAY:
MOV R5,#2
HERE1 :
MOV R4,#180
HERE2 :
MOV R3,#255
HERE3 :
DJNZ R3 , HERE3

52
DJNZ R4 , HERE2
DJNZ R5 , HERE1
RET
; Delay = 2 x 180 x 255 x 2 MC x 1 . 0 8 5 us = 199 ,206 us
Now write a program to toggle all the bits of P1 every 200 ms. Assume crystal frequency is 11.0592 MHz
and the system is using DS89C420/30/40/50.
Solution:

Listing 34: Toggle P1 Every 200 ms – DS89C420 (Example 3-21)


; T e s t e d f o r DS89C420 o f 11 . 0 5 9 2 MHz.
MOV A,#55H
AGAIN:
MOV P1 ,A
ACALL DELAY 200m
CPL A
SJMP AGAIN
;−−−−Time d e l a y
DELAY 200m :
MOV R5,#9
HERE1 :
MOV R4,#242
HERE2 :
MOV R3,#255
HERE3 :
DJNZ R3 , HERE3
DJNZ R4 , HERE2
DJNZ R5 , HERE1
RET
; Delay = 9 x 242 x 255 x 4 MC x 90 ns = 199 ,940 us
Use an oscilloscope to measure the system square wave period to verify delay.
From the above discussion we conclude that use of the instruction in generating time delay is not the
most reliable method. To get more accurate time delay we use timers as described in Chapter 9. Meanwhile,
to get an accurate time delay for a given 8051 microcontroller, we must use an oscilloscope to measure the
exact time delay.
See the following Web sites for 8051 products and their features from various companies:
• [Link]
• [Link]

12.6 SJMP to Itself Using $ Sign


In cases where there is no monitor program, we need to short jump to itself in order to keep the microcontroller
busy. A simple way of doing that is to use the $ sign. That means in place of this:

Listing 35: SJMP to Label


HERE: SJMP HERE
we can use the following:

Listing 36: SJMP to Itself Using Dollar Sign


SJMP $ ; s h o r t jump t o i t s e l f

53
Review Questions
11. True or false. In the 8051, the machine cycle lasts 12 clock cycles of the crystal frequency.
12. The minimum number of machine cycles needed to execute an 8051 instruction is .

13. For Question 12, what is the maximum number of cycles needed, and for which instructions?
14. Find the machine cycle for a crystal frequency of 12 MHz.
15. Assuming a crystal frequency of 12 MHz, find the time delay associated with the loop section of the
following DELAY subroutine.

Listing 37: Delay Subroutine for Review Question 16


DELAY:
MOV R3,#100
HERE:
NOP
NOP
NOP
DJNZ R3 , HERE
RET

16. True or false. In the DS89C420/30, the machine cycle lasts 12 clock cycles of the crystal frequency.
17. Find the machine cycle for a DS89C420/30 if the crystal frequency is 11.0592 MHz.

Summary
The flow of a program proceeds sequentially, from instruction to instruction, unless a control transfer instruc-
tion is executed. The various types of control transfer instructions in Assembly language include conditional
and unconditional jumps, and call instructions.
The looping action in 8051 Assembly language is performed using a special instruction, which decrements
a counter and jumps to the top of the loop if the counter is not zero. Other jump instructions jump
conditionally, based on the value of the carry flag, the accumulator, or bits of the I/O port. Unconditional
jumps can be long or short, depending on the relative value of the target address. Special attention must be
given to the effect of LCALL and ACALL instructions on the stack.

Problems
Section 3.1: Loop and Jump Instructions
1. In the 8051, looping action with the instruction “DJNZ Rx, rel address” is limited to iterations.
2. If a conditional jump is not taken, what is the next instruction to be executed?

3. In calculating the target address for a jump, a displacement is added to the contents of register .
4. The mnemonic SJMP stands for and it is a -byte instruction.
5. The mnemonic LJMP stands for and it is a -byte instruction.

6. What is the advantage of using SJMP over LJMP?


7. True or false. The target of a short jump is within −128 to +127 bytes of the current PC.
8. True or false. All 8051 jumps are short jumps.
9. Which of the following instructions is (are) not a short jump?

54
(a) JZ (b) JNC (c) LJMP (d) DJNZ
10. A short jump is a -byte instruction. Why?
11. True or false. All conditional jumps are short jumps.
12. Show code for a nested loop to perform an action 1000 times.

13. Show code for a nested loop to perform an action 100,000 times.
14. Find the number of times the following loop is performed.
MOV R6,#200
BACK:
MOV R5,#100
HERE:
DJNZ R5 ,HERE
DJNZ R6 ,BACK

15. The target address of a jump backward is a maximum of bytes from the current PC.
16. The target address of a jump forward is a maximum of bytes from the current PC.

Section 3.2: Call Instructions


17. LCALL is a -byte instruction.
18. ACALL is a -byte instruction.

19. The ACALL target address is limited to bytes from the present PC.
20. The LCALL target address is limited to bytes from the present PC.
21. When LCALL is executed, how many bytes of the stack are used?
22. When ACALL is executed, how many bytes of the stack are used?

23. Why do the PUSH and POP instructions in a subroutine need to be equal in number?
24. Describe the action associated with the POP instruction.
25. Show the stack for the following code.
000B 120300 LCALL DELAY
000E 80F0 SJMP BACK ; keep doing t h i s
0010

0010 ;−−−t h i s i s t h e d e l a y s u b r o u t i n e
0300 ORG 300H
0300 DELAY:
0300 7DFF MOV R5,#0FFH ; R5=255
0302 DDFE AGAIN: DJNZ R5 ,AGAIN ; s t a y h e r e
0304 22 RET ; r e t u r n

26. Reassemble Example 3-10 at ORG 200 (instead of ORG 0) and show the stack frame for the first
LCALL instruction.

55
Section 3.3: Time Delay for Various 8051 Chips
26. Find the system frequency if the machine cycle = 1.2 µs.
27. Find the machine cycle if the crystal frequency is 18 MHz.

28. Find the machine cycle if the crystal frequency is 12 MHz.


29. Find the machine cycle if the crystal frequency is 25 MHz.
30. True or false. LJMP and SJMP instructions take the same amount of time to execute even though one
is a 3-byte instruction and the other is a 2-byte instruction.

31. Find the time delay for the delay subroutine shown below, if the system has an 8051 with frequency
of 11.0592 MHz.
DELAY:
MOV R3,#150
HERE:
NOP
NOP
NOP
DJNZ R3 ,HERE
RET

32. Find the time delay for the delay subroutine shown below, if the system has an 8051 with frequency
of 16 MHz.
DELAY:
MOV R3,#200
HERE:
NOP
NOP
NOP
DJNZ R3 ,HERE
RET

33. Find the time delay for the delay subroutine shown below, if the system has an 8051 with frequency
of 11.0592 MHz.
DELAY:
MOV R5,#100
BACK:
MOV R2,#200
AGAIN:
MOV R3,#250
HERE:
NOP
NOP
DJNZ R3 ,HERE
DJNZ R2 ,AGAIN
DJNZ R5 ,BACK
RET

34. Find the time delay for the delay subroutine shown below, if the system has an 8051 with frequency
of 16 MHz.

56
DELAY:
MOV R2,#150
AGAIN:
MOV R3,#250
HERE:
NOP
NOP
NOP
DJNZ R3 ,HERE
DJNZ R2 ,AGAIN
RET

35. Repeat Problem 32 for DS89C420/30.


36. Repeat Problem 33 for DS89C420/30.
37. Repeat Problem 34 for DS89C420/30.
38. Repeat Problem 35 for DS89C420/30.
39. In an AT89C51-based system, explain performance improvement if we replace the AT89C51 chip with
a DS89C420/30. Is it 12 times faster?

Answers to Review Questions


Section 3.1: Loop and Jump Instructions
1. Decrement and jump if not zero
2. True
3. 2
4. A
5. 3

Section 3.2: Call Instructions


6. Long CALL and Absolute CALL
7. True
8. The address of where to return is in the stack.
9. Upon executing the RET instruction, the CPU pops off the top two bytes of the stack into the program
counter (PC) register and starts to execute from this new location.
10. 3

Section 3.3: Time Delay for Various 8051 Chips


11. True
12. 1
13. MUL and DIV each take 4 machine cycles.
14. 12 MHz / 12 = 1 MHz, and MC = 1 / 1 MHz = 1 µs.
15. [100 × (1 + 1 + 1 + 2)] × 1 µs = 500 µs = 0.5 milliseconds.

57
16. False. It takes 1 clock.
17. 11.0592 MHz / 1 = 11.0592 MHz; machine cycle is 1 / 11.0592 MHz = 0.0904 µs = 90.4 ns

58

You might also like