8051 Tutorial for programmers and beginners

The following chapters will help you to study about 8051 controllers......before going into programming you should have knowledge in controller architecture, memory maps, registers, instructions sets, ports, interrupts and other embedded concepts. If you are a beginner then its right place to start. 8051 is the basic controller, its easy to study but in the starting you will face problem.....but i'll give assurance that if you study one controller well then you can study other controllers easily.




Chapter 1

Introduction

The block diagram of the Intel MCS-8051 architecture is shown in Fig. 1. The features of the 8051 core are:
  • 8-bit CPU optimized for control applications
  • Extensive Boolean processing capabilities
  • 64K program memory address space
  • 64K data memory address space
  • 4K bytes of on-chip program memory
  • 128 bytes of on-chip data RAM
  • 32 bidirectional and individually addressable I/O lines
  • Two 16-bit timers
  • Full duplex UART
  • 6-source/ 5 vector interrupt structure with two priority levels
  • On-chip clock oscillator

       
                                      
                                              Fig. 1 Architecture of MCS 8051




Chapter 2

Types of Memory

On-Chip memory refers to any memory (Code, RAM, or other) that physically exists on the microcontroller itself.
External code memory is program memory that resides off the chip. This is often in the form of an external EPROM.
External RAM resides off-chip. This is often in the form of standard static RAM or flash RAM.

Code Memory

This is the memory that holds the actual 8051 program. It is limited to 64K size. 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.

External RAM

This refers to random access memory found off-chip. This memory has slower access time than on-chip RAM. 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! While Internal RAM is limited to 128 bytes (256 bytes with an 8052), the 8051 supports 64K external RAM.

On-Chip Memory

The 8051 has on-chip memory of two types: Internal RAM and Special Function Register (SFR) memory.
The layout of the 8051's internal memory is presented in the memory map shown in Table 1.


The 128 bytes of internal ram are 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. Bit Memory also resides in 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 8051’s stack since, as illustrated in the memory map, the area reserved for the stack is only 80 bytes--and usually it is less since thses 80 bytes have to be shared between the stack and user variables.

Register Banks

The 8051 microcontroller uses registers 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.
                     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.
As the memory map shows, the microcontroller has four distinct register banks. When the microcontroller is first powered 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, register R4 will now be synonomous with Internal RAM address 1Ch.
Register banks really reside in the first 32 bytes of Internal RAM.
If only the first register bank (i.e. bank 0) is used, the Internal RAM locations 08h through 1Fh may be used without caution. But if register banks 1, 2, or 3 are used great care must be exercised in using addresses below 20h since there is a possibility that the "R" registers may be overwritten.

Bit Memory

The 8051gives 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 you’ve 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

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 or you may execute:
                     SETB 80h
Both these instructions accomplish the same thing. However, using the SETB command will turn on the P0.0 line without affecting the status of any of the other P0 output lines. The MOV command effectively turns off all the other output lines except P1.0, which may not be acceptable in some cases.
On power up, the Stack Pointer (SP) is initialized to 08h. 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.

Special Function Register (SFR) Memory

Special Function Registers (SFRs) are areas of memory that control specific functionality of the 8051 processor. For example, four SFRs permit access to the 8051’s 32 input/output lines. Another SFR allows a program to read or write to the 8051’s serial port. Other SFRs allow the user to set the serial baud rate, control and access timers, and configure the 8051’s interrupt system.

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 8051’s 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 (it’s 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.



Chapter 2

Special Function Registers

SFRs are accessed as if they were normal Internal RAM. The only difference is that Internal RAM is from address 00h through 7Fh whereas SFR registers exist in the address range of 80h through FFh. Each SFR has an address (80h through FFh) and a name. The following table lists the symbols, names and addresses of the 8051 SFRs.


Although the address range 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 Descriptions

There are four I/O ports of 8 bits each for a total of 32 I/O lines. The four ports are called P0, P1, P2 and P3.
P0 (Port 0)
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.

SP (Stack Pointer)
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 that modify the stack, such as PUSH, POP,
LCALL, RET, RETI, and whenever interrupts are provoked by the microcontroller.
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 such as 2F if you will be using the alternate register banks and/or bit memory.

DPL/DPH (Data Pointer Low/High)

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). 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 to decrement DPTR. If you wish to decrement the value of DPTR, you must write your own code to do so.

