0% found this document useful (0 votes)
25 views95 pages

8051 Notes 18-19

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

8051 Notes 18-19

microcontorller
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 95

8051 Microcontroller

1. 8051 Microcontroller

An embedded system can be defined as a system that does a specific task smartly.
Washing machines, ovens, elevators, traffic control systems are the some of the examples
of embedded systems. The smartness of the system is due to the presence of the electronic
device present in it called ‘Microcontrollers’.

1.1 MICROPROCESSORS & MICROCONTROLLERS


Microprocessors: A microprocessor is a multipurpose, programmable logic device that
reads binary instructions from a storage device called memory accepts binary data as
input and processes data according to those instructions and provides results as outputs.

The physical components of the entire system refer to ‘Hardware’ while the set of
instructions written for the system to perform a task is called ‘Program’ and further group
of programs refers to ‘Software’.

Devices like microprocessor communicate and operate using binary digits ‘0’ & ‘1’ and
are referred to as ‘bits’. Every microprocessor has its own set of instructions which are in
the form of binary patterns called ‘machine language’. It is very difficult for the
programmer to communicate in the language of 0’s and 1’s, hence representation of
binary instructions in terms of abbreviated names called ‘mnemonics’ came into existence
and this became the language of microprocessors and is called as ‘assembly language’.

Programmer can communicate with microprocessor by entering instructions & data


through input devices such as keyboard or simple switches. Once microprocessor
processes the data, the result can be displayed through output devices such as seven
segments LED’s or can be printed by a printer.

Microprocessor based system consists of following components as shown in fig 1.

Arithmetic & Logic Unit: The purpose of this unit is to perform arithmetic
operations such as addition and subtraction and logical operations such as
ANDing, ORing, XORing & complementing.

Register Array: The CPU uses registers to store information temporarily such as
values to be processed, address of value to be fetched from memory during the
execution of program and are accessible to the user through instructions. Registers
can be 8- bit, 16- bit, 32- bit, or 64-bit. In general, the more and bigger the
registers, the better the CPU. The disadvantage of more and bigger registers is the
increased cost of such a CPU.

Harish G C, Assistant Professor, Department of E&CE 1


8051 Microcontroller

Figure 1.1: General block diagram of microprocessor

Program counter: Microprocessor / controller uses program counter to sequence


the execution of instructions. The function of program counter is to point to the
memory address from which next byte has to be fetched. When a byte is being
fetched, the pc is incremented by one to point to the next memory location.

Accumulator: It is the most versatile register that is used to hold the results of
many instructions particularly arithmetic and logical

Stack pointer: The word ‘stack’ refers to the set of memory locations in the R/W
memory which stores data byte temporarily during the execution of a program.
Stack pointer is a register that tracks the storage & retrieval of the information. An
address in the stack pointer indicates that the next two memory locations can be
used for storage.

Clock signals: clock signals control the generation of control signals. All actions
are initiated either by leading edge or by trailing edge of the clock and takes fixed
number of clock periods to complete the task. These provide the basic timing
signal for computer operations.

Interrupts: It is an input to the processor that indicates the occurrence of an


event. The processor responds to an interrupt by saving the current machine status
and branch to service the interrupt and then return back to normal execution mode.
The program code memory, data memory, I/O ports, Timer/counters etc are
externally interfaced to microprocessor.

Microcontrollers: Figure 1.2 shows the block diagram of typical microcontroller, which
is a true computer on a chip. The design approach of the microcontroller mirrors that of
the microprocessor. The microcontroller also had other features needed to make a
complete computer: ROM, RAM, I/O capability, counters etc. Some of the benefits of
microcontrollers include the following:

Cost advantage: The biggest advantage of microcontrollers against larger


microprocessors is that the design and hardware costs are much lesser and can be kept to
a minimum. A microcontroller is cheap to replace, while microprocessors are ten times
more expensive.

Harish G C, Assistant Professor, Department of E&CE 2


8051 Microcontroller

Lesser power usage: Microcontrollers are generally built using a technology known as
Complementary Metal Oxide Semiconductor (CMOS). This technology is a competent
fabrication system that uses less power and is more immune to power spikes than other
techniques.

All-in-one: A microcontroller usually comprises of a CPU, ROM, RAM and I/O ports,
built within it to execute a single and dedicated task. On the other hand, a microprocessor
generally does not have a RAM, ROM or IO pins and generally uses its pins as a bus to
interface to peripherals such as RAM, ROM, serial ports, digital and analog IO.

Figure 1.2: General block diagram of a microcontroller

It consists of

Timers/ Counters: Timers may be used to create time delay and counter may be
used to count the external events happening outside the microcontroller that
occurred within a time interval.

I/O Ports: This helps in transferring data and instructions in binary from the
outside world to the microcontroller and vice versa.

Internal RAM & ROM: The function of the memory is to store information, almost
as same as that of register. Programs and data are stored in memory. Memory
section usually a mixture of RAM(to store data) & ROM(to store code and may
be data) or in other words mixture of volatile & non volatile memory and it has
two important purposes

✓ To store the binary codes for the sequence of instructions to be executed by


processor.
✓ To store the binary coded data with which the processor is going to be working.

Harish G C, Assistant Professor, Department of E&CE 3


8051 Microcontroller

Table 1.1: Difference between Microprocessors & Microcontrollers

Microprocessors Microcontrollers

CPU is stand alone. RAM, ROM, timers are all CPU,RAM, ROM, timers are all
separate and are to be interfaced with CPU located on a single chip

They are Versatile & general purpose These are not very versatile

They have expansive applications These are used where cost, power &
space criteria are considered

Large number of instructions with flexible Limited number of instructions with


addressing modes few addressing modes

Designer can decide the amount of RAM, ROM Fixed amount of ROM, RAM and I/O
that is required to be connected ports on chip

Access time for memory and I/O devices are Access time for memory and I/O
more devices are less

Very few instructions which have bit-handling Many instructions with bit-handling
capability. capability.

Figure below shows the general block diagram Figure below shows the general block
of microprocessor diagram of microcontroller

ALU Int. ALU I/O


RA POR
M T
ACCUMULAT
ACCUMULATOR I/O
OR
POR
WORKING Int. T
REGISTERS RO WORKING
M REGISTERS

PROGRAM STACK PROGR STACK


COUNTER POINTER AM POINTER
COUNT
CLOCK INTERRUPT CLOCK
ER INTERRU
CIRCUIT CIRCUITS CIRCUI PT
T CIRCUIT
Note2: Microcontrollers are preferred over Microprocessors for embedded systems due
S
to low power consumption.

Harish G C, Assistant Professor, Department of E&CE 4


8051 Microcontroller

Criteria for selecting an appropriate microcontroller


✓ The amount of RAM and ROM available on chip.
✓ Power consumption.
✓ The number of I/O pins and the timer on the chip.
✓ Its flexibility to upgrade to higher performance or lower power consumption
versions.
✓ Cost per unit and speed.
✓ Whether it is available in DIP (Dual In Package) or QFP (Quad Flat Package).

1.2 TYPES OF MICROCONTROLLERS

Figure 1.2: Tree structure showing the classification of microcontrollers

1.3 VON-NEUMAN ARCHITECTURE


Microcontrollers based on the Von-Neuman architecture have a single data bus that is
used to fetch both instructions and data. Program instructions and data are stored in a
common main memory. When such a controller addresses main memory, it first fetches
an instruction, and then it fetches the data to support the instruction. The two separate
fetches slows up the controller’s operation. Figure 1.3 shows the Von-Neuman
Architecture.

Figure 1.3: Von Neumann Architecture

The Von-Neuman architecture’s main advantage is that it simplifies the microcontroller


design because only one memory is accessed. In microcontrollers, the contents of RAM

Harish G C, Assistant Professor, Department of E&CE 5


8051 Microcontroller

can be used for data storage and program instruction storage. For example, the Motorola
68HC11 microcontroller adopts Von- Neuman architecture.

1.4 HARVARD ARCHITECTURE


Microcontrollers based on the Harvard Architecture have separate data bus and an
instruction bus. This allows execution to occur in parallel. As an instruction is being “pre-
fetched”, the current instruction is executing on the data bus. Once the current instruction
is complete, the next instruction is ready to go. This pre-fetch theoretically allows for
much faster execution than Von-Neuman architecture, on the expense of complexity.
Figure 1.4 shows the Harvard Architecture. The Harvard Architecture executes
instructions in fewer instruction cycles than the Von- Neuman architecture. Example, the
Intel MCS-51 family of microcontrollers and PIC microcontrollers uses Harvard
Architecture.

Figure 1.4: Harvard Architecture

1.5 CISC VS RISC


Table 1.2: Difference between CISC & RISC
CISC RISC
Acronyms as Complex Instruction Set Computer Acronyms as Reduced Instruction Set
Computer
Consists of large instruction set to perform many Consists of small instruction set to perform
types of operations limited operations
Simple instructions take multiple machine Simple instructions requires one machine
cycles for its execution cycle for its execution which leads to faster
execution
Frequent memory accesses Memory accessing is not frequent
Variety of addressing modes Fewer addressing modes
Program size is smaller Comparatively program size is larger
No need for specialized compiler design Efficient and optimized compiler design
required
Complex decoding circuit is necessary Small chip area needed for instruction
decoding and sequencing control
Instruction pipelining is absent Instruction pipelining increases execution
speed
Ex: Intel 8096 family, Intel 8086 family, Ex: ARM processor, Motorola 88100, Alpha
Motorola 680X0 family AXP

Harish G C, Assistant Professor, Department of E&CE 6


8051 Microcontroller

1.6 8051 Architecture


The 8051 is one of the most popular microcontrollers in use today. The ability to program
an 8051 is an important skill for anyone who plans to develop products that will take
advantage of microcontrollers. This unit helps to understand architecture and features of
8051.

The architectural block diagram of 8051 is shown in fig 1.5. The 8051 is a 40 – pin DIP
and most commonly used microcontroller. The specific features of 8051 are the
following:

Fig 1.5: Architectural block diagram of 8051 microcontroller

Harish G C, Assistant Professor, Department of E&CE 7


8051 Microcontroller

8 – Bit CPU with two registers: A (accumulator) & B. Accumulator is used in


most arithmetic and logic operations. Register B is also used for integer
multiplication and division.

A 16 – bit register called Program Counter (PC). It holds the address of the
location of the next instruction to be executed.

A 16 – bit Data Pointer (DPTR) register. It is used to access external memory.

An 8 – bit Program Status Word (PSW) register. It indicates certain conditions


like status of carry, sign, parity, etc, after the execution of some instructions.

Internal RAM of 128 bytes divided as

Four register banks of 8 register each. (R0 to R7 each of 8 – bit size)

Sixteen bytes, which are bit addressable. The individual bits of these bytes
can be altered.

Eighty bytes of general RAM memory.

Internal ROM of 4K bytes used to store program code.

Four 8 – bit ports, P0 to P3. A port pins are used to send or to read data from
external devices.

Two 16 – bit timer/counter: Used as timers to generate delay between two events
with the help of internal clock pulses or used as a counter to count external pulses.

Full duplex serial data transmitter/receiver register, SBUF. This holds the byte to
be transmitted or the received byte, when serial communication is used.

Two external interrupts and three internal interrupts. Interrupts are events which
interrupt the normal sequence of execution of instructions.

Control registers: TCON, TMOD, SCON, PCON, IP and IE which control the
operations of the timers, serial ports and interrupts.

Oscillator and clock circuits.

Harish G C, Assistant Professor, Department of E&CE 8


8051 Microcontroller

1.7 PROGRAMMING MODEL OF 8051


The programming model of 8051 in fig 1.6 shows the 8051 as a collection of 8 – bit, 16 –
bit registers and 8 – bit memory locations. The model is complicated by number of
special function registers that must be present to make a microcomputer a
microcontroller.

Fig 1.6: Programming model of 8051

Each register, with the exception of the program counter, has an internal 1 – byte address
assigned to it. Some registers (marked with an asterisk ‘*‘ in fig 1.6) are both byte and bit
addressable. That is, the entire byte of data at such register addresses may be read or
altered, or individual bits may be read or altered. Software instructions are generally able
to specify a register by its address, its symbolic name, or both.

Harish G C, Assistant Professor, Department of E&CE 9


8051 Microcontroller

1.8 PIN DIAGRAM OF 8051


A pin out of the 8051 packaged in a 40 – pin DIP is shown in figure 1.7

Fig 1.7: The 8051 pin diagram

ALE/PROG (30): Address Latch Enable output pulse for latching the low byte of the
address during accesses to external memory. (ALE is emitted at a constant rate of 1/6 of
the oscillator frequency, for external timing or clocking purposes, even when there are no
accesses to external memory.) This pin is also the program pulse input (PROG) during
EPROM programming. PSEN (29): Program Store Enable is an active low output signal.
When 8051 wants access program code from external ROM, it is connected to enable pin
of ROM chip.

EA/VPP (31): When EA is held high the CPU access code from internal program
memory (unless the Program Counter exceeds 0FFFH in the 80C51). Holding EA pin
low, forces the CPU to access external program memory. This pin also receives the
programming supply voltage (VPP) during EPROM programming.

XTAL1 (19): Input to the inverting oscillator amplifier.

XTAL2 (18): Output from the inverting oscillator amplifier.

Harish G C, Assistant Professor, Department of E&CE 10


8051 Microcontroller

Ports: All ports are 8-bit bidirectional I/O ports. A port pins are used to send or to read
data from external devices. Each of these pins can be configured as an input or an output.

Port 0 (32 to 39) and Port 2 (21 to 28): P0 and P2 together provide the 16 – bit address
to access external memory i.e., AD0 to AD15. P0 provides the lower 8 – bit address (also
used as data lines) AD0 to AD7 and P2 provides the upper 8 – bit address A8 – A15.

Port 1 (1 to 8): Port 1 is an 8-bit bidirectional I/O port with internal pullups.

Port 3 (10 to 17): Port 3 is an 8-bit bidirectional I/O port with internal pullups. It also
serves the functions of various special features of the 8051 Family as follows:

Port Pin Alternate Function:


P3.0 RxD (serial input port)
P3.1 TxD (serial output port)
P3.2 INT0 (external interrupt 0)
P3.3 INT1 (external interrupt 1)
P3.4 T0 (timer 0 external input)
P3.5 T1 (timer 1 external input)
P3.6 WR (external data memory write strobe)
P3.7 RD (external data memory read strobe)
RST (9): A logic one on this pin disables the microcontroller and clears the contents of
most registers.

VCC (40) and VSS (20): Supply voltage (+5v) and Circuit ground potential respectively.

1.9 INTERNAL MEMORY ORGANIZATION IN 8051


The 8051 has a separate memory space for code (programs) and data. Figure 1.8 shows
internal memory organization of 8051.

Code memory (Internal ROM): It refers to 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 (4KB). Code may also be stored completely
off-chip in an external ROM (max of 64KB) or, more commonly, an external EPROM.
Flash RAM is also another popular method of storing a program.

Data memory (Internal RAM): The 8051 has 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.

Harish G C, Assistant Professor, Department of E&CE 11


8051 Microcontroller

Fig 1.8: Internal memory organization of 8051.

The 128 bytes of internal RAM is subdivided as shown on the memory map.

Four register banks of 8 register each (32bytes). By default register bank 0 is


selected and different register banks are selected with the help of flags bits(RS1
& RS0) present in PSW.

RB0 – 00h to 07h


RB1 – 08h to 0fh
RB2 – 10h to 17h
RB3 – 18h to 1fh

RAM location can be referred by their name (say R4) or by its address (04h)
Ex: ADD A, R4 or ADD A, 04H

Sixteen bytes, which are bit addressable (also byte addressable). The individual
bits of these bytes can be altered. Ex: SETB 07h

Eighty bytes of general purpose RAM memory 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.

Harish G C, Assistant Professor, Department of E&CE 12


8051 Microcontroller

1.10 ORGANIZATION OF SFRS:

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. Fig 1.9 shows an organization of SFR in 8051. The
following two points should be noted about the SFR addresses.

