Sunteți pe pagina 1din 76


Electrical & Computer engineering department

Embedded Systems
Course Module

Achamie Aynalem
Department of electrical & computer engineering
Debre Tabor University
Embedded Systems 1

Contents............................................................................................................................... 1
Chapter 1: Introduction to Embedded Systems .................................................................. 3
1.1 A System ..................................................................................................................... 3
1.1.1 Embedded System ................................................................................................ 3
1.1.2 Basic Structure of an Embedded System ............................................................ 4
1.1.3 Types of Embedded Systems ............................................................................... 5
1.1.4 Characteristics of an Embedded System ............................................................. 7
1.1.5 Advantages and Disadvantages of Embedded systems ....................................... 7
1.1.6 Applications Areas ............................................................................................... 8
1.1.7 Challenges in embedded system design .............................................................. 9
1.1.8 Design methodologies ......................................................................................... 9
1.2 Microprocessors ....................................................................................................... 12
1.3 Microcontroller ........................................................................................................ 12
1.4 Microprocessor vs. Microcontroller ........................................................................ 13
1.5 Skills required for an Embedded system Designer ................................................. 14
Chapter-2: Embedded Microcontrollers ........................................................................... 15
2.1 Brief History of 8051 ................................................................................................ 23
2.2 8051 Flavors / Members.......................................................................................... 23
2.3 Features of 8051 Microcontroller ............................................................................ 24
2.4 8051 Microcontroller Architecture (Block Diagram).............................................. 24
2.5 8051 Schematic Pin out ........................................................................................... 26
2.6 I/O Ports and Bit Addressability ............................................................................. 30
2.7 On-Chip Memory Internal RAM ............................................................................. 31
2.7.1 General Purpose Registers ................................................................................ 31
2.7.2 Bit Addressable Memory................................................................................... 33
2.7.3 General Memory ............................................................................................... 33
2.7.4 Special Function Registers ................................................................................ 33
2.7.5 Bit Addressable RAM ........................................................................................ 34
2.7.6 Registers ............................................................................................................ 34
Chapter-3: 8051 Programming in Assembly Language.................................................... 35
3.1 Introduction ............................................................................................................. 35
3.2 8051 Programming Execution Steps of Assembly Language ................................. 35

Embedded Systems 2
3.3 The Elements of an Assembly Language Programming ........................................ 36
3.4 Addressing Modes ................................................................................................... 37
3.5 Instruction Set ......................................................................................................... 38
Chapter-4: 8051 Microcontroller Applications ................................................................ 44
4.1 Embedded Software Development Tools ................................................................ 44
4.1.1 Procedure for Embedded System Programming .............................................. 44
4.1.2 Basics Declaration ............................................................................................ 45
4.2 Embedded Applications .......................................................................................... 46
4.2.1 LED interfacing with 8051 microcontroller...................................................... 46
4.2.2 Push Button Interfacing with 8051 microcontrollers ...................................... 48
4.2.3 LCD (Liquid Crystal Display) Interfacing with 8051 microcontroller ............. 49
4.2.4 Keypad Interfacing with 8051 microcontroller ................................................ 54
4.2.5 Serial Communication with 8051 microcontroller........................................... 58
Chapter-5: Real-Time Operating Systems ........................................................................ 64
5.1 Introduction to Real-Time Operating Systems ....................................................... 64
5.2 Types of Real Time Operating System .................................................................... 66
5.3 Features of RTOS ..................................................................................................... 66
5.4 Real-Time Embedded System with RTOS .............................................................. 67
5.5 RTOS Architecture ................................................................................................... 68
5.6 Kernel ....................................................................................................................... 68
5.6.1 Task Management ............................................................................................. 69
5.6.2 Task Synchronization & Intertask Communication ..........................................71
5.6.3 Memory Management ....................................................................................... 73
5.6.4 Timer Management .......................................................................................... 74
5.6.5 Interrupt and Event Handling .......................................................................... 74
5.6.6 Device I/O Management ................................................................................... 74
Text Books: .................................................................................................................... 74
Individual Assignment .................................................................................................. 75
Group Assignment ......................................................................................................... 75

Embedded Systems 3

Chapter 1: Introduction to Embedded Systems

1.1 A System
A system is a way of working, organizing or doing one or many tasks according to
a fixed plan, program, or set of rules. A system is also an arrangement in which all its
units assemble and work together according to the plan or program.
A watch is a time-display system, which consists different parts/components
organized to show the real time and continuously update every second.
 Are set of protocols that are agreed up on by the users of the system. The possible
set of rules for the watch system above are:
 All the needles move only clockwise.
 A thin and long needle rotates every second it returns to the same position after a
 A long needle rotates every minute such that it returns back to the same position
after an hour. Etc…
1.1.1 Embedded System
Embedded systems are computing systems with tightly coupled hardware and
software integration that are designed to perform a dedicated function. The word
embedded reflects the fact that these systems are usually an integral part of a larger
system, known as the embedding system. Multiple embedded systems can coexist in an
embedding system.
A combination of hardware and software which together form a component of a
larger machine.
An example of an embedded system is a microprocessor that controls an
automobile engine.
An embedded system is designed to run on its own without human intervention,
and may be required to respond to events in real time.
An embedded system is a microcontroller-based, software-driven, reliable, real-
time control system, autonomous, or human or network interactive, operating on
diverse physical variable and in diverse environments, and sold into a competitive and
cost conscious market.
Any system that embeds computing components with a stored program, which
control some activities in the system, is normally known as embedded systems.Loosely
defined, any device that includes a programmable computer but is not itself intended to
be a general-purpose computer. Embedded systems are electronic systems that contain
a microprocessor or microcontroller, but we do not think of them as computers– the
computer is hidden or embedded in the system.
An embedded system is a controller programmed and controlled by a real-time
operating system (RTOS) with a dedicated function within a larger mechanical or
electrical system, often real-time computing constraints. It is embedded as part of a
complete device often including hardware and mechanical parts.
More than 98% of the computers existing in the world are embedded, that is,
integrated to a larger system with the purpose of managing its resources and
monitoring/controlling its functions using special hardware devices. IOT (Internet of
Things) mainly composed of embedded systems where some smaller hardware devices
are embedded in a larger system like automobile, refrigerator, watches, Bicycles, etc.

Embedded Systems 4
History of embedded system
If we look at times past, it’ll be clear that from 1930 to 40s, computers were mostly dedicated to
the single-purpose task. In the earliest time of the computer, we see some distinguished embedded
system which is Apollo Guidance Computer developed by Charles Stark Draper at the MIT
Instrumentation Laboratory. In the 60s, Embedded System had come down in cost and taken rise in
processing power and in functionality as well. The first microprocessor Intel 4004 was just designed
for calculators and some others small projects but still, they required much external support in the
form of memory and chips. In the mid of 80s, a new form of this technique was seemed this modern
form of microcontroller allowed more spread use and that was by the end of the decade become the
norm rather than the exception for many electronic devices.
1.1.2 Basic Structure of an Embedded System
Let us discuss in detail the building blocks of hardware of an Embedded System.
 Input Devices
 Output Devices
 Central Processing Unit
 Communication Interfaces
 Memory (ROM and RAM)
 Application Specific Circuit

Case Study of embedded system

To understand the design of an Embedded System, at first, we consider the idea
of acquisition system as in given below diagram. Let us consider a case of temperature
measurement. and data acquisition system., First of all, we select a temperature sensor
like thermometer or AD590 or LM35 or LM75 etc. After that, the analog
The following illustration shows the basic structure of an embedded system:

Data is converted into the digital data and signal conditioning is also properly
done at the same time. Now, this digital input is supplied to the microcontroller through
its ports. At next step, the data must be controlled and processed by creating a source
file in a suitable program (C or Assembly) and C compilers can be used. Next, program

Digitally signed by Acham Aynalem

Acham Aynalem
DN: C=ET, OU=DTU, O=DTU, CN=Acham Aynalem,
Reason: I am the author of this document
Location: Debre Tabor University
Date: 2019-04-16 23:04:57
Foxit Reader Version: 9.4.0
Embedded Systems 5
will be debugged and found error free then it’ll be dumped into the microcontroller flash
memory using ISP. Finally, microcontroller chip will act as an embedded chip.
 Sensor − It measures the physical quantity and converts it to an electrical signal
which can be read by an observer or by any electronic instrument like an A-D
converter. A sensor stores the measured quantity to the memory.
 A-D Converter − an analog-to-digital converter converts the analog signal sent
by the sensor into a digital signal.
 Processor − Processors process the data to measure the output and store it to
the memory.
 D-A Converter − A digital-to-analog converter converts the digital data fed by
the processor to analog data
 Actuator − An actuator compares the output given by the D-A Converter to the
actual (expected) output stored in it and stores the approved output.
 Embedded Controller or CPU
Embedded controller is a controller that is embedded either in a greater system
or in some device for some purpose other than to provide a general purpose
computing. It essentially is used to control something in a larger system. For
example, something that controls car-braking system is an embedded controller.

1.1.3 Types of Embedded Systems

Embedded systems can be classified into different types based on performance,
functional requirements and performance of the microcontroller.

Embedded systems are classified into four categories based on their performance
and functional requirements:
• Stand alone embedded systems
• Real time embedded systems
• Networked embedded systems
• Mobile embedded systems
• Embedded Systems are classified into three types based on the performance of
the microcontroller such as
• Small scale embedded systems
• Medium scale embedded systems
• Sophisticated embedded systems
Real-time embedded system:
Real-time systems are those which give a quick response to critical situations.
They are used in military, medical and industrial applications. Engineers working in
these systems have high demand is current days. To develop the real-time embedded

Embedded Systems 6
system we require timing analysis, multitasking design, debugging, cross-platform
testing and architecture design. In these systems, quick response is very important.
Better hardware is also used in these systems to avoid failure in performance. Real-time
systems control the external environment by input & output interfaces and sensors. The
external environment includes human and other animals. Some examples of real-time
embedded systems include:-
• Controlling heat, elevators, lights, and doors in buildings
• Robots
• Traffic control system including railway tracks, airspace, shipping lines, highways
• Radio, satellite and telephone communication
• Patient monitoring system
• Radiation therapy system in the hospital
• Computer games
• Multimedia systems which consist of video, audio, text and graphics interfaces
• Military usage that includes tracking, weapons, and command & control
Standalone embedded system:
This type of embedded system works for itself as a device without needing any
interconnected computer. It can take data in the form of analog or digital signals. This
system first process data and then outputs data by displaying on the screen. It can also
output data to any attached device. Examples of standalone embedded systems include:-
• Microwave ovens
• Digital cameras
• Mp3 players
• Video game consoles
• Temperature measurement systems
Networked embedded system:
Networked embedded systems are those systems which are connected to the
network to give output to the attached resources. The devices in the networked
embedded system are connected to the network with network interfaces. The network
can be either a local area network (LAN) or a wide area network (WAN). The connection
in networked embedded systems can be wireless or wired. This embedded system is fast
and emerging its popularity over days. The embedded web server is that which is
connected to network devices and is controlled by the web browser also. Example of this
is the office security system. In office security system, different sensors (light sensors,
smoke sensors or motion detectors) are networked together through LAN and controlled
over the WAN (internet).
Mobile embedded system:
Mobile embedded systems are limited in resources including memory. Examples
of mobile embedded systems include:-
• Personal digital assistants (PDA)
• Cellular phones
• Mp3 players
• Digital cameras
Small-scale embedded system:
Small-scale embedded systems consist of 8-16 bit microcontroller. This system
can perform tasks at a small level. They have on-chip ROM and RAM. Small-scale
systems can be even activated by the battery. The tools used to develop small-scale
embedded systems are an editor, cross assembler, assembler and integrated

