0% found this document useful (0 votes)
15 views125 pages

Microcontrollers: 8051 & MSP430 Course Guide

The document outlines a course on Microcontrollers and Applications, detailing objectives, teaching methods, and module content. It covers microcontroller architectures, assembly language programming, timers, interrupts, and interfacing with external devices, specifically focusing on the 8051 and MSP430 microcontrollers. The course aims to equip students with practical programming skills and the ability to analyze real-time requirements in microcontroller applications.

Uploaded by

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

Microcontrollers: 8051 & MSP430 Course Guide

The document outlines a course on Microcontrollers and Applications, detailing objectives, teaching methods, and module content. It covers microcontroller architectures, assembly language programming, timers, interrupts, and interfacing with external devices, specifically focusing on the 8051 and MSP430 microcontrollers. The course aims to equip students with practical programming skills and the ability to analyze real-time requirements in microcontroller applications.

Uploaded by

reelrush1725
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Microcontrollers and Applications

Course Code 22ET361 CIE Marks 50


Teaching Hours/Week (L: T:P: S) [Link] SEE Marks 50
Total Hours of Pedagogy 40 hours Theory Total Marks 100
Credits 3 Exam Hours 3
Course objectives: This course imparts knowledge
1. To understand the various system architectures & internal architectures of
microcontroller.
2. To program in assembly level and C level with understanding of different set of
instructions
3. To communicate with the microcontroller and external devices using serial and parallel
communication
4. To interface external world to microcontroller using assembly/c programming.
Teaching-Learning Process (General Instructions)
These are sample Strategies, which teacher can use to accelerate the attainment of the various
course outcomes.
1. Lecture method (L) does not mean only traditional lecture method, but different type of
teaching methods may be adopted to develop the outcomes.
2. Show Video/animation films to explain evolution of communication technologies.
3. Encourage collaborative (Group) Learning in the class
4. Ask at least three HOTS (Higher order Thinking) questions in the class, which promotes
critical thinking
5. Adopt Problem Based Learning (PBL), which fosters students’ Analytical skills, develop
thinking skills such as the ability to evaluate, generalize, and analyse information rather
than simply recall it.
6. Show the different ways to solve the same problem and encourage the students to come up
with their own creative ways to solve them.
7. Discuss how every concept can be applied to the real world - and when that's possible, it
helps improve the students' understanding.
Module-1
Microprocessors and microcontroller: Introduction, Microprocessors and Microcontrollers, RISC
& CISC CPU Architectures, Harvard & Von-Neumann CPU architecture, Basic Microprocessor
Architecture
The 8051 Architecture: Introduction, Features of 8051, Architecture of 8051, Pin diagram of 8051,
1
Memory organization, External Memory interfacing, stacks.
Teaching- Learning Chalk and Talk, YouTube videos, Flipped Class Technique, Programming
Process assignments RBT Level: L1, L2, L3
Module-2
Assembly Language Programming: Addressing modes. Instruction set: Instruction timings, 8051
instructions: Data transfer instructions, Arithmetic instructions, Logical instructions, Branch
instructions, Conditional/Unconditional Branch instructions, Subroutine instructions, and Bit
manipulation instruction.
Assembly language programs and Time delay calculations. [Assembler directives], Assembly
Language programs on data transfer, Arithmetic Operations, logical operations
Teaching- Learning Chalk and Talk, YouTube videos, Flipped Class Technique, Programming
Process assignments RBT Level: L1, L2, L3
Module-3*
8051 Timers/counters: Timers and Counters, 8051 timers/counters, programming 8051 timers in
assembly. Serial Communication: Data communication, Basics of Serial Data Communication,
8051 Serial Communication, connections to RS-232, Serial communication Programming in
assembly. Programming timers/counter and serial communication using C.
Teaching- Learning Chalk and Talk, YouTube videos, Flipped Class Technique, Programming
Process assignments RBT Level: L1, L2, L3
Module-4*
Interrupts: Basics of interrupts, 8051 interrupt structure of 8051 Programming timer interrupts,
programming external hardware interrupts Programming serial communication interrupts.
Interrupt priority in 8051.
8051 Interfacing and Applications: Basics of I/O concepts, I/O Port Operation, Interfacing 8051 to
LCD, Keyboard, Stepper motor, DC motor and ADC by using programming in C
Teaching- Learning Chalk and Talk, YouTube videos, Flipped Class Technique, Programming
Process assignments RBT Level: L1, L2, L3
Module-5
MSP430 Microcontroller
Architecture: Pin – out, Functional Block Diagram, Memory, Central Processing unit, Memory
Mapped input and output, Clock Generator.
Instruction Set: Addressing Modes, Constant Generator and Emulated Instructions, Instruction Set,
Examples.
Teaching- Learning Chalk and Talk, YouTube videos, Flipped Class Technique, Programming
Process assignments RBT Level: L1, L2, L3
Course outcomes (Course Skill Set) At the end of the course the student will be able to :
2
Module 1

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.

1.2 Difference between Microprocessor and Microcontroller


The 8051 Architecture
2.1 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.

2.2 Architecture of 8051

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.

80h P0 SP DPL DPH PCON


88h TCON TMOD TL0 TL1 TH0 TH1
90h P1
98h SCON SBUF
A0h P2
A8h IE
B0h P3
B8h IP
C0h
C8h
D0h PSW
D8h
E0h A
E8h
F0h B
F8h

Fig. 2.6: SFR Memory Map

2.3 Pin Diagram of 8051 Microcontroller

The 8051 microcontroller is a 40 pin DIP as shown in


fig 2.7. The crystal frequency is the basic clock
frequency of the microcontroller. The 8051 requires
11
+5V single power supply and is designed for 1MHz
minimum clock frequency to 20MHz, Maximum
frequency.
Ports – P0, P1, P2 & P3:
The four ports P0, P1, P2 and P3 each use 8 pins,
making them 8 – bit ports. All the ports upon RESET,
are configured as input, ready to be used as input
ports. When the first 0 is written to a port, it becomes
an output port.
Port 0 Alternate function
As shown in pin diagram, Port 0 is designated as AD 7
– 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 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.

Port 3 Alternate function Pin no. Functionality

P3.0 RXD (Receive Data) 10 Serial


Communication
P3.1 TXD (Transmit Data) 11 signals

P3.2 ∫ 0 ( Interrupt 0) 12
External
Interrupts
P3.3 ∫ 1 ( Interrupt 1) 13

P3.4 T0 (Timer 0 input) 14


External Timer
P3.5 T1 (Timer 1 input) 15 0/1 Inputs

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

MOV R1, #12h

MOV R4, #0F3h

PUSH 6

PUSH 1

PUSH 4

After Push 6 After PUSH 1 After PUSH 4

08h 08h 25 08h 25 08h 25


09h 09h 09h 12 09h 12
0Ah 0Ah 0Ah 0Ah F3
0Bh 0Bh 0Bh 0Bh
SP = 08 SP = 09h SP = 0Ah
14
Start SP = 07h

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

After POP 6 After POP 1 After POP 4


R6=F3h R1=12h R4=25h
08h 25 08h 25 08h
09h 12 09h 09h
0Ah 0Ah 0Ah
0Bh 0Bh 0Bh
SP = 09h SP = 08h SP = 07h

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

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

2.5 Addressing Modes of 8051

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

2. 8051 instructions: Data transfer instructions

3. Arithmetic instructions,

4. Logical instructions

5. Branch instructions

6. Bit manipulation instruction

7. Subroutine instructions

8. Assembler Directives

9. Assembly language programs and Time delay calculations.

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

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

2 Data transfer instructions


