Overview of Embedded Systems Concepts
Overview of Embedded Systems Concepts
By
Chandra Sekhar G.
Assistant Professor
Electronics and Communication Engineering Dept.
Bharati Vidyapeeth’s College of Engineering
New Delhi
UNIT - I
Overview of Embedded Systems:
Characteristics of Embedded Systems.
Comparison of Embedded Systems with general purpose processors.
General architecture and functioning of micro controllers.
8051 micro controllers.
PIC Microcontrollers:
Architecture, Registers, memory interfacing, interrupts, instructions.
Programming and peripherals.
Note: Prerequisites: Clear Conceptual knowledge in Microprocessors, Microcontrollers and their Functional
Units.
This Notes is prepared mostly using NPTEL Videos of Embedded Systems, IIT Delhi. Some concepts are taken
from Internet.
This notes is prepared to complete the syllabus in the given number of lectures and in the exam point of view.
For more and detailed theory go through Mazidi(For overview of Embedded Systems) and Peatman(For PIC).
Embedded Systems - Overview
System: A system is an arrangement in which all its units assembled work together according to a set of
rules. It can also be defined as a way of working, organizing or doing one or many tasks according to a fixed
plan. For example, a watch is a time displaying system. Its components follow a set of rules to show time. If
one of its parts fails, the watch will stop working. So we can say, in a system, all its subcomponents depend
on each other.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Characteristics of Embedded Systems: Most Important************
Sophisticated functionality. Application dependent processors and not
Real time operation. general purpose processors which we find in
Low manufacturing cost computers
Low power Consumption Restricted memory
Explanation:
What are the characteristics of embedded systems?
First thing is, they all implement sophisticated functionality. The degree of sophistication can vary from
appliance to appliance.
They satisfy real time operation. Is it always true? It is not necessarily true and what is the real time
operation, we shall comeback to this point slightly later on.
They should have in many cases, low manufacturing cost, but cost itself is an issue which requires further
closer examination.
In many cases the appliances uses application dependent processors and not general purpose processors
which we find in computers.
They need to work with restricted memory
Manufacturing cost: There are two aspects;
First aspect is what we call non- recurring engineering cost, which is actually the development cost into
that system. The other aspect of the cost is production and marketing each unit. If we are targeting a
mass market then what we need to optimize is a production marketing cost.
But if you are trying to develop a very specialized application then we can invest in NRE as well as we
may compensate set for high production cost.
Say, for example, if I am designing an automated system for an aircraft, I can invest money for its
development, I can use highly sophisticated equipments, but the same flexibility is not with me when I
am designing a cell phone, a low cost cell phone aiming to serve a mass market. So the best technology
choice will therefore depend on the number of units we plan to produce.
Real time operation: What is the real time operation?
The basic definition is that operations must be completed by deadlines.
So if I have a deadline, a real time operation must be completed within deadline.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
We have two kinds of real time deadlines;
hard real time deadlines and soft real time headlines and accordingly also, we classify real time
systems.
In a hard real time systems, we cannot really miss a deadline. If you are talking about an atomic reactor
control, if I miss a deadline then there can be a catastrophe.
On the other hand, for a soft real time systems, we can at times miss deadline. See for example, when
we are playing a video on a laptop even if we cannot decode a frame in time, nothing catastrophic
happens, only it disturbs you viewing experience.
Many systems are also multi-rate that means those embedded systems are receiving inputs from the
external worlds and inputs can come at different rates.
So they need to handle different rate inputs and we call them therefore multi-rate systems.
There also various application dependent requirements, in many cases, just take for example, an
aircraft system with definitely need fault-tolerance
Also for medical equipment when we are monitoring a critical patient using an embedded system, we
do need fault-tolerance and reliability. Further, the systems must be safe; systems must avoid physical
or economic damage to person as well as property.
Further, if they are dedicated systems, then the design consideration is obviously different because they
are not expected to be programmed on a regular basis. So what we say, the programmability of the
systems would be really used during the right lifetime of the system.
That means once programmed the systems are expected to execute infinitely for a large duration of time
without users intervention. And they are expected to be programmed or designed for specific tasks and
therefore they are basically what we call dedicated systems.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Your MP3 players, your DVD players, radar control system; because in radar although there is a control
system the basic job is processing of the data. Similarly, a sonar system; they are all example the signal
processing systems.
And communication and networking is another category of which the most common example is your
cellular phones. And now, we are getting a number of internet appliance, in fact, the web enabled
vending machine is an example of this kind of an internet appliance.
So what are the different kinds of functions that an embedded system is expected to implement?
First is, if it has got the actuation, sensing an actuation as a basic task it must realize some control law;
it has to realize a control law.
Second important issue is that there has to be a sequencing logic. This sequencing logic is obviously
task specific and it is not a general purpose sequencing logic; it could have a task specific sequencing
logic implemented into it.
Third thing is that it should have signal processing if it is required and wherever and where we are
interfacing an embedded system with external sensory input we need signal processing. So, in many
cases, even when the signal processing is not core activity we need signal processing ability to deal with
sensory inputs.
Fourth one is application specific interfacing because application will tell us what kind of sensors and
what kind of actuators to be interconnected and accordingly we should have that interfacing. This
interfacing implies both hardware as well as software.
Next thing is fault response; what happens when a fault occurs. A basic issue or basic design philosophy
for fault response is what we know as, what we call graceful degradation. Catastrophic failure should
not happen. The system should tell users that things are failing and gracefully it would degrade.
Say, for example battery failure, there should be a message to the user saying that battery is low. So user
can take some action. It should not suddenly stop its activity all of a sudden. So graceful degradation is
another important function which is to be implemented.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Structure of an Embedded System****
Processors in a System
A processor has two essential units −
Program Flow Control Unit (CU) Execution Unit (EU)
The CU includes a fetch unit for fetching instructions from the memory. The EU has circuits that implement
the instructions pertaining to data transfer operation and data conversion from one form to another.
The EU includes the Arithmetic and Logical Unit (ALU) and also the circuits that execute instructions for a
program control task such as interrupt, or jump to another set of instructions.
A processor runs the cycles of fetch and executes the instructions in the same sequence as they are fetched
from memory.
Types of Processors
Processors can be of the following categories −
General Purpose Processor (GPP)
o Microprocessor o Digital Signal Processor
o Microcontroller o Media Processor
o Embedded Processor
Application Specific System Processor (ASSP)
Application Specific Instruction Processors (ASIPs)
GPP core(s) or ASIP core(s) on either an Application Specific Integrated Circuit (ASIC) or a Very Large
Scale Integration (VLSI) circuit.
Microprocessor******
A microprocessor is a single VLSI chip having a CPU. In addition, it may also have other units such as coaches,
floating point processing arithmetic unit, and pipelining units that help in faster processing of instructions.
Earlier generation microprocessors’ fetch-and-execute cycle was guided by a clock frequency of order of ~1
MHz. Processors now operate at a clock frequency of 2GHz.
Microcontroller************
A microcontroller is a single-chip VLSI unit (also called microcomputer) which, although having limited
computational capabilities, possesses enhanced input/output capability and a number of on-chip functional
units. Microcontrollers are particularly used in embedded systems for real-time control applications with on-
chip program memory and devices.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Microprocessor vs Microcontroller***********
Let us now take a look at the most notable differences between a microprocessor and a microcontroller.
Microprocessor Microcontroller
Microprocessors are multitasking in nature. Can Single task oriented. For example, a washing
perform multiple tasks at a time. For example, on machine is designed for washing clothes only.
computer we can play music while writing text in text
editor.
RAM, ROM, I/O Ports, and Timers can be added RAM, ROM, I/O Ports, and Timers cannot be
externally and can vary in numbers. added externally. These components are to be
embedded together on a chip and are fixed in
numbers.
Designers can decide the number of memory or I/O Fixed number for memory or I/O makes a
ports needed. microcontroller ideal for a limited but specific task.
External support of external memory and I/O ports Microcontrollers are lightweight and cheaper than a
makes a microprocessor-based system heavier and microprocessor.
costlier.
External devices require more space and their power A microcontroller-based system consumes less
consumption is higher. power and takes less space.
Von Neumann Architecture:**** The Von Neumann architecture was first proposed by a
computer scientist John von Neumann. In this architecture, one data path or bus exists for both instruction and
data. As a result, the CPU does one operation at a time. It either fetches an instruction from memory, or
performs read/write operation on data. So an instruction fetch and a data operation cannot occur
simultaneously, sharing a common bus. Von-Neumann architecture supports simple hardware. It allows the
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
use of a single, sequential memory. Today's processing speeds vastly outpace memory access times, and we
employ a very fast but small amount of memory (cache) local to the processor.
Harvard Architecture******
The Harvard architecture offers separate storage and signal buses for instructions and data. This architecture
has data storage entirely contained within the CPU, and there is no access to the instruction storage as data.
Computers have separate memory areas for program instructions and data using internal data buses, allowing
simultaneous access to both instructions and data. Programs needed to be loaded by an operator; the processor
could not boot itself. In a Harvard architecture, there is no need to make the two memories share properties.
Single memory to be shared by both code and data. Separate memories for code and data.
Processor needs to fetch code in a separate clock cycle Single set of clock cycles is sufficient, as separate
and data in another clock cycle. So it requires two sets buses are used to access code and data.
of clock cycles.
Pipeline Organization:*****
Pipelining involves the concept of overlapped execution of instructions
Increases speed – most instructions executed in single cycle.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
We can perform pipelining if the instruction has more than 2 stages for the completion of executing
and instruction.
3-stage (ARM7TDMI and earlier) 6-stage (ARM10TDMI)
5-stage (ARMS, ARM9TDMI)
Pipeline flushed and refilled on branch, causing execution to slow down
Special features in instruction set eliminate small jumps in code to obtain the best flow through
pipeline
CISC RISC
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Larger set of instructions. Easy to program Smaller set of Instructions. Difficult to
program.
Many addressing modes causing complex instruction Few addressing modes, fix instruction
formats. format.
Higher clock cycles per second. Low clock cycle per second.
Control unit implements large instruction set using micro- Each instruction is to be executed by
program unit. hardware.
Slower execution, as instructions are to be read from Faster execution, as each instruction is to be
memory and decoded by the decoder unit. executed by hardware.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Assemblers: An assembler is a program that takes basic computer instructions (called as assembly
language) and converts them into a pattern of bits that the computer's processor can use to perform its basic
operations. An assembler creates object code by translating assembly instruction mnemonics into opcodes,
resolving symbolic names to memory locations. Assembly language uses a mnemonic to represent each low-
level machine operation (opcode).
Simulators
Code is tested for the MCU / system by simulating it on the host computer used for code development.
Simulators try to model the behavior of the complete microcontroller in software.
Functions of Simulators
A simulator performs the following functions −
Defines the processor or processing device family as well as its various versions for the target system.
Monitors the detailed information of a source code part with labels and symbolic arguments as the
execution goes on for each single step.
Provides the status of RAM and simulated ports of the target system for each single step execution.
Monitors system response and determines throughput.
Provides trace of the output of contents of program counter versus the processor registers.
Provides the detailed meaning of the present command.
Monitors the detailed information of the simulator commands as these are entered from the keyboard or
selected from the menu.
Supports the conditions (up to 8 or 16 or 32 conditions) and unconditional breakpoints.
Provides breakpoints and the trace which are together the important testing and debugging tool.
Facilitates synchronizing the internal peripherals and delays.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Embedded Systems - 8051 Microcontroller
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 is a basic type of micro controller based on Harvard & RISC Architectures
and developed primarily for use in embedded systems technology. Normally, this microcontroller was
developed using NMOS technology, which requires more power to operate. Therefore, Intel redesigned
Microcontroller 8051 using CMOS technology and their updated versions came with a letter C in their name,
for instance an 80C51 it is an 8 bit microcontroller. These latest Microcontrollers requires less power to operate
as compared to their previous versions. The 8051 Microcontroller has two buses and can have two memory
spaces of 64K X 8 size for program and data units. It has an 8 bit processing unit and 8 bit accumulator units.
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. The 8051
microcontrollers work with 8-bit data bus. So they can support external data memory up to 64K and external
program memory of 64k at best. Collectively, 8051 microcontrollers can address 128k of external memory.
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
ROM(bytes) 4K 8K 0K
Timers 2 3 2
I/O pins 32 32 32
Serial port 1 1 1
Interrupt sources 6 8 6
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Features of 8051 Microcontroller
An 8051 microcontroller comes bundled with the following features −
64K bytes on-chip program memory (ROM) 16 bit Timers (usually 2, but may have more or
128 bytes on-chip data memory (RAM) less)
Four register banks Three internal and two external Interrupts
128 user defined software flags Four 8-bit ports,(short model have two 8-bit ports)
8-bit bidirectional data bus 16-bit program counter and data pointer
16-bit unidirectional address bus 8051 may also have a number of special features
32 general purpose registers each of 8-bit such as UARTs, ADC, Op-amp, etc.
Central Processor Unit (CPU): As we know that the CPU is the brain of any processing device of the
microcontroller. It monitors and controls all operations that are performed on the Microcontroller units.
The User has no control over the work of the CPU directly. It reads program written in ROM memory and
executes them and do the expected task of that application.
Interrupts: As its name suggests, Interrupt is a subroutine call that interrupts of the microcontrollers main
operations or work and causes it to execute any other program, which is more important at the time of operation.
The feature of Interrupt is very useful as it helps in case of emergency operations. An Interrupts gives us a
mechanism to put on hold the ongoing operations, execute a subroutine and then again resumes to another type
of operations. The Microcontroller 8051 can be configured in such a way that it temporarily terminates or pause
the main program at the occurrence of interrupts. When a subroutine is completed, then the execution of main
program starts. Generally five interrupt sources are there in 8051 Microcontroller. There are 5 vectored
interrupts are shown in below
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
INTO TF1
TFO R1/T1
INT1
Out of these, (INT0) ̅ and (INT1) ̅ are external interrupts that could be negative edge triggered or low level
triggered. When All these interrupts are activated, set the corresponding flags except for serial interrupts. The
interrupt flags are cleared when the processor branches to the interrupt service routine (ISR). The external
interrupt flags are cleared when the processor branches to the interrupt service routine, provides the interrupt
is a negative edge triggered whereas the timers and serial port interrupts two of them are external interrupts,
two of them are timer interrupts and one serial port interrupt terminal in general.
Memory: Microcontroller requires a program which is a collection of instructions. This program tells
microcontroller to do specific tasks. These programs require a memory on which these can be saved and read
by Microcontroller to perform specific operations of a particular task. The memory which is used to store
the program of the microcontroller is known as code memory or Program memory of applications. It is known
as ROM memory of microcontroller also requires a memory to store data or operands temporarily of the micro
controller. The data memory of the 8051 is used to store data temporarily for operation is known RAM memory.
8051 microcontroller has 4K of code memory or program memory, that has 4KB ROM and also 128 bytes of
data memory of RAM.
BUS: Basically Bus is a collection of wires which work as a communication channel or medium for transfer
of Data. These buses consists of 8, 16 or more wires of the microcontroller. Thus, these can carry 8 bits, 16 bits
simultaneously. Hire two types of buses that are shown in below
Address Bus Data Bus
Address Bus: Microcontroller 8051 has a 16 bit address bus for transferring the data. It is used to address
memory locations and to transfer the address from CPU to Memory of the microcontroller. It has five addressing
modes that are
Oscillator: Generally, we know that the microcontroller is a device, therefore it requires clock pulses for its
operation of microcontroller applications. For this purpose, microcontroller 8051 has an on-chip oscillator
which works as a clock source for Central Processing Unit of the microcontroller. The output pulses of oscillator
are stable. Therefore, it enables synchronized work of all parts of the 8051 Microcontroller. We have to connect
a crystal between XTAL1 and XTAL2 pins of the 8051 which are directly connected to the on-chip oscillator.
Typical frequency of 8051 MC is 11.0592MHz
Input/Output Port: Normally microcontroller is used in embedded systems to control the operation of
machines in the microcontroller. Therefore, to connect it to other machines, devices or peripherals we require
I/O interfacing ports in the microcontroller interface. For this purpose microcontroller 8051 has 4 input, output
ports to connect it to the other peripherals. Out of these 4 ports, 2 ports are used for address and data where 8bits
of data and 8bits of lower byte of address are multiplexed.
Timers/Counters: 8051 microcontroller has two 16 bit timers and counters. These counters are again
divided into a 8 bit register. The timers are used for measurement of intervals to determine the pulse width of
pulses.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Applications of 8051 Microcontroller:
Some of the applications of 8051 is mainly used in daily life & industrial applications also some of that
applications are shown below
Light sensing and controlling devices Fire detections and safety devices
Temperature sensing and Automobile applications
controlling devices Defense applications
Some industrial applications of micro controller and its applications
Industrial instrumentation devices Process control devices
Some of 8051 microcontroller devices are used in measurement applications
Voltmeter applications Current meter objects
Measuring and revolving objects Hand held metering system
8051 Microcontroller Applications in Embedded Systems
The applications of 8051 microcontroller involves in 8051 based projects. The list of 8051 projects is listed
below.
Arduino Managed High Sensitive LDR based Power Saver for Street Light Control System
The Temperature Humidity Monitoring System of Soil Based on Wireless Sensor Networks using
Arduino
RFID based Electronic Passport System for Easy Governance using Arduino
Arduino based RFID Sensed Device Access
Arduino based DC Motor Speed Control
Arduino Based Line Following Robot
Zigbee based Automatic Meter Reading System
GSM based Electricity Energy Meter Billing with Onsite Display
Android Phone Speech Recognition Sensed Voice Command based Notice Board Display
Parking Availability Indication System
Voice Controlled Home Appliances
Remote Control Home Appliances
PC Mouse operated Electrical Load Control Using VB Application
Solar Highway Lighting System with Auto Turn Off in Daytime
8051 Microcontroller based Wireless Energy Meter
Farmer Friendly Solar Based Electric Fence for Deterring Cattles
Vehicle Movement Sensed Streetlight with Daytime auto off Features
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Detailed Architechture of 8051 Microcontroller:
From this we have to explain how CPU will work for Arithmetic and logic operations and also how it will
generate timing & control signals for the execution of instructions. We will see how an addition operation will
be performed by the CPU.
2008 XXH ADD A , B ; When 8051 start executing this instruction PC will change from 2008 to 2009
and opcode (XXH) loaded at ROM or program memory location will be loaded into Instruction register. Then
the contents or opcode present in the IR are decoded and the corresponding timing and control signals are
generated. Here timing and control signals are generated for addition of contents in A & B as follows:
1. Transfer the data or content in Accumulator to Temporary register 2, i.e. Temp2 (A)
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
2. Transfer the data or content in B register to Temporary register 1, i.e. Temp1 (B)
3. Perform the addition operation in ALU (Arithmetic and Logic Unit) and store the result in the Accumulator.
And also set the flags in the PSW (Program status word) based on the result obtained. (A)
Temp1+Temp2
4. For all the above steps required timing and control signals are generated and the signals will be transmitted
to the registers, memory blocks and peripherals through the address and data path.
Note − In a DIP package, you can recognize the first pin and the last pin by the cut at the middle of the IC. The
first pin is on the left of this cut mark and the last pin (i.e. the 40th pin in this case) is to the right of the cut
mark.
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
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
(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 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 alternate bits of P1 continuously
START: MOV A,#55
BACK: MOV P1,A
ACALL DELAY
CPL A ; Complement(invert) reg. A
SJMP BACK
; Delay Subroutine
Delay: MOV R1, #0FFH ; R1 = Counter 1 = 255
LOOP2: MOV R2, #0FFH ; R2 = Counter 2 = 255
LOOP1: DJNZ R2, LOOP1
DJNZ R1, LOOP2
RET
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
ACALL DELAY ;wait
MOV A,P1 ;get another data from P1
MOV R6,A ;save it in R6
ACALL DELAY ;wait
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.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
;Toggle all bits of continuously
MOV A,#55
BACK:
MOV P2,A
ACALL DELAY
CPL A ; complement(invert) reg. A
SJMP BACK
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
BACK:
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)
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.4 < T0 14
P3.5 < T1 15
P3.6 < WR 16
Single-Bit Instructions
Instructions Function
JBC bit, target jump to target if bit = 1, clear bit (jump if bit, then clear)
Stack Pointer: Stack is implemented in RAM and a CPU register is used to access it called SP (Stack
Pointer) register. SP register is an 8-bit register and can address memory addresses of range 00h to FFh.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Initially, the SP register contains value 07 to point to location 08 as the first location being used for the stack
by the 8051.
When the content of a CPU register is stored in a stack, it is called a PUSH operation. When the content of a
stack is stored in a CPU register, it is called a POP operation. In other words, a register is pushed onto the stack
to save it and popped off the stack to retrieve it.
Infinite Loop
An infinite loop or an endless loop can be identified as a sequence of instructions in a computer program that
executes endlessly in a loop, because of the following reasons −
loop with no terminating condition.
loop with a terminating condition that can never be met.
loop with a terminating condition that causes the loop to start over.
Such infinite loops normally caused older operating systems to become unresponsive, as an infinite loop
consumes all the available processor time. I/O operations waiting for user inputs are also called "infinite loops".
One possible cause of a computer "freezing" is an infinite loop; other causes include deadlock and access
violations.
Embedded systems, unlike a PC, never "exit" an application. They idle through an Infinite Loop waiting for an
event to take place in the form of an interrupt, or a pre-scheduled task. In order to save power, some processors
enter special sleep or wait modes instead of idling through an Infinite Loop, but they will come out of this
mode upon either a timer or an External Interrupt.
Interrupts
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 Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Assembling and Running an 8051 Program: Here we will discuss about the basic
form of an assembly language. The steps to create, assemble, and run an assembly language program are as
follows −
First, we use an editor to type in a program similar to the above program. Editors like MS-DOS EDIT
program that comes with all Microsoft operating systems can be used to create or edit a program. The
Editor must be able to produce an ASCII file. The "asm" extension for the source file is used by an
assembler in the next step.
The "asm" source file contains the program code created in Step 1. It is fed to an 8051 assembler. The
assembler then converts the assembly language instructions into machine code instructions and
produces an .obj file (object file) and a .lst file (list file). It is also called as a source file, that's why
some assemblers require that this file have the "src" extensions. The "lst" file is optional. It is very
useful to the program because it lists all the opcodes and addresses as well as errors that the assemblers
detected.
Assemblers require a third step called linking. The link program takes one or more object files and
produces an absolute object file with the extension "abs".
Next, the "abs" file is fed to a program called "OH" (object to hex converter), which creates a file with
the extension "hex" that is ready to burn in to the ROM.
Data Type
The 8051 microcontroller contains a single data type of 8-bits, and each register is also of 8-bits size. The
programmer has to break down data larger than 8-bits (00 to FFH, or to 255 in decimal) so that it can be
processed by the CPU.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
DB (Define Byte): The DB directive is the most widely used data directive in the assembler. It is used to
define the 8-bit data. It can also be used to define decimal, binary, hex, or ASCII formats data. For decimal,
the "D" after the decimal number is optional, but it is required for "B" (binary) and "Hl" (hexadecimal).
To indicate ASCII, simply place the characters in quotation marks ('like this'). The assembler generates ASCII
code for the numbers/characters automatically. The DB directive is the only directive that can be used to define
ASCII strings larger than two characters; therefore, it should be used for all the ASCII data definitions. Some
examples of DB are given below −
ORG 500H
DATA1: DB 28 ;DECIMAL (1C in hex)
DATA2: DB 00110101B ;BINARY (35 in hex)
DATA3: DB 39H ;HEX
ORG 510H
DATA4: DB "2591" ;ASCII NUMBERS
ORG 520H
DATA6: DA "MY NAME IS Michael" ;ASCII CHARACTERS
Either single or double quotes can be used around ASCII strings. DB is also used to allocate memory in byte-
sized chunks.
Assembler Directives
Some of the directives of 8051 are as follows −
ORG (origin) − The origin directive is used to indicate the beginning of the address. It takes the
numbers in hexa or decimal format. If H is provided after the number, the number is treated as hexa,
otherwise decimal. The assembler converts the decimal number to hexa.
EQU (equate) − It is used to define a constant without occupying a memory location. EQU associates
a constant value with a data label so that the label appears in the program, its constant value will be
substituted for the label. While executing the instruction "MOV R3, #COUNT", the register R3 will be
loaded with the value 25 (notice the # sign). The advantage of using EQU is that the programmer can
change it once and the assembler will change all of its occurrences; the programmer does not have to
search the entire program.
END directive − It indicates the end of the source (asm) file. The END directive is the last line of the
program; anything after the END directive is ignored by the assembler.
Labels in Assembly Language
All the labels in assembly language must follow the rules given below −
Each label name must be unique. The names used for labels in assembly language programming consist
of alphabetic letters in both uppercase and lowercase, number 0 through 9, and special characters such
as question mark (?), period (.), at the rate @, underscore (_), and dollar($).
The first character should be in alphabetical character; it cannot be a number.
Reserved words cannot be used as a label in the program. For example, ADD and MOV words are the
reserved words, since they are instruction mnemonics.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Embedded Systems - Registers
Registers are used in the CPU to store information on temporarily basis which could be data to be processed,
or an address pointing to the data which is to be fetched. In 8051, there is one data type is of 8-bits, from the
MSB (most significant bit) D7 to the LSB (least significant bit) D0. With 8-bit data type, any data type larger
than 8-bits must be broken into 8-bit chunks before it is processed.
The most widely used registers of the 8051 are A (accumulator), B, R0-R7, DPTR (data pointer), and PC
(program counter). All these registers are of 8-bits, except DPTR and PC.
Storage Registers in 8051
We will discuss the following types of storage registers here −
Accumulator Data Pointer (DPTR)
B register Program Counter (PC)
R register (R0 – R7) Stack Pointer (SP)
Accumulator
The accumulator, register A, is used for all arithmetic and logic operations. If the accumulator is not present,
then every result of each calculation (addition, multiplication, shift, etc.) is to be stored into the main memory.
Access to main memory is slower than access to a register like the accumulator because the technology used
for the large main memory is slower (but cheaper) than that used for a register.
The "R" Registers
The "R" registers are a set of eight registers, namely, R0, R1 to R7. These registers function as auxiliary or
temporary storage registers in many operations. Consider an example of the sum of 10 and 20. Store a variable
10 in an accumulator and another variable 20 in, say, register R4. To process the addition operation, execute
the following command −
ADD A,R4
After executing this instruction, the accumulator will contain the value 30. Thus "R" registers are very
important auxiliary or helper registers. The Accumulator alone would not be very useful if it were not for
these "R" registers. The "R" registers are meant for temporarily storage of values.
Let us take another example. We will add the values in R1 and R2 together and then subtract the values of R3
and R4 from the result.
MOV A,R3 ;Move the value of R3 into the accumulator
ADD A,R4 ;Add the value of R4
MOV R5,A ;Store the resulting value temporarily in R5
MOV A,R1 ;Move the value of R1 into the accumulator
ADD A,R2 ;Add the value of R2
SUBB A,R5 ;Subtract the value of R5 (which now contains R3 + R4)
As you can see, we used R5 to temporarily hold the sum of R3 and R4. Of course, this is not the most efficient
way to calculate (R1 + R2) – (R3 + R4), but it does illustrate the use of the "R" registers as a way to store
values temporarily.
The "B" Register: The "B" register is very similar to the Accumulator in the sense that it may hold an 8-
bit (1-byte) value. The "B" register is used only by two 8051 instructions: MUL AB and DIV AB. To quickly
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
and easily multiply or divide A by another number, you may store the other number in "B" and make use of
these two instructions. Apart from using MUL and DIV instructions, the "B" register is often used as yet
another temporary storage register, much like a ninth R register.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
address (08h). SP is modified directly by the 8051 by six instructions: PUSH, POP, ACALL, LCALL, RET,
and RETI.
P PSW.0 Parity FLAG. Set/ cleared by hardware during instruction cycle to indicate
even/odd number of 1 bit in accumulator.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
We can select the corresponding Register Bank bit using RS0 and RS1 bits.
RS1 RS2 Register Bank Address
0 0 0 00H-07H
0 1 1 08H-0FH
1 0 2 10H-17H
1 1 3 18H-1FH
CY, the carry flag − This carry flag is set (1) whenever there is a carry out from the D7 bit. It is affected
after an 8-bit addition or subtraction operation. It can also be reset to 1 or 0 directly by an instruction
such as "SETB C" and "CLR C" where "SETB" stands for set bit carry and "CLR" stands for clear
carry.
AC, auxiliary carry flag − If there is a carry from D3 and D4 during an ADD or SUB operation, the
AC bit is set; otherwise, it is cleared. It is used for the instruction to perform binary coded decimal
arithmetic.
P, the parity flag − The parity flag represents the number of 1's in the accumulator register only. If the
A register contains odd number of 1's, then P = 1; and for even number of 1's, P = 0.
OV, the overflow flag − This flag is set whenever the result of a signed number operation is too large
causing the high-order bit to overflow into the sign bit. It is used only to detect errors in signed
arithmetic operations.
Example
Show the status of CY, AC, and P flags after the addition of 9CH and 64H in the following instruction.
MOV A, #9CH
ADD A, # 64H
Solution: 9C 10011100
+64 01100100
100 00000000
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
80 bytes from 30H to 7FH locations are used for read and write storage; it is called as scratch pad.
These 80 locations RAM are widely used for the purpose of storing data and parameters by 8051
programmers.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Stack and its Operations
Stack in the 8051: The stack is a section of a RAM used by the CPU to store information such as data or
memory address on temporary basis. The CPU needs this storage area considering limited number of
registers.
How Stacks are Accessed: As the stack is a section of a RAM, there are registers inside the CPU to
point to it. The register used to access the stack is known as the stack pointer register. The stack pointer in the
8051 is 8-bits wide, and it can take a value of 00 to FFH. When the 8051 is initialized, the SP register
contains the value 07H. This means that the RAM location 08 is the first location used for the stack. The
storing operation of a CPU register in the stack is known as a PUSH, and getting the contents from the stack
back into a CPU register is called a POP.
Pushing into the Stack
In the 8051, the stack pointer (SP) points to the last used location of the stack. When data is pushed onto the
stack, the stack pointer (SP) is incremented by 1. When PUSH is executed, the contents of the register are
saved on the stack and SP is incremented by 1. To push the registers onto the stack, we must use their RAM
addresses. For example, the instruction "PUSH 1" pushes register R1 onto the stack.
Popping from the Stack
Popping the contents of the stack back into a given register is the opposite to the process of pushing. With
every pop operation, the top byte of the stack is copied to the register specified by the instruction and the stack
pointer is decremented once.
JZ Jump if A = 0
JNZ Jump if A ≠ 0
JC Jump if CY = 1
JNC Jump if CY ≠ 1
JB Jump if bit = 1
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
JZ (jump if A = 0) − In this instruction, the content of the accumulator is checked. If it is zero, then the
8051 jumps to the target address. JZ instruction can be used only for the accumulator, it does not apply
to any other register.
JNZ (jump if A is not equal to 0) − In this instruction, the content of the accumulator is checked to be
non-zero. If it is not zero, then the 8051 jumps to the target address.
JNC (Jump if no carry, jumps if CY = 0) − The Carry flag bit in the flag (or PSW) register is used to
make the decision whether to jump or not "JNC label". The CPU looks at the carry flag to see if it is
raised (CY = 1). If it is not raised, then the CPU starts to fetch and execute instructions from the address
of the label. If CY = 1, it will not jump but will execute the next instruction below JNC.
JC (Jump if carry, jumps if CY = 1) − If CY = 1, it jumps to the target address.
JB (jump if bit is high)
JNB (jump if bit is low)
Note − It must be noted that all conditional jumps are short jumps, i.e., the address of the target must be within
–128 to +127 bytes of the contents of the program counter.
Unconditional Jump Instructions
There are two unconditional jumps in 8051 −
LJMP (long jump) − LJMP is 3-byte instruction in which the first byte represents opcode, and the
second and third bytes represent the 16-bit address of the target location. The 2-byte target address is
to allow a jump to any memory location from 0000 to FFFFH.
SJMP (short jump) − It is a 2-byte instruction where the first byte is the opcode and the second byte
is the relative address of the target location. The relative address ranges from 00H to FFH which is
divided into forward and backward jumps; that is, within –128 to +127 bytes of memory relative to the
address of the current PC (program counter). In case of forward jump, the target address can be within
a space of 127 bytes from the current PC. In case of backward jump, the target address can be within –
128 bytes from the current PC.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
In general, we can write,
MOV A, #data
It is termed as immediate because 8-bit data is transferred immediately to the accumulator (destination
operand).
The following illustration describes the above instruction and its execution. The opcode 74H is saved at 0202
address. The data 6AH is saved at 0203 address in the program memory. After reading the opcode 74H, the
data at the next program memory address is transferred to accumulator A (E0H is the address of accumulator).
Since the instruction is of 2-bytes and is executed in one cycle, the program counter will be incremented by 2
and will point to 0204 of the program memory.
Note − The '#' symbol before 6AH indicates that the operand is a data (8 bit). In the absence of '#', the
hexadecimal number would be taken as an address.
Direct Addressing Mode
This is another way of addressing an operand. Here, the address of the data (source data) is given as an operand.
Let’s take an example.
MOV A, 04H
The register bank#0 (4th register) has the address 04H. When the MOV instruction is executed, the data stored
in register 04H is moved to the accumulator. As the register 04H holds the data 1FH, 1FH is moved to the
accumulator.
Note − We have not used '#' in direct addressing mode, unlike immediate mode. If we had used '#', the data
value 04H would have been transferred to the accumulator instead of 1FH.
Now, take a look at the following illustration. It shows how the instruction gets executed.
As shown in the below illustration, this is a 2-byte instruction which requires 1 cycle to complete. The PC will
be incremented by 2 and will point to 0204. The opcode for the instruction MOV A, address is E5H. When the
instruction at 0202 is executed (E5H), the accumulator is made active and ready to receive data. Then the PC
goes to the next address as 0203 and looks up the address of the location of 04H where the source data (to be
transferred to accumulator) is located. At 04H, the control finds the data 1F and transfers it to the accumulator
and hence the execution is completed.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Register Direct Addressing Mode
In this addressing mode, we use the register name directly (as source operand). Let us try to understand with
the help of an example.
MOV A, R4
At a time, the registers can take values from R0 to R7. There are 32 such registers. In order to use 32 registers
with just 8 variables to address registers, register banks are used. There are 4 register banks named from 0 to
3. Each bank comprises of 8 registers named from R0 to R7.
At a time, a single register bank can be selected. Selection of a register bank is made possible through a Special
Function Register (SFR) named Processor Status Word (PSW). PSW is an 8-bit SFR where each bit can be
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
programmed as required. Bits are designated from PSW.0 to PSW.7. PSW.3 and PSW.4 are used to select
register banks.
Now, take a look at the above illustration to get a clear understanding of how it works.
Opcode EC is used for MOV A, R4. The opcode is stored at the address 0202 and when it is executed, the
control goes directly to R4 of the respected register bank (that is selected in PSW). If register bank #0 is
selected, then the data from R4 of register bank #0 will be moved to the accumulator. Here 2F is stored at 04H.
04H represents the address of R4 of register bank #0.
Data (2F) movement is highlighted in bold. 2F is getting transferred to the accumulator from data memory
location 0C H and is shown as dotted line. 0CH is the address location of Register 4 (R4) of register bank #1.
The instruction above is 1 byte and requires 1 cycle for complete execution. What it means is, you can save
program memory by using register direct addressing mode.
So the opcode for MOV A, @R0 is E6H. Assuming that the register bank #0 is selected, the R0 of register
bank #0 holds the data 20H. Program control moves to 20H where it locates the data 2FH and it transfers 2FH
to the accumulator. This is a 1-byte instruction and the program counter increments by 1 and moves to 0203 of
the program memory.
Note − Only R0 and R1 are allowed to form a register indirect addressing instruction. In other words, the
programmer can create an instruction either using @R0 or @R1. All register banks are allowed.
Indexed Addressing Mode: We will take two examples to understand the concept of indexed
addressing mode. Take a look at the following instructions −
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
MOVC A, @A+DPTR and MOVC A, @A+PC
where DPTR is the data pointer and PC is the program counter (both are 16-bit registers). Consider the first
example.
MOVC A, @A+DPTR
The source operand is @A+DPTR. It contains the source data from this location. Here we are adding the
contents of DPTR with the current content of the accumulator. This addition will give a new address which is
the address of the source data. The data pointed by this address is then transferred to the accumulator.
The opcode is 93H. DPTR has the value 01FE, where 01 is located in DPH (higher 8 bits) and FE is located in
DPL (lower 8 bits). Accumulator has the value 02H. Then a 16-bit addition is performed and 01FE H+02H
results in 0200 H. Data at the location 0200H will get transferred to the accumulator. The previous value inside
the accumulator (02H) will be replaced with the new data from 0200H. The new data in the accumulator is
highlighted in the illustration.
This is a 1-byte instruction with 2 cycles needed for execution and the execution time required for this
instruction is high compared to previous instructions (which were all 1 cycle each).
The other example MOVC A, @A+PC works the same way as the above example. Instead of adding DPTR
with the accumulator, here the data inside the program counter (PC) is added with the accumulator to obtain
the target address.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
In the 8051, register A, B, DPTR, and PSW are a part of the group of registers commonly referred to as SFR
(special function registers). An SFR can be accessed by its name or by its address.
The following table shows a list of SFRs and their addresses.
Byte Bit Address SFR
Address
FF
F0 F7 F6 F5 F4 F3 F2 F1 F0 B
E0 E7 E6 E5 E4 E3 E2 E1 E0 ACC
D0 D7 D6 D5 D4 D3 D2 - D0 PSW
B8 - - - BC BB BA B9 B8 IP
B0 B7 B6 B5 B4 B3 B2 B1 B0 P3
A2 AF - - AC AB AA A9 A8 IE
A0 A7 A6 A5 A4 A3 A2 A1 A0 P2
98 9F 9E 9D 9C 9B 9A 99 98 SCON
90 97 96 95 94 93 92 91 90 P1
80 87 87 85 84 83 82 81 80 P0
Consider the following two points about the SFR addresses.
A special function register can have an address between 80H to FFH. These addresses are above 80H,
as the addresses from 00 to 7FH are the addresses of RAM memory inside the 8051.
Not all the address space of 80 to FF are used by the SFR. Unused locations, 80H to FFH, are reserved
and must not be used by the 8051 programmer.
The Program Status Word (PSW) contains status bits to reflect the current state of the CPU. The 8051 variants
provide one special function register, PSW, with the status information. The 8251 provides two additional
status flags, Z and N, which are available in a second special function register called PSW1.
The register incremented for every machine cycle. The register is incremented considering 1 to 0
transition at its corresponding to an external input
pin (T0, T1).
Maximum count rate is 1/12 of the oscillator Maximum count rate is 1/24 of the oscillator
frequency. frequency.
A timer uses the frequency of the internal clock, A counter uses an external signal to count pulses.
and generates delay.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Timers of 8051 and their Associated Registers: The 8051 has two timers, Timer 0
and Timer 1. They can be used as timers or as event counters. Both Timer 0 and Timer 1 are 16-bit wide.
Since the 8051 follows an 8-bit architecture, each 16 bit is accessed as two separate registers of low-byte and
high-byte.
Timer 0 Register
The 16-bit register of Timer 0 is accessed as low- and high-byte. The low-byte register is called TL0 (Timer 0
low byte) and the high-byte register is called TH0 (Timer 0 high byte). These registers can be accessed like
any other register. For example, the instruction MOV TL0, #4H moves the value into the low-byte of Timer
#0.
Timer 1 Register
The 16-bit register of Timer 1 is accessed as low- and high-byte. The low-byte register is called TL1 (Timer 1
low byte) and the high-byte register is called TH1 (Timer 1 high byte). These registers can be accessed like
any other register. For example, the instruction MOV TL1, #4H moves the value into the low-byte of Timer
1.
Gate − When set, the timer only runs while M1 − Mode bit 1.
INT(0,1) is high. M0 − Mode bit 0.
C/T − Counter/Timer select bit.
GATE: Every timer has a means of starting and stopping. Some timers do this by software, some by
hardware, and some have both software and hardware controls. 8051 timers have both software and hardware
controls. The start and stop of a timer is controlled by software using the instruction SETB TR1 and CLR
TR1 for timer 1, and SETB TR0 and CLR TR0 for timer 0.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
The SETB instruction is used to start it and it is stopped by the CLR instruction. These instructions start and
stop the timers as long as GATE = 0 in the TMOD register. Timers can be started and stopped by an external
source by making GATE = 1 in the TMOD register.
C/T (CLOCK / TIMER)
This bit in the TMOD register is used to decide whether a timer is used as a delay generator or an event
manager. If C/T = 0, it is used as a timer for timer delay generation. The clock source to create the time delay
is the crystal frequency of the 8051. If C/T = 0, the crystal frequency attached to the 8051 also decides the
speed at which the 8051 timer ticks at a regular interval.
Timer frequency is always 1/12th of the frequency of the crystal attached to the 8051. Although various 8051
based systems have an XTAL frequency of 10 MHz to 40 MHz, we normally work with the XTAL frequency
of 11.0592 MHz. It is because the baud rate for serial communication of the [Link] = 11.0592 allows the
8051 system to communicate with the PC with no errors.
M1 / M2
M1 M2 Mode
1 1 Spilt mode.
Hardware Interrupt: A hardware interrupt is an electronic alerting signal sent to the processor from
an external device, like a disk controller or an external peripheral. For example, when we press a key on the
keyboard or move the mouse, they trigger hardware interrupts which cause the processor to read the
keystroke or mouse position.
Software Interrupt: A software interrupt is caused either by an exceptional condition or a special
instruction in the instruction set which causes an interrupt when it is executed by the processor. For example,
if the processor's arithmetic logic unit runs a command to divide a number by zero, to cause a divide-by-zero
exception, thus causing the computer to abandon the calculation or display an error message. Software
interrupt instructions work similar to subroutine calls.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
What is Polling?
The state of continuous monitoring is known as polling. The microcontroller keeps checking the status of other
devices; and while doing so, it does no other operation and consumes all its processing time for monitoring.
This problem can be addressed by using interrupts.
In the interrupt method, the controller responds only when an interruption occurs. Thus, the controller is not
required to regularly monitor the status (flags, signals etc.) of interfaced and inbuilt devices.
Interrupts v/s Polling
Here is an analogy that differentiates an interrupt from polling −
Interrupt Polling
An interrupt is like a shopkeeper. If one needs a service or The polling method is like a salesperson. The salesman
product, he goes to him and apprises him of his needs. In goes from door to door while requesting to buy a product
case of interrupts, when the flags or signals are received, or service. Similarly, the controller keeps monitoring the
they notify the controller that they need to be serviced. flags or signals one by one for all devices and provides
service to whichever component that needs its service.
Reset 0000 9
When the reset pin is activated, the 8051 jumps to the address location 0000. This is power-up reset.
Two interrupts are set aside for the timers: one for timer 0 and one for timer 1. Memory locations are
000BH and 001BH respectively in the interrupt vector table.
Two interrupts are set aside for hardware external interrupts. Pin no. 12 and Pin no. 13 in Port 3 are for
the external hardware interrupts INT0 and INT1, respectively. Memory locations are 0003H and 0013H
respectively in the interrupt vector table.
Serial communication has a single interrupt that belongs to both receive and transmit. Memory location
0023H belongs to this interrupt.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
If the interrupt source is still asserted when the Edge-triggered interrupt modules can be acted
firmware interrupt handler handles the interrupt, the immediately, no matter how the interrupt source
interrupt module will regenerate the interrupt, causing behaves.
the interrupt handler to be invoked again.
Level-triggered interrupts are cumbersome for Edge-triggered interrupts keep the firmware's
firmware. code complexity low, reduce the number of
conditions for firmware, and provide more
flexibility when interrupts are handled.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
PT1 IP.3 Defines the Timer 1 interrupt priority level.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
PIC Microcontrollers
PIC microcontroller was developed in the year 1993 by microchip technology. The term PIC stands for
Peripheral Interface Controller. Initially this was developed for supporting PDP computers to control its
peripheral devices, and therefore, named as a peripheral interface device. These microcontrollers are very fast
and easy to execute a program compared with other microcontrollers. PIC Microcontroller architecture is based
on Harvard and RISC architecture. PIC microcontrollers are very popular due to their ease of programming,
wide availability, easy to interfacing with other peripherals, low cost, large user base and serial programming
capability (reprogramming with flash memory), etc. PIC mainly targeted for Low End Applications
We know that the microcontroller is an integrated chip which consists of CPU, RAM, ROM, timers, and
counters, etc. In the same way, PIC microcontroller architecture consists of RAM, ROM, CPU, timers, counters
and supports the protocols such as SPI, CAN, and UART for interfacing with other peripherals. At present PIC
microcontrollers are extensively used for industrial purpose due to low power consumption, high performance
ability and easy of availability of its supporting hardware and software tools like compilers, debuggers and
simulators.
Every PIC microcontroller architecture consists of some registers and stack where registers function as Random
Access Memory( RAM) and stack saves the return addresses. The main features of PIC microcontrollers are
RAM, flash memory, Timers/Counters, EEPROM, I/O Ports, USART, CCP (Capture/Compare/PWM module),
SSP, Comparator, ADC (analog to digital converter), PSP(parallel slave port), LCD and ICSP (in circuit serial
programming) The 8-bit PIC microcontroller is classified into four types on the basis of internal architecture
such as Base Line PIC, Mid Range PIC, Enhanced Mid Range PIC and PIC18
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Architecture of PIC Microcontroller
Memory Organization
The memory module in the PIC microcontroller architecture consists of RAM (Random Access Memory), ROM
(Read Only Memory) and STACK.
Memory Organization
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Read Only Memory (ROM)
Read only memory is a stable memory which is used to store the data permanently. In PIC microcontroller
architecture, the architecture ROM stores the instructions or program, according to the program
the microcontroller acts. The ROM is also called as program memory, wherein the user will write the program
for microcontroller and saves it permanently, and finally the program is executed by the CPU.
The microcontrollers performance depends on the instruction, which is executed by the CPU.
Flash Memory
Flash memory is also programmable read only memory (PROM) in which we can read, write and erase the
program thousands of times. Generally, the PIC microcontroller uses this type of ROM.
Stack
When an interrupt occurs, first the PIC microcontroller has to execute the interrupt and the existing process
address. Then that is being executed is stored in the stack. After completing the execution of the interrupt,
the microcontroller calls the process with the help of address, which is stored in the stack and get executes the
process.
I/O Ports
The series of PIC16 consists of five ports such as Port A, Port B, Port C, Port D & Port E.
Port A is an 16-bit port that can be used as input or output port based on the status of the TRISA (Tradoc
Intelligence Support Activity) register.
Port B is an 8- bit port that can be used as both input and output port.
Port C is an 8-bit and the input of output operation is decided by the status of the TRISC register.
Port D is an 8-bit port acts as a slave port for connection to the microprocessor BUS.
Port E is a 3-bit port which serves the additional function of the control signals to the analog to digital converter.
BUS
BUS is used to transfer and receive the data from one peripheral to another. It is classified into two types such
as data bus and address.
Data Bus: It is used for only transfer or receive the data.
Address Bus: Address bus is used to transmit the memory address from the peripherals to the CPU. I/O pins
are used to interface the external peripherals; UART and USART both are serial communication protocols which
are used for interfacing serial devices like GSM, GPS, Bluetooth, IR , etc.
Timers/ Counters
PIC microcontroller has four timer/counters wherein the one 8-bit timer and the remaining timers have the
choice to select 8 or 16-bit mode. Timers are used for generating accuracy actions, for example, creating specific
time delays between two operations.
Interrupts
PIC microcontroller consists of 20 internal interrupts and three external interrupt sources which are associated
with different peripherals like ADC, USART, Timers, and so on.
Serial Communication
Serial communication is the method of transferring data one bit at a time sequentially over a communication
channel.
USART: The name USART stands for Universal synchronous and Asynchronous Receiver and
Transmitter which is a serial communication for two protocols. It is used for transmitting and receiving
the data bit by bit over a single wire with respect to clock pulses. The PIC microcontroller has two pins
TXD and RXD. These pins are used for transmitting and receiving the data serially.
SPI Protocol: The term SPI stands for Serial Peripheral Interface. This protocol is used to send data between PIC
microcontroller and other peripherals such as SD cards, sensors and shift registers. PIC microcontroller support
three wire SPI communications between two devices on a common clock source. The data rate of SPI protocol is
more than that of the USART.
I2C Protocol: The term I2C stands for Inter Integrated Circuit , and it is a serial protocol which is used to connect
low speed devices such as EEPROMS, microcontrollers, A/D converters, etc. PIC microcontroller support two
wire Interface or I2C communication between two devices which can work as both Master and Slave device.
Serial Communication
Oscillators
Oscillators are used for timing generation. Pic microcontroller consist of external oscillators like RC oscillators
or crystal oscillators. Where the crystal oscillator is connected between the two oscillator pins. The value of the
capacitor is connected to every pin that decides the mode of the operation of the oscillator. The modes are crystal
mode, high-speed mode and the low-power mode. In case of RC oscillators, the value of the resistor & capacitor
determine the clock frequency and the range of clock frequency is 30KHz to 4MHz.
CCP module: The name CCP module stands for capture/compare/PWM where it works in three modes such
as capture mode, compare mode and PWM mode.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
Capture Mode: Capture mode captures the time of arrival of a signal, or in other words, when the CCP pin goes
high, it captures the value of the Timer1.
Compare Mode: Compare mode acts as an analog comparator. When the timer1 value reaches a certain reference
value, then it generates an output.
PWM Mode: PWM mode provides pulse width modulated output with a 10-bit resolution and programmable
duty cycle.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
PIC18 MCU Detailed Architecture:
Using this detailed architecture we can explain the data moves, arithmetic and logical operations takes place
and how the timing & control signals will be generated after instruction fetch and decode. From the above
diagram, as the working register or W register is connected to ALU directly, one operand is always present in
W and the 2nd operand will come from either instruction register or from the memory. After specified operation
performed ALU will set the flags and stored the result as specified in the instruction.
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
CPU Architecture of PIC18 Microcontroller:******
Embedded Systems Chandra Sekhar G. Assist. Professor ECE Bharati Vidyapeeth’s College of Engg., New Delhi.
PIC Microcontrollers
1 : Introduction to PIC Microcontrollers
PIC Microcontrollers********
PIC stands for Peripheral Interface Controller given by Microchip Technology to identify its single-chip
microcontrollers. These devices have been very successful in 8-bit microcontrollers. The main reason is that
Microchip Technology has continuously upgraded the device architecture and added needed peripherals to the
microcontroller to suit customers' requirements. The development tools such as assembler and simulator are
freely available on the internet at [Link] .
The architectures of various PIC microcontrollers can be divided as follows.
Low - end PIC Architectures :*******
Microchip PIC microcontrollers are available in various types. When PIC microcontroller MCU was first
available from General Instruments in early 1980's, the microcontroller consisted of a simple processor
executing 12-bit wide instructions with basic I/O functions. These devices are known as low-end architectures.
They have limited program memory and are meant for applications requiring simple interface functions and
small program & data memories. Some of the low-end device numbers are
12C5XX
16C5X
16C505
Mid range PIC Architectures
Mid range PIC architectures are built by upgrading low-end architectures with more number of peripherals,
more number of registers and more data/program memory. Some of the mid-range devices are
16C6X
16C7X
16F87X
Program memory type is indicated by an alphabet.
C = EPROM
F = Flash
RC = Mask ROM
Popularity of the PIC microcontrollers is due to the following factors.
1. Speed: Harvard Architecture, RISC architecture, 1 instruction cycle = 4 clock cycles.
2. Instruction set simplicity: The instruction set consists of just 35 instructions (as opposed to 111
instructions for 8051).
3. Power-on-reset and brown-out reset. Brown-out-reset means when the power supply goes below a
specified voltage (say 4V), it causes PIC to reset; hence malfunction is avoided.
A watch dog timer (user programmable) resets the processor if the software/program ever malfunctions
and deviates from its normal operation.
4. PIC microcontroller has four optional clock sources.
o Low power crystal
o Mid range crystal
o High range crystal
o RC oscillator (low cost).
5. Programmable timers and on-chip ADC.
6. Up to 12 independent interrupt sources.
7. Powerful output pin control (25 mA (max.) current sourcing capability per pin.)
8. EPROM/OTP/ROM/Flash memory option.
9. I/O port expansion capability.
10. Free assembler and simulator support from Microchip at [Link]
CPU Architecture: *******
The CPU uses Harvard architecture with separate Program and Variable (data) memory interface. This
facilitates instruction fetch and the operation on data/accessing of variables simultaneously.
When a peripheral interrupt, that is enabled, is received, the processor goes to 004H. A suitable branching to
the interrupt service routine (ISR) is written at 004H.
Data memory (Register Files):
Data Memory is also known as Register File. Register File consists of two components.
1. General purpose register file (same as RAM).
2. Special purpose register file (similar to SFR in 8051).
Fig 16.3 Data Memory map
The special purpose register file consists of input/output ports and control registers. Addressing from 00H to
FFH requires 8 bits of address. However, the instructions that use direct addressing modes in PIC to address
these register files use 7 bits of instruction only. Therefore the register bank select (RP0) bit in the STATUS
register is used to select one of the register banks.
In indirect addressing FSR register is used as a pointer to anywhere from 00H to FFH in the data memory.
In addition to I/O pins, there is a Master clear pin (MCLR) which is equivalent to reset in 8051. However,
unlike 8051, MCLR should be pulled low to reset the micro controller. Since PIC16C74Ahas inherent power-
on reset, no special connection is required with MCLR pin to reset the micro controller on power-on.
There are two VDD pins and two VSS pins. There are two pins (OSC1 and OSC2) for connecting the crystal
oscillator/ RC oscillator. Hence the total number of pins with a 16C74A is 33+7=40. This IC is commonly
available in a dual-in-pin (DIP) package.
ADDRESSING MODES:*****************
To know the working principal and data handling we need to have clear knowledge on addressing modes of pic
microcontroller. The PIC microcontrollers support three addressing modes .They are
(i) Immediate or Literal Addressing Mode
(ii) Register Direct or Memory Direct Addressing Mode
(iii) Indirect Addressing Mode
Immediate addressing mode:
In this addressing mode, the operand is a number or constant not an address as MOVLW 43h, the operand here is
data not address. So in this addressing mode of pic microcontroller data is direct transferred and data is immediate
after opcode that is why this type of addressing is called immediate addressing. This way is fast in execution.
Direct addressing:
Direct Addressing is done through a 9-bit address. In direct addressing mode, 7 bits (0-6) of the instruction
identify the register file address and two bits (RP1, RP0) from STATUS register as is shown in bellow Figure.
Any access to SFR(Special Function Registers) registers can be an example of direct addressing.
Register operand addressing mode: it also same as the Direct addressing mode as the register are memory
locations in the Data memory or RAM. In this addressing mode, the operand is a Register which holds the data to
be execute. Register operand addressing mode deals with the registers like: CLR W
The below diagram explains the method of accessing register file address 13H by direct addressing method
Indirect addressing:
It does not take an address from an instruction, but it derives it from IRP bit of STATUS and FSR(File Selection
Register) registers. Addressed location is accessed through INDF register which in fact holds the address indicated
by the FSR. Indirect addressing is very convenient for manipulating data arrays located in GPR registers. In this
case, it is necessary to initialize FSR register with a starting address of the array, and the rest of the data can be
accessed by incrementing the FSR register. Above Figure shows the indirect addressing concept.
Instruction Set:
The instruction set for PIC16C74A consists of only 35 instructions. Some of these instructions are byte oriented
instructions and some are bit oriented instructions.
The byte oriented instructions that require two parameters (For example, movf f, F(W)) expect the f to be
replaced by the name of a special purpose register (e.g., PORTA) or the name of a RAM variable (e.g., NUM1),
which serves as the source of the operand. 'f' stands for file register. The F(W) parameter is the destination of
the result of the operation. It should be replaced by:
F, if the destination is to be the source register.
W, if the destination is to be the working register (i.e., Accumulator or W register).
The bit oriented instructions also expect parameters (e.g., btfsc f, b). Here 'f' is to be replaced by the name of
a special purpose register or the name of a RAM variable. The 'b' parameter is to be replaced by a bit number
ranging from 0 to 7.
For Example:
Z equ 2
Z has been equated to 2. Here, the instruction will test the Z bit of the STATUS register and will skip the next
instruction if Z bit is clear.
The literal instructions require an operand having a known value (e.g., 0AH) or a label that represents a
known value.
For example:
NUM equ 0AH ; Assigns 0AH to the label NUM ( a constant )
movlw NUM ; will move 0AH to the W register.
Every instruction fits in a single 14-bit word. In addition, every instruction also executes in a single cycle,
unless it changes the content of the Program Counter. These features are due to the fact that PIC micro
controller has been designed on the principles of RISC (Reduced Instruction Set Computer) architecture.
Instruction set:********************
Instruction
Mnemonics Description
Cycles
bcf f, b Clear bit b of register f 1
bsf f, b Set bit b of register f 1
clrw Clear working register W 1
clrf f Clear f 1
movlw k Move literal 'k' to W 1
movwf f Move W to f 1
movf f, F(W) Move f to F or W 1
swapf f, F(W) Swap nibbles of f, putting result in F or W 1
andlw k And literal value into W 1
andwf f, F(W) And W with F and put the result in W or F 1
andwf f, F(W) And W with F and put the result in W or F 1
iorlw k inclusive-OR literal value into W 1
iorwf f, F(W) inclusive-OR W with f and put the result in F or W 1
xorlw k Exclusive-OR literal value into W 1
xorwf f, F(W) Exclusive-OR W with f and put the result in F or W 1
addlw k Add the literal value to W and store the result in W 1
addwf f, F(W) Add W to f and store the result in F or W 1
Subtract the literal value from W and store the result in
sublw k 1
W
subwf f, F(W) Subtract f from W and store the result in F or W 1
Copy f into F or W; rotate F or W left through the carry
rlf f, F(W) 1
bit
Copy f into F or W; rotate F or W right through the carry
rrf f, F(W) 1
bit
Test 'b' bit of the register f and skip the next instruction if
btfsc f, b 1/2
bit is clear
Test 'b' bit of the register f and skip the next instruction if
btfss f, b 1/2
bit is set
Decrement f and copy the result to F or W; skip the next
decfsz f, F(W) 1/2
instruction if the result is zero
Increment f and copy the result to F or W; skip the next
incfcz f, F(W) 1/2
instruction if the result is zero
goto label Go to the instruction with the label "label" 2
Go to the subroutine "label", push the Program Counter
call label 2
in the stack
Return from the subroutine, POP the Program Counter
retrun 2
from the stack
Retrun from the subroutine, POP the Program Counter
retlw k 2
from the stack; put k in W
Return from Interrupt Service Routine and re-enable
retie 2
interrupt
clrwdt Clear Watch Dog Timer 1
sleep Go into sleep/ stand by mode 1
nop No operation 1
Encoding of instruction:
As has been discussed, each instruction is of 14-bit long. These 14-bits contain both op-code and the operand.
Some examples of instruction encoding are shown here.
Example-1:
bcf f, b Clear 'b' bit of register 'f'
Operands: 0 ≤ f ≤ 127
0≤b≤7
Encoding:
The instruction is executed in one instruction cycle, i.e., 4 clock cycles. The activities in various clock cycles
are as follows.
Example-2:
goto K Go to label 'k' instruction
Operand: 0 ≤ K ≤ 2047 (11-bit address is specified)
Operation: K PC <10:0>
PCLATH <4:3> PC <12:11>
Encoding:
Since this instruction requires modification of program Counter, it takes two instruction cycles for execution.
Q-Cycle activities are shown as follows.
4 : I/O Port Configuration
Discussion on I/O ports of PIC16C74A:******
PIC16C74A has five I/O ports. Port-B, Port-C and Port-D have 8 pins each. Port-A and Port-E have 6 and 3
pins respectively. Each port has bidirectional digital I/O capability. In addition, these I/O ports are multiplexed
with alternate functions for the peripheral devices on the microcontroller. In general, when a peripheral is
enabled, that pin may not be used as a general purpose I/O pin. Each port latch has a corresponding TRIS (Tri-
state Enable) register for configuring the port either as an input or as an output. The port pins are designated
by the alphabet R, followed by the respective port (viz. A, B, C, D or E) and the pin number. For example,
Port-A pins are named as RA0, RA1, etc.
Port-A: Port-A pins RA0-RA3 and RA5 are similar. These pins function (alternate function) as analog inputs
to the analog-to-digital converter.
The alternate function of RA4 pin is Timer-0 clock input (T0CKI). RA4 pin is an open drain pin and hence
requires external pull-up when configured as output pin. It is shown in the following figure.
Fig 19.2 RA4 pin Configuration
Configuration of Port-A pins
Example : Set RA0-RA3 as outputs and RA4 - RA5 as inputs.
bcf STATUS, RP0 ; Select Bank-0
clrf PORTA ; Clears the data latch
bsf STATUS, RP0 ; Select Bank-1
movlw 30H ; W 03H ( data direction )
movwf TRISA ; Set RA0-RA3 as outputs, RA4-RA5 as inputs
Port-B
Port-B is an 8-bit bidirectional I/O port. The data direction in Port-B is controlled by TRISB register. Setting
a bit in TRISB register puts the corresponding output in high impedance input mode. When a bit in TRISB is
made zero, the corresponding pin in Port-B outputs the content of the latch (output mode).
Each port pin has a weak internal pull-up that can be enabled by clearing bit of OPTION register (bit-
7). When a pin is configured in the output mode, the weak pull-up is automatically turned off. Internal pull-up
is used so that we can directly drive a device from the pins.
Fig 19.3 Pins RB0-RB3 of Port-B
Configuration of Port-B pins
Example : Set RB0-RB3 as outputs, RB4-RB5 as inputs, RB7 as output.
bcf STATUS, RP0
clrf PORTB
bsf STATUS, RP0
movlw 70H
movwf TRISB
5:Timer modules in PIC Microcontroller
Overview of Timer Modules :************
PIC 16C74A has three modules, viz., Timer-0, Timer-1 and Timer-2. Timer-0 and Timer-2 are 8-bit timers.
Timer-1 is a 16-bit timer. Each timer module can generate an interrupt on timer overflow.
Timer-0 Overview:
The timer-0 module is a simple 8-bit UP counter. The clock source can be either the internal clock (fosc /4) or
an external clock. When the clock source is external, the Timer-0 module can be programmed to increment on
either the rising or falling clock edge. Timer-0 module has a programmable pre-scaler option. This pre-scaler
can be assigned either to Timer-0 or the Watch dog timer, but not to both.
The Timer-0 Counter sets a flag T0IF (Timer-0 Interrupt Flag) when it overflows and can cause an interrupt at
that time if that interrupt source has been enabled, (T0IE = 1), i.e., timer-0 interrupt enable bit = 1.
OPTION Register Configuration :
Option Register (Addr: 81H) Controls the prescaler and Timer -0 clock source. The following OPTION register
configuration is for clock source = fosc /4 and no Watchdog timer.
The operating and control modes of Timer1 are determined by the special purpose register T1CON.
1 clock source is . Since the internal clock is selected, the timer is always synchronized and there
is no further need of synchronization.
As a counter (TMR1CS = 1). In the counter mode, external clock input from the pin RCO/T1CKI is
selected.
The input clock ( ) has a pre-scaler option of 1:1, 1:4 or 1:16 which is selected by bit 0 and bit 1 of
T2CON register respectively.
The Timer 2 module has an 8bit period register (PR2). Timer-2 increments from 00H until it is equal to PR2
and then resets to 00H on the next clock cycle. PR2 is a readable and writable register. PR2 is initailised to
FFH on reset.
The output of TMR2 goes through a 4bit post-scaler (1:1, 1:2, to 1:16) to generate a TMR2 interrupt by setting
TMR2IF.
Fig 21.5 Schematic diagram showing the interrupt logic for PIC
7 : CCP Modules
Capture / Compare /PWM (CCP) Modules:**************
PIC16C74A has two CCP Modules. Each CCP module contains a 16 bit register (two 8-bit registers) and can
operate in one of the three modes, viz., 16-bit capture, 16-bit compare, or up to 10-bit Pulse Width Modulation
(PWM). The details of the two modules (CCP1 and CCp2) are given as follows.
CCP1 Module:
CCP1 Module consists of two 8-bit registers, viz., CCPR1L (low byte) and CCPR1H (high byte). The
CCP1CON register controls the operation of CCP1 Module.
CCP2 Module:
CCP2 Module consists of two 8 bit registers, viz., CCPR2L (Low byte) and CCPR2H (high byte). The
CCP1CON register controls the operation of CCP2 Module.
Both CCP1 and CCP2 modules are identical in operation with the exception of the operation of special event
trigger.
The following table shows the timer resources for the CCP Mode.
CCP Mode Timer Used
Capture Timer 1
Compare Timer 1
PWM Timer 2
CCP1CON Register (Address 17H )
CCP2CON Register is exactly similar to CCP1CON register. CCP2CON Register address is 1DH. CCP1CON
controls CCP module1 where as CCP2CON controls CCP Module2.
Bit 5-4:
CCP1X CCP1Y: PWM least significant bits. These bits are of no use in Capture mode. In PWM Mode, these
bits are the two Lsbs of the PWM duty cycle. The eight Msbs are found in CCPR1L. Thus the PWM mode
operates in 10-bit mode.
Bit 3-0:
CCP1M3:CCP1MO (CCP1 Mode select bits)
0000=Capture/Compare/PWM Mode off
0100=Capture mode, every falling edge
0101=Capture mode, every rising edge
0110=Capture mode, every 4 th rising edge
0111=Capture mode, every 16 th rising edge
1000=Compare mode, set output on match (CCP1IF bit is set)
1001=Compare mode, clear output on match (CCP1IF bit is set)
1010=Compare mode, generate software interrupt on match (CCP1IF bit is set, CCP1 pin unaffected)
1011=Compare mode, trigger special event (CCP1IF bit is set;CCP1 resets Tmr1; CCP2 resets TMR1 and
starts A/D conversion if A/D module is Enabled)
11XX=PWM mode.
Capture Mode (CCP1):
Capture Mode captures the 16-bit value of TMR1 into CCPR1H:CCPR1L register pair in response to an event
occurring on RC2/CCP1 pin. Capture Mode for CCP2 is exactly similar to that of CCP1.
An event on RC2/CCP1 pin is defined as follows:
Every falling edge
Every rising edge.
Every 4 th rising edge.
Every 16 th rising edge.
In compare mode, the 16-bit CCPR1 register value is compared against TMR1 register pair (TMR1H and
TMR1L) value. When a match occurs, the RC2/CCP1 pin is driven high or driven low or remains unchanged
as decided by CCP1CON<3:0> bits.
In software interrupt mode, CCP1IF bit is set but CCP1 pin in unaffected.
As shown in the figure, in special event trigger mode, both CCP1 and CCP2 intiates an A/D conversion.
PWM mode (CCP1)************
Both CCP1 and CCP2 have similar operation in PWM mode. Here we will discuss PWM with respect to CCP1.
In PWM mode, the CCP1 pin produces upto a 10-bit resolution Pulse Width Modulation (PWM) output.
RC2/CCP1 pin should be configured in the uotput mode by clearing TRISC<2> bit.
The schematic block diagram of CCP1 module in PWM mode is shown in the figure.
A PWM output as shown has a time period. The time for which the output stays high is called duty cycle.
PWM Period
The PWM period is specified by writing to PR2 register. The PWM period can be calculated using the
following formula:
PWM period = [( PR 2) + 1] × 4 × T osc × (TMR2 prescale value)
PWM frequency = 1/ PWM period
When TMR2 is equal to PR2, the following events occur on the next increment cycle.
TMR2 is cleared
the CCP1 pin is set (if PWM duty cycle is 0
The PWM duty cycle is latched from CCPR1L into CCPR1H
bits. Up to 10-bit resolution is available where CCPR1L contains the eight MSBs and CCP1CON < 5 : 4
> contains the two LSB's. The 10-bit value is represented by CCPR1L : CCP1CON < 5 : 4 >.
The PWM duty cycle is given by
PWM duty cycle = (CCPR1L : CCP1CON < 5 : 4 > ). T osc . (TMR2 prescale value)
To understand the 10-bit counter configuration from Timer-2, let us first see the counting mechanism of
Timer-2, as shown in Fig 22.4.
The CCPR1H register and a 2-bit internal latch are used to double buffer the PWM duty cycle. This double
buffering is essential for glitchless PWM operation. When the CCPR1H and 2-bit latch match TMR2
concatenated with an internal 2-bit Q clock or 2-bits of prescaler, the CCP1 pin is cleared. Maximum PWM
resolution (bits) for a given PWM frequency can be calculated as
If the PWM duty cycle is longer than the PWM period, then the CCP1 pin will not be cleared.
PWM Period and duty cycle calculation
Example:
Find the maximum resolution of duty cycle that can be used with a 78.124 kHz frequency and 20 MHz
oscillator.
Any value greater than 255 will result in a 100 % duty cycle. The following table gives the PWM frequency
fPWM if fosc = 20MHz
Duty cycle resolution 10-Bit counter scale PR2 value Prescaler 1 Prescaler 4 Prescaler 16
10 bit 1024 255 19.53 KHz 4.88 kHz 1.22 kHz
≈ 10 bit 1000 249 20kHz 5kHz 1.25kHz
8 bit 256 63 78.125kHz 19.53kHz 4.88kHz
6 bit 64 15 312.5kHz 78.125kHz 19.53kHz
8 : Analog to Digital Convertor Module
ADC Module****************
An analog-to-digital converter (ADC) converts an analog signal into an equivalent digital number. PIC
16C74A has an inbuilt ADC with the following features -
8-bit conversion
8 analog input channels
An analog multiplexer
A sample and hold circuit for signal on the selected input channel
Alternative clock sources for carrying out conversion
Adjustable sampling rate
Choice of an internal or external reference voltage
Interrupt to microcontroller on end of conversion
Port A and Port E pins are used for analog inputs/reference voltage for ADC. In A/D conversion, the input
analog voltage is digitized and an equivalent digital output is generated as shown in the figure.
The ADCON0 register, which is shown below, controls the operation of A/D module.
ADCON1 Register
This register specifies the analog inputs
Fig 23.6 Schematic diagram of A/D convertor analog inputs and reference voltage
Steps for A/D conversion
1. Configure A/D module
Configure analog inputs/voltage reference and digital I/O (ADCON1)
Select A/D Channel (ADCON0)
Select A/D Conversion Clock (ADCON0)
Turn on A/D Module (ADCON0)
2. Configure A/D Interrupt (Optional)
Clear ADIF bit in PIR1 register
Set ADIE bit in PIE1 register
Set GIE bit
3. Wait for required acquisition time
4. Start Conversion - set GO/ bit (ADCON0)
5. Wait for A/D conversion to complete, by either polling GO/ bit or by waiting for the A/D
interrupt
6. Read A/D result registers (ADRES). Clear ADIF if required.
Example Program
A/D conversion with interrupt
org 000H
goto Mainline
org 020H
bsf STATUS, RP0 ; Select Bank 1
clrf ADCON 1 ; Configure A/D inputs
bsf PIE1, ADIE ; Enable A/D interrupt
bcf STATUS, RP0 ; Select Bank 0
movlw 081H ; Select fosc/32, channel 0, A/D on
movwf ADCON0
bcf PIR1, ADIF
bsf INTCON, PEIE ; Enable peripheral and global interrupt bits
bsf INTCON, GIE ; interrupt bits
; Ensure that the required sampling time of the selected input channel has been elapsed.
; Then conversion may be started.
; bsf ADCON0, GO ; Start A/D conversion.
; ADIF bit will be set and GO/
; bit is cleared upon completion of A/D conversion.
Interrupt Service Routine
Org 004H
Movf ADRES, W ; Result of A/D conversion in W
Consideration of Sampling Time
When a channel is selected (writing to ADCON0), the switch 'SW' in Fig 23.8 is closed, changing CHOLD to
VSource . When A/D conversion is started (setting Go bit in ADCON0), SW is opened. The time from the
closure of 'SW' till the voltage across CHOLD (Vo) reaches VSource is the minimum sampling time Ts .
The actual sampling time can be higher than Ts .
The graph between Ts and source resistance RSource is shown in Fig 23.7.+
Fig 23.7 Relation between sampling time and source resistance
Fig 23.9
From Fig 23.9,
Either of these modes can be used to interconnect two or more PIC chips to each other using a minimal number
of wires for communication. Alternatively, either can be used to connect a PIC microcontroller to a peripheral
chip. When I 2C mode is selected, the peripheral chip must also have an I 2C interface. On the other hand, the
SPI mode provides the clock and serial data lines for direct connection to shift registers. This leads to increased
I/O interface capability and an arbitrary number of I/O devices can be connected to a PIC microcontroller. SPI
can also achieve data rate significantly higher than I2C. Both the communication methods are synchronous,
i.e., the data transfer is synchronized with an explicit clock signal.
Two special purpose registers control the synchronous serial port (SSP) operations. These registers are:
SSPCON (Synchronous Serial Port Control Register), Address: 14H
SSPSTAT(Synchronous Serial Port status Register), Address: 94H
Fig 25.1 PIC connection (in SPI mode) with a shift register
When an 8-bit data is written to SSPBUF, the data is shifted out of RC5/SD0 pin. With CKP = 1, the data is stable
at the positive transition but changes at the negative transition. The shift shifts the data at the positive clock
transition. After 8 clock pulses, all 8-bits are shifted in the shift register. The completion of data transfer is
indicated by SSPIF interrupt flag becoming ' 1' . The interrupt service routine make RC4 ' 1' , thus latching the 8-
bit data to the output of the shift register. The configuration of various registers are shown in Fig 25.2
Port configurations
Fig 25.2 Various Register Configurations
Parallel Input Port Realization
A shift register (74HC165) is connected to the PIC microcontroller as shown in Fig 25.3. Pin RD7 is configured
as an output and is used to load 8-bit data to the shift register. A dummy write to SSPBUF initiates data transfer.
Data bit is read into RC4/SDI at the negative clock transition (CKP = 0) where the data bit is stable. Data is
shifted in the shift register at the position clock transition as shown in the timing diagram. After the completion
of data transfer, SSPIF interrupt flag goes high. Therafter the 8-bit data can be read by reading SSPBUF.
Fig 25.3 Realization of an 8-bit parallel input port with PIC in SPI mode.
Port configurations
Fig 25.4 gives the configurations various registers for inputs parallel port realization.
I2C bus transfer consists of a number of byte transfers within a START condition and either another START
condition or a STOP condition. During the idle state when no data transfer is taking place, both SDA and SCL
lines are released by all the devices and remains high. When a master wants to initiate a data transfer, it pulls
SDA low followed by SCL being pulled low. This is called START condition. Similarly, when the processor
wants to terminate the data transfer it first releases SCL (SCL becomes high) and then SDA. This is called a
STOP condition. START and STOP conditions are shown in the diagram as follows.
Fig 26.3 Timing diagram for START and STOP Conditions
START and STOP conditions are unique and they never happen within a data transfer.
Data Communication Protocol:
In I2C communication both 7-bit and 10-bit slave addressing are possible. In 7-bit addressing mode 128 slaves
can be interfaced with a single master. Similarly, in 10-bit addressing mode, 1024 slaves can be interfaced with
the master. We will discuss here 7-bit addressing mode only. 10-bit addressing mode is similar to 7-bit
addressing except from the fact that the number of address bits is more.
Following a 'start' condition, the master sends a 7-bit address of the slave on SDA line. The MSB is sent first.
After sending 7-bit address of the slave peripheral, a R/ (8th bit) bit is sent by the master. If R/ bit is '0',
the following byte (after the acknowledgement bit) is written by the master to the addressed slave peripheral.
If R/ =1, the following byte (after the acknowledgement bit) has to be read from the slave by the master.
After sending the 7-bit address of the slave, the master sends the address (usually 8 bit) of the internal register
of the slave wherefrom the data has to be read or written to. The subsequent access is automatically directed
to the next address of the internal register.
The following diagrams give the general format to write and read from several peripheral internal registers.
rlf TRBUF, F
movf RBUF,F
btfss STATUS, Z
call out_bit ; Send a bit available in C
btfss STATUS, Z
goto TR_1
call in_bit ; Get the ACK bit in RCBUF<0>
movlw 01H ;
andwf RCBUF, W ; Store the complement of ACK bit in Z flag
return
The RCVBYTE subroutine receives a byte from I2 C into W using a RAM variable RCBUF buffer.
Call RCVBYTE with bit 7 of TRBUF clear for ACK
Call RCVBYTE with bit 7 of TRBUF set for NOACK
RCBUF is an 8-bit RAM variable used for recieving the data. the bit is recieved in the RCBUF<0> and is
rotated successively through RCBUF as shown. The reception ends when all 8-bits are recieved.
RCVBYTE:
movlw 01H
movwf RCBUF ; Keep an index for 8-bits to be recieved.
RCV_1:
rlf RCBUF, F
call In_bit
btfss STATUS, C
goto RCV_1
rlf TRBUF, F
call Out_bit
movf RCBUF,w
return
The out_bit subroutine transmits carry bit, then clears the carry bit.
Out_bit:
bcf INDF, SDA
btfsc STATUS, C
bsf INDF, SDA ; Send carry bit
bsf INDF, SCL
call DELAY
bcf INDF, SCL
bcf STATUS,C ; Clear carry bit
return
The in_bit subroutine receives one bit into bit-0 of RCBUF.
In_bit:
bsf INDF,SDA
bsf INDF, SCL
bcf RCBUF, 0
btfsc PORTC, SDA ; Check SDA line for data bit
bsf RCBUF, 0
bcf INDF, SCL
return
Example of I 2 C interfacing
DAC interfacing on I 2 C bus:
MAX518 is a dual 8-bit Digital to Analog Converter (DAC) with I2C interface. The address of the device is
selectable through two pins AD1 and AD0 . This device works in I2C slave mode. The connection diagram is
shown as follows.
TRISE:
This register plays a crucial role in PSP configuration and control. The lower three bits control the data
direction of PortE. the upper four bits are used in conjunction with parallel slave port as shown here.
TRISE, ADD: 89 H
As explained, PSP Mode facilitates bidirectional 8-bit parallel data transfer. After ADCON1<b2-b0> and
TRISE<b4, b2-b0> bits are set by the user program, PORTD and PORTE are configured for PSP. When PC
wants to write an 8-bit data to PIC, it addresses the PIC microcontroller and the I/O address decoding circuit
makes go low selecting the PIC chip. PC also makes (I/O write) pin low and floats the data through
its data bus (b7-b0). The data is written to PORTD and IBF flag in TRISE Register is set indicating that a byte
is waiting at PORTD input buffer to be read by the PIC. Simultaneously PSPIF flag bit of PIR1 register is set
and an interrupt is generated if PSPIE, PEIE and GIE bits have been set (i.e., the peripheral PSP interrupt is
enabled.). After the data is read from PORTD, IBF bit automatically becomes zero; however PSPIF bit has to
be cleared by software. If a second byte is written by the PC before the first byte is read, the second byte is lost
and the IBOV flag in TRISE register is set indicating this loss.
Similarly a byte can also be read by the PC from the PIC microcontroller. When PIC writes a byte to PORTD,
OBF flag is set indicating that the byte is waiting to be read by the PC. When the PC reads this bytes, OBF
flag in TRISE Register is automatically cleared and the interrupt flag bit PSPIF is set indicating that the byte
has been read by the PC from PIC microcontroller.