8051-interfacing-techniques-pratical guide-with examples-in detail-part-4 by itechlearn


More Info
									                                                              8051 Tutorial

                (C) Copyright 1997, 1998, 1999 by Vault Information Services. All Rights Reserved.



                                                      8051 Tutorial: Introduction

           Despite it’s relatively old age, the 8051 is                             programming. The appendices are a useful
one of the most popular microcontrollers in use                                     reference tool that will assist both the novice
today. Many derivative microcontrollers have since                                  programmer as well as the experienced
been developed that are based on--and                                               professional developer.
compatible with--the 8051. Thus, the ability to                                              This document assumes the following:
program an 8051 is an important skill for anyone                                    • A general knowledge of programming.
who plans to develop products that will take                                        • An understanding of decimal, hexidecimal, and
advantage of microcontrollers.                                                          binary number systems.
           Many web pages, books, and tools are                                     • A general knowledge of hardware.
available for the 8051 developer.                                                            That is to say, no knowledge of the 8051
           I hope the information contained in this                                 is assumed--however, it is assumed you’ve done
document/web page will assist you in mastering                                      some amount of programming before, have a
8051 programming. While it is not my intention that                                 basic understanding of hardware, and a firm grasp
this document replace a hardcopy book purchased                                     on the three numbering systems mentioned above.
at your local book store, it is entirely possible that                              The concept of converting a number from
this may be the case. It is likely that this document                               deciminal to hexidecimal and/or to binary is not
contains everything you will need to learn 8051                                     within the scope of this document--and if you can’t
assembly language programming. Of course, this                                      do those types of conversions there are probably
document is free and you get what you pay for so                                    some concepts that will not be completely
if, after reading this document, you still are lost you                             understandable.
may find it necessary to buy a book.                                                This document attempts to address the need of
           This document is both a tutorial and a                                   the typical programmer. For example, there are
reference tool. The various chapters of the                                         certain features that are nifty and in some cases
document will explain the 8051 step by step. The                                    very useful--but 95% of the programmers will
chapters are targeted at people who are                                             never use these features.
attempting to learn 8051 assembly language

                                 8051 Tutorial: Types of Memory

      The 8051 has three very general types of          necessary to have a basic understanding of these
memory. To effectively program the 8051 it is           memory types.

        On-Chip Memory refers to any memory                      External Code Memory is code (or
(Code, RAM, or other) that physically exists on the     program) memory that resides off-chip. This is
microcontroller itself. On-chip memory can be of        often in the form of an external EPROM.
several types, but we'll get into that shortly.                  External RAM is RAM memory that
                                                        resides off-chip. This is often in the form of
                                                        standard static RAM or flash RAM.

                                               Code Memory

        Code memory is the memory that holds            This varies depending on the version of the chip
the actual 8051 program that is to be run. This         that is being used. Each version offers specific
memory is limited to 64K and comes in many              capabilities and one of the distinguishing factors
shapes and sizes: Code memory may be found              from chip to chip is how much ROM/EPROM
on-chip, either burned into the microcontroller as      space the chip has.
ROM or EPROM. Code may also be stored                            However, code memory is most commonly
completely off-chip in an external ROM or, more         implemented as off-chip EPROM. This is
commonly, an external EPROM. Flash RAM is               especially true in low-cost development systems
also another popular method of storing a program.       and in systems developed by students.
Various combinations of these memory types may                    Programming Tip: Since code memory is
also be used--that is to say, it is possible to have    restricted to 64K, 8051 programs are limited to 64K.
4K of code memory on-chip and 64k of code               Some assemblers and compilers offer ways to get
memory off-chip in an EPROM.                            around this limit when used with specially wired
                                                        hardware. However, without such special compilers and
        When the program is stored on-chip the          hardware, programs are limited to 64K.

                                               External RAM

         As an obvious opposite of Internal RAM,                   What External RAM loses in speed and
the 8051 also supports what is called External          flexibility it gains in quantity. While Internal RAM is
RAM. As the name suggests, External RAM is any          limited to 128 bytes the 8051 supports External
random access memory which is found off-chip.           RAM up to 64K.
Since the memory is off-chip it is not as flexible in             Programming Tip: The 8051 may only
terms of accessing, and is also slower. For             address 64k of RAM. To expand RAM beyond this limit
example, to increment an Internal RAM location by       requires programming and hardware tricks. You may
1 requires only 1 instruction and 1 instruction         have to do this "by hand" since many compilers and
                                                        assemblers, while providing support for programs in
cycle. To increment a 1-byte value stored in            excess of 64k, do not support more than 64k of RAM.
External RAM requires 4 instructions and 7              This is rather strange since it has been my experience
instruction cycles. In this case, external memory is    that programs can usually fit in 64k but often RAM is
7 times slower!                                         what is lacking. Thus if you need more than 64k of RAM,
                                                        doesn't, be prepared to do it by hand.

                                                On-Chip Memory.

         As mentioned at the beginning of this               (SFR) memory. The layout of the 8051's internal
 chapter, the 8051 includes a certain amount of on-          memory is presented in the following memory
 chip memory. On-chip memory is really one of two            map:

        As is illustrated in this map, the 8051 has a                  Bit Memory also lives and is part of internal
bank of 128 bytes of Internal RAM. This Internal RAM          RAM. We'll talk more about bit memory very shortly,
is found on-chip on the 8051 so it is the fastest RAM         but for now just keep in mind that bit memory actually
available, and it is also the most flexible in terms of       resides in internal RAM, from addresses 20h through
reading, writing, and modifying it’s contents. Internal       2Fh.
RAM is volatile, so when the 8051 is reset this                        The 80 bytes remaining of Internal RAM, from
memory is cleared.                                            addresses 30h through 7Fh, may be used by user
        The 128 bytes of internal ram is subdivided           variables that need to be accessed frequently or at
as shown on the memory map. The first 8 bytes (00h            high-speed. This area is also utilized by the
- 07h) are "register bank 0". By manipulating certain         microcontroller as a storage area for the operating
SFRs, a program may choose to use register banks              stack. This fact severely limits the 8051’s stack since,
1, 2, or 3. These alternative register banks are              as illustrated in the memory map, the area reserved
located in internal RAM in addresses 08h through              for the stack is only 80 bytes--and usually it is less
1Fh.                                                          since this 80 bytes has to be shared between the
        We'll discuss "register banks" more in a later        stack and user variables.
and are part of internal RAM.

                                                 Register Banks

          The 8051 uses 8 "R" registers which are            the above instruction accomplishes the same thing
 used in many of its instructions. These "R"                 as the following operation:
 registers are numbered from 0 through 7 (R0, R1,
 R2, R3, R4, R5, R6, and R7). These registers are                    ADD A,04h
 generally used to assist in manipulating values
 and moving data from one memory location to                          This instruction adds the value found in
 another. For example, to add the value of R4 to             Internal RAM address 04h to the value of the
 the Accumulator, we would execute the following             Accumulator, leaving the result in the Accumulator.
 instruction:                                                Since R4 is really Internal RAM 04h, the above
                                                             instruction effectively accomplished the same
          ADD A,R4                                           thing.
                                                                      But watch out! As the memory map
         However, as the memory map shows, the               shows, the 8051 has four distinct register banks.
 "R" Register R4 is really part of Internal RAM.             When the 8051 is first booted up, register bank 0
 Specifically, R4 is address 04h. This can be see in         (addresses 00h through 07h) is used by default.
 the bright green section of the memory map. Thus            However, your program may instruct the 8051 to
use one of the alternate register banks; i.e.,             interrupts later). However, always remember that
register banks 1, 2, or 3. In this case, R4 will no        the register banks really reside in the first 32 bytes
longer be the same as Internal RAM address 04h.            of Internal RAM.
For example, if your program instructs the 8051 to                  Programming Tip: If you only use the first
use register bank 3, "R" register R4 will now be           register bank (i.e. bank 0), you may use Internal RAM
synonomous with Internal RAM address 1Ch.                  locations 08h through 1Fh for your own use. But if you
         The concept of register banks adds a              plan to use register banks 1, 2, or 3, be very careful
                                                           about using addresses below 20h as you may end up