2.1 MOV instructions
In this group, the instructions perform data transfer operations of the following types.
a. Move the contents of a register Rn to A : MOV A, Rn
examples:
MOV A,R2
MOV A,R7
b. Move the contents of a register A to Rn :MOV Rn, A
MOV R4,A
MOV R1,A
c. Move an immediate 8 bit data to register A or to Rn :MOV A,#VV, MOV Rn,#VV
MOV A, #45H
MOV R6, #51H
d. Move an immediate 8 bit data to memory location using direct address :MOV DDh,#VV
MOV 30H, #44H
e. Move an immediate 8 bit data to memory location using indirect addressing through Ri :
MOV @Ri,#VV
MOV @R0, #0E8H
f. Move an immediate 16 bit data to DPTR: MOV DPTR,#VVVV
MOV DPTR, #0F5A2H
MOV DPTR, #5467H
g. Move the contents of a memory location to A or A to a memory location using direct
addressing : MOV A, DDH/MOV DDH,A
20
MOV A, 65H
MOV 45H, A
h. Move the contents of a memory location to A or A to a memory location using indirect
addressing : MOV @Ri,A /MOV A,@Ri
MOV A, @R0
MOV @R1, A
i. Move the contents of a memory location to Rn or Rn to a memory location using direct
addressing :MOV Rn,DDH, / MOV DDH,Rn
MOV R3, 65H
MOV 45H, R2
[Link] the contents of memory location to another memory location using direct addressing:
MOV DDH,DDH
MOV 47H, 65H
k. Move the contents of memory location to another memory location using register indirect
addressing: MOV DDH,@Ri/ MOV @Ri, DDH
MOV 45H, @R0
MOV @R1,50H
l. Move the contents of an external memory to A or A to an external memory : MOVX A,
@Ri/MOVX @Ri, A/MOVX A, @DPTR,/ MOVX @DPTR, A
The MOVX instructions transfers data between the Accumulator and a byte of external data

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

Sample explanation for MOV A,@R0

Instruction: MOV A,@R0


Number of bytes: 1 byte
Machine cycles: 1 cycle
Function: moves the content of internal memory location pointed to by R0 into A
Operation : A M[[R0]]
Flags Affected: No flags affected
Before execution: After Execution
R0=50h R0=50h
[50h]=77h [50h]=77h
A=xx A=77h
Note: follow the above format for explaining all the instrucitons

2.2 Push and Pop instructions

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

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

Sample explanation for ADD A,@R0

Instruction: ADD A,@R0


Number of bytes: 1 byte
Machine cycles: 1 cycle
Function: Add the content of internal memory location pointed by R0 and accumulator store the
sum into A
Operation : A A+M[[R0]]
Flags Affected: All flags CY,AC,OV and P are affected
Before execution: After Execution
R0=50h R0=50h
[50h]=77h [50h]=77h
A=40h A=B0h flags: CY=0,P=1,OV=1AF=0

Sample explanation for ADD A, R0

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

A=F4h A=52h flags: CY=1,AF=1,P=1,OV=0

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
25
iv. SUBB A, @R0
CY AC and OV flags will be affected by this operation.

Sample explanation for SUBB A,40h

Instruction: SUBB A,40h


Number of bytes: 1 byte
Machine cycles: 1 cycle
Function: subtracts the contents of memory location from Accumulator store the difference in
accumulator.
Operation : A A-M[40h]
Flags Affected: all flags are affected
Before execution: After Execution
M[40h]=65h M[40h]=65h

A=F4h A=71h flags: CY=1,AF=0,P=0,OV=0


3.5 Multiplication
MUL AB. This instruction multiplies two 8 bit unsigned numbers which are stored in A and B
register. After multiplication the lower byte of the result will be stored in accumulator and
higher byte of result will be stored in B register. Carry flag will always be cleared and Overflow
flag will be set if product is >8bit

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)

3.6 Increment and Decrement: increments the operand by one.


INC A
INC Rn
INC DDh
INC @Ri
INC DPTR
INC increments the value of source by 1. If the initial value of register is FFh, incrementing the
value will cause it to reset to 0. The Carry Flag is not set when the value "rolls over" from 255 to
0.
In the case of "INC DPTR", the value two-byte unsigned integer value of DPTR is incremented. If
the initial value of DPTR is FFFFh, incrementing the value will cause it to reset to 0.
Sample explanation
Instruction: INC DPTR
Number of bytes: 1 byte
Machine cycles: 2 cycles
Function: Increments 16 bit contents of DPTR(DPH:DPL)
Operation : DPTR=DPTR+1
Flags Affected: no flags are affected
Before execution: After Execution
DPL=FFh DPL=00h
DPH=F4h DPH=F5h

Decrement: decrements the operand by one.


DEC A
DEC Rn
DEC DDh
DEC @Ri
DEC decrements the value of source by 1. If the initial value of is 0, decrementing the value will
cause it to reset to FFh. The Carry Flag is not set when the value "rolls over" from 0 to FFh.
4. Logical Instructions
Logical AND
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

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.

A7-4 A3-0 A3-0 A7-4

Before Execution After execution

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

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: -
1. Short jump range (-128 to 127 from the instruction following the jump instruction)

Sample explanation for sjmp

Instruction: sjmp reladds


Number of bytes: 2 bytes
Machine cycles: 2 cycles
Function: Jumps unconditionally to the location address obtained by adding PC with reladds.
Operation :PC<- PC+2
PC PC+reladds
Flags Affected: no flags are affected
Before execution: After Execution
0040h: sjmp 03h
0042h:------- PC0045h
Performs jump to the location 0045h
0045h: --------

Instructions that use Relative Jump


SJMP <relative address>; this is unconditional jump
The remaining relative jumps are conditional jumps
JC <relative address>
JNC <relative address>
JB bit, <relative address>
JNB bit, <relative address>
JBC bit, <relative address>
CJNE <destination byte>, <source byte>, <relative address>
DJNZ <byte>, <relative address>
JZ <relative address>
JNZ <relative address>

Instruction: JBC bit, <relative address>


Number of bytes: 3 bytes
Machine cycles: 2 cycles
30
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:------- PC0045h
Performs jump to the location 0045h
0045h: --------

M[20h]=35h( bit 00h=1) M[20h]=34h( bit 00h=0)

CJNE <destination byte>, <source byte>, <relative address>


CJNE A,#VV,reladss
CJNE A,DDh,reladss
CJNE Rn,#VV,reladss
CJNE @Ri,#VV,reladss

Instruction: CJNE Rn,#VV, <relative address>


Number of bytes: 3 bytes
Machine cycles: 2 cycles
Function: If Rn≠VV jump to location by adding reladds to PC
Set CY=1 if Rn<VV
CY=0 if Rn>VV
If Rn=VV resume with next instruction
Operation : if Rn≠VV PC<- PC+2
PC PC+reladds
CY=1 if Rn<VV
CY=0 if Rn>VV
If Rn=VV PC<- PC+2
Flags: CY affected
Before execution: After Execution
0040h: cjne r4,#35h,03h
0042h:------- PC0045h
Performs jump to the location 0045h
0045h: --------

R4=23h R4=23h CY=1

DJNZ <byte>, <relative address>


DJNZ Rn,reladd
DJNZ DDh, reladd

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

If Rn=00 resume with next instruction


Operation : if Rn≠00 PC<- PC+2
PC PC+reladds

If Rn=00 PC<- PC+2


Flags: no flags affected
Before execution: After Execution
R4=06 R4=05
0040h: djnz r4,,03h
0042h:------- PC0045h
Performs jump to the location 0045h
0045h: --------

AJMP addr11(short absolute jump)

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.

Instruction: ajmp addr11