PCON (Power Control)

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 that 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)

 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 that are set when an external interrupt has occured.

TMOD (Timer Mode)

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)

 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)

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)

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)

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. To use the 8051's on-board serial port, it is generally necessary to initialize the following SFRs: SCON, TCON, and TMOD. This is because SCON controls the serial port. However, in most cases the program will wish to use one of the timers to establish the serial port's baud rate. In this case, it is necessary to configure timer 1 by initializing TCON and TMOD.

SBUF (Serial Control)

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)

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. 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)

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)

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 corresponds to pin P3.0, bit 7 corresponds to 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

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

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. 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 unpredictably.

ACC (Accumulator)

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)

The "B" register is used in two instructions: the multiply and divide operations. The "B" register is also commonly used as an auxiliary register to temporarily store values.

Other SFRs

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 other than the standard 8051, 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. 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 will 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.

Chapter 3

Basic Registers


Accumulator

The Accumulator 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 8051’s 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.

Auxillary registers

The auxillary registers are a set of eight registers that are named R0, R1, etc. up to R7.
These registers are used 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.
For example, let’s 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:
                     MOV A, R3 ; Move the value of R3 into the accumulator
                     ADD A, R4 ; Add the value of R4
                     MOV R5, A ; Store the resulting value temporarily in R5
                     MOV A,R1 ; Move the value of R1 into the accumulator
                     ADD A,R2 ; Add the value of R2
                     SUBB A,R5 ; Subtract the value of R5
As you can see, we used R5 to temporarily hold the sum of R3 and R4.

"B" Register

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 used only 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.




The Data Pointer (DPTR)

The Data Pointer (DPTR) is the 8051’s only user-accessable 16-bit (2-byte) register. The Accumulator, "R" registers, and "B" register are all 1-byte values. DPTR, as the name suggests, is used to point to data. It is used when external memory is accessed. The microcontroller 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 it’s the only true 16-bit register available. It is often used to store 2-byte values that have nothing to do with memory locations.

Program Counter (PC)

The Program Counter (PC) is a 2-byte address that 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 isn’t 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 can’t do something like PC=2430h. On the other hand, if you execute LJMP 2340h you’ve effectively accomplished the same thing.

Stack Pointer (SP)

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. 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.

Chapter 4

Addressing Modes


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
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.
For example, the instruction:
                     MOV A, #20h
This instruction uses Immediate Addressing because the Accumulator will be loaded with the value that immediately follows; in this case 20H. 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 (hexadecimal) and store it in the Accumulator. Direct addressing is generally fast since, although the value to be loaded isn’t included in the instruction, it is quickly accessable since it is stored in the 8051’s Internal RAM. It is also much more flexible than Immediate Addressing since the value to be loaded is whatever is found at the given addres, which may be variable.
Any direct addressing instruction referring to an address between 00h and 7Fh is referring to Internal Memory. Any instruction referring to addresses between 80h and FFh is referring to the SFR control registers that control the 8051 microcontroller itself.



Indirect Addressing

Indirect addressing is a very powerful addressing mode providing a great deal of flexibility. Indirect addressing is also the only way to access the extra 128 bytes of Internal RAM found on an 8052.
                Indirect addressing appears as follows:
                     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 found at the address indicated by R0. If R0 holds the value 40h and Internal RAM address 40h holds the value 67h. When the above instruction is executed the 8051, the Accumulator ends up holding 67h. Indirect addressing always refers to Internal RAM; it never refers to an SFR.

External Direct

There are only two commands that use External Direct addressing mode:
                     MOVX A, @DPTR
                     MOVX @DPTR, A

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 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. 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 reach of this instruction would be limited to 256 bytes of External RAM.

Chapter 5

Program Flow

When an 8051 is first initialized, it resets the PC to 0000h. The 8051 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, START
                              NOP
                      START:
                              ....
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 START, skipping the NOP instruction. If the bit is not set the conditional branch fails and program execution continues, as usual, with the NOP instruction that follows. Conditional branching is really the fundamental building block of program logic since all "decisions" are accomplished by using conditional branching. 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 that follows the conditional branch instruction. This means that in the above example the label HELLO must be within +/- 128 bytes of the memory address that contains the conditional branching instruction.