great level of flexibility to the 8051, especially         overwriting the value of your "R" registers!
when dealing with interrupts (we'll talk about

                                                   Bit Memory

         The 8051, being a communications-                          Bit variables 00h through 7Fh are for user-
oriented microcontroller, gives the user the ability       defined functions in their programs. However, bit
to access a number of bit variables. These                 variables 80h and above are actually used to
variables may be either 1 or 0.                            access certain SFRs on a bit-by-bit basis. For
         There are 128 bit variables available to the      example, if output lines P0.0 through P0.7 are all
user, numberd 00h through 7Fh. The user may                clear (0) and you want to turn on the P0.0 output
make use of these variables with commands such             line you may either execute:
as SETB and CLR.
                                                                    MOV P0,#01h || SETB 80h
         It is important to note that Bit Memory is
variables occupy the 16 bytes of Internal RAM                       Both these instructions accomplish the
from 20h through 2Fh. Thus, if you write the value         same thing. However, using the SETB command
FFh to Internal RAM address 20h you’ve                     will turn on the P0.0 line without effecting the
effectively set bits 00h through 07h.                      status of any of the other P0 output lines. The
         But since the 8051 provides special               MOV command effectively turns off all the other
instructions to access these 16 bytes of memory            output lines which, in some cases, may not be
on a bit by bit basis it is useful to think of it as a     acceptable.
                                                                      Programming Tip: By default, the 8051
separate type of memory. However, always keep              initializes the Stack Pointer (SP) to 08h when the
in mind that it is just a subset of Internal RAM--and      microcontroller is booted. This means that the stack will
that operations performed on Internal RAM can              start at address 08h and expand upwards. If you will be
change the values of the bit variables.                    using the alternate register banks (banks 1, 2 or 3) you
         Programming Tip: If your program does not         must initialize the stack pointer to an address above the
use bit variables, you may use Internal RAM locations      highest register bank you will be using, otherwise the
20h through 2Fh for your own use. But if you plan to use   stack will overwrite your alternate register banks.
bit variables, be very careful about using addresses       Similarly, if you will be using bit variables it is usually a
from 20h through 2Fh as you may end up overwriting         good idea to initialize the stack pointer to some value
the value of your bits!                                    greater than 2Fh to guarantee that your bit variables are
                                                           protected from the stack.

                                  Special Function Register (SFR) Memory

         Special Function Registers (SFRs) are             99 Hex. Thus, to write the value "1" to the serial
areas of memory that control specific functionality        port you would execute the instruction:
of the 8051 processor. For example, four SFRs
permit access to the 8051’s 32 input/output lines.                  MOV 99h,#01h
Another SFR allows a program to read or write to
the 8051’s serial port. Other SFRs allow the user                   As you can see, it appears that the SFR is
to set the serial baud rate, control and access            part of Internal Memory. This is not the case.
timers, and configure the 8051’s interrupt system.         When using this method of memory access (it’s
         When programming, SFRs have the                   called direct address), any instruction that has an
illusion of being Internal Memory. For example, if         address of 00h through 7Fh refers to an Internal
you want to write the value "1" to Internal RAM            RAM memory address; any instruction with an
location 50 hex you would execute the instruction:         address of 80h through FFh refers to an SFR
                                                           control register.
        MOV 50h,#01h                                                Programming Tip: SFRs are used to control
                                                           the way the 8051 functions. Each SFR has a specific
        Similarly, if you want to write the value "1"      purpose and format which will be discussed later. Not all
to the 8051’s serial port you would write this value       addresses above 80h are assigned to SFRs. However,
                                                           this area may NOT be used as additional RAM memory
to the SBUF SFR, which has an SFR address of               even if a given address has not been assigned to an
                                         8051 Tutorial: SFRs

                                             What Are SFRs?

         The 8051 is a flexible microcontroller with    RAM is from address 00h through 7Fh whereas
a relatively large number of modes of operations.       SFR registers exist in the address range of 80h
Your program may inspect and/or change the              through FFh.
operating mode of the 8051 by manipulating the                  Each SFR has an address (80h through
values of the 8051's Special Function Registers         FFh) and a name. The following chart provides a
(SFRs).                                                 graphical presentation of the 8051's SFRs, their
         SFRs are accessed as if they were normal       names, and their address.
Internal RAM. The only difference is that Internal

        As you can see, although the address                     Programming Tip: It is recommended that you
range of 80h through FFh offer 128 possible             not read or write to SFR addresses that have not been
addresses, there are only 21 SFRs in a standard         assigned to an SFR. Doing so may provoke undefined
8051. All other addresses in the SFR range (80h         behavior and may cause your program to be
                                                        incompatible with other 8051-derivatives that use the
through FFh) are considered invalid. Writing to or      given SFR for some other purpose.
reading from these registers may produce
undefined values or behavior.

                                                SFR Types

         As mentioned in the chart itself, the SFRs     be thought of as auxillary SFRs in the sense that
that have a blue background are SFRs related to         they don't directly configure the 8051 but obviously
the I/O ports. The 8051 has four I/O ports of 8 bits,   the 8051 cannot operate without them. For
for a total of 32 I/O lines. Whether a given I/O line   example, once the serial port has been configured
is high or low and the value read from the line are     using SCON, the program may read or write to the
controlled by the SFRs in green.                        serial port using the SBUF register.
         The SFRs with yellow backgrouns are                      Programming Tip: The SFRs whose names
SFRs which in some way control the operation or         appear in red in the chart above are SFRs that may be
the configuration of some aspect of the 8051. For       accessed via bit operations (i.e., using the SETB and
example, TCON controls the timers, SCON                 CLR instructions). The other SFRs cannot be accessed
                                                        using bit operations. As you can see, all SFRs that
controls the serial port.                               whose addresses are divisible by 8 can be accessed
         The remaining SFRs, with green                 with bit operations.
backgrounds, are "other SFRs." These SFRs can

                                                 SFR Descriptions

        This section will endeavor to quickly                 SFR--this information will be covered in separate
overview each of the standard SFRs found in the               chapters of the tutorial. This section is to just give
above SFR chart map. It is not the intention of this          you a general idea of what each SFR does.
section to fully explain the functionality of each

        P0 (Port 0, Address 80h, Bit-Addressable): This is input/output port 0. Each bit of this SFR
corresponds to one of the pins on the microcontroller. For example, bit 0 of port 0 is pin P0.0, bit 7 is pin
P0.7. Writing a value of 1 to a bit of this SFR will send a high level on the corresponding I/O pin whereas
a value of 0 will bring it to a low level.
         Programming Tip: While the 8051 has four I/O port (P0, P1, P2, and P3), if your hardware uses external
RAM or external code memory (i.e., your program is stored in an external ROM or EPROM chip or if you are using
external RAM chips) you may not use P0 or P2. This is because the 8051 uses ports P0 and P2 to address the
external memory. Thus if you are using external RAM or code memory you may only use ports P1 and P3 for your
own use.

          SP (Stack Pointer, Address 81h): This is the stack pointer of the microcontroller. This SFR
indicates where the next value to be taken from the stack will be read from in Internal RAM. If you push a
value onto the stack, the value will be written to the address of SP + 1. That is to say, if SP holds the
value 07h, a PUSH instruction will push the value onto the stack at address 08h. This SFR is modified by
all instructions which modify the stack, such as PUSH, POP, LCALL, RET, RETI, and whenever interrupts
are provoked by the microcontroller.
           Programming Tip: The SP SFR, on startup, is initialized to 07h. This means the stack will start at 08h and
start expanding upward in internal RAM. Since alternate register banks 1, 2, and 3 as well as the user bit variables
occupy internal RAM from addresses 08h through 2Fh, it is necessary to initialize SP in your program to some other
value if you will be using the alternate register banks and/or bit memory. It's not a bad idea to initialize SP to 2Fh as
the first instruction of every one of your programs unless you are 100% sure you will not be using the register banks
and bit variables.

         DPL/DPH (Data Pointer Low/High, Addresses 82h/83h): The SFRs DPL and DPH work
together to represent a 16-bit value called the Data Pointer. The data pointer is used in operations
regarding external RAM and some instructions involving code memory. Since it is an unsigned two-byte
integer value, it can represent values from 0000h to FFFFh (0 through 65,535 decimal).
          Programming Tip: DPTR is really DPH and DPL taken together as a 16-bit value. In reality, you almost
always have to deal with DPTR one byte at a time. For example, to push DPTR onto the stack you must first push
DPL and then DPH. You can't simply plush DPTR onto the stack. Additionally, there is an instruction to "increment
DPTR." When you execute this instruction, the two bytes are operated upon as a 16-bit value. However, there is no
instruction that decrements DPTR. If you wish to decrement the value of DPTR, you must write your own code to do

        PCON (Power Control, Addresses 87h): The Power Control SFR is used to control the 8051's
power control modes. Certain operation modes of the 8051 allow the 8051 to go into a type of "sleep"
mode which requires much less power. These modes of operation are controlled through PCON.
Additionally, one of the bits in PCON is used to double the effective baud rate of the 8051's serial port.

        TCON (Timer Control, Addresses 88h, Bit-Addressable): The Timer Control SFR is used to
configure and modify the way in which the 8051's two timers operate. This SFR controls whether each of
the two timers is running or stopped and contains a flag to indicate that each timer has overflowed.
Additionally, some non-timer related bits are located in the TCON SFR. These bits are used to configure
the way in which the external interrupts are activated and also contain the external interrupt flags which
are set when an external interrupt has occured.

         TMOD (Timer Mode, Addresses 89h): The Timer Mode SFR is used to configure the mode of
operation of each of the two timers. Using this SFR your program may configure each timer to be a 16-bit
timer, an 8-bit autoreload timer, a 13-bit timer, or two separate timers. Additionally, you may configure the
timers to only count when an external pin is activated or to count "events" that are indicated on an
external pin.
         TL0/TH0 (Timer 0 Low/High, Addresses 8Ah/8Bh): These two SFRs, taken together, represent
timer 0. Their exact behavior depends on how the timer is configured in the TMOD SFR; however, these
timers always count up. What is configurable is how and when they increment in value.

         TL1/TH1 (Timer 1 Low/High, Addresses 8Ch/8Dh): These two SFRs, taken together, represent
timer 1. Their exact behavior depends on how the timer is configured in the TMOD SFR; however, these

        P1 (Port 1, Address 90h, Bit-Addressable): This is input/output port 1. Each bit of this SFR
corresponds to one of the pins on the microcontroller. For example, bit 0 of port 1 is pin P1.0, bit 7 is pin
a value of 0 will bring it to a low level.

        SCON (Serial Control, Addresses 98h, Bit-Addressable): The Serial Control SFR is used to
configure the behavior of the 8051's on-board serial port. This SFR controls the baud rate of the serial
port, whether the serial port is activated to receive data, and also contains flags that are set when a byte
is successfully sent or received.
         Programming Tip: To use the 8051's on-board serial port, it is generally necessary to initialize the following
SFRs: SCON, TCON, and TMOD. This is because SCON controls the serial port. However, in most cases the
program will wish to use one of the timers to establish the serial port's baud rate. In this case, it is necessary to
configure timer 1 by initializing TCON and TMOD.

         SBUF (Serial Control, Addresses 99h): The Serial Buffer SFR is used to send and receive data
via the on-board serial port. Any value written to SBUF will be sent out the serial port's TXD pin. Likewise,
any value which the 8051 receives via the serial port's RXD pin will be delivered to the user program via
SBUF. In other words, SBUF serves as the output port when written to and as an input port when read

        P2 (Port 2, Address A0h, Bit-Addressable): This is input/output port 2. Each bit of this SFR
corresponds to one of the pins on the microcontroller. For example, bit 0 of port 2 is pin P2.0, bit 7 is pin
a value of 0 will bring it to a low level.
own use.

         IE (Interrupt Enable, Addresses A8h): The Interrupt Enable SFR is used to enable and disable
specific interrupts. The low 7 bits of the SFR are used to enable/disable the specific interrupts, where as
the highest bit is used to enable or disable ALL interrupts. Thus, if the high bit of IE is 0 all interrupts are
disabled regardless of whether an individual interrupt is enabled by setting a lower bit.

        P3 (Port 3, Address B0h, Bit-Addressable): This is input/output port 3. Each bit of this SFR
corresponds to one of the pins on the microcontroller. For example, bit 0 of port 3 is pin P3.0, bit 7 is pin
a value of 0 will bring it to a low level.

         IP (Interrupt Priority, Addresses B8h, Bit-Addressable): The Interrupt Priority SFR is used to
specify the relative priority of each interrupt. On the 8051, an interrupt may either be of low (0) priority or
high (1) priority. An interrupt may only interrupt interrupts of lower priority. For example, if we configure
the 8051 so that all interrupts are of low priority except the serial interrupt, the serial interrupt will always
be able to interrupt the system, even if another interrupt is currently executing. However, if a serial
interrupt is executing no other interrupt will be able to interrupt the serial interrupt routine since the serial
interrupt routine has the highest priority.

         PSW (Program Status Word, Addresses D0h, Bit-Addressable): The Program Status Word is
used to store a number of important bits that are set and cleared by 8051 instructions. The PSW SFR
contains the carry flag, the auxiliary carry flag, the overflow flag, and the parity flag. Additionally, the PSW
register contains the register bank select flags which are used to select which of the "R" register banks
are currently selected.
         Programming Tip: If you write an interrupt handler routine, it is a very good idea to always save the PSW
SFR on the stack and restore it when your interrupt is complete. Many 8051 instructions modify the bits of PSW. If
your interrupt routine does not guarantee that PSW is the same upon exit as it was upon entry, your program is
bound to behave rather erradically and unpredictably--and it will be tricky to debug since the behavior will tend not to
make any sense.

        ACC (Accumulator, Addresses E0h, Bit-Addressable): The Accumulator is one of the most-
used SFRs on the 8051 since it is involved in so many instructions. The Accumulator resides as an SFR
at E0h, which means the instruction MOV A,#20h is really the same as MOV E0h,#20h. However, it is a
good idea to use the first method since it only requires two bytes whereas the second option requires
three bytes.

         B (B Register, Addresses F0h, Bit-Addressable): The "B" register is used in two instructions:
the multiply and divide operations. The B register is also commonly used by programmers as an auxiliary
register to temporarily store values.

                                              Other SFRs

          The chart above is a summary of all the     on the 8051), the SFRs SBUF2 and SCON2 have
SFRs that exist in a standard 8051. All derivative    been added. In addition to all the SFRs listed
microcontrollers of the 8051 must support these       above, the DS80C320 also recognizes these two
basic SFRs in order to maintain compatability with    new SFRs as valid and uses their values to
the underlying MSCS51 standard.                       determine the mode of operation of the secondary
          A common practice when semiconductor        serial port. Obviously, these new SFRs have been
firms wish to develop a new 8051 derivative is to     assigned to SFR addresses that were unused in
add additional SFRs to support new functions that     the original 8051. In this manner, new 8051
exist in the new chip.                                derivative chips may be developed which will run
          For example, the Dallas Semiconductor       existing 8051 programs.
DS80C320 is upwards compatible with the 8051.                   Programming Tip: If you write a program that
This means that any program that runs on a            utilizes new SFRs that are specific to a given derivative
standard 8051 should run without modification on      chip and not included in the above SFR list, your
the DS80C320. This means that all the SFRs            program will not run properly on a standard 8051 where
                                                      that SFR does not exist. Thus, only use non-standard
defined above also apply to the Dallas component.     SFRs if you are sure that your program wil only have to
          However, since the DS80C320 provides        run on that specific microcontroller. Likewise, if you write
many new features that the standard 8051 does         code that uses non-standard SFRs and subsequently
not, there must be some way to control and            share it with a third-party, be sure to let that party know
configure     these    new   features.   This    is   that your code is using non-standard SFRs to save them
accomplished by adding additional SFRs to those       the headache of realizing that due to strange behavior at
listed here. For example, since the DS80C320          run-time.
supports two serial ports (as opposed to just one

                                  8051 Tutorial: Basic Registers

                                               The Accumulator

         If you’ve worked with any other assembly           accumulator. More than half of the 8051’s 255
languages you will be familiar with the concept of          instructions manipulate or use the accumulator in
an Accumulator register.                                    some way.
         The Accumulator, as it’s name suggests,                     For example, if you want to add the
is used as a general register to accumulate the             number 10 and 20, the resulting 30 will be stored
results of a large number of instructions. It can           in the Accumulator. Once you have a value in the
hold an 8-bit (1-byte) value and is the most                Accumulator you may continue processing the
versatile register the 8051 has due to the shear            value or you may store it in another register or in
number of instructions that make use of the                 memory.

                                               The "R" registers

         The "R" registers are a set of eight                       After executing this instruction the
registers that are named R0, R1, etc. up to and             Accumulator will contain the value 30.
including R7.                                                       You may think of the "R" registers as very
         These registers are used as auxillary              important auxillary, or "helper", registers. The
registers in many operations. To continue with the          Accumulator alone would not be very useful if it
above example, perhaps you are adding 10 and                were not for these "R" registers.
20. The original number 10 may be stored in the                     The "R" registers are also used to
Accumulator whereas the value 20 may be stored              temporarily store values. For example, let’s say
in, say, register R4. To process the addition you           you want to add the values in R1 and R2 together
would execute the command:                                  and then subtract the values of R3 and R4. One
                                                            way to do this would be:
        ADD A,R4

        ADD A,R4        ;Add the value of R4
        MOV R5,A        ;Store the resulting value temporarily in R5
        ADD A,R2        ;Add the value of R2

        As you can see, we used R5 to                       (R1+R2) - (R3 +R4) but it does illustrate the use of
temporarily hold the sum of R3 and R4. Of course,           the "R" registers as a way to store values
this isn’t the most efficient way to calculate              temporarily.

                                               The "B" Register

         The "B" register is very similar to the            another number, you may store the other number
Accumulator in the sense that it may hold an 8-bit          in "B" and make use of these two instructions.
(1-byte) value.                                                      Aside from the MUL and DIV instructions,
         The "B" register is only used by two 8051          the "B" register is often used as yet another
instructions: MUL AB and DIV AB. Thus, if you               temporary storage register much like a ninth "R"
want to quickly and easily multiply or divide A by          register.

                                          The Data Pointer (DPTR)

         The Data Pointer (DPTR) is the 8051’s              access external memory at the address indicated
only user-accessable 16-bit (2-byte) register. The          by DPTR.
Accumulator, "R" registers, and "B" register are all                 While DPTR is most often used to point to
1-byte values.                                              data in external memory, many programmers often
         DPTR, as the name suggests, is used to             take advantge of the fact that it’s the only true 16-
point to data. It is used by a number of commands           bit register available. It is often used to store 2-
which allow the 8051 to access external memory.             byte values which have nothing to do with memory
When the 8051 accesses external memory it will              locations.

                                           The Program Counter (PC)

         The Program Counter (PC) is a 2-byte               the other hand, if you execute LJMP 2340h you’ve
address which tells the 8051 where the next                 effectively accomplished the same thing.
instruction to execute is found in memory. When                      It is also interesting to note that while you
the 8051 is initialized PC always starts at 0000h           may change the value of PC (by executing a jump
and is incremented each time an instruction is              instruction, etc.) there is no way to read the value
executed. It is important to note that PC isn’t             of PC. That is to say, there is no way to ask the
always incremented by one. Since some                       8051 "What address are you about to execute?"
instructions require 2 or 3 bytes the PC will be            As it turns out, this is not completely true: There is
incremented by 2 or 3 in these cases.                       one trick that may be used to determine the
         The Program Counter is special in that             current value of PC. This trick will be covered in a
there is no way to directly modify it’s value. That is      later chapter.
to say, you can’t do something like PC=2430h. On

                                             The Stack Pointer (SP)

         The Stack Pointer, like all registers except       you immediately push a value onto the stack, the
DPTR and PC, may hold an 8-bit (1-byte) value.              value will be stored in Internal RAM address 08h.
The Stack Pointer is used to indicate where the             This makes sense taking into account what was
next value to be removed from the stack should be           mentioned two paragraphs above: First the 8051
taken from.                                                 will increment the value of SP (from 07h to 08h)
         When you push a value onto the stack, the          and then will store the pushed value at that
8051 first increments the value of SP and then              memory address (08h).
stores the value at the resulting memory location.                   SP is modified directly by the 8051 by six
         When you pop a value off the stack, the            instructions: PUSH, POP, ACALL, LCALL, RET,
8051 returns the value from the memory location             and RETI. It is also used intrinsically whenever an
indicated by SP, and then decrements the value of           interrupt is triggered (more on interrupts later.
SP.                                                         Don’t worry about them for now!).
         This order of operation is important. When
the 8051 is initialized SP will be initialized to 07h. If

                                8051 Tutorial: Addressing Modes

      An "addressing mode" refers to how you            summary, the addressing modes are as follows,
are addressing a given memory location. In              with an example of each:

                 Immediate Addressing                        MOV A,#20h
                 Direct Addressing                           MOV A,30h
                 Indirect Addressing                         MOV A,@R0
                 External Direct                             MOVX A,@DPTR
                 Code Indirect                               MOVC A,@A+DPTR

        Each of these addressing modes provides important flexibility.

                                          Immediate Addressing

        Immediate addressing is so-named                         This     instruction      uses      Immediate
because the value to be stored in memory                Addressing because the Accumulator will be
immediately follows the operation code in memory.       loaded with the value that immediately follows; in
That is to say, the instruction itself dictates what    this case 20 (hexidecimal).
value will be stored in memory.                                  Immediate addressing is very fast since
        For example, the instruction:                   the value to be loaded is included in the
                                                        instruction. However, since the value to be loaded
        MOV A,#20h                                      is fixed at compile-time it is not very flexible.

                                            Direct Addressing

         Direct addressing is so-named because                   Also, it is important to note that when
the value to be stored in memory is obtained by         using direct addressing any instruction which
directly retrieving it from another memory location.    refers to an address between 00h and 7Fh is
For example:                                            referring to Internal Memory. Any instruction which
                                                        refers to an address between 80h and FFh is
        MOV A,30h                                       referring to the SFR control registers that control
                                                        the 8051 microcontroller itself.
         This instruction will read the data out of              The obvious question that may arise is, "If
Internal RAM address 30 (hexidecimal) and store it      direct addressing an address from 80h through
in the Accumulator.                                     FFh refers to SFRs, how can I access the upper
         Direct addressing is generally fast since,     128 bytes of Internal RAM that are available on the
although the value to be loaded isn’t included in       8052?" The answer is: You can’t access them
the instruction, it is quickly accessable since it is   using direct addressing. As stated, if you directly
stored in the 8051’s Internal RAM. It is also much      refer to an address of 80h through FFh you will be
more flexible than Immediate Addressing since the       referring to an SFR. However, you may access the
value to be loaded is whatever is found at the          8052’s upper 128 bytes of RAM by using the next
given address--which may be variable.                   addressing mode, "indirect addressing."

                                           Indirect Addressing

        Indirect addressing is a very powerful          Internal RAM which is found at the address
addressing mode which in many cases provides            indicated by R0.
an exceptional level of flexibility. Indirect                    For example, let’s say R0 holds the value
addressing is also the only way to access the extra     40h and Internal RAM address 40h holds the value
128 bytes of Internal RAM found on an 8052.             67h. When the above instruction is executed the
        Indirect addressing appears as follows:         8051 will check the value of R0. Since R0 holds
                                                        40h the 8051 will get the value out of Internal RAM
        MOV A,@R0                                       address 40h (which holds 67h) and store it in the
                                                        Accumulator. Thus, the Accumulator ends up
        This instruction causes the 8051 to             holding 67h.
analyze the value of the R0 register. The 8051 will              Indirect addressing always refers to
then load the accumulator with the value from           Internal RAM; it never refers to an SFR. Thus, in a
                                                        prior example we mentioned that SFR 99h can be
used to write a value to the serial port. Thus one            solution to write the value ‘1’ to the serial port:
may think that the following would be a valid
        MOV R0,#99h      ;Load the address of the serial port
        MOV @R0,#01h     ;Send 01 to the serial port -- WRONG!!

         This is not valid. Since indirect addressing         two instructions would produce an undefined result
always refers to Internal RAM these two                       since the 8051 only has 128 bytes of Internal
instructions would write the value 01h to Internal            RAM.
RAM address 99h on an 8052. On an 8051 these

                                                  External Direct

         External Memory is accessed using a                          As you can see, both commands utilize
suite of instructions which use what I call "External         DPTR. In these instructions, DPTR must first be
Direct" addressing. I call it this because it appears         loaded with the address of external memory that
to be direct addressing, but it is used to access             you wish to read or write. Once DPTR holds the
external memory rather than internal memory.                  correct external memory address, the first
         There are only two commands that use                 command will move the contents of that external
External Direct addressing mode:                              memory address into the Accumulator. The
                                                              second command will do the opposite: it will allow
        MOVX A,@DPTR
                                                              you to write the value of the Accumulator to the
        MOVX @DPTR,A
                                                              external memory address pointed to by DPTR.

                                                External Indirect

        External memory can also be accessed                  address in External RAM. Since the value of @R0
using a form of indirect addressing which I call              can only be 00h through FFh the project would
External Indirect addressing. This form of                    effectively be limited to 256 bytes of External
addressing is usually only used in relatively small           RAM.       There      are     relatively     simple
projects that have a very small amount of external            hardware/software tricks that can be implemented
RAM. An example of this addressing mode is:                   to access more than 256 bytes of memory using
                                                              External Indirect addressing; however, it is usually
        MOVX @R0,A                                            easier to use External Direct addressing if your
                                                              project has more than 256 bytes of External RAM.
        Once again, the value of R0 is first read
and the value of the Accumulator is written to that

                                   8051 Tutorial: Program Flow

         When an 8051 is first initialized, it resets   modify the value of the PC; specifically, conditional
the PC to 0000h. The 8051 then begins to execute        branching instructions, direct jumps and calls, and
instructions sequentially in memory unless a            "returns" from subroutines. Additionally, interrupts,
program instruction causes the PC to be otherwise       when enabled, can cause the program flow to
altered. There are various instructions that can        deviate from it’s otherwise sequential scheme.

                                          Conditional Branching

          The 8051 contains a suite of instructions     execution continues, as usual, with the NOP
which, as a group, are referred to as "conditional      instruction which follows.
branching" instructions. These instructions cause                Conditional branching is really the
program execution to follow a non-sequential path       fundamental building block of program logic since
if a certain condition is true.                         all "decisions" are accomplished by using
          Take, for example, the JB instruction. This   conditional branching. Conditional branching can
instruction means "Jump if Bit Set." An example of      be thought of as the "IF...THEN" structure in 8051
the JB instruction might be:                            assembly language.
                                                                 An important note worth mentioning about
                 JB 45h,HELLO
                                                        conditional branching is that the program may only
        HELLO:                                          branch to instructions located withim 128 bytes
                                                        prior to or 127 bytes following the address which
        In this case, the 8051 will analyze the         follows the conditional branch instruction. This
contents of bit 45h. If the bit is set program          means that in the above example the label HELLO
execution will jump immediately to the label            must be within +/- 128 bytes of the memory
HELLO, skipping the NOP instruction. If the bit is      address which contains the conditional branching
not set the conditional branch fails and program        instruction.

                                               Direct Jumps

         While conditional branching is extremely                It is worth mentioning that, aside from
important, it is often necessary to make a direct       LJMP, there are two other instructions which
call to a given memory location without basing it       cause a direct jump to occur: the SJMP and AJMP
on a given logical decision. This is equivalent to      commands. Functionally, these two commands
saying "Goto" in BASIC. In this case you want the       perform the exact same function as the LJMP
program flow to continue at a given memory              command--that is to say, they always cause
address without considering any conditions.             program flow to continue at the address indicated
         This is accomplished in the 8051 using         by the command. However, SJMP and AJMP differ
"Direct Jump and Call" instructions. As illustrated     in the following ways:
in the last paragraph, this suite of instructions
causes program flow to change unconditionally.          •   The SJMP command, like the conditional
         Consider the example:                              branching instructions, can only jump to an
                                                            address within +/- 128 bytes of the SJMP
              LJMP NEW_ADDRESS
              .                                         •   The AJMP command can only jump to an
              .                                             address that is in the same 2k block of
        NEW_ADDRESS:                                        memory as the AJMP command. That is to
                                                            say, if the AJMP command is at code memory
         The LJMP instruction in this example               location 650h, it can only do a jump to
means "Long Jump." When the 8051 executes this              addresses 0000h through 07FFh (0 through
instruction the PC is loaded with the address of            2047, decimal).
NEW_ADDRESS          and     program    execution
continues sequentially from there.                              You may be asking yourself, "Why would I
         The obvious difference between the Direct      want to use the SJMP or AJMP command which
Jump and Call instructions and the conditional          have restrictions as to how far they can jump if
branching is that with Direct Jumps and Calls           they do the same thing as the LJMP command
program flow always changes. With conditional           which can jump anywhere in memory?" The
branching program flow only changes if a certain        answer is simple: The LJMP command requires
condition is true.                                      three bytes of code memory whereas both the
                                                        SJMP and AJMP commands require only two.
Thus, if you are developing an application that has     program I saved 150 bytes and was able to meet
memory restrictions you can often save quite a bit      my 2048 byte memory restriction.
of memory using the 2-byte AJMP/SJMP                              NOTE: Some quality assemblers will actually
instructions instead of the 3-byte instruction.         do the above conversion for you automatically. That is,
          Recently, I wrote a program that required     they’ll automatically change your LJMPs to SJMPs
2100 bytes of memory but I had a memory                 whenever possible. This is a nifty and very powerful
                                                        capability that you may want to look for in an assembler
restriction of 2k (2048 bytes). I did a                 if you plan to develop many projects that have relatively
search/replace changing all LJMPs to AJMPs and          tight memory restrictions.
the program shrunk downto 1950 bytes. Thus,
without changing any logic whatsoever in my

                                                Direct Calls

         Another operation that will be familiar to     Program Counter onto the stack and then
seasoned programmers is the LCALL instruction.          continues executing code at the address indicated
This is similar to a "Gosub" command in Basic.          by the LCALL instruction.
         When the 8051 executes an LCALL
instruction it immediately pushes the current

                                          Returns from Routines

         Another structure that can cause program                The RET command is direct in the sense
flow to change is the "Return from Subroutine"          that it always changes program flow without
instruction, known as RET in 8051 Assembly              basing it on a condition, but is variable in the
Language.                                               sense that where program flow continues can be
         The RET instruction, when executed,            different each time the RET instruction is executed
returns to the address following the instruction that   depending on from where the subroutine was
called the given subroutine. More accurately, it        called originally.
returns to the address that is stored on the stack.


        An interrupt is a special feature which         handler. The interrupt handler performs whatever
allows the 8051 to provide the illusion of "multi-      special functions are required to handle the event
tasking," although in reality the 8051 is only doing    and then returns control to the 8051 at which point
one thing at a time. The word "interrupt" can often     program execution continues as if it had never
be subsituted with the word "event."                    been interrupted.
        An interrupt is triggered whenever a                     The topic of interrupts is somewhat tricky
corresponding event occurs. When the event              and very important. For that reason, an entire
occurs, the 8051 temporarily puts "on hold" the         chapter will be dedicated to the topic. For now,
normal execution of the program and executes a          suffice it to say that Interrupts can cause program
special section of code referred to as an interrupt     flow to change.


         In order to understand--and better make                 This means that the 8051 can execute
use of--the 8051, it is necessary to understand         921,583 single-cycle instructions per second.
some underlying information concerning timing.          Since a large number of 8051 instructions are
         The 8051 operates based on an external         single-cycle instructions it is often considered that
crystal. This is an electrical device which, when       the 8051 can execute roughly 1 million instructions
energy is applied, emits pulses at a fixed              per second, although in reality it is less--and,
frequency. One can find crystals of virtually any       depending on the instructions being used, an
frequency      depending     on     the   application   estimate of about 600,000 instructions per second
requirements. When using an 8051, the most              is more realistic.
common crystal frequencies are 12 megahertz and                  For example, if you are using exclusively
11.059 megahertz--with 11.059 being much more           2-cycle instructions you would find that the 8051
common. Why would anyone pick such an odd-ball          would execute 460,791 instructions per second.
frequency? There’s a real reason for it--it has to do   The 8051 also has two really slow instructions that
with generating baud rates and we’ll talk more          require a full 4 cycles to execute--if you were to
about it in the Serial Communication chapter. For       execute nothing but those instructions you’d find
the remainder of this discussion we’ll assume that      performance to be about 230,395 instructions per
we’re using an 11.059Mhz crystal.                       second.
         Microcontrollers (and many other electrical             It is again important to emphasize that not
systems) use crystals to syncrhronize operations.       all instructions execute in the same amount of
The 8051 uses the crystal for precisely that: to        time. The fastest instructions require one machine
synchronize it’s operation. Effectively, the 8051       cycle (12 crystal pulses), many others require two
operates using what are called "machine cycles."        machine cycles (24 crystal pulses), and the two
A single machine cycle is the minimum amount of         very slow math operations require four machine
time in which a single 8051 instruction can be          cycles (48 crystal pulses).
executed. although many instructions take multiple                NOTE: Many 8051 derivative chips change
cycles.                                                 instruction timing. For example, many optimized
         A cycle is, in reality, 12 pulses of the       versions of the 8051 execute instructions in 4 oscillator
crystal. That is to say, if an instruction takes one    cycles instead of 12; such a chip would be effectively 3
                                                        times faster than the 8051 when used with the same
machine cycle to execute, it will take 12 pulses of     11.059 Mhz crystal.
the crystal to execute. Since we know the crystal is             Since all the instructions require different
pulsing 11,059,000 times per second and that one        amounts of time to execute a very obvious
machine cycle is 12 pulses, we can calculate how        question comes to mind: How can one keep track
many instruction cycles the 8051 can execute per        of time in a time-critical application if we have no
second:                                                 reference to time in the outside world?
        11,059,000 / 12 = 921,583
                                                                 Luckily, the 8051 includes timers which
                                                        allow us to time events with high precision--which
                                                        is    the    topic     of    the     next    chapter.

                                        8051 Tutorial: Timers

        The 8051 comes equipped with two                3) Generating baud rates for the serial port.
and configured individually. The 8051 timers have               The three timer uses are distinct so we will
three general functions:                                talk about each of them separately. The first two
1) Keeping time and/or calculating the amount of        uses will be discussed in this chapter while the use
    time between events,                                of timers for baud rate generation will be