Number of bytes: 2 bytes
Machine cycles: 2 cycles
Function: Jumps unconditionally to the location address obtained by replacing PC with 11 it
absolute address
Operation :PC10:0 add11
Flags Affected: no flags are affected
Before execution: After Execution
0040h: ajmp 0145h
0042h:------- PC0145h
Performs jump to the location 0145h
0145h: --------

Long Absolute Jump/Call


LJMP <address 16>
JMP @A+DPTR
Instruction: ljmp addr16
Number of bytes: 3 bytes
Machine cycles: 2 cycles
32
Function: Jumps unconditionally to the location address obtained by replacing PC with 11 it
absolute address
Operation :PC15:0 add16
Flags Affected: no flags are affected
Before execution: After Execution
0040h: ajmp F145h
0042h:------- PCF145h
Performs jump to the location F145h
F145h: --------

Another classification of jump instructions is


1. The unconditional jump is a jump in which control is transferred unconditionally to
the target location. Examples: sjmp,ajmp,ljmp( explanation is same as above)
2. The conditional jump is a jump in which control is transferred to target location only if
certain condition is met.
Examples:
Mnemonic operation
JC raddr Jump to the relative address if CY = 1
JNC raddr Jump to the relative address if CY = 0
JB bit, raddr Jump to the relative address if bit = 1
JNB bit, Jump to the relative address if bit = 0
raddr
JBC bit, addr Jump to the relative address if bit = 1. Then clear bit to 0.
CJNE dest, Compare jump if not equal. If the destination and source is not equal,
source, then jump is executed. Also the CY flag is affected.
raddr
DJNZ dest, Decrement dest reg by one and check for non zero. If non zero the
raddr jump is executed based on the relative address. No flags are affected.
JZ raddr Jumps to the relative address, if A = 0.
JNZ raddr Jumps to the relative address if A ≠ 0

All conditional jumps are short jumps.


Bit level jump instructions:
Bit level JUMP instructions will check the conditions of the bit and if condition is true, it jumps
to the address specified in the instruction. All the bit jumps are relative jumps.
JB bit, rel ; jump if the direct bit is set to the relative address specified.
JNB bit, rel ; jump if the direct bit is clear to the relative address specified.
JBC bit, rel ; jump if the direct bit is set to the relative address specified and then clear the bit.

6. Subroutine CALL And RETURN Instructions


Common practice while writing a large program, is to break the program into small modules
which can be written and tested by individual programmer. This is known as modularity. This
reduces the development time and also increases the readability. In 8051 these modules are
33
known as subroutines. Subroutines are called by main program whenever its required to be
used. Subroutines are handled by CALL and RET instructions when call instruction is executed
the control will be transferred to the subroutine. When ret instruction is executed control will
be transferred from subroutine to main program as shown.

There are two types of CALL instructions

1. LCALL address(16 bit)

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)

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

A,Rn AND Register to Accumulator 1


ANL
ANL A,direct AND direct byte to Accumulator 2
ANL A,@Ri AND indirect RAM to Accumulator 1
ANL A,#data AND immediate data to Accumulator 2
ANL direct,A AND Accumulator to direct byte 2
ANL direct,#data AND immediate data to direct byte 3
ORL A,Rn OR register to Accumulator 1 1
ORL A, direct OR direct byte to Accumulator 2
ORL A,@Ri OR indirect RAM to Accumulator 1
ORL A,# data OR immediate data to Accumulator 2
39
ORL direct,A OR Accumulator to direct byte 2 2
ORL direct,#data OR immediate data to direct byte 3
XRL A,Rn Exclusive-OR register to Accumulator 1
XRL A,direct Exclusive-OR direct byte to Accumulator 2
Exclusive-OR indirect RAM to
XRL A,@Ri 1
Accumulator
Exclusive-OR immediate data to
XRL A,#data 2
Accumulator
XRL direct,A Exclusive-OR Accumulator to direct byte 2
Exclusive-OR immediate data to direct
XRL direct,#data 3
byte
CLR A Clear Accumulator 1
CPL A Complement Accumulator 1
RL A Rotate Accumulator Left 1
Rotate Accumulator Left through the
RLC A 1
Carry
RR A Rotate Accumulator Right 1
Rotate Accumulator Right through the
RRC A 1
Carry
SWAP A Swap nibbles within the Accumulator 1

DATA TRANSFER OPERATIONS

A,Rn Move register to Accumulator 1


MOV
MOV A,direct Move direct byte to Accumulator 2
MOV A,@Ri Move indirect RAM to Accumulator 1
MOV A,#data Move immediate data to Accumulator 2
MOV Rn,A Move Accumulator to register 1
MOV Rn,direct Move direct byte to register 2
MOV Rn,#data Move immediate data to register 2
MOV direct,A Move Accumulator to direct byte 2
MOV direct,Rn Move register to direct byte 2
MOV direct,direct Move direct byte to direct 3
MOV direct,@Ri Move indirect RAM to direct byte 2
MOV direct,#data Move immediate data to direct byte 3
MOV @Ri,A Move Accumulator to indirect RAM 1
MOV @Ri,direct Move direct byte to indirect RAM 2
MOV @Ri,#data Move immediate data to indirect RAM 2
MOV DPTR,#data16 Load Data Pointer with a 16-bit Constant 3
MOVC A,@A+DPTR Move Code byte relative to DPTR to Acc 1
MOVC A,@A+PC Move Code byte relative to PC to Acc 1
MOVX A,@Ri Move External RAM (8-bit address) to Acc 1
40
MOVX A,@DPTR Move External RAM (16-bit address) to Acc 1
MOVX @Ri,A Move Acc to External RAM (8-bitaddr) 1
MOVX @DPTR,A Move Acc to External RAM (16-bitaddr) 1
PUSH direct Push(Write) direct byte onto stack 2
POP direct Pop(Read) direct byte from stack 2
XCH A,Rn Exchange register with Accumulator 1
XCH A,direct Exchange direct byte with Accumulator 2
XCH A,@Ri Exchange indirect RAM with Accumulator 1
XCHD A,@Ri Exchange low-order Digit indirect RAM with Acc 1

BOOLEAN VARIABLE MANIPULATION

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

addr11 Absolute Subroutine Call 2


ACALL
LCALL addr16 Long Subroutine Call 3
RET Return from Subroutine 1
RETI Return from interrupt 1
AJMP addr11 Absolute Jump 2
41
LJMP addr16 Long Jump 3
SJMP rel Short Jump (relative address) 2
JMP @A+DPTR Jump indirect relative to the DPTR 1
JZ rel Jump if Accumulator is Zero 2
JNZ rel Jump if Accumulator is Not Zero 2
A,direct,rel
Compare direct byte to Acc and Jump if
CJNE 3
Not Equal
Compare immediate to Acc and Jump if
CJNE A,#data,rel 3
Not Equal
Compare immediate to register and
CJNE Rn,#data,rel 3
Jump if Not Equal
Compare immediate to indirect and
CJNE @Ri,#data,rel 3
Jump if Not Equal
Decrement register and Jump if Not
DJNZ Rn,rel 2
Zero
Decrement direct byte and Jump if Not
DJNZ direct,rel 3
Zero
NOP No Operation 1

Sample programs and delay calculation:


1. Write an ALP in 8051 to add two 16 bit numbers stored in external memory. After addition
store the result in internal data memory.
Sol:
Let the 16 – bit data to be added are 45 38h and 68 62h is available in external RAM loc
6000h and 7000h as follows
6000h: 45 7000h: 68
6001h: 38 7001h: 62
The 16 – bit result is to be stored in internal RAM from 20h
ORG 30H
MOV R2, #60H
MOV R3, #70H
MOV DPL, #01
MOV R0, #21H
MOV R7, #02
CLR C