Embedded Systems 7
development environment (IDE). The purpose of this system is not computation but to
control as a computer embedded inside it. It behaves as a component of a computer and
its function is not to compute. The small-scale system is dedicated to some specific task.
To apply for the job as a small-scale embedded designer you need skills including data
communication, digital electronic design, control engineering, software engineering,
computer architecture, motors & actuators, analog electronic design, sensors &
measurement and IC design & measurement.
Medium scale embedded system:
This embedded system has 16-32 bit microprocessor or microcontroller with
external RAM and ROM They can perform medium to complex level works. The
integration between hardware and software is complex in these embedded systems.
Programming languages used to develop medium scale embedded systems include Java,
C, Visual C++, debugger, C++, RTOS, simulator, source code engineering tool and IDE.
The designer of the medium scale embedded system should also know how to use
semaphores, queues, mailboxes, pipes, and sockets. Knowing the application
programming interface (API) in the RTOS tool for controlling microcontroller is also
Sophisticated embedded system:
The embedded system which can do large-scale works with multiple 32-64 bit
chips is known as sophisticated embedded systems. They can perform distributed work
on a large scale. The complexity of hardware and software is very high in these systems.
In sophisticated embedded systems, hardware and software are assembled together on
large scale and designing of hardware products is also included in these systems.

1.1.4 Characteristics of an Embedded System

• Embedded systems are application specific & single functioned; application is
known apriori, the programs are executed repeatedly.
• Efficiency is of paramount importance for embedded systems. They are
optimized for energy, code size, execution time, weight & dimensions, and cost.
• Embedded systems are typically designed to meet real time constraints; a real
time system reacts to stimuli from the controlled object/ operator within the time
interval dictated by the environment. For real time systems, right answers
arriving too late (or even too early) are wrong.
• Embedded systems often interact (sense, manipulate & communicate) with
external world through sensors and actuators and hence are typically reactive
systems; a reactive system is in continual interaction with the environment and
executes at a pace determined by that environment.
• They generally have minimal or no user interface.

1.1.5 Advantages and Disadvantages of Embedded systems

• Easily Customizable
• Low power consumption
• Low cost
• Enhanced performance
• High development effort

Embedded Systems 8
• Larger time to market

1.1.6 Applications Areas

 Consumer Products
TV, stereo, remote control, phone / mobile phone, refrigerator, microwave,
washing machine, electric tooth brush, oven / rice or bread cooker, watch, alarm
clock, electronic musical instruments
 Medical Systems
pace maker, patient monitoring systems, injection systems, intensive care units,

 Office Equipment
printer, copier, fax, …
 Tools
multimeter, oscilloscope, line tester, GPS, …
 Banking
ATMs, statement printers, …
 Transportation
(Planes/Trains/[Automobiles] and Boats)
radar, traffic lights, signalling systems, …
 Automobiles
engine management, trip computer, cruise control, immobilizer, car alarm,
airbag, ABS, ESP, …
 Building Systems
elevator, heater, air conditioning, lighting, key card entries, locks, alarm systems,

 Agriculture
feeding systems, milking systems, …
 Space
satellite systems, …
Example: BMW 850i brake and stability control system
 Anti-lock brake system (ABS): pumps brakes to reduce skidding.
 Automatic stability control (ASC+T): controls engine to improve stability.
 ABS and ASC+T communicate.
 ABS was introduced first---needed to interface to existing ABS module.

Embedded Systems 9
1.1.7 Challenges in embedded system design
 How much hardware do we need?
 How big is the CPU? Memory?
 How do we meet our deadlines?
 Faster hardware or cleverer software?
 How do we minimize power?
 Turn off unnecessary logic? Reduce memory accesses?
 Does it really work?
 Is the specification correct?
 Does the implementation meet the spec?
 How do we test for real-time characteristics?
 How do we test on real data?
 How do we work on the system?
 Observability, controllability?
 What is our development platform?

1.1.8 Design methodologies

A procedure for designing a system.
 Understanding your methodology helps you ensure you didn’t skip anything.
 Compilers, software engineering tools, computer-aided design (CAD) tools, etc.,
can be used to:
o help automate methodology steps;
o keep track of the methodology itself.
Design goals
• Performance.
• Overall speed, deadlines.
• Functionality and user interface.
• Manufacturing cost.
• Power consumption.
• Other requirements (physical size, etc.)
Levels of abstraction

Plain language description of what the user wants and expects to get.
May be developed in several ways:
 talking directly to customers;

Embedded Systems 10
 talking to marketing representatives;
 providing prototypes to users for comment.
Functional vs. non-functional requirements
Functional requirements:
• output as a function of input.
Non-functional requirements:
• time required to compute output;
• size, weight, etc.;
• power consumption;
• reliability; etc.
Example: GPS moving map requirements
Moving map obtains position from GPS, paints map from local database.

GPS moving map requirements form

purpose consumer-grade moving map for driving
inputs power button, two control buttons
outputs back-lit LCD 400 X 600
functions 5-receiver GPS; three resolutions; displays current lat/lon
performance updates screen within 0.25 sec of movement
manufacturing cost $100 cost-of-goods-sold
power 100 mW
physical size/weight no more than 2: X 6:, 12 oz.

A more precise description of the system:
• should not imply a particular architecture;
• provides input to the architecture design process.
• May include functional and non-functional elements.
• May be executable or may be in mathematical form for proofs.
GPS specification, should include:
What is received from GPS;
• map data;
• user interface;
• operations required to satisfy user requests;
• background operations needed to keep the system running.

Architecture design
What major components go satisfying the specification?
Hardware components:
• CPUs, peripherals, etc.
Software components:

Embedded Systems 11
• major programs and their operations.
• Must take into account functional and non-functional specifications.

GPS moving map block diagram

GPS moving map hardware architecture

GPS moving map software architecture

Designing hardware and software components

Must spend time architecting the system before you start coding.
Some components are ready-made, some can be modified from existing designs, others
must be designed from scratch.
System integration
• Put together the components.
• Many bugs appear only at this stage.
• Have a plan for integrating components to uncover bugs quickly, test as much
functionality as early as possible.

Embedded Systems 12
1.2 Microprocessors
Microprocessor is a general-purpose digital computer central processing unit
(CPU). Additional external circuitry are added to make it a microcomputer. The
microprocessor needs to be connected via buses to other principal components of
computing such as RAM, ROM, TIMER and I/O devices.

Central Processing Unit

Brain of the computer system, administers all activity in the system and performs
all operations on the data. It continuously performs two operations, fetching and
executing instructions. To understand and execute instructions, it used binary code
called instruction set.
To execute an instruction the processor must:
• Fetch the instruction from memory
• Decode the instruction to know that the instruction is ordering the machine to
• Execute the instruction/actually perform what it’s ordered to do
• Store the result back in memory
Fetching involves the following steps:
• Contents of Program counter are placed on address bus.
• READ signal is activated.
• Data (instruction opcode) are read from RAM and placed on data bus.
• Opcode (operation code) is latched into the CPU’s internal instruction register.
• PC is incremented to prepare for the next fetch from memory

Types of buses:
A bus a collection of wires carrying information with a common purpose.
• Address bus: carries the address of a specified location. For n address lines, 2n
locations can be accessed.
• Data bus: carries information between the CPU and memory or between the
CPU and I/O devices.
• Control bus: carries control signals supplied by the CPU to synchronize the
movement of information on the address and data bus

1.3 Microcontroller
Microcontroller is a highly integrated chip that includes the CPU, RAM, ROM,
I/O, TIMERS, INTERRUPT CONTROLLERS and so on in a single chip. Microcontroller
does not need any external bus to connect it to the principal component of computing.

Embedded Systems 13

Types of microcontrollers
Microcontrollers can be categorized based on the following criteria.
• Bit size of registers(4,8,16,32)
• Memory(embedded/external)
• Family (8051, PIC, ARM etc.)
• Instruction set(CISC, RISC)

Microcontroller applications
• Automotive applications
• Home appliances (microwave oven, refrigerators, TV, VCRs, stereo)
• Automobiles (engine control, diagnostics, and climatecontrol)
• Environmental control (green house, factory, home)
• Instrumentation
• Aerospace
• Extensively used in “Robotics”
• Data logging
1.4 Microprocessor vs. Microcontroller
Microprocessor Microcontroller
• Single chip CPU • Contains a CPU and much of the
• Used as CPU in microcomputer circuitry of a complete microcomputer
• Intensive instruction sets system in a single chip
• Powerful addressing modes • Used in small, minimum component
• Instructions operate on nibble, byte designs performing control-oriented
etc. activities.

Embedded Systems 14
• Multitasking in nature. Can perform • Single bit operations
multiple tasks at a time. For example, • Single task oriented. For example, a
on computer we can play music while washing machine is designed for
writing text in text editor. washing clothes only
• RAM, ROM, I/O Ports, and Timers • RAM, ROM, I/O Ports, and Timers
can be added externally and can vary cannot be added externally. These
in numbers. components are to be embedded
• External support of external memory together on a chip and are fixed in
and I/O ports makes a numbers.
microprocessor-based system heavier • Microcontrollers are lightweight and
and costlier cheaper than a microprocessor.
1.5 Skills required for an Embedded system Designer
1. For small scale embedded system designer:
- understanding of Microcontroller
- Memory allocation
- C programming
- Use of IDE
- Debugging
2. For Medium scale ES designer:
- RTOS with application programming Interface for the specific
3. For sophisticated ES designer:
- Co-design
- H/w, RTOS, HDLs programming

Embedded Systems 15

Chapter Two
Embedded Microcontrollers
2.1. Architecture of a microcontroller

1. The Central Processing Unit

The central processing unit (CPU) does all the computing: it fetches, decodes and executes
program instructions and directs the flow of data to and from memory. Most CPUs are
synchronous. This means that they depend on the cycles of a processor clock. A clock
generates a high-frequency square wave usually driven by a crystal, a RC (resistor capacitor) or
an external source. The clock is sometimes referred to as an oscillator. To perform timer
operation inside microcontroller, usually there is externally connected or on-chip oscillator.
2. Buses
Bus is a group of wires which uses as a communication canal or acts as means of data transfer.
The different bus configuration includes 8, 16 or more cables. Therefore, a bus can bear 8 bits,
16 bits all together. Two types of bus;
Address Bus: It is used for transferring data from Central Processing Unit to Memory. 8051
microcontrollers for example, has 16 bit address bus.
Data bus: It is used for transferring the data from one peripherals position to other peripherals.
8051 microcontrollers for example, is consisting of 8 bits data bus.
3. Timer
A timer is a counter that is incremented at a fixed rate when the system clock pulses. The CPU
uses the timer to keep track of time accurately. The timer can generate a stream of pulses or a
single pulse at different frequencies. It can be used to start and stop tasks at desired times.

Embedded Systems 16
4. Memory
It provides storage for the software that it will run.
Two types;
ROM (Read only Memory): is non-volatile memory used for program information and
permanent data. This memory (code memory) may be implemented using ROM, EPROM or
Flash memory.
RAM(random access memory): is used to write and read data values as a program runs.
It provides storage for data such as program variables and intermediate results that might be
created throughout the operation of the embedded system.
Generally, embedded systems have small RAM that is available for their operation.
Application of ROM
1. Storing 'Application' program from where the processor fetches the instruction codes
2. Storing codes for system booting, initializing, Initial input data and Strings.
3. Storing codes for RTOS.
4. Storing Pointers (addresses) of various service routines.
Application of RAM
1. Storing the variables during program run,
2. Storing the stacks,
3. Storing input or output buffers for example, for speech or image .

5. Peripherals
Embedded processors typically include a number of input and output (I/O) peripherals available
as pins of the chip that is used to communicate with the outside world.
Communication is the act of giving, receiving or exchanging information, ideas and opinions so
that the message is completely understood by both parties.
 There are many protocols for communication, but all of those are based on either serial
communication or parallel communication.
 If a port has programmable input and output, it will also have an associated register
which specifies whether the data is input or output.
 On many devices this register is called the DDR (data direction register).
 Parallel communication is the process of sending or receiving multiple bits at the same
time through parallel channels.

Embedded Systems 17
 Crosstalk is a phenomenon by which a signal transmitted on one channel of a
transmission bus creates an undesired effect in another channel.
 Clock skew is the time difference in the arrival of two sequentially adjacent registers in
parallel circuit.
• Serial communication is the process of sending or receiving data in one bit at a time

 Simplex, half duplex, full duplex

 Small no of connections
 No cross talk, clock skew,
 cheap

Embedded Systems 18

Expanded microcontroller architecture