Direct Jumps

This type of instruction causes 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.
                                                   LJMP NEW_ADDRESS
                                                   MOV A, #3
                                                   …
                                                   …                                        
                                                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. Aside from LJMP, there are two other instructions that 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).
The LJMP command requires three bytes of code memory whereas both the SJMP and AJMP commands require only two.

Direct Calls

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.

Returns from Routines

Another structure that can cause program flow to change is the "Return from Subroutine" instruction, known as RET in 8051 Assembly Language. 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 that 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 suspends 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.

Chapter 6

Instruction Set, Timing, and Low-Level Info

CPU Timing

The 8051 has an on-chip oscillator which can be used as the clock source for the CPU. The CPU timing is based on the external crystal connected between the pins XTAL1 and XTAL2. The internal clock generator defines the sequence of states that make up the 8051 machine cycle. A machine cycle consists of a sequence of 6 states numbered S1 through S6. Each state time lasts for two oscillatory periods. Thus a machine cycle takes 12 oscillatory periods or 1microsecond if the oscillatory frequency is 12 MHz. Each state is divided into a Phase 1 half and a Phase 2 half. Fig. 2 shows the fetch/execute sequences in states and phases for various kinds of instructions. Normally two program fetches are generated during each machine cycle. The CPU ignores the second fetch if it does not need the second code byte. Execution of a one-cycle instruction begins during State 1 of the machine cycle.when the opcode is latched on to the Instruction register.
A second fetch occurs during S4 of the same machine cycle. Execution is complete at the end of State 6 of this machine cycle.
The MOVX instruction takes two machine cycles to execute. No program fetch is generated during the second cycle of a MOVX instruction. This is the only time program fetches are skipped.
The fetch/execute sequences are same whether the Program memory is internal or external to the chip. Execution times do not depend on whether the Program memory is external or internal.

Alphabetical List of Instructions

                     ACALL: Absolute Call
                     ADD, ADDC: Add Accumulator (With Carry)
                     AJMP: Absolute Jump
                     ANL: Bitwise AND
                     CJNE: Compare and Jump if Not Equal
                     CLR: Clear Register
                     CPL: Complement Register
                     DA: Decimal Adjust
                     DEC: Decrement Register
                     DIV: Divide Accumulator by B
                     DJNZ: Decrement Register and Jump if Not Zero
                     INC: Increment Register
                     JB: Jump if Bit Set
                     JBC: Jump if Bit Set and Clear Bit
                     JC: Jump if Carry Set
                     JMP: Jump to Address
                     JNB: Jump if Bit Not Set
                     JNC: Jump if Carry Not Set
                     JNZ: Jump if Accumulator Not Zero
                     JZ: Jump if Accumulator Zero
                     LCALL: Long Call
                     LJMP: Long Jump
                     MOV: Move Memory
                     MOVC: Move Code Memory
                     MOVX: Move Extended Memory
                     MUL: Multiply Accumulator by B
                     NOP: No Operation
                     ORL: Bitwise OR
                     POP: Pop Value From Stack
                     PUSH: Push Value Onto Stack
                     RET: Return From Subroutine
                     RETI: Return From Interrupt
                     RL: Rotate Accumulator Left
                     RLC: Rotate Accumulator Left Through Carry
                     RR: Rotate Accumulator Right
                     RRC: Rotate Accumulator Right Through Carry
                     SETB: Set Bit
                     SJMP: Short Jump
                     SUBB: Subtract From Accumulator With Borrow
                     SWAP: Swap Accumulator Nibbles
                     XCH: Exchange Bytes
                     XCHD: Exchange Digits
                     XRL: Bitwise Exclusive OR
                     Undefined: Undefined Instruction

Fig. 2 State Sequences in 8051


Chapter 7
Timers

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.
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.

Using timers to measure time

Obviously, one of the primary uses of timers is to measure time. We will discuss this use of timers first and will subsequently discuss the use of timers to count events. When a timer is used to measure time it is also called an "interval timer" since it is measuring the time of the interval between two events. When a timer is in interval timer mode and correctly configured, it will increment by 1 every machine cycle that is equivalent to 12 crystal periods. Thus a running timer will be incremented:
                     12,000,000 / 12 = 1,00,000  per second for a 12 MHz clock.