2) Counting the events themselves, or                   discussed in the chapter relating to serial ports.

                                        How does a timer count?

        How does a timer count? The answer to                     Programming Tip: Some derivative chips
this question is very simple: A timer always counts     actually allow the program to configure whether the
up. It doesn’t matter whether the timer is being        timers count up or down. However, since this option only
used as a timer, a counter, or a baud rate              exists on some derivatives it is beyond the scope of this
                                                        tutorial which is aimed at the standard 8051. It is only
generator: A timer is always incremented by the         mentioned here in the event that you absolutely need a
microcontroller.                                        timer to count backwards, you will know that you may be
                                                        able to find an 8051-compatible microcontroller that
                                                        does it.

                                    USING TIMERS TO MEASURE TIME

         Obviously, one of the primary uses of          times. How can you wait "half of a time?" You
timers is to measure time. We will discuss this use     can’t. So we come to another important
of timers first and will subsequently discuss the       calculation.
use of timers to count events. When a timer is                   Let’s say we want to know how many
used to measure time it is also called an "interval     times the timer will be incremented in .05 seconds.
timer" since it is measuring the time of the interval   We can do simple multiplication: .05 * 921,583 =
between two events.                                     46,079.15.
         How long does a timer take to count?
         First, it’s worth mentioning that when a                This tells us that it will take .05 seconds