There are a number of peripheral protocols implemented on microcontrollers
1. Pulse Width Modulation (PWM)
PWM is a technique for delivering a variable amount of power efficiently to external hardware
devices. It can be used to control for example the speed of
electric motors, the brightness of an LED light, and the temperature of a heating element.
A PWM signal rapidly switches between high and low at some fixed frequency, varying the
amount of time that it holds the signal high.

2. General-Purpose Digital I/O

They are parallel communication peripherals which provide input or output binary data with a
single bit allocated to each pin within the port.
It transfers multiple bits of information simultaneously, hence the name parallel port.
The individual bits and pins within the port can usually be used independently of each other.
These ports are used to provide parallel interfaces such as the Centronics printer interface, output
signals to LEDs and alphanumeric displays and so on.
As inputs, they can be used with switches and keyboards to support control panels.
 If the processor supply voltage is VDD, voltage close to VDD (or supply voltage )
represents a logic one, and a voltage near zero represents logic zero. However, in active
low logic, these interpretations are reversed .
 A GPIO pin may be configured to be an output or Input port.
 When used as output, the current limitation should be considered. i.e. If the resistance of
connected device is R,
This current should be kept within the specified tolerance or amplifier may be needed to deliver
adequate current or voltage.

Embedded Systems 19
 Electrical isolation may be needed b/n processor ckt and external devices since the
external device nose electrical power may spill off to the power or ground lines to disrupt
the processor; or the device may operate in a very d/t voltage or power compared to the
 When GPIO are configured as input pin, they may be Schmitt triggered.

Serial communication protocols