Thus if a timer has counted from 0 to 50,000 you may calculate:
                     50,000 / 1,000,000 = 0.05  seconds.
Obviously, this is a little more useful. If you know it takes 1/20th of a second to count from 0 to 50,000 and you want to execute some event every second you simply wait for the timer to count from 0 to 50,000 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 that function essentially the same way. One timer is TIMER0 and the other is TIMER1. The two timers share two SFRs (TMOD and TCON) that control the timers. In addition to this the registers TH0/TL0 are related to Timer 0 and TH1/TL1 are related to Timer1. Timer 0 has two SFRs dedicated exclusively to itself: TH0 the high byte of the timer and TL0 the 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 (3E8h), TH0 will hold the high byte of the value (3h= 3 decimal) and TL0 will contain the low byte of the value (E8h = 232 decimal).
                     TH0 * 256 + TL0 = 1000
                     3 * 256 + 232 = 1000
Timer 1 works the exact same way, but it’s 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.

TMOD

TMOD (Timer Mode) is used to control the mode of operation of both timers. Each bit of the SFR gives the microcontroller specific information concerning how to run a timer. The high four bits (bits 4 through 7) relate to Timer 1 whereas the low four bits (bits 0 through 3) perform the exact same functions, but for timer 0. Table 3 shows the detailed description of the options that can be selected using TMOD register.



Mode 0 (13-bit Time Mode)

Consider Timer 0 for this example.
Timer mode "0" is a 13-bit timer.  When the timer is in 13-bit mode, TL0 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 TL0 and bits 0-7 of TH0. 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.
The same discussion holds for Timer 1 except that TL1 and TH1 are the corresponding registers.

Mode 1(16-bit Time Mode)
Timer mode "1" is a 16-bit timer. This is a very commonly used mode. It functions just like 13-bit mode except that all 16 bits are used. For Timer 0, TL0 is incremented from 0 to 255. When TL0 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.

Mode 2(8-bit Time Mode)

The timer in Mode 2 is an 8-bit auto-reload mode. WhenTimer0 is in mode 2, TH0 holds the "reload value" and TL0 is the timer itself. Thus, TL0 starts counting up. When TL0 reaches 255 and is subsequently incremented, instead of resetting to 0 (as in the case of modes 0 and 1), it will be reset to the value stored in TH0. The value in TH0 does not change as a result of upcount nor overflow. The auto-reload mode is very commonly used for establishing a baud rate for the serial port.

Mode 3 (Split Timer)

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.

TCON SFR

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




This SFR is bit addressable as follows.
                     MOV TCON, #80h
                        ... or
                     SETB TF1
The most significant bit can be changed without modifying any of the other bits.

Initializing a Timer

For example to write a program to initialize Timer 0 in the 16-bit continuous run mode and start the timer the TMOD SFR needs to be set. 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 to be turned 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. To start the timer running we must set the TR0 bit in TCON SFR with the following instruction.
                     SETB TR0
Timer 0 will now be incremented every machine cycle.

Reading the Timer

The actual value of the timer can be read as a 16-bit number or the timer overflow can be detected. If the timer is in an 8-bit mode--that is, either 8-bit AutoReload mode or in split timer mode the 1-byte value of the timer can be read directly. However, if the timer is in 13-bit or 16-bit mode the following procedure is adopted. In this case, we load the accumulator with the high byte of Timer 0. We then load R0 with the low byte of Timer 0. Finally, we check to see if the high byte we read out of Timer 0--which is now stored in the Accumulator--is the same as the current Timer 0 high byte. If it isn’t it means the timer has just "rolled over" and the timer value needs to be read again. The low byte of the timer will be in R0 and the high byte in the Accumulator. Alternatively the timer run bit can be cleared to stop the timer (i.e. CLR TR0), the timer value can be read and then timer can be restarted by setting the timer run bit (i.e. SETB TR0).

Detecting Timer Overflow

Whenever a timer overflows from its highest value back to 0, the microcontroller automatically sets the TFx bit in the TCON register. If TF0 is set it means that timer 0 has overflowed; if TF1 is set it means that timer 1 has overflowed. This feature can be used for setting accurate time delays.
                     MOV TH0, #60;High byte of 15360 (60 * 256 = 15360)
                     MOV TL0, #176; Low byte of 176 (15360 + 176 = 15536)
                     MOV TMOD, #01;Put Timer 0 in 16-bit mode
                     SETB TR0; Make Timer 0 start counting
                     JNB TF0, $; If TF0 is not set, jump back to this same instruction