timer is in interval timer mode (as opposed to          (1/20th of a second) to count from 0 to 46,079.
event counter mode) and correctly configured, it        Actually, it will take it .049999837 seconds--so
will increment by 1 every machine cycle. As you         we’re off by .000000163 seconds--however, that’s
will recall from the previous chapter, a single         close enough for government work. Consider that
machine cycle consists of 12 crystal pulses. Thus       if you were building a watch based on the 8051
a running timer will be incremented:                    and made the above assumption your watch would
                                                        only gain about one second every 2 months.
        11,059,000 / 12 = 921,583                       Again, I think that’s accurate enough for most
                                                        applications--I wish my watch only gained one
         921,583 times per second. Unlike               second every two months!
instructions--some of which require 1 machine                    Obviously, this is a little more useful. If you
cycle, others 2, and others 4--the timers are           know it takes 1/20th of a second to count from 0 to
consistent: They will always be incremented once        46,079 and you want to execute some event every
per machine cycle. Thus if a timer has counted          second you simply wait for the timer to count from
from 0 to 50,000 you may calculate:                     0 to 46,079 twenty times; then you execute your
                                                        event, reset the timers, and wait for the timer to
        50,000 / 921,583 = .0542                        count up another 20 times. In this manner you will
                                                        effectively execute your event once per second,
         .0542 seconds have passed. In plain            accurate to within thousandths of a second.