There are different serial communication protocols in embedded systems
4. UART (Universal Asynchronous Receiver
 It is basically a hardware that convert parallel data into serial data.
 UART adds specific bit to the data packet instead of the clock signal.(i.e. it’s
 Example: COM1 & COM2 ports in a PC

Embedded Systems 20

5. SPI – Serial Peripheral interface

• Common Synchronous communication protocol used by many devices.
For example: SD card, RFID card reader, and 2.4GHz wireless transmitter/receivers.
 Master/Slave relationship, where master controls data transfer
 Transfer data between various IC chips, at very high speed.
 Data and control lines of the SPI are:
 Master Out Slave In (MOSI) also called Serial Data In (SDI).
 Master In Slave Out (MISO) also Called Serial Data Out (SDO).
 Serial Clock (SCLK or SCK): generated by the master for
 Synchronization.
 Slave Select (SS) on the master and Chip Select (CS) on the slave.

Embedded Systems 21

6. I2C Inter Integrated Circuits bus interface

 Bi-directional 2-wire, Multi Master, Low Bandwidth, and short distance
serial communication bus protocol.
 Has a 7-bit address space with 16 reserved address, hence 112 is the
maximum number of nodes that can communicate on the same bus.
 The two bi-directional lines are:
– SDA: Serial Data line for data transfer
– SCL: Serial Clock line for clock signal and synchronization.
Typical voltage used are +5V and +3.3V
7. USB Universal Serial Bus
It is a set of interfacing specifications for high speed wired
communication between electronic systems and peripherals and devices
using single standardized interface socket.
Advantages of USB:
 Low cost.
 Expandability.
 Auto configuration.
 Hot swapping.
 Providing power to the bus.

Analogue Inputs

Embedded Systems 22
While processors operate in the digital domain, the natural world does not and tends to orientate
to analogue values. As a result, interfaces between the system and the external environment need
to be converted from analogue to digital and vice versa. On microcontrollers, there are analog
inputs that convert analog signals to a digital stream.

Interrupts is a sub-routine call to the microcontroller interrupting the current running program
when some other program with high priority is requested for acquiring the system buss.
Interrupts are mostly hardware mechanisms that instruct the program that an event has occurred.
They may occur at any time, and are therefore asynchronous to the program flow. They require
special handling by the processor, and are ultimately handled by a corresponding Interrupt
Service Routine (ISR).
Interrupts need to be handled quickly. If you take too much time servicing an interrupt, then you
may miss another interrupt

Embedded Microcontrollers
There are more than 140 microcontrollers and more than 40 companies that
produce them. Some example includes
– 8051 families (INTEL): Produced by more than 50 companies
– AVR microcontrollers
– ARM microcontrollers
– PIC microcontrollers
– Arduino microcontrollers

Criteria for choosing microcontroller

While choosing a microcontroller, make sure it meets the task at hand and that it is
cost effective. Whether 8-bit, 16-bit or 32-bit microcontroller best handle our task.
The following points should be considered for choosing microcontroller
 Speed - What is the highest speed the microcontroller can support?
 Packaging - Is it 40-pin DIP (Dual-inline-package) or QFP (Quad
flat package)? This is important in terms of space, assembling and
prototyping the end-product.
 Power Consumption - This is an important criteria for battery powered

Embedded Systems 23
 Amount of RAM and ROM on the chip.
 Count of I/O pins and Timers on the chip.
 Cost per Unit - This is important in terms of final cost of the product in
which the microcontroller is to be used.
Further, make sure you have tools such as compilers, debuggers, and
assemblers, available with the microcontroller.

2.2. The 8051 microcontroller

2.2.1 Brief History of 8051
The first microprocessor 4004 was invented by Intel Corporation. 8085 and 8086
microprocessors were also invented by Intel. In 1981, Intel introduced an 8-bit
microcontroller called the 8051. It was referred as system on a chip because it had 128
bytes of RAM, 4K byte of on-chip ROM, two timers, one serial port, and 4 ports (8-bit
wide), all on a single chip. When it became widely popular, Intel allowed other
manufacturers to make and market different flavors of 8051 with its code compatible
with 8051. It means that if you write your program for one flavor of 8051, it will run on
other flavors too, regardless of the manufacturer. This has led to several versions with
different speeds and amounts of on-chip RAM.
2.2 8051 Flavors / Members
8052 microcontroller − 8052 has all the standard features of the 8051
microcontroller as well as an extra 128 bytes of RAM and an extra timer. It also has 8K
bytes of on-chip program ROM instead of 4K bytes.
8031 microcontroller − It is another member of the 8051 family. This chip is
often referred to as a ROM-less 8051, since it has 0K byte of on-chip ROM. You must
add external ROM to it in order to use it, which contains the program to be fetched and
executed. This program can be as large as 64K bytes. But in the process of adding
external ROM to the 8031, it lost 2 ports out of 4 ports. To solve this problem, we can
add an external I/O to the 8031
Comparison between 8051 Family Members
The following table compares the features available in 8051, 8052, and 8031.
Feature 8051 8052 8031

ROM(bytes) 4K 8K 0K

RAM(bytes) 128 256 128

Timers 2 3 2

I/O pins 32 32 32

Serial port 1 1 1

Interrupt 6 8 6

Embedded Systems 24
2.3 Features of 8051 Microcontroller
• 8 – Bit ALU: ALU or Arithmetic Logic Unit is the heart of a microcontroller. It
performs arithmetic and bitwise operation on binary numbers. The ALU in 8051
is an 8 – Bit ALU i.e. it can perform operations on 8 – bit data.
• 8 – Bit Accumulator: The Accumulator is an important register associated
with the ALU. The accumulator in 8051 is an 8 – bit register.
• RAM: 8051 Microcontroller has 128 Bytes of RAM which includes SFRs and
Input / Output Port Registers.
• ROM: 8051 has 4 KB of on-chip ROM (Program Memory).
• I/O Ports: 8051 has four 8 – bit Input / Output Ports which are bit addressable
and bidirectional.
• Timers / Counters: 8051 has two 16 – bit Timers / Counters.
• Serial Port: 8051 supports full duplex UART Communication.
• External Memory: 8051Microcontroller can access two 16 – bit address line at
once: one each for RAM and ROM. The total external memory that an 8051
Microcontroller can access for RAM and ROM is 64KB (216 for each type).
• Four register banks
• 128 user defined software flags
• 8-bit bidirectional data bus
• 16-bit unidirectional address bus
• 32 general purpose registers each of 8-bit
• Three internal and two external Interrupts
• 16-bit program counter and data pointer
• 8051 may also have a number of special features such as UARTs, ADC, Op-amp,
• Additional Features: on-chip oscillator, Boolean Processor, Power Down
Mode, etc.

2.4 8051 Microcontroller Architecture (Block Diagram)

It has 8 bit processing unit and 8 bit accumulator, and have 8 bit and 16 bit
8051 Microcontroller General Block Diagram

8051 Internal Block Diagram


Embedded Systems 25
It monitors controls all operations that are performed in microcontroller, its
function is to read program written in ROM memory and do the executed task.
Interrupts are subroutine call that interrupts microcontrollers main operation or
work and causes it to execute some other program which is more important at that time
it can be explain as the microcontroller terminates or pause the main program at the
occurrence of interrupt. There are five interrupts sources in 8051 microcontroller, 2
external interrupts, 2 timer interrupts, 1 serial port interrupts.
Microcontroller requires programmers which is the collection of instruction,
these programs tells microcontroller to do specific task. These instruction sets requires
memory on which they can be saved and read by microcontroller to perform operation .
The memory which is used to store the program of microcontroller is known as program
memory. It is known as ROM (read only memory), and the memory which is used to
temporarily store data for operation is knows as data memory Known as ‘RAM’, micro
controller has program memory and 128 bytes of data memory.

Bus: Bus is a collection of wires work as communication channel or media of transfer

Two types of Buses are there:
Address Bus- 16 bit address bus used to address memory location
Data bus- Carry 8 bit data.

Embedded Systems 26
As we know microcontroller is a digital circuit device hence it requires clock for
operation. 8051 has an on chip oscillators which work as clock source for CPU. The
output pulse of oscillator are stable therefore it enables synchronized work of all parts of
8051 microcontroller.
Input/output ports
As we know microcontroller is used in embedded system therefore to connect it
to the other machine or devices, or peripherals we require I/O interfacing ports for this
microcontroller has 7 input output ports to connect other peripherals.
Timers /Counters
Microcontroller has two 16 bit timers and counters. The timers are used for
measurement of intervals to determine pulse width etc.
ALU: This unit is for arithmetic calculations.
Accumulator (A): 8 bit addressable used for arithmetic operations.
B (register) – used only for two instructions MUL AB and DIV AB.
Program counter (pc)- It is a 16 bit register, by this 8051 can access program address
from 0000H to FFFFH a total of 64 kb of code.
Flag bits register and PSW registers: Flag bit register in 8051 is called as program
status word (PSW). It is an 8 bit and bit addressable special purpose register, means
each bit can be set or reset independently. There are 4 flag in 8051.
P- Parity flag- PSW 0.0
If <1> then odd number of 1 in accumulator
If <0> then even number of 1 in accumulator
Overflow flag: Used to detect error in signed arithmetic operations.
Carry flag: it is used to detect errors in unsigned arithmetic operations, and affected
after 8 bit addition and subtraction.
Stack in 8051:
Stack is use to store the data temporally 08H to 1FH can be used as stack in RAM
Stack pointer (SP): It is 8 bit register, it indicate current RAM address available for
2.5 8051 Schematic Pin out
In 8051, I/O operations are done using four ports and 40 pins. The following pin
diagram shows the details of the 40 pins. I/O operation port reserves 32 pins where
each port has 8 pins. The other 8 pins are designated as Vcc, GND, XTAL1, XTAL2, RST,
EA (bar), ALE/PROG (bar), and PSEN (bar). It is a 40 Pin PDIP (Plastic Dual Inline

Embedded Systems 27

I/O Ports and their Functions

The four ports P0, P1, P2, and P3, each use 8 pins, making them 8-bit ports.
Upon RESET, all the ports are configured as inputs, ready to be used as input ports.
When the first 0 is written to a port, it becomes an output. To reconfigure it as an input,
a 1 must be sent to a port.
Port 0 (Pin No 32 – Pin No 39)
It has 8 pins (32 to 39). It can be used for input or output. Unlike P1, P2, and P3
ports, we normally connect P0 to 10K-ohm pull-up resistors to use it as an input or
output port being an open drain.
It is also designated as AD0-AD7, allowing it to be used as both address and data.
In case of 8031 (i.e. ROMless Chip), when we need to access the external ROM, then P0
will be used for both Address and Data Bus. ALE (Pin no 31) indicates if P0 has address
or data. When ALE = 0, it provides data D0-D7, but when ALE = 1, it has address A0-
A7. In case no external memory connection is available, P0 must be connected
externally to a 10K-ohm pull-up resistor.

MOV A,#0FFH ;(comments: A=FFH(Hexadecimal i.e. A=1111 1111)

MOV P0,A ;(Port0 have 1's on every pin so that it works as Input)
Port 1 (Pin 1 through 8)
It is an 8-bit port (pin 1 through 8) and can be used either as input or output. It
doesn't require pull-up resistors because they are already connected internally. Upon

Embedded Systems 28
reset, Port 1 is configured as an input port. The following code can be used to send
alternating values of 55H and AAH to Port 1.
;Toggle all bits of continuously
MOV A,#55
CPL A ;complement(invert) reg. A
If Port 1 is configured to be used as an output port, then to use it as an input port
again, program it by writing 1 to all of its bits as in the following code.
;Toggle all bits of continuously
MOV A ,#0FFH ;A = FF hex
MOV P1,A ;Make P1 an input port
MOV A,P1 ;get data from P1
MOV R7,A ;save it in Reg R7
MOV A,P1 ;get another data from P1
MOV R6,A ;save it in R6
MOV A,P1 ;get another data from P1
MOV R5,A ;save it in R5
Port 2 (Pins 21 through 28)
Port 2 occupies a total of 8 pins (pins 21 through 28) and can be used for both
input and output operations. Just as P1 (Port 1), P2 also doesn't require external Pull-up
resistors because they are already connected internally. It must be used along with P0 to
provide the 16-bit address for the external memory. So it is also designated as (A0–A7),
as shown in the pin diagram. When the 8051 is connected to an external memory, it
provides path for upper 8-bits of 16-bits address, and it cannot be used as I/O. Upon
reset, Port 2 is configured as an input port. The following code can be used to send
alternating values of 55H and AAH to port 2.
;Toggle all bits of continuously
MOV A,#55
CPL A ; complement(invert) reg. A
If Port 2 is configured to be used as an output port, then to use it as an input port again,
program it by writing 1 to all of its bits as in the following code.
;Get a byte from P2 and send it to P1
MOV A,#0FFH ;A = FF hex
MOV P2,A ;make P2 an input port
MOV A,P2 ;get data from P2
MOV P1,A ;send it to Port 1
SJMP BACK ;keep doing that
Port 3 (Pins 10 through 17)

Embedded Systems 29
It is also of 8 bits and can be used as Input/Output. This port provides some
extremely important signals. P3.0 and P3.1 are RxD (Receiver) and TxD (Transmitter)
respectively and are collectively used for Serial Communication. P3.2 and P3.3 pins are
used for external interrupts. P3.4 and P3.5 are used for timers T0 and T1 respectively.
P3.6 and P3.7 are Write (WR) and Read (RD) pins. These are active low pins, means
they will be active when 0 is given to them and these are used to provide Read and Write
operations to External ROM in 8031 based systems.
P3 Bit Function Pin

P3.0 RxD 10

P3.1 < TxD 11

P3.2 < Complement of INT0 12

P3.3 < INT1 13

P3.4 < T0 14

P3.5 < T1 15

P3.6 < WR 16

P3.7 < Complement of RD 17

Dual Role of Port 0 and Port 2
Dual role of Port 0 − Port 0 is also designated as AD0–AD7, as it can be used for
both data and address handling. While connecting an 8051 to external memory, Port 0
can provide both address and data. The 8051 microcontroller then multiplexes the input
as address or data in order to save pins.
Dual role of Port 2 − Besides working as I/O, Port P2 is also used to provide 16-
bit address bus for external memory along with Port 0. Port P2 is also designated as
(A8– A15), while Port 0 provides the lower 8-bits via A0–A7. In other words, we can say
that when an 8051 is connected to an external memory (ROM) which can be maximum
up to 64KB and this is possible by 16 bit address bus because we know 216 = 64KB.
Port2 is used for the upper 8-bit of the 16 bits address, and it cannot be used for I/O and
this is the way any Program code of external ROM is addressed.
Hardware Connection of Pins
Vcc − Pin 40 provides supply to the Chip and it is +5 V.
Gnd − Pin 20 provides ground for the Reference.
XTAL1, XTAL2 (Pin no 18 & Pin no 19) − 8051 has on-chip oscillator but requires
external clock to run it. A quartz crystal is connected between the XTAL1 & XTAL2
pin of the chip. This crystal also needs two capacitors of 30pF for generating a signal of
desired frequency. One side of each capacitor is connected to ground. 8051 IC is
available in various speeds and it all depends on this Quartz crystal, for example, a 20
MHz microcontroller requires a crystal with a frequency no more than 20 MHz.

Embedded Systems 30

RST (Pin No. 9) − It is an Input pin and active High pin. Upon applying a high pulse
on this pin, that is 1, the microcontroller will reset and terminate all activities. This
process is known as Power-On Reset. Activating a power-on reset will cause all values in
the register to be lost. It will set a program counter to all 0's. To ensure a valid input of
Reset, the high pulse must be high for a minimum of two machine cycles before it is
allowed to go low, which depends on the capacitor value and the rate at which it charges.
(Machine Cycle is the minimum amount of frequency a single instruction requires in
EA or External Access (Pin No. 31) − It is an input pin. This pin is an active low pin;
upon applying a low pulse, it gets activated. In case of microcontroller (8051/52) having
on-chip ROM, the EA (bar) pin is connected to Vcc. But in an 8031 microcontroller
which does not have an on-chip ROM, the code is stored in an external ROM and then
fetched by the microcontroller. In this case, we must connect the (pin no 31) EA to Gnd
to indicate that the program code is stored externally.

PSEN or Program store Enable (Pin No 29) − This is also an active low pin, i.e., it
gets activated after applying a low pulse. It is an output pin and used along with the EA
pin in 8031 based (i.e. ROMLESS) Systems to allow storage of program code in external
ALE or (Address Latch Enable) − This is an Output Pin and is active high. It is especially
used for 8031 IC to connect it to the external memory. It can be used while deciding
whether P0 pins will be used as Address bus or Data bus. When ALE = 1, then the P0
pins work as Data bus and when ALE = 0, then the P0 pins act as Address bus.
2.6 I/O Ports and Bit Addressability
It is a most widely used feature of 8051 while writing code for 8051. Sometimes
we need to access only 1 or 2 bits of the port instead of the entire 8-bits. 8051 provides
the capability to access individual bits of the ports.

Embedded Systems 31
While accessing a port in a single-bit manner, we use the syntax "SETB X. Y" where X is
the port number (0 to 3), and Y is a bit number (0 to 7) for data bits D0-D7 where D0 is
the LSB and D7 is the MSB. For example, "SETB P1.5" sets high bit 5 of port 1.
The following code shows how we can toggle the bit P1.2 continuously.
CLR P1.2
Single-Bit Instructions
Instructions Function

SETB bit Set the bit (bit = 1)

CLR bit clear the bit (bit = 0)

CPL bit complement the bit (bit = NOT bit)

JB bit, target jump to target if bit = 1 (jump if bit)

JNB bit, jump to target if bit = 0 (jump if no bit)


JBC bit, target jump to target if bit = 1, clear bit (jump if bit, then
2.7 On-Chip Memory Internal RAM

2.7.1 General Purpose Registers

Four Register Banks, Each bank has R0-R7, Selectable by psw.2,3

Embedded Systems 32

mov A,R5
mov A, 05h
Register Banks
 Active bank selected by PSW [RS1,RS0] bit
 Permits fast “context switching” in interrupt service routines (ISR).

Embedded Systems 33
2.7.2 Bit Addressable Memory

20h – 2Fh (16 locations * 8-bits = 128 bits)

Bit addressing: mov C, 67h or mov C, 2Ch.7
2.7.3 General Memory
 Address from 30h – 7fh
 Addressed by byte

2.7.4 Special Function Registers

 DATA registers
 CONTROL registers
o Timers
o Serial ports
o Interrupt system

Embedded Systems 34
o Analog to Digital converter
o Digital to Analog converter
o Etc.
 Addresses 80h – FFh
 Direct Addressing used to access SPRs
2.7.5 Bit Addressable RAM

2.7.6 Registers

Embedded Systems 35

Chapter-3: 8051 Programming in Assembly Language

3.1 Introduction
The assembly language is a low-level programming language used to write
program code in terms of mnemonics. Even though there are many high-level languages
that are currently in demand, assembly programming language is popularly used in
many applications. It can be used for direct hardware manipulations. It is also used to
write the 8051 programming code efficiently with less number of clock cycles by
consuming less memory compared to the other high-level languages.

3.2 8051 Programming Execution Steps of Assembly Language

The assembly language is a fully hardware related programming language. The
embedded designers must have sufficient knowledge on hardware of particular
processor or controllers before writing the program. The assembly language is
developed by mnemonics; therefore, users cannot understand it easily to modify the

Assembly programming language is developed by various compilers and the

“keiluvison” is best suitable for microcontroller programming development.
Microcontrollers or processors can understand only binary language in the form of ‘0s
or 1s’; An assembler converts the assembly language to binary language, and then stores
it in the microcontroller memory to perform the specific task.
The assembly language is made up of elements which all are used to write the
program in sequential manner. Follow the given rules to write programming in
assembly language.
Rules of Assembly Language
• The assembly code must be written in upper case letters
• The labels must be followed by a colon (label:)
• All symbols and labels must begin with a letter
• All comments are typed in lower case
• The last line of the program must be the END directive

Embedded Systems 36
• The assembly language mnemonics are in the form of op-code, such as MOV,
ADD, JMP, and so on, which are used to perform the operations.

Op-code: The op-code is a single instruction that can be executed by the CPU. Here the
op-code is a MOV instruction.
Operands: The operands are a single piece of data that can be operated by the op-
code. Example, multiplication operation is performed by the operands that are
multiplied by the operand.
Syntax: MUL a,b;
3.3 The Elements of an Assembly Language Programming
• Assembler Directives
• Instruction Set
• Addressing Modes
Assembler Directives:
The assembling directives give the directions to the CPU. The
8051 microcontroller consists of various kinds of assembly directives to give the
direction to the control unit. The most useful directives are 8051 programming, such as:
ORG(origin): This directive indicates the start of the program. This is used to set the
register address during assembly. For example; ORG 0000h tells the compiler all
subsequent code starting at address 0000h.
Syntax: ORG 0000h

DB(define byte): The define byte is used to allow a string of bytes. For example, print
the “EDGEFX” wherein each character is taken by the address and finally prints the
“string” by the DB directly with double quotes.
ORG 0000h
MOV a, #00h

EQU (equivalent): The equivalent directive is used to equate address of the variable.
reg equ,09h

Embedded Systems 37
MOV reg,#2h
END:The END directive is used to indicate the end of the program.
reg equ,09h
MOV reg,#2h
3.4 Addressing Modes
The way of accessing data is called addressing mode. The CPU can access the data
in different ways by using addressing modes. The 8051 microcontroller consists of five
addressing modes such as:
• Immediate Addressing Mode
• Register Addressing Mode
• Direct Addressing Mode
• Indirect Addressing Mode
• Base Index Addressing Mode
Immediate Addressing Mode:
In this addressing mode, the source must be a value that can be followed by the
‘#’ and destination must be SFR registers, general purpose registers and address. It is
used for immediately storing the value in the memory registers.
MOV A, #20h //A is an accumulator register, 20 is stored in the A//
MOV R0,#15 // R0 is a general purpose register; 15 is stored in the R0 register//
MOV P0, #07h //P0 is a SFR register;07 is stored in the P0//
MOV 20h,#05h //20h is the address of the register; 05 stored in the 20h//
MOV R0, #1
MOV R0, #20 //R0 <—R0[15]+20, the final value is stored in R0//

Register Addressing Mode:

In this addressing mode, the source and destination must be a register, but not
general purpose registers. So the data is not moved within the general purpose bank
MOV A, B; // A is a SFR register, B is a general purpose register//
MOV R0, R1 //Invalid instruction, GPR to GPR not possible//
MOV R0, #02h
MOV A, #30h
ADD R0, A //R0<—R0+A, the final value is stored in the R0 register//

Direct Addressing Mode

Embedded Systems 38
In this addressing mode, the source or destination (or both source and destination)
must be an address, but not value.
MOV A,20h // 20h is an address; A is a register//
MOV 00h, 07h // both are addressed of the GPS registers//
MOV 07h,#01h
MOV A, #08h
ADD A,07h //A<—A+07h the final value is stored in A//

Indirect Addressing Mode:

In this addressing mode, the source or destination (or destination or source) must
be a indirect address, but not a value. This addressing mode supports the pointer
concept. The pointer is a variable that is used to store the address of the other variable.
This pointer concept is only used for R0 and R1 registers.
MOVR0, #01h //01 value is stored in the R0 register, R0 address is 08h//
MOV R1, #08h //R1 is the pointer variable that stores address (08h) of R0 //
MOV 20h,@R1 //01 value is stored in the 20h address of the GP register//

Base Index Addressing Mode:

This addressing mode is used to read the data from the external memory or ROM
memory. All addressing modes cannot read the data from the code memory. The code
must read through the DPTR register. The DPTR is used to point the data in the code or
external memory.
MOVC A, @A+DPTR //C indicates code memory//
MOCX A, @A+DPTR // X indicate external memory//
EX: MOV A, #00H //00H is stored in the A register//
MOV DPTR, #0500H //DPTR points 0500h address in the memory//
MOVC A, @A+DPTR //send the value to the A register//
MOV P0, A //date of A send to the PO registrar//

3.5 Instruction Set

The instruction set is the structure of the controller or processor that provides
commands to the controller to guide the controller for processing data. The instruction
set consists of instructions, native data types, addressing modes, interrupt registers,
exceptional handling and memory architecture. The 8051 microcontroller can follow
CISC instructions with Harvard architecture. In case of the 8051 programming different
types of CISC instructions include:
• Data Transfer Instruction set
• Sequential Instruction Set

Embedded Systems 39
• Arithmetic Instruction set
• Branching Instruction set
• Loop Instrcution Set
• Conditional Instruction set
• Unconditional Instruction set
• Logical Instruction set
• Boolean Instruction set
Arithmetic Instruction Set:
The arithmetic instructions perform the basic operations such as:
• Addition
• Multiplication
• Subtraction
• Division
ORG 0000h
MOV R0, #03H // move the value 3 to the register R0//
MOV A, #05H // move the value 5 to accumulator A//
Add A, 00H // addA value with R0 value and stores the result inA//
ORG 0000h
MOV B, #03H // move the value 3 to the register R0//
MOV A, #05H // move the value 5 to accumulator A//
MUL AB // Multiplied result is stored in the Accumulator A //
ORG 0000h
MOV R0, #03H // move the value 3 to register R0//
MOV A, #05H // move the value 5 to accumulator A//
SUBB A, 00H // Result value is stored in the Accumulator A //
ORG 0000h
MOV B, #03H // move the value 3 to register R0//
MOV A, #15H // move the value 5 to accumulator A//
DIV AB // final value is stored in the Accumulator A //

Embedded Systems 40
Conditional Instructions:
The CPU executes the instructions based on the condition by checking the single bit
status or byte status. The 8051 microcontroller consists of various conditional
instructions such as:
JB —>Jump below
JNB —> Jump if not below
JC —> Jump if Carry
JNC —>Jump if not Carry
JZ —>Jump if Zero
JNZ —> Jump if not Zero

1. Syntax:
JB P1.0, label
Label: – – – – – – – –
2. Syntax:
JNB P1.0, label
Label: – – – – – – – –
3. Syntax:
JC, label
Label: – – – – – – – –
4. Syntax:
JNC, label
Label: – – – – – – – –
5. Syntax:
JZ, label
Embedded Systems 41
Label: – – – – – – – –
6. Syntax:
JNZ, label
Label: – – – – – – – –
Call and Jump Instructions:
The call and jump instructions are used to avoid the code replication of the
program. When some specific code used more than once in different places in the
program, if we mention specific name to code then we could use that name anywhere in
the program without entering a code for every time. This reduces the complexity of the
program. The 8051 programming consists of call and jump instructions such as LCALL,
1. Syntax:
ORG 0000h
ACALL, label
Label: – – – – – – – –
2. Syntax:
ORG 0000h
LCALL, label
Label: – – – – – – – –

Embedded Systems 42

Loop Instructions:
The loop instructions are used to repeat the block each time while performing
the increment and decrement operations. The 8051 microcontroller consist two types of
loop instructions:
CJNE —> compare and jump if not equal
DJNZ —> decrement and jump if not zero
1. Syntax:
MOV A, #00H
MOV B, #10H
Label:INC A
CJNE A, label
2. Syntax:
MOV R0, #10H
Label:– – – – – –
DJNE R0, label
Logical Instruction Set:
The 8051 microcontroller instruction set provides the AND, OR, XOR, TEST,
NOT and Boolean logic instructions for set and clears the bits based on the need in the

1. Syntax:
MOV A, #20H /00100000/
MOV R0, #03H /00000101/
ORL A, R0 //00100000/00000101=00000000//

Embedded Systems 43
2. Syntax:
MOV A, #20H /00100000/
MOV R0, #03H /00000101/
3. Syntax:
MOV A, #20H /00100000/
MOV R0, #03H /00000101/
Shifting Operators
The shift operators are used for sending and receiving the data efficiently. The
8051 microcontroller consist four shift operators:
RR —> Rotate Right
RRC —>Rotate Right through carry
RL —> Rotate Left
RLC —>Rotate Left through carry
Rotate Right (RR):
In this shifting operation, the MSB becomes LSB and all bits shift towards right side bit-
by-bit, serially.
MOV A, #25h

Rotate Left (RL):

In this shifting operation, the MSB becomes LSB and all bits shift towards Left side bit-
by-bit, serially.
MOV A, #25h

RRC Rotate Right through Carry:

In this shifting operation, the LSB moves to carry and the carry becomes MSB, and all
the bits are shift towards right side bit by bit position.
MOV A, #27h
RLC Rotate Left through Carry:
In this shifting operation, the MSB moves to carry and the carry becomes LSB and all
the bits shift towards left side in a bit-by-bit position.
MOV A, #27h

Embedded Systems 44

Chapter-4: 8051 Microcontroller Applications

4.1 Embedded Software Development Tools
Application programs are typically developed, compiled, and run on host system
Embedded programs are targeted to a target processor (different from the
development/host processor and operating environment) that drives a device or
controls What tools are needed to develop, test, and locate embedded software into the
target processor and its operating environment?
Host: Where the embedded software is developed, compiled, tested, debugged,
optimized, and prior to its translation into target device. (Because the host has
keyboards, editors, monitors, printers, more memory, etc. for development, while the
target may have not of these capabilities for developing the software.)
Target: After development, the code is cross-compiled, translated – cross-assembled,
linked (into target processor instruction set) and located into the target
Cross-Compilers –
Native tools are good for host, but to port/locate embedded code to target, the
host must have a tool-chain that includes a cross-compiler, one which runs on the host
but produces code for the target processor
Cross-compiling doesn’t guarantee correct target code due to (e.g., differences in word
sizes, instruction sizes, variable declarations, library functions)
Cross-Assemblers and Tool Chain
Host uses cross-assembler to assemble code in target’s instruction syntax for the
Tool chain is a collection of compatible, translation tools, which are ‘pipelined’ to
produce a complete binary/machine code that can be linked and located into the target
4.1.1 Procedure for Embedded System Programming

Embedded Systems 45

4.1.2 Basics Declaration

The extension of the C language is called an Embedded C programming
language. The embedded programming in C language has some additional features such
as data types and keywords and header file or library file is represented as
#include<microcontroller name. h>
Embedded C Additional Keywords
macros define

The “sbit” is used for declaring the single PIN of the microcontroller. For example LED
is connected to the P0.1 pin, it is not recommended to send the value to the port pin
directly, first we have to declare the pin with another variable then after we can use
anywhere in the program.
Syntax: sbit a=P0^1; //declares the respective pin with a variable//
a=0x01; //send the value to the port pin//

The “bit” is used for checking the status of the variable.

Syntax: bit c; //declares the bit variable//
c=a; //a value is assigned to the c variable //
if(c==1) //check the condition true or false//

Embedded Systems 46
The “SFR” keyword is used to access the SFR registers by another name. The SFR
register defined as a special function register, it contains all peripheral related registers
by indicating the address. The SFR register is declared by the SFR keyword. The SFR
keyword must be in capital letters.
Syntax: SFR port=0x00; //0x00 is a port0 address it is declared by port variable//
Port=0x01; //then send the value to the port0//
The “volatile” keyword is most important keyword in the embedded system
development. The variable that declares with the volatile keyword value could not be
changed unexpectedly. It can be used in memory mapped peripheral registers, global
variables modified by the ISRs. Without using the volatile keyword for transmitting and
receiving the data, code error or an optimization error will takes place.
Syntax: volatile int k;

The macro is a name it is used to declare the block of statements as pre-processor

directive. Whenever the name is used, it is replaced by the contents of the macro. The
macros represent by the #define. The whole port pins are defined by the macros.
Syntax: #define dat Po; //the whole port is declared by a variable//
dat=0x01; //data send to the port0//

4.2 Embedded Applications

• LED interfacing with 8051 microcontroller
• Push Button Interfacing with 8051 microcontrollers
• LCD Interfacing with 8051 microcontroller
• Keypad Interfacing with 8051 microcontroller
• UART in 8051 microcontroller
4.2.1 LED interfacing with 8051 microcontroller
The LED is a semiconductor device which is used in many applications, mostly for
indication purpose. It is finding a huge range of applications as indicators during test to
check the validity of results at different stages. They are very cheap and easily available
in a variety of shape, color and size. The LEDs are used to design message display
boards and traffic control signal lights etc. Here the LEDs are interfaced to the PORT3
of the 8051 microcontroller.LED blinking is the most basic application with a
microcontroller to see a physical output. One can understand the concept of input-
output configurations of the general-purpose I/O port in a microcontroller with the
simple LED blinking project.
Interfacing LED with Microcontroller Pin

Embedded Systems 47

Circuit Diagram

#include<reg51.h> // special function register declarations
// for the intended 8051 derivative
void main (void)
while(1) // infinite loop
P3 = 0x00; // LED ON
P3 = 0xff; // LED OFF

Embedded Systems 48
void Delay(void)
int j;
int i;

4.2.2 Push Button Interfacing with 8051 microcontrollers

Push buttons are used for switch mechanisms in embedded systems. A switch connected
to an IO pin when pressed can change the state of the pin to low or high depending on
its initial state. The change can be identified in firmware and can make the controller
work accordingly. This tutorial includes a simple example of interfacing a push button
with the AT89S51 controller so as to glow an LED.

The push button is connected to P0.0 (0th pin of port0). The pin is connected
externally with a pull-up resistor since there is no internal pull-up resistor for port 0.
The other end of the pushbutton is connected to ground. The voltage at the pin will be
VCC when the button is not pushed. It will get grounded on pressing the button. The
LED connected to the P2.0 pin is connected with a series resistor to limit the current.
#define LED P2_0

Embedded Systems 49
#define switch_pin P0_0
void Delay(int k)
int j;
int i;
void main (void)
switch_pin = 1; // Making Switch PIN input
LED_pin=1; //LED off initially

while(1) //infinite loop

if(switch_pin == 0 ) //If switch pressed
LED_pin = 0; //LED ON
Delay(2000); //Delay
LED_pin = 1; //LED OFF

4.2.3 LCD (Liquid Crystal Display) Interfacing with 8051 microcontroller

16×2 Liquid Crystal Display which will display the 32 characters at a time in two rows
(16 characters in one row). Each character in the display is of size 5×7 pixel matrix. This
matrix differs for different 16×2 LCD modules, if you take JHD162A, this matrix goes to
5×8. There are 16 pins in the LCD module, the pin configuration us given below
1 VSS Ground pin

2 VCC Power supply pin of 5V

3 VEE Used for adjusting the contrast commonly attached to the

Embedded Systems 50



4 RS RS is the register select pin used to write display data to the LCD
(characters), this pin has to be high when writing the data to the LCD.
During the initializing sequence and other commands this pin should

5 R/W Reading and writing data to the LCD for reading the data R/W pin
should be high (R/W=1) to write the data to LCD R/W pin should be
low (R/W=0)

6 E Enable pin is for starting or enabling the module. A high to low pulse
of about 450ns pulse is given to this pin.

7 DB0

8 DB1

9 DB2

10 DB3

11 DB4 DB0-DB7 Data pins for giving data(normal data like numbers
characters or command data) which is meant to be displayed

12 DB5

13 DB6

14 DB7

15 LED+ Back light of the LCD which should be connected to Vcc

16 LED- Back light of LCD which should be connected to ground.

So by reading the above table you can get a brief idea how to display a character. For
displaying a character you should enable the enable pin (pin 6) by giving a pulse of
450ns, after enabling the pin6 you should select the register select pin (pin4) in write
mode. To select the register select pin in write mode you have to make this pin high
(RS=1), after selecting the register select you have to configure the R/W to write mode
that is R/W should be low (R/W=0).
Follow these simple steps for displaying a character or data
E=1; enable pin should be high
RS=1; Register select should be high
R/W=0; Read/Write pin should be low.
To send a command to the LCD just follows these steps:
E=1; enable pin should be high
RS=0; Register select should be low
R/W=0; Read/Write pin should be low.

Embedded Systems 51

Commands: There are some preset commands which will do a specific task in the
LCD. These commands are very important for displaying data in LCD. The list of
commands given below:
0F For switching on LCD, blinking the cursor.

1 Clearing the screen

2 Return home.

4 Decrement cursor

6 Increment cursor

E Display on and also cursor on

80 Force cursor to beginning of the first line

C0 Force cursor to beginning of second line

38 Use two lines and 5x7 matrix

83 Cursor line 1 position 3

3C Activate second line

0C3 Jump to second line position 3

0C1 Jump to second line position1

Interfacing 16×2 LCD with 8051 Circuit Diagram

Embedded Systems 52

Programming LCD to 8051

Coming to the programming you should follow these steps:
STEP1: Initialization of LCD.
STEP2: Sending commands to LCD.
STEP3: Writing the data to LCD.
Initializing LCD
To initialize LCD to the 8051 the following instruction and commands are to be embed
in to the functions
0x38 is used for 8-bit data initialization.
0xoC for making LCD display on and cursor off.
0X01 for clearing the display of the LCD.
0x80 for positioning the cursor at first line .
Sending Commands to the LCD
E=1; enable pin should be high
RS=0; Register select should be low for sending commands
Placing the data on the data registers
R/W=0; Read/Write pin should be low for writing the data.
Writing the Data to the LCD
E=1; enable pin should be high
RS=1; Register select should be high for writing data
Placing the data on the data registers
R/W=0; Read/Write pin should be low for writing the data.
#define lcd P0
sbit rs=P2^0;
sbit e=P2^1;

Embedded Systems 53
void delay (int);
void cmd (char);
void display (char);
void custom (void);
void string (char *);
void init (void);

unsigned char custom_char[]= {0x00,0x04,0x0E,0x04,0x15,0x0E,0x04,0x00,

0x00,0x0E,0x15,0x1B,0x0E,0x0E,0x00,0x00, };

void delay (int d)

unsigned char i;
void cmd (char c)
void display (char c)
void custom (void)
int k;

Embedded Systems 54
void string (char *p)
void init (void)
void main()
string("Electronics Hub ");
string(" Presents ");
string(" Custom Chars ");
string(" on 16x2 LCD ");

4.2.4 Keypad Interfacing with 8051 microcontroller

Matrix Keypad Interfacing
The advantage of a matrix keypad is that the use of it will allow the programmer
to reduce the number of pins to be used. In a 4×4 matrix keypad, there are four rows
and four columns connected to 16 push button switches. It may look like one needs 16

Embedded Systems 55
pins for the microcontroller to be connected to the matrix keypad but practically 16
inputs of keypad interface are possible with the 8 pins of a microcontroller port. All 8
lines can be connected to the same port or different ports based on the application
requirements. In fact, 8 port pins of a microcontroller are sufficient for a 4×4 keypad
interface using row & column matrix connection technique by saving other 8 bits of the
Matrix keypad interfacing and key press identification can be explained in a step
by step manner which involves a software. First, we give a HIGH on row pins. When a
key is pressed, the corresponding row and column get shorted. In the second step, a
software scans the pins connected to the columns. If it detects a HIGH on any particular
column, then it is found that the key press has been made of a key in that column. The
third step is to figure out which key is pressed exactly. For this, the software writes logic
high on row pins sequentially. The pin of the column on which the pressed key is
situated will become high.
Principle of Working

4x4 Keypad

Keypad is used as an input device to read the key pressed by user and to process it.
4x4 keypad consists of 4 rows and 4 columns. Switches are placed between the rows and
columns. A key press establishes a connection between corresponding row and column
between which the switch is placed.
To read the key press, we need to configure the rows as outputs and columns as inputs.
Columns are read after applying signals to the rows in order to determine whether or
not a key is pressed and if pressed, which key is pressed.

Embedded Systems 56
For more information about keypad and how to use it, refer the topic 4x4 Keypad in the
sensors and modules section.
Here, we are going to interface 4x4 keypad with AT89S52 (8051) and will display the
pressed key on LCD16x2.
Interfacing Diagram

Keypad interfacing with 8051 Program

4x4 Keypad Interfacing with 8051(AT89s52)

#include "LCD_8_bit.h" /* 16x2 LCD header file*/

#define keyport P1

sbit RS = P3^5; /* RS(register select) for LCD16x2 */

sbit RW = P3^6; /* RW(Read/write) for LCD16x2 */
sbit ENABLE = P3^7; /* EN(Enable) pin for LCD16x2*/
unsigned char keypad[4][4] = {{'7','8','9','/'},
{' ','0','=','+'} };

Embedded Systems 57
unsigned char colloc, rowloc;
unsigned char key_detect()
keyport=0xF0; /*set port direction as input-output*/
keyport = 0xF0;
colloc = keyport;
colloc&= 0xF0; /* mask port for column read only */
}while(colloc != 0xF0); /* read status of column */

delay(20); /* 20ms key debounce time */
colloc = (keyport & 0xF0); /* read status of column */
}while(colloc == 0xF0); /* check for any key press */

colloc = (keyport & 0xF0);
}while(colloc == 0xF0);

/* now check for rows */
keyport= 0xFE;
/* check for pressed key in 1st row */
colloc = (keyport & 0xF0);
if(colloc != 0xF0)
rowloc = 0;

keyport = 0xFD;
/* check for pressed key in 2nd row */
colloc = (keyport & 0xF0);
if(colloc != 0xF0)
rowloc = 1;

keyport = 0xFB; /* check for pressed key in 3rd row */

colloc = (keyport & 0xF0);
if(colloc != 0xF0)

Embedded Systems 58
rowloc = 2;

keyport = 0xF7; /* check for pressed key in 4th row */

colloc = (keyport & 0xF0);
if(colloc != 0xF0)
rowloc = 3;

if(colloc == 0xE0)
else if(colloc == 0xD0)
else if(colloc == 0xB0)

int main(void)
LCD_String_xy(1,0,"Press a key");

LCD_Char(key_detect()); /* Display which key is pressed */

4.2.5 Serial Communication with 8051 microcontroller

A serial communication programming of 8051 microcontroller. when electronic
devices communicate with each other, They can transfer data in two different ways. One
is serial and other one is parallel, When digital data is transferred serially, it is
transmitted bit by bit, whereas in parallel transfer, many bits are transmitted at same

Embedded Systems 59
time. Though parallel transfer of data is much faster but requires many wires. while
serial transfer is slower as compared to parallel transfer but requires few wires. Serial
communication maybe synchronous or asynchronous. In synchronous communication,
transmitter also transmits a clock along with data. This clock is used for synchronization
between transmitter and receiver device In asynchronous transfer of data, There is no
Serial communication maybe simplex, half-duplex or full duplex. simplex
communication means that data will be transmitted only in one direction while half
duplex means data will be transmitted in both directions but at one time, only one
device can transmit, whereas full duplex means data may be transmitted in both
directions at one time, while one device is transmitting, it can also receive data
transmitted from other device at same time. As I have mentioned before, transmitter
and receiver are configured to communicate at some data transfer rate before
communication starts. This data transfer rate or number of bits transmitted per second
is called baud rate for handling serial communication.
Parallel communication is fast but it is not applicable for long distances (for
printers). Moreover it is also expensive. Serial is not much fast as parallel
communication but it can deal with transmission of data over longer distances (for
telephone line, ADC, DAC). It is also cheaper and requires less physical wires, that’s why
we use serial communication. This article also deals with how to serially communicate in
8051 microcontroller.

Methods of Serial Communication

There are two methods of Serial Communication:

Synchronous: Transfer the block of data (characters) between sender and receiver
spaced by fixed time interval. This transmission is synchronized by an external clock.
Asynchronous: There is no clock involved here and transmission is synchronized by
special signals along the transmission medium. It transfers a single byte at a time
between sender and receiver along with inserting a start bit before each data character
and a stop bit at its termination so that to inform the receiver where the data begins and

Embedded Systems 60
ends. An example is the interface between a keyboard and a computer. Keyboard is the
transmitter and the computer is the receiver. We use USART and UART for serial
communications. USART or UART is a microcontroller peripheral which converts
incoming and outgoing bytes of data into a serial bit stream. Both have same work but
with different methods which is explained below.
USART: USART stands for Universal Synchronous/Asynchronous Receiver-
Transmitter. USART uses external clock so it needs separate line to carry the clock
signal. Sending peripheral generates a clock and the receiving peripheral recover from
the data stream without knowing the baud rate ahead of time. By use of external clock,
USART’s data rate can be much higher (up to rates of 4 Mbps) than that of a standard
UART: It stands for Universal Asynchronous Receiver-Transmitter. A UART generates
its internal data clock to the microcontroller. It synchronizes that clock with the data
stream by using the start bit transition. The receiver needs the baud rate to know ahead
of time to properly receive the data stream.
8051 Serial Communication Programming Registers
8051 microcontroller has a built-in serial port called UART. We can easily read and
write values to the serial port. For using serial port we simply need to configure the
serial port:
Operation mode (how many data bits we want)
Baud rate
There are 21 Special function registers (SFR) in 8051 microcontroller and 21 unique
locations are for these 21 SFR. Each of these register is of 1 byte size. The “Serial
Control” (SCON) is the SFR which is used to configure serial port.

SM0: Serial port mode

Bit 0 of serial port mode.
SM1: Serial port mode
Bit 1 of serial port mode.
SM2: Enable multiprocessor
Enable multiprocessor communication in modes 2 and 3 (for 9 bit UART).
REN: Receiver Enable
Set/clear by software to enable/disable receive operation
TB8: Transmit bit 8
Set or clear by software. The 9 bits will be transmitted in mode 2 and 3.
TB8 = 1, a value is written to the serial port, 9th bit of data = 1.
TB8 = 0, 9th bit of data = 0, RI will not set.
RB8: Receive bit 8
Set or clear by software. The 9 bits will be received in mode 2 and 3. First eight bits are
the data received and 9th bit received will be placed in RB8.
TI: Transmit Interrupt flag
Set by hardware when a byte is transmitted completely. Now the port is free and ready
to send the next byte. This bit must be cleared by software.
RI: Receive Interrupt flag

Embedded Systems 61
Set by hardware when a byte has been completely received. This lets the program to
know that it needs to read the value quickly before another byte is read. This bit must be
cleared by software.

Configuration Settings
Setting Operation Mode of Serial Port:
The Upper four bits are configuration bits. SM0 and SM1 set the serial mode between
0 and 3. The four modes along with the baud rates are in the table given below. In
modes 0 and 2 the baud rate is fixed which is based on the oscillator frequency. In
modes 1 and 3 the baud rate is variable which depends on how often Timer 1 overflows.
Baud rate
SM0 SM1 MODE Description

0 0 0 shift register (Fosc./12)

0 1 1 8 bit UART Variable (set by Timer 1)

1 0 2 9 bit UART (Fosc./64)

1 1 3 9 bit UART Variable (set by Timer 1)

SM2 is a flag bit for Multiprocessor communication. When SM2 is set, the 8051
microcontroller will set the RI (Receive Interrupt) flag whenever a byte is received (if
the 9th bit received is “1”). By this way, program knows that a byte has been received
and it needs to be processed. If 9th bit is clear, the RI flag will never be set. We will clear
this RI bit so that the flag is set upon reception of any character.
If SM2=1, RI=1 (only if 9th bit of received byte is 1)
REN is Receiver Enable bit. Set this bit if we want to receive data through serial port.
REN=1 (for serial communication)
Setting the Baud Rate of Serial Port:
Baud Rate:
It is defined as number of bits transmitted or received per second and is usually
expressed in Bits per second bps. After setting the operation mode of serial port, the
program must configure the serial ports baud rate which is only applicable to Serial Port
modes 1 and 3. For mode 0 and 2 oscillator frequency determines the Baud Rate.
For mode 0:
Baud rate is always the oscillator frequency divided by 12. For crystal of frequency
11.059MHz, Baud rate will be 921,583 baud.
Baud rate = (11.0592MHz/12) = 921,583 baud
For mode 2:
Baud rate is always the oscillator frequency divided by 64. For crystal of frequency
11.059MHz, Baud rate will be 172,797 baud.
Baud rate == (11.0592MHz/64) = 172,797 baud
For mode 1 and 3:
For them, the baud rate is determined by how frequently timer 1 overflows. The more
frequent timer 1 overflows, the higher the baud rate. There are many ways due to which
timer 1 overflows at a rate that determines a baud rate. The most common method is:
We put timer 1 in 8-bit auto-reload mode (timer mode 2).

Embedded Systems 62
This 8 bit timer that allows only values of 00 to FFH loaded in timer register TH1.
Set a reload value in TH1 that causes Timer 1 to overflow at a frequency appropriate to
generate a baud rate.
If PCON.7 is clear (SMOD=0), then to generate a given baud rate, the value to be put in
TH1 can be determined from an equation:
TH1 = 256 – ((Crystal / 384) / Baud)
If the value to be load in TH1 by above equation is not in whole number then we can’t
get accurate baud rate. For that case, set PCON.7 (SMOD=1). The baud rate gets double
and the equation becomes:
TH1 = 256 – ((Crystal / 192) / Baud)
How to calculate baud rate for serial communication in 8051
Let us take an example. If we have crystal of frequency 11.059MHz and we want to
configure the serial port to 19,200 baud rate, firstly we try equation 1. By using equation
TH1 = 256 – ((Crystal / 384) / Baud)
TH1 = 256 – ((11.059MHz/ 384) / 19200 )
TH1 = 256 – 1.5 = 254.5
By setting 254 and 255, we don’t achieve accurate baud rate so we need to set PCON.7
(SMOD=1). This doubles the baud rate and we will use equation 2 for determining TH1
value. By using equation 2:
TH1 = 256 – ((Crystal / 192) / Baud)
TH1 = 256 – ((11.059MHz/ 192) / 19200)
TH1 = 256 – 3 = 253
Thus by setting TH1 to 253 we get correct frequency for 19,200 baud rate.

Example of serial communication 8051 microcontroller in Keil

8051 microcontroller is used in the schematic. Crystal frequency is set to 11.059MHz.
Baud rate used is 9600. A virtual terminal is used. The data coming from transmitter
pin of controller will be displayed on virtual terminal. The send to the microcontroller is
also received on receiver pin of controller which is sent through virtual terminal by
pressing specific key. The program is such that the baud rate is set to 9600.
For 9600 baud rate:
TH1 = 256 – ((Crystal / 384) / Baud)
TH1 = 256 – ((11.59MHz/ 384) / 9600 )
TH1 = 256 – 3 = 253
The Hex value of 253 is FD which should be loaded to TH1
Port 3 pin 0 receiver pin is connected to TX of virtual terminal.
Port 3 pin 1 transmitter pin is connected to RX of virtual terminal.
Port 1 lower four pins are connected with 4 LEDs.
Code of serial communication 8051 microcontroller
#include <REGX51.H>
void cct_init(void);
void SerialInitialize(void);
void uart_msg(unsigned char *c);
void uart_tx(unsigned char);
sbit led1 = P1^0;
sbit led2 = P1^1;

Embedded Systems 63
sbit led3 = P1^2;
sbit led4 = P1^3;
void main()
EA = 1;
ES = 1;
uart_msg("Initializing Serial Communication");
uart_msg("1,2,3,4 key can on leds and a,b,c,d can off them respectively.");
uart_tx(0x0d); //next line
uart_msg("Press the key for particular LED");

void cct_init(void) //initialize cct

P0 = 0x00; //not used
P1 = 0x00; //output port used for leds
P2 = 0x00; //not used
P3 = 0x03; //used for serial communication

void SerialInitialize(void) //Initialize Serial Port

TMOD = 0x20; //Timer 1 In Mode 2 -Auto Reload to Generate Baud Rate
SCON = 0x50; //Serial Mode 1, 8-Data Bit, REN Enabled
TH1 = 0xFD; //Load Baud Rate 9600 To Timer Register
TR1 = 1; //Start Timer

void uart_msg(unsigned char *c)

while(*c != 0)

void uart_tx(unsigned char serialdata)

SBUF = serialdata; //Load Data to Serial Buffer Register
while(TI == 0); //Wait Until Transmission To Complete
TI = 0; //Clear Transmission Interrupt Flag

Embedded Systems 64
void serial_ISR (void) interrupt 4
char chr; //receive character
chr = SBUF;
RI = 0;
P0 = ~P0; //Show the data has been updated
case '1': led1 = 1; uart_msg("1st on"); uart_tx(0x0d); break;
case '2': led2 = 1; uart_msg("2nd on"); uart_tx(0x0d); break;
case '3': led3 = 1; uart_msg("3rd on"); uart_tx(0x0d); break;
case '4': led4 = 1; uart_msg("4th on"); uart_tx(0x0d); break;
case 'a': led1 = 0; uart_msg("1st off"); uart_tx(0x0d); break;
case 'b': led2 = 0; uart_msg("2nd off"); uart_tx(0x0d); break;
case 'c': led3 = 0; uart_msg("3rd off"); uart_tx(0x0d); break;
case 'd': led4 = 0; uart_msg("4th off"); uart_tx(0x0d); break;
default: ; break; //do nothing
RI = 0;

Chapter-5: Real-Time Operating Systems

5.1 Introduction to Real-Time Operating Systems
Embedded Computing Applications exist in a spectacular range of size and
complexity for areas such as home automation to cell phones, automobiles and
industrial controllers. Most of these applications demand such functionality,
performance and reliability from the software that simple and direct assembly language
programming of the processors is clearly ruled out. Moreover, as a distinguishing
feature from general purpose computing, a large part of the computation is “real-time”
or time constrained and also reactive or “external event driven” since such systems
generally interface strongly with the external environment through a variety of devices.
Thus, an operating system is generally used. An operating system facilitates
development of application program by making available a number of services, which,
otherwise would have to be coded by the application program. The application programs
“interface” with the hardware through a operating system services and functions. It is

Embedded Systems 65
therefore important understand the basic features of such operating systems. In this
chapter we present the fundamental concepts of a real-time operating system in a
generic context. Most large industrial controllers employ such operating systems.
What is an RTOS?
A Real Time Operating System, commonly known as an RTOS, is a software
component that rapidly switches between tasks, giving the impression that multiple
programs are being executed at the same time on a single processing core. “Real-Time
Operating System (RTOS) is a multitasking operating system intended for real-time
applications.” RTOS is implemented in products all around us, ranging from military,
and consumer to scientific applications. In actual fact the processing core can only
execute one program at any one time, and what the RTOS is actually doing is rapidly
switching between individual programming threads (or Tasks) to give the impression
that multiple programs are executing simultaneously. Examples of RTOS vendors are:
VxWorks, VRTX, pSOS, Nucleus, C Executive, LynxOS, QNX, Multi-Task!, AMX, and
dozens more.
Difference Between GPOS And RTOS
• General purpose operating systems cannot perform real time tasks whereas
RTOS is suitable for real time applications.
• There is deadline associated with real time kernel but GPOS does not follow
timely mechanism.
• The real time kernel follows preemptive scheduling policy whereas GPOS follow
non preemptive scheduling technique.
• Synchronization is a problem with GPOS whereas synchronization is achieved in
real time kernel.
• Inter task communication is done using real time OS where GPOS does not.
• Latency is a problem with GPOS but it is overcome using real time OS.
• Priority inversion cannot be done in GPOS, it is done with real time kernel.
• Jitter i.e. timing error in task is not present in real time OS, present in GPOS.
• The mathematical relation cannot be defined for GPOS, for a real time OS
mathematical equation can be defined.
Why use an RTOS?
There are well-established techniques for writing good embedded software
without the use of an RTOS. In some cases, these techniques may provide the most
appropriate solution; however as the solution becomes more complex, the benefits of an
RTOS become more apparent. These include:
• Priority Based Scheduling: The ability to separate critical processing from non-
critical is a powerful tool.
• Abstracting Timing Information: The RTOS is responsible for timing and
provides API functions. This allows for cleaner (and smaller) application code.
• Maintainability/Extensibility: Abstracting timing dependencies and task based
design results in fewer interdependencies between modules. This makes for
easier maintenance.
• Modularity: The task based API naturally encourages modular development as a
task will typically have a clearly defined role.
• Promotes Team Development: The task-based system allows separate
designers/teams to work independently on their parts of the project.
• Easier Testing: Modular task based development allows for modular task based

Embedded Systems 66
• Code Reuse: Another benefit of modularity is that similar applications on similar
platforms will inevitably lead to the development of a library of standard tasks.
• Improved Efficiency: An RTOS can be entirely event driven; no processing time is
wasted polling for events that have not occurred.
• Idle Processing: Background or idle processing is performed in the idle task. This
ensures that things such as CPU load measurement, background CRC checking
etc will not affect the main processing.
5.2 Types of Real Time Operating System
Depending upon the nature of application real time OS are designed and they are
classified into 3 types, namely, Hard Real Time RTOS, Soft Real Time RTOS, and Firm
Real Time RTOS as described below:
1. Soft Real Time Operating System
Soft real time OS is a type of OS where certain deadlines may be missed, they will
respond at a time t=0+.
Soft real time systems are not constrained to extreme rules. The critical time of
the soft real time may be delayed to some extent. The expected latency between the tasks
and time constraints may be deviated.
The preemption period for a soft real time task is about few milliseconds.
Examples: Digital camera, mobile phones, online data base etc.
2. Hard Real Time Operating System
Hard real time OS is a type of OS we can predict the deadline, they will respond
at a time t=0. Hard real time systems are constrained to predicted time constraints,
deadlines and latency.
Examples: Air bag control in cars, anti-lock brake, engine control system etc.
The preemption period for hard real time system is almost less than few microseconds.
3. Firm Real Time Operating System
This type of RTOS has certain time constraints which are not strict and it may
cause undesired effect.
Example for firm RTOS is automated visual inspection in industrial automation. This
system examines and detects the defected parts of assembly line. This type is also called
event response system.
5.3 Features of RTOS
The design of an RTOS is essentially a balance between providing a reasonably rich
feature set for application development and deployment and, not sacrificing
predictability and timeliness. A basic RTOS will be equipped with the following features:

i. Multitasking and Preemptibility

An RTOS must be multi-tasked and preemptible to support multiple tasks in real-time
applications. The scheduler should be able to preempt any task in the system and
allocate the resource to the task that needs it most even at peak load.
ii. Task Priority
Preemption defines the capability to identify the task that needs a resource the most and
allocates it the control to obtain the resource. In RTOS, such capability is achieved by
assigning individual task with the appropriate priority level. Thus, it is important for
RTOS to be equipped with this feature.
iii. Reliable and Sufficient Inter Task Communication Mechanism

Embedded Systems 67
For multiple tasks to communicate in a timely manner and to ensure data integrity
among each other, reliable and sufficient inter-task communication and synchronization
mechanisms are required.
iv. Priority Inheritance
To allow applications with stringent priority requirements to be implemented, RTOS
must have a sufficient number of priority levels when using priority scheduling.
v. Predefined Short Latencies
An RTOS needs to have accurately defined short timing of its system calls. The
behavior metrics are:
 Task switching latency: The time needed to save the context of a currently
executing task and switching to another task is desirable to be short.
 Interrupt latency: The time elapsed between execution of the last instruction of
the interrupted task and the first instruction in the interrupt handler.
 Interrupt dispatch latency. The time from the last instruction in the interrupt
handler to the next task scheduled to run.
vi. Control of Memory Management
To ensure predictable response to an interrupt, an RTOS should provide way for task to
lock its code and data into real memory.

5.4 Real-Time Embedded System with RTOS

Embedded Systems 68

5.5 RTOS Architecture

The architecture of an RTOS is dependent on the complexity of its deployment.
Good RTOSs are scalable to meet different sets of requirements for different
applications. For simple applications, an RTOS usually comprises only a kernel. For
more complex embedded systems, an RTOS can be a combination of various modules,
including the kernel, networking protocol stacks, and other components as illustrated in
Figure below.

5.6 Kernel
An operating system generally consists of two parts: kernel space (kernel mode)
and user space (user mode). Kernel is the smallest and central component of an
operating system. Its services include managing memory and devices and also to
provide an interface for software applications to use the resources. Additional services
such as managing protection of programs and multitasking may be included depending
on architecture of operating system.
The kernel of an RTOS provides an abstraction layer between the application software
and hardware. This abstraction layer comprises of six main types of common services

Embedded Systems 69
provided by the kernel to the application software. Figure shows the six common
services of an RTOS kernel.

5.6.1 Task Management

Task management allows programmers to design their software as a number of
separate “chunks” of codes with each handling a distinct goal and deadline. This service
encompasses mechanism such as scheduler and dispatcher that creates and maintain
task objects.
Task Object
To achieve concurrency in real-time application program, the application is
decompose into small, schedulable, and sequential program units known as “Task”. In
real-time context, task is the basic unit of execution and is governed by three time-
critical properties; release time, deadline and execution time. Release time refers to the
point in time from which the task can be executed. Deadline is the point in time by
which the task must complete. Execution time denotes the time the task takes to
execute. A task object is defined by the following set of components:
Task Control block (Task data structures residing in RAM and only accessible by RTOS)
Task Stack (Data defined in program residing in RAM and accessible by stack pointer)
Task Routine (Program code residing in ROM)
Possible States Transition of Tasks
Each task may exist in any of the four states, including running, ready, or blocked
and dormant as shown in Figure. During the execution of an application program,
individual tasks are continuously changing from one state to another. However, only
one task is in the running mode (i.e. given CPU control) at any point of the execution. In
the process where CPU control is change from one task to another, context of the to-be-
suspended task will be saved while context of the to-be-executed task will be retrieved.
This process of saving the context of a task being suspended and restoring the context of
a task being resumed is called context switching.

Embedded Systems 70

The scheduler keeps record of the state of each task and selects from among them
that are ready to execute and allocates the CPU to one of them. A scheduler helps to
maximize CPU utilization among different tasks in a multi-tasking program and to
minimize waiting time. There are generally two types of schedulers: non-preemptive and
priority-based preemptive. Non-preemptive scheduling or cooperative multitasking
requires the tasks to cooperate with each other to explicitly give up control of the
processor. When a task releases the control of the processor, the next most important
task that is ready to run will be executed. A task that is newly assigned with a higher
priority will only gain control of the processor when the current executing task
voluntarily gives up the control. Figure gives an example of a non-preemptive

Priority-based preemptive scheduling requires control of the processor be given

to the task of the highest priority at all time. In the event that makes a higher priority
task ready to run, the current task is immediately suspended and the control of the
processor is given to the higher priority task. Figure shows an example of a preemptive

Embedded Systems 71

The dispatcher gives control of the CPU to the task selected by the scheduler by
performing context switching and changes the flow of execution. At any time an RTOS is
running, the flow of execution passes through one of three areas: through the task
program code, through an interrupt service routine, or through the kernel.
5.6.2 Task Synchronization & Intertask Communication
Task synchronization and intertask communications serves to enable information to be
transmitted safely from one task to another. The service also makes it possible for tasks
to coordinate and cooperate with one another.
Task Synchronization
Synchronization is essential for tasks to share mutually exclusive resources (devices,
buffers, etc) and/or allow multiple concurrent tasks to be executed (e.g. Task A needs a
result from task B, so task A can only run till task B produces it). Task synchronization is
achieved using two types of mechanisms; 1) Event Objects and 2) Semaphores.
Event objects are used when task synchronization is required without resource sharing.
They allow one or more tasks to keep waiting for a specified event to occur. An event
object can exist in either of two states: triggered and non-triggered. An event object in a
triggered state indicates that a waiting task may resume. In contrast, if the event object
is in a nontriggered state, a waiting task will need to stay suspended

Working Principle of Event Objects

Sharing of resource among tasks can be a problem when the coordination is not well
done. For instance, if task A begins reading a set of data currently being updated by task
B, task A might received corrupted data – mixture of new and existing data. To resolve

Embedded Systems 72
this problem, RTOS kernels provide a semaphore object and associated semaphore
services to ensure the integrity of data.
A semaphore has an associated resource count and a wait queue. The resource count
indicates availability of resource. The wait queue manages the tasks waiting for
resources from the semaphore. A semaphore functions like a key that define whether a
task has the access to the resource. A task gets an access to the resource when it acquires
the semaphore. The resource count of a semaphore determines the number of times the
semaphore can be acquired. When a task acquires the semaphore, its count decrement
by one. Likewise, its count increment by one when a task releases the semaphore.
Generally. There are three types of semaphore:
Binary Semaphores (semaphore value of either 0 or 1 to indicate unavailability and
availability respectively)
Counting Semaphores (semaphore value of 0 or greater indicating it can be
acquired/released multiple times)
Mutually Exclusion Semaphores (semaphore value of 0 or 1 but lock count can be 0 or
greater for recursive locking). Figure illustrates the types of semaphore.

Embedded Systems 73

Intertask Communication
Intertask communication involves sharing of data among tasks through sharing
of memory space, transmission of data and etc. Few of mechanisms available for
executing intertask communications includes:
• Message queues
• Pipes
• Remote procedural calls (RPC)
A message queue is an object used for intertask communication through which task
send or receive messages placed in a shared memory. Tasks and ISRs send and receive
messages to the queue through services provided by the kernel. A task seeking for a
message from an empty queue is blocked either for a duration or until a message is
received. The sending and receiving of messages to and from the queue may follow
1) First In First Out (FIFO),
2) Last in First Out (LIFO) or
3) Priority (PRI) sequence.
Usually, a message queue comprises of an associated queue control block (QCB),
name, unique ID, memory buffers, queue length, maximum message length and one or
more task waiting lists. A message queue with a length of 1 is commonly known as a
mailbox. A pipe is an object that provide simple communication channel used for
unstructured data exchange among tasks. A pipe can be opened, closed, written to and
read from. Traditionally, a pipe is a unidirectional data exchange facility. There are two
descriptors respectively at each end of the pipe for reading and writing. Data is written
into the pipe as an unstructured byte stream via one descriptor and read from the pipe
in the FIFO order from the other. Unlike message queue, a pipe does not store multiple
messages but stream of bytes. In addition, data flow from a pipe cannot be prioritized.
Remote procedure call (RPC) component permits distributed computing where
task can invoke the execution of a another task on a remote computer, as if the task ran
on the same computer.
5.6.3 Memory Management
An embedded RTOS usually strive to achieve small footprint by including only
the functionality needed for the user’s applications. There are two types of memory
management in RTOSs. They are Stack and Heap managements. In a multi-tasking
RTOS, each task needs to be allocated with an amount of memory for storing their