In the above code the first two lines initialize the Timer 0 starting value to 15536. The next two instructions configure timer 0 and turn it on. Finally, the last instruction JNB TF0, $, reads "Jump, if TF0 is not set, back to this same instruction." The "$" operand means, in most assemblers, the address of the current instruction. Thus as long as the timer has not overflowed and the TF0 bit has not been set the program will keep executing this same instruction. The timer will count (65536 - 15536 = 50000 counts) before overflowing to 0. For a 12MHz clock oscillator counting at 1MHz rate, this means a delay of 1/20th of a second.for the TF0 bit to be set and program execution will then break out of the loop.

Timing the length of events

This method uses an external pin to control the timer operation. If GATE0 on the TMOD SFR is set to 1 and a logic high signal is applied externally to pin INT0 (P3.2) on the 8051 the timer will start counting up. When P3.2 is low the timer will automatically be stopped. Thus the external pin P3.2 can control and time external events.

Timers as event counters

To use Timer 0 as event counter set C/T bit in TMOD SFR to 1. Timer 0 will now monitor the P3.4 line and increment whenever the logic level on that pin makes a transition from logic high to logic low.  This 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.

Chapter 8

Serial Communication


The 8051 has an integrated UART for serial communication. The operation mode and the baud rate should be selected for serial communication. Once configured, all we have to do is to 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.

Setting the Serial Port Mode

The SCON SFR allows us to configure the Serial Port. The first four bits (bits 4 through 7) are configuration bits. Bits SM0 and SM1 let us set the serial mode to a value between 0 and 3, inclusive. 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 oscillator frequency. In mode 1 and mode 3 the baud rate is variable based on how Timer 1 overflows.


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." If you want to receive data via the serial port, 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 data 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.

Setting the Serial Port Baud Rate

Once the Serial Port Mode has been configured, as explained above, the program must configure the serial port’s baud rate. This only applies to Serial Port modes 1 and 3. The Baud Rate is determined based on the oscillator frequency when in mode 0 and 2. In mode 0, the baud rate is always the oscillator frequency divided by 12. This means if the crystal frequency is 11.059Mhz, mode 0 baud rate will always be 921,583 baud. In mode 2 the baud rate is always the oscillator frequency divided by 64, so a 11.059Mhz crystal speed will yield a baud rate of 172,797.

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).
                     TH1 = 256 - ((Crystal / 384) / Baud)
If PCON.7 is set then the baud rate is effectively doubled, thus the equation becomes:
                     TH1 = 256 - ((Crystal / 192) / Baud)
For example, if we have an 11.059Mhz crystal and we want to configure the serial port to 19,200 baud we try plugging it in the first equation:
                     TH1 = 256 - ((Crystal / 384) / Baud)
                     TH1 = 256 - ((11059000 / 384) / 19200)
                     TH1 = 256 - ((28,799) / 19200)
                     TH1 = 256 - 1.5 = 254.5
As you can see, to obtain 19,200 baud on a 11.059Mhz crystal we’d have to set TH1 to 254.5. If we set it to 254 we will have achieved 14,400 baud and if we set it to 255 we will have achieved 28,800 baud. 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:
                     TH1 = 256 - ((Crystal / 192) / Baud)
                     TH1 = 256 - ((11059000 / 192) / 19200)
                     TH1 = 256 - ((57699) / 19200)
                     TH1 = 256 - 3 = 253
Here we are able to calculate a nice, even TH1 value. Therefore, to obtain 19,200 baud with an 11.059MHz crystal we must:

                     1. Configure Serial Port mode 1 or 3.
                     2. Configure Timer 1 to timer mode 2 (8-bit auto-reload).
                     3. Set TH1 to 253 to reflect the correct frequency for 19,200 baud.
                     4. Set PCON.7 (SMOD) to double the baud rate.

Writing to the Serial Port

Once the Serial Port has been propertly configured as explained above, the serial port is ready to be used to send data and receive data. 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:
                    CLR TI; Clear TI bit
                    MOV SBUF, #’A’; Send the letter ‘A’ to the serial port
                     JNB TI, $; Pause until the RI bit is set.