English, about half of a tenth of a second, or one-              Thus, we now have a system with which to
twentieth of a second.                                  measure time. All we need to review is how to
         Obviously it’s not very useful to know         control the timers and initialize them to provide us
.0542 seconds have passed. If you want to               with the information we need.
execute an event once per second you’d have to
wait for the timer to count from 0 to 50,000 18.45

                                                   Timer SFRs

        As mentioned before, the 8051 has two                        We’ve given SFRs names to make it
timers which each function essentially the same             easier to refer to them, but in reality an SFR has a
way. One timer is TIMER0 and the other is                   numeric address. It is often useful to know the
TIMER1. The two timers share two SFRs (TMOD                 numeric address that corresponds to an SFR
and TCON) which control the timers, and each                name. The SFRs relating to timers are:
timer also has two SFRs dedicated solely to itself
(TH0/TL0 and TH1/TL1).

                        SFR Name                   Description               SFR Address
                            TH0                  Timer 0 High Byte                 8Ch
                            TL0                  Timer 0 Low Byte                  8Ah
                            TH1                  Timer 1 High Byte                 8Dh
                            TL1                  Timer 1 Low Byte                  8Bh
                           TCON                    Timer Control                   88h
                           TMOD                     Timer Mode                     89h

       When you enter the name of an SFR into               When Timer 0 has the value 1000, TH0 will hold
an assembler, it internally converts it to a number.        the high byte of the value (3 decimal) and TL0 will
For example, the command:                                   contain the low byte of the value (232 decimal).
                                                            Reviewing low/high byte notation, recall that you
        MOV TH0,#25h                                        must multiply the high byte by 256 and add the low
                                                            byte to calculate the final value. That is to say:
        moves the value 25h into the TH0 SFR.
However, since TH0 is the same as SFR address                         TH0 * 256 + TL0 = 1000
8Ch this command is equivalent to:                                    3 * 256 + 232 = 1000

        MOV 8Ch,#25h                                                Timer 1 works the exact same way, but it’s
                                                            SFRs are TH1 and TL1.
         Now, back to the timers. Timer 0 has two                   Since there are only two bytes devoted to
SFRs dedicated exclusively to itself: TH0 and TL0.          the value of each timer it is apparent that the
Without making things too complicated to start off          maximum value a timer may have is 65,535. If a
with, you may just think of this as the high and low        timer contains the value 65,535 and is
byte of the timer. That is to say, when Timer 0 has         subsequently incremented, it will reset--or
a value of 0, both TH0 and TL0 will contain 0.              overflow--back to 0.

                                                 The TMOD SFR

         Let’s first talk about our first control SFR:      high four bits (bits 4 through 7) relate to Timer 1
TMOD (Timer Mode). The TMOD SFR is used to                  whereas the low four bits (bits 0 through 3)
control the mode of operation of both timers. Each          perform the exact same functions, but for timer 0.
bit of the SFR gives the microcontroller specific                   The individual bits of TMOD have the
information concerning how to run a timer. The              following functions:

 Bit     Name                                    Explanation of Function                                       Timer
  7      GATE1                                                                                                   1
                    clear the timer will run regardless of the state of INT1.
  6       C/T1                                                                                                   1
                    the timer will be incremented every machine cycle.
                     Timer mode bit (see below)
  5       T1M1                                                                                                   1
                    Timer mode bit (see below)
  4       T1M0                                                                                                   1
  3      GATE0                                                                                                   0
                    clear the timer will run regardless of the state of INT0.
  2       C/T0                                                                                                   0
                    the timer will be incremented every machine cycle.
                     Timer mode bit (see below)
  1       T0M1                                                                                                   0
                    Timer mode bit (see below)
  0       T0M0                                                                                                   0

        As you can see in the above chart, four            mode of operation. The modes of operation are:
bits (two for each timer) are used to specify a

                           TxM1 TxM0 Timer Mode             Description of Mode
                             0       0             0       13-bit Timer.
                             0       1             1       16-bit Timer
                             1       0             2       8-bit auto-reload
                             1       1             3       Split timer mode

                                         13-bit Time Mode (mode 0)

         Timer mode "0" is a 13-bit timer. This is a       This also means, in essence, the timer can only
relic that was kept around in the 8051 to maintain         contain 8192 values. If you set a 13-bit timer to 0,
compatability with it’s predecesor, the 8048.              it will overflow back to zero 8192 machine cycles
Generally the 13-bit timer mode is not used in new         later.
development.                                                         Again, there is very little reason to use this
         When the timer is in 13-bit mode, TLx will        mode and it is only mentioned so you won’t be
count from 0 to 31. When TLx is incremented from           surprised if you ever end up analyzing archaeic
31, it will "reset" to 0 and increment THx. Thus,          code which has been passed down through the
effectively, only 13 bits of the two timer bytes are       generations (a generation in a programming shop
being used: bits 0-4 of TLx and bits 0-7 of THx.           is often on the order of about 3 or 4 months).

                                         16-bit Time Mode (mode 1)

        Timer mode "1" is a 16-bit timer. This is a        THx to be incremented by 1. Since this is a full 16-
very commonly used mode. It functions just like            bit timer, the timer may contain up to 65536
13-bit mode except that all 16 bits are used. TLx          distinct values. If you set a 16-bit timer to 0, it will
is incremented from 0 to 255. When TLx is                  overflow back to 0 after 65,536 machine cycles.
incremented from 255, it resets to 0 and causes

                                             8-bit Time Mode (mode 2)

         Timer mode "2" is an 8-bit auto-reload            0 (as in the case of modes 0 and 1), it will be reset
mode. What is that, you may ask? Simple. When a            to the value stored in THx.
timer is in mode 2, THx holds the "reload value"                    For example, let’s say TH0 holds the value
and TLx is the timer itself. Thus, TLx starts              FDh and TL0 holds the value FEh. If we were to
counting up. When TLx reaches 255 and is                   watch the values of TH0 and TL0 for a few
subsequently incremented, instead of resetting to          machine cycles this is what we’d see:

                                 Machine Cycle         TH0 Value      TL0 Value
                                         1               FDh             FEh
                                         2               FDh             FFh
                                         3               FDh             FDh
                                         4               FDh             FEh
                                         5               FDh             FFh
                                         6               FDh             FDh
                                         7               FDh             FEh

        As you can see, the value of TH0 never             check the value and/or to reload it. When you use
changed. In fact, when you use mode 2 you                  mode 2 the microcontroller takes care of this for
almost always set THx to a known value and TLx             you. Once you’ve configured a timer in mode 2
is the SFR that is constantly incremented.                 you don’t have to worry about checking to see if
        What’s the benefit of auto-reload mode?            the timer has overflowed nor do you have to worry
Perhaps you want the timer to always have a                about resetting the value--the microcontroller
value from 200 to 255. If you use mode 0 or 1,             hardware will do it all for you.
you’d have to check in code to see if the timer had                The auto-reload mode is very commonly
overflowed and, if so, reset the timer to 200. This        used for establishing a baud rate which we will talk
takes precious instructions of execution time to           more about in the Serial Communications chapter.

                                        Split Timer Mode (mode 3)

         Timer mode "3" is a split-timer mode.          stop the real timer 1 since the bits that do that are
When Timer 0 is placed in mode 3, it essentially        now linked to TH0. The real timer 1, in this case,
becomes two separate 8-bit timers. That is to say,      will be incremented every machine cycle no matter
Timer 0 is TL0 and Timer 1 is TH0. Both timers          what.
count from 0 to 255 and overflow back to 0. All the               The only real use I can see of using split
bits that are related to Timer 1 will now be tied to    timer mode is if you need to have two separate
TH0.                                                    timers and, additionally, a baud rate generator. In
         While Timer 0 is in split mode, the real       such case you can use the real Timer 1 as a baud
Timer 1 (i.e. TH1 and TL1) can be put into modes        rate generator and use TH0/TL0 as two separate
0, 1 or 2 normally--however, you may not start or       timers.

                                              The TCON SFR

        Finally, there’s one more SFR that              information about them. The TCON SFR has the
controls the two timers and provides valuable           following structure:

         Bit Name Bit Addres                            Explanation of Function                                  Timer
          7    TF1        8Fh                                                                                      1
          6    TR1        8Eh                                                                                      1
                                   clear Timer 1 is off.
          5    TF0        8Dh                                                                                      0
          4    TR0        8Ch                                                                                      0
                                   clear Timer 0 is off.

         As you may notice, we’ve only defined 4 of             or, since the SFR is bit-addressable, you
the 8 bits. That’s because the other 4 bits of the      could just execute the command:
SFR don’t have anything to do with timers--they
have to do with Interrupts and they will be                        SETB TF1
discussed in the chapter that addresses interrupts.
         A new piece of information in this chart is             This has the benefit of setting the high bit
the column "bit address." This is because this SFR      of TCON without changing the value of any of the
is "bit-addressable." What does this mean? It           other bits of the SFR. Usually when you start or
means if you want to set the bit TF1--which is the      stop a timer you don’t want to modify the other
highest bit of TCON--you could execute the              values in TCON, so you take advantage of the fact
command:                                                that the SFR is bit-addressable.
        MOV TCON, #80h

                                            Initializing a Timer

          Now that we’ve discussed the timer-           on is bit 0 of TMOD. Thus to initialize the timer we
related SFRs we are ready to write code that will       execute the instruction:
initialize the timer and start it running.
          As you’ll recall, we first must decide what              MOV TMOD,#01h
want a 16-bit timer that runs continuously; that is              Timer 0 is now in 16-bit timer mode.
to say, it is not dependent on any external pins.       However, the timer is not running. To start the
          We must first initialize the TMOD SFR.        timer running we must set the TR0 bit We can do
Since we are working with timer 0 we will be using      that by executing the instruction:
the lowest 4 bits of TMOD. The first two bits,
                                                                   SETB TR0
GATE0 and C/T0 are both 0 since we want the
timer to be independent of the external pins. 16-bit
mode is timer mode 1 so we must clear T0M1 and                   Upon executing these two instructions
set T0M0. Effectively, the only bit we want to turn     timer 0 will immediately begin counting, being
                                                        incremented once every machine cycle (every 12
                                                        crystal pulses).

                                                  Reading the Timer

        There are two common ways of reading                     the actual value of the timer as a 16-bit number, or
the value of a 16-bit timer; which you use depends               you may simply detect when the timer has
on your specific application. You may either read                overflowed.

                                           Reading the value of a Timer

either 8-bit AutoReload mode or in split timer                              REPEAT: MOV A,TH0
                                                                                    MOV R0,TL0
mode--then reading the value of the timer is                                        CJNE A,TH0,REPEAT
simple. You simply read the 1-byte value of the
timer and you’re done.                                                     In this case, we load the accumulator with
         However, if you’re dealing with a 13-bit or             the high byte of Timer 0. We then load R0 with the