✓ The SFR’s have addresses between 80h and ffh. These addresses are above 80h,
since the addresses 00h to 7fh are addresses of RAM memory inside the 8051.
✓ Not all the address space of 80h o ffh is used by the SFR. The unused locations
80h to ffh are reserved and must not be used by the 8051 programmer.

Fig 1.9: Organization of SFR in 8051.

Note: The ‘*’ represents bit – addressable SFR’s

Harish G C, Assistant Professor, Department of E&CE 13


8051 Microcontroller

1.11 PSW (PROGRAM STATUS WORD)


The PSW is an 8 – bit register which indicates certain conditions like carry, sign etc.,
after the execution of certain instructions. The Program Status Word is at address D0h
and is a bit-addressable register.

Fig 1.10: PSW in 8051

Carry Flag (CY): This flag is set whenever there is a carry (from bit D7) after an
addition or a borrow after subtraction. It can also be set to 0 or 1 using CLR C or SETB C
instruction respectively.

Auxiliary Carry Flag (AC): This flag is set whenever there is a carry from lower nibble
(bit D3) to higher nibble (bit D4) or a borrow from higher nibble (bit D4) to lower nibble
(bit D3).

Over Flow Flag (OV): This flag is set whenever the result of a signed arithmetic
operation is too large, causing the higher – order bit to overflow into sign bit. I t is used to
detect errors in signed arithmetic operations.

Parity Flag (P): This reflects the number of 1’s in the accumulator register. If it has odd
number of 1’s then P = 1 else P = 0.

RS1 & RS0: Select register bank as shown in figure 2.6. By default register bank 0 is
selected.

Harish G C, Assistant Professor, Department of E&CE 14


8051 Microcontroller

Table 2.3: INSTRUCTIONS THAT AFFECT FLAG BITS

1.12 EXTERNAL MEMORY INTERFACE


Figure 1.11 shows the connections between an 8051 and an external memory
configuration consisting of 16K of EPROM and 8K of static RAM.

Fig 1.11: External memory connections to 8051


The 8051 accesses external RAM whenever certain program instructions are executed.
External ROM is accessed whenever the EA (external access-active low signal) pin is
connected to the ground or when the PC contains an address higher than the last address

Harish G C, Assistant Professor, Department of E&CE 15


8051 Microcontroller

in the internal 4K ROM (0FFFh). The 8051 design can thus use internal and external
ROM automatically.

For 16K EPROM address lines required is


2 ^ x ≈ 16Kbytes. Therefore, x = 14 where ‘x’ is number of address lines.
So A0 to A13 address lines are needed to connect external ROM memory.
Similarly for 8K RAM, 2 ^ x ≈ 8Kbytes and hence x = 13.
So A0 to A12 address lines are needed to connect external RAM memory.

Figure 1.12 shows the timing diagram associated with external memory access cycle.

Fig 1.12: External memory timing

During any memory access cycle, port 0 is time multiplexed. That is, it first provides the
lower byte of the 16 – bit memory address, then act as a bidirectional data bus to write or
read a byte of memory data. Port 2 provides the higher byte of the memory address during
the entire memory read/write cycle.

The ALE clock pulse provides the correct timing for latch to save the lower byte address
of external memory.

PSEN (active low) pin will go low to enable the ROM to place a byte of program code
on data bus.
The WR (active low) and RD (active low) pins will go low, enabling data to flow
between the RAM and the data bus

Harish G C, Assistant Professor, Department of E&CE 16


8051 Microcontroller

1.13 THE 8051 OSCILLATOR AND CLOCK

The heart of the 8051 is the circuitry that generates the clock pulses by which all internal
operations are synchronized. Pins XTAL1 and XTAL2 are provided for connecting a
resonant network to form an oscillator. Typically a quartz crystal and capacitors are
employed, as shown in figure 1.13. The crystal frequency, typically 1MHz to 16MHz is
the basic internal clock frequency of microcontroller.

Fig 1.13: Oscillator timing and circuit

Serial data communication needs often dictate the frequency of the oscillator because of
the requirement that internal counters must divide the basic clock rate to yield standard
communication bit per second (baud) rates. If the basic clock frequency is not divisible
without a remainder, then the resulting communication frequency is not standard.

Ceramic resonator may be used as a low cost alternative to crystal resonators. However
decrease in frequency stability and accuracy make the ceramic resonator a poor choice if
the high speed data communication with other systems, or critical timing, is to be done.

f = crystal clock frequency


P = smallest interval of time within the microcontroller called pulse
Machine cycle: The smallest interval of time to accomplish any simple instruction, or
part of a complex instruction.
One machine cycle = Six states
One state = Two oscillator pulse

Harish G C, Assistant Professor, Department of E&CE 17


8051 Microcontroller

A state is a basic time interval for discrete operation of microcontroller such as fetching
an opcode byte, decoding an opcode, executing an opcode, or writing a data byte.

Program instruction may require one, two, or four machine cycles to be executed,
depending on the type of instruction. The time required to execute an instruction is given
by,
Tinst = (C * 12) / crystal frequency, where C is the number of machine cycles

For example, Let crystal frequency, f = 16MHz.

ADD A, R1 is one cycle instruction then Tinst = 0.75 microseconds.

1.14 PC-PROGRAM COUNTER


• Points to the address of next instruction to be executed from ROM
• It is 16 bit register means the 8051 can access program address from 0000H to
FFFFH. A total of 64KB of code. 16 bit register means.

Initial value 0000 0000 0000 0 0 0 0 (0000H)


Final value 1111 1111 1111 1 1 1 1 (FFFFH)

• Initially PC has 0000H


• ORG instruction is used to initialize the PC ORG 0000H means PC
initialize by 0000H
• PC is incremented after each instruction.

Example:

Mnemonics Machine codes


MOV R5, #25H 7D 25
MOV A, #00H 74 00
ADD A, R5 2D
HERE: SJMP HERE; 80 FE

When 7D is accessed then PC locate the


0001H (next instruction to be executed)
When 00 is accessed then PC locate the
0004H (next instruction to be executed)

Harish G C, Assistant Professor, Department of E&CE 18


8051 Microcontroller

EXERCISE PROBLEMS:

Example A: Show the status of the CY, AC and P flag after the addition of 38H
and 2FH in the following instructions.

MOV A, #38H
ADD A, #2FH

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

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


AC = 1 since there is a carry from the D3 to the D4 bi
P = 1 since the accumulator has an odd number of 1s (it has five 1s)

Harish G C, Assistant Professor, Department of E&CE 19


8051 Microcontroller

2. 8051 INSTRUCTION SET

2.1 ASSEMBLER DIRECTIVES


The assembler directives are special instruction to the assembler program to define some
specific operations but these directives are not part of the executable program. Some of
the most frequently assembler directives are listed as follows:

✓ ORG OriGinate, defines the starting address for the program in program (code)
memory
✓ EQU EQUate, assigns a numeric value to a symbol identifier so as to make the
program more readable.
✓ DB Define a Byte, puts a byte (8-bit number) number constant at this memory
location
✓ DW Define a Word, puts a word (16-bit number) number constant at this
memory location
✓ END This is the last statement in the source file to advise the assembler to stop
the assembly process.

2.2 ASSEMBLY LANGUAGE INSTRUCTION FORMAT


An Assembly language instruction consists of four fields
[Label:] mnemonic [operands] [;comment]
Mnemonics → assembly level instructions are called mnemonic like MOV R5
Operands → on which the operation is performed.

Example:
Loop: MOV R1, #25H ; transfer 25H into R1

[Label] mnemonics operand comments

Note: Brackets indicates that a field is optional, and not all lines have them. The label
field allows the program to refer to a line of code by name. The label field cannot exceed
a certain number of characters.

Harish G C, Assistant Professor, Department of E&CE 20


8051 Microcontroller

2.3 ADDRESSING MODES:


The various ways of accessing data (stored in register/ memory or be provided as an
immediate data) are called addressing modes.
There are several addressing modes available to the 8051 instruction set, as follows:

Immediate Addressing
Register Addressing
Direct Addressing
Indirect Addressing
Relative Addressing
Absolute addressing
Long Addressing
Indexed Addressing

Immediate Addressing: Immediate addressing simply means that the operand (which
immediately follows the instruction opcode) is the data value to be used. For example the
instruction:

MOV A, #99d

Number 99d

Register Addressing: One of the eight general-registers, R0 to R7, can be specified as the
instruction operand. The assembly language documentation refers to a register generically
as Rn. Ex: ADD A, R5; Adds register R5 contents to A (accumulator)

Direct addressing: Means that the data value is obtained directly from the memory
location specified in the operand. For ex: MOV A, 47h. The instruction reads the data
from Internal RAM address 47h and stores this in the accumulator.
Direct addressing can be used to access Internal RAM , including the SFR registers.

Harish G C, Assistant Professor, Department of E&CE 21


8051 Microcontroller

Indirect Addressing: In this mode of addressing the instruction performs an operation on


the data whose address is contained in register R0 or R1. Instructions using indirect
addressing are single byte instructions. In 8051 assembly language the symbol @ before
R0 or R1 denotes indirect addressing.

An example instruction, which uses indirect addressing, is as follows:

MOV A, @R0

@ symbol indicates that it is indirect addressing mode. R0 contains a value, for example
54h, which is to be used as the address of the internal RAM location, which contains the
operand data. Indirect addressing refers to Internal RAM only and cannot be used to refer
to SFR registers.

Note: Only R0 or R1 can be used as register data pointers for indirect addressing when
using
MOV instructions.

Relative Addressing: This addressing mode is used only with certain jump instructions. A
relative address (or offset) is an 8-bit signed value, which is added to the program counter
to form the address of the next instruction executed. The range for such a jump instruction
is –128 to +127 locations. Although the range is rather limited, relative addressing does
offers the advantage of providing position-independent code (since absolute addresses are
not used). For example, the instruction

JZ rel ; performs the following operations:


(PC) ¬ (PC) + 2
IF (A) = 0
THEN (PC) ¬ (PC) + rel
ELSE continue

The branch destination is computed by adding the signed relative-displacement in the


second instruction byte to the PC, after incrementing the PC twice.

Absolute addressing: There are only two instructions that use this addressing: ACALL
(absolute call) and AJMP (absolute jump). These instructions perform branching within

Harish G C, Assistant Professor, Department of E&CE 22


8051 Microcontroller

the current 2K page of program memory. The branch address is obtained by successively
concatenating the five high-order bits of the program counter, bits 5 – 7 of the op-code,
and the second byte of the instruction. The diagram illustrates how this is done:

Note that the branch destination address is within the same 2K page of program memory
because the highest most five address bits are the same as those in the program counter
before the branch is taken.

Long Addressing: Only two instructions use this addressing mode. These instructions are
LCALL addr16 and LJMP addr16. Both of these are three byte instructions with the op-
code being the first byte and the following two bytes are the address high-byte and
address low-byte respectively. These instructions enable the program to branch to
anywhere within the full 64 K-bytes of program memory address space (216 = 64K).

An example instruction is: LJMP 5000h; full 16 bit address is specified in operand

Indexed Addressing: With indexed addressing a separate register, either the program
counter, PC, or the data pointer DTPR, is used as a base address and the accumulator is
used as an offset
address. The effective address is formed by adding the value from the base address to the
value from the offset address. Indexed addressing in the 8051 is used with the JMP or
MOVC instructions. Look up tables are easy to implement with the help of index
addressing.

Consider the example instruction:

JMP @A+DPTR (PC) ¬ (A) +(DPTR)


MOVC A,@A+DPTR (A) ¬ ((A) + (DPTR))
MOVC A,@A+PC (PC) ¬ (PC) + 1
(A) ¬ ((A) + (PC))

Harish G C, Assistant Professor, Department of E&CE 23


8051 Microcontroller

MOVC is a move instruction, which moves data from the external code memory space.
The address operand in this example is formed by adding the content of the DPTR
register to the accumulator value. Here the DPTR value is referred to as the base address
and the accumulator value us referred to as the index address.

2.4 Types of instructions


The 8051 instructions are divided among five functional groups:
i. Data transfer
ii. Arithmetic
iii. Logical
iv. Boolean
v. Program branching

The assembly level instructions include: data transfer instructions, arithmetic,


instructions, logical instructions, program control instructions, and some special
instructions such as the rotate instructions.

i. Data transfer

Many computer operations are concerned with moving data from one location to another.
The 8051 uses five different types of instruction to move data:
MOV MOVX MOVC PUSH and POP XCH

MOV
In the 8051 the MOV instruction is concerned with moving data internally, i.e. between
Internal RAM, SFR registers, general registers etc. MOVX and MOVC are used in
accessing external memory data. The MOV instruction has the following format:

MOV destination <- source

The instruction copies (copy is a more accurate word than move) data from a defined
source location to a destination location. Example MOV instructions are:

MOV R2, #80h ; Move immediate data value 80h to register R2


MOV R4, A ; Copy data from accumulator to register R4
MOV DPTR, #0F22Ch ; Move immediate value F22Ch to the DPTR register
MOV R2, 80h ; Copy data from 80h (Port 0 SFR) to R2
MOV 52h, #52h ; Copy immediate data value 52h to RAM location 52h
MOV 52h, 53h ; Copy data from RAM location 53h to RAM 52h
MOV A, @R0 ; Copy contents of location addressed in R0 to A
(Indirect addressing)

Harish G C, Assistant Professor, Department of E&CE 24


8051 Microcontroller

MOVX
The 8051 the external memory can be addressed using indirect addressing only. The
DPTR register is used to hold the address of the external data (since DPTR is a 16-bit
register it can address 64KByte locations: 216 = 64K). The 8 bit registers R0 or R1 can
also be used for indirect addressing of external memory but the address range is limited to
the lower 256 bytes of memory (28 = 256 bytes).

The MOVX instruction is used to access the external memory (X indicates eXternal
memory access). All external moves must work through the A register (accumulator).
Examples of MOVX instructions are:

MOVX @DPTR, A ; Copy data from A to the address specified in DPTR


MOVX A, @DPTR ; Copy data from address specified in DPTR to A

MOVC
MOVX instructions operate on RAM, which is (normally) a volatile memory. Program
tables often need to be stored in ROM since ROM is non-volatile memory. The MOVC
instruction is used to read data from the external code memory (ROM). Like the MOVX
instruction the DPTR register is used as the indirect address register. The indirect
addressing is enhanced to realize an indexed addressing mode where register A can be
used to provide an offset in the address specification. Like the MOVX instruction all
moves must be done through register A. The following sequence of instructions provides
an example:

MOV DPTR, # 2000h ; Copy the data value 2000h to the DPTR register
MOV A, #80h ; Copy the data value 80h to register A
MOVC A, @A+DPTR ; Copy the contents of the address 2080h (2000h + 80h) to register A

Note: for the MOVC the program counter can also be used to form the address.

XCH
The above move instructions copy data from a source location to a destination location,
leaving the source data unaffected. A special XCH (eXCHange) instruction will actually
swap the data between source and destination, effectively changing the source data.
Immediate addressing may not be used with XCH. XCH instructions must use register A.
XCHD is a special case of the exchange instruction where just the lower nibbles are
exchanged. Examples using the XCH instruction are:

XCH A, R3 ; Exchange bytes between A and R3


XCH A, @R0 ; Exchange bytes between A and RAM location whose address is in R0
XCH A, A0h ; Exchange bytes between A and RAM location A0h (SFR port 2)

Harish G C, Assistant Professor, Department of E&CE 25


8051 Microcontroller

ii. Arithmetic:
Some key flags within the PSW, i.e. C, AC, OV, P, are utilized in many of the arithmetic
instructions. The arithmetic instructions can be grouped as follows:

➢ Addition
➢ Subtraction
➢ Increment/decrement
➢ Multiply/divide
➢ Decimal adjust

Addition
Register A (the accumulator) is used to hold the result of any addition operation. Some
simple addition examples are:

ADD A, #25h ; Adds the number 25h to A, putting sum in A