BACK: MOV DPH, R2

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

RPT: MOVX A, @DPTR

ADD A, R2
MOV R2, A
JNC SKIP
INC R1

SKIP: INC DPTR

DJNZ R7, RPT


MOVX @DPTR, A
MOV A, R1
INC DPTR
MOVX @DPTR, A
SJMP $
3. Write an ALP to add N – 8 bit nos. available from memory location START. Display the
result at Port 0 and Port 1
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
43
DJNZ R7, BACK

MOV P0, A

MOV P1, R2

SJMP $

4. 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.
Sol:

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

EVE: MOV @R0, #0FFh

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

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 $

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

RPT: MOVX A, @DPTR

ADD A, R0
MOV R0, A
INC DPTR
DJNZ R7, RPT
DIV AB
MOVX @DPTR, A

END

9. Write a delay program to generate a delay of 10ms. Assume crystal frequency of


11.0592MHz. show delay calculations
Since the crystal frequency is 11.0592MHz, 1 Machine cycle = 1.085µs. So, to create a delay
10 m
of 10ms, the WAIT loop should be executed for = 200µ. To create a delay of 200µs, the
50
200 µ
value to be loaded in R1 is = 92
2∗1.085 µ
Delay: MOV R2, #50
RPT: MOV R1, #92

WAIT: DJNZ R1, WAIT

DJNZ R2, RPT

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

LAST: DJNZ R7, BACK

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

The 8051 microcontroller is a 40 pin DIP as


shown in fig 2.7. The crystal frequency is the
basic clock frequency of the microcontroller. The
8051 requires +5V single power supply and is
designed for 1MHz minimum clock frequency to
20MHz, Maximum frequency.
Ports – P0, P1, P2 & P3:
The four ports P0, P1, P2 and P3 each use 8 pins,
making them 8 – bit ports. All the ports upon
RESET, are configured as input, ready to be used
as input ports. When the first 0 is written to a
port, it becomes an output port.
Port 0 Alternate function

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.

Port 3 Alternate function Pin no. Functionality

P3.0 RXD (Receive Data) 10 Serial


Communication
P3.1 TXD (Transmit Data) 11 signals

P3.2 ∫ 0 ( Interrupt 0) 12
External
Interrupts
P3.3 ∫ 1 ( Interrupt 1) 13

P3.4 T0 (Timer 0 input) 14


External Timer
P3.5 T1 (Timer 1 input) 15 0/1 Inputs

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.

PSEN (Pin 29)


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 (Pin 30)
• 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
54
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.

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

08h 08h 25 08h 25 08h 25


09h 09h 09h 12 09h 12
0Ah 0Ah 0Ah 0Ah F3
0Bh 0Bh 0Bh 0Bh
Start SP = 07h SP = 08 SP = 09h SP = 0Ah
Ex. 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
POP 2 0Ah F9
0Bh 54
55
Start SP = 0Bh

Sol. After POP 6 After POP 1 After POP 4


R6=F3h R1=12h R4=25h
08h 25 08h 25 08h
09h 12 09h 09h
0Ah 0Ah 0Ah
0Bh 0Bh 0Bh
SP = 09h SP = 08h SP = 07h

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

PUSH 4 PUSH 5 POP 4

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

2.5 Addressing Modes of 8051

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

Instruction Set Table


of
Contents
1. Instruction timings

2. 8051 instructions: Data transfer instructions

3. Arithmetic instructions,

4. Logical instructions
59
5. Branch instructions

6. Bit manipulation instruction

7. Subroutine instructions

8. Assembler Directives

9. Assembly language programs and Time delay calculations.

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

2 Data transfer instructions


2.1 MOV instructions
In this group, the instructions perform data transfer operations of the following types.
a. Move the contents of a register Rn to A : MOV A, Rn
examples:
MOV A,R2
MOV A,R7
b. Move the contents of a register A to Rn :MOV Rn, A
MOV R4,A
MOV R1,A
c. Move an immediate 8 bit data to register A or to Rn :MOV A,#VV, MOV Rn,#VV
MOV A, #45H
MOV R6, #51H
d. Move an immediate 8 bit data to memory location using direct address :MOV DDh,#VV
MOV 30H, #44H
e. Move an immediate 8 bit data to memory location using indirect addressing through Ri :
MOV @Ri,#VV
MOV @R0, #0E8H
f. Move an immediate 16 bit data to DPTR: MOV DPTR,#VVVV
MOV DPTR, #0F5A2H
MOV DPTR, #5467H
g. Move the contents of a memory location to A or A to a memory location using direct addressing : MOV
A, DDH/MOV DDH,A
MOV A, 65H
MOV 45H, A
h. Move the contents of a memory location to A or A to a memory location using indirect addressing :
MOV @Ri,A /MOV A,@Ri
MOV A, @R0
MOV @R1, A
i. Move the contents of a memory location to Rn or Rn to a memory location using direct addressing : MOV
Rn,DDH, / MOV DDH,Rn
MOV R3, 65H
MOV 45H, R2
[Link] the contents of memory location to another memory location using direct addressing:
MOV DDH,DDH
MOV 47H, 65H
k. Move the contents of memory location to another memory location using register indirect addressing:
MOV DDH,@Ri/ MOV @Ri, DDH
61
MOV 45H, @R0
MOV @R1,50H
l. Move the contents of an external memory to A or A to an external memory : MOVX A, @Ri/MOVX @Ri,
A/MOVX A, @DPTR,/ MOVX @DPTR, A
The MOVX instructions transfers data between the Accumulator and a byte of external data
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.

*Ri-R0/R1
Rn-R0 to R7
VV-immediate 8 bit data
62
DD-direct address
VVVV-immediate 16 bit data

Sample explanation for MOV A,@R0

Instruction: MOV A,@R0


Number of bytes: 1 byte
Machine cycles: 1 cycle
Function: moves the content of internal memory location pointed to by R0 into A
Operation : A M[[R0]]
Flags Affected: No flags affected
Before execution: After Execution
R0=50h R0=50h
[50h]=77h [50h]=77h
A=xx A=77h
Note: follow the above format for explaining all the instrucitons

2.2 Push and Pop instructions

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.

Sample explanation for ADD A,@R0

Instruction: ADD A,@R0


Number of bytes: 1 byte
Machine cycles: 1 cycle
Function: Add the content of internal memory location pointed by R0 and accumulator store the sum into
A
Operation : A A+M[[R0]]
Flags Affected: All flags CY,AC,OV and P are affected
Before execution: After Execution
R0=50h R0=50h
[50h]=77h [50h]=77h
A=40h A=B0h flags: CY=0,P=1,OV=1AF=0

Sample explanation for ADD A, R0

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

A=F4h A=52h flags: CY=1,AF=1,P=1,OV=0

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.

Sample explanation for SUBB A,40h

Instruction: SUBB A,40h


Number of bytes: 1 byte
66
Machine cycles: 1 cycle
Function: subtracts the contents of memory location from Accumulator store the difference in
accumulator.
Operation : A A-M[40h]
Flags Affected: all flags are affected
Before execution: After Execution
M[40h]=65h M[40h]=65h

A=F4h A=71h flags: CY=1,AF=0,P=0,OV=0


3.5 Multiplication
MUL AB. This instruction multiplies two 8 bit unsigned numbers which are stored in A and B register.
After multiplication the lower byte of the result will be stored in accumulator and higher byte of result
will be stored in B register. Carry flag will always be cleared and Overflow flag will be set if product is
>8bit

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)

3.6 Increment and Decrement: increments the operand by one.


