Microcontrollers and Applications
Microcontrollers and Applications
Microcontrollers and Applications
(i)
ii | Microcontrollers and Applications
MICROCONTROLLERS AND
APPLICATIONS
Author
Prof. Santanu Chattopadhyay
Professor,
Dept. of Electronics and Electrical Communication Engineering
IIT Kharagpur, West Bengal
Reviewer
Dr. C.H. Vithalani
Professor,
Electronics and Communication Engineering (ECE),
Gujarat Technological University,
L.D. College of Engineering, Navarangpura, Ahmedabad, Gujarat
(ii)
BOOK AUTHOR DETAILS
Prof. Santanu Chattopadhyay, Prof (HAG), Electronics and Communication Engineering (ECE),
Dept. of Electronics & Electrical Communication Engineering, IIT Kharagpur, West Midnapur,
721302, West Bengal
Email ID: [email protected]
1. Dr. Amit Kumar Srivastava, Director, Faculty Development Cell, All India Council for
Technical Education (AICTE), New Delhi, India
Email ID: [email protected]
Phone Number: 011-29581312
2. Mr. Sanjoy Das, Assistant Director, Faculty Development Cell, All India Council for Technical
Education (AICTE), New Delhi, India
Email ID: [email protected]
Phone Number: 011-29581339
January, 2023
© All India Council for Technical Education (AICTE)
ISBN : 978-81-960576-0-2
All rights reserved. No part of this work may be reproduced in any form, by mimeograph or
any other means, without permission in writing from the All India Council for Technical
Education (AICTE).
Further information about All India Council for Technical Education (AICTE) courses may be
obtained from the Council Office at Nelson Mandela Marg, Vasant Kunj, New Delhi-110070.
Printed and published by All India Council for Technical Education (AICTE), New Delhi.
Laser Typeset by:
Printed at:
Disclaimer: The website links provided by the author in this book are placed for informational,
educational & reference purpose only. The Publisher do not endorse these website links or the
views of the speaker / content of the said weblinks. In case of any dispute, all legal matters to be
settled under Delhi Jurisdiction, only.
(iii)
iv | Microcontrollers and Applications
(iv)
ACKNOWLEDGEMENT
The author is grateful to the authorities of AICTE, particularly Prof. T. G. Sitharam,
Chairman; Prof. M. P. Poonia, Vice-Chairman; Prof. Rajive Kumar, Member-
Secretary and Dr. Amit Kumar Srivastava, Director, Faculty Development Cell for
their planning to publish the book on Microcontrollers and Applications. I sincerely
acknowledge the valuable contributions of the reviewer of the book Dr. Chandulal
Vithalani, Professor, Department of Electronics and Communication Engineering,
L.D. College of Engineering, Ahmedabad for going through the entire manuscript
line-by-line and providing valuable suggestions for content improvements. My
sincere thanks to my wife Santana for being the constant source of inspiration to write
this, as well as, several other books in the past. I would also like to mention about our
son Sayantan, who always pushes me to newer challenges to put my knowledge into
black and white – leading to this book as well.
This book is an outcome of various suggestions of AICTE members, experts and
authors who shared their opinion and thought to further develop the engineering
education in our country. Acknowledgements are due to the contributors and different
workers in this field whose published books, review articles, papers, photographs,
footnotes, references and other valuable information enriched me at the time of
writing the book.
Santanu Chattopadhyay
(v)
vi | Microcontrollers and Applications
PREFACE
In electronic system design, microcontrollers have become a very important component.
Digital systems interacting with the environment need computation power for signal
processing or for executing a control algorithm. As an electronic system designer,
particularly in the digital domain, one should have a good grasp on the features,
architectures, programming techniques and interfacing requirements of various
microcontrollers, available in the market. Though it is a difficult task to have very good
knowledge on each of the alternatives available, one should be able to select the best
possible solution for a given application and go ahead with the design and development
task without much inconvenience.
To address the issue of application development using microcontrollers, this
book attempts to provide a deep understanding for the microcontroller 8051. In order
to introduce the concepts related to microcontrollers, first some basic topics on
computer organization, 8085 and 8086 microprocessors have been discussed. This will
help the reader to prepare the background to initiate the study on microcontrollers.
The features of generic microcontrollers have been elaborated to establish their
requirement, over and above the existing microprocessors. The architecture,
programming and interfacing issues of the 8051 have been elaborated in sufficient
detail. Connecting keyboard, LEDs, 7-segment displays, LCDs to the 8051 have been
illustrated. To interact with the world, which is analog in nature, analog-to-digital and
digital-to-analog converter (ADC and DAC) interfacing techniques have been
enumerated. The 8051 supports both the parallel and the serial modes of
communication. Both the modes have been illustrated for data transfer to/from the
8051 chip. Apart from assembly language programming for interfacing and control
algorithms, Embedded C language has been explored. Along with that, some commonly
used advanced microcontrollers, such as, PIC, AVR and ARM have also been
introduced to provide a working knowledge of those processors.
Processor architectures could be classified into two main categories – CISC
(Complex Instruction Set Computer) and RISC (Reduced Instruction Set Computer).
Features of both the RISC and the CISC architectures have been detailed. This has
been followed by the discussion on advanced microcontrollers (PIC, AVR, and ARM)
that attempt to mix the good features of both RISC and CISC architectures. Most of the
advanced processors possess built-in peripherals, such as, timers, ADCs etc. They also
possess several communication standards supported and different power-down modes
suitable for low-power applications. Discussions have been included to enumerate
such options.
(vi)
The book is an outcome of the author’s experience of handling the theory and
laboratory courses on subjects like Microprocessors, Microcontrollers and Embedded
Systems for more than two decades. It is expected that the book will be highly useful to
the students and the subject teachers, for whom it has been primarily meant for. It may
also be useful to anybody starting a career as an embedded system designer. Any
constructive suggestion to improve the quality of the book in its future editions is most
welcome.
Santanu Chattopadhyay
(vii)
viii | Microcontrollers and Applications
OUTCOME BASED EDUCATION
For the implementation of an outcome based education the first requirement is to
develop an outcome based curriculum and incorporate an outcome based assessment
in the education system. By going through outcome based assessments, evaluators will
be able to evaluate whether the students have achieved the outlined standard, specific
and measurable outcomes. With the proper incorporation of outcome based education
there will be a definite commitment to achieve a minimum standard for all learners
without giving up at any level. At the end of the programme running with the aid of
outcome based education, a student will be able to arrive at the following outcomes:
Programme Outcomes (POs) are statements that describe what students are
expected to know and be able to do upon graduating from the program. These relate to
the skills, knowledge, analytical ability attitude and behaviour that students acquire
through the program. The POs essentially indicate what the students can do from
subject-wise knowledge acquired by them during the program. As such, POs define the
professional profile of an engineering diploma graduate.
National Board of Accreditation (NBA) has defined the following seven POs for
an Engineering diploma graduate:
(viii)
COURSE OUTCOMES
By the end of the course the students will be able to:
CO-1: Understand and Compare Fundamentals of Microprocessors and Microcontrollers.
CO-2: Illustrate Architecture of AT 8051Microcontroller.
CO-3: Implement C- Language Programs for Data Manipulation and Interfacing.
CO-4: Interface I/O and Peripheral Devices with AT 8051 Microcontroller.
CO-5: Implement Communication Standards and Protocols.
CO-6: Understand Architecture of ARM (RISC) Microcontroller.
Mapping of Course Outcomes with Programme Outcomes to be done according
to the matrix given below:
Expected Mapping with Programme Outcomes
Course (1- Weak Correlation; 2- Medium correlation; 3- Strong Correlation)
Outcomes
PO-1 PO-2 PO-3 PO-4 PO-5 PO-6 PO-7
CO-1 3 3 3 3 1 1 3
CO-2 3 2 2 2 1 1 3
CO-3 3 2 2 2 1 1 3
CO-4 3 2 2 3 1 1 3
CO-5 3 3 3 3 1 1 3
CO-6 3 3 3 3 1 1 3
(ix)
x | Microcontrollers and Applications
GUIDELINES FOR TEACHERS
To implement Outcome Based Education (OBE) knowledge level and skill set of the
students should be enhanced. Teachers should take a major responsibility for the proper
implementation of OBE. Some of the responsibilities (not limited to) for the teachers
in OBE system may be as follows:
Within reasonable constraint, they should manoeuvre time to the best advantage of
all students.
They should assess the students only upon certain defined criterion without
considering any other potential ineligibility to discriminate them.
They should try to grow the learning abilities of the students to a certain level before
they leave the institute.
They should try to ensure that all the students are equipped with the quality
knowledge as well as competence after they finish their education.
They should always encourage the students to develop their ultimate performance
capabilities.
They should facilitate and encourage group work and team work to consolidate
newer approach.
They should follow Blooms taxonomy in every part of the assessment.
Bloom’s Taxonomy
Teacher should Student should be Possible Mode of
Level
Check able to Assessment
Create Students ability to create Design or Create Mini project
Technical
Students ability to use Operate or
Apply Presentation/
information Demonstrate
Demonstration
(x)
(xi)
xii | Microcontrollers and Applications
LIST OF ABBREVIATIONS
AC Auxiliary Carry kHz Kilohertz
ADC Analog to Digital Converter LCD Liquid Crystal Diode
ALE Address Latch Enable LED Light Emitting Diode
ALU Arithmetic Logic Unit LSB Least Significant Bit
AVR Advanced Virtual RISC MHz Megahertz
BIU Bus Interface Unit MSB Most Significant Bit
BP Base Pointer OE Output Enable
CAN Controller Area Network OTP One Time Programmable
CCP Capture Compare Pulse width modulation PC Program Counter
CISC Complex Instruction Set Computer PCB Printed Circuit Board
CLK Clock PIC Programmable Interface Controller
CPU Central Processing Unit PPI Programmable Peripheral Interface
CS Code Segment PSEN Program Strobe Enable
CY Carry PWM Pulse Width Modulation
DAC Digital to Analog Converter RAM Random Access Memory
DB Define Byte RD Read
DI Destination Index RISC Reduced Instruction Set Computer
DS Data Segment ROM Read Only Memory
EA External Access RS Register Select
EOC End of Conversion SC Start Conversion
ES Extra Segment SCI Serial Communication Interface
EU Execution Unit SI Source Index
FIQ Fast Interrupt Processing SID Serial Input Data
GPR General Purpose Register SoC System-on-Chip
GUI Graphical User Interface SOD Serial Output Data
IDE Integrated Development Environment SP Stack Pointer
IE Interrupt Enable SPI Serial Peripheral Interface
IIC, I2C Inter Integrated Circuit SS Stack Segment
IP Instruction Pointer, Interrupt Priority WR Write
IR Instruction Register Z Zero
kB Kilobytes
(xii)
LIST OF FIGURES
Unit 1 Fundamentals of Microprocessors and Microcontrollers
Fig 2.1: (a) 8051 pin diagram (b) Grouping of 8051 pins 37
Fig 2.2: Internal Block Diagram of the 8051 38
Fig 2.3: Internal RAM Locations 39
Fig 2.4: Clock Circuit – (a) Crystal (b) Direct 42
Fig 2.5: Reset Circuit 43
Fig 2.6: Hardware Structure of I/O Pin 45
Fig 2.7: Hardware Structure of I/O Pin 46
Fig 2.8: Hardware Structure Port 0 Pin 47
Fig 2.9: Demultiplexing of Address and Data Lines 48
Fig 2.10: External Program Memory with (a) EA = 0, (b) EA = 1 49
Fig 2.11: Signal Lines for Program Memory Interface 49
Fig 2.12: Example Program Memory Interface 50
(xiii)
xiv | Microcontrollers and Applications
Fig 2.13: Signal Lines for Program Memory Interface 50
Fig 2.14: Example Data Memory Interface 51
Fig 2.15: Combined Program and Data Memory 51
Fig 2.16: Machine Cycle of the Intel 8051 CPU 52
Fig 2.17: Timing Diagram for External Program Memory Access 52
Fig 2.18: Timing Diagram with External Program and Data Memory Access 53
Fig 2.19: Important Files in Assembly 58
(xiv)
Fig 4.6: Connecting LED to a port pin 130
Fig 4.7: Interfacing 8 switches and 8 LEDs 130
Fig 4.8: Interfacing a 4 4 Hex keyboard 131
Fig 4.9: Flowchart for keyboard scan routine 132
Fig 4.10: (a) 7-segment module (b) Digits 137
Fig 4.11: 7-segment display (a) Common anode (b) Common cathode 138
Fig 4.12: Ways to connect common anode displays 138
Fig 4.13: Multiplexing 7-Segment Displays 139
Fig 4.14: Four multiplexed 7-segment displays 139
Fig 4.15: An LCD module 143
Fig 4.16: LCD Read operation 144
Fig 4.17: LCD Write operation 144
Fig 4.18: Interfacing LCD module with the 8051 145
Fig 4.19: ADC0808/0809 schematic 149
Fig 4.20: Timing diagram for ADC0808/0809 150
Fig 4.21: Interfacing ADC0808/0809 with the 8051 151
Fig 4.22: Pin layout of DAC0808 154
Fig 4.23: Interfacing DAC0808 with 8051 154
Fig 4.24: Analog signal to 8051 158
Fig 4.25: LM35 pin layout 158
Fig 4.26: 8255 pin layout 159
Fig 4.27: Grouping of pins of 8255 159
Fig 4.28: Control word format of 8255 160
Fig 4.29: Interfacing 8255 with the 8051 161
(xv)
xvi | Microcontrollers and Applications
LIST OF TABLES
Unit 1 Fundamentals of Microprocessors and Microcontrollers
Table 1.1: Steps in instruction execution 9
Table 1.2: Control signals activated for different instructions 10
Table 1.3: Classification of 8085 instructions 15
Table 1.4: Comparison between 8-bit Microcontrollers 21
Table 1.5: Feature comparison between low-level and high-level languages 24
(xvi)
Table 4.3: Table for Sine wave generation 156
Table 4.4: 8255 port selection 159
Unit 5 Introduction to Advanced Processors and Concepts
Table 5.1: CISC vs. RISC 176
Table 5.2: Ports in PIC18F452 179
Table 5.3: Comparison of AVR Series Microcontrollers 182
Table 5.4: Programmer Model 183
Table 5.5: Comparison of 8051, PIC, AVR 185
Table 5.6: ARM Instruction Set Summary 189
Table 5.7: Comparison across LPC214x devices 193
Table 5.8: Registers for I/O Port Programming 195
(xvii)
xviii | Microcontrollers and Applications
CONTENTS
Foreword iv
Acknowledgement v
Preface vi
Outcome Based Education viii
Course Outcomes ix
Guidelines for Teachers x
Guidelines for Students xi
List of Abbreviations xii
List of Figures xiii
List of Tables xvi
(xviii)
(xix)
xx | Microcontrollers and Applications
3.2.2 Register Addressing Mode 69
3.2.3 Direct Addressing Mode 70
3.2.4 Register Indirect Addressing Mode 70
3.2.5 Bit Direct Addressing Mode 70
3.3 Instructions of the 8051 71
3.3.1 Data Transfer Instructions 71
3.3.2 Branching Instructions 76
3.3.3 Arithmetic and Logic Instructions 81
3.3.4 Other Miscellaneous Instructions 89
3.4 C Language Programming for the 8051 91
3.4.1 Data Types 92
3.5 Program Debugging 96
3.6 Programming Timers and Counters 97
3.6.1 Timer Programming 97
3.6.2 Counter Programming 103
3.7 Programming Interrupts 104
3.7.1 Interrupts in 8051 105
3.7.2 Interrupt Enable Register 106
3.7.3 Timer Interrupts 106
3.7.4 External Interrupts 108
3.7.5 Interrupt Priorities 110
3.8 Serial Communication Programming 110
3.8.1 Setting Baud Rate 111
3.8.2 Registers for Serial Communication 112
3.8.3 Serial Transmission 113
3.8.4 Serial Reception 115
3.8.5 Serial Communication Interrupt 116
Unit summary 118
Exercises 118
Know more 123
References and suggested readings 123
(xx)
4.3 Hex Keyboard Interfacing 131
4.4 Seven-Segment Display Interfacing 137
4.4.1 Multiplexed Display 138
4.5 Liquid Crystal Display (LCD) Interfacing 142
4.6 Analog to Digital Converter (ADC) Interfacing 148
4.7 Digital to Analog Converter (DAC) Interfacing 153
4.8 Interfacing Temperature Sensor 158
4.9 8255 Interfacing 159
Unit summary 163
Exercises 163
Know more 167
References and suggested readings 168
(xxi)
1
Fundamentals of Microprocessors
d
and Microcontrollers
UNIT SPECIFICS
Through this unit we have discussed the following aspects:
A program logic getting translated into actions of modules in a computer;
Internal configuration of a computer;
Concepts of address-, data- and control buses;
Internal architecture of a generic CPU – registers, ALU, instruction decoding and
execution process;
An overview of the 8085 microprocessor – pin diagram, internal architecture and
programming;
An overview of the 8086/88 microprocessor – architecture, summary of instructions;
Microcomputer systems and distinction between microprocessors and microcontrollers;
An overview of 8-bit microcontrollers with a comparison between the popular ones;
Integrated Development Environment (IDE) for microcontroller based system
development.
The overall discussion in the unit is to give an overview of CPU architectures, starting with
the basic knowledge of components in a computer system. It has been assumed that the reader has
a good understanding of Digital Electronics with topics like logic gates, memory elements,
registers, counters etc. Also a basic understanding of programming will be helpful. A good number
of examples have been included to explain the concepts, wherever needed.
A large number of multiple choice questions have been provided with their answers. Apart from
that, subjective questions of short and long answer type have been included. A few numerical
problems with answers have been provided. A list of references and suggested readings have been
given, so that, one can go through them for more details. The section “Know More” has been
carefully designed so that the supplementary information provided in this part becomes beneficial
for the users of the book. This section mainly highlights the initial activity, history of the
development of microcontrollers, recent developments and application areas.
RATIONALE
This unit on fundamentals of microprocessors and microcontrollers helps the reader to understand
the basic architecture of a computer system, its components, interfacing between them and the
2 | Microcontrollers and Applications
working principle. Starting with the block diagram level representation of a computing system with
CPU, memory and peripherals, it goes into the details of functioning of the CPU to co-ordinate
between all the components. The unit explains how a typical CPU works by getting instructions
and data from memory and I/O devices interfaced with it. It shows the internal of a CPU at register
level with ALU and bus interfaces. The unit takes the reader through an overview of the 8085 and
8086/88 microprocessors. This acquaints the reader with the basic philosophy behind developing
electronic systems around microprocessors and microcontrollers. This, in turn, leads to discussion
on microcomputers and finally takes the reader to microcontrollers, which are single-chip
microcomputers. The unit discusses on microcontroller architecture, comparison between
available microcontrollers, how to select a microcontroller for a specific application, etc. For
microcontroller based system design, the unit introduces the reader to the integrated development
environment (IDE). Thus, the unit gives bird’s-eye-view of microcontroller based system design.
PRE-REQUISITES
Electronics: Digital Electronics
Programming: Basic Computer Programming
UNIT OUTCOMES
List of outcomes of this unit is as follows:
U1-O1: List the modules inside a processor
U1-O2: Draw the block-level interfacing of memory to processors
U1-O3: State the internal architecture of 8085 and 8086
U1-O4: Compare between microprocessors and microcontrollers
UI-O5: Distinguish between high- and low-level languages
UI-O6: State the role of tools present in an Integrated Development Environment
EXPECTED MAPPING WITH COURSE OUTCOMES
Unit-1 Outcomes (1- Weak Correlation; 2- Medium correlation; 3- Strong Correlation)
CO-1 CO-2 CO-3 CO-4 CO-5 CO-6
U1-O1 3 2 1 - - -
U1-O2 2 - - - - -
U1-O3 3 1 - - - -
U1-O4 3 1 - - - -
U1-O5 1 - 1 - - -
UI-O6 2 - - - - -
Microcontrollers and Applications | 3
MA
1.1 Introduction
A computing system contains one or more processors as its primary component. The job
of the processor is to carry out the computation intended by the user of the system. The intended
computation is the program to be executed by the processor. The program is designed by the user
and made available to the processor through the memory modules present in the system. Apart from
the program, some input values, needed for computation, are to be provided to the processor and
the outputs produced from the computation are to be made available to the user. This entire
relationship between the modules in a computing system could be understood by the following
example.
4 | Microcontrollers and Applications
Microprocessors and microcontrollers are semiconductor chips that can function as a
processor in a computing system. In the process of familiarizing the readers with an overview of
their operations and the commonly available processing platforms, the next section will highlight
the basic organization of modules in a computing system.
CPU
shown in Fig 1.3, least significant 14 00
Decoder
0 01 CS
address lines (A0 to A13) are connected 10
directly to all the four memory chips. 1 11 Memory 3
The next two higher order address lines Address
A14 and A15 are passed through a 2-to-4 CS
decoder to generate 4 chip select signals
for the memory chips. Thus, for the Memory 4
addresses generated by the CPU in the Address
range of 0000H-3FFFH Memory 1 is CS
accessed. For addresses 4000H-7FFFH,
8000H-BFFFH, and C000H-FFFFH, Fig 1.3: Memory interfacing with CPU
Memory 2, Memory 3 and Memory 4
are accessed, respectively.
In Example 1.2, if some I/O devices need to be connected as well, some of the decoder
output lines may be connected to enable those devices. This, of course, will reduce the amount of
memory that could be attached in the system.
1.2.2 Data Bus
This is used to transport data between the CPU and memory and/or I/O devices. More the
width of the data bus, more data can be transferred at a single go. However, having more number
of lines in a data bus (or, any other bus) also means more required area on the board (housing the
full system) to route them
8-bit Data Bus
between the modules,
increasing the cost of the D0-3
system. Typical size of data
bus varies between 8 to 64 D4-7
CPU
Address & CS
Memory 1 Memory 2
bits. Processing power of the
CPU is often guided by the
width of the data bus. If the
data bus width is 8-bits,
modules internal to the CPU Fig 1.4: Connecting memory modules in parallel
are generally designed to do
operations (such as, addition, subtraction, multiplication etc.) on 8-bit operands only. It may be
noted that data bus of individual memory chips may be of lesser width than the CPU data bus. A
6 | Microcontrollers and Applications
number of memory chips may be operated in parallel to match the data bus lines of the CPU. For
example, in Fig 1.4, individual memory chips are of 4-bit data bus. Two such chips are connected
in parallel to cater to the 8-bit data bus requirement of the CPU.
1.2.3 Control Bus
Apart from the address and data bus lines, CPU also need several control signals connected
to the memory chips and I/O devices. Further, it needs to check the status of devices connected to
the system. Sometimes, devices need to contact the CPU proactively on occurrence of some event,
for example, the user pressing a key on the keyboard. These control and status lines, from and to
the CPU, collectively form the control bus. There cannot be any typical sizes for the control bus.
However, two very important control signals for any CPU is the Read (RD) and the Write (WR).
The signal RD is activated when the CPU needs to read the content of a memory location or input
device. Similarly, WR is activated when the CPU wants to modify the content of a memory location
or output some data to an output device.
A computer system
normally contains two types of RD
memory modules – Random WR
Access Memory (RAM) and
CPU
RAM ROM
Read Only Memory (ROM).
Content of ROM is permanent in
nature and is used to hold
program/data that is not going to
change frequently. Examples of Fig 1.5: RD, WR signals to memory
such content include booting
program of the system, some specific bit pattern that may be used to display some pattern in output
device, etc. ROM content could be reprogrammed only by using some additional devices,
commonly known as Programmer. On the other hand, content of RAM is volatile. It is used to keep
user programs and data. The CPU can only read the contents of ROM, however, may do both read
and write operations for RAM. The control lines RD and WR are to be connected accordingly, as
shown in Fig 1.5.
Example 1.3: Fig 1.6 shows a computer system with a processor having 16-bit address bus and
8-bit data bus. The system has a total of 64kB of memory interfaced with the processor. Out of
these 64kB, 16kB is ROM and 48kB RAM. Individual memory chips are of capacity 16k 4-
bits. Thus, each 8-bit memory word has been configured by connecting two such memory chips
in parallel. Address lines A0 to A13 have been connected to the address lines of the memory chips.
A 2-to-4 decoder has been used to generate the chip select signals from the highest order address
bits, A14 and A15. The RAM chips have got both the RD and WR control signals connected to
them, as their locations may both be read and written by the CPU. On the other hand, only the
RD line has been connected to the ROM chips, as the ROM locations could only be read by the
CPU. It may be noted that the data lines of ROM are unidirectional, coming out of the memory
chip. For RAM chips, the data lines are bidirectional, as data may both be read or written onto
Microcontrollers and Applications | 7
them. Processor generates address in the range of 0 to 64k that get mapped onto pair of memory
chips to give 8-bit data.
D0-D7
D0-D3
D4-D7
ROM ROM
A0-A13 CS CS
A14
A15
CPU
RAM RAM
00
Decoder
0 01 CS CS
10
1 11
RAM RAM
CS CS
RD
WR
RAM RAM
CS CS
Fig 1.6: Interfacing 16KB ROM and 48KB RAM with CPU
8 | Microcontrollers and Applications
3. Some special function registers are often put into the CPU, as noted next.
a. Program Counter (PC): It points to the address of the next instruction to be
executed. After fetching the next instruction from memory to CPU, PC is
incremented by size of the instruction (in number of bytes), to make it point to the
next instruction. When the CPU is powered on or is reset, PC is loaded with a fixed
value, predecided by the designer of the CPU. Content of PC is put into the address
bus to fetch the next instruction to be executed by the processor. In some of the
processors, PC is called Instruction Pointer (IP).
b. Flags: This register holds the status information with respect to the last operation
carried out by the ALU. It contains bits named as ZERO, CARRY etc. The ZERO
flag bit is set if the last operation performed by the ALU has zero as the computed
result. Similarly, the CARRY bit is set if the last operation resulted into a value
beyond the range that can be stored in the registers. The flags help in making
decisions regarding the instruction sequence to follow.
Instruction
External Address Bus
external components
Register
Registers
Control signals
to internal and
Instruction Program
Decoder & Counter
Control
Internal Bus
Flags
c. Instruction Register (IR): This register holds the instruction as it is fetched from
the memory. Each instruction is stored in memory in a coded form. Once it reaches
the IR, the Instruction Decoder is used to decode it. Based on the instruction, the
controller generates the control signals over successive time frames to accomplish
the intended task of the instruction.
Microcontrollers and Applications | 9
1.2.5 Operation of CPU
CPU executes the instructions one-by-one starting with the instruction at memory
location pointed to by the PC. It typically follows the sequence of operations “Fetch
Decode Execute” for each instruction. The operations continue till the processor executes
a HALT instruction, or as long as the processor is powered. The sequence of operations has
been enumerated in Table 1.1.
Table 1.1: Steps in instruction execution
Fetch 1. Address of next instruction pointed to by PC is put on the address bus.
2. RD signal activated.
3. Next instruction from memory reaches Instruction Register.
4. PC incremented to point to the next instruction.
Decode 5. Decoder decodes the instruction and decides the sequence in which
various control signals are to be activated to accomplish the instruction.
Execute 6. Operands for the instruction brought from memory and/or registers.
7. Operation carried out in ALU, Flags updated.
8. Result stored back in register/memory.
Example 1.4: Next we shall look into instruction execution by a hypothetical CPU shown in Fig
1.8.
R1
Instruction Program
Decoder & R2 Counter
Control
Internal Bus
Flags
Fig 1.8: A hypothetical CPU
10 | Microcontrollers and Applications
The CPU has three registers R0, R1 and R2 in it. Apart from that, there is a special register W
that can hold an address. The address field present in an instruction may be copied from IR to it
and made available to the address bus to access memory locations. To understand the control
signals generated over the time-steps, we assume that each register has got two signals associated
with it – load and enable. When the load signal is activated, the content from the bus it is
connected to, is copied into it. When the enable signal is activated, content of the corresponding
register is put onto the bus. For example, to copy the content of register R0 to register R1, the
signals to be activated are enable_R0 and load_R1. Similarly, ALU has control signals to
perform different arithmetic and logic operations. We shall consider the following three
instructions.
LOAD R0, 1000 ; Load the content of Memory[1000] into R0
ADD R0, R1, R2 ; R2 R0 + R1
STORE R2, 3000 ; Store the content of R2 at Memory[3000]
Control signals activated at different time steps to execute these instructions have been shown
in Table 1.2.
Table 1.2: Control signals activated for different instructions
Instruction Time Control Signals
Step
t1 Enable_PC, RD
t2 Load_IR
LOAD R0, 1000 t3 Decode, Increment_PC
t4 Load_W, Enable_IR
t5 Enable_W, RD, Load_R0
t1 Enable_PC, RD
ADD R0, R1, R2 t2 Load_IR
t3 Decode, Increment_PC
t4 Enable_R0, Enable_R1, Add_ALU, Load_R2
t1 Enable_PC, RD
t2 Load_IR
STORE R2, 3000 t3 Decode, Increment_PC
t4 Load_W, Enable_IR
t5 Enable_W, WR, Enable_R2
Microcontrollers and Applications | 11
It may be noted that the time steps t1 and t2 correspond to Fetch stage, t3 corresponds to
Decode phase and the rest of the time steps constitute the Execute phase of operation. Fetch and
Decode stages (that is, time steps t1 to t3) are same for all instructions, Execute phase depends
upon the instruction being carried out.
The first microprocessor was Intel’s 4004, introduced in 1971. It has been a 4-bit processor with
10-bit address bus and 4-bit data bus, operating at 108 kHz. It was quickly succeeded by 8008 (8-
bit data bus), 8080 and 8085. The microprocessor 8085, introduced in 1976, is a processor with 8-
bit data bus, 16-bit address bus, operating at 3 MHz clock.
12 | Microcontrollers and Applications
VCC VSS
X1 40 VCC X1
1 1 40 20
X2 2 39 HOLD X2 28 A
2 15 High order
RESET OUT 3 38 HLDA SID A address bus
Ports
Serial I/O
SOD 4 37 CLK (OUT) 5 21 8
SOD
SID 5 36 RESET IN 4
TRAP 6 35 READY 19 AD7
8085A
8085A
Status Signals
Control and
29 S 0
AD1 13 28 A15
READY 33 1
AD2 14 27 A14 35 IO/M
HOLD 39 34 RD
AD3 15 26 A13
RESET IN 32
AD4 16 25 A12 36 WR
AD5 A11 31
17 24
INTA
AD6 18 23 A10 11 RESET OUT
Ack.
AD7 19 22 A9 HLDA 3
38
VSS 20 21 A8 37 CLK (OUT)
Fig 1.9(a): 8085A pin diagram Fig 1.9(b): Grouping of 8085A pins
Address and Data Bus: The 8085 CPU has 16-bit address bus A15-A0 and 8-bit data bus D7-D0.
To reduce the overall pin count,
the lower order address bus A7-A0
has been multiplexed with data AD7-0
bus lines D7-D0. For memory D7-0 Memory
Latch
8085
Microcontrollers and Applications | 13
are available in AD7-AD0. ALE signal could be used to demultiplex the address and data lines by
using an external latch, as shown in Fig 1.10.
X1, X2, CLK (OUT): A crystal is connected between X1 and X2 to generate clock signal for 8085.
Internally, the crystal frequency is divided by 2. Thus, to make the processor work at 3 MHz, the
crystal frequency should be 6 MHz. The processor clock is also available at CLK (OUT) pin to
connect to other peripherals that may need synchronization with the processor clock.
Externally Initiated Signals: There are several pins in this category. Out of them, INTR, TRAP,
RST 7.5, RST 6.5 and RST 5.5 are known as interrupt lines. An activation on these lines will cause
the 8085 CPU to suspend its current work and diverge to some special routine, which may be for
serving some special device etc. For example, if a keyboard has been interfaced to 8085 via some
interrupt line, a key press may cause an interrupt to the processor. The processor now diverges to
a special routine to read the key value. Once the service is over, the processor will resume its
suspended work. The line INTA is to acknowledge an INTR input. The signals HOLD and HLDA
are used for interfacing other bus masters to the system. A bus master may be responsible for bulk
data transfer from memory. On getting signal in the HOLD line, the 8085 relinquishes its control
over address, data and control lines. It is acknowledged in the HLDA pin. The bus control is
regained via interrupt when the secondary bus master no more needs the bus. On getting a low in
the RESET IN line, the processor resets with its program counter becoming zero and activating the
RESET OUT pin to inform the interfaced devices.
Serial I/O Ports: The lines SID (Serial Input Data) and SOD (Serial Output Data) can be used for
serial I/O operations, one bit at a time.
Status Signals: Signals like RD, WR are used for memory interfaces. The lines S0, S1 and IO/M
indicates the operation that the 8085 is currently doing, such as, memory read, memory write, I/O
read, I/O write, fetch, interrupt etc.
General Purpose Registers (GPRs): There are six general purpose registers to store 8-bit data
inside the CPU. These are named as B, C, D, E, H and L. The registers can be paired into three 16-
14 | Microcontrollers and Applications
bit registers – BC, DE and HL. The registers can hold operands for different operations. The 16-bit
pairs can also be used to provide address to operand stored in memory.
RST 5.5
RST 6.5
RST 7.5
TRAP
INTR
INTA
SOD
SID
Interrupt Control Serial Control
8-bit Internal Data Bus
X1
Timing and Control Address Address/Data
X2
Buffer (8) Buffer (8)
HLDA
S0
S1
HOLD
RESET OUT
WR
Ready
CLK (OUT)
RESET IN
IO/M
RD
ALE
A15-A8 AD7-AD0
Address Bus Address/Data Bus
Special Purpose Registers: There are several special purpose registers, as noted next.
1. Accumulator (A register): This is an 8-bit register, acting as one of the source operands
and the destination for all ALU operations. ALU can perform 8-bit arithmetic and logic
operations. While carrying out the ALU operation, a temporary register (marked as Temp
in Fig 1.11) holds the second operand for two-operand operations.
Microcontrollers and Applications | 15
2. Flags: This is an 8-bit register, though only 5 bits of it are used to contain status
information corresponding to the last ALU operation. The flag bits are Zero (Z), Carry
(CY), Sign (S), Parity (P) and Auxiliary Carry (AC).
3. Program Counter (PC): A 16-bit register that contains the address of the memory location
corresponding to the next instruction to be executed.
4. Stack Pointer (SP): A 16-bit register that is used to point to a RAM location corresponding
to “stack”. The “stack” is a part of RAM that is used in the context of subprogram call or
an interrupt. For both these situations, processor saves the return address in stack, before
jumping to the subprogram. So that, when the subprogram/service routine is over, the PC
could be reloaded with the value saved in stack, and thus resume the suspended operation.
Availability of stack aids in realizing nested subprograms as well.
16 | Microcontrollers and Applications
Machine Special instructions affecting the HLT ; Halt the CPU operation
Control operation of the CPU RST ; Software interrupt
NOP ; Do nothing
Example 1.5: The following is a 8085 code fragment that can find the maximum of a set of
numbers stored from the memory location 3000H. The number of numbers in the set is stored at
location 3000H, the numbers start from 3001H. The largest number will be stored at location
5000H.
LXI H, 3000H ; Set HL-pair to the address of the array
MOV C, M ; Get number of numbers in C
INX H ; Make HL-pair to point to the first number
MOV A, M ; Get first number in A, assume it to be the largest
DCR C ; Decrement count
L1: INX H ; Make HL-pair point to the next number
CMP M ; Compare current largest in A with next number
JNC L2 ; If CY=0, it means A is still the largest, no action
MOV A, M ; Update new largest in A
L2: DCR C ; Decrement count
JNZ L1 ; Goto L1, if some numbers left
STA 5000H ; Store the largest at memory location 5000H
Microcontrollers and Applications | 17
necessity was felt to have a processors,
16-bit 8086/88 processor enjoys
VCC
advantages like increased memory CLK
addressing (1 mega, compared to 64 BHE/S7
kilo), increased speed (upto 10 MHz), GND A19/S6 Multiplexed Address
powerful instruction set, possibility of GND and Status Signals
working in a multiprocessor A16/S3
INTR
environment. The 8086 chip can NMI
operate in two modes – the minimum
HOLD AD15
mode and the maximum mode. The READY
minimum mode is very close in RESET
operation as 8085. Details of signals in Multiplexed Address
the minimum mode has been shown in and Data Buses
Fig 1.12. The MN/MX pin set to ‘1’
forces the minimum mode, while INTA AD0
setting the input to ‘0’ enables the HOLDA
ALE
maximum mode operation. For the M/IO
maximum mode operation, a bus RD Control and
controller (such as, 8288) is employed WR Status Signals
to generate the necessary control TEST DEN
signals. Pins of 8086 change their MN/MX DT/R
functionality slightly to give inputs to
the bus controller. For example, the
pins S0, S1 and S2 are introduced Fig 1.12: The 8086 in Minimum Mode
instead of DEN, DT/R and M/IO
respectively. Another control LOCK is used to prevent other processors from getting control of the
bus.
Bus Interface Unit (BIU): The BIU interfaces the 8086 with external memory and I/O devices.
The 8086 has 20-bit address bus and a 16-bit data bus. Thus, it can access a total of 1 mega memory
locations of size 16-bit each. A 20-bit address produced by the 8086 processor consists of two parts
– segment and offset, each of 16-bit width. An address is computed by left shifting the 16-bit
segment value by 4 bits, creating a 20-bit value and then adding the 16-bit offset to it. That is,
𝑎𝑑𝑑𝑟𝑒𝑠𝑠 16 𝑠𝑒𝑔𝑚𝑒𝑛𝑡 𝑣𝑎𝑙𝑢𝑒 𝑜𝑓𝑓𝑠𝑒𝑡
18 | Microcontrollers and Applications
Address Bus (20 bit)
AH AL AX
BH BL BX ALU
CH CL CX
DH DL DX
SP
General CS
BP
Registers DS
SI
SS
DI
ES
ALU Data Bus IP
(16 bit) Internal Bus 8086 Bus
Comm. Regs. Control
System
Temporary Registers
Internal Instruction Queue
Control 1 2 3 4 5 6
ALU System
To specify the segment part, the 8086/88 CPU uses four segment registers, each of 16-bit
width – Code Segment register (CS), Data Segment register (DS), Stack Segment register (SS) and
Extra Segment register (ES). The processor allows four active segments for any program, at a time.
The code segment of a program is supposed to contain the program code. The data and stack
segments are to contain the data part and the stack part of the program, respectively. An additional
segment is allowed that is typically used as an extra data segment. When a program is loaded into
the memory, the segment registers CS, DS, ES and SS are initialized suitably to point to the base
of those segments. It may be noted that each segment can be of size upto 64 k, thus the amount of
active part of a program, at any point of time is 4 64 k 256 k. Of course, the segment registers
can be reloaded with some other values to refer to program fragments (code, data etc.) beyond 256
k size limit.
To perform program fetch, another 16-bit register, Instruction Pointer (IP) is used. IP is
equivalent to PC on 8085. To get the next instruction from memory, the register pair CS:IP is used
to generate the 20-bit address, 16 CS IP using the 20-bit ALU present in the BIU. Successive
bytes are fetched into an Instruction Queue (6 bytes in 8086, 4 in 8088). Presence of this instruction
queue enables fetch-execute overlap in 8086/88. When the current instruction is being executed by
the EU, BIU may bring in successive instructions, upto 6 bytes, into the queue.
Microcontrollers and Applications | 19
Execution Unit (EU): The EU is responsible for decoding and executing individual instructions.
It has a 16-bit ALU for performing arithmetic and logic operations. Apart from a few temporary
registers (not available to the user), there are three sets of registers, as noted next.
General Purpose Registers: There are four, 16-bit general purpose registers – AX, BX, CX
and DX. Each of them can also be used to behave as two 8-bit registers. AX is composed
of 8-bit registers AH and AL, BX containing BH and BL, CX containing CH and CL and
DX being composed of DH and DL. The register AX also behaves as accumulator, as in
8085.
Pointer Registers: Stack Pointer (SP) and Base Pointer (BP) are the two 16-bit registers,
used to access data in the stack segment. SP is incremented/decremented automatically
during stack operations. Memory access via SP and BP uses SS as the segment register,
the address being computed as, 16 SS SP or BP .
Index Registers: The 16-bit Source Index (SI) and Destination Index (DI) registers are used
primarily for indexed memory access. By default, the access via SI uses DS as the segment
register (address = 16 DS + SI) and via DI uses ES as the segment register (address = 16
ES + DI). They are also used in single-byte instruction MOVSB to transfer the content
from a source block (pointed to by DS:SI) to a destination block (pointed to by ES:DI) with
CX register holding the number of bytes to be transferred.
The instruction set of 8086/88 processor can be grouped into the following categories.
Data Transfer Instructions – MOV, XCHG, PUSH, POP etc.
Arithmetic Instructions – ADD, SUB, MUL, DIV etc.
Logical Instructions – AND, OR etc.
String Manipulation Instructions – MOVS, LODS, STOS, REP etc.
Process Control Instructions – STC, STD, NOP, HALT, WAIT, LOCK etc.
Control Transfer Instructions – JMP, JE, JC, CALL, RET etc.
A detailed discussion on the instructions is beyond the scope of this book and can be found in the
references noted at the end of the Unit.
20 | Microcontrollers and Applications
The generic components
in a microcomputer Data Bus
Microprocessor
system has been shown
in Fig 1.14. The
Counter
Comm.
DAC &
Timer/
Serial
microcomputer systems ROM RAM GPIO
ADC
available today can be
broadly classified into
the following categories.
Address Bus
Fig 1.14: Generic Microcomputer System
1. Personal
Computer (PC)/Desktop: These are mostly single-user systems with applications, such as,
office automation, finance, internet access, limited computation etc. They often contain
large number of system and application software.
2. Workstation: These are high performance desktop systems that specialize in executing
certain engineering/scientific applications efficiently. Typical examples of such
applications are Computer-Aided Design (CAD), Computer-Aided Engineering (CAE) and
Computer-Aided Manufacturing (CAM). The workstations generally possess high-end
microprocessors, large memory (both primary and secondary) and often a high-resolution
screen, specialized I/O devices etc.
3. Single-Board Computers: These are computers housed on a single Printed Circuit Board
(PCB) and is often used for educational and training purposes. Apart from the
microprocessor, the board contains limited amount of ROM, RAM, chips to realize
timer/counter operations and interfaces for very simple I/O devices (like matrix keyboard,
seven-segment LED, LCD modules, switches for digital inputs, etc.). The ROM contains
a simple monitor program, responsible for monitoring the system resources and aiding in
executing user programs.
4. Single-Chip Microcomputers (Microcontrollers): In this category, the entire
microcomputer system is fabricated onto a single silicon chip. Such systems are typically
used in different controller applications.
Microcontrollers and Applications | 21
used in embedded applications have specialized interfaces like Serial Peripheral Interface (SPI),
Inter Integrated Circuits (IIC/I2C) etc.
Intel introduced the 8-bit microcontroller 8051 in 1981 with 128-byte RAM, 4kB ROM,
two timers, one serial port and four 8-bit parallel ports. After its initial success, Intel allowed other
manufacturers to produce different variants of 8051. Accordingly, variants like 8031, 8052 etc.
came. Some other 8-bit microcontrollers that came into existence are Zylog’s Z8, Microchip 16C74
and 16F874 from PIC. Table 1.4 shows a comparison between the most commonly available 8-bit
microcontrollers.
Interrupt pins
External events
Interrupt RAM ROM Timers/
Control Counters
Internal Bus
CPU
Output
Analog
Analog
Serial
Output
Serial
Input
Input
GPIO lines
Fig 1.15: Block Diagram of a Typical Microcontroller
8031 128 0 12 2
8051 128 4 12 2
8052 256 8 12 3
8751 256 8 EPROM 12 3
22 | Microcontrollers and Applications
87C58 256 32 EPROM 12-24 3
87C51GB 256 8 EPROM 12-16 3
89C61x2 1024 64 Flash 20-33 3
AT89S8252 256 8 Flash, 2 EPROM 24 3
PIC16C74 192 4 20 3
AVRATTINY10 32 1 12 1
Z8 1024 8 20 2
Microcontrollers and Applications | 23
8. Availability of good development platform. Though Table 1.4 has listed a number of
microcontrollers, each one has its own instruction set. Mastering all of them is very
difficult, if not impossible, for any system designer. To solve this problem, the vendors of
these chips normally come up with a set of software to help in programming the
microcontroller. It is often the case that the development platform allows the program to
be written in some high-level language, such as C. Microcontroller-specific compiler and
assembler translate the program to machine language. User-friendliness of such
development platform often bias the selection of microcontroller by the designer.
9. Availability of microcontroller chip in the market is another guiding factor. For easy
availability, the original designers of microcontrollers often license other companies to
manufacture their chips. For example, the widely popular 8051 chip is produced by
companies like Intel, Atmel, Infineon, Dallas, Philips (NXP) etc. Many of the
microcontrollers are now available as Intellectual Property Core (IP Core) to be integrated
in single chip System-on-Chip (SoC) designs. With the advancement in VLSI design, this
has become a possibility.
1.7 Lower and Higher Level Languages
The CPU of a microcontroller understands the instructions coded in binary form only.
Thus, any program to be executed by the processor, must be in this format. A program in binary
form is called a machine language program. Though easily understood by the processor, it is too
cumbersome for the system designer to write a program in machine language. At the same time,
the system designer may wish to work close to the actual CPU hardware (in terms of CPU registers,
ALU operations etc.) to have a much optimized version of his/her program. To enable it, processor
designers have created an
intermediary language for the Processor
valid instruction set of a Instruction Set
Assembly Language
Machine Language
assembly language of the
(Binary file)
Program
(Text file)
Program
24 | Microcontrollers and Applications
Thus, machine language is the lowest level at which a program may be written for a
processor. Assembly language
constitutes the next higher level. Processor
However, for a program of Instruction Set
Assembly Language
Machine Language
medium to high complexity,
(Binary file)
writing it directly in assembly
Program
(Text file)
Program
language is also difficult. In the Compiler
absence of programming
constructs like loop, if-then-else, Assembler
switch-case etc., it is too tedious
to express the program logic
elegantly in assembly language. Assembly Language
Also, the maintainability, Program
debugging and upgradation of
assembly language program Fig 1.17: High-Level Language Compilation
become important issues. Even
with a moderate degree of documentation of program code, it is very difficult for a third person to
understand an assembly language program. In contrast, programs written in languages like C/C++
allow all the programming facilities. Such languages are known as higher-level languages. A
program written in a high-level language is converted to machine level by means of tools known
as compilers. Compilers use the assembler of a processor to target the final code to a specific
processor. Program updating, migrating to other processors also become very easy. The compiler
may be asked to generate the assembly language program also, as a by-product. This has been
shown in Fig 1.17. It should be understood that due to automated translation of programs written
in higher level languages, the machine code generated by a compiler may not be highly optimized,
compared to the assembly language program written by an experienced system programmer. A
summary of feature comparison between low-level and high-level languages has been shown in
Table 1.5.
Microcontrollers and Applications | 25
For an IDE targeted to microcontroller based system design, the tools included in the IDE
are as follows.
1. Editor: This is possibly the first tool in the chain leading to system development. The
program code, in some high-level language, is written using the editor. The code is also
often called the source code.
2. Compiler: Once the source code is ready, the compiler is used to translate it into machine
code, also called object code. It should be understood that the IDE may be running on a PC
with Pentium processor, whereas, the compiler in IDE is producing code for some other
microcontroller, say 8051. Here, 8051 is the target processor. Such a compiler running on
a system and producing code for some other target processor is called a Cross Compiler.
3. Assembler: The source code may also be written in the assembly language of the processor.
An assembler will be used to translate the same to machine language. The assembler is also
included as a step in the
compilation process. Source File 1 Source File 2 Source File k
4. Linker: A linker may
combine a number of
object code files into a
single executable. This Compiler Compiler Compiler
facilitates a number of
designers developing
parts of the program Object File 1 Object File 2 Object File k
and combine into one
module later. Apart
from the modules Library Executable
Linker
developed by the module
designers, an IDE may
contain predesigned Fig 1.18: Linking multiple source and library modules
libraries to be included
26 | Microcontrollers and Applications
in the executable. For example, there may be library modules to glow an LED or reading
some sensor values, available as library routines readily integratable with the system
developed. Fig 1.18 shows the details.
5. Debugger: A debugger is a software running inside the IDE that can be used to diagnose
logical errors in the code. The debugging can be done by the help of a simulator or an
emulator.
a. Simulator: A simulator for the microcontroller tries to model the entire behaviour
of the microcontroller in software. However, it should be understood that a
simulator cannot match the speed of a real microcontroller. Simulating the external
events (such as, inputs from sensors arriving at desired time) is also very difficult.
Thus, a simulator may not be able to truly mimic the behaviour of the overall
system. Simulator is best suited to test algorithms that run completely within the
microcontroller.
b. Emulator: This is a piece of hardware that behaves exactly as the microcontroller
chip. The functionality of the microcontroller is emulated in real-time. In real
microcontroller, the program code is placed in ROM/EPROM which makes it
difficult to modify. On the other hand, an emulator stores the program in RAM
which behaves as the program memory. The RAM code can be modified quickly
to aid in the debugging process. Once the designer is satisfied with the performance
of the system in the emulator, the program may be downloaded into ROM/EPROM
of the microcontroller. Some microcontrollers (such as, 8051) allows external
program and data memory to be interfaced with them. For such chips, the emulator
may utilize the microcontroller itself for the purpose of emulation, with program
stored in external RAM instead of on-chip ROM.
Some of the well-known IDEs for microcontrollers include MPLAB for PIC
microcontrollers, Arduino for Arduino microcontrollers and Keil for range of microcontrollers like
8051, ARM7, C16x/ST10 etc.
Microcontrollers and Applications | 27
Example 1.16: Fig 1.19 shows the
structure and essential components of μVision Project Manager
Keil μVision IDE. It has full featured
source code editor, device database for
configuring the tools, integrated C Compiler Macro Assembler
compiler, assembler and linker, source-
and assembler-level debugger with
peripheral simulator, debugging on Real-Time Operating
target hardware and flash programming System Kernel
to download final code into the flash
ROM of the microcontroller.
Linker/Locator
μVision Debugger
UNIT SUMMARY
Microprocessors and microcontrollers are heart of any computing system – it may be a
microcomputer or any other electronic system targeted to a dedicated application. Microprocessors
constitute the CPU of a microcomputer. It contains a dedicated set of registers, one or more ALU,
decoding logic and controller for operation. Memory chips and peripherals are interfaced with the
CPU via address-, data- and control buses. Program instructions are fetched to the CPU, decoded
and executed over time steps, using control signals generated by the controller. The 8085 is an
eight-bit microprocessor with relatively simple internal architecture and instruction set. This is one
of the very widely used microprocessors, primarily before the introduction of 16-bit microprocessor
8086/88 and its advanced successors. When an entire microcomputer is put into a single chip, it is
called a microcontroller. With memory and other commonly used peripherals put into a single chip,
it has found wide applications in electronic system design. One of the most popular and well known
8-bit microcontroller is 8051. With several microcontrollers available in the market, choice of the
one to be used for an application is often guided by its internal resources, speed, cost etc.
Availability of good design environment translating the required functionality specified in high-
level language to final machine code of the microcontroller, aiding in debugging and correction,
also guides the selection process.
28 | Microcontrollers and Applications
EXERCISES
Microcontrollers and Applications | 29
(A) Registers (B) Timers
(C) DAC, ADC (D) None of the other options
MQ18. In microcontrollers, access to registers is
(A) Faster than on-chip RAM (B) Slower than on-chip RAM
(C) Same speed as on-chip RAM (D) None of the other options
MQ19. In microcontrollers memory access is generally faster than microprocessors because
(A) Memory is on-chip (B) Length of buses small
(C) Data access is less (D) None of the other options
MQ20. A low-level language is friendly to
(A) Programmer (B) Processor
(C) Both Programmer and Processor (D) None of the other options
MQ21. Porting of programs across microcontrollers will be easy if the program is written in
(A) Machine language (B) Assembly language
(C) High-level language (D) None of the other options
MQ22. Simulator and emulator are
(A) Both software (B) Software and hardware respectively
(C) Hardware and Software respectively (D) Both hardware
MQ23. The first tool in IDE tool flow is
(A) Editor (B) Compiler (C) Assembler (D) Debugger
MQ24. Executable code is produced by
(A) Editor (B) Compiler (C) Linker (D) Debugger
MQ25. The tool that can give more confidence on the correctness of the design is
(A) Simulator (B) Emulator (C) Compiler (D) Linker
SQ1. Enumerate the CPU signal lines to be connected to memory for interfacing.
SQ2. With respect to Example 1.4, list down the control signals to be activated at different time
steps to execute the instruction “SUB R0, R1, R2” that computes R2 R0 – R1.
SQ3. How is the ALE signal used in demultiplexing of AD7-AD0 in 8085?
SQ4. How does the ALU in BIU differ from the ALU in EU of 8086?
SQ5. How does the physical address get computed in 8086?
SQ6. How does a microcomputer system differ from a general computer system?
SQ7. Identify the typical components of a microcontroller.
30 | Microcontrollers and Applications
SQ8. How does a microcontroller differ from a microprocessor?
SQ9. Compare the features of low- and high-level languages.
SQ10. Identify the components of an IDE.
LQ1. A hypothetical CPU has 15-bit address bus and 8-bit data bus. Draw a diagram depicting the
interfacing of 8kB RAM and 4kB ROM with it using memory chips of size 2k 4-bits each.
Show all control line connections as well.
LQ2. Compare between the operations of 8085 with 8088.
LQ3. Enumerate the criteria guiding the selection of a microcontroller for an application.
LQ4. Compare the features of high-level language C with the assembly language of 8085.
LQ5. How does the operation of a compiler differ from that of linker?
Numerical Problems
NQ1. A hypothetical CPU has 10-bit address bus. Assuming the system to have a 512 byte memory
chip interfaced with it, compute the maximum number of peripheral devices that could be
accessed by the processor.
NQ2. Suppose the content of registers A and B of the 8085 CPU are 139 and 125. Compute the
content of A register after executing the instruction “ADD B”.
NQ3. Compute the address put onto the address bus of 8086 processor if the contents of CS and IP
registers are 20E0H and 0231H.
NQ4. Compute the frequency at which 8085 processor will work if the crystal has a frequency of
6.2 MHz.
NQ5. The 8051 CPU has 128 byte RAM and 4kB ROM space. Determine the number of address
lines sufficient to access the program and data memory respectively.
Answers of Numerical Problems
1: 512, 2: 8, 3: 21031H, 4: 3.1 MHz, 5: 7, 12
Microcontrollers and Applications | 31
KNOW MORE
Going back to the history of development of microcontrollers, during 1970s, Gary Boone
of Texas Instruments discovered a single integrated circuit chip that could hold all the essential
circuit components to make a calculator. With this chip, only a keypad and a display unit are to be
added to make a complete calculator. The chip with around 5000 transistors provided 3000 bits of
program memory and 128 bits of data memory. The invention was named as TMS1802NC. Looking
into the broad range of requirements from users, TI continued to improve upon the chip. By 1974,
the microcontroller TMS1000 was commercially available. On the other hand, Intel produced their
first microcontroller 8048 in 1976 and introduced the hugely successful 8051 in 1980. In the 1990s,
electrically erasable flash memories came. As a result, a number of microcontrollers from
Microchip and Atmel use this flash memory technologies. Further developments include advanced
microcontrollers, like ARM. These devices are being used in almost every domain of human life,
starting from automobiles, lighting, communication, low-power hand-held devices (such as, smart
phones) to even tooth brushes and toys.
32 | Microcontrollers and Applications
2
d
The 8051 Architecture
UNIT SPECIFICS
Through this unit, the following concepts have been elaborated:
Features of different commonly available 8051 variants;
Functionality of its pins along with their function-wise grouping;
The internal architecture of the 8051 chip, in terms of its CPU, memory, I/O ports and
timers;
The clock and reset circuitry for the 8051;
Usage of parts of memory as stack;
Hardware structure of I/O port pins;
Interfacing of external program and data memory chips;
Concepts of timing diagrams and instruction execution cycles;
A classification summary of the instructions of 8051;
Assembly language program structure for the 8051.
The overall discussion in the unit is to give the details of the 8051 architecture, starting with
the pin diagram of the chip and the internal block diagram. It has been assumed that the reader
has gone through the Unit-1 of this book and has got an initial grasp on the general processor
structure, memory interfacing and instruction execution process. A basic understanding of
programming will be helpful for this unit, as well, particularly to follow the overview of assembly
language programming part. A good number of examples have been included to explain the
concepts, wherever needed.
A large number of multiple choice questions, relevant for the topics discussed in this unit, have
been provided with their answers. Apart from that, subjective questions of short and long answer
type have been included. A few numerical problems with answers have been provided. A list of
references and suggested readings have been given, so that, one can go through them for more
details. The section “Know More” has been carefully designed so that the supplementary
information provided in this part becomes beneficial for the users of the book. This section mainly
highlights the initial activity, the history of the development of 8051 and some features of the 8051
chip that have been carried forward to many advanced processors.
34 | Microcontrollers and Applications
RATIONALE
This unit on the 8051 architecture illustrates the internal organization and working of the 8051
chip. Starting with the identification of the features of the 8051 variants, it next looks into the pin-
level detail of the chip. The unit discusses about the internal blocks of the 8051 chip, the distribution
of on-chip RAM into different portions, such as, register banks, bit- and byte-addressable locations,
the special registers etc. and I/O ports. The clock circuitry explains the clock input alternatives,
while the reset circuit provides mechanism to reset the chip. The unit discusses how to set up a
stack in the RAM. The I/O pins of the 8051 are of special type, providing pin-level control over the
I/O operations. The input operation needs a special activity to enable the pins for reading. The on-
chip memory of the 8051 is very limited. To go for any medium to large size program, it is necessary
to interface external memory modules. This is done by providing the address and data lines through
the ports. To understand the operating procedure of the CPU, it is necessary to view the activation
of various signals over the time. This can be captured best by the timing diagrams spanning over
the clock cycles. The 8051 chip supports a set of instructions of different types – data transfer,
arithmetic and logic operations, bit manipulation, program branching etc. In order to write a
correct assembly language program, familiarity of operation of the assembler, its input-output
formats are required. This unit makes the reader to have a basic understanding of the assembly
language program structure and its input/output files. Thus, the unit gives a good understanding
of the structure and operation of the 8051 chip.
PRE-REQUISITES
Electronics: Unit 1 of the book
Programming: Basic Computer Programming
UNIT OUTCOMES
List of outcomes of this unit is as follows:
U2-O1: State the functionality of pins of the 8051
U2-O2: Draw block-level diagram of internal architecture of the 8051
U2-O3: Enumerate the registers and their functionalities
U2-O4: State the operation of clock and reset circuitry of the 8051
U2-O5: Draw the structure of I/O pins
U2-O6: Interface external program and data memories to the 8051
U2-O7: Draw timing diagrams for external memory access
U2-O8: List instruction types of the 8051
U2-O9: State the structure of assembly language programs
Microcontrollers and Applications | 35
2.1 Introduction
36 | Microcontrollers and Applications
The microcontroller 8051 is the first one in the MCS-51 family introduced by the Intel
Corporation in 1981. It has the resources in it, as noted in Table 2.1. There are two more members
in the MCS-51 family. The first
Table 2.1: Features of 8051 Processor
one, the 8031 processor, has zero
CPU 8 bit
on-chip ROM with other features
ROM (on-chip) 4 kB
same as 8051. The second one, the
RAM (on-chip) 128 bytes
8052 processor, has several
Timer/Counter 2, 16-bit
augmented features, compared to
Digital I/O 32 pins
8051. For example, the 8052 has
Serial Port 1
8kB on-chip ROM, 256 bytes
Interrupts 6
RAM, 3 timers and 8 interrupt
Program memory address space 64 kB
sources. Among the 8051
Data memory address space 64 kB
microcontrollers also there are
several variants. This has happened as 8051 is fabricated by different manufacturers under different
part numbers. The products mainly differ in the memory technology used to realize the ROM. In
the following some such variants have been enumerated.
8751: It uses UV-EPROM to realize the on-chip ROM. For programming, PROM burner is
needed. It needs a UV-EPROM eraser to erase the content to aid in reprogramming. The
erasing takes time upto 20 minutes.
AT89C51: It uses flash memory for on-chip ROM. Thus, the microcontroller needs a ROM
burner, however, eraser is not needed. It saves reprogramming time.
DS89C4x0: This constitutes a family of microcontrollers (x varying from 2 to 5) with flash
ROM. The chips have on-chip loader that can be interfaced to a PC via serial COM ports.
OTP versions: The one-time-programmable (OTP) versions of 8051 are available with
cheaper unit price, compared to flash versions. These are often used in mass production of
systems, once the program logic has been debugged and finalized using the flash versions.
Microcontrollers and Applications | 37
as asynchronous reset input to the 8051. The switch must be closed for at least two machine
cycles (discussed later) of the processor to give a proper reset pulse.
MA
+5V
VCC VSS
40 VCC XTAL1 20
P1.0 1 19 40
P1.1 2 39 P0.0/AD0 39
P1.2 3 38 P0.1/AD1 P0.0/AD0
20 to
P1.3 4 37 P0.2/AD2 XTAL2
P0.7/AD7
P1.4 5 36 P0.3/AD3
P0.4/AD4 +5V PSEN 29 32
P1.5 6 35
P1.6 7 34 P0.5/AD5 ALE 30
P1.7 8 33 P0.6/AD6 10μF EA 31
RST 9 32 P0.7/AD7 9 1
8051
RST
8051
P3.0/RXD 10 31 EA
8.2kΩ P1.0 to P1.7
P3.1/TXD 11 30 ALE
P3.2/INT0 12 29 PSEN
P2.7/A15
8
P3.3/INT1 13 28 P3.0/RXD 10
P3.4/T0 14 27 P2.6/A14 P3.1/TXD 11
P3.5/T1 15 26 P2.5/A13 P3.2/INT0 12
21
P3.6/WR 16 25 P2.4/A12 P3.3/INT1 13 P2.0/A8
P3.7/RD 17 24 P2.3/A11 P3.4/T0 14 to
XTAL2 18 23 P2.2/A10 P3.5/T1 15 P2.7/A15
XTAL1/ 19 22 P2.1/A9 28
CLKIN V P3.6/WR 16
SS 20 21 P2.0/A8 P3.7/RD 17
Fig 2.1(a): 8051 pin diagram Fig 2.1(b): Grouping of 8051 pins
𝐄𝐀 (Pin 31): The pin indicates external access by the 8051. When set to high, the 8051
uses internal ROM for instructions. When the line is set low, the external memory is
accessed.
Port 0 (Pins 32 to 39): These pins act as an 8-bit I/O port. The pins are also used to
provide multiplexed address-data bus lines AD7-AD0. The port bit lines are open-drain
and thus need external pull-up resistors to be connected for their proper operation.
Port 1 (Pins 1 to 8): This is an 8-bit I/O port and is the only port whose lines are not
assigned additional functions.
Port 2 (Pins 21 to 28): The port bit lines are assigned the additional role to provide higher
order address lines A8-A15 for external memory access.
38 | Microcontrollers and Applications
Port 3 (Pins 10 to 17): The port bits can be used for I/O purposes. However, each pin has
got some alternate function assigned to it. The pins 10 and 11 are used for serial I/O. Pins
12 and 13 act as inputs corresponding to active low interrupt lines INT0 and INT1. Pins 14
and 15 are timer control inputs T0 and T1, respectively. Finally, the pins 16 and 17 are
assigned the additional responsibility of providing write (WR) and read (RD) controls for
the external data memory access.
𝐏𝐒𝐄𝐍 (Pin 29): It is used as strobe to access the external program memory.
ALE (Pin 30): It is used to demultiplex the lines AD7-AD0 into the lower order address
bus and data bus.
External Interrupts
Counter
Interrupt 128 Byte 4 kB Timer 1
Inputs
Control RAM ROM
Timer 0
CPU
Bus Serial
OSC I/O Ports
Control Port
P0 P1 P2 P3 TXD RXD
Fig 2.2: Internal Block Diagram of the 8051
2.3.1 CPU
Microcontrollers and Applications | 39
The CPU consists of an Arithmetic Logic Unit (ALU), Instruction Decoder and Control
and a number of registers. The ALU is a 8-bit one, capable of performing several types of arithmetic
and logic operations. Like other CPUs, the instruction FF
from program memory with location pointed to by the
Special Function Registers
Program Counter (PC) is fetched into an Instruction
80
Register. The instruction is decoded by the
Instruction Decoder to generate relevant sequence of 7F
control signals. Apart from PC, the CPU contains a General Purpose RAM
set of general- and special-purpose registers. As the 30
CPU registers are mapped onto RAM locations,
2F 7F 7E 7D 7C 7B 7A 79 78
details of the registers will be discussed in
2E 77 76 75 74 73 72 71 70
conjunction with the RAM.
2D 6F 6E 6D 6C 6B 6A 69 68
2C 67 66 65 64 63 62 61 60
2.3.2 Memory 2B 5F 5E 5D 5C 5B 5A 59 58
The 8051 chip has 4kB on-chip program 2A 57 56 55 54 53 52 51 50
memory implemented using EPROM/flash 29 4F 4E 4D 4C 4B 4A 49 48
technology. It also has 128 byte data memory (RAM). 28 47 46 45 44 43 42 41 40
Thus, the RAM location addresses range over 00H to 27 3F 3E 3D 3C 3B 3A 39 38
7FH. However, beyond 7FH (and till 0FFH), some 26 37 36 35 34 33 32 31 30
RAM addresses are defined to correspond to some
25 2F 2E 2D 2C 2B 2A 29 28
special function registers. It may be noted that only
24 27 26 25 24 23 22 21 20
few of the address locations between 80H and 0FFH
are used for this purpose, rest of the locations are not 23 1F 1E 1D 1C 1B 1A 19 18
usable. The internal RAM organization has been 22 17 16 15 14 13 12 11 10
shown in Fig 2.3. It consists of the following 21 0F 0E 0D 0C 0B 0A 09 08
components. 20 07 06 05 04 03 02 01 00
1F
Register Bank 3
1. Register Banks (00H to 1FH): These are the 18
lowest 32 bytes of RAM space grouped into 17
4 banks of 8 locations each. Each bank 10 Register Bank 2
consists of registers R0, R1, R2, R3, R4, R5,
0F
R6 and R7. At a time, only one bank of Register Bank 1
registers is active that can be used by the 08
instruction being executed. Activation of 07
banks is controlled by two status bits in the 00 Register Bank 0
Processor Status Word (PSW) register.
Instructions can use the name of a register or Fig 2.3: Internal RAM Locations
a memory address to refer to an operand. For example, the RAM address 04H and register
R4 in Bank-0 refer to the same memory location.
40 | Microcontrollers and Applications
2. Bit-Addressable RAM (20H to 2FH): These are 16 memory locations of which individual
bits can be referred to by the bit-manipulating instructions. Such instructions can set/clear
a bit, complement it or check the value. Some of the Special Function Registers (SFRs),
noted later, are also bit-addressable.
3. General Purpose RAM (30H to 7FH): These 80 bytes of RAM locations could be used
as general purpose storage space by the programs. It may be noted that for most of the
applications, a stack space is needed for subprograms and interrupt handlers. The stack is
also sometimes implemented in this region. As a result, the remaining usable space may be
quite small.
4. Special Function Registers (SFRs): Several addresses in the range of 80H to 0FFH are
dedicated for SFRs. Out of the total 128 locations available in this range, only 21 have been
used and the remaining addresses are undefined. A user program should not try to access
those addresses, as the result may be unpredictable. The used registers are noted next.
Accumulator (0E0H): Also referred to as A register in the instructions, the
accumulator is used in all arithmetic and logic instructions. It holds one of the source
operands and also acts as destination for such instructions. It is a 8-bit bit-addressable
register.
B Register (0F0H): This is another general purpose 8-bit register, which is also bit-
addressable. The primary use of B register is as an operand and a destination of
multiplication and division instructions.
Stack Pointer (81H): It points to the top of the stack. The stack is implemented in the
on-chip RAM. On reset, the 8-bit stack pointer is initialized with 07H. It is not bit-
addressable.
Data Pointer (82H – 83H): This is a 16-bit register consisting of two 8-bit parts –
Data Pointer High (DPH) with RAM address 83H and Data Pointer Low (DPL) with
memory address 82H. The DPTR register can be used to access on-chip ROM or an
externally connected RAM. The register is not bit-addressable.
Interrupt Related: Two registers Interrupt Enable Control (IE) and Interrupt
Priority Control (IP) are available at RAM addresses 0A8H and 0B8H respectively,
both being bit-addressable. The IE register is used for enabling/disabling certain
interrupts while the IP is used to define the relative priorities between the enabled
interrupts.
Timer/Counter Related: The current values of timers/counters are held in a few 8-
bit registers. For timer-0, the lower byte is stored in register TL0 (memory address
8AH), higher byte in TH0 (8CH). For timer-1, the corresponding registers are TL1
(8BH) and TH1 (8DH). Apart from that, TCON register at 88H controls the operation
of the timers/counters. Mode set register TMOD at 89H configures the modes of the
timers/counters. Out of all these, only the TCON register is bit-addressable.
Serial I/O Related: A bit-addressable register SCON at RAM address 98H controls
the serial I/O operations. The SBUF register at 99H contains the data
received/transmitted serially.
Microcontrollers and Applications | 41
Power Control: The PCON register at RAM address 87H sets the power control to
be applied. The register is not bit-addressable.
Processor Status Word (0D0H): This 8-bit PSW register contains 4 bits
corresponding to the status of the last ALU operation. Two more bits in it control the
register bank to be used by the instructions, one bit is available to the user for
programming, while one bit is kept undefined. Table 2.2 shows the bit usages of PSW
register.
42 | Microcontrollers and Applications
There are two timers in the 8051 microcontroller – Timer-0 and Timer-1. The timers can
also be used as counters to count external events occurring on pins T0 and T1, respectively. The
timers can be configured into 16-bit, 13-bit and 8-bit modules.
C2
XTAL2 NC XTAL2
30 pF
30 pF
External
XTAL1 XTAL1
Oscillator
C1
(a) (b)
Fig 2.4: Clock Circuit – (a) Crystal (b) Direct
Machine Cycle: A machine cycle refers to the time for a group of related activities, such as,
accessing the memory. One machine cycle for the 8051 chip consists of a number of clock cycles.
The original 8051 was designed to have 12 clock cycles per machine cycle. Thus, depending upon
the frequency of the crystal connected to it, duration of a machine cycle may vary even for this
original version of the 8051. A certain number of machine cycles are needed to execute a complete
instruction. The data sheet of the 8051 chip lists the number of machine cycles needed for each
instruction. As noted earlier, there are many different manufacturers of 8051. With the
Microcontrollers and Applications | 43
advancement in VLSI technology, these variants support different maximum clock frequencies.
The number of clock cycles per machine cycle and the number of machine cycles needed for an
instruction, also vary across these implementations. For example, a MOV instruction in the original
8051 chip needs 1 machine cycle with 12 clock cycles in the machine cycle. On the other hand, the
same MOV instruction needs 2 machine cycles in DS89C4x0, each machine cycle requiring just
one clock cycle.
Example 2.1: Assuming the crystal frequency to be 11.0592 MHz, let us compute the time
needed to execute (i) MOV (ii) MUL instructions, for 8051 and DS89C4x0 chips. First, the
duration of a clock cycle is 1/11.0592 = 0.0904 μS. Hence, duration of a machine cycle for 8051
is 12 0.0904 = 1.0848 μS. For DS89C4x0, machine cycle duration is 1 0.0904 = 0.0904 μS.
From the data sheet, it can be found that the number of machine cycles for MOV in 8051 is 1
and for DS89C4x0, it is 2. Thus, the time needed to execute a MOV instruction in 8051 is 1.0848
μS, while for DS89C4x0 it is 2 0.0904 = 0.1808 μS. For MUL, 4 machine cycles are needed for
8051 and 9 for DS89C4x0. Thus, the time required for a MUL instruction in the 8051 is
4 1.0848 = 4.3392 μS. For DS89C4x0, the corresponding time is 9 0.0904 = 0.8136 μS.
2.5 Reset Circuit
The 8051 chip has an active high RESET input (marked as RST, Pin 9). The input line
should be held low during normal operation of the chip. To reset the chip, a high pulse of duration
equal to at least two machine cycles be applied to RST. As noted previously, different 8051 variants
Table 2.3: Register values on reset
+5V
Register Value (Hex)
10μF Accumulator 00
B 00
RST PC 0000
S DPTR 0000
PSW 00
8.2kΩ
SP 07
Ports P0-P3 0FF
44 | Microcontrollers and Applications
to high. The switch should be kept pressed for at least two machine cycles to cause a reset. On
reset, the contents of important registers in the 8051 chip are as shown in Table 2.3.
Microcontrollers and Applications | 45
The 8051 has four ports for I/O operations, named as Port 0, Port 1, Port 2 and Port 3. Each
port has 8 bidirectional I/O pins. For any port, the
pins can be programmed individually to act as input Table 2.4: Alternate Functions of Port 1
or as output. Each I/O pin has an associated D-latch Bit No. Alternate function
that can hold the value at the corresponding pin. As 0 RxD
discussed in Section 2.2, out of the four ports, only 1 TxD
the Port1 can be considered as assigned the pure I/O 2 INT0
responsibilities. Port 0 pins have the task of acting as 3 INT1
multiplexed lower-order address and data bus. Port 2 4 T0
provides higher order address. Port 3 bits have the 5 T1
additional responsibilities, as noted in Table 2.4. 6 WR
7 RD
2.7.1 Hardware Structure of I/O Pin
The generic hardware structure of an I/O pin in 8051 has been shown in Fig 2.6. This
corresponds more to the pins of Port 1, as those are not assigned any additional functionality. The
overall structure consists of the following components.
Connection to data bus: Each port bit is connected to one of the data bus lines. The data
transfer takes place between the 8-bit data bus lines and the port bits.
D-latch: One D-latch is used to hold the value that is output from the CPU to the pin. For
this, the Latch_Enable signal be made high.
Tristate buffers: Two tristate buffers control the flow of information from the port to the
data bus line.
Tristate buffer TB1 Read_Latch VCC
controls the
LOAD
availability of pin TB2
input to the CPU bus To CPU
line. TB2 controls Bus line I/O Pin
the latch output D Q
reaching the CPU
bus. TB1 has the EN QBAR M
Latch_Enable
control input
Read_Pin, while
TB2 has TB1
Read_Latch. Read_Pin
Naturally, the two
control signals Fig 2.6: Hardware Structure of I/O Pin
should not be activated simultaneously. The 8051 has different groups of instructions for
the two categories of operations.
46 | Microcontrollers and Applications
Gate transistor: Enabling and disabling the gate control input to the nMOS transistor turns
it on or off. Accordingly, the port pin logic level becomes high (with transistor M being
off) or low (with M on).
Write Operation: To write a high (1) to the I/O pin, that is for an output operation, the CPU bus
bit has to be turned high and the Latch_Enable signal activated. This will set Q to 1 and QBAR to
0. The transistor M gets turned off. As a result, the port pin gets charged to 1 through the Load.
Similarly, for a 0 output, the bus bit is set to 0. QBAR becomes 1, turning on the transistor M. The
port pin line discharges through M, going to logic 0.
Read Operation: As noted
Read_Latch VCC
earlier, there are two types of
I/O read (input) operations 0
LOAD
supported in 8051. The first TB2
one reads the content of the D- To CPU
latch. This is implemented by Bus line I/O Pin
1 D Q 1
activating the Read_Latch
and deactivating Read_Pin. 0
The other category reads the EN QBAR M
Latch_Enable
value given as input at the port
pin. For this, Read_Pin is
activated, while Read_Latch TB1
is deactivated. However, there Read_Pin 1
is an issue with this input
Fig 2.7: Hardware Structure of I/O Pin
operation. Consider that the
D-latch has been set previously with the value Q = 0, that is, QBAR = 1. As QBAR is 1, it turns on
the transistor M. Now, with M turned on, the port pin cannot stay at logic high, as it will get
discharged via M, in that case. Thus, though reading a 0 input at port pin can be error-free, to read
a 1, it is necessary that D-latch is set to Q = 1, QBAR = 0. This can be ensured by outputting a 1 to
the port bit. Thus, whenever an input operation is needed, to ensure correct result, it is required that
an “output 1” operation is performed at the port bit. This will set QBAR to 0, disabling the transistor
M. The situation has been illustrated in Fig 2.7 after the following two operations have been
performed in sequence.
1. Output 1 to the port bit
2. Input the bit from the port
As a result, any input operation consists of two instructions. The first instruction writes a 1 to the
port pin, while the second instruction performs the actual input operation.
Microcontrollers and Applications | 47
2.7.2 Port 0 Structure
Structure of Port 0 pins is a bit different, compared to the other ports. A typical Port 0 pin
structure has been shown in
Fig 2.8. Compared to Fig 2.6, Read_Latch VCC
in a Port 0 pin, there is no
internal pull-up resistance TB2
connected. Thus, the port bits To CPU
are open-drain. Writing a 1 to Bus line
D Q
the D-latch turns off the
transistor M, which causes I/O Pin
the pin to float. It does not EN QBAR M
Latch_Enable
create problem in the port
acting as multiplexed
address/data bus. However, TB1
while using it for I/O Read_Pin
purposes, an external pull-up
Fig 2.8: Hardware Structure Port 0 Pin
resistance must be connected
to source current to the pin. For address/data multiplexing, the port bit is connected to some latch
(for example, 74LS373), thus external pull-up is not needed in that case. Due to its open-drain
configuration, the Port 0 can drive more number of fanouts, compared to other ports. While the
ports Port 1, Port 2 and Port 3 can drive upto 4 TTL inputs, Port 0 can drive upto 8 TTL inputs.
8-bit Latch
8085 processor, an
Address lines
external 8-bit latch is AD0-AD7 IN
needed to hold the ALE G
address lines steady,
even after the ALE has Fig 2.9: Demultiplexing of Address and Data Lines
been withdrawn.
Generally, the ALE signal is activated for two clock cycles. The address-data bus
demultiplexing process has been shown in Fig 2.9.
5. PSEN: The signal, Program Strobe Enable (PSEN) is an active low output signal of 8051.
It is used to access the external program memory. The external program memory is
generally implemented via ROM having an Output Enable (OE) pin. The PSEN line is
connected to OE.
6. RD: The Read (RD) is an active low output signal of 8051, used to read data from the
external data memory. The data memory can be upto 64kB in size with address provided
by the DPTR register.
7. WR: The Write (WR) is also an active low output signal, used for writing data onto the
external data memory.
2.8.1 External Program Memory Interface
Fig 2.10 shows the access rules to the program memory interfaced, based upon the EA
input setting. As shown in Fig 2.10(a), when the EA pin is grounded, the 8051 uses the external
program memory only, for its entire address range. However, with EA = 1, the 8051 uses both the
on-chip and the external program memories. The on-chip memory is size-restricted to 4kB. Thus,
for program addresses generated by the CPU in the range 0000H to 0FFFH, the on-chip ROM is
Microcontrollers and Applications | 49
accessed. For addresses in the range 1000H to 0FFFFH, the external ROM is accessed. This has
been shown in Fig 2.10(b).
EA = 0 EA = 1
FFFF FFFF
External
External
1000
0FFF
Internal
0000 0000
(a) (b)
Fig 2.10: External Program Memory with (a) EA = 0,
(b) EA = 1
Fig 2.11 shows the connection of signal lines onto the 8051 side to access external program
memory. The EA pin may be set to high or low, as discussed. Port 2 provides the higher order
address bus lines. The lower-order address lines are extracted from the Port 0 lines AD0-AD7
through demultiplexing, using 8-bit latch. The PSEN line is available for connecting to the OE line
of the external ROM.
A8-A15
8-bit Latch
EA A8-A15
ALE G A0-A7
8051
AD0-AD7 IN
D0-D7
PSEN
50 | Microcontrollers and Applications
Example 2.2:
16kB ROM
Consider the
interfacing of 64kB CS
00
Decoder
external program PSEN
A14 0 01
memory to the 8051 A15 10
1
16kB ROM
chip. It is assumed that 11
the on-chip ROM A8-A13 D0-D7
space will not be used
8051
by the system and that
ALE G
Latch
16kB ROM
the 64kB space will be
A0-A7
arranged with ROM AD0-AD7
A0-A13
chips of 16 kB each.
Thus four such chips
are needed. The EA
16kB ROM
OE
interface has been
shown in Fig 2.12.
Fig 2.12: Example Program Memory Interface
No dependency on EA AD0-AD7 IN
line. D0-D7
PSEN connection is not RD
required. WR
Port 0 and Port 2 lines
are used to provide 16- Fig 2.13: Signal Lines for Program Memory Interface
bit address- and 8-bit
data-bus lines.
Read (RD) and Write (WR) signals from Port 3 are used for read and write operations.
Microcontrollers and Applications | 51
Example 2.3: Fig
16kB RAM
2.14 shows an
example external data
memory interface 00 CS
Decoder
with the 8051 chip. A14 0 01
The system realizes A15 10
16kB RAM
1
64 kB external data 11
memory space. Each A8-A13 D0-D7
8051
RAM chip is assumed
to be of size 16 kB.
ALE G
Latch
16kB RAM
Four such memory A0-A7
chips have been AD0-AD7 A0-A13
integrated here. The
address- and data-bus
connections are WR
16kB RAM
WR
similar to that for RD RD
Example 2.2.
However, the PSEN Fig 2.14: Example Data Memory Interface
and EA lines do not
have any role. Instead of them, RD and WR controls have been connected with individual RAM
chips.
Microcontrollers and Applications | 53
clock pulses. As shown in Fig 2.16, in every machine cycle, the ALE signal is activated twice,
indicating that the internal/external memory could be accessed twice per machine cycle. Depending
upon the instruction being executed, different number of memory accesses may be necessary. Fig
2.17 shows a timing diagram corresponding to a read operation from the external program memory.
It reads two bytes from the memory. The whole operation takes one machine cycle with the content
of the first byte being available at pulse 2 of State 4. The other operand is available at pulse 2 of
State 1 in the next machine cycle. That next machine cycle can use this data for any intended
operation, such as, moving to some register. In each memory access, Port 2 holds the content of the
higher-order address bus. Port 0 functions as the multiplexed address-data bus that holds the lower-
order address bus content, A0-A7 at the beginning. The falling edge of the ALE signal indicates
the time at which the lower-address bus content is stable and could be used to latch the address in
the external latch. The line PSEN is used as strobe for the external program memory access. The
rising edge of PSEN is used as strobe for the external program memory access. The rising edge
indicates the time at which valid data from the external memory is available in the data bus (that
is, Port 0).
The timing diagram shown in Fig 2.18 considers the situation in which a one-byte
instruction is accessed from the external program memory, which in turn, instructs the CPU to read
one byte from the external data memory. This is generally accomplished by the MOVX instruction,
S1 S2 S3 S4 S5 S6 S1 S2 S3 S4 S5 S6
ALE
PSEN
RD
Fig 2.18: Timing Diagram with External Program and Data Memory Access
illustrated later. The whole execution spans over two machine cycles. In the first machine cycle,
the external program memory is accessed, with values of PCH and PCL being put on Port 2 and
54 | Microcontrollers and Applications
Port 0 lines respectively, to provide address. The content is read from the program memory on the
rising edge of PSEN. In the next machine cycle, content of DPH register is put on Port 2 and DPL
on Port 0, to provide address. It may be noted that the registers DPH and DPL together constitute
the 16-bit DPTR register, used for accessing external data memory. The low-to-high transition of
the RD line is used as strobe for the data memory read operation.
2.10 Instruction Set Summary
In this section, we shall look into an overview of the 8051 instructions. Details of all the
instructions have been presented in Unit 3. The instructions could be grouped into five categories
– Data Transfer, Arithmetic Operations, Logical Operations, Bit-Manipulation Operations and
Program Branching. Table 2.5 summarizes the categories along with examples.
Table 2.5: The 8051 Instruction Set Summary
Type & Mnemonics Operands Examples
Data Transfer: Register, MOV A, R0 ; A gets content of R0
MOV, MOVX, Memory MOV R3, 5 ; R3 gets RAM[5]
PUSH, POP, XCH address,
MOV R5, #10H ; R5 gets 10H
Pointer
register, MOVX A, @DPTR ; A gets content of memory
Immediate data location pointed to by DPTR
PUSH 4 ; Push content of RAM[4] to stack
POP 3 ; Pop stack top to RAM[3]
XCH A, R2 ; Contents of A and R2 exchanged
Arithmetic Register, ADD A, R1 ; A gets (A + R1)
Operations: Memory ADD A, 5 ; A gets (A + RAM[5])
ADD, ADDC, address,
ADDC A, @R2 ; A gets (A + RAM[R2] +
SUBB, INC, DEC, Pointer
register, Carry Flag)
MUL, DIV, DA
Immediate data SUBB A, #10 ; A gets (A – 10 – Carry Flag)
INC R4 ; R4 gets R4 + 1
MUL AB ; A and B gets lower and higher
bytes of A B
DIV AB ; A and B gets quotient and
remainder of A B
DA A ; A gets converted to BCD format
Logical Operations: Register, ANL A, R1 ; A gets (A AND R1)
ANL, ORL, XRL, Memory ORL A, 5 ; A gets (A OR RAM[5])
CLR, CPL, RL, RLC, address,
XRL A, #10H ; A gets (A XOR 10H)
RR, RRC, SWAP Pointer
XRL A, @R2 ; A gets (A XOR RAM[R2])
Microcontrollers and Applications | 55
register, CLR A ; A gets 0
Immediate data CPL A ; A gets (NOT A)
RL A ; A content rotated left
RRC A ; A along with Carry, rotated left
SWAP A ; Swap nibbles of A
Bit-Manipulation Carry Flag, Bit CLR C ; Carry flag gets 0
Operations: address CLR PSW.3 ; Clear bit 3 of PSW register
CLR, SETB, CPL, SETB 1AH ; RAM-bit 1A gets 1
ANL, ORL, MOV
CPL 1CH ; RAM-bit 1C gets 0
ANL C, 1FH ; Carry flag ANDed with bit 1FH
MOV C,1FH ; Carry flag gets bit from 1FH
Program Branching 11-bit address, ACALL <11-bit> ; PC saved in stack and
– Unconditional: 16-bit address, PC[10:0] gets <11-bit>
ACALL, LCALL, 8-bit relative
LJMP <16-bit> ; PC gets <16-bit>
JMP, SJMP, AJMP. address
JMP @A+DPTR ; PC gets (A + DPTR)
LJMP, RET, RETI
SJMP <8-bit> ; PC gets (PC + <8-bit>)
RET ; Return from subroutine
PC gets 2 bytes by popping stack
RETI ; Return from interrupt handler
PC gets 2 bytes by popping stack
Program Branching 8-bit relative JC <8-bit> ; PC gets (PC + <8-bit>) if Carry set
– Conditional: address JB 1AH, <8-bit> ; PC gets (PC + <8-bit>) if 1AH set
JC, JNC, JB, JNB, JNZ <8-bit> ; PC gets (PC + <8-bit>) if Zero flag
JBC, JZ, JNZ, CJNE,
not set
DJNZ
CJNE A, 5, <8-bit> ; PC gets (PC + <8-bit>) if A not
equal to RAM[5]
DJNZ R1, <8-bit> ; R1 gets R1 – 1. PC gets (PC +
<8-bit>) if R1 is non-zero now
DJNZ 5, <8-bit> ; RAM[5] decremented by 1. If
RAM[5] non-zero, PC gets
(PC + <8-bit>)
Machine Control: - NOP ; Do nothing
NOP
56 | Microcontrollers and Applications
2.11 Assembly Language Program Structure
Any assembly language program consists of a series of lines of assembly language
instructions. Each instruction has the following components – an optional label, a mandatory
mnemonic, a number of operands (depending upon the mnemonic) and an optional comment (often
demarcated by a ‘;’ character), as shown next.
[label:] mnemonic [operands] [; comment]
For example, consider the following instruction.
HERE: MOV A, R0 ; A gets content of R0
HERE is a label that may be used to specify some jump target. MOV is the mnemonic, A and R0
are two operands. “MOV A, R0” is an instruction of 8051, as noted previously.
Apart from the processor instructions, an assembly language program may have some
additional components that can be classified into assembler directives and storage declarations.
Both of these are dependent, to a large extent, on the assembler being used to generate machine
code from the assembly code. The following discussion is a generic one, which may differ to some
extent in any individual assembler.
2.11.1 Assembler Directives
Most of the 8051 assemblers support the three directives – ORG (origin), EQU (equate)
and END (end of source code).
1. ORG: It is used to indicate the starting memory address for an assembly language
instruction block. It is of the form,
which indicates that the code corresponding to the following instruction is meant for
memory location number. For example, consider the following code sequence.
ORG 1000H
MOV A, R1
Here, the machine code for the instruction “MOV A, R1” is to be placed at memory
location 1000H. It may be noted that an assembly language program may have several
ORG statements in it. Each ORG defines a new start address of its immediately following
code fragment.
2. EQU: This defines a constant. No storage space is allotted to hold the constant value
separately. A typical syntax for EQU directive of an assembler may be as follows.
Microcontrollers and Applications | 57
Here, TOTAL is a label. In the source code, whenever the assembler finds the label
TOTAL, it is replaced by the constant 100, before translating the corresponding instruction.
For example, with the previous definition of TOTAL, the assembly language statement
“MOV R1, #TOTAL” is same as “MOV R1, #100”.
Introduction of the EQU directive helps the programmer to write more structured
programs, with the ease of modification. For example, the constant TOTAL may define the
total number of numbers (100 in this case) in an array, processed by the program. The
programmer may need to load several registers/memory locations with the value 100. Now,
if the requirement changes and the number of numbers become 1000, all those program
instructions need to change from 100 to 1000. This is an error-prone activity. On the other
hand, in the presence of definition “TOTAL EQU 100” and using the constant TOTAL in
all those instructions, it is very easy to effect the change from 100 to 1000 by just changing
the constant definition to “TOTAL EQU 1000”. All the relevant instructions get modified
accordingly.
3. END: The END directive specifies that the assembler should not consider anything beyond
this line to be part of the source code. Thus, it indicates the end of the assembly process.
58 | Microcontrollers and Applications
2.11.3 Important Files
There are several files that are involved in the assembly process. First, the assembly
language program is written
into a text file, called the source Source Hex
Assembler
file. It typically has the File File
extension “.asm”. The file is
assembled to produce a binary List
file containing the machine File
code of 8051. The machine
code is in a format that the IDE Fig 2.19: Important Files in Assembly
may download to the 8051
development kit. This binary file has the extension “.hex”. The hex file is not understandable by
the programmer writing the source code. To help the programmer in the debugging and
understanding process, often the assemblers produce another text file that lists side-by-side the
machine code generated and the instruction translated. This file is called the list file and often has
the extension “.lst”.
Example 2.4: Consider the problem of identifying the smallest number in an array of size N.
The array is stored in the external data memory starting from location 2000H. The source code
of the program has been listed next. Size of the array, N has been taken as a constant via the
EQU declaration. Here, N has been set to 4. Comments have been attached with each line for
explanation. The program is assumed to start at ROM address 0000H, identified by the ORG
statement. Memory location 40H has been used to hold a temporary variable TEMP.
ORG 0000H
TEMP EQU 40H ; Temporary location
N EQU 04H ; Size of array
MOV R4, #N-1 ; R4 holds a count
MOV DPTR, #2000H ; DPTR points to start of array
MOVX A, @DPTR ; Get first element in A
L1: MOV R1, A ; Assume it smallest and copy in R1
L2: INC DPTR ; DPTR points to the next element
MOVX A, @DPTR ; Get next element in A
MOV TEMP, A ; Save next element at TEMP
MOV A, R1 ; Get previous element into A
CJNE A, TEMP, L3 ; Compare two elements
SJMP L4 ; If equal, A is holding the smallest
Microcontrollers and Applications | 59
L3: JC L4 ; If previous element smaller, no problem
MOV A, TEMP ; If previous element larger, get smaller in A
L4: DJNZ R4, L1 ; Check for end of array
END ; A has the smallest
60 | Microcontrollers and Applications
UNIT SUMMARY
The 8051 is one of the most popular microcontrollers developed, studied and used in
systems, over the years. Apart from the CPU, the chip contains on-chip ROM, RAM, timers and
I/O ports. The on-chip RAM has several sections in it – the register banks, bit-addressable portion,
scratch pad, stack space and special function registers. The basic 8051 design from the Intel has
two timers and four, 8-bit I/O ports. The port bits can be configured individually as input or output.
The ports can also be used to access external program- and data-memory chips, used for extending
the memory capacity. Execution of instructions consists of several machine cycles, each machine
cycle containing a fixed number of clock cycles. The instructions supported by the 8051 can be
grouped into classes, such as, data transfer, arithmetic/logic operations, control transfer, etc. An
assembly language program, apart from containing machine instructions, will generally have
variable storage space, constants etc. This unit has given a detailed view of all these aspects of the
8051.
EXERCISES
MQ1. If the crystal connected to the Intel 8051 chip is of frequency 10MHz, length of its machine
cycle is
(A) 1.4 μs (B) 1.2 μs (C) 1.0 μs (D) 1.6 μs
MQ2. If RS0 = 0 and RS1 = 0, the register bank address range in 8051 is
(A) 00H-07H (B) 08H-0FH (C) 10H-17H (D) 18H-1FH
MQ3. If RS0 = 1 and RS1 = 0, the register bank address range of 8051 is
(A) 00H-07H (B) 08H-0FH (C) 10H-17H (D) 18H-1FH
MQ4. In 8051, to make the address range 10H-17H as the present register bank, the bits RS0 and
RS1 be set to
(A) RS0 = 1, RS1 = 1 (B) RS0 = 1, RS1 = 0
(C) RS0 = 0, RS1 = 1 (D) RS0 = 0, RS1 = 0
MQ5. Bit address 42H belongs to the byte address in 8051 RAM
(A) 26H (B) 28H (C) 2AH (D) None of the other options
MQ6. Which of the following is NOT a valid status word bit in 8051?
(A) Z (B) OV (C) CY (D) AC
MQ7. Which of the following is NOT a valid status word bit in 8051?
(A) P (B) OV (C) CY (D) None of the other options
MQ8. On RESET, the value of SP in 8051 is
(A) 07H (B) 00H (C) 0FH (D) 1FH
MQ9. Which port of 8051 needs external pull-up resistances to be connected?
(A) P0 (B) P1 (C) P2 (D) P3
Microcontrollers and Applications | 61
MQ10. For getting input from a port bit of 8051 if a '1' is not written to it, reading of which value
may create problem?
(A) 0 (B) 1 (C) Both 1 and 0 (D) Neither of 0 nor 1
MQ11. Bit address 67H belongs to the byte address in 8051 RAM
(A) 2CH (B) 2DH (C) 2FH (D) None of the other options
MQ12. Bit address 42H belongs to the byte address in 8051 RAM
(A) 26H (B) 28H (C) 2AH (D) None of the other options
MQ13. IP register in 8051 controls
(A) Instruction parity (B) Interrupt parity
(C) Interrupt priority (D) None of the other options
MQ14. In a 8051 program, it is required to configure the MSB and LSB of port P0 as output. The
statement for this can be
(A) MOV P0, #81H (B) MOV P0, #FFH
(C) MOV P0, #8FH (D) None of the other options
MQ15. Number of interrupt pins in 8051 is
(A) 1 (B) 2 (C) 3 (D) 4
MQ16. Flag bit in 8051 used to detect errors in signed arithmetic is
(A) P (B) OV (C) CY (D) None of the other options
MQ17. What is the meaning of the 8051 instruction “MOV A, 05H”?
(A) 05H is stored in the accumulator
(B) Fifth bit of accumulator set to 1
(C) Content of memory location 05H copied to the accumulator
(D) None of the other options
MQ18. External Access is used in 8051 to permit
(A) Peripherals (B) Power supply (C) ALE (D) Memory interfacing
MQ19. SFR address range of 8051 is
(A) 80H to 0FEH (B) 00H to 0FFH (C) 80H to 0FFH (D) 70H to 80H
MQ20. The I/O ports in 8051 that are used as address and data for external memory are
(A) P1 and P2 (B) P1 and P3 (C) P0 and P2 (D) P0 and P3
MQ21. In 8051, which bit-level operation is possible?
(A) Complement (B) Set (C) Reset (D) All the other options
MQ22. Which control signal may be generated in 8051 to access off-chip devices?
(A) ALE (B) PSEN (C) RD, WR (D) All of the other options
MQ23. Which 8051 register does not have an on-chip RAM address?
(A) Stack pointer (B) Program counter
(C) Data pointer (D) Timer
MQ24. Bit address range in 8051 on-chip RAM is
(A) 00H to 0FFH (B) 01H to 7FH
(C) 00H to 7FH (D) 80H to 0FFH
MQ25. The 8051 port bits used as external inputs for counters are
(A) P3.4, P3.5 (B) P2.4, P2.5
(C) P3.0, P3.1 (D) None of the other options
62 | Microcontrollers and Applications
Answers of Multiple Choice Questions
1:B, 2:A, 3:B, 4:B, 5:B, 6:A, 7:D, 8:A, 9:A, 10:B, 11:A, 12:B, 13:C, 14:D, 15:B, 16:B, 17:C,
18:D, 19:C, 20:C, 21:D, 22:D, 23:B, 24:C, 25:A
Numerical Problems
NQ1. Find out the minimum time for which the reset pin be activated to reset the 8051 chip with
original Intel design having a crystal of frequency 12MHz connected to it.
NQ2. Determine the maximum size of the stack of 8051 with the requirement that the stack does
not interfere with the register banks.
NQ3. Consider the list file shown in Example 2.4. If the label “L3” was associated with the
statement “MOV TEMP, A” at line 10, what will be value be stored at 000E to have the correct
jump offset?
Microcontrollers and Applications | 63
NQ4. A program executes the instructions
ADD A, R1
ADD A, R2
If the initial contents of A, R1 and R2 are 100, 200 and 215 in decimal, compute the content
of A register after executing the two instructions.
NQ5. In NQ4 if the instruction “ADD A, R2” is modified to “ADDC A, R2”, compute the content
of the A register.
Answers of Numerical Problems
1: 2 μS, 2: 80 bytes, 3: 0FAH (decimal –6), 4: 3, 5: 4
KNOW MORE
The 8051 was the very first microcontroller from the Intel; the brain child of Robert Noyce,
Gordon Moore and Andy Grove. The instruction set of the 8051 was devised by John H. Wharton.
The 8051 is the first CPU on-a-chip that provided bit manipulation. Another very important feature
of the 8051 is the usage of Register Banks, which has been followed later by many of the advanced
processors, such as ARM. It helps is realizing Context Switching. Context Switching refers to the
process of changing the executing process to another one. For this change over, all the registers of
the CPU need to be saved first. After that, the CPU suspends the execution of current process and
starts executing another one. This is particularly true for interrupts. Occurrence of an interrupt
needs saving all registers, so that the processing can be resumed later. With the availability of
register banks, if the interrupt routine uses a new set of registers, saving and restoration of registers
are not necessary. This saves time in context switching.
64 | Microcontrollers and Applications
Dynamic QR Code for Further Reading
1. S. Chattopadhyay, SWAYAM/NPTEL course on “Microprocessors
and Microcontrollers”.
3
d
Instruction Set and
Programming
UNIT SPECIFICS
Through this unit, the following concepts have been elaborated:
Various addressing modes and machine instructions available in the 8051;
Assembly and C language programming for the 8051;
Developing complete programs for the 8051;
Program debugging strategies;
Timers and counters for the 8051;
Interrupt concepts in the 8051;
Serial communication facility of the 8051.
The discussion in the unit is to give the details of the 8051 instruction set and programming,
timers, interrupts and serial communication. This is the most important unit, as far as the software
development part is concerned. It highlights the ways in which the operands can be specified in the
instructions. High-level programming in C language has also been introduced. It has been assumed
that the reader has gone through the previous units of this book and has got an understanding of
the instruction execution process. A basic background of programming is essential for this unit. A
good number of examples have been included to explain the concepts, wherever needed.
A large number of multiple choice questions, relevant for the topics discussed in this unit, have
been provided with their answers. Apart from that, subjective questions of short and long answer
type have been included. A list of tentative practical problems has been given. A list of references
and suggested readings will help the readers to get more details. The section “Know More” has
been carefully designed so that the supplementary information provided in this part becomes
beneficial for the users of the book. This section mainly highlights the initial activity, the history of
the development of 8051 and some features of the 8051 instruction set that have been carried
forward to many advanced processors.
RATIONALE
This unit on the 8051 instruction set and programming provides a detailed view of the machine
instructions supported and their utilization in developing programs to solve computational and
interfacing problems. The programs may be written in the assembly language or in some high-level
language, like C. However, for a system designer, it is essential to understand the assembly
66 | Microcontrollers and Applications
language in order to check and debug the program logic at machine level. The unit has started with
the addressing modes supported by the 8051. It specifies the ways in which an operand could be
referred to in an instruction. The operand may be a constant, a register, a memory location whose
address is specified directly or indirectly. The instructions of the 8051 could be classified into
several categories, such as, data transfer, arithmetic and logic computations, branching etc. Each
of the categories has been discussed in detail by enumerating all the instructions belonging to it,
along with their applications. Complete assembly language programs have been included to
enumerate the usage of instructions in program logic. The programs can also be written in high-
level languages like C. However, suitable data types are needed to be included. The C programs
can access the machine registers, ports etc. For problems with complex computational logic, it may
be easier to write in C, rather than assembly language. To detect the logical bugs in a program,
the debuggers are used. A debugger can help in executing a program line-by-line, stop at some
predefined breakpoints, check/modify contents of registers and/or memory locations etc. Another
important programming aspect for the 8051 is using its timers and counters. As the 8051 is used in
many real-time systems, usage of hardware timers is often a requirement. The 8051 may be needed
to be informed about occurrence of special events, commonly known as interrupts. The 8051
supports different types of interrupts and the programmer needs to be familiar with the development
of corresponding service routines. The 8051 supports serial communication of data to devices that
does not support 8-bit parallel communication, due to various reasons. Thus, this unit gives a
complete view of program development techniques for the 8051, usage of its timers, interrupts and
serial communication features.
PRE-REQUISITES
Electronics: Unit 1, 2 of the book
UNIT OUTCOMES
List of outcomes of this unit is as follows:
U3-O1: State the addressing modes of the 8051
U3-O2: List the operands permitted in different addressing modes
U3-O3: List the data transfer instructions
U3-O4: State the usage of arithmetic and logic instructions
U3-O5: State the branching instructions
U3-O6: Distinguish between absolute and relative branching
U3-O7: Write assembly and C programs for problems like searching, sorting, computation, I/O
U3-O8: List the features of debuggers
U3-O9: Program timers and counters of the 8051
U3-O10: Write service routines for interrupts in the 8051
Microcontrollers and Applications | 67
U3-O11: Write program code to transmit and receive data serially in the 8051
68 | Microcontrollers and Applications
3.1 Introduction
The 8051 processor supports a large number of instructions. The instructions are of size 1-
byte, 2-bytes or 3-bytes. Out of a total of 111 instructions supported by the 8051, 49 are single-byte
instructions, while there are 45 two-byte and 17 three-byte instructions. All variants of the 8051
support the same instruction set. The instruction set is particularly optimized for 8-bit operations.
Each instruction has an opcode part (also called the mnemonic) that identifies the action to be
performed by the CPU. The action may necessitate zero/one/two operands to be used in the
operation. Typical actions include the movement of data across the registers and memory locations,
arithmetic and logical operations, controlling I/O devices via the ports, byte- and bit-level
manipulations. The 8051 processor allows flexibilities in the form in which the operand addresses
could be specified by the programmer. These alternatives are classified as the addressing modes
for the operands. Typically, an operand may be a register, some memory location, an immediate
value etc.
With the availability of compilers for high-level languages, it is possible to write programs
in those languages, thus bypassing the assembly level programming altogether. However, for
debugging purposes, a designer may need to check the happenings at a much deeper level, may be
at the machine code level. The machine code has direct correspondence with the assembly language
statements – not the high-level one. Thus, the understanding of the instruction set of the processor
is essential for the microcontroller based system designers. It may be noted that most of the IDEs
possess a disassembler tool that can give back the assembly language program from the machine
code in program memory.
Microcontrollers and Applications | 69
3.2.1 Immediate Addressing Mode
As the name suggests, in this mode, the operand is available to the CPU as soon as the
instruction has been fetched. The operand is present along with the instruction itself, no further
action is needed to get it. Naturally, the operand has to be a constant value. In most of the
assemblers, the constant value has to be preceded by a ‘#’ character. The following are a few
examples of the usage of immediate addressing mode.
It may be noted that the DPTR is a 16-bit register which can also be considered as two 8-bit
registers, DPH and DPL. The last instruction “MOV DPTR, #9A23H” is equivalent to the
following two instructions, taken together.
70 | Microcontrollers and Applications
3.2.3 Direct Addressing Mode
In direct addressing mode, the instruction contains the address of the operand which is
actually stored at a memory location. The mode could be used to specify the on-chip RAM locations
as the operands. Following are a few such examples.
MOV R5, 45H ; R5 gets the content of the RAM location 45H
MOV 55H, R2 ; RAM location 55H gets the content of R2
MOV 10H, 20H ; RAM location 10H gets the content of RAM location 20H
It may be noted that the specification of the operand in direct addressing mode is similar
to the immediate operand, excepting the ‘#’ character at the beginning. This should be followed
carefully by the programmer. The last example, noted above, has both the operands specified using
direct addressing mode. This provides a mechanism to implement data movement between the CPU
registers. For example, to move the content of the register R2 to the register R5 of Bank-0, the
instruction “MOV 5, 2” could be used. As noted earlier, another probable instruction for this,
“MOV R5, R2” using register addressing for both the operands, is invalid.
The registers R0 and R1 are used to index into the on-chip RAM. Similarly, to access off-chip
RAM, the DPTR register can be used for indexing. For this, the MOVX instruction could be used,
as shown next.
MOVX A, @DPTR ; A gets the content of external RAM location pointed to by DPTR
Depending upon the addressing mode used to specify the destination and the source,
several subvariants are possible.
(a) Accumulator A as destination. Here, any of the available addressing modes can be
used to specify the source, as shown in Table 3.1.
(b) Accumulator A as source. This is similar to the previous case. However, the
destination operand can only be from either of the following modes – register, direct
or register indirect. Some examples have been shown in Table 3.2.
72 | Microcontrollers and Applications
Table 3.2: MOV with A as source
Addressing Mode Format Example Meaning
Register MOV Rn, A MOV R2, A R2 = Content of A
Direct MOV direct, A MOV 42H, A RAM[42H] = A
Indirect MOV @Ri, A MOV @R0, A RAM[(R0)] = A
(c) Bank register as destination. Any of the registers R0-R7 in the current bank could be
used as the destination. The source operand may be an immediate one, the
Accumulator or a memory address. The cases have been shown in Table 3.3.
(d) Direct memory address as destination. With the destination operand in direct
addressing mode, the source may be of any other mode including direct addressing.
Table 3.4 shows the cases individually.
(e) Indirect memory address as destination. The registers R0 and R1 could be used as
pointer for the destination address of MOV instruction. Table 3.5 shows the
alternatives for the source operand.
Microcontrollers and Applications | 73
(f) Bit operands. MOV instruction can also be used to copy one bit to another. Following
are a few examples. The addressing mode of the operands is bit direct addressing.
(g) 16-bit data movement. The MOV instruction works for 16-bit data as well. One of the
very important 16-bit registers in the 8051 CPU is DPTR which can be used by the
programmer to access external memory. The DPTR register can be initialized as
follows.
2. MOVC: This instruction is used to move a code byte from on-chip ROM to the A register.
The instruction is typically utilized to access on-chip lookup tables in programs. There are
two variants of this instruction depending upon the 16-bit register holding the base address
of the table. Either DPTR or PC can be used to hold the base value. To index into the table,
the offset of the data element has to be in A. The data is copied into A.
MOVC A, @A+DPTR
To use this instruction, the DPTR should be initialized to the base value.
Example 3.1: The first ten prime numbers (indexed as 0, 1, ... 9) are 2, 3, 5, 7, 11, 13,
17, 19, 23, 29. If these are stored in the ROM starting at location 200H and the register
R3 contains the index of the prime we are looking for, the following code fragment using
the instruction “MOVC A, @A +DPTR” could be used to get the prime in A register.
MOV DPTR, #200H ; DPTR holds the base
MOV A, R3 ; A contains the index
MOVC A, @A+DPTR ; A contains the prime
ORG 200H
PRIME DB 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ; The lookup table
(b) PC as base register. Sometimes, instead of keeping the table away from the program
code, the programmer may find it more logical to keep it immediately following the
74 | Microcontrollers and Applications
code. As code is accessed via the Program Counter (PC), in such cases, it may be
advantageous to use the PC as the base. The offset is as usual contained in A. The
format for the instruction is “MOVC A, @A+PC”.
Example 3.2: Example 3.1, when rewritten following this principle will be as follows.
Here, when the CPU is executing the instruction “MOVC A, @A+PC”, the PC is already
pointing to the next instruction RET which is of size 1 byte. Thus, to reach the proper
offset, the register A has been incremented by 1, beforehand.
MOV A, R3 ; A contains the index
INC A ; Adjust offset
MOVC A, @A+PC ; A contains the prime
RET
PRIME DB 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ; The lookup table
3. MOVX: The instruction can be used to transfer data between the external memory and A
register. Both 16- and 8-bit addresses can be mentioned for the external memory. For 16-
bit address, the DPTR register is used, while the registers R0 and R1 can be used to provide
8-bit address.
(a) Address by DPTR. The following instructions could be used for this purpose.
Microcontrollers and Applications | 75
L1: INC DPTR ; DPTR points to next prime
DJNZ R3, NEXT ; Decrement counter, get next
ORG 2000H
PRIME DB 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ; The lookup table
4. PUSH and POP: The PUSH instruction is used to copy one byte operand to the on-chip
RAM location pointed to by the stack pointer (SP). The SP register is incremented by 1.
The operand can be specified using only the direct addressing mode. Typical example of
PUSH is as follows, which stores the content of A register (memory address 0E0H) to stack
memory location 33H, assuming that the current value of SP is 32. The SP register is
incremented to 33H.
PUSH 0E0H
Instructions, such as, “PUSH A”, “PUSH @R0”, “PUSH R2” are invalid.
On the other hand, the POP instruction copies the content from top of stack
(pointed to by SP) to the direct operand address mentioned in the instruction. For example,
with SP having the value 33H, the instruction “POP 0E0H” will copy the of RAM location
33H to A register. The stack pointer SP will be decremented to 32H.
5. XCH and XCHD: The XCH instruction swaps the content of A register with a source byte
mentioned as an operand. The generic instruction is of the format “XCH <byte>”. The
addressing modes supported for the operand along with examples have been noted in Table
3.6.
Table 3.6: XCH and XCHD instructions
Addressing
Format Example Meaning
Mode
XCH A, Rn XCH A, R1 Contents of R1 and A exchanged
Register
XCHD A, Rn XCHD A, R1 Lower nibbles of R1 and A exchanged
Contents of RAM[(R0)] and A
Indirect XCH A, @Ri XCH A, @R0
exchanged
Contents of RAM[40H] and A
Direct XCH A, direct XCH A, 40H
exchanged
The XCHD (exchange digit) is similar to the XCH with the exception that only the lower
nibbles (lower order 4 bits) of the source byte and A register get exchanged. The higher
order nibbles remain unchanged. For example, if A = 45H and R1 = 7AH, “XCHD A, R1”
will convert A to 4AH and R1 to 75H.
76 | Microcontrollers and Applications
3.3.2 Branching Instructions
The 8051 CPU generally works by fetching the instructions serially from program memory.
The next instruction to be executed is pointed to by the register PC. However, depending upon the
logic of the program, this straight-line sequence often needs to be modified to create the facilities
like branching to some other sequence, creating a loop structure or executing a subprogram. In the
following, discussion has been carried out by grouping the relevant instructions into three
categories – unconditional branching, conditional branching, subprogram call/return.
1. Unconditional branching. There are three instructions in this category – LJMP, AJMP and
SJMP. Out of these, LJMP is a 3-byte instruction, while the other two are 2 byte wide.
As the address part specifies 16 bits, the branch target can be anywhere within the 64k
address space of the 8051.
AJMP: The absolute jump is a 2-byte instruction with the following syntax.
As the PC is 16-bit wide, the 11-bit address part is used to replace only the lower-order
11 bits of the PC. The higher-order 5 bits remain unaltered. Thus, the branch target must
be within the 2k range of the current PC location.
SJMP: The short jump is also a two-byte instruction, however, the second byte provides
the distance (called offset) of the branch target from the current PC value. The format
of the instruction is as follows.
SJMP <8-bit offset>
After fetching the SJMP instruction, the content of PC is equal to the address of the next
memory location. To execute SJMP, the offset part is added to the PC. Now, if the offset
is a positive number, it implies a forward jump. If the offset is negative, it is a backward
jump. As the offset is an 8-bit value, the target must be within a distance of -128 bytes
to +127 bytes. This type of limited branching is also known as relative branch. While
translating an SJMP instruction to machine code, the assembler computes this distance
and keeps as the second byte of the translated instruction. For example, consider the
following code fragment.
…
Microcontrollers and Applications | 77
L1: MOV R1, #10
MOV R2, #20
NOP
SJMP L1
Here the first two MOV instructions are each of 2 bytes, NOP is of 1 byte and SJMP is
of 2 bytes. Thus, after the SJMP instruction has been fetched, the difference of the
address location represented by L1 from the current PC value will be -7 (0F9H). It may
be noted that this offset of -7 is independent of the location from which the entire
program has been loaded. This type of relative addressing makes program code
amenable to relocation to any part of the memory without any changes in the code itself.
Apart from SJMP, all conditional branching instructions in the 8051 are also relative in
nature.
2. Conditional Branching. These instructions modify the PC value with the jump target if the
specified condition is met. All conditional branches are relative to the PC, similar to SJMP.
The following are the variants available.
Out of all the instructions noted in Table 3.7, the JBC is a special one which also clears
the bit to zero.
CJNE: This instruction, compare and jump if not equal, compares between a source
byte and a destination byte. The carry flag (CY) gets set to 1 if the destination is less
than the source and reset otherwise. The format of the instruction is as follows.
78 | Microcontrollers and Applications
Table 3.8: CJNE instructions
Addressing
Format Example Meaning
Mode
CJNE A, #data,
Immediate CJNE A, #45, L1 Jump to L1 if A ≠45
target
CJNE A, direct,
Direct CJNE A, 42H, L1 Jump to L1 if A ≠ RAM[42H]
target
CJNE Rn, #data,
Register CJNE R1, #45, L1 Jump to L1 if R1 ≠45
target
CJNE @Ri,
Indirect CJNE @R1, #45, L1 Jump to L1 if RAM[(R1)] ≠45
#data, target
Example 3.4: The CJNE instruction can be used to implement some program logic that
repeats a set of activities till some internal or external condition is met. For example, the
following program reads continually the content of port P2. If the value read is less than
100, it is output to port P1. If the value is more than 100, it is output to port P0. If the
value is exactly equal to 100, the program proceeds to the instruction labelled NEXT. It
is assumed that the port P2 has been already configured as input.
L0: MOV A, P2 ; Read P2 into A
CJNE A, 100, L1 ; If A = 100, jump to NEXT
SJMP NEXT ;
L1: JNC L2 ; If A > 100
MOV P0, A ; Output to P0
SJMP L0 ; Read next input
L2: MOV P1, A ; A < 100, Output to P1
SJMP L0 ; Read next input
NEXT:
DJNZ: The instruction, decrement and jump if not zero, decrements a specified byte
and if the result is nonzero, control branches to the mentioned target address. A
speciality of the instruction is that, none of the status flags are affected. The format of
the instruction is as follows.
Table 3.9 shows the addressing mode combinations that are permissible for specifying
the DJNZ instruction.
Microcontrollers and Applications | 79
Example 3.5: The DJNZ instruction is typically used to implement loop structures in
the program. Any of the general purpose registers/memory locations can be used as a
counter. With each iteration of the loop-body, the counter may is decremented by 1,
till the counter value becomes zero. For example, in the following code fragment, the
register R3 has been assumed to contain a counter value. In the body of the loop, the
input value from port P0 has been copied into the port P1 as output. It is assumed that
the port P0 has been already configured as input.
L0: MOV A, P0 ; Read P0 into A
MOV P1, A ; Output to P1
DJNZ R3, L0 ; Decrement counter and
; repeat if the counter R3 is
; nonzero
80 | Microcontrollers and Applications
Similar to the unconditional branch instructions, the 8051 supports two
subprogram call instructions, namely LCALL and ACALL. A basic difference between the
branch and the call instructions is that unlike branch, after the subprogram has been
executed, control returns to the instruction immediately following the call instruction. For
this, the return address is saved onto the stack. Any subprogram ends with a RET
instruction which causes the PC to be loaded with the address available at the top of the
stack.
Assuming that the LCALL instruction starts at memory location 1000H, the next
instruction will be at 1003H. If the SP is at 32H, the return address 1003H is stored in
RAM locations 33H and 34H. The new SP value becomes 34H. The 16-bit address
specified in the instruction is copied into the PC and thus the control jumps to the
subprogram.
The 11 least-significant bits of PC is replaced with the 11-bit address to jump to the
subprogram. The 16-bit return address is saved onto the stack and SP is incremented by
two. As in AJMP, ACALL restricts the target to be within 2k address range from the
current PC.
RET and RETI: Both RET and RETI are single byte instructions, consisting of only
the mnemonic. The RET instruction is used as the last instruction of a subprogram that
makes the execution to be restarted from the instruction following the last
LCALL/ACALL instruction. Contents from the top two bytes are popped from the stack
and loaded into the PC register. The SP is decremented by two. The RETI instruction is
used in the subprograms corresponding to interrupt service routines. On occurrence of
an interrupt, similar to subprogram call, the control branches to a subprogram, decided
beforehand. Before that, the return address is saved onto stack, similar to
LCALL/ACALL. As in RET, RETI also restores the content of PC from the stack. Apart
from that, RETI also restores the interrupt logic to accept any additional interrupts. If
any interrupt has been pending before RETI, corresponding service routine is taken up
for execution only after executing one instruction at the return address.
Microcontrollers and Applications | 81
Example 3.6: Let us consider a program that has got some light-emitting diodes
(LEDs) connected to Port P1 of the 8051. It makes all the LEDs to blink continually.
For this, the program first outputs 00H to the port and then 0FFH after a certain delay.
The process is repeated continually for the blinking effect. The delay is designed as
a subprogram called from the main program.
L1: MOV A, #00H ; Set 00H in A
MOV P1, A ; Output to P1
LCALL DELAY_RTN ; Call Delay Routine
MOV A, #0FFH ; Set 0FFH in A
MOV P1, A ; Output to P1
LCALL DELAY_RTN ; Call Delay Routine
SJMP L1 ; Repeat for ever
DELAY_RTN: MOV R3, #0FFH ; R3 used as counter
L2: DJNZ R3, L2 ; Loop if R3 ≠ 0
RET ; Return from subprogarm
1. Arithmetic instructions. Several arithmetic operations are supported by the 8051. These
include addition (ADD, ADDC, DA), subtraction (SUBB), multiplication (MUL) and
division (DIV).
ADD, ADDC, DA: These instructions work with 8-bit data. Both unsigned and signed
arithmetic could be done. For the ADD instruction, the first operand and the destination
are always the accumulator (A register). The second operand is a byte, as shown next.
The source byte can be specified using different addressing modes. Table 3.10 shows
various cases with examples.
82 | Microcontrollers and Applications
Table 3.10: ADD with different addressing modes
Addressing Mode Format Example Meaning
Register ADD A, Rn ADD A, R2 A = A + R2
Immediate ADD A, #data ADD A, #20H A = A + 20H
Direct ADD A, direct ADD A, 5 A = A + RAM[5]
Indirect ADD A, @Ri ADD A, @R0 A = A + RAM[(R0)]
The operation affects the status flags carry (CY), auxiliary carry (AC) and overflow
(OV). The addition may be a signed operation or an unsigned operation. The unsigned
operation has operands and results in the range of 00H to 0FFH. For a result beyond
0FFH (255 in decimal), the CY flag becomes 1, indicating the fact. For signed operation,
the valid operands and results are in the range of -128 to +127. The overflow flag (OV)
indicates if the result is beyond this range.
The ADDC instruction stands for “Add with carry”. The instruction is of the
following format.
After executing the instruction, the content of A register gets modified to A + <source
byte> + CY. The source byte may be specified using different addressing modes,
similar to Table 3.10.
DA A
A decimal number when converted to the BCD format has each digit coded as a 4-bit
binary number. For example, the number 45 in decimal, when converted to 8-bit binary
representation will have it represented as 00101101. The same number when converted
to BCD will be 01000101, with the most significant 4 bits representing the digit 4 and
the least significant 4 bits representing 5. Naturally, if two BCD numbers are added
using the ADD instruction of 8051, the result will need further refinement for
correction. For example, addition of BCD numbers 45 (01000101) and 35 (00110101)
results in the bit pattern 01111010 as the content of the accumulator. Execution of “DA
A” instruction on this, results into the decimal number 80 coded into BCD as 10000000
in the accumulator.
Microcontrollers and Applications | 83
Example 3.7: Let us consider a set of 10 numbers stored from RAM location 35H
onwards. The following program will add those numbers and store the result at
memory location 50H.
L1: MOV R0, #35H ; Set memory pointer in R0
MOV R3, #10 ; Set counter in R3
CLR A ; Clear A
CLR C ; Clear CY
NEXT: ADDC A, @R0 ; Add next number
DJNZ R3, NEXT ; All numbers added?
MOV 50H, A ; Store result at 50H
Example 3.8: In Example 3.7, if the numbers are in BCD format, the following
program will add those numbers and store the result at memory location 50H. If the
result is more than 99, location 51H will have the third most significant digit. It is
assumed that the sum is less than 1000.
L1: MOV R0, #35H ; Set memory pointer in R0
MOV R3, #10 ; Set counter in R3
CLR A ; Clear A
CLR R4 ; R4 holds the 3rd digit
NEXT: ADD A, @R0 ; Add next number
DA A ; Adjust for BCD
JNC L1 ; If CY = 0, do not change R4
INC R4 ; Increase 3rd digit
DJNZ R3, NEXT ; All numbers added?
MOV 50H, A ; Store result at 50H
MOV 51H, R4 ; Store result at 51H
SUBB: This instruction is used to perform subtraction operation. The format of the
instruction is as follows.
It subtracts the source byte and the carry flag (CY) from A register. It may be noted that
there is no simple SUB instruction without carry. Thus, while doing subtraction, it is
84 | Microcontrollers and Applications
implied that the carry flag be cleared beforehand. For example, the following code
fragment subtracts 29H from the accumulator.
CLR C
SUBB A, #29H
To execute the SUBB instruction, the operations carried out are as follows.
Example 3.9: Let us look into the process of subtraction followed in the 8051,
considering the operation of subtracting 22H from 25H with the carry assumed to be
reset.
25H = 00100101
22H = + 11011110 (2’s complement)
1 00000011
03H (0310) = 0 00000011 (Invert carry)
On the other hand, subtraction of 25H from 22H will proceed as follows.
22H = 00100010
22H = + 11011011 (2’s complement)
0 11111101
FDH (-310) = 1 11111101 (Invert carry)
MUL AB
For example, if A =10010 and B = 20010, after “MUL AB”, the result is 2000010 =
4E20H. The A register will now have 20H and B register 4EH. The MUL instruction
affects the carry (CY) and the overflow (OV) flags. The CY flag is always reset and the
OV flag is set to 1 if the result is more than 255.
Microcontrollers and Applications | 85
DIV: This instruction performs the operation of dividing the byte present in
accumulator by the byte in B register. The instruction is of the format noted next.
DIV AB
It should be ensured that the B register content is nonzero, else the result will be
undefined. After division, the quotient is made available in register A and remainder in
B. For example, if A = 4510 and B = 710, after executing “DIV AB”, the contents of A
and B registers will be 610 and 310, respectively. Execution of DIV clears the CY flag.
The OV flag is set if the instruction attempts to divide by zero, else reset.
Handling Overflows: In 8-bit signed arithmetic, the range of valid numbers is -128 to
+127. If at any point of time, result of a computation is beyond this range, the result is
erroneous and the 8051 indicates the error by setting the OV flag to 1. It is the
responsibility of the programmer to check the OV flag after the operation, wherever
necessary. The 8051 sets the OV flag in either of the two situations noted in the
following.
1. There is a carry from D6 to D7 but no carry from D7. The carry flag is zero in
this case. As there is a carry from D6 to D7, the result could not be contained in
7 bits. The carry generated at D6 position got absorbed at the D7 bit. Hence the
D7 bit of both the operands must have been zero, indicating positive numbers.
Whereas, in the result, the bit is 1 indicating a negative number. Hence an
overflow.
2. There is a carry from D7 but no carry from D6 to D7. In this case, both the
operands must have D7 = 1, indicating both as negative numbers. After the
operation, D7 must be zero, which means a positive number. Thus, it is also a
case of overflow.
2. Logic instructions. These instructions are useful for carrying out logical operations on the
operands. The Boolean operators supported are AND, OR, XOR and complement.
AND: The AND operation is performed using the ANL (AND logical) instruction. The
instruction has the following format.
A bit-by-bit ANDing of the dest-byte with the source-byte is performed and the result
is stored in the dest-byte. Table 3.11 shows the usage of ANL instruction in different
addressing modes.
86 | Microcontrollers and Applications
Table 3.11: ANL with different addressing modes
Addressing
Format Example Meaning
Mode
Register ANL A, Rn ANL A, R2 A = A AND R2
Immediate ANL A, #data ANL A, #20H A = A AND 20H
ANL A, direct ANL A, 5 A = A AND RAM[5]
Direct ANL direct, A ANL 5, A RAM[5] = RAM[5] AND A
ANL direct, #data ANL 35, #42H RAM[35] = RAM[35] AND 42H
Indirect ANL A, @Ri ANL A, @R0 A = A AND RAM[(R0)]
There is a special version of ANL instruction that works with bit operands. Here, the
destination is the carry flag (CY). The instruction has the format as follows.
ANL C, <source-bit>
Another variant can specify the invert of source-bit as operand, as shown next.
ANL C, /<source-bit>
Example 3.10: The following code fragment sets the location 50H to 0FFH if the
input port bits P2.2 is 1 and P2.5 is zero. Else, the location is set to 77H.
MOV 50H, #0FFH ; Set memory location 50H
MOV C, P2.2 ; Get bit P2.2 into CY
ANL C, /P2.5 ; AND with invert of P2.5
JNC L1 ;
MOV 50H, #77H ; Set memory location 50H
L1:
OR, XOR: Similar to AND, there are instructions to carry out the bit-by-bit operations
for OR and XOR. The addressing modes supported in these instructions are similar to
that for the ANL instruction. The corresponding instructions are ORL and XRL. Some
such examples are noted next.
ORL A, R2 ; A = A OR R2
XRL A, #20H ; A = A XOR 20H
Microcontrollers and Applications | 87
CPL: This is an instruction to complement the content of the accumulator. The 1’s
complement of the content is computed. The instruction is as follows.
CPL A
There is another variant of the instruction that works with bit operand. It complements
the specified bit. The instruction is of the following format.
CPL <bit>
For example, the instruction “CPL P1.5” will complement the port 1’s bit number 5.
Example 3.11: The following program fragment toggles the bits of the port P2
using the CPL instruction. The initial pattern put in port P2 sets alternate bits to 1’s
and 0’s. After that, the bits flip continually.
3. Rotate instructions. These instructions can be used to rotate the accumulator register A
towards left or right. There are four different instructions performing rotations – RR, RL,
RRC and RLC. In the following, each of these has been discussed in detail.
RR: The rotate right (RR) instruction rotates the content of accumulator right by one
bit position. All bits, starting with
MSB, are shifted right with the
LSB fed back to the MSB. It has
been shown in Fig 3.2. The format MSB LSB
of the instruction is as follows.
Fig 3.2: RR Instruction
RR A
88 | Microcontrollers and Applications
RL: It stands for rotate left (RL). The content of the accumulator is rotated left. The
bits are shifted left from LSB
towards MSB. The MSB is fed
back to the LSB. The operation
has been shown in Fig 3.3. The MSB LSB
format of the instruction is as
follows. Fig 3.3: RL Instruction
RL A
RRC A
RLC A
Microcontrollers and Applications | 89
Example 3.12: The following code fragment can be used to transfer the bits of the
accumulator serially through the bit 0 of port P1.
INC: This instruction increments the operand by 1. Unlike ADD instruction, it does not
affect any of the status flags. There are two variants of the INC instruction. One version
takes a byte as the operand, while the other one uses the 16-bit register DPTR. Different
addressing modes supported by the instruction have been noted in Table 3.12.
DEC: This instruction decrements the operand by 1. Unlike INC, the instruction does not
work for DPTR (though “DEC DPL” is supported). It also does not affect the status flags.
The remaining addressing modes supported by the instruction have been noted in Table
3.13.
90 | Microcontrollers and Applications
Table 3.13: DEC with different addressing modes
Addressing Mode Format Example Meaning
Accumulator DEC A DEC A A=A–1
Register DEC Rn DEC R4 R4 = R4 – 1
Direct DEC direct DEC 5 RAM[5] = RAM[5] – 1
Indirect DEC @Ri DEC @R0 RAM[(R0)] = RAM[(R0)] – 1
NOP: This is the No Operation instruction. The execution of this instruction has no effect
on any of CPU registers or memory locations. Only the program counter is incremented
to continue executing the next instruction. The instruction is used to introduce small delay
in the execution process of the program. The instruction has the format noted next.
NOP
SWAP: This is the swap instruction that can be used to swap the nibbles of the
accumulator register A. In the process, the bits D3-D0 of A gets exchanged with the bits
D7-D4. Format of the instruction is as follows.
SWAP A
Microcontrollers and Applications | 91
MOV TEMP, A ; Copy A into TEMP
MOV A, R1 ; Get previous number in A
CJNE A, TEMP, L3 ; A ≠ (TEMP), goto L3
SJMP L4 ; A = (TEMP), goto L4
L3: JC L4 ; A < (TEMP), goto L4
MOVX @DPTR, A ; A > (TEMP), exchange
MOV A, TEMP ; two locations
DEC DPL ;
MOVX @DPTR, A ;
INC DPL ;
L4: DJNZ R3, L2 ; Repeat until R3 is zero
DJNZ R2, L1 ; Repeat until R2 is zero
END
92 | Microcontrollers and Applications
Compared to the full C language, embedded C can be considered as a subset of it, primarily used
for microcontroller based system design. The programs need to be concerned about the limited
resources (memory, I/O ports etc.). Embedded C programs are generally complied using cross-
compilers that create files to be downloaded onto the microcontroller for execution. In the
following, discussion has been carried out enumerating the data types supported in embedded C
along with some example code fragments.
#include <reg51.h>
void main (void)
{
unsigned char m;
for (m = 0; m < 0x80; m++)
P2 = m;
}
Signed char: The signed character can represent values in the range –128 to +127, as it uses an 8-
bit representation. This is the default data type used in Embedded C. Thus, it is necessary to be
more specific in the programs in declaring variables of type “unsigned char”, if the values are in
the range 0 to 255.
Example 3.15: The following C language program adds 10 signed characters stored in an array
a. The result is put in the variable b.
#include <reg51.h>
void main (void)
{
signed char a[] = { ‐2, ‐5, 10, 20, ‐3, 1, ‐1, 45, 25, ‐6 };
signed char b = 0;
unsigned char j;
for (j = 0; j < 10; j++)
b += a[ j ];
}
Microcontrollers and Applications | 93
Unsigned int: The unsigned integer can represent numbers in the range 0 to 65535 (0FFFFH). The
8051 uses the 16-bit numbers for specific applications, such as, memory address, counter values
etc. As all arithmetic and logic operations are performed on 8-bit data, the programmer should be
careful in declaring variables of this data type. The memory locations being 8-bit wide, an unsigned
integer variable will occupy two bytes. The access to those memory locations is also more complex
than a byte access. As a result, the hex-file code generated by the compiler may be much larger
than the same program using unsigned character variables only. It may be noted that the embedded
C compilers use signed integer as default. Thus, the unsigned keyword is very important to be
mentioned.
Example 3.16: The following C language program uses an unsigned integer variable to introduce
some delay in the execution so that the bits of the port P2 are flipped continually.
#include <reg51.h>
void main (void)
{
unsigned char m;
for (; ;) {
P2 = 0x55;
for (m = 0; m < 65530; m++);
P2 = 0xAA;
for (m = 0; m < 65530; m++);
}
}
Signed int: The signed integer is a 16-bit data type. Variables of this type can hold values in the
range –32768 to +32767. This is the default integer data type used by the compilers.
Single bit: There are two bit data types supported by the compilers of the 8051. One of them, bit
can refer to the bits in the bit-addressable RAM locations 20H-2FH. The other type sbit can be used
to refer to the individual bits of special function registers.
Example 3.17: The following C language program flips the bit-4 of port P1 continually.
#include <reg51.h>
sbit BIT4 = P1^4; // Bit‐4 of Port P1
void main (void)
{
unsigned char m;
94 | Microcontrollers and Applications
for (; ;) {
BIT4 = 0;
for (m = 0; m < 65530; m++);
BIT4 = 1;
for (m = 0; m < 65530; m++);
}
}
Special function register: This is a byte type data, written as sfr, corresponding to the special
function registers of the 8051. Unlike sbit, sfr data type corresponds to byte-size special function
registers.
Example 3.18: The following C language program flips the bits of the port P2 continually using
sfr data type.
sfr P2 = 0xA0;
void main (void)
{
unsigned char m;
for (; ;) {
P2 = 0x55;
for (m = 0; m < 65530; m++);
P2 = 0xAA;
for (m = 0; m < 65530; m++);
}
}
Example 3.19: The following assembly language program reads the ports P0 and P1 continually,
computes AND of the values read and outputs to the port P2.
ORG 0000H ;
MOV P0, #0FFH ; Set P0 as input
MOV P1, #0FFH ; Set P1 as input
L1: MOV A, P1 ; Read next value from P1
MOV R1, A ; Save value read in R1
MOV A, P0 ; Read next value from P0
ANL A, R1 ; Perform AND operation
MOV P2, A ; Output result to P2
SJMP L1 ; Continue
Microcontrollers and Applications | 95
#include <reg51.h>
unsigned char data1;
unsigned char data2;
unsigned char result;
void main (void)
{
while (1) {
data1 = P1;
data2 = P0;
result = data1 & data2;
P2 = result;
}
}
Example 3.20: The following assembly language program reads the port bits P0.0 and P1.4
continually, computes AND of the values read and outputs to the port P2.1.
ORG 0000H ;
MOV P0, #0FFH ; Set P0 as input
MOV P1, #0FFH ; Set P1 as input
L1: MOV A, P1 ; Read next value from P1
RR A ; Rotate right A 4 times
RR A
RR A
RR A
MOV R1, A ; Copy content of A in R1
MOV A, P0 ; Read next value from P0
ANL A, R1 ; Perform AND operation
RL A ; Rotate A left
MOV P2, A ; Output result to P2.1
SJMP L1 ; Continue
96 | Microcontrollers and Applications
#include <reg51.h>
bit data1 = P0.0;
bit data2 = P1.4;
bit result = P2.1;
void main (void)
{
while (1) {
result = data1 & data2;
}
}
1. Single Step. The technique allows executing one instruction at a time. After executing the
instruction, control is given back to the user to check for values of registers and memory
locations. The values could also be modified by the user before stepping into the execution
of the next instruction.
2. Breakpoint. The debugger can make the program execution to be suspended at some
specific lines of the source code. After setting a breakpoint at a source code line or a
subprogram, the program execution can be initiated. If the control reaches the breakpoint,
execution gets suspended and the user may check/modify the registers, memory locations
etc.
Most of the integrated development environments (IDEs) of the 8051 support debugging at both
assembly language and C program levels. The machine code is downloaded onto the development
board having the 8051 chip through some cable connected via the USB or serial communication
ports of the computer. The IDE executes the debugger which works by sending the commands to
and receiving the data from the 8051 via some on-chip monitor routine loaded separately into the
microcontroller.
Microcontrollers and Applications | 97
3.6 Programming Timers and Counters
Timers and counters are two important components in developing systems interacting with
the nature. Certain events are to be organized at some particular time instant. Accurate time delays
may need to be inserted between sequences of events etc. This necessitates the availability of
one/more high precision timers. Also, in many applications we need event counters. The occurrence
of events may be fed as digital pulses to the 8051 which is counted by the timer/counter module.
There are two timers in the 8051, named as Timer 0 and Timer 1. Both are 16-bit timers
that can be configured to work as 8-bit, 13-bit or 16-bit timers. The registers associated with the
operation of timers are as follows.
1. Timer registers. Each timer has got two 8-bit registers, THx and TLx, associated with it to hold
the 16-bit
time/ TH0 TL0
count. For
D15 D14 D13 D12 D11 D10 D9 D8 D7 D6 D5 D4 D3 D2 D1 D0
Timer 0,
registers (a)
are TH0 TH1 TL1
and TL0.
For Timer D15 D14 D13 D12 D11 D10 D9 D8 D7 D6 D5 D4 D3 D2 D1 D0
1, those
(b)
are TH1
Fig 3.6: Timer registers (a) Timer 0 (b) Timer 1
and TL1.
The register structure has been shown in Fig 3.6. Registers can be used in conjunction with
MOV instruction, similar to other registers. For example,
98 | Microcontrollers and Applications
2. Timer mode
register TMOD. Timer 0 Timer 1
This is an 8-bit
register GATE C/T M1 M0 GATE C/T M1 M0
controlling both
the timers. While Fig 3.7: TMOD register structure
the bits 0 to 3 of
the register control the mode of operation of Timer 0, the bits 4 to 7 are dedicated to the control
of Timer 1. The structure of TMOD register has been shown in Fig 3.7. Each part has the
following components.
M1, M0: These two bits determine Table 3.14: M1, M0 bit settings
the timer mode selection. Table M1 M0 Mode Operation
3.14 illustrates the mode settings. 0 0 0 13-bit timer/counter
The modes 1 and 2 are commonly
THx holds 8-bit count
used in applications and will be
TLx is a 5-bit prescalar
explored in the following.
0 1 1 16-bit timer/counter
C/T: The bit selects either timer 1 0 2 8-bit auto reload
operation or counter operation. THx holds reload value
C/T = 0 implies timer operation, TLx holds count
while C/T = 1 implies counter 1 1 3 Split timer
operation. For timer operation, the crystal is used to derive the clock source to provide
clock ticks to the timer. The timer frequency is set to 1/12th of the crystal frequency, as
shown in Fig 3.8. For example, if the crystal is of frequency 12 MHz, the timer will operate
at a frequency of 1 MHz. For most
of the 8051 based systems, the
crystal is of frequency 11.0592 XTAL 12 Clock for
MHz. This is primarily to match Oscillator Timer
the serial data transfer rate with
the then existing IBM PC. For this Fig 3.8: Derivation of Timer clock
crystal, the timer frequency is
921.6 kHz, resulting into the time period of 1.085 μSec. For C/T=1 (counter operation), the
count pulses are fed from T0 (P3.4) and T1 (P3.5) for Timer 0 and Timer 1, respectively.
GATE: This bit specifies the way in which the timer will be controlled. The starting and
stopping of timers can be controlled via both software and hardware means. Resetting the
GATE bit (GATE = 0) will ensure only software based control to start and stop the
corresponding timer. Setting the GATE bit (GATE = 1) provides combined software and
hardware control to start or stop the timer.
Microcontrollers and Applications | 99
The software control is achieved via the TR0 and TR1 bits in the Timer Control
register, TCON. The bits TR0 and TR1 can be set or reset to serve the purpose of
controlling the timers, as follows.
TCON register structure has been shown in Fig 3.9. The most significant four bits of TCON
are to
control the Timer control bits Interrupt control bits
timers
while the TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0
least
significant TFx: Timer x overflow flag, TRx: Timer x run control
four bits
IEx: External interrupt x edge flag, ITx: External interrupt x control
control the
x = 0, 1
external Fig 3.9: TCON register structure
interrupt
lines (that will be discussed in conjunction with interrupts). The bits TF0 and TF1 are timer
flags. The flag bit of a timer gets set when the corresponding timer rolls over from its
maximum value to zero. The TF bits can also be set/reset as follows.
As noted earlier, applications developed around the 8051 that use timer, utilize mostly mode 1 or
mode 2 of operation. In the following these modes have been discussed in detail.
1. Mode 1 timer operation. This is a 16-bit timer operation mode. The timer may be initialized to
any value between 0000H and FFFFH. The 16-bit value is loaded into the register pair TH-TL.
After loading the initial value, the timer is started by executing the instruction “SETB TR0” or
“SETB TR1” for Timer-0 or Timer-1, respectively. From this point onwards, the timer starts
incrementing
with each XTAL
clock tick. 12 TH TL TF
Osc.
After the Timer register Overflow
count has TR bit
reached Fig 3.11: Timer in Mode 1
FFFFH, at
the next clock tick, the value rolls over to zero and sets the corresponding TF bit of TCON
register to high. The timer operation in mode 1 has been illustrated in Fig 3.11. Assuming that
the crystal frequency is 11.0592 MHz, the timer will operate at a frequency of 921.6 kHz having
clock time period of 1.085 μS. Thus, if the initial value loaded in the timer is hexadecimal
XXYY, the overflow will occur after (FFFF – XXYY + 1) 1.085 μS. On the other hand, to
generate a time delay D, it is divided by 1.085 μS to get a count n. From this, (65536 – n) is
computed. The resulting value is converted into a 16-bit hexadecimal value xxyy. The value xx
is loaded in TH and yy into TL.
Example 3.21: Let us consider the problem of generating a square wave with 50% duty cycle
and ON/OFF periods of 10 mS each. The time delay of 10 mS will be generated using the Timer
0 in mode 1.
As per the discussion on initializing the timer, the value of n should be 10 ms 1.085
μS = 9217. Thus, the initial value of the timer will be 56319 (DBFFH). Hence the TH and the
TL registers should be loaded with DBH and FFH, respectively. The square wave will be
generated on P2.5. The assembly language program for the same is as follows.
ORG 0000H ;
CLR P2.5 ; Clear port bit P2.5
MOV TMOD, #01H ; Set Timer 0 in Mode 1
L1: MOV TL0, #0FFH ; Load TL
MOV TH0, #0DBH ; Load TH
CPL P2.5 ; Complement P2.5
Microcontrollers and Applications | 101
SETB TR0 ; Start timer
L2: JNB TF0, L2 ; Check roll over of TF0 flag
CLR TR0 ; Stop timer
CLR TF0 ; Clear timer flag
SJMP L1 ; Repeat
END
102 | Microcontrollers and Applications
initial timer value is loaded into the TH register, which is copied automatically to the TL
register initially, and later on at each roll over event. The programmer need not load the value
to TL explicitly, only clearing the TF flag after a roll over will restart the timer. The situation
has been explained in Fig 3.12, which is very much similar to Fig 3.11, excepting the reload
part. However, since the maximum count value is 255, Mode 2 is not very suitable for
generating large delays. In the following, Example 3.21 has been revisited with the ON/OFF
period of 20 μS.
Example 3.22: Let us consider the problem of generating a square wave with 50% duty cycle
and ON/OFF periods of 20 μS each. Timer 0 in mode 2 has been used to insert appropriate delay
in the waveform generation.
The value of n, in this case is should be 10 ms 1.085 μS = 19. Thus, the initial value
of the timer will be 237 (EDH). Hence the TH0 register should be loaded with EDH. In mode 2,
as soon as TH0 is loaded with the value, it is automatically copied into TL0. The assembly
language program for the same is as follows.
ORG 0000H ;
CLR P2.5 ; Clear port bit P2.5
MOV TMOD, #02H ; Set Timer 0 in Mode 2
MOV TH0, #0EDH ; Load TH0
L1: CPL P2.5 ; Complement P2.5
SETB TR0 ; Start timer
L2: JNB TF0, L2 ; Check roll over of TF0 flag
CLR TF0 ; Clear timer flag
SJMP L1 ; Repeat
END
The same program written in C will be as follows.
#include <reg51.h>
sbit p2_5 = P2^5;
void main (void)
{
TMOD = 0x02; // Timer 0, Mode 2
TH0 = 0xED; // Load TH0
while (1) {
p2_5 = ~p2_5; // Toggle P2.5
TR0 = 1; // Start timer
while (! TF0); // Wait for overflow
TF0 = 0; // Reset timer flag
}
}
Microcontrollers and Applications | 103
3.6.2 Counter Programming
The timers available in the 8051 can be used to count external pulses also. For this, the
timers need to be operated in the counter
mode by setting the corresponding C/T T0/T1 TH TL TF
bit of TMOD register to 1. The T0 input Timer register Overflow
pin (Pin 14) is used to feed the pulses to TR0/TR1 bit
be counted by Counter 0, while the T1 Fig 3.13: Counter in Mode 1
pin (Pin 15) is earmarked for Counter 1.
The counters do upcounting on
occurrence of pulses on T0 and T1. It T0/T1 TL TF
may be noted that the pins 14 and 15 are Overflow
multiplexed with Port 3 bits, P3.4 and TR0/TR1 bit Reload
P3.5, respectively. The operation of the TH
counters in Mode 1 and Mode 2,
counting external input pin events have Fig 3.14: Counter in Mode 2
been illustrated in Fig 3.13 and 3.14,
respectively.
Example 3.23: Consider the problem of counting pulses on T0 pin using Mode 2 counter
operation. The TH0 register is cleared, so that, whenever the count in TL0 exceeds 255 and it
rolls over, the TL0 register will be reloaded with zero from TH0. The TF0 flag will also be set.
The program outputs the current count available in TL0 to the port P1. The assembly language
code for the program is as follows.
ORG 0000H ;
MOV TMOD, #06H ; Set Counter 0 in Mode 2
SETB P3.4 ; Make T0 input line
MOV TH0, #0 ; Clear TH0
SETB TR0 ; Start counter
L1: MOV A,TL0 ; Get TL0 content in A
MOV P1, A ; Output to Port 1
JNB TF0, L1 ; Continue till roll over
CLR TF0 ; Clear timer flag
The SJMP L1 ; Repeat
END
same program written in C will be as follows.
#include <reg51.h>
sbit p3_4 = P3^4;
104 | Microcontrollers and Applications
void main (void)
{
TMOD = 0x06; // Counter 0, Mode 2
TH0 = 0; // Clear TH0
p3_4 = 1; // Configure T0 in input mode
TR0 = 1; // Start counter
while (1) {
P1 = TL0; // Output TL0 count to Port 1
if ( TF0 ) TF0 = 0; // If roll over, reset TF0
}
}
The 8051 programming techniques discussed so far, develop program logic in which the
processor controls the flow of execution. For example, if a program is supposed to do a data transfer
from an input device to a memory buffer space, it has to check continually whether the device is
ready for data transfer. The transfer can take place only when the device is ready. However, the
processor needs to check the status in a loop. The technique is often known as polling. A major
problem with polling is the wastage of processor time in busy wait state. The input devices are
mostly electromechanical in nature and are often operated by human operators. This increases the
wastage of computing power further. The situation is aggravated further if a number of devices are
connected to the 8051 and the processor may check the status of those devices one by one, in a
circular fashion.
A better technique for data transfer uses the concept of interrupts. In this, whenever a
device is ready for data transfer, it informs the processor about it. The processor, busy in some
other execution sequence, now suspends the current operation and branches to a special program
fragment to take care of the data transfer operation. Once the data transfer is over, the processor
resumes the suspended program. This avoids the wastage of processor time in busy-wait cycle.
Microcontrollers and Applications | 105
the routine to service the interrupt, interaction part is equivalent to the actual interrupt service
and restarting the reading process is like resuming the original program being executed.
The 8051 processor supports six interrupts, as follows. Table 3.15 summarizes the types
of interrupts, the vector address, pin number etc.
1. Reset. This is the Pin 9 of the chip. Whenever the input is high, the 8051 gets a Reset interrupt
and the control branches to ROM address 0000H.
2. Timers: The two timers present in the 8051 will generate interrupts – Timer 0 interrupt and
Timer 1 interrupt, when the corresponding timer rolls over and the TF bit gets set. Control
branches to address 000BH and 001BH, respectively for the Timer 0 and Timer 1 interrupts.
3. INT0, INT1: These are also called external interrupts. The corresponding pins are 12
(multiplexed with P3.2) and 13 (multiplexed with P3.3). The memory address for INT0 is
0003H, while for INT1, it is 0013H.
4. Serial Communication: This is an interrupt activated on receiving/transmitting a character
serially by the 8051.
From Table 3.15 it may be noted that for interrupts like INT0, INT1, Timers etc. the
addresses are separated by just eight bytes. Table 3.15: Interrupts in the 8051
Thus, the corresponding service routines have Interrupt ROM Pin No.
space of eight bytes only. If the interrupt address
service routine is more than eight bytes long, Reset 0000H 9
an LJMP instruction can be used to jump to a INT0 0003H 12 (P3.2)
memory address having an empty chunk of Timer 0 interrupt 000BH
memory space. The situation is further tight INT1 0013H 13 (P3.3)
for the Reset – only three bytes are free for its Timer 1 interrupt 001BH
service routine that can accommodate only an Serial communication 0023H
LJMP instruction.
106 | Microcontrollers and Applications
3.7.2 Interrupt Enable Register
By default, all interrupts are disabled on resetting the 8051. Thus, the 8051 will not respond
to any of the interrupts,
till those are enabled (MSB) (LSB)
specifically via EA ‐ ET2 ES ET1 EX1 ET0 EX0
software. The
enable/disable status of Fig 3.15: Interrupt Enable (IE) register structure
the 8051 is controlled
by the setting of the Interrupt Enable (IE) register. The register structure has been shown in Fig
3.15. The individual bit settings are as follows.
EA: Setting EA = 0 disables all interrupts. On the other hand, if EA = 1, the status of individual
interrupts are controlled by other bits of IE register as noted next.
ET2, ET1, ET0: Control the Timer interrupts. Out of these, ET2 is meaningful for the 8052 only,
as the 8051 does not have Timer 2. ET1and ET0 correspond to enabling of Timer 1 and Timer 0
interrupts, respectively. Setting the bit to 1 enables the relevant timer, setting to 0 disables the timer.
ES: Enables or disables the serial communication interrupt.
EX1, EX0: These bits correspond to the external interrupts INT1 and INT0. Setting EX1 to 1
enables INT1, resetting to 0 disables it. Same is the case with EX0 for INT0 interrupt.
For example, for the 8051, to enable the two timer interrupts and INT0 while keeping others
in a disabled mode, the IE register should be set to the bit pattern “10001011” using an instruction
like,
MOV IE, #10001011B
3.7.3 Timer Interrupts
The IE register can be programmed to enable the generation of interrupts when a particular
timer rolls over and the TF bit is set. Thus, after starting a timer, the 8051 need not wait checking
continually the status of the TF bit. Whenever the interrupt occurs, program control gets transferred
to the corresponding service routine address (000BH for Timer 0 and 001BH for Timer 1). It may
be noted that the Timer Flag TF0 and TF1 will automatically reset once the control jumps to the
corresponding Interrupt Service Routine.
Microcontrollers and Applications | 107
Example 3.25: Let us consider the problem of generating a square wave with 50% duty cycle
and ON/OFF periods of 20 μS each. Timer 0 in mode 2 has been used to insert appropriate delay
in the waveform generation. However, compared to the previous case, the timer will generate
interrupt whenever it rolls over and the corresponding service routine to complement P2.5 will
get executed. The assembly language program for the same is as follows.
ORG 0000H ;
LJMP MAIN ; Jump to MAIN, bypass IVT
ORG 000BH ; ISR for Timer 0
CPL P2.5 ; Complement port bit P2.5
RETI ; Return from ISR
ORG 0030H ; Main routine starts here
MAIN: MOV TMOD, #02H ; Set Timer 0 in Mode 2
MOV TH0, #0EDH ; Load TH0
MOV IE, #82H ; Enable Timer 0
SETB TR0 ; Start timer
L1: SJMP L1 ; Stay here
END
The last statement of the program has been made an infinite loop to demonstrate that the 8051
need not check the TF0 flag anymore. Instead of looping here, the program may proceed to other
computations also. The same program written in C will be as follows.
#include <reg51.h>
sbit p2_5 = P2^5;
void timer0 (void) interrupt 1
{
p2_5 = ~p2_5; // Complement P2.5
}
void main (void)
{
TMOD = 0x02; // Timer 0, Mode 2
TH0 = 0xED; // Load TH0
IE = 0x82H; // Enable Timer 0 interrupt
while (1); // Infinite loop
}
108 | Microcontrollers and Applications
3.7.4 External Interrupts
The 8051 has two pins, called INT0 and INT1 (multiplexed with port pins P3.2 and P3.3,
respectively). If these pins are activated, the operation of the 8051 gets interrupted. A generic
classification of interrupt
activation has been shown Interrupt
in Fig 3.16. An interrupt
may support triggering via Level‐triggered Edge‐triggered
one of the following
methods. Low‐level High‐level Rising edge Falling edge
1 1 1 1
Low Level: Interrupt is
triggered if the 0 0 0 0
corresponding pin is Fig 3.16: Triggering of generic interrupts
kept low for some time.
High Level: In this case, keeping the pin high for some time triggers the interrupt.
Rising Edge: Interrupt gets triggered if there is a low-to-high transition in the interrupt pin.
Falling Edge: Interrupt is triggered if there is a high-to-low transition in the interrupt pin.
The 8051 interrupts, INT0 and INT1, support two triggering modes – low-level and falling
edge. As noted in Fig 3.9, the lower nibble of the TCON register controls the interrupt triggering
modes. The bits IT0 (TCON.0) and IT1 (TCON.1) control the interrupt type and can be set/reset
by software. If the bit IT0 is set, INT0 will be triggered by a falling edge, if reset, it is low level
triggered. Similar is the case in bit IT1 for the interrupt INT1. For the falling edge triggering, the
occurrence of high-to-low pulse in INT0 is remembered in IE0 (TCON.1) flag bit. For IT1, it is
remembered in IE1 (TCON.3). These flags are cleared upon executing the corresponding RETI
instruction. However, it may be noted that the low-level of INT0 and INT1 are not remembered
internally. Thus, for the low-level interrupt to be sensed properly, it must be held low till the
beginning of the ISR but withdrawn before the RETI instruction in the ISR (to avoid sensing
multiple interrupts on the line). As a general rule, the low-level should be maintained for around
four machine cycles, but not more. For the edge-triggered interrupt sensing, the interrupt pin must
be held high for one machine cycle followed by low for at least one machine cycle.
Example 3.26: Let us consider the example in which a switch has been connected to the INT0
pin and an LED to port bit P2.0. If the switch is closed, a 0 value is sent to INT0. In the service
routine for the interrupt, the LED is turned ON. It remains ON for some small time, turns OFF
and control returns from the service routine.
ORG 0000H ;
LJMP MAIN ; Jump to MAIN, bypass IVT
ORG 0003H ; ISR for INT0
Microcontrollers and Applications | 109
SETB P2.0 ; Set port bit P2.0, LED ON
MOV R2, #0FFH ; R2 used as counter
L1: DJNZ R2, L1 ; Wait for some time
CLR P2.0 ; LED OFF
RETI ; Return from ISR
ORG 0030H ; Main routine starts here
MAIN: MOV IE, #81H ; Enable INT0
L2: SJMP L2 ; Wait in loop
END
#include <reg51.h>
sbit p2_0 = P2^0;
void external0 (void) interrupt 0
{
p2_0 = 1; // Complement P2.5
for (i = 0; i < 10000; i++);
p2_0 = 0;
}
void main (void)
{
IE = 0x81H; // Enable INT0 interrupt
while (1); // Infinite loop
}
If we are looking for falling edge triggering of INT0, in the MAIN routine, IT0 (TCON.0) bit be
set by executing the instruction “SETB TCON.0”.
110 | Microcontrollers and Applications
3.7.5 Interrupt Priorities
A very pertinent question about interrupts is to determine which interrupt will get serviced
first, if two or more interrupts have occurred together. Upon reset, the 8051 has the following
priority setting. INT0 has the highest priority, followed by Timer 0, INT1, Timer 1, Serial
Communication, in sequence. That is,
INT0 > Timer 0 > INT1 > Timer 1 > Serial Communication.
An individual interrupt can be assigned the highest priority by setting the corresponding
bit in the Interrupt Priority (IP) register. The structure of the IP register has been shown in Fig
3.17. The register is bit-addressable. The two most significant bits of the register are reserved. The
bit PT2 controls
priority of Timer 2 (MSB) (LSB)
interrupt in 8051, PS is ‐ PT2 PS PT1 PX1 PT0 PX0
for Serial interrupt,
PT1 and PT0 for Timer Fig 3.17: Interrupt Enable (IE) register structure
1 and Timer 0, PX1 and
PX0 correspond to the external interrupts INT1 and INT0, respectively. For example, if the bit PT1
is set to 1 while all others are 0 in IP, Timer 1 gets the highest priority among all. If multiple bits
are set in the IP register, all of them will have higher priorities than other interrupts, while within
them, the priority ordering will be as per the default priority. For example, if the bits PX1 and PT0
are set to 1, the interrupts INT1 and Timer 0 will have higher priority than others, while between
INT1 and Timer 0, Timer 0 interrupt will have more priority than INT1. It may be noted that if a
higher priority interrupt occurs while the service routine of a lower priority interrupt is being
executed, control will get transferred to the service routine of the higher priority interrupt.
A major problem with the bus-based parallel communication between the processor and
the devices is the requirement to run a large number of signal lines for connection. For applications
with limited size and requiring possibly less data transfer rate, serial bit-by-bit communication may
be sufficient. This reduces the pin count for the interface, as well. A serial communication takes
place between a transmitter and a receiver, both of which are devices having electronic interface
supporting transmission and/or reception. Serial communication can be classified into the following
categories.
Simplex Mode: Communication is always unidirectional between a master and a slave device.
Duplex Mode: Communication is bidirectional.
Half-duplex Mode: Communication is bidirectional, however, at any point of time, data is
transferred in one direction only.
Microcontrollers and Applications | 111
Serial communication can also be classified to be either synchronous or asynchronous in
nature. For synchronous communication, the transmitter and the receiver need to work on the same
clock signal, which may not be always feasible. If the transmitter and the receiver work on their
own clock signals, it is referred to as an asynchronous transmission. Asynchronous transmission is
preferable to synchronous transmission, however, needs a fixed protocol to be followed for faithful
communication. For transmission, every character is put into a frame structure. When there are no
data transmission, the line is at 1 (high). Beginning of a frame is identified by a 0-bit, called start
bit. The start bit is
followed by 8-bit D7 D0
ASCII code of the stop
1 start
0 1 0 0 0 0 1
character being bit bit
transmitted. After
that, the end of Transmission direction
frame is marked
by one/two 1 Fig 3.18: Frame structure for character ‘C’ (ASCII code 43H)
(high) bit(s),
called stop bit(s). The frame structure has been shown in Fig 3.18. Sometimes, a frame also contains
a parity bit. The parity may be even or odd. For even parity system, the parity bit is set/reset such
that the total number of 1’s in the character code along with the parity bit is even. On the other
hand, in odd-parity system, the total number of 1’s is odd. Inclusion of parity bit in the frame may
aid in detecting transmission error. During transmission, if one or any odd number of bits get
modified, the recomputed parity bit at receiver will not match with the received parity bit, flagging
an error. The rate of data transfer is stated as bps (bits per second). It is also called baud rate. For
serial communication, the transmitter and the receiver must agree upon the frame format, baud rate
etc.
For serial communication, the 8051 has two pins, called TxD (Transmit Data) and RxD
(Receive Data). The pins are multiplexed with the port 3 bits, P3.0 and P3.1, respectively. As a
result, the voltage levels supported are +5V for a 1 and 0V for a 0. It may be noted that the serial
communication standard RS232C has -3 to -25V for logic 1 and +3 to +25V for logic 0. Hence if
the 8051 has to follow this standard, some additional interfacing chip (such as, MAX232) has to be
used. Further discussion on this has been omitted for the sake of brevity.
112 | Microcontrollers and Applications
serial communication circuitry within the 8051 further divides this frequency further by 32 to drive
the Timer 1. Now, the TH1 register is loaded with the appropriate value, so that the timer pulses
(due to roll over) could be generated at appropriate time instants. These pulses are used for bit
timing. For example, assuming the crystal frequency to be 11.0592 MHz, as per the above
discussion, the clock signal fed to the Timer 1 has a frequency of 11.0592 12 32 = 28800
Hz. If the TH1 register is loaded with the value 0FDH (-3 in decimal), it will take three pulses to
roll over, setting the baud rate to 28800 3 = 9600. Some typical baud rates and their
corresponding TH1 register initialization values have been noted in Table 3.16. All calculations
assume the crystal frequency to be 11.0592 MHz. For a different crystal frequency, the TH1 values
could be determined, as explained previously.
The 8051 has two important registers associated with serial communication – SBUF and
SCON. Both the registers are 8-bit wide.
SBUF: The Serial Buffer register is responsible for transmitting and receiving characters for the
8051. For transmitting a character serially, the character has to be written into the SBUF register.
Once the character is written onto SBUF, it is put into a frame by adding the start and the stop
bits. The frame transmission through TxD pin initiates immediately. Similarly, when bits are
received by the 8051 via the RxD pin, the framing bits are removed and the character received
is put into the SBUF register. The user program can now read the SBUF register to get the
character. The SBUF register can be used in conjunction with MOV instruction as noted next.
SCON: The Serial Port Control register is responsible for determining the framing structure
and also to enable/disable transmission and reception. This is a bit-addressable register with
structure as shown
in Fig 3.19. The bits (MSB) (LSB)
have the following SM0 SM1 SM2 REN TB8 RB8 TI RI
meanings.
Fig 3.19: Serial Port Control (SCON) register structure
SM0, SM1: These
two bits determine the mode of serial transmission. Four alternative modes are supported –
Mode 0, Mode 1, Mode 2 and Mode 3. Out of these, only the Mode 1 is used extensively. For
Mode 1, SM0 and SM1 are set to 0 and 1, respectively. Hence, in our discussion, we shall
concentrate only on this mode. Mode 1 implies 8-bit data with one start bit and one stop bit in
Microcontrollers and Applications | 113
each frame. Thus, the frame size is 10 bits. The mode also allows various baud rate settings by
programming the TH1 register.
SM2: This bit is used for multiprocessor communication. For our discussion, the bit will always
be set to 0 to disable multiprocessor mode.
REN: This is called the Receive Enable bit. By default, the 8051 only transmits data via the
TxD line. If the programmer wants also to receive data serially through RxD pin, the REN bit
must be set to 1. Thus, by resetting the bit, user can block the reception of serial data by the
8051.
TB8, RB8: These bits are used mostly in Mode 2 and Mode 3 of communication. Thus, in our
discussion and also for most of the serial communication applications, the bits are reset to 0.
TI: The Transmit Interrupt bit is set to 1 by the 8051 after completing transmission of the 8-bit
character available in the SBUF register. It indicates that the 8051 is ready to transfer another
character. The TI flag bit is set at the beginning of sending the stop bit in the frame. The user
program can check this to determine whether to copy the next character to be transmitted to
SBUF.
RI: The Receive Interrupt bit is set when the 8051 has placed the received byte into the SBUF
register. It may be noted that the 8051 receives the frame serially, removes the start and the stop
bits from it and places the character into the SBUF register. The RI flag is set halfway through
the reception of the stop bit. Upon detecting the RI flag set, the user program should read the
character from the SBUF register, before it is lost.
To transmit characters serially, the 8051 first programs the Timer 1 in mode 2 (auto-reload)
and loads TH1 register appropriately for the required baud rate. The SCON register is programmed
in mode 1. The timer is started by setting the TR1 bit. The TI bit is cleared. To send a character, it
is written into the SBUF register. The TI flag is monitored continually to check the completion of
this character transmission. Once TI is found to be 1, the transfer of the character is complete. For
transmitting further characters, the TI flag is cleared and the next character is copied into the SBUF
register. The following example illustrates the serial transmission.
Example 3.27: Consider the problem of serially transmitting the character string “8051” at a
baud rate of 9600 using the serial mode 1. The assembly language program for the problem is as
follows.
114 | Microcontrollers and Applications
ORG 0000H ;
MOV TMOD, #20H ; Timer 1, Mode 2
MOV TH1, #0FDH ; Baud rate 9600
MOV SCON, #40H ; Mode 1, REN disabled
SETB TR1 ; Start Timer 1, auto‐reload
MOV A, # ‘8’ ; Load ‘8’ into A
ACALL SEND ; Transfer ‘8’
MOV A, # ‘0’ ; Load ‘0’ into A
ACALL SEND ; Transfer ‘0’
MOV A, # ‘5’ ; Load ‘5’ into A
ACALL SEND ; Transfer ‘5’
MOV A, # ‘1’ ; Load ‘1’ into A
L1: SJMP L1 ; Loop here continually
SEND: MOV SBUF, A ; Load SBUF
L2: JNB TI, L2 ; Wait for last bit to be sent
CLR TI ; Get ready for next byte
RET ; Return from subprogram
END
The same program written in C will be as follows.
#include <reg51.h>
void Send_Ser (unsigned char);
void main (void)
{
TMOD = 0x20; // Timer 1, Mode 2
TH1 = 0xFD; // 9600 baud rate
SCON = 0x40; // Set SCON in Mode 1, REN disabled
TR1 = 1; // Start timer
Send_Ser(‘8’); // Send ‘8’
Send_Ser(‘0’); // Send ‘0’
Send_Ser(‘5’); // Send ‘5’
Send_Ser(‘1’); // Send ‘1’
while (1); // Wait here infinitely
}
Microcontrollers and Applications | 115
void Send_Ser(unsigned char m)
{
SBUF = m; // Copy character to SBUF
while (TI == 0); // Wait for last bit to be sent
TI = 0; // Reset TI bit
}
Similar to the case of transmission, to receive characters serially, the Timer 1 is programmed
in mode 2 (auto-reload) and TH1 initialized appropriately for the required baud rate. The SCON
register is programmed in mode 1 with REN enabled. The timer is started by setting the TR1 bit.
The RI bit is cleared. The RI flag is now monitored continually to check the receipt of a character.
When RI becomes 1, the SBUF will contain the received character. It can now be copied to some
other place. The RI flag is cleared to enable reception of the next character, if any. The following
example illustrates the serial reception.
Example 3.28: Consider the problem of serially receiving characters. The received characters
are sent to the port P1 for display. The assembly language program for the problem is as follows.
ORG 0000H ;
MOV TMOD, #20H ; Timer 1, Mode 2
MOV TH1, #0FDH ; Baud rate 9600
MOV SCON, #50H ; Mode 1, REN enabled
SETB TR1 ; Start Timer 1, auto‐reload
L1: ACALL RECV ; Get next character serially
MOV P1, A ; Copy A to the port P1
SJMP L1 ; Continue
RECV: JNB RI, RECV ; Wait for the character
MOV A, SBUF ; Wait for last bit to be sent
CLR RI ; Get ready for next byte
RET ; Return
END
The same program written in C will be as follows.
116 | Microcontrollers and Applications
#include <reg51.h>
void main (void)
{
unsigned char my_char;
TMOD = 0x20; // Timer 1, Mode 2
TH1 = 0xFD; // 9600 baud rate
SCON = 0x40; // Set SCON in Mode 1, REN disabled
TR1 = 1; // Start timer
while (1) { // Loop
while (RI == 0); // Wait for RI to become 1
my_char = SBUF; // Read character from SBUF
P1 = my_char; // Put character into port P1
RI = 0; // Reset RI flag
}
}
3.8.5 Serial Communication Interrupt
In Section 3.7.2 we have seen that the IE register contains ES bit which stands for enabling
the serial interrupt. On the other hand, the examples noted in Section 3.8.3 and 3.8.4 contain loops
that continually checks the TI and RI flags to get confirmation about transmission and reception of
character, respectively. This busy wait loops can be avoided by utilizing the serial interrupt.
However, in the 8051, only one interrupt has been kept for both transmission and reception. As a
result, if the serial interrupt is enabled in the IE register, whenever the TI flag or the RI flag is set,
it gives interrupt to the 8051. Thus, as and when a serial communication takes place, control
branches to the address 0023H. In the service routine, the TI and RI flags should be checked to
determine the actual source of interrupt – successful transmission or successful reception.
Appropriate action can then be taken by the service routine. It has been explained in the following.
Example 3.29: Consider the system that reads port P1 and transmits the character read serially.
Simultaneously, it receives characters serially and outputs it to port P2. An interrupt driven
approach for the problem is as follows.
ORG 0000H
LJMP MAIN ; Jump to main routine
ORG 0023H
LJMP SERIAL ; Jump to Serial Int. routine
ORG 0030H
MAIN: MOV P1, #0FFH ; Make P1 input port
MOV TMOD, #20H ; Timer 1, Mode 2
MOV TH1, #0FDH ; Baud rate 9600
Microcontrollers and Applications | 117
MOV SCON, #50H ; Mode 1, REN enabled
MOV IE, #10010000B ; Enable serial interrupt
SETB TR1 ; Start Timer 1, auto‐reload
L1: MOV A, P1 ; Read port P1
MOV SBUF, A ; Serially transmit
SJMP L1 ; Loop continually
ORG 100H ;
SERIAL: JB TI, L2 ; Jump if TI is set
MOV A, SBUF ; Else character received
MOV P2, A ; Copy to P2
CLR RI ; Get ready for next byte
RETI ; Return
L2: CLR TI ; Clear TI
RETI ; Return
END
The same program written in C will be as follows.
#include <reg51.h>
void serial0 () interrupt 4
{
if (TI == 1) TI = 0; // Clear interrupt
else {
P2 = SBUF; // Put serial data onto P2
RI = 0; // Clear interrupt
}
}
void main (void)
{
unsigned char my_char;
P1 = 0xFF; // Make P1 input port
TMOD = 0x20; // Timer 1, Mode 2
TH1 = 0xFD; // 9600 baud rate
SCON = 0x50; // Set SCON in Mode 1, REN enabled
IE = 0x90; // Enable serial interrupt
TR1 = 1; // Start timer
118 | Microcontrollers and Applications
while (1) { // Loop
my_char = P1; // Read character from port P1
SBUF = my_char; // Put character into SBUF
}
}
UNIT SUMMARY
The 8051 supports a large number of machine-level instructions, commonly known as
assembly language instructions. Each assembly language instruction possesses a mnemonic
(identifying the operation to be performed by the CPU) and a few operands (on which the operation
is to be carried out). The instructions can be grouped into several categories – data transfer,
arithmetic and logic operations, branching etc. On the other hand, the operands in those instructions
can be a constant value, a register, a memory location etc. The 8051 supports a number of ways to
specify the operands. The assembly language instructions can be used to express the program logic
of a specific problem to be solved. The assembly language program is converted into the machine
code with the help of assemblers. For problems with logic complexity moderate to high, it may be
difficult to express the logic neatly in the assembly language. Such programs are often developed
in the C language with augmentations in the data types to include signed/unsigned char/int, bits etc.
Most of the IDEs of the 8051 supports program debugging by single stepping, breakpoint settings,
and viewing/modifying register/memory contents etc. Timers and counters are important
components of any microcontroller based system design. The 8051 contains two timers/counters
which may be configured to operate in various modes. Another important feature of any processor
is to inform it about events is interrupt. The 8051 supports different types of interrupt sources –
timers, reset, external interrupt pins and serial communication related. Serial communication is
helpful in situations where parallel communication is not possible due to pin/wire limitations. The
unit provides a detailed overview of all these topics along with a good number of programming
examples.
EXERCISES
Multiple Choice Questions
Microcontrollers and Applications | 119
(A) 2 kbytes (B) 4 kbytes (C) 8 kbytes (D) 16 kbytes
MQ5. Arithmetic operations supported by the 8051 can be of bit width
(A) 8 (B) 4 (C) 16 (D) All of the other options
MQ6. The “DA A” instruction works correctly for nonzero numbers upto
(A) 255 (B) 99 (C) 100 (D) None of the other options
MQ7. NOP instruction introduces
(A) Address (B) Delay (C) Memory location (D) None of the other options
MQ8. CJNE instruction sets the CY flag to 1 if
(A) destination = source (B) destination < source
(C) destination > source (D) destination ≤ source
MQ9. If R2 = 1, the instruction “DJNZ R2, L1” will take control to
(A) L1 (B) Next instruction
(C) Depends on assembler (D) None of the other options
MQ10. The instruction which will definitely clear the operand bit is
(A) JB (B) JBC (C) JNB (D) None of the other options
MQ11. The size of data moved by MOV instruction in the 8051 can be of bits
(A) 1 (B) 8 (C) 16 (D) All of the other options
MQ12. In which of the following the data to be moved be very close to the current instruction?
(A) MOVC A, @A+DPTR (B) MOVC A, @A+PC
(C) Both the cases (D) None of the cases
MQ13. MQ13. After executing MUL instruction, the CY flag is
(A) 0 (B) 1 (C) Depends on result (D) Not affected
Microcontrollers and Applications | 121
Answers of Multiple Choice Questions
1:C, 2:A, 3:D, 4:A, 5:A, 6:B, 7:B, 8:B, 9:A, 10:B, 11:D, 12:B, 13:A, 14:D, 15:A, 16:D, 17:B,
18:B, 19:B, 20:B, 21:A, 22:B, 23:B, 24:A, 25:B, 26:A, 27: A, 28: B, 29: B, 30: A, 31: A, 32:
C, 33: B, 34: B, 35: D
122 | Microcontrollers and Applications
Practical Problems
PQ1. Write an assembly language program to find the minimum of an array of N numbers stored
at external RAM location 2000H onwards. The minimum value be stored at external RAM
location 1000H.
Hint: The code structure will be similar to the Example 3.13. Assume the first number to be the
minimum and store at location 1000H. Now, read the successive numbers from the array and
check if the read number is less than the value stored at 1000H. If the new number is less,
update 1000H.
PQ2. Write an assembly language program to compute the square of each number in an array of N
numbers stored at RAM locations 2000H onwards. Assume the resulting numbers to be
within 255. Write the corresponding C program also.
Hint: Read next number from the array into A register. Copy A to B. Use “MUL AB” instruction
to get the square. As the result is within 255, the result of the multiplication will be available
in the A register. Copy A register back to array.
PQ3. Write an assembly language program to check if the number stored at RAM location 40H is
a prime or not. If the number is a prime, store 1 at 41H, else store 0 at 41H.
Hint: To check if a number M is prime or not, it is sufficient to check if it is divisible by any other
number in the range 2 to M/2. Hence, a loop may be created to check for the divisibility. If
the number is not divisible by any of these, the number is prime.
PQ4. Write an assembly language program to check if all the elements in the array of N numbers
starting at 2000H are same as the elements of the array starting at 1000H.
Hint: A loop may be created to check element by element, the two arrays.
PQ5. A string is said to be a palindrome if it is same when read backwards. For example, the string
“MALAYALAM”. Assuming that the string is stored from RAM location 40H and the
number of characters in it at location 55H, check if the string is a palindrome. If the string is
a palindrome, 1 is stored at 30H, else a 0 is stored there.
Hint: Two pointers R0 and R1 be set to the beginning and the end of the string. Now, the two
memory locations pointed to may be compared for equality. If the two characters are same,
R0 should be incremented and R1 decremented. If there is a mismatch at any point, the string
is not a palindrome. The string is a palindrome if R0 crosses R1.
PQ6. Develop assembly language and C programs for generating a square wave with 25% duty
cycle and time period 100 μS on port bit P2.2.
Hint: Refer to Example 3.22. However, the ON time is 25 μS and OFF time 75 μS. The delay values
are to be loaded into the registers accordingly.
PQ7. Develop assembly language and C programs to count the number of pulses on the line T1 of
the 8051 microcontroller. The count value should be available at port P1.
Microcontrollers and Applications | 123
Hint: Refer to Example 3.23.
PQ8. Suppose that two switches have been connected to the INT0 and INT1 pins of the 8051. If a
switch is closed, it gives a 0 value to the corresponding pin. An LED has been connected to
the port bit P2.1. Develop an interrupt based program so that the LED is turned ON if the
switch connected to INT0 is closed. Closing the switch connected to INT1 line turns OFF
the LED.
Hint: Refer to Example 3.26.
PQ9. Develop assembly language and C programs to serially transmit the string
“MICROCONTROLLER” through the 8051. The program should read P0.1 bit.
Transmission of the string be repeated as long as the bit is 1.
Hint: Refer to Example 3.27.
PQ10. Develop an interrupt driven version for the problem PQ9. Moreover, instead of reading from
port P0.1, the program should check a serially received byte. Transmission should stop if the
received byte is character ‘0’.
Hint: Refer to Example 3.29.
KNOW MORE
One of the major applications of microcontrollers, including 8051 is in Embedded Systems.
An embedded system is a dedicated electronic system with one/more processor(s) inside it. The
system performs single or a few well defined operations only. Typical examples of such systems
are digital camera, mobile phone, electronic toys, household appliances like washing machine,
microwave etc., automobiles, telephone exchanges, satellites and so on. These systems often has
part of it implemented in hardware and part in software to meet the system specifications. For the
software part, it is mostly a microcontroller. However, other types of processors, such as,
microprocessors, digital signal processors can also be used. Availability of on-chip program- and
data-memory aids in the realizing such systems with smaller footprints, using the microcontrollers.
4 I/O Interfacing
UNIT SPECIFICS
Through this unit, the following concepts have been elaborated:
Interfacing I/O devices to the 8051 ports;
Hardware and software for the interfacings;
Connecting switch, LED, keyboards, LCD, ADC, DAC with the 8051;
Interfacing the 8255, the Programmable Peripheral Interface chip.
The discussion in the unit is to illustrate the strategy to connect input-output devices with the
8051 ports. This is the most important unit, as far as interfacing is concerned. As the devices vary
widely, the interfacing requirements of them also vary. Very simple devices include switch and LED
for input and output, respectively. However, more complex ones include LCD, DAC, ADC etc. For
each such device, the hardware and the software have been enumerated. It has been assumed that
the reader has gone through the previous units of this book and has got an understanding of the
assembly language and high-level programming for 8051. A basic background of digital circuit is
essential for this unit. A good number of examples have been included to explain the concepts.
A large number of multiple choice questions, relevant for the topics discussed in this unit,
have been provided with their answers. Apart from that, subjective questions of short and long
answer type have been included. A list of tentative practical problems has been given. A list of
references and suggested readings will help the readers to get more details. The section “Know
More” has been carefully designed so that the supplementary information provided in this part
becomes beneficial for the users of the book.
RATIONALE
This unit on I/O interfacing provides a detailed view of the hardware and software
requirements to interface different types of input-output devices with the 8051. While interfacing a
device, its voltage, current and timing requirements are to be kept in consideration. The interfacing
programs may be written in either assembly language or in some high-level language, like C. The
126 | Microcontrollers and Applications
unit has started with the problem of interfacing simple switch and single LED to the 8051. Since
the switch is a mechanical device, it is often jittery and the designer needs to take care of the same
in the electronic part of the system. Glowing a number of LEDs also require the timing and
brightness to be taken into consideration. This has been followed by discussion on interfacing
matrix keyboard with hexadecimal digits 0 to F. Two I/O ports are used for this interfacing. To
display more complex patterns, 7-segment LEDs and LCD interfacing can be used. Specifics of
such interfacing have been detailed. To interface with the analog world, analog-to-digital and
digital-to-analog converters are essential for most of the control applications. Interfacing different
sensors are also through the analog-to-digital converters. The 8051 chip provides four I/O ports,
however, the port bits are multiplexed with other functions as well. To overcome the shortage of
I/O pins, often the chip 8255 is interfaced with it. The 8255 provides three dedicated I/O ports that
can be used to interface with other I/O devices. Thus, the unit gives a complete overview of the
interfacing strategies followed in systems developed around the 8051 microcontroller.
PRE-REQUISITES
Electronics: Units 1, 2, 3 of the book
UNIT OUTCOMES
List of outcomes of this unit is as follows:
U4-O1: Interface mechanical switches to the 8051
U4-O2: Connect LEDs to the port of 8051
U4-O3: Multiplex several 7-segment display modules with the 8051
U4-O4: Interface LCD module with the 8051
U4-O5: Connect analog-to-digital converter to the 8051
U4-O6: Connect digital-to-analog converter to the 8051
U4-O7: Extend the number of I/O ports of 8051 using the 8255
EXPECTED MAPPING WITH COURSE OUTCOMES
Unit-4 Outcomes (1- Weak Correlation; 2- Medium correlation; 3- Strong Correlation)
CO-1 CO-2 CO-3 CO-4 CO-5 CO-6
U4-O1 1 1 3 3 - -
U4-O2 1 1 3 3 - -
U4-O3 1 1 3 3 - -
U4-O4 1 1 3 3 - -
U4-O5 1 1 2 3 - -
U4-O6 1 1 2 3 - -
U4-O7 1 1 1 3 - -
Microcontrollers and Applications | 127
4.1 Introduction
Microcontrollers are mostly used in control applications. The controllers sense the
environment/plant and actuate the devices to control it. Depending upon the activity being
controlled, the type of devices connected to the microcontroller also varies. The devices can be
broadly classified into two categories – the input devices (mostly sensors) and the output devices
(mostly actuators). Very simple example of input device is a switch having only two positions, ON
and OFF. It can be interfaced to a port bit of the 8051 to read the switch status by a program.
Similarly, a single LED can be used to show the status of a port bit, which may be the outcome of
some control algorithm executed by the 8051. On the other hand, many of the input-output devices
may be electro-mechanical in nature. Thus, these devices are having specific requirements in terms
of voltage, current, timing etc. For example, a pattern displayed on an output device should be
flicker-free and steady for being interpretable by the human eyes. An input switch may be jittery
in its operation that may lead to input errors. A motor which may be rotating at a certain speed,
requires a finite amount of time to stop or reverse its direction. Hence, interfacing an input/output
device to the 8051 requires two tasks to be carried out carefully. The first task is to design the
circuit to connect the device. The hardware has to be designed in a manner, such that, the commands
given by the control program through port bit settings are converted to the appropriate voltage,
current or other specific requirements of the device. The second task is to design the software to
be executed by the 8051 to read the input devices or write to the output devices. As the 8051 ports
are limited in terms of the total number of I/O bits and their driving capacities, it may be required
to interface additional chips/components to augment the same.
128 | Microcontrollers and Applications
4.2.1 Switch Interfacing 5V
5V 5V
The simplest input device
is a switch that can be turned
either ON or OFF. The switch Port pin
10kΩ (internal pull-up) Port
needs to be interfaced to a port pin Port Port
of the 8051 to get its status read by pin
pin pin
the program. Fig 4.1 shows three 470Ω
different configurations in which
a switch may be interfaced. Fig
4.1(a) reads in a logic 0 when the
(a) (b) (c)
switch is closed and logic 1 when
the switch is open. With switch Fig 4.1: Connecting switch to a port pin
closed, the current drawn is about
0.5 mA which the port pin can sustain. Fig 4.1(b) shows the case in which a closed switch gives
logic 1 to the port pin. With the switch open, the port pin gets a logic 0. However, in this connection,
if by chance the port bit is set to 0 due to an output operation from the program while the switch is
also simultaneously closed, a very high
current will flow to the port pin, possibly 5V
damaging the same. Similarly, Fig 4.1(c)
can also lead to damage in the port pin DIP Switch
due to a high current flow when an
output operation has set the pin to 0. P1.7
Thus, the configuration suggested in Fig P1.6
4.1(a) is the preferred one. P1.5
8051
As a port of the 8051 contains 8 P1.4
bits, it can be used to interface upto eight P1.3
such switches together. An assembly P1.2
containing such switches is called a P1.1
Dual-Inline-Package (DIP) switch. Fig P1.0
4.2 shows a schematic diagram for the
hardware connection of a DIP switch Fig 4.2: Schematic for DIP switch connection
(with eight individual switches in it) to
the port P1 of the 8051. The code fragment to read the status is as follows.
Microcontrollers and Applications | 129
Contact Debouncing
The mechanical switches, such as, push button switch, toggle switch, electromechanical
relays etc. work on the principle of make-and-break contacts. The switches are normally open,
leading to logic 1, as shown in Fig 4.1(a) and 4.2. However, when the switch is being closed, due
to mechanical vibrations, several small pulses get created, as shown in Fig 4.3. This is known as
contact bounce or switch bounce. Due to this
phenomena, the 8051 may sense it as several
key presses. If the switch is connected to the
interrupt pin, several interrupts will get
generated. Special care needs to be taken to Fig 4.3: Bouncing effect in contacts/switches
resolve this problem. Both hardware and
software based debouncing solutions have been suggested to resolve the problem of contact
bouncing.
Hardware Solution. An RC network can be used to
+5V
solve the bouncing problem. When the switch is
open, the capacitor charges to a logic high level
through the pull-up resistor. As a result, the output
of the inverter feeding the port bit is 0. Now, if the To Port Bit
switch is closed momentarily, the capacitor
discharges quickly, making the port bit 1. Choosing S
the values of R and C judiciously, one can make
the RC time-constant to be larger than the switch Fig 4.4: Hardware debouncing
bounce time, thus preventing the possibility of the
capacitor charging quickly. The structure has been shown in Fig 4.4.
130 | Microcontrollers and Applications
has not been read as multiple presses. The whole process may be repeated a number of times to
ensure confidence in operation. The flowchart for the process has been shown in Fig 4.5.
5V 5V
DIP Switch
P1.7 P0.7
P1.6 P0.6
P1.5 P0.5
8051
P1.4 P0.4
P1.3 P0.3
P1.2 P0.2
P1.1 P0.1
P1.0 P0.0
Microcontrollers and Applications | 131
in Fig 4.7. The following program reads the settings of the switches through Port 1. If a switch
is pressed, the corresponding port bit will be read as a 0. The pattern read is output to Port 0.
Thus, the corresponding LED will turn ON. The 8051 assembly language code for the operation
is as follows. Debouncing has not been considered here since it is assumed that once a setting is
done by the user, there is some delay before it is modified. This ensures that the display is stable
for a particular switch setting.
ORG 0
MOV P1, #0FFH ; Set P1 in input mode
L1: MOV A, P1 ; Read Port P1
MOV P0, A ; Write to Port P0
SJMP L1 ; Continue
END
The corresponding C language program is as follows.
#include <reg51.h>
void main (void)
{
while (1) P0 = P1;
}
132 | Microcontrollers and Applications
has been pressed, the least significant 4
Start
bits of the port P2 will be 1011. Thus,
making the row lines 0, one at a time,
and reading the column input, any key Set all rows to 0 Set next row to 0
press can be uniquely identified. Some
additional steps are necessary to ensure
that all the keys are initially in open Read all columns Read all columns
state. This can be checked easily by
outputting an all-zero pattern to the
No All keys No Key press
port P1and checking that the least
significant 4-bits of the port P2 are all open in this row
1’s. Also, debouncing needs to be Yes Yes
taken care of. As there is no additional
Read all columns Identify key
capacitive circuitry connected in Fig
4.8, software debouncing is the ideal
solution, in this case. Fig 4.9 shows a No
Any key Get key code
flowchart to elaborate the logic to be pressed
followed by the keyboard routine. Yes
After debouncing, if a key has been Return
pressed, to detect it one row is set to 0, Wait for debounce
by turn. The columns are read and the
column giving 0 to the port identifies Read all columns
the key. A code table may then be
consulted to get the key code. For
example, the co-ordinate of row-1, No Any key Yes
pressed
column-1 corresponds to the key code
5. The following is the assembly Fig 4.9: Flowchart for keyboard scan routine
language program to scan the keyboard
and get the code of the key pressed (if any) at RAM location 50H.
ORG 1000H
MOV P2, #0FFH ; Set P2 in input mode
L1: MOV P1, #00H ; Ground all rows
L2: MOV A, P2 ; Read all columns
ANL A, #0FH ; Mask unused MSBs
CJNE A, #0FH, L2 ; Check for all keys open
ACALL DELAY ; Some key may be pressed, wait for 20ms
MOV A, P2 ; Read all columns
Microcontrollers and Applications | 133
ANL A, #0FH ; Mask unused MSBs
CJNE A, #0FH, L2 ; No key pressed, go back
ACALL DELAY ; Key pressed, wait for 20ms
MOV P1, #0FEH ; Ground row 0
MOV A, P2 ; Read all columns
ANL A, #0FH ; Mask unused MSBs
CJNE A, #0FH, ROW_0 ; Some key in row 0 pressed
MOV P1, #0FDH ; Ground row 1
MOV A, P2 ; Read all columns
ANL A, #0FH ; Mask unused MSBs
CJNE A, #0FH, ROW_1 ; Some key in row 1 pressed
MOV P1, #0FBH ; Ground row 2
MOV A, P2 ; Read all columns
ANL A, #0FH ; Mask unused MSBs
CJNE A, #0FH, ROW_2 ; Some key in row 2 pressed
MOV P1, #0F7H ; Ground row 3
MOV A, P2 ; Read all columns
ANL A, #0FH ; Mask unused MSBs
CJNE A, #0FH, ROW_3 ; Some key in row 3 pressed
AJMP L1 ; No key pressed, repeat scanning
ROW_0: MOV DPTR, #KEY_ROW_0 ; DPTR = Start of Row 0
SJMP FIND_KEY ; Find column for the key
ROW_1: MOV DPTR, #KEY_ROW_1 ; DPTR = Start of Row 1
SJMP FIND_KEY ; Find column for the key
ROW_2: MOV DPTR, #KEY_ROW_2 ; DPTR = Start of Row 2
SJMP FIND_KEY ; Find column for the key
ROW_3: MOV DPTR, #KEY_ROW_3 ; DPTR = Start of Row 3
FIND_KEY: RRC A ; Rotate A and get column status to CY
JNC MATCHED ; Column found, if CY=0
INC DPTR ; DPTR = Next column address
SJMP FIND_KEY ; Check for next column
134 | Microcontrollers and Applications
MATCHED: CLR A ; Clear accumulator
MOVC A, @A+DPTR ; Get code from the table
MOV 50H, A ; Get key code to RAM[50]
AJMP L1 ; Repeat scanning
ORG 2000H
KEY_ROW_0: DB ‘0’, ‘1’, ‘2’, ‘3’ ; Row 0
KEY_ROW_1: DB ‘4’, ‘5’, ‘6’, ‘7’ ; Row 1
KEY_ROW_2: DB ‘8’, ‘9’, ‘A’, ‘B’ ; Row 2
KEY_ROW_3: DB ‘C’, ‘D’, ‘E’, ‘F’ ; Row 3
END
As it could be found, the program code for the keyboard routine is quite complex and
lengthy. The same can be expressed in a more compact manner using the C language for
programming. In the following a C code has been given for the same function. The key code will
be stored in a variable key_pressed.
# include <reg51.h>
# define COLUMN P2 // P2 will read the columns
# define ROW P1 // P1 will select rows
void delay_rtn( unsigned int del_val );
unsigned char keys[4][4] = { ‘0’, ‘1’, ’2’, ‘3’,
‘4’, ‘5’, ‘6’, ‘7’,
‘8’, ‘9’, ‘A’, ‘B’
‘C’, ‘D’, ‘E’, ‘F’ };
Microcontrollers and Applications | 135
unsigned char key_pressed;
void main()
{
unsigned char col_id, row_id;
COLUMN = 0xFF; // Configure P2 in input mode
while (1) do {
do {
ROW = 0x00; // Ground all rows
col_id = COLUMN; // Read all columns
col_id &= 0x0F; // Mask unused bits
} while ( col_id != 0x0F ); // All keys open now
do {
do {
col_id = COLUMN; // Read all columns
col_id &= 0x0F; // Mask unused bits
} while ( col_id == 0x0F ); // Wait till some key pressed
delay_rtn( 20 ); // Wait for 20 ms
col_id = COLUMN; // Read all columns
col_id &= 0x0F; // Mask unused bits
} while ( col_id == 0x0F );
// Some key definitely pressed – identify it
while (1) do {
ROW = 0xFE; // Ground Row 0
col_id = COLUMN; // Read columns
col_id &= 0x0F; // Mask unused bits
if ( col_id != 0x0F ) {
row_id = 0; // Save row index
break; // Exit while‐loop
}
ROW = 0xFD; // Ground Row 1
col_id = COLUMN; // Read columns
col_id &= 0x0F; // Mask unused bits
if ( col_id != 0x0F ) {
row_id = 1; // Save row index
136 | Microcontrollers and Applications
break; // Exit while‐loop
}
ROW = 0xFB; // Ground Row 1
col_id = COLUMN; // Read columns
col_id &= 0x0F; // Mask unused bits
if ( col_id != 0x0F ) {
row_id = 2; // Save row index
break; // Exit while‐loop
}
ROW = 0xF7; // Ground Row 1
col_id = COLUMN; // Read columns
col_id &= 0x0F; // Mask unused bits
if ( col_id != 0x0F ) {
row_id = 3; // Save row index
break; // Exit while‐loop
}
}
if ( col_id == 0x0E )
key_pressed = keys[ row_loc ][ 0 ];
else if ( col_id == 0x0D )
key_pressed = keys[ row_loc ][ 1 ];
else if ( col_id == 0x0B )
key_pressed = keys[ row_loc ][ 2 ];
else
key_pressed = keys[ row_loc ][ 3 ];
}
}
void delay_rtn( unsigned int del_val )
{
unsigned int x, y;
for (x = 0; x < 1000; x++)
for (y = 0; y < del_val; y++);
}
Microcontrollers and Applications | 137
4.4 Seven-Segment Display Interfacing
One of the very common output devices used in the microprocessor and microcontroller
based systems is
a 7-segment a a
b
LED display, as c f g b
shown in Fig d common
e
4.10(a). In this,7 f e c
LEDs are g
arranged in a dp d dp
manner to show (a)
the digit ‘8’. As a a a a a
shown in Fig f
f g b f
g b g b f g b f g b
4.10(b),
different LED e c e c e c e c e c
segments can be dp
d dp d dp d dp d dp d
turned on to
display the a a a a a
digits 0 to 9. f g b f f f g b
g b g b f g b
Some other
characters and e c e c e c e c e c
symbols can dp dp d dp
d d d dp d dp
also be
displayed by (b)
turning on the Fig 4.10: (a) 7-segment module (b) Digits
LEDs selectively. Though it is called a 7-segment display, there are 8 LEDs in it, marked as a, b,
c, d, e, f, g and dp (decimal point). One such display module can show a single digit. A number of
them could be used to display multi-digit numbers. Such displays are typically used to show
counters, token numbers, clock time, date etc.
The 7-segment display modules come in two variants – common anode and common cathode.
In a common anode module (shown in Fig 4.11(a)), the anode terminals of the LEDs are joined
together to a common terminal. On the other hand, in a common cathode module (shown in Fig
4.11(b)), the cathode terminals are combined into a common terminal. Both have 8 LEDs in them.
138 | Microcontrollers and Applications
Out of the two
configurations, Anode Cathode
common anode is common
the preferred one a b c d e f g dp
for many of the
designers, as this
can ensure more
current through a b c d e f g dp
common
the LEDs for a (a) (b)
brighter display. Fig 4.11: 7-segment display (a) Common anode (b) Common cathode
The 8051 port bits
can typically sink 1.6 mA of current, compared to its source current capacity of 60 μA. Fig 4.12
shows two different ways in which the current limiting resistors can be connected in the interface.
Out of these two,
the structure Common anode Common anode
7-segment display
shown in Fig 5V 7‐segment display
a 5V a
4.12(b) is b P1.0 com. b P1.0
com. P1.1
preferable, as in c P1.1 c
Fig 4.12(a), P1.2 P1.2
d P1.3 d P1.3
brightness varies e e
depending upon (a) P1.4 (b) P1.4
f f
the number of g P1.5 g P1.5
dp P1.6 dp P1.6
LEDs turned on. P1.7 P1.7
For a common
anode display Fig 4.12: Ways to connect common anode displays
module with
inputs a to dp fed through an I/O port of the Table 4.1: Patterns for digits
8051, the output pattern corresponding to Port Bits
different digits have been shown in Table Digit 7 6 5 4 3 2 1 0 Hex
4.1. dp g f e d c b a
0 1 1 0 0 0 0 0 0 C0
4.4.1 Multiplexed Display 1 1 1 0 0 1 1 1 1 CF
A major problem with the 7- 2 1 0 1 0 0 1 0 0 A4
segment display interface, shown in Fig 1 0 1 1 0 0 0 0 B0
3
4.12 is that, connecting multiple such
4 1 0 0 1 1 0 0 1 99
modules require large number of I/O port
pins. Each module requires eight output 5 1 0 0 1 0 0 1 0 92
port bits to drive the LED segments. On the 6 1 0 0 0 0 0 1 0 82
other hand, most of the applications 7 1 1 1 1 1 0 0 0 F8
involving such LED display need a number 8 1 0 0 0 0 0 0 0 80
of such modules to be integrated together. 1 0 0 1 0 0 0 0 90
9
Microcontrollers and Applications | 139
For example, a real-time clock module will
need at least six such 7-segment displays Port 1
Bit lines
(two each for the hour, minute and second
parts). Interfacing such a clock display
module with the 8051 is then not possible Module 1 Module 2 Module 3 Module 4
due to the I/O pin limitations. To sort out
this problem, most of the interfacing Select lines
solutions rely upon the persistence property Port 2
human vision. According to it, human eye
and brain retain a visual impression for
about 1/30th of a second. Thus, after Select next module
displaying a pattern (of sufficient through Port 2
brightness) if it is taken off and redisplayed
within the duration of the persistence
window, we shall see a steady image only. Output pattern to
In a multiplexed display with more than Port 1
one modules, the first module is selected
and the pattern for it is output. Next, the
second module is selected with the Fig 4.13: Multiplexing 7-Segment Displays
corresponding bit pattern sent to the port, and so on. The whole process is repeated continually, so
that within 1/30 of a second, each display module gets updated with its pattern. To reduce the
hardware, the port bits providing the pattern are fed to all the display modules. The selection of the
module is done via appropriate port bits. Since only one module is enabled, the pattern can change
the digit only in that module.
1 kΩ
P2.0
P2.1
P2.2 5V
P2.3
330Ω BC557 BC557 BC557 BC557
P1.0
8051
140 | Microcontrollers and Applications
Fig 4.14 shows the hardware connection for four seven-segment display modules in a
multiplexed fashion to the 8051. The module selection is done via the least significant four bits of
the port P2, while bit patterns for digit display are sent by the port P1. As module drives need more
current, p-n-p transistors BC557 have been used in the circuit. Next, we shall see how to feed bit
patterns through the 8051 ports to display a numeric string of four decimal digits (for example,
“1579”) continually in the four multiplexed segments. The string is assumed to be stored at four
bytes starting from RAM location 2000H. The program is stored from memory location 1000H.
The program uses a subprogram named BIT_PATT that gets the bit pattern to be output to the port
P1 for a particular digit of the string. Index of the digit is made available in register R1 before
making the call. It returns the bit pattern to glow the LED segments in the register A. The display
program is in an infinite loop so the pattern displayed is stable. The array DGT_PATT stores the
bit pattern to be output to a module to glow the required segments for a digit (as shown in Table
4.1).
ORG 1000H
DGT_PATT: DB 0C0H, 0CFH, 0A4H, ; Bit patterns for digits
0B0H, 99H, 92H, 82H,
0F8H, 80H, 90H
; Display most significant digit
L1: MOV R1, #0 ; Set R1
ACALL BIT_PATT ; Get bit pattern in A
MOV P1, A ; Send pattern to glow segments
MOV P2, #11110111 ; Select module
ACALL DELAY_RTN ; Put a small delay
; Display second digit
MOV R1, #1
ACALL BIT_PATT
MOV P1, A
MOV P2, #11111011
ACALL DELAY_RTN
; Display third digit
MOV R1, #2
ACALL BIT_PATT
MOV P1, A
Microcontrollers and Applications | 141
MOV P2, #11111101
ACALL DELAY_RTN
; Display fourth digit
MOV R1, #3 ; Read all columns
ACALL BIT_PATT ; Mask unused MSBs
MOV P1, A ; Some key in row 2 pressed
MOV P2, #11111110 ; Ground row 3
ACALL DELAY_RTN
AJMP L1 ; Repeat display
ORG 2000H
STRING: DB “1579” ; String to be displayed
END
142 | Microcontrollers and Applications
The corresponding program in C language can be as follows.
# include <reg51.h>
void delay_rtn( unsigned int del_val );
unsigned char DGT_PATT[10] = { 0xC0, 0xCF, 0xA4, 0xB0, 0x99,
0x92, 0x82, 0xF8, 0x80, 0x90 };
unsigned char STRING[4] = “1597”;
void main()
{
while (1) do {
P1 = DGT_PATT[ STRING[ 0 ] – ‘0’]; P2 = 0xF7; delay_rtn( 20 );
P1 = DGT_PATT[ STRING[ 1 ] – ‘0’]; P2 = 0xFB; delay_rtn( 20 );
P1 = DGT_PATT[ STRING[ 2 ] – ‘0’]; P2 = 0xFD; delay_rtn( 20 );
P1 = DGT_PATT[ STRING[ 3 ] – ‘0’]; P2 = 0xFE; delay_rtn( 20 );
}
}
void delay_rtn( unsigned int del_val )
{
unsigned int x, y;
for (x = 0; x < 1000; x++)
for (y = 0; y < del_val; y++);
}
4.5 Liquid Crystal Display (LCD) Interfacing
LCD is an electronic display device working on the principle of light modulating properties
of liquid crystals, combined with polarizers. LCD can display arbitrary images, preset words, digits
etc. In the recent time, LCDs have become much more preferable to the 7-segment LED displays
due to the following reasons. The price of such devices have reduced significantly. As noted earlier,
LCDs can display digits, characters and graphics, while the 7-segment LED displays are useful for
digits and possibly a limited set of characters. Most of the LCD devices have built-in refreshing
circuitry. Thus, the processor need not do anything special to keep the display stable. Programming
of such devices is also very simple.
An LCD module with its pinout has been shown in Fig 4.15. The display consists of two
rows, with each row being capable of printing a number of characters. Typical LCDs may have 1,
2 or 4 lines with each line capable of accommodating 16, 20 or 40 characters. An LCD display with
2 lines and 40 characters is specified as 40 2 LCD. The bits DB7 through DB0 are used to specify
the individual character positions. For any address, DB7 is always 1, DB6 is 0 for line 1 and 1 for
Microcontrollers and Applications | 143
line 2. Remaining DB5 through
LED Negative
VEE (Control)
DB0 are used to refer to one of
VSS (Ground)
LED Positive
VCC (+5V)
the 40 positions (0 to 39). Thus,
Read/Write
these bits can take up the values
Enable
from 00000 (decimal 0) to
100111 (decimal 39). Hence, the Data Pins (0 to 7)
RS
line 1 addresses range over 80H
to A7H, while line 2 addresses 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
range over C0H to E7H. The
display consists of the following
pins, grouped as per their
functionality.
The LCD display accepts a set of commands sent to its command register for proper display
of patterns. Table 4.2 shows the major commands accepted by the LCD module, the command
codes and the corresponding actions. All commands are eight bit wide and sent through the pins
DB0 through DB7. The commands can clear the display, move cursor to different positions on the
LCD screen etc. The display is assumed to have two lines.
Fig 4.16 and 4.17 show the timing diagram depicting the behavior of various interfacing
signals for the read and the write operations of the LCD command register, respectively. Thus, in
both the cases, RS has been set to 0. The R/W line is set to 1 for the read operation (Fig 4.15) and
0 for the write operation (Fig 4.16). The read operation also needs a low-to-high pulse on the E line
(Fig 4.15), while the write operation needs a high-to-low pulse (Fig 4.16). Typical values of Setup
Time, Hold Time, Enable Pulse Width and Data Setup Time are 140ns, 10ns, 450ns and 195ns,
respectively. Thus, an interface routine must take care of these minimum delays to be provided
between the activation and deactivation of signals. A better method may be to monitor the DB7
line with RS = 0 and R/W = 1 to read the data bit line, after sending a command and waiting for
the LCD module to be free to accept the next command.
DB0-7 DB0-7
Data Data
Hold
E E Data Setup Time
Data delay Time
R/W Setup Hold
Time Enable Pulse Time
R/W
Setup Hold
RS Time Time RS
Fig 4.16: LCD Read operation Fig 4.17: LCD Write operation
Microcontrollers and Applications | 145
Fig 4.18 shows an
interfacing of an LCD module
+5V
LCD Module
with the 8051. The data pins DB0
LED–
LED+
VCC
DB1
VEE
R/W
VSS
DB0
DB4
DB2
DB3
DB5
DB6
DB7
through DB7 are driven by the
RS
E
port P1. Other important pins RS,
R/W and E are connected via the
560Ω
port bits P3.2, P3.1 and P3.0, 10kΩ
respectively. It is assumed that
the LCD module is a 40 2 one
with backlit LEDs present. The +5V
8051 assembly language program
P3.1
P1.1
P1.3
P1.4
P1.5
P1.7
P3.2
P3.0
P1.0
P1.2
P1.6
to display the string “8051”
starting at line 1, position 18 has
8051
been noted next. The program Fig 4.18: Interfacing LCD module with the 8051
works by checking the busy flag,
DB7 pin status, before issuing a command or data to the LCD.
ORG 1000H
MOV A, #38H ; Initialize 2 line LCD, 5 7 matrix
ACALL ISS_CMD ; Issue the command
MOV A, #0EH ; LCD on, cursor on
ACALL ISS_CMD ; Issue the command
MOV A, #01H ; Clear LCD
ACALL ISS_CMD ; Issue the command
MOV A, #92H ; Cursor at line 1, position 18
ACALL ISS_CMD ; Issue the command
MOV A, #‘8’ ; Display letter ‘8’
ACALL DSP_DATA
MOV A, #‘0’ ; Display letter ‘0’
ACALL DSP_DATA
MOV A, #‘5’ ; Display letter ‘5’
ACALL DSP_DATA
MOV A, #‘1’ ; Display letter ‘1’
L1: SJMP L1 ; Remain at this position
146 | Microcontrollers and Applications
MOV P1, A ; Issue the command code
CLR P3.2 ; Make RS = 0
CLR P3.1 ; Set R/W to 0 for a write
SETB P3.0 ; Set E = 1 for high-to-low pulse
ACALL DELAY_RTN ; Give a delay
CLR P3.0 ; Set E = 0 to latch the command
RET ; Return
Microcontrollers and Applications | 147
CLR TR0 ; Stop Timer 0
CLR TF0 ; Clear Timer 0 flag
RET
END
The corresponding C language program can be as follows.
# include <reg51.h>
sfr LCD_DB_Pins = P1; // LCD data pins connected to P1
sbit RS = P3^2; // RS connected to Port 3, pin 2
sbit RW = P3^1; // Read/Write to Port 3, pin 1
sbit E = P3^0; // Enable to Port 3, pin 0
sbit BUSY = P1^7; // DB7 gives the busy status
void delay_rtn( unsigned int del_val );
void LCD_Command( unsigned char value );
void LCD_Data( unsigned char value );
void LCD_Ready();
void main()
{
LCD_Command( 0x38 ); // Initialize 2 line LCD, 5 7 matrix
LCD_Command( 0x0E ); // LCD on, cursor on
LCD_Command( 0x01 ); // Clear LCD
LCD_Command( 0x92 ); // Line 1, position 18
LCD_Data( ‘8’ ); // Display ‘8’
LCD_Data( ‘0’ ); // Display ‘0’
LCD_Data( ‘5’ ); // Display ‘5’
LCD_Data( ‘1’ ); // Display ‘1’
}
void LCD_Command( unsigned char value )
{
LCD_Ready(); // Check LCD busy flag DB7
LCD_DB_Pins = value; // Put value on DB pins
RS = 0; RW = 0; E = 1;
delay_rtn( 1 );
E = 0; // High‐to‐Low pulse on E
}
148 | Microcontrollers and Applications
void LCD_Data( unsigned char value )
{
LCD_Ready(); // Check LCD busy flag DB7
LCD_DB_Pins = value; // Put value on DB pins
RS = 1; RW = 0; E = 1;
delay_rtn( 1 );
E = 0; // High‐to‐Low pulse on E
}
void LCD_Ready()
{
BUSY = 1; // Make DB7 input
RS = 0; RW = 1;
while (BUSY == 1) { E = 0; delay_rtn( 1 ); E = 1; } // Wait for BUSY = 0
}
void delay_rtn( unsigned int del_val )
{
unsigned int x, y;
for (x = 0; x < 1000; x++)
for (y = 0; y < del_val; y++);
}
4.6 Analog to Digital Converter (ADC) Interfacing
Analog-to-Digital Converter (ADC) is a very important device that often needs to be
interfaced with the 8051 to interact with the environment. While the 8051 (or any other
microprocessor/microcontroller) is a digital device working with binary values of digital signals,
the physical world is analog in nature. The physical signals are continuous in nature, for example,
temperature, pressure, velocity, light intensity etc. A sensor/transducer can convert such signals
into some equivalent electrical signals. To process the generated voltage/current signals by the
8051, it is required to convert those into digital values. An ADC performs this function. The number
of bits (n) of the digital signal produced, is called the resolution of the ADC. The typical values of
n are 8, 10, 12, 16 etc. As an ADC converts an analog signal into a set of digital values, the smallest
change in the input that can effect a change in the digital output, is called a step size. With a
resolution of n = 8, there can be 256 number of steps. Assuming the range of a voltage signal that
this ADC converts, to be 5V, the step size is equal to 5V/256 = 19.53mV. On the other hand, if we
need to keep the step size to say 10mV, the conversion range for this ADC will be 2.56V.
Microcontrollers and Applications | 149
Several ADCs have been designed by different manufacturers. A typical one is
ADC0808/0809 from National
Semiconductor (currently, Texas Clock VCC GND
Instruments). This is an 8-bit ADC (n
= 8). There are eight analog channels
IN0 D0
that the chip can handle in a IN1 D1
multiplexed fashion. The two IN2 D2
converters, the ADC0808 and IN3 D3
ADC0809, are functionally identical IN4 D4
except that the ADC0808 has a total IN5 ADC0808/0809 D5
unadjusted error of ±1∕2 LSB and the IN6 D6
ADC0809 has an unadjusted error of IN7 D7
Vref(+) EOC
±1 LSB. Fig 4.19 shows a schematic
for the chip with the following signal Vref(–) OE
line distribution.
VCC, GND: The chip needs a
power supply of 5 volts. SC ALE C B A
Clock: Though the maximum Fig 4.19: ADC0808/0809 schematic
clock speed supported by the chip
is 1280 kHz, the typical clock value used is 640 kHz.
Vref(+), Vref(–): These two pins set the reference voltage for the conversion process. With
Vref(+) set at 5V and Vref(–) grounded, the step size is 19.53 mV, as explained earlier.
Similarly, the step size can be set to other suitable values by selecting the reference voltages
appropriately.
IN0-IN7: These are eight analog input channels. The ADC can convert upto eight analog inputs
to their equivalent digital bits by multiplexing these channels.
C, B, A, ALE: These are the select inputs for the analog channels. By specifying a suitable 3-
bit value to them (with C as MSB), a specific channel may be selected for conversion. A low-
to-high pulse should be given to the ALE input to register the selection.
SC: It stands for Start Conversion. A low-to-high pulse is applied to SC to initiate the analog-
to-digital conversion process.
EOC: The End of Conversion signal from the ADC indicates that the conversion process has
been completed. A high-to-low transition of this line marks the completion.
OE: The Output Enable (OE) input is activated to read the conversion value. A low-to-high
pulse on the OE pin makes the digital value available at pins D0 to D7.
The sequence of operation for the analog-to-digital conversion process has been shown in Fig
4.20. It consists of the following steps.
150 | Microcontrollers and Applications
1. The channel for the analog
input is selected. Proper Clock
channel number is put at C, B,
A. C, B, A
Channel No.
2. A transition of low-to-high is
applied in the ALE input to the ALE
ADC.
3. A low-to-high pulse is
SC
applied on the SC line to
instruct the ADC to start the
conversion process. EOC
4. The ADC gives a high-to-low D0‐D7
transition on EOC line to mark Digital value
end of conversion.
5. A low-to-high transition on OE
the OE line makes the ADC to
Fig 4.20: Timing diagram for ADC0808/0809
put the digital value on D0‐
D7.
Fig 4.21 shows the connection for interfacing ADC0808/0809 to the 8051. Out of eight available
analog channels, in this interface a single channel (Channel 1) has been used. The port P1 of the
8051 has been used to read-in the converted digital value. Port P2 has been used to connect to other
signal lines of the ADC. Bits 0, 1 and 2 of port P2 have been used to provide proper select values
needed for the input channel 1.The Vref(+) has been set to 2.56V and Vref(-) to 0 to ensure 10mV
step size. Bit P2.3 controls ALE for the ADC. Bits P2.4 and P2.5 provide the output enable (OE)
and start conversion (SC) for the ADC. The end-of-conversion (EOC) pin of the ADC has been
connected to the port bit P2.6. The clock input for the ADC has been drawn from the crystal
connected to the 8051. Since the crystal frequency is high, it is passed through four D flip-flops
(with Q connected to D) to reduce it. Each such flip-flop divides the frequency by two. The VCC
is connected to 5V, GND to 0 and chip select (CS) also put at zero to select the ADC chip.
Microcontrollers and Applications | 151
5V
ADC0808/0809
IN0
XTAL2 P2.3 ALE IN1 Channel Used
11.0592 P2.2 A IN2
8051
MHz P2.1 B IN3
P2.0 C IN4
IN5
IN6
P1.0-P1.7 D0‐D7 IN7
Vref(‐)
CS
Clock GND
D Q D Q D Q D Q
Q Q Q Q
Fig 4.21: Interfacing ADC0808/0809 with the 8051
The assembly language program for interfacing the 8051 with the ADC0808/0809 has been
shown in the following.
ORG 1000H
MOV P1, #0FFH ; Configure P1 as an input port
SETB P2.6 ; Make EOC an input line
CLR P2.3 ; Clear ALE
CLR P2.4 ; Clear OE
CLR P2.5 ; Clear SC
152 | Microcontrollers and Applications
CLR P2.5 ; Clear SC
L2: JB P2.6, L2 ; Wait for EOC to become low
L3: JNB P2.6, L3 ; Wait for EOC to become high
SETB P2.4 ; Set OE to high
ACALL DELAY_RTN ; Put delay
MOV A, P1 ; Read the converted digital value
CLR P2.4 ; Clear OE
SJMP L1 ; Proceed to convert next analog input
#include <reg51.h>
sbit SEL_C = P2^0;
sbit SEL_B = P2^1;
sbit SEL_A = P2^2;
sbit ALE = P2^3;
sbit OE = P2^4;
sbit SC = P2^5;
sbit EOC = P2^6;
sfr DIG_VAL = P1;
void delay_rtn( unsigned int del_val );
void main()
{
DIG_VAL = 0xFF; // Configure P1 as input
Microcontrollers and Applications | 153
EOC = 1; // Configure EOC line as input
ALE = 0; // Clear ALE
SC = 0; // Clear SC
OE = 0; // Clear OE
while (1) {
SEL_C = 0; SEL_B = 0; SEL_A = 1; // Choose channel 1
delay_rtn(1);
ALE = 1;
delay_rtn(1);
SC = 1;
delay_rtn(1);
ALE = 0;
SC = 0; // Start conversion
while (EOC == 1); // Wait for conversion to complete
while (EOC == 0);
OE = 1; // Enable output to be read
delay_rtn(1);
A = DIG_VAL;
OE = 0;
}
}
void delay_rtn( unsigned int del_val )
{
unsigned int x, y;
for (x = 0; x < 1000; x++)
for (y = 0; y < del_val; y++);
}
4.7 Digital to Analog Converter (DAC) Interfacing
Digital-to-Analog converter is another electronic component often interfaced with the 8051
to control the environment or output some equivalent analog quantity, corresponding to a digital
value. Similar to ADC, the resolution is decided by the number of bits in the digital input. In a
DAC, a digital input is specified using the bits D0-D7 (with D0 as the LSB and D7 as the MSB)
gets converted into an output current Iout as a fraction of the reference output current Iref.
𝐷7 𝐷6 𝐷5 𝐷4 𝐷3 𝐷2 𝐷1 𝐷0
𝐼 𝐼
2 4 8 16 32 64 128 256
154 | Microcontrollers and Applications
The current Iref is decided by the reference voltage Vref and is generally set to 2.0 mA. There
can be 256 discrete current levels that can be output by an 8-bit DAC. Though DACs of higher
resolution are available, those are more expensive and may not be very much useful for
microcontroller based applications. The Iout can be converted to voltage by simply passing the
current through a resistor, however, in most of the cases, an operational amplifier is used to separate
the DAC from other stages.
DAC0808
(with A1 as MSB and A8 as LSB). Pins IO 4 13 VCC
13 and 2 correspond to the positive (MSB) A1 5 12 A8 (LSB)
power supply VCC and GND lines,
A2 6 11 A7
respectively, while the pin 3
corresponds to VEE, the negative A3 7 10 A6
power supply. Pins 14 and 15 are the A4 8 9 A5
positive and negative reference voltage
Fig 4.22: Pin layout of DAC0808
inputs VREF+ and VREF-. Pin 16 is
for the compensation capacitor. The output is available at pin 4, marked as IO. This is a current
output that needs to be converted to voltage for analog output.
A4 8 2
P1.4 GND
8051
Microcontrollers and Applications | 155
used with feedback resistance 5kΩ to convert the output current to analog voltage.
The interface shown in Fig 4.23 can be used to generate different types of analog
waveforms. In the following, two examples have been noted – one to generate a triangular wave
and the second one to generate a sine wave.
Example 4.2: Triangular Wave Generation. To generate triangular wave, the values 0 to 255
can be output to port P1 followed by decrementing upto 0. The digital values, when converted
by the DAC will provide an analog output triangular waveform. The 8051 source code for the
same has been presented next. After outputting a digital value, a small delay has been introduced
to allow time to the DAC to convert the pattern. It may be noted that increasing the delay value
will convert the waveform to be more of staircase in shape. The waveform can be viewed on an
oscilloscope to see the shape and adjust the delay value accordingly.
ORG 0
CLR A ; Clear accumulator
L1: MOV P1, A ; Send data to DAC
ACALL DLA ; Insert delay
CJNE A, #0FFH, L2 ; Check if 255 reached
SJMP L3 ; Jump to decrement
L2: INC A ; Increment A
SJMP L1 ; Repeat increment
L3: DEC A ; Continue
MOV P1, A ; Send to DAC
ACALL DLA ; Insert delay
CJNE A, #01, L4 ; Check if 0 reached
CLR A ; Clear accumulator
SJMP L1 ; Repeat increment
L4: SJMP L3 ; Repeat decrement
DLA: NOP ; Small delay routine
NOP
RET
END
The corresponding C language program is as follows.
#include <reg51.h>
void main (void)
{
unsigned char i;
156 | Microcontrollers and Applications
while (1) {
for (i = 0; i < 255; i++) { P1 = i; delay_rtn(2); }
for (i = 255; i > 0; i ‐‐) { P1 = i; delay_rtn(2); }
}
}
void delay_rtn( unsigned int del_val )
{ unsigned int x, y;
for (x = 0; x < 1000; x++)
for (y = 0; y < del_val; y++);
}
Example 4.3: Sine Wave Generation. To generate a sine wave, we first need to prepare a table
of the sine values of different angles in the range 0 to 360 degrees. Assuming that corresponding
to zero degree, the output voltage is 5V and that the peak voltage can be at most 10V, the equation
governing the sine wave is as follows.
𝑉 5V 5 sin 𝜃
The 10V range is covered by 256 digital levels of inputs. Thus, each level constitutes a voltage
of 25.6V. Table 4.3 shows the different angles and their corresponding digital input to be sent to
the DAC for generating the sine wave.
The assembly language program for the sine wave generation is as follows. It stores the
values noted in Table 4.3 and outputs those periodically to produce the sine wave. It may be
Microcontrollers and Applications | 157
noted that as the values are 30 degree apart, the generated waveform will not be very smooth. To
produce a better waveform, more intermediary values are to be kept in the table and output to the
DAC.
ORG 0
WAVE: DB 128, 192, 238, 255,
238, 192, 128, 64, ; The Table
17, 0, 17, 64, 128
L1: MOV DPTR, #WAVE ; DPTR points to Table
MOV R2, #13 ; R2 holds count
The C
L2: CLR A
MOVC A, @A+DPTR ; Get next sine value
MOV P1, A ; Output to Port P1
INC DPTR ; DPTR points to next
DJNZ R2, L2 ; Go for next value
SJMP L1 ; Generate next wave
END
language program for the same can be as follows.
#include <reg51.h>
void main (void)
{
unsigned char WAVE[ 12 ] = {128, 192, 238, 255,
238, 192, 128, 64,
17, 0, 17, 64};
unsigned char i;
while (1) {
for (i = 0; i < 255; i++) {
P1 = WAVE[ i ];
delay_rtn(2);
}
}
}
void delay_rtn( unsigned int del_val )
{ unsigned int x, y;
for (x = 0; x < 1000; x++)
for (y = 0; y < del_val; y++);
}
158 | Microcontrollers and Applications
4.8 Interfacing Temperature Sensor
Physical data from the real-world need to be converted to electrical signals for interaction
with the microcontroller. Temperature is one of the very important physical quantities, monitored
by the microcontroller based systems. The device used to sense the physical quantity is a sensor.
For example, a constantan alloy (Cu-55%, Ni-45%) wire is a sensor that creates a change in its
resistance when subjected to mechanical displacement. A sensor becomes a transducer when it can
convert one form of energy into another. For example, a
thermocouple is a heat sensor which is also a transducer, as
in response to a change in temperature, it outputs a Analog Signal
proportional change in the electromotive force (emf).
However, the terms sensor and transducer are often used
interchangeably without much differentiation. Transducer
Microcontrollers and Applications | 159
4.9 8255 Interfacing
8255
PC7 10 31 D3
have more I/O ports in the system. The chip 8255 is PC6 11 30 D4
specifically used for this purpose. Fig 4.26 shows the pin PC5 12 29 D5
PC4 13 28 D6
layout of the chip. It is a 40-pin chip with three PC0 14 27 D7
independent 8-bit ports, named as A, B and C. Each port PC1 15 26 VCC
PC2 16 25 PB7
can be configured as input or output. Apart from the 24 PC3 17 24 PB6
pins (PA0-PA7, PB0-PB7, PC0-PC7), the remaining 16 PB0 18 23 PB5
PB1 19 22 PB4
lines of 8255 are used for interfacing the chip with the PB2 20 21 PB3
8051 (or any other processor). Fig 4.27 shows the Fig 4.26: 8255 pin layout
grouping of pins with respect to their functionality and
recommended connections. It has been
detailed in the following. D0‐D7 PA
D0-D7: These are data pins, generally
8255
𝐑𝐃, 𝐖𝐑: These are control signals
provided by the 8051 to direct a read A0
operation or a write operation onto the A1 PC
registers/ports of the 8255. CS
160 | Microcontrollers and Applications
transfer to the 8255, the CS must be set to low. The values of A1 and A0 will decide the
port/register selection as noted in Table 4.4.
0: Output
0: Output
0: Mode 0
1: Mode 1
0: Output
0: Output
00: Mode 0
01: Mode 1
0: BSR mode
1x: Mode 2
1: I/O mode
word to the
1: Input
1: Input
1: Input
1: Input
Port CU
Port CL
Port B
Port A
control register.
Fig 4.28 shows
the bit setting
needed for Fig 4.28: Control word format of 8255
different modes of
operation of the ports. The ports A, B and C are put into two groups. Group A corresponds to the
Port A and the upper 4-bits of Port C (CU). Group B corresponds to the Port B and the lower 4-bits
of Port C (CL). The mode settings are as follows.
1. Mode 0, Simple I/O. This mode can be used to program any of the ports A, B, CU and CL as
input or output. Entire 8-bits (for A and B) or 4-bits (for CU and CL) are to be configured as
either input or output, individual bits within a port cannot be programmed differently. This is
the most common mode used in 8255 based port interfacing. For example, to set all the three
ports in output mode, the control word should be “10000000”, that is, 80H. Similarly, to set Port
A as input and all the remaining three (Port B, CU and CL) as output, the control word should
be “10010000”, that is, 90H.
2. Mode 1, Handshaking. In this mode, ports A and B can be used as input or output with the port
C bits providing handshaking signals.
3. Mode 2, Bidirectional Handshaking. In this mode, port A can be used as bidirectional I/O port
with handshaking signals through port C. Port B bits can be used in either Mode 0 or Mode 1.
4. Bit Set/Reset (BSR) Mode. In this mode, individual bits of Port C can be programmed
independently.
Microcontrollers and Applications | 161
Fig 4.29
shows the RD
interfacing of 8255 P3.7
with the 8051. It has P3.6 WR
been assumed that A15 WR RD
P2.7
8051
the 8255 will get PA
P2.6 A14 CS
selected only for
8255
addresses with A15 A0 PB
= A14 = 1. As shown ALE G A0
A1
Latch
in Table 4.4, Port A AD0‐7 A1
P0 PC
gets selected for A1 A7 D0‐7 Reset
= 0, A0 = 0. Thus,
for data transfer
through Port A, the Fig 4.29: Interfacing 8255 with the 8051
address should be
“11xxxxxxxxxxxx00”. Similarly, for the ports B, C and control register, the addresses should be
“11xxxxxxxxxxxx01”, “11xxxxxxxxxxxx10” and “11xxxxxxxxxxxx11”, respectively. One set of
addresses for the ports A, B, C and the control register can thus be, C000H, C001H, C002H and
C003H, respectively. It may be noted that many more addresses are possible, as most of the bits
are don’t cares.
The following assembly language program can be used to output patterns to the ports A, B
and C in such a fashion that the 8-bit outputs in each port are “01010101” (55H) followed by
“10101010” (AAH) continually. For this, the ports are first configured as output ports by writing
the control word 80H to the control register. The program then enters into an infinite loop to output
the patterns. The DPTR register has been used as 16-bit address pointer for the 8255 addresses.
ORG 0
MOV DPTR, #0C003H ; DPTR points to control register
MOV A, #80H ; Load control word
MOVX @DPTR, A ; Issue control word
MOV A, 55H ; Load 55H to A
L1: MOV DPTR, #0C000H ; DPTR points to Port A
MOV @DPTR, A ; Output to Port A
INC DPTR ; DPTR points to Port B
MOV @DPTR, A ; Output to Port B
INC DPTR ; DPTR points to Port C
MOVX @DPTR, A ; Output to Port C
CPL A ; Complement A
ACALL DL_RTN ; Call Delay routine
162 | Microcontrollers and Applications
SJMP L1 ; Continue
DL_RTN: MOV TMOD, #01 ; Timer 0, Mode 1
MOV TL0, #0E0H ; Load TH and TL
MOV TH0, #0B1H ; 0B1E0H for 20ms delay
SETB TR0 ; Start timer
AGAIN: JNB TF0, AGAIN ; Monitor Timer 0
CLR TR0 ; Stop Timer 0
CLR TF0 ; Clear Timer 0 flag
RET
END
The C language program for the 8255 interface can be as follows. Many of the 8051
compilers support a macro called XBYTE for external memory access. As in this case, the 8255
ports are accessed as external memory locations, the macro has been utilized.
#include <reg51.h>
#include <absacc.h>
void delay_rtn( unsigned int del_val );
void main()
{
unsigned char pattern; // Pattern to be sent to ports
XBYTE[0xC003] = 0x80; // Configure all ports as output
while (1) {
pattern = 0x55;
XBYTE[0xC000] = pattern; // Send 55H to all ports
XBYTE[0xC001] = pattern;
XBYTE[0xC002] = pattern;
delay_rtn( 100 ); // Put a delay
pattern = 0xAA;
XBYTE[0xC000] = pattern; // Send 0AAH to all ports
XBYTE[0xC001] = pattern;
XBYTE[0xC002] = pattern;
delay_rtn( 100 ); // Put a delay
}
}
void delay_rtn( unsigned int del_val )
{
Microcontrollers and Applications | 163
unsigned int x, y;
for (x = 0; x < 1000; x++)
for (y = 0; y < del_val; y++);
}
It may be noted that Mode 0 is the most common one for 8255 interfacing. Other modes
are used for more sophisticated devices (such as, printers) that have bidirectional handshaking lines
for interface.
UNIT SUMMARY
Interfacing input-output devices is very important for any microcontroller based system,
interacting with the real-world. As the 8051 is a digital device, the simplest input device to interface
is a switch while the simplest output device is a LED. As switches are mechanical in nature,
debouncing is necessary to overcome the jitter. An example of more complex switch device is a
matrix keyboard. A hexadecimal matrix keyboard can be interfaced using two ports of the 8051,
by repeatedly scanning the rows and columns. In the display domain, LCDs have gradually replaced
the LED based displays. LCD interfacing requires set of commands to be sent to it from the 8051.
Analog world interfacing requires connecting analog-to-digital and digital-to-analog converters to
interact with the environment. ADCs are also used to interface various sensors with the 8051. The
number of I/O pins of 8051 appear to be insufficient for many applications, as most of the pins are
assigned more than one function. To solve this problem, often the 8255 chip is interfaced. This chip
provides three, 8-bit ports. The ports can be utilized to connect other devices to the 8051. Though
8255 has a number of modes of operations, the most common one configures the ports as simple
input or output ports. This has been discussed in detail. Thus, this unit has provided a very good
overview of interfacing devices and chips to the 8051.
EXERCISES
Multiple Choice Questions
164 | Microcontrollers and Applications
(A) (i) (B) (i), (ii) (C) (ii), (iv) (D) (ii)
MQ4. For interfacing an LED with 8051 port, if P = 1, which configuration will glow the LED?
(A) (i) (B) (i), (ii) (C) (ii), (iv) (D) (ii)
MQ5. Which type of LED displays need common side to be grounded?
(A) Common anode (B) Common cathode
(C) Both common anode and common cathode (D) None of the displays
MQ6. Which type of LED displays need common side to be tied high?
(A) Common anode (B) Common cathode
(C) Both common anode and common cathode (D) None of the displays
MQ7. In Fig 4.13 if a decoder is used to produce the module selection inputs in interfacing 4 7-
segment displays, the decoder should be of size
(A) 1-to-2 (B) 2-to-4 (C) 3-to-8 (D) None of the other options
MQ8. For matrix keyboard, debouncing can be implemented using
(A) Hardware techniques (B) Software techniques
(C) Both hardware and software techniques (D) None of the other options
MQ9. In a 4x4 matrix keyboard operation, software debouncing is performed by
(A) Reading each row twice
(B) Writing 0 to more than one columns
(C) Reading each row more than twice
(D) None of the other options
MQ10. For matrix keyboard, debouncing helps to
(A) Read one key when multiple keys are pressed
Microcontrollers and Applications | 165
(B) Read a key only once avoiding vibrations
(C) Sense one key multiple times
(D) None of the other options
MQ11. A 4x4 matrix keyboard is interfaced with 8051 via ports P0 and P1. The rows and
columns of the keyboard are pulled high via resistances. To check whether all keys are
released,
(A) All-zero be written to P0 and P1 be read for all 1
(B) All-zero be written to P1 and P0 be read for all 1
(C) Either port can be used to write zeros while the other to read for all 1
(D) None of the other options is valid
MQ12. In a 4x4 matrix keyboard with keys 0 to F, keys are arranged on a row-major format
(keys 0-3 forms first row, 4-7 second row, and so on). Rows are scanned one-by-one. If
the keys 8 and F are pressed simultaneously, number of 0-bits in the pattern read at a time
is
(A) 1 (B) 2 (C) 0 (D) 4
MQ13. Which display device(s) require(s) refreshing?
(A) 7-segment (B) LCD
(C) Both 7-segment and LCD (D) None of the other options
MQ14. In LCD module, busy status is reflected at pin
(A) DB0 (B) DB3 (C) DB5 (D) DB7
MQ15. In LCD devices setting RS to 0 selects
(A) Instruction command code register (B) Data register
(C) Status register (D) Control register
MQ16. The appropriate pin of a processor to which the Start Conversion (SC) line of ADC be
connected to is
(A) Port bit (B) Interrupt
(C) Either a port bit or interrupt (D) Neither port bit nor interrupt
MQ17. The appropriate pin of a processor to which the End of Conversion (EOC) line of ADC
be connected to is
(A) Port bit (B) Interrupt
(C) Either a port bit or interrupt (D) Neither port bit nor interrupt
MQ18. With the reference voltage as 10V, the step size of a 10-bit ADC will be
(A) 9.76mV (B) 10mV (C) 2.56mV (D) None of the other options
MQ19. Number of digital output bits of DAC0808 is
(A) 8 (B) 4 (C) 12 (D) None of the mentioned
MQ20. If an 8-bit output port of the 8051 drives a DAC to produce a sawtooth waveform, the
most appropriate value to be output after 255 is
(A) 0 (B) 127 (C) 254 (D) 256
MQ21. The device converting one energy form to another is called a
(A) Transformer (B) Transducer (C) Sensor (D) Actuator
MQ22. A signal conditioning circuit is generally used before
(A) ADC (B) DAC
166 | Microcontrollers and Applications
(C) Both ADC and DAC (D) None of the other options
MQ23. In 8255, port requiring external pull-up is
(A) A (B) B (C) C (D) None of the other options
MQ24. In 8255, control word is written to
(A) A (B) B (C) C (D) None of the other options
MQ25. In 8255, bit addressability is available with port
(A) A (B) B (C) C (D) D
Microcontrollers and Applications | 167
Practical Problems
PQ1. Design the hardware and software to interface 2, 8-bit DIP switches to the ports P1 and P2
of the 8051. The switch settings are to be displayed on 8 LEDs connected to the port P0,
alternately.
Hint: Use the template in Example 4.1. Another DIP switch to be connected to port P2. The
program should be modified to display the settings alternately to the LEDS in port P0.
PQ2. Design the hardware and software to interface a 4 4 hex keyboard. The program should
work on the principle of column scanning. That is, at a time, one of the columns be made 0
and the rows be checked for a keypress in a row.
Hint: Use the template in Section 4.3. Port P1 should be an input port and P2 output port. The
program be modified accordingly to reverse the role of row and column scanning.
PQ3. Design a rolling display with 4, 7-segment LED modules. It should display the numbers 0 to
9 continually. To have the rolling effect, periodically a display module should copy the digit
currently being displayed by its right neighbour and the rightmost module displaying the
next digit in sequence.
Hint: Use the template in Section 4.4. To have rolling effect, an “update_buffer” routine may be
developed and called periodically to update the buffer content corresponding to the digits to
be displayed.
PQ4. Repeat PQ3 for an LCD module.
Hint: Refer to Section 4.5.
PQ5. Design the hardware and software to interface an ADC with the 8051.
Hint: Refer to Section 4.6.
PQ6. Design the hardware and software to generate a smooth sine wave through DAC using 8051.
Hint: Refer to Example 4.3.
PQ7. Interface an 8255 chip with the 8051.
Hint: Refer to Section 4.9.
KNOW MORE
The analog-to-digital converters discussed in this unit are parallel in nature. They provide
the digital output as 8-bit parallel data. This often creates problem to route all the 8 lines through
the PCB, particularly if the system has a number of chips mounted on the board. A variation to this
provides the converted data in serial fashion, with one bit clocked out on each high-to-low transition
of the clock signal. This effectively reduces the data out pins from eight to one. A typical example
of such ADC is MAX1112 which is an 8-bit serial ADC.
168 | Microcontrollers and Applications
Similar to LM35 which is a temperature sensor working on the Celsius scale, its variant
LM34 works for Fahrenheit scale. It works in the range of -50 to +300 degree Fahrenheit. These
sensors are highly linear in nature. However, many sensors do not provide linearity over their entire
range of operation. They require special circuitry to get a linear behaviour. The same compensation
can also be done in software.
5
Microcontrollers and Applications | 169
Introduction to Advanced Processors
d and Concepts
UNIT SPECIFICS
Through this unit we have discussed the following aspects:
Understanding the basics of CISC and RISC architectures;
Comparing the features of RISC vs. CISC;
Overview of the advanced microcontroller PIC;
Understanding the basics of AVR microcontroller;
Overview of the ARM architecture;
Features of LPC214x series of microcontrollers developed around ARM7;
Input-Output programming with LPC2148 microcontroller.
The discussion in this unit is to give an overview of advanced microcontrollers. It has started
with the basics of and differences between the CISC and the RISC architecture principles. It has
covered the advanced processors like PIC, AVR and ARM. It has been assumed that the reader has
a good understanding of conventional processor architectures, microprocessors and
microcontrollers. A good number of examples have been included to explain the concepts, wherever
needed.
A large number of multiple choice questions have been provided with their answers. Apart from
that, subjective questions of short and long answer type have been included. A few practical
problems with solution hints have been provided. A list of references and suggested readings have
been given, so that, one can go through them for more details. The section “Know More” has been
carefully designed so that the supplementary information provided in this part becomes beneficial
for the users of the book. This section mainly highlights the recent developments and application
areas with advanced microcontrollers like ARM.
RATIONALE
This unit on introduction to advanced microcontrollers helps the reader to understand the basics
of advanced microcontrollers that are in use in different applications. The requirements of such
devices include less area, high performance with built-in peripheral and communication modules.
The unit starts with a discussion on CISC and RISC architectures. The two philosophies have been
explained with distinction between them. After that, advanced microcontrollers have been
170 | Microcontrollers and Applications
presented. In this category, first the PIC microcontroller series, PIC18F has been taken up.
Another very common microcontroller comes from the AVR series. The ATmega32 series
microcontroller has been illustrated to bring out the essence of the AVR family. The ARM
microcontrollers have come up almost as default for the low power advanced microcontroller
applications. The ARM architecture has evolved a lot – starting from the ARM1 to the advanced
Cortex series. The ARM7 series is an intermediary that works well for understanding the features
and acts as a link between the older and the recent processors of ARM. ARM7 architecture has
been discussed in sufficient detail. A particular implementation of ARM7, LPC214x series has been
presented along with the input-output programming features that can make the reader understand
the basics and capabilities of the series. Thus, the unit gives bird’s-eye-view of advanced
microcontroller based system design.
PRE-REQUISITES
Electronics: Units 1, 2, 3, 4 of the book
UNIT OUTCOMES
List of outcomes of this unit is as follows:
U5-O1: State the basic features of CISC and RISC architectures
U5-O2: Compare between the features of RISC and CISC
U5-O3: Enumerate the internal architecture of PIC microcontrollers
U5-O4: Enumerate the internal architecture of AVR microcontrollers
U5-O5: State the features of ARM
U5-O6: Enumerate the ARM7 architecture
U5-O7: Develop hardware and software for I/O programming with LPC2148
Microcontrollers and Applications | 171
MA
5.1 Introduction
In order to get some fruitful computation done, a processor interacts with the memory for
instructions and data. The instruction set supported by a processor is fixed at its design time. Thus,
the processor designer has the liberty to make the processor powerful enough to handle complex
operations by its individual instructions directly. This increases the complexity of the processor
hardware design. The alternative approach for the designer may be to support simple machine
instructions only by the processor, while the complex operations of high-level languages are to be
realized by a group of machine instructions. Here, the job of translating complex high-level
operations into a sequence of simple processor instructions, is carried out by optimizing compilers.
Both the approaches are effective, however, needs special care at the hardware and/or software
level.
1. The multiplication of two memory operands may be implemented directly in the hardware, via
a machine instruction,
MULT a, b ; a=a b
However, to implement it in hardware, the operands a and b are to be brought into CPU
registers first. The register contents are then multiplied, storing the result in some third register.
Content of this third register is then copied back to a. The primary advantage of the approach
is that the high-level language compiler does not need to do much work, since matching
machine instruction is directly available and all sub-operations are taken care of by the
processor itself. Of course, the overall multiplication instruction takes a number of clock
cycles.
2. The other option may be to have the machine instruction MULT working only on CPU
registers, loading and storing of operands being taken care of by separate LOAD and STORE
instructions. The approach makes the processor hardware simple, however, the job of the
compiler increases significantly as it has to determine the best possible instruction subsequence
to realize a high-level operation.
The first approach is commonly known as Complex Instruction Set Computer (CISC) while
the second one is known as Reduced Instruction Set Computer (RISC). A computer’s performance
ability is often expressed by the following equation.
172 | Microcontrollers and Applications
𝑡𝑖𝑚𝑒 𝑡𝑖𝑚𝑒 𝑐𝑦𝑐𝑙𝑒𝑠 𝑖𝑛𝑠𝑡𝑟𝑢𝑐𝑡𝑖𝑜𝑛𝑠
𝑝𝑟𝑜𝑔𝑟𝑎𝑚 𝑐𝑦𝑐𝑙𝑒 𝑖𝑛𝑠𝑡𝑟𝑢𝑐𝑡𝑖𝑜𝑛 𝑝𝑟𝑜𝑔𝑟𝑎𝑚
The CISC approach attempts to minimize the number of instructions per program, while the RISC
approach attempts to reduce cycles per instruction. The CISC sacrifices the number of cycles per
instruction, while RISC sacrifices the required number of instructions per program. The following
example illustrates the situation better.
Example 5.1: Consider a program with 80% instructions simple and 20% complex. For CISC
implementation, let each simple instruction take 4 cycles and complex instructions 10 cycles,
cycle time being 100 ns. For RISC implementation, simple instruction takes one clock cycle.
Also, let any complex operation take on an average, 12 simple instructions. Cycle time for RISC
is assumed to be 75 ns.
Then, time needed by the CISC processor to execute a program with 106 instructions will be
given by,
10 0.80 4 10 0.20 10 100 10 = 0.52 sec.
The time needed by the RISC processor for the same program will be about,
Thus, in this case, the RISC processor is expected to accomplish the program in less than
half the time needed by the CISC processor.
1. CISC processors support a large number of instructions, typically more than 200. The
instructions are complex in nature. The complexity comes primarily from the amount of
computation done in the individual instructions. For example, an instruction may compute “s
= s + ai bi” to facilitate multiply-accumulate type operations. However, the instruction, in
turn, includes a multiplication and an addition, which are much simpler in nature. Many
different data types may also be supported for the operands, such as, byte, word, double word
etc.
2. Supports addressing modes, some of which may be quite complex in nature. Apart from the
direct, indirect and immediate modes (as for the 8051), a CISC processor may support auto-
increment and auto-decrement modes among others. These modes are similar to the indirect
mode with the additional feature of index register being incremented (for auto-increment) or
Microcontrollers and Applications | 173
decremented (for auto-decrement) automatically, after accessing a memory location. These are
useful for operations that modify each element of an array. However, this makes the instruction
format complex and require additional time/hardware to modify the index register.
4. The controller for the processor is generally implemented using microprogramming techniques.
Microcoding of new instructions provide the flexibility of making CISC machines upwardly
compatible: a new computer would run the same programs of earlier computers, as the
instruction set of the new processor is a superset of the same for the earlier processors.
However, microprogrammed control units are slower than complete hardwired units.
5. Small code size for programs. As the individual instructions are complex, they can correspond
to more computation. Thus, the size of the user program is expected to be less.
6. Instruction decoding is complex. This happens due to the requirement of supporting large
number of instructions with non-uniform format. Having more addressing modes makes the
problem of decoding further difficult.
7. Less number of general purpose registers. Many of the operations are performed with the
operands present in memory only. The result is also stored in memory. This reduces the
requirements of general purpose registers. To support special instructions, some additional
special purpose registers may get introduced.
Example 5.2: Let us consider the Intel i486 as an example of a typical CISC processor. It is a
32-bit integer processor along with an on-chip floating-point unit. The processor supports 235
instructions of size varying from 1 to 12 bytes. Eleven different addressing modes are supported.
There are eight general-purpose registers. Instructions are executed following different execution
models: register-register, register-memory and memory-memory. As the decoding of
instructions become a significant problem, instruction execution is divided into five pipelined
stages: Fetch, Decode1, Decode2, Execute and Write-Back.
174 | Microcontrollers and Applications
Though the CISC processors may possess the advantages of compiler simplification,
smaller program size and expected faster program execution (due to hardware solution for complex
operation), there are several disadvantages also, as listed next.
1. Large number of complex instructions require complex hardware, escalating the area, delay
and power requirements of the associated circuitry. More number of decoding steps in i486 is
a clear indication in that direction.
2. Complex instructions are introduced in CISC to match with instructions available in high-level
languages. However, a small mismatch between them may turn the complex machine
instruction to be mostly useless. The problem gets aggravated further if a number of high-level
languages are to be supported. One complex instruction of CISC may not match with variations
in similar instructions across all high-level languages supported. As a result, the compiled
program may become inefficient.
3. Compiler simplification may not always be achievable. Optimizer may find it difficult to
realize the intended computation of a high-level language program by using individual machine
instructions which themselves are not very simple and uniform in nature.
4. Advantage of small program size may not be very beneficial as the cost of memory chips is
declining at a rapid rate. Moreover, with the increasing instruction size (for example, upto 12
bytes in i486), overall code size reduction may not be significant.
5. As instructions are highly non-uniform in terms of size and execution time, supporting
instruction pipelining becomes an issue.
In the last section, we have seen CISC approach to solve the problem of efficient execution
of high-level language programs by the processor. It has been observed that the approach has
several drawbacks, as well. The other extreme in processor design is to have a simple instruction
set in which all instructions are of same size and takes same amount of time (typically, one cycle)
to execute. This second approach is followed in designing the Reduced Instruction Set Computer
(RISC) processors. The main characteristics of a RISC processor are as follows.
1. It possesses a small number of simple instructions only. Simplicity comes in terms of size of
the instruction and its execution time. Instruction size is kept such that it can be fetched in a
single memory access, that is, memory word size.
Microcontrollers and Applications | 175
2. Compared to CISC architecture, the controller in a RISC processor is often hardwired. This
makes it possible to run the processor fast. CPU also takes less silicon area and possibly less
power/energy to execute programs.
4. Only simple addressing modes are supported. This reduces the instruction complexity
significantly.
5. A large number of registers is made available to the programmer. Variables and intermediate
results of a computation are stored in registers, so that repeated loading from memory is not
needed. Similarly, local variables and parameters of a procedure are allotted space in CPU
registers.
Example 5.3: Let us consider the RISC processor SPARC. This is a 32-bit processor having an
integer unit and a floating point co-processor. It has only 69 basic instructions. There are 40 to
520 general purpose registers, each of width 32 bits. The registers are grouped into 2 to 32
overlapping register windows. A register window is assigned to a procedure. Thus, it is ensured
that the registers of the
calling procedure are not Level m
inadvertently modified
by instructions in the Parameter Local Temporary
called procedure. The Registers Registers Registers
overlapping of windows
of caller and called Call / Return
procedures help in Level m + 1
passing parameters and
return values between Parameter Local Temporary
them. Fig 5.1 illustrates Registers Registers Registers
the idea in which a Level
m procedure has called Fig 5.1: Overlapping Register Windows
another one (at level
m+1). Temporary registers of level m procedure have been overlapped with the parameter
registers of the called procedure at level m+1. Thus, parameters need not be passed separately to
the called procedure, these are already available in its register window.
However, RISC is also not free from all disadvantages. The following issues need to be
taken care of.
176 | Microcontrollers and Applications
1. An operation of high-level language may need multiple machine instructions. This effectively
increases the number of memory accesses for certain applications.
3. Despite their advantages, RISC chips require software support. In particular, availability of a
good optimizing compiler that can utilize the instruction set effectively, is a must for the
success of RISC technology.
4. Some of the CISC features, like hardware support for loop, copying a chunk of data from a
source memory block to a destination memory block etc. are required by the programming
community.
Table 5.1 summarizes the major differences between the CISC and the RISC architectures.
However, neither RISC nor CISC has come up as a better alternative. As a result, the
microcontrollers and other processors being designed in the recent time are tried out to have the
better features of both the alternatives incorporated into them. In the following we shall look into
three such advanced microcontrollers – PIC, AVR and ARM.
Microcontrollers and Applications | 177
5.4 PIC Microcontroller
PIC – Programmable Interface Controller, microcontrollers are one of the popular set of RISC
based processors, introduced in the year 1993 by the General Instruments. These have been widely
used in different applications, including smartphones, audio accessories and advanced medical
devices. There are different variants of PIC, however, PIC18F constitute the advanced one. In the
following, we shall concentrate on the PIC18F series only. Fig 5.2 shows the pin configuration of
the PIC18F452.
PIC18F452
RA5/AN4/SS/LVDIN RB1/INT1
RE0/AN5/RD RB0/INT0
RE1/AN6/WR VDD
RE2/AN7/CS VSS
VDD RD7/PSP7
VSS RD6/PSP6
OSC1/CLKI RD5/PSP5
RA6/OSC2/CLKO RD4/PSP4
RC0/T1OSO/T1CKI RC7/RX/DT
RC1/T1OSI/CCP2 RC6/TX/CK
RC2/CCP1 RC5/SDO
RC3/SCK/SCL RC4/SDI/SDA
RD0/PSP0 22 RD3/PSP3
RD1/PSP1 20 21 RD2/PSP2
Fig 5.2: Pin Configuration of PIC18F452
178 | Microcontrollers and Applications
Data Bus (8 bit)
RA0/AN0
RA1/AN1
Table Pointer Data Latch RA2/AN2/VREF‐
Port A
RA3/AN3/VREF+
Data RAM RA4/T0CKI
upto 4K RA5/AN4/SS/LVDIN
inc/dec logic RA6/OSC2/CLKO
Address Latch
Address Bus PCLATU PCLATH RB0/INT0
(21 bit) RB1/INT1
RB2/INT2
Port B
PCU PCH PCL RB3/CCP2
Program Counter RB4
RB5/PGM
Address Latch BSR Bank0, F RB6/PGC
RB7/PGD
Program Mem.
upto 2M 31 Level Stack FSR0 RC0/T1OSO/T1CKI
Data Latch FSR1 RC1/T1OSI/CCP2
FSR2 RC2/CCP1
Port C
Table Latch RC3/SCK/SCL
RC4/SDI/SDA
RC5/SDO
inc/dec RC6/TX/CK
ROM Latch Decode logic RC7/RX/DT
RD0/PSP0
Instruction RD1/PSP1
RD2/PSP2
Port D
Register
RD3/PSP3
RD4/PSP4
Instruction RD5/PSP5
Decode & Control PRODH PRODL RD6/PSP6
RD7/PSP7
T1OSCI OSC2/CLKO
T1OSCO OSC1/CLKI
8‐bit Multiplier RE0/AN5/RD
Port E
Timing Power‐up Timer
RE1/AN6/WR
Gen.
VDD, VSS
Master Parallel
CCP1 CCP2 Synchronous USART Slave Port
Data EEPROM
Serial Port
of PIC18F452
Fig 5.3: Block diagram
Microcontrollers and Applications | 179
Fig 5.3 shows the internal block diagram. It has an 8-bit CPU, 2 Mbyte program memory, 256 bytes
to 1 kB EEPROM, upto 3968 bytes of on-chip SRAM, 4kB to 128 kB flash program memory.
Sophisticated timers are available that can perform functions, such as, input capture, output
compare, pulse width modulation, real-time interrupt and watchdog timer. Several serial
communication protocols are supported, namely, Serial Communication Interface (SCI), Serial
Peripheral Interface (SPI), Inter-Integrated Circuit (I2C) and Controller Area Network (CAN). A
10-bit Analog-to-Digital converter (ADC) is available. The CPU can operate at upto 40 MHz crystal
oscillator. Further, instruction pipelining is used to increase the performance of the processor to
one instruction per cycle. The microcontroller follows Harvard architecture in which the program
and the data memory are separate. The two memories have their individual address and data buses.
The policy allows simultaneous access for data and instruction in program execution.
The CPU contains an 8-bit ALU, an 8-bit working accumulator register (WREG) and an
8-bit multiplier. The lower byte of the 16-bit multiplication result is stored in the PRODL register,
higher order 8 bits in PRODH. The program memory address is 21-bit wide, corresponding to a
maximum of 2 MB space. However, the PIC18F452 has only 32 kB program memory, requiring
15-bit address bus only – 6 bits are left unused. Instructions stored in the program memory are
either 2-bytes or 4-bytes wide with the least significant byte always stored at an even address. A
table pointer is used access tables and data stored in the program memory. A 31-level stack stores
the return addresses from subprogram calls and interrupts. The stack is not part of any other
memory and is controlled separately by a 5-bit stack pointer, initialized to 0, on reset. The data
memory is of size upto 4 MB with a 12-bit address bus. In PIC18F452, the data memory size is
1536 bytes, organized as 6 banks of 256 bytes each. This makes the lower part of the data memory,
the upper part being dedicated to special function registers (SFRs). The SFRs control the operations
of peripheral units (such as, timers/counters, ADC, interrupts, serial communication and so on),
selection of clock sources, watchdog operations etc. The SFRs are programmed during the
programming of the flash memory.
5.4.1 Timers
The PIC18F452 has four timers named as Timer0, Timer1, Timer2 and Timer3. An
overview of the timers is presented next.
Timer0: This timer can be made to operate either in 8-bit mode or in 16-bit mode. It supports 8-
bit programmable prescaler. The clock source can be internal or external. Thus, it can act
both as a timer and a counter. The timer is capable of generating interrupt on overflow. The
SFR T0CON controls the operation of this timer.
Timer1: This is a 16-bit timer controlled by the SFR T1CON. It can also work as a timer or a
counter. The prescalar value can be 1, 2, 4 or 8 only.
Timer2: It is an 8-bit timer that has a Period register associated with it. An interrupt is generated
when the timer value becomes equal to the Period register value. The timer has
programmable prescalar and postscalar.
Timer3: It is similar to Timer1 in operation.
Capture: In capture mode, a CCP module acts like a stopwatch. The time corresponding to the
occurrence of an event is recorded, however, the clock continues to run (unlike stopwatch
that stops on occurrence of the event). The 16-bit time value of Timer1 or Timer3
(depending upon the control register setting) is captured into CCPRxH:CCPRxL.
Compare: In this mode, the 16-bit content of CCPRxH:CCPRxL is compared continually with the
Timer1 or Timer3 value. For CCP1 module, when a match occurs, RC2/CCP1 pin gets
affected. The change in the pin is programmable to become high, low, toggle, no change
or to generate an interrupt. RB3/CCP2 pin gets affected for CCP2 compare operation.
PWM: The CCP module can be made to produce a pulse width modulated output at CCP1 or
CCP2 pin. It’s operation is controlled by Timer2. The period and duty cycle can be
specified. The timer values, CCPRxL and CCPxCON registers are to be loaded
accordingly.
Microcontrollers and Applications | 181
5.4.3 Analog-to-Digital Converter Module
The PIC18F family contains a 10-bit ADC that can support multiple analog channels. In
PIC18F452, there are eight channels AN0-AN7 shared by the pins of ports PORTA and PORTE.
The SFR ADCON0 and ADCON1 controls the operation of the ADC. The converted digital values
are made available at ADRESH (higher order 2-bits) and ADRESL (remaining 8-bits) registers. If
enabled, an interrupt is generated at the completion of the conversion process. To connect an analog
source to any of the analog input pins AN0 to AN7, it is recommended to ensure that the source
resistance is limited to 2.5 kΩ.
5.4.4 Interrupts
The sources of interrupts in the PIC18F452 can be classified into two categories – core
interrupt sources and peripheral interrupt sources. The core interrupt sources include the following.
The interrupts can be grouped into two groups by the programmer – high priority and low
priority. All the high-priority interrupts vector to address 00008H, whereas all low-priority
interrupts jump to the address 00018H. There are a number of registers controlling the operation,
enabling/disabling of interrupts.
182 | Microcontrollers and Applications
Register Direct: The instruction uses an 8-bit value to directly identify the register. For
example, in the instruction “movwf 0x20, A”, copies the WREG register to the data register
0x20.
Immediate: The operand value is directly specified in the instruction. For example, the
instruction "addlw 0x10” adds the value 0x10 to the WREG register.
Inherent: The operand is implied in the instruction. For example, in the instruction “andlw
0x3C”, the value 3CH is ANDed with the WREG. Here, the operand WREG is inherent.
Indirect: Here, a special function register is used as a pointer to the actual data register. For
example, in the instruction “movwf INDF0”, INDF0 gives the indirect operand.
Thus, PIC18F provides a limited set of addressing modes with 2- and 4-byte instruction format.
Detailed discussion about the instruction set of PIC18F is beyond the scope of the book. The readers
may look into the references noted at the end of the unit for more detail.
2 kB Static RAM
32, 8-bit general purpose registers
32 kB Flash
1 kB EEPROM
Programmable USART
10-bit ADC with 8 analog channels
One 16-bit, two 8-bit timer/counter
SPI interface
32, programmable I/O limes
Four PWM channels
Programmable watchdog
Microcontrollers and Applications | 183
On-chip boot program
Fig 5.4 shows the pin
diagram for ATMega32. It PB0/XCK/T0 1 40 PA0/ADC0
has 40 pins. Two pins are PB1/T1 2 PA1/ADC1
for power supply and PB2/INT2/AIN0 PA2/ADC2
PB3/OC0/AIN1 PA3/ADC3
ground. Pins 12 and 13 are
PB4/SS PA4/ADC4
for oscillator. Pin 9 is the
PB5/MOSI PA5/ADC5
ATmega32
reset pin. Three pins are PB6/MISO PA6/ADC6
dedicated to the power PB7/SCK PA7/ADC7
supply and reference for the RESET AREF
VCC GND
internal ADC. There are 32
GND AVCC
I/O pins arranged into 4 XTAL2 PC7/TOSC2
groups of 8-bit ports. Port A XTAL1 PC6/TOSC1
can be used for digital I/O or PD0/RXD PC5/TDI
as eight analog input PD1/TXD PC4/TDO
PD2/INT0 PC3/TMS
channels. Timer 0 and PD3/INT1 PC2/TCK
Timer 2 are 8-bit timers, PD4/OC1B PC1/SDA
while Timer 1 is a 16-bit PD5/OC1A 22 PC0/SCL
timer. It supports SPI, I2C PD6/ICP1 20 21 PD7/OC2
and USART standards. Fig Fig 5.4: Pin Configuration of ATmega32
5.5 shows the block diagram
of ATmega32.
ATmega32 has on-chip analog comparator, an interrupt has been assigned to it that is
generated based on the results of comparison. Three external interrupt pins are supported. Sensing
of the interrupts are also programmable. The device can operate at a frequency from 1 to 16 MHz.
As noted earlier, most of the instructions take one clock cycle, while multiplication takes two clock
cycles. On-chip debugging facilities are available through JTAG Boundary Scan. There are 32, 8-
bit general purpose registers in the ATmega32, named R0-R31. There are three 16-bit registers X,
Y and Z. These registers overlap with the general purpose registers R26 to R31. The three registers
could be used as
address pointers, Table 5.4: Programmer Model
or to contain data Category Name Number Size Function
values wider than General purpose R0-R31 32 8 bit Store data
8 bits. The Z working register
register could be Address pointer X,Y, Z 3 16 bit Address pointer
used to access the Stack pointer SP 1 16 bit Stack access
program memory. Program counter PC 1 14 bit Address of instruction
The registers Status register SREG 1 8 bit Status information
available in the
ATmega32 programmer model have been listed in Table 5.4. The SRAM locations are used as
184 | Microcontrollers and Applications
PA0‐PA7 PC0‐PC7
PORTA DRIVERS/BUFFERS PORTC DRIVERS/BUFFERS
PORTA DIGITAL INTERFACE PORTC DIGITAL INTERFACE
AVCC
INTERNAL
OSCILLATOR
PROGRAM SRAM
FLASH XTAL1
WATCHDOG OSCILLATOR
TIMER XTAL2
INSTRUCTION GENERAL
REGISTER PURPOSE
REGISTERS
MCU CTRL.
& TIMING 𝑅𝐸𝑆𝐸𝑇
INSTRUCTION X
DECODER Y INTERRUPT INTERNAL
UNIT CALIBRATED
Z OSCILLATOR
CONTROL LINES
EEPROM
ALU
STATUS REG.
USART
PROGRAMMING
LOGIC SPI
+ COMP. INTERFACE
‐
PORTB DIGITAL INTERFACE PORTD DIGITAL INTERFACE
PORTB DRIVERS/BUFFERS PORTD DRIVERS/BUFFERS
PB0‐PB7 PD0‐PD7
Fig 5.5: Block
Diagram of ATmega32
Microcontrollers and Applications | 185
follows. The 32 general purpose registers occupy the SRAM locations from 00H to 1FH. I/O ports
span over the locations from 20H to 5FH, user data from 60H to 85H.
Immediate: Data encoded into the instruction itself. Operand is available in the Flash, the
program memory. For example, in the instruction “ldi r16, 0x56”, the operand 56H is put as part
of it. This is a marked deviation from Harvard architecture which says that the data is available
only in the data memory.
Direct: These are two-word instructions. One word specifies the address of the data memory
space. For example, the instruction “lds R1, K” where K is a 16-bit data memory address.
Indirect with displacement: In this case, along with an address pointer (X, Y or Z), a
displacement is also mentioned. For example, “ldd R1, Y+q” instruction copies the content of
memory location Y+q to R1.
Indirect with pre-increment: The content of the address pointer register is incremented before
accessing the addressed memory location. For example, in the instruction “ld R1, +X”, X is first
incremented. The memory location pointed to by this new X register content is copied to R1.
Indirect with post-increment: Similar to pre-increment, however, register increment takes place
after accessing the memory. For example, an instruction of this category may be “ld R1, X+”.
Similarly, there are indirect access modes with pre- and post-decrement operations.
Now that we have seen three different Table 5.5: Comparison of 8051, PIC, AVR
microcontrollers, namely 8051, PIC and AVR, Feature 8051 PIC AVR
Table 5.5 presents a comparison between them. Speed Slow Moderate Fast
The 8051 is one of the very simple
Memory Small Large Large
microcontrollers. However, the features available
CISC/RISC CISC RISC RISC
in it have been extended in the advanced
ADC No Yes Yes
controllers. Also, in the advanced
microcontrollers, many of the frequently used Timers Yes Yes Yes
peripherals have been included, so that overall PWM No Yes Yes
footprint of the system remains small.
The ARM microcontroller is a 32-bit RISC processor developed by the ARM Corporation,
previously known as Acron RISC Machine. However, ARM Corporation does not produce any
processor chip. Rather, the production of systems built around ARM based CPU is licensed to
186 | Microcontrollers and Applications
various companies, such as, NXP, STMicroelectronics, Texas Instruments, to name a few. The
licensee can develop their own processors compliant with the ARM instruction set. The following
are some of the notable features of the ARM architecture.
The ARM architecture is very simple. As a result, it requires less number of transistors in the
chip. As a whole system is built on a chip (called, System-on-Chip, SoC), more space on the
chip is made available to realize memory and other peripherals. The silicon die can
accommodate more amount of memory and various associated logic modules, such as, ADC,
Timers/Counters, SPI, I2C, USART, and so on.
Very carefully designed instruction set architecture with pipelined design that optimizes the
power consumption. As a result, the ARM has become almost the default choice for low-power
applications.
Supports two instruction sets. The default 32-bit instruction set is called the ARM instruction
set. However, another 16-bit instruction set, called THUMB, has been made available that
results in better code density and further power reduction.
Performance is often much higher than other contemporary advanced processors, possibly with
CISC architecture.
The design of the architecture is highly modular. In the entire design, only the integer pipeline,
responsible for integer arithmetic is mandatory. The designer has the choice to take other
modules (for example, real arithmetic), based upon the requirements.
Built-in JTAG debug port and on-chip embedded in-circuit emulator support full debugging.
The first version of the ARM, ARM1 was introduced in 1985 as a 26-bit RISC processor.
The 32-bit RISC processor, ARM7 was introduced in 1992. After that several other processor
architectures have been introduced over the years, namely ARM7, ARM8, ARM9TDMI, ARM10,
ARM11, Cortex etc. To have a basic understanding of the ARM architecture, we shall look into the
ARM7 architecture in more detail.
Incrementer Bus
one of the Address Register nExec
operand to the Data32
Bigend
PC Bus
ALU comes Address Prog32
through the A Incrementer Mclk
nWait
Instruction Decoder &
bus from the nRW
registers. The Register Bank nBW
Control Logic
other operand, 31, 32‐bit Register nIRQ
nFIQ
ALU Bus
B Bus
B bus passes Abort
through the nOPC
A Bus
Booth’s Multiplier nTrans
barrel shifter nMreq
module first. Seq
Lock
This enables nCpi
shifting/rotation Barrel Shifter Cpa
of the second Cpb
nM[4:0]
operand before
carrying out the 32‐bit ALU
operation. ARM7
supports three
stage pipelined Write Data Register Instruction Pipeline
Read Data Register
execution of
instructions, DBE Dout[31:0] nEnout Data[31:0]
similar to the
classical fetch- Fig 5.6: Block Diagram of ARM7
decode-execute
pipeline. In this structure, while the first instruction reaches the execute stage, a second one will be
in decode phase, while a third instruction will be memory fetch stage. The uniform size and similar
execution time for the instructions aid in smooth realization of the pipeline. In ARM7 pipeline, the
execute stage is heavily loaded. It has the responsibilities to read the operands, perform ALU
operation and write back the result. To have further balance between the stages, the later versions
of ARM processors contain 5, 6 and 8 stage pipeline structures.
188 | Microcontrollers and Applications
Large uniform set of registers having 16 general purpose registers accessible by the user. Such
set of uniform registers is called a register file.
Follows a load/store architecture model. In this model, instructions carrying out data operations
operate only on registers. Such instructions do not work with memory operands. Memory access
instructions are load and store only.
Addressing modes are simple. This simplifies the instruction decoding stage.
All ARM instructions are 32-bit wide and most of them have a regular three-operand encoding.
This uniformity enhances balance between the pipeline stages.
Interestingly, along with the features common to the pure RISC processors, ARM has
included some features of CISC also to improve the performance. Some such features are noted in
the following.
Each instruction has been given the capacity to control the ALU and the shifter. For example,
while a simple ADD instruction can add two operands, if necessary, the instruction can also get
one of its operands shifted through the use of shifter. This makes the instruction more complex
– closer to CISC.
Supported addressing modes have been enhanced by including the autoincrement and
autodecrement modes.
Multibyte load/store instructions have been introduced so that the CPU may be instructed to
move multiple bytes of data between memory and register file. Naturally, time for executing the
instruction is dependent upon the number of bytes moved – a violation of equal execution time
requirement of RISC instructions.
Each instruction has a four bit condition code attached to it. The instruction will get executed
only if the specified condition is satisfied (elaborated later).
Unlike many other processors, instructions involving the ALU operations, may or may not affect
the status flags. For example, pure ADD instruction does not affect the status flags. To ensure
that the status flags get affected, ADDS instruction has to be used.
The ARM processors can work in one of the six modes, namely, User mode, Fast Interrupt
Processing (FIQ) mode, Normal Interrupt Processing (IRQ) mode, Supervisor (SVC) mode,
Undefined (UNDEF) mode and Abort mode. The user mode is for normal execution of user
programs. A program in user mode can make a system call to reach the supervisor mode. There are
two types of interrupts supported by the ARM – fast and normal. In response to fast interrupt, the
processor reaches the FIQ mode, whereas for normal interrupts, it is the IRQ mode. The undefined
mode is entered if the received instruction code part is not understandable by the processor. Abort
mode corresponds to memory fault.
Microcontrollers and Applications | 189
Each mode has got its associated set of registers. There are 16 general purpose registers
R0-R15 in the user mode. Out of these, R15 is the program counter, however, unlike other
processors, the R15 can also be manipulated as a general purpose register. There is no stack defined
by default in ARM. If necessary, user has to implement stack as part of the program. The register
R13 is conventionally used by the users as stack pointer. In the absence of stack, for subprogram
call and return, the register R14 is used as the link register. In a procedure call, the current program
counter value (that is, the return address) is automatically copied into the R14 register. To
implement a return from the procedure, the R14 register is copied into R15. Each mode has got its
own copy of R13 and R14 registers. Apart from that, each mode has a status register of its own. All
modes, except the user mode has a register to save the content of the status register of its previous
mode. The FIQ mode has additional set of registers for R7-R12 also. This helps in writing the
service routines using the additional registers only which eliminates the necessity of saving and
restoring registers used by the interrupt service routine.
190 | Microcontrollers and Applications
Byte Data Transfer data LDR R0, [R8]; R0 = Mem[R8] 1, 2 or 4 bytes data
Transfer between memory LDR R0, [R1,-R2]; R0 = transfer
and registers Mem[R1 – R2] Base plus offset can be
LDR R0, [R1,#4]; R0 = used
Mem[R1 + 4] Auto-increment
LDR R0, [R1,#4]!; R0 = supported
Mem[R1 + 4], R1 = R1 + 4
Block Data Multi-byte data LDMIA R12!, {R0-R11}; Data transfer between 1-
Transfer transfer between Load 48 bytes of data from 16 registers to/from
memory and memory buffer pointed to by memory
registers R12 to registers R0-R11 Lowest register number
STMIA R13!, {R0-R11}; to/from lowest memory
Store 48 bytes of data from address
registers R0-R11 to memory Can implement stack or
buffer pointed to by R13 bulk data movement
Multiplication Integer MUL R0, R1, R2; R0 = R1 * Source and destination
multiplication R2 separate registers
with 32/64 bit MULA R0, R1, R2, R3; R0 = R15 not usable
results R1 * R2 + R3 For each pair of bits in
source, 1 clock plus 1
clock to start
Early terminates if
source becomes zero
Software Interrupts the SWI #n, n is a 24-bit number Control jumps to SWI
Interrupt CPU via program interrupt vector
instruction Value of n ignored by
the processor
Realizes system calls, a
total of 224 calls possible
Branching Branch to a B <target>; Branch to target Relative branching only
different location BL <target>; Branch to target Jump within ±32 MB
with PC+4 saved in R14 BL used for subroutine
Subroutine return by
copying R14 to R15
All ARM instructions can be executed conditionally. For this, a condition code may be
prefixed with the instruction. The instruction gets executed only if the status flags satisfy the
specified condition. For example, the instruction “EQADD R1, R2, R3” has the effect of R1 getting
R2 + R3 only if the equality condition is satisfied. Else, though the instruction reaches the CPU
Microcontrollers and Applications | 191
and goes into the execution phase, effect is similar to a “no operation”. Availability of this facility
eliminates small branching in the program, the code becomes more of a straight line one and
augments the pipeline performance. The following example clarifies the point.
if R1 = R2 then
R3 = R4 + R5
else
R3 = R4 – R5
In the following, two tentative assembly codes are shown. The left one does not assume the
existence of conditional instructions, thus some additional branch instructions got created. The
code on the right side uses conditional instructions that results in a straight line code. For the
code in the left side, if the equality condition is satisfied, the processor, after executing “JE L1”
has to wait for the instruction at L1 to be available to it. The prefetched instruction “SUB R3,
R4, R5” is not the correct one to be executed in that case. This problem is commonly known as
pipeline stall. Such problems do not occur with the right side code.
CMP R1, R2 CMP R1, R2
JE L1 EQADD R3, R4, R5
SUB R3, R4, R5 NESUB R3, R4, R5
JMP L2
L1: ADD R3, R4, R5
L2:
It may be noted that conditional branching can be implemented using conditional execution of
branch instructions, in a similar fashion.
Though the ARM instruction set has many interesting features, there is a marked deviation
from the contemporary processors in terms of stack, conditional execution and software interrupt
support. The other instruction set, THUMB contains 16-bit instructions and are stored in the
memory in a compressed form. The THUMB instructions are executed unconditionally, excepting
the branch instructions.
While using THUMB, 16‐bit Instruction THUMB ARM Inst.
the user has unlimited THUMB code pipeline decompressor decoder
access only to the
registers R0-R7 and
R13-R15. The total Fig 5.7: THUMB to ARM conversion
192 | Microcontrollers and Applications
number of software interrupts is limited to 256. Similar to other conventional processors, PUSH
and POP instructions have been included in the THUMB set. Upon reset, the processor enters into
ARM instruction set mode. To use THUMB mode, the user program should execute a “BX
<target>” or “BLX <target>” instruction. The processor will expect the THUMB instructions to
start from the target address. The BX/BLX instruction should also be used to come back to ARM
instruction set mode from THUMB. However, the THUMB instructions are not directly executed
by the ARM processor. After reaching the instruction pipeline, the THUMB instruction goes
through a decompressor to get converted into its equivalent ARM instruction, and get executed
thereafter. The situation has been shown in Fig 5.7. However, programs written in THUMB
requires less memory space due to compression. THUMB also consumes upto 30% less power than
ARM code, in general, while ARM code is about 40% faster than THUMB. In a typical system,
ARM instruction set should be used for on-chip memory, containing small speed-critical routines,
while THUMB should be used with off-chip memory for non-critical routines.
Example 5.5: Consider the problem of finding the maximum of a set of numbers stored at a
memory buffer starting at address pointed to by R3. Register R2 holds the count of the number
of numbers in the buffer. The following is the assembly language code for the problem. The
largest number be available at R1.
EOR R1, R1, R1 ; Clear R1 by XORing
CMP R2, #0
BEQ OVER ; Block empty, done
L1: LDR R3, [R0] ; Get next data
CMP R3, R1 ; Compare
BCC L2 ; Skip if R1 is bigger
MOV R1, R3 ; Else get larger in R1
L2: ADD R0, R0, #4 ; Increment R0 for the next number
SUBS R2, R2, #1 ; Decrement R2
BNE L1 ; If count still not zero, goto L1
OVER: ; R1 has the largest
Microcontrollers and Applications | 193
5.6.5 LPC214x – An ARM7 Implementation
In this section, a typical implementation of ARM7 architecture, LPC214x has been
discussed. LPC214x series of
microcontrollers are very popular Table 5.7: Comparison across LPC214x devices
due to their tiny size and low Device SRAM Flash No. of ADC No. of DAC
power consumption, particularly
for devices that require (kB) (kB) channels channels
miniaturisation. There are five LPC2141 8 32 6 -
different microcontrollers in the
series, namely LPC2141/ LPC2142 16 64 6 1
42/44/46/48. A comparison LPC2144 16 128 14 1
between the devices has been
presented in Table 5.7. It comes as LPC2146 40 256 14 1
a quad-flat package. There are 8- LPC2148 40 512 14 1
40kB of SRAM and 32-512kB
flash memory. USB 2.0 is supported. One to two on-chip 10-bit ADCs provide a total of 6-14
analog channels. Some variants have on-chip 10-bit DAC as well. Two 32-bit timers/counters are
available with four capture and four compare channels. There is a 6-channel pulse width modulation
module and an watchdog timer. Interfaces like SPI, SSP, I2C, USART are available for
communication. A real-time clock module with independent power supply has been provided in it.
Upto 21 external interrupt pins are available. Fig 5.8 shows the block diagram of the LPC214x
microcontroller.
LPC2148 has got two General Purpose I/O (GPIO) ports, namely, Port 0 (P0) and Port 1
(P1). Both the ports are 32-bit wide, however, for P1, the bits 16 to 31 are only available for
input/output. All bits of P0 are available for I/O, however, these pins also have several functions
multiplexed to them. As a result, the actual number of I/O pins available, depends upon the
application in hand which may use other modules of the chip as well. For example, pin P0.21 also
acts as PWM5 (Pulse Width Modulation), AD1.6 (ADC), CAP1.3 (Capture input for Timer1,
Channel 3). For Port 0, 28 out of 32 pins can be configured as bidirectional. P0.24, P0.26 and P0.27
are unavailable. P0.30 can be used as output pin only.
194 | Microcontrollers and Applications
PLL0
System Clock
Trace Module
Test/Debug System
Emulation
Interface
P0[31:28], Functions
P0[25:0] ARM7 PLL1
Fast General
Purpose I/O AHB Bridge Vectored
P1[31:16] Interrupt
USB Clock Controller
ARM7 local bus
AMBA AHB
Internal SRAM Internal Flash
Controller Controller
AHB
RAM Decoder
Flash AHB to APB APB
SRAM D+ D‐ UP_LED
Bridge Divider
Microcontrollers and Applications | 195
Table 5.8 shows the important registers and their settings for GPIO operations. The
registers need to be programmed properly to get the I/O operations done. The registers control the
functionality of the pins, I/O directions,
setting and resetting of bits. Individual Table 5.8: Registers for I/O Port Programming
bits can be programmed separately. In
particular, for I/O operation, first the Register Functionality
direction of the port bit be set. For (x = 0, 1)
example, the setting “IO0DIR = 0x04”
IOxPIN Register can be read to get the current
will configure the Pin 2 of Port 0 (P0.2)
state of the GPIO pins.
as output and other bits as input. For an
input operation, the IOxPIN register IOxDIR Controls direction of port bits. Setting a
can be read. However, for output bit to 0 makes port pin to act as input, 1
operation, to write a 1, corresponding makes the pin output.
bit of IOxSET register should be set to
IOxCLR Drives the corresponding pin to 0.
1. To output a 0, the bit in IOxCLR be
set to 1. After a port pin has been IOxSET Drives the corresponding pin to 1.
written with some value, the value can
be read from the IOxPIN register bit.
Example 5.6: Consider the problem of setting P0.14 pin to high first and then low. The C code
fragment for it is as follows.
# include <lpc214x.h>
void Delay_rtn(void);
int main(void)
{
IO0DIR = 0x3; // Configure P0.0 and P0.1 as output
196 | Microcontrollers and Applications
while (1)
{
IO0SET = 0x3; // Turn LEDs on
Delay_rtn();
IO0CLR = 0x03; // Turn LEDs off
Delay_rtn();
}
}
void Delay_rtn(void)
{
int a, b;
b = 0;
for (a = 0; a < 2000000; a++) b++; // Do something, else compiler may
// remove the loop
}
Example 5.8: A switch is connected to P0.0, an LED to P0.1. The LED should glow whenever
the switch is closed. The corresponding C program is
shown next. P0.0
# include <lpc214x.h>
int main(void)
P0.1
{
IO0DIR &= ~(1); // Make P0.0 input
IO0DIR |= (1<<1); // Configure P0.1 as output
while (1) {
if (!(IO0PIN & (1)) // Becomes true if P0.0 = 0
IO0SET |= (1 << 1); // Drive P0.1 high
else
IO0CLR |= (1 << 1); // Make P0.1 low
}
}
Microcontrollers and Applications | 197
UNIT SUMMARY
Though 8051 is one of the very popular microcontrollers, its usage is now limited due to
the introduction of several new microcontrollers. All these architectures could be classified to be
CISC or RISC. A clear discussion on the features of RISC and CISC processor architectures has
been presented that also distinguishes between the two. Among the advanced microcontrollers,
three examples have been taken up. The first one is PIC. In this category the advanced series
PIC18F has been discussed. This has been followed by the AVR microcontrollers. The AVR also
has a number of series. Among them, ATmega32 is the most popular one and has been discussed
in the unit. Among the recent microcontrollers targeting low power applications, ARM is now
almost the choice, by default. Again, ARM has a number of processor architectures. The most
advanced being the Cortex series. However, for better understanding, ARM7 architecture has been
taken up. Several companies have different implementations of the ARM7. The one, LPC214x by
the NXP is a very popular processor. The I/O programming with this processor has been discussed
that will enable the reader to carry out interfacing assignments comfortably. More detailed
discussion on each of these processors and series are beyond the scope of the book. The readers are
requested to look into the references for the same.
EXERCISES
198 | Microcontrollers and Applications
MQ7. Size of address bus in bits for PIC18F series is
(B) 16 (B) 21 (C) 24 (D) None of the other options
MQ8. PIC18F can work upto crystal frequency
(A) 10MHz (B) 20MHz (C) 30MHz (D) None of the other options
MQ9. Port bit width of port A of PIC18F processor is
(A) 7 (B) 8 (C) 15 (D) 16
MQ10. Number of timers in PIC18F is
(B) 2 (B) 3 (C) 3 (D) 4
MQ11. The mode in which a timer works as a stopwatch is
(B) Capture (B) Compare (C) PWM (D)None of the other options
MQ12. The high priority interrupt vector in PIC18F is
(B) 00008H (B) 00010H (C) 00016H (D) 00018H
MQ13. Number of timers in ATmega32 is
(A) 1 (B) 2 (C) 3 (D)4
MQ14. In AVR, the registers X, Y and Z overlap with
(B) R0-R5 (B) R16-R21 (C) R26-R31 (D) None of the other options
MQ15. Bit width of address pointers in AVR is
(A) 8 (B) 16 (C) 32 (D) 64
MQ16. The address pointer that can be used to access program memory in AVR is the register
(A) X (B) Y (C) Z (D) All of the options mentioned
MQ17. Width (in bits) of Timer 2 in ATmega32 is
(A) 8 (B) 13 (C) 16 (D) None of the other options
MQ18. In AVR, the start address of GPRs in memory is
(A) 00H (B) 20H (C) 60H (D) None of the other options
MQ19. Width of instructions in the THUMB instruction set, in number of bits is
(A) 16 (B) 32 (C) 48 (D) None of the other options
MQ20. ALE signal in ARM processor is
(B) To the processor (B) From the processor
(C) Not present (D) Bidirectional
MQ21. The register that acts as program counter in ARM is
(A) R13 (B) R14 (C) R15 (D) None of the other options
MQ22. The register useful for making subprogram calls in ARM is
(A) R13 (B) R14 (C) R15 (D) None of the other options
MQ23. Conditional execution of instructions in ARM helps in improving
(B) Pipeline performance (B) Stack overflows
(C) Loop implementation (D) None of the other options
MQ24. In LPC2148 the register responsible for setting direction of I/O ports is
(B) IOxDEP (B) IOxPIN (C) IOxSET (D) None of the other options
MQ25. ARM instruction to change instruction set is
(B) BX (B) XCH (C) THUMB (D) None of the other options
Microcontrollers and Applications | 199
Answers of Multiple Choice Questions
1:A, 2:B, 3:A, 4:C, 5:C, 6:A, 7:B, 8:D, 9:A, 10:D, 11:A, 12:A, 13:C, 14:C, 15:B, 16:C, 17:A,
18:A, 19:A, 20:A, 21:C, 22:B, 23: A, 24: D, 25: A
Practical Problems
PQ1. Write an assembly language program for ARM processor to find the minimum of a set of
numbers.
Hint: Refer to Example 5.5.
PQ2. Modify the code in Example 5.7 so that alternate LEDs glow at a time.
Hint: Refer to example 5.7.
PQ3. Modify the code in Example 5.7 so that the LEDs connected to the 8 least significant bits of
port show the number stored in the variable kount, initialized at the program development
time.
Hint: Refer to Example 5.7.
200 | Microcontrollers and Applications
PQ4. Modify the program in Example 5.8 so that there are two switches – SW1 and SW2. Pressing
SW1 will turn ON the LED, pressing SW2 will turn the LED OFF. If both the switches are
pressed, SW1 will have higher priority, turning the LED ON.
Hint: Refer to Example 5.8.
PQ5. Modify the program in Example 5.8 so that there are two switches – SW1 and SW2 and two
LEDs – L1 and L2. In SW1 is closed, L1 will glow. If SW1 is open, L1 will also be OFF.
Similarly SW2 controls the LED L2. However, if both the switches are closed, both L1 and
L2 will blink continually till both the switches are released.
Hint: Refer to Example 5.8.
KNOW MORE
Beyond ARM7, some more ARM processors have been introduced, namely, ARM8,
ARM9TDMI, StrongARM, ARM10 and ARM11. The latest development in the ARM family is
the introduction of ARM Cortex processors. It has three families. The Cortex-A corresponds to
application processors with third party applications. The Cortex-R are embedded processors
supporting real-time signal processing and control applications. The microcontroller series is
marked as Cortex-M. This series is fully programmable in C and possesses only two modes – user
mode and supervisor mode. It has one non-maskable interrupt and upto 240 prioritizable interrupts.
Microcontrollers and Applications | 201
CO-1
CO-2
CO-3
CO-4
CO-5
CO-6
The data filled in the above table can be used for gap analysis.
202 | Index
Microcontrollers and Applications | 203
Index
204 | Index
FIQ, 188 Mnemonic, 56, 68
Flags, 8, 15 MOVC, 73
Frame, 111 MOVX, 74
General purpose I/O, 193 Multiplexed display, 138
General purpose RAM, 40 NOP, 90
General purpose registers, 13, 19 Normal Interrupt Processing Mode, 188
GPIO, 19, 193 Opcode, 68
Half-duplex, 110 Open-drain, 47
Handshaking, 160 ORG, 56
Hex file, 58 OTP, 36
Hex keyboard, 131 Parity, 111
I2C, 179 Persistence, 139
IDE, 25, 96 Pointer registers, 19
Immediate, 182, 185 Polling, 104
Immediate addressing, 69 Power control, 41
Index registers, 19 Power-on reset, 43
Indirect, 185 PPI, 159
Indirect with displacement, 185 Processor status word, 41
Indirect with post-increment, 185 Program Counter, 8, 15, 39, 183
Indirect with pre-increment, 185 Program Strobe Enable, 48
Inherent, 182 Programmable Peripheral Interface, 159
Instruction Decoder, 39 PSEN, 38, 48
Instruction Pointer, 8 Pulse Width Modulation, 180
Instruction Register, 8, 39 PWM, 180
Integrated Development Environment, 25, 96 RAM, 6
Intellectual Property Core, 23 Random Access Memory, 6
Inter-Integrated Circuit, 179 Read Only Memory, 6
Interrupt enable, 106 Reduced Instruction Set Computer, 174
Interrupt priority, 110 Register, 7
Interrupt service routine, 105 Register addressing, 69
Interrupt vector table, 105 Register banks, 39
Interrupts, 104, 105, 181 Register direct, 182
IP core, 23 Register direct addressing, 70
IRQ, 188 Register file, 188
JTAG Boundary Scan, 183 Register indirect addressing, 68, 70
LCD, 142 Resolution, 148, 153
LCD command, 143 RETI, 80
LED, 130, 137 RISC, 174,176
Level triggered, 108 ROM, 6
Light emitting diode, 130, 137 Rotate instructions, 87
Link register, 189 SCI, 179
Linker, 25 Sensor, 158
Liquid crystal display, 142 Serial buffer, 112
List file, 58 Serial Communication Interface, 179
Load-store architecture, 175, 188 Serial Peripheral Interface, 179
Machine control, 16 Serial reception, 115
Machine cycle, 42, 52 Serial transmission, 113
Machine language, 23 Seven-segment display, 137
Maximum mode, 17 Signal conditioning, 158
MegaAVR, 182 Signed char, 92
Minimum mode, 17 Signed int, 93
Microcontrollers and Applications | 205
Single bit, 93 Switch, 128
Simplex, 110 Synchronous, 111
Simulator, 26 System-on-Chip, 23
Sine wave, 154,156 Timer/Counter, 40
Single step, 96 Timers, 180
Single-Board Computers, 20 TinyAVR, 182
Single-Chip Computers, 20 TMOD, 98
SoC, 23 Transducer, 158
Special function register, 40, 93, 179 Triangular wave, 155
Special purpose registers, 14SPI, 179 Unconditional branching, 76
Stack Pointer, 15, 40, 42, 189 Unsigned char, 92
Start conversion, 149 Unsigned int, 87
Static debugging, 96 Word size, 4
Step size, 148 Workstation, 20
Subprogram call/return, 79 XmegaAVR, 182
SWAP, 90 ZERO, 8
206 | Index