ADD A, R3 ; Adds the register R3 value to A, putting sum in A

The flags in the PSW register are affected by the various addition operations, as follows:

✓ The C (carry) flag is set to 1 if the addition resulted in a carry out of the
accumulator’s MSB bit, otherwise it is cleared.
✓ The AC (auxiliary) flag is set to 1 if there is a carry out of bit position 3 of the
accumulator, otherwise it is cleared.
✓ For signed numbers the OV flag is set to 1 if there is an arithmetic overflow
(described elsewhere in these notes)

Simple addition is done within the 8051 based on 8 bit numbers, but it is often required to
add 16 bit numbers, or 24 bit numbers etc. This leads to the use of multiple byte (multi-
precision) arithmetic. The least significant bytes are first added, and if a carry results, this
carry is carried over in the addition of the next significant byte etc. This addition process
is done at 8-bit precision steps to achieve multi precision arithmetic. The ADDC
instruction is used to include the carry bit in the addition process. Example instructions
using ADDC are:

ADDC A, #55h ; Add contents of A, the number 55h, the carry bit; and put the sum in A
ADDC A, R4 ; Add the contents of A, the register R4, the carry bit; and put the sum in A.

Subtraction
Computer subtraction can be achieved using 2’s complement arithmetic. Most computers
also provide instructions to directly subtract signed or unsigned numbers. The
accumulator, register A, will contain the result (difference) of the subtraction operation.
The C (carry) flag is treated as a borrow flag, which is always subtracted from the
minuend during a subtraction operation. Some examples of subtraction instructions are:

Harish G C, Assistant Professor, Department of E&CE 26


8051 Microcontroller

SUBB A, #55d ; Subtract the number 55 and the C flag from A; and put the result in A.
SUBB A, R6 ; Subtract R6 the C flag from A; and put the result in A.
SUBB A, 58h ; Subtract the number in RAM location 58h and the C flag From A; and
put the result in A.

Increment/Decrement
The increment (INC) instruction has the effect of simply adding a binary 1 to a number
while a decrement (DEC) instruction has the effect of subtracting a binary 1 from a
number. The increment and decrement instructions can use the addressing modes: direct,
indirect and register. The flags C, AC, and OV are not affected by the increment or
decrement instructions. If a value of FFh is increment it overflows to 00h. If a value of
00h is decrement it underflows to FFh. The DPTR can overflow from FFFFh to 0000h.
The DPTR register cannot be decremented using a DEC instruction (unfortunately!).
Some example INC and DEC instructions are as follows:

INC R7 ; Increment register R7


INC A ; Increment A
INC @R1 ; Increment the number which is the content of the address in R1
DEC A ; Decrement register A
DEC 43h ; Decrement the number in RAM address 43h
INC DPTR ; Increment the DPTR register

Multiply / Divide
The 8051 supports 8-bit multiplication and division. This is low precision (8 bit)
arithmetic but is useful for many simple control applications. The arithmetic is relatively
fast since multiplication and division are implemented as single instructions. If better
precision, or indeed, if floating point arithmetic is required then special software routines
need to be written. For the MUL or DIV instructions the A and B registers must be used
and only unsigned numbers are supported. Flags affected are OV and CY.

Multiplication
The MUL instruction is used as follows (note absence of a comma between the A and
B operands): MUL AB; Multiply A by B. The resulting product resides in registers A
and B, the low-order byte is in A and the high order byte is in B.
Division
The DIV instruction is used as follows:
DIV AB ; A is divided by B.
The remainder is put in register B and the integer part of the quotient is put in register
A.
Decimal Adjust (Special)
The 8051 performs all arithmetic in binary numbers (i.e. it does not support BCD
arithmetic). If two BCD numbers are added then the result can be adjusted by using the
DA, decimal adjust, instruction:
DA A ; Decimal adjust A following the addition of two BCD numbers.

Harish G C, Assistant Professor, Department of E&CE 27


8051 Microcontroller

iii. Logical operations:


Most control applications implement control logic using Boolean operators to act on the
data. Most microcomputers provide a set of Boolean instructions that act on byte level
data. However, the 8051 (somewhat uniquely) additionally provides Boolean instruction
which can operate on bit level data.

The following Boolean operations can operate on byte level or bit level data:

ANL Logical AND


ORL Logical OR
CPL Complement (logical NOT)
XRL Logical XOR (exclusive OR)

The destination address of the operartion can be the accumulator (register A), a general
register, or a direct address. Status flags are not affected by these logical operations
(unless PSW is directly manipulated). Example instructions are:

ANL A, #55h ; AND each bit in A with corresponding bit in number 55h, leaving the
result in A.
ANL 42h, R4 ; AND each bit in RAM location 42h with corresponding bit in R4, leaving
the result in RAM location 42h.
ORL A,@R1 ; OR each bit in A with corresponding bit in the number whose address is
contained in R1 leaving the result in A.
XRL R4, 80h ; XOR each bit in R4 with corresponding bit in RAM location 80h (port 0),
leaving result in A.
CPL R0 ; Complement each bit in R0

Rotate Instructions
The ability to rotate the A register (accumulator) data is useful to allow examination of
individual bits. The options for such rotation are as follows:
RL A ; Rotate A one bit to the left. Bit 7 rotates to the bit 0 position

RLC A ; The Carry flag is used as a ninth bit in the rotation loop

Harish G C, Assistant Professor, Department of E&CE 28


8051 Microcontroller

Swap =
special
The Swap
instruction
swaps the accumulator’s high order nibble with the low-order nibble using the instruction:

iv. Branch instructions


The 8051 supports three kinds of unconditional jump instructions: LJMP SJMP AJMP

LJMP
LJMP (long jump) causes the program to branch to a destination address defined by the
16-bit operand in the jump instruction. Because a 16-bit address is used the instruction
can cause a jump to any location within the 64KByte program space (216 = 64K). Some
example instructions are:

LJMP LABEL_X ; Jump to the specified label


LJMP 0F200h ; Jump to address 0F200h
LJMP @A+DPTR ; Jump to address which is the sum of DPTR and Reg. A

SJMP
SJMP (short jump) uses a single byte address. This address is a signed 8-bit number and
allows the program to branch to a distance –128 bytes back from the current PC address
or +127 bytes forward from the current PC address. The address mode used with this
form of jumping (or branching) is referred to as relative addressing, introduced earlier, as
the jump is calculated relative to the current PC address.

AJMP
This is a special 8051 jump instruction, which allows a jump with a 2KByte address
boundary (a 2K page) There is also a generic JMP instruction supported by many 8051

Harish G C, Assistant Professor, Department of E&CE 29


8051 Microcontroller

assemblers. The assembler will decide which type of jump instruction to use, LJMP,
SJMP or AJMP, so as to choose the most efficient instruction.

Program control using conditional jumps


Most 8051 jump instructions use an 8-bit destination address, based on relative
addressing, i.e. addressing within the range –128 to +127 bytes. When using a conditional
jump instruction the programmer can simply specify a program label or a full 16-bit
address for the conditional jump instruction’s destination. The assembler will position the
code and work out the correct 8-bit relative address for the instruction. Some example
conditional jump instructions are:

JZ LABEL_1 ; Jump to LABEL_1 if accumulator is equal to zero


JNZ LABEL_X ; Jump to LABEL_X if accumulator is not equal to zero
JNC LABEL_Y ; Jump to LABEL_Y if the carry flag is not set
DJNZ R2, LABEL ; Decrement R2 and jump to LABEL if the resulting value of R2 is not
zero.
CJNE R1, #55h , LABEL_2 ; Compare the magnitude of R1 and the number 55h and
jump to
LABEL_2 if the magnitudes are not equal.

Note, jump instructions such as DJNZ and CJNE are very powerful as they carry out a
particular operation (e.g.: decrement, compare) and then make a decision based on the
result of this operation. Some example code later will help to explain the context in which
such instructions might be used.

v. Boolean Instructions:
The 8051 has a range of Boolean variable manipulating instructions which enable us to
set or reset individual bits within some of the locations in the internal RAM, and some of
the special function registers. We give some examples of these instructions in the table
below.
The following SFR registers are addressable in bit level operations: PSW, IE, IP, TCON,
SCON.

Examples of bit level logical operations are as follows:

SETB 2Fh ; Bit 7 of Internal RAM location 25h is set


CLR C ; Clear the carry flag (flag =0)
CPL 20h ; Complement bit 0 of Internal RAM location 24h
MOV C, 87h ; Move to carry flag the bit 7of Port 0 (SFR at 80h)
ANL C,90h ; AND C with the bit 0 of Port 1 (SFR at 90)
ORL C, 91h ; OR C with the bit 1 of Port 1 (SFR at 90)

Harish G C, Assistant Professor, Department of E&CE 30


8051 Microcontroller

1. Write a program to add the values of locations 50H and 51H and store the result in
locations in 52h and 53H.

ORG 0000H ; Set program counter 0000H


MOV A,50H ; Load the contents of Memory location 50H into A ADD ADD A,51H
; Add the contents of memory 51H with CONTENTS A
MOV 52H,A ; Save the LS byte of the result in 52H
MOV A, #00 ; Load 00H into A
ADDC A, #00 ; Add the immediate data and carry to A
MOV 53H,A ; Save the MS byte of the result in location 53h
END

2. Write a program to store data FFH into RAM memory locations 50H to 58H using direct
addressing mode

ORG 0000H ; Set program counter 0000H


MOV A, #0FFH ; Load FFH into A
MOV 50H, A ; Store contents of A in location 50H
MOV 51H, A ; Store contents of A in location 5IH
MOV 52H, A ; Store contents of A in location 52H
MOV 53H, A ; Store contents of A in location 53H
MOV 54H, A ; Store contents of A in location 54H
MOV 55H, A ; Store contents of A in location 55H
MOV 56H, A ; Store contents of A in location 56H
MOV 57H, A ; Store contents of A in location 57H
MOV 58H, A ; Store contents of A in location 58H

END

3. Write a program to subtract a 16 bit number stored at locations 51H-52H from 55H-56H
and store the result in locations 40H and 41H. Assume that the least significant byte of data or
the result is stored in low address. If the result is positive, then store 00H, else store 01H in
42H.

ORG 0000H ; Set program counter 0000H


MOV A, 55H ; Load the contents of memory location 55 into A
CLR C ; Clear the borrow flag
SUBB A,51H ; Sub the contents of memory 51H from contents of A
MOV 40H, A ; Save the LSByte of the result in location 40H
MOV A, 56H ; Load the contents of memory location 56H into A
SUBB A, 52H ; Subtract the content of memory 52H from the content A
MOV 41H, ; Save the MSbyte of the result in location 415.
MOV A, #00 ; Load 005 into A
ADDC A, #00 ; Add the immediate data and the carry flag to A
MOV 42H, A ; If result is positive, store00H, else store 0lH in 42H

END

4. Write a program to add two 16 bit numbers stored at locations 51H-52H and 55H-56H and
store the result in locations 40H, 41H and 42H. Assume that the least significant byte of data
and the result is stored in low address and the most significant byte of data or the result
is stored in high address.

ORG 0000H ; Set program counter 0000H


MOV A,51H ; Load the contents of memory location 51H into A
ADD A,55H ; Add the contents of 55H with contents of A
MOV 40H,A ; Save the LS byte of the result in location 40H

Harish G C, Assistant Professor, Department of E&CE 31


8051 Microcontroller

MOV A,52H ; Load the contents of 52H into A


ADDC A,56H ; Add the contents of 56H and CY flag with A
MOV 41H,A ; Save the second byte of the result in 41H
MOV A,#00 ; Load 00H into A
ADDC A,#00 ; Add the immediate data 00H and CY to A
MOV 42H,A ; Save the MS byte of the result in location 42H

END

5. Write a program to store data FFH into RAM memory locations 50H to 58H using indirect
addressing mode.

ORG 0000H ; Set program counter 0000H


MOV A, #0FFH ; Load FFH into A
MOV RO, #50H ; Load pointer, R0-50H
MOV R5, #08H ; Load counter, R5-08H
Start:MOV @RO, A ; Copy contents of A to RAM pointed by R0
INC RO ; Increment pointer
DJNZ R5, start ; Repeat until R5 is zero

END

6. Write a program to add two Binary Coded Decimal (BCD) numbers stored at locations 60H
and 61H and store the result in BCD at memory locations 52H and 53H. Assume that the
least significant byte of the result is stored in low address.

ORG 0000H ; Set program counter 00004


MOV A,60H ; Load the contents of memory location 6.0.H into A
ADD A,61H ; Add the contents of memory location 61H with contents of A
DA A ; Decimal adjustment of the sum in A
MOV 52H, A ; Save the least significant byte of the result in location 52H
MOV A,#00 ; Load 00H into .A
ADDC A,#00H ; Add the immediate data and the contents of carry flag to A
MOV 53H,A ; Save the most significant byte of the result in location 53:,

END

7. Write a program to clear 10 RAM locations starting at RAM address 1000H.

ORG 0000H ;Set program counter 0000H


MOV DPTR, #1000H ;Copy address 1000H to DPTR
CLR A ;Clear A
MOV R6, #0AH ;Load 0AH to R6
again: MOVX @DPTR,A ;Clear RAM location pointed by DPTR
INC DPTR ;Increment DPTR
DJNZ R6, again ;Loop until counter R6=0

END

8. Write a program to compute 1 + 2 + 3 + N (say N=15) and save the sum at70H
ORG 0000H ; Set program counter 0000H
N EQU 15
; Clear R0
MOV R0,#00
CLR A ; Clear A
again: INC R0 ; Increment R0
ADD A, R0 ; Add the contents of R0 with A
CJNE R0,#N,again ; Loop until counter, R0, N

Harish G C, Assistant Professor, Department of E&CE 32


8051 Microcontroller

MOV 70H,A ; Save the result in location 70H END

9. Write a program to multiply two 8 bit numbers stored at locations 70H and 71H and store
the result at memory locations 52H and 53H. Assume that the least significant byte of the
result is stored in low address.

ORG 0000H ; Set program counter 00 OH


MOV A, 70H ; Load the contents of memory location 70h into A
MOV B, 71H ; Load the contents of memory location 71H into B
MUL AB ; Perform multiplication
MOV 52H,A ; Save the least significant byte of the result in location 52H MOV 53H,B ; Save the
most significant byte of the result in location 53

END

10. Ten 8 bit numbers are stored in internal data memory from location 5oH. Write a
program to increment the data.
Assume that ten 8 bit numbers are stored in internal data memory from location 50H, hence
R0 or R1 must be used as a pointer.
The program is as follows.

OPT 0000H
MOV R0,#50H
MOV R3,#0AH
Loopl: INC @R0
INC RO
DJNZ R3, loopl END

END

11. Write a program to find the average of five 8 bit numbers. Store the result in H.
(Assume that after adding five 8 bit numbers, the result is 8 bit only).

ORG 0000H
MOV 40H,#05H
MOV 41H,#55H
MOV 42H,#06H
MOV 43H,#1AH
MOV 44H,#09H
MOV R0,#40H
MOV R5,#05H
MOV B,R5
CLR A
Loop: ADD A,@RO
INC RO
DJNZ R5,Loop
DIV AB
MOV 55H,A

END

12. Write a program to find the cube of an 8 bit number program is as follows

ORG 0000H
MOV R1,#N
MOV A,R1 //SQUARE IS COMPUTED
MOV B,R1
MUL AB

Harish G C, Assistant Professor, Department of E&CE 33


8051 Microcontroller

MOV R2, B
MOV B, R1
MUL AB
MOV 50,A
MOV 51,B
MOV A,R2
MOV B, R1
//CUBE IS STORED IN 52H,51H,50H
MUL AB
ADD A, 51H
MOV 51H, A
MOV 52H, B
MOV A, # 00H
ADDC A, 52H
MOV 52H, A

END

13. Write a program to exchange the lower nibble of data present in external memory 6000H and
6001H

ORG 0000H ;Setprogramcounter00h