The above three instructions will successfully transmit a character and wait for the TI bit to be set before continuing. The last instruction says "Jump if the TI bit is not set to $"--$, in most assemblers, means "the same address of the current instruction." Thus the 8051 will pause on the JNB instruction until the TI bit is set by the 8051 upon successful transmission of the character.

Reading the Serial Port

Reading data received by the serial port is equally easy. To read a byte from the serial port one just needs to read the value stored in the SBUF (99h) SFR after the 8051 has automatically set the RI flag in SCON. 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:

                     JNB RI, $; Wait for the 8051 to set the RI flag
                     MOV A, SBUF; Read the character from the serial port

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

Chapter 9
Interrupts


Interrupts are events that cause program flow to deviate from sequential execution. They provide a mechanism to suspend normal program flow, execute a subroutine and resume program flow. The subroutine is called an interrupt handler. 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 related to the event that occured. Once complete, control would be returned to the original program. 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 we’d be burning precious "instruction cycles" checking for events that usually don’t happen. For example, let’s say we have a large 16k program executing many subroutines performing many tasks. Let’s also suppose that we want our program to automatically toggle the P3.0 port every time timer 0 overflows. The code to do this isn’t 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, let’s 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 we’re 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 we’ve 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 always in the main program loop.

Luckily, this isn’t 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, you’ll notice the CLR TF0 command has disappeared. That’s because when the 8051 executes our "timer 0 interrupt routine," it automatically clears the TF0 flag. You’ll 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 we’ve 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 it’s much easier to read and understand because we don’t 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 it’s 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.
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.

Source
Interrupt Vector address (Hex)
IE0
03
TF0
0B
IE1
13
TF1
1B
RI + TI
23
TF2 + EXF2
2B
Table 8: Interrupt Vectors
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

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. The program must specifically tell the 8051 that it wishes to enable interrupts and specifically which interrupts it wishes to enable.
The program may enable and disable interrupts by modifying the IE SFR (A8h):

