8051 Microcontroller
8051 Microcontroller
Dr. NAGARAJA B G
Professor & HoD,
Department of ECE, Jain Institute of Technology, Davangere, Karnataka.
Gouthami Publications
No. 101(3), Yashashwini Nilaya
2nd Cross, Basaveshwara Nagara,
Shimoga, Karnataka
8051 Microcontroller for V Sem. BE Students of VTU
written by, Dr. Arun Kumar G, Dr. Nagaraja B G, Dr. Spoorti J Jainar and Dr. Purohit Shrinivasacharya
Published by
Gouthami Publications
No. 101(3), Yashashwini Nilaya
2nd Cross, Basaveshwara Nagara,
Shimoga, Karnataka
Mobile: 9686799389
E-mail: [email protected]
©Publisher
Price: ` 200.00
Copyright : Every effort has been made to avoid errors or omission in this publication. In spite of this, some errors
might have crept in. Any mistakes, error or discrepancy noted may be brought to our notice which shall be taken care
of in the next edition.
No part of this book may be reproduced or copied in any form or by any means (graphic, electronic or me-
chanical, including photocopying, recording, taping, or information retrieval system) or reproduced on any disc, tape,
perforated media or other information storage device, etc., without the written permission of the publishers. Breach of
this condition is liable for legal action.
For binding mistakes, misprints or for missing pages, etc., the publisher’s liability is limited to replacement
within one month of purchase by a similar edition. All expenses in this connection are to be borne by the purchaser. All
disputes are subject to Shimoga jurisdiction only.
Dedicated
To Almighty,
all our Family members,
Teachers
&
Friends
Preface
The importance of microcontroller in this modern computing world is unbelievable as it plays a
very important role in each & every day-to-day application as majority of the products in the markets
have an inbuilt microcontroller for its operation. It is therefore necessary for any technical person of any
branch to know the basics of microprocessor & microcontroller as this is the era of computing. Thus,
it is a matter of great pleasure for us to write a text-book covering the entire syllabi for the V semester
engineering students of microcontrollers at the fundamental level.
The authors are immensely pleased to release the first edition of their book,
‘8051 Microcontroller’. The fundamental concepts of this book are presented in an easily understandable,
clear & systematic manner so that any student can understand the programming concepts and get through
his/her fundas. The book prepares very carefully as several background topics with essential illustrations
and practical examples and then further gives the complex programming concepts step by step and
also their explanations with the list of instruction sets and gives totally an exam oriented approach,
which will be very useful from the scoring point of view. This book covers the entire syllabus of ‘8051
Microcontroller’ for the V semester CBCS Scheme (Common to EC/TC) of VTU, Belagavi, Karnataka.
A large number of programming exercises along with their algorithms are also given, so that the students
can develope their own programs for any type of applications.
Five modules are present in this text-book & the topics that are covered are
Module -1: 8051 Microcontroller
Module -2: 8051 Instruction Set
Module -3: 8051 Stack, I/O Port Interfacing and Programming
Module -4: 8051 Timers and Serial Port
Module -5: 8051 Interrupts and Interfacing Applications
All the five modules are well addressed theoretically as well as problematically. A large number
of examination problems have been solved to substantiate the theoretical concepts. At the same time,
solutions to the examination question papers are also has been put up & thus the book seems to be giving
totally an examination oriented approach.
This book will be very much useful not only to the students of various engineering and polytechnic
colleges, but also to the teachers. The book also serves as a ready reckoner for some of the competitive
v
vi 8051 Microcontroller
exams. Suggestions for the improvement of this book are highly appreciated in this regard & are
welcomed.
Special Naman is due to His Holiness Sri Sri Shivarathrishwara Deshikendra Mahaswamiji,
President JSS Mahavidyapeetha Mysore and my sincere thanks to the Management of
JSS Mahavidyapeetha Mysore.
We also acknowledge all the help rendered by the personnels of JSS Academy of Technical
Education, Noida, Uttar Pradesh, Jain Institute of Technology, Davangere and Siddaganga Institute of
Technology, Tumakuru, for their constant support in bringing out this master piece for the V semester
CBCS Scheme (Common to E&CE/TC) of VTU, Belagavi, Karnataka.
Not but the least, we would like to thank all our family members for their infinite patience and
understanding they have demonstrated in allowing us to allocate family time for the writing of this book.
Finally, we are indebted to all the persons who have helped us in preparing this manuscript directly
or indirectly by giving us valuable suggestions & moral support, in the sense we wish to express our
profound thanks to all those people who have helped in making this book a reality.
Module 2: 8 051 Instruction Set: Addressing Modes, Data Transfer instructions, Arithmetic instructions,
Logical instructions, Branch instructions, Bit manipulation instructions. Simple Assembly
language program examples (without loops) to use these instructions.
Module 3: 8051 Stack, I/O Port Interfacing and Programming: 8051 Stack, Stack and Subroutine
instructions. Assembly language program examples on subroutine and involving loops -
Delay subroutine, Factorial of an 8 bit number (result maximum 8 bit), Block move without
overlap, Addition of N 8 bit numbers, Picking smallest/largest of N 8 bit numbers, Interfacing
simple switch and LED to I/O ports to switch on/off LED with respect to switch status.
Module 4: 8051 Timers and Serial Port: 8051 Timers and Counters – Operation and Assembly
language programming to generate a pulse using Mode-1 and a square wave using Mode-2
on a port pin.
8 051 Serial Communication- Basics of Serial Data Communication, RS-232 standard, 9 pin
RS232 signals, Simple Serial Port programming in Assembly and C to transmit a message
and to receive data serially.
Module 5: 8051 Interrupts and Interfacing Applications: 8051 Interrupts. 8051 Assembly language
programming to generate an external interrupt using a switch, 8051 C programming to
generate a square waveform on a port pin using a Timer interrupt.
I nterfacing 8051 to ADC-0804, LCD and Stepper motor and their 8051 Assembly language
interfacing programming.
*****
vii
Contents
Module 1 8051 Microcontroller
1.1 Introduction to Microprocessor & Microcontrollers 1
1.1.1 Microprocessor 1
1.1.2 Evolution of Microprocessors 2
1.1.3 Microcontrollers 2
1.2 Microprocessor V/s Microcontroller 3
1.2.1 RISC and CISC 4
1.2.2 Harvard and Von Neumann architectures 5
1.2.3 Selection of Microcontrollers 6
1.3 Embedded Systems 7
1.4 Embedded Microcontrollers 7
1.5 8051 Architecture - Registers 7
1.5.1 Variants of MCS-51 family and their features 12
1.5.2 Applications of Microcontrollers 12
1.5.3 Special Function Register (SFR) 13
1.5.4 Features of 8051 Microcontroller 14
1.6 8051 pin details 15
1.7 I/O ports functions 18
1.7.1 PORT 0 19
1.7.2 PORT 1 20
1.7.3 PORT 2 21
1.7.4 PORT 3 21
ix
x 8051 Microcontroller
1.1.1 Microprocessor
Data Bus
CPU
Address Bus
1
2 8051 Microcontroller
1.1.3 Microcontrollers
Serial
I/O Timer COM
Port
CPU
General CPU RAM ROM
RAM ROM I/O Timer Serial
Purpose Port COM
Port Serial
Micro
I/O Timer COM
- processor
Address Bus Port
Data
Data and
Address
CPU Program
Control Memory
Harvard
Data Data
Data Program
Memory Address Address Memory
CPU
Control Control
(RAM) (ROM)
ff P
ackaging (The number of pins & the packaging format. This determines
the required space & assembly layout.)
2. Availability of assembler, debuggers, complier, emulator, technical support and
expertise both in-house and outside.
3. Microcontroller availability in needed quantities both now and in the future.
Register
Registers are used to store information temporarily, while the information could be
• a byte of data to be processed, or
• an address pointing to the data to be fetched
Majority of 8051 register are 8-bit registers. The most widely used registers are
• Accumulator (A), for all arithmetic and logic instructions.
• B, R0, R1, R2, R3, R4, R5, R6, R7.
• DPTR (data pointer) and PC (Program Counter).
8 8051 Microcontroller
Arithmetic Special
Function i/o
and Logic
Port 0
PSW
Latch
Registers A0-A7
unit D0-D7
RAM
8-bit Data and
A B Address Bus
Port 1
Latch
i/o
DPTR
PC DPH ROM
Port 2
Latch
DPL i/o
A8-A15
16-bit Address Bus
i/o
Interrupt
Port 3
Latch
System Special Counter
EA Byte/Bit Serial Data
ALE timing Function
PSEN Address RD-WR
Registers
XTAL1 System IE
XTAL2 Register
Interrupts IP
RSET Bank 3
timers PCON
VCC Register SBUF
Data Buffers
GND Bank 2 SCON
Memory
TCON
Control Register
TMOD
Bank 1 TLO
Register THO
TL1
Bank 0 TH1
Internal RAM Structure
A register (Accumulator):
• Accumulator is a 8 bit register & is widely used for arithmetic and data transfer
operations.
• The arithmetic operations are addition, subtraction, multiplication, division &
Boolean bit manipulating etc.
• The data transfer operation between the 8051 microcontroller and any external
memory.
Note: It can be accessed through its SFR address of 0E0H.
8051 Microcontroller 9
B-register:
• B-register to store 8-bit result of multiplication & division operations
• It is used as temporary register where data may be stored.
Note: It can be accessed through its SFR address 0F0H.
BUS:
Bus is a collection of wires which work as a communication channel or medium for
transfer of data. The 8051 has two types of buses:
1. Address Bus (16-bits) and 2. Data Bus (8-bits)
Program Counter (PC):
• PC is a16-bit register which points to the address of the next instruction to be
executed.
• The PC is automatically incremented after every instruction byte is fetched.
• PC is the only register that does not have an internal address.
• When 8051 is RESET, the default value of PC is 0000 H.
• Each register can be used either as Timer or counter and can be divided into
two 8-bit registers called Timer Low (TL) and Timer High (TH).
STACK (8-bit)
• The stack is a section of RAM used by the CPU to store information temporarily.
This information could be data or an address.
• The register used to access the stack is called the SP (stack pointer) register.
The stack pointer in 8051 is only 8 bits wide
• The storing of a CPU register in the stack is called a PUSH, and loading the
contents of the stack back into a CPU register is called a POP.
8 bit 8 bit
Fig.1.5.3: DPTR
• DPTR is a 16-bit register, which holds a 16-bit address.
• DPTR can be split into 2 parts:
ff DPL: Data pointer Low byte having internal address 82h.
ff DPH: Data pointer high byte having internal address 83h.
• DPTR is very useful for string operations and look up table operations.
Memory Organization:
The 8051 microcontroller’s memory is divided into
1. Internal RAM – 128 bytes: Used for temporarily storing and keeping intermediate
results and variables.
2. ROM – 4K bytes: Used for permanent saving program being executed
Interrupts:
The 8051 Microcontroller has 6 interrupts:
–––– ––––
RESET, I NT0, I NT1, Timer 0,Timer 1 Serial Port (TI/RI)
8051 Microcontroller 11
CY AC F0 RS1 RS0 OV - P
D7 D6 D5 D4 D3 D2 D1 D0
Fig.1.5.4: Program Status Word.
• The program status word (PSW) register is an 8-bit register. It is also referred
to as the flag register. Only 6 bits are used by the 8051. The two unused bits
are user-definable flags.
• The Carry (CY), Auxiliary carry (AC), Overflow (OV) and Parity (P) are called
Conditional flags because these flags indicate some conditions after the
instruction is executed.
Carry Flag (CY):
After performing arithmetic & logic operation if there is a carryout from the MSB (D7
i.e. 7th- bit) then CY = 1, otherwise CY = 0
Example 1-1
how the status of the CY, AC and P flag after the addition of 38H and
S
2FH in the following instructions.
MOV A, #38H
ADD A, #2FH ; after the addition A=67H, CY=0
Solution:
1 1 1
38 0 0 1 1 1 0 0 0
+ 2F + 0 0 1 0 1 1 1 1
67 0 1 1 0 0 1 1 1
CY = 0 since there is no carry beyond the D7 bit.
8051 Microcontroller 13
Example 1-2
Show the status of the CY, AC and P flag after the addition of 9CH and
64H in the following instructions.
MOV A, #9CH
ADD A, #64H ; after the addition A=00H, CY=1
Solution:
1 1 1 1 1 1
9C 1 0 0 1 1 1 0 0
+ 64 + 0 1 1 0 0 1 0 0
1 00 1 0 0 0 0 0 0 0 0
Example 1-3
how the status of the CY, AC and P flag after the addition of 88H and
S
93H in the following instructions.
MOV A, #88H
ADD A, #93H ; after the addition A=1BH, CY=1
Solution:
1
88 1 0 0 0 1 0 0 0
+ 93 + 1 0 0 1 0 0 1 1
1 1B 1 0 0 0 1 1 0 1 1
F8h FFh
F0h B F7h
E8h EFh
E0h ACC E7h
D8h DFh
D0h PSW D7h
C8h CFh
C0h C7h
B8h IP BFh
B0h P3 B7h
A8h IE AFh
A0h P2 A7h
98h SCON SBUF 9Fh
90h P1 97h
88h TCON TMOD TL0 TL1 TH0 TH1 8Fh
80h PO SP DPL DPH PCON 87h
1. 8-bit CPU.
2. 4 Kbytes Internal ROM (Program Memory).
3. 128 bytes Internal RAM (Data Memory).
4. It has four 8-bit ports (Port 0, 1, 2, & 3), total 32 input/output lines.
5. Two 16-bit timers (T0 & T1).
6. One Full duplex serial communication port (data Transmitter/ Receiver).
7. Six Interrupt sources.
8051 Microcontroller 15
P1.0 1 40 VCC
P1.0 1 40 VCC
P1.1 2 39 P0.0 (AD0)
P1.2 3 38 P0.1 (AD1)
P1.3 4 37 P0.2 (AD2)
A total of 32
Port 1
P1.4 5 36 P0.3 (AD3)
pins are set
Port 0
P1.5 6 35 P0.4 (AD4) aside for the
P1.6 7 34 P0.5 (AD5) four ports P0,
P1.7 8 33 P0.6 (AD6) P1, P2, P3,
RST 9 32 P0.7 (AD7) where each
(RXD) P3.0 10 31 ––– port has 8 pins
EA/VPP
–––––
(TXD) P3.1 11 8051 30 ALE/PROG
–––– 12 29 ––––––
(INT0) P3.2 PSEN
––––
(INT1) P3.3 13 28 P2.7 (A15)
Port 3
(T0) P3.4 14 27 P2.6 (A14)
(T1) P3.5 15 26 P2.5 (A13)
––––
(WR ) P3.6 16 25 P2.4 (A12) Port 2
–––
(RD) P3.7 17 24 P2.3 (A11)
XTAL2 18 23 P2.2 (A10)
XTAL1 19 22 P2.1 (A9)
GND 20 21 P2.0 (A8)
P0.0
P0.1
Port 0
P0.2
8051 P0.3
P0.4
P0.5
P0.6
P0.7
Solution:
The P0 is 1st loaded with 55H = 01010101 and its complement i.e. 10101010 = AAH
is given to P0 continuously.
BACK: MOV A, #55H
MOV P0, A
ACALL DELAY ; Delay routine not shown
MOV A, #0AAH
MOV P0, A
ACALL DELAY ; Delay routine not shown
SJMP BACK
Solution:
MOV A, #55H
BACK: MOV P1, A
ACALL DELAY
CPL A ; complement register A
SJMP BACK
Solution:
MOV A, #0FFH ; A=FF hex
MOV P1, A ; make P1 an input port by writing it all 1s
MOV A, P1 ; get data from P1
MOV R3, A ; save it to in register R3
ACALL DELAY ; wait
MOV A, P1 ; another data from P1
MOV R1, A ; save it to in register R1
2F 7F 7E 7D 7C 7B 7A 79 78
2E 77 76 75 74 73 72 71 70
2D 6F 6E 6D 6C 6B 6A 69 68
2C 67 66 65 64 63 62 61 60
2B 5F 5E 5D 5C 5B 5A 59 58
2A 57 56 55 54 53 52 51 50
29 4F 4E 4D 4C 4B 4A 49 '48
28 47 46 45 44 43 42 41 46
27 3F 3E 3D 3C 3B 3A 39 38
26 37 36 35 34 33 32 31 30
25 2F 2E 2D 2C 2B 2A 29 28
Bit Address
24 27 26 25 24 23 22 21 20
23 1F 1E 1D 1C 1B 1A 19 18
22 17 16 15 14 13 12 11 10
21 0F 0E 0D 0C 0B 0A 09 08
20 07 06 05 04 03 02 01 00
Byte Address
• The area of bit addressable RAM is usually used to store bit variables.
• The address range from 20h to 2Fh (16 bytes) is bit-addressable RAM. Each bit
can be accessed from 00H to 7FH.
• The total bit addressable location are 16 bytes x 8 bits = 128 bits.
• Each bit can be accessed from 00H to 7FH.
• The programming using bit addressable area saves wastage of memory.
Note: For example, Bit 0 of byte 20h has the bit address 0, and bit 7 of byte 2Fh
has the bit address 7Fh).
F8h FFh
F0h B F7h
E8h EFh
E0h ACC E7h
D8h DFh
D0h PSW D7h
C8h CFh
C0h C7h
B8h IP BFh
B0h P3 B7h
A8h IE AFh
A0h P2 A7h
98h SCON SBUF 9Fh
90h P1 97h
88h TCON TMOD TL0 TL1 TH0 TH1 8Fh
80h PO SP DPL DPH PCON 87h
• There are 21 Special function registers (SFR) in 8051 micro controller and these
are Register A, Register B, PSW, PCON etc. and each of these registers are of
1 byte size. Some of these special function registers are bit addressable, while
some are byte addressable.
• SFRs are used to control timers, counters, serial ports, I/O ports and
peripherals.
External RAM
FFFFH
0000 H
Fig. 1.8.5: External RAM
• External data memory is 64 K Bytes read/write memory.
• The external data memory is indirectly accessed through a Data Pointer Register,
it is slower than access to internal data memory.
Program Memory
––– –––
EA = 1 EA = 0
FFFFH FFFFH
External
program
memory
0000H 0000H
––– –––
• The Program memory accessed through EA pin. The EA is an active low
input.
––– –––
• When EA is connected to VCC i.e. EA =1, the 8051 can access 4 K bytes of
internal ROM i.e. 0000H to 0FFFH and external ROM of 60 K bytes i.e. 1000H
to FFFFH.
––– –––
• When EA is connected to GND i.e., EA =0, then all program fetches are directed
to external ROM i.e. 0000H to FFFFH.
Pins of 8051 used for external memory interfacing and list their functions.
The pins which are used for external memory interfacing are:
––
–– –––– –––– –––– –––––– –––––
––
EA, R D, WR , OE , PS E N, & AL E
Refer pin details of 8051 to explain the functions of each pin.
D0
P0
D7
–––
EA +VCC RAM
L
A A0
T
C A7
8051 ALE
CLK H ADDR
P2 A8
A15
––– –––
P3 RD O E
––– –––
WR WR
––– ––––
• The RD & WR pins are used when a RAM has to be accessed.
–––
• When RD = 0, a data byte can be read from a RAM location.
––––
• When WR= 0, a data byte can be written into a RAM location.
D0
P0
D7
–––
EA L ROM/
8051 A A0 EPROM
T
C A7
ALE
H ADDR
P2 A8
A15
–––––– –––
PSEN OE
Example 1.8:
Interface 4K RAM to 8051 Microcontroller
WR WR
RD OE
A15
A14
A13 CE
A12
Port 2 A11
A11
8 A10 A10 4K
A9 A9
0 A8 A8 RAM
ALE
5
AD7 A7
1 7
AD6 A6
AD5 4 A5
Port 0 AD4 3 A4
AD3 A3
AD2 7 A2
AD1 A1
3
AD0 A0
D0D1D2D3 D4 D5D6 D7
Example 1.9:
Interface 4K ROM to 8051 Microcontroller
VCC
EA
PSEN CE
OE
A11 A11
A10 A10
8 4K
A9 A9
0 A8 A8 ROM
ALE
5
AD7 A7
1 7
AD6 A6
AD5 4 A5
Port 0 AD4 3 A4
AD3 A3
AD2 7 A2
AD1 A1
3
AD0 A0
5V
VSS
D0D1D2D3 D4 D5D6 D7
Example 1.10:
Interface 8K RAM to 8051 Microcontroller
P3.7 RD
P3.6 WR
PSEN A15
A14 CE WE OE
P2.7 A13 A13
8 A12 A12
8Kx8
0 P2.0 A8
ALE G Data
5
P0.7 AD7 D Q A7 RAM
1
74LS373
P0.0 AD0 A0 A0
OC D7 D0
D7
D0
Fig.1.9.6: Interface 8K RAM to 8051 Microcontroller
Example 1.11:
Interface 8K ROM to 8051 Microcontroller
Describe the method of interfacing 8K PROM to 8051 microcontroller 10-Marks
P3.7 VCC
EA RD
P3.6 WR
PSEN CE OE VPP
8 P2.7
A12 A12
0 P2.0 A8 A8 2864
(2764)
5 ALE G
8Kx8
1 P0.7 AD7 D Q A7
Program
74LS373 ROM
VCC P0.0 AD0 A0 A0
OC D7 D0
VSS
D7
D0
Fig.1.9.7a: Interface 8K ROM to 8051 Microcontroller
32 8051 Microcontroller
74LS373
P0.0 AD0 A0 A0
OC D7 D0
D7
D0
Fig.1.9.7 b: Interface 8K DATA ROM to 8051 Microcontroller
D7
D0
Fig.1.9.7 c: Interface 8K of single external ROM for both CODE and DATA
8051 Microcontroller 33
Example 1.12:
Interface 8K EPROM & 4K RAM to 8051 Microcontroller
VCC VCC
WR RD OE OE WE
PSEN CE
A15
A14
A13 CE
A12 A12 A12
Port 2 A11 A11
A11
8 A10 A10 8K A10 4K
A9 A9 A9
0 A8 A8 RAM/ A8 RAM
ALE EPROM
5
AD7 A7 A7
1 7
AD6 A6 A6
AD5 4 A5 A5
Port 0 AD4 A4 A4
3 A3 A3
AD3
AD2 7 A2 A2
AD1 A1 A1
AD0
3 A0 A0
D0 D1 D2 D3 D4 D5 D6 D7 D0 D1 D2 D3 D4 D5 D6 D7
Example 1.13:
Interface 16K EPROM & 8K RAM to 8051 Microcontroller.
VCC VCC
WR RD OE OE WE
EA CE
PSEN
A15
A14
CE
A13 A13
A12 A12 A12
Port 2 A11 A11
A11
8 A10 A10 16K A10 8K
A9 A9 A9
0 A8 A8 ROM/ A8 RAM
ALE EEPROM
5
AD7 A7 A7
1 7
AD6 A6 A6
AD5 4 A5 A5
Port 0 AD4 3 A4 A4
AD3 A3 A3
AD2 7 A2 A2
AD1 A1 A1
AD0
3 A0 A0
D0 D1 D2 D3 D4 D5 D6 D7 D0 D1 D2 D3 D4 D5 D6 D7
Example 1.14:
Interfacing 8 Kbyte RAM and 8 Kbyte ROM to 8051 microcontroller.
VCC VCC
WR RD OE OE WE
PSEN CE
A15
A14
A13 CE
A12 A12 A12
Port 2 A11 A11
A11
8 A10 A10 8K A10 8K
A9 A9 A9
0 A8 A8 ROM A8 RAM
ALE
5
AD7 A7 A7
1 7
AD6 A6 A6
AD5 4 A5 A5
Port 0 AD4 A4 A4
3 A3 A3
AD3
AD2 7 A2 A2
AD1 A1 A1
AD0
3 A0 A0
D0 D1 D2 D3 D4 D5 D6 D7 D0 D1 D2 D3 D4 D5 D6 D7
Example 1.15:
Interfacing 8 Kbyte RAM and 8 Kbyte ROM to 8051 microcontroller.
P0.0 74LS373
AD0 A0 A0 A0
OC D7 D0 D7 D0
D7
D0
Fig.1.9.11: Interfacing 8 Kbyte RAM and ROM with 8051.
Example 1.16:
Interfacing 16 Kbyte DATA RAM, DATA ROM and PROM to 8051
microcontroller.
P3.7 RD
EA
P3.6 WR
PSEN
74LS138
P2.6 A14 A Y0
P2.7 B Y1 VCC VCC
A15
C Y2
G2B Y3
G2A G1
8051 CE WE OE OE OE
VCC CE CE
A13 A13 A13 A13
PD.0 74LS373 A0 A0 A0
AD0 A0
OC D7 D0 D7 D0 D7 D0
Fig.1.9.12: Interfacing 16 Kbyte DATA RAM, DATA ROM and PROM to 8051
microcontroller.
8051 Microcontroller 37
Example 1.17:
Identify to which Memory Location (ML) the data is moved after the
execution of the following program segment
SETB RS1
CLR RS0
MOV R1,#25h
MOV R3,#65h 5-Marks
Solution.
• The figure below gives the details of the banks and their memory location (ML).
Bank 0 Bank 1 Bank 2 Bank 3
Hex Hex Hex Hex
07 R7 0F R7 17 R7 1F R7
06 R6 0E R6 16 R6 1E R6
05 R5 0D R5 15 R5 1D R5
04 R4 0C R4 14 R4 1C R4
03 R3 0B R3 13 R3 1B R3
02 R2 0A R2 12 R2 1A R2
01 R1 09 R1 11 R1 19 R1
00 R0 08 R0 10 R0 18 R0
• After execution of above code, Bank 2 is selected and is shown in below table.
RS1 RS0 Bank Selected Address
1 0 Bank 2 10H – 17H
• From above diagram it is clear that in Bank 2, R1 memory location is 11H and
R2 memory location is 12H.
Bank 2 Selected
Register Memory location
R1 11H
R2 12H
2
8051 Instruction Set
2.1 INTRODUCTION
Computer languages are mainly classified into three types:
1. Low Level Languages 2. Middle Level Language 3. High Level Language
Computer Languages
C = A + B;
C C++ java
High Level Language
Hardware
38
8051 Instruction Set 39
Advantages:
1. More standardize and easier than machine languages.
2. Operate efficiently.
3. Easy to debug programs.
Disadvantages:
1. Assembly language is defined for a specific machine and specific processor.
Therefore, programs are not portable to other computers.
2. Source programs tend to be large and difficult to follow.
3. Many instructions are required to achieve small tasks.
4. Easy for the computer to understand but are more difficult for the programmer
to write (Complex).
5. The program has to be translated into machine code in order to work.
Advantages:
1. Easier to read, write and maintain.
2. High-Level languages make complex programming simpler.
3. Error ratio is less in high level language and debugging is easier.
4. Length of the program is also small compared with low-level language.
5. Many real time problems can be easily solved with high level language.
6. Portable ( can work across different CPU families and support a wide range of
data types)
Disadvantages:
1. Usually slower than lower-level languages (for example assembler is fastest than C).
ORG (origin)
• The ORG directive is used to indicate the beginning of the address.
• The number that comes after ORG can be either in hex or in decimal.
• If the number is not followed by H, it is decimal and the assembler will convert
it to hexadecimal.
• Some assemblers use “. ORG” (dot ORG) instead of “ORG” for the origin directive.
Example: ORG 1000H
DB (Define data)
• It is used to define the 8-bit data and most widely used data directive in the
assembler.
• When DB is used to define data, the numbers can be in decimal, binary, hex,
or ASCII formats. For decimal, the “D” after the decimal number is optional,
“B”for binary and “H” for hexadecimal.
• To indicate ASCII, simply place the characters in single quotes or double
quotes. The assembler will assign the ASCII code for the numbers or characters
automatically.
• The DB directive is the only directive that can be used to define ASCII strings larger
than two characters; therefore, it should be used for all ASCII data definitions.
Examples:
ORG 1000H
DATA1: DB 40 ;DECIMAL NUMBER
DATA2: DB 00100111B ; BINARY NUMBER
DATA3: DB 1Fh ;HEXADECIMAL NUMBER
DATA4: DB “DIPLOMA” ;ASCII CHARACTER
DATA5: DB “2016” ;ASCII NUMBER
END
EQU
• EQU is used to define a constant without occupying a memory location.
• The EQU directive does not set aside storage for a data item but associates a
constant value with a data label.
• When the label appears in the program, its constant value will be substituted
for the label.
• Assume that there is a constant used in many different places in the program,
and the programmer wants to change its value throughout. By the use of EQU,
one can change it once and the assembler will change all of its occurrences.
8051 Instruction Set 43
Example:
ORG 1000H
COUNT EQU 40H
MOV A,#COUNT ; COPY 40 INTO A
END
• EQU indicates to the assembler the end of the source (asm) file.
• The END directive is the last line of an 8051 program, meaning that in the
source code anything after the END directive is ignored by the assembler.
• Some assemblers use “. END” (“dot END”) instead of “END”.
Example:
ORG 1000H
COUNT EQU 40H
MOV A,#COUNT ; COPY 40 INTO A
END
NOTE:
• The “#” sign distinguishes between the immediate and direct addressing mode.
The absence of the “#” sign is the direct addressing mode.
8051 Instruction Set 45
Advantages
• The advantage is that it makes accessing data dynamic rather than static as in
direct addressing mode. Looping is not possible in direct addressing mode.
Limitations
• R0 and R1 are the only registers that can be used for pointers in register indirect
addressing mode Since R0 and R1 are 8 bits wide, their use is limited to access
any information in the internal RAM.
• The accessing of externally connected RAM or on-chip ROM need 16-bit pointer.
In such case, the DPTR register is used.
NOTE:
• Indexed addressing mode is widely used in accessing data elements of look-up
table entries located in the program ROM.
Table 2.1.1: Nomenclatures for register, data, address and variables are used
while write instructions.
A Accumulator
B “B” register
C Carry bit
Rn Register R0 - R7 of the currently selected register bank
Direct 8-bit internal direct address for data. The data could be in lower 128
bytes of RAM (00 - 7FH) or it could be in the special function register
(80 - FFH).
@Ri 8-bit external or internal RAM address available in register R0 or R1.
This is used for indirect addressing mode.
8051 Instruction Set 47
Arithmetic Instructions
Syntax Flags affected Bytes Cycles
ADD A, #data CY, OV & AC 2 1
Operation (A) (A) + 8-bit data
Description Adds the 8-bit immediate data with accumulator contents and
result is stored in accumulator.
Example ADD A, #04H
Before Execution After Execution
A = 05H A = 09H
Result: Result:
4 5 H 5 0 H
+ 1 5 H + 5 5 H
Flags
Mnemonics Byte Cycle Operation
Affected
ADD A, #data 2 1 (A) (A) + 8-bit data CY, OV & AC
ADD A, Rn 1 1 (A) (A) + (Rn) CY, OV & AC
ADD A, direct 2 1 (A) (A) + (direct address) CY, OV & AC
ADD A, @Ri 1 1 (A) (A) + ((Ri)) CY, OV & AC
ADDC A, #data 2 1 (B) (A) + (C) + 8-bit data CY, OV & AC
ADDC A, Rn 1 1 (B) (A) + (C) + (Rn) CY, OV & AC
ADDC A, direct 2 1 (A) (A) + (C) + (direct address) CY, OV & AC
ARITHMETIC INSTRUCTIONS
ADDC A, @Ri 1 1 (A) (A) + (C) + ((Ri)) CY, OV & AC
SUBB A,#data 2 1 (A) (A) - #-bit data CY, OV & AC
SUBB A, Rn 1 1 (A) (A) - (Rn) CY, OV & AC
SUBB A, direct 2 1 (A) (A) - (direct address) CY, OV & AC
SUBB A, @Ri 1 1 (A) (A) - ((Ri)) NONE
INC A 1 1 (A) (A) + 1 NONE
INC Rn 1 1 (Rn) (Rn) + 1 NONE
INC direct 2 1 (direct) (direct) + 1 NONE
INC @Ri 1 1 ((Ri)) ((Ri)) + 1 NONE
DEC A 1 1 (A) (A) - 1 NONE
54 8051 Microcontroller
If (A)7-4> 9 or (CY) = 1
Then
Add +6 to (A)7-4
(SP) (direct)
Description Push onto Stack
• The stack pointer is incremented by one. The content of the
indicated variable is then copied into the internal RAM location
address by the stack pointer.
• The PUSH instruction supports only direct addressing mode.
Therefore, PUSH A, PUSH R0 etc. are invalid instructions.
Example 1. PUSH 0E0H ; 0E0H is the RAM address of Accumulator.
Example RL A
Before Execution After Execution
A = C2 H A = 85H
Carry flag
Example RLC A
Before Execution After Execution
A = C2 H & CY = 0 A = 84H & CY =1
68 8051 Microcontroller
7 6 5 4 3 2 1 0
PRA
Example RR A
Before Execution After Execution
A = C2 H A = 61H
7 6 5 4 3 2 1 0 C
Carry flag
Example RRC A
Before Execution After Execution
A = C2 H & CY = 0 A = 61H & CY = 0
Logical Instructions
Mnemonics Byte Cycle Operation Flags
Affected
8051 Instruction Set 69
Boolean Instructions
Syntax Flags affected Bytes Cycles
CLR C CY 1 1
Operation (CY) 0
Description Clear the carry flag bit.
Example CLR C
Before Execution After Execution
CY = 1 CY = 0
Boolean Instructions
Mnemonics Byte Cycle Operation Flags Affected
CLR C 1 1 (CY) 0 CY
CLR bit 1 1 (bit) 0 NONE
SETB C 1 1 (CY) 1 CY
SETB bit 2 1 (bit) 1 NONE
CPL C 1 1 (CY) NOT(CY) CY
CPL bit 2 1 (bit) NOT(bit) NONE
ANL C,bit 2 2 (C) (C) AND (bit) CY
ANL C,/bit 2 2 (C) (C) AND [ NOT(bit) ] CY
ORL C,bit 2 2 (C) (C) OR (bit) CY
ORL C,/bit 2 2 (C) (C) OR [ NOT(bit) ] CY
MOV C,bit 2 1 (C) (bit) CY
MOV bit,C 2 2 (bit) (C) NONE
RETI NONE 1 2
Operation (PC)15-8 (SP)
(SP) (SP)-1
(PC)7-0 (SP)
(SP) (SP) -1
Description Absolute subroutine call.
• RET instruction is used at the end of an Interrupt Service Routine
(ISR). The top two bytes of the stack are popped in the program
counter (PC), the stack pointer (SP) is decremented by 2.
P1 P2 P1 P2 P1 P2 P1 P2 P1 P2 P1 P2
S1 S2 S3 S4 S5 S6
One machine cycle
6 states, 12 pulses
In 8051, two pulses constitute a state and machine cycle is made up of six
states. Some instructions may require more than one machine cycle.
The time required to execute an instruction is given by
C × 12d
T=
f
Where, T is the time for instruction to be executed
f is the crystal frequency and
C is the number of machine cycles.
Example2.1
For 8051 microcontroller, find the time taken for an instructions which takes
i) 1 Machine cycle ii) 2 Machine cycles iii) 4 Machine cycles
Solution:
C × 12d 1 × 12
i) T= = = 1.085 µSec
f 11.0592 × 106
C × 12d 2 × 12
ii) T= = = 2.170 µSec
f 11.0592 × 106
C × 12d 4 × 12
iii) T= = = 4.340 µSec
f 11.0592 × 106
88
8051 Stack, I/O Port Interfacing and Programming 89
0Bh 0Bh
0Ah 0Ah
Sp = Sp+1
09h Sp = 08h 09h
30 Sp = 08h
08h 08h
Sp = 07h
Example 3.2
ORG 00H
MOV R2, #30H
MOV R3, #40H
MOV R4, #41H
PUSH 2
PUSH 3
PUSH 4
END
Solution:
0Bh
0Ah
09h
08h
After Execution
Example 3.3
ORG 00H
MOV SP, #30H
SETB PSW.3
MOV R0, #0FFH
MOV R1, #0EEH
MOV A, #01H
PUSH 8
PUSH 9
PUSH 0E0H
END
Solution:
Before execution After execution
34h 34h
33h 33h
01 Sp
32h 32h
EE
31h 31h
EF
30h 30h
Sp = 30h Sp = 32h
Example 3.4:
POP 4
POP 3
POP 2
8051 Stack, I/O Port Interfacing and Programming 91
Solution:
Before execution
FF Sp = 0Bh
0Bh
41
0Ah
40
09h
30
08h
After execution
i) Relative range:
• The Jump can be within –128 bytes. (for backward Jump) or +127 bytes (for
forward Jump) of memory relative to the address of current program counter
(PC).
• Jump or call instruction with relative range will be of 2-byte instructions. The
1st byte is opcode and second byte is relative address of target location.
92 8051 Microcontroller
Next Page
SADD Limit
SADD Limit
This Page
LADD Limit
0000
Fig. 3.2.1 Jump instruction ranges
Note: SADD: Short address, LADD: Long address
ii) Absolute range:
• In 8051, program memory is divided into logical divisions called pages each of
2k byte.
• Maximum size program memory is 64 K bytes. Size of each page is 2K bytes.
64 Kb
Maximum number of pages = = 32 pages
2 Kb
8051 Stack, I/O Port Interfacing and Programming 93
7d1h F231h
0000H
(2001d) (62,001d)
16 - bit PC
5 bit 11 bit
Program
Long range
M/M
0000h
• This range allows the Jump to any where in the memory location from 0000h
to FFFFh.
• The Jump or call instructions with this range will be of 3 byte instructions in
which 1st byte is opcode and 2nd and 3rd bytes represents the 16-bit address of
target location.
94 8051 Microcontroller
3.3 Subroutine
A subroutine is a program that may be used many times in the execution of a larger
program. The subroutine could be written into the body of the main program everywhere
it is needed, resulting in the fastest possible code execution.
Program Counter
PCH PCL
SP + 2 PCH SP + 2
SP + 1 PCL SP + 1
Stack area RET RETI
SP SP
PCH PCL
Program Counter
ACALL LCALL
Interrupt Internal RAM
Fig.3.3.1: Storing and retrieving the return address
8051 Stack, I/O Port Interfacing and Programming 95
Example 3.6:
Factorial of an 8 bit number (result maximum 8 bit)
Solution:
The factorial of a number is given by
N! = N x (N-1) x (N-2) x…..x 3 x 2 x 1
ORG 00h
MOV A,#01H
MOV B,A
UP: MUL AB
INC A
CJNE B,#06H, UP
END
Result: 6 x 5 x 4 x 3 x 2 x 1 = 120d = 78H
Example 3.7:
Factorial of an 8 bit number (result more than8 bit)
Solution:
ORG 00h
MOV A,#01H
MOV B,A
UP: MUL AB
INC A
CJNE B,#07H, UP
END
Result: 6 x 5 x 4 x 3 x 2 x 1 = 720d = 2D0H
Example 3.8:
Block move without overlap
Solution:
ORG 0000H : Specifying starting address
MOV R0, #50H : m
ove immediate data 50H into reg R0 [Source
location]
MOV R1, #60H : m
ove immediate data into 60H reg R1
[Destination location]
MOV R2, #0AH : m
ove immediate data into 0AH reg R2 [Counter
register]
8051 Stack, I/O Port Interfacing and Programming 97
Example 3.9:
Example 3.10:
O/P:
O/P: O/P:
O/P O/P
O/P:
O/P:
O/P: O/P:
O/P:
Example 3.11:
Interfacing simple switch and LED to I/O ports to switch on/off LED with
respect to switch status.
Solution:
• If SW is closed i.e. P0.0=0. Now Turn off the LED by making P2.0=1 (The cathode
is high and turns off the LED)
• If SW is open i.e. P0.0=1. Now Turn on the LED by making P2.0=0 (The cathode
is low and turns off the LED)
M.Tech, Lecturer in E&CE Dept. S.T.J.I.T, Ranebennur.
M.Tech, Lecturer in E&CE Dept. S.T.J.I.T, Ranebennur.
8051 Stack, I/O Port Interfacing and Programming 99
VCC = 5V
R 2.2K
LED
P2.0
5V
8051
R 10K
R 3 SW
VSSP0.0 2 1
10K
mm
R0,#20H R0,#20H
Assembly Language Programs
MOV
MOV
MOVR0,#20H
R1,#30H MOVR0,#20H
R1,#30H
BLOCK MOVE BLOCK EXCHANGE
coo
MOV
UP: R1,#30H MOV
UP: R1,#30H
ORG 00H ORG 00H
UP: UP: MOV A,@R0
MOV A,@R0
MOV R2,#04H MOV R2,#04H
MOV
MOVA,@R0 MOVMOV
R0,#20H
A,@R0
p.c.
MOV R0,#20H
@R1,A XCH A,@R1
MOV R1,#30H MOVXCH
R1,#30H
A,@R1
MOV
INC @R1,A
R0 XCH
MOV A,@R1
@R0,A
UP:
uup
UP:
INC
INCR0R1 MOVMOV
INC @R0,A
A,@R0
R0
MOV A,@R0
XCHINC
A,@R1
roro
INC R1 R2,UP
DJNZ INCR0R1
MOV @R1,A
MOV @R0,A
INC R0
DJNZ
ENDR2,UP INC R1 R2,UP
INC DJNZ
R0
stsgg
INC R1
END INCDJNZ
R1 R2,UP
END
DJNZ R2,UP DJNZ
ENDR2,UP
I/P:
END END
I/P: I/P:
I/P I/P
I/P:
nnt
dee
O/P:
O/P:
O/P
uud
sst t
Continued...
O/P:
tiyty
O/P:
tu
8051 Stack, I/O Port Interfacing and Programming 101
ys
ADDITION
ADDITIONOFOF
TWO 16-BIT
TWO 16-BIT NUMBERO/P: SUBTRACTION
NUMBER SUBTRACTION OFOF
TWO 16-BIT
TWO 16-BIT
(MULTIBYTE
(MULTIBYTEADDITION)
ADDITION) O/P NUMBER
NUMBER(MULTIBYTESUBTRACTION)
(MULTIBYTESUBTRACTIO
ADDITION OF TWO 16-BIT NUMBER SUBTRACTION OF TWO 16-BIT
t
ADDITION OF TWO 16-BIT NUMBER SUBTRACTION OF TWO 16-BIT
(MULTIBYTE ADDITION) NUMBER (MULTIBYTESUBTRACTION)
i
(MULTIBYTE
ORG 00H ADDITION) NUMBER ORG(MULTIBYTESUBTRACTIO
00H
MOV
ORG
ORG 00H
MOVR7,#02H
00HR7,#02H
ORG 00H
. c MOV
ORG
ORG 00H
MOVR7,#02H
00H R7,#02H
ORG 00H
w
MOV MOVR0,#20H
R7,#02H MOV R0,#20H
R7,#02H
MOV R0,#20H
R7,#02H MOV
MOV R0,#20H
R7,#02H
MOV R1,#40H
R0,#20H MOV R1,#40H
R0,#20H
w
MOV R1,#40H
c coo
MOV R0,#20H MOV
MOV R1,#40H
R0,#20H
UP:MOV R1,#40H
UP:MOV R1,#40H UP:MOV R1,#40H
UP:MOV R1,#40H
p.p.c..c
ADDITION OF TWO 16-BIT NUMBER SUBTRACTION OF TWO 16-BIT
w
ououuupp
ADDC A,@R1 MOV A,@R0
SUBB A,@R1
MOV A,@R0 MOV A,@R0
MOVMOV
R7,#02H
@R1,A MOV R7,#02H
ADDCMOV A,@R1 MOV
SUBB @R1,A
A,@R1
ADDC@R1,A
MOV R0,#20H A,@R1 MOV
MOV R0,#20HSUBB@R1,A
A,@R1
MOVINC
MOV R0
INC@R1,A
R1,#40HR0@R1,A MOV R1,#40H
INC
MOV R0
INC@R1,A
R0@R1,A
grgrorro
MOV MOV
UP: INCINCR1
R0 UP: INC R1
R0
INC R1
MOV A,@R0 R0 MOV A,@R0INC
INC R1
R0
DJNZ
ADDC R1R7,UP
INCA,@R1
DJNZ R7,UP SUBB DJNZ
A,@R1 R1R7,UP
INCDJNZ
MOVJNC
DJNZ
tsstsgsg
$581.80$5*
INC R1
@R1,A
NOCARRY
R7,UP
JNC NOCARRY
INC R0DJNZ R7,UP
INC
JNC R2
NOCARRY
INC R1JNC NOCARRY
INC R2
MOV @R1,A
INC R0
JNC
DJNZ
INC
JNC
INC R1 INC
JNC
DJNZ
R2
R7,UP
INCRanebennur.
M.Tech, Lecturer in E&CE Dept. S.T.J.I.T, R1
NOCARRY
R7,UP
NOCARRY
R7,UP
NOCARRY
JNCR2
enennnt t
NOCARRY
NOCARRY: DJNZ
MOV
INCR7,UP
NOCARRY: MOV R2A,R2
A,R2 DJNZ
NOCARRY: R7,UP
MOV
INC R2A,R2
INC R2 NOCARRY: MOV A,R2
JNC NOCARRY JNC NOCARRYINC R2
NOCARRY: MOV @R1,A
A,R2 NOCARRY: MOV @R1,A
A,R2
ududddee
INC R2MOV
NOCARRY: MOV@R1,A
A,R2 INC R2 MOV
NOCARRY: MOV@R1,A
A,R2
NOCARRY: MOVEND
MOVA,R2
END@R1,A NOCARRY: MOV A,R2
END
MOVEND@R1,A
MOV @R1,A MOV @R1,A
I/P:I/P: MOVEND@R1,A MOV @R1,A
I/P:I/P: END
END END END END
ststuttu
I/P: I/P:
I/P I/P: I/P I/P:
ityiytysys
.c citit
w .c..c
O/P: O/P:
O/P:
O/P
w www
O/P O/P:
O/P: O/P:
O/P: O/P:
wwwww
ww
ORG
Hexadecimal to00H
Hexadecimal BCD
to BCD ORG
BCD 00H
BCD
to Hexadecimal
to Hexadecimal
ORG 00H ORG 00H
MOV A,30H MOV A,20H
102 MOV A,30H MOV A,20H 8051 Microcontroller
ORG
MOV
ORG
00H00H
B,#0AH ORG ORG
00H00H
MOV B,#10H
MOV B,#0AH MOV B,#10H
MOV MOV
A,30H
DIV A,30H
AB MOV MOV
A,20H
DIV A,20H
AB
DIV AB DIV AB
Hexadecimal
MOV to BCD
B,#0AH
B,#0AH BCD to Hexadecimal
MOV 33H,B MOV MOV B,#10H
B,#10H
R2,B
MOV 33H,B
ORG 00H ORG 00HR2,B
MOV
DIVMOV
DIV
AB AB
B,#0AH DIV
AB AB
DIVMOV B,#0AH
MOV A,30H MOV B,#0AH MOV
MOVA,20H
B,#0AH
MOV MOV
33H,B
33H,B
MOV B,#0AH DIVDIV AB
AB MOV
MOV
MUL
MOV
MUL
B,#10H
AB
R2,B
R2,B
AB
DIV AB MOV MOV
B,#0AH
B,#0AH
32H,B DIV
MOVAB
MOV
ADD B,#0AH
B,#0AH
A,R2
MOV 32H,B ADD A,R2
MOV 33H,B DIVDIV AB AB
MOV 31H,A MOV
MULR2,B
MUL
AB AB
MOV 31H,A MOV 21H,A
MOV B,#0AH MOV 21H,A
MOV B,#0AH
MOV MOV
32H,B
END 32H,B ADD ADD
A,R2
END A,R2
DIV AB END MUL
ENDAB
MOV MOV
31H,A
31H,A MOV MOV 21H,A
21H,A
MOV 32H,B ADD A,R2
I/P: ENDEND I/P:ENDEND
MOV 31H,A
I/P: I/P: MOV 21H,A
END END
I/P I/P:I/P: I/P
I/P:I/P:
O/P:
O/P: O/P:
O/P O/P:
O/P
O/P:O/P: O/P:O/P:
I/P
I/P: I/P:
I/P
I/P: I/P:
O/P:
O/P O/P: O/P:
O/P O/P:
O/P:
O/P: O/P:
O/P:
ASCENDING DESCENDING
ORG 00H ORG 00H
MOV R7,#03H MOV R7,#03H
MAIN: MOV R0,#30H MAIN: MOV R0,#30H
MOV R6,#03H MOV R6,#03H
UP: MOV A,@R0 UP: MOV A,@R0
INC R0 INC R0
MOV B,@R0 MOV B,@R0
CJNE A,B,NEXT CJNE A,B,NEXT
NEXT: NEXT:
JC NOEXCHANGE JNC NOEXCHANGE
MOV @R0,A MOV @R0,A
DEC R0 DEC R0
MOV @R0,B MOV @R0,B
INC R0 INC R0
NOEXCHANGE: NOEXCHANGE:
DJNZ R6,UP DJNZ R6,UP
DJNZ R7,MAIN DJNZ R7,MAIN
END END
Continued...
DJNZ R7,MAIN DJNZ
DJNZR7,MAIN
R7,MAIN
DJNZ
DJNZ R6,UP
R6,UP DJNZ
DJNZR6,UP
R6,UP
END
END END
DJNZ R7,MAIN END
DJNZ R7,MAIN
DJNZ R7,MAIN DJNZ R7,MAIN
END
8051 Stack, I/O Port Interfacing
END and Programming END
END 105
I/P:
I/P: I/P:
I/P:
SERIALCOMMUNICATION
SERIAL COMMUNICATION SERIALCOMMUNICATION
SERIAL COMMUNICATION
I/P:
I/P:I/P I/P I/P:
I/P:
ORG00H
ORG 00H ORG00h
ORG 00h
MOVTMOD,#20H
MOV TMOD,#20H MOVTMOD,#20h
MOV TMOD,#20h
O/P: MOVTH1,#-3
MOV TH1,#-3 MOVTH1,#-3
MOV TH1,#-3
O/P
O/P: O/P O/P:
O/P:
MOVSCON,#50H
MOV SCON,#50H MOVSCON,#50h
MOV SCON,#50h
O/P:
O/P: O/P:
SETBTR1
SETB TR1 O/P: SETBTR1
SETB TR1
UP:MOV
UP: MOVA,A,#'S'
#'S' REPEAT:
REPEAT:
ACALL SEND
ACALLSEND
SERIAL COMMUNICATION MOVDPTR,
SERIAL MOV DPTR,#msg
#msg
COMMUNICATION
ORG 00H MOV
MOVA,A,#'T'
#'T' ORG 00h
UP:CLR
UP: CLRAA
MOV TMOD,#20H
ACALLSEND
ACALL SEND MOV TMOD,#20h
MOVCA,@A+DPTR
MOVC A,@A+DPTR
MOV TH1,#-3 MOV TH1,#-3
MOVA,A,#'J'
MOV #'J' JZ REPEAT
JZ REPEAT
MOV SCON,#50H MOV SCON,#50h
SEND
ACALLSEND
SETB TR1 ACALL SETB TR1ACALL SEND
ACALLSEND
UP: MOV A, #'S'
Lecturer in
M.Tech, Lecturer
#'I'M.Tech,
MOVA,A,#'I'
E&CE
REPEAT:
in Dept.
E&CE S.T.J.I.T,
Dept. Ranebennur.
S.T.J.I.T, Ranebennur.
MOV INCDPTR
INC DPTR
ACALL SENDACALL SEND MOV DPTR, #msg
ACALL SEND
M.Tech, Lecturer inin
E&CE Dept. SJMPUP
SJMP
S.T.J.I.T, UP
Ranebennur.
MOV A, #'T' M.Tech, UP: CLR A
Lecturer E&CE Dept. S.T.J.I.T, Ranebennur.
MOVA,A,#'T'
MOV #'T'
ACALL SEND MOVC A,@A+DPTR
MOV A, #'J'
ACALL SEND
ACALLSEND REPEAT
JZ SEND:
SEND:
ACALL SEND
SJMP UP
SJMPUP ACALL SEND
MOVSBUF,A
MOV SBUF,A
MOV A, #'I' INC DPTR
HERE:JNB
HERE: JNBTI, HERE
TI,HERE
ACALL SEND SJMP UP
MOV A, #'T' SEND: CLRTITI
CLR
ACALL
SENDSEND
SEND: :MOV
MOVSBUF,
SBUF,AA MOV SBUF,A
RET
RET
SJMP UP JNB
HERE:
HERE: JNBTI, HERE
TI,HERE HERE:JNB TI, HERE
CLR TI
CLRTITI
CLR msg:db
msg: db"STJIT",0
"STJIT",0
SEND:MOV SBUF, A RET
RET
HERE:JNB TI, RET
HERE msg: db "RYMEC",0
END
END
CLR TI END
END END
RET
END
O/P:
O/P: O/P:
O/P:
O/P O/P
RYMECRYMEC
RYMECRYMEC
RYMECRYMEC
106 8051 Microcontroller
DELAY: DELAY:
SETB TR0 SETB TR0
HERE: JNB TF0, HERE HERE: JNB TF0, HERE
CLR TR0 CLR TR0
CLR TF0 CLR TF0
RET RET
END END
O/P O/P
COUNTERS
HEX-UP COUNTER HEX-UP COUNTER
(Refer after reading Module-4)
ORG 00H ORG 00H
UP: UP:
MOV P1,A MOV P1,A
INC A INC A
ACALL DELAY ACALL DELAY
SJMP UP SJMP UP
DELAY: DELAY:
MOV R0,#60H MOV TL0,#00H
MOV R1,#0FFH MOV TH0,#00H
MOV R2,#0FFH SETB TR0
BACK: HERE: JNB TF0,HERE
DJNZ R2,BACK CLR TR0
DJNZ R1,BACK CLR TF0
DJNZ R0,BACK RET
RET END
END
108 8051 Microcontroller
DELAY: DELAY:
MOV R0,#60H MOV TL0,#00H
MOV R1,#0FFH MOV TH0,#00H
MOV R2,#0FFH SETB TR0
BACK: HERE: JNB TF0,HERE
DJNZ R2,BACK CLR TR0
DJNZ R1,BACK CLR TF0
DJNZ R0,BACK RET
RET END
END
..... Continued
8051 Stack, I/O Port Interfacing and Programming 109
Appendix
A.1 Introduction to Embedded C and its applicability to 8051
• The use of C language to program microcontrollers is becoming too common
and most of the time it’s not easy to build an application in assembly which
instead you can make easily in C. So it’s important to know C language for
microcontroller which is commonly known as Embedded C.
• The conventional ‘C’ language and its extensions are used for programming
embedded systems, it is referred to as “Embedded C Programming”.
• Embedded “C” can be considered as a subset of conventional “C” language.
• A software program called “Cross compiler” is used for the conversion of
programs written in Embedded “C” to target processor / controller specific
instructions.
• The “C” is the most common embedded language and almost 80% of embedded
applications are coded in “C”.
• With 8051 microcontroller we are going to use Keil C51 Compiler, hence we
also call it Keil C.
Compiler
Compiler is a software tool that converts a source code written in a high level language
on top of a particular operating system running on a specific target processor
architecture.
Cross Compiler
Cross compiler are software tools used in cross platform development applications. In
cross platform development, the compiler running on a particular target processor /
OS converts the source code to machine code for a target processor whose architecture
and instruction set are different from the current development environment (OS).
Keywords
These are the reserved names used by the “C” language. All the keywords should be
written in lowercase letters. ANSI “C” support 32 such keywords.
Examples: int, char, float, void, while, for, long etc.
A.2 Data Types
The data types of 8051 are
1. unsigned char
• Since 8051 is an 8-bit microcontroller and the character data type is also
8-bit. So char data type is most widely used in 8051 C.
• The unsigned char is an 8-bit data type that takes a value in the range of 0
to 255 i.e. 00H to FFH.
• Used for setting a counter value, to represent ASCII character etc.
2. signed char
• The signed char is an 8-bit data type that uses the Most Significant Bit (MSB)
D7 to represent +ve or –ve value.
• So only 7-bits are used to represent the magnitude of the number.
• The signed char ranges from -128 to +127.
• Used to represent quantity having –ve values such as Temperature etc.
3. unsigned int
• The unsigned int is a 16-bit data type that ranges from 0 to 65635 (0000H
to FFFFH).
• The unsigned int is used to define a 16-bit variables such as memory
addresses. It is also used to set counter values of more than 256.
• Since 8051 is an 8-bit microcontroller so the int data type takes two bytes
of RAM. The misuse of int variables will result in a larger HEX file.
4. signed int
• The signed int is a 16-bit data type that uses the MSB i.e. D15 bit to represent
+ve or –ve value.
• So, only 15-bits are used to represent the magnitude of the number.
• The signed int ranges from -32,768 to +32,767.
• Used to represent +ve or – ve values.
5. sbit
• The sbit keyword is used to access single bit addressable registers.
• It allows access to the single bit of the SFR registers.
• Its size is 1-bit i.e. either 0 or 1
6. bit
• The bit data type allows to access single bit of bit-addressable memory
spaces 20H to 2FH.
• Its size is 1-bit i.e. either 0 or 1.
Appendix 115
7. sfr
• The sfr data type is used to access the byte-size SFR registers.
• Its size is 8-bits i.e. 1 byte.
• RAM addresses 80H to FFH are used.
Note: T
he C compilers use the signed char and signed int as the default if we do
not put the keyword unsigned in front of the char and int.
Table A.1: Data types in 8051
C Programs
unsigned char
Example A.1:
Write an 8051 C program to send values 00H - 0BBH to port P3
Solution:
Example A.2:
Write an 8051 C program to send hex values for ASCII characters of 0, 1,
2, 3, 4, 5, A, B, C, D and F to port P1.
Solution:
#include <reg51.h>
void main(void)
{
unsigned char mynums[]=“012345ABCDF”;
unsigned char i;
for (i=0;i<11;i++)
P1=mynums[i];
}
Example A.3:
Write an 8051 C program to toggle all the bits of P2 continuously.
Solution:
//Toggle P2 forever
#include <reg51.h>
void main(void)
{ for (;;)
{
P2=0xAA;
P2=0x55;
}
}
signed char
Example A.4:
Write an 8051 C program to send values of –3 to +3 to port P1.
Solution:
#include <reg51.h>
void main(void)
{
charmynums[]={+1,-1,+2,-2,+3,-3};
unsigned char i;
Appendix 117
for(i=0;i<6;i++)
P1=mynums[i];
}
Note: T
he negative values will be displayed in the 2’s complement for as –1 = FFH,
–2 = FEH, –3 = FDH, –4 = FCH and so on.
unsigned int
Example A.5:
Write an 8051 C program to toggle bit D0 of the port P0 (i.e. P0.0) 50,000
times.
Solution:
#include <reg51.h>
sbit MYBIT=P0^0;
void main(void)
{
unsigned int i;
for (i=0;i<50000;i++)
{
MYBIT=0;
MYBIT=1;
}
}
Example A.6:
Write in 8051 C program to toggle bits of PI continuously forever with
some delay.
Solution:
# include <reg51.h>
void main (void)
{
unsigned int x;
for (;;)
{
Pl=0x55;
for (x=0;x<40000;x++) ; //time delay
Pl=0xAA;
for (x=0;x<40000;x++);
118 8051 Microcontroller
}
}
signed int
Example A.7:
Write an 8051 C program to send values of –5 to +5 to port P1.
Solution:
#include <reg51.h>
void main(void)
{
int mynums[]={+1,-1,+2,-2,+3,-3,+4,-4,+5,-5};
unsigned char i;
for(i=0;i<10;x++)
P1=mynums[i];
}
The negative values will be displayed in the 2’s complement.
single bit
Example A.8:
Write an 8051 C program to toggle bit D0 of the port P0 (P0.0) 50,000
times.
Solution:
#include <reg51.h>
Example A.9:
Write an 8051 C program to toggle only bit P0.1 continuously without
disturbing the rest of the bits of P0.
Solution:
#include <reg51.h>
sbit mybit=P0^1;
void main(void)
{
while (1)
{
mybit =0; // turn on P0.1
mybit =1; // turn off P0.1
}
}
Formulae
1 1
1. Clock Period = = = 0.090 µs
Clock frequency 11.0592 × 106
Example A.10:
The 8051 microcontroller uses a clock frequency of 11.0592 MHz.
Calculate
i) Clock period ‘T’
ii) Time of one machine cycle.
iii) Time delay provided by AAH machine cycles.
Solution:
1 1
Clock
i) Clock ‘T’ ==
Period
period = == 0.090
0.09 µµs
s
Clock frequency 11.0592 × 106
Example A.11:
Write an 8051 C program to toggle bits of P0 continuously forever with
some delay.
Solution:
//Toggle P0 forever with some delay in between “on” and “off”
#include <reg51.h>
void main(void)
{
unsigned int x;
for (;;) //repeat forever or while (1)
{
P0=0x55;
for (x=0;x<1275;x++); //1 ms delay
P0=0xAA;
for (x=0;x<1275;x++); //1 ms delay
}
}
Example A.12:
Write a 8051 C program to toggle all the bits of P0 and P1 continuously
with a 1 ms delay. Use XTAL = 11.0592 MHz.
Solution:
#include <reg51.h>
voidmain(void)
{
unsigned int x;
while(1) //repeat forever
{
P0=0x55;
P1=0x55;
for(x=0;x<1275;x++); //1ms delay
122 8051 Microcontroller
P0=0xAA;
P1=0xAA;
for (x=0;x<1275;x++); //1ms delay
}
}
Example A.13:
Write a 8051 C program to generate a square wave of 50% duty cycle with
Ton = Toff = 500 ms.
Solution:
TON
Duty cycle =
TON + TOFF
C Program
#include<reg51.h>
void delay(unsigned int);
void main( )
{while (1) //repeat continuously
{
P0^1=0; //make P0.1 pin low
delay(500); //call delay subroutine with a parameter of 500
P0^1=1; //make P0.1 pin high
delay(500); //call delay subroutine with a parameter of 500
} //end of while
} //end of main
void delay (unsigned int count)
{
unsigned int i, j;
for(i=0; i<count; i++) //outer loop repeated count times
for(j=0; j<1275; j++); //inner loop for 1 ms delay
}
Appendix 123
Example A.14:
Write a 8051 C program to generate a square wave of 75% duty cycle with
T =400 ms on pin P0.4.
Solution:
T = 400 ms
Duty cycle = 75% = 0.75
Ton Ton
Duty cycle = =
T 400ms
Ton =400 × 0.75 = 300 ms
Toff = T – Ton = 400 – 300 = 100 ms.
C Program
include <reg51.h>
void delay (unsigned int);
void main
{ while(l)
{
P0^4=1;
delay(300);
P0^4=0;
delay(l00);
}
}
void delay (unsigned int count)
{
unsigned int i,j;
for(i=0; i<count; i++)
for(j=0;j<1275;j++);
}
Example A.15:
Write an 8051 C program to toggle bits of P1 ports continuously with a
250ms.
Solution:
#include <reg51.h>
void delay(unsigned int);
void main(void)
124 8051 Microcontroller
{
while (1) //repeat forever
{
P1=0x55;
delay(250);
P1=0xAA;
delay(250);
}
}
void delay (unsigned int count)
{
unsigned int i,j;
for(i=0;i<count;i++)
for(j=0;j<1275;j++);
}
Example A.16:
Write an 8051 C program to get a byte of data from P1, wait ½ second,
and then send it to P2.
Solution:
#include <reg51.h>
void delay(unsigned int);
void main(void)
{
unsigned char mydata;
P1=0xFF; //make P1 input port
while (1) // repeat forever
{
mydata=P1; //get a byte from P1
delay(500);
P2=mydata; //send it to P2
}
Appendix 125
}
void delay(unsigned int count)
{
unsigned int i, j;
for (i=0; i<count; i++)
for (j=0; j<1275; j++);
}
Example A.17:
Write an 8051 C program to toggle all the bits of P0, P1 and P2
continuously with a 250 ms delay. Use the sfr keyword to declare the port
addresses.
Solution:
sfr P0=0x80;
sfr P1=0x90;
Another way to access the SFR RAM space
sfr P2=0xA0;
80 - FFH is to use the sfr data type
void delay(unsigned int);
void main(void)
{
while (1)
{
P0=0x55;
P1=0x55;
P2=0x55;
delay(250);
P0=0xAA;
P1=0xAA;
P2=0xAA;
delay(250);
}
}
void delay(unsigned int count)
{
unsigned inti, j;
for (i=0; i<count; i++)
for (j=0; j<1275; j++);
}
Example A.18:
Write an 8051 C program to turn bit P1.5 on and off 50,000 times.
Solution:
sbit MYBIT=0x95;
void main(void) We can access a single bit of any SFR if
{ we specify the bit address
unsigned int i;
for (i=0;i<50000;i++)
{
MYBIT=1;
MYBIT=0;
}
}
Appendix 127
Notice that there is no #include <reg51.h>. This allows us to access any byte
of the SFR RAM space 80-FFH. This is widely used for the new generation of
8051 microcontrollers.
Example A.20:
Write an 8051 C program to monitor bit P0.5. If it is high, send AAH to
P1; otherwise, send FFH to P3.
Solution:
#include <reg51.h>
sbit mybit=P0^5;
void main(void)
{
mybit=1; //make mybit an input
while (1)
{
128 8051 Microcontroller
if (mybit==1)
P1=0xAA;
else
P3=0xFF;
}
}
Example A.21:
Write an 8051 C program to get the status of bit P1.1, save it, and send
it to P0.1 continuously.
Solution:
#include <reg51.h>
sbit inbit=P1^1;
sbit outbit=P0^1;
bit membit; //use bit to declare
//bit- addressable memory
void main(void)
We use bit data type to access data
{ in a bit-addressable section of the
while (1) data RAM space 20 - 2FH
{
membit=inbit; //get a bit from P1.1
outbit=membit; //send it to P0.1
}
}
Example A.21:
The data pins of an LCD are connected to P1. The information is latched
into the LCD whenever its Enable pin goes from high to low. Write an 8051
C program to send "RYMEC Engineering College Ballari" to this LCD.
Solution:
#include <reg51.h>
#define LCDData P1 //LCDData declaration
sbit En=P2^0; //the enable pin
void main(void)
{
unsigned char message[]= "RYMEC Engineering College Ballari";
Appendix 129
unsigned char z;
for (z=0;z<33;z++) //send 33 characters
{
LCDData=message[z];
En=l; //a high-
En=0; //-to-low pulse to latch data
}
}
Arithmetic operators
The arithmetic operators in 8051 C are Additioin (+), Subtraction (-), Multiplication (*)
and Division (/) and are shown in table A.3
Table A.3 Arithmetic Operators in C
Operator Description Example
+ Adds two operands. A + B = 30
− Subtracts second operand from the first. A − B = 10
* Multiplies both operands. A ∗ B = 200
∕ Divides numerator by de-numerator. A ∕ B = 2
Example A.22:
Write a C program to understand all the arithmetic operators available
in 8051 C.
Solution:
#include <reg51.h>
void main(void)
{
unsigned char A=20;
unsigned char B=10;
P1=A + B;
P1=A - B;
P1=A * B;
P1=A / B;
}
130 8051 Microcontroller
Example A.23:
The following program will explain the different logical operations. We
can run on simulator and examine the results.
Solution:
#include <reg51.h>
void main(void)
{
P0=0x35 & 0x0F; //ANDing
P1=0x04 | 0x68; //ORing
P2=0x54 ^ 0x78; //XORing
P0=~0x55; //inversing
P1=0x9A >> 3; //shifting right 3
P2=0x77 >> 4; //shifting right 4
P0=0x6 << 4; //shifting left 4
}
Example A.24:
Write an 8051 C program to toggle all the bits of P0 and P1 continuously
with a 300ms delay. Using the inverting and Ex-OR operators,
respectively.
132 8051 Microcontroller
Solution:
#include <reg51.h>
void delay(unsigned int);
void main(void)
{
P0=0x55;
P1=0x55;
while (1)
{
P0=~P0;
P1=P1^0xFF;
delay(300);
}
}
void delay(unsigned int count)
{
unsigned int i,j;
for(i=0; i<count; i++)
for(j=0; j<1275;j++);
}
Example A.25:
Write an 8051 C program to get bit P1.2 and send it to P2.3 after
inverting it.
Write a C program to read P1.2 and send it to P2.3 after inverting it.
5 Marks
Solution:
#include <reg51.h>
sbit inbit=P1^2;
sbit outbit=P2^3;
bit membit;
void main(void)
{
while (1)
Appendix 133
{
membit=inbit; //get a bit from P1.2
outbit=~membit; //invert it and send
//it to P2.3
}
}
Example A.26:
Write an 8051 C program to read the P1.0 and P1.1 bits and issue an
ASCII character to P0 that is if P1.1 and P1.0 is 00 send ‘0’ if 01 send
‘1’, if 10 send ‘2’ and if 11 send ‘3’.
Algorithm
1. Make P1 as input port.
2. Read P1 value.
3. Mask all bits except D0 & D1 of P1 and put the masked value in x.
4. If x=0; send ‘0’ to P0, else if x=1; send ‘1’ to P0, else if x=2; send ‘2’ to P0, else
send ‘3’ to P0. (use switch statement).
5. Repeat from step 2.
Solution:
#include <reg51.h>
void main(void)
{
unsigned char z;
z=P1; //read P1
z=z&0x3; //mask the unused bits
switch (z) //make decision
{
case(0):
{
P0=‘0’; break; //send ASCII 0
}
case(1):
134 8051 Microcontroller
{
P0=‘1’; break; //send ASCII 1
}
case(2):
{
P0=‘2’; break; //send ASCII 2
}
case(3):
{
P0=‘3’; break; //send ASCII 3
}
}}
Example A.27:
Compile and single-step the following program on your 8051 simulator.
Examine the contents of the 128-byte RAM space to locate the ASCII
values.
Solution:
#include <reg51.h>
void main(void)
{
unsigned char mynum[]=“RYMEC”; //RAM space
unsigned char z;
for (z=0;z<=5;z++)
P1=mynum[z];
}
Appendix 135
Example A.28:
Write, compile and single-step the following program on your 8051simulator.
Examine the contents of the code space to locate the values.
Solution:
#include <reg51.h>
void main (void)
{
unsigned char mydata[100]; //RAM space
unsigned char x, i=0;
for (x=0;x<100;x++)
{ i++;
mydata [x]=i;
P0=i;
}
}
Example A.29:
Compile and single-step the following program on your 8051simulator.
Examine the contents of the code space to locate the ASCII values.
Solution:
To make the C compiler use the
code space instead of the RAM
#include <reg51.h> space, we need to put the keyword
void main(void) code in front of the variable
{ declaration
code unsigned char mynum[]="GMIT DAVANGERE";
unsigned char i;
for (i=0;i<14;i++)
P1=mynum[i];
}
Example A.30:
Compare and contrast the following programs and discuss the advantages
and disadvantages of each one.
i) #include <reg51.h>
Void main (void)
{
136 8051 Microcontroller
P1 = “H”;
P1 = “E”;
P1 = “L”;
P1 = “L”;
P1 = “O”;
}
Solution:
Short and simple.
he individual character is embedded into the program and it mixes the
T
code and data together. Thus, it’s not flexible.
ii) #include <reg51.h>
Void main (void)
{
unsigned char mydata [ ] = “HELLO”;
unsigned char z;
for (z=0; z<5; z++)
P1 = mydata [z];
}
Solution:
he Array elements are stored in RAM, therefore the size of the array is
T
limited.
iii)
#include <reg51.h>
Void main (void)
{
code unsigned char mydata [ ] = “HELLO”;
unsigned char z;
for (z=0; z<5; z++)
P1 = mydata [z];
}
Solution:
se a separate area of the code space for data. This allows the size of the
U
array to be as long as you want if you have the on-chip ROM.
owever, the more code space you use for data, the less space is left for
H
your program code.
Appendix 137
Example A.31:
rite an 8051 C program to convert packed BCD 0x29 to ASCII and display
W
the bytes on P1 and P2.
Write
a 8051 C program to convert packed BCD to ASCII and to display it
on P1 and P2 5 Marks
Solution:
#include <reg51.h>
void main(void)
{
unsigned char x,y,z;
unsigned char mybyte=0x29;
x=mybyte&0x0F;
P1=x|0x30;
y=mybyte&0xF0;
y=y>>4;
P2=y|0x30;
}
Example A.32:
Write an 8051 C program to convert ASCII digits ‘4’ and ‘7’ into packed
BCD and to display on port P1. 5 Marks
Solution:
#include <reg51.h>
void main(void)
{
unsigned char bcdbyte;
unsigned char w=‘4’;
unsigned char z=‘7’;
w=w&0x0F;
w=w<<4;
z=z&0x0F;
bcdbyte=w|z;
P1=bcdbyte;
}
138 8051 Microcontroller
Example A.33:
Write an 8051 C program to toggle all the bits of P0 for every 500ms
i) by using NOT operator
ii) by using EX-OR operator
Solution
#include <reg51.h>
void delay(unsigned int);
void main(void)
{
P0=0x55;
while(1)
{
P0=~P0;
delay(500);
}
}
void delay(unsigned int itime)
{
unsigned int i,j;
for (i=0;i<itime;i++)
for (j=0;j<1275;j++);
}
ii) By using EX-OR operator
#include <reg51.h>
void delay(unsigned int);
void main(void)
{
P0=0x55;
while(1)
{
P0 = P0 ^ 0xFF;
Appendix 139
delay(500);
}
}
4.1 Introduction
The 8051 has two16-bit timers/counters, they can be used either as
• Timers to generate a time delay or
• Event counters to count events happening outside the microcontroller.
The two timers are
i) Timer/Counter T0 and ii) Timer/Counter T1
T0 T1
• Each register can be used either for Timer or counter and can be divided into Two
8-bit registers called Timer Low (TL) and Timer High (TH) as shown in Fig. 4.1.1.
• Both timers 0 and 1 use the same register, called TMOD (timer mode), to set
the various timer operation modes.
• TCON is a bit-addressable 8-bit register used for timer control.
140
8051 Timers and Serial Port 141
• The 16-bit register of Timer 0 is accessed as low byte and high byte.
• The low byte register is called TL0 and the high byte register is called TH0.
• These registeres can be accessed like any other registers such as A, B, R0 to
R7 etc.
Example:
MOV TLO, # 55H ; Move the value 55H into TL0 register
MOV R1, TL0 ; Copy the content of TL0 into R1 register.
Example:
MOV TH1, # 55H ; Move the value 55H into TH1 register
MOV R1, TH1 ; Copy the content of TH1 into R1 register.
For Timer 1
Bit 7: Gate (Gating control)
––––
• When Gate=1, the Timer/Counter 1 is enabled only when INT1 pin is high (p 3.3)
––––
and the TR1 control bit is high (i.e. Gate = INT1 = TRI = 1).
142 8051 Microcontroller
For Timer 0
Bit 3:Gate (Gating control)
––––
• When Gate = 1, the Timer/Counter 0 is enabled only when I NT0 pin is high
––––
(p3.2) and the TR1 control bit is high (i.e. Gate = I NT0 =TR0 = 1).
• When Gate =0, the Timer/Counter 0 is enabled whenever the TR0 control bit is
––––
set (i.e. Gate=TR0 = 1 & regardless of the State of I NT0 pin).
–
Bit 2: C/T (Timer or Counter selected)
–
• When C/T = 0, Timer mode selected. In Timer mode, Timer 0 will increment
every machine cycle.
–
• When C/T =1, counter mode selected. In counter mode, Timer 0 will count
events (pulses) on T0 pin (P3.4).
Note:
• The only difference between Timer/counter is the sources of the clock pulses.
When used as a timer, the clock pulses are sourced from the oscillator through
the divide by 12-d circuit.
• When used as a counter, Pin T0 (P3.4) supplies pulses to counter 0, & Pin T1
(P3.5) supplies pulses to counter1.
Note:
• TMOD register configuration for Timer 0/1 in Mode 1 & Mode 2.
TMOD
Timer & Mode TMOD Register
value
TIMER 1 TIMER 0
– –
GATE C/T M1 M0 GATE C/T M1 M0
Timer 0, Mode 1 × × × × 0 0 0 1 01H
Timer Mode 1
TIMER 1 TIMER 0
– –
GATE C/T M1 M0 GATE C/T M1 M0
Timer 1, Mode 1 0 0 0 1 × × × × 10H
Timer Mode 1
TIMER 1 TIMER 0
– –
GATE C/T M1 M0 GATE C/T M1 M0
Timer 0, Mode 2 × × × × 0 0 1 0 02H
Timer Mode 2 of
operation operation
TIMER 1 TIMER 0
– –
GATE C/T M1 M0 GATE C/T M1 M0
Timer 1, Mode 2 0 0 1 0 × × × × 20H
Timer Mode 2 of
operation
144 8051 Microcontroller
Example 4.1:
Find the values of TMOD to operate as timers in the following modes.
(a) Mode 1 Timer 1 (b) Mode 2 Timer 0, Mode 2 Timer 1
(c) Mode 0 Timer 1
Solution
(a) TMOD is 00010000 = 10H
–
The gate control bit and C/T bit are made 0, and the unused timer (Timer
0 bit is also 0)
(b) TMOD is 01010010 = 52H
(c) TMOD is 00000000H = 00H
Example 4.2:
Indicate which mode and which timer are selected for each of the
following
(a) MOV TMOD, #01H (b) MOV TMOD, #20H (c) MOV TMOD, #12H
Solution:
We convert the value from hex to binary
(a) TMOD = 00000001, mode 1 of timer 0 is selected.
(b) TMOD = 00100000, mode 2 of timer 1 is selected.
(c) TMOD = 00010010, mode 2 of timer 0, and mode 1 of timer 1 are selected.
Example 4.3:
Find the timer’s clock frequency and its period for various 8051-based
–
system, with the crystal frequency 11.0592 MHz when C/T bit of TMOD is
0.
Solution:
XTAL
÷ 12
oscillator
Machine Cycle
P1 P2 P1 P2 P1 P2 P1 P2 P1 P2 P1 P2
S1 S2 S3 S4 S5 S6
One machine cycle
6 states, 12 pulses
Example 4.4:
For 8051 microcontroller, find the time taken for an instructions which takes
i) 1 Machine cycle ii) 2 Machine cycles iii) 4 Machine cycles
Solution:
C × 12d 1 × 12
i) T= = = 1.085 µSec
f 11.0592 × 106
C × 12d 2 × 12
ii) T= = = 2.170 µSec
f 11.0592 × 106
C × 12d 4 × 12
iii) T= = = 4.340 µSec
f 11.0592 × 106
Fig.4.2.4:TCON register.
• TCON (timer control) register is a bit-addressable 8-bit register.
• The upper four bits (bit 4 to bit 7) are used to store the TF and TR bits of both
timer 0 & 1.
146 8051 Microcontroller
• The lower four bits (bit 0 to bit 3) are set aside for controlling the interrupt bits.
Bit Bit Name Bit Function
Timer 1 Overflow flag.
TF1=1, when timer 1 register overflows.
7 TF1
TF1=0, when processor vectors to execute interrupt service routine
located at program address 001Bh.
Timer 1 run control bit. Set/Cleared by software.
6 TR1 TR1=1, enable timer to count.
TR1=0, halt timer.
Timer 0 Overflow flag.
TF0=1, when timer 0 register overflows.
5 TF0
TF0=0, when processor vectors to execute interrupt service routine
located at program address 000Bh.
Timer 0 run control bit. Set/Cleared by software.
4 TR0 TR0=1, enable timer to count.
TR0=0, halt timer.
External interrupt 1 Edge flag.
Set to 1 when a high-to-low edge signal is received on port 3.3
––––
3 IE1 ( I N T1).
Cleared when processor vectors to interrupt service routine at
program address 0013h. (Not related to timer operations).
For Timer 0
SETB TR0 SETB TCON 4
CLR TR0 CLR TXON 4
SETB TF0 CLR TCON 5
CLR TF0 CLR TCON 5
For Timer 1
SETB TR1 SETB TCON 6
CLR TR1 CLR TCON 6
SETB TF1 SETB TCON 7
CLR TF1 CLR TCON 7
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 the original value, and TF must
be reset to 0.
imer 0 in Mode1
Explain the operation of timer0 in mode 1 5-Marks
XTAL
÷12 TH0 TL0 TF0
oscillator
– TF0 goes high Overflow
C/T = 0 TR0 flag
Timer 1 in Mode1
XTAL
÷12 TH1 TL1 TF1
oscillator
– Overflow
C/T = 0 TR1 flag
2. Load registers TL1 and TH1 with initial count value (16-bit value i.e. 0000H to
FFFFH)
3. Start the Timer 1 by setting TR1 in TCON register (SETB TR1)
4. Timer 1 started and it counts until it reaches its maximum value i.e. FFFFH
and it rolls over to 0000H. Now it will set the TF1 bit in TCON register.
Keep monitoring TF1 with the “JNB TF1, here” instruction until TF1 is set.
5. Stop the Timer 1 (Set TR1=0)
6. Clear TF1 flag for the next round.
7. Go back to Step 2 to load TH1 and TL1 again.
4.3.2 Timer in Mode 2
The following are the characteristics and operations of mode 2:
1. It is an 8-bit timer; therefore, it allows only values of 00 to FFH to be loaded
into the timer’s register TH.
2. After TH is loaded with the 8-bit value, the 8051 gives a copy of it to TL
Then the timer must be started. This is done by the instruction SETB TR0 for
timer 0 and SETB TR1 for timer 1.
3. After the timer is started, it starts to count up by incrementing the TL
register.
ff It counts up until it reaches its maximum.
ff When it rolls over from FFH to 00, it sets high the TF (timer flag).
4. When the TL register rolls from FFH to 0 and TF is set to 1, TL is reloaded automati-
cally with the original value kept by the TH register.
• To repeat the process, we must simply clear TF and let it go without any need
by the programmer to reload the original value.
• This makes mode 2 an auto-reload, in contrast with mode 1 in which the
programmer has to reload TH and TL.
XTAL Overflow
÷12 TL0 TF0
oscillator flag
–
C/T = 0 TR0 TF0 goes high
Reload when FF 0
TH0
Timer 1 in Mode 2
1. Load the TMOD register with 20H to operate in Timer 0 in Mode 2.
2. Load initial value into TH1 register (8-bit value i.e. 00H to FFH). The TH1
content is automatically copied into TL1 register.
XTAL Overflow
÷12 TL1 TF1
oscillator flag
–
C/T = 0 TR1 TF goes high
Reload when FF 0
TH1
Fig.4.3.4: Block diagram of Timer 1 in Mode 2
–
Note: C/T = 0, TMOD = 20H & TCON = 40H
8051
TH0
P1
TL0
P3.4
a switch T0
Timer 0
Overflow
external TH0 TL0 TF0
flag
input P in
TR0 TF0 goes high
3.4
when FFFF 0
–
C/T = 0
Fig.4.4.2: Block diagram of Counter 0 in Mode 1
–
Note: C/T =1, TMOD = 05H & TCON =10H
Timer 1
external TH1 TL1 TF1
input P in Overflow
TR1 TF1 goes high
3.5 flag
when FFFF 0
–
C/T = 1
Fig.4.4.3: Block diagram of Counter 1 in Mode 1
–
Note: C/T = 1, TMOD = 50H & TCON = 40H
Steps to program Counter1 in Mode 1
1. Load the TMOD register with 50H to operate in Counter1 in Mode 1.
2. Load registers TL1 and TH1 with initial count value (16-bit value i.e. 0000H to FFFFH)
3. Start the Counter1 by setting TR1 in TCON register (SETB TR1)
4. Counter1 started and it counts until it reaches its maximum value i.e. FFFFH
and it rolls over to 0000H. Now it will set the TF1 bit in TCON register.
Keep monitoring TF1 with the “JNB TF1, here” instruction until TF1 is set.
5. Stop the Counter1 (Set TR1=0)
6. Clear TF1 flag for the next round.
7. Go back to Step 2 to load TH1 and TL1 again.
Counter 0 in Mode 2
Timer 0 Overflow
TL0 TF0
external flag
input P in TR0 TF goes high
3.4 Reload
when FF 0
– TH0
C/T = 1
4. Counter 0 started and it counts until it reaches its maximum value i.e. FFH
and it rolls over to 00H. Now, it will set the TF0 bit in TCON register and the
TL0 is reloaded automatically with the initial value (i.e. TH0 value).
Keep monitoring TF0 with the “JNB TF0, here” instruction until TF0 is set.
5. Clear TF0 flag for the next round.
6. Go back to Step 4, since mode 2 is auto-reload.
Counter 1 in Mode 2
Timer 0 Overflow
TL1 TF1
external flag
input P in TR1 TF goes high
3.5 Reload
when FF 0
– TH1
C/T = 1
Fig.4.4.5: Block diagram of Counter 1 in Mode 2
–
Note: C/T = 1, TMOD = 60H & TCON = 40H
Steps to program Counter1 in Mode 2
1. Load the TMOD register with 60H to operate in Counter1 in Mode 2.
2. Load initial value into TH1 register (8-bit value i.e. 00H to FFH). The TH1
content is automatically copied into TL1 register.
3. Start the Counter1 by setting TR1 in TCON register (SETB TR1)
4. Counter1 started and it counts until it reaches its maximum value i.e. FFH and
it rolls over to 00H. Now, it will set the TF1 bit in TCON register and the TL1
is reloaded automatically with the initial value (i.e. TH1 value).
Keep monitoring TF1 with the “JNB TF1, here” instruction until TF1 is set.
5. Clear TF1 flag for the next round.
6. Go back to Step 4, since mode 2 is auto-reload.
FORMULAE
12
Time delay = [Maximum Count Value − (initial count + 1)]×
Crystal Frequency
Crystal Frequency
Initial Count = Maximum Count Value − Time delay × + 1
12
12
Maximum delay = Maximum Count Value ×
Crystal Frequency
8051 Timers and Serial Port 155
he initial value (16-bit) should be loaded into the 16-bit timer register
T
THTL as TH1 = FF (MSB) and TL1 – EA (LSB).
For timer 0 in mode 1 TMOD = 01H
The initial value is loaded into Timer0 register i.e. TL0 = EAH & TH0 = FFH.
C Program
#include <reg51.h>
void main ( )
{
156 8051 Microcontroller
Example 4.6:
rite an ALP and C program to generate 50% duty cycle on P1.1. Use
W
timer 1 in mode 1 to generate the delay. Use an initial value of FFAAH
for the timer and a crystal frequency of 11.0592 MHz. Also calculate the
frequency of square wave.
Solution:
C Program
#include <reg51.h>
void delay (void);
sbit pin=p1^1;
void main ( )
{
TMOD=0x10; //Tiimer1, Mode1
while (1)
{
Pin=~pin; //Toggle PORT 1 pin P1.1
TL1=0xAA; //Initial value FFAA i.e. TL1=AAH
TH1=0xFF; //TH1=FFH
}
void delay ( );
}
T1 T2
12
= × (FFFF − FFAA + 1) = 1.085 µs × 56 H = 1.085 µs × 86 D
11.0592 M
Hence
Crystal frequency
(Initial value − 1) = Maximum value of mode 0 − Required delay ×
12
4 × 10−3 × 22 × 106
= FFFF −
12
−3
3 × 10 × 22 MHz
= FFFFH −
12
= 65535 − 7333
= 58202 + 1
Initial value = E35BH
SJMP HERE
C Program
#include <reg51.h>
void delay (void);
sbit pin=P1^1;
void main ( )
{
TMOD=0x10; //Tiimer1, Mode1
while (1)
{
TL1=0x5B; //initial value to generate 4 ms ON time
TH1=0xE3;
pin=1; //Port Pin P1.1 is made high
delay( );
TL1=0x84; // initial value to generate 4 ms ON
// time
TH1=0xEA;
pin = 0; // Port Pin P1.1 is made low
delay( );
Example 4.8:
Write an ALP and C program to generate a square wave of 20 KHz on pin
P2.5. Use timer 0 in mode 2 with crytal frequency of 22 MHz.
8051 Timers and Serial Port 161
Solution:
ORG 00H
MOV TMOD, #02H ; Timer0 in Mode 2
MOV TH0, #D2H ; Initial value loaded in TH0 register
SETB TR0 ; Start Timer 0
WAIT: JNB TF0, WAIT ; wait till TF0=1
C Program
#include <reg51.h>
sbit pin=P2^5;
void main ( )
{
TMOD=0x02; //Timer0, Mode2
TH0=0xD2; // Initial value loaded in TH0 register
TR0=1; //Start Timer0
162 8051 Microcontroller
while(1)
{
pin=~pin; // toggle Port Pin P1.1
while (TF0==0); // executes loop until TF0=0 &
comes out when TF0=1
TF0=0; // Clear TF0 for next overflow
} // end of while loop
} // end of main
Example 4.9:
Assume that XTAL = 1.0592 MHz, Use timer Timer1 Mode2,
a. Generate square wave on pin P1.0 with initial value 05H and find the
frequency of the generated square wave.
b. The smallest frequency achievable in the program, and the TH value
to do that.
Solution:
a)
ORG 00H
MOV TMOD,#20h ;T1/mode 2/8-bit/auto-reload
MOV TH1, #5 ;TH1 = 5
SETB TRI ;start timer 1
BACK JNB TF1, BACK ;stay until timer rolls over
CPL P1.0 ;comp,P1.0 to get hi,lo
SJMP BACK ;mode 2 is auto reload
END
ff In mode 2, we do not need to reload TH since it is auto - reload.
Initial value = 05h
ff Since this program generates a 50% duty cycle square wave,
TON
T1
TOFF
12
Time delay = − [Max. value in Mode 2 − initial value ]
Crystal frequency
12
= − [FF(h) − 05]
11.0592 MHz
12
= [255 − 05]
11.0592 MHz
= 1.085069 7 10 −6 [250]
Time delay = 271.26 µ sec .
From the program, we know that,
TON = TOFF = 271.26 μsec
Example 4.10:
Assume that XTAL = 22MHz, write a program to generate a square wave
of frequency 1KHz on pin P1.2. Use timer0 in Mode2.
164 8051 Microcontroller
Solution:
XTAL = 22 MHz, f = 1 KHz on P1.2 pin
1 1
We know that, T = =
f 1 KHz
T = 1 m sec
T = TON + TOFF = 1 m sec
∴ TON = TOFF = 0.5 msec
12
Maximum possible delay in Mode 2 = FF(h) ×
Crystal frequency
12
= 255(d) × = 0.1390909 m sec
22 MHz
But, required delay is 0.5 msec.
So, 1st generate a delay of 0.1 msec and repeat the loop for 5 times.
i.e., 0.1 msec × 5 = 0.5 msec
0.5 m sec
counter "N " = =5
0.1 m sec
ORG 00H
MOV TMOD,#02H ;Timer 0, mode 2
REPT: CPL P1.2 ;complement P1.2
MOV R0, #05 ;count for multiple delays
AGAIN MOV TH0,#48H ;loaf TH0 value
SETB TR0 ;start Timer 0
BACK JNB TF0, BACK ;stay until timer rolls over
CLR TR0 ;stop timer
8051 Timers and Serial Port 165
In the above counter value, we are getting fraction value, so, change the counter
value.
Case 1:
250 m sec
Counter "N " = = 5000
50 m sec
1st generate a time delay of 50 msec and repeat the process for 5000 times,
i.e.,
50 μsec ×100 × 50 = 250 msec
It can be written as, 100 × 50 = 5000
Computatioin of Initial value:
Crystal frequency
(Initial vlaue − 1) = Max. Value in Mode 2 − Required time delay ×
12
11.0592 MHz
= FF(h) − 50 µ sec ×
12
(Initial vlaue − 1) = 255(d) − 46.08 + 1
= 210(d)
Initial vlaue = D2h
166 8051 Microcontroller
Case 2:
Counter "N " = 250 m sec = 10000
25 µ sec
"N " = 10,000
It can be written as 250 × 40 = 10000
i.e., 25 μsec × 250 × 40 = 250 msec
Crystal frequency
(Initial vlaue − 1) = Max. Value in Mode 2 − Required time delay ×
12
11.0592 MHz
= FF(h) − 25 µ sec ×
12
(Initial vlaue − 1) = 255(1) − 23.04 d + 1 = 233
Initial vlaue = E9h
Example 4.12
Write an 8051 c program to creat a frequency of 2500 Hz on pin P2.7.
Use timer 1, mode 2 to creat the delay
Solution
1 1
T= =
F 2500 Hz
T = 0.4 m sec
T = 0.4 msec
T = TON + TOFF
T = 0.2 msec +0.2 msec
C Program
#include<reg51.h>
voidd elay (void);
sbit mybit=P2^7;
void main(void)
168 8051 Microcontroller
{
while(1)
{
mybit=~mybit; //toggle P2.7
delay();
}
}
voiddelay (void)
{
TMOD=0x20; //Timer 1, mode 2(8-bit auto-reload)
THL=-184; //load TH1(auto-reload value)
TR1=1; //turn on T1
while (TF1==0) //wait for TF1 to roll over
TR1=0; //turn off T1
TF1=0; //clear TF1
}
Example 4.13:
ssume that 1-Hz external clock is being fed into pin T1 (P3.5). Write a
A
C program for counter 1 in mode 2 (8 -bit auto reload) to count up and
display the state of the TL1 count on P1. Start the count at 0H
Solution
include<reg51.h>
sbit Tl=P3^5;
void main(void)
{
Tl=l; //make T1 an input
TMOD=0×60;
TH0=0; //set count to 0
while(1) //repeat for ever
{
do
{
TR1=1; //start timer
8051 Timers and Serial Port 169
P3.5
T1
Sender Receiver
Parallel communication
Parallel Transfer
D0
Sender Receiver
D7
Receive Interrupt
When 8051 receives data serially via RxD, it gets rid of the start
and stop bits and places the byte in SBUF register
0 RI
It raises the RI flag bit to indicate that a byte has been received
and should be picked up before it is lost.
RI is raised halfway through the stop bit.
4.6.6 RS 232
Table 4.6.1: IBM PC DB-9 Signals
Pin Description
RS232 Connector DB-9 –– ––
1 Data carrier detect (DCD )
2 Received data (RxD)
3 Transmitted data (TxD)
4 Data terminal ready (DTR)
5 Signal ground (GND)
––––
6 Data set ready (DSR )
––––
7 Request to send (RTS)
––––
8 Clear to send (CTS)
9 Ring indicator (Rl)
DTE DTE
T×D T×D
R×D R×D
Ground
FORMULAE
Crystal frequency 1
Baud rate = ×
12 × 32 (256 − TH1)
Crystal frequency
TH1 = 256 −
12 × 32 × Baud rate
Example 4.14:
1. ith XTAL = 11.0592 MHz, find the TH1 value needed to have the following
W
baud rates. (a) 9600 (b) 4800 (c) 2400 (d) 1200
Solution
Initial Value
Baud Rate
TH1 in Hexadecimal TH1 in decimal
FD –3 9600
FA –6 4800
F4 –12 2400
E8 –24 1200
Note: In 8051, serial communication uses a standard crystal frequency i.e.
11.0592 MHz.
8051 Timers and Serial Port 177
0 1 0 1 0 0 0 0
Example 4.15:
rite a program for the 8051 to transfer letter “A” serially at 9600 baud,
W
continuously.
Solution:
ORH 00H
MOV TMOD,#20H ;timer 1,mode 2(auto reload)
MOV TH1,#-3 ;9600 baud rate
MOV SCON,#50H ;8-bit, 1 stop, REN enabled
SETB TR1 ;start timer 1
AGAIN: MOV SBUF,#”A” ;letter “A” to transfer
HERE: JNB TI, HERE ;wait for the last bit
CLR TI ;clear TI for next char
SJMP AGAIN ;keep sending A
END
C-Program
#include <reg51.h>
void main(void)
{
TMOD=0x20; //use Timer 1, mode 2
178 8051 Microcontroller
Example 4.17:
Write an ALP and C program to serially transmit the message “HELLO”
continuously at a baud rate of 9600, 8-bit data and 1 stop bit.
Solution:
ALP C Program
ORG 00H #include <reg51.h>
MOV TMOD, #20H void send(unsigned char);
MOV TH1, #-3 void main()
MOV SCON, #50H {
SETB TR1 TMOD=0x20;
AGAIN MOV A, # “H”
ACALL SEND
......Continued
180 8051 Microcontroller
Example 4.18:
Write an ALP and C program to serially transmit the message “GMIT
DAVANGERE” continuously at a baud rate of 9600, 8-bit data and 1 stop
bit.
Solution:
ALP C Program
ORG 00H #include <reg51.h>
MOV TMOD, #20H void main( )
MOV TH1,#-3 {
MOV SCON,#50H unsigned char i;
SETB TR1 unsigned char msg[ ] =
repeat: MOV DPTR,#msg “GMIT DAVANGERE”;
up: CLR A TMOD=0x20;
MOVC A,@A+DPTR TH1=0xFD;
JZ repeat SCON=0x50;
ACALL send TR1=1;
INC DPTR while (1)
......Continued
8051 Timers and Serial Port 181
SJMP up {
send: MOV SBUF,A for(i=0; i<14; i++)
{
here: JNB TI, here SBUF=msg[i];
CLR TI while (TI==0);
RET TI=0;
msg: db “GMIT DAVANGERE”,0 }
END }
}
Example 4.19
rite a program to transfer a letter 'Y' serially at 9600 baud continuously
W
and also to send a letter 'N' through port0, which is connected to a
display divide
Solution
ORG 00h
MOV TMOD,#020H ; timer 1. mode 2
MOV TH1,#-3 ; 9600 baud rate
MOV SCON,#50H ; 8 bits, 1stop, REN enabled
SETB TRI ; START TIMER 1
AGAIN:
MOV SBUF, #"Y" ; transfer *Y* serially
HERE: JNB TI, HERE ; WAIT FOR transmission to be over
CLR TI ; clear Tl for next transmission
MOV P0, #"N" ; move "N" to P0 for parallel transfer
SJMP AGAIN ; repeat
END
P3.1
8051
Display
P0
Example 4.20:
Write an ALP and C program to receive serial data at 4800 baud rate and
send it to port 0.
Solution
ALP
ORG 00H
MOV TMOD, #20H ;Timer1, Mode2
MOV TH1, #-6 ;4800 baud rate
MOV SCON, #50H ;serial mode 1
SETB TR1 ;start timer 1
AGAIN: CLR RI ;clear RI flag
WAIT: JNB RI, WAIT ;wait till character is received
MOV A, SBUF ;received character is moved into Accumulator
MOV P0, A ;copy Accumulator content into P0
SJMP AGAIN ;repeat for next character
END
C Program
#include <reg51.h>
void main()
{
unsigned char rdata;
TMOD=0x20; //use Timer 1, mode 2
TH1=0xFA; //4800 baud rate
SCON=0x50; //serial mode 1
TR1=1; //start timer 1
while (1)
{
while (RI==0); //wait to receive data
rdata=SBUF; //read received data
P0=rdata; //send received data to P0
RI=0; //clear RI flag
} //end of while
} //end of main
8051 Timers and Serial Port 183
Example 4.21:
rite a Cprogram for the 8051 to transfer the letter "C" serially at 9600
W
baud continuously. Use S bit data and 1 stop bit.
Solution
#include<reg51.h> ORG 00H
void mainO MOV TMOD,#20h
{ MOV THl,#-3
TMOD=0x20; MOV SCON,#50h
THl=0xFD; SETB TR1
SCON=0X50; up:
TR1=1; MOV SBUF,#'C'
while(l) here: JNB TI here
{ CLR TI
SBUF='C'; SJMP up
while(TI=0); END
TI=0;
}
}
Example 4.22:
INC DPTR {
SJMP up for(i=0; i< 12; i++)
send: {
MOV SBUF, A SBUF=msg[i];
here: JNB TI, here while (TI==0);
CLR TI TI=0:
RET }
msg: db "GOOD MORNING",0 }
END }
Example 4.23:
Write an 8051 C program to receive byte of data serially and put them
on P1. Set the baud rate to 4800, 8-bit data, 1 stop bit.
Solution
SCON=0X50; up:
TR1=1; here: JNB RI, here
while(1) MOV A, SBUF
{ MOV P1,A
while(RI==0); CLR RI
P1=SBUF; SJMP up
RI=0; END
}
}
NOTE: Both programs are correct.
Example 4.24:
Write an 8051 ALP and C program to transfer serially the character “H”
continuously at a baud rate of 9600.
Solution
Example 4.25:
Write an 8051 ALP and C program to transfer serially the character
“H” continuously at a baud rate of 19200 with a crystal frequency of
11.0592 MHz.
186 8051 Microcontroller
Solution
Example 4.26:
Write an 8051 ALP and C program to transfer serially the character “H”
to serial #1 continuously at a baud rate of 9600.
Solution
Example 4.27:
Write an 8051 ALP and C program to receive data serially and it in RAM
memory location 60h. Set a baud rate of 9600.
Solution
Example 4.28:
Write an 8051 ALP and C program to receive data serially and it in RAM
memory location 60h. Set a baud rate of 9600. Use serial #1.
Solution
Example 4.29:
Write an 8051 ALP and C program to transfer serially the character “H”
continuously at a baud rate of 19200 with a crystal frequency of 11.0592
MHz.
Solution
Example 4.30:
Write an 8051 C program to send two different strings to the serial port.
Assuming that SW is connected to pin P2.0, monitor its status and make
a decision as follows:
SW=0: send your first name
8051 Timers and Serial Port 189
#include<reg51.h>
sbit SW=P2^0; //input switch
void main(void)
{
unsigned char i;
unsigned char fname [] =”ALI”;
unsigned char lname [] ="AKBAR";
TMOD=0x20;
TH1=0xFD;
SCON=0x50;
TR1=1;
if (SW==0) //check switch
{
for (i=0;i<3;i++)
{
SBUF=fname[i];
while (TI==0);
TI=0;
}
}
else
{
for (i=0 ; i<5 ; i++) //write name
{
SBUF=lname[i]; //place value in buffer
while (TI==0); //wait for transmit
TI=0;
}
}
}
Example 4.31:
Write an 8051 C program to send two messages “Normal Speed” and
“High Speed” to the serial port. Assuming that SW is connected to pin
P2.0, monitor its status and set the baud rate as follows:
190 8051 Microcontroller
#include<reg 51.h>
sbit SW=P2^0; //input switch
void main(void)
{
unsigned char i;
unsigned char mess1 [] =”Normal Speed”;
unsigned char mess2 [] =”High Speed”;
TMOD=0X20; //use timer1, 8bit auto-reload
TH1=0XFD; //9600 for normal speed
SCON=0X50;
TR1=1; //star timer
if (SW= =0)
{
for (i=0;i<12;i++)
{
SBUF=mess1[i];
while (TI= =0);
TI=0;
}
}
else
{
PCON=PCON|0X80; //for high speed of 19200
for (i=0;i<10;i++)
{
SBUF=mess2[i];
while (TI= =0);
TI=0;
}
}
}
5
8051 Interrupts and Interfacing
Applications
5.1 Introduction to Interrupts
An interrupt is the occurrence of a condition (an event) that causes a temporary
suspension of a program while the event is serviced by another program (Interrupt
Service Routine ‘ISR’).
OR
An interrupt is an external or internal event that interrupts the microcontroller
to inform it that a device needs its service.
191
192 8051 Microcontroller
Sl.
INTERRUPTS POLLING
No.
1 Whenever any device needs its service, Microcontroller can monitor the
the device notifies the microcontroller status of several devices and serve
by sending it an interrupt signal. each of them as certain conditions
Upon receiving an interrupt signal, the are met.After that, it moves on to
microcontroller interrupts whatever it is monitor the next device until each
doing and serves the device. one is serviced.
2 Each device can get the attention of the The polling method cannot assign
microcontroller based on the priority priority since it checks all devices
assigned to it. in a round-robin fashion.
3 Microcontroller can also ignore (MASK) Microcontroller cannot ignore (MASK)
a device request for service. a device request for service.
4 Microcontroller time is used efficiently. Microcontroller time is not efficiently
used.
D7 D0
EA – ET2 ES ET1 EX1 ET0 EX0
Note: U
ser software should not write is to reserved bits. These bits may be used in
future flash microcontrollers to invoke new features.
To enable an interrupt, we take the following steps:
1. Bit D7 of the IE register (EA) must be set to high to allow the rest of register to
take effect
2. The value of EA
• If EA = 1, interrupts are enabled and will be responded to if their corresponding
bits in IE are high.
• If EA = 0, no interrupt will be responded to, even if the associated bit in the
IE register is high.
5.1.7 Interrupt Priority
When the 8051 is powered up, the priorities are assigned according to Table 4.7.2.
In reality, the priority scheme is nothing but an internal polling sequence in which the
8051 polls the interrupts in the sequence listed and responds accordingly
Table 5.1.2: 8051 Interrupt Priority upon Reset
Highest to Lowest Priority
––––
External Interrupt 0 (INT 0)
Timer Interrupt 0 (TF0)
––––
External Interrupt 1 (INT 1)
Timer Interrupt 1 (TF1)
Serial Communication (RI + TI)
For example, that if external hardware interrupts 0 and 1 are activated at the same
––––
time, external interrupt 0 is responded to first. Only after INT 0 has been serviced,
–––– ––––
INT 1 serviced, since INT 1 has the lowest priority.
8051 Interrupts and Interfacing Applications 195
D7 D0
– – PT2 PS PT1 PX1 PT0 PX0
Fig. 5.1.2: Interrupt Priority Register
Priority bit = 1 assigns high priority. Priority bit = 0 assigns low priority.
— IP.7 Reserved
— IP.6 Reserved
PT2 IP.5 Timer 2 interrupt priority bit (8052 only)
PS IP.4 Serial port interrupt priority bit
PT1 IP.3 Timer 1 interrupt priority bit
PX1 . IP.2 External interrupt 1 priority bit
PT0 IP.l Timer 0 interrupt priority bit
PX0 IP.0 External interrupt 0 priority bit
Note: User software should never write 1s to unimplemented bits, since they may be
used in future microcontrollers to invoke new features.
Each interrupt source can be programmed to have one of the two priority levels
by setting (high priority) or clearing (low priority) a bit in the IP (Interrupt Priority)
Register. A low priority interrupt can itself be interrupted by a high priority interrupt,
but not by another low priority interrupt. If two interrupts of different priority levels are
received simultaneously, the request of higher priority level is served. If the requests
of the same priority level are received simultaneously, an internal polling sequence
determines which request is to be serviced.
Example 5.1:
Discuss what happens if interrupts INT0, TF0, and INT1 are activated at
the same time. Assume priority levels were set by the power-up reset and
the external hardware interrupts are edge-triggered.
196 8051 Microcontroller
Solution:
If these three interrupts are activated at the same time, they are latched and kept
internally. Then the 8051 checks all five interrupts according to the sequence listed in
Table 4.7.2. If any is activated, it services it in sequence. Therefore, when the above
three interrupts are activated, IE0 (external interrupt 0) is serviced first, then timer 0
(TF0), and finally IE1 (external interrupt 1).
Example 5.2:
––––
(a) P rogram the IP register to assign the highest priority to INT 1 (external
interrupt 1),
–––– ––––
(b) Discuss what happens if INT 0 INT 1 , and TF0 are activated at the
same time. Assume the interrupts are both edge-triggered.
Solution:
––––
(a) MOV IP,#00000100B ;IP.2=1 assign INT 1 higher priority. The instruction SETB
IP.2 also will do the same thing as the above line since IP is bit-addressable.
––––
(b) The instruction in Step (a) assigned a higher priority to I INT 1 than the others;
–––– ––––
therefore, when INT 0, INT 1, and TF0 interrupts are activated at the same time,
–––– ––––
the 8051 services INT 1 first, then it services INT 0, then TF0. This is due to the
–––––
fact that INT1 has a higher priority than the other two because of the instruction
––––
in Step (a). The instruction in Step (a) makes both the INT 0 and TF0 bits in the IP
––––
register 0. As a result, the sequence in Table 4.7.2 gives a higher priority to IINT 0
over TF0.
Example 5.3:
Assume that after reset, the interrupt priority is set the instruction MOV
IP,#00001100B. Discuss the sequence in which the interrupts are serviced.
Solution:
The instruction “MOV IP #00001100B” (B is for binary) and timer 1 (TF1)to a higher
priority level compared with the reset of the interrupts. However, since they are polled
according to Table 5.1.2, they will have the following priority.
––––
Highest Priority External Interrupt 1 (I NT1)
Timer Interrupt 1 (TF1)
––––
External Interrupt 0 (I NT0)
Timer Interrupt 0 (TF0)
Lowest Priority Serial Communication (RI+TI)
8051 Interrupts and Interfacing Applications 197
Example 5.4:
Show the instructions to
(a) Enable the serial interrupt, timer 0 interrupt, and external hardware
interrupt 1 (EX1),and
(b) Disable (mask) the timer 0 interrupt, then
(c) Show how to disable all the interrupts with a single instruction.
Solution:
(a)
MOV IE,#10010110B ;enable serial, timer 0, EX1
Another way to perform the same manipulation is
SETB IE.7 ;EA=1, global enable
SETB IE.4 ;enable serial interrupt
SETB IE.1 ;enable Timer 0 interrupt
SETB IE.2 ;enable EX1
(b)
CLR IE.1 ;mask (disable) timer 0 interrupt only
(c)
CLR IE.7 ;disable all interrupts
Example 5.5:
Discuss the interrupt priority order achieved by the execution of
MOV IP,#11H instruction 5-Marks
Ans. IP = 0 0 0 1 0 0 0 1 i.e. PS=1 & PX0=1
• After executing MOV IP,#11H instruction, two interrupts i.e. Serial port interrupt
and External interrupt 0 are assigned with priority levels
• The external interrupt 0 has highest priority. So it will be served first.
• The serial port interrupt has lowest priority and hence served after external
interrupt 0.
Disadvantages
1. Sometimes requires additional hardware.
2. Degradation of processor performance (busy wait)
3. Kernel has to be modified when adding devices.
4. More inter-processor communication.
5. Task must know low level details of the drive.
6. Lower priority interrupts can block higher priority interrupts.
7. Trends to be more complex.
8. Each ISR has a mechanism to set the external interrupt mask to stop lower-
priorities interrupts from halting the current ISR, which add extra code to
each ISR.
Differentiate between RET and RETI
RET
• The RET instruction returns the program from a subroutine.
8051 Interrupts and Interfacing Applications 199
• RET pops the return address from the stack and continue execution
there and making the 8051 return to where it left. The high byte
and low byte address of PC from the stack and decrements the
SP by 2.
• The execution of the instruction will result in the program to resume from the
location just after the CALL instruction.
• No flags are affected.
Example:
• Suppose SP=0BH originally and an interrupt is detected during the instruction
ending at location 0213H
ff RAM Internal locations 0AH and 0BH contain the values 14H and 02H
respectively.
ff The RET instruction leaves SP = 09H and returns program execution to
location 0214H.
RETI
• The RETI instruction returns the program from an interrupt subroutine.
• RETI pops the high byte and low byte address of a PC from
the stack and restores the interrupt logic to accept additional
interrupts.
• SP decrements by 2 and no other registers are affected. However the PSW is not
automatically restored to its pre-interrupt status.
• After the RETI, program execution will resume immediately after the point at
which the interrupt is detected.
• No flags are affected.
Example:
• Suppose SP=0BH originally and an interrupt is detected during the instruction
ending at location 0213H
ff RAM Internal locations 0AH and 0BH contain the values 14H and 02H
respectively.
ff The RETI instruction leaves SP=09H and returns program execution to
location 0214H.
Explain why we cannot use RET instead of RETI as the last instruction of
an ISR.
Solution:
• RET and RETI perform the same actions of popping off the top two bytes of the
200 8051 Microcontroller
stack into the program counter, and making the 8051 return to where it left.
• However, RETI also performs an additional task of clearing the interrupt-in-
service flag, indicating that the servicing of the interrupt is over and the 8051
now can accept a new interrupt on that pin.
• If we use RET instead of RETI as the last instruction of the interrupt service routine,
then it will simply block any new interrupt on that pin after the first interrupt, since
the pin status would indicate that the interrupt is still being serviced.
• In the case of TF0, TF1, TCON.1 and TCON.3, they are cleared due to the
execution of RETI.
5.1.10 Enabling or disabling of Interrupts.
1. Using bit instructions
Method 1 Method 2 Comments
SETB EA SETB IE. 7 ; EA=1 ;enable interrupts
SETB ET0 SETB IE. 1 ; ET0 = 1;enable timer 0 interrupt
SETB ET1 SETB IE. 3 ; ET1 = 1;enable timer 1 interrupt
SETB EX0 SETB IE. 0 ; EX0= 1;enable external 0 interrupt
CLR ES CLR IE. 4 ; ES=0 ;disable serial interrupt
CLR EX1 CLR IE. 2 ; EX1=0 ;disable external 1 interrupt
2. Using byte instruction
MOV IE, #10001011B 'OR' MOV IE, #8DH
Note: Bypassing interrupt vector table
ORG 0000H ;wake-up ROM reset locationi
LJMP TO ;bypass interrupt vectortable
; the wake-up program
ORG 30H
TO:
....
END
Example 5.4:
Write a C program using interrupts to do the following:
(a) Generate a 10000 Hz frequency on P2.1 using TO 8-bit auto-reload,
(b) Use timer 1 as an event counter to count up a 1-Hz pulse and display
it on P0. The pulse is connected to EX1. Assume that XTAL = 11.0592
MHz. Set the baud rate at 9600.
Solution:
include <reg51.h>
abit WAVE = P2^1;
8051 Interrupts and Interfacing Applications 201
P0 LEDs
8051
P2.1
10000 Hz
Fig.5.1.3: Generating square wave on P2.1
Example 5.:7
Show the instructions to
(a) Enable the serial interrupt, timer 0 interrupt, and external hardware
interrupt 1 (EX1),and
202 8051 Microcontroller
Example 5.8:
Write a program that displays a value of *Y at port l and 'N' at port 3
and also generates a square wave of 10 kHz with Timer 0 in mode 2 at
port pin P0.1. XTAL=22 MHz.
Solution:
;––– upon wake up, go to main,avoid using memory space allocated to
interrupt vectoi table
ORG 0000H
LJMP MAIN ;bypass interrupt vector table
;---ISR for Timer 0 to generate square wave
ORG 000BH ;Timer 0 interrupt vector
CPL P0.1
RETI
;---the main program for initialization
ORG 003OH ;a location after the interrupt vectors
MAIN: MOV TMOD,#02H ;Timer 0, mode 2 (auto-reload)
8051 Interrupts and Interfacing Applications 203
Example 5.9:
rite a program to generate two square waves one of 5 KHz frequency
W
at pin P1.1 and another of frequency 25 kHz at pin P2.1 Assume
XTAL = 22 MHz.
8051
P1.1 5 kHz
P2.1 25 kHz
Solution:
;Tested for an AT89C51 with a crystal frequency of 22 MHz.
ORG 0000H ;avoid using the interrupt vector table
LJMP MAIN
;--ISR for Timer 0
ORG 000B ;Interrupt vector for Timer 0
CPL Pl.l
RETI
;---ISR for Timer 1
ORG 001BH ;Interrupt vector for Timer 1
CPL P2.1
RETI
;---main program for initialization
ORG 0030H
MAIN: MOV TMOD,#22H ;both timers are initialized for Mode 2
MOV IE,#8AH ;enable the Timer 0 and Timer 1 Interrupts
MOV THO,#048H ;count value for 5 KHz square wave
MOV TH1,#0B6H ;count value for 25 KHz square wave
SETB TR0 ;start Timer 0
204 8051 Microcontroller
Example 5.10:
Two switches are connected to pins P3.2 and P 3.3. When a switch is
pressed, the corresponding line goes low. Write a program to
(a) light all LEDs connected to port 1, if the first switch is pressed.
(b) light all LEDs connected to port 2, if the second switch is pressed.
Solution:
Example 5.11:
Generate from all pins of Portl, a square wave which is half the frequency
of the signal applied at INTO pin.
8051 Interrupts and Interfacing Applications 205
Solution:
;Tested for an AT89C51 with a crystal frequency of 22 MHz.
Every negative edge at Pin 3.2 will cause the INT0 (vectored to location 0003) interrupt
to be activated.
ORG 0000H
LJMP MAIN
;--ISR for hardware interrupt INT0
ORG 0003H
CPL PI
RETI
ORG 0030H
MAIN: SETB TCON.0 ;make INTO an edge-triggered interrupt
MOV IE,#81H ;enable hardware interrupt INT0
HERE: SJMP HERE
END
Example 5.12:
Write a C program that continuously gets a single bit of data from P1.1
and sends it to P1.2, while simultaneously creating a square wave of 200
ms period on pin P1.3. Use timer 0 to create the square wave. Assume that
XTAL = 11.0592 MHz.
Solution:
We will use timer 0 in mode 2 (auto-reload). One half of the period is 100 μs.
100/1.085 μs = 92, and TH0 = 256 - 92 = 164 or A4H
200 μs/2 = 100μs 8051
100 μs / 1.085 μs = 92
Example 5.13:
Write a C program using interrupts to do the following:
(a) Generate a 10000 Hz frequency on P0.1 using TO 8-bit auto-reload,
(b) Use timer 1 as an event counter to count up a 1-Hz pulse and display
it on P1. The pulse is connected to EX1
Assume that XTAL = 11.0592 MHz. Set the baud rate at 9600.
Solution:
1 / 10000 Hz = 100 μs
100 μs / 2 = 50 μs
50 μs / 1.085 μis = 46
#include <reg51.h>
sbit WAVE = P0^1; 8051
unsigned char cnt;
P1 LEDs
void timer0() interrupt 1
{
WAVE = ~WAVE; //toggle pin
}
void timerl() interrupt 3 P0.1
10000 Hz
{
cnt++; //increment counter
PI = cnt; //display value on pins
}
void main()
{
cnt =0; //set counter to zero
TMOD = 0x42;
TH0 = 0x-46; //10000 Hz
IE = 0x86; //enable interrupts
8051 Interrupts and Interfacing Applications 207
Solution:
We will use timer 0 mode 2 (auto-reload).
T = T1 + T2
100μs
100μs
T = 200µs T1 T2
T
T1 = T2 = = 100µs
2 T=200μs
#include <reg51.h>
sbit SW=P1^7;
sbit S_data=P1^0;
sbit S_WAVE=P2^5;
void timer0(void) interrupt 1
{
S_WAVE=~S_WAVE; //toggle pin
}
void main()
{
SW=1; //make switch input
TMOD=0x02;
208 8051 Microcontroller
TH0=0xA4; //TH0=-92
IE=0x82; //enable interrupt for timer 0
while (1)
{
S_data=SW; //send switch to LED
} 8051
}
P1.0 LED
Example 5.15:
Write a C program using interrupts to do the following:
(a) Receive data serially and send it to P0
(b) Read port P1, transmit data serially, and give a copy to P2
(c) Make timer 0 generate a square wave of 5 kHz frequency
Assume that XTAL = 11.0592 MHz. Set the baud rate at 4800
Solution:
1 1 100μs
Time period T = = = 200µs 100μs
f 5KHz T1 T2
T = T1 + T2
T = 200µs T=200μs
T
T1 = T2 = = 100µs
2
Initial Count value:
Required delay × crystal freqyency
TH0 = Final value −
12
100µs × 11.0592 MHz
= 256 − = 256 − 92 = 164 = A4H
12
TH0 = A4H
#include <reg51.h>
8051 Interrupts and Interfacing Applications 209
sbit WAVE=P0^1;
void timer0() interrupt 1
{
WAVE=~WAVE; //toggle pin
}
void serial0() interrupt 4
{
if (TI==1)
{
TI=0; //clear interrupt
}
else
{
P0=SBUF; //put value on pins
RI=0; //clear interrupt
}
}
void main()
{
unsigned char x;
P1=0xFF; //make P1 an input
TMOD=0x22;
TH1=0xF6; //4800 baud rate
SCON=0x50;
TH0=0xA4; //5 kHz has T=200us
IE=0x92; //enable interrupts
TR1=1; //start timer 1
TR0=1; //start timer 0
while (1)
{
x=P1; //read value from pins
SBUF=x; //put value in buffer
P2=x; //write value to pins
}
}
210 8051 Microcontroller
Example 5.16:
Write a C program using interrupts to do the following:
(a) Generate a 10 KHz frequency on P2.1 using T0 8-bit auto-reload
(b) Use timer 1 as an event counter to count up a 1-Hz pulse and display
it on P0. The pulse is connected to EX1.
Assume that XTAL = 11.0592 MHz. Set the baud rate at 9600.
Solution:
#include <reg51.h>
sbit WAVE =P2^1;
unsigned char cnt;
void timer0 ( ) interrupt 1
{
WAVE=~WAVE; //toggle pin
}
void timer1() interrupt 3
{
cnt++; //increment counter
P0=cnt; //display value on pins
}
void main()
{
cnt=0; //set counter to 0
TMOD=0x42;
TH0=0x-46; //10 KHz
IE=0x86; //enable interrupts
TR0=1; //start timer 0
while (1); //wait until interrupted
}
Example 5.17:
Write an ALP and C Program to generate a square wave of 5 KHz with
Timer0 Mode2 at port pin P2.1 using interrupt mode. Also display a value
of “A’ at PORT 0. Use XTAL = 22 MHz.
Solution:
We know that
8051 Interrupts and Interfacing Applications 211
T = T1 + T2
1 1
T= = = 2 × 10 −4 s
f 5KHz
T
T1 = T2 = = 1 × 10 −4 s
2
5 kHz
Timer 0
T1 T2 Mode 2 P2.1
8051
T
P0 A
IE register configuration
Enable Enable
interrupts timer 0
Fig. 5.1.6: IE register configuration
Load IE = 82H
The instruction used is MOV IE,#82H OR SETB EA and SETB ET0
212 8051 Microcontroller
ALP
ORG 00H
SJMP MAIN ;jump to main program
ORG 000BH ;ISR for Timer0
CPL P2.1 ;Toggle pin P2.1 for square wave
RETI ;return from interrupt
ORG 30H ;main program written from 30H
MAIN: MOV TMOD, #02H ;Timer0, Mode2
MOV TH0, #49h ;initial value to generate 5 KHz
MOV IE,#82H ;Enable ET0=1 & EA=1
SETB TR0 ;start timer 0
MOV P0,#’A’ ;Display ‘A’ at PORT P0
SJMP AGAIN
END
C Program
#include <reg51.h>
void timer0(void) interrupt 1 // ISR for interrupt number 1
{
P2.1=~P2.1; //Toggle pin P2.1 for square wave
}
void main( )
{
TMOD=0x02; //use Timer 0, mode 2
IE=0x82; //Enable ET0=1 & EA=1
TH0=0x49; //initial value to generate 5 KHz
TR0=1; //start timer 0
while (1)
{
P0=”A”; //send “A” to P0
} //end of while
} //end of main
Example 5.18:
rite an ALP and C Program to generate two square waves of 25 KHz and
W
5 KHz at pins P0.1 and P0.2 respectively using timer 0 & timer 1 in Mode
2 in interrupt mode. Use XTAL = 22 MHz.
8051 Interrupts and Interfacing Applications 213
Solution:
25 kHz
Timer 0 P0.1 T2
T1
8051 5 kHz
Timer 1 P0.2 T
For 5 KHz
We know that
1 1
T= = = 0.2 ms
f 5KHz
T = T1 + T2
T
T1 = T2 = = 0.1 ms
2
Initial Count value:
Required delay × crystal freqyency
TH1 = Final value −
12
1 × 10 −4 s × 22 × 106
= 256 − = 256 − 183 = 73
12
TH1 = 49H
For 25 KHz
We know that
T = T1 + T2
1 1 T
T= = = 4 × 10−5 s T1 = T2 = = 2 × 10−5 s
f 25KHz 2
Initial Count value:
Required delay × crystal freqyency
TH0 = Final value −
12
2 × 10−5 s × 22 × 106
= 256 − = 256 − 37 = 219d
12
TH0 = DBH
214 8051 Microcontroller
IE register configuration
Load IE = 8AH
The instruction used is MOV IE,#8AH OR SETB EA, SETB ET1 and SETB ET0
ALP
ORG 00H
SJMP MAIN ;jump to main program
ORG 000BH ;ISR for Timer 0
CPL P0.1 ;Toggle pin P0.1 for square wave
RETI ;return from interrupt
ORG 001BH ;ISR for Timer 1
CPL P0.2 ;Toggle pin P0.2 for square wave
RETI ;return from interrupt
ORG 30H ;main program written from 30H
MAIN: MOV TMOD, #22H ;Timer0 & Timer1 in Mode2
MOV IE,#8AH ;Enable ET0=1, ET1=1 & EA=1
MOV TH0, #0DBH ;initial value to generate 25 KHz
MOV TH0, #49h ;initial value to generate 5 KHz
SETB TR0 ;start timer 0
SETB TR1 ;start timer 1
AGAIN: SJMP AGAIN
END
Note: T
he instruction SJMP HERE executes continuously until an interrupt occurs,
it jumps to Timer 0 or Timer 1 ISR and services it and then return to the main
program i.e. SJMP HERE
8051 Interrupts and Interfacing Applications 215
C Program
#include <reg51.h>
void timer0(void) interrupt 1 // ISR for interrupt number 1
{
P0.1=~P0.1; //Toggle pin P0.1 for square wave
}
void timer1(void) interrupt 3 // ISR for interrupt number 3
{
P0.2=~P0.2; //Toggle pin P0.2 for square wave
}
void main( )
{
TMOD=0x22; //use Timer 0, Timer 1 in mode 2
IE=0x8A; //Enable ET0=1, ET1=1 & EA=1
TH0=0xDB; //initial value to generate 25 KHz
TH1=0x49; //initial value to generate 5 KHz
TR0=1; //start timer 0
TR1=1; //start timer 1
while (1); //wait for indefinite time
} //end of main
5.2.1 Introduction
VCC
Analog Binary
ADC
signal output
input
• The ADC consists of an analog input, digital outputs, control lines and power
supply as shown in figure. 6.3.1.
• ADC converts an input analog signal to a digital output.
• ADCs are mainly classified into
i. Serial ADCs and
ii. Parallel ADCs
5.2.2 Pin diagram of ADC0804
CS 1 20 VCC(or VREF)
RD 2 19 CLK R
WR 3 18 DB0(LSB)
CLK IN 4 17 D1
INTR 5 16 D2
ADC0804
VIN(+) 6 15 D3
VIN(–) 7 14 D4
A GND 8 13 D5
VREF/2 9 12 D6
D GND 10 11 D7(MSB)
1
f=
1.1 RC
––––––
5 INT R • This is an active low output pin.
––––––
• When INT R = 0, indicate end of conversion (EOC)
to 8051.
6 & 7 VIN(+)& VIN(-) • VIN(+) pin is connected with analog input to be
converted to digital
• VIN(-) pin is connected to ground
• These are the differential analog input given by
VIN = VIN(+) - VIN(-)
2. Keep monitoring the INTR pin. If INTR is low, the conversion is finished and we
can go to the next step. If INTR is high, keep polling until it goes low.
3. After the INTR has become low, we make CS=0 and send a high-to-low pulse to
the RD pin to get the data out of the ADC0804 IC chip. The timing diagram for
this process is shown in figure. 5.2.3
Note: CS is set to low for both RD and WR pulses
WR
D0-D7 Data out
INTR
Start conversion End conversion
RD
Read it
Fig. 5.2.3: Read and Write Timing for ADC0804
Example 5.19:
rite the schematic, algorithm and a program to interface a ADC 0804
W
to 8051 +5V
8051 ADC0804
VCC 10K 150pF
P2.5 RD
P2.6 WR CLK R
CLK IN +5V
P1.0 D0
Vref/2 1.28V
Vin(+) 10K
Vin(–)
POT
P1.7 AGND
D7
CS
P2.7 INTR GND
ALGORITHM
1. Set P1 as input port and P2.7 as input pin
2. Send a start of conversion to ADC. WR = low to high signal.
3. Wait for end of conversion by reading in the INTR pin (INTR = EOC = 0)
4. Enable RD =0, so that converted data is put on D0-D7 lines
5. Read in the digital data on D0-D7 using P1
6. Call hexadecimal to ASCII conversion.
7. Call data display to display the ASCII values on LCD.
{
unsigned char value;
MYDATA = OxFF; //make PI and input
INTR = 1; //make INTR and input
RD = 1; //set RD high
WR = 1; //set WR high
while(1)
{
WR = 0; //send WR pulse
WR = 1; //L-to-H(Start Conversion)
while(INTR == 1); //wait for EOC
RD = 0; //send RD pulse
value = MYDATA; //read value
ConvertAndDisplay(value); //Display value on LCD
RD = 1;
}
}
5.3.1 Introduction
LCD is finding widespread use replacing LEDs
• The declining prices of LCD
• The ability to display numbers, characters, and graphics
• Incorporation of a refreshing controller into the LCD, thereby relieving the CPU
of the task of refreshing the LCD
• Ease of programming for characters and graphics.
D0-D7 Data
tD
E
R/W tAS tAH
RS
tAH = Hold time after E has
come down for both RS and
R/W = 10ns(minimum)
tAS = Setup time prior to E
(going high) for both RS and
R/W = 140ns(minimum)
Example 5.14:
Write the schematic, algorithm and a program to interface a alphanumeric
LCD to 8051 and to display ‘INDIA’
+5V
P1.0 D0 VCC
10K
LCD VEE
P1.7 D7 P0T
ALGORITHM
1. Initialize the LCD using the lcdcmd subroutine.
2. Send the commands 38H, 0EH, 01H, 06H and 86H to PORT P1
3. Make RS = 0 & R/W = 0
4. Make enable Pin E=1 for a 1 ms.
5. Make enable Pin E=0
6. Return to calling program
end the ASCII value ‘I’, ‘N’, ‘D’, ‘I’, ‘A’ to PORT P1 and call lcddata subroutine
7. S
with 250 ms delay.
8. Make RS = 1 & R/W = 0
9. Make enable Pin E=1 for a 1 ms.
10. Make enable Pin E=0
11. Return to calling program
ORG 00H
MOV A,#38H ;Initialize LCD 2 LINES, 5X7 MATRIX
ACALL COMNWRT ;call command subroutine
ACALL DELAY ;give LCD some time
MOV A,#0EH ;display on, cursor on
ACALL COMNWRT ;call command subroutine
ACALL DELAY ;give LCD some time
MOV A,#01 ;clear LCD
ACALL COMNWRT ;call command subroutine
ACALL DELAY ;give LCD some time
MOV A,#06H ;shift cursor right
ACALL COMNWRT ;call command subroutine
ACALL DELAY ;give LCD some time
MOV A,#84H ;cursor at line 1, pos. 4
ACALL COMNWRT ;call command subroutine
ACALL DELAY ;give LCD some time
MOV A,#’I’ ;display letter I
ACALL DATAWRT ;call display subroutine
ACALL DELAY ;give LCD some time
MOV A,#’N’ ;display letter N
ACALL DATAWRT ;call display subroutine
ACALL DELAY ;give LCD some time
MOV A,#’D’ ;display letter D
ACALL DATAWRT ;call display subroutine
ACALL DELAY ;give LCD some time
MOV A,#’I’ ;display letter I
ACALL DATAWRT ;call display subroutine
ACALL DELAY ;give LCD some time
MOV A,#’A’ ;display letter A
ACALL DATAWRT ;call display subroutine
AGAIN: SJMP AGAIN ;stay here
COMNWRT: ;send command to LCD
MOV P1,A ;copy reg A to port 1
8051 Interrupts and Interfacing Applications 225
void main()
{
lcdcmd(0x38);
delay(250);
lcdcmd(0x0E);
226 8051 Microcontroller
delay(250);
lcdcmd(0x01);
delay(250);
lcdcmd(0x06);
delay(250);
lcdcmd(0x86);
delay(250);
lcddata(‘I’);
delay(250);
lcddata(‘N’);
delay(250);
lcddata(‘D’);
delay(250);
lcddata(‘I’);
delay(250);
lcddata(‘A’);
}
void lcdcmd(unsigned char value)
{
ldata = value; //put the value on the pins
RS=0;
RW=0;
E=1; //strobe the enable pin
delay(1);
E=0;
return;
}
void lcddata(unsigned char value)
{
ldata = value; //put the value on the pins
RS=1;
RW=0;
E=1; //strobe the enable pin
delay(1);
E=0;
return;
}
void delay(unsigned int count)
{
unsigned int i, j;
8051 Interrupts and Interfacing Applications 227
for(i=0;i<count;i++)
for(j=0;j<1275;j++);
}
Example 5.15:
Write the schematic, algorithm and a program to interface a alphanumeric
LCD to 8051 and to display ‘HELLO’
+5V
P1.0 D0 VCC
10K POT
LCD VEE
P1.7 D7
8051 RS R/W E VSS
P2.0
P2.1
P2.2
ORG 00H
MOV A,#38H ;initialize LCD 2 lines ,5x7 matrix
ACALL COMMAND ;issue command
MOV A,#0EH ;LCD on, cursor on
ACALL COMMAND ;issue command
MOV A,#01H ;clear LCD command
ACALL COMMAND ;issue command
MOV A,#06H ;shift cursor right
ACALL COMMAND ;issue command
MOV A,#86H ;cursor: line 1, pos. 6
ACALL COMMAND ;command subroutine
COMMAND:
ACALL READY ;is LCD ready?
MOV P1,A ;issue command code
CLR P2.0 ;RS=0 for command
CLR P2.1 ;R/W=0 to write to LCD
SETB P2.2 ;E=1 for H-to-L pulse
CLR P2.2 ;E=0,latch in
RET
DATA_DISPLAY:
ACALL READY ;is LCD ready?
MOV P1,A ;issue data
8051 Interrupts and Interfacing Applications 229
delay(250);
lcdcmd(‘E’);
delay(250);
lcdcmd(‘L’);
delay(250);
lcdcmd(‘L’);
delay(250);
lcdcmd(‘O’);
}
5.4 Stepper Motor
5.4.1 Introduction
A
N
C O D
N
S
N Average
S North
A
O
C D
N
S
B
COM
Average N C
South S D
COM
B
Fig. 5.4.1 ROTOR Alignment Fig. 5.4.2: Stator Windings configuration
• A stepper motor translates electrical pulses into mechanical movements. Stepper
motors have a permanent magnet rotor called shaft surrounded by a stator.
• A stepper motor or step motor or stepping motor is a brushless DC electric
motor that divides a full rotation into a number of equal steps. The motor’s
position can then be commanded to move and hold at one of these steps.
The most common stepper motor has four stator windings that are paired with
center-tapped common as shown in figure. This type of stepper motor is commonly
referred to as a four-phase or unipolar stepper motor. The center tap allows a change
of current direction in each of two coils when a winding is grounded, thereby resulting
in a polarity change of the stator. Notice that while a conventional motor shaft runs
freely, the stepper motor shaft moves in fixed repeatable increment, which alone one
to move it to a precise position.
232 8051 Microcontroller
The direction of the rotation is dictated by the stator poles. The stator poles are
determined by the current sent through the wire coils. As the direction of the current
is changed, the polarity is also changed causing the reverse motion of the rotor. The
stepper motor has a total of 6 leads: 4 leads representing the four stator winding and
2 common for the center-tapped leads.
The figure explains the stepper motor control system.
To stepper motor
+5V
+5V supply
Unipolar Stepper
4.7k
4.7k
4.7k
4.7k
degrees rotation step. These four coils are activated in the cyclic order. The
figure shown gives the direction of rotation of the shaft of the stepper motor.
There are different methods to drive a stepper motor. Some of these are
explained below.
Full Step Drive (1.80/Step): In this method two coils are energized at a time. Thus,
here two opposite coils are excited at a time.
Half Step Drive (0.90/Step): In this method coils are energized alternatively.
Thus it rotates with half step angle. In this method, two coils can be energized
at a time or single coil can be energized. Thus it increases the number of
rotations per cycle.
Control Switch
Example 5.16:
Sketch the schematic for interfacing a stepper motor to 8051
Solution:
To stepper motor
+5V
+5V supply
Unipolar Stepper
4.7k
4.7k
4.7k
4.7k
Example 5.17:
Write the schematic, algorithm and a program to interface a stepper motor
to 8051 and to rotate the motor in clock wise direction using normal 4 step
sequence
Solution:
To stepper motor
+5V
+5V supply
Unipolar Stepper
4.7k
4.7k
4.7k
4.7k
DS89C4x0 9 ULN2003 Motor
P1.0
P1.1
P1.2
P1.3
8
Algorithm
1. For clockwise direction, load the sequence 66H into P1
2. Call 100 msdelay
3. Load the sequence 33H into P1
4. Call 100 msdelay
5. Load the sequence 99H into P1
6. Call 100 msdelay
7. Load the sequence CCH into P1
8. Call 100 msdelay
9. Repeat from step 1
236 8051 Microcontroller
Method 1 Method 2
ORG 00H ORG 00H
BACK: MOV A,#66H BACK: MOV P1, #66H
MOV P1,A ACALL DELAY
RR A MOV P1, #33H
ACALL DELAY ACALL DELAY
MOV P1, #99H
SJMP BACK ACALL DELAY
MOV P1, #CCH
DELAY:MOV R0,#255 ACALL DELAY
UP1: MOV R1,#255 SJMP BACK
UP2: DJNZ R1,UP2 DELAY: MOV R0,#255
DJNZ R0,UP1 UP1: MOV R1,#255
RET UP2: DJNZ R1,UP2
END DJNZ R0,UP1
RET
END
C language interfacing programming
#include <reg51.h>
void delay(unsigned int i);
void main ( )
{
while (1)
{
P1 = 0x66;
delay (100);
P1 = 0x33H;
delay (100);
P1 = 0x99;
delay (100);
P1 = 0xCC;
delay (100);
}
}
void delay(unsigned int count)
{
unsignedint i, j;
for(i=0;i<count;i++)
for(j=0;j<1275;j++);
}
8051 Interrupts and Interfacing Applications 237
Example 5.18:
Write the schematic, algorithm and a program to interface a stepper motor to 8051
and to rotate the motor in anti-clock wise direction using wave drive sequence
Solution: +5V To stepper motor
+5V
supply
Unipolar Stepper
4.7k
4.7k
4.7k
DS89C4x0 4.7k 9 ULN2003 Motor
P1.0
P1.1
P1.2
P1.3
8
In wave-drive 4-step sequence, the initial values to be used for clockwise are 8H,
4H, 2H and 1H.
In wave-drive 4-step sequence, the initial values to be used for counter-clockwise are
1H, 2H, 4H and 8H.
Algorithm
1. Port 1 is used as output port
2. Load the sequence 01H into P1
3. Call 100 msdelay
4. Load the sequence 02H into P1
5. Call 100 msdelay
238 8051 Microcontroller
Method 1 Method 2
ORG 00H ORG 00H
BACK: MOV A,#01H BACK: MOV P1, #01H
MOV P1,A ACALL DELAY
RL A MOV P1, #02H
ACALL DELAY ACALL DELAY
MOV P1, #04H
SJMP BACK ACALL DELAY
MOV P1, #08H
DELAY: MOV R0,#255 ACALL DELAY
UP1: MOV R1,#255
UP2: DJNZ R1,UP2 SJMP BACK
DJNZ R0,UP1
RET DELAY: MOV R0,#255
END UP1: MOV R1,#255
UP2: DJNZ R1,UP2
DJNZ R0,UP1
RET
END
C Program
#include <reg51.h>
void delay(unsigned int i);
void main ( )
{
while (1)
{
P1=0x11;
delay (100);
P1=0x22;
delay (100);
8051 Interrupts and Interfacing Applications 239
P1=0x44;
delay (100);
P1 = 0x88;
delay (100);
}
}
void delay(unsigned int count)
{
unsigned int i, j;
for(i=0;i<count;i++)
for(j=0;j<1275;j++);
}
Example 5.19:
A switch is connected to pin P2.7. Write a C program to monitor the
status of SW and perform the following:
i. If SW = 0, the stepper motor moves clockwise.
ii. If SW = 1, the stepper motor moves counterclockwise.
Solution:
• To generate the full-step 4-step sequence, the initial values to be used for
clockwise are 66H, 33H, 99H and CCH.
• To generate the full-step 4-step sequence, the initial values to be used for
counter-clockwise are CCH, 99H, 33H and 66H.
+5
+12V
ILQ74 +12 Unipolar Stepper
470
470
470
470
The optoisolator
Use one power supply
provides additional
for the motor and
protection of the 8051
ULN2003 and another
+12V
for the 8051
Algorithm
1. If SW = 0, rotate the motor in clockwise direction
2. Load the sequence 66H into P1
3. Call 100 msdelay
4. Load the sequence 33H into P1
5. Call 100 msdelay
6. Load the sequence 99H into P1
7. Call 100 msdelay
8. Load the sequence CCH into P1
9. Call 100 msdelay
10. Else (i.e. if SW =1)
11. Rotate motor in counterclockwise direction i.e. load the sequence CCH into P1
12. Call 100 msdelay
13. Load the sequence 99H into P1
14. Call 100 msdelay
15. Load the sequence 33H into P1
16. Call 100 msdelay
17. Load the sequence 66H into P1
18. Call 100 msdelay
19. Repeat from step 1
Method 1 Method 2
ORG 00H ORG 00H
SETB P2.7 SETB P2.7
MOV A, #66H
NEXT: JNB P2.7, CLOCKWISE BACK: JNB P2.7, CLOCKWISE
RL A
MOV P1, A MOV P1, #CCH
ACALL DELAY ACALL DELAY
SJMP NEXT MOV P1, #99H
CLOCKWISE: RR A ACALL DELAY
MOV P1, A MOV P1, #33H
ACALL DELAY ACALL DELAY
SJMP NEXT MOV P1, #66H
DELAY: MOV R0, #255 ACALL DELAY
UP2: MOV R1, #255 SJMP BACK
Continued...
8051 Interrupts and Interfacing Applications 241
SJMP BACK
{
P1 = 0xCC;
delay (100);
P1 = 0x99;
delay (100);
P1 = 0x33;
delay (100);
P1 = 0x66;
delay (100);
}
}
}
void delay(unsigned int count)
{
unsignedint i, j;
for(i=0;i<count;i++)
for(j=0;j<1275;j++);
}
Example 5.20:
Write a program to rotate a motor 80o in the clockwise direction. The
motor has a step angle of 2o. Use the 4-step sequence.
Solution:
+5
+12V
ILQ74 +12 Unipolar Stepper
470
470
470
470
The optoisolator
Use one power supply
provides additional
for the motor and
protection of the 8051
ULN2003 and another
+12V
for the 8051
Algorithm
1. Initialize a counter with 40 steps
2. Load the sequence 66H into P1
3. Call delay
4. For clockwise direction rotate the phase sequence right
5. Decrement counter (R0) and repeat from step 1 until counter is zero
6. If counter is zero i.e. R0=0, Stop.
while (1);
}
void delay(unsigned int count)
{
unsignedint i, j;
for(i=0;i<count;i++)
for(j=0;j<1275;j++);
}
Example 5.21:
Write a program to rotate a motor 80o in the clockwise direction. The
motor has a step angle of 2o. Use the 4-step sequence.
Solution:
Algorithm
1. Initialize a counter with 40 steps
2. Load the sequence 66H into P1
3. Call delay
4. For clockwise direction rotate the phase sequence right
5. Decrement counter (R0) and repeat from step 1 until counter is zero
6. If counter is zero i.e. R0=0, Stop.
+5
+12V
ILQ74 +12 Unipolar Stepper
470
470
470
470
The optoisolator
Use one power supply
provides additional
for the motor and
protection of the 8051
ULN2003 and another
+12V
for the 8051
Solution:
+5
+12V
ILQ74 +12 Unipolar Stepper
470
470
470
470
8051 1 Opto 10 ULN2003 Motor
1K
P1.0 2 16
3 15
4 14 1K
P1.1
6 13 1K
P1.2 5 12
8 11
10 1K
P1.3 7
P2.7 9
9
The optoisolator
Use one power supply
provides additional
for the motor and
protection of the 8051
ULN2003 and another
+12V
for the 8051
ORG 0200H
DB 8,4,2,1
END
C language interfacing programming
#include <reg51.h>
void main ( )
{
code unsigned char sequence[]={08,04,02,01};
unsigned char i;
while(1)
{
for(i=0;i<4;i++)
{ P1=sequence[i];
delay(100);
}
}
}
void delay(unsigned int count)
{
unsignedint i, j;
for(i=0;i<count;i++)
for(j=0;j<1275;j++);
}
ii. Clockwise using the half-step 8-step sequence.
Algorithm
1. Initialize a counter R0 for 08 steps
2. Initialize the starting address of the sequence table
3. Get value from the sequence table and output to port P1
4. Increment the DPTR pointer
5. Decrement counter (R0) and repeat from step 3 until counter is zero
6. If counter is zero i.e. R0=0, repeat from step 1.
Assembly language interfacing programming
ORG 00H
UP: MOV R0, #08
248 8051 Microcontroller
ORG 0100H
DB 09, 08, 0CH, 04, 06,02,03,01
END
C language interfacing programming
#include <reg51.h>
void main ( )
{
code unsigned char sequence[]={09,08,0x0C,04,06,02,03,01};
unsigned char i;
while(1)
{
for(i=0;i<8;i++)
{ P1=sequence[i];
delay(100);
}
}
}
void delay(unsigned int count)
{
unsigned int i, j;
for(i=0;i<count;i++)
for(j=0;j<1275;j++);
}
8051 Programs
8051 Programs
1. Show the stack contents, SP contents and contents of any register affected
after each step of the following sequence of operation.
Solution:
PROGRAM SP STACK CONTENT REGISTER CONTENT
MOV SP,#70H 70H - -
MOV R5,#30H 70H - R5=30H
MOV A,#44H 70H - A=44H
ADD A,R5 70H - A=74H
MOV R4,A 70H - R4=74H
PUSH 4 71H 74H R4=74H
PUSH 5 72H 30H R5=30H
POP 4 71H - R4=30H
2. Write a program to logically OR the contents of ports P1 & P2 and put the
result in external RAM location.
Solution:
ORG 00H
MOV DPTR,#0100H
MPV P1,#0FFH
MOV P2,#0FFH
MOV A,P1
MOV R0,P1
ORL A,R2
249
250 8051 Microcontroller
MOVX @DPTR,A
END
3. Find the sum of the values 79h,F5h & E2h; put the sum in registers R0
(low byte) & R5 (higher byte).
Solution:
ORG 00H
MOV R0,#00H
MOV A,#79H
ADD A,#0F5H
ADDC A,#0E2H
MOV R5,A
JNC NOCARRY
INC R0
NOCARRY: END
5. Find the status of carry flag after the following code sequence.
Solution:
i) CLR A ii) CLR C iii) CLR C
ADD A,#0FFH JNC OVER JC OVER
JNC OVER CPL C SETB C CPL C
OVER: OVER: OVER:
6. Write an ALP to add two input data of 16-bit result in 4 distinct addressing
modes.
Solution:
Immediate Direct Register Indirect Addressing
ORG 00H ORG 00H ORG 00H ORG 00H
MOV A,#0FFH MOV A,40H MOV R0,#0FFH MOV R0,#40H
ADD A,#0FFH ADD A,41H MOVR1,#0FFH MOV R1,#51H
END MOV 51H,A MOV A,R0 MOV A,@R0
JNC NOCARRY ADD A,R1 INC R0
INCR2 MOV R3,A ADD A,@R0
NOCARRY: MOV 50H,R2 JNC NOCARRY MOV @R1,A
END INCR2 JNC NOCARRY
NOCARRY:END INC R2
NOCARRY: MOV A,R2
DEC R1
MOV @R1,A
END
252 8051 Microcontroller
7. Write a program to put the number 34H in registers R4, R5, R6 & R7 using
different addressing modes.
Solution:
Immediate Direct Register Indirect Addressing
ORG 00H ORG 00H ORG 00H ORG 00H
MOV R4,#34H MOV 40H,#34H MOV A,#34H MOV R0,#40H
MOV R5,#34H MOV R4, 40H MOV R4,A MOV 04H,@R0
MOV R6,#34H MOV R5, 40H MOV R5,A MOV 05H,@R0
MOV R7,#34H MOV R6, 40H MOV R6,A MOV 06H,@R0
END MOV R7, 40H MOV R7,A MOV 07H,@R0
END END END
8. Write an ALP in 8051 to perform the following operation: Z = (X1 + Y1)
* (X2 + Y2) where, X1, X2, Y1 and Y2 are the 8-bit hexadecimal numbers
stored in the RAM locations. Write a subroutine for the addition and
assume that each addition result with 8 bit number.
Solution:
et X 1,Y 1,X2 & Y2 are stored at memory locations 30H, 31H, 32H and 33H,
L
respectively and results will be stored at memory locations 34H and 35H.
ORG 00H
MOV R0, #30H
ACALL ADDITION
MOVR1, A
INC R0
ACALL ADDITION
MOV B, R1
MUL AB
MOV 34H, A
MOV 35H, B
SJMP EXIT
ADDITION:
MOV A,@R0
INC R0
ADD A,@R0
RET
EXIT:
END
8051 Programs 253
9. Write an ALP to clear both R0 & R1 of Bank 1 & Bank 2 without using their
direct address.
Solution:
ORG 00H
SETB PSW.3
CLR PSW.4
MOV R0,#00H
MOVR1,#00H
CLR PSW.3
SETB PSW.4
MOV R0,#00H
MOVR1,#00H
END
10. Write an ALP to clear R0 of bank 1 & bank 3 without using its address.
Solution:
ORG 00H
SETB PSW.3
CLR PSW.4
MOV R0,#00H
SETB PSW.3
SETB PSW.4
MOV R0,#00H
END
11. Write a program to set the carry flag to 1, if the number in reg. A is even
and reset the carry flag to 0, if the number in reg. A is ODD. Use the
assembly language of 8051.
Method-1 Method-2 Method-3
ORG 00H ORG 00H ORG 00H
MOV A,30H MOV A,30H MOV A,30H
RRC A RRC A ADD A,#00H
JNC NEXT JC NEXT JB PSW.0, NEXT
SETB C CLR C CLR C
SJMP EXIT SJMP EXIT SJMP EXIT
NEXT: CLR C NEXT: SETB C NEXT: SETB C
EXIT: END EXIT: END EXIT: END
254 8051 Microcontroller
15. Write a C-program to toggle all bits of P0 & P2 continuously with 250
msec delay. Use inverting operator.
Solution:
#include<reg51.h>
void delay(unsigned int);
void main()
{
P0=0x55;
P2=0x55;
while(1)
{
P0= P0;
P2= P2;
delay(250);
}
}
void delay(unsigned int count)
{
unsigned int i,j;
for(i=0;ijcount;i++)
for(j = 0;ji1275;j ++);
}
16. A switch (sw) is connected to P2.0 port pin. Write a C-program to send
out the values 44H serially one bit at a time via P1.0,depending upon the
switch condition: when SW=0; LSB should go out first, when SW=1; MSB
should go out first.
Solution:
#include<reg51.h>
sbit Pin0=P1 ^0;
sbitALSB = ACC^0;
sbitAMSB = ACC^7;
sbitSW = P 2^0;
voidmain( )
256 8051 Microcontroller
{
unsigned char mydata = 0x44;
unsigned char i;
ACC = mydata;
if (SW ==0)
{
for (i = 0; i < 8; i + +)
{
pin = ALSB;
ACC = ACC>> 1;
}
}
else
{
for (i = 0; i < 8; i + +)
{
pin = AMSB;
ACC = ACC << 1;
}
}
}
18. Write an 8051 C-program to toggle all the bits of P1, P2 & P0 continuously
with a 250 msec delay. Use SFR keyword to declare the port address.
Solution:
sfr P0=0x80;
sfr P1=0x90;
sfr P2=0xA0;
void delay(unsigned int);
void main()
{
while(1)
{
P0=0x55;
P1 = 0x55;
8051 Programs 257
P2=0x55;
delay(250);
P0=0xAA;
P1 = 0xAA;
P2=0xAA;
delay(250);
}
}
void delay(unsigned int count)
{
unsigned int i,j;
for(i=0;iicount;i++)
for(j = 0;ji1275;j ++);
}
19. Write an 8051 C-program to convert a given hex-data 0FFH into its
equivalent decimal data and display the result digits on P0, P1 & P2.
Solution:
#include<reg51.h>
void main()
{
unsigned char x, bindata, dl, dm, dh;
bindata=0xFF;
x=bindata/10;
dl=bindata%10;
dm=x%10;
dh=x/10;
P0=dl;
P1=dm;
P2=dh;
}
20. Write a C-program in 8051 to convert packed BCD 0x39 to ASCII and display
the bytes on P1 & P2.
258 8051 Microcontroller
Solution:
#include<reg51.h>
void main()
{
unsigned char x,y,z;
unsigned char mydata=0x39;
x=mydata & 0x0F;
P1=x | 0x30;
y = mydata & 0xP0;
y = y » 4;
P2 = y | 0x30;
}
void main()
{
while(1)
{
P1 = 0x55;
delay(250);
P1 = 0xAA;
delay(250);
}
}
void delay(unsigned int count)
{
unsigned int i,j;
for(i=0;ijcount;i++)
for(j = 0;ji1275;j ++);
}