16-bit timer the chore is a little more complicated.             low byte of Timer 0. Finally, we check to see if the
Consider what would happen if you read the low                   high byte we read out of Timer 0--which is now
byte of the timer as 255, then read the high byte of             stored in the Accumulator--is the same as the
the timer as 15. In this case, what actually                     current Timer 0 high byte. If it isn’t it means we’ve
happened was that the timer value was 14/255                     just "rolled over" and must reread the timer’s
(high byte 14, low byte 255) but you read 15/255.                value--which we do by going back to REPEAT.
Why? Because you read the low byte as 255. But                   When the loop exits we will have the low byte of
when you executed the next instruction a small                   the timer in R0 and the high byte in the
amount of time passed--but enough for the timer to               Accumulator.
increment again at which time the value rolled over                        Another much simpler alternative is to
from 14/255 to 15/0. But in the process you’ve                   simply turn off the timer run bit (i.e. CLR TR0),
read the timer as being 15/255. Obviously there’s                read the timer value, and then turn on the timer
a problem there.                                                 run bit (i.e. SETB TR0). In that case, the timer isn’t
         The solution? It’s not too tricky, really. You          running so no special tricks are necessary. Of
read the high byte of the timer, then read the low               course, this implies that your timer will be stopped
byte, then read the high byte again. If the high byte            for a few machine cycles. Whether or not this is
read the second time is not the same as the high                 tolerable depends on your specific application.
byte read the first time you repeat the cycle. In
code, this would appear as:

                                             Detecting Timer Overflow

         Often it is necessary to just know that the                     We can use this approach to cause the
timer has reset to 0. That is to say, you are not                program to execute a fixed delay. As you’ll recall,
particularly interest in the value of the timer but              we calculated earlier that it takes the 8051 1/20th
rather you are interested in knowing when the                    of a second to count from 0 to 46,079. However,
timer has overflowed back to 0.                                  the TFx flag is set when the timer overflows back
         Whenever a timer overflows from it’s                    to 0. Thus, if we want to use the TFx flag to
highest value back to 0, the microcontroller                     indicate when 1/20th of a second has passed we
automatically sets the TFx bit in the TCON                       must set the timer initially to 65536 less 46079, or
register. This is useful since rather than checking              19,457. If we set the timer to 19,457, 1/20th of a
the exact value of the timer you can just check if               second later the timer will overflow. Thus we come
the TFx bit is set. If TF0 is set it means that timer 0          up with the following code to execute a pause of
has overflowed; if TF1 is set it means that timer 1              1/20th of a second:
has overflowed.

        SETB TR0          ;Make Timer 0 start counting

          In the above code the first two lines                  assemblers, the address of the current instruction.
initialize the Timer 0 starting value to 19,457. The             Thus as long as the timer has not overflowed and
next two instructions configure timer 0 and turn it              the TF0 bit has not been set the program will keep
on. Finally, the last instruction JNB TF0,$, reads               executing this same instruction. After 1/20th of a
"Jump, if TF0 is not set, back to this same                      second timer 0 will overflow, set the TF0 bit, and
instruction." The "$" operand means, in most                     program execution will then break out of the loop.

                                          Timing the length of events

          The 8051 provides another cool toy that              this bit because we wanted the timer to run
can be used to time the length of events.                      regardless of the state of the external pins.
          For example, let's say we're trying to save          However, now it would be nice if an external pin
electricity in the office and we're interested in how          could control whether the timer was running or not.
long a light is turned on each day. When the light             It can. All we need to do is connect the lightswitch
is turned on, we want to measure time. When the                to pin INT0 (P3.2) on the 8051 and set the bit
light is turned off we don't. One option would be to           GATE0. When GATE0 is set Timer 0 will only run
connect the lightswitch to one of the pins,                    if P3.2 is high. When P3.2 is low (i.e., the
constantly read the pin, and turn the timer on or off          lightswitch is off) the timer will automatically be
based on the state of that pin. While this would               stopped.
work fine, the 8051 provides us with an easier                          Thus, with no control code whatsoever,
method of accomplishing this.                                  the external pin P3.2 can control whether or not
          Looking again at the TMOD SFR, there is              our timer is running or not.
a bit called GATE0. So far we've always cleared

                                  USING TIMERS AS EVENT COUNTERS

         We've discussed how a timer can be used               road. We could attach this sensor to one of the
for the obvious purpose of keeping track of time.              8051's I/O lines and constantly monitor it,
However, the 8051 also allows us to use the                    detecting when it pulsed high and then
timers to count events.                                        incrementing our counter when it went back to a
         How can this be useful? Let's say you had             low state. This is not terribly difficult, but requires
a sensor placed across a road that would send a                some code. Let's say we hooked the sensor to
pulse every time a car passed over it. This could              P1.0; the code to count cars passing would look
be used to determine the volume of traffic on the              something like this:


         As you can see, it's only three lines of              timer 0--the value of timer 0 will be the number of
code. But what if you need to be doing other                   cars that have passed.
processing at the same time? You can't be stuck                         So what exactly is an event? What does
in the JNB P1.0,$ loop waiting for a car to pass if            timer 0 actually "count?" Speaking at the electrical
you need to be doing other things. Of course,                  level, the 8051 counts 1-0 transitions on the P3.4
there are ways to get around even this limitation              line. This means that when a car first runs over our
but the code quickly becomes big, complex, and                 sensor it will raise the input to a high ("1")
ugly.                                                          condition. At that point the 8051 will not count
         Luckily, since the 8051 provides us with a            anything since this is a 0-1 transition. However,
way to use the timers to count events we don't                 when the car has passed the sensor will fall back
have to bother with it. It is actually painfully easy.         to a low ("0") state. This is a 1-0 transition and at
We only have to configure one additional bit.                  that instant the counter will be incremented by 1.
         Let's say we want to use Timer 0 to count                      It is important to note that the 8051 checks
the number of cars that pass. If you look back to              the P3.4 line each instruction cycle (12 clock
the bit table for the TCON SFR you will there is a             cycles). This means that if P3.4 is low, goes high,
bit called "C/T0"--it's bit 2 (TCON.2). Reviewing              and goes back low in 6 clock cycles it will probably
the explanation of the bit we see that if the bit is           not be detected by the 8051. This also means the
clear then timer 0 will be incremented every                   8051 event counter is only capable of counting
machine cycle. This is what we've already used to              events that occur at a maximum of 1/24th the rate
measure time. However, if we set C/T0 timer 0 will             of the crystal frequency. That is to say, if the
monitor the P3.4 line. Instead of being                        crystal frequency is 12.000 Mhz it can count a
incremented every machine cycle, timer 0 will                  maximum of 500,000 events per second (12.000
count events on the P3.4 line. So in our case we               Mhz * 1/24 = 500,000). If the event being counted
simply connect our sensor to P3.4 and let the 8051             occurs more than 500,000 times per second it will
do the work. Then, when we want to know how                    not be able to be accurately counted by the 8051.
many cars have passed, we just read the value of

                                 8051 Tutorial: Serial Communication

         One of the 8051’s many powerful features                         However, we do not have to do this.
is it’s integrated UART, otherwise known as a                   Instead, we simply need to configure the serial
serial port. The fact that the 8051 has an                      port’s operation mode and baud rate. Once
integrated serial port means that you may very                  configured, all we have to do is write to an SFR to
easily read and write values to the serial port. If it          write a value to the serial port or read the same
were not for the integrated serial port, writing a              SFR to read a value from the serial port. The 8051
byte to a serial line would be a rather tedious                 will automatically let us know when it has finished
process requring turning on and off one of the I/O              sending the character we wrote and will also let us
lines in rapid succession to properly "clock out"               know whenever it has received a byte so that we
each individual bit, including start bits, stop bits,           can process it. We do not have to worry about
and parity bits.                                                transmission at the bit level--which saves us quite
                                                                a bit of coding and processing time.

                                             Setting the Serial Port Mode

         The first thing we must do when using the                     First, let’s present the "Serial Control"
8051’s integrated serial port is, obviously,                    (SCON) SFR and define what each bit of the SFR
configure it. This lets us tell the 8051 how many               represents:
and how the baud rate will be determined.

             Bit      Name      Bit Addres                     Explanation of Function
                                               Serial port mode bit 0
              7       SM0          9Fh
                                               Serial port mode bit 1.
              6       SM1          9Eh
                                               Mutliprocessor Communications Enable (explained later)
              5       SM2          9Dh
                                                Receiver Enable. This bit must be set in order to receive
              4       REN          9Ch
                                                Transmit bit 8. The 9th bit to transmit in mode 2 and 3.
              3       TB8          9Bh
                                               Receive bit 8. The 9th bit received in mode 2 and 3.
              2       RB8          9Ah
                                                Transmit Flag. Set when a byte has been completely
              1        TI          99h
                                                Receive Flag. Set when a byte has been completely
              0        RI          98h


            SM0       SM1       Serial Mode       Explanation                Baud Rate
                  0         0            0         8-bit Shift Register      Oscillator / 12
                  0         1            1         8-bit UART                Set by Timer 1 (*)
                  1         0            2         9-bit UART                Oscillator / 32 (*)
                  1         1            3         9-bit UART                Set by Timer 1 (*)

         Note: The baud rate indicated in this table is         rate will be calculated. In modes 0 and 2 the baud
doubled if PCON.7 (SMOD) is set.                                rate is fixed based on the oscillator’s frequency. In
         The SCON SFR allows us to configure the                modes 1 and 3 the baud rate is variable based on
Serial Port. Thus, we’ll go through each bit and                how often Timer 1 overflows. We’ll talk more about
review it’s function. The first four bits (bits 4               the various Serial Modes in a moment.
through 7) are configuration bits.                                        The next bit, SM2, is a flag for
         Bits SM0 and SM1 let us set the serial                 "Multiprocessor      communication."       Generally,
mode to a value between 0 and 3, inclusive. The                 whenever a byte has been received the 8051 will
four modes are defined in the chart immediately                 set the "RI" (Receive Interrupt) flag. This lets the
above. As you can see, selecting the Serial Mode                program know that a byte has been received and
selects the mode of operation (8-bit/9-bit, UART or             that it needs to be processed. However, when
Shift Register) and also determines how the baud                SM2 is set the "RI" flag will only be triggered if the
9th bit received was a "1". That is to say, if SM2 is       but on the reception side. When a byte is received
set and a byte is received whose 9th bit is clear,          in modes 2 or 3, a total of nine bits are received. In
the RI flag will never be set. This can be useful in        this case, the first eight bits received are the data
certain advanced serial applications. For now it is         of the serial byte received and the value of the
safe to say that you will almost always want to             ninth bit received will be placed in RB8.
clear this bit so that the flag is set upon reception                 TI means "Transmit Interrupt." When a
of any character.                                           program writes a value to the serial port, a certain
          The next bit, REN, is "Receiver Enable."          amount of time will pass before the individual bits
This bit is very straightforward: If you want to            of the byte are "clocked out" the serial port. If the
receive data via the serial port, set this bit. You will    program were to write another byte to the serial
almost always want to set this bit.                         port before the first byte was completely output,
          The last four bits (bits 0 through 3) are         the data being sent would be garbled. Thus, the
operational bits. They are used when actually               8051 lets the program know that it has "clocked
sending and receiving data--they are not used to            out" the last byte by setting the TI bit. When the TI
configure the serial port.                                  bit is set, the program may assume that the serial
          The TB8 bit is used in modes 2 and 3. In          port is "free" and ready to send the next byte.
modes 2 and 3, a total of nine data bits are                          Finally, the RI bit means "Receive
transmitted. The first 8 data bits are the 8 bits of        Interrupt." It funcions similarly to the "TI" bit, but it
the main value, and the ninth bit is taken from             indicates that a byte has been received. That is to
TB8. If TB8 is set and a value is written to the            say, whenever the 8051 has received a complete
serial port, the data’s bits will be written to the         byte it will trigger the RI bit to let the program know
serial line followed by a "set" ninth bit. If TB8 is        that it needs to read the value quickly, before
clear the ninth bit will be "clear."                        another byte is read.
          The RB8 also operates in modes 2 and 3