INC A
INC Rn
INC DDh
INC @Ri
INC DPTR
INC increments the value of source by 1. If the initial value of register is FFh, incrementing the value will
cause it to reset to 0. The Carry Flag is not set when the value "rolls over" from 255 to 0.
In the case of "INC DPTR", the value two-byte unsigned integer value of DPTR is incremented. If the initial
value of DPTR is FFFFh, incrementing the value will cause it to reset to 0.
Sample explanation
Instruction: INC DPTR
Number of bytes: 1 byte
Machine cycles: 2 cycles
Function: Increments 16 bit contents of DPTR(DPH:DPL)
Operation : DPTR=DPTR+1
Flags Affected: no flags are affected
Before execution: After Execution
DPL=FFh DPL=00h
DPH=F4h DPH=F5h

Decrement: decrements the operand by one.


DEC A
DEC Rn
DEC DDh
DEC @Ri
DEC decrements the value of source by 1. If the initial value of is 0, decrementing the value will cause it to
reset to FFh. The Carry Flag is not set when the value "rolls over" from 0 to FFh.
4. Logical Instructions
Logical AND

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

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

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.

A7-4 A3-0 A3-0 A7-4

Before Execution After execution

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)

Sample explanation for sjmp

Instruction: sjmp reladds


Number of bytes: 2 bytes
Machine cycles: 2 cycles
Function: Jumps unconditionally to the location address obtained by adding PC with reladds.
Operation :PC<- PC+2
PC PC+reladds
Flags Affected: no flags are affected
Before execution: After Execution
0040h: sjmp 03h
0042h:------- PC0045h
Performs jump to the location 0045h
0045h: --------

Instructions that use Relative Jump


SJMP <relative address>; this is unconditional jump
The remaining relative jumps are conditional jumps
JC <relative address>
JNC <relative address>
JB bit, <relative address>
JNB bit, <relative address>
JBC bit, <relative address>
CJNE <destination byte>, <source byte>, <relative address>
DJNZ <byte>, <relative address>
JZ <relative address>
JNZ <relative address>

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:------- PC0045h
Performs jump to the location 0045h
0045h: --------

M[20h]=35h( bit 00h=1) M[20h]=34h( bit 00h=0)

CJNE <destination byte>, <source byte>, <relative address>


CJNE A,#VV,reladss
CJNE A,DDh,reladss
CJNE Rn,#VV,reladss
CJNE @Ri,#VV,reladss

Instruction: CJNE Rn,#VV, <relative address>


Number of bytes: 3 bytes
Machine cycles: 2 cycles
Function: If Rn≠VV jump to location by adding reladds to PC
Set CY=1 if Rn<VV
CY=0 if Rn>VV
If Rn=VV resume with next instruction
Operation : if Rn≠VV PC<- PC+2
PC PC+reladds
CY=1 if Rn<VV
CY=0 if Rn>VV
If Rn=VV PC<- PC+2
Flags: CY affected
Before execution: After Execution
0040h: cjne r4,#35h,03h
0042h:------- PC0045h
Performs jump to the location 0045h
0045h: --------

R4=23h R4=23h CY=1

DJNZ <byte>, <relative address>


73
DJNZ Rn,reladd
DJNZ DDh, reladd

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

If Rn=00 resume with next instruction


Operation : if Rn≠00 PC<- PC+2
PC PC+reladds

If Rn=00 PC<- PC+2


Flags: no flags affected
Before execution: After Execution
R4=06 R4=05
0040h: djnz r4,,03h
0042h:------- PC0045h
Performs jump to the location 0045h
0045h: --------

AJMP addr11(short absolute jump)


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.

Instruction: ajmp addr11


Number of bytes: 2 bytes
Machine cycles: 2 cycles
Function: Jumps unconditionally to the location address obtained by replacing PC with 11 it absolute
address
Operation :PC10:0 add11
Flags Affected: no flags are affected
Before execution: After Execution
0040h: ajmp 0145h
0042h:------- PC0145h
Performs jump to the location 0145h
0145h: --------

Long Absolute Jump/Call


LJMP <address 16>
JMP @A+DPTR
Instruction: ljmp addr16
Number of bytes: 3 bytes
74
Machine cycles: 2 cycles
Function: Jumps unconditionally to the location address obtained by replacing PC with 11 it absolute
address
Operation :PC15:0 add16
Flags Affected: no flags are affected
Before execution: After Execution
0040h: ajmp F145h
0042h:------- PCF145h
Performs jump to the location F145h
F145h: --------

Another classification of jump instructions is


3. The unconditional jump is a jump in which control is transferred unconditionally to the target
location. Examples: sjmp,ajmp,ljmp( explanation is same as above)
4. The conditional jump is a jump in which control is transferred to target location only if certain
condition is met.
Examples:
Mnemonic operation
JC raddr Jump to the relative address if CY = 1
JNC raddr Jump to the relative address if CY = 0
JB bit, raddr Jump to the relative address if bit = 1
JNB bit, Jump to the relative address if bit = 0
raddr
JBC bit, addr Jump to the relative address if bit = 1. Then clear bit to 0.
CJNE dest, Compare jump if not equal. If the destination and source is not equal,
source, then jump is executed. Also the CY flag is affected.
raddr
DJNZ dest, Decrement dest reg by one and check for non zero. If non zero the
raddr jump is executed based on the relative address. No flags are affected.
JZ raddr Jumps to the relative address, if A = 0.
JNZ raddr Jumps to the relative address if A ≠ 0

All conditional jumps are short jumps.


Bit level jump instructions:
Bit level JUMP instructions will check the conditions of the bit and if condition is true, it jumps to the
address specified in the instruction. All the bit jumps are relative jumps.
JB bit, rel ; jump if the direct bit is set to the relative address specified.
JNB bit, rel ; jump if the direct bit is clear to the relative address specified.
JBC bit, rel ; jump if the direct bit is set to the relative address specified and then clear the bit.

6. Subroutine CALL And RETURN Instructions


Common practice while writing a large program, is to break the program into small modules which can be
written and tested by individual programmer. This is known as modularity. This reduces the development
75
time and also increases the readability. In 8051 these modules are known as subroutines. Subroutines are
called by main program whenever its required to be used. Subroutines are handled by CALL and RET
instructions when call instruction is executed the control will be transferred to the subroutine. When ret
instruction is executed control will be transferred from subroutine to main program as shown.

There are two types of CALL instructions

1. LCALL address(16 bit)

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

ANL A,Rn AND Register to Accumulator 1


ANL A,direct AND direct byte to Accumulator 2
ANL A,@Ri AND indirect RAM to Accumulator 1
ANL A,#data AND immediate data to Accumulator 2
ANL direct,A AND Accumulator to direct byte 2
ANL direct,#data AND immediate data to direct byte 3
ORL A,Rn OR register to Accumulator 1 1
ORL A, direct OR direct byte to Accumulator 2
ORL A,@Ri OR indirect RAM to Accumulator 1
ORL A,# data OR immediate data to Accumulator 2
ORL direct,A OR Accumulator to direct byte 2 2
ORL direct,#data OR immediate data to direct byte 3
XRL A,Rn Exclusive-OR register to Accumulator 1
81
XRL A,direct Exclusive-OR direct byte to Accumulator 2
Exclusive-OR indirect RAM to
XRL A,@Ri 1
Accumulator
Exclusive-OR immediate data to
XRL A,#data 2
Accumulator
XRL direct,A Exclusive-OR Accumulator to direct byte 2
Exclusive-OR immediate data to direct
XRL direct,#data 3
byte
CLR A Clear Accumulator 1
CPL A Complement Accumulator 1
RL A Rotate Accumulator Left 1
Rotate Accumulator Left through the
RLC A 1
Carry
RR A Rotate Accumulator Right 1
Rotate Accumulator Right through the
RRC A 1
Carry
SWAP A Swap nibbles within the Accumulator 1