Each interrupt of the 8051has its own bit in the Interrupt enable register. Individual interrupts are enabled by setting the corresponding bit to 1. 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).





  • A high priority interrupt cannot be interrupted.

    • A high-priority interrupt may interrupt a low-priority interrupt.
    • A low-priority interrupt may 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 that is serviced first by polling sequence will be executed first.

    Interrupt handling

    When an interrupt is triggered, the following actions are taken automatically by the microcontroller:

    • The current Program Counter is saved on the stack, low-byte first.
    • Interrupts of the same and lower priority are blocked.
    • In the case of Timer and External interrupts, the corresponding interrupt flag is cleared.
    • Program execution transfers to the corresponding interrupt handler vector address.
    • The Interrupt Handler Routine executes.
    • An interrupt ends when your program executes the RETI (Return from Interrupt) instruction.
    • 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.

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

    As you can see, our code checks the 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.
    Important Interrupt Consideration: Register Protection

    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 isn’t aware that they are executing in the "background." However, consider the following code:
                         CLR C; Clear carry
                         MOV A, #25h; Load the accumulator with 25h
                         ADDC A, #10h; Add 10h, with carry
    After the above three instructions are 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 doesn’t make sense. A programmer that was unfamiliar with interrupts would be convinced that the microcontroller was damaged in some way.
    What has happened, in reality, is the interrupt did not protect the registers it used. An interrupt must leave the processor in the same state as it was in when the interrupt initiated. 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 heart’s 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. In general, your interrupt routine must protect the following registers:
                         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 by 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 register’s 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 you’ve 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.

    Common Problems with Interrupts

    Interrupts are a very powerful tool available to the 8051 developer, but when used incorrectly they can be a source of a huge number of debugging hours. Errors in interrupt routines are often very difficult to diagnose and correct. 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.
    Annexure A
    Assembly language Instructions

    Data Transfer Instructions in 8051

    MOV: Most of the data transfer instructions involve the use of the MOV opcode. The table below gives a list of data transfer instructions that access internal data memory space alongwith the addressing modes involved.

    Mnemonic
    Operation
    Addressing Modes
    Direct
    Indirect
    Register
    Immediate
    MOV A, <src>
    A = <src>
    X
    X
    X
    X
    MOV <dest>, A
    <dest> = A
    X
    X
    X

     MOV<dest>, <src>
    <dest> = A
    X
    X
    X

    MOV DPTR, #data16
    DPTR  = 16bit immd const.


    X

    PUSH <src>
    INC SP: MOV "@SP,<src>
    X



    POP <dest>
    MOV <dest>, "@SP": DEC SP
    X



    XCHG A, <byte>
    ACC and <byte> exchange data
    X
    X
    X

    XCHD A, @Ri
    ACC and @Ri exchange low nibbles

    X





    The upper 128 bytes of RAM space can be accessed only by indirect addressing, and SFR space can be accessed only by direct addressing. The stack space resides in on-chip RAM and grows upward. The PUSH instruction first increments the Stack Pointer (SP), then copies the byte into the stack. PUSH and POP use only direct addressing to identify the byte being saved or restored, but the stack itself is accessed by indirect addressing using the SP register. Instructions with MOVX work on data transfer that accesses external RAM memory. Instructions with MOVC work on moving constants for reading look-up tables in program memory. The Data transfer instructions include a 16-bit MOV that can be used to initialize the Data pointer for look-up tables in program memory or for 16-bit data memory accesses.

    Boolean Instructions

    The internal RAM contains128 addressable bits, and the SFR space can support upto 128 other addressable bits. All the port lines are bit-addressable. The instructions in the table indicate the mnemonic, operation and the affecetd flags.

    Mnemonic
    Operation
    Remarks
    ANL C, bit
    C = C.AND.Bit
    Carry Logical And Bit
    ANL C, /bit
    C = C.AND.NOT. Bit
    Carry Logical And with Complement Bit
    ORL C, bit
    C = C.OR. Bit
    Carry Logical OR bit
    ORL C, /bit
    C = C.OR.NOT.Bit
    Carry Logical OR on Complement Bit.
    MOV C, bit
    C = Bit
    Move specified bit into Carry Flag
    MOV bit, C
    Bit = C
    Move carry flag into specified bit
     CLR C
    C = 0
    Set carry flag to 0
    CLR bit
    Bit = 0
    Set specified bit to 0
    SETB C
    C = 1
    Set carry flag to 1
    SETB bit
    Bit = 1
    Set specified bit to 1
    CPL C
    C = .NOT. C
    Complement carry flag
    CPL bit
    Bit = .NOT. bit
    Complement bit
    JC rel
    Jump if C = 1
    Jump to address rel, if Carry flag = 1
    JNC rel
    Jump if C = 0
    Jump to address rel, if Carry flag = 0
    JB bit, rel
    Jump if bit = 1
    Jump to address rel, if bit  = 1
    JNB bit, rel
    Jump if bit = 0
    Jump to address rel, if bit  = 0
    JBC bit, rel
    Jump if bit = 1;CLR bit
    Jump to address rel, if bit = 1. Clear bit.

    All bit accesses are by direct addressing. Bit addresses 00 through 7Fh are on the lower 128  RAM space while bit addresses 80H through FFH are in SFR space.


    Logical instructions

    The instructions that perform Boolean operations on bytes such as AND, OR perform the operation on a bit-by-bit basis. If the Accumulator contains 01101101 and <byte> contains 10100011, then the instruction
    ANL A, <byte> will leave the accumulator holding 00100001B.
    For example the ANL instruction may take the following forms.

    ANL A, #80H             (direct addressing)
    ANL A, @Ri              (indirect addressing)
    ANL A, R6                 (register addressing)
    ANL A, #53H             (immediate constant)

    Boolean operations can be performed on any byte in the lower 128 internal dara memory space or the SFR space using direct addressing, without having to use the accumulator.
    The rotate instructions are used for shifting the accumulator left or right. The SWAP instruction is used to interchange the high and lower nibbles within the accumulator.
    The table below lists the logical instructions available with the 8051.

    Mnemonic
    Operation
    Addressing Modes
    Remarks
    Dir
    Ind
    Reg
    Imm
    ANL A, <byte>
    A =  A.AND.<byte>
    X
    X
    X
    X
    Logical AND
    ANL <byte>, A
    <byte> = <byte> .AND. A
    X



    Logical AND
    ANL <byte>, #data
    <byte> = <byte> .AND.#data
    X



    Logical AND
    ORL A, <byte>
    A = A.OR. <byte>
    X



    Logical OR
    ORL <byte>, A
    <byte> = <byte> .OR. A
    X



    Logical OR
    ORL <byte>, #data
    <byte> = <byte> .XOR. A
    X



    Logical OR
    XRL A, <byte>
    A = A.XOR. <byte>
    X
    X
    X
    X
    Exclusive OR
    XRL <byte>, A
    <byte> = <byte>.XOR. #data
    X



    Exclusive OR
    XRL <byte>, #data
    <byte> = <byte>.XOR, #data
    X



    Exclusive OR
    CLR A
    A = 00
    Accumulator only
    Clear acc.
    CPL A
    A = .NOT. A
    Accumulator only
    Complement
    RL A
    Rotate ACC left by 1 bit
    Accumulator only
    Shift instruction
    RLC A
    Rotate left through carry
    Accumulator only
    Shift instruction
    RR A
    Rotate ACC right 1 bit
    Accumulator only
    Shift instruction
    RRC A
    Rotate Right through carry
    Accumulator only
    Shift instruction
    SWAP A
    Swap nibbles in A
    Accumulator only
    Exchange instruction


    Arithmetic instructions

    The arithmetic instructions comprise of ADD, SUB, MUL, DIV, INC and DEC. The table below indicates the addressing modes used with these instructions.  For example, the ADD A, <byte> instruction can be written as
    ADD A, 80H              (direct addressing)
    ADD A, @R0             (indirect addressing)
    ADD A,R3                 (register addressing)
    ADD A, #13H                        (immediate addressing.
    The list illustrates the various modes of addressing permitted with the ADD instruction in 8051. Note that any byte in the internal data memory space can be incremented or decremented without using the accumulator. The INC instruction on the data pointer aids in generating addresses for accessing the external memory. The result of the multiply instruction MUL AB puts the result in the concatenated B and A registers. The DIV AB instruction puts the quotient in the A register and the remainder in the B register.
    Shifting operations are equivalent to division or multiplication by 2 depending on the direction of the shift. A right shift is equivalent to division by 2 and a left shift is equivalent to multiplication by 2.


    Mnemonic
    Operation
    Addressing Modes
    Remarks
    Dir
    Ind
    Reg
    Imm
    ADD A, <byte>
    A = A + <byte>
    X
    X
    X
    X
    Addition
    ADDC A, <byte>
    A = A + <byte> + C
    X
    X
    X
    X
    Add with carry
    SUBB A, <byte>
    A = A - <byte> -C
    X
    X
    X
    X
    Subtract with borrow
    INC A
    A = A+ 1
    Accumulator only
    Increment
    INC  <byte>
    <byte> = <byte> + 1
    X
    X
    X

    Byte increment
    INC DPTR
    DPTR = DPTR +1
    Data Pointer only
    Increment
    DEC A
    A = A -1
    Accumulator only
    Decrement
    DEC <byte>
    <byte> = <byte> - 1
    X
    X
    X

    Decrement
    MUL AB
    B:A = B X A
    Acc and B only
    Multiply
    DIV AB
    A = Int[A/B], B = Mod [A/B]
    ACC and B only
    Quotient and remainder.
    DA A
    Decimal Adjust
    Accumulator only
    Decimal adjust
    The DA A instruction is used for BCD arithmeticoperations. In BCD arithmetic, ADD and ADDC instructions should be followed by a DA A operation, to ensure that the result is a BCD number. The DA A operation produces a meaningful result only as the second step in the addition of two BCD bytes.


     
    People who look for this also look for the below topics
    blinking of led or port
    8051 interfacing DC motor
    8051 interfacing with keypad
    8051 interfacing with LCD
    8051 interfacing with LCD and display Counter
    LCD sample program
    serial communication (RS-232) in 8051(polling method)
    serial with interrupt
    how to print serial received data on LCD.
    8051 interfacing STEPPER motor
    how to use TIMER in 8051
    8051 interfacing SEVEN SEGMENT display
    Timers with interrupt concept
    how to generate PWM in 8051
    4 bit LCD interfacing with 8051
    8051 Tuitorial
    how to install python
    Embedded Documents (sensors, protocol...etc)  
    Special NEWS