and functions essentially the same way as TB8,

                                          Setting the Serial Port Baud Rate

        Once the Serial Port Mode has been
configured, as explained above, the program must                     For example, if we have an 11.059Mhz
configure the serial port’s baud rate. This only            crystal and we want to configure the serial port to
applies to Serial Port modes 1 and 3. The Baud              19,200 baud we try plugging it in the first equation:
Rate is determined based on the oscillator’s
frequency when in mode 0 and 2. In mode 0, the                       TH1 = 256 - ((Crystal / 384) / Baud)
baud rate is always the oscillator frequency                         TH1 = 256 - ((28,799) / 19200)
divided by 12. This means if you’re crystal is                       TH1 = 256 - 1.5 = 254.5
11.059Mhz, mode 0 baud rate will always be
921,583 baud. In mode 2 the baud rate is always                     As you can see, to obtain 19,200 baud on
the oscillator frequency divided by 64, so a                a 11.059Mhz crystal we’d have to set TH1 to
11.059Mhz crystal speed will yield a baud rate of           254.5. If we set it to 254 we will have achieved
172,797.                                                    14,400 baud and if we set it to 255 we will have
        In modes 1 and 3, the baud rate is                  achieved 28,800 baud. Thus we’re stuck...
determined by how frequently timer 1 overflows.                     But not quite... to achieve 19,200 baud we
The more frequently timer 1 overflows, the higher           simply need to set PCON.7 (SMOD). When we do
the baud rate. There are many ways one can                  this we double the baud rate and utilize the second
cause timer 1 to overflow at a rate that determines         equation mentioned above. Thus we have:
a baud rate, but the most common method is to
put timer 1 in 8-bit auto-reload mode (timer mode                    TH1 = 256 - ((Crystal / 192) / Baud)
2) and set a reload value (TH1) that causes Timer                    TH1 = 256 - ((11059000 / 192) / 19200)
                                                                     TH1 = 256 - ((57699) / 19200)
1 to overflow at a frequency appropriate to                          TH1 = 256 - 3 = 253
generate a baud rate.
        To determine the value that must be                        Here we are able to calculate a nice, even
placed in TH1 to generate a given baud rate, we             TH1 value. Therefore, to obtain 19,200 baud with
may use the following equation (assuming                    an 11.059MHz crystal we must:
PCON.7 is clear).
                                                            1) Configure Serial Port mode 1 or 3.
                                                            2) Configure Timer 1 to timer mode 2 (8-bit auto-
         If PCON.7 is set then the baud rate is                reload).
effectively doubled, thus the equation becomes:             3) Set TH1 to 253 to reflect the correct frequency
                                                               for 19,200 baud.
        TH1 = 256 - ((Crystal / 192) / Baud)                4) Set PCON.7 (SMOD) to double the baud rate.
                                           Writing to the Serial Port

         Once the Serial Port has been propertly                      The 8051 lets us know when it is done
configured as explained above, the serial port is             transmitting a character by setting the TI bit in
ready to be used to send data and receive data. If            SCON. When this bit is set we know that the last
you thought that configuring the serial port was              character has been transmitted and that we may
simple, using the serial port will be a breeze.               send the next character, if any. Consider the
         To write a byte to the serial port one must          following code segment:
example, if you wanted to send the letter "A" to the                  CLR TI            ;Be sure the bit is initially clear
                                                                      MOV SBUF,#’A’     ;Send the letter ‘A’ to the serial
serial port, it could be accomplished as easily as:                   port
                                                                      JNB TI,$          ;Pause until the RI bit is set.
        MOV SBUF,#’A’
                                                                       The above three instructions will
         Upon execution of the above instruction              successfully transmit a character and wait for the
the 8051 will begin transmitting the character via            TI bit to be set before continuing. The last
the serial port. Obviously transmission is not                instruction says "Jump if the TI bit is not set to $"--
instantaneous--it takes a measureable amount of               $, in most assemblers, means "the same address
time to transmit. And since the 8051 does not have            of the current instruction." Thus the 8051 will
a serial output buffer we need to be sure that a              pause on the JNB instruction until the TI bit is set
character is completely transmitted before we try             by the 8051 upon successful transmission of the
to transmit the next character.                               character.

                                            Reading the Serial Port

        Reading data received by the serial port is                   For example, if your program wants to wait
equally easy. To read a byte from the serial port             for a character to be received and subsequently
one just needs to read the value stored in the                read it into the Accumulator, the following code
SBUF (99h) SFR after the 8051 has automatically               segment may be used:
set the RI flag in SCON.

        MOV A,SBUF      ;Read the character from the serial port

         The first line of the above code segment                      Once the RI bit is set upon character
waits for the 8051 to set the RI flag; again, the             reception the above condition automatically fails
8051 sets the RI flag automatically when it                   and program flow falls through to the "MOV"
receives a character via the serial port. So as long          instruction which reads the value.
instruction continuously.

                                      8051 Tutorial: Interrupts

          As stated earlier, program flow is always    16-bit timer mode, timer 0 will overflow every
sequential, being altered only by those instructions   65,536 machine cycles. In that time we would
which expressly cause program flow to deviate in       have performed 655 JNB tests for a total of 1310
some way. However, interrupts give us a                instruction cycles, plus another 2 instruction cycles
mechanism to "put on hold" the normal program          to perform the code. So to achieve our goal we’ve
flow, execute a subroutine, and then resume            spent 1312 instruction cycles. So 2.002% of our
normal program flow as if we had never left it. This   time is being spent just checking when to toggle
subroutine, called an interrupt handler, is only       P3.0. And our code is ugly because we have to
executed when a certain event (interrupt) occurs.      make that check every iteration of our main
The event may be one of the timers "overflowing,"      program loop.
receiving a character via the serial port,                      Luckily, this isn’t necessary. Interrupts let
transmitting a character via the serial port, or one   us forget about checking for the condition. The
of two "external events." The 8051 may be              microcontroller itself will check for the condition
configured so that when any of these events occur      automatically and when the condition is met will
the main program is temporarily suspended and          jump to a subroutine (called an interrupt handler),
control passed to a special section of code which      execute the code, then return. In this case, our
presumably would execute some function related         subroutine would be nothing more than:
to the event that occured. Once complete, control              CPL P3.0
would be returned to the original program. The                 RETI
main program never even knows it was
interrupted.                                                    First, you’ll notice the CLR TF0 command
          The ability to interrupt normal program      has disappeared. That’s because when the 8051
execution when certain events occur makes it           executes our "timer 0 interrupt routine," it
much easier and much more efficient to handle          automatically clears the TF0 flag. You’ll also notice
certain conditions. If it were not for interrupts we   that instead of a normal RET instruction we have a
would have to manually check in our main               RETI instruction. The RETI instruction does the
program whether the timers had overflown,              same thing as a RET instruction, but tells the 8051
whether we had received another character via the      that an interrupt routine has finished. You must
serial port, or if some external event had occured.    always end your interrupt handlers with RETI.
Besides making the main program ugly and hard                   Thus, every 65536 instruction cycles we
to read, such a situation would make our program       execute the CPL instruction and the RETI
inefficient since we’d be burning precious             instruction. Those two instructions together require
"instruction cycles" checking for events that          3 instruction cycles, and we’ve accomplished the
usually don’t happen.                                  same goal as the first example that required 1312
          For example, let’s say we have a large       instruction cycles. As far as the toggling of P3.0
16k program executing many subroutines                 goes, our code is 437 times more efficient! Not to
performing many tasks. Let’s also suppose that we      mention it’s much easier to read and understand
want our program to automatically toggle the P3.0      because we don’t have to remember to always
port every time timer 0 overflows. The code to do      check for the timer 0 flag in our main program. We
this isn’t too difficult:                              just setup the interrupt and forget about it, secure
                                                       in the knowledge that the 8051 will execute our
        JNB TF0,SKIP_TOGGLE                            code whenever it’s necessary.
        CPL P3.0
        CLR TF0                                                 The same idea applies to receiving data
        SKIP_TOGGLE: ...                               via the serial port. One way to do it is to
                                                       continuously check the status of the RI flag in an
         Since the TF0 flag is set whenever timer 0    endless loop. Or we could check the RI flag as
overflows, the above code will toggle P3.0 every       part of a larger program loop. However, in the
time timer 0 overflows. This accomplishes what we      latter case we run the risk of missing characters--
want, but is inefficient. The JNB instruction          what happens if a character is received right after
consumes 2 instruction cycles to determine that        we do the check, the rest of our program executes,
the flag is not set and jump over the unnecessary      and before we even check RI a second character
code. In the event that timer 0 overflows, the CPL     has come in. We will lose the first character. With
and CLR instruction require 2 instruction cycles to    interrupts, the 8051 will put the main program "on
execute. To make the math easy, let’s say the rest     hold" and call our special routine to handle the
of the code in the program requires 98 instruction     reception of a character. Thus, we neither have to
cycles. Thus, in total, our code consumes 100          put an ugly check in our main code nor will we lose
instruction cycles (98 instruction cycles plus the 2   characters.
that are executed every iteration to determine
whether or not timer 0 has overflowed). If we’re in
                     What Events Can Trigger Interrupts, and where do they go?

         We can configure the 8051 so that any of                In other words, we can configure the 8051
the following events will cause an interrupt:           so that when Timer 0 Overflows or when a
                                                        character is sent/received, the appropriate
        •   Timer 0 Overflow.                           interrupt handler routines are called.
        •   Timer 1 Overflow.                                    Obviously we need to be able to
        •   Reception/Transmission       of   Serial    distinguish between various interrupts and
            Character.                                  executing different code depending on what
        •   External Event 0.                           interrupt was triggered. This is accomplished by
        •   External Event 1.                           jumping to a fixed address when a given interrupt

                           Interrupt          Flag      Interrupt Handler Address
                           External 0         IE0                   0003h
                            Timer 0           TF0                   000Bh
                           External 1         IE1                   0013h
                            Timer 1           TF1                   001Bh
                             Serial           RI/TI                 0023h

        By consulting the above chart we see that       suspended and control will jump to 000BH. It is
whenever Timer 0 overflows (i.e., the TF0 bit is        assumed that we have code at address 0003H
set), the main program will be temporarily              that handles the situation of Timer 0 overflowing.

                                          Setting Up Interrupts

         By default at powerup, all interrupts are      8051 that it wishes to enable interrupts and
disabled. This means that even if, for example, the     specifically which interrupts it wishes to enable.
TF0 bit is set, the 8051 will not execute the                    Your program may enable and disable
interrupt. Your program must specifically tell the      interrupts by modifying the IE SFR (A8h):

                     Bit Name Bit Address              Explanation of Function
                      7    EA           AFh     Global Interrupt Enable/Disable
                      6     -           AEh     Undefined
                      5     -           ADh     Undefined
                      4    ES           ACh     Enable Serial Interrupt
                      3    ET1          ABh     Enable Timer 1 Interrupt
                      2    EX1          AAh     Enable External 1 Interrupt
                      1    ET0          A9h     Enable Timer 0 Interrupt
                      0    EX0          A8h     Enable External 0 Interrupt

         As you can see, each of the 8051’s             bits of IE are set. Setting bit 7 will enable all the