DATA TRANSFER OPERATIONS

MOV A,Rn Move register to Accumulator 1


MOV A,direct Move direct byte to Accumulator 2
MOV A,@Ri Move indirect RAM to Accumulator 1
MOV A,#data Move immediate data to Accumulator 2
MOV Rn,A Move Accumulator to register 1
MOV Rn,direct Move direct byte to register 2
MOV Rn,#data Move immediate data to register 2
MOV direct,A Move Accumulator to direct byte 2
MOV direct,Rn Move register to direct byte 2
MOV direct,direct Move direct byte to direct 3
MOV direct,@Ri Move indirect RAM to direct byte 2
MOV direct,#data Move immediate data to direct byte 3
MOV @Ri,A Move Accumulator to indirect RAM 1
MOV @Ri,direct Move direct byte to indirect RAM 2
MOV @Ri,#data Move immediate data to indirect RAM 2
MOV DPTR,#data16 Load Data Pointer with a 16-bit Constant 3
MOVC A,@A+DPTR Move Code byte relative to DPTR to Acc 1
MOVC A,@A+PC Move Code byte relative to PC to Acc 1
MOVX A,@Ri Move External RAM (8-bit address) to Acc 1
MOVX A,@DPTR Move External RAM (16-bit address) to Acc 1
MOVX @Ri,A Move Acc to External RAM (8-bitaddr) 1
MOVX @DPTR,A Move Acc to External RAM (16-bitaddr) 1
PUSH direct Push(Write) direct byte onto stack 2
82
POP direct Pop(Read) direct byte from stack 2
XCH A,Rn Exchange register with Accumulator 1
XCH A,direct Exchange direct byte with Accumulator 2
XCH A,@Ri Exchange indirect RAM with Accumulator 1
XCHD A,@Ri Exchange low-order Digit indirect RAM with Acc 1

BOOLEAN VARIABLE MANIPULATION

CLR C Clear Carry 1


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

ACALL addr11 Absolute Subroutine Call 2


LCALL addr16 Long Subroutine Call 3
RET Return from Subroutine 1
RETI Return from interrupt 1
AJMP addr11 Absolute Jump 2
LJMP addr16 Long Jump 3
SJMP rel Short Jump (relative address) 2
JMP @A+DPTR Jump indirect relative to the DPTR 1
JZ rel Jump if Accumulator is Zero 2
JNZ rel Jump if Accumulator is Not Zero 2
83
A,direct,rel
Compare direct byte to Acc and Jump if
CJNE 3
Not Equal
Compare immediate to Acc and Jump if
CJNE A,#data,rel 3
Not Equal
Compare immediate to register and
CJNE Rn,#data,rel 3
Jump if Not Equal
Compare immediate to indirect and
CJNE @Ri,#data,rel 3
Jump if Not Equal
Decrement register and Jump if Not
DJNZ Rn,rel 2
Zero
Decrement direct byte and Jump if Not
DJNZ direct,rel 3
Zero
NOP No Operation 1

9. Sample programs and delay calculation:


13. Write an ALP in 8051 to add two 16 bit numbers stored in external memory. After addition store the result in internal data memory.
[06M]
Sol:
Let the 16 – bit data to be added are 45 38h and 68 62h is available in external RAM loc 6000h and 7000h as follows
6000h: 45 7000h: 68
6001h: 38 7001h: 62
The 16 – bit result is to be stored in internal RAM from 20h
ORG 30H
MOV R2, #60H
MOV R3, #70H
MOV DPL, #01
MOV R0, #21H
MOV R7, #02
CLR C
BACK: MOV DPH, R2
MOVX A, @DPTR
MOV R1, A
MOV DPH, R3
MOVX A, @DPTR
ADDC A, R1
MOV @R0, A
DEC R0
DEC DPL
DJNZ R7, BACK
SJMP $
14. 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. Dec 2011–09M
MOV R7, #20
MOV DPTR, #2000H
MOV R2, #00
MOV R1, #00
RPT: MOVX A, @DPTR
ADD A, R2
MOV R2, A

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

3. 7. 6 Programming the 8051 to receive data serially.....................................................................30

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.

3.2. Basic registers of Timer


Both timer 0 and timer 1 are 16 – bit wide. Since the 8051 has an 8 – bit architecture, each 16 – bit
timer is accessed as two separate registers of low byte (TL) and high byte (TH).

D15 D14 D13 D12 D11 D10 D9 D8 D7 D6 D5 D4 D3 D2 D1 D0

TH0 (8Ch) TL0 (8Ah)


Fig 3.1: Timer 0 Registers
Note: Byte addresses are mentioned inside the brackets

D15 D14 D13 D12 D11 D10 D9 D8 D7 D6 D5 D4 D3 D2 D1 D0

TH1 (8Dh) TL1 (8Bh)


Fig 3.2: Timer 1 Registers

3.2.1 Timer – 0 registers

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

Fig 3.3: TMOD (Timer Mode) Register

Gate(G) Gating control bit.


 When set, the timer /counter is enabled only while INTX pin is high and TRX control pin is
set.
 When cleared, the timer is enabled whenever the TRX pin is set.

C/𝑇̅ Timer or counter selected.


 Cleared for Timer operation. For delay generation using timers, clear this bit.
 Set for counter operation. For counting any external events, set this bit.

M1 & M0 Mode bits 1 & 0. The Timer/Counter can be put in various modes of operation as
mentioned below

M1 M0 Mode Description

0 0 0 13 – Bit timer mode.

0 1 1 16 – bit timer mode


16 – Bit timer/counters with THX and TLX are cascaded.
1 0 2 8 – Bit auto reload.
8 – Bit auto reload timer/counter; THX holds the initial value to be loaded
into TLX each time timer overflows.
1 1 3 Split timer mode.

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

Fig 3.4: Timer Frequency

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

3.2.4 TCON (Timer Control) register

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

TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0

Timer Control Interrupt Control

Fig 3.4: TCON (Timer Control) Register


The timers are started by using the instructions to set timer start bits TR0 and TR1, which are
called timer run control bits. The timer can be stopped by clearing these timer run control
bits. When a timer counts to its maximum value, it sets a flag named TF0 for Timer 0 and

92
TF1 for Timer 1. The details of the bit pattern of TCON are shown below.

BIT Symbol Bit Address Function

TCON.7 TF1 8Fh Timer 1 overflow flag

TCON.6 TR1 8Eh Timer 1 Run control bit

TCON.5 TF0 8Dh Timer 0 overflow flag

TCON.4 TR0 8Ch Timer 0 Run control bit

3.3 Mode 1 programming


The following are the characteristics and operations of Mode 1 timer:
1. It is a 16 – bit timer; therefore, it allows values of 0000h to FFFFh to be loaded into
the timer’s registers TLX and THX.
2. After TH and TL registers are loaded with 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. The timer registers TH and TL counts up (increments) for every timer cycle until it
reaches its limit of FFFFh. When it rolls over from FFFFh to 0000h, it sets high a
flag bit called TF (Timer overflow flag). This timer flag can be monitored. Once
timer overflows, stop the timer with the instructions “CLR TR0” for timer 0 and
“CLR TR1” for timer 1.
4. After the timer reaches its limit and rolls over, in order to repeat the process the
registers TH and TL must be reloaded with its initial value and TF must be reset to 0.

XTAL
Oscillator ÷ 12
TH TL TF

C/T = 0 TF goes high when FFFFh 0000h


TR