Embedded Systems 74
contexts (i.e. volatile information such as registers contents, program counter, etc) for
context switching. This allocation of memory is done using task-control block model.
This set of memory is commonly known as kernel stack and the management process
termed Stack Management. Upon the completion of a program initialization, physical
memory of the MCU or MPU will usually be occupied with program code, program data
and system stack. The remaining physical memory is called heap. This heap memory is
typically used by the kernel for dynamic memory allocation of data space for tasks. The
memory is divided into fixed size memory blocks, which can be requested by tasks.
When a task finishes using a memory block it must return it to the pool. This process of
managing the heap memory is known as Heap management.
5.6.4 Timer Management
In embedded systems, system and user tasks are often scheduled to perform after
a specified duration. To provide such scheduling, there is a need for a periodical
interrupt to keep track of time delays and timeout. Most RTOSs today offer both
“relative timers” that work in units of ticks, and “absolute timers” that work with
calendar date and time. For each kind of timer, RTOSs provide a “task delay” service,
and also a “task alert” service based on the signaling mechanism (e.g. event flags).
Another timer service provided is in meeting task deadline by cooperating with task
schedulers to determine whether tasks have met or missed their real-time deadlines.
5.6.5 Interrupt and Event Handling
An interrupt is a hardware mechanism used to inform the CPU that an
asynchronous event has occurred. A fundamental challenge in RTOS design is
supporting interrupts and thereby allowing asynchronous access to internal RTOS data
structures. The interrupt and event handling mechanism of an RTOS provides the
following functions:
• Defining interrupt handler
• Creation and deletion of ISR
• Referencing the state of an ISR
• Enabling and disabling of an interrupt
• Changing and referencing of an interrupt mask
and help to ensure:
• Data integrity by restricting interrupts from occurring when modifying a data
• Minimum interrupt latencies due to disabling of interrupts when RTOS is
performing critical operations
• Fastest possible interrupt responses that marked the preemptive performance of
• Shortest possible interrupt completion time with minimum overheads
5.6.6 Device I/O Management
An RTOS kernel is often equipped with a device I/O management service to
provide a uniform framework (application programmer’s interface-“API”) and
supervision facility for an embedded system to organize and access large numbers of
diverse hardware device drivers. However, most device driver APIs and supervisors are
“standard” only within a specific RTOS.