MOV DPTR, #6000H ; Copy address 6000H to DP TR
MOVX A, @DPTR ;Copycontentsof60008toA
MOV R0, #45H ;Loadpointer,R0=45H
MOV @RO, A ;CopycontofAtoRAMpointedby80
INC DPL ;Incrementpointer
MOVX A, @DPTR ;Copycontentsof60018toA
XCHD A, @R0 ;E x c h a n g e l o w e r n i b b l e o f A w i t h R A M p o i n t e d b y R O
MOVX @DPTR, A ;CopycontentsofAto60018
DEC DPL ;Decrementpointer
MOV A, @R0 ;CopycontofRAMpointedbyR0toA
MOVX @DPTR, A ;CopycontofAtoRAMpointedbyDPTR

END

14. Write a program to count the number of and o's of 8 bit data stored in location 6000H.

ORG 00008 ; Set program counter 00008


MOV DPTR, #6000h ; Copy address 6000H to DPTR
MOVX A, @DPTR ;CopynumbertoA
MOV R0,#08 ; C o py 0 8 i n R O
MOV R2,#00 ;Copy00inR2
MOV R3,#00 ;Copy00inR3
CLR C ; Clear carry flag
BACK: RLC A ;RotateAthroughcarryflag
JC NEXT ;IfCF=1,branchtonext
INC R2 ; I f C F = 0 , i n c r e m e n t R 2 AJMP NEXT2
NEXT: INC R3 ;IfCF=1,incrementR3
NEXT2: DJNZ RO,BACK ;RepeatuntilROiszero

END

16. Two 8 bit numbers are stored in location 1000h and 1001h of external data memory. Write
a program to find the GCD of the numbers and store the result in 2000h.

Harish G C, Assistant Professor, Department of E&CE 34


8051 Microcontroller

ALGORITHM
• Step 1 :Initialize external data memory with data and DPTR with address
• Step 2 :Load A and TEMP with the operands
• Step 3 :Are the two operands equal? If yes, go to step 9
• Step 4 :Is (A) greater than (TEMP) ? If yes, go to step 6
• Step 5 :Exchange (A) with (TEMP) such that A contains the bigger number
• Step 6 :Perform division operation (contents of A with contents of TEMP)
• Step 7 :If the remainder is zero, go to step 9
• Step 8 :Move the remainder into A and go to step 4
• Step 9 :Save the contents 'of TEMP in memory and terminate the program

ORG 0000H ; Set program counter 0000H


TEMP EQU 70H
TEMPI EQU 71H
; Copy address 100011 to DPTR
MOV DPTR, #1000H
MOVX A, @DPTR ; Copy First number to A
MOV TEMP, A ; Copy First number to temp INC DPTR
MOVX A, @DPTR ; Copy Second number to A
LOOPS: CJNE A, TEMP,
; (A) /= (TEMP) branch to LOOP1
LOOP1
AJMP LOOP2 ; (A) = (TEMP) branch to L00P2
LOOP1: JNC LOOP3 ; (A) > (TEMP) branch to LOOP3
; (A) < (TEMP) exchange (A) with
NOV TEMPI, A
(TEMP)
MOV A, TEMP
MOV TEMP, TEMPI
LOOP3: MOV B, TEMP
DIV AB ; Divide (A) by (TEMP)
MOV A, B ; Move remainder to A
CJNE A,#00, LOOPS ; (A)/=00 branch to LOOPS
LOOP2: MOV A, TEMP
MOV DPTR, #2000H ; Store the result in 2000H
MOVX @DPTR, A

END

3. 8051 Stack, I/O Port Interfacing and Programming

Harish G C, Assistant Professor, Department of E&CE 35


8051 Microcontroller

2.10 STACK IN 8051

• RAM locations from 08H to 1FH can be used as stack. Stack is used to store the data
temporarily. Stack is last in first out (LIFO)
• Stack pointer (SP)
✓ 8bit register
✓ It indicates current RAM address available for
stack or it points the top of stack.
✓ Initially by default at 07H because first location of
stack is 08H.
✓ After each PUSH instruction the SP is incremented
by one while in MC after PUSH instruction SP is
decremented.
✓ After each POP instruction the SP is decremented.

PUSH and POP


PUSH and POP instructions are used with the stack only. The SFR register SP contains
the current stack address. Direct addressing is used as shown in the following examples:

PUSH 4Ch ; Contents of RAM location 4Ch is saved to the stack. SP is incremented.
PUSH 00h ; The content of R0 (which is at 00h in RAM) is saved to the stack and SP is
incremented.
POP 80h ; The data from current SP address is copied to 80h and SP is decremented.

Example:

MOV R6,#25H;
MOV R1,#12H;
MOV R4,#OF3H;
PUSH 06H;
PUSH 01H;
POP 04H;

Harish G C, Assistant Professor, Department of E&CE 36


8051 Microcontroller

• If we want to use other than 24byte (08H to 1FH) of stack. We can change SP to point
RAM address 30H to 7FH by MOV SP, #XX ; Any value from 30 to 7FH

Conflicting of Register Banks and Stack:

• We know locations from 08H to 1FH is used as stack and it is also used as register
bank.
• If in the program, we use the Register Bank 1 to 3 and also use the stack then
conflicts exist and error can be possible.
• For removing this situation we use the stack from location 30H to 7FH by shifting
SP to 2FH. MOV SP,#2FH;

Example A: Show the stack and stack pointer from the following. Assume the default
stack area.

MOV R6, #25H


MOV R1, #12H
MOV R4, #0F3H
PUSH 6
PUSH 1
PUSH 4

Solution:

Harish G C, Assistant Professor, Department of E&CE 37


8051 Microcontroller

Example B: Examining the stack, show the contents of the register and SP after
execution of the following instructions. All value are in hex.

POP 3 ; POP stack into R3


POP 5 ; POP stack into R5
POP 2 ; POP stack into R2

Solution:

A subroutine is called using the LCALL or the ACALL instruction.

LCALL
This instruction is used to call a subroutine at a specified address. The address is 16 bits
long so the call can be made to any location within the 64KByte memory space. When a
LCALL instruction is executed the current PC content is automatically pushed onto the
stack of the PC. When the program returns from the subroutine the PC contents is
returned from the stack so that the program can resume operation from the point where
the LCALL was made The return from subroutine is achieved using the RET instruction,
which simply pops the PC back from the stack.
The LCALL instruction works as follows.

