Microcontroller
Microcontroller
Objectives
Upon completion of this chapter, you will be able to:
1
CPU RAM ROM
I/O Timer Serial COM Port
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.
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.
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.
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.
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?
Feature Quantity
ROM 4K bytes
RAM 128 bytes
Timer 2
I/O pins 32
Serial port 1
Interrupt sources 6
5
Figure 3: Inside the 8051 Microcontroller Block Diagram
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.
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.
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].
• [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?
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.
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.
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.
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.
12
Figure 4: Some 8-bit Registers of the 8051
13
Figure 5: Some 8051 16-bit Registers
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.
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.
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:
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.
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.
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.
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.
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.
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.
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.
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.
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?
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:
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.
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”.
Review Questions
1. The directive is always used for ASCII strings.
24
Figure 8: Bits of the PSW Register
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.
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.
38 00111000
+ 2F 00101111
-----
67 01100111
Example 2-3
Show the status of the CY, AC, and P flags after the addition of 9CH and 64H in the following instructions.
9C 10011100
+ 64 01100100
-----
100 00000000
Example 2-4
Show the status of the CY, AC, and P flags after the addition of 88H and 93H in the following instructions.
88 10001000
+ 93 10010011
-----
11B 00011011
27
Review Questions
1. The flag register in the 8051 is called .
2. What is the size of the flag register in the 8051?
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.
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:
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:
• RAM location 0 has value 99H RAM location 1 has value 85H
• RAM location 2 has value 3FH RAM location 7 has value 63H
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.
• 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
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.
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”.
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
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
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.
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
37. Find the CY flag value after each of the following codes.
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
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.
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’)
36. 08
37. 0
38. 00 to 07
39. Bank 3
40. 18H to 1FH
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
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.
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.
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.
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:
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.
41
Figure 12: Target Address Calculation for Short Jump Instructions
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.
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.
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.
43
Figure 13: 8051 Assembly Main Program That Calls Subroutines
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.
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)
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.
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.
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.
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
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.
(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
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)
49
For an 8051 system of 11.0592 MHz, find the time delay for the following subroutine:
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
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.
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).
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.
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:
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.
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.
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.
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.
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
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