Text Books:
Computers as Components by Wayne Wolf; Morgan Kaufmann Harcourt India Press

Embedded Systems 75
The 8051 Microcontroller by K.J. Ayala, Penram International
The 8051 Microcontroller and Embedded Systems by M.A. Mazidi and J. G. Mazidi,
Pearson Education press.
An Embedded Software Primer by David E. Simon, Pearson Education
Embedded Systems by Raj Kamal, TMH
Embedded Systems Architecture by Tammy Noergaard; Elsevier Press
An introduction to the design of small scale embedded systems
8051 Microcontroller & Embedded Systems by Dr. Rajiv Kapadia, Jaico Press
Fundamental of Embedded software by Daniel W. Lewis, PHI
Networking and Internetworking with Microcontrollers by Fred Eady, Elsivier press

Individual Assignment
1. Explain the concept of interrupts and times in 8051 microcontroller with
programming examples.

Group Assignment
01. Implement the interfacing of LED with microcontroller
02. Implement the interfacing of switch and LED with microcontroller
03. Implement the interfacing of LCD with microcontroller
04. Implement the interfacing of seven segment display with microcontroller
05. Implement the interfacing of keypad with microcontroller
06. Implement the interfacing of serial communication with microcontroller
07. Implement the interfacing of object sensor with microcontroller
08.Implement the interfacing of temperature sensor with microcontroller
09. Implement the interfacing of soil moisture sensor with microcontroller
10. Implement the interfacing of humidity sensor with microcontroller
11. Implement the interfacing of ultrasonic sensor with microcontroller
12. Implement the interfacing of stepper motor with microcontroller
13. Implement the interfacing of relay with microcontroller
14. Implement traffic signal control using microcontroller
15. Implement street light automation using microcontroller
16. Implement water level control system using microcontroller
17. Implement the interfacing of GPS with microcontroller
18. Implement the interfacing of GSM with microcontroller

Each group should submit the following:

1. Documentation
Title of the Assignment
Theoretical description
Circuit Diagram
Results (Output)
2. Power point presentation : Make PPT for the above.