a. During execution of LCALL, [PC] = [PC]+3; (if address where LCALL resides is say,
0x3254; during execution of this instruction [PC] = 3254h + 3h = 3257h
b. [SP]=[SP]+1; (if SP contains default value 07, then SP increments and [SP]=08
c. [[SP]] = [PC7-0]; (lower byte of PC content ie., 57 will be stored in memory location
08.
d.[SP]=[SP]+1; (SP increments again and [SP]=09)
e. [[SP]] = [PC15-8]; (higher byte of PC content ie., 32 will be stored in memory location
09. With these the address (0x3254) which was in PC is stored in stack.
f. [PC]= address (16 bit); the new address of subroutine is loaded to PC. No flags are
affected

Harish G C, Assistant Professor, Department of E&CE 38


8051 Microcontroller

ACALL
The ACALL instruction is logically similar to the LCALL but has a limited address range
similar to the AJMP instruction. CALL is a generic call instruction supported by many
8051 assemblers. The assembler will decide which type of call instruction, LCALL or
ACALL, to use so as to choose the most efficient instruction.

The ACALL instruction works as follows.

a. During execution of ACALL, [PC] = [PC]+2; (if address where LCALL resides is say,
0x8549; during execution of this instruction [PC] = 8549h + 2h = 854Bh
b. [SP]=[SP]+1; (if SP contains default value 07, then SP increments and [SP]=08
c. [[SP]] = [PC7-0]; (lower byte of PC content ie., 4B will be stored in memory location
08.
d. [SP]=[SP]+1; (SP increments again and [SP]=09)
e. [[SP]] = [PC15-8]; (higher byte of PC content ie., 85 will be stored in memory location
09. With these the address (0x854B) which was in PC is stored in stack
f. [PC10-0]= address (11 bit); the new address of subroutine is loaded to PC. No flags are
affected

RET instruction
RET instruction pops top two contents from the stack and load it to PC.

a. [PC15-8] = [[SP]] ;content of current top of the stack will be moved to higher byte of
PC.
b. [SP]=[SP]-1; (SP decrements)
c. [PC7-0] = [[SP]] ;content of bottom of the stack will be moved to lower byte of PC.
d. [SP]=[SP]-1; (SP decrements again)

2.5 TIME DELAY CALCULATIONS:


CPU executing an instruction takes a certain number of clock cycles referred as to as
machine cycles

✓ The length of machine cycle depends on the frequency of the crystal oscillator
connected to 8051
✓ In original 8051, one machine cycle lasts 12 oscillator periods

Example (3.5.1): Find the period of the machine cycle for 11.0592 MHz crystal
frequency and find how long it takes to execute each instruction.
(a) MOV R3,#55 (b) DEC R3 (c) DJNZ R2 target
(d) LJMP (e) SJMP (f) NOP (g) MUL AB

Solution:
11.0592/12 = 921.6 kHz;
machine cycle is 1/921.6 kHz = 1.085μs

Harish G C, Assistant Professor, Department of E&CE 39


8051 Microcontroller

Machine cycles Time to execute


(a) 1 1x1.085μs = 1.085μs
(b) 1 1x1.085μs = 1.085μs
(c) 2 2x1.085μs = 2.17μs
(d) 2 2x1.085μs = 2.17μs
(e) 2 2x1.085μs = 2.17μs
(f) 1 1x1.085μs = 1.085μs
(g) 4 4x1.085μs = 4.34μs
------------------------------------------------------------------------------------------------------------
Example (3.5.2): Find the size of the delay in following program, if the crystal frequency
is 11.0592MHz.

MOV A,#55H
AGAIN: MOV P1,A
ACALL DELAY
CPL A
SJMP AGAIN

;---time delay-------

DELAY: MOV R3,#200


HERE: DJNZ R3,HERE
RET

Solution:

Machine cycle

DELAY: MOV R3,#200 1


HERE: DJNZ R3,HERE 2
RET 2

Therefore, [(200x2) +1+2] x 1.085μs = 436.255μs.


-----------------------------------------------------------------------------------------------------------
3.5.1 INCREASING DELAY USING NOP:

Example (3.5.3): Find the size of the delay in following program, if the crystal frequency
is 11.0592MHz.

Machine Cycle
DELAY: MOV R3,#250 1
HERE: NOP 1

Harish G C, Assistant Professor, Department of E&CE 40


8051 Microcontroller

NOP 1
NOP 1
NOP 1
DJNZ R3,HERE 2
RET 2
Solution:

The time delay inside HERE loop is [250(1+1+1+1+2)] x1.085μs = 1627.5μs.


Adding the two instructions outside loop we have 1627.5μs + 3 x 1.085μs = 1630.755μs
------------------------------------------------------------------------------------------------------------
3.5.2 LARGE DELAY USING NESTED LOOP:

Example (3.5.4): Find the size of the delay in following program, if the crystal frequency
is 11.0592MHz.

Machine Cycle
DELAY: MOV R2,#200 1
AGAIN: MOV R3,#250 1
HERE: NOP 1
NOP 1
DJNZ R3,HERE 2
DJNZ R2,AGAIN 2
RET 2
Solution:

For HERE loop, we have (4x250)x1.085μs=1085μs.


For AGAIN loop repeats HERE loop 200 times, so we have 200x1085μs=217000μs. But
“MOV R3,#250” and “DJNZ R2,AGAIN” at the start and end of the AGAIN loop add
(3x200x1.805)=651μs.

As a result we have 217000+651=217651μs.

Note: the time is approximate since we have ignored the first and last instructions in the
subroutine.
------------------------------------------------------------------------------------------------------------
3.5.3 DELAY CALCULATION FOR OTHER 8051:

Two factors can affect the accuracy of the delay

Crystal frequency: The duration of the clock period of the machine cycle is a function of
this crystal frequency

8051 design: The original machine cycle duration was set at 12 clocks.

Harish G C, Assistant Professor, Department of E&CE 41


8051 Microcontroller

Advances in both IC technology and CPU design in recent years have made the 1-clock
machine cycle a common feature

Clocks per machine cycle for various 8051 versions

Chip/Maker Clocks per Machine Cycle

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

Example (3.5.5): Find the period of the machine cycle (MC) for various versions of
8051, if XTAL=11.0592 MHz. (a) AT89C51 (b) P89C54X2 (c) DS5000 (d) DS89C4x0

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

------------------------------------------------------------------------------------------------------------
Example (3.5.6): For an AT8051 and DSC89C4x0 system of 11.0592 MHz, find how
long it takes to execute each instruction.

(a) MOV R3,#55 (b) DEC R3 (c) DJNZ R2 target


(d) LJMP (e) SJMP (f) NOP (g) MUL AB

Solution:

AT8051 DS89C4x0

Harish G C, Assistant Professor, Department of E&CE 42


8051 Microcontroller

(a) 1x1085ns = 1085ns 2x90ns = 180ns


(b) 1x1085ns = 1085ns 1x90ns = 90ns
(c) 2x1085ns = 2170ns 4x90ns = 360ns
(d) 2x1085ns = 2170ns 3x90ns = 270ns
(e) 2x1085ns = 2170ns 3x90ns = 270ns
(f) 1x1085ns = 1085ns 1x90ns = 90ns
(g) 4x1085ns = 4340ns 9x90ns = 810ns

Harish G C, Assistant Professor, Department of E&CE 43


8051 Microcontroller

Harish G C, Assistant Professor, Department of E&CE 44


8051 Microcontroller

Harish G C, Assistant Professor, Department of E&CE 45


8051 Microcontroller

8051 TIMERS AND SERIAL PORT

------------------------------------------------------------------------------------------------------------
4.3 TIMER PROGRAMMING
The 8051 has two timers/counters, they can be used either as

✓ Timers to generate a time delay or as


✓ Event counters to count events happening outside the microcontroller

Both Timer 0 and Timer 1 are 16 bits wide. Since 8051 has an 8-bit architecture, each 16-
bits timer is accessed as two separate registers of low byte (TL0/TL1) and high byte
(TH0/TH1). Accessed like any other register. Ex: MOV TL0,#4FH
MOV R5,TH0

Both timers 0 and 1 use the same register, called TMOD (timer mode), to set the various
timer operation modes. TMOD is a 8-bit register.

Harish G C, Assistant Professor, Department of E&CE 46


8051 Microcontroller

Fig 4.3.1: TMOD register format

Example 4.3.1: Indicate which mode and which timer are selected for each of the
following.
(a) MOV TMOD, #01H (b) MOV TMOD, #20H (c) MOV TMOD, #12H

Solution:
We convert the value from hex to binary. From Figure 9-3 we have:
(a) TMOD = 00000001, mode 1 of timer 0 is selected.
(b) TMOD = 00100000, mode 2 of timer 1 is selected.
(c) TMOD = 00010010, mode 2 of timer 0, and mode 1 of timer 1 are selected.
------------------------------------------------------------------------------------------------------------
Example 4.3.2: Find the timer’s clock frequency and its period for various 8051-based
system, with the crystal frequency 11.0592 MHz when C/T bit of TMOD is 0.

Solution:

1/12 × 11.0529 MHz = 921.6 MHz;


T = 1/921.6 kHz = 1.085 us
------------------------------------------------------------------------------------------------------------

Harish G C, Assistant Professor, Department of E&CE 47


8051 Microcontroller

4.3.1 TIMER MODE 1 PROGRAMMING:

The following are the characteristics and operations of mode1:

1. It is a 16-bit timer; therefore, it allows value of 0000 to FFFFH to be loaded into


the timer’s register TL and TH
2. After TH and TL are loaded with a 16-bit initial value, the timer must be started. This
is done by SETB TR0 for timer 0 and SETB TR1 for timer 1
3. After the timer is started, it starts to count up
✓ It counts up until it reaches its limit of FFFFH
✓ When it rolls over from FFFFH to 0000, it sets high a flag bit called TF (timer
flag). Each timer has its own timer flag: TF0 for timer 0, and TF1 for timer 1. This
timer Flag can be monitored
✓ When this timer flag is raised, one option would be to stop the timer with the
instructions CLR TR0 or CLR TR1, for timer 0 and timer 1, respectively
4. After the timer reaches its limit and rolls over, in order to repeat the process
✓ TH and TL must be reloaded with the original value, and
✓ TF must be reloaded to 0

The following are the steps to Mode 1 Program:

1. Load the TMOD value register indicating which timer (timer 0 or timer 1) is to be
used and which timer mode (0 or 1) is selected
2. Load registers TL and TH with initial count value
3. Start the timer
4. Keep monitoring the timer flag (TF) with the JNB TFx, target instruction to see if it is
raised. Get out of the loop when TF becomes high
5. Stop the timer
6. Clear the TF flag for the next round
7. Go back to Step 2 to load TH and TL again

Example 4.3.3: In the following program, we create a square wave of 50% duty cycle
(with equal portions high and low) on the P1.5 bit. Timer 0 is used to generate the
time delay. Analyze the program

Solution:

MOV TMOD,#01 ;Timer 0, mode 1(16-bit mode)


HERE: MOV TL0,#0F2H ;TL0=F2H, the low byte

Harish G C, Assistant Professor, Department of E&CE 48


8051 Microcontroller

MOV TH0,#0FFH ;TH0=FFH, the high byte


CPL P1.5 ;toggle P1.5
ACALL DELAY
SJMP HERE
DELAY: SETB TR0 ;start the timer 0
AGAIN: JNB TF0,AGAIN ;monitor timer flag 0 until it rolls over
CLR TR0 ;stop timer 0
CLR TF0 ;clear timer 0 flag
RET

In the above program notice the following step.

1. TMOD is loaded.
2. FFF2H is loaded into TH0-TL0.
3. P1.5 is toggled for the high and low portions of the pulse.
4. The DELAY subroutine using the timer is called.
5. In the DELAY subroutine, timer 0 is started by the SETB TR0 instruction.
6. Timer 0 counts up with the passing of each clock, which is provided by the crystal
oscillator. As the timer counts up, it goes through the states of FFF3, FFF4, FFF5,
FFF6,
FFF7, FFF8, FFF9, FFFA, FFFB, and so on until it reaches FFFFH. One more clock
rolls
it to 0, raising the timer flag (TF0=1).

7. Timer 0 is stopped by the instruction CLR TR0. The DELAY subroutine ends, and the
process is repeated.

Note: To repeat the process, we must reload the TL and TH registers, and the process is
Repeated
------------------------------------------------------------------------------------------------------------
Example 4.3.4: In Example 4.3.3, calculate the amount of time delay in the DELAY
subroutine generated by the timer and also calculate the frequency of the square wave.
Assume XTAL = 11.0592 MHz.

Solution:

✓ Timer frequency = 11.0592 MHz / 12 = 921.6 kHz


✓ clock has a period of T = 1/921.6kHz = 1.085us. In other words, Timer 0 counts
up each 1.085 us
✓ The number of counts for the roll over is FFFFH – FFF2H = 0DH (13 decimal).
However, we add one to 13 because of the extra clock needed when it rolls over

Harish G C, Assistant Professor, Department of E&CE 49


8051 Microcontroller

from FFFF to 0 and raise the TF flag.


✓ This gives Td = 14 × 1.085us = 15.19us for half the pulse.
✓ For the entire period it is
T = 2 × 15.19us = 30.38us as the time delay generated by the timer.
✓ Frequency of square wave generated by the example program 4.3.3 is
f = 1/30.38 us = 32.91 KHz
------------------------------------------------------------------------------------------------------------
Example 4.3.5: Find the delay generated by timer 0 in the following code. Do not include
the overhead due to instruction.

CLR P2.3 ;Clear P2.3


MOV TMOD,#01 ;Timer 0, 16-bitmode
HERE: MOV TL0,#3EH ;TL0=3Eh, the low byte
MOV TH0,#0B8H ;TH0=B8H, the high byte
SETB P2.3 ;SET high timer 0
SETB TR0 ;Start the timer 0
AGAIN: JNB TF0,AGAIN ;Monitor timer flag 0
CLR TR0 ;Stop the timer 0
CLR TF0 ;Clear TF0 for next round
CLR P2.3

Solution:

(a) (FFFFH – B83E + 1) = 47C2H = 18370 in decimal and 18370 × 1.085 us = 19.93 ms
(b) Since THTL = B83EH = 47166 (in decimal) we have 65536 – 47166 = 18370. This
means that the timer counts from B38EH to FFFF. This plus Rolling over to 0 goes
through a total of 18370 clock cycles, where each clock is 1.085 us in duration.

Therefore, we have 18370 × 1.085 us = 19.93145 ms as the width of the pulse.


------------------------------------------------------------------------------------------------------------
Note: The largest time delay generated by timer in mode 1 operation is when we load TH
& TL registers with value 00h.
Therefore we have largest delay = (65536 - 0) × 1.085 us = 71.1065ms.

The value to be loaded in to TH and TL register is calculated using formula

(a) In hex
Td = (FFFF – THTL + 1) × 1.085 us,
Notice that value THTL are in hex.
(b) In decimal
Convert values of the TH, TL register to decimal, then
Td = (65536 - NNNN) × 1.085 us
Where Td is time delay to be generated

Harish G C, Assistant Professor, Department of E&CE 50


8051 Microcontroller

Example 4.3.6: Assume that XTAL = 11.0592 MHz, write a program to generate a
square wave of 2 kHz frequency on pin P1.5.

Solution:
This is similar to Example 9-10, except that we must toggle the bit to generate the square
wave. Look at the following steps.

(a) T = 1 / f = 1 / 2 kHz = 500 us the period of square wave.


(b) 1 / 2 of it for the high and low portion of the pulse is 250 us.
(c) 250 us / 1.085 us = 230 and 65536 – 230 = 65306 which in hex is FF1AH.
(d) TL = 1A and TH = FF, all in hex. The program is as follow.

ORG 0000H
MOV TMOD,#01 ;Timer 0, 16-bitmode
AGAIN: MOV TL1,#1AH ;TL1=1A, low byte of timer
MOV TH1,#0FFH ;TH1=FF, the high byte
SETB TR1 ;Start timer 1
BACK: JNB TF1,BACK ;until timer rolls over
CLR TR1 ;Stop the timer 1
CLR P1.5 ;Clear timer flag 1
CLR TF1 ;Clear timer 1 flag
SJMP AGAIN ;Reload timer
END
------------------------------------------------------------------------------------------------------------
Example 4.3.7: Examine the following program and find the time delay in seconds.
Exclude the overhead due to the instructions in the loop.

MOV TMOD,#10H ;Timer 1, mod 1


MOV R3,#200 ;cnter for multiple delay
AGAIN: MOV TL1,#08H ;TL1=08,low byte of timer
MOV TH1,#01H ;TH1=01,high byte
SETB TR1 ;Start timer 1
BACK: JNB TF1,BACK ;until timer rolls over
CLR TR1 ;Stop the timer 1
CLR TF1 ;clear Timer 1 flag
DJNZ R3,AGAIN ;if R3 not zero then reload timer

Solution:

TH-TL = 0108H = 264 in decimal and 65536 – 264 = 65272. Now


65272 × 1.085 μs = 70.820 ms, and for 200 of them we have
200 ×70.820 ms = 14.164024 seconds.

-----------------------------------------------------------------------------------------------------------

Harish G C, Assistant Professor, Department of E&CE 51


8051 Microcontroller

4.3.2 TIMER MODE 2 PROGRAMMING:

The following are the characteristics and operations of mode 2:

1. It is an 8-bit timer; therefore, it allows only values of 00 to FFH to be loaded into the
timer’s register TH
2. After TH is loaded with the 8-bit value, the 8051 gives a copy of it to TL. Then the
timer must be started. This is done by the instruction SETB TR0 for timer 0 and SETB
TR1 for timer 1
3. After the timer is started, it starts to count up by incrementing the TL register. It counts
up until it reaches its limit of FFH. When it rolls over from FFH to 00, it sets high the
TF (timer flag).
4. When the TL register rolls from FFH to 0 and TF is set to 1, TL is reloaded
automatically with the original value kept by the TH register
✓ To repeat the process, we must simply clear TF and let it go without any need by
the programmer to reload the original value
✓ This makes mode 2 an auto-reload, in contrast with mode 1 in which the
programmer has to reload TH and TL

The following are the steps to Mode 2 Program:

1. Load the TMOD value register indicating which timer (timer 0 or timer 1) is to be
used, and the timer mode (mode 2) is selected
2. Load the TH registers with the initial count value
3. Start timer
4. Keep monitoring the timer flag (TF) with the JNB TFx, target instruction to see
whether it is raised
✓ Get out of the loop when TF goes high
5. Clear the TF flag
6. Go back to Step4, since mode 2 is autoreload

Example 4.3.8: Assume XTAL = 11.0592 MHz, find the frequency of the square wave
generated on pin P1.0 in the following program

ORG 0000H
MOV TMOD,#20H ;T1/8-bit/auto reload
MOV TH1,#5 ;TH1 = 5

Harish G C, Assistant Professor, Department of E&CE 52


8051 Microcontroller

SETB TR1 ;start the timer 1


BACK: JNB TF1,BACK ;till timer rolls over
CPL P1.0 ;P1.0 to hi, lo
CLR TF1 ;clear Timer 1 flag
SJMP BACK ;mode 2 is auto-reload

Solution:
First notice the target address of SJMP. In mode 2 we do not need to reload TH since it is
auto-reload.
Now (256 - 05) × 1.085 us = 251 × 1.085 us = 272.33 us is the high portion of the pulse.
Since it is a 50% duty cycle square wave, the period T is twice of that.
Therefore, T = 2 × 272.33 us = 544.67 us and the frequency = 1.83597 kHz
------------------------------------------------------------------------------------------------------------
Example 4.3.9: Find the frequency of a square wave generated on pin P1.0 in the
following Code

MOV TMOD,#2H ;Timer 0, mod 2 (8-bit, auto reload)


MOV TH0,#0
AGAIN: MOV R5,#250 ;multiple delay count
ACALL DELAY
CPL P1.0
SJMP AGAIN
DELAY: SETB TR0 ;start the timer 0
BACK: JNB TF0,BACK ;stay timer rolls over
CLR TR0 ;stop timer
CLR TF0 ;clear TF for next round
DJNZ R5,DELAY
RET
Solution:

T = 2 ( 250 × 256 × 1.085 us ) = 138.88ms, and frequency = 72 Hz


---------------------------------------------------------------------------------------------------------
Example 4.3.10: Assuming that we are programming the timers for mode 2, find the
value (in hex) loaded into TH for each of the following cases.
(a) MOV TH1,#-200 (b) MOV TH0,#-60
(c) MOV TH1,#-3 (d) MOV TH1,#-12
(e) MOV TH0,#-48

Solution:
You can use the Windows scientific calculator to verify the result provided by the
assembler. In Windows calculator, select decimal and enter 200. Then select hex, then +/-
to get the TH value. Remember that we only use the right two digits and ignore the rest
since our data is an 8-bit data.

Harish G C, Assistant Professor, Department of E&CE 53


8051 Microcontroller

Decimal 2’s complement (TH value)


-3 FDH
-12 F4H
-48 D0H
-60 C4H
-200 38H

Note: The number 200 is the timer count till the TF is set to 1
The advantage of using negative values is that you don’t need to calculate the value
loaded to THx
------------------------------------------------------------------------------------------------------------
4.3.3 PROGRAMMING TIMERS IN C:

Example 4.3.11: Write an 8051 C program to toggle all the bits of port P1 continuously
with 50ms delay. Use Timer 0, 16-bit mode to generate the delay.

Solution:

Time delay, Td = [FFFF – THTL + 1] * 1.085μs = 50ms


Therefore, TH0TL0 = 4BFD

#include <reg51.h>
void T0Delay(void);
void main(void)
{
while (1)
{
P1=~P1;
T0Delay();
}
}

void T0Delay(void)
{
TMOD=0x01;
TL0=0xfd;
TH0=0x4b;
TR0=1;
while (TF0==0);
TR0=0;
TF0=0;
}
------------------------------------------------------------------------------------------------------------

Example 4.3.12: Write an 8051 C program to toggle all bits of P2 continuously every
500ms. Use Timer 1, mode 1 to create the delay.

Harish G C, Assistant Professor, Department of E&CE 54


8051 Microcontroller

Solution:

Using timer in mode 1 we can able to generate largest delay of 71.16ms.

Hence we are generating a time delay of 25ms and repeating the same for 20 times.

Time delay, Td = [FFFF – THTL + 1] * 1.085μs = 25ms


THTL = A5FE

Total required delay = 25ms * 20

//tested for DS89C420, XTAL = 11.0592 MHz

#include <reg51.h>
void T1M1Delay(void);
void main(void)
{
unsigned char x;
P2=0x55;
while (1)
{
P2=~P2;
for (x=0;x<20;x++)
T1M1Delay();
}
}

void T1M1Delay(void)
{
TMOD=0x10;
TL1=0xFE;
TH1=0xA5;
TR1=1;
while (TF1==0);
TR1=0;
TF1=0;
}
------------------------------------------------------------------------------------------------------------

Example 4.3.13: A switch is connected to pin P1.2. Write an 8051 C program to monitor
SW and create the following frequencies on pin P1.7: SW=0: 500Hz, SW=1: 750Hz, use
Timer 0, mode 1 for both of them.

Solution:

Harish G C, Assistant Professor, Department of E&CE 55


8051 Microcontroller

For, 500Hz when SW=0


Cycle period = 1/500Hz = 2ms
Half cycle period = 2ms/2 = 1ms
Time delay, Td = [FFFF – THTL + 1] * 1.085μs = 1ms
Therefore, TH0TL0 = FC67

For, 750Hz when SW=1


Cycle period = 1/750Hz = 1.33ms
Half cycle period = 1.33ms/2 = 0.66ms
Time delay, Td = [FFFF – THTL + 1] * 1.085μs = 0.66ms
Therefore, TH0TL0 = FD9A

#include <reg51.h>
sbit mybit=P1^5;
sbit SW=P1^7;
void T0M1Delay(unsigned char);
void main(void)
{
SW=1;
while (1)
{
mybit=~mybit;
if (SW==0)
T0M1Delay(0);
else
T0M1Delay(1);
}
}

void T0M1Delay(unsigned char c)


{
TMOD=0x01;
if (c==0)
{
TL0=0x67;
TH0=0xFC;
}
else
{
TL0=0x9A;
TH0=0xFD;
}
TR0=1;
while (TF0==0);
TR0=0;
TF0=0;
}
-----------------------------------------------------------------------------------------------------------
Harish G C, Assistant Professor, Department of E&CE 56
8051 Microcontroller

Example 4.3.14: Write an 8051 C program to create a frequency of 2500 Hz on pin P2.7.
Use Timer 1, mode 2 to create delay.

Solution:

For, 2500Hz
Cycle period = 1/2500Hz = 400 μs
Half cycle period = 400 μs /2 = 200 μs
Time delay, Td = [FF – TH + 1] * 1.085μs = 200 μs
Therefore, TH0TL0 = 48h = -184d
Or

200 μs / 1.085 μs = 184; No need to calculate TH value to be loaded.


#include <reg51.h>
void T1M2Delay(void);
sbit mybit=P2^7;
void main(void)
{ unsigned char x;
while (1)
{
mybit=~mybit;
T1M2Delay();
}
}
void T1M2Delay(void)
{
TMOD=0x20;
TH1=-184;
TR1=1;
while (TF1==0);
TR1=0;
TF1=0;
}
-----------------------------------------------------------------------------------------------------------
4.4 COUNTER PROGRAMMING:

Timers can also be used as counters counting events happening outside the 8051

✓ When it is used as a counter, it is a pulse outside the 8051 that increments the
TH, TL registers
✓ TMOD and TH, TL registers are the same as for the timer discussed previously
✓ Programming the timer in the last section also applies to programming it as a
counter, except the source of the frequency
✓ The C/T bit in the TMOD registers decides the source of the clock for the timer
✓ When C/T = 1, the timer is used as a counter and gets its pulses from outside the

Harish G C, Assistant Professor, Department of E&CE 57


8051 Microcontroller

8051.The counter counts up as pulses are fed from pins 14 and 15, these pins are
called T0 (timer 0 input) and T1 (timer 1 input)

Port 3 pins used for Timers 0 and 1

If GATE = 1, the start and stop of the timer are done externally through pins P3.2 and
P3.3 for timers 0 and 1, respectively. This hardware way allows start or stop the timer
externally at any time via a simple switch

THTL

------------------------------------------------------------------------------------------------------------

Example 4.4.1: Assuming that clock pulses are fed into pin T1, write a program for
counter 1 in mode 2 to count the pulses and display the state of the TL1 count on P2,
which connects to 8 LEDs.

Harish G C, Assistant Professor, Department of E&CE 58


8051 Microcontroller

Solution:
MOV TM0D,#01100000B ;counter 1, mode 2, C/T=1 external pulses
MOV TH1,#0 ;clear TH1
SETB P3.5 ;make T1 input
AGAIN: SETB TR1 ;start the counter
BACK: MOV A,TL1 ;get copy of TL
MOV P2,A ;display it on port 2
JNB TF1,Back ;keep doing, if TF = 0
CLR TR1 ;stop the counter 1
CLR TF1 ;make TF=0
SJMP AGAIN ;keep doing it
Notice in the above program the role of the instruction SETB P3.5. Since ports are set up
for output when the 8051 is powered up, we make P3.5 an input port by making it high.
In other words, we must configure (set high) the T1 pin (pin P3.5) to allow pulses to be
fed into it.
------------------------------------------------------------------------------------------------------------
4.4.1 C PROGRAMMING OF TIMERS AS COUNTERS:

Example 4.4.2: Assume that a 1-Hz external clock is being fed into pin T1 (P3.5). Write
a C program for counter 1 in mode 2 (8-bit auto reload) to count up and display the state
of the TL1 count on P1. Start the count at 0H.

Solution:
#include <reg51.h>
sbit T1=P3^5;
void main(void)
{
T1=1; Make P3^5 to act as an input port
TMOD=0x60;
TH1=0;
while (1)
{
do
{
TR1=1;
P1=TL1;
}
while (TF1==0);
TR1=0;
TF1=0;
}
}
-----------------------------------------------------------------------------------------------------------

Harish G C, Assistant Professor, Department of E&CE 59


8051 Microcontroller

Example 4.4.3: Assume that a 1-Hz external clock is being fed into pin T0 (P3.4). Write
a C program for counter 0 in mode 1 (16-bit) to count the pulses and display the state of
the TH0 and TL0 registers on P2 and P1, respectively.

Solution:

#include <reg51.h>
void main(void)
{
T0=1;
TMOD=0x05;
TL0=0
TH0=0;
while (1)
{
do
{
TR0=1;
P1=TL0;
P2=TH0;
}
while (TF0==0);
TR0=0;
TF0=0;
}
}

5.1 BASICS OF SERIAL COMMUNICATION

Computers transfer data in two ways:

✓ Parallel
• Often 8 or more lines (wire conductors) are used to transfer data to a device
that is only a few feet away
✓ Serial
• To transfer to a device located many meters away, the serial method is used
• The data is sent one bit at a time

Harish G C, Assistant Professor, Department of E&CE 60


8051 Microcontroller

✓ At the transmitting end, the byte of data must be converted to serial bits using
parallel-in-serial-out shift register
✓ At the receiving end, there is a serial-in- parallel-out shift register to receive the
serial data and pack them into byte
✓ When the distance is short, the digital signal can be transferred as it is on a simple
wire and requires no modulation
✓ If data is to be transferred on the telephone line, it must be converted from 0s and
1s to audio tones. This conversion is performed by a device called a modem,
“Modulator/demodulator”

Serial data communication uses two methods,

✓ Synchronous method transfers a block of data at a time


✓ Asynchronous method transfers a single byte at a time

It is possible to write software to use either of these methods, but the programs can be
tedious and long. There are special IC chips made by many manufacturers for serial
communications

✓ UART (universal asynchronous Receiver-transmitter)


✓ USART (universal synchronous-asynchronous Receiver-transmitter)

5.1.1 HALF- AND FULL-DUPLEX TRANSMISSION:

If data can be transmitted and received, it is a duplex transmission

✓ If data transmitted one way a time, it is referred to as half duplex


✓ If data can go both ways at a time, it is full duplex. Full duplex requires two wire
conductors for data lines, one for transmission and one for reception, in order to
transfer and receive data simultaneously.

This is contrast to simplex transmission, such as printers, in which the computer only
sends data.

------------------------------------------------------------------------------------------------------------
5.1.2 START AND STOP BITS:

A protocol is a set of rules agreed by both the sender and receiver on

Harish G C, Assistant Professor, Department of E&CE 61


8051 Microcontroller

✓ How the data is packed


✓ How many bits constitute a character
✓ When the data begins and ends

Asynchronous serial data communication is widely used for character-oriented


transmissions, while block oriented data transfer use the synchronous method.

✓ Each character is placed in between start and stop bits, this is called framing
✓ The start bit is always one bit, but the stop bit can be one or two bits
✓ The start bit is always a 0 (low) and the stop bit(s) is 1 (high)

✓ Due to the extended ASCII characters, 8-bit ASCII data is common. In older
systems, ASCII characters were 7-bit.
✓ Assuming that we are transferring a text file of ASCII characters using 1 stop bit,
we have a total of 10 bits for each character
• This gives 25% overhead, i.e. each 8-bit character with an extra 2 bits
✓ In some systems in order to maintain data integrity, the parity bit of the character
byte is included in the data frame
• UART chips allow programming of the parity bit for odd-, even-, and no-parity
options
------------------------------------------------------------------------------------------------------------
5.1.3 DATA TRANSFER RATE:

✓ The rate of data transfer in serial data communication is stated in bps (bits per
second).
✓ Another widely used terminology for bps is baud rate
• It is modem terminology and is defined as the number of signal changes
per second
• In modems, there are occasions when a single change of signal transfers
several bits of data
✓ As far as the conductor wire is concerned, the baud rate and bps are the

Harish G C, Assistant Professor, Department of E&CE 62


8051 Microcontroller

same, and we use the terms interchangeably


✓ The data transfer rate of given computer system depends on communication ports
incorporated into that system
• IBM PC/XT could transfer data at the rate of 100 to 9600 bps
• Pentium-based PCs transfer data at rates as high as 56K bps
• In asynchronous serial data communication, the baud rate is limited to 100K
bps
------------------------------------------------------------------------------------------------------------
5.1.4 RS232 STANDARDS:

✓ An interfacing standard RS232 was set by the Electronics Industries Association


(EIA) in 1960
✓ The standard was set long before the advent of the TTL logic family, its input and
output voltage levels are not TTL compatible
• In RS232, a 1 is represented by -3 ~ -25 V, while a 0 bit is +3 ~ +25 V, making
-3 to +3 undefined

RS232 DB-25 Pins:

Since not all pins are used in PC cables (i.e. DB-25), IBM introduced the DB-9 version of
the serial I/O standard.

------------------------------------------------------------------------------------------------------------
5.1.5 DATA COMMUNICATION CLASSIFICATION:

Current terminology classifies data communication equipment as

✓ DTE (data terminal equipment) refers to terminal and computers that send and
receive data
✓ DCE (data communication equipment) refers to communication equipment, such
as modems
✓ The simplest connection between a PC and microcontroller requires a minimum of
three pins, TxD, RxD, and ground

Harish G C, Assistant Professor, Department of E&CE 63


8051 Microcontroller

DTR (data terminal ready) : When terminal is turned on, it sends out signal DTR to
indicate that it is ready for communication
DSR (data set ready) : When DCE is turned on and has gone through the self-test,
it assert DSR to indicate that it is ready to communicate
RTS (request to send) : When the DTE device has byte to transmit, it assert RTS
to signal the modem that it has a byte of data to transmit
CTS (clear to send) : When the modem has room for storing the data it is to
receive, it sends out signal CTS to DTE to indicate that it
can receive the data now
DCD (data carrier detect) : The modem asserts signal DCD to inform the DTE that a
valid carrier has been detected and that contact between it
and the other modem is established
RI (ring indicator) : An output from the modem and an input to a PC indicates
that the telephone is ringing. It goes on and off in
synchronous with the ringing sound.
5.2 8051 CONNECTION TO RS232:

The 8051 has two pins that are used specifically for transferring and receiving data
serially.

✓ These two pins are called TxD and RxD and are part of the port 3 group (P3.0 and
P3.1)
✓ These pins are TTL compatible; therefore, they require a line driver(MAX232) to
make them RS232 compatible
✓ One advantage of the MAX232 chip is that it uses a +5V power source which, is
the same as the source voltage for the 8051.
✓ The MAX232 has two set of line drivers for transferring and receiving data, as
shown in figure.
✓ MAX2323 requires four capacitors ranging from 1uF to 22uF. The most widely
used value of these capacitors is 22uF.

Harish G C, Assistant Professor, Department of E&CE 64


8051 Microcontroller

To save board space, some designers use MAX233 chip from Maxim

✓ MAX233 performs the same job as MAX232 but eliminates the need for
capacitors
✓ Notice that MAX233 and MAX232 are not pin compatible

5.3 SERIAL COMMUNICATION PROGRAMMING:

To allow data transfer between the PC and an 8051 system without any error, we must
make sure that the baud rate of 8051 system matches the baud rate of the PC’s COM port.
Hyper-terminal function supports baud rates much higher than listed below.

PC Baud Rates:

Baud rates supported by


486/Pentium IBM PC BIOS

Harish G C, Assistant Professor, Department of E&CE 65


8051 Microcontroller

------------------------------------------------------------------------------------------------------------
Example 5.3.1: With XTAL = 11.0592 MHz, find the TH1 value needed to have the
following baud rates. (a) 9600 (b) 2400 (c) 1200

Solution:
The machine cycle frequency of 8051 = 11.0592 / 12 = 921.6 kHz, and 921.6 kHz / 32 =
28,800 Hz is frequency by UART to timer 1 to set baud rate.
(a) 28,800 / 3 = 9600 where -3 = FD (hex) is loaded into TH1
(b) 28,800 / 12 = 2400 where -12 = F4 (hex) is loaded into TH1
(c) 28,800 / 24 = 1200 where -24 = E8 (hex) is loaded into TH1

Notice that dividing 1/12 of the crystal frequency by 32 is the default value upon
activation of the 8051 RESET pin.

------------------------------------------------------------------------------------------------------------
5.3.1 SBUF REGISTER:

SBUF is an 8-bit register used solely for serial communication

✓ For a byte data to be transferred via the TxD line, it must be placed in the SBUF
register. The moment a byte is written into SBUF, it is framed with the start and
stop bits and transferred serially via the TxD line
✓ SBUF holds the byte of data when it is received by 8051 RxD line. When the bits
are received serially via RxD, the 8051 deframes it by eliminating the stop and
start bits, making a byte out of the data received, and then placing it in SBUF

MOV SBUF,#’D’ ;load SBUF=44h, ASCII for ‘D’


MOV SBUF,A ;copy accumulator into SBUF
MOV A,SBUF ;copy SBUF into accumulator
--------------------------------------------------------------------------------------------------------------------
5.3.2 SCON REGISTER:

SCON is an 8-bit register used to program the start bit, stop bit, and data bits of data
framing, among other things.

Harish G C, Assistant Professor, Department of E&CE 66


8051 Microcontroller

SM0 SCON.7 Serial port mode specifier


SM1 SCON.6 Serial port mode specifier
SM2 SCON.5 Used for multiprocessor communication
REN SCON.4 Set/cleared by software to enable/disable reception
TB8 SCON.3 Not widely used
RB8 SCON.2 Not widely used
TI SCON.1 Transmit interrupt flag. Set by hardware at the begin of the
stop bit Mode 1. Must be cleared by software
RI SCON.0 Receive interrupt flag. Set by HW at the begin of the stop
bit mode 1. Must be cleared by SW

Note: Make SM2, TB8, and RB8 =0

SM0, SM1: They determine the framing of data by specifying the number of bits Per
character, and the start and stop bits

SM2: This enables the multiprocessing capability of the 8051


REN (receive enable) : It is a bit-addressable register. When it is high, it allows 8051 to
receive data on RxD pin. If low, the receiver is disabled.
TI (transmit interrupt): When 8051 finishes the transfer of 8-bit character. It raises TI
flag to indicate that it is ready to transfer another byte. TI bit is raised at the beginning of
the stop bit
RI (receive interrupt) : When 8051 receives data serially via RxD, it gets rid of the start
and stop bits and places the byte in SBUF register. It raises the RI flag bit to indicate that
a byte has been received and should be picked up before it is lost. RI is raised halfway
through the stop bit.
------------------------------------------------------------------------------------------------------------
5.3.3 PROGRAMMING SERIAL DATA TRANSMITTING:

In programming the 8051 to transfer character bytes serially the following steps must
be taken.

1. TMOD register is loaded with the value 20H, indicating the use of timer 1 in mode 2
(8-bit auto- reload) to set baud rate
2. The TH1 is loaded with one of the values to set baud rate for serial data transfer
3. The SCON register is loaded with the value 50H, indicating serial mode 1, where an 8-
bit data is framed with start and stop bits
4. TR1 is set to 1 to start timer 1

Harish G C, Assistant Professor, Department of E&CE 67


8051 Microcontroller

5. TI is cleared by CLR TI instruction


6. The character byte to be transferred serially is written into SBUF register
7. The TI flag bit is monitored with the use of instruction JNB TI, xx to see if the
character has been transferred completely
8. To transfer the next byte, go to step 5
------------------------------------------------------------------------------------------------------------
Example 5.3.2: Write a program for the 8051 to transfer letter “A” serially at 4800 baud,
continuously.
Solution:

MOV TMOD,#20H ;timer 1,mode 2(auto reload)


MOV TH1,#-6 ;4800 baud rate
MOV SCON,#50H ;8-bit, 1 stop, REN enabled
SETB TR1 ;start timer 1
AGAIN: MOV SBUF,#”A” ;letter “A” to transfer
HERE: JNB TI,HERE ;wait for the last bit
CLR TI ;clear TI for next char
SJMP AGAIN ;keep sending A
-----------------------------------------------------------------------------------------------------------
Example 5.3.3: Write a program for the 8051 to transfer “YES” serially at 9600 baud, 8-
bit data, 1 stop bit, do this continuously

Solution:

MOV TMOD,#20H ;timer 1,mode 2(auto reload)


MOV TH1,#-3 ;9600 baud rate
MOV SCON,#50H ;8-bit, 1 stop, REN enabled
SETB TR1 ;start timer 1
AGAIN: MOV A,#”Y” ;transfer “Y”
ACALL TRANS
MOV A,#”E” ;transfer “E”
ACALL TRANS
MOV A,#”S” ;transfer “S”
ACALL TRANS
SJMP AGAIN ;keep doing it

;serial data transfer subroutine

TRANS: MOV SBUF,A ;load SBUF


HERE: JNB TI,HERE ;wait for the last bit
CLR TI ;get ready for next byte
RET
------------------------------------------------------------------------------------------------------------

Harish G C, Assistant Professor, Department of E&CE 68


8051 Microcontroller

Importance of TI Flag:

The steps that 8051 goes through in transmitting a character via TxD

1. The byte character to be transmitted is written into the SBUF register


2. The start bit is transferred
3. The 8-bit character is transferred on bit at a time
4. The stop bit is transferred. It is during the transfer of the stop bit that 8051 raises the TI
flag, indicating that the last character was transmitted
5. By monitoring the TI flag, we make sure that we are not overloading the SBUF. If we
write another byte into the SBUF before TI is raised, the untransmitted portion of the
previous byte will be lost
6. After SBUF is loaded with a new byte, the TI flag bit must be forced to 0 by CLR TI in
order for this new byte to be transferred

The TI bit can be checked by

✓ The instruction JNB TI, xx or


✓ Using an interrupt
-----------------------------------------------------------------------------------------------------------
5.3.4 PROGRAMMING SERIAL DATA RECEIVING:

In programming the 8051 to receive character bytes serially, the following steps must be
taken

1. TMOD register is loaded with the value 20H, indicating the use of timer 1 in mode 2
(8-bit auto-reload) to set baud rate
2. TH1 is loaded to set baud rate
3. The SCON register is loaded with the value 50H, indicating serial mode 1, where an 8-
bit data is framed with start and stop bits
4. TR1 is set to 1 to start timer 1
5. RI is cleared by CLR RI instruction
6. The RI flag bit is monitored with the use of instruction JNB RI,xx to see if an entire
character has been received yet
7. When RI is raised, SBUF has the byte; its contents are moved into a safe place
8. To receive the next character, go to step 5
------------------------------------------------------------------------------------------------------------
Example 5.3.4: Write a program for the 8051 to receive bytes of data serially, and put
them in P1, set the baud rate at 4800, 8-bit data, and 1 stop bit

Solution:

MOV TMOD,#20H ;timer 1,mode 2(auto reload)


MOV TH1,#-6 ;4800 baud rate

Harish G C, Assistant Professor, Department of E&CE 69


8051 Microcontroller

MOV SCON,#50H ;8-bit, 1 stop, REN enabled


SETB TR1 ;start timer 1
HERE: JNB RI,HERE ;wait for char to come in
MOV A,SBUF ;saving incoming byte in A
MOV P1,A ;send to port 1
CLR RI ;get ready to receive next byte
SJMP HERE ;keep getting data
------------------------------------------------------------------------------------------------------------
Example 5.3.5: Assume that the 8051 serial port is connected to the COM port of IBM
PC, and on the PC, we are using the terminal.exe program to send and receive data
serially. P1 and P2 of the 8051 are connected to LEDs and switches, respectively. Write
an 8051 program to (a) send to PC the message “We Are Ready”, (b) receive any data
send by PC and put it on LEDs connected to P1, and (c) get data on switches connected to
P2 and send it to PC serially. The program should perform part (a) once, but parts (b) and
(c) continuously, use 4800 baud rate.

Solution:

ORG 0
MOV P2,#0FFH ;make P2 an input port
MOV TMOD,#20H ;timer 1, mode 2
MOV TH1,#0FAH ;4800 baud rate
MOV SCON,#50H ;8-bit, 1 stop, REN enabled
SETB TR1 ;start timer 1
MOV DPTR,#MYDATA ;load pointer for message
H_1: CLR A
MOV A,@A+DPTR ;get the character
JZ B_1 ;if last character get out
ACALL SEND ;otherwise call transfer
INC DPTR ;next one
SJMP H_1 ;stay in loop
B_1: MOV a,P2 ;read data on P2
ACALL SEND ;transfer it serially
ACALL RECV ;get the serial data
MOV P1,A ;display it on LEDs
SJMP B_1 ;stay in loop indefinitely

;----serial data transfer. ACC has the data------

SEND: MOV SBUF,A ;load the data


H_2: JNB TI,H_2 ;stay here until last bit gone
CLR TI ;get ready for next char
RET ;return to caller

Harish G C, Assistant Professor, Department of E&CE 70


8051 Microcontroller

;----Receive data serially in ACC----------------

RECV: JNB RI,RECV ;wait here for char


MOV A,SBUF ;save it in ACC
CLR RI ;get ready for next char
RET ;return to caller

;-----The message---------------

MYDATA: DB “We Are Ready”,0


END

------------------------------------------------------------------------------------------------------------
Importance of RI Flag:

In receiving bit via its RxD pin, 8051 goes through the following steps.

1. It receives the start bit. Indicating that the next bit is the first bit of the character byte it
is about to receive
2. The 8-bit character is received one bit at a time
3. The stop bit is received. When receiving the stop bit 8051 makes RI = 1, indicating that
an entire character byte has been received and must be picked up before it gets
overwritten by an incoming character
4. By checking the RI flag bit when it is raised, we know that a character has been
received and is sitting in the SBUF register. We copy the SBUF contents to a safe
place in some other register or memory before it is lost
5. After the SBUF contents are copied into a safe place, the RI flag bit must be forced to 0
by CLR RI in order to allow the next received character byte to be placed in SBUF.
Failure to do this causes loss of the received character

The RI bit can be checked by

✓ The instruction JNB RI,xx or


✓ Using an interrupt
------------------------------------------------------------------------------------------------------------
5.3.5 DOUBLING BAUD RATE:

There are two ways to increase the baud rate of data transfer

Harish G C, Assistant Professor, Department of E&CE 71


8051 Microcontroller

✓ To use a higher frequency crystal


✓ To change a bit in the PCON register

PCON register is an 8-bit register. When 8051 is powered up, SMOD is zero. We can set
it to high by software and thereby double the baud rate.

MOV A,PCON ;place a copy of PCON in ACC


SETB ACC.7 ;make D7=1
MOV PCON,A ;changing any other bits

Note: It is not a bit addressable register

Baud Rate comparison for SMOD=0 and SMOD=1

------------------------------------------------------------------------------------------------------------

Example 5.3.6: Assume that XTAL = 11.0592 MHz for the following program, state (a)
what this program does, (b) compute the frequency used by timer 1 to set the baud rate,
and (c) find the baud rate of the data transfer.

MOV A,PCON ;A=PCON


MOV ACC.7 ;make D7=1
MOV PCON,A ;SMOD=1, double baud rate with same XTAL
freq.
MOV TMOD,#20H ;timer 1, mode 2
MOV TH1,-3 ;19200 (57600/3 =19200)
MOV SCON,#50H ;8-bit data, 1 stop bit, RI enabled
SETB TR1 ;start timer 1
MOV A,#”B” ;transfer letter B
A_1: CLR TI ;make sure TI=0
MOV SBUF,A ;transfer it

Harish G C, Assistant Professor, Department of E&CE 72


8051 Microcontroller

H_1: JNB TI,H_1 ;stay here until the last bit is gone
SJMP A_1 ;keep sending “B” again

Solution:
(a) This program transfers ASCII letter B (01000010 binary) continuously

(b) With XTAL = 11.0592 MHz and SMOD = 1 in the above program, we have:

11.0592 / 12 = 921.6 kHz machine cycle frequency.


921.6 / 16 = 57,600 Hz frequency used by timer 1 to set the baud rate.

(c) 57600 / 3 = 19,200, the baud rate.


------------------------------------------------------------------------------------------------------------
Example 5.3.7: Find the TH1 value (in both decimal and hex) to set the baud rate to each
of the following. (a) 9600 (b) 4800 if SMOD=1. Assume that XTAL 11.0592 MHz

Solution:
With XTAL = 11.0592 and SMOD = 1, we have timer frequency = 57,600 Hz.
(a) 57600 / 9600 = 6; so TH1 = -6 or TH1 = FAH
(b) 57600 / 4800 = 12; so TH1 = -12 or TH1 = F4H
------------------------------------------------------------------------------------------------------------
Example 5.3.8: Find the baud rate if TH1 = -2, SMOD = 1, and XTAL = 11.0592 MHz.
Is this baud rate supported by IBM compatible PCs?

Solution:
With XTAL = 11.0592 and SMOD = 1, we have timer frequency = 57,600 Hz. The baud
rate is 57,600/2 = 28,800. This baud rate is not supported by the BIOS of the PCs;
however, the PC can be programmed to do data transfer at such a speed. Also,
HyperTerminal in Windows supports this and other baud rates.
Example 5.3.9: Write a program to send the message “The Earth is but One Country” to
serial port. Assume a SW is connected to pin P1.2. Monitor its status and set the baud rate
as follows:
SW = 0, 4800 baud rate
SW = 1, 9600 baud rate
Assume XTAL = 11.0592 MHz, 8-bit data, and 1 stop bit.

Solution:

SW BIT P1.2
ORG 0H ;starting position
MAIN: MOV TMOD,#20H
MOV TH1,#-6 ;4800 baud rate (default)
MOV SCON,#50H
SETB TR1

Harish G C, Assistant Professor, Department of E&CE 73


8051 Microcontroller

SETB SW ;make SW an input


S1: JNB SW,SLOWSP ;check SW status
MOV A,PCON ;read PCON
SETB ACC.7 ;set SMOD high for 9600
MOV PCON,A ;write PCON
SJMP OVER ;send message
SLOWSP: MOV A,PCON ;read PCON
SETB ACC.7 ;set SMOD low for 4800
MOV PCON,A ;write PCON
OVER: MOV DPTR,#MESS1 ;load address to message
FN: CLR A
MOVC A,@A+DPTR ;read value
JZ S1 ;check for end of line
ACALL SENDCOM ;send value to serial port
INC DPTR ;move to next value
SJMP FN ; repeat

;------------

SENDCOM: MOV SBUF,A ;place value in buffer


HERE: JNB TI,HERE ;wait until transmitted
CLR TI ;clear
RET ;return

;------------

MESS1: DB “The Earth is but One Country”, 0


END
------------------------------------------------------------------------------------------------------------
5.4: SERIAL PORT PROGRAMMING IN C

Example 5.4.1: Write a C program for 8051 to transfer the letter “A” serially at 4800
baud continuously. Use 8-bit data and 1 stop bit.
Solution:
#include <reg51.h>
void main(void)
{
TMOD=0x20; //use Timer 1, mode 2
TH1=0xFA; //4800 baud rate
SCON=0x50;
TR1=1;
while (1)
{

Harish G C, Assistant Professor, Department of E&CE 74


8051 Microcontroller

SBUF=‘A’; //place value in buffer


while (TI==0);
TI=0;
}}
------------------------------------------------------------------------------------------------------------
Example 5.4.2: Write an 8051 C program to transfer the message “YES” serially at 9600
baud, 8-bit data, 1 stop bit. Do this continuously.
Solution:
#include <reg51.h>
void SerTx(unsigned char);
void main(void)
{
TMOD=0x20; //use Timer 1, mode 2
TH1=0xFD; //9600 baud rate
SCON=0x50;
TR1=1; //start timer
while (1)
{
SerTx(‘Y’);
SerTx(‘E’);
SerTx(‘S’);
}
}
void SerTx(unsigned char x)
{
SBUF=x; //place value in buffer
while (TI==0); //wait until transmitted
TI=0;
}
Example 5.4.3: Program the 8051 in C to receive bytes of data serially and put them in
P1. Set the baud rate at 4800, 8-bit data, and 1 stop bit.

Solution:

#include <reg51.h>
void main(void)
{
unsigned char mybyte;
TMOD=0x20; //use Timer 1, mode 2
TH1=0xFA; //4800 baud rate
SCON=0x50;
TR1=1; //start timer
while (1) //repeat forever
{

Harish G C, Assistant Professor, Department of E&CE 75


8051 Microcontroller

while (RI==0); //wait to receive


mybyte=SBUF; //save value
P1=mybyte; //write value to port
RI=0;
}
}
------------------------------------------------------------------------------------------------------------
Example 5.4.4: Write an 8051 C Program to send the two messages “Normal Speed” and
“High Speed” to the serial port. Assuming that SW is connected to pin P2.0, monitor its
status and set the baud rate as follows:
SW = 0, 28,800 baud rate
SW = 1, 56K baud rate
Assume that XTAL = 11.0592 MHz for both cases.

Solution:

#include <reg51.h>
sbit MYSW=P2^0; //input switch
void main(void)
{
unsigned char z;
unsigned char Mess1[]=“Normal Speed”;
unsigned char Mess2[]=“High Speed”;
TMOD=0x20; //use Timer 1, mode 2
TH1=0xFF; //28800 for normal
SCON=0x50;
TR1=1; //start timer

if(MYSW==0)
{
for (z=0;z<12;z++)
{
SBUF=Mess1[z]; //place value in buffer
while(TI==0); //wait for transmit
TI=0;
}
}
else
{
PCON=PCON|0x80; //for high speed of 56K
for (z=0;z<10;z++)
{

Harish G C, Assistant Professor, Department of E&CE 76


8051 Microcontroller

SBUF=Mess2[z]; //place value in buffer


while(TI==0); //wait for transmit
TI=0;
}
}
}

Harish G C, Assistant Professor, Department of E&CE 77


8051 Microcontroller

4. 8051 INTERRUPTS AND INTERFACING


APPLICATIONS

4.1 INTERRUPTS

An interrupt is an external or internal event that interrupts the microcontroller to inform it


that a device needs its service. A single microcontroller can serve several devices by two
ways i.e. Interrupts and polling methods.

4.1.1 INTERRUPTS AND POLLING

Polling:

✓ The microcontroller continuously monitors the status of a given device


✓ When the conditions met, it performs the service
✓ After that, it moves on to monitor the next device until everyone is serviced

Note: The polling method is not efficient, since it wastes much of the microcontroller’s
time by polling devices that do not need service

ex. JNB TF,target

Interrupts:

✓ Whenever any device needs its service, the device notifies the microcontroller by
sending it an interrupt signal
✓ Upon receiving an interrupt signal, the microcontroller interrupts whatever it is
doing
and serves the device
✓ The program which is associated with the interrupt is called the interrupt service
routine (ISR) or interrupt handler

The advantage of interrupts is that the microcontroller can serve many devices (not all at
the same time)

✓ Each devices can get the attention of the microcontroller based on the assigned
priority
✓ For the polling method, it is not possible to assign priority since it checks all
devices in a round-robin fashion
✓ The microcontroller can also ignore (mask) a device request for service which is
not possible for the polling method.

Harish G C, Assistant Professor, Department of E&CE 78


8051 Microcontroller

4.1.2 INTERRUPT SERVICE ROUTINE:

For every interrupt, there must be an interrupt service routine (ISR), or interrupt handler

✓ When an interrupt is invoked, the microcontroller runs the interrupt service


routine
✓ For every interrupt, there is a fixed location in memory that holds the address of
its ISR
✓ The group of memory locations set aside to hold the addresses of ISRs is called
interrupt vector table

4.1.3 STEPS IN EXECUTING AN INTERRUPT:

Upon activation of an interrupt, the microcontroller goes through the following steps

1. It finishes the instruction it is executing and saves the address of the next instruction
(PC) on the stack
2. It also saves the current status of all the interrupts internally (i.e.: not on the stack)
3. It jumps to a fixed location in memory, called the interrupt vector table, that holds the
address of the ISR
4. The microcontroller gets the address of the ISR from the interrupt vector table and
jumps to it. It starts to execute the interrupt service subroutine until it reaches the last
instruction of the subroutine which is RETI (return from interrupt)
5. Upon executing the RETI instruction, the microcontroller returns to the place where it
was interrupted. First, it gets the program counter (PC) address from the stack by
popping the top two bytes of the stack into the PC. Then it starts to execute from that
address.

4.1.4 SIX INTERRUPTS IN 8051:

Six interrupts are allocated as follows

✓ Reset – power-up reset


✓ Two interrupts are set aside for the timers: one for timer 0 and one for timer 1
✓ Two interrupts are set aside for hardware external interrupts
✓ P3.2 and P3.3 are for the external hardware interrupts INT0 (or EX1), and INT1
(or EX2)
✓ Serial communication has a single interrupt that belongs to both receive and
transfer

Interrupt Flag Vector address


-----------------------------------------------------------------------------------
System RESET RST 0000h
External interrupt 0 IE0 0003h
Harish G C, Assistant Professor, Department of E&CE 79
8051 Microcontroller

Timer/counter 0 TF0 000Bh


External interrupt 1 IE1 0013h
Timer/counter 1 TF1 001Bh
Serial port RI or TI 0023h
ORG 0 ; wake-up ROM reset location
LJMP MAIN ; by-pass int. vector table

; ---- the wake-up program

ORG 30H
MAIN:
....
END

Note: Only three bytes of ROM space assigned to the reset pin. We put the LJMP as the
first instruction and redirect the processor away from the interrupt vector table.

4.2 ENABLING AND DISABLING AN INTERRUPT


Upon reset, all interrupts are disabled (masked), meaning that none will be responded to
by the microcontroller if they are activated. The interrupts must be enabled by software in
order for the microcontroller to respond to them. There is a register called IE (interrupt
enable) that is responsible for enabling (unmasking) and disabling (masking) the
interrupts.

EA IE.7 Disables all interrupts


-- IE.6 Not implemented, reserved for future use
ET2 IE.5 Enables or disables timer 2 overflow interrupt (8952)
ES IE.4 Enables or disables the serial port interrup1
ET1 IE.3 Enables or disables timer 1 overflow interrupt
EX1 IE.2 Enables or disables external interrupt 1
EX1 IE.2 Enables or disables external interrupt 1
EX0 IE.0 Enables or disables external interrupt 0

Fig 4.2.1: Interrupt Enable register

To enable an interrupt, we take the following steps:

1. Bit D7 of the IE register (EA) must be set to high to allow the rest of register to take

Harish G C, Assistant Professor, Department of E&CE 80


8051 Microcontroller

effect
2. The value of EA
✓ If EA = 1, interrupts are enabled and will be responded to if their corresponding
bits in IE are high
✓ If EA = 0, no interrupt will be responded to, even if the associated bit in the IE
register is high

Example 4.2.1: Show the instructions to (a) enable the serial interrupt, timer 0 interrupt,
and external hardware interrupt 1 (EX1),and (b) disable (mask) the timer 0
interrupt, then (c) show how to disable all the interrupts with a single instruction.

Solution:

(a) MOV IE,#10010110B ;enable serial, timer 0, EX1

Another way to perform the same manipulation is

SETB IE.7 ; EA=1, global enable


SETB IE.4 ; enable serial interrupt
SETB IE.1 ; enable Timer 0 interrupt
SETB IE.2 ; enable EX1

(b) CLR IE.1 ; mask (disable) timer 0 interrupt only

(c) CLR IE.7 ; disable all interrupts

4.5 TIMER INTERRUPTS

The timer flag (TF) is raised when the timer rolls over

✓ In polling TF, we have to wait until the TF is raised. The problem with this
method is that the microcontroller is tied down while waiting for TF to be raised,
and cannot do anything else.
✓ Using interrupts solves this problem and, avoids tying down the controller
✓ If the timer interrupt in the IE register is enabled, whenever the timer rolls over,
TF israised, and the microcontroller is interrupted in whatever it is doing, and
jumps to the interrupt vector table to service the ISR. In this way, the
microcontroller can do other tasks until it is notified that the timer has rolled over.

-----------------------------------------------------------------------------------------------------------

Harish G C, Assistant Professor, Department of E&CE 81


8051 Microcontroller

Example 4.5.1: Write a program that continuously get 8-bit data from P0 and sends it to
P1 while simultaneously creating a square wave of 200 μs period on pin P2.1. Use timer 0
to create the square wave. Assume that XTAL = 11.0592 MHz.

Solution:

We will use timer 0 in mode 2 (auto reload). TH0 = 100/1.085 us = 92

;--upon wake-up go to main, avoid using memory allocated to Interrupt Vector Table

ORG 0000H
LJMP MAIN ; by-pass interrupt vector table

;--ISR for timer 0 to generate square wave

ORG 000BH ; Timer 0 interrupt vector table


CPL P2.1 ; toggle P2.1 pin
RETI ; return from ISR

;--The main program for initialization

ORG 0030H ; after vector table space


MAIN: MOV TMOD,#02H ;Timer 0, mode 2
MOV P0,#0FFH ;make P0 an input port
MOV TH0,#-92 ;TH0=A4H for -92
MOV IE,#82H ;IE=10000010 (bin) enable Timer 0
SETB TR0 ; Start Timer 0
BACK: MOV A,P0 ;get data from P0
MOV P1,A ;issue it to P1
SJMP BACK ; keep doing it loop unless interrupted by TF0
END

Example 4.5.2: Write a program to generate a square wave of 50Hz frequency on pin
P1.2. use timer 0, mode 1in interrupt mode to create square wave. Assume that
XTAL=11.0592 MHz

Solution:

ORG 0
LJMP MAIN
ORG 000BH ;ISR for Timer 0
CPL P1.2
MOV TL0,#00
MOV TH0,#0DCH

Harish G C, Assistant Professor, Department of E&CE 82


8051 Microcontroller

RETI
ORG 30H

; --------main program for initialization

MAIN:MOV TM0D,#00000001B ;Timer 0, Mode 1


MOV TL0,#00
MOV TH0,#0DCH
MOV IE,#82H ;enable Timer 0 interrupt
SETB TR0
HERE:SJMP HERE
END
------------------------------------------------------------------------------------------------------------
4.6 EXTERNAL HARDWARE INTERRUPTS

The 8051 has two external hardware interrupts

✓ Pin 12 (P3.2) and pin 13 (P3.3) of the 8051, designated as INT0 and INT1, are
used as external hardware interrupts
✓ The interrupt vector table locations 0003H and 0013H are set aside for INT0 and
INT1
✓ There are two activation levels for the external hardware interrupts
• Level trigged
• Edge trigged

4.6.1 LEVEL TRIGGED INTERRUPT:

In the level-triggered mode, INT0 and INT1 pins are normally high. This is called a
level-triggered or level activated interrupt and is the default mode upon reset of the 8051.

Harish G C, Assistant Professor, Department of E&CE 83


8051 Microcontroller

✓ If a low-level signal is applied to them, it triggers the interrupt, and then the
microcontroller stops whatever it is doing and jumps to the interrupt vector table to
service that interrupt.
✓ The low-level signal at the INT pin must be removed before the execution of the last
instruction of the ISR, RETI; otherwise, another interrupt will be generated
-----------------------------------------------------------------------------------------------------------
Example 4.6.1: Assume that the INT1 pin is connected to a switch that is normally high.
Whenever it goes low, it should turn on an LED. The LED is connected to P1.3 and is
normally off. When it is turned on it should stay on for a fraction of a second. As long as
the switch is pressed low, the LED should stay on.

Solution:

ORG 0000H
LJMP MAIN ;by-pass interrupt

;vector table
;--ISR for INT1 to turn on LED

ORG 0013H ;INT1 ISR


SETB P1.3 ;turn on LED
MOV R3,#255
BACK: DJNZ R3,BACK ;keep LED on for a while
CLR P1.3 ;turn off the LED
RETI ;return from ISR

;--MAIN program for initialization

ORG 30H
MAIN: MOV IE,#10000100B ;enable external INT 1
HERE: SJMP HERE ;stay here until get interrupted
END
------------------------------------------------------------------------------------------------------------
Sampling Low Level-Triggered Interrupt:

The Pins P3.2 and P3.3 are used for normal I/O unless the INT0 and INT1 bits in the IE
register are enabled.

✓ After the hardware interrupts in the IE register are enabled, the controller keeps
sampling the INTn pin for a low-level signal once each machine cycle.
✓ The pin must be held in a low state until the start of the execution of ISR
✓ If the INTn pin is brought back to a logic high before the start of the execution of
ISR there will be no interrupt
✓ If INTn pin is left at a logic low after the RETI instruction of the ISR, another
interrupt will be activated after one instruction is executed

Harish G C, Assistant Professor, Department of E&CE 84


8051 Microcontroller

✓ To ensure the activation of the hardware interrupt at the INTn pin, make sure that
the duration of the low-level signal is around 4 machine cycles, but no more.

• This is due to the fact that the level-triggered interrupt is not latched
• Thus the pin must be held in a low state until the start of the ISR execution

Note: On reset, IT0 (TCON.0) and IT1 (TCON.2) are both low, making external interrupt
level-triggered.
------------------------------------------------------------------------------------------------------------
4.6.2 EDGE-TRIGGERED INTERRUPT:

To make INT0 and INT1 edge triggered interrupts, we must program the bits of the
TCON (i.e. IT0 and IT1) register.

TCON (Timer/Counter) Register (Bit-addressable)

TF1 TCON.7 Timer 1 OV flag. Set by hardware when timer/counter1


overflows. Cleared by hardware as the processor vectors to
the interrupt service routine
TR1 TCON.6 Timer 1 run control bit. Set/cleared by software to turn
timer/counter 1 on/off
TF0 TCON.5 Timer 0 OV flag. Set by hardware when timer/counter 0
overflows. Cleared by hardware as the processor vectors to
the interrupt service routine
TR0 TCON.4 Timer 0 run control bit. Set/cleared by software to turn
timer/counter 0 on/off
IE1 TCON.3 External interrupt 1 edge flag. Set by CPU when the
external interrupt edge (H-to-L transition) is detected.
Cleared by CPU when the interrupt is processed
IT1 TCON.2 Interrupt 1 type control bit. Set/cleared by software to
specify falling edge/low level triggered external interrupt
IE0 TCON.1 External interrupt 0 edge flag. Set by CPU when the
external interrupt edge (H-to-L transition) is detected.
Cleared by CPU when the interrupt is processed
IT0 TCON.0 Interrupt 0 type control bit. Set/cleared by software to
specify falling edge/low-level triggered external interrupt

Harish G C, Assistant Professor, Department of E&CE 85


8051 Microcontroller

Sampling Edge - Triggered Interrupt

In edge-triggered interrupts,

✓ The external source must be held high for at least one machine cycle, and then
held low for at least one machine cycle.
✓ The falling edge of pins INT0 and INT1 are latched by the 8051 and are held by
the TCON.1 and TCON.3 bits of TCON register

• Function as interrupt-in-service flags


• It indicates that the interrupt is being serviced now and on this INTn pin, and
no new interrupt will be responded to until this service is finished

Minimum pulse duration to detect edge-triggered interrupts XTAL=11.0592MHz is

Regarding the IT0 and IT1 bits in the TCON register, the following two points must be
emphasized.
✓ When the ISRs are finished (that is, upon execution of RETI), these bits (TCON.1
and TCON.3) are cleared, indicating that the interrupt is finished and the 8051 is
ready to respond to another interrupt on that pin
✓ During the time that the interrupt service routine is being executed, the INTn pin
is ignored, no matter how many times it makes a high-to-low transition

• RETI clears the corresponding bit in TCON register (TCON.1 or TCON.3)


• There is no need for instruction CLR TCON.1 before RETI in the ISR
associated with INT0
-----------------------------------------------------------------------------------------------------------
Q. What is the difference between the RET and RETI instructions? Explain why we can
not use RET instead of RETI as the last instruction of an ISR.

Ans:
Both perform the same actions of popping off the top two bytes of the stack into the
program counter, and marking the 8051 return to where it left off. However, RETI also
performs an additional task of clearing the interrupt-in-service flag, indicating that the
servicing of the interrupt is over and the 8051 now can accept a new interrupt on that pin.
If you use RET instead of RETI as the last instruction of the interrupt service routine, you
simply block any new interrupt on that pin after the first interrupt, since the pin status
would indicate that the interrupt is still being serviced. In the cases of TF0, TF1, TCON.1,
and TCON.3, they are cleared due to the execution of RETI.

Harish G C, Assistant Professor, Department of E&CE 86


8051 Microcontroller

4.7 INTERRUPT PRIORITY

When the 8051 is powered up, the priorities are assigned according to the sequence given
in table 4.7.1. In reality, the priority scheme is nothing but an internal polling sequence in
which the 8051 polls the interrupts in the sequence listed and responds accordingly.

Interrupt Priority Table 4.7.1 Upon Reset

Example 4.7.1: Discuss what happens if interrupts INT0, TF0, and INT1 are activated at
the same time. Assume priority levels were set by the power-up reset and the external
hardware interrupts are edge triggered.

Solution:
If these three interrupts are activated at the same time, they are latched and kept
internally. Then the 8051 checks all five interrupts according to the sequence listed in
Table 11-3. If any is activated, it services it in sequence. Therefore, when the above three
interrupts are activated, IE0 (external interrupt 0) is serviced first, then timer 0 (TF0), and
finally IE1 (external interrupt 1).
------------------------------------------------------------------------------------------------------------
We can alter the sequence of interrupt priority by assigning a higher priority to any one of
the interrupts by programming a register called IP (interrupt priority)

✓ To give a higher priority to any of the interrupts, we make the corresponding bit in
the IP register high
✓ When two or more interrupt bits in the IP register are set to high. While these
interrupts have a higher priority than others, they are serviced according to the
sequence of Table 4.7.1.

Interrupt Priority Register (Bit-addressable)

-- IP.7 Reserved

Harish G C, Assistant Professor, Department of E&CE 87


8051 Microcontroller

--- IP.6 Reserved


PT2 IP.5 Timer 2 interrupt priority bit (8052 only)
PS IP.4 Serial port interrupt priority bit
PT1 IP.3 Timer 1 interrupt priority bit
PX1 IP.2 External interrupt 1 priority bit
PT0 IP.1 Timer 0 interrupt priority bit
PX0 IP.0 External interrupt 0 priority bit

Example 4.7.2: (a) Program the IP register to assign the highest priority to INT1
(external interrupt 1), then (b) discuss what happens if INT0, INT1, and TF0 are activated
at the same time. Assume the interrupts are both edge-triggered.

Solution:
(a) MOV IP,#00000100B ;IP.2=1 assign INT1 higher priority. The instruction SETB IP.2
also will do the same thing as the above line since IP is bit-addressable.

(b) The instruction in Step (a) assigned a higher priority to INT1 than the others;
therefore, when INT0, INT1, and TF0 interrupts are activated at the same time, the 8051
services INT1 first, then it services INT0, then TF0. This is due to the fact that INT1 has
a higher priority than the other two because of the instruction in Step (a). The instruction
in Step (a) makes both the INT0 and TF0 bits in the IP register 0. As a result, the
sequence in Table 4.7.1 is followed which gives a higher priority to INT0 over TF0
------------------------------------------------------------------------------------------------------------
Example 4.7.3: Assume that after reset, the interrupt priority is set the instruction MOV
IP,#00001100B. Discuss the sequence in which the interrupts are serviced.

Solution:
The instruction “MOV IP #00001100B” (B is for binary) and timer 1 (TF1)to a higher
priority level compared with the reset of the interrupts. However, since they are polled
according to Table, they will have the following priority.

Highest Priority External Interrupt 1 (INT1)


Timer Interrupt 1 (TF1)
External Interrupt 0 (INT0)
Timer Interrupt 0 (TF0)
Lowest Priority Serial Communication (RI+TI)
------------------------------------------------------------------------------------------------------------
4.7.1 INTERRUPT INSIDE AN INTERRUPT:
In the 8051 a low-priority interrupt can be interrupted by a higher-priority interrupt but
not by another low priority interrupt. Although all the interrupts are latched and kept
internally, no low-priority interrupt can get the immediate attention of the CPU until the
8051 has finished servicing the high-priority interrupts
------------------------------------------------------------------------------------------------------------

Harish G C, Assistant Professor, Department of E&CE 88


8051 Microcontroller

PIN DIAGRAM OF 8051

Harish G C, Assistant Professor, Department of E&CE 89


8051 Microcontroller

ARCHITECTURE OF 8051

Harish G C, Assistant Professor, Department of E&CE 90


8051 Microcontroller

PROGRAMMING MODEL OF 8051

Harish G C, Assistant Professor, Department of E&CE 91


8051 Microcontroller

ORGANIZATION OF INTERNAL RAM MEMORY

Harish G C, Assistant Professor, Department of E&CE 92


8051 Microcontroller

SFR REGISTER LAYOUT

Harish G C, Assistant Professor, Department of E&CE 93


8051 Microcontroller

Bit Addressable RAM

Bit Addressable RAM

Harish G C, Assistant Professor, Department of E&CE 94


8051 Microcontroller

Harish G C, Assistant Professor, Department of E&CE 95

You might also like