Fig 3.5: Mode 1 Timer operation using Software control

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

To produce a square wave of 2kHz,


assuming 50% duty cycle on pin P2.3
1 P2.3
2 𝑘𝐻𝑧
TTot = = 0.5ms

⟹ TON = TOFF = 𝑇𝑇𝑜𝑡 = 0.25ms


t
2
0.5ms
So, the pin P2.3 should be complemented
Fig 3.6: Square wave of 2 kHz
forever for 250µs once.
The timer 0 in mode 1 should be configured to produce a delay of 250µs.
The number of timer cycles required to generate 250µs = 250µ = 250 timer cycles.

The 16 bit initial value to be loaded in timer 0 registers:


TH0 TL0
hex
-250d FF 06 h

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

Delay: SETB TR0 ;Start Timer 0


Wait: JNB TF0, Wait ;Wait till Timer 0 overflows, thereby producing 250µs
CLR TR0 ;Stop Timer 0
CLR TF0 ;Reset the timer 0 Flag bit
RET

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

The 16 bit initial value to be loaded in timer 1 registers:


TH1 TL1
hex
- 4608d EE 00 h

MOV TMOD, #10h ;Timer 1 in Mode 1


Back: MOV TH1, #0EEh ; The 16 – bit initial values are loaded in Timer registers
MOV TL1, #00h

95
ACALL Delay
CPL P1.5 ;Complement Port pin P1.5
SJMP Back

Delay: SETB TR1 ;Start Timer 1


Wait: JNB TF1, Wait ;Wait till Timer 1 overflows, thereby producing 5ms
CLR TR1 ;Stop Timer 1
CLR TF1 ;Reset the timer 1 Flag bit
RET

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

Fig 3.7: Square wave with different ON and OFF


times
Sol: Given XTAL = 22 MHz
⟹1 Machine cycle = 1
22𝑀
* 12 = 0.545µs.

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

TH0 TL0 TH0 TL0


hex hex
- 5505d EA 7F h - 22026d A9 F6 h

MOV TMOD, #01h ;Timer 0 in Mode 1.


Back: MOV TH0, #0A9h ;To generate OFF Time, load A9 F6h in timer registers.
MOV TL0, #0F6h

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.

Delay: SETB TR0 ;Start Timer 0


Wait: JNB TF0, Wait ;Wait till Timer 0 overflows, thereby producing 5ms
CLR TR0 ;Stop Timer 0
CLR TF0 ;Reset the timer 0 Flag bit
RET

Ex. 3.6 For the following XTAL frequencies, calculate the


Maximum delay generated using 8051 mode 1 timer
operations

i). 8 MHz ii). 11.0592 MHz iii). 22 MHZ

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

maximum delay possible using mode t


1 timer with XTAL of 22 MHz is 2 Sec
35.71ms, which is very less than the
Fig 3.8: Pulse train of 2 Sec period
required amount of 1 sec delay.
So, configure a delay of lesser than the max. delay, say 25ms, and repeat this delay for ‘n’ times to
get the required amount of 1 sec.
1 sec = 25ms * n
⟹ n = 40
For a Delay of 25 ms: TH1 TL1
25𝑚
hex
0.545
Timer cycles required = = 45,872cycles - 45872d 4C D0 h
µ
MOV TMOD, #10h ;Timer 1 in Mode 1.
Rept: MOV R7, #40 ;Load the ‘n’ value to R register to repeat the delay
Back: MOV TH1, #4Ch ;To generate 25ms, load 4C D0h in timer registers.
MOV TL1, #0D0h
ACALL Delay
DJNZ R7, Back ;If R7 G 0, then repeat the delay of 25 ms.
CPL P2.4
SJMP Rept ;Repeat for reloading to get continuous square wave.

Delay: SETB TR1 ;Start Timer 1


Wait: JNB TF1, Wait ;Wait till Timer 1 overflows, thereby producing 5ms
CLR TR1 ;Stop Timer 1
CLR TF1 ;Reset the timer 1 Flag bit
RET

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

Fig 3.9: Mode 2 Timer operation using Software control

Steps to program timers in mode 2


To generate a time delay using the timer in mode 2, the following steps need to be taken.
1. Load the TMOD register indicating which timer (Timer 0 or Timer 1) is to be used and
select the mode 2 timer.
2. Load the 8 – bit initial value in TH register.
3. Start the timer.
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.

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

⟹ TON = TOFF = 𝑇𝑇𝑜𝑡 = 100µ


t
2
200µs
So, the pin P1.2 should be
Fig 3.10: Square wave of 5 kHz
complemented forever for 100µs once.
Delay required = 100µs
100µ
0.545µ
Timer cycles required = = 183 timer cycles.

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.

Ex. 3.10 For the following XTAL frequencies, calculate


the Maximum delay generated using 8051 mode 2
timer operations

i). 8 MHz ii). 11.0592 MHz iii). 22 MHZ

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

MOV TMOD, #20h ;Timer 1 in Mode 1.


MOV TH1, # - 230 ;Load the initial value in TH1
SETB TR1 ;Start Timer 1
Rept: MOV R7, # 16 ;Load the ‘n’ value to R register to repeat the delay
Outer: MOV R6, # 250
Inner: ACALL Delay
DJNZ R6, Inner ;If R6 G 0, then go to Label inner.
DJNZ R7, Outer ;If R7 G 0, then go to Label outer.
CPL P2.4
SJMP Rept ;Repeat for reloading to get continuous square wave.

Delay: JNB TF1, $ ;Wait till Timer 1 overflows, thereby producing 250µs
CLR TF1 ;Reset the timer 1 Flag bit
RET

Ex. 3.12 Assuming XTAL = 11.0592 MHz, Find


i). the frequency of the square wave generated on pin P1.0
ii). the smallest frequency achievable in the given program and the TH value in doing so.
MOV TMOD, #20h
MOV TH1, # 5
SETB TR1
Back: JNB TF1, S
CPL P1.0

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.

Since delay required is 50ms, Mode 1 timer is best suited


Timer 0 in mode 1:
TMOD = 0000 0001b = 01h
50𝑚
1.085
Timer cycles required for 50ms = = 46, 083 cycles.
µ

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.

Delay: SETB TR0 ;Start Timer 0


Wait: JNB TF0, Wait ;Wait till Timer 0 overflows, thereby producing 50ms
CLR TR0 ;Stop Timer 0
CLR TF0 ;Reset the timer 0 Flag bit
RET

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.

TMOD = 0000 0001b = 01h


For 500Hz frequency (When ‘SW’ = 0) For 750 Hz frequency (When ‘SW’ = 1)
1 1
500 750
TTot = = 2ms TTot = = 1.33ms

⟹ TON = TOFF = 𝑇𝑇𝑜𝑡 = 1ms ⟹ TON = TOFF = 𝑇𝑇𝑜𝑡 = 0.667ms


2 2

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

TH0 TL0 TH0 TL0


hex hex
- 922d FC 66 h - 615d FD 99 h

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.

Delay: SETB TR0 ;Start Timer 0


Wait: JNB TF0, Wait ;Wait till Timer 0 overflows,
CLR TR0 ;Stop Timer 0
CLR TF0 ;Reset the timer 0 Flag bit
RET

3.5 Counter Programming


In the previous discussions, the timers of 8051 microcontroller are used for delay generation.
These timers can also be used as an event counter, counting events happening outside the 8051.
The use of timers as an event counter is covered in this section.
 When timer/counter is used as a timer for delay generation, the 8051’s crystal is used as
the source for incrementing the timer registers, as discussed in earlier sections.
 When timer/counter is used as an event counter for counting external events, the pulse
