Microcontrollers: 8051 & MSP430 Course Guide
Microcontrollers: 8051 & MSP430 Course Guide
1. To apply the fundamental knowledge of 8051, MSP 430 architecture and Programming the
Microprocessors
design requirements. and Microcontrollers
2. Analyze real time requirements using ON chip resources of 8051, MSP 430.
3. Evaluate the need of interfacing external devices to satisfy design requirements.
Table of Contents
4. Develop assembly and Embedded C Programs for I/O peripherals.
. 1. Microprocessors and Microcontroller
Suggested Learning Resources:
1.1 Introduction
Text1.2
Books
Difference between Microprocessor and Microcontroller
1.1.3 Muhammad
RISC and CISCAli
CPUMazidi
Architectures
and Janice Gillespie Mazidi and Rollin D. McKinlay, “The 8051
1.4 Microcontroller and Embedded
Harvard & Von-Neumann Systems – using assembly and C”, PHI, 2006 / Pearson,
CPU architecture
2006.
1.4.1 Von Neumann Architecture
2. Ramesh S. Gaonkar , “Microprocessor architecture, programming, and applications with
1.4.2 Harvard Architecture
the 8085”, Prentice Hall, Edition 5, 2002
2. The
3. 8051 Architecture
Douglas hall, “Microprocessor and Interfacing- Programming & Hardware”, 2nd , TMH,
2.1 2006
Introduction
4.2.2 John Davies,of“MSP430
Architecture 8051 Microcontroller Basics”, Elsevier, 2008.
REFERENCE 2.2.1BOOKS:
Arithmetic and Logic Unit
1. Kenneth2.2.2
J. Ayala “The 8051 Microcontroller Architecture, Programming & Applications”, 2nd
CPU Registers
edition, Penram International,
2.2.3 Program 1996 (PSW)
Status Word Thomson Learning 2005.
2. Raj Kamal, “Microcontrollers: Architecture, Programming, Interfacing and System Design”,
2.2.4 Memory
Pearson Education, 2005.
3. Y.C. Liu2.2.5
andSpecial
G. A. Gibson
Function,“Microcomputer
Registers (SFR) systems-The 8086 / 8088 Family” 2E PHI -2003
Referred link
2.3 Pin Diagram of 8051 Microcontroller
[Link]
2.4 External
Activity Memory interface
Based Learning (Suggested Activities in Class)/ Practical Based learning Programming
Assignments / Mini Projects RAM
2.4.1 External Data interface
can be given to improve programming skills
2.4.2 External Data ROM interface
2.5 Stack
2.6 Addressing Modes of 8051
2.6.1 Immediate Addressing Mode
2.6.2 Register Addressing Mode
2.6.3 Direct Addressing mode
2.6.4 Register indirect addressing mode
2.6.5 Indexed addressing mode
1.1 Introduction
The term microprocessor and microcontroller have always been confused with each other. Both of
them have been designed for real time application. They share many common features and at the same
time they have significant differences. Both the IC’s i.e., the microprocessor and microcontroller
cannot be distinguished by looking at them. They are available in different version starting from 6 pin
3
to as high as 80 to 100 pins or even higher depending on the features.
The 8051 is the first microcontroller of the MCS – 51 families, introduced by Intel Corporation at the
end of the 1980s. The 8051 family with its many enhanced members enjoys the largest market share,
estimated to be about 40% among the various microcontroller architecture. This microcontroller had
128 bytes of RAM, 4K bytes of On – chip ROM, two timers, one serial port and four ports (each of 8 –
bits wide) all on a single chip. At the time, it was referred to as a “ system on a chip”. The 8051 is an 8 –
bit processor, meaning that the CPU can work on only 8 bits of data at a time.
The salient features of the 8051 microcontroller are given below:
8 – bit CPU.
On – chip clock oscillator.
4K bytes of on – chip program memory (ROM).
128 bytes of on – chip program memory (RAM).
Four 8 – bit ports named, P0, P1, P2 and P3.
Two 16 – bit Timers named T0 and T1.
Full duplex asynchronous receiver transmitter (UART)
Five – vector interrupt structure with 2 priority levels.
External memory interface of up to 64K bytes of Program and data space.
Fig 2.2 shows the functional block of the internal operations of an 8051 microcontroller. The
8051 includes an 8 – bit CPU, memory, four 8 – bit ports, two 16 – bit timer/counters and a
universal Asynchronous Receiver Transmitter.
2.2.1 Arithmetic and Logic Unit
The Arithmetic and Logic Unit (ALU) performs the computing functions. The accumulator is
an 8 – bit register. In arithmetic and logical operations, one of the operands is present in ‘A’
register. After the arithmetic or logical operations being performed, the result is stored in ‘A’
register and the status of the ALU operations will be reflecting in the status flag register
4
(PSW) of 8051.
CPU Registers
‘A’ Register (0E0h): Similar to any Intel microprocessor, the 8051 has an 8 bit Accumulator
register, and in the instructions, it is referred as ‘A’. The accumulator is used in all arithmetic
5
and logical operations and has direct connections to ALU. One of the operands is stored in the
‘A’ register. In multiplication process, one of the 8 – bit operands is stored in ‘A’ register, and
after the operation, register ‘A’ contains lower byte of the result. Similarly, in division
operation, it holds the 8 – bit dividend, and after the operation, the quotient is stored in ‘A’.
Also in indexed addressing mode, register ‘A’ holds the index value to be added with
DPTR/PC to generate the address of program memory.
‘B’ Register (0F0h): The 8 – bit ‘B’ register is used in multiply and division operations. In
multiplication operation, one of the operand is available in register ‘B’, and after the
operation, the upper byte of the product is available in ‘B’. Similarly, in division operation, it
holds the 8 – bit divisor, and after the operation, the remainder is stored in ‘B’.
Program Status Word Register (0D0h): The 8 – bit Program Status Word (PSW) register
contains the arithmetic status of the ALU and the register bank select bits for the data memory.
8051 has 4 Math flags (CY, OV, AC & P) which tell the status of the arithmetic operations
performed by 8051. PSW is a Bit addressable register.
R0 to R7 Registers: The "R" registers are a set of eight 8 – bit registers that are named R0, R1, etc. up
to and including R7. These registers are used as auxiliary registers in many operations.
You may think of the "R" registers as very important auxiliary, or "helper", registers. The Accumulator
alone would not be very useful if it were not for these "R" registers. The "R" registers are also used to
temporarily store values. In addition, the Registers R 0 and R1 will be useful to hold the address of
internal RAM locations and work as Address pointers.
The Data Pointer (DPTR): The Data pointer (DPTR) is a 16 – bit register, consist of two 8 –
bit registers, a high byte (DPH), and a low byte (DPL). Its intended is to hold a 16 – bit
address of the external RAM or internal/external ROM.
Program Counter (PC): Program counter is a 16 – bit register. The 16 – bit PC specifies the
address of the next instruction to be executed. Upon reset, the PC will be set to 0000h, and the
CPU will start executing the first instruction stored in the program space at 0000h. The PC
automatically updates to point to the next instruction based on the instruction length. For
instance, if the instruction length is 2 bytes, the PC will be incremented twice to execute the
next instruction. The instructions of 8051 is of length 1/2/3 bytes.
The Stack Pointer (SP): The stack pointer is an 8 – bit register. The Stack Pointer is used to
indicate where the next value to be removed from the stack should be taken from. Upon reset,
the stack pointer is initialized to 07h, its default value, defining the stack memory from 08h of
internal RAM.
6
Program Status Word (PSW)
The program status word (PSW) register is an 8 – bit register. It is also referred as the flag register.
Although the PSW register is 8 – bit wide, only 6 bits of it are used by the 8051. The two unused bits
are user – definable bits. Four of the flags are called conditional flags, meaning that they indicate
some conditions that result after an instruction is executed. These four flags are CY (Carry), AC
(Auxiliary Cary), P (Parity) and OV (Overflow).
Memory
The 8051 have 4KB of on chip program memory (ROM), 128 Bytes of on chip data memory
7
(RAM) and 21 bytes meant for Special function registers (SFR). The following diagram
shows the programming model of 8051 Microcontroller.
Internal RAM Organization:
The internal RAM of 8051 is 128 Bytes of which
i). Four register banks, each containing eight registers
ii). Sixteen Bytes which may be addressed at the bit level
iii). Eighty Bytes of general purpose data memory.
i). Register Banks (00h – 1fh): The first 32 bytes of 8051 internal RAM are grouped into
four banks (RB0 – RB3) of eight locations each. RS1 and RS0 of (Bit 4 & 3) PSW are used
to select different register banks.
ii). Bit addressable RAM (20h – 2fh): A bit addressable area of 16 Bytes occupies RAM
byte address 20h – 2Fh, forming a total of 128 addressable bits. An addressable bit may be
specified by its bit address of 00h – 7Fh, or 8 – bits may form a byte address from 20h –
2Fh. Thus for example, bit address 4Fh is also bit 7 of byte address 29h. Addressable bits are
useful when the program need only to remember a binary event.
8
00h R0 30h
01h R1
02h R2
03h R3
04h R4
05h R5
06h R6
07h R7
08h R0
09h R1
0Ah R2
0Bh R3
0Ch R4
0Dh R5
0Eh R6
0Fh R7
MSB LSB
10h R0
20h 07h 00h
11h R1
21h 0Fh 08h
12h R2
22h 17h 10h
13h R3
23h 1Fh 18h
14h R4
24h 27h 20h
15h R5
25h 2Fh 28h
16h R6
17h R7 26h 37h 30h
18h R0 27h 3Fh 38h
19h R1 28h 47h 40h
1Ah R2 29h 4Fh 48h
1Bh R3 2Ah 57h 50h
1Ch R4 2Bh 5Fh 58h
1Dh R5 2Ch 67h 60h
1Eh R6 2Dh 6Fh 68h
1Fh R7 2Eh 77h 70h
2Fh 7Fh 78h
7Fh
a). Working Registers b). Bit Addressable RAM c). General Purpose RAM
Note: Byte Addresses are shown to the left; Bit Addresses are shown inside a location.
Fig. 2.5: Internal RAM Organization
iii). General Purpose RAM (30h – 7fh): These 80 Bytes of internal RAM are available for
9
general purpose data storage. Access to this area of memory is fast as compared to access of
external memory and instructions with a single byte operands use this area for storage.
2.2.5 Special Function Registers (SFR)
The SFR registers are located in the address range 80h – FFh as shown in the table 2.1. Not
all the locations within the range are defined. Each SFR has a very specific function. Only 21
SFRs are available in 8051 microcontroller and the following table defines all the SFRs
available. (* represents Bit addressable SFR).
Sl. No Symbol Name Address
1 *A Accumulator 0E0h
2 *B B Register 0F0h
3 *PSW Program Status Word 0D0h
4 SP Stack pointer 81h
5 DPL Data Pointer Low 82h
6 DPH Data Pointer High 83h
7 *P0 Port 0 80h
8 *P1 Port 1 90h
9 *P2 Port 2 0A0h
10 *P3 Port 3 0B0h
11 *IP Interrupt Priority 0B8h
12 *IE Interrupt Enable 0A8h
13 TMOD Timer Mode Control 89h
14 *TCON Timer Control 88h
15 TH0 Timer/ Counter 0 High 8Ch
16 TL0 Timer/ Counter 0 Low 8Ah
17 TH1 Timer/ Counter 1 High 8Dh
18 TL1 Timer/ Counter 1 Low 8Bh
19 *SCON Serial Control 98h
20 SBUF Serial Data Buffer 99h
21 PCON Power Control 87h
Table 2.1
Note: The lower nibble of SFR address ending with 0 or 8 are Bit – Addressable SFR.
The complete SFR memory map is shown in fig. 2.6.
10
The direct addressing is the only way to access the SFRs except the Accumulator. Out of 21
SFRs of 8051, 11 SFRs are Bit – addressable; whose lower nibble addresses ends either with
0 or 8.
Port 0, provides both address and data. The 8051 multiplexes address and data through port 0
to save pins.
Port 2 Alternate function
As shown in pin diagram, Port 2 is designated as A 15 – A8, allowing it to be used for upper 8 –
bit address of external memory connecting to 8051.
Port 3 Alternate function
Port 3 has additional function of providing some extremely important signals such as
interrupts. Table 2.2 provides the alternate functions of P3.
P3.2 ∫ 0 ( Interrupt 0) 12
External
Interrupts
P3.3 ∫ 1 ( Interrupt 1) 13
12
P3.6 WR ( Write Strobe) 16
External RAM
P3.7 RD ( Read Strobe) 17 signals
Table 2.2
EA
If external access ¿) is held high, it selects
internal program memory (ROM) for the
address 0000h to 0FFFh. Beyond this address
(1000h to FFFFh), it selects external program
memory as shown in fig. 2.8. Else, if this pin
is connected to GND (active low signal), it
selects only external program memory for the
address ranging from 0000h to FFFFh.
PSEN
Program strobe signal is the output control signal. It remains low while fetching external
program memory. During the internal program execution, the condition of this pin is high.
ALE
• Address latch enable is used to
demultiplex AD0 – AD7 of port 0. ALE
indicates if P0 has address or data.
– When ALE=0, it provides data
D0-D7
– When ALE=1, it has address
A0-A7
This signal is used primarily to latch low
order address from the multiplexed bus and
generate a separate bus of eight address lines
13
A0 – A7 as shown in Fig. 2.9.
2.4 Stack
The stack refers to an area of internal RAM that is used in conjunction with certain op codes
to store and retrieve data quickly. The 8 – bit stack pointer (SP) register is used by the 8051
to hold an internal RAM address that is called the top of the stack. The address held by the
SP register is the location in the internal RAM where the last byte of data was stored by a
stack operation. When the 8051 is powered on, the SP register contains the value of 07h.
This means, that RAM location 08h is the first location used for the stack by 8051.
When data is to be placed on the stack (PUSH Operation), the SP increments by 1 before
storing data on the stack, so that the stack grows up as data is stored. As data is retrieved
from the stack (POP Operation), the byte is read from the stack, and then the SP
decremented to point to the next available byte of stored data.
Show the Stack and stack pointer for the following. Assume the default stack area and
the register bank 0 is selected.
MOV R6, #25h
PUSH 6
PUSH 1
PUSH 4
Examining the stack, show the contents of the registers and SP after execution of the
following instructions.
POP 3 08h 6C
POP 5 09h 76
0Ah F9
POP 2
0Bh 54
Start SP = 0Bh
Show the Stack contents, SP contents & Contents of any register affected after each step of the
following sequence of operations.
MOV 81h, #70h
MOV A, #44h
ADD A, R5
MOV R4, A
PUSH 4
PUSH 5
POP 4
Since stack pointer is loaded with 70h, the stack memory starts from 71h onwards.
15
SP 70 70 00 70 00 70 00
R5 30 71 74 71 74 71 74
A 74 72 00 72 30 72 30
R4 74 73 00 73 00 73 00
For every PUSH Instruction, the stack pointer gets incremented by 1, & in that internal RAM
content, the direct RAM address content gets stored. Thus, PUSH 4 stores 04h Content (74h)
on 71h & PUSH 5 stores 05h Content (30h) on 72h. The POP 4 will retrieve the 72h content
(30h) and moves to 04h content. After this, SP gets decremented by 1. Thus R4 will be 30h
The CPU can access data in various ways. The data could be in a register, or in a memory, or
be provided as an immediate value. These various ways of accessing data are called
addressing modes.
The 8051 microcontroller provides a total of five distinct addressing modes. They are as
follows:
i). Immediate
ii). Register
iii). Direct
iv). Register indirect
v). Indexed
2.5.1 Immediate Addressing Mode
In this addressing mode, the source operand is a constant. In immediate addressing mode, as
the name implies, the instruction is assembled, the operand comes immediately after the
opcode.
Ex: MOV A, #25h ;loads 25h into A
MOV DPTR, #25h ;DPTR = 00 25h
16
2.5.2 Register Addressing Mode
Register addressing mode involves the use of registers to hold the data to be manipulated.
Ex: MOV A, R0 ; copy the content of R into A
MOV R6, A ; Saves accumulator in R6
It should be noted that the source and the destination register size must match. For instance,
MOV A, DPTR is invalid since DPTR is 16 – bit and the accumulator is 8 – bit wide.
This addressing mode can move data between the accumulator and R registers, but
movement of data between R registers is not allowed. For Ex., the instruction MOV R1, R2
is invalid.
2.5.3 Direct Addressing mode
In this addressing mode, the data is there in a Internal RAM memory location whose address
is known and this address is given as a part of the instruction. Any internal RAM address or
SFR address can be given directly in the instruction.
Ex: MOV A, 40h ; Save the content of RAM loc 40h into A
MOV 0D0h, A ; Save the content of A in RAM Loc PSW.
Another major use of direct addressing mode is the stack. In the 8051 family, only direct
addressing mode is allowed for pushing onto the stack. Therefore, an instruction such as
“PUSH A” is invalid. Pushing the accumulator content onto the stack must be “PUSH
0E0h”.
2.5.4 Register indirect addressing mode
In the register addressing mode, a register is used as a pointer to the data. If the data is inside
the CPU, only registers R0 and R1 are used for this purpose. In other words, R2 – R7 cannot
be used to hold the address of an operand located in RAM using this addressing mode. When
R0 or R1 are used as a pointers, they must be preceded by the “@” sign as shown below.
Ex: MOV A, @R0 ; move the content of internal RAM location whose address is held by
R0 into A.
MOV 40h, @R1 move the content of internal RAM location whose address ; is held by
R0 into 40h
Also, the indirect addressing is the only way, for all External Memory access of data. In case
of External access of Data, the 16 – bit address must be made available in DPTR as below.
Ex: MOVX A, @DPTR ;Move the external RAM Content whose address is held by
DPTR into A
2.5.5 Indexed addressing mode
17
Indexed addressing mode is widely used in accessing data elements of look – up table entries
in the program ROM space of 8051 microcontroller.
Ex: MOVC A, @A+DPTR
MOVC A, @A+PC
The 16 – bit DPTR/PC and register A are used to form the address of the data element stored
in the on – chip ROM. Since the data element is stored in the code space (Program memory)
of 8051, it uses the MOVC instead of MOV (‘C’ represent Code space).
Module 2
Instruction Set
18
Table of Contents
1. Instruction timings
3. Arithmetic instructions,
4. Logical instructions
5. Branch instructions
7. Subroutine instructions
8. Assembler Directives
1. Instruction Timings
The 8051 internal operations and external read/write operations are controlled by the
oscillator clock which runs by crystal connected between XTAL2 and XTAL1 pins of 8051.
Machine cycle is defined as 12 oscillator periods. A machine cycle consists of six states and each
state lasts for two oscillator periods. An instruction takes one to four machine cycles to execute
an instruction.
Instruction cycle is defined as the time required for completing the execution of an instruction.
The 8051 instruction cycle consumes one or two or four machine cycles.
19
Ex. If 8051 microcontroller is operated with 12 MHz oscillator, find the execution time for the
following four instructions.
1. ADD A, 45H ---------------1 mc
2. SUBB A, #55H ---------------1mc
3. MOV DPTR, #2000H--------2mc
4. MUL AB ----------------------4mc
*mc-machine cycle
Since the oscillator frequency is 12 MHz, Time for 1 machine cycle = 12/12 MHz =1 μS.
Total time consumed by above code is
=total number of machine cyclesX Period of 1mc
=8X1 μS.=8 μS.
8051 Instructions
memory, which is why ―X is appended to MOV. There are two types of instructions, differing in
whether they provide an 8-bit or 16-bit indirect address to the external data RAM.
MOVX A,@R1
MOVX @R0,A
The above instructions are used to access 256 bytes(called as 1 page) of external memory
MOVX A,@DPTR
MOVX@DPTR,A
The above instructions are used to access entire 64Kb of external memory.
m. Move the contents of program memory to A
MOVC A, @A+PC
MOVC A, @A+DPTR
The MOVC instructions load the Accumulator with a code byte or constant from program
Memory. The address of the byte fetched is the sum of the original unsigned 8-bit Accumulator
contents and the contents of a 16-bit base register, which may be either the Data Pointer or the
PC. No flags are affected after execution.
21
*Ri-R0/R1
Rn-R0 to R7
VV-immediate 8 bit data
DD-direct address
VVVV-immediate 16 bit data
A stack is a last in first out memory. In 8051 internal RAM space can be used as stack. The
22
address of the stack is contained in a register called stack pointer. Instructions PUSH and POP
are used for stack operations. When a data is to be placed on the stack, the stack pointer
increments before storing the data on the stack so that the stack grows up as data is stored
(pre-increment). As the data is retrieved from the stack the byte is read from the stack, and then
SP decrements to point the next available byte of stored data (post decrement). The stack
pointer is set to 07 when the 8051 resets. So that default stack memory starts from address
location 08 onwards (to avoid overwriting the default register bank ie., bank 0).
Eg; Show the stack and SP for the following
[SP]=07 //CONTENT OF SP IS 07 (DEFAULT VALUE)
MOV R6, #25H
MOV R1, #12H
MOV R4, #0F3H
PUSH 6
PUSH 1
PUSH 4
POP 6
POP 1
POP 4
The content of source ie., register, direct memory or indirect memory will be exchanged with
the contents of destination ie., accumulator.
XCH A,Rn ex: XCH A, R6=> exchanges the contents of Accumulator with R6
23
XCH A,@Ri ex: XCH A,
XCH A,DDh
k. Exchange digit. Exchange the lower order nibble of Accumulator (A0-A3) with lower order
nibble of the internal RAM location which is indirectly addressed by the register.
i. XCHD A,@R1
ii. XCHD A,@R0
3. Arithmetic instructions.
The 8051 can perform addition, subtraction. Multiplication and division operations on 8 bit
unsigned numbers.
3.1 Addition
In this group, we have instructions to
i. Add the contents of A with immediate data with or without carry: ADD A,#VV
i. ADD A, #45H
ii. ADDC A, #OB4H
ii. Add the contents of A with register Rn with or without carry.: ADD A, R5
i. ADD A, R5
ii. ADDC A, R2
iii. Add the contents of A with contents of memory with or without carry using direct and
indirect addressing : ADD A, DDH/ADD A,@Ri
i. ADD A, 51H
ii. ADDC A, 75H
iii. ADD A, @R1
iv. ADDC A, @R0
CY AC and OV flags will be affected by above operations.
Instruction: ADD A, R0
Number of bytes: 1 byte
Machine cycles: 1 cycle
Function: adds the content of R0 and accumulator, store the sum into accumulator.
24
Operation : A A+[R0]
Flags Affected: all flags are affected
Before execution: After Execution
R0=5Eh R0=5Eh
1: MOV A,#23H
MOV R1,#55H
ADD A,R1 // [A]=78
DA A // [A]=78 no changes in the accumulator after da a
Eg 2: MOV A,#53H
MOV R1,#58H
ADD A,R1 // [A]=ABh
DA A // [A]=[A]+66H ->[A]=11, CY=1,AF=1,PF=1,OV=0 . ANSWER IS 111. Accumulator data is
changed after DA A
3.4 Subtraction
In this group, we have instructions to
i. Subtract the contents of A with immediate data with or without carry. SUBB A, #VV
i. SUBB A, #45H
ii. SUBB A, #OB4H
ii. Subtract the contents of A with register Rn with or without carry. SUBB A, Rn
i. SUBB A, R5
ii. SUBB A, R2
iii. Subtract the contents of A with contents of memory with or without carry using direct and
indirect addressing: SUBB A, DDh/ SUBB A, @Ri
i. SUBB A, 51H
ii. SUBB A, 75H
iii. SUBB A, @R1
25
iv. SUBB A, @R0
CY AC and OV flags will be affected by this operation.
Instruction: MUL AB
Number of bytes: 1 byte
Machine cycles: 4 cycles
Function: Multiply the contents of A and B store lower byte of product in A and higher byte in B.
Operation : A:B AXB
Flags Affected: all flags are affected
Before execution: After Execution
A=5Eh A=98h
B=F4h B=59h , flags: CY=0, P=1,OV=1(as product is > 8 bit)
DIV AB. This instruction divides the 8 bit unsigned number which is stored in A by the 8 bit
unsigned number which is stored in B register. After division the result will be stored in
accumulator and remainder will be stored in B register. Overflow flag is 1.
Instruction: DIV AB
Number of bytes: 1 byte
Machine cycles: 4 cycles
Function: Divide the contents of A by B store quotient in A and remainder in B.
Operation : A:B A/B
Flags Affected: all flags are affected
Before execution: After Execution
26
A=E8h A=08h
B=1Bh B=10h , flags: CY=0, P=1,OV=0
Note: to calculate remainder =dividend-(divisorXquotient)
ANL A,#VVh
ANL A, Rn
ANL A,DDh
ANL A,@Ri
ANL DDh,A
ANL DDh, #VVh
27
Refer class notes for sample explanations:
Logical Ex-OR
XRL destination, source: XRL does a bitwise "EX-OR" operation between source and destination,
leaving the resulting value in destination. The value in source is not affected. " XRL " instruction
logically EX-OR the bits of source and destination.
XRL A,#DATA XRL A,Rn
XRL A,DIRECT XRL A,@Ri
XRL DIRECT,A XRL DIRECT, #DATA
Sample explanation
Instruction: XRL 40h,#0fh
Number of bytes: 1 byte
Machine cycles: 2 cycles
Function: Exor the contents of memory location with immediate value store the result in
memory location
Operation :
Flags Affected: all flags are affected
Before execution: After Execution
M[40h]=5Eh M[40h]=51h
Logical NOT
CPL complements operand, leaving the result in operand. If operand is a single bit then the state
of the bit will be reversed. If operand is the Accumulator then all the bits in the Accumulator will
be reversed.
CPL A
ORL destination, source: ORL does a bitwise "OR" operation between source and destination,
leaving the resulting value in destination. The value in source is not affected. " OR " instruction
logically OR the bits of source and destination.
ORL A,#VV
ORL A, Rn
ORL A,DDH
ORL A,@Ri
ORL DDh,A
ORL DDh, #VV
SWAP A – Swap the upper nibble and lower nibble of A. The swap instruction works only with
Accumulator. It swaps the lower nibble and the upper nibble of accumulator.
Rotate Instructions
28
RR A
This instruction is rotate right the accumulator. Its operation is illustrated below. Each bit is
shifted one location to the right, with bit 0 going to bit 7.
RL A
Rotate left the accumulator. Each bit is shifted one location to the left, with bit 7 going to bit 0
RRC A
Rotate right through the carry. Each bit is shifted one location to the right, with bit 0 going into
the carry bit in the PSW, while the carry was at goes into bit 7
RLC A
Rotate left through the carry. Each bit is shifted one location to the left, with bit 7 going into the
carry bit in the PSW, while the carry goes into bit 0.
Sample explanation
Instruction: RL A
Number of bytes: 1 byte
Machine cycles: 1 cycle
Function: Rotate the accumulator Left by 1 bit
Operation : D0<-D7 and D7:D1<-D6:D0
Flags Affected: no flags are affected
Before execution: After Execution
A=10h A=20h
5. Branch (JUMP) Instructions
Jump and Call Program Range
There are 3 types of jump instructions. They are:-
1. Relative Jump
29
2. Short Absolute Jump
3. Long Absolute Jump
Relative Jump
Jump that replaces the PC (program counter) content with a new address by adding relative
address to the PC. Reladdr must be within -128 (for back ward jump) or +127 bytes of the
instruction(for forward jump) that follows the SJMP instruction
31
Instruction: DJNZ Rn,<reladds>
Number of bytes: 2 bytes
Machine cycles: 2 cycles
Function:Rn<-Rn-1
If Rn≠00 jump to location by adding reladds to PC
AJMP unconditionally jumps to the indicated code address. The new value for the Program
Counter is calculated by replacing 11 bits of the PC with 11 bits of absolute address. It is short
absolute range jump. The destination address is a 11 – bit constant. The instruction is 2 – byte
long. The jump will happen anywhere in 2K size of program memory.
This is long call instruction which unconditionally calls the subroutine located at the indicated
16 bit address. This is a 3 byte instruction. The LCALL instruction works as follows.
a. During execution of LCALL, [PC] = [PC]+3;
b. [SP]=[SP]+1; increment the stack pointer by 1
c. [[SP]]; = [PC7-0]; store the lower byte of return address ( ie lower byte of PC) onto the stack
d. [SP]=[SP]+1; increment the stack pointer by 1
e. [SP]] = [PC15-8]; store the higher byte of return address ( ie lower byte of PC) onto the stack
f. [PC]= address (16 bit); the new address of subroutine is loaded to PC. No flags are affected.
2. ACALL address11
This is absolute call instruction which unconditionally calls the subroutine located at the
indicated 11 bit address. This is a 2 byte instruction. The SCALL instruction works as follows.
a. During execution of LCALL, [PC] = [PC]+3;
b. [SP]=[SP]+1; increment the stack pointer by 1
c. [[SP]] = [PC7-0]; store the lower byte of return address ( ie lower byte of PC) onto the stack
d. [SP]=[SP]+1; increment the stack pointer by 1
e. [[SP]] = [PC15-8]; store the higher byte of return address ( ie lower byte of PC) onto the stack
f. [PC10:PC0]=addr11, 11 bit absolute address the new address of subroutine is loaded to PC.
No flags are affected
34
RET instruction
RET instruction pops top two contents from the stack and load it to PC.
g. [PC15-8] = [[SP]] ;content of current top of the stack(higher byte of return address) will be
moved to higher byte of PC.
h. [SP]=[SP]-1; (SP decrements)
i. [PC7-0] = [[SP]] ;content of bottom of the stack(lower byte of return address) will be moved
to lower byte of PC.
j. [SP]=[SP]-1; (SP decrements again)
8. Assembler Directives
The assembler directives instruct the assembler on how to process subsequent assembly
language instructions. Each assembler uses various directives. This does not create any
machine code like ALP does. The most common assembler directives are listed as follows
i). ORG
ii). END
iii). EQU
iv). DB
i). ORG (origin): the ORG directive is used to indicate the beginning address of a
program segment or a program itself. The number after ORG can be hex or in decimal.
Ex: ORG 00h ; this directive tells the CPU that the machine codes of the following
instructions are stored in ROM space from address 0000h.
ii). END: This directive indicates to the assembler the end of the source (ASM) file.
Anything after this directive is ignored by the assembler.
iii). EQU (Equate): This directive is used to define constant, without occupying a
memory location. It equates a constant with a data name, and where ever the name is
used in the program, its constant value is substituted.
For Ex.
35
N equ 10
………….
MOV R2, #N will move R2 with a value of 0Ah.
iv). DB (Define byte): This directive is used to define the 8 – bit data. When DB is used
to define data, we can use decimal, binary, hex or ASCII formats. For a decimal number
“D” after the number is optional; a binary number is indicated by a “B” at the end of the
number, “H” for hexa decimal number. To indicate ASCII format, the characters are
placed in quotation marks
Ex:
ORG 30h
data1: DB 16 ; Decimal
data2: DB 16h ; hexa format
data3: DB 0010b ; binary format
data4: DB “16” ; ASCII Format
36
37
Instruction sets of 8051
Arithmatic Operations
NO. OF
OPERAND DESCRIPTION
PCODE BYTES
ADD A,Rn Add register to Accumulator 1
ADD A,direct Add direct byte to Accumulator 2
38
ADD A,@Ri Add indirect RAM to Accumulator 1
ADD A,#data Add immediate data to Accumulator 2
Add register to Accumulator with
ADDC A,Rn 1
Carry
Add direct byte to Accumulator with
ADDC A,direct 2
Carry
Add indirect RAM to Accumulator
ADDC A,@Ri 1
with Carry
ADDC A,#data Add immediate data to Acc with Carry 2
Subtract Register from Acc with
SUBB A,Rn 1
borrow
Subtract direct byte from Acc with
SUBB A,direct 2
borrow
Subtract indirect RAM from ACC
SUBB A,@Ri 1
with borrow
Subtract immediate data from Acc
SUBB A,#data 2
with borrow
INC A Increment Accumulator 1
INC Rn Increment register 1
INC direct Increment direct byte 2
INC @Ri Increment direct RAM 1
DEC A Decrement Accumulator 1
DEC Rn Decrement Register 1
DEC direct Decrement direct byte 2
DEC @Ri Decrement indirect RAM 1
INC DPTR Increment Data Pointer 1
MUL AB Multiply A & B 1
DIV AB Divide A by B 1
DA A Decimal Adjust Accumulator 1
LOGICAL OPERATIONS
C Clear Carry 1
CLR
CLR bit Clear direct bit 2
SETB C Set Carry 1
SETB bit Set direct bit 2
CPL C Complement Carry 1
CPL bit Complement direct bit 2
ANL C,bit AND direct bit to CARRY 2
ANL C,/bit AND complement of direct bit to Carry 2
ORL C,bit OR direct bit to Carry 2
ORL C,/bit OR complement of direct bit to Carry 2
MOV C,bit Move direct bit to Carry 2
MOV bit,C Move Carry to direct bit 2
JC rel Jump if Carry is set 2
JNC rel Jump if Carry not set 2
JB bit,rel Jump if direct Bit is set 3
JNB bit,rel Jump if direct Bit is Not set 3
JBC bit,rel Jump if direct Bit is set & clear bit 3
PROGRAM BRANCHING
MOVX A, @DPTR
MOV R1, A
42
MOV DPH, R3
MOVX A, @DPTR
ADDC A, R1
MOV @R0, A
DEC R0
DEC DPL
DJNZ R7, BACK
SJMP $
2. Write an 8051 ALP to find the sum of 20 data bytes stored in an array of external RAM
starting with address 2000h. Store the 16 bit sum at the end of array.
MOV R7, #20
MOV DPTR, #2000H
MOV R2, #00
MOV R1, #00
ADD A, R2
MOV R2, A
JNC SKIP
INC R1
INC R2
SKIP: INC R0
43
DJNZ R7, BACK
MOV P0, A
MOV P1, R2
SJMP $
i). Exchange contents of External RAM to ii). Exchange contents of A and B Register
Internal Ram using stack
MOV DPTR, #8100h PUSH 0E0h
MOV R0, #40h PUSH 0F0h
MOVX A, @DPTR POP 0E0h
MOV 30h, @R0 POP 0F0h
MOV @R0, A SJMP $
MOV A, 30h
MOVX @DPTR, A
SJMP $
5. Write an 8051 ALP which checks whether the 10 nos. stored from external RAM memory
address, 2000h are odd/even. The program should store accordingly 00/FFh from internal
RAM loc. 30h onwards
The 8 – bit binary number can be odd if the LSB is 1, even if the LSB is 0.
For ex. Consider the 8 – bit number as DA h: the LSB is 0, so the given no is even and so on.
MOV DPTR, #2000h
MOV R0, #30h
MOV R7, #10
RPT: MOVX A, @DPTR
JNB 0E7h, EVE
ODD: MOV @R0, #00
SJMP SKIP
SKIP: INC R0
INC DPTR
44
DJNZ R7, RPT
SJMP $
6. Write a subroutine which checks the content of 20h. If it is a positive number, the
subroutine finds its 2’s complement and stores it in same location and returns.
The 8 – bit number can be a positive number, if its MSB is 0, negative number if the MSB is 1.
For instance, if the number is say, 7A h, the number is a positive number since the MSB is 0.
POSIT: MOV A, 20h
JB 0E7hLAST
CPL A
INC A
MOV 20h, A
LAST: RET
7. Write an ALP in 8051 to count the number of positive and negative numbers present in the
internal memory block starting with the address 20h containing N – bytes. Store the count
after the last byte in the memory block.
MOV R7, #N
MOV R0, #20h
MOV R1, #0 ; for counting positive numbers
MOV R2, #0 ; for counting negative numbers
JB 0E7h, NEG
POS: INC R1
SJMP SKIP
NEG: INC R2
SKIP: INC R0
8. Write an ALP to find the average of 10 numbers stored at external data memory starting at
1000h. Store the result at the end of the array
45
MOV DPTR, #1000h
MOV R7, #10
MOV R0, #00
MOV 0F0h, R7
ADD A, R0
MOV R0, A
INC DPTR
DJNZ R7, RPT
DIV AB
MOVX @DPTR, A
END
RET
10. Write an 8051 assembly time delay subroutine to generate a time delay of 100µs when
called. Assume crystal frequency is 12MHz. Show delay calculations. Do not use timers.
Since the crystal frequency is 12MHz, 1 machine cycle = 1µs. DJNZ instruction is a 2 machine
cycle instruction, so if R2 is loaded with 50, DJNZ r2, $ will execute for 100µs.
DELAY: MOV R2, #50
DJNZ R2, $ ; 2 Machine Cycle Instructions repeating for 50 times
RET
11. A 4 – bit number N is available in internal RAM location 40h. write an ALP to compute 1 + 2
+ 3 + … + N and store the 8 – bit result in 41h and 42H
MOV R0,40H
46
CLR A
MOV R1,#01
MOV R2,#00H
ADD A, R1
JNC SKIP
INC R2
SKIP: INC R1
DJNZ R0 RPT
MOV 41H, A
MOV 42H,A
SJMP $
12. Write an ALP to count the number of 1’s and 0’s of an 8 – bit data stored in RAM loc 6000h.
Store the 1’s count in 6001h and 0’s count in 6002h.
MOV DPTR, #6000h
MOVX A, @DPTR
MOV R7, #8
MOV R1, #00
MOV R2, #00
BACK: RLC A
JC SKIP
INC R1
SJMP LAST
SKIP: INC R2
MOV A, R1
INC DPTR
MOVX @DPTR, A
MOV A, R2
INC DPTR
MOVX @DPTR, A
SJMP $
END
47
48
49
50
51
2.3 Pin Diagram of 8051 Microcontroller
52
As shown in pin diagram, Port 0 is designated as
AD7 – AD0, allowing it to be used for both
address and data. When connecting an external
memory to 8051,
Port 0, provides both address and data. The 8051 multiplexes Fig. 2.7:and
address Pindata
diagram of 8051
through port 0 to
save pins.
Port 2 Alternate function
As shown in pin diagram, Port 2 is designated as A 15 – A8, allowing it to be used for upper 8 –
bit address of external memory connecting to 8051.
Port 3 Alternate function
Port 3 has additional function of providing some extremely important signals such as interrupts.
Table 2.2 provides the alternate functions of P3.
P3.2 ∫ 0 ( Interrupt 0) 12
External
Interrupts
P3.3 ∫ 1 ( Interrupt 1) 13
53
P3.6 WR ( Write Strobe) 16
External RAM
P3.7 RD ( Read Strobe) 17 signals
Table 2.2
EA (Pin 31)
If external access ¿) is held high, it selects
internal program memory (ROM) for the
address 0000h to 0FFFh. Beyond this
address (1000h to FFFFh), it selects external
program memory as shown in fig. 2.8. Else,
if this pin is connected to GND (active low
signal), it selects only external program
memory for the address ranging from 0000h
to FFFFh.
2.4 Stack
The stack refers to an area of internal RAM that is used in conjunction with certain op codes
to store and retrieve data quickly. The 8 – bit stack pointer (SP) register is used by the 8051
to hold an internal RAM address that is called the top of the stack. The address held by the
SP register is the location in the internal RAM where the last byte of data was stored by a
stack operation. When the 8051 is powered on, the SP register contains the value of 07h.
This means, that RAM location 08h is the first location used for the stack by 8051.
When data is to be placed on the stack (PUSH Operation), the SP increments by 1 before
storing data on the stack, so that the stack grows up as data is stored. As data is retrieved
from the stack (POP Operation), the byte is read from the stack, and then the SP
decremented to point to the next available byte of stored data.
Ex. 3 Show the Stack and stack pointer for the following. Assume the default stack area and
the register bank 0 is selected.
MOV R6, #25h
MOV R1, #12h
MOV R4, #0F3h
PUSH 6
PUSH 1
PUSH 4
Sol. After Push 6 After PUSH 1 After PUSH 4
Ex. 5 Show the Stack contents, SP contents & Contents of any register affected after each step of the
following sequence of operations.
MOV 81h, #70h
MOV R5, #30h
MOV A, #44h
ADD A, R5
MOV R4, A
PUSH 4
PUSH 5
POP 4
Sol. Since stack pointer is loaded with 70h, the stack memory starts from 71h onwards.
SP 70 70 00 70 00 70 00
R5 30 SP 71 74 71 74 SP 71 74
A 74 72 00 SP 72 30 72 30
R4 74 73 00 73 00 73 00
For every PUSH Instruction, the stack pointer gets incremented by 1, & in that internal RAM
content, the direct RAM address content gets stored. Thus, PUSH 4 stores 04h Content (74h)
56
on 71h & PUSH 5 stores 05h Content (30h) on 72h. The POP 4 will retrieve the 72h content
(30h) and moves to 04h content. After this, SP gets decremented by 1. Thus R4 will be 30h
The CPU can access data in various ways. The data could be in a register, or in a memory, or
be provided as an immediate value. These various ways of accessing data are called
addressing modes.
The 8051 microcontroller provides a total of five distinct addressing modes. They are as
follows:
i). Immediate
ii). Register
iii). Direct
iv). Register indirect
v). Indexed
2.5.1 Immediate Addressing Mode
In this addressing mode, the source operand is a constant. In immediate addressing mode, as
the name implies, the instruction is assembled, the operand comes immediately after the
opcode.
Ex: MOV A, #25h ;loads 25h into A
MOV DPTR, #25h ;DPTR = 00 25h
2.5.2 Register Addressing Mode
Register addressing mode involves the use of registers to hold the data to be manipulated.
Ex: MOV A, R0 ; copy the content of R into A
MOV R6, A ; Saves accumulator in R6
It should be noted that the source and the destination register size must match. For instance,
MOV A, DPTR is invalid since DPTR is 16 – bit and the accumulator is 8 – bit wide.
This addressing mode can move data between the accumulator and R registers, but
movement of data between R registers is not allowed. For Ex., the instruction MOV R1, R2
is invalid.
2.5.3 Direct Addressing mode
In this addressing mode, the data is there in a Internal RAM memory location whose address
57
is known and this address is given as a part of the instruction. Any internal RAM address or
SFR address can be given directly in the instruction.
Ex: MOV A, 40h ; Save the content of RAM loc 40h into A
MOV 0D0h, A ; Save the content of A in RAM Loc PSW.
Another major use of direct addressing mode is the stack. In the 8051 family, only direct
addressing mode is allowed for pushing onto the stack. Therefore, an instruction such as
“PUSH A” is invalid. Pushing the accumulator content onto the stack must be “PUSH
0E0h”.
2.5.4 Register indirect addressing mode
In the register addressing mode, a register is used as a pointer to the data. If the data is inside
the CPU, only registers R0 and R1 are used for this purpose. In other words, R2 – R7 cannot
be used to hold the address of an operand located in RAM using this addressing mode. When
R0 or R1 are used as a pointers, they must be preceded by the “@” sign as shown below.
Ex: MOV A, @R0 ; move the content of internal RAM location whose address is held by
R0 into A.
MOV 40h, @R1 move the content of internal RAM location whose address ; is held by
R0 into 40h
Also, the indirect addressing is the only way, for all External Memory access of data. In case
of External access of Data, the 16 – bit address must be made available in DPTR as below.
Ex: MOVX A, @DPTR ;Move the external RAM Content whose address is held by
DPTR into A
2.5.5 Indexed addressing mode
Indexed addressing mode is widely used in accessing data elements of look – up table entries
in the program ROM space of 8051 microcontroller.
Ex: MOVC A, @A+DPTR
MOVC A, @A+PC
The 16 – bit DPTR/PC and register A are used to form the address of the data element stored
in the on – chip ROM. Since the data element is stored in the code space (Program memory)
of 8051, it uses the MOVC instead of MOV (‘C’ represent Code space).
58
Module 2
3. Arithmetic instructions,
4. Logical instructions
59
5. Branch instructions
7. Subroutine instructions
8. Assembler Directives
1. Instruction Timings
The 8051 internal operations and external read/write operations are controlled by the oscillator clock
which runs by crystal connected between XTAL2 and XTAL1 pins of 8051.
Machine cycle is defined as 12 oscillator periods. A machine cycle consists of six states and each state
lasts for two oscillator periods. An instruction takes one to four machine cycles to execute an instruction.
Instruction cycle is defined as the time required for completing the execution of an instruction. The 8051
instruction cycle consumes one or two or four machine cycles.
Ex. If 8051 microcontroller is operated with 12 MHz oscillator, find the execution time for the following four
instructions.
1. ADD A, 45H ---------------1 mc
2. SUBB A, #55H ---------------1mc
3. MOV DPTR, #2000H--------2mc
4. MUL AB ----------------------4mc
*mc-machine cycle
Since the oscillator frequency is 12 MHz, Time for 1 machine cycle = 12/12 MHz =1 μS.
Total time consumed by above code is
=total number of machine cyclesX Period of 1mc
=8X1 μS.=8 μS.
8051 Instructions
60
The instructions of 8051 can be classified as,
1. Data transfer instructions
2. Arithmetic instructions
3. Logical instructions
4. Branch instructions
5. Subroutine instructions
6. Bit manipulation instructions
MOVX A,@R1
MOVX @R0,A
The above instructions are used to access 256 bytes(called as 1 page) of external memory
MOVX A,@DPTR
MOVX@DPTR,A
The above instructions are used to access entire 64Kb of external memory.
m. Move the contents of program memory to A
MOVC A, @A+PC
MOVC A, @A+DPTR
The MOVC instructions load the Accumulator with a code byte or constant from program
Memory. The address of the byte fetched is the sum of the original unsigned 8-bit Accumulator contents
and the contents of a 16-bit base register, which may be either the Data Pointer or the PC. No flags are
affected after execution.
*Ri-R0/R1
Rn-R0 to R7
VV-immediate 8 bit data
62
DD-direct address
VVVV-immediate 16 bit data
A stack is a last in first out memory. In 8051 internal RAM space can be used as stack. The address of the
stack is contained in a register called stack pointer. Instructions PUSH and POP are used for stack
operations. When a data is to be placed on the stack, the stack pointer increments before storing the data
on the stack so that the stack grows up as data is stored (pre-increment). As the data is retrieved from the
stack the byte is read from the stack, and then SP decrements to point the next available byte of stored
data (post decrement). The stack pointer is set to 07 when the 8051 resets. So that default stack memory
starts from address location 08 onwards (to avoid overwriting the default register bank ie., bank 0).
Eg; Show the stack and SP for the following
[SP]=07 //CONTENT OF SP IS 07 (DEFAULT VALUE)
MOV R6, #25H
MOV R1, #12H
MOV R4, #0F3H
PUSH 6
PUSH 1
PUSH 4
POP 6
POP 1
POP 4
63
2.3 Exchange instructions
The content of source ie., register, direct memory or indirect memory will be exchanged with the contents
of destination ie., accumulator.
XCH A,Rn ex: XCH A, R6=> exchanges the contents of Accumulator with R6
XCH A,@Ri ex: XCH A,
XCH A,DDh
k. Exchange digit. Exchange the lower order nibble of Accumulator (A0-A3) with lower order nibble of the
internal RAM location which is indirectly addressed by the register.
i. XCHD A,@R1
ii. XCHD A,@R0
64
3. Arithmetic instructions.
The 8051 can perform addition, subtraction. Multiplication and division operations on 8 bit unsigned
numbers.
3.1 Addition
In this group, we have instructions to
i. Add the contents of A with immediate data with or without carry: ADD A,#VV
i. ADD A, #45H
ii. ADDC A, #OB4H
ii. Add the contents of A with register Rn with or without carry.: ADD A, R5
i. ADD A, R5
ii. ADDC A, R2
iii. Add the contents of A with contents of memory with or without carry using direct and indirect
addressing : ADD A, DDH/ADD A,@Ri
i. ADD A, 51H
ii. ADDC A, 75H
iii. ADD A, @R1
iv. ADDC A, @R0
CY AC and OV flags will be affected by above operations.
Instruction: ADD A, R0
Number of bytes: 1 byte
Machine cycles: 1 cycle
Function: adds the content of R0 and accumulator, store the sum into accumulator.
Operation : A A+[R0]
Flags Affected: all flags are affected
Before execution: After Execution
R0=5Eh R0=5Eh
65
3.2 DA A (Decimal Adjust After Addition).
When two BCD numbers are added, the answer is a non-BCD number. To get the result in BCD, we use DA
A instruction after the addition. DA A works as follows.
If lower nibble (digit) is greater than 9 or auxiliary carry is 1, 6 is added to lower nibble.
If upper nibble(digit) is greater than 9 or carry is 1, 6 is added to upper nibble.
Number of bytes: 1 byte
Machine cycles: 1 cycle
Function: Decimal adjust after addition
Operation : if D0-D3 of Acc>9 or AF=1 A=A+06h
If D4-D7 of Acc>9 or CY=1 A=A+60h
Flags Affected: All flags CY,AC,OV and P are affected
1: MOV A,#23H
MOV R1,#55H
ADD A,R1 // [A]=78
DA A // [A]=78 no changes in the accumulator after da a
Eg 2: MOV A,#53H
MOV R1,#58H
ADD A,R1 // [A]=ABh
DA A // [A]=[A]+66H ->[A]=11, CY=1,AF=1,PF=1,OV=0 . ANSWER IS 111. Accumulator data is changed
after DA A
3.4 Subtraction
In this group, we have instructions to
i. Subtract the contents of A with immediate data with or without carry. SUBB A, #VV
i. SUBB A, #45H
ii. SUBB A, #OB4H
ii. Subtract the contents of A with register Rn with or without carry. SUBB A, Rn
i. SUBB A, R5
ii. SUBB A, R2
iii. Subtract the contents of A with contents of memory with or without carry using direct and indirect
addressing: SUBB A, DDh/ SUBB A, @Ri
i. SUBB A, 51H
ii. SUBB A, 75H
iii. SUBB A, @R1
iv. SUBB A, @R0
CY AC and OV flags will be affected by this operation.
Instruction: MUL AB
Number of bytes: 1 byte
Machine cycles: 4 cycles
Function: Multiply the contents of A and B store lower byte of product in A and higher byte in B.
Operation : A:B AXB
Flags Affected: all flags are affected
Before execution: After Execution
A=5Eh A=98h
B=F4h B=59h , flags: CY=0, P=1,OV=1(as product is > 8 bit)
67
DIV AB. This instruction divides the 8 bit unsigned number which is stored in A by the 8 bit unsigned
number which is stored in B register. After division the result will be stored in accumulator and
remainder will be stored in B register. Overflow flag is 1.
Instruction: DIV AB
Number of bytes: 1 byte
Machine cycles: 4 cycles
Function: Divide the contents of A by B store quotient in A and remainder in B.
Operation : A:B A/B
Flags Affected: all flags are affected
Before execution: After Execution
A=E8h A=08h
B=1Bh B=10h , flags: CY=0, P=1,OV=0
Note: to calculate remainder =dividend-(divisorXquotient)
68
ANL destination, source: ANL does a bitwise "AND" operation between source and destination, leaving the
resulting value in destination. The value in source is not affected. "AND" instruction logically AND the bits
of source and destination.
ANL A,#VVh
ANL A, Rn
ANL A,DDh
ANL A,@Ri
ANL DDh,A
ANL DDh, #VVh
Logical Ex-OR
XRL destination, source: XRL does a bitwise "EX-OR" operation between source and destination, leaving
the resulting value in destination. The value in source is not affected. " XRL " instruction logically EX-OR
the bits of source and destination.
XRL A,#DATA XRL A,Rn
XRL A,DIRECT XRL A,@Ri
XRL DIRECT,A XRL DIRECT, #DATA
Sample explanation
Instruction: XRL 40h,#0fh
Number of bytes: 1 byte
Machine cycles: 2 cycles
Function: Exor the contents of memory location with immediate value store the result in memory location
Operation :
Flags Affected: all flags are affected
Before execution: After Execution
M[40h]=5Eh M[40h]=51h
Logical NOT
CPL complements operand, leaving the result in operand. If operand is a single bit then the state of the bit
will be reversed. If operand is the Accumulator then all the bits in the Accumulator will be reversed.
CPL A
69
ORL destination, source: ORL does a bitwise "OR" operation between source and destination, leaving the
resulting value in destination. The value in source is not affected. " OR " instruction logically OR the bits of
source and destination.
ORL A,#VV
ORL A, Rn
ORL A,DDH
ORL A,@Ri
ORL DDh,A
ORL DDh, #VV
SWAP A – Swap the upper nibble and lower nibble of A. The swap instruction works only with
Accumulator. It swaps the lower nibble and the upper nibble of accumulator.
Rotate Instructions
RR A
This instruction is rotate right the accumulator. Its operation is illustrated below. Each bit is shifted one
location to the right, with bit 0 going to bit 7.
RL A
Rotate left the accumulator. Each bit is shifted one location to the left, with bit 7 going to bit 0
RRC A
Rotate right through the carry. Each bit is shifted one location to the right, with bit 0 going into the carry
bit in the PSW, while the carry was at goes into bit 7
RLC A
70
Rotate left through the carry. Each bit is shifted one location to the left, with bit 7 going into the carry bit
in the PSW, while the carry goes into bit 0.
Sample explanation
Instruction: RL A
Number of bytes: 1 byte
Machine cycles: 1 cycle
Function: Rotate the accumulator Left by 1 bit
Operation : D0<-D7 and D7:D1<-D6:D0
Flags Affected: no flags are affected
Before execution: After Execution
A=10h A=20h
71
5. Branch (JUMP) Instructions
Jump and Call Program Range
There are 3 types of jump instructions. They are:-
1. Relative Jump
2. Short Absolute Jump
3. Long Absolute Jump
Relative Jump
Jump that replaces the PC (program counter) content with a new address by adding relative address to
the PC. Reladdr must be within -128 (for back ward jump) or +127 bytes of the instruction(for forward
jump) that follows the SJMP instruction
The advantages of the relative jump are as follows:-
1. Only 1 byte of jump address needs to be specified in the 2's complement form, ie. For jumping ahead,
the range is 0 to 127 and for jumping back, the range is -1 to -128.
2. Specifying only one byte reduces the size of the instruction and speeds up program execution.
Disadvantages of the absolute jump: -
2. Short jump range (-128 to 127 from the instruction following the jump instruction)
72
Instruction: JBC bit, <relative address>
Number of bytes: 3 bytes
Machine cycles: 2 cycles
Function: If bit=1 jump to location clear the bit before jumping to the location
If bit=0 resume with next instruction
Operation : if bit=1 PC<- PC+3
PC PC+reladds
Bit=0
If bit=0 PC<- PC+3
Flags Affected: no flags are affected
Before execution: After Execution
0040h: jbc 00h,02h
0043h:------- PC0045h
Performs jump to the location 0045h
0045h: --------
This is long call instruction which unconditionally calls the subroutine located at the indicated 16 bit
address. This is a 3 byte instruction. The LCALL instruction works as follows.
a. During execution of LCALL, [PC] = [PC]+3;
b. [SP]=[SP]+1; increment the stack pointer by 1
c. [[SP]]; = [PC7-0]; store the lower byte of return address ( ie lower byte of PC) onto the stack
d. [SP]=[SP]+1; increment the stack pointer by 1
e. [SP]] = [PC15-8]; store the higher byte of return address ( ie lower byte of PC) onto the stack
f. [PC]= address (16 bit); the new address of subroutine is loaded to PC. No flags are affected.
2. ACALL address11
This is absolute call instruction which unconditionally calls the subroutine located at the indicated 11 bit
address. This is a 2 byte instruction. The SCALL instruction works as follows.
a. During execution of LCALL, [PC] = [PC]+3;
b. [SP]=[SP]+1; increment the stack pointer by 1
c. [[SP]] = [PC7-0]; store the lower byte of return address ( ie lower byte of PC) onto the stack
d. [SP]=[SP]+1; increment the stack pointer by 1
e. [[SP]] = [PC15-8]; store the higher byte of return address ( ie lower byte of PC) onto the stack
f. [PC10:PC0]=addr11, 11 bit absolute address the new address of subroutine is loaded to PC. No flags are
affected
76
RET instruction
RET instruction pops top two contents from the stack and load it to PC.
g. [PC15-8] = [[SP]] ;content of current top of the stack(higher byte of return address) will be moved to
higher byte of PC.
h. [SP]=[SP]-1; (SP decrements)
i. [PC7-0] = [[SP]] ;content of bottom of the stack(lower byte of return address) will be moved to lower
byte of PC.
j. [SP]=[SP]-1; (SP decrements again)
Briefly explain the different assembler directives used in an Assembly language program
June 2012-04M
8. Assembler Directives
The assembler directives instruct the assembler on how to process subsequent assembly language
instructions. Each assembler uses various directives. This does not create any machine code like
ALP does. The most common assembler directives are listed as follows
i). ORG
ii). END
iii). EQU
iv). DB
i). ORG (origin): the ORG directive is used to indicate the beginning address of a program segment
or a program itself. The number after ORG can be hex or in decimal.
Ex: ORG 00h ; this directive tells the CPU that the machine codes of the following instructions are
stored in ROM space from address 0000h.
ii). END: This directive indicates to the assembler the end of the source (ASM) file. Anything after
this directive is ignored by the assembler.
iii). EQU (Equate): This directive is used to define constant, without occupying a memory location.
It equates a constant with a data name, and where ever the name is used in the program, its
constant value is substituted.
For Ex.
77
N equ 10
………….
MOV R2, #N will move R2 with a value of 0Ah.
iv). DB (Define byte): This directive is used to define the 8 – bit data. When DB is used to define
data, we can use decimal, binary, hex or ASCII formats. For a decimal number “D” after the number
is optional; a binary number is indicated by a “B” at the end of the number, “H” for hexa decimal
number. To indicate ASCII format, the characters are placed in quotation marks
Ex:
ORG 30h
data1: DB 16 ; Decimal
data2: DB 16h ; hexa format
data3: DB 0010b ; binary format
data4: DB “16” ; ASCII Format
78
79
Instruction sets of 8051
Arithmatic Operations
NO. OF
PCODE OPERAND DESCRIPTION
BYTES
ADD A,Rn Add register to Accumulator 1
ADD A,direct Add direct byte to Accumulator 2
ADD A,@Ri Add indirect RAM to Accumulator 1
ADD A,#data Add immediate data to Accumulator 2
80
Add register to Accumulator with
ADDC A,Rn 1
Carry
Add direct byte to Accumulator with
ADDC A,direct 2
Carry
Add indirect RAM to Accumulator
ADDC A,@Ri 1
with Carry
ADDC A,#data Add immediate data to Acc with Carry 2
Subtract Register from Acc with
SUBB A,Rn 1
borrow
Subtract direct byte from Acc with
SUBB A,direct 2
borrow
Subtract indirect RAM from ACC
SUBB A,@Ri 1
with borrow
Subtract immediate data from Acc
SUBB A,#data 2
with borrow
INC A Increment Accumulator 1
INC Rn Increment register 1
INC direct Increment direct byte 2
INC @Ri Increment direct RAM 1
DEC A Decrement Accumulator 1
DEC Rn Decrement Register 1
DEC direct Decrement direct byte 2
DEC @Ri Decrement indirect RAM 1
INC DPTR Increment Data Pointer 1
MUL AB Multiply A & B 1
DIV AB Divide A by B 1
DA A Decimal Adjust Accumulator 1
LOGICAL OPERATIONS
PROGRAM BRANCHING
84
JNC SKIP
INC R1
SKIP: INC DPTR
DJNZ R7, RPT
MOVX @DPTR, A
MOV A, R1
INC DPTR
MOVX @DPTR, A
SJMP $
15. Write an ALP to add N – 8 bit nos. available from memory location START. Display the result at Port 0 and Port 1
Jun 2011-08M
Let N = 5 eight bit numbers are stored from internal RAM loc. 20h (START) onwards.
MOV R7, #N
MOV R0, #START
MOV R2, #00
BACK: ADD A, @R0
JNC SKIP
INC R2
SKIP: INC R0
DJNZ R7, BACK
MOV P0, A
MOV P1, R2
SJMP $
16. Write a program segment to realize the following:
i). Exchange contents of external data memory 8100h with contents of internal data memory 40h
ii). Exchange contents of A – reg and B – reg using stack. Dec 2012-06M
Sol:
i). Exchange contents of External RAM to Internal Ram ii). Exchange contents of A and B Register using stack
MOV DPTR, #8100h PUSH 0E0h
MOV R0, #40h PUSH 0F0h
MOVX A, @DPTR POP 0E0h
MOV 30h, @R0 POP 0F0h
MOV @R0, A SJMP $
MOV A, 30h
MOVX @DPTR, A
SJMP $
17. Write an 8051 ALP which checks whether the 10 nos. stored from external RAM memory address, 2000h are odd/even. The program
should store accordingly 00/FFh from internal RAM loc. 30h onwards June 2013-10M
The 8 – bit binary number can be odd if the LSB is 1, even if the LSB is 0.
For ex. Consider the 8 – bit number as DA h: the LSB is 0, so the given no is even and so on.
MOV DPTR, #2000h
MOV R0, #30h
MOV R7, #10
RPT: MOVX A, @DPTR
JNB 0E7h, EVE
ODD: MOV @R0, #00
SJMP SKIP
EVE: MOV @R0, #0FFh
SKIP: INC R0
INC DPTR
DJNZ R7, RPT
SJMP $
18. Write a subroutine which checks the content of 20h. If it is a positive number, the subroutine finds its 2’s complement and stores it in
same location and returns. June 2013-05M
The 8 – bit number can be a positive number, if its MSB is 0, negative number if the MSB is 1.
85
For instance, if the number is say, 7A h, the number is a positive number since the MSB is 0.
POSIT: MOV A, 20h
JB 0E7hLAST
CPL A
INC A
MOV 20h, A
LAST: RET
19. Write an ALP in 8051 to count the number of positive and negative numbers present in the internal memory block starting with the
address 20h containing N – bytes. Store the count after the last byte in the memory block.
June 2012-06M
MOV R7, #N
MOV R0, #20h
MOV R1, #0 ; for counting positive numbers
MOV R2, #0 ; for counting negative numbers
RPT: MOV A, @R0
JB 0E7h, NEG
POS: INC R1
SJMP SKIP
NEG: INC R2
SKIP: INC R0
DJNZ R7, RPT
MOV @R0, 1
INC R0
MOV @R0, 2
SJMP $
20. Write an ALP to find the average of 10 numbers stored at external data memory starting at 1000h. Store the result at the end of the
array 08M
MOV DPTR, #1000h
MOV R7, #10
MOV R0, #00
MOV 0F0h, R7
RPT: MOVX A, @DPTR
ADD A, R0
MOV R0, A
INC DPTR
DJNZ R7, RPT
DIV AB
MOVX @DPTR, A
END
21. Write a delay program to generate a delay of 10ms. Assume crystal frequency of 11.0592MHz. show delay calculations
Dec 2012-06M
Since the crystal frequency is 11.0592MHz, 1 Machine cycle = 1.085µs. So, to create a delay of 10ms, the WAIT loop should be executed
10 m 200 µ
for = 200µ. To create a delay of 200µs, the value to be loaded in R1 is = 92
50 2∗1.085 µ
Delay: MOV R2, #50
RPT: MOV R1, #92
WAIT: DJNZ R1, WAIT
DJNZ R2, RPT
RET
22. Write an 8051 assembly time delay subroutine to generate a time delay of 100µs when called. Assume crystal frequency is 12MHz.
Show delay calculations. Do not use timers. Dec 2013-06M
Since the crystal frequency is 12MHz, 1 machine cycle = 1µs. DJNZ instruction is a 2 machine cycle instruction, so if R2 is loaded with 50,
DJNZ r2, $ will execute for 100µs.
DELAY: MOV R2, #50
86
DJNZ R2, $ ; 2 Machine Cycle Instructions repeating for 50 times
RET
23. A 4 – bit number N is available in internal RAM location 40h. write an ALP to compute 1 + 2 + 3 + … + N and store the 8 – bit result in
41h 06M
MOV A, 40h
MOV R0, A
DEC R0
BACK: ADD A, R0
DJNZ R0, BACK
MOV 41h, A
SJMP $
24. Write an ALP to count the number of 1’s and 0’s of an 8 – bit data stored in RAM loc 6000h. Store the 1’s count in 6001h and 0’s count
in 6002h. 06M
MOV DPTR, #6000h
MOVX A, @DPTR
MOV R7, #8
MOV R1, #00
MOV R2, #00
BACK: RLC A
JC SKIP
INC R1
SJMP LAST
SKIP: INC R2
LAST: DJNZ R7, BACK
MOV A, R1
INC DPTR
MOVX @DPTR, A
MOV A, R2
INC DPTR
MOVX @DPTR, A
SJMP $
END
Module – 3
8051 Timers/Counters:
Timers/Counters of 8051 Microcontroller............................................................................2
Basic registers of Timer........................................................................................................2
Timer – 0 registers....................................................................................................................2
87
Timer – 1 registers....................................................................................................................2
TMOD (Timer Mode) register...................................................................................................2
TCON (Timer Control) register..................................................................................................5
Mode 1 programming............................................................................................................6
Mode 2 programming..........................................................................................................12
Counter Programming.........................................................................................................18
C/𝑇 bit in TMOD register.......................................................................................................19
Mode 1 Counter programming............................................................................................19
Serial port Programming of 8051........................................................................................21
RxD and TxD pins in the 8051.................................................................................................22
SBUF register..........................................................................................................................22
SCON register (98h*)..............................................................................................................22
Setting the Baud rate..............................................................................................................24
3. 7. 5 Programming the 8051 to transfer data serially.....................................................25
88
3.1. Timers/Counters of 8051 Microcontroller
The 8051 microcontroller has two Timers/Counters, named Timer 0 (T0) and Timer 1 (T1). They
can be used either as timers to generate a required time delay or as a counter operation to count
external events happening. To operate these timers, knowledge about timer related SFRs are
necessary.
The 16 – bit registers of timer 0 is accessed as low byte and high byte. The low byte is called TL0
(Timer 0 low byte) and the high byte register is referred to as TH0 (Timer 0 high byte). These
registers can be accessed like any other registers with the help of MOV instruction with the help
of its direct SFR addresses.
3.2.2 Timer – 1 registers
Timer 1 is also 16 – bits, and its 16 – bit register is split into two bytes, referred to as TL1 (Timer 1
low byte) and TH1 (Timer 1 high byte). The timer registers for both timers are shown in Fig. 3.1
and 3.2.
3.2.3 TMOD (Timer Mode) register
Both timers (Timer 0 and Timer1) use the same register, called TMOD (Timer mode) register to
89
set the timer in various modes of operation. TMOD, as shown in Fig 3.3, is an 8 – bit register, in
which lower 4 – bits are set aside for Timer 0 and the upper 4 bits for Timer 1. In each case, the
lower 2 bits are used to set the timer mode and the upper 2 bits to specify the operations. This SFR
is accessed with the help of the byte address 89h.
MSB LSB
G C/T M1 M0 G C/T M1 M0
Timer 1 Timer 0
M1 & M0 Mode bits 1 & 0. The Timer/Counter can be put in various modes of operation as
mentioned below
M1 M0 Mode Description
90
Ex. 3.1 Find the values of TMOD to operate as timers in the following modes:
i). Mode 1 Timer 1
ii). Mode 2 Timer 0, Mode 1 Counter 1
iii). Mode 0 Timer 1
Sol: From Fig. 3.3,
i). TMOD is 0001 0000b = 10h.
ii). TMOD is 0101 0010b = 52h.
iii). TMOD is 0000 0000b = 00h.
C/T̅ (Counter/T̅̅̅ı̅m̅̅̅e̅r̅):
generator or an event counter. If C/𝑇̅ = 0, it is used as a timer for delay generation. The
This bit in the TMOD register is used to decide whether the timer is used as a delay
clock source for the time delay is the crystal frequency of the 8051.
Clock source for Timer:
Every timer needs a clock pulse to tick (increment). The source of the clock for the
timer operation (C/𝑇̅ = 0), is the crystal (XTAL) attached to 8051. This means that
the size of the crystal frequency decides the speed at which the 8051 timer ticks.
The
1 th
12
frequency of the timer is always of the frequency of the crystal attached to the
8051.
Timer
XTAL Frequency
Oscillator ÷ 12
Ex. 3.2 Find the timer’s clock frequency and its period for the various 8051 based
systems, with the following XTAL frequencies.
i). 12 MHz ii). 16 MHz iii). 11.0592 MHz
1 1
12 12
Sol: i). Timer Frequency = * XTAL = * 12 MHz= 1 MHz
1
𝑇i𝑚𝑒𝑟 𝐹𝑟𝑒𝑞𝑢
So, Timer period (or) Timer Cycle (or) Machine cycle = = 1 µs.
91
ii). For XTAL as 16 MHz,
Timer Freq = 1.33MHz & Timer Cycle = 0.75 µs
iii). For XTAL = 11.0592 MHz
Timer Freq = 921.6kHz & Timer Cycle = 1.085 µs
Gate:
The other bit of the TMOD register is the Gate (G) bit. Notice in the TMOD register of
Fig. 3.3 that both Timers 0 & 1 have gate bit. The purpose of this bit is explained
below:
Every timer has a means of starting and stopping. Some timers do this by software,
some by hardware, and some have both software and hardware controls. The timers in
the 8051 have both. The start and stop of the timer are controlled by way of software by
the Timer Run (TRX) bits (TR0 for Timer 0 and TR1 for Timer 1). So for starting the
timers with the help of only TRX pins are achieved by putting the Gate pin to ‘0’. This
way is referred as software control of timers. The hardware way of starting and
stopping the timers by an external source or with the help of a switch is achieved by
making Gate pin to ‘1’.
The bit pattern of Timer control register is shown in Fig. 3.4. Notice that, only the upper
nibble of TCON register have bits needed for timer operations. The Byte address of TCON
register is 88h. This register is a bit addressable SFR.
MSB LSB
92
TF1 for Timer 1. The details of the bit pattern of TCON are shown below.
XTAL
Oscillator ÷ 12
TH TL TF
93
Steps to program in Mode 1:
To generate a time delay, using the timer’s mode 1, the following steps are taken.
1. Load the TMOD register indicating which timer (Timer 0 or Timer 1) is to be used
and timer in mode 1 is selected.
2. The 16 – bit initial values are loaded in TH and TL registers.
3. Start the timer, by making the timer run bit (TR) to 1.
4. Keep on monitoring the timer flag (TF) with JNB TFX, $ instruction, to see if it is
raised. Get out of the loop when TF becomes high.
5. Stop the timer and clear the timer flag bit.
6. Go back to step 2, to reload the Timer registers and repeat the process.
Ex. 3.3 Write an 8051 ALP to generate a square wave of 2 kHz frequency on Port pin P2.3.
Assume XTAL = 12 MHz. Use Timer0 in Mode 1 of operation.
Sol: Given XTAL = 12MHz.
1
⟹1 Machine cycle = 1
K𝑇𝐴𝐿
1 Machine cycle = * 12
12
* 12 = 1µs.
𝑀
Timer 0 in Mode 1:
TMOD = 0000 0001 b = 01h
250µs
250µs
94
MOV TMOD, #01h ;Timer 0 in Mode 1
Back: MOV TH0, #0FFh ; The 16 – bit initial values are loaded in Timer registers
MOV TL0, #06h
ACALL Delay
CPL P2.3 ;Complement Port pin P2.3
SJMP Back
Ex. 3.4 Assuming that XTAL = 11.0592 MHz, what 16 – bit value need to be loaded into
timer registers to have a delay of 5ms. Also write an 8051 ALP for Timer 1 to
create a pulse width of 5ms on P1.5
Sol: Given XTAL = 11.0592 MHz
⟹1 Machine cycle = 1
* 12 = 1.085µs.
Timer 1 in Mode 1:
TMOD = 0001 0000 b = 10h
The timer 1 in mode 1 should be configured to produce a delay of 5ms.
5𝑚
1.085
The number of timer cycles required to generate 5ms = = 4608 timer cycles.
µ
95
ACALL Delay
CPL P1.5 ;Complement Port pin P1.5
SJMP Back
Ex. 3.5 Generate a square wave with an ON time of 3ms and an OFF time of 10ms on all
pins of port 0. Assume XTAL = 22 MHz. Use Timer 0 in Mode 1 operation.
3ms 10ms
All Bits of P0
Timer 0 in Mode 1:
TMOD = 0000 0001 b = 01h
On Time calculations: Off Time calculations:
Delay required = 3ms Delay required = 10ms
3𝑚 10𝑚
0.545µ
Timer cycles required = = 5505cycles
0.545µ
Timer cycles required = = 22026cycles
96
MOV P0, #00h ;Make all bits of P0 as Low.
ACALL Delay
MOV TH0, #0EAh ;To generate ON Time, load EA 7Fh in timer registers.
MOV TL0, #7Fh
MOV P0, #0FFh ; Make all bits of P0 as high.
ACALL Delay
SJMP Back ;Repeat for reloading to get continuous square wave.
Sol: To produce Maximum delay in mode 1 timer operation, the 16 – bit initial value to be
loaded in timer registers be all zeros. i.e., 00 00h
The timer spends 65, 536 timer cycles (2^16) to overflow producing maximum delay
Sl. No XTAL Timer cycle Max. Delay
1. 8MHz 1.5µs 1.5µs * 65536 ≅ 98ms
2. 11.0592MHz 1.085µs 1.085µs * 65536 ≅ 71ms
3. 22MHz 0.545µs 0.545µs * 65536 ≅ 36ms
Ex. 3.7 Assuming XTAL = 22 MHz, write a program to generate a pulse train of 2 seconds on
pin P2.4. Use Timer 1 in mode 1.
Sol: Given XTAL = 22 MHz
97
⟹1 Machine cycle = 1
22𝑀
* 12 = 0.545µs.
98
Timer 1 in Mode 1:
TMOD = 0001 0000 b = 10h
For a time period of 2 seconds, the
1 Sec
1 Sec
half period should be 1 second. From
Ex. 3.6, it is quite clear that the P2.4
99
3.4 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 00h 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. Once the timer is started, it start to count up by incrementing the TL register. It
counts up until it reaches it limit of FFh. When it rolls over from FFh to 00h, it sets
high the TF flag.
4. When the TL register rolls from FFh to 00h, and TF is set to 1, TL is reloaded
automatically with its original value kept in TH register. To repeat the process, one
must clear the TF flag, and let it go without the need of programmer to reload the
initial value.
This makes mode – 2 an auto reload, in contrast with mode 1 in which the programmer
has to reload TH and TL registers.
XTAL
÷ 12
Oscillator TL TF
Reload
C/T = 0 TF goes high
TR
TH when FFh 00h
10
0
5. Clear the TF flag
6. Go back to step 4, since mode 2 is auto reloaded.
Ex. 3.8 Assuming that XTAL is 22 MHz, write a program to generate a square wave of
frequency 5 kHz on pin P1.2. Use timer 1 in mode 2.
Sol: Given XTAL = 22MHz.
⟹ 1 Machine cycle = 1 1
K𝑇𝐴𝐿
1 Machine cycle = * 12
22𝑀
* 12 =
0.545µs.
Timer 1 in Mode 2:
TMOD = 0010 0000 b = 20h
100µs
100µs
To produce a square wave of 5kHz,
assuming 50% duty cycle on pin P1.2
1 P1.2
5 𝑘𝐻𝑧
TTot = = 200µs
So, - 183d should be loaded in TH1 register. The assembler will convert the negative value
to its appropriate 8 – bit value and loads into TH1.
MOV TMOD, #20h ; Timer 1 in mode 2
MOV TH1, # - 183 ;Load the initial value in TH1
SETB TR1 ; Start timer 1
Back: ACALL Delay
CPL P1.2
SJMP Back ; Repeat to get continuous square wave.
Delay: JNB TF1, Delay ;Wait till timer overflows, after 183 cycles, TF1 = 1
CLR TF1 ; Clear the overflow flag
RET
10
1
Ex. 3.9 Assuming that timers are in mode 2 operation, find the value (in hex) loaded into
TH for each of the following cases
i). MOV TH1, # -200 ii). MOV TH0, # -60 iii). MOV TH1, # -3
Sol: Enter -200 in decimal mode and select hex, to get the 2’s complement value. Also
remember to take least 2 hex digits, since mode 2 is an 8 – bit timer operation.
i) -200d = 38h
ii) -60d = C4h
iii). -3d = FDh.
Sol: To produce Maximum delay in mode 2 timer operation, the 8 – bit initial value to be
loaded in timer registers be all zeros. i.e., 00h
The timer spends 256 timer cycles (2^8) to overflow producing maximum delay
Sl. No XTAL Timer cycle Max. Delay
1. 8MHz 1.5µs 1.5µs * 256 = 384µs
2. 11.0592MHz 1.085µs 1.085µs * 256 ≅ 278µs
3. 22MHz 0.545µs 0.545µs * 256 ≅ 140µs
Ex. 3.11 Assuming XTAL = 11.0592 MHz, write a program to generate a pulse train of 2 seconds
on pin P2.4. Use Timer 1 in mode 2.
Sol: Given XTAL = 11.0592 MHz
⟹1 Machine cycle = 1
11.0592𝑀
* 12 = 1.085µs.
Timer 1 in Mode 2:
TMOD = 0010 0000 b = 20h
For a time period of 2 seconds, the half period should be 1 second. From Ex. 3.10, it is quite
clear that the maximum delay possible using mode 2 timer with XTAL of 11.0592 MHz is
10
2
277µs, which is very less than the requires amount of 1 sec delay.
So, configure a delay of lesser than the max. delay, say 250µs, and repeat this delay for ‘n’ times
10
3
to get the required amount of 1 sec.
1 sec = 250µs * n
⟹ n = 4000
Since, 4000 is > 8 – bits, this can be as a product of two 8 – bit numbers as follows:
4000 = 250 * 16
For a Delay of 250 µs:
250µ
1.085µ
Timer cycles required = = 230cycles
Delay: JNB TF1, $ ;Wait till Timer 1 overflows, thereby producing 250µs
CLR TF1 ;Reset the timer 1 Flag bit
RET
10
4
CLR TF1
SJMP Back
Sol: i). Based on the value available in TH1, the timer spends 251 timer cycles before rolls
over, producing a delay of 251 * 1.085µ = 272µs.
So, TON = TOFF = 272µs. TTOT
= 272µ + 272µ = 544µs
1
544
The frequency of the square wave on pin P1.0 is = 1.83 kHz.
µ
ii). To get the smallest frequency possible, the delay should be of maximum. This can
be achieved by loading 00h in TH1 register as the initial value.
In this case, TON = TOFF = 256 * 1.085µ = 277.5µs. TTOT
= 277.5µ + 277.5µ = 555µs.
1
555
The frequency of the square wave on pin P1.0 is = 1.80 kHz.
µ
Ex. 3.13 Write an ALP to read input from port 1, complement it and output via port 2. Transfer
should be done once in 50ms, use timer 0 for delay generation and assume XTAL =
11.0592 MHz
Sol: Given XTAL = 11.0592 MHz
⟹1 Machine cycle = 1
11.0592𝑀
* 12 = 1.085µs.
TH0 TL0
hex
- 46083d 4B FD h
MOV TMOD, #01h ; Timer 0 in mode 1
MOV P0, #0FFh ;P0 as Input port
Back: MOV TH0, #4Bh ; 16 – bit initial value loaded in timer registers
MOV TL0, #0FDh
ACALL Delay
10
5
MOV A, P1 ; Read port 1 and move to Acc
CPL A ; Complement A
MOV P2, A ; Output via port 2
SJMP Back ; go for next byte transfer.
Ex. 3.14 A switch ‘SW’ is connected to pin P1.2. Write an 8051 ALP to monitor the switch and
create the following frequencies on P1.7
i. When ‘SW’ = 0; F = 500 Hz
ii. When ‘SW’ = 1; F = 750 Hz.
Use timer 0, mode 1 for both of them. Assume XTAL = 11.0592 MHz.
Sol: Given XTAL = 11.0592 MHz
⟹1 Machine cycle = 1
11.0592𝑀
* 12 = 1.085µs.
So, the pin P1.7 should be complemented So, the pin P1.7 should be complemented
forever for 1ms once. forever for 0.667ms once.
1𝑚
Timer cycles for 1ms = 0.667𝑚 = 615cycles
1.085µ 1.085µ
Timer cycles for 1ms = = 922cycles
10
6
MOV TMOD, #01h ; Timer 0 mode 1
SETB P1.2 ; Make Port P1.2 as input pin
Back: JNB P1.2, Fre_500Hz ; Read the switch position
Fre_750Hz: MOV TH0, # 0FDh ; Load the 16 – bit initial value for 750Hz
MOV TL0, # 99h
ACALL Delay
SJMP Last
Fre_500Hz: MOV TH0, # 0FCh ; Load the 16 – bit initial value for 500Hz
MOV TL0, # 66h
ACALL Delay
Last: CPL P1.7
SJMP Back ; Go back to check the status of the switch.
10
7
C/T̅ bit in TMOD register
Recall from the last section, that the C/𝑇̅ bit in the TMOD register decides the source
If C/𝑇̅ = 0, Timer mode, the timer gets pulses from the crystal connected to the 8051.
of the clock for the timer.
If C/𝑇̅ = 1, Counter mode, the timer gets pulses from outside the 8051.
∴, when C/𝑇̅ = 1, the counter counts up as pulses are fed from pins 14th and 15th of the 40 –
pin DIP. These pins are called T0 (Timer 0 input) and T1 (Timer 1 input). Notice these pins
belong to port 3. In the case of Timer 0, when C/𝑇̅ = 1, pin P3.4 provides the clock pulse and
the counter counts up for each of the clock pulse coming from that pin. Similarly, for timer 1,
when C/𝑇̅ = 1, each clock pulse coming in from pin P3.5 makes the counter to count up.
Port 3 pins used for Timers 0 and 1
Pin Port Pin Function Description
14 P3.4 T0 Timer/Counter 0 External input
15 P3.5 T1 Timer/Counter 1 External input
MSB LSB
G C/T M1 M0 G C/T M1 M0
Timer 1 Timer 0
10
8
Overflow Flag Overflow Flag
Timer 0 External input Timer 1 External input
P3.4 TH0 TL0 TF0 P3.5 TH1 TL1 TF1
C/T = 1
C/T = 1
TR0 TR1
a). Timer 0 with external input b). Timer 1 with external input
ORG 0000h
RPT: MOV TMOD, #15h ;Timer 0 as counter and Timer 1 as timer for 1 sec delay gen.
SETB P3.4 ; make P3.4 as input port.
MOV TL0, # 00h ;set the 16 – bit initial values in Timer 0 registers as 00 00h
MOV TH0, # 00h
SETB TR0 ;Start the Timer 0(Counter operation)
10
9
MOV R0, # 40
Again: MOV TL1, # 0D0h ; Initialize the 16 – bit value in timer registers.
MOV TH1, # 4Ch
SETB TR1 ;Start timer 1
Wait: JNB TF1, $ ;Wait till timer 1 overflows producing 25ms delay
CLR TR1 ;Stop timer 1
CLR TF1 ;Clear timer 1 overflow flag
DJNZ R0, Again ;Repeat 25ms delay for 40 times.
MOV A, TL0
MOV P2, A ;Move TL0 to P2 and TH0 to P1 which is connected to some
MOV A, TH0 ;output devices
MOV P1, A
SJMP RPT ;Repeat this process
END
11
0
3.7.1 RxD and TxD pins in the 8051
The 8051 has 2 pins that are used specially for transferring and receiving data serially. These two
pins are called TxD and RxD and are part of port 3 group (P3.0 and P3.1). Pins 11 of the 8051
(P3.1) is assigned to TxD and pin 10 (P3.0) is designated as RxD.
3.7.2 SBUF register
SBUF is an 8 – bit register used only for serial communication in the 8051. For a byte of data to
be transferred via TxD pin, it must be placed in SBUF. Similarly, SBUF holds the byte of the
data when it is received by the RxD pin of 8051. The moment a byte is placed in SBUF, it is
framed with the start bit before D0 bit and stop bit after D7 bit of the data and transferred serially
via TxD pin. Similarly, when bits are received serially via RxD pin, the 8051 de frames it by
eliminating the start and stop bits, and then places the received byte in SBUF
3.7.3 SCON register (98h*)
Fig 3.14 shows the SCON SFR, which is at the address 98h (a bit addressable SFR).
11
1
SM0, SM1
SM0 and SM1 are D7 and D6 bits of the SCON register, respectively. These bits determine the
framing of data by specifying the number of bits per character, and the start and stop bits. They
take the following combinations:
More importantly, serial mode 1 allows the baud rate to be variable and is set by the timer 1 of
the 8051. In serial mode 1, for each character a total of 10 bits are transferred, where the first bit
is the start bit, followed by 8 bits of data and finally 1 stop bit.
SM2
SM2 is the D5 bit of SCON register. This bit enables the multiprocessor capability of the 8051
and for our discussion, set SM2 as ‘0’.
REN
The REN (receive enable) bit is D4 of the SCON register. The REN bit is also referred to as
SCON.4 since SCON is a bit addressable SFR.
when REN = 1: UART is enabled
11
2
when REN = 0; UART is disabled.
So, by making REN as 1, 8051 can transfer and receive data serially via, TxD and RxD pins.
TB8 and RB8
TB8 (Transfer bit) and RB8 (Receive bit) are D3 and D2 bits of SCON register. We make these
bits as ‘0’, since it is used for serial modes 2 and 3.
TI
TI (Transmit interrupt) is the D1 bit of SCON register. This is an extremely important flag bit in
the SCON register. When the 8051 finishes the transfer of the 8 – bit character, it raises the TI
flag to indicate that UART is ready to transfer next character. The TI is raised by 8051 at the
beginning of the stop bit.
RI
RI (Receive interrupt) is the D0 bit of SCON register. This is another extremely important flag
bit in the SCON register. When the 8051 receives data serially via RxD, it get rid of start and
stop bits and places the byte in SBUF register. Then it raises the RI flag to indicate that a byte is
received serially. The RI is raised by 8051 at the halfway through the stop bit.
3.7.4 Setting the Baud 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.
The 8051 transfers and receives data serially at many different baud rates. The baud rate in serial
mode 1 is variable and can be set by timer 1 in mode 2 operation.
As shown in fig 3.16, the 8051 divides the crystal frequency by 12 to get the machine cycle
frequency. In the case of XTAL as 11.0592 MHz, the machine cycle frequency is 921.6 kHz. The
8051 serial communication UART circuitry divides the machine cycle frequency by 32 before
given to timer 1 to set the baud rate. Therefore, 921.6 kHz divided by 32 gives 28, 800 Hz. This
frequency can be divided by a value to get compatible baud rates. For instance, if 9600 baud rate
is needed, -3d should be loaded to TH1meaning dividing the UART frequency by 3 times.
11
3
Baud Rate TH1 (decimal) TH1 (Hex)
9600 -3 FD
4800 -6 FA
2400 -12 F4
1200 -24 E8
Ex. 3.15 With XTAL = 11.0592 MHz, find the TH1 value
needed to have the following baud rates.
a). 9600 b). 4800 c). 2400
Sol: With XTAL = 11.0592 MHz,
⇒ Machine cycle frequency = K𝑇𝐴𝐿
= 11.0592𝑀 = 921.6 kHz
12 12
In programming the 8051 to transfer character bytes serially, the following steps must be taken
1. The TMOD register is loaded with the value 20h, indicating the use of Timer in mode 2
(8 – bit auto reload) for setting the baud rate.
2. The TH1 is loaded with the one of the values in the above table to set the baud rate for
serial data transfer.
3. The SCON is loaded with 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. The character byte to be transferred serially is placed in SBUF register.
6. The TI flag is monitored with the use of JNB TI, $ instruction to check whether all the 8
– bits in the character is completely transferred.
7. Clear TI flag and repeat step 5 for next transfer.
11
4
11
5
Ex. 3.16 Write a program to transfer a letter ‘Y’ serially at 9600 baud rate continuously,
and also send a letter ‘N’ through port 0, which is connected to a display device.
Sol Here one byte of data (ASCII value
‘Y’
of ‘Y’, which is 59h) is transmitted P3.1
(TX
serially via TxD pin (P3.1), and )
another is transmitted in parallel 8051
‘N’
(ASCII value of ‘N’, which is 4Eh) P0 DISPLAY
via P0 pins.
Note: relate the ALP written below with the step sequence stated above in section3.7.
3.7.4
MOV TMOD, # 20h 5
; Timer 1, Mode 2 (Auto reload operation)
MOV TH1, # -3 ; 9600 Baud rate
MOV SCON , # 50h ;Serial mode 1, 8 – bit UART with start and stop bits
SETB TR1 ;Start timer 1
Again: MOV SBUF, # ’Y’ ;place the character in SBUF to transmit serially
Here: JNB TI, Here ;Wait till all the bits in the character is transferred
CLR TI ; Clear the TI flag for next serial transfer
MOV P0, # ’N’ ; Move ‘N’ to P0 for parallel transfer
SJMP Again ; Repeat this process for ever.
Ex. 3.17 Take data in through ports 0, 1, and 2, one after the other and transfer the data
serially, continuously at a baud rate of 4800.
Sol: MOV TMOD, # 20h ; Timer 1, Mode 2 (Auto reload operation)
MOV TH1, # -6 ; 4800 Baud rate
MOV SCON, # 50h ;Serial mode 1, 8 – bit UART with start and stop bits
MOV P0, # 0FFh ;Make P0 as an input port
MOV P1, # 0FFh ;Make P1 as an input port
MOV P2, # 0FFh ;Make P2 as an input port
SETB TR1 ;Start timer 1
Rpt: MOV A, P0 ; Read P0 pins
ACALL Send ; Call the subroutine
MOV A, P1 ; Read P1 pins
11
6
ACALL Send ; Call the subroutine
MOV A, P2 ; Read P2 pins
ACALL Send ; Call the subroutine
SJMP Rpt Repeat this process for ever
; Transferring data serially – subroutine
Send: MOV SBUF, A ;place the character in SBUF to transmit serially
Here: JNB TI, Here ;Wait till all the bits in the character is transferred
CLR TI ; Clear the TI flag for next serial transfer
RET ; Return to the main program
Ex. 3.18 Write an 8051 ALP to transmit serially the message “Welcome” at a baud rate of
9600, and assume XTAL freq as 11.0592 MHz
Sol: MOV TMOD, # 20h ; Timer 1, Mode 2 (Auto reload operation)
MOV TH1,# -3 ; 9600 Baud rate
MOV SCON, #50h ;Serial mode 1, 8 – bit UART with start and stop bits
SETB TR1 ;Start timer 1
MOV DPTR, # Msg ;Load pointer for the message
Rpt: CLR A
MOVC A, @A+DPTR ;Get the character
JZ Last ; If last character, get out
ACALL Send ; Otherwise call the subroutine
INC DPTR ; Point the next character
SJMP Rpt ; Repeat the process
Last: SJMP $
Msg: DB “Welcome” 0 ; Define Byte the message with last character as null
; Transferring data serially – subroutine
Send: MOV SBUF, A ;place the character in SBUF to transmit serially
Here: JNB TI, Here ;Wait till all the bits in the character is transferred
CLR TI ; Clear the TI flag for next serial transfer
RET ; Return to the main program
11
7
Ex. 3.19 Write an 8051 ALP to transmit serially the message “SWITCH ON” or
“SWITCH OFF”, depending on the status of the simple switch connected to pin
P1.2. Use 2400 Baud rate, and assume XTAL freq as 11.0592 MHz
Sol
SW
SW = 1; “SWITCH ON”
P1.2 P3.1
8051
(TX SW = 0; “SWITCH OFF”
)
11
8
Ex. 3.20 Write a program in assembly language for 8051 to send 2 messages “Normal
Speed” and “High Speed” to the serial port. Assuming that a SW is connected to
pin P2.0, monitor its status and set the baud rate as follows:
when SW = 0; MSG1 at 4800 Baud rate
when SW = 1; MSG2 at 9600 Baud rate
Sol: VCC
11
9
Msg2: DB “Normal Speed” 0
; Transferring data serially – subroutine
Send: MOV SBUF, A ;place the character in SBUF to transmit serially
Here: JNB TI, Here ;Wait till all the bits in the character is transferred
CLR TI ; Clear the TI flag for next serial transfer
RET ; Return to the main program
Ex. 3.21 Write an 8051 ALP to send 2 different strings to the serial port. Assuming that a SW is
connected to pin P2.5, monitor its status and make a decision as follows: when SW = 0; Send your first
name when SW = 1; Send your last name;
Assume XTAL = 11.0592 MHz, and a baud rate of 9600.
Sol:
12
0
VCC
SW
P2.5
12
1
SW = 0; “First name” P3.1
8051
SW = 1; “Last name”
In programming the 8051 to transfer character bytes serially, the following steps must be taken
1. The TMOD register is loaded with the value 20h, indicating the use of Timer in mode 2
(8 – bit auto reload) for setting the baud rate.
2. The TH1 is loaded with the one of the values in the above table to set the baud rate.
3. The SCON is loaded with 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. (TX
)
5. The RI flag is monitored with the use of JNB RI, $ instruction to check whether all the 8
– bits in the character is completely received.
12
2
6. When RI is raised, SBUF has the byte. Its contents are moved into a safe place, like
accumulator.
7. Clear RI flag and repeat step 5 to receive next character.
Ex. 3.22 Write an 8051 ALP to receive the data which has been sent in serial form and
sent it out to port 0 in parallel form. Also save the data at RAM loc. 60h.
Sol:
R
‘Y’
P3.0
x
8051
Y
P0 DISPLAY
60h Y
Let the data received via RxD pin is the ASCII value of character ‘Y’ (59h). When the
8051 receives data serially via RxD, it gets rid of start and stop bits and places the byte in
SBUF register. Then it raises the RI flag to indicate that a byte is received serially. The
below program demonstrates this theory of receiving the data serially.
MOV TMOD, # 20h ; Timer 1, Mode 2 (Auto reload operation)
MOV TH1, # -3 ; 9600 Baud rate
MOV SCON, # 50h ;Serial mode 1, 8 – bit UART with start and stop bits
SETB TR1 ;Start timer 1
Wait: JNB RI, Wait ;Wait till all the bits in the character is received
CLR RI ;RI flag is cleared
MOV A, SBUF ; Received data, which is available in SBUF, is moved to A
MOV P0, A ; Send to P0 in parallel & and store in 60h internal RAM
MOV 60h, A
SJMP $
Ex. 3.23 Assume that the serial port is connected to the COM port of the IBM PC, and on
the PC we are using the hyper Terminal 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 the PC, the message “We are READY”,
12
3
b). Receive any data sent by the PC and put it on the LEDs connected to P1,
and c). Get data on switches connected to P2 and sent it to PC serially.
The program should perform part (a) once, but parts (b) and (c) continuously. Use
4800 baud rate.
Sol:
LEDs
To PC P1
TxD
8051
From
RxD SW
COM Port P2
12
4
RET ; Return to the main program
; Receiving data serially – subroutine
Recev: JNB RI, Recev ;Wait till all the bits in the character is received
MOV A, SBUF ;RI flag is cleared
CLR RI ; Received data, which is available in SBUF, is moved to A
RET ; Return to the main program