interrupts has its own bit in the IE SFR. You           interrupts that have been selected by setting other
enable a given interrupt by setting the                 bits in IE. This is useful in program execution if you
corresponding bit. For example, if you wish to          have time-critical code that needs to execute. In
enable Timer 1 Interrupt, you would execute             this case, you may need the code to execute from
either:                                                 start to finish without any interrupt getting in the
        MOV IE,#08h || SETB ET1                         way. To accomplish this you can simply clear bit 7
         Both of the above instructions set bit 3 of    criticial code is done.
IE, thus enabling Timer 1 Interrupt. Once Timer 1                  So, to sum up what has been stated in this
Interrupt is enabled, whenever the TF1 bit is set,      section, to enable the Timer 1 Interrupt the most
the 8051 will automatically put "on hold" the main      common approach is to execute the following two
program and execute the Timer 1 Interrupt               instructions:
Handler at address 001Bh.
         However, before Timer 1 Interrupt (or any              SETB ET1
other interrupt) is truly enabled, you must also set            SETB EA
bit 7 of IE. Bit 7, the Global Interupt
Enable/Disable, enables or disables all interrupts               Thereafter, the Timer 1 Interrupt Handler
simultaneously. That is to say, if bit 7 is cleared     at 01Bh will automatically be called whenever the
then no interrupts will occur, even if all the other    TF1 bit is set (upon Timer 1 overflow).

                                             Polling Sequence

        The 8051 automatically evaluates whether         1)   External 0 Interrupt
an interrupt should occur after every instruction.       2)   Timer 0 Interrupt
When checking for interrupt conditions, it checks        3)   External 1 Interrupt
them in the following order:                             4)   Timer 1 Interrupt
                                                         5)   Serial Interrupt

                                            Interrupt Priorities

          The 8051 offers two levels of interrupt        the timer interrupt. In this case, if Timer 1 Interrupt
priority: high and low. By using interrupt priorities    is already executing you may wish that the serial
you may assign higher priority to certain interrupt      interrupt itself interrupts the Timer 1 Interrupt.
conditions.                                              When the serial interrupt is complete, control
          For example, you may have enabled              passes back to Timer 1 Interrupt and finally back
Timer 1 Interrupt which is automatically called          to the main program. You may accomplish this by
every time Timer 1 overflows. Additionally, you          assigning a high priority to the Serial Interrupt and
may have enabled the Serial Interrupt which is           a low priority to the Timer 1 Interrupt.
called every time a character is received via the                 Interrupt priorities are controlled by the IP
serial port. However, you may consider that              SFR (B8h). The IP SFR has the following format:
receiving a character is much more important than

                     Bit    Name     Bit Address         Explanation of Function
                      7       -           -         Undefined
                      6       -           -         Undefined
                      5       -           -         Undefined
                      4      PS          BCh        Serial Interrupt Priority
                      3      PT1         BBh        Timer 1 Interrupt Priority
                      2      PX1         BAh        External 1 Interrupt Priority
                      1      PT0         B9h        Timer 0 Interrupt Priority
                      0      PX0         B8h        External 0 Interrupt Priority

         When considering interrupt priorities, the      •    A low-priority interrupt may only occur if no
following rules apply:                                        other interrupt is already executing.
• Nothing can interrupt a high-priority interrupt--      •    If two interrupts occur at the same time, the
     not even another high priority interrupt.                interrupt with higher priority will execute first. If
• A high-priority interrupt may interrupt a low-              both interrupts are of the same priority the
     priority interrupt.                                      interrupt which is serviced first by polling
                                                              sequence will be executed first.

                               What Happens When an Interrupt Occurs?

         When an interrupt is triggered, the             •    Program     execution    transfers   to    the
following actions are taken automatically by the              corresponding    interrupt   handler    vector
microcontroller:                                              address.
• The current Program Counter is saved on the            •    The Interrupt Handler Routine executes.
     stack, low-byte first.
• Interrupts of the same and lower priority are                   Take special note of the third step: If the
     blocked.                                            interrupt being handled is a Timer or External
• In the case of Timer and External interrupts,          interrupt, the microcontroller automatically clears
     the corresponding interrupt flag is set.            the interrupt flag before passing control to your
                                                         interrupt handler routine.

                                What Happens When an Interrupt Ends?

         An interrupt ends when your program             •    Two bytes are popped off the stack into the
executes the RETI instruction. When the RETI                  Program Counter to restore normal program
instruction is executed the following actions are             execution.
taken by the microcontroller:                            •    Interrupt status is restored to its pre-interrupt

                                                 Serial Interrupts

         Serial Interrupts are slightly different than                 This means that when your serial interrupt
the rest of the interrupts. This is due to the fact           is executed, it may have been triggered because
that there are two interrupt flags: RI and TI. If             the RI flag was set or because the TI flag was set--
either flag is set, a serial interrupt is triggered. As       or because both flags were set. Thus, your routine
you will recall from the section on the serial port,          must check the status of these flags to determine
the RI bit is set when a byte is received by the              what action is appropriate. Also, since the 8051
serial port and the TI bit is set when a byte has             does not automatically clear the RI and TI flags
been sent.                                                    you must clear these bits in your interrupt handler.

        INT_SERIAL:     JNB RI,CHECK_TI      ;If the RI flag is not set, we jump to check TI
                        MOV A,SBUF           ;If we got to this line, it’s because the RI bit *was* set
                        CLR RI               ;Clear the RI bit after we’ve processed it
        CHECK_TI:       JNB TI,EXIT_INT      ;If the TI flag is not set, we jump to the exit point
                        CLR TI               ;Clear the TI bit before we send another character
                        MOV SBUF,#’A’        ;Send another character to the serial port
        EXIT_INT:       RETI

        As you can see, our code checks the                   the interrupt bits, the serial interrupt will be
status of both interrupts flags. If both flags were           executed over and over until you clear the bit.
set, both sections of code will be executed. Also             Thus it is very important that you always clear the
note that each section of code clears its                     interrupt flags in a serial interrupt.
corresponding interrupt flag. If you forget to clear

                         Important Interrupt Consideration: Register Protection

         One very important rule applies to all                        Remember, the idea behind interrupts is
interrupt handlers: Interrupts must leave the                 that the main program isn’t aware that they are
processor in the same state as it was in when the             executing in the "background." However, consider
interrupt initiated.                                          the following code:

                                   CLR C              ;Clear carry
                                   MOV A,#25h         ;Load the accumulator with 25h
                                   ADDC A,#10h        ;Add 10h, with carry

         After the above three instructions are               the value of the accumulator is the same at the
executed, the accumulator will contain a value of             end of the interrupt as it was at the beginning. This
35h.                                                          is generally accomplished with a PUSH and POP
         But what would happen if right after the             sequence. For example:
MOV instruction an interrupt occured. During this
interrupt, the carry bit was set and the value of the                     PUSH ACC
                                                                          PUSH PSW
accumulator was changed to 40h. When the                                  MOV A,#0FFh
interrupt finished and control was passed back to                         ADD A,#02h
the main program, the ADDC would add 10h to                               POP PSW
40h, and additionally add an additional 1h because                        POP ACC
the carry bit is set. In this case, the accumulator
will contain the value 51h at the end of execution.                    The guts of the interrupt is the MOV
         In this case, the main program has                   instruction and the ADD instruction. However,
seemingly calculated the wrong answer. How can                these two instructions modify the Accumulator (the
25h + 10h yield 51h as a result? It doesn’t make              MOV instruction) and also modify the value of the
sense. A programmer that was unfamiliar with                  carry bit (the ADD instruction will cause the carry
interrupts would be convinced that the                        bit to be set). Since an interrupt routine must
microcontroller was damaged in some way,                      guarantee that the registers remain unchanged by
provoking        problems      with      mathematical         the routine, the routine pushes the original values
calculations.                                                 onto the stack using the PUSH instruction. It is
         What has happened, in reality, is the                then free to use the registers it protected to its
interrupt did not protect the registers it used.              heart’s content. Once the interrupt has finished its
         Restated: An interrupt must leave the                task, it pops the original values back into the
processor in the same state as it was in when the             registers. When the interrupt exits, the main
interrupt initiated.                                          program will never know the difference because
         What does this mean? It means if your                the registers are exactly the same as they were
interrupt uses the accumulator, it must insure that           before the interrupt executed.

         In general, your interrupt routine must               PUSH R0
protect the following registers:
                                                                This is due to the fact that depending on
        •   PSW                                        which register bank is selected, R0 may refer to
        •   DPTR (DPH/DPL)                             either internal ram address 00h, 08h, 10h, or 18h.
        •   PSW                                        R0, in and of itself, is not a valid memory address
        •   ACC
                                                       that the PUSH and POP instructions can use.
        •   B
        •   Registers R0-R7                                     Thus, if you are using any "R" register in
                                                       your interrupt routine, you will have to push that
         Remember that PSW consists of many            register’s absolute address onto the stack instead
individual bits that are set by various 8051           of just saying PUSH R0. For example, instead of
instructions. Unless you are absolutely sure of        PUSH R0 you would execute:
what you are doing and have a complete
                                                               PUSH 00h
understanding of what instructions set what bits, it
is generally a good idea to always protect PSW by
                                                               Of course, this only works if you’ve
pushing and popping it off the stack at the
                                                       selected the default register set. If you are using
beginning and end of your interrupts.
                                                       an alternate register set, you must PUSH the
         Note also that most assemblers (in fact,
                                                       address which corresponds to the register you are
ALL assemblers that I know of) will not allow you
to execute the instruction:

                                   Common Problems with Interrupts

          Interrupts are a very powerful tool              them and subsequently pop only ACC and
available to the 8051 developer, but when used             PSW off the stack before exiting. In this case,
incorrectly they can be a source of a huge number          since you forgot to restore the value of "B", an
of debugging hours. Errors in interrupt routines are       extra value remains on the stack. When you
often very difficult to diagnose and correct.              execute the RETI instruction the 8051 will use
          If you are using interrupts and your             that value as the return address instead of the
program is crashing or does not seem to be                 correct value. In this case, your program will
performing as you would expect, always review              almost certainly crash. ALWAYS MAKE SURE
the following interrupt-related issues:                    YOU POP THE SAME NUMBER OF VALUES
• Register Protection: Make sure you are                   OFF THE STACK AS YOU PUSHED ONTO
     protecting all your registers, as explained           IT.
     above. If you forget to protect a register that
     your main program is using, very strange                   Using RET instead of RETI: Remember
     results may occur. In our example above we        that interrupts are always terminated with the RETI
     saw how failure to protect registers caused the   instruction. It is easy to inadvertantly use the RET
     main program to apparently calculate that 25h     instruction instead. However, the RET instruction
     + 10h = 51h. If you witness problems with         will not end your interrupt. Usually, using a RET
     registers changing values unexpectedly or         instead of a RETI will cause the illusion of your
     operations producing "incorrect" values, it is    main program running normally, but your interrupt
     very likely that you’ve forgotten to protect      will only be executed once. If it appears that your
     registers.    ALWAYS       PROTECT       YOUR     interrupt mysteriously stops executing, verify that
     REGISTERS.                                        you are exiting with RETI.
• Forgetting to restore protected values:                       Simulators, such as Vault Information
     Another common error is to push registers         Services’ 8052 Simulator for Windows, contain
     onto the stack to protect them, and then forget   special features which will notify you if you fail to
     to pop them off the stack before exiting the      protect registers or commit other common
     interrupt. For example, you may push ACC, B,      interrupt-related errors.
     and PSW onto the stack in order to protect


To top