8051 Tutorial
8051 Tutorial
8051 Tutorial
The 8051 has three very general types of memory. To effectively program the 8051 it is
necessary to have a basic understanding of these memory types.
The memory types are illustrated in the following graphic. They are: On-Chip Memory, External
Code Memory, and External RAM.
On-Chip Memory refers to any memory (Code, RAM, or other) that physically exists on the
microcontroller itself. On-chip memory can be of several types, but we'll get into that shortly.
External Code Memory is code (or program) memory that resides off-chip. This is often in the
form of an external EPROM.
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 the actual 8051 program that is to be run. This memory
is limited to 64K and comes in many shapes and sizes: Code memory may be found on-chip,
either burned into the microcontroller as ROM or EPROM. Code may also be stored completely
off-chip in an external ROM or, more commonly, an external EPROM. Flash RAM is also
another popular method of storing a program. Various combinations of these memory types may
also be used--that is to say, it is possible to have 4K of code memory on-chip and 64k of code
memory off-chip in an EPROM.
When the program is stored on-chip the 64K maximum is often reduced to 4k, 8k, or 16k. This
varies depending on the version of the chip that is being used. Each version offers specific
capabilities and one of the distinguishing factors from chip to chip is how much ROM/EPROM
space the chip has.
However, code memory is most commonly implemented as off-chip EPROM. This is especially
true in low-cost development systems and in systems developed by students.
Programming Tip: Since code memory is restricted to 64K, 8051 programs are
limited to 64K. Some assemblers and compilers offer ways to get around this limit
when used with specially wired hardware. However, without such special
compilers and hardware, programs are limited to 64K.
External RAM
As an obvious opposite of Internal RAM, the 8051 also supports what is called External RAM.
As the name suggests, External RAM is any random access memory which is found off-chip.
Since the memory is off-chip it is not as flexible in terms of accessing, and is also slower. For
example, to increment an Internal RAM location by 1 requires only 1 instruction and 1
instruction cycle. To increment a 1-byte value stored in External RAM requires 4 instructions
and 7 instruction cycles. In this case, external memory is 7 times slower!
What External RAM loses in speed and flexibility it gains in quantity. While Internal RAM is
limited to 128 bytes (256 bytes with an 8052), the 8051 supports External RAM up to 64K.
Programming Tip: The 8051 may only address 64k of RAM. To expand RAM
beyond this limit requires programming and hardware tricks. You may have to do
this "by hand" since many compilers and assemblers, while providing support for
programs in excess of 64k, do not support more than 64k of RAM. This is rather
strange since it has been my experience that programs can usually fit in 64k but
often RAM is what is lacking. Thus if you need more than 64k of RAM, check to
see if your compiler supports it-- but if it doesn't, be prepared to do it by hand.
On-Chip Memory
As mentioned at the beginning of this chapter, the 8051 includes a certain amount of on-chip
memory. On-chip memory is really one of two types: Internal RAM and Special Function
Register (SFR) memory. The layout of the 8051's internal memory is presented in the following
memory map:
As is illustrated in this map, the 8051 has a bank of 128 bytes of Internal RAM. This Internal
RAM is found on-chip on the 8051 so it is the fastest RAM available, and it is also the most
flexible in terms of reading, writing, and modifying its contents. Internal RAM is volatile, so
when the 8051 is reset this memory is cleared.
The 128 bytes of internal ram is subdivided as shown on the memory map. The first 8 bytes (00h
- 07h) are "register bank 0". By manipulating certain SFRs, a program may choose to use register
banks 1, 2, or 3. These alternative register banks are located in internal RAM in addresses 08h
through 1Fh. We'll discuss "register banks" more in a later chapter. For now it is sufficient to
know that they "live" and are part of internal RAM.
Bit Memory also lives and is part of internal RAM. We'll talk more about bit memory very
shortly, but for now just keep in mind that bit memory actually resides in internal RAM, from
addresses 20h through 2Fh.
The 80 bytes remaining of Internal RAM, from addresses 30h through 7Fh, may be used by user
variables that need to be accessed frequently or at high-speed. This area is also utilized by the
microcontroller as a storage area for the operating stack. This fact severely limits the 8051s stack
since, as illustrated in the memory map, the area reserved for the stack is only 80 bytes--and
usually it is less since this 80 bytes has to be shared between the stack and user variables.
Register Banks
The 8051 uses 8 "R" registers which are used in many of its instructions. These "R" registers are
numbered from 0 through 7 (R0, R1, R2, R3, R4, R5, R6, and R7). These registers are generally
used to assist in manipulating values and moving data from one memory location to another. For
example, to add the value of R4 to the Accumulator, we would execute the following instruction:
ADD A,R4
Thus if the Accumulator (A) contained the value 6 and R4 contained the value 3, the
Accumulator would contain the value 9 after this instruction was executed.
However, as the memory map shows, the "R" Register R4 is really part of Internal RAM.
Specifically, R4 is address 04h. This can be see in the bright green section of the memory map.
Thus the above instruction accomplishes the same thing as the following operation:
ADD A,04h
This instruction adds the value found in Internal RAM address 04h to the value of the
Accumulator, leaving the result in the Accumulator. Since R4 is really Internal RAM 04h, the
above instruction effectively accomplished the same thing.
But watch out! As the memory map shows, the 8051 has four distinct register banks. When the
8051 is first booted up, register bank 0 (addresses 00h through 07h) is used by default. However,
your program may instruct the 8051 to use one of the alternate register banks; i.e., register banks
1, 2, or 3. In this case, R4 will no longer be the same as Internal RAM address 04h. For example,
if your program instructs the 8051 to use register bank 3, "R" register R4 will now be
synonomous with Internal RAM address 1Ch.
The concept of register banks adds a great level of flexibility to the 8051, especially when
dealing with interrupts (we'll talk about interrupts later). However, always remember that the
register banks really reside in the first 32 bytes of Internal RAM.
Programming Tip: If you only use the first register bank (i.e. bank 0), you may
use Internal RAM locations 08h through 1Fh for your own use. But if you plan to
use register banks 1, 2, or 3, be very careful about using addresses below 20h as
you may end up overwriting the value of your "R" registers!
Bit Memory
The 8051, being a communications-oriented microcontroller, gives the user the ability to access a
number of bit variables. These variables may be either 1 or 0.
There are 128 bit variables available to the user, numberd 00h through 7Fh. The user may make
use of these variables with commands such as SETB and CLR. For example, to set bit number 24
(hex) to 1 you would execute the instruction:
SETB 24h
It is important to note that Bit Memory is really a part of Internal RAM. In fact, the 128 bit
variables occupy the 16 bytes of Internal RAM from 20h through 2Fh. Thus, if you write the
value FFh to Internal RAM address 20h youve effectively set bits 00h through 07h. That is to say
that:
MOV 20h,#0FFh
is equivalent to:
SETB 00h
SETB 01h
SETB 02h
SETB 03h
SETB 04h
SETB 05h
SETB 06h
SETB 07h
As illustrated above, bit memory isnt really a new type of memory. Its really just a subset of
Internal RAM. But since the 8051 provides special instructions to access these 16 bytes of
memory on a bit by bit basis it is useful to think of it as a separate type of memory. However,
always keep in mind that it is just a subset of Internal RAM--and that operations performed on
Internal RAM can change the values of the bit variables.
Programming Tip: If your program does not use bit variables, you may use
Internal RAM locations 20h through 2Fh for your own use. But if you plan to use
bit variables, be very careful about using addresses from 20h through 2Fh as you
may end up overwriting the value of your bits!
Bit variables 00h through 7Fh are for user-defined functions in their programs. However, bit
variables 80h and above are actually used to access certain SFRs on a bit-by-bit basis. For
example, if output lines P0.0 through P0.7 are all clear (0) and you want to turn on the P0.0
output line you may either execute:
MOV P0,#01h
SETB 80h
Both these instructions accomplish the same thing. However, using the SETB command will turn
on the P0.0 line without effecting the status of any of the other P0 output lines. The MOV
command effectively turns off all the other output lines which, in some cases, may not be
acceptable.
Programming Tip: By default, the 8051 initializes the Stack Pointer (SP) to 07h
when the microcontroller is booted. This means that the stack will start at address
08h and expand upwards. If you will be using the alternate register banks (banks 1,
2 or 3) you must initialize the stack pointer to an address above the highest register
bank you will be using, otherwise the stack will overwrite your alternate register
banks. Similarly, if you will be using bit variables it is usually a good idea to
initialize the stack pointer to some value greater than 2Fh to guarantee that your
bit variables are protected from the stack.
When programming, SFRs have the illusion of being Internal Memory. For example, if you want
to write the value "1" to Internal RAM location 50 hex you would execute the instruction:
MOV 50h,#01h
Similarly, if you want to write the value "1" to the 8051s serial port you would write this value to
the SBUF SFR, which has an SFR address of 99 Hex. Thus, to write the value "1" to the serial
port you would execute the instruction:
MOV 99h,#01h
As you can see, it appears that the SFR is part of Internal Memory. This is not the case. When
using this method of memory access (its called direct address), any instruction that has an
address of 00h through 7Fh refers to an Internal RAM memory address; any instruction with an
address of 80h through FFh refers to an SFR control register.
Programming Tip: SFRs are used to control the way the 8051 functions. Each
SFR has a specific purpose and format which will be discussed later. Not all
addresses above 80h are assigned to SFRs. However, this area may NOT be used
as additional RAM memory even if a given address has not been assigned to an
SFR.
Each SFR has an address (80h through FFh) and a name. The following chart provides a
graphical presentation of the 8051's SFRs, their names, and their address.
As you can see, although the address range of 80h through FFh offer 128 possible addresses,
there are only 21 SFRs in a standard 8051. All other addresses in the SFR range (80h through
FFh) are considered invalid. Writing to or reading from these registers may produce undefined
values or behavior.
SFR Types
As mentioned in the chart itself, the SFRs that have a blue background are SFRs related to the
I/O ports. The 8051 has four I/O ports of 8 bits, for a total of 32 I/O lines. Whether a given I/O
line is high or low and the value read from the line are controlled by the SFRs in green.
The SFRs with yellow backgrouns are SFRs which in some way control the operation or the
configuration of some aspect of the 8051. For example, TCON controls the timers, SCON
controls the serial port.
The remaining SFRs, with green backgrounds, are "other SFRs." These SFRs can be thought of
as auxillary SFRs in the sense that they don't directly configure the 8051 but obviously the 8051
cannot operate without them. For example, once the serial port has been configured using
SCON, the program may read or write to the serial port using the SBUF register.
Programming Tip: The SFRs whose names appear in red in the chart above are
SFRs that may be accessed via bit operations (i.e., using the SETB and CLR
instructions). The other SFRs cannot be accessed using bit operations. As you can
see, all SFRs that whose addresses are divisible by 8 can be accessed with bit
operations.
SFR Descriptions
This section will endeavor to quickly overview each of the standard SFRs found in the above
SFR chart map. It is not the intention of this section to fully explain the functionality of each
SFR--this information will be covered in separate chapters of the tutorial. This section is to just
give you a general idea of what each SFR does.
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 so.
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/8Ch): 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 8Bh/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 timers always count up. What is configurable is how and when they
increment in value.
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 P1.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.
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.
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 from.
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 P2.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.
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 P3.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.
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 SFRs that exist in a standard 8051. All derivative
microcontrollers of the 8051 must support these basic SFRs in order to maintain compatability
with the underlying MSCS51 standard.
A common practice when semiconductor firms wish to develop a new 8051 derivative is to add
additional SFRs to support new functions that exist in the new chip. For example, the Dallas
Semiconductor DS80C320 is upwards compatible with the 8051. This means that any program
that runs on a standard 8051 should run without modification on the DS80C320. This means that
all the SFRs defined above also apply to the Dallas component.
However, since the DS80C320 provides many new features that the standard 8051 does not,
there must be some way to control and configure these new features. This is accomplished by
adding additional SFRs to those listed here. For example, since the DS80C320 supports two
serial ports (as opposed to just one on the 8051), the SFRs SBUF2 and SCON2 have been added.
In addition to all the SFRs listed above, the DS80C320 also recognizes these two new SFRs as
valid and uses their values to determine the mode of operation of the secondary serial port.
Obviously, these new SFRs have been assigned to SFR addresses that were unused in the
original 8051. In this manner, new 8051 derivative chips may be developed which will run
existing 8051 programs.
Programming Tip: If you write a program that utilizes new SFRs that are specific
to a given derivative chip and not included in the above SFR list, your program
will not run properly on a standard 8051 where that SFR does not exist. Thus, only
use non-standard SFRs if you are sure that your program wil only have to run on
that specific microcontroller. Likewise, if you write code that uses non-standard
SFRs and subsequently share it with a third-party, be sure to let that party know
that your code is using non-standard SFRs to save them the headache of realizing
that due to strange behavior at run-time.
Online Store
Consulting Services
The 8052.com Book
Message Forum
8052 ForumChat BoardForum Rules (Read!)Tutorials
Tutorials Index8051/8052 Tutorial16-Bit MathLCD Programming8051 Instruction Set8052 FAQs
News
Code Library
Links
User Pages
8052 Projects
8052.com SBC8052 Video8052 TCP/IP8052 CD-ROMDisassemblerAbout 8052.com
Contact UsAbout 8052.comLegal InfoPrivacy PolicyAdvertising
8051 Tutorial: Basic Registers
The Accumulator
If youve worked with any other assembly languages you will be familiar with the concept of an
Accumulator register.
The Accumulator, as its name suggests, is used as a general register to accumulate the results of
a large number of instructions. It can hold an 8-bit (1-byte) value and is the most versatile
register the 8051 has due to the shear number of instructions that make use of the accumulator.
More than half of the 8051s 255 instructions manipulate or use the accumulator in some way.
For example, if you want to add the number 10 and 20, the resulting 30 will be stored in the
Accumulator. Once you have a value in the Accumulator you may continue processing the value
or you may store it in another register or in memory.
These registers are used as auxillary registers in many operations. To continue with the above
example, perhaps you are adding 10 and 20. The original number 10 may be stored in the
Accumulator whereas the value 20 may be stored in, say, register R4. To process the addition
you would execute the command:
ADD A,R4
After executing this instruction the Accumulator will contain the value 30.
You may think of the "R" registers as very important auxillary, or "helper", registers. The
Accumulator alone would not be very useful if it were not for these "R" registers.
The "R" registers are also used to temporarily store values. For example, lets say you want to add
the values in R1 and R2 together and then subtract the values of R3 and R4. One way to do this
would be:
As you can see, we used R5 to temporarily hold the sum of R3 and R4. Of course, this isnt the
most efficient way to calculate (R1+R2) - (R3 +R4) but it does illustrate the use of the "R"
registers as a way to store values temporarily.
The "B" register is very similar to the Accumulator in the sense that it may hold an 8-bit (1-byte)
value.
The "B" register is only used by two 8051 instructions: MUL AB and DIV AB. Thus, if you
want to quickly and easily multiply or divide A by another number, you may store the other
number in "B" and make use of these two instructions.
Aside from the MUL and DIV instructions, the "B" register is often used as yet another
temporary storage register much like a ninth "R" register.
DPTR, as the name suggests, is used to point to data. It is used by a number of commands which
allow the 8051 to access external memory. When the 8051 accesses external memory it will
access external memory at the address indicated by DPTR.
While DPTR is most often used to point to data in external memory, many programmers often
take advantge of the fact that its the only true 16-bit register available. It is often used to store 2-
byte values which have nothing to do with memory locations.
The Program Counter (PC) is a 2-byte address which tells the 8051 where the next instruction to
execute is found in memory. When the 8051 is initialized PC always starts at 0000h and is
incremented each time an instruction is executed. It is important to note that PC isnt always
incremented by one. Since some instructions require 2 or 3 bytes the PC will be incremented by
2 or 3 in these cases.
The Program Counter is special in that there is no way to directly modify its value. That is to say,
you cant do something like PC=2430h. On the other hand, if you execute LJMP 2430h youve
effectively accomplished the same thing.
The Stack Pointer, like all registers except DPTR and PC, may hold an 8-bit (1-byte) value. The
Stack Pointer is used to indicate where the next value to be removed from the stack should be
taken from.
When you push a value onto the stack, the 8051 first increments the value of SP and then stores
the value at the resulting memory location.
When you pop a value off the stack, the 8051 returns the value from the memory location
indicated by SP, and then decrements the value of SP.
This order of operation is important. When the 8051 is initialized SP will be initialized to 07h. If
you immediately push a value onto the stack, the value will be stored in Internal RAM address
08h. This makes sense taking into account what was mentioned two paragraphs above: First the
8051 will increment the value of SP (from 07h to 08h) and then will store the pushed value at
that memory address (08h).
SP is modified directly by the 8051 by six instructions: PUSH, POP, ACALL, LCALL, RET,
and RETI. It is also used intrinsically whenever an interrupt is triggered (more on interrupts later.
Dont worry about them for now!).
An "addressing mode" refers to how you are addressing a given memory location. In summary,
the addressing modes are as follows, 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 because the value to be stored in memory immediately
follows the operation code in memory. That is to say, the instruction itself dictates what value
will be stored in memory.
MOV A,#20h
This instruction uses Immediate Addressing because the Accumulator will be loaded with the
value that immediately follows; in this case 20 (hexidecimal).
Immediate addressing is very fast since the value to be loaded is included in the instruction.
However, since the value to be loaded is fixed at compile-time it is not very flexible.
Direct Addressing
Direct addressing is so-named because the value to be stored in memory is obtained by directly
retrieving it from another memory location. For example:
MOV A,30h
This instruction will read the data out of Internal RAM address 30 (hexidecimal) and store it in
the Accumulator.
Direct addressing is generally fast since, although the value to be loaded isnt included in the
instruction, it is quickly accessable since it is stored in the 8051s Internal RAM. It is also much
more flexible than Immediate Addressing since the value to be loaded is whatever is found at the
given address--which may be variable.
Also, it is important to note that when using direct addressing any instruction which refers to an
address between 00h and 7Fh is referring to Internal Memory. Any instruction which refers to an
address between 80h and FFh is referring to the SFR control registers that control the 8051
microcontroller itself.
The obvious question that may arise is, "If direct addressing an address from 80h through FFh
refers to SFRs, how can I access the upper 128 bytes of Internal RAM that are available on the
8052?" The answer is: You cant access them using direct addressing. As stated, if you directly
refer to an address of 80h through FFh you will be referring to an SFR. However, you may
access the 8052s upper 128 bytes of RAM by using the next addressing mode, "indirect
addressing."
Indirect Addressing
Indirect addressing is a very powerful addressing mode which in many cases provides an
exceptional level of flexibility. Indirect addressing is also the only way to access the extra 128
bytes of Internal RAM found on an 8052.
MOV A,@R0
This instruction causes the 8051 to analyze the value of the R0 register. The 8051 will then load
the accumulator with the value from Internal RAM which is found at the address indicated by
R0.
For example, lets say R0 holds the value 40h and Internal RAM address 40h holds the value 67h.
When the above instruction is executed the 8051 will check the value of R0. Since R0 holds 40h
the 8051 will get the value out of Internal RAM address 40h (which holds 67h) and store it in the
Accumulator. Thus, the Accumulator ends up holding 67h.
Indirect addressing always refers to 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
may think that the following would be a valid solution to write the value 1 to the serial port:
This is not valid. Since indirect addressing always refers to Internal RAM these two instructions
would write the value 01h to Internal RAM address 99h on an 8052. On an 8051 these two
instructions would produce an undefined result since the 8051 only has 128 bytes of Internal
RAM.
External Direct
External Memory is accessed using a suite of instructions which use what I call "External Direct"
addressing. I call it this because it appears to be direct addressing, but it is used to access external
memory rather than internal memory.
There are only two commands that use External Direct addressing mode:
MOVX A,@DPTR
MOVX @DPTR,A
As you can see, both commands utilize DPTR. In these instructions, DPTR must first be loaded
with the address of external memory that you wish to read or write. Once DPTR holds the correct
external memory address, the first command will move the contents of that external memory
address into the Accumulator. The second command will do the opposite: it will allow you to
write the value of the Accumulator to the external memory address pointed to by DPTR.
External Indirect
External memory can also be accessed using a form of indirect addressing which I call External
Indirect addressing. This form of addressing is usually only used in relatively small projects that
have a very small amount of external RAM. An example of this addressing mode is:
MOVX @R0,A
Once again, the value of R0 is first read and the value of the Accumulator is written to that
address in External RAM. Since the value of @R0 can only be 00h through FFh the project
would effectively be limited to 256 bytes of External RAM. There are relatively simple
hardware/software tricks that can be implemented to access more than 256 bytes of memory
using External Indirect addressing; however, it is usually easier to use External Direct addressing
if your project has more than 256 bytes of External RAM.
When an 8051 is first initialized, it resets the PC to 0000h. The 8051 then begins to execute
instructions sequentially in memory unless a program instruction causes the PC to be otherwise
altered. There are various instructions that can modify the value of the PC; specifically,
conditional branching instructions, direct jumps and calls, and "returns" from subroutines.
Additionally, interrupts, when enabled, can cause the program flow to deviate from its otherwise
sequential scheme.
Conditional Branching
The 8051 contains a suite of instructions which, as a group, are referred to as "conditional
branching" instructions. These instructions cause program execution to follow a non-sequential
path if a certain condition is true.
Take, for example, the JB instruction. This instruction means "Jump if Bit Set." An example of
the JB instruction might be:
JB 45h,HELLO
NOP
HELLO: ....
In this case, the 8051 will analyze the contents of bit 45h. If the bit is set program execution will
jump immediately to the label HELLO, skipping the NOP instruction. If the bit is not set the
conditional branch fails and program execution continues, as usual, with the NOP instruction
which follows.
Conditional branching is really the fundamental building block of program logic since all
"decisions" are accomplished by using conditional branching. Conditional branching can be
thought of as the "IF...THEN" structure in 8051 assembly language.
An important note worth mentioning about conditional branching is that the program may only
branch to instructions located withim 128 bytes prior to or 127 bytes following the address which
follows the conditional branch instruction. This means that in the above example the label
HELLO must be within +/- 128 bytes of the memory address which contains the conditional
branching instruction.
Direct Jumps
While conditional branching is extremely important, it is often necessary to make a direct branch
to a given memory location without basing it on a given logical decision. This is equivalent to
saying "Goto" in BASIC. In this case you want the program flow to continue at a given memory
address without considering any conditions.
This is accomplished in the 8051 using "Direct Jump and Call" instructions. As illustrated in the
last paragraph, this suite of instructions causes program flow to change unconditionally.
LJMP NEW_ADDRESS
.
.
.
NEW_ADDRESS: ....
The LJMP instruction in this example means "Long Jump." When the 8051 executes this
instruction the PC is loaded with the address of NEW_ADDRESS and program execution
continues sequentially from there.
The obvious difference between the Direct Jump and Call instructions and the conditional
branching is that with Direct Jumps and Calls program flow always changes. With conditional
branching program flow only changes if a certain condition is true.
It is worth mentioning that, aside from LJMP, there are two other instructions which cause a
direct jump to occur: the SJMP and AJMP commands. Functionally, these two commands
perform the exact same function as the LJMP command--that is to say, they always cause
program flow to continue at the address indicated by the command. However, SJMP and AJMP
differ in the following ways:
The SJMP command, like the conditional branching instructions, can only jump to an
address within +/- 128 bytes of the SJMP command.
The AJMP command can only jump to an address that is in the same 2k block of memory
as the AJMP command. That is to say, if the AJMP command is at code memory
location 650h, it can only do a jump to addresses 0000h through 07FFh (0 through
2047, decimal).
You may be asking yourself, "Why would I want to use the SJMP or AJMP command which
have restrictions as to how far they can jump if they do the same thing as the LJMP command
which can jump anywhere in memory?" The answer is simple: The LJMP command requires
three bytes of code memory whereas both the SJMP and AJMP commands require only two.
Thus, if you are developing an application that has memory restrictions you can often save quite
a bit of memory using the 2-byte AJMP/SJMP instructions instead of the 3-byte instruction.
Recently, I wrote a program that required 2100 bytes of memory but I had a memory restriction
of 2k (2048 bytes). I did a search/replace changing all LJMPs to AJMPs and the program shrunk
downto 1950 bytes. Thus, without changing any logic whatsoever in my program I saved 150
bytes and was able to meet my 2048 byte memory restriction.
NOTE: Some quality assemblers will actually do the above conversion for you automatically.
That is, they'll automatically change your LJMPs to SJMPs whenever possible. This is a nifty
and very powerful capability that you may want to look for in an assembler if you plan to
develop many projects that have relatively tight memory restrictions.
Direct Calls
Another operation that will be familiar to seasoned programmers is the LCALL instruction. This
is similar to a "Gosub" command in Basic.
When the 8051 executes an LCALL instruction it immediately pushes the current Program
Counter onto the stack and then continues executing code at the address indicated by the LCALL
instruction.
The RET instruction, when executed, returns to the address following the instruction that called
the given subroutine. More accurately, it returns to the address that is stored on the stack.
The RET command is direct in the sense that it always changes program flow without basing it
on a condition, but is variable in the sense that where program flow continues can be different
each time the RET instruction is executed depending on from where the subroutine was called
originally.
Interrupts
An interrupt is a special feature which allows the 8051 to provide the illusion of "multi-tasking,"
although in reality the 8051 is only doing one thing at a time. The word "interrupt" can often be
subsituted with the word "event."
An interrupt is triggered whenever a corresponding event occurs. When the event occurs, the
8051 temporarily puts "on hold" the normal execution of the program and executes a special
section of code referred to as an interrupt handler. The interrupt handler performs whatever
special functions are required to handle the event and then returns control to the 8051 at which
point program execution continues as if it had never been interrupted.
The topic of interrupts is somewhat tricky and very important. For that reason, an entire chapter
will be dedicated to the topic. For now, suffice it to say that Interrupts can cause program flow to
change.
In order to understand--and better make use of--the 8051, it is necessary to understand some
underlying information concerning timing.
The 8051 operates based on an external crystal. This is an electrical device which, when energy
is applied, emits pulses at a fixed frequency. One can find crystals of virtually any frequency
depending on the application requirements. When using an 8051, the most common crystal
frequencies are 12 megahertz and 11.059 megahertz--with 11.059 being much more common.
Why would anyone pick such an odd-ball frequency? Theres a real reason for it--it has to do with
generating baud rates and well talk more about it in the Serial Communication chapter. For the
remainder of this discussion well assume that were using an 11.059Mhz crystal.
Microcontrollers (and many other electrical systems) use crystals to syncrhronize operations. The
8051 uses the crystal for precisely that: to synchronize its operation. Effectively, the 8051
operates using what are called "machine cycles." A single machine cycle is the minimum amount
of time in which a single 8051 instruction can be executed. although many instructions take
multiple cycles.
A cycle is, in reality, 12 pulses of the crystal. That is to say, if an instruction takes one machine
cycle to execute, it will take 12 pulses of the crystal to execute. Since we know the crystal is
pulsing 11,059,000 times per second and that one machine cycle is 12 pulses, we can calculate
how many instruction cycles the 8051 can execute per second:
11,059,000 / 12 = 921,583
This means that the 8051 can execute 921,583 single-cycle instructions per second. Since a large
number of 8051 instructions are single-cycle instructions it is often considered that the 8051 can
execute roughly 1 million instructions per second, although in reality it is less--and, depending
on the instructions being used, an estimate of about 600,000 instructions per second is more
realistic.
For example, if you are using exclusively 2-cycle instructions you would find that the 8051
would execute 460,791 instructions per second. The 8051 also has two really slow instructions
that require a full 4 cycles to execute--if you were to execute nothing but those instructions youd
find performance to be about 230,395 instructions per second.
It is again important to emphasize that not all instructions execute in the same amount of time.
The fastest instructions require one machine cycle (12 crystal pulses), many others require two
machine cycles (24 crystal pulses), and the two very slow math operations require four machine
cycles (48 crystal pulses).
NOTE: Many 8051 derivative chips change instruction timing. For example, many optimized
versions of the 8051 execute instructions in 4 oscillator cycles instead of 12; such a chip would
be effectively 3 times faster than the 8051 when used with the same 11.059 Mhz crystal.
Since all the instructions require different amounts of time to execute a very obvious question
comes to mind: How can one keep track of time in a time-critical application if we have no
reference to time in the outside world?
Luckily, the 8051 includes timers which allow us to time events with high precision--which is
the topic of the next chapter.
The 8051 comes equipped with two timers, both of which may be controlled, set, read, and
configured individually. The 8051 timers have three general functions: 1) Keeping time and/or
calculating the amount of time between events, 2) Counting the events themselves, or 3)
Generating baud rates for the serial port.
The three timer uses are distinct so we will talk about each of them separately. The first two uses
will be discussed in this chapter while the use of timers for baud rate generation will be
discussed in the chapter relating to serial ports.
11,059,000 / 12 = 921,583
921,583 times per second. Unlike instructions--some of which require 1 machine cycle, others 2,
and others 4--the timers are consistent: They will always be incremented once per machine cycle.
Thus if a timer has counted from 0 to 50,000 you may calculate:
.0542 seconds have passed. In plain English, about half of a tenth of a second, or one-twentieth
of a second.
Obviously its not very useful to know .0542 seconds have passed. If you want to execute an
event once per second youd have to wait for the timer to count from 0 to 50,000 18.45 times.
How can you wait "half of a time?" You cant. So we come to another important calculation.
Lets say we want to know how many times the timer will be incremented in .05 seconds. We can
do simple multiplication:
This tells us that it will take .05 seconds (1/20th of a second) to count from 0 to 46,079. Actually,
it will take it .049999837 seconds--so were off by .000000163 seconds--however, thats close
enough for government work. Consider that if you were building a watch based on the 8051 and
made the above assumption your watch would only gain about one second every 2 months.
Again, I think thats accurate enough for most applications--I wish my watch only gained one
second every two months!
Obviously, this is a little more useful. If you know it takes 1/20th of a second to count from 0 to
46,079 and you want to execute some event every second you simply wait for the timer to count
from 0 to 46,079 twenty times; then you execute your event, reset the timers, and wait for the
timer to count up another 20 times. In this manner you will effectively execute your event once
per second, accurate to within thousandths of a second.
Thus, we now have a system with which to measure time. All we need to review is how to
control the timers and initialize them to provide us with the information we need.
Timer SFRs
As mentioned before, the 8051 has two timers which each function essentially the same way.
One timer is TIMER0 and the other is TIMER1. The two timers share two SFRs (TMOD and
TCON) which control the timers, and each timer also has two SFRs dedicated solely to itself
(TH0/TL0 and TH1/TL1).
Weve given SFRs names to make it easier to refer to them, but in reality an SFR has a numeric
address. It is often useful to know the numeric address that corresponds to an SFR name. The
SFRs relating to timers are:
When you enter the name of an SFR into an assembler, it internally converts it to a number. For
example, the command:
MOV TH0,#25h
moves the value 25h into the TH0 SFR. However, since TH0 is the same as SFR address 8Ch
this command is equivalent to:
MOV 8Ch,#25h
Timer 0 has two SFRs dedicated exclusively to itself: TH0 and TL0. Without making things too
complicated to start off with, you may just think of this as the high and low byte of the timer.
That is to say, when Timer 0 has a value of 0, both TH0 and TL0 will contain 0. When Timer 0
has the value 1000, TH0 will hold the high byte of the value (3 decimal) and TL0 will contain
the low byte of the value (232 decimal). Reviewing low/high byte notation, recall that you must
multiply the high byte by 256 and add the low byte to calculate the final value. That is to say:
Timer 1 works the exact same way, but its SFRs are TH1 and TL1.
Since there are only two bytes devoted to the value of each timer it is apparent that the maximum
value a timer may have is 65,535. If a timer contains the value 65,535 and is subsequently
incremented, it will reset--or overflow--back to 0.
When the timer is in 13-bit mode, TLx will count from 0 to 31. When TLx is incremented from
31, it will "reset" to 0 and increment THx. Thus, effectively, only 13 bits of the two timer bytes
are being used: bits 0-4 of TLx and bits 0-7 of THx. This also means, in essence, the timer can
only contain 8192 values. If you set a 13-bit timer to 0, it will overflow back to zero 8192
machine cycles later.
Again, there is very little reason to use this mode and it is only mentioned so you wont be
surprised if you ever end up analyzing archaeic code which has been passed down through the
generations (a generation in a programming shop is often on the order of about 3 or 4 months).
TLx is incremented from 0 to 255. When TLx is incremented from 255, it resets to 0 and causes
THx to be incremented by 1. Since this is a full 16-bit timer, the timer may contain up to 65536
distinct values. If you set a 16-bit timer to 0, it will overflow back to 0 after 65,536 machine
cycles.
For example, lets say TH0 holds the value FDh and TL0 holds the value FEh. If we were to
watch the values of TH0 and TL0 for a few machine cycles this is what wed see:
As you can see, the value of TH0 never changed. In fact, when you use mode 2 you almost
always set THx to a known value and TLx is the SFR that is constantly incremented.
Whats the benefit of auto-reload mode? Perhaps you want the timer to always have a value from
200 to 255. If you use mode 0 or 1, youd have to check in code to see if the timer had overflowed
and, if so, reset the timer to 200. This takes precious instructions of execution time to check the
value and/or to reload it. When you use mode 2 the microcontroller takes care of this for you.
Once youve configured a timer in mode 2 you dont have to worry about checking to see if the
timer has overflowed nor do you have to worry about resetting the value--the microcontroller
hardware will do it all for you.
The auto-reload mode is very commonly used for establishing a baud rate which we will talk
more about in the Serial Communications chapter.
Timer mode "3" is a split-timer mode. When Timer 0 is placed in mode 3, it essentially becomes
two separate 8-bit timers. That is to say, Timer 0 is TL0 and Timer 1 is TH0. Both timers count
from 0 to 255 and overflow back to 0. All the bits that are related to Timer 1 will now be tied to
TH0.
While Timer 0 is in split mode, the real Timer 1 (i.e. TH1 and TL1) can be put into modes 0, 1 or
2 normally--however, you may not start or stop the real timer 1 since the bits that do that are now
linked to TH0. The real timer 1, in this case, will be incremented every machine cycle no matter
what.
The only real use I can see of using split timer mode is if you need to have two separate timers
and, additionally, a baud rate generator. In such case you can use the real Timer 1 as a baud rate
generator and use TH0/TL0 as two separate timers.
A new piece of information in this chart is the column "bit address." This is because this SFR is
"bit-addressable." What does this mean? It means if you want to set the bit TF1--which is the
highest bit of TCON--you could execute the command:
... or, since the SFR is bit-addressable, you could just execute the command:
SETB TF1
This has the benefit of setting the high bit of TCON without changing the value of any of the
other bits of the SFR. Usually when you start or stop a timer you dont want to modify the other
values in TCON, so you take advantage of the fact that the SFR is bit-addressable.
Initializing a Timer
Now that weve discussed the timer-related SFRs we are ready to write code that will initialize
the timer and start it running.
As youll recall, we first must decide what mode we want the timer to be in. In this case we want
a 16-bit timer that runs continuously; that is to say, it is not dependent on any external pins.
We must first initialize the TMOD SFR. Since we are working with timer 0 we will be using the
lowest 4 bits of TMOD. The first two bits, 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
set T0M0. Effectively, the only bit we want to turn on is bit 0 of TMOD. Thus to initialize the
timer we execute the instruction:
MOV TMOD,#01h
Timer 0 is now in 16-bit timer mode. However, the timer is not running. To start the timer
running we must set the TR0 bit We can do that by executing the instruction:
SETB TR0
Upon executing these two instructions 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 value of a 16-bit timer; which you use depends on
your specific application. You may either read the actual value of the timer as a 16-bit number,
or you may simply detect when the timer has overflowed.
If your timer is in an 8-bit mode--that is, either 8-bit AutoReload mode or in split timer mode--
then reading the value of the timer is simple. You simply read the 1-byte value of the timer and
youre done.
However, if youre dealing with a 13-bit or 16-bit timer the chore is a little more complicated.
Consider what would happen if you read the low byte of the timer as 255, then read the high byte
of the timer as 15. In this case, what actually happened was that the timer value was 14/255 (high
byte 14, low byte 255) but you read 15/255. Why? Because you read the low byte as 255. But
when you executed the next instruction a small amount of time passed--but enough for the timer
to increment again at which time the value rolled over from 14/255 to 15/0. But in the process
youve read the timer as being 15/255. Obviously theres a problem there.
The solution? Its not too tricky, really. You read the high byte of the timer, then read the low
byte, then read the high byte again. If the high byte read the second time is not the same as the
high byte read the first time you repeat the cycle. In code, this would appear as:
Another much simpler alternative is to simply turn off the timer run bit (i.e. CLR TR0), read the
timer value, and then turn on the timer run bit (i.e. SETB TR0). In that case, the timer isnt
running so no special tricks are necessary. Of course, this implies that your timer will be stopped
for a few machine cycles. Whether or not this is tolerable depends on your specific application.
Often it is necessary to just know that the timer has reset to 0. That is to say, you are not
particularly interest in the value of the timer but rather you are interested in knowing when the
timer has overflowed back to 0.
Whenever a timer overflows from its highest value back to 0, the microcontroller automatically
sets the TFx bit in the TCON register. This is useful since rather than checking the exact value of
the timer you can just check if the TFx bit is set. If TF0 is set it means that timer 0 has
overflowed; if TF1 is set it means that timer 1 has overflowed.
We can use this approach to cause the program to execute a fixed delay. As youll recall, we
calculated earlier that it takes the 8051 1/20th of a second to count from 0 to 46,079. However,
the TFx flag is set when the timer overflows back to 0. Thus, if we want to use the TFx flag to
indicate when 1/20th of a second has passed we must set the timer initially to 65536 less 46079,
or 19,457. If we set the timer to 19,457, 1/20th of a second later the timer will overflow. Thus we
come up with the following code to execute a pause of 1/20th of a second:
The 8051 provides another cool toy that can be used to time the length of events.
For example, let's say we're trying to save electricity in the office and we're interested in how
long a light is turned on each day. When the light is turned on, we want to measure time. When
the light is turned off we don't. One option would be to connect the lightswitch to one of the pins,
constantly read the pin, and turn the timer on or off based on the state of that pin. While this
would work fine, the 8051 provides us with an easier method of accomplishing this.
Looking again at the TMOD SFR, there is a bit called GATE0. So far we've always cleared this
bit because we wanted the timer to run regardless of the state of the external pins. However, now
it would be nice if an external pin could control whether the timer was running or not. It can. All
we need to do is connect the lightswitch to pin INT0 (P3.2) on the 8051 and set the bit GATE0.
When GATE0 is set Timer 0 will only run if P3.2 is high. When P3.2 is low (i.e., the lightswitch
is off) the timer will automatically be stopped.
Thus, with no control code whatsoever, the external pin P3.2 can control whether or not our
timer is running or not.
How can this be useful? Let's say you had a sensor placed across a road that would send a pulse
every time a car passed over it. This could be used to determine the volume of traffic on the road.
We could attach this sensor to one of the 8051's I/O lines and constantly monitor it, detecting
when it pulsed high and then incrementing our counter when it went back to a low state. This is
not terribly difficult, but requires some code. Let's say we hooked the sensor to P1.0; the code to
count cars passing would look something like this:
JNB P1.0,$ ;If a car hasn't raised the signal, keep waiting
JB P1.0,$ ;The line is high which means the car is on the sensor right now
INC COUNTER ;The car has passed completely, so we count it
As you can see, it's only three lines of code. But what if you need to be doing other processing at
the same time? You can't be stuck in the JNB P1.0,$ loop waiting for a car to pass if you need to
be doing other things. Of course, there are ways to get around even this limitation but the code
quickly becomes big, complex, and ugly.
Luckily, since the 8051 provides us with a way to use the timers to count events we don't have to
bother with it. It is actually painfully easy. We only have to configure one additional bit.
Let's say we want to use Timer 0 to count the number of cars that pass. If you look back to the bit
table for the TCON SFR you will there is a bit called "C/T0"--it's bit 2 (TCON.2). Reviewing the
explanation of the bit we see that if the bit is clear then timer 0 will be incremented every
machine cycle. This is what we've already used to measure time. However, if we set C/T0 timer
0 will monitor the P3.4 line. Instead of being incremented every machine cycle, timer 0 will
count events on the P3.4 line. So in our case we simply connect our sensor to P3.4 and let the
8051 do the work. Then, when we want to know how many cars have passed, we just read the
value of timer 0--the value of timer 0 will be the number of cars that have passed.
So what exactly is an event? What does timer 0 actually "count?" Speaking at the electrical level,
the 8051 counts 1-0 transitions on the P3.4 line. This means that when a car first runs over our
sensor it will raise the input to a high ("1") condition. At that point the 8051 will not count
anything since this is a 0-1 transition. However, when the car has passed the sensor will fall back
to a low ("0") state. This is a 1-0 transition and at that instant the counter will be incremented by
1.
It is important to note that the 8051 checks the P3.4 line each instruction cycle (12 clock cycles).
This means that if P3.4 is low, goes high, and goes back low in 6 clock cycles it will probably
not be detected by the 8051. This also means the 8051 event counter is only capable of counting
events that occur at a maximum of 1/24th the rate of the crystal frequency. That is to say, if the
crystal frequency is 12.000 Mhz it can count a maximum of 500,000 events per second (12.000
Mhz * 1/24 = 500,000). If the event being counted occurs more than 500,000 times per second it
will not be able to be accurately counted by the 8051.
8051 Tutorial: Serial Communication
One of the 8051s many powerful features is its integrated UART, otherwise known as a serial
port. The fact that the 8051 has an integrated serial port means that you may very easily read and
write values to the serial port. If it were not for the integrated serial port, writing a byte to a serial
line would be a rather tedious process requring turning on and off one of the I/O lines in rapid
succession to properly "clock out" each individual bit, including start bits, stop bits, and parity
bits.
However, we do not have to do this. Instead, we simply need to configure the serial ports
operation mode and baud rate. Once configured, all we have to do is write to an SFR to write a
value to the serial port or read the same SFR to read a value from the serial port. The 8051 will
automatically let us know when it has finished sending the character we wrote and will also let
us know whenever it has received a byte so that we can process it. We do not have to worry
about transmission at the bit level--which saves us quite a bit of coding and processing time.
The first thing we must do when using the 8051s integrated serial port is, obviously, configure it.
This lets us tell the 8051 how many data bits we want, the baud rate we will be using, and how
the baud rate will be determined.
First, lets present the "Serial Control" (SCON) SFR and define what each bit of the SFR
represents:
Additionally, it is necessary to define the function of SM0 and SM1 by an additional table:
(*) Note: The baud rate indicated in this table is doubled if PCON.7 (SMOD) is set.
The SCON SFR allows us to configure the Serial Port. Thus, well go through each bit and review
its function.
Bits SM0 and SM1 let us set the serial mode to a value between 0 and 3, inclusive. The four
modes are defined in the chart immediately above. As you can see, selecting the Serial Mode
selects the mode of operation (8-bit/9-bit, UART or Shift Register) and also determines how the
baud rate will be calculated. In modes 0 and 2 the baud rate is fixed based on the oscillators
frequency. In modes 1 and 3 the baud rate is variable based on how often Timer 1 overflows.
Well talk more about the various Serial Modes in a moment.
The next bit, SM2, is a flag for "Multiprocessor communication." Generally, whenever a byte
has been received the 8051 will set the "RI" (Receive Interrupt) flag. This lets the program know
that a byte has been received and that it needs to be processed. However, when 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 set and
a byte is received whose 9th bit is clear, the RI flag will never be set. This can be useful in
certain advanced serial applications. For now it is safe to say that you will almost always want to
clear this bit so that the flag is set upon reception of any character.
The next bit, REN, is "Receiver Enable." This bit is very straightforward: If you want to receive
data via the serial port, set this bit. You will almost always want to set this bit.
The last four bits (bits 0 through 3) are operational bits. They are used when actually sending and
receiving data--they are not used to configure the serial port.
The TB8 bit is used in modes 2 and 3. In modes 2 and 3, a total of nine data bits are transmitted.
The first 8 data bits are the 8 bits of the main value, and the ninth bit is taken from TB8. If TB8
is set and a value is written to the serial port, the datas bits will be written to the serial line
followed by a "set" ninth bit. If TB8 is clear the ninth bit will be "clear."
The RB8 also operates in modes 2 and 3 and functions essentially the same way as TB8, but on
the reception side. When a byte is received in modes 2 or 3, a total of nine bits are received. In
this case, the first eight bits received are the data of the serial byte received and the value of the
ninth bit received will be placed in RB8.
TI means "Transmit Interrupt." When a program writes a value to the serial port, a certain
amount of time will pass before the individual bits of the byte are "clocked out" the serial port. If
the program were to write another byte to the serial port before the first byte was completely
output, the data being sent would be garbled. Thus, the 8051 lets the program know that it has
"clocked out" the last byte by setting the TI bit. When the TI bit is set, the program may assume
that the serial port is "free" and ready to send the next byte.
Finally, the RI bit means "Receive Interrupt." It funcions similarly to the "TI" bit, but it indicates
that a byte has been received. That is to say, whenever the 8051 has received a complete byte it
will trigger the RI bit to let the program know that it needs to read the value quickly, before
another byte is read.
In modes 1 and 3, the baud rate is determined by how frequently timer 1 overflows. The more
frequently timer 1 overflows, the higher the baud rate. There are many ways one can cause timer
1 to overflow at a rate that determines a baud rate, but the most common method is to put timer 1
in 8-bit auto-reload mode (timer mode 2) and set a reload value (TH1) that causes Timer 1 to
overflow at a frequency appropriate to generate a baud rate.
To determine the value that must be placed in TH1 to generate a given baud rate, we may use the
following equation (assuming PCON.7 is clear).
But not quite... to achieve 19,200 baud we simply need to set PCON.7 (SMOD). When we do
this we double the baud rate and utilize the second equation mentioned above. Thus we have:
To write a byte to the serial port one must simply write the value to the SBUF (99h) SFR. For
example, if you wanted to send the letter "A" to the serial port, it could be accomplished as easily
as:
MOV SBUF,#A
Upon execution of the above instruction the 8051 will begin transmitting the character via the
serial port. Obviously transmission is not instantaneous--it takes a measureable amount of time to
transmit. And since the 8051 does not have a serial output buffer we need to be sure that a
character is completely transmitted before we try to transmit the next character.
The 8051 lets us know when it is done transmitting a character by setting the TI bit in SCON.
When this bit is set we know that the last character has been transmitted and that we may send
the next character, if any. Consider the following code segment:
For example, if your program wants to wait for a character to be received and subsequently read
it into the Accumulator, the following code segment may be used:
As the name implies, an interrupt is some event which interrupts normal program execution.
As stated earlier, program flow is always sequential, being altered only by those instructions
which expressly cause program flow to deviate in some way. However, interrupts give us a
mechanism to "put on hold" the normal program flow, execute a subroutine, and then resume
normal program flow as if we had never left it. This subroutine, called an interrupt handler, is
only executed when a certain event (interrupt) occurs. The event may be one of the timers
"overflowing," receiving a character via the serial port, transmitting a character via the serial
port, or one of two "external events." The 8051 may be configured so that when any of these
events occur the main program is temporarily suspended and control passed to a special section
of code which presumably would execute some function related to the event that occured. Once
complete, control would be returned to the original program. The main program never even
knows it was interrupted.
The ability to interrupt normal program execution when certain events occur makes it much
easier and much more efficient to handle certain conditions. If it were not for interrupts we
would have to manually check in our main program whether the timers had overflown, whether
we had received another character via the serial port, or if some external event had occured.
Besides making the main program ugly and hard to read, such a situation would make our
program inefficient since wed be burning precious "instruction cycles" checking for events that
usually dont happen.
For example, lets say we have a large 16k program executing many subroutines performing
many tasks. Lets also suppose that we want our program to automatically toggle the P3.0 port
every time timer 0 overflows. The code to do this isnt too difficult:
JNB TF0,SKIP_TOGGLE
CPL P3.0
CLR TF0
SKIP_TOGGLE: ...
Since the TF0 flag is set whenever timer 0 overflows, the above code will toggle P3.0 every time
timer 0 overflows. This accomplishes what we want, but is inefficient. The JNB instruction
consumes 2 instruction cycles to determine that the flag is not set and jump over the unnecessary
code. In the event that timer 0 overflows, the CPL and CLR instruction require 2 instruction
cycles to execute. To make the math easy, lets say the rest of the code in the program requires 98
instruction cycles. Thus, in total, our code consumes 100 instruction cycles (98 instruction cycles
plus the 2 that are executed every iteration to determine whether or not timer 0 has overflowed).
If were in 16-bit timer mode, timer 0 will overflow every 65,536 machine cycles. In that time we
would have performed 655 JNB tests for a total of 1310 instruction cycles, plus another 2
instruction cycles to perform the code. So to achieve our goal weve spent 1312 instruction
cycles. So 2.002% of our time is being spent just checking when to toggle P3.0. And our code is
ugly because we have to make that check every iteration of our main program loop.
Luckily, this isnt necessary. Interrupts let us forget about checking for the condition. The
microcontroller itself will check for the condition automatically and when the condition is met
will jump to a subroutine (called an interrupt handler), execute the code, then return. In this case,
our subroutine would be nothing more than:
CPL P3.0
RETI
First, youll notice the CLR TF0 command has disappeared. Thats because when the 8051
executes our "timer 0 interrupt routine," it automatically clears the TF0 flag. Youll also notice
that instead of a normal RET instruction we have a RETI instruction. The RETI instruction does
the same thing as a RET instruction, but tells the 8051 that an interrupt routine has finished. You
must always end your interrupt handlers with RETI.
Thus, every 65536 instruction cycles we execute the CPL instruction and the RETI instruction.
Those two instructions together require 3 instruction cycles, and weve accomplished the same
goal as the first example that required 1312 instruction cycles. As far as the toggling of P3.0
goes, our code is 437 times more efficient! Not to mention its much easier to read and understand
because we dont have to remember to always check for the timer 0 flag in our main program. We
just setup the interrupt and forget about it, secure in the knowledge that the 8051 will execute our
code whenever its necessary.
The same idea applies to receiving data via the serial port. One way to do it is to continuously
check the status of the RI flag in an endless loop. Or we could check the RI flag as part of a
larger program loop. However, in the latter case we run the risk of missing characters--what
happens if a character is received right after we do the check, the rest of our program executes,
and before we even check RI a second character has come in. We will lose the first character.
With interrupts, the 8051 will put the main program "on hold" and call our special routine to
handle the reception of a character. Thus, we neither have to put an ugly check in our main code
nor will we lose characters.
We can configure the 8051 so that any of the following events will cause an interrupt:
Timer 0 Overflow.
Timer 1 Overflow.
Reception/Transmission of Serial Character.
External Event 0.
External Event 1.
In other words, we can configure the 8051 so that when Timer 0 Overflows or when a character
is sent/received, the appropriate interrupt handler routines are called.
Obviously we need to be able to distinguish between various interrupts and executing different
code depending on what interrupt was triggered. This is accomplished by jumping to a fixed
address when a given interrupt occurs.
By consulting the above chart we see that whenever Timer 0 overflows (i.e., the TF0 bit is set),
the main program will be temporarily suspended and control will jump to 000BH. It is assumed
that we have code at address 000BH that handles the situation of Timer 0 overflowing.
Setting Up Interrupts
By default at powerup, all interrupts are disabled. This means that even if, for example, the TF0
bit is set, the 8051 will not execute the interrupt. Your program must specifically tell the 8051
that it wishes to enable interrupts and specifically which interrupts it wishes to enable.
Your program may enable and disable interrupts by modifying the IE SFR (A8h):
As you can see, each of the 8051s interrupts has its own bit in the IE SFR. You enable a given
interrupt by setting the corresponding bit. For example, if you wish to enable Timer 1 Interrupt,
you would execute either:
MOV IE,#08h
or
SETB ET1
Both of the above instructions set bit 3 of IE, thus enabling Timer 1 Interrupt. Once Timer 1
Interrupt is enabled, whenever the TF1 bit is set, the 8051 will automatically put "on hold" the
main program and execute the Timer 1 Interrupt Handler at address 001Bh.
However, before Timer 1 Interrupt (or any other interrupt) is truly enabled, you must also set bit
7 of IE. Bit 7, the Global Interupt Enable/Disable, enables or disables all interrupts
simultaneously. That is to say, if bit 7 is cleared then no interrupts will occur, even if all the other
bits of IE are set. Setting bit 7 will enable all the interrupts that have been selected by setting
other bits in IE. This is useful in program execution if you have time-critical code that needs to
execute. In this case, you may need the code to execute from start to finish without any interrupt
getting in the way. To accomplish this you can simply clear bit 7 of IE (CLR EA) and then set it
after your time-criticial code is done.
So, to sum up what has been stated in this section, to enable the Timer 1 Interrupt the most
common approach is to execute the following two instructions:
SETB ET1
SETB EA
Thereafter, the Timer 1 Interrupt Handler at 01Bh will automatically be called whenever the TF1
bit is set (upon Timer 1 overflow).
Polling Sequence
The 8051 automatically evaluates whether an interrupt should occur after every instruction.
When checking for interrupt conditions, it checks them in the following order:
External 0 Interrupt
Timer 0 Interrupt
External 1 Interrupt
Timer 1 Interrupt
Serial Interrupt
This means that if a Serial Interrupt occurs at the exact same instant that an External 0 Interrupt
occurs, the External 0 Interrupt will be executed first and the Serial Interrupt will be executed
once the External 0 Interrupt has completed.
Interrupt Priorities
The 8051 offers two levels of interrupt priority: high and low. By using interrupt priorities you
may assign higher priority to certain interrupt conditions.
For example, you may have enabled Timer 1 Interrupt which is automatically called every time
Timer 1 overflows. Additionally, you may have enabled the Serial Interrupt which is called every
time a character is received via the serial port. However, you may consider that receiving a
character is much more important than the timer interrupt. In this case, if Timer 1 Interrupt is
already executing you may wish that the serial interrupt itself interrupts the Timer 1 Interrupt.
When the serial interrupt is complete, control passes back to Timer 1 Interrupt and finally back
to the main program. You may accomplish this by assigning a high priority to the Serial Interrupt
and a low priority to the Timer 1 Interrupt.
Interrupt priorities are controlled by the IP SFR (B8h). The IP SFR has the following format:
Nothing can interrupt a high-priority interrupt--not even another high priority interrupt.
A high-priority interrupt may interrupt a low-priority interrupt.
A low-priority interrupt may only occur if no other interrupt is already executing.
If two interrupts occur at the same time, the interrupt with higher priority will execute
first. If both interrupts are of the same priority the interrupt which is serviced first by
polling sequence will be executed first.
Take special note of the third step: If the interrupt being handled is a Timer or External interrupt,
the microcontroller automatically clears the interrupt flag before passing control to your interrupt
handler routine. This means it is not necessary that you clear the bit in your code.
An interrupt ends when your program executes the RETI (Return from Interrupt) instruction.
When the RETI instruction is executed the following actions are taken by the microcontroller:
Two bytes are popped off the stack into the Program Counter to restore normal program
execution.
Interrupt status is restored to its pre-interrupt status.
Serial Interrupts
Serial Interrupts are slightly different than the rest of the interrupts. This is due to the fact that
there are two interrupt flags: RI and TI. If either flag is set, a serial interrupt is triggered. As you
will recall from the section on the serial port, the RI bit is set when a byte is received by the
serial port and the TI bit is set when a byte has been sent.
This means that when your serial interrupt is executed, it may have been triggered because the RI
flag was set or because the TI flag was set--or because both flags were set. Thus, your routine
must check the status of these flags to determine what action is appropriate. Also, since the 8051
does not automatically clear the RI and TI flags 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, its because the RI bit *was* set
CLR RI ;Clear the RI bit after weve 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 status of both interrupts flags. If both flags were set, both
sections of code will be executed. Also note that each section of code clears its corresponding
interrupt flag. If you forget to clear the interrupt bits, the serial interrupt will be executed over
and over until you clear the bit. Thus it is very important that you always clear the interrupt flags
in a serial interrupt.
One very important rule applies to all interrupt handlers: Interrupts must leave the processor in
the same state as it was in when the interrupt initiated.
Remember, the idea behind interrupts is that the main program isnt aware that they are executing
in the "background." However, consider the following code:
After the above three instructions are executed, the accumulator will contain a value of 35h.
But what would happen if right after the MOV instruction an interrupt occured. During this
interrupt, the carry bit was set and the value of the accumulator was changed to 40h. When the
interrupt finished and control was passed back to the main program, the ADDC would add 10h to
40h, and additionally add an additional 1h because the carry bit is set. In this case, the
accumulator will contain the value 51h at the end of execution.
In this case, the main program has seemingly calculated the wrong answer. How can 25h + 10h
yield 51h as a result? It doesnt make sense. A programmer that was unfamiliar with interrupts
would be convinced that the microcontroller was damaged in some way, provoking problems
with mathematical calculations.
What has happened, in reality, is the interrupt did not protect the registers it used. Restated: An
interrupt must leave the processor in the same state as it was in when the interrupt initiated.
What does this mean? It means if your interrupt uses the accumulator, it must insure that the
value of the accumulator is the same at the end of the interrupt as it was at the beginning. This is
generally accomplished with a PUSH and POP sequence. For example:
PUSH ACC
PUSH PSW
MOV A,#0FFh
ADD A,#02h
POP PSW
POP ACC
The guts of the interrupt is the MOV instruction and the ADD instruction. However, these two
instructions modify the Accumulator (the MOV instruction) and also modify the value of the
carry bit (the ADD instruction will cause the carry bit to be set). Since an interrupt routine must
guarantee that the registers remain unchanged by the routine, the routine pushes the original
values onto the stack using the PUSH instruction. It is then free to use the registers it protected to
its hearts content. Once the interrupt has finished its task, it pops the original values back into the
registers. When the interrupt exits, the main program will never know the difference because the
registers are exactly the same as they were before the interrupt executed.
PSW
DPTR (DPH/DPL)
PSW
ACC
B
Registers R0-R7
Remember that PSW consists of many individual bits that are set by various 8051 instructions.
Unless you are absolutely sure of what you are doing and have a complete understanding of what
instructions set what bits, it is generally a good idea to always protect PSW by pushing and
popping it off the stack at the beginning and end of your interrupts.
Note also that most assemblers (in fact, ALL assemblers that I know of) will not allow you to
execute the instruction:
PUSH R0
This is due to the fact that depending on which register bank is selected, R0 may refer to either
internal ram address 00h, 08h, 10h, or 18h. R0, in and of itself, is not a valid memory address
that the PUSH and POP instructions can use.
Thus, if you are using any "R" register in your interrupt routine, you will have to push that
registers absolute address onto the stack instead of just saying PUSH R0. For example, instead
of PUSH R0 you would execute:
PUSH 00h
Of course, this only works if youve selected the default register set. If you are using an alternate
register set, you must PUSH the address which corresponds to the register you are using.
If you are using interrupts and your program is crashing or does not seem to be performing as
you would expect, always review the following interrupt-related issues:
Register Protection: Make sure you are protecting all your registers, as explained above.
If you forget to protect a register that your main program is using, very strange results
may occur. In our example above we saw how failure to protect registers caused the
main program to apparently calculate that 25h + 10h = 51h. If you witness problems
with registers changing values unexpectedly or operations producing "incorrect" values,
it is very likely that you've forgotten to protect registers. ALWAYS PROTECT
YOUR REGISTERS.
Forgetting to restore protected values: Another common error is to push registers onto
the stack to protect them, and then forget to pop them off the stack before exiting the
interrupt. For example, you may push ACC, B, and PSW onto the stack in order to
protect them and subsequently pop only ACC and PSW off the stack before exiting. In
this case, since you forgot to restore the value of "B", an extra value remains on the
stack. When you execute the RETI instruction the 8051 will use that value as the return
address instead of the correct value. In this case, your program will almost certainly
crash. ALWAYS MAKE SURE YOU POP THE SAME NUMBER OF VALUES
OFF THE STACK AS YOU PUSHED ONTO IT.
Using RET instead of RETI: Remember that interrupts are always terminated with the
RETI instruction. It is easy to inadvertantly use the RET instruction instead. However,
the RET instruction will not end your interrupt. Usually, using a RET instead of a RETI
will cause the illusion of your main program running normally, but your interrupt will
only be executed once. If it appears that your interrupt mysteriously stops executing,
verify that you are exiting with RETI.
8052 Tutorial
The 8052 microcontroller is the 8051's "big brother." It is a slightly more powerful
microcontroller, sporting a number of additional features which the developer may make use of:
That's really about all there is to the difference between the 8051 and 8052. The remainder of this
tutorial will explain these additional features offered by the 8052, and how they are used within
user programs. Throughout this tutorial, it is assumed that you already have read the 8051
Tutorial and have a thorough understanding of it.
The standard 8051 microcontroller contains 128 bytes of Internal RAM that are available to the
developer as working memory for variables and/or for the operating stack. Instructions that refer
to addresses in the range of 00h through 7Fh refer to the 8051's Internal RAM, while addresses
in the range of 80h through FFh refer to Special Function Registers (SFRs).
Although the 8052 has 256 bytes of Internal RAM, the above method of referrencing them
remains true. Any address between 00h and 7Fh refers to Internal RAM whereas address in the
range of 80h through FFh refer to SFRs.
The 8052's additional Internal RAM may only be referred by Indirect Addressing. Indirect
addressing always refers to Internal RAM, never to an SFR.
Thus, to read the value contained in Internal RAM address 90h, the developer would need to
code something along the lines of the following:
It is very important to understand that the above code is not the same as the following:
In addition to the 8051's standard 21 SFRs, the 8052 adds an additional 5 SFRs related to the
8052's third timer. All of the original 8051 SFRs function exactly as they do in the 8051-the
8052 simply adds new SFRs, it doesn't change the definition of the standard SFRs.
The five new SFRs are in the range of C8h to CDh (SFR C9h is not defined).
T2CON SFR
The operation of Timer 2 (T2) is controlled almost entirely by the T2CON SFR, at address C8h.
Note that since this SFR is evenly divisible by 8 that it is bit-addressable.
BIT
BIT NAME ADDRESS DESCRIPTION
Timer 2 Overflow. This bit is set when T2 overflows. When
T2 interrupt is enabled, this bit will cause the interrupt to be
7 TF2 CFh
triggered. This bit will not be set if either TCLK or RCLK bits
are set.
Timer 2 External Flag. Set by a reload or capture caused by a
1-0 transition on T2EX (P1.1), but only when EXEN2 is set.
6 EXF2 CEh
When T2 interrupt is enabled, this bit will cause the interrupt to
be triggered.
Timer 2 Receive Clock. When this bit is set, Timer 2 will be
5 RCLK CDh used to determine the serial port receive baud rate. When clear,
Timer 1 will be used.
Timer 2 Receive Clock. When this bit is set, Timer 2 will be
4 TCLK CCh used to determine the serial port transmit baud rate. When
clear, Timer 1 will be used.
Timer 2 External Enable. When set, a 1-0 transition on T2EX
3 EXEN2 CBh
(P1.1) will cause a capture or reload to occur.
Timer 2 Run. When set, timer 2 will be turned on. Otherwise,
2 TR2 CAh
it is turned off.
Timer 2 Counter/Interval Timer. If clear, Timer 2 is an
1 C/T2 C9h interval counter. If set, Timer 2 is incremented by 1-0 transition
on T2 (P1.0).
Timer 2 Capture/Reload. If clear, auto reload occurs on timer
0 CP/RL2 C8h 2 overflow, or T2EX 1-0 transition if EXEN2 is set. If set, a
capture will occur on a 1-0 transition of T2EX if EXEN2 is set.
With the standard 8051, Timer 1 is the only timer which may be used to determine the baud rate
of the serial port. Additionally, the receive and transmit baud rate must be the same.
With the 8052, however, the user may configure the serial port to receive at one baud rate and
transmit with another. For example, if RCLK is set and TCLK is cleared, serial data will be
received at the baud rate determined by Timer 2 whereas the baud rate of transmitted data will be
determined by Timer 1.
Determining the auto-reload values for a specific baud rate is discussed in Serial Port Operation;
the only difference is that in the case of Timer 2, the auto-reload value is placed in RCAP2H and
RCAP2L, and the value is a 16-bit value rather than an 8-bit value.
NOTE: When Timer 2 is used as a baud rate generator (either TCLK or RCLK are set),
the Timer 2 Overflow Flag (TF2) will not be set.
To operate Timer 2 in auto-reload mode, the CP/RL2 bit (T2CON.0) must be clear. In this mode,
Timer 2 (TH2/TL2) will be reloaded with the reload value (RCAP2H/RCAP2L) whenever Timer
2 overflows; that is to say, whenever Timer 2 overflows from FFFFh back to 0000h. An
overflow of Timer 2 will cause the TF2 bit to be set, which will cause an interrupt to be
triggered, if Timer 2 interrupt is enabled. Note that TF2 will not be set on an overflow condition
if either RCLK or TCLK (T2CON.5 or T2CON.4) are set.
Additionally, by also setting EXEN2 (T2CON.3), a reload will also occur whenever a 1-0
transition is detected on T2EX (P1.1). A reload which occurs as a result of such a transition will
cause the EXF2 (T2CON.6) flag to be set, triggering a Timer 2 interrupt if said interrupt has
been enabled.
A new mode specific to Timer 2 is called "Capture Mode." As the name implies, this mode
captures the value of Timer 2 (TH2 and TL2) into the capture SFRs (RCAP2H and RCAP2L).
To put Timer 2 in capture mode, CP/RL2 (T2CON.0) must be set, as must be EXEN2
(T2CON.3).
When configured as mentioned above, a capture will occur whenever a 1-0 transition is detected
on T2EX (P1.1). At the moment the transition is detected, the current values of TH2 and TL2
will be copied into RCAP2H and RCAP2L, respectively. At the same time, the EXF2
(T2CON.6) bit will be set, which will trigger an interrupt if Timer 2 interrupt is enabled.
NOTE 1: Note that even in capture mode, an overflow of Timer 2 will result in TF2
being set and an interrupt being triggered.
NOTE 2: Capture mode is an efficient way to measure the time between events. At the
moment that an event occurs, the current value of Timer 2 will be copied into
RCAP2H/L. However, Timer 2 will not stop and an interrupt will be triggered. Thus
your interrupt routine may copy the value of RCAP2H/L to a temporary holding
variable without having to stop Timer 2. When another capture occurs, your interrupt
can take the difference of the two values to determine the time transpired. Again, the
main advantage is that you don't have to stop timer 2 to read its value, as is the case
with timer 0 and timer 1.
TIMER 2 INTERRUPT
As is the case with the other two timers, timer 2 can be configured to trigger and interrupt. In
fact, the text above indicates a number of situations that can trigger a timer 2 interrupt.
To enable Timer 2 interrupt, set ET2 (IE.5). This bit of IE is only valid on an 8052. Similarly, the
priority of Timer 2 interrupt can be configured using PT2 (IP.5). As always, be sure to also set
EA (IE.7) when enabling any interrupt.
Once Timer 2 interrupt has been enabled, a Timer 2 interrupt will be triggered whenever TF2
(T2CON.7) or EXF2 (T2CON.6) are set. The Timer 2 Interrupt routine must be placed at 002Bh
in code memory.
NOTE: Like the Serial Interrupt, Timer 2 interrupt does not clear the interrupt flag
that triggered the interrupt. Since there are two conditions that can trigger a Timer
2 interrupt, either TF2 or EXF2 being set, the microcontroller leaves the flags
alone so that your interrupt routine can determine the source of the interrupt and
act accordingly. It is possible (and even probable!) that you will want to do one
thing when the timer overflows and something completely different when a
capture or reload is triggered by an external event. Thus, be sure to always clear
TF2 and EXF2 in your Timer 2 Interrupt. Failing to do so will cause the interrupt
to be triggered repeatedly until the bits are cleared.
16-Bit Addition
16-bit addition is the addition of two 16-values. First, we must recognize that the addition of two
16-bit values will result in a value that is, at most, 17 bits long. Why is this so? The largest value
that can fit in 16-bits is 256 * 256 - 1 = 65,535. If we add 65,535 + 65,535, we get the result of
131,070. This value fits in 17 bits. Thus when adding two 16-bit values, we will get a 17-bit
value. Since the 8051 works with 8-bit values, we will use the following statement: "Adding two
16-bit values results in a 24-bit value". Of course, 7 of the highest 8 bits will never be used--but
we will have our entire answer in 3 bytes. Also keep in mind that we will be working with
unsigned integers.
Programming Tip: Another option, instead of using 3 full bytes for the answer, is
to use 2 bytes (16-bits) for the answer, and the carry bit ( C ), to hold the 17th bit.
This is perfectly acceptable, and probably even preferred. The more advanced
programmer will understand and recognize this option, and be able to make use of
it. However, since this is an introduction to 16-bit mathematics it is our goal that
the answer produced by the routines be in a form that is easy for the reader to
utilize, once calculated. It is our belief that this is best achieved by leaving the
answer fully expressed in 3 8-bit values.
Let's consider adding the following two decimal values: 6724 + 8923. The answer is, of course,
15647. How do we go about adding these values with the 8051? The first step is to always work
with hexadecimal values. Simlply convert the two values you wish to add to hexadecimal. In this
case, that is equivalent to the following hexadecimal addition: 1A44 + 22DB.
How do we add thes two numbers? Let's use the exact same method we used in primary school,
and in the previous section:
. 256's 1's
. 1A 44
+ 22 DB
= 3D 1F
First, notice the difference. We are no longer working with a 1's, 10's, and 100's columns. We are
just working with two columns: The 1's column and the 256's column. In familiar computer
terms: We're working with the low byte (the 1's column) and the high byte (the 256's column).
However, the process is exactly the same.
First we add the values in the 1's column (low byte): 44 + DB = 11F. Only a 2-digit hexadecimal
value can fit in a single column, so we leave the 1F in the low-byte column, and carry the 1 to
the high-byte column. We now add the high bytes: 1A + 22 = 3C, plus the 1 we carried from the
low-byte column. We arrive at the value 3D.
Thus, our completed answer is 3D1F. If we convert 3D1F back to decimal, we arrive at the
answer 15647. This matches with the original addition we did in decimal. The process works.
Thus the only challenge is to code the above process into 8051 assembly language. As it turns
out, this is incredibly easy.
We'll use the following table to explain how we're going to do the addition:
1. Add the low bytes R7 and R5, leave the answer in R3.
2. Add the high bytes R6 and R4, adding any carry from step 1, and leave the answer in R2.
3. Put any carry from step 2 in the final byte, R1.
We'll now convert the above process to assembly language, step by step.
Step 1: Add the low bytes R7 and R5, leave the answer in R3.
Step 2: Add the R6 and R4, add carry, leave the answer in R2.
Step 3: Put any carry from step 2 in the final byte, R1.
That's it! Combining the code from the three steps, we come up with the following subroutine:
ADD16_16:
;Step 1 of the process
MOV A,R7 ;Move the low-byte into the accumulator
ADD A,R5 ;Add the second low-byte to the accumulator
MOV R3,A ;Move the answer to the low-byte of the result
And to call our routine to add the two values we used in the example above, we'd use the code:
o 16-bit subtraction
16-bit Subtraction
16-bit subtraction is the subtraction of one 16-bit value from another. A subtraction of this nature
results in another 16-bit value. Why? The number 65535 is a 16-bit value. If we subtract 1 from
it, we have 65534 which is also a 16-bit value. Thus any 16-bit subtraction will result in another
16-bit value.
Let's consider the subtraction of the following two decimal values: 8923 - 6905. The answer is
2018. How do we go about subtracting these values with the 8051? As is the case with addition,
the first step is to convert the expression to hexadecimal. The above decimal subtraction is
equivalent to the following hexadecimal subtraction: 22DB - 1AF9.
. 256's 1's
. 22 DB
- 1A F9
= 07 E2
First we subtract the second value in the 1's column (low byte): DB - F9. Since F9 is greater than
DB, we need to "borrow" from the 256's column. Thus we actually perform the subtraction 1DB
- F9 = E2. The value E2 is what we leave in the 1's column.
Now we must perform the subtraction 22 - 1A. However, we must remember that we "borrowed"
1 from the 256's column, so we must subtract an additional 1. So the subtraction for the 256's
column becomes 22 - 1A - 1 = 7, which is the value we leave in the 256's column.
Thus our final answer is 07E2. If we conver this back to decimal, we get the value 2018, which
coincides with the math we originally did in decimal.
As we did with addition, we'll use a small table to help us conver the above process to 8051
assembly language:
. 256's 1's
. R6 R7
+ R4 R5
= R2 R3
Since we're subtracting 16-bit values, each value requires two 8-bit registers. Essentially, the
value to be subtracted from will be held in R6 and R7 (the high byte in R6 and the low byte in
R7) while the value to be subtracted will be held in R4 and R5 (the high byte in R4 and the low
byte in R5). We will leave our answer in R2, and R3.
1. Subtract the low bytes R5 from R7, leave the answer in R3.
2. Subtract the high byte R4 from R6, less any borrow, and leave the answer in R2.
We'll now convert the above process to assembly language, step by step.
Step 1: Subtract the low bytes R5 from R7, leave the answer in R3.
MOV A,R7 ;Move the low-byte into the accumulator
CLR C ;Always clear carry before first subtraction
SUBB A,R5 ;Subtract the second low-byte from the accumulator
MOV R3,A ;Move the answer to the low-byte of the result
Step 2: Subtract the high byte R4 from R6, less any borrow, and leave the answer in R2.
Programming Tip: The SUBB instruction always subtracts the second value in
the instruction from the first, less any carry. While there are two versions of the
ADD instruction (ADD and ADDC), one of which ignores the carry bit, there is no
such distinction with the SUBB instruction. This means before you perform the
first subtraction, you must always be sure to clear the carry bit. Otherwise, if the
carry bit happens to be set you'll end up subtracting it from your first column value
-- which would be incorrect.
Combining the code from the two steps above, we come up with the following subroutine:
SUBB16_16:
;Step 1 of the process
MOV A,R7 ;Move the low-byte into the accumulator
CLR C ;Always clear carry before first subtraction
SUBB A,R5 ;Subtract the second low-byte from the accumulator
MOV R3,A ;Move the answer to the low-byte of the result
And to call our routine to subtract the two values we used in the example above, we'd use the
code:
o 16-bit multiplication
16-bit Multiplication
16-bit multiplication is the multiplication of two 16-bit value from another. Such a multiplication
results in a 32-bit value.
For the sake of example, let's multiply 25,136 by 17,198. The answer is 432,288,928. As with
both addition and subtraction, let's first convert the expression into hexadecimal: 6230h x
432Eh.
Once again, let's arrange the numbers in columns as we did in primary school to multiply
numbers, although now the grid becomes more complicated. The green section represents the
original two values. The yellow section represents the intermediate calculations obtained by
multipying each byte of the original values. The red section of the grid indicates our final
answer, obtained by summing the columns in the yellow area.
We'll now convert the above process to assembly language, step by step.
Combining the code from the two steps above, we come up with the following subroutine:
MUL16_16:
;Multiply R5 by R7
MOV A,R5 ;Move the R5 into the Accumulator
MOV B,R7 ;Move R7 into B
MUL AB ;Multiply the two values
MOV R2,B ;Move B (the high-byte) into R2
MOV R3,A ;Move A (the low-byte) into R3
;Multiply R5 by R6
MOV A,R5 ;Move R5 back into the Accumulator
MOV B,R6 ;Move R6 into B
MUL AB ;Multiply the two values
ADD A,R2 ;Add the low-byte into the value already in R2
MOV R2,A ;Move the resulting value back into R2
MOV A,B ;Move the high-byte into the accumulator
ADDC A,#00h ;Add zero (plus the carry, if any)
MOV R1,A ;Move the resulting answer into R1
MOV A,#00h ;Load the accumulator with zero
ADDC A,#00h ;Add zero (plus the carry, if any)
MOV R0,A ;Move the resulting answer to R0.
;Multiply R4 by R7
MOV A,R4 ;Move R4 into the Accumulator
MOV B,R7 ;Move R7 into B
MUL AB ;Multiply the two values
ADD A,R2 ;Add the low-byte into the value already in R2
MOV R2,A ;Move the resulting value back into R2
MOV A,B ;Move the high-byte into the accumulator
ADDC A,R1 ;Add the current value of R1 (plus any carry)
MOV R1,A ;Move the resulting answer into R1.
MOV A,#00h ;Load the accumulator with zero
ADDC A,R0 ;Add the current value of R0 (plus any carry)
MOV R0,A ;Move the resulting answer to R1.
;Multiply R4 by R6
MOV A,R4 ;Move R4 back into the Accumulator
MOV B,R6 ;Move R6 into B
MUL AB ;Multiply the two values
ADD A,R1 ;Add the low-byte into the value already in R1
MOV R1,A ;Move the resulting value back into R1
MOV A,B ;Move the high-byte into the accumulator
ADDC A,R0 ;Add it to the value already in R0 (plus any carry)
MOV R0,A ;Move the resulting answer back to R0
And to call our routine to multiply the two values we used in the example above, we'd use the
code:
16-bit division is the division of one 16-bit value by another 16-bit value, returning a 16-
bit quotient and a 16-bit remainder. I used r1/r0 for dividend/remainder and r3/r2 for
divisor/quotient.
Programming Tip: The number of bits in the quotient and the remainder can
never be larger than the number of bits in the original divident. For example, if
you are dividing a 16-bit value by a 2-bit value, both the quotient and the
remainder must be able to handle a 16-bit result. If you are dividing a 24-bit value
by a 16-bit value, the quotient and remainder must both be able to handle a 24-bit
result.
So, again, let's remember how we did division in elementary school. For example, 179
divided by 8:
1 7 9 / 8 = 22 (quotient)
1 6
---
1 9
1 6
---
3 (remainder)
It's necessary necessary to follow this same process step by step. There is a 3-digit-
dividend, so we expect 3 digits maximum for quotient. We "shift left" the divisor 2 digits
(3-1) such that the number of digits in the divisor is the same as the number of digits in
the dividend. So we get:
179/800=???
We divide the two numbers, multiply the result by the divisor and substract this result
from the dividend. In this first step 179 can't be divided by 800, so the the result is 0. We
subtract 0 from 179 and still have 179:
1 7 9 / 8 0 0 = 0 ? ?
0
-----
1 7 9
We then "shift right" the divisor 1 digit and repeat the process. 179 divided by 80 results
in an answer of 2. After we subtract 160 (2x80) we are left with a remainder of 19:
1 7 9 / 8 0 = 0 2 ?
1 6 0
-----
1 9
We repeat the process again until the divisor has shifted into its original position:
1 7 9 : 8 = 0 2 2
1 6 0
-----
1 9
1 6
-----
3
This may have been an unnecessary review of elementary school math, but it is important
to remember exactly how the process is performed because we do exactly the same with
the 8052 in binary system.
In this routine we will place the original dividend into R1 (high-byte) and R0 (low-byte)
and the divisor in R3 (high-byte) and R2 (low-byte).
In the case of our example (179 divided by 8), the initial registers would be:
R1/R0 00000000 10110011
R3/R2 00000000 00001000
Step 1. Shift left the divisor.
MOV B,#00h ;Clear B since B will count the number of left-shifted bits
div1:
INC B ;Increment counter for each left shift
MOV A,R2 ;Move the current divisor low byte into the accumulator
RLC A ;Shift low-byte left, rotate through carry to apply highest bit
to high-byte
MOV R2,A ;Save the updated divisor low-byte
MOV A,R3 ;Move the current divisor high byte into the accumulator
RLC A ;Shift high-byte left high, rotating in carry from low-byte
MOV R3,A ;Save the updated divisor high-byte
JNC div1 ;Repeat until carry flag is set from high-byte
In the case of our example, once the above code is executed the registers will be as
follows (including the carry bit 'C'):
C/R1/R0 0 00000000 10110011
C/R3/R2 1 00000000 00000000
At this point we can do the division itself. As we are in binary mode there is no need for
a real division--it's just a comparison. At this point it's important to know the steps from
above.
Step 2. Shift left the divisor.
To see how the loop works here are the registers after each step:
1 r1/0 00000000 10110011 ;dividend
r3/2 10000000 00000000 ;divisor
r5/4 00000000 00000000 ;result
...
div16_16:
CLR C ;Clear carry initially
MOV R4,#00h ;Clear R4 working variable initially
MOV R5,#00h ;CLear R5 working variable initially
MOV B,#00h ;Clear B since B will count the number of left-shifted bits
div1:
INC B ;Increment counter for each left shift
MOV A,R2 ;Move the current divisor low byte into the accumulator
RLC A ;Shift low-byte left, rotate through carry to apply highest bit
to high-byte
MOV R2,A ;Save the updated divisor low-byte
MOV A,R3 ;Move the current divisor high byte into the accumulator
RLC A ;Shift high-byte left high, rotating in carry from low-byte
MOV R3,A ;Save the updated divisor high-byte
JNC div1 ;Repeat until carry flag is set from high-byte
div2: ;Shift right the divisor
MOV A,R3 ;Move high-byte of divisor into accumulator
RRC A ;Rotate high-byte of divisor right and into carry
MOV R3,A ;Save updated value of high-byte of divisor
MOV A,R2 ;Move low-byte of divisor into accumulator
RRC A ;Rotate low-byte of divisor right, with carry from high-byte
MOV R2,A ;Save updated value of low-byte of divisor
CLR C ;Clear carry, we don't need it anymore
MOV 07h,R1 ;Make a safe copy of the dividend high-byte
MOV 06h,R0 ;Make a safe copy of the dividend low-byte
MOV A,R0 ;Move low-byte of dividend into accumulator
SUBB A,R2 ;Dividend - shifted divisor = result bit (no factor, only 0 or
1)
MOV R0,A ;Save updated dividend
MOV A,R1 ;Move high-byte of dividend into accumulator
SUBB A,R3 ;Subtract high-byte of divisor (all together 16-bit
substraction)
MOV R1,A ;Save updated high-byte back in high-byte of divisor
JNC div3 ;If carry flag is NOT set, result is 1
MOV R1,07h ;Otherwise result is 0, save copy of divisor to undo subtraction
MOV R0,06h
div3:
CPL C ;Invert carry, so it can be directly copied into result
MOV A,R4
RLC A ;Shift carry flag into temporary result
MOV R4,A
MOV A,R5
RLC A
MOV R5,A
DJNZ B,div2 ;Now count backwards and repeat until "B" is zero
MOV R3,05h ;Move result to R3/R2
MOV R2,04h ;Move result to R3/R2
RET
LCD Backgorund
Frequently, an 8051 program must interact with the outside world using input and output
devices that communicate directly with a human being. One of the most common devices
attached to an 8051 is an LCD display. Some of the most common LCDs connected to
the 8051 are 16x2 and 20x2 displays. This means 16 characters per line by 2 lines and 20
characters per line by 2 lines, respectively.
Fortunately, a very popular standard exists which allows us to communicate with the vast
majority of LCDs regardless of their manufacturer. The standard is referred to as
HD44780U, which refers to the controller chip which receives data from an external
source (in this case, the 8051) and communicates directly with the LCD.
44780 BACKGROUND
The 44780 standard requires 3 control lines as well as either 4 or 8 I/O lines for the data
bus. The user may select whether the LCD is to operate with a 4-bit data bus or an 8-bit
data bus. If a 4-bit data bus is used the LCD will require a total of 7 data lines (3 control
lines plus the 4 lines for the data bus). If an 8-bit data bus is used the LCD will require a
total of 11 data lines (3 control lines plus the 8 lines for the data bus).
The three control lines are referred to as EN, RS, and RW.
The EN line is called "Enable." This control line is used to tell the LCD that you are
sending it data. To send data to the LCD, your program should make sure this line is low
(0) and then set the other two control lines and/or put data on the data bus. When the
other lines are completely ready, bring EN high (1) and wait for the minimum amount of
time required by the LCD datasheet (this varies from LCD to LCD), and end by bringing
it low (0) again.
The RS line is the "Register Select" line. When RS is low (0), the data is to be treated as
a command or special instruction (such as clear screen, position cursor, etc.). When RS is
high (1), the data being sent is text data which sould be displayed on the screen. For
example, to display the letter "T" on the screen you would set RS high.
The RW line is the "Read/Write" control line. When RW is low (0), the information on
the data bus is being written to the LCD. When RW is high (1), the program is
effectively querying (or reading) the LCD. Only one instruction ("Get LCD status") is a
read command. All others are write commands--so RW will almost always be low.
Finally, the data bus consists of 4 or 8 lines (depending on the mode of operation selected
by the user). In the case of an 8-bit data bus, the lines are referred to as DB0, DB1, DB2,
DB3, DB4, DB5, DB6, and DB7.
AN EXAMPLE HARDWARE CONFIGURATION
As we've mentioned, the LCD requires either 8 or 11 I/O lines to communicate with. For
the sake of this tutorial, we are going to use an 8-bit data bus--so we'll be using 11 of the
8051's I/O pins to interface with the LCD.
Let's draw a sample psuedo-schematic of how the LCD will be connected to the 8051.
As you can see, we've established a 1-to-1 relation between a pin on the 8051 and a line
on the 44780 LCD. Thus as we write our assembly program to access the LCD, we are
going to equate constants to the 8051 ports so that we can refer to the lines by their
44780 name as opposed to P0.1, P0.2, etc. Let's go ahead and write our initial equates:
DB0 EQU P1.0
DB1 EQU P1.1
DB2 EQU P1.2
DB3 EQU P1.3
DB4 EQU P1.4
DB5 EQU P1.5
DB6 EQU P1.6
DB7 EQU P1.7
EN EQU P3.7
RS EQU P3.6
RW EQU P3.5
DATA EQU P1
Having established the above equates, we may now refer to our I/O lines by their 44780
name. For example, to set the RW line high (1), we can execute the following
insutrction:
SETB RW
HANDLING THE EN CONTROL LINE
As we mentioned above, the EN line is used to tell the LCD that you are ready for it to
execute an instruction that you've prepared on the data bus and on the other control lines.
Note that the EN line must be raised/lowered before/after each instruction sent to the
LCD regardless of whether that instruction is read or write, text or instruction. In short,
you must always manipulate EN when communicating with the LCD. EN is the LCD's
way of knowing that you are talking to it. If you don't raise/lower EN, the LCD doesn't
know you're talking to it on the other lines.
Thus, before we interact in any way with the LCD we will always bring the EN line low
with the following instruction:
CLR EN
And once we've finished setting up our instruction with the other control lines and data
bus lines, we'll always bring this line high:
SETB EN
The line must be left high for the amount of time required by the LCD as specified in its
datasheet. This is normally on the order of about 250 nanoseconds, but check the
datasheet. In the case of a typical 8051 running at 12 MHz, an instruction requires 1.08
microseconds to execute so the EN line can be brought low the very next instruction.
However, faster microcontrollers (such as the DS89C420 which executes an instruction
in 90 nanoseconds given an 11.0592 Mhz crystal) will require a number of NOPs to
create a delay while EN is held high. The number of NOPs that must be inserted depends
on the microcontroller you are using and the crystal you have selected.
The instruction is executed by the LCD at the moment the EN line is brought low with a
final CLR EN instruction.
Programming Tip: The LCD interprets and executes our command at the instant the EN
line is brought low. If you never bring EN low, your instruction will never be executed.
Additionally, when you bring EN low and the LCD executes your instruction, it requires
a certain amount of time to execute the command. The time it requires to execute an
instruction depends on the instruction and the speed of the crystal which is attached to
the 44780's oscillator input.
CHECKING THE BUSY STATUS OF THE LCD
As previously mentioned, it takes a certain amount of time for each instruction to be
executed by the LCD. The delay varies depending on the frequency of the crystal
attached to the oscillator input of the 44780 as well as the instruction which is being
executed.
While it is possible to write code that waits for a specific amount of time to allow the
LCD to execute instructions, this method of "waiting" is not very flexible. If the crystal
frequency is changed, the software will need to be modified. Additionally, if the LCD
itself is changed for another LCD which, although 44780 compatible, requires more time
to perform its operations, the program will not work until it is properly modified.
A more robust method of programming is to use the "Get LCD Status" command to
determine whether the LCD is still busy executing the last instruction received.
The "Get LCD Status" command will return to us two tidbits of information; the
information that is useful to us right now is found in DB7. In summary, when we issue
the "Get LCD Status" command the LCD will immediately raise DB7 if it's still busy
executing a command or lower DB7 to indicate that the LCD is no longer occupied. Thus
our program can query the LCD until DB7 goes low, indicating the LCD is no longer
busy. At that point we are free to continue and send the next command.
Since we will use this code every time we send an instruction to the LCD, it is useful to
make it a subroutine. Let's write the code:
WAIT_LCD:
CLR EN ;Start LCD command
CLR RS ;It's a command
SETB RW ;It's a read command
MOV DATA,#0FFh ;Set all pins to FF initially
SETB EN ;Clock out command to LCD
MOV A,DATA ;Read the return value
JB ACC.7,WAIT_LCD ;If bit 7 high, LCD still busy
CLR EN ;Finish the command
CLR RW ;Turn off RW for future commands
RET
Thus, our standard practice will be to send an instruction to the LCD and then call our
WAIT_LCD routine to wait until the instruction is completely executed by the LCD.
This will assure that our program gives the LCD the time it needs to execute instructions
and also makes our program compatible with any LCD, regardless of how fast or slow it
is.
Programming Tip: The above routine does the job of waiting for the LCD, but
were it to be used in a real application a very definite improvement would need to
be made: as written, if the LCD never becomes "not busy" the program will
effectively "hang," waiting for DB7 to go low. If this never happens, the program
will freeze. Of course, this should never happen and won't happen when the
hardware is working properly. But in a real application it would be wise to put
some kind of time limit on the delay--for example, a maximum of 256 attempts to
wait for the busy signal to go low. This would guarantee that even if the LCD
hardware fails, the program would not lock up.
INITIALIZING THE LCD
Before you may really use the LCD, you must initialize and configure it. This is
accomplished by sending a number of initialization instructions to the LCD.
The first instruction we send must tell the LCD whether we'll be communicating with it
with an 8-bit or 4-bit data bus. We also select a 5x8 dot character font. These two options
are selected by sending the command 38h to the LCD as a command. As you will recall
from the last section, we mentioned that the RS line must be low if we are sending a
command to the LCD. Thus, to send this 38h command to the LCD we must execute the
following 8051 instructions:
CLR RS
MOV DATA,#38h
SETB EN
CLR EN
LCALL WAIT_LCD
Programming Tip: The LCD command 38h is really the sum of a number of
option bits. The instruction itself is the instruction 20h ("Function set"). However,
to this we add the values 10h to indicate an 8-bit data bus plus 08h to indicate that
the display is a two-line display.
We've now sent the first byte of the initialization sequence. The second byte of the
initialization sequence is the instruction 0Eh. Thus we must repeat the initialization code
from above, but now with the instruction. Thus the the next code segment is:
CLR RS
MOV DATA,#0Eh
SETB EN
CLR EN
LCALL WAIT_LCD
Programming Tip: The command 0Eh is really the instruction 08h plus 04h to
turn the LCD on. To that an additional 02h is added in order to turn the cursor on.
The last byte we need to send is used to configure additional operational parameters of
the LCD. We must send the value 06h.
CLR RS
MOV DATA,#06h
SETB EN
CLR EN
LCALL WAIT_LCD
Programming Tip: The command 06h is really the instruction 04h plus 02h to
configure the LCD such that every time we send it a character, the cursor position
automatically moves to the right.
So, in all, our initialization code is as follows:
INIT_LCD:
CLR RS
MOV DATA,#38h
SETB EN
CLR EN
LCALL WAIT_LCD
CLR RS
MOV DATA,#0Eh
SETB EN
CLR EN
LCALL WAIT_LCD
CLR RS
MOV DATA,#06h
SETB EN
CLR EN
LCALL WAIT_LCD
RET
Having executed this code the LCD will be fully initialized and ready for us to send
display data to it.
CLEARING THE DISPLAY
When the LCD is first initialized, the screen should automatically be cleared by the
44780 controller. However, it's always a good idea to do things yourself so that you can
be completely sure that the display is the way you want it. Thus, it's not a bad idea to
clear the screen as the very first opreation after the LCD has been initialiezd.
An LCD command exists to accomplish this function. Not suprisingly, it is the command
01h. Since clearing the screen is a function we very likely will wish to call more than
once, it's a good idea to make it a subroutine:
CLEAR_LCD:
CLR RS
MOV DATA,#01h
SETB EN
CLR EN
LCALL WAIT_LCD
RET
How that we've written a "Clear Screen" routine, we may clear the LCD at any time by
simply executing an LCALL CLEAR_LCD.
Programming Tip: Executing the "Clear Screen" instruction on the LCD also
positions the cursor in the upper left-hand corner as we would expect.
WRITING TEXT TO THE LCD
Now we get to the real meat of what we're trying to do: All this effort is really so we can
display text on the LCD. Really, we're pretty much done.
Once again, writing text to the LCD is something we'll almost certainly want to do over
and over--so let's make it a subroutine.
WRITE_TEXT:
SETB RS
MOV DATA,A
SETB EN
CLR EN
LCALL WAIT_LCD
RET
The WRITE_TEXT routine that we just wrote will send the character in the
accumulator to the LCD which will, in turn, display it. Thus to display text on the LCD
all we need to do is load the accumulator with the byte to display and make a call to this
routine. Pretty easy, huh?
A "HELLO WORLD" PROGRAM
Now that we have all the component subroutines written, writing the classic "Hello
World" program--which displays the text "Hello World" on the LCD is a relatively trivial
matter. Consider:
LCALL INIT_LCD
LCALL CLEAR_LCD
MOV A,#'H'
LCALL WRITE_TEXT
MOV A,#'E'
LCALL WRITE_TEXT
MOV A,#'L'
LCALL WRITE_TEXT
MOV A,#'L'
LCALL WRITE_TEXT
MOV A,#'O'
LCALL WRITE_TEXT
MOV A,#' '
LCALL WRITE_TEXT
MOV A,#'W'
LCALL WRITE_TEXT
MOV A,#'O'
LCALL WRITE_TEXT
MOV A,#'R'
LCALL WRITE_TEXT
MOV A,#'L'
LCALL WRITE_TEXT
MOV A,#'D'
LCALL WRITE_TEXT
The above "Hello World" program should, when executed, initialize the LCD, clear the
LCD screen, and display "Hello World" in the upper left-hand corner of the display.
CURSOR POSITIONING
The above "Hello World" program is simplistic in the sense that it prints its text in the
upper left-hand corner of the screen. However, what if we wanted to display the word
"Hello" in the upper left-hand corner but wanted to display the word "World" on the
second line at the tenth character? This sounds simple--and actually, it is simple.
However, it requires a little more understanding of the design of the LCD.
The 44780 contains a certain amount of memory which is assigned to the display. All the
text we write to the 44780 is stored in this memory, and the 44780 subsequently reads
this memory to display the text on the LCD itself. This memory can be represented with
the following "memory map":
In the above memory map, the area shaded in blue is the visible display. As you can see,
it measures 16 characters per line by 2 lines. The numbers in each box is the memory
address that corresponds to that screen position.
Thus, the first character in the upper left-hanad corner is at address 00h. The following
character position (character #2 on the first line) is address 01h, etc. This continues until
we reach the 16th character of the first line which is at address 0Fh.
However, the first character of line 2, as shown in the memory map, is at address 40h.
This means if we write a character to the last position of the first line and then write a
second character, the second character will not appear on the second line. That is because
the second character will effectively be written to address 10h--but the second line begins
at address 40h.
Thus we need to send a command to the LCD that tells it to position the cursor on the
second line. The "Set Cursor Position" instruction is 80h. To this we must add the
address of the location where we wish to position the cursor. In our example, we said we
wanted to display "World" on the second line on the tenth character position.
Referring again to the memory map, we see that the tenth character position of the
second line is address 4Ah. Thus, before writing the word "World" to the LCD, we must
send a "Set Cursor Position" instruction--the value of this command will be 80h (the
instruction code to position the cursor) plus the address 4Ah. 80h + 4Ah = CAh. Thus
sending the command CAh to the LCD will position the cursor on the second line at the
tenth character position:
CLR RS
MOV DATA,#0CAh
SETB EN
CLR EN
LCALL WAIT_LCD
The above code will position the cursor on line 2, character 10. To display "Hello" in the
upper left-hand corner with the word "World" on the second line at character position 10
just requires us to insert the above code into our existing "Hello World" program. This
results in the following:
LCALL INIT_LCD
LCALL CLEAR_LCD
MOV A,#'H'
LCALL WRITE_TEXT
MOV A,#'E'
LCALL WRITE_TEXT
MOV A,#'L'
LCALL WRITE_TEXT
MOV A,#'L'
LCALL WRITE_TEXT
MOV A,#'O'
LCALL WRITE_TEXT
CLR RS
MOV DATA,#0CAh
SETB EN
CLR EN
LCALL WAIT_LCD
MOV A,#'W'
LCALL WRITE_TEXT
MOV A,#'O'
LCALL WRITE_TEXT
MOV A,#'R'
LCALL WRITE_TEXT
MOV A,#'L'
LCALL WRITE_TEXT
MOV A,#'D'
LCALL WRITE_TEXT
SUMMARY
This tutorial has presented the underlying concepts of programming an LCD display.
Obviously it has not addresses all issues. The 44780 LCD controller offers many other
functions which are accessed using other commands, and some of the commands already
presented include other options that were not discussed here. However, this tutorial
should get you going in the right direction.
This second LCD-tutorial is based on 'Introduction to LCD Programming', so you should to read
that first.
In the first tutorial we have seen that character LCD's based on the HD44780 chip can be driven
in 8bits mode, which requires in total 11 lines from you microcontroller. If we want (or need) to
spare some lines for other purposes it is possible to drive the display in 4bits mode, which
requires 7 lines. It is possible to use only 6 lines, in which case R/W is tied to GrouND. This
configuration is seen many times in projects. Instead of reading the busy flag (which is
somewhat trickier than it is in 8 bit modus) we have to use delay loops. These delayloops have to
be recalculated when using other oscillator frequencies. In this tutorial we use the somewhat
harder solution, making use of the busy flag and being independent of the oscillator frequency.
The only drawback using 4 bits is that commands and data have to be sent in two nibbles (4bit
parts) to the display, which take slightly more time. In many cases that won't be a problem.
To keep things simple, I will take the examples from the first tutorial, make the necessary
changes and only explain the differences.
HARDWARE CONFIGURATION
The only difference with the 8bit version is DB0, DB1, DB2 and DB3 on the displaymodule
side. These lines are not connected to the processor. Leave those lines unconnected, DON'T
SHORT THEM TO GROUND as seen in projects where R/W is tied to ground.
Again, if you want to know how to handle the control lines in your programs, please read the
first tutorial on LCD displays. In 4-bit mode, we have to read and write databytes and
commandbytes in two separate 'nibbles' (4bit parts). To make only minor changes to the original
example, we make two subroutines; one to read two nibbles from the LCD, and the other to write
two nibbles to the LCD. Furthermore, the toggling of the EN-line is also taken to these
subroutines, because we have to toggle for each nibble.
READ_2_NIBBLES:
ORL DATA,#0F0 ;Be sure to release datalines (set outputlatches
;to '1') so we can read the LCD
SETB EN
MOV A,DATA ;Read first part of the return value
(high nibble)
CLR EN
ANL A,#0F0h ;Only high nibble is usable
PUSH ACC
SETB EN
MOV A,DATA ;Read second part of the return value (low nibble)
CLR EN
ANL A,#0F0h ;Only high nibble is usable
SWAP A ;Last received is actually low nibble, so put it
in place
MOV R7,A
POP ACC
ORL A,R7 ;And combine it with low nibble
RET
WRITE_2_NIBBLES:
PUSH ACC ;Save A for low nibble
ORL DATA,#0F0h ;Bits 4..7 <- 1
ORL A,#0Fh ;Don't affect bits 0-3
ANL DATA,A ;High nibble to display
SETB EN
CLR EN
POP ACC ;Prepare to send
SWAP A ;...second nibble
ORL DATA,#0F0h ; Bits 4...7 <- 1
ORL A,#0Fh ; Don't affect bits 0...3
ANL DATA,A ;Low nibble to display
SETB EN
CLR EN
RET
As we see in the WRITE_2_NIBBLES routine, there are some logic instructions (ORL, ANL) so
I/O lines P1.0 to P1.3 are not affected. These lines are thus free for input or output and not
affected by this routine.
WAIT_LCD:
CLR RS ;It's a command
SETB RW ;It's a read command
LCALL READ_2_NIBBLES ;Take two nibbles from LCD in A
JB ACC.7,WAIT_LCD ;If bit 7 high, LCD still busy
CLR RW ;Turn off RW for future commands
RET
The first instruction we send must tell the LCD we'll be communicating with it with a 4-bit data
bus. We also select a 5x8 dot character font. These two options are selected by sending the
command 28h to the LCD as a command. After powering up the LCD, it is in 8-bit mode.
Because only four bits are connected, the first command has to be send twice; the first time to
switch to 4-bits mode, (the lower 4 bits of the command are not seen), the second time to send it
as two nibbles so the lower part is received, too.
CLR RS
CLR RW
CLR EN
SETB EN
MOV DATA,#28h
CLR EN
LCALL WAIT_LCD
MOV A,#28h
LCALL WRITE_2_NIBBLES ;Write A as two separate nibbles to LCD
LCALL WAIT_LCD
Programming Tip: The LCD command 28h is really the sum of a number of
option bits. The instruction itself is the instruction 20h ("Function set"). However,
to this we add the values 0h to indicate a 4-bit data bus plus 08h to indicate that
the display is a two-line display.
We've now sent the first byte of the initialisation sequence. The second byte of the initialisation
sequence is the instruction 0Eh. Thus we must repeat the initialisation code from above, but now
with the instruction. Thus the next code segment is:
MOV A,#0Eh
LCALL WRITE_2_NIBBLES ;Write A as two separate nibbles to LCD
LCALL WAIT_LCD
Programming Tip: The command 0Eh is really the instruction 08h plus 04h to
turn the LCD on. To that an additional 02h is added in order to turn the cursor on.
The last byte we need to send is used to configure additional operational parameters of the LCD.
We must send the value 06h.
MOV A,#06h
LCALL WRITE_2_NIBBLES ;Write A as two separate nibbles to LCD
LCALL WAIT_LCD
Programming Tip: The command 06h is really the instruction 04h plus 02h to
configure the LCD such that every time we send it a character, the cursor position
automatically moves to the right.
Having executed this code the LCD will be fully initialised and ready for us to send display data
to it.
CLEAR_LCD:
CLR RS
MOV A,#01h
LCALL WRITE_2_NIBBLES ;Write A as two separate nibbles to LCD
LCALL WAIT_LCD
RET
WRITE_TEXT:
SETB RS
LCALL WRITE_2_NIBBLES
LCALL WAIT_LCD
RET
LCALL INIT_LCD
LCALL CLEAR_LCD
MOV A,#'H'
LCALL WRITE_TEXT
MOV A,#'E'
LCALL WRITE_TEXT
MOV A,#'L'
LCALL WRITE_TEXT
MOV A,#'L'
LCALL WRITE_TEXT
MOV A,#'O'
LCALL WRITE_TEXT
MOV A,#' '
LCALL WRITE_TEXT
MOV A,#'W'
LCALL WRITE_TEXT
MOV A,#'O'
LCALL WRITE_TEXT
MOV A,#'R'
LCALL WRITE_TEXT
MOV A,#'L'
LCALL WRITE_TEXT
MOV A,#'D'
LCALL WRITE_TEXT
The above "Hello World" program should, when executed, initialise the LCD, clear the LCD
screen, and display "Hello World" in the upper left-hand corner of the display. As you see, no
difference in this routine with the 8bit drive routines.
CURSOR POSITIONING
Let's again, write the word 'world' on the second line now, from the tenth position:
LCALL INIT_LCD
LCALL CLEAR_LCD
MOV A,#'H'
LCALL WRITE_TEXT
MOV A,#'E'
LCALL WRITE_TEXT
MOV A,#'L'
LCALL WRITE_TEXT
MOV A,#'L'
LCALL WRITE_TEXT
MOV A,#'O'
LCALL WRITE_TEXT
CLR RS
MOV A,#0C9h
LCALL WRITE_2_NIBBLES
LCALL WAIT_LCD
MOV A,#'W'
LCALL WRITE_TEXT
MOV A,#'O'
LCALL WRITE_TEXT
MOV A,#'R'
LCALL WRITE_TEXT
MOV A,#'L'
LCALL WRITE_TEXT
MOV A,#'D'
LCALL WRITE_TEXT
SUMMARY
This tutorial has presented the underlying concepts of programming an LCD display in 4bit
modus. If things in this document are not clear, please be sure to read again the first tutorial on
using LCD modules.
1. 8 characters x 1 line
First Line:00 01 02 03 04 05 06 07
First Line: 00 01 02 03 04 05 06 07
Second Line:40 41 42 43 44 45 46 47
4. To use the second line, don't forget to initialise the display as a TWO lines display.
5. 16 characters x 1 line
First Line:00 01 02 03 04 05 06 07 40 41 42 43 44 45 46 47
6. In fact, in this case the two lines are placed one after another. So when we want to use the
display from the ninth position, it has to be initialised as if it were a TWO lines display!
Mind the ninth position is addressed as 40h, not 08h.
1. 16 characters x 1 line
First Line:00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
2. On the outside this module looks the same like #3 above, but all characterpositions are
addressed continuously. The module has to be initialised as a ONE-line display.
3. 20 characters x 1 line
First Line:00 01 02 03 04 05 06 07 08 09 40 41 42 43 44 45 46 47 48 49
4. In fact, from HD44780 point of view, in this case two lines are placed one after another.
So when we want to use the display from the eleventh position, it has to be initialised as
if it were a TWO lines display! Mind the eleventh position is addressed as 40h, not
0Ah.
5. 40 characters x 1 line
6. The module has to be initialised as a TWO lines display, if we also want to use the
second line.
7. 24 characters x 2 lines
First Line: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13
14 15 16 17
Second 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53
Line: 54 55 56 57
8. The module has to be initialised as a TWO lines display, if we also want to use the
second line.
9. 40 characters x 2 lines
10. The module has to be initialised as a TWO lines display, if we also want to use the
second line. This is also the maximum configuration which is possible with one
HD44780 + extension chips (80 characters).
11. 16 characters x 4 lines
First Line: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
Second Line:40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F
Third Line: 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F
Fourth Line: 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F
12. To use the second and the fourth line, the module has to be initialised as a TWO lines
display (strange, no?). In fact, the third line is continuous to the first line, and the fourth
line is continuous two the second line (from addressing point of view).
13. 20 characters x 4 lines
First Line: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13
Second Line:40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53
Third Line: 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 22 23 24 25 26 27
Fourth Line: 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F 60 61 62 63 64 65 66 67
14. To use the second and the fourth line, the module has to be initialised as a TWO lines
display. In fact, the third line is continuous to the first line, and the fourth line is
continuous two the second line (from addressing point of view).
15. 24 characters x 4 lines
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13
First Line: 14 15 16 17
Second 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F 30 31 32 33
Line: 34 35 36 37
Third Line: 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53
54 55 56 57
Fourth
60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 72 73
Line: 74 75 76 77
16. To use the THIRD and the FOURTH line, the module has to be initialised as a TWO
lines display. Look out! There is a small 'view'-gap between the address ing of the first
and the second line (and the third and fourth line respectively).
17. 40 characters x 4 lines
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12...
First Line: 27
Second 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52...
67
Line: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12...
Third Line: 27
Fourth Line:40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52...
67
18. These modules uses two HD44780's (each with expansion chips) and can be seen as two
40 x 2 modules in one. All wiring is common, except for the EN (enable) lines, which
are separate to drive each HD44780 apart.
Tip:If you are not sure what configuration your display has, you can do use the
following trick: Imagine you have a 16 characters x 1 line display. You want to
know if it has configuration #3 in the first section or #1 in this section. Just
connect the contrast input of your module to GND (= maximum contrast) and
apply only power (+5V) to the module. The module will be initialised by an
internal routine, which puts it in single line modus. Only the positions that belong
to the first line will be black.
Conclusion: If all positions are black, we have a module as described under #1 of this section. If
only the first 8 characters are black, you have a module as described under # of the previous
section.
Not all possible module configurations are described here, but with the help of this information
you must be able to work with different modules. Some (functional, not necessary pin-)
compatible chips; to help you to determine your module:
Controller:
HD44780 (Hitachi)
KS0066 (Samsung)
SED1278 (Epson)
Expansion 8 x 2:
HD44100 (Hitachi)
KS0061 (Samsung)
M5259 (OKI)
Expansion 12 x 2:
SED1181 (Epson)
Expansion 16 x 2:
HD66100 (Hitachi)
Note: Some modules have black blobs which are chips direct mounted on the pc-board, covered
with some resin substantion, so the chips are not recognisable.
This page will go through the development of a simple software-base RTC solution using 8051
Timer 1 (T1). Thus, your software application will have the benefit of an RTC without requiring
any additional hardware.
Your software will require a known crystal speed. If you change the crystal speed
connected to your 8051, you will have to modify the software accordingly.
The accuracy of our RTC will only be as accurate as the crystal you use.
The variation of an RTC compared to the current time is called "drift" and is often measured in
"seconds of drift per month." A specification may indicate that a given hardware RTC is accurate
"+/- 10 seconds per month." If you are going to use a software-based RTC, such as this one, be
sure your crystal is rated with minimal variation.
NOTE: The standard 8051 Timer increments every 12 crystal cycles. However, some
derivative chips increment their timers after a different number of crystal cycles: For
example, Dallas microcontrollers can be programmed to increment every 4 cycles. If
you are using a derivative that uses some value other than 12, you will have to make the
appropriate changes to this code.
Let's establish some more equates to make our code more portable:
CRYSTAL EQU 11059200 ;The crystal speed
TMRCYCLE EQU 12 ;The number of crystal cycles per timer
increment
TMR_SEC EQU CRYSTAL/TMRCYCLE ;The # of timer increments per second
Thus, should our crystal frequency change or should we move our code to a derivative
microcontroller that uses some other value than 12, we simply need to modify our constants.
Step 3:Calculating the Timer 1 Overflow Frequency
Remember, a 16-bit timer will count from 0 to 65,535 before resetting. This is important when
you consider that Timer 1 will be incremented 921,600 times per second. Obviously it will
overflow it's 65,535 maximum value a number of times in the course of one second-to be exact,
it will overflow 921600/65536=14 times per second. If we were to use the timer in 8-bit or auto-
reload mode, the timer would end up overflowing 3599 times per second, which is a lot harder to
keep track of.
So we will have timer 1 running in 16-bit mode. However, we have a problem: Timer 1 will
actually overflow 921600/65536= 14.0625 times per second. Obviously it's not possible for it to
overflow .0625 times. This means we can't simply count the number of overflows from it
counting from 0 to 65536. We'll be introducing even more inaccuracy. In the case of an
11.0592Mhz crystal, this inaccuracy will be about 0.44%, but if we were to use this same
program with a 12.000Mhz crystal, the inaccuracy would be 1.70% which is much worse. Other
crystal frequencies could result in even less accuracy. Generally, the slower the crystal, the more
pronounced the error will be-and the error can easily become significant.
That being the case, we're going to need to have timer 1 overflow at some frequency that adds up
nicely to 1 second intervals. For example, 65536 timer 1 cycles is 65536/921600 = .071 seconds.
In other words, for timer 1 to start counting at 0, count up to 65,535, and overflow back to 0 will
take .071 seconds. The problem is that 1.00 seconds divided by .071 seconds does not produce an
integer result, thus we have inaccuracy. Our goal is to have timer 1 overflow at a frequency that
can be multiplied by an integer to arrive at 1.00 seconds.
For example, if instead of overflowing every .071 seconds, timer 1 were to overflow every .05
seconds, we would know that after 20 overflows exactly one second had passed. How long is .05
seconds in terms of timer cycles? Simple: 921600 * .05 = 46080. In other words, after timer 1
has been incremented 46080 times, 1/20th of a second (.05 seconds) have passed.
So the trick is to have our timer overflow every .05 seconds instead of every .071 seconds.
Remember that the timer overflows when it reaches 65,535 and is incremented to 0. We
calculated above that we want the timer to overflow every 46,080 cycles. To do that, we need to
have the counter start counting at some value other than 0. In fact, we need to have timer 0 start
counting at 65536-46080=19456. In other words, if we initialize timer 1 to 19456, it will then
take 46,080 cycles for it to reset to 0. When it resets to 0, we need to once again reset it to 19456.
Again, we want our code to be portable, so first let's define an equate that indicates how many
timer cycles will pass in .05 seconds. We already have an equate TMR_SEC which indicates
how many timer cycles pass in a second, so to determine how many cycles make up 1/20th of a
second is just a matter of multiplying the first value by .05.
First, we need to initialize timer 1 to the reset value that we calculated in our equates in the last
section. We do that with the following instructions:
One other thing: We should initialize our clock variables. We do this with the following
instructions:
Configuring the Timer 1 interrupt is very easy. We just need to enable interrupt (set the EA bit)
and enable timer 1 interrupt (set the ET1) bit. We do that with the following code:
Before we write our code, let's consider what we need to do every 20th of a second:
Thus whenever our interrupt is triggered, we need to reset the timer to RESET_VALUE that we
calculated earlier. Also remember that we need to make sure our interrupt leaves the main
working variables in the same state they were in when the interrupt started, so we start by pusing
the registers we will change onto the stack so we can restore them when we finish the interrupt.
Once TICKS is decremented to 0, the DJNZ instruction above will fail and execution will
continue with this section of code meaning that a full second has passed.
We must first reset TICKS to 20 so that the countdown is ready for another second to pass, and
we must increment the number of seconds. We do that with the following code:
EXIT_RTC:
POP PSW ;Restore the PSW register
POP ACC ;Restore the accumulator
RETI ;Exit the interrupt routine
Step 7: Puting it All Together
That's really about all there is to it. We've written all the code fragments, so let's put it all
together in a single program:
MAIN:
MOV TH1,#HIGH RESET_VALUE ;Initialize timer high-byte
MOV TL1,#LOW RESET_VALUE ;Initialize timer low-byte
MOV TMOD,#10h ;Set timer 1 to 16-bit mode
SETB TR1 ;Start timer 1 running
MOV HOURS,#00 ;Initialize to 0 hours
MOV MINUTES,#00 ;Initialize to 0 minutes
MOV SECONDS,#00 ;Initialize to 0 seconds
MOV TICKS,#20 ;Initialize countdown tick counter to 20
SETB EA ;Initialize interrupts
SETB ET1 ;Initialize Timer 1 interrupt
.... Your main program continues here ...
Step 8: Using The RTC
Once you've included the above code in your program, you may simply add your "main"
program to the end. Your program can set the RTC by setting the HOUR, MINUTE, and
SECONDS variables, or may obtain the current time by reading them. Other than that, you can
pretty much forget about the RTC because it will be running all by itself in the background using
timer 1 interrupt.
It's probably a good idea to point out a few shortcomings and observations about the above
solution-because if I don't, I'll receive lots of email! First, there is a slight error introduced in the
ISR. As you can see in the code, the ISR turns off timer 1 while it resets TH1 and TL1. In all, the
timer is turned off for three instructions: It is turned off for the two MOV instructions, and it is
turned off until the end of the SETB instruction. On a standard 8051, each MOV instruction
requires 2 clock cycles to operate, and the SETB instruction requires 1. Thus the clock
effectively loses 5 cycles due to the ISR implementation. If you wish to take this into account,
you may simply replace the ISR code with the following. which will take into account these 5
"lost" cycles.
CLR TR1
MOV TH1,#HIGH (RESET_VALUE-5)
MOV TL1,#LOW (RESET_VALUE-5)
SETB TR1
Second, this solution is based on interrupts. If you use other interrupts in your program, the timer
1 interrupt may not necessarily execute right away. If another interrupt of the same priority is
executing when timer 1 overflows, our RTC interrupt will not execute into the other interrupt has
finished. This will introduce inaccuracy. The only way to guarantee that our RTC interrupt will
always execute immediately is to give it an interrupt priority of "1" and give all other interrupts a
priority of "0". This can be done with the following instruction:
MOV IP,#8 ;Timer 1 Priority=1, all others = 0
Finally, another disadvantage is the fact that the solution requires dedicated use of timer 1. Your
main program isn't allowed to change the value of the timer-doing so will cause the RTC to
become completely inaccurate. Your program can read the timer, but it may never change it.
Conclusion
As mentioned at the beginning, a software-based RTC is a simple solution that can be
implemented instead of using RTC hardware in your design. This is a reasonable solution if you
don't require tremendous accuracy or if you already have hardware in the field that doesn't have
RTC hardware, but new requirements include some kind of clock. This is a neat way to avoid
recalling or replacing all the hardware.
2. OTHER INFORMATION
Explanation of Intel-Standard File Format
Intel HEX File Format
The "Intel-Standard" HEX file is one of the most popular and commonly used formats in
the 8052 world. The standard is used to burn the 8052 program into an EPROM, PROM,
etc. For example, an 8052 assembler will usually generate an Intel Standard HEX file
which can then be loaded into an EPROM programmer and burned into the chip.
An Intel Standard HEX file is an ASCII file with one "record" per line. Each line has the
following format:
Position Description
Record Marker: The first character of the line is always a colon (ASCII 0x3A) to identify the line as
1
an Intel HEX file
Record Length: This field contains the number of data bytes in the register represented as a 2-digit
2-3 hexidecimal number. This is the total number of data bytes, not including the checksum byte nor the
first 9 characters of the line.
Address: This field contains the address where the data should be loaded into the chip. This is a value
4-7
from 0 to 65,535 represented as a 4-digit hexidecimal value.
Record Type: This field indicates the type of record for this line. The possible values are: 00=Register
8-9
contains normal data. 01=End of File. 02=Extended address.
Data Bytes: The following bytes are the actual data that will be burned into the EPROM. The data is
10 - ?
represented as 2-digit hexidecimal values.
Checksum: The last two characters of the line are a checksum for the line. The checksum value is
Last 2
calculated by taking the two's complement of the sum of all the preceeding data bytes, excluding the
characters
checksum byte itself and the colon at the beginning of the line.