applied to port P3.4 or P3.5 is used to increment the timer registers.
In counter mode, the role of TMOD, THX and TLX remains same as discussed for timer modes.

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

Fig 3.11: TMOD (Timer Mode) Register

Mode 1 Counter programming


The following are the characteristics and operations of Mode 1 counter:
1. It is a 16 – bit counter; initially, the timer’s registers TLX and THX are set to 00 00h.
2. The counter must be started. This is done by “SETB TR0” for timer 0 and “SETB TR1”
for timer 1.
3. The timer registers TH and TL counts up (increments) for every external clock pulses fed
to P3.4 for Timer 0 and P3.5 for Timer 1.
These clock pulses could be the number of the people passing through the entrance, or the
number of wheel rotation, or any other events that can be converted to pulses.

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

Fig 3.12: Counter in mode 1 Programming


Ex. 3.14 Find the frequency of an input signal fed to pin P3.4. Use XTAL = 22MHz.
Sol: Since external pulse is fed to pin P3.4, the timer 0 should be configured as an event counter.
The frequency is the number of clock pulses per second duration. So Timer 1 should be
configured to generate a delay of 1 second. During this 1 second, Timer 0 is to run as a 16 –bit
event counter, as the input pulse is fed to P3.4. At the end of one sec, the values in TL0 and TH0
give the number of pulses that were received at pin p3.4 during this second. This gives the
frequency of the unknown signal.
TMOD = 0 0 0 1 0 1 0 1 b = 15h; T0 as Mode – 1 Event counter & T1 as Mode – 1 timer.
Given XTAL = 22MHz ⟹ 1 machine cycle = 0.545µs
Max. delay for timers in mode 1 = 216 machine cycle = 65 536 * 0.545µ = 35.71ms.
So, configure a delay of lesser than the max. delay, say 25ms, and repeat this delay for ‘n’ times
to get the required amount of 1 sec.
1 sec = 25ms * n
⟹ n = 40
For a Delay of 25 ms: TH1 TL1
hex
25𝑚 - 45872d 4C D0 h
Timer cycles required = = 45,872cycles

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

3.7 Serial port Programming of 8051


When a microprocessor communicates with the outside world, it provides the data in byte-sized
chunks. In some cases, such as printers, the information is simply grabbed from the 8 – bit data
bus and presented to the 8 – bit data bus of the printer. This can work only if the cable is not too
long, since long cables diminish and even distort signals. Further an 8 – bit data path is
expensive. For these reasons, serial communication is used for transferring data between two
systems located at distances of hundreds of feet to millions of miles apart. Fig 3.13 diagrams
serial vs. parallel data transfers.
D7

Sender Receiver Sender Receiver


D0

a). Serial Transfer b). Parallel Transfer

Fig 3.13: Serial vs Parallel data transfer

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

SM0 SM1 SM2 REN TB8 RB8 TI RI

Fig 3.14: SCON register (98h*)

SM0 SCON.7 Serial mode specifier


SM1 SCON.6 Serial mode specifier
SM2 SCON.5 Used for Multiprocessor mode; make as ‘0’
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 beginning of the stop bit in mode 1.
 Must be cleared by software.
RI SCON.0 Receive interrupt flag.
 Set by hardware at the halfway through the stop bit in mode 1.
 Must be cleared by software.
Note: Make SM2, TB8, RB8 as ‘0’

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:

SM0 SM1 Modes of operation


0 0 Serial Mode 0
0 1 Serial Mode 1 ;8 –bit data with 1 stop bit and 1 start bit
1 0 Serial Mode 2
1 1 Serial Mode 3
Of the 4 serial modes, only mode 1 is of interest to us. In the SCON register, when serial mode 1
is chosen, the data framing is 8 – bits, 1 stop bit and one start bit, as shown in fig. 3.15.
One frame of
data

Space 0 0 0 0 0 0 Start Mark


Stop 1 1 bit
bit
D7

Goes out last Goes out first


Fig 3.15: Framing ASCII “A” (41h) with start and stop bit

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.

XTAL Machine cycle freq. ÷32 28,800 Hz


Oscillator ÷12 921.6kHz by UART To Timer 1 for setting
the Baud rate
11.0592MHz
Fig 3.16: 8051 UART – Setting the Baud rate

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

and UART frequency = 𝑀𝑎𝑐ℎi𝑛𝑒 𝑐𝑦𝑐𝑙𝑒 𝐹𝑟𝑒𝑞


= 921.6 𝑘
32 12
= 28, 800Hz.

a). 28,800/3 = 9600; where -3d = FDh is loaded in TH1


b). 28,800/6 = 4800; where -6d = FAh is loaded in TH1
c). 28,800/12 = 2400; where -12d = F4h is loaded in TH1.

3. 7. 5 Programming the 8051 to transfer data serially

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

MOV TMOD, # 20h ; Timer 1, Mode 2 (Auto reload operation)

MOV TH1,# -12 ; 9600 Baud rate


MOV SCON, #50h ;Serial mode 1, 8 – bit UART with start and stop bits
SETB TR1 ;Start timer 1
SETB P1.2 ; Make P1.2 as input pin
Rpt: JNB P1.2, SW_OFF ; Check for the switch position
SW_ON: MOV DPTR, # Msg1 ; Load pointer for Switch on
SJMP Trans
SW_OFF: MOV DPTR, # Msg2 ; Load pointer for Switch off
Trans: 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 Trans ; Repeat the process
Last: SJMP Rpt ; Read the switch position
Msg1: DB “SWITCH ON” 0
Msg2: DB “SWITCH OFF” 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 ; Retun to the main program

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

SW SW = 1; “High Speed @9600 Baud


rate” P2.0 P3.1
8051 (TX
) SW = 0; “Normal Speed @4800 Baud rate”

MOV TMOD, # 20h ; Timer 1, Mode 2 (Auto reload operation)


MOV SCON, #50h ;Serial mode 1, 8 – bit UART with start and stop bits
SETB 2.0 ; Make P2.0 as input pin
Rpt: JNB P2.0, SW_OFF
SW_ON: MOV TH1,# -3 ; 9600 Baud rate
SETB TR1 ;Start timer 1
MOV DPTR, # Msg1 ;Place DPTR pointing High speed message
SJMP Trans
SW_OFF: MOV TH1,# -6 ; 4800 Baud rate
SETB TR1 ;Start timer 1
MOV DPTR, # Msg2 ;Place DPTR pointing Normal speed message
Trans: 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 Trans ; Repeat the process
SJMP Rpt ; Read the switch position

Msg1: DB “High Speed” 0

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”

* Refer Ex. 3.19 for Solution.

3. 7. 6 Programming the 8051 to receive data serially

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

MOV P2, #0FFh ;Make P2 as input port


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
SETB TR1 ;Start timer 1
MOV DPTR, #Msg Place DPTR pointing initial We are READY message
Init: CLR A
MOVC A, @A+DPTR ;Get the character
JZ Rpt ; If last character, get out
ACALL Send ; Otherwise call the subroutine
INC DPTR ; Point the next character
SJMP Init ; Repeat the process
Rpt: MOV A, P2 ;Read port 2 switch positions and place it in A
ACALL Send ; Send it to PC serially.
ACALL Recev ; Receive Data serially from PC and store it in ACC
MOV P1, A ; send the data to LEDs connected to P1
SJMP Rpt ; Repeat this process for ever.
; Transferring data serially – subroutine
Send: MOV SBUF, A ;place the character in SBUF to transmit serially
Wait: JNB TI, Wait ;Wait till all the bits in the character is transferred
CLR TI ; Clear the TI flag for next serial transfer

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

Msg: DB “We are READY” 